Dispatch tasks to Codex and opencode.

My Claude Code setup: mods, plugins, skills and settings, so a new machine is one clone away.
git clone git@github-personal:aidan-nunn-sys/claude-config.git ~/Work/personal/claude-config
~/Work/personal/claude-config/install.sh
Then:
<SET-ME> values install.sh reports in ~/.claude.json (MCP secrets are never committed).~/.config/mise/config.toml: "npm:optimaizr" = { version = "0.11.0", allow_low_downloads = true }~/.config/mise/config.toml: "npm:agent-browser" = "latest"Mods and skills are symlinked from this repo, so edits land here directly. Settings changed through Claude Code live in ~/.claude; run ./capture.sh and review git diff to bring them back.
| Path | What |
|---|---|
mods/ | Mods loaded through CLAUDE_CODE_PLUGIN_DIRS (built by install.sh from this folder) |
plugins/plugins.json | Marketplaces and which marketplace plugins are enabled |
skills/ | Personal skills, symlinked into ~/.claude/skills |
agents/ | Claude subagents (spec-writer, approver), symlinked into ~/.claude/agents |
opencode/agent/ | opencode agents (factory-reviewer), symlinked into ~/.config/opencode/agent |
settings/settings.json | ~/.claude/settings.json minus plugin dirs, plugins and hooks; ${HOME} for paths |
settings/mcp.json | User MCP servers, secrets blanked |
settings/rulebook.json | Generic example rules (copied only when the machine has none; not captured) |
docs/specs/ | Design specs |
skills/factory runs a spec, build, review, approve, PR loop for one job at a time, in replacenc-erp, ReplaceNCWeb and my-medusa-store. PRs go to dev; the owner merges. Design: docs/specs/2026-10-19-factory-design.md.
Commands: /factory <feature>, /factory next, /factory approve <job-id>, /factory rework <job-id> <note>, /factory retry <job-id>, /factory cleanup.
| Role | Model | Where |
|---|---|---|
| spec-writer | Opus | agents/spec-writer.md |
| builder | Codex gpt-6.1-sol, effort high | xagent dispatch |
| reviewers (security, UX, UI, code) | opencode deepseek-v4.1-flash-free, variant max | xagent dispatch with the factory-reviewer agent |
| approver | Opus | agents/approver.md |
Each repo's CLAUDE.md or AGENTS.md needs a ## Factory section; /factory refuses to start without it. Its labels:
Setup: fresh-checkout setup for a worktree.Env links: git-ignored env files to symlink from the main checkout.Review DB: the database reviewers may use.Dev server: how to start the dev server on a given port.Sign-in: how reviewers sign in to the running app.Validate: test, type-check, build and lint commands.Post-merge hosts: where post-merge steps run, for /factory cleanup.| Mod | Source | Local changes |
|---|---|---|
| hud | own | prompt hint, context weather bar, cache countdown, kaomoji mascot |
| rulebook | own | hard rules in ~/.claude/rulebook.json, /rules, mcp__rulebook__add_rule |
| xagent | own | dispatch for Codex and opencode |
| handoff | own | /handoff [next] writes a handoff doc to ~/.claude/handoffs/ |
| agent-radar | hamzafer/claude-code-mods @ 87f108479bbf | /radar runs mid-turn (immediate) and toggles closed; shows xagent's external agents |
| mission-control | hamzafer/claude-code-mods @ 87f108479bbf | shows xagent's external agents; code-map view (Haiku diff summaries, headless Chrome) stripped |
| blast-radius | hamzafer/claude-code-mods @ 87f108479bbf | 60 s auto-cancel |
| review-watch | hamzafer/claude-code-mods @ 87f108479bbf | none |
| where-am-i | hamzafer/claude-code-mods @ 87f108479bbf | shows only "next" |
| secret-box | ray-amjad/claude-code-mods @ 467b20300d8e | none |
Upstream commits are the repos' HEAD on 2026-10-14, when this repo was made; installs were from around then. Read upstream changes before pulling them in.
~/.claude/.credentials.json and MCP secrets.diagnose-crash, omarchy, symlinks into /usr/share/omarchy), themes/omarchy.json, the herdr SessionStart hook..claude-plugin/types/ in each mod: SDK types Claude Code writes itself.hooks/register.ts 279 lines1// xagent: run Codex as a worker for a Claude Code session. dispatch runs one external agent.
2import { atom, update } from 'claude-code'
3import type { EngineInterface, Register } from 'claude-code'
4
5import type { DispatchInput, DispatchResult, Parsed, ProviderQuota, XAgent } from '../types'
6import { buildArgv } from './backends'
7import { changedFiles, snapshot, treeOf } from './io'
8import { feed, firstLine, parse, sessionIdIn } from './parse'
9import { describeOne, isBlocked } from './quota'
10
11const agents = atom({ plugin: 'xagent', key: 'agents' } as const, [] as XAgent[])
12const blocked = atom({ plugin: 'xagent', key: 'blocked' } as const, {} as Record<string, ProviderQuota>)
13
14const DISPATCH_SCHEMA = {
15 type: 'object',
16 properties: {
17 backend: { type: 'string', enum: ['codex', 'opencode'] },
18 model: { type: 'string' },
19 effort: { type: 'string', enum: ['low', 'medium', 'high', 'xhigh', 'max'] },
20 mode: { type: 'string', enum: ['read-only', 'write'] },
21 prompt: { type: 'string' },
22 dir: { type: 'string', description: 'working directory, absolute' },
23 schema: { type: 'string', description: 'path to a JSON schema file; the full answer comes back as `answer`' },
24 resume: { type: 'string', description: 'sessionId from an earlier dispatch, to continue it' },
25 network: { type: 'boolean', description: 'codex write mode: allow the sandbox network access' },
26 agent: { type: 'string', description: 'opencode: agent name to run as' },
27 outputFile: { type: 'string', description: 'absolute path or ~, shaped <repo>/.factory/jobs/<job>/[round-N/]<name>.md: the whole answer is written here on success' },
28 timeoutMs: { type: 'number' },
29 override: { type: 'boolean', description: 'run on a backend at 90 % of its quota; only when the user said so' },
30 },
31 required: ['backend', 'mode', 'prompt'],
32}
33
34const DEFAULT_TIMEOUT_MS = 20 * 60_000
35const BACKSTOP_S = 5 // coreutils timeout sends TERM this long past the time limit, KILL 10 s later
36const STOP_SLACK_MS = 2_000 // how long past that TERM a stop may take to be confirmed
37// The headroom proxy wrapper exports these; inherited, they put copilot in BYOK mode and bill Claude, not the backend's own subscription login.
38const PROXY_ENV = ['COPILOT_PROVIDER_BASE_URL', 'COPILOT_PROVIDER_TYPE', 'COPILOT_PROVIDER_API_KEY', 'COPILOT_PROVIDER_BEARER_TOKEN', 'COPILOT_MODEL', 'OPENAI_BASE_URL', 'ANTHROPIC_BASE_URL']
39const COOLDOWN_MS = 30 * 60_000
40const LIMIT_WORDS = /usage limit|rate limit|quota|exceeded|\b429\b/i
41// `failed to run command`: coreutils timeout could not start the CLI (not installed, not on PATH).
42const AUTH_WORDS = /not logged in|log in|unauthori[sz]ed|\b401\b|ENOENT|command not found|failed to run command/i
43const RETRY_PROMPT = 'You were stopped at the time limit. Continue the same task from where you are, then give the final answer.'
44
45export function expandHome(path: string, home: string): string {
46 return path === '~' ? home : path.startsWith('~/') ? `${home}${path.slice(1)}` : path
47}
48
49const OUTPUT_FILE = /^\/.+\/\.factory\/jobs\/[^/]+\/(round-\d+\/)?[^/]+\.md$/
50
51export function validOutputFile(path: string): boolean {
52 return OUTPUT_FILE.test(path) && !path.split('/').includes('..')
53}
54
55// The OS backstop, still argv: coreutils timeout ends the child (and what it started) a few
56// seconds past the time limit, whether or not the engine's stream can interrupt a pending pull.
57export function withBackstop(argv: string[], timeoutMs: number): string[] {
58 return ['env', ...PROXY_ENV.flatMap(name => ['-u', name]), 'timeout', '--kill-after=10s', `${Math.ceil(timeoutMs / 1000) + BACKSTOP_S}s`, ...argv]
59}
60
61// How long after the time limit a stop may take to be confirmed: until just past the backstop's TERM.
62export function stopGraceMs(timeoutMs: number): number {
63 return Math.ceil(timeoutMs / 1000) * 1000 - timeoutMs + BACKSTOP_S * 1000 + STOP_SLACK_MS
64}
65
66// Ends the child through its stream (leaving the loop kills it) and says whether that is
67// confirmed within the grace period: stop() resolved, or the pull already under way ended the
68// stream (the child is gone) or failed. A pull that brings more output means it is still alive.
69// A rejected or hanging stop() alone is not confirmed.
70export async function stopStream(stop: () => Promise<unknown>, sleep: () => Promise<void>, pending?: Promise<IteratorResult<unknown, unknown>>): Promise<boolean> {
71 const never = new Promise<boolean>(() => {})
72 const ended = stop().then(() => true, () => false)
73 const pulled = pending ? pending.then(step => (step.done ? true : never), () => true) : never
74 return Promise.race([ended, pulled, sleep().then(() => false)])
75}
76
77async function mark($: EngineInterface, backend: string, q: ProviderQuota) {
78 await update($, blocked, all => ({ ...all, [backend]: q }))
79}
80
81async function track($: EngineInterface, id: string, patch: Partial<XAgent>) {
82 await update($, agents, list => list.map(a => (a.id === id ? { ...a, ...patch } : a)))
83}
84
85// One CLI run. `stopped` is false only when a child we had to stop was not confirmed gone.
86async function runOnce($: EngineInterface, input: DispatchInput, argv: string[], id: string, signal?: AbortSignal): Promise<Parsed & { stopped: boolean }> {
87 const out = feed(input.backend)
88 let stderr = ''
89 let failure: string | undefined
90 let end: { code: number | null; signal: string | null } = { code: null, signal: null }
91 let stopped = true
92 let pulling = false
93 const limit = input.timeoutMs ?? DEFAULT_TIMEOUT_MS
94 // spawn closes stdin from the start (no `input`): codex exec otherwise waits on it.
95 const stream = $.process.spawn({ argv: withBackstop(argv, limit), cwd: input.dir })
96 const stop = () => stream.return({ code: null, signal: null })
97 const grace = () => $.clock.sleep(stopGraceMs(limit))
98 // Wall clock, raced against each pull: a child that prints nothing must still stop.
99 let ring: () => void = () => {}
100 const expired = new Promise<'expired'>(resolve => (ring = () => resolve('expired')))
101 const timer = $.clock.after(limit, () => ring())
102 // The user interrupted (Esc): the engine kills the child; stop reading at once.
103 const aborted = new Promise<'aborted'>(resolve => {
104 if (signal?.aborted) resolve('aborted')
105 else signal?.addEventListener('abort', () => resolve('aborted'), { once: true })
106 })
107 try {
108 while (true) {
109 pulling = true
110 // The pull is kept, not dropped: if the stream cannot be stopped while it is pending, its
111 // end (the backstop killed the child) is what confirms the stop.
112 const pull = stream.next()
113 const step = await Promise.race([pull, expired, aborted])
114 pulling = false
115 if (step === 'aborted') {
116 void stop().catch(() => {})
117 void pull.catch(() => {}) // left unread: its end no longer matters
118 failure = 'interrupted'
119 break
120 }
121 if (step === 'expired') {
122 stopped = await stopStream(stop, grace, pull)
123 failure = stopped ? 'timed out' : 'timed out (child may still be running)'
124 break
125 }
126 if (step.done) {
127 end = step.value ?? end
128 break
129 }
130 const piece = step.value
131 if (piece.stream === 'stderr') {
132 stderr = (stderr + piece.text).slice(-2000)
133 continue
134 }
135 const status = out.push(piece.text)
136 if (status) await track($, id, { last: status })
137 }
138 } catch (err) {
139 failure ??= (err as Error).message
140 // A failed pull means the child never started or already ended. A failure in our own code
141 // between pulls leaves it running, so stop it.
142 if (!pulling) stopped = await stopStream(stop, grace)
143 } finally {
144 timer.cancel()
145 }
146 const stdout = out.text()
147 const sessionId = sessionIdIn(input.backend, stdout)
148 if (failure) return { ok: false, summary: '', sessionId, error: failure, stopped }
149 const result = parse(input.backend, stdout, Boolean(input.schema))
150 const why = stderr.trim().split('\n').slice(-3).join(' ').slice(0, 300)
151 // The CLI's own error (a usage limit, say) says more than stderr or the exit code.
152 const said = !result.ok && result.error !== 'no answer in output' ? result.error : undefined
153 // An answer only counts from a child that ended cleanly.
154 if (end.signal) return { ...result, ok: false, error: said ?? `killed by ${end.signal}`, stopped }
155 if (end.code !== 0) return { ...result, ok: false, error: said ?? (!result.ok && why ? why : `exited with code ${end.code}`), stopped }
156 if (!result.ok && result.error === 'no answer in output' && why) return { ...result, error: why, stopped }
157 return { ...result, stopped }
158}
159
160export async function runDispatch($: EngineInterface, raw: DispatchInput, task: string, signal?: AbortSignal): Promise<DispatchResult> {
161 const home = (await $.env.get('HOME')) ?? ''
162 const input: DispatchInput = { ...raw, dir: raw.dir && expandHome(raw.dir, home), schema: raw.schema && expandHome(raw.schema, home), outputFile: raw.outputFile && expandHome(raw.outputFile, home) }
163 let argv: string[]
164 try {
165 argv = buildArgv(input)
166 } catch (err) {
167 const q = (await snapshot($))[input.backend]
168 return { ok: false, summary: '', sessionId: null, error: (err as Error).message, attempts: 0, baseTree: null, tree: null, filesChanged: null, quota: q }
169 }
170 const startedAt = await $.clock.now()
171 const before = (await snapshot($))[input.backend]
172 const refuse = (error: string, extra: Partial<DispatchResult> = {}): DispatchResult => ({ ok: false, summary: '', sessionId: null, error, attempts: 0, baseTree: null, tree: null, filesChanged: null, quota: before, ...extra })
173 // The 90 % rule: no new work for a provider that close to a limit, unless the user said so.
174 if (!input.override && isBlocked(before, startedAt)) return refuse(`${input.backend} is at 90 % of a quota window: ask the user, or pass override if they allow it`)
175 // outputFile is written outside the host's permission checks: only a job's own .md under .factory.
176 if (input.outputFile !== undefined && !validOutputFile(input.outputFile)) return refuse('outputFile must be <repo>/.factory/jobs/<job>/[round-N/]<name>.md, absolute, with no ..')
177 // A writer may only start once its baseline is known: a lost baseline cannot be taken back after edits.
178 const base = input.mode === 'write' ? await treeOf($, input.dir) : { tree: null }
179 if (base.error) return refuse(`baseline snapshot failed: ${base.error}`, { treeError: base.error })
180 const id = `x${startedAt.toString(36)}${Math.random().toString(36).slice(2, 6)}`
181 const quotaLine = describeOne(input.backend, before, startedAt).split('\n')[0] ?? ''
182 const one: XAgent = { id, backend: input.backend, model: input.model ?? 'default', effort: input.effort ?? 'default', task, status: 'running', startedAt, last: 'starting', quota: quotaLine }
183 await update($, agents, list => [one, ...list].slice(0, 30))
184
185 // From here the agent is listed as running: whatever happens below, it must not stay that way.
186 let ended = false
187 let thrown: unknown
188 try {
189 let attempts = 1
190 let result: Parsed & { stopped: boolean } = await runOnce($, input, argv, id, signal)
191 // One retry, owned here (the skill never retries): only once the first child is known to be
192 // gone, and never after the user interrupted.
193 if (result.error === 'timed out' && result.stopped && !signal?.aborted) {
194 attempts = 2
195 await track($, id, { last: 'timed out; retrying' })
196 const again: DispatchInput = result.sessionId ? { ...input, resume: result.sessionId, prompt: RETRY_PROMPT } : input
197 result = await runOnce($, again, buildArgv(again), id, signal)
198 }
199 // Interrupted: the engine has moved on and may refuse further calls; end the agent first and
200 // skip the tree, diff and quota work.
201 if (signal?.aborted) {
202 await track($, id, { status: 'failed', endedAt: await $.clock.now().catch(() => startedAt), last: 'stopped: interrupted' })
203 ended = true
204 const { stopped: _, full: __, ...parsed } = result
205 return { ...parsed, ok: false, error: 'interrupted', attempts, baseTree: base.tree, tree: null, filesChanged: null, quota: before }
206 }
207
208 const now = await $.clock.now()
209 // An interrupt says nothing about the backend: leave its quota marks alone.
210 if (!result.ok && !signal?.aborted) {
211 const why = result.error ?? ''
212 if (AUTH_WORDS.test(why)) await mark($, input.backend, { state: 'unavailable', reason: why.slice(0, 80) })
213 // opencode is free-tier: its 429s and "exceeded" output-length errors must not block the one rerun.
214 else if (input.backend !== 'opencode' && LIMIT_WORDS.test(why)) await mark($, input.backend, { state: 'cooldown', until: now + COOLDOWN_MS })
215 }
216 // The whole answer goes to the file, uncut. A failed run writes nothing. This comes after the quota marks: a write failure says nothing about the backend.
217 let written: string | undefined
218 if (result.ok && input.outputFile && result.full !== undefined) {
219 try {
220 await $.fs.write(input.outputFile, `${result.full}\n`)
221 written = input.outputFile
222 } catch (err) {
223 result = { ...result, ok: false, error: `could not write outputFile: ${(err as Error).message}` }
224 }
225 }
226
227 const after = base.tree ? await treeOf($, input.dir) : { tree: null }
228 const diff = base.tree && after.tree && input.dir ? await changedFiles($, input.dir, base.tree, after.tree) : null
229 const treeError = after.error ?? (diff && 'error' in diff ? diff.error : undefined)
230 const quota = (await snapshot($))[input.backend]
231 await track($, id, { status: result.ok ? 'done' : 'failed', endedAt: now, last: result.ok ? 'finished' : `stopped: ${result.error}` })
232 ended = true
233 const { stopped: _, full: __, ...parsed } = result
234 return {
235 ...parsed,
236 ...(written ? { outputFile: written } : {}),
237 attempts,
238 baseTree: base.tree,
239 tree: after.tree,
240 filesChanged: diff && 'files' in diff ? diff.files : null,
241 quota,
242 ...(treeError ? { treeError } : {}),
243 }
244 } catch (err) {
245 thrown = err
246 throw err
247 } finally {
248 if (!ended) {
249 const why = thrown instanceof Error ? thrown.message : signal?.aborted ? 'interrupted' : String(thrown ?? 'unknown')
250 const at = await $.clock.now().catch(() => startedAt)
251 await track($, id, { status: 'failed', endedAt: at, last: `stopped: ${why}` }).catch(() => {})
252 }
253 }
254}
255
256export const register: Register = on => {
257 on('session.start', async ($, e, next) => {
258 const r = await next(e)
259 await $.tool.register({ name: 'dispatch', description: 'Run one task on an external coding agent (codex or opencode). Returns a short summary, the files it changed and a sessionId for resume.', inputSchema: DISPATCH_SCHEMA }).catch(() => {})
260 return r
261 })
262
263 // A gating hook answers even when something in it throws.
264 on('tool.call', { tool: 'mcp__xagent__dispatch' }, async ($, e, next) => {
265 const input: DispatchInput = e
266 return runDispatch($, input, firstLine(input.prompt, 80), next.signal)
267 .then(r => ({ result: JSON.stringify(r) }))
268 .catch((err: Error) => ({ deny: `xagent dispatch failed: ${err.message}` }))
269 })
270
271 // The transcript row echoes the whole input, prompt included; draw the prompt's first line only.
272 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
273 if (e.props.tool !== 'mcp__xagent__dispatch') return next(e)
274 const input = (e.props.input ?? {}) as Record<string, unknown>
275 const prompt = typeof input.prompt === 'string' ? firstLine(input.prompt, 80) : input.prompt
276 return next({ ...e, props: { ...e.props, input: { ...input, prompt } } })
277 })
278}
279hooks/backends.ts 36 lines1// The command line for one dispatch. No shell: each element is one argv entry.
2import type { DispatchInput } from '../types'
3
4// opencode has no sandbox flag, so a run is only as read-only as its agent: only these deny edits.
5export const OPENCODE_READONLY_AGENTS = ['factory-reviewer']
6
7export function buildArgv(i: DispatchInput): string[] {
8 if (i.backend === 'codex') {
9 // `exec resume` takes no -s or -C, so the sandbox goes through -c and the directory through spawn's cwd.
10 const argv = ['codex', 'exec', ...(i.resume ? ['resume'] : []), '--json', '--skip-git-repo-check', '-c', `sandbox_mode="${i.mode === 'write' ? 'workspace-write' : 'read-only'}"`]
11 if (i.model) argv.push('-m', i.model)
12 if (i.effort) argv.push('-c', `model_reasoning_effort=${i.effort}`)
13 if (i.network && i.mode === 'write') argv.push('-c', 'sandbox_workspace_write.network_access=true')
14 if (i.schema) argv.push('--output-schema', i.schema)
15 // `--` ends the options: a prompt starting with `-` (a pasted "- [ ] Step") is not a flag.
16 if (i.resume) return [...argv, '--', i.resume, i.prompt]
17 if (i.dir) argv.push('-C', i.dir)
18 return [...argv, '--', i.prompt]
19 }
20 if (i.backend === 'opencode') {
21 if (i.mode !== 'read-only') throw new Error('opencode runs read-only only')
22 if (!i.agent) throw new Error('opencode read-only needs an agent with edits denied')
23 if (!OPENCODE_READONLY_AGENTS.includes(i.agent)) throw new Error(`opencode agent ${i.agent} is not an allowed read-only agent`)
24 // Never --auto: a run that needs approval fails rather than approving itself.
25 // --flag=value, so a value starting with `-` cannot become a flag.
26 const argv = ['opencode', 'run', '--format', 'json']
27 if (i.model) argv.push(`--model=${i.model}`)
28 if (i.effort) argv.push(`--variant=${i.effort}`)
29 if (i.agent) argv.push(`--agent=${i.agent}`)
30 if (i.dir) argv.push(`--dir=${i.dir}`)
31 if (i.resume) argv.push(`--session=${i.resume}`)
32 return [...argv, '--', i.prompt]
33 }
34 throw new Error(`unknown backend ${String(i.backend)}`)
35}
36hooks/io.ts 86 lines1// What xagent reads from the host: git trees of a working directory, and each provider's quota.
2import { atom, read } from 'claude-code'
3import type { EngineInterface } from 'claude-code'
4
5import type { ProviderQuota, Snapshot } from '../types'
6import { claudeFromUsage, codexFromRollout, merge } from './quota'
7
8const blocked = atom({ plugin: 'xagent', key: 'blocked' } as const, {} as Record<string, ProviderQuota>)
9
10export type Tree = { tree: string | null; error?: string }
11
12async function home($: EngineInterface) {
13 return (await $.env.get('HOME')) ?? ''
14}
15
16const lastErr = (stderr: string) => stderr.trim().split('\n').slice(-1)[0] ?? ''
17
18// The working tree, untracked files included, as a git tree object. A scratch index keeps the
19// user's own index untouched. `tree: null` with no error: not a git repo.
20export async function treeOf($: EngineInterface, dir?: string): Promise<Tree> {
21 if (!dir) return { tree: null }
22 const inside = await $.process.run(['git', '-C', dir, 'rev-parse', '--is-inside-work-tree'], { timeoutMs: 10_000 }).catch(() => null)
23 if (!inside || inside.exitCode !== 0) return { tree: null }
24 const scratch = `${await home($)}/.cache/xagent`
25 const index = `${scratch}/index-${await $.clock.now()}-${Math.random().toString(36).slice(2, 8)}`
26 try {
27 const made = await $.process.run(['mkdir', '-p', scratch], { timeoutMs: 5_000 })
28 if (made.exitCode !== 0) return { tree: null, error: `mkdir ${scratch}: ${lastErr(made.stderr)}` }
29 const git = (args: string[]) => $.process.run(['git', '-C', dir, ...args], { env: { GIT_INDEX_FILE: index }, timeoutMs: 60_000 })
30 if ((await git(['read-tree', 'HEAD'])).exitCode !== 0) {
31 const empty = await git(['read-tree', '--empty']) // a repo with no commits yet
32 if (empty.exitCode !== 0) return { tree: null, error: `git read-tree: ${lastErr(empty.stderr)}` }
33 }
34 const added = await git(['add', '-A'])
35 if (added.exitCode !== 0) return { tree: null, error: `git add: ${lastErr(added.stderr)}` }
36 const tree = await git(['write-tree'])
37 if (tree.exitCode !== 0 || !tree.stdout.trim()) return { tree: null, error: `git write-tree: ${lastErr(tree.stderr)}` }
38 return { tree: tree.stdout.trim() }
39 } catch (err) {
40 return { tree: null, error: (err as Error).message }
41 } finally {
42 await $.process.run(['rm', '-f', index], { timeoutMs: 5_000 }).catch(() => null)
43 }
44}
45
46// NUL-separated names, so paths with spaces or non-ASCII come back as they are.
47export async function changedFiles($: EngineInterface, dir: string, a: string, b: string): Promise<{ files: string[] } | { error: string }> {
48 const r = await $.process.run(['git', '-C', dir, 'diff', '--name-only', '-z', a, b], { timeoutMs: 30_000 }).catch(() => null)
49 if (!r || r.exitCode !== 0) return { error: `git diff: ${lastErr(r?.stderr ?? 'did not run')}` }
50 if (r.isStdoutTruncated) return { error: 'git diff: file list too long' }
51 return { files: r.stdout.split('\0').filter(Boolean) }
52}
53
54// The rollout written most recently (a resumed old session counts), read from its end: the first
55// rate_limits sample found is the newest. Up to three files, for one with no sample yet.
56async function codexQuota($: EngineInterface) {
57 const sessions = `${await home($)}/.codex/sessions`
58 const found = await $.process.run(['find', sessions, '-name', 'rollout-*.jsonl', '-mtime', '-8', '-printf', '%T@ %p\\n'], { timeoutMs: 10_000 }).catch(() => null)
59 if (!found || found.exitCode !== 0) return codexFromRollout('')
60 const newest = found.stdout
61 .split('\n')
62 .map(l => /^(\S+) (.+)$/.exec(l))
63 .flatMap(m => (m?.[1] && m[2] ? [{ at: Number(m[1]), path: m[2] }] : []))
64 .sort((x, y) => y.at - x.at)
65 .slice(0, 3)
66 for (const f of newest) {
67 // tac puts the end first; process.run keeps the first 4 MB, so that is the file's last 4 MB.
68 const r = await $.process.run(['tac', f.path], { timeoutMs: 10_000 }).catch(() => null)
69 if (!r || r.exitCode !== 0) continue
70 const q = codexFromRollout(r.stdout.split('\n').reverse().join('\n'))
71 if (q.state !== 'unknown') return q
72 }
73 return codexFromRollout('')
74}
75
76export async function snapshot($: EngineInterface): Promise<Snapshot> {
77 const now = await $.clock.now()
78 const marks = await read($, blocked)
79 const usage = await $.session.usage().catch(() => null)
80 return {
81 claude: claudeFromUsage(usage?.rateLimits ?? []),
82 codex: merge(marks.codex, await codexQuota($), now),
83 opencode: merge(marks.opencode, { state: 'unknown' }, now),
84 }
85}
86hooks/parse.ts 141 lines1// Reads each CLI's JSON lines into one result, and one line of status for the radar.
2import type { Backend, Parsed } from '../types'
3
4export const SUMMARY_CAP = 4000
5export const STRUCTURED_CAP = 200_000
6export const KEEP_CAP = 2 * STRUCTURED_CAP // what feed() keeps of a run's stdout
7
8type J = Record<string, any>
9
10function lines(stdout: string): J[] {
11 const out: J[] = []
12 for (const l of stdout.split('\n')) {
13 try {
14 const j = JSON.parse(l)
15 if (j && typeof j === 'object') out.push(j)
16 } catch {}
17 }
18 return out
19}
20
21export function firstLine(text: string, n: number): string {
22 return (text.split('\n')[0] ?? '').slice(0, n)
23}
24
25function done(answer: string | null, sessionId: string | null, error: string | undefined, structured: boolean): Parsed {
26 const summary = (answer ?? '').trim().slice(0, SUMMARY_CAP)
27 if (error) return { ok: false, summary, sessionId, error }
28 if (answer === null) return { ok: false, summary: '', sessionId, error: 'no answer in output' }
29 if (!structured) return { ok: true, summary, full: answer.trim(), sessionId }
30 // A schema answer goes back whole: a cut one is not JSON and would break the plan-review loop.
31 const whole = answer.trim()
32 if (whole.length > STRUCTURED_CAP) return { ok: false, summary, sessionId, error: 'answer too long' }
33 try {
34 JSON.parse(whole)
35 } catch {
36 return { ok: false, summary, sessionId, error: 'answer is not valid JSON' }
37 }
38 return { ok: true, summary, full: whole, answer: whole, sessionId }
39}
40
41export function sessionIdIn(backend: Backend, stdout: string): string | null {
42 let id: string | null = null
43 for (const j of lines(stdout)) {
44 if (backend === 'codex' && j.type === 'thread.started') id = j.thread_id ?? null
45 if (backend === 'opencode' && !id && typeof j.sessionID === 'string') id = j.sessionID
46 }
47 return id
48}
49
50export function parse(backend: Backend, stdout: string, structured: boolean): Parsed {
51 let answer: string | null = null
52 let error: string | undefined
53 const sessionId = sessionIdIn(backend, stdout)
54 if (backend === 'codex') {
55 for (const j of lines(stdout)) {
56 if (j.type === 'item.completed' && j.item?.type === 'agent_message') answer = String(j.item.text ?? '')
57 if (j.type === 'turn.failed' || j.type === 'error') error = j.error?.message ?? j.message ?? 'codex failed'
58 }
59 }
60 if (backend === 'opencode') {
61 for (const j of lines(stdout)) {
62 if (j.type === 'text') answer = String(j.part?.text ?? '')
63 if (j.type === 'error') error = j.error?.data?.message ?? j.error?.message ?? 'opencode failed'
64 }
65 }
66 return done(answer, sessionId, error, structured)
67}
68
69// The lines parse() and sessionIdIn() read. Command output and reasoning are dropped as they stream.
70function wanted(backend: Backend, j: J, first: boolean): boolean {
71 if (backend === 'codex') return j.type === 'thread.started' || j.type === 'turn.failed' || j.type === 'error' || (j.type === 'item.completed' && j.item?.type === 'agent_message')
72 if (backend === 'opencode') return first || j.type === 'text' || j.type === 'error' // the first event carries sessionID
73 return false
74}
75
76// Takes stdout as it streams. An event can arrive split across chunks, so lines are put back
77// together first. Only wanted lines are kept, within KEEP_CAP: the oldest go first, except the
78// first, which carries the session id.
79export function feed(backend: Backend) {
80 let partial = ''
81 let size = 0
82 const kept: string[] = []
83 let first = true
84 const take = (line: string): string | null => {
85 let j: J
86 try {
87 j = JSON.parse(line)
88 } catch {
89 return null
90 }
91 if (!j || typeof j !== 'object') return null
92 const isFirst = first
93 first = false
94 if (wanted(backend, j, isFirst)) {
95 kept.push(line)
96 size += line.length + 1
97 while (size > KEEP_CAP && kept.length > 1) size -= (kept.splice(1, 1)[0] ?? '').length + 1
98 }
99 return lastLine(backend, line)
100 }
101 return {
102 // The newest radar status in this chunk, if any.
103 push(text: string): string | null {
104 const parts = (partial + text).split('\n')
105 partial = parts.pop() ?? ''
106 if (partial.length > KEEP_CAP) partial = '' // a line that long is never a usable answer
107 let status: string | null = null
108 for (const l of parts) status = take(l) ?? status
109 return status
110 },
111 // What parse() should read, including a last line that had no newline.
112 text(): string {
113 if (partial) take(partial)
114 partial = ''
115 return kept.join('\n')
116 },
117 }
118}
119
120export function lastLine(backend: Backend, line: string): string | null {
121 let j: J
122 try {
123 j = JSON.parse(line)
124 } catch {
125 return null
126 }
127 if (backend === 'codex') {
128 if (j.item?.type === 'command_execution') return `running ${String(j.item.command).slice(0, 60)}`
129 if (j.item?.type === 'file_change') return 'editing files'
130 if (j.item?.type === 'agent_message') return 'writing'
131 if (j.type === 'turn.started') return 'thinking'
132 return null
133 }
134 if (backend === 'opencode') {
135 if (j.type === 'tool_use') return `tool: ${String(j.part?.tool ?? 'unknown').slice(0, 60)}`
136 if (j.type === 'text') return 'writing'
137 return null
138 }
139 return null
140}
141hooks/quota.ts 68 lines1// Quota per provider: windows of used %, pace against elapsed time, and the 90 % stop.
2// A window past its reset and a cooldown past its end are old news: they never block.
3import type { ProviderQuota, Window } from '../types'
4
5export const BLOCK_AT = 90
6const KIND_MINUTES: Record<string, number> = { five_hour: 300, seven_day: 10080 }
7
8const current = (w: Window, now: number) => w.resetsAt === null || w.resetsAt > now
9
10export function pace(w: Window, now: number): number | null {
11 if (w.resetsAt === null || w.resetsAt <= now) return null
12 const total = w.windowMinutes * 60_000
13 const elapsed = Math.min(Math.max(total - (w.resetsAt - now), 0), total)
14 return w.usedPercent - (elapsed / total) * 100
15}
16
17export function isBlocked(q: ProviderQuota, now: number): boolean {
18 if (q.state === 'unavailable') return true
19 if (q.state === 'cooldown') return q.until > now
20 if (q.state === 'windows') return q.windows.some(w => current(w, now) && w.usedPercent >= BLOCK_AT)
21 return false
22}
23
24export function merge(mark: ProviderQuota | undefined, live: ProviderQuota, now: number): ProviderQuota {
25 if (mark?.state === 'unavailable') return mark
26 if (mark?.state === 'cooldown' && mark.until > now) return mark
27 return live
28}
29
30export function codexFromRollout(text: string): ProviderQuota {
31 let last: any = null
32 for (const l of text.split('\n')) {
33 if (!l.includes('rate_limits')) continue
34 try {
35 const j = JSON.parse(l)
36 if (j.payload?.rate_limits) last = j.payload.rate_limits
37 } catch {}
38 }
39 if (!last) return { state: 'unknown' }
40 const windows: Window[] = [last.primary, last.secondary]
41 .filter((w: any) => w && typeof w.used_percent === 'number')
42 .map((w: any) => ({ usedPercent: w.used_percent, windowMinutes: w.window_minutes ?? 300, resetsAt: typeof w.resets_at === 'number' ? w.resets_at * 1000 : null }))
43 return windows.length ? { state: 'windows', windows } : { state: 'unknown' }
44}
45
46export function claudeFromUsage(limits: { kind: string; percentUsed: number; resetsAt?: string }[]): ProviderQuota {
47 if (!limits.length) return { state: 'unknown' }
48 return {
49 state: 'windows',
50 windows: limits.map(l => ({ usedPercent: l.percentUsed, windowMinutes: KIND_MINUTES[l.kind] ?? 300, resetsAt: l.resetsAt ? Date.parse(l.resetsAt) : null })),
51 }
52}
53
54function windowLine(name: string, w: Window, now: number): string {
55 if (w.resetsAt !== null && w.resetsAt <= now) return `${name}: ${w.windowMinutes}m window reset passed`
56 const p = pace(w, now)
57 const lead = p === null ? 'reset time unknown' : p >= 0 ? `${Math.round(p)} ahead of pace` : `${Math.round(-p)} behind pace`
58 const resets = w.resetsAt === null ? '' : `, resets in ${Math.round((w.resetsAt - now) / 60_000)}m`
59 return `${name}: ${w.windowMinutes}m window ${Math.round(w.usedPercent)}% used, ${lead}${resets}`
60}
61
62export function describeOne(name: string, q: ProviderQuota, now: number): string {
63 if (q.state === 'unknown') return `${name}: unknown`
64 if (q.state === 'unavailable') return `${name}: unavailable (${q.reason})`
65 if (q.state === 'cooldown') return q.until > now ? `${name}: cooling down for ${Math.round((q.until - now) / 60_000)}m` : `${name}: unknown`
66 return q.windows.map(w => windowLine(name, w, now)).join('\n')
67}
68types/index.d.ts 71 lines1export type Backend = 'codex' | 'opencode'
2export type Mode = 'read-only' | 'write'
3export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
4
5export type DispatchInput = {
6 backend: Backend
7 model?: string
8 effort?: Effort
9 mode: Mode
10 prompt: string
11 dir?: string
12 schema?: string // path to a JSON schema file; the answer must parse as JSON
13 resume?: string // session id from an earlier result
14 network?: boolean // codex, write mode only: let the sandboxed run reach the network
15 agent?: string // opencode: the agent to run as
16 outputFile?: string // absolute path or ~, shaped <repo>/.factory/jobs/<job>/[round-N/]<name>.md: the whole answer is written here on success
17 timeoutMs?: number
18 override?: boolean // run even though the backend is at 90 % of a window: only when the user said so
19}
20
21// What one CLI run's output says.
22export type Parsed = {
23 ok: boolean
24 summary: string // at most SUMMARY_CAP chars, for display
25 full?: string // internal: the whole answer, never returned; register.ts writes it to outputFile
26 answer?: string // with a schema: the whole answer, valid JSON
27 sessionId: string | null
28 error?: string
29}
30
31export type DispatchResult = Omit<Parsed, 'full'> & {
32 outputFile?: string // where the whole answer was written
33 attempts: number
34 baseTree: string | null // git tree of `dir` before the run; null outside a repo or read-only
35 tree: string | null // git tree after the run
36 filesChanged: string[] | null // paths that differ between baseTree and tree
37 treeError?: string // a git snapshot failed inside a repo (filesChanged is then null)
38 quota: ProviderQuota // this backend's quota, read after the run
39}
40
41export type XAgent = {
42 id: string
43 backend: Backend
44 model: string
45 effort: string
46 task: string
47 status: 'running' | 'done' | 'failed'
48 startedAt: number
49 endedAt?: number
50 last: string
51 quota: string // the backend's quota line when it started
52}
53
54export type Window = { usedPercent: number; windowMinutes: number; resetsAt: number | null } // resetsAt: epoch ms, null when unknown
55export type ProviderQuota =
56 | { state: 'unknown' }
57 | { state: 'windows'; windows: Window[] }
58 | { state: 'cooldown'; until: number }
59 | { state: 'unavailable'; reason: string }
60export type Snapshot = { claude: ProviderQuota; codex: ProviderQuota; opencode: ProviderQuota }
61
62declare module 'claude-code' {
63 interface PluginState {
64 xagent: { agents: XAgent[]; blocked: Record<string, ProviderQuota> }
65 }
66 // Written by hand: the generated MCP types only know servers that were connected when they were made.
67 interface McpToolInputs {
68 mcp__xagent__dispatch: DispatchInput
69 }
70}
71