ccdeck 3.53.2 → 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 (62) hide show
  1. package/README.md +56 -4
  2. package/THIRD_PARTY_NOTICES.md +31 -1
  3. package/dist/web/assets/{BrowserWatchModal-DedhCY8E.js → BrowserWatchModal-Bfvo_8H6.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-1m1mQQhW.js → IntegrationModal-GS5jIQ_J.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-Sgo5WNTi.js → RadioPanel-Bxd2ElWb.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-BqjzLlO_.js → TrafficRadar-FgHBI2Oh.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-2pcftBwX.js → UsageHistoryModal-APwKtE2J.js} +1 -1
  8. package/dist/web/assets/{app-BZaB84m4.js → app-BzHVsgB2.js} +90 -90
  9. package/dist/web/assets/{index-D1WZBFCw.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 +39 -1
  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/deck-prefs.mjs +6 -1
  57. package/src/server/index.mjs +9 -2
  58. package/src/server/login-service.mjs +2 -0
  59. package/src/server/pinned-build.mjs +2 -0
  60. package/src/server/reports-routes.mjs +10 -0
  61. package/src/server/reports.mjs +46 -5
  62. package/src/server/ui-language.mjs +17 -0
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "ws",
3
+ "version": "8.22.1",
4
+ "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
5
+ "keywords": [
6
+ "HyBi",
7
+ "Push",
8
+ "RFC-6455",
9
+ "WebSocket",
10
+ "WebSockets",
11
+ "real-time"
12
+ ],
13
+ "homepage": "https://github.com/websockets/ws",
14
+ "bugs": "https://github.com/websockets/ws/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/websockets/ws.git"
18
+ },
19
+ "author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
20
+ "license": "MIT",
21
+ "main": "index.js",
22
+ "exports": {
23
+ ".": {
24
+ "browser": "./browser.js",
25
+ "import": "./wrapper.mjs",
26
+ "require": "./index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "browser": "browser.js",
31
+ "engines": {
32
+ "node": ">=10.0.0"
33
+ },
34
+ "files": [
35
+ "browser.js",
36
+ "index.js",
37
+ "lib/*.js",
38
+ "wrapper.mjs"
39
+ ],
40
+ "scripts": {
41
+ "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
42
+ "integration": "mocha --throw-deprecation test/*.integration.js",
43
+ "lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
44
+ },
45
+ "peerDependencies": {
46
+ "bufferutil": "^4.0.1",
47
+ "utf-8-validate": ">=5.0.2"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "bufferutil": {
51
+ "optional": true
52
+ },
53
+ "utf-8-validate": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "devDependencies": {
58
+ "@eslint/js": "^10.0.1",
59
+ "benchmark": "^2.1.4",
60
+ "bufferutil": "^4.0.1",
61
+ "eslint": "^10.0.1",
62
+ "eslint-config-prettier": "^10.0.1",
63
+ "eslint-plugin-prettier": "^5.0.0",
64
+ "globals": "^17.0.0",
65
+ "mocha": "^8.4.0",
66
+ "nyc": "^15.0.0",
67
+ "prettier": "^3.0.0",
68
+ "utf-8-validate": "^6.0.0"
69
+ },
70
+ "allowScripts": {
71
+ "bufferutil": true,
72
+ "utf-8-validate": true
73
+ }
74
+ }
@@ -0,0 +1,21 @@
1
+ import createWebSocketStream from './lib/stream.js';
2
+ import extension from './lib/extension.js';
3
+ import PerMessageDeflate from './lib/permessage-deflate.js';
4
+ import Receiver from './lib/receiver.js';
5
+ import Sender from './lib/sender.js';
6
+ import subprotocol from './lib/subprotocol.js';
7
+ import WebSocket from './lib/websocket.js';
8
+ import WebSocketServer from './lib/websocket-server.js';
9
+
10
+ export {
11
+ createWebSocketStream,
12
+ extension,
13
+ PerMessageDeflate,
14
+ Receiver,
15
+ Sender,
16
+ subprotocol,
17
+ WebSocket,
18
+ WebSocketServer
19
+ };
20
+
21
+ export default WebSocket;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ccdeck",
3
- "version": "3.53.2",
3
+ "version": "3.80.0",
4
4
  "description": "Local dashboard for Claude Code and Codex CLI sessions: which Claude Code session needs input, every tool call and Claude Code subagent live, token cost and quota, several Claude accounts. Run npx ccdeck.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -98,9 +98,11 @@
98
98
  "vitest": "^2.1.9"
99
99
  },
100
100
  "dependencies": {
101
- "fs-native-extensions": "1.5.2"
101
+ "fs-native-extensions": "1.5.2",
102
+ "ws": "8.22.1"
102
103
  },
103
104
  "bundledDependencies": [
104
- "fs-native-extensions"
105
+ "fs-native-extensions",
106
+ "ws"
105
107
  ]
106
108
  }
@@ -84,6 +84,7 @@
84
84
  "without one."
85
85
  ],
86
86
  "//summaries": {
87
+ "3.80.0": "Codex account switching, continuation and sharing",
87
88
  "3.53.0": "Codex accounts, with sign-in, switching and Auto-switch",
88
89
  "3.52.0": "ccdeck in nine more languages",
89
90
  "3.51.0": "Jira integration updates",
@@ -131,7 +132,44 @@
131
132
  "3.43.3",
132
133
  "3.48.1",
133
134
  "3.49.1",
134
- "3.53.1"
135
+ "3.53.1",
136
+ "3.53.3"
137
+ ],
138
+ "3.80.0": [
139
+ {
140
+ "title": "Switch Codex accounts without losing your place",
141
+ "body": "Move supported running Codex conversations and their subagents to another account, then continue the same work.",
142
+ "priority": "highlight",
143
+ "icon": "accounts",
144
+ "noticeLabel": "Compatibility",
145
+ "notice": "Requires Codex 0.166.0 or newer and a private auth.json login on a supported shared native server. Conversations connected to that server switch together. ccdeck waits for tools and approvals, and must stay open to renew the selected login. After a lost connection or restart, a server that cannot confirm the workspace identity requires Reconnect selected account. If continuation is unconfirmed, check the conversation before continuing manually; uncertain sends are never repeated automatically."
146
+ },
147
+ {
148
+ "title": "Share Codex logins between your machines",
149
+ "body": "Choose accounts to export, then paste the code into Import Codex accounts on another machine, including Windows.",
150
+ "priority": "highlight",
151
+ "icon": "accounts",
152
+ "noticeLabel": "Login privacy",
153
+ "notice": "Sharing is optional and exports live ChatGPT credentials, including the renewal token, from file-backed logins. The code is encoded, not encrypted, and has no automatic expiry or ccdeck revocation. Use a trusted private channel and delete clipboard or message copies afterward. Renewal on one machine can invalidate the other copy and require signing in again. Configuration and conversation history are not transferred."
154
+ },
155
+ {
156
+ "title": "See your available Codex resets",
157
+ "body": "Usage shows saved rate-limit resets and their nearest expiry when the selected account provides them.",
158
+ "priority": "highlight",
159
+ "noticeLabel": "Availability",
160
+ "notice": "Reset inventory requires a validated file-backed login and an available provider reading. Checking the inventory never spends a reset."
161
+ },
162
+ {
163
+ "title": "Continue managed terminal tasks on another account",
164
+ "body": "With Codex Auto-switch enabled, supported terminal tasks can resume the same conversation on an account with quota after a usage-limit failure.",
165
+ "priority": "required",
166
+ "noticeLabel": "Terminal setup",
167
+ "notice": "Update an existing setup with Enable in terminal, then open a new terminal. Interactive continuation requires Codex 0.166.0 or newer with the native remote transport. Only supported commands launched through ccdeck terminal selection are covered; explicit CODEX_HOME pins, independent sessions and incompatible profile settings require manual handling."
168
+ },
169
+ {
170
+ "title": "Help us improve Codex support",
171
+ "body": "We are continuing to improve Codex support, and feedback on switching, subagents and sharing is welcome through the Feedback button in ccdeck."
172
+ }
135
173
  ],
136
174
  "3.53.2": [
137
175
  {
@@ -0,0 +1,87 @@
1
+ // Provider-independent selection and continuation. Claude deliberately keeps its
2
+ // existing cswap path; only an explicitly supplied adapter can run this engine.
3
+ export function chooseEngineAccount(rows, quotas, { threshold = 90, next = 'room', heldOut = [], exclude = [], nowSec = Date.now() / 1000 } = {}) {
4
+ const excluded = new Set([...heldOut, ...exclude]);
5
+ const fits = rows.flatMap(row => {
6
+ if (excluded.has(row.id) || excluded.has(row.sameAccountAs) || row.available === false
7
+ || !(row.signedIn ?? row.signedInFilePresent)) return [];
8
+ const q = quotas.get(row.id);
9
+ if (!q?.ok || q.stale || Number.isFinite(q.fetchedAt) && nowSec * 1000 - q.fetchedAt > 15 * 60_000) return [];
10
+ const windows = (q.windows ?? []).filter(w => Number.isFinite(w.usedPercent) && w.usedPercent >= 0 && (w.resetAt == null || w.resetAt > nowSec));
11
+ // An empty or expired reading is unknown, never unlimited room.
12
+ if (!windows.length) return [];
13
+ const load = Math.max(...windows.map(w => w.usedPercent));
14
+ if (load >= threshold) return [];
15
+ const weekly = windows.find(w => w.seconds >= 6 * 86400 && w.resetAt != null && w.resetAt - nowSec <= 4 * 86400);
16
+ return [{ id: row.id, load, reset: weekly?.resetAt ?? null }];
17
+ });
18
+ const soon = next === 'weekly' ? fits.filter(f => f.reset !== null) : [];
19
+ return (soon.length ? soon.sort((a, b) => a.reset - b.reset || a.load - b.load) : fits.sort((a, b) => a.load - b.load))[0] ?? null;
20
+ }
21
+
22
+ /** Every retry starts only after the adapter has observed the previous process
23
+ * exit and a terminal usage-limit failure. No retry of a partial/unknown result,
24
+ * no `--last`, no global account change, no repeated account in the same run. */
25
+ export async function runAccountEngine(adapter, initial, { signal, onSwitch = () => {} } = {}) {
26
+ const tried = new Set();
27
+ let current = initial;
28
+ let threadId = initial.threadId ?? null;
29
+ for (let attempt = 0; attempt < 32; attempt++) {
30
+ if (signal?.aborted) return { code: 130, reason: 'cancelled' };
31
+ tried.add(current.id);
32
+ const result = await adapter.run(current, { signal });
33
+ if (signal?.aborted) return { ...result, reason: 'cancelled' };
34
+ const manual = result.reason === 'manual_switch';
35
+ if ((!manual && result.reason !== 'usage_limit') || !result.threadId || result.code === 0) return result;
36
+ if (!manual && threadId && threadId !== result.threadId) return { ...result, reason: 'thread_changed' };
37
+ threadId = result.threadId;
38
+ const settings = await adapter.settings();
39
+ if (!manual && !settings.enabled) return { ...result, reason: 'disabled' };
40
+ const rows = await adapter.accounts();
41
+ const source = rows.find(row => row.id === current.id);
42
+ if (!source) return { ...result, reason: 'source_unavailable' };
43
+ let pick;
44
+ if (manual) {
45
+ const target = rows.find(row => row.id === result.targetId && row.id !== current.id && row.available !== false && (row.signedIn ?? row.signedInFilePresent));
46
+ if (!target) return { ...result, reason: 'target_unavailable' };
47
+ pick = { id: target.id };
48
+ } else {
49
+ const exclude = [...tried];
50
+ for (const row of rows) if (row.sameAccountAs === current.id || source.sameAccountAs === row.id
51
+ || source.sameAccountAs && row.sameAccountAs === source.sameAccountAs) exclude.push(row.id);
52
+ const quotas = new Map();
53
+ for (const row of rows) {
54
+ if (signal?.aborted) return { ...result, reason: 'cancelled' };
55
+ if (!exclude.includes(row.id) && !settings.heldOut?.includes(row.id)) {
56
+ try { quotas.set(row.id, await adapter.quota(row.id)); } catch { /* unavailable is not room */ }
57
+ }
58
+ }
59
+ pick = chooseEngineAccount(rows, quotas, { ...settings, exclude });
60
+ if (!pick) return { ...result, reason: 'no_account_with_room' };
61
+ const latest = await adapter.settings();
62
+ if (!latest.enabled || signal?.aborted) return { ...result, reason: 'cancelled' };
63
+ if (!chooseEngineAccount(rows.filter(row => row.id === pick.id), quotas, { ...latest, exclude })) return { ...result, reason: 'settings_changed' };
64
+ }
65
+ // Do not move a stopped rollout into an account we cannot launch.
66
+ if (!manual && attempt === 31) return { ...result, reason: 'attempt_limit' };
67
+ let next;
68
+ try { next = await adapter.prepare({ from: current, id: pick.id, threadId }); }
69
+ catch { return { ...result, reason: 'handoff_failed' }; }
70
+ const abandon = async reason => {
71
+ try { await next.restoreSource?.(); }
72
+ catch { return { ...result, reason: 'handoff_failed' }; }
73
+ return { ...result, reason };
74
+ };
75
+ if (signal?.aborted) return abandon('cancelled');
76
+ let beforeLaunch;
77
+ try { beforeLaunch = await adapter.settings(); }
78
+ catch { return abandon('handoff_failed'); }
79
+ if (signal?.aborted) return abandon('cancelled');
80
+ if (!manual && (!beforeLaunch.enabled || beforeLaunch.heldOut?.includes(next.id))) return abandon('disabled');
81
+ try { onSwitch({ from: current.id, to: next.id, threadId }); }
82
+ catch { return abandon('handoff_failed'); }
83
+ if (manual) { tried.clear(); attempt = -1; }
84
+ current = next;
85
+ }
86
+ return { code: 1, reason: 'attempt_limit', threadId };
87
+ }
@@ -43,7 +43,30 @@ export async function handleCodexProfiles(_req, res) {
43
43
  const { discoverCodexProfiles } = await import('./codex-profiles.mjs');
44
44
  const { readCodexSelection } = await import('./codex-selection.mjs');
45
45
  const selection = await readCodexSelection();
46
- send(res, 200, { profiles: await discoverCodexProfiles({ selection, enableNative: true }), revision: selection.revision });
46
+ const { codexLiveAccountStatus } = await import('./codex-live-engine.mjs');
47
+ send(res, 200, { profiles: await discoverCodexProfiles({ selection, enableNative: true }), revision: selection.revision, live: codexLiveAccountStatus() });
48
+ }
49
+
50
+ /** Manual credential transfer is POST-only and behind the global mutation
51
+ * gate. All failures are fixed codes: no auth, blob, native stderr or paths
52
+ * can reach the generic request logger/reporting path. */
53
+ export async function handleCodexAccountShare(req, res, action) {
54
+ try {
55
+ const { createCodexShare, importCodexShare, CODEX_SHARE_MAX_LENGTH } = await import('./codex-share.mjs');
56
+ const raw = await readBody(req, res, CODEX_SHARE_MAX_LENGTH + 4096).catch(() => null);
57
+ let body;
58
+ try { body = JSON.parse(raw ?? ''); } catch { return send(res, 400, { ok: false, reason: 'bad_request' }); }
59
+ const allowed = action === 'export' ? ['ids'] : ['blob', 'expectedRevision'];
60
+ if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(key => !allowed.includes(key))) {
61
+ return send(res, 400, { ok: false, reason: 'bad_request' });
62
+ }
63
+ const result = await (action === 'export' ? createCodexShare(body) : importCodexShare(body));
64
+ send(res, 200, result);
65
+ } catch (error) {
66
+ const safe = new Set(['invalid_profiles', 'unknown_profile', 'file_auth_required', 'unsupported_auth', 'share_too_large', 'invalid_share', 'invalid_revision', 'selection_conflict', 'selection_busy', 'registry_corrupt', 'registry_write_failed', 'profile_unavailable', 'import_write_failed', 'windows_permissions_failed']);
67
+ const reason = safe.has(error?.code) ? error.code : 'share_failed';
68
+ send(res, ['selection_conflict', 'selection_busy'].includes(reason) ? 409 : reason === 'unknown_profile' ? 404 : 400, { ok: false, reason });
69
+ }
47
70
  }
48
71
 
49
72
  export async function handleCodexProfileMutation(req, res, action) {
@@ -57,13 +80,18 @@ export async function handleCodexProfileMutation(req, res, action) {
57
80
  // that is about to be moved away: stop it first, so nothing lands there.
58
81
  if (action === 'remove' && typeof body.id === 'string') (await import('./codex-login.mjs')).cancelCodexLogin(body.id);
59
82
  try {
60
- const result = action === 'select' ? await selectCodexProfile(body)
83
+ const result = action === 'select' ? await selectCodexProfile({ ...body, switchRunning: true })
61
84
  : action === 'remove' ? await removeCodexProfile(body)
62
85
  : action === 'replace' ? await replaceCodexLogin(body)
63
86
  : action === 'rename' ? await renameCodexProfile(body) : await addCodexProfile(body);
87
+ let live;
88
+ if (action === 'select') {
89
+ try { live = await (await import('./codex-live-engine.mjs')).requestCodexLiveAccount(result.runningSelection); }
90
+ catch { live = { state: 'failed', reason: 'live_switch_failed', profileId: null }; }
91
+ }
64
92
  // Registry paths are local implementation details; only explicit command
65
93
  // requests below return a home as part of a copyable terminal command.
66
- send(res, 200, { ok: true, id: result.id ?? result.profileId, revision: result.revision, status: result.status });
94
+ send(res, 200, { ok: true, id: result.id ?? result.profileId, revision: result.revision, status: result.status, ...(live ? { live } : {}) });
67
95
  } catch (error) {
68
96
  const reason = error?.code ?? 'operation_failed';
69
97
  const conflicts = ['selection_conflict', 'operation_conflict', 'selection_busy'];
@@ -1,7 +1,7 @@
1
1
  // Auto-switch for Codex accounts: when the account new sessions start on is
2
2
  // nearly full, move the default to another account that still has room.
3
- // Running sessions keep the account they started on; only the registry's
4
- // default moves, through the same selectCodexProfile the panel uses.
3
+ // This loop moves only the registry's default, through selectCodexProfile.
4
+ // Managed exec continuation is a separate adapter of the shared account engine.
5
5
  import { readFile, mkdir, unlink } from 'node:fs/promises';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { dirname, join, resolve } from 'node:path';
@@ -9,6 +9,7 @@ import { deckDataDir } from './deck-home.mjs';
9
9
  import { createTemp, renameWithRetry } from './atomic-write.mjs';
10
10
  import { readCodexSelection, selectCodexProfile } from './codex-selection.mjs';
11
11
  import { discoverCodexProfiles, readCodexProfileQuota } from './codex-profiles.mjs';
12
+ import { chooseEngineAccount } from './account-engine.mjs';
12
13
 
13
14
  // The same whole-percent range the page offers (CUSTOM_MIN / CUSTOM_MAX in
14
15
  // src/web/auto-switch-threshold.ts). A server module must not import from the
@@ -18,7 +19,6 @@ const THRESHOLD_MAX = 99;
18
19
  const DEFAULT_THRESHOLD = '90';
19
20
  const COOLDOWN_MS = 5 * 60_000;
20
21
  const TICK_MS = 60_000;
21
- const DAY = 86_400;
22
22
  const idPattern = /^[a-f0-9]{20}$/;
23
23
 
24
24
  const storeDir = o => resolve(o.store ?? deckDataDir());
@@ -117,12 +117,6 @@ const liveWindows = (quota, nowSec) =>
117
117
  (quota?.windows ?? []).filter(w => Number.isFinite(w.usedPercent) && (w.resetAt == null || w.resetAt > nowSec));
118
118
  const loadOf = live => (live.length ? Math.max(...live.map(w => w.usedPercent)) : null);
119
119
 
120
- // When the weekly window resets, if it does within 4 days; otherwise null.
121
- function weeklyReset(live, nowSec) {
122
- const w = live.find(x => x.seconds >= 6 * DAY && x.resetAt != null && x.resetAt - nowSec <= 4 * DAY);
123
- return w ? w.resetAt : null;
124
- }
125
-
126
120
  const hasLogin = row => (row.signedIn === undefined ? row.signedInFilePresent === true : row.signedIn === true);
127
121
 
128
122
  export async function codexAutoTick(options = {}) {
@@ -154,20 +148,15 @@ export async function codexAutoTick(options = {}) {
154
148
  // A row that is the same ChatGPT account shares the quota that just ran out.
155
149
  const roster = rows.filter(r => r.id !== home.id && r.available && hasLogin(r)
156
150
  && !state.heldOut.includes(r.id) && r.sameAccountAs !== home.id);
157
- const fits = [];
151
+ const quotas = new Map();
158
152
  for (const row of roster) { // one at a time: each read may spawn a process
159
- const quota = await readQuota(row.id, readOpts);
160
- if (!quota?.ok || quota.stale) continue;
161
- const live = liveWindows(quota, nowSec);
162
- const load = loadOf(live) ?? 0;
163
- if (load < threshold) fits.push({ id: row.id, load, reset: weeklyReset(live, nowSec) });
153
+ quotas.set(row.id, await readQuota(row.id, readOpts));
164
154
  }
165
- if (!fits.length) {
155
+ const pick = chooseEngineAccount(roster, quotas, { threshold, next: state.next, nowSec });
156
+ if (!pick) {
166
157
  m.lastTick = { at: now(), event: 'nowhere', reason: 'no_account_with_room' };
167
158
  return;
168
159
  }
169
- const soon = state.next === 'weekly' ? fits.filter(f => f.reset !== null) : [];
170
- const pick = soon.length ? soon.sort((a, b) => a.reset - b.reset)[0] : fits.sort((a, b) => a.load - b.load)[0];
171
160
  try {
172
161
  await select({ id: pick.id, expectedRevision: selection.revision, operationId: randomUUID() }, options);
173
162
  } catch (e) {
@@ -0,0 +1,272 @@
1
+ import { renameWithRetry } from './atomic-write.mjs';
2
+ // Codex adapter for supervised exec sessions. Authentication remains in each
3
+ // Codex home; a handoff transfers only the exact, closed conversation rollout.
4
+ import { randomUUID } from 'node:crypto';
5
+ import { spawn } from 'node:child_process';
6
+ import { StringDecoder } from 'node:string_decoder';
7
+ import { chmod, link, lstat, mkdir, open, readdir, realpath, readFile, unlink } from 'node:fs/promises';
8
+ import { constants } from 'node:fs';
9
+ import { dirname, join, relative } from 'node:path';
10
+ import { spawnSpec } from './exec-spec.mjs';
11
+ import { configHash, isTrustOnlyConfig, isCustomCodexConfig } from './codex-engine-config.mjs';
12
+ import { codexHandoffPath } from './codex-handoff.mjs';
13
+ import { killTree } from './exec-children.mjs';
14
+ import { readCodexSelection } from './codex-selection.mjs';
15
+ import { discoverCodexProfiles, readCodexProfileQuota } from './codex-profiles.mjs';
16
+ import { readCodexAuto } from './codex-auto.mjs';
17
+
18
+ const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
19
+ const CONTINUE = 'Continue the previous task from where it stopped. Check the existing work before repeating any action.';
20
+ const MAX_LINE = 1024 * 1024;
21
+
22
+ // Only a conservative, understood argv shape may be reconstructed on resume.
23
+ // Unknown options still reach Codex unchanged, but cannot authorize a handoff.
24
+ const values = new Set(['-c', '--config', '--enable', '--disable', '-m', '--model', '-s', '--sandbox', '-a', '--ask-for-approval', '-C', '--cd', '--add-dir', '--output-schema', '-o', '--output-last-message', '--color']);
25
+ const switches = new Set(['--json', '--strict-config', '--skip-git-repo-check', '--ignore-user-config', '--ignore-rules', '--approve-for-me', '--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust', '--search']);
26
+ export function codexEngineInvocation(args) {
27
+ const kept = [];
28
+ let exec = false, resume = false, threadId = null, prompt = false;
29
+ for (let i = 0; i < args.length; i++) {
30
+ const a = args[i];
31
+ if (prompt) return null; // extra positional arguments/attachments need their own contract
32
+ if (a === 'exec' && !exec) { exec = true; kept.push(a); continue; }
33
+ if (a === 'resume' && exec && !resume) { resume = true; continue; }
34
+ if (a === '--') {
35
+ if (!exec || i !== args.length - 2) return null;
36
+ prompt = true; i++; continue;
37
+ }
38
+ const key = a.split('=')[0];
39
+ if (values.has(key)) {
40
+ kept.push(a);
41
+ if (a === key) { if (i + 1 >= args.length) return null; kept.push(args[++i]); }
42
+ // Do not route a non-OpenAI provider or remote/configured proxy implicitly.
43
+ if ((key === '-c' || key === '--config') && /^(?:model_provider|model_providers\.|chatgpt_base_url|openai_base_url)/.test(kept[kept.length - 1].replace(/^--config=/, ''))) return null;
44
+ continue;
45
+ }
46
+ if (switches.has(a)) { kept.push(a); continue; }
47
+ if (a.startsWith('-') && a !== '-') return null;
48
+ if (!exec) return null;
49
+ if (resume && !threadId) { if (!UUID.test(a)) return null; threadId = a; }
50
+ else prompt = true;
51
+ }
52
+ if (!exec || !kept.includes('--json')) return null;
53
+ return { threadId, resumeArgs: id => [...kept, 'resume', id, '--', CONTINUE] };
54
+ }
55
+
56
+ export function runCodexEngineAttempt(executable, args, home, { signal, stdout = process.stdout, stderr = process.stderr, spawnChild = spawn, resumed = false, env = process.env } = {}) {
57
+ if (signal?.aborted) return Promise.resolve({ code: 130, reason: 'cancelled' });
58
+ return new Promise((resolveRun, reject) => {
59
+ const spec = spawnSpec(executable, args);
60
+ const child = spawnChild(spec.file, spec.args, { ...spec.opts, stdio: [resumed ? 'ignore' : 'inherit', 'pipe', 'pipe'], env: { ...env, CODEX_HOME: home } });
61
+ let pending = '', threadId = null, failed = null, completed = false, uncertain = false;
62
+ const decoder = new StringDecoder('utf8');
63
+ function line(text) {
64
+ if (!text.trim()) return;
65
+ let event;
66
+ try { event = JSON.parse(text); } catch { uncertain = true; return; }
67
+ if (event.type === 'thread.started') {
68
+ if (!UUID.test(event.thread_id ?? '') || threadId && threadId !== event.thread_id) uncertain = true;
69
+ else threadId = event.thread_id;
70
+ }
71
+ if (event.type === 'turn.completed') completed = true;
72
+ if (event.type === 'turn.failed') failed = event.error;
73
+ }
74
+ const pump = (source, target, inspect = false) => {
75
+ source.on('data', chunk => {
76
+ if (!target.write(chunk)) { source.pause(); target.once('drain', () => source.resume()); }
77
+ if (!inspect) return;
78
+ pending += decoder.write(chunk);
79
+ let end;
80
+ while ((end = pending.indexOf('\n')) >= 0) { line(pending.slice(0, end)); pending = pending.slice(end + 1); }
81
+ if (pending.length > MAX_LINE) { pending = ''; uncertain = true; }
82
+ });
83
+ };
84
+ pump(child.stdout, stdout, true);
85
+ pump(child.stderr, stderr);
86
+ let escalation;
87
+ const stop = () => {
88
+ killTree(child, 'SIGTERM');
89
+ escalation ??= setTimeout(() => killTree(child, 'SIGKILL'), 2000);
90
+ escalation.unref?.();
91
+ };
92
+ signal?.addEventListener('abort', stop, { once: true });
93
+ child.once('error', error => { clearTimeout(escalation); signal?.removeEventListener('abort', stop); reject(error); });
94
+ child.once('close', (code, killedBy) => {
95
+ clearTimeout(escalation);
96
+ signal?.removeEventListener('abort', stop);
97
+ pending += decoder.end();
98
+ if (pending) line(pending);
99
+ const message = typeof failed?.message === 'string' ? failed.message : '';
100
+ const quota = /(?:usage limit|quota (?:exceeded|exhausted)|exceeded your current quota|insufficient_quota|usage_limit_reached)/i.test(message);
101
+ resolveRun({ code: code ?? (killedBy === 'SIGINT' ? 130 : 143), threadId,
102
+ reason: signal?.aborted || killedBy ? 'cancelled' : uncertain ? 'protocol_error' : completed ? 'completed' : failed && quota ? 'usage_limit' : 'failed' });
103
+ });
104
+ });
105
+ }
106
+
107
+ export async function transferCodexThread(sourceHome, targetHome, threadId, { moveSource = false, onSourceMoved } = {}) {
108
+ if (!UUID.test(threadId)) throw new Error('Invalid Codex conversation id.');
109
+ const root = join(sourceHome, 'sessions');
110
+ let found = null, visited = 0;
111
+ // Bounded and layout-specific; never walk arbitrary/symlinked directories.
112
+ async function walk(dir, depth) {
113
+ if (++visited > 4096) throw new Error('Codex conversation scan exceeded its limit.');
114
+ let entries;
115
+ try { entries = await readdir(dir, { withFileTypes: true }); } catch (e) { if (e.code === 'ENOENT') return; throw e; }
116
+ for (const entry of entries) {
117
+ const path = join(dir, entry.name);
118
+ if (depth < 3 && entry.isDirectory() && /^\d{2,4}$/.test(entry.name)) await walk(path, depth + 1);
119
+ else if (depth === 3 && entry.isFile() && entry.name.endsWith(`-${threadId}.jsonl`)) {
120
+ if (found) throw new Error('Codex conversation has more than one rollout.');
121
+ found = path;
122
+ }
123
+ }
124
+ }
125
+ if ((await lstat(root)).isSymbolicLink()) throw new Error('Codex conversation folder must not be a symbolic link.');
126
+ await walk(root, 0);
127
+ if (!found) throw new Error('Codex conversation could not be found; nothing was resumed.');
128
+ const handle = await open(found, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
129
+ let snapshot, content;
130
+ try {
131
+ snapshot = await handle.stat();
132
+ if (snapshot.size > 64 * 1024 * 1024) throw new Error('Codex conversation is too large to transfer automatically.');
133
+ const header = Buffer.alloc(64 * 1024);
134
+ const { bytesRead } = await handle.read(header, 0, header.length, 0);
135
+ const first = header.subarray(0, bytesRead).toString('utf8').split('\n')[0];
136
+ const meta = JSON.parse(first);
137
+ if (meta.type !== 'session_meta' || meta.payload?.id !== threadId) throw new Error('Codex conversation identity did not match.');
138
+ content = Buffer.alloc(snapshot.size);
139
+ for (let offset = 0; offset < content.length;) {
140
+ const { bytesRead } = await handle.read(content, offset, content.length - offset, offset);
141
+ if (!bytesRead) throw new Error('Codex conversation was truncated while being transferred.');
142
+ offset += bytesRead;
143
+ }
144
+ } finally { await handle.close(); }
145
+ const targetRoot = join(targetHome, 'sessions');
146
+ await mkdir(targetRoot, { recursive: true, mode: 0o700 });
147
+ if ((await lstat(targetRoot)).isSymbolicLink()) throw new Error('Target conversation folder must not be a symbolic link.');
148
+ const destination = join(targetRoot, relative(root, found));
149
+ let parent = targetRoot;
150
+ for (const part of relative(targetRoot, dirname(destination)).split(/[\\/]/)) {
151
+ parent = join(parent, part);
152
+ await mkdir(parent, { mode: 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
153
+ if (!(await lstat(parent)).isDirectory()) throw new Error('Target conversation path is unavailable.');
154
+ }
155
+ if (content.length !== snapshot.size || content.at(-1) !== 10) throw new Error('Codex conversation has an incomplete final record.');
156
+ // Publish the complete private file atomically and exclusively. The sidecar
157
+ // exists before publication, so a live deck never replays the copied prefix.
158
+ try { await lstat(destination); throw new Error('Target conversation already exists.'); }
159
+ catch (e) { if (e.code !== 'ENOENT') throw e; }
160
+ const marker = codexHandoffPath(destination);
161
+ const receipt = await open(marker, 'wx', 0o600);
162
+ try { await receipt.writeFile(JSON.stringify({ version: 1, threadId, copiedBytes: content.length })); }
163
+ catch (e) { await unlink(marker).catch(() => {}); throw e; }
164
+ finally { await receipt.close(); }
165
+ const staged = `${destination}.${randomUUID()}.tmp`;
166
+ let published = false;
167
+ try {
168
+ const output = await open(staged, 'wx', 0o600);
169
+ try { await output.writeFile(content); await output.sync(); }
170
+ finally { await output.close(); }
171
+ const after = await lstat(found);
172
+ if (after.size !== snapshot.size || after.mtimeMs !== snapshot.mtimeMs || after.ino !== snapshot.ino) throw new Error('Codex conversation changed while being transferred.');
173
+ await link(staged, destination);
174
+ published = true;
175
+ } finally {
176
+ await unlink(staged).catch(() => {});
177
+ if (!published) await unlink(marker).catch(() => {});
178
+ }
179
+ if (moveSource) {
180
+ const backup = `${found}.ccdeck-moved-${randomUUID()}`;
181
+ try {
182
+ await renameWithRetry(found, backup);
183
+ await chmod(backup, 0o600);
184
+ // A returning rollout publishes a fresh prefix receipt. Keep the old
185
+ // one beside its backup rather than blocking a later round trip.
186
+ await renameWithRetry(codexHandoffPath(found), codexHandoffPath(backup)).catch(e => { if (e.code !== 'ENOENT') throw e; });
187
+ }
188
+ catch (error) {
189
+ await renameWithRetry(backup, found).catch(() => {});
190
+ await unlink(destination).catch(() => {}); await unlink(marker).catch(() => {}); throw error;
191
+ }
192
+ let restored = false;
193
+ onSourceMoved?.(async () => {
194
+ if (restored) return;
195
+ const saved = await lstat(backup);
196
+ if (!saved.isFile() || saved.ino !== snapshot.ino || saved.size !== snapshot.size
197
+ || saved.mtimeMs !== snapshot.mtimeMs) throw new Error('Codex source backup changed; restore manually.');
198
+ // Exclusive hard links restore the exact stopped rollout without ever
199
+ // overwriting work created in the source home after preparation.
200
+ try { await link(codexHandoffPath(backup), codexHandoffPath(found)); }
201
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
202
+ await link(backup, found);
203
+ restored = true;
204
+ });
205
+ }
206
+ return destination;
207
+ }
208
+
209
+ export function createCodexEngineAdapter(file, executable, args, home, options = {}) {
210
+ const invocation = codexEngineInvocation(args);
211
+ if (!invocation) return null;
212
+ const settingsOptions = { store: dirname(file), ...options };
213
+ let selection;
214
+ const leases = new Map();
215
+ return {
216
+ async close() {
217
+ for (const lease of leases.values()) {
218
+ try {
219
+ const owner = JSON.parse(await readFile(lease.path, 'utf8'));
220
+ if (owner.pid === process.pid && owner.nonce === lease.nonce) await unlink(lease.path);
221
+ } catch { /* never remove a replacement lease */ }
222
+ }
223
+ leases.clear();
224
+ },
225
+ invocation,
226
+ async settings() {
227
+ const s = await readCodexAuto(settingsOptions);
228
+ const config = await readFile(join(home, 'config.toml'), 'utf8').catch(e => { if (e.code === 'ENOENT') return ''; throw e; });
229
+ // A custom provider/profile can use a different authentication lifecycle.
230
+ // Its process remains untouched instead of rotating ChatGPT accounts.
231
+ const custom = isCustomCodexConfig(config);
232
+ return { enabled: s.enabled && !custom, custom, threshold: Number(s.settings['autoswitch.threshold'].value), next: s.choice.next, heldOut: s.heldOut };
233
+ },
234
+ async accounts() {
235
+ selection = await readCodexSelection(settingsOptions);
236
+ return discoverCodexProfiles({ ...settingsOptions, selection, enableNative: true });
237
+ },
238
+ quota(id) { return readCodexProfileQuota(id, { ...settingsOptions, selection, enableNative: true }); },
239
+ run(current, context) { return runCodexEngineAttempt(executable, current.args, current.home, { ...options, ...context, resumed: current.resumed }); },
240
+ async prepare({ from, id, threadId, sessionConfig }) {
241
+ // Per-account configuration can select a different provider, MCP servers,
242
+ // or permissions. Never transfer work into a different configuration.
243
+ const config = async home => readFile(join(home, 'config.toml'), 'utf8').catch(e => { if (e.code === 'ENOENT') return ''; throw e; });
244
+ const latest = await readCodexSelection(settingsOptions);
245
+ const target = latest.profiles.find(p => p.id === id && p.available);
246
+ const source = latest.profiles.find(p => p.id === from.id && p.available);
247
+ if (!target || !source || await realpath(source.home) !== await realpath(from.home)) throw new Error('Codex accounts changed before continuation.');
248
+ // One owner for this conversation across every target account. A stale
249
+ // lease after a crash is refused rather than guessing about a live run.
250
+ if (!leases.has(threadId)) {
251
+ const locks = join(dirname(file), 'codex-engine-locks');
252
+ await mkdir(locks, { recursive: true, mode: 0o700 });
253
+ if (!(await lstat(locks)).isDirectory()) throw new Error('Codex continuation lock folder is unavailable.');
254
+ const lock = join(locks, `${threadId}.lock`);
255
+ const handle = await open(lock, 'wx', 0o600);
256
+ const nonce = randomUUID();
257
+ try { await handle.writeFile(JSON.stringify({ pid: process.pid, nonce })); }
258
+ catch (e) { await unlink(lock).catch(() => {}); throw e; }
259
+ finally { await handle.close(); }
260
+ leases.set(threadId, { path: lock, nonce });
261
+ }
262
+ const sourceConfig = await config(from.home), targetConfig = await config(target.home);
263
+ if (sourceConfig !== targetConfig && (!sessionConfig || sessionConfig.sourceHash !== configHash(sourceConfig)
264
+ || !isTrustOnlyConfig(targetConfig) && configHash(targetConfig) !== sessionConfig.originHash)) throw new Error('Codex account configurations differ; resume manually.');
265
+ let restoreSource;
266
+ await transferCodexThread(from.home, target.home, threadId, { moveSource: options.moveConversation === true,
267
+ onSourceMoved: restore => { restoreSource = restore; } });
268
+ return { id, home: target.home, args: invocation.resumeArgs(threadId), resumed: true, threadId,
269
+ ...(restoreSource ? { restoreSource } : {}) };
270
+ },
271
+ };
272
+ }