tokenusage-cli 0.2.3 → 0.2.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
@@ -3,6 +3,57 @@
3
3
  本包(`tokenusage-cli`)的用户可见变更记录。发版时在顶部新增一节,
4
4
  `## <版本号>` 行会被 release workflow 取作 GitHub Release 正文。
5
5
 
6
+ ## 0.2.5
7
+
8
+ 0.2.4 验收后的小修:去掉安装警告、修正初始化重复文案,并补 Windows CI。
9
+
10
+ - 移除 `@mongodb-js/zstd` 与两处 Node 20 zstd 回落分支:包 `engines` 已是
11
+ `>=22.19`,`node:zlib` 自带 zstd。`npm i -g` 不再出现 `prebuild-install`
12
+ 弃用警告,运行时副本也少一个 native 依赖。
13
+ - 修 `init` 跳过行重复文案:detail 已以 `Skipped` 开头时不再叠加
14
+ `Skipped - ` 前缀(此前显示 `Skipped - Skipped (--no-integrations)`)。
15
+ - 顺手去掉 `--dry-run` 收尾的重复 `Dry run complete` 行,只保留
16
+ `Run init without --dry-run to apply changes.`。
17
+ - README 补齐 `init` 的 `--yes` / `--dry-run` / `--no-open` / `--link-code`
18
+ 参数说明。
19
+ - CI 新增 `windows-latest` job:跑 CLI 测试 + `init --dry-run` 烟测并断言
20
+ 输出不含 `Skipped - Skipped`,避免 VBS / 入口类回归只靠发版前人工验收。
21
+
22
+ ## 0.2.4
23
+
24
+ 计划任务抗 Node 版本切换 + 自检一次性收口的采集可靠性修复(发 0.2.3 后立即补;
25
+ 家里机实测发现)。
26
+
27
+ - 0.2.3 的隐藏 VBS 把 npm 全局前缀里的包路径写死,而 nvm-windows 的全局前缀
28
+ 按 Node 版本分目录(如 `E:\nvm\nvm\v24.4.1\node_modules\tokenusage-cli`)。
29
+ `nvm use` 之后该路径消失,任务每小时以 "file not found" 失败
30
+ (`LastTaskResult` 非 0、日志停更),而任务本身看起来仍"已注册"。
31
+ - VBS 现在先 `FileExists` 探测包路径,缺失时回落到 init 复制到数据目录的自包含
32
+ 运行时 `~/.tokenusage/tracker/app/bin/tracker.js`,采集不中断。
33
+ - VBS 的引号改用 `Chr(34)` 拼接(不再依赖转义写法),行为不变:wscript 直接起
34
+ node、隐藏窗口、用退出码回填 `LastTaskResult`。
35
+ - 运行时副本改为"依赖闭包"复制:旧实现整目录 `fs.cp`,在 pnpm 安装下只复制到
36
+ junction 链接(副本里 `node_modules` 只有 1 项),副本一跑就是
37
+ `Cannot find module`;现在按依赖图逐个复制真实目录,npm / pnpm 两种布局都能
38
+ 得到自包含副本。
39
+ - 副本先复制到 `app.new` 暂存目录,**实际启动一遍**(`require` 全部直接依赖 +
40
+ `--version`)通过后才替换 `app` 并写 `.runtime-ready` 标记。没有标记的副本
41
+ 一律不使用——半成品副本在忽略输出的后台进程里静默死掉,表现与"采集正常"
42
+ 完全一样,这是最难排查的一类失败。
43
+ - notify / OpenClaw hook / OpenClaw session plugin / sync 自动重试脚本统一按
44
+ "带标记的副本 → 已安装包入口 → npx" 三级选择启动器。
45
+ - `tokenusage doctor` 新增 `runtime.copy` 检查:缺标记、版本落后都会给出
46
+ warn 与重跑 `init` 的建议(升级 CLI 后重跑之前先能看见)。
47
+ - `init` 复制失败不再静默:报告里列一行(stderr 同时提示),并说明会自动回退。
48
+ - `uninstall` 一并清理暂存目录 `app.new`。
49
+ - 后台 spawn 全部加 `windowsHide`(notify 之外的 hook / 自动重试 / 本地 API),
50
+ 避免 GUI 宿主(如 oh-my-pi)每轮闪一个控制台窗口。
51
+ - `sync --watch --interval=<毫秒>` 等号写法不再泄漏进 sync 参数(此前会被当成
52
+ 未知参数导致每一轮失败);低于 1 分钟仍按 15 分钟处理。
53
+ - 仍然建议升级或切换 Node 版本后重跑一次
54
+ `tokenusage init --yes --no-integrations --no-open`:回落副本是上次 init 的
55
+ 快照,重跑才会同步到最新版本。
56
+
6
57
  ## 0.2.3
7
58
 
8
59
  修复 0.2.x 计划任务的两个隐藏缺陷(0.2.2 升级验收时实测发现)。
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` 关闭运行记录上报;`--no-integrations` 不装任何 hook/notify/插件,只做纯定时采集)。不含配对 |
33
+ | `tokenusage init` | 本地初始化:扫描根配置、各工具 hook 安装、注册每小时计划任务(Windows 隐藏窗口)。`--no-task` 跳过任务;`--run-report=off` 关闭运行记录上报;`--no-integrations` 不装任何 hook/notify/插件,只做纯定时采集;`--yes` 非交互;`--dry-run` 只预览不落盘;`--no-open` 不打开浏览器;`--link-code <code>` 用已有配对码。不含配对 |
34
34
  | `tokenusage device-login` | 设备流配对:输出 `user_code`,在站点 `/device` 页批准后本机拿到设备令牌 |
35
35
  | `tokenusage sync` | 解析本地 AI 工具日志 → 上报小时桶 + 会话元数据 |
36
36
  | `tokenusage sync --watch` | 常驻模式,默认每 15 分钟增量一轮(`--interval <ms>` 可调,≥60000) |
@@ -107,7 +107,21 @@ CLI 也不发送匿名安装心跳:上游的 `tokenusage-telemetry` 端点在
107
107
 
108
108
  ## 数据目录
109
109
 
110
- `~/.tokenusage/`(`0700` 目录 + `0600` 文件):`tracker/config.json`(配对与运行配置)、上传队列(`queue.jsonl` + offset)、会话分析 sidecar、`session-upload-watermarks.json`(增量水位)、`tracker/logs/sync.log`(自动采集滚动日志)、暂停标志。与旧版 tokentracker CLI 的 `~/.tokentracker/` 互不干扰,迁移期两套 CLI 可在同一台机器共存。
110
+ `~/.tokenusage/`(`0700` 目录 + `0600` 文件):`tracker/config.json`(配对与运行配置)、`tracker/app/`(自包含运行时副本,`.runtime-ready` 记录版本)、上传队列(`queue.jsonl` + offset)、会话分析 sidecar、`session-upload-watermarks.json`(增量水位)、`tracker/logs/sync.log`(自动采集滚动日志)、暂停标志。与旧版 tokentracker CLI 的 `~/.tokentracker/` 互不干扰,迁移期两套 CLI 可在同一台机器共存。
111
+
112
+ ## 自包含运行时副本(0.2.4+)
113
+
114
+ init 会把当前 CLI 及其依赖闭包复制到 `~/.tokenusage/tracker/app`,并写入
115
+ `.runtime-ready`(版本 + 安装时间)。计划任务 / notify / hook 优先启动已安装包;
116
+ 包路径失效时(典型是 nvm-windows 切换 Node 版本后全局前缀变化)自动回落到副本,
117
+ 小时任务不再 `file not found`。副本先复制到 `app.new` 暂存,`require` 全部直接
118
+ 依赖且 `--version` 实跑通过后才替换并写标记;没有标记的副本不会被任何自动采集
119
+ 入口使用。
120
+
121
+ 升级 CLI 或切换 Node 版本后重跑一次
122
+ `tokenusage init --yes --no-integrations --no-open` 刷新副本;`tokenusage doctor`
123
+ 的 `runtime.copy` 检查会报告副本缺失、缺标记或版本落后,`uninstall --purge`
124
+ 连同数据目录一并清理。
111
125
 
112
126
  ## provider 支持面
113
127
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Self-hosted AI coding token usage collector for the Token Usage dashboard.",
5
5
  "keywords": [
6
6
  "token-usage",
@@ -43,7 +43,6 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@journeyapps/wa-sqlite": "2.0.7",
46
- "@mongodb-js/zstd": "^2.0.1",
47
46
  "@sentry/node": "^11.8.0",
48
47
  "smol-toml": "^1.9.0",
49
48
  "undici": "8.12.2",
@@ -51,7 +50,6 @@
51
50
  },
52
51
  "pnpm": {
53
52
  "onlyBuiltDependencies": [
54
- "@mongodb-js/zstd",
55
53
  "@journeyapps/wa-sqlite",
56
54
  "esbuild"
57
55
  ]
package/src/cli.js CHANGED
@@ -79,19 +79,25 @@ async function run(argv) {
79
79
  }
80
80
  }
81
81
 
82
- // Split `--interval <ms>` off the sync args. Values below the 1-minute floor
83
- // (or a missing value) fall back to 15 min, but the flag must ALWAYS be
84
- // removed: leaving it behind made cmdSync reject every pass with
85
- // "Unknown option: --interval" instead of the documented fallback.
82
+ // Split `--interval <ms>` (or `--interval=<ms>`) off the sync args. Values
83
+ // below the 1-minute floor (or a missing value) fall back to 15 min, but the
84
+ // flag must ALWAYS be removed: leaving it behind made cmdSync reject every
85
+ // pass with "Unknown option: --interval" instead of the documented fallback.
86
86
  function resolveWatchInterval(rest) {
87
87
  const args = rest.filter((arg) => arg !== "--watch");
88
- const intervalIndex = args.indexOf("--interval");
89
88
  let intervalMs = 15 * 60_000;
90
- if (intervalIndex >= 0) {
91
- const value = Number(args[intervalIndex + 1]);
92
- if (Number.isFinite(value) && value >= 60_000) intervalMs = value;
93
- args.splice(intervalIndex, 2);
89
+ let value;
90
+ const spacedIndex = args.indexOf("--interval");
91
+ const equalsIndex = args.findIndex((arg) => arg.startsWith("--interval="));
92
+ if (spacedIndex >= 0) {
93
+ value = args[spacedIndex + 1];
94
+ args.splice(spacedIndex, 2);
95
+ } else if (equalsIndex >= 0) {
96
+ value = args[equalsIndex].slice("--interval=".length);
97
+ args.splice(equalsIndex, 1);
94
98
  }
99
+ const parsed = Number(value);
100
+ if (Number.isFinite(parsed) && parsed >= 60_000) intervalMs = parsed;
95
101
  return { args, intervalMs };
96
102
  }
97
103
 
@@ -84,7 +84,8 @@ const {
84
84
  } = require("../lib/rollout");
85
85
  const { resolveRuntimeConfig, DEFAULT_BASE_URL, DEFAULT_DASHBOARD_URL, normalizeInstanceBaseUrl, assertInsforgeRuntime,
86
86
  clearDeviceIdentity, resetInstanceState } = require("../lib/runtime-config");
87
- const { registerWindowsScheduledTask, TASK_NAME } = require("../lib/scheduled-task");
87
+ const { registerWindowsScheduledTask, TASK_NAME, cliEntryPath } = require("../lib/scheduled-task");
88
+ const { runtimeReadyMarkerPath } = require("../lib/runtime-entry");
88
89
  const {
89
90
  BOLD,
90
91
  DIM,
@@ -331,7 +332,7 @@ function renderAccountNotLinked({ context } = {}) {
331
332
  process.stdout.write(
332
333
  [
333
334
  "",
334
- "Dry run complete. Run init without --dry-run to apply changes.",
335
+ "Run init without --dry-run to apply changes.",
335
336
  "",
336
337
  ].join("\n"),
337
338
  );
@@ -388,7 +389,7 @@ async function runSetup({
388
389
  const installedAt = existingConfig?.installedAt || new Date().toISOString();
389
390
  let pendingBrowserAuth = false;
390
391
 
391
- await installLocalTrackerApp({ appDir });
392
+ const runtimeCopy = await installLocalTrackerApp({ appDir });
392
393
 
393
394
  const existingPlainConfig =
394
395
  existingConfig && typeof existingConfig === "object" && !Array.isArray(existingConfig)
@@ -443,6 +444,17 @@ async function runSetup({
443
444
  dryRun: Boolean(opts.dryRun),
444
445
  });
445
446
 
447
+ if (runtimeCopy.ok === false) {
448
+ // Never silent: a missing runtime copy degrades collection to the installed
449
+ // package/npx, so it must show up in the report (and on stderr, since the
450
+ // report line is dimmed as "skipped").
451
+ const detail = describeRuntimeCopyFailure(runtimeCopy);
452
+ process.stderr.write(
453
+ `Runtime copy skipped (${detail}); notify and the scheduled task will use the installed CLI.\n`,
454
+ );
455
+ summary.push({ label: "Runtime copy", status: "skipped", detail });
456
+ }
457
+
446
458
  // Windows scheduled task takeover (0.2.0): hourly auto sync behind a hidden
447
459
  // VBS runner — no conhost flash, no shell redirect (sync self-logs to the
448
460
  // rolling logs/sync.log). Best-effort; pause/resume toggle this task.
@@ -453,9 +465,16 @@ async function runSetup({
453
465
  detail: "Skipped (--no-task); auto syncs stay manual",
454
466
  });
455
467
  } else {
456
- // The VBS always targets the package's bin entry (scheduled-task.js owns
457
- // that path): pointing it at src/cli.js makes the hidden task a no-op.
458
- const taskOutcome = registerWindowsScheduledTask({ binDir });
468
+ // The VBS targets the package's bin entry (scheduled-task.js owns that
469
+ // path): pointing it at src/cli.js makes the hidden task a no-op. The
470
+ // runtime copy refresh below is also the task's fallback, so an nvm switch
471
+ // (which drops the version-specific npm prefix) does not kill collection —
472
+ // but only a copy with its readiness marker counts as usable.
473
+ const fallbackCliJs =
474
+ runtimeCopy.ok === true && fssync.existsSync(runtimeReadyMarkerPath(appDir))
475
+ ? trackerBinPath
476
+ : undefined;
477
+ const taskOutcome = registerWindowsScheduledTask({ binDir, fallbackCliJs });
459
478
  summary.push({
460
479
  label: "Scheduled task",
461
480
  status: taskOutcome.registered ? "installed" : "skipped",
@@ -1520,13 +1539,14 @@ function normalizePlatform(value) {
1520
1539
  return "unknown";
1521
1540
  }
1522
1541
 
1523
- function buildNotifyHandler({ trackerDir, packageName }) {
1542
+ function buildNotifyHandler({ trackerDir, packageName, packageEntry = cliEntryPath() }) {
1524
1543
  // Keep this file dependency-free: Node built-ins only.
1525
1544
  // It must never block Codex; it spawns sync in the background and exits 0.
1526
1545
  const queueSignalPath = path.join(trackerDir, "notify.signal");
1527
1546
  const originalPath = path.join(trackerDir, "codex_notify_original.json");
1528
1547
  const fallbackPkg = packageName || "tokenusage-cli";
1529
1548
  const trackerBinPath = path.join(trackerDir, "app", "bin", "tracker.js");
1549
+ const runtimeReadyPath = runtimeReadyMarkerPath(path.join(trackerDir, "app"));
1530
1550
 
1531
1551
  return `#!/usr/bin/env node
1532
1552
  'use strict';
@@ -1559,7 +1579,8 @@ const codexOriginalPath = ${JSON.stringify(originalPath)};
1559
1579
  const acodeOriginalPath = ${JSON.stringify(path.join(trackerDir, "acode_notify_original.json"))};
1560
1580
  const codeOriginalPath = ${JSON.stringify(path.join(trackerDir, "code_notify_original.json"))};
1561
1581
  const trackerBinPath = ${JSON.stringify(trackerBinPath)};
1562
- const depsMarkerPath = path.join(trackerDir, 'app', 'bin', 'tracker.js');
1582
+ const runtimeReadyPath = ${JSON.stringify(runtimeReadyPath)};
1583
+ const packageEntryPath = ${JSON.stringify(packageEntry || null)};
1563
1584
  const fallbackPkg = ${JSON.stringify(fallbackPkg)};
1564
1585
  const selfPath = path.resolve(__filename);
1565
1586
  const home = os.homedir();
@@ -1602,14 +1623,20 @@ try {
1602
1623
  try { last = Number(fs.readFileSync(throttlePath, 'utf8')) || 0; } catch (_) {}
1603
1624
  if (now - last > 20_000) {
1604
1625
  try { fs.writeFileSync(throttlePath, String(now), 'utf8'); } catch (_) {}
1605
- const hasLocalRuntime = fs.existsSync(trackerBinPath);
1606
- const hasLocalDeps = fs.existsSync(depsMarkerPath);
1626
+ // Pick the first usable launcher: the init-copied runtime (self-contained,
1627
+ // survives an nvm switch — but only with its readiness marker), then the
1628
+ // installed package entry, then npx as the last resort. A half-copied
1629
+ // runtime must never be spawned: it dies with MODULE_NOT_FOUND in an
1630
+ // ignored stdio stream, which looks exactly like a successful sync.
1631
+ const hasLocalRuntime = fs.existsSync(runtimeReadyPath) && fs.existsSync(trackerBinPath);
1632
+ const hasPackageEntry = Boolean(packageEntryPath) && fs.existsSync(packageEntryPath);
1607
1633
  const syncArgs = ['sync', '--auto', '--from-notify', '--source', source];
1608
- if (hasLocalRuntime && hasLocalDeps) {
1609
- spawnDetached([process.execPath, trackerBinPath, ...syncArgs]);
1610
- } else {
1611
- spawnDetached(['npx', '--yes', fallbackPkg, ...syncArgs]);
1612
- }
1634
+ const cmd = hasLocalRuntime
1635
+ ? [process.execPath, trackerBinPath, ...syncArgs]
1636
+ : hasPackageEntry
1637
+ ? [process.execPath, packageEntryPath, ...syncArgs]
1638
+ : ['npx', '--yes', fallbackPkg, ...syncArgs];
1639
+ spawnDetached(cmd);
1613
1640
  }
1614
1641
  } catch (_) {}
1615
1642
 
@@ -2341,43 +2368,158 @@ async function isDir(p) {
2341
2368
  }
2342
2369
  }
2343
2370
 
2371
+ // The only modules the runtime copy must carry — the CLI's declared deps.
2372
+ const PACKAGE_DEPENDENCIES = Object.keys(
2373
+ require(path.resolve(__dirname, "../../package.json")).dependencies || {},
2374
+ );
2375
+
2344
2376
  async function installLocalTrackerApp({ appDir }) {
2345
2377
  // Test-only escape hatch: skip the ~10 MB runtime copy (src + dashboard/dist +
2346
2378
  // node_modules) when a test only exercises hook/config/notify wiring. Copying
2347
2379
  // the bundle per test case dominates the init test suite's wall time. Tests
2348
2380
  // that assert on the copied runtime simply leave this unset.
2349
- if (process.env.TOKENUSAGE_SKIP_LOCAL_RUNTIME_COPY === "1") return;
2350
- // Copy the current package's runtime (bin + src) into ~/.tokenusage so notify can run sync without npx.
2381
+ if (process.env.TOKENUSAGE_SKIP_LOCAL_RUNTIME_COPY === "1") return { ok: true, skipped: true };
2382
+ // Copy the current package's runtime (bin + src + deps) into ~/.tokenusage so
2383
+ // notify can run sync without npx and without npm's global prefix.
2351
2384
  const packageRoot = path.resolve(__dirname, "../..");
2385
+
2386
+ // When running from the installed local runtime (or when appDir is symlinked
2387
+ // to this package), source and destination resolve to the same place. Do not
2388
+ // delete appDir in that case.
2389
+ if (await pathsPointToSameLocation(packageRoot, appDir)) {
2390
+ return { ok: true, reused: true };
2391
+ }
2392
+
2393
+ // Build into a staging dir first: a failed copy must never destroy a working
2394
+ // runtime (or leave a half one behind that hooks would spawn and die in).
2395
+ const stagingDir = `${appDir}.new`;
2396
+ await fs.rm(stagingDir, { recursive: true, force: true, maxRetries: 3 }).catch(() => {});
2397
+ const built = await buildRuntimeCopy({ packageRoot, appDir: stagingDir });
2398
+ if (!built.ok) {
2399
+ await fs.rm(stagingDir, { recursive: true, force: true, maxRetries: 3 }).catch(() => {});
2400
+ return built;
2401
+ }
2402
+
2403
+ await fs.rm(appDir, { recursive: true, force: true, maxRetries: 3 }).catch(() => {});
2404
+ try {
2405
+ await fs.rename(stagingDir, appDir);
2406
+ } catch (_err) {
2407
+ await fs.rm(stagingDir, { recursive: true, force: true, maxRetries: 3 }).catch(() => {});
2408
+ return { ok: false, missing: [], reason: "swap-failed" };
2409
+ }
2410
+
2411
+ // The marker is the contract every spawn point checks: only a copy that
2412
+ // booted gets one.
2413
+ const version = require(path.resolve(__dirname, "../../package.json")).version;
2414
+ await fs
2415
+ .writeFile(
2416
+ runtimeReadyMarkerPath(appDir),
2417
+ JSON.stringify({ version, installedAt: new Date().toISOString() }, null, 2),
2418
+ "utf8",
2419
+ )
2420
+ .catch(() => {});
2421
+ return { ok: true };
2422
+ }
2423
+
2424
+ // Assemble bin + src + the dependency closure in `appDir` and prove it boots.
2425
+ // Returns {ok:true} / {ok:false, missing, reason}.
2426
+ async function buildRuntimeCopy({ packageRoot, appDir }) {
2352
2427
  const srcFrom = path.join(packageRoot, "src");
2353
2428
  const binFrom = path.join(packageRoot, "bin", "tokenusage.js");
2354
2429
  const packageJsonFrom = path.join(packageRoot, "package.json");
2355
2430
  const nodeModulesFrom = path.join(packageRoot, "node_modules");
2356
2431
  const dashboardDistFrom = path.join(packageRoot, "dashboard", "dist");
2357
2432
 
2358
- // When running from the installed local runtime (or when appDir is symlinked to this package),
2359
- // source and destination resolve to the same place. Do not delete appDir in that case.
2360
- if (await pathsPointToSameLocation(packageRoot, appDir)) {
2361
- return;
2433
+ try {
2434
+ await ensureDir(appDir);
2435
+ await fs.cp(srcFrom, path.join(appDir, "src"), { recursive: true });
2436
+ await ensureDir(path.join(appDir, "bin"));
2437
+ const binTo = path.join(appDir, "bin", "tracker.js");
2438
+ await fs.copyFile(binFrom, binTo);
2439
+ await fs.chmod(binTo, 0o755).catch(() => {});
2440
+ await fs.copyFile(packageJsonFrom, path.join(appDir, "package.json")).catch(() => {});
2441
+ if (await isDir(dashboardDistFrom)) {
2442
+ await fs.cp(dashboardDistFrom, path.join(appDir, "dashboard", "dist"), { recursive: true });
2443
+ }
2444
+ } catch (err) {
2445
+ return { ok: false, missing: [], reason: `copy-failed: ${err?.message || err}` };
2362
2446
  }
2363
2447
 
2364
- const srcTo = path.join(appDir, "src");
2365
- const binToDir = path.join(appDir, "bin");
2366
- const binTo = path.join(binToDir, "tracker.js");
2367
- const nodeModulesTo = path.join(appDir, "node_modules");
2368
- const dashboardDistTo = path.join(appDir, "dashboard", "dist");
2448
+ const deps = await copyRuntimeDependencies({
2449
+ from: nodeModulesFrom,
2450
+ to: path.join(appDir, "node_modules"),
2451
+ });
2452
+ if (!deps.ok) return { ok: false, missing: deps.missing, reason: "missing-dependencies" };
2453
+
2454
+ const boot = await probeRuntimeCopy(appDir);
2455
+ if (!boot.ok) return { ok: false, missing: boot.missing, reason: boot.reason };
2456
+ return { ok: true };
2457
+ }
2369
2458
 
2370
- await fs.rm(appDir, { recursive: true, force: true }).catch(() => {});
2371
- await ensureDir(appDir);
2372
- await fs.cp(srcFrom, srcTo, { recursive: true });
2373
- await ensureDir(binToDir);
2374
- await fs.copyFile(binFrom, binTo);
2375
- await fs.chmod(binTo, 0o755).catch(() => {});
2376
- await fs.copyFile(packageJsonFrom, path.join(appDir, "package.json")).catch(() => {});
2377
- if (await isDir(dashboardDistFrom)) {
2378
- await fs.cp(dashboardDistFrom, dashboardDistTo, { recursive: true });
2459
+ // Boot the staged copy with the current Node: `require` every declared
2460
+ // dependency (which loads their transitive graph too) and print the version
2461
+ // through the real CLI entry. Only a copy that survives both gets a marker.
2462
+ function probeRuntimeCopy(appDir) {
2463
+ const trackerBinPath = path.join(appDir, "bin", "tracker.js");
2464
+ const script = [
2465
+ "const names = " + JSON.stringify(PACKAGE_DEPENDENCIES) + ";",
2466
+ "const missing = [];",
2467
+ "for (const name of names) {",
2468
+ " try { require(name); } catch (err) {",
2469
+ " if (err && (err.code === 'MODULE_NOT_FOUND' || err.code === 'ERR_MODULE_NOT_FOUND')) {",
2470
+ " missing.push(name);",
2471
+ " }",
2472
+ " }",
2473
+ "}",
2474
+ "if (missing.length > 0) { console.error(missing.join(',')); process.exit(3); }",
2475
+ ].join("\n");
2476
+ const env = { ...process.env };
2477
+ // The probe must not trigger telemetry or hook spawning.
2478
+ env.TOKENUSAGE_NO_TELEMETRY = "1";
2479
+ try {
2480
+ const probe = cp.spawnSync(process.execPath, ["-e", script], {
2481
+ cwd: appDir,
2482
+ env,
2483
+ encoding: "utf8",
2484
+ windowsHide: true,
2485
+ timeout: 60_000,
2486
+ stdio: ["ignore", "pipe", "pipe"],
2487
+ });
2488
+ if (probe.status !== 0) {
2489
+ const reported = String(probe.stderr || "").trim();
2490
+ const missing = reported
2491
+ .split(",")
2492
+ .map((name) => name.trim())
2493
+ .filter(Boolean);
2494
+ return { ok: false, missing, reason: "dependency-probe-failed" };
2495
+ }
2496
+ const boot = cp.spawnSync(process.execPath, [trackerBinPath, "--version"], {
2497
+ cwd: appDir,
2498
+ env,
2499
+ encoding: "utf8",
2500
+ windowsHide: true,
2501
+ timeout: 60_000,
2502
+ stdio: ["ignore", "pipe", "pipe"],
2503
+ });
2504
+ if (boot.status !== 0) {
2505
+ return {
2506
+ ok: false,
2507
+ missing: [],
2508
+ reason: `boot-failed: ${String(boot.stderr || "").trim().split("\n")[0] || `exit ${boot.status}`}`,
2509
+ };
2510
+ }
2511
+ return { ok: true };
2512
+ } catch (err) {
2513
+ return { ok: false, missing: [], reason: `probe-error: ${err?.message || err}` };
2379
2514
  }
2380
- await copyRuntimeDependencies({ from: nodeModulesFrom, to: nodeModulesTo });
2515
+ }
2516
+
2517
+ function describeRuntimeCopyFailure(result) {
2518
+ const missing = Array.isArray(result?.missing) ? result.missing.filter(Boolean) : [];
2519
+ const reason = result?.reason ? String(result.reason) : "incomplete copy";
2520
+ if (missing.length === 0) return reason;
2521
+ const preview = missing.slice(0, 3).join(", ");
2522
+ return `${reason}: ${preview}${missing.length > 3 ? " …" : ""}`;
2381
2523
  }
2382
2524
 
2383
2525
  async function pathsPointToSameLocation(a, b) {
@@ -2410,7 +2552,12 @@ async function runFirstSyncAndRead({ trackerBinPath, trackerDir, packageName })
2410
2552
  }
2411
2553
  const fallbackPkg = packageName || "tokenusage-cli";
2412
2554
  const argv = ["sync", "--auto", "--drain"];
2413
- const hasLocalRuntime = typeof trackerBinPath === "string" && fssync.existsSync(trackerBinPath);
2555
+ // Same readiness contract as notify: a runtime copy without its marker is a
2556
+ // half copy — spawn the installed package instead of dying silently.
2557
+ const hasLocalRuntime =
2558
+ typeof trackerBinPath === "string" &&
2559
+ fssync.existsSync(trackerBinPath) &&
2560
+ fssync.existsSync(runtimeReadyMarkerPath(path.join(trackerDir, "app")));
2414
2561
  const cmd = hasLocalRuntime
2415
2562
  ? [process.execPath, trackerBinPath, ...argv]
2416
2563
  : ["npx", "--yes", fallbackPkg, ...argv];
@@ -2430,6 +2577,7 @@ async function runFirstSyncAndRead({ trackerBinPath, trackerDir, packageName })
2430
2577
  // detached so we can let it keep running past our timeout — the user
2431
2578
  // still gets data later via dashboard auto-refresh.
2432
2579
  detached: true,
2580
+ windowsHide: true,
2433
2581
  stdio: "ignore",
2434
2582
  env: process.env,
2435
2583
  });
@@ -2485,19 +2633,117 @@ function readFirstSyncTotals(trackerDir) {
2485
2633
  return { totalTokens, sources: Array.from(sources) };
2486
2634
  }
2487
2635
 
2636
+ // Copy the CLI's dependency closure into `to` as a flat node_modules tree.
2637
+ //
2638
+ // npm installs the CLI's deps flat (real directories), so copying them is
2639
+ // enough. pnpm links them as junctions into a shared store: copying the links
2640
+ // yields a runtime that breaks as soon as that store entry moves (nvm switch),
2641
+ // and NOT following them yields a runtime with no deps at all. So walk the
2642
+ // declared dependency graph and copy each package's *real* directory instead —
2643
+ // that flattens both layouts into something self-contained.
2488
2644
  async function copyRuntimeDependencies({ from, to }) {
2645
+ if (!(await isDir(from))) return { ok: false, missing: PACKAGE_DEPENDENCIES };
2646
+
2647
+ const { packages } = collectRuntimePackages(from);
2489
2648
  try {
2490
- const st = await fs.stat(from);
2491
- if (!st.isDirectory()) return;
2649
+ await ensureDir(to);
2650
+ for (const [name, dir] of packages) {
2651
+ await fs.cp(dir, path.join(to, name), {
2652
+ recursive: true,
2653
+ dereference: true,
2654
+ filter: skipNestedNodeModules(dir),
2655
+ });
2656
+ }
2492
2657
  } catch (_e) {
2493
- return;
2658
+ return { ok: false, missing: await missingRuntimeDependencies(to) };
2659
+ }
2660
+ const missing = await missingRuntimeDependencies(to);
2661
+ return { ok: missing.length === 0, missing };
2662
+ }
2663
+
2664
+ // Breadth-first walk of the declared dependency graph. Follows the same lookup
2665
+ // Node does for each package — its own node_modules, then the node_modules next
2666
+ // to it (pnpm: `.pnpm/<id>/node_modules`, npm: the flat root) — so nothing from
2667
+ // the hoisted store leaks in. Optional deps are followed when present but their
2668
+ // absence is not an error.
2669
+ function collectRuntimePackages(nodeModulesRoot) {
2670
+ const packages = new Map();
2671
+ const unresolved = [];
2672
+ const queue = PACKAGE_DEPENDENCIES.map((name) => ({ name, from: null, optional: false }));
2673
+ while (queue.length > 0) {
2674
+ const item = queue.shift();
2675
+ if (packages.has(item.name)) continue;
2676
+ const dir =
2677
+ item.from === null
2678
+ ? realDirSync(path.join(nodeModulesRoot, item.name))
2679
+ : resolveDependencyPackage(item.from, item.name);
2680
+ const manifest = dir ? readPackageJsonSync(dir) : null;
2681
+ if (!dir || !manifest) {
2682
+ if (!item.optional) unresolved.push(item.name);
2683
+ continue;
2684
+ }
2685
+ packages.set(item.name, dir);
2686
+ const required = Object.keys(manifest.dependencies || {});
2687
+ for (const dep of required) queue.push({ name: dep, from: dir, optional: false });
2688
+ for (const dep of Object.keys(manifest.optionalDependencies || {})) {
2689
+ queue.push({ name: dep, from: dir, optional: true });
2690
+ }
2691
+ }
2692
+ return { packages, unresolved };
2693
+ }
2694
+
2695
+ function resolveDependencyPackage(packageDir, name) {
2696
+ const parentNodeModules = name.startsWith("@")
2697
+ ? path.dirname(path.dirname(packageDir))
2698
+ : path.dirname(packageDir);
2699
+ return (
2700
+ realDirSync(path.join(packageDir, "node_modules", name)) ||
2701
+ realDirSync(path.join(parentNodeModules, name))
2702
+ );
2703
+ }
2704
+
2705
+ // Packages that ship their own node_modules keep it linked to pnpm's shared
2706
+ // store; dereferencing those links would drag the entire workspace dependency
2707
+ // graph into the runtime copy.
2708
+ function skipNestedNodeModules(from) {
2709
+ return (src) => {
2710
+ const rel = path.relative(from, src);
2711
+ return !rel || !rel.split(path.sep).includes("node_modules");
2712
+ };
2713
+ }
2714
+
2715
+ function realDirSync(p) {
2716
+ if (!isDirSync(p)) return null;
2717
+ try {
2718
+ const real = fssync.realpathSync(p);
2719
+ return isDirSync(real) ? real : null;
2720
+ } catch (_e) {
2721
+ return null;
2722
+ }
2723
+ }
2724
+
2725
+ function isDirSync(p) {
2726
+ try {
2727
+ return fssync.statSync(p).isDirectory();
2728
+ } catch (_e) {
2729
+ return false;
2494
2730
  }
2731
+ }
2495
2732
 
2733
+ function readPackageJsonSync(dir) {
2496
2734
  try {
2497
- await fs.cp(from, to, { recursive: true });
2735
+ return JSON.parse(fssync.readFileSync(path.join(dir, "package.json"), "utf8"));
2498
2736
  } catch (_e) {
2499
- // Best-effort: missing dependencies will fall back to npx at notify time.
2737
+ return null;
2738
+ }
2739
+ }
2740
+
2741
+ async function missingRuntimeDependencies(nodeModulesDir) {
2742
+ const missing = [];
2743
+ for (const name of PACKAGE_DEPENDENCIES) {
2744
+ if (!(await isDir(path.join(nodeModulesDir, name)))) missing.push(name);
2500
2745
  }
2746
+ return missing;
2501
2747
  }
2502
2748
 
2503
2749
  function isDebugEnabled() {