Skip to content
Merged
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
16 changes: 16 additions & 0 deletions hooks/codex/hooks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume|clear|compact",
"hooks": [
{
"type": "command",
"command": "node ~/.codex/hooks/codex-session-mapping.cjs",
"timeout": 5
}
]
}
]
}
}
165 changes: 165 additions & 0 deletions hooks/codex/hooks/codex-session-mapping.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const SESSION_FILE_ENV_KEYS = [
'CODEX_SESSION_FILE',
'CODEX_SESSION_FILE_PATH',
'CODEX_TRANSCRIPT_PATH',
'OPENAI_CODEX_SESSION_FILE',
'OPENAI_CODEX_SESSION_FILE_PATH',
];

const SESSION_FILE_INPUT_KEYS = [
'session_file',
'sessionFile',
'session_file_path',
'sessionFilePath',
'transcript_path',
'transcriptPath',
];

const SESSION_ID_ENV_KEYS = [
'CODEX_THREAD_ID',
'CODEX_SESSION_ID',
'OPENAI_CODEX_THREAD_ID',
'OPENAI_CODEX_SESSION_ID',
];

const SESSION_ID_INPUT_KEYS = [
'session_id',
'sessionId',
'thread_id',
'threadId',
'conversation_id',
'conversationId',
];

const CODEX_PID_ENV_KEYS = [
'CODEX_PID',
'CODEX_PROCESS_PID',
'OPENAI_CODEX_PID',
'OPENAI_CODEX_PROCESS_PID',
'AI_DEVKIT_CODEX_PID',
];

const CODEX_PID_INPUT_KEYS = [
'codex_pid',
'codexPid',
'codex_process_pid',
'codexProcessPid',
'pid',
];

function readHookInput() {
if (process.stdin.isTTY) return {};

try {
const raw = fs.readFileSync(0, 'utf8').trim();
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}

function normalizeValue(value) {
if (typeof value === 'string' && value.trim()) return value.trim();
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return String(value);
return undefined;
}

function inputSources(input) {
return [input, input?.payload, input?.session, input?.thread].filter(
(source) => source && typeof source === 'object',
);
}

function inputValue(input, keys) {
for (const source of inputSources(input)) {
const value = firstValue(keys, (key) => source[key]);
if (value) return value;
}

return undefined;
}

function envValue(keys) {
return firstValue(keys, (key) => process.env[key]);
}

function firstValue(keys, getValue) {
for (const key of keys) {
const value = normalizeValue(getValue(key));
if (value) return value;
}

return undefined;
}

function readRegistry(registryFile) {
let existing;

try {
existing = JSON.parse(fs.readFileSync(registryFile, 'utf8'));
} catch {
return {};
}

return existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {};
}

function writeRegistry(registryFile, registry) {
fs.mkdirSync(path.dirname(registryFile), { recursive: true });
fs.writeFileSync(registryFile, JSON.stringify(registry, null, 2), 'utf8');
}

function findSessionFileById(homeDir, sessionId) {
const codexSessionsDir = path.join(homeDir, '.codex', 'sessions');
const pendingDirs = [codexSessionsDir];

while (pendingDirs.length > 0) {
const dir = pendingDirs.pop();
let entries;

try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}

for (const entry of entries) {
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
pendingDirs.push(entryPath);
} else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name.includes(sessionId)) {
return entryPath;
}
}
}

return undefined;
}

function resolveSessionFile(homeDir, input) {
const explicitPath = envValue(SESSION_FILE_ENV_KEYS) || inputValue(input, SESSION_FILE_INPUT_KEYS);

if (explicitPath) return explicitPath;

const sessionId = envValue(SESSION_ID_ENV_KEYS) || inputValue(input, SESSION_ID_INPUT_KEYS);

return sessionId ? findSessionFileById(homeDir, sessionId) : undefined;
}

function resolveCodexPid(input) {
const pid = envValue(CODEX_PID_ENV_KEYS) || inputValue(input, CODEX_PID_INPUT_KEYS);

return pid || String(process.ppid || process.pid);
}

const input = readHookInput();
const homeDir = os.homedir();
const registryFile = path.join(homeDir, '.codex', 'ai-devkit', 'sessions.json');
const registry = readRegistry(registryFile);

registry[resolveCodexPid(input)] = resolveSessionFile(homeDir, input) || 'ephemeral';
writeRegistry(registryFile, registry);
121 changes: 121 additions & 0 deletions packages/agent-manager/src/__tests__/adapters/CodexAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,127 @@ describe('CodexAdapter', () => {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});

it('should map a running Codex process from the hook session mapping', async () => {
const originalHome = process.env.HOME;
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-mapping-'));
process.env.HOME = tmpHome;

try {
const mappedAdapter = new CodexAdapter(new AgentRegistry(path.join(tmpHome, 'agents.json')));
const sessionsDir = path.join(tmpHome, '.codex', 'sessions');
const dateDir = path.join(sessionsDir, '2026', '06', '26');
const mappingPath = path.join(tmpHome, '.codex', 'ai-devkit', 'sessions.json');
const sessionFile = path.join(dateDir, 'rollout-2026-06-26T09-56-12-sess-mapped.jsonl');
const recentTs = new Date().toISOString();

fs.mkdirSync(dateDir, { recursive: true });
fs.mkdirSync(path.dirname(mappingPath), { recursive: true });
fs.writeFileSync(sessionFile, [
JSON.stringify({ type: 'session_meta', payload: { id: 'sess-mapped', timestamp: recentTs, cwd: '/repo-mapped' } }),
JSON.stringify({ type: 'event', timestamp: recentTs, payload: { type: 'agent_message', message: 'mapped conversation' } }),
].join('\n'));
fs.writeFileSync(mappingPath, JSON.stringify({ 5151: sessionFile }));

const processes: ProcessInfo[] = [
{
pid: 5151,
command: 'codex',
cwd: '/repo-mapped',
tty: 'ttys001',
startTime: new Date('2026-06-26T09:56:12.000Z'),
},
];
mockedListAgentProcesses.mockReturnValue(processes);
mockedEnrichProcesses.mockReturnValue(processes);

const agents = await mappedAdapter.detectAgents();

expect(agents).toHaveLength(1);
expect(agents[0]).toMatchObject({
type: 'codex',
pid: 5151,
sessionId: 'sess-mapped',
projectPath: '/repo-mapped',
summary: 'mapped conversation',
sessionFilePath: sessionFile,
});
expect(mockedBatchGetSessionFileBirthtimes).not.toHaveBeenCalled();
expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled();
} finally {
process.env.HOME = originalHome;
fs.rmSync(tmpHome, { recursive: true, force: true });
}
});

it('should fall back to legacy matching when mapped session file cannot be parsed', async () => {
const originalHome = process.env.HOME;
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-mapping-fallback-'));
process.env.HOME = tmpHome;

try {
const mappedAdapter = new CodexAdapter(new AgentRegistry(path.join(tmpHome, 'agents.json')));
const sessionsDir = path.join(tmpHome, '.codex', 'sessions');
const dateDir = path.join(sessionsDir, '2026', '06', '26');
const mappingPath = path.join(tmpHome, '.codex', 'ai-devkit', 'sessions.json');
const badSessionFile = path.join(dateDir, 'bad.jsonl');
const fallbackSessionFile = path.join(dateDir, 'fallback.jsonl');
const recentTs = new Date().toISOString();

fs.mkdirSync(dateDir, { recursive: true });
fs.mkdirSync(path.dirname(mappingPath), { recursive: true });
fs.writeFileSync(badSessionFile, '{not-json');
fs.writeFileSync(fallbackSessionFile, [
JSON.stringify({ type: 'session_meta', payload: { id: 'sess-fallback', timestamp: recentTs, cwd: '/repo-fallback' } }),
JSON.stringify({ type: 'event', timestamp: recentTs, payload: { type: 'token_count', message: 'fallback conversation' } }),
].join('\n'));
fs.writeFileSync(mappingPath, JSON.stringify({ 6161: badSessionFile }));

const processes: ProcessInfo[] = [
{
pid: 6161,
command: 'codex',
cwd: '/repo-fallback',
tty: 'ttys001',
startTime: new Date('2026-06-26T09:56:12.000Z'),
},
];
const fallbackSession: SessionFile = {
sessionId: 'sess-fallback',
filePath: fallbackSessionFile,
projectDir: dateDir,
birthtimeMs: new Date('2026-06-26T09:56:15.000Z').getTime(),
resolvedCwd: '',
};
mockedListAgentProcesses.mockReturnValue(processes);
mockedEnrichProcesses.mockReturnValue(processes);
mockedBatchGetSessionFileBirthtimes.mockReturnValue([fallbackSession]);
mockedMatchProcessesToSessions.mockReturnValue([
{
process: processes[0],
session: { ...fallbackSession, resolvedCwd: '/repo-fallback' },
deltaMs: 3000,
},
]);

const agents = await mappedAdapter.detectAgents();

expect(agents).toHaveLength(1);
expect(agents[0]).toMatchObject({
pid: 6161,
sessionId: 'sess-fallback',
summary: 'fallback conversation',
sessionFilePath: fallbackSessionFile,
});
expect(mockedMatchProcessesToSessions).toHaveBeenCalledWith(
[processes[0]],
expect.arrayContaining([expect.objectContaining({ filePath: fallbackSessionFile })]),
);
} finally {
process.env.HOME = originalHome;
fs.rmSync(tmpHome, { recursive: true, force: true });
}
});
});

describe('detectAgents — registry cache short-circuit', () => {
Expand Down
Loading
Loading