SLOPSHOPPER

delegation

Everything for delegating coding work: Codex, agy and Claude worker skills; /delegate, /explore, /delegate-setup, /delegate-confirm and /delegations; the…

panebandguardcommandtoastprompt
v0.9.0MITupdated 2026-10-17MohamedHamed001/claude-delegation
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · delegation
│ ┃ Delegations ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ ╭────────────────────────────────────────╮ ⏺ Read(src/auth.ts) │ ┃ │ Running now (0) │ ⎿ Read 6 lines │ ┃ │ │ ⏺ Update(src/auth.ts) │ ┃ │ Nothing delegated right now │ ⎿ Added 2 lines, removed 1 line │ ┃ ╰────────────────────────────────────────╯ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ ╭────────────────────────────────────────╮ │ ┃ │ This session (0) │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ │ │ ┃ │ No delegations yet in this session │ ✻ Worked for 42s · done 4:20 PM │ ┃ ╰────────────────────────────────────────╯ │ ┃ › /delegations │ ┃ ╭────────────────────────────────────────╮ ⎿ delegation: Delegations pane opened. │ ┃ │ Today, all sessions │ │ ┃ │ │ │ ┃ │ Delegations 0 │ │ ┃ │ Opus requests while delegating 0 │ │ ┃ │ Opus units while delegating 0 │ │ ┃ │ Claude worker units 0 │ │ ┃ │ Relay calls (Codex and others) 0 │ │ ┃ ╰────────────────────────────────────────╯ │ ┃ │ ┃ ╭────────────────────────────────────────╮ │ ┃ │ From your cost test (6 Oct) │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Delegations
╭────────────────────────────────────────────────────────╮ │ Running now (0) │ │ │ │ Nothing delegated right now │ ╰────────────────────────────────────────────────────────╯ ╭────────────────────────────────────────────────────────╮ │ This session (0) │ │ │ │ No delegations yet in this session │ ╰────────────────────────────────────────────────────────╯ ╭────────────────────────────────────────────────────────╮ │ Today, all sessions │ │ │ │ Delegations 0 │ │ Opus requests while delegating 0 │ │ Opus units while delegating 0 │ │ Claude worker units 0 │ │ Relay calls (Codex and others) 0 │ ╰────────────────────────────────────────────────────────╯ ╭────────────────────────────────────────────────────────╮ │ From your cost test (6 Oct) │ │ │ │ Opus solo: passed 3 of 3, fastest │ │ Codex: about 10% cheaper on Claude, 2 to 3 times │ │ slower │ │ Sonnet: most expensive every time │ ╰────────────────────────────────────────────────────────╯
README

claude-delegation

A plugin for Claude Code: delegation.

Everything for delegating coding work: Codex, agy and Claude worker skills; /delegate, /explore, /delegate-setup, /delegate-confirm and /delegations; the official Codex plugin's commands bundled as /codex-* with matching /agy-* commands (rescue, review, adversarial-review, status, result, cancel, setup); a measured delegation policy that refuses tasks too small to be worth it; and a live view of running jobs and what they cost.

Part of claude-mods, which lists this plugin and its siblings.

Install

/plugin marketplace add MohamedHamed001/claude-delegation
/plugin install delegation@claude-delegation

Then start a new session: a session reads its plugins once, when it starts. Update later with /plugin marketplace update claude-delegation.

Requirements

  • Claude Code 2.1.28x or newer. The plugins use function hooks (TypeScript modules the app loads), which older versions do not run.
  • Windows, macOS or Linux. Process handling is detected per session: PowerShell on Windows, ps and pkill elsewhere. Developed on Windows; macOS has not been tested yet.
  • For delegation only, the workers you want to use:
  • Node.js 18 or newer (the relay and Codex scripts are Node scripts).
  • Codex: npm install -g @openai/codex, then codex login.
  • agy: the Google Antigravity CLI, signed in by running agy once.
  • Claude subagents need nothing extra.

What it does

Everything for delegating coding work, in one plugin: worker skills, slash commands, a delegation policy that is enforced, and a live view of running jobs and what they cost.

Why it exists

Delegating feels cheaper than it is. A session carries a large context before any work, and every main-model request re-reads it; briefing a worker, waiting for it and reviewing its work add about as many requests as the delegation removes. A controlled test on real tasks of 1 to 6 files, each done three ways, found:

SetupPassedClaude-side costTime
Opus alone3 of 3baselinefastest
Opus + Sonnet subagent2 of 3about a third moreslower
Opus + Codex2 of 3about a tenth less2 to 3 times slower

So the plugin's default is: do the work yourself, and delegate only when it pays.

What you get

PartWhat it does
PolicyAdded to every session's system prompt, so nobody has to copy rules into CLAUDE.md. Delegate only: large separable work with a check the worker can run; work that should move off the Claude limit (Codex); when you ask; read-only review; fast read-only exploration (agy).
EnforcementA delegation whose brief names only one or two files is refused, and Claude is told to do it directly. Allowed anyway when you asked for delegation, or when it is read-only.
Plain wordsSaying "delegate this", "hand this over" or naming a worker (Codex, agy, Sonnet) counts as asking, no slash command needed.
BandAbove the prompt: a little Clawd for each delegated job, captioned codex:implement or Explore/haiku. While the job runs it walks back and forth and stops at each end to act out its job (Sonnet swings its hammer, Codex types, Opus's monocle glints, agy's rainbow slides, Haiku waves, Claude looks around). Each model has its own: Opus wears a gold monocle, Sonnet holds a hammer, Haiku is small and pink, Codex is purple and winks, agy is a rainbow, anything else is plain Claude orange. Dimmed when done, red when it failed. Under the pets, one line on the newest job (or a warning when one has run for 15+ minutes), with Stop, Delegations and Hide buttons. A new prompt clears finished pets; Hide hides the band until then.
PaneDelegations button or /delegations: jobs running now, every job this session with what it cost, today's totals across sessions, and the cost test's findings.
Skillscodex-delegate, agy-delegate, claude-delegate, delegate-setup, gpt-5-4-prompting, codex-result-handling.

Commands

CommandWhat it does
/delegate <task>Delegates the task if it is worth it under the policy; otherwise says why and does it directly
/explore <question>Asks agy a fast, read-only question about the codebase; Claude spot-checks its file and line claims
/delegate-setupChooses which worker and model handles which kind of work (writes the lane map)
`/delegate-confirm on\off`Asks before every delegation starts (off by default; no argument shows the setting)
/delegationsOpens the pane

And the same seven commands for each worker:

Action/codex-…/agy-…
rescue <task>Hands a task to Codex (may edit the workspace)Hands a task to agy (runs with permissions skipped, see below)
reviewRead-only review of your local changesRead-only review of your local changes
adversarial-review [focus]Review that challenges the design and its assumptionsSame, on agy's stronger model
statusRunning and recent jobsRunning and recent jobs
result [job-id]A finished job's full reportA finished job's report
cancel [job-id]Stops a running jobStops a running job
setupChecks Node, Codex and its sign-inChecks agy and its sign-in, lists default models

Flags on rescue and the reviews: --background (run detached; check with status), --model <name>, and for reviews --base <ref> (review a branch against a base instead of the working tree). /codex-setup --enable-review-gate turns on Codex's optional stop-time review gate (off by default).

status, result, cancel and setup answer at once without a Claude turn. Rescue and the reviews hand Claude a prompt: it writes the brief, runs the worker, then reviews the result itself.

Which model a command uses

--model on the command wins; otherwise the command's lane in your lane map; otherwise:

CommandLaneDefault model
/codex-rescueimplementgpt-6-luna
/codex-reviewreviewgpt-6-luna
/codex-adversarial-reviewdeep-reviewgpt-6.1-sol
/agy-rescueagy-implementgemini-3.8-flash-high
/agy-reviewagy-reviewgemini-3.8-flash-high
/agy-adversarial-reviewthird-opiniongemini-3.1-pro-high
/exploreresearchgemini-3.8-flash-medium

Rule of thumb: the cheapest model that can do the job. Fast models for lookups, a mid model for edits and reviews, the strongest only for design challenges.

First run

  1. Install the workers you want (see Requirements).
  2. Run /codex-setup and /agy-setup to check them.
  3. Run /delegate-setup once to pick your lanes. The lane map is stored in ~/.config/delegate-skills/config.json (or $XDG_CONFIG_HOME/delegate-skills/).

Without a lane map the commands use the defaults above.

Things to know

  • agy and permissions. agy runs headless and cannot ask for permission, so any action that needs approval is refused and the run fails. /agy-rescue therefore passes --dangerously-skip-permissions: agy can then do anything on your machine, not only in the repository. Running /agy-rescue is that approval. Reviews and /explore run in agy's read-only plan mode and are told not to run shell commands at all.
  • agy job files. Each agy job keeps its files in ~/.claude/delegation/agy-jobs/<id>/: job.json, brief.md, diff.patch (reviews), result.json and agy's logs.
  • Keep reviews small. A fast model asked to review a large diff can explore the repository for a long time. Review a few files at a time; the relay stops a run at its timeout.
  • The official Codex plugin. This plugin bundles it (see Credits). If codex@openai-codex is installed as well, the bundled /codex-* commands step aside and point to its /codex:* ones; the policy and job tracking still apply to them.
  • Confirm before delegating. Some models have a small allowance (Sol, gpt-6.1-sol), and others may cost more. /delegate-confirm on makes every delegation (a Codex run, an agy or other relay, a Claude subagent) first show the worker, the model, the lane, and the brief's size and file count, with Run it and Cancel; closing the dialog counts as Cancel. It is off by default, is kept across sessions, and /delegate-confirm off turns it off again.
  • Cost figures. Claude subagents report tokens, so their cost is shown. Codex and agy report nothing to Claude, so they show as calls and time, with the Opus requests made while they ran.

How it knows what is running

SourceWhat it tells the plugin
The Agent tool call and agent.spawnA Claude subagent started, its id and its real model
The subagent's own requests and turn.completeWhat it cost and when it finished
A shell command running <name>-delegate/scripts/relay.mjs --brief <file>A relay job (Codex, agy, Claude CLI); a background one counts as finished when its process is gone
A shell command running `codex-companion.mjs task\review\adversarial-review`A Codex plugin job; a background one is followed through the job id it prints
Main-conversation requests while a job is openWhat delegating cost on the Opus side

Developing

claude plugin validate .
claude plugin test .

To run your working copy instead of the installed version, add this folder to CLAUDE_CODE_PLUGIN_DIRS (separated by ; on Windows, : elsewhere), for example in the env block of ~/.claude/settings.json, then start a new session.

Licence

This repository is under the MIT licence.

It includes third-party code, each under its own licence, listed with every change in skills/NOTICE.md:

  • The skills codex-delegate, agy-delegate, claude-delegate and delegate-setup from amElnagdy/delegate-skills (MIT).
  • The Codex companion, its command texts and the skills gpt-5-4-prompting and codex-result-handling from OpenAI's Codex plugin for Claude Code (codex@openai-codex 1.0.6), under the Apache License 2.0 with its NOTICE.

Not affiliated with Anthropic, OpenAI or Google.

Source 3 files
hooks/register.tsx 1173 lines
1// Delegation: shows work handed to Claude subagents, Codex, agy and other relays.
2//
3// It also carries the delegation policy: the rule goes into every session's instructions,
4// and a delegation of a one- or two-file task is refused unless the user asked for it.
5//
6// What you see:
7//   - A one-line band while a job runs (or just finished, ran too long, or vanished).
8//   - A pane (Delegations button or /delegations): what is running, with a Stop button
9//     for relay jobs; every job of this session with what it cost; today's totals; and
10//     the findings of the 6 Oct cost test.
11//
12// Where the information comes from:
13//   Claude subagent starts      the Agent tool call (description, model, background)
14//   its id and real model       the agent.spawn event
15//   its cost and its finish     its own requests and its turn.complete, which carry its id
16//   relay starts (Codex, ...)   a shell command running <name>-delegate/scripts/relay.mjs
17//   Codex plugin jobs           a /codex:rescue subagent, or a codex-companion.mjs command;
18//                               a background one is watched through its job id
19//   a foreground relay's finish the command returning, with the relay's summary
20//   a background relay's finish the relay process disappearing from the process list
21//   Opus's cost while delegating every main-conversation request while a job is open
22//
23// The rules (recognising a relay, sizing a task, choosing the band line) are in logic.ts.
24
25import { atom, read, update } from 'claude-code'
26import type { EngineInterface, Register, Timer } from 'claude-code'
27
28import type { DayTotals, Job } from '../types'
29import {
30  EMPTY_DAY,
31  addToDay,
32  bandFor,
33  bandJobs,
34  petRows,
35  petSvg,
36  petMark,
37  relayLabel,
38  subagentLabel,
39  PET_FRAME_MS,
40  costUnits,
41  dayOf,
42  formatElapsed,
43  formatUnits,
44  COMPANION_WORK,
45  DELEGATION_POLICY,
46  backgroundCompanionJobId,
47  filesNamed,
48  isCodexRescue,
49  isReadOnly,
50  isReadOnlyRequest,
51  isSmall,
52  killMatchingArgv,
53  laneMapText,
54  listProcessesArgv,
55  parseCompanion,
56  platformFromUname,
57  parseRelay,
58  relayFailed,
59  relayModel,
60  refusalReason,
61  confirmQuestion,
62  parseConfirmArg,
63  userAskedToDelegate,
64  subagentWorker,
65  titleFromBrief,
66  touchedFiles,
67  ACTION_DESCRIPTIONS,
68  WORKER_ACTIONS,
69  agyJobState,
70  agyStatusTable,
71  fillTemplate,
72  modelFor,
73  newAgyJobId,
74  splitArgs,
75  withModel,
76} from './logic'
77import type { AgyJob, Lane, PendingRun, Platform, Usage, Worker, WorkerAction } from './logic'
78
79const PANE = 'delegations'
80const TICK_MS = 15_000
81const DAYS_KEY = 'days'
82/** Store key: true when every delegation asks before it starts (/delegate-confirm on). */
83const CONFIRM_KEY = 'confirm'
84const SMALL_TASK_ADVICE =
85  'Small task: in your cost test, Opus solo was cheaper and faster for 1-file changes'
86
87// The lane map from delegate-setup, read at session start: as lines for the system prompt,
88// and as data for the models the /codex-* and /agy-* commands pick.
89let laneText = ''
90let lanes: Record<string, Lane> = {}
91
92// True when the official Codex plugin is installed too: our /codex-* commands then point to
93// its /codex:* ones instead of running a second copy.
94let officialCodex = false
95
96// Where /agy-* jobs keep their files: one folder per job with job.json, brief.md, result.json.
97let agyJobsRoot = ''
98
99// Windows or macOS/Linux, decided once at session start; it picks the process commands.
100let platform: Platform = 'windows'
101
102// The user's latest message, typed by them. A small delegation is allowed when it asked
103// for one. A plain variable: losing it on a reload only means one extra refusal.
104let lastUserMessage = ''
105
106/** The refusal sent back for a small delegation the user did not ask for, or null to allow. */
107function smallDelegationRefusal(brief: string, readOnly: boolean): string | null {
108  if (readOnly || !isSmall(brief) || userAskedToDelegate(lastUserMessage)) {
109    return null
110  }
111
112  return refusalReason(filesNamed(brief))
113}
114
115const jobs = atom({ plugin: 'delegation', key: 'jobs' } as const, [])
116const today = atom({ plugin: 'delegation', key: 'today' } as const, EMPTY_DAY)
117const now = atom({ plugin: 'delegation', key: 'now' } as const, 0)
118const bandClearedAt = atom({ plugin: 'delegation', key: 'bandClearedAt' } as const, 0)
119const bandHidden = atom({ plugin: 'delegation', key: 'bandHidden' } as const, false)
120const frame = atom({ plugin: 'delegation', key: 'frame' } as const, 0)
121
122// The fast timer that moves the pets' legs. A module variable: a reload loses it, so
123// session.start (which runs again on a reload) restarts it when a job is still running.
124let petTimer: Timer | null = null
125
126/** Note a failure in the debug log (claude --debug). The band never blocks real work. */
127function reportFailure($: EngineInterface, where: string, err: unknown) {
128  $.ui.log(`delegation: ${where} failed: ${err instanceof Error ? err.message : String(err)}`, { to: 'debug' })
129}
130
131/** Start the pets' animation, unless it already runs. It stops itself when no job runs. */
132function startPetTimer($: EngineInterface) {
133  if (petTimer) {
134    return
135  }
136  petTimer = $.clock.every(PET_FRAME_MS, () => {
137    void (async () => {
138      const list = await read($, jobs)
139      if (!list.some(job => job.status === 'running')) {
140        petTimer?.cancel()
141        petTimer = null
142        return
143      }
144      await update($, frame, n => n + 1)
145    })().catch(err => reportFailure($, 'pet animation', err))
146  })
147}
148
149/** Change one job, found by its id. */
150async function changeJob($: EngineInterface, id: string, change: (job: Job) => Job) {
151  await update($, jobs, list => list.map(job => (job.id === id ? change(job) : job)))
152}
153
154/** Add numbers to today's totals, here and in the store all sessions share. */
155async function addToday($: EngineInterface, change: Partial<DayTotals>) {
156  const day = dayOf(await $.clock.now())
157  const all = ((await $.store.get(DAYS_KEY)) ?? {}) as Record<string, DayTotals>
158  const updated = addToDay(all[day] ?? EMPTY_DAY, change)
159  // Keep only today's entry: older days are not shown anywhere.
160  await $.store.set(DAYS_KEY, { [day]: updated })
161  await update($, today, () => updated)
162}
163
164/** Record a new job and count it for today. */
165async function startJob($: EngineInterface, job: Job, isRelay: boolean) {
166  await update($, jobs, list => [...list, job])
167  startPetTimer($)
168  await addToday($, { jobs: 1, relayCalls: isRelay ? 1 : 0 })
169  if (job.small) {
170    $.ui.toast(SMALL_TASK_ADVICE)
171  }
172}
173
174/** Mark a job ended. It keeps counting Opus requests until the current turn ends. */
175async function finishJob($: EngineInterface, id: string, status: Job['status'], filesChanged?: number | null) {
176  const at = await $.clock.now()
177  await changeJob($, id, job =>
178    job.status === 'running'
179      ? { ...job, status, finishedAt: at, filesChanged: filesChanged ?? job.filesChanged }
180      : job,
181  )
182  const job = (await read($, jobs)).find(one => one.id === id)
183  if (job && status === 'done') {
184    $.ui.toast(`${job.worker} finished: ${job.title}`)
185  }
186}
187
188/**
189 * The command lines of all running processes (PowerShell on Windows, ps elsewhere).
190 * Used to tell whether a background job is still alive.
191 */
192async function processCommandLines($: EngineInterface): Promise<string> {
193  const listed = await $.process.run(listProcessesArgv(platform), { timeoutMs: 15_000 })
194
195  return listed.stdout
196}
197
198/** A background job whose process is gone has finished (or died). Check them all. */
199async function checkBackgroundRelays($: EngineInterface) {
200  const open = (await read($, jobs)).filter(job => job.status === 'running' && job.background && job.aliveMarker)
201  if (open.length === 0) {
202    return
203  }
204  const running = await processCommandLines($)
205  for (const job of open) {
206    if (!running.includes(job.aliveMarker as string)) {
207      // We cannot tell success from failure here; the relay's result.json says that,
208      // and Claude reads it when it is notified. "done" means "no longer running".
209      await finishJob($, job.id, 'done')
210    }
211  }
212}
213
214/**
215 * Stop a job by ending every process whose command line carries its marker: the brief
216 * path of a relay job, or the job id of a background Codex plugin job.
217 */
218async function stopJob($: EngineInterface, job: Job) {
219  if (!job.aliveMarker) {
220    return
221  }
222  await $.process.run(killMatchingArgv(platform, job.aliveMarker), { timeoutMs: 20_000 }).catch(() => undefined)
223  await finishJob($, job.id, 'stopped')
224  $.ui.toast(`Stopped ${job.worker}: ${job.title}`)
225}
226
227/**
228 * A codex-companion.mjs call from the official Codex plugin.
229 *
230 * Inside a /codex:rescue subagent it is that rescue job's actual Codex run, already
231 * checked against the policy when the subagent started: only record its model and, for a
232 * background run, its job id. Called directly, it is a job of its own, checked here.
233 */
234async function runCompanion(
235  $: EngineInterface,
236  e: { tool_use_id: string; agentId?: string },
237  next: (e: never) => Promise<unknown>,
238  call: import('./logic').CompanionCall,
239) {
240  const rescueJob = e.agentId
241    ? (await read($, jobs)).find(job => job.agentId === e.agentId && job.status === 'running')
242    : undefined
243
244  if (!rescueJob) {
245    const readOnly = call.subcommand !== 'task' || !call.write
246    const refusal = smallDelegationRefusal(call.text, readOnly)
247    if (refusal) {
248      $.ui.toast('Refused a small delegation: doing it directly is cheaper')
249
250      return { deny: refusal }
251    }
252    const job: Job = {
253      id: e.tool_use_id,
254      worker: call.subcommand === 'task' ? 'Codex' : `Codex ${call.subcommand}`,
255      model: call.model,
256      title: call.text ? titleFromBrief(call.text) : call.subcommand,
257      label: relayLabel('codex', call.subcommand),
258      startedAt: await $.clock.now(),
259      finishedAt: null,
260      status: 'running',
261      background: call.background,
262      small: isSmall(call.text),
263      aliveMarker: null,
264      agentId: null,
265      opusRequests: 0,
266      opusUnits: 0,
267      workerUnits: 0,
268      filesChanged: null,
269      isTracking: true,
270    }
271    await startJob($, job, true).catch(() => undefined)
272  } else if (call.model) {
273    await changeJob($, rescueJob.id, job => ({ ...job, model: call.model })).catch(() => undefined)
274  }
275
276  const ran = await next(e as never)
277  const ownerId = rescueJob ? rescueJob.id : e.tool_use_id
278  const jobId = call.background ? backgroundCompanionJobId(JSON.stringify(ran)) : null
279  if (jobId) {
280    // Codex keeps working in a worker process that carries this id: watch it, and let
281    // Stop end it.
282    await changeJob($, ownerId, job => ({ ...job, background: true, aliveMarker: jobId })).catch(() => undefined)
283  } else if (!rescueJob) {
284    await finishJob($, ownerId, 'done').catch(() => undefined)
285  }
286
287  return ran
288}
289
290/** Read a brief file for its title and size. A missing file just gives defaults. */
291async function readBrief($: EngineInterface, path: string): Promise<string> {
292  try {
293    const content = await $.fs.read(path)
294
295    return typeof content === 'string' ? content : ''
296  } catch {
297    return ''
298  }
299}
300
301const CONFIRM_RUN = 'Run it'
302const CONFIRM_CANCEL = 'Cancel'
303
304/** Is confirmation on? Off unless /delegate-confirm on was run; off too if the store fails. */
305async function confirmOn($: EngineInterface): Promise<boolean> {
306  try {
307    return (await $.store.get(CONFIRM_KEY)) === true
308  } catch {
309    return false
310  }
311}
312
313/**
314 * With confirmation on: show what is about to be sent and wait for a yes.
315 * Returns the refusal text when the person cancels, or null to let the run start.
316 */
317async function confirmRefusal($: EngineInterface, run: PendingRun): Promise<string | null> {
318  if (!(await confirmOn($))) {
319    return null
320  }
321  let answer = CONFIRM_CANCEL
322  try {
323    answer = await $.ui.ask(confirmQuestion(run), { header: 'Delegation', options: [CONFIRM_RUN, CONFIRM_CANCEL] })
324  } catch {
325    // Dismissed: treat it as Cancel, so nothing is spent by accident.
326  }
327  if (answer === CONFIRM_RUN) {
328    return null
329  }
330
331  return (
332    `The user cancelled this ${run.worker} run in the delegation plugin's dialog` +
333    (answer !== CONFIRM_CANCEL ? ` and wrote: "${answer}"` : '') +
334    '. Do not retry it; ask whether to narrow the brief, use a cheaper model, or do it directly.'
335  )
336}
337
338// ---- The bundled worker commands: /codex-* and /agy-* ------------------------------------
339
340const PLAIN_REVIEW_STYLE =
341  'Ask agy for a careful code review of the patch: bugs, regressions, missing tests and unclear code.'
342const ADVERSARIAL_STYLE =
343  'Ask agy for an adversarial review: challenge whether this approach is the right one, which ' +
344  'assumptions it depends on and where it could fail under real conditions, not only line-level ' +
345  "defects. Include the user's focus, if any."
346
347/** The plugin's folder with forward slashes, so paths in prompts work in Bash and PowerShell. */
348function rootPath($: EngineInterface): string {
349  return $.plugin.root.replace(/\\/g, '/')
350}
351
352/** Hand Claude a prompt without waiting: it only starts once the command has finished. */
353function sendToClaude($: EngineInterface, text: string) {
354  void $.prompt.submit({ text, asUser: true }).catch(() => undefined)
355}
356
357/** A JSON file's content, or null when it is missing or not JSON. */
358async function readJson($: EngineInterface, path: string): Promise<any> {
359  try {
360    return JSON.parse(String(await $.fs.read(path)))
361  } catch {
362    return null
363  }
364}
365
366/**
367 * /codex-<action>: the vendored Codex companion. Status, result and cancel run it directly
368 * and answer at once; the others hand Claude the upstream command text, with our model added.
369 */
370async function codexCommand($: EngineInterface, action: WorkerAction, args: string): Promise<{ text: string }> {
371  if (officialCodex) {
372    return {
373      text: `The official Codex plugin is installed, so use /codex:${action}. This plugin still sizes and tracks its jobs.`,
374    }
375  }
376  const codexRoot = `${rootPath($)}/codex`
377  // setup only checks node, Codex and its sign-in, and prints how to install what is missing.
378  if (action === 'status' || action === 'result' || action === 'cancel' || action === 'setup') {
379    // CLAUDE_PLUGIN_DATA cleared: the companion then keeps state where Claude's shell runs do.
380    const ran = await $.process.run(
381      ['node', `${codexRoot}/scripts/codex-companion.mjs`, action, ...args.split(/\s+/).filter(Boolean)],
382      { env: { CLAUDE_PLUGIN_DATA: '' }, timeoutMs: 60_000 },
383    )
384
385    return { text: (ran.stdout || ran.stderr).trim() || `The Codex companion printed nothing for ${action}.` }
386  }
387
388  const model = modelFor(`codex-${action}`, splitArgs(args).model, lanes)
389  const template = String(await $.fs.read(`${codexRoot}/commands/${action}.md`))
390  lastUserMessage = `delegate ${args}` // the user asked: the size check must not refuse it
391  sendToClaude($, fillTemplate(template, { ARGUMENTS: withModel(args, model), CLAUDE_PLUGIN_ROOT: codexRoot }))
392
393  return { text: `Sent to Claude: Codex ${action} (${model}).` }
394}
395
396/** Every agy job on this machine, newest first, with its state. */
397async function agyJobs($: EngineInterface): Promise<Array<AgyJob & { state: ReturnType<typeof agyJobState> }>> {
398  const entries = await $.fs.list(agyJobsRoot).catch(() => [])
399  const running = entries.length > 0 ? await processCommandLines($).catch(() => '') : ''
400  const rows = []
401  for (const entry of entries.filter(one => one.kind === 'dir')) {
402    const job: AgyJob | null = await readJson($, `${agyJobsRoot}/${entry.name}/job.json`)
403    if (job) {
404      const result = await readJson($, `${agyJobsRoot}/${entry.name}/result.json`)
405      // The relay's command line carries the brief path, which carries the job id.
406      rows.push({ ...job, state: agyJobState(result, running.includes(job.id)) })
407    }
408  }
409
410  return rows.sort((a, b) => b.startedAt - a.startedAt)
411}
412
413/** /agy-<action>: the Codex commands' twins, built on the agy relay and a folder per job. */
414async function agyCommand($: EngineInterface, action: WorkerAction, args: string): Promise<{ text: string }> {
415  if (!agyJobsRoot) {
416    return { text: 'No home folder found, so agy jobs have nowhere to keep their files.' }
417  }
418  const at = await $.clock.now()
419
420  if (action === 'status') {
421    return { text: agyStatusTable((await agyJobs($)).slice(0, 10), at) }
422  }
423
424  if (action === 'result' || action === 'cancel') {
425    const all = await agyJobs($)
426    const wanted = args.trim()
427    const job = wanted
428      ? all.find(one => one.id === wanted)
429      : action === 'cancel'
430        ? all.find(one => one.state === 'running')
431        : all[0]
432    if (!job) {
433      return { text: wanted ? `No agy job ${wanted}. /agy-status lists them.` : `No agy job to ${action}.` }
434    }
435    if (action === 'cancel') {
436      if (job.state !== 'running') {
437        return { text: `${job.id} is not running (${job.state}).` }
438      }
439      await $.process.run(killMatchingArgv(platform, job.id), { timeoutMs: 20_000 }).catch(() => undefined)
440      for (const tracked of (await read($, jobs)).filter(one => one.status === 'running' && one.aliveMarker?.includes(job.id))) {
441        await finishJob($, tracked.id, 'stopped')
442      }
443
444      return { text: `Cancelled ${job.id}: ${job.title}` }
445    }
446    const result = await readJson($, `${agyJobsRoot}/${job.id}/result.json`)
447    if (!result) {
448      return { text: `${job.id} has no result yet (${job.state}).` }
449    }
450    // A review changes nothing: its git status is the changes it reviewed, not its own.
451    const files =
452      job.kind === 'rescue' && Array.isArray(result.touchedFiles)
453        ? `\n\nFiles touched: ${result.touchedFiles.join(', ') || 'none'}`
454        : ''
455    const failure = result.status !== 'completed' && result.error ? `\n\nWhy it failed: ${result.error}` : ''
456
457    return {
458      text: `${job.id} · ${job.kind} · ${result.status} · ${job.model}\n\n${result.finalMessage || '(agy gave no final message)'}${failure}${files}`,
459    }
460  }
461
462  if (action === 'setup') {
463    const version = await $.process.run(['agy', '--version'], { timeoutMs: 15_000 }).catch(() => null)
464    if (!version || version.exitCode !== 0) {
465      return {
466        text: 'agy is not installed or not on PATH. Install the Google Antigravity CLI, run `agy` once to sign in, then run /agy-setup again.',
467      }
468    }
469    const models = await $.process.run(['agy', 'models'], { timeoutMs: 30_000 }).catch(() => null)
470    const listed = models && models.exitCode === 0 ? models.stdout.trim().split('\n').filter(Boolean).length : 0
471
472    return {
473      text: [
474        `agy ${version.stdout.trim()}`,
475        listed > 0 ? `Signed in: ${listed} models available.` : 'Could not list models: run `agy` once to sign in.',
476        `Defaults: rescue ${modelFor('agy-rescue', null, lanes)}, review ${modelFor('agy-review', null, lanes)}, ` +
477          `adversarial review ${modelFor('agy-adversarial-review', null, lanes)}.`,
478        'Lanes in the delegate-setup config change these; --model on a command overrides them.',
479      ].join('\n'),
480    }
481  }
482
483  // rescue, review, adversarial-review: record the job, then hand Claude the steps.
484  const parsed = splitArgs(args)
485  const model = modelFor(`agy-${action}`, parsed.model, lanes)
486  const id = newAgyJobId(at)
487  const jobDir = `${agyJobsRoot}/${id}`
488  const job: AgyJob = { id, kind: action, title: parsed.text ? titleFromBrief(parsed.text) : action, model, startedAt: at }
489  await $.fs.write(`${jobDir}/job.json`, JSON.stringify(job, null, 2))
490
491  const template = String(await $.fs.read(`${rootPath($)}/agy/commands/${action === 'rescue' ? 'rescue' : 'review'}.md`))
492  lastUserMessage = `delegate ${args}` // the user asked: the size check must not refuse it
493  sendToClaude(
494    $,
495    fillTemplate(template, {
496      JOB_ID: id,
497      JOB_DIR: jobDir,
498      RELAY: `${rootPath($)}/skills/agy-delegate/scripts/relay.mjs`,
499      MODEL: model,
500      TASK: parsed.text || '(none given)',
501      BASE: parsed.base ?? 'none: review the working tree',
502      BACKGROUND_NOTE: parsed.background ? ' with `run_in_background: true`, then tell the user to check `/agy-status`' : '',
503      REVIEW_STYLE: action === 'adversarial-review' ? ADVERSARIAL_STYLE : PLAIN_REVIEW_STYLE,
504    }),
505  )
506
507  return { text: `Sent to Claude: agy ${action} (${model}), job ${id}.` }
508}
509
510export const register: Register = on => {
511  on('session.start', async ($, e, next) => {
512    // Which process commands to use. `uname` is missing on most Windows machines.
513    try {
514      const uname = await $.process.run(['uname', '-s'], { timeoutMs: 5_000 })
515      platform = platformFromUname(uname.exitCode === 0 ? uname.stdout : null)
516    } catch {
517      platform = 'windows'
518    }
519
520    try {
521      const at = await $.clock.now()
522      await update($, now, () => at)
523      const all = ((await $.store.get(DAYS_KEY)) ?? {}) as Record<string, DayTotals>
524      await update($, today, () => all[dayOf(at)] ?? EMPTY_DAY)
525    } catch {
526      // The band works without today's totals.
527    }
528
529    // The lane map lives where delegate-setup writes it: $XDG_CONFIG_HOME, else ~/.config.
530    try {
531      const xdg = await $.env.get('XDG_CONFIG_HOME')
532      const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
533      const configDir = xdg ?? (home ? `${home}/.config` : null)
534      if (home) {
535        agyJobsRoot = `${home.replace(/\\/g, '/')}/.claude/delegation/agy-jobs`
536      }
537      if (configDir) {
538        const raw = await $.fs.read(`${configDir}/delegate-skills/config.json`)
539        const config = JSON.parse(typeof raw === 'string' ? raw : '{}')
540        laneText = laneMapText(config)
541        lanes = config.lanes ?? {}
542      }
543    } catch {
544      laneText = '' // no lanes yet: /delegate-setup creates them, and the commands use defaults
545    }
546
547    // The official Codex plugin names its commands codex:<name>.
548    try {
549      officialCodex = (await $.command.list()).some(command => command.name.startsWith('codex:'))
550    } catch {
551      officialCodex = false
552    }
553
554    // Each command on its own, so a name the app refuses does not block the others.
555    // (/delegate-setup is the shipped delegate-setup skill itself, so it needs no command.)
556    const commands = [
557      { name: 'delegations', description: 'Open the delegations pane' },
558      { name: 'delegate', description: 'Delegate a task, if it is worth it: /delegate <task>' },
559      { name: 'explore', description: 'Ask agy a fast read-only question about the codebase: /explore <question>' },
560      { name: 'delegate-confirm', description: 'Ask before every delegation starts: /delegate-confirm on|off' },
561    ]
562    for (const worker of ['codex', 'agy'] as const) {
563      const name = worker === 'codex' ? 'Codex' : 'agy'
564      for (const action of WORKER_ACTIONS) {
565        commands.push({ name: `${worker}-${action}`, description: ACTION_DESCRIPTIONS[action].replace('{worker}', name) })
566      }
567    }
568    for (const command of commands) {
569      await $.command.register(command).catch(() => undefined)
570    }
571
572    $.clock.every(TICK_MS, () => {
573      void (async () => {
574        const at = await $.clock.now()
575        await update($, now, () => at)
576        await checkBackgroundRelays($)
577      })().catch(() => undefined)
578    })
579
580    // After a reload the jobs survive but the pet timer does not: restart it if one runs.
581    try {
582      if ((await read($, jobs)).some(job => job.status === 'running')) {
583        startPetTimer($)
584      }
585    } catch (err) {
586      reportFailure($, 'restarting the pet animation', err)
587    }
588
589    return next(e)
590  })
591
592  on('command.run', { command: 'delegate' }, async ($, e) => {
593    const task = e.args.trim()
594    if (task === '') {
595      return { text: 'Usage: /delegate <task>' }
596    }
597    lastUserMessage = `delegate ${task}` // the user asked: the size check must not refuse it
598    // Not awaited: the prompt only starts once this command has finished, so waiting for it
599    // here would wait forever and the command would never answer.
600    void $.prompt
601      .submit({
602        text:
603          'Delegate this task if it is worth it under the delegation policy; if it is not, say why ' +
604          'and do it yourself. Pick the worker and lane, write a tight brief (files it may change, ' +
605          `acceptance check), run it, then review the result.\n\nTask: ${task}`,
606        asUser: true,
607      })
608      .catch(() => undefined)
609
610    return { text: 'Sent to Claude to delegate.' }
611  })
612
613  on('command.run', { command: 'explore' }, async ($, e) => {
614    const question = e.args.trim()
615    if (question === '') {
616      return { text: 'Usage: /explore <question about the codebase>' }
617    }
618    lastUserMessage = `delegate explore ${question}`
619    // Not awaited, for the same reason as /delegate.
620    void $.prompt
621      .submit({
622        text:
623          'Answer this question about the codebase by asking agy read-only on its research lane ' +
624          '(agy-delegate skill, --lane research --read-only). Ask it for file and line references, ' +
625          `spot-check the key ones, then answer.\n\nQuestion: ${question}`,
626        asUser: true,
627      })
628      .catch(() => undefined)
629
630    return { text: 'Sent to Claude to ask agy.' }
631  })
632
633  on('command.run', { command: 'delegate-confirm' }, async ($, e) => {
634    const setting = parseConfirmArg(e.args)
635    if (setting === 'invalid') {
636      return { text: 'Usage: /delegate-confirm on|off (no argument shows the setting)' }
637    }
638    if (setting !== null) {
639      await $.store.set(CONFIRM_KEY, setting)
640    }
641    const enabled = setting ?? (await confirmOn($))
642
643    return {
644      text: enabled
645        ? 'Confirmation is on: every delegation asks before it starts. /delegate-confirm off turns it off.'
646        : 'Confirmation is off: delegations start without asking. /delegate-confirm on turns it on.',
647    }
648  })
649
650  on('command.run', { command: 'delegations' }, async $ => {
651    await $.ui.open({ id: PANE, title: 'Delegations' })
652
653    return { text: 'Delegations pane opened.' }
654  })
655
656  for (const worker of ['codex', 'agy'] as const satisfies readonly Worker[]) {
657    for (const action of WORKER_ACTIONS) {
658      on('command.run', { command: `${worker}-${action}` }, async ($, e) => {
659        try {
660          return worker === 'codex' ? await codexCommand($, action, e.args) : await agyCommand($, action, e.args)
661        } catch (error) {
662          return { text: `/${worker}-${action} failed: ${error instanceof Error ? error.message : String(error)}` }
663        }
664      })
665    }
666  }
667
668  // ---- The policy: in every session's instructions --------------------------------------
669
670  // Appended to the system prompt, so the rule travels with the plugin instead of living in
671  // each person's CLAUDE.md. "session" scope: it is ours, not shared across organizations.
672  on('prompt.compose', async ($, e, next) => {
673    const composed = await next(e)
674
675    return {
676      ...composed,
677      sections: [
678        ...composed.sections,
679        {
680          id: 'delegation:policy',
681          text: laneText ? `${DELEGATION_POLICY}\n\n${laneText}` : DELEGATION_POLICY,
682          scope: 'session' as const,
683        },
684      ],
685    }
686  })
687
688  on('prompt.submit', async ($, e, next) => {
689    // Only what the person typed counts as asking; not text a plugin sent for them.
690    if (e.origin?.kind === 'composer') {
691      lastUserMessage = e.text
692    }
693    // A new prompt: finished pets leave the band (running ones stay), and Hide ends.
694    try {
695      const at = await $.clock.now()
696      await update($, bandClearedAt, () => at)
697      await update($, bandHidden, () => false)
698    } catch (err) {
699      reportFailure($, 'clearing the band', err)
700    }
701
702    return next(e)
703  })
704
705  // ---- Claude subagents -------------------------------------------------------------
706
707  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
708    // Enforce the policy: a small task the user did not ask to delegate is refused, and
709    // Claude gets the reason back as the tool's result.
710    const rescue = isCodexRescue(e.subagent_type)
711    const readOnly =
712      isReadOnly({ subagentType: e.subagent_type }) || (rescue && isReadOnlyRequest(e.prompt))
713    const refusal = smallDelegationRefusal(e.prompt, readOnly)
714    if (refusal) {
715      $.ui.toast('Refused a small delegation: doing it directly is cheaper')
716
717      return { deny: refusal }
718    }
719    // /codex:rescue is not asked about here: its forwarder runs a companion command, which asks.
720    if (!rescue) {
721      const cancelled = await confirmRefusal($, {
722        worker: subagentWorker(e.model),
723        model: e.model ?? null,
724        lane: null,
725        brief: e.prompt,
726      })
727      if (cancelled) {
728        return { deny: cancelled }
729      }
730    }
731
732    const background = e.run_in_background !== false
733    try {
734      const job: Job = {
735        id: e.tool_use_id,
736        // /codex:rescue: a Sonnet forwarder whose real worker is Codex.
737        worker: rescue ? 'Codex (rescue)' : subagentWorker(e.model),
738        model: rescue ? (e.prompt.match(/--model\s+(\S+)/)?.[1] ?? null) : (e.model ?? null),
739        title: e.description,
740        label: rescue ? 'codex:rescue' : subagentLabel(e.subagent_type, e.model),
741        startedAt: await $.clock.now(),
742        finishedAt: null,
743        status: 'running',
744        background,
745        small: isSmall(e.prompt),
746        aliveMarker: null,
747        agentId: null,
748        opusRequests: 0,
749        opusUnits: 0,
750        workerUnits: 0,
751        filesChanged: null,
752        isTracking: true,
753      }
754      await startJob($, job, false)
755    } catch {
756      // A job we failed to record only goes missing from the pane.
757    }
758
759    const ran = await next(e)
760    // A foreground subagent has finished when the call returns. A background one only
761    // started; its own turn.complete (below) says when it ends. A rescue subagent that
762    // started Codex in the background has a job id marker by now: Codex is still working.
763    const job = (await read($, jobs).catch(() => [] as Job[])).find(one => one.id === e.tool_use_id)
764    if (!background && !(job && job.aliveMarker)) {
765      await finishJob($, e.tool_use_id, 'done').catch(() => undefined)
766    }
767
768    return ran
769  })
770
771  // The spawn event links the tool call to the subagent's id and its real model.
772  on('agent.spawn', async ($, e, next) => {
773    const spawned = await next(e)
774    // The model is known even when no id came back (a remote workflow agent has none).
775    if (spawned.model || spawned.agentId) {
776      const agentId = spawned.agentId ?? null
777      await changeJob($, e.tool_use_id, job => ({
778        ...job,
779        agentId: agentId ?? job.agentId,
780        model: spawned.model ?? job.model,
781        worker: job.worker === 'Subagent' ? subagentWorker(spawned.model) : job.worker,
782        // "Explore/inherit" becomes "Explore/opus"; a rescue's "codex:rescue" stays.
783        label: (job.label ?? '').includes('/')
784          ? subagentLabel(job.label.split('/')[0], spawned.model ?? job.model)
785          : job.label,
786      })).catch(() => undefined)
787    }
788
789    return spawned
790  })
791
792  // ---- Relays: Codex, agy, a separate Claude CLI ---------------------------------------
793
794  for (const shell of ['Bash', 'PowerShell'] as const) {
795    on('tool.call', { tool: shell }, async ($, e, next) => {
796      const companion = parseCompanion(e.command)
797      if (companion && COMPANION_WORK.has(companion.subcommand)) {
798        const cancelled = await confirmRefusal($, {
799          worker: 'Codex',
800          model: companion.model,
801          lane: null,
802          brief: companion.text,
803        })
804        if (cancelled) {
805          return { deny: cancelled }
806        }
807
808        return runCompanion($, e, next, companion)
809      }
810
811      const relay = parseRelay(e.command)
812      if (!relay) {
813        return next(e)
814      }
815
816      const brief = await readBrief($, relay.briefPath)
817      const refusal = smallDelegationRefusal(brief, isReadOnly({ command: e.command }))
818      if (refusal) {
819        $.ui.toast('Refused a small delegation: doing it directly is cheaper')
820
821        return { deny: refusal }
822      }
823      const cancelled = await confirmRefusal($, {
824        worker: relay.worker,
825        model: relay.model ?? (relay.lane ? (lanes[relay.lane]?.model ?? null) : null),
826        lane: relay.lane,
827        brief,
828      })
829      if (cancelled) {
830        return { deny: cancelled }
831      }
832
833      const background = e.run_in_background === true
834      try {
835        const job: Job = {
836          id: e.tool_use_id,
837          worker: relay.worker,
838          model: relayModel(relay, lanes),
839          title: brief ? titleFromBrief(brief) : 'delegated task',
840          label: relayLabel(relay.skill, relay.lane),
841          startedAt: await $.clock.now(),
842          finishedAt: null,
843          status: 'running',
844          background,
845          small: isSmall(brief),
846          aliveMarker: relay.briefPath,
847          agentId: null,
848          opusRequests: 0,
849          opusUnits: 0,
850          workerUnits: 0,
851          filesChanged: null,
852          isTracking: true,
853        }
854        await startJob($, job, true)
855      } catch {
856        // As above.
857      }
858
859      const ran = await next(e)
860      if (!background) {
861        // The relay ran in the foreground and has finished; its summary is the output.
862        const output = JSON.stringify(ran)
863        const failed = relayFailed(output)
864        await finishJob($, e.tool_use_id, failed ? 'failed' : 'done', touchedFiles(output.replace(/\\"/g, '"'))).catch(
865          () => undefined,
866        )
867      }
868
869      return ran
870    })
871  }
872
873  // ---- Cost: every model request ------------------------------------------------------
874
875  on('turn.step', async function* ($, e, next) {
876    const result = yield* next(e)
877    try {
878      if (result.usage) {
879        const units = costUnits(result.usage as Usage)
880        if (e.agentId) {
881          // A subagent's request: it belongs to the job with that subagent id.
882          const agentId = e.agentId
883          const owner = (await read($, jobs)).find(job => job.agentId === agentId)
884          if (owner) {
885            await changeJob($, owner.id, job => ({ ...job, workerUnits: job.workerUnits + units }))
886            await addToday($, { workerUnits: units })
887          }
888        } else {
889          // An Opus request while delegation is open counts towards what delegating cost.
890          const open = (await read($, jobs)).filter(job => job.isTracking)
891          if (open.length > 0) {
892            await update($, jobs, list =>
893              list.map(job =>
894                job.isTracking
895                  ? { ...job, opusRequests: job.opusRequests + 1, opusUnits: job.opusUnits + units }
896                  : job,
897              ),
898            )
899            await addToday($, { opusRequests: 1, opusUnits: units })
900          }
901        }
902      }
903    } catch {
904      // Never let bookkeeping break a model request.
905    }
906
907    return result
908  })
909
910  on('turn.complete', async ($, e, next) => {
911    const result = await next(e)
912    try {
913      if (e.agentId) {
914        // A background subagent finished.
915        const agentId = e.agentId
916        const owner = (await read($, jobs)).find(job => job.agentId === agentId && job.status === 'running')
917        if (owner) {
918          await finishJob($, owner.id, e.isAborted ? 'failed' : 'done')
919        }
920      } else {
921        // The main turn ended: jobs that finished stop counting Opus requests now,
922        // which covers the review Opus did right after the result came back.
923        await update($, jobs, list =>
924          list.map(job => (job.isTracking && job.status !== 'running' ? { ...job, isTracking: false } : job)),
925        )
926      }
927    } catch {
928      // As above.
929    }
930
931    return result
932  })
933
934  // ---- Drawing --------------------------------------------------------------------------
935
936  // The band: a pet for each job, over one line in the shared three-column layout, above
937  // what others draw.
938  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
939    const beneath = await next(e)
940    if (e.props.hasSurvey || (await read($, bandHidden))) {
941      return beneath
942    }
943    const time = await read($, now)
944    const list = await read($, jobs)
945    const band = bandFor(list, time)
946    const pets = bandJobs(list, await read($, bandClearedAt))
947    if (band.kind === 'hidden' && pets.length === 0) {
948      return beneath
949    }
950
951    const ui = $.ui.resolve(e)
952    const { Box, Button, Text } = ui
953    // The desktop draws Text in its own font, so pixel art made of half blocks breaks
954    // there; it draws Svg, the pet's pixels as squares. Ask the surface, not the table:
955    // the terminal's table carries an Svg constructor too, which it cannot draw.
956    const Svg = e.surface !== 'terminal' && 'Svg' in ui ? ui.Svg : null
957    const step = await read($, frame)
958    const job = band.kind === 'hidden' ? null : band.job
959    const who = job ? `${job.worker}${job.model ? ` (${job.model})` : ''}` : ''
960
961    return (
962      <Box flexDirection="column" rowGap={1}>
963        {/* Its own filled card, one per plugin, so stacked bands read as separate. */}
964        <Box flexDirection="column" backgroundColor="userMessageBackground" paddingX={1}>
965          {pets.length > 0 && (
966            <Box key="pets" columnGap={2} flexWrap="wrap">
967              {pets.map(pet => {
968                const label = pet.label ?? pet.worker
969                // Each model has its own pet; a failed one is red, a finished one dimmed.
970                const dim = pet.status === 'done' || pet.status === 'stopped'
971
972                return (
973                  <Box key={`pet:${pet.id}`} flexDirection="column" alignItems="center">
974                    {Svg && (
975                      <Svg
976                        key={`pet:${pet.id}:svg`}
977                        alt={`${label} pet`}
978                        {...petSvg(pet, step)}
979                      />
980                    )}
981                    {!Svg && petRows(pet, step).map((row, i) => (
982                      <Box key={`pet:${pet.id}:${i}`}>
983                        {row.map((run, j) => (
984                          <Text
985                            key={`pet:${pet.id}:${i}:${j}`}
986                            color={run.color}
987                            backgroundColor={run.backgroundColor}
988                            dimColor={dim}
989                          >
990                            {run.text}
991                          </Text>
992                        ))}
993                      </Box>
994                    ))}
995                    <Text key={`caption:${pet.id}`} dimColor={dim}>
996                      {label} {petMark(pet)}
997                    </Text>
998                  </Box>
999                )
1000              })}
1001            </Box>
1002          )}
1003
1004          <Box columnGap={1} alignItems="center">
1005            {band.kind !== 'hidden' && job && (
1006              <Box flexGrow={1} flexShrink={1} minWidth={0} columnGap={1} alignItems="center">
1007                <Box width={2}>
1008                  {band.kind === 'running' && <Text color="warning">⠹</Text>}
1009                  {band.kind === 'advice' && <Text color="warning">i</Text>}
1010                  {band.kind === 'long' && <Text color="warning">!</Text>}
1011                  {band.kind === 'finished' && (
1012                    <Text color={job.status === 'done' ? 'success' : 'error'}>{job.status === 'done' ? '✓' : '✗'}</Text>
1013                  )}
1014                </Box>
1015
1016                <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
1017                  {band.kind === 'running' && (
1018                    <Text wrap="truncate-end">
1019                      {who} · {job.title} · {formatElapsed(time - job.startedAt)}
1020                      {band.count > 1 ? ` · ${band.count} running` : ''}
1021                    </Text>
1022                  )}
1023                  {band.kind === 'advice' && (
1024                    <Text color="warning" wrap="truncate-end">
1025                      {SMALL_TASK_ADVICE}
1026                    </Text>
1027                  )}
1028                  {band.kind === 'long' && (
1029                    <Text color="warning" wrap="truncate-end">
1030                      {who} running for {formatElapsed(time - job.startedAt)}. Still working?
1031                    </Text>
1032                  )}
1033                  {band.kind === 'finished' && (
1034                    <Text wrap="truncate-end">
1035                      {job.worker} {job.status} in {formatElapsed((job.finishedAt ?? time) - job.startedAt)}
1036                      {job.filesChanged !== null ? ` · ${job.filesChanged} files changed` : ''} · {job.title}
1037                    </Text>
1038                  )}
1039                </Box>
1040              </Box>
1041            )}
1042            {band.kind === 'hidden' && <Box flexGrow={1} />}
1043
1044            {band.kind !== 'finished' && job && job.aliveMarker && job.status === 'running' && (
1045              <Button key="band-stop" label="Stop" onPress={() => stopJob($, job)} />
1046            )}
1047            <Button
1048              key="open-delegations"
1049              label="Delegations"
1050              onPress={() => $.ui.open({ id: PANE, title: 'Delegations' })}
1051            />
1052            {/* Out of the way until the next prompt; the pane still has everything. */}
1053            <Button
1054              key="band-hide"
1055              label="Hide"
1056              onPress={() => update($, bandHidden, () => true).catch(err => reportFailure($, 'hiding the band', err))}
1057            />
1058          </Box>
1059        </Box>
1060        {beneath}
1061      </Box>
1062    )
1063  })
1064
1065  // The pane: running now, this session, today, and the cost test's findings.
1066  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1067    const list = await read($, jobs)
1068    const day = await read($, today)
1069    const time = await read($, now)
1070    const { Box, Button, Text } = $.ui.resolve(e)
1071    const running = list.filter(job => job.status === 'running')
1072
1073    /** One outlined card with a muted heading, as in the focus pane. */
1074    const section = (title: string, body: unknown) => (
1075      <Box flexDirection="column" rowGap={1} paddingX={1} borderStyle="round" borderDimColor>
1076        <Text dimColor>{title}</Text>
1077        {body}
1078      </Box>
1079    )
1080
1081    /** A label on the left and its value on the right. */
1082    const row = (label: string, value: string) => (
1083      <Box columnGap={2}>
1084        <Box flexGrow={1}>
1085          <Text dimColor>{label}</Text>
1086        </Box>
1087        <Text>{value}</Text>
1088      </Box>
1089    )
1090
1091    const statusMark: Record<Job['status'], string> = {
1092      running: '⠹',
1093      done: '✓',
1094      failed: '✗',
1095      stopped: '■',
1096    }
1097
1098    return (
1099      <Box flexDirection="column" rowGap={1} padding={1}>
1100        {section(
1101          `Running now (${running.length})`,
1102          <Box flexDirection="column" rowGap={1}>
1103            {running.length === 0 && <Text dimColor>Nothing delegated right now</Text>}
1104            {running.map(job => (
1105              <Box columnGap={1} alignItems="center">
1106                <Text color="warning">⠹</Text>
1107                <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
1108                  <Text>
1109                    {job.worker}
1110                    {job.model ? ` (${job.model})` : ''} · {job.title}
1111                  </Text>
1112                </Box>
1113                <Text dimColor>{formatElapsed(time - job.startedAt)}</Text>
1114                {job.aliveMarker && (
1115                  <Button key={`stop:${job.id}`} label="Stop" onPress={() => stopJob($, job)} />
1116                )}
1117              </Box>
1118            ))}
1119          </Box>,
1120        )}
1121
1122        {section(
1123          `This session (${list.length})`,
1124          <Box flexDirection="column" rowGap={1}>
1125            {list.length === 0 && <Text dimColor>No delegations yet in this session</Text>}
1126            {list.map(job => (
1127              <Box flexDirection="column">
1128                <Box columnGap={1}>
1129                  <Text color={job.status === 'done' ? 'success' : job.status === 'running' ? 'warning' : 'error'}>
1130                    {statusMark[job.status]}
1131                  </Text>
1132                  <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
1133                    <Text>
1134                      {job.worker} · {job.title}
1135                    </Text>
1136                  </Box>
1137                  {job.small && <Text dimColor>small</Text>}
1138                </Box>
1139                <Text dimColor>
1140                  {'  '}Opus {job.opusRequests} requests, {formatUnits(job.opusUnits)} units
1141                  {job.workerUnits > 0 ? ` · ${job.worker} ${formatUnits(job.workerUnits)} units` : ''}
1142                  {job.filesChanged !== null ? ` · ${job.filesChanged} files` : ''}
1143                  {job.finishedAt !== null ? ` · ${formatElapsed(job.finishedAt - job.startedAt)}` : ''}
1144                </Text>
1145              </Box>
1146            ))}
1147          </Box>,
1148        )}
1149
1150        {section(
1151          'Today, all sessions',
1152          <Box flexDirection="column">
1153            {row('Delegations', String(day.jobs))}
1154            {row('Opus requests while delegating', String(day.opusRequests))}
1155            {row('Opus units while delegating', formatUnits(day.opusUnits))}
1156            {row('Claude worker units', formatUnits(day.workerUnits))}
1157            {row('Relay calls (Codex and others)', String(day.relayCalls))}
1158          </Box>,
1159        )}
1160
1161        {section(
1162          'From your cost test (6 Oct)',
1163          <Box flexDirection="column">
1164            <Text>Opus solo: passed 3 of 3, fastest</Text>
1165            <Text>Codex: about 10% cheaper on Claude, 2 to 3 times slower</Text>
1166            <Text>Sonnet: most expensive every time</Text>
1167          </Box>,
1168        )}
1169      </Box>
1170    )
1171  })
1172}
1173
hooks/logic.ts 961 lines
1// The delegation mod's rules, as plain functions with no access to the app.
2// Tested on their own in logic.test.ts; register.tsx only does the wiring.
3
4import type { DayTotals, Job } from '../types'
5
6const SECOND = 1000
7const MINUTE = 60 * SECOND
8
9/** A running job past this age gets a warning: the Codex stall in the cost test hung for hours. */
10export const LONG_RUNNING_MS = 15 * MINUTE
11/** How long the "small task" advice stays in the band after a delegation starts. */
12export const ADVICE_MS = 60 * SECOND
13/** How long a finished job stays in the band. */
14export const FINISHED_SHOWN_MS = 10 * MINUTE
15
16/** The token counts the API reports for one request. */
17export type Usage = {
18  input_tokens: number
19  output_tokens: number
20  cache_read_input_tokens: number
21  cache_creation_input_tokens: number
22}
23
24/**
25 * One request in cost units: the API price list's ratios between token kinds
26 * (fresh input 1, cache read 0.1, cache write 2, output 5). Same rule as the cache mod.
27 */
28export function costUnits(usage: Usage): number {
29  return (
30    usage.input_tokens +
31    usage.cache_read_input_tokens * 0.1 +
32    usage.cache_creation_input_tokens * 2 +
33    usage.output_tokens * 5
34  )
35}
36
37/** A relay command that hands work to another tool, as found in a shell command. */
38export type RelayCall = {
39  worker: string
40  /** The skill's short name: "codex" for codex-delegate/scripts/relay.mjs. */
41  skill: string
42  briefPath: string
43  model: string | null
44  lane: string | null
45}
46
47const RELAY_WORKERS: Record<string, string> = {
48  'codex-delegate': 'Codex',
49  'agy-delegate': 'agy',
50  'claude-delegate': 'Claude CLI',
51  'cursor-delegate': 'Cursor',
52  'opencode-delegate': 'opencode',
53}
54
55/** Read one flag's value: `--model gpt-6-luna` or `--model "gpt 6"` -> the value. */
56function flag(command: string, name: string): string | null {
57  const match = command.match(new RegExp(`--${name}\\s+(?:"([^"]+)"|'([^']+)'|(\\S+))`))
58
59  return match ? (match[1] ?? match[2] ?? match[3]) : null
60}
61
62/**
63 * The part of a shell command that is actually run. A heredoc (`cat > file <<'EOF' ...`)
64 * carries a file's text inside the command; that text can mention a relay or the companion
65 * without calling it, so everything from the first heredoc marker on is left out.
66 */
67export function runPart(command: string): string {
68  return command.split(/<<-?\s*['"]?\w+/)[0]
69}
70
71/**
72 * Recognise a delegation in a shell command: a `relay.mjs` call with a brief.
73 * Returns null for anything else, including `relay.mjs --help`.
74 */
75export function parseRelay(fullCommand: string): RelayCall | null {
76  const command = runPart(fullCommand)
77  const relay = command.match(/([\w-]+-delegate)[\\/]scripts[\\/]relay\.mjs/)
78  if (!relay) {
79    return null
80  }
81  const briefPath = flag(command, 'brief')
82  if (!briefPath) {
83    return null // --help, or a brief piped on stdin, which we cannot read back
84  }
85
86  return {
87    worker: RELAY_WORKERS[relay[1]] ?? relay[1],
88    skill: (relay[1] ?? '').replace(/-delegate$/, ''),
89    briefPath,
90    model: flag(command, 'model'),
91    lane: flag(command, 'lane'),
92  }
93}
94
95/**
96 * Whether a foreground relay's output says it failed. Every relay ends with a summary line,
97 * "relay: failed (exit 1)  ·  codex 0.9"; a JSON result's "status": "failed" counts too.
98 * Failed, timed out, aborted, or the worker's CLI was not there ("codex_unavailable").
99 */
100export function relayFailed(output: string): boolean {
101  return (
102    /relay: (?:failed|timeout|aborted|\w+_unavailable) \(exit/.test(output) ||
103    /"status"\s*:\s*\\?"(?:failed|timeout|aborted|\w+_unavailable)/.test(output)
104  )
105}
106
107/**
108 * The model a relay call runs on: its --model flag, else the model its lane names in the
109 * lane map, else the lane itself ("lane implement") when the map names no model. The pet
110 * takes its look from this, so a Claude relay on a Sonnet lane gets Sonnet's pet.
111 */
112export function relayModel(relay: Pick<RelayCall, 'model' | 'lane'>, lanes: Record<string, Lane>): string | null {
113  if (relay.model) {
114    return relay.model
115  }
116  if (!relay.lane) {
117    return null
118  }
119
120  return lanes[relay.lane]?.model ?? `lane ${relay.lane}`
121}
122
123/** The worker name for a Claude subagent, from the model it was asked to use. */
124export function subagentWorker(model: string | undefined): string {
125  if (!model) {
126    return 'Subagent'
127  }
128  const family = model.replace(/^claude-/, '').split('-')[0]
129
130  return family.charAt(0).toUpperCase() + family.slice(1)
131}
132
133/**
134 * How many distinct files a brief names, counted from path-like words with a code
135 * extension. A rough measure of task size: good enough to flag a one-file job.
136 */
137export function filesNamed(text: string): number {
138  const paths = text.match(
139    /[\w.\\/-]+\.(?:py|ts|tsx|js|jsx|mjs|cjs|json|sql|ya?ml|toml|cs|java|go|rs|html|css|scss|vue|kt|swift|rb|php)\b/g,
140  )
141
142  return new Set(paths ?? []).size
143}
144
145/** One or two named files: the size where Opus solo was cheaper and faster in the cost test. */
146export function isSmall(text: string): boolean {
147  const count = filesNamed(text)
148
149  return count > 0 && count <= 2
150}
151
152/** Files the relay says the worker changed: `"touchedFiles": ["a", "b"]` -> 2. */
153export function touchedFiles(output: string): number | null {
154  const match = output.match(/"touchedFiles"\s*:\s*(\[[^\]]*\]|null)/)
155  if (!match || match[1] === 'null') {
156    return null
157  }
158
159  return (match[1].match(/"[^"]*"/g) ?? []).length
160}
161
162/** A short task name from a brief: its first non-empty line, without markdown, cut to fit. */
163export function titleFromBrief(brief: string): string {
164  const line =
165    brief
166      .split('\n')
167      .map(text => text.replace(/^[#>*\-\s]+/, '').replace(/[*_`]/g, '').trim())
168      .find(text => text !== '') ?? 'delegated task'
169
170  return line.length <= 60 ? line : `${line.slice(0, 59).trimEnd()}…`
171}
172
173/** 372_000 -> "45s"-style elapsed time: "45s", "6m 12s", "1h 3m". */
174export function formatElapsed(ms: number): string {
175  const seconds = Math.max(0, Math.floor(ms / SECOND))
176  if (seconds < 60) {
177    return `${seconds}s`
178  }
179  const minutes = Math.floor(seconds / 60)
180  if (minutes < 60) {
181    return `${minutes}m ${seconds % 60}s`
182  }
183
184  return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
185}
186
187/** 186_432 -> "186k". */
188export function formatUnits(units: number): string {
189  if (units >= 1_000_000) {
190    return `${(units / 1_000_000).toFixed(1)}M`
191  }
192
193  return units >= 1_000 ? `${Math.round(units / 1_000)}k` : String(Math.round(units))
194}
195
196/** The calendar day of a moment, in local time: "2026-10-06". */
197export function dayOf(ms: number): string {
198  const date = new Date(ms)
199  const pad = (n: number) => String(n).padStart(2, '0')
200
201  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
202}
203
204export const EMPTY_DAY: DayTotals = { jobs: 0, opusRequests: 0, opusUnits: 0, workerUnits: 0, relayCalls: 0 }
205
206/** Add one set of numbers to a day's totals. */
207export function addToDay(day: DayTotals, change: Partial<DayTotals>): DayTotals {
208  return {
209    jobs: day.jobs + (change.jobs ?? 0),
210    opusRequests: day.opusRequests + (change.opusRequests ?? 0),
211    opusUnits: day.opusUnits + (change.opusUnits ?? 0),
212    workerUnits: day.workerUnits + (change.workerUnits ?? 0),
213    relayCalls: day.relayCalls + (change.relayCalls ?? 0),
214  }
215}
216
217/** What the band shows. */
218export type Band =
219  | { kind: 'hidden' }
220  | { kind: 'advice'; job: Job }
221  | { kind: 'running'; job: Job; count: number }
222  | { kind: 'long'; job: Job }
223  | { kind: 'finished'; job: Job }
224
225/**
226 * Pick the one thing worth a line, most urgent first:
227 *   long      a job has been running for 15 minutes or more
228 *   advice    a small job started less than a minute ago
229 *   running   a job is in progress
230 *   finished  a job ended in the last 10 minutes
231 */
232export function bandFor(jobs: readonly Job[], now: number): Band {
233  const running = jobs.filter(job => job.status === 'running')
234  const newest = running.at(-1)
235  if (newest) {
236    const oldest = running[0]
237    if (now - oldest.startedAt >= LONG_RUNNING_MS) {
238      return { kind: 'long', job: oldest }
239    }
240    if (newest.small && now - newest.startedAt < ADVICE_MS) {
241      return { kind: 'advice', job: newest }
242    }
243
244    return { kind: 'running', job: newest, count: running.length }
245  }
246
247  const finished = jobs
248    .filter(job => job.finishedAt !== null && now - job.finishedAt < FINISHED_SHOWN_MS)
249    .at(-1)
250
251  return finished ? { kind: 'finished', job: finished } : { kind: 'hidden' }
252}
253
254// ---------------------------------------------------------------------------
255// The pets: one small sprite per job in the band, with a caption.
256// ---------------------------------------------------------------------------
257
258/** How often the pets' legs move while a job runs. */
259export const PET_FRAME_MS = 100
260
261/** The caption for a relay job: "codex:implement", or "codex:run" without a lane. */
262export function relayLabel(skill: string, lane: string | null): string {
263  return `${skill}:${lane ?? 'run'}`
264}
265
266/**
267 * The caption for a subagent: "Explore/haiku". The model is the family only; a subagent
268 * that inherits the main model shows "inherit" until its spawn event names the model.
269 */
270export function subagentLabel(subagentType: string | undefined, model: string | null | undefined): string {
271  const family = model ? model.replace(/^claude-/, '').split('-')[0] : 'inherit'
272
273  return `${subagentType ?? 'general-purpose'}/${family}`
274}
275
276/** Which pet a job gets: one design per model or worker. */
277export type PetKind = 'opus' | 'sonnet' | 'haiku' | 'codex' | 'agy' | 'claude'
278
279/**
280 * The pet for a job, from its caption, worker and model. The relays come first, so a
281 * Codex rescue run by a Sonnet forwarder is still Codex; anything unknown is plain Claude.
282 */
283export function petKind(job: Job): PetKind {
284  const text = `${job.label ?? ''} ${job.worker} ${job.model ?? ''}`.toLowerCase()
285  for (const kind of ['agy', 'codex', 'haiku', 'sonnet', 'opus'] as const) {
286    if (text.includes(kind)) {
287      return kind
288    }
289  }
290
291  return 'claude'
292}
293
294/**
295 * The jobs that get a pet: every running job, and each job that finished since the
296 * user's last prompt. Older finished jobs stay in the pane, just not in the band.
297 */
298export function bandJobs(jobs: readonly Job[], clearedAt: number): Job[] {
299  return jobs.filter(
300    job => job.status === 'running' || (job.finishedAt !== null && job.finishedAt >= clearedAt),
301  )
302}
303
304/**
305 * One pet design, as square pixels: '#' is the body, '.' is empty (the eyes are empty
306 * pixels), any other letter takes its colour from the palette. The body is one colour,
307 * or a list of colours, one per column (agy's rainbow). `work` is the animation the pet
308 * plays while it works, one pixel grid per step, each as wide as `pixels`.
309 */
310type PetDesign = {
311  pixels: readonly string[]
312  body: string | readonly string[]
313  palette: Readonly<Record<string, string>>
314  work: readonly (readonly string[])[]
315}
316
317const LEGS = '.#.#..#.#.'
318const CLAWD = ['.########.', '.#.####.#.', '##.####.##', '##########', LEGS, LEGS]
319
320/** Clawd, how each model dresses it up, and the job it acts out. */
321export const PET_DESIGNS: Readonly<Record<PetKind, PetDesign>> = {
322  // A gold monocle around the right eye, its chain hanging down. Works: the lens glints.
323  opus: {
324    pixels: ['.#####ggg.', '.#.###g.g.', '##.###g.g#', '######ggg#', '.#.#..#.#g', LEGS],
325    body: '#d97757',
326    palette: { g: '#e5c07b', w: '#ffffff' },
327    work: [
328      ['.#####ggg.', '.#.###g.g.', '##.###g.g#', '######ggg#', '.#.#..#.#g', LEGS],
329      ['.#####ggg.', '.#.###gwg.', '##.###g.g#', '######ggg#', '.#.#..#.#g', LEGS],
330    ],
331  },
332  // Holding a hammer: grey head, wooden handle. Works: swings it down and back up.
333  sonnet: {
334    pixels: ['.########.HHH', '.#.####.#..h.', '##.####.##.h.', '###########h.', '.#.#..#.#..h.', '.#.#..#.#....'],
335    body: '#61afef',
336    palette: { H: '#abb2bf', h: '#a0703c' },
337    work: [
338      ['.########.HHH', '.#.####.#..h.', '##.####.##.h.', '###########h.', '.#.#..#.#..h.', '.#.#..#.#....'],
339      ['.########....', '.#.####.#...H', '##.####.##hhH', '##########..H', '.#.#..#.#....', '.#.#..#.#....'],
340    ],
341  },
342  // Smaller: two rows instead of three. Works: waves its arms.
343  haiku: {
344    pixels: ['.######.', '##.##.##', '.######.', '.#.##.#.'],
345    body: '#ff87d7',
346    palette: {},
347    work: [
348      ['.######.', '##.##.##', '.######.', '.#.##.#.'],
349      ['########', '.#.##.#.', '.######.', '.#.##.#.'],
350    ],
351  },
352  // Winking: the left eye a closed slit. Works: types, one arm up, then the other.
353  codex: {
354    pixels: ['.########.', '.######.#.', '##..###.##', '##########', LEGS, LEGS],
355    body: '#c678dd',
356    palette: {},
357    work: [
358      ['.########.', '.######.#.', '##..###.##', '##########', LEGS, LEGS],
359      ['.########.', '#######.#.', '##..###.##', '.#########', LEGS, LEGS],
360      ['.########.', '.######.#.', '##..###.##', '##########', LEGS, LEGS],
361      ['.########.', '.######.##', '##..###.##', '#########.', LEGS, LEGS],
362    ],
363  },
364  // A rainbow body. Works: the colours slide along it (see petRows).
365  agy: {
366    pixels: CLAWD,
367    body: ['#e06c75', '#e5a54b', '#e5c07b', '#98c379', '#56b6c2', '#61afef', '#7a7fe8', '#c678dd', '#e06c9f', '#e06c75'],
368    palette: {},
369    work: [CLAWD],
370  },
371  // Plain Clawd. Works: looks left, then right.
372  claude: {
373    pixels: CLAWD,
374    body: '#d97757',
375    palette: {},
376    work: [
377      CLAWD,
378      ['.########.', '.#.###.##.', '##.###.###', '##########', LEGS, LEGS],
379      CLAWD,
380      ['.########.', '.##.###.#.', '###.###.##', '##########', LEGS, LEGS],
381    ],
382  },
383}
384
385/** How many cells a running pet walks across, and how long each part of its loop takes. */
386export const PET_TRACK = 6
387/** Frames (of PET_FRAME_MS) per cell walked: one cell every 200 ms. */
388const WALK_FRAMES = 2
389/** Frames spent working at each end of the track: two seconds. */
390const WORK_FRAMES = 20
391/** Frames per step of the work animation. */
392const WORK_STEP_FRAMES = 3
393/** One loop: walk right, work, walk left, work. */
394export const PET_LOOP_FRAMES = 2 * (PET_TRACK * WALK_FRAMES + WORK_FRAMES)
395
396/**
397 * Where a pet is and what it is doing. `offset` is its distance from the left end of the
398 * track, in cells; `step` counts its leg steps while walking, its work steps while working.
399 */
400export type PetPose = { offset: number; walking: boolean; working: boolean; step: number }
401
402/** A number from the job's id, so pets that start together do not move in lockstep. */
403function loopStart(id: string): number {
404  let sum = 0
405  for (const char of id) {
406    sum = (sum * 31 + char.charCodeAt(0)) % PET_LOOP_FRAMES
407  }
408
409  return sum
410}
411
412/**
413 * The pet's pose at a frame. A running pet loops: walk right, work, walk left, work.
414 * Any other pet stands still in the middle of the track.
415 */
416export function petPose(job: Job, frame: number): PetPose {
417  if (job.status !== 'running') {
418    return { offset: PET_TRACK / 2, walking: false, working: false, step: 0 }
419  }
420  const walk = PET_TRACK * WALK_FRAMES
421  let t = (frame + loopStart(job.id)) % PET_LOOP_FRAMES
422  if (t < walk) {
423    return { offset: Math.floor(t / WALK_FRAMES), walking: true, working: false, step: Math.floor(t / WALK_FRAMES) }
424  }
425  t -= walk
426  if (t < WORK_FRAMES) {
427    return { offset: PET_TRACK, walking: false, working: true, step: Math.floor(t / WORK_STEP_FRAMES) }
428  }
429  t -= WORK_FRAMES
430  if (t < walk) {
431    const cells = Math.floor(t / WALK_FRAMES)
432    return { offset: PET_TRACK - cells, walking: true, working: false, step: cells }
433  }
434  t -= walk
435
436  return { offset: 0, walking: false, working: true, step: Math.floor(t / WORK_STEP_FRAMES) }
437}
438
439/** A run of cells drawn in one Text: same colour, same background. */
440export type PetRun = { text: string; color?: string; backgroundColor?: string }
441
442/** Mid-step: the front leg of each pair lifted, by clearing every other foot pixel. */
443function stepping(pixels: readonly string[]): string[] {
444  const rows = [...pixels]
445  let foot = 0
446  rows[rows.length - 1] = [...(rows.at(-1) ?? '')]
447    .map(pixel => (pixel !== '.' && foot++ % 2 === 0 ? '.' : pixel))
448    .join('')
449
450  return rows
451}
452
453/** Add a run to a row, joining it to the last one when their colours match. */
454function addRun(runs: PetRun[], run: PetRun) {
455  const last = runs.at(-1)
456  if (last && last.color === run.color && last.backgroundColor === run.backgroundColor) {
457    last.text += run.text
458  } else {
459    runs.push({ ...run })
460  }
461}
462
463/** One pixel's colour, or null where the pet is not (its eyes, and the track around it). */
464export type PetGrid = (string | null)[][]
465
466/**
467 * The pet at a frame as a grid of pixel colours, placed on its track: as wide as the pet
468 * plus PET_TRACK, as tall as its design. Both renderers draw from this, the terminal's
469 * text (petRows) and the desktop's SVG (petSvg), so they always show the same pet.
470 * A failed job's pet is all 'error' (the theme's red).
471 */
472export function petGrid(job: Job, frame: number): PetGrid {
473  const design = PET_DESIGNS[petKind(job)]
474  const pose = petPose(job, frame)
475  let pixels: readonly string[]
476  if (pose.walking) {
477    pixels = pose.step % 2 === 1 ? stepping(design.pixels) : design.pixels
478  } else if (pose.working) {
479    pixels = design.work[pose.step % design.work.length] ?? design.pixels
480  } else {
481    pixels = design.pixels
482  }
483  // agy's rainbow slides one column per work step.
484  const slide = pose.working ? pose.step : 0
485
486  const colourOf = (pixel: string, column: number): string | null => {
487    if (pixel === '.') {
488      return null
489    }
490    if (job.status === 'failed') {
491      return 'error'
492    }
493    if (pixel !== '#') {
494      return design.palette[pixel] ?? null
495    }
496    if (typeof design.body === 'string') {
497      return design.body
498    }
499
500    return design.body[(column + slide) % design.body.length] ?? null
501  }
502
503  return pixels.map(row => [
504    ...Array<null>(pose.offset).fill(null),
505    ...[...row].map((pixel, column) => colourOf(pixel, column)),
506    ...Array<null>(PET_TRACK - pose.offset).fill(null),
507  ])
508}
509
510/**
511 * The pet's text rows at a frame, for the terminal. Each text cell holds two pixels,
512 * one above the other: ▀ the top, ▄ the bottom, █ both; when both are filled in
513 * different colours the cell is ▀ in the top colour on a background of the bottom
514 * colour. Cells next to each other with the same colours are joined into one run.
515 */
516export function petRows(job: Job, frame: number): PetRun[][] {
517  const grid = petGrid(job, frame)
518  const width = grid[0]?.length ?? 0
519  const rows: PetRun[][] = []
520  for (let row = 0; row < grid.length; row += 2) {
521    const runs: PetRun[] = []
522    for (let column = 0; column < width; column++) {
523      const top = grid[row]?.[column] ?? null
524      const bottom = grid[row + 1]?.[column] ?? null // an odd last row has no pixel below
525      if (top && bottom) {
526        addRun(runs, top === bottom ? { text: '█', color: top } : { text: '▀', color: top, backgroundColor: bottom })
527      } else if (top) {
528        addRun(runs, { text: '▀', color: top })
529      } else if (bottom) {
530        addRun(runs, { text: '▄', color: bottom })
531      } else {
532        addRun(runs, { text: ' ' })
533      }
534    }
535    rows.push(runs)
536  }
537
538  return rows
539}
540
541/** How big one pet pixel is on the desktop, in CSS pixels. */
542export const PET_PIXEL_PX = 4
543/** The SVG has no theme: the red a failed pet is drawn in there. */
544const SVG_ERROR = '#e06c75'
545
546/**
547 * The pet at a frame as an SVG, for the desktop, which draws text in its own font and
548 * so cannot show half-block pixel art: one square per pixel, at PET_PIXEL_PX each.
549 * A finished pet is drawn faded, as the terminal dims it.
550 */
551export function petSvg(job: Job, frame: number): { source: string; width: number; height: number } {
552  const grid = petGrid(job, frame)
553  const width = (grid[0]?.length ?? 0) * PET_PIXEL_PX
554  const height = grid.length * PET_PIXEL_PX
555  const squares: string[] = []
556  grid.forEach((row, y) =>
557    row.forEach((colour, x) => {
558      if (colour) {
559        const fill = colour === 'error' ? SVG_ERROR : colour
560        squares.push(
561          `<rect x="${x * PET_PIXEL_PX}" y="${y * PET_PIXEL_PX}" width="${PET_PIXEL_PX}" height="${PET_PIXEL_PX}" fill="${fill}"/>`,
562        )
563      }
564    }),
565  )
566  const faded = job.status === 'done' || job.status === 'stopped' ? ' opacity="0.45"' : ''
567  const source =
568    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" ` +
569    `viewBox="0 0 ${width} ${height}" shape-rendering="crispEdges"><g${faded}>${squares.join('')}</g></svg>`
570
571  return { source, width, height }
572}
573
574/** The mark after a pet's caption: what state the job is in. */
575export function petMark(job: Job): string {
576  if (job.status === 'running') {
577    return job.background ? '◌' : '…'
578  }
579
580  return { done: '✓', failed: '✗', stopped: '■' }[job.status]
581}
582
583// ---------------------------------------------------------------------------
584// The delegation policy this plugin carries, so nobody has to copy it into CLAUDE.md.
585// ---------------------------------------------------------------------------
586
587/** Added to every session's system prompt by the prompt.compose hook. */
588export const DELEGATION_POLICY = `# Delegation policy (from the delegation plugin)
589
590Delegate only where it pays. Measured on real tasks of 1 to 6 files, each done three ways:
591Opus alone passed every task and was fastest; Opus with a Sonnet subagent cost about a
592third more on the Claude side and failed once; Opus with Codex cost about a tenth less on
593the Claude side but took two to three times as long and failed once.
594
595Why: a session carries a large context before any work, and every main-model request
596re-reads it. Delegating saves only when it removes main-model requests; briefing, waiting
597and reviewing usually add about as many as they remove.
598
599Default: do the work yourself. Delegate only when at least one holds:
6001. The work is large and separable (many files, or a long run-and-fix loop) and has an
601   acceptance check the worker can run itself.
6022. The user's Claude limit is the constraint and time is not: use Codex.
6033. The user explicitly asks for delegation.
6044. It is an independent, read-only review or second opinion.
6055. It is fast, read-only exploration (sweeping the codebase, "where is X", "how does Y work")
606   that would otherwise read many files into your own context: ask agy on its research lane
607   and spot-check the key file and line claims, since fast models are less careful.
608
609Do not delegate changes to one or two files, quick fixes, or work you will have to re-read
610in full to review. Do not hand implementation to Sonnet subagents.
611
612When you do delegate: write one tight brief with the acceptance check and the exact files
613the worker may change (workers have broken shared test fixtures); run Codex relays in the
614foreground when nobody will resume the session; keep the review to reading the diff and
615running the tests.
616
617When the user says "delegate", "hand this over", "hand it off" or names a worker (Codex,
618agy, Sonnet), treat it as a request to delegate, even without a slash command.
619
620This plugin ships the skills codex-delegate, agy-delegate, claude-delegate, delegate-setup,
621gpt-5-4-prompting and codex-result-handling; the commands /delegate, /explore, /delegate-setup,
622/delegate-confirm and /delegations; and for Codex and for agy the same seven commands: rescue (hand over a task),
623review, adversarial-review, status, result, cancel and setup (/codex-review, /agy-rescue, ...).
624It refuses a delegation whose brief names only one or two files, unless the user asked for
625delegation or the delegation is read-only. With /delegate-confirm on, the user approves each
626delegation in a dialog before it starts; if they cancel, do not retry it.`
627
628/** Does the user's own message ask for delegation? Then a small delegation is allowed. */
629export function userAskedToDelegate(message: string): boolean {
630  return (
631    /\b(delegat\w*|codex|sonnet|haiku|subagents?|sub-agents?|agy|antigravity|luna|terra|sol)\b/i.test(message) ||
632    /\bhand(?:ing|ed)?[\s-]*(?:(?:it|this|that|them)\s+)?(?:over|off)\b|\bhandover\b/i.test(message)
633  )
634}
635
636/** Read-only work (exploring, reviewing, second opinions) is never blocked. */
637export function isReadOnly(options: { subagentType?: string; command?: string }): boolean {
638  if (options.subagentType && /^(explore|plan|claude-code-guide)$/i.test(options.subagentType)) {
639    return true
640  }
641  const command = options.command ?? ''
642
643  return /--read-only\b|--sandbox\s+read-only|--lane\s+(review|deep-review|explore|second-opinion|third-opinion|research)\b/.test(
644    command,
645  )
646}
647
648/** The reason given back to Claude when a small delegation is refused. */
649export function refusalReason(files: number): string {
650  return (
651    `Delegation refused by the delegation plugin: the brief names only ${files} file(s). ` +
652    'For changes this small, doing the work yourself was cheaper and faster in measured runs. ' +
653    'Do it directly. (Delegation is allowed when the user asks for it, or for read-only work.)'
654  )
655}
656
657// ---------------------------------------------------------------------------
658// The official Codex plugin (openai-codex): /codex:rescue and codex-companion.mjs.
659//
660// /codex:rescue starts a "codex:codex-rescue" subagent, a thin forwarder that runs one
661// shell command: `node .../codex-companion.mjs task [--background] [--write] ... "<task>"`.
662// The companion can also be called directly (review, adversarial-review). A background
663// task prints "<title> started in the background as <job-id>.", and its worker process
664// carries `--job-id <job-id>` on its command line.
665// ---------------------------------------------------------------------------
666
667/** One codex-companion.mjs command. */
668export type CompanionCall = {
669  subcommand: string
670  background: boolean
671  /** --write: Codex may edit files. Without it the companion runs Codex read-only. */
672  write: boolean
673  model: string | null
674  /** The task text: the last long quoted argument. */
675  text: string
676}
677
678/** Companion subcommands that do work; status, result, cancel and setup are bookkeeping. */
679export const COMPANION_WORK = new Set(['task', 'review', 'adversarial-review'])
680
681/** The subagent type /codex:rescue uses. */
682export function isCodexRescue(subagentType: string | undefined): boolean {
683  return subagentType === 'codex:codex-rescue'
684}
685
686/** The last quoted argument long enough to be a task description. */
687function lastQuoted(command: string): string {
688  const quoted = [...command.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)]
689    .map(match => match[1] ?? match[2])
690    .filter(text => text.length > 15 && !/codex-companion\.mjs/.test(text))
691
692  return quoted.at(-1) ?? ''
693}
694
695/** Recognise a codex-companion.mjs call in a shell command, or null. */
696export function parseCompanion(fullCommand: string): CompanionCall | null {
697  const command = runPart(fullCommand)
698  const match = command.match(/codex-companion\.mjs["']?\s+([a-z-]+)/)
699  if (!match) {
700    return null
701  }
702
703  return {
704    subcommand: match[1],
705    background: /--background\b/.test(command),
706    write: /--write\b/.test(command),
707    model: flag(command, 'model'),
708    text: lastQuoted(command),
709  }
710}
711
712// ---- Confirm before a delegation starts (off unless /delegate-confirm on) ------------------
713//
714// Some models have a small allowance (Sol), and pricier ones may come. With confirmation on,
715// every delegation (Codex, agy, a Claude subagent, any relay) first shows what is about to
716// be sent and waits for a yes.
717
718/** A delegation about to start, as the confirmation question describes it. */
719export type PendingRun = { worker: string; model: string | null; lane: string | null; brief: string }
720
721/** The question shown before a delegation: worker, model, lane, and how much is being sent. */
722export function confirmQuestion(run: PendingRun): string {
723  const model = run.model ? ` on ${run.model}` : ' on its default model'
724  const lane = run.lane ? `, lane ${run.lane}` : ''
725  const files = filesNamed(run.brief)
726  const size = run.brief
727    ? `The brief is ${run.brief.length.toLocaleString('en-US')} characters and names ${files} file${files === 1 ? '' : 's'}.`
728    : 'It reviews the current changes; no brief text.'
729
730  return `Claude is about to start a ${run.worker} run${model}${lane}. ${size} Run it?`
731}
732
733/** /delegate-confirm's argument: true for on, false for off, null to show the setting, or 'invalid'. */
734export function parseConfirmArg(args: string): boolean | null | 'invalid' {
735  const word = args.trim().toLowerCase()
736  if (word === '') {
737    return null
738  }
739  if (word === 'on') {
740    return true
741  }
742  if (word === 'off') {
743    return false
744  }
745
746  return 'invalid'
747}
748
749/** The job id a background companion task reports, or null. */
750export function backgroundCompanionJobId(output: string): string | null {
751  return output.match(/started in the background as ([\w.-]+?)\.(?:\s|$|\\n|")/)?.[1] ?? null
752}
753
754/** A rescue request that only asks for diagnosis, review or research runs Codex read-only. */
755export function isReadOnlyRequest(text: string): boolean {
756  return (
757    /\b(read-only|review|diagnos\w*|investigat\w*|research)\b/i.test(text) &&
758    !/\b(fix|implement|change|write)\b/i.test(text)
759  )
760}
761
762// ---------------------------------------------------------------------------
763// Processes, on Windows and on macOS/Linux.
764// ---------------------------------------------------------------------------
765
766export type Platform = 'windows' | 'unix'
767
768/**
769 * Decide the platform from `uname -s`. On Windows `uname` is usually missing (null); when
770 * Git's tools provide it, it answers MINGW/MSYS/CYGWIN, which is still Windows.
771 */
772export function platformFromUname(output: string | null): Platform {
773  return output && !/MINGW|MSYS|CYGWIN|Windows/i.test(output) ? 'unix' : 'windows'
774}
775
776/** The command that prints every running process's full command line. */
777export function listProcessesArgv(platform: Platform): string[] {
778  return platform === 'windows'
779    ? ['powershell', '-NoProfile', '-Command', 'Get-CimInstance Win32_Process | ForEach-Object CommandLine']
780    : ['ps', '-axo', 'command']
781}
782
783/** Characters that mean something in a regular expression, escaped so pkill matches literally. */
784function escapeForPattern(text: string): string {
785  return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
786}
787
788/**
789 * The command that ends every process whose command line contains `marker`: with its
790 * child processes on Windows (taskkill /T); on macOS/Linux, pkill on the matching ones.
791 */
792export function killMatchingArgv(platform: Platform, marker: string): string[] {
793  if (platform === 'unix') {
794    return ['pkill', '-f', escapeForPattern(marker)]
795  }
796  // PowerShell single-quoted strings escape a quote by doubling it.
797  const literal = marker.replace(/'/g, "''")
798
799  return [
800    'powershell',
801    '-NoProfile',
802    '-Command',
803    `Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine.Contains('${literal}') -and $_.CommandLine -notmatch 'Get-CimInstance' } | ForEach-Object { taskkill /PID $_.ProcessId /T /F | Out-Null }`,
804  ]
805}
806
807// ---------------------------------------------------------------------------
808// The lane map from delegate-setup, for the system prompt.
809// ---------------------------------------------------------------------------
810
811/** One lane as delegate-setup writes it in ~/.config/delegate-skills/config.json. */
812export type Lane = { implementer?: string; model?: string; effort?: string; variant?: string; readOnly?: boolean }
813
814/**
815 * The lane map as a few lines for the system prompt, grouped by implementer:
816 *   - codex (codex-delegate): implement -> gpt-6-luna; deep-review -> gpt-6.1-sol, read-only
817 * Empty when no lanes are configured; /delegate-setup creates them.
818 */
819export function laneMapText(config: unknown): string {
820  const lanes = (config as { lanes?: Record<string, Lane> } | null)?.lanes
821  if (!lanes || Object.keys(lanes).length === 0) {
822    return ''
823  }
824  const byImplementer = new Map<string, string[]>()
825  for (const [name, lane] of Object.entries(lanes)) {
826    if (!lane.implementer) {
827      continue
828    }
829    const dials = [lane.model, lane.effort && `effort ${lane.effort}`, lane.variant && `variant ${lane.variant}`, lane.readOnly && 'read-only']
830      .filter(Boolean)
831      .join(', ')
832    const entries = byImplementer.get(lane.implementer) ?? []
833    entries.push(dials ? `${name} -> ${dials}` : name)
834    byImplementer.set(lane.implementer, entries)
835  }
836  const lines = [...byImplementer].map(
837    ([implementer, entries]) => `- ${implementer} (${implementer}-delegate): ${entries.join('; ')}`,
838  )
839
840  return [
841    '# Delegation lanes (from delegate-setup)',
842    'Pass `--lane <name>` to the matching relay; an explicit `--model` overrides the lane.',
843    ...lines,
844  ].join('\n')
845}
846
847// ---------------------------------------------------------------------------
848// The bundled worker commands: /codex-* (the official Codex plugin's, vendored under
849// codex/) and /agy-* (the same commands for agy, built on the agy relay).
850// ---------------------------------------------------------------------------
851
852export type Worker = 'codex' | 'agy'
853
854/** The seven commands each worker gets, in the order the typeahead lists them. */
855export const WORKER_ACTIONS = ['rescue', 'review', 'adversarial-review', 'status', 'result', 'cancel', 'setup'] as const
856export type WorkerAction = (typeof WORKER_ACTIONS)[number]
857
858/** One line each for the typeahead. */
859export const ACTION_DESCRIPTIONS: Record<WorkerAction, string> = {
860  rescue: 'Hand a task to {worker}',
861  review: 'Read-only {worker} review of your local changes',
862  'adversarial-review': '{worker} review that challenges the design and its assumptions',
863  status: 'Show {worker} jobs, running and recent',
864  result: "Show a finished {worker} job's report",
865  cancel: 'Cancel a running {worker} job',
866  setup: 'Check that {worker} is installed and signed in',
867}
868
869/**
870 * The lane each model-running command reads its model from, and the model used when that
871 * lane is not configured. An explicit --model on the command beats both.
872 */
873export const COMMAND_MODELS: Record<string, { lane: string; model: string }> = {
874  'codex-rescue': { lane: 'implement', model: 'gpt-6-luna' },
875  'codex-review': { lane: 'review', model: 'gpt-6-luna' },
876  'codex-adversarial-review': { lane: 'deep-review', model: 'gpt-6.1-sol' },
877  'agy-rescue': { lane: 'agy-implement', model: 'gemini-3.8-flash-high' },
878  'agy-review': { lane: 'agy-review', model: 'gemini-3.8-flash-high' },
879  'agy-adversarial-review': { lane: 'third-opinion', model: 'gemini-3.1-pro-high' },
880}
881
882/** The model a command runs: --model if given, else its lane's model, else the default. */
883export function modelFor(command: string, requested: string | null, lanes: Record<string, Lane>): string {
884  const defaults = COMMAND_MODELS[command]
885
886  return requested ?? lanes[defaults.lane]?.model ?? defaults.model
887}
888
889/** A command's arguments with the run flags taken out; `text` is what is left. */
890export type CommandArgs = { background: boolean; model: string | null; base: string | null; text: string }
891
892export function splitArgs(args: string): CommandArgs {
893  let text = args
894  const take = (name: string): string | null => {
895    const value = flag(text, name)
896    text = text.replace(new RegExp(`--${name}\\s+(?:"[^"]+"|'[^']+'|\\S+)`), '')
897
898    return value
899  }
900  const model = take('model')
901  const base = take('base')
902  const background = /--background\b/.test(text)
903  text = text.replace(/--(background|wait)\b/g, '')
904
905  return { background, model, base, text: text.replace(/\s+/g, ' ').trim() }
906}
907
908/** Codex commands pass the arguments on as typed; this adds `--model` when it is missing. */
909export function withModel(args: string, model: string): string {
910  return /--model\s/.test(args) ? args : `--model ${model} ${args}`.trim()
911}
912
913/**
914 * A command file turned into a prompt: the front matter dropped, and each `${KEY}` (and the
915 * Claude Code `$ARGUMENTS`) replaced. Unknown placeholders are left as they are.
916 */
917export function fillTemplate(markdown: string, values: Record<string, string>): string {
918  const body = markdown.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '').trim()
919
920  return body
921    .replace(/\$\{([A-Z_]+)\}/g, (whole, key: string) => values[key] ?? whole)
922    .replace(/\$ARGUMENTS/g, values.ARGUMENTS ?? '')
923}
924
925/** A new agy job id from the clock, short enough to type: agy-<base 36 time>. */
926export function newAgyJobId(now: number): string {
927  return `agy-${now.toString(36)}`
928}
929
930/** What agy-status shows for a job, from its result.json and whether its relay still runs. */
931// "no result": the relay is not running and wrote no result: not started yet, or killed.
932export type AgyJobState = 'running' | 'done' | 'failed' | 'no result'
933
934export function agyJobState(result: { status?: string } | null, alive: boolean): AgyJobState {
935  // A live relay wins: a rerun in the same folder leaves the last run's result.json behind.
936  if (alive) {
937    return 'running'
938  }
939  if (result) {
940    return result.status === 'completed' ? 'done' : 'failed'
941  }
942
943  return 'no result'
944}
945
946/** One agy job as its job.json records it. */
947export type AgyJob = { id: string; kind: string; title: string; model: string; startedAt: number }
948
949/** The agy jobs as a Markdown table, newest first. */
950export function agyStatusTable(rows: Array<AgyJob & { state: AgyJobState }>, now: number): string {
951  if (rows.length === 0) {
952    return 'No agy jobs yet. Start one with /agy-rescue or /agy-review.'
953  }
954  const lines = rows.map(
955    row =>
956      `| ${row.id} | ${row.kind} | ${row.state} | ${row.model} | ${formatElapsed(now - row.startedAt)} ago | ${row.title} |`,
957  )
958
959  return ['| Job | Kind | State | Model | Started | Task |', '|---|---|---|---|---|---|', ...lines].join('\n')
960}
961
types/index.d.ts 71 lines
1// The values this mod keeps in the session's state, and their shapes.
2
3/** One piece of delegated work: a Claude subagent, or a relay call to Codex, agy, etc. */
4export type Job = {
5  /** The id of the tool call that started it. */
6  id: string
7  /** Who does the work: "Sonnet", "Haiku", "Opus", "Codex", "agy", "Claude CLI", ... */
8  worker: string
9  /** The model, when known ("gpt-6-luna", "claude-sonnet-5-5"), or the lane ("lane implement"). */
10  model: string | null
11  /** A short name for the task, from the delegation's description or brief. */
12  title: string
13  /**
14   * The caption under the job's pet in the band: "skill:lane" for a relay ("codex:implement"),
15   * "type/model" for a subagent ("Explore/haiku"). Also picks the pet's colour.
16   */
17  label: string
18  startedAt: number
19  finishedAt: number | null
20  status: 'running' | 'done' | 'failed' | 'stopped'
21  /** Started in the background, so finishing is noticed later rather than right away. */
22  background: boolean
23  /** The brief names one or two files at most: the kind of task solo did better on. */
24  small: boolean
25  /**
26   * Text that appears in the command line of the job's process while it runs: the brief
27   * path for relay.mjs jobs, the job id for background Codex plugin jobs. Used to tell
28   * whether the job is still alive and to stop it. Null when the mod cannot stop it.
29   */
30  aliveMarker: string | null
31  /** For Claude subagents: the subagent's id, which its requests and completion carry. */
32  agentId: string | null
33  /** Opus requests made, and their cost units, while this job was open. */
34  opusRequests: number
35  opusUnits: number
36  /** The worker's own cost units (Claude subagents only; Codex reports no tokens here). */
37  workerUnits: number
38  /** Files the worker changed, when the relay reported it. */
39  filesChanged: number | null
40  /** Still counting Opus requests: true until the turn in which the job finished ends. */
41  isTracking: boolean
42}
43
44/** Delegation totals for one calendar day, across all sessions. */
45export type DayTotals = {
46  jobs: number
47  opusRequests: number
48  opusUnits: number
49  workerUnits: number
50  relayCalls: number
51}
52
53declare module 'claude-code' {
54  interface PluginState {
55    delegation: {
56      /** Every delegation in this session, oldest first. */
57      jobs: Job[]
58      /** Today's totals, shared by all sessions through the store. */
59      today: DayTotals
60      /** The current time, refreshed on a timer so elapsed times redraw. */
61      now: number
62      /** When the user last sent a prompt: the band shows no job that finished before it. */
63      bandClearedAt: number
64      /** True after the band's Hide button, until the next prompt. */
65      bandHidden: boolean
66      /** The pets' animation frame, counted up on a fast timer while a job runs. */
67      frame: number
68    }
69  }
70}
71