tokenusage-cli 0.5.5 → 0.6.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.
@@ -2,6 +2,7 @@ const os = require("node:os");
2
2
  const path = require("node:path");
3
3
  const fs = require("node:fs/promises");
4
4
  const { expandHome } = require("../lib/scan-roots");
5
+ const { parseFlags } = require("../lib/cli-flags");
5
6
 
6
7
  const {
7
8
  restoreCodexNotify,
@@ -290,17 +291,17 @@ function formatOmpHookRemoveLine(ompHookRemove) {
290
291
  return "- oh-my-pi notify extension: no change";
291
292
  }
292
293
 
293
- function parseArgs(argv) {
294
- const out = { purge: false };
295
- for (let i = 0; i < argv.length; i++) {
296
- const a = argv[i];
297
- if (a === "--purge") out.purge = true;
298
- else throw new Error(`Unknown option: ${a}`);
299
- }
300
- return out;
294
+ const UNINSTALL_FLAGS = {
295
+ command: "uninstall",
296
+ defaults: { purge: false },
297
+ flags: [{ flag: "--purge", key: "purge" }],
298
+ };
299
+
300
+ function parseArgs(argv = []) {
301
+ return parseFlags(argv, UNINSTALL_FLAGS);
301
302
  }
302
303
 
303
- module.exports = { cmdUninstall, formatOmpHookRemoveLine };
304
+ module.exports = { cmdUninstall, formatOmpHookRemoveLine, parseArgs, flagSpec: UNINSTALL_FLAGS };
304
305
 
305
306
  async function isFile(p) {
306
307
  try {
@@ -24,22 +24,25 @@ const { readJson } = require("../lib/fs");
24
24
  const { cloudUsageResetBlocksUpload } = require("../lib/cloud-usage-reset");
25
25
  const { compactPendingQueue } = require("../lib/upload-queue");
26
26
  const { resolveRuntimeConfig } = require("../lib/runtime-config");
27
- const { UsageError, unknownOptionError } = require("../lib/cli-errors");
27
+ const { UsageError } = require("../lib/cli-errors");
28
+ const { parseFlags } = require("../lib/cli-flags");
28
29
  const { acquireSyncLock, drainQueueToCloud } = require("./sync");
29
30
 
30
31
  const BATCH_SIZE = 200;
31
32
  const MAX_BATCHES = 5;
32
33
  const MAX_BATCHES_DRAIN = 100;
33
34
 
34
- function parseArgs(argv) {
35
- const out = { drain: false, json: false };
36
- for (let i = 0; i < argv.length; i++) {
37
- const a = argv[i];
38
- if (a === "--drain" || a === "--force") out.drain = true;
39
- else if (a === "--json") out.json = true;
40
- else throw unknownOptionError(a, "upload");
41
- }
42
- return out;
35
+ const UPLOAD_FLAGS = {
36
+ command: "upload",
37
+ defaults: { drain: false, json: false },
38
+ flags: [
39
+ { flag: "--drain", aliases: ["--force"], key: "drain" },
40
+ { flag: "--json", key: "json" },
41
+ ],
42
+ };
43
+
44
+ function parseArgs(argv = []) {
45
+ return parseFlags(argv, UPLOAD_FLAGS);
43
46
  }
44
47
 
45
48
  async function pendingBytes(queuePath, queueStatePath) {
@@ -68,9 +71,12 @@ async function cmdUpload(argv, options = {}) {
68
71
  });
69
72
  }
70
73
 
74
+ // baseUrl 用解析后的 runtime:自托管实例地址通常来自 config.json 或
75
+ // --base-url,只读旧 INSFORGE env 会让 marker 的 base 永远不匹配,重置过的
76
+ // 队列永远无法通过 `upload` 收尾(sync 已在用运行时值)。
71
77
  const canUpload = () => !cloudUsageResetBlocksUpload(trackerDir, {
72
78
  ownerId: process.env.TOKENUSAGE_CLOUD_OWNER_ID,
73
- baseUrl: process.env.TOKENUSAGE_INSFORGE_BASE_URL,
79
+ baseUrl: runtime.baseUrl || process.env.TOKENUSAGE_INSFORGE_BASE_URL,
74
80
  deviceId: process.env.TOKENUSAGE_CLOUD_DEVICE_ID,
75
81
  });
76
82
  if (!canUpload()) {
@@ -148,4 +154,4 @@ async function cmdUpload(argv, options = {}) {
148
154
  );
149
155
  }
150
156
 
151
- module.exports = { cmdUpload, parseArgs };
157
+ module.exports = { cmdUpload, parseArgs, flagSpec: UPLOAD_FLAGS };
@@ -27,6 +27,10 @@ const path = require("node:path");
27
27
 
28
28
  const { runCommand, resolveBinaryPath, statBinaryInDirs, commonGlobalBinDirectories, resolvedCliEnvironment } = require("./command-runner");
29
29
 
30
+ const {
31
+ normalizeResetAt,
32
+ } = require("./limits-core");
33
+
30
34
  const ARK_LIMITS_CACHE_FILE = "ark-agent-plan-limits-cache.json";
31
35
  const ARK_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS = 12 * 60 * 60 * 1000;
32
36
  const ARK_USAGE_PLAN_TIMEOUT_MS = 10_000;
@@ -54,19 +58,6 @@ function clampPercent(value) {
54
58
  return Math.max(0, Math.min(100, value));
55
59
  }
56
60
 
57
- function normalizeResetAt(value) {
58
- if (value === null || value === undefined || value === "") return null;
59
- if (typeof value === "number" || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
60
- const raw = Number(value);
61
- if (!Number.isFinite(raw)) return null;
62
- const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
63
- const date = new Date(milliseconds);
64
- return Number.isFinite(date.getTime()) ? date.toISOString() : null;
65
- }
66
- const timestamp = Date.parse(String(value));
67
- return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
68
- }
69
-
70
61
  function planLabelForTier(tier) {
71
62
  const normalized = String(tier || "").trim().toLowerCase();
72
63
  const mapping = {
@@ -27,6 +27,10 @@ const path = require("node:path");
27
27
 
28
28
  const { runCommand, resolveBinaryPath, statBinaryInDirs, commonGlobalBinDirectories, resolvedCliEnvironment } = require("./command-runner");
29
29
 
30
+ const {
31
+ normalizeResetAt,
32
+ } = require("./limits-core");
33
+
30
34
  const ARK_LIMITS_CACHE_FILE = "ark-coding-plan-limits-cache.json";
31
35
  const ARK_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS = 12 * 60 * 60 * 1000;
32
36
  const ARK_USAGE_PLAN_TIMEOUT_MS = 10_000;
@@ -68,19 +72,6 @@ function clampPercent(value) {
68
72
  return Math.max(0, Math.min(100, value));
69
73
  }
70
74
 
71
- function normalizeResetAt(value) {
72
- if (value === null || value === undefined || value === "") return null;
73
- if (typeof value === "number" || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
74
- const raw = Number(value);
75
- if (!Number.isFinite(raw)) return null;
76
- const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
77
- const date = new Date(milliseconds);
78
- return Number.isFinite(date.getTime()) ? date.toISOString() : null;
79
- }
80
- const timestamp = Date.parse(String(value));
81
- return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
82
- }
83
-
84
75
  // The provider's display name is already "Ark Coding Plan", so the plan label
85
76
  // carries only the tier — otherwise the panel title would read
86
77
  // "Ark Coding Plan Coding Plan Lite".
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+
3
+ // 声明式旗标解析(唯一实现)。
4
+ //
5
+ // 每个命令只声明「接受哪些旗标、写进哪个字段」,三类错误的文案与退出码
6
+ // 统一在这里:未知旗标(UNKNOWN_OPTION)、值旗标缺值(MISSING_VALUE)、
7
+ // 布尔旗标被赋值(UNEXPECTED_VALUE)。此前 8 个命令各写一份 if/else,
8
+ // 同一类错误才会一会儿退出 2、一会儿退出 1(还带着「Re-run with --debug」
9
+ // 这种把用户拼错当成崩溃的提示)。
10
+ //
11
+ // `flagNames()` 供 `test/cli-surface.test.js` 做「帮助文案 ↔ 解析器」的
12
+ // 双向一致性断言:任一方向改漏都会红。
13
+ //
14
+ // const FLAGS = {
15
+ // command: "upload",
16
+ // defaults: { drain: false, json: false },
17
+ // flags: [
18
+ // { flag: "--drain", aliases: ["--force"], key: "drain" },
19
+ // { flag: "--json", key: "json" },
20
+ // { flag: "--out", key: "out", kind: "value" },
21
+ // ],
22
+ // };
23
+
24
+ const { UsageError, unknownOptionError } = require("./cli-errors");
25
+
26
+ function usageHint(command) {
27
+ return command
28
+ ? `Run \`tokenusage ${command} --help\` for supported options.`
29
+ : "Run `tokenusage --help` to see supported commands.";
30
+ }
31
+
32
+ function missingValueError(flag, command) {
33
+ return new UsageError(`${flag} requires a value`, {
34
+ code: "MISSING_VALUE",
35
+ hint: usageHint(command),
36
+ });
37
+ }
38
+
39
+ /**
40
+ * @param {string[]} argv 命令自身的参数(`--help` 已由 cli.js 剥离)
41
+ * @param {{
42
+ * command: string,
43
+ * defaults?: Record<string, unknown>,
44
+ * flags?: Array<{
45
+ * flag: string,
46
+ * aliases?: string[],
47
+ * key: string,
48
+ * kind?: "boolean" | "value",
49
+ * parse?: (raw: string, flag: string) => unknown,
50
+ * const?: unknown,
51
+ * }>,
52
+ * }} spec
53
+ */
54
+ function parseFlags(argv = [], { command, defaults = {}, flags = [] } = {}) {
55
+ const out = { ...defaults };
56
+ const byFlag = new Map();
57
+ for (const entry of flags) {
58
+ byFlag.set(entry.flag, entry);
59
+ for (const alias of entry.aliases || []) byFlag.set(alias, entry);
60
+ }
61
+
62
+ for (let i = 0; i < argv.length; i += 1) {
63
+ const token = String(argv[i]);
64
+ // 仅长旗标支持 `--flag=value`(与整改前各命令的行为一致)。
65
+ const eqIndex = token.startsWith("--") ? token.indexOf("=") : -1;
66
+ const name = eqIndex > 0 ? token.slice(0, eqIndex) : token;
67
+ const inlineValue = eqIndex > 0 ? token.slice(eqIndex + 1) : undefined;
68
+ const entry = byFlag.get(name);
69
+ if (!entry) throw unknownOptionError(token, command);
70
+
71
+ if ((entry.kind || "boolean") === "value") {
72
+ let raw = inlineValue;
73
+ if (raw === undefined) {
74
+ raw = argv[i + 1];
75
+ if (raw == null || raw === "" || String(raw).startsWith("--")) {
76
+ throw missingValueError(name, command);
77
+ }
78
+ i += 1;
79
+ } else if (raw === "") {
80
+ throw missingValueError(name, command);
81
+ }
82
+ out[entry.key] = entry.parse ? entry.parse(raw, name) : raw;
83
+ continue;
84
+ }
85
+
86
+ if (inlineValue !== undefined) {
87
+ throw new UsageError(`${name} takes no value`, {
88
+ code: "UNEXPECTED_VALUE",
89
+ hint: usageHint(command),
90
+ });
91
+ }
92
+ out[entry.key] = "const" in entry ? entry.const : true;
93
+ }
94
+
95
+ return out;
96
+ }
97
+
98
+ /** 该 spec 接受的全部旗标名(含别名),按声明顺序去重。 */
99
+ function flagNames(spec = {}) {
100
+ const names = [];
101
+ for (const entry of spec.flags || []) {
102
+ for (const name of [entry.flag, ...(entry.aliases || [])]) {
103
+ if (!names.includes(name)) names.push(name);
104
+ }
105
+ }
106
+ return names;
107
+ }
108
+
109
+ module.exports = { parseFlags, flagNames };
@@ -23,6 +23,17 @@
23
23
  const fs = require("node:fs");
24
24
  const path = require("node:path");
25
25
 
26
+ const {
27
+ clampPercent,
28
+ buildWindow,
29
+ normalizeResetAt: coreNormalizeResetAt,
30
+ } = require("./limits-core");
31
+
32
+ // CommandCode treats a non-positive resetAt as absent; 0 would render 1970.
33
+ function normalizeResetAt(value) {
34
+ return coreNormalizeResetAt(value, { rejectNonPositive: true });
35
+ }
36
+
26
37
  const COMMANDCODE_API_BASE_URL = "https://api.commandcode.ai";
27
38
  const COMMANDCODE_API_KEY_ENV = "COMMAND_CODE_API_KEY";
28
39
  const COMMANDCODE_AUTH_DIRNAME = ".commandcode";
@@ -78,44 +89,6 @@ function readCommandcodeApiKey({ home, env = process.env } = {}) {
78
89
  return isNonEmptyString(parsed?.apiKey) ? parsed.apiKey.trim() : null;
79
90
  }
80
91
 
81
- function normalizeResetAt(value) {
82
- if (value === null || value === undefined || value === "") return null;
83
- if (
84
- typeof value === "number" ||
85
- /^\d+(?:\.\d+)?$/.test(String(value).trim())
86
- ) {
87
- const raw = Number(value);
88
- if (!Number.isFinite(raw) || raw <= 0) return null;
89
- const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
90
- const date = new Date(milliseconds);
91
- return Number.isFinite(date.getTime()) ? date.toISOString() : null;
92
- }
93
- const timestamp = Date.parse(String(value));
94
- return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
95
- }
96
-
97
- function clampPercent(value) {
98
- if (value === null || value === undefined || value === "") return null;
99
- const n = Number(value);
100
- if (!Number.isFinite(n)) return null;
101
- if (n <= 0) return 0;
102
- if (n >= 100) return 100;
103
- return n;
104
- }
105
-
106
- function buildWindow({ usedPercent, resetAt, windowSeconds = null }) {
107
- const pct = clampPercent(usedPercent);
108
- if (pct === null) return null;
109
- const window = {
110
- used_percent: pct,
111
- reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
112
- };
113
- if (Number.isFinite(windowSeconds) && windowSeconds > 0) {
114
- window.limit_window_seconds = windowSeconds;
115
- }
116
- return window;
117
- }
118
-
119
92
  // Upstream window rows are `{ used, cap, resetAt }` (epoch ms). Tolerate the
120
93
  // snake_case spellings other providers use so a server rename stays a miss on
121
94
  // one window, not a crash.
package/src/lib/doctor.js CHANGED
@@ -3,7 +3,7 @@ const path = require("node:path");
3
3
  const { constants } = require("node:fs");
4
4
 
5
5
  const { readJsonStrict } = require("./fs");
6
- const { collectPricingCoverage } = require("./pricing-coverage");
6
+ const { collectPricingCoverage, readLastWinsBuckets } = require("./pricing-coverage");
7
7
 
8
8
  async function buildDoctorReport({
9
9
  runtime = {},
@@ -23,6 +23,7 @@ async function buildDoctorReport({
23
23
  checks.push(await checkTrackerDir(paths.trackerDir));
24
24
  checks.push(await checkRuntimeCopy(paths.trackerDir));
25
25
  checks.push(await checkPricingCoverage(paths.trackerDir));
26
+ checks.push(await checkSourceCoverage(paths.trackerDir, now));
26
27
  }
27
28
  if (paths.configPath) {
28
29
  checks.push(await checkConfigJson(paths.configPath));
@@ -312,6 +313,95 @@ async function checkPricingCoverage(trackerDir) {
312
313
  }
313
314
  }
314
315
 
316
+ // "No new rows for a week" is the point where an idle-but-installed tool and a
317
+ // broken parser look identical to a reader — sources.coverage names both.
318
+ const STALE_SOURCE_MS = 7 * 86_400_000;
319
+
320
+ // Every collection audit ends up asking the same question — "is this source
321
+ // actually landing rows, or did its parser quietly stop finding data?" — and
322
+ // the only way to answer it used to be an ad-hoc queue scan. Report the newest
323
+ // bucket per source over a 30-day window so a silent source is visible in one
324
+ // line; a queue whose newest bucket is over a week old is a warning, not a
325
+ // disease, because idle tools legitimately stop writing.
326
+ async function checkSourceCoverage(trackerDir, now = () => new Date()) {
327
+ const queuePath = path.join(trackerDir, "queue.jsonl");
328
+ const windowDays = 30;
329
+ const toMs = now().getTime();
330
+ const fromMs = toMs - windowDays * 86_400_000;
331
+ try {
332
+ const buckets = await readLastWinsBuckets({ queuePath, fromMs, toMs });
333
+ if (buckets.length === 0) {
334
+ return {
335
+ id: "sources.coverage",
336
+ status: "ok",
337
+ critical: false,
338
+ detail: `no local buckets in the last ${windowDays}d`,
339
+ meta: { window_days: windowDays, sources: [] },
340
+ };
341
+ }
342
+
343
+ const bySource = new Map();
344
+ for (const bucket of buckets) {
345
+ const entry = bySource.get(bucket.source) || {
346
+ source: bucket.source,
347
+ buckets: 0,
348
+ tokens: 0,
349
+ last_hour_start: bucket.hour_start,
350
+ };
351
+ entry.buckets += 1;
352
+ entry.tokens += bucket.total_tokens;
353
+ if (bucket.hour_start > entry.last_hour_start) entry.last_hour_start = bucket.hour_start;
354
+ bySource.set(bucket.source, entry);
355
+ }
356
+ const sources = [...bySource.values()].sort(
357
+ (a, b) => b.last_hour_start.localeCompare(a.last_hour_start) || a.source.localeCompare(b.source),
358
+ );
359
+
360
+ const newestMs = Date.parse(sources[0].last_hour_start);
361
+ const newestAgeMs = Number.isFinite(newestMs) ? Math.max(0, toMs - newestMs) : null;
362
+ const stale = sources.filter((entry) => {
363
+ const ms = Date.parse(entry.last_hour_start);
364
+ return Number.isFinite(ms) && toMs - ms > STALE_SOURCE_MS;
365
+ });
366
+
367
+ const parts = [
368
+ `${sources.length} source(s) in the last ${windowDays}d; newest ${sources[0].source}` +
369
+ (newestAgeMs === null ? "" : ` ${formatAge(newestAgeMs)} ago`),
370
+ ];
371
+ if (stale.length > 0) {
372
+ const shown = stale.slice(0, 5).map((entry) => {
373
+ const ms = Date.parse(entry.last_hour_start);
374
+ return `${entry.source} ${formatAge(Math.max(0, toMs - ms))}`;
375
+ });
376
+ parts.push(
377
+ `${stale.length} silent over ${STALE_SOURCE_MS / 86_400_000}d: ${shown.join(", ")}` +
378
+ (stale.length > shown.length ? ` (+${stale.length - shown.length} more)` : ""),
379
+ );
380
+ }
381
+
382
+ return {
383
+ id: "sources.coverage",
384
+ status: newestAgeMs !== null && newestAgeMs > STALE_SOURCE_MS ? "warn" : "ok",
385
+ critical: false,
386
+ detail: parts.join("; "),
387
+ meta: { window_days: windowDays, sources },
388
+ };
389
+ } catch (error) {
390
+ return {
391
+ id: "sources.coverage",
392
+ status: "warn",
393
+ critical: false,
394
+ detail: `source coverage check failed: ${error?.message || error}`,
395
+ };
396
+ }
397
+ }
398
+
399
+ function formatAge(ms) {
400
+ if (ms >= 86_400_000) return `${Math.floor(ms / 86_400_000)}d`;
401
+ if (ms >= 3_600_000) return `${Math.floor(ms / 3_600_000)}h`;
402
+ return `${Math.max(1, Math.floor(ms / 60_000))}m`;
403
+ }
404
+
315
405
  // The init-copied runtime (`<trackerDir>/app`) is what notify hooks and the
316
406
  // hidden task prefer; without its readiness marker they fall back to the
317
407
  // installed CLI. Surface that state instead of leaving it invisible.
package/src/lib/fs.js CHANGED
@@ -527,7 +527,17 @@ async function updateJsonLocked(
527
527
  }
528
528
  }
529
529
 
530
+ async function safeStatSize(p) {
531
+ try {
532
+ const st = await fs.stat(p);
533
+ return st && st.isFile() ? st.size : 0;
534
+ } catch (_e) {
535
+ return 0;
536
+ }
537
+ }
538
+
530
539
  module.exports = {
540
+ safeStatSize,
531
541
  ensureDir,
532
542
  writeFileAtomic,
533
543
  attachWriteHint,
@@ -2,6 +2,11 @@ const fs = require("node:fs");
2
2
  const os = require("node:os");
3
3
  const path = require("node:path");
4
4
 
5
+ const {
6
+ clampPercent,
7
+ buildWindow,
8
+ } = require("./limits-core");
9
+
5
10
  const DEFAULT_BILLING_BASE_URL = "https://cli-chat-proxy.grok.com";
6
11
  const DEFAULT_BILLING_TIMEOUT_MS = 15_000;
7
12
  const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;
@@ -103,24 +108,6 @@ function grokIsoReset(value) {
103
108
  return Number.isFinite(ts) && ts > 0 ? new Date(ts).toISOString() : null;
104
109
  }
105
110
 
106
- function clampPercent(value) {
107
- if (value === null || value === undefined || value === "") return null;
108
- const n = Number(value);
109
- if (!Number.isFinite(n)) return null;
110
- if (n <= 0) return 0;
111
- if (n >= 100) return 100;
112
- return n;
113
- }
114
-
115
- function buildWindow({ usedPercent, resetAt }) {
116
- const pct = clampPercent(usedPercent);
117
- if (pct === null) return null;
118
- return {
119
- used_percent: pct,
120
- reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
121
- };
122
- }
123
-
124
111
  /**
125
112
  * Map Grok's USAGE_PERIOD_TYPE_* enum (or a bare "weekly"/"monthly" string)
126
113
  * into a short period key the UI can switch labels on.
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+
3
+ // Shared primitives for the per-provider subscription limits readers.
4
+ //
5
+ // Every provider module grew its own copy of these while their quota payloads
6
+ // converged on the same shape (`used_percent` + `reset_at` ISO). The provider
7
+ // modules keep their provider-specific math — fraction scaling, resetInSec,
8
+ // used/cap pairs, HTML scraping — and share only what is provably identical.
9
+
10
+ // null for "no value" (missing, unparseable), otherwise 0..100 clamped.
11
+ function clampPercent(value) {
12
+ if (value === null || value === undefined || value === "") return null;
13
+ const n = Number(value);
14
+ if (!Number.isFinite(n)) return null;
15
+ if (n <= 0) return 0;
16
+ if (n >= 100) return 100;
17
+ return n;
18
+ }
19
+
20
+ function toFiniteNumberOrNull(value) {
21
+ if (value === null || value === undefined || value === "") return null;
22
+ const n = Number(value);
23
+ return Number.isFinite(n) ? n : null;
24
+ }
25
+
26
+ // Accepts epoch seconds, epoch milliseconds, numeric strings and ISO strings and
27
+ // always answers an ISO string (or null). Providers disagree on units, so the
28
+ // 10^10 threshold picks ms whenever the value is large enough to be one.
29
+ // `rejectNonPositive` is for providers where 0 means "absent" rather than 1970.
30
+ function normalizeResetAt(value, { rejectNonPositive = false } = {}) {
31
+ if (value === null || value === undefined || value === "") return null;
32
+ if (typeof value === "number" || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
33
+ const raw = Number(value);
34
+ if (!Number.isFinite(raw)) return null;
35
+ if (rejectNonPositive && raw <= 0) return null;
36
+ const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
37
+ const date = new Date(milliseconds);
38
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
39
+ }
40
+ const timestamp = Date.parse(String(value));
41
+ return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
42
+ }
43
+
44
+ // The window shape the dashboard and macOS app both read. A window without a
45
+ // usable percentage is dropped (null) rather than shown as an empty bar.
46
+ function buildWindow({ usedPercent, resetAt, windowSeconds = null }) {
47
+ const pct = clampPercent(usedPercent);
48
+ if (pct === null) return null;
49
+ const window = {
50
+ used_percent: pct,
51
+ reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
52
+ };
53
+ if (Number.isFinite(windowSeconds) && windowSeconds > 0) {
54
+ window.limit_window_seconds = windowSeconds;
55
+ }
56
+ return window;
57
+ }
58
+
59
+ module.exports = {
60
+ clampPercent,
61
+ toFiniteNumberOrNull,
62
+ normalizeResetAt,
63
+ buildWindow,
64
+ };
@@ -7,6 +7,10 @@ const os = require("node:os");
7
7
  const path = require("node:path");
8
8
  const { fetchQoderCnCliLimits } = require("./qoder-cn-cli-limits");
9
9
 
10
+ const {
11
+ normalizeResetAt,
12
+ } = require("./limits-core");
13
+
10
14
  const QODER_SITES = {
11
15
  international: {
12
16
  id: "international",
@@ -74,19 +78,6 @@ function firstDefined(object, camel, snake) {
74
78
  return object?.[camel] ?? object?.[snake];
75
79
  }
76
80
 
77
- function normalizeResetAt(value) {
78
- if (value === null || value === undefined || value === "") return null;
79
- if (typeof value === "number" || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
80
- const raw = Number(value);
81
- if (!Number.isFinite(raw)) return null;
82
- const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
83
- const date = new Date(milliseconds);
84
- return Number.isFinite(date.getTime()) ? date.toISOString() : null;
85
- }
86
- const timestamp = Date.parse(String(value));
87
- return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
88
- }
89
-
90
81
  function quotaSummary(container) {
91
82
  return firstDefined(container, "quotaSummary", "quota_summary") || null;
92
83
  }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs/promises");
4
+
5
+ // Copy a queue/state file next to itself before a destructive rewrite, so a
6
+ // repair that drops rows is always reversible. Missing file → null (nothing to
7
+ // back up); any other error propagates, because rewriting a queue without a
8
+ // backup is exactly the case this guards.
9
+ async function backupExistingFile(filePath) {
10
+ if (typeof filePath !== "string" || !filePath) return null;
11
+ try {
12
+ const stat = await fs.stat(filePath);
13
+ if (!stat.isFile()) return null;
14
+ } catch (e) {
15
+ if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return null;
16
+ throw e;
17
+ }
18
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
19
+ const backupPath = `${filePath}.bak.${stamp}`;
20
+ await fs.copyFile(filePath, backupPath);
21
+ return backupPath;
22
+ }
23
+
24
+ module.exports = { backupExistingFile };