This repository was archived by the owner on Feb 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathrunCodex.ts
More file actions
772 lines (709 loc) · 30.9 KB
/
runCodex.ts
File metadata and controls
772 lines (709 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
import { render } from "ink";
import React from "react";
import { ApiClient } from '@/api/api';
import { CodexMcpClient } from './codexMcpClient';
import { CodexPermissionHandler } from './utils/permissionHandler';
import { ReasoningProcessor } from './utils/reasoningProcessor';
import { DiffProcessor } from './utils/diffProcessor';
import { randomUUID } from 'node:crypto';
import { logger } from '@/ui/logger';
import { Credentials, readSettings } from '@/persistence';
import { AgentState, Metadata } from '@/api/types';
import { initialMachineMetadata } from '@/daemon/run';
import { configuration } from '@/configuration';
import packageJson from '../../package.json';
import os from 'node:os';
import { MessageQueue2 } from '@/utils/MessageQueue2';
import { hashObject } from '@/utils/deterministicJson';
import { projectPath } from '@/projectPath';
import { resolve, join } from 'node:path';
import fs from 'node:fs';
import { startHappyServer } from '@/claude/utils/startHappyServer';
import { MessageBuffer } from "@/ui/ink/messageBuffer";
import { CodexDisplay } from "@/ui/ink/CodexDisplay";
import { trimIdent } from "@/utils/trimIdent";
import type { CodexSessionConfig } from './types';
import { CHANGE_TITLE_INSTRUCTION } from '@/gemini/constants';
import { notifyDaemonSessionStarted } from "@/daemon/controlClient";
import { registerKillSessionHandler } from "@/claude/registerKillSessionHandler";
import { delay } from "@/utils/time";
import { stopCaffeinate } from "@/utils/caffeinate";
type ReadyEventOptions = {
pending: unknown;
queueSize: () => number;
shouldExit: boolean;
sendReady: () => void;
notify?: () => void;
};
/**
* Notify connected clients when Codex finishes processing and the queue is idle.
* Returns true when a ready event was emitted.
*/
export function emitReadyIfIdle({ pending, queueSize, shouldExit, sendReady, notify }: ReadyEventOptions): boolean {
if (shouldExit) {
return false;
}
if (pending) {
return false;
}
if (queueSize() > 0) {
return false;
}
sendReady();
notify?.();
return true;
}
/**
* Main entry point for the codex command with ink UI
*/
export async function runCodex(opts: {
credentials: Credentials;
startedBy?: 'daemon' | 'terminal';
}): Promise<void> {
type PermissionMode = 'default' | 'read-only' | 'safe-yolo' | 'yolo';
interface EnhancedMode {
permissionMode: PermissionMode;
model?: string;
}
//
// Define session
//
const sessionTag = randomUUID();
const api = await ApiClient.create(opts.credentials);
// Log startup options
logger.debug(`[codex] Starting with options: startedBy=${opts.startedBy || 'terminal'}`);
//
// Machine
//
const settings = await readSettings();
let machineId = settings?.machineId;
if (!machineId) {
console.error(`[START] No machine ID found in settings, which is unexpected since authAndSetupMachineIfNeeded should have created it. Please report this issue on https://github.com/slopus/happy-cli/issues`);
process.exit(1);
}
logger.debug(`Using machineId: ${machineId}`);
await api.getOrCreateMachine({
machineId,
metadata: initialMachineMetadata
});
//
// Create session
//
let state: AgentState = {
controlledByUser: false,
}
let metadata: Metadata = {
path: process.cwd(),
host: os.hostname(),
version: packageJson.version,
os: os.platform(),
machineId: machineId,
homeDir: os.homedir(),
happyHomeDir: configuration.happyHomeDir,
happyLibDir: projectPath(),
happyToolsDir: resolve(projectPath(), 'tools', 'unpacked'),
startedFromDaemon: opts.startedBy === 'daemon',
hostPid: process.pid,
startedBy: opts.startedBy || 'terminal',
// Initialize lifecycle state
lifecycleState: 'running',
lifecycleStateSince: Date.now(),
flavor: 'codex'
};
const response = await api.getOrCreateSession({ tag: sessionTag, metadata, state });
const session = api.sessionSyncClient(response);
// Always report to daemon if it exists
try {
logger.debug(`[START] Reporting session ${response.id} to daemon`);
const result = await notifyDaemonSessionStarted(response.id, metadata);
if (result.error) {
logger.debug(`[START] Failed to report to daemon (may not be running):`, result.error);
} else {
logger.debug(`[START] Reported session ${response.id} to daemon`);
}
} catch (error) {
logger.debug('[START] Failed to report to daemon (may not be running):', error);
}
const messageQueue = new MessageQueue2<EnhancedMode>((mode) => hashObject({
permissionMode: mode.permissionMode,
model: mode.model,
}));
// Track current overrides to apply per message
let currentPermissionMode: PermissionMode | undefined = undefined;
let currentModel: string | undefined = undefined;
session.onUserMessage((message) => {
// Resolve permission mode (validate)
let messagePermissionMode = currentPermissionMode;
if (message.meta?.permissionMode) {
const validModes: PermissionMode[] = ['default', 'read-only', 'safe-yolo', 'yolo'];
if (validModes.includes(message.meta.permissionMode as PermissionMode)) {
messagePermissionMode = message.meta.permissionMode as PermissionMode;
currentPermissionMode = messagePermissionMode;
logger.debug(`[Codex] Permission mode updated from user message to: ${currentPermissionMode}`);
} else {
logger.debug(`[Codex] Invalid permission mode received: ${message.meta.permissionMode}`);
}
} else {
logger.debug(`[Codex] User message received with no permission mode override, using current: ${currentPermissionMode ?? 'default (effective)'}`);
}
// Resolve model; explicit null resets to default (undefined)
let messageModel = currentModel;
if (message.meta?.hasOwnProperty('model')) {
messageModel = message.meta.model || undefined;
currentModel = messageModel;
logger.debug(`[Codex] Model updated from user message: ${messageModel || 'reset to default'}`);
} else {
logger.debug(`[Codex] User message received with no model override, using current: ${currentModel || 'default'}`);
}
const enhancedMode: EnhancedMode = {
permissionMode: messagePermissionMode || 'default',
model: messageModel,
};
messageQueue.push(message.content.text, enhancedMode);
});
let thinking = false;
session.keepAlive(thinking, 'remote');
// Periodic keep-alive; store handle so we can clear on exit
const keepAliveInterval = setInterval(() => {
session.keepAlive(thinking, 'remote');
}, 2000);
const sendReady = () => {
session.sendSessionEvent({ type: 'ready' });
try {
api.push().sendToAllDevices(
"It's ready!",
'Codex is waiting for your command',
{ sessionId: session.sessionId }
);
} catch (pushError) {
logger.debug('[Codex] Failed to send ready push', pushError);
}
};
// Debug helper: log active handles/requests if DEBUG is enabled
function logActiveHandles(tag: string) {
if (!process.env.DEBUG) return;
const anyProc: any = process as any;
const handles = typeof anyProc._getActiveHandles === 'function' ? anyProc._getActiveHandles() : [];
const requests = typeof anyProc._getActiveRequests === 'function' ? anyProc._getActiveRequests() : [];
logger.debug(`[codex][handles] ${tag}: handles=${handles.length} requests=${requests.length}`);
try {
const kinds = handles.map((h: any) => (h && h.constructor ? h.constructor.name : typeof h));
logger.debug(`[codex][handles] kinds=${JSON.stringify(kinds)}`);
} catch { }
}
//
// Abort handling
// IMPORTANT: There are two different operations:
// 1. Abort (handleAbort): Stops the current inference/task but keeps the session alive
// - Used by the 'abort' RPC from mobile app
// - Similar to Claude Code's abort behavior
// - Allows continuing with new prompts after aborting
// 2. Kill (handleKillSession): Terminates the entire process
// - Used by the 'killSession' RPC
// - Completely exits the CLI process
//
let abortController = new AbortController();
let shouldExit = false;
let storedSessionIdForResume: string | null = null;
/**
* Handles aborting the current task/inference without exiting the process.
* This is the equivalent of Claude Code's abort - it stops what's currently
* happening but keeps the session alive for new prompts.
*/
async function handleAbort() {
logger.debug('[Codex] Abort requested - stopping current task');
try {
// Store the current session ID before aborting for potential resume
if (client.hasActiveSession()) {
storedSessionIdForResume = client.storeSessionForResume();
logger.debug('[Codex] Stored session for resume:', storedSessionIdForResume);
}
abortController.abort();
reasoningProcessor.abort();
logger.debug('[Codex] Abort completed - session remains active');
} catch (error) {
logger.debug('[Codex] Error during abort:', error);
} finally {
abortController = new AbortController();
}
}
/**
* Handles session termination and process exit.
* This is called when the session needs to be completely killed (not just aborted).
* Abort stops the current inference but keeps the session alive.
* Kill terminates the entire process.
*/
const handleKillSession = async () => {
logger.debug('[Codex] Kill session requested - terminating process');
await handleAbort();
logger.debug('[Codex] Abort completed, proceeding with termination');
try {
// Update lifecycle state to archived before closing
if (session) {
session.updateMetadata((currentMetadata) => ({
...currentMetadata,
lifecycleState: 'archived',
lifecycleStateSince: Date.now(),
archivedBy: 'cli',
archiveReason: 'User terminated'
}));
// Send session death message
session.sendSessionDeath();
await session.flush();
await session.close();
}
// Force close Codex transport (best-effort) so we don't leave stray processes
try {
await client.forceCloseSession();
} catch (e) {
logger.debug('[Codex] Error while force closing Codex session during termination', e);
}
// Stop caffeinate
stopCaffeinate();
// Stop Happy MCP server
happyServer.stop();
logger.debug('[Codex] Session termination complete, exiting');
process.exit(0);
} catch (error) {
logger.debug('[Codex] Error during session termination:', error);
process.exit(1);
}
};
// Register abort handler
session.rpcHandlerManager.registerHandler('abort', handleAbort);
registerKillSessionHandler(session.rpcHandlerManager, handleKillSession);
//
// Initialize Ink UI
//
const messageBuffer = new MessageBuffer();
const hasTTY = process.stdout.isTTY && process.stdin.isTTY;
let inkInstance: any = null;
if (hasTTY) {
console.clear();
inkInstance = render(React.createElement(CodexDisplay, {
messageBuffer,
logPath: process.env.DEBUG ? logger.getLogPath() : undefined,
onExit: async () => {
// Exit the agent
logger.debug('[codex]: Exiting agent via Ctrl-C');
shouldExit = true;
await handleAbort();
}
}), {
exitOnCtrlC: false,
patchConsole: false
});
}
if (hasTTY) {
process.stdin.resume();
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
process.stdin.setEncoding("utf8");
}
//
// Start Context
//
const client = new CodexMcpClient();
// Helper: find Codex session transcript for a given sessionId
function findCodexResumeFile(sessionId: string | null): string | null {
if (!sessionId) return null;
try {
const codexHomeDir = process.env.CODEX_HOME || join(os.homedir(), '.codex');
const rootDir = join(codexHomeDir, 'sessions');
// Recursively collect all files under the sessions directory
function collectFilesRecursive(dir: string, acc: string[] = []): string[] {
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return acc;
}
for (const entry of entries) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
collectFilesRecursive(full, acc);
} else if (entry.isFile()) {
acc.push(full);
}
}
return acc;
}
const candidates = collectFilesRecursive(rootDir)
.filter(full => full.endsWith(`-${sessionId}.jsonl`))
.filter(full => {
try { return fs.statSync(full).isFile(); } catch { return false; }
})
.sort((a, b) => {
const sa = fs.statSync(a).mtimeMs;
const sb = fs.statSync(b).mtimeMs;
return sb - sa; // newest first
});
return candidates[0] || null;
} catch {
return null;
}
}
const permissionHandler = new CodexPermissionHandler(session);
const reasoningProcessor = new ReasoningProcessor((message) => {
// Callback to send messages directly from the processor
session.sendCodexMessage(message);
});
const diffProcessor = new DiffProcessor((message) => {
// Callback to send messages directly from the processor
session.sendCodexMessage(message);
});
client.setPermissionHandler(permissionHandler);
client.setHandler((msg) => {
logger.debug(`[Codex] MCP message: ${JSON.stringify(msg)}`);
// Add messages to the ink UI buffer based on message type
if (msg.type === 'agent_message') {
messageBuffer.addMessage(msg.message, 'assistant');
} else if (msg.type === 'agent_reasoning_delta') {
// Skip reasoning deltas in the UI to reduce noise
} else if (msg.type === 'agent_reasoning') {
messageBuffer.addMessage(`[Thinking] ${msg.text.substring(0, 100)}...`, 'system');
} else if (msg.type === 'exec_command_begin') {
messageBuffer.addMessage(`Executing: ${msg.command}`, 'tool');
} else if (msg.type === 'exec_command_end') {
const output = msg.output || msg.error || 'Command completed';
const truncatedOutput = output.substring(0, 200);
messageBuffer.addMessage(
`Result: ${truncatedOutput}${output.length > 200 ? '...' : ''}`,
'result'
);
} else if (msg.type === 'task_started') {
messageBuffer.addMessage('Starting task...', 'status');
} else if (msg.type === 'task_complete') {
messageBuffer.addMessage('Task completed', 'status');
sendReady();
} else if (msg.type === 'turn_aborted') {
messageBuffer.addMessage('Turn aborted', 'status');
sendReady();
}
if (msg.type === 'task_started') {
if (!thinking) {
logger.debug('thinking started');
thinking = true;
session.keepAlive(thinking, 'remote');
}
}
if (msg.type === 'task_complete' || msg.type === 'turn_aborted') {
if (thinking) {
logger.debug('thinking completed');
thinking = false;
session.keepAlive(thinking, 'remote');
}
// Reset diff processor on task end or abort
diffProcessor.reset();
}
if (msg.type === 'agent_reasoning_section_break') {
// Reset reasoning processor for new section
reasoningProcessor.handleSectionBreak();
}
if (msg.type === 'agent_reasoning_delta') {
// Process reasoning delta - tool calls are sent automatically via callback
reasoningProcessor.processDelta(msg.delta);
}
if (msg.type === 'agent_reasoning') {
// Complete the reasoning section - tool results or reasoning messages sent via callback
reasoningProcessor.complete(msg.text);
}
if (msg.type === 'agent_message') {
session.sendCodexMessage({
type: 'message',
message: msg.message,
id: randomUUID()
});
}
if (msg.type === 'exec_command_begin' || msg.type === 'exec_approval_request') {
let { call_id, type, ...inputs } = msg;
session.sendCodexMessage({
type: 'tool-call',
name: 'CodexBash',
callId: call_id,
input: inputs,
id: randomUUID()
});
}
if (msg.type === 'exec_command_end') {
let { call_id, type, ...output } = msg;
session.sendCodexMessage({
type: 'tool-call-result',
callId: call_id,
output: output,
id: randomUUID()
});
}
if (msg.type === 'token_count') {
session.sendCodexMessage({
...msg,
id: randomUUID()
});
}
if (msg.type === 'patch_apply_begin') {
// Handle the start of a patch operation
let { call_id, auto_approved, changes } = msg;
// Add UI feedback for patch operation
const changeCount = Object.keys(changes).length;
const filesMsg = changeCount === 1 ? '1 file' : `${changeCount} files`;
messageBuffer.addMessage(`Modifying ${filesMsg}...`, 'tool');
// Send tool call message
session.sendCodexMessage({
type: 'tool-call',
name: 'CodexPatch',
callId: call_id,
input: {
auto_approved,
changes
},
id: randomUUID()
});
}
if (msg.type === 'patch_apply_end') {
// Handle the end of a patch operation
let { call_id, stdout, stderr, success } = msg;
// Add UI feedback for completion
if (success) {
const message = stdout || 'Files modified successfully';
messageBuffer.addMessage(message.substring(0, 200), 'result');
} else {
const errorMsg = stderr || 'Failed to modify files';
messageBuffer.addMessage(`Error: ${errorMsg.substring(0, 200)}`, 'result');
}
// Send tool call result message
session.sendCodexMessage({
type: 'tool-call-result',
callId: call_id,
output: {
stdout,
stderr,
success
},
id: randomUUID()
});
}
if (msg.type === 'turn_diff') {
// Handle turn_diff messages and track unified_diff changes
if (msg.unified_diff) {
diffProcessor.processDiff(msg.unified_diff);
}
}
});
// Start Happy MCP server (HTTP) and prepare STDIO bridge config for Codex
const happyServer = await startHappyServer(session);
const bridgeCommand = join(projectPath(), 'bin', 'happy-mcp.mjs');
const mcpServers = {
happy: {
command: bridgeCommand,
args: ['--url', happyServer.url]
}
} as const;
let first = true;
try {
logger.debug('[codex]: client.connect begin');
await client.connect();
logger.debug('[codex]: client.connect done');
let wasCreated = false;
let currentModeHash: string | null = null;
let pending: { message: string; mode: EnhancedMode; isolate: boolean; hash: string } | null = null;
// If we restart (e.g., mode change), use this to carry a resume file
let nextExperimentalResume: string | null = null;
while (!shouldExit) {
logActiveHandles('loop-top');
// Get next batch; respect mode boundaries like Claude
let message: { message: string; mode: EnhancedMode; isolate: boolean; hash: string } | null = pending;
pending = null;
if (!message) {
// Capture the current signal to distinguish idle-abort from queue close
const waitSignal = abortController.signal;
const batch = await messageQueue.waitForMessagesAndGetAsString(waitSignal);
if (!batch) {
// If wait was aborted (e.g., remote abort with no active inference), ignore and continue
if (waitSignal.aborted && !shouldExit) {
logger.debug('[codex]: Wait aborted while idle; ignoring and continuing');
continue;
}
logger.debug(`[codex]: batch=${!!batch}, shouldExit=${shouldExit}`);
break;
}
message = batch;
}
// Defensive check for TS narrowing
if (!message) {
break;
}
// If a session exists and mode changed, restart on next iteration
if (wasCreated && currentModeHash && message.hash !== currentModeHash) {
logger.debug('[Codex] Mode changed – restarting Codex session');
messageBuffer.addMessage('═'.repeat(40), 'status');
messageBuffer.addMessage('Starting new Codex session (mode changed)...', 'status');
// Capture previous sessionId and try to find its transcript to resume
try {
const prevSessionId = client.getSessionId();
nextExperimentalResume = findCodexResumeFile(prevSessionId);
if (nextExperimentalResume) {
logger.debug(`[Codex] Found resume file for session ${prevSessionId}: ${nextExperimentalResume}`);
messageBuffer.addMessage('Resuming previous context…', 'status');
} else {
logger.debug('[Codex] No resume file found for previous session');
}
} catch (e) {
logger.debug('[Codex] Error while searching resume file', e);
}
client.clearSession();
wasCreated = false;
currentModeHash = null;
pending = message;
// Reset processors/permissions like end-of-turn cleanup
permissionHandler.reset();
reasoningProcessor.abort();
diffProcessor.reset();
thinking = false;
session.keepAlive(thinking, 'remote');
continue;
}
// Display user messages in the UI
messageBuffer.addMessage(message.message, 'user');
currentModeHash = message.hash;
try {
// Map permission mode to approval policy and sandbox for startSession
const approvalPolicy = (() => {
switch (message.mode.permissionMode) {
case 'default': return 'untrusted' as const;
case 'read-only': return 'never' as const;
case 'safe-yolo': return 'on-failure' as const;
case 'yolo': return 'on-failure' as const;
}
})();
const sandbox = (() => {
switch (message.mode.permissionMode) {
case 'default': return 'workspace-write' as const;
case 'read-only': return 'read-only' as const;
case 'safe-yolo': return 'workspace-write' as const;
case 'yolo': return 'danger-full-access' as const;
}
})();
if (!wasCreated) {
const startConfig: CodexSessionConfig = {
prompt: first ? message.message + '\n\n' + CHANGE_TITLE_INSTRUCTION : message.message,
sandbox,
'approval-policy': approvalPolicy,
config: { mcp_servers: mcpServers }
};
if (message.mode.model) {
startConfig.model = message.mode.model;
}
// Check for resume file from multiple sources
let resumeFile: string | null = null;
// Priority 1: Explicit resume file from mode change
if (nextExperimentalResume) {
resumeFile = nextExperimentalResume;
nextExperimentalResume = null; // consume once
logger.debug('[Codex] Using resume file from mode change:', resumeFile);
}
// Priority 2: Resume from stored abort session
else if (storedSessionIdForResume) {
const abortResumeFile = findCodexResumeFile(storedSessionIdForResume);
if (abortResumeFile) {
resumeFile = abortResumeFile;
logger.debug('[Codex] Using resume file from aborted session:', resumeFile);
messageBuffer.addMessage('Resuming from aborted session...', 'status');
}
storedSessionIdForResume = null; // consume once
}
// Apply resume file if found
if (resumeFile) {
(startConfig.config as any).experimental_resume = resumeFile;
}
await client.startSession(
startConfig,
{ signal: abortController.signal }
);
wasCreated = true;
first = false;
} else {
const response = await client.continueSession(
message.message,
{ signal: abortController.signal }
);
logger.debug('[Codex] continueSession response:', response);
}
} catch (error) {
logger.warn('Error in codex session:', error);
const isAbortError = error instanceof Error && error.name === 'AbortError';
if (isAbortError) {
messageBuffer.addMessage('Aborted by user', 'status');
session.sendSessionEvent({ type: 'message', message: 'Aborted by user' });
// Abort cancels the current task/inference but keeps the Codex session alive.
// Do not clear session state here; the next user message should continue on the
// existing session if possible.
} else {
messageBuffer.addMessage('Process exited unexpectedly', 'status');
session.sendSessionEvent({ type: 'message', message: 'Process exited unexpectedly' });
// For unexpected exits, try to store session for potential recovery
if (client.hasActiveSession()) {
storedSessionIdForResume = client.storeSessionForResume();
logger.debug('[Codex] Stored session after unexpected error:', storedSessionIdForResume);
}
}
} finally {
// Reset permission handler, reasoning processor, and diff processor
permissionHandler.reset();
reasoningProcessor.abort(); // Use abort to properly finish any in-progress tool calls
diffProcessor.reset();
thinking = false;
session.keepAlive(thinking, 'remote');
emitReadyIfIdle({
pending,
queueSize: () => messageQueue.size(),
shouldExit,
sendReady,
});
logActiveHandles('after-turn');
}
}
} finally {
// Clean up resources when main loop exits
logger.debug('[codex]: Final cleanup start');
logActiveHandles('cleanup-start');
try {
logger.debug('[codex]: sendSessionDeath');
session.sendSessionDeath();
logger.debug('[codex]: flush begin');
await session.flush();
logger.debug('[codex]: flush done');
logger.debug('[codex]: session.close begin');
await session.close();
logger.debug('[codex]: session.close done');
} catch (e) {
logger.debug('[codex]: Error while closing session', e);
}
logger.debug('[codex]: client.forceCloseSession begin');
await client.forceCloseSession();
logger.debug('[codex]: client.forceCloseSession done');
// Stop Happy MCP server
logger.debug('[codex]: happyServer.stop');
happyServer.stop();
// Clean up ink UI
if (process.stdin.isTTY) {
logger.debug('[codex]: setRawMode(false)');
try { process.stdin.setRawMode(false); } catch { }
}
// Stop reading from stdin so the process can exit
if (hasTTY) {
logger.debug('[codex]: stdin.pause()');
try { process.stdin.pause(); } catch { }
}
// Clear periodic keep-alive to avoid keeping event loop alive
logger.debug('[codex]: clearInterval(keepAlive)');
clearInterval(keepAliveInterval);
if (inkInstance) {
logger.debug('[codex]: inkInstance.unmount()');
inkInstance.unmount();
}
messageBuffer.clear();
logActiveHandles('cleanup-end');
logger.debug('[codex]: Final cleanup completed');
}
}