ccdeck 3.52.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-CRqdEVdh.js → BrowserWatchModal-CKN9jBCT.js} +1 -1
- package/dist/web/assets/{IntegrationModal-BDzEIGSM.js → IntegrationModal-Cb9MgsP1.js} +1 -1
- package/dist/web/assets/{RadioPanel-BJlsCpnN.js → RadioPanel-D8h6qba-.js} +1 -1
- package/dist/web/assets/{TrafficRadar-BGxw-hlO.js → TrafficRadar-3_aX8BI6.js} +1 -1
- package/dist/web/assets/{UsageHistoryModal-C_WBpNIp.js → UsageHistoryModal-DgMXDORj.js} +1 -1
- package/dist/web/assets/{app-B53fC4gE.js → app-BwJGP2ic.js} +96 -96
- package/dist/web/assets/{app-Co1HNGP8.css → app-xTrs4aEH.css} +1 -1
- package/dist/web/assets/{index-D9nJhUJR.js → index-C8fQC4Vq.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/release-notes.json +22 -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
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./app-
|
|
1
|
+
import"./app-BwJGP2ic.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
|
package/dist/web/index.html
CHANGED
|
@@ -77,9 +77,9 @@
|
|
|
77
77
|
document.documentElement.setAttribute("data-density", density === "tightest" || density === "tighter" || density === "compact" || density === "comfortable" ? density : "default");
|
|
78
78
|
})();
|
|
79
79
|
</script>
|
|
80
|
-
<script type="module" crossorigin src="/assets/index-
|
|
81
|
-
<link rel="modulepreload" crossorigin href="/assets/app-
|
|
82
|
-
<link rel="stylesheet" crossorigin href="/assets/app-
|
|
80
|
+
<script type="module" crossorigin src="/assets/index-C8fQC4Vq.js"></script>
|
|
81
|
+
<link rel="modulepreload" crossorigin href="/assets/app-BwJGP2ic.js">
|
|
82
|
+
<link rel="stylesheet" crossorigin href="/assets/app-xTrs4aEH.css">
|
|
83
83
|
</head>
|
|
84
84
|
<body>
|
|
85
85
|
<div id="root"></div>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ccdeck",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.53.0",
|
|
4
4
|
"description": "Local dashboard for Claude Code and Codex CLI sessions: which Claude Code session needs input, every tool call and Claude Code subagent live, token cost and quota, several Claude accounts. Run npx ccdeck.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/release-notes.json
CHANGED
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"without one."
|
|
85
85
|
],
|
|
86
86
|
"//summaries": {
|
|
87
|
+
"3.53.0": "Codex accounts, with sign-in, switching and Auto-switch",
|
|
87
88
|
"3.52.0": "ccdeck in nine more languages",
|
|
88
89
|
"3.51.0": "Jira integration updates",
|
|
89
90
|
"3.46.0": "Plans, accounts and skills at a glance"
|
|
@@ -131,6 +132,27 @@
|
|
|
131
132
|
"3.48.1",
|
|
132
133
|
"3.49.1"
|
|
133
134
|
],
|
|
135
|
+
"3.53.0": [
|
|
136
|
+
{
|
|
137
|
+
"title": "👥 Codex accounts: sign in, switch and Auto-switch",
|
|
138
|
+
"body": "Add Codex accounts from ccdeck with the official sign-in, see each one's usage, choose the default for new sessions and, if you turn it on, let Auto-switch move to the account with room.",
|
|
139
|
+
"priority": "highlight",
|
|
140
|
+
"noticeLabel": "Codex accounts",
|
|
141
|
+
"notice": "Each account keeps its own Codex folder, and ccdeck never copies, logs or refreshes its tokens. Removing an account moves its folder to codex-profiles-removed instead of deleting it. Auto-switch is off by default and acts only on a reading taken now."
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
"title": "🔀 One Accounts panel for Claude and Codex",
|
|
145
|
+
"body": "With both CLIs installed, a Claude | Codex switch in the panel's header changes the view, never the account in use, and ccdeck remembers it."
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
"title": "🕐 Reset times fit in every language",
|
|
149
|
+
"body": "The time until a reset beside each quota bar is no longer cut where a language's words run longer."
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
"title": "🛠️ Tool and Skill activity work when the deck's folder is gone",
|
|
153
|
+
"body": "Both open again when the folder ccdeck was started from has been deleted."
|
|
154
|
+
}
|
|
155
|
+
],
|
|
134
156
|
"3.52.0": [
|
|
135
157
|
{
|
|
136
158
|
"title": "🌍 ccdeck in your language",
|
|
@@ -37,6 +37,105 @@ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
|
37
37
|
// When it does, the import skips its own detached collection — see importAccount.
|
|
38
38
|
export const CHECKS_IMPORTS = process.platform === "darwin";
|
|
39
39
|
|
|
40
|
+
// Read-only opt-in Codex profile discovery. Exposes opaque references only;
|
|
41
|
+
// never serializes CODEX_HOME, auth.json contents, or OAuth credentials.
|
|
42
|
+
export async function handleCodexProfiles(_req, res) {
|
|
43
|
+
const { discoverCodexProfiles } = await import('./codex-profiles.mjs');
|
|
44
|
+
const { readCodexSelection } = await import('./codex-selection.mjs');
|
|
45
|
+
const selection = await readCodexSelection();
|
|
46
|
+
send(res, 200, { profiles: await discoverCodexProfiles({ selection, enableNative: true }), revision: selection.revision });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function handleCodexProfileMutation(req, res, action) {
|
|
50
|
+
const raw = await readBody(req, res, 4096).catch(() => null);
|
|
51
|
+
let body;
|
|
52
|
+
try { body = JSON.parse(raw ?? ''); } catch { return send(res, 400, { ok: false, reason: 'bad_request' }); }
|
|
53
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return send(res, 400, { ok: false, reason: 'bad_request' });
|
|
54
|
+
const { selectCodexProfile, addCodexProfile, removeCodexProfile, renameCodexProfile } = await import('./codex-selection.mjs');
|
|
55
|
+
const { replaceCodexLogin } = await import('./codex-profiles.mjs');
|
|
56
|
+
// A sign-in still waiting on this account would write its login into a home
|
|
57
|
+
// that is about to be moved away: stop it first, so nothing lands there.
|
|
58
|
+
if (action === 'remove' && typeof body.id === 'string') (await import('./codex-login.mjs')).cancelCodexLogin(body.id);
|
|
59
|
+
try {
|
|
60
|
+
const result = action === 'select' ? await selectCodexProfile(body)
|
|
61
|
+
: action === 'remove' ? await removeCodexProfile(body)
|
|
62
|
+
: action === 'replace' ? await replaceCodexLogin(body)
|
|
63
|
+
: action === 'rename' ? await renameCodexProfile(body) : await addCodexProfile(body);
|
|
64
|
+
// Registry paths are local implementation details; only explicit command
|
|
65
|
+
// requests below return a home as part of a copyable terminal command.
|
|
66
|
+
send(res, 200, { ok: true, id: result.id ?? result.profileId, revision: result.revision, status: result.status });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
const reason = error?.code ?? 'operation_failed';
|
|
69
|
+
const conflicts = ['selection_conflict', 'operation_conflict', 'selection_busy'];
|
|
70
|
+
send(res, conflicts.includes(reason) ? 409 : reason === 'unknown_profile' ? 404 : 400, { ok: false, reason });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Auto-switch for Codex: the same two calls as Claude's, on the deck's own loop
|
|
75
|
+
* (codex-auto.mjs). The POST can move the account new sessions start on, so it
|
|
76
|
+
* stays behind the deck's mutation gate like the rest of this file. */
|
|
77
|
+
export async function handleCodexAuto(_req, res) {
|
|
78
|
+
const { readCodexAuto } = await import('./codex-auto.mjs');
|
|
79
|
+
send(res, 200, await readCodexAuto());
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function handleCodexAutoAction(req, res) {
|
|
83
|
+
const { applyCodexAuto } = await import('./codex-auto.mjs');
|
|
84
|
+
const raw = await readBody(req, res, 4096).catch(() => null);
|
|
85
|
+
let body = null;
|
|
86
|
+
try { body = JSON.parse(raw ?? ''); } catch { /* refused below */ }
|
|
87
|
+
const result = await applyCodexAuto(body);
|
|
88
|
+
send(res, result.ok ? 200 : 400, result);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function handleCodexProfileLogin(req, res) {
|
|
92
|
+
const { resolveCodexProfile } = await import('./codex-profiles.mjs');
|
|
93
|
+
const { codexLoginCommand } = await import('./codex-terminal.mjs');
|
|
94
|
+
const directory = await resolveCodexProfile(new URL(req.url, 'http://localhost').searchParams.get('id'));
|
|
95
|
+
if (!directory) return send(res, 404, { ok: false, reason: 'unknown_profile' });
|
|
96
|
+
send(res, 200, { command: codexLoginCommand(directory) });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Signing a Codex profile in from the deck: start it, read how it is going, or
|
|
100
|
+
* cancel it. See codex-login.mjs. */
|
|
101
|
+
export async function handleCodexProfileLoginFlow(req, res, action) {
|
|
102
|
+
const { startCodexLogin, codexLoginState, cancelCodexLogin } = await import('./codex-login.mjs');
|
|
103
|
+
let id;
|
|
104
|
+
if (action === 'state') id = new URL(req.url, 'http://localhost').searchParams.get('id');
|
|
105
|
+
else {
|
|
106
|
+
const raw = await readBody(req, res, 1024).catch(() => null);
|
|
107
|
+
try { id = JSON.parse(raw ?? '').id; } catch { return send(res, 400, { ok: false, reason: 'bad_request' }); }
|
|
108
|
+
}
|
|
109
|
+
if (typeof id !== 'string' || !/^[a-f0-9]{20}$/.test(id)) return send(res, 404, { ok: false, reason: 'unknown_profile' });
|
|
110
|
+
if (action === 'start') {
|
|
111
|
+
const result = await startCodexLogin(id);
|
|
112
|
+
return send(res, result.ok ? 200 : 404, result);
|
|
113
|
+
}
|
|
114
|
+
send(res, 200, action === 'cancel' ? cancelCodexLogin(id) : codexLoginState(id));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function handleCodexTerminalCommand(req, res) {
|
|
118
|
+
const { codexTerminalCommand } = await import('./codex-terminal.mjs');
|
|
119
|
+
const url = new URL(req.url, 'http://localhost');
|
|
120
|
+
const command = codexTerminalCommand(url.searchParams.get('action') ?? 'install', url.searchParams.get('shell'));
|
|
121
|
+
if (!command) return send(res, 400, { ok: false, reason: 'unsupported_shell' });
|
|
122
|
+
send(res, 200, { command });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function handleCodexProfileQuota(req, res) {
|
|
126
|
+
const { readCodexProfileQuota } = await import('./codex-profiles.mjs');
|
|
127
|
+
const id = new URL(req.url, 'http://localhost').searchParams.get('id');
|
|
128
|
+
send(res, 200, await readCodexProfileQuota(id, { enableNative: true }));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function handleCodexProfileLaunch(req, res) {
|
|
132
|
+
const { codexProfileLaunchCommand } = await import('./codex-profiles.mjs');
|
|
133
|
+
const id = new URL(req.url, 'http://localhost').searchParams.get('id');
|
|
134
|
+
const command = await codexProfileLaunchCommand(id);
|
|
135
|
+
if (!command) return send(res, 404, { error: 'unknown_profile' });
|
|
136
|
+
send(res, 200, { command });
|
|
137
|
+
}
|
|
138
|
+
|
|
40
139
|
export async function handleClaudeAccounts(req, res) {
|
|
41
140
|
const { fetchClaudeAccounts } = await import(
|
|
42
141
|
pathToFileURL(join(PKG_ROOT, "src/server/claude-accounts.mjs")).href
|
|
@@ -184,7 +184,7 @@ async function observeClaude(n) {
|
|
|
184
184
|
|
|
185
185
|
async function observeCodex(n) {
|
|
186
186
|
const quota = await import(pathToFileURL(join(PKG_ROOT, "src/server/codex-quota.mjs")).href);
|
|
187
|
-
const reading = await quota.fetchCodexQuota();
|
|
187
|
+
const reading = await quota.fetchCodexQuota({ enableNative: true });
|
|
188
188
|
const who = quota.codexQuotaAccount(reading);
|
|
189
189
|
const key = who ? codexAccountKey(who.accountId, who.email) : null;
|
|
190
190
|
if (!key) return;
|
|
@@ -49,7 +49,7 @@ async function probe(runImpl, cand) {
|
|
|
49
49
|
return undefined;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
const ask = (fn) => { try { return Boolean(fn()); } catch { return false; } };
|
|
52
|
+
const ask = async (fn) => { try { return Boolean(await fn()); } catch { return false; } };
|
|
53
53
|
|
|
54
54
|
/**
|
|
55
55
|
* `{ claudeVersion?, codexVersion? }` — each present only when its CLI is on the
|
|
@@ -66,7 +66,7 @@ export async function detectCliVersions({
|
|
|
66
66
|
} = {}) {
|
|
67
67
|
const out = {};
|
|
68
68
|
try {
|
|
69
|
-
if (ask(claudePresent)) {
|
|
69
|
+
if (await ask(claudePresent)) {
|
|
70
70
|
// The candidate list is claude-dir.mjs's answer to "where does `claude`
|
|
71
71
|
// live", so a version is found on the same installs the deck already
|
|
72
72
|
// recognises — not only the one on the launcher's PATH. First hit wins; a
|
|
@@ -81,7 +81,7 @@ export async function detectCliVersions({
|
|
|
81
81
|
// No candidate list exists for Codex — the deck reads its sessions off disk
|
|
82
82
|
// and never spawns the CLI — so the bare name goes through run()'s own PATH
|
|
83
83
|
// and shim resolution, which is the same resolution every other spawn uses.
|
|
84
|
-
if (ask(codexPresent)) {
|
|
84
|
+
if (await ask(codexPresent)) {
|
|
85
85
|
const v = await probe(runImpl, "codex");
|
|
86
86
|
if (v) out.codexVersion = v;
|
|
87
87
|
}
|
|
@@ -14,10 +14,12 @@
|
|
|
14
14
|
// a rejected promise from a background poll would take the server down.
|
|
15
15
|
import { readFile, chmod, unlink } from "node:fs/promises";
|
|
16
16
|
import { createHash } from "node:crypto";
|
|
17
|
-
import { join } from "node:path";
|
|
17
|
+
import { join, resolve } from "node:path";
|
|
18
18
|
import { CODEX_HOME } from "./codex-dir.mjs";
|
|
19
|
+
import { readCodexSelection } from "./codex-selection.mjs";
|
|
19
20
|
import { createTemp, renameWithRetry, resolveWriteTarget } from "./atomic-write.mjs";
|
|
20
21
|
import { PRODUCT } from "./brand.mjs";
|
|
22
|
+
import { readNativeCodexAccount } from "./codex-native-account.mjs";
|
|
21
23
|
|
|
22
24
|
// This file used to resolve CODEX_HOME itself, as `process.env.CODEX_HOME ??
|
|
23
25
|
// join(homedir(), ".codex")`. `??` falls back on null and undefined only, so an
|
|
@@ -133,9 +135,9 @@ function expiryMs(accessToken) {
|
|
|
133
135
|
return typeof exp === "number" ? exp * 1000 : null;
|
|
134
136
|
}
|
|
135
137
|
|
|
136
|
-
async function readAuthFile() {
|
|
138
|
+
async function readAuthFile(home = CODEX_HOME) {
|
|
137
139
|
try {
|
|
138
|
-
const parsed = JSON.parse(await readFile(
|
|
140
|
+
const parsed = JSON.parse(await readFile(join(home, "auth.json"), "utf8"));
|
|
139
141
|
return (parsed && typeof parsed === "object") ? parsed : null;
|
|
140
142
|
} catch {
|
|
141
143
|
return null;
|
|
@@ -363,10 +365,49 @@ function identityFrom(auth, refreshed) {
|
|
|
363
365
|
*
|
|
364
366
|
* Returns { ok: true, accessToken, accountId, … } or { ok: false, reason }
|
|
365
367
|
* where reason is `no_token` (never logged in) / `refresh_rejected` (re-login
|
|
366
|
-
* required) / `refresh_failed` (transient).
|
|
368
|
+
* required) / `refresh_failed` (transient). Explicit alternate homes never
|
|
369
|
+
* refresh; selectedReadOnly follows the server selection without rotating tokens.
|
|
370
|
+
* Never throws.
|
|
367
371
|
*/
|
|
368
|
-
|
|
369
|
-
|
|
372
|
+
// Native Codex resolves managed/configured system stores; file remains the legacy default.
|
|
373
|
+
export async function usesNativeCodexAccount(home, selectionEnabled = false) {
|
|
374
|
+
if (selectionEnabled) return true;
|
|
375
|
+
try {
|
|
376
|
+
const text = await readFile(join(home, 'config.toml'), 'utf8');
|
|
377
|
+
const root = text.split(/^\s*\[/m)[0];
|
|
378
|
+
const mode = root.match(/^\s*(?:cli_auth_credentials_store|"cli_auth_credentials_store"|'cli_auth_credentials_store')\s*=\s*["'](file|keyring|auto|ephemeral)["']\s*(?:#.*)?$/m)?.[1];
|
|
379
|
+
return mode === 'keyring' || mode === 'auto' || mode === 'ephemeral';
|
|
380
|
+
} catch (error) { return error.code !== 'ENOENT'; }
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export async function getCodexAuth({ home = CODEX_HOME, allowRefresh = true, selectedReadOnly = false, enableNative = false, nativeRead = readNativeCodexAccount } = {}) {
|
|
384
|
+
if (selectedReadOnly) {
|
|
385
|
+
try {
|
|
386
|
+
const selected = await readCodexSelection();
|
|
387
|
+
const directory = selected.selectionEnabled ? selected.home : CODEX_HOME;
|
|
388
|
+
const fingerprint = await codexCredentialFingerprint({ home: directory });
|
|
389
|
+
const authoritative = enableNative && await usesNativeCodexAccount(directory, selected.selectionEnabled);
|
|
390
|
+
let auth = authoritative ? { ok: false, reason: 'no_token' } : await getCodexAuth({ home: directory, allowRefresh: false });
|
|
391
|
+
if (enableNative && (authoritative || (!auth.ok && auth.reason === 'no_token'))) {
|
|
392
|
+
const native = await nativeRead(directory, { force: true });
|
|
393
|
+
if (native.ok && native.signedIn) auth = {
|
|
394
|
+
ok: true, apiKeyMode: native.plan === 'api', planType: native.plan,
|
|
395
|
+
accountId: null, email: native.label, accessToken: null, refreshed: false, identityVersion: native.identityVersion, authSource: 'native',
|
|
396
|
+
};
|
|
397
|
+
else auth = { ok: false, reason: native.reason ?? 'no_token', metadataUnavailable: !native.ok };
|
|
398
|
+
}
|
|
399
|
+
const current = await readCodexSelection();
|
|
400
|
+
if (selected.selectionEnabled !== current.selectionEnabled || selected.home !== current.home
|
|
401
|
+
|| selected.profileId !== current.profileId || selected.revision !== current.revision
|
|
402
|
+
|| (!authoritative && await codexCredentialFingerprint({ home: directory }) !== fingerprint)) {
|
|
403
|
+
return { ok: false, reason: "profile_changed" };
|
|
404
|
+
}
|
|
405
|
+
return auth;
|
|
406
|
+
} catch { return { ok: false, reason: "selection_unavailable" }; }
|
|
407
|
+
}
|
|
408
|
+
// Only the legacy primary credential owner can rotate tokens.
|
|
409
|
+
allowRefresh = allowRefresh && resolve(home) === resolve(CODEX_HOME);
|
|
410
|
+
let auth = await readAuthFile(home);
|
|
370
411
|
|
|
371
412
|
// An `OPENAI_API_KEY` login is a platform credential, not a ChatGPT session.
|
|
372
413
|
// Flagged rather than rejected so the caller can say so plainly instead of
|
|
@@ -397,10 +438,11 @@ export async function getCodexAuth({ allowRefresh = true } = {}) {
|
|
|
397
438
|
* credential that was refused: `codex login` writes a new pair, and a wait
|
|
398
439
|
* that outlived it answered the user's ↻ with the old refusal.
|
|
399
440
|
*/
|
|
400
|
-
export async function codexCredentialFingerprint() {
|
|
401
|
-
const
|
|
441
|
+
export async function codexCredentialFingerprint({ home = CODEX_HOME } = {}) {
|
|
442
|
+
const auth = await readAuthFile(home);
|
|
443
|
+
const tokens = auth?.tokens;
|
|
402
444
|
if (!tokens?.access_token && !tokens?.refresh_token) return null;
|
|
403
|
-
return tokenHash(
|
|
445
|
+
return tokenHash(JSON.stringify([resolve(home), auth.auth_mode, tokens.access_token, tokens.refresh_token, tokens.account_id, tokens.id_token]));
|
|
404
446
|
}
|
|
405
447
|
|
|
406
448
|
/**
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// Auto-switch for Codex accounts: when the account new sessions start on is
|
|
2
|
+
// nearly full, move the default to another account that still has room.
|
|
3
|
+
// Running sessions keep the account they started on; only the registry's
|
|
4
|
+
// default moves, through the same selectCodexProfile the panel uses.
|
|
5
|
+
import { readFile, mkdir, unlink } from 'node:fs/promises';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { dirname, join, resolve } from 'node:path';
|
|
8
|
+
import { deckDataDir } from './deck-home.mjs';
|
|
9
|
+
import { createTemp, renameWithRetry } from './atomic-write.mjs';
|
|
10
|
+
import { readCodexSelection, selectCodexProfile } from './codex-selection.mjs';
|
|
11
|
+
import { discoverCodexProfiles, readCodexProfileQuota } from './codex-profiles.mjs';
|
|
12
|
+
|
|
13
|
+
// The same whole-percent range the page offers (CUSTOM_MIN / CUSTOM_MAX in
|
|
14
|
+
// src/web/auto-switch-threshold.ts). A server module must not import from the
|
|
15
|
+
// web tree, so the two numbers are repeated here.
|
|
16
|
+
const THRESHOLD_MIN = 50;
|
|
17
|
+
const THRESHOLD_MAX = 99;
|
|
18
|
+
const DEFAULT_THRESHOLD = '90';
|
|
19
|
+
const COOLDOWN_MS = 5 * 60_000;
|
|
20
|
+
const TICK_MS = 60_000;
|
|
21
|
+
const DAY = 86_400;
|
|
22
|
+
const idPattern = /^[a-f0-9]{20}$/;
|
|
23
|
+
|
|
24
|
+
const storeDir = o => resolve(o.store ?? deckDataDir());
|
|
25
|
+
const filePath = o => join(storeDir(o), 'codex-auto.json');
|
|
26
|
+
|
|
27
|
+
// Last tick and cooldown live in memory only, one set per store.
|
|
28
|
+
const memory = new Map();
|
|
29
|
+
const mem = o => {
|
|
30
|
+
const key = storeDir(o);
|
|
31
|
+
if (!memory.has(key)) memory.set(key, { lastTick: null, lastSwitchAt: 0 });
|
|
32
|
+
return memory.get(key);
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
function validThreshold(v) {
|
|
36
|
+
if (typeof v !== 'string' || !/^\d{1,3}$/.test(v)) return false;
|
|
37
|
+
const n = Number(v);
|
|
38
|
+
return n >= THRESHOLD_MIN && n <= THRESHOLD_MAX;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function load(o) {
|
|
42
|
+
let raw = {};
|
|
43
|
+
try { raw = JSON.parse(await readFile(filePath(o), 'utf8')) ?? {}; } catch { /* missing or corrupt: defaults */ }
|
|
44
|
+
return {
|
|
45
|
+
enabled: raw.enabled === true,
|
|
46
|
+
threshold: validThreshold(raw.threshold) ? raw.threshold : DEFAULT_THRESHOLD,
|
|
47
|
+
next: raw.next === 'weekly' ? 'weekly' : 'room',
|
|
48
|
+
heldOut: Array.isArray(raw.heldOut) ? [...new Set(raw.heldOut.filter(id => typeof id === 'string' && idPattern.test(id)))] : [],
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function save(o, state) {
|
|
53
|
+
const target = filePath(o);
|
|
54
|
+
await mkdir(dirname(target), { recursive: true });
|
|
55
|
+
const { tmp, handle } = await createTemp(target, { mode: 0o600 });
|
|
56
|
+
try {
|
|
57
|
+
try { await handle.writeFile(JSON.stringify(state) + '\n', 'utf8'); await handle.sync(); }
|
|
58
|
+
finally { await handle.close(); }
|
|
59
|
+
await renameWithRetry(tmp, target);
|
|
60
|
+
} catch (e) { await unlink(tmp).catch(() => {}); throw e; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const statusOf = (o, s) => ({
|
|
64
|
+
ok: true,
|
|
65
|
+
enabled: s.enabled,
|
|
66
|
+
external: false,
|
|
67
|
+
lastTick: mem(o).lastTick,
|
|
68
|
+
settings: { 'autoswitch.threshold': { value: s.threshold, isDefault: s.threshold === DEFAULT_THRESHOLD } },
|
|
69
|
+
choice: { next: s.next, home: null },
|
|
70
|
+
heldOut: s.heldOut,
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
export async function readCodexAuto(options = {}) {
|
|
74
|
+
return statusOf(options, await load(options));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Writes are read-modify-write, so two quick posts must not interleave.
|
|
78
|
+
let writes = Promise.resolve();
|
|
79
|
+
|
|
80
|
+
export function applyCodexAuto(body, options = {}) {
|
|
81
|
+
const run = writes.then(() => apply(body, options));
|
|
82
|
+
writes = run.catch(() => {});
|
|
83
|
+
return run;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function apply(body, options) {
|
|
87
|
+
const bad = { ok: false, reason: 'bad_request' };
|
|
88
|
+
if (!body || typeof body !== 'object') return bad;
|
|
89
|
+
const state = await load(options);
|
|
90
|
+
switch (body.action) {
|
|
91
|
+
case 'enable':
|
|
92
|
+
if (typeof body.enabled !== 'boolean') return bad;
|
|
93
|
+
state.enabled = body.enabled;
|
|
94
|
+
break;
|
|
95
|
+
case 'setting':
|
|
96
|
+
if (body.key !== 'autoswitch.threshold' || !validThreshold(body.value)) return bad;
|
|
97
|
+
state.threshold = body.value;
|
|
98
|
+
break;
|
|
99
|
+
case 'next':
|
|
100
|
+
if (body.value !== 'room' && body.value !== 'weekly') return bad;
|
|
101
|
+
state.next = body.value;
|
|
102
|
+
break;
|
|
103
|
+
case 'account':
|
|
104
|
+
if (typeof body.id !== 'string' || !idPattern.test(body.id) || typeof body.enabled !== 'boolean') return bad;
|
|
105
|
+
state.heldOut = state.heldOut.filter(id => id !== body.id);
|
|
106
|
+
if (!body.enabled) state.heldOut.push(body.id);
|
|
107
|
+
break;
|
|
108
|
+
default:
|
|
109
|
+
return bad;
|
|
110
|
+
}
|
|
111
|
+
try { await save(options, state); } catch { return { ok: false, reason: 'write_failed' }; }
|
|
112
|
+
return statusOf(options, state);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Only windows that have not reset count: a reset window's percent is old news.
|
|
116
|
+
const liveWindows = (quota, nowSec) =>
|
|
117
|
+
(quota?.windows ?? []).filter(w => Number.isFinite(w.usedPercent) && (w.resetAt == null || w.resetAt > nowSec));
|
|
118
|
+
const loadOf = live => (live.length ? Math.max(...live.map(w => w.usedPercent)) : null);
|
|
119
|
+
|
|
120
|
+
// When the weekly window resets, if it does within 4 days; otherwise null.
|
|
121
|
+
function weeklyReset(live, nowSec) {
|
|
122
|
+
const w = live.find(x => x.seconds >= 6 * DAY && x.resetAt != null && x.resetAt - nowSec <= 4 * DAY);
|
|
123
|
+
return w ? w.resetAt : null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const hasLogin = row => (row.signedIn === undefined ? row.signedInFilePresent === true : row.signedIn === true);
|
|
127
|
+
|
|
128
|
+
export async function codexAutoTick(options = {}) {
|
|
129
|
+
try {
|
|
130
|
+
const state = await load(options);
|
|
131
|
+
if (!state.enabled) return;
|
|
132
|
+
const m = mem(options);
|
|
133
|
+
const now = options.now ?? Date.now;
|
|
134
|
+
if (now() - m.lastSwitchAt < COOLDOWN_MS) return;
|
|
135
|
+
const nowSec = Math.floor(now() / 1000);
|
|
136
|
+
const threshold = Number(state.threshold);
|
|
137
|
+
const readSelection = options.readSelection ?? readCodexSelection;
|
|
138
|
+
const discover = options.discover ?? discoverCodexProfiles;
|
|
139
|
+
const readQuota = options.readQuota ?? readCodexProfileQuota;
|
|
140
|
+
const select = options.select ?? selectCodexProfile;
|
|
141
|
+
|
|
142
|
+
const selection = await readSelection(options);
|
|
143
|
+
const rows = await discover({ ...options, selection, enableNative: true });
|
|
144
|
+
const home = rows.find(r => r.id === selection.profileId);
|
|
145
|
+
if (!home) return;
|
|
146
|
+
const readOpts = { ...options, selection, enableNative: true };
|
|
147
|
+
const homeQuota = await readQuota(home.id, readOpts);
|
|
148
|
+
// Only a reading taken now says how full an account is: the last good one
|
|
149
|
+
// kept for a failed read is an old number, and acting on it moves sessions
|
|
150
|
+
// for a window that may have reset, or onto an account that has since filled.
|
|
151
|
+
const homeLoad = homeQuota?.ok && !homeQuota.stale ? loadOf(liveWindows(homeQuota, nowSec)) : null;
|
|
152
|
+
if (homeLoad === null || homeLoad < threshold) return;
|
|
153
|
+
|
|
154
|
+
// A row that is the same ChatGPT account shares the quota that just ran out.
|
|
155
|
+
const roster = rows.filter(r => r.id !== home.id && r.available && hasLogin(r)
|
|
156
|
+
&& !state.heldOut.includes(r.id) && r.sameAccountAs !== home.id);
|
|
157
|
+
const fits = [];
|
|
158
|
+
for (const row of roster) { // one at a time: each read may spawn a process
|
|
159
|
+
const quota = await readQuota(row.id, readOpts);
|
|
160
|
+
if (!quota?.ok || quota.stale) continue;
|
|
161
|
+
const live = liveWindows(quota, nowSec);
|
|
162
|
+
const load = loadOf(live) ?? 0;
|
|
163
|
+
if (load < threshold) fits.push({ id: row.id, load, reset: weeklyReset(live, nowSec) });
|
|
164
|
+
}
|
|
165
|
+
if (!fits.length) {
|
|
166
|
+
m.lastTick = { at: now(), event: 'nowhere', reason: 'no_account_with_room' };
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const soon = state.next === 'weekly' ? fits.filter(f => f.reset !== null) : [];
|
|
170
|
+
const pick = soon.length ? soon.sort((a, b) => a.reset - b.reset)[0] : fits.sort((a, b) => a.load - b.load)[0];
|
|
171
|
+
try {
|
|
172
|
+
await select({ id: pick.id, expectedRevision: selection.revision, operationId: randomUUID() }, options);
|
|
173
|
+
} catch (e) {
|
|
174
|
+
if (e?.code === 'selection_conflict') return; // somebody else moved it; look again next tick
|
|
175
|
+
throw e;
|
|
176
|
+
}
|
|
177
|
+
m.lastSwitchAt = now();
|
|
178
|
+
m.lastTick = { at: now(), event: 'switched', to: pick.id, trigger: 'proactive' };
|
|
179
|
+
} catch { /* a failed round is retried on the next tick */ }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let stopLoop = null;
|
|
183
|
+
|
|
184
|
+
export function startCodexAutoLoop(options = {}) {
|
|
185
|
+
if (stopLoop) return stopLoop;
|
|
186
|
+
let running = false;
|
|
187
|
+
const timer = setInterval(async () => {
|
|
188
|
+
if (running) return;
|
|
189
|
+
running = true;
|
|
190
|
+
try { await codexAutoTick(options); } catch { /* the tick never throws; belt and braces */ }
|
|
191
|
+
finally { running = false; }
|
|
192
|
+
}, TICK_MS);
|
|
193
|
+
timer.unref();
|
|
194
|
+
stopLoop = () => { clearInterval(timer); stopLoop = null; };
|
|
195
|
+
return stopLoop;
|
|
196
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Signing a Codex profile in from the deck, without a terminal.
|
|
2
|
+
//
|
|
3
|
+
// `codex login --device-auth` prints a link and a one-time code, then waits for
|
|
4
|
+
// the person to approve it in any browser, on any machine, and writes the login
|
|
5
|
+
// into the home it was started for. That fits a dialog: the deck starts it for
|
|
6
|
+
// one profile's own home, shows the link and the code, and watches the process.
|
|
7
|
+
// The deck never sees the credential: Codex writes it where Codex keeps it.
|
|
8
|
+
//
|
|
9
|
+
// One sign-in per profile at a time, and nothing starts until asked. A browser
|
|
10
|
+
// that cannot reach the machine is no problem, since the code is typed on the
|
|
11
|
+
// page rather than sent back to a local port.
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { forgetCodexReadings } from './codex-native-account.mjs';
|
|
14
|
+
import { resolveCodexProfile } from './codex-profiles.mjs';
|
|
15
|
+
|
|
16
|
+
/** Codex says the code lasts 15 minutes; the process is stopped a minute later. */
|
|
17
|
+
const LIFETIME_MS = 16 * 60_000;
|
|
18
|
+
/** A finished sign-in's answer stays readable this long, then the entry goes. */
|
|
19
|
+
const KEEP_MS = 10 * 60_000;
|
|
20
|
+
const MAX_OUTPUT = 8192;
|
|
21
|
+
|
|
22
|
+
const logins = new Map();
|
|
23
|
+
|
|
24
|
+
/** Strip terminal colour and cursor codes from what Codex prints. */
|
|
25
|
+
const plain = text => text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
|
|
26
|
+
|
|
27
|
+
/** The link and the code out of what `codex login --device-auth` prints. Only an
|
|
28
|
+
* OpenAI sign-in page is ever returned as a link: the dialog turns it into a
|
|
29
|
+
* button, and a line of output is not trusted to say where that button goes. */
|
|
30
|
+
export function parseDeviceLogin(output) {
|
|
31
|
+
const text = plain(String(output));
|
|
32
|
+
const url = text.match(/https:\/\/auth\.openai\.com\/[^\s]*/)?.[0] ?? null;
|
|
33
|
+
const code = text.match(/\b([A-Z0-9]{4}-[A-Z0-9]{4,6})\b/)?.[1] ?? null;
|
|
34
|
+
return { url, code };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function view(entry) {
|
|
38
|
+
return entry
|
|
39
|
+
? { ok: true, state: entry.state, url: entry.url, code: entry.code, expiresAt: entry.expiresAt, reason: entry.reason ?? null }
|
|
40
|
+
: { ok: true, state: 'idle', url: null, code: null, expiresAt: null, reason: null };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Start a sign-in for one profile, or return the one already running. */
|
|
44
|
+
export async function startCodexLogin(id, options = {}) {
|
|
45
|
+
const directory = await resolveCodexProfile(id, options);
|
|
46
|
+
if (!directory) return { ok: false, reason: 'unknown_profile' };
|
|
47
|
+
const running = logins.get(id);
|
|
48
|
+
if (running && ['starting', 'waiting'].includes(running.state)) return view(running);
|
|
49
|
+
|
|
50
|
+
const entry = { state: 'starting', url: null, code: null, expiresAt: null, reason: null, output: '', child: null, timer: null };
|
|
51
|
+
logins.set(id, entry);
|
|
52
|
+
const finish = (state, reason = null) => {
|
|
53
|
+
if (['done', 'failed', 'cancelled', 'expired'].includes(entry.state)) return;
|
|
54
|
+
entry.state = state;
|
|
55
|
+
entry.reason = reason;
|
|
56
|
+
clearTimeout(entry.timer);
|
|
57
|
+
entry.timer = setTimeout(() => { if (logins.get(id) === entry) logins.delete(id); }, KEEP_MS);
|
|
58
|
+
entry.timer.unref?.();
|
|
59
|
+
};
|
|
60
|
+
let child;
|
|
61
|
+
try {
|
|
62
|
+
child = (options.spawn ?? spawn)(options.command ?? 'codex', ['login', '--device-auth'], {
|
|
63
|
+
env: { ...(options.env ?? process.env), CODEX_HOME: directory, NO_COLOR: '1' },
|
|
64
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
65
|
+
shell: (options.platform ?? process.platform) === 'win32',
|
|
66
|
+
windowsHide: true,
|
|
67
|
+
});
|
|
68
|
+
} catch { finish('failed', 'codex_missing'); return view(entry); }
|
|
69
|
+
entry.child = child;
|
|
70
|
+
const onData = chunk => {
|
|
71
|
+
entry.output = (entry.output + chunk.toString()).slice(-MAX_OUTPUT);
|
|
72
|
+
if (entry.state !== 'starting') return;
|
|
73
|
+
const { url, code } = parseDeviceLogin(entry.output);
|
|
74
|
+
if (url && code) {
|
|
75
|
+
entry.url = url;
|
|
76
|
+
entry.code = code;
|
|
77
|
+
entry.state = 'waiting';
|
|
78
|
+
entry.expiresAt = Date.now() + 15 * 60_000;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
child.stdout?.on('data', onData);
|
|
82
|
+
child.stderr?.on('data', onData);
|
|
83
|
+
child.once('error', error => finish('failed', error?.code === 'ENOENT' ? 'codex_missing' : 'login_failed'));
|
|
84
|
+
child.once('close', code => {
|
|
85
|
+
if (entry.state === 'cancelled') return;
|
|
86
|
+
// "Done" waits for the old login's readings to go, so nothing reads them first.
|
|
87
|
+
if (code === 0) void forgetCodexReadings(directory).catch(() => {}).finally(() => finish('done'));
|
|
88
|
+
else finish('failed', entry.state === 'starting' ? 'no_code' : 'login_failed');
|
|
89
|
+
});
|
|
90
|
+
entry.timer = setTimeout(() => {
|
|
91
|
+
if (['starting', 'waiting'].includes(entry.state)) { finish('expired', 'code_expired'); child.kill(); }
|
|
92
|
+
}, options.lifetimeMs ?? LIFETIME_MS);
|
|
93
|
+
entry.timer.unref?.();
|
|
94
|
+
return view(entry);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function codexLoginState(id) {
|
|
98
|
+
return view(logins.get(id));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Stop a sign-in that is still waiting, so closing the dialog leaves no process. */
|
|
102
|
+
export function cancelCodexLogin(id) {
|
|
103
|
+
const entry = logins.get(id);
|
|
104
|
+
if (!entry || !['starting', 'waiting'].includes(entry.state)) return view(entry);
|
|
105
|
+
entry.state = 'cancelled';
|
|
106
|
+
clearTimeout(entry.timer);
|
|
107
|
+
entry.timer = setTimeout(() => { if (logins.get(id) === entry) logins.delete(id); }, KEEP_MS);
|
|
108
|
+
entry.timer.unref?.();
|
|
109
|
+
try { entry.child?.kill(); } catch { /* already gone */ }
|
|
110
|
+
return view(entry);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** For tests: forget every sign-in and stop the ones still running. */
|
|
114
|
+
export function resetCodexLogins() {
|
|
115
|
+
for (const entry of logins.values()) { clearTimeout(entry.timer); try { entry.child?.kill(); } catch { /* gone */ } }
|
|
116
|
+
logins.clear();
|
|
117
|
+
}
|