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.

feat(chat): parse and locate codex rollouts for the ⌘M view

review7c9255f41637
diff --git a/src/core/codex-chat.locate.test.ts b/src/core/codex-chat.locate.test.ts
new file mode 100644
index 000000000..51f77d6ef
--- /dev/null
+++ b/src/core/codex-chat.locate.test.ts
@@ -0,0 +1,138 @@
+// Locating a codex node's rollout: by its OWN thread id, under its OWN account's CODEX_HOME, and
+// never by anything weaker. The failure this guards is the one CLAUDE.md records for codex before:
+// a resolver that answers "a transcript" rather than "this session's transcript" shows a stranger's
+// conversation.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { fakePlatform } from './platform-fake'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { locateCodexRollout, resetCodexRolloutCacheForTests } from './codex-chat'
+import { codexHomeForAccount } from './codex-accounts-core'
+
+const ID = '01a0c9f4-2b7e-7c31-9d52-5e8a1f3b6c20'
+const OTHER = '01a0c9f4-2b7e-7c31-9d52-5e8a1f3b6c99'
+
+let home: string
+let f: ReturnType<typeof fakePlatform>
+let savedCodexHome: string | undefined
+
+const put = (root: string, rel: string, body = '{}\n'): string => {
+ const p = path.join(root, rel)
+ fs.mkdirSync(path.dirname(p), { recursive: true })
+ fs.writeFileSync(p, body)
+ return p
+}
+const sessions = (): string => path.join(home, '.codex', 'sessions')
+
+beforeEach(() => {
+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-codex-locate-'))
+ vi.spyOn(os, 'homedir').mockReturnValue(home)
+ savedCodexHome = process.env.CODEX_HOME
+ delete process.env.CODEX_HOME
+ f = fakePlatform()
+ initPlatform(f)
+ resetCodexRolloutCacheForTests()
+})
+afterEach(() => {
+ vi.restoreAllMocks()
+ resetPlatformForTests()
+ if (savedCodexHome === undefined) delete process.env.CODEX_HOME
+ else process.env.CODEX_HOME = savedCodexHome
+ fs.rmSync(home, { recursive: true, force: true })
+})
+
+describe('locateCodexRollout', () => {
+ it('finds the rollout named for exactly this thread id under the system home', async () => {
+ put(sessions(), `2026/09/23/rollout-2026-09-23T10-00-00-${OTHER}.jsonl`)
+ const mine = put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID })).toBe(mine)
+ })
+
+ it('never answers with another session: no substring match, no newest-in-cwd fallback', async () => {
+ // `includes()` would hit this file for the id `…6c20` minus its first group: the id must be
+ // the WHOLE `-<id>.jsonl` suffix.
+ put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-x${ID}.jsonl`)
+ put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl.bak`)
+ put(sessions(), `2026/09/24/other-${ID}.jsonl`)
+ // A claude transcript for the same cwd is not codex's business at all.
+ put(path.join(home, '.claude', 'projects', '-srv-demo'), `${ID}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID })).toBeUndefined()
+ })
+
+ it('refuses an id that could not be a thread id, before touching the disk', async () => {
+ put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ for (const bad of [undefined, '', '../x', `${ID}/..`, 'zz', '*']) {
+ expect(await locateCodexRollout({ sessionId: bad }), String(bad)).toBeUndefined()
+ }
+ })
+
+ it('a thread id is a WHOLE uuid: a trailing group of another id never matches its file', async () => {
+ // `5e8a1f3b6c20` is hex and 12 long, so claude's looser SESSION_ID_RE admits it — and
+ // `rollout-…-9d52-5e8a1f3b6c20.jsonl` really does end in `-5e8a1f3b6c20.jsonl`.
+ put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ for (const partial of ['5e8a1f3b6c20', '9d52-5e8a1f3b6c20', '7c31-9d52-5e8a1f3b6c20', `${ID}0`]) {
+ expect(await locateCodexRollout({ sessionId: partial }), partial).toBeUndefined()
+ }
+ // …and the uuid itself is accepted in either case.
+ expect(await locateCodexRollout({ sessionId: ID })).toBeDefined()
+ })
+
+ it('reads a MANAGED account\'s own home, never the system one', async () => {
+ const acct = 'acct-1'
+ const managed = path.join(codexHomeForAccount(f.userDataDir, acct, path.join(home, '.nodeterm', 'cx')), 'sessions')
+ put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`) // the system home's copy
+ expect(await locateCodexRollout({ sessionId: ID, accountId: acct })).toBeUndefined()
+ const mine = put(managed, `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ resetCodexRolloutCacheForTests()
+ expect(await locateCodexRollout({ sessionId: ID, accountId: acct })).toBe(mine)
+ })
+
+ it('an account id that cannot name a home finds nothing (never the system home)', async () => {
+ put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID, accountId: '../escape' })).toBeUndefined()
+ })
+
+ it('honours the host\'s CODEX_HOME for the system account', async () => {
+ const relocated = path.join(home, 'elsewhere')
+ process.env.CODEX_HOME = relocated
+ const mine = put(path.join(relocated, 'sessions'), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID })).toBe(mine)
+ })
+
+ it('does not follow a symlinked rollout or date directory', async () => {
+ const outside = put(home, `outside/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ fs.mkdirSync(path.join(sessions(), '2026', '09'), { recursive: true })
+ fs.symlinkSync(outside, path.join(sessions(), '2026', '09', `rollout-2026-09-24T09-00-00-${ID}.jsonl`))
+ fs.symlinkSync(path.join(home, 'outside'), path.join(sessions(), '2026', '10'))
+ expect(await locateCodexRollout({ sessionId: ID })).toBeUndefined()
+ })
+
+ it('prefers the hook-fed path, but only when it names this thread and exists', async () => {
+ const scanned = put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ const hooked = put(home, `hooked/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID }, () => hooked)).toBe(hooked)
+ // A hint naming ANOTHER thread's file is ignored, not trusted.
+ const foreign = put(home, `hooked/rollout-2026-09-24T09-00-00-${OTHER}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID }, () => foreign)).toBe(scanned)
+ // A hint that no longer exists falls back to the scan.
+ expect(await locateCodexRollout({ sessionId: ID }, () => path.join(home, `gone/rollout-x-${ID}.jsonl`))).toBe(scanned)
+ // A hint that is a SYMLINK (to anything) is not a rollout codex wrote.
+ const link = path.join(home, 'hooked', `rollout-2026-09-24T09-00-01-${ID}.jsonl`)
+ fs.symlinkSync(foreign, link)
+ expect(await locateCodexRollout({ sessionId: ID }, () => link)).toBe(scanned)
+ })
+
+ it('caches a hit, and heals when the cached file disappears', async () => {
+ const first = put(sessions(), `2026/09/24/rollout-2026-09-24T09-00-00-${ID}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID })).toBe(first)
+ fs.rmSync(first)
+ const moved = put(sessions(), `2026/09/25/rollout-2026-09-25T09-00-00-${ID}.jsonl`)
+ expect(await locateCodexRollout({ sessionId: ID })).toBe(moved)
+ })
+
+ it('a missing sessions directory is simply not found', async () => {
+ expect(await locateCodexRollout({ sessionId: ID })).toBeUndefined()
+ })
+})
diff --git a/src/core/codex-chat.test.ts b/src/core/codex-chat.test.ts
new file mode 100644
index 000000000..286dea8ed
--- /dev/null
+++ b/src/core/codex-chat.test.ts
@@ -0,0 +1,369 @@
+// The ⌘M reader for a codex rollout. Every input is SYNTHETIC (codex-rollout-fake.ts), in the
+// record shapes measured on real rollouts — see that file's header for the versions.
+import { describe, it, expect } from 'vitest'
+import {
+ chatMessagesFromCodex,
+ parseCodexChatRecords,
+ parseCodexChatWindow,
+ codexToolArg,
+ codexResultSummary
+} from './codex-chat'
+import { parseChatWindow } from './transcript-reader'
+import {
+ agentMessageEvent,
+ agentMessageItem,
+ assistantText,
+ commandExecutionItem,
+ compacted,
+ contextCompactionItem,
+ customToolCall,
+ customToolOutput,
+ extensionItem,
+ fileChangeItem,
+ functionCall,
+ functionOutput,
+ injectedContext,
+ interAgentMeta,
+ reasoning,
+ reasoningItem,
+ riAgentMessage,
+ riMessage,
+ rollout,
+ rolloutLine,
+ sessionMeta,
+ subAgentActivityItem,
+ taskComplete,
+ taskFailed,
+ taskStarted,
+ threadSettingsApplied,
+ tokenCount,
+ tokenUsageRecord,
+ toolSearchCall,
+ toolSearchOutput,
+ turnAborted,
+ turnContext,
+ userMessageEvent,
+ userMessageItem,
+ worldState,
+ type CodexRec
+} from './codex-rollout-fake'
+
+const records = (text: string): Array<{ raw: string; offset: number }> => {
+ const out: Array<{ raw: string; offset: number }> = []
+ let offset = 0
+ for (const raw of text.split('\n')) {
+ out.push({ raw, offset })
+ offset += Buffer.byteLength(raw) + 1
+ }
+ return out
+}
+const parsePaged = (text: string) => parseCodexChatRecords(records(text), true)
+const texts = (msgs: ReturnType<typeof chatMessagesFromCodex>) =>
+ msgs.map((m) => `${m.role}:${m.parts.map((p) => (p.kind === 'text' ? p.text : `[${p.name}] ${p.arg}`)).join('|')}`)
+
+describe('user turns', () => {
+ it('reads the TYPED prompt from the UI record, never the model-side copy or the injected context (paginated)', () => {
+ const msgs = chatMessagesFromCodex(
+ rollout([
+ sessionMeta('paginated'),
+ ...injectedContext(),
+ riMessage('user', ['fix the build']),
+ userMessageItem(['fix the build']),
+ assistantText('On it.')
+ ])
+ )
+ expect(texts(msgs)).toEqual(['user:fix the build', 'assistant:On it.'])
+ })
+
+ it('reads the typed prompt from event_msg/user_message on the LEGACY format', () => {
+ const msgs = chatMessagesFromCodex(
+ rollout(
+ [sessionMeta('legacy'), ...injectedContext(), userMessageEvent('why is CI red?'), riMessage('user', ['why is CI red?'])],
+ 'legacy'
+ )
+ )
+ expect(texts(msgs)).toEqual(['user:why is CI red?'])
+ })
+
+ it('keeps each text item of a UserMessage as its own part and drops a pasted image', () => {
+ const msgs = chatMessagesFromCodex(
+ rollout([userMessageItem(['look at this', { type: 'local_image', path: '/tmp/shot.png' }, 'and this'])])
+ )
+ expect(msgs).toHaveLength(1)
+ expect(msgs[0].parts).toEqual([
+ { kind: 'text', text: 'look at this' },
+ { kind: 'text', text: 'and this' }
+ ])
+ })
+
+ it('an image-only or blank prompt yields no bubble (same rule as claude)', () => {
+ const msgs = chatMessagesFromCodex(
+ rollout([userMessageItem([{ type: 'local_image', path: '/tmp/shot.png' }]), userMessageEvent(' '), userMessageEvent(42)])
+ )
+ expect(msgs).toEqual([])
+ })
+})
+
+describe('assistant turns', () => {
+ it('renders commentary and final answers from the response_item, and skips the UI duplicates', () => {
+ const msgs = chatMessagesFromCodex(
+ rollout([
+ assistantText('Looking at the logs.', 'commentary'),
+ agentMessageItem('Looking at the logs.', 'commentary'),
+ agentMessageEvent('Looking at the logs.', 'commentary'),
+ assistantText('The build is fixed.'),
+ agentMessageItem('The build is fixed.')
+ ])
+ )
+ expect(texts(msgs)).toEqual(['assistant:Looking at the logs.', 'assistant:The build is fixed.'])
+ })
+
+ it('one text part per output_text item; an empty item is dropped', () => {
+ const msgs = chatMessagesFromCodex(
+ rollout([riMessage('assistant', ['first', { type: 'output_text', text: '' }, 'second'], 'final_answer')])
+ )
+ expect(msgs[0].parts).toEqual([
+ { kind: 'text', text: 'first' },
+ { kind: 'text', text: 'second' }
+ ])
+ })
+
+ it('never renders reasoning (encrypted, and dropped for claude too)', () => {
+ expect(chatMessagesFromCodex(rollout([reasoning(), reasoningItem()]))).toEqual([])
+ })
+})
+
+describe('tool calls', () => {
+ it('a function_call becomes a tool part and its output is attached by call_id', () => {
+ const msgs = chatMessagesFromCodex(
+ rollout([
+ functionCall('call_1', 'exec_command', { cmd: 'npm test', workdir: '/srv/demo', max_output_tokens: 4000 }),
+ functionOutput(
+ 'call_1',
+ 'Chunk ID: 7f\nWall time: 1.2 seconds\nProcess exited with code 0\nOriginal token count: 12\nOutput:\n12 passed\n0 failed'
+ )
+ ])
+ )
+ expect(msgs).toEqual([
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'exec_command', arg: 'npm test', result: '12 passed 0 failed' }], at: expect.any(Number) }
+ ])
+ })
+
+ it('a custom tool (`exec`, JavaScript input) keeps its input as the arg and its array output as the result', () => {
+ const input = 'const r = await tools.exec_command({cmd:"ls"})\ntext(r.output)'
+ const msgs = chatMessagesFromCodex(
+ rollout([
+ customToolCall('call_2', 'exec', ` ${input} `),
+ customToolOutput('call_2', [
+ { type: 'input_text', text: 'Script completed\nWall time 0.1 seconds\nOutput:\n' },
+ { type: 'input_text', text: 'a.txt\nb.txt' },
+ { type: 'input_image', image_url: 'data:image/png;base64,AAAA' }
+ ])
+ ])
+ )
+ expect(msgs[0].parts).toEqual([{ kind: 'tool', name: 'exec', arg: input, result: 'a.txt b.txt' }])
+ })
+
+ it('tool_search pairs with its output by call_id; an output with no text sets no result', () => {
+ const msgs = chatMessagesFromCodex(rollout([toolSearchCall('call_3', 'calendar'), toolSearchOutput('call_3')]))
+ expect(msgs[0].parts).toEqual([{ kind: 'tool', name: 'tool_search', arg: 'calendar' }])
+ })
+
+ it('an orphan output (its call is not in the read) is dropped on the unpaged read', () => {
+ expect(chatMessagesFromCodex(rollout([functionOutput('call_gone', 'x')]))).toEqual([])
+ })
+
+ it('a missing / empty name falls back to "tool"', () => {
+ const msgs = chatMessagesFromCodex(rollout([functionCall('c', '', { cmd: 'ls' })]))
+ expect(msgs[0].parts[0]).toMatchObject({ kind: 'tool', name: 'tool', arg: 'ls' })
+ })
+})
+
+describe('codexToolArg', () => {
+ it('picks the first known string field, in order', () => {
+ expect(codexToolArg('{"cmd":"ls -la","workdir":"/x"}')).toBe('ls -la')
+ expect(codexToolArg('{"target":"/root/w","message":"please rebase"}')).toBe('please rebase')
+ expect(codexToolArg({ query: 'calendar' })).toBe('calendar')
+ expect(codexToolArg('{"command":["bash","-lc","make"]}')).toBe('bash -lc make')
+ expect(codexToolArg('{"path":"a","cmd":"b"}')).toBe('b') // cmd outranks path
+ })
+ it('is empty for arguments it cannot name, never raw JSON', () => {
+ expect(codexToolArg('{"duration_ms":5000}')).toBe('')
+ expect(codexToolArg('not json')).toBe('')
+ expect(codexToolArg('null')).toBe('')
+ expect(codexToolArg('[1,2]')).toBe('')
+ expect(codexToolArg('{"cmd":42}')).toBe('')
+ expect(codexToolArg(undefined)).toBe('')
+ })
+ it('caps at 200 UTF-16 units', () => {
+ expect(codexToolArg(JSON.stringify({ cmd: 'x'.repeat(300) }))).toBe('x'.repeat(200))
+ })
+})
+
+describe('codexResultSummary', () => {
+ it('drops the preamble up to the `Output:` line, then keeps three lines capped at 500', () => {
+ expect(codexResultSummary('Chunk ID: 1\nWall time: 1s\nProcess exited with code 1\nOriginal token count: 3\nOutput:\nE1\nE2\nE3\nE4')).toBe(
+ 'E1 E2 E3'
+ )
+ expect(codexResultSummary([{ type: 'input_text', text: 'Script completed\nWall time 0.1 seconds\nOutput:\n' }, { type: 'input_text', text: 'y'.repeat(900) }])).toBe(
+ 'y'.repeat(500)
+ )
+ })
+ it('an empty body falls back to the preamble (it still says how the call ended)', () => {
+ expect(codexResultSummary('Script completed\nWall time 0.1 seconds\nOutput:\n')).toBe('Script completed Wall time 0.1 seconds')
+ })
+ it('text without a preamble is summarized as is; `Output:` past the sixth line is content', () => {
+ expect(codexResultSummary('plain\nresult')).toBe('plain result')
+ expect(codexResultSummary('1\n2\n3\n4\n5\n6\nOutput:\nx')).toBe('1 2 3')
+ })
+ it('non-text output yields nothing', () => {
+ expect(codexResultSummary(undefined)).toBe('')
+ expect(codexResultSummary({ content: 'x' })).toBe('')
+ expect(codexResultSummary([{ type: 'input_image', image_url: 'data:' }])).toBe('')
+ })
+})
+
+describe('notes the harness writes', () => {
+ it('a failed turn shows its error message as an assistant note', () => {
+ const msgs = chatMessagesFromCodex(rollout([taskFailed("You've hit your usage limit.")]))
+ expect(texts(msgs)).toEqual(["assistant:[error] You've hit your usage limit."])
+ })
+ it('an interrupted turn says so; a non-string reason is dropped from the note', () => {
+ const msgs = chatMessagesFromCodex(rollout([turnAborted('interrupted'), turnAborted(7)]))
+ expect(texts(msgs)).toEqual(['assistant:[turn aborted: interrupted]', 'assistant:[turn aborted]'])
+ })
+ it('a completed turn, and an error with no message, show nothing', () => {
+ expect(chatMessagesFromCodex(rollout([taskComplete(), taskFailed(''), taskFailed(5)]))).toEqual([])
+ })
+})
+
+describe('skipped records', () => {
+ const SKIPPED: CodexRec[] = [
+ sessionMeta('paginated'),
+ turnContext('gpt-5.6-sol', 'medium'),
+ taskStarted(),
+ taskComplete(),
+ tokenCount(),
+ tokenUsageRecord(),
+ worldState(),
+ threadSettingsApplied(),
+ interAgentMeta(),
+ compacted(),
+ reasoning(),
+ ...injectedContext(),
+ riAgentMessage('/root/worker_1', '/root', 'done with the rebase'),
+ agentMessageEvent('dup'),
+ agentMessageItem('dup'),
+ commandExecutionItem(),
+ fileChangeItem(),
+ reasoningItem(),
+ extensionItem(),
+ contextCompactionItem(),
+ subAgentActivityItem()
+ ]
+ it('render nothing and are counted, never shown as raw JSON', () => {
+ const out = parsePaged(rollout(SKIPPED))
+ expect(out.messages).toEqual([])
+ expect(out.skipped).toBe(SKIPPED.length)
+ })
+
+ it('a malformed line costs one line, never the read', () => {
+ const body =
+ 'not json\nnull\n[1]\n"str"\n{"type":"response_item","payload":null}\n{"type":"response_item","payload":[1]}\n' +
+ '{"type":"event_msg","payload":{"type":"item_completed","item":null}}\n' +
+ '{"type":"event_msg","payload":{"type":"item_completed","item":{"type":"UserMessage","content":"x"}}}\n' +
+ '{"type":"response_item","payload":{"type":"message","role":"assistant","content":null}}\n' +
+ '{"type":"response_item","payload":{"type":"message","role":"assistant","content":[null,1,{"type":"output_text","text":5}]}}\n' +
+ rolloutLine(assistantText('survived'), 0)
+ const out = parsePaged(body)
+ expect(texts(out.messages)).toEqual(['assistant:survived'])
+ expect(out.skipped).toBe(10)
+ })
+})
+
+describe('timestamps, keys and model (paged)', () => {
+ it('`at` is the line\'s own timestamp; keys are absolute byte offsets on the paged read only', () => {
+ const body = rollout([sessionMeta('paginated'), userMessageItem(['hi']), assistantText('hello')])
+ const lines = body.split('\n')
+ const off1 = Buffer.byteLength(lines[0]) + 1
+ const off2 = off1 + Buffer.byteLength(lines[1]) + 1
+ const paged = parsePaged(body).messages
+ expect(paged.map((m) => m.key)).toEqual([off1, off2])
+ expect(paged.map((m) => m.at)).toEqual([Date.parse('2026-09-24T09:00:01.000Z'), Date.parse('2026-09-24T09:00:02.000Z')])
+ const unpaged = chatMessagesFromCodex(body)
+ expect(unpaged.every((m) => m.key === undefined)).toBe(true)
+ expect(unpaged.map((m) => m.at)).toEqual(paged.map((m) => m.at))
+ })
+
+ it('a line without a valid timestamp has no `at`', () => {
+ const raw = JSON.stringify({ timestamp: 'nope', type: 'event_msg', payload: { type: 'user_message', message: 'x' } })
+ expect(chatMessagesFromCodex(raw)[0].at).toBeUndefined()
+ })
+
+ it('tool parts carry the call_id as `id` on the paged read only', () => {
+ const body = rollout([functionCall('call_9', 'exec_command', { cmd: 'ls' })])
+ expect(parsePaged(body).messages[0].parts[0]).toMatchObject({ id: 'call_9' })
+ expect(chatMessagesFromCodex(body)[0].parts[0]).not.toHaveProperty('id')
+ })
+
+ it('an output whose call is in an OLDER window is carried (paged), keyed by call_id', () => {
+ const out = parsePaged(rollout([customToolOutput('call_old', [{ type: 'input_text', text: 'late result' }])]))
+ expect(out.messages).toEqual([])
+ expect([...out.unmatched]).toEqual([['call_old', 'late result']])
+ })
+
+ it('model and effort come from the NEWEST turn_context, both from that one record', () => {
+ const out = parsePaged(rollout([turnContext('gpt-5.5', 'high'), assistantText('a'), turnContext('gpt-5.6-sol', 'medium')]))
+ expect(out.model).toBe('gpt-5.6-sol')
+ expect(out.effort).toBe('medium')
+ })
+
+ it('an effort the newest turn_context does not state is ABSENT, never carried from an older one', () => {
+ const out = parsePaged(rollout([turnContext('gpt-5.5', 'high'), turnContext('gpt-5.6-sol')]))
+ expect(out.model).toBe('gpt-5.6-sol')
+ expect('effort' in out).toBe(false)
+ })
+
+ it('a model that is not a short string is absent; the unpaged read reports neither', () => {
+ const out = parsePaged(rollout([turnContext('m'.repeat(101), 'x'.repeat(100))]))
+ expect('model' in out).toBe(false)
+ expect(out.effort).toBe('x'.repeat(100))
+ expect(parseCodexChatRecords(records(rollout([turnContext('gpt-5.5', 'high')])), false)).not.toHaveProperty('model')
+ })
+})
+
+describe('parseCodexChatWindow', () => {
+ const body = rollout([
+ userMessageItem(['first']),
+ assistantText('a'.repeat(300)),
+ userMessageItem(['second']),
+ assistantText('done')
+ ])
+ const buf = Buffer.from(body)
+
+ it('splits the window exactly like claude\'s parseChatWindow (cursor, partial line, lookbehind)', () => {
+ for (const start of [0, 1, 40, 200, buf.length - 30, buf.indexOf(0x0a) , buf.indexOf(0x0a) + 1]) {
+ const codex = parseCodexChatWindow(buf.subarray(start), start)
+ const claude = parseChatWindow(buf.subarray(start), start)
+ expect(codex.olderCursor, `start ${start}`).toBe(claude.olderCursor)
+ expect(codex.noCompleteLine, `start ${start}`).toBe(claude.noCompleteLine)
+ }
+ })
+
+ it('returns exactly the ChatWindowParse shape — no internal counters on the wire', () => {
+ const w = parseCodexChatWindow(buf, 0)
+ expect(Object.keys(w).sort()).toEqual(['messages', 'noCompleteLine', 'olderCursor', 'unmatchedResults'])
+ expect(texts(w.messages)).toEqual(['user:first', `assistant:${'a'.repeat(300)}`, 'user:second', 'assistant:done'])
+ })
+
+ it('a window holding no complete line says so and points before itself', () => {
+ const w = parseCodexChatWindow(buf.subarray(10, 20), 10)
+ expect(w).toEqual({ messages: [], olderCursor: 10, unmatchedResults: [], noCompleteLine: true })
+ })
+
+ it('carries model/effort keys only when stated', () => {
+ const w = parseCodexChatWindow(Buffer.from(rollout([turnContext('gpt-5.6-sol', 'low'), assistantText('x')])), 0)
+ expect(w.model).toBe('gpt-5.6-sol')
+ expect(w.effort).toBe('low')
+ })
+})
diff --git a/src/core/codex-chat.ts b/src/core/codex-chat.ts
new file mode 100644
index 000000000..d2a8988ae
--- /dev/null
+++ b/src/core/codex-chat.ts
@@ -0,0 +1,410 @@
+// A codex rollout (`<CODEX_HOME>/sessions/YYYY/MM/DD/rollout-<ts>-<thread id>.jsonl`) as the ⌘M
+// panel's structured messages — the same `ChatMessage` / `ChatPart` shapes claude's reader emits,
+// so the panel, the kanban card modal and the phone (over the relay, `ChatPage` v1) render it with
+// no agent-specific code. Separate from `transcript-reader.ts`'s claude parser: claude's records
+// (`message.content`, `tool_use` / `tool_result`) share nothing with codex's, and pointing claude's
+// resolver at a codex id is how a codex node once read a stranger's claude session.
+//
+// ── The measured format (codex-cli 0.114.0 → 0.156.1, 67 rollouts, 2026-09-28) ──────────────────
+// Every line is `{timestamp, type, payload}`; the paginated format (≥ 0.151, `session_meta.payload
+// .history_mode: "paginated"`) adds a numeric `ordinal`. Two parallel streams describe one session:
+// - `response_item` — what the MODEL sees: `message` (role user / developer / assistant),
+// `reasoning`, `function_call` / `function_call_output`, `custom_tool_call` /
+// `custom_tool_call_output`, `tool_search_call` / `tool_search_output`, `agent_message`.
+// - `event_msg` — what the UI saw: `user_message` + `agent_message` (legacy ≤ 0.146), or
+// `item_completed` with a thread item (`UserMessage`, `AgentMessage`, `CommandExecution`, …) on
+// the paginated format; plus `task_started` / `task_complete` / `turn_aborted` / `token_count`.
+//
+// Which stream each part comes from is the whole design:
+// - USER text comes from the UI stream ONLY. The model-side `role:user` messages also carry the
+// context codex injects (`# AGENTS.md instructions…`, `<environment_context>`, subagent tasks,
+// image wrappers) — measured: every typed prompt appears in the UI stream, and every model-side
+// user text missing from it was injected. Reading the UI record needs no prefix heuristics.
+// The two UI shapes never co-occur in one rollout (measured over all 67).
+// - ASSISTANT text and TOOLS come from the model stream only: it exists on both formats, and a tool
+// call and its output are correlated by `call_id` exactly like claude's `tool_use_id`. The UI
+// copies (`agent_message` events, `AgentMessage` items) are skipped, or every answer would show
+// twice.
+// - `reasoning` is skipped (encrypted; claude's thinking is dropped too), and so are developer
+// messages, compaction, inter-agent `agent_message` deliveries and every metadata record.
+//
+// Paging: a rollout is append-only JSONL, so it pages exactly like claude's transcript — keys are
+// absolute byte offsets and an output whose call sits in an older window is carried in
+// `unmatchedResults` (see `parseCodexChatWindow`).
+import fs from 'node:fs'
+import path from 'node:path'
+import type { ChatCarriedToolResult, ChatMessage, ChatPart } from '../shared/types'
+import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'
+import type { ChatWindowParse } from './transcript-reader'
+import { codexHomeFor } from './codex-config-dir'
+
+type ToolPart = Extract<ChatPart, { kind: 'tool' }>
+
+/** A tool result's summary: first three lines joined by a space, first 500 UTF-16 units — claude's
+ * `summarizeResult` rule, so a result reads the same on either agent. */
+const RESULT_LINES = 3
+const RESULT_MAX = 500
+/** Longest `model` / `effort` value reported (same bound as claude's reader). */
+const META_MAX = 100
+/** Longest `turn_aborted` reason shown in the note; a longer one is dropped from it. */
+const REASON_MAX = 100
+/** How far down a tool output the `Output:` line may sit and still end a preamble. */
+const PREAMBLE_MAX_LINES = 6
+/** The name a `tool_search_call` gets (the record itself carries none). */
+export const CODEX_TOOL_SEARCH = 'tool_search'
+
+/** Which argument field names a tool call, in order: codex's own `cmd` (exec_command) first, then
+ * claude's `toolArg` keys, then `query` (tool search) and `message` (the collaboration tools). */
+const ARG_KEYS = ['cmd', 'command', 'file_path', 'path', 'pattern', 'query', 'description', 'prompt', 'message'] as const
+
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
+
+/**
+ * The one-line hint for a tool call: `arguments` is a JSON string (function_call) or an object
+ * (tool_search_call). The first `ARG_KEYS` field holding a string (or, for `command`, an array of
+ * strings, joined by a space) wins, capped at `CHAT_TOOL_ARG_MAX`. Anything else — unparseable,
+ * not an object, no known field — is `''`, never the raw JSON.
+ */
+export function codexToolArg(args: unknown): string {
+ let o: unknown = args
+ if (typeof args === 'string') {
+ try {
+ o = JSON.parse(args)
+ } catch {
+ return ''
+ }
+ }
+ if (!isObj(o)) return ''
+ for (const k of ARG_KEYS) {
+ const v = o[k]
+ if (typeof v === 'string') return v.slice(0, CHAT_TOOL_ARG_MAX)
+ if (k === 'command' && Array.isArray(v) && v.length > 0 && v.every((x) => typeof x === 'string')) {
+ return v.join(' ').slice(0, CHAT_TOOL_ARG_MAX)
+ }
+ }
+ return ''
+}
+
+/** The text of a tool output: a string, or the `input_text` / `output_text` items of an array
+ * joined by `\n` (an `input_image` item has no text). Anything else has none. */
+function outputText(output: unknown): string {
+ if (typeof output === 'string') return output
+ if (!Array.isArray(output)) return ''
+ return output
+ .filter((c): c is { type: string; text: string } => isObj(c) && (c.type === 'input_text' || c.type === 'output_text') && typeof c.text === 'string')
+ .map((c) => c.text)
+ .join('\n')
+}
+
+/**
+ * A tool output's summary. Codex opens its tool outputs with a preamble that ends at a line reading
+ * exactly `Output:` — `Script completed / Wall time … / Output:` (exec), `Chunk ID / Wall time /
+ * Process exited with code N / Original token count / Output:` (exec_command). Summarizing from the
+ * top would show that preamble on every call, so the summary starts after it (leading blank lines
+ * skipped). An empty body falls back to the preamble, which still says how the call ended. Only an
+ * `Output:` within the first `PREAMBLE_MAX_LINES` lines counts; later it is content.
+ */
+export function codexResultSummary(output: unknown): string {
+ const lines = outputText(output).split('\n')
+ const marker = lines.slice(0, PREAMBLE_MAX_LINES).indexOf('Output:')
+ let pick = lines
+ if (marker >= 0) {
+ const body = lines.slice(marker + 1)
+ let first = 0
+ while (first < body.length && body[first].trim() === '') first++
+ pick = first < body.length ? body.slice(first) : lines.slice(0, marker)
+ }
+ return pick.slice(0, RESULT_LINES).join(' ').slice(0, RESULT_MAX)
+}
+
+function metaString(v: unknown): string | undefined {
+ return typeof v === 'string' && v.length > 0 && v.length <= META_MAX ? v : undefined
+}
+
+function lineTime(v: unknown): number | undefined {
+ if (typeof v !== 'string' || !v) return undefined
+ const t = Date.parse(v)
+ return Number.isFinite(t) ? t : undefined
+}
+
+/** Text parts of a content array: items of `type` whose `text` is a non-empty string. */
+function textParts(content: unknown, type: string): ChatPart[] {
+ if (!Array.isArray(content)) return []
+ const parts: ChatPart[] = []
+ for (const c of content) {
+ if (isObj(c) && c.type === type && typeof c.text === 'string' && c.text) parts.push({ kind: 'text', text: c.text })
+ }
+ return parts
+}
+
+export interface CodexChatParse {
+ messages: ChatMessage[]
+ /** PAGED only: outputs whose call is not among these lines (it lives in an OLDER window). */
+ unmatched: Map<string, string>
+ /** PAGED only: the newest `turn_context`'s `model` / `effort` — both from that ONE record. */
+ model?: string
+ effort?: string
+ /** Non-blank lines that rendered nothing (no message, no result): metadata, reasoning, injected
+ * context, UI duplicates, malformed lines. Diagnostic only — never on the wire. */
+ skipped: number
+}
+
+/**
+ * Parse rollout lines into chat messages. `paged` adds what only a paged read needs: `key` (the
+ * line's absolute byte offset), the `call_id` as a tool part's `id`, the carried outputs, and
+ * `model` / `effort`. The unpaged read carries `at` too (same as claude).
+ */
+export function parseCodexChatRecords(
+ records: Iterable<{ raw: string; offset: number }>,
+ paged: boolean
+): CodexChatParse {
+ const messages: ChatMessage[] = []
+ const unmatched = new Map<string, string>()
+ const toolById = new Map<string, ToolPart>()
+ let model: string | undefined
+ let effort: string | undefined
+ let skipped = 0
+ for (const { raw, offset } of records) {
+ if (!raw.trim()) continue
+ let o: unknown
+ try {
+ o = JSON.parse(raw)
+ } catch {
+ skipped++
+ continue
+ }
+ if (!isObj(o) || !isObj(o.payload)) {
+ skipped++
+ continue
+ }
+ const p = o.payload
+ const at = lineTime(o.timestamp)
+ const push = (role: ChatMessage['role'], parts: ChatPart[]): void => {
+ const m: ChatMessage = { role, parts }
+ if (at !== undefined) m.at = at
+ if (paged) m.key = offset
+ messages.push(m)
+ }
+ const tool = (name: string, arg: string, callId: unknown): void => {
+ const part: ToolPart = { kind: 'tool', name, arg }
+ if (paged && typeof callId === 'string' && callId) part.id = callId
+ if (typeof callId === 'string' && callId) toolById.set(callId, part)
+ push('assistant', [part])
+ }
+ let rendered = false
+ if (o.type === 'event_msg') {
+ if (p.type === 'user_message') {
+ // LEGACY: the prompt exactly as typed.
+ if (typeof p.message === 'string' && p.message.trim()) {
+ push('user', [{ kind: 'text', text: p.message }])
+ rendered = true
+ }
+ } else if (p.type === 'item_completed') {
+ // PAGINATED: the same, as a thread item. Every other item type duplicates the model stream
+ // (AgentMessage) or describes a tool the model stream already carries.
+ const item = p.item
+ if (isObj(item) && item.type === 'UserMessage') {
+ const parts = textParts(item.content, 'text')
+ if (parts.length) {
+ push('user', parts)
+ rendered = true
+ }
+ }
+ } else if (p.type === 'task_complete') {
+ // A turn that FAILED (measured: `usage_limit_exceeded`) says why only here. Without the
+ // note the reader sees a prompt followed by nothing.
+ const err = p.error
+ if (isObj(err) && typeof err.message === 'string' && err.message.trim()) {
+ push('assistant', [{ kind: 'text', text: `[error] ${err.message}` }])
+ rendered = true
+ }
+ } else if (p.type === 'turn_aborted') {
+ const reason = typeof p.reason === 'string' ? p.reason.trim() : ''
+ const shown = reason && reason.length <= REASON_MAX ? `: ${reason}` : ''
+ push('assistant', [{ kind: 'text', text: `[turn aborted${shown}]` }])
+ rendered = true
+ }
+ } else if (o.type === 'response_item') {
+ if (p.type === 'message') {
+ // Only the assistant's own words. role user / developer is model-side context (see header).
+ if (p.role === 'assistant') {
+ const parts = textParts(p.content, 'output_text')
+ if (parts.length) {
+ push('assistant', parts)
+ rendered = true
+ }
+ }
+ } else if (p.type === 'function_call') {
+ tool(typeof p.name === 'string' && p.name ? p.name : 'tool', codexToolArg(p.arguments), p.call_id)
+ rendered = true
+ } else if (p.type === 'custom_tool_call') {
+ const input = typeof p.input === 'string' ? p.input.trim().slice(0, CHAT_TOOL_ARG_MAX) : ''
+ tool(typeof p.name === 'string' && p.name ? p.name : 'tool', input, p.call_id)
+ rendered = true
+ } else if (p.type === 'tool_search_call') {
+ tool(CODEX_TOOL_SEARCH, codexToolArg(p.arguments), p.call_id)
+ rendered = true
+ } else if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output' || p.type === 'tool_search_output') {
+ const callId = typeof p.call_id === 'string' && p.call_id ? p.call_id : undefined
+ const target = callId ? toolById.get(callId) : undefined
+ const s = codexResultSummary(p.output)
+ if (target) {
+ if (s) target.result = s
+ rendered = true
+ } else if (paged && s && callId) {
+ // Its call is in an OLDER window (codex writes the call before its output).
+ unmatched.set(callId, s)
+ rendered = true
+ }
+ }
+ } else if (o.type === 'turn_context' && paged) {
+ // One record answers BOTH: a field it does not state is absent, never carried forward from an
+ // older turn (same rule as claude's reader).
+ model = metaString(p.model)
+ effort = metaString(p.effort)
+ }
+ if (!rendered) skipped++
+ }
+ const out: CodexChatParse = { messages, unmatched, skipped }
+ if (model !== undefined) out.model = model
+ if (effort !== undefined) out.effort = effort
+ return out
+}
+
+/** The unpaged (legacy) read: every line of `text`, no keys, no carried results. */
+export function chatMessagesFromCodex(text: string): ChatMessage[] {
+ return parseCodexChatRecords(
+ text.split('\n').map((raw) => ({ raw, offset: 0 })),
+ false
+ ).messages
+}
+
+/**
+ * One byte window of a rollout, with EXACTLY the window contract of claude's `parseChatWindow`
+ * (transcript-reader.ts) — `buf` starts one lookbehind byte before the window when `bufStart > 0`,
+ * everything up to the first `\n` is the dropped partial line, `olderCursor` is where the first
+ * complete line starts, and a window with no complete line reports `noCompleteLine` pointing at
+ * `bufStart`. Kept as its own copy (a dozen lines) rather than a refactor of claude's function, so
+ * this agent's reader stays in its own file; `codex-chat.test.ts` pins that the two split every
+ * boundary identically.
+ */
+export function parseCodexChatWindow(buf: Buffer, bufStart: number): ChatWindowParse {
+ const end = bufStart + buf.length
+ let from = 0
+ let olderCursor: number | null = null
+ if (bufStart > 0) {
+ const nl = buf.indexOf(0x0a)
+ if (nl < 0 || bufStart + nl + 1 >= end) {
+ return { messages: [], olderCursor: bufStart, unmatchedResults: [], noCompleteLine: true }
+ }
+ from = nl + 1
+ olderCursor = bufStart + from
+ }
+ const records: Array<{ raw: string; offset: number }> = []
+ while (from < buf.length) {
+ const nl = buf.indexOf(0x0a, from)
+ const to = nl < 0 ? buf.length : nl
+ if (to > from) records.push({ raw: buf.toString('utf8', from, to), offset: bufStart + from })
+ from = to + 1
+ }
+ const { messages, unmatched, model, effort } = parseCodexChatRecords(records, true)
+ const carried: ChatCarriedToolResult[] = [...unmatched].map(([id, result]) => ({ id, result }))
+ return {
+ messages,
+ olderCursor,
+ unmatchedResults: carried,
+ ...(model !== undefined ? { model } : {}),
+ ...(effort !== undefined ? { effort } : {}),
+ noCompleteLine: false
+ }
+}
+
+// ── Locating the rollout ─────────────────────────────────────────────────────────────────────────
+
+/**
+ * A codex thread id: one WHOLE uuid (measured: UUIDv7, e.g. `01a0cd92-5650-7190-950b-…`). Claude's
+ * looser `SESSION_ID_RE` (hex and dashes, 8–64) is not enough here — a uuid's last group is itself
+ * 12 hex characters, so `-<that group>.jsonl` would match ANOTHER thread's rollout name.
+ */
+export const CODEX_THREAD_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+/** How deep under `sessions/` a rollout may sit (codex writes `YYYY/MM/DD/`). */
+const LOCATE_MAX_DEPTH = 4
+
+/** `rollout-<anything>-<id>.jsonl`: the thread id is the WHOLE suffix, never a substring. */
+function isRolloutFor(name: string, sessionId: string): boolean {
+ return name.startsWith('rollout-') && name.endsWith(`-${sessionId}.jsonl`)
+}
+
+async function readable(p: string): Promise<boolean> {
+ try {
+ const st = await fs.promises.lstat(p)
+ return st.isFile()
+ } catch {
+ return false
+ }
+}
+
+const rolloutCache = new Map<string, string>()
+/** Test seam: the hit cache outlives a test's temp home otherwise. */
+export function resetCodexRolloutCacheForTests(): void {
+ rolloutCache.clear()
+}
+
+/**
+ * The rollout of THIS codex session: the file whose name ends in `-<thread id>.jsonl` under the
+ * node's own account's `CODEX_HOME/sessions` (`codexHomeFor`: a managed account's private home, or
+ * the system `$CODEX_HOME` / `~/.codex`). Keyed strictly by the thread id — there is no cwd or
+ * newest-file fallback, because an answer that is "a codex session" rather than "this one" is a
+ * stranger's conversation. Symlinks (files or date directories) are not followed, so the answer
+ * cannot leave the sessions tree.
+ *
+ * `hinted` is the hook-fed path a live context tail holds for the id (authoritative when the pane's
+ * own `CODEX_HOME` differs from ours). It is used only when its file name names this very thread
+ * and it exists — a hint is a shortcut, not a way to point one session at another's file.
+ */
+export async function locateCodexRollout(
+ q: { sessionId?: string; accountId?: string },
+ hinted?: (sessionId: string) => string | undefined
+): Promise<string | undefined> {
+ const id = q.sessionId
+ if (!id || !CODEX_THREAD_ID_RE.test(id)) return undefined
+ const hint = hinted?.(id)
+ if (hint && isRolloutFor(path.basename(hint), id) && (await readable(hint))) return hint
+ let root: string
+ try {
+ root = path.join(codexHomeFor(q.accountId), 'sessions')
+ } catch {
+ // An account id that cannot name a home (codexAccountHome refuses it): nothing to read, and
+ // certainly not the system home.
+ return undefined
+ }
+ const cacheKey = `${root}\0${id}`
+ const cached = rolloutCache.get(cacheKey)
+ if (cached) {
+ if (await readable(cached)) return cached
+ rolloutCache.delete(cacheKey)
+ }
+ // Newest date directory first: the session being read is almost always a recent one.
+ const walk = async (dir: string, depth: number): Promise<string | undefined> => {
+ let entries: fs.Dirent[]
+ try {
+ entries = await fs.promises.readdir(dir, { withFileTypes: true })
+ } catch {
+ return undefined
+ }
+ for (const e of entries) {
+ if (e.isFile() && isRolloutFor(e.name, id)) return path.join(dir, e.name)
+ }
+ if (depth >= LOCATE_MAX_DEPTH) return undefined
+ const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name).sort().reverse()
+ for (const d of dirs) {
+ const hit = await walk(path.join(dir, d), depth + 1)
+ if (hit) return hit
+ }
+ return undefined
+ }
+ const found = await walk(root, 0)
+ if (found) rolloutCache.set(cacheKey, found)
+ return found
+}
diff --git a/src/core/codex-rollout-fake.ts b/src/core/codex-rollout-fake.ts
new file mode 100644
index 000000000..c7fa03f09
--- /dev/null
+++ b/src/core/codex-rollout-fake.ts
@@ -0,0 +1,259 @@
+// SYNTHETIC codex rollout records, in the shapes measured on real rollouts (codex-cli 0.114.0,
+// 0.145.0, 0.146.0, 0.151.0 and 0.156.1 — 67 files, 2026-09-28). Test support only: the ⌘M codex
+// reader's unit tests and its golden fixtures (src/shared/chat-fixtures/codex/) are built from these,
+// never from a slice of a real rollout — real ones carry customer data.
+//
+// Every builder returns ONE rollout line as an object; `rolloutLine` serializes it with the
+// envelope codex writes (`timestamp`, `type`, `payload`, and `ordinal` on the paginated format).
+// Field order inside each payload follows the measured records, so a fixture reads like the real
+// thing. Nothing here decides behaviour.
+
+export type CodexRec = { type: string; payload: Record<string, unknown>; metadata?: Record<string, unknown> }
+
+export const CODEX_SID = '01a0c9f4-2b7e-7c31-9d52-5e8a1f3b6c20'
+const T0 = Date.parse('2026-09-24T09:00:00.000Z')
+
+/** One JSONL line. `index` fixes the timestamp (T0 + index seconds); `ordinal` is the paginated
+ * format's per-line counter — absent on the legacy format. */
+export function rolloutLine(r: CodexRec, index: number, ordinal?: number): string {
+ const timestamp = new Date(T0 + index * 1000).toISOString()
+ const env: Record<string, unknown> = { timestamp, type: r.type, payload: r.payload }
+ if (r.metadata) env.metadata = r.metadata
+ if (ordinal !== undefined) env.ordinal = ordinal
+ return JSON.stringify(env) + '\n'
+}
+
+/** A whole rollout: legacy lines carry no `ordinal`, paginated ones number every line from 0. */
+export function rollout(recs: CodexRec[], format: 'legacy' | 'paginated' = 'paginated'): string {
+ return recs.map((r, i) => rolloutLine(r, i, format === 'paginated' ? i : undefined)).join('')
+}
+
+// ── Session / turn metadata (never rendered) ─────────────────────────────────────────────────────
+export const sessionMeta = (format: 'legacy' | 'paginated', id = CODEX_SID): CodexRec => ({
+ type: 'session_meta',
+ payload: {
+ id,
+ timestamp: '2026-09-24T09:00:00.000Z',
+ cwd: '/srv/demo',
+ originator: 'codex_cli_rs',
+ cli_version: format === 'legacy' ? '0.145.0' : '0.156.1',
+ source: 'cli',
+ model_provider: 'openai',
+ base_instructions: { text: 'You are a coding agent.' },
+ history_mode: format,
+ session_id: id,
+ thread_source: 'user'
+ }
+})
+export const turnContext = (model: unknown, effort?: unknown): CodexRec => ({
+ type: 'turn_context',
+ payload: {
+ turn_id: 'turn-synthetic',
+ cwd: '/srv/demo',
+ approval_policy: 'on-request',
+ sandbox_policy: { type: 'workspace-write' },
+ model,
+ ...(effort === undefined ? {} : { effort }),
+ summary: 'auto',
+ collaboration_mode: {
+ mode: 'default',
+ settings: { model, reasoning_effort: effort ?? null, developer_instructions: null }
+ }
+ }
+})
+export const taskStarted = (): CodexRec => ({
+ type: 'event_msg',
+ payload: { type: 'task_started', turn_id: 'turn-synthetic', started_at: 1790000000, model_context_window: 258400, collaboration_mode_kind: 'default' }
+})
+export const taskComplete = (last: string | null = 'Done.'): CodexRec => ({
+ type: 'event_msg',
+ payload: { type: 'task_complete', turn_id: 'turn-synthetic', last_agent_message: last, started_at: 1790000000, completed_at: 1790000030, duration_ms: 30000 }
+})
+export const taskFailed = (message: unknown, info = 'usage_limit_exceeded'): CodexRec => ({
+ type: 'event_msg',
+ payload: {
+ type: 'task_complete',
+ turn_id: 'turn-synthetic',
+ last_agent_message: null,
+ started_at: 1790000000,
+ completed_at: 1790000001,
+ duration_ms: 1000,
+ error: { codex_error_info: info, message }
+ }
+})
+export const turnAborted = (reason: unknown = 'interrupted'): CodexRec => ({
+ type: 'event_msg',
+ payload: { type: 'turn_aborted', turn_id: 'turn-synthetic', reason, started_at: 1790000000, completed_at: 1790000002, duration_ms: 2000 }
+})
+export const tokenCount = (): CodexRec => ({
+ type: 'event_msg',
+ payload: {
+ type: 'token_count',
+ info: {
+ total_token_usage: { input_tokens: 20000, cached_input_tokens: 18000, output_tokens: 300, reasoning_output_tokens: 100, total_tokens: 20300 },
+ last_token_usage: { input_tokens: 12000, cached_input_tokens: 11000, output_tokens: 200, reasoning_output_tokens: 50, total_tokens: 12200 },
+ model_context_window: 258400
+ },
+ rate_limits: { primary: null, secondary: null }
+ }
+})
+export const tokenUsageRecord = (): CodexRec => ({
+ type: 'token_usage_record',
+ payload: { response_id: 'resp_synthetic', session_id: CODEX_SID, thread_id: CODEX_SID, turn_id: 'turn-synthetic', root_turn_id: 'turn-synthetic', usage: {}, turn_token_usage: {}, thread_token_usage: {} }
+})
+export const worldState = (): CodexRec => ({ type: 'world_state', payload: { full: true, state: {} } })
+export const threadSettingsApplied = (): CodexRec => ({
+ type: 'event_msg',
+ payload: { type: 'thread_settings_applied', thread_id: CODEX_SID, thread_settings: {} }
+})
+export const interAgentMeta = (): CodexRec => ({ type: 'inter_agent_communication_metadata', payload: { trigger_turn: true } })
+export const compacted = (): CodexRec => ({
+ type: 'compacted',
+ payload: {
+ message: '',
+ replacement_history: [
+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'An earlier prompt, as the model sees it.' }] },
+ { type: 'compaction', encrypted_content: 'gAAAAsynthetic' }
+ ],
+ replacement_history_metadata: [],
+ window_id: 'w2',
+ window_number: 2,
+ previous_window_id: 'w1',
+ first_window_id: 'w1',
+ compaction_response_id: 'resp_compact',
+ latest_token_usage_record: null
+ }
+})
+
+// ── What the model sees (response_item) ──────────────────────────────────────────────────────────
+const passthrough = { internal_chat_message_metadata_passthrough: {} }
+/** A model-side `message`: `role` user / developer carries injected context; assistant carries
+ * `output_text` and a `phase` (commentary | final_answer). */
+export const riMessage = (role: string, texts: unknown[], phase?: string): CodexRec => ({
+ type: 'response_item',
+ payload: {
+ type: 'message',
+ id: 'msg_synthetic',
+ role,
+ content: texts.map((t) =>
+ typeof t === 'string' ? { type: role === 'assistant' ? 'output_text' : 'input_text', text: t } : t
+ ),
+ ...(phase ? { phase } : {}),
+ ...passthrough
+ }
+})
+export const assistantText = (text: string, phase = 'final_answer'): CodexRec => riMessage('assistant', [text], phase)
+export const reasoning = (): CodexRec => ({
+ type: 'response_item',
+ payload: { type: 'reasoning', id: 'rs_synthetic', summary: [], encrypted_content: 'gAAAAsyntheticreasoning', ...passthrough }
+})
+export const functionCall = (callId: string, name: string, args: unknown, namespace?: string): CodexRec => ({
+ type: 'response_item',
+ payload: {
+ type: 'function_call',
+ id: 'fc_synthetic',
+ name,
+ ...(namespace ? { namespace } : {}),
+ arguments: typeof args === 'string' ? args : JSON.stringify(args),
+ call_id: callId,
+ ...passthrough
+ }
+})
+export const functionOutput = (callId: string, output: unknown): CodexRec => ({
+ type: 'response_item',
+ payload: { type: 'function_call_output', id: 'fco_synthetic', call_id: callId, output, ...passthrough },
+ metadata: { client_authored: false, fallback_token_limit_override: null }
+})
+export const customToolCall = (callId: string, name: string, input: unknown): CodexRec => ({
+ type: 'response_item',
+ payload: { type: 'custom_tool_call', id: 'ctc_synthetic', status: 'completed', call_id: callId, name, input, ...passthrough }
+})
+export const customToolOutput = (callId: string, output: unknown): CodexRec => ({
+ type: 'response_item',
+ payload: { type: 'custom_tool_call_output', id: 'ctco_synthetic', call_id: callId, output, ...passthrough },
+ metadata: { client_authored: false, fallback_token_limit_override: null }
+})
+export const toolSearchCall = (callId: string, query: string): CodexRec => ({
+ type: 'response_item',
+ payload: { type: 'tool_search_call', id: 'ts_synthetic', call_id: callId, status: 'completed', execution: 'client', arguments: { query }, ...passthrough }
+})
+export const toolSearchOutput = (callId: string): CodexRec => ({
+ type: 'response_item',
+ payload: { type: 'tool_search_output', call_id: callId, status: 'completed', execution: 'client', tools: [{ name: 'demo_tool' }], ...passthrough }
+})
+export const riAgentMessage = (author: string, recipient: string, text: string): CodexRec => ({
+ type: 'response_item',
+ payload: {
+ type: 'agent_message',
+ id: 'am_synthetic',
+ author,
+ recipient,
+ content: [
+ { type: 'input_text', text },
+ { type: 'encrypted_content', encrypted_content: 'gAAAAsyntheticagent' }
+ ],
+ ...passthrough
+ }
+})
+
+// ── What the UI saw (event_msg) ──────────────────────────────────────────────────────────────────
+/** LEGACY format (≤ 0.146): the prompt exactly as the user typed it. */
+export const userMessageEvent = (message: unknown): CodexRec => ({
+ type: 'event_msg',
+ payload: { type: 'user_message', message, images: [], local_images: [], text_elements: [] }
+})
+/** LEGACY format: the UI's copy of an assistant message (duplicates the response_item). */
+export const agentMessageEvent = (message: string, phase = 'final_answer'): CodexRec => ({
+ type: 'event_msg',
+ payload: { type: 'agent_message', message, phase, memory_citation: null }
+})
+const itemCompleted = (item: Record<string, unknown>): CodexRec => ({
+ type: 'event_msg',
+ payload: { type: 'item_completed', thread_id: CODEX_SID, turn_id: 'turn-synthetic', item, started_at_ms: 1790000000000, completed_at_ms: 1790000000100 }
+})
+/** PAGINATED format (≥ 0.151): the prompt exactly as the user typed it. `content` items are
+ * `{type:'text'}` and, for a pasted image, `{type:'local_image'}`. */
+export const userMessageItem = (content: unknown[]): CodexRec =>
+ itemCompleted({
+ type: 'UserMessage',
+ id: 'item_user',
+ client_id: 'client_synthetic',
+ content: content.map((c) => (typeof c === 'string' ? { type: 'text', text: c, text_elements: [] } : c))
+ })
+/** PAGINATED format: the UI's copy of an assistant message (duplicates the response_item). */
+export const agentMessageItem = (text: string, phase = 'final_answer'): CodexRec =>
+ itemCompleted({ type: 'AgentMessage', id: 'item_agent', phase, content: [{ type: 'Text', text }] })
+export const commandExecutionItem = (): CodexRec =>
+ itemCompleted({
+ type: 'CommandExecution',
+ id: 'item_cmd',
+ command: ['/bin/bash', '-lc', 'ls'],
+ cwd: '/srv/demo',
+ process_id: '1',
+ source: 'unified_exec_startup',
+ status: 'completed',
+ parsed_cmd: [{ type: 'list_files', cmd: 'ls' }],
+ aggregated_output: 'a.txt\n',
+ formatted_output: 'a.txt',
+ stdout: 'a.txt\n',
+ stderr: '',
+ exit_code: 0,
+ duration: { secs: 0, nanos: 1000000 }
+ })
+export const fileChangeItem = (): CodexRec =>
+ itemCompleted({ type: 'FileChange', id: 'item_fc', status: 'completed', stdout: '', stderr: '', changes: { '/srv/demo/a.txt': { type: 'add', content: 'x\n' } } })
+export const reasoningItem = (): CodexRec =>
+ itemCompleted({ type: 'Reasoning', id: 'item_rs', summary_text: [], raw_content: [] })
+export const extensionItem = (): CodexRec =>
+ itemCompleted({ type: 'Extension', id: 'item_ext', kind: 'clock.sleep', durationMs: 1000 })
+export const contextCompactionItem = (): CodexRec => itemCompleted({ type: 'ContextCompaction', id: 'item_cc' })
+export const subAgentActivityItem = (): CodexRec =>
+ itemCompleted({ type: 'SubAgentActivity', id: 'item_sa', kind: 'completed', agent_path: '/root/worker_1', agent_thread_id: 'thread-child' })
+
+/** The model-side twin of a typed prompt, plus the context codex injects before it. The typed text
+ * is ALSO written here (as a role:user input_text) — the reader must not show it twice. */
+export const injectedContext = (): CodexRec[] => [
+ riMessage('developer', ['<permissions instructions>\nApprovals are on-request.\n</permissions instructions>']),
+ riMessage('user', ['# AGENTS.md instructions for /srv/demo\n\n<INSTRUCTIONS>\nBe terse.\n</INSTRUCTIONS>']),
+ riMessage('user', ['<environment_context>\n <cwd>/srv/demo</cwd>\n</environment_context>'])
+]