tokenusage-cli 0.2.5 → 0.2.6

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,26 @@
3
3
  本包(`tokenusage-cli`)的用户可见变更记录。发版时在顶部新增一节,
4
4
  `## <版本号>` 行会被 release workflow 取作 GitHub Release 正文。
5
5
 
6
+ ## 0.2.6
7
+
8
+ 移除从未接线的错误上报 SDK,安装体积与运行时副本明显变小;采集行为不变。
9
+
10
+ - 删除 `@sentry/node` 与 `src/lib/sentry.js`、`src/lib/telemetry-pref.js`:
11
+ CLI 只在启动时 init 了 Sentry,`captureException` 没有任何调用点,实际从不上报;
12
+ 但它在运行时副本里占 44 MB(67.5 MB 的约 65%),全局安装还带入
13
+ `@sentry/bundler-plugins` 的构建期依赖链(安装总量 93.1 MB 中约 59 MB)。
14
+ 移除后运行时副本 22.9 MB(实测 462 个文件)、干净 prefix 安装 23 MB
15
+ (此前 93.1 MB),且不再有第三方上报入口。
16
+ - `bin/tokenusage.js` 未捕获异常的兜底里还留着一个 `require('../src/lib/sentry')`
17
+ (包在 try/catch 里,删模块后永不生效的残留);一并删除,守卫测试改为同时扫描
18
+ `src/` 与 `bin/`。
19
+ - README 隐私边界同步:CLI 不做匿名心跳、也不做任何第三方错误上报。
20
+ - `THIRD_PARTY_NOTICES.md` 的运行时依赖示例去掉 `@sentry/node`。
21
+ - 新增 `test/packaging.test.js` 守卫:`@sentry/*` 不得重新出现在依赖或源码中;
22
+ 运行时副本回归测试改用 `yauzl` 的传递依赖 `pend` 验证扁平闭包复制。
23
+ - 未随本版改动:macOS/Linux 原生调度、`init` 逐工具集成选择(见
24
+ `docs/cli-release.md` §四,等真机验证/形态确认后再做)。
25
+
6
26
  ## 0.2.5
7
27
 
8
28
  0.2.4 验收后的小修:去掉安装警告、修正初始化重复文案,并补 Windows CI。
package/README.md CHANGED
@@ -103,7 +103,7 @@ 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` 约束。
106
+ CLI 不发送匿名安装心跳,也不做任何第三方错误上报:上游的 `tokenusage-telemetry` 端点在自托管后端从未实现(0.2.3 移除);从未接线的 Sentry SDK 也已在 0.2.6 删除。除你自己配对的实例外,CLI 不向任何第三方发送数据。
107
107
 
108
108
  ## 数据目录
109
109
 
@@ -11,6 +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
- 本包不含其他第三方资产:运行时依赖(`undici`、`@sentry/node` 等)的许可随
14
+ 本包不含其他第三方资产:运行时依赖(如 `undici`)的许可随
15
15
  `node_modules` 一同分发;品牌图标、字体与定价快照属于 Web 端,登记在仓库根目录的
16
16
  `THIRD_PARTY_NOTICES.md`。
package/bin/tokenusage.js CHANGED
@@ -43,12 +43,6 @@ if (applyResult && applyResult.unprotected === true) {
43
43
  }
44
44
 
45
45
  run(argv).catch((err) => {
46
- try {
47
- const { captureException } = require('../src/lib/sentry');
48
- captureException(err, { tags: { surface: 'cli-unhandled' } });
49
- } catch {
50
- /* ignore */
51
- }
52
46
  console.error(err?.stack || String(err));
53
47
  if (debug) {
54
48
  if (typeof err?.status === 'number') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Self-hosted AI coding token usage collector for the Token Usage dashboard.",
5
5
  "keywords": [
6
6
  "token-usage",
@@ -43,7 +43,6 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@journeyapps/wa-sqlite": "2.0.7",
46
- "@sentry/node": "^11.8.0",
47
46
  "smol-toml": "^1.9.0",
48
47
  "undici": "8.12.2",
49
48
  "yauzl": "^3.4.0"
package/src/cli.js CHANGED
@@ -9,16 +9,6 @@ const { cmdSessions } = require("./commands/sessions");
9
9
  const { cmdPause, cmdResume } = require("./commands/pause");
10
10
 
11
11
  async function run(argv) {
12
- // Best-effort Sentry init (no-op without DSN / when telemetry opted out).
13
- try {
14
- const { initSentry } = require("./lib/sentry");
15
- const { resolveTrackerPaths } = require("./lib/tracker-paths");
16
- const { trackerDir } = await resolveTrackerPaths().catch(() => ({ trackerDir: null }));
17
- await initSentry({ trackerDir });
18
- } catch {
19
- /* never block CLI startup on telemetry */
20
- }
21
-
22
12
  const [command, ...rest] = argv;
23
13
 
24
14
  // No args → short help (the upstream local dashboard was removed in this
@@ -2474,8 +2474,6 @@ function probeRuntimeCopy(appDir) {
2474
2474
  "if (missing.length > 0) { console.error(missing.join(',')); process.exit(3); }",
2475
2475
  ].join("\n");
2476
2476
  const env = { ...process.env };
2477
- // The probe must not trigger telemetry or hook spawning.
2478
- env.TOKENUSAGE_NO_TELEMETRY = "1";
2479
2477
  try {
2480
2478
  const probe = cp.spawnSync(process.execPath, ["-e", script], {
2481
2479
  cwd: appDir,
@@ -234,8 +234,8 @@ test("init's runtime copy works from the published layout (bin/tokenusage.js)",
234
234
  "declared dependency copied as a real directory",
235
235
  );
236
236
  assert.ok(
237
- fs.existsSync(path.join(appDir, "node_modules", "@sentry", "core")),
238
- "transitive dependency of @sentry/node copied too (flattened closure)",
237
+ fs.existsSync(path.join(appDir, "node_modules", "pend")),
238
+ "transitive dependency of yauzl copied too (flattened closure)",
239
239
  );
240
240
  // The marker is what every spawn point probes: without it hooks fall back
241
241
  // to the installed CLI instead of spawning a half copy.
@@ -10,6 +10,7 @@ const { test } = require("node:test");
10
10
 
11
11
  const PACKAGE_ROOT = path.join(__dirname, "..");
12
12
  const SRC = path.join(PACKAGE_ROOT, "src");
13
+ const BIN = path.join(PACKAGE_ROOT, "bin");
13
14
 
14
15
  function readSource(...segments) {
15
16
  return fs.readFileSync(path.join(PACKAGE_ROOT, ...segments), "utf8");
@@ -35,12 +36,35 @@ test("local-api spawns the package bin entry, not the missing bin/tracker.js", (
35
36
  );
36
37
  });
37
38
 
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);
39
+ test("the unused Sentry error-reporting SDK stays out of the package", () => {
40
+ // 0.2.6 removed @sentry/node: it was only initialized (captureException had no
41
+ // call sites) and shipped 44 MB into the runtime copy plus a build-time
42
+ // bundler-plugin chain into every npm install. Keep it out unless the
43
+ // reporting path is actually wired and budgeted again.
44
+ const pkg = JSON.parse(readSource("package.json"));
45
+ const declared = { ...(pkg.dependencies || {}), ...(pkg.optionalDependencies || {}) };
46
+ assert.ok(
47
+ !Object.keys(declared).some((name) => name === "@sentry/node" || name.startsWith("@sentry/")),
48
+ "@sentry/* must not be a declared dependency",
49
+ );
50
+ assert.ok(
51
+ !fs.existsSync(path.join(SRC, "lib", "sentry.js")),
52
+ "the inert sentry bootstrap must stay deleted",
53
+ );
54
+ assert.ok(
55
+ !fs.existsSync(path.join(SRC, "lib", "telemetry-pref.js")),
56
+ "the opt-out helper only existed to gate Sentry",
57
+ );
58
+ const roots = [SRC, BIN];
59
+ for (const root of roots) {
60
+ const sourceFiles = fs
61
+ .readdirSync(root, { recursive: true })
62
+ .filter((rel) => String(rel).endsWith(".js"));
63
+ for (const rel of sourceFiles) {
64
+ const source = fs.readFileSync(path.join(root, String(rel)), "utf8");
65
+ assert.ok(!source.includes("@sentry/"), `${rel} must not require the removed SDK`);
66
+ }
67
+ }
44
68
  });
45
69
 
46
70
  test("the unported install heartbeat stays removed", () => {
package/src/lib/sentry.js DELETED
@@ -1,231 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Optional Sentry error reporting for the Node CLI / EmbeddedServer runtime.
5
- *
6
- * Privacy contract (keep in sync with README "隐私边界"):
7
- * - Off unless TOKENUSAGE_SENTRY_DSN (or SENTRY_DSN) is set.
8
- * - Honors the shared telemetry opt-out
9
- * (TOKENUSAGE_NO_TELEMETRY / DO_NOT_TRACK / config.json `"telemetry": false`).
10
- * - Fail-closed in the node test runner.
11
- * - Never intended to carry prompts, code, or provider secrets; beforeSend
12
- * scrubs common secret patterns from event payloads.
13
- */
14
-
15
- const path = require("node:path");
16
- const pkg = require("../../package.json");
17
- const { readJson } = require("./fs");
18
- const { isTelemetryDisabled } = require("./telemetry-pref");
19
-
20
- const SECRET_PATTERN =
21
- /(?:api[_-]?key|access[_-]?token|refresh[_-]?token|cookie|secret|password|dsn)[=:\s]+["']?[^\s"'\\]{8,}/gi;
22
- const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi;
23
- const JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9._-]{10,}\.[A-Za-z0-9._-]{10,}\b/g;
24
-
25
- let initialized = false;
26
-
27
- function resolveDsn(env = process.env) {
28
- const raw = env?.TOKENUSAGE_SENTRY_DSN || env?.SENTRY_DSN || "";
29
- return typeof raw === "string" ? raw.trim() : "";
30
- }
31
-
32
- function resolveEnvironment(env = process.env) {
33
- const raw = typeof env?.TOKENUSAGE_SENTRY_ENVIRONMENT === "string"
34
- ? env.TOKENUSAGE_SENTRY_ENVIRONMENT.trim()
35
- : "";
36
- if (raw) return raw;
37
- if (env?.NODE_ENV === "production") return "production";
38
- return "development";
39
- }
40
-
41
- function resolveShell(env = process.env) {
42
- const raw = typeof env?.TOKENUSAGE_APP_SHELL === "string"
43
- ? env.TOKENUSAGE_APP_SHELL.trim().toLowerCase()
44
- : "";
45
- if (raw === "macos" || raw === "windows" || raw === "linux" || raw === "cli") return raw;
46
- return "cli";
47
- }
48
-
49
- function scrubString(value) {
50
- if (typeof value !== "string" || !value) return value;
51
- return value
52
- .replace(BEARER_PATTERN, "Bearer [Filtered]")
53
- .replace(JWT_PATTERN, "[Filtered]")
54
- .replace(SECRET_PATTERN, "[Filtered]");
55
- }
56
-
57
- function scrubValue(value, depth = 0) {
58
- if (depth > 6 || value == null) return value;
59
- if (typeof value === "string") return scrubString(value);
60
- if (Array.isArray(value)) return value.map((item) => scrubValue(item, depth + 1));
61
- if (typeof value === "object") {
62
- const out = {};
63
- for (const [key, nested] of Object.entries(value)) {
64
- const lower = key.toLowerCase();
65
- if (
66
- lower.includes("authorization") ||
67
- lower.includes("cookie") ||
68
- lower.includes("password") ||
69
- lower.includes("secret") ||
70
- lower.includes("token") ||
71
- lower.includes("api_key") ||
72
- lower.includes("apikey")
73
- ) {
74
- out[key] = "[Filtered]";
75
- } else {
76
- out[key] = scrubValue(nested, depth + 1);
77
- }
78
- }
79
- return out;
80
- }
81
- return value;
82
- }
83
-
84
- function truncateMaybe(value, max = 240) {
85
- if (typeof value !== "string") return value;
86
- if (value.length <= max) return value;
87
- return `${value.slice(0, max)}…[truncated]`;
88
- }
89
-
90
- function scrubEvent(event) {
91
- if (!event || typeof event !== "object") return event;
92
- const next = { ...event };
93
- if (next.message) next.message = truncateMaybe(scrubString(next.message));
94
- if (next.extra) next.extra = scrubValue(next.extra);
95
- if (next.contexts) next.contexts = scrubValue(next.contexts);
96
- if (next.request) next.request = scrubValue(next.request);
97
- // Console breadcrumbs can carry parser / JSON.parse excerpts of local logs
98
- // (prompt text). Drop them entirely; keep only non-console crumbs and scrub.
99
- if (Array.isArray(next.breadcrumbs)) {
100
- next.breadcrumbs = next.breadcrumbs
101
- .filter((crumb) => crumb && crumb.category !== "console")
102
- .map((crumb) => scrubValue(crumb));
103
- }
104
- if (next.exception?.values) {
105
- next.exception = {
106
- ...next.exception,
107
- values: next.exception.values.map((item) => ({
108
- ...item,
109
- value: truncateMaybe(scrubString(item?.value)),
110
- })),
111
- };
112
- }
113
- // Never attach IP / user PII by default.
114
- if (next.user) {
115
- next.user = { id: typeof next.user.id === "string" ? next.user.id : undefined };
116
- }
117
- return next;
118
- }
119
-
120
- /**
121
- * Initialise Sentry once for this process. Never throws.
122
- * @returns {Promise<{ enabled: boolean, reason?: string }>}
123
- */
124
- async function initSentry({
125
- env = process.env,
126
- trackerDir,
127
- version = pkg.version,
128
- } = {}) {
129
- try {
130
- if (initialized) return { enabled: true, reason: "already-initialized" };
131
- if (env?.NODE_TEST_CONTEXT !== undefined) {
132
- return { enabled: false, reason: "test-env" };
133
- }
134
-
135
- const dsn = resolveDsn(env);
136
- if (!dsn) return { enabled: false, reason: "no-dsn" };
137
-
138
- let config = {};
139
- if (trackerDir) {
140
- config = (await readJson(path.join(trackerDir, "config.json"))) || {};
141
- }
142
- if (isTelemetryDisabled({ env, config })) {
143
- return { enabled: false, reason: "opt-out" };
144
- }
145
-
146
- // Honor the same outbound proxy / fail-closed policy as the rest of the CLI.
147
- // Sentry's Node transport uses node:https (not undici), so pass proxy explicitly.
148
- const {
149
- readPersistedProxyConfig,
150
- resolveEffectiveProxySource,
151
- } = require("./proxy-env");
152
- const proxyConfig = readPersistedProxyConfig();
153
- const proxyResolved = resolveEffectiveProxySource({ env, proxyConfig });
154
- if (proxyResolved?.source === "blocked") {
155
- return { enabled: false, reason: "proxy-blocked" };
156
- }
157
-
158
- // Lazy require keeps unit tests that never call init from paying the
159
- // module graph cost at import time of unrelated modules.
160
- const Sentry = require("@sentry/node");
161
- Sentry.init({
162
- dsn,
163
- environment: resolveEnvironment(env),
164
- release: `tokenusage-cli@${String(version || "").trim() || "0.0.0"}`,
165
- sendDefaultPii: false,
166
- tracesSampleRate: 0,
167
- // Errors only: drop process-session + console; replace Http so request
168
- // sessions stay off (Http defaults sessions:true and bypasses beforeSend).
169
- integrations(defaults) {
170
- const filtered = defaults.filter((integration) => {
171
- const name = integration?.name || "";
172
- return name !== "ProcessSession" && name !== "Console" && name !== "Http";
173
- });
174
- filtered.push(Sentry.httpIntegration({ sessions: false }));
175
- return filtered;
176
- },
177
- transportOptions: proxyResolved?.proxyUrl
178
- ? { proxy: proxyResolved.proxyUrl }
179
- : undefined,
180
- beforeSend(event) {
181
- return scrubEvent(event);
182
- },
183
- initialScope: {
184
- tags: {
185
- shell: resolveShell(env),
186
- runtime: "node",
187
- },
188
- },
189
- });
190
- initialized = true;
191
- return { enabled: true };
192
- } catch {
193
- return { enabled: false, reason: "init-failed" };
194
- }
195
- }
196
-
197
- function captureException(error, context) {
198
- if (!initialized) return;
199
- try {
200
- const Sentry = require("@sentry/node");
201
- if (context) {
202
- Sentry.withScope((scope) => {
203
- if (context.tags) {
204
- for (const [key, value] of Object.entries(context.tags)) {
205
- scope.setTag(key, String(value));
206
- }
207
- }
208
- if (context.extra) scope.setExtras(scrubValue(context.extra));
209
- Sentry.captureException(error);
210
- });
211
- return;
212
- }
213
- Sentry.captureException(error);
214
- } catch {
215
- /* never break the CLI */
216
- }
217
- }
218
-
219
- module.exports = {
220
- initSentry,
221
- captureException,
222
- resolveDsn,
223
- resolveEnvironment,
224
- resolveShell,
225
- scrubEvent,
226
- scrubString,
227
- // test helpers
228
- _resetForTests() {
229
- initialized = false;
230
- },
231
- };
@@ -1,28 +0,0 @@
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 };