tokenusage-cli 0.2.1 → 0.2.2

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
@@ -3,6 +3,21 @@
3
3
  本包(`tokenusage-cli`)的用户可见变更记录。发版时在顶部新增一节,
4
4
  `## <版本号>` 行会被 release workflow 取作 GitHub Release 正文。
5
5
 
6
+ ## 0.2.2
7
+
8
+ 新机初始化修复与采集口径修正。
9
+
10
+ - 修复严重初始化缺陷:从 npm 安装后 `tokenusage init` 必崩(包内缺少
11
+ `bin/tracker.js`——fork 改名 bin 后安装器没跟着改,0.1.0 起所有已发布版本
12
+ 受影响;单测因跳过运行时拷贝未覆盖)。新增防回归测试直接执行运行时拷贝。
13
+ - init 新增 `--no-integrations`:只做扫描根配置、计划任务注册与运行上报,
14
+ **不改动任何 AI 工具的配置**(不装 hooks/notify/插件)。只要定时采集、
15
+ 不想被触碰各工具配置的机器终于可以安全重跑 init。
16
+ - init 的欢迎屏与完成屏改为显示真实站点地址(原先写死一个本地端口残留)。
17
+ - 计划任务运行的口径修正:init 注册的隐藏任务改跑 `sync --from-scheduled`,
18
+ 运行记录正确标记为"定时"(此前记成"手动"),并写入滚动日志(此前隐藏
19
+ 运行无任何日志痕迹)。已在 0.2.0/0.2.1 注册过任务的机器重跑一次 init 即可升级。
20
+
6
21
  ## 0.2.1
7
22
 
8
23
  修复 0.2.0 的严重回归:运行上报的版本号读取用了错误的相对路径(`Cannot find
package/README.md CHANGED
@@ -30,7 +30,7 @@ tokenusage sync --drain # 首次/积压补传(更大的批处理预算)
30
30
 
31
31
  | 命令 | 说明 |
32
32
  |---|---|
33
- | `tokenusage init` | 本地初始化:扫描根配置、各工具 hook 安装、注册每小时计划任务(Windows 隐藏窗口;`--no-task` 跳过任务;`--run-report=off` 关闭运行记录上报)。不含配对 |
33
+ | `tokenusage init` | 本地初始化:扫描根配置、各工具 hook 安装、注册每小时计划任务(Windows 隐藏窗口;`--no-task` 跳过任务;`--run-report=off` 关闭运行记录上报;`--no-integrations` 不装任何 hook/notify/插件,只做纯定时采集)。不含配对 |
34
34
  | `tokenusage device-login` | 设备流配对:输出 `user_code`,在站点 `/device` 页批准后本机拿到设备令牌 |
35
35
  | `tokenusage sync` | 解析本地 AI 工具日志 → 上报小时桶 + 会话元数据 |
36
36
  | `tokenusage sync --watch` | 常驻模式,默认每 15 分钟增量一轮(`--interval <ms>` 可调,≥60000) |
@@ -69,6 +69,7 @@ tokenusage status # 查看当前采集状态
69
69
  退出(不报错、不上报、不留运行记录);**手动 `tokenusage sync` 永远可用**。
70
70
  - Windows 上 init 会注册每小时计划任务 `TokenUsageSync`(隐藏窗口,无黑框),
71
71
  pause/resume 顺势 disable/enable 它;`uninstall` 一并删除任务与脚本。
72
+ 任务以 `--from-scheduled` 运行:运行记录标记为"定时"并写入滚动日志。
72
73
  - 自动采集的日志落在 `~/.tokenusage/tracker/logs/sync.log`(1 MiB 滚动一代),
73
74
  不依赖终端重定向。
74
75
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Self-hosted AI coding token usage collector for token-usage (forked from TokenTracker, MIT).",
5
5
  "keywords": [
6
6
  "token-usage",
@@ -82,7 +82,7 @@ const {
82
82
  resolveMuseHome,
83
83
  resolveTraeStoragePath,
84
84
  } = require("../lib/rollout");
85
- const { resolveRuntimeConfig, DEFAULT_BASE_URL, normalizeInstanceBaseUrl, assertInsforgeRuntime,
85
+ const { resolveRuntimeConfig, DEFAULT_BASE_URL, DEFAULT_DASHBOARD_URL, normalizeInstanceBaseUrl, assertInsforgeRuntime,
86
86
  clearDeviceIdentity, resetInstanceState } = require("../lib/runtime-config");
87
87
  const { registerWindowsScheduledTask, TASK_NAME } = require("../lib/scheduled-task");
88
88
  const {
@@ -193,7 +193,7 @@ async function cmdInit(argv, options = {}) {
193
193
  const appDir = path.join(trackerDir, "app");
194
194
  const trackerBinPath = path.join(appDir, "bin", "tracker.js");
195
195
 
196
- renderWelcome();
196
+ renderWelcome(runtime.dashboardUrl || DEFAULT_DASHBOARD_URL);
197
197
 
198
198
  if (opts.dryRun) {
199
199
  process.stdout.write(`${color("Dry run: preview only (no changes applied).", DIM)}\n\n`);
@@ -273,11 +273,11 @@ async function cmdInit(argv, options = {}) {
273
273
  ahaSpinner.stop();
274
274
  }
275
275
 
276
- renderLocalSuccess({ firstSync });
276
+ renderLocalSuccess({ firstSync, dashboardUrl: runtime.dashboardUrl || DEFAULT_DASHBOARD_URL });
277
277
  await maybeShowStarCta({ trackerDir });
278
278
  }
279
279
 
280
- function renderWelcome() {
280
+ function renderWelcome(dashboardUrl = DEFAULT_DASHBOARD_URL) {
281
281
  const providerCount = SUPPORTED_PROVIDERS.length;
282
282
  // Show first 5 by name for grounding, then "+N more" so the line stays one row.
283
283
  const previewNames = SUPPORTED_PROVIDERS.slice(0, 5).join(", ");
@@ -296,13 +296,13 @@ function renderWelcome() {
296
296
  DIVIDER,
297
297
  "",
298
298
  ` Tracks: ${providerLine}`,
299
- ` Dashboard: http://localhost:7680`,
299
+ ` Dashboard: ${dashboardUrl}`,
300
300
  "",
301
301
  ].join("\n"),
302
302
  );
303
303
  }
304
304
 
305
- function renderLocalSuccess({ firstSync } = {}) {
305
+ function renderLocalSuccess({ firstSync, dashboardUrl = DEFAULT_DASHBOARD_URL } = {}) {
306
306
  const lines = ["", `${BOLD}Setup complete!${RESET}`, ""];
307
307
 
308
308
  if (firstSync && firstSync.totalTokens > 0) {
@@ -320,7 +320,7 @@ function renderLocalSuccess({ firstSync } = {}) {
320
320
 
321
321
  lines.push(
322
322
  "",
323
- ` Dashboard: ${CYAN}http://localhost:7680${RESET}`,
323
+ ` Dashboard: ${CYAN}${dashboardUrl}${RESET}`,
324
324
  "",
325
325
  );
326
326
  process.stdout.write(lines.join("\n"));
@@ -351,6 +351,17 @@ function shouldUseBrowserAuth({ deviceToken, opts }) {
351
351
  async function buildDryRunSummary({ opts, home, trackerDir, notifyPath, runtime }) {
352
352
  const deviceToken = runtime?.deviceToken || null;
353
353
  const pendingBrowserAuth = shouldUseBrowserAuth({ deviceToken, opts });
354
+ if (opts.noIntegrations) {
355
+ return {
356
+ summary: [{
357
+ label: "Integrations",
358
+ status: "skipped",
359
+ detail: "Skipped (--no-integrations); tool configs stay untouched",
360
+ }],
361
+ pendingBrowserAuth,
362
+ deviceToken,
363
+ };
364
+ }
354
365
  const context = buildIntegrationTargets({ home, trackerDir, notifyPath });
355
366
  const summary = await previewIntegrations({ context });
356
367
  return { summary, pendingBrowserAuth, deviceToken };
@@ -415,13 +426,22 @@ async function runSetup({
415
426
 
416
427
  await writeNotifyHandler({ trackerDir, notifyPath });
417
428
 
418
- const summary = await applyIntegrationSetup({
419
- home,
420
- trackerDir,
421
- notifyPath,
422
- notifyOriginalPath,
423
- dryRun: Boolean(opts.dryRun),
424
- });
429
+ // --no-integrations (0.2.2): machines that only want scheduled scanning can
430
+ // take over the task without the CLI touching any tool's config — hooks,
431
+ // notify entries and the opencode plugin all stay exactly as they are.
432
+ const summary = opts.noIntegrations
433
+ ? [{
434
+ label: "Integrations",
435
+ status: "skipped",
436
+ detail: "Skipped (--no-integrations); tool configs stay untouched",
437
+ }]
438
+ : await applyIntegrationSetup({
439
+ home,
440
+ trackerDir,
441
+ notifyPath,
442
+ notifyOriginalPath,
443
+ dryRun: Boolean(opts.dryRun),
444
+ });
425
445
 
426
446
  // Windows scheduled task takeover (0.2.0): hourly auto sync behind a hidden
427
447
  // VBS runner — no conhost flash, no shell redirect (sync self-logs to the
@@ -1453,6 +1473,7 @@ function parseArgs(argv) {
1453
1473
  dryRun: false,
1454
1474
  runReport: null,
1455
1475
  noTask: false,
1476
+ noIntegrations: false,
1456
1477
  };
1457
1478
 
1458
1479
  for (let i = 0; i < argv.length; i++) {
@@ -1468,6 +1489,7 @@ function parseArgs(argv) {
1468
1489
  else if (a === "--run-report") out.runReport = normalizeRunReportFlag(argv[++i]);
1469
1490
  else if (a.startsWith("--run-report=")) out.runReport = normalizeRunReportFlag(a.slice("--run-report=".length));
1470
1491
  else if (a === "--no-task") out.noTask = true;
1492
+ else if (a === "--no-integrations") out.noIntegrations = true;
1471
1493
  else if (a === "--no-auth") out.noAuth = true;
1472
1494
  else if (a === "--no-open") out.noOpen = true;
1473
1495
  else if (a === "--yes") out.yes = true;
@@ -2329,7 +2351,7 @@ async function installLocalTrackerApp({ appDir }) {
2329
2351
  // Copy the current package's runtime (bin + src) into ~/.tokenusage so notify can run sync without npx.
2330
2352
  const packageRoot = path.resolve(__dirname, "../..");
2331
2353
  const srcFrom = path.join(packageRoot, "src");
2332
- const binFrom = path.join(packageRoot, "bin", "tracker.js");
2354
+ const binFrom = path.join(packageRoot, "bin", "tokenusage.js");
2333
2355
  const packageJsonFrom = path.join(packageRoot, "package.json");
2334
2356
  const nodeModulesFrom = path.join(packageRoot, "node_modules");
2335
2357
  const dashboardDistFrom = path.join(packageRoot, "dashboard", "dist");
@@ -593,7 +593,7 @@ async function cmdSync(argv, context = {}) {
593
593
  // log line, no run record. A manual sync is the user's explicit request
594
594
  // and runs regardless of the flag.
595
595
  const autoishSync = opts.auto || opts.background || opts.fromRetry || opts.fromNotify ||
596
- opts.fromOpenclaw || context.trigger === "watch";
596
+ opts.fromOpenclaw || opts.fromScheduled || context.trigger === "watch";
597
597
  if (autoishSync && isCollectionPaused(trackerDir)) return;
598
598
  // Auto-flavored runs self-log to the rolling file so neither the scheduled
599
599
  // task nor a TTY-less hook run loses its trail.
@@ -3965,6 +3965,7 @@ function parseArgs(argv) {
3965
3965
  else if (a === "--from-notify") out.fromNotify = true;
3966
3966
  else if (a === "--from-retry") out.fromRetry = true;
3967
3967
  else if (a === "--from-openclaw") out.fromOpenclaw = true;
3968
+ else if (a === "--from-scheduled") out.fromScheduled = true;
3968
3969
  else if (a === "--source") {
3969
3970
  out.source = normalizeSyncSource(argv[i + 1]);
3970
3971
  i += 1;
@@ -37,6 +37,9 @@ function vbsPathFor(binDir) {
37
37
  * pitfall (paths with spaces) never applies.
38
38
  */
39
39
  function buildHiddenRunnerVbs({ nodeExe, cliJs }) {
40
+ // --from-scheduled: the run reports trigger=scheduled, self-logs via autoLog
41
+ // and uploads without consulting the cloud-sync preference — the registered
42
+ // task is the default collection path, not an opt-in flavor.
40
43
  return [
41
44
  "' Token Usage — hidden sync runner.",
42
45
  "' The scheduled task launches this script (GUI subsystem: no conhost",
@@ -45,7 +48,7 @@ function buildHiddenRunnerVbs({ nodeExe, cliJs }) {
45
48
  "' own rolling logs/sync.log — no shell redirect involved.",
46
49
  "Dim shell",
47
50
  "Set shell = CreateObject(\"WScript.Shell\")",
48
- `WScript.Quit shell.Run("""${nodeExe}"" ""${cliJs}"" sync", 0, True)`,
51
+ `WScript.Quit shell.Run("""${nodeExe}"" ""${cliJs}"" sync --from-scheduled", 0, True)`,
49
52
  "",
50
53
  ].join("\n");
51
54
  }
@@ -23,10 +23,13 @@ function buildRunId(startedAtMs = Date.now(), randomBytes = 2) {
23
23
  // background flavors (retry, publish, openclaw signal) fold into the four
24
24
  // allowed values: hook/signal spawns are notify, everything scheduled or
25
25
  // retrying is scheduled, the --watch loop is watch, a plain CLI run is manual.
26
+ // --from-scheduled marks the init-registered scheduled task's run: unlike
27
+ // --auto it bypasses the cloud-sync preference gate (the task must upload on
28
+ // default installs), which is why it needs its own flag.
26
29
  function resolveSyncTrigger(opts = {}, context = {}) {
27
30
  if (context?.trigger === "watch") return "watch";
28
31
  if (opts?.fromNotify || opts?.fromOpenclaw) return "notify";
29
- if (opts?.auto || opts?.background || opts?.fromRetry) return "scheduled";
32
+ if (opts?.fromScheduled || opts?.auto || opts?.background || opts?.fromRetry) return "scheduled";
30
33
  return "manual";
31
34
  }
32
35
 
@@ -11,6 +11,7 @@
11
11
 
12
12
  const assert = require("node:assert/strict");
13
13
  const fs = require("node:fs");
14
+ const os = require("node:os");
14
15
  const path = require("node:path");
15
16
  const { test } = require("node:test");
16
17
 
@@ -18,6 +19,9 @@ const {
18
19
  zcodeRowTotals,
19
20
  buildZcodeRestorationRow,
20
21
  } = require("../src/commands/sync");
22
+ const {
23
+ installLocalTrackerApp,
24
+ } = require("../src/commands/init");
21
25
  const {
22
26
  parseBucketKey,
23
27
  bucketKey,
@@ -198,3 +202,30 @@ test("fix 5: TOKENUSAGE_BASE_URL/TOKENUSAGE_ANON_KEY win; INSFORGE_* remain lega
198
202
  });
199
203
  assert.equal(both.baseUrl, "https://new.example");
200
204
  });
205
+
206
+ test("no stale dashboard constants in init output", () => {
207
+ const source = fs.readFileSync(
208
+ path.join(__dirname, "..", "src", "commands", "init.js"),
209
+ "utf8",
210
+ );
211
+ // The welcome/success banners print the configured dashboard URL; the old
212
+ // hardcoded TokenTracker default must not reappear in either renderer.
213
+ assert.ok(!source.includes("localhost:7680"), "stale localhost dashboard must not reappear in init.js");
214
+ });
215
+
216
+ test("init's runtime copy works from the published layout (bin/tokenusage.js)", async () => {
217
+ // 0.1.0–0.2.1 shipped without bin/tracker.js (the fork renamed the bin to
218
+ // tokenusage.js but the installer kept the old name), so `tokenusage init`
219
+ // crashed with ENOENT on every fresh npm install. The unit suite never ran
220
+ // this path: init tests set TOKENUSAGE_SKIP_LOCAL_RUNTIME_COPY=1.
221
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "tu-init-copy-"));
222
+ const appDir = path.join(home, "tracker", "app");
223
+ try {
224
+ await installLocalTrackerApp({ appDir });
225
+ assert.ok(fs.existsSync(path.join(appDir, "bin", "tracker.js")), "app/bin/tracker.js copied");
226
+ assert.ok(fs.existsSync(path.join(appDir, "src", "cli.js")), "app/src copied");
227
+ assert.ok(fs.existsSync(path.join(appDir, "package.json")), "app/package.json copied");
228
+ } finally {
229
+ fs.rmSync(home, { recursive: true, force: true });
230
+ }
231
+ });
@@ -173,13 +173,21 @@ test("hidden-runner VBS quotes paths individually and propagates the exit code",
173
173
  cliJs: "C:\\Users\\me\\AppData\\tokenusage-cli\\src\\cli.js",
174
174
  });
175
175
  assert.match(vbs, /WScript\.Quit shell\.Run/);
176
- assert.match(vbs, /""C:\\Program Files\\nodejs\\node\.exe"" ""C:\\Users\\me\\AppData\\tokenusage-cli\\src\\cli\.js"" sync/);
176
+ assert.match(vbs, /""C:\\Program Files\\nodejs\\node\.exe"" ""C:\\Users\\me\\AppData\\tokenusage-cli\\src\\cli\.js"" sync --from-scheduled/);
177
177
  // Hidden window (0) + wait for completion (True).
178
178
  assert.match(vbs, /, 0, True\)/);
179
179
  // The task name stays stable — pause/resume and uninstall toggle by name.
180
180
  assert.equal(TASK_NAME, "TokenUsageSync");
181
181
  });
182
182
 
183
+ test("--from-scheduled reports as scheduled, unlike a plain manual run", () => {
184
+ assert.equal(resolveSyncTrigger({ fromScheduled: true }), "scheduled");
185
+ // The scheduled task must upload on default installs, so --from-scheduled
186
+ // deliberately does NOT map onto the cloud-sync-gated auto/background flags.
187
+ assert.equal(resolveSyncTrigger({ auto: true }), "scheduled");
188
+ assert.equal(resolveSyncTrigger({}), "manual");
189
+ });
190
+
183
191
  // Runtime-require depth guard: a `require("../package.json")` inside src/commands
184
192
  // or src/lib resolves to a nonexistent src/package.json and only explodes when
185
193
  // the lazy call site runs (0.2.0 shipped exactly this in sync.js's report tail —