tokenusage-cli 0.2.3 → 0.2.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
@@ -3,6 +3,41 @@
3
3
  本包(`tokenusage-cli`)的用户可见变更记录。发版时在顶部新增一节,
4
4
  `## <版本号>` 行会被 release workflow 取作 GitHub Release 正文。
5
5
 
6
+ ## 0.2.4
7
+
8
+ 计划任务抗 Node 版本切换 + 自检一次性收口的采集可靠性修复(发 0.2.3 后立即补;
9
+ 家里机实测发现)。
10
+
11
+ - 0.2.3 的隐藏 VBS 把 npm 全局前缀里的包路径写死,而 nvm-windows 的全局前缀
12
+ 按 Node 版本分目录(如 `E:\nvm\nvm\v24.4.1\node_modules\tokenusage-cli`)。
13
+ `nvm use` 之后该路径消失,任务每小时以 "file not found" 失败
14
+ (`LastTaskResult` 非 0、日志停更),而任务本身看起来仍"已注册"。
15
+ - VBS 现在先 `FileExists` 探测包路径,缺失时回落到 init 复制到数据目录的自包含
16
+ 运行时 `~/.tokenusage/tracker/app/bin/tracker.js`,采集不中断。
17
+ - VBS 的引号改用 `Chr(34)` 拼接(不再依赖转义写法),行为不变:wscript 直接起
18
+ node、隐藏窗口、用退出码回填 `LastTaskResult`。
19
+ - 运行时副本改为"依赖闭包"复制:旧实现整目录 `fs.cp`,在 pnpm 安装下只复制到
20
+ junction 链接(副本里 `node_modules` 只有 1 项),副本一跑就是
21
+ `Cannot find module`;现在按依赖图逐个复制真实目录,npm / pnpm 两种布局都能
22
+ 得到自包含副本。
23
+ - 副本先复制到 `app.new` 暂存目录,**实际启动一遍**(`require` 全部直接依赖 +
24
+ `--version`)通过后才替换 `app` 并写 `.runtime-ready` 标记。没有标记的副本
25
+ 一律不使用——半成品副本在忽略输出的后台进程里静默死掉,表现与"采集正常"
26
+ 完全一样,这是最难排查的一类失败。
27
+ - notify / OpenClaw hook / OpenClaw session plugin / sync 自动重试脚本统一按
28
+ "带标记的副本 → 已安装包入口 → npx" 三级选择启动器。
29
+ - `tokenusage doctor` 新增 `runtime.copy` 检查:缺标记、版本落后都会给出
30
+ warn 与重跑 `init` 的建议(升级 CLI 后重跑之前先能看见)。
31
+ - `init` 复制失败不再静默:报告里列一行(stderr 同时提示),并说明会自动回退。
32
+ - `uninstall` 一并清理暂存目录 `app.new`。
33
+ - 后台 spawn 全部加 `windowsHide`(notify 之外的 hook / 自动重试 / 本地 API),
34
+ 避免 GUI 宿主(如 oh-my-pi)每轮闪一个控制台窗口。
35
+ - `sync --watch --interval=<毫秒>` 等号写法不再泄漏进 sync 参数(此前会被当成
36
+ 未知参数导致每一轮失败);低于 1 分钟仍按 15 分钟处理。
37
+ - 仍然建议升级或切换 Node 版本后重跑一次
38
+ `tokenusage init --yes --no-integrations --no-open`:回落副本是上次 init 的
39
+ 快照,重跑才会同步到最新版本。
40
+
6
41
  ## 0.2.3
7
42
 
8
43
  修复 0.2.x 计划任务的两个隐藏缺陷(0.2.2 升级验收时实测发现)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
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
@@ -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,
@@ -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() {
@@ -8,6 +8,8 @@ const { functionUrlFor, fetchFunctionResponse } = require("../lib/function-url")
8
8
  const { cloudUsageResetBlocksUpload, finishCloudDeviceUsageReset } = require("../lib/cloud-usage-reset");
9
9
  const { KIMI_MODEL_REPAIR_KEY, repairKimiModelAttribution } = require("../lib/kimi-model-repair");
10
10
  const { readSqliteJsonRows } = require("../lib/sqlite-reader");
11
+ const { runtimeReadyMarkerPath, runtimeBinPath } = require("../lib/runtime-entry");
12
+ const { cliEntryPath } = require("../lib/scheduled-task");
11
13
 
12
14
  const { resolveInstallPaths, resolveZcodeNativeDbPath, resolveMimoNativeDbPath, ensureFlatCursor } = require("../lib/install-resolver");
13
15
  const { multiInstallParse, mergeBothFileSources } = require("../lib/multi-install-parser");
@@ -4458,7 +4460,9 @@ async function scheduleAutoRetry({
4458
4460
 
4459
4461
  spawnAutoRetryProcess({
4460
4462
  retryPath,
4461
- trackerBinPath: path.join(trackerDir, "app", "bin", "tracker.js"),
4463
+ trackerBinPath: runtimeBinPath(trackerDir),
4464
+ runtimeReadyPath: runtimeReadyMarkerPath(path.join(trackerDir, "app")),
4465
+ packageEntryPath: cliEntryPath(),
4462
4466
  fallbackPkg: "tokenusage-cli",
4463
4467
  delayMs,
4464
4468
  });
@@ -4484,8 +4488,22 @@ async function clearAutoRetry(trackerDir) {
4484
4488
  await fs.unlink(retryPath).catch(() => {});
4485
4489
  }
4486
4490
 
4487
- function spawnAutoRetryProcess({ retryPath, trackerBinPath, fallbackPkg, delayMs }) {
4488
- const script = buildAutoRetryScript({ retryPath, trackerBinPath, fallbackPkg, delayMs });
4491
+ function spawnAutoRetryProcess({
4492
+ retryPath,
4493
+ trackerBinPath,
4494
+ runtimeReadyPath,
4495
+ packageEntryPath,
4496
+ fallbackPkg,
4497
+ delayMs,
4498
+ }) {
4499
+ const script = buildAutoRetryScript({
4500
+ retryPath,
4501
+ trackerBinPath,
4502
+ runtimeReadyPath,
4503
+ packageEntryPath,
4504
+ fallbackPkg,
4505
+ delayMs,
4506
+ });
4489
4507
  try {
4490
4508
  const child = cp.spawn(process.execPath, ["-e", script], {
4491
4509
  detached: true,
@@ -4500,13 +4518,22 @@ function spawnAutoRetryProcess({ retryPath, trackerBinPath, fallbackPkg, delayMs
4500
4518
  } catch (_e) {}
4501
4519
  }
4502
4520
 
4503
- function buildAutoRetryScript({ retryPath, trackerBinPath, fallbackPkg, delayMs }) {
4521
+ function buildAutoRetryScript({
4522
+ retryPath,
4523
+ trackerBinPath,
4524
+ runtimeReadyPath,
4525
+ packageEntryPath,
4526
+ fallbackPkg,
4527
+ delayMs,
4528
+ }) {
4504
4529
  return (
4505
4530
  `'use strict';\n` +
4506
4531
  `const fs = require('node:fs');\n` +
4507
4532
  `const cp = require('node:child_process');\n` +
4508
4533
  `const retryPath = ${JSON.stringify(retryPath)};\n` +
4509
4534
  `const trackerBinPath = ${JSON.stringify(trackerBinPath)};\n` +
4535
+ `const runtimeReadyPath = ${JSON.stringify(runtimeReadyPath)};\n` +
4536
+ `const packageEntryPath = ${JSON.stringify(packageEntryPath || null)};\n` +
4510
4537
  `const fallbackPkg = ${JSON.stringify(fallbackPkg)};\n` +
4511
4538
  `const delayMs = ${Math.max(0, Math.floor(delayMs || 0))};\n` +
4512
4539
  `setTimeout(() => {\n` +
@@ -4522,9 +4549,15 @@ function buildAutoRetryScript({ retryPath, trackerBinPath, fallbackPkg, delayMs
4522
4549
  ` if (payload && typeof payload.syncSource === 'string' && payload.syncSource.trim()) {\n` +
4523
4550
  ` argv.push('--source', payload.syncSource.trim());\n` +
4524
4551
  ` }\n` +
4525
- ` const cmd = fs.existsSync(trackerBinPath)\n` +
4552
+ ` // Same readiness contract as notify: a copy without its marker is half\n` +
4553
+ ` // copied, so retry through the installed package instead.\n` +
4554
+ ` const hasLocalRuntime = fs.existsSync(runtimeReadyPath) && fs.existsSync(trackerBinPath);\n` +
4555
+ ` const hasPackageEntry = Boolean(packageEntryPath) && fs.existsSync(packageEntryPath);\n` +
4556
+ ` const cmd = hasLocalRuntime\n` +
4526
4557
  ` ? [process.execPath, trackerBinPath, ...argv]\n` +
4527
- ` : ['npx', '--yes', fallbackPkg, ...argv];\n` +
4558
+ ` : hasPackageEntry\n` +
4559
+ ` ? [process.execPath, packageEntryPath, ...argv]\n` +
4560
+ ` : ['npx', '--yes', fallbackPkg, ...argv];\n` +
4528
4561
  ` try {\n` +
4529
4562
  ` const child = cp.spawn(cmd[0], cmd.slice(1), { detached: true, windowsHide: true, stdio: 'ignore', env: process.env });\n` +
4530
4563
  ` child.unref();\n` +
@@ -143,8 +143,10 @@ async function cmdUninstall(argv) {
143
143
  await fs.unlink(path.join(binDir, "run-sync-hidden.vbs")).catch(() => {});
144
144
  const taskDelete = deleteWindowsScheduledTask();
145
145
 
146
- // Remove local app runtime (installed by init for notify-driven sync).
146
+ // Remove local app runtime (installed by init for notify-driven sync) and any
147
+ // staging directory left behind by an interrupted runtime copy.
147
148
  await fs.rm(path.join(trackerDir, "app"), { recursive: true, force: true }).catch(() => {});
149
+ await fs.rm(path.join(trackerDir, "app.new"), { recursive: true, force: true }).catch(() => {});
148
150
 
149
151
  // Deliberately NOT removed by --purge: the machine-identity seed lets a
150
152
  // reinstall reuse the same cloud device row instead of double-counting the
@@ -64,6 +64,9 @@ function runCommand(commandRunner, command, args, options = {}) {
64
64
  try {
65
65
  child = cp.spawn(shellCommand, args, {
66
66
  ...spawnOptions,
67
+ // Detection/probe commands pipe their output; never let Windows pop a
68
+ // console window when the CLI itself runs from a GUI host.
69
+ windowsHide: spawnOptions.windowsHide ?? true,
67
70
  detached: useProcessGroup || spawnOptions.detached,
68
71
  shell: useShell,
69
72
  stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
package/src/lib/doctor.js CHANGED
@@ -16,6 +16,7 @@ async function buildDoctorReport({
16
16
 
17
17
  if (paths.trackerDir) {
18
18
  checks.push(await checkTrackerDir(paths.trackerDir));
19
+ checks.push(await checkRuntimeCopy(paths.trackerDir));
19
20
  }
20
21
  if (paths.configPath) {
21
22
  checks.push(await checkConfigJson(paths.configPath));
@@ -176,6 +177,75 @@ async function checkTrackerDir(trackerDir) {
176
177
  }
177
178
  }
178
179
 
180
+ // The init-copied runtime (`<trackerDir>/app`) is what notify hooks and the
181
+ // hidden task prefer; without its readiness marker they fall back to the
182
+ // installed CLI. Surface that state instead of leaving it invisible.
183
+ async function checkRuntimeCopy(trackerDir) {
184
+ const { runtimeAppDir, runtimeBinPath, runtimeReadyMarkerPath } = require("./runtime-entry");
185
+ const appDir = runtimeAppDir(trackerDir);
186
+ const binPath = runtimeBinPath(trackerDir);
187
+ const markerPath = runtimeReadyMarkerPath(appDir);
188
+
189
+ if (!(await isDirectory(appDir))) {
190
+ return {
191
+ id: "runtime.copy",
192
+ status: "ok",
193
+ detail: "no runtime copy (hooks use the installed CLI)",
194
+ critical: false,
195
+ meta: { path: appDir },
196
+ };
197
+ }
198
+
199
+ const marker = await readJsonStrict(markerPath);
200
+ const cliVersion = require("../../package.json").version;
201
+ if (!(await isFile(binPath)) || marker.status !== "ok") {
202
+ return {
203
+ id: "runtime.copy",
204
+ status: "warn",
205
+ detail: "runtime copy incomplete; re-run `tokenusage init` (hooks currently use the installed CLI)",
206
+ critical: false,
207
+ meta: { path: appDir, marker: marker.status },
208
+ };
209
+ }
210
+ const version = marker.value && typeof marker.value.version === "string" ? marker.value.version : null;
211
+ if (version && version !== cliVersion) {
212
+ return {
213
+ id: "runtime.copy",
214
+ status: "warn",
215
+ detail: `runtime copy v${version} is older than the CLI v${cliVersion}; re-run \`tokenusage init\``,
216
+ critical: false,
217
+ meta: { path: appDir, version, cli_version: cliVersion },
218
+ };
219
+ }
220
+ return {
221
+ id: "runtime.copy",
222
+ status: "ok",
223
+ detail: `runtime copy ready${version ? ` (v${version})` : ""}`,
224
+ critical: false,
225
+ meta: {
226
+ path: appDir,
227
+ version,
228
+ installed_at: marker.value && typeof marker.value.installedAt === "string" ? marker.value.installedAt : null,
229
+ },
230
+ };
231
+ }
232
+
233
+ async function isDirectory(p) {
234
+ try {
235
+ return (await fs.stat(p)).isDirectory();
236
+ } catch (_err) {
237
+ return false;
238
+ }
239
+ }
240
+
241
+ async function isFile(p) {
242
+ try {
243
+ return (await fs.stat(p)).isFile();
244
+ } catch (_err) {
245
+ return false;
246
+ }
247
+ }
248
+
179
249
  async function checkConfigJson(configPath) {
180
250
  const res = await readJsonStrict(configPath);
181
251
  if (res.status === "ok") {
@@ -761,6 +761,9 @@ function runSyncCommand(extraEnv = {}, opts = {}) {
761
761
  } : {}),
762
762
  TOKENUSAGE_LOCAL_SYNC_DEVICE_TOKEN: extraEnv.TOKENUSAGE_DEVICE_TOKEN || "",
763
763
  },
764
+ // The API can be hosted by a GUI process (desktop shell): keep the piped
765
+ // sync child console-less on Windows.
766
+ windowsHide: true,
764
767
  stdio: ["ignore", "pipe", "pipe"],
765
768
  });
766
769
  const cancel = () => child.kill("SIGTERM");
@@ -116,6 +116,8 @@ function spawnNotify() {
116
116
  try {
117
117
  const child = spawn(process.execPath, [notifyPath, "--source=" + SOURCE], {
118
118
  detached: true,
119
+ // A GUI-hosted oh-my-pi would otherwise flash a console window per turn.
120
+ windowsHide: true,
119
121
  stdio: "ignore",
120
122
  env: process.env,
121
123
  });
@@ -3,6 +3,8 @@ const path = require("node:path");
3
3
  const fs = require("node:fs/promises");
4
4
  const fssync = require("node:fs");
5
5
  const { runOpenclawCli } = require("./openclaw-cli");
6
+ const { cliEntryPath } = require("./scheduled-task");
7
+ const { runtimeReadyMarkerPath } = require("./runtime-entry");
6
8
 
7
9
  const OPENCLAW_HOOK_NAME = "tokenusage-openclaw-sync";
8
10
  const OPENCLAW_HOOK_DIRNAME = "openclaw-hook";
@@ -237,8 +239,14 @@ Triggers non-blocking 'tokenusage sync --auto --from-openclaw' runs when OpenCla
237
239
  `;
238
240
  }
239
241
 
240
- function buildHookHandler({ trackerDir, packageName = "tokenusage-cli", openclawHome }) {
242
+ function buildHookHandler({
243
+ trackerDir,
244
+ packageName = "tokenusage-cli",
245
+ openclawHome,
246
+ packageEntry = cliEntryPath(),
247
+ }) {
241
248
  const trackerBinPath = path.join(trackerDir, "app", "bin", "tracker.js");
249
+ const runtimeReadyPath = runtimeReadyMarkerPath(path.join(trackerDir, "app"));
242
250
  const fallbackPkg = packageName || "tokenusage-cli";
243
251
  const safeOpenclawHome = openclawHome || path.join(os.homedir(), ".openclaw");
244
252
 
@@ -249,10 +257,11 @@ function buildHookHandler({ trackerDir, packageName = "tokenusage-cli", openclaw
249
257
  `const cp = require('node:child_process');\n` +
250
258
  `const trackerDir = ${JSON.stringify(trackerDir)};\n` +
251
259
  `const trackerBinPath = ${JSON.stringify(trackerBinPath)};\n` +
260
+ `const runtimeReadyPath = ${JSON.stringify(runtimeReadyPath)};\n` +
261
+ `const packageEntryPath = ${JSON.stringify(packageEntry || null)};\n` +
252
262
  `const fallbackPkg = ${JSON.stringify(fallbackPkg)};\n` +
253
263
  `const openclawHome = ${JSON.stringify(safeOpenclawHome)};\n` +
254
264
  `const throttlePath = path.join(trackerDir, 'openclaw.sync.throttle');\n` +
255
- `const depsMarkerPath = path.join(trackerDir, 'app', 'bin', 'tracker.js');\n` +
256
265
  `const THROTTLE_MS = 15_000;\n` +
257
266
  `\n` +
258
267
  `module.exports = async function handler(event) {\n` +
@@ -295,13 +304,17 @@ function buildHookHandler({ trackerDir, packageName = "tokenusage-cli", openclaw
295
304
  ` if (prevModel) env.TOKENUSAGE_OPENCLAW_PREV_MODEL = prevModel;\n` +
296
305
  ` if (prevUpdatedAt) env.TOKENUSAGE_OPENCLAW_PREV_UPDATED_AT = prevUpdatedAt;\n` +
297
306
  `\n` +
298
- ` const hasLocalRuntime = fs.existsSync(trackerBinPath);\n` +
299
- ` const hasLocalDeps = fs.existsSync(depsMarkerPath);\n` +
300
- ` const cmd = hasLocalRuntime && hasLocalDeps\n` +
307
+ ` // First usable launcher: init-copied runtime (only with its readiness\n` +
308
+ ` // marker), then the installed package entry, then npx.\n` +
309
+ ` const hasLocalRuntime = fs.existsSync(runtimeReadyPath) && fs.existsSync(trackerBinPath);\n` +
310
+ ` const hasPackageEntry = Boolean(packageEntryPath) && fs.existsSync(packageEntryPath);\n` +
311
+ ` const cmd = hasLocalRuntime\n` +
301
312
  ` ? [process.execPath, trackerBinPath, 'sync', '--auto', '--from-openclaw']\n` +
302
- ` : ['npx', '--yes', fallbackPkg, 'sync', '--auto', '--from-openclaw'];\n` +
313
+ ` : hasPackageEntry\n` +
314
+ ` ? [process.execPath, packageEntryPath, 'sync', '--auto', '--from-openclaw']\n` +
315
+ ` : ['npx', '--yes', fallbackPkg, 'sync', '--auto', '--from-openclaw'];\n` +
303
316
  `\n` +
304
- ` const child = cp.spawn(cmd[0], cmd.slice(1), { detached: true, stdio: 'ignore', env });\n` +
317
+ ` const child = cp.spawn(cmd[0], cmd.slice(1), { detached: true, windowsHide: true, stdio: 'ignore', env });\n` +
305
318
  ` child.unref();\n` +
306
319
  ` } catch (_) {}\n` +
307
320
  `};\n` +
@@ -3,6 +3,8 @@ const path = require("node:path");
3
3
  const fs = require("node:fs/promises");
4
4
  const fssync = require("node:fs");
5
5
  const { runOpenclawCli } = require("./openclaw-cli");
6
+ const { cliEntryPath } = require("./scheduled-task");
7
+ const { runtimeReadyMarkerPath } = require("./runtime-entry");
6
8
 
7
9
  const OPENCLAW_SESSION_PLUGIN_ID = "openclaw-session-sync";
8
10
  const OPENCLAW_SESSION_PLUGIN_DIRNAME = "openclaw-plugin";
@@ -344,8 +346,14 @@ function buildSessionPluginMeta() {
344
346
  )}\n`;
345
347
  }
346
348
 
347
- function buildSessionPluginIndex({ trackerDir, packageName = "tokenusage-cli", openclawHome }) {
349
+ function buildSessionPluginIndex({
350
+ trackerDir,
351
+ packageName = "tokenusage-cli",
352
+ openclawHome,
353
+ packageEntry = cliEntryPath(),
354
+ }) {
348
355
  const trackerBinPath = path.join(trackerDir, "app", "bin", "tracker.js");
356
+ const runtimeReadyPath = runtimeReadyMarkerPath(path.join(trackerDir, "app"));
349
357
  const fallbackPkg = packageName || "tokenusage-cli";
350
358
  const safeOpenclawHome = openclawHome || path.join(os.homedir(), ".openclaw");
351
359
 
@@ -356,9 +364,10 @@ function buildSessionPluginIndex({ trackerDir, packageName = "tokenusage-cli", o
356
364
  `\n` +
357
365
  `const trackerDir = ${JSON.stringify(trackerDir)};\n` +
358
366
  `const trackerBinPath = ${JSON.stringify(trackerBinPath)};\n` +
367
+ `const runtimeReadyPath = ${JSON.stringify(runtimeReadyPath)};\n` +
368
+ `const packageEntryPath = ${JSON.stringify(packageEntry || null)};\n` +
359
369
  `const fallbackPkg = ${JSON.stringify(fallbackPkg)};\n` +
360
370
  `const openclawHome = ${JSON.stringify(safeOpenclawHome)};\n` +
361
- `const depsMarkerPath = path.join(trackerDir, 'app', 'bin', 'tracker.js');\n` +
362
371
  `const triggerStatePath = path.join(trackerDir, 'openclaw.session-sync.trigger-state.json');\n` +
363
372
  `const SESSION_TRIGGER_THROTTLE_MS = 15_000;\n` +
364
373
  `\n` +
@@ -405,14 +414,19 @@ function buildSessionPluginIndex({ trackerDir, packageName = "tokenusage-cli", o
405
414
  `}\n` +
406
415
  `\n` +
407
416
  `function spawnSync({ args, env = {} }) {\n` +
408
- ` const hasLocalRuntime = fs.existsSync(trackerBinPath);\n` +
409
- ` const hasLocalDeps = fs.existsSync(depsMarkerPath);\n` +
417
+ ` // First usable launcher: init-copied runtime (only with its readiness\n` +
418
+ ` // marker), then the installed package entry, then npx.\n` +
419
+ ` const hasLocalRuntime = fs.existsSync(runtimeReadyPath) && fs.existsSync(trackerBinPath);\n` +
420
+ ` const hasPackageEntry = Boolean(packageEntryPath) && fs.existsSync(packageEntryPath);\n` +
410
421
  ` const argv = Array.isArray(args) && args.length > 0 ? args : ['sync', '--auto'];\n` +
411
- ` const cmd = hasLocalRuntime && hasLocalDeps\n` +
422
+ ` const cmd = hasLocalRuntime\n` +
412
423
  ` ? [process.execPath, trackerBinPath, ...argv]\n` +
413
- ` : ['npx', '--yes', fallbackPkg, ...argv];\n` +
424
+ ` : hasPackageEntry\n` +
425
+ ` ? [process.execPath, packageEntryPath, ...argv]\n` +
426
+ ` : ['npx', '--yes', fallbackPkg, ...argv];\n` +
414
427
  ` const child = cp.spawn(cmd[0], cmd.slice(1), {\n` +
415
428
  ` detached: true,\n` +
429
+ ` windowsHide: true,\n` +
416
430
  ` stdio: 'ignore',\n` +
417
431
  ` env: { ...process.env, ...env }\n` +
418
432
  ` });\n` +
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+
3
+ // Shared layout constants for the init-copied runtime (`<trackerDir>/app`).
4
+ //
5
+ // init copies the CLI (bin + src + deps) into the data dir so notify hooks and
6
+ // the scheduled task can run `sync` without npx and without depending on npm's
7
+ // global prefix (nvm-windows makes that prefix version-specific). The copy is
8
+ // only usable when `.runtime-ready` exists next to it: every spawn point probes
9
+ // both the launcher and the marker, so a half-copied runtime (missing deps)
10
+ // degrades to the installed package instead of dying silently in an ignored
11
+ // stdio stream — which looks exactly like "collection is running" while
12
+ // nothing is collected.
13
+
14
+ const path = require("node:path");
15
+
16
+ const RUNTIME_READY_MARKER = ".runtime-ready";
17
+
18
+ function runtimeAppDir(trackerDir) {
19
+ return path.join(trackerDir, "app");
20
+ }
21
+
22
+ function runtimeBinPath(trackerDir) {
23
+ return path.join(runtimeAppDir(trackerDir), "bin", "tracker.js");
24
+ }
25
+
26
+ function runtimeReadyMarkerPath(appDir) {
27
+ return path.join(appDir, RUNTIME_READY_MARKER);
28
+ }
29
+
30
+ module.exports = {
31
+ RUNTIME_READY_MARKER,
32
+ runtimeAppDir,
33
+ runtimeBinPath,
34
+ runtimeReadyMarkerPath,
35
+ };
@@ -4,7 +4,7 @@
4
4
  //
5
5
  // init "takes over" the registration that 0.1.0 left to a manual runbook:
6
6
  // the task action launches a VBS wrapper (GUI subsystem — no conhost flash
7
- // on Interactive tasks), which runs `node <cli.js> sync` fully hidden and
7
+ // on Interactive tasks), which runs `node <bin entry> sync` fully hidden and
8
8
  // propagates the exit code via WScript.Quit. The CLI logs to a rolling
9
9
  // <trackerDir>/logs/sync.log itself (autoLog sink), so the registration no
10
10
  // longer needs a `>>` redirect — which also removes the cmd /c quoting
@@ -39,31 +39,60 @@ function cliEntryPath() {
39
39
  }
40
40
 
41
41
  /**
42
- * The hidden-runner wrapper. Paths are quoted individually and cmd is NOT
43
- * involved: wscript runs node directly, so the cmd /c outer-quote-stripping
44
- * pitfall (paths with spaces) never applies.
42
+ * The hidden-runner wrapper. Paths are quoted individually (via Chr(34), so
43
+ * the VBS has no quote-escaping puzzles) and cmd is NOT involved: wscript
44
+ * runs node directly, so the cmd /c outer-quote-stripping pitfall (paths with
45
+ * spaces) never applies.
46
+ *
47
+ * `fallbackCliJs` is the init-copied runtime (trackerDir/app/bin/tracker.js).
48
+ * The primary path lives in npm's global prefix, which nvm-windows makes
49
+ * version-specific: after `nvm use` the package is gone from that prefix and
50
+ * an unconditional launch would fail every hour with "file not found". The
51
+ * fallback keeps collecting (with the last init-copied build) instead.
45
52
  */
46
- function buildHiddenRunnerVbs({ nodeExe, cliJs }) {
53
+ function buildHiddenRunnerVbs({ nodeExe, cliJs, fallbackCliJs }) {
47
54
  // --from-scheduled: the run reports trigger=scheduled, self-logs via autoLog
48
55
  // and uploads without consulting the cloud-sync preference — the registered
49
56
  // task is the default collection path, not an opt-in flavor.
50
- return [
57
+ const lines = [
51
58
  "' Token Usage — hidden sync runner.",
52
59
  "' The scheduled task launches this script (GUI subsystem: no conhost",
53
60
  "' flash); it runs the sync fully hidden and returns its exit code so the",
54
61
  "' task's LastTaskResult stays meaningful. Sync output lands in the CLI's",
55
62
  "' own rolling logs/sync.log — no shell redirect involved.",
56
- "Dim shell",
63
+ "Dim shell, fso, nodeExe, cliJs, cmd, q",
57
64
  "Set shell = CreateObject(\"WScript.Shell\")",
58
- `WScript.Quit shell.Run("""${nodeExe}"" ""${cliJs}"" sync --from-scheduled", 0, True)`,
65
+ "Set fso = CreateObject(\"Scripting.FileSystemObject\")",
66
+ "q = Chr(34)",
67
+ `nodeExe = "${nodeExe}"`,
68
+ `cliJs = "${cliJs}"`,
69
+ ];
70
+ if (fallbackCliJs) {
71
+ lines.push(
72
+ "' npm's global prefix is version-specific under nvm-windows, so the",
73
+ "' path above disappears after `nvm use`. init also copies a",
74
+ "' self-contained runtime into the data dir; fall back to it rather than",
75
+ "' failing the hourly run with \"file not found\".",
76
+ `If Not fso.FileExists(cliJs) Then cliJs = "${fallbackCliJs}"`,
77
+ );
78
+ }
79
+ lines.push(
80
+ "cmd = q & nodeExe & q & \" \" & q & cliJs & q & \" sync --from-scheduled\"",
81
+ "WScript.Quit shell.Run(cmd, 0, True)",
59
82
  "",
60
- ].join("\n");
83
+ );
84
+ return lines.join("\n");
61
85
  }
62
86
 
63
- function writeHiddenRunner({ binDir, nodeExe = process.execPath, cliJs = cliEntryPath() }) {
87
+ function writeHiddenRunner({
88
+ binDir,
89
+ nodeExe = process.execPath,
90
+ cliJs = cliEntryPath(),
91
+ fallbackCliJs,
92
+ }) {
64
93
  fs.mkdirSync(binDir, { recursive: true });
65
94
  const vbsPath = vbsPathFor(binDir);
66
- fs.writeFileSync(vbsPath, buildHiddenRunnerVbs({ nodeExe, cliJs }), { mode: 0o600 });
95
+ fs.writeFileSync(vbsPath, buildHiddenRunnerVbs({ nodeExe, cliJs, fallbackCliJs }), { mode: 0o600 });
67
96
  return vbsPath;
68
97
  }
69
98
 
@@ -71,10 +100,15 @@ function writeHiddenRunner({ binDir, nodeExe = process.execPath, cliJs = cliEntr
71
100
  * Register (idempotently — /F overwrites) the hourly hidden task. Returns
72
101
  * {registered: true} or {registered: false, reason} instead of throwing.
73
102
  */
74
- function registerWindowsScheduledTask({ binDir, cliJs = cliEntryPath(), nodeExe = process.execPath }) {
103
+ function registerWindowsScheduledTask({
104
+ binDir,
105
+ cliJs = cliEntryPath(),
106
+ nodeExe = process.execPath,
107
+ fallbackCliJs,
108
+ }) {
75
109
  if (!isWindows()) return { registered: false, reason: "not_windows" };
76
110
  try {
77
- const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs });
111
+ const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs, fallbackCliJs });
78
112
  execFileSync(
79
113
  "schtasks",
80
114
  [
@@ -221,10 +221,28 @@ test("init's runtime copy works from the published layout (bin/tokenusage.js)",
221
221
  const home = fs.mkdtempSync(path.join(os.tmpdir(), "tu-init-copy-"));
222
222
  const appDir = path.join(home, "tracker", "app");
223
223
  try {
224
- await installLocalTrackerApp({ appDir });
224
+ const result = await installLocalTrackerApp({ appDir });
225
+ assert.equal(result.ok, true, `installation reported a failure: ${JSON.stringify(result)}`);
225
226
  assert.ok(fs.existsSync(path.join(appDir, "bin", "tracker.js")), "app/bin/tracker.js copied");
226
227
  assert.ok(fs.existsSync(path.join(appDir, "src", "cli.js")), "app/src copied");
227
228
  assert.ok(fs.existsSync(path.join(appDir, "package.json")), "app/package.json copied");
229
+ // 0.2.4: the copy must be self-contained. npm links nothing, but pnpm links
230
+ // deps as junctions into a shared store — copying those links produced a
231
+ // runtime that died with MODULE_NOT_FOUND (one node_modules entry, no deps).
232
+ assert.ok(
233
+ fs.existsSync(path.join(appDir, "node_modules", "smol-toml")),
234
+ "declared dependency copied as a real directory",
235
+ );
236
+ assert.ok(
237
+ fs.existsSync(path.join(appDir, "node_modules", "@sentry", "core")),
238
+ "transitive dependency of @sentry/node copied too (flattened closure)",
239
+ );
240
+ // The marker is what every spawn point probes: without it hooks fall back
241
+ // to the installed CLI instead of spawning a half copy.
242
+ const markerPath = path.join(appDir, ".runtime-ready");
243
+ assert.ok(fs.existsSync(markerPath), ".runtime-ready written only after the copy booted");
244
+ const marker = JSON.parse(fs.readFileSync(markerPath, "utf8"));
245
+ assert.equal(marker.version, require("../package.json").version);
228
246
  } finally {
229
247
  fs.rmSync(home, { recursive: true, force: true });
230
248
  }
@@ -16,6 +16,17 @@ test("a valid --interval is adopted and removed from the sync args", () => {
16
16
  });
17
17
  });
18
18
 
19
+ test("--interval=<ms> works too and never leaks into the sync args", () => {
20
+ assert.deepEqual(resolveWatchInterval(["--watch", "--interval=300000", "--no-sessions"]), {
21
+ args: ["--no-sessions"],
22
+ intervalMs: 300_000,
23
+ });
24
+ assert.deepEqual(resolveWatchInterval(["--interval=1000"]), {
25
+ args: [],
26
+ intervalMs: FALLBACK_MS,
27
+ });
28
+ });
29
+
19
30
  test("a sub-floor or missing --interval falls back to 15 min but is still removed", () => {
20
31
  for (const rest of [["--watch", "--interval", "1000"], ["--interval", "0"], ["--watch", "--interval"], ["--interval", "abc"]]) {
21
32
  const parsed = resolveWatchInterval(rest);
@@ -173,14 +173,38 @@ test("hidden-runner VBS quotes paths individually and propagates the exit code",
173
173
  nodeExe: "C:\\Program Files\\nodejs\\node.exe",
174
174
  cliJs: "C:\\Users\\me\\AppData\\tokenusage-cli\\bin\\tokenusage.js",
175
175
  });
176
- assert.match(vbs, /WScript\.Quit shell\.Run/);
177
- assert.match(vbs, /""C:\\Program Files\\nodejs\\node\.exe"" ""C:\\Users\\me\\AppData\\tokenusage-cli\\bin\\tokenusage\.js"" sync --from-scheduled/);
176
+ // Chr(34) builds the quotes: no VBS quote-escaping, no cmd /c layer, and
177
+ // paths with spaces stay intact.
178
+ assert.match(vbs, /q = Chr\(34\)/);
179
+ assert.ok(vbs.includes('nodeExe = "C:\\Program Files\\nodejs\\node.exe"'));
180
+ assert.ok(vbs.includes('cliJs = "C:\\Users\\me\\AppData\\tokenusage-cli\\bin\\tokenusage.js"'));
181
+ assert.ok(vbs.includes('cmd = q & nodeExe & q & " " & q & cliJs & q & " sync --from-scheduled"'));
178
182
  // Hidden window (0) + wait for completion (True).
179
- assert.match(vbs, /, 0, True\)/);
183
+ assert.match(vbs, /WScript\.Quit shell\.Run\(cmd, 0, True\)/);
180
184
  // The task name stays stable — pause/resume and uninstall toggle by name.
181
185
  assert.equal(TASK_NAME, "TokenUsageSync");
182
186
  });
183
187
 
188
+ // nvm-windows installs npm globals into a version-specific prefix, so the
189
+ // recorded package path vanishes after `nvm use` and the hourly run failed
190
+ // every time with "file not found". The VBS now falls back to the
191
+ // init-copied runtime, which lives under the data dir.
192
+ test("hidden-runner VBS falls back to the init runtime when the package path disappears", () => {
193
+ const fallback = "C:\\Users\\me\\.tokenusage\\tracker\\app\\bin\\tracker.js";
194
+ const vbs = buildHiddenRunnerVbs({
195
+ nodeExe: "C:\\Program Files\\nodejs\\node.exe",
196
+ cliJs: "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\tokenusage-cli\\bin\\tokenusage.js",
197
+ fallbackCliJs: fallback,
198
+ });
199
+ assert.ok(
200
+ vbs.includes(`If Not fso.FileExists(cliJs) Then cliJs = "${fallback}"`),
201
+ "the runtime copy must be the fallback target",
202
+ );
203
+ // Non-nvm layouts have nothing to fall back to; the line stays out.
204
+ const plain = buildHiddenRunnerVbs({ nodeExe: "node.exe", cliJs: "C:\\a\\b.js" });
205
+ assert.ok(!plain.includes("FileExists"), "no fallback probe without a fallback path");
206
+ });
207
+
184
208
  // 0.2.2 regression: init registered src/cli.js instead of the bin entry. That
185
209
  // file only exports run(), so the hidden task exited 0 within ~0.1 s without
186
210
  // collecting or logging anything — a silent, permanently "successful" task.
@@ -52,3 +52,32 @@ test("the unported install heartbeat stays removed", () => {
52
52
  assert.ok(!sync.includes("maybeSendHeartbeat"));
53
53
  assert.ok(!sync.includes('require("../lib/telemetry")'));
54
54
  });
55
+
56
+ test("every auto-sync spawn point gates on the runtime-copy readiness marker", () => {
57
+ // 0.2.4: a runtime copy without its marker is a half copy (missing deps) and
58
+ // dies with MODULE_NOT_FOUND inside an ignored stdio stream — collection
59
+ // looks alive while nothing is collected. Each generated/hidden launcher must
60
+ // check the marker before choosing it.
61
+ const init = readSource("src", "commands", "init.js");
62
+ assert.ok(init.includes("runtimeReadyMarkerPath"), "init.js must write and probe the marker");
63
+
64
+ const notify = readSource("src", "commands", "init.js");
65
+ assert.ok(
66
+ notify.includes("const hasLocalRuntime = fs.existsSync(runtimeReadyPath) && fs.existsSync(trackerBinPath);"),
67
+ "the notify handler must require both the launcher and the marker",
68
+ );
69
+
70
+ for (const file of [["src", "lib", "openclaw-hook.js"], ["src", "lib", "openclaw-session-plugin.js"]]) {
71
+ const source = readSource(...file);
72
+ assert.ok(
73
+ source.includes("runtimeReadyPath") && source.includes("packageEntryPath"),
74
+ `${file.join("/")} must bake the marker + installed-package fallback`,
75
+ );
76
+ }
77
+
78
+ const sync = readSource("src", "commands", "sync.js");
79
+ assert.ok(
80
+ sync.includes("runtimeReadyPath") && sync.includes("packageEntryPath"),
81
+ "the auto-retry script must use the same launcher selection",
82
+ );
83
+ });
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+
3
+ // The init-copied runtime (`<trackerDir>/app`) is the launcher behind notify
4
+ // hooks, the hidden scheduled task and the auto-retry child. 0.2.4 made its
5
+ // readiness marker the single gate: a copy that never booted must never be
6
+ // spawned (it dies with MODULE_NOT_FOUND inside an ignored stdio stream, which
7
+ // is indistinguishable from "collection is running"), and `doctor` must say so.
8
+
9
+ const assert = require("node:assert/strict");
10
+ const fs = require("node:fs");
11
+ const os = require("node:os");
12
+ const path = require("node:path");
13
+ const { test } = require("node:test");
14
+
15
+ const { buildNotifyHandler } = require("../src/commands/init");
16
+ const { buildDoctorReport } = require("../src/lib/doctor");
17
+ const { runtimeAppDir, runtimeBinPath, runtimeReadyMarkerPath, RUNTIME_READY_MARKER } = require("../src/lib/runtime-entry");
18
+
19
+ const CLI_VERSION = require("../package.json").version;
20
+
21
+ async function withTrackerDir(fn) {
22
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "tu-runtime-copy-"));
23
+ const trackerDir = path.join(home, "tracker");
24
+ fs.mkdirSync(trackerDir, { recursive: true });
25
+ try {
26
+ return await fn({ home, trackerDir });
27
+ } finally {
28
+ fs.rmSync(home, { recursive: true, force: true });
29
+ }
30
+ }
31
+
32
+ async function runtimeCopyCheck(trackerDir) {
33
+ const report = await buildDoctorReport({
34
+ runtime: { baseUrl: "https://example.test", deviceToken: "present", dashboardUrl: "https://example.test" },
35
+ diagnostics: null,
36
+ fetch: async () => ({ ok: true, status: 200 }),
37
+ paths: { trackerDir, configPath: path.join(trackerDir, "config.json") },
38
+ });
39
+ return report.checks.find((check) => check.id === "runtime.copy");
40
+ }
41
+
42
+ test("runtime-entry: the marker lives next to the copy, not inside bin/", () => {
43
+ const trackerDir = path.join("home", ".tokenusage", "tracker");
44
+ assert.equal(runtimeAppDir(trackerDir), path.join(trackerDir, "app"));
45
+ assert.equal(runtimeBinPath(trackerDir), path.join(trackerDir, "app", "bin", "tracker.js"));
46
+ assert.equal(
47
+ runtimeReadyMarkerPath(runtimeAppDir(trackerDir)),
48
+ path.join(trackerDir, "app", RUNTIME_READY_MARKER),
49
+ );
50
+ });
51
+
52
+ test("doctor: no runtime copy is fine (hooks use the installed CLI)", async () => {
53
+ const check = await withTrackerDir(({ trackerDir }) => runtimeCopyCheck(trackerDir));
54
+ assert.equal(check.status, "ok");
55
+ assert.match(check.detail, /installed CLI/);
56
+ });
57
+
58
+ test("doctor: a copy without its marker is reported as incomplete", async () => {
59
+ await withTrackerDir(async ({ trackerDir }) => {
60
+ const appDir = runtimeAppDir(trackerDir);
61
+ fs.mkdirSync(path.join(appDir, "bin"), { recursive: true });
62
+ fs.writeFileSync(path.join(appDir, "bin", "tracker.js"), "// half copy\n");
63
+ const check = await runtimeCopyCheck(trackerDir);
64
+ assert.equal(check.status, "warn");
65
+ assert.match(check.detail, /incomplete/);
66
+ });
67
+ });
68
+
69
+ test("doctor: a ready copy reports its version", async () => {
70
+ await withTrackerDir(async ({ trackerDir }) => {
71
+ const appDir = runtimeAppDir(trackerDir);
72
+ fs.mkdirSync(path.join(appDir, "bin"), { recursive: true });
73
+ fs.writeFileSync(path.join(appDir, "bin", "tracker.js"), "// copy\n");
74
+ fs.writeFileSync(
75
+ runtimeReadyMarkerPath(appDir),
76
+ JSON.stringify({ version: CLI_VERSION, installedAt: "2026-10-28T00:00:00.000Z" }),
77
+ );
78
+ const check = await runtimeCopyCheck(trackerDir);
79
+ assert.equal(check.status, "ok");
80
+ assert.match(check.detail, new RegExp(`v${CLI_VERSION.replace(/\./g, "\\.")}`));
81
+ assert.equal(check.meta.version, CLI_VERSION);
82
+ });
83
+ });
84
+
85
+ test("doctor: a copy from an older CLI is flagged for a re-run", async () => {
86
+ await withTrackerDir(async ({ trackerDir }) => {
87
+ const appDir = runtimeAppDir(trackerDir);
88
+ fs.mkdirSync(path.join(appDir, "bin"), { recursive: true });
89
+ fs.writeFileSync(path.join(appDir, "bin", "tracker.js"), "// copy\n");
90
+ fs.writeFileSync(runtimeReadyMarkerPath(appDir), JSON.stringify({ version: "0.0.1" }));
91
+ const check = await runtimeCopyCheck(trackerDir);
92
+ assert.equal(check.status, "warn");
93
+ assert.match(check.detail, /older than the CLI/);
94
+ });
95
+ });
96
+
97
+ test("notify handler: marker + installed-package fallback baked into the template", () => {
98
+ const source = buildNotifyHandler({ trackerDir: path.join("C:", "home", ".tokenusage", "tracker") });
99
+ assert.ok(source.includes("runtimeReadyPath"), "the template must probe the readiness marker");
100
+ assert.ok(source.includes("packageEntryPath"), "the template must carry the installed CLI entry");
101
+ assert.ok(
102
+ source.includes("const hasLocalRuntime = fs.existsSync(runtimeReadyPath) && fs.existsSync(trackerBinPath);"),
103
+ "both the launcher and the marker are required",
104
+ );
105
+ assert.ok(
106
+ source.includes(": hasPackageEntry\n ? [process.execPath, packageEntryPath, ...syncArgs]"),
107
+ "the middle tier runs the installed package without npx",
108
+ );
109
+ // The generated file must stay dependency-free: only node built-ins.
110
+ assert.ok(!/require\(['"](?!node:)/.test(source), "notify.cjs must only require node: built-ins");
111
+ });