SLOPSHOPPER

codex-subagent

Agent types backed by OpenAI GPT through a per-session codex app-server daemon: the Agent tool spawns codex-subagent:luna or codex-subagent:sol like any…

processnetworktimeragents
A shopper browsing a rack in a slop shop
README

.dotfiles

Installation

Windows CMD

Requirements:

  • Windows CMD
  • curl executable
  • Winget executable (>= v1.6.2631, follow instruction from winget repository if you don't have or have a lower version)
curl -L dotfiles.ranolp.dev/setup | cmd /Q

Windows PowerShell (TODO)

Requirements:

  • Windows PowerShell
  • Winget executable (>= v1.6.2631, follow instruction from winget repository if you don't have or have a lower version)
curl dotfiles.ranolp.dev/setup | iex

Windows ArchWSL (WIP)

Requirements:

  • ArchWSL Bash
  • curl executable
curl -L dotfiles.ranolp.dev/setup | sh

macOS (TODO)

Requirements:

  • macOS zsh
  • curl executable
curl -L dotfiles.ranolp.dev/setup | sh
Source 1 files
hooks/register.ts 868 lines
1import type { ApiMessage, EngineInterface, Register, SessionMessage, Timer, TimerCall, TurnStepChunk, TurnStepResult, TurnUsage } from 'claude-code'
2
3// codex-subagent: pinned GPT agent types, served by codex app-server.
4//
5// The Agent tool spawns `codex-subagent:luna` (or `:sol`) like any agent, so
6// the engine owns the agentId, the background task, the completion
7// notification and SendMessage resumes. This plugin answers every `turn.step`
8// of those agents without `next`, so no Claude request is ever sent.
9//
10// Codex keeps its own shell and apply_patch, sandboxed by the agent type. The
11// Claude-side tools codex lacks (read-only MCP tools, Skill, WebFetch, WebSearch)
12// are handed to codex as dynamic tools. When codex calls one, the step answers
13// with that tool_use and stops with `tool_use`, so Claude Code runs the tool
14// inside this agent's loop (hooks, permissions, MCP auth all apply); the next
15// step reads the tool_result and hands it back to the codex call that is still
16// waiting. The agent's first message (CLAUDE.md, skill listing, environment)
17// becomes codex's developer instructions.
18//
19// A hooks module has no Node and no sockets, so the daemon is a node bridge
20// (daemon/codex-bridge.mjs) speaking HTTP on a unix socket to the mod and
21// JSON-RPC on stdio to `codex app-server`.
22
23export const TYPES = {
24  luna: { model: 'gpt-6-luna', effort: 'xhigh', sandbox: 'workspace-write', blurb: 'slow but cheap implementer, only for a task that may run slow but must run cheap' },
25  sol: { model: 'gpt-5.6-sol', effort: 'medium', sandbox: 'workspace-write', blurb: 'default implementer for code changes from a settled plan' },
26} as const
27type TypeName = keyof typeof TYPES
28const PREFIX = 'codex-subagent:'
29const MODEL_AUTO_COMPACT_TOKEN_LIMIT = 150000
30
31// Claude-side tools codex has no equivalent of. Read/Edit/Write/Bash/Grep/Glob
32// stay codex's own (shell + apply_patch). Agent is left out: a codex agent
33// spawning agents would nest a second agent loop under a step this plugin holds.
34type JsonSchema = Record<string, unknown>
35const str = (description: string) => ({ type: 'string', description })
36export const BUILTIN_RELAY: Record<string, JsonSchema> = {
37  Skill: { type: 'object', properties: { skill: str('A skill name from the available-skills list'), args: str('Optional arguments for the skill') }, required: ['skill'] },
38  WebFetch: { type: 'object', properties: { url: str('The URL to fetch'), prompt: str('What to extract from the fetched content') }, required: ['url', 'prompt'] },
39  WebSearch: {
40    type: 'object',
41    properties: { query: str('The search query'), allowed_domains: { type: 'array', items: { type: 'string' } }, blocked_domains: { type: 'array', items: { type: 'string' } } },
42    required: ['query'],
43  },
44}
45// $.tool.list() carries no input schema, so an MCP tool leaves the mod as an
46// open object; the bridge swaps in the schema it harvests (see the bridge),
47// and Claude Code's own validator answers a malformed call either way.
48const OPEN_OBJECT: JsonSchema = { type: 'object', additionalProperties: true }
49
50// Codex reserves the `mcp__` prefix for its own MCP tools ("dynamic tool name
51// is reserved") and the Responses API caps a function name at 64 characters
52// of [A-Za-z0-9_-], so an MCP tool goes to codex as `claude_mcp__…`, hashed
53// when that would run long. Built-in names pass through unchanged.
54export function codexName(claudeName: string): string {
55  if (!claudeName.startsWith('mcp__')) return claudeName
56  const name = `claude_${claudeName}`.replace(/[^A-Za-z0-9_-]/g, '_')
57  if (name.length <= 64) return name
58  let h = 0x811c9dc5
59  for (let i = 0; i < claudeName.length; i++) h = Math.imul(h ^ claudeName.charCodeAt(i), 0x01000193) >>> 0
60  return `${name.slice(0, 55)}_${h.toString(16).padStart(8, '0')}`
61}
62
63export type DynamicTool = { type: 'function'; name: string; description: string; inputSchema: JsonSchema }
64// `mcp` maps each MCP tool's codex name to its Claude name, the key the bridge's harvested schemas use.
65export type Relay = { tools: DynamicTool[]; claudeName: Map<string, string>; mcp: Record<string, string> }
66export function relaySet(tools: readonly { name: string; description: string; mcp: boolean }[]): Relay {
67  const claudeName = new Map<string, string>()
68  const mcp: Record<string, string> = {}
69  const out: DynamicTool[] = []
70  const readOnly = /^(?:[a-z0-9]+_)*?(get|list|read|search|fetch|query|lookup|find|preview|whoami|guide)(?:_|$|[A-Z])/i
71  for (const t of tools) {
72    if (!t.mcp && !(t.name in BUILTIN_RELAY)) continue
73    const toolName = t.name.slice(t.name.lastIndexOf('__') + 2)
74    if (t.mcp && (!t.name.startsWith('mcp__') || !readOnly.test(toolName))) continue
75    const name = codexName(t.name)
76    claudeName.set(name, t.name)
77    if (t.mcp) mcp[name] = t.name
78    const description = name === t.name ? t.description || t.name : `Claude Code tool ${t.name}. ${t.description}`.trim()
79    out.push({ type: 'function', name, description, inputSchema: BUILTIN_RELAY[t.name] ?? OPEN_OBJECT })
80  }
81  return { tools: out, claudeName, mcp }
82}
83
84export function typeOf(subagentType: string): TypeName | undefined {
85  if (!subagentType.startsWith(PREFIX)) return undefined
86  const t = subagentType.slice(PREFIX.length)
87  return t in TYPES ? (t as TypeName) : undefined
88}
89
90// A step naming one of these models is a codex agent's, whatever this module
91// knows of its id: Anthropic answers every one of them 404 model_not_found.
92export function typeForModel(model: string): TypeName | undefined {
93  return (Object.keys(TYPES) as TypeName[]).find(t => TYPES[t].model === model)
94}
95
96// A Claude model as the engine names one: an id, a provider-prefixed id, or an alias.
97const CLAUDE_MODEL = /claude|anthropic|^(?:opus|sonnet|haiku|fable|opusplan|best|default)(?:\[|-|$)/i
98
99// Whether a step belongs to codex, and which type serves it. The agent's type
100// decides first: a model may be a stale definition's (`gpt-5.6-luna` from
101// before a reload) or an Agent-tool override (`opus`), and either must still
102// stay off Claude. Any non-Claude model also counts, since Anthropic would 404 it.
103export type Claim = { ours: boolean; type?: TypeName }
104export function codexClaim(model: string, subagentType?: string): Claim {
105  if (subagentType?.startsWith(PREFIX)) return { ours: true, type: typeOf(subagentType) ?? typeForModel(model) }
106  const type = typeForModel(model)
107  if (type) return { ours: true, type }
108  return { ours: model !== '' && !CLAUDE_MODEL.test(model) }
109}
110
111// The thread cwd is codex's workspace-write root. $.session.cwd() follows a
112// shell `cd` in the main session, so a worker spawned from a subdirectory
113// could write only there; the repo root keeps the whole project writable.
114// Outside a repo (or with no git) the spawn directory itself stays the root.
115export async function workspaceRoot(run: EngineInterface['process']['run'], cwd: string): Promise<string> {
116  try {
117    const r = await run(['git', 'rev-parse', '--show-toplevel'], { cwd })
118    const top = r.stdout.trim()
119    return r.exitCode === 0 && top ? top : cwd
120  } catch {
121    return cwd
122  }
123}
124
125const stripReminders = (s: string) => s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim()
126
127// The text this step must hand codex: the newest user row that is a real
128// message (the spawn prompt on the first step, a SendMessage on a resume).
129// A tool-result row can also carry a new user message, so its text is real
130// prompt input and must not be discarded.
131export function pendingPrompt(rows: readonly SessionMessage[]): string | undefined {
132  for (let i = rows.length - 1; i >= 0; i--) {
133    const r = rows[i]
134    if (!r) continue
135    if (r.role === 'assistant') return undefined
136    const text = stripReminders(r.text)
137    if (text) return text
138  }
139  return undefined
140}
141
142type ContentItem = { type: 'inputText'; text: string } | { type: 'inputImage'; imageUrl: string }
143
144function toItems(content: unknown): ContentItem[] {
145  const blocks = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : []
146  const items: ContentItem[] = []
147  for (const b of blocks as { type: string; text?: string; source?: { type: string; media_type?: string; data?: string; url?: string } }[]) {
148    if (b.type === 'text' && b.text) {
149      const text = stripReminders(b.text)
150      if (text) items.push({ type: 'inputText', text })
151    } else if (b.type === 'image' && b.source) {
152      const url = b.source.type === 'base64' ? `data:${b.source.media_type};base64,${b.source.data}` : b.source.url
153      if (url) items.push({ type: 'inputImage', imageUrl: url })
154    }
155  }
156  return items
157}
158
159// The answer to a relayed call: its tool_result, plus the text blocks Claude
160// Code puts after it in the same message (a Skill's body arrives that way).
161// A message delivered to the agent while the call ran (`delivered`, the texts
162// session.receive queued) rides in that same message but is not the tool's:
163// it comes back apart as `messages`, for codex to read as user input.
164export function toolResultFor(api: readonly ApiMessage[], toolUseId: string, delivered: readonly string[] = []): { contentItems: ContentItem[]; success: boolean; messages?: string[] } | undefined {
165  const last = api[api.length - 1]
166  if (!last || last.role !== 'user') return undefined
167  const blocks = last.content as ApiBlock[]
168  const i = blocks.findIndex(b => b.type === 'tool_result' && b.tool_use_id === toolUseId)
169  if (i < 0) return undefined
170  const r = blocks[i]
171  if (!r) return undefined
172  const trailing = blocks.slice(i + 1).filter(b => b.type === 'text' || b.type === 'image')
173  const isDelivered = (b: ApiBlock) => b.type === 'text' && typeof b.text === 'string' && delivered.some(d => d !== '' && stripReminders(b.text!).includes(d))
174  const messages = trailing.filter(isDelivered).map(b => stripReminders(b.text!))
175  const contentItems = r.toolDenialKind === 'user-rejected'
176    ? [{ type: 'inputText' as const, text: 'user rejected this tool call' }]
177    : [...toItems(r.content), ...toItems(trailing.filter(b => !isDelivered(b)))]
178  return { contentItems: contentItems.length ? contentItems : [{ type: 'inputText', text: '(empty result)' }], success: !r.is_error, ...(messages.length ? { messages } : {}) }
179}
180
181// What the agent's first message carries ahead of the task itself: hook
182// context, the deferred-tool list, environment, skill listing, CLAUDE.md,
183// date. The last text block is the spawn prompt, which goes in as the turn.
184export function inheritedContext(api: readonly ApiMessage[]): string {
185  const first = api[0]
186  if (!first || first.role !== 'user') return ''
187  const texts = (first.content as { type: string; text?: string }[]).filter(b => b.type === 'text' && b.text).map(b => b.text!)
188  return texts.slice(0, -1).join('\n\n')
189}
190
191const PREAMBLE = `You are running as a subagent inside a Claude Code session; a Claude model delegated this task to you and reads your final message as the result.
192- Do file reads, edits and commands with your own shell and apply_patch tools.
193- The Claude session's other tools are relayed to you as dynamic tools: read-only mcp__<server>__<tool> as claude_mcp__<server>__<tool>, Skill (load a skill from the listing below by name, then follow what it returns), WebFetch and WebSearch. Call them through tools.<name> in exec. Claude Code runs them with its own permissions and returns the result.
194- Never call spawn_agent, followup_task, send_message, wait_agent, interrupt_agent or list_agents: this task runs in one agent, you.
195- Where the instructions below name Claude tools you do not have (Read, Edit, Write, Bash, Grep, Glob, Agent, Task*), use your shell or apply_patch for the same effect, or skip the step.
196
197The Claude session's context for this agent follows.`
198
199// In auto mode the harness delivers a subagent's report only through a
200// SubagentHandback call and drops its final text, so the mod makes that call
201// with codex's answer; codex itself never sees the tool. `handback` holds the
202// report until the call's result shows whether it was delivered.
203const HANDBACK = 'SubagentHandback'
204type Agent = { type: TypeName; cwd: string; writableRoots: string[]; threadId?: string; waiting?: { toolUseId: string; callId: string }; relay?: Relay; handback?: { toolUseId: string; text: string } }
205export type StepMeta = { threadId: string; model?: string; resumed: boolean; bridgePid: number; codexPid: number }
206type CodexUsage = { inputTokens: number; cachedInputTokens: number; cacheWriteInputTokens?: number; outputTokens: number; reasoningOutputTokens: number; totalTokens: number }
207type StepResult = StepMeta & { usage?: CodexUsage | null } & ({ toolCall: { callId: string; tool: string; arguments: unknown } } | { final: { text: string; status?: string; errors: string[] } })
208type StepEvent = StepResult | (StepMeta & { error: string })
209export type StepReply = { pending: true } | StepEvent | { error: string }
210
211const claudeUsage = (usage: CodexUsage | null | undefined, model: string): TurnUsage | null => usage ? {
212  input_tokens: Math.max(0, usage.inputTokens - usage.cachedInputTokens - (usage.cacheWriteInputTokens ?? 0)),
213  output_tokens: usage.outputTokens,
214  cache_read_input_tokens: usage.cachedInputTokens,
215  cache_creation_input_tokens: usage.cacheWriteInputTokens ?? 0,
216  model,
217} : null
218
219type ApiBlock = { type: string; id?: string; name?: string; text?: string; input?: { message?: unknown }; tool_use_id?: string; content?: unknown; is_error?: boolean; toolDenialKind?: string }
220
221// $.http.fetch's text for a socket nothing listens on (missing, or left by a
222// dead bridge). Its 30 s "aborted: no complete answer" is not one: that bridge
223// is alive, and a second one would run the same prompt again.
224export const unreachable = (err: unknown) => /\bfailed: .*(FailedToOpenSocket|ConnectionRefused|ECONNREFUSED|ENOENT)/.test(String(err))
225
226export function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
227  let interrupt = () => {}
228  const aborted = new Promise<never>((_, reject) => {
229    interrupt = () => reject(new Error('interrupted'))
230    if (signal.aborted) interrupt()
231    else signal.addEventListener('abort', interrupt, { once: true })
232  })
233  return Promise.race([work, aborted]).finally(() => signal.removeEventListener('abort', interrupt))
234}
235
236export const interrupted = (err: unknown) => err instanceof Error && err.message === 'interrupted'
237
238// The harness aborts a subagent whose stream yields nothing for 600 s, and
239// codex can think longer than that without a tool call. Every chunk the turn
240// streams counts as progress; an empty thinking chunk is the one the
241// transcript does not keep, so the answer stays clean. Pass $.clock.after,
242// not $.clock.sleep: a sleep is charged to the dispatch's own time budget.
243export const KEEPALIVE_MS = 30_000
244
245export async function* keepalive<T>(work: Promise<T>, signal: AbortSignal, onBeat: () => void, after: TimerCall, intervalMs = KEEPALIVE_MS): AsyncGenerator<TurnStepChunk, T> {
246  const settled = work.then(value => ({ value }), (error: unknown) => ({ error }))
247  for (;;) {
248    let timer: Timer | undefined
249    const beat = new Promise<'beat'>(resolve => { timer = after(intervalMs, () => resolve('beat')) })
250    const r = await abortable(Promise.race([settled, beat]), signal).finally(() => timer?.cancel())
251    if (r === 'beat') {
252      onBeat()
253      yield { kind: 'thinking', index: 0, text: '' }
254      continue
255    }
256    if ('error' in r) throw r.error
257    return r.value
258  }
259}
260
261export const MAX_WAIT_RETRIES = 3
262
263export async function settlePending(
264  reply: StepReply,
265  wait: () => Promise<StepReply>,
266  onRetry: (err: unknown) => void,
267  health: () => Promise<unknown> = async () => {},
268): Promise<StepResult> {
269  let current = reply
270  let retries = 0
271  while ('pending' in current) {
272    try {
273      current = await wait()
274    } catch (err) {
275      if (!/aborted: no complete answer/.test(String(err))) throw err
276      if (retries >= MAX_WAIT_RETRIES) throw new Error(`bridge /wait gave up after ${MAX_WAIT_RETRIES} retries; last error: ${String(err)}`)
277      onRetry(err)
278      try {
279        await health()
280      } catch (healthErr) {
281        throw new Error(`bridge /wait health check failed after ${retries + 1} retries: ${String(healthErr)}; last /wait error: ${String(err)}`)
282      }
283      retries++
284    }
285  }
286  if ('error' in current) throw new Error(`bridge: ${current.error}`)
287  return current
288}
289
290type BridgeChunk = { stream: string; text: string; exitCode?: unknown; signal?: unknown }
291const BRIDGE_STARTUP_TIMEOUT_MS = 15_000
292// How long an unregistered codex step waits for in-flight spawns to register it.
293const SPAWN_WAIT_MS = 5_000
294// A hook's own time per dispatch is 10 s (HookBudget.ms), and an await on
295// anything but a `$` call or `next` spends it. Such a wait stops this far short
296// of the budget, so the step ends itself before the engine deems the hook absent.
297const BUDGET_RESERVE_MS = 2_000
298
299function processStatus(err: unknown): string {
300  if (!err || typeof err !== 'object') return 'exit code=unknown'
301  const e = err as { exitCode?: unknown; code?: unknown; signal?: unknown }
302  const code = e.exitCode ?? e.code
303  return `${code === undefined ? 'exit code=unknown' : `exit code=${String(code)}`}${e.signal ? ` signal=${String(e.signal)}` : ''}`
304}
305
306// `after` is $.clock.after: the hook environment declares no setTimeout.
307export function bridgeReady(events: AsyncIterable<BridgeChunk>, after: TimerCall, timeoutMs = BRIDGE_STARTUP_TIMEOUT_MS): Promise<void> {
308  let resolve!: () => void
309  let reject!: (error: Error) => void
310  const promise = new Promise<void>((res, rej) => { resolve = res; reject = rej })
311  let stderrTail = ''
312  let status = 'exit code=unknown'
313  let settled = false
314  let timer: Timer | undefined
315  const finish = (error?: Error) => {
316    if (settled) return
317    settled = true
318    timer?.cancel()
319    if (error) reject(error)
320    else resolve()
321  }
322  timer = after(timeoutMs, () => finish(new Error(`codex bridge startup timed out after ${timeoutMs}ms; exit code=unknown; stderr tail: ${stderrTail || '(empty)'}`)))
323  void (async () => {
324    try {
325      for await (const { stream, text } of events) {
326        if (stream === 'stderr') stderrTail = (stderrTail + text).slice(-2000)
327        if (stream === 'exit') status = `${text || 'exit'}${status === 'exit code=unknown' ? '' : `; ${status}`}`
328        if (stream === 'stdout' && text.includes('"ready":true')) finish()
329      }
330      finish(new Error(`codex bridge exited before ready; ${status}; stderr tail: ${stderrTail || '(empty)'}`))
331    } catch (err) {
332      finish(new Error(`codex bridge failed before ready; ${processStatus(err)}; ${String(err)}; stderr tail: ${stderrTail || '(empty)'}`))
333    }
334  })()
335  return promise
336}
337
338// cyrb53: the fingerprint only has to tell one bridge source from another.
339export function contentHash(text: string): string {
340  let h1 = 0xdeadbeef, h2 = 0x41c6ce57
341  for (let i = 0; i < text.length; i++) {
342    const c = text.charCodeAt(i)
343    h1 = Math.imul(h1 ^ c, 2654435761)
344    h2 = Math.imul(h2 ^ c, 1597334677)
345  }
346  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
347  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
348  return (h2 >>> 0).toString(16).padStart(8, '0') + (h1 >>> 0).toString(16).padStart(8, '0')
349}
350
351// The bridge's source as this module sees it on disk. A bridge outlives a
352// module reload, so a bridge whose /health reports another fingerprint runs
353// code this module was not written against. The fingerprint covers every file
354// the bridge loads at startup: codex-bridge.mjs and codex-config.mjs.
355export const bridgeSource = ($: EngineInterface) => `${$.plugin.root}/daemon/codex-bridge.mjs`
356export const bridgeConfigSource = ($: EngineInterface) => `${$.plugin.root}/daemon/codex-config.mjs`
357export const UNREAD_FINGERPRINT = 'unread'
358export async function bridgeFingerprint($: EngineInterface): Promise<string> {
359  try {
360    return contentHash((await Promise.all([bridgeSource($), bridgeConfigSource($)].map(p => $.fs.read(p)))).join('\0'))
361  } catch (err) {
362    // An unreadable source must not keep the bridge from starting; it only skips the staleness check.
363    $.ui.log(`[codex-subagent] cannot fingerprint ${bridgeSource($)}: ${String(err)}`, { to: 'debug' })
364    return UNREAD_FINGERPRINT
365  }
366}
367
368// A bridge for the session's life; resolves once it listens. A step calls this
369// again when nothing listens on the socket (the bridge or codex died), or when
370// the bridge runs stale code; the new bridge takes over the socket (the old one
371// exits once its socket is replaced) and resumes threads from the threadId the step sends.
372function startBridge($: EngineInterface, sock: string, onFail: (ready: Promise<void>) => void): Promise<void> {
373  let stop: (() => void) | undefined
374  async function* output() {
375    const bridge = await $.process.spawn({ argv: ['node', bridgeSource($), sock, await bridgeFingerprint($), String(MODEL_AUTO_COMPACT_TOKEN_LIMIT)] })
376    stop = () => {
377      try { (bridge as unknown as { kill?: (signal?: string) => void }).kill?.('SIGTERM') } catch (err) { $.ui.log(`[codex-bridge] failed to stop after startup failure: ${String(err)}`, { to: 'debug' }) }
378    }
379    for await (const chunk of bridge) {
380      const { stream, text } = chunk
381      // $.ui.log drops any text over 4096 characters, so long bridge lines go in pieces.
382      for (const line of text.trimEnd().split('\n'))
383        for (let i = 0; i < line.length; i += 3900) $.ui.log(`[codex-bridge ${stream}] ${line.slice(i, i + 3900)}`, { to: 'debug' })
384      yield chunk
385    }
386    const status = bridge as unknown as { exitCode?: unknown; code?: unknown; signal?: unknown }
387    yield { stream: 'exit', text: processStatus(status), exitCode: status.exitCode ?? status.code, signal: status.signal }
388    $.ui.log('[codex-bridge] exited', { to: 'debug' })
389  }
390  const ready = bridgeReady(output(), (ms, fn) => $.clock.after(ms, fn))
391  void ready.catch(() => { stop?.(); onFail(ready) })
392  return ready
393}
394
395async function socketPath($: EngineInterface): Promise<string> {
396  const home = (await $.env.get('HOME')) ?? '/tmp'
397  return `${home}/.claude-work/run/codex-subagent-${await $.session.id()}.sock`
398}
399
400// What one load of this module keeps: a hot reload starts it over.
401type ModState = {
402  hookLog?: { path: string; text: string }
403  logChain: Promise<void>
404  registration?: Promise<void>
405  registrationLogged: boolean
406  // Each agent's definition (`codex-subagent:luna`, `general-purpose`, ...), by id.
407  subagentTypes: Map<string, string>
408}
409
410// The hook-side log beside the bridge's: `$.fs.write` replaces a whole file,
411// so the module keeps the text and writes it back, cut to its newest half
412// once it passes LOG_MAX.
413const LOG_MAX = 1 << 20
414function diag(st: ModState, $: EngineInterface, line: string): void {
415  try { $.ui.log(`[codex-subagent] ${line}`, { to: 'debug' }) } catch {}
416  st.logChain = st.logChain.then(async () => {
417    if (!st.hookLog) {
418      const path = (await socketPath($)).replace(/\.sock$/, '.hook.log')
419      st.hookLog = { path, text: await $.fs.read(path).catch(() => '') }
420    }
421    st.hookLog.text += `${new Date().toISOString()} ${line}\n`
422    if (st.hookLog.text.length > LOG_MAX) st.hookLog.text = st.hookLog.text.slice(-(LOG_MAX >> 1))
423    await $.fs.write(st.hookLog.path, st.hookLog.text)
424  }).catch(() => {})
425}
426
427// A hot reload runs register() again but not session.start, so the first
428// hook of a fresh module registers the types once more; a re-registered name
429// is replaced, so a TYPES model change reaches the running session.
430function ensureRegistered(st: ModState, $: EngineInterface): Promise<void> {
431  return st.registration ??= (async () => {
432    if ((await $.env.get('CODEX_SUBAGENT_HARVEST')) === '1') return
433    for (const [name, t] of Object.entries(TYPES)) {
434      await $.agent.register({
435        name,
436        description: `Runs the task on OpenAI ${t.model} at ${t.effort} effort in the ${t.sandbox} sandbox through Codex (codex's own shell and edit tools, plus this session's read-only MCP tools and skills relayed; ${t.blurb}). SendMessage continues the same codex thread.`,
437        prompt: 'This agent is served by Codex; this prompt is never sent to a Claude model.',
438        model: t.model, // turn steps go to codex; engine compaction also sees this id, intercepted below
439      })
440    }
441  })().catch(err => {
442    st.registration = undefined
443    if (!st.registrationLogged) { st.registrationLogged = true; diag(st, $, `agent type registration failed (retried on the next hook): ${String(err)}`) }
444  })
445}
446
447async function subagentTypeOf(st: ModState, $: EngineInterface, agents: ReadonlyMap<string, Agent>, agentId: string | undefined): Promise<string | undefined> {
448  if (!agentId) return undefined
449  const known = agents.get(agentId)
450  if (known) return `${PREFIX}${known.type}`
451  if (!st.subagentTypes.has(agentId)) {
452    try {
453      for (const a of await $.agent.list()) st.subagentTypes.set(a.id, a.type)
454    } catch (err) {
455      diag(st, $, `agent list failed while classifying ${agentId}: ${String(err)}`)
456    }
457  }
458  return st.subagentTypes.get(agentId)
459}
460
461const writableFix = 'add a line `writable: /abs/repo, /abs/other-worktree` to the brief naming every directory the worker must write'
462async function writableRootsFromPrompt($: EngineInterface, prompt: string, cwd: string, required: boolean): Promise<{ writableRoots?: string[]; error?: string }> {
463  const writableLine = /^writable:[ \t]*(.+)$/m.exec(prompt)?.[1]
464  if (writableLine === undefined)
465    return required ? { error: `Codex subagent spawn denied: prompt is missing the required writable: line; ${writableFix}.` } : {}
466  const writableRoots = writableLine.split(',').map(root => root.trim())
467  const nonAbsolute = writableRoots.filter(root => !root.startsWith('/'))
468  if (nonAbsolute.length)
469    return { error: `Codex subagent spawn denied: writable paths must be absolute; offending path(s): ${nonAbsolute.map(root => `\`${root || '<empty>'}\``).join(', ')}; ${writableFix}.` }
470  const nonDirectories = (await Promise.all(writableRoots.map(async root => {
471    try {
472      const result = await $.process.run(['test', '-d', root], { cwd })
473      return result.exitCode === 0 ? undefined : root
474    } catch {
475      return root
476    }
477  }))).filter((root): root is string => root !== undefined)
478  if (nonDirectories.length)
479    return { error: `Codex subagent spawn denied: writable path(s) must be existing directories; offending path(s): ${nonDirectories.map(root => `\`${root}\``).join(', ')}; ${writableFix}.` }
480  return { writableRoots }
481}
482
483export const register: Register = (on) => {
484  const st: ModState = { logChain: Promise.resolve(), registrationLogged: false, subagentTypes: new Map() }
485  const agents = new Map<string, Agent>()
486  // Messages delivered to a codex agent and not yet handed to codex, by agent id.
487  const inbox = new Map<string, string[]>()
488  // Codex spawns whose next(e) has not resolved yet.
489  const spawning = new Set<Promise<void>>()
490  // The first block index each codex step has not yielded yet: the turn.step
491  // .catch handler writes its error there, past the chunks the failed hook left.
492  const freeBlock = new Map<string, number>()
493  const stepKey = (e: { agentId?: string; turnId: string; index: number }) => `${e.agentId ?? ''}|${e.turnId}|${e.index}`
494  // Agents a step has claimed for codex: the .catch handler reads it without awaiting.
495  const claimed = new Set<string>()
496
497  on('session.receive', async ($, e, next) => {
498    const r = await next(e)
499    const text = r.text?.trim()
500    if (e.agentId && text && agents.has(e.agentId)) inbox.set(e.agentId, [...(inbox.get(e.agentId) ?? []), text])
501    return r
502  })
503
504  on('session.compact', async ($, e, next) => {
505    const subagentType = await subagentTypeOf(st, $, agents, e.agentId)
506    if (!subagentType?.startsWith(PREFIX)) return next(e)
507    if (!Array.isArray(e.messages)) return { skip: 'codex agent compaction needs messages' }
508    const messages = e.messages
509    const lastAssistant = messages.findLastIndex(message => message.role === 'assistant')
510    return { messages: messages.slice(Math.max(0, lastAssistant)) }
511  })
512
513  let sock = ''
514  let bridgeReady: Promise<void> | undefined
515  const dropFailedBridge = (failed: Promise<void>) => { if (bridgeReady === failed) bridgeReady = undefined }
516  // The bridgeReady whose /health matched this module's bridge source.
517  let verifiedBridge: Promise<void> | undefined
518
519  on('session.start', async ($, e, next) => {
520    const started = await next(e)
521    // The bridge's schema-harvest child is a `claude -p` that never reaches the
522    // API; were this plugin installed there, it would start a bridge of its own.
523    if ((await $.env.get('CODEX_SUBAGENT_HARVEST')) === '1') return started
524    sock = await socketPath($)
525    await ensureRegistered(st, $)
526    bridgeReady = startBridge($, sock, dropFailedBridge)
527    return started
528  })
529
530  on('agent.spawn', async ($, e, next) => {
531    void ensureRegistered(st, $)
532    const type = typeOf(e.subagentType)
533    if (!type) return next(e)
534    // The first step can race both writable-root checks and next(e), so track the whole spawn.
535    let done!: () => void
536    const spawned = new Promise<void>(resolve => { done = resolve })
537    spawning.add(spawned)
538    let r: Awaited<ReturnType<typeof next>>
539    let cwd: string
540    let writableRoots: string[] = []
541    try {
542      const spawnCwd = e.cwd ?? await $.session.cwd()
543      const parsed = await writableRootsFromPrompt($, e.prompt, spawnCwd, true)
544      if (parsed.error) return { deny: parsed.error }
545      writableRoots = parsed.writableRoots!
546      cwd = writableRoots[0]
547      r = await next(e)
548      if (r.agentId) { agents.set(r.agentId, { type, cwd, writableRoots }); st.subagentTypes.set(r.agentId, e.subagentType) }
549    } finally {
550      spawning.delete(spawned)
551      done()
552    }
553    if (r.agentId) {
554      try {
555        sock ||= await socketPath($)
556        bridgeReady ??= startBridge($, sock, dropFailedBridge)
557        const ready = bridgeReady
558        await abortable(ready, next.signal)
559        const res = await $.http.fetch('http://codex-bridge/remember', {
560          method: 'POST', socketPath: sock, headers: { 'content-type': 'application/json' },
561          body: JSON.stringify({ key: r.agentId, type, cwd, writableRoots }),
562        })
563        if (!res.ok) throw new Error(`bridge POST /remember ${res.status}: ${res.text.slice(0, 2000)}`)
564      } catch (err) {
565        diag(st, $, `could not persist ${r.agentId}: ${err instanceof Error ? err.message : String(err)}`)
566      }
567    }
568    return r
569  })
570
571  on('turn.step', async function* ($, e, next) {
572    const agentId = e.agentId
573    const key = stepKey(e)
574    freeBlock.delete(key)
575    for (const k of freeBlock.keys()) { if (freeBlock.size < 64) break; freeBlock.delete(k) }
576    const used = (index: number) => { freeBlock.set(key, Math.max(freeBlock.get(key) ?? 0, index + 1)) }
577    const finish = (text: string, index = 0) => { used(index); return endTurn(e, text, index) }
578    // `work` is no `$` call, so waiting on it is charged to this hook's budget:
579    // once what the budget spares has passed, `onExpiry` settles it instead.
580    const withinBudget = <T>(work: Promise<T>, capMs: number, onExpiry: () => T): Promise<T> => {
581      let timer: Timer | undefined
582      const expired = new Promise<T>((resolve, reject) => {
583        timer = $.clock.after(Math.max(0, Math.min(capMs, next.budget.remainingMs - BUDGET_RESERVE_MS)), () => {
584          try { resolve(onExpiry()) } catch (err) { reject(err) }
585        })
586      })
587      return Promise.race([work, expired]).finally(() => timer?.cancel())
588    }
589    const bridgeUp = (ready: Promise<void>) => withinBudget(abortable(ready, next.signal), Infinity, () => {
590      throw new Error(`the codex bridge is still starting after this step's time budget (${next.budget.ms} ms)`)
591    })
592    const post = (route: string, payload: unknown) =>
593      $.http.fetch(`http://codex-bridge${route}`, { method: 'POST', socketPath: sock, headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) })
594    void ensureRegistered(st, $)
595    let agent = agentId ? agents.get(agentId) : undefined
596    if (!agent && agentId && spawning.size) {
597      // This may be the first step of a codex spawn still inside next(e); a
598      // spawn that never resolves must not hold the step, so the wait is bounded.
599      await withinBudget(Promise.all(spawning).then(() => {}), SPAWN_WAIT_MS, () => {})
600      agent = agents.get(agentId)
601    }
602    const subagentType = await subagentTypeOf(st, $, agents, agentId)
603    const claim: Claim = agent ? { ours: true, type: agent.type } : codexClaim(e.model, subagentType)
604    if (claim.ours && agentId) claimed.add(agentId)
605    const cause = `model=${e.model} type=${subagentType ?? '(unknown)'}`
606    let rebuilt = false
607    if (!agent && agentId) {
608      let found = false
609      try {
610        sock ||= await socketPath($)
611        bridgeReady ??= startBridge($, sock, dropFailedBridge)
612        const ready = bridgeReady
613        await bridgeUp(ready)
614        const res = await abortable(post('/recover', { key: agentId }), next.signal)
615        if (!res.ok) throw new Error(`bridge POST /recover ${res.status}: ${res.text.slice(0, 2000)}`)
616        const recovered = JSON.parse(res.text) as { found?: boolean; type?: TypeName; cwd?: string; writableRoots?: string[]; threadId?: string }
617        found = recovered.found === true
618        if (found && recovered.type && recovered.cwd) {
619          const writableRoots = recovered.writableRoots?.length ? recovered.writableRoots : [recovered.cwd]
620          agent = { type: recovered.type, cwd: writableRoots[0], writableRoots, threadId: recovered.threadId }
621        }
622      } catch (err) {
623        diag(st, $, `recovery lookup failed for ${agentId} (${cause}): ${String(err)}`)
624        if (claim.ours) return yield* finish(`[codex-subagent error] cannot reach the bridge to recover ${agentId}: ${err instanceof Error ? err.message : String(err)}; send the message again`)
625      }
626      // Neither this module nor the bridge has seen the spawn: the agent's
627      // type (or its model) names the codex type, and the session's repo root
628      // is the cwd the spawn would pick.
629      if (!agent && !found && claim.ours) {
630        if (!claim.type) {
631          diag(st, $, `${agentId} is a codex step no type serves (${cause})`)
632          return yield* finish(`[codex-subagent error] cannot serve ${agentId} on codex: neither its agent type nor its model names a codex-subagent type (${cause}); this step was not sent to Claude`)
633        }
634        try {
635          const cwd = await workspaceRoot((argv, init) => $.process.run(argv, init), await $.session.cwd())
636          agent = { type: claim.type, cwd, writableRoots: [cwd] }
637          rebuilt = true
638          diag(st, $, `${agentId} unknown to spawn and bridge; serving it as ${claim.type} in ${agent.cwd} (${cause})`)
639        } catch (err) {
640          return yield* finish(`[codex-subagent error] cannot recover ${agentId ??'(unknown agent)'}: ${err instanceof Error ? err.message : String(err)}`)
641        }
642      }
643      if (agent && agentId) agents.set(agentId, agent)
644    }
645    if (!agent || !agentId) {
646      if (claim.ours) {
647        diag(st, $, `ending an unservable codex step for ${agentId ?? '(no agent id)'} (${cause})`)
648        return yield* finish(agentId ? `[codex-subagent error] cannot recover ${agentId} (${cause})` : `[codex-subagent error] ${e.model} step carries no agent id`)
649      }
650      return yield* next(e)
651    }
652    if (next.signal.aborted) return yield* finish('[codex-subagent error] interrupted')
653    const onAbort = () => { void post('/interrupt', { key: agentId }).catch(err => diag(st, $, `interrupt failed: ${String(err)}`)) }
654    next.signal.addEventListener('abort', onAbort)
655    // Block 0 holds the keepalive's thinking once it beats; the answer then streams in block 1.
656    let block = 0
657    const ask = async (route: string, payload: unknown) => {
658      const res = await abortable(post(route, payload), next.signal)
659      if (!res.ok) throw new Error(`bridge POST ${route} ${res.status}: ${res.text.slice(0, 2000)}`)
660      const r = JSON.parse(res.text) as StepReply
661      if ('error' in r) throw new Error(`bridge: ${r.error}`)
662      return r
663    }
664
665    // The bridge routes /health for GET only; every other route is a POST.
666    const getHealth = () => abortable($.http.fetch('http://codex-bridge/health', { method: 'GET', socketPath: sock }), next.signal)
667
668    const settle = (reply: StepReply): Promise<StepResult> => settlePending(
669      reply,
670      () => ask('/wait', { key: agentId }),
671      err => diag(st, $, `/wait failed (${String(err)}); retrying`),
672      async () => {
673        const res = await getHealth()
674        if (!res.ok) throw new Error(`bridge GET /health ${res.status}: ${res.text.slice(0, 2000)}`)
675      }
676    )
677    // True once the listening bridge runs this module's bridge source. A stale
678    // bridge is replaced only while no other agent has a turn in it and this
679    // step holds none of its tool calls; otherwise the next step checks again.
680    const bridgeCurrent = async (body: Record<string, unknown>): Promise<boolean> => {
681      const ready = bridgeReady
682      if (!ready || verifiedBridge === ready) return true
683      const want = await bridgeFingerprint($)
684      if (want === UNREAD_FINGERPRINT) return true
685      const res = await getHealth()
686      if (!res.ok) {
687        diag(st, $, `bridge GET /health ${res.status}: ${res.text.slice(0, 2000)}; cannot check its code, stepping through it`)
688        return true
689      }
690      const health = JSON.parse(res.text) as { fingerprint?: string; busy?: string[]; threads?: [string, string | null][] }
691      if (health.fingerprint === want) { verifiedBridge = ready; return true }
692      // A bridge from before /health reported `busy` still lists its threads;
693      // any of those agents the engine shows running may be mid-turn in it.
694      const known = new Set((health.threads ?? []).map(([key]) => key))
695      const others = Array.isArray(health.busy)
696        ? health.busy.filter(key => key !== agentId)
697        : (await $.agent.list()).filter(a => a.id !== agentId && a.status === 'running' && known.has(a.id)).map(a => a.id)
698      const holdsCall = body.toolResult !== undefined
699      if (others.length || holdsCall) {
700        diag(st, $, `bridge runs stale code (fingerprint ${health.fingerprint ?? '(none)'}, want ${want}); restart deferred: ${holdsCall ? `${agentId} answers a held tool call` : `turns running for ${others.join(', ')}`}`)
701        return false
702      }
703      diag(st, $, `bridge runs stale code (fingerprint ${health.fingerprint ?? '(none)'}, want ${want}); replacing it`)
704      const fresh = bridgeReady = startBridge($, sock, dropFailedBridge)
705      await bridgeUp(fresh)
706      verifiedBridge = fresh
707      return true
708    }
709    const step = async (body: Record<string, unknown>): Promise<StepResult> => {
710      let submitted = false
711      const roundTrip = async () => {
712        const ready = bridgeReady ?? (bridgeReady = startBridge($, sock, dropFailedBridge))
713        await bridgeUp(ready)
714        if (!(await bridgeCurrent(body)) && body.toolResult && body.prompt !== undefined) {
715          // A stale bridge may ignore `prompt` beside `toolResult`; the message
716          // rides in the tool's output instead, the one place it reaches codex.
717          const result = body.toolResult as { contentItems: ContentItem[] }
718          body.toolResult = { ...result, contentItems: [...result.contentItems, { type: 'inputText', text: body.prompt as string }] }
719          delete body.prompt
720        }
721        const reply = await ask('/step', body)
722        submitted = true
723        return settle(reply)
724      }
725      try {
726        return await roundTrip()
727      } catch (err) {
728        if (!unreachable(err) || submitted) throw err
729        diag(st, $, `bridge unreachable (${String(err)}); restarting it`)
730        const fresh = bridgeReady = startBridge($, sock, dropFailedBridge)
731        await bridgeUp(fresh)
732        return roundTrip()
733      }
734    }
735
736    // A failure from here on reaches the .catch handler below, which ends the
737    // turn as text: a failed hook would otherwise fall through to a Claude request.
738    try {
739      const api = await $.session.messages({ agentId, as: 'api' })
740      if (!Array.isArray(api)) throw new Error(`cannot read agent ${agentId}'s messages: ${api.deny}`)
741      const rows = await $.session.messages({ agentId })
742      const prompt = Array.isArray(rows) ? pendingPrompt(rows) : undefined
743      if (!agent.handback) {
744        const last = api[api.length - 1]
745        const handback = last?.role === 'assistant' ? (last.content as ApiBlock[]).find(b => b.type === 'tool_use' && b.name === HANDBACK && b.id && typeof b.input?.message === 'string') : undefined
746        if (handback?.id) agent.handback = { toolUseId: handback.id, text: handback.input!.message as string }
747      }
748      // A delivered SubagentHandback ends the run with no step after it, so the
749      // handback outlives it here; a user message after it is a SendMessage
750      // resume, which must start a codex turn rather than replay the old ending.
751      if (agent.handback && prompt !== undefined) agent.handback = undefined
752      if (agent.handback) {
753        // A refused or failed handback ends as plain text, which the harness then delivers.
754        const { toolUseId, text } = agent.handback
755        agent.handback = undefined
756        return yield* finish(toolResultFor(api, toolUseId)?.success ? `(report delivered through ${HANDBACK})` : text)
757      }
758      agent.relay ??= relaySet(await $.tool.list())
759      if (!agent.waiting) {
760        const last = api[api.length - 1]
761        const call = last?.role === 'assistant' ? (last.content as ApiBlock[]).find(b => b.type === 'tool_use' && b.id?.startsWith('toolu_codex_') && !b.id.startsWith('toolu_codex_handback_')) : undefined
762        if (call?.id) agent.waiting = { toolUseId: call.id, callId: call.id.slice('toolu_codex_'.length) }
763      }
764      const type = TYPES[agent.type]
765      const body: Record<string, unknown> = { key: agentId, agentType: agent.type, threadId: agent.threadId, cwd: agent.cwd, writableRoots: agent.writableRoots, model: type.model, effort: type.effort, sandbox: type.sandbox, mcpTools: agent.relay.mcp }
766      const delivered = inbox.get(agentId) ?? []
767      const answered = agent.waiting && toolResultFor(api, agent.waiting.toolUseId, delivered)
768      if (agent.waiting && answered) {
769        const { messages, ...result } = answered
770        body.toolResult = { callId: agent.waiting.callId, ...result }
771        // The bridge answers the call first, then steers this text into the running turn.
772        if (messages) {
773          body.prompt = messages.join('\n\n')
774          const left = delivered.filter(d => !messages.some(m => m.includes(d)))
775          if (left.length) inbox.set(agentId, left)
776          else inbox.delete(agentId)
777        }
778      } else {
779        inbox.delete(agentId)
780        if (!prompt) throw new Error(`agent ${agentId} has neither a pending prompt nor the tool_result for ${agent.waiting?.toolUseId ?? '(none)'}`)
781        if (!agent.threadId) {
782          body.dynamicTools = agent.relay.tools
783          body.developerInstructions = `${PREAMBLE}\n\n${inheritedContext(api)}`
784        }
785        body.prompt = prompt
786      }
787      if (typeof body.prompt === 'string') {
788        const parsed = await writableRootsFromPrompt($, body.prompt, agent.cwd, false)
789        if (parsed.error) throw new Error(parsed.error)
790        if (parsed.writableRoots) { agent.writableRoots = parsed.writableRoots; body.writableRoots = parsed.writableRoots }
791      }
792      agent.waiting = undefined
793      sock ||= await socketPath($)
794      bridgeReady ??= startBridge($, sock, dropFailedBridge)
795      let reply = yield* keepalive(step(body), next.signal, () => { block = 1; used(0) }, (ms, fn) => $.clock.after(ms, fn))
796      agent.threadId = reply.threadId
797      let usage = claudeUsage(reply.usage, reply.model ?? type.model)
798
799      for (;;) {
800        if (!('toolCall' in reply)) break
801        const { callId, tool, arguments: input } = reply.toolCall
802        const name = agent.relay?.claudeName.get(tool)
803        if (!name) {
804          const failed: Record<string, unknown> = { key: agentId, agentType: agent.type, threadId: agent.threadId, cwd: agent.cwd, writableRoots: agent.writableRoots, model: type.model, effort: type.effort, sandbox: type.sandbox, toolResult: { callId, contentItems: [{ type: 'inputText', text: `tool not relayed: ${tool}` }], success: false } }
805          reply = yield* keepalive(step(failed), next.signal, () => { block = 1; used(0) }, (ms, fn) => $.clock.after(ms, fn))
806          agent.threadId = reply.threadId
807          usage = claudeUsage(reply.usage, reply.model ?? type.model) ?? usage
808          continue
809        }
810        const toolUseId = `toolu_codex_${callId.replace(/[^A-Za-z0-9_-]/g, '_')}`
811        agent.waiting = { toolUseId, callId }
812        used(block)
813        const chunks: TurnStepChunk[] = [
814          { kind: 'tool', index: block, id: toolUseId, name },
815          { kind: 'input', index: block, json: JSON.stringify(input ?? {}) },
816          { kind: 'stop', stopReason: 'tool_use', usage },
817        ]
818        for (const c of chunks) yield c
819        return { turnId: e.turnId, index: e.index, answer: '', toolUses: [{ name, input }], stopReason: 'tool_use', usage } satisfies TurnStepResult
820      }
821
822      const f = 'final' in reply ? reply.final : { text: '', status: undefined, errors: ['bridge reply had neither toolCall nor final'] }
823      const errors = f.errors.length ? `\n\n[codex errors] ${f.errors.join('\n')}` : ''
824      const notice = rebuilt && api.some(m => m.role === 'assistant') ? '[codex-subagent: the earlier codex thread was not recoverable; this answer comes from a fresh thread]\n\n' : ''
825      const text = `${notice}${f.text}${errors}\n\n[codex-subagent: model=${reply.model ?? '?'} thread=${reply.threadId}${reply.resumed ? ' (resumed)' : ''} codexPid=${reply.codexPid} bridgePid=${reply.bridgePid} status=${f.status}]`
826      const toolUseId = `toolu_codex_handback_${reply.threadId.replace(/[^A-Za-z0-9_-]/g, '_')}_${e.turnId.replace(/[^A-Za-z0-9_-]/g, '_')}_${e.index}`
827      agent.handback = { toolUseId, text }
828      const input = { message: text }
829      used(block)
830      yield { kind: 'tool', index: block, id: toolUseId, name: HANDBACK }
831      yield { kind: 'input', index: block, json: JSON.stringify(input) }
832      yield { kind: 'stop', stopReason: 'tool_use', usage }
833      return { turnId: e.turnId, index: e.index, answer: '', toolUses: [{ name: HANDBACK, input }], stopReason: 'tool_use', usage } satisfies TurnStepResult
834    } finally {
835      next.signal.removeEventListener('abort', onAbort)
836    }
837  }).catch(async function* ($, e, next) {
838    // A codex step must never reach `next`: beneath it is the Claude request.
839    // The hook classifies the step before anything in it can fail, so this
840    // reads that verdict without awaiting; only a step that failed before then
841    // asks $.agent.list, bounded well inside the 1 s grace.
842    const agentId = e.agentId
843    const known = agentId !== undefined && (claimed.has(agentId) || agents.has(agentId))
844    let ours = known || codexClaim(e.model, agentId ? st.subagentTypes.get(agentId) : undefined).ours
845    if (!ours && agentId && !st.subagentTypes.has(agentId)) {
846      let timer: Timer | undefined
847      const listed = await Promise.race([
848        $.agent.list().catch(() => [] as { id: string; type: string }[]),
849        new Promise<{ id: string; type: string }[]>(resolve => { timer = $.clock.after(300, () => resolve([])) }),
850      ]).finally(() => timer?.cancel())
851      ours = codexClaim(e.model, listed.find(a => a.id === agentId)?.type).ours
852    }
853    if (!ours) return yield* next(e)
854    const key = stepKey(e)
855    const index = freeBlock.get(key) ?? 0
856    freeBlock.delete(key)
857    const { kind, message } = next.error
858    try { diag(st, $, `turn.step ${kind} for ${e.agentId ?? '(no agent id)'}: ${message ?? '(no message)'}`) } catch {}
859    return yield* endTurn(e, `[codex-subagent error] step hook ${kind}: ${message ?? '(no message)'}; send the message again`, index)
860  })
861}
862
863async function* endTurn(e: { turnId: string; index: number }, text: string, block = 0): AsyncGenerator<TurnStepChunk, TurnStepResult> {
864  yield { kind: 'text', index: block, text }
865  yield { kind: 'stop', stopReason: 'end_turn', usage: null }
866  return { turnId: e.turnId, index: e.index, answer: text, toolUses: [], stopReason: 'end_turn', usage: null }
867}
868