ccdeck 3.53.3 → 3.80.0

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.
Files changed (58) hide show
  1. package/README.md +55 -3
  2. package/THIRD_PARTY_NOTICES.md +31 -1
  3. package/dist/web/assets/{BrowserWatchModal-CJ0CW4Go.js → BrowserWatchModal-Bfvo_8H6.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-DlJzBN8b.js → IntegrationModal-GS5jIQ_J.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-CHl3s3OH.js → RadioPanel-Bxd2ElWb.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-Cw3i0Hux.js → TrafficRadar-FgHBI2Oh.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-CiB5-CTH.js → UsageHistoryModal-APwKtE2J.js} +1 -1
  8. package/dist/web/assets/{app-2vj7uk2U.js → app-BzHVsgB2.js} +69 -69
  9. package/dist/web/assets/{index-D1YZbdq3.js → index-7whwMaPX.js} +1 -1
  10. package/dist/web/index.html +2 -2
  11. package/node_modules/ws/LICENSE +20 -0
  12. package/node_modules/ws/README.md +540 -0
  13. package/node_modules/ws/browser.js +8 -0
  14. package/node_modules/ws/index.js +22 -0
  15. package/node_modules/ws/lib/buffer-util.js +142 -0
  16. package/node_modules/ws/lib/constants.js +19 -0
  17. package/node_modules/ws/lib/event-target.js +292 -0
  18. package/node_modules/ws/lib/extension.js +203 -0
  19. package/node_modules/ws/lib/limiter.js +55 -0
  20. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  21. package/node_modules/ws/lib/receiver.js +743 -0
  22. package/node_modules/ws/lib/sender.js +610 -0
  23. package/node_modules/ws/lib/stream.js +161 -0
  24. package/node_modules/ws/lib/subprotocol.js +62 -0
  25. package/node_modules/ws/lib/validation.js +152 -0
  26. package/node_modules/ws/lib/websocket-server.js +562 -0
  27. package/node_modules/ws/lib/websocket.js +1426 -0
  28. package/node_modules/ws/package.json +74 -0
  29. package/node_modules/ws/wrapper.mjs +21 -0
  30. package/package.json +5 -3
  31. package/release-notes.json +37 -0
  32. package/src/server/account-engine.mjs +87 -0
  33. package/src/server/account-routes.mjs +31 -3
  34. package/src/server/codex-auto.mjs +7 -18
  35. package/src/server/codex-engine-adapter.mjs +272 -0
  36. package/src/server/codex-engine-bridge.mjs +47 -0
  37. package/src/server/codex-engine-config.mjs +42 -0
  38. package/src/server/codex-engine-rpc.mjs +88 -0
  39. package/src/server/codex-handoff.mjs +20 -0
  40. package/src/server/codex-interactive-engine.mjs +335 -0
  41. package/src/server/codex-live-checkpoint.mjs +55 -0
  42. package/src/server/codex-live-credentials.mjs +214 -0
  43. package/src/server/codex-live-engine.mjs +577 -0
  44. package/src/server/codex-live-handoff.mjs +300 -0
  45. package/src/server/codex-live-lease.mjs +64 -0
  46. package/src/server/codex-live-rpc.mjs +155 -0
  47. package/src/server/codex-quota.mjs +36 -2
  48. package/src/server/codex-selection.mjs +62 -8
  49. package/src/server/codex-share.mjs +193 -0
  50. package/src/server/codex-terminal-runner.mjs +38 -1
  51. package/src/server/codex-terminal.mjs +15 -3
  52. package/src/server/codex-watch.mjs +3 -1
  53. package/src/server/codex-windows-private.mjs +96 -0
  54. package/src/server/codex-windows-private.ps1 +140 -0
  55. package/src/server/codex-windows-proxy.mjs +53 -0
  56. package/src/server/index.mjs +7 -1
  57. package/src/server/login-service.mjs +2 -0
  58. package/src/server/pinned-build.mjs +2 -0
@@ -0,0 +1,47 @@
1
+ // One authenticated local TUI connection. No browser origins, no shared port,
2
+ // no credentials in the URL, no public listener. ws handles RFC6455 framing.
3
+ import { createServer } from 'node:http';
4
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
5
+ import { WebSocketServer, WebSocket } from 'ws';
6
+
7
+ export async function createCodexEngineBridge({ onMessage, onDisconnect = () => {} }) {
8
+ const token = randomBytes(32).toString('hex');
9
+ const expected = Buffer.from(`Bearer ${token}`);
10
+ const server = createServer((_req, res) => { res.writeHead(404); res.end(); });
11
+ const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 * 1024, perMessageDeflate: false });
12
+ let client = null, accepted = false;
13
+ server.on('upgrade', (req, socket, head) => {
14
+ const actual = Buffer.from(String(req.headers.authorization ?? ''));
15
+ if (accepted || req.headers.origin || req.url !== '/' || actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
16
+ socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return;
17
+ }
18
+ accepted = true;
19
+ wss.handleUpgrade(req, socket, head, ws => {
20
+ client = ws;
21
+ ws.on('error', () => {});
22
+ ws.on('close', () => { client = null; onDisconnect(); });
23
+ ws.on('message', (data, binary) => {
24
+ if (binary) { ws.close(1003); return; }
25
+ let message;
26
+ try { message = JSON.parse(data.toString()); } catch { ws.close(1007); return; }
27
+ if (!message || typeof message !== 'object' || Array.isArray(message)) { ws.close(1007); return; }
28
+ Promise.resolve().then(() => onMessage(message)).catch(() => ws.close(1011));
29
+ });
30
+ });
31
+ });
32
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
33
+ return {
34
+ url: `ws://127.0.0.1:${server.address().port}/`, token,
35
+ send(message) {
36
+ if (client?.readyState !== WebSocket.OPEN) return;
37
+ if (client.bufferedAmount > 64 * 1024 * 1024) { client.close(1009); return; }
38
+ client.send(JSON.stringify(message));
39
+ },
40
+ async close() {
41
+ client?.terminate();
42
+ await new Promise(resolve => wss.close(resolve));
43
+ server.closeAllConnections?.();
44
+ await new Promise(resolve => server.close(resolve));
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,42 @@
1
+ // Preserve the live session's configuration through native RPC, without
2
+ // rewriting either account's config or putting settings/secrets in process argv.
3
+ import { readFile } from 'node:fs/promises';
4
+ import { createHash } from 'node:crypto';
5
+ import { join } from 'node:path';
6
+ export const configHash = text => createHash('sha256').update(text).digest('hex');
7
+ export const configText = home => readFile(join(home, 'config.toml'), 'utf8').catch(e => { if (e.code === 'ENOENT') return ''; throw e; });
8
+ export const isCustomCodexConfig = text => /^\s*(?:model_provider|["']model_provider["'])\s*=\s*["'](?!openai["'])/m.test(text)
9
+ || /^\s*(?:profile|["']profile["'])\s*=/m.test(text);
10
+ export function isTrustOnlyConfig(text) {
11
+ let project = false;
12
+ for (const raw of text.split(/\r?\n/)) {
13
+ const line = raw.trim();
14
+ if (!line || line.startsWith('#')) continue;
15
+ if (line.startsWith('[')) {
16
+ if (!/^\[projects\..+\]\s*(?:#.*)?$/.test(line)) return false;
17
+ project = true;
18
+ } else if (!project || !/^trust_level\s*=\s*["'](?:trusted|untrusted)["']\s*(?:#.*)?$/.test(line)) return false;
19
+ }
20
+ return true;
21
+ }
22
+ function merge(a, b) {
23
+ for (const [key, value] of Object.entries(b ?? {})) {
24
+ if (['__proto__', 'prototype', 'constructor'].includes(key)) throw new Error('Invalid config key.');
25
+ a[key] = value && typeof value === 'object' && !Array.isArray(value)
26
+ ? merge(a[key] && typeof a[key] === 'object' && !Array.isArray(a[key]) ? a[key] : {}, value) : value;
27
+ }
28
+ return a;
29
+ }
30
+ export async function captureSessionConfig(rpc, home, cwd) {
31
+ const before = await configText(home);
32
+ const result = await rpc.request('config/read', { includeLayers: true, ...(cwd ? { cwd } : {}) });
33
+ if (!Array.isArray(result?.layers)) return null;
34
+ const overrides = {};
35
+ // Native ConfigReadResponse lists highest priority first.
36
+ for (const layer of [...result.layers].reverse()) if (!layer.disabledReason && layer.config && typeof layer.config === 'object') merge(overrides, layer.config);
37
+ // Only raw TOML layers round-trip as overrides. The effective config/read
38
+ // view contains display values (for example empty policy arrays as strings)
39
+ // that native thread/resume cannot parse back into configuration.
40
+ if (await configText(home) !== before) throw new Error('Codex configuration changed during handoff.');
41
+ return { overrides, sourceHash: configHash(before), originHash: configHash(before) };
42
+ }
@@ -0,0 +1,88 @@
1
+ // Owned app-server process. JSON-RPC stays in memory; no auth or conversation
2
+ // messages are written to logs. Internal calls cannot collide with TUI ids.
3
+ import { spawn } from 'node:child_process';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { spawnSpec } from './exec-spec.mjs';
6
+ import { killTree } from './exec-children.mjs';
7
+
8
+ export function startEngineRpc(executable, args, home, { env = process.env, onMessage = () => {}, onClose = () => {}, onState = () => {}, spawnChild = spawn, deadlineMs = 12_000 } = {}) {
9
+ const spec = spawnSpec(executable, args);
10
+ const child = spawnChild(spec.file, spec.args, { ...spec.opts, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'ignore'], env: { ...env, CODEX_HOME: home } });
11
+ const kill = signal => {
12
+ if (process.platform !== 'win32' && child.pid) {
13
+ try { process.kill(-child.pid, signal); return; } catch { /* already exited */ }
14
+ }
15
+ killTree(child, signal);
16
+ };
17
+ const pending = new Map();
18
+ const prefix = `ccdeck-${randomUUID()}-`;
19
+ let serial = 0, chunks = [], buffered = 0, invalid = false, closed = false, stopping, exitCode = null, forced = false;
20
+ const ended = new Promise(resolve => {
21
+ const finish = () => {
22
+ if (closed) return;
23
+ closed = true;
24
+ for (const call of pending.values()) { clearTimeout(call.timer); call.reject(new Error('Codex connection closed.')); }
25
+ pending.clear(); onClose(); resolve();
26
+ };
27
+ child.once('close', code => { exitCode = code; finish(); });
28
+ child.once('error', finish);
29
+ });
30
+ child.stdin.on('error', () => {});
31
+ function protocolError(reason) {
32
+ invalid = true; chunks = []; buffered = 0;
33
+ onState({ state: 'backend-protocol-error', reason }); kill('SIGTERM');
34
+ }
35
+ child.stdout.on('data', chunk => {
36
+ if (invalid) return;
37
+ // Plugin catalogs can contain large inline icons. Scan each incoming byte
38
+ // once, instead of rescanning/copying an ever-growing partial JSON string.
39
+ let offset = 0;
40
+ while (offset < chunk.length) {
41
+ const end = chunk.indexOf(10, offset), stop = end < 0 ? chunk.length : end;
42
+ const part = chunk.subarray(offset, stop);
43
+ buffered += part.length;
44
+ if (buffered > 64 * 1024 * 1024) { protocolError('size'); return; }
45
+ chunks.push(part);
46
+ if (end < 0) return;
47
+ const line = Buffer.concat(chunks, buffered).toString('utf8');
48
+ chunks = []; buffered = 0; offset = end + 1;
49
+ if (!line.trim()) continue;
50
+ let message;
51
+ try { message = JSON.parse(line); } catch { protocolError('json'); return; }
52
+ const call = pending.get(message.id);
53
+ if (call && !message.method) {
54
+ clearTimeout(call.timer); pending.delete(message.id);
55
+ if (message.error) call.reject(new Error('Codex rejected an engine request.'));
56
+ else call.resolve(message.result);
57
+ } else if (!(typeof message.id === 'string' && message.id.startsWith(prefix) && !message.method)) onMessage(message);
58
+ }
59
+ });
60
+ function send(message) {
61
+ if (closed || child.stdin.destroyed) throw new Error('Codex connection is unavailable.');
62
+ // Bound both RPC requests and writes from a misbehaving local client.
63
+ if (child.stdin.writableLength > 64 * 1024 * 1024) throw new Error('Codex request queue is full.');
64
+ child.stdin.write(JSON.stringify(message) + '\n');
65
+ }
66
+ return {
67
+ send,
68
+ request(method, params) {
69
+ if (pending.size >= 64) return Promise.reject(new Error('Codex request queue is full.'));
70
+ const id = prefix + (++serial);
71
+ return new Promise((resolve, reject) => {
72
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error('Codex request timed out; it was not retried.')); }, deadlineMs);
73
+ pending.set(id, { resolve, reject, timer });
74
+ try { send({ id, method, params }); } catch (error) { clearTimeout(timer); pending.delete(id); reject(error); }
75
+ });
76
+ },
77
+ async stop() {
78
+ if (stopping) return stopping;
79
+ stopping = (async () => {
80
+ child.stdin.end(); // EOF lets app-server flush the rollout before exit.
81
+ const term = setTimeout(() => { forced = true; kill('SIGTERM'); }, 2000);
82
+ const force = setTimeout(() => kill('SIGKILL'), 4000);
83
+ try { await ended; return !forced && exitCode === 0; } finally { clearTimeout(term); clearTimeout(force); }
84
+ })();
85
+ return stopping;
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,20 @@
1
+ // A transferred rollout contains history the deck already observed in another
2
+ // home. New watcher cursors start after that prefix, not by replaying its tools.
3
+ import { open } from 'node:fs/promises';
4
+ import { constants } from 'node:fs';
5
+ export const codexHandoffPath = path => `${path}.ccdeck-handoff.json`;
6
+ export async function codexHandoffOffset(path, sid, size) {
7
+ let marker, rollout;
8
+ try {
9
+ marker = await open(codexHandoffPath(path), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
10
+ if ((await marker.stat()).size > 512) return 0;
11
+ const value = JSON.parse(await marker.readFile('utf8'));
12
+ if (value.version !== 1 || value.threadId !== sid || !Number.isSafeInteger(value.copiedBytes)
13
+ || value.copiedBytes <= 0 || value.copiedBytes > Math.min(size, 64 * 1024 * 1024)) return 0;
14
+ rollout = await open(path, 'r');
15
+ const boundary = Buffer.alloc(1);
16
+ await rollout.read(boundary, 0, 1, value.copiedBytes - 1);
17
+ return boundary[0] === 10 ? value.copiedBytes : 0;
18
+ } catch { return 0; }
19
+ finally { await marker?.close(); await rollout?.close(); }
20
+ }
@@ -0,0 +1,335 @@
1
+ // The native TUI stays attached to one local bridge. Only its owned app-server
2
+ // changes account after an explicit selection or terminal quota failure, once
3
+ // active tools have finished and the old backend has exited cleanly.
4
+ import { dirname } from 'node:path';
5
+ import { readCodexSelection } from './codex-selection.mjs';
6
+ import { captureSessionConfig, configHash, configText, isTrustOnlyConfig, isCustomCodexConfig } from './codex-engine-config.mjs';
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { realpath } from 'node:fs/promises';
9
+ import { spawn, execFile } from 'node:child_process';
10
+ import { promisify } from 'node:util';
11
+ import { runAccountEngine } from './account-engine.mjs';
12
+ import { createCodexEngineAdapter } from './codex-engine-adapter.mjs';
13
+ import { createCodexEngineBridge } from './codex-engine-bridge.mjs';
14
+ import { startEngineRpc } from './codex-engine-rpc.mjs';
15
+ import { spawnSpec } from './exec-spec.mjs';
16
+ import { killTree } from './exec-children.mjs';
17
+
18
+ const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
19
+ const fields = ['approvalPolicy', 'approvalsReviewer', 'baseInstructions', 'config', 'cwd', 'developerInstructions', 'model', 'modelProvider', 'personality', 'sandbox', 'serviceTier'];
20
+ const turnFields = ['approvalPolicy', 'approvalsReviewer', 'cwd', 'disabledPluginIds', 'effort', 'model', 'outputSchema', 'personality', 'sandboxPolicy', 'serviceTier', 'summary'];
21
+ const pick = (source, keys) => Object.fromEntries(keys.filter(k => Object.hasOwn(source ?? {}, k)).map(k => [k, source[k]]));
22
+ const clone = value => JSON.parse(JSON.stringify(value));
23
+ const continuation = 'Continue the previous task from where it stopped. Check the existing work before repeating any action.';
24
+ const toolTypes = new Set(['commandExecution', 'mcpToolCall', 'dynamicToolCall', 'fileChange', 'collabAgentToolCall', 'subAgentActivity', 'webSearch', 'imageView', 'imageGeneration', 'sleep']);
25
+ const deferredMethods = new Set(['account/read', 'account/rateLimits/read', 'app/installed', 'app/read', 'plugin/list', 'skills/list', 'config/read', 'configRequirements/read', 'model/list', 'collaborationMode/list', 'command/exec']);
26
+
27
+ export function codexInteractiveInvocation(args) {
28
+ const backendArgs = ['app-server', '--listen', 'stdio://'];
29
+ const values = new Set(['-c', '--config', '--enable', '--disable', '-m', '--model', '-s', '--sandbox', '-a', '--ask-for-approval', '-C', '--cd', '--add-dir']);
30
+ const flags = new Set(['--strict-config', '--no-alt-screen', '--search', '--approve-for-me', '--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust']);
31
+ let resume = false, threadId = null, prompt = false;
32
+ for (let i = 0; i < args.length; i++) {
33
+ const arg = args[i], key = arg.split('=')[0];
34
+ if (prompt) return null;
35
+ if (values.has(key)) {
36
+ let value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
37
+ if (value === undefined) return null;
38
+ if (['-c', '--config'].includes(key)) {
39
+ if (/^\s*(?:model_provider|model_providers\.|chatgpt_base_url|openai_base_url|cli_auth_credentials_store)/.test(value)) return null;
40
+ backendArgs.push('-c', value);
41
+ } else if (key === '--enable' || key === '--disable') backendArgs.push(key, value);
42
+ continue;
43
+ }
44
+ if (flags.has(arg)) { if (arg === '--strict-config') backendArgs.push(arg); continue; }
45
+ if (arg === 'resume' && !resume) { resume = true; continue; }
46
+ if (arg === '--' && i === args.length - 2) { prompt = true; i++; continue; }
47
+ if (arg.startsWith('-')) return null;
48
+ if (resume && !threadId) { if (!UUID.test(arg)) return null; threadId = arg; }
49
+ else { if (!resume && ['exec', 'e', 'review', 'fork', 'login', 'logout', 'app', 'app-server', 'mcp', 'mcp-server', 'completion', 'sandbox', 'debug', 'apply', 'cloud', 'features', 'help', 'update'].includes(arg)) return null; prompt = true; }
50
+ }
51
+ // A picker can choose unrelated histories. Explicit ids have a clear owner.
52
+ if (resume && !threadId) return null;
53
+ return { backendArgs, threadId };
54
+ }
55
+
56
+ export async function supportsCodexInteractiveEngine(executable, env = process.env) {
57
+ try {
58
+ const spec = spawnSpec(executable, ['--help']);
59
+ const { stdout } = await promisify(execFile)(spec.file, spec.args, { ...spec.opts, env, timeout: 5000, maxBuffer: 256 * 1024 });
60
+ return stdout.includes('--remote ') && stdout.includes('--remote-auth-token-env');
61
+ } catch { return false; }
62
+ }
63
+
64
+ export async function createInteractiveCodexSession(file, executable, args, home, options = {}) {
65
+ const invocation = codexInteractiveInvocation(args);
66
+ if (!invocation) return null;
67
+ const adapter = options.adapter ?? createCodexEngineAdapter(file, executable, ['exec', '--json'], home, { ...options, moveConversation: true });
68
+ const controller = new AbortController();
69
+ const clients = new Map(), serverRequests = new Set(), threads = new Map(), active = new Set(), processes = new Set(), tools = new Set();
70
+ const deferredRequests = [];
71
+ let rpc, bridge, initialize, settleAttempt, current, failedThread, frozen = false, automatic = true, closed = false;
72
+ let authChanged = false, restoring = false, quotaFailure = null, deferredTurn = null, interrupted = false, engineFinished = false;
73
+ let selectedThread = invocation.threadId, pendingManual = null, lastManualRevision = 0, manualTurn = false, manualInterrupt = false, switchingManual = false;
74
+ const turnIds = new Map();
75
+ const selectionOptions = { store: dirname(file), ...options };
76
+ const readSelection = options.readSelection ?? (() => readCodexSelection(selectionOptions));
77
+ let initialSelection;
78
+ try { initialSelection = await readSelection(); lastManualRevision = initialSelection.runningSelection?.revision ?? 0; } catch { /* registry is checked on each poll */ }
79
+ let inheritedConfig = null;
80
+ // Isolated login homes start empty. Keep the original CLI's settings for
81
+ // those sessions, regardless of which account was selected at launch.
82
+ const original = initialSelection?.originalHome;
83
+ const originalPath = original ? await realpath(original).catch(() => null) : null;
84
+ if (originalPath && originalPath !== await realpath(home) && isTrustOnlyConfig(await configText(home))) {
85
+ const text = await configText(original);
86
+ if (text.trim() && !isCustomCodexConfig(text)) {
87
+ const reader = startEngineRpc(executable, options.backendArgs ?? invocation.backendArgs, original, { env: options.env });
88
+ try {
89
+ await reader.request('initialize', { clientInfo: { name: 'ccdeck-config', version: '1' }, capabilities: { experimentalApi: true } });
90
+ const captured = await captureSessionConfig(reader, original);
91
+ if (captured) inheritedConfig = { ...captured, sourceHash: configHash(await configText(home)) };
92
+ } finally { await reader.stop(); }
93
+ }
94
+ }
95
+ const sendClient = message => bridge.send(message);
96
+ const rejectClient = (message, text) => {
97
+ if (message.id !== undefined && message.method) sendClient({ id: message.id, error: { code: -32000, message: text } });
98
+ };
99
+ function fromClient(message) {
100
+ if (closed) return;
101
+ if (frozen) {
102
+ // These requests have not reached any backend. Hold startup/metadata
103
+ // work once, so the native TUI does not show spurious handoff warnings.
104
+ if (message.id !== undefined && deferredMethods.has(message.method) && deferredRequests.length < 32) {
105
+ deferredRequests.push(clone(message)); return;
106
+ }
107
+ if (message.method === 'turn/interrupt') {
108
+ interrupted = true; automatic = false;
109
+ if (deferredTurn) rejectClient(deferredTurn, 'Your queued message was cancelled.');
110
+ deferredTurn = null;
111
+ }
112
+ // The native TUI may submit a queued follow-up as a failed turn ends.
113
+ // Hold that unsent request once; do not add an engine Continue as well.
114
+ if (message.method === 'turn/start' && message.params?.threadId === failedThread && !deferredTurn && !interrupted) {
115
+ automatic = false; deferredTurn = clone(message);
116
+ options.onState?.({ state: 'follow-up-held' });
117
+ return;
118
+ }
119
+ if (['turn/interrupt', 'account/login/start', 'account/logout', 'thread/start', 'thread/fork'].includes(message.method)
120
+ || message.method === 'thread/resume' && message.params?.threadId !== failedThread) automatic = false;
121
+ options.onState?.({ state: 'request-during-handoff', method: message.method, sameThread: message.params?.threadId === failedThread });
122
+ rejectClient(message, 'Account continuation is in progress. Please wait, then try again.');
123
+ return;
124
+ }
125
+ if (inheritedConfig && ['thread/start', 'thread/resume', 'thread/fork'].includes(message.method)) {
126
+ message = { ...message, params: { ...message.params, config: { ...inheritedConfig.overrides, ...message.params?.config } } };
127
+ }
128
+ if (['turn/start', 'turn/interrupt', 'thread/start', 'thread/resume', 'thread/fork'].includes(message.method)) quotaFailure = null;
129
+ if (message.method === 'turn/interrupt') { pendingManual = null; manualTurn = false; manualInterrupt = false; }
130
+ if (message.method === 'turn/start' && threads.has(message.params?.threadId)
131
+ && !threads.get(message.params.threadId).ephemeral) selectedThread = message.params.threadId;
132
+ if (message.method === 'process/spawn') processes.add(message.params?.processHandle);
133
+ if (message.method === 'initialize') initialize = clone(message.params);
134
+ if (['account/login/start', 'account/logout'].includes(message.method)) authChanged = true;
135
+ if (message.id !== undefined && message.method) {
136
+ if (clients.size >= 128) { rejectClient(message, 'Too many pending requests.'); return; }
137
+ clients.set(message.id, { method: message.method, params: clone(message.params ?? {}) });
138
+ } else if (!message.method) serverRequests.delete(message.id);
139
+ try { rpc.send(message); } catch { rejectClient(message, 'Codex connection is unavailable. No request was retried.'); }
140
+ }
141
+ function fromServer(message) {
142
+ if (closed) return;
143
+ const request = clients.get(message.id);
144
+ if (!message.method && request) {
145
+ clients.delete(message.id);
146
+ const thread = message.result?.thread;
147
+ if (thread && UUID.test(thread.id ?? '') && ['thread/start', 'thread/resume', 'thread/fork'].includes(request.method)) {
148
+ if (request.params.ephemeral !== true) selectedThread = thread.id;
149
+ threads.set(thread.id, { ephemeral: request.params.ephemeral === true, resume: { ...pick(request.params, fields), ...(thread.cwd ? { cwd: thread.cwd } : {}) }, turn: {}, ...(inheritedConfig ? { sessionConfig: inheritedConfig } : {}) });
150
+ }
151
+ }
152
+ if (message.method && message.id !== undefined) serverRequests.add(message.id);
153
+ const p = message.params;
154
+ if (message.method === 'process/exited') processes.delete(p?.processHandle);
155
+ if (message.method === 'item/started' && toolTypes.has(p?.item?.type)) tools.add(p.item.id);
156
+ if (message.method === 'item/completed' && p?.item?.status !== 'inProgress') tools.delete(p?.item?.id);
157
+ if (message.method === 'turn/started') { active.add(p?.threadId); turnIds.set(p?.threadId, p?.turn?.id); }
158
+ if (message.method === 'turn/completed') {
159
+ active.delete(p?.threadId); turnIds.delete(p?.threadId);
160
+ if (manualInterrupt && p?.threadId === selectedThread) manualTurn = p.turn.status === 'interrupted'
161
+ || p.turn.error?.codexErrorInfo === 'usageLimitExceeded';
162
+ }
163
+ if (request?.method === 'process/spawn' && message.error) processes.delete(request.params.processHandle);
164
+ if (request?.method === 'turn/start' && !message.error) {
165
+ const owned = threads.get(request.params.threadId);
166
+ if (owned) owned.turn = pick(request.params, turnFields);
167
+ }
168
+ // Closing the old owned backend is a transport handoff, not a closed user
169
+ // thread. Letting the TUI see it would trigger its own competing resume.
170
+ if (!(frozen && ['thread/closed', 'thread/started', 'thread/status/changed'].includes(message.method))) sendClient(message);
171
+ if (message.method === 'turn/completed' && p?.turn?.status === 'failed'
172
+ && p.turn.error?.codexErrorInfo === 'usageLimitExceeded' && threads.has(p.threadId)
173
+ && !threads.get(p.threadId).ephemeral) quotaFailure = p;
174
+ maybeManual();
175
+ maybeFailover();
176
+ }
177
+ function maybeManual() {
178
+ if (!pendingManual || closed || frozen || restoring || authChanged || !initialize || !selectedThread
179
+ || !threads.has(selectedThread) || threads.get(selectedThread).ephemeral || clients.size || serverRequests.size || tools.size || processes.size) return;
180
+ if ([...active].some(id => id !== selectedThread)) return;
181
+ if (pendingManual.id === current.id) { pendingManual = null; return; }
182
+ if (engineFinished) { engineFinished = false; drive(current); }
183
+ if (active.has(selectedThread)) {
184
+ if (!manualInterrupt) {
185
+ manualInterrupt = true; manualTurn = false;
186
+ rpc.request('turn/interrupt', { threadId: selectedThread, turnId: turnIds.get(selectedThread) }).catch(() => { pendingManual = null; manualInterrupt = false; });
187
+ }
188
+ return;
189
+ }
190
+ const intent = pendingManual; pendingManual = null; manualInterrupt = false;
191
+ beginHandoff(selectedThread, { reason: 'manual_switch', targetId: intent.id }, manualTurn);
192
+ manualTurn = false;
193
+ }
194
+ function maybeFailover() {
195
+ if (engineFinished || !quotaFailure || restoring || frozen || authChanged || active.size || tools.size || processes.size || clients.size || serverRequests.size || !initialize) return;
196
+ const threadId = quotaFailure.threadId; quotaFailure = null;
197
+ beginHandoff(threadId, { reason: 'usage_limit' }, true);
198
+ }
199
+ function beginHandoff(threadId, outcome, continueTask) {
200
+ failedThread = threadId;
201
+ frozen = true; automatic = continueTask; interrupted = false;
202
+ switchingManual = outcome.reason === 'manual_switch';
203
+ options.onState?.({ state: 'switching', trigger: switchingManual ? 'manual' : 'quota', targetId: outcome.targetId });
204
+ const owner = rpc;
205
+ (async () => {
206
+ const saved = threads.get(threadId);
207
+ const captured = await captureSessionConfig(owner, current.home, saved.resume.cwd);
208
+ // config/read is backend-wide. A later backend's defaults must not
209
+ // replace the original thread settings we already carried over.
210
+ saved.sessionConfig = saved.sessionConfig && captured
211
+ ? { ...saved.sessionConfig, sourceHash: captured.sourceHash } : captured;
212
+ const clean = await owner.stop();
213
+ if (!closed) settleAttempt?.({ code: 1, threadId, ...outcome, ...(!clean ? { reason: 'failed' } : {}) });
214
+ })().catch(async () => {
215
+ // Even a failed configuration read must drain the old backend before
216
+ // restoring it. Two writers must never own the same rollout.
217
+ const clean = await owner.stop();
218
+ if (!closed) settleAttempt?.({ code: 1, reason: clean ? 'handoff_failed' : 'failed' });
219
+ });
220
+ }
221
+ function start(home) {
222
+ return (options.startRpc ?? startEngineRpc)(executable, options.backendArgs ?? invocation.backendArgs, home, {
223
+ ...options, onMessage: fromServer,
224
+ onClose: () => { options.onState?.({ state: 'backend-closed' }); if (!frozen && !closed) settleAttempt?.({ code: 1, reason: 'failed' }); },
225
+ });
226
+ }
227
+ async function reconnect(next, continueTask) {
228
+ rpc = start(next.home);
229
+ await rpc.request('initialize', initialize);
230
+ rpc.send({ method: 'initialized', params: {} });
231
+ const saved = threads.get(failedThread);
232
+ if (!saved) throw new Error('Codex conversation ownership is unknown.');
233
+ const resumed = await rpc.request('thread/resume', { ...saved.resume, ...(saved.sessionConfig ? { config: { ...saved.sessionConfig.overrides, ...saved.resume.config } } : {}), threadId: failedThread, excludeTurns: true });
234
+ if (resumed?.thread?.id !== failedThread) throw new Error('Codex resumed a different conversation.');
235
+ frozen = false;
236
+ selectedThread = failedThread;
237
+ options.onState?.({ state: 'resumed', automatic: continueTask && automatic, accountId: next.id });
238
+ for (const request of deferredRequests.splice(0)) fromClient(request);
239
+ if (deferredTurn) {
240
+ const queued = deferredTurn; deferredTurn = null;
241
+ if (continueTask && !interrupted && !controller.signal.aborted) fromClient(queued);
242
+ else rejectClient(queued, 'Automatic continuation stopped. Please submit your message again.');
243
+ } else if (continueTask && automatic && !interrupted && !controller.signal.aborted) {
244
+ // One submission only. A timeout is ambiguous and is never resubmitted.
245
+ await rpc.request('turn/start', { ...saved.turn, threadId: failedThread, clientUserMessageId: randomUUID(), input: [{ type: 'text', text: continuation }] });
246
+ }
247
+ }
248
+ bridge = await createCodexEngineBridge({ onMessage: fromClient, onDisconnect: () => { options.onState?.({ state: 'client-disconnected' }); void close(); } });
249
+ const initial = { id: createHash('sha256').update(await realpath(home)).digest('hex').slice(0, 20), home, threadId: invocation.threadId };
250
+ // A selection committed between launcher resolution and engine startup
251
+ // still belongs to this launch, rather than being mistaken for an old event.
252
+ if (initialSelection?.profileId === initialSelection?.runningSelection?.id
253
+ && initialSelection?.runningSelection && initialSelection.profileId !== initial.id) pendingManual = initialSelection.runningSelection;
254
+ let readyResolve, readyReject;
255
+ const ready = new Promise((resolve, reject) => { readyResolve = resolve; readyReject = reject; });
256
+ const provider = {
257
+ ...adapter,
258
+ prepare(params) { return adapter.prepare({ ...params, sessionConfig: threads.get(params.threadId)?.sessionConfig }); },
259
+ run(next) {
260
+ current = next;
261
+ return new Promise((resolveAttempt, reject) => {
262
+ settleAttempt = resolveAttempt;
263
+ if (controller.signal.aborted) { resolveAttempt({ code: 130, reason: 'cancelled' }); return; }
264
+ if (!rpc) { rpc = start(next.home); readyResolve(); }
265
+ else if (frozen) reconnect(next, true).catch(reject);
266
+ });
267
+ },
268
+ };
269
+ let done;
270
+ function drive(startAt) {
271
+ done = runAccountEngine(provider, startAt, { signal: controller.signal }).then(async result => {
272
+ engineFinished = true;
273
+ if (!closed && frozen && failedThread) {
274
+ restoring = true;
275
+ try { await reconnect(current, false); } catch { await close(); }
276
+ restoring = false;
277
+ }
278
+ if (!closed && !frozen && result.reason === 'failed') await close();
279
+ return result;
280
+ }).catch(async () => { engineFinished = true; readyReject(new Error('Codex app-server could not start.')); await close(); return { code: 1, reason: 'failed' }; });
281
+ return done;
282
+ }
283
+ drive(initial);
284
+ let checking = false;
285
+ const poll = setInterval(async () => {
286
+ if (checking || closed) return;
287
+ checking = true;
288
+ try {
289
+ const s = await readSelection(), intent = s.runningSelection;
290
+ if (intent && intent.revision > lastManualRevision) {
291
+ lastManualRevision = intent.revision;
292
+ pendingManual = intent;
293
+ options.onState?.({ state: 'manual-requested', targetId: intent.id });
294
+ }
295
+ maybeManual();
296
+ } catch { /* unavailable metadata never authorizes a switch */ }
297
+ finally { checking = false; }
298
+ }, options.manualPollMs ?? 500);
299
+ poll.unref();
300
+ let closing;
301
+ async function close() {
302
+ if (closing) return closing;
303
+ closed = true; clearInterval(poll); controller.abort();
304
+ settleAttempt?.({ code: 130, reason: 'cancelled' });
305
+ closing = (async () => { await rpc?.stop(); await adapter.close(); await bridge.close(); })();
306
+ return closing;
307
+ }
308
+ await ready;
309
+ return { url: bridge.url, token: bridge.token, tuiHome: inheritedConfig ? original : home, get done() { return done; }, close };
310
+ }
311
+
312
+ export async function runInteractiveCodex(file, executable, args, home, options = {}) {
313
+ const session = await createInteractiveCodexSession(file, executable, args, home, options);
314
+ if (!session) throw new Error('Unsupported interactive Codex invocation.');
315
+ const spec = spawnSpec(executable, ['--remote', session.url, '--remote-auth-token-env', 'CCDECK_CODEX_ENGINE_TOKEN', ...args]);
316
+ const child = spawn(spec.file, spec.args, { ...spec.opts, stdio: 'inherit', env: { ...(options.env ?? process.env), CODEX_HOME: session.tuiHome, CCDECK_CODEX_ENGINE_TOKEN: session.token } });
317
+ let force;
318
+ const stop = () => {
319
+ killTree(child, 'SIGTERM');
320
+ force ??= setTimeout(() => killTree(child, 'SIGKILL'), 2000);
321
+ force.unref?.();
322
+ };
323
+ const hold = () => {}; // Ctrl+C belongs to the native TUI; it is not an engine retry.
324
+ process.on('SIGINT', hold); process.on('SIGTERM', stop); process.on('SIGHUP', stop);
325
+ try {
326
+ return await new Promise((resolve, reject) => {
327
+ child.once('error', reject);
328
+ child.once('close', (code, signal) => resolve({ code: code ?? (signal === 'SIGINT' ? 130 : 143), signal }));
329
+ });
330
+ } finally {
331
+ clearTimeout(force);
332
+ process.removeListener('SIGINT', hold); process.removeListener('SIGTERM', stop); process.removeListener('SIGHUP', stop);
333
+ await session.close();
334
+ }
335
+ }
@@ -0,0 +1,55 @@
1
+ // Parent-owned V2 agents pause by finishing a cooperative checkpoint, never by
2
+ // interrupting tool execution whose start is absent from the native item feed.
3
+ import { liveError } from './codex-live-rpc.mjs';
4
+ import { readCodexLiveTurn } from './codex-live-handoff.mjs';
5
+
6
+ const inputs = turn => turn.items.filter(i => i.type === 'userMessage').map(i => i.id);
7
+ export async function requestCodexLiveCheckpoints(rpc, entries, options) {
8
+ for (const entry of entries) if (!entry.checkpointReady) await options.record(entry, 'checkpoint_waiting');
9
+ for (const owner of entries.filter(e => !e.resumeViaThreadId && !e.checkpointReady)) {
10
+ await options.beforeSend?.();
11
+ await options.record(owner, 'checkpoint_sent');
12
+ const targets = entries.filter(e => e.resumeViaThreadId === owner.threadId).reverse().map(e => e.threadId);
13
+ const text = 'A ccdeck account change is pending. Keep the existing assignments and conversation history. '
14
+ + 'Use native send_message to ask each of these existing subagents to finish its current tool call, record a concise checkpoint of its unfinished assignment, '
15
+ + 'then END its current response with CCDECK_CHECKPOINT_' + owner.checkpointId + ': ' + JSON.stringify(targets)
16
+ + '. This is a temporary pause, not completion of the original assignments. Do not spawn replacements or close agents. '
17
+ + 'Do not message an agent that already finished or was closed. Wait for all requested checkpoints, then checkpoint your own unfinished work and END your current response '
18
+ + 'with the same marker. Do not resume any checkpointed task until the account change is complete and you receive the continuation instruction. '
19
+ + 'Honor newer user instructions; if the user cancelled or asked to stop, remain stopped.';
20
+ await rpc.request('turn/steer', { threadId: owner.threadId, expectedTurnId: owner.turnId,
21
+ clientUserMessageId: owner.checkpointId, input: [{ type: 'text', text }] });
22
+ }
23
+ }
24
+
25
+ export async function inspectCodexLiveCheckpoints(rpc, entries, options) {
26
+ let pending = false;
27
+ for (const entry of entries) {
28
+ if (entry.phase === 'skipped') continue;
29
+ const t = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
30
+ if (!t || (t.parentThreadId ?? null) !== (entry.parentThreadId ?? null)) throw liveError('native_activity_changed');
31
+ if (t.status?.type === 'notLoaded') { pending = true; continue; }
32
+ const turn = await readCodexLiveTurn(rpc, t);
33
+ if (!turn || turn.itemsView !== 'full' || !Array.isArray(turn.items)) throw liveError('native_activity_unknown');
34
+ if (turn.rootTurnId !== entry.rootTurnId || !entry.resumeViaThreadId && turn.id !== entry.turnId) throw liveError('native_activity_changed');
35
+ if (!entry.resumeViaThreadId) {
36
+ const previous = turn.items.filter(i => i.type === 'userMessage' && (entry.checkpointReady || i.clientId !== entry.checkpointId)).map(i => i.id);
37
+ if (JSON.stringify(previous) !== JSON.stringify(entry.inputIds)) throw liveError('native_activity_changed');
38
+ }
39
+ if (entry.checkpointReady) {
40
+ if (turn.id !== entry.turnId || turn.status !== 'completed'
41
+ || !turn.items.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId))) throw liveError('native_activity_changed');
42
+ continue;
43
+ }
44
+ if (turn.status === 'inProgress') { pending = true; continue; }
45
+ if (turn.status !== 'completed') throw liveError('native_continue_unconfirmed');
46
+ const ready = turn.items.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId));
47
+ if (ready) {
48
+ entry.turnId = turn.id; entry.inputIds = inputs(turn); entry.checkpointReady = true;
49
+ await options.record(entry, 'checkpoint_ready');
50
+ } else await options.record(entry, 'skipped'); // Naturally finished work stays finished.
51
+ }
52
+ const paused = entries.filter(e => e.checkpointReady);
53
+ if (!pending && paused.some(e => e.resumeViaThreadId && !paused.some(p => p.threadId === e.resumeViaThreadId))) throw liveError('native_continue_unconfirmed');
54
+ return pending ? null : { waiting: false, paused };
55
+ }