Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

refactor: implement sliding-window P2P retry logic and enable agent-specific CODEX_HOME path resolution for model cache and hooks

0xken15191c8127c5e4
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 37c3faecf..92bdd17c7 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2282,6 +2282,7 @@ async function runForeground(session: AuthSession): Promise<void> {
const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, {
bornOnly: true,
pid: observed.processIdentity.pid,
+ codexHome: agent.codexHome ?? undefined,
})
if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return
sessionId = found.sessionId
@@ -3344,6 +3345,11 @@ async function runForeground(session: AuthSession): Promise<void> {
// normally launched one. The key is never printed.
console.log(describeGridLaunch(engine, grid))
}
+ // A Codex agent pointed at a profile OTHER than this machine's default reads hooks.json from
+ // THAT folder, not the one `harness login` already installed into — without this, such an agent
+ // fires no hook at all (no SessionStart/UserPromptSubmit/Stop) and never streams a single event.
+ // Idempotent, so paying this on every create against an already-set-up profile is free.
+ if (codexHome && !env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome)
// Do not start a second interactive login shell merely to ask whether the engine is installed.
// The pane's own shell performs the same check before exec, and installs only when necessary.
// This removes ~1s of shell startup from the click-to-terminal critical path.
diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.ts
index dc859da53..1d7785f6d 100644
--- a/cli/src/lib/hooks.spec.ts
+++ b/cli/src/lib/hooks.spec.ts
@@ -60,6 +60,29 @@ describe('Codex hook installation', () => {
expect(readFileSync(file, 'utf-8')).toBe(first)
})
+ it('installs into a custom CODEX_HOME profile, with a matching --codex-home baked in', async () => {
+ const customProfile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
+ try {
+ const { installCodexHooks } = await loadHooks()
+ installCodexHooks(19473, customProfile)
+
+ const profileFile = join(customProfile, 'hooks.json')
+ const first = readFileSync(profileFile, 'utf-8')
+ const parsed = JSON.parse(first)
+ const cmd = parsed.hooks.SessionStart[0].hooks[0].command
+ expect(cmd).toContain(`--codex-home '${customProfile}'`)
+
+ // The default profile is untouched by installing into a different one.
+ expect(existsSync(join(codexHome, 'hooks.json'))).toBe(false)
+
+ // Idempotent: a second install into the same profile is a no-op.
+ installCodexHooks(19473, customProfile)
+ expect(readFileSync(profileFile, 'utf-8')).toBe(first)
+ } finally {
+ rmSync(customProfile, { recursive: true, force: true })
+ }
+ })
+
it('leaves malformed user hook configuration untouched', async () => {
const file = join(codexHome, 'hooks.json')
writeFileSync(file, '{not-json')
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 97e5439b5..0bde0f3e1 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -14,7 +14,6 @@ import { VERSION } from '../version.js'
import { managedNodePath } from './nodeRuntime.js'
const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
-const CODEX_HOOKS_PATH = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'hooks.json')
const GROK_HOOKS_PATH = join(env.GROK_HOME, 'hooks', 'harness.json')
const CURSOR_HOOKS_PATH = join(process.env.CURSOR_HOME || join(homedir(), '.cursor'), 'hooks.json')
// agy reads hooks from its SHARED customization root (~/.gemini/config), not from its own state dir —
@@ -57,7 +56,13 @@ function shellQuote(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`
}
-function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok' | 'agy' | 'copilot'): string {
+function command(
+ port: number,
+ engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok' | 'agy' | 'copilot',
+ // Only ever non-default for 'codex': a per-agent CODEX_HOME profile gets its OWN hooks.json, and
+ // that file's baked --codex-home must match where it actually lives (see installCodexHooks).
+ codexHome: string = env.CODEX_HOME,
+): string {
return [
// Absolute, never the bare word `node`. This string is executed later by the ENGINE, in a shell
// whose PATH is none of our business — and since the product ships its own Node, a computer with
@@ -68,7 +73,7 @@ function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes'
'--port', String(port),
'--data-dir', shellQuote(env.ADAPTER_DATA_DIR),
'--claude-projects-dir', shellQuote(env.CLAUDE_PROJECTS_DIR),
- '--codex-home', shellQuote(env.CODEX_HOME),
+ '--codex-home', shellQuote(codexHome),
'--grok-home', shellQuote(env.GROK_HOME),
'--cursor-home', shellQuote(env.CURSOR_HOME),
'--hermes-home', shellQuote(env.HERMES_HOME),
@@ -142,22 +147,30 @@ function writeJsonAtomic(file: string, value: unknown): void {
renameSync(tmp, file)
}
-/** Merge Machine's user-level Codex hooks without replacing unrelated hooks. A malformed existing file
- * is left untouched: silently replacing it could disable user security/automation hooks. */
-export function installCodexHooks(port: number): void {
+/**
+ * Merge Machine's user-level Codex hooks without replacing unrelated hooks. A malformed existing
+ * file is left untouched: silently replacing it could disable user security/automation hooks.
+ *
+ * `codexHome` defaults to this machine's own default profile, but a Codex agent launched against a
+ * different CODEX_HOME profile (see `Agent.codexHome`/`agent_create`) reads hooks.json from THAT
+ * folder, not this one — so `onCreateAgent` calls this again with the chosen profile before
+ * spawning such an agent. Idempotent either way.
+ */
+export function installCodexHooks(port: number, codexHome: string = env.CODEX_HOME): void {
+ const hooksPath = join(codexHome, 'hooks.json')
let settings: Settings = {}
- if (existsSync(CODEX_HOOKS_PATH)) {
+ if (existsSync(hooksPath)) {
try {
- settings = JSON.parse(readFileSync(CODEX_HOOKS_PATH, 'utf-8')) as Settings
+ settings = JSON.parse(readFileSync(hooksPath, 'utf-8')) as Settings
} catch (err) {
- console.error(`[hooks] Codex hooks file is invalid JSON; leaving it unchanged: ${CODEX_HOOKS_PATH}`)
+ console.error(`[hooks] Codex hooks file is invalid JSON; leaving it unchanged: ${hooksPath}`)
console.error('[hooks] fix the file, then restart harness login')
return
}
}
if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
- const cmd = command(port, 'codex')
+ const cmd = command(port, 'codex', codexHome)
const required: Array<{ event: 'SessionStart' | 'UserPromptSubmit'; matcher?: string }> = [
{ event: 'SessionStart', matcher: 'startup|resume|clear|compact' },
{ event: 'UserPromptSubmit' },
@@ -177,12 +190,12 @@ export function installCodexHooks(port: number): void {
}
if (!changed) {
- console.log('[hooks] Codex SessionStart/UserPromptSubmit hooks already installed')
+ console.log(`[hooks] Codex SessionStart/UserPromptSubmit hooks already installed → ${hooksPath}`)
return
}
try {
- writeJsonAtomic(CODEX_HOOKS_PATH, settings)
- console.log(`[hooks] installed Codex SessionStart/UserPromptSubmit hooks → ${CODEX_HOOKS_PATH}`)
+ writeJsonAtomic(hooksPath, settings)
+ console.log(`[hooks] installed Codex SessionStart/UserPromptSubmit hooks → ${hooksPath}`)
console.log('[hooks] Codex requires reviewing these user hooks with /hooks before normal use')
} catch (err) {
console.error('[hooks] failed to write Codex hooks.json:', err)
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 731afc24b..596a8a124 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1043,6 +1043,53 @@ describe('agent identity: the process owns the agent, the session is bound to it
})
})
+ it('validates a Codex transcript against the agent\'s own profile, not the daemon default', async () => {
+ const { validTranscriptPath } = await loadRegistryModule()
+ const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
+ try {
+ const file = join(profile, 'sessions', 'rollout-x.jsonl')
+ mkdirSync(join(file, '..'), { recursive: true })
+ writeFileSync(file, '{}\n')
+ expect(validTranscriptPath('codex', file, profile)).toBe(true)
+ // Without the override this file sits outside the (default) trusted root and must be refused.
+ expect(validTranscriptPath('codex', file)).toBe(false)
+ } finally {
+ rmSync(profile, { recursive: true, force: true })
+ }
+ })
+
+ it('registers a codex session against the profile it was created with', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
+ try {
+ const pending = registry.openPendingAgent({
+ engine: 'codex',
+ runtimes: [{ backend: 'tmux', paneId: '%9' }],
+ cwd: '/tmp/demo',
+ codexHome: profile,
+ })!
+ expect(pending.codexHome).toBe(profile)
+
+ const transcriptFile = join(profile, 'sessions', 'rollout-x.jsonl')
+ mkdirSync(join(transcriptFile, '..'), { recursive: true })
+ writeFileSync(transcriptFile, '{}\n')
+
+ const result = registry.register({
+ engine: 'codex',
+ sessionId: 'sess-1',
+ transcriptPath: transcriptFile,
+ tmuxPane: '%9',
+ cwd: '/tmp/demo',
+ processIdentity: processIdentity(909),
+ })
+ expect(result?.entry.sessionId).toBe('sess-1')
+ expect(result?.entry.codexHome).toBe(profile)
+ } finally {
+ rmSync(profile, { recursive: true, force: true })
+ }
+ })
+
it('keeps a name given before the agent had a session', async () => {
// Names live under the ENGINE session id — that is what survives the launcher and comes back on a
// resume, since the agent id is minted fresh each launch. An agent renamed while still unbound has
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 798254799..3842c07ad 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -485,7 +485,7 @@ function isWithin(root: string, file: string): boolean {
return rel === '' || (!rel.startsWith('..') && !rel.startsWith(`/`) && !rel.startsWith(`\\`))
}
-export function validTranscriptPath(engine: AgentEngine, filePath: string): boolean {
+export function validTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string): boolean {
try {
const actual = realpathSync(filePath)
const root = realpathSync(
@@ -496,7 +496,8 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string): bool
: engine === 'muse'
? join(env.MUSE_HOME, 'sessions')
: engine === 'codex'
- ? join(env.CODEX_HOME, 'sessions')
+ // The specific agent's own CODEX_HOME profile, when it has one — see RegisteredSession.codexHome.
+ ? join(codexHome || env.CODEX_HOME, 'sessions')
: engine === 'grok'
? join(env.GROK_HOME, 'sessions')
: engine === 'agy'
@@ -689,14 +690,17 @@ class Registry {
: null
let bound = typeof raw?.sessionId === 'string' && raw.sessionId !== ''
const rawSessionId = typeof raw?.sessionId === 'string' ? raw.sessionId : ''
+ // This row's own CODEX_HOME profile, when it was created against one other than the default —
+ // see RegisteredSession.codexHome.
+ const rawCodexHome = raw?.codexHome ?? undefined
let repairedCodexTranscript = false
if (engine === 'codex' && transcriptPath) {
const meta = readCodexRolloutMeta(transcriptPath)
if (meta?.isSubagent) {
const repaired = meta.parentThreadId === rawSessionId
- ? resolveCodexRollout(rawSessionId, join(env.CODEX_HOME, 'sessions'))
+ ? resolveCodexRollout(rawSessionId, join(rawCodexHome || env.CODEX_HOME, 'sessions'))
: null
- if (!repaired || !validTranscriptPath('codex', repaired) || readCodexRolloutMeta(repaired)?.isSubagent) {
+ if (!repaired || !validTranscriptPath('codex', repaired, rawCodexHome) || readCodexRolloutMeta(repaired)?.isSubagent) {
changed = true
bound = false
transcriptPath = null
@@ -717,7 +721,7 @@ class Registry {
}
if (
(bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)
- || (bound && transcriptPath !== null && !validTranscriptPath(engine, transcriptPath))
+ || (bound && transcriptPath !== null && !validTranscriptPath(engine, transcriptPath, rawCodexHome))
) {
bound = false
transcriptPath = null
@@ -1039,7 +1043,9 @@ class Registry {
// Copilot's session id is a uuid and names the directory its event stream lives in.
|| (engine === 'copilot' && !GROK_SESSION_RE.test(sessionId))
|| (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && engine !== 'grok' && engine !== 'agy' && engine !== 'copilot' && !transcriptPath)
- || (transcriptPath && !validTranscriptPath(engine, transcriptPath))
+ // The already-registered agent (opened at agent_create time) already carries its own
+ // CODEX_HOME profile, if it has one other than the default — see RegisteredSession.codexHome.
+ || (transcriptPath && !validTranscriptPath(engine, transcriptPath, processAgent?.codexHome ?? undefined))
) return null
if (engine === 'codex' && transcriptPath && readCodexRolloutMeta(transcriptPath)?.isSubagent) return null
@@ -1110,6 +1116,10 @@ class Registry {
title: titleDisplayName(input.title ?? existing?.title ?? null),
model: modelString(input.model) ?? existing?.model ?? null,
cliVersion: input.cliVersion ?? existing?.cliVersion ?? null,
+ // Chosen once at agent_create time and never re-derived (unlike `grid`, which openProcessAgent
+ // re-reads off the live process on every discovery) — a hook-triggered bind must carry it
+ // forward or the very first SessionStart hook would silently wipe the agent's chosen profile.
+ codexHome: existing?.codexHome ?? null,
processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,
registeredAt: existing?.registeredAt ?? now,
updatedAt: now,
diff --git a/cli/src/lib/remoteRelay.spec.ts b/cli/src/lib/remoteRelay.spec.ts
index 20201916d..67f00c593 100644
--- a/cli/src/lib/remoteRelay.spec.ts
+++ b/cli/src/lib/remoteRelay.spec.ts
@@ -20,8 +20,7 @@ function fakeEntry(overrides: Partial<Record<string, unknown>> = {}) {
p2pStreams: new Set<string>(),
streams: new Set<string>(),
p2pMigrating: new Map<string, number>(),
- p2pRetryCount: 0,
- p2pRetryLifetimeTotal: 0,
+ p2pRetryTimestamps: [] as number[],
p2pRetryTimer: null,
upgradeAttempts: 0,
upgradeTimer: null,
@@ -161,23 +160,23 @@ describe('RemoteRelayPool p2p retry policy', () => {
demoteP2p: (machineId: string, entry: ReturnType<typeof fakeEntry>, reason: string) => void
}
- it('schedules up to 3 retries (i.e. 4 attempts total: 1 initial + 3 retries), then refuses a 4th', () => {
+ it('schedules up to 10 retries within an hour, then refuses an 11th', () => {
vi.useFakeTimers()
- const RETRY_MAX = 3 // mirrors the unexported P2P_RETRY_MAX constant in remoteRelay.ts
+ const HOURLY_CAP = 10 // mirrors the unexported P2P_RETRY_HOURLY_CAP constant in remoteRelay.ts
try {
const entry = fakeEntry()
// The initial attempt itself is NOT scheduled through scheduleP2pRetry (it fires unconditionally
// at e2e_welcome) — this exercises only the retries that follow each subsequent failure.
- for (let i = 1; i <= RETRY_MAX; i++) {
+ for (let i = 1; i <= HOURLY_CAP; i++) {
pool.scheduleP2pRetry('machine-1', entry)
expect(entry.p2pRetryTimer, `retry #${i} should have been scheduled`).not.toBeNull()
- expect(entry.p2pRetryCount).toBe(i)
+ expect(entry.p2pRetryTimestamps).toHaveLength(i)
vi.advanceTimersByTime(60_000)
entry.p2pRetryTimer = null // the real timer callback nulls this before re-dialing; simulate that
}
- pool.scheduleP2pRetry('machine-1', entry) // one retry past the cap — refused, quota spent
+ pool.scheduleP2pRetry('machine-1', entry) // one retry past the cap — refused, quota spent for this hour
expect(entry.p2pRetryTimer).toBeNull()
- expect(entry.p2pRetryCount).toBe(RETRY_MAX)
+ expect(entry.p2pRetryTimestamps).toHaveLength(HOURLY_CAP)
} finally {
vi.useRealTimers()
}
@@ -191,32 +190,38 @@ describe('RemoteRelayPool p2p retry policy', () => {
const firstTimer = entry.p2pRetryTimer
pool.scheduleP2pRetry('machine-1', entry) // a second failure before the first retry even fires
expect(entry.p2pRetryTimer).toBe(firstTimer)
- expect(entry.p2pRetryCount).toBe(1)
+ expect(entry.p2pRetryTimestamps).toHaveLength(1)
} finally {
vi.useRealTimers()
}
})
- it('a success resets the short-term counter so a later demote gets a fresh budget', () => {
- const entry = fakeEntry({ p2pRetryCount: 3 }) // quota exhausted from a prior run of failures
- entry.p2pRetryCount = 0 // what startP2p's onState does on 'direct' — exercised here directly
- pool.scheduleP2pRetry('machine-1', entry)
- expect(entry.p2pRetryTimer).not.toBeNull()
- expect(entry.p2pRetryCount).toBe(1)
+ it('a retry from over an hour ago ages out of the window, freeing up budget again', () => {
+ vi.useFakeTimers()
+ try {
+ const longAgo = Date.now() - 61 * 60 * 1000 // just past the 1-hour lookback
+ // Quota looks fully spent at a glance (10 timestamps), but every one of them is stale.
+ const entry = fakeEntry({ p2pRetryTimestamps: Array(10).fill(longAgo) })
+ pool.scheduleP2pRetry('machine-1', entry)
+ expect(entry.p2pRetryTimer).not.toBeNull()
+ expect(entry.p2pRetryTimestamps).toHaveLength(1) // the 10 stale ones were pruned, one fresh one added
+ } finally {
+ vi.useRealTimers()
+ }
})
- it('the lifetime cap stops scheduling even with a fresh short-term counter', () => {
- const entry = fakeEntry({ p2pRetryLifetimeTotal: 10 })
+ it('the hourly cap stops scheduling while those attempts are still within the window', () => {
+ const entry = fakeEntry({ p2pRetryTimestamps: Array(10).fill(Date.now()) })
pool.scheduleP2pRetry('machine-1', entry)
expect(entry.p2pRetryTimer).toBeNull()
- expect(entry.p2pRetryCount).toBe(0)
+ expect(entry.p2pRetryTimestamps).toHaveLength(10) // refused — nothing new was recorded
})
it('demoteP2p (case B: was direct, then demoted) schedules a retry through the same policy', () => {
const entry = fakeEntry({ p2pStreams: new Set(['stream-a']) })
pool.demoteP2p('machine-1', entry, 'send_failed')
expect(entry.p2pRetryTimer).not.toBeNull()
- expect(entry.p2pRetryCount).toBe(1)
+ expect(entry.p2pRetryTimestamps).toHaveLength(1)
})
})
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index 0f2769e20..f12fd9c26 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -42,13 +42,17 @@ const HEARTBEAT_MS = 20_000
// A p2p attempt that never reaches 'direct', or one that did and then got demoted mid-session, both
// leave the stream(s) on the ws relay with nothing to bring them back — see scheduleP2pRetry(). One
-// policy for both cases: retry every 60s, capped at 3 retries (4 attempts total) since the last
-// success, reset on the next 'direct'. p2pRetryLifetimeTotal is the belt-and-braces cap across the
-// entry's whole life, so a connection that flaps direct/demoted forever every few minutes cannot
-// retry forever just because each success resets the short-term counter.
+// policy for both cases: retry every 60s, capped at P2P_RETRY_HOURLY_CAP attempts within any trailing
+// hour (tracked in p2pRetryTimestamps, not a plain counter) — a ROLLING window rather than a lifetime
+// total, deliberately: the underlying reason a connection can't reach p2p is often transient at the
+// scale of hours (the machine's public IP changed, a router rebooted, a NAT binding thawed), so a
+// connection that burned its whole budget hours ago should still get to try again now rather than
+// staying stuck on relay for the rest of the daemon's uptime. Old attempts simply age out of the
+// lookback on their own, which is also why there is no separate "reset on a success" step any more —
+// a connection that's been healthy for a while naturally has an empty recent window already.
const P2P_RETRY_DELAY_MS = 60_000
-const P2P_RETRY_MAX = 3
-const P2P_RETRY_LIFETIME_CAP = 10
+const P2P_RETRY_WINDOW_MS = 60 * 60 * 1000
+const P2P_RETRY_HOURLY_CAP = 10
// How long a stream may sit in p2pMigrating before the sweep (piggybacked on heartbeatTimer) gives up
// on it and lets the ordinary demote-on-mismatch rule apply again.
const P2P_MIGRATION_TTL_MS = 30_000
@@ -100,11 +104,9 @@ interface Entry {
streams: Set<string>
/** streamId -> when its migration to p2p started, so a stuck one can be swept off the heartbeat. */
p2pMigrating: Map<string, number>
- /** Retries since the last 'direct' (or since entry creation, if never direct). Reset to 0 on 'direct'. */
- p2pRetryCount: number
- /** Retries across this entry's whole life — never reset. The safeguard against a flapping connection
- * retrying forever purely because each success resets p2pRetryCount. */
- p2pRetryLifetimeTotal: number
+ /** Timestamps (ms epoch) of retry attempts within the trailing P2P_RETRY_WINDOW_MS — see
+ * scheduleP2pRetry(). A rolling window, not a lifetime counter: old attempts age out on their own. */
+ p2pRetryTimestamps: number[]
p2pRetryTimer: ReturnType<typeof setTimeout> | null
/** TURN-to-direct upgrade trials — see scheduleUpgradeAttempt()/attemptUpgrade()/promoteToDirect().
* Entirely separate bookkeeping from p2pMigrating/p2pRetry*: this never touches entry.p2p (the live,
@@ -123,8 +125,9 @@ interface Entry {
* than guessed closed (see promoteToDirect()) — cleaned up wherever the entry itself is torn down. */
upgradeOrphan: TerminalP2pInitiator | null
/** True once this entry has either cut over to a true direct pair, or spent all 3 attempts without
- * one — either way, stop trying. Never reset (unlike p2pRetryCount): there is no "next demote" to
- * re-arm a budget for here, since staying on direct or giving up are both permanent for this entry. */
+ * one — either way, stop trying. Never reset (unlike p2pRetryTimestamps' rolling window): there is
+ * no "next demote" to re-arm a budget for here, since staying on direct or giving up are both
+ * permanent for this entry. */
upgradeDone: boolean
}
@@ -268,8 +271,7 @@ export class RemoteRelayPool {
p2pStreams: new Set(),
streams: new Set(),
p2pMigrating: new Map(),
- p2pRetryCount: 0,
- p2pRetryLifetimeTotal: 0,
+ p2pRetryTimestamps: [],
p2pRetryTimer: null,
upgradeAttempts: 0,
upgradeTimer: null,
@@ -563,7 +565,8 @@ export class RemoteRelayPool {
onState: (state, setupMs, reason) => {
if (state === 'direct') {
wasDirect = true
- entry.p2pRetryCount = 0 // a fresh success re-arms the full retry budget for the NEXT demote, if any
+ // No explicit retry-budget reset here any more: p2pRetryTimestamps is a rolling window, so a
+ // connection that's been healthy for a while already has an empty recent window on its own.
// 'relayed' distinguishes a Cloudflare TURN path from a truly direct one. Both are "p2p" as far
// as the terminal is concerned, but only one of them is billed per GB.
const relayed = p2p.transport === 'relay'
@@ -695,16 +698,18 @@ export class RemoteRelayPool {
* or reached it once and then got demoted. Either way `entry.p2p` is null here (the failed/demoted
* instance already cleared it) so `startP2p`'s own guard will accept the retry once the timer fires.
*
- * p2pRetryCount is reset to 0 on every 'direct' (see startP2p's onState), so a demote long after a
- * clean run gets the full budget again — p2pRetryLifetimeTotal, which never resets, is what stops a
- * connection that flaps direct/demoted forever from retrying forever.
+ * The budget is a ROLLING window (P2P_RETRY_HOURLY_CAP attempts within the trailing
+ * P2P_RETRY_WINDOW_MS), not a lifetime total — see the constants' own comment for why: the reason a
+ * connection can't reach p2p right now is often no longer true an hour from now (a changed IP, a
+ * router reboot, a NAT binding that thawed), and a connection that burned its whole budget hours ago
+ * should still get another shot rather than being stuck on relay for the rest of the daemon's uptime.
*/
private scheduleP2pRetry(machineId: string, entry: Entry): void {
if (entry.p2pRetryTimer) return
- if (entry.p2pRetryLifetimeTotal >= P2P_RETRY_LIFETIME_CAP) return
- if (entry.p2pRetryCount >= P2P_RETRY_MAX) return
- entry.p2pRetryCount++
- entry.p2pRetryLifetimeTotal++
+ const windowStart = Date.now() - P2P_RETRY_WINDOW_MS
+ entry.p2pRetryTimestamps = entry.p2pRetryTimestamps.filter((t) => t > windowStart)
+ if (entry.p2pRetryTimestamps.length >= P2P_RETRY_HOURLY_CAP) return
+ entry.p2pRetryTimestamps.push(Date.now())
entry.p2pRetryTimer = setTimeout(() => {
entry.p2pRetryTimer = null
if (this.entries.get(machineId) !== entry) return // entry was torn down/replaced meanwhile
diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.ts
index 38be5fde2..a69f50ac6 100644
--- a/cli/src/lib/runtimeProfile.ts
+++ b/cli/src/lib/runtimeProfile.ts
@@ -1205,7 +1205,10 @@ export class RuntimeProfileManager {
const output: RuntimeModelOption[] = []
const seen = new Set<string>()
let cache: CodexCache = {}
- try { cache = JSON.parse(await readFile(join(env.CODEX_HOME, 'models_cache.json'), 'utf8')) as CodexCache } catch { /* current state fallback below */ }
+ // This agent's own CODEX_HOME profile, when it has one other than the default (see
+ // RegisteredSession.codexHome) — otherwise the picker would show the default profile's cached
+ // models for an agent that is not actually running on it.
+ try { cache = JSON.parse(await readFile(join(session.codexHome || env.CODEX_HOME, 'models_cache.json'), 'utf8')) as CodexCache } catch { /* current state fallback below */ }
for (const item of Array.isArray(cache.models) ? cache.models : []) {
const model = text(item.slug)
if (!model || item.visibility === 'hide') continue
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
index a924fda80..c92660a6f 100644
--- a/cli/src/lib/sessionRepair.spec.ts
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -281,3 +281,43 @@ describe('session repair — Grok', () => {
await expect(findLiveSession('grok', CWD, STARTED_AT)).resolves.toEqual({ sessionId: id, transcriptPath: file })
})
})
+
+/** A codex rollout-shaped transcript: session_meta line one, under <codexHome>/sessions/. */
+function writeCodexRollout(codexHome: string, id: string, cwd: string, mtimeMs: number): string {
+ const dir = join(codexHome, 'sessions')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, `rollout-2026-08-03T09-00-00-${id}.jsonl`)
+ writeFileSync(file, `${JSON.stringify({ type: 'session_meta', payload: { id, cwd } })}\n`)
+ utimesSync(file, new Date(mtimeMs), new Date(mtimeMs))
+ return file
+}
+
+describe('session repair — Codex profiles', () => {
+ it('scans the agent\'s own codexHome profile, not the default', async () => {
+ const profile = tempRoot()
+ const id = 'a1b2c3d4-1111-4a4a-8a8a-000000000001'
+ const file = writeCodexRollout(profile, id, CWD, STARTED_AT + 5_000)
+ vi.resetModules()
+ const { findLiveSession } = await import('./sessionRepair.js')
+
+ await expect(findLiveSession('codex', CWD, STARTED_AT, { codexHome: profile, bornOnly: true }))
+ .resolves.toEqual({ sessionId: id, transcriptPath: file })
+ })
+
+ it('finds nothing when no codexHome override is given and the rollout lives in a custom profile', async () => {
+ const profile = tempRoot()
+ const defaultHome = tempRoot() // an empty stand-in default, so the assertion cannot depend on this machine's real ~/.codex
+ const id = 'a1b2c3d4-1111-4a4a-8a8a-000000000002'
+ writeCodexRollout(profile, id, CWD, STARTED_AT + 5_000)
+ vi.resetModules()
+ process.env.CODEX_HOME = defaultHome
+ const { findLiveSession } = await import('./sessionRepair.js')
+
+ try {
+ // No opts.codexHome: falls back to the default CODEX_HOME, which does not contain this rollout.
+ await expect(findLiveSession('codex', CWD, STARTED_AT, { bornOnly: true })).resolves.toBeNull()
+ } finally {
+ delete process.env.CODEX_HOME
+ }
+ })
+})
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index d64e3fb13..3f804983b 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -242,7 +242,9 @@ export async function findLiveSession(
engine: AgentEngine,
cwd: string,
startedAtMs: number,
- opts?: { bornOnly?: boolean; pid?: number },
+ // codexHome: the specific agent's own CODEX_HOME profile, when it isn't this machine's default —
+ // see RegisteredSession.codexHome. Only the 'codex' case below reads it.
+ opts?: { bornOnly?: boolean; pid?: number; codexHome?: string },
): Promise<RepairedSession | null> {
const sinceMs = startedAtMs - START_SLACK_MS
// The DB engines match on a directory STRING, so ask for both spellings of it (see sameDir).
@@ -257,7 +259,7 @@ export async function findLiveSession(
// belongs to a subagent, which must never become an agent of its own.
// Its session id lives INSIDE the file: the name is `rollout-<timestamp>-<id>.jsonl`, so deriving
// the id from the filename produced the literal string "rollout-…" (seen on a live pane).
- return fileEngineSession(join(env.CODEX_HOME, 'sessions'), cwd, startedAtMs, async (path) => {
+ return fileEngineSession(join(opts?.codexHome || env.CODEX_HOME, 'sessions'), cwd, startedAtMs, async (path) => {
const meta = readCodexRolloutMeta(path)
return meta && !meta.isSubagent ? { cwd: meta.cwd, sessionId: meta.id || undefined } : null
}, opts)
diff --git a/cli/src/lib/terminalP2p.ts b/cli/src/lib/terminalP2p.ts
index 683c70eb4..6fd33964c 100644
--- a/cli/src/lib/terminalP2p.ts
+++ b/cli/src/lib/terminalP2p.ts
@@ -21,6 +21,15 @@ export const TERMINAL_P2P_CHANNEL = 'terminal-v1'
*/
export const TERMINAL_P2P_NEGOTIATION_TIMEOUT_MS = 25_000
export const TERMINAL_P2P_MAX_BUFFERED_BYTES = 2 * 1024 * 1024
+/**
+ * ICE's `disconnected` state means checks are currently failing but the agent is still trying — it
+ * can recover back to `connected` on its own within seconds after a brief wifi drop, NAT rebind, or
+ * packet-loss blip, which is the whole reason WebRTC has this as a state distinct from `failed`.
+ * Treating it as instantly fatal (as this file used to) killed the whole p2p connection over
+ * hiccups that would have cleared up on their own. This is how long to wait for that self-recovery
+ * before giving up and reporting it as a real failure ourselves.
+ */
+export const TERMINAL_P2P_DISCONNECT_GRACE_MS = 5_000
export const TERMINAL_P2P_SIGNAL_TYPES = new Set([
'p2p_offer',
@@ -222,6 +231,7 @@ export class TerminalP2pInitiator {
private starting = false
private finished = false
private timeout: ReturnType<typeof setTimeout> | null = null
+ private disconnectGraceTimer: ReturnType<typeof setTimeout> | null = null
private waiters: ReadyWaiter[] = []
private sawAnswer = false
@@ -405,6 +415,7 @@ export class TerminalP2pInitiator {
this.ready = false
if (this.timeout) clearTimeout(this.timeout)
this.timeout = null
+ this.clearDisconnectGrace()
for (const waiter of this.waiters.splice(0)) waiter(false)
if (notifyPeer) {
this.deps.sendSignal('p2p_abort', {
@@ -421,11 +432,27 @@ export class TerminalP2pInitiator {
this.deps.onState?.('closed', this.now() - this.startedAt, reason)
}
+ private clearDisconnectGrace(): void {
+ if (this.disconnectGraceTimer) { clearTimeout(this.disconnectGraceTimer); this.disconnectGraceTimer = null }
+ }
+
private wirePeer(pc: RTCPeerConnection): void {
pc.connectionStateChange.subscribe((state) => {
if (this.pc !== pc || this.finished) return
this.step(`ice-${state}`)
- if (state === 'failed' || state === 'disconnected') this.fail(`peer_${state}`)
+ if (state === 'failed') { this.clearDisconnectGrace(); this.fail('peer_failed'); return }
+ if (state === 'disconnected') {
+ if (this.disconnectGraceTimer) return // already waiting on a previous disconnect
+ this.disconnectGraceTimer = setTimeout(() => {
+ this.disconnectGraceTimer = null
+ if (this.pc === pc && !this.finished) this.fail('peer_disconnected_timeout')
+ }, TERMINAL_P2P_DISCONNECT_GRACE_MS)
+ this.disconnectGraceTimer.unref?.()
+ return
+ }
+ // Any other state (back to 'connected', or 'connecting' mid-ICE-restart) means it self-healed —
+ // a pending grace timer from an earlier 'disconnected' no longer applies.
+ this.clearDisconnectGrace()
})
}
@@ -472,6 +499,7 @@ interface ResponderEntry {
channel: RTCDataChannel | null
ready: boolean
timeout: ReturnType<typeof setTimeout>
+ disconnectGraceTimer: ReturnType<typeof setTimeout> | null
closing: boolean
}
@@ -553,6 +581,7 @@ export class TerminalP2pResponderPool {
if (entry.closing) return
entry.closing = true
clearTimeout(entry.timeout)
+ if (entry.disconnectGraceTimer) clearTimeout(entry.disconnectGraceTimer)
if (notifyPeer) {
this.deps.sendSignal(connId, 'p2p_abort', {
sessionId: entry.sessionId,
@@ -649,6 +678,7 @@ export class TerminalP2pResponderPool {
channel: null,
ready: false,
closing: false,
+ disconnectGraceTimer: null,
timeout: setTimeout(() => {
if (entry.ready) this.deps.onUnavailable?.(connId, 'negotiation_timeout')
void (stillCurrent() ? this.closeConnection(connId, 'negotiation_timeout') : this.closeShadow(connId, 'negotiation_timeout'))
@@ -670,10 +700,26 @@ export class TerminalP2pResponderPool {
): void {
entry.pc.connectionStateChange.subscribe((state) => {
if (!isCurrent() || entry.closing) return
- if (state === 'failed' || state === 'disconnected') {
- if (entry.ready && this.entries.get(connId) === entry) this.deps.onUnavailable?.(connId, `peer_${state}`)
- void close(`peer_${state}`)
+ if (state === 'failed') {
+ if (entry.disconnectGraceTimer) { clearTimeout(entry.disconnectGraceTimer); entry.disconnectGraceTimer = null }
+ if (entry.ready && this.entries.get(connId) === entry) this.deps.onUnavailable?.(connId, 'peer_failed')
+ void close('peer_failed')
+ return
+ }
+ if (state === 'disconnected') {
+ if (entry.disconnectGraceTimer) return // already waiting on a previous disconnect
+ // Same reasoning as TerminalP2pInitiator's wirePeer: 'disconnected' is ICE still trying, not a
+ // verdict — give it a beat to recover on its own before treating this as a real failure.
+ entry.disconnectGraceTimer = setTimeout(() => {
+ entry.disconnectGraceTimer = null
+ if (!isCurrent() || entry.closing) return
+ if (entry.ready && this.entries.get(connId) === entry) this.deps.onUnavailable?.(connId, 'peer_disconnected_timeout')
+ void close('peer_disconnected_timeout')
+ }, TERMINAL_P2P_DISCONNECT_GRACE_MS)
+ entry.disconnectGraceTimer.unref?.()
+ return
}
+ if (entry.disconnectGraceTimer) { clearTimeout(entry.disconnectGraceTimer); entry.disconnectGraceTimer = null }
})
entry.pc.onDataChannel.subscribe((channel) => {
if (!isCurrent() || channel.label !== TERMINAL_P2P_CHANNEL) {