@radnine/claude-session-daemon 0.8.3 → 0.9.2

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,772 @@
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
+ /**
26
+ * Wraps one `codex app-server` child (JSON-RPC over stdio) for one FlightDeck
27
+ * chat, and keeps one Codex thread alive across turns. It follows the harness
28
+ * contract in harness.js and writes the same stream-json events as
29
+ * ClaudeProcess, so Rails and the terminal render a Codex chat unchanged.
30
+ *
31
+ * The Codex thread id is the chat's resume handle. It is exposed as
32
+ * `claudeSessionId` (the daemon's name for the vendor session id), which the
33
+ * daemon reports in `session_activated` and Rails stores; after a daemon
34
+ * restart Rails passes it back and the process resumes the thread.
35
+ */
36
+ class CodexProcess extends EventEmitter {
37
+ /**
38
+ * @param {string} sessionId - FlightDeck session id
39
+ * @param {object} [options]
40
+ * @param {string} [options.workingDir]
41
+ * @param {string} [options.claudeSessionId] - Codex thread id to resume (with options.resume)
42
+ * @param {boolean} [options.resume]
43
+ * @param {object} [options.logger]
44
+ * @param {string} [options.codexCommand] - path to the codex binary
45
+ * @param {string} [options.systemPrompt] - persona prompt, sent as developer instructions
46
+ * @param {string} [options.model] - Codex model id
47
+ * @param {string} [options.effort] - reasoning effort for each turn
48
+ * @param {object} [options.sessionEnv] - extra env for the child
49
+ * @param {{command: string, args: string[], env?: object}} [options.radMcp] - how to start the rad MCP server
50
+ * @param {Function} [options._spawnFn] - tests: replacement for child_process.spawn
51
+ */
52
+ constructor(sessionId, options = {}) {
53
+ super();
54
+
55
+ this._sessionId = sessionId;
56
+ this._resumeThreadId = options.resume ? options.claudeSessionId || null : null;
57
+ this._threadId = null;
58
+ this._workingDir = options.workingDir || process.cwd();
59
+ this._logger = options.logger || _defaultLogger();
60
+ this._codexCommand = options.codexCommand || 'codex';
61
+ this._spawnFn = options._spawnFn || defaultSpawn;
62
+ this._sessionEnv = options.sessionEnv || {};
63
+ this._systemPrompt = options.systemPrompt || null;
64
+ this._model = options.model || null;
65
+ this._effort = options.effort || null;
66
+ this._radMcp = options.radMcp;
67
+
68
+ this._state = 'idle';
69
+ this._child = null;
70
+ this._pid = null;
71
+ this._startedAt = null;
72
+
73
+ this._nextRequestId = 0;
74
+ this._pending = new Map(); // request id -> { resolve, reject, timer, method }
75
+ this._ready = null;
76
+ this._translator = null;
77
+ this._inbox = []; // messages waiting for the next turn
78
+ this._busy = false; // a turn is starting or running
79
+ this._activeTurnId = null;
80
+ this._interruptPending = false;
81
+ this._turnSeq = 0;
82
+ this._turnToken = 0;
83
+
84
+ this._turns = new TurnTracker();
85
+ }
86
+
87
+ // -------------------------------------------------------------------------
88
+ // Public API (the harness contract)
89
+ // -------------------------------------------------------------------------
90
+
91
+ spawn() {
92
+ if (this._state !== 'idle') {
93
+ throw new Error(`Cannot spawn: process is not idle (state=${this._state})`);
94
+ }
95
+
96
+ this._state = 'spawning';
97
+
98
+ const env = buildCodexEnv(process.env, this._sessionEnv, this._sessionId);
99
+ env.CODEX_HOME = prepareCodexHome(env);
100
+ const args = buildCodexArgs({ env, radMcp: this._radMcp, writableRoots: gitWritableRoots(this._workingDir) });
101
+
102
+ this._logger.info(`Spawning Codex app-server: ${this._codexCommand}`, {
103
+ sessionId: this._sessionId,
104
+ threadId: this._resumeThreadId,
105
+ cwd: this._workingDir,
106
+ model: this._model,
107
+ authMode: codexAuthMode(env),
108
+ codexHome: env.CODEX_HOME,
109
+ });
110
+
111
+ this._child = this._spawnFn(this._codexCommand, args, {
112
+ cwd: this._workingDir,
113
+ stdio: ['pipe', 'pipe', 'pipe'],
114
+ env,
115
+ });
116
+
117
+ if (this._child.stdin && typeof this._child.stdin.on === 'function') {
118
+ this._child.stdin.on('error', (err) => {
119
+ this._logger.warn('Codex stdin error', { pid: this._pid, error: err.message });
120
+ });
121
+ }
122
+
123
+ this._pid = this._child.pid;
124
+ this._startedAt = Date.now();
125
+ this._state = 'running';
126
+
127
+ this._setupStdout();
128
+ this._setupStderr();
129
+ this._setupError();
130
+ this._setupClose();
131
+
132
+ this._ready = this._handshake();
133
+ this._ready.catch((err) => {
134
+ this._logger.error('Codex handshake failed', { sessionId: this._sessionId, error: err.message });
135
+ });
136
+
137
+ this.emit('spawned');
138
+ }
139
+
140
+ /**
141
+ * Resolves once the thread exists (or is resumed) and claudeSessionId is
142
+ * known. The daemon awaits it right after spawn().
143
+ * @returns {Promise<void>}
144
+ */
145
+ ready() {
146
+ return this._ready || Promise.reject(new Error('Codex process was not spawned'));
147
+ }
148
+
149
+ sendMessage(text, commandId = null) {
150
+ if (this._state !== 'running' || !this._child) {
151
+ this._logger.warn('Cannot send message: process not running');
152
+ return false;
153
+ }
154
+
155
+ this._turns.written(commandId, text);
156
+ this._inbox.push(text);
157
+ this._logger.debug('Queued message for Codex', { length: text.length, commandId });
158
+ this._pump();
159
+ return true;
160
+ }
161
+
162
+ sendSlashCommand(command, commandId = null) {
163
+ return this.sendMessage(command, commandId);
164
+ }
165
+
166
+ /**
167
+ * Stop the running turn with turn/interrupt. The process and the thread stay,
168
+ * and the next message starts a new turn.
169
+ * @returns {boolean} true if there was nothing to stop or the request went out
170
+ */
171
+ interrupt() {
172
+ if (this._state !== 'running' || !this._child) {
173
+ this._logger.warn('Cannot interrupt: process not running');
174
+ return false;
175
+ }
176
+ if (!this._busy) return true;
177
+
178
+ if (!this._activeTurnId) {
179
+ // turn/start has not answered yet; interrupt as soon as it does.
180
+ this._interruptPending = true;
181
+ return true;
182
+ }
183
+
184
+ this._logger.info('Interrupting Codex turn', { pid: this._pid, turnId: this._activeTurnId });
185
+ this._request('turn/interrupt', { threadId: this._threadId, turnId: this._activeTurnId }).catch((err) => {
186
+ this._logger.error('turn/interrupt failed', { error: err.message });
187
+ });
188
+ return true;
189
+ }
190
+
191
+ async kill(timeoutMs = 5000) {
192
+ if (this._state !== 'running' && this._state !== 'spawning') {
193
+ return;
194
+ }
195
+
196
+ this._state = 'stopping';
197
+ this._logger.info('Stopping Codex process', { pid: this._pid });
198
+
199
+ try {
200
+ this._child.stdin.end();
201
+ } catch (_) { /* ignore */ }
202
+
203
+ try {
204
+ this._child.kill('SIGTERM');
205
+ } catch (_) { /* ignore if already dead */ }
206
+
207
+ const exited = await this._waitForExit(timeoutMs);
208
+
209
+ if (!exited) {
210
+ this._logger.warn('Process did not exit after SIGTERM, sending SIGKILL', { pid: this._pid });
211
+ try {
212
+ this._child.kill('SIGKILL');
213
+ } catch (_) { /* ignore */ }
214
+ await this._waitForExit(2000);
215
+ }
216
+
217
+ this._state = 'stopped';
218
+ }
219
+
220
+ isAlive() {
221
+ if (!this._child || !this._pid) return false;
222
+ if (this._state === 'stopped') return false;
223
+
224
+ try {
225
+ return this._child.kill(0) !== false;
226
+ } catch (_) {
227
+ return false;
228
+ }
229
+ }
230
+
231
+ // -------------------------------------------------------------------------
232
+ // Getters
233
+ // -------------------------------------------------------------------------
234
+
235
+ get pid() { return this._pid; }
236
+ get state() { return this._state; }
237
+ get sessionId() { return this._sessionId; }
238
+ /** The Codex thread id: what Rails stores and passes back to resume. */
239
+ get claudeSessionId() { return this._threadId || this._resumeThreadId; }
240
+ get startedAt() { return this._startedAt; }
241
+ get workingDir() { return this._workingDir; }
242
+ get currentCommandId() { return this._turns.currentCommandId; }
243
+ unfinishedCommandIds() { return this._turns.unfinishedCommandIds(); }
244
+ readCommandIds() { return this._turns.readCommandIds(); }
245
+
246
+ // -------------------------------------------------------------------------
247
+ // Handshake and turns
248
+ // -------------------------------------------------------------------------
249
+
250
+ async _handshake() {
251
+ await this._request('initialize', {
252
+ clientInfo: { name: 'flightdeck-daemon', title: 'FlightDeck', version: '1' },
253
+ capabilities: null,
254
+ });
255
+ this._notify('initialized');
256
+
257
+ // workspace-write with network (set in buildCodexArgs): git commit works in
258
+ // a worktree, and git push / package installs reach the network.
259
+ const params = {
260
+ cwd: this._workingDir,
261
+ approvalPolicy: 'never',
262
+ sandbox: 'workspace-write',
263
+ };
264
+ if (this._model) params.model = this._model;
265
+ if (this._systemPrompt) params.developerInstructions = this._systemPrompt;
266
+
267
+ let response;
268
+ if (this._resumeThreadId) {
269
+ response = await this._request('thread/resume', { threadId: this._resumeThreadId, ...params });
270
+ } else {
271
+ response = await this._request('thread/start', params);
272
+ }
273
+
274
+ this._threadId = response.thread.id;
275
+ this._translator = new CodexTranslator({
276
+ threadId: this._threadId,
277
+ model: response.model || this._model,
278
+ cwd: this._workingDir,
279
+ });
280
+ this._logger.info('Codex thread ready', {
281
+ sessionId: this._sessionId, threadId: this._threadId, resumed: !!this._resumeThreadId,
282
+ });
283
+
284
+ this._pump();
285
+ }
286
+
287
+ // Start the next queued message as a turn, when none is running.
288
+ _pump() {
289
+ if (!this._translator || this._busy || this._state !== 'running') return;
290
+ const text = this._inbox.shift();
291
+ if (text === undefined) return;
292
+
293
+ this._busy = true;
294
+ this._activeTurnId = null;
295
+ this._translator.messageSent(text);
296
+
297
+ const params = {
298
+ threadId: this._threadId,
299
+ input: [{ type: 'text', text, text_elements: [] }],
300
+ };
301
+ if (this._effort) params.effort = this._effort;
302
+
303
+ // A turn/start answer belongs to the turn that sent it. If that turn already
304
+ // finished and the next one started, the answer is stale and must not
305
+ // become the next turn's active id.
306
+ const token = ++this._turnSeq;
307
+ this._turnToken = token;
308
+
309
+ this._request('turn/start', params).then((response) => {
310
+ if (token !== this._turnToken) return;
311
+ const turnId = response && response.turn && response.turn.id;
312
+ if (this._busy && !this._activeTurnId) this._activeTurnId = turnId || null;
313
+ if (this._interruptPending) {
314
+ this._interruptPending = false;
315
+ this.interrupt();
316
+ }
317
+ }).catch((err) => {
318
+ if (token !== this._turnToken) return;
319
+ this._logger.error('turn/start failed', { error: err.message });
320
+ this._failTurn(err.message);
321
+ });
322
+ }
323
+
324
+ // A turn that never started: show the error and end it like any other turn,
325
+ // so the chat does not wait on it forever.
326
+ _failTurn(message) {
327
+ this._interruptPending = false;
328
+ const events = [
329
+ ...this._translator.translate('turn/started', { turn: { id: null } }),
330
+ ...this._translator.translate('error', { error: { message: `Codex could not start the turn: ${message}` }, willRetry: false }),
331
+ ...this._translator.translate('turn/completed', { turn: { id: null, status: 'failed' } }),
332
+ ];
333
+ this._emitEvents(events);
334
+ this._busy = false;
335
+ this._activeTurnId = null;
336
+ this._pump();
337
+ }
338
+
339
+ _onNotification(method, params) {
340
+ if (!this._translator) return;
341
+ if (params && params.threadId && params.threadId !== this._threadId) return;
342
+
343
+ if (method === 'turn/started' && params.turn) this._activeTurnId = params.turn.id;
344
+
345
+ // A malformed notification must not take the daemon down: show the error
346
+ // in the chat and keep the process running.
347
+ let events;
348
+ try {
349
+ events = this._translator.translate(method, params);
350
+ } catch (err) {
351
+ this._logger.error('Codex notification could not be translated', { method, error: err.message });
352
+ events = [];
353
+ try {
354
+ events = [this._translator._assistant(
355
+ [{ type: 'text', text: `FlightDeck could not read a Codex ${method} message: ${err.message}` }],
356
+ `codex-error-${Date.now()}`,
357
+ )];
358
+ } catch (_) { /* nothing more to show */ }
359
+ // Rails ends a turn only on a result event, so a turn whose completion
360
+ // could not be read still needs one or the chat input stays disabled.
361
+ if (method === 'turn/completed') {
362
+ events.push({
363
+ type: 'result',
364
+ subtype: 'error_during_execution',
365
+ is_error: true,
366
+ duration_ms: 0,
367
+ duration_api_ms: 0,
368
+ num_turns: 1,
369
+ result: `FlightDeck could not read a Codex ${method} message: ${err.message}`,
370
+ total_cost_usd: 0,
371
+ session_id: this._threadId,
372
+ });
373
+ }
374
+ }
375
+ this._emitEvents(events);
376
+
377
+ if (method === 'turn/completed') {
378
+ // An interrupt still waiting for the turn/start answer belonged to this
379
+ // turn, which is over. Keeping it would interrupt the next turn.
380
+ this._interruptPending = false;
381
+ this._busy = false;
382
+ this._activeTurnId = null;
383
+ this._pump();
384
+ }
385
+ }
386
+
387
+ _emitEvents(events) {
388
+ for (const event of events) {
389
+ this.emit('output', event, this._turns.observe(event));
390
+ }
391
+ }
392
+
393
+ // Codex asks before things the approval policy allows it to ask about. With
394
+ // "never" it should not; if it does, refuse rather than hang the turn.
395
+ _onServerRequest(message) {
396
+ const { id, method } = message;
397
+ this._logger.warn('Codex server request', { method });
398
+ if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval') {
399
+ this._respond(id, { decision: 'decline' });
400
+ return;
401
+ }
402
+ this._respondError(id, -32601, `FlightDeck does not handle ${method}`);
403
+ }
404
+
405
+ // -------------------------------------------------------------------------
406
+ // JSON-RPC plumbing
407
+ // -------------------------------------------------------------------------
408
+
409
+ _write(obj) {
410
+ const payload = JSON.stringify(obj) + '\n';
411
+ try {
412
+ this._child.stdin.write(payload);
413
+ return true;
414
+ } catch (err) {
415
+ this._logger.warn('Failed to write to Codex stdin', { error: err.message });
416
+ return false;
417
+ }
418
+ }
419
+
420
+ _request(method, params) {
421
+ return new Promise((resolve, reject) => {
422
+ if (this._state !== 'running' || !this._child) {
423
+ reject(new Error(`Codex process is not running (${method})`));
424
+ return;
425
+ }
426
+ const id = ++this._nextRequestId;
427
+ const timer = setTimeout(() => {
428
+ this._pending.delete(id);
429
+ reject(new Error(`Codex did not answer ${method} within ${REQUEST_TIMEOUT_MS / 1000}s`));
430
+ }, REQUEST_TIMEOUT_MS);
431
+ if (timer.unref) timer.unref();
432
+ this._pending.set(id, { resolve, reject, timer, method });
433
+ if (!this._write({ id, method, params })) {
434
+ clearTimeout(timer);
435
+ this._pending.delete(id);
436
+ reject(new Error(`Could not write ${method} to Codex`));
437
+ }
438
+ });
439
+ }
440
+
441
+ _notify(method, params) {
442
+ this._write(params === undefined ? { method } : { method, params });
443
+ }
444
+
445
+ _respond(id, result) {
446
+ this._write({ id, result });
447
+ }
448
+
449
+ _respondError(id, code, message) {
450
+ this._write({ id, error: { code, message } });
451
+ }
452
+
453
+ _setupStdout() {
454
+ const rl = createInterface({ input: this._child.stdout });
455
+
456
+ rl.on('line', (line) => {
457
+ if (!line) return;
458
+
459
+ let message;
460
+ try {
461
+ message = JSON.parse(line);
462
+ } catch (_) {
463
+ this._logger.warn('Unparseable Codex stdout line', { line: line.slice(0, 200) });
464
+ this.emit('error', line);
465
+ return;
466
+ }
467
+
468
+ if (message.method && message.id !== undefined) {
469
+ this._onServerRequest(message);
470
+ } else if (message.method) {
471
+ this._onNotification(message.method, message.params || {});
472
+ } else if (message.id !== undefined) {
473
+ this._onResponse(message);
474
+ }
475
+ });
476
+ }
477
+
478
+ _onResponse(message) {
479
+ const pending = this._pending.get(message.id);
480
+ if (!pending) return;
481
+ this._pending.delete(message.id);
482
+ clearTimeout(pending.timer);
483
+
484
+ if (message.error) {
485
+ pending.reject(new Error(message.error.message || `Codex error on ${pending.method}`));
486
+ } else {
487
+ pending.resolve(message.result);
488
+ }
489
+ }
490
+
491
+ _setupStderr() {
492
+ const rl = createInterface({ input: this._child.stderr });
493
+
494
+ rl.on('line', (line) => {
495
+ if (!line) return;
496
+ this._logger.warn('Codex stderr', { line });
497
+ this.emit('stderr', line);
498
+ });
499
+ }
500
+
501
+ // The child could not be spawned (codex not installed, wrong command). Node
502
+ // throws an uncaught exception for an unhandled 'error' event, which would
503
+ // take the whole daemon down with every other chat on it.
504
+ _setupError() {
505
+ this._child.on('error', (err) => {
506
+ const message = err && err.code === 'ENOENT'
507
+ ? `Codex CLI not found: ${this._codexCommand}`
508
+ : `Codex process error: ${err && err.message}`;
509
+ this._logger.error(message, { sessionId: this._sessionId, error: err && err.message });
510
+ this._state = 'stopped';
511
+ const failure = new Error(message);
512
+ for (const [id, pending] of this._pending) {
513
+ clearTimeout(pending.timer);
514
+ pending.reject(failure);
515
+ this._pending.delete(id);
516
+ }
517
+ if (this.listenerCount('error') > 0) this.emit('error', message);
518
+ });
519
+ }
520
+
521
+ _setupClose() {
522
+ this._child.on('close', (code, signal) => {
523
+ this._logger.info('Codex process exited', { code, signal, pid: this._pid });
524
+ this._state = 'stopped';
525
+ for (const [id, pending] of this._pending) {
526
+ clearTimeout(pending.timer);
527
+ pending.reject(new Error(`Codex exited before answering ${pending.method}`));
528
+ this._pending.delete(id);
529
+ }
530
+ this.emit('exit', code, signal, {
531
+ commandId: this._turns.newestWrittenCommandId,
532
+ unfinishedCommandIds: this._turns.unfinishedCommandIds(),
533
+ readCommandIds: this._turns.readCommandIds(),
534
+ });
535
+ });
536
+ }
537
+
538
+ _waitForExit(timeoutMs) {
539
+ return new Promise((resolve) => {
540
+ if (this._state === 'stopped') {
541
+ resolve(true);
542
+ return;
543
+ }
544
+
545
+ let timer;
546
+ const onClose = () => {
547
+ clearTimeout(timer);
548
+ resolve(true);
549
+ };
550
+
551
+ timer = setTimeout(() => {
552
+ this._child.removeListener('close', onClose);
553
+ resolve(false);
554
+ }, timeoutMs);
555
+
556
+ this._child.once('close', onClose);
557
+ });
558
+ }
559
+ }
560
+
561
+ // ---------------------------------------------------------------------------
562
+ // Spawn environment and arguments
563
+ // ---------------------------------------------------------------------------
564
+
565
+ /**
566
+ * `chatgpt` (default): the chat runs on the ChatGPT login in ~/.codex/auth.json,
567
+ * so OPENAI_API_KEY and CODEX_API_KEY are removed from the child's env; a key
568
+ * in the daemon's env would otherwise bill the API instead of the plan.
569
+ * `api_key`: the pilot opted in with CODEX_AUTH_MODE=api_key and keeps its key.
570
+ */
571
+ function codexAuthMode(env) {
572
+ return String(env.CODEX_AUTH_MODE || 'chatgpt').toLowerCase() === 'api_key' ? 'api_key' : 'chatgpt';
573
+ }
574
+
575
+ function buildCodexEnv(baseEnv, sessionEnv, sessionId) {
576
+ const env = { ...baseEnv, ...sessionEnv, CLAUDE_SESSION_ID: sessionId };
577
+ delete env.CLAUDECODE; // same nested-session guard as the Claude harness
578
+ stripDaemonSecrets(env);
579
+
580
+ if (codexAuthMode(env) !== 'api_key') {
581
+ delete env.OPENAI_API_KEY;
582
+ delete env.CODEX_API_KEY;
583
+ }
584
+ return env;
585
+ }
586
+
587
+ /**
588
+ * How Claude chats reach the rad MCP server on a pilot: the user-scope `rad`
589
+ * entry the FlightDeck installer wrote to Claude's config, which runs
590
+ * ~/.flightdeck/rad-mcp (the launcher reads RAD_URL and RAD_TOKEN from
591
+ * ~/.flightdeck/rad-mcp.env). Codex gets the same command.
592
+ *
593
+ * The entry's `env` map is returned too, so a pilot (or a test stack) that
594
+ * points rad at another Rails through that map gets the same behaviour on Codex.
595
+ *
596
+ * @returns {{command: string, args: string[], env?: object}|null}
597
+ */
598
+ function findRadMcp(env = process.env, home = os.homedir()) {
599
+ const configDir = env.CLAUDE_CONFIG_DIR;
600
+ const claudeConfig = configDir ? path.join(configDir, '.claude.json') : path.join(home, '.claude.json');
601
+ try {
602
+ const rad = JSON.parse(fs.readFileSync(claudeConfig, 'utf8')).mcpServers?.rad;
603
+ if (rad && typeof rad.command === 'string' && Array.isArray(rad.args)) {
604
+ const found = { command: rad.command, args: rad.args.map(String) };
605
+ const radEnv = stringEnv(rad.env);
606
+ if (radEnv) found.env = radEnv;
607
+ return found;
608
+ }
609
+ } catch (_) { /* no Claude config, or not JSON */ }
610
+
611
+ const launcher = path.join(home, '.flightdeck', 'rad-mcp');
612
+ if (fs.existsSync(launcher)) return { command: 'ruby', args: [launcher] };
613
+ return null;
614
+ }
615
+
616
+ // Keep only string-valued entries of an MCP `env` map; null when none are left.
617
+ function stringEnv(map) {
618
+ if (!map || typeof map !== 'object' || Array.isArray(map)) return null;
619
+ const out = {};
620
+ for (const [key, value] of Object.entries(map)) {
621
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = String(value);
622
+ }
623
+ return Object.keys(out).length ? out : null;
624
+ }
625
+
626
+ /**
627
+ * The Codex home every FlightDeck Codex chat runs in. It is separate from the
628
+ * user's own ~/.codex, so a chat loads none of the user's MCP servers, plugins
629
+ * or trusted-project entries, and gets the same tool set on every pilot. It is
630
+ * a fixed directory (never a per-session temp dir), so Codex thread history
631
+ * survives daemon restarts and `thread/resume` finds the thread.
632
+ *
633
+ * Override with FLIGHTDECK_CODEX_HOME.
634
+ */
635
+ function flightdeckCodexHome(env = process.env, home = os.homedir()) {
636
+ return env.FLIGHTDECK_CODEX_HOME || path.join(home, '.flightdeck', 'codex-home');
637
+ }
638
+
639
+ // Where the user's own Codex keeps its login. FLIGHTDECK_CODEX_HOME applies to
640
+ // the child only; CODEX_HOME in the daemon's env is the user's choice of home.
641
+ function userCodexHome(env = process.env, home = os.homedir()) {
642
+ const configured = env.CODEX_HOME;
643
+ if (configured && path.resolve(configured) !== path.resolve(flightdeckCodexHome(env, home))) return configured;
644
+ return path.join(home, '.codex');
645
+ }
646
+
647
+ /**
648
+ * Create the dedicated Codex home and link the user's login into it.
649
+ * Codex rewrites auth.json in place (open with truncate, no temp file and
650
+ * rename; codex-rs/login/src/auth/storage.rs, rust-v0.162.1), so a refreshed
651
+ * token is written through the symlink to the user's file and the two never
652
+ * drift. Nothing in the user's Codex home is modified, copied or removed; only
653
+ * the symlink in the FlightDeck home is created or repaired. A regular file
654
+ * already at that path (a login done in this home) is left alone.
655
+ *
656
+ * @returns {string} the CODEX_HOME to give the child
657
+ */
658
+ function prepareCodexHome(env = process.env, home = os.homedir()) {
659
+ const codexHome = flightdeckCodexHome(env, home);
660
+ fs.mkdirSync(codexHome, { recursive: true, mode: 0o700 });
661
+
662
+ const source = path.join(userCodexHome(env, home), 'auth.json');
663
+ const link = path.join(codexHome, 'auth.json');
664
+ if (!fs.existsSync(source)) return codexHome;
665
+
666
+ let existing = null;
667
+ try { existing = fs.lstatSync(link); } catch (_) { /* absent */ }
668
+ if (existing) {
669
+ if (!existing.isSymbolicLink()) return codexHome;
670
+ if (fs.readlinkSync(link) === source) return codexHome;
671
+ fs.unlinkSync(link);
672
+ }
673
+ fs.symlinkSync(source, link);
674
+ return codexHome;
675
+ }
676
+
677
+ /**
678
+ * The git directories a `git add` / `git commit` in `workingDir` writes to:
679
+ * the repo's git dir and its common git dir (they differ in a linked
680
+ * worktree, where the common dir lives in the main checkout). workspace-write
681
+ * only lets a chat write under its cwd and keeps `.git` read-only even there,
682
+ * so without these, `git add` fails with "Unable to create ... index.lock:
683
+ * Operation not permitted". Real paths, because the sandbox compares them.
684
+ * Empty when `workingDir` is not inside a git repo.
685
+ *
686
+ * @param {string} workingDir
687
+ * @param {Function} [exec] execFileSync, injectable for tests
688
+ * @returns {string[]}
689
+ */
690
+ function gitWritableRoots(workingDir, exec = childProcess.execFileSync) {
691
+ try {
692
+ const out = exec('git', ['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir'], {
693
+ cwd: workingDir, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'],
694
+ });
695
+ const roots = [];
696
+ for (const line of String(out).split('\n')) {
697
+ const dir = line.trim();
698
+ if (!dir) continue;
699
+ let real = dir;
700
+ try { real = fs.realpathSync(dir); } catch (_) { /* keep as reported */ }
701
+ if (!roots.includes(real)) roots.push(real);
702
+ }
703
+ return roots;
704
+ } catch (_) {
705
+ return [];
706
+ }
707
+ }
708
+
709
+ /**
710
+ * Arguments for `codex app-server`. Per-process `-c` overrides, so no config
711
+ * file is written:
712
+ * - sandbox_workspace_write.network_access: workspace-write blocks the network
713
+ * by default, which breaks git push and installs.
714
+ * - mcp_servers.rad: the command a Claude chat uses, plus env_vars so that
715
+ * CLAUDE_SESSION_ID (and the URL and token, when set) reach the server, plus
716
+ * the rad entry's own env map (it wins over the daemon's env, as in Claude).
717
+ *
718
+ * The user's MCP servers and plugins are not an argument concern: the child
719
+ * runs in the dedicated CODEX_HOME (prepareCodexHome), whose config.toml is
720
+ * empty, so only the `rad` server above exists.
721
+ */
722
+ function buildCodexArgs({ env, radMcp, writableRoots } = {}) {
723
+ const args = ['app-server', '-c', 'sandbox_workspace_write.network_access=true'];
724
+ if (Array.isArray(writableRoots) && writableRoots.length) {
725
+ args.push('-c', `sandbox_workspace_write.writable_roots=${JSON.stringify(writableRoots)}`);
726
+ }
727
+ // Even an empty Codex home gets the built-in `codex_apps` MCP server (the
728
+ // ChatGPT account's connectors, 100+ tools) and the curated plugin catalog
729
+ // whenever the login is a ChatGPT login. Turn both features off.
730
+ for (const feature of NO_CHATGPT_EXTRAS) args.push('-c', `features.${feature}=false`);
731
+
732
+ const rad = radMcp === undefined ? findRadMcp(env) : radMcp;
733
+ if (rad) {
734
+ args.push(
735
+ '-c', `mcp_servers.rad.command=${JSON.stringify(rad.command)}`,
736
+ '-c', `mcp_servers.rad.args=${JSON.stringify(rad.args)}`,
737
+ '-c', `mcp_servers.rad.env_vars=${JSON.stringify(RAD_ENV_VARS)}`,
738
+ '-c', 'mcp_servers.rad.enabled=true',
739
+ // approval_policy "never" refuses any MCP tool the server does not mark
740
+ // read-only. rad's tools are the chat's own FlightDeck calls.
741
+ '-c', 'mcp_servers.rad.default_tools_approval_mode="approve"',
742
+ );
743
+ const radEnv = stringEnv(rad.env);
744
+ if (radEnv) {
745
+ // CLAUDE_SESSION_ID is the chat's own id; an entry cannot override it.
746
+ delete radEnv.CLAUDE_SESSION_ID;
747
+ const pairs = Object.entries(radEnv).map(([k, v]) => `${JSON.stringify(k)} = ${JSON.stringify(v)}`);
748
+ if (pairs.length) args.push('-c', `mcp_servers.rad.env={ ${pairs.join(', ')} }`);
749
+ }
750
+ }
751
+ return args;
752
+ }
753
+
754
+ function _defaultLogger() {
755
+ return {
756
+ debug: () => {},
757
+ info: () => {},
758
+ warn: () => {},
759
+ error: () => {},
760
+ child: () => _defaultLogger(),
761
+ };
762
+ }
763
+
764
+ module.exports = CodexProcess;
765
+ module.exports.buildCodexEnv = buildCodexEnv;
766
+ module.exports.buildCodexArgs = buildCodexArgs;
767
+ module.exports.gitWritableRoots = gitWritableRoots;
768
+ module.exports.findRadMcp = findRadMcp;
769
+ module.exports.prepareCodexHome = prepareCodexHome;
770
+ module.exports.flightdeckCodexHome = flightdeckCodexHome;
771
+ module.exports.codexAuthMode = codexAuthMode;
772
+ module.exports.RAD_ENV_VARS = RAD_ENV_VARS;