Run worker jobs on Codex or Antigravity (Gemini) in the background, with completion notifications and a jobs pane

A Claude Code mod that runs worker jobs on Codex, or on Antigravity's agy CLI (Gemini), in the background, the way a background Agent subagent runs on Claude.
dispatch: the model hands Codex a self-contained brief and gets a job id back at once. The job runs detached (setsid codex exec), so reloading the mod or restarting Claude Code doesn't kill it.result / cancel: read a job's full report, or kill its whole process tree./codex: a pane listing this session's Codex jobs next to its Claude subagents. The status line shows codex ▸ N running.Each job's files are in ~/.cache/codex-lane/<id>/: brief.md, meta.json, events.jsonl (Codex's --json stream), stderr.log, last.md (the final report) and exit.
/plugin install codex-lane --marketplace wryskware/claude-mods
For one session from a clone: claude --plugin-dir <clone>/mods/codex-lane.
It needs the codex CLI on PATH, logged in, and Linux or macOS (setsid, bash). The Antigravity engine also needs agy (logged in) and bwrap (Linux).
| Field | |
|---|---|
brief | The self-contained task. Codex sees none of the conversation. |
description | A 3–5 word label for the pane and the notification. |
engine | codex (default) or antigravity. |
effort | Codex: low, medium, high, xhigh. Antigravity: low, medium, high. |
cwd | Working directory; defaults to the session's. |
model | Codex: defaults to your ~/.codex/config.toml. Antigravity: gemini-3.8-flash (default) or gemini-4-argon; the effort picks the variant (gemini-4-argon-high). |
worktree | Codex only: true runs it in a separate git worktree (codex exec --worktree). |
Antigravity jobs run agy -p <brief> --output-format json --dangerously-skip-permissions and have ag- ids. agy's own --sandbox doesn't confine file writes, so the mod runs it under bwrap: the filesystem is read-only except cwd, its git dir, agy's state (~/.gemini, ~/.cache/antigravity, ~/.config/Antigravity) and any addDirs, with a private /tmp. The network stays on, since agy needs it to reach Gemini. The brief is passed as an argument, so it must be under 100k characters.
Which work goes to Codex, and at what effort, is up to you. Put your routing rules in your CLAUDE.md.
If ai-usagebar is installed, the mod adds one line of Claude and Codex (and Antigravity Gemini, when it reports one) usage that the model reads with each prompt and after each Agent or dispatch call:
[quota, 2m old] claude: 5h 5%, week 30% (+3 vs pace, resets in 5d3h) | codex: week 8% (+5 vs pace, resets in 6d18h) | spawned since: claude 1, codex 2
"vs pace" is percentage points above or below an even burn of the week. The usage is sampled at most every 5 minutes, so the line also counts the spawns made since the sample was taken. The mod reports the numbers and the model chooses the lane, by your rules. Without ai-usagebar the line is left out.
Codex jobs run under Codex's workspace-write sandbox, Antigravity jobs under the bwrap one above. A workspace can change that with .claude/codex-lane.json. The mod uses the nearest one at or above the job's cwd:
{ "network": true, "addDirs": ["/home/me/.ssh"] }
| Key | Effect |
|---|---|
sandbox | read-only (Codex only), workspace-write, danger-full-access (Antigravity: no bwrap). |
network | true allows network access under Codex's workspace-write. |
addDirs | Extra writable directories (--add-dir). |
hooks/register.tsx 521 lines1// codex-lane: run worker jobs on Codex, or on Antigravity (Gemini), in the background.
2//
3// The model calls `dispatch` with a self-contained brief, as it would spawn a
4// background Agent. The job runs detached (`setsid`), outside this module, so a
5// reload or a restart never kills it; everything it writes lands in
6// ~/.cache/codex-lane/<id>/. A 5s timer watches for the DONE marker and, when it
7// appears, submits the final report as a prompt, which wakes an idle session the
8// way a finished background agent's notification does. The disk is the source of
9// truth: after a reload the timer picks the jobs up again from there.
10
11import { atom, read, update } from 'claude-code'
12import type { EngineInterface, Register } from 'claude-code'
13
14import type { AgentRow, DispatchInput, JobView } from '../types'
15import { applyQuotaReport, countSpawn, endQuotaRefresh, quotaLine, startQuotaRefresh } from './quota'
16
17const PLUGIN = 'codex-lane'
18const PANE = 'codex-lane'
19const TICK_MS = 5000
20const REPORT_LIMIT = 20000
21
22const jobsAtom = atom({ plugin: 'codex-lane', key: 'jobs' } as const, [] as JobView[])
23const agentsAtom = atom({ plugin: 'codex-lane', key: 'agents' } as const, [] as AgentRow[])
24const nowAtom = atom({ plugin: 'codex-lane', key: 'now' } as const, 0)
25
26type Engine = 'codex' | 'antigravity'
27const ENGINES: Engine[] = ['codex', 'antigravity']
28const ENGINE_NAME: Record<Engine, string> = { codex: 'Codex', antigravity: 'Antigravity' }
29
30/** Reasoning efforts. Codex takes `model_reasoning_effort`; agy models carry the effort in their id. */
31const EFFORTS: Record<Engine, string[]> = {
32 codex: ['low', 'medium', 'high', 'xhigh'],
33 antigravity: ['low', 'medium', 'high'],
34}
35const AGY_DEFAULT_MODEL = 'gemini-3.8-flash'
36/** agy takes the prompt as an argument, and Linux caps one argument at 128 KiB. */
37const AGY_BRIEF_LIMIT = 100_000
38/** Antigravity's own state, writable inside its sandbox. */
39const AGY_STATE_DIRS = ['.gemini', '.cache/antigravity', '.config/Antigravity']
40
41// One job, detached. Its stdio is closed first so `$.process.run` returns at
42// once; `setsid` makes it a process group of its own, so cancel kills the tree.
43const RUNNER = `exec </dev/null >/dev/null 2>&1
44dir=$1; shift
45echo $$ > "$dir/pid"
46codex exec "$@" - < "$dir/brief.md" > "$dir/events.jsonl" 2> "$dir/stderr.log"
47code=$?
48[ -e "$dir/exit" ] || echo "$code" > "$dir/exit"
49touch "$dir/DONE"`
50
51// The same for Antigravity: "$@" is the whole command (bwrap … agy …), and agy
52// takes the brief as -p's argument. Its --output-format json reply lands in
53// events.jsonl; the module turns it into last.md when the job ends.
54const AGY_RUNNER = `exec </dev/null >/dev/null 2>&1
55dir=$1; shift
56echo $$ > "$dir/pid"
57"$@" -p "$(cat "$dir/brief.md")" > "$dir/events.jsonl" 2> "$dir/stderr.log"
58code=$?
59[ -e "$dir/exit" ] || echo "$code" > "$dir/exit"
60touch "$dir/DONE"`
61
62type Meta = {
63 id: string
64 /** Absent on jobs from before Antigravity: those are Codex. */
65 engine?: Engine
66 session: string
67 description: string
68 effort: string
69 model?: string
70 cwd: string
71 startedAt: number
72 args: string[]
73}
74
75/** Optional per-workspace sandbox exceptions, read from <dir>/.claude/codex-lane.json. */
76type WorkspaceConfig = { sandbox?: string; network?: boolean; addDirs?: string[] }
77
78let root: string | undefined
79let ticking = false
80/** Finished jobs never change again; keep them out of the per-tick reads. */
81const finished = new Map<string, JobView>()
82
83async function jobsRoot($: EngineInterface): Promise<string> {
84 if (!root) {
85 const home = (await $.process.run(['printenv', 'HOME'])).stdout.trim()
86 root = `${home}/.cache/codex-lane`
87 }
88 return root
89}
90
91async function readText($: EngineInterface, path: string): Promise<string | undefined> {
92 return $.fs.read(path).catch(() => undefined)
93}
94
95function engineOf(meta: Meta): Engine {
96 return meta.engine ?? 'codex'
97}
98
99/** Writes an Antigravity job's last.md from its JSON reply, once. */
100async function writeAgyReport($: EngineInterface, dir: string) {
101 if (await $.fs.exists(`${dir}/last.md`)) return
102 const text = (await readText($, `${dir}/events.jsonl`))?.trim()
103 if (!text) return
104 try {
105 const out = JSON.parse(text) as { status?: string; response?: string }
106 const head = out.status && out.status !== 'SUCCESS' ? `(Antigravity status ${out.status})\n\n` : ''
107 await $.fs.write(`${dir}/last.md`, `${head}${out.response ?? ''}`)
108 } catch {
109 // Not JSON (agy failed before replying): notify falls back to stderr.
110 }
111}
112
113async function workspaceConfig($: EngineInterface, cwd: string): Promise<WorkspaceConfig> {
114 for (let dir = cwd.replace(/\/+$/, ''); ; dir = dir.slice(0, dir.lastIndexOf('/'))) {
115 const text = await readText($, `${dir}/.claude/codex-lane.json`)
116 if (text !== undefined) return JSON.parse(text) as WorkspaceConfig
117 if (!dir) return {}
118 }
119}
120
121function duration(ms: number): string {
122 const s = Math.max(0, Math.round(ms / 1000))
123 if (s < 60) return `${s}s`
124 if (s < 3600) return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
125 return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
126}
127
128function statusOf(exit: string): JobView['status'] {
129 if (exit === 'cancelled') return 'cancelled'
130 return exit === '0' ? 'done' : 'failed'
131}
132
133async function notify($: EngineInterface, meta: Meta, dir: string, view: JobView) {
134 const report = (await readText($, `${dir}/last.md`))?.trim() ?? ''
135 const parts = [
136 `[codex-lane] ${ENGINE_NAME[engineOf(meta)]} job ${meta.id} (${meta.description}) ${view.status} after ${duration(
137 (view.endedAt ?? meta.startedAt) - meta.startedAt,
138 )}.`,
139 ]
140 if (report) {
141 parts.push(report.length > REPORT_LIMIT
142 ? `${report.slice(0, REPORT_LIMIT)}\n\n…(report cut; call result("${meta.id}") for the rest)`
143 : report)
144 } else {
145 const stderr = (await readText($, `${dir}/stderr.log`))?.trim() ?? ''
146 parts.push(`No final report. stderr tail:\n${stderr.slice(-4000) || '(empty)'}`)
147 }
148 parts.push(`Logs: ${dir}/ (events.jsonl, stderr.log, last.md)`)
149 void $.prompt.submit({ text: parts.join('\n\n') })
150}
151
152/** Asks ai-usagebar for a new quota sample when the last one is stale. */
153async function refreshQuota($: EngineInterface) {
154 if (!startQuotaRefresh()) return
155 try {
156 const ran = await $.process.run(['ai-usagebar', 'usage', '--json'], { timeoutMs: 60_000 })
157 if (ran.exitCode === 0) applyQuotaReport(ran.stdout)
158 } catch {
159 // Not installed or timed out: keep the last sample and try again later.
160 } finally {
161 endQuotaRefresh()
162 }
163}
164
165async function tick($: EngineInterface) {
166 void refreshQuota($)
167 if (ticking) return
168 ticking = true
169 try {
170 const base = await jobsRoot($)
171 const session = await $.session.id()
172 const now = Date.now()
173 const views: JobView[] = []
174
175 for (const entry of await $.fs.list(base).catch(() => [])) {
176 if (entry.kind !== 'dir') continue
177 const known = finished.get(entry.name)
178 if (known) {
179 views.push(known)
180 continue
181 }
182 const dir = `${base}/${entry.name}`
183 const metaText = await readText($, `${dir}/meta.json`)
184 if (!metaText) continue
185 const meta = JSON.parse(metaText) as Meta
186 if (meta.session !== session) continue
187
188 let isDone = await $.fs.exists(`${dir}/DONE`)
189 if (!isDone) {
190 // A runner that died without its marker (a reboot, a kill -9) is lost.
191 const pid = (await readText($, `${dir}/pid`))?.trim()
192 const alive = pid ? (await $.process.run(['kill', '-0', pid])).exitCode === 0 : true
193 if (!alive && !(await $.fs.exists(`${dir}/DONE`))) {
194 await $.fs.write(`${dir}/exit`, 'lost\n')
195 await $.fs.write(`${dir}/DONE`, '')
196 }
197 isDone = await $.fs.exists(`${dir}/DONE`)
198 }
199
200 const view: JobView = {
201 id: meta.id,
202 engine: engineOf(meta),
203 description: meta.description,
204 effort: meta.effort,
205 cwd: meta.cwd,
206 startedAt: meta.startedAt,
207 status: 'running',
208 }
209 if (isDone) {
210 view.status = statusOf(((await readText($, `${dir}/exit`)) ?? '').trim())
211 view.endedAt = (await $.fs.stat(`${dir}/DONE`)).mtimeMs
212 finished.set(meta.id, view)
213 if (view.engine === 'antigravity') await writeAgyReport($, dir)
214 if (!(await $.fs.exists(`${dir}/notified`))) {
215 await $.fs.write(`${dir}/notified`, '')
216 await notify($, meta, dir, view)
217 }
218 }
219 views.push(view)
220 }
221
222 views.sort((a, b) => a.startedAt - b.startedAt)
223 const running = ENGINES.map(engine => {
224 const n = views.filter(v => v.engine === engine && v.status === 'running').length
225 return n ? `${engine === 'codex' ? 'codex' : 'agy'} ▸ ${n} running` : undefined
226 }).filter(Boolean)
227 $.ui.status(running.length ? running.join(' · ') : undefined)
228
229 const agents = (await $.agent.list()).map(a => ({
230 id: a.id,
231 description: a.description,
232 type: a.type,
233 status: a.status,
234 }))
235 await update($, jobsAtom, () => views)
236 await update($, agentsAtom, () => agents)
237 await update($, nowAtom, () => now)
238 } finally {
239 ticking = false
240 }
241}
242
243/**
244 * Starts an Antigravity job. agy's own --sandbox does not confine files, so
245 * workspace-write is bubblewrap: the filesystem read-only except cwd, its git
246 * dir, agy's state and any addDirs, with a private /tmp. agy needs the network
247 * to reach Gemini, so `network` has no effect here.
248 */
249async function dispatchAgy(
250 $: EngineInterface,
251 input: DispatchInput,
252 job: { id: string; dir: string; cwd: string; config: WorkspaceConfig },
253) {
254 const { id, dir, cwd, config } = job
255 const model = `${(input.model ?? AGY_DEFAULT_MODEL).replace(/-(low|medium|high)$/, '')}-${input.effort}`
256 const agy = ['agy', '--model', model, '--output-format', 'json', '--dangerously-skip-permissions']
257
258 const sandbox = config.sandbox ?? 'workspace-write'
259 if (sandbox === 'read-only') return { deny: 'Antigravity has no read-only mode here; use codex for read-only work.' }
260 let command: string[]
261 if (sandbox === 'danger-full-access') {
262 command = ['env', '-C', cwd, ...agy]
263 } else {
264 const home = (await $.process.run(['printenv', 'HOME'])).stdout.trim()
265 const git = await $.process.run(['git', '-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'])
266 const writable = [
267 cwd,
268 ...AGY_STATE_DIRS.map(d => `${home}/${d}`),
269 ...(git.exitCode === 0 ? [git.stdout.trim()] : []),
270 ...(config.addDirs ?? []),
271 ]
272 command = [
273 'bwrap', '--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',
274 ...writable.flatMap(d => ['--bind-try', d, d]),
275 '--die-with-parent', '--chdir', cwd,
276 ...agy,
277 ]
278 }
279
280 const meta: Meta = {
281 id,
282 engine: 'antigravity',
283 session: await $.session.id(),
284 description: input.description,
285 effort: input.effort,
286 model,
287 cwd,
288 startedAt: Date.now(),
289 args: command,
290 }
291 await $.fs.write(`${dir}/brief.md`, input.brief)
292 await $.fs.write(`${dir}/meta.json`, JSON.stringify(meta, null, 2))
293
294 const started = await $.process.run(['setsid', '-f', 'bash', '-c', AGY_RUNNER, PLUGIN, dir, ...command])
295 if (started.exitCode !== 0) {
296 return { deny: `Could not start Antigravity: ${started.stderr.trim() || `exit ${started.exitCode}`}` }
297 }
298 void tick($)
299
300 countSpawn('agy')
301 const quota = quotaLine()
302 return {
303 ...(quota ? { context: [quota] } : {}),
304 result: `Started Antigravity job ${id} (${model}; ${sandbox === 'danger-full-access' ? sandbox : 'bwrap workspace-write, network on'}) in ${cwd}. Its report arrives as a message when it finishes; don't poll. Logs: ${dir}/`,
305 }
306}
307
308const DISPATCH_DESCRIPTION = `Start a worker job in the background on Codex (OpenAI; the default) or Antigravity (Google's agy CLI, Gemini models): the equivalent of spawning a background Agent worker.
309
310Returns a job id at once. When the job finishes, its final report arrives as a new message, as a finished background agent's does: do not poll, sleep or wait for it.
311
312\`brief\` must be self-contained, exactly as for an Agent worker: objective, deliverable, relevant files, constraints, decision authority, verification method, return format. Codex sees none of this conversation.
313
314\`engine\`: \`codex\` (default) or \`antigravity\`.
315- Codex: \`model\` defaults to ~/.codex/config.toml; \`effort\` is low, medium, high or xhigh. Set \`worktree: true\` to run it in a separate git worktree.
316- Antigravity: \`model\` is \`gemini-3.8-flash\` (default) or \`gemini-4-argon\` (any \`agy models\` id works); \`effort\` is low, medium or high and picks the model's effort variant. No \`worktree\`. The brief must be under 100k characters.
317
318It runs in \`cwd\` (default: the session's) under a workspace-write sandbox (for Antigravity: bubblewrap, filesystem read-only except \`cwd\`, its git dir and agy's own state; network on), unless that workspace's .claude/codex-lane.json says otherwise.`
319
320export const register: Register = on => {
321 on('session.start', async ($, e, next) => {
322 await $.tool.register({
323 name: 'dispatch',
324 description: DISPATCH_DESCRIPTION,
325 inputSchema: {
326 type: 'object',
327 properties: {
328 brief: { type: 'string', description: 'The self-contained task brief.' },
329 description: { type: 'string', description: 'A short (3-5 word) label for the job.' },
330 engine: { type: 'string', enum: ENGINES, description: 'codex (default) or antigravity.' },
331 effort: { type: 'string', enum: EFFORTS.codex },
332 cwd: { type: 'string', description: 'Absolute working directory; default the session cwd.' },
333 model: { type: 'string', description: 'Model override; omit for the engine default.' },
334 worktree: { type: 'boolean', description: 'Run in a separate git worktree.' },
335 },
336 required: ['brief', 'description', 'effort'],
337 },
338 })
339 await $.tool.register({
340 name: 'result',
341 description:
342 'Read a Codex or Antigravity job\'s status and its full final report. Only needed when the completion message cut the report short, or to check a job on request; never to poll.',
343 inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
344 })
345 await $.tool.register({
346 name: 'cancel',
347 description: 'Cancel a running Codex or Antigravity job (kills its whole process tree).',
348 inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
349 })
350 await $.command.register({ name: 'codex', description: 'Show Codex and Antigravity jobs and Claude subagents in a pane' })
351
352 $.clock.every(TICK_MS, () => tick($))
353 void tick($)
354 return next(e)
355 })
356
357 on('tool.call', { tool: 'mcp__codex-lane__dispatch' }, async ($, e) => {
358 // The matcher does not narrow `e` to this tool's input; the schema above holds it.
359 const input = e as unknown as DispatchInput
360 const { effort } = input
361 const engine = input.engine ?? 'codex'
362 if (!ENGINES.includes(engine)) return { deny: `Unknown engine "${engine}"; use ${ENGINES.join(' or ')}.` }
363 if (!EFFORTS[engine].includes(effort)) {
364 return { deny: `Unknown ${ENGINE_NAME[engine]} effort "${effort}"; use one of ${EFFORTS[engine].join(', ')}.` }
365 }
366 if (engine === 'antigravity') {
367 if (input.worktree) return { deny: 'Antigravity has no worktree mode; make a worktree and pass it as cwd.' }
368 if (input.brief.length > AGY_BRIEF_LIMIT) {
369 return { deny: `Antigravity briefs must be under ${AGY_BRIEF_LIMIT} characters; point it at a file instead.` }
370 }
371 }
372
373 const cwd = input.cwd ?? (await $.process.run(['pwd'])).stdout.trim()
374 if (!(await $.fs.exists(cwd))) return { deny: `cwd ${cwd} does not exist.` }
375 const config = await workspaceConfig($, cwd)
376
377 const base = await jobsRoot($)
378 const id = `${engine === 'codex' ? 'cx' : 'ag'}-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`
379 const dir = `${base}/${id}`
380
381 if (engine === 'antigravity') return dispatchAgy($, input, { id, dir, cwd, config })
382
383 const args = [
384 '--json',
385 '--skip-git-repo-check',
386 '-C', cwd,
387 '-o', `${dir}/last.md`,
388 '-s', config.sandbox ?? 'workspace-write',
389 '-c', `model_reasoning_effort="${effort}"`,
390 ]
391 if (input.model) args.push('-m', input.model)
392 if (config.network) args.push('-c', 'sandbox_workspace_write.network_access=true')
393 for (const extra of config.addDirs ?? []) args.push('--add-dir', extra)
394 if (input.worktree) args.push('--worktree')
395
396 const meta: Meta = {
397 id,
398 engine,
399 session: await $.session.id(),
400 description: input.description,
401 effort,
402 model: input.model,
403 cwd,
404 startedAt: Date.now(),
405 args,
406 }
407 await $.fs.write(`${dir}/brief.md`, input.brief)
408 await $.fs.write(`${dir}/meta.json`, JSON.stringify(meta, null, 2))
409
410 const started = await $.process.run(['setsid', '-f', 'bash', '-c', RUNNER, PLUGIN, dir, ...args])
411 if (started.exitCode !== 0) {
412 return { deny: `Could not start Codex: ${started.stderr.trim() || `exit ${started.exitCode}`}` }
413 }
414 void tick($)
415
416 const sandbox = [config.sandbox ?? 'workspace-write', config.network && 'network on'].filter(Boolean).join(', ')
417 countSpawn('codex')
418 const quota = quotaLine()
419 return {
420 ...(quota ? { context: [quota] } : {}),
421 result: `Started Codex job ${id} (effort ${effort}${input.model ? `, ${input.model}` : ''}; ${sandbox}${input.worktree ? ', own worktree' : ''}) in ${cwd}. Its report arrives as a message when it finishes; don't poll. Logs: ${dir}/`,
422 }
423 })
424
425 on('tool.call', { tool: 'mcp__codex-lane__result' }, async ($, e) => {
426 const { id } = e as unknown as { id: string }
427 const dir = `${await jobsRoot($)}/${id}`
428 if (!(await $.fs.exists(`${dir}/meta.json`))) return { deny: `No job ${id}.` }
429 if (!(await $.fs.exists(`${dir}/DONE`))) return { result: `Job ${id} is still running. Logs: ${dir}/` }
430 if (id.startsWith('ag-')) await writeAgyReport($, dir)
431 const exit = ((await readText($, `${dir}/exit`)) ?? '').trim()
432 const report = (await readText($, `${dir}/last.md`))?.trim()
433 const stderr = report ? '' : `\n\nstderr tail:\n${((await readText($, `${dir}/stderr.log`)) ?? '').slice(-4000)}`
434 return { result: `Job ${id}: ${statusOf(exit)} (exit ${exit}).\n\n${report || '(no final report)'}${stderr}` }
435 })
436
437 on('tool.call', { tool: 'mcp__codex-lane__cancel' }, async ($, e) => {
438 const { id } = e as unknown as { id: string }
439 const dir = `${await jobsRoot($)}/${id}`
440 if (!(await $.fs.exists(`${dir}/meta.json`))) return { deny: `No job ${id}.` }
441 if (await $.fs.exists(`${dir}/DONE`)) return { result: `Job ${id} already finished.` }
442 // The cancel is its own notice: mark it notified so no completion prompt follows.
443 await $.fs.write(`${dir}/notified`, '')
444 await $.fs.write(`${dir}/exit`, 'cancelled\n')
445 const pid = (await readText($, `${dir}/pid`))?.trim()
446 if (pid) await $.process.run(['kill', '-s', 'TERM', '--', `-${pid}`])
447 await $.fs.write(`${dir}/DONE`, '')
448 void tick($)
449 return { result: `Cancelled job ${id}.` }
450 })
451
452 // The quota line rides beside each prompt and after each spawn, so the model
453 // can choose a lane with no call of its own.
454 on('prompt.submit', ($, e, next) => {
455 const quota = quotaLine()
456 return next(quota ? { ...e, context: [...(e.context ?? []), quota] } : e)
457 })
458
459 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
460 const ran = await next(e)
461 if (ran.deny !== undefined) return ran
462 countSpawn('claude')
463 const quota = quotaLine()
464 return quota ? { ...ran, context: [...(ran.context ?? []), quota] } : ran
465 })
466
467 on('command.run', { command: 'codex' }, async $ => {
468 await $.ui.open({ id: PANE, title: 'Workers' })
469 void tick($)
470 return { text: 'Workers pane opened.' }
471 })
472
473 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
474 const { Box, Text } = $.ui.resolve(e)
475 const jobs = await read($, jobsAtom)
476 const agents = await read($, agentsAtom)
477 const now = await read($, nowAtom)
478 const COLOR: Record<JobView['status'], string> = {
479 running: 'warning',
480 done: 'success',
481 failed: 'error',
482 cancelled: 'inactive',
483 }
484
485 return (
486 <Box flexDirection="column">
487 {ENGINES.map(engine => {
488 const mine = jobs.filter(job => (job.engine ?? 'codex') === engine)
489 return (
490 <Box flexDirection="column">
491 <Text bold>{ENGINE_NAME[engine]}</Text>
492 {mine.length === 0 && <Text dimColor>{` No ${ENGINE_NAME[engine]} jobs this session.`}</Text>}
493 {mine.map(job => (
494 <Text wrap="truncate-end">
495 <Text color={COLOR[job.status]}>{job.status === 'running' ? '▸' : job.status === 'done' ? '✓' : '✗'}</Text>
496 {` ${job.description} `}
497 <Text dimColor>
498 {`${job.effort} · ${duration((job.endedAt ?? now) - job.startedAt)} · ${job.id}`}
499 </Text>
500 </Text>
501 ))}
502 <Text> </Text>
503 </Box>
504 )
505 })}
506 <Text bold>Claude</Text>
507 {agents.length === 0 && <Text dimColor> No subagents this session.</Text>}
508 {agents.map(agent => (
509 <Text wrap="truncate-end">
510 <Text color={agent.status === 'running' ? 'warning' : agent.status === 'completed' ? 'success' : 'inactive'}>
511 {agent.status === 'running' ? '▸' : agent.status === 'completed' ? '✓' : '·'}
512 </Text>
513 {` ${agent.description} `}
514 <Text dimColor>{`${agent.type} · ${agent.status}`}</Text>
515 </Text>
516 ))}
517 </Box>
518 )
519 })
520}
521hooks/quota.ts 121 lines1// Quota lane: one line of Claude/Codex/Antigravity usage the model reads beside each prompt
2// and after each Agent or dispatch call, so it can pick a lane without asking.
3//
4// The numbers come from `ai-usagebar usage --json`, which owns the credentials
5// and the provider rate limits. It is asked at most every 5 minutes, from the
6// mod's timer (register.tsx runs it), never from a hook a prompt waits on; without it the line is
7// simply left out. Spawns counted since the last sample cover a burst of
8// dispatches the sample cannot see yet.
9
10const WEEK = 604800
11const FIVE_HOUR = 18000
12const MAX_AGE_MS = 300_000
13const RETRY_MS = 60_000
14
15type Metric = { label: string; percent?: number; window_secs?: number; reset_at?: string }
16type Entry = { id: string; metrics?: Metric[]; error?: string | null }
17type Window = { name: string; pct: number; resetsAt?: number; windowSecs?: number }
18type Lane = { windows: Window[]; error?: string }
19
20export type LaneName = 'claude' | 'codex' | 'agy'
21
22const VENDORS: Record<string, LaneName> = { anthropic: 'claude', openai: 'codex', antigravity: 'agy' }
23/** Antigravity also meters its Claude & GPT-OSS models; jobs here use only Gemini. */
24const KEEP: Partial<Record<LaneName, RegExp>> = { agy: /^Gemini/ }
25
26let sample: { at: number; lanes: Partial<Record<LaneName, Lane>> } | undefined
27let lastTry = 0
28let refreshing = false
29const spawned: Record<LaneName, number> = { claude: 0, codex: 0, agy: 0 }
30
31/** Counts a spawn on a lane until the next sample shows its usage. */
32export function countSpawn(lane: LaneName) {
33 spawned[lane]++
34}
35
36/** Claims a refresh when the sample is stale and none is running; pair with endQuotaRefresh. */
37export function startQuotaRefresh(): boolean {
38 const now = Date.now()
39 if (refreshing || now - lastTry < RETRY_MS) return false
40 if (sample && now - sample.at < MAX_AGE_MS) return false
41 refreshing = true
42 lastTry = now
43 return true
44}
45
46export function endQuotaRefresh() {
47 refreshing = false
48}
49
50/** Takes `ai-usagebar usage --json` output as the new sample; bad JSON keeps the old one. */
51export function applyQuotaReport(stdout: string) {
52 let report: { entries?: Entry[] }
53 try {
54 report = JSON.parse(stdout) as { entries?: Entry[] }
55 } catch {
56 return
57 }
58 const lanes: Partial<Record<LaneName, Lane>> = {}
59 for (const entry of report.entries ?? []) {
60 const lane = VENDORS[entry.id]
61 if (!lane) continue
62 lanes[lane] = {
63 error: entry.error ?? undefined,
64 windows: (entry.metrics ?? [])
65 .filter(m => typeof m.percent === 'number' && (KEEP[lane]?.test(m.label) ?? true))
66 .map(m => ({
67 name: m.label.replace(/\s*\([^)]*\)\s*$/, '').trim(),
68 pct: m.percent as number,
69 resetsAt: m.reset_at ? Date.parse(m.reset_at) : undefined,
70 windowSecs: m.window_secs,
71 })),
72 }
73 }
74 sample = { at: Date.now(), lanes }
75 spawned.claude = 0
76 spawned.codex = 0
77 spawned.agy = 0
78}
79
80function span(ms: number): string {
81 const m = Math.max(0, Math.round(ms / 60000))
82 if (m < 60) return `${m}m`
83 const h = Math.floor(m / 60)
84 return h < 48 ? `${h}h` : `${Math.floor(h / 24)}d${h % 24}h`
85}
86
87/** Points above (+) or below (−) an even burn of a weekly window. */
88function pace(w: Window, now: number): number | undefined {
89 if (w.windowSecs !== WEEK || w.resetsAt === undefined) return undefined
90 const remaining = w.resetsAt - now
91 if (remaining <= 0 || remaining > WEEK * 1000) return undefined
92 return Math.round(w.pct - 100 * (1 - remaining / (WEEK * 1000)))
93}
94
95function describe(lane: Lane | undefined, now: number): string {
96 if (!lane) return 'no data'
97 if (lane.windows.length === 0) return lane.error ? 'unavailable' : 'no data'
98 return lane.windows
99 .map(w => {
100 if (w.windowSecs === FIVE_HOUR) return `5h ${w.pct}%`
101 const p = pace(w, now)
102 const label = /weekly$/i.test(w.name) ? 'week' : `${w.name} week`
103 const parts = [p === undefined ? undefined : `${p >= 0 ? '+' : '−'}${Math.abs(p)} vs pace`,
104 w.resetsAt ? `resets in ${span(w.resetsAt - now)}` : undefined].filter(Boolean)
105 return `${label} ${w.pct}%${parts.length ? ` (${parts.join(', ')})` : ''}`
106 })
107 .join(', ')
108}
109
110/** The line the model reads, or undefined while there is no sample. */
111export function quotaLine(): string | undefined {
112 if (!sample) return undefined
113 const now = Date.now()
114 const counts = spawned.claude || spawned.codex || spawned.agy
115 ? ` | spawned since: claude ${spawned.claude}, codex ${spawned.codex}, agy ${spawned.agy}`
116 : ''
117 // Left out for anyone without Antigravity in ai-usagebar.
118 const agy = sample.lanes.agy ? ` | agy: ${describe(sample.lanes.agy, now)}` : ''
119 return `[quota, ${span(now - sample.at)} old] claude: ${describe(sample.lanes.claude, now)} | codex: ${describe(sample.lanes.codex, now)}${agy}${counts}`
120}
121types/index.d.ts 34 lines1export type JobView = {
2 id: string
3 engine?: 'codex' | 'antigravity'
4 description: string
5 effort: string
6 cwd: string
7 startedAt: number
8 endedAt?: number
9 status: 'running' | 'done' | 'failed' | 'cancelled'
10}
11
12export type DispatchInput = {
13 brief: string
14 description: string
15 effort: string
16 engine?: 'codex' | 'antigravity'
17 cwd?: string
18 model?: string
19 worktree?: boolean
20}
21
22export type AgentRow = { id: string; description: string; type: string; status: string }
23
24declare module 'claude-code' {
25 interface McpToolInputs {
26 'mcp__codex-lane__dispatch': DispatchInput
27 'mcp__codex-lane__result': { id: string }
28 'mcp__codex-lane__cancel': { id: string }
29 }
30 interface PluginState {
31 'codex-lane': { jobs: JobView[]; agents: AgentRow[]; now: number }
32 }
33}
34