Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/plans/2026-11-28-native-codex-transcript-identity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Restore fresh native Codex transcript ownership

## Evidence

A fresh native Codex 0.172.0 pane can process prompts while Agent Code has no attached rollout.
A resumed pane already has its exact UUID and can read its transcript.
A disposable 0.172.0 TUI emitted SessionStart with source startup, a UUID and a rollout path.
The filename UUID equalled the root session_meta.id and the recorded source was cli.
The existing exact-ID locator and lease validate a candidate before tailing. Use that path.

## Implementation and verification

1. Install a private startup-only receipt for each fresh native launch. Keep reporting and user hooks independent.
2. Accept only root startup identities in the current launch. Wait for the verified rollout to become readable.
3. Reuse the existing exact-ID registration and stop ownership work on disposal or successful attachment.
4. Exercise concurrent same-directory launches, delayed files, invalid evidence, cleanup and real CLI compatibility.

Refs #1565

## Results

Two installed Codex 0.172.0 TUIs shared a disposable home and cwd, with a localhost fixture and no TLDR or proxy. Both returned their own marker from the application transcript and distinct root session IDs. The personal SessionStart hook ran for both launches. Removing the launch identity hook reproduced the empty transcript on the same test.

The receipt can arrive before headless startup or rollout creation. The existing exact-ID locator still owns the final filename, metadata and lease checks. Disabled or unsupported hooks provide no additional evidence. Existing panes need a fresh launch or a resume by known identity.
42 changes: 24 additions & 18 deletions src/providers/codex/runtime/codexSession.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { excludeExternalControlFromCodex } from '@providers/shared/runtime/externalControlExclusion.js'
import { createCodexTldrHooks } from '@providers/shared/runtime/tldrHooks.js'
import type { PrivateCodexTldrHooks } from '@providers/shared/runtime/tldrHooks.js'
import { createCodexLaunchHooks } from '@providers/shared/runtime/tldrHooks.js'
import type { PrivateCodexLaunchHooks } from '@providers/shared/runtime/tldrHooks.js'
import { EventEmitter } from 'events'
import { mkdir } from 'fs/promises'
import { join } from 'path'
Expand Down Expand Up @@ -232,16 +232,16 @@ type CodexStartAttempt = {
resumeRolloutPreparation: CodexResumeRolloutPreparation | null
pty: ReturnType<typeof ptySpawn> | null
headless: CodexHeadless | null
/** Private TLDR hook header file (#917). Generation-owned like the proxy: a
* cancelled start must delete the file holding its bearer. */
tldrHooks: PrivateCodexTldrHooks | null
/** Generation-owned hook receipts and optional TLDR credentials. A cancelled
* start revokes its watcher and removes its private directory. */
launchHooks: PrivateCodexLaunchHooks | null
rollbackPromise: Promise<void> | null
}

export class CodexSession extends EventEmitter {
private headless: CodexHeadless | null = null
private pty: ReturnType<typeof ptySpawn> | null = null
private tldrHooks: PrivateCodexTldrHooks | null = null
private launchHooks: PrivateCodexLaunchHooks | null = null
private exited = false
private composerReady = false
/** The native-composer readiness last published after the startup latch
Expand Down Expand Up @@ -325,7 +325,7 @@ export class CodexSession extends EventEmitter {
resumeRolloutPreparation: null,
pty: null,
headless: null,
tldrHooks: null,
launchHooks: null,
rollbackPromise: null,
}
// WHY generation identity, rather than a permanent `stopped` boolean, is
Expand Down Expand Up @@ -469,17 +469,19 @@ export class CodexSession extends EventEmitter {
// prompt-input profile (which must stay last) and the resume subcommand.
// Created inside the rollback region because the header file holds the
// session bearer.
const tldrHooks = await createCodexTldrHooks(this.builtInMcpServers, TLDR_HOOK_RUNTIME_DIR)
const launchHooks = await createCodexLaunchHooks(
this.builtInMcpServers, TLDR_HOOK_RUNTIME_DIR, !this.resumeSessionId && !this.proxyServer,
)
if (!this.isStartAttemptActive(attempt)) {
// Stop may already have drained this attempt before the file existed;
// this continuation is then its only owner.
try { await tldrHooks?.dispose() } catch { /* best-effort */ }
try { await launchHooks?.dispose() } catch { /* best-effort */ }
return
}
if (tldrHooks) {
attempt.tldrHooks = tldrHooks
this.tldrHooks = tldrHooks
args.push(...tldrHooks.args)
if (launchHooks) {
attempt.launchHooks = launchHooks
this.launchHooks = launchHooks
args.push(...launchHooks.args)
}
if (this.resumeSessionId) {
// WHY app-level replacement waits until this exact boundary: proxy
Expand Down Expand Up @@ -686,6 +688,9 @@ export class CodexSession extends EventEmitter {
}

this.headless.on('exit', ({ exitCode, signal }) => {
// The native process can exit without SessionManager calling stop.
// Revoke only this generation's watcher and private files.
void attempt.launchHooks?.dispose().catch(() => {})
this.exited = true
this.composerReady = false
this.nativeComposerPublished = 'ready'
Expand All @@ -709,6 +714,7 @@ export class CodexSession extends EventEmitter {
const res = await this.headless.start()
if (!this.isStartAttemptActive(attempt)) return
sessionsDir = res.sessionsDir
attempt.launchHooks?.startup?.start(sessionsDir, this.headless)
} catch (err) {
await this.rollbackStart(attempt)
throw err
Expand Down Expand Up @@ -774,7 +780,7 @@ export class CodexSession extends EventEmitter {
resumeRolloutPreparation: this.resumeRolloutPreparation,
pty: this.pty,
headless: this.headless,
tldrHooks: this.tldrHooks,
launchHooks: this.launchHooks,
rollbackPromise: null,
}
owned.cancelled = true
Expand All @@ -790,8 +796,8 @@ export class CodexSession extends EventEmitter {
const preparationTask = owned.resumeRolloutPreparationTask
const preparation = owned.resumeRolloutPreparation
const pty = owned.pty
const tldrHooks = owned.tldrHooks
owned.tldrHooks = null
const launchHooks = owned.launchHooks
owned.launchHooks = null
owned.proxyAdapter = null
owned.proxyServer = null
owned.headless = null
Expand All @@ -811,7 +817,7 @@ export class CodexSession extends EventEmitter {
this.resumeRolloutPreparation = null
}
if (pty && this.pty === pty) this.pty = null
if (tldrHooks && this.tldrHooks === tldrHooks) this.tldrHooks = null
if (launchHooks && this.launchHooks === launchHooks) this.launchHooks = null

owned.rollbackPromise = (async () => {
try { proxyAdapter?.detach() } catch { /* best-effort */ }
Expand Down Expand Up @@ -847,7 +853,7 @@ export class CodexSession extends EventEmitter {
try { pty?.kill() } catch { /* best-effort */ }
// After the PTY is gone, so a final in-flight hook is not denied its
// credential while the provider can still act on the answer.
try { await tldrHooks?.dispose() } catch { /* best-effort */ }
try { await launchHooks?.dispose() } catch { /* best-effort */ }
})()
await owned.rollbackPromise
// WHY keep a cancelled generation discoverable while cleanup is pending.
Expand Down
67 changes: 67 additions & 0 deletions src/providers/codex/runtime/nativeStartupReceipt.system.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { execFileSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import { createCodexLaunchHooks } from '@providers/shared/runtime/tldrHooks.js'

const root = await mkdtemp(join(tmpdir(), 'codex-launch-id-'))
const hooks: NonNullable<Awaited<ReturnType<typeof createCodexLaunchHooks>>>[] = []
afterEach(async () => {
await Promise.all(hooks.splice(0).map(hook => hook.dispose()))
await rm(root, { recursive: true, force: true })
})

async function launch() {
const hook = (await createCodexLaunchHooks([], root, true))!
hooks.push(hook)
const command = JSON.parse(/command=("(?:[^"\\]|\\.)*")/.exec(hook.args.find(arg => arg.startsWith('hooks.SessionStart='))!)![1]!)
const send = (session_id: string, override = {}) => execFileSync('/bin/sh', ['-c', command], {
input: JSON.stringify({ session_id, source: 'startup', hook_event_name: 'SessionStart', ...override }),
})
const observed: string[] = []
const owner = {
observeProviderThreadIdentity: (id: string) => { observed.push(id) },
getSessionMeta: () => observed[0] ? { id: observed[0] } : null,
}
return { hook, send, observed, owner }
}

it('keeps simultaneous private launches separate and waits for the root rollout to become durable', async () => {
const [a, b] = await Promise.all([launch(), launch()])
const sessions = join(root, 'sessions')
await mkdir(sessions)
const [idA, idB, child, stale] = [randomUUID(), randomUUID(), randomUUID(), randomUUID()] as const
async function writeRollout(id: string, source: unknown = 'cli') {
await writeFile(join(sessions, `rollout-2026-11-28T12-00-00-${id}.jsonl`),
JSON.stringify({ type: 'session_meta', payload: { id, cwd: '/same/workspace', source } }) + '\n')
}
await Promise.all([writeRollout(idB), writeRollout(child, { subagent: {} }), writeRollout(stale)])
a.send(stale, { source: 'resume' })
a.send(stale, { hook_event_name: 'SubagentStart', agent_id: stale })
a.send(stale, { transcript_path: `/elsewhere/rollout-date-${idB}.jsonl` })
a.send(child)
a.send(idA)
a.hook.startup!.start(sessions, a.owner)
b.hook.startup!.start(sessions, b.owner)
b.send(idB)
await vi.waitFor(() => expect(b.observed).toEqual([idB]))
expect(a.observed).toEqual([])
await writeRollout(idA)
await vi.waitFor(() => expect(a.observed).toEqual([idA]))
})

it('revokes an observed startup hint when its launch ends before rollout creation', async () => {
const a = await launch()
const id = randomUUID()
const sessions = join(root, 'sessions')
await mkdir(sessions)
a.hook.startup!.start(sessions, a.owner)
a.send(id)
await a.hook.dispose()
await writeFile(join(sessions, `rollout-date-${id}.jsonl`),
JSON.stringify({ type: 'session_meta', payload: { id, source: 'cli' } }) + '\n')
await new Promise(resolve => setTimeout(resolve, 180))
expect(a.observed).toEqual([])
})
137 changes: 137 additions & 0 deletions src/providers/codex/runtime/nativeStartupReceipt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { watch, type FSWatcher } from 'node:fs'
import { open, readFile, readdir, unlink } from 'node:fs/promises'
import { basename, join } from 'node:path'
import { findCodexRolloutPathByThreadId } from 'codex-headless'

type Owner = {
observeProviderThreadIdentity(id: string): void
getSessionMeta(): { id: string } | null
}

const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i
const receiptName = /^start\.[a-zA-Z0-9]+\.json$/

type ThreadHint = { id: string; bucketPath?: string }

function startupThread(raw: string): ThreadHint | null {
const event = JSON.parse(raw)
if (event?.hook_event_name !== 'SessionStart' || event.source !== 'startup' ||
event.agent_id != null || event.agent_type != null ||
typeof event.session_id !== 'string' || !UUID.test(event.session_id)) return null
const id = event.session_id.toLowerCase()
if (event.transcript_path != null && (typeof event.transcript_path !== 'string' ||
!basename(event.transcript_path).toLowerCase().endsWith(`-${id}.jsonl`))) return null
// Only the documented date bucket and filename can select a fast-path read
// under the host's own sessions root. Never open a provider-supplied path.
const bucketPath = typeof event.transcript_path === 'string'
? /\/(\d{4}\/\d{2}\/\d{2}\/rollout-[^/]+\.jsonl)$/.exec(event.transcript_path)?.[1]
: undefined
return { id, bucketPath }
}

async function rootMetadata(file: string, id: string): Promise<boolean> {
const handle = await open(file, 'r')
try {
// Match the locator's bounded prefix. A valid subagent rollout can also
// have a perfectly consistent UUID/filename, but cannot own this TUI.
const prefix = Buffer.alloc(256 * 1024)
const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0)
const line = JSON.parse(prefix.toString('utf8', 0, bytesRead).split('\n', 1)[0]!)
return line.type === 'session_meta' && line.payload?.id?.toLowerCase() === id &&
line.payload.source === 'cli' && line.payload.parent_thread_id == null
} finally { await handle.close() }
}

/** SessionStart is a launch-scoped statement from Codex itself. The file may
* arrive before headless starts or before the first rollout record is durable.
* Keep its UUID until the regular coordinator proves ownership and tails it. */
export class NativeStartupReceipt {
private watcher?: FSWatcher
private timer?: NodeJS.Timeout
private stopped = false

constructor(private directory: string) {}

start(sessionsDir: string, owner: Owner): void {
if (this.stopped) return
let delay = 100
let busy = false
let dirty = false
const inspect = async () => {
if (this.stopped || busy) return
busy = true
let retry = false
try {
retry = await this.offerReceipts(sessionsDir, owner)
} catch { retry = true } finally {
busy = false
if (!this.stopped && (dirty || retry || !this.watcher)) {
const timeout = dirty ? 0 : delay
delay = Math.min(delay * 2, 30_000)
dirty = false
this.timer = setTimeout(() => void inspect(), timeout)
this.timer.unref()
}
}
}
const wake = () => {
clearTimeout(this.timer)
if (busy) dirty = true
else void inspect()
}
try {
this.watcher = watch(this.directory, { persistent: false }, (_event, name) => {
if (name === null || receiptName.test(name)) wake()
})
this.watcher.on('error', () => {
this.watcher?.close()
this.watcher = undefined
wake()
})
} catch { /* Poll at a capped backoff when the OS cannot provide a watcher. */ }
wake()
}

/** Report whether a receipt still needs another look. An unrelated or child
* receipt cannot block the root waiting beside it in the same directory. */
private async offerReceipts(sessionsDir: string, owner: Owner): Promise<boolean> {
let pending = false
for (const name of await readdir(this.directory)) {
if (this.stopped || !receiptName.test(name)) continue
const path = join(this.directory, name)
if (owner.getSessionMeta()) {
this.stop()
await unlink(path).catch(() => {})
return false
}

let hint: ThreadHint | null = null
try { hint = startupThread(await readFile(path, 'utf8')) } catch { /* Invalid or retired receipt. */ }
if (hint) {
try {
const file = hint.bucketPath
? join(sessionsDir, hint.bucketPath)
: await findCodexRolloutPathByThreadId(sessionsDir, hint.id)
if (!file) { pending = true; continue }
if (await rootMetadata(file, hint.id)) {
if (!this.stopped) owner.observeProviderThreadIdentity(hint.id)
pending = true
continue
}
} catch {
// SessionStart can run before the file exists or its header is complete.
pending = true
continue
}
}
await unlink(path).catch(() => {})
}
return pending
}

stop(): void {
this.stopped = true
this.watcher?.close()
clearTimeout(this.timer)
}
}
Loading
Loading