tokenusage-cli 0.1.0 → 0.2.1

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 (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,76 +1,76 @@
1
- function createProgress({ stream } = {}) {
2
- const out = stream || process.stdout;
3
- const enabled = Boolean(out && out.isTTY);
4
- const frames = ["|", "/", "-", "\\"];
5
- const intervalMs = 90;
6
-
7
- let timer = null;
8
- let text = "";
9
- let frame = 0;
10
- let lastLen = 0;
11
-
12
- function render() {
13
- if (!enabled) return;
14
- const line = `${frames[frame++ % frames.length]} ${text}`;
15
- const pad = lastLen > line.length ? " ".repeat(lastLen - line.length) : "";
16
- lastLen = line.length;
17
- out.write(`\r${line}${pad}`);
18
- }
19
-
20
- function start(initialText) {
21
- if (!enabled) return;
22
- text = initialText || "";
23
- if (timer) clearInterval(timer);
24
- timer = setInterval(render, intervalMs);
25
- render();
26
- }
27
-
28
- function update(nextText) {
29
- text = nextText || "";
30
- render();
31
- }
32
-
33
- function stop() {
34
- if (!enabled) return;
35
- if (timer) clearInterval(timer);
36
- timer = null;
37
- out.write(`\r${" ".repeat(lastLen)}\r`);
38
- lastLen = 0;
39
- }
40
-
41
- return { enabled, start, update, stop };
42
- }
43
-
44
- function renderBar(progress, width = 20) {
45
- const p = Number.isFinite(progress) ? Math.min(1, Math.max(0, progress)) : 0;
46
- const filled = Math.round(p * width);
47
- const empty = Math.max(0, width - filled);
48
- return `[${"=".repeat(filled)}${"-".repeat(empty)}] ${Math.round(p * 100)}%`;
49
- }
50
-
51
- function formatNumber(n) {
52
- const v = Number(n);
53
- if (!Number.isFinite(v)) return "0";
54
- return Math.trunc(v).toLocaleString("en-US");
55
- }
56
-
57
- function formatBytes(bytes) {
58
- const n = Number(bytes);
59
- if (!Number.isFinite(n) || n <= 0) return "0 B";
60
- const units = ["B", "KB", "MB", "GB", "TB"];
61
- let v = n;
62
- let i = 0;
63
- while (v >= 1024 && i < units.length - 1) {
64
- v /= 1024;
65
- i += 1;
66
- }
67
- const fixed = i === 0 ? String(Math.trunc(v)) : v.toFixed(v >= 10 ? 1 : 2);
68
- return `${fixed} ${units[i]}`;
69
- }
70
-
71
- module.exports = {
72
- createProgress,
73
- renderBar,
74
- formatNumber,
75
- formatBytes,
76
- };
1
+ function createProgress({ stream } = {}) {
2
+ const out = stream || process.stdout;
3
+ const enabled = Boolean(out && out.isTTY);
4
+ const frames = ["|", "/", "-", "\\"];
5
+ const intervalMs = 90;
6
+
7
+ let timer = null;
8
+ let text = "";
9
+ let frame = 0;
10
+ let lastLen = 0;
11
+
12
+ function render() {
13
+ if (!enabled) return;
14
+ const line = `${frames[frame++ % frames.length]} ${text}`;
15
+ const pad = lastLen > line.length ? " ".repeat(lastLen - line.length) : "";
16
+ lastLen = line.length;
17
+ out.write(`\r${line}${pad}`);
18
+ }
19
+
20
+ function start(initialText) {
21
+ if (!enabled) return;
22
+ text = initialText || "";
23
+ if (timer) clearInterval(timer);
24
+ timer = setInterval(render, intervalMs);
25
+ render();
26
+ }
27
+
28
+ function update(nextText) {
29
+ text = nextText || "";
30
+ render();
31
+ }
32
+
33
+ function stop() {
34
+ if (!enabled) return;
35
+ if (timer) clearInterval(timer);
36
+ timer = null;
37
+ out.write(`\r${" ".repeat(lastLen)}\r`);
38
+ lastLen = 0;
39
+ }
40
+
41
+ return { enabled, start, update, stop };
42
+ }
43
+
44
+ function renderBar(progress, width = 20) {
45
+ const p = Number.isFinite(progress) ? Math.min(1, Math.max(0, progress)) : 0;
46
+ const filled = Math.round(p * width);
47
+ const empty = Math.max(0, width - filled);
48
+ return `[${"=".repeat(filled)}${"-".repeat(empty)}] ${Math.round(p * 100)}%`;
49
+ }
50
+
51
+ function formatNumber(n) {
52
+ const v = Number(n);
53
+ if (!Number.isFinite(v)) return "0";
54
+ return Math.trunc(v).toLocaleString("en-US");
55
+ }
56
+
57
+ function formatBytes(bytes) {
58
+ const n = Number(bytes);
59
+ if (!Number.isFinite(n) || n <= 0) return "0 B";
60
+ const units = ["B", "KB", "MB", "GB", "TB"];
61
+ let v = n;
62
+ let i = 0;
63
+ while (v >= 1024 && i < units.length - 1) {
64
+ v /= 1024;
65
+ i += 1;
66
+ }
67
+ const fixed = i === 0 ? String(Math.trunc(v)) : v.toFixed(v >= 10 ? 1 : 2);
68
+ return `${fixed} ${units[i]}`;
69
+ }
70
+
71
+ module.exports = {
72
+ createProgress,
73
+ renderBar,
74
+ formatNumber,
75
+ formatBytes,
76
+ };
@@ -1,117 +1,117 @@
1
- const fs = require("node:fs");
2
- const fsp = require("node:fs/promises");
3
- const path = require("node:path");
4
- const readline = require("node:readline");
5
-
6
- async function purgeProjectUsage({
7
- projectKey,
8
- projectQueuePath,
9
- projectQueueStatePath,
10
- projectState,
11
- cursors,
12
- }) {
13
- if (!projectKey || !projectQueuePath || !projectQueueStatePath || !projectState) {
14
- return { removed: 0, kept: 0, removedBuckets: 0, removedProjectCursors: 0 };
15
- }
16
-
17
- let previousOffset = 0;
18
- const previousState = await fsp.readFile(projectQueueStatePath, "utf8").catch(() => null);
19
- if (previousState) {
20
- try {
21
- const parsed = JSON.parse(previousState);
22
- const offset = Number(parsed?.offset || 0);
23
- if (Number.isFinite(offset) && offset >= 0) previousOffset = offset;
24
- } catch (_err) {
25
- previousOffset = 0;
26
- }
27
- }
28
-
29
- const buckets =
30
- projectState.buckets && typeof projectState.buckets === "object" ? projectState.buckets : {};
31
- let removedBuckets = 0;
32
- const prefix = `${projectKey}|`;
33
- for (const key of Object.keys(buckets)) {
34
- if (key.startsWith(prefix)) {
35
- delete buckets[key];
36
- removedBuckets += 1;
37
- }
38
- }
39
- projectState.buckets = buckets;
40
-
41
- let removedProjectCursors = 0;
42
- const files = cursors?.files && typeof cursors.files === "object" ? cursors.files : {};
43
- for (const cursor of Object.values(files)) {
44
- if (!cursor || typeof cursor !== "object") continue;
45
- if (cursor.project?.projectKey === projectKey) {
46
- delete cursor.project;
47
- removedProjectCursors += 1;
48
- }
49
- }
50
-
51
- let removed = 0;
52
- let kept = 0;
53
- let nextOffset = 0;
54
- const st = await fsp.stat(projectQueuePath).catch(() => null);
55
- if (st && st.isFile()) {
56
- const tmpPath = `${projectQueuePath}.tmp`;
57
- await fsp.mkdir(path.dirname(projectQueuePath), { recursive: true });
58
- const input = fs.createReadStream(projectQueuePath, "utf8");
59
- const output = fs.createWriteStream(tmpPath, { encoding: "utf8" });
60
- const rl = readline.createInterface({ input, crlfDelay: Infinity });
61
-
62
- let inputOffset = 0;
63
- let outputOffset = 0;
64
- for await (const line of rl) {
65
- const trimmed = line.trim();
66
- const inputBytes = Buffer.byteLength(line, "utf8") + 1;
67
- inputOffset += inputBytes;
68
- if (!trimmed) continue;
69
- let parsed = null;
70
- try {
71
- parsed = JSON.parse(trimmed);
72
- } catch (_err) {
73
- const entry = trimmed + "\n";
74
- output.write(entry);
75
- outputOffset += Buffer.byteLength(entry, "utf8");
76
- kept += 1;
77
- if (inputOffset <= previousOffset) {
78
- nextOffset = outputOffset;
79
- }
80
- continue;
81
- }
82
- if (parsed && parsed.project_key === projectKey) {
83
- removed += 1;
84
- if (inputOffset <= previousOffset) {
85
- nextOffset = outputOffset;
86
- }
87
- continue;
88
- }
89
- const entry = JSON.stringify(parsed) + "\n";
90
- output.write(entry);
91
- outputOffset += Buffer.byteLength(entry, "utf8");
92
- kept += 1;
93
- if (inputOffset <= previousOffset) {
94
- nextOffset = outputOffset;
95
- }
96
- }
97
-
98
- await new Promise((resolve, reject) => {
99
- output.end(resolve);
100
- output.on("error", reject);
101
- });
102
-
103
- await fsp.rename(tmpPath, projectQueuePath);
104
- if (previousOffset >= inputOffset) {
105
- nextOffset = outputOffset;
106
- }
107
- } else {
108
- await fsp.writeFile(projectQueuePath, "", "utf8");
109
- nextOffset = 0;
110
- }
111
-
112
- await fsp.writeFile(projectQueueStatePath, JSON.stringify({ offset: nextOffset }), "utf8");
113
-
114
- return { removed, kept, removedBuckets, removedProjectCursors };
115
- }
116
-
117
- module.exports = { purgeProjectUsage };
1
+ const fs = require("node:fs");
2
+ const fsp = require("node:fs/promises");
3
+ const path = require("node:path");
4
+ const readline = require("node:readline");
5
+
6
+ async function purgeProjectUsage({
7
+ projectKey,
8
+ projectQueuePath,
9
+ projectQueueStatePath,
10
+ projectState,
11
+ cursors,
12
+ }) {
13
+ if (!projectKey || !projectQueuePath || !projectQueueStatePath || !projectState) {
14
+ return { removed: 0, kept: 0, removedBuckets: 0, removedProjectCursors: 0 };
15
+ }
16
+
17
+ let previousOffset = 0;
18
+ const previousState = await fsp.readFile(projectQueueStatePath, "utf8").catch(() => null);
19
+ if (previousState) {
20
+ try {
21
+ const parsed = JSON.parse(previousState);
22
+ const offset = Number(parsed?.offset || 0);
23
+ if (Number.isFinite(offset) && offset >= 0) previousOffset = offset;
24
+ } catch (_err) {
25
+ previousOffset = 0;
26
+ }
27
+ }
28
+
29
+ const buckets =
30
+ projectState.buckets && typeof projectState.buckets === "object" ? projectState.buckets : {};
31
+ let removedBuckets = 0;
32
+ const prefix = `${projectKey}|`;
33
+ for (const key of Object.keys(buckets)) {
34
+ if (key.startsWith(prefix)) {
35
+ delete buckets[key];
36
+ removedBuckets += 1;
37
+ }
38
+ }
39
+ projectState.buckets = buckets;
40
+
41
+ let removedProjectCursors = 0;
42
+ const files = cursors?.files && typeof cursors.files === "object" ? cursors.files : {};
43
+ for (const cursor of Object.values(files)) {
44
+ if (!cursor || typeof cursor !== "object") continue;
45
+ if (cursor.project?.projectKey === projectKey) {
46
+ delete cursor.project;
47
+ removedProjectCursors += 1;
48
+ }
49
+ }
50
+
51
+ let removed = 0;
52
+ let kept = 0;
53
+ let nextOffset = 0;
54
+ const st = await fsp.stat(projectQueuePath).catch(() => null);
55
+ if (st && st.isFile()) {
56
+ const tmpPath = `${projectQueuePath}.tmp`;
57
+ await fsp.mkdir(path.dirname(projectQueuePath), { recursive: true });
58
+ const input = fs.createReadStream(projectQueuePath, "utf8");
59
+ const output = fs.createWriteStream(tmpPath, { encoding: "utf8" });
60
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
61
+
62
+ let inputOffset = 0;
63
+ let outputOffset = 0;
64
+ for await (const line of rl) {
65
+ const trimmed = line.trim();
66
+ const inputBytes = Buffer.byteLength(line, "utf8") + 1;
67
+ inputOffset += inputBytes;
68
+ if (!trimmed) continue;
69
+ let parsed = null;
70
+ try {
71
+ parsed = JSON.parse(trimmed);
72
+ } catch (_err) {
73
+ const entry = trimmed + "\n";
74
+ output.write(entry);
75
+ outputOffset += Buffer.byteLength(entry, "utf8");
76
+ kept += 1;
77
+ if (inputOffset <= previousOffset) {
78
+ nextOffset = outputOffset;
79
+ }
80
+ continue;
81
+ }
82
+ if (parsed && parsed.project_key === projectKey) {
83
+ removed += 1;
84
+ if (inputOffset <= previousOffset) {
85
+ nextOffset = outputOffset;
86
+ }
87
+ continue;
88
+ }
89
+ const entry = JSON.stringify(parsed) + "\n";
90
+ output.write(entry);
91
+ outputOffset += Buffer.byteLength(entry, "utf8");
92
+ kept += 1;
93
+ if (inputOffset <= previousOffset) {
94
+ nextOffset = outputOffset;
95
+ }
96
+ }
97
+
98
+ await new Promise((resolve, reject) => {
99
+ output.end(resolve);
100
+ output.on("error", reject);
101
+ });
102
+
103
+ await fsp.rename(tmpPath, projectQueuePath);
104
+ if (previousOffset >= inputOffset) {
105
+ nextOffset = outputOffset;
106
+ }
107
+ } else {
108
+ await fsp.writeFile(projectQueuePath, "", "utf8");
109
+ nextOffset = 0;
110
+ }
111
+
112
+ await fsp.writeFile(projectQueueStatePath, JSON.stringify({ offset: nextOffset }), "utf8");
113
+
114
+ return { removed, kept, removedBuckets, removedProjectCursors };
115
+ }
116
+
117
+ module.exports = { purgeProjectUsage };
package/src/lib/prompt.js CHANGED
@@ -1,24 +1,24 @@
1
- const readline = require("node:readline");
2
-
3
- async function prompt(label) {
4
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
5
- const value = await new Promise((resolve) => rl.question(label, resolve));
6
- rl.close();
7
- return String(value || "").trim();
8
- }
9
-
10
- async function promptHidden(label) {
11
- const rl = readline.createInterface({
12
- input: process.stdin,
13
- output: process.stdout,
14
- terminal: true,
15
- });
16
- const value = await new Promise((resolve) => {
17
- rl._writeToOutput = function _writeToOutput() {};
18
- rl.question(label, (answer) => resolve(answer));
19
- });
20
- rl.close();
21
- return String(value || "").trim();
22
- }
23
-
24
- module.exports = { prompt, promptHidden };
1
+ const readline = require("node:readline");
2
+
3
+ async function prompt(label) {
4
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
5
+ const value = await new Promise((resolve) => rl.question(label, resolve));
6
+ rl.close();
7
+ return String(value || "").trim();
8
+ }
9
+
10
+ async function promptHidden(label) {
11
+ const rl = readline.createInterface({
12
+ input: process.stdin,
13
+ output: process.stdout,
14
+ terminal: true,
15
+ });
16
+ const value = await new Promise((resolve) => {
17
+ rl._writeToOutput = function _writeToOutput() {};
18
+ rl.question(label, (answer) => resolve(answer));
19
+ });
20
+ rl.close();
21
+ return String(value || "").trim();
22
+ }
23
+
24
+ module.exports = { prompt, promptHidden };
@@ -1,104 +1,104 @@
1
- // Provider service-status probes (Statuspage.io-style), CodexBar-inspired.
2
- //
3
- // Answers "is the provider itself down?" so the limits panel can explain
4
- // upstream failures instead of leaving users guessing (issue: users read a
5
- // red/stale Claude limits row as a Token Usage bug during Anthropic
6
- // incidents). Fail-soft by design: a probe failure never breaks the limits
7
- // response — callers get the last good reading or null, never a throw.
8
- //
9
- // Statuspage.io contract (`/api/v2/status.json`):
10
- // { "page": { "updated_at": ISO }, "status": { "indicator": "none|minor|major|critical", "description": "..." } }
11
-
12
- const STATUS_PROBE_TIMEOUT_MS = 6_000;
13
- // Status pages change on incident timescales; 5 minutes keeps the limits
14
- // poll (2-min TTL upstream) from hammering statuspage.io every cycle.
15
- const STATUS_CACHE_TTL_MS = 5 * 60 * 1000;
16
- // Serve a stale last-good reading for up to 30 minutes when probes fail, so a
17
- // transient network blip doesn't flap the incident row on and off.
18
- const STATUS_LAST_GOOD_MAX_AGE_MS = 30 * 60 * 1000;
19
-
20
- const STATUS_PAGE_SPECS = {
21
- claude: {
22
- // status.anthropic.com 302-redirects here; use the canonical host directly.
23
- apiUrl: "https://status.claude.com/api/v2/status.json",
24
- pageUrl: "https://status.claude.com",
25
- },
26
- };
27
-
28
- const VALID_INDICATORS = new Set(["none", "minor", "major", "critical"]);
29
-
30
- // providerId -> { data, fetchedAtMs } (data may be null after a failed probe
31
- // with no last-good to fall back on).
32
- let statusCache = new Map();
33
-
34
- function normalizeStatusPayload(payload, spec, nowMs) {
35
- const indicator = payload?.status?.indicator;
36
- if (typeof indicator !== "string" || !VALID_INDICATORS.has(indicator)) return null;
37
- const description = typeof payload?.status?.description === "string"
38
- ? payload.status.description.trim()
39
- : "";
40
- const updatedAt = typeof payload?.page?.updated_at === "string" && payload.page.updated_at
41
- ? payload.page.updated_at
42
- : new Date(nowMs).toISOString();
43
- return {
44
- indicator,
45
- description: description || null,
46
- updated_at: updatedAt,
47
- url: spec.pageUrl,
48
- };
49
- }
50
-
51
- /**
52
- * Fetch a provider's public service status. Never throws; returns
53
- * `{ indicator, description, updated_at, url }` or null when the provider has
54
- * no status page, the probe fails with no usable last-good reading, or the
55
- * payload is malformed.
56
- */
57
- async function fetchProviderServiceStatus(providerId, { fetchImpl = fetch, nowMs = Date.now() } = {}) {
58
- const spec = STATUS_PAGE_SPECS[providerId];
59
- if (!spec) return null;
60
-
61
- const cached = statusCache.get(providerId);
62
- if (cached && nowMs - cached.fetchedAtMs < STATUS_CACHE_TTL_MS) {
63
- return cached.data;
64
- }
65
-
66
- let data = null;
67
- try {
68
- const controller = new AbortController();
69
- const timer = setTimeout(() => controller.abort(), STATUS_PROBE_TIMEOUT_MS);
70
- try {
71
- const res = await fetchImpl(spec.apiUrl, {
72
- method: "GET",
73
- headers: { Accept: "application/json" },
74
- signal: controller.signal,
75
- });
76
- if (res.ok) {
77
- data = normalizeStatusPayload(await res.json(), spec, nowMs);
78
- }
79
- } finally {
80
- clearTimeout(timer);
81
- }
82
- } catch (_error) {
83
- // fall through to last-good handling below
84
- }
85
-
86
- if (!data && cached?.data && nowMs - cached.fetchedAtMs < STATUS_LAST_GOOD_MAX_AGE_MS) {
87
- // Probe failed: keep serving the previous reading (without refreshing its
88
- // clock, so a dead status page eventually ages out to null).
89
- return cached.data;
90
- }
91
-
92
- statusCache.set(providerId, { data, fetchedAtMs: nowMs });
93
- return data;
94
- }
95
-
96
- function resetProviderStatusCache() {
97
- statusCache = new Map();
98
- }
99
-
100
- module.exports = {
101
- fetchProviderServiceStatus,
102
- resetProviderStatusCache,
103
- STATUS_PAGE_SPECS,
104
- };
1
+ // Provider service-status probes (Statuspage.io-style), CodexBar-inspired.
2
+ //
3
+ // Answers "is the provider itself down?" so the limits panel can explain
4
+ // upstream failures instead of leaving users guessing (issue: users read a
5
+ // red/stale Claude limits row as a Token Usage bug during Anthropic
6
+ // incidents). Fail-soft by design: a probe failure never breaks the limits
7
+ // response — callers get the last good reading or null, never a throw.
8
+ //
9
+ // Statuspage.io contract (`/api/v2/status.json`):
10
+ // { "page": { "updated_at": ISO }, "status": { "indicator": "none|minor|major|critical", "description": "..." } }
11
+
12
+ const STATUS_PROBE_TIMEOUT_MS = 6_000;
13
+ // Status pages change on incident timescales; 5 minutes keeps the limits
14
+ // poll (2-min TTL upstream) from hammering statuspage.io every cycle.
15
+ const STATUS_CACHE_TTL_MS = 5 * 60 * 1000;
16
+ // Serve a stale last-good reading for up to 30 minutes when probes fail, so a
17
+ // transient network blip doesn't flap the incident row on and off.
18
+ const STATUS_LAST_GOOD_MAX_AGE_MS = 30 * 60 * 1000;
19
+
20
+ const STATUS_PAGE_SPECS = {
21
+ claude: {
22
+ // status.anthropic.com 302-redirects here; use the canonical host directly.
23
+ apiUrl: "https://status.claude.com/api/v2/status.json",
24
+ pageUrl: "https://status.claude.com",
25
+ },
26
+ };
27
+
28
+ const VALID_INDICATORS = new Set(["none", "minor", "major", "critical"]);
29
+
30
+ // providerId -> { data, fetchedAtMs } (data may be null after a failed probe
31
+ // with no last-good to fall back on).
32
+ let statusCache = new Map();
33
+
34
+ function normalizeStatusPayload(payload, spec, nowMs) {
35
+ const indicator = payload?.status?.indicator;
36
+ if (typeof indicator !== "string" || !VALID_INDICATORS.has(indicator)) return null;
37
+ const description = typeof payload?.status?.description === "string"
38
+ ? payload.status.description.trim()
39
+ : "";
40
+ const updatedAt = typeof payload?.page?.updated_at === "string" && payload.page.updated_at
41
+ ? payload.page.updated_at
42
+ : new Date(nowMs).toISOString();
43
+ return {
44
+ indicator,
45
+ description: description || null,
46
+ updated_at: updatedAt,
47
+ url: spec.pageUrl,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Fetch a provider's public service status. Never throws; returns
53
+ * `{ indicator, description, updated_at, url }` or null when the provider has
54
+ * no status page, the probe fails with no usable last-good reading, or the
55
+ * payload is malformed.
56
+ */
57
+ async function fetchProviderServiceStatus(providerId, { fetchImpl = fetch, nowMs = Date.now() } = {}) {
58
+ const spec = STATUS_PAGE_SPECS[providerId];
59
+ if (!spec) return null;
60
+
61
+ const cached = statusCache.get(providerId);
62
+ if (cached && nowMs - cached.fetchedAtMs < STATUS_CACHE_TTL_MS) {
63
+ return cached.data;
64
+ }
65
+
66
+ let data = null;
67
+ try {
68
+ const controller = new AbortController();
69
+ const timer = setTimeout(() => controller.abort(), STATUS_PROBE_TIMEOUT_MS);
70
+ try {
71
+ const res = await fetchImpl(spec.apiUrl, {
72
+ method: "GET",
73
+ headers: { Accept: "application/json" },
74
+ signal: controller.signal,
75
+ });
76
+ if (res.ok) {
77
+ data = normalizeStatusPayload(await res.json(), spec, nowMs);
78
+ }
79
+ } finally {
80
+ clearTimeout(timer);
81
+ }
82
+ } catch (_error) {
83
+ // fall through to last-good handling below
84
+ }
85
+
86
+ if (!data && cached?.data && nowMs - cached.fetchedAtMs < STATUS_LAST_GOOD_MAX_AGE_MS) {
87
+ // Probe failed: keep serving the previous reading (without refreshing its
88
+ // clock, so a dead status page eventually ages out to null).
89
+ return cached.data;
90
+ }
91
+
92
+ statusCache.set(providerId, { data, fetchedAtMs: nowMs });
93
+ return data;
94
+ }
95
+
96
+ function resetProviderStatusCache() {
97
+ statusCache = new Map();
98
+ }
99
+
100
+ module.exports = {
101
+ fetchProviderServiceStatus,
102
+ resetProviderStatusCache,
103
+ STATUS_PAGE_SPECS,
104
+ };