ccdeck 4.0.2 → 4.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/web/assets/AccountBridge-Cx7no9kK.js +1 -0
  2. package/dist/web/assets/{AccountSection-crq1VjX0.js → AccountSection-HmlI65gN.js} +1 -1
  3. package/dist/web/assets/{BrowserWatchModal-CoXeeb2o.js → BrowserWatchModal-DwY9hX-u.js} +1 -1
  4. package/dist/web/assets/{FeedbackConversations-BDjrxpxf.js → FeedbackConversations-6S1QZR6S.js} +1 -1
  5. package/dist/web/assets/{IntegrationModal-4Z8_QVBa.js → IntegrationModal-a8CAd22m.js} +1 -1
  6. package/dist/web/assets/{IntegrationSkeleton-DHuH_POu.js → IntegrationSkeleton-C2RiqqMA.js} +1 -1
  7. package/dist/web/assets/{RadioPanel-Dw3zruRE.js → RadioPanel-CyJsFSkf.js} +1 -1
  8. package/dist/web/assets/StageShell-DXcdcjPI.js +4 -0
  9. package/dist/web/assets/{TrafficRadar--OAIaujE.js → TrafficRadar-CEbp0Yi7.js} +1 -1
  10. package/dist/web/assets/{UsageHistoryModal-D1hw3AaJ.js → UsageHistoryModal-i16x6suY.js} +1 -1
  11. package/dist/web/assets/{app-82JtqhPe.css → app-BW8ALk8H.css} +1 -1
  12. package/dist/web/assets/{app-DiIDGQPy.js → app-C0usT8Zy.js} +95 -93
  13. package/dist/web/assets/{index-BXBkLnYy.js → index-BQWffZlx.js} +1 -1
  14. package/dist/web/assets/{inspector-status-pane-DP7kOBus.js → inspector-status-pane-DD3QOXE6.js} +1 -1
  15. package/dist/web/assets/{screens-CqpMhDCL.js → screens-DAn5OlXe.js} +1 -1
  16. package/dist/web/assets/stage-board-kUkV8N-4.js +2 -0
  17. package/dist/web/assets/{use-account-DskceWF8.js → use-account-x7fuCA6S.js} +1 -1
  18. package/dist/web/index.html +3 -3
  19. package/package.json +1 -1
  20. package/release-notes.json +30 -0
  21. package/src/server/claude-dir.mjs +93 -6
  22. package/src/server/claude-install.mjs +315 -0
  23. package/src/server/claude-reset-credits.mjs +77 -11
  24. package/src/server/cswap-admin.mjs +73 -4
  25. package/src/server/index.mjs +10 -0
  26. package/src/server/pro-engine-client.mjs +7 -3
  27. package/src/server/pro-engine-terminal.mjs +22 -2
  28. package/src/server/request-gates.mjs +3 -0
  29. package/dist/web/assets/AccountBridge-BWSoT0Lr.js +0 -1
  30. package/dist/web/assets/StageShell-Dn1RGcsF.js +0 -4
  31. package/dist/web/assets/stage-board-0PYMffFC.js +0 -2
@@ -0,0 +1,315 @@
1
+ // Installing Claude Code from the deck, for the two places that find none: a
2
+ // session pane told `agent-missing`, and an Accounts sign-in whose `claude`
3
+ // could not be run. Both offer Install Claude Code, which is this.
4
+ //
5
+ // GET /api/claude-install { ok, state: idle|running|done|failed, id?, reason?, detail?, command, blocked? }
6
+ // POST /api/claude-install start one: { ok: true, id }, or 409 { ok: false, code }
7
+ //
8
+ // THE OFFICIAL INSTALLER, AND NOTHING OF OUR OWN. What runs is the script
9
+ // Anthropic's setup page labels Recommended, the same one `command` names for
10
+ // people who would rather paste it into a terminal: install.sh through bash on
11
+ // macOS and Linux, install.ps1 through Windows PowerShell on Windows. It needs
12
+ // no administrator, and it puts `claude` in ~/.local/bin (claude.exe in
13
+ // %USERPROFILE%\.local\bin on Windows), the first place the deck's own list
14
+ // looks (claude-dir.mjs).
15
+ //
16
+ // DOWNLOADED, THEN RUN AS A FILE. https only, under a deadline and a size cap,
17
+ // into a 0600 file inside a fresh 0700 folder of its own, run as an argument
18
+ // vector and never through a shell string, and the folder removed afterwards
19
+ // whatever happened.
20
+ //
21
+ // NOTHING OF IT IS LOGGED. Neither the script nor what it prints. The last few
22
+ // lines of its output are kept in memory for one reason, a failure's, and are
23
+ // shown only to the page that asked, with the home folder written as ~.
24
+ //
25
+ // DONE MEANS THE DECK CAN RUN IT. An installer that exits 0 is not enough: the
26
+ // install counts only when the deck's own resolver (claude-identity.mjs) now
27
+ // finds `claude`, the one the session pane and the sign-in will go on to run.
28
+ //
29
+ // ONE AT A TIME. The job is one value per deck that every tab reads; a second
30
+ // start while it runs is refused, and the outcome stays readable afterwards
31
+ // under the id it was started with, so a page shows only an outcome it watched.
32
+ //
33
+ // AGENTS_DECK_NO_INSTALL=1 and AGENTS_DECK_NO_DOWNLOAD=1 turn the download
34
+ // off, as they do for tmux and the engine: the status says so, and the page
35
+ // offers the command to run instead.
36
+ import { spawn as nodeSpawn } from "node:child_process";
37
+ import { randomBytes } from "node:crypto";
38
+ import { existsSync, promises as fs } from "node:fs";
39
+ import { homedir, tmpdir } from "node:os";
40
+ import { join, win32 as winPath } from "node:path";
41
+ import { adminClaudeBin } from "./claude-identity.mjs";
42
+ import { killTree, watchChild } from "./exec-children.mjs";
43
+ import { pathLookup } from "./exec-spec.mjs";
44
+ import { readBody, send } from "./http-io.mjs";
45
+
46
+ export const CLAUDE_INSTALL_ROUTE = "/api/claude-install";
47
+
48
+ /** The script, as Anthropic publishes it for each platform. */
49
+ export const INSTALL_SCRIPTS = Object.freeze({
50
+ posix: "https://claude.ai/install.sh",
51
+ win32: "https://claude.ai/install.ps1",
52
+ });
53
+
54
+ /** The scripts are a few KB; anything near this is not one. */
55
+ export const INSTALL_SCRIPT_MAX = 1024 * 1024;
56
+ /** The script's download. */
57
+ export const DOWNLOAD_TIMEOUT_MS = 60_000;
58
+ /** The whole install: the installer fetches Claude Code itself, tens of MB. */
59
+ export const INSTALL_TIMEOUT_MS = 10 * 60_000;
60
+ /** How much of the installer's output a failure keeps. */
61
+ export const TAIL_LINES = 5;
62
+ /** And how much of it is held while it runs, from its end. */
63
+ const TAIL_BYTES = 8 * 1024;
64
+ /** A line of it, at most, as a failure shows it. */
65
+ const LINE_MAX = 240;
66
+ /** The requests carry no body worth reading; a small cap answers 413 above it. */
67
+ const BODY_LIMIT = 1024;
68
+
69
+ /** The manual command, the one Anthropic's setup page labels Recommended. */
70
+ export function claudeInstallCommand(platform = process.platform) {
71
+ return platform === "win32"
72
+ ? `irm ${INSTALL_SCRIPTS.win32} | iex`
73
+ : `curl -fsSL ${INSTALL_SCRIPTS.posix} | bash`;
74
+ }
75
+
76
+ /** Why no download may start here, or null. */
77
+ export function claudeInstallBlocked(env = process.env) {
78
+ return env.AGENTS_DECK_NO_INSTALL === "1" || env.AGENTS_DECK_NO_DOWNLOAD === "1" ? "download-disabled" : null;
79
+ }
80
+
81
+ /**
82
+ * The program and its arguments for the downloaded `file`: bash on macOS and
83
+ * Linux, Windows PowerShell from System32 on Windows (by its full path, so
84
+ * nothing on PATH or in the deck's folder can stand in for it).
85
+ */
86
+ export function installerArgv(platform, file, { env = process.env, exists = existsSync } = {}) {
87
+ if (platform === "win32") {
88
+ const root = env.SystemRoot || env.SYSTEMROOT || env.systemroot || "C:\\Windows";
89
+ const ps = winPath.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
90
+ return { file: ps, args: ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file] };
91
+ }
92
+ return { file: exists("/bin/bash") ? "/bin/bash" : "bash", args: [file] };
93
+ }
94
+
95
+ /**
96
+ * Whether the deck's own resolver finds `claude` now: the path the sign-in
97
+ * and the quota read run (adminClaudeBin, over claude-dir.mjs's list), there
98
+ * on disk, or a bare name PATH holds.
99
+ */
100
+ export function deckFindsClaude({
101
+ platform = process.platform, env = process.env, home = homedir(), exists = existsSync,
102
+ } = {}) {
103
+ const bin = adminClaudeBin(platform, env, home, exists);
104
+ if (/[\\/]/.test(bin)) return Boolean(exists(bin));
105
+ return pathLookup(bin, platform, { pathEnv: env.PATH ?? env.Path ?? env.path ?? "", exists }) !== null;
106
+ }
107
+
108
+ const ESCAPES = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-Z\\-_]/g;
109
+ const CONTROLS = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;
110
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
111
+
112
+ /**
113
+ * The last lines of what the installer printed, as a failure shows them: no
114
+ * terminal escapes or control characters, a progress line's carriage returns
115
+ * read as the line it ended on, blank lines dropped, each line cut short, and
116
+ * the home folder written as ~.
117
+ */
118
+ export function outputTail(text, { home = homedir(), platform = process.platform, lines = TAIL_LINES } = {}) {
119
+ const clean = String(text ?? "").replace(ESCAPES, "");
120
+ const kept = clean.split(/\r?\n/)
121
+ .map(line => line.split("\r").filter(part => part.trim()).at(-1) ?? "")
122
+ .map(line => line.replace(CONTROLS, "").trimEnd())
123
+ .filter(line => line.trim())
124
+ .slice(-lines)
125
+ .map(line => (line.length > LINE_MAX ? `${line.slice(0, LINE_MAX - 1)}…` : line));
126
+ let out = kept.join("\n");
127
+ if (home && home.length > 1) {
128
+ const flags = platform === "win32" ? "gi" : "g";
129
+ out = out.replace(new RegExp(escapeRe(home), flags), "~");
130
+ if (platform === "win32") out = out.replace(new RegExp(escapeRe(home.replace(/\\/g, "/")), flags), "~");
131
+ }
132
+ return out;
133
+ }
134
+
135
+ class InstallFailure extends Error {
136
+ constructor(reason, detail = "") {
137
+ super(reason);
138
+ this.reason = reason;
139
+ this.detail = detail;
140
+ }
141
+ }
142
+
143
+ /** The script's text, under the deadline and the cap, from an https address
144
+ * that stayed https. */
145
+ async function download(url, { fetchImpl, timeoutMs }) {
146
+ if (new URL(url).protocol !== "https:") throw new InstallFailure("download-failed");
147
+ let res;
148
+ try {
149
+ res = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
150
+ } catch {
151
+ throw new InstallFailure("download-failed");
152
+ }
153
+ if (!res?.ok) throw new InstallFailure("download-failed");
154
+ // A redirect may not leave https.
155
+ if (res.url && new URL(res.url).protocol !== "https:") throw new InstallFailure("download-failed");
156
+ const declared = Number(res.headers?.get?.("content-length"));
157
+ if (Number.isFinite(declared) && declared > INSTALL_SCRIPT_MAX) throw new InstallFailure("download-failed");
158
+ const chunks = [];
159
+ let size = 0;
160
+ try {
161
+ if (res.body && typeof res.body.getReader === "function") {
162
+ const reader = res.body.getReader();
163
+ for (;;) {
164
+ const { done, value } = await reader.read();
165
+ if (done) break;
166
+ size += value.byteLength;
167
+ if (size > INSTALL_SCRIPT_MAX) {
168
+ try { await reader.cancel(); } catch { /* already closed */ }
169
+ throw new InstallFailure("download-failed");
170
+ }
171
+ chunks.push(Buffer.from(value));
172
+ }
173
+ } else {
174
+ const whole = Buffer.from(await res.arrayBuffer());
175
+ size = whole.byteLength;
176
+ if (size > INSTALL_SCRIPT_MAX) throw new InstallFailure("download-failed");
177
+ chunks.push(whole);
178
+ }
179
+ } catch (err) {
180
+ if (err instanceof InstallFailure) throw err;
181
+ throw new InstallFailure("download-failed");
182
+ }
183
+ const body = Buffer.concat(chunks);
184
+ // An empty answer, or a web page where the script should be (a sign-in or
185
+ // a challenge in front of it), is not a script to run.
186
+ const head = body.subarray(0, 512).toString("utf8").trimStart().toLowerCase();
187
+ if (size === 0 || head.startsWith("<!doctype") || head.startsWith("<html")) throw new InstallFailure("download-failed");
188
+ return body;
189
+ }
190
+
191
+ /** Runs the installer to its end, its deadline, or a failure to start. */
192
+ function runInstaller({ spawnImpl, argv, cwd, env, timeoutMs, platform }) {
193
+ return new Promise((resolve) => {
194
+ let tail = "";
195
+ const keep = (chunk) => { tail = (tail + chunk.toString("utf8")).slice(-TAIL_BYTES); };
196
+ let child;
197
+ try {
198
+ child = spawnImpl(argv.file, argv.args, {
199
+ cwd, env, shell: false, windowsHide: true,
200
+ stdio: ["ignore", "pipe", "pipe"],
201
+ // Its own process group on POSIX, so the deadline stops what it started too.
202
+ detached: platform !== "win32",
203
+ });
204
+ } catch {
205
+ resolve({ started: false, code: null, timedOut: false, tail });
206
+ return;
207
+ }
208
+ watchChild(child, { processGroup: platform !== "win32" });
209
+ let timedOut = false;
210
+ let settled = false;
211
+ const timer = setTimeout(() => { timedOut = true; killTree(child, "SIGKILL"); }, timeoutMs);
212
+ timer.unref?.();
213
+ const finish = (out) => {
214
+ if (settled) return;
215
+ settled = true;
216
+ clearTimeout(timer);
217
+ resolve({ ...out, timedOut, tail });
218
+ };
219
+ child.stdout?.on("data", keep);
220
+ child.stderr?.on("data", keep);
221
+ child.on("error", () => finish({ started: false, code: null }));
222
+ child.on("close", (code) => finish({ started: true, code }));
223
+ });
224
+ }
225
+
226
+ /**
227
+ * The deck's one installer. Every dependency is a parameter so the suite runs
228
+ * the whole job with a fake download and a fake installer, never the network
229
+ * and never a real script.
230
+ */
231
+ export function createClaudeInstaller({
232
+ platform = process.platform,
233
+ env = process.env,
234
+ home = () => homedir(),
235
+ tmp = () => tmpdir(),
236
+ fetchImpl = (...a) => globalThis.fetch(...a),
237
+ spawnImpl = nodeSpawn,
238
+ exists = existsSync,
239
+ found = () => deckFindsClaude({ platform, env, home: home(), exists }),
240
+ downloadTimeoutMs = DOWNLOAD_TIMEOUT_MS,
241
+ installTimeoutMs = INSTALL_TIMEOUT_MS,
242
+ } = {}) {
243
+ let job = null; // { id, state, reason?, detail?, run }
244
+
245
+ const run = async (current) => {
246
+ let dir = null;
247
+ try {
248
+ dir = await fs.mkdtemp(join(tmp(), "ccdeck-claude-install-"));
249
+ if (platform !== "win32") await fs.chmod(dir, 0o700);
250
+ const url = platform === "win32" ? INSTALL_SCRIPTS.win32 : INSTALL_SCRIPTS.posix;
251
+ const script = await download(url, { fetchImpl, timeoutMs: downloadTimeoutMs });
252
+ const file = join(dir, platform === "win32" ? "install.ps1" : "install.sh");
253
+ await fs.writeFile(file, script, { mode: 0o600, flag: "wx" });
254
+ const out = await runInstaller({
255
+ spawnImpl, platform, env, cwd: dir, timeoutMs: installTimeoutMs,
256
+ argv: installerArgv(platform, file, { env, exists }),
257
+ });
258
+ const detail = outputTail(out.tail, { home: home(), platform });
259
+ if (!out.started) throw new InstallFailure("start-failed");
260
+ if (out.timedOut) throw new InstallFailure("timed-out", detail);
261
+ if (out.code !== 0) throw new InstallFailure("exit-failed", detail);
262
+ if (!found()) throw new InstallFailure("installed-but-not-found");
263
+ Object.assign(current, { state: "done" });
264
+ } catch (err) {
265
+ const failure = err instanceof InstallFailure ? err : new InstallFailure("failed");
266
+ Object.assign(current, { state: "failed", reason: failure.reason, ...(failure.detail ? { detail: failure.detail } : {}) });
267
+ } finally {
268
+ if (dir) await fs.rm(dir, { recursive: true, force: true }).catch(() => {});
269
+ }
270
+ };
271
+
272
+ return Object.freeze({
273
+ /** Where the install stands, and the command for doing it by hand. */
274
+ status() {
275
+ const blocked = claudeInstallBlocked(env);
276
+ const out = { state: job?.state ?? "idle", command: claudeInstallCommand(platform), shell: platform === "win32" ? "powershell" : "terminal" };
277
+ if (job) out.id = job.id;
278
+ if (job?.reason) out.reason = job.reason;
279
+ if (job?.detail) out.detail = job.detail;
280
+ if (blocked) out.blocked = blocked;
281
+ return out;
282
+ },
283
+ /** Starts one, unless one runs or downloads are off. Never awaits it. */
284
+ start() {
285
+ if (job?.state === "running") return { ok: false, code: "running" };
286
+ const blocked = claudeInstallBlocked(env);
287
+ if (blocked) return { ok: false, code: blocked };
288
+ const current = { id: randomBytes(8).toString("hex"), state: "running" };
289
+ job = current;
290
+ current.run = run(current);
291
+ return { ok: true, id: current.id };
292
+ },
293
+ /** The running job's end, for the suite. */
294
+ settled: () => job?.run ?? Promise.resolve(),
295
+ });
296
+ }
297
+
298
+ let shared = null;
299
+ /** The deck's installer, made on first use. */
300
+ export function claudeInstaller() {
301
+ shared ??= createClaudeInstaller();
302
+ return shared;
303
+ }
304
+
305
+ /** GET: where the install stands. */
306
+ export async function handleClaudeInstallStatus(_req, res, { installer = claudeInstaller() } = {}) {
307
+ return send(res, 200, { ok: true, ...installer.status() });
308
+ }
309
+
310
+ /** POST: start one. 409 names why not: one runs already, or downloads are off. */
311
+ export async function handleClaudeInstallStart(req, res, { installer = claudeInstaller() } = {}) {
312
+ try { await readBody(req, res, BODY_LIMIT); } catch { return; /* answered 413 already */ }
313
+ const out = installer.start();
314
+ return send(res, out.ok ? 200 : 409, out);
315
+ }
@@ -12,7 +12,17 @@
12
12
  // decision, taken in Claude itself. So nothing here reads a grant's `id`, its
13
13
  // `label`, `next_grant_id` or `event_props`: an id is a redemption handle, and
14
14
  // a value that is never read cannot end up in a response, a log line or a test
15
- // fixture. What survives the parse is a count and two instants per grant.
15
+ // fixture. What survives the parse is a count, two instants and a kind per
16
+ // grant, the kind one word from RESET_KINDS.
17
+ //
18
+ // WHICH LIMIT A RESET CLEARS. Claude names its grants by what they give back —
19
+ // a 5-hour reset, a weekly one, a full one, and a Fable reset that returns what
20
+ // Fable used to the weekly limit — and a panel that called them all "limit
21
+ // resets" left nobody able to tell which quota one would clear (user feedback).
22
+ // The kind is worked out the way Claude Code works it out (2.1.328), from three
23
+ // fields and nothing else: `gives_back_weekly`, `type` and `clears`. A grant
24
+ // whose fields say nothing this deck recognises is "unknown", which the panel
25
+ // words as the neutral limit reset it always printed — never a guess.
16
26
  //
17
27
  // FAIL CLOSED. The shape below is Claude Code's own (its zod schema for this
18
28
  // block, read out of the 2.1.283 binary), and it can change without notice. A
@@ -37,8 +47,52 @@ export const MAX_GRANT_RECORDS = 200;
37
47
  */
38
48
  export const MAX_AVAILABLE_RESETS = 50;
39
49
 
50
+ /**
51
+ * What a grant can be, in the order the Usage panel lists them: the kinds
52
+ * Claude names, then the grant nothing here could name.
53
+ */
54
+ export const RESET_KINDS = Object.freeze(["fable", "full", "weekly", "session", "unknown"]);
55
+
56
+ /** The `type` values Claude Code knows. Anything else is not read. */
57
+ const KNOWN_TYPES = new Set(["session", "weekly", "full"]);
58
+
59
+ /** The limits a grant's `clears` may name, as Claude Code's schema lists them. */
60
+ const KNOWN_LIMITS = new Set([
61
+ "five_hour", "seven_day", "seven_day_overage_included", "seven_day_opus", "seven_day_sonnet",
62
+ "seven_day_cowork", "seven_day_omelette", "seven_day_oauth_apps",
63
+ ]);
64
+
40
65
  const isCount = (v) => Number.isInteger(v) && v >= 0;
41
66
 
67
+ /**
68
+ * Which limit a grant clears, as one of RESET_KINDS.
69
+ *
70
+ * Claude Code's rule: a grant that gives back weekly usage is a Fable reset;
71
+ * otherwise its `type`, when it has one; otherwise its `clears` — the 5-hour
72
+ * limit alone is a session reset, weekly limits without the 5-hour one a weekly
73
+ * reset, and both a full one.
74
+ *
75
+ * Each field is read only when it is what that rule expects: `gives_back_weekly`
76
+ * a boolean, `type` one of the three known words, `clears` a non-empty list of
77
+ * known limit names. A list with anything else in it is not read at all,
78
+ * because a grant that clears a limit this deck has never heard of may clear
79
+ * more than the names it does know. Claude Code calls a grant with nothing to
80
+ * go on a full reset; this deck calls it unknown, which is every grant sent
81
+ * before these fields existed.
82
+ */
83
+ function grantKind(g) {
84
+ if (g.gives_back_weekly === true) return "fable";
85
+ if (KNOWN_TYPES.has(g.type)) return g.type;
86
+ const clears = g.clears;
87
+ if (!Array.isArray(clears) || clears.length === 0) return "unknown";
88
+ if (!clears.every((c) => typeof c === "string" && KNOWN_LIMITS.has(c))) return "unknown";
89
+ const fiveHour = clears.includes("five_hour");
90
+ const others = clears.some((c) => c !== "five_hour");
91
+ if (fiveHour && !others) return "session";
92
+ if (others && !fiveHour) return "weekly";
93
+ return "full";
94
+ }
95
+
42
96
  /**
43
97
  * A grant's start or end as epoch milliseconds: `null` when it has none, and
44
98
  * `undefined` when it has one nobody can read. The difference matters — an
@@ -67,7 +121,7 @@ function readGrant(g) {
67
121
  const startsAt = bound(g.starts_at);
68
122
  const endsAt = bound(g.ends_at);
69
123
  if (startsAt === undefined || endsAt === undefined) return null;
70
- return { resetsLeft: g.resets_left, paused: g.paused, startsAt, endsAt };
124
+ return { resetsLeft: g.resets_left, paused: g.paused, startsAt, endsAt, kind: grantKind(g) };
71
125
  }
72
126
 
73
127
  /**
@@ -93,8 +147,11 @@ export function readResetGrants(block) {
93
147
  }
94
148
 
95
149
  /**
96
- * What the Usage panel shows, from grants readResetGrants accepted: how many
97
- * resets can be spent at `now`, and when the first of them lapses.
150
+ * What the Usage panel shows, from grants readResetGrants accepted: for each
151
+ * kind of reset the account can spend at `now`, how many, and when the first
152
+ * of them lapses — `[{ kind, availableCount, nextExpiryAt }]`, in RESET_KINDS'
153
+ * order, with only the kinds that have one. An eligible account with nothing
154
+ * to spend is an empty list; null is "not known", as before.
98
155
  *
99
156
  * A grant counts when it is not paused, has resets left, has started and has
100
157
  * not ended. `usable_now` is deliberately not consulted: Claude sets it false
@@ -103,7 +160,11 @@ export function readResetGrants(block) {
103
160
  * owns.
104
161
  *
105
162
  * `nextExpiryAt` is epoch milliseconds, like the Codex row's, and null when no
106
- * counted grant has an end.
163
+ * counted grant of that kind has an end.
164
+ *
165
+ * The cap holds for every group and for all of them together: more than
166
+ * MAX_AVAILABLE_RESETS in either reads as a malformed block, and the whole
167
+ * answer is null rather than one implausible line beside believable ones.
107
168
  *
108
169
  * Recomputed at every read rather than frozen at fetch time, because the
109
170
  * inventory is held between fetches: a grant that ends while it is held has to
@@ -111,17 +172,22 @@ export function readResetGrants(block) {
111
172
  */
112
173
  export function availableResetCredits(grants, now) {
113
174
  if (!Array.isArray(grants)) return null;
114
- let availableCount = 0;
115
- let nextExpiryAt = null;
175
+ const byKind = new Map();
176
+ let total = 0;
116
177
  for (const g of grants) {
117
178
  if (g.paused || g.resetsLeft <= 0) continue;
118
179
  if (g.startsAt !== null && g.startsAt > now) continue;
119
180
  if (g.endsAt !== null && g.endsAt <= now) continue;
120
- availableCount += g.resetsLeft;
121
- if (g.endsAt !== null && (nextExpiryAt === null || g.endsAt < nextExpiryAt)) nextExpiryAt = g.endsAt;
181
+ const kind = RESET_KINDS.includes(g.kind) ? g.kind : "unknown";
182
+ const group = byKind.get(kind) ?? { kind, availableCount: 0, nextExpiryAt: null };
183
+ group.availableCount += g.resetsLeft;
184
+ if (g.endsAt !== null && (group.nextExpiryAt === null || g.endsAt < group.nextExpiryAt)) group.nextExpiryAt = g.endsAt;
185
+ byKind.set(kind, group);
186
+ total += g.resetsLeft;
122
187
  }
123
- if (availableCount > MAX_AVAILABLE_RESETS) return null;
124
- return { availableCount, nextExpiryAt };
188
+ const groups = RESET_KINDS.filter((k) => byKind.has(k)).map((k) => byKind.get(k));
189
+ if (total > MAX_AVAILABLE_RESETS || groups.some((g) => g.availableCount > MAX_AVAILABLE_RESETS)) return null;
190
+ return groups;
125
191
  }
126
192
 
127
193
  /** Both of the above, for a response read once and shown straight away. */
@@ -416,9 +416,15 @@ let _starting = null;
416
416
 
417
417
  export function loginState() {
418
418
  if (!_login) return { state: "idle" };
419
- const { state, step, url, error, account, expiresAt, restore } = _login;
419
+ const { state, step, url, error, account, expiresAt, restore, wrongAccount } = _login;
420
420
  return {
421
421
  state, url: url ?? null, error: error ?? null, account: account ?? null, expiresAt: expiresAt ?? null,
422
+ // Who signed in instead of the account this sign-in was started for, and
423
+ // that account — set only on the `failed` that refuseOtherAccount writes,
424
+ // so the dialog can name both in the reader's language. Not `reason`:
425
+ // every refusal spreads this object AFTER its own reason, and a field of
426
+ // that name here would overwrite it.
427
+ wrongAccount: wrongAccount ?? null,
422
428
  // Where inside `registering` the flow is — see LOGIN_STEPS. Null before it
423
429
  // and on a failure that happened before it, and left on the step that was
424
430
  // running when anything after it failed, which is how the dialog knows
@@ -619,6 +625,10 @@ async function spawnLogin(email) {
619
625
  // account than the store records: the restore puts THAT one back.
620
626
  previousActive: before.liveNum,
621
627
  previousEmail: identity?.email ?? null,
628
+ // The account this sign-in was started FOR, when it was started for one —
629
+ // "Sign in again" on an account whose login expired. Null for the plain
630
+ // Add, which takes whoever signs in. See refuseOtherAccount.
631
+ wanted: email ?? null,
622
632
  before,
623
633
  url: null,
624
634
  error: null,
@@ -755,6 +765,10 @@ function loginFailureText(r) {
755
765
  * with; the done handler simply drops it.
756
766
  */
757
767
  async function registerSignedIn(flow, identity) {
768
+ // Asked before anything is written: `cswap add` records whoever is signed in,
769
+ // so a sign-in started for one account that came back as another would add
770
+ // or refresh THAT one and leave the account the user meant to fix as it was.
771
+ if (flow.wanted && !sameAddress(identity?.email, flow.wanted)) return refuseOtherAccount(flow, identity);
758
772
  // Before the lock, not inside it: waiting for another change to the store to
759
773
  // finish is part of saving this one, and the dialog says so rather than
760
774
  // going on claiming the sign-in is still being confirmed.
@@ -813,6 +827,42 @@ async function registerSignedIn(flow, identity) {
813
827
  });
814
828
  }
815
829
 
830
+ /** The sentence a sign-in that came back as another account ends with: the
831
+ * dialog names both accounts from `wrongAccount`, and this is for anything
832
+ * that reads only `error`. The same words as admin-failure.ts's REASONS row. */
833
+ const WRONG_ACCOUNT_TEXT = "a different account signed in, so nothing was saved";
834
+
835
+ /**
836
+ * A sign-in for one account that came back as another: nothing is recorded,
837
+ * and the machine goes back to the account it was on, exactly as a cancel
838
+ * puts it back.
839
+ *
840
+ * "Sign in again" on an expired account pre-fills its address, and the page
841
+ * still lets the user pick any account the browser is signed into. Taking that
842
+ * one would add it — or refresh it, if the deck already holds it — while the
843
+ * expired account stays expired, under a success card that names somebody
844
+ * else. So no `cswap add`, and no store write of any kind besides the restore.
845
+ *
846
+ * The restore is not optional here: `claude auth login` has already replaced
847
+ * Claude Code's live login with the account that signed in, and nothing else
848
+ * would move it back.
849
+ */
850
+ async function refuseOtherAccount(flow, identity) {
851
+ return withStoreLock(async () => {
852
+ flow.restore = await restoreActive(flow.previousActive);
853
+ invalidateClaudeAccountsCache();
854
+ // Left on `confirm`, the stage that found it: the account was confirmed,
855
+ // and it was the wrong one.
856
+ flow.step = "confirm";
857
+ flow.error = WRONG_ACCOUNT_TEXT;
858
+ flow.wrongAccount = { signedIn: identity?.email ?? "", wanted: flow.wanted };
859
+ // Last, because the dialog stops polling on it: everything it reads about
860
+ // this ending has to be on the flow by then.
861
+ flow.state = "failed";
862
+ return { ok: false, reason: "wrong_account", ...loginState() };
863
+ });
864
+ }
865
+
816
866
  /**
817
867
  * Hand the code back, then register whatever it signed us in as.
818
868
  *
@@ -906,6 +956,21 @@ export async function cancelLogin() {
906
956
  /** Nothing to put back, or it is already back: the shape every caller reads. */
907
957
  const RESTORED = Object.freeze({ restored: true, activeNum: null, activeEmail: null, detail: null });
908
958
 
959
+ /**
960
+ * Whether slot `num` is back in front: in the store AND as Claude Code's live
961
+ * login.
962
+ *
963
+ * The store alone answered this, and `claude auth login` never touches the
964
+ * store: a sign-in that completed in the browser and was then cancelled, or
965
+ * refused as the wrong account, leaves activeAccountNumber where it was while
966
+ * every Claude Code session runs as whoever just signed in. The store read
967
+ * "already back" and the switch that would have put the login back never ran.
968
+ * `liveNum` is the store's own number when no live login can be read, so this
969
+ * asks nothing more of a machine where the two cannot differ.
970
+ */
971
+ const backOn = (store, num) =>
972
+ String(store.activeNum) === String(num) && String(store.liveNum) === String(num);
973
+
909
974
  /**
910
975
  * Put the account that was active before the login back in front — and ANSWER
911
976
  * whether it went back (#951).
@@ -935,11 +1000,15 @@ const RESTORED = Object.freeze({ restored: true, activeNum: null, activeEmail: n
935
1000
  async function restoreActive(num) {
936
1001
  if (num == null) return RESTORED;
937
1002
  const after = await readStore();
938
- if (String(after.activeNum) === String(num)) return RESTORED;
1003
+ if (backOn(after, num)) return RESTORED;
939
1004
  const r = await run(await cswapBin(), ["switch", String(num)], { timeout: 30_000 });
940
1005
  const now = await readStore();
941
- if (String(now.activeNum) === String(num)) return RESTORED;
942
- const active = now.activeNum == null ? null : String(now.activeNum);
1006
+ if (backOn(now, num)) return RESTORED;
1007
+ // Who the machine is on: Claude Code's login when that is what did not come
1008
+ // back, and null for one the store does not hold — "could not be put back,
1009
+ // check which account" is then the true sentence, not a slot that is wrong.
1010
+ const on = String(now.liveNum) !== String(num) ? now.liveNum : now.activeNum;
1011
+ const active = on == null ? null : String(on);
943
1012
  return {
944
1013
  restored: false,
945
1014
  activeNum: active,
@@ -205,6 +205,9 @@ import {
205
205
  handleEngineStatus, handleEngineAction,
206
206
  } from "./terminal-routes.mjs";
207
207
  import { installTerminalUpgrade } from "./terminal-socket.mjs";
208
+ // Claude Code's own installer, run from the deck where a session pane or a
209
+ // sign-in finds no `claude` (claude-install.mjs).
210
+ import { handleClaudeInstallStart, handleClaudeInstallStatus } from "./claude-install.mjs";
208
211
  // Whether this deck's platform has the Command Panel, which Settings' switch
209
212
  // follows: Linux and macOS; on Windows only the test-only preview, which no
210
213
  // production entry can ask for (command-panel-platform.mjs).
@@ -580,6 +583,13 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
580
583
  // install from the registry or from a file, a cancel and a remove.
581
584
  if (req.method === "GET" && url.pathname === "/api/terminal/engine") return guard(handleEngineStatus(req, res, terminal), res);
582
585
  if (req.method === "POST" && url.pathname.startsWith("/api/terminal/engine/")) return guard(handleEngineAction(req, res, url.pathname.slice("/api/terminal/engine/".length), terminal), res);
586
+ // Claude Code's install, beside the engine's and behind the same gates:
587
+ // the read is in GUARDED_READS, the start is a mutation like any other.
588
+ // Not under the Command Panel's switch, since the Accounts sign-in offers
589
+ // it as well (claude-install.mjs). Spelled out, as every route here is,
590
+ // so the gate tests that read the routes from this source see it.
591
+ if (req.method === "GET" && url.pathname === "/api/claude-install") return guard(handleClaudeInstallStatus(req, res), res);
592
+ if (req.method === "POST" && url.pathname === "/api/claude-install") return guard(handleClaudeInstallStart(req, res), res);
583
593
  // The ccdeck account (account-flag.mjs). Switched off, each of these is
584
594
  // the 404 below, word for word, and nothing of the account is loaded. The
585
595
  // two reads are in GUARDED_READS; the POSTs are mutations like any other.
@@ -2,6 +2,7 @@
2
2
  import { spawn } from 'node:child_process';
3
3
  import { randomBytes } from 'node:crypto';
4
4
  import { EventEmitter } from 'node:events';
5
+ import { engineClaudeHint } from './claude-dir.mjs';
5
6
  import { ENGINE_PROTOCOL, ENGINE_MAX_FRAME, verifyEngineInstallation } from './pro-engine-install.mjs';
6
7
 
7
8
  const fail = (code, message = 'The terminal engine is unavailable.') => Object.assign(new Error(message), { code });
@@ -30,11 +31,14 @@ export const TERMINAL_OPT_IN = 'CCDECK_ENGINE_TERMINAL';
30
31
  * The engine's environment: `env` without TERMINAL_OPT_IN, in any case, so a
31
32
  * value the deck inherited from its shell never reaches an engine; then set to
32
33
  * exactly "1" for an engine started for the Command Panel (`terminal`), and
33
- * for no other.
34
+ * for no other. `claude` is the deck's own `claude` where the engine's search
35
+ * would not find it (claude-dir.mjs engineClaudeHint), given as
36
+ * AGENTS_DECK_CLAUDE only while `env` has no value of its own for it.
34
37
  */
35
- export function engineEnv(env, terminal) {
38
+ export function engineEnv(env, terminal, claude = null) {
36
39
  const out = {};
37
40
  for (const [key, value] of Object.entries(env)) if (key.toUpperCase() !== TERMINAL_OPT_IN) out[key] = value;
41
+ if (typeof claude === 'string' && claude && !String(out.AGENTS_DECK_CLAUDE ?? '').trim()) out.AGENTS_DECK_CLAUDE = claude;
38
42
  if (terminal === true) out[TERMINAL_OPT_IN] = '1';
39
43
  return out;
40
44
  }
@@ -95,7 +99,7 @@ export class ProEngineClient extends EventEmitter {
95
99
  async #launch() {
96
100
  const installation = await awaitStartup(this.#verify(this.options), undefined, 5000);
97
101
  if (this.#closed) throw fail('closed');
98
- const child = spawn(installation.executable, [], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, shell: false, env: engineEnv(process.env, this.options.terminal) });
102
+ const child = spawn(installation.executable, [], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, shell: false, env: engineEnv(process.env, this.options.terminal, engineClaudeHint()) });
99
103
  this.#child = child; this.#installation = installation; this.#nonce = randomBytes(32).toString('hex');
100
104
  const generation = ++this.#generation;
101
105
  // Stream ids start again at 1 for every engine instance.