Spin up Claude Code workers from a picker: OpenRouter (any model) or Amazon Bedrock (Claude), as tmux panes or terminal tabs; team messaging between them

Claude Code mods (function-hook plugins). Each folder is one plugin; .claude-plugin/marketplace.json makes this repo a marketplace.
| Mod | What it does |
|---|---|
cheap-worker | /worker spins up Claude Code workers from a picker; /workers lists, messages and closes them. Team mode lets workers find each other (ListAgents) and talk (SendMessage). |
agent-progress | /progress: animated progress bar per agent (main, subagents, workers) from their task lists. |
agent-map | /map: project file tree; red 🔨 = an agent is editing it, green ✓ = done, ready for review. |
context-bar | Context-window breakdown above the prompt. |
usage-meter | 5-hour / weekly usage in the footer. |
quick-settings | ⚙ footer button for model and effort. |
skins | /skins: colour themes (Tokyo Night, Dracula, Gruvbox, …). |
cw-pane, driver-seat-guard, evidence-band | For the driver-seat workflow; skip them elsewhere. |
/plugin marketplace add ianwilson97/claude-mods
/plugin install cheap-worker@ianwilson-mods
/plugin install agent-progress@ianwilson-mods
/plugin install agent-map@ianwilson-mods
On the machine where this folder is the live copy (loaded through CLAUDE_CODE_PLUGIN_DIRS), don't also install from the marketplace: each mod would load twice.
Set per machine in /config (or pluginConfigs.cheap-worker.options in ~/.claude/settings.json):
| Option | Values | |
|---|---|---|
provider | openrouter (default) | Any OpenRouter model; key read from $CW_OPENROUTER_API_KEY (export it in ~/.zshenv). Workers skip user settings, hooks and plugins. |
bedrock | Claude only (Sonnet / Opus / Haiku). Workers keep your user settings, so the Bedrock env there (CLAUDE_CODE_USE_BEDROCK, AWS_REGION, AWS_PROFILE, …) applies. No call to openrouter.ai. | |
launch | panes (default) | All workers tiled in tmux session cw: tmux new -A -s cw. |
tabs | Each worker gets a tmux session of its own and opens in a background tab: a Herdr or cmux tab when Claude Code runs inside one, else a Ghostty tab (focus stays where you were). | |
remote | Each worker runs on this repo's Fly Sprite, unattended; see remote workers below. |
Work laptop: provider = bedrock, launch = tabs.
crewThe mod installs crew into ~/.local/bin (that folder must be on your PATH; it never overwrites a different crew).
crew # list running workers, pick one by number
crew ab12c # attach to cw-ab12c
If Ghostty can't be scripted (macOS asks once to let Claude control Ghostty; a managed Mac may refuse), the worker still runs: press CMD+T and run crew. Closing a tab only detaches; the worker keeps running until you close it from /workers.
Needs: tmux; for auto-opened tabs, Herdr, cmux or Ghostty 1.3+.
launch = remote)With launch = remote, /worker (and driver-seat's cw chore) runs the worker on this repo's own Fly Sprite, a small cloud machine, instead of your laptop:
cw/<worker-name> on GitHub. The final commit starts with [cw-done] and says what it did and how it tested it.curl -fsSL https://sprites.dev/install.sh | sh, then sprite login.gh auth login.mcp-cw-.In a Claude Code session inside the repo, run /cheap-worker:remote-setup. It does the following, and is safe to re-run:
mcp-cw-<owner>-<repo>, and the repo is cloned onto it.cw-remote github to make them:cw/… branches. Nothing else on your account is reachable from the sprite.main, whatever it decides.You can also run it yourself, in the repo: cw-remote github. It lists what it will change and asks before doing anything.
sprite exec … cat ~/.cw/topic in your own terminal, then subscribe to that topic in the ntfy app.baseline checkpoint.Then set /config → cheap-worker → Where workers open = remote.
/worker, type the task, press Enter. You'll see:
cw-x is running on the sprite, with the sprite's URL. In Ghostty or cmux a tab also attaches to the worker; Herdr gets no tab.crew x attaches from any terminal, and the URL opens it in a browser, which works on a phone too.done (about 2 minutes after it goes quiet), stuck (a question or menu it can't answer), or died (it exited without finishing).git fetch origin cw/cw-x and review the branch./workers lists remote workers next to local ones, and can message or close them. Closing one removes its checkout on the sprite; its branch stays on GitHub.
Cost: the sprite bills while it's awake, and an open browser tab on its URL keeps it awake, so close the tab when you're done looking. Before each launch, cw-remote takes a sprite checkpoint named pre-<worker>. Restoring one is manual, and it rolls back every worker on the sprite.
/plugin lists the mods as enabled. Managed settings can block marketplaces or plugins; if so, nothing loads./worker, launch one with task say hi; a Ghostty tab opens (or the toast says CMD+T, then crew …)./workers send one a message: messaging is Claude Code's own (ListAgents / SendMessage) and works under Bedrock unless policy turns it off.hooks/register.tsx 981 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Active, Launch, Mode, Msg, Picker, WStats } from '../types'
5import { BEDROCK_MODELS, DEFAULT_MODEL, META_FORMAT, attachCommand, defaultModelFor, ghosttyTabScript, parseRemoteList, remoteAttachCommand, herdrPaneId, isSlug, surfaceRef, toMode, workerName, bannerModel, parseMeta, choicesFor, clockDur, costOf, isRetired, isWorking, kfmt, leadFrom, parseModels, parsePanes, parsePeer, peekLines, price, projectDir, search, sq, teamPreamble, toPins, tokensOf, usageFrom, vendorOf, workerScript } from './worker'
6import type { LaunchMode, Provider, RemoteRow } from './worker'
7
8const PANE = 'cheap-worker'
9const VIEW = 'cheap-workers'
10const FORCE_AFTER_MS = 6000
11const OR_LIME = '#c8f031'
12const ACCENT = '#9fd17a'
13// Permission mode as the card's colored word, like the screenshot's tier word.
14const MODE_WORD: Record<Mode, string> = { acceptEdits: 'edits', auto: 'auto', default: 'ask' }
15// A remote worker always runs in bypass mode, whatever the picker says: its card says remote.
16const modeWord = (l: Launch | null | undefined) => (!l ? '?' : l.remote ? 'remote' : MODE_WORD[l.mode])
17const MODE_COLOR: Record<Mode, string> = { acceptEdits: '#57ab5a', auto: '#539bf5', default: '#e0823d' }
18// Provider logos as 16×16 pixel-art SVG traces (assets/providers-svg), for the remote surfaces' Svg; '' = none.
19const iconsSvg = new Map<string, string>()
20// 8×8 colour grids (assets/providers-px.json) drawn as half-block text: works in every
21// terminal, including ones that can't show images (the desktop app's terminal prints alt text).
22let pixels: Record<string, (string | null)[][]> | null = null
23const MODES: readonly { value: Mode; label: string; note: string }[] = [
24 { value: 'acceptEdits', label: 'edits', note: 'auto-approves file edits, asks for the rest' },
25 { value: 'auto', label: 'auto', note: 'auto mode (under OpenRouter it may show a billing dialog once)' },
26 { value: 'default', label: 'ask', note: 'asks before every edit and command' },
27]
28
29const DEFAULTS: Picker = {
30 model: DEFAULT_MODEL,
31 mode: 'acceptEdits',
32 query: '',
33 models: [],
34 recent: [DEFAULT_MODEL],
35 pins: [],
36 launched: [],
37 flash: null,
38 active: [],
39 closing: [],
40 team: false,
41 messages: [],
42 stats: {},
43 showFinished: true,
44}
45const MAX_MESSAGES = 40
46// The plugin's userConfig (set per machine in /config): set by register, which reruns when it changes.
47const cfg: { provider: Provider; launch: LaunchMode } = { provider: 'openrouter', launch: 'panes' }
48const CREW_MARK = '# crew — cheap-worker'
49// Remote workers per sprite, as `cw-remote list` last said. Refreshed only on demand (launch, the
50// tool, /workers): every `sprite exec` wakes the sprite, so the 5 s poll only reads this cache.
51const remoteRows = new Map<string, RemoteRow[]>()
52const cwRemote = ($: EngineInterface) => `${$.plugin.root}/bin/cw-remote`
53// State outlives a reload, and the default above only seeds an empty slot: a
54// value saved by an older version lacks newer fields until session.start fills them.
55const picker = atom({ plugin: 'cheap-worker', key: 'picker' } as const, DEFAULTS)
56
57async function loadModels($: EngineInterface): Promise<boolean> {
58 if (cfg.provider === 'bedrock') {
59 await update($, picker, p => ({ ...p, models: BEDROCK_MODELS }))
60 return true
61 }
62 const res = await $.http.fetch('https://openrouter.ai/api/v1/models').catch(() => null)
63 if (!res?.ok) return false
64 const models = parseModels(res.text)
65 await update($, picker, p => ({ ...p, models }))
66 return true
67}
68
69async function openPane($: EngineInterface) {
70 await $.ui.open({ id: PANE, title: 'Cheap worker' })
71 if ((await read($, picker)).models.length === 0) await loadModels($)
72}
73
74async function togglePin($: EngineInterface, id: string) {
75 await update($, picker, p => ({ ...p, pins: p.pins.includes(id) ? p.pins.filter(x => x !== id) : [...p.pins, id] }))
76 await $.store.set('pins', (await read($, picker)).pins)
77}
78
79async function tmux($: EngineInterface, args: string[]) {
80 return $.process.run(['tmux', ...args])
81}
82
83/** What a launch may set instead of the picker's current choice (the workers tool sets these). */
84type LaunchOpts = { model?: string; mode?: Mode; team?: boolean; name?: string; lead?: string }
85
86async function launch($: EngineInterface, task: string, over: LaunchOpts = {}): Promise<{ l: Launch; isTabOpen: boolean | null }> {
87 const picked = await read($, picker)
88 const saved = { ...picked, ...(over.model && { model: over.model }), ...(over.mode && { mode: over.mode }), ...(over.team !== undefined && { team: over.team }) }
89 if (over.model && cfg.provider === 'openrouter' && !isSlug(over.model)) throw new Error(`not an OpenRouter model id: ${over.model}`)
90 if (over.model && cfg.provider === 'bedrock' && !BEDROCK_MODELS.some(m => m.id === over.model)) throw new Error(`Bedrock runs ${BEDROCK_MODELS.map(m => m.id.split('/')[1]).join(', ')}, not ${over.model}`)
91 // a model the provider can't run (e.g. an OpenRouter pick, then switched to bedrock) → its default
92 const isRunnable = cfg.provider === 'bedrock' ? BEDROCK_MODELS.some(m => m.id === saved.model) : !BEDROCK_MODELS.some(m => m.id === saved.model)
93 const p = isRunnable ? saved : { ...saved, model: defaultModelFor(cfg.provider) }
94 // remote: the sprite reaches models through the Sprites OpenRouter Connector, never a key from here
95 if (cfg.provider === 'openrouter' && cfg.launch !== 'remote') {
96 const key = await $.process.run(['zsh', '-c', '[[ -n $CW_OPENROUTER_API_KEY ]]'])
97 if (key.exitCode !== 0) throw new Error('CW_OPENROUTER_API_KEY is not set in ~/.zshenv')
98 }
99
100 const name = over.name ?? `cw-${(await $.clock.now()).toString(36).slice(-5)}`
101 if (over.name) {
102 const taken = (p.active ?? []).some(a => a.name === name) || [...remoteRows.values()].flat().some(r => r.meta.name === name) || (await tmux($, ['has-session', '-t', `=${name}`]).catch(() => null))?.exitCode === 0
103 if (taken) throw new Error(`a worker named ${name} is already running`)
104 }
105 if (cfg.launch === 'remote') return launchRemote($, p, name, task, over)
106 const prompt = p.team
107 ? `${teamPreamble({ name, teammates: (p.active ?? []).map(a => a.name), lead: await leadName($) })}\n\nTask: ${task || 'wait for messages from teammates or the lead.'}`
108 : task
109 // Single-quoted whole, so only the pane's own zsh expands the key reference.
110 const contextTokens = p.models.find(m => m.id === p.model)?.contextTokens
111 const run = `zsh -c ${sq(workerScript({ name, model: p.model, mode: p.mode, task: prompt, contextTokens, provider: cfg.provider }))}`
112 const cwd = await $.session.cwd()
113 const fmt = ['-P', '-F', '#{pane_id}']
114
115 const startedAt = await $.clock.now()
116 const label = async (pane: string) => {
117 await tmux($, ['set', '-p', '-t', pane, '@cw', name])
118 // on the pane, so every session (not just this one) knows what this worker is
119 for (const [k, v] of [['@cw_model', p.model], ['@cw_mode', p.mode], ['@cw_start', String(startedAt)], ['@cw_cwd', cwd], ['@cw_task', task.replace(/[\t\n]+/g, ' ').slice(0, 200)]] as const)
120 await tmux($, ['set', '-p', '-t', pane, k, v])
121 }
122 const l: Launch = { name, model: p.model, mode: p.mode, pane: '', task, isLive: true, startedAt, cwd }
123
124 if (cfg.launch === 'tabs') {
125 // A tmux session of its own (it outlives a closed tab), shown in a new terminal tab.
126 const made = await tmux($, ['new-session', '-d', '-s', name, '-x', '200', '-y', '50', '-c', cwd, ...fmt, run])
127 if (made.exitCode !== 0) throw new Error(made.stderr.trim() || 'tmux could not start a session')
128 const pane = made.stdout.trim()
129 await label(pane)
130 const tmuxPath = (await $.process.run(['zsh', '-c', 'command -v tmux']).catch(() => null))?.stdout.trim() ?? ''
131 return { l: { ...l, pane }, isTabOpen: tmuxPath.startsWith('/') && (await openTab($, name, attachCommand(name, tmuxPath))) }
132 }
133
134 // The same layout as cw: session `cw`, window `workers`, tiled panes.
135 const hasSession = (await tmux($, ['has-session', '-t', 'cw'])).exitCode === 0
136 const hasWindow = hasSession && (await tmux($, ['list-windows', '-t', 'cw', '-F', '#W'])).stdout.split('\n').includes('workers')
137 const made = !hasSession
138 ? await tmux($, ['new-session', '-d', '-s', 'cw', '-n', 'workers', '-x', '200', '-y', '50', '-c', cwd, ...fmt, run])
139 : !hasWindow
140 ? await tmux($, ['new-window', '-t', 'cw:', '-n', 'workers', '-c', cwd, ...fmt, run])
141 : await tmux($, ['split-window', '-d', '-t', 'cw:workers', '-c', cwd, ...fmt, run])
142 if (made.exitCode !== 0) throw new Error(made.stderr.trim() || 'tmux could not open a pane')
143 const pane = made.stdout.trim()
144 await tmux($, ['select-layout', '-t', 'cw:workers', 'tiled'])
145 await label(pane)
146 await tmux($, ['set', '-t', 'cw', 'pane-border-status', 'top'])
147 await tmux($, ['set', '-t', 'cw', 'pane-border-format', ' #{@cw} '])
148 return { l: { ...l, pane }, isTabOpen: null }
149}
150
151/** Asks the sprite for its workers (one `sprite exec`); keeps the last answer when it can't be reached. */
152async function listRemote($: EngineInterface, sprite: string, url: string): Promise<RemoteRow[]> {
153 const res = await $.process.run([cwRemote($), 'list', '-s', sprite], { timeoutMs: 60_000 }).catch(() => null)
154 if (res?.exitCode !== 0) return remoteRows.get(sprite) ?? []
155 const rows = parseRemoteList(res.stdout, sprite, url)
156 remoteRows.set(sprite, rows)
157 return rows
158}
159
160/**
161 * Every sprite a remote worker of ours ran on, live or not (a reload empties the cache, which marks
162 * them gone), plus this repo's sprite under launch: remote, so a fresh session sees its workers.
163 * Never called from the 5 s poll.
164 */
165async function refreshRemote($: EngineInterface) {
166 const sprites = new Map<string, string>()
167 for (const l of (await read($, picker)).launched) if (l.remote) sprites.set(l.remote.sprite, l.remote.url)
168 if (cfg.launch === 'remote') {
169 // a local read of the git origin: no sprite is asked
170 const res = await $.process.run([cwRemote($), 'sprite'], { cwd: await $.session.cwd() }).catch(() => null)
171 const own = res?.exitCode === 0 ? res.stdout.trim() : ''
172 if (/^mcp-cw-[a-z0-9-]+$/.test(own) && !sprites.has(own)) sprites.set(own, '')
173 }
174 for (const [sprite, url] of sprites) await listRemote($, sprite, url)
175}
176
177/**
178 * launch: remote. cw-remote owns everything remote-invariant (bypass, flags, env, preamble, push,
179 * checkpoint); this builds the task prompt and hands it over. A refusal throws: no local fallback.
180 */
181async function launchRemote($: EngineInterface, p: Picker, name: string, task: string, over: LaunchOpts): Promise<{ l: Launch; isTabOpen: boolean | null }> {
182 if (cfg.provider === 'bedrock') throw new Error("remote workers run through the sprite's OpenRouter Connector; set provider to openrouter in /config")
183 const cwd = await $.session.cwd()
184 const cr = cwRemote($)
185 let prompt = task
186 if (p.team) {
187 // teammates are the sprite's workers: this laptop session is no one's lead unless asked
188 const res = await $.process.run([cr, 'list'], { cwd, timeoutMs: 60_000 }).catch(() => null)
189 const mates = res?.exitCode === 0 ? parseRemoteList(res.stdout, 'mcp-cw-x', '').map(r => r.meta.name) : []
190 prompt = `${teamPreamble({ name, teammates: mates, lead: over.lead ?? null })}\n\nTask: ${task || 'wait for messages from teammates or the lead.'}`
191 }
192 const tmp = ((await $.env.get('TMPDIR').catch(() => undefined)) || '/tmp').replace(/\/+$/, '')
193 const file = `${tmp}/cw-prompt-${name}.txt`
194 await $.fs.write(file, prompt)
195 const sha = (await $.process.run(['git', '-C', cwd, 'rev-parse', 'HEAD']).catch(() => null))?.stdout.trim() ?? ''
196 if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error(`remote workers start from a commit: ${cwd} has none (or isn't a git repo)`)
197 const ctx = p.models.find(m => m.id === p.model)?.contextTokens
198 const startedAt = await $.clock.now()
199 const res = await $.process.run([cr, 'launch', name, p.model, sha, file, ...(ctx ? [String(ctx)] : [])], { cwd, timeoutMs: 120_000 })
200 if (res.exitCode !== 0) throw new Error(res.stderr.trim() || `cw-remote launch exited ${res.exitCode}`)
201 const sprite = res.stdout.match(/^remote=(\S+)/m)?.[1] ?? ''
202 const url = res.stdout.match(/^url=(\S*)/m)?.[1] ?? ''
203 if (!sprite) throw new Error(`cw-remote launch said: ${res.stdout.trim()}`)
204 const l: Launch = { name, model: p.model, mode: p.mode, pane: `${sprite}:${name}`, task, isLive: true, startedAt, cwd, remote: { sprite, url } }
205 await listRemote($, sprite, url)
206 let command = ''
207 try {
208 command = remoteAttachCommand(cr, sprite, name)
209 } catch {
210 return { l, isTabOpen: false }
211 }
212 return { l, isTabOpen: await openTab($, name, command, true) }
213}
214
215/**
216 * Opens a background tab attached to the worker's session: in Herdr or cmux (when this session
217 * runs inside one) through its CLI, else in Ghostty through AppleScript. False → the caller says CMD+T + crew.
218 */
219async function openTab($: EngineInterface, name: string, command: string, isRemote = false): Promise<boolean> {
220 // Herdr first: it runs inside cmux or Ghostty, so when it's here it's the layer you're looking at.
221 const herdrWs = await $.env.get('HERDR_WORKSPACE_ID').catch(() => undefined)
222 // ponytail: a remote attach fights Herdr's own keys (owner accepted), so remote gets no Herdr tab
223 if (herdrWs && isRemote) return false
224 if (herdrWs) {
225 const herdr = (await $.env.get('HERDR_BIN_PATH').catch(() => undefined)) || 'herdr'
226 const made = await $.process.run([herdr, 'tab', 'create', '--workspace', herdrWs, '--label', name], { timeoutMs: 10_000 }).catch(() => null)
227 const pane = made?.exitCode === 0 ? herdrPaneId(made.stdout) : null
228 if (!pane) return false
229 const ran = await $.process.run([herdr, 'pane', 'run', pane, command], { timeoutMs: 10_000 }).catch(() => null)
230 return ran?.exitCode === 0
231 }
232 if (await $.env.get('CMUX_WORKSPACE_ID').catch(() => undefined)) {
233 const cmux = (await $.env.get('CMUX_BUNDLED_CLI_PATH').catch(() => undefined)) || 'cmux'
234 const made = await $.process.run([cmux, 'new-surface', '--type', 'terminal', '--focus', 'false'], { timeoutMs: 10_000 }).catch(() => null)
235 const ref = made?.exitCode === 0 ? surfaceRef(made.stdout) : null
236 if (!ref) return false
237 await $.process.run([cmux, 'rename-tab', '--surface', ref, name], { timeoutMs: 10_000 }).catch(() => null)
238 const sent = await $.process.run([cmux, 'send', '--surface', ref, `${command}\n`], { timeoutMs: 10_000 }).catch(() => null)
239 return sent?.exitCode === 0
240 }
241 // The first run waits on macOS's "allow control of Ghostty?" dialog; past 15s (or refused) → manual CMD+T + crew.
242 const tab = await $.process.run(['osascript', '-e', ghosttyTabScript(command)], { timeoutMs: 15_000 }).catch(() => null)
243 return tab?.exitCode === 0
244}
245
246/** Puts the `crew` picker on PATH (~/.local/bin), never over someone else's `crew`. */
247async function installCrew($: EngineInterface) {
248 const home = (await $.env.get('HOME').catch(() => undefined)) ?? ''
249 const src = await $.fs.read(`${$.plugin.root}/bin/crew`).catch(() => null)
250 if (!home || typeof src !== 'string') return
251 // cw-remote too, for crew and driver-seat's cw: a link that follows plugin updates, never over a real file
252 await $.process
253 .run(['zsh', '-fc', '[[ -L $1 || ! -e $1 ]] && mkdir -p ${1:h} && ln -sfn $2 $1', '_', `${home}/.local/bin/cw-remote`, cwRemote($)])
254 .catch(() => null)
255 const dest = `${home}/.local/bin/crew`
256 const cur = await $.fs.read(dest).catch(() => null)
257 if (cur === src || (typeof cur === 'string' && !cur.includes(CREW_MARK))) return
258 await $.process.run(['mkdir', '-p', `${home}/.local/bin`])
259 await $.fs.write(dest, src)
260 await $.process.run(['chmod', '+x', dest])
261}
262
263/** Launches, records it for the views, and says where it went (the picker's flash and the tool's answer). */
264async function startWorker($: EngineInterface, task: string, over: LaunchOpts = {}): Promise<{ l: Launch; where: string }> {
265 const { l, isTabOpen } = await launch($, task, over)
266 const short = l.name.slice(3)
267 const where = l.remote
268 ? isTabOpen
269 ? `${l.name} is running on the sprite. Phone: ${l.remote.url} · desk: its new tab, or crew ${short}`
270 : `${l.name} is running on the sprite. No tab here: open ${l.remote.url} in a browser, or crew ${short}`
271 : isTabOpen === null
272 ? `${l.name} started in tmux cw:workers. Watch: tmux new -A -s cw`
273 : isTabOpen
274 ? `${l.name} opened in a new tab (or: crew ${l.name.slice(3)})`
275 : `${l.name} is running. Open it: CMD+T, then crew ${l.name.slice(3)}`
276 await update($, picker, x => ({ ...x, launched: [l, ...x.launched].slice(0, 12), flash: { text: where, isError: false } }))
277 if (isTabOpen === false && !l.remote) $.ui.toast(`${l.name}: CMD+T, then crew ${l.name.slice(3)}`)
278 return { l, where }
279}
280
281const TOOL = 'workers'
282const TOOL_SPEC = {
283 name: TOOL,
284 description: [
285 'Run Claude Code worker sessions (cheap-worker), the same as the /worker picker.',
286 'launch: start one; task (what to do), optional model (OpenRouter slug, or sonnet/opus/haiku on Bedrock), mode (edits | auto | ask), team (true: knows its teammates and reports to this session by message), name (e.g. "auth-fix" → cw-auth-fix).',
287 'list: running workers (name, model, mode, busy, last output lines).',
288 'send: message a worker by name (to, text); its reply arrives here as a new message.',
289 'close: stop a worker by name.',
290 ].join('\n'),
291 inputSchema: {
292 type: 'object',
293 properties: {
294 action: { type: 'string', enum: ['launch', 'list', 'send', 'close'] },
295 task: { type: 'string', description: 'launch: what the worker should do (empty: start idle)' },
296 model: { type: 'string', description: 'launch: model; defaults to the picker\'s current one' },
297 mode: { type: 'string', enum: ['edits', 'auto', 'ask'], description: 'launch: permission mode; default the picker\'s' },
298 team: { type: 'boolean', description: 'launch: team (true) or solo (false); default the picker\'s' },
299 lead: { type: 'string', description: 'launch (remote team): the remote worker its teammates report to' },
300 name: { type: 'string', description: 'launch: the worker\'s name; close/send also accept it' },
301 to: { type: 'string', description: 'send: the worker\'s name' },
302 text: { type: 'string', description: 'send: the message' },
303 },
304 required: ['action'],
305 },
306 isDeferred: false,
307}
308
309/** The tool's answer for one call: plain text the model reads. */
310async function runTool($: EngineInterface, i: Record<string, unknown>): Promise<string> {
311 const str = (k: string) => (typeof i[k] === 'string' ? (i[k] as string).trim() : '')
312 const action = str('action')
313 if (action === 'launch') {
314 const mode = str('mode') ? toMode(str('mode')) : undefined
315 if (mode === null) return `Unknown mode "${str('mode')}": use edits, auto or ask.`
316 const name = str('name') ? workerName(str('name')) : undefined
317 if (name === null) return `Can't make a worker name from "${str('name')}": use letters, digits and hyphens.`
318 let model = str('model') || undefined
319 if (model && cfg.provider === 'bedrock' && !model.includes('/')) model = `anthropic/${model}`
320 const team = typeof i.team === 'boolean' ? i.team : (await read($, picker)).team
321 const lead = str('lead') ? workerName(str('lead')) : undefined
322 if (lead === null) return `Can't make a worker name from lead "${str('lead')}".`
323 const { l, where } = await startWorker($, str('task'), { model, mode, team, name, ...(lead && { lead }) })
324 return `Launched ${l.name}: ${l.model}, ${modeWord(l)} mode, ${team ? 'team' : 'solo'}.\n${where}\nMessage it with action "send", to "${l.name}".`
325 }
326 await refreshRemote($)
327 await refreshLive($)
328 const active = (await read($, picker)).active ?? []
329 const find = (raw: string) => {
330 const n = workerName(raw)
331 return active.find(a => a.name === n || a.name === raw)
332 }
333 if (action === 'list') {
334 if (active.length === 0) return 'No workers running.'
335 return active
336 .map(a => `${a.name} · ${a.launch?.model ?? '?'} · ${modeWord(a.launch)} · ${a.isClosing ? 'closing' : a.isBusy ? 'working' : 'idle'}${a.peek.length ? `\n ${a.peek.join('\n ')}` : ''}`)
337 .join('\n')
338 }
339 if (action === 'send') {
340 const w = find(str('to') || str('name'))
341 if (!w) return `No running worker named "${str('to') || str('name')}". Running: ${active.map(a => a.name).join(', ') || 'none'}.`
342 if (!str('text')) return 'send needs text.'
343 const res = await deliver($, w.name, str('text'))
344 return res.isDelivered ? `Delivered to ${w.name}.` : `Not delivered to ${w.name}: ${res.reason}.`
345 }
346 if (action === 'close') {
347 const w = find(str('name') || str('to'))
348 if (!w) return `No running worker named "${str('name') || str('to')}".`
349 await closeWorker($, w.pane)
350 if (w.launch?.remote) return `Closing ${w.name} on ${w.launch.remote.sprite}: asked it to /exit; its window, watcher and worktree go after ${FORCE_AFTER_MS / 1000}s. Branch cw/${w.name} stays on origin.`
351 return `Closing ${w.name}: asked it to /exit; its pane is killed after ${FORCE_AFTER_MS / 1000}s if it's still there.`
352 }
353 return `Unknown action "${action}": use launch, list, send or close.`
354}
355
356// This session's name as other sessions address it, from the ListAgents tool.
357async function leadName($: EngineInterface): Promise<string | null> {
358 const res = await $.tool.call({ tool: 'ListAgents' } as never).catch(() => null)
359 const r = res as { result?: unknown } | null
360 const text = typeof r?.result === 'string' ? r.result : JSON.stringify(r?.result ?? '')
361 return leadFrom(text)
362}
363
364async function logMessage($: EngineInterface, m: Msg) {
365 await update($, picker, x => ({ ...x, messages: [...(x.messages ?? []), m].slice(-MAX_MESSAGES) }))
366}
367
368/** One message to a worker: by session message locally, through cw-remote send for a remote one. Logged either way. */
369async function deliver($: EngineInterface, to: string, text: string): Promise<{ isDelivered: boolean; reason: string }> {
370 const r = (await read($, picker)).launched.find(l => l.name === to && l.remote)?.remote
371 let res: { isDelivered: boolean; reason: string }
372 if (r) {
373 const tmp = ((await $.env.get('TMPDIR').catch(() => undefined)) || '/tmp').replace(/\/+$/, '')
374 const file = `${tmp}/cw-send-${to}.txt`
375 await $.fs.write(file, text)
376 const ran = await $.process.run([cwRemote($), 'send', to, file, '-s', r.sprite], { timeoutMs: 60_000 }).catch(err => ({ exitCode: 1, stdout: '', stderr: String(err) }))
377 res = { isDelivered: ran.exitCode === 0, reason: ran.stderr.trim() || 'cw-remote send failed' }
378 } else {
379 const sent = await $.session.send({ to, text }).catch(err => ({ isDelivered: false as const, reason: String(err) }))
380 res = { isDelivered: sent.isDelivered, reason: 'reason' in sent ? String(sent.reason) : 'unknown' }
381 }
382 await logMessage($, { dir: 'out', peer: to, text, at: await $.clock.now(), ...(res.isDelivered ? {} : { isFailed: true }) })
383 return res
384}
385
386async function sendTo($: EngineInterface, to: string, text: string) {
387 const res = await deliver($, to, text)
388 if (!res.isDelivered) $.ui.toast(`Not delivered to ${to}: ${res.reason}`)
389}
390
391// tmux is the source of truth: every labelled pane on the server (session `cw`'s
392// tiles and tabs-mode sessions `cw-*` alike), this mod's
393// workers and driver-seat's alike, each with a peek at its last output lines.
394async function refreshLive($: EngineInterface) {
395 const res = await tmux($, ['list-panes', '-a', '-F', META_FORMAT]).catch(() => null)
396 const panes = res?.exitCode === 0 ? parseMeta(res.stdout) : []
397 // Workers another session launched (or launched before pane metadata existed): learn the
398 // model from the startup banner once, save it on the pane, and adopt them here.
399 const known = new Set((await read($, picker)).launched.map(l => l.pane))
400 const adopted: Launch[] = []
401 for (const m of panes) {
402 if (known.has(m.pane)) continue
403 let model = m.model
404 if (!model) {
405 const full = (await tmux($, ['capture-pane', '-p', '-J', '-S', '-', '-t', m.pane]).catch(() => null))?.stdout ?? ''
406 model = bannerModel(full) ?? ''
407 if (model) await tmux($, ['set', '-p', '-t', m.pane, '@cw_model', model])
408 }
409 if (!model) continue // not a cheap worker we can describe (e.g. driver-seat's): stays external
410 const mode = (['acceptEdits', 'auto', 'default'] as const).find(x => x === m.mode) ?? 'acceptEdits'
411 adopted.push({ name: m.name, model, mode, pane: m.pane, task: m.task, isLive: true, ...(m.start ? { startedAt: m.start } : {}), ...(m.cwd ? { cwd: m.cwd } : {}) })
412 }
413 // remote rows come from the cache only: this runs every 5 s and must never wake a sprite
414 const remote = [...remoteRows.values()].flat()
415 const knownNow = new Set([...known, ...adopted.map(a => a.pane)])
416 for (const r of remote) {
417 if (knownNow.has(r.meta.pane)) continue
418 adopted.push({ name: r.meta.name, model: r.meta.model, mode: 'acceptEdits', pane: r.meta.pane, task: r.meta.task, isLive: true, remote: r.remote, ...(r.meta.start ? { startedAt: r.meta.start } : {}) })
419 }
420 if (adopted.length > 0) await update($, picker, x => ({ ...x, launched: [...adopted, ...x.launched].slice(0, 24) }))
421 const p = await read($, picker)
422 const active: Active[] = []
423 for (const { pane, name } of panes) {
424 const cap = (await tmux($, ['capture-pane', '-p', '-J', '-t', pane]).catch(() => null))?.stdout ?? ''
425 active.push({
426 pane,
427 name,
428 launch: p.launched.find(l => l.pane === pane) ?? null,
429 peek: peekLines(cap),
430 isClosing: p.closing.includes(pane),
431 isBusy: isWorking(cap),
432 })
433 }
434 for (const r of remote)
435 active.push({
436 pane: r.meta.pane,
437 name: r.meta.name,
438 launch: p.launched.find(l => l.pane === r.meta.pane) ?? null,
439 peek: peekLines(r.lines.join('\n')),
440 isClosing: p.closing.includes(r.meta.pane),
441 isBusy: r.isBusy,
442 })
443 const live = new Set([...panes.map(x => x.pane), ...remote.map(r => r.meta.pane)])
444 const now = await $.clock.now()
445 await update($, picker, x => ({
446 ...x,
447 active,
448 closing: x.closing.filter(c => live.has(c)),
449 launched: x.launched.map(l => {
450 const isLive = live.has(l.pane)
451 return { ...l, isLive, ...(!isLive && l.endedAt === undefined ? { endedAt: now } : {}) }
452 }),
453 }))
454 await refreshStats($)
455 $.ui.status(active.length > 0 ? `workers: ${active.length} running` : undefined)
456}
457
458// Tokens, ≈cost and context fill, read from each worker's own transcript: live
459// workers every refresh, a finished one once more after it ends.
460async function refreshStats($: EngineInterface) {
461 const p = await read($, picker)
462 const home = (await $.env.get('HOME').catch(() => undefined)) ?? ''
463 const now = await $.clock.now()
464 const next: Record<string, WStats> = { ...(p.stats ?? {}) }
465 const found: Record<string, string> = {}
466 for (const l of p.launched) {
467 // a finished worker gets 15s more of reads, so its last reply is counted
468 const isSettled = !l.isLive && now - (l.endedAt ?? now) > 15_000 && next[l.name] !== undefined
469 // a remote worker's transcript is on its sprite: searching the laptop every 5 s finds nothing
470 if (isSettled || l.remote || !l.cwd || !home) continue
471 let file = l.transcript
472 if (!file) {
473 const dir = projectDir(home, l.cwd)
474 const hit = await $.process.run(['grep', '-rl', '--include=*.jsonl', '-e', `"agentName":"${l.name}"`, dir]).catch(() => null)
475 file = hit?.stdout.split('\n').find(Boolean)
476 if (!file) continue
477 found[l.name] = file
478 }
479 const text = await $.fs.read(file).catch(() => null)
480 if (typeof text !== 'string') continue
481 const u = usageFrom(text)
482 const model = p.models.find(m => m.id === l.model)
483 next[l.name] = {
484 tokens: tokensOf(u),
485 cost: costOf(u, model),
486 ctxPct: model?.contextTokens ? Math.round((100 * u.lastPrompt) / model.contextTokens) : null,
487 }
488 }
489 await update($, picker, x => ({
490 ...x,
491 stats: next,
492 launched: x.launched.map(l => (found[l.name] ? { ...l, transcript: found[l.name] } : l)),
493 }))
494}
495
496// Asks the worker to /exit (its transcript closes cleanly), then kills the pane
497// if it's still there: a worker mid-turn only reads /exit once the turn ends.
498async function closeWorker($: EngineInterface, pane: string) {
499 await update($, picker, x => ({ ...x, closing: [...x.closing.filter(c => c !== pane), pane] }))
500 const r = (await read($, picker)).launched.find(l => l.pane === pane)?.remote
501 if (r) {
502 // cw-remote does the /exit, the wait, the kill and the cleanup on the sprite; the branch stays
503 const name = pane.slice(r.sprite.length + 1)
504 await $.process.run([cwRemote($), 'close', name, '-s', r.sprite], { timeoutMs: 60_000 }).catch(() => null)
505 remoteRows.set(r.sprite, (remoteRows.get(r.sprite) ?? []).filter(x => x.meta.pane !== pane))
506 await refreshLive($)
507 return
508 }
509 await tmux($, ['send-keys', '-t', pane, 'C-u'])
510 await tmux($, ['send-keys', '-t', pane, '-l', '/exit'])
511 await tmux($, ['send-keys', '-t', pane, 'Enter'])
512 await refreshLive($)
513 $.clock.after(FORCE_AFTER_MS, async () => {
514 const still = (await tmux($, ['list-panes', '-a', '-F', '#{pane_id}'])).stdout.split('\n').includes(pane)
515 if (still) {
516 // claude survives the hangup kill-pane sends, so stop its process first
517 // (the pane exec'd into claude: the pane's pid is the worker's).
518 const pid = (await tmux($, ['display-message', '-p', '-t', pane, '#{pane_pid}'])).stdout.trim()
519 if (/^\d+$/.test(pid)) await $.process.run(['kill', pid])
520 await tmux($, ['kill-pane', '-t', pane])
521 }
522 await refreshLive($)
523 })
524}
525
526async function openView($: EngineInterface) {
527 await refreshRemote($)
528 await refreshLive($)
529 await $.ui.open({ id: VIEW, title: 'Workers' })
530}
531
532export const register: Register = (on, options) => {
533 const o = (options ?? {}) as { provider?: unknown; launch?: unknown }
534 cfg.provider = o.provider === 'bedrock' ? 'bedrock' : 'openrouter'
535 cfg.launch = o.launch === 'tabs' || o.launch === 'remote' ? o.launch : 'panes'
536
537 on('session.start', async ($, e, next) => {
538 const via = cfg.provider === 'bedrock' ? 'Bedrock Claude' : 'cheap OpenRouter'
539 await $.command.register({ name: 'worker', description: `Spin up a ${via} worker (${cfg.launch === 'tabs' ? 'opens a terminal tab' : cfg.launch === 'remote' ? "on this repo's sprite" : 'tmux pane'})` })
540 await $.command.register({ name: 'workers', description: 'See and close the active workers' })
541 const pins = toPins(await $.store.get('pins').catch(() => null))
542 await update($, picker, p => {
543 const base = { ...DEFAULTS, ...p, pins, model: pins[0] ?? p.model ?? DEFAULTS.model }
544 // switching provider: a model the other provider can't run falls back to its default
545 if (cfg.provider === 'bedrock')
546 return { ...base, models: BEDROCK_MODELS, model: BEDROCK_MODELS.some(m => m.id === base.model) ? base.model : defaultModelFor('bedrock') }
547 return BEDROCK_MODELS.some(m => m.id === base.model) ? { ...base, models: [], model: DEFAULT_MODEL } : base
548 })
549 void installCrew($)
550 await $.tool.register(TOOL_SPEC as never).catch(() => null)
551 // ponytail: polls tmux; one list-panes plus a capture per worker, fine for a handful
552 $.clock.every(5000, () => refreshLive($))
553 return next(e)
554 })
555
556 // The workers tool (TOOL_SPEC): answered here, never passed on (nothing beneath serves it).
557 on('tool.call', { tool: 'mcp__cheap-worker__workers' } as never, async ($, e) => {
558 try {
559 return { result: await runTool($, e as unknown as Record<string, unknown>) } as never
560 } catch (err) {
561 return { result: `Failed: ${err instanceof Error ? err.message : String(err)}` } as never
562 }
563 }).catch(() => ({ result: 'Failed: the workers tool hit an internal error.' }) as never)
564
565 on('command.run', { command: 'worker' }, async $ => {
566 await openPane($)
567 return { text: 'Cheap worker pane open.' }
568 })
569
570 // Messages other sessions send here: logged for the Workers view and toasted,
571 // then passed on untouched so the model still reads them.
572 on('session.receive', async ($, e, next) => {
573 const kind = (e.origin as { kind: string }).kind
574 if (e.agentId === undefined && (kind === 'peer' || kind === 'peer-send-message')) {
575 const { from, body } = parsePeer(e.text)
576 await logMessage($, { dir: 'in', peer: from, text: body, at: await $.clock.now() })
577 $.ui.toast(`✉ ${from}: ${body.length > 60 ? `${body.slice(0, 59)}…` : body}`)
578 }
579 return next(e)
580 })
581
582 on('command.run', { command: 'workers' }, async $ => {
583 await openView($)
584 return { text: 'Workers view open.' }
585 })
586
587 // Footer button, bottom right beside quick-settings' ⚙: the OpenRouter mark
588 // (Ghostty/kitty draw it; elsewhere a lime dot) and a live worker count.
589 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
590 const below = await next(e)
591 const els = $.ui.resolve(e)
592 const { Box, Button, Text } = els
593 const Svg = e.surface !== 'terminal' && 'Svg' in els ? els.Svg : null
594 const running = (await read($, picker)).active?.length ?? 0
595 if (Svg && !iconsSvg.has('openrouter')) {
596 const svg = await $.fs.read(`${$.plugin.root}/assets/providers-svg/openrouter.svg`).catch(() => null)
597 iconsSvg.set('openrouter', typeof svg === 'string' ? svg : '')
598 }
599 const orSvg = iconsSvg.get('openrouter')
600 const mark =
601 cfg.provider === 'bedrock' ? (
602 <Text color="#d97757">✻</Text>
603 ) : Svg && orSvg ? (
604 <Svg key="or-mark" source={orSvg} width={14} height={14} alt="OpenRouter" />
605 ) : (
606 <Text color={OR_LIME}>◉</Text>
607 )
608 return (
609 <Box justifyContent="space-between">
610 <Box flexGrow={1}>{below}</Box>
611 <Box key="worker-chip" columnGap={1} marginLeft={2}>
612 {mark}
613 <Button key="worker-open" plain label="worker" hover={{ color: OR_LIME, bold: true }} onPress={() => openPane($)} />
614 {running > 0 && (
615 <Button key="workers-view" plain label={`· ${running} live`} hover={{ color: OR_LIME, bold: true }} onPress={() => openView($)} />
616 )}
617 </Box>
618 </Box>
619 )
620 })
621
622 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
623 const els = $.ui.resolve(e)
624 const { Box, Button, Text } = els
625 // mobile draws no Input: text boxes are left out there
626 const Input = 'Input' in els ? els.Input : null
627 const p = await read($, picker)
628 const info = (id: string) => p.models.find(m => m.id === id)
629 const isBedrock = cfg.provider === 'bedrock'
630 const priceOf = (id: string) => (isBedrock ? 'via Amazon Bedrock' : price(info(id)))
631 const matches = search(p.models, p.query)
632 const choices =
633 cfg.provider === 'bedrock' ? BEDROCK_MODELS.map(m => m.id) : choicesFor(p.models, p.query, p.pins, p.recent)
634 const choose = (id: string) =>
635 update($, picker, x => ({ ...x, model: id, recent: [id, ...x.recent.filter(r => r !== id)].slice(0, 4) }))
636
637 return (
638 <Box flexDirection="column" gap={1} paddingX={1}>
639 <Box flexDirection="column">
640 <Text bold color={ACCENT}>Model</Text>
641 <Box justifyContent="space-between">
642 <Text>
643 <Text bold>{p.model}</Text>
644 <Text dimColor> {priceOf(p.model)}</Text>
645 {isRetired(p.models, p.model) && <Text color="#e5534b"> not in catalog: retired?</Text>}
646 </Text>
647 {!isBedrock && <Button
648 key="refresh"
649 plain
650 dimColor
651 label={`↻ refresh${p.models.length > 0 ? ` (${p.models.length})` : ''}`}
652 onPress={async () => {
653 const ok = await loadModels($)
654 const n = (await read($, picker)).models.length
655 await update($, picker, x => ({
656 ...x,
657 flash: ok ? { text: `Catalog refreshed: ${n} tool-capable models.`, isError: false } : { text: 'OpenRouter unreachable; kept the old list.', isError: true },
658 }))
659 }}
660 />}
661 </Box>
662 {Input && !isBedrock && (
663 <Input
664 key="query"
665 placeholder={p.models.length > 0 ? `search ${p.models.length} tool-capable models…` : 'loading models… (or type a slug, Enter)'}
666 value={p.query}
667 onInput={(value: string) => update($, picker, x => ({ ...x, query: value }))}
668 onSubmit={(value: string) => (matches[0] ? choose(matches[0].id) : choose(value.trim()))}
669 />
670 )}
671 <Box flexDirection="column">
672 {choices.map(id => (
673 <Box key={`row-${id}`} columnGap={1}>
674 <Button key={`pin-${id}`} plain label={p.pins.includes(id) ? '★' : '☆'} onPress={() => togglePin($, id)} />
675 <Button
676 key={`m-${id}`}
677 plain
678 dimColor={id !== p.model}
679 label={`${id === p.model ? '●' : '○'} ${id} ${isRetired(p.models, id) ? '✗ retired?' : priceOf(id)}`}
680 onPress={() => choose(id)}
681 />
682 </Box>
683 ))}
684 </Box>
685 </Box>
686
687 <Box flexDirection="column">
688 <Text bold color={ACCENT}>Permissions</Text>
689 <Box columnGap={1}>
690 {MODES.map(m => (
691 <Button
692 key={`mode-${m.value}`}
693 label={`${m.value === p.mode ? '●' : '○'} ${m.label}`}
694 variant={m.value === p.mode ? 'primary' : 'secondary'}
695 onPress={() => update($, picker, x => ({ ...x, mode: m.value }))}
696 />
697 ))}
698 </Box>
699 <Text dimColor>{MODES.find(m => m.value === p.mode)?.note}</Text>
700 </Box>
701
702 <Box flexDirection="column">
703 <Text bold color={ACCENT}>Team</Text>
704 <Box columnGap={1}>
705 <Button
706 key="team-toggle"
707 label={p.team ? '● team' : '○ solo'}
708 variant={p.team ? 'primary' : 'secondary'}
709 onPress={() => update($, picker, x => ({ ...x, team: !x.team }))}
710 />
711 </Box>
712 <Text dimColor>
713 {p.team
714 ? `knows its teammates${(p.active ?? []).length > 0 ? ` (${p.active.map(a => a.name).join(', ')})` : ''} and reports to this session via SendMessage`
715 : 'works alone; you can still message it from the Workers view'}
716 </Text>
717 </Box>
718
719 <Box flexDirection="column">
720 <Text bold color={ACCENT}>Task</Text>
721 {Input && (
722 <Input
723 key="task"
724 placeholder="what should the worker do? (Enter launches; empty opens it idle)"
725 submitLabel="Launch"
726 onSubmit={async (value: string) => {
727 try {
728 await startWorker($, value.trim())
729 } catch (err) {
730 const text = err instanceof Error ? err.message : String(err)
731 await update($, picker, x => ({ ...x, flash: { text, isError: true } }))
732 }
733 }}
734 />
735 )}
736 </Box>
737
738 {p.flash && <Text color={p.flash.isError ? '#e5534b' : '#57ab5a'}>{p.flash.isError ? '✗' : '✓'} {p.flash.text}</Text>}
739
740 <Box key="to-view">
741 <Button
742 key="open-view"
743 plain
744 dimColor={p.active.length === 0}
745 label={p.active.length > 0 ? `◉ ${p.active.length} live worker${p.active.length > 1 ? 's' : ''} · view & close →` : '○ no live workers · view →'}
746 hover={{ color: OR_LIME, bold: true }}
747 onPress={() => openView($)}
748 />
749 </Box>
750 </Box>
751 )
752 })
753
754 on('ui.render', { component: 'Pane', requestId: VIEW }, async ($, e) => {
755 const els = $.ui.resolve(e)
756 const { Box, Button, Text } = els
757 const Input = 'Input' in els ? els.Input : null
758 const Svg = e.surface !== 'terminal' && 'Svg' in els ? els.Svg : null
759 const p = await read($, picker)
760 const now = await $.clock.now()
761 const stats = p.stats ?? {}
762 if (pixels === null) {
763 const raw = await $.fs.read(`${$.plugin.root}/assets/providers-px.json`).catch(() => null)
764 try {
765 pixels = typeof raw === 'string' ? JSON.parse(raw) : {}
766 } catch {
767 pixels = {}
768 }
769 }
770 const hhmm = (t: number) => {
771 const d = new Date(t)
772 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
773 }
774
775 // Provider marks, read once per load ('' = no logo shipped: letter badge).
776 const vendors = new Set([...(p.active ?? []), ...p.launched].map(w => vendorOf(('launch' in w ? w.launch?.model : w.model) ?? '')))
777 for (const v of vendors) {
778 if (v && Svg && !iconsSvg.has(v)) {
779 const svg = await $.fs.read(`${$.plugin.root}/assets/providers-svg/${v}.svg`).catch(() => null)
780 iconsSvg.set(v, typeof svg === 'string' ? svg : '')
781 }
782 }
783
784 const running = p.active ?? []
785 const finished = p.launched.filter(l => !l.isLive)
786 const all = [...running.map(w => w.launch).filter((l): l is Launch => l !== null), ...finished]
787 const totals = all.reduce(
788 (t, l) => {
789 const s = stats[l.name]
790 return { cost: t.cost + (s?.cost ?? 0), tokens: t.tokens + (s?.tokens ?? 0) }
791 },
792 { cost: 0, tokens: 0 },
793 )
794 const firstStart = Math.min(...all.map(l => l.startedAt ?? now), now)
795 const lastEnd = running.length > 0 ? now : Math.max(...finished.map(l => l.endedAt ?? now), firstStart)
796
797 const avatar = (model: string, key: string) => {
798 const v = vendorOf(model)
799 const svg = iconsSvg.get(v)
800 const grid = e.surface === 'terminal' ? pixels?.[v] : undefined
801 return grid ? (
802 <Box key={`av-${key}`} flexDirection="column" width={8}>
803 {[0, 2, 4, 6].map(y => (
804 <Text key={`av-${key}-${y}`}>
805 {grid[y]!.map((top, x) => {
806 const bot = grid[y + 1]![x] ?? null
807 return top && bot ? (
808 <Text key={`px-${x}`} color={top} backgroundColor={bot}>▀</Text>
809 ) : top ? (
810 <Text key={`px-${x}`} color={top}>▀</Text>
811 ) : bot ? (
812 <Text key={`px-${x}`} color={bot}>▄</Text>
813 ) : (
814 ' '
815 )
816 })}
817 </Text>
818 ))}
819 </Box>
820 ) : Svg && svg ? (
821 <Svg key={`av-${key}`} source={svg} width={32} height={32} alt={`${v} logo`} />
822 ) : (
823 <Box key={`av-${key}`} width={8} height={4} justifyContent="center" alignItems="center" backgroundColor="#2d333b">
824 <Text bold color={OR_LIME}>{(v || '?').slice(0, 1).toUpperCase()}</Text>
825 </Box>
826 )
827 }
828 const tile = (label: string, value: string) => (
829 <Box key={`tile-${label}`} flexDirection="column" flexGrow={1} borderStyle="round" borderColor="#3b3f4a" paddingX={1}>
830 <Text dimColor>{label}</Text>
831 <Text bold>{value}</Text>
832 </Box>
833 )
834 const bar = (pct: number, color: string, width = 34) => {
835 const fill = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
836 return (
837 <Text>
838 <Text color={color}>{'━'.repeat(fill)}</Text>
839 <Text color="#3b3f4a">{'━'.repeat(width - fill)}</Text>
840 </Text>
841 )
842 }
843 const statLine = (l: Launch | null, end: number) => {
844 const s = l ? stats[l.name] : undefined
845 const parts = [
846 s?.ctxPct != null ? `ctx ${s.ctxPct}%` : null,
847 s ? kfmt(s.tokens) : null,
848 s?.cost != null ? `≈$${s.cost.toFixed(2)}` : null,
849 l?.startedAt ? clockDur(end - l.startedAt) : null,
850 ].filter(Boolean)
851 return parts.join(' · ')
852 }
853 const title = (l: Launch | null, name: string) => {
854 const t = l?.task?.split('\n')[0]?.trim()
855 return t ? (t.length > 48 ? `${t.slice(0, 47)}…` : t) : name
856 }
857 const subtitle = (l: Launch | null, name: string) =>
858 l ? (
859 <Text>
860 <Text color={MODE_COLOR[l.mode]}>{modeWord(l)}</Text>
861 <Text dimColor> {l.model.split('/')[1] ?? l.model} · {name}</Text>
862 </Text>
863 ) : (
864 <Text dimColor>{name} · driver-seat / external</Text>
865 )
866
867 return (
868 <Box flexDirection="column" gap={1} paddingX={1}>
869 <Box justifyContent="space-between">
870 <Text bold>Workers</Text>
871 <Button key="view-refresh" plain dimColor label="↻" onPress={() => refreshLive($)} />
872 </Box>
873
874 <Box columnGap={1}>
875 {tile('Cost', all.length > 0 ? `≈$${totals.cost.toFixed(2)}` : '—')}
876 {tile('Tokens', all.length > 0 ? kfmt(totals.tokens) : '—')}
877 {tile('Time', all.length > 0 ? clockDur(lastEnd - firstStart) : '—')}
878 </Box>
879
880 <Box flexDirection="column">
881 <Text dimColor>Running · {running.length}</Text>
882 {running.length === 0 && <Text dimColor> none. Launch one from the worker button.</Text>}
883 {running.map(w => {
884 const color = w.launch ? MODE_COLOR[w.launch.mode] : OR_LIME
885 const s = w.launch ? stats[w.launch.name] : undefined
886 return (
887 <Box key={`card-${w.pane}`} flexDirection="column" paddingY={0} marginTop={1}>
888 <Box columnGap={2}>
889 {avatar(w.launch?.model ?? '', w.pane)}
890 <Box flexDirection="column" flexGrow={1}>
891 <Box justifyContent="space-between">
892 <Text bold>{title(w.launch, w.name)}</Text>
893 <Text color={w.isClosing ? '#e8c46a' : w.isBusy ? '#57ab5a' : '#768390'}>
894 {w.isClosing ? '◌ closing' : w.isBusy ? '●' : '◌ idle'}
895 </Text>
896 </Box>
897 {subtitle(w.launch, w.name)}
898 <Box justifyContent="space-between">
899 <Text dimColor>{w.peek.at(-1)?.slice(0, 40) ?? 'starting…'}</Text>
900 <Text dimColor>{statLine(w.launch, now)}</Text>
901 </Box>
902 {bar(s?.ctxPct ?? 0, color)}
903 </Box>
904 </Box>
905 <Box columnGap={2} marginLeft={6}>
906 {Input && !w.isClosing && (
907 <Input
908 key={`msg-${w.pane}`}
909 placeholder={`message ${w.name}…`}
910 submitLabel="Send"
911 onSubmit={(value: string) => (value.trim() ? sendTo($, w.name, value.trim()) : undefined)}
912 />
913 )}
914 {!w.isClosing && (
915 <Button
916 key={`close-${w.pane}`}
917 plain
918 dimColor
919 label="✕ close"
920 hover={{ color: '#e5534b', bold: true }}
921 onPress={() => closeWorker($, w.pane)}
922 />
923 )}
924 </Box>
925 </Box>
926 )
927 })}
928 </Box>
929
930 {finished.length > 0 && (
931 <Box flexDirection="column">
932 <Box key="finished-head">
933 <Button
934 key="toggle-finished"
935 plain
936 dimColor
937 label={`${p.showFinished ? '▾' : '▸'} Finished · ${finished.length}`}
938 onPress={() => update($, picker, x => ({ ...x, showFinished: !x.showFinished }))}
939 />
940 </Box>
941 {p.showFinished &&
942 finished.map(l => (
943 <Box key={`done-${l.name}`} columnGap={2} marginTop={1}>
944 {avatar(l.model, `done-${l.name}`)}
945 <Box flexDirection="column" flexGrow={1}>
946 <Box justifyContent="space-between">
947 <Text bold>{title(l, l.name)}</Text>
948 <Text color="#57ab5a">✓</Text>
949 </Box>
950 {subtitle(l, l.name)}
951 <Box justifyContent="flex-end">
952 <Text dimColor>{statLine(l, l.endedAt ?? now)}</Text>
953 </Box>
954 {bar(100, MODE_COLOR[l.mode])}
955 </Box>
956 </Box>
957 ))}
958 </Box>
959 )}
960
961 {(p.messages ?? []).length > 0 && (
962 <Box flexDirection="column">
963 <Box justifyContent="space-between">
964 <Text dimColor>Messages · {(p.messages ?? []).length}</Text>
965 <Button key="msgs-clear" plain dimColor label="clear" onPress={() => update($, picker, x => ({ ...x, messages: [] }))} />
966 </Box>
967 {(p.messages ?? []).slice(-8).map((m, i) => (
968 <Text key={`m-${i}-${m.at}`} dimColor={m.dir === 'out'}>
969 <Text color={m.isFailed ? '#e5534b' : m.dir === 'in' ? OR_LIME : undefined}>{m.dir === 'in' ? '←' : m.isFailed ? '✗' : '→'}</Text>
970 {` ${hhmm(m.at)} ${m.peer}: ${m.text.length > 90 ? `${m.text.slice(0, 89)}…` : m.text}`}
971 </Text>
972 ))}
973 </Box>
974 )}
975
976 <Text dimColor>watch live: tmux new -A -s cw · ✕ sends /exit, force-closes after {FORCE_AFTER_MS / 1000}s</Text>
977 </Box>
978 )
979 })
980}
981hooks/worker.ts 312 lines1import type { Mode, OrModel } from '../types'
2
3export const DEFAULT_MODEL = 'deepseek/deepseek-v4.1-flash'
4
5/** Where workers' model calls go: OpenRouter (any model, your key) or Amazon Bedrock (Claude only). */
6export type Provider = 'openrouter' | 'bedrock'
7/** How workers are shown: panes tiled in tmux session `cw`, one tmux session each opened as a terminal tab, or on this repo's Fly Sprite. */
8export type LaunchMode = 'panes' | 'tabs' | 'remote'
9
10// Bedrock's choices: Claude Code's own aliases, written as slugs so the picker,
11// pins and the Anthropic avatar work unchanged. No catalog fetch, no prices.
12export const BEDROCK_MODELS: OrModel[] = ['sonnet', 'opus', 'haiku'].map(a => ({ id: `anthropic/${a}`, inPerM: 0, outPerM: 0 }))
13export const defaultModelFor = (p: Provider) => (p === 'bedrock' ? 'anthropic/sonnet' : DEFAULT_MODEL)
14
15/** A worker's name: `cw-` then lowercase letters, digits and inner hyphens (tmux session, tab label, crew). */
16export const isWorkerName = (s: string) => /^cw-[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/.test(s)
17
18/** A name asked for (`auth fix`, `cw-auth-fix`, `Auth_Fix`) as a worker name, or null when nothing usable is left. */
19export function workerName(raw: string): string | null {
20 const slug = raw.trim().toLowerCase().replace(/^cw-/, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '')
21 const name = `cw-${slug}`
22 return slug && isWorkerName(name) ? name : null
23}
24
25/** The permission modes as the picker words them (edits/auto/ask) or as Claude Code does. */
26export function toMode(raw: string): Mode | null {
27 const m = raw.trim().toLowerCase()
28 return m === 'edits' || m === 'acceptedits' ? 'acceptEdits' : m === 'auto' ? 'auto' : m === 'ask' || m === 'default' ? 'default' : null
29}
30
31/** `cmux new-surface` prints `OK surface:110 pane:38 workspace:14`: the new tab's ref. */
32export const surfaceRef = (stdout: string) => stdout.match(/\bsurface:\d+\b/)?.[0] ?? null
33
34/** What cmux types into the new tab: the attach, then Enter (a real newline; cmux sends text as typed). */
35export function attachLine(session: string, tmuxPath: string): string {
36 return `${attachCommand(session, tmuxPath)}\n`
37}
38
39/** The attach as one shell line; '=…' quoted, since zsh expands a bare =word to a command path. */
40export function attachCommand(session: string, tmuxPath: string): string {
41 if (!isWorkerName(session)) throw new Error(`not a worker session: ${session}`)
42 if (!/^\/[\w./+-]+$/.test(tmuxPath)) throw new Error(`not an absolute tmux path: ${tmuxPath}`)
43 return `${tmuxPath} attach -t '=${session}'`
44}
45
46/** `herdr tab create` answers JSON; the new tab's shell is `result.root_pane.pane_id` (e.g. `w5:p2`). */
47export function herdrPaneId(stdout: string): string | null {
48 try {
49 const id = (JSON.parse(stdout) as { result?: { root_pane?: { pane_id?: unknown } } }).result?.root_pane?.pane_id
50 return typeof id === 'string' && /^[\w:-]+$/.test(id) ? id : null
51 } catch {
52 return null
53 }
54}
55
56/** The attach to a remote worker, through cw-remote by absolute path (a tab's command gets no PATH). */
57export function remoteAttachCommand(cwRemote: string, sprite: string, name: string): string {
58 if (!/^\/[\w./+-]+$/.test(cwRemote)) throw new Error(`not an absolute cw-remote path: ${cwRemote}`)
59 if (!/^mcp-cw-[a-z0-9-]+$/.test(sprite)) throw new Error(`not a cw sprite: ${sprite}`)
60 if (!isWorkerName(name)) throw new Error(`not a worker name: ${name}`)
61 return `${cwRemote} attach ${name} -s ${sprite}`
62}
63
64/**
65 * AppleScript for Ghostty 1.3+: a new tab in the front window whose process is the
66 * attach itself, then re-selects the tab you were on so focus doesn't jump. The command is
67 * attachCommand(...) or remoteAttachCommand(...): absolute paths, since a tab gets no Homebrew PATH.
68 */
69export function ghosttyTabScript(command: string): string {
70 if (/["\\]/.test(command)) throw new Error(`can't put this command in AppleScript: ${command}`)
71 return [
72 'tell application "Ghostty"',
73 ' set cfg to new surface configuration',
74 ` set command of cfg to "${command}"`,
75 ' if (count of windows) is 0 then',
76 ' new window with configuration cfg',
77 ' else',
78 ' set w to front window',
79 ' set here to selected tab of w',
80 ' new tab in w with configuration cfg',
81 ' select tab here',
82 ' end if',
83 'end tell',
84 ].join('\n')
85}
86
87// An OpenRouter slug, `vendor/name` with an optional `:variant`; anything else
88// never reaches the shell.
89export const isSlug = (s: string) => /^[a-z0-9][\w.-]*\/[\w.-]+(:[\w.-]+)?$/i.test(s)
90
91/** Single-quotes `s` for a POSIX shell. */
92export const sq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
93
94/**
95 * The zsh script a worker pane runs. The key is referenced, never inlined:
96 * the pane's zsh expands $CW_OPENROUTER_API_KEY from ~/.zshenv, so it never
97 * appears in tmux's or ps's argument lists.
98 */
99export function workerScript(opts: { name: string; model: string; mode: Mode; task: string; contextTokens?: number; provider?: Provider }): string {
100 if (!isSlug(opts.model)) throw new Error(`not an OpenRouter model id: ${opts.model}`)
101 const m = opts.model
102 if (opts.provider === 'bedrock') {
103 const alias = m.split('/')[1]
104 if (!BEDROCK_MODELS.some(b => b.id === m) || !alias) throw new Error(`not a Bedrock model choice: ${m}`)
105 // Bedrock config (CLAUDE_CODE_USE_BEDROCK, AWS_*) lives in user settings, so they
106 // must load: no --setting-sources here. Claude Code maps the alias to the Bedrock id.
107 return `exec command claude -n ${opts.name} --model ${alias} --strict-mcp-config --permission-mode ${opts.mode}${opts.task ? ` ${sq(opts.task)}` : ''}`
108 }
109 return [
110 'export ANTHROPIC_BASE_URL=https://openrouter.ai/api ANTHROPIC_AUTH_TOKEN=$CW_OPENROUTER_API_KEY ANTHROPIC_API_KEY=',
111 `export ANTHROPIC_DEFAULT_OPUS_MODEL=${m} ANTHROPIC_DEFAULT_SONNET_MODEL=${m} ANTHROPIC_DEFAULT_HAIKU_MODEL=${m} CLAUDE_CODE_SUBAGENT_MODEL=${m}`,
112 // Claude Code doesn't know OpenRouter models and assumes 200k; give it the real window.
113 ...(opts.contextTokens && Number.isInteger(opts.contextTokens) ? [`export CLAUDE_CODE_MAX_CONTEXT_TOKENS=${opts.contextTokens}`] : []),
114 // Your own skills without the rest of user settings: a folder holding only .claude/skills
115 // (a link to ~/.claude/skills), added with --add-dir. Edits there are denied: acceptEdits would
116 // auto-approve them, and the link leads to the real skills.
117 'S=$HOME/.claude/cw-skills; mkdir -p $S/.claude && ln -sfn $HOME/.claude/skills $S/.claude/skills',
118 // Same flags cw proved in Phase 0: no user hooks/plugins or MCP servers ride along.
119 // --add-dir and --disallowedTools take several values: --permission-mode stays between them and the task.
120 `exec command claude -n ${opts.name} --model sonnet --setting-sources project,local --strict-mcp-config --add-dir $S --disallowedTools "Edit(/$S/**)" "Edit(/$HOME/.claude/skills/**)" "Edit(/$HOME/.agents/skills/**)" --permission-mode ${opts.mode}${opts.task ? ` ${sq(opts.task)}` : ''}`,
121 ].join('\n')
122}
123
124/** Compacts OpenRouter's /models payload to the tool-capable models, cheapest input first. */
125export function parseModels(json: string): OrModel[] {
126 const data = (JSON.parse(json) as { data?: unknown[] }).data ?? []
127 return data
128 .flatMap(raw => {
129 const m = raw as {
130 id?: string
131 context_length?: number
132 pricing?: { prompt?: string; completion?: string; input_cache_read?: string }
133 supported_parameters?: string[]
134 }
135 if (!m.id || !isSlug(m.id) || !m.supported_parameters?.includes('tools')) return []
136 return [
137 {
138 id: m.id,
139 inPerM: Number(m.pricing?.prompt ?? 0) * 1e6,
140 outPerM: Number(m.pricing?.completion ?? 0) * 1e6,
141 ...(m.pricing?.input_cache_read !== undefined && { cachePerM: Number(m.pricing.input_cache_read) * 1e6 }),
142 ...(Number.isInteger(m.context_length) && { contextTokens: m.context_length }),
143 },
144 ]
145 })
146 .sort((a, b) => a.inPerM - b.inPerM)
147}
148
149/** Every space-separated word of `query` in the id; the first `limit`, cheapest first. */
150export function search(models: readonly OrModel[], query: string, limit = 6): OrModel[] {
151 const words = query.toLowerCase().split(/\s+/).filter(Boolean)
152 if (words.length === 0) return []
153 return models.filter(m => words.every(w => m.id.toLowerCase().includes(w))).slice(0, limit)
154}
155
156export const price = (m: OrModel | undefined) =>
157 m ? `$${+m.inPerM.toFixed(2)}/$${+m.outPerM.toFixed(2)} per M` : 'price unknown'
158
159/** What the list shows: search hits while searching, else pins then recent picks. */
160export function choicesFor(models: readonly OrModel[], query: string, pins: readonly string[], recent: readonly string[]): string[] {
161 const hits = search(models, query)
162 if (hits.length > 0) return hits.map(m => m.id)
163 return [...pins, ...recent.filter(r => !pins.includes(r))]
164}
165
166/** Gone from a loaded catalog; never claimed while the catalog is empty (offline, loading). */
167export const isRetired = (models: readonly OrModel[], id: string) => models.length > 0 && !models.some(m => m.id === id)
168
169/** Reads the stored pin list, dropping anything that isn't a slug. */
170export const toPins = (raw: unknown): string[] =>
171 Array.isArray(raw) ? raw.filter((x): x is string => typeof x === 'string' && isSlug(x)) : []
172
173/** `tmux list-panes -F '#{pane_id}|#{@cw}'` → labelled worker panes (unlabelled panes aren't workers). */
174export function parsePanes(stdout: string): { pane: string; name: string }[] {
175 return stdout
176 .split('\n')
177 .map(line => line.split('|'))
178 .filter(([pane, name]) => pane?.startsWith('%') && name)
179 .map(([pane, name]) => ({ pane: pane as string, name: name as string }))
180}
181
182// Claude Code's frame: rules, the empty prompt, the footer hints. Not what the worker is doing.
183const CHROME = /^[─━│┃╭╮╰╯▐▛▜▝▘\s]*$|^❯\s*$|shift\+tab|esc to interrupt|\? for shortcuts|auto mode on|accept edits on/
184
185/** The last `n` meaningful lines of a captured pane, each cut to `width`. */
186export function peekLines(capture: string, n = 2, width = 72): string[] {
187 return capture
188 .split('\n')
189 .map(l => l.trimEnd())
190 .filter(l => l.trim() !== '' && !CHROME.test(l))
191 .slice(-n)
192 .map(l => (l.trim().length > width ? `${l.trim().slice(0, width - 1)}…` : l.trim()))
193}
194
195/** A cross-session delivery's sender and body: `<cross-session-message … from-name="cw-ping" …>body</…>`. */
196export function parsePeer(text: string): { from: string; body: string } {
197 const from = text.match(/from-name="([^"]+)"/)?.[1] ?? text.match(/from="([^"]+)"/)?.[1] ?? 'peer'
198 const body = text.match(/<cross-session-message[^>]*>([\s\S]*?)<\/cross-session-message>/)?.[1] ?? text
199 return { from, body: body.trim() }
200}
201
202/** This session's own name, from the ListAgents tool's first line ("This session is <name> [ref] …"). */
203export const leadFrom = (listAgents: string) => listAgents.match(/This session is (.+?) \[[0-9a-f]+\]/)?.[1] ?? null
204
205/** The team note a worker launched with "team" on reads before its task. */
206export function teamPreamble(opts: { name: string; teammates: readonly string[]; lead: string | null }): string {
207 const mates = opts.teammates.filter(t => t !== opts.name)
208 return [
209 `You are ${opts.name}, a worker on a team of Claude Code sessions on this machine.`,
210 mates.length > 0
211 ? `Teammates right now: ${mates.join(', ')}. More may join; the ListAgents tool lists every session.`
212 : 'No teammates yet; the ListAgents tool lists sessions that join later.',
213 'Coordinate with the SendMessage tool: hand off work, ask a teammate for a result, or tell them what you changed. Keep messages short and specific.',
214 opts.lead
215 ? `Your lead is the session named "${opts.lead}". SendMessage it when you finish (one-line summary and where the result is) or when you are blocked. Copy the lead on decisions that affect other workers.`
216 : 'When you finish or are blocked, say so in your own output.',
217 'Messages from teammates arrive as new prompts; answer them, then continue your task.',
218 ].join('\n')
219}
220
221/** Claude Code's transcript folder for a working directory: every / and . becomes -. */
222export const projectDir = (home: string, cwd: string) => `${home}/.claude/projects/${cwd.replace(/[/.]/g, '-')}`
223
224export type Usage = { input: number; cacheRead: number; cacheWrite: number; output: number; lastPrompt: number }
225
226/** Token totals of one transcript; a streamed reply repeats its message id, so each id counts once. */
227export function usageFrom(jsonl: string): Usage {
228 const seen = new Set<string>()
229 const u: Usage = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, lastPrompt: 0 }
230 for (const line of jsonl.split('\n')) {
231 if (!line.includes('"usage"')) continue
232 let d: { type?: string; message?: { id?: string; usage?: Record<string, number> } }
233 try {
234 d = JSON.parse(line)
235 } catch {
236 continue
237 }
238 const m = d.message
239 if (d.type !== 'assistant' || !m?.usage || !m.id || seen.has(m.id)) continue
240 seen.add(m.id)
241 const x = m.usage
242 u.input += x.input_tokens ?? 0
243 u.cacheRead += x.cache_read_input_tokens ?? 0
244 u.cacheWrite += x.cache_creation_input_tokens ?? 0
245 u.output += x.output_tokens ?? 0
246 u.lastPrompt = (x.input_tokens ?? 0) + (x.cache_read_input_tokens ?? 0) + (x.cache_creation_input_tokens ?? 0)
247 }
248 return u
249}
250
251/** ≈ USD at the model's listed rates (cache reads at the cache rate when listed, else input rate). */
252export const costOf = (u: Usage, m: OrModel | undefined) =>
253 m ? ((u.input + u.cacheWrite) * m.inPerM + u.cacheRead * (m.cachePerM ?? m.inPerM) + u.output * m.outPerM) / 1e6 : null
254
255export const tokensOf = (u: Usage) => u.input + u.cacheRead + u.cacheWrite + u.output
256
257export const vendorOf = (model: string) => model.split('/')[0]?.replace(/^~/, '') ?? ''
258
259export const kfmt = (n: number) => (n >= 1e6 ? `${+(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`)
260
261/** 0:27, 12:05, 1:02:09 */
262export function clockDur(ms: number): string {
263 const s = Math.max(0, Math.floor(ms / 1000))
264 const h = Math.floor(s / 3600)
265 const mm = Math.floor((s % 3600) / 60)
266 const ss = String(s % 60).padStart(2, '0')
267 return h > 0 ? `${h}:${String(mm).padStart(2, '0')}:${ss}` : `${mm}:${ss}`
268}
269
270/** Claude Code shows "esc to interrupt" only while a turn runs. */
271export const isWorking = (capture: string) => /esc to interrupt/.test(capture)
272
273/** The full model id from a worker's startup banner ("deepseek/deepseek-v4.1-flash · API Usage Billing"). */
274export const bannerModel = (capture: string) => capture.match(/([a-z0-9][\w.-]*\/[\w.:-]+) · API Usage Billing/i)?.[1] ?? null
275
276/** Pane metadata every session can read: tmux options set at launch, tab-separated by list-panes. */
277export const META_FORMAT = '#{pane_id}\t#{@cw}\t#{@cw_model}\t#{@cw_mode}\t#{@cw_start}\t#{@cw_cwd}\t#{@cw_task}'
278export type PaneMeta = { pane: string; name: string; model: string; mode: string; start: number | null; cwd: string; task: string }
279/** A worker on a sprite, from `cw-remote list`; its pane is `<sprite>:<name>`, unique across sprites and local panes. */
280export type RemoteRow = { meta: PaneMeta; isBusy: boolean; lines: string[]; remote: { sprite: string; url: string } }
281export function parseRemoteList(stdout: string, sprite: string, url: string): RemoteRow[] {
282 const rows: RemoteRow[] = []
283 for (const line of stdout.split('\n')) {
284 let o: Record<string, unknown>
285 try {
286 o = JSON.parse(line) as Record<string, unknown>
287 } catch {
288 continue
289 }
290 const str = (k: string) => (typeof o[k] === 'string' ? (o[k] as string) : '')
291 if (!o || !isWorkerName(str('name'))) continue
292 rows.push({
293 meta: { pane: `${sprite}:${str('name')}`, name: str('name'), model: str('model'), mode: str('mode'), start: typeof o.start === 'number' && o.start > 0 ? o.start : null, cwd: str('cwd'), task: str('task') },
294 isBusy: o.isBusy === true,
295 lines: Array.isArray(o.lines) ? o.lines.filter((l): l is string => typeof l === 'string') : [],
296 remote: { sprite, url },
297 })
298 }
299 return rows
300}
301
302export function parseMeta(stdout: string): PaneMeta[] {
303 return stdout
304 .split('\n')
305 .map(l => l.split('\t'))
306 .filter(f => f[0]?.startsWith('%') && f[1])
307 .map(([pane, name, model, mode, start, cwd, ...task]) => ({
308 pane: pane!, name: name!, model: model ?? '', mode: mode ?? '',
309 start: start && /^\d+$/.test(start) ? Number(start) : null, cwd: cwd ?? '', task: task.join('\t'),
310 }))
311}
312types/index.d.ts 60 lines1/** One OpenRouter model that takes tools, prices in USD per million tokens. */
2export type OrModel = { id: string; inPerM: number; outPerM: number; cachePerM?: number; contextTokens?: number }
3export type Mode = 'acceptEdits' | 'auto' | 'default'
4export type Launch = {
5 name: string
6 model: string
7 mode: Mode
8 pane: string
9 task: string
10 isLive: boolean
11 startedAt?: number
12 /** Where it ran, to find its transcript. */
13 cwd?: string
14 /** Its transcript, once found. */
15 transcript?: string
16 /** When the pane was first seen gone. */
17 endedAt?: number
18 /** Runs on this Fly Sprite (launch: remote); its pane is `<sprite>:<name>`. */
19 remote?: { sprite: string; url: string }
20}
21
22/** Read from a worker's transcript. */
23export type WStats = { tokens: number; cost: number | null; ctxPct: number | null }
24
25/** A live worker pane in tmux session `cw`, joined with what this mod launched there (if it did). */
26export type Active = { pane: string; name: string; launch: Launch | null; peek: string[]; isClosing: boolean; isBusy: boolean }
27
28/** One message to or from a worker, as this session saw it. */
29export type Msg = { dir: 'in' | 'out'; peer: string; text: string; at: number; isFailed?: boolean }
30
31export type Picker = {
32 model: string
33 mode: Mode
34 query: string
35 /** Fetched when the pane opens; empty until then or when offline. */
36 models: OrModel[]
37 recent: string[]
38 /** Starred models, kept across sessions in $.store; the first is the default. */
39 pins: string[]
40 launched: Launch[]
41 flash: { text: string; isError: boolean } | null
42 /** Refreshed from tmux every few seconds. */
43 active: Active[]
44 /** Panes sent /exit, awaiting the force-kill check. */
45 closing: string[]
46 /** Launch the next worker as a team member (teammates + lead in its prompt). */
47 team: boolean
48 /** Newest last, capped. */
49 messages: Msg[]
50 /** Per worker name. */
51 stats: Record<string, WStats>
52 showFinished: boolean
53}
54
55declare module 'claude-code' {
56 interface PluginState {
57 'cheap-worker': { picker: Picker }
58 }
59}
60