ccdeck 3.80.0 → 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 (39) hide show
  1. package/README.md +8 -4
  2. package/bin/cli/tui.js +433 -11
  3. package/dist/web/assets/{BrowserWatchModal-Bfvo_8H6.js → BrowserWatchModal-DKvBSlGT.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-GS5jIQ_J.js → IntegrationModal-D3NLczRe.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-Bxd2ElWb.js → RadioPanel-dCIMGTd9.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-FgHBI2Oh.js → TrafficRadar-CMbwnKe7.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-APwKtE2J.js → UsageHistoryModal-DkGBQaM4.js} +1 -1
  8. package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
  9. package/dist/web/assets/{app-BzHVsgB2.js → app-l0spNrc0.js} +93 -93
  10. package/dist/web/assets/{index-7whwMaPX.js → index-inV7HzhI.js} +1 -1
  11. package/dist/web/index.html +3 -3
  12. package/package.json +1 -1
  13. package/release-notes.json +34 -0
  14. package/src/server/account-notify.mjs +81 -16
  15. package/src/server/account-routes.mjs +18 -0
  16. package/src/server/account-watch.mjs +21 -0
  17. package/src/server/codex-auto.mjs +157 -37
  18. package/src/server/codex-lan-identity.mjs +61 -0
  19. package/src/server/codex-live-rpc.mjs +4 -1
  20. package/src/server/codex-profiles.mjs +34 -4
  21. package/src/server/codex-projects.mjs +308 -0
  22. package/src/server/codex-selection.mjs +17 -2
  23. package/src/server/codex-share.mjs +46 -1
  24. package/src/server/codex-terminal.mjs +1 -1
  25. package/src/server/codex-usage.mjs +69 -0
  26. package/src/server/index.mjs +6 -4
  27. package/src/server/lan-codex-store.mjs +170 -0
  28. package/src/server/lan-codex.mjs +103 -0
  29. package/src/server/lan-deck.mjs +5 -0
  30. package/src/server/lan-engine.mjs +34 -6
  31. package/src/server/lan-manifest.mjs +16 -2
  32. package/src/server/lan-serve.mjs +16 -6
  33. package/src/server/pinned-build.mjs +3 -0
  34. package/src/server/request-gates.mjs +3 -0
  35. package/src/server/tui-codex.mjs +229 -0
  36. package/src/server/tui-lan.mjs +684 -0
  37. package/src/server/tui-machine.mjs +492 -0
  38. package/src/server/tui-network.mjs +730 -0
  39. package/src/server/tui-view.mjs +735 -60
@@ -0,0 +1,61 @@
1
+ // Who a Codex login is, as Local network names it — a leaf with nothing but
2
+ // node:crypto under it, because the Codex panel's reader (codex-profiles.mjs)
3
+ // needs the same name for the share dialog, and that reader is also copied
4
+ // into the self-contained terminal helper (see codex-terminal.mjs), which must
5
+ // not pull the LAN engine in after it. The rules that use the name are
6
+ // lan-codex.mjs's; the store that reads it off disk is lan-codex-store.mjs.
7
+ import { createHash } from "node:crypto";
8
+
9
+ /** Every Codex key starts with this, so one `shared` list holds both kinds and
10
+ * a key says which store it belongs to without a second field to agree with. */
11
+ export const CODEX_KEY_PREFIX = "codex:";
12
+
13
+ const short = value => createHash("sha256").update(value).digest("hex").slice(0, 32);
14
+
15
+ /**
16
+ * The identity of one Codex account across decks: its email and its ChatGPT
17
+ * workspace — one address can be in two workspaces, and those are two quotas.
18
+ *
19
+ * NOT ITS REFRESH TOKEN, which a renewal replaces: keyed on that, an account
20
+ * would be a stranger to itself a week later and every round would add it
21
+ * again. NOT THE RAW WORKSPACE ID either, which nothing here needs to show: it
22
+ * is hashed, as the Codex panel hashes it for its own label.
23
+ *
24
+ * Null for a login with no email, which is an API key rather than an account.
25
+ */
26
+ export function codexLanKey(email, accountId) {
27
+ const mail = typeof email === "string" ? email.trim().toLowerCase() : "";
28
+ if (!mail) return null;
29
+ const workspace = typeof accountId === "string" && accountId ? short(accountId) : "";
30
+ return `${CODEX_KEY_PREFIX}${mail}@@${workspace}`;
31
+ }
32
+
33
+ /** A refresh token as a deck may say it: a hash, never the token. */
34
+ export const tokenHash = token => (typeof token === "string" && token ? short(token) : null);
35
+
36
+ function claimsOf(token) {
37
+ if (typeof token !== "string") return null;
38
+ const part = token.split(".")[1];
39
+ if (!part) return null;
40
+ try {
41
+ const claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
42
+ return claims && typeof claims === "object" ? claims : null;
43
+ } catch { return null; }
44
+ }
45
+
46
+ /** Who a Codex login is, as Local network names it, and the hash of the
47
+ * refresh token it carries — or null for an API key, or a file that is not a
48
+ * ChatGPT login. The email is the id_token's: unsigned here, so it names a row
49
+ * and chooses nothing that could overwrite a login (see codexSyncAction). */
50
+ export function codexLoginOf(auth) {
51
+ if (!auth || typeof auth !== "object" || auth.auth_mode === "apikey") return null;
52
+ const tokens = auth.tokens;
53
+ if (!tokens || typeof tokens !== "object" || typeof tokens.refresh_token !== "string" || !tokens.refresh_token) return null;
54
+ const claims = claimsOf(tokens.id_token);
55
+ const email = typeof claims?.email === "string" ? claims.email.replace(/[\x00-\x1f\x7f]/g, "").trim().slice(0, 254) : "";
56
+ const account = typeof tokens.account_id === "string" && tokens.account_id
57
+ ? tokens.account_id
58
+ : claims?.["https://api.openai.com/auth"]?.chatgpt_account_id;
59
+ const key = codexLanKey(email, typeof account === "string" ? account : "");
60
+ return key ? { key, email, rt: tokenHash(tokens.refresh_token) } : null;
61
+ }
@@ -9,6 +9,7 @@ import WebSocket from 'ws';
9
9
  import { pathLookup, spawnSpec } from './exec-spec.mjs';
10
10
  import { inspectWindowsPrivateSocket, holdWindowsPrivatePath } from './codex-windows-private.mjs';
11
11
  import { createCodexWindowsProxy } from './codex-windows-proxy.mjs';
12
+ import { RUNNING_VERSION } from './running-version.mjs';
12
13
 
13
14
  export const liveError = code => Object.assign(new Error(code), { code });
14
15
  const runFile = promisify(execFile);
@@ -147,7 +148,9 @@ export async function connectCodexLiveRpc(endpoint, options = {}) {
147
148
  const after = windows ? await inspectWindowsPrivateSocket(endpoint.socketPath, options.windowsPrivate) : await inspectPosixSocket(endpoint.socketPath);
148
149
  if (after.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
149
150
  if (guard && !guard.valid()) throw liveError('untrusted_native_socket');
150
- await rpc.request('initialize', { clientInfo: { name: 'ccdeck', title: 'ccdeck', version: '3.53.1' }, capabilities: { experimentalApi: true } });
151
+ // The version this deck runs, not the one this line was written in: the
152
+ // daemon logs it, and a fixed number told it 3.53.1 long after.
153
+ await rpc.request('initialize', { clientInfo: { name: 'ccdeck', title: 'ccdeck', version: RUNNING_VERSION ?? '0.0.0' }, capabilities: { experimentalApi: true } });
151
154
  send({ method: 'initialized', params: {} });
152
155
  return rpc;
153
156
  } catch (error) { rpc.close(); throw error; }
@@ -9,6 +9,7 @@ import { createHash } from 'node:crypto';
9
9
  import { readCodexSelection, codexProfileId, codexSelectionError, moveCodexLogin } from './codex-selection.mjs';
10
10
  import { usesNativeCodexAccount } from './codex-auth.mjs';
11
11
  import { readNativeCodexAccount } from './codex-native-account.mjs';
12
+ import { codexLoginOf } from './codex-lan-identity.mjs';
12
13
  export { configuredCodexHomes } from './codex-selection.mjs';
13
14
 
14
15
  /** Resolve each explicitly trusted home once before scanning rollout trees.
@@ -28,6 +29,29 @@ export async function codexProfileSessionDirs(options = {}) {
28
29
  return result;
29
30
  }
30
31
 
32
+ /** The claims of an auth.json's id_token, or {} when it has none that decode. */
33
+ function idTokenClaims(auth) {
34
+ try { return JSON.parse(Buffer.from(auth?.tokens?.id_token?.split('.')[1] ?? '', 'base64url').toString()) ?? {}; }
35
+ catch { return {}; }
36
+ }
37
+
38
+ /** The ChatGPT account id a parsed auth.json is signed in to, or null. The one
39
+ * rule the profile roster and the Projects report both read it by: the stored
40
+ * `account_id`, else the id_token's own claim. It is the value a rollout's
41
+ * `creator_account_id` carries, so it stays on the server: callers compare it
42
+ * and never send it. */
43
+ export function codexAccountIdOf(auth, claims = idTokenClaims(auth)) {
44
+ const account = auth?.tokens?.account_id ?? claims['https://api.openai.com/auth']?.chatgpt_account_id;
45
+ return typeof account === 'string' && account !== '' ? account : null;
46
+ }
47
+
48
+ /** The account id a Codex home is signed in to right now, or null when it has no
49
+ * readable login. */
50
+ export async function readCodexHomeAccountId(home) {
51
+ try { return codexAccountIdOf(JSON.parse(await readFile(join(home, 'auth.json'), 'utf8'))); }
52
+ catch { return null; }
53
+ }
54
+
31
55
  /** The ID identifies a home, never an OAuth token or an email address. */
32
56
  export async function discoverCodexProfiles(options = {}) {
33
57
  const selection = options.selection ?? await readCodexSelection(options);
@@ -44,16 +68,21 @@ export async function discoverCodexProfiles(options = {}) {
44
68
  try { await access(join(directory, 'auth.json')); installed = true; } catch { /* No login yet. */ }
45
69
  const credentialVersion = await credentialFileVersion(directory);
46
70
  let identity = null;
71
+ /** How Local network names this login, the key and the email it is offered
72
+ * under — the server's own (see codex-lan-identity.mjs), so a tick in the
73
+ * share dialog is the key the manifest is built from. No token. */
74
+ let lan = null;
47
75
  try {
48
76
  const auth = JSON.parse(await readFile(join(directory, 'auth.json'), 'utf8'));
49
- let claims = {};
50
- try { claims = JSON.parse(Buffer.from(auth.tokens?.id_token?.split('.')[1] ?? '', 'base64url').toString()); } catch { /* Account ID may still be available. */ }
77
+ const login = codexLoginOf(auth);
78
+ if (login) lan = { key: login.key, email: login.email };
79
+ const claims = idTokenClaims(auth);
51
80
  const email = typeof claims.email === 'string' ? claims.email.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 254) : null;
52
- const account = auth.tokens?.account_id ?? claims['https://api.openai.com/auth']?.chatgpt_account_id;
81
+ const account = codexAccountIdOf(auth, claims);
53
82
  const workspace = typeof account === 'string' ? createHash('sha256').update(account).digest('hex').slice(0, 8) : null;
54
83
  identity = email ? `${email}${workspace ? ` · ${workspace}` : ''}` : workspace ? `Account ${workspace}` : null;
55
84
  } catch { /* Missing or malformed login metadata uses the profile label. */ }
56
- if (await credentialFileVersion(directory) !== credentialVersion) identity = null;
85
+ if (await credentialFileVersion(directory) !== credentialVersion) { identity = null; lan = null; }
57
86
  const id = selection.profiles?.find(p => p.home === directory)?.id ?? await codexProfileId(directory);
58
87
  const managedEntry = selection.managedProfiles?.find(p => p.id === id);
59
88
  const managedLabel = selection.profileLabels?.find(p => p.id === id)?.label ?? managedEntry?.label ?? null;
@@ -74,6 +103,7 @@ export async function discoverCodexProfiles(options = {}) {
74
103
  available,
75
104
  ...(native ? { signedIn: native.ok && native.signedIn, authSource: 'native', metadataUnavailable: !native.ok, metadataReason: native.reason ?? null } : {}),
76
105
  signedInFilePresent: installed, // file presence is NOT authentication validity
106
+ ...(lan ? { lan } : {}),
77
107
  });
78
108
  // The file's workspace goes in too: one address on one plan can be two
79
109
  // workspaces, and Codex's own answer does not always tell them apart.
@@ -0,0 +1,308 @@
1
+ // The Projects report for a Codex profile: what one signed-in Codex home spent,
2
+ // per project and per day, in the shape the Claude accounts' report has
3
+ // (account-projects.mjs reportFrom/dailyFrom), so the same dialog renders both.
4
+ //
5
+ // WHY THE TALLY IS PER FOLDER AND CREATOR ACCOUNT. A rollout names two things
6
+ // that matter here: the folder the session started in (`session_meta.payload.cwd`,
7
+ // canonicalised the way the watcher canonicalises it, so a symlinked checkout is
8
+ // one project) and the ChatGPT account that created it (`creator_account_id`).
9
+ // Claude's report has to guess which account a transcript belonged to from a swap
10
+ // log; a Codex home has no such problem, because a profile IS one home and the
11
+ // home's auth.json says who is signed in to it NOW. So a session is the project
12
+ // of its folder, with one exception below, and nothing is inferred.
13
+ //
14
+ // WHAT GOES TO `unattributed`. A rollout whose creator is known, whose home's
15
+ // login is known, and where the two DIFFER was written by an earlier sign-in in
16
+ // this folder (the user logged out and in as someone else, or replaced the
17
+ // login). Its spend is real but is not this account's, so the whole file counts
18
+ // under `unattributed`, which the dialog keeps apart from the account's own
19
+ // totals and reconciles to the day as Claude's does. A rollout with no recorded
20
+ // cwd cannot be placed on a project and goes there too. A rollout with no
21
+ // `creator_account_id` (an older Codex, or an API-key login) is NOT a mismatch —
22
+ // absence proves nothing — so it counts for its project. The raw account id is
23
+ // only ever compared here; it is never put in the report.
24
+ //
25
+ // WHY THE FOLD IS foldCodexCost. A session card prices a Codex session from
26
+ // codex-cost-usage.mjs: only OBSERVED INCREASES of the cumulative totals, under
27
+ // the model and the service tier in force at that record, with the whole session
28
+ // discarded when a total goes DOWN (a rollout that restarted its counters cannot
29
+ // be added up with what came before). This report runs every record of a rollout
30
+ // through that same fold and attributes each record's increase to the local day
31
+ // of the record's timestamp, so a day's tokens here and a session card's cost
32
+ // cannot disagree. When the fold discards its totals the per-day tally of that
33
+ // file is discarded with them, for the same reason. Lines before the window are
34
+ // folded too: they are what makes the first in-window delta a delta rather than
35
+ // the session's lifetime total.
36
+ //
37
+ // THE COUNTERS MAPPING. Counters is the Claude shape `{ i, o, cr, cc, c1h, c5m,
38
+ // s? }`. Codex's `input_tokens` INCLUDES the cached portion, and the client's
39
+ // billedInputTokens (src/web/pricing.ts) subtracts `cr` itself for a Codex model,
40
+ // so `i` is the cache-inclusive input as reported, NOT input minus cache. `o` is
41
+ // output, `cr` the cached input, `cc` the cache-write input; `c1h` and `c5m` are
42
+ // Claude's cache-lifetime split and are 0 here. `s` holds the share billed at a
43
+ // tier other than standard ("fast", "flex"…), a SUBSET of the counters it sits
44
+ // on, with the same mapping.
45
+ //
46
+ // WHICH FILES, AND THE MTIME RULE. A resumed session appends to its ORIGINAL
47
+ // rollout, however old its name or day folder is (#1731), so a window cannot pick
48
+ // files by the day directory: a plain rollout is read when its mtime is inside
49
+ // the window, and the per-record timestamps then decide which of its tokens count.
50
+ // A compressed `.jsonl.zst` is one Codex already judged cold, and its mtime is the
51
+ // moment of compression rather than of any work, so it is chosen by the start time
52
+ // its file name carries — the rule codex-usage.mjs applies to it too. The one case
53
+ // that misses is a compressed rollout that started before the window and was
54
+ // written inside it, which Codex does not leave compressed.
55
+ //
56
+ // WHAT IT COSTS. A rollout can be many megabytes, so each is read a chunk at a
57
+ // time (forEachRolloutLine) and never held whole. The per-day, per-model tally of
58
+ // a file is memoised by path + size + mtime and does not depend on the window, so
59
+ // any window is cut from the same memo; the attribution against the login is made
60
+ // at report time, so replacing the login re-files the same memo. Files read at
61
+ // most MAX_PARALLEL_READS at a time, overlapping calls share one scan, and a
62
+ // finished report is kept for a few seconds. Memo entries for files no longer in
63
+ // the tree are dropped on the next scan.
64
+ import { stat } from "node:fs/promises";
65
+ import { basename, join } from "node:path";
66
+ import { walkRolloutDays } from "./codex-dir.mjs";
67
+ import { codexCostState, foldCodexCost } from "./codex-cost-usage.mjs";
68
+ import { canonicalCwd } from "./canonical-path.mjs";
69
+ import { forEachRolloutLine } from "./codex-usage.mjs";
70
+ import { readCodexHomeAccountId, resolveCodexProfile } from "./codex-profiles.mjs";
71
+ import { localDay, windowCutoff } from "./account-projects.mjs";
72
+
73
+ const MAX_PARALLEL_READS = 4;
74
+ const MAX_PARALLEL_STATS = 16;
75
+ const REPORT_CACHE_MS = 20_000;
76
+ const PLAIN = ".jsonl";
77
+ const COMPRESSED = ".jsonl.zst";
78
+
79
+ // A record the fold can act on says one of these; every other line (the bulk of a
80
+ // rollout, the response items) is skipped before the JSON.parse.
81
+ const FOLDED = ["session_meta", '"model"', "thread_settings_applied", "total_token_usage"];
82
+
83
+ /** @type {Map<string, Map<string, object>>} sessions dir -> path -> memo entry */
84
+ const memo = new Map();
85
+ /** Reads in progress, by file identity, so two overlapping scans open a file once. */
86
+ const fileReads = new Map();
87
+ /** Reports in progress and finished, by `id:days`. */
88
+ const reportInflight = new Map();
89
+ const reportCache = new Map();
90
+
91
+ const zero = () => ({ i: 0, o: 0, cr: 0, cc: 0, c1h: 0, c5m: 0 });
92
+
93
+ function addInto(dst, src) {
94
+ dst.i += src.i; dst.o += src.o; dst.cr += src.cr; dst.cc += src.cc;
95
+ dst.c1h += src.c1h; dst.c5m += src.c5m;
96
+ for (const [tier, share] of Object.entries(src.s ?? {})) addInto(((dst.s ??= {})[tier] ??= zero()), share);
97
+ }
98
+
99
+ /** A fold bucket (codex-cost-usage.mjs) as plain numbers, or zeros. */
100
+ function plainBucket(bucket) {
101
+ const take = u => ({ i: u?.input_tokens ?? 0, o: u?.output_tokens ?? 0, cr: u?.cached_input_tokens ?? 0, cc: u?.cache_write_input_tokens ?? 0 });
102
+ return { ...take(bucket), speeds: new Map([...(bucket?.speeds ?? [])].map(([tier, u]) => [tier, take(u)])) };
103
+ }
104
+
105
+ /** What a record added to its model's bucket, as Counters, or null when nothing. */
106
+ function deltaCounters(before, after) {
107
+ const out = zero();
108
+ out.i = after.i - before.i; out.o = after.o - before.o; out.cr = after.cr - before.cr; out.cc = after.cc - before.cc;
109
+ for (const [tier, now] of after.speeds) {
110
+ const was = before.speeds.get(tier);
111
+ const d = { i: now.i - (was?.i ?? 0), o: now.o - (was?.o ?? 0), cr: now.cr - (was?.cr ?? 0), cc: now.cc - (was?.cc ?? 0), c1h: 0, c5m: 0 };
112
+ if (d.i > 0 || d.o > 0 || d.cr > 0 || d.cc > 0) (out.s ??= {})[tier] = d;
113
+ }
114
+ return out.i > 0 || out.o > 0 || out.cr > 0 || out.cc > 0 ? out : null;
115
+ }
116
+
117
+ /** Read one rollout into its memo entry: the creator and folder its header
118
+ * names, and its per-day, per-model Counters. Null when it could not be read. */
119
+ async function readRollout(path, fallbackDay) {
120
+ const state = codexCostState();
121
+ const days = new Map();
122
+ let creator = null;
123
+ let rawCwd = null;
124
+ let sawMeta = false;
125
+ let lastDay = null;
126
+ const onLine = raw => {
127
+ if (!FOLDED.some(needle => raw.includes(needle))) return;
128
+ let obj;
129
+ try { obj = JSON.parse(raw); } catch { return; }
130
+ if (!obj || typeof obj !== "object") return;
131
+ const ts = typeof obj.timestamp === "string" ? Date.parse(obj.timestamp) : NaN;
132
+ if (Number.isFinite(ts)) lastDay = localDay(ts);
133
+ if (obj.type === "session_meta" && !sawMeta) {
134
+ sawMeta = true;
135
+ const pl = obj.payload;
136
+ creator = typeof pl?.creator_account_id === "string" && pl.creator_account_id !== "" ? pl.creator_account_id : null;
137
+ rawCwd = typeof pl?.cwd === "string" ? pl.cwd : null;
138
+ }
139
+ const counts = obj.type === "event_msg" && obj.payload?.type === "token_count"
140
+ && obj.payload.info?.total_token_usage && typeof obj.payload.info.total_token_usage === "object";
141
+ const model = state.model;
142
+ const before = counts ? plainBucket(state.models.get(model)) : null;
143
+ foldCodexCost(state, obj);
144
+ if (!counts) return;
145
+ // The fold threw its totals away (a cumulative total went down): so does the
146
+ // tally, or a day here would carry tokens its session card no longer prices.
147
+ if (state.models.size === 0) { days.clear(); return; }
148
+ if (!model) return;
149
+ const d = deltaCounters(before, plainBucket(state.models.get(model)));
150
+ if (!d) return;
151
+ const day = lastDay ?? fallbackDay;
152
+ const perModel = days.get(day) ?? new Map();
153
+ addInto(perModel.get(model) ?? perModel.set(model, zero()).get(model), d);
154
+ days.set(day, perModel);
155
+ };
156
+ if (!await forEachRolloutLine(path, onLine)) return null;
157
+ return { creator, cwd: await canonicalCwd(rawCwd), days };
158
+ }
159
+
160
+ /** The start time a rollout's file name carries, in LOCAL time as Codex writes it
161
+ * (#609), or null for a name that is not a rollout's. */
162
+ function nameStartMs(name) {
163
+ const m = /^rollout-(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-/.exec(name);
164
+ if (!m) return null;
165
+ const [y, mo, d, h, mi, s] = m.slice(1).map(Number);
166
+ const dt = new Date(y, mo - 1, d, h, mi, s);
167
+ return dt.getMonth() === mo - 1 && dt.getDate() === d ? dt.getTime() : null;
168
+ }
169
+
170
+ async function forEachLimited(items, limit, worker) {
171
+ let next = 0;
172
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
173
+ while (next < items.length) await worker(items[next++]);
174
+ }));
175
+ }
176
+
177
+ /** Bring the memo of one sessions tree up to date for the files a window needs,
178
+ * and return it. Files no longer on disk are evicted whatever the window. */
179
+ async function scanTree(sessionsDir, windowStartMs) {
180
+ const files = [];
181
+ await walkRolloutDays((dir, names) => {
182
+ for (const name of names) {
183
+ const compressed = name.endsWith(COMPRESSED);
184
+ if (!compressed && !(name.endsWith(PLAIN) && name.startsWith("rollout-"))) continue;
185
+ files.push({ path: join(dir, name), name, compressed });
186
+ }
187
+ }, { sessionsDir });
188
+ await forEachLimited(files, MAX_PARALLEL_STATS, async file => {
189
+ try { Object.assign(file, { st: await stat(file.path) }); } catch { /* gone since the walk */ }
190
+ });
191
+ const known = memo.get(sessionsDir) ?? new Map();
192
+ const kept = new Map();
193
+ const wanted = [];
194
+ for (const file of files) {
195
+ if (!file.st) continue;
196
+ const prior = known.get(file.path);
197
+ const fresh = prior && prior.size === file.st.size && prior.mtimeMs === file.st.mtimeMs;
198
+ if (fresh) kept.set(file.path, prior);
199
+ if (fresh || windowStartMs == null) { if (!fresh) wanted.push(file); continue; }
200
+ const startMs = file.compressed ? nameStartMs(file.name) : null;
201
+ const inWindow = file.compressed ? startMs != null && startMs >= windowStartMs : file.st.mtimeMs >= windowStartMs;
202
+ if (inWindow) wanted.push(file);
203
+ }
204
+ await forEachLimited(wanted, MAX_PARALLEL_READS, async file => {
205
+ const { size, mtimeMs } = file.st;
206
+ const identity = `${file.path}\0${size}\0${mtimeMs}`;
207
+ let read = fileReads.get(identity);
208
+ if (!read) {
209
+ read = readRollout(file.path, localDay(mtimeMs)).finally(() => fileReads.delete(identity));
210
+ fileReads.set(identity, read);
211
+ }
212
+ const entry = await read;
213
+ if (entry) kept.set(file.path, { ...entry, size, mtimeMs, compressed: file.compressed, startMs: nameStartMs(file.name) });
214
+ });
215
+ memo.set(sessionsDir, kept);
216
+ return kept;
217
+ }
218
+
219
+ /** The report's one window cut, over memo entries already filtered to the window. */
220
+ function buildReport(entries, accountId, days, now) {
221
+ const cutoff = windowCutoff(days, now);
222
+ const projects = new Map(); // cwd -> day -> model -> Counters
223
+ const unattributed = new Map(); // day -> model -> Counters
224
+ const put = (bucket, day, model, c) => {
225
+ const perModel = bucket.get(day) ?? new Map();
226
+ addInto(perModel.get(model) ?? perModel.set(model, zero()).get(model), c);
227
+ bucket.set(day, perModel);
228
+ };
229
+ for (const entry of entries) {
230
+ // An earlier sign-in's sessions, or one with no folder, are not this
231
+ // account's project work; see the header.
232
+ const otherLogin = accountId && entry.creator && entry.creator !== accountId;
233
+ const target = otherLogin || !entry.cwd ? unattributed : projects.get(entry.cwd) ?? projects.set(entry.cwd, new Map()).get(entry.cwd);
234
+ for (const [day, models] of entry.days) {
235
+ if (cutoff && day < cutoff) continue;
236
+ for (const [model, c] of models) put(target, day, model, c);
237
+ }
238
+ }
239
+ const sum = byDay => {
240
+ const models = {};
241
+ for (const perModel of byDay.values()) for (const [m, c] of perModel) addInto(models[m] ??= zero(), c);
242
+ return Object.keys(models).length ? models : null;
243
+ };
244
+ const toObject = perModel => Object.fromEntries([...perModel]);
245
+ const projectList = [...projects]
246
+ .map(([path, byDay]) => ({ path, name: basename(path) || path || "(unknown)", models: sum(byDay) }))
247
+ .filter(p => p.models)
248
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
249
+ // Per day, like dailyFrom: unattributed folds only into days that already have
250
+ // project work, so history made by another sign-in raises no column of its own.
251
+ const byDay = new Map();
252
+ for (const [path, perDay] of projects) {
253
+ for (const [day, models] of perDay) {
254
+ const slot = byDay.get(day) ?? byDay.set(day, { projects: [], un: null }).get(day);
255
+ slot.projects.push({ path, models: toObject(models) });
256
+ }
257
+ }
258
+ for (const [day, models] of unattributed) {
259
+ const slot = byDay.get(day);
260
+ if (slot) slot.un = toObject(models);
261
+ }
262
+ const daily = [...byDay.entries()]
263
+ .sort((a, b) => (a[0] < b[0] ? -1 : 1))
264
+ .map(([day, s]) => ({ day, projects: s.projects.sort((a, b) => (a.path < b.path ? -1 : 1)), unattributed: s.un }));
265
+ return { ok: true, trackedSince: null, days: days || 0, projects: projectList, unattributed: sum(unattributed), daily };
266
+ }
267
+
268
+ /** The earliest millisecond a window of `days` reaches, or null for all time. */
269
+ function windowStart(days, now) {
270
+ const cutoff = windowCutoff(days, now);
271
+ if (!cutoff) return null;
272
+ const [y, m, d] = cutoff.split("-").map(Number);
273
+ return new Date(y, m - 1, d).getTime();
274
+ }
275
+
276
+ /**
277
+ * The Projects report of one Codex profile over `days` (1, 7, 30; 0 is all).
278
+ *
279
+ * `options` injects what a test has to control: `selection` (the homes and
280
+ * profile ids, as readCodexSelection answers), `now`, and `cacheMs`.
281
+ */
282
+ export async function codexProjectsReport({ id, days } = {}, options = {}) {
283
+ const d = days === 1 ? 1 : days === 30 ? 30 : days === 0 ? 0 : 7;
284
+ const home = await resolveCodexProfile(id, options);
285
+ if (!home) return { ok: false, reason: "unknown_profile" };
286
+ const now = typeof options.now === "function" ? options.now() : options.now ?? Date.now();
287
+ const cacheMs = options.cacheMs ?? REPORT_CACHE_MS;
288
+ const key = `${id}:${d}`;
289
+ const cached = reportCache.get(key);
290
+ if (cached && now - cached.at < cacheMs) return cached.value;
291
+ const running = reportInflight.get(key);
292
+ if (running) return running;
293
+ const run = (async () => {
294
+ const sessionsDir = join(home, "sessions");
295
+ const tree = await scanTree(sessionsDir, windowStart(d, now));
296
+ const start = windowStart(d, now);
297
+ // The same selection the scan made: a plain rollout by mtime, a compressed
298
+ // one by its name — applied again here so a memo filled by a wider window
299
+ // does not widen this one.
300
+ const inWindow = [...tree.values()].filter(e => start == null
301
+ || (e.compressed ? e.startMs != null && e.startMs >= start : e.mtimeMs >= start));
302
+ const value = buildReport(inWindow, await readCodexHomeAccountId(home), d, now);
303
+ reportCache.set(key, { at: now, value });
304
+ return value;
305
+ })().finally(() => { reportInflight.delete(key); });
306
+ reportInflight.set(key, run);
307
+ return run;
308
+ }
@@ -25,9 +25,9 @@ export function codexSelectionError(code) {
25
25
  return Object.assign(new Error(code), { code });
26
26
  }
27
27
  const fail = code => { throw codexSelectionError(code); };
28
- const idPattern = /^[a-f0-9]{20}$/;
28
+ export const idPattern = /^[a-f0-9]{20}$/;
29
29
  const operationPattern = /^[A-Za-z0-9_-]{1,128}$/;
30
- const safeCodes = new Set(['not_removable', 'login_not_movable', 'selection_conflict', 'operation_conflict', 'selection_busy', 'unknown_profile', 'profile_unavailable', 'registry_corrupt', 'registry_write_failed', 'invalid_operation', 'invalid_revision', 'invalid_label', 'import_write_failed', 'windows_permissions_failed']);
30
+ const safeCodes = new Set(['not_removable', 'login_not_movable', 'selection_conflict', 'operation_conflict', 'selection_busy', 'unknown_profile', 'profile_unavailable', 'registry_corrupt', 'registry_write_failed', 'invalid_operation', 'invalid_revision', 'invalid_label', 'import_write_failed', 'windows_permissions_failed', 'login_changed']);
31
31
  const storeDir = options => resolve(options.store ?? deckDataDir(options.platform, options.env, options.home));
32
32
  export const codexSelectionPath = (options = {}) => join(storeDir(options), 'codex-accounts.json');
33
33
 
@@ -377,6 +377,21 @@ export async function moveCodexLogin({ id, into, expectedRevision } = {}, option
377
377
  });
378
378
  }
379
379
 
380
+ /** Hand one registered profile's home to `fn` under the registry lock, the
381
+ * lock every sign-in, move and import of this deck takes — so what `fn` checks
382
+ * in that home is still true when it writes there. The registry itself is only
383
+ * read: nothing is added, selected or persisted. Local network's heal is the
384
+ * caller (see lan-codex-store.mjs). */
385
+ export async function withCodexProfileLocked({ id } = {}, fn, options = {}) {
386
+ if (typeof id !== 'string' || !idPattern.test(id)) fail('unknown_profile');
387
+ return locked(options, async () => {
388
+ const state = await initial(options);
389
+ const profile = state.profiles.find(p => p.id === id);
390
+ if (!profile || !await directoryExists(profile.home)) fail('unknown_profile');
391
+ return fn(profile.home);
392
+ });
393
+ }
394
+
380
395
  /** Register a prepared batch under the same lock as account selection. The
381
396
  * callback creates and writes only fresh, empty managed homes. No existing home is
382
397
  * passed to it, including on retries. Only credential fingerprints persist in
@@ -6,7 +6,7 @@ import { constants } from 'node:fs';
6
6
  import { chmod, lstat, mkdir, open, readFile, unlink } from 'node:fs/promises';
7
7
  import { join } from 'node:path';
8
8
  import { createTemp, renameWithRetry } from './atomic-write.mjs';
9
- import { readCodexSelection, importCodexProfiles } from './codex-selection.mjs';
9
+ import { readCodexSelection, importCodexProfiles, withCodexProfileLocked } from './codex-selection.mjs';
10
10
  import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath } from './codex-windows-private.mjs';
11
11
 
12
12
  export const CODEX_SHARE_PREFIX = 'ccdeck-codex-v1.';
@@ -156,6 +156,51 @@ function parseShare(blob) {
156
156
  });
157
157
  }
158
158
 
159
+ /** The logins a share carries, validated as an import validates them, without
160
+ * touching disk: Local network reads who a login is before it lands. */
161
+ export function readCodexShare(blob) { return parseShare(blob); }
162
+
163
+ /** Put the one login a share carries into a registered profile's home in place
164
+ * of the login there — only while `stillDead(auth)` says that login is still
165
+ * the one the caller proved superseded. The check and the write happen under
166
+ * the registry lock every sign-in and move of this deck takes, so a sign-in
167
+ * that lands meanwhile is never overwritten. Local network's heal, and only
168
+ * that: an import never replaces anything (see importCodexShare). */
169
+ export async function replaceCodexLoginFromShare({ blob, id, stillDead } = {}, options = {}) {
170
+ const entries = parseShare(blob);
171
+ if (entries.length !== 1 || typeof stillDead !== 'function') fail('invalid_share');
172
+ return withCodexProfileLocked({ id }, async home => {
173
+ const target = join(home, 'auth.json');
174
+ let current = null;
175
+ try {
176
+ const info = await lstat(target);
177
+ if (info.isFile() && info.size <= AUTH_MAX_BYTES) current = JSON.parse(await readFile(target, 'utf8'));
178
+ } catch { /* no login there to replace */ }
179
+ if (!current || !stillDead(current)) fail('login_changed');
180
+ let tmp, guard;
181
+ try {
182
+ // ON WINDOWS ONLY INTO A PRIVATE FOLDER, by the rule secureCodexImportHome
183
+ // states: a profile that arrived over the network has one, while a folder
184
+ // made by a plain mkdir (a sign-in profile, or ~/.codex) does not and is
185
+ // refused here rather than repaired — its permissions are never changed.
186
+ if ((options.platform ?? process.platform) === 'win32') guard = await holdWindowsPrivatePath(home, { ...options, kind: 'directory' });
187
+ const staged = await createTemp(target, { mode: 0o600 });
188
+ tmp = staged.tmp;
189
+ try { await staged.handle.writeFile(JSON.stringify(entries[0].auth) + '\n'); await staged.handle.sync(); }
190
+ finally { await staged.handle.close(); }
191
+ await chmod(tmp, 0o600);
192
+ if (guard && !guard.valid()) fail('windows_permissions_failed');
193
+ await renameWithRetry(tmp, target);
194
+ tmp = null;
195
+ } catch (error) {
196
+ if (tmp) await unlink(tmp).catch(() => {});
197
+ if (error.code === 'windows_permissions_failed' || error.code === 'windows_private_path_unsafe') fail('windows_permissions_failed');
198
+ fail('import_write_failed');
199
+ } finally { await guard?.release(); }
200
+ return { ok: true, home };
201
+ }, options);
202
+ }
203
+
159
204
  /** The common Windows helper creates the directory with its protected DACL
160
205
  * atomically. Never stage a secret into a directory created by plain mkdir on
161
206
  * Windows; chmod there controls read-only, not confidentiality. */
@@ -93,7 +93,7 @@ export async function configureCodexTerminal(action, options = {}) {
93
93
  await chmod(manifest, 0o600);
94
94
  for (const name of ['codex-terminal-runner.mjs', 'exec-spec.mjs', 'account-engine.mjs', 'codex-engine-adapter.mjs', 'codex-handoff.mjs',
95
95
  'codex-interactive-engine.mjs', 'codex-engine-config.mjs', 'codex-engine-rpc.mjs', 'codex-engine-bridge.mjs',
96
- 'codex-auto.mjs', 'codex-selection.mjs', 'codex-profiles.mjs', 'codex-native-account.mjs',
96
+ 'codex-auto.mjs', 'codex-selection.mjs', 'codex-profiles.mjs', 'codex-lan-identity.mjs', 'codex-native-account.mjs',
97
97
  'codex-auth.mjs', 'codex-dir.mjs', 'deck-home.mjs', 'claude-dir.mjs', 'atomic-write.mjs', 'brand.mjs', 'exec-children.mjs']) {
98
98
  await writeFileAtomic(join(directory, name), await readFile(new URL(`./${name}`, import.meta.url), 'utf8'));
99
99
  await chmod(join(directory, name), 0o600);
@@ -251,6 +251,75 @@ async function readCompressedTokenSeries(filePath) {
251
251
  finally { source?.destroy(); }
252
252
  }
253
253
 
254
+ /**
255
+ * Hand every line of a rollout to `onLine`, plain or compressed, a chunk at a
256
+ * time — the line reader codex-projects.mjs folds a whole rollout with.
257
+ *
258
+ * It is the same read the two series readers above do (a bounded chunk, a
259
+ * StringDecoder for a UTF-8 sequence that straddles a boundary, a final line with
260
+ * no newline, the compressed source held and destroyed), kept apart from them
261
+ * because they build a token series out of each line and this one builds
262
+ * whatever its caller asks. Resolves true when the file was read to its end and
263
+ * false when it could not be (missing, unreadable, a torn archive, or a Node
264
+ * that cannot decompress), so a caller never memoises half a file.
265
+ */
266
+ export async function forEachRolloutLine(filePath, onLine) {
267
+ if (filePath.endsWith(COMPRESSED)) {
268
+ if (!createZstdDecompress) {
269
+ if (!warnedNoZstd) {
270
+ warnedNoZstd = true;
271
+ console.error(
272
+ `${PRODUCT} codex-usage: this Node (${process.version}) cannot read Codex's compressed `
273
+ + "rollouts; sessions older than about a week are being left out. Node 22.15 or newer reads them.",
274
+ );
275
+ }
276
+ return false;
277
+ }
278
+ let source = null;
279
+ try {
280
+ const decoder = new StringDecoder("utf8");
281
+ let pending = "";
282
+ source = createReadStream(filePath);
283
+ const stream = source.pipe(createZstdDecompress());
284
+ source.on("error", err => { stream.destroy(err); });
285
+ for await (const chunk of stream) {
286
+ pending += decoder.write(chunk);
287
+ let from = 0;
288
+ let nl;
289
+ while ((nl = pending.indexOf("\n", from)) >= 0) { onLine(pending.slice(from, nl)); from = nl + 1; }
290
+ if (from > 0) pending = pending.slice(from);
291
+ }
292
+ pending += decoder.end();
293
+ if (pending) onLine(pending);
294
+ return true;
295
+ } catch { return false; }
296
+ finally { source?.destroy(); }
297
+ }
298
+ let fd;
299
+ try {
300
+ fd = await open(filePath, "r");
301
+ const { size } = await fd.stat();
302
+ const buf = Buffer.allocUnsafe(READ_CHUNK_BYTES);
303
+ const decoder = new StringDecoder("utf8");
304
+ let pending = "";
305
+ let pos = 0;
306
+ while (pos < size) {
307
+ const { bytesRead } = await fd.read(buf, 0, READ_CHUNK_BYTES, pos);
308
+ if (bytesRead <= 0) break;
309
+ pos += bytesRead;
310
+ pending += decoder.write(buf.subarray(0, bytesRead));
311
+ let from = 0;
312
+ let nl;
313
+ while ((nl = pending.indexOf("\n", from)) >= 0) { onLine(pending.slice(from, nl)); from = nl + 1; }
314
+ if (from > 0) pending = pending.slice(from);
315
+ }
316
+ pending += decoder.end();
317
+ if (pending) onLine(pending);
318
+ return true;
319
+ } catch { return false; }
320
+ finally { await fd?.close().catch(() => {}); }
321
+ }
322
+
254
323
  /** The reader, exported under a test-only name. The compressed path cannot be
255
324
  * reached through `fetchCodexUsage` without a Codex home full of week-old
256
325
  * sessions, and the thing worth checking is that both spellings produce the