ccdeck 3.51.0 → 3.53.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 +13 -4
- package/bin/cli/help.js +1 -1
- package/bin/cli/one-shot.js +3 -2
- package/bin/cli/second-start.js +2 -2
- package/bin/cli/uninstall.js +1 -1
- package/bin/codex-profile.js +21 -0
- package/bin/deck.js +4 -3
- package/dist/web/assets/BrowserWatchModal-CKN9jBCT.js +1 -0
- package/dist/web/assets/IntegrationModal-Cb9MgsP1.js +7 -0
- package/dist/web/assets/RadioPanel-D8h6qba-.js +1 -0
- package/dist/web/assets/TrafficRadar-3_aX8BI6.js +8 -0
- package/dist/web/assets/UsageHistoryModal-DgMXDORj.js +1 -0
- package/dist/web/assets/app-BwJGP2ic.js +358 -0
- package/dist/web/assets/app-xTrs4aEH.css +1 -0
- package/dist/web/assets/{index-CWUj8Kqh.js → index-C8fQC4Vq.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +2 -1
- package/release-notes.json +36 -0
- package/src/server/account-routes.mjs +99 -0
- package/src/server/account-watch.mjs +1 -1
- package/src/server/cli-versions.mjs +3 -3
- package/src/server/codex-auth.mjs +51 -9
- package/src/server/codex-auto.mjs +196 -0
- package/src/server/codex-login.mjs +117 -0
- package/src/server/codex-native-account.mjs +288 -0
- package/src/server/codex-profiles.mjs +243 -0
- package/src/server/codex-quota.mjs +370 -251
- package/src/server/codex-selection.mjs +371 -0
- package/src/server/codex-terminal-runner.mjs +78 -0
- package/src/server/codex-terminal.mjs +109 -0
- package/src/server/codex-watch.mjs +38 -22
- package/src/server/depth-facts.mjs +1 -1
- package/src/server/discovery.mjs +13 -0
- package/src/server/index.mjs +19 -1
- package/src/server/installer.mjs +11 -5
- package/src/server/log-election.mjs +32 -3
- package/src/server/login-service.mjs +1 -1
- package/src/server/memory-files.mjs +2 -2
- package/src/server/pinned-build.mjs +3 -0
- package/src/server/request-gates.mjs +9 -0
- package/src/server/running-deck.mjs +12 -1
- package/src/server/session-enrichment.mjs +2 -2
- package/src/server/tool-audit.mjs +15 -1
- package/src/server/usage-routes.mjs +1 -1
- package/dist/web/assets/BrowserWatchModal-CDpunrq9.js +0 -1
- package/dist/web/assets/IntegrationModal-BctMcNU8.js +0 -7
- package/dist/web/assets/RadioPanel-DQNFtYOx.js +0 -1
- package/dist/web/assets/TrafficRadar-DRt3Al7E.js +0 -8
- package/dist/web/assets/UsageHistoryModal-DlgPufgs.js +0 -1
- package/dist/web/assets/app-4x4wTE-L.js +0 -321
- package/dist/web/assets/app-o4kL0FgZ.css +0 -1
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// Supported Codex JSONL RPC; no credential files, token extraction or login.
|
|
2
|
+
// Protocol: https://developers.openai.com/codex/app-server
|
|
3
|
+
// account/rateLimits/read may proactively refresh via Codex's own AuthManager:
|
|
4
|
+
// https://github.com/openai/codex/blob/main/codex-rs/login/src/auth/manager.rs
|
|
5
|
+
// account/read currently exposes email/plan, not workspace ID: equal revisions
|
|
6
|
+
// cannot prove that two same-email workspaces are the same account. Managed
|
|
7
|
+
// home labels remain essential. Recheck account/read after every quota read.
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { posix, win32 } from 'node:path';
|
|
12
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
13
|
+
import { candidateSpec, isBatch, pathLookup } from './exec-spec.mjs';
|
|
14
|
+
import { killTree, watchChild } from './exec-children.mjs';
|
|
15
|
+
|
|
16
|
+
const cache = new Map();
|
|
17
|
+
const dependencyIds = new WeakMap();
|
|
18
|
+
let nextDependency = 0;
|
|
19
|
+
const CACHE_LIMIT = 64;
|
|
20
|
+
const CACHE_MS = 60_000;
|
|
21
|
+
const activeQuotaFloor = (entry, now) => entry.quotaValue && Number.isFinite(entry.quotaAt) && now - entry.quotaAt < CACHE_MS;
|
|
22
|
+
const DEADLINE_MS = 12_000;
|
|
23
|
+
const MAX_OUTPUT = 1024 * 1024;
|
|
24
|
+
const MAX_LINE = 64 * 1024;
|
|
25
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
26
|
+
async function authFileVersion(home, path, readStat = stat) {
|
|
27
|
+
try {
|
|
28
|
+
const info = await readStat(path.join(home, 'auth.json'));
|
|
29
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`;
|
|
30
|
+
} catch (error) { return error.code === 'ENOENT' ? 'missing' : null; }
|
|
31
|
+
}
|
|
32
|
+
const dependencyId = value => {
|
|
33
|
+
if (!value || !['function', 'object'].includes(typeof value)) return 0;
|
|
34
|
+
if (!dependencyIds.has(value)) dependencyIds.set(value, ++nextDependency);
|
|
35
|
+
return dependencyIds.get(value);
|
|
36
|
+
};
|
|
37
|
+
const bounded = (value, maximum) => Number.isFinite(value) && value > 0 ? Math.min(value, maximum) : maximum;
|
|
38
|
+
const safePlan = value => typeof value === 'string' && /^[a-z0-9_-]{1,40}$/.test(value) ? value : null;
|
|
39
|
+
const failure = (reason, now, identity = {}) => ({
|
|
40
|
+
ok: false, signedIn: false, label: null, identityVersion: null, plan: null,
|
|
41
|
+
...identity, ok: false, windows: [], fetchedAt: now(), reason,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
function accountIdentity(result) {
|
|
45
|
+
if (!result || !Object.hasOwn(result, 'account')) return null;
|
|
46
|
+
const account = result.account;
|
|
47
|
+
if (account === null) return { ok: true, signedIn: false, label: null, identityVersion: hash('null'), plan: null };
|
|
48
|
+
if (!account || !['chatgpt', 'apiKey'].includes(account.type)) return null;
|
|
49
|
+
const rawEmail = typeof account.email === 'string' ? account.email.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 254) : null;
|
|
50
|
+
const email = rawEmail && /^[^\s@/\\]+@[^\s@/\\]+$/.test(rawEmail) ? rawEmail : null;
|
|
51
|
+
// Some versions may add a public account ID. Hash it; never serialize it.
|
|
52
|
+
const rawId = account.id ?? account.accountId;
|
|
53
|
+
const accountHash = typeof rawId === 'string' && rawId.length <= 256 ? hash(rawId) : null;
|
|
54
|
+
const workspace = accountHash?.slice(0, 8) ?? null;
|
|
55
|
+
const plan = account.type === 'apiKey' ? 'api' : safePlan(account.planType);
|
|
56
|
+
return {
|
|
57
|
+
ok: true, signedIn: true,
|
|
58
|
+
label: account.type === 'apiKey' ? 'Codex API key' : `${email ?? 'Codex account'}${workspace ? ` · ${workspace}` : ''}`,
|
|
59
|
+
identityVersion: hash(JSON.stringify([account.type, email, plan, accountHash])), plan,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function quotaWindows(result) {
|
|
63
|
+
const bucket = result?.rateLimitsByLimitId?.codex ?? result?.rateLimits;
|
|
64
|
+
if (!bucket || (bucket.limitId != null && bucket.limitId !== 'codex')) return null;
|
|
65
|
+
const window = value => {
|
|
66
|
+
if (!value || typeof value.usedPercent !== 'number' || !Number.isFinite(value.usedPercent) || value.usedPercent < 0) return null;
|
|
67
|
+
const seconds = typeof value.windowDurationMins === 'number' ? value.windowDurationMins * 60 : null;
|
|
68
|
+
return {
|
|
69
|
+
usedPercent: value.usedPercent,
|
|
70
|
+
seconds: Number.isFinite(seconds) && seconds > 0 ? seconds : null,
|
|
71
|
+
resetAt: typeof value.resetsAt === 'number' && Number.isFinite(value.resetsAt) && value.resetsAt >= 0 ? value.resetsAt : null,
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
return [window(bucket.primary), window(bucket.secondary)].filter(Boolean);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function rpcRead(home, options) {
|
|
78
|
+
const { platform, env, now, includeQuota } = options;
|
|
79
|
+
const lookup = options.pathLookup ?? pathLookup;
|
|
80
|
+
let executable;
|
|
81
|
+
try { executable = options.executable ?? lookup('codex', platform, { pathEnv: env.PATH ?? env.Path ?? '' }); }
|
|
82
|
+
catch { return Promise.resolve(failure('cli_unavailable', now)); }
|
|
83
|
+
if (!executable) return Promise.resolve(failure('cli_unavailable', now));
|
|
84
|
+
// PATH lookup happens in the deck's cwd, before the child moves to its home.
|
|
85
|
+
const path = platform === 'win32' ? win32 : posix;
|
|
86
|
+
if (!path.isAbsolute(executable)) executable = path.resolve(process.cwd(), executable);
|
|
87
|
+
const spec = candidateSpec(executable, ['app-server'], platform);
|
|
88
|
+
if (isBatch(executable, platform) && !win32.isAbsolute(spec.file)) {
|
|
89
|
+
const root = env.SystemRoot ?? env.systemroot;
|
|
90
|
+
// A bare cmd.exe could be shadowed inside the selected home on Windows.
|
|
91
|
+
const wrapper = root && win32.isAbsolute(root) ? win32.join(root, 'System32', 'cmd.exe')
|
|
92
|
+
: lookup('cmd.exe', platform, { pathEnv: env.PATH ?? env.Path ?? '' });
|
|
93
|
+
if (!wrapper || !win32.isAbsolute(wrapper)) return Promise.resolve(failure('cli_unavailable', now));
|
|
94
|
+
spec.file = wrapper;
|
|
95
|
+
}
|
|
96
|
+
const childEnv = { ...env, CODEX_HOME: home };
|
|
97
|
+
// Ambient API keys must not replace this home's keyring identity.
|
|
98
|
+
delete childEnv.OPENAI_API_KEY; delete childEnv.CODEX_API_KEY;
|
|
99
|
+
if (platform === 'win32') childEnv.NoDefaultCurrentDirectoryInExePath = '1';
|
|
100
|
+
return new Promise(resolve => {
|
|
101
|
+
let child, timer, done = false, expected = 0, before = null, windows = [], bytes = 0, pending = '';
|
|
102
|
+
const decoder = new StringDecoder('utf8');
|
|
103
|
+
const finish = value => {
|
|
104
|
+
if (done) return;
|
|
105
|
+
done = true; clearTimeout(timer);
|
|
106
|
+
pending = ''; before = null;
|
|
107
|
+
try { child?.stdin?.end(); } catch { /* already closed */ }
|
|
108
|
+
try { (options.killChild ?? killTree)(child, 'SIGKILL'); } catch { /* already gone */ }
|
|
109
|
+
child?.stdout?.destroy(); child?.stderr?.destroy();
|
|
110
|
+
resolve(value);
|
|
111
|
+
};
|
|
112
|
+
const send = value => {
|
|
113
|
+
if (done) return;
|
|
114
|
+
try { child.stdin.write(JSON.stringify(value) + '\n'); }
|
|
115
|
+
catch { finish(failure('rpc_error', now)); }
|
|
116
|
+
};
|
|
117
|
+
const response = message => {
|
|
118
|
+
if (!message || typeof message !== 'object') return finish(failure('protocol_error', now));
|
|
119
|
+
if (message.method && Object.hasOwn(message, 'id')) {
|
|
120
|
+
// External-token callbacks and tool requests are outside this reader.
|
|
121
|
+
// Never answer with credentials, approve actions, or start a login.
|
|
122
|
+
return finish(failure('unsupported_auth', now));
|
|
123
|
+
}
|
|
124
|
+
if (message.id !== expected) return; // notifications / unrelated responses
|
|
125
|
+
if (message.error) {
|
|
126
|
+
const reason = [-32601, -32602].includes(message.error.code) ? 'unsupported' : 'rpc_error';
|
|
127
|
+
return finish(failure(reason, now, before ?? {}));
|
|
128
|
+
}
|
|
129
|
+
if (!Object.hasOwn(message, 'result')) return finish(failure('protocol_error', now));
|
|
130
|
+
if (expected === 0) {
|
|
131
|
+
expected = 1;
|
|
132
|
+
send({ method: 'initialized', params: {} });
|
|
133
|
+
send({ id: 1, method: 'account/read', params: { refreshToken: false } });
|
|
134
|
+
} else if (expected === 1) {
|
|
135
|
+
before = accountIdentity(message.result);
|
|
136
|
+
if (!before) return finish(failure('unsupported', now));
|
|
137
|
+
if (!includeQuota || !before.signedIn || before.plan === 'api') {
|
|
138
|
+
return finish({ ...before, windows: [], fetchedAt: now() });
|
|
139
|
+
}
|
|
140
|
+
expected = 2;
|
|
141
|
+
send({ id: 2, method: 'account/rateLimits/read' });
|
|
142
|
+
} else if (expected === 2) {
|
|
143
|
+
windows = quotaWindows(message.result);
|
|
144
|
+
if (!windows) return finish(failure('quota_unavailable', now, before));
|
|
145
|
+
expected = 3;
|
|
146
|
+
send({ id: 3, method: 'account/read', params: { refreshToken: false } });
|
|
147
|
+
} else {
|
|
148
|
+
const after = accountIdentity(message.result);
|
|
149
|
+
if (!after || after.identityVersion !== before.identityVersion) return finish(failure('profile_changed', now, after ?? {}));
|
|
150
|
+
finish({ ...after, windows, fetchedAt: now() });
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
try {
|
|
154
|
+
child = watchChild((options.spawn ?? spawn)(spec.file, spec.args, {
|
|
155
|
+
...spec.opts, cwd: home, env: childEnv, shell: false, windowsHide: true,
|
|
156
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
157
|
+
}));
|
|
158
|
+
timer = setTimeout(() => finish(failure('timeout', now)), bounded(options.deadlineMs, DEADLINE_MS));
|
|
159
|
+
child.on('error', error => finish(failure(error?.code === 'ENOENT' ? 'cli_unavailable' : 'rpc_error', now)));
|
|
160
|
+
child.on('close', () => finish(failure('unsupported', now)));
|
|
161
|
+
child.stdin.on('error', () => finish(failure('rpc_error', now)));
|
|
162
|
+
child.stdout.on('error', () => finish(failure('rpc_error', now)));
|
|
163
|
+
child.stderr.on('error', () => {});
|
|
164
|
+
child.stderr.resume(); // drain without buffering, returning or logging it
|
|
165
|
+
child.stdout.on('data', chunk => {
|
|
166
|
+
if (done) return;
|
|
167
|
+
bytes += Buffer.byteLength(chunk);
|
|
168
|
+
if (bytes > bounded(options.maxOutputBytes, MAX_OUTPUT)) return finish(failure('output_limit', now));
|
|
169
|
+
pending += typeof chunk === 'string' ? chunk : decoder.write(chunk);
|
|
170
|
+
let newline;
|
|
171
|
+
while (!done && (newline = pending.indexOf('\n')) >= 0) {
|
|
172
|
+
if (Buffer.byteLength(pending.slice(0, newline)) > MAX_LINE) return finish(failure('output_limit', now));
|
|
173
|
+
const line = pending.slice(0, newline); pending = pending.slice(newline + 1);
|
|
174
|
+
if (!line.trim()) continue;
|
|
175
|
+
let message;
|
|
176
|
+
try { message = JSON.parse(line); } catch { return finish(failure('protocol_error', now)); }
|
|
177
|
+
response(message);
|
|
178
|
+
}
|
|
179
|
+
if (Buffer.byteLength(pending) > MAX_LINE) finish(failure('output_limit', now));
|
|
180
|
+
});
|
|
181
|
+
send({ id: 0, method: 'initialize', params: { clientInfo: { name: 'ccdeck', version: '3.39.1' } } });
|
|
182
|
+
} catch { finish(failure('cli_unavailable', now)); }
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Capture home once. Injectable spawn/executable/pathLookup/killChild/now
|
|
187
|
+
* support synthetic tests; callers never forward HTTP input as options.
|
|
188
|
+
* Cache keys separate quota from metadata. No reads of plaintext auth files.
|
|
189
|
+
*/
|
|
190
|
+
export async function readNativeCodexAccount(home, options = {}) {
|
|
191
|
+
const now = options.now ?? Date.now;
|
|
192
|
+
const platform = options.platform ?? process.platform;
|
|
193
|
+
const path = platform === 'win32' ? win32 : posix;
|
|
194
|
+
if (typeof home !== 'string' || !path.isAbsolute(home) || home.includes('\0')) return Promise.resolve(failure('profile_unavailable', now));
|
|
195
|
+
const env = { ...(options.env ?? process.env) };
|
|
196
|
+
// Match Codex's canonical-home keyring identity and share floors across aliases.
|
|
197
|
+
try { home = await (options.realpath ?? realpath)(home); }
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (!['ENOENT', 'ENOTDIR'].includes(error.code)) return failure('profile_unavailable', now);
|
|
200
|
+
}
|
|
201
|
+
const includeQuota = options.includeQuota === true;
|
|
202
|
+
const key = JSON.stringify([home, includeQuota, platform, options.executable ?? null, env.PATH ?? env.Path ?? '',
|
|
203
|
+
dependencyId(options.spawn), dependencyId(options.pathLookup), dependencyId(options.killChild), dependencyId(options.now), dependencyId(options.stat), dependencyId(options.realpath), options.deadlineMs ?? null, options.maxOutputBytes ?? null]);
|
|
204
|
+
const started = now();
|
|
205
|
+
const held = cache.get(key);
|
|
206
|
+
if (held && (held.pending || (!options.force && started >= held.at && started - held.at < CACHE_MS))) return (held.pending ?? Promise.resolve(structuredClone(held.value))).then(value => structuredClone(value));
|
|
207
|
+
cache.delete(key);
|
|
208
|
+
for (const [id, entry] of cache) if (!entry.pending && !activeQuotaFloor(entry, started) && (started < entry.at || started - entry.at >= CACHE_MS)) cache.delete(id);
|
|
209
|
+
if (cache.size >= CACHE_LIMIT) {
|
|
210
|
+
const settled = [...cache].find(([, entry]) => !entry.pending && !activeQuotaFloor(entry, started));
|
|
211
|
+
if (!settled) return Promise.resolve(failure('native_busy', now));
|
|
212
|
+
cache.delete(settled[0]);
|
|
213
|
+
}
|
|
214
|
+
let attemptedQuota = false;
|
|
215
|
+
const entry = { at: started, pending: null, value: null, quotaAt: held?.quotaAt, quotaValue: held?.quotaValue, quotaFileVersion: held?.quotaFileVersion };
|
|
216
|
+
const pending = Promise.resolve().then(async () => {
|
|
217
|
+
// One shared wall-clock budget; verification cannot reuse either cache or
|
|
218
|
+
// the first process's in-memory auth snapshot. Keep admission held throughout.
|
|
219
|
+
const deadline = Date.now() + bounded(options.deadlineMs, DEADLINE_MS);
|
|
220
|
+
const fileVersion = await authFileVersion(home, path, options.stat);
|
|
221
|
+
if (fileVersion === null) return failure('profile_unavailable', now);
|
|
222
|
+
const initialRemaining = deadline - Date.now();
|
|
223
|
+
if (initialRemaining <= 0) return failure('timeout', now);
|
|
224
|
+
// Force means verify identity now, never bypass the per-home usage floor.
|
|
225
|
+
if (includeQuota && activeQuotaFloor(entry, started)) {
|
|
226
|
+
const fresh = await rpcRead(home, { ...options, platform, env, now, includeQuota: false, deadlineMs: initialRemaining });
|
|
227
|
+
if (!fresh.ok) return failure(fresh.reason ?? 'rpc_error', now);
|
|
228
|
+
if (fileVersion !== entry.quotaFileVersion || await authFileVersion(home, path, options.stat) !== fileVersion) return failure('profile_changed', now);
|
|
229
|
+
const old = entry.quotaValue;
|
|
230
|
+
if (old.ok && (!fresh.signedIn || fresh.identityVersion !== old.identityVersion)) return failure('profile_changed', now);
|
|
231
|
+
return { ...old, stale: true };
|
|
232
|
+
}
|
|
233
|
+
if (includeQuota) { attemptedQuota = true; entry.quotaAt = started; entry.quotaFileVersion = fileVersion; }
|
|
234
|
+
const value = await rpcRead(home, { ...options, platform, env, now, includeQuota, deadlineMs: initialRemaining });
|
|
235
|
+
// No usage request goes out for a home nobody is signed in to, or one on an
|
|
236
|
+
// API key, so there is no floor to hold. Held, it refused the first real
|
|
237
|
+
// read after a sign-in for the rest of the minute, as a "changed" login.
|
|
238
|
+
if (includeQuota && value.ok && (!value.signedIn || value.plan === 'api')) {
|
|
239
|
+
attemptedQuota = false;
|
|
240
|
+
entry.quotaAt = entry.quotaValue = entry.quotaFileVersion = undefined;
|
|
241
|
+
return value;
|
|
242
|
+
}
|
|
243
|
+
if (includeQuota) entry.quotaValue = value;
|
|
244
|
+
if (!includeQuota || !value.ok || !value.signedIn || value.plan === 'api') return value;
|
|
245
|
+
const remaining = deadline - Date.now();
|
|
246
|
+
if (remaining <= 0) return failure('timeout', now);
|
|
247
|
+
const fresh = await rpcRead(home, { ...options, platform, env, now, includeQuota: false, deadlineMs: remaining });
|
|
248
|
+
if (!fresh.ok) return failure(fresh.reason ?? 'rpc_error', now);
|
|
249
|
+
if (await authFileVersion(home, path, options.stat) !== fileVersion) return failure('profile_changed', now);
|
|
250
|
+
if (!fresh.signedIn || fresh.identityVersion !== value.identityVersion) return failure('profile_changed', now, fresh);
|
|
251
|
+
return { ...value, fetchedAt: now() };
|
|
252
|
+
})
|
|
253
|
+
.catch(() => failure('rpc_error', now)).then(value => {
|
|
254
|
+
if (attemptedQuota) entry.quotaValue = value;
|
|
255
|
+
entry.pending = null; entry.at = now(); entry.value = value;
|
|
256
|
+
return structuredClone(value);
|
|
257
|
+
});
|
|
258
|
+
entry.pending = pending; cache.set(key, entry);
|
|
259
|
+
return pending;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The deck has just put a new login of this home's own account in place, so the
|
|
263
|
+
* file moved and the account did not. A good reading stays good and keeps its
|
|
264
|
+
* floor, or the row and the Usage panel would read "changed" for the rest of the
|
|
265
|
+
* minute. A failed one says nothing about the new login, so the next read is a
|
|
266
|
+
* real one: it may be the very expiry this sign-in cured. */
|
|
267
|
+
export async function settleMovedLogin(home, options = {}) {
|
|
268
|
+
const path = (options.platform ?? process.platform) === 'win32' ? win32 : posix;
|
|
269
|
+
const canonical = await canonicalHome(home, options);
|
|
270
|
+
const version = await authFileVersion(canonical, path, options.stat);
|
|
271
|
+
for (const [key, entry] of cache) {
|
|
272
|
+
if (JSON.parse(key)[0] !== canonical || entry.pending) continue;
|
|
273
|
+
if (entry.quotaValue?.ok) entry.quotaFileVersion = version;
|
|
274
|
+
else cache.delete(key);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** A sign-in just finished in this home, on whichever account it landed on: what
|
|
279
|
+
* was read before says nothing about it, floor included. The first read of a new
|
|
280
|
+
* login is a real one. Only a person signing in lifts the floor; no poll does. */
|
|
281
|
+
export async function forgetCodexReadings(home, options = {}) {
|
|
282
|
+
const canonical = await canonicalHome(home, options);
|
|
283
|
+
for (const [key, entry] of cache) if (JSON.parse(key)[0] === canonical && !entry.pending) cache.delete(key);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function canonicalHome(home, options) {
|
|
287
|
+
try { return await (options.realpath ?? realpath)(home); } catch { return home; }
|
|
288
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// Explicit Codex homes are separate profiles, not snapshots of auth.json.
|
|
2
|
+
// Discovery reads display metadata only; credentials are never copied or refreshed.
|
|
3
|
+
// The one place a login's access token is used is the quota fallback below, which
|
|
4
|
+
// sends it to OpenAI's own usage endpoint, as the deck's ambient Codex quota
|
|
5
|
+
// reader does, and never to a refresh endpoint.
|
|
6
|
+
import { access, realpath, readFile, stat } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { readCodexSelection, codexProfileId, codexSelectionError, moveCodexLogin } from './codex-selection.mjs';
|
|
10
|
+
import { usesNativeCodexAccount } from './codex-auth.mjs';
|
|
11
|
+
import { readNativeCodexAccount } from './codex-native-account.mjs';
|
|
12
|
+
export { configuredCodexHomes } from './codex-selection.mjs';
|
|
13
|
+
|
|
14
|
+
/** Resolve each explicitly trusted home once before scanning rollout trees.
|
|
15
|
+
* Deduping canonical directories avoids reading a symlink alias twice. */
|
|
16
|
+
export async function codexProfileSessionDirs(options = {}) {
|
|
17
|
+
const selection = options.selection ?? await readCodexSelection(options);
|
|
18
|
+
const homes = selection.homes;
|
|
19
|
+
const seen = new Set();
|
|
20
|
+
const result = [];
|
|
21
|
+
for (const home of homes) {
|
|
22
|
+
let canonical;
|
|
23
|
+
try { canonical = await realpath(home); } catch { canonical = home; }
|
|
24
|
+
if (seen.has(canonical)) continue;
|
|
25
|
+
seen.add(canonical);
|
|
26
|
+
result.push(join(home, 'sessions'));
|
|
27
|
+
}
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The ID identifies a home, never an OAuth token or an email address. */
|
|
32
|
+
export async function discoverCodexProfiles(options = {}) {
|
|
33
|
+
const selection = options.selection ?? await readCodexSelection(options);
|
|
34
|
+
const homes = selection.homes;
|
|
35
|
+
const seen = new Set();
|
|
36
|
+
const profiles = [];
|
|
37
|
+
const logins = new Map();
|
|
38
|
+
for (const directory of homes) {
|
|
39
|
+
let canonical;
|
|
40
|
+
try { canonical = await realpath(directory); } catch { canonical = directory; }
|
|
41
|
+
if (seen.has(canonical)) continue;
|
|
42
|
+
seen.add(canonical);
|
|
43
|
+
let installed = false;
|
|
44
|
+
try { await access(join(directory, 'auth.json')); installed = true; } catch { /* No login yet. */ }
|
|
45
|
+
const credentialVersion = await credentialFileVersion(directory);
|
|
46
|
+
let identity = null;
|
|
47
|
+
try {
|
|
48
|
+
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. */ }
|
|
51
|
+
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;
|
|
53
|
+
const workspace = typeof account === 'string' ? createHash('sha256').update(account).digest('hex').slice(0, 8) : null;
|
|
54
|
+
identity = email ? `${email}${workspace ? ` · ${workspace}` : ''}` : workspace ? `Account ${workspace}` : null;
|
|
55
|
+
} catch { /* Missing or malformed login metadata uses the profile label. */ }
|
|
56
|
+
if (await credentialFileVersion(directory) !== credentialVersion) identity = null;
|
|
57
|
+
const id = selection.profiles?.find(p => p.home === directory)?.id ?? await codexProfileId(directory);
|
|
58
|
+
const managedEntry = selection.managedProfiles?.find(p => p.id === id);
|
|
59
|
+
const managedLabel = selection.profileLabels?.find(p => p.id === id)?.label ?? managedEntry?.label ?? null;
|
|
60
|
+
const available = await stat(directory).then(info => info.isDirectory(), () => false);
|
|
61
|
+
const authoritative = options.enableNative && await usesNativeCodexAccount(directory, selection.selectionEnabled);
|
|
62
|
+
const native = options.enableNative && (authoritative || !installed) && available
|
|
63
|
+
? await (options.nativeRead ?? readNativeCodexAccount)(directory, { force: true }) : null;
|
|
64
|
+
const accountLabel = native ? (native.ok && native.signedIn ? native.label : null) : identity;
|
|
65
|
+
profiles.push({
|
|
66
|
+
id,
|
|
67
|
+
identityVersion: native?.signedIn ? native.identityVersion : createHash('sha256').update(credentialVersion).digest('hex'),
|
|
68
|
+
label: managedLabel ? `${managedLabel}${accountLabel ? ` · ${accountLabel}` : ''}` : accountLabel ?? (profiles.length === 0 ? 'Default Codex' : `Codex profile ${profiles.length + 1}`),
|
|
69
|
+
...(managedLabel ? { managedLabel } : {}),
|
|
70
|
+
...(managedEntry ? { managed: true } : {}),
|
|
71
|
+
/** Who it is signed in as, or null: the row's name when it has no other. */
|
|
72
|
+
account: accountLabel,
|
|
73
|
+
active: id === selection.profileId,
|
|
74
|
+
available,
|
|
75
|
+
...(native ? { signedIn: native.ok && native.signedIn, authSource: 'native', metadataUnavailable: !native.ok, metadataReason: native.reason ?? null } : {}),
|
|
76
|
+
signedInFilePresent: installed, // file presence is NOT authentication validity
|
|
77
|
+
});
|
|
78
|
+
// The file's workspace goes in too: one address on one plan can be two
|
|
79
|
+
// workspaces, and Codex's own answer does not always tell them apart.
|
|
80
|
+
logins.set(id, native?.signedIn ? `${native.identityVersion}:${identity ?? ''}` : identity);
|
|
81
|
+
}
|
|
82
|
+
return withSameAccount(profiles, logins);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Replace the stored login of an account already here with a sign-in that landed
|
|
86
|
+
* on it, as Claude's does. Asked of the deck's own reading, never of the browser:
|
|
87
|
+
* a login does not move onto a row until both are seen to be one account. */
|
|
88
|
+
export async function replaceCodexLogin({ id, into, expectedRevision } = {}, options = {}) {
|
|
89
|
+
const selection = await readCodexSelection(options);
|
|
90
|
+
const roster = await discoverCodexProfiles({ ...options, selection, enableNative: true });
|
|
91
|
+
if (roster.find(profile => profile.id === id)?.sameAccountAs !== into) throw codexSelectionError('not_same_account');
|
|
92
|
+
return moveCodexLogin({ id, into, expectedRevision }, options);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Two rows signed in to one ChatGPT account share one quota, and the second adds
|
|
96
|
+
* nothing: the sign-in page takes whichever account the browser is already in,
|
|
97
|
+
* so this is how a second account usually fails to be one. The default keeps its
|
|
98
|
+
* place, and every other row with its login names the one it repeats. */
|
|
99
|
+
function withSameAccount(profiles, logins) {
|
|
100
|
+
const first = new Map();
|
|
101
|
+
for (const profile of [...profiles].sort((a, b) => Number(b.active) - Number(a.active))) {
|
|
102
|
+
const login = logins.get(profile.id);
|
|
103
|
+
if (!login) continue;
|
|
104
|
+
if (first.has(login)) profile.sameAccountAs = first.get(login);
|
|
105
|
+
else first.set(login, profile.id);
|
|
106
|
+
}
|
|
107
|
+
return profiles;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Resolve a browser-supplied opaque ID only against homes explicitly trusted
|
|
111
|
+
* at server startup. Never accept a path from an HTTP request. */
|
|
112
|
+
export async function resolveCodexProfile(id, options = {}) {
|
|
113
|
+
if (typeof id !== 'string' || !/^[a-f0-9]{20}$/.test(id)) return null;
|
|
114
|
+
const selection = options.selection ?? await readCodexSelection(options);
|
|
115
|
+
const homes = selection.homes;
|
|
116
|
+
for (const directory of homes) {
|
|
117
|
+
if ((selection.profiles?.find(p => p.home === directory)?.id ?? await codexProfileId(directory)) === id) return directory;
|
|
118
|
+
}
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Command for a new terminal session. An environment override only applies
|
|
123
|
+
* to the launched process; no existing session or global auth is modified. */
|
|
124
|
+
export async function codexProfileLaunchCommand(id, options = {}) {
|
|
125
|
+
const selection = options.selection ?? await readCodexSelection(options);
|
|
126
|
+
const directory = await resolveCodexProfile(id, { ...options, selection });
|
|
127
|
+
if (!directory) return null;
|
|
128
|
+
if (selection.selectionEnabled && !await stat(directory).then(info => info.isDirectory(), () => false)) {
|
|
129
|
+
throw codexSelectionError('profile_unavailable');
|
|
130
|
+
}
|
|
131
|
+
if ((options.platform ?? process.platform) === 'win32') {
|
|
132
|
+
// PowerShell environment changes persist in the current shell, so restore
|
|
133
|
+
// the previous value even if Codex exits unsuccessfully.
|
|
134
|
+
return `$previousCodexHome = $env:CODEX_HOME; try { $env:CODEX_HOME = '${directory.replaceAll("'", "''")}'; codex } finally { $env:CODEX_HOME = $previousCodexHome }`;
|
|
135
|
+
}
|
|
136
|
+
return `CODEX_HOME='${directory.replaceAll("'", "'\\''")}' codex`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Read-only per-profile quota. The main CODEX_HOME keeps its existing quota
|
|
140
|
+
* poller; alternate profiles never trigger single-use OAuth refreshes. */
|
|
141
|
+
const profileQuotaCache = new Map();
|
|
142
|
+
async function credentialFileVersion(directory) {
|
|
143
|
+
try {
|
|
144
|
+
const info = await stat(join(directory, 'auth.json'));
|
|
145
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`;
|
|
146
|
+
} catch { return 'missing'; }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export async function readCodexProfileQuota(id, options = {}) {
|
|
150
|
+
const selection = options.selection ?? await readCodexSelection(options);
|
|
151
|
+
const directory = await resolveCodexProfile(id, { ...options, selection });
|
|
152
|
+
if (!directory) return { ok: false, reason: 'unknown_profile' };
|
|
153
|
+
if (!await stat(directory).then(info => info.isDirectory(), () => false)) {
|
|
154
|
+
return { ok: false, reason: 'profile_unavailable' };
|
|
155
|
+
}
|
|
156
|
+
// Invalidate cached quota after a login / account replacement. The file may
|
|
157
|
+
// contain an entirely different ChatGPT account within the cache lifetime.
|
|
158
|
+
const credentialVersion = await credentialFileVersion(directory);
|
|
159
|
+
const authoritative = options.enableNative && await usesNativeCodexAccount(directory, selection.selectionEnabled);
|
|
160
|
+
if (options.enableNative && (authoritative || credentialVersion === 'missing')) {
|
|
161
|
+
const native = await (options.nativeRead ?? readNativeCodexAccount)(directory, { includeQuota: true, force: true });
|
|
162
|
+
if (!authoritative && await credentialFileVersion(directory) !== credentialVersion) return { ok: false, reason: 'profile_changed' };
|
|
163
|
+
if (!native.ok || !native.signedIn || native.plan === 'api') return { ok: false, reason: native.reason ?? (native.plan === 'api' ? 'api_key_mode' : 'no_token'), fetchedAt: native.fetchedAt,
|
|
164
|
+
...(native.stale ? { stale: true } : {}) };
|
|
165
|
+
return { ok: true, partial: true, identityVersion: native.identityVersion, fetchedAt: native.fetchedAt, plan: native.plan, windows: native.windows,
|
|
166
|
+
...(native.stale ? { stale: true } : {}) };
|
|
167
|
+
}
|
|
168
|
+
const now = Date.now();
|
|
169
|
+
const cached = profileQuotaCache.get(id);
|
|
170
|
+
if (cached?.credentialVersion === credentialVersion && cached.pending) return cached.pending;
|
|
171
|
+
if (cached?.credentialVersion === credentialVersion && now - cached.at < 60_000) return cached.value;
|
|
172
|
+
// Last-good readings may be shown as stale only for the same auth file.
|
|
173
|
+
const lastGood = cached?.credentialVersion === credentialVersion ? cached.lastGood : null;
|
|
174
|
+
const request = (async () => {
|
|
175
|
+
let auth;
|
|
176
|
+
try { auth = JSON.parse(await readFile(join(directory, 'auth.json'), 'utf8')); }
|
|
177
|
+
catch { return { ok: false, reason: 'no_token' }; }
|
|
178
|
+
if (auth?.auth_mode === 'apikey' || !auth?.tokens?.access_token) {
|
|
179
|
+
return { ok: false, reason: auth?.auth_mode === 'apikey' ? 'api_key_mode' : 'no_token' };
|
|
180
|
+
}
|
|
181
|
+
// This read-only path must never spend a rotating refresh credential.
|
|
182
|
+
// Report expiry instead of contacting the API with a known-expired token.
|
|
183
|
+
try {
|
|
184
|
+
const payload = JSON.parse(Buffer.from(auth.tokens.access_token.split('.')[1], 'base64url').toString());
|
|
185
|
+
if (typeof payload.exp === 'number' && payload.exp * 1000 <= Date.now()) {
|
|
186
|
+
return { ok: false, reason: 'expired' };
|
|
187
|
+
}
|
|
188
|
+
} catch { /* Non-JWT tokens may still be accepted by the service. */ }
|
|
189
|
+
const claims = (() => {
|
|
190
|
+
try { return JSON.parse(Buffer.from(auth.tokens.id_token.split('.')[1], 'base64url').toString()); }
|
|
191
|
+
catch { return {}; }
|
|
192
|
+
})();
|
|
193
|
+
const accountId = auth.tokens.account_id ?? claims?.['https://api.openai.com/auth']?.chatgpt_account_id;
|
|
194
|
+
const headers = { Authorization: `Bearer ${auth.tokens.access_token}`, Accept: 'application/json', 'User-Agent': 'codex-cli' };
|
|
195
|
+
if (accountId) headers['ChatGPT-Account-Id'] = accountId;
|
|
196
|
+
let response;
|
|
197
|
+
try {
|
|
198
|
+
response = await (options.fetch ?? fetch)('https://chatgpt.com/backend-api/wham/usage', {
|
|
199
|
+
headers, cache: 'no-store', signal: AbortSignal.timeout(12_000),
|
|
200
|
+
});
|
|
201
|
+
} catch { return { ok: false, reason: 'fetch_error' }; }
|
|
202
|
+
if (!response.ok) return { ok: false, reason: response.status === 401 ? 'reauth_required' : `http_${response.status}` };
|
|
203
|
+
let body;
|
|
204
|
+
try { body = await response.json(); }
|
|
205
|
+
catch { return { ok: false, reason: 'decode_error' }; }
|
|
206
|
+
const window = (value) => {
|
|
207
|
+
const raw = value?.used_percent;
|
|
208
|
+
if (raw == null || raw === '') return null;
|
|
209
|
+
const pct = Number(raw);
|
|
210
|
+
return Number.isFinite(pct) && pct >= 0
|
|
211
|
+
? { usedPercent: pct, resetAt: value.resets_at ?? null, seconds: value.limit_window_seconds ?? null }
|
|
212
|
+
: null;
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
ok: true, fetchedAt: Date.now(),
|
|
216
|
+
identityVersion: createHash('sha256').update(credentialVersion).digest('hex'),
|
|
217
|
+
plan: body?.plan_type ?? claims?.['https://api.openai.com/auth']?.chatgpt_plan_type ?? null,
|
|
218
|
+
windows: [window(body?.rate_limit?.primary_window), window(body?.rate_limit?.secondary_window)].filter(Boolean),
|
|
219
|
+
};
|
|
220
|
+
})();
|
|
221
|
+
const pending = request.then(async (value) => {
|
|
222
|
+
// A login may have changed while the remote service was responding. Never
|
|
223
|
+
// publish (or cache) a quota reading from a superseded auth.json.
|
|
224
|
+
if (await credentialFileVersion(directory) !== credentialVersion) {
|
|
225
|
+
return { ok: false, reason: 'profile_changed' };
|
|
226
|
+
}
|
|
227
|
+
const retryable = value.reason === 'fetch_error' || value.reason === 'http_429'
|
|
228
|
+
|| /^http_5\d\d$/.test(value.reason ?? '');
|
|
229
|
+
return !value.ok && retryable && lastGood
|
|
230
|
+
? { ...value, stale: true, lastGood }
|
|
231
|
+
: value;
|
|
232
|
+
});
|
|
233
|
+
profileQuotaCache.set(id, { at: now, pending, credentialVersion, lastGood });
|
|
234
|
+
const value = await pending;
|
|
235
|
+
if (profileQuotaCache.get(id)?.pending === pending) {
|
|
236
|
+
if (value.reason === 'profile_changed') profileQuotaCache.delete(id);
|
|
237
|
+
else profileQuotaCache.set(id, {
|
|
238
|
+
at: Date.now(), value, credentialVersion,
|
|
239
|
+
lastGood: value.ok ? value : lastGood,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return value;
|
|
243
|
+
}
|