@radnine/claude-session-daemon 0.8.3 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1081 @@
1
+ 'use strict';
2
+
3
+ const { EventEmitter } = require('node:events');
4
+ const childProcess = require('node:child_process');
5
+ const defaultSpawn = childProcess.spawn;
6
+ const { createInterface } = require('node:readline');
7
+ const fs = require('node:fs');
8
+ const os = require('node:os');
9
+ const path = require('node:path');
10
+ const { TurnTracker } = require('./turn-tracker');
11
+ const { CodexTranslator } = require('./codex-translator');
12
+ const { stripDaemonSecrets } = require('./harness');
13
+
14
+ const REQUEST_TIMEOUT_MS = 60000;
15
+
16
+ // Codex features that add MCP servers or plugins of their own, on top of the
17
+ // config file: `apps` is the built-in codex_apps connector server.
18
+ const NO_CHATGPT_EXTRAS = ['apps', 'plugins', 'remote_plugin'];
19
+
20
+ // Env vars Codex does not hand to MCP servers on its own (it passes a few base
21
+ // variables and does not expand ${VAR}). The rad MCP server reads the first
22
+ // four; CLAUDE_SESSION_ID is the chat's own session id.
23
+ const RAD_ENV_VARS = ['CLAUDE_SESSION_ID', 'FLIGHTDECK_URL', 'RAD_URL', 'RAD_TOKEN'];
24
+
25
+ // Names an MCP entry's env map may not change in the child's env, because Codex
26
+ // itself, and every shell command a chat runs, runs with them. CLAUDE_SESSION_ID
27
+ // is the chat's own id. The proxy names match in any case, as tools read both.
28
+ const GUARDED_ENV_VARS = new Set(['PATH', 'HOME', 'CLAUDE_SESSION_ID', 'NODE_OPTIONS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'NODE_EXTRA_CA_CERTS']);
29
+ const GUARDED_ENV_PREFIXES = ['CODEX_', 'OPENAI_', 'ANTHROPIC_', 'LD_', 'DYLD_'];
30
+ const PROXY_ENV_VARS = new Set(['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY']);
31
+
32
+ function isGuardedEnvVar(name) {
33
+ return GUARDED_ENV_VARS.has(name)
34
+ || PROXY_ENV_VARS.has(name.toUpperCase())
35
+ || GUARDED_ENV_PREFIXES.some((prefix) => name.startsWith(prefix));
36
+ }
37
+
38
+ // Codex server names become a dotted config key (mcp_servers.<name>.command).
39
+ const MCP_SERVER_NAME = /^[A-Za-z0-9_-]+$/;
40
+
41
+ /**
42
+ * Wraps one `codex app-server` child (JSON-RPC over stdio) for one FlightDeck
43
+ * chat, and keeps one Codex thread alive across turns. It follows the harness
44
+ * contract in harness.js and writes the same stream-json events as
45
+ * ClaudeProcess, so Rails and the terminal render a Codex chat unchanged.
46
+ *
47
+ * The Codex thread id is the chat's resume handle. It is exposed as
48
+ * `claudeSessionId` (the daemon's name for the vendor session id), which the
49
+ * daemon reports in `session_activated` and Rails stores; after a daemon
50
+ * restart Rails passes it back and the process resumes the thread.
51
+ */
52
+ class CodexProcess extends EventEmitter {
53
+ /**
54
+ * @param {string} sessionId - FlightDeck session id
55
+ * @param {object} [options]
56
+ * @param {string} [options.workingDir]
57
+ * @param {string} [options.claudeSessionId] - Codex thread id to resume (with options.resume)
58
+ * @param {boolean} [options.resume]
59
+ * @param {object} [options.logger]
60
+ * @param {string} [options.codexCommand] - path to the codex binary
61
+ * @param {string} [options.systemPrompt] - persona prompt, sent as developer instructions
62
+ * @param {string} [options.model] - Codex model id
63
+ * @param {string} [options.effort] - reasoning effort for each turn
64
+ * @param {object} [options.sessionEnv] - extra env for the child
65
+ * @param {{command: string, args: string[], env?: object}} [options.radMcp] - how to start the rad MCP server
66
+ * @param {Array<{name: string, command: string, args: string[], env?: object}>} [options.mcpServers] - the other
67
+ * MCP servers; by default the stdio servers a Claude chat in workingDir gets (findMcpServers)
68
+ * @param {Function} [options._spawnFn] - tests: replacement for child_process.spawn
69
+ */
70
+ constructor(sessionId, options = {}) {
71
+ super();
72
+
73
+ this._sessionId = sessionId;
74
+ this._resumeThreadId = options.resume ? options.claudeSessionId || null : null;
75
+ this._threadId = null;
76
+ this._workingDir = options.workingDir || process.cwd();
77
+ this._logger = options.logger || _defaultLogger();
78
+ this._codexCommand = options.codexCommand || 'codex';
79
+ this._spawnFn = options._spawnFn || defaultSpawn;
80
+ this._sessionEnv = options.sessionEnv || {};
81
+ this._systemPrompt = options.systemPrompt || null;
82
+ this._model = options.model || null;
83
+ this._effort = options.effort || null;
84
+ this._radMcp = options.radMcp;
85
+ this._mcpServers = options.mcpServers;
86
+ this._skillRoots = [];
87
+ this._memoryIndex = null;
88
+
89
+ this._state = 'idle';
90
+ this._child = null;
91
+ this._pid = null;
92
+ this._startedAt = null;
93
+
94
+ this._nextRequestId = 0;
95
+ this._pending = new Map(); // request id -> { resolve, reject, timer, method }
96
+ this._ready = null;
97
+ this._translator = null;
98
+ this._inbox = []; // messages waiting for the next turn
99
+ this._busy = false; // a turn is starting or running
100
+ this._activeTurnId = null;
101
+ this._interruptPending = false;
102
+ this._turnSeq = 0;
103
+ this._turnToken = 0;
104
+
105
+ this._turns = new TurnTracker();
106
+ }
107
+
108
+ // -------------------------------------------------------------------------
109
+ // Public API (the harness contract)
110
+ // -------------------------------------------------------------------------
111
+
112
+ spawn() {
113
+ if (this._state !== 'idle') {
114
+ throw new Error(`Cannot spawn: process is not idle (state=${this._state})`);
115
+ }
116
+
117
+ this._state = 'spawning';
118
+
119
+ const baseEnv = buildCodexEnv(process.env, this._sessionEnv, this._sessionId);
120
+ baseEnv.CODEX_HOME = prepareCodexHome(baseEnv);
121
+ const mcpServers = this._mcpServers === undefined
122
+ ? findMcpServers({ env: baseEnv, workingDir: this._workingDir, logger: this._logger })
123
+ : this._mcpServers;
124
+ const { args, env } = buildCodexLaunch({
125
+ env: baseEnv,
126
+ radMcp: this._radMcp,
127
+ mcpServers,
128
+ writableRoots: gitWritableRoots(this._workingDir),
129
+ logger: this._logger,
130
+ });
131
+ this._skillRoots = claudeSkillRoots(env, this._workingDir);
132
+ this._memoryIndex = memoryIndexPath(env, this._workingDir);
133
+
134
+ this._logger.info(`Spawning Codex app-server: ${this._codexCommand}`, {
135
+ sessionId: this._sessionId,
136
+ threadId: this._resumeThreadId,
137
+ cwd: this._workingDir,
138
+ model: this._model,
139
+ authMode: codexAuthMode(env),
140
+ codexHome: env.CODEX_HOME,
141
+ });
142
+
143
+ this._child = this._spawnFn(this._codexCommand, args, {
144
+ cwd: this._workingDir,
145
+ stdio: ['pipe', 'pipe', 'pipe'],
146
+ env,
147
+ });
148
+
149
+ if (this._child.stdin && typeof this._child.stdin.on === 'function') {
150
+ this._child.stdin.on('error', (err) => {
151
+ this._logger.warn('Codex stdin error', { pid: this._pid, error: err.message });
152
+ });
153
+ }
154
+
155
+ this._pid = this._child.pid;
156
+ this._startedAt = Date.now();
157
+ this._state = 'running';
158
+
159
+ this._setupStdout();
160
+ this._setupStderr();
161
+ this._setupError();
162
+ this._setupClose();
163
+
164
+ this._ready = this._handshake();
165
+ this._ready.catch((err) => {
166
+ this._logger.error('Codex handshake failed', { sessionId: this._sessionId, error: err.message });
167
+ });
168
+
169
+ this.emit('spawned');
170
+ }
171
+
172
+ /**
173
+ * Resolves once the thread exists (or is resumed) and claudeSessionId is
174
+ * known. The daemon awaits it right after spawn().
175
+ * @returns {Promise<void>}
176
+ */
177
+ ready() {
178
+ return this._ready || Promise.reject(new Error('Codex process was not spawned'));
179
+ }
180
+
181
+ sendMessage(text, commandId = null) {
182
+ if (this._state !== 'running' || !this._child) {
183
+ this._logger.warn('Cannot send message: process not running');
184
+ return false;
185
+ }
186
+
187
+ this._turns.written(commandId, text);
188
+ this._inbox.push(text);
189
+ this._logger.debug('Queued message for Codex', { length: text.length, commandId });
190
+ this._pump();
191
+ return true;
192
+ }
193
+
194
+ sendSlashCommand(command, commandId = null) {
195
+ return this.sendMessage(command, commandId);
196
+ }
197
+
198
+ /**
199
+ * Stop the running turn with turn/interrupt. The process and the thread stay,
200
+ * and the next message starts a new turn.
201
+ * @returns {boolean} true if there was nothing to stop or the request went out
202
+ */
203
+ interrupt() {
204
+ if (this._state !== 'running' || !this._child) {
205
+ this._logger.warn('Cannot interrupt: process not running');
206
+ return false;
207
+ }
208
+ if (!this._busy) return true;
209
+
210
+ if (!this._activeTurnId) {
211
+ // turn/start has not answered yet; interrupt as soon as it does.
212
+ this._interruptPending = true;
213
+ return true;
214
+ }
215
+
216
+ this._logger.info('Interrupting Codex turn', { pid: this._pid, turnId: this._activeTurnId });
217
+ this._request('turn/interrupt', { threadId: this._threadId, turnId: this._activeTurnId }).catch((err) => {
218
+ this._logger.error('turn/interrupt failed', { error: err.message });
219
+ });
220
+ return true;
221
+ }
222
+
223
+ async kill(timeoutMs = 5000) {
224
+ if (this._state !== 'running' && this._state !== 'spawning') {
225
+ return;
226
+ }
227
+
228
+ this._state = 'stopping';
229
+ this._logger.info('Stopping Codex process', { pid: this._pid });
230
+
231
+ try {
232
+ this._child.stdin.end();
233
+ } catch (_) { /* ignore */ }
234
+
235
+ try {
236
+ this._child.kill('SIGTERM');
237
+ } catch (_) { /* ignore if already dead */ }
238
+
239
+ const exited = await this._waitForExit(timeoutMs);
240
+
241
+ if (!exited) {
242
+ this._logger.warn('Process did not exit after SIGTERM, sending SIGKILL', { pid: this._pid });
243
+ try {
244
+ this._child.kill('SIGKILL');
245
+ } catch (_) { /* ignore */ }
246
+ await this._waitForExit(2000);
247
+ }
248
+
249
+ this._state = 'stopped';
250
+ }
251
+
252
+ isAlive() {
253
+ if (!this._child || !this._pid) return false;
254
+ if (this._state === 'stopped') return false;
255
+
256
+ try {
257
+ return this._child.kill(0) !== false;
258
+ } catch (_) {
259
+ return false;
260
+ }
261
+ }
262
+
263
+ // -------------------------------------------------------------------------
264
+ // Getters
265
+ // -------------------------------------------------------------------------
266
+
267
+ get pid() { return this._pid; }
268
+ get state() { return this._state; }
269
+ get sessionId() { return this._sessionId; }
270
+ /** The Codex thread id: what Rails stores and passes back to resume. */
271
+ get claudeSessionId() { return this._threadId || this._resumeThreadId; }
272
+ get startedAt() { return this._startedAt; }
273
+ get workingDir() { return this._workingDir; }
274
+ get currentCommandId() { return this._turns.currentCommandId; }
275
+ unfinishedCommandIds() { return this._turns.unfinishedCommandIds(); }
276
+ readCommandIds() { return this._turns.readCommandIds(); }
277
+
278
+ // -------------------------------------------------------------------------
279
+ // Handshake and turns
280
+ // -------------------------------------------------------------------------
281
+
282
+ async _handshake() {
283
+ await this._request('initialize', {
284
+ clientInfo: { name: 'flightdeck-daemon', title: 'FlightDeck', version: '1' },
285
+ capabilities: null,
286
+ });
287
+ this._notify('initialized');
288
+
289
+ // Codex loads repo skills only from .agents/skills and .codex/skills. Add
290
+ // the Claude skills folders before the thread starts, so its first turn
291
+ // sees them. A Codex without this call still gets a working chat.
292
+ if (this._skillRoots.length) {
293
+ try {
294
+ await this._request('skills/extraRoots/set', { extraRoots: this._skillRoots });
295
+ } catch (err) {
296
+ this._logger.warn('Codex did not take the Claude skills folders', { roots: this._skillRoots, error: err.message });
297
+ }
298
+ }
299
+
300
+ // workspace-write with network (set in buildCodexArgs): git commit works in
301
+ // a worktree, and git push / package installs reach the network.
302
+ const params = {
303
+ cwd: this._workingDir,
304
+ approvalPolicy: 'never',
305
+ sandbox: 'workspace-write',
306
+ };
307
+ if (this._model) params.model = this._model;
308
+ const instructions = developerInstructions(this._systemPrompt, this._memoryIndex);
309
+ if (instructions) params.developerInstructions = instructions;
310
+
311
+ let response;
312
+ if (this._resumeThreadId) {
313
+ response = await this._request('thread/resume', { threadId: this._resumeThreadId, ...params });
314
+ } else {
315
+ response = await this._request('thread/start', params);
316
+ }
317
+
318
+ this._threadId = response.thread.id;
319
+ this._translator = new CodexTranslator({
320
+ threadId: this._threadId,
321
+ model: response.model || this._model,
322
+ cwd: this._workingDir,
323
+ });
324
+ this._logger.info('Codex thread ready', {
325
+ sessionId: this._sessionId, threadId: this._threadId, resumed: !!this._resumeThreadId,
326
+ });
327
+
328
+ this._pump();
329
+ }
330
+
331
+ // Start the next queued message as a turn, when none is running.
332
+ _pump() {
333
+ if (!this._translator || this._busy || this._state !== 'running') return;
334
+ const text = this._inbox.shift();
335
+ if (text === undefined) return;
336
+
337
+ this._busy = true;
338
+ this._activeTurnId = null;
339
+ this._translator.messageSent(text);
340
+
341
+ const params = {
342
+ threadId: this._threadId,
343
+ input: [{ type: 'text', text, text_elements: [] }],
344
+ };
345
+ if (this._effort) params.effort = this._effort;
346
+
347
+ // A turn/start answer belongs to the turn that sent it. If that turn already
348
+ // finished and the next one started, the answer is stale and must not
349
+ // become the next turn's active id.
350
+ const token = ++this._turnSeq;
351
+ this._turnToken = token;
352
+
353
+ this._request('turn/start', params).then((response) => {
354
+ if (token !== this._turnToken) return;
355
+ const turnId = response && response.turn && response.turn.id;
356
+ if (this._busy && !this._activeTurnId) this._activeTurnId = turnId || null;
357
+ if (this._interruptPending) {
358
+ this._interruptPending = false;
359
+ this.interrupt();
360
+ }
361
+ }).catch((err) => {
362
+ if (token !== this._turnToken) return;
363
+ this._logger.error('turn/start failed', { error: err.message });
364
+ this._failTurn(err.message);
365
+ });
366
+ }
367
+
368
+ // A turn that never started: show the error and end it like any other turn,
369
+ // so the chat does not wait on it forever.
370
+ _failTurn(message) {
371
+ this._interruptPending = false;
372
+ const events = [
373
+ ...this._translator.translate('turn/started', { turn: { id: null } }),
374
+ ...this._translator.translate('error', { error: { message: `Codex could not start the turn: ${message}` }, willRetry: false }),
375
+ ...this._translator.translate('turn/completed', { turn: { id: null, status: 'failed' } }),
376
+ ];
377
+ this._emitEvents(events);
378
+ this._busy = false;
379
+ this._activeTurnId = null;
380
+ this._pump();
381
+ }
382
+
383
+ _onNotification(method, params) {
384
+ if (!this._translator) return;
385
+ if (params && params.threadId && params.threadId !== this._threadId) return;
386
+
387
+ if (method === 'turn/started' && params.turn) this._activeTurnId = params.turn.id;
388
+
389
+ // A malformed notification must not take the daemon down: show the error
390
+ // in the chat and keep the process running.
391
+ let events;
392
+ try {
393
+ events = this._translator.translate(method, params);
394
+ } catch (err) {
395
+ this._logger.error('Codex notification could not be translated', { method, error: err.message });
396
+ events = [];
397
+ try {
398
+ events = [this._translator._assistant(
399
+ [{ type: 'text', text: `FlightDeck could not read a Codex ${method} message: ${err.message}` }],
400
+ `codex-error-${Date.now()}`,
401
+ )];
402
+ } catch (_) { /* nothing more to show */ }
403
+ // Rails ends a turn only on a result event, so a turn whose completion
404
+ // could not be read still needs one or the chat input stays disabled.
405
+ if (method === 'turn/completed') {
406
+ events.push({
407
+ type: 'result',
408
+ subtype: 'error_during_execution',
409
+ is_error: true,
410
+ duration_ms: 0,
411
+ duration_api_ms: 0,
412
+ num_turns: 1,
413
+ result: `FlightDeck could not read a Codex ${method} message: ${err.message}`,
414
+ total_cost_usd: 0,
415
+ session_id: this._threadId,
416
+ });
417
+ }
418
+ }
419
+ this._emitEvents(events);
420
+
421
+ if (method === 'turn/completed') {
422
+ // An interrupt still waiting for the turn/start answer belonged to this
423
+ // turn, which is over. Keeping it would interrupt the next turn.
424
+ this._interruptPending = false;
425
+ this._busy = false;
426
+ this._activeTurnId = null;
427
+ this._pump();
428
+ }
429
+ }
430
+
431
+ _emitEvents(events) {
432
+ for (const event of events) {
433
+ this.emit('output', event, this._turns.observe(event));
434
+ }
435
+ }
436
+
437
+ // Codex asks before things the approval policy allows it to ask about. With
438
+ // "never" it should not; if it does, refuse rather than hang the turn.
439
+ _onServerRequest(message) {
440
+ const { id, method } = message;
441
+ this._logger.warn('Codex server request', { method });
442
+ if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval') {
443
+ this._respond(id, { decision: 'decline' });
444
+ return;
445
+ }
446
+ this._respondError(id, -32601, `FlightDeck does not handle ${method}`);
447
+ }
448
+
449
+ // -------------------------------------------------------------------------
450
+ // JSON-RPC plumbing
451
+ // -------------------------------------------------------------------------
452
+
453
+ _write(obj) {
454
+ const payload = JSON.stringify(obj) + '\n';
455
+ try {
456
+ this._child.stdin.write(payload);
457
+ return true;
458
+ } catch (err) {
459
+ this._logger.warn('Failed to write to Codex stdin', { error: err.message });
460
+ return false;
461
+ }
462
+ }
463
+
464
+ _request(method, params) {
465
+ return new Promise((resolve, reject) => {
466
+ if (this._state !== 'running' || !this._child) {
467
+ reject(new Error(`Codex process is not running (${method})`));
468
+ return;
469
+ }
470
+ const id = ++this._nextRequestId;
471
+ const timer = setTimeout(() => {
472
+ this._pending.delete(id);
473
+ reject(new Error(`Codex did not answer ${method} within ${REQUEST_TIMEOUT_MS / 1000}s`));
474
+ }, REQUEST_TIMEOUT_MS);
475
+ if (timer.unref) timer.unref();
476
+ this._pending.set(id, { resolve, reject, timer, method });
477
+ if (!this._write({ id, method, params })) {
478
+ clearTimeout(timer);
479
+ this._pending.delete(id);
480
+ reject(new Error(`Could not write ${method} to Codex`));
481
+ }
482
+ });
483
+ }
484
+
485
+ _notify(method, params) {
486
+ this._write(params === undefined ? { method } : { method, params });
487
+ }
488
+
489
+ _respond(id, result) {
490
+ this._write({ id, result });
491
+ }
492
+
493
+ _respondError(id, code, message) {
494
+ this._write({ id, error: { code, message } });
495
+ }
496
+
497
+ _setupStdout() {
498
+ const rl = createInterface({ input: this._child.stdout });
499
+
500
+ rl.on('line', (line) => {
501
+ if (!line) return;
502
+
503
+ let message;
504
+ try {
505
+ message = JSON.parse(line);
506
+ } catch (_) {
507
+ this._logger.warn('Unparseable Codex stdout line', { line: line.slice(0, 200) });
508
+ this.emit('error', line);
509
+ return;
510
+ }
511
+
512
+ if (message.method && message.id !== undefined) {
513
+ this._onServerRequest(message);
514
+ } else if (message.method) {
515
+ this._onNotification(message.method, message.params || {});
516
+ } else if (message.id !== undefined) {
517
+ this._onResponse(message);
518
+ }
519
+ });
520
+ }
521
+
522
+ _onResponse(message) {
523
+ const pending = this._pending.get(message.id);
524
+ if (!pending) return;
525
+ this._pending.delete(message.id);
526
+ clearTimeout(pending.timer);
527
+
528
+ if (message.error) {
529
+ pending.reject(new Error(message.error.message || `Codex error on ${pending.method}`));
530
+ } else {
531
+ pending.resolve(message.result);
532
+ }
533
+ }
534
+
535
+ _setupStderr() {
536
+ const rl = createInterface({ input: this._child.stderr });
537
+
538
+ rl.on('line', (line) => {
539
+ if (!line) return;
540
+ this._logger.warn('Codex stderr', { line });
541
+ this.emit('stderr', line);
542
+ });
543
+ }
544
+
545
+ // The child could not be spawned (codex not installed, wrong command). Node
546
+ // throws an uncaught exception for an unhandled 'error' event, which would
547
+ // take the whole daemon down with every other chat on it.
548
+ _setupError() {
549
+ this._child.on('error', (err) => {
550
+ const message = err && err.code === 'ENOENT'
551
+ ? `Codex CLI not found: ${this._codexCommand}`
552
+ : `Codex process error: ${err && err.message}`;
553
+ this._logger.error(message, { sessionId: this._sessionId, error: err && err.message });
554
+ this._state = 'stopped';
555
+ const failure = new Error(message);
556
+ for (const [id, pending] of this._pending) {
557
+ clearTimeout(pending.timer);
558
+ pending.reject(failure);
559
+ this._pending.delete(id);
560
+ }
561
+ if (this.listenerCount('error') > 0) this.emit('error', message);
562
+ });
563
+ }
564
+
565
+ _setupClose() {
566
+ this._child.on('close', (code, signal) => {
567
+ this._logger.info('Codex process exited', { code, signal, pid: this._pid });
568
+ this._state = 'stopped';
569
+ for (const [id, pending] of this._pending) {
570
+ clearTimeout(pending.timer);
571
+ pending.reject(new Error(`Codex exited before answering ${pending.method}`));
572
+ this._pending.delete(id);
573
+ }
574
+ this.emit('exit', code, signal, {
575
+ commandId: this._turns.newestWrittenCommandId,
576
+ unfinishedCommandIds: this._turns.unfinishedCommandIds(),
577
+ readCommandIds: this._turns.readCommandIds(),
578
+ });
579
+ });
580
+ }
581
+
582
+ _waitForExit(timeoutMs) {
583
+ return new Promise((resolve) => {
584
+ if (this._state === 'stopped') {
585
+ resolve(true);
586
+ return;
587
+ }
588
+
589
+ let timer;
590
+ const onClose = () => {
591
+ clearTimeout(timer);
592
+ resolve(true);
593
+ };
594
+
595
+ timer = setTimeout(() => {
596
+ this._child.removeListener('close', onClose);
597
+ resolve(false);
598
+ }, timeoutMs);
599
+
600
+ this._child.once('close', onClose);
601
+ });
602
+ }
603
+ }
604
+
605
+ // ---------------------------------------------------------------------------
606
+ // Spawn environment and arguments
607
+ // ---------------------------------------------------------------------------
608
+
609
+ /**
610
+ * `chatgpt` (default): the chat runs on the ChatGPT login in ~/.codex/auth.json,
611
+ * so OPENAI_API_KEY and CODEX_API_KEY are removed from the child's env; a key
612
+ * in the daemon's env would otherwise bill the API instead of the plan.
613
+ * `api_key`: the pilot opted in with CODEX_AUTH_MODE=api_key and keeps its key.
614
+ */
615
+ function codexAuthMode(env) {
616
+ return String(env.CODEX_AUTH_MODE || 'chatgpt').toLowerCase() === 'api_key' ? 'api_key' : 'chatgpt';
617
+ }
618
+
619
+ function buildCodexEnv(baseEnv, sessionEnv, sessionId) {
620
+ const env = { ...baseEnv, ...sessionEnv, CLAUDE_SESSION_ID: sessionId };
621
+ delete env.CLAUDECODE; // same nested-session guard as the Claude harness
622
+ stripDaemonSecrets(env);
623
+
624
+ if (codexAuthMode(env) !== 'api_key') {
625
+ delete env.OPENAI_API_KEY;
626
+ delete env.CODEX_API_KEY;
627
+ }
628
+ return env;
629
+ }
630
+
631
+ /**
632
+ * How Claude chats reach the rad MCP server on a pilot: the user-scope `rad`
633
+ * entry the FlightDeck installer wrote to Claude's config, which runs
634
+ * ~/.flightdeck/rad-mcp (the launcher reads RAD_URL and RAD_TOKEN from
635
+ * ~/.flightdeck/rad-mcp.env). Codex gets the same command.
636
+ *
637
+ * The entry's `env` map is returned too, so a pilot (or a test stack) that
638
+ * points rad at another Rails through that map gets the same behaviour on Codex.
639
+ *
640
+ * @returns {{command: string, args: string[], env?: object}|null}
641
+ */
642
+ function findRadMcp(env = process.env, home = os.homedir()) {
643
+ const rad = readJson(claudeConfigFile(env, home))?.mcpServers?.rad;
644
+ if (rad && typeof rad.command === 'string' && Array.isArray(rad.args)) {
645
+ const found = { command: rad.command, args: rad.args.map(String) };
646
+ const radEnv = stringEnv(rad.env);
647
+ if (radEnv) found.env = radEnv;
648
+ return found;
649
+ }
650
+
651
+ const launcher = path.join(home, '.flightdeck', 'rad-mcp');
652
+ if (fs.existsSync(launcher)) return { command: 'ruby', args: [launcher] };
653
+ return null;
654
+ }
655
+
656
+ // ---------------------------------------------------------------------------
657
+ // What a Claude chat in the same directory gets (#491)
658
+ // ---------------------------------------------------------------------------
659
+
660
+ // The Claude CLI's config directory (global CLAUDE.md, skills, project memory)
661
+ // and its main config file (MCP servers), the way the CLI finds them.
662
+ function claudeConfigDir(env = process.env, home = os.homedir()) {
663
+ return env.CLAUDE_CONFIG_DIR || path.join(home, '.claude');
664
+ }
665
+
666
+ function claudeConfigFile(env = process.env, home = os.homedir()) {
667
+ return env.CLAUDE_CONFIG_DIR ? path.join(env.CLAUDE_CONFIG_DIR, '.claude.json') : path.join(home, '.claude.json');
668
+ }
669
+
670
+ function readJson(file) {
671
+ try {
672
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
673
+ } catch (_) {
674
+ return null; // missing, or not JSON
675
+ }
676
+ }
677
+
678
+ function isDirectory(dir) {
679
+ try {
680
+ return fs.statSync(dir).isDirectory();
681
+ } catch (_) {
682
+ return false;
683
+ }
684
+ }
685
+
686
+ /**
687
+ * The Claude skills folders for a chat in `workingDir`: the repo's
688
+ * `.claude/skills` and the user's Claude skills folder, the ones that exist.
689
+ * Codex follows symlinked skill folders (checked on 0.162.1).
690
+ *
691
+ * A folder Codex already loads by itself (`.agents/skills` and `.codex/skills`
692
+ * in the repo, `~/.agents/skills`, `$CODEX_HOME/skills`), or one already in
693
+ * this list, is left out, compared by real path. A repo whose `.claude/skills`
694
+ * is a symlink to `.agents/skills` would otherwise get its skills relabelled
695
+ * from repo to user: Codex lists a folder once, under the scope of the last
696
+ * root that named it.
697
+ */
698
+ function claudeSkillRoots(env = process.env, workingDir = process.cwd(), home = os.homedir()) {
699
+ const native = [
700
+ path.join(workingDir, '.agents', 'skills'),
701
+ path.join(workingDir, '.codex', 'skills'),
702
+ path.join(home, '.agents', 'skills'),
703
+ ];
704
+ if (env.CODEX_HOME) native.push(path.join(env.CODEX_HOME, 'skills'));
705
+ const seen = new Set(native.filter(isDirectory).map(realPath));
706
+
707
+ const roots = [];
708
+ for (const root of [path.join(workingDir, '.claude', 'skills'), path.join(claudeConfigDir(env, home), 'skills')]) {
709
+ if (!isDirectory(root)) continue;
710
+ const real = realPath(root);
711
+ if (seen.has(real)) continue;
712
+ seen.add(real);
713
+ roots.push(root);
714
+ }
715
+ return roots;
716
+ }
717
+
718
+ function realPath(dir) {
719
+ try {
720
+ return fs.realpathSync(dir);
721
+ } catch (_) {
722
+ return path.resolve(dir);
723
+ }
724
+ }
725
+
726
+ /**
727
+ * The Claude project memory index for `workingDir`, or null. Claude names the
728
+ * project folder after the cwd with every character other than a letter or
729
+ * digit turned into "-".
730
+ */
731
+ function memoryIndexPath(env = process.env, workingDir = process.cwd(), home = os.homedir()) {
732
+ const project = workingDir.replace(/[^a-zA-Z0-9]/g, '-');
733
+ const index = path.join(claudeConfigDir(env, home), 'projects', project, 'memory', 'MEMORY.md');
734
+ return fs.existsSync(index) ? index : null;
735
+ }
736
+
737
+ // The persona prompt, plus one line pointing at the memory index when there is one.
738
+ function developerInstructions(systemPrompt, memoryIndex) {
739
+ if (!memoryIndex) return systemPrompt || null;
740
+ const line = `Before you start, read your memory index at ${memoryIndex}. It lists what earlier chats in this repo learned; open the files it links to when they bear on your task.`;
741
+ return systemPrompt ? `${systemPrompt}\n\n${line}` : line;
742
+ }
743
+
744
+ /**
745
+ * Expand `${VAR}` and `${VAR:-default}` against `env`, as Claude does for MCP
746
+ * entries. Null when a variable is unset and has no default.
747
+ */
748
+ function expandEnvRefs(value, env) {
749
+ return expandRefs(value, env).value;
750
+ }
751
+
752
+ // { value, missing }: missing names the first unset variable with no default.
753
+ function expandRefs(value, env) {
754
+ let missing = null;
755
+ const out = String(value).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_, name, fallback) => {
756
+ const set = env[name];
757
+ if (set !== undefined && (set !== '' || fallback === undefined)) return set;
758
+ if (fallback !== undefined) return fallback;
759
+ if (!missing) missing = name;
760
+ return '';
761
+ });
762
+ return { value: missing ? null : out, missing };
763
+ }
764
+
765
+ function mcpMap(servers) {
766
+ return servers && typeof servers === 'object' && !Array.isArray(servers) ? servers : {};
767
+ }
768
+
769
+ // One Claude MCP entry as a server Codex can start, or null (logged once).
770
+ function stdioServer(name, entry, env, logger) {
771
+ const type = entry && (entry.type || (entry.url ? 'http' : 'stdio'));
772
+ if (!MCP_SERVER_NAME.test(name) || type !== 'stdio' || typeof entry.command !== 'string') {
773
+ logger.warn('Skipping MCP server for Codex: only stdio servers with a plain name can run there', { server: name, type });
774
+ return null;
775
+ }
776
+
777
+ const unset = [];
778
+ const expand = (value) => {
779
+ const { value: out, missing } = expandRefs(value, env);
780
+ if (missing) unset.push(missing);
781
+ return out;
782
+ };
783
+ const server = { name, command: expand(entry.command), args: (Array.isArray(entry.args) ? entry.args : []).map(expand) };
784
+ const serverEnv = stringEnv(entry.env);
785
+ if (serverEnv) {
786
+ for (const key of Object.keys(serverEnv)) serverEnv[key] = expand(serverEnv[key]);
787
+ server.env = serverEnv;
788
+ }
789
+ if (unset.length) {
790
+ logger.warn('Skipping MCP server for Codex: it needs an environment variable that is not set', { server: name, variable: unset[0] });
791
+ return null;
792
+ }
793
+ return server;
794
+ }
795
+
796
+ function stringList(value) {
797
+ return Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
798
+ }
799
+
800
+ /**
801
+ * The stdio MCP servers a Claude chat in `workingDir` gets, besides rad: the
802
+ * user's `mcpServers`, the repo's `.mcp.json`, and this directory's entry under
803
+ * `projects` in the Claude config, in Claude's scope order (the project entry
804
+ * wins, then .mcp.json, then the user's). HTTP, SSE and OAuth servers are
805
+ * skipped with one log line each. A `rad` entry is left to findRadMcp, so a
806
+ * chat always reaches its own FlightDeck the way it does today.
807
+ *
808
+ * Claude's disable state applies too, each skip with one log line: a server
809
+ * named in this directory's `disabledMcpServers` (any scope, what `/mcp`
810
+ * disable writes), and a .mcp.json server named in `disabledMcpjsonServers`
811
+ * there or in a Claude settings file. `enabledMcpjsonServers` is not a gate:
812
+ * .mcp.json stdio servers load without approval.
813
+ *
814
+ * @returns {Array<{name: string, command: string, args: string[], env?: object}>}
815
+ */
816
+ function findMcpServers({ env = process.env, workingDir = process.cwd(), logger = _defaultLogger(), home = os.homedir() } = {}) {
817
+ const config = readJson(claudeConfigFile(env, home)) || {};
818
+ const projects = mcpMap(config.projects);
819
+ let real = workingDir;
820
+ try { real = fs.realpathSync(workingDir); } catch (_) { /* keep as given */ }
821
+ const project = projects[workingDir] || projects[real] || {};
822
+ const repo = (readJson(path.join(workingDir, '.mcp.json')) || {}).mcpServers;
823
+
824
+ const disabled = new Set(stringList(project.disabledMcpServers));
825
+ const settingsFiles = [
826
+ path.join(claudeConfigDir(env, home), 'settings.json'),
827
+ path.join(workingDir, '.claude', 'settings.json'),
828
+ path.join(workingDir, '.claude', 'settings.local.json'),
829
+ ];
830
+ const disabledJson = new Set([
831
+ ...stringList(project.disabledMcpjsonServers),
832
+ ...settingsFiles.flatMap((file) => stringList((readJson(file) || {}).disabledMcpjsonServers)),
833
+ ]);
834
+
835
+ const merged = new Map(); // name -> { scope, entry }; a later scope wins
836
+ for (const [scope, map] of [['user', config.mcpServers], ['project', repo], ['local', project.mcpServers]]) {
837
+ for (const [name, entry] of Object.entries(mcpMap(map))) merged.set(name, { scope, entry });
838
+ }
839
+
840
+ const servers = [];
841
+ for (const [name, { scope, entry }] of merged) {
842
+ if (name === 'rad') continue;
843
+ const reason = disabled.has(name) ? 'disabledMcpServers'
844
+ : scope === 'project' && disabledJson.has(name) ? 'disabledMcpjsonServers' : null;
845
+ if (reason) {
846
+ logger.warn('Skipping MCP server for Codex: it is disabled for this directory in Claude', { server: name, reason });
847
+ continue;
848
+ }
849
+ const server = stdioServer(name, entry, env, logger);
850
+ if (server) servers.push(server);
851
+ }
852
+ return servers;
853
+ }
854
+
855
+ // Keep only string-valued entries of an MCP `env` map; null when none are left.
856
+ function stringEnv(map) {
857
+ if (!map || typeof map !== 'object' || Array.isArray(map)) return null;
858
+ const out = {};
859
+ for (const [key, value] of Object.entries(map)) {
860
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = String(value);
861
+ }
862
+ return Object.keys(out).length ? out : null;
863
+ }
864
+
865
+ /**
866
+ * The Codex home every FlightDeck Codex chat runs in. It is separate from the
867
+ * user's own ~/.codex, so a chat loads none of the user's MCP servers, plugins
868
+ * or trusted-project entries, and gets the same tool set on every pilot. It is
869
+ * a fixed directory (never a per-session temp dir), so Codex thread history
870
+ * survives daemon restarts and `thread/resume` finds the thread.
871
+ *
872
+ * Override with FLIGHTDECK_CODEX_HOME.
873
+ */
874
+ function flightdeckCodexHome(env = process.env, home = os.homedir()) {
875
+ return env.FLIGHTDECK_CODEX_HOME || path.join(home, '.flightdeck', 'codex-home');
876
+ }
877
+
878
+ // Where the user's own Codex keeps its login. FLIGHTDECK_CODEX_HOME applies to
879
+ // the child only; CODEX_HOME in the daemon's env is the user's choice of home.
880
+ function userCodexHome(env = process.env, home = os.homedir()) {
881
+ const configured = env.CODEX_HOME;
882
+ if (configured && path.resolve(configured) !== path.resolve(flightdeckCodexHome(env, home))) return configured;
883
+ return path.join(home, '.codex');
884
+ }
885
+
886
+ /**
887
+ * Create the dedicated Codex home and link two files into it:
888
+ * - auth.json, the user's Codex login. Codex rewrites auth.json in place (open
889
+ * with truncate, no temp file and rename; codex-rs/login/src/auth/storage.rs,
890
+ * rust-v0.162.1), so a refreshed token is written through the symlink to the
891
+ * user's file and the two never drift.
892
+ * - AGENTS.md, the user's Claude global CLAUDE.md, which Codex reads as the
893
+ * global rules for every chat (#491).
894
+ * Nothing in the user's Codex or Claude folders is modified, copied or
895
+ * removed; only the symlinks in the FlightDeck home are created or repaired.
896
+ * A regular file already at either path (a login done in this home, rules
897
+ * written for it) is left alone.
898
+ *
899
+ * @returns {string} the CODEX_HOME to give the child
900
+ */
901
+ function prepareCodexHome(env = process.env, home = os.homedir()) {
902
+ const codexHome = flightdeckCodexHome(env, home);
903
+ fs.mkdirSync(codexHome, { recursive: true, mode: 0o700 });
904
+ linkInto(path.join(userCodexHome(env, home), 'auth.json'), path.join(codexHome, 'auth.json'));
905
+ linkInto(path.join(claudeConfigDir(env, home), 'CLAUDE.md'), path.join(codexHome, 'AGENTS.md'));
906
+ return codexHome;
907
+ }
908
+
909
+ // Point `link` at `source` when the source exists, unless a regular file is there.
910
+ function linkInto(source, link) {
911
+ if (!fs.existsSync(source)) return;
912
+
913
+ let existing = null;
914
+ try { existing = fs.lstatSync(link); } catch (_) { /* absent */ }
915
+ if (existing) {
916
+ if (!existing.isSymbolicLink()) return;
917
+ if (fs.readlinkSync(link) === source) return;
918
+ fs.unlinkSync(link);
919
+ }
920
+ fs.symlinkSync(source, link);
921
+ }
922
+
923
+ /**
924
+ * The git directories a `git add` / `git commit` in `workingDir` writes to:
925
+ * the repo's git dir and its common git dir (they differ in a linked
926
+ * worktree, where the common dir lives in the main checkout). workspace-write
927
+ * only lets a chat write under its cwd and keeps `.git` read-only even there,
928
+ * so without these, `git add` fails with "Unable to create ... index.lock:
929
+ * Operation not permitted". Real paths, because the sandbox compares them.
930
+ * Empty when `workingDir` is not inside a git repo.
931
+ *
932
+ * @param {string} workingDir
933
+ * @param {Function} [exec] execFileSync, injectable for tests
934
+ * @returns {string[]}
935
+ */
936
+ function gitWritableRoots(workingDir, exec = childProcess.execFileSync) {
937
+ try {
938
+ const out = exec('git', ['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir'], {
939
+ cwd: workingDir, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'],
940
+ });
941
+ const roots = [];
942
+ for (const line of String(out).split('\n')) {
943
+ const dir = line.trim();
944
+ if (!dir) continue;
945
+ let real = dir;
946
+ try { real = fs.realpathSync(dir); } catch (_) { /* keep as reported */ }
947
+ if (!roots.includes(real)) roots.push(real);
948
+ }
949
+ return roots;
950
+ } catch (_) {
951
+ return [];
952
+ }
953
+ }
954
+
955
+ /**
956
+ * Arguments and env for `codex app-server`. Per-process `-c` overrides, so no
957
+ * config file is written:
958
+ * - sandbox_workspace_write.network_access: workspace-write blocks the network
959
+ * by default, which breaks git push and installs.
960
+ * - project_doc_fallback_filenames: Codex reads CLAUDE.md in a directory with
961
+ * no AGENTS.md, so a chat gets the repo's Claude rules (#491).
962
+ * - mcp_servers.rad: the command a Claude chat uses, plus env_vars so that
963
+ * CLAUDE_SESSION_ID (and the URL and token, when set) reach the server.
964
+ * - mcp_servers.<name>: every other stdio server a Claude chat gets
965
+ * (findMcpServers), enabled and approved like rad.
966
+ *
967
+ * No MCP env value goes on argv, where `ps` shows it. Each one is set in the
968
+ * child's env and its name listed in that server's env_vars, so Codex hands
969
+ * it to the server. A server's own `args` (as written, or after ${VAR}
970
+ * expansion) do go on argv, as they do on the server's command line in a
971
+ * Claude chat. The rad entry's map wins over the daemon's env, as in Claude.
972
+ * Two servers that need different values under one name cannot share the
973
+ * child's env: the later one is skipped with a log line. So is a server that
974
+ * would change a name Codex itself runs with (isGuardedEnvVar) to a value the
975
+ * daemon's env does not already have; the rad entry drops such a name with a
976
+ * log line instead. Log lines name the variable, never its value.
977
+ *
978
+ * The user's own Codex MCP servers and plugins never load: the child runs in
979
+ * the dedicated CODEX_HOME (prepareCodexHome), which has no config.toml.
980
+ *
981
+ * @returns {{args: string[], env: object}} env is a new object
982
+ */
983
+ function buildCodexLaunch({ env = {}, radMcp, mcpServers = [], writableRoots, logger = _defaultLogger() } = {}) {
984
+ const childEnv = { ...env };
985
+ const args = ['app-server', '-c', 'sandbox_workspace_write.network_access=true'];
986
+ if (Array.isArray(writableRoots) && writableRoots.length) {
987
+ args.push('-c', `sandbox_workspace_write.writable_roots=${JSON.stringify(writableRoots)}`);
988
+ }
989
+ // Even an empty Codex home gets the built-in `codex_apps` MCP server (the
990
+ // ChatGPT account's connectors, 100+ tools) and the curated plugin catalog
991
+ // whenever the login is a ChatGPT login. Turn both features off.
992
+ for (const feature of NO_CHATGPT_EXTRAS) args.push('-c', `features.${feature}=false`);
993
+ args.push('-c', 'project_doc_fallback_filenames=["CLAUDE.md"]');
994
+
995
+ const addServer = (name, server, envVars) => {
996
+ args.push(
997
+ '-c', `mcp_servers.${name}.command=${JSON.stringify(server.command)}`,
998
+ '-c', `mcp_servers.${name}.args=${JSON.stringify(server.args)}`,
999
+ );
1000
+ if (envVars.length) args.push('-c', `mcp_servers.${name}.env_vars=${JSON.stringify(envVars)}`);
1001
+ args.push(
1002
+ '-c', `mcp_servers.${name}.enabled=true`,
1003
+ // approval_policy "never" refuses any MCP tool the server does not mark
1004
+ // read-only. These are the tools a Claude chat in this repo has.
1005
+ '-c', `mcp_servers.${name}.default_tools_approval_mode="approve"`,
1006
+ );
1007
+ };
1008
+
1009
+ const claimed = new Map(); // env name -> the value an MCP server needs
1010
+ const rad = radMcp === undefined ? findRadMcp(env) : radMcp;
1011
+ if (rad) {
1012
+ const applied = [];
1013
+ for (const [key, value] of Object.entries(stringEnv(rad.env) || {})) {
1014
+ if (isGuardedEnvVar(key) && childEnv[key] !== value) {
1015
+ logger.warn('Ignoring a variable in the rad MCP entry env: Codex itself runs with it', { server: 'rad', variable: key });
1016
+ continue;
1017
+ }
1018
+ childEnv[key] = value;
1019
+ applied.push(key);
1020
+ }
1021
+ const envVars = [...new Set([...RAD_ENV_VARS, ...applied])];
1022
+ for (const key of envVars) claimed.set(key, childEnv[key]);
1023
+ addServer('rad', { command: rad.command, args: rad.args }, envVars);
1024
+ }
1025
+
1026
+ for (const server of mcpServers) {
1027
+ const serverEnv = stringEnv(server.env) || {};
1028
+ const guarded = Object.entries(serverEnv).find(([key, value]) => isGuardedEnvVar(key) && childEnv[key] !== value);
1029
+ if (guarded) {
1030
+ logger.warn('Skipping MCP server for Codex: its env would change a variable Codex itself runs with', {
1031
+ server: server.name, variable: guarded[0],
1032
+ });
1033
+ continue;
1034
+ }
1035
+ const clash = Object.entries(serverEnv).find(([key, value]) => claimed.has(key) && claimed.get(key) !== value);
1036
+ if (clash) {
1037
+ logger.warn('Skipping MCP server for Codex: another server needs a different value for one of its env variables', {
1038
+ server: server.name, variable: clash[0],
1039
+ });
1040
+ continue;
1041
+ }
1042
+ for (const [key, value] of Object.entries(serverEnv)) {
1043
+ childEnv[key] = value;
1044
+ claimed.set(key, value);
1045
+ }
1046
+ addServer(server.name, server, Object.keys(serverEnv));
1047
+ }
1048
+
1049
+ return { args, env: childEnv };
1050
+ }
1051
+
1052
+ // The `codex app-server` arguments alone (see buildCodexLaunch).
1053
+ function buildCodexArgs(options = {}) {
1054
+ return buildCodexLaunch(options).args;
1055
+ }
1056
+
1057
+ function _defaultLogger() {
1058
+ return {
1059
+ debug: () => {},
1060
+ info: () => {},
1061
+ warn: () => {},
1062
+ error: () => {},
1063
+ child: () => _defaultLogger(),
1064
+ };
1065
+ }
1066
+
1067
+ module.exports = CodexProcess;
1068
+ module.exports.buildCodexEnv = buildCodexEnv;
1069
+ module.exports.buildCodexArgs = buildCodexArgs;
1070
+ module.exports.gitWritableRoots = gitWritableRoots;
1071
+ module.exports.findRadMcp = findRadMcp;
1072
+ module.exports.prepareCodexHome = prepareCodexHome;
1073
+ module.exports.flightdeckCodexHome = flightdeckCodexHome;
1074
+ module.exports.codexAuthMode = codexAuthMode;
1075
+ module.exports.RAD_ENV_VARS = RAD_ENV_VARS;
1076
+ module.exports.buildCodexLaunch = buildCodexLaunch;
1077
+ module.exports.findMcpServers = findMcpServers;
1078
+ module.exports.claudeSkillRoots = claudeSkillRoots;
1079
+ module.exports.memoryIndexPath = memoryIndexPath;
1080
+ module.exports.developerInstructions = developerInstructions;
1081
+ module.exports.expandEnvRefs = expandEnvRefs;