tokenusage-cli 0.5.3 → 0.5.5

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,46 @@
6
6
  > 0.4.x 之前的条目为压缩摘要;细节与当时的验收记录见 `docs/cli-release.md`
7
7
  > 与 `docs/archive/`。
8
8
 
9
+ ## 0.5.5
10
+
11
+ 2026-11-11。新增只读子命令 `tokenusage project-profiles`(契约 §2.13),供桌面端伴生工具
12
+ 读取 web 上编辑的项目显示名 / logo / 仓库。零破坏性变更:现有子命令行为、对账基线与队列
13
+ 格式均不变,服务端只需部署含该 series 的版本(否则 CLI 报 `Unknown account series`,
14
+ 桌面端静默降级)。
15
+
16
+ - **新增 `tokenusage project-profiles`**:不带参数,凭证解析与 `sync` 同一条路径(运行时
17
+ 配置 → `cloud-device-token` 文件,自定义 base 需配 anon key),把账号的项目档案以**单行
18
+ JSON** 打到 stdout(`{"profiles":[{project_key, display_name, repo_url, repo_source,
19
+ detected_repo_url, manual_repo_url, repo_hidden, logo_url, logo_upload_url}]}`)。诊断信息
20
+ 一律走 stderr + `UsageError`(退出码 2),stdout 始终保持可解析。
21
+ - **桌面端消费方式**:桌面经 `run_cli` 捕获该行并解析,挂载时与每 5 分钟刷新一次,用于把
22
+ 项目列表 / 项目详情的显示名、logo、仓库链接对齐 web;未配对、HTTP 失败或旧 CLI 均静默
23
+ 降级为队列 key + 字母方块,界面不空。
24
+
25
+ 升级说明:装完即生效(无迁移动作)。Volta 托管的机器升级要跑 `volta install
26
+ tokenusage-cli@0.5.5`(`npm i -g` 只更新 image-dir 副本,`volta run` 仍解析 packages
27
+ 副本,见 `docs/cli-release.md` §十三/§十四)。
28
+
29
+ ## 0.5.4
30
+
31
+ 2026-11-09。tracker 目录写入被拒时的可诊断性与降级。零契约变更,服务端无需同步升级;对账
32
+ 基线(`queue.jsonl` last-wins)与队列文件格式不变。
33
+
34
+ - **原子写的临时文件创建加短重试**:Windows 上过滤驱动或上一轮释放的收尾窗口会让 `*.tmp`
35
+ 创建偶发返回 `EPERM`/`EBUSY`;此前 `writeFileAtomic` 直接抛出,桌面端「立即同步」「暂停
36
+ 采集」以一行裸 errno 中断。现在与 `sync.lock` 同策略(3 × 150 ms),耗尽后才原样上抛。
37
+ - **写入失败附带可读提示**:`EPERM`/`EACCES`/`EBUSY`/`EROFS` 时错误挂一行
38
+ `Hint: Cannot create files in <目录> (<code>) …`,点明「进程权限或完整性级别低于该目录」并
39
+ 给出处理方向;`bin/tokenusage.js` 打印 `Hint:`,桌面端 Alert 直接可见。
40
+ - **`pause` 标志改走 `writeFileAtomic`**:原先手写 `<file>.<pid>.tmp`,没有任何保护;
41
+ `resume` 的 unlink 失败同样附带 hint。
42
+ - **skip 标记写入失败不再致命**:锁没拿到时若 `sync.skip.json` 写不进去,仍输出同义的
43
+ `Sync skipped: … (<code>)` 并以 exit 0 结束——标记缺失只影响可观测面,不会把一次「跳过」
44
+ 升级成崩溃。
45
+
46
+ 升级说明:无需任何动作,随下次计划任务自动生效;桌面端「立即同步 / 暂停」遇到这类拒绝时
47
+ 从裸崩溃改为可读错误。
48
+
9
49
  ## 0.5.3
10
50
 
11
51
  2026-11-09。同步锁稳健性 + 上游命令名残留清理。零契约变更,服务端无需同步升级;对账基线
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "description": "Self-hosted AI coding token usage collector for the Token Usage dashboard.",
5
5
  "keywords": [
6
6
  "token-usage",
package/src/cli.js CHANGED
@@ -21,6 +21,7 @@ const { cmdDoctor } = require("./commands/doctor");
21
21
  const { cmdUninstall } = require("./commands/uninstall");
22
22
  const { cmdDeviceLogin } = require("./commands/device-login");
23
23
  const { cmdSessions } = require("./commands/sessions");
24
+ const { cmdProjectProfiles } = require("./commands/project-profiles");
24
25
  const { cmdPause, cmdResume } = require("./commands/pause");
25
26
 
26
27
  const DEFAULT_WATCH_INTERVAL_MS = 15 * 60_000;
@@ -223,6 +224,17 @@ const COMMANDS = [
223
224
  " --no-git Skip git outcome attribution",
224
225
  ],
225
226
  },
227
+ {
228
+ name: "project-profiles",
229
+ summary: "Print the web-edited project profiles (display name, logo, repo)",
230
+ run: (argv) => cmdProjectProfiles(argv),
231
+ usage: [
232
+ "tokenusage project-profiles",
233
+ "",
234
+ "Prints the account's project profiles as a single JSON line (contract",
235
+ "docs/cli-contract.md §2.13). No options.",
236
+ ],
237
+ },
226
238
  ];
227
239
 
228
240
  function findCommand(name) {
@@ -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(
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+
3
+ // `tokenusage project-profiles` — read-only mirror of the web-edited project
4
+ // profiles (docs/cli-contract.md §2.13), for the desktop companion: the
5
+ // desktop never reads the device token file (desktop-plan §3 boundary 1), so
6
+ // the CLI — which already holds the pairing credential — fetches the account
7
+ // payload and prints it as a single JSON line on stdout. Diagnostics travel
8
+ // through UsageError (stderr + exit 2) so stdout stays parseable.
9
+
10
+ const os = require("node:os");
11
+ const path = require("node:path");
12
+
13
+ const { readJson } = require("../lib/fs");
14
+ const { resolveTrackerPaths } = require("../lib/tracker-paths");
15
+ const { normalizeInstanceBaseUrl, resolveRuntimeConfig } = require("../lib/runtime-config");
16
+ const { readCloudDeviceTokenEntry } = require("../lib/cloud-device-token");
17
+ const { functionUrlFor, fetchFunctionResponse } = require("../lib/function-url");
18
+ const { UsageError, unknownOptionError } = require("../lib/cli-errors");
19
+
20
+ // Contract §2.13: the desktop parses this exact payload shape.
21
+ const SLUG = "token-usage-account-project-profiles";
22
+
23
+ function parseArgs(args = []) {
24
+ for (const a of args) throw unknownOptionError(a, "project-profiles");
25
+ return {};
26
+ }
27
+
28
+ /**
29
+ * Same resolution order as `resolveDeviceTokenPresence`: runtime config
30
+ * (env / config.json) first, then the cloud-device-token file — but this
31
+ * returns the VALUE, which the desktop's `run_cli` capture turns into data.
32
+ * The cloud file is only trusted when its recorded instance matches the
33
+ * configured one (same guard as the presence check).
34
+ */
35
+ async function resolveCredentials({ home }) {
36
+ const { trackerDir } = await resolveTrackerPaths({ home });
37
+ const config = (await readJson(path.join(trackerDir, "config.json"))) || {};
38
+ const runtime = resolveRuntimeConfig({ config, env: process.env });
39
+ const baseUrl =
40
+ typeof runtime.baseUrl === "string" ? runtime.baseUrl.trim() : "";
41
+ let deviceToken =
42
+ typeof runtime.deviceToken === "string" ? runtime.deviceToken.trim() : "";
43
+
44
+ if (!deviceToken) {
45
+ const entry = readCloudDeviceTokenEntry(
46
+ path.join(trackerDir, "cloud-device-token.json"),
47
+ );
48
+ // The cache entry stores the credential as `token` (bound to userId /
49
+ // baseUrl / machineId), unlike config.json's `deviceToken`.
50
+ const entryToken =
51
+ entry && typeof entry.token === "string" ? entry.token.trim() : "";
52
+ const entryBase = normalizeInstanceBaseUrl(
53
+ (entry && entry.baseUrl) || "",
54
+ );
55
+ const configuredBase = normalizeInstanceBaseUrl(baseUrl);
56
+
57
+ if (entryToken && (!configuredBase || entryBase === configuredBase)) {
58
+ deviceToken = entryToken;
59
+ }
60
+ }
61
+
62
+ return { baseUrl, deviceToken };
63
+ }
64
+
65
+ async function cmdProjectProfiles(argv = [], context = {}) {
66
+ parseArgs(argv);
67
+ const home = context.home || os.homedir();
68
+ const { baseUrl, deviceToken } = await resolveCredentials({ home });
69
+
70
+ if (!baseUrl || !deviceToken) {
71
+ throw new UsageError("This machine is not paired yet.", {
72
+ code: "NOT_PAIRED",
73
+ hint: "Run `tokenusage device-login` first, then try again.",
74
+ });
75
+ }
76
+
77
+ const res = await fetchFunctionResponse(functionUrlFor(baseUrl, SLUG), {
78
+ headers: {
79
+ Accept: "application/json",
80
+ Authorization: `Bearer ${deviceToken}`,
81
+ },
82
+ });
83
+ if (!res.ok) {
84
+ const body = (await res.text().catch(() => "")).replace(/\s+/g, " ").slice(0, 200);
85
+ throw new UsageError(`Request failed with HTTP ${res.status}.`, {
86
+ code: "HTTP_ERROR",
87
+ hint: body || "Check your instance URL and try again.",
88
+ });
89
+ }
90
+ const payload = await res.json();
91
+ process.stdout.write(`${JSON.stringify(payload)}\n`);
92
+ }
93
+
94
+ module.exports = { cmdProjectProfiles };
@@ -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) {
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
 
@@ -82,6 +78,52 @@ const TRANSITION_GUARD_ATTEMPTS = 1000;
82
78
  // trouble must be survivable and queryable, not loud).
83
79
  const LOCK_TRANSIENT_OPEN_RETRIES = 3;
84
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
+ }
85
127
 
86
128
  function parseLockOwner(raw) {
87
129
  try {
@@ -488,6 +530,7 @@ async function updateJsonLocked(
488
530
  module.exports = {
489
531
  ensureDir,
490
532
  writeFileAtomic,
533
+ attachWriteHint,
491
534
  readJson,
492
535
  readJsonStrict,
493
536
  writeJson,