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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(agents): codex subagent visualization via native SubagentStart/Stop hooks
enes6f7c8a79228e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7c3a7f007..f1560be0b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -933,7 +933,8 @@ else, and its context links must keep classifying across restarts).process re-advertises the same endpoint (restart handoff). A `setRawListener` channel feedsthe per-node context-window meter (`context-tail.ts` — **one tail per agent**, each with its own`parse` dep: claude's usage records, `codexContextParse`, `geminiContextParse`) and the subagent- live-transcript (`subagent-tail.ts`, claude only). The same events feed the **agent-status mirror**+ live-transcript (`subagent-tail.ts` — claude via meta-dir `track`, codex via `trackFile` with the+ stateful `codex-subagent-format.ts` formatter). The same events feed the **agent-status mirror**(`core/agent-status-mirror.ts`) the mobile companion reads; the mirror carries an optional`settings` block (`claudePermissionMode`/`autoSupported`/`claudeAccounts`) so the phone canlaunch agents with the desktop's permission mode + managed accounts, and SSH slices get their@@ -1109,6 +1110,28 @@ else, and its context links must keep classifying across restarts).(`<…>/<sessionId>/subagents/agent-<id>.jsonl`, matched by `tool_use_id` via the sibling`.meta.json`), tails it read-only, formats each line (assistant text + tool calls + results),and streams chunks over `agent:subagent-activity` into the store.+ **Codex** (2026-08-24, `spawn_agent` collaboration — issue #401) joined via its **native+ `SubagentStart`/`SubagentStop` hooks**, measured on codex-cli 0.146.0, keyed by `agent_id` (NOT+ `tool_use_id` — nothing correlates the spawn tool call with the Start it launches; agent_id is+ stable across the child's life, parallel + nested spawns included, and nested children fire+ through the same subscription so every card connects flat to the owning terminal node). Facts a+ refactor must not lose: **(1)** every agent_id-tagged codex event carries the PARENT's+ `session_id` with the CHILD's rollout as `transcript_path` — both raw listeners skip the+ context-meter track for them (else the parent's meter re-points at the child) and `normalizeCodex`+ returns null for child tool events (else a child Bash event flips a finished parent back to+ RUNNING after an async spawn); pinned by `hook-verified-parity.test.ts`. **(2)** the spawn task+ text is **encrypted end-to-end** (`tool_input.message` and the NEW_TASK payload are Fernet blobs)+ — there is no `taskLabel`; the readable `Task name:` header reaches the card via the activity+ stream instead. **(3)** the live tail is `subagentTail.trackFile` (the path is handed to us —+ no meta-dir matching) with the **stateful, per-entry** `createCodexSubagentFormatter`+ (`core/codex-subagent-format.ts`): a spawn child is a FORK of the parent thread, so its rollout+ opens with a replay of the parent's context, suppressed until the+ `inter_agent_communication_metadata` / NEW_TASK gate — per entry, because two concurrent+ subagents sharing one closure would gate each other. **(4)** codex's `SubagentStop` IS the real+ end (no async-launch-ack trap, no task-notification sniffing), carrying+ `last_assistant_message` as the card's result. Remote (SSH) codex nodes get cards but no live+ activity yet (the child rollout is on the host; claude's `remote-subagent-tail` has no codex+ counterpart — follow-up).- **/loop, /schedule & /cron node** (agents in `RECURRING_CAPABLE`) — detected from the **tools**the agent invokes (robust; users often phrase it in natural language so the prompt rarely startswith the slash): `PreToolUse` for `Skill` (skill ∈ loop/schedule/cron), `CronCreate` (→ cron,diff --git a/src/core/agents/hook-verified-parity.test.ts b/src/core/agents/hook-verified-parity.test.tsindex c2f080178..8fc296d2a 100644--- a/src/core/agents/hook-verified-parity.test.ts+++ b/src/core/agents/hook-verified-parity.test.ts@@ -157,6 +157,23 @@ describe('both shells register a 4-arg raw listener', () => {expect(branches(code('src/main/index.ts'))).toBe(branches(code('src/server/agent-status.ts')))})+ // Same one-shell-drift rule, next instance: the codex subagent branch (spawn_agent fan-out).+ // Both raw listeners must (a) tail the child rollout off SubagentStart via trackFile and+ // (b) skip the context-meter track for agent_id-tagged child events — a shell missing (a)+ // silently has no live activity, and one missing (b) re-points the parent's meter at the+ // child's rollout (SubagentStart carries the parent session_id with the CHILD's path).+ it('both raw listeners carry the codex subagent branch (trackFile + agent_id gate)', () => {+ for (const rel of ['src/main/index.ts', 'src/server/agent-status.ts']) {+ const src = code(rel)+ expect(src, `${rel} misses the SubagentStart trackFile branch`).toMatch(+ /SubagentStart'\s*\)\s*\{\s*subagentTail\.trackFile/+ )+ expect(src, `${rel} misses the agent_id child-event gate`).toMatch(+ /agentId === 'codex' && p\.agent_id/+ )+ }+ })+it('the normalized listener is where verified travels, and it is the only gate input', () => {// Both shells subscribe to the SAME src/core hook server, so this one line is what carries the// flag to the src/core mirror on both of them. A refactor that drops it here would leave thediff --git a/src/core/agents/hooks/codex-trust.ts b/src/core/agents/hooks/codex-trust.tsindex bb88427a3..5756bf771 100644--- a/src/core/agents/hooks/codex-trust.ts+++ b/src/core/agents/hooks/codex-trust.ts@@ -38,6 +38,8 @@ export type CodexEventLabel =| 'session_start'| 'user_prompt_submit'| 'stop'+ | 'subagent_start'+ | 'subagent_stop'export type CodexTrustEntry = {/** Path on disk to the hooks.json that declares the hook (the "key_source"). */diff --git a/src/core/agents/hooks/codex.test.ts b/src/core/agents/hooks/codex.test.tsindex c0bb001dd..653736231 100644--- a/src/core/agents/hooks/codex.test.ts+++ b/src/core/agents/hooks/codex.test.ts@@ -18,7 +18,7 @@ describe('buildCodexHooksAndTrust', () => {expect(buildCodexHooksAndTrust(null, 'cmd', '/h/hooks.json')).toBeNull()})- it('appends the managed handler to all six events + emits one trust entry per event', () => {+ it('appends the managed handler to all eight events + emits one trust entry per event', () => {const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh')const built = buildCodexHooksAndTrust({}, command, '/home/u/.codex/hooks.json')expect(built).not.toBeNull()@@ -82,7 +82,7 @@ describe('buildCodexHooksAndTrust', () => {expect(built.config.hooks?.PreCompact).toBeUndefined()})- // GOLDEN: these six hashes were read from a LIVE codex config.toml on a host where the status+ // GOLDEN: the first six hashes were read from a LIVE codex config.toml on a host where the status// hooks fire correctly (codex-cli 0.114.0). Locking them guards the exact JSON canonicalization// codex hashes against — any drift here silently breaks every codex status badge.it('matches the byte-exact trust hashes codex accepts in the field', () => {@@ -95,7 +95,18 @@ describe('buildCodexHooksAndTrust', () => {pre_tool_use: 'sha256:4518d886ca33ee61eba15a15e6348df03891a37f496a9a29a7eaae8b05623eed',permission_request: 'sha256:c15e31e91f0ad513f1dd37bbbf5e1263cb0ba7a819b16dd60bc85f576d5bcb85',post_tool_use: 'sha256:ec6d59bff150ef00c30f7ef63abdf3c5a839a12f98ebe5dc542ecdfcc2da9d2f',- stop: 'sha256:bd559fa7db307ab42dac8fa42b49c46b3daa50f944adad2f0a97140a70c70081'+ stop: 'sha256:bd559fa7db307ab42dac8fa42b49c46b3daa50f944adad2f0a97140a70c70081',+ // The subagent pair was verified live differently: a capture home whose trust entries were+ // computed by this same algorithm had codex-cli 0.146.0 FIRE SubagentStart/SubagentStop+ // (spawn_agent measurement run, 2026-08-24) — i.e. codex accepted hashes of this shape for+ // these labels. The values below pin the canonicalization for this command string.+ subagent_start: 'sha256:9034d6329983b581fc9f996344766d6129321c5c33369a79c9971aa8879d3d5f',+ subagent_stop: 'sha256:88c207ae65d9d016967fce19b01735b5700f827cbfdb48692e42305f7427f0b6'})})++ it('subscribes the subagent pair (spawn_agent fan-out) with snake_case labels', () => {+ expect(CODEX_EVENTS).toContain('SubagentStart')+ expect(CODEX_EVENTS).toContain('SubagentStop')+ })})diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex fcd45e7de..d3e709139 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -38,13 +38,19 @@ import {type CodexTrustEntry} from './codex-trust'-// Confirmed codex event set.+// Confirmed codex event set. SubagentStart/SubagentStop drive the subagent fan-out cards+// (codex's spawn_agent collaboration tool) — measured live on codex-cli 0.146.0: SubagentStart+// carries `agent_id`/`agent_type` and its `transcript_path` is the CHILD's rollout; SubagentStop+// adds `agent_transcript_path` + `last_assistant_message`. Older codex versions skip hook event+// names they don't recognize, so subscribing these on a pre-subagent CLI is inert, not an error.export const CODEX_EVENTS = ['SessionStart','UserPromptSubmit','PreToolUse','PermissionRequest','PostToolUse',+ 'SubagentStart',+ 'SubagentStop','Stop'] as const@@ -58,6 +64,8 @@ export const CODEX_EVENT_LABEL: Record<(typeof CODEX_EVENTS)[number], CodexEventPreToolUse: 'pre_tool_use',PermissionRequest: 'permission_request',PostToolUse: 'post_tool_use',+ SubagentStart: 'subagent_start',+ SubagentStop: 'subagent_stop',Stop: 'stop'}diff --git a/src/core/codex-subagent-format.test.ts b/src/core/codex-subagent-format.test.tsnew file mode 100644index 000000000..3e4b5aa44--- /dev/null+++ b/src/core/codex-subagent-format.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it } from 'vitest'+import { createCodexSubagentFormatter } from './codex-subagent-format'++// Every line shape below is from the LIVE spawn_agent capture on codex-cli 0.146.0+// (2026-08-24, single + parallel + nested runs), trimmed to the fields the formatter reads.+const j = (o: unknown): string => JSON.stringify(o)++const META = j({ type: 'inter_agent_communication_metadata', payload: { trigger_turn: true } })+const NEW_TASK = j({+ type: 'response_item',+ payload: {+ type: 'agent_message',+ author: '/root/agent_b',+ recipient: '/root/agent_b/nested_echo',+ content: [+ { type: 'input_text', text: 'Message Type: NEW_TASK\nTask name: /root/agent_b/nested_echo\nSender: /root/agent_b\nPayload:\n' },+ { type: 'encrypted_content', encrypted_content: 'gAAAAABqjFoIEMsnnu…' }+ ]+ }+})+const PROSE = j({+ type: 'event_msg',+ payload: { type: 'agent_message', message: 'I’m running the exact command now.', phase: 'commentary' }+})+const TOOL = j({+ type: 'response_item',+ payload: { type: 'custom_tool_call', name: 'exec', input: 'echo hello-from-subagent', call_id: 'call_1' }+})+const TOOL_OUT = j({+ type: 'response_item',+ payload: {+ type: 'custom_tool_call_output',+ call_id: 'call_1',+ output: [+ { type: 'input_text', text: 'Script completed\nWall time 0.2 seconds\nOutput:\n' },+ { type: 'input_text', text: 'hello-from-subagent\n' }+ ]+ }+})+const FN_CALL = j({+ type: 'response_item',+ payload: {+ type: 'function_call',+ name: 'spawn_agent',+ namespace: 'collaboration',+ arguments: '{"task_name":"nested_echo","fork_turns":"all","message":"gAAAAABqjFoIEMsn…"}'+ }+})+const FN_OUT = j({+ type: 'response_item',+ payload: { type: 'function_call_output', output: '{"task_name":"/root/agent_b/nested_echo"}' }+})+const NESTED = j({+ type: 'event_msg',+ payload: {+ type: 'sub_agent_activity',+ event_id: 'call_X',+ agent_thread_id: '01a0343f-8ceb-7141-8d24-978ddea92bef',+ agent_path: '/root/agent_a',+ kind: 'started'+ }+})+// Fork-replay lines that precede the task delivery — the PARENT's context, never the child's work.+const REPLAY_META = j({ type: 'session_meta', payload: {} })+const REPLAY_PROSE = j({+ type: 'event_msg',+ payload: { type: 'agent_message', message: 'I’ll delegate exactly that shell command…' }+})+const REPLAY_USER = j({ type: 'event_msg', payload: { type: 'user_message', message: 'Please use spawn_agent…' } })+const TOKENS = j({ type: 'event_msg', payload: { type: 'token_count', info: {} } })++describe('createCodexSubagentFormatter', () => {+ it('suppresses the fork-replay prefix until the task delivery, then streams the child work', () => {+ const fmt = createCodexSubagentFormatter()+ const out = fmt([REPLAY_META, REPLAY_PROSE, REPLAY_USER, META, NEW_TASK, PROSE, TOOL, TOOL_OUT].join('\n'))+ expect(out).toBe(+ [+ 'Task: /root/agent_b/nested_echo',+ 'I’m running the exact command now.',+ '$ exec echo hello-from-subagent',+ ' ↳ Script completed … (+3 lines)'+ ].join('\n')+ )+ // Nothing replayed leaked through.+ expect(out).not.toContain('delegate')+ })++ it('the gate is stateful ACROSS chunks — replay in chunk 1, work in chunk 2', () => {+ const fmt = createCodexSubagentFormatter()+ expect(fmt([REPLAY_PROSE, REPLAY_USER].join('\n'))).toBe('')+ expect(fmt(META + '\n')).toBe('')+ expect(fmt(PROSE + '\n')).toBe('I’m running the exact command now.')+ })++ it('each formatter instance gates independently (two concurrent subagents)', () => {+ const a = createCodexSubagentFormatter()+ const b = createCodexSubagentFormatter()+ a(META + '\n')+ // b never saw its gate — it must still suppress.+ expect(b(PROSE + '\n')).toBe('')+ expect(a(PROSE + '\n')).toBe('I’m running the exact command now.')+ })++ it('the NEW_TASK message itself opens the gate when no metadata line precedes it', () => {+ const fmt = createCodexSubagentFormatter()+ expect(fmt([REPLAY_PROSE, NEW_TASK, PROSE].join('\n'))).toBe(+ ['Task: /root/agent_b/nested_echo', 'I’m running the exact command now.'].join('\n')+ )+ })++ it('formats function_call with a readable arg and never the encrypted message', () => {+ const fmt = createCodexSubagentFormatter()+ const out = fmt([META, FN_CALL, FN_OUT].join('\n'))+ expect(out).toContain('$ spawn_agent nested_echo')+ expect(out).not.toContain('gAAAA')+ expect(out).toContain('↳ {"task_name":"/root/agent_b/nested_echo"}')+ })++ it('a nested spawn observed from this child is one ↪ line', () => {+ const fmt = createCodexSubagentFormatter()+ expect(fmt([META, NESTED].join('\n'))).toBe('↪ spawned /root/agent_a')+ })++ it('skips bookkeeping lines and survives torn/non-JSON input', () => {+ const fmt = createCodexSubagentFormatter()+ expect(fmt([META, TOKENS, '{not json', ''].join('\n'))).toBe('')+ })+})diff --git a/src/core/codex-subagent-format.ts b/src/core/codex-subagent-format.tsnew file mode 100644index 000000000..cef5e9345--- /dev/null+++ b/src/core/codex-subagent-format.ts@@ -0,0 +1,135 @@+// Formats a codex subagent's rollout into the activity-log text streamed to its fan-out card —+// the codex counterpart of subagent-tail's claude `formatSubagentChunk`, fed to the tail via+// `trackFile`'s per-entry formatter. Every shape here was measured live on codex-cli 0.146.0+// (spawn_agent single, parallel and nested captures — see PR #401 discussion).+//+// The formatter is STATEFUL, one instance per tracked subagent: a spawn_agent child is a FORK of+// the parent thread (`fork_turns: "all"`), so its rollout OPENS with a replay of the parent's+// context — the parent's session_meta, prior messages, even the parent's own commentary lines.+// Streaming that replay would fill the card with the parent's words before the child has done+// anything. The child's real work begins at the task delivery, marked by an+// `inter_agent_communication_metadata` line ({"trigger_turn":true}) immediately followed by the+// NEW_TASK `response_item/agent_message` — everything before whichever of those appears first is+// suppressed. If neither ever appears (an unforked spawn mode we have not observed), the card+// shows no activity rather than the wrong session's: same degrade-to-nothing rule as the meters.+//+// The task text itself is NOT available: spawn_agent's `message` is encrypted end-to-end (a+// Fernet blob in the tool_input AND in the NEW_TASK payload's `encrypted_content`). The readable+// part is the NEW_TASK header ("Message Type: … Task name: /root/agent_b/nested_echo …"), which+// is collapsed to a `Task: <name>` line.++interface RolloutLine {+ type?: string+ payload?: {+ type?: string+ // event_msg/agent_message+ message?: string+ // event_msg/sub_agent_activity+ kind?: string+ agent_path?: string+ // response_item/agent_message | custom_tool_call_output+ content?: unknown+ output?: unknown+ // response_item/function_call | custom_tool_call+ name?: string+ arguments?: string+ input?: unknown+ }+}++function textItems(content: unknown): string {+ if (!Array.isArray(content)) return ''+ return content+ .map((c) => (c && typeof c === 'object' && 'text' in c ? String((c as { text?: unknown }).text ?? '') : ''))+ .filter(Boolean)+ .join('')+}++function snippet(s: string, max = 80): string {+ return s.replace(/\s+/g, ' ').trim().slice(0, max)+}++// One-line result summary, same look as claude's subagent activity log.+function summarize(raw: string): string {+ const r = raw.trim()+ if (!r) return ''+ const lines = r.split('\n')+ const first = (lines.find((l) => l.trim()) ?? '').trim().slice(0, 100)+ const extra = lines.length > 1 ? ` … (+${lines.length - 1} lines)` : ''+ return ` ↳ ${first}${extra}`+}++// `arguments` is a JSON string. Prefer the one human-relevant field over dumping the object —+// for spawn_agent that is task_name (`message` is an encrypted blob, never show it).+function argSummary(args: string | undefined): string {+ if (!args) return ''+ try {+ const a = JSON.parse(args) as Record<string, unknown>+ if (typeof a.task_name === 'string') return a.task_name+ if (typeof a.command === 'string') return snippet(a.command)+ const entries = Object.entries(a).filter(([, v]) => typeof v !== 'string' || (v as string).length <= 120)+ if (!entries.length) return ''+ return snippet(entries.map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`).join(' '))+ } catch {+ return snippet(args)+ }+}++export function createCodexSubagentFormatter(): (text: string) => string {+ // False until the fork-replay prefix has passed (see header comment).+ let live = false++ const formatLine = (line: string): string => {+ let o: RolloutLine+ try {+ o = JSON.parse(line)+ } catch {+ return ''+ }+ const p = o.payload ?? {}+ if (o.type === 'inter_agent_communication_metadata') {+ live = true+ return ''+ }+ // Inter-agent traffic (NEW_TASK delivery and siblings). Its arrival also ends the replay:+ // in the captures it lands right after the metadata line, but gate on it independently so a+ // rollout that skips the metadata still starts streaming here.+ if (o.type === 'response_item' && p.type === 'agent_message') {+ live = true+ const text = textItems(p.content)+ const task = /Task name:\s*(\S+)/.exec(text)+ if (task) return `Task: ${task[1]}`+ return text.trim()+ }+ if (!live) return ''+ if (o.type === 'event_msg') {+ // The child's own prose (commentary + final answer). The replayed parent prose upstream of+ // the gate never reaches here.+ if (p.type === 'agent_message') return (p.message ?? '').trim()+ // A NESTED spawn observed from this child — one line, the nested card carries the rest.+ if (p.type === 'sub_agent_activity' && p.kind === 'started' && p.agent_path) {+ return `↪ spawned ${p.agent_path}`+ }+ return ''+ }+ if (o.type === 'response_item') {+ if (p.type === 'function_call' && p.name) {+ const arg = argSummary(p.arguments)+ return `$ ${p.name}${arg ? ` ${arg}` : ''}`+ }+ if (p.type === 'custom_tool_call' && p.name) {+ const arg = typeof p.input === 'string' ? snippet(p.input) : ''+ return `$ ${p.name}${arg ? ` ${arg}` : ''}`+ }+ if (p.type === 'custom_tool_call_output') return summarize(textItems(p.output))+ if (p.type === 'function_call_output') {+ return summarize(typeof p.output === 'string' ? p.output : '')+ }+ return ''+ }+ return ''+ }++ return (text: string): string =>+ text.split('\n').filter(Boolean).map(formatLine).filter(Boolean).join('\n')+}diff --git a/src/core/subagent-tail.test.ts b/src/core/subagent-tail.test.tsindex 8b1f01b90..4acc21b2b 100644--- a/src/core/subagent-tail.test.ts+++ b/src/core/subagent-tail.test.ts@@ -119,6 +119,80 @@ describe('createSubagentTail', () => {})})+describe('trackFile (codex leg: pre-resolved file + per-entry formatter)', () => {+ it('tails the given file directly with the injected stateful formatter', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-file-'))+ const file = path.join(dir, 'rollout-child.jsonl')+ // A stateful formatter (mirrors the codex fork-replay gate): suppress until 'GATE'.+ const newFormatter = () => {+ let live = false+ return (text: string): string =>+ text+ .split('\n')+ .filter(Boolean)+ .map((l) => {+ if (l === 'GATE') {+ live = true+ return ''+ }+ return live ? l : ''+ })+ .filter(Boolean)+ .join('\n')+ }+ fs.writeFileSync(file, 'replayed-noise\nGATE\nchild-work-1\n')+ const send = vi.fn()+ const tail = createSubagentTail(send)+ tail.trackFile('agent-1', file, newFormatter)+ await wait(600)+ fs.appendFileSync(file, 'child-work-2\n')+ await wait(600)+ const out = streamed(send)+ expect(out).toContain('child-work-1')+ expect(out).toContain('child-work-2') // formatter state survived across chunks+ expect(out).not.toContain('replayed-noise')+ tail.finish('agent-1')+ })++ it('two trackFile entries do not share formatter state', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-file2-'))+ const a = path.join(dir, 'a.jsonl')+ const b = path.join(dir, 'b.jsonl')+ const newFormatter = () => {+ let live = false+ return (text: string): string =>+ text+ .split('\n')+ .filter(Boolean)+ .map((l) => (l === 'GATE' ? ((live = true), '') : live ? l : ''))+ .filter(Boolean)+ .join('\n')+ }+ fs.writeFileSync(a, 'GATE\nfrom-a\n')+ fs.writeFileSync(b, 'from-b-before-gate\n')+ const send = vi.fn()+ const tail = createSubagentTail(send)+ tail.trackFile('a', a, newFormatter)+ tail.trackFile('b', b, newFormatter)+ await wait(600)+ const byId = new Map<string, string>()+ for (const c of send.mock.calls) {+ const { toolUseId, chunk } = c[0] as { toolUseId: string; chunk: string }+ byId.set(toolUseId, (byId.get(toolUseId) ?? '') + chunk)+ }+ expect(byId.get('a')).toContain('from-a')+ expect(byId.get('b')).toBeUndefined() // b's own gate never arrived+ tail.finish('a')+ tail.finish('b')+ })++ it('a missing filePath is ignored (no entry, no timer leak)', () => {+ const tail = createSubagentTail(vi.fn())+ tail.trackFile('x', undefined)+ tail.finish('x') // must be a no-op, not a throw+ })+})+describe('subagent-tail read cap', () => {it('reads at most SUBAGENT_READ_CAP bytes per tick and continues next tick', async () => {expect(SUBAGENT_READ_CAP).toBe(1024 * 1024)diff --git a/src/core/subagent-tail.ts b/src/core/subagent-tail.tsindex 39020ac14..9688d3766 100644--- a/src/core/subagent-tail.ts+++ b/src/core/subagent-tail.ts@@ -28,6 +28,12 @@ interface Tracked {* this the torn line's halves each fail JSON.parse and the whole line is silently lost.*/carry?: Buffer | null+ /**+ * Per-entry chunk formatter (trackFile's). Deliberately per ENTRY, not per tail instance:+ * a codex formatter is STATEFUL (it suppresses the fork-replay prefix of the child rollout),+ * so two concurrent subagents sharing one closure would gate each other's output.+ */+ fmt?: (text: string) => string}function textOf(content: unknown): string {@@ -134,6 +140,17 @@ export function splitCompleteLines(data: Buffer): { text: string; carry: Bufferexport interface SubagentTail {track(toolUseId: string, transcriptPath: string | undefined): void+ /**+ * Tail an already-resolved transcript FILE — no meta-dir matching, no claude formatting.+ * The codex leg: SubagentStart hands us the child rollout's path directly, and `newFormatter`+ * builds that entry's (stateful) line formatter. Same 400ms tick, cap, carry and finish+ * semantics as track().+ */+ trackFile(+ toolUseId: string,+ filePath: string | undefined,+ newFormatter?: () => (text: string) => string+ ): voidfinish(toolUseId: string): void}@@ -193,7 +210,7 @@ export function createSubagentTail(const data = e.carry?.length ? Buffer.concat([e.carry, buf]) : bufconst { text, carry } = splitCompleteLines(data)e.carry = carry- const out = formatSubagentChunk(text)+ const out = (e.fmt ?? formatSubagentChunk)(text)if (out) emit(toolUseId, out + '\n')} catch {// file may not exist yet / transient read error@@ -217,12 +234,22 @@ export function createSubagentTail(tracked.set(toolUseId, { dir, file: null, offset: 0 })if (!timer) timer = setInterval(tick, 400) // only runs while subagents are active},+ trackFile(toolUseId, filePath, newFormatter) {+ if (!filePath || tracked.has(toolUseId)) return+ tracked.set(toolUseId, {+ dir: path.dirname(filePath),+ file: filePath,+ offset: 0,+ fmt: newFormatter?.()+ })+ if (!timer) timer = setInterval(tick, 400)+ },finish(toolUseId) {// The file is complete now, so a held-back carry is a real final line that just lacks// its trailing newline — flush it after the final read instead of dropping it.const flushCarry = (e: Tracked): void => {if (!e.carry?.length) return- const out = formatSubagentChunk(e.carry.toString('utf-8'))+ const out = (e.fmt ?? formatSubagentChunk)(e.carry.toString('utf-8'))e.carry = nullif (out) emit(toolUseId, out + '\n')}diff --git a/src/main/index.ts b/src/main/index.tsindex 598478f64..69cd84334 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -181,6 +181,7 @@ import { createSubagentTail } from '../core/subagent-tail'import { createContextTail, type TaskNotification } from '../core/context-tail'import { geminiContextParse } from '../core/gemini-session'import { codexContextParse } from '../core/codex-session'+import { createCodexSubagentFormatter } from '../core/codex-subagent-format'import { codexHome } from '../core/usage/codex-usage'import { grokRawFields, isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'import { grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'@@ -2096,8 +2097,10 @@ app.whenReady().then(async () => {// would mean changing `ContextTail.track(sessionId, path)` and the four call sites that depend on// it. The poller (offset reads, torn-line carry, change-gated push) is written once in// createContextTail; only the token keys differ, so only `parse` differs. Neither gets- // onTaskNotification/onToolResult: both are claude transcript features (subagent cards, the- // declined-ask rescue), and neither agent is in SUBAGENT_CAPABLE.+ // onTaskNotification/onToolResult: both are claude transcript features (the task-notification+ // sniff exists because claude's hooks never send the async subagent's real end; codex's+ // SubagentStop hook IS the real end, so its subagent cards need no transcript sniffing —+ // and the declined-ask rescue is claude-only too).const geminiContextTail = createContextTail(pushContextUpdate, { parse: geminiContextParse })// Hand the gemini session-name reader its path authority (declared above the handlers that use// it, assigned here where the tail exists).@@ -2615,14 +2618,45 @@ app.whenReady().then(async () => {// jailed by the same `safeTranscriptPath` claude uses (widened to those two agents' transcript// roots), because a forged POST could otherwise aim a file read at an arbitrary local path.if (agentId === 'gemini' || agentId === 'codex') {- const p = payload as { session_id?: string; transcript_path?: string; hook_event_name?: string }+ const p = payload as {+ session_id?: string+ transcript_path?: string+ hook_event_name?: string+ agent_id?: string+ }// A REMOTE (SSH) node's transcript lives on the HOST, and these tails read the LOCAL disk —// a host path like `~/.gemini/tmp/…` clears the local jail, so without this we would meter// whatever same-named file happens to exist on THIS machine. Remote meters for these agents// are out of scope (remote-context-tail.ts is that path), so skip rather than report the// wrong machine's numbers. The Server Edition needs no counterpart: it has no SSH projects,// which is why its copy of this branch is otherwise identical but lacks these two lines.+ // (A remote codex node's subagent CARDS still work — normalize is machine-agnostic — it is+ // only the live-activity tail that has no remote leg yet.)if (nodeId && ptyManager.sshRemoteForNode(nodeId)) return+ // Codex subagent events (spawn_agent), BEFORE the meter track: every agent_id-tagged event+ // carries the PARENT's session_id with the CHILD's rollout as transcript_path (measured,+ // codex-cli 0.146.0 — SubagentStart and the child's own tool events alike), so falling+ // through would re-point the parent's context meter at the child's rollout. The tail is the+ // shared subagentTail instance: releaseNodeTails/SessionEnd cleanup then covers codex ids+ // through the same nodeSubagents bookkeeping claude uses.+ if (agentId === 'codex' && p.agent_id) {+ if (p.hook_event_name === 'SubagentStart') {+ subagentTail.trackFile(+ p.agent_id,+ safeTranscriptPath(p.transcript_path),+ createCodexSubagentFormatter+ )+ if (nodeId) {+ const set = nodeSubagents.get(nodeId) ?? new Set<string>()+ set.add(p.agent_id)+ nodeSubagents.set(nodeId, set)+ }+ } else if (p.hook_event_name === 'SubagentStop') {+ subagentTail.finish(p.agent_id)+ if (nodeId) nodeSubagents.get(nodeId)?.delete(p.agent_id)+ }+ return+ }const transcriptPath = safeTranscriptPath(p.transcript_path)const tail = agentId === 'gemini' ? geminiContextTail : codexContextTailif (p.session_id && transcriptPath) tail.track(p.session_id, transcriptPath)diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.tsindex 23ca97adc..c782dc737 100644--- a/src/server/agent-status.test.ts+++ b/src/server/agent-status.test.ts@@ -48,6 +48,7 @@ function recTail() {return {tail: {track: (...args: unknown[]) => calls.push({ m: 'track', args }),+ trackFile: (...args: unknown[]) => calls.push({ m: 'trackFile', args }),finish: (...args: unknown[]) => calls.push({ m: 'finish', args }),untrack: (...args: unknown[]) => calls.push({ m: 'untrack', args })},@@ -153,6 +154,78 @@ describe('wireAgentStatus', () => {expect(sub.calls).toEqual([])})+ // Codex subagents (spawn_agent): payload shapes from the live codex-cli 0.146.0 capture —+ // SubagentStart's transcript_path is the CHILD's rollout, keyed by agent_id.+ it('codex SubagentStart tails the child rollout via trackFile, SubagentStop finishes it', () => {+ const fh = fakeHooks()+ const sub = recTail()+ wireAgentStatus(platform, { hooks: fh.hooks as never, subagentTail: sub.tail as never })+ const childPath = path.join(os.homedir(), '.codex', 'sessions', '2026', '08', '24', 'rollout-child.jsonl')+ fh.fireRaw('codex', 'n1', {+ hook_event_name: 'SubagentStart',+ session_id: 'parent-s',+ transcript_path: childPath,+ agent_id: 'agent-1',+ agent_type: 'default'+ })+ const tf = sub.calls.find((c) => c.m === 'trackFile')+ expect(tf?.args[0]).toBe('agent-1')+ expect(tf?.args[1]).toBe(path.resolve(childPath))+ fh.fireRaw('codex', 'n1', {+ hook_event_name: 'SubagentStop',+ session_id: 'parent-s',+ agent_id: 'agent-1',+ agent_type: 'default',+ last_assistant_message: 'done'+ })+ expect(sub.calls.some((c) => c.m === 'finish' && c.args[0] === 'agent-1')).toBe(true)+ })++ it('a codex SubagentStart outside the transcript jail does not tail anything', () => {+ const fh = fakeHooks()+ const sub = recTail()+ wireAgentStatus(platform, { hooks: fh.hooks as never, subagentTail: sub.tail as never })+ fh.fireRaw('codex', 'n1', {+ hook_event_name: 'SubagentStart',+ session_id: 'parent-s',+ transcript_path: path.join(os.homedir(), '.ssh', 'id_rsa'),+ agent_id: 'agent-evil'+ })+ const tf = sub.calls.find((c) => c.m === 'trackFile')+ expect(tf?.args[1]).toBeUndefined() // jailed → tail ignores it+ })++ it("a codex child's agent_id-tagged tool event neither tracks a subagent nor throws", () => {+ const fh = fakeHooks()+ const sub = recTail()+ wireAgentStatus(platform, { hooks: fh.hooks as never, subagentTail: sub.tail as never })+ fh.fireRaw('codex', 'n1', {+ hook_event_name: 'PreToolUse',+ session_id: 'parent-s',+ agent_id: 'agent-1',+ agent_type: 'default',+ tool_name: 'Bash',+ tool_input: { command: 'echo hi' },+ transcript_path: path.join(os.homedir(), '.codex', 'sessions', 'child.jsonl')+ })+ expect(sub.calls).toEqual([])+ })++ it('codex SubagentStop finish is covered by ptyDestroy cleanup too', () => {+ const fh = fakeHooks()+ const sub = recTail()+ wireAgentStatus(platform, { hooks: fh.hooks as never, subagentTail: sub.tail as never })+ const childPath = path.join(os.homedir(), '.codex', 'sessions', 'rollout-child.jsonl')+ fh.fireRaw('codex', 'n1', {+ hook_event_name: 'SubagentStart',+ session_id: 'parent-s',+ transcript_path: childPath,+ agent_id: 'agent-1'+ })+ platform.cast(platform.attach({ sendText: () => {}, sendBinary: () => {} }), IPC.ptyDestroy, ['n1'])+ expect(sub.calls.some((c) => c.m === 'finish' && c.args[0] === 'agent-1')).toBe(true)+ })+it('ptyDestroy untracks the node context tail and finishes its subagents, clearing the maps', () => {const fh = fakeHooks()const sub = recTail()diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex fda130412..16c66be94 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -17,6 +17,7 @@ import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'import { createContextTail, type ContextTail, type TaskNotification } from '../core/context-tail'import { geminiContextParse } from '../core/gemini-session'import { codexContextParse } from '../core/codex-session'+import { createCodexSubagentFormatter } from '../core/codex-subagent-format'import { codexHome } from '../core/usage/codex-usage'import { setNodeTranscript } from '../core/context-link'import { isSafeLocalTranscriptPath } from '../core/claude-accounts-core'@@ -135,8 +136,10 @@ export function wireAgentStatus(// would mean changing `ContextTail.track(sessionId, path)` and the four call sites that depend on// it. The poller (offset reads, torn-line carry, change-gated push) is written once in// createContextTail; only the token keys differ, so only `parse` differs. Neither gets- // onTaskNotification/onToolResult: both are claude transcript features (subagent cards, the- // declined-ask rescue), and neither agent is in SUBAGENT_CAPABLE.+ // onTaskNotification/onToolResult: both are claude transcript features (the task-notification+ // sniff exists because claude's hooks never send the async subagent's real end; codex's+ // SubagentStop hook IS the real end, so its subagent cards need no transcript sniffing —+ // and the declined-ask rescue is claude-only too).const geminiContextTail = createContextTail(pushContextUpdate, { parse: geminiContextParse })const codexContextTail = createContextTail(pushContextUpdate, { parse: codexContextParse })@@ -215,7 +218,35 @@ export function wireAgentStatus(// on the host; the server has no SSH-project manager (see the module header), so every node it// serves is local and there is nothing to skip.if (agentId === 'gemini' || agentId === 'codex') {- const p = payload as { session_id?: string; transcript_path?: string; hook_event_name?: string }+ const p = payload as {+ session_id?: string+ transcript_path?: string+ hook_event_name?: string+ agent_id?: string+ }+ // Codex subagent events (spawn_agent), BEFORE the meter track — same rule as the desktop:+ // every agent_id-tagged event carries the PARENT's session_id with the CHILD's rollout as+ // transcript_path (measured, codex-cli 0.146.0), so falling through would re-point the+ // parent's context meter at the child's rollout. The shared subagentTail instance means the+ // existing nodeSubagents cleanup paths cover codex ids too.+ if (agentId === 'codex' && p.agent_id) {+ if (p.hook_event_name === 'SubagentStart') {+ subagentTail.trackFile(+ p.agent_id,+ safeTranscriptPath(p.transcript_path),+ createCodexSubagentFormatter+ )+ if (nodeId) {+ const set = nodeSubagents.get(nodeId) ?? new Set<string>()+ set.add(p.agent_id)+ nodeSubagents.set(nodeId, set)+ }+ } else if (p.hook_event_name === 'SubagentStop') {+ subagentTail.finish(p.agent_id)+ if (nodeId) nodeSubagents.get(nodeId)?.delete(p.agent_id)+ }+ return+ }const transcriptPath = safeTranscriptPath(p.transcript_path)const tail = agentId === 'gemini' ? geminiContextTail : codexContextTailif (p.session_id && transcriptPath) tail.track(p.session_id, transcriptPath)diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 3bed6712d..9fe7e5333 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -125,7 +125,9 @@ export const SESSION_ID_CAPABLE = ['claude', 'copilot'] as const// binary and current official reference accept `--session-id=<uuid>`, so it does not borrow an// unrelated Claude probe result. Custom agents resolve through their declared base harness.export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot'] as const-export const SUBAGENT_CAPABLE = ['claude'] as const+// claude: Task/Agent tool via hooks (tool_use_id-keyed). codex: spawn_agent collaboration via its+// native SubagentStart/SubagentStop hooks (agent_id-keyed), measured on codex-cli 0.146.0.+export const SUBAGENT_CAPABLE = ['claude', 'codex'] as constexport const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cronexport const BRANCH_CAPABLE = ['claude'] as constexport const CONTEXT_LINK_CAPABLE = ['claude', 'codex', 'gemini', 'opencode'] as constdiff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.tsindex 91bc47120..650905b87 100644--- a/src/shared/agents/normalize.test.ts+++ b/src/shared/agents/normalize.test.ts@@ -405,3 +405,84 @@ describe('normalizeCodex — request_user_input (ask-the-user)', () => {expect(e?.awaitingInput).toBeFalsy()})})++// Payload shapes below are the LIVE capture from codex-cli 0.146.0 (spawn_agent measurement run,+// 2026-08-24): parent session_id + the child's agent_id/agent_type; SubagentStart's+// transcript_path is the CHILD's rollout; a child's own tool events carry agent_id too.+describe('normalizeCodex — subagents (spawn_agent)', () => {+ function cenv(payload: Record<string, unknown>): RawHookEnvelope {+ return { nodeId: 'n1', agentId: 'codex', payload }+ }++ it('SubagentStart → subagent-start keyed by agent_id, typed by agent_type', () => {+ const e = normalizeCodex(+ cenv({+ hook_event_name: 'SubagentStart',+ session_id: '01a0343d-d249-73e2-a462-e824df60d95c',+ turn_id: '01a0343d-ef3a-7840-b6ed-683b7b024519',+ transcript_path: '/home/u/.codex/sessions/2026/08/24/rollout-child.jsonl',+ agent_id: '01a0343d-ef01-7700-b32f-c32ee1fc21f9',+ agent_type: 'default'+ })+ )+ expect(e).toMatchObject({+ kind: 'subagent-start',+ toolUseId: '01a0343d-ef01-7700-b32f-c32ee1fc21f9',+ subagentType: 'default',+ sessionId: '01a0343d-d249-73e2-a462-e824df60d95c'+ })+ // The spawn message is encrypted end-to-end — there is no task text to label the card with.+ expect(e?.taskLabel).toBeUndefined()+ })++ it('SubagentStop → subagent-end carrying the child final answer as result', () => {+ const e = normalizeCodex(+ cenv({+ hook_event_name: 'SubagentStop',+ session_id: '01a0343d-d249-73e2-a462-e824df60d95c',+ agent_id: '01a0343d-ef01-7700-b32f-c32ee1fc21f9',+ agent_type: 'default',+ agent_transcript_path: '/home/u/.codex/sessions/2026/08/24/rollout-child.jsonl',+ last_assistant_message: 'The command output was:\n\n`hello-from-subagent`'+ })+ )+ expect(e).toMatchObject({+ kind: 'subagent-end',+ toolUseId: '01a0343d-ef01-7700-b32f-c32ee1fc21f9',+ result: 'The command output was:\n\n`hello-from-subagent`'+ })+ })++ // After an async spawn the parent's turn can end while the child still runs; a child Bash+ // event mapping to 'working' would flip the finished parent back to RUNNING with nothing to+ // clear it. Child activity reaches the card via the rollout tail, not the state machine.+ it("a child's own tool events (agent_id-tagged) do not drive the parent state", () => {+ for (const ev of ['PreToolUse', 'PostToolUse']) {+ const e = normalizeCodex(+ cenv({+ hook_event_name: ev,+ session_id: '01a0343d-d249-73e2-a462-e824df60d95c',+ agent_id: '01a0343d-ef01-7700-b32f-c32ee1fc21f9',+ agent_type: 'default',+ tool_name: 'Bash',+ tool_input: { command: 'echo hello-from-subagent' }+ })+ )+ expect(e).toBeNull()+ }+ })++ // The PARENT's spawn/wait tool calls carry no agent_id and stay ordinary working events —+ // the card is keyed off SubagentStart, never off the spawn tool call.+ it('the parent spawn_agent tool call remains a plain working event', () => {+ const e = normalizeCodex(+ cenv({+ hook_event_name: 'PreToolUse',+ session_id: 's1',+ tool_name: 'collaborationspawn_agent',+ tool_input: { task_name: 'echo_check', fork_turns: 'all', message: 'gAAAA…' }+ })+ )+ expect(e).toMatchObject({ kind: 'state', state: 'working' })+ })+})diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex e51995538..db8b3325d 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -296,6 +296,13 @@ interface CodexPayload {prompt?: stringtool_name?: stringtool_input?: { prompt?: string; question?: string; questions?: { question?: string }[] }+ // Subagent (spawn_agent collaboration) fields, measured on codex-cli 0.146.0:+ // SubagentStart/SubagentStop carry agent_id + agent_type, and a CHILD's own tool events carry+ // agent_id/agent_type too (the child runs inside the same codex process, so its hooks fire+ // through the parent's subscription). SubagentStop adds last_assistant_message.+ agent_id?: string+ agent_type?: string+ last_assistant_message?: string}export function normalizeCodex(env: RawHookEnvelope): NormalizedAgentEvent | null {@@ -303,6 +310,29 @@ export function normalizeCodex(env: RawHookEnvelope): NormalizedAgentEvent | nulconst ev = p.hook_event_name ?? p.hookEventNameconst base = { nodeId: env.nodeId, agentId: env.agentId, sessionId: p.session_id }+ // Subagent fan-out (spawn_agent). Keyed by agent_id — the child's rollout/session uuid —+ // NOT tool_use_id: the spawn tool's Pre/PostToolUse and the SubagentStart it launches carry+ // different turn ids and nothing correlates them, while agent_id is stable across the child's+ // whole life (measured: parallel + nested spawns each get a distinct agent_id, and a nested+ // child's Start/Stop fire through the same subscription). No taskLabel: the spawn message is+ // encrypted end-to-end (tool_input.message AND the NEW_TASK payload in the child rollout are+ // Fernet blobs), so there is no task text to show — the live transcript tail carries the+ // readable "Task name:" header instead.+ if (ev === 'SubagentStart' && p.agent_id) {+ return { ...base, kind: 'subagent-start', toolUseId: p.agent_id, subagentType: p.agent_type }+ }+ // The real end signal — codex fires SubagentStop when the child's turn completes, so unlike+ // claude there is no async-launch-ack trap to dodge here. Duration/token counts are not in the+ // payload; the card keeps its live-timer elapsed and the result text.+ if (ev === 'SubagentStop' && p.agent_id) {+ return { ...base, kind: 'subagent-end', toolUseId: p.agent_id, result: p.last_assistant_message }+ }+ // A CHILD's own tool events (tagged agent_id) must not drive the PARENT node's state: after an+ // async spawn the parent's turn can end (Stop → done) while the child still runs, and a child+ // Bash event mapping to 'working' would flip a finished node back to RUNNING with no later+ // parent event to clear it. Child activity reaches the card via the rollout tail instead.+ if (p.agent_id) return null+// UserPromptSubmit is codex's turn start — flag newTurn so the renderer clears// per-turn fan-out once per turn, not on every tool event.if (ev === 'UserPromptSubmit') {