ccdeck 3.53.3 → 3.81.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 (78) hide show
  1. package/README.md +63 -7
  2. package/THIRD_PARTY_NOTICES.md +31 -1
  3. package/bin/cli/tui.js +433 -11
  4. package/dist/web/assets/{BrowserWatchModal-CJ0CW4Go.js → BrowserWatchModal-DKvBSlGT.js} +1 -1
  5. package/dist/web/assets/{IntegrationModal-DlJzBN8b.js → IntegrationModal-D3NLczRe.js} +1 -1
  6. package/dist/web/assets/{RadioPanel-CHl3s3OH.js → RadioPanel-dCIMGTd9.js} +1 -1
  7. package/dist/web/assets/{TrafficRadar-Cw3i0Hux.js → TrafficRadar-CMbwnKe7.js} +1 -1
  8. package/dist/web/assets/{UsageHistoryModal-CiB5-CTH.js → UsageHistoryModal-DkGBQaM4.js} +1 -1
  9. package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
  10. package/dist/web/assets/{app-2vj7uk2U.js → app-l0spNrc0.js} +93 -93
  11. package/dist/web/assets/{index-D1YZbdq3.js → index-inV7HzhI.js} +1 -1
  12. package/dist/web/index.html +3 -3
  13. package/node_modules/ws/LICENSE +20 -0
  14. package/node_modules/ws/README.md +540 -0
  15. package/node_modules/ws/browser.js +8 -0
  16. package/node_modules/ws/index.js +22 -0
  17. package/node_modules/ws/lib/buffer-util.js +142 -0
  18. package/node_modules/ws/lib/constants.js +19 -0
  19. package/node_modules/ws/lib/event-target.js +292 -0
  20. package/node_modules/ws/lib/extension.js +203 -0
  21. package/node_modules/ws/lib/limiter.js +55 -0
  22. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  23. package/node_modules/ws/lib/receiver.js +743 -0
  24. package/node_modules/ws/lib/sender.js +610 -0
  25. package/node_modules/ws/lib/stream.js +161 -0
  26. package/node_modules/ws/lib/subprotocol.js +62 -0
  27. package/node_modules/ws/lib/validation.js +152 -0
  28. package/node_modules/ws/lib/websocket-server.js +562 -0
  29. package/node_modules/ws/lib/websocket.js +1426 -0
  30. package/node_modules/ws/package.json +74 -0
  31. package/node_modules/ws/wrapper.mjs +21 -0
  32. package/package.json +5 -3
  33. package/release-notes.json +71 -0
  34. package/src/server/account-engine.mjs +87 -0
  35. package/src/server/account-notify.mjs +81 -16
  36. package/src/server/account-routes.mjs +49 -3
  37. package/src/server/account-watch.mjs +21 -0
  38. package/src/server/codex-auto.mjs +163 -54
  39. package/src/server/codex-engine-adapter.mjs +272 -0
  40. package/src/server/codex-engine-bridge.mjs +47 -0
  41. package/src/server/codex-engine-config.mjs +42 -0
  42. package/src/server/codex-engine-rpc.mjs +88 -0
  43. package/src/server/codex-handoff.mjs +20 -0
  44. package/src/server/codex-interactive-engine.mjs +335 -0
  45. package/src/server/codex-lan-identity.mjs +61 -0
  46. package/src/server/codex-live-checkpoint.mjs +55 -0
  47. package/src/server/codex-live-credentials.mjs +214 -0
  48. package/src/server/codex-live-engine.mjs +577 -0
  49. package/src/server/codex-live-handoff.mjs +300 -0
  50. package/src/server/codex-live-lease.mjs +64 -0
  51. package/src/server/codex-live-rpc.mjs +158 -0
  52. package/src/server/codex-profiles.mjs +34 -4
  53. package/src/server/codex-projects.mjs +308 -0
  54. package/src/server/codex-quota.mjs +36 -2
  55. package/src/server/codex-selection.mjs +78 -9
  56. package/src/server/codex-share.mjs +238 -0
  57. package/src/server/codex-terminal-runner.mjs +38 -1
  58. package/src/server/codex-terminal.mjs +15 -3
  59. package/src/server/codex-usage.mjs +69 -0
  60. package/src/server/codex-watch.mjs +3 -1
  61. package/src/server/codex-windows-private.mjs +96 -0
  62. package/src/server/codex-windows-private.ps1 +140 -0
  63. package/src/server/codex-windows-proxy.mjs +53 -0
  64. package/src/server/index.mjs +12 -4
  65. package/src/server/lan-codex-store.mjs +170 -0
  66. package/src/server/lan-codex.mjs +103 -0
  67. package/src/server/lan-deck.mjs +5 -0
  68. package/src/server/lan-engine.mjs +34 -6
  69. package/src/server/lan-manifest.mjs +16 -2
  70. package/src/server/lan-serve.mjs +16 -6
  71. package/src/server/login-service.mjs +2 -0
  72. package/src/server/pinned-build.mjs +5 -0
  73. package/src/server/request-gates.mjs +3 -0
  74. package/src/server/tui-codex.mjs +229 -0
  75. package/src/server/tui-lan.mjs +684 -0
  76. package/src/server/tui-machine.mjs +492 -0
  77. package/src/server/tui-network.mjs +730 -0
  78. package/src/server/tui-view.mjs +735 -60
@@ -0,0 +1,53 @@
1
+ // Codex 0.166's Windows endpoint is AF_UNIX, not a named pipe. Its official
2
+ // app-server proxy relays raw bytes, including the WebSocket HTTP handshake.
3
+ import { Duplex } from 'node:stream';
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { win32 } from 'node:path';
6
+ import { spawnSpec } from './exec-spec.mjs';
7
+
8
+ const disconnected = () => Object.assign(new Error('native_disconnected'), { code: 'native_disconnected' });
9
+ export function createCodexWindowsProxy(endpoint, options = {}) {
10
+ const env = { ...(options.env ?? process.env), CODEX_HOME: endpoint.home };
11
+ for (const key of Object.keys(env)) if (/^(OPENAI_API_KEY|CODEX_API_KEY)$/i.test(key)) delete env[key];
12
+ const spec = spawnSpec(endpoint.executable, ['app-server', 'proxy', '--sock', endpoint.socketPath], options.platform ?? process.platform);
13
+ const child = (options.spawnChild ?? spawn)(spec.file, spec.args,
14
+ { ...spec.opts, env, windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'ignore'] });
15
+ let timer, stopped = false;
16
+ const stream = new Duplex({
17
+ read() { child.stdout.resume(); },
18
+ write(data, encoding, done) { child.stdin.write(data, encoding, error => done(error ? disconnected() : null)); },
19
+ final(done) { child.stdin.end(done); },
20
+ destroy(error, done) {
21
+ clearTimeout(timer);
22
+ if (!stopped) {
23
+ stopped = true;
24
+ if (child.exitCode === null && child.signalCode === null) {
25
+ if ((options.platform ?? process.platform) === 'win32' && child.pid) {
26
+ // npm's .cmd/JS wrapper may own a child proxy. Stop this process tree
27
+ // only; never call daemon stop or target an advertised daemon PID.
28
+ const taskkill = win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'taskkill.exe');
29
+ (options.execFile ?? execFile)(taskkill, ['/PID', String(child.pid), '/T', '/F'],
30
+ { timeout: 2000, windowsHide: true, shell: false, maxBuffer: 4096 }, () => {});
31
+ } else child.kill();
32
+ }
33
+ child.stdin.destroy(); child.stdout.destroy();
34
+ }
35
+ done(error);
36
+ },
37
+ });
38
+ // HTTP/ws accept a Duplex but expect the small net.Socket tuning interface.
39
+ stream.setNoDelay = stream.setKeepAlive = () => stream;
40
+ stream.setTimeout = (ms, callback) => {
41
+ clearTimeout(timer);
42
+ if (callback) stream.once('timeout', callback);
43
+ if (ms) timer = setTimeout(() => stream.emit('timeout'), ms);
44
+ return stream;
45
+ };
46
+ child.stdout.on('data', data => { if (!stream.push(data)) child.stdout.pause(); });
47
+ child.stdout.on('end', () => stream.push(null));
48
+ child.stdout.on('error', () => stream.destroy(disconnected()));
49
+ child.stdin.on('error', () => stream.destroy(disconnected()));
50
+ child.on('error', () => stream.destroy(disconnected()));
51
+ child.on('exit', () => stream.destroy(disconnected()));
52
+ return stream;
53
+ }
@@ -139,7 +139,7 @@ export { markDeckReady, releaseRestart } from "./lifecycle.mjs";
139
139
  import { prefsRead } from "./prefs-state.mjs";
140
140
  // Quota read for the account notifications while no page reads it — only while
141
141
  // one of their quota switches is on (account-watch.mjs).
142
- import { startAccountWatch } from "./account-watch.mjs";
142
+ import { startAccountWatch, noteCodexAutoTick } from "./account-watch.mjs";
143
143
  // This deck's LAN engine, what the settings may tell it, and the probe that
144
144
  // asks whether other decks can reach it — see lan-deck.mjs. startServer hands
145
145
  // it the prefs at boot; the settings route does after every write.
@@ -164,7 +164,7 @@ export { sendInternalError };
164
164
  // The accounts surface's routes — see account-routes.mjs. The boot wires the
165
165
  // stale-copy repair and starts auto-switch through the same module.
166
166
  import { handleStopContinue, handleStopContinueRead } from "./stop-continue.mjs";
167
- import { cswapAutoModule, getProjectRollup, handleAccountLoginState, handleAccountProjects, handleClaudeAccountAdmin, handleClaudeAccountSwitch, handleClaudeAccounts, handleCodexProfiles, handleCodexProfileQuota, handleCodexProfileLaunch, handleCodexProfileMutation, handleCodexProfileLogin, handleCodexProfileLoginFlow, handleCodexTerminalCommand, handleCodexAuto, handleCodexAutoAction, handleCswapAuto, handleCswapAutoAction, wireAccountOrigins, wireStaleCopyRepair } from "./account-routes.mjs";
167
+ import { cswapAutoModule, getProjectRollup, handleAccountLoginState, handleAccountProjects, handleClaudeAccountAdmin, handleClaudeAccountSwitch, handleClaudeAccounts, handleCodexProfiles, handleCodexAccountShare, handleCodexProfileQuota, handleCodexProfileProjects, handleCodexProfileLaunch, handleCodexProfileMutation, handleCodexProfileLogin, handleCodexProfileLoginFlow, handleCodexTerminalCommand, handleCodexAuto, handleCodexAutoAction, handleCswapAuto, handleCswapAutoAction, wireAccountOrigins, wireStaleCopyRepair } from "./account-routes.mjs";
168
168
  // Browser Watch's three routes — see browser-watch-routes.mjs.
169
169
  import { handleBrowserWatch, handleBrowserWatchDismiss, handleBrowserWatchSettings } from "./browser-watch-routes.mjs";
170
170
  // The music routes, every one behind AGENTS_DECK_NO_MUSIC — see music-routes.mjs.
@@ -404,9 +404,12 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
404
404
  if (req.method === "GET" && url.pathname === "/api/claude-accounts") return guard(handleClaudeAccounts(req, res), res);
405
405
  if (req.method === "GET" && url.pathname === "/api/codex-profiles") return guard(handleCodexProfiles(req, res), res);
406
406
  if (req.method === "GET" && url.pathname === "/api/codex-profile-quota") return guard(handleCodexProfileQuota(req, res), res);
407
+ if (req.method === "GET" && url.pathname === "/api/codex-profile-projects") return guard(handleCodexProfileProjects(req, res), res);
407
408
  if (req.method === "GET" && url.pathname === "/api/codex-profile-launch") return guard(handleCodexProfileLaunch(req, res), res);
408
409
  if (req.method === "GET" && url.pathname === "/api/codex-auto") return guard(handleCodexAuto(req, res), res);
409
410
  if (req.method === "POST" && url.pathname === "/api/codex-auto") return guard(handleCodexAutoAction(req, res), res);
411
+ if (req.method === "POST" && url.pathname === "/api/codex-accounts-share") return guard(handleCodexAccountShare(req, res, "export"), res);
412
+ if (req.method === "POST" && url.pathname === "/api/codex-accounts-import") return guard(handleCodexAccountShare(req, res, "import"), res);
410
413
  if (req.method === "POST" && url.pathname === "/api/codex-profile-select") return guard(handleCodexProfileMutation(req, res, "select"), res);
411
414
  if (req.method === "POST" && url.pathname === "/api/codex-profile-add") return guard(handleCodexProfileMutation(req, res, "add"), res);
412
415
  if (req.method === "POST" && url.pathname === "/api/codex-profile-remove") return guard(handleCodexProfileMutation(req, res, "remove"), res);
@@ -563,6 +566,10 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
563
566
  if (codex) {
564
567
  startCodexWatcher(workspace);
565
568
  server.once("close", stopCodexEnrichment);
569
+ const liveOptions = { env: { ...process.env } };
570
+ const liveAccounts = await import("./codex-live-engine.mjs");
571
+ liveAccounts.startCodexLiveAccounts(liveOptions);
572
+ server.once("close", () => { void liveAccounts.stopCodexLiveAccounts(liveOptions); });
566
573
  }
567
574
  if (claude) {
568
575
  const recovery = createClaudeRecovery({ workspace });
@@ -596,8 +603,9 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
596
603
  // caller with nothing to wait for.
597
604
  cswapAutoModule().then(m => m.initCswapAuto({ after: cswapQuiet })).catch(() => {});
598
605
  // Codex's Auto-switch, on the deck's own loop. A settings read a minute
599
- // unless somebody turned it on (codex-auto.mjs).
600
- import("./codex-auto.mjs").then(m => m.startCodexAutoLoop()).catch(() => {});
606
+ // unless somebody turned it on (codex-auto.mjs). Each tick tells the
607
+ // account notifications what it did, for the swap notice.
608
+ import("./codex-auto.mjs").then(m => m.startCodexAutoLoop({ onTick: noteCodexAutoTick })).catch(() => {});
601
609
  // The account notifications' own quota reads, for the providers this deck
602
610
  // watches. Idle — a check of two switches every couple of minutes — unless
603
611
  // the threshold or the reset notification is on.
@@ -0,0 +1,170 @@
1
+ // This deck's Codex accounts as Local network reads, gives and takes them — the
2
+ // store half of lan-codex.mjs's rules, as the claude-swap adapters in
3
+ // lan-deck.mjs are Claude's. The engine never opens a credential: it asks this
4
+ // for rows, for one login sealed as a share, and to place one that arrived.
5
+ //
6
+ // WHAT IS READ is each registered home's auth.json, for three things: who it is
7
+ // signed in as (the id_token's email), which workspace (the account id, hashed
8
+ // into the key), and a hash of the refresh token it holds now. No token leaves
9
+ // this file except inside the share `exportAccount` builds for a `want` the
10
+ // engine has already proved and checked, and nothing is ever refreshed here.
11
+ //
12
+ // WHAT IS KEPT is each profile's token history, as hashes, in
13
+ // codex-lan-lineage.json beside the Codex registry: the token it holds now and
14
+ // the ones it held before. That history is how a paired deck proves its copy
15
+ // of a login is dead (see codexSyncAction), and it outlives a restart because a
16
+ // renewal can happen while the deck is not running.
17
+ import { lstat, mkdir, readFile, unlink } from "node:fs/promises";
18
+ import { dirname, join } from "node:path";
19
+ import { createTemp, renameWithRetry } from "./atomic-write.mjs";
20
+ import { nextLineage } from "./lan-codex.mjs";
21
+ import { codexLoginOf } from "./codex-lan-identity.mjs";
22
+
23
+ export { codexLoginOf };
24
+
25
+ const AUTH_MAX_BYTES = 32_000;
26
+ const LINEAGE_MAX_BYTES = 256_000;
27
+
28
+ /** The login on file in one home, or null: no file, a file that is not a
29
+ * plain bounded one, or one that is not a ChatGPT login. */
30
+ export async function codexLoginOnFile(home) {
31
+ try {
32
+ const file = join(home, "auth.json");
33
+ const info = await lstat(file);
34
+ if (!info.isFile() || info.size > AUTH_MAX_BYTES) return null;
35
+ return codexLoginOf(JSON.parse(await readFile(file, "utf8")));
36
+ } catch { return null; }
37
+ }
38
+
39
+ /**
40
+ * The adapter the LAN engine takes as `codex`. `options` reaches the Codex
41
+ * registry and share modules (a store directory in the suite); `readSelection`,
42
+ * `share` and `settle` may replace those modules' functions there too.
43
+ */
44
+ export function createCodexLan(options = {}) {
45
+ const selectionModule = () => import("./codex-selection.mjs");
46
+ const shareModule = () => import("./codex-share.mjs");
47
+ const readSelection = async () => (options.readSelection ?? (await selectionModule()).readCodexSelection)(options);
48
+
49
+ let lineage = null;
50
+ let writing = Promise.resolve();
51
+ const lineageFile = async () => join(dirname((await selectionModule()).codexSelectionPath(options)), "codex-lan-lineage.json");
52
+ const loadLineage = async () => {
53
+ if (lineage) return lineage;
54
+ let kept = {};
55
+ try {
56
+ const file = await lineageFile();
57
+ if ((await lstat(file)).size <= LINEAGE_MAX_BYTES) {
58
+ const raw = JSON.parse(await readFile(file, "utf8"));
59
+ if (raw && typeof raw.profiles === "object" && raw.profiles && !Array.isArray(raw.profiles)) kept = raw.profiles;
60
+ }
61
+ } catch { /* none yet: every profile starts with no history */ }
62
+ lineage = lineage ?? { profiles: { ...kept } };
63
+ return lineage;
64
+ };
65
+ const saveLineage = () => {
66
+ const text = JSON.stringify(lineage) + "\n";
67
+ writing = writing.then(async () => {
68
+ const target = await lineageFile();
69
+ // The deck's data folder, which nothing may have made yet on a deck that
70
+ // never took a Codex lock.
71
+ await mkdir(dirname(target), { recursive: true, mode: 0o700 });
72
+ const { tmp, handle } = await createTemp(target, { mode: 0o600 });
73
+ try {
74
+ try { await handle.writeFile(text, "utf8"); await handle.sync(); }
75
+ finally { await handle.close(); }
76
+ await renameWithRetry(tmp, target);
77
+ } catch (err) { await unlink(tmp).catch(() => {}); throw err; }
78
+ }).catch(() => { /* kept in memory; the next change writes it again */ });
79
+ return writing;
80
+ };
81
+
82
+ return {
83
+ /** Every registered home signed in to a ChatGPT account, in the rules' shape:
84
+ * `num` is the profile id, `active` the one Codex runs on here. */
85
+ async readAccounts() {
86
+ const selection = await readSelection();
87
+ const kept = await loadLineage();
88
+ let changed = false;
89
+ const rows = [];
90
+ const seen = new Set();
91
+ for (const profile of selection.profiles ?? []) {
92
+ seen.add(profile.id);
93
+ if (!profile.available) continue;
94
+ const login = await codexLoginOnFile(profile.home);
95
+ const next = nextLineage(kept.profiles[profile.id], login?.rt ?? null);
96
+ if (next.changed) { kept.profiles[profile.id] = next.entry; changed = true; }
97
+ if (!login) continue;
98
+ rows.push({
99
+ key: login.key, email: login.email, alive: true, readable: true, unreadableWhy: "export failed",
100
+ num: profile.id, active: profile.id === selection.profileId, rt: login.rt, was: next.entry.was,
101
+ });
102
+ }
103
+ // A profile removed here takes its history with it.
104
+ for (const id of Object.keys(kept.profiles)) {
105
+ if (!seen.has(id)) { delete kept.profiles[id]; changed = true; }
106
+ }
107
+ if (changed) await saveLineage();
108
+ return rows;
109
+ },
110
+
111
+ /** One profile's login as a share holding exactly that login, or null. The
112
+ * share is read back before it goes, so a profile that changed accounts
113
+ * since the manifest never answers a `want` for the old one. */
114
+ async exportAccount(id, expectedKey) {
115
+ try {
116
+ const { createCodexShare, readCodexShare } = await shareModule();
117
+ const out = await (options.share ?? createCodexShare)({ ids: [id] }, options);
118
+ const entries = readCodexShare(out?.blob);
119
+ return entries.length === 1 && codexLoginOf(entries[0].auth)?.key === expectedKey ? out.blob : null;
120
+ } catch { return null; }
121
+ },
122
+
123
+ /**
124
+ * Place one login that arrived. An add registers a new profile, as Import
125
+ * does; a heal puts it in place of the dead copy `mine` names, and only
126
+ * while that copy is still the token the other deck renewed past.
127
+ *
128
+ * NARROWED TO THE ONE ACCOUNT ASKED FOR. The seal binds the envelope to the
129
+ * key that was requested, not its contents, and a share can carry twenty
130
+ * logins: one that is not exactly the asked-for account is refused whole.
131
+ */
132
+ async importAccount(blob, step, mine) {
133
+ const { importCodexShare, readCodexShare, replaceCodexLoginFromShare } = await shareModule();
134
+ let entries;
135
+ try { entries = readCodexShare(blob); } catch { return { ok: false, why: "import refused" }; }
136
+ if (entries.length !== 1 || codexLoginOf(entries[0].auth)?.key !== step?.key) return { ok: false, why: "import refused" };
137
+ if (step.action === "heal") {
138
+ if (!mine?.num || !mine.rt) return { ok: false, why: "import refused" };
139
+ try {
140
+ const { home } = await replaceCodexLoginFromShare({
141
+ blob, id: mine.num,
142
+ stillDead: auth => {
143
+ const here = codexLoginOf(auth);
144
+ return here?.key === step.key && here.rt === mine.rt;
145
+ },
146
+ }, options);
147
+ // The account did not change, its login did: keep a good reading's
148
+ // floor and drop a failed one, as a sign-in moved in place does.
149
+ try { await (options.settle ?? (await import("./codex-native-account.mjs")).settleMovedLogin)(home); }
150
+ catch { /* the next read settles it */ }
151
+ return { ok: true };
152
+ } catch (err) {
153
+ return { ok: false, why: err?.code === "login_changed" ? "import refused" : "import failed" };
154
+ }
155
+ }
156
+ // A conflict is somebody else changing the registry between the read and
157
+ // the write; one fresh read is enough to tell that from a real failure.
158
+ for (let attempt = 0; attempt < 2; attempt++) {
159
+ try {
160
+ const { revision } = await readSelection();
161
+ const out = await importCodexShare({ blob, expectedRevision: revision }, options);
162
+ return out?.results?.[0]?.status === "imported" ? { ok: true } : { ok: false, why: "import refused" };
163
+ } catch (err) {
164
+ if (err?.code !== "selection_conflict" || attempt) return { ok: false, why: "import failed" };
165
+ }
166
+ }
167
+ return { ok: false, why: "import failed" };
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,103 @@
1
+ // Codex accounts on Local network: the rules, pure, as lan-copies.mjs holds
2
+ // Claude's. No sockets, no timers, no filesystem — the store is
3
+ // lan-codex-store.mjs, and the engine carries both kinds of login over one
4
+ // pairing, one seal and one `want`.
5
+ //
6
+ // THEY TRAVEL IN THEIR OWN LIST. A manifest's `accounts` is Claude's, and every
7
+ // deck since the first one reads it as claude-swap logins: a Codex row there
8
+ // would be asked for, handed over, and refused by `cswap import` on every round
9
+ // of an older deck. So Codex rows go in a `codex` field that an older deck never
10
+ // reads — the same additive rule the card and the usage readings follow.
11
+ import { manifestFor, offered, onePerKey, slotFor } from "./lan-copies.mjs";
12
+ import { CODEX_KEY_PREFIX, codexLanKey, tokenHash } from "./codex-lan-identity.mjs";
13
+
14
+ // The name of a login is a leaf of its own — see codex-lan-identity.mjs.
15
+ export { CODEX_KEY_PREFIX, codexLanKey, tokenHash };
16
+
17
+ /** How many superseded logins a row remembers. A login is renewed about once a
18
+ * week; eight covers two months of a paired deck that was switched off. */
19
+ export const LINEAGE_MAX = 8;
20
+
21
+ const HASH = /^[a-f0-9]{32}$/;
22
+
23
+ export const isCodexKey = key => typeof key === "string" && key.startsWith(CODEX_KEY_PREFIX);
24
+
25
+ /**
26
+ * Remember the refresh token one profile holds now, and the ones it held before.
27
+ * `entry` is what was kept for that profile, or nothing. Returns the entry to
28
+ * keep and whether it changed, so the store writes only when it did.
29
+ */
30
+ export function nextLineage(entry, rt) {
31
+ const was = Array.isArray(entry?.was) ? entry.was.filter(h => HASH.test(h)) : [];
32
+ if (!HASH.test(rt ?? "")) return { entry: { rt: null, was }, changed: !!entry?.rt };
33
+ if (entry?.rt === rt) return { entry: { rt, was }, changed: false };
34
+ const older = HASH.test(entry?.rt ?? "") ? [entry.rt, ...was.filter(h => h !== entry.rt)] : was;
35
+ return { entry: { rt, was: older.filter(h => h !== rt).slice(0, LINEAGE_MAX) }, changed: true };
36
+ }
37
+
38
+ /**
39
+ * What to do about one Codex account, given my copy and a paired deck's.
40
+ *
41
+ * "add" I do not have this account at all.
42
+ * "heal" My copy's refresh token is one the other deck has already renewed
43
+ * past. A Codex refresh token works once: the deck that renews it
44
+ * keeps the account and every other copy is refused from then on. So
45
+ * when that deck says it held my token before the one it holds now,
46
+ * my copy is dead — proven, not guessed from an expiry or a failed
47
+ * read — and its copy is the same login, renewed.
48
+ * null Anything else, which is most of the time.
49
+ *
50
+ * A DIFFERENT LOGIN IS NEVER REPLACED. Somebody who signed in on each machine
51
+ * holds two token families that share no history, so neither deck can find its
52
+ * token in the other's list, and both keep their own. The same holds for a copy
53
+ * that works: it is in nobody's history until somebody renews past it.
54
+ */
55
+ export function codexSyncAction(mine, theirs) {
56
+ if (!theirs || !theirs.alive || theirs.shareable === false) return null;
57
+ if (!mine) return "add";
58
+ return HASH.test(mine.rt ?? "") && Array.isArray(theirs.was) && theirs.was.includes(mine.rt) ? "heal" : null;
59
+ }
60
+
61
+ /** Everything to do this round over one paired deck's Codex list, in key order
62
+ * like Claude's plan, so a failure halfway is the same half each time. */
63
+ export function planCodex(local, remote) {
64
+ const mine = new Map(onePerKey(local).map(a => [a.key, a]));
65
+ const out = [];
66
+ for (const theirs of remote) {
67
+ const action = codexSyncAction(mine.get(theirs.key), theirs);
68
+ if (action) out.push({ key: theirs.key, email: theirs.email, action, provider: "codex" });
69
+ }
70
+ return out.sort((a, b) => a.key.localeCompare(b.key));
71
+ }
72
+
73
+ /**
74
+ * This deck's Codex list for one paired deck: the Claude rules word for word —
75
+ * only what is ticked, the login it is on listed and not given unless its owner
76
+ * said so, nothing about it while that is hidden — plus each row's token
77
+ * history, which is what lets the other deck tell a dead copy of this login from
78
+ * a different login of the same account.
79
+ */
80
+ export function codexManifest(accounts, shared, opts = {}) {
81
+ const codex = accounts.filter(a => isCodexKey(a.key));
82
+ return manifestFor(codex, shared.filter(isCodexKey), opts).map(row => {
83
+ const held = slotFor(codex, row.key);
84
+ return HASH.test(held?.rt ?? "")
85
+ ? { ...row, rt: held.rt, was: (held.was ?? []).filter(h => HASH.test(h)).slice(0, LINEAGE_MAX) }
86
+ : row;
87
+ });
88
+ }
89
+
90
+ /**
91
+ * A paired deck's Codex list as this deck keeps it: read, not trusted. The
92
+ * Claude list's rules — strings where strings belong, fifty logins at most — and
93
+ * only keys that are Codex keys, with hashes that are hashes.
94
+ */
95
+ export function offeredCodex(list) {
96
+ const raw = (Array.isArray(list) ? list : []).filter(a => a && isCodexKey(a.key));
97
+ return offered(raw).filter(a => isCodexKey(a.key)).map(row => {
98
+ const src = raw.find(a => a.key === row.key && HASH.test(a.rt ?? ""));
99
+ if (!src) return row;
100
+ const was = Array.isArray(src.was) ? src.was.filter(h => typeof h === "string" && HASH.test(h)).slice(0, LINEAGE_MAX) : [];
101
+ return { ...row, rt: src.rt, was };
102
+ });
103
+ }
@@ -27,6 +27,7 @@ import { createRouteCheck } from "./route-via.mjs";
27
27
  import { DISCOVERY_PORT } from "./lan-beacon.mjs";
28
28
  import { aboutThisDeck } from "./lan-about.mjs";
29
29
  import { createUsageShare } from "./usage-share.mjs";
30
+ import { createCodexLan } from "./lan-codex-store.mjs";
30
31
  import { MAC_FW, PROBE_PS, UFW_CONF, UFW_DEFAULTS, isActive, localAliases, reachability, readMacProbe, readProbe, readUfw, silentInbound } from "./lan-reach.mjs";
31
32
  import { run } from "./exec.mjs";
32
33
  // A LAN round checks the imports it lands the way the paste box does.
@@ -131,6 +132,10 @@ export const lanEngine = createEngine({
131
132
  // moved/reused slot can never satisfy a want for another account.
132
133
  return accountKey(accounts[0]?.email, accounts[0]?.organizationUuid) === expectedKey ? out.blob : null;
133
134
  },
135
+ // This deck's Codex logins, offered and taken by the same pairing in a list
136
+ // of their own — see lan-codex.mjs for the rules and lan-codex-store.mjs for
137
+ // what is read and written.
138
+ codex: createCodexLan(),
134
139
  // The logins a round just imported, checked once after it — see checkImports.
135
140
  checkArrivals: async steps => {
136
141
  const { checkImports } = await import("./cswap-admin.mjs");
@@ -41,8 +41,9 @@
41
41
  // anything.
42
42
  import {
43
43
  addTrusted, ANNOUNCE_MS, credentialAad, dropTrusted, identityFrom, open, peerWhy, plan, PRESENT_MS,
44
- sharedWith, stillListed, transferChallenge, trustedPeer,
44
+ sharedWith, slotFor, stillListed, transferChallenge, trustedPeer,
45
45
  } from "./lan-sync.mjs";
46
+ import { isCodexKey, offeredCodex, planCodex } from "./lan-codex.mjs";
46
47
  import { mintInvite, readInvite } from "./lan-invite.mjs";
47
48
  import { createInviteOffer } from "./lan-invite-offer.mjs";
48
49
  import { syncAccounts } from "./lan-accounts.mjs";
@@ -252,6 +253,10 @@ function askOver(conn, frame) {
252
253
  */
253
254
  export function createEngine({
254
255
  readAccounts, exportAccount, importAccount, checkArrivals, liveLogin,
256
+ /** This deck's Codex logins — `readAccounts`, `exportAccount(id, key)` and
257
+ * `importAccount(blob, step, mine)`, see lan-codex-store.mjs — or nothing,
258
+ * which is a deck that offers and takes Claude logins only. */
259
+ codex = null,
255
260
  onChange, onError, onIdentity, onPort, onTrust, onUnpaired, onDial, onShared, now = Date.now,
256
261
  /**
257
262
  * The UDP socket the beacon shouts through, injectable for the same reason
@@ -440,6 +445,15 @@ export function createEngine({
440
445
  await usage?.refresh(accounts);
441
446
  return accounts;
442
447
  };
448
+ /** This deck's Codex logins in the same shape, or null for a deck without
449
+ * them. A Codex store that cannot be read offers nothing this time; it is
450
+ * never a reason for a round, or the Claude logins in it, to fail. */
451
+ const localCodex = codex ? async () => {
452
+ try {
453
+ const rows = await codex.readAccounts();
454
+ return Array.isArray(rows) ? rows.filter(r => isCodexKey(r?.key)) : [];
455
+ } catch { return []; }
456
+ } : null;
443
457
 
444
458
  /** This deck's side of the manifest exchange: the frame it sends, what it
445
459
  * keeps of the one it hears — a paired deck's card and the logins it offers,
@@ -522,6 +536,7 @@ export function createEngine({
522
536
  const { serve } = createServe({
523
537
  settings: () => cfg, serverNow: () => server, myFp: () => identity.fp,
524
538
  inbound, learnCaller, keepManifest, manifestFrame, localAccounts, liveLogin, exportAccount, onError,
539
+ localCodex, exportCodex: codex ? (id, key) => codex.exportAccount(id, key) : null,
525
540
  });
526
541
 
527
542
  /**
@@ -626,7 +641,8 @@ export function createEngine({
626
641
  /** Checks the logins a round brought, once, and records any reason one is
627
642
  * unusable here on its row. An unanswered check is not a failure. */
628
643
  const markArrivals = async done => {
629
- const arrived = done.filter(d => d.ok);
644
+ // claude-swap's logins only: it is claude-swap that is asked.
645
+ const arrived = done.filter(d => d.ok && d.provider !== "codex");
630
646
  if (!arrived.length || !checkArrivals) return;
631
647
  let found = null;
632
648
  try { found = await checkArrivals(arrived); } catch { /* unasked is not a failure of the round */ }
@@ -742,10 +758,11 @@ export function createEngine({
742
758
  && trustedPeer(cfg.trusted, conn.peerFp)?.pub === conn.peerPub;
743
759
  if (!stillPaired()) throw new Error("peer no longer paired");
744
760
  const mine = await localAccounts();
761
+ const mineCodex = localCodex ? await localCodex() : null;
745
762
  // The owner can revoke trust or disable sync while the store is read.
746
763
  // Never send this deck's account identities on that old connection.
747
764
  if (!stillPaired()) throw new Error("peer no longer paired");
748
- const theirs = await ask(manifestFrame(mine, conn.key, conn.peerFp));
765
+ const theirs = await ask(manifestFrame(mine, conn.key, conn.peerFp, mineCodex));
749
766
  // A response from a round that was stopped or unpaired is stale even
750
767
  // when the peer had already sent it before the setting changed.
751
768
  if (!stillPaired()) throw new Error("peer no longer paired");
@@ -802,7 +819,14 @@ export function createEngine({
802
819
  // the store lock, while the panel drew 50 and every other paired deck
803
820
  // waited behind it. `step.key` also reached transferChallenge and
804
821
  // importAccount untyped, which `offered`'s filter would have caught.
805
- const wanted = plan(mine, list);
822
+ // AND THEN ITS CODEX LOGINS, after every Claude one and by the same steps
823
+ // below — a `want` with its own proof, a sealed `have`, an import, a tick
824
+ // onward for an add. Their own list, read off the frame here because the
825
+ // token history the heal needs is not kept (see lan-codex.mjs).
826
+ const wanted = [
827
+ ...plan(mine, list),
828
+ ...(mineCodex ? planCodex(mineCodex, offeredCodex(theirs.codex)) : []),
829
+ ];
806
830
  /** One login, asked for and opened: a `want` carrying its own proof that
807
831
  * names the account (see transferChallenge), and the `have` opened under
808
832
  * the additional data it was sealed with. The login, or why there is
@@ -840,9 +864,13 @@ export function createEngine({
840
864
  // The step goes down with the blob: the wiring has to know WHICH account
841
865
  // it is placing before it may treat a decline as an empty slot rather
842
866
  // than as a healthy one.
867
+ // A Codex login goes to the Codex store, with the copy it heals.
843
868
  let got;
844
- try { got = await importAccount(blob, step); }
845
- catch {
869
+ try {
870
+ got = step.provider === "codex"
871
+ ? await codex.importAccount(blob, step, slotFor(mineCodex, step.key))
872
+ : await importAccount(blob, step);
873
+ } catch {
846
874
  // One local store failure must not erase earlier arrivals or stop
847
875
  // independent logins from being received. Store diagnostics can
848
876
  // contain credential material, so only a fixed verdict leaves here.
@@ -6,6 +6,7 @@
6
6
  // lan-copies.mjs's, and the card's are lan-about.mjs's.
7
7
  import { currentFor, heardCurrent, manifestFor, offered, sharedWith } from "./lan-sync.mjs";
8
8
  import { openAbout, sealAbout } from "./lan-about.mjs";
9
+ import { codexManifest, offeredCodex } from "./lan-codex.mjs";
9
10
 
10
11
  /**
11
12
  * `about` is this deck's own card, or null for a deck built without one. `now`
@@ -40,7 +41,7 @@ export function createManifests({ about, now, myFp, settings, usage = null }) {
40
41
  * it shares with that deck (see sharedWith), which of them it is on, and its
41
42
  * card. One frame whichever way it travels — the question a round asks, and
42
43
  * the answer `serve` gives. */
43
- const manifestFrame = (accounts, key, toFp) => {
44
+ const manifestFrame = (accounts, key, toFp, codexAccounts = null) => {
44
45
  const cfg = settings();
45
46
  const shared = sharedWith(cfg, toFp);
46
47
  const list = manifestFor(accounts, shared, { sendInUse: cfg.sendInUse === true, shareActive: cfg.shareActive });
@@ -51,6 +52,12 @@ export function createManifests({ about, now, myFp, settings, usage = null }) {
51
52
  // The readings this deck owns for accounts in `list`, sealed like the
52
53
  // card. An older deck ignores the key, as it ignores the card.
53
54
  ...(usage ? usage.fieldFor(key, toFp, list) : {}),
55
+ // The Codex logins it shares with that deck, by Claude's rules, in a list
56
+ // of their own that an older deck never reads — see lan-codex.mjs. Sent
57
+ // empty too, so unticking the last one is heard.
58
+ ...(Array.isArray(codexAccounts)
59
+ ? { codex: codexManifest(codexAccounts, shared, { sendInUse: cfg.sendInUse === true, shareActive: cfg.shareActive }) }
60
+ : {}),
54
61
  };
55
62
  };
56
63
 
@@ -67,7 +74,14 @@ export function createManifests({ about, now, myFp, settings, usage = null }) {
67
74
  if (card) aboutBy.set(fromFp, { ...card, at: now() });
68
75
  if (!Array.isArray(frame.accounts)) return null;
69
76
  const list = offered(frame.accounts);
70
- offersBy.set(fromFp, { at: now(), accounts: list, current: heardCurrent(frame.current, list) });
77
+ offersBy.set(fromFp, {
78
+ at: now(), accounts: list, current: heardCurrent(frame.current, list),
79
+ // Its Codex logins, from a deck new enough to send them — without their
80
+ // token history, which only the round reads, and reads off the frame.
81
+ ...(Array.isArray(frame.codex)
82
+ ? { codex: offeredCodex(frame.codex).map(({ rt: _rt, was: _was, ...row }) => row) }
83
+ : {}),
84
+ });
71
85
  // Never awaited: handing a reading to claude-swap runs behind the round.
72
86
  usage?.heard(key, frame, fromFp, list);
73
87
  return list;
@@ -7,6 +7,7 @@
7
7
  // of them can change while the store is read.
8
8
  import { credentialAad, IN_USE, mayGiveInUse, seal, sharedWith, slotFor, transferChallenge, trustedPeer } from "./lan-sync.mjs";
9
9
  import { liveLoginIs } from "./account-health.mjs";
10
+ import { isCodexKey } from "./lan-codex.mjs";
10
11
 
11
12
  /**
12
13
  * `settings`, `serverNow` and `myFp` answer the engine's settings in force,
@@ -15,11 +16,13 @@ import { liveLoginIs } from "./account-health.mjs";
15
16
  * `learnCaller` is the engine's dial-back for a paired deck nothing here
16
17
  * dials. `keepManifest` and `manifestFrame` are lan-manifest.mjs's,
17
18
  * `localAccounts` reads the store in the rules' shape, and `liveLogin`,
18
- * `exportAccount` and `onError` are the engine's own.
19
+ * `exportAccount` and `onError` are the engine's own. `localCodex` and
20
+ * `exportCodex` are the same two for Codex logins, or null on a deck without
21
+ * them — see lan-codex.mjs.
19
22
  */
20
23
  export function createServe({
21
24
  settings, serverNow, myFp, inbound, learnCaller, keepManifest, manifestFrame, localAccounts, liveLogin, exportAccount,
22
- onError,
25
+ localCodex = null, exportCodex = null, onError,
23
26
  }) {
24
27
  /** Frames from a deck that finished the handshake AND that somebody here has
25
28
  * accepted. Nothing reaches this before both, which is the whole point of
@@ -48,11 +51,12 @@ export function createServe({
48
51
  // nothing here dials is ever known by what it offers.
49
52
  keepManifest(ctx.key, msg, ctx.peerFp);
50
53
  const accounts = await localAccounts();
54
+ const codexAccounts = localCodex ? await localCodex() : null;
51
55
  // Reading the store can take long enough for the owner to unpair this
52
56
  // deck. Do not disclose account identities or the active account from
53
57
  // a manifest assembled before that decision.
54
58
  if (!mayAnswer()) return ctx.send({ t: "no", why: "not paired" });
55
- return ctx.send(manifestFrame(accounts, ctx.key, ctx.peerFp));
59
+ return ctx.send(manifestFrame(accounts, ctx.key, ctx.peerFp, codexAccounts));
56
60
  }
57
61
  if (msg.t === "want") {
58
62
  // A listener may have authenticated this socket before its owner
@@ -78,10 +82,16 @@ export function createServe({
78
82
  if (typeof msg.proof !== "string" || msg.proof !== want) {
79
83
  return ctx.send({ t: "no", why: "proof" });
80
84
  }
85
+ // A CODEX LOGIN takes every step below in the same order, from its own
86
+ // store: the tick, the slot, the one this deck is on, readable, alive.
87
+ // Only the CLI check is Claude's, since it asks claude-swap who is
88
+ // signed in. A deck without Codex has none to give.
89
+ const codexWant = isCodexKey(msg.key);
90
+ if (codexWant && !(localCodex && exportCodex)) return ctx.send({ t: "no", why: "not mine to give" });
81
91
  // Only what the user ticked, checked again here rather than trusted
82
92
  // from the manifest we sent: the list can change between the two, and
83
93
  // the answer that matters is the one at the moment of sending.
84
- const accounts = await localAccounts();
94
+ const accounts = codexWant ? await localCodex() : await localAccounts();
85
95
  if (!maySend()) return ctx.send({ t: "no", why: "not shared" });
86
96
  // The slot manifestFor told the peer about, by the same rule: with two
87
97
  // slots for one identity, an expired one listed first must not hide a
@@ -106,11 +116,11 @@ export function createServe({
106
116
  if (!mine.alive) return ctx.send({ t: "no", why: "not mine to give" });
107
117
  // The active slot exports the live CLI login, and its verdict can
108
118
  // predate a `/login` as somebody else, so ask the CLI who it is now.
109
- if (mine.active && liveLogin && !liveLoginIs(await liveLogin(), mine.email, mine.org)) {
119
+ if (!codexWant && mine.active && liveLogin && !liveLoginIs(await liveLogin(), mine.email, mine.org)) {
110
120
  return ctx.send({ t: "no", why: "export failed" });
111
121
  }
112
122
  if (!maySend()) return ctx.send({ t: "no", why: "not shared" });
113
- const blob = await exportAccount(mine.num, msg.key);
123
+ const blob = codexWant ? await exportCodex(mine.num, msg.key) : await exportAccount(mine.num, msg.key);
114
124
  if (!maySend()) return ctx.send({ t: "no", why: "not shared" });
115
125
  // A Mac's failed export refreshes the verdict behind `readable` in the
116
126
  // background, so when the Keychain was why, the next ask is answered by
@@ -409,6 +409,8 @@ export const SETTING_VARS = Object.freeze([
409
409
  // Radar's off switch (index.mjs). A deck started at login without it would
410
410
  // look for Claude Code's collector and capture it.
411
411
  "AGENTS_DECK_NO_RADAR",
412
+ // Keep native Codex account control disabled after a login-service restart.
413
+ "AGENTS_DECK_NO_CODEX_LIVE",
412
414
  ]);
413
415
 
414
416
  export function settingsEnv(env = process.env) {
@@ -64,6 +64,11 @@ const PINNED_MODULES = [
64
64
  "codex-terminal.mjs",
65
65
  "codex-native-account.mjs",
66
66
  "codex-auto.mjs",
67
+ "codex-profiles.mjs", "codex-selection.mjs", "codex-live-engine.mjs",
68
+ "codex-share.mjs", "codex-login.mjs",
69
+ // The Codex profile Projects report, reached only through import() from its
70
+ // route (it imports account-projects.mjs, pinned below, for the day rule).
71
+ "codex-projects.mjs",
67
72
  "ccusage.mjs",
68
73
  "browser-watch.mjs",
69
74
  "browser-watch-store.mjs",
@@ -447,6 +447,9 @@ export const GUARDED_READS = new Set([
447
447
  // credentials are deliberately omitted from the response.
448
448
  "/api/codex-profiles",
449
449
  "/api/codex-profile-quota",
450
+ // Per-project token spend of one Codex profile: the Claude report's class of
451
+ // secret, under the same rule as /api/account-projects below.
452
+ "/api/codex-profile-projects",
450
453
  "/api/codex-auto",
451
454
  "/api/codex-profile-launch",
452
455
  "/api/codex-profile-login",