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.
- package/README.md +63 -7
- package/THIRD_PARTY_NOTICES.md +31 -1
- package/bin/cli/tui.js +433 -11
- package/dist/web/assets/{BrowserWatchModal-CJ0CW4Go.js → BrowserWatchModal-DKvBSlGT.js} +1 -1
- package/dist/web/assets/{IntegrationModal-DlJzBN8b.js → IntegrationModal-D3NLczRe.js} +1 -1
- package/dist/web/assets/{RadioPanel-CHl3s3OH.js → RadioPanel-dCIMGTd9.js} +1 -1
- package/dist/web/assets/{TrafficRadar-Cw3i0Hux.js → TrafficRadar-CMbwnKe7.js} +1 -1
- package/dist/web/assets/{UsageHistoryModal-CiB5-CTH.js → UsageHistoryModal-DkGBQaM4.js} +1 -1
- package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
- package/dist/web/assets/{app-2vj7uk2U.js → app-l0spNrc0.js} +93 -93
- package/dist/web/assets/{index-D1YZbdq3.js → index-inV7HzhI.js} +1 -1
- package/dist/web/index.html +3 -3
- package/node_modules/ws/LICENSE +20 -0
- package/node_modules/ws/README.md +540 -0
- package/node_modules/ws/browser.js +8 -0
- package/node_modules/ws/index.js +22 -0
- package/node_modules/ws/lib/buffer-util.js +142 -0
- package/node_modules/ws/lib/constants.js +19 -0
- package/node_modules/ws/lib/event-target.js +292 -0
- package/node_modules/ws/lib/extension.js +203 -0
- package/node_modules/ws/lib/limiter.js +55 -0
- package/node_modules/ws/lib/permessage-deflate.js +530 -0
- package/node_modules/ws/lib/receiver.js +743 -0
- package/node_modules/ws/lib/sender.js +610 -0
- package/node_modules/ws/lib/stream.js +161 -0
- package/node_modules/ws/lib/subprotocol.js +62 -0
- package/node_modules/ws/lib/validation.js +152 -0
- package/node_modules/ws/lib/websocket-server.js +562 -0
- package/node_modules/ws/lib/websocket.js +1426 -0
- package/node_modules/ws/package.json +74 -0
- package/node_modules/ws/wrapper.mjs +21 -0
- package/package.json +5 -3
- package/release-notes.json +71 -0
- package/src/server/account-engine.mjs +87 -0
- package/src/server/account-notify.mjs +81 -16
- package/src/server/account-routes.mjs +49 -3
- package/src/server/account-watch.mjs +21 -0
- package/src/server/codex-auto.mjs +163 -54
- package/src/server/codex-engine-adapter.mjs +272 -0
- package/src/server/codex-engine-bridge.mjs +47 -0
- package/src/server/codex-engine-config.mjs +42 -0
- package/src/server/codex-engine-rpc.mjs +88 -0
- package/src/server/codex-handoff.mjs +20 -0
- package/src/server/codex-interactive-engine.mjs +335 -0
- package/src/server/codex-lan-identity.mjs +61 -0
- package/src/server/codex-live-checkpoint.mjs +55 -0
- package/src/server/codex-live-credentials.mjs +214 -0
- package/src/server/codex-live-engine.mjs +577 -0
- package/src/server/codex-live-handoff.mjs +300 -0
- package/src/server/codex-live-lease.mjs +64 -0
- package/src/server/codex-live-rpc.mjs +158 -0
- package/src/server/codex-profiles.mjs +34 -4
- package/src/server/codex-projects.mjs +308 -0
- package/src/server/codex-quota.mjs +36 -2
- package/src/server/codex-selection.mjs +78 -9
- package/src/server/codex-share.mjs +238 -0
- package/src/server/codex-terminal-runner.mjs +38 -1
- package/src/server/codex-terminal.mjs +15 -3
- package/src/server/codex-usage.mjs +69 -0
- package/src/server/codex-watch.mjs +3 -1
- package/src/server/codex-windows-private.mjs +96 -0
- package/src/server/codex-windows-private.ps1 +140 -0
- package/src/server/codex-windows-proxy.mjs +53 -0
- package/src/server/index.mjs +12 -4
- package/src/server/lan-codex-store.mjs +170 -0
- package/src/server/lan-codex.mjs +103 -0
- package/src/server/lan-deck.mjs +5 -0
- package/src/server/lan-engine.mjs +34 -6
- package/src/server/lan-manifest.mjs +16 -2
- package/src/server/lan-serve.mjs +16 -6
- package/src/server/login-service.mjs +2 -0
- package/src/server/pinned-build.mjs +5 -0
- package/src/server/request-gates.mjs +3 -0
- package/src/server/tui-codex.mjs +229 -0
- package/src/server/tui-lan.mjs +684 -0
- package/src/server/tui-machine.mjs +492 -0
- package/src/server/tui-network.mjs +730 -0
- package/src/server/tui-view.mjs +735 -60
|
@@ -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
|
+
}
|
|
@@ -9,6 +9,7 @@ import { noteQuotaHistory, forgetQuotaHistoryAccount } from "./quota-history.mjs
|
|
|
9
9
|
// optional, unknown values pass through verbatim, and a `partial` flag tells
|
|
10
10
|
// the UI when something was dropped instead of silently showing less.
|
|
11
11
|
import { readFile } from "node:fs/promises";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
12
13
|
// One clamp for both quota readers: see the note on cooldownFromHeader. From
|
|
13
14
|
// quota-oauth.mjs, which owns it, rather than through quota.mjs, which only
|
|
14
15
|
// re-exported it and brings the whole Claude quota chain with it.
|
|
@@ -20,6 +21,7 @@ import { usesNativeCodexAccount, decodeJwt, codexCredentialFingerprint, getCodex
|
|
|
20
21
|
import { PRODUCT } from "./brand.mjs";
|
|
21
22
|
import { resetLabel } from "./reset-label.mjs";
|
|
22
23
|
import { readNativeCodexAccount } from "./codex-native-account.mjs";
|
|
24
|
+
import { readLiveCodexCredential } from "./codex-live-credentials.mjs";
|
|
23
25
|
|
|
24
26
|
// Resolved by codex-dir.mjs rather than here. This file used to spell it
|
|
25
27
|
// `process.env.CODEX_HOME ?? join(homedir(), ".codex")`, which keeps an empty
|
|
@@ -229,6 +231,37 @@ async function fetchResetCredits(base, auth) {
|
|
|
229
231
|
} catch { return null; }
|
|
230
232
|
}
|
|
231
233
|
|
|
234
|
+
// Native account/rateLimits/read omits the saved reset grants. Read their
|
|
235
|
+
// inventory separately, using only a validated file-backed login from the same
|
|
236
|
+
// profile. Codex remains the credential owner; this path never renews or redeems.
|
|
237
|
+
const nativeResetCache = new Map();
|
|
238
|
+
const configFingerprint = async home => createHash('sha256').update(await readFile(join(home, 'config.toml')).catch(() => '')).digest('hex');
|
|
239
|
+
async function nativeResetCredits(selected, home, native, fingerprint, credentialRead) {
|
|
240
|
+
if (!fingerprint || !/^[a-f0-9]{20}$/.test(selected.profileId ?? '')
|
|
241
|
+
|| await codexCredentialFingerprint({ home }) !== fingerprint) return null;
|
|
242
|
+
const config = await configFingerprint(home);
|
|
243
|
+
const key = `${selected.profileId}:${native.identityVersion}:${fingerprint}:${config}`;
|
|
244
|
+
const now = Date.now(), held = nativeResetCache.get(key);
|
|
245
|
+
if (held && now - held.at < CACHE_MS) return held.promise;
|
|
246
|
+
if (native.stale) return null;
|
|
247
|
+
if (nativeResetCache.size >= MAX_SELECTED_READERS) nativeResetCache.delete(nativeResetCache.keys().next().value);
|
|
248
|
+
const promise = (async () => {
|
|
249
|
+
try {
|
|
250
|
+
if (await codexCredentialFingerprint({ home }) !== fingerprint) return null;
|
|
251
|
+
const auth = await credentialRead(selected.profileId, { refresh: false });
|
|
252
|
+
const suffix = auth.accountId ? ` · ${createHash('sha256').update(auth.accountId).digest('hex').slice(0, 8)}` : '';
|
|
253
|
+
if (auth.profileId !== selected.profileId || ![auth.email, auth.email + suffix].includes(native.label)
|
|
254
|
+
|| auth.expiresAt <= Date.now() || await codexCredentialFingerprint({ home }) !== fingerprint) return null;
|
|
255
|
+
const base = await readBaseUrl(home);
|
|
256
|
+
if (!isCredentialHost(base)) return null;
|
|
257
|
+
const credits = await fetchResetCredits(base, auth);
|
|
258
|
+
return await codexCredentialFingerprint({ home }) === fingerprint && await configFingerprint(home) === config ? credits : null;
|
|
259
|
+
} catch { return null; }
|
|
260
|
+
})();
|
|
261
|
+
nativeResetCache.set(key, { at: now, promise });
|
|
262
|
+
return promise;
|
|
263
|
+
}
|
|
264
|
+
|
|
232
265
|
async function requestUsage(base, auth) {
|
|
233
266
|
return fetch(base + usagePath(base), {
|
|
234
267
|
headers: authHeaders(auth),
|
|
@@ -591,7 +624,7 @@ function selectedReader(selection) {
|
|
|
591
624
|
}
|
|
592
625
|
|
|
593
626
|
/** Capture the selected target once; reject a completion from any old revision. */
|
|
594
|
-
export async function fetchCodexQuota({ force = false, readSelection: read = readCodexSelection, enableNative = false, nativeRead = readNativeCodexAccount } = {}) {
|
|
627
|
+
export async function fetchCodexQuota({ force = false, readSelection: read = readCodexSelection, enableNative = false, nativeRead = readNativeCodexAccount, credentialRead = readLiveCodexCredential } = {}) {
|
|
595
628
|
let selected;
|
|
596
629
|
try { selected = await read(); }
|
|
597
630
|
catch { return { ok: false, reason: "selection_unavailable" }; }
|
|
@@ -609,7 +642,7 @@ export async function fetchCodexQuota({ force = false, readSelection: read = rea
|
|
|
609
642
|
try { result = authoritative ? { ok: false, reason: "no_token" } : await (entry?.reader ?? legacyReader).fetch({ force }); }
|
|
610
643
|
finally { if (entry) entry.active--; }
|
|
611
644
|
if (enableNative && result.reason === "no_token") {
|
|
612
|
-
const fingerprint =
|
|
645
|
+
const fingerprint = await codexCredentialFingerprint({ home });
|
|
613
646
|
const native = await nativeRead(home, { includeQuota: true, force: true });
|
|
614
647
|
if (!authoritative && await codexCredentialFingerprint({ home }) !== fingerprint) {
|
|
615
648
|
return { ok: false, reason: 'profile_changed' };
|
|
@@ -621,6 +654,7 @@ export async function fetchCodexQuota({ force = false, readSelection: read = rea
|
|
|
621
654
|
result = { ok: true, windows, extraWindows: [], plan: native.plan, planLabel: planLabel(native.plan),
|
|
622
655
|
email: native.label, partial: true, coverage: "standard_limits", refreshed: false, fetchedAt: native.fetchedAt,
|
|
623
656
|
...(native.stale ? { stale: true } : {}) };
|
|
657
|
+
result.resetCredits = await nativeResetCredits(selected, home, native, fingerprint, credentialRead);
|
|
624
658
|
_accountOfQuota.set(result, { accountId: `profile:${selected.profileId}`, profileId: selected.profileId, email: native.label });
|
|
625
659
|
} else result = { ok: false, reason: native.reason ?? (native.plan === 'api' ? 'api_key_mode' : 'no_token'), fetchedAt: native.fetchedAt,
|
|
626
660
|
...(native.stale ? { stale: true } : {}) };
|
|
@@ -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']);
|
|
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
|
|
|
@@ -48,6 +48,7 @@ async function validate(state, options) {
|
|
|
48
48
|
const ids = new Set();
|
|
49
49
|
for (const p of state.profiles) {
|
|
50
50
|
if (!p || typeof p.id !== 'string' || !idPattern.test(p.id) || ids.has(p.id) || typeof p.home !== 'string' || !path.isAbsolute(p.home)
|
|
51
|
+
|| (p.importFingerprint !== undefined && (!p.managed || !/^[a-f0-9]{64}$/.test(p.importFingerprint)))
|
|
51
52
|
|| typeof p.managed !== 'boolean' || !(p.label === null || validLabel(p.label))) fail('registry_corrupt');
|
|
52
53
|
ids.add(p.id);
|
|
53
54
|
if (p.managed) {
|
|
@@ -62,11 +63,14 @@ async function validate(state, options) {
|
|
|
62
63
|
if (await directoryExists(p.home) && await codexProfileId(p.home) !== p.id) fail('profile_unavailable');
|
|
63
64
|
}
|
|
64
65
|
if (!state.profiles.some(p => p.home === state.originalHome) || !ids.has(state.selectedProfileId)) fail('registry_corrupt');
|
|
66
|
+
if (state.runningSelection != null && (!ids.has(state.runningSelection.id) || !Number.isSafeInteger(state.runningSelection.revision)
|
|
67
|
+
|| state.runningSelection.revision < 1 || state.runningSelection.revision > state.revision)) fail('registry_corrupt');
|
|
65
68
|
const operations = new Set();
|
|
66
69
|
for (const op of state.operations) {
|
|
67
70
|
if (!op || typeof op.operationId !== 'string' || !operationPattern.test(op.operationId) || operations.has(op.operationId)
|
|
68
71
|
|| !['add', 'select'].includes(op.kind) || !ids.has(op.id) || !Number.isSafeInteger(op.revision)
|
|
69
72
|
|| op.revision < 1 || op.revision > state.revision
|
|
73
|
+
|| (op.switchRunning !== undefined && typeof op.switchRunning !== 'boolean')
|
|
70
74
|
|| (op.kind === 'select' && (!Number.isSafeInteger(op.expectedRevision) || op.expectedRevision < 0))
|
|
71
75
|
|| (op.kind === 'add' && !(op.label === null || validLabel(op.label)))) fail('registry_corrupt');
|
|
72
76
|
operations.add(op.operationId);
|
|
@@ -104,9 +108,9 @@ async function snapshot(state, options) {
|
|
|
104
108
|
})));
|
|
105
109
|
// Absence is a recoverable state, not permission to choose another account.
|
|
106
110
|
return {
|
|
107
|
-
home, profileId: state?.selectedProfileId ?? await codexProfileId(home),
|
|
111
|
+
home, originalHome: state?.originalHome ?? homes[0], profileId: state?.selectedProfileId ?? await codexProfileId(home),
|
|
108
112
|
revision: state?.revision ?? 0, selectionEnabled: state !== null,
|
|
109
|
-
available: await directoryExists(home), homes, profiles,
|
|
113
|
+
available: await directoryExists(home), homes, profiles, runningSelection: state?.runningSelection ?? null,
|
|
110
114
|
managedProfiles: (state?.profiles ?? []).filter(p => p.managed).map(({ id, label }) => ({ id, label })),
|
|
111
115
|
/** The name somebody gave each account, the deck's own or not. */
|
|
112
116
|
profileLabels: (state?.profiles ?? []).filter(p => p.label).map(({ id, label }) => ({ id, label })),
|
|
@@ -218,14 +222,15 @@ function replay(state, operationId, kind, matches) {
|
|
|
218
222
|
if (op && (op.kind !== kind || !matches(op))) fail('operation_conflict');
|
|
219
223
|
return op;
|
|
220
224
|
}
|
|
221
|
-
export async function selectCodexProfile({ id, expectedRevision, operationId: operation } = {}, options = {}) {
|
|
225
|
+
export async function selectCodexProfile({ id, expectedRevision, operationId: operation, switchRunning = false } = {}, options = {}) {
|
|
222
226
|
operationId(operation);
|
|
227
|
+
if (typeof switchRunning !== 'boolean') fail('invalid_operation');
|
|
223
228
|
if (typeof id !== 'string' || !idPattern.test(id)) fail('unknown_profile');
|
|
224
229
|
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
|
|
225
230
|
return locked(options, async () => {
|
|
226
231
|
const state = await initial(options);
|
|
227
|
-
if (replay(state, operation, 'select', o => o.id === id && o.expectedRevision === expectedRevision)) {
|
|
228
|
-
return { ...await snapshot(state, options), status: 'applied_for_new_sessions' };
|
|
232
|
+
if (replay(state, operation, 'select', o => o.id === id && o.expectedRevision === expectedRevision && !!o.switchRunning === switchRunning)) {
|
|
233
|
+
return { ...await snapshot(state, options), status: switchRunning ? 'requested_for_managed_sessions' : 'applied_for_new_sessions' };
|
|
229
234
|
}
|
|
230
235
|
if (state.revision !== expectedRevision) fail('selection_conflict');
|
|
231
236
|
const homes = await homesFor(state, options);
|
|
@@ -236,10 +241,11 @@ export async function selectCodexProfile({ id, expectedRevision, operationId: op
|
|
|
236
241
|
if (!state.profiles.some(p => p.id === id)) state.profiles.push({ id, home, label: null, managed: false });
|
|
237
242
|
state.selectedProfileId = id;
|
|
238
243
|
state.revision++;
|
|
239
|
-
state.operations.push({ operationId: operation, kind: 'select', id, expectedRevision, revision: state.revision });
|
|
244
|
+
state.operations.push({ operationId: operation, kind: 'select', id, expectedRevision, revision: state.revision, ...(switchRunning ? { switchRunning } : {}) });
|
|
245
|
+
if (switchRunning) state.runningSelection = { id, revision: state.revision };
|
|
240
246
|
const result = await snapshot(state, options);
|
|
241
247
|
await persist(state, options);
|
|
242
|
-
return { ...result, status: 'applied_for_new_sessions' };
|
|
248
|
+
return { ...result, status: switchRunning ? 'requested_for_managed_sessions' : 'applied_for_new_sessions' };
|
|
243
249
|
});
|
|
244
250
|
}
|
|
245
251
|
/** Add an account this deck keeps the home of. The name is optional: without
|
|
@@ -318,6 +324,7 @@ export async function removeCodexProfile({ id, expectedRevision } = {}, options
|
|
|
318
324
|
async function dropProfile(state, profile, options) {
|
|
319
325
|
const { id } = profile;
|
|
320
326
|
state.profiles = state.profiles.filter(p => p.id !== id);
|
|
327
|
+
if (state.runningSelection?.id === id) delete state.runningSelection;
|
|
321
328
|
// What this profile's add and select left behind would name a profile that
|
|
322
329
|
// is gone, which the registry's own check refuses.
|
|
323
330
|
state.operations = state.operations.filter(op => op.id !== id);
|
|
@@ -369,3 +376,65 @@ export async function moveCodexLogin({ id, into, expectedRevision } = {}, option
|
|
|
369
376
|
return { ...await dropProfile(state, profile, options), status: 'replaced' };
|
|
370
377
|
});
|
|
371
378
|
}
|
|
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
|
+
|
|
395
|
+
/** Register a prepared batch under the same lock as account selection. The
|
|
396
|
+
* callback creates and writes only fresh, empty managed homes. No existing home is
|
|
397
|
+
* passed to it, including on retries. Only credential fingerprints persist in
|
|
398
|
+
* metadata; the registry never receives auth contents. */
|
|
399
|
+
export async function importCodexProfiles({ entries, expectedRevision }, prepareHome, options = {}) {
|
|
400
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) fail('invalid_revision');
|
|
401
|
+
if (!Array.isArray(entries) || entries.length < 1 || entries.length > 20
|
|
402
|
+
|| entries.some(e => !e || !/^[a-f0-9]{64}$/.test(e.fingerprint) || !(e.label === null || validLabel(e.label)))) fail('invalid_operation');
|
|
403
|
+
return locked(options, async () => {
|
|
404
|
+
const state = await initial(options);
|
|
405
|
+
const existing = fingerprint => state.profiles.find(p => p.importFingerprint === fingerprint);
|
|
406
|
+
// A fully repeated import is safe even if the caller lost the reply or
|
|
407
|
+
// another operation has since changed the selection revision.
|
|
408
|
+
if (entries.some(e => !existing(e.fingerprint)) && state.revision !== expectedRevision) fail('selection_conflict');
|
|
409
|
+
const made = [], results = [], guards = [];
|
|
410
|
+
try {
|
|
411
|
+
for (let index = 0; index < entries.length; index++) {
|
|
412
|
+
const entry = entries[index], previous = existing(entry.fingerprint);
|
|
413
|
+
if (previous) {
|
|
414
|
+
if (!await directoryExists(previous.home)) fail('profile_unavailable');
|
|
415
|
+
results.push({ id: previous.id, status: 'already_imported' }); continue;
|
|
416
|
+
}
|
|
417
|
+
const root = join(storeDir(options), 'codex-profiles');
|
|
418
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
419
|
+
if (!(await lstat(root)).isDirectory()) fail('registry_corrupt');
|
|
420
|
+
const home = join(root, randomBytes(16).toString('hex'));
|
|
421
|
+
// The preparer creates the home: on Windows it needs an atomic
|
|
422
|
+
// protected DACL at creation, which mkdir(mode) cannot provide.
|
|
423
|
+
made.push(home);
|
|
424
|
+
const guard = await prepareHome(home, index);
|
|
425
|
+
if (guard) guards.push(guard);
|
|
426
|
+
const id = await codexProfileId(home);
|
|
427
|
+
state.profiles.push({ id, home, label: entry.label, managed: true, importFingerprint: entry.fingerprint });
|
|
428
|
+
results.push({ id, status: 'imported' });
|
|
429
|
+
}
|
|
430
|
+
if (guards.some(guard => !guard.valid())) fail('windows_permissions_failed');
|
|
431
|
+
if (made.length) { state.revision++; await persist(state, options); }
|
|
432
|
+
return { revision: state.revision, results };
|
|
433
|
+
} catch (error) {
|
|
434
|
+
for (const guard of guards) await guard.release();
|
|
435
|
+
// None of these homes was registered if preparation or commit failed.
|
|
436
|
+
await Promise.all(made.map(home => rm(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })));
|
|
437
|
+
throw error;
|
|
438
|
+
} finally { for (const guard of guards) await guard.release(); }
|
|
439
|
+
});
|
|
440
|
+
}
|