SLOPSHOPPER

opus-conductor

Opus 5.5 conducts a mission: plans sized tasks, delegates hard labor to Sonnet 5.5 workers and narrow jobs to Haiku 5.5 scouts at the reasoning effort each…

panebandguardtoaststatusprompt
v1.6.0no licenseupdated 2026-10-26okashiina/illa-mods/opus-conductor
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · opus-conductor
│ ┃ opus-conductor ✕ › fix the failing auth test and add an audit log call │ ┃ ◆ Opus Conductor │ ┃ No mission yet. Type /conduct, pick conduct ● opus-conductor: opus-conductor: tools did not register (TypeError: │ ┃ (opus-conductor), and describe what done ⏺ Read(src/auth.ts) │ ┃ looks like. Opus 5.5 plans it, Sonnet 5.5 ⎿ Read 6 lines │ ┃ workers build, Haiku 5.5 scouts look things ⏺ Update(src/auth.ts) │ ┃ up, and it all shows up here. ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ AGENTS 0 working · 0 done ⎿ 3 pass, 1 fail │ ┃ No agents launched yet. │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ [ Autopilot: on ] │ ✻ Worked for 42s · done 4:20 PM │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · opus-conductor
◆ Opus Conductor No mission yet. Type /conduct, pick conduct (opus-conductor), and describe what done looks like. Opus 5.5 plans it, Sonnet 5.5 workers build, Haiku 5.5 scouts look things up, and it all shows up here. AGENTS 0 working · 0 done No agents launched yet. [ Autopilot: on ]
README

opus-conductor

Opus 5.5 is the thinker, manager and integrator. Sonnet 5.5 workers do the hard labor, and Haiku 5.5 scouts do fast, narrow jobs. It's the SOL orchestrator idea (Sol → Opus, Luna → Sonnet) with a /goal-style live board.

Install

/plugin install opus-conductor --marketplace okashiina/illa-mods

On older Claude Code: /plugin marketplace add okashiina/illa-mods, then /plugin install opus-conductor@illa-mods. Restart or run /reload-plugins. Update later with claude plugin update opus-conductor@illa-mods.

Use

TypeDoes
/opus-conductor:conduct <what done looks like>Starts a mission. Opus plans sized tasks, picks a helper and a reasoning effort for each, delegates, then verifies and integrates.
/opus-conductor:conductOpens the live board.
/opus-conductor:conduct stop · auto on · auto off · clearStops the mission, toggles autopilot, or clears the board.
mission tool action hold (Opus calls it)Opus is waiting on something outside the session: a render, CI, a background command. Autopilot stays quiet until a task notification, you, or its timer wakes it.

In the desktop app, type /conduct and pick conduct (opus-conductor) from the menu.

  • Board: a progress ring, every agent with its model, its live activity and its self-reported %, and the task plan. There's also a band above the prompt (c opens the board) and a status line.
  • Who does what:
ModelRoleGets
Opus 5.5conductorArchitecture, design, diagnosis, security, integration, review.
Sonnet 5.5workerImplementation, refactors, tests, multi-step debugging, agentic coding.
Haiku 5.5scoutLookups, file and log sweeps, extraction, summaries, triage, running a check and reporting it, browser checks.

Haiku 5.5 costs $0.10 / $0.50 per MTok for prompts up to 100K tokens. It is strong at narrow work (OSWorld 72%) but well behind Sonnet on complex agentic coding (Terminal-Bench 4.0: 39% vs 71%), so it never gets design or hard coding. Its cyber safeguards also block pentest-style work.

  • Reasoning effort, picked per task by Opus: the Agent tool can't set effort per call, so there is one agent type per effort.
Effortopus-conductor:worker-* (Sonnet 5.5)opus-conductor:scout-* (Haiku 5.5)
lowmechanical edits from an exact specsingle lookups, greps, one value, one named check
mediumclear-brief implementation (the default for agentic coding)summaries, triage, extraction across several files
highnontrivial implementation, cross-module refactors, tricky tests, bounded debuggingcareful cross-checks, browser flows, costly-if-wrong sweeps
xhighhard multi-step debugging, long multi-file builds where a miss is costlynot offered

Opus starts workers at medium and scouts at low. It raises one level for each thing that makes a task harder: unfamiliar code, subtle invariants, many interacting files, a fix that must hold under tests. It lowers one level for repetitive work. Task size alone never raises effort. Plan tasks record their effort, and the board shows it on each task and agent. Opus's own effort is the session's setting.

  • Model steering during a mission:
  • Subagents with no model set run on Sonnet 5.5.
  • Explore agents run on Haiku 5.5.
  • Any older Haiku request is lifted to Haiku 5.5.
  • An explicit Opus or Sonnet choice is kept.
  • Autopilot: it nudges Opus to continue, at most 8 times, while tasks are open and no worker is running. Opus can pause it to ask you a question (wait) or to wait on the outside world (hold).
  • No nudge spam (1.5): autopilot never asks twice for nothing.
  • hold: Opus says what it waits on and, optionally, after how many minutes to check again. While work goes on (agents running, a background task, the outside job), the board says "cooking" with a spinner. Only a stall with nothing running says "standing by · 12m left".
  • Stall detection: a nudged turn that changed nothing on the board (no task moved, no agent started, no file written) puts the mission on hold for 5 min, doubling per stall in a row up to 30 min, instead of nudging again.
  • Background work: a turn in which Opus started a background command or a monitor is held too, since its notification wakes the session.
  • Waking: a task notification, a peer message, a scheduled trigger, or you typing resumes the mission at once. The timer wakes Opus once with "check whether it's ready; if not, hold again". The board has a "Resume now" button.
  • Your message also resets the stall count and the autopilot budget.
  • Live bars (1.6): each agent's bar moves with every tool call. Before its first report it shows an estimate from its tool calls (~14%), and after a report it creeps up until the next one. A task whose agent handed back counts 90% until Opus verifies it, and active plan segments fill with their agent's %.
  • Session model: run the session on Opus 5.5 for the intended split. If it isn't, the board shows a warning when Opus first hands off a task.

Develop

  • Run claude plugin validate . and claude plugin test . in this folder.
  • An installed copy is read from this folder. After editing, run /reload-plugins in a session to pick up the changes.
  • Develop risky changes on a copy with claude --plugin-dir <copy> so running sessions are untouched.
Source 3 files
hooks/register.tsx 770 lines
1// Opus Conductor: Opus 5.5 thinks, plans and integrates; Sonnet 5.5 workers do
2// the hard labor. Adapted from the SOL orchestrator skill (Sol -> Opus, Luna ->
3// Sonnet) with a /goal-style progress meter.
4// - /conduct <goal> (commands/conduct.md): hands Opus the conductor brief; the
5//   hook starts the mission board and opens the pane.
6// - The model gets mcp__opus-conductor__mission (the plan board) and the
7//   opus-conductor:worker agent type (Sonnet 5.5). Workers report their own %
8//   with mcp__opus-conductor__report.
9// - Pane: progress ring (desktop), mission bar, every agent with its model,
10//   what it's doing right now, its %, and the plan. A band above the prompt and
11//   a status line show the same in short.
12// - Autopilot: while the mission is unfinished and no worker is running, an
13//   ended turn is followed by a "continue" prompt (at most maxContinues times).
14//   It stays quiet while the mission holds: Opus called "hold" because it
15//   waits on something outside the session, a nudged turn changed nothing on
16//   the board (a stall), or Opus started a background task. A task
17//   notification, the person, or a fallback timer wakes it. The board calls a
18//   hold "cooking" while work goes on, and "standing by" only for a stall.
19
20import { atom, read, update } from 'claude-code'
21import type { Elements, EngineInterface, Register } from 'claude-code'
22
23import type { AgentRow, Mission, ConductorSettings, Task } from '../types'
24import {
25  BACKGROUND_HOLD,
26  HAIKU,
27  SCOUT,
28  SCOUT_EFFORTS,
29  SONNET,
30  WORKER,
31  agentPct,
32  WORKER_EFFORTS,
33  agentName,
34  applyAction,
35  clip,
36  continuation,
37  describeCall,
38  effortOf,
39  eta,
40  fingerprint,
41  holdExpired,
42  isStopWord,
43  isWriteTool,
44  minutes,
45  missionToolSpec,
46  newMission,
47  phase,
48  progress,
49  reportToolSpec,
50  scoutPrompt,
51  stallHold,
52  startsBackgroundWork,
53  steerModel,
54  taskFraction,
55  taskIdIn,
56  workerPrompt,
57} from './mission'
58
59const PLUGIN = 'opus-conductor'
60const PANE = 'opus-conductor'
61const RECENT_MS = 10 * 60000
62
63const missionAtom = atom({ plugin: 'opus-conductor', key: 'mission' } as const, null)
64const agentsAtom = atom({ plugin: 'opus-conductor', key: 'agents' } as const, [])
65const settingsAtom = atom({ plugin: 'opus-conductor', key: 'settings' } as const, { auto: true, maxContinues: 8 } as ConductorSettings)
66
67const WORKER_USE: Record<string, string> = {
68  low: 'mechanical edits from an exact spec, renames, formatting, boilerplate',
69  medium: 'clear-brief implementation and coordinated small changes (the default for agentic coding)',
70  high: 'nontrivial implementation, refactors across modules, tests with tricky cases, bounded debugging',
71  xhigh: 'hard multi-step debugging or long multi-file builds where a miss is costly',
72}
73
74const SCOUT_USE: Record<string, string> = {
75  low: 'single lookups, greps, pulling one value, running one named check',
76  medium: 'summaries, triage, extraction across several files or docs',
77  high: 'careful cross-checking, browser flows, sweeps where a wrong answer is costly',
78}
79
80const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
81
82/** a spinner frame that turns with the clock: the board ticks every second while cooking */
83function spin(now: number): string {
84  return SPIN[Math.floor(now / 1000) % SPIN.length] ?? '⠋'
85}
86
87const COLOR = { opus: '#D97757', sonnet: '#6A9BCC', haiku: '#3FB8AF', done: '#3FB950', wait: '#D29922', fail: '#F85149', track: '#8B949E' }
88
89type $ = EngineInterface
90type Kit = Elements[keyof Elements]
91
92function isLive(m: Mission | null): m is Mission {
93  return !!m && (m.status === 'running' || m.status === 'waiting' || m.status === 'holding')
94}
95
96async function sync($: $) {
97  const m = await read($, missionAtom)
98  const agents = await read($, agentsAtom)
99  const running = agents.filter(a => a.status === 'running').length
100  if (isLive(m)) {
101    const p = progress(m, agents)
102    const ph = phase(m, agents)
103    const word = ph === 'waiting' ? 'waiting on you' : ph === 'standby' ? 'standing by' : ph === 'planning' ? 'planning' : `cooking ${p.pct}%`
104    $.ui.status(`◆ conduct ${word}${running ? ` · ${running} agent${running > 1 ? 's' : ''}` : ''}`)
105  } else if (running) {
106    $.ui.status(`◆ ${running} agent${running > 1 ? 's' : ''} running`)
107  } else {
108    $.ui.status(undefined)
109  }
110}
111
112async function setMission($: $, fn: (m: Mission | null) => Mission | null) {
113  await update($, missionAtom, m => fn(m ?? null))
114  await sync($)
115}
116
117async function setAgents($: $, fn: (list: AgentRow[]) => AgentRow[]) {
118  await update($, agentsAtom, list => fn([...(list ?? [])]).slice(-40))
119  await sync($)
120}
121
122async function openPane($: $) {
123  await $.ui.open({ id: PANE, title: 'Opus Conductor' })
124}
125
126// the fallback timer of the current hold; a hot reload drops it, session.start re-arms it
127let holdTimer: { cancel: () => void } | null = null
128
129function dropHoldTimer() {
130  holdTimer?.cancel()
131  holdTimer = null
132}
133
134/** Arms the hold's timer: when it runs out and the hold still stands, Opus is woken once. */
135async function armHold($: $) {
136  dropHoldTimer()
137  const m = await read($, missionAtom)
138  if (!m || m.status !== 'holding' || !m.holdUntil) return
139  const now = await $.clock.now()
140  const until = m.holdUntil
141  holdTimer = $.clock.after(Math.max(0, until - now), async () => {
142    holdTimer = null
143    const cur = await read($, missionAtom)
144    if (!cur || cur.status !== 'holding' || cur.holdUntil !== until) return
145    // the wake counts as a nudge: a turn that again changes nothing holds longer, with no nudge between
146    const at = await $.clock.now()
147    const mark = fingerprint(cur, await read($, agentsAtom))
148    await setMission($, x => (x ? { ...x, status: 'running', holdUntil: 0, nudgedAt: at, mark, doing: 'hold ran out; checking' } : x))
149    void $.prompt.submit({ text: holdExpired(cur) })
150  })
151}
152
153/** Puts the mission on hold from the hook side, with a fallback timer. */
154async function hold($: $, now: number, ms: number, note: string, stalls: number) {
155  await setMission($, x => (x ? { ...x, status: 'holding', holdUntil: now + ms, note, stalls, nudgedAt: 0, pendingAt: 0, doing: stalls ? `standing by: ${note}` : `cooking: ${note}` } : x))
156  await armHold($)
157}
158
159export const register: Register = on => {
160  // Recomputed on every load: session.start registers them again.
161  let missionTool = `mcp__${PLUGIN}__mission`
162  let reportTool = `mcp__${PLUGIN}__report`
163  const workerType = `${PLUGIN}:${WORKER}`
164  const scoutType = `${PLUGIN}:${SCOUT}`
165  let warnedModel = false
166
167  on('session.start', async ($, e, next) => {
168    const saved = await $.store.get('settings').catch(() => undefined)
169    if (saved && typeof saved === 'object') await update($, settingsAtom, s => ({ ...s, ...(saved as Partial<ConductorSettings>) }))
170    try {
171      missionTool = (await $.tool.register(missionToolSpec('mission'))).tool
172      reportTool = (await $.tool.register(reportToolSpec('report'))).tool
173    } catch (err) {
174      $.ui.log(`opus-conductor: tools did not register (${String(err)})`)
175    }
176    // one agent type per (kind, effort): Opus picks the effort by picking the type
177    for (const effort of WORKER_EFFORTS) {
178      try {
179        await $.agent.register({
180          name: agentName('worker', effort),
181          description: `Sonnet 5.5 worker at ${effort} effort, for the Opus Conductor: ONE well-scoped outcome with a full delegation contract. Fits ${WORKER_USE[effort]}.`,
182          prompt: workerPrompt(reportTool),
183          model: SONNET,
184          effort,
185        })
186      } catch (err) {
187        $.ui.log(`opus-conductor: worker-${effort} did not register (${String(err)})`)
188      }
189    }
190    for (const effort of SCOUT_EFFORTS) {
191      try {
192        await $.agent.register({
193          name: agentName('scout', effort),
194          description: `Haiku 5.5 scout at ${effort} effort, for the Opus Conductor: ONE narrow job with a checkable answer. Fits ${SCOUT_USE[effort]}. Not for design, complex coding or security work.`,
195          prompt: scoutPrompt(reportTool),
196          model: HAIKU,
197          effort,
198        })
199      } catch (err) {
200        $.ui.log(`opus-conductor: scout-${effort} did not register (${String(err)})`)
201      }
202    }
203    // elapsed times, ETAs and the spinner move while nothing is written:
204    // every second while cooking, every 5 s otherwise
205    let ticks = 0
206    $.clock.every(1000, () => {
207      ticks++
208      void Promise.all([read($, missionAtom), read($, agentsAtom)]).then(([m, agents]) => {
209        if (isLive(m) && (phase(m, agents) === 'cooking' || ticks % 5 === 0)) $.ui.invalidate('ui.render')
210      })
211    })
212    await armHold($)
213    await sync($)
214
215    return next(e)
216  })
217
218  // ---------- the command ----------
219
220  // /conduct is the plugin's own markdown command (commands/conduct.md), so every
221  // surface lists it. Its body is the brief Opus reads; this hook adds the board,
222  // and answers the control words itself without starting a turn.
223  on('command.run', { command: ['conduct', 'opus-conductor:conduct'] }, async ($, e, next) => {
224    const args = e.args.trim()
225    const now = await $.clock.now()
226    const [key, value, ...rest] = args.toLowerCase().split(/\s+/)
227
228    if (!args) {
229      await openPane($)
230      return { text: 'Opus Conductor board opened.' }
231    }
232    if (isStopWord(args)) {
233      await setMission($, m => (isLive(m) ? { ...m, status: 'stopped', endedAt: now } : m))
234      return { text: 'Mission stopped. Running agents finish on their own.' }
235    }
236    if (key === 'auto' && (value === 'on' || value === 'off') && !rest.length) {
237      const saved = await update($, settingsAtom, s => ({ ...s, auto: value === 'on' }))
238      await $.store.set('settings', saved).catch(() => undefined)
239      return { text: `Autopilot ${value}.` }
240    }
241    if (key === 'clear' && !value) {
242      await setMission($, () => null)
243      await setAgents($, list => list.filter(a => a.status === 'running'))
244      return { text: 'Conductor board cleared.' }
245    }
246
247    await setMission($, () => newMission(args, now))
248    await setAgents($, list => list.filter(a => a.status === 'running'))
249    await openPane($)
250    return next(e)
251  })
252
253  on('prompt.submit', async ($, e, next) => {
254    const kind = e.origin.kind
255    if (kind === 'composer' || kind === 'bridge') {
256      // the person speaking resumes a waiting or held mission and refills the autopilot
257      await setMission($, m => (isLive(m) ? { ...m, status: 'running', continues: 0, stalls: 0, holdUntil: 0, nudgedAt: 0, pendingAt: 0 } : m))
258      dropHoldTimer()
259    } else if (kind !== 'plugin') {
260      // what Opus waited for arrived (a task notification, a peer, a schedule): the hold is over
261      const m = await read($, missionAtom)
262      if (isLive(m) && (m.status === 'holding' || m.pendingAt)) {
263        await setMission($, x => (x ? { ...x, status: x.status === 'holding' ? 'running' : x.status, holdUntil: 0, nudgedAt: 0, pendingAt: 0, doing: `woken by a ${kind}` } : x))
264        dropHoldTimer()
265      }
266    }
267    return next(e)
268  })
269
270  // ---------- tools: the board, worker reports, and what everyone is doing ----------
271
272  on('tool.call', async ($, e, next) => {
273    const now = await $.clock.now()
274    const input = e as unknown as Record<string, unknown>
275
276    if (e.tool === missionTool) {
277      let reply = ''
278      await setMission($, m => {
279        const first = clip((input.tasks as { title?: string }[] | undefined)?.[0]?.title ?? 'Mission', 120)
280        const action = String(input.action ?? '')
281        // a finished mission is history: a new plan is a new mission, more work reopens it
282        const base =
283          !m || m.status === 'stopped' || (m.status === 'done' && action === 'plan')
284            ? newMission(first, now)
285            : m.status === 'done' && (action === 'add' || action === 'start')
286              ? { ...m, status: 'running' as const, endedAt: 0, continues: 0 }
287              : m
288        const r = applyAction(base, input, now)
289        reply = r.text
290        return r.mission
291      })
292      const after = await read($, missionAtom)
293      if (after?.status === 'done') $.ui.toast('◆ Mission complete')
294      if (after?.status === 'holding') {
295        await armHold($)
296      } else {
297        dropHoldTimer()
298      }
299      return { result: reply }
300    }
301
302    if (e.tool === reportTool) {
303      if (!e.agentId) return { result: 'Only delegated workers report progress; Opus updates the board with the mission tool.' }
304      const pct = Math.max(0, Math.min(100, Math.round(Number(input.pct) || 0)))
305      await setAgents($, list => list.map(a => (a.id === e.agentId ? { ...a, pct, pctTools: a.tools, doing: clip(input.doing, 90) || a.doing } : a)))
306      return { result: 'Reported.' }
307    }
308
309    const doing = describeCall(String(e.tool), input)
310    if (e.agentId) {
311      const id = e.agentId
312      const known = (await read($, agentsAtom)).some(a => a.id === id)
313      if (known) await setAgents($, list => list.map(a => (a.id === id ? { ...a, tools: a.tools + 1, doing } : a)))
314    } else {
315      const m = await read($, missionAtom)
316      if (isLive(m)) {
317        const writes = isWriteTool(String(e.tool)) ? 1 : 0
318        const background = startsBackgroundWork(String(e.tool), input)
319        await setMission($, x => (x ? { ...x, writes: x.writes + writes, ...(background ? { pendingAt: now } : {}), ...(e.tool === 'Agent' ? {} : { doing }) } : x))
320      }
321    }
322
323    return next(e)
324  })
325
326  // ---------- agents: steer models, and put each one on the board ----------
327
328  on('agent.spawn', async ($, e, next) => {
329    const m = await read($, missionAtom)
330    let input = e
331    if (isLive(m) && !e.fork) {
332      // Opus manages: labor on Sonnet 5.5, narrow read-heavy jobs on Haiku 5.5
333      const model = steerModel(e.model, e.subagentType, { worker: workerType, scout: scoutType })
334      if (model) input = { ...e, model }
335      if (!e.parentAgentId && !/opus/i.test(e.parentModel) && !warnedModel) {
336        warnedModel = true
337        $.ui.toast(`Conductor is running on ${e.parentModel}, not Opus 5.5: switch the session model for the full effect`)
338      }
339    }
340
341    const r = await next(input)
342    if (!r.agentId) return r
343
344    const now = await $.clock.now()
345    const taskId = taskIdIn(e.description, e.prompt)
346    const ownType = e.subagentType.startsWith(workerType) || e.subagentType.startsWith(scoutType)
347    const effort = ownType ? effortOf(e.subagentType) : undefined
348    const row: AgentRow = {
349      id: r.agentId,
350      label: clip(e.description || e.name || e.subagentType, 60),
351      model: r.model,
352      type: e.subagentType,
353      startedAt: now,
354      endedAt: 0,
355      status: 'running',
356      tools: 0,
357      doing: 'starting',
358      pct: 0,
359      taskId,
360      summary: '',
361      ...(effort ? { effort } : {}),
362    }
363    await setAgents($, list => [...list.filter(a => a.id !== row.id), row])
364    if (taskId && isLive(m)) {
365      await setMission($, x =>
366        x ? { ...x, tasks: x.tasks.map(t => (t.id !== taskId ? t : { ...t, ...(t.status === 'pending' ? { status: 'active' as const, startedAt: now } : {}), agentId: row.id, ...(effort && !t.effort ? { effort } : {}) })) } : x,
367      )
368    }
369    return r
370  })
371
372  on('turn.complete', async ($, e, next) => {
373    const r = await next(e)
374    const now = await $.clock.now()
375
376    if (e.agentId) {
377      const id = e.agentId
378      const status = e.isAborted ? 'stopped' : e.reason === 'answer' ? 'done' : 'failed'
379      await setAgents($, list =>
380        list.map(a => (a.id === id ? { ...a, status, endedAt: now, pct: status === 'done' ? 100 : a.pct, doing: status === 'done' ? 'handed back to Opus' : status, summary: clip(e.answer, 220) } : a)),
381      )
382      return r
383    }
384
385    const m = await read($, missionAtom)
386    // waiting on the person or on hold: autopilot stays quiet
387    if (!m || m.status !== 'running') return r
388    const agents = await read($, agentsAtom)
389    const p = progress(m, agents)
390    if (p.n > 0 && p.doneN === p.n) {
391      await setMission($, x => (x ? { ...x, status: 'done', endedAt: now, doing: 'done' } : x))
392      $.ui.toast(`◆ Mission done in ${minutes(now - m.startedAt)}: ${clip(m.title, 60)}`)
393      return r
394    }
395
396    const settings = await read($, settingsAtom)
397    const working = agents.some(a => a.status === 'running')
398
399    // Opus started a background task this turn: its notification wakes the session, not a nudge.
400    if (!working && m.pendingAt > 0) {
401      await hold($, now, BACKGROUND_HOLD, 'a background task Opus started', 0)
402      return r
403    }
404    // A nudged turn that changed nothing on the board is a stall: hold, longer each stall
405    // in a row, instead of asking again. A nudged turn that moved the board clears the count.
406    const mark = fingerprint(m, agents)
407    const nudged = m.nudgedAt > 0
408    if (!working && nudged && mark === m.mark) {
409      const stalls = m.stalls + 1
410      const ms = stallHold(stalls)
411      await hold($, now, ms, `no progress after the last nudge (${stalls})`, stalls)
412      $.ui.toast(`◆ Autopilot standing by ${minutes(ms)}: the last nudge changed nothing`)
413      return r
414    }
415    const stalls = nudged ? 0 : m.stalls
416
417    // Autopilot: a running worker wakes Opus with its notification; otherwise nudge.
418    if (settings.auto && e.reason === 'answer' && !e.isAborted && !working && m.continues < settings.maxContinues) {
419      await setMission($, x => (x ? { ...x, continues: x.continues + 1, nudgedAt: now, mark, stalls, doing: 'continuing (autopilot)' } : x))
420      void $.prompt.submit({ text: continuation(m) })
421    } else {
422      await setMission($, x => (x ? { ...x, nudgedAt: 0, stalls, doing: working ? 'waiting on workers' : 'idle' } : x))
423    }
424    return r
425  })
426
427  // ---------- drawing ----------
428
429  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
430    const table = $.ui.resolve(e)
431    const m = await read($, missionAtom)
432    const agents = await read($, agentsAtom)
433    const settings = await read($, settingsAtom)
434    const now = await $.clock.now()
435    const width = Math.max(40, e.props.bodyColumns || 80)
436    return drawPane($, table, { m, agents, settings, now, width })
437  })
438
439  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
440    const m = await read($, missionAtom)
441    const now = await $.clock.now()
442    const recent = !!m && m.status === 'done' && now - m.endedAt < RECENT_MS
443    if (e.props.hasSurvey || !m || !(isLive(m) || recent)) return next(e)
444
445    const below = await next(e)
446    const { Box, Text, Button } = $.ui.resolve(e)
447    const agents = await read($, agentsAtom)
448    const p = progress(m, agents)
449    const running = agents.filter(a => a.status === 'running')
450    const width = Math.max(30, e.props.bodyColumns || 80)
451    const ph = phase(m, agents)
452    const tone = ph === 'done' ? COLOR.done : ph === 'waiting' || ph === 'standby' ? COLOR.wait : COLOR.opus
453    const right =
454      ph === 'done'
455        ? 'done ✓'
456        : ph === 'waiting'
457          ? 'waiting on you'
458          : ph === 'standby'
459            ? standbyWord(m, now)
460            : ph === 'planning'
461              ? `${spin(now)} planning…`
462              : `${spin(now)} cooking · ${p.pct}%${running.length ? ` · ${running.length} agent${running.length > 1 ? 's' : ''}` : ''}`
463
464    return (
465      <Box flexDirection="column">
466        <Box flexDirection="row" justifyContent="space-between" columnGap={2}>
467          <Text bold wrap="truncate-end">
468            <Text color={COLOR.opus}>◆ </Text>
469            {m.title}
470          </Text>
471          <Box flexDirection="row" columnGap={2} flexShrink={0}>
472            <Text bold color={tone}>{right}</Text>
473            <Button key="conduct-open" label="board" hotkey="c" plain onPress={() => openPane($)} />
474          </Box>
475        </Box>
476        {m.planAt > 0 && <Text color={tone}>{textBar(p.fraction, Math.min(width - 2, 80))}</Text>}
477        <Text dimColor wrap="truncate-end">
478          {running.length
479            ? running.map(a => `${modelName(a.model)} ${pctLabel(a)} · ${a.doing}`).join('  |  ')
480            : `Opus: ${m.doing}`}
481        </Text>
482        {below}
483      </Box>
484    )
485  })
486}
487
488// ---------- pieces ----------
489
490/** "standing by · 12m left" or "standing by · until a notification" */
491function standbyWord(m: Mission, now: number): string {
492  return m.holdUntil ? `standing by · ${minutes(Math.max(0, m.holdUntil - now))} left` : 'standing by · until a notification'
493}
494
495/** "40%" when the agent reported, "~14%" while it's an estimate from its tool calls */
496function pctLabel(a: AgentRow): string {
497  return `${a.pct > 0 ? '' : '~'}${agentPct(a)}%`
498}
499
500function modelName(id: string): string {
501  const hit = /(opus|sonnet|haiku|fable)[-_ ]?(\d+)?(?:[-.](\d+))?/i.exec(id)
502  if (!hit) return clip(id || 'inherit', 16)
503  const word = hit[1] ?? ''
504  const name = word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
505  return hit[2] ? `${name} ${hit[2]}${hit[3] ? '.' + hit[3] : ''}` : name
506}
507
508function modelColor(id: string): string {
509  return /opus/i.test(id) ? COLOR.opus : /sonnet/i.test(id) ? COLOR.sonnet : /haiku/i.test(id) ? COLOR.haiku : COLOR.track
510}
511
512function ownerColor(owner: Task['owner']): string {
513  return owner === 'opus' ? COLOR.opus : owner === 'haiku' ? COLOR.haiku : COLOR.sonnet
514}
515
516const OWNER_LABEL: Record<Task['owner'], string> = { opus: 'Opus  ', sonnet: 'Sonnet', haiku: 'Haiku ' }
517
518/** a fixed-width effort tag so task titles stay aligned */
519const EFFORT_TAG: Record<NonNullable<Task['effort']>, string> = { low: 'low ', medium: 'med ', high: 'high', xhigh: 'xhi ' }
520
521function textBar(fraction: number, width: number): string {
522  const w = Math.max(8, width)
523  const n = Math.round(Math.max(0, Math.min(1, fraction)) * w)
524  return '█'.repeat(n) + '░'.repeat(w - n)
525}
526
527function ringSvg(fraction: number, label: string, color: string): string {
528  const r = 30
529  const c = 2 * Math.PI * r
530  const dash = (Math.max(0, Math.min(1, fraction)) * c).toFixed(1)
531  return `<svg xmlns="http://www.w3.org/2000/svg" width="76" height="76" viewBox="0 0 76 76"><circle cx="38" cy="38" r="${r}" fill="none" stroke="${COLOR.track}" stroke-opacity="0.25" stroke-width="7"/><circle cx="38" cy="38" r="${r}" fill="none" stroke="${color}" stroke-width="7" stroke-linecap="round" stroke-dasharray="${dash} ${c.toFixed(1)}" transform="rotate(-90 38 38)"/><text x="38" y="43" text-anchor="middle" font-family="ui-sans-serif,system-ui,sans-serif" font-size="16" font-weight="700" fill="${color}">${label}</text></svg>`
532}
533
534function barSvg(fraction: number, color: string, width: number): string {
535  const f = Math.max(0, Math.min(1, fraction))
536  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="8" viewBox="0 0 ${width} 8"><rect width="${width}" height="8" rx="4" fill="${COLOR.track}" fill-opacity="0.25"/><rect width="${(f * width).toFixed(1)}" height="8" rx="4" fill="${color}"/></svg>`
537}
538
539/** One segment per live task, colored by where it stands; an active one fills with its agent's %. */
540function segmentsSvg(tasks: readonly Task[], agents: readonly AgentRow[], width: number): string {
541  const live = tasks.filter(t => t.status !== 'dropped')
542  if (!live.length) return barSvg(0, COLOR.track, width)
543  const gap = 3
544  const w = (width - gap * (live.length - 1)) / live.length
545  const rects = live
546    .map((t, i) => {
547      const x = (i * (w + gap)).toFixed(1)
548      const seg = (fill: string, opacity: number, len: number) => `<rect x="${x}" width="${Math.max(2, len).toFixed(1)}" height="6" rx="3" fill="${fill}" fill-opacity="${opacity}"/>`
549      if (t.status === 'done') return seg(COLOR.done, 1, w)
550      if (t.status !== 'active') return seg(COLOR.track, 0.3, w)
551      const f = Math.max(0.08, taskFraction(t, agents))
552      return seg(ownerColor(t.owner), 0.3, w) + seg(ownerColor(t.owner), 1, w * f)
553    })
554    .join('')
555  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="6" viewBox="0 0 ${width} 6">${rects}</svg>`
556}
557
558/** what Opus is up to, in one line under the header */
559function opusLine(m: Mission, ph: ReturnType<typeof phase>, running: number): string {
560  if (ph === 'waiting') return `asks: ${m.note}`
561  if (m.status !== 'holding') return m.doing
562  if (ph === 'standby') return `standing by: ${m.note}`
563  return running ? `watching ${running} agent${running > 1 ? 's' : ''} cook · ${m.note}` : `cooking: ${m.note}`
564}
565
566function segmentsText(tasks: readonly Task[]): string {
567  return tasks
568    .filter(t => t.status !== 'dropped')
569    .map(t => (t.status === 'done' ? '■' : t.status === 'active' ? '▣' : '□'))
570    .join('')
571}
572
573type View = { m: Mission | null; agents: readonly AgentRow[]; settings: ConductorSettings; now: number; width: number }
574
575function drawPane($: EngineInterface, table: Kit, v: View) {
576  const { Box, Text, Button } = table
577  const Svg = 'Svg' in table ? table.Svg : undefined
578  const { m, agents, settings, now, width } = v
579  const bar = (fraction: number, color: string, cols: number) =>
580    Svg ? <Svg source={barSvg(fraction, color, Math.max(80, cols * 7))} alt={`${Math.round(fraction * 100)} percent`} /> : <Text color={color}>{textBar(fraction, cols)}</Text>
581
582  const header = (() => {
583    if (!m) {
584      return (
585        <Box flexDirection="column">
586          <Text bold color={COLOR.opus}>◆ Opus Conductor</Text>
587          <Text dimColor>No mission yet. Type /conduct, pick conduct (opus-conductor), and describe what done looks like. Opus 5.5 plans it, Sonnet 5.5 workers build, Haiku 5.5 scouts look things up, and it all shows up here.</Text>
588        </Box>
589      )
590    }
591    const p = progress(m, agents)
592    const left = eta(m, agents, now)
593    const ph = phase(m, agents)
594    const tone = ph === 'done' ? COLOR.done : ph === 'waiting' || ph === 'standby' ? COLOR.wait : ph === 'stopped' ? COLOR.track : COLOR.opus
595    const word =
596      ph === 'done'
597        ? `Done ✓ in ${minutes(m.endedAt - m.startedAt)}`
598        : ph === 'stopped'
599          ? 'Stopped'
600          : ph === 'waiting'
601            ? 'Waiting on you'
602            : ph === 'standby'
603              ? `Standing by · ${p.doneN} of ${p.n} tasks done`
604              : m.planAt
605                ? `${spin(now)} Cooking · ${p.doneN} of ${p.n} tasks done`
606                : `${spin(now)} Planning…`
607    const live = isLive(m)
608    const meta = [
609      live ? `⏱ ${minutes(now - m.startedAt)}` : '',
610      left !== null ? `~${minutes(left)} left` : '',
611      m.status === 'holding' ? (m.holdUntil ? `checks back in ${minutes(Math.max(0, m.holdUntil - now))}` : 'checks back on a notification') : '',
612      settings.auto ? `autopilot ${m.continues}/${settings.maxContinues}` : 'autopilot off',
613    ].filter(Boolean)
614    return (
615      <Box flexDirection="column" rowGap={0}>
616        <Box flexDirection="row" columnGap={2} alignItems="center">
617          {Svg && <Svg source={ringSvg(p.fraction, `${p.pct}%`, tone)} alt={`Mission ${p.pct} percent done`} width={76} height={76} />}
618          <Box flexDirection="column" flexGrow={1} flexShrink={1}>
619            <Text bold color={COLOR.opus}>◆ OPUS CONDUCTOR</Text>
620            <Text bold wrap="wrap">{m.title}</Text>
621            <Text color={tone} bold>{Svg ? word : `${p.pct}% · ${word}`}</Text>
622          </Box>
623        </Box>
624        {m.planAt > 0 &&
625          (Svg ? (
626            <Svg source={segmentsSvg(m.tasks, agents, Math.max(120, Math.min(width, 90) * 7))} alt={`${p.doneN} of ${p.n} tasks done`} />
627          ) : (
628            <Text color={tone}>{segmentsText(m.tasks)}</Text>
629          ))}
630        <Text dimColor wrap="truncate-end">{meta.join('  ·  ')}</Text>
631        {live && (
632          <Text wrap="truncate-end">
633            <Text color={COLOR.opus} bold>Opus 5.5 </Text>
634            <Text dimColor>{opusLine(m, ph, agents.filter(a => a.status === 'running').length)}</Text>
635          </Text>
636        )}
637      </Box>
638    )
639  })()
640
641  const running = agents.filter(a => a.status === 'running')
642  const finished = agents.filter(a => a.status !== 'running').reverse()
643  const shownFinished = finished.slice(0, 5)
644
645  const runningCard = (a: AgentRow) => {
646    const tone = modelColor(a.model)
647    return (
648      <Box flexDirection="column" key={`agent-${a.id}`} borderStyle="round" borderColor={tone} paddingX={1}>
649        <Box flexDirection="row" justifyContent="space-between" columnGap={1}>
650          <Text wrap="truncate-end">
651            <Text color={tone}>● </Text>
652            <Text bold color={tone}>{modelName(a.model)}</Text>
653            <Text dimColor>{a.effort ? ` · ${a.effort} ` : ' '}</Text>
654            <Text bold>{a.label}</Text>
655          </Text>
656          <Text dimColor>{`${minutes(now - a.startedAt)} · ${a.tools} tools`}</Text>
657        </Box>
658        <Box flexDirection="row" columnGap={1} alignItems="center">
659          {bar(Math.max(0.03, agentPct(a) / 100), tone, Math.min(24, Math.max(8, width - 30)))}
660          <Text dimColor>{`${spin(now + a.startedAt)} ${pctLabel(a)}`}</Text>
661        </Box>
662        <Text dimColor wrap="truncate-end">{`▸ ${a.doing}`}</Text>
663      </Box>
664    )
665  }
666
667  const finishedRow = (a: AgentRow) => {
668    const icon = a.status === 'done' ? '✓' : a.status === 'failed' ? '✗' : '■'
669    const tone = a.status === 'done' ? COLOR.done : a.status === 'failed' ? COLOR.fail : COLOR.track
670    return (
671      <Box flexDirection="row" justifyContent="space-between" columnGap={1} key={`agent-${a.id}`}>
672        <Text wrap="truncate-end">
673          <Text color={tone}>{icon} </Text>
674          <Text color={modelColor(a.model)}>{modelName(a.model)}</Text>
675          <Text dimColor>{a.effort ? ` · ${a.effort} ` : ' '}</Text>
676          <Text dimColor>{a.label}</Text>
677        </Text>
678        <Text dimColor>{`${minutes(a.endedAt - a.startedAt)} · ${a.tools} tools`}</Text>
679      </Box>
680    )
681  }
682
683  const taskRow = (t: Task) => {
684    const icon = t.status === 'done' ? '✓' : t.status === 'active' ? '▶' : t.status === 'dropped' ? '×' : '○'
685    const tone = t.status === 'done' ? COLOR.done : t.status === 'active' ? ownerColor(t.owner) : COLOR.track
686    return (
687      <Text wrap="truncate-end" key={`task-${t.id}`}>
688        <Text color={tone}>{icon} </Text>
689        <Text dimColor>{`#${t.id} ${t.size} `}</Text>
690        <Text color={ownerColor(t.owner)}>{OWNER_LABEL[t.owner]} </Text>
691        {t.effort && <Text dimColor>{`${EFFORT_TAG[t.effort]} `}</Text>}
692        <Text bold={t.status === 'active'} dimColor={t.status === 'done' || t.status === 'dropped'} strikethrough={t.status === 'dropped'}>{t.title}</Text>
693      </Text>
694    )
695  }
696
697  // the plan keeps what's moving in view: the last two done, then everything open
698  const plan = (() => {
699    if (!m) return null
700    const done = m.tasks.filter(t => t.status === 'done')
701    const hiddenDone = Math.max(0, done.length - 2)
702    const keep = new Set(done.slice(-2).map(t => t.id))
703    const rows = m.tasks.filter(t => t.status !== 'done' || keep.has(t.id))
704    return { hiddenDone, rows }
705  })()
706
707  const live = isLive(m)
708
709  return (
710    <Box flexDirection="column" rowGap={1}>
711      {header}
712      <Box flexDirection="column" rowGap={0}>
713        <Text bold>{`AGENTS  ${running.length} working · ${finished.length} done`}</Text>
714        {!agents.length && <Text dimColor>No agents launched yet.</Text>}
715        {running.map(runningCard)}
716        {shownFinished.map(finishedRow)}
717        {finished.length > shownFinished.length && <Text dimColor>{`+${finished.length - shownFinished.length} earlier`}</Text>}
718      </Box>
719      {m && plan && (
720        <Box flexDirection="column">
721          <Text bold>PLAN</Text>
722          {!m.tasks.length && <Text dimColor>Waiting for Opus to plan…</Text>}
723          {plan.hiddenDone > 0 && <Text color={COLOR.done} dimColor>{`✓ ${plan.hiddenDone} earlier tasks done`}</Text>}
724          {plan.rows.map(taskRow)}
725        </Box>
726      )}
727      <Box flexDirection="row" columnGap={2} flexWrap="wrap">
728        {live && (
729          <Button
730            key="conduct-stop"
731            label="Stop mission"
732            onPress={async () => {
733              const at = await $.clock.now()
734              await update($, missionAtom, x => (x ? { ...x, status: 'stopped' as const, endedAt: at } : x))
735            }}
736          />
737        )}
738        {m?.status === 'holding' && (
739          <Button
740            key="conduct-resume"
741            label={m.stalls > 0 ? 'Resume now' : 'Check now'}
742            onPress={async () => {
743              const cur = await update($, missionAtom, x => (x ? { ...x, status: 'running' as const, holdUntil: 0, nudgedAt: 0, pendingAt: 0, doing: 'resumed by you' } : x))
744              if (cur) void $.prompt.submit({ text: holdExpired(cur) })
745            }}
746          />
747        )}
748        <Button
749          key="conduct-auto"
750          label={settings.auto ? 'Autopilot: on' : 'Autopilot: off'}
751          onPress={async () => {
752            const next = await update($, settingsAtom, s => ({ ...s, auto: !s.auto }))
753            await $.store.set('settings', next).catch(() => undefined)
754          }}
755        />
756        {!live && (m || agents.length > 0) && (
757          <Button
758            key="conduct-clear"
759            label="Clear board"
760            onPress={async () => {
761              await update($, missionAtom, () => null)
762              await update($, agentsAtom, list => (list ?? []).filter(a => a.status === 'running'))
763            }}
764          />
765        )}
766      </Box>
767    </Box>
768  )
769}
770
hooks/mission.ts 420 lines
1// Opus Conductor's mission: the plan Opus keeps through the mod's tool, the
2// progress the pane draws from it, and the words the mod hands the models.
3// Pure functions, no `$`: the tests drive them directly.
4
5import type { AgentRow, Effort, Mission, Owner, Size, Task } from '../types'
6
7export const SONNET = 'claude-sonnet-5-5'
8export const HAIKU = 'claude-haiku-5-5'
9export const WORKER = 'worker'
10export const SCOUT = 'scout'
11
12/** One registered agent type per effort: the Agent tool can't set effort per call. */
13export const WORKER_EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh']
14export const SCOUT_EFFORTS: readonly Effort[] = ['low', 'medium', 'high']
15const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh']
16
17export function effortOf(v: unknown): Effort | undefined {
18  const hit = /(?:^|[-\s:])(xhigh|high|medium|low)$/i.exec(String(v ?? '').trim())
19  const e = hit?.[1]?.toLowerCase() as Effort | undefined
20  return e && EFFORTS.includes(e) ? e : undefined
21}
22
23/** worker-high, scout-low, ...: the agent type for a kind of helper at one effort */
24export function agentName(kind: 'worker' | 'scout', effort: Effort): string {
25  return `${kind}-${effort}`
26}
27const SIZES: Record<Size, number> = { S: 1, M: 2, L: 3 }
28const STOP = /^(stop|cancel|off|end|abort)$/i
29
30export function isStopWord(text: string): boolean {
31  return STOP.test(text.trim())
32}
33
34export function clip(text: unknown, max: number): string {
35  const s = String(text ?? '').replace(/\s+/g, ' ').trim()
36  return s.length > max ? s.slice(0, max - 1) + '…' : s
37}
38
39export function minutes(ms: number): string {
40  const s = Math.max(0, Math.round(ms / 1000))
41  if (s < 60) return `${s}s`
42  const m = Math.round(s / 60)
43  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
44}
45
46export function newMission(condition: string, now: number): Mission {
47  const first = condition.split(/\r?\n/).map(l => l.trim()).find(Boolean) ?? 'Mission'
48  return {
49    title: clip(first, 120),
50    condition: condition.slice(0, 4000),
51    startedAt: now,
52    endedAt: 0,
53    status: 'running',
54    tasks: [],
55    nextId: 1,
56    planAt: 0,
57    continues: 0,
58    note: '',
59    doing: 'reading the ask',
60    holdUntil: 0,
61    nudgedAt: 0,
62    mark: '',
63    stalls: 0,
64    pendingAt: 0,
65    writes: 0,
66  }
67}
68
69const MIN = 60000
70/** a stall's hold: 5 min, doubling each stall in a row, at most 30 min */
71export function stallHold(stalls: number): number {
72  return Math.min(30, 5 * 2 ** Math.max(0, stalls - 1)) * MIN
73}
74/** how long a background task may take before the fallback timer asks Opus to look */
75export const BACKGROUND_HOLD = 15 * MIN
76
77/** What the board looks like: unchanged across a nudged turn means the nudge did nothing. */
78export function fingerprint(m: Mission, agents: readonly AgentRow[]): string {
79  const tasks = m.tasks.map(t => `${t.id}${t.status[0]}`).join('')
80  const rows = agents.map(a => `${a.id}${a.status[0]}`).join('')
81  return `${tasks}|${rows}|${m.writes}`
82}
83
84/** tools whose call is progress in itself, nudge or not */
85export function isWriteTool(tool: string): boolean {
86  return /^(Edit|MultiEdit|Write|NotebookEdit|Agent)$/.test(tool)
87}
88
89/** a tool call that starts work the session hears about later, as a task notification */
90export function startsBackgroundWork(tool: string, input: Record<string, unknown>): boolean {
91  if (tool === 'Monitor' || tool === 'ScheduleWakeup') return true
92  return (tool === 'Bash' || tool === 'PowerShell') && input.run_in_background === true
93}
94
95function resume(m: Mission) {
96  if (m.status === 'waiting' || m.status === 'holding') m.status = 'running'
97  m.holdUntil = 0
98  m.pendingAt = 0
99}
100
101type RawTask = { title?: unknown; size?: unknown; owner?: unknown; effort?: unknown }
102
103function sizeOf(v: unknown): Size {
104  const s = String(v ?? '').trim().toUpperCase().charAt(0)
105  return s === 'S' || s === 'L' ? s : 'M'
106}
107
108function ownerOf(v: unknown): Owner {
109  const s = String(v ?? '')
110  return /opus/i.test(s) ? 'opus' : /haiku|scout/i.test(s) ? 'haiku' : 'sonnet'
111}
112
113/**
114 * The model a mission's spawn should run on, or undefined to leave the call as made.
115 * Labor defaults to Sonnet 5.5; read-only exploring defaults to Haiku 5.5; any
116 * Haiku request is lifted to Haiku 5.5; an explicit Sonnet/Opus/Fable choice stands.
117 */
118export function steerModel(model: string | undefined, subagentType: string, own: { worker: string; scout: string }): string | undefined {
119  if (model) return /haiku/i.test(model) && !/5[-.]5/.test(model) ? HAIKU : undefined
120  if (subagentType.startsWith(own.worker) || subagentType.startsWith(own.scout)) return undefined
121  return /^explore$/i.test(subagentType) ? HAIKU : SONNET
122}
123
124function makeTasks(m: Mission, raw: unknown): Task[] {
125  const list = Array.isArray(raw) ? (raw as RawTask[]) : []
126  return list
127    .filter(t => t && clip(t.title, 140))
128    .map(t => ({
129      id: m.nextId++,
130      title: clip(t.title, 140),
131      size: sizeOf(t.size),
132      owner: ownerOf(t.owner),
133      ...(effortOf(t.effort) ? { effort: effortOf(t.effort) } : {}),
134      status: 'pending' as const,
135      agentId: '',
136      startedAt: 0,
137      doneAt: 0,
138      note: '',
139    }))
140}
141
142export type MissionInput = {
143  action?: unknown
144  tasks?: unknown
145  ids?: unknown
146  note?: unknown
147  minutes?: unknown
148}
149
150function idsOf(raw: unknown): number[] {
151  const list = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]
152  return list.map(Number).filter(n => Number.isInteger(n))
153}
154
155/** Applies one call of the mission tool; returns the mission after it and the reply. */
156export function applyAction(
157  before: Mission,
158  input: MissionInput,
159  now: number,
160): { mission: Mission; text: string } {
161  const m: Mission = { ...before, tasks: before.tasks.map(t => ({ ...t })) }
162  const action = String(input.action ?? 'show').toLowerCase()
163  const note = clip(input.note, 300)
164  const pick = (ids: number[]) => m.tasks.filter(t => ids.includes(t.id))
165
166  if (action === 'plan' || action === 'add') {
167    if (action === 'plan') m.tasks = m.tasks.filter(t => t.status !== 'pending')
168    const added = makeTasks(m, input.tasks)
169    if (!added.length) return { mission: before, text: 'No tasks given. Pass tasks: [{ title, size: S|M|L, owner: opus|sonnet }].' }
170    m.tasks.push(...added)
171    if (!m.planAt) m.planAt = now
172    m.doing = 'planned; dispatching'
173    resume(m)
174    return { mission: m, text: `${action === 'plan' ? 'Plan set' : 'Added'}: ${added.map(t => `#${t.id} ${t.title} (${t.size}, ${t.owner})`).join('; ')}.\n${summary(m)}` }
175  }
176
177  if (action === 'start' || action === 'done' || action === 'drop') {
178    const hit = pick(idsOf(input.ids))
179    if (!hit.length) return { mission: before, text: `No task with ids ${JSON.stringify(input.ids)}. ${summary(before)}` }
180    for (const t of hit) {
181      if (action === 'start') {
182        t.status = 'active'
183        t.startedAt = t.startedAt || now
184      } else if (action === 'done') {
185        t.status = 'done'
186        t.doneAt = now
187        t.startedAt = t.startedAt || now
188      } else {
189        t.status = 'dropped'
190      }
191      if (note) t.note = note
192    }
193    resume(m)
194    return { mission: m, text: summary(m) }
195  }
196
197  if (action === 'wait') {
198    m.status = 'waiting'
199    m.note = note || 'waiting on the person'
200    m.holdUntil = 0
201    return { mission: m, text: 'Mission paused for the person. Autopilot will not continue until they reply.' }
202  }
203
204  if (action === 'hold') {
205    const mins = Math.max(0, Math.min(24 * 60, Number(input.minutes) || 0))
206    m.status = 'holding'
207    m.note = note || 'waiting on something outside this session'
208    m.holdUntil = mins ? now + mins * MIN : 0
209    m.pendingAt = 0
210    m.doing = `cooking: ${m.note}`
211    const wake = mins ? `in ${mins} min` : 'only when a notification arrives'
212    return { mission: m, text: `On hold: ${m.note}. Autopilot stays quiet; a task notification, the person, or the timer (${wake}) wakes you. End your turn now without further checks.` }
213  }
214
215  if (action === 'complete') {
216    m.status = 'done'
217    m.endedAt = now
218    m.note = note
219    // a verified mission finishes every task still on its plan
220    for (const t of m.tasks) {
221      if (t.status === 'active' || t.status === 'pending') {
222        t.status = 'done'
223        t.doneAt = now
224      }
225    }
226    return { mission: m, text: `Mission complete. ${summary(m)}` }
227  }
228
229  return { mission: before, text: summary(before) }
230}
231
232export function live(m: Mission): Task[] {
233  return m.tasks.filter(t => t.status !== 'dropped')
234}
235
236/**
237 * An agent's live %: its own report, creeping up with each tool call since, or,
238 * before its first report, an estimate from the tool calls it has made.
239 * Never 100 until it hands back.
240 */
241export function agentPct(a: AgentRow): number {
242  if (a.status === 'done') return 100
243  if (a.pct > 0) return Math.min(95, Math.round(a.pct + Math.min(15, Math.max(0, a.tools - (a.pctTools ?? a.tools)) * 1.5)))
244  return Math.round(75 * (1 - Math.exp(-a.tools / 30)))
245}
246
247/** Finished weight over the plan's weight; an active task counts its agent's live %. */
248export function progress(m: Mission, agents: readonly AgentRow[] = []) {
249  const tasks = live(m)
250  const total = tasks.reduce((a, t) => a + SIZES[t.size], 0)
251  let done = 0
252  for (const t of tasks) {
253    if (t.status === 'done') done += SIZES[t.size]
254    else if (t.status === 'active') done += SIZES[t.size] * taskFraction(t, agents)
255  }
256  const doneN = tasks.filter(t => t.status === 'done').length
257  const fraction = m.status === 'done' ? 1 : total ? done / total : 0
258  return { n: tasks.length, doneN, fraction, pct: Math.round(fraction * 100) }
259}
260
261/** How far an active task is: its running agent's live % (at most 90%), 90% once its agent handed back. */
262export function taskFraction(t: Task, agents: readonly AgentRow[]): number {
263  const mine = agents.filter(x => x.taskId === t.id && x.status !== 'failed' && x.status !== 'stopped')
264  if (!mine.length) return 0
265  return Math.min(0.9, Math.max(...mine.map(a => agentPct(a) / 100)))
266}
267
268/**
269 * What the mission is doing, in the board's words. A hold is "cooking" whenever
270 * work goes on: agents running, a background task, or the outside job Opus
271 * waits on. Only a stall with nothing running is "standing by".
272 */
273export function phase(m: Mission, agents: readonly AgentRow[]): 'planning' | 'cooking' | 'standby' | 'waiting' | 'done' | 'stopped' {
274  if (m.status === 'done' || m.status === 'stopped' || m.status === 'waiting') return m.status
275  const working = agents.some(a => a.status === 'running')
276  if (m.status === 'holding' && m.stalls > 0 && !working) return 'standby'
277  return m.planAt || working ? 'cooking' : 'planning'
278}
279
280/** Time left at the mission's own pace, once a quarter of it is done. */
281export function eta(m: Mission, agents: readonly AgentRow[], now: number): number | null {
282  const p = progress(m, agents)
283  if ((m.status !== 'running' && m.status !== 'holding') || !m.planAt || p.fraction < 0.25 || p.fraction >= 1) return null
284  const spent = now - m.planAt
285  return (spent / p.fraction) * (1 - p.fraction)
286}
287
288export function summary(m: Mission): string {
289  const p = progress(m)
290  const rows = m.tasks.map(t => `#${t.id} [${t.status}] ${t.size} ${t.owner}${t.effort ? `@${t.effort}` : ''}: ${t.title}${t.note ? ` (${t.note})` : ''}`)
291  return [`Mission "${m.title}": ${p.doneN}/${p.n} tasks, ${p.pct}%.`, ...rows].join('\n')
292}
293
294/** The task an Agent call is for: "#3" in its description or prompt. */
295export function taskIdIn(...texts: (string | undefined)[]): number {
296  for (const t of texts) {
297    const hit = /#(\d{1,4})\b/.exec(t ?? '')
298    if (hit) return Number(hit[1])
299  }
300  return 0
301}
302
303/** One short line of what a tool call does, for an agent's card. */
304export function describeCall(tool: string, input: Record<string, unknown>): string {
305  const file = (v: unknown) => String(v ?? '').split(/[\\/]/).pop() ?? ''
306  switch (tool) {
307    case 'Bash':
308    case 'PowerShell': {
309      // the step that matters, not the cd and variables in front of it
310      const parts = String(input.command ?? '').split(/&&|;|\n/).map(x => x.trim()).filter(Boolean)
311      const step = parts.filter(x => !/^(cd|set|export|\$?[A-Za-z_][A-Za-z0-9_]*=)/.test(x)).pop() ?? parts.pop() ?? ''
312      return `$ ${clip(step, 70)}`
313    }
314    case 'Read':
315      return `reading ${file(input.file_path)}`
316    case 'Edit':
317    case 'MultiEdit':
318      return `editing ${file(input.file_path)}`
319    case 'Write':
320      return `writing ${file(input.file_path)}`
321    case 'Grep':
322      return `searching "${clip(input.pattern, 40)}"`
323    case 'Glob':
324      return `finding ${clip(input.pattern, 40)}`
325    case 'WebFetch':
326    case 'WebSearch':
327      return `web: ${clip(input.query ?? input.url, 50)}`
328    case 'Agent':
329      return `delegating: ${clip(input.description, 50)}`
330    default:
331      return tool.startsWith('mcp__') ? tool.split('__').slice(1).join(' · ') : tool
332  }
333}
334
335// ---------- words for the models ----------
336
337export function missionToolSpec(name: string) {
338  return {
339    name,
340    description:
341      'Opus Conductor mission board: the plan the person watches live. Actions: ' +
342      '"plan" (replace pending tasks) / "add" with tasks [{ title, size: S|M|L, owner: "opus"|"sonnet"|"haiku", effort: "low"|"medium"|"high"|"xhigh" }]; ' +
343      '"start" / "done" / "drop" with ids [n] and an optional note; "wait" with a note when you need the person; ' +
344      '"hold" with a note (and optional minutes) when you are waiting on something outside this session (a render, CI, a background command, a monitor): ' +
345      'autopilot stays quiet until a task notification, the person, or the timer wakes you; ' +
346      '"complete" with a note once the whole mission is verified; "show". Mark a task done only after you verified its result.',
347    inputSchema: {
348      type: 'object',
349      properties: {
350        action: { type: 'string', enum: ['plan', 'add', 'start', 'done', 'drop', 'wait', 'hold', 'complete', 'show'] },
351        tasks: {
352          type: 'array',
353          items: {
354            type: 'object',
355            properties: {
356              title: { type: 'string' },
357              size: { type: 'string', enum: ['S', 'M', 'L'] },
358              owner: { type: 'string', enum: ['opus', 'sonnet', 'haiku'] },
359              effort: { type: 'string', enum: ['low', 'medium', 'high', 'xhigh'] },
360            },
361            required: ['title'],
362          },
363        },
364        ids: { type: 'array', items: { type: 'integer' } },
365        note: { type: 'string' },
366        minutes: { type: 'number', minimum: 1, description: 'for "hold": wake me after this many minutes if nothing else does' },
367      },
368      required: ['action'],
369    },
370  }
371}
372
373export function reportToolSpec(name: string) {
374  return {
375    name,
376    description:
377      'For a delegated worker: report your progress to the conductor\'s live board. ' +
378      'pct is your own honest estimate 0-100 of your assignment; doing is a few words on what you are doing now. ' +
379      'Call it after each meaningful step (roughly every 3-5 tool calls).',
380    inputSchema: {
381      type: 'object',
382      properties: { pct: { type: 'number', minimum: 0, maximum: 100 }, doing: { type: 'string' } },
383      required: ['pct', 'doing'],
384    },
385  }
386}
387
388export function scoutPrompt(reportTool: string): string {
389  return `You are a Haiku 5.5 scout under an Opus 5.5 conductor. You do one narrow, well-defined job fast: look things up, read and sweep files, extract or summarize, triage, or run a named check and report what it says.
390
391Rules:
392- Do exactly the job in the brief. Do not design, refactor, or decide; if the job needs judgment the brief does not settle, stop and say so.
393- Prefer reading over writing. Edit files only when the brief names the exact change.
394- Quote evidence: file paths with line numbers, command output, URLs. Never guess a value you could not find; say it is missing.
395- Report progress with ${reportTool} (pct 0-100 and a few words) after each meaningful step, and pct 100 just before you finish.
396- Finish with a compact result in the shape the brief asks for, then any gaps.`
397}
398
399export function workerPrompt(reportTool: string): string {
400  return `You are a Sonnet 5.5 worker under an Opus 5.5 conductor. The conductor owns design decisions, integration and verification; you own exactly one delegated outcome.
401
402Rules:
403- Do the assignment exactly as briefed. Stay inside the stated scope; never touch files listed under "Do not touch".
404- Locked decisions are not yours to revisit. If the brief is wrong or blocked, stop and report the evidence instead of widening scope.
405- Report progress with ${reportTool} (pct 0-100 and a few words) after each meaningful step, and pct 100 just before you finish.
406- Run the verification the brief names. Do not claim a check passed that you did not run.
407- Finish with: summary, changed files, checks run with their result, remaining risks.`
408}
409
410export function continuation(m: Mission): string {
411  const open = live(m).filter(t => t.status !== 'done')
412  if (!m.planAt) return `Continue the Opus Conductor mission "${m.title}": make the plan with the mission tool first, then delegate.`
413  return `Continue the Opus Conductor mission "${m.title}". Open tasks: ${open.map(t => `#${t.id} ${t.title} [${t.status}, ${t.owner}]`).join('; ')}. Delegate, verify, integrate and update the board. If you need the person, call the mission tool with action "wait". If you are waiting on something outside this session (a render, CI, a background command, a monitor), call it with action "hold" and end the turn; never answer with a status update alone.`
414}
415
416/** The prompt that wakes Opus when a hold's timer runs out. */
417export function holdExpired(m: Mission): string {
418  return `The hold on the Opus Conductor mission "${m.title}" ran out (${m.note}). Check once whether what you were waiting on is ready. If it is, continue the mission; if not, call the mission tool with action "hold" again, with a longer timer, and end the turn.`
419}
420
types/index.d.ts 81 lines
1export type Size = 'S' | 'M' | 'L'
2export type Owner = 'opus' | 'sonnet' | 'haiku'
3export type Effort = 'low' | 'medium' | 'high' | 'xhigh'
4export type TaskStatus = 'pending' | 'active' | 'done' | 'dropped'
5
6export type Task = {
7  id: number
8  title: string
9  size: Size
10  owner: Owner
11  /** the reasoning effort Opus chose for it; absent on tasks planned before 1.4 */
12  effort?: Effort
13  status: TaskStatus
14  agentId: string
15  startedAt: number
16  doneAt: number
17  note: string
18}
19
20/** holding: Opus waits on something outside the session (a render, CI, a background command); autopilot stays quiet */
21export type MissionStatus = 'running' | 'waiting' | 'holding' | 'done' | 'stopped'
22
23export type Mission = {
24  title: string
25  condition: string
26  startedAt: number
27  endedAt: number
28  status: MissionStatus
29  tasks: Task[]
30  nextId: number
31  planAt: number
32  continues: number
33  note: string
34  doing: string
35  /** while holding: when the fallback timer wakes Opus; 0 = only a notification or the person does */
36  holdUntil: number
37  /** when autopilot last nudged; 0 when the last turn was not its */
38  nudgedAt: number
39  /** the board's fingerprint at the last nudge: unchanged after the turn = a stall */
40  mark: string
41  /** stalls in a row: each one doubles the hold */
42  stalls: number
43  /** when Opus started a background task this turn (Bash run_in_background, Monitor); 0 otherwise */
44  pendingAt: number
45  /** main-loop write tool calls so far: part of the fingerprint */
46  writes: number
47}
48
49export type AgentStatus = 'running' | 'done' | 'failed' | 'stopped'
50
51export type AgentRow = {
52  id: string
53  label: string
54  model: string
55  type: string
56  startedAt: number
57  endedAt: number
58  status: AgentStatus
59  tools: number
60  doing: string
61  pct: number
62  /** its tool count when it last reported pct: the bar creeps from there until the next report */
63  pctTools?: number
64  taskId: number
65  /** the effort its agent type runs at; absent for agents that aren't the conductor's */
66  effort?: Effort
67  summary: string
68}
69
70export type ConductorSettings = { auto: boolean; maxContinues: number }
71
72declare module 'claude-code' {
73  interface PluginState {
74    'opus-conductor': {
75      mission: Mission | null
76      agents: AgentRow[]
77      settings: ConductorSettings
78    }
79  }
80}
81