tokenusage-cli 0.5.2 → 0.5.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,45 @@
6
6
  > 0.4.x 之前的条目为压缩摘要;细节与当时的验收记录见 `docs/cli-release.md`
7
7
  > 与 `docs/archive/`。
8
8
 
9
+ ## 0.5.4
10
+
11
+ 2026-11-09。tracker 目录写入被拒时的可诊断性与降级。零契约变更,服务端无需同步升级;对账
12
+ 基线(`queue.jsonl` last-wins)与队列文件格式不变。
13
+
14
+ - **原子写的临时文件创建加短重试**:Windows 上过滤驱动或上一轮释放的收尾窗口会让 `*.tmp`
15
+ 创建偶发返回 `EPERM`/`EBUSY`;此前 `writeFileAtomic` 直接抛出,桌面端「立即同步」「暂停
16
+ 采集」以一行裸 errno 中断。现在与 `sync.lock` 同策略(3 × 150 ms),耗尽后才原样上抛。
17
+ - **写入失败附带可读提示**:`EPERM`/`EACCES`/`EBUSY`/`EROFS` 时错误挂一行
18
+ `Hint: Cannot create files in <目录> (<code>) …`,点明「进程权限或完整性级别低于该目录」并
19
+ 给出处理方向;`bin/tokenusage.js` 打印 `Hint:`,桌面端 Alert 直接可见。
20
+ - **`pause` 标志改走 `writeFileAtomic`**:原先手写 `<file>.<pid>.tmp`,没有任何保护;
21
+ `resume` 的 unlink 失败同样附带 hint。
22
+ - **skip 标记写入失败不再致命**:锁没拿到时若 `sync.skip.json` 写不进去,仍输出同义的
23
+ `Sync skipped: … (<code>)` 并以 exit 0 结束——标记缺失只影响可观测面,不会把一次「跳过」
24
+ 升级成崩溃。
25
+
26
+ 升级说明:无需任何动作,随下次计划任务自动生效;桌面端「立即同步 / 暂停」遇到这类拒绝时
27
+ 从裸崩溃改为可读错误。
28
+
29
+ ## 0.5.3
30
+
31
+ 2026-11-09。同步锁稳健性 + 上游命令名残留清理。零契约变更,服务端无需同步升级;对账基线
32
+ (`queue.jsonl` last-wins)与队列文件格式不变。
33
+
34
+ - **sync.lock 瞬时创建被拒不再裸崩**:Windows 上过滤驱动或上一轮释放的收尾窗口,会让锁文件
35
+ 名的创建偶发返回 `EPERM`(或共享冲突的 `EBUSY`)——此前只把「名字已存在」(`EEXIST`)当作
36
+ 被占用,其余错误码直接抛出,桌面端「立即同步」会以一行裸 errno 中断。现在这两个错误码先
37
+ 做一轮短重试(3 × 150 ms,多数瞬时态自愈),仍未拿到锁则归入既有的「锁不可得」语义:写
38
+ `sync.skip.json` 标记(`lock_busy` + 可读 detail)、正常退出,采集不被打断,持久性损坏也
39
+ 保持可观测。活锁持有者仍然只走 `EEXIST` 路径,行为不变。
40
+ - **上游 `tracker` 命令名残留清理**:`device-login` 的配对码过期提示此前让用户 re-run
41
+ `tracker device-login`,而本 fork 的二进制叫 `tokenusage`——照着敲会得到「命令不存在」;
42
+ 源码内同类残留(注释里的 `tracker sync` / `tracker status` 等)一并改正,branding 守卫
43
+ 测试锁死回潮。
44
+
45
+ 升级说明:无需任何动作,随下次计划任务自动生效;修复对桌面端「立即同步」立竿见影
46
+ (下一版桌面端随附的 CLI 同理)。
47
+
9
48
  ## 0.5.2
10
49
 
11
50
  2026-11-08。上传队列防线:彻底消除「毒批/超大批次导致队头永久卡死」类故障。零契约变更,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
4
4
  "description": "Self-hosted AI coding token usage collector for the Token Usage dashboard.",
5
5
  "keywords": [
6
6
  "token-usage",
@@ -174,7 +174,7 @@ async function cmdDeviceLogin(argv = [], options = {}) {
174
174
  return;
175
175
  }
176
176
  if (result.status === "expired") {
177
- throw new Error("device_code expired — re-run `tracker device-login`");
177
+ throw new Error("device_code expired — re-run `tokenusage device-login`");
178
178
  }
179
179
  if (result.status === "unknown") {
180
180
  throw new Error("device_code is unknown — server may have evicted it");
@@ -1233,7 +1233,7 @@ async function applyIntegrationSetup({
1233
1233
  }
1234
1234
 
1235
1235
  // CodeBuddy: Claude-Code fork. Install the SessionEnd hook so finished
1236
- // sessions trigger notify.cjs → tracker sync; passive scan still runs as a
1236
+ // sessions trigger notify.cjs → tokenusage sync; passive scan still runs as a
1237
1237
  // safety net for sessions that don't fire SessionEnd cleanly.
1238
1238
  const codebuddyDirExists = want("codebuddy") && await isDir(context.codebuddyDir);
1239
1239
  if (!want("codebuddy")) {
@@ -1249,7 +1249,7 @@ async function applyIntegrationSetup({
1249
1249
  }
1250
1250
 
1251
1251
  // WorkBuddy: sibling Claude-Code fork. Same SessionEnd hook → notify.cjs →
1252
- // tracker sync; passive scan still runs as a safety net.
1252
+ // tokenusage sync; passive scan still runs as a safety net.
1253
1253
  const workbuddyDirExists = want("workbuddy") && await isDir(context.workbuddyDir);
1254
1254
  if (!want("workbuddy")) {
1255
1255
  summary.push(notSelectedItem("workbuddy"));
@@ -25,7 +25,7 @@ async function cmdPause() {
25
25
  const { trackerDir } = await resolveTrackerPaths({ home: os.homedir() });
26
26
  const alreadyPaused = isCollectionPaused(trackerDir);
27
27
 
28
- setCollectionPaused(trackerDir, true);
28
+ await setCollectionPaused(trackerDir, true);
29
29
  const schedule = setAutoSyncEnabled(false);
30
30
 
31
31
  process.stdout.write(
@@ -46,7 +46,7 @@ async function cmdResume() {
46
46
  const { trackerDir } = await resolveTrackerPaths({ home: os.homedir() });
47
47
  const wasPaused = isCollectionPaused(trackerDir);
48
48
 
49
- setCollectionPaused(trackerDir, false);
49
+ await setCollectionPaused(trackerDir, false);
50
50
  const schedule = setAutoSyncEnabled(true);
51
51
 
52
52
  process.stdout.write(
@@ -693,8 +693,19 @@ async function cmdSync(argv, context = {}) {
693
693
  const lock = await acquireSyncLock(lockPath, opts, lockWaitOptions);
694
694
  if (!lock) {
695
695
  // Warn on stderr so the notice reaches interactive and background runs
696
- // alike without disturbing anything that parses sync's stdout.
697
- process.stderr.write(await recordSyncSkip(trackerDir, lockPath));
696
+ // alike without disturbing anything that parses sync's stdout. The marker
697
+ // is diagnostics, not the skip itself: a failed write (Windows' transient
698
+ // EPERM on create) must not turn a skipped sync into a crash — the notice
699
+ // still reaches stderr, just without the marker.
700
+ let notice;
701
+ try {
702
+ notice = await recordSyncSkip(trackerDir, lockPath);
703
+ } catch (error) {
704
+ notice =
705
+ "Sync skipped: sync lock could not be acquired — " +
706
+ `failed to write ${SYNC_SKIP_MARKER} (${error?.code || error?.message || "unknown error"})\n`;
707
+ }
708
+ process.stderr.write(notice);
698
709
  return;
699
710
  }
700
711
  let progress = null;
@@ -11,6 +11,8 @@
11
11
  const fs = require("node:fs");
12
12
  const path = require("node:path");
13
13
 
14
+ const { writeFileAtomic, attachWriteHint } = require("./fs");
15
+
14
16
  const PAUSE_FILE = "pause.flag.json";
15
17
  const RUN_REPORT_KEY = "runReport";
16
18
 
@@ -39,22 +41,23 @@ function readCollectionPause(trackerDir) {
39
41
  }
40
42
  }
41
43
 
42
- function setCollectionPaused(trackerDir, paused, { at = new Date().toISOString() } = {}) {
43
- fs.mkdirSync(trackerDir, { recursive: true });
44
+ // Async so the write goes through writeFileAtomic (same-directory tmp + rename,
45
+ // with its short retry for Windows' transient EPERM on create): the previous
46
+ // hand-rolled `${file}.${process.pid}.tmp` write aborted `tokenusage pause`
47
+ // with a bare errno instead of landing the flag.
48
+ async function setCollectionPaused(trackerDir, paused, { at = new Date().toISOString() } = {}) {
44
49
  const file = pauseFilePath(trackerDir);
45
50
 
46
51
  if (!paused) {
47
52
  try {
48
53
  fs.unlinkSync(file);
49
54
  } catch (error) {
50
- if (error?.code !== "ENOENT") throw error;
55
+ if (error?.code !== "ENOENT") throw attachWriteHint(error, file);
51
56
  }
52
57
  return;
53
58
  }
54
59
 
55
- const tmp = `${file}.${process.pid}.tmp`;
56
- fs.writeFileSync(tmp, `${JSON.stringify({ paused: true, at })}\n`, { mode: 0o600 });
57
- fs.renameSync(tmp, file);
60
+ await writeFileAtomic(file, `${JSON.stringify({ paused: true, at })}\n`, { mode: 0o600 });
58
61
  }
59
62
 
60
63
  function isRunReportEnabled(trackerDir) {
@@ -162,7 +162,7 @@ async function collectTrackerDiagnostics({
162
162
  const kiroCliDbPath = resolveKiroCliDbPathInline(process.env, home);
163
163
  const kiroCliPresent = require("node:fs").existsSync(kiroCliDbPath);
164
164
 
165
- // WSL installs (win32 only) — surfaced so `tracker doctor --json` can
165
+ // WSL installs (win32 only) — surfaced so `tokenusage doctor --json` can
166
166
  // confirm dual-install discovery without running a sync.
167
167
  let kiroWslInstalls = null;
168
168
  let claudeWslProjects = null;
package/src/lib/fs.js CHANGED
@@ -16,11 +16,7 @@ async function writeFileAtomic(filePath, content, { mode } = {}) {
16
16
  // private from creation instead of relying on a later chmod that a crash
17
17
  // between write and chmod would skip.
18
18
  try {
19
- await fs.writeFile(
20
- tmp,
21
- content,
22
- mode == null ? { encoding: "utf8" } : { encoding: "utf8", mode },
23
- );
19
+ await writeTmpFile(tmp, content, mode);
24
20
  await fs.rename(tmp, filePath);
25
21
  } catch (err) {
26
22
  try {
@@ -28,7 +24,7 @@ async function writeFileAtomic(filePath, content, { mode } = {}) {
28
24
  } catch {
29
25
  /* tmp may not exist if writeFile failed before creating it */
30
26
  }
31
- throw err;
27
+ throw attachWriteHint(err, filePath);
32
28
  }
33
29
  }
34
30
 
@@ -72,6 +68,62 @@ const MAX_RECLAIM_DEPTH = 4;
72
68
  const MAX_RECLAIM_SWEEP_DEPTH = 64;
73
69
  const TRANSITION_GUARD_RETRY_MS = 5;
74
70
  const TRANSITION_GUARD_ATTEMPTS = 1000;
71
+ // Windows: creating the lock NAME itself can transiently fail with
72
+ // ERROR_ACCESS_DENIED (Node reports EPERM; sharing-mode conflicts surface as
73
+ // EBUSY) while a filter driver settles or the previous lease's release
74
+ // completes. A live holder can never produce these codes — an existing name
75
+ // always collides as EEXIST first. Retry briefly, then fall through to the
76
+ // held semantics so a real constant failure stays visible via sync.skip.json
77
+ // instead of crashing every run with a raw errno (issue #431's lesson: lock
78
+ // trouble must be survivable and queryable, not loud).
79
+ const LOCK_TRANSIENT_OPEN_RETRIES = 3;
80
+ const LOCK_TRANSIENT_OPEN_RETRY_MS = 150;
81
+ // The same Windows create-denial that the lock absorbs also hits plain atomic
82
+ // writes: `sync.skip.json.tmp…` and `pause.flag.json…tmp` surfaced a raw EPERM
83
+ // and aborted the command (desktop「立即同步」/「暂停采集」). Retry the tmp create
84
+ // briefly, then let the error out unchanged.
85
+ const WRITE_TRANSIENT_RETRIES = 3;
86
+ const WRITE_TRANSIENT_RETRY_MS = 150;
87
+
88
+ function isTransientCreateError(error) {
89
+ return error?.code === "EPERM" || error?.code === "EBUSY";
90
+ }
91
+
92
+ // A write failure is usually actionable in one specific way: the *folder*
93
+ // refused the create (permissions, or a process integrity level lower than the
94
+ // folder's label). Attach that as a one-line hint — bin/tokenusage.js prints
95
+ // `hint` after the error, and the desktop's actions card shows the same tail.
96
+ const WRITE_HINT_CODES = new Set(["EPERM", "EACCES", "EBUSY", "EROFS"]);
97
+
98
+ function attachWriteHint(error, filePath) {
99
+ if (!error || typeof error !== "object" || error.hint) return error;
100
+ if (!WRITE_HINT_CODES.has(error.code)) return error;
101
+ const dir = path.dirname(filePath);
102
+ error.hint =
103
+ `Cannot create files in ${dir} (${error.code}). ` +
104
+ "The process may run with less access or a lower integrity level than that folder " +
105
+ "(for example inside a sandbox, or started by a host process that runs at low integrity). " +
106
+ "Retry from a normal terminal, or grant this user write access to the folder.";
107
+ return error;
108
+ }
109
+
110
+ async function writeTmpFile(tmp, content, mode) {
111
+ for (let attempt = 0; ; attempt += 1) {
112
+ try {
113
+ await fs.writeFile(
114
+ tmp,
115
+ content,
116
+ mode == null ? { encoding: "utf8" } : { encoding: "utf8", mode },
117
+ );
118
+ return;
119
+ } catch (error) {
120
+ if (attempt >= WRITE_TRANSIENT_RETRIES - 1 || !isTransientCreateError(error)) {
121
+ throw error;
122
+ }
123
+ await new Promise((resolve) => setTimeout(resolve, WRITE_TRANSIENT_RETRY_MS));
124
+ }
125
+ }
126
+ }
75
127
 
76
128
  function parseLockOwner(raw) {
77
129
  try {
@@ -290,6 +342,7 @@ async function openLock(
290
342
  reclaimDepth = 0,
291
343
  serializeRelease = true,
292
344
  sweptReclaimGuards = false,
345
+ retryTransient = true,
293
346
  } = {},
294
347
  ) {
295
348
  try {
@@ -409,6 +462,38 @@ async function openLock(
409
462
  }
410
463
  return null;
411
464
  }
465
+ if (e && (e.code === "EPERM" || e.code === "EBUSY") && retryTransient) {
466
+ // Transient create-denial on the lock name (see LOCK_TRANSIENT_OPEN_*
467
+ // above): retry briefly, then the held semantics. Nothing about a live
468
+ // holder reaches this branch — EEXIST owns that path.
469
+ for (let attempt = 0; attempt < LOCK_TRANSIENT_OPEN_RETRIES; attempt += 1) {
470
+ await new Promise((resolve) =>
471
+ setTimeout(resolve, LOCK_TRANSIENT_OPEN_RETRY_MS),
472
+ );
473
+ try {
474
+ return await openLock(lockPath, {
475
+ quietIfLocked,
476
+ beforeReclaim,
477
+ beforeReleaseUnlink,
478
+ reclaimDepth,
479
+ serializeRelease,
480
+ sweptReclaimGuards,
481
+ retryTransient: false,
482
+ });
483
+ } catch (retryError) {
484
+ if (
485
+ !retryError ||
486
+ (retryError.code !== "EPERM" && retryError.code !== "EBUSY")
487
+ ) {
488
+ throw retryError;
489
+ }
490
+ }
491
+ }
492
+ if (!quietIfLocked) {
493
+ process.stdout.write("Another sync is already running.\n");
494
+ }
495
+ return null;
496
+ }
412
497
  throw e;
413
498
  }
414
499
  }
@@ -445,6 +530,7 @@ async function updateJsonLocked(
445
530
  module.exports = {
446
531
  ensureDir,
447
532
  writeFileAtomic,
533
+ attachWriteHint,
448
534
  readJson,
449
535
  readJsonStrict,
450
536
  writeJson,
@@ -12,13 +12,13 @@
12
12
  * session logs (`~/.claude/projects/`, `~/.gemini/sessions/`, etc.). Our
13
13
  * parsers can read those logs directly without the hook; the only loss is
14
14
  * "data is fresh within seconds" → it's now "data is fresh after the next
15
- * scheduled `tracker sync`".
15
+ * scheduled `tokenusage sync`".
16
16
  *
17
17
  * This module surfaces that fact: for each hook-driven provider, decide
18
18
  * whether the local install is in **passive mode** (no hook + log dir
19
- * present). `tracker status` reports it, and the dashboard can show a
19
+ * present). `tokenusage status` reports it, and the dashboard can show a
20
20
  * single banner asking the user whether to acknowledge & continue in
21
- * passive mode or attempt re-install (`tracker init`).
21
+ * passive mode or attempt re-install (`tokenusage init`).
22
22
  *
23
23
  * Detection is purely best-effort — we never *fail* sync because hooks are
24
24
  * missing; we just label the source so users / AI agents know latency is
@@ -250,6 +250,18 @@
250
250
  "cache_read": 0.06,
251
251
  "note": "InclusionAI Ant Ling 3.1 Flash (released 2026-09-29). Novita USD list via models.dev: $0.30/$0.90 per MTok input/output, $0.06 cache read; no published cache-write rate (retrieved 2026-11-08). Queue rows report the bare id; LiteLLM only carries ling-3.0 variants under provider-qualified keys."
252
252
  },
253
+ "ling-3.2-flash": {
254
+ "input": 0.3,
255
+ "output": 0.9,
256
+ "cache_read": 0.06,
257
+ "note": "InclusionAI Ant Ling 3.2 Flash (multimodal MoE, released 2026-11). Launch rates reported at parity with Ling 3.1 Flash ($0.30/$0.90 per MTok); the API is free on some channels during the launch window and no official pricing page has been located yet (retrieved 2026-11-08), so this entry is provisional — revisit against the official rate card. Spotted unpriced by `tokenusage doctor` pricing.coverage (dsh rows, ~20M tokens / 7d). Cache read mirrors the 3.1 pin pending a published cache-hit rate."
258
+ },
259
+ "Ling-3.2-flash": {
260
+ "input": 0.3,
261
+ "output": 0.9,
262
+ "cache_read": 0.06,
263
+ "note": "Same SKU and rates as ling-3.2-flash; the capitalized spelling is what the dsh collector actually reports (exact matching is case-sensitive, and the dot-restored form ling-3.2.flash cannot hit the dash key). Mirrors the MiniMax-M2.7-highspeed/minimax-m3 dual-registration precedent."
264
+ },
253
265
  "deepseek-v4-flash": {
254
266
  "input": 0.44,
255
267
  "output": 1.32,