Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(agents): no NEEDS YOU for a codex PermissionRequest under its auto-reviewer (#1228)

eneskircaf2dee12595af
diff --git a/CLAUDE.md b/CLAUDE.md
index 6de7f877d..77f39282f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2468,6 +2468,22 @@ else, and its context links must keep classifying across restarts).
hook server's try/catch before), never the node's delivery chain. A remote (SSH) grok node's file is on its host, so it reads "cannot
tell" and behaves exactly as before — a remote leg is a follow-up. Unmeasured: `events.jsonl`'s
shape on other grok versions (a changed shape degrades to today's behaviour).
+- **Codex NEEDS YOU is checked against the session rollout under its auto-reviewer**
+ (`core/agents/codex-permission-gate.ts`, issue #1171, in the hook server, so both shells get it).
+ With `approvals_reviewer = "auto_review"` codex fires `PermissionRequest`, then its own reviewer
+ subagent approves or refuses with nobody asked; no hook fires until the approved command's
+ `PostToolUse`, so the node read NEEDS YOU for the review plus the whole command. MEASURED
+ (2026-10-16, private CODEX_HOME + fake Responses model, codex 0.156.1 `exec` and 0.163.0 TUI;
+ fixture `shared/agents/__fixtures__/codex/auto-review-permission.json`): the hook payload has NO
+ reviewer field; the rollout's per-turn `turn_context` carries `approvals_reviewer` and a `turn_id`
+ equal to the hook's, already on disk when the hook runs; `guardian_subagent` is recorded as
+ `auto_review`; a failed review rejects to the agent, never to a person. Rules: a closed match (the
+ `turn_context` for THIS `turn_id`, value in `CODEX_AUTO_REVIEWERS`) suppresses the event, so the
+ node keeps PreToolUse's `working`; everything else — no `turn_id`, unknown value, a path outside
+ the codex sessions roots (system `$CODEX_HOME/sessions`, managed `~/.nodeterm/cx/<16hex>/sessions`),
+ unreadable file (O_NOFOLLOW), no match within the 16 MB backward scan, a read over 500 ms — is
+ published unchanged as `waiting`. The hook reply never waits on the read; later events of the
+ node wait behind it. A remote (SSH) codex node's rollout is on its host, so it behaves as before.
- **Grok chat view (⌘M + phone `chat.page`)** — `parseGrokChat` (`core/grok-chat.ts`) reads
`chat_history.jsonl` into claude's `ChatMessage`/`ChatPart` shapes (no new wire field): typed
prompts, assistant text, tool calls (`arg` = the salient argument — `command`, `target_file`, …, in
diff --git a/src/core/agents/codex-permission-gate.test.ts b/src/core/agents/codex-permission-gate.test.ts
new file mode 100644
index 000000000..5fbda773c
--- /dev/null
+++ b/src/core/agents/codex-permission-gate.test.ts
@@ -0,0 +1,193 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { normalizeCodex, type NormalizedAgentEvent } from '../../shared/agents/normalize'
+import { testTmpDir } from '../test-tmp'
+import {
+ createCodexPermissionGate,
+ isCodexPermissionRequest,
+ isCodexRolloutPath,
+ readRolloutReviewer,
+ type CodexPermissionGateDeps
+} from './codex-permission-gate'
+import fixture from '../../shared/agents/__fixtures__/codex/auto-review-permission.json'
+
+type Rec = { type: string; payload: Record<string, unknown> }
+const hooks = (fixture.hooks as { payload: Record<string, unknown> }[]).map((h) => h.payload)
+const rollout = fixture.rollout as unknown as Rec[]
+const permission = hooks.find((h) => h.hook_event_name === 'PermissionRequest')!
+const turnCtx = rollout.find((r) => r.type === 'turn_context')!
+const TURN = permission.turn_id as string
+
+const dir = testTmpDir('nodeterm-codexgate-')
+const roots = { fixed: [path.join(dir, 'codex', 'sessions')], managedRoot: path.join(dir, 'cx') }
+let n = 0
+function writeRollout(recs: Rec[], root = roots.fixed[0]): string {
+ const file = path.join(root, '2026', '10', '16', `rollout-2026-10-16T12-36-34-${n++}.jsonl`)
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, recs.map((r) => JSON.stringify(r) + '\n').join(''))
+ return file
+}
+const withReviewer = (v: unknown): Rec[] =>
+ rollout.map((r) => (r.type === 'turn_context' ? { ...r, payload: { ...r.payload, approvals_reviewer: v } } : r))
+
+const ev = (p: Record<string, unknown>): NormalizedAgentEvent =>
+ normalizeCodex({ nodeId: 'c1', agentId: 'codex', payload: p }) as NormalizedAgentEvent
+
+describe('codex rollout reviewer read', () => {
+ it('the captured PermissionRequest carries no reviewer field and the turn ids match', () => {
+ expect(JSON.stringify(permission)).not.toMatch(/review/i)
+ expect(turnCtx.payload.turn_id).toBe(TURN)
+ expect(turnCtx.payload.approvals_reviewer).toBe('auto_review')
+ })
+
+ it('finds the turn_context for the hook turn, scanning backward across chunk boundaries', async () => {
+ const pad = { type: 'event_msg', payload: { type: 'x', text: 'y'.repeat(5000) } }
+ const file = writeRollout([...rollout.slice(0, 5), ...Array(40).fill(pad), ...rollout.slice(5)])
+ for (const chunk of [7, 64, 999, 1 << 20]) {
+ expect(await readRolloutReviewer(file, TURN, 16 << 20, chunk)).toBe('auto_review')
+ }
+ })
+
+ it('reads the turn_context when it is the first line of the file', async () => {
+ const file = writeRollout([turnCtx])
+ expect(await readRolloutReviewer(file, TURN, 1 << 20, 13)).toBe('auto_review')
+ })
+
+ it('takes only the record for THIS turn, never a newer or older one', async () => {
+ const other = { ...turnCtx, payload: { ...turnCtx.payload, turn_id: 'other', approvals_reviewer: 'auto_review' } }
+ const mine = { ...turnCtx, payload: { ...turnCtx.payload, approvals_reviewer: 'user' } }
+ const file = writeRollout([mine, other])
+ expect(await readRolloutReviewer(file, TURN)).toBe('user')
+ expect(await readRolloutReviewer(file, 'missing')).toBeNull()
+ })
+
+ it('gives up past the byte bound', async () => {
+ const pad = { type: 'event_msg', payload: { text: 'z'.repeat(4000) } }
+ const file = writeRollout([turnCtx, ...Array(20).fill(pad)])
+ expect(await readRolloutReviewer(file, TURN, 40_000, 1000)).toBeNull()
+ expect(await readRolloutReviewer(file, TURN, 200_000, 1000)).toBe('auto_review')
+ })
+
+ it('missing file and symlinked file read as unknown', async () => {
+ expect(await readRolloutReviewer(path.join(dir, 'nope.jsonl'), TURN)).toBeNull()
+ const real = writeRollout(withReviewer('auto_review'))
+ const link = path.join(path.dirname(real), 'rollout-link.jsonl')
+ fs.symlinkSync(real, link)
+ expect(await readRolloutReviewer(link, TURN)).toBeNull()
+ })
+
+ it('the path jail admits only rollouts under the codex sessions roots', () => {
+ const ok = path.join(roots.fixed[0], '2026', '10', '16', 'rollout-a.jsonl')
+ expect(isCodexRolloutPath(ok, roots)).toBe(true)
+ expect(isCodexRolloutPath(path.join(roots.managedRoot, '0123456789abcdef', 'sessions', 'x', 'rollout-a.jsonl'), roots)).toBe(true)
+ expect(isCodexRolloutPath(path.join(roots.managedRoot, '0123456789abcdef', 'auth', 'rollout-a.jsonl'), roots)).toBe(false)
+ expect(isCodexRolloutPath(path.join(roots.managedRoot, '..', 'sessions', 'rollout-a.jsonl'), roots)).toBe(false)
+ expect(isCodexRolloutPath(path.join(roots.fixed[0], '..', '..', 'id_rsa'), roots)).toBe(false)
+ expect(isCodexRolloutPath(path.join(roots.fixed[0], 'a', '..', '..', 'rollout-a.jsonl'), roots)).toBe(false)
+ expect(isCodexRolloutPath(path.join(roots.fixed[0], 'a', 'notes.jsonl'), roots)).toBe(false)
+ expect(isCodexRolloutPath('relative/rollout-a.jsonl', roots)).toBe(false)
+ })
+})
+
+describe('codex permission gate', () => {
+ const out: NormalizedAgentEvent[] = []
+ let gate: ReturnType<typeof createCodexPermissionGate> | undefined
+ afterEach(() => {
+ gate?.dispose()
+ out.length = 0
+ })
+ const deps = (over: Partial<CodexPermissionGateDeps> = {}): CodexPermissionGateDeps => ({
+ roots: () => roots,
+ readReviewer: (f, t) => readRolloutReviewer(f, t),
+ setTimer: (fn, ms) => setTimeout(fn, ms),
+ clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>),
+ confirmTimeoutMs: 2000,
+ ...over
+ })
+ const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 30))
+ const run = async (reviewer: unknown, over: Partial<CodexPermissionGateDeps> = {}, payload = permission): Promise<void> => {
+ const file = writeRollout(withReviewer(reviewer))
+ gate = createCodexPermissionGate((e) => out.push(e), deps(over))
+ for (const h of hooks) {
+ const p = h === permission ? { ...payload, transcript_path: file } : { ...h, transcript_path: file }
+ gate.handle('c1', p, ev(p))
+ }
+ await settle()
+ }
+
+ it('under auto_review the PermissionRequest is not shown as NEEDS YOU, order kept', async () => {
+ await run('auto_review')
+ expect(out.map((e) => e.state)).toEqual(['working', 'working', 'working', 'working', 'done'])
+ expect(out.some((e) => e.state === 'waiting')).toBe(false)
+ })
+
+ it('the legacy guardian_subagent spelling is the same reviewer', async () => {
+ await run('guardian_subagent')
+ expect(out.some((e) => e.state === 'waiting')).toBe(false)
+ })
+
+ for (const [label, value] of [
+ ['user', 'user'],
+ ['an unknown value', 'auto_review_v2'],
+ ['a non-string', 1]
+ ] as const) {
+ it(`keeps NEEDS YOU for ${label}`, async () => {
+ await run(value)
+ expect(out.map((e) => e.state)).toEqual(['working', 'working', 'working', 'waiting', 'working', 'done'])
+ })
+ }
+
+ it('keeps NEEDS YOU when the hook carries no turn_id', async () => {
+ const { turn_id: _drop, ...noTurn } = permission
+ await run('auto_review', {}, noTurn)
+ expect(out.map((e) => e.state)).toContain('waiting')
+ })
+
+ it('keeps NEEDS YOU for a transcript path outside the jail', async () => {
+ const file = writeRollout(withReviewer('auto_review'), path.join(dir, 'elsewhere'))
+ gate = createCodexPermissionGate((e) => out.push(e), deps())
+ gate.handle('c1', { ...permission, transcript_path: file }, ev(permission))
+ await settle()
+ expect(out.map((e) => e.state)).toEqual(['waiting'])
+ })
+
+ it('keeps NEEDS YOU when the read is slower than the timeout, and later events wait behind it', async () => {
+ await run('auto_review', {
+ confirmTimeoutMs: 5,
+ readReviewer: () => new Promise((r) => setTimeout(() => r('auto_review'), 60))
+ })
+ await new Promise((r) => setTimeout(r, 80))
+ expect(out.map((e) => e.state)).toEqual(['working', 'working', 'working', 'waiting', 'working', 'done'])
+ })
+
+ it('keeps NEEDS YOU when the read throws', async () => {
+ await run('auto_review', { readReviewer: () => Promise.reject(new Error('x')) })
+ expect(out.map((e) => e.state)).toContain('waiting')
+ })
+
+ it('reads a turn once', async () => {
+ let reads = 0
+ const file = writeRollout(withReviewer('auto_review'))
+ gate = createCodexPermissionGate((e) => out.push(e), deps({
+ readReviewer: (f, t) => {
+ reads++
+ return readRolloutReviewer(f, t)
+ }
+ }))
+ const p = { ...permission, transcript_path: file }
+ gate.handle('c1', p, ev(p))
+ gate.handle('c1', p, ev(p))
+ await settle()
+ expect(reads).toBe(1)
+ expect(out).toEqual([])
+ })
+
+ it('isCodexPermissionRequest is a closed match', () => {
+ expect(isCodexPermissionRequest(permission, ev(permission))).toBe(true)
+ const pre = hooks.find((h) => h.hook_event_name === 'PreToolUse')!
+ expect(isCodexPermissionRequest(pre, ev(pre))).toBe(false)
+ expect(isCodexPermissionRequest({ ...permission, agent_id: 'a' }, ev(permission))).toBe(false)
+ expect(isCodexPermissionRequest(permission, null)).toBe(false)
+ })
+})
diff --git a/src/core/agents/codex-permission-gate.ts b/src/core/agents/codex-permission-gate.ts
new file mode 100644
index 000000000..e9a924f36
--- /dev/null
+++ b/src/core/agents/codex-permission-gate.ts
@@ -0,0 +1,269 @@
+// Codex's PermissionRequest, checked against the session rollout before it is shown as NEEDS YOU
+// (issue #1171).
+//
+// WHY. `normalizeCodex` maps every `PermissionRequest` hook to `waiting`. With codex's automatic
+// approval reviewer (`approvals_reviewer = "auto_review"` in config.toml) nobody is asked: codex
+// fires the hook, hands the request to its own reviewer subagent, and runs (or refuses) the
+// command. No hook fires again until the approved command's `PostToolUse`, so the node read NEEDS
+// YOU for the review PLUS the command's whole run, with an inbox card, a push and a false alarm to
+// any orchestrator watching it.
+//
+// MEASURED (2026-10-16, private CODEX_HOME, a local fake Responses model; codex-cli 0.156.1 under
+// `codex exec` and 0.163.0 in the interactive TUI — fixture
+// `src/shared/agents/__fixtures__/codex/auto-review-permission.json`):
+// - The PermissionRequest payload carries NO reviewer field (`permission_mode: "default"`), so
+// the hook alone cannot tell the two cases apart.
+// - The session rollout (the payload's `transcript_path`) has one `turn_context` record per turn,
+// written at turn start, carrying `approvals_reviewer` (`"user"` or `"auto_review"`) and a
+// `turn_id` EQUAL to the hook's own `turn_id`. It is on disk before the hook runs (the hook
+// script read it back from inside the PermissionRequest hook).
+// - `approvals_reviewer = "guardian_subagent"` in config.toml is accepted and recorded as
+// `"auto_review"`: the old name of the same reviewer, so both spellings mean the same thing.
+// - A reviewer that cannot finish (its answer was not valid JSON) REJECTS the command back to the
+// agent; it is never handed to the user. The reviewer runs in its own rollout
+// (`thread_source: "guardian_review"`), not in the main one.
+//
+// RULES (each a refusal; every "cannot tell" is today's behaviour, `waiting`):
+// - Closed match: only a `turn_context` whose `turn_id` equals the hook's `turn_id`, and only an
+// `approvals_reviewer` in `CODEX_AUTO_REVIEWERS`, suppresses the event. A hook with no
+// `turn_id`, a value we do not know, a path outside the codex sessions roots, a missing or
+// unreadable file, no matching record within `CODEX_ROLLOUT_SCAN_MAX_BYTES` of the end, or a
+// read slower than `confirmTimeoutMs`: the hook is published unchanged.
+// - Suppressed means NOT PUBLISHED: the node keeps the `working` its PreToolUse just set (codex
+// fires PreToolUse before PermissionRequest for the same call). Nothing is invented.
+// - The hook reply never waits: the hook server answers 204 before this gate reads anything.
+// - Per node, later hook events wait behind a confirm read (bounded by the timeout), so a
+// `waiting` published on the slow path can never land after a newer event.
+//
+// A REMOTE (SSH) codex node's rollout lives on its host: the local file is absent and the hook is
+// published unchanged (the badge behaves as before). Lives in the hook server, so Desktop and the
+// Server Edition get it from one place.
+import path from 'path'
+import os from 'os'
+import { constants as fsc, promises as fsp } from 'fs'
+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'
+import { systemCodexHome } from '../codex-accounts-core'
+
+/** The `approvals_reviewer` values that mean "codex's own reviewer decides, no person is asked". */
+export const CODEX_AUTO_REVIEWERS = ['auto_review', 'guardian_subagent'] as const
+
+/** How far back from the end of a rollout the `turn_context` is looked for. The longest single
+ * turn across 62 real rollouts measured 5.9 MB from its `turn_context` to the next one. */
+export const CODEX_ROLLOUT_SCAN_MAX_BYTES = 16 * 1024 * 1024
+const CHUNK_BYTES = 256 * 1024
+const TURN_CONTEXT_MARK = Buffer.from('"type":"turn_context"')
+
+/** True for the normalized event a codex PermissionRequest hook produces (never a child's: those
+ * normalize to null). */
+export function isCodexPermissionRequest(payload: Record<string, unknown>, e: NormalizedAgentEvent | null): boolean {
+ if (!e || e.kind !== 'state' || e.state !== 'waiting') return false
+ const p = payload as { hook_event_name?: unknown; hookEventName?: unknown; agent_id?: unknown }
+ if (p.agent_id) return false
+ return (p.hook_event_name ?? p.hookEventName) === 'PermissionRequest'
+}
+
+/** The codex `sessions` roots on this machine: the system home (`$CODEX_HOME` honoured) and the
+ * managed accounts' short homes `~/.nodeterm/cx/<16 hex>`. */
+export function codexSessionsRoots(): { fixed: string[]; managedRoot: string } {
+ return {
+ fixed: [path.join(systemCodexHome(), 'sessions')],
+ managedRoot: path.join(os.homedir(), '.nodeterm', 'cx')
+ }
+}
+
+/** Whether `file` is a codex rollout under one of the roots. Lexical, on a resolved path: the
+ * payload is untrusted (a forged hook POST must not aim a read anywhere else). */
+export function isCodexRolloutPath(file: string, roots: { fixed: string[]; managedRoot: string }): boolean {
+ if (!file || !path.isAbsolute(file)) return false
+ const abs = path.resolve(file)
+ if (!/^rollout-[^/\\]*\.jsonl$/.test(path.basename(abs))) return false
+ for (const r of roots.fixed) if (abs.startsWith(r + path.sep)) return true
+ const m = roots.managedRoot
+ if (!abs.startsWith(m + path.sep)) return false
+ const segs = path.relative(m, abs).split(path.sep)
+ return segs.length >= 3 && /^[0-9a-f]{16}$/.test(segs[0]) && segs[1] === 'sessions'
+}
+
+/** `approvals_reviewer` of a `turn_context` line for `turnId`; `''` when that record has no string
+ * value; `null` for any other line. */
+function reviewerOfLine(line: Buffer, turnId: string): string | null {
+ if (line.indexOf(TURN_CONTEXT_MARK) < 0) return null
+ let r: unknown
+ try {
+ r = JSON.parse(line.toString('utf8'))
+ } catch {
+ return null
+ }
+ const rec = r as { type?: unknown; payload?: { turn_id?: unknown; approvals_reviewer?: unknown } } | null
+ if (!rec || rec.type !== 'turn_context' || !rec.payload || rec.payload.turn_id !== turnId) return null
+ return typeof rec.payload.approvals_reviewer === 'string' ? rec.payload.approvals_reviewer : ''
+}
+
+/**
+ * The `approvals_reviewer` of the newest `turn_context` for `turnId`, scanning the file BACKWARD
+ * from its end in chunks, at most `maxBytes`. `null` when the file cannot be read or holds no such
+ * record within the bound. The last component is opened with O_NOFOLLOW.
+ */
+export async function readRolloutReviewer(
+ file: string,
+ turnId: string,
+ maxBytes = CODEX_ROLLOUT_SCAN_MAX_BYTES,
+ chunkBytes = CHUNK_BYTES
+): Promise<string | null> {
+ let fh: Awaited<ReturnType<typeof fsp.open>> | undefined
+ try {
+ fh = await fsp.open(file, fsc.O_RDONLY | (fsc.O_NOFOLLOW ?? 0))
+ const st = await fh.stat()
+ if (!st.isFile()) return null
+ let pos = st.size
+ const floor = Math.max(0, st.size - maxBytes)
+ // Bytes after the last newline seen so far that belong to a line not yet complete (its start
+ // lies in an earlier chunk).
+ let carry: Buffer = Buffer.alloc(0)
+ while (pos > floor) {
+ const len = Math.min(chunkBytes, pos - floor)
+ pos -= len
+ const buf = Buffer.alloc(len)
+ await fh.read(buf, 0, len, pos)
+ const data = carry.length ? Buffer.concat([buf, carry]) : buf
+ // Complete lines are those that END inside `data` and START after a newline in `data`.
+ let end = data.length
+ for (let i = data.length - 1; i >= 0; i--) {
+ if (data[i] !== 0x0a) continue
+ const v = reviewerOfLine(data.subarray(i + 1, end), turnId)
+ if (v !== null) return v
+ end = i
+ }
+ carry = Buffer.from(data.subarray(0, end))
+ // The first line of the file has no newline before it.
+ if (pos === 0) return reviewerOfLine(carry, turnId)
+ }
+ return null
+ } catch {
+ return null
+ } finally {
+ await fh?.close().catch(() => {})
+ }
+}
+
+export interface CodexPermissionGateDeps {
+ roots: () => { fixed: string[]; managedRoot: string }
+ readReviewer: (file: string, turnId: string) => Promise<string | null>
+ setTimer: (fn: () => void, ms: number) => unknown
+ clearTimer: (t: unknown) => void
+ /** A confirm read slower than this publishes the hook unchanged. */
+ confirmTimeoutMs: number
+}
+
+export const defaultCodexPermissionGateDeps = (): CodexPermissionGateDeps => ({
+ roots: codexSessionsRoots,
+ readReviewer: (file, turnId) => readRolloutReviewer(file, turnId),
+ setTimer: (fn, ms) => {
+ const t = setTimeout(fn, ms)
+ ;(t as { unref?: () => void }).unref?.()
+ return t
+ },
+ clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>),
+ confirmTimeoutMs: 500
+})
+
+export interface CodexPermissionGate {
+ /** Every codex hook event goes through here; `deliver` is the hook server's listener. */
+ handle(nodeId: string, payload: Record<string, unknown>, e: NormalizedAgentEvent | null): void
+ dispose(): void
+}
+
+/** Turns remembered per node: the reviewer of a turn never changes, so a second PermissionRequest
+ * in the same turn costs no read. */
+const TURNS_PER_NODE = 4
+
+export function createCodexPermissionGate(
+ deliver: (e: NormalizedAgentEvent) => void,
+ deps: CodexPermissionGateDeps = defaultCodexPermissionGateDeps()
+): CodexPermissionGate {
+ const chains = new Map<string, Promise<void>>()
+ const known = new Map<string, Map<string, string>>() // nodeId → `${file}\0${turnId}` → reviewer
+ let disposed = false
+
+ let warned = false
+ const safeDeliver = (e: NormalizedAgentEvent): void => {
+ try {
+ deliver(e)
+ } catch (err) {
+ if (!warned) {
+ warned = true
+ console.warn('[codex-permission-gate] listener threw; event dropped', err)
+ }
+ }
+ }
+
+ const enqueue = (nodeId: string, step: () => Promise<void> | void): void => {
+ const next = (chains.get(nodeId) ?? Promise.resolve()).then(step).catch(() => {})
+ chains.set(nodeId, next)
+ void next.then(() => {
+ if (chains.get(nodeId) === next) chains.delete(nodeId)
+ })
+ }
+
+ /** The reviewer for this hook, or null when it cannot be told. */
+ const reviewerFor = async (nodeId: string, payload: Record<string, unknown>): Promise<string | null> => {
+ const p = payload as { transcript_path?: unknown; turn_id?: unknown }
+ const file = typeof p.transcript_path === 'string' ? p.transcript_path : ''
+ const turnId = typeof p.turn_id === 'string' ? p.turn_id : ''
+ if (!turnId || !isCodexRolloutPath(file, deps.roots())) return null
+ const key = `${path.resolve(file)}\0${turnId}`
+ const cached = known.get(nodeId)?.get(key)
+ if (cached !== undefined) return cached
+ const v = await deps.readReviewer(path.resolve(file), turnId)
+ if (v === null || disposed) return v
+ let m = known.get(nodeId)
+ if (!m) known.set(nodeId, (m = new Map()))
+ m.delete(key)
+ m.set(key, v)
+ while (m.size > TURNS_PER_NODE) m.delete(m.keys().next().value as string)
+ return v
+ }
+
+ return {
+ handle(nodeId, payload, e) {
+ if (disposed || !e || !isCodexPermissionRequest(payload, e)) {
+ if (disposed) {
+ if (e) safeDeliver(e)
+ return
+ }
+ enqueue(nodeId, () => {
+ if (e) safeDeliver(e)
+ })
+ return
+ }
+ enqueue(
+ nodeId,
+ () =>
+ new Promise<void>((resolve) => {
+ let settled = false
+ const finish = (suppress: boolean): void => {
+ if (settled) return
+ settled = true
+ if (!suppress) safeDeliver(e)
+ resolve()
+ }
+ const t = deps.setTimer(() => finish(false), deps.confirmTimeoutMs)
+ reviewerFor(nodeId, payload).then(
+ (v) => {
+ deps.clearTimer(t)
+ finish(v !== null && (CODEX_AUTO_REVIEWERS as readonly string[]).includes(v))
+ },
+ () => {
+ deps.clearTimer(t)
+ finish(false)
+ }
+ )
+ })
+ )
+ },
+ dispose() {
+ disposed = true
+ known.clear()
+ }
+ }
+}
diff --git a/src/core/agents/hook-server.codex-permission.test.ts b/src/core/agents/hook-server.codex-permission.test.ts
new file mode 100644
index 000000000..597b67a44
--- /dev/null
+++ b/src/core/agents/hook-server.codex-permission.test.ts
@@ -0,0 +1,85 @@
+// End to end through the REAL hook server (issue #1171): the captured codex hook sequence under
+// `approvals_reviewer = "auto_review"` (`__fixtures__/codex/auto-review-permission.json`), the gate
+// reading a real rollout on disk, and the listener both shells install.
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { request } from 'node:http'
+import { hookServer } from './hook-server'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform } from '../platform-fake'
+import { testTmpDir } from '../test-tmp'
+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'
+import { defaultCodexPermissionGateDeps } from './codex-permission-gate'
+import fixture from '../../shared/agents/__fixtures__/codex/auto-review-permission.json'
+
+type Rec = { type: string; payload: Record<string, unknown> }
+const hooks = (fixture.hooks as { payload: Record<string, unknown> }[]).map((h) => h.payload)
+const rollout = fixture.rollout as unknown as Rec[]
+const events: NormalizedAgentEvent[] = []
+let sessions = ''
+
+beforeAll(async () => {
+ const dir = testTmpDir('nodeterm-codexgate-hs-')
+ sessions = path.join(dir, 'codex', 'sessions')
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: path.join(dir, 'ud') }))
+ await hookServer.start()
+ hookServer.setListener((e) => events.push(e))
+ hookServer.setCodexPermissionGateDeps({
+ ...defaultCodexPermissionGateDeps(),
+ roots: () => ({ fixed: [sessions], managedRoot: path.join(dir, 'cx') })
+ })
+})
+afterAll(() => hookServer.stop())
+beforeEach(() => {
+ events.length = 0
+})
+
+function post(payload: Record<string, unknown>): Promise<number> {
+ const body = new URLSearchParams({ nodeId: 'c1', version: '2', payload: JSON.stringify(payload) }).toString()
+ return new Promise((resolve, reject) => {
+ const req = request(
+ {
+ host: '127.0.0.1',
+ port: hookServer.getPort(),
+ path: '/hook/codex',
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Nodeterm-Hook-Token': hookServer.getToken() }
+ },
+ (res) => {
+ res.resume()
+ res.on('end', () => resolve(res.statusCode ?? 0))
+ }
+ )
+ req.on('error', reject)
+ req.end(body)
+ })
+}
+const until = async (ok: () => boolean): Promise<void> => {
+ for (let i = 0; i < 100 && !ok(); i++) await new Promise((r) => setTimeout(r, 20))
+}
+
+async function replay(reviewer: string): Promise<(string | undefined)[]> {
+ const file = path.join(sessions, '2026', '10', '16', `rollout-${reviewer}.jsonl`)
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(
+ file,
+ rollout
+ .map((r) => (r.type === 'turn_context' ? { ...r, payload: { ...r.payload, approvals_reviewer: reviewer } } : r))
+ .map((r) => JSON.stringify(r) + '\n')
+ .join('')
+ )
+ for (const h of hooks) expect(await post({ ...h, transcript_path: file })).toBe(204)
+ await until(() => events.at(-1)?.state === 'done')
+ return events.map((e) => e.state)
+}
+
+describe('hook server + codex permission gate', () => {
+ it('auto_review: the node never reads NEEDS YOU', async () => {
+ expect(await replay('auto_review')).toEqual(['working', 'working', 'working', 'working', 'done'])
+ })
+ it('user reviewer: NEEDS YOU as before', async () => {
+ expect(await replay('user')).toEqual(['working', 'working', 'working', 'waiting', 'working', 'done'])
+ })
+})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 64f7b79ef..ff6968368 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -19,6 +19,12 @@ import {
type GrokPermissionGate,
type GrokPermissionGateDeps
} from './grok-permission-gate'
+import {
+ createCodexPermissionGate,
+ defaultCodexPermissionGateDeps,
+ type CodexPermissionGate,
+ type CodexPermissionGateDeps
+} from './codex-permission-gate'
import { classifyClaudeConfigDir, configDirFromTranscriptPath } from '../claude-accounts-core'
import { claudeAccountsSnapshot } from '../claude-config-dir'
import type { CodexIdentityEvent, ObservedClaudeAccount } from '../../shared/types'
@@ -526,6 +532,24 @@ export class HookServer {
return this.grokPermissionGate
}
+ private codexPermissionGate: CodexPermissionGate | null = null
+ private codexGateDeps: CodexPermissionGateDeps | undefined
+ /** Test seam: the codex permission gate's file/timer deps. */
+ setCodexPermissionGateDeps(deps: CodexPermissionGateDeps): void {
+ this.codexPermissionGate?.dispose()
+ this.codexPermissionGate = null
+ this.codexGateDeps = deps
+ }
+ private codexGate(): CodexPermissionGate {
+ if (!this.codexPermissionGate) {
+ this.codexPermissionGate = createCodexPermissionGate(
+ (e) => this.listener?.(e),
+ this.codexGateDeps ?? defaultCodexPermissionGateDeps()
+ )
+ }
+ return this.codexPermissionGate
+ }
+
// Raw payload listener: receives the parsed (un-normalized) hook JSON. Drives the
// contextTail/subagentTail features, which need transcript_path (not in NormalizedAgentEvent).
// `meta` carries what the transport knows about the caller (see HookEventMeta).
@@ -1116,6 +1140,11 @@ export class HookServer {
// published, and cleared from it once answered (core/agents/grok-permission-gate.ts).
// Every grok event goes through the gate so their order is kept per node.
if (agentId === 'grok') this.grokGate().handle(nodeId, payload, labelled)
+ // Codex's PermissionRequest is checked against the session rollout: under codex's own
+ // auto-reviewer nobody is asked, so it must not read as NEEDS YOU (issue #1171,
+ // core/agents/codex-permission-gate.ts). Every codex event goes through the gate so their
+ // order is kept per node.
+ else if (agentId === 'codex') this.codexGate().handle(nodeId, payload, labelled)
else if (labelled && this.listener) this.listener(labelled)
}
res.writeHead(204)
@@ -1556,6 +1585,8 @@ export class HookServer {
this.requestLedgerFile = null
this.grokPermissionGate?.dispose()
this.grokPermissionGate = null
+ this.codexPermissionGate?.dispose()
+ this.codexPermissionGate = null
this.server?.close()
this.server = null
// The file must not advertise a listener that no longer exists (issue #445): a stopped server
diff --git a/src/shared/agents/__fixtures__/codex/auto-review-permission.json b/src/shared/agents/__fixtures__/codex/auto-review-permission.json
new file mode 100644
index 000000000..cfaa3819d
--- /dev/null
+++ b/src/shared/agents/__fixtures__/codex/auto-review-permission.json
@@ -0,0 +1,573 @@
+{
+ "note": "Captured 2026-10-16 with codex-cli 0.163.0 (interactive TUI, private CODEX_HOME, local fake Responses model, approvals_reviewer = \"auto_review\", approval_policy = \"on-request\", sandbox_mode = \"read-only\"). The same shapes were seen with 0.156.1 under codex exec. Paths rewritten to /lab. receivedAt = epoch seconds the hook script ran. rollout = the main thread rollout records (developer message text elided).",
+ "hooks": [
+ {
+ "receivedAt": 1792143394.6406503,
+ "payload": {
+ "session_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "transcript_path": "/lab/codexhome/sessions/2026/10/16/rollout-2026-10-16T12-36-34-01a14412-0711-7150-a315-ffbf31a65435.jsonl",
+ "cwd": "/lab/work",
+ "hook_event_name": "SessionStart",
+ "model": "fake",
+ "permission_mode": "default",
+ "source": "startup"
+ }
+ },
+ {
+ "receivedAt": 1792143394.6451676,
+ "payload": {
+ "session_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "transcript_path": "/lab/codexhome/sessions/2026/10/16/rollout-2026-10-16T12-36-34-01a14412-0711-7150-a315-ffbf31a65435.jsonl",
+ "cwd": "/lab/work",
+ "hook_event_name": "UserPromptSubmit",
+ "model": "fake",
+ "permission_mode": "default",
+ "prompt": "run the tests"
+ }
+ },
+ {
+ "receivedAt": 1792143394.677283,
+ "payload": {
+ "session_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "transcript_path": "/lab/codexhome/sessions/2026/10/16/rollout-2026-10-16T12-36-34-01a14412-0711-7150-a315-ffbf31a65435.jsonl",
+ "cwd": "/lab/work",
+ "hook_event_name": "PreToolUse",
+ "model": "fake",
+ "permission_mode": "default",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "touch /lab/outside-12 && sleep 4"
+ },
+ "tool_use_id": "call12"
+ }
+ },
+ {
+ "receivedAt": 1792143394.7050555,
+ "payload": {
+ "session_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "transcript_path": "/lab/codexhome/sessions/2026/10/16/rollout-2026-10-16T12-36-34-01a14412-0711-7150-a315-ffbf31a65435.jsonl",
+ "cwd": "/lab/work",
+ "hook_event_name": "PermissionRequest",
+ "model": "fake",
+ "permission_mode": "default",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "touch /lab/outside-12 && sleep 4",
+ "description": "need to write outside sandbox"
+ }
+ }
+ },
+ {
+ "receivedAt": 1792143398.8070297,
+ "payload": {
+ "session_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "transcript_path": "/lab/codexhome/sessions/2026/10/16/rollout-2026-10-16T12-36-34-01a14412-0711-7150-a315-ffbf31a65435.jsonl",
+ "cwd": "/lab/work",
+ "hook_event_name": "PostToolUse",
+ "model": "fake",
+ "permission_mode": "default",
+ "tool_name": "Bash",
+ "tool_input": {
+ "command": "touch /lab/outside-12 && sleep 4"
+ },
+ "tool_response": "",
+ "tool_use_id": "call12"
+ }
+ },
+ {
+ "receivedAt": 1792143398.83488,
+ "payload": {
+ "session_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "transcript_path": "/lab/codexhome/sessions/2026/10/16/rollout-2026-10-16T12-36-34-01a14412-0711-7150-a315-ffbf31a65435.jsonl",
+ "cwd": "/lab/work",
+ "hook_event_name": "Stop",
+ "model": "fake",
+ "permission_mode": "default",
+ "stop_hook_active": false,
+ "last_assistant_message": "done"
+ }
+ }
+ ],
+ "rollout": [
+ {
+ "timestamp": "2026-10-16T09:36:34.621Z",
+ "ordinal": 0,
+ "type": "session_meta",
+ "payload": {
+ "session_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "timestamp": "2026-10-16T09:36:34.579Z",
+ "cwd": "/lab/work",
+ "runtime_workspace_roots": [
+ "/lab/work"
+ ],
+ "originator": "codex-tui",
+ "cli_version": "0.163.0",
+ "source": "vscode",
+ "thread_source": "user",
+ "model_provider": "fake",
+ "history_mode": "paginated",
+ "context_window": {
+ "window_id": "01a14412-0712-77d3-b873-62635003554e"
+ }
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.621Z",
+ "ordinal": 1,
+ "type": "event_msg",
+ "payload": {
+ "type": "task_started",
+ "turn_attribution": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "turn_trigger": "user",
+ "parent_turn_id": null,
+ "initiating_agent_path": null,
+ "root_turn_id": "01a14412-073a-7333-91b1-416c357192ac"
+ },
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "root_turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "started_at": 1792143394,
+ "model_context_window": 258400,
+ "collaboration_mode_kind": "default"
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.633Z",
+ "ordinal": 2,
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "id": "msg_01a14412-0749-7330-9661-4de9833ab8fc",
+ "role": "developer",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "<elided by fixture>"
+ }
+ ],
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "create_time": 1792143394.6334124,
+ "content_item_kinds": [
+ "host_skills.instructions",
+ "permissions.instructions",
+ "collaboration_mode.instructions"
+ ]
+ }
+ },
+ "metadata": {
+ "client_authored": false,
+ "mcp_attribution": {
+ "status": "none"
+ }
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.633Z",
+ "ordinal": 3,
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "id": "msg_01a14412-0749-7330-9661-4dfdab95e628",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "<environment_context>\n <cwd>/lab/work</cwd>\n <shell>bash</shell>\n <current_date>2026-10-16</current_date>\n <timezone>Europe/Istanbul</timezone>\n <filesystem><workspace_roots><root>/lab/work</root></workspace_roots><permission_profile type=\"managed\"><file_system type=\"restricted\"><entry access=\"read\"><special>:root</special></entry></file_system></permission_profile></filesystem>\n</environment_context>"
+ }
+ ],
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "create_time": 1792143394.6334188,
+ "content_item_kinds": [
+ "environments.environment_context"
+ ]
+ }
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.635Z",
+ "ordinal": 5,
+ "type": "turn_context",
+ "payload": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "root_turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "disabled_plugin_ids": [],
+ "cwd": "/lab/work",
+ "approval_policy": "on-request",
+ "approvals_reviewer": "auto_review",
+ "sandbox_policy": {
+ "type": "read-only"
+ },
+ "permission_profile": {
+ "type": "managed",
+ "file_system": {
+ "type": "restricted",
+ "entries": [
+ {
+ "path": {
+ "type": "special",
+ "value": {
+ "kind": "root"
+ }
+ },
+ "access": "read"
+ }
+ ]
+ },
+ "network": "restricted"
+ },
+ "model": "fake",
+ "collaboration_mode": {
+ "mode": "default",
+ "settings": {
+ "model": "fake",
+ "reasoning_effort": null,
+ "developer_instructions": "# Collaboration Mode: Default\n\nYou are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.\n\nYour active mode changes only when new developer instructions with a different `<collaboration_mode>...</collaboration_mode>` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.\n\n## request_user_input availability\n\nUse the `request_user_input` tool only when it is listed in the available tools for this turn.\n\nIn Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions.\n\nUse the `request_user_input` tool only for optional questions where the answer would materially improve the quality of the work.\n\nIf `request_user_input` returns no answers, continue with best judgment instead of asking again or treating the turn as blocked.\n\nNever use the `request_user_input` tool for permission requests or permission-related escalations.\n\nIf explicit user input is required for another reason before progress can safely continue, do not use the `request_user_input` tool. Ask the user directly with one concise plain-text question instead. Never write a multiple choice question as a textual assistant message.\n"
+ }
+ },
+ "multi_agent_version": "v1",
+ "realtime_active": false,
+ "summary": "none"
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.635Z",
+ "ordinal": 6,
+ "type": "event_msg",
+ "payload": {
+ "type": "thread_settings_applied",
+ "thread_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "thread_settings": {
+ "model": "fake",
+ "model_provider_id": "fake",
+ "approval_policy": "on-request",
+ "approvals_reviewer": "auto_review",
+ "permission_profile": {
+ "type": "managed",
+ "file_system": {
+ "type": "restricted",
+ "entries": [
+ {
+ "path": {
+ "type": "special",
+ "value": {
+ "kind": "root"
+ }
+ },
+ "access": "read"
+ }
+ ]
+ },
+ "network": "restricted"
+ },
+ "cwd": "/lab/work",
+ "runtime_workspace_roots": [
+ "/lab/work"
+ ],
+ "collaboration_mode": {
+ "mode": "default",
+ "settings": {
+ "model": "fake",
+ "reasoning_effort": null,
+ "developer_instructions": "# Collaboration Mode: Default\n\nYou are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.\n\nYour active mode changes only when new developer instructions with a different `<collaboration_mode>...</collaboration_mode>` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.\n\n## request_user_input availability\n\nUse the `request_user_input` tool only when it is listed in the available tools for this turn.\n\nIn Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions.\n\nUse the `request_user_input` tool only for optional questions where the answer would materially improve the quality of the work.\n\nIf `request_user_input` returns no answers, continue with best judgment instead of asking again or treating the turn as blocked.\n\nNever use the `request_user_input` tool for permission requests or permission-related escalations.\n\nIf explicit user input is required for another reason before progress can safely continue, do not use the `request_user_input` tool. Ask the user directly with one concise plain-text question instead. Never write a multiple choice question as a textual assistant message.\n"
+ }
+ },
+ "disabled_plugin_ids": []
+ }
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.645Z",
+ "ordinal": 7,
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "id": "msg_01a14412-0755-7ed2-a0bd-1c876f36b476",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "run the tests"
+ }
+ ],
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "create_time": 1792143394.6456115,
+ "content_item_kinds": [
+ "user.text"
+ ]
+ }
+ },
+ "metadata": {
+ "retained_source": {
+ "id": {
+ "message_id": "msg_01a14412-0755-7ed2-a0bd-1c876f36b476",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "role": "user"
+ },
+ "revision": "retained_01a14412-0755-7ed2-a0bd-1ca634a45f43",
+ "complete": true
+ },
+ "client_authored": false,
+ "user_input_order": 0,
+ "mcp_attribution": {
+ "status": "none"
+ }
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.646Z",
+ "ordinal": 8,
+ "type": "event_msg",
+ "payload": {
+ "type": "item_completed",
+ "thread_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "item": {
+ "type": "UserMessage",
+ "id": "01a14412-0755-7ed2-a0bd-1c94dd571a01",
+ "client_id": "ef49187c-3d13-4541-b46d-0ce657b85026",
+ "content": [
+ {
+ "type": "text",
+ "text": "run the tests",
+ "text_elements": []
+ }
+ ]
+ },
+ "started_at_ms": 1792143394646,
+ "completed_at_ms": 1792143394646
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:34.669Z",
+ "ordinal": 9,
+ "type": "response_item",
+ "payload": {
+ "type": "function_call",
+ "id": "fc12",
+ "name": "exec_command",
+ "arguments": "{\"cmd\":\"touch /lab/outside-12 && sleep 4\",\"sandbox_permissions\":\"require_escalated\",\"justification\":\"need to write outside sandbox\"}",
+ "call_id": "call12",
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac"
+ }
+ },
+ "metadata": {
+ "client_authored": false,
+ "user_input_order": 1
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:38.801Z",
+ "ordinal": 11,
+ "type": "event_msg",
+ "payload": {
+ "type": "item_completed",
+ "thread_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "item": {
+ "type": "CommandExecution",
+ "id": "call12",
+ "process_id": "78676",
+ "command": [
+ "/bin/bash",
+ "-lc",
+ "touch /lab/outside-12 && sleep 4"
+ ],
+ "cwd": "file:///lab/work",
+ "parsed_cmd": [
+ {
+ "type": "unknown",
+ "cmd": "touch /lab/outside-12 && sleep 4"
+ }
+ ],
+ "source": "unified_exec_startup",
+ "status": "completed",
+ "aggregated_output": "",
+ "exit_code": 0,
+ "duration": {
+ "secs": 3,
+ "nanos": 857768531
+ }
+ },
+ "started_at_ms": 1792143394943,
+ "completed_at_ms": 1792143398801
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:38.807Z",
+ "ordinal": 12,
+ "type": "response_item",
+ "payload": {
+ "type": "function_call_output",
+ "id": "fco_01a14412-1797-72d0-8598-da94e4694366",
+ "call_id": "call12",
+ "output": "Chunk ID: 289115\nWall time: 3.8578 seconds\nProcess exited with code 0\nOriginal token count: 0\nOutput:\n",
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "create_time": 1792143398.807718
+ }
+ },
+ "metadata": {
+ "client_authored": false,
+ "fallback_token_limit_override": 3000
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:38.808Z",
+ "ordinal": 13,
+ "type": "event_msg",
+ "payload": {
+ "type": "token_count",
+ "info": {
+ "total_token_usage": {
+ "input_tokens": 10,
+ "cached_input_tokens": 0,
+ "cache_write_input_tokens": 0,
+ "output_tokens": 5,
+ "reasoning_output_tokens": 0,
+ "total_tokens": 15
+ },
+ "last_token_usage": {
+ "input_tokens": 10,
+ "cached_input_tokens": 0,
+ "cache_write_input_tokens": 0,
+ "output_tokens": 5,
+ "reasoning_output_tokens": 0,
+ "total_tokens": 15
+ },
+ "model_context_window": 258400
+ },
+ "rate_limits": {
+ "limit_id": "codex",
+ "limit_name": null,
+ "primary": null,
+ "secondary": null,
+ "credits": null,
+ "individual_limit": null,
+ "spend_control_reached": null,
+ "plan_type": null,
+ "rate_limit_reached_type": null
+ }
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:38.825Z",
+ "ordinal": 14,
+ "type": "event_msg",
+ "payload": {
+ "type": "item_completed",
+ "thread_id": "01a14412-0711-7150-a315-ffbf31a65435",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "item": {
+ "type": "AgentMessage",
+ "id": "m16",
+ "content": [
+ {
+ "type": "Text",
+ "text": "done"
+ }
+ ]
+ },
+ "started_at_ms": 1792143398825,
+ "completed_at_ms": 1792143398825
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:38.826Z",
+ "ordinal": 15,
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "id": "m16",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "output_text",
+ "text": "done"
+ }
+ ],
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "content_item_kinds": [
+ "unknown"
+ ]
+ }
+ },
+ "metadata": {
+ "retained_source": {
+ "id": {
+ "message_id": "m16",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "role": "assistant"
+ },
+ "revision": "retained_01a14412-17aa-70d0-a7a1-00295e13a9f8",
+ "complete": true
+ },
+ "client_authored": false,
+ "user_input_order": 2
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:38.827Z",
+ "ordinal": 17,
+ "type": "event_msg",
+ "payload": {
+ "type": "token_count",
+ "info": {
+ "total_token_usage": {
+ "input_tokens": 20,
+ "cached_input_tokens": 0,
+ "cache_write_input_tokens": 0,
+ "output_tokens": 10,
+ "reasoning_output_tokens": 0,
+ "total_tokens": 30
+ },
+ "last_token_usage": {
+ "input_tokens": 10,
+ "cached_input_tokens": 0,
+ "cache_write_input_tokens": 0,
+ "output_tokens": 5,
+ "reasoning_output_tokens": 0,
+ "total_tokens": 15
+ },
+ "model_context_window": 258400
+ },
+ "rate_limits": {
+ "limit_id": "codex",
+ "limit_name": null,
+ "primary": null,
+ "secondary": null,
+ "credits": null,
+ "individual_limit": null,
+ "spend_control_reached": null,
+ "plan_type": null,
+ "rate_limit_reached_type": null
+ }
+ }
+ },
+ {
+ "timestamp": "2026-10-16T09:36:38.836Z",
+ "ordinal": 18,
+ "type": "event_msg",
+ "payload": {
+ "type": "task_complete",
+ "root_turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "turn_id": "01a14412-073a-7333-91b1-416c357192ac",
+ "last_agent_message": "done",
+ "started_at": 1792143394,
+ "completed_at": 1792143398,
+ "duration_ms": 4216,
+ "time_to_first_token_ms": 49
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index 413f12049..2fc1b1632 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -558,6 +558,9 @@ export function normalizeCodex(env: RawHookEnvelope): NormalizedAgentEvent | nul
if (ev === 'SessionStart' || ev === 'PreToolUse' || ev === 'PostToolUse') {
return { ...base, kind: 'state', state: 'working' }
}
+ // Under codex's own auto-reviewer (`approvals_reviewer = "auto_review"`) nobody is asked; the
+ // hook server's codex permission gate (core/agents/codex-permission-gate.ts) reads the rollout
+ // and drops this event then. The payload alone cannot tell (measured: no reviewer field).
if (ev === 'PermissionRequest') return { ...base, kind: 'state', state: 'waiting' }
if (ev === 'Stop') return { ...base, kind: 'state', state: 'done' }
return null