tokenusage-cli 0.2.2 → 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/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") {
@@ -26,7 +26,7 @@ const SYNC_TIMEOUT_MS = 120_000;
26
26
  // request still falls back normally; subsequent fan-out requests reuse that
27
27
  // decision for a short cooldown and return local data immediately.
28
28
  const ACCOUNT_VIEW_FAILURE_BACKOFF_MS = 2 * 60_000;
29
- const TRACKER_BIN = path.resolve(__dirname, "../../bin/tracker.js");
29
+ const TRACKER_BIN = path.resolve(__dirname, "../../bin/tokenusage.js");
30
30
  const MAX_DEVICE_NAME_LENGTH = 128;
31
31
 
32
32
  function getSystemDeviceName() {
@@ -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");
@@ -1424,7 +1427,7 @@ function createLocalApiHandler({ queuePath, serverVersion = null, trackerDataDir
1424
1427
  // 必须和 dashboard/src/lib/cloud-sync.ts 使用同一个设备身份。
1425
1428
  // 旧云端设备按 (platform, device_name) 认领;如果这里发明
1426
1429
  // local-sync 身份,会多出一个 active device,账户视图会把历史求和两次。
1427
- device_name: getSystemDeviceName() || `Token Tracker (dashboard) #${machineId.slice(0, 8)}`,
1430
+ device_name: getSystemDeviceName() || `Token Usage (dashboard) #${machineId.slice(0, 8)}`,
1428
1431
  platform: dashboardPlatform,
1429
1432
  machine_id: machineId,
1430
1433
  }),
@@ -3158,23 +3161,6 @@ function createLocalApiHandler({ queuePath, serverVersion = null, trackerDataDir
3158
3161
  return true;
3159
3162
  }
3160
3163
 
3161
- // --- telemetry preference (anonymous analytics opt-out mirror) ---
3162
- // The dashboard's analytics init on localhost / native-app surfaces asks
3163
- // this before sending anything, so TOKENUSAGE_NO_TELEMETRY /
3164
- // DO_NOT_TRACK / config.json `"telemetry": false` turn off dashboard
3165
- // analytics together with the daily heartbeat (src/lib/telemetry.js).
3166
- if (p === "/api/functions/tokenusage-telemetry-pref") {
3167
- const { isTelemetryDisabled } = require("./telemetry");
3168
- let config = {};
3169
- try {
3170
- config = JSON.parse(fs.readFileSync(path.join(path.dirname(qp), "config.json"), "utf8")) || {};
3171
- } catch {
3172
- config = {};
3173
- }
3174
- json(res, { disabled: isTelemetryDisabled({ env: process.env, config }) });
3175
- return true;
3176
- }
3177
-
3178
3164
  // --- machine-id (stable per-machine device identity for cloud sync) ---
3179
3165
  // The dashboard reads this before issuing a cloud device token so the
3180
3166
  // device_name keys on the MACHINE, not the browser — see
@@ -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` +
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Passive-mode detection.
3
3
  *
4
- * Token Tracker normally collects token usage by installing SessionEnd hooks
4
+ * Token Usage normally collects token usage by installing SessionEnd hooks
5
5
  * into supported CLIs (Claude Code, Codex CLI, Gemini CLI, …). The hook
6
6
  * fires `notify.cjs` after each turn → sync runs immediately → data is
7
7
  * fresh within seconds.
@@ -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
@@ -31,32 +31,68 @@ function vbsPathFor(binDir) {
31
31
  return path.join(binDir, VBS_FILE);
32
32
  }
33
33
 
34
+ // The task must launch the package's CLI entry, not src/cli.js: the latter is
35
+ // a library that only exports run(), so a hidden `node src/cli.js sync ...`
36
+ // exits 0 having collected nothing (the task then looks successful forever).
37
+ function cliEntryPath() {
38
+ return path.resolve(__dirname, "..", "..", "bin", "tokenusage.js");
39
+ }
40
+
34
41
  /**
35
- * The hidden-runner wrapper. Paths are quoted individually and cmd is NOT
36
- * involved: wscript runs node directly, so the cmd /c outer-quote-stripping
37
- * 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.
38
52
  */
39
- function buildHiddenRunnerVbs({ nodeExe, cliJs }) {
53
+ function buildHiddenRunnerVbs({ nodeExe, cliJs, fallbackCliJs }) {
40
54
  // --from-scheduled: the run reports trigger=scheduled, self-logs via autoLog
41
55
  // and uploads without consulting the cloud-sync preference — the registered
42
56
  // task is the default collection path, not an opt-in flavor.
43
- return [
57
+ const lines = [
44
58
  "' Token Usage — hidden sync runner.",
45
59
  "' The scheduled task launches this script (GUI subsystem: no conhost",
46
60
  "' flash); it runs the sync fully hidden and returns its exit code so the",
47
61
  "' task's LastTaskResult stays meaningful. Sync output lands in the CLI's",
48
62
  "' own rolling logs/sync.log — no shell redirect involved.",
49
- "Dim shell",
63
+ "Dim shell, fso, nodeExe, cliJs, cmd, q",
50
64
  "Set shell = CreateObject(\"WScript.Shell\")",
51
- `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)",
52
82
  "",
53
- ].join("\n");
83
+ );
84
+ return lines.join("\n");
54
85
  }
55
86
 
56
- function writeHiddenRunner({ binDir, nodeExe = process.execPath, cliJs }) {
87
+ function writeHiddenRunner({
88
+ binDir,
89
+ nodeExe = process.execPath,
90
+ cliJs = cliEntryPath(),
91
+ fallbackCliJs,
92
+ }) {
57
93
  fs.mkdirSync(binDir, { recursive: true });
58
94
  const vbsPath = vbsPathFor(binDir);
59
- fs.writeFileSync(vbsPath, buildHiddenRunnerVbs({ nodeExe, cliJs }), { mode: 0o600 });
95
+ fs.writeFileSync(vbsPath, buildHiddenRunnerVbs({ nodeExe, cliJs, fallbackCliJs }), { mode: 0o600 });
60
96
  return vbsPath;
61
97
  }
62
98
 
@@ -64,10 +100,15 @@ function writeHiddenRunner({ binDir, nodeExe = process.execPath, cliJs }) {
64
100
  * Register (idempotently — /F overwrites) the hourly hidden task. Returns
65
101
  * {registered: true} or {registered: false, reason} instead of throwing.
66
102
  */
67
- function registerWindowsScheduledTask({ binDir, cliJs, nodeExe = process.execPath }) {
103
+ function registerWindowsScheduledTask({
104
+ binDir,
105
+ cliJs = cliEntryPath(),
106
+ nodeExe = process.execPath,
107
+ fallbackCliJs,
108
+ }) {
68
109
  if (!isWindows()) return { registered: false, reason: "not_windows" };
69
110
  try {
70
- const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs });
111
+ const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs, fallbackCliJs });
71
112
  execFileSync(
72
113
  "schtasks",
73
114
  [
@@ -139,6 +180,7 @@ module.exports = {
139
180
  VBS_FILE,
140
181
  isWindows,
141
182
  vbsPathFor,
183
+ cliEntryPath,
142
184
  buildHiddenRunnerVbs,
143
185
  writeHiddenRunner,
144
186
  registerWindowsScheduledTask,
package/src/lib/sentry.js CHANGED
@@ -3,9 +3,9 @@
3
3
  /**
4
4
  * Optional Sentry error reporting for the Node CLI / EmbeddedServer runtime.
5
5
  *
6
- * Privacy contract (keep in sync with docs/PRIVACY.md and dashboard/src/lib/sentry.js):
6
+ * Privacy contract (keep in sync with README "隐私边界"):
7
7
  * - Off unless TOKENUSAGE_SENTRY_DSN (or SENTRY_DSN) is set.
8
- * - Honors the same telemetry opt-out as the daily heartbeat
8
+ * - Honors the shared telemetry opt-out
9
9
  * (TOKENUSAGE_NO_TELEMETRY / DO_NOT_TRACK / config.json `"telemetry": false`).
10
10
  * - Fail-closed in the node test runner.
11
11
  * - Never intended to carry prompts, code, or provider secrets; beforeSend
@@ -15,7 +15,7 @@
15
15
  const path = require("node:path");
16
16
  const pkg = require("../../package.json");
17
17
  const { readJson } = require("./fs");
18
- const { isTelemetryDisabled } = require("./telemetry");
18
+ const { isTelemetryDisabled } = require("./telemetry-pref");
19
19
 
20
20
  const SECRET_PATTERN =
21
21
  /(?:api[_-]?key|access[_-]?token|refresh[_-]?token|cookie|secret|password|dsn)[=:\s]+["']?[^\s"'\\]{8,}/gi;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Outbound telemetry opt-out, shared by the optional Sentry error reporting.
5
+ *
6
+ * 0.2.3 removed the upstream anonymous install heartbeat: this backend never
7
+ * implemented `/api/functions/tokenusage-telemetry`, so every sync only earned
8
+ * a 404. Sentry remains strictly opt-in (needs a DSN) and honors the same
9
+ * opt-out switches:
10
+ * - TOKENUSAGE_NO_TELEMETRY=1
11
+ * - DO_NOT_TRACK (the standard)
12
+ * - `"telemetry": false` in config.json
13
+ */
14
+
15
+ function isTruthyFlag(value) {
16
+ if (typeof value !== "string") return false;
17
+ const v = value.trim().toLowerCase();
18
+ return v === "1" || v === "true";
19
+ }
20
+
21
+ function isTelemetryDisabled({ env = process.env, config = {} } = {}) {
22
+ if (isTruthyFlag(env?.TOKENUSAGE_NO_TELEMETRY)) return true;
23
+ if (isTruthyFlag(env?.DO_NOT_TRACK)) return true;
24
+ if (config && config.telemetry === false) return true;
25
+ return false;
26
+ }
27
+
28
+ module.exports = { isTelemetryDisabled };
@@ -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
  }
@@ -0,0 +1,24 @@
1
+ // Branding guard (AGENTS.md 硬性约束 9): the product is "Token Usage"; the
2
+ // tokentracker name may only survive as a legacy path alias. The vendored
3
+ // upstream banner still spelled TOKEN TRACKER until 0.2.3.
4
+
5
+ const assert = require("node:assert/strict");
6
+ const fs = require("node:fs");
7
+ const path = require("node:path");
8
+ const { test } = require("node:test");
9
+
10
+ function readSource(...segments) {
11
+ return fs.readFileSync(path.join(__dirname, "..", "src", ...segments), "utf8");
12
+ }
13
+
14
+ test("init's welcome banner uses the Token Usage name", () => {
15
+ const initSource = readSource("commands", "init.js");
16
+ assert.match(initSource, /Token Usage/);
17
+ assert.ok(!initSource.includes("Token Tracker"), "fork branding must not reappear in init");
18
+ assert.ok(!initSource.includes("TRACKER"), "the ASCII logo must spell TOKEN USAGE");
19
+ });
20
+
21
+ test("local-api's fallback device name no longer says Token Tracker", () => {
22
+ const source = readSource("lib", "local-api.js");
23
+ assert.ok(!source.includes("Token Tracker"));
24
+ });
@@ -0,0 +1,43 @@
1
+ // `sync --watch --interval <ms>`: README promises values below the 1-minute
2
+ // floor fall back to 15 min. The flag used to survive into cmdSync's args when
3
+ // the value was rejected, so every pass failed with "Unknown option".
4
+
5
+ const assert = require("node:assert/strict");
6
+ const { test } = require("node:test");
7
+
8
+ const { resolveWatchInterval } = require("../src/cli");
9
+
10
+ const FALLBACK_MS = 15 * 60_000;
11
+
12
+ test("a valid --interval is adopted and removed from the sync args", () => {
13
+ assert.deepEqual(resolveWatchInterval(["--watch", "--interval", "120000"]), {
14
+ args: [],
15
+ intervalMs: 120_000,
16
+ });
17
+ });
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
+
30
+ test("a sub-floor or missing --interval falls back to 15 min but is still removed", () => {
31
+ for (const rest of [["--watch", "--interval", "1000"], ["--interval", "0"], ["--watch", "--interval"], ["--interval", "abc"]]) {
32
+ const parsed = resolveWatchInterval(rest);
33
+ assert.equal(parsed.intervalMs, FALLBACK_MS, `intervalMs for ${JSON.stringify(rest)}`);
34
+ assert.deepEqual(parsed.args, [], `leftover args for ${JSON.stringify(rest)}`);
35
+ }
36
+ });
37
+
38
+ test("unrelated sync flags survive untouched", () => {
39
+ assert.deepEqual(resolveWatchInterval(["--watch", "--drain", "--no-sessions"]), {
40
+ args: ["--drain", "--no-sessions"],
41
+ intervalMs: FALLBACK_MS,
42
+ });
43
+ });
@@ -25,6 +25,7 @@ const {
25
25
  } = require("../src/lib/sync-report");
26
26
  const {
27
27
  TASK_NAME,
28
+ cliEntryPath,
28
29
  buildHiddenRunnerVbs,
29
30
  } = require("../src/lib/scheduled-task");
30
31
 
@@ -170,16 +171,52 @@ test("report() is strictly best-effort: never throws, skips unpaired runs, logs
170
171
  test("hidden-runner VBS quotes paths individually and propagates the exit code", () => {
171
172
  const vbs = buildHiddenRunnerVbs({
172
173
  nodeExe: "C:\\Program Files\\nodejs\\node.exe",
173
- cliJs: "C:\\Users\\me\\AppData\\tokenusage-cli\\src\\cli.js",
174
+ cliJs: "C:\\Users\\me\\AppData\\tokenusage-cli\\bin\\tokenusage.js",
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 --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"'));
177
182
  // Hidden window (0) + wait for completion (True).
178
- assert.match(vbs, /, 0, True\)/);
183
+ assert.match(vbs, /WScript\.Quit shell\.Run\(cmd, 0, True\)/);
179
184
  // The task name stays stable — pause/resume and uninstall toggle by name.
180
185
  assert.equal(TASK_NAME, "TokenUsageSync");
181
186
  });
182
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
+
208
+ // 0.2.2 regression: init registered src/cli.js instead of the bin entry. That
209
+ // file only exports run(), so the hidden task exited 0 within ~0.1 s without
210
+ // collecting or logging anything — a silent, permanently "successful" task.
211
+ test("scheduled task launches the CLI entry, never the inert src/cli.js", () => {
212
+ const entry = cliEntryPath().replace(/\\/g, "/");
213
+ assert.match(entry, /\/bin\/tokenusage\.js$/);
214
+ assert.ok(fs.existsSync(cliEntryPath()), "the registered entry must exist in the package");
215
+
216
+ const vbs = buildHiddenRunnerVbs({ nodeExe: "node.exe", cliJs: cliEntryPath() });
217
+ assert.doesNotMatch(vbs, /src[\\/]cli\.js/);
218
+ });
219
+
183
220
  test("--from-scheduled reports as scheduled, unlike a plain manual run", () => {
184
221
  assert.equal(resolveSyncTrigger({ fromScheduled: true }), "scheduled");
185
222
  // The scheduled task must upload on default installs, so --from-scheduled