ccdeck 3.45.0 → 3.47.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 +79 -47
- package/bin/cli/startup.js +27 -3
- package/bin/deck.js +32 -1
- package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +1 -0
- package/dist/web/assets/IntegrationModal-8tTi25gA.js +6 -0
- package/dist/web/assets/RadioPanel-DbmJJPsz.js +1 -0
- package/dist/web/assets/TrafficRadar-CPjAXd5e.js +8 -0
- package/dist/web/assets/{UsageHistoryModal-DAhplVju.js → UsageHistoryModal-qfmvXdWJ.js} +1 -1
- package/dist/web/assets/app-BFFG6Wz8.js +321 -0
- package/dist/web/assets/app-DfcfHvcX.css +1 -0
- package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
- package/dist/web/assets/{index-r8Ymr47Q.js → index-Ca87aJP9.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/release-notes.json +60 -0
- package/src/server/ccusage-install.mjs +58 -1
- package/src/server/ccusage-registry.mjs +289 -0
- package/src/server/ccusage-runner.mjs +9 -2
- package/src/server/claude-accounts.mjs +56 -19
- package/src/server/claude-login.mjs +129 -0
- package/src/server/claude-settings-catalog.d.mts +37 -0
- package/src/server/claude-settings-catalog.mjs +169 -0
- package/src/server/claude-settings-docs.mjs +109 -0
- package/src/server/claude-settings-index.json +251 -0
- package/src/server/claude-settings-routes.mjs +46 -0
- package/src/server/claude-settings.mjs +406 -0
- package/src/server/cli-arrival.mjs +64 -0
- package/src/server/cswap-admin.mjs +12 -3
- package/src/server/index.mjs +18 -2
- package/src/server/installer.mjs +24 -7
- package/src/server/integrations/proxy.mjs +11 -2
- package/src/server/integrations/routes.mjs +6 -4
- package/src/server/login-service.mjs +2 -2
- package/src/server/quota-close-watch.mjs +81 -0
- package/src/server/quota-closes.mjs +181 -0
- package/src/server/quota-history.mjs +8 -1
- package/src/server/quota-shape.mjs +12 -0
- package/src/server/quota.mjs +28 -1
- package/src/server/request-gates.mjs +3 -1
- package/src/server/skill-hook.mjs +28 -22
- package/src/server/system-metrics.mjs +4 -0
- package/src/server/tool-audit-operations.mjs +30 -10
- package/src/server/tool-audit-report.mjs +79 -7
- package/src/server/tool-audit-routes.mjs +5 -1
- package/src/server/tool-audit-skills.mjs +8 -3
- package/src/server/tool-audit.mjs +55 -5
- package/src/server/traffic-radar-capture.mjs +3 -3
- package/src/server/traffic-radar-config.mjs +43 -3
- package/src/server/traffic-radar-monitor.mjs +8 -5
- package/src/server/traffic-radar-permission.mjs +162 -0
- package/src/server/traffic-radar-platform.mjs +93 -20
- package/src/server/traffic-radar-routes.mjs +8 -18
- package/src/server/traffic-radar-service.mjs +81 -94
- package/src/server/traffic-radar.mjs +32 -9
- package/src/server/usage-routes.mjs +14 -2
- package/dist/web/assets/BrowserWatchModal-Cbzf3TWa.js +0 -1
- package/dist/web/assets/IntegrationModal-BnnBr0a3.js +0 -5
- package/dist/web/assets/RadioPanel-BIqrMLQN.js +0 -1
- package/dist/web/assets/TrafficRadar-D1gZCIwX.js +0 -8
- package/dist/web/assets/app-BW3NYUYB.js +0 -318
- package/dist/web/assets/app-C5RY_wZ4.css +0 -1
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// ccusage fetched straight from the npm registry, for a machine with no npm.
|
|
2
|
+
//
|
|
3
|
+
// The managed install in ccusage-install.mjs is `npm install ccusage --prefix`,
|
|
4
|
+
// and the fallback after it is `npx -y ccusage@latest`. Both need Node's npm,
|
|
5
|
+
// and the desktop app is the one way of running this deck that never needed
|
|
6
|
+
// Node at all: it runs the deck on its own Electron binary. Reproduced on a
|
|
7
|
+
// clean Windows VM with the 3.46.0 app and no Node: the boot logged
|
|
8
|
+
// `'"npm.cmd"' is not recognized`, the npx fallback failed the same way, and the
|
|
9
|
+
// Usage panel never had anything from ccusage to show — on the machine of a
|
|
10
|
+
// first-time user, which is the one that judges the tool.
|
|
11
|
+
//
|
|
12
|
+
// What npm would have done here is small enough to do without it. ccusage 20
|
|
13
|
+
// has no dependencies. Its package is a cli.js that runs a native binary, and
|
|
14
|
+
// that binary ships as one optional dependency per platform
|
|
15
|
+
// (`@ccusage/ccusage-<platform>-<arch>`, a few MB, no install scripts). So this
|
|
16
|
+
// asks the registry for the two packages, checks each tarball against the
|
|
17
|
+
// sha512 the registry publishes for it, which is the check npm itself makes, and
|
|
18
|
+
// unpacks them into the same directory npm would have produced, so
|
|
19
|
+
// resolveEntry, nativeCcusage and cli.js find everything where they always have.
|
|
20
|
+
//
|
|
21
|
+
// Nothing is installed anywhere but the deck's own cache directory, and no
|
|
22
|
+
// package script is run, because npm would not run one for these two either.
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import { existsSync } from "node:fs";
|
|
25
|
+
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
26
|
+
import path from "node:path";
|
|
27
|
+
import { gunzip } from "node:zlib";
|
|
28
|
+
import { promisify } from "node:util";
|
|
29
|
+
|
|
30
|
+
const gunzipAsync = promisify(gunzip);
|
|
31
|
+
|
|
32
|
+
/** The registry this asks, unless the environment names another. npm exports
|
|
33
|
+
* `npm_config_registry` to everything it runs, and a user who set it by hand
|
|
34
|
+
* has said where their packages come from. */
|
|
35
|
+
export function registryBase(env = process.env) {
|
|
36
|
+
const named = String(env.npm_config_registry ?? env.NPM_CONFIG_REGISTRY ?? "").trim();
|
|
37
|
+
return (named || "https://registry.npmjs.org").replace(/\/+$/, "");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** ccusage's platform package for this machine, named the way its cli.js names
|
|
41
|
+
* it, or null on a platform ccusage publishes no binary for. */
|
|
42
|
+
export function nativePackageName(platform = process.platform, arch = process.arch) {
|
|
43
|
+
if (!["darwin", "linux", "win32"].includes(platform)) return null;
|
|
44
|
+
if (arch !== "x64" && arch !== "arm64") return null;
|
|
45
|
+
return `@ccusage/ccusage-${platform}-${arch}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Bigger than either package by an order of magnitude, and a stop for a
|
|
49
|
+
* registry or proxy that answers with something that is not a package. */
|
|
50
|
+
const MAX_TARBALL_BYTES = 64 << 20;
|
|
51
|
+
|
|
52
|
+
// A dist-tag or an exact version. Anything else would be put into a URL path.
|
|
53
|
+
const SPEC = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
|
|
54
|
+
|
|
55
|
+
async function getJson(url, { fetch, signal }) {
|
|
56
|
+
const res = await fetch(url, { headers: { accept: "application/json" }, signal });
|
|
57
|
+
if (!res.ok) throw new Error(`${url} answered ${res.status}`);
|
|
58
|
+
return res.json();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The registry's record of one version of one package: its version, where its
|
|
63
|
+
* tarball is, the integrity string that tarball has to match, and its optional
|
|
64
|
+
* dependencies. `spec` is a dist-tag ("latest") or an exact version.
|
|
65
|
+
*/
|
|
66
|
+
export async function packageVersion(name, spec, { fetch = globalThis.fetch, base = registryBase(), signal } = {}) {
|
|
67
|
+
if (!SPEC.test(String(spec))) throw new Error(`not a version or tag: ${spec}`);
|
|
68
|
+
// A scoped name keeps its `@` and has its `/` escaped, which is how the
|
|
69
|
+
// registry spells it in a path.
|
|
70
|
+
const url = `${base}/${name.replace("/", "%2F")}/${spec}`;
|
|
71
|
+
const doc = await getJson(url, { fetch, signal });
|
|
72
|
+
const tarball = doc?.dist?.tarball;
|
|
73
|
+
const integrity = doc?.dist?.integrity;
|
|
74
|
+
if (typeof doc?.version !== "string" || typeof tarball !== "string" || typeof integrity !== "string") {
|
|
75
|
+
throw new Error(`${url} did not describe a package version`);
|
|
76
|
+
}
|
|
77
|
+
if (!/^https?:\/\//.test(tarball)) throw new Error(`${name}@${doc.version} has no usable tarball URL`);
|
|
78
|
+
return { name, version: doc.version, tarball, integrity, optional: doc.optionalDependencies ?? {} };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Whether `bytes` are what `integrity` says, by the sha512 entries in it.
|
|
83
|
+
*
|
|
84
|
+
* An integrity string is space-separated `<algo>-<base64>` entries. Only sha512
|
|
85
|
+
* is accepted: the registry publishes it for every package this fetches, and a
|
|
86
|
+
* record that offers only something weaker is not one to trust a binary to.
|
|
87
|
+
*/
|
|
88
|
+
export function integrityMatches(bytes, integrity) {
|
|
89
|
+
const wanted = String(integrity ?? "").split(/\s+/)
|
|
90
|
+
.filter(e => e.startsWith("sha512-"))
|
|
91
|
+
.map(e => e.slice("sha512-".length).split("?")[0]);
|
|
92
|
+
if (!wanted.length) return false;
|
|
93
|
+
const got = createHash("sha512").update(bytes).digest("base64");
|
|
94
|
+
return wanted.includes(got);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function download(pkg, { fetch, signal }) {
|
|
98
|
+
const res = await fetch(pkg.tarball, { signal });
|
|
99
|
+
if (!res.ok) throw new Error(`${pkg.tarball} answered ${res.status}`);
|
|
100
|
+
const declared = Number(res.headers?.get?.("content-length"));
|
|
101
|
+
if (declared > MAX_TARBALL_BYTES) throw new Error(`${pkg.name}@${pkg.version} is ${declared} bytes, more than a ccusage package should be`);
|
|
102
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
103
|
+
if (bytes.length > MAX_TARBALL_BYTES) throw new Error(`${pkg.name}@${pkg.version} is ${bytes.length} bytes, more than a ccusage package should be`);
|
|
104
|
+
if (!integrityMatches(bytes, pkg.integrity)) {
|
|
105
|
+
throw new Error(`${pkg.name}@${pkg.version} does not match the integrity the registry published for it`);
|
|
106
|
+
}
|
|
107
|
+
return bytes;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const text = (buf, start, len) => {
|
|
111
|
+
const raw = buf.subarray(start, start + len);
|
|
112
|
+
const end = raw.indexOf(0);
|
|
113
|
+
return raw.subarray(0, end === -1 ? raw.length : end).toString("utf8");
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const octal = (buf, start, len) => {
|
|
117
|
+
if (buf[start] & 0x80) throw new Error("tar entry uses a size encoding no npm package needs");
|
|
118
|
+
const s = text(buf, start, len).trim();
|
|
119
|
+
return s ? parseInt(s, 8) : 0;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/** The `path` record out of a pax extended header, or null. */
|
|
123
|
+
function paxPath(body) {
|
|
124
|
+
for (const line of body.toString("utf8").split("\n")) {
|
|
125
|
+
const m = /^\d+ path=(.*)$/.exec(line);
|
|
126
|
+
if (m) return m[1];
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The entries of an uncompressed tar archive: `{ name, mode, type, body }`.
|
|
133
|
+
*
|
|
134
|
+
* Only what npm tarballs use: ustar headers with their prefix field, pax `path`
|
|
135
|
+
* records and GNU long names. Everything is read out of one buffer that has
|
|
136
|
+
* already passed the integrity check, so a truncated archive is the one
|
|
137
|
+
* malformation worth naming.
|
|
138
|
+
*
|
|
139
|
+
* Exported for tests.
|
|
140
|
+
*/
|
|
141
|
+
export function* tarEntries(buf) {
|
|
142
|
+
let off = 0;
|
|
143
|
+
let longName = null;
|
|
144
|
+
while (off + 512 <= buf.length) {
|
|
145
|
+
const head = buf.subarray(off, off + 512);
|
|
146
|
+
if (head.every(b => b === 0)) return;
|
|
147
|
+
const size = octal(head, 124, 12);
|
|
148
|
+
const type = head[156] ? String.fromCharCode(head[156]) : "0";
|
|
149
|
+
const prefix = text(head, 257, 6).startsWith("ustar") ? text(head, 345, 155) : "";
|
|
150
|
+
const start = off + 512;
|
|
151
|
+
if (start + size > buf.length) throw new Error("the package archive is truncated");
|
|
152
|
+
const body = buf.subarray(start, start + size);
|
|
153
|
+
off = start + Math.ceil(size / 512) * 512;
|
|
154
|
+
if (type === "x" || type === "L") { longName = type === "x" ? paxPath(body) : text(body, 0, body.length); continue; }
|
|
155
|
+
if (type === "g") continue;
|
|
156
|
+
const short = text(head, 0, 100);
|
|
157
|
+
const name = longName ?? (prefix ? `${prefix}/${short}` : short);
|
|
158
|
+
longName = null;
|
|
159
|
+
yield { name, mode: octal(head, 100, 8), type, body };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Unpack an npm tarball into `dest`, without its top directory (`package/` in
|
|
165
|
+
* every tarball npm publishes).
|
|
166
|
+
*
|
|
167
|
+
* Regular files and directories only. npm drops links out of a package too,
|
|
168
|
+
* and a link is the one entry that could make a later write land outside
|
|
169
|
+
* `dest`. Every name is also checked to stay inside `dest`: a `..`, a drive
|
|
170
|
+
* letter or a colon, which on Windows names a stream of another file, fails the
|
|
171
|
+
* whole unpack rather than skipping one entry, because a package that contains
|
|
172
|
+
* one of those is not one to run.
|
|
173
|
+
*
|
|
174
|
+
* Exported for tests.
|
|
175
|
+
*/
|
|
176
|
+
export async function unpack(tgz, dest) {
|
|
177
|
+
const tar = await gunzipAsync(tgz);
|
|
178
|
+
const root = path.resolve(dest);
|
|
179
|
+
await mkdir(root, { recursive: true });
|
|
180
|
+
for (const entry of tarEntries(tar)) {
|
|
181
|
+
if (entry.type !== "0" && entry.type !== "5") continue;
|
|
182
|
+
const parts = entry.name.replace(/\\/g, "/").split("/").filter(p => p && p !== ".");
|
|
183
|
+
parts.shift();
|
|
184
|
+
if (!parts.length) continue;
|
|
185
|
+
if (parts.some(p => p === ".." || p.includes(":"))) {
|
|
186
|
+
throw new Error(`the package archive names a path outside itself: ${entry.name}`);
|
|
187
|
+
}
|
|
188
|
+
const target = path.resolve(root, ...parts);
|
|
189
|
+
if (!target.startsWith(root + path.sep)) {
|
|
190
|
+
throw new Error(`the package archive names a path outside itself: ${entry.name}`);
|
|
191
|
+
}
|
|
192
|
+
if (entry.type === "5") { await mkdir(target, { recursive: true }); continue; }
|
|
193
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
194
|
+
// An executable bit is kept, as npm keeps it. ccusage's cli.js would set it
|
|
195
|
+
// on the native binary anyway before running it, but a copy that looks
|
|
196
|
+
// like npm's is one nothing downstream has to know about. Windows has no
|
|
197
|
+
// such bit and ignores the mode.
|
|
198
|
+
await writeFile(target, entry.body, { mode: entry.mode & 0o111 ? 0o755 : 0o644 });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Put ccusage `spec` and this platform's native package into `pkgDir`, the
|
|
204
|
+
* directory npm would have made `node_modules/ccusage`.
|
|
205
|
+
*
|
|
206
|
+
* The native package goes INSIDE it, under `pkgDir/node_modules/@ccusage/…`,
|
|
207
|
+
* where Node's resolution from cli.js finds it first. That keeps the whole
|
|
208
|
+
* install one directory, so it is swapped in with one rename: a run that starts
|
|
209
|
+
* while this works sees the old copy or the new one, never half of each.
|
|
210
|
+
*
|
|
211
|
+
* Built in a sibling directory and renamed into place. If the old copy cannot
|
|
212
|
+
* be moved aside — on Windows, a ccusage.exe still running out of it — the new
|
|
213
|
+
* one is thrown away and the old one stays, which is the same outcome as an npm
|
|
214
|
+
* update that failed, and the next check tries again.
|
|
215
|
+
*
|
|
216
|
+
* Resolves to the version installed. `fetch` and `platform`/`arch` are
|
|
217
|
+
* injectable for tests.
|
|
218
|
+
*/
|
|
219
|
+
export async function fetchCcusage({
|
|
220
|
+
spec = "latest",
|
|
221
|
+
pkgDir,
|
|
222
|
+
fetch = globalThis.fetch,
|
|
223
|
+
base = registryBase(),
|
|
224
|
+
platform = process.platform,
|
|
225
|
+
arch = process.arch,
|
|
226
|
+
timeoutMs = 120_000,
|
|
227
|
+
} = {}) {
|
|
228
|
+
if (typeof fetch !== "function") throw new Error("this Node has no fetch");
|
|
229
|
+
const nativeName = nativePackageName(platform, arch);
|
|
230
|
+
if (!nativeName) throw new Error(`ccusage publishes no build for ${platform}-${arch}`);
|
|
231
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
232
|
+
const opts = { fetch, base, signal };
|
|
233
|
+
|
|
234
|
+
const main = await packageVersion("ccusage", spec, opts);
|
|
235
|
+
const nativeSpec = main.optional[nativeName];
|
|
236
|
+
if (typeof nativeSpec !== "string" || !SPEC.test(nativeSpec)) {
|
|
237
|
+
throw new Error(`ccusage@${main.version} names no exact ${nativeName} version`);
|
|
238
|
+
}
|
|
239
|
+
const native = await packageVersion(nativeName, nativeSpec, opts);
|
|
240
|
+
const [mainTgz, nativeTgz] = await Promise.all([download(main, opts), download(native, opts)]);
|
|
241
|
+
|
|
242
|
+
const stamp = `${process.pid}-${Date.now()}`;
|
|
243
|
+
const staging = `${pkgDir}.fetching-${stamp}`;
|
|
244
|
+
const old = `${pkgDir}.old-${stamp}`;
|
|
245
|
+
try {
|
|
246
|
+
await unpack(mainTgz, staging);
|
|
247
|
+
await unpack(nativeTgz, path.join(staging, "node_modules", ...nativeName.split("/")));
|
|
248
|
+
await mkdir(path.dirname(pkgDir), { recursive: true });
|
|
249
|
+
const hadOld = existsSync(pkgDir);
|
|
250
|
+
if (hadOld) await renameSoon(pkgDir, old);
|
|
251
|
+
try {
|
|
252
|
+
await renameSoon(staging, pkgDir);
|
|
253
|
+
} catch (err) {
|
|
254
|
+
if (hadOld) await renameSoon(old, pkgDir).catch(() => {});
|
|
255
|
+
throw err;
|
|
256
|
+
}
|
|
257
|
+
// Only once the new copy is in place: until then `old` is the copy to put back.
|
|
258
|
+
if (hadOld) await rm(old, { recursive: true, force: true, maxRetries: 10, retryDelay: 25 }).catch(() => {});
|
|
259
|
+
} finally {
|
|
260
|
+
await rm(staging, { recursive: true, force: true }).catch(() => {});
|
|
261
|
+
}
|
|
262
|
+
return main.version;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* `rename`, given a moment when Windows says the file is busy.
|
|
267
|
+
*
|
|
268
|
+
* A freshly written ccusage.exe is opened by the antivirus scanner before
|
|
269
|
+
* anything else gets to it, and while it is open its directory cannot be
|
|
270
|
+
* renamed. That is a hold of a moment, not a refusal, and npm's own file system
|
|
271
|
+
* layer retries the same three codes for the same reason.
|
|
272
|
+
*/
|
|
273
|
+
async function renameSoon(from, to, tries = 8) {
|
|
274
|
+
for (let i = 1; ; i++) {
|
|
275
|
+
try {
|
|
276
|
+
return await rename(from, to);
|
|
277
|
+
} catch (err) {
|
|
278
|
+
if (i >= tries || !["EPERM", "EACCES", "EBUSY"].includes(err?.code)) throw err;
|
|
279
|
+
await new Promise(r => setTimeout(r, 50 * i));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** The version the registry calls `latest`, for the daily update check on a
|
|
285
|
+
* machine with no `npm view` to ask. */
|
|
286
|
+
export async function latestCcusage({ fetch = globalThis.fetch, base = registryBase(), timeoutMs = 30_000 } = {}) {
|
|
287
|
+
const { version } = await packageVersion("ccusage", "latest", { fetch, base, signal: AbortSignal.timeout(timeoutMs) });
|
|
288
|
+
return version;
|
|
289
|
+
}
|
|
@@ -12,8 +12,8 @@ import { existsSync } from "node:fs";
|
|
|
12
12
|
import { killTree, pathLookup, spawnSpec } from "./exec.mjs";
|
|
13
13
|
import { note, stamp, tagged } from "./ccusage-failure.mjs";
|
|
14
14
|
import {
|
|
15
|
-
discardDamagedInstall, installsDisabled, lastInstallError, maybeBackgroundUpdate,
|
|
16
|
-
startInstall, touchMarker, winShim,
|
|
15
|
+
discardDamagedInstall, installsDisabled, lastInstallError, maybeBackgroundUpdate, npmAvailable,
|
|
16
|
+
resolveEntry, startInstall, touchMarker, winShim,
|
|
17
17
|
} from "./ccusage-install.mjs";
|
|
18
18
|
|
|
19
19
|
const TIMEOUT_MS = 90_000;
|
|
@@ -158,6 +158,13 @@ async function getRunner() {
|
|
|
158
158
|
await startInstall("latest");
|
|
159
159
|
resolved = resolveEntry();
|
|
160
160
|
if (resolved) { touchMarker(); return { kind: "node", entry: resolved.entry }; }
|
|
161
|
+
// No npm means no npx, so there is no fallback to hand back. The install that
|
|
162
|
+
// just failed was the registry download, and its own account is the whole
|
|
163
|
+
// story: an npx run here would only fail again with "npx is not recognized"
|
|
164
|
+
// and the modal would lead with that instead.
|
|
165
|
+
if (!npmAvailable()) {
|
|
166
|
+
throw tagged("fetch_failed", lastInstallError() ?? "ccusage could not be downloaded from the npm registry");
|
|
167
|
+
}
|
|
161
168
|
// npm unavailable / offline → fall back to npx, carrying WHY the managed
|
|
162
169
|
// install is not here. Without that the modal can only describe the fallback,
|
|
163
170
|
// and the fallback is the second thing that failed.
|
|
@@ -59,6 +59,10 @@ import { observeOrgTelemetry } from "./org-telemetry.mjs";
|
|
|
59
59
|
// Whether a switch target's stored login is known dead, and whether a
|
|
60
60
|
// collection would read it first (#2184). Pure, and imports nothing.
|
|
61
61
|
import { collectionWouldRead, deadLoginOf } from "./login-guard.mjs";
|
|
62
|
+
// Which slot is active: the one Claude Code is signed in as, matched the way
|
|
63
|
+
// `cswap list` matches it, rather than the number only cswap's own commands
|
|
64
|
+
// move. See its header for the drift that made this a module.
|
|
65
|
+
import { activeFrom, readLiveLogin } from "./claude-login.mjs";
|
|
62
66
|
import { dirname, join } from "node:path";
|
|
63
67
|
import { existsSync } from "node:fs";
|
|
64
68
|
import { homedir, platform } from "node:os";
|
|
@@ -232,19 +236,14 @@ async function readJson(path) {
|
|
|
232
236
|
}
|
|
233
237
|
}
|
|
234
238
|
|
|
235
|
-
/** claude-swap's sequence.json — the accounts, their order and which slot
|
|
236
|
-
*
|
|
237
|
-
*
|
|
239
|
+
/** claude-swap's sequence.json — the accounts, their order and which slot
|
|
240
|
+
* cswap last recorded as active (which is not always who is signed in: see
|
|
241
|
+
* claude-login.mjs) — or null when it is missing or will not parse.
|
|
242
|
+
* seedFirstAccount tells those two apart first, so it reads the file itself. */
|
|
238
243
|
async function readSequence(root) {
|
|
239
244
|
return readJson(join(root, "sequence.json"));
|
|
240
245
|
}
|
|
241
246
|
|
|
242
|
-
/** The slot a sequence.json names as active, as the string its `accounts` are
|
|
243
|
-
* keyed by, or null when it names none. */
|
|
244
|
-
function activeSlot(seq) {
|
|
245
|
-
return seq?.activeAccountNumber != null ? String(seq.activeAccountNumber) : null;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
247
|
/** The usage rows in claude-swap's cache/usage.json, keyed by slot — see
|
|
249
248
|
* usageRows for which of them may be believed. */
|
|
250
249
|
async function readUsageRows(root) {
|
|
@@ -473,17 +472,25 @@ async function readRoster(now, gen) {
|
|
|
473
472
|
const rows = await readUsageRows(root);
|
|
474
473
|
const orgTelemetry = await observeOrgTelemetry({ seq }).catch(() => ({}));
|
|
475
474
|
|
|
475
|
+
// WHO IS ACTIVE IS WHO CLAUDE CODE IS SIGNED IN AS. sequence.json's
|
|
476
|
+
// activeAccountNumber moves only when a cswap command switches, so a
|
|
477
|
+
// `/login` made anywhere else left the panel on the previous account for
|
|
478
|
+
// good, and every decision taken from the roster — Switch, Auto-switch, the
|
|
479
|
+
// expired-login guard, the paired decks' in-use mark — with it. Read on every
|
|
480
|
+
// roster read; the stored number stands only when no login can be read.
|
|
481
|
+
const active = activeFrom(seq, await readLiveLogin());
|
|
482
|
+
|
|
476
483
|
// Kick a collection for the NEXT poll if anything is due — either because
|
|
477
484
|
// claude-swap's schedule says so, or because an account has never been
|
|
478
485
|
// fetched at all.
|
|
479
|
-
nudgeCollector(rows, Object.keys(seq.accounts), now,
|
|
486
|
+
nudgeCollector(rows, Object.keys(seq.accounts), now, active.num);
|
|
480
487
|
|
|
481
488
|
// Who the CLI says is signed in, asked ONLY when the store claims the active
|
|
482
489
|
// account is in trouble — see authTrouble. That is the one case where the
|
|
483
490
|
// stored verdict and the live truth can disagree, and it is rare: a healthy
|
|
484
491
|
// machine never spends this subprocess. Never fatal, because a CLI that
|
|
485
492
|
// cannot be reached is not evidence either way.
|
|
486
|
-
const activeNum =
|
|
493
|
+
const activeNum = active.num;
|
|
487
494
|
const activeRow = activeNum ? rows[activeNum] : null;
|
|
488
495
|
const identity = (activeRow?.consecutiveFailures ?? 0) > 0
|
|
489
496
|
? await currentIdentity().catch(() => null)
|
|
@@ -505,7 +512,7 @@ async function readRoster(now, gen) {
|
|
|
505
512
|
const row = rows[num];
|
|
506
513
|
const key = accountKey(acct.email, acct.organizationUuid);
|
|
507
514
|
const origin = Object.hasOwn(origins, key) ? origins[key] : null;
|
|
508
|
-
const shown = rosterRow({
|
|
515
|
+
const shown = rosterRow({ activeNum, num, acct, row, identity, now, key, origin, telemetry: orgTelemetry[acct.organizationUuid] ?? null });
|
|
509
516
|
accounts.push(shown);
|
|
510
517
|
// A put-off incident is over once a read succeeds after it, and the
|
|
511
518
|
// put-off goes with it (#1893) — said here, where the read is, rather than
|
|
@@ -514,7 +521,12 @@ async function readRoster(now, gen) {
|
|
|
514
521
|
}
|
|
515
522
|
tidyOrigins(origins, recovered, seq.accounts);
|
|
516
523
|
|
|
517
|
-
|
|
524
|
+
// `unlistedLogin`: Claude Code is signed in as an account claude-swap does
|
|
525
|
+
// not hold, so no row is active and the panel says whose login it is.
|
|
526
|
+
return finish({
|
|
527
|
+
ok: true, accounts, activeNum: activeNum != null ? Number(activeNum) : null,
|
|
528
|
+
unlistedLogin: active.unlisted, fetchedAt: now,
|
|
529
|
+
});
|
|
518
530
|
}
|
|
519
531
|
|
|
520
532
|
/**
|
|
@@ -532,7 +544,7 @@ function observedMs(seconds) {
|
|
|
532
544
|
return Number.isFinite(ms) && ms > 0 && Number.isFinite(new Date(ms).getTime()) ? ms : null;
|
|
533
545
|
}
|
|
534
546
|
|
|
535
|
-
function rosterRow({
|
|
547
|
+
function rosterRow({ activeNum, num, acct, row, identity, now, key, origin = null, telemetry = null }) {
|
|
536
548
|
const matches = rowIsFor(row, acct);
|
|
537
549
|
const good = matches ? row.lastGood : null;
|
|
538
550
|
|
|
@@ -540,7 +552,8 @@ function rosterRow({ seq, num, acct, row, identity, now, key, origin = null, tel
|
|
|
540
552
|
// When claude-swap last TRIED, well or not. A refusal counts against a login
|
|
541
553
|
// only when it came after the deck last signed that login in (#1893).
|
|
542
554
|
const attemptedAtMs = matches ? observedMs(row.lastAttemptAt) : null;
|
|
543
|
-
|
|
555
|
+
// The slot Claude Code is signed in as, from readRoster (claude-login.mjs).
|
|
556
|
+
const isActive = activeNum === num;
|
|
544
557
|
const trouble = authTrouble(row, {
|
|
545
558
|
matches, isActive, identity, email: acct.email, fetchedAt: fetchedAtMs, now,
|
|
546
559
|
});
|
|
@@ -713,12 +726,13 @@ export function authTrouble(row, {
|
|
|
713
726
|
*
|
|
714
727
|
* Returns null rather than a partial when anything about the row is unsure:
|
|
715
728
|
* the caller's fallback is to fetch for itself, and a wrong number is worse
|
|
716
|
-
* than a slow one.
|
|
729
|
+
* than a slow one. That includes a login claude-swap does not hold: there is
|
|
730
|
+
* no row for it, and the stored active slot's would be someone else's numbers.
|
|
717
731
|
*/
|
|
718
732
|
export async function activeAccountUsage() {
|
|
719
733
|
const root = backupRoot();
|
|
720
734
|
const seq = await readSequence(root);
|
|
721
|
-
const num =
|
|
735
|
+
const num = activeFrom(seq, await readLiveLogin()).num;
|
|
722
736
|
const acct = num ? seq?.accounts?.[num] : null;
|
|
723
737
|
if (!acct) return null;
|
|
724
738
|
|
|
@@ -739,6 +753,27 @@ export async function activeAccountUsage() {
|
|
|
739
753
|
};
|
|
740
754
|
}
|
|
741
755
|
|
|
756
|
+
/**
|
|
757
|
+
* What claude-swap last collected for every account it manages: the two small
|
|
758
|
+
* files activeAccountUsage reads, under the same identity guard, and nothing
|
|
759
|
+
* else — no CLI, no verdicts, no repair. The record of how full each window was
|
|
760
|
+
* at its reset (quota-close-watch.mjs) reads this on a timer, and a timer must
|
|
761
|
+
* not start what a look at the accounts panel does.
|
|
762
|
+
*/
|
|
763
|
+
export async function storedUsageReadings() {
|
|
764
|
+
const root = backupRoot();
|
|
765
|
+
const seq = await readSequence(root);
|
|
766
|
+
if (!seq?.accounts || typeof seq.accounts !== "object") return [];
|
|
767
|
+
const rows = await readUsageRows(root);
|
|
768
|
+
return Object.entries(seq.accounts).flatMap(([num, acct]) => {
|
|
769
|
+
const row = rows[num];
|
|
770
|
+
const fetchedAt = rowIsFor(row, acct) ? observedMs(row.fetchedAt) : null;
|
|
771
|
+
return row?.lastGood && fetchedAt != null
|
|
772
|
+
? [{ email: acct.email, organizationUuid: acct.organizationUuid ?? "", lastGood: row.lastGood, fetchedAt }]
|
|
773
|
+
: [];
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
|
|
742
777
|
/**
|
|
743
778
|
* Ask claude-swap to collect now, if its own schedule agrees.
|
|
744
779
|
*
|
|
@@ -752,7 +787,7 @@ export async function requestCollection() {
|
|
|
752
787
|
const seq = await readSequence(root);
|
|
753
788
|
if (!seq?.accounts) return false;
|
|
754
789
|
const rows = await readUsageRows(root);
|
|
755
|
-
return nudgeCollector(rows, Object.keys(seq.accounts), Date.now(), seq.
|
|
790
|
+
return nudgeCollector(rows, Object.keys(seq.accounts), Date.now(), activeFrom(seq, await readLiveLogin()).num);
|
|
756
791
|
}
|
|
757
792
|
|
|
758
793
|
/**
|
|
@@ -827,7 +862,9 @@ async function switchTarget(num) {
|
|
|
827
862
|
const acct = seq?.accounts?.[key];
|
|
828
863
|
if (!acct) return null;
|
|
829
864
|
const row = (await readUsageRows(root))[key];
|
|
830
|
-
|
|
865
|
+
// Active the way cswap's switch decides "already on it": the slot Claude
|
|
866
|
+
// Code is signed in as, which is the switch that writes nothing live.
|
|
867
|
+
return { acct, row, matches: rowIsFor(row, acct), active: activeFrom(seq, await readLiveLogin()).num === key };
|
|
831
868
|
}
|
|
832
869
|
|
|
833
870
|
/**
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Who Claude Code is signed in as right now, and which claude-swap slot that is.
|
|
2
|
+
//
|
|
3
|
+
// The roster used to call the slot in sequence.json's `activeAccountNumber` the
|
|
4
|
+
// active account. claude-swap writes that number only when one of its own
|
|
5
|
+
// commands switches or adds, so a `/login` in Claude Code — or `claude auth
|
|
6
|
+
// login`, or anything else that signs in without cswap — left it naming the
|
|
7
|
+
// previous account for good. The panel showed A while `cswap list` and Claude
|
|
8
|
+
// Code's /status both said B; ↻ re-read the same stale number; and Switch on B
|
|
9
|
+
// did nothing, because cswap saw it was already on B and wrote nothing.
|
|
10
|
+
//
|
|
11
|
+
// `cswap list` never trusts that number. It reads the live identity out of
|
|
12
|
+
// Claude Code's global config and matches it to a slot (switcher.py
|
|
13
|
+
// _get_current_account and _find_account_slot). This module is that rule, so
|
|
14
|
+
// the deck and `cswap list` cannot answer "who is active" two ways.
|
|
15
|
+
//
|
|
16
|
+
// A file read, never a spawn and never the keychain: it runs on every roster
|
|
17
|
+
// read. And only when the file has changed: .claude.json can be large, so an
|
|
18
|
+
// unchanged one costs a stat, as org-telemetry.mjs keeps it. Only when there is
|
|
19
|
+
// no live identity to read — no config file, one that will not parse, or one
|
|
20
|
+
// with nobody signed in — does the stored number stand in, which is what the
|
|
21
|
+
// roster did before.
|
|
22
|
+
import { readFile, stat } from "node:fs/promises";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { posix, win32 } from "node:path";
|
|
25
|
+
import { claudeConfigDir } from "./claude-dir.mjs";
|
|
26
|
+
import { claudePlanToken } from "./depth-facts.mjs";
|
|
27
|
+
|
|
28
|
+
async function exists(path, statFile) {
|
|
29
|
+
try { await statFile(path); return true; } catch { return false; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The global config file Claude Code keeps its signed-in account in, chosen
|
|
34
|
+
* the way claude-swap's paths.py get_global_config_path chooses it: the legacy
|
|
35
|
+
* `<config dir>/.config.json` while Claude Code would still use it, otherwise
|
|
36
|
+
* `($CLAUDE_CONFIG_DIR || home)/.claude.json`.
|
|
37
|
+
*/
|
|
38
|
+
export async function claudeGlobalConfigPath({
|
|
39
|
+
env = process.env, home = homedir(), platform = process.platform, statFile = stat,
|
|
40
|
+
} = {}) {
|
|
41
|
+
const { join } = platform === "win32" ? win32 : posix;
|
|
42
|
+
const configDir = claudeConfigDir(env, home, platform);
|
|
43
|
+
const global = join(env.CLAUDE_CONFIG_DIR?.trim() ? configDir : home, ".claude.json");
|
|
44
|
+
const legacy = join(configDir, ".config.json");
|
|
45
|
+
try {
|
|
46
|
+
const st = await statFile(legacy);
|
|
47
|
+
if (st.isFile() && (st.size > 0 || ((st.mode & 0o222) !== 0 && !(await exists(global, statFile))))) return legacy;
|
|
48
|
+
} catch { /* no legacy file: the global one */ }
|
|
49
|
+
return global;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// The last answer, and the file it was read from: path, mtime and size.
|
|
53
|
+
let _last = null;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The plan of a signed-in account, as claudePlanToken names it ("max-20x",
|
|
57
|
+
* "pro"…), or null when `oauthAccount` does not say one it knows.
|
|
58
|
+
*
|
|
59
|
+
* Claude Code keeps the plan in two places: `subscriptionType` and
|
|
60
|
+
* `rateLimitTier` beside the token in .credentials.json, and
|
|
61
|
+
* `organizationType` ("claude_max") and `organizationRateLimitTier`
|
|
62
|
+
* ("default_claude_max_20x") here. This is the one every platform has: on
|
|
63
|
+
* macOS the token, and the two fields beside it, are in the Keychain.
|
|
64
|
+
*/
|
|
65
|
+
export function planOfAccount(oauth) {
|
|
66
|
+
const type = typeof oauth?.organizationType === "string" ? oauth.organizationType.trim().replace(/^claude_/i, "") : "";
|
|
67
|
+
return claudePlanToken({ subscriptionType: type, rateLimitTier: oauth?.organizationRateLimitTier }) ?? null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Who Claude Code is signed in as — `{ email, orgUuid }` from the config's
|
|
72
|
+
* `oauthAccount`, and `plan` when planOfAccount can say it — or null when that
|
|
73
|
+
* cannot be read. `orgUuid` is "" for a login with no organization, as
|
|
74
|
+
* claude-swap normalises it.
|
|
75
|
+
*/
|
|
76
|
+
export async function readLiveLogin({
|
|
77
|
+
env = process.env, home = homedir(), platform = process.platform, statFile = stat, read = readFile,
|
|
78
|
+
} = {}) {
|
|
79
|
+
try {
|
|
80
|
+
const path = await claudeGlobalConfigPath({ env, home, platform, statFile });
|
|
81
|
+
const st = await statFile(path);
|
|
82
|
+
if (_last?.path === path && _last.mtimeMs === st.mtimeMs && _last.size === st.size) return _last.login;
|
|
83
|
+
const oauth = JSON.parse(String(await read(path, "utf8")).replace(/^/, ""))?.oauthAccount;
|
|
84
|
+
const email = typeof oauth?.emailAddress === "string" ? oauth.emailAddress : "";
|
|
85
|
+
const plan = planOfAccount(oauth);
|
|
86
|
+
const login = email
|
|
87
|
+
? { email, orgUuid: typeof oauth.organizationUuid === "string" ? oauth.organizationUuid : "", ...(plan && { plan }) }
|
|
88
|
+
: null;
|
|
89
|
+
_last = { path, mtimeMs: st.mtimeMs, size: st.size, login };
|
|
90
|
+
return login;
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The slot holding that login, matched on (email, organizationUuid) exactly as
|
|
98
|
+
* claude-swap's _find_account_slot matches it — the email as written, a slot
|
|
99
|
+
* with no organization key as "" (one whose key is null matches nothing, as
|
|
100
|
+
* there) — or null when no slot holds it.
|
|
101
|
+
*/
|
|
102
|
+
export function slotOfLogin(seq, login) {
|
|
103
|
+
if (!login) return null;
|
|
104
|
+
for (const [num, acct] of Object.entries(seq?.accounts ?? {})) {
|
|
105
|
+
const org = acct && Object.hasOwn(acct, "organizationUuid") ? acct.organizationUuid : "";
|
|
106
|
+
if (acct?.email === login.email && org === login.orgUuid) return num;
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Which slot is active, and on whose word:
|
|
113
|
+
*
|
|
114
|
+
* - `{ num, unlisted: null, source: "login" }`: Claude Code is signed in as
|
|
115
|
+
* slot `num`, whatever sequence.json last recorded;
|
|
116
|
+
* - `{ num: null, unlisted: email, source: "login" }`: it is signed in as an
|
|
117
|
+
* account claude-swap does not hold, so no row is active and the panel can
|
|
118
|
+
* say whose login it is;
|
|
119
|
+
* - `{ num, unlisted: null, source: "store" }`: no live identity could be
|
|
120
|
+
* read, so sequence.json's number stands, as it always did.
|
|
121
|
+
*/
|
|
122
|
+
export function activeFrom(seq, login) {
|
|
123
|
+
if (!login) {
|
|
124
|
+
const stored = seq?.activeAccountNumber;
|
|
125
|
+
return { num: stored != null ? String(stored) : null, unlisted: null, source: "store" };
|
|
126
|
+
}
|
|
127
|
+
const num = slotOfLogin(seq, login);
|
|
128
|
+
return { num, unlisted: num == null ? login.email : null, source: "login" };
|
|
129
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type ClaudeSettingGroup = "sessions" | "memory" | "git" | "terminal" | "updates";
|
|
2
|
+
export type ClaudeSettingKind = "switch" | "choice" | "days" | "allowTool" | "attribution";
|
|
3
|
+
|
|
4
|
+
export interface ClaudeSettingOption {
|
|
5
|
+
value: string | null;
|
|
6
|
+
label: string;
|
|
7
|
+
/** A value in the file that means the same as this option. */
|
|
8
|
+
also?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ClaudeSettingOverride {
|
|
12
|
+
env: string;
|
|
13
|
+
when: "on" | "off";
|
|
14
|
+
effect: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ClaudeSettingEntry {
|
|
18
|
+
id: string;
|
|
19
|
+
key: string;
|
|
20
|
+
group: ClaudeSettingGroup;
|
|
21
|
+
kind: ClaudeSettingKind;
|
|
22
|
+
label: string;
|
|
23
|
+
note: string;
|
|
24
|
+
keywords: readonly string[];
|
|
25
|
+
since?: string;
|
|
26
|
+
overrides?: readonly ClaudeSettingOverride[];
|
|
27
|
+
legacy?: boolean;
|
|
28
|
+
unset?: boolean | number;
|
|
29
|
+
tool?: string;
|
|
30
|
+
options?: readonly (ClaudeSettingOption | number)[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const CLAUDE_SETTINGS_DOCS: string;
|
|
34
|
+
export const CLAUDE_SETTING_GROUPS: readonly { id: ClaudeSettingGroup; title: string }[];
|
|
35
|
+
export const CLAUDE_SETTINGS: readonly ClaudeSettingEntry[];
|
|
36
|
+
export function claudeSettingById(id: string): ClaudeSettingEntry | undefined;
|
|
37
|
+
export function daysLabel(days: number): string;
|