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.

feat: implement automatic Codex profile discovery and integration with agent configuration

0xken15c63b371c3a4d
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index d66127588..ea911bf74 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -24,6 +24,7 @@ import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { ENGINES, type AgentEngine } from './engines/types.js'
import { listDir } from './lib/fsBrowse.js'
+import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
import { parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
import { probeEngines } from './lib/engineProbe.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
@@ -315,6 +316,8 @@ export class BackendSocket {
bypassPermission: boolean
/** A grid to point this agent at instead of the engine's own login; null when none was chosen. */
grid: GridLaunchOverride | null
+ /** A Codex CODEX_HOME folder to launch this agent against instead of `~/.codex`; codex only. */
+ codexHome: string | null
}) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
/** Injectable for queue-isolation tests; production uses the machine-local probe. */
@@ -1422,6 +1425,10 @@ export class BackendSocket {
command: entry.command,
installable: entry.installable,
installCommand: entry.installable ? engineInstallRecipe(entry.engine).command : null,
+ // Static per-CLI-version capability, not a probe result: its mere presence is what
+ // lets an older CLI (which never sends the field) keep reading as "unknown" rather
+ // than "no", per the desktop app's `EngineAvailability.fromJson`.
+ ...(entry.engine === 'codex' ? { supportsCodexHome: true } : {}),
})),
}))
.catch(() => reply(type, requestId, { error: 'ENGINE_PROBE_FAILED' }))
@@ -1520,11 +1527,24 @@ export class BackendSocket {
// that quietly ran on the engine's own login would look like it worked.
const grid = parseGridLaunchOverride(payload.grid)
if (grid.state === 'invalid') { reply(type, requestId, { error: 'INVALID_GRID', detail: grid.reason }); return }
+ // Same validation the desktop app already applies client-side (`Agent._safeCodexHome`) —
+ // repeated here because a client's own check is not a guarantee about what actually
+ // arrives on the wire.
+ const rawCodexHome = typeof payload.codexHome === 'string' ? payload.codexHome : null
+ const codexHome = rawCodexHome && rawCodexHome.startsWith('/') && rawCodexHome.length <= 4096
+ && !/[\x00-\x1f\x7f]/.test(rawCodexHome)
+ ? rawCodexHome
+ : null
+ if (codexHome && (engine !== 'codex' || grid.state === 'ok')) {
+ reply(type, requestId, { error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' })
+ return
+ }
const result = await this.onCreateAgent({
engine,
cwd,
bypassPermission: payload.bypassPermission === true,
grid: grid.state === 'ok' ? grid.override : null,
+ codexHome,
})
// `detail` carries the underlying cause (tmux's own message) so the person who clicked
// Create can read it, rather than having to open a log on the machine that failed.
@@ -1614,6 +1634,29 @@ export class BackendSocket {
return
}
+ case 'codex_profiles_list': {
+ // Which CODEX_HOME folders THIS machine can offer — answered here, on the machine in
+ // question, for the same reason `engines_probe` is: a Codex profile is a folder on disk,
+ // and a folder on a Mac means nothing on the Docker rig it was asked about instead.
+ const observed = Array.isArray(payload.observedPaths)
+ ? payload.observedPaths.filter((p): p is string => typeof p === 'string')
+ : []
+ try {
+ reply(type, requestId, { profiles: listCodexProfiles(observed) })
+ } catch {
+ reply(type, requestId, { error: 'CODEX_PROFILES_FAILED' })
+ }
+ return
+ }
+
+ case 'codex_profile_link': {
+ const path = typeof payload.path === 'string' ? payload.path : ''
+ const result = linkCodexProfile(path)
+ if ('error' in result) { reply(type, requestId, { error: result.error }); return }
+ reply(type, requestId, { profile: result })
+ return
+ }
+
case 'agent_read_file': {
// View one file — ≤5MB, text-only (mirror the hosted runtime’s guard).
const projectId = payload.agentId as string | undefined
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d5f97ff55..37c3faecf 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -3295,7 +3295,7 @@ async function runForeground(session: AuthSession): Promise<void> {
return undefined
}
- backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid }) => {
+ backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid, codexHome }) => {
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
try {
if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
@@ -3365,6 +3365,8 @@ async function runForeground(session: AuthSession): Promise<void> {
// answered and refused (`SPAWN_FAILED`) — see createAgentPane.ts. Registration itself is retried
// there: a stale registry entry from a previous tmux-server generation occasionally collides with
// a freshly-minted pane id, and that collision clears on its own on the very next pane.
+ // Mutually exclusive with a grid (backendSocket.ts refuses the two together): a chosen Codex
+ // profile becomes the new session's CODEX_HOME, the same `-e` mechanism a grid's own env rides.
const result = await createAndRegisterPane({
tmuxBackend,
registry,
@@ -3372,8 +3374,9 @@ async function runForeground(session: AuthSession): Promise<void> {
cwd,
sessionLabel: label,
argv,
- env: gridLaunch?.env,
+ env: gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined),
grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
+ codexHome,
})
if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
const { spawned, pending } = result
diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.ts
index 66bb1b993..c5f59c948 100644
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@ -2,14 +2,14 @@ import { describe, expect, it } from 'vitest'
import { agentFrame } from './agentFrame.js'
import type { RegisteredSession } from './registry.js'
-function session(grid: RegisteredSession['grid']): RegisteredSession {
+function session(grid: RegisteredSession['grid'], codexHome: RegisteredSession['codexHome'] = null): RegisteredSession {
return {
schemaVersion: 2,
active: true,
sessionId: 's1', engine: 'claude', agentId: 'h1', boundAt: 0, transcriptPath: null,
projectDir: 'tmp', cwd: '/tmp', tmuxPane: '%1', source: null, title: null, model: null,
runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux/%1',
- cliVersion: '2.1.212', processIdentity: null, gateway: null, grid,
+ cliVersion: '2.1.212', processIdentity: null, gateway: null, grid, codexHome,
registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
}
}
@@ -31,6 +31,16 @@ describe('agentFrame', () => {
expect(frame).toHaveProperty('grid', null)
})
+ it('carries the chosen Codex profile folder', async () => {
+ expect(await agentFrame(session(null, '/Users/x/.codex-personal'), { selectedModel: null, terminalAvailable: true }))
+ .toMatchObject({ codexHome: '/Users/x/.codex-personal' })
+ })
+
+ it('reports no Codex profile as null rather than omitting the field', async () => {
+ const frame = await agentFrame(session(null), { selectedModel: null, terminalAvailable: true })
+ expect(frame).toHaveProperty('codexHome', null)
+ })
+
it('passes through the caller-resolved model and terminal availability', async () => {
expect(await agentFrame(session(null), { selectedModel: 'opus', terminalAvailable: false }))
.toMatchObject({ selectedModel: 'opus', terminal: { available: false, primary: 'tmux/%1' } })
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 34e75f39c..821843191 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -42,6 +42,7 @@ export type AgentFrame = {
engine: RegisteredSession['engine']
selectedModel: string | null
grid: GridAssignment | null
+ codexHome: string | null
}
/** What the caller knows and this module deliberately does not look up for itself. */
@@ -82,5 +83,9 @@ export async function agentFrame(
// a real answer ("on no grid") and must be sent as one — omitting the key would make every push
// indistinguishable from a daemon too old to know about grids.
grid: s.grid ?? null,
+ // The Codex profile folder this agent launched against, if one was chosen instead of the
+ // engine's own login. Codex only; null is a real answer ("uses ~/.codex") for the same reason
+ // `grid: null` is above.
+ codexHome: s.codexHome ?? null,
}
}
diff --git a/cli/src/lib/codexProfileDiscovery.test.ts b/cli/src/lib/codexProfileDiscovery.test.ts
new file mode 100644
index 000000000..bb873c31a
--- /dev/null
+++ b/cli/src/lib/codexProfileDiscovery.test.ts
@@ -0,0 +1,208 @@
+import { describe, expect, it, afterEach } from 'vitest'
+import { mkdtempSync, mkdirSync, writeFileSync, chmodSync, rmSync, statSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { discoverCodexProfiles } from './codexProfileDiscovery.js'
+
+const dirs: string[] = []
+
+function tempHome(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'codex-discovery-'))
+ dirs.push(dir)
+ return dir
+}
+
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+function write(path: string, content: string, { executable = false } = {}): void {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, content)
+ if (executable) chmodSync(path, 0o755)
+}
+
+describe('discoverCodexProfiles — conventional homes', () => {
+ it('finds a .codex folder that has auth.json', () => {
+ const home = tempHome()
+ mkdirSync(join(home, '.codex'))
+ writeFileSync(join(home, '.codex', 'auth.json'), '{}')
+ expect(discoverCodexProfiles({ home, environment: {} })).toContain(join(home, '.codex'))
+ })
+
+ it('finds a folder named like a Codex profile that has config.toml', () => {
+ const home = tempHome()
+ mkdirSync(join(home, '.codex_personal'))
+ writeFileSync(join(home, '.codex_personal', 'config.toml'), '')
+ expect(discoverCodexProfiles({ home, environment: {} })).toContain(join(home, '.codex_personal'))
+ })
+
+ it('finds a codex-prefixed folder under XDG_CONFIG_HOME', () => {
+ const home = tempHome()
+ const config = join(home, 'myconfig')
+ mkdirSync(join(config, 'codex-team'), { recursive: true })
+ writeFileSync(join(config, 'codex-team', 'auth.json'), '{}')
+ const found = discoverCodexProfiles({ home, environment: { XDG_CONFIG_HOME: config } })
+ expect(found).toContain(join(config, 'codex-team'))
+ })
+
+ it('ignores an empty .codex folder with no marker file', () => {
+ const home = tempHome()
+ mkdirSync(join(home, '.codex'))
+ expect(discoverCodexProfiles({ home, environment: {} })).not.toContain(join(home, '.codex'))
+ })
+
+ it('ignores a folder that merely starts with "codex" but has no marker', () => {
+ const home = tempHome()
+ mkdirSync(join(home, '.codex-unrelated'))
+ writeFileSync(join(home, '.codex-unrelated', 'notes.txt'), 'hi')
+ expect(discoverCodexProfiles({ home, environment: {} })).not.toContain(join(home, '.codex-unrelated'))
+ })
+})
+
+describe('discoverCodexProfiles — CODEX_HOME', () => {
+ it('honors an absolute CODEX_HOME from the environment', () => {
+ const home = tempHome()
+ const found = discoverCodexProfiles({ home, environment: { CODEX_HOME: '/opt/codex-ci' } })
+ expect(found).toContain('/opt/codex-ci')
+ })
+
+ it('ignores a relative CODEX_HOME', () => {
+ const home = tempHome()
+ const found = discoverCodexProfiles({ home, environment: { CODEX_HOME: 'relative/codex' } })
+ expect(found).not.toContain('relative/codex')
+ })
+})
+
+describe('discoverCodexProfiles — shell configuration', () => {
+ it('reads a literal CODEX_HOME export from .zshrc', () => {
+ const home = tempHome()
+ write(join(home, '.zshrc'), 'export CODEX_HOME=/Users/x/.codex-work\n')
+ expect(discoverCodexProfiles({ home, environment: {} })).toContain('/Users/x/.codex-work')
+ })
+
+ it('expands $HOME and ${HOME} and a leading tilde in an assignment', () => {
+ const home = tempHome()
+ write(
+ join(home, '.bashrc'),
+ [
+ 'CODEX_HOME=$HOME/.codex-a',
+ 'CODEX_HOME=${HOME}/.codex-b',
+ 'CODEX_HOME=~/.codex-c',
+ ].join('\n'),
+ )
+ const found = discoverCodexProfiles({ home, environment: {} })
+ expect(found).toContain(join(home, '.codex-a'))
+ expect(found).toContain(join(home, '.codex-b'))
+ expect(found).toContain(join(home, '.codex-c'))
+ })
+
+ it('follows an alias body into its assignment', () => {
+ const home = tempHome()
+ write(join(home, '.zshrc'), "alias work-codex='CODEX_HOME=/Users/x/.codex-aliased codex'\n")
+ expect(discoverCodexProfiles({ home, environment: {} })).toContain('/Users/x/.codex-aliased')
+ })
+
+ it('follows a sourced file', () => {
+ const home = tempHome()
+ write(join(home, '.zshenv'), `source ${join(home, 'extra.sh')}\n`)
+ write(join(home, 'extra.sh'), 'export CODEX_HOME=/Users/x/.codex-sourced\n')
+ expect(discoverCodexProfiles({ home, environment: {} })).toContain('/Users/x/.codex-sourced')
+ })
+
+ it('supports ZDOTDIR', () => {
+ const home = tempHome()
+ const zdot = join(home, 'zdotdir')
+ mkdirSync(zdot, { recursive: true })
+ write(join(home, '.zshenv'), `export ZDOTDIR=${zdot}\n`)
+ write(join(zdot, '.zshrc'), 'export CODEX_HOME=/Users/x/.codex-zdot\n')
+ expect(discoverCodexProfiles({ home, environment: {} })).toContain('/Users/x/.codex-zdot')
+ })
+
+ it('supports fish set -gx and conf.d/functions', () => {
+ const home = tempHome()
+ const config = join(home, '.config')
+ write(join(config, 'fish', 'config.fish'), 'set -gx CODEX_HOME /Users/x/.codex-fish\n')
+ write(join(config, 'fish', 'conf.d', 'extra.fish'), 'set --export CODEX_HOME /Users/x/.codex-fish-confd\n')
+ write(join(config, 'fish', 'functions', 'helper.fish'), 'set -gx CODEX_HOME /Users/x/.codex-fish-fn\n')
+ const found = discoverCodexProfiles({ home, environment: {} })
+ expect(found).toContain('/Users/x/.codex-fish')
+ expect(found).toContain('/Users/x/.codex-fish-confd')
+ expect(found).toContain('/Users/x/.codex-fish-fn')
+ })
+
+ it('ignores comments, computed expressions and single-quoted literals', () => {
+ const home = tempHome()
+ write(
+ join(home, '.zshrc'),
+ [
+ '# CODEX_HOME=/Users/x/.codex-comment',
+ 'CODEX_HOME=$(echo /Users/x/.codex-computed)',
+ "CODEX_HOME='$HOME/.codex-literal'",
+ ].join('\n'),
+ )
+ const found = discoverCodexProfiles({ home, environment: {} })
+ expect(found).not.toContain('/Users/x/.codex-comment')
+ expect(found).not.toContain('/Users/x/.codex-computed')
+ // Single-quoted: '$HOME' must stay literal text, not expand, and not start with '/' either way.
+ expect([...found].some((p) => p.includes('.codex-literal'))).toBe(false)
+ })
+
+ it('follows a literal executable path referenced without alias/source, but never runs it', () => {
+ const home = tempHome()
+ const sentinel = join(home, 'MUST_NOT_EXECUTE')
+ const script = join(home, 'bin-shortcut.sh')
+ write(script, `#!/bin/sh\ntouch ${sentinel}\nexport CODEX_HOME=/Users/x/.codex-shortcut\n`, { executable: true })
+ write(join(home, '.zshrc'), `${script}\n`)
+ const found = discoverCodexProfiles({ home, environment: {} })
+ expect(found).toContain('/Users/x/.codex-shortcut')
+ expect(() => statSync(sentinel)).toThrow()
+ })
+
+ it('does not treat auth.json as shell configuration even if sourced', () => {
+ const home = tempHome()
+ mkdirSync(join(home, '.codex'), { recursive: true })
+ writeFileSync(join(home, '.codex', 'auth.json'), 'CODEX_HOME=/should-never-be-read')
+ write(join(home, '.zshrc'), `source ${join(home, '.codex', 'auth.json')}\n`)
+ const found = discoverCodexProfiles({ home, environment: {} })
+ expect(found).not.toContain('/should-never-be-read')
+ })
+
+ it('skips a shell file larger than the 64KB cap', () => {
+ const home = tempHome()
+ const huge = 'x'.repeat(70 * 1024) + '\nCODEX_HOME=/Users/x/.codex-oversized\n'
+ write(join(home, '.zshrc'), huge)
+ expect(discoverCodexProfiles({ home, environment: {} })).not.toContain('/Users/x/.codex-oversized')
+ })
+
+ it('skips a binary file (contains a null byte) even under a script-like name', () => {
+ const home = tempHome()
+ mkdirSync(home, { recursive: true })
+ writeFileSync(join(home, '.zshrc'), Buffer.from('CODEX_HOME=/nope\0binary'))
+ expect(discoverCodexProfiles({ home, environment: {} })).not.toContain('/nope')
+ })
+
+ it('discovers an executable declaring CODEX_HOME in a PATH bin directory', () => {
+ const home = tempHome()
+ const bin = join(home, 'custom-bin')
+ write(join(bin, 'tool'), '#!/bin/bash\nexport CODEX_HOME=/Users/x/.codex-path-bin\n', { executable: true })
+ const found = discoverCodexProfiles({ home, environment: { PATH: bin } })
+ expect(found).toContain('/Users/x/.codex-path-bin')
+ })
+
+ it('ignores a non-executable file sitting in a PATH bin directory', () => {
+ const home = tempHome()
+ const bin = join(home, 'custom-bin')
+ write(join(bin, 'tool'), '#!/bin/bash\nexport CODEX_HOME=/Users/x/.codex-noexec\n', { executable: false })
+ const found = discoverCodexProfiles({ home, environment: { PATH: bin } })
+ expect(found).not.toContain('/Users/x/.codex-noexec')
+ })
+
+ it('ignores an executable with no recognizable shell shebang', () => {
+ const home = tempHome()
+ const bin = join(home, 'custom-bin')
+ write(join(bin, 'tool'), '#!/usr/bin/env python3\nCODEX_HOME=/Users/x/.codex-python\n', { executable: true })
+ const found = discoverCodexProfiles({ home, environment: { PATH: bin } })
+ expect(found).not.toContain('/Users/x/.codex-python')
+ })
+})
diff --git a/cli/src/lib/codexProfileDiscovery.ts b/cli/src/lib/codexProfileDiscovery.ts
new file mode 100644
index 000000000..7f2c89556
--- /dev/null
+++ b/cli/src/lib/codexProfileDiscovery.ts
@@ -0,0 +1,372 @@
+/**
+ * Finds references to Codex state folders, without executing a shell or reading auth.json. This is
+ * a bounded reader of literal shell configuration, not a shell interpreter: computed paths remain
+ * available through explicit linking (see `codexProfiles.ts`).
+ *
+ * Ported from the Flutter desktop app's `lib/core/codex_profile_discovery.dart` (this is the "get
+ * data" half of the feature moving down onto the machine the agent will actually launch on, so it
+ * works for a remote machine too — see `codex_profiles_list` in `backendSocket.ts`).
+ */
+
+import { existsSync, openSync, closeSync, readSync, readdirSync, realpathSync, statSync } from 'fs'
+import { join } from 'path'
+
+const MAX_FILE_BYTES = 64 * 1024
+const MAX_FILES = 256
+const MAX_ENTRIES = 512
+const MAX_DEPTH = 4
+const TIMEOUT_MS = 3_000
+// Any execute bit (owner/group/other) — same test as Dart's `stat.mode & 0x49`.
+const ANY_EXEC_MODE = 0o111
+const DATA_FILE_RE = /\.(?:jsonl?|toml|sqlite3?|db)$/i
+const SHEBANG_RE = /^#![^\n]*\b(?:ba|z|fi|da|k)?sh\b/
+
+export interface CodexProfileDiscoveryOptions {
+ home: string
+ environment: Record<string, string>
+}
+
+/** Discover candidate `CODEX_HOME`-shaped folders on this machine. Never throws. */
+export function discoverCodexProfiles(options: CodexProfileDiscoveryOptions): Set<string> {
+ const discovery = new CodexProfileDiscovery(options.home, options.environment)
+ try {
+ discovery.scan()
+ } catch {
+ // Best-effort: whatever was found before the failure is still useful.
+ }
+ return discovery.paths
+}
+
+function isDataFile(path: string): boolean {
+ return DATA_FILE_RE.test(path)
+}
+
+class CodexProfileDiscovery {
+ readonly paths = new Set<string>()
+ private readonly visited = new Set<string>()
+ private readonly binDirectories = new Set<string>()
+ private readonly deadline: number
+ private stopped = false
+
+ constructor(
+ private readonly home: string,
+ private readonly environment: Record<string, string>,
+ ) {
+ this.deadline = Date.now() + TIMEOUT_MS
+ }
+
+ private timedOut(): boolean {
+ if (this.stopped) return true
+ if (Date.now() > this.deadline) this.stopped = true
+ return this.stopped
+ }
+
+ scan(): void {
+ const variables: Record<string, string> = { HOME: this.home, PATH: this.environment.PATH ?? '' }
+ for (const [key, value] of Object.entries(this.environment)) {
+ if (value.startsWith('/') || key === 'PATH') variables[key] = value
+ }
+ const inherited = this.environment.CODEX_HOME
+ if (inherited && inherited.startsWith('/')) this.paths.add(inherited)
+ const config = this.environment.XDG_CONFIG_HOME || join(this.home, '.config')
+ this.conventionalHomes(this.home)
+ this.conventionalHomes(config)
+
+ // Finder does not inherit the user's shell PATH. Include its usual private bin locations and
+ // read startup files directly instead of sourcing them.
+ this.binDirectories.add(join(this.home, '.local', 'bin'))
+ this.binDirectories.add(join(this.home, 'bin'))
+ this.readShell(join(this.home, '.zshenv'), variables, 0)
+ const zdot = variables.ZDOTDIR || this.home
+ const rcFiles = new Set([
+ join(zdot, '.zshenv'),
+ join(zdot, '.zprofile'),
+ join(zdot, '.zshrc'),
+ join(zdot, '.zlogin'),
+ join(this.home, '.profile'),
+ join(this.home, '.bash_profile'),
+ join(this.home, '.bash_login'),
+ join(this.home, '.bashrc'),
+ join(this.home, '.bash_aliases'),
+ join(config, 'fish', 'config.fish'),
+ ])
+ for (const path of rcFiles) this.readShell(path, variables, 0)
+ for (const folder of [join(config, 'fish', 'conf.d'), join(config, 'fish', 'functions')]) {
+ for (const entry of this.entries(folder)) {
+ if (entry.endsWith('.fish')) this.readShell(entry, variables, 0)
+ }
+ }
+ this.addBinDirectories(this.environment.PATH)
+ // Files explicitly referenced by aliases/source have priority over a PATH full of unrelated
+ // tools. A huge tool installation must not stall a dialog.
+ for (const folder of [...this.binDirectories].slice(0, 24)) {
+ for (const entry of this.entries(folder)) {
+ if (this.visited.size >= MAX_FILES) break
+ this.readShell(entry, { ...variables }, 0, true)
+ }
+ }
+ }
+
+ private entries(path: string): string[] {
+ if (this.timedOut()) return []
+ try {
+ return readdirSync(path).slice(0, MAX_ENTRIES).map((name) => join(path, name))
+ } catch {
+ return []
+ }
+ }
+
+ private conventionalHomes(root: string): void {
+ for (const entry of this.entries(root)) {
+ const base = entry.split('/').pop() ?? entry
+ const name = base.replace(/^\./, '')
+ if (!name.toLowerCase().startsWith('codex')) continue
+ if (existsSync(join(entry, 'auth.json')) || existsSync(join(entry, 'config.toml'))) {
+ this.paths.add(entry)
+ }
+ }
+ }
+
+ private addBinDirectories(path: string | undefined): void {
+ if (!path) return
+ for (const segment of path.split(':')) {
+ if (segment.startsWith('/')) this.binDirectories.add(segment)
+ }
+ }
+
+ private readShell(
+ path: string,
+ variables: Record<string, string>,
+ depth: number,
+ executable = false,
+ ): void {
+ if (this.timedOut() || depth > MAX_DEPTH || this.visited.size >= MAX_FILES) return
+ // These are Codex data, never configuration scripts to inspect.
+ if (isDataFile(path)) return
+ let fd: number
+ try {
+ const st = statSync(path)
+ if (!st.isFile() || st.size > MAX_FILE_BYTES) return
+ if (executable && (st.mode & ANY_EXEC_MODE) === 0) return
+ const resolved = realpathSync(path)
+ if (isDataFile(resolved)) return
+ if (this.visited.has(resolved)) return
+ this.visited.add(resolved)
+ fd = openSync(path, 'r')
+ } catch {
+ // A missing, unreadable or broken link does not hide the other profiles.
+ return
+ }
+ try {
+ // Cap the read too: a file can grow after stat. No named pipes/devices.
+ const buffer = Buffer.alloc(MAX_FILE_BYTES + 1)
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, 0)
+ if (bytesRead > MAX_FILE_BYTES) return
+ const slice = buffer.subarray(0, bytesRead)
+ if (slice.includes(0)) return
+ let content: string
+ try {
+ content = new TextDecoder('utf-8', { fatal: true }).decode(slice)
+ } catch {
+ return // An executable binary is not shell configuration.
+ }
+ if (executable && !SHEBANG_RE.test(content)) return
+ this.readCommands(content, variables, depth)
+ } catch {
+ // Unreadable once opened (e.g. a device file slipping past the stat check).
+ } finally {
+ closeSync(fd)
+ }
+ }
+
+ private readCommands(content: string, variables: Record<string, string>, depth: number): void {
+ for (const rawCommand of shellCommands(content)) {
+ if (this.timedOut()) return
+ let start = 0
+ while (start < rawCommand.length && (rawCommand[start] === 'then' || rawCommand[start] === 'do')) start++
+ const command = rawCommand.slice(start)
+ if (command.length === 0) continue
+ const first = literal(command[0], variables)
+ if (first === 'alias') {
+ for (const token of command.slice(1)) {
+ const match = /^[\w-]+=([\s\S]*)$/.exec(token)
+ if (!match || depth >= MAX_DEPTH) continue
+ const body = literal(match[1], variables)
+ if (body != null) this.readCommands(body, { ...variables }, depth + 1)
+ }
+ continue
+ }
+ if ((first === 'source' || first === '.') && command.length >= 2) {
+ const source = literal(command[1], variables)
+ if (source != null && source.startsWith('/')) this.readShell(source, variables, depth + 1)
+ continue
+ }
+ // fish: set -gx CODEX_HOME /path; set --export CODEX_HOME /path.
+ if (first === 'set') {
+ const values = command.slice(1).filter((word) => !word.startsWith('-'))
+ if (values.length === 2) this.assignment(`${values[0]}=${values[1]}`, variables)
+ continue
+ }
+ let prefix = true
+ for (const token of command) {
+ if (!prefix) break
+ if (this.assignment(token, variables)) continue
+ const word = literal(token, variables)
+ if (
+ word != null &&
+ new Set(['export', 'local', 'declare', 'typeset', 'readonly', 'exec', 'env', 'command', 'then', 'do']).has(word)
+ ) {
+ continue
+ }
+ if (token.startsWith('-')) continue
+ // Follow literal executable shortcuts, including aliases pointing to a script outside PATH.
+ // The script supplies evidence; its name need not mention Codex. Never execute the shortcut
+ // to ask it for an answer.
+ if (word != null && word.startsWith('/')) {
+ this.readShell(word, { ...variables }, depth + 1, true)
+ }
+ prefix = false
+ }
+ }
+ }
+
+ private assignment(token: string, variables: Record<string, string>): boolean {
+ const raw = /^([A-Za-z_][A-Za-z0-9_]*)=/.exec(token)
+ const value0 = literal(token, variables)
+ const decoded = value0 == null ? null : /^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/.exec(value0)
+ const name = raw?.[1] ?? decoded?.[1]
+ if (!name) return false
+ const value = decoded?.[2]
+ if (value == null) {
+ delete variables[name] // a computed reassignment invalidates the old value
+ return true
+ }
+ if (name === 'CODEX_HOME' && value.startsWith('/')) this.paths.add(value)
+ if (name === 'PATH') this.addBinDirectories(value)
+ if (value.startsWith('/') || name === 'PATH') {
+ variables[name] = value
+ } else {
+ delete variables[name]
+ }
+ return true
+ }
+}
+
+/**
+ * Keep quotes until interpretation, so '$HOME' stays literal while "$HOME" expands. In an alias the
+ * outer quotes are removed before reading its body.
+ */
+function* shellCommands(source: string): Generator<string[]> {
+ const input = source.replace(/\\\r\n/g, '').replace(/\\\n/g, '')
+ let words: string[] = []
+ let word = ''
+ let quote: string | null = null
+ for (let i = 0; i < input.length; i++) {
+ const c = input[i]
+ if (c === '\\' && quote !== "'" && i + 1 < input.length) {
+ word += c
+ i++
+ word += input[i]
+ continue
+ }
+ if (quote != null) {
+ word += c
+ if (c === quote) quote = null
+ continue
+ }
+ if (c === '$' && i + 1 < input.length && input[i + 1] === '{') {
+ const end = input.indexOf('}', i + 2)
+ if (end < 0) return
+ word += input.slice(i, end + 1)
+ i = end
+ continue
+ }
+ if (c === '$' && i + 1 < input.length && input[i + 1] === '(') {
+ // Keep computed expressions opaque, including nested commands, so their contents can never
+ // become profile declarations of their own.
+ let level = 1
+ const start = i
+ i += 2
+ while (i < input.length && level > 0) {
+ if (input[i] === '(') level++
+ if (input[i] === ')') level--
+ i++
+ }
+ if (level > 0) return
+ word += input.slice(start, i)
+ i--
+ continue
+ }
+ if (c === "'" || c === '"') {
+ quote = c
+ word += c
+ continue
+ }
+ if (c === '#' && word.length === 0) {
+ while (i < input.length && input[i] !== '\n') i++
+ if (words.length > 0) yield words
+ words = []
+ continue
+ }
+ if (' \t\r\n;|&(){}'.includes(c)) {
+ if (word.length > 0) {
+ words.push(word)
+ word = ''
+ }
+ if ('\n;|&(){}'.includes(c) && words.length > 0) {
+ yield words
+ words = []
+ }
+ } else {
+ word += c
+ }
+ }
+ if (quote != null) return
+ if (word.length > 0) words.push(word)
+ if (words.length > 0) yield words
+}
+
+/**
+ * Only literal paths and simple variable references. No command substitution, eval, globbing,
+ * parameter operators or positional arguments are interpreted.
+ */
+function literal(raw: string, variables: Record<string, string>): string | null {
+ let out = ''
+ let quote: string | null = null
+ for (let i = 0; i < raw.length; i++) {
+ const c = raw[i]
+ if (c === '\\' && quote !== "'") {
+ i++
+ if (i >= raw.length) return null
+ out += raw[i]
+ continue
+ }
+ if (c === "'" || c === '"') {
+ if (quote == null) {
+ quote = c
+ continue
+ }
+ if (quote === c) {
+ quote = null
+ continue
+ }
+ }
+ if (quote !== "'" && c === '$') {
+ const match = /^\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/.exec(raw.slice(i))
+ const value = match == null ? undefined : variables[match[1] ?? match[2]]
+ if (match == null || value == null) return null
+ out += value
+ i += match[0].length - 1
+ continue
+ }
+ if (quote !== "'" && c === '`') return null
+ if (quote == null && '*?[]'.includes(c)) return null
+ // Tilde expands only at the start of a word or an assignment's value.
+ if (quote == null && c === '~' && (i === 0 || raw[i - 1] === '=') && (i + 1 === raw.length || raw[i + 1] === '/')) {
+ out += variables.HOME ?? ''
+ continue
+ }
+ out += c
+ }
+ return quote == null ? out : null
+}
diff --git a/cli/src/lib/codexProfiles.test.ts b/cli/src/lib/codexProfiles.test.ts
new file mode 100644
index 000000000..6a9ac7b0e
--- /dev/null
+++ b/cli/src/lib/codexProfiles.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { homedir, tmpdir } from 'os'
+import { join } from 'path'
+import type * as CodexProfilesModule from './codexProfiles.js'
+
+let dataDir = ''
+let home = ''
+
+async function loadModule(): Promise<typeof CodexProfilesModule> {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ return import('./codexProfiles.js')
+}
+
+const emptyDiscovery = { home: '/nonexistent-empty-home', environment: {} }
+
+describe('codexProfiles', () => {
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'codex-profiles-data-'))
+ // Under the real home, not os.tmpdir(): resolveCodexProfilePath realpath-resolves everything it
+ // returns, and macOS's tmpdir sits behind a /var → /private/var symlink that would otherwise
+ // make the resolved path disagree with the literal folder these tests just created.
+ home = mkdtempSync(join(homedir(), '.codex-profiles-test-'))
+ })
+
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ rmSync(home, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ })
+
+ it('resolveCodexProfilePath rejects a relative path', async () => {
+ const { resolveCodexProfilePath } = await loadModule()
+ expect(resolveCodexProfilePath('relative/codex')).toEqual({ error: 'INVALID_PATH' })
+ })
+
+ it('resolveCodexProfilePath rejects a path with control characters', async () => {
+ const { resolveCodexProfilePath } = await loadModule()
+ expect(resolveCodexProfilePath('/tmp/codex\nhome')).toEqual({ error: 'INVALID_PATH' })
+ })
+
+ it('resolveCodexProfilePath rejects a folder that does not exist', async () => {
+ const { resolveCodexProfilePath } = await loadModule()
+ expect(resolveCodexProfilePath(join(home, 'nope'))).toEqual({ error: 'NOT_FOUND' })
+ })
+
+ it('resolveCodexProfilePath rejects a path that is a file, not a directory', async () => {
+ const { resolveCodexProfilePath } = await loadModule()
+ const file = join(home, 'not-a-dir')
+ writeFileSync(file, '')
+ expect(resolveCodexProfilePath(file)).toEqual({ error: 'NOT_FOUND' })
+ })
+
+ it('resolveCodexProfilePath accepts and resolves an existing absolute folder', async () => {
+ const { resolveCodexProfilePath } = await loadModule()
+ const folder = join(home, '.codex-work')
+ mkdirSync(folder)
+ expect(resolveCodexProfilePath(folder)).toEqual({ path: folder, label: '.codex-work' })
+ })
+
+ it('linkCodexProfile persists the resolved path on this machine', async () => {
+ const { linkCodexProfile } = await loadModule()
+ const folder = join(home, '.codex-linked')
+ mkdirSync(folder)
+ expect(linkCodexProfile(folder)).toEqual({ path: folder, label: '.codex-linked' })
+ const persisted = JSON.parse(readFileSync(join(dataDir, 'codex-profiles.json'), 'utf8'))
+ expect(persisted).toEqual([folder])
+ })
+
+ it('linkCodexProfile refuses a folder that does not exist', async () => {
+ const { linkCodexProfile } = await loadModule()
+ expect(linkCodexProfile(join(home, 'ghost'))).toEqual({ error: 'NOT_FOUND' })
+ })
+
+ it('listCodexProfiles returns a previously linked folder', async () => {
+ const { linkCodexProfile, listCodexProfiles } = await loadModule()
+ const folder = join(home, '.codex-linked')
+ mkdirSync(folder)
+ linkCodexProfile(folder)
+ expect(listCodexProfiles([], emptyDiscovery)).toEqual([{ path: folder, label: '.codex-linked' }])
+ })
+
+ it('listCodexProfiles drops a linked folder that has since vanished', async () => {
+ const { linkCodexProfile, listCodexProfiles } = await loadModule()
+ const folder = join(home, '.codex-linked')
+ mkdirSync(folder)
+ linkCodexProfile(folder)
+ rmSync(folder, { recursive: true, force: true })
+ expect(listCodexProfiles([], emptyDiscovery)).toEqual([])
+ })
+
+ it('listCodexProfiles includes observedPaths without requiring them to be linked', async () => {
+ const { listCodexProfiles } = await loadModule()
+ const folder = join(home, '.codex-observed')
+ mkdirSync(folder)
+ expect(listCodexProfiles([folder], emptyDiscovery)).toEqual([{ path: folder, label: '.codex-observed' }])
+ })
+
+ it('listCodexProfiles includes freshly discovered folders', async () => {
+ const { listCodexProfiles } = await loadModule()
+ mkdirSync(join(home, '.codex'))
+ writeFileSync(join(home, '.codex', 'auth.json'), '{}')
+ expect(listCodexProfiles([], { home, environment: {} })).toEqual([
+ { path: join(home, '.codex'), label: '.codex' },
+ ])
+ })
+
+ it('listCodexProfiles dedupes linked, observed and discovered copies of the same folder', async () => {
+ const { linkCodexProfile, listCodexProfiles } = await loadModule()
+ const folder = join(home, '.codex')
+ mkdirSync(folder)
+ writeFileSync(join(folder, 'auth.json'), '{}')
+ linkCodexProfile(folder)
+ expect(listCodexProfiles([folder], { home, environment: {} })).toEqual([{ path: folder, label: '.codex' }])
+ })
+
+ it('listCodexProfiles sorts by label (case-insensitive), then by path', async () => {
+ const { listCodexProfiles } = await loadModule()
+ const b = join(home, '.codex-Beta')
+ const a = join(home, '.codex-alpha')
+ mkdirSync(a)
+ mkdirSync(b)
+ expect(listCodexProfiles([a, b], emptyDiscovery)).toEqual([
+ { path: a, label: '.codex-alpha' },
+ { path: b, label: '.codex-Beta' },
+ ])
+ })
+
+ it('listCodexProfiles never throws when the state file is malformed', async () => {
+ const { listCodexProfiles } = await loadModule()
+ writeFileSync(join(dataDir, 'codex-profiles.json'), 'not json', { mode: 0o600 })
+ expect(listCodexProfiles([], emptyDiscovery)).toEqual([])
+ })
+})
diff --git a/cli/src/lib/codexProfiles.ts b/cli/src/lib/codexProfiles.ts
new file mode 100644
index 000000000..af9733b5d
--- /dev/null
+++ b/cli/src/lib/codexProfiles.ts
@@ -0,0 +1,145 @@
+/**
+ * Codex profiles — CODEX_HOME folders this machine can point a Codex agent at.
+ *
+ * Runs entirely on whatever machine the CLI is on (see `backendSocket.ts`'s `codex_profiles_list`
+ * and `codex_profile_link` cases), which is what makes this work for a remote machine: the desktop
+ * app never touches a filesystem itself, it only renders what this reports. Ported from the Flutter
+ * desktop app's `lib/core/codex_profiles.dart`, whose discovery half moved to `codexProfileDiscovery.ts`
+ * and whose "linked" persistence moved from the app's own local storage (which could not mean
+ * anything for a remote machine) to this machine's own state directory.
+ */
+
+import { closeSync, constants, fchmodSync, fsyncSync, openSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
+import { randomUUID } from 'crypto'
+import { homedir } from 'os'
+import { join } from 'path'
+import { env } from '../config/env.js'
+import { discoverCodexProfiles } from './codexProfileDiscovery.js'
+import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
+
+export interface CodexProfile {
+ path: string
+ label: string
+}
+
+export type CodexProfileError = { error: 'INVALID_PATH' | 'NOT_FOUND' }
+
+const FILE = join(env.ADAPTER_DATA_DIR, 'codex-profiles.json')
+const MAX_LINKED = 256
+const CONTROL_CHARS_RE = /[\x00-\x1f\x7f]/
+
+function labelFor(path: string): string {
+ const parts = path.split('/').filter((p) => p.length > 0)
+ return parts.length > 0 ? parts[parts.length - 1] : path
+}
+
+function readLinkedPaths(): Set<string> {
+ try {
+ const raw = JSON.parse(readPrivateStateFile(FILE, 1024 * 1024)) as unknown
+ if (Array.isArray(raw)) {
+ return new Set(raw.filter((p): p is string => typeof p === 'string').slice(0, MAX_LINKED))
+ }
+ } catch {
+ // Discovery still works when the optional saved list is unavailable/unreadable/malformed.
+ }
+ return new Set()
+}
+
+function atomicWriteJson(file: string, value: unknown): void {
+ hardenPrivateStateFileIfPresent(file)
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`
+ let renamed = false
+ try {
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(fd, JSON.stringify(value, null, 2))
+ fchmodSync(fd, 0o600)
+ fsyncSync(fd)
+ } finally {
+ closeSync(fd)
+ }
+ renameSync(temporary, file)
+ renamed = true
+ } finally {
+ if (!renamed) rmSync(temporary, { force: true })
+ }
+}
+
+function writeLinkedPaths(paths: Set<string>): void {
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
+ atomicWriteJson(FILE, [...paths].slice(0, MAX_LINKED))
+}
+
+/** Validate + resolve a folder path the same way for both linking and re-checking a saved one. */
+export function resolveCodexProfilePath(path: string): CodexProfile | CodexProfileError {
+ if (!path.startsWith('/') || path.length > 4096 || CONTROL_CHARS_RE.test(path)) {
+ return { error: 'INVALID_PATH' }
+ }
+ let st
+ try {
+ st = statSync(path)
+ } catch {
+ return { error: 'NOT_FOUND' }
+ }
+ if (!st.isDirectory()) return { error: 'NOT_FOUND' }
+ let resolved: string
+ try {
+ resolved = realpathSync(path)
+ } catch {
+ return { error: 'NOT_FOUND' }
+ }
+ if (resolved.length > 4096 || CONTROL_CHARS_RE.test(resolved)) return { error: 'INVALID_PATH' }
+ return { path: resolved, label: labelFor(resolved) }
+}
+
+/** Link a folder as a Codex profile, persisted on this machine so it survives future requests. */
+export function linkCodexProfile(path: string): CodexProfile | CodexProfileError {
+ const profile = resolveCodexProfilePath(path)
+ if ('error' in profile) return profile
+ const linked = readLinkedPaths()
+ linked.add(profile.path)
+ writeLinkedPaths(linked)
+ return profile
+}
+
+function processEnvironment(): Record<string, string> {
+ const environment: Record<string, string> = {}
+ for (const [key, value] of Object.entries(process.env)) {
+ if (value !== undefined) environment[key] = value
+ }
+ return environment
+}
+
+/**
+ * Every Codex profile this machine can offer: previously linked folders, `observedPaths` (Codex
+ * homes the caller already knows about from this same machine's other Codex agents), and freshly
+ * discovered folders. Never throws — a discovery scan that fails still returns the linked/observed
+ * folders that resolved fine.
+ */
+export function listCodexProfiles(
+ observedPaths: readonly string[] = [],
+ /** Injectable for tests only; production always discovers this machine's own home/environment. */
+ discoveryOptions: { home: string; environment: Record<string, string> } = {
+ home: homedir(),
+ environment: processEnvironment(),
+ },
+): CodexProfile[] {
+ const candidates = new Set<string>([...readLinkedPaths(), ...observedPaths])
+ try {
+ for (const path of discoverCodexProfiles(discoveryOptions)) {
+ candidates.add(path)
+ }
+ } catch {
+ // A discovery failure must not hide linked/observed profiles that are still good.
+ }
+ const profiles = new Map<string, CodexProfile>()
+ for (const path of candidates) {
+ const resolved = resolveCodexProfilePath(path)
+ // A vanished folder or a malformed persisted entry must not be offered as a working profile.
+ if (!('error' in resolved)) profiles.set(resolved.path, resolved)
+ }
+ return [...profiles.values()].sort((a, b) => {
+ const byLabel = a.label.toLowerCase().localeCompare(b.label.toLowerCase())
+ return byLabel !== 0 ? byLabel : a.path.localeCompare(b.path)
+ })
+}
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index c980f6558..8436cc061 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -28,6 +28,7 @@ export interface CreateAgentPaneDeps {
primaryRuntimeKey?: string
cwd?: string | null
grid?: { baseUrl: string; model: string | null } | null
+ codexHome?: string | null
}) => RegisteredSession | null }
engine: AgentEngine
cwd?: string | null
@@ -36,6 +37,8 @@ export interface CreateAgentPaneDeps {
argv: string[]
env?: Record<string, string>
grid?: { baseUrl: string; model: string | null } | null
+ /** The CODEX_HOME folder this agent was launched against, if the caller chose one; codex only. */
+ codexHome?: string | null
maxAttempts?: number
}
@@ -67,6 +70,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<
primaryRuntimeKey: terminalRouteKey(spawned.runtime),
cwd: deps.cwd,
grid: deps.grid,
+ codexHome: deps.codexHome,
})
if (pending) return { ok: true, spawned, pending }
console.warn(`[agent] create ${deps.engine} registration failed · pane ${spawned.runtime.paneId} · `
diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.ts
index f9bea1956..43ad56d0b 100644
--- a/cli/src/lib/e2ee/core.test.ts
+++ b/cli/src/lib/e2ee/core.test.ts
@@ -197,6 +197,6 @@ describe('e2ee core — interop keystone', () => {
it('core.ts still hashes to the pinned value shared with the other implementations', () => {
const here = dirname(fileURLToPath(import.meta.url))
const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')
- expect(actual).toBe('6e910a4da4e4e96550f119302bf64eaa22b7b01b76d54d520730561a6ce630af')
+ expect(actual).toBe('e21ceb78f3cf8ca56d09bc52daf336f89a75d05dd84ee6882c7b736cfd5bb415')
})
})
diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.ts
index 523a2a193..6c7d8a894 100644
--- a/cli/src/lib/e2ee/core.ts
+++ b/cli/src/lib/e2ee/core.ts
@@ -352,6 +352,8 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([
'agent_recent_result', 'agent_create_result', 'agent_restart_result',
// A remote-machine directory listing (New Agent folder browser) — leaks filesystem layout if plaintext.
'fs_list_dir_result',
+ // Same reasoning as fs_list_dir_result: reveals Codex profile folder names/paths on this machine.
+ 'codex_profiles_list_result', 'codex_profile_link_result',
])
/** Client→adapter frames that carry or can trigger adapter-local user data. */
export const ENCRYPTED_DOWN_TYPES = new Set<string>([
@@ -363,7 +365,7 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([
'question_response',
'agents_list', 'sessions_list', 'session_get', 'models_list',
'agent_create', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',
- 'fs_list_dir',
+ 'fs_list_dir', 'codex_profiles_list', 'codex_profile_link',
'device_e2ee_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair',
'e2ee_pairings_unpair_all', 'e2ee_browser_link_create',
// Remote terminal control is always pairwise E2EE. The relay may route by outer type/connId but must
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 85dcaf117..798254799 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -99,6 +99,13 @@ export interface RegisteredSession {
* exactly like `gateway`, never declared. See `gridAssignment.ts`. Carries no credential.
*/
grid?: GridAssignment | null
+ /**
+ * The CODEX_HOME folder this agent was launched against, if one was chosen instead of `~/.codex`.
+ * Codex only. Unlike `grid`, this is chosen once at creation and never re-derived from the live
+ * process — a running agent cannot be moved to a different profile the way it can be retargeted
+ * to a different grid.
+ */
+ codexHome?: string | null
/** Legacy launcher-owned snapshots may still contain this field. New records never write it. */
launcherId?: string
transcriptPath: string | null
@@ -936,6 +943,7 @@ class Registry {
primaryRuntimeKey?: string
cwd?: string | null
grid?: GridAssignment | null
+ codexHome?: string | null
}): RegisteredSession | null {
if (this.writeBlocked) return null
const runtimes = normalizedRuntimes(input.runtimes)
@@ -953,6 +961,7 @@ class Registry {
engine: input.engine,
gateway: null,
grid: input.grid ?? null,
+ codexHome: input.codexHome ?? null,
transcriptPath: null,
projectDir: basename(input.cwd ?? '') || agentId,
cwd: input.cwd ?? null,