tokenusage-cli 0.2.2 → 0.2.3

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,35 @@
3
3
  本包(`tokenusage-cli`)的用户可见变更记录。发版时在顶部新增一节,
4
4
  `## <版本号>` 行会被 release workflow 取作 GitHub Release 正文。
5
5
 
6
+ ## 0.2.3
7
+
8
+ 修复 0.2.x 计划任务的两个隐藏缺陷(0.2.2 升级验收时实测发现)。
9
+
10
+ - 计划任务指向错误入口:init 注册的隐藏 VBS 调用的是 `src/cli.js`——那是只
11
+ 导出 `run()` 的库文件、没有命令行入口,任务 0.1 秒内以退出码 0 结束,
12
+ 既不采集也不写日志,`LastTaskResult` 永远是 0(看起来永远成功)。VBS 现
13
+ 固定指向包内 `bin/tokenusage.js`,并有回归测试锁定(禁止再指向 `src/cli.js`)。
14
+ - 定时运行不落日志:`sync --from-scheduled` 只打印到 stdout,隐藏窗口下没有
15
+ 任何 trail,与 0.2.2 发布说明不符。现在所有自动风味运行(scheduled / hook /
16
+ retry / watch)统一追加到滚动日志 `~/.tokenusage/tracker/logs/sync.log`。
17
+ - 已注册过任务的机器:升级后重跑一次
18
+ `tokenusage init --yes --no-integrations --no-open` 即可修正任务入口。
19
+ - 品牌残留:init 启动横幅的 ASCII 与大标题仍是上游的 TOKEN TRACKER,
20
+ local-api 的兜底设备名也写 Token Tracker;按 AGENTS 命名约束统一为
21
+ Token Usage,并加回归测试防回潮。
22
+ - 移除上游遗留的匿名安装心跳(`POST /api/functions/tokenusage-telemetry`):
23
+ 本仓库契约与 Web 端都没有该路由,每次 sync 只会拿到 404 并进退避,还与启动屏
24
+ "只有 token 计数离开本机"的口径冲突。要统计安装量,先补服务端路由再恢复。
25
+ - 修正 local-api 遗留的本地服务 spawn 路径(`bin/tracker.js` 自 fork 起就不
26
+ 存在),并新增发包自检测试:bin 入口存在、spawn 路径可解析、无孤儿端点。
27
+ - `--help` 补齐 `init --no-integrations/--no-task` 与 `sync --interval`。
28
+ - 修正 `sync --watch --interval <ms>` 的非法值处理:README 承诺低于 1 分钟回退
29
+ 15 分钟,但此前参数会漏进 cmdSync,导致每轮以 `Unknown option: --interval`
30
+ 失败;现在该参数始终被剥离,并有单测覆盖。
31
+ - 署名与包元数据收敛:`description` 去掉 fork 字样;`THIRD_PARTY_NOTICES.md`
32
+ 只保留上游 TokenTracker 一节(其余条目是 Web 端资产,本仓库已不存在也不随包);
33
+ README 的来源说明收为一句,指向 `LICENSE` / `THIRD_PARTY_NOTICES.md`。
34
+
6
35
  ## 0.2.2
7
36
 
8
37
  新机初始化修复与采集口径修正。
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # tokenusage-cli
2
2
 
3
- 自托管 AI 编码 token 用量采集器,为 [token-usage](https://github.com/baiwumm/token-usage)(自托管仪表盘)上报数据。fork 自 [TokenTracker](https://github.com/xiufengsun/TokenTracker)(MIT,见 `LICENSE` 与 `THIRD_PARTY_NOTICES.md`),指向 token-usage 契约(`docs/cli-contract.md`)。
3
+ 自托管 AI 编码 token 用量采集器,为 [token-usage](https://github.com/baiwumm/token-usage)(自托管仪表盘)上报数据,指向其契约(`docs/cli-contract.md`)。代码来源与许可见 `LICENSE` 与 `THIRD_PARTY_NOTICES.md`。
4
4
 
5
5
  > 运行要求:Node ≥ 22.19(由上传依赖 undici 8 的引擎下限决定)。
6
6
 
@@ -103,6 +103,8 @@ CLI 未配对也能正常用,只是**降级为“只采集、不上报”**:
103
103
 
104
104
  **永不上传**:prompt / 助手正文 / 工具参数 / 命令输出 / diff / 会话标题 / 本地绝对路径 / resume 命令。测试(`test/session-upload.test.js`)用字段白名单锁定该边界。
105
105
 
106
+ CLI 也不发送匿名安装心跳:上游的 `tokenusage-telemetry` 端点在自托管后端从未实现,0.2.3 起已移除。可选的 Sentry 错误上报必须显式配置 DSN,并受 `TOKENUSAGE_NO_TELEMETRY` / `DO_NOT_TRACK` 约束。
107
+
106
108
  ## 数据目录
107
109
 
108
110
  `~/.tokenusage/`(`0700` 目录 + `0600` 文件):`tracker/config.json`(配对与运行配置)、上传队列(`queue.jsonl` + offset)、会话分析 sidecar、`session-upload-watermarks.json`(增量水位)、`tracker/logs/sync.log`(自动采集滚动日志)、暂停标志。与旧版 tokentracker CLI 的 `~/.tokentracker/` 互不干扰,迁移期两套 CLI 可在同一台机器共存。
@@ -1,6 +1,6 @@
1
1
  # Third-Party Notices
2
2
 
3
- This project includes third-party assets and code. The following notices apply.
3
+ `tokenusage-cli` 以 MIT 发布,许可正文与版权行见本包 [`LICENSE`](./LICENSE)。
4
4
 
5
5
  ## TokenTracker (upstream)
6
6
 
@@ -11,130 +11,6 @@ upstream repository and were then modified for the token-usage contract
11
11
  (`docs/cli-contract.md` in the repository root). The upstream MIT license text
12
12
  and copyright notice are preserved in this package's `LICENSE` file.
13
13
 
14
- ## RunCat menu bar cat frames
15
-
16
- The running-cat animation frames used by the macOS menu bar icon
17
- (`TokenTrackerBar/TokenTrackerBar/Assets.xcassets/RunnerCat0…4.imageset`)
18
- are from [menubar_runcat](https://github.com/Kyome22/menubar_runcat)
19
- by Takuto Nakamura (Kyome22).
20
-
21
- Copyright © 2019 Takuto Nakamura
22
-
23
- Licensed under the Apache License, Version 2.0 (the "License");
24
- you may not use these files except in compliance with the License.
25
- You may obtain a copy of the License at
26
-
27
- http://www.apache.org/licenses/LICENSE-2.0
28
-
29
- Unless required by applicable law or agreed to in writing, software
30
- distributed under the License is distributed on an "AS IS" BASIS,
31
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
32
- See the License for the specific language governing permissions and
33
- limitations under the License.
34
-
35
- ## Bot companion morphing engine
36
-
37
- The vector morphing engine behind the `bot` pet character and its menu bar icon
38
- (`dashboard/src/lib/bot/`, and the frame data generated from it by
39
- `scripts/gen-bot-frames.cjs`) is from [bloub](https://github.com/jeremy-prt/bloub)
40
- by Jérémy Perret, vendored unmodified at commit
41
- [`b4bb3c1b5f93`](https://github.com/jeremy-prt/bloub/tree/b4bb3c1b5f93c7b87a2e8d620f667c4093d97749).
42
-
43
- Note when re-vendoring: `dashboard/src/lib/bot/README.md` is ours, not upstream's, and
44
- `decor.ts` / `skins.ts` are listed in `scripts/ops/ui-hardcode-baseline.json`, so a
45
- refresh needs that file re-copied and the baseline regenerated.
46
-
47
- Copyright © 2026 Jérémy Perret
48
-
49
- Permission is hereby granted, free of charge, to any person obtaining a copy
50
- of this software and associated documentation files (the "Software"), to deal
51
- in the Software without restriction, including without limitation the rights
52
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
53
- copies of the Software, and to permit persons to whom the Software is
54
- furnished to do so, subject to the following conditions:
55
-
56
- The above copyright notice and this permission notice shall be included in all
57
- copies or substantial portions of the Software.
58
-
59
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
60
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
61
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
62
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
63
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
64
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
65
- SOFTWARE.
66
-
67
- ## Devin brand mark
68
-
69
- `dashboard/public/brand-logos/devin.svg` is a monochrome vector trace of the
70
- official Devin "nodes" mark published by Cognition at
71
- `https://app.devin.ai/assets/pwa/apple-touch-icon.png` (also
72
- `https://app.devin.ai/assets/pwa/pwa-icon-192.png`). The Devin name and logo
73
- are trademarks of Cognition; the mark is bundled solely to identify the Devin
74
- CLI source and subscription quota in the dashboard, recoloured to `currentColor` like the
75
- other provider marks.
76
-
77
- ## Hairline line figures
78
-
79
- The Cloud plan page uses [Hairline](https://github.com/lucasmarkes/hairline) v0.5.0 by Lucas Marques.
80
-
81
- MIT License
82
-
83
- Copyright (c) 2026 Lucas Marques
84
-
85
- Permission is hereby granted, free of charge, to any person obtaining a copy
86
- of this software and associated documentation files (the "Software"), to deal
87
- in the Software without restriction, including without limitation the rights
88
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
89
- copies of the Software, and to permit persons to whom the Software is
90
- furnished to do so, subject to the following conditions:
91
-
92
- The above copyright notice and this permission notice shall be included in all
93
- copies or substantial portions of the Software.
94
-
95
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
96
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
97
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
98
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
99
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
100
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
101
- SOFTWARE.
102
-
103
- ## React Bits ElectricLogo
104
-
105
- The dark Cloud plan artwork adapts the user-provided React Bits ElectricLogo by David Haz.
106
- Source: https://reactbits.dev/animations/electric-logo
107
- Vendored integration: dashboard/vendor/react-bits/.
108
-
109
- MIT + Commons Clause License Condition v1.0
110
-
111
- Copyright (c) 2026 David Haz
112
-
113
- Permission is hereby granted, free of charge, to any person obtaining a copy
114
- of this software and associated documentation files (the "Software"), to deal
115
- in the Software without restriction, including without limitation the rights
116
- to use, copy, modify, merge, publish, and distribute the Software **as part of an application, website, or product**, subject to the following conditions:
117
-
118
- The above copyright notice and this permission notice shall be included in all
119
- copies or substantial portions of the Software.
120
-
121
- ## Commons Clause Restriction
122
-
123
- You may use this Software, including for any commercial purpose, **so long as you do not sell, sublicense, or redistribute the components themselves-whether alone, in a bundle, or as a ported version.**
124
-
125
- ## No Warranty
126
-
127
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
128
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
129
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
130
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
131
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
132
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
133
- SOFTWARE.
134
-
135
-
136
- ## OGL
137
-
138
- The ElectricLogo renderer uses OGL 1.0.11 by Nathan Gordon.
139
- Source: https://github.com/oframe/ogl
140
- License: Unlicense (public domain dedication), as declared in the OGL package metadata.
14
+ 本包不含其他第三方资产:运行时依赖(`undici`、`@sentry/node` 等)的许可随
15
+ `node_modules` 一同分发;品牌图标、字体与定价快照属于 Web 端,登记在仓库根目录的
16
+ `THIRD_PARTY_NOTICES.md`。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.2.2",
4
- "description": "Self-hosted AI coding token usage collector for token-usage (forked from TokenTracker, MIT).",
3
+ "version": "0.2.3",
4
+ "description": "Self-hosted AI coding token usage collector for the Token Usage dashboard.",
5
5
  "keywords": [
6
6
  "token-usage",
7
7
  "token",
package/src/cli.js CHANGED
@@ -79,22 +79,29 @@ async function run(argv) {
79
79
  }
80
80
  }
81
81
 
82
- // --watch: keep the process alive and re-run sync on an interval. Each pass
83
- // reuses the session-analytics sidecar cache and the upload watermarks, so a
84
- // pass with nothing new is cheap (a directory signature stat + a no-op).
85
- // The trigger tag rides context into cmdSync so run telemetry can report
86
- // `watch` runs distinctly from scheduled/manual/notify ones (§2.11).
87
- async function watchSync(rest) {
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.
86
+ function resolveWatchInterval(rest) {
88
87
  const args = rest.filter((arg) => arg !== "--watch");
89
88
  const intervalIndex = args.indexOf("--interval");
90
89
  let intervalMs = 15 * 60_000;
91
90
  if (intervalIndex >= 0) {
92
91
  const value = Number(args[intervalIndex + 1]);
93
- if (Number.isFinite(value) && value >= 60_000) {
94
- intervalMs = value;
95
- args.splice(intervalIndex, 2);
96
- }
92
+ if (Number.isFinite(value) && value >= 60_000) intervalMs = value;
93
+ args.splice(intervalIndex, 2);
97
94
  }
95
+ return { args, intervalMs };
96
+ }
97
+
98
+ // --watch: keep the process alive and re-run sync on an interval. Each pass
99
+ // reuses the session-analytics sidecar cache and the upload watermarks, so a
100
+ // pass with nothing new is cheap (a directory signature stat + a no-op).
101
+ // The trigger tag rides context into cmdSync so run telemetry can report
102
+ // `watch` runs distinctly from scheduled/manual/notify ones (§2.11).
103
+ async function watchSync(rest) {
104
+ const { args, intervalMs } = resolveWatchInterval(rest);
98
105
 
99
106
  process.stdout.write(`tokenusage sync --watch: every ${Math.round(intervalMs / 60_000)} min (Ctrl+C to stop)\n`);
100
107
  for (;;) {
@@ -118,7 +125,8 @@ function printHelp() {
118
125
  "Usage:",
119
126
  " tokenusage -v, --version Show version info",
120
127
  " tokenusage [--debug] init [--yes] [--dry-run] [--no-open] [--link-code <code>] [--run-report=on|off]",
121
- " tokenusage [--debug] sync [--auto] [--drain] [--no-sessions] [--watch]",
128
+ " [--no-integrations] [--no-task]",
129
+ " tokenusage [--debug] sync [--auto] [--drain] [--no-sessions] [--watch] [--interval <ms>]",
122
130
  " tokenusage [--debug] status [--probe-keychain] [--probe-keychain-details]",
123
131
  " tokenusage [--debug] pause | resume",
124
132
  " tokenusage [--debug] diagnostics [--out diagnostics.json]",
@@ -143,4 +151,4 @@ function printHelp() {
143
151
  );
144
152
  }
145
153
 
146
- module.exports = { run };
154
+ module.exports = { run, resolveWatchInterval };
@@ -105,12 +105,12 @@ const ASCII_LOGO = [
105
105
  " ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║",
106
106
  " ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║",
107
107
  " ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝",
108
- " ████████╗██████╗ █████╗ ██████╗██╗ ██╗███████╗██████╗",
109
- " ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗",
110
- " ██║ ██████╔╝███████║██║ █████╔╝ █████╗ ██████╔╝",
111
- " ██║ ██╔══██╗██╔══██║██║ ██╔═██╗ ██╔══╝ ██╔══██╗",
112
- " ██║ ██║ ██║██║ ██║╚██████╗██║ ██╗███████╗██║ ██║",
113
- " ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝",
108
+ " ██╗ ██╗███████╗ █████╗ ██████╗ ███████╗",
109
+ " ██║ ██║██╔════╝██╔══██╗██╔════╝ ██╔════╝",
110
+ " ██║ ██║███████╗███████║██║ ███╗█████╗",
111
+ " ██║ ██║╚════██║██╔══██║██║ ██║██╔══╝",
112
+ " ╚██████╔╝███████║██║ ██║╚██████╔╝███████╗",
113
+ " ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝",
114
114
  ].join("\n");
115
115
 
116
116
  const DIVIDER = "----------------------------------------------";
@@ -290,7 +290,7 @@ function renderWelcome(dashboardUrl = DEFAULT_DASHBOARD_URL) {
290
290
  [
291
291
  ASCII_LOGO,
292
292
  "",
293
- `${BOLD}Token Tracker${RESET} ${color("Local-first usage across " + providerCount + " AI CLIs", DIM)}`,
293
+ `${BOLD}Token Usage${RESET} ${color("Local-first usage across " + providerCount + " AI CLIs", DIM)}`,
294
294
  DIVIDER,
295
295
  `${CYAN}Nothing leaves your machine — token counts only, never prompts or responses.${RESET}`,
296
296
  DIVIDER,
@@ -453,10 +453,9 @@ async function runSetup({
453
453
  detail: "Skipped (--no-task); auto syncs stay manual",
454
454
  });
455
455
  } else {
456
- const taskOutcome = registerWindowsScheduledTask({
457
- binDir,
458
- cliJs: path.resolve(__dirname, "..", "cli.js"),
459
- });
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 });
460
459
  summary.push({
461
460
  label: "Scheduled task",
462
461
  status: taskOutcome.registered ? "installed" : "skipped",
@@ -174,7 +174,6 @@ const AUTO_UPLOAD_CONFIG = {
174
174
  maxBatchesLarge: 100,
175
175
  };
176
176
  const UPLOAD_BUDGET_MS = 90_000;
177
- const { maybeSendHeartbeat } = require("../lib/telemetry");
178
177
  const {
179
178
  isCursorInstalled,
180
179
  extractCursorSessionToken,
@@ -638,7 +637,10 @@ async function cmdSync(argv, context = {}) {
638
637
  // try/finally so an auxiliary diagnostic never strands the sync lock.
639
638
  await clearSyncSkip(trackerDir);
640
639
  progress = !opts.auto ? createProgress({ stream: process.stdout }) : null;
641
- if (opts.auto) {
640
+ // Every auto-flavored run (scheduled task, hooks, retry, watch) self-logs:
641
+ // a hidden TTY-less task has no other trail, so --from-scheduled must not
642
+ // fall through to the interactive stdout summary below.
643
+ if (autoishSync) {
642
644
  autoLog("Auto sync started — scanning local provider sessions…");
643
645
  }
644
646
  const configPath = path.join(trackerDir, "config.json");
@@ -3878,7 +3880,7 @@ async function cmdSync(argv, context = {}) {
3878
3880
  }
3879
3881
  }
3880
3882
 
3881
- if (!opts.auto) {
3883
+ if (!autoishSync) {
3882
3884
  const codexRecordOnlyWarning = formatRecordOnlyWarning(countRecordOnlyFiles(cursors));
3883
3885
  process.stdout.write(
3884
3886
  [
@@ -3907,13 +3909,6 @@ async function cmdSync(argv, context = {}) {
3907
3909
  );
3908
3910
  }
3909
3911
 
3910
- // Anonymous daily heartbeat (shared 24h throttle with serve — see
3911
- // src/lib/telemetry.js). Awaited because hook-spawned sync processes exit
3912
- // right after this function returns, which would kill an in-flight
3913
- // request; the throttle makes it a network no-op on all but the first
3914
- // sync of the day, and maybeSendHeartbeat never throws.
3915
- await maybeSendHeartbeat({ trackerDir });
3916
-
3917
3912
  // §2.11 run record (empty runs included) — the last thing a run does,
3918
3913
  // strictly best-effort: failures only reach the local log, never the
3919
3914
  // ingest outcome above or this process's exit code.
@@ -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() {
@@ -1424,7 +1424,7 @@ function createLocalApiHandler({ queuePath, serverVersion = null, trackerDataDir
1424
1424
  // 必须和 dashboard/src/lib/cloud-sync.ts 使用同一个设备身份。
1425
1425
  // 旧云端设备按 (platform, device_name) 认领;如果这里发明
1426
1426
  // local-sync 身份,会多出一个 active device,账户视图会把历史求和两次。
1427
- device_name: getSystemDeviceName() || `Token Tracker (dashboard) #${machineId.slice(0, 8)}`,
1427
+ device_name: getSystemDeviceName() || `Token Usage (dashboard) #${machineId.slice(0, 8)}`,
1428
1428
  platform: dashboardPlatform,
1429
1429
  machine_id: machineId,
1430
1430
  }),
@@ -3158,23 +3158,6 @@ function createLocalApiHandler({ queuePath, serverVersion = null, trackerDataDir
3158
3158
  return true;
3159
3159
  }
3160
3160
 
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
3161
  // --- machine-id (stable per-machine device identity for cloud sync) ---
3179
3162
  // The dashboard reads this before issuing a cloud device token so the
3180
3163
  // device_name keys on the MACHINE, not the browser — see
@@ -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.
@@ -31,6 +31,13 @@ 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
42
  * The hidden-runner wrapper. Paths are quoted individually and cmd is NOT
36
43
  * involved: wscript runs node directly, so the cmd /c outer-quote-stripping
@@ -53,7 +60,7 @@ function buildHiddenRunnerVbs({ nodeExe, cliJs }) {
53
60
  ].join("\n");
54
61
  }
55
62
 
56
- function writeHiddenRunner({ binDir, nodeExe = process.execPath, cliJs }) {
63
+ function writeHiddenRunner({ binDir, nodeExe = process.execPath, cliJs = cliEntryPath() }) {
57
64
  fs.mkdirSync(binDir, { recursive: true });
58
65
  const vbsPath = vbsPathFor(binDir);
59
66
  fs.writeFileSync(vbsPath, buildHiddenRunnerVbs({ nodeExe, cliJs }), { mode: 0o600 });
@@ -64,7 +71,7 @@ function writeHiddenRunner({ binDir, nodeExe = process.execPath, cliJs }) {
64
71
  * Register (idempotently — /F overwrites) the hourly hidden task. Returns
65
72
  * {registered: true} or {registered: false, reason} instead of throwing.
66
73
  */
67
- function registerWindowsScheduledTask({ binDir, cliJs, nodeExe = process.execPath }) {
74
+ function registerWindowsScheduledTask({ binDir, cliJs = cliEntryPath(), nodeExe = process.execPath }) {
68
75
  if (!isWindows()) return { registered: false, reason: "not_windows" };
69
76
  try {
70
77
  const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs });
@@ -139,6 +146,7 @@ module.exports = {
139
146
  VBS_FILE,
140
147
  isWindows,
141
148
  vbsPathFor,
149
+ cliEntryPath,
142
150
  buildHiddenRunnerVbs,
143
151
  writeHiddenRunner,
144
152
  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 };
@@ -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,32 @@
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("a sub-floor or missing --interval falls back to 15 min but is still removed", () => {
20
+ for (const rest of [["--watch", "--interval", "1000"], ["--interval", "0"], ["--watch", "--interval"], ["--interval", "abc"]]) {
21
+ const parsed = resolveWatchInterval(rest);
22
+ assert.equal(parsed.intervalMs, FALLBACK_MS, `intervalMs for ${JSON.stringify(rest)}`);
23
+ assert.deepEqual(parsed.args, [], `leftover args for ${JSON.stringify(rest)}`);
24
+ }
25
+ });
26
+
27
+ test("unrelated sync flags survive untouched", () => {
28
+ assert.deepEqual(resolveWatchInterval(["--watch", "--drain", "--no-sessions"]), {
29
+ args: ["--drain", "--no-sessions"],
30
+ intervalMs: FALLBACK_MS,
31
+ });
32
+ });
@@ -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,28 @@ 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
176
  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/);
177
+ assert.match(vbs, /""C:\\Program Files\\nodejs\\node\.exe"" ""C:\\Users\\me\\AppData\\tokenusage-cli\\bin\\tokenusage\.js"" sync --from-scheduled/);
177
178
  // Hidden window (0) + wait for completion (True).
178
179
  assert.match(vbs, /, 0, True\)/);
179
180
  // The task name stays stable — pause/resume and uninstall toggle by name.
180
181
  assert.equal(TASK_NAME, "TokenUsageSync");
181
182
  });
182
183
 
184
+ // 0.2.2 regression: init registered src/cli.js instead of the bin entry. That
185
+ // file only exports run(), so the hidden task exited 0 within ~0.1 s without
186
+ // collecting or logging anything — a silent, permanently "successful" task.
187
+ test("scheduled task launches the CLI entry, never the inert src/cli.js", () => {
188
+ const entry = cliEntryPath().replace(/\\/g, "/");
189
+ assert.match(entry, /\/bin\/tokenusage\.js$/);
190
+ assert.ok(fs.existsSync(cliEntryPath()), "the registered entry must exist in the package");
191
+
192
+ const vbs = buildHiddenRunnerVbs({ nodeExe: "node.exe", cliJs: cliEntryPath() });
193
+ assert.doesNotMatch(vbs, /src[\\/]cli\.js/);
194
+ });
195
+
183
196
  test("--from-scheduled reports as scheduled, unlike a plain manual run", () => {
184
197
  assert.equal(resolveSyncTrigger({ fromScheduled: true }), "scheduled");
185
198
  // The scheduled task must upload on default installs, so --from-scheduled
@@ -0,0 +1,54 @@
1
+ // Packaging guards: what `npm pack` ships must actually boot. 0.1.x shipped
2
+ // without bin/tracker.js (installer still pointed at the pre-fork name) and
3
+ // local-api's dormant local server still resolved that missing path. The
4
+ // upstream install-count heartbeat was also never ported to this backend.
5
+
6
+ const assert = require("node:assert/strict");
7
+ const fs = require("node:fs");
8
+ const path = require("node:path");
9
+ const { test } = require("node:test");
10
+
11
+ const PACKAGE_ROOT = path.join(__dirname, "..");
12
+ const SRC = path.join(PACKAGE_ROOT, "src");
13
+
14
+ function readSource(...segments) {
15
+ return fs.readFileSync(path.join(PACKAGE_ROOT, ...segments), "utf8");
16
+ }
17
+
18
+ test("package bin points at the CLI entry that actually ships", () => {
19
+ const pkg = JSON.parse(readSource("package.json"));
20
+ assert.equal(pkg.bin.tokenusage, "bin/tokenusage.js");
21
+ assert.ok(
22
+ fs.existsSync(path.join(PACKAGE_ROOT, pkg.bin.tokenusage)),
23
+ "the declared bin file must exist in the tarball",
24
+ );
25
+ });
26
+
27
+ test("local-api spawns the package bin entry, not the missing bin/tracker.js", () => {
28
+ const source = readSource("src", "lib", "local-api.js");
29
+ assert.ok(!source.includes('"../../bin/tracker.js"'), "bin/tracker.js never existed after the fork");
30
+ const match = source.match(/TRACKER_BIN = path\.resolve\(__dirname, "([^"]+)"\)/);
31
+ assert.ok(match, "TRACKER_BIN must stay a single resolved path");
32
+ assert.ok(
33
+ fs.existsSync(path.resolve(path.join(SRC, "lib"), match[1])),
34
+ `local-api spawn target does not resolve: ${match[1]}`,
35
+ );
36
+ });
37
+
38
+ test("telemetry opt-out flags still gate the optional Sentry reporting", () => {
39
+ const { isTelemetryDisabled } = require("../src/lib/telemetry-pref");
40
+ assert.equal(isTelemetryDisabled({ env: {}, config: {} }), false);
41
+ assert.equal(isTelemetryDisabled({ env: { TOKENUSAGE_NO_TELEMETRY: "1" }, config: {} }), true);
42
+ assert.equal(isTelemetryDisabled({ env: { DO_NOT_TRACK: "true" }, config: {} }), true);
43
+ assert.equal(isTelemetryDisabled({ env: {}, config: { telemetry: false } }), true);
44
+ });
45
+
46
+ test("the unported install heartbeat stays removed", () => {
47
+ assert.ok(
48
+ !fs.existsSync(path.join(SRC, "lib", "telemetry.js")),
49
+ "the backend has no /api/functions/tokenusage-telemetry route, so nothing may post to it",
50
+ );
51
+ const sync = readSource("src", "commands", "sync.js");
52
+ assert.ok(!sync.includes("maybeSendHeartbeat"));
53
+ assert.ok(!sync.includes('require("../lib/telemetry")'));
54
+ });
@@ -1,193 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Anonymous daily heartbeat for counting active installs.
5
- *
6
- * Privacy contract (documented in README "Privacy" section — keep in sync):
7
- * the payload carries exactly four fields — a one-way sha256 hash of the
8
- * machine id, the app version, `process.platform`, and the app shell
9
- * (cli / macos / windows / linux). No token counts, no model names, no usernames,
10
- * no paths. Opt out with TOKENUSAGE_NO_TELEMETRY=1, the DO_NOT_TRACK
11
- * standard, or `"telemetry": false` in config.json.
12
- */
13
-
14
- const path = require("node:path");
15
- const crypto = require("node:crypto");
16
-
17
- const pkg = require("../../package.json");
18
- const { readJson, writeJson } = require("./fs");
19
- const { getOrCreateMachineId } = require("./machine-id");
20
- const { resolveRuntimeConfig } = require("./runtime-config");
21
- const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
22
- const {
23
- decideAutoUpload,
24
- recordUploadSuccess,
25
- recordUploadFailure,
26
- } = require("./upload-throttle");
27
-
28
- const HEARTBEAT_FUNCTION_SLUG = "tokenusage-telemetry";
29
- const HEARTBEAT_STATE_FILE = "telemetry.heartbeat.json";
30
- const HEARTBEAT_INTERVAL_MS = 24 * 60 * 60 * 1000;
31
- // The hash namespace is versioned so the anonymous id can be rotated fleet-wide
32
- // by bumping the string. sha256(namespace + machineId) cannot be joined back to
33
- // the cloud device rows (those store the machineId itself).
34
- const MACHINE_HASH_NAMESPACE = "tokenusage-telemetry-v1:";
35
- // Generous because some networks need 3-4s just for the TLS handshake to the
36
- // cloud host; sync awaits this at most once per day so the worst-case stall
37
- // is bounded and rare.
38
- const DEFAULT_TIMEOUT_MS = 10_000;
39
- const VALID_SHELLS = new Set(["cli", "macos", "windows", "linux"]);
40
-
41
- const THROTTLE_CONFIG = {
42
- intervalMs: HEARTBEAT_INTERVAL_MS,
43
- jitterMsMax: 60_000,
44
- backoffInitialMs: 60 * 60_000, // failures retry hourly at most
45
- backoffMaxMs: HEARTBEAT_INTERVAL_MS,
46
- };
47
-
48
- function isTelemetryDisabled({ env = process.env, config = {} } = {}) {
49
- if (isTruthyFlag(env?.TOKENUSAGE_NO_TELEMETRY)) return true;
50
- if (isTruthyFlag(env?.DO_NOT_TRACK)) return true;
51
- if (config && config.telemetry === false) return true;
52
- return false;
53
- }
54
-
55
- function isTruthyFlag(value) {
56
- if (typeof value !== "string") return false;
57
- const v = value.trim().toLowerCase();
58
- return v === "1" || v === "true";
59
- }
60
-
61
- function hashMachineId(machineId) {
62
- return crypto
63
- .createHash("sha256")
64
- .update(`${MACHINE_HASH_NAMESPACE}${machineId}`)
65
- .digest("hex");
66
- }
67
-
68
- function resolveShell(env = process.env) {
69
- const raw = typeof env?.TOKENUSAGE_APP_SHELL === "string"
70
- ? env.TOKENUSAGE_APP_SHELL.trim().toLowerCase()
71
- : "";
72
- return VALID_SHELLS.has(raw) ? raw : "cli";
73
- }
74
-
75
- function buildHeartbeatPayload({ machineId, version = pkg.version, platform = process.platform, env = process.env }) {
76
- return {
77
- machine_hash: hashMachineId(machineId),
78
- app_version: String(version || "").slice(0, 32),
79
- platform: String(platform || "unknown").slice(0, 16),
80
- shell: resolveShell(env),
81
- };
82
- }
83
-
84
- /**
85
- * Send the daily heartbeat if allowed. Never throws; every failure path is a
86
- * silent no-op so serve/sync flow is never affected. Returns a small status
87
- * object for tests and debug logging.
88
- */
89
- async function maybeSendHeartbeat({
90
- trackerDir,
91
- fetchImpl = fetch,
92
- nowMs = Date.now(),
93
- env = process.env,
94
- timeoutMs = DEFAULT_TIMEOUT_MS,
95
- version,
96
- } = {}) {
97
- try {
98
- if (!trackerDir) return { sent: false, reason: "no-tracker-dir" };
99
-
100
- // Never phone home from the node test runner: many tests drive cmdSync /
101
- // cmdServe directly from sandboxed temp homes, and their fresh throttle
102
- // state would let a real POST through to production on every run. Tests
103
- // that exercise this module inject their own env without this marker.
104
- if (env?.NODE_TEST_CONTEXT !== undefined) {
105
- return { sent: false, reason: "test-env" };
106
- }
107
-
108
- const configPath = path.join(trackerDir, "config.json");
109
- const config = (await readJson(configPath)) || {};
110
- if (isTelemetryDisabled({ env, config })) {
111
- return { sent: false, reason: "opt-out" };
112
- }
113
-
114
- const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
115
- const state = await readJson(statePath);
116
- const decision = decideAutoUpload({
117
- nowMs,
118
- pendingBytes: 1, // heartbeats always have "one ping pending"
119
- state,
120
- config: THROTTLE_CONFIG,
121
- });
122
- if (!decision.allowed) {
123
- return { sent: false, reason: "throttled", blockedUntilMs: decision.blockedUntilMs };
124
- }
125
-
126
- const machineId = getOrCreateMachineId(path.join(trackerDir, "queue.jsonl"));
127
- if (!machineId) return { sent: false, reason: "no-machine-id" };
128
-
129
- const runtime = resolveRuntimeConfig({ config, env });
130
- const payload = buildHeartbeatPayload({ machineId, version, env });
131
-
132
- const controller = new AbortController();
133
- const timer = setTimeout(() => controller.abort(), timeoutMs);
134
- let response;
135
- try {
136
- response = await fetchFunctionResponse(functionUrlFor(runtime.baseUrl, HEARTBEAT_FUNCTION_SLUG), {
137
- method: "POST",
138
- headers: {
139
- "Content-Type": "application/json",
140
- apikey: runtime.anonKey,
141
- },
142
- body: JSON.stringify(payload),
143
- signal: controller.signal,
144
- }, fetchImpl);
145
- } finally {
146
- clearTimeout(timer);
147
- }
148
-
149
- if (!response || !response.ok) {
150
- const failedState = recordUploadFailure({
151
- nowMs,
152
- state,
153
- error: { message: `heartbeat http ${response?.status || "error"}`, status: response?.status },
154
- config: THROTTLE_CONFIG,
155
- });
156
- await writeJson(statePath, failedState);
157
- return { sent: false, reason: "http-error", status: response?.status };
158
- }
159
-
160
- const nextState = recordUploadSuccess({ nowMs, state, config: THROTTLE_CONFIG });
161
- await writeJson(statePath, nextState);
162
- return { sent: true, reason: "sent" };
163
- } catch (e) {
164
- // Includes abort/network errors: record backoff if we can, stay silent.
165
- try {
166
- const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
167
- const state = await readJson(statePath);
168
- await writeJson(
169
- statePath,
170
- recordUploadFailure({
171
- nowMs,
172
- state,
173
- error: { message: String(e?.message || e) },
174
- config: THROTTLE_CONFIG,
175
- }),
176
- );
177
- } catch {
178
- // Even state persistence failed — nothing else to do.
179
- }
180
- return { sent: false, reason: "error" };
181
- }
182
- }
183
-
184
- module.exports = {
185
- HEARTBEAT_FUNCTION_SLUG,
186
- HEARTBEAT_STATE_FILE,
187
- HEARTBEAT_INTERVAL_MS,
188
- isTelemetryDisabled,
189
- hashMachineId,
190
- resolveShell,
191
- buildHeartbeatPayload,
192
- maybeSendHeartbeat,
193
- };