tokenusage-cli 0.1.0 → 0.2.0

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +39 -19
  2. package/LICENSE +22 -22
  3. package/README.md +94 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +181 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,2436 +1,2484 @@
1
- const os = require("node:os");
2
- const path = require("node:path");
3
- const fs = require("node:fs/promises");
4
- const fssync = require("node:fs");
5
- const cp = require("node:child_process");
6
- const crypto = require("node:crypto");
7
-
8
- const {
9
- ensureDir,
10
- writeFileAtomic,
11
- readJson,
12
- writeJson,
13
- chmod600IfPossible,
14
- } = require("../lib/fs");
15
- const { resolveMimoNativeDbPath } = require("../lib/install-resolver");
16
- const { resolveDumateDbPaths } = require("../lib/dumate");
17
- const { expandHome } = require("../lib/scan-roots");
18
- const { prompt, promptHidden } = require("../lib/prompt");
19
- const {
20
- upsertCodexNotify,
21
- upsertAcodeNotify,
22
- upsertEveryCodeNotify,
23
- readCodexNotify,
24
- readAcodeNotify,
25
- readEveryCodeNotify,
26
- buildCodexNotifyCmd,
27
- buildAcodeNotifyCmd,
28
- buildEveryCodeNotifyCmd,
29
- isManagedNotifyCmd,
30
- } = require("../lib/codex-config");
31
- const {
32
- upsertClaudeHook,
33
- upsertClaudeUsageHooks,
34
- buildClaudeHookCommand,
35
- buildHookCommand,
36
- isClaudeHookConfigured,
37
- areClaudeUsageHooksConfigured,
38
- } = require("../lib/claude-config");
39
- const {
40
- resolveGeminiConfigDir,
41
- resolveGeminiSettingsPath,
42
- buildGeminiHookCommand,
43
- upsertGeminiHook,
44
- isGeminiHookConfigured,
45
- } = require("../lib/gemini-config");
46
- const {
47
- resolveOpencodeConfigDir,
48
- upsertOpencodePlugin,
49
- isOpencodePluginInstalled,
50
- } = require("../lib/opencode-config");
51
- const { isCursorInstalled, extractCursorSessionToken } = require("../lib/cursor-config");
52
- const { removeOpenclawHookConfig, probeOpenclawHookState } = require("../lib/openclaw-hook");
53
- const {
54
- installOpenclawSessionPlugin,
55
- probeOpenclawSessionPluginState,
56
- } = require("../lib/openclaw-session-plugin");
57
- const {
58
- resolveGrokHome,
59
- resolveGrokHooksDir,
60
- upsertGrokHook,
61
- probeGrokHookState,
62
- removeGrokHook,
63
- GROK_HOOK_FILENAME
64
- } = require("../lib/grok-hook");
65
- const {
66
- upsertOmpHook,
67
- probeOmpHookState,
68
- } = require("../lib/omp-hook");
69
- const { resolveTrackerPaths } = require("../lib/tracker-paths");
70
- const {
71
- resolveOmpAgentDir,
72
- resolvePiAgentDir,
73
- piAgentDirCollidesWithOmp,
74
- resolvePrimeAgentDir,
75
- resolveMinimaxCodeSessionsDir,
76
- resolveCommandCodeHome,
77
- resolveLmstudioLogFiles,
78
- resolveUnslothDbPath,
79
- resolveAnythingllmDbPath,
80
- resolveDevinDbPath,
81
- resolveReasonixHome,
82
- resolveMuseHome,
83
- resolveTraeStoragePath,
84
- } = require("../lib/rollout");
85
- const { resolveRuntimeConfig, DEFAULT_BASE_URL, normalizeInstanceBaseUrl, assertInsforgeRuntime,
86
- clearDeviceIdentity, resetInstanceState } = require("../lib/runtime-config");
87
- const {
88
- BOLD,
89
- DIM,
90
- CYAN,
91
- RESET,
92
- color,
93
- isInteractive,
94
- promptMenu,
95
- createSpinner,
96
- } = require("../lib/cli-ui");
97
- const { renderLocalReport, renderAuthTransition, renderSuccessBox } = require("../lib/init-flow");
98
- const { maybeShowStarCta } = require("../lib/star-cta");
99
-
100
- const ASCII_LOGO = [
101
- "████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗",
102
- "╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║",
103
- " ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║",
104
- " ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║",
105
- " ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║",
106
- " ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝",
107
- " ████████╗██████╗ █████╗ ██████╗██╗ ██╗███████╗██████╗",
108
- " ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗",
109
- " ██║ ██████╔╝███████║██║ █████╔╝ █████╗ ██████╔╝",
110
- " ██║ ██╔══██╗██╔══██║██║ ██╔═██╗ ██╔══╝ ██╔══██╗",
111
- " ██║ ██║ ██║██║ ██║╚██████╗██║ ██╗███████╗██║ ██║",
112
- " ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝",
113
- ].join("\n");
114
-
115
- const DIVIDER = "----------------------------------------------";
116
- const DEFAULT_DASHBOARD_URL = "https://www.tokenusage.cc";
117
-
118
- // Single source of truth for the welcome screen's provider count + sample list.
119
- // test/discovery-metadata.test.js keeps this aligned with public tool copy.
120
- const SUPPORTED_PROVIDERS = [
121
- "Claude Code",
122
- "Codex CLI",
123
- "AStudio",
124
- "Cursor",
125
- "Gemini CLI",
126
- "Antigravity",
127
- "Kiro",
128
- "OpenCode",
129
- "OpenClaw",
130
- "Every Code",
131
- "Hermes Agent",
132
- "GitHub Copilot",
133
- "Kimi Code",
134
- "CodeBuddy",
135
- "WorkBuddy",
136
- "WorkBuddy AI",
137
- "Grok Build",
138
- "oh-my-pi",
139
- "OmO",
140
- "pi",
141
- "Dots",
142
- "Prime Agent",
143
- "Craft Agents",
144
- "Reasonix",
145
- "Muse Code",
146
- "Kilo CLI",
147
- "Kilo Code",
148
- "Roo Code",
149
- "Zed Agent",
150
- "Goose",
151
- "Droid",
152
- "Mimo",
153
- "DuMate",
154
- "ZCode",
155
- "Qoder",
156
- "AnythingLLM Desktop",
157
- "Claude Science",
158
- "DeepSeek Harness",
159
- "TRAE Work CN",
160
- "TRAE",
161
- "LM Studio",
162
- "Unsloth Studio",
163
- "Devin CLI",
164
- "Cline",
165
- "MiniMax Code",
166
- "Command Code",
167
- ];
168
-
169
- async function cmdInit(argv, options = {}) {
170
- const opts = parseArgs(argv);
171
- const home = options.home || os.homedir();
172
- if (opts.anonKeyFile) opts.anonKey = (await fs.readFile(opts.anonKeyFile, "utf8")).trim();
173
-
174
- const { rootDir, trackerDir, binDir } = await resolveTrackerPaths({ home });
175
-
176
- const configPath = path.join(trackerDir, "config.json");
177
- const notifyOriginalPath = path.join(trackerDir, "codex_notify_original.json");
178
- const linkCodeStatePath = path.join(trackerDir, "link_code_state.json");
179
-
180
- const existingConfig = await readJson(configPath);
181
- const runtime = resolveRuntimeConfig({
182
- cli: { baseUrl: opts.baseUrl, dashboardUrl: opts.dashboardUrl, anonKey: opts.anonKey },
183
- config: existingConfig || {},
184
- env: process.env,
185
- });
186
- assertInsforgeRuntime(runtime);
187
- const notifyPath = path.join(binDir, "notify.cjs");
188
- const appDir = path.join(trackerDir, "app");
189
- const trackerBinPath = path.join(appDir, "bin", "tracker.js");
190
-
191
- renderWelcome();
192
-
193
- if (opts.dryRun) {
194
- process.stdout.write(`${color("Dry run: preview only (no changes applied).", DIM)}\n\n`);
195
- }
196
-
197
- if (isInteractive() && !opts.yes && !opts.dryRun) {
198
- const choice = await promptMenu({
199
- message: "? Proceed with installation?",
200
- options: ["Yes, configure my environment", "No, exit"],
201
- defaultIndex: 0,
202
- });
203
- const normalizedChoice = String(choice || "")
204
- .trim()
205
- .toLowerCase();
206
- if (normalizedChoice.startsWith("no") || normalizedChoice.includes("exit")) {
207
- process.stdout.write("Setup cancelled.\n");
208
- return;
209
- }
210
- }
211
-
212
- if (opts.dryRun) {
213
- const preview = await buildDryRunSummary({
214
- opts,
215
- home,
216
- trackerDir,
217
- notifyPath,
218
- runtime,
219
- });
220
- renderLocalReport({ summary: preview.summary, isDryRun: true });
221
- renderAccountNotLinked({ context: "dry-run" });
222
- return;
223
- }
224
-
225
- const spinner = createSpinner({ text: "Analyzing and configuring local environment..." });
226
- spinner.start();
227
- let setup;
228
- try {
229
- setup = await runSetup({
230
- opts,
231
- home,
232
- trackerDir,
233
- binDir,
234
- configPath,
235
- notifyOriginalPath,
236
- linkCodeStatePath,
237
- notifyPath,
238
- appDir,
239
- trackerBinPath,
240
- runtime,
241
- existingConfig,
242
- });
243
- } catch (err) {
244
- spinner.stop();
245
- throw err;
246
- }
247
- spinner.stop();
248
-
249
- renderLocalReport({ summary: setup.summary, isDryRun: false });
250
-
251
- // Run first sync inline (with a generous timeout) so we can render the
252
- // *actual* token total in the success message — the aha moment. If the
253
- // sync exceeds the timeout we surrender the wait but leave it running, so
254
- // the dashboard still picks up data shortly after.
255
- const ahaSpinner = createSpinner({ text: "Running first sync..." });
256
- ahaSpinner.start();
257
- let firstSync = null;
258
- try {
259
- firstSync = await runFirstSyncAndRead({
260
- trackerBinPath,
261
- trackerDir,
262
- packageName: "tokenusage",
263
- });
264
- } catch (err) {
265
- const msg = err && err.message ? err.message : "unknown error";
266
- process.stderr.write(`Initial sync issue: ${msg}\n`);
267
- } finally {
268
- ahaSpinner.stop();
269
- }
270
-
271
- renderLocalSuccess({ firstSync });
272
- await maybeShowStarCta({ trackerDir });
273
- }
274
-
275
- function renderWelcome() {
276
- const providerCount = SUPPORTED_PROVIDERS.length;
277
- // Show first 5 by name for grounding, then "+N more" so the line stays one row.
278
- const previewNames = SUPPORTED_PROVIDERS.slice(0, 5).join(", ");
279
- const remaining = providerCount - 5;
280
- const providerLine =
281
- remaining > 0
282
- ? `${previewNames} +${remaining} more`
283
- : previewNames;
284
- process.stdout.write(
285
- [
286
- ASCII_LOGO,
287
- "",
288
- `${BOLD}Token Tracker${RESET} ${color("Local-first usage across " + providerCount + " AI CLIs", DIM)}`,
289
- DIVIDER,
290
- `${CYAN}Nothing leaves your machine — token counts only, never prompts or responses.${RESET}`,
291
- DIVIDER,
292
- "",
293
- ` Tracks: ${providerLine}`,
294
- ` Dashboard: http://localhost:7680`,
295
- "",
296
- ].join("\n"),
297
- );
298
- }
299
-
300
- function renderLocalSuccess({ firstSync } = {}) {
301
- const lines = ["", `${BOLD}Setup complete!${RESET}`, ""];
302
-
303
- if (firstSync && firstSync.totalTokens > 0) {
304
- const tokens = firstSync.totalTokens.toLocaleString("en-US");
305
- const sourceCount = firstSync.sources.length;
306
- const sourceWord = sourceCount === 1 ? "provider" : "providers";
307
- lines.push(
308
- ` ${BOLD}${tokens}${RESET} tokens tracked across ${sourceCount} ${sourceWord}.`,
309
- );
310
- } else {
311
- lines.push(
312
- " No usage history yet — run any AI CLI and tokens appear within a minute.",
313
- );
314
- }
315
-
316
- lines.push(
317
- "",
318
- ` Dashboard: ${CYAN}http://localhost:7680${RESET}`,
319
- "",
320
- );
321
- process.stdout.write(lines.join("\n"));
322
- }
323
-
324
- function renderAccountNotLinked({ context } = {}) {
325
- if (context === "dry-run") {
326
- process.stdout.write(
327
- [
328
- "",
329
- "Dry run complete. Run init without --dry-run to apply changes.",
330
- "",
331
- ].join("\n"),
332
- );
333
- return;
334
- }
335
- renderLocalSuccess();
336
- }
337
-
338
- function shouldUseBrowserAuth({ deviceToken, opts }) {
339
- if (deviceToken) return false;
340
- if (opts.noAuth) return false;
341
- if (opts.linkCode) return false;
342
- if (opts.email || opts.password) return false;
343
- return true;
344
- }
345
-
346
- async function buildDryRunSummary({ opts, home, trackerDir, notifyPath, runtime }) {
347
- const deviceToken = runtime?.deviceToken || null;
348
- const pendingBrowserAuth = shouldUseBrowserAuth({ deviceToken, opts });
349
- const context = buildIntegrationTargets({ home, trackerDir, notifyPath });
350
- const summary = await previewIntegrations({ context });
351
- return { summary, pendingBrowserAuth, deviceToken };
352
- }
353
-
354
- async function runSetup({
355
- opts,
356
- home,
357
- trackerDir,
358
- binDir,
359
- configPath,
360
- notifyOriginalPath,
361
- linkCodeStatePath,
362
- notifyPath,
363
- appDir,
364
- trackerBinPath,
365
- runtime,
366
- existingConfig,
367
- }) {
368
- await ensureDir(trackerDir);
369
- await ensureDir(binDir);
370
- let deviceToken = runtime?.deviceToken || null;
371
- let deviceId = existingConfig?.deviceId || null;
372
- const installedAt = existingConfig?.installedAt || new Date().toISOString();
373
- let pendingBrowserAuth = false;
374
-
375
- await installLocalTrackerApp({ appDir });
376
-
377
- const existingPlainConfig =
378
- existingConfig && typeof existingConfig === "object" && !Array.isArray(existingConfig)
379
- ? existingConfig
380
- : {};
381
- const previousRuntime = resolveRuntimeConfig({ config: existingPlainConfig, env: {} });
382
- const changedInstance = normalizeInstanceBaseUrl(previousRuntime.baseUrl) !== runtime.baseUrl ||
383
- previousRuntime.anonKey !== runtime.anonKey;
384
- if (changedInstance) {
385
- resetInstanceState(trackerDir);
386
- deviceToken = null; deviceId = null;
387
- }
388
- const config = {
389
- ...(changedInstance ? clearDeviceIdentity(existingPlainConfig) : existingPlainConfig),
390
- installedAt,
391
- // Keep a persisted legacy URL until the first sync. sync owns the migration
392
- // lock and must reset the upload offset/backoff before removing this marker;
393
- // rewriting it here would skip the historical replay permanently.
394
- baseUrl: opts.baseUrl || existingPlainConfig.baseUrl || DEFAULT_BASE_URL,
395
- };
396
- if (changedInstance || opts.dashboardUrl) {
397
- config.dashboardUrl = runtime.dashboardUrl;
398
- }
399
- if (changedInstance || opts.anonKey || runtime.sources.anonKey === "env") config.anonKey = runtime.anonKey;
400
- if (runtime.baseUrl !== DEFAULT_BASE_URL) {
401
- config.baseUrl = runtime.baseUrl;
402
- config.dashboardUrl = runtime.dashboardUrl;
403
- }
404
-
405
- await writeJson(configPath, config);
406
- await chmod600IfPossible(configPath);
407
-
408
- await writeNotifyHandler({ trackerDir, notifyPath });
409
-
410
- const summary = await applyIntegrationSetup({
411
- home,
412
- trackerDir,
413
- notifyPath,
414
- notifyOriginalPath,
415
- dryRun: Boolean(opts.dryRun),
416
- });
417
-
418
- return {
419
- summary,
420
- pendingBrowserAuth,
421
- deviceToken,
422
- deviceId,
423
- installedAt,
424
- };
425
- }
426
-
427
- async function writeNotifyHandler({ trackerDir, binDir, notifyPath, packageName = "tokenusage-cli" }) {
428
- const resolvedNotifyPath =
429
- notifyPath || path.join(binDir || path.join(path.dirname(trackerDir), "bin"), "notify.cjs");
430
- await ensureDir(path.dirname(resolvedNotifyPath));
431
- await writeFileAtomic(
432
- resolvedNotifyPath,
433
- buildNotifyHandler({ trackerDir, packageName }),
434
- );
435
- await fs.chmod(resolvedNotifyPath, 0o755).catch(() => {});
436
- return resolvedNotifyPath;
437
- }
438
-
439
- async function repairCodexNotifyIntegration({ home = os.homedir(), trackerDir, binDir, safeMode = true } = {}) {
440
- const paths = trackerDir && binDir ? { trackerDir, binDir } : await resolveTrackerPaths({ home });
441
- const resolvedTrackerDir = trackerDir || paths.trackerDir;
442
- const resolvedBinDir = binDir || paths.binDir;
443
- const notifyPath = await writeNotifyHandler({
444
- trackerDir: resolvedTrackerDir,
445
- binDir: resolvedBinDir,
446
- });
447
- const context = buildIntegrationTargets({
448
- home,
449
- trackerDir: resolvedTrackerDir,
450
- notifyPath,
451
- });
452
- const codexProbe = await probeFile(context.codexConfigPath);
453
- if (!codexProbe.exists) {
454
- return { changed: false, skippedReason: "config-missing", notifyPath };
455
- }
456
-
457
- const currentNotify = await readCodexNotify(context.codexConfigPath);
458
- if (arraysEqual(currentNotify, context.notifyCmd)) {
459
- return { changed: false, skippedReason: null, notifyPath };
460
- }
461
-
462
- const repairDecision = safeMode
463
- ? await shouldRepairCodexNotify({
464
- currentNotify,
465
- expectedNotify: context.notifyCmd,
466
- notifyOriginalPath: context.notifyOriginalPath,
467
- })
468
- : { repair: true, captureOriginal: true, replaceOriginal: false };
469
- if (!repairDecision.repair) {
470
- return { changed: false, skippedReason: repairDecision.reason || "external-notify", notifyPath };
471
- }
472
-
473
- const result = await upsertCodexNotify({
474
- codexConfigPath: context.codexConfigPath,
475
- notifyCmd: context.notifyCmd,
476
- notifyOriginalPath: context.notifyOriginalPath,
477
- captureOriginal: repairDecision.captureOriginal,
478
- replaceOriginal: repairDecision.replaceOriginal,
479
- });
480
- return { ...result, skippedReason: null, notifyPath };
481
- }
482
-
483
- async function repairAcodeNotifyIntegration({ home = os.homedir(), trackerDir, binDir, safeMode = true } = {}) {
484
- const paths = trackerDir && binDir ? { trackerDir, binDir } : await resolveTrackerPaths({ home });
485
- const resolvedTrackerDir = trackerDir || paths.trackerDir;
486
- const resolvedBinDir = binDir || paths.binDir;
487
- const notifyPath = await writeNotifyHandler({
488
- trackerDir: resolvedTrackerDir,
489
- binDir: resolvedBinDir,
490
- });
491
- const context = buildIntegrationTargets({
492
- home,
493
- trackerDir: resolvedTrackerDir,
494
- notifyPath,
495
- });
496
- const acodeProbe = await probeFile(context.acodeConfigPath);
497
- if (!acodeProbe.exists) {
498
- return { changed: false, skippedReason: "config-missing", notifyPath };
499
- }
500
-
501
- const currentNotify = await readAcodeNotify(context.acodeConfigPath);
502
- if (arraysEqual(currentNotify, context.acodeNotifyCmd)) {
503
- return { changed: false, skippedReason: null, notifyPath };
504
- }
505
-
506
- const repairDecision = safeMode
507
- ? await shouldRepairCodexNotify({
508
- currentNotify,
509
- expectedNotify: context.acodeNotifyCmd,
510
- notifyOriginalPath: context.acodeNotifyOriginalPath,
511
- })
512
- : { repair: true, captureOriginal: true, replaceOriginal: false };
513
- if (!repairDecision.repair) {
514
- return { changed: false, skippedReason: repairDecision.reason || "external-notify", notifyPath };
515
- }
516
-
517
- const result = await upsertAcodeNotify({
518
- acodeConfigPath: context.acodeConfigPath,
519
- notifyCmd: context.acodeNotifyCmd,
520
- notifyOriginalPath: context.acodeNotifyOriginalPath,
521
- captureOriginal: repairDecision.captureOriginal,
522
- replaceOriginal: repairDecision.replaceOriginal,
523
- });
524
- return { ...result, skippedReason: null, notifyPath };
525
- }
526
-
527
- async function repairRuntimeIntegrations({
528
- home = os.homedir(),
529
- trackerDir,
530
- binDir,
531
- safeMode = true,
532
- } = {}) {
533
- const paths = trackerDir && binDir ? { trackerDir, binDir } : await resolveTrackerPaths({ home });
534
- const resolvedTrackerDir = trackerDir || paths.trackerDir;
535
- const resolvedBinDir = binDir || paths.binDir;
536
- const notifyPath = await writeNotifyHandler({
537
- trackerDir: resolvedTrackerDir,
538
- binDir: resolvedBinDir,
539
- });
540
- const context = buildIntegrationTargets({
541
- home,
542
- trackerDir: resolvedTrackerDir,
543
- notifyPath,
544
- });
545
- const integrations = {};
546
- const warnings = [];
547
-
548
- const attempt = async (key, work) => {
549
- try {
550
- integrations[key] = await work();
551
- } catch (error) {
552
- integrations[key] = { changed: false, skippedReason: "repair-failed" };
553
- warnings.push({ integration: key, error: error?.message || String(error) });
554
- }
555
- };
556
-
557
- await attempt("codex", () => repairCodexNotifyIntegration({
558
- home,
559
- trackerDir: resolvedTrackerDir,
560
- binDir: resolvedBinDir,
561
- safeMode,
562
- }));
563
- await attempt("acode", () => repairAcodeNotifyIntegration({
564
- home,
565
- trackerDir: resolvedTrackerDir,
566
- binDir: resolvedBinDir,
567
- safeMode,
568
- }));
569
-
570
- const hookRepairs = [
571
- ["claude", context.claudeDir, () => upsertClaudeUsageHooks({
572
- settingsPath: context.claudeSettingsPath,
573
- hookCommand: context.claudeHookCommand,
574
- })],
575
- ["gemini", context.geminiConfigDir, () => upsertGeminiHook({
576
- settingsPath: context.geminiSettingsPath,
577
- hookCommand: context.geminiHookCommand,
578
- })],
579
- ["codebuddy", context.codebuddyDir, () => upsertClaudeHook({
580
- settingsPath: context.codebuddySettingsPath,
581
- hookCommand: context.codebuddyHookCommand,
582
- })],
583
- ["workbuddy", context.workbuddyDir, () => upsertClaudeHook({
584
- settingsPath: context.workbuddySettingsPath,
585
- hookCommand: context.workbuddyHookCommand,
586
- })],
587
- ["workbuddy-ai", context.workbuddyAiDir, () => upsertClaudeHook({
588
- settingsPath: context.workbuddyAiSettingsPath,
589
- hookCommand: context.workbuddyAiHookCommand,
590
- })],
591
- ];
592
- for (const [key, configDir, repair] of hookRepairs) {
593
- if (await isDir(configDir)) await attempt(key, repair);
594
- else integrations[key] = { changed: false, skippedReason: "config-missing" };
595
- }
596
-
597
- if (await isDir(context.opencodeConfigDir)) {
598
- await attempt("opencode", () => upsertOpencodePlugin({
599
- configDir: context.opencodeConfigDir,
600
- notifyPath,
601
- }));
602
- } else {
603
- integrations.opencode = { changed: false, skippedReason: "config-missing" };
604
- }
605
-
606
- return { notifyPath, integrations, warnings };
607
- }
608
-
609
- function buildIntegrationTargets({ home, trackerDir, notifyPath }) {
610
- const codexHome = process.env.CODEX_HOME || path.join(home, ".codex");
611
- const codexConfigPath = path.join(codexHome, "config.toml");
612
- const acodeHome = process.env.TOKENUSAGE_ACODE_HOME || path.join(home, ".acode");
613
- const acodeConfigPath = path.join(acodeHome, "config.toml");
614
- const codeHome = process.env.CODE_HOME || path.join(home, ".code");
615
- const codeConfigPath = path.join(codeHome, "config.toml");
616
- const notifyOriginalPath = path.join(trackerDir, "codex_notify_original.json");
617
- const acodeNotifyOriginalPath = path.join(trackerDir, "acode_notify_original.json");
618
- const codeNotifyOriginalPath = path.join(trackerDir, "code_notify_original.json");
619
- const notifyCmd = buildCodexNotifyCmd(notifyPath);
620
- const acodeNotifyCmd = buildAcodeNotifyCmd(notifyPath);
621
- const codeNotifyCmd = buildEveryCodeNotifyCmd(notifyPath);
622
- const claudeDir = path.join(home, ".claude");
623
- const claudeSettingsPath = path.join(claudeDir, "settings.json");
624
- const claudeHookCommand = buildClaudeHookCommand(notifyPath);
625
- // CodeBuddy CLI (Tencent) is a Claude-Code fork — same settings.json hook
626
- // schema, same SessionEnd event. We install the same hook with a different
627
- // --source token so notify.cjs / sync know which provider triggered.
628
- const codebuddyDir = process.env.CODEBUDDY_HOME || path.join(home, ".codebuddy");
629
- const codebuddySettingsPath = path.join(codebuddyDir, "settings.json");
630
- const codebuddyHookCommand = buildHookCommand(notifyPath, "codebuddy");
631
- // WorkBuddy CLI (Tencent) is the same Claude-Code-fork hook schema as CodeBuddy.
632
- const workbuddyDir = process.env.WORKBUDDY_HOME || path.join(home, ".workbuddy");
633
- const workbuddySettingsPath = path.join(workbuddyDir, "settings.json");
634
- const workbuddyHookCommand = buildHookCommand(notifyPath, "workbuddy");
635
- // WorkBuddy AI is the international build of the very same CLI. It keeps its
636
- // data in a sibling home (~/.workbuddy-ai), so it needs its own hook install
637
- // and its own --source token to be attributed separately from the CN build.
638
- const workbuddyAiDir = expandHome(process.env.WORKBUDDY_AI_HOME, home) || path.join(home, ".workbuddy-ai");
639
- const workbuddyAiSettingsPath = path.join(workbuddyAiDir, "settings.json");
640
- const workbuddyAiHookCommand = buildHookCommand(notifyPath, "workbuddy-ai");
641
- const geminiConfigDir = resolveGeminiConfigDir({ home, env: process.env });
642
- const geminiSettingsPath = resolveGeminiSettingsPath({ configDir: geminiConfigDir });
643
- const geminiHookCommand = buildGeminiHookCommand(notifyPath);
644
- const opencodeConfigDir = resolveOpencodeConfigDir({ home, env: process.env });
645
-
646
- return {
647
- trackerDir,
648
- codexConfigPath,
649
- acodeConfigPath,
650
- codeConfigPath,
651
- notifyOriginalPath,
652
- acodeNotifyOriginalPath,
653
- codeNotifyOriginalPath,
654
- notifyCmd,
655
- acodeNotifyCmd,
656
- codeNotifyCmd,
657
- claudeDir,
658
- claudeSettingsPath,
659
- claudeHookCommand,
660
- codebuddyDir,
661
- codebuddySettingsPath,
662
- codebuddyHookCommand,
663
- workbuddyDir,
664
- workbuddySettingsPath,
665
- workbuddyHookCommand,
666
- workbuddyAiDir,
667
- workbuddyAiSettingsPath,
668
- workbuddyAiHookCommand,
669
- geminiConfigDir,
670
- geminiSettingsPath,
671
- geminiHookCommand,
672
- opencodeConfigDir,
673
- };
674
- }
675
-
676
- async function applyIntegrationSetup({
677
- home,
678
- trackerDir,
679
- notifyPath,
680
- notifyOriginalPath,
681
- dryRun = false,
682
- }) {
683
- const context = buildIntegrationTargets({ home, trackerDir, notifyPath });
684
- context.notifyOriginalPath = notifyOriginalPath;
685
-
686
- const summary = [];
687
-
688
- const codexProbe = await probeFile(context.codexConfigPath);
689
- if (codexProbe.exists) {
690
- const currentNotify = await readCodexNotify(context.codexConfigPath);
691
- const result = await upsertCodexNotify({
692
- codexConfigPath: context.codexConfigPath,
693
- notifyCmd: context.notifyCmd,
694
- notifyOriginalPath: context.notifyOriginalPath,
695
- replaceOriginal: shouldReplaceStoredOriginalNotify(currentNotify, context.notifyCmd),
696
- });
697
- summary.push({
698
- label: "Codex CLI",
699
- status: result.changed ? "updated" : "set",
700
- detail: result.changed ? "Updated config" : "Config already set",
701
- });
702
- } else {
703
- summary.push({ label: "Codex CLI", status: "skipped", detail: renderSkipDetail(codexProbe) });
704
- }
705
-
706
- const acodeProbe = await probeFile(context.acodeConfigPath);
707
- if (acodeProbe.exists) {
708
- const currentNotify = await readAcodeNotify(context.acodeConfigPath);
709
- const result = await upsertAcodeNotify({
710
- acodeConfigPath: context.acodeConfigPath,
711
- notifyCmd: context.acodeNotifyCmd,
712
- notifyOriginalPath: context.acodeNotifyOriginalPath,
713
- replaceOriginal: shouldReplaceStoredOriginalNotify(currentNotify, context.acodeNotifyCmd),
714
- });
715
- summary.push({
716
- label: "AStudio",
717
- status: result.changed ? "updated" : "set",
718
- detail: result.changed ? "Updated config" : "Config already set",
719
- });
720
- } else {
721
- summary.push({ label: "AStudio", status: "skipped", detail: renderSkipDetail(acodeProbe) });
722
- }
723
-
724
- const claudeDirExists = await isDir(context.claudeDir);
725
- if (claudeDirExists) {
726
- await upsertClaudeUsageHooks({
727
- settingsPath: context.claudeSettingsPath,
728
- hookCommand: context.claudeHookCommand,
729
- });
730
- summary.push({ label: "Claude", status: "installed", detail: "Hooks installed" });
731
- } else {
732
- summary.push({ label: "Claude", status: "skipped", detail: "Config not found" });
733
- }
734
-
735
- const geminiConfigExists = await isDir(context.geminiConfigDir);
736
- if (geminiConfigExists) {
737
- await upsertGeminiHook({
738
- settingsPath: context.geminiSettingsPath,
739
- hookCommand: context.geminiHookCommand,
740
- });
741
- summary.push({ label: "Gemini", status: "installed", detail: "Hooks installed" });
742
- } else {
743
- summary.push({ label: "Gemini", status: "skipped", detail: "Config not found" });
744
- }
745
-
746
- const opencodeResult = await upsertOpencodePlugin({
747
- configDir: context.opencodeConfigDir,
748
- notifyPath,
749
- });
750
- if (opencodeResult?.skippedReason === "config-missing") {
751
- summary.push({ label: "Opencode Plugin", status: "skipped", detail: "Config not found" });
752
- } else {
753
- summary.push({
754
- label: "Opencode Plugin",
755
- status: opencodeResult?.changed ? "installed" : "set",
756
- detail: "Plugin installed",
757
- });
758
- }
759
-
760
- // Cursor (API-based, no hooks needed)
761
- if (isCursorInstalled({ home })) {
762
- const cursorAuth = extractCursorSessionToken({ home });
763
- if (cursorAuth) {
764
- summary.push({
765
- label: "Cursor",
766
- status: "detected",
767
- detail: "Usage synced via Cursor API (no hooks needed)",
768
- });
769
- } else {
770
- summary.push({
771
- label: "Cursor",
772
- status: "skipped",
773
- detail: "Installed but not logged in (login in Cursor to enable)",
774
- });
775
- }
776
- } else {
777
- summary.push({ label: "Cursor", status: "skipped", detail: "Not installed" });
778
- }
779
-
780
- // Kimi: passive reader — no hook installation needed.
781
- // Token Usage reads both legacy ~/.kimi/ and official ~/.kimi-code/ sessions.
782
- {
783
- const kimiHome = process.env.KIMI_HOME || path.join(home, ".kimi");
784
- const kimiCodeHome = process.env.KIMI_CODE_HOME || path.join(home, ".kimi-code");
785
- const fssync = require("node:fs");
786
- if (fssync.existsSync(path.join(kimiHome, "sessions")) || fssync.existsSync(path.join(kimiCodeHome, "sessions"))) {
787
- summary.push({ label: "Kimi Code", status: "detected", detail: "Passive reader (no hook needed)" });
788
- }
789
- }
790
-
791
- // oh-my-pi: passive session scan always works; also install an optional
792
- // notify extension so turn_end triggers sync --source omp near-real-time.
793
- {
794
- const fssyncLocal = require("node:fs");
795
- const ompAgentDir = resolveOmpAgentDir(process.env);
796
- const ompSessions = ompAgentDir && fssyncLocal.existsSync(path.join(ompAgentDir, "sessions"));
797
- if (ompAgentDir && (ompSessions || fssyncLocal.existsSync(ompAgentDir))) {
798
- if (dryRun) {
799
- const probe = await probeOmpHookState({ home, trackerDir, env: process.env });
800
- summary.push({
801
- label: "oh-my-pi",
802
- status: "detected",
803
- detail: probe.configured
804
- ? "Notify extension already installed (passive scan still runs)"
805
- : "Will install notify extension + keep passive scan",
806
- });
807
- } else {
808
- const result = await upsertOmpHook({ home, trackerDir, env: process.env });
809
- if (result.written) {
810
- summary.push({
811
- label: "oh-my-pi",
812
- status: "installed",
813
- detail: `Notify extension → ${result.extensionPath} (passive scan still runs)`,
814
- });
815
- } else if (result.skippedReason === "unmanaged-extension-present") {
816
- summary.push({
817
- label: "oh-my-pi",
818
- status: "skipped",
819
- detail: "Existing unmanaged tokenusage-notify extension left untouched",
820
- });
821
- } else {
822
- summary.push({
823
- label: "oh-my-pi",
824
- status: "detected",
825
- detail: "Passive reader (notify extension not written)",
826
- });
827
- }
828
- }
829
- }
830
- }
831
-
832
- // pi (@mariozechner/pi-coding-agent): passive reader — no hook installation needed.
833
- // Token Usage reads ~/.pi/agent/sessions/**/*.jsonl directly. Skip when its
834
- // agent dir collides with omp's so the summary matches what sync will scan.
835
- if (!piAgentDirCollidesWithOmp(process.env)) {
836
- // Same win32 nullability as oh-my-pi above: resolvePiAgentDir is null when
837
- // ~/.pi doesn't exist, so guard before joining.
838
- const piAgentDir = resolvePiAgentDir(process.env);
839
- if (piAgentDir && fssync.existsSync(path.join(piAgentDir, "sessions"))) {
840
- summary.push({ label: "pi", status: "detected", detail: "Passive reader (no hook needed)" });
841
- }
842
- }
843
-
844
- // Prime Agent: metadata-only passive reader — no hook installation needed.
845
- {
846
- const primeAgentDir = resolvePrimeAgentDir(process.env);
847
- if (primeAgentDir && fssync.existsSync(path.join(primeAgentDir, "sessions"))) {
848
- summary.push({ label: "Prime Agent", status: "detected", detail: "Passive usage reader (no hook needed)" });
849
- }
850
- }
851
-
852
- // MiniMax Code: passive reader of ~/.minimax/v2/sessions — no hook installation needed.
853
- {
854
- const minimaxCodeSessionsDir = resolveMinimaxCodeSessionsDir(process.env);
855
- if (minimaxCodeSessionsDir && fssync.existsSync(minimaxCodeSessionsDir)) {
856
- summary.push({ label: "MiniMax Code", status: "detected", detail: "Passive usage reader (no hook needed)" });
857
- }
858
- }
859
-
860
- // Command Code (`cmd`): passive reader of ~/.commandcode/projects — no hook
861
- // installation needed, and none exists to install.
862
- {
863
- const commandCodeProjectsDir = path.join(resolveCommandCodeHome(process.env), "projects");
864
- if (fssync.existsSync(commandCodeProjectsDir)) {
865
- summary.push({ label: "Command Code", status: "detected", detail: "Passive session reader (no hook needed)" });
866
- }
867
- }
868
-
869
- // Craft Agents: passive reader — no hook installation needed.
870
- // Token Usage reads ~/.craft-agent/workspaces/<id>/sessions/**/session.jsonl
871
- // (and any user-relocated workspace listed in ~/.craft-agent/config.json).
872
- {
873
- const craftConfigDir = process.env.CRAFT_CONFIG_DIR || path.join(home, ".craft-agent");
874
- if (fssync.existsSync(craftConfigDir)) {
875
- summary.push({ label: "Craft Agents", status: "detected", detail: "Passive reader (no hook needed)" });
876
- }
877
- }
878
-
879
- // Reasonix: passive reader of content-free *.jsonl.telemetry.json sidecars.
880
- {
881
- const reasonixHome = resolveReasonixHome(process.env);
882
- if (fssync.existsSync(reasonixHome)) {
883
- summary.push({ label: "Reasonix", status: "detected", detail: "Passive telemetry reader (no hook needed)" });
884
- }
885
- }
886
-
887
- // Muse Code: passive reader of ~/.local/share/muse/sessions/**/session.jsonl.
888
- {
889
- if (fssync.existsSync(path.join(resolveMuseHome(process.env), "sessions"))) {
890
- summary.push({ label: "Muse Code", status: "detected", detail: "Passive session reader (no hook needed)" });
891
- }
892
- }
893
-
894
- // International TRAE usage is read locally; no hook or vendor login is needed.
895
- {
896
- const { resolveTraeDbPaths } = require("../lib/trae-db");
897
- const traeDbPaths = resolveTraeDbPaths(process.env);
898
- const traeStoragePath = resolveTraeStoragePath(process.env);
899
- if (traeDbPaths.length || traeStoragePath) {
900
- summary.push({
901
- label: "TRAE",
902
- status: "detected",
903
- detail: traeDbPaths.length
904
- ? "Local usage reader (shared application key; optional TOKENUSAGE_TRAE_SQLCIPHER_KEY override)"
905
- : "Plan info only — no local usage database found",
906
- });
907
- }
908
- }
909
-
910
- // Grok Build (xAI): SessionEnd hook in ~/.grok/hooks/ + handler in ~/.tokenusage/bin/
911
- {
912
- try {
913
- const grokState = await probeGrokHookState({ home, trackerDir, env: process.env });
914
- if (grokState.hasGrokInstall) {
915
- const grokRes = await upsertGrokHook({ home, trackerDir, env: process.env });
916
- summary.push({
917
- label: "Grok Build",
918
- status: grokRes.configured ? "installed" : "detected",
919
- detail: grokRes.configured ? "SessionEnd hook installed (99-tokenusage-usage.json)" : "Grok detected"
920
- });
921
- }
922
- } catch (err) {
923
- summary.push({ label: "Grok Build", status: "error", detail: String(err?.message || err) });
924
- }
925
- }
926
-
927
- // Kilo CLI (kilo.ai @kilocode/plugin): passive reader — no hook installation
928
- // needed. Reuses OpenCode-fork SQLite schema at ~/.local/share/kilo/kilo.db
929
- // (override via KILO_HOME).
930
- {
931
- const xdgDataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
932
- const kiloHome = process.env.KILO_HOME || path.join(xdgDataHome, "kilo");
933
- const kiloDbPath = path.join(kiloHome, "kilo.db");
934
- if (fssync.existsSync(kiloDbPath)) {
935
- summary.push({ label: "Kilo CLI", status: "detected", detail: "Passive reader (no hook needed)" });
936
- }
937
- }
938
-
939
- {
940
- const dumateDbPaths = resolveDumateDbPaths({ home });
941
- if (dumateDbPaths.length > 0) {
942
- summary.push({ label: "DuMate", status: "detected", detail: "Passive reader (no hook needed)" });
943
- }
944
- }
945
-
946
- // Mimo (mimocode): passive reader — no hook installation needed. Reuses the
947
- // OpenCode-fork SQLite schema at ~/.local/share/mimocode/mimocode.db
948
- // (override via MIMO_HOME).
949
- {
950
- const mimoDbPath = resolveMimoNativeDbPath({ home });
951
- if (fssync.existsSync(mimoDbPath)) {
952
- summary.push({ label: "Mimo", status: "detected", detail: "Passive reader (no hook needed)" });
953
- }
954
- }
955
-
956
- // LM Studio and Unsloth Studio: passive readers — no hooks needed.
957
- {
958
- const lmstudioLogFiles = await resolveLmstudioLogFiles(process.env);
959
- if (lmstudioLogFiles.length > 0) {
960
- summary.push({
961
- label: "LM Studio",
962
- status: "detected",
963
- detail: `Passive reader · ${lmstudioLogFiles.length} log${lmstudioLogFiles.length !== 1 ? "s" : ""}`,
964
- });
965
- }
966
- }
967
-
968
- {
969
- const unslothDbPath = resolveUnslothDbPath(process.env);
970
- if (unslothDbPath && fssync.existsSync(unslothDbPath)) {
971
- summary.push({
972
- label: "Unsloth Studio",
973
- status: "detected",
974
- detail: "Passive reader (no hook needed)",
975
- });
976
- }
977
- }
978
-
979
- // AnythingLLM Desktop: passive SQLite reader — no hook installation needed.
980
- {
981
- const anythingllmDbPath = resolveAnythingllmDbPath(process.env);
982
- if (anythingllmDbPath && fssync.existsSync(anythingllmDbPath)) {
983
- summary.push({
984
- label: "AnythingLLM Desktop",
985
- status: "detected",
986
- detail: "Passive reader (no hook needed)",
987
- });
988
- }
989
- }
990
-
991
- // Devin CLI (Cognition): passive SQLite reader — no hook installation needed.
992
- {
993
- const devinDbPath = resolveDevinDbPath(process.env);
994
- if (devinDbPath && fssync.existsSync(devinDbPath)) {
995
- summary.push({
996
- label: "Devin CLI",
997
- status: "detected",
998
- detail: "Passive reader (no hook needed)",
999
- });
1000
- }
1001
- }
1002
-
1003
- // Kilo Code VS Code extension (kilocode.kilo-code): passive reader — no hook
1004
- // installation needed. Scans ui_messages.json under every detected VS Code-
1005
- // family install (Code, Cursor, CodeBuddy, Windsurf, …).
1006
- {
1007
- const { resolveKilocodeTaskFiles } = require("../lib/rollout");
1008
- const taskFiles = resolveKilocodeTaskFiles(process.env);
1009
- if (taskFiles.length > 0) {
1010
- const ides = Array.from(new Set(taskFiles.map((t) => t.ide))).join(", ");
1011
- summary.push({
1012
- label: "Kilo Code (VS Code extension)",
1013
- status: "detected",
1014
- detail: `Passive reader · ${taskFiles.length} task${taskFiles.length !== 1 ? "s" : ""} in ${ides}`,
1015
- });
1016
- }
1017
- }
1018
-
1019
- // Cline CLI v3 / desktop app: passive reader — no hook installation needed.
1020
- // Cline keeps its own data dir (~/.cline/data/sessions, overridable through
1021
- // CLINE_DIR/CLINE_DATA_DIR/CLINE_SESSION_DATA_DIR); the VS Code extension's
1022
- // globalStorage layout is a separate, older install we do not read.
1023
- {
1024
- const { resolveClineSessionFilesWithStatus } = require("../lib/rollout");
1025
- const clineScan = resolveClineSessionFilesWithStatus(process.env);
1026
- const sessionFiles = clineScan.files;
1027
- if (sessionFiles.length > 0) {
1028
- summary.push({
1029
- label: "Cline",
1030
- status: "detected",
1031
- detail: `Passive reader · ${sessionFiles.length} transcript${sessionFiles.length !== 1 ? "s" : ""}`,
1032
- });
1033
- }
1034
- for (const failure of clineScan.errors) {
1035
- summary.push({
1036
- label: "Cline",
1037
- status: "error",
1038
- detail: `Passive reader discovery failed · ${failure.root}: ${failure.error.code ? `${failure.error.code}: ` : ""}${failure.error.message}`,
1039
- });
1040
- }
1041
- }
1042
-
1043
- // CodeBuddy: Claude-Code fork. Install the SessionEnd hook so finished
1044
- // sessions trigger notify.cjs → tracker sync; passive scan still runs as a
1045
- // safety net for sessions that don't fire SessionEnd cleanly.
1046
- const codebuddyDirExists = await isDir(context.codebuddyDir);
1047
- if (codebuddyDirExists) {
1048
- await upsertClaudeHook({
1049
- settingsPath: context.codebuddySettingsPath,
1050
- hookCommand: context.codebuddyHookCommand,
1051
- });
1052
- summary.push({ label: "CodeBuddy", status: "installed", detail: "Hooks installed" });
1053
- } else {
1054
- summary.push({ label: "CodeBuddy", status: "skipped", detail: "Config not found" });
1055
- }
1056
-
1057
- // WorkBuddy: sibling Claude-Code fork. Same SessionEnd hook → notify.cjs →
1058
- // tracker sync; passive scan still runs as a safety net.
1059
- const workbuddyDirExists = await isDir(context.workbuddyDir);
1060
- if (workbuddyDirExists) {
1061
- await upsertClaudeHook({
1062
- settingsPath: context.workbuddySettingsPath,
1063
- hookCommand: context.workbuddyHookCommand,
1064
- });
1065
- summary.push({ label: "WorkBuddy", status: "installed", detail: "Hooks installed" });
1066
- } else {
1067
- summary.push({ label: "WorkBuddy", status: "skipped", detail: "Config not found" });
1068
- }
1069
-
1070
- // WorkBuddy AI: international build, same hook schema, sibling home.
1071
- const workbuddyAiDirExists = await isDir(context.workbuddyAiDir);
1072
- if (workbuddyAiDirExists) {
1073
- await upsertClaudeHook({
1074
- settingsPath: context.workbuddyAiSettingsPath,
1075
- hookCommand: context.workbuddyAiHookCommand,
1076
- });
1077
- summary.push({ label: "WorkBuddy AI", status: "installed", detail: "Hooks installed" });
1078
- } else {
1079
- summary.push({ label: "WorkBuddy AI", status: "skipped", detail: "Config not found" });
1080
- }
1081
-
1082
- const openclawBefore = await probeOpenclawSessionPluginState({
1083
- home,
1084
- trackerDir,
1085
- env: process.env,
1086
- });
1087
- const openclawInstall = await installOpenclawSessionPlugin({
1088
- home,
1089
- trackerDir,
1090
- packageName: "tokenusage-cli",
1091
- env: process.env,
1092
- });
1093
- if (openclawInstall?.skippedReason === "openclaw-cli-missing") {
1094
- summary.push({
1095
- label: "OpenClaw Session Plugin",
1096
- status: "skipped",
1097
- detail: "OpenClaw CLI not found",
1098
- });
1099
- } else if (openclawInstall?.skippedReason === "openclaw-plugins-install-failed") {
1100
- summary.push({
1101
- label: "OpenClaw Session Plugin",
1102
- status: "skipped",
1103
- detail: `Install failed${openclawInstall.error ? `: ${openclawInstall.error}` : ""}`,
1104
- });
1105
- } else if (openclawInstall?.skippedReason === "openclaw-config-unreadable") {
1106
- summary.push({
1107
- label: "OpenClaw Session Plugin",
1108
- status: "skipped",
1109
- detail: openclawInstall.error
1110
- ? `OpenClaw config unreadable: ${openclawInstall.error}`
1111
- : "OpenClaw config unreadable",
1112
- });
1113
- } else if (openclawInstall?.configured) {
1114
- summary.push({
1115
- label: "OpenClaw Session Plugin",
1116
- status: openclawBefore?.configured ? "set" : "installed",
1117
- detail: openclawBefore?.configured
1118
- ? "Session plugin already linked"
1119
- : "Session plugin linked (restart OpenClaw gateway to activate)",
1120
- });
1121
- } else {
1122
- summary.push({
1123
- label: "OpenClaw Session Plugin",
1124
- status: "skipped",
1125
- detail: "OpenClaw session plugin unavailable",
1126
- });
1127
- }
1128
-
1129
- const legacyHookState = await probeOpenclawHookState({ home, trackerDir, env: process.env });
1130
- if (legacyHookState?.configured || legacyHookState?.linked || legacyHookState?.enabled) {
1131
- await removeOpenclawHookConfig({ home, trackerDir, env: process.env });
1132
- summary.push({
1133
- label: "OpenClaw Hook (legacy)",
1134
- status: "updated",
1135
- detail: "Removed legacy command hook (migrated to session plugin)",
1136
- });
1137
- }
1138
-
1139
- const codeProbe = await probeFile(context.codeConfigPath);
1140
- if (codeProbe.exists) {
1141
- const currentNotify = await readEveryCodeNotify(context.codeConfigPath);
1142
- const result = await upsertEveryCodeNotify({
1143
- codeConfigPath: context.codeConfigPath,
1144
- notifyCmd: context.codeNotifyCmd,
1145
- notifyOriginalPath: context.codeNotifyOriginalPath,
1146
- replaceOriginal: shouldReplaceStoredOriginalNotify(currentNotify, context.codeNotifyCmd),
1147
- });
1148
- summary.push({
1149
- label: "Every Code",
1150
- status: result.changed ? "updated" : "set",
1151
- detail: result.changed ? "Updated config" : "Config already set",
1152
- });
1153
- } else {
1154
- summary.push({ label: "Every Code", status: "skipped", detail: renderSkipDetail(codeProbe) });
1155
- }
1156
-
1157
- return summary;
1158
- }
1159
-
1160
- async function previewIntegrations({ context }) {
1161
- const summary = [];
1162
- const home = os.homedir();
1163
-
1164
- const codexProbe = await probeFile(context.codexConfigPath);
1165
- if (codexProbe.exists) {
1166
- const existing = await readCodexNotify(context.codexConfigPath);
1167
- const matches = arraysEqual(existing, context.notifyCmd);
1168
- summary.push({
1169
- label: "Codex CLI",
1170
- status: matches ? "set" : "updated",
1171
- detail: matches ? "Already configured" : "Will update config",
1172
- });
1173
- } else {
1174
- summary.push({ label: "Codex CLI", status: "skipped", detail: renderSkipDetail(codexProbe) });
1175
- }
1176
-
1177
- const acodeProbe = await probeFile(context.acodeConfigPath);
1178
- if (acodeProbe.exists) {
1179
- const existing = await readAcodeNotify(context.acodeConfigPath);
1180
- const matches = arraysEqual(existing, context.acodeNotifyCmd);
1181
- summary.push({
1182
- label: "AStudio",
1183
- status: matches ? "set" : "updated",
1184
- detail: matches ? "Already configured" : "Will update config",
1185
- });
1186
- } else {
1187
- summary.push({ label: "AStudio", status: "skipped", detail: renderSkipDetail(acodeProbe) });
1188
- }
1189
-
1190
- const claudeDirExists = await isDir(context.claudeDir);
1191
- if (claudeDirExists) {
1192
- const configured = await areClaudeUsageHooksConfigured({
1193
- settingsPath: context.claudeSettingsPath,
1194
- hookCommand: context.claudeHookCommand,
1195
- });
1196
- summary.push({
1197
- label: "Claude",
1198
- status: "installed",
1199
- detail: configured ? "Hooks already installed" : "Will install hooks",
1200
- });
1201
- } else {
1202
- summary.push({ label: "Claude", status: "skipped", detail: "Config not found" });
1203
- }
1204
-
1205
- const codebuddyDirExists = await isDir(context.codebuddyDir);
1206
- if (codebuddyDirExists) {
1207
- const configured = await isClaudeHookConfigured({
1208
- settingsPath: context.codebuddySettingsPath,
1209
- hookCommand: context.codebuddyHookCommand,
1210
- });
1211
- summary.push({
1212
- label: "CodeBuddy",
1213
- status: "installed",
1214
- detail: configured ? "Hooks already installed" : "Will install hooks",
1215
- });
1216
- } else {
1217
- summary.push({ label: "CodeBuddy", status: "skipped", detail: "Config not found" });
1218
- }
1219
-
1220
- const workbuddyDirExists = await isDir(context.workbuddyDir);
1221
- if (workbuddyDirExists) {
1222
- const configured = await isClaudeHookConfigured({
1223
- settingsPath: context.workbuddySettingsPath,
1224
- hookCommand: context.workbuddyHookCommand,
1225
- });
1226
- summary.push({
1227
- label: "WorkBuddy",
1228
- status: "installed",
1229
- detail: configured ? "Hooks already installed" : "Will install hooks",
1230
- });
1231
- } else {
1232
- summary.push({ label: "WorkBuddy", status: "skipped", detail: "Config not found" });
1233
- }
1234
-
1235
- const workbuddyAiDirExists = await isDir(context.workbuddyAiDir);
1236
- if (workbuddyAiDirExists) {
1237
- const configured = await isClaudeHookConfigured({
1238
- settingsPath: context.workbuddyAiSettingsPath,
1239
- hookCommand: context.workbuddyAiHookCommand,
1240
- });
1241
- summary.push({
1242
- label: "WorkBuddy AI",
1243
- status: "installed",
1244
- detail: configured ? "Hooks already installed" : "Will install hooks",
1245
- });
1246
- } else {
1247
- summary.push({ label: "WorkBuddy AI", status: "skipped", detail: "Config not found" });
1248
- }
1249
-
1250
- const geminiConfigExists = await isDir(context.geminiConfigDir);
1251
- if (geminiConfigExists) {
1252
- const configured = await isGeminiHookConfigured({
1253
- settingsPath: context.geminiSettingsPath,
1254
- hookCommand: context.geminiHookCommand,
1255
- });
1256
- summary.push({
1257
- label: "Gemini",
1258
- status: "installed",
1259
- detail: configured ? "Hooks already installed" : "Will install hooks",
1260
- });
1261
- } else {
1262
- summary.push({ label: "Gemini", status: "skipped", detail: "Config not found" });
1263
- }
1264
-
1265
- const opencodeDirExists = await isDir(context.opencodeConfigDir);
1266
- const installed = await isOpencodePluginInstalled({ configDir: context.opencodeConfigDir });
1267
- const opencodeDetail = installed
1268
- ? "Plugin already installed"
1269
- : opencodeDirExists
1270
- ? "Will install plugin"
1271
- : "Will create config and install plugin";
1272
- summary.push({
1273
- label: "Opencode Plugin",
1274
- status: "installed",
1275
- detail: opencodeDetail,
1276
- });
1277
-
1278
- const openclawState = await probeOpenclawSessionPluginState({
1279
- home,
1280
- trackerDir: context.trackerDir,
1281
- env: process.env,
1282
- });
1283
- if (openclawState?.skippedReason === "openclaw-config-missing") {
1284
- summary.push({
1285
- label: "OpenClaw Session Plugin",
1286
- status: "skipped",
1287
- detail: "OpenClaw config not found",
1288
- });
1289
- } else if (openclawState?.skippedReason === "openclaw-config-unreadable") {
1290
- summary.push({
1291
- label: "OpenClaw Session Plugin",
1292
- status: "skipped",
1293
- detail: openclawState.error
1294
- ? `OpenClaw config unreadable: ${openclawState.error}`
1295
- : "OpenClaw config unreadable",
1296
- });
1297
- } else {
1298
- summary.push({
1299
- label: "OpenClaw Session Plugin",
1300
- status: openclawState?.configured ? "set" : "installed",
1301
- detail: openclawState?.configured
1302
- ? "Session plugin already linked"
1303
- : "Will link session plugin (restart OpenClaw gateway to activate)",
1304
- });
1305
- }
1306
-
1307
- const legacyHookState = await probeOpenclawHookState({
1308
- home,
1309
- trackerDir: context.trackerDir,
1310
- env: process.env,
1311
- });
1312
- if (legacyHookState?.configured || legacyHookState?.linked || legacyHookState?.enabled) {
1313
- summary.push({
1314
- label: "OpenClaw Hook (legacy)",
1315
- status: "updated",
1316
- detail: "Will remove legacy command hook during migration",
1317
- });
1318
- }
1319
-
1320
- const codeProbe = await probeFile(context.codeConfigPath);
1321
- if (codeProbe.exists) {
1322
- const existing = await readEveryCodeNotify(context.codeConfigPath);
1323
- const matches = arraysEqual(existing, context.codeNotifyCmd);
1324
- summary.push({
1325
- label: "Every Code",
1326
- status: matches ? "set" : "updated",
1327
- detail: matches ? "Already configured" : "Will update config",
1328
- });
1329
- } else {
1330
- summary.push({ label: "Every Code", status: "skipped", detail: renderSkipDetail(codeProbe) });
1331
- }
1332
-
1333
- return summary;
1334
- }
1335
-
1336
- function renderSkipDetail(probe) {
1337
- if (!probe || probe.reason === "missing") return "Config not found";
1338
- if (probe.reason === "permission-denied") return "Permission denied";
1339
- if (probe.reason === "not-file") return "Invalid config";
1340
- return "Unavailable";
1341
- }
1342
-
1343
- function arraysEqual(a, b) {
1344
- if (!Array.isArray(a) || !Array.isArray(b)) return false;
1345
- if (a.length !== b.length) return false;
1346
- for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1347
- return true;
1348
- }
1349
-
1350
- async function shouldRepairCodexNotify({ currentNotify, expectedNotify, notifyOriginalPath }) {
1351
- if (!Array.isArray(currentNotify) || currentNotify.length === 0) {
1352
- return { repair: true, captureOriginal: true, replaceOriginal: true };
1353
- }
1354
- if (arraysEqual(currentNotify, expectedNotify)) {
1355
- return { repair: false, reason: "already-set" };
1356
- }
1357
- if (isTokenUsageNotify(currentNotify, expectedNotify)) {
1358
- return { repair: true, captureOriginal: false };
1359
- }
1360
- if (
1361
- isSkyComputerUseNotify(currentNotify)
1362
- && containsNestedTokenUsageNotify(currentNotify, expectedNotify)
1363
- ) {
1364
- return { repair: false, reason: "already-wrapped" };
1365
- }
1366
- if (isSkyComputerUseNotify(currentNotify)) {
1367
- return { repair: true, captureOriginal: true, replaceOriginal: true };
1368
- }
1369
-
1370
- const original = await readJson(notifyOriginalPath);
1371
- const originalNotify = Array.isArray(original?.notify) ? original.notify : null;
1372
- if (arraysEqual(currentNotify, originalNotify)) {
1373
- return { repair: true, captureOriginal: true, replaceOriginal: false };
1374
- }
1375
-
1376
- return { repair: false, reason: "external-notify" };
1377
- }
1378
-
1379
- function shouldReplaceStoredOriginalNotify(currentNotify, expectedNotify) {
1380
- if (isTokenUsageNotify(currentNotify, expectedNotify)) return false;
1381
- return currentNotify === null || Array.isArray(currentNotify);
1382
- }
1383
-
1384
- // Single source of truth for "is this notify command ours?", shared with
1385
- // status (configured check) and uninstall (restore gate) so the three cannot
1386
- // drift apart. See isManagedNotifyCmd in src/lib/codex-config.js.
1387
- function isTokenUsageNotify(cmd, expectedNotify) {
1388
- return isManagedNotifyCmd(cmd, expectedNotify);
1389
- }
1390
-
1391
- function isSkyComputerUseNotify(cmd) {
1392
- if (!Array.isArray(cmd)) return false;
1393
- return cmd.some((part) => typeof part === "string" && part.includes("SkyComputerUseClient"));
1394
- }
1395
-
1396
- function containsNestedTokenUsageNotify(cmd, expectedNotify) {
1397
- if (!Array.isArray(cmd)) return false;
1398
- for (const part of cmd) {
1399
- if (typeof part !== "string") continue;
1400
- try {
1401
- if (isTokenUsageNotify(JSON.parse(part), expectedNotify)) return true;
1402
- } catch (_) {}
1403
- }
1404
- return false;
1405
- }
1406
-
1407
- function parseArgs(argv) {
1408
- const out = {
1409
- baseUrl: null,
1410
- dashboardUrl: null,
1411
- anonKey: null,
1412
- anonKeyFile: null,
1413
- email: null,
1414
- password: null,
1415
- deviceName: null,
1416
- linkCode: null,
1417
- noAuth: false,
1418
- noOpen: false,
1419
- yes: false,
1420
- dryRun: false,
1421
- };
1422
-
1423
- for (let i = 0; i < argv.length; i++) {
1424
- const a = argv[i];
1425
- if (a === "--base-url") out.baseUrl = argv[++i] || null;
1426
- else if (a === "--dashboard-url") out.dashboardUrl = argv[++i] || null;
1427
- else if (a === "--anon-key") out.anonKey = argv[++i] || null;
1428
- else if (a === "--anon-key-file") out.anonKeyFile = argv[++i] || null;
1429
- else if (a === "--email") out.email = argv[++i] || null;
1430
- else if (a === "--password") out.password = argv[++i] || null;
1431
- else if (a === "--device-name") out.deviceName = argv[++i] || null;
1432
- else if (a === "--link-code") out.linkCode = argv[++i] || null;
1433
- else if (a === "--no-auth") out.noAuth = true;
1434
- else if (a === "--no-open") out.noOpen = true;
1435
- else if (a === "--yes") out.yes = true;
1436
- else if (a === "--dry-run") out.dryRun = true;
1437
- else throw new Error(`Unknown option: ${a}`);
1438
- }
1439
- return out;
1440
- }
1441
-
1442
- function sleep(ms) {
1443
- if (!ms || ms <= 0) return Promise.resolve();
1444
- return new Promise((resolve) => setTimeout(resolve, ms));
1445
- }
1446
-
1447
- function normalizePlatform(value) {
1448
- if (value === "darwin") return "macos";
1449
- if (value === "win32") return "windows";
1450
- if (value === "linux") return "linux";
1451
- return "unknown";
1452
- }
1453
-
1454
- function buildNotifyHandler({ trackerDir, packageName }) {
1455
- // Keep this file dependency-free: Node built-ins only.
1456
- // It must never block Codex; it spawns sync in the background and exits 0.
1457
- const queueSignalPath = path.join(trackerDir, "notify.signal");
1458
- const originalPath = path.join(trackerDir, "codex_notify_original.json");
1459
- const fallbackPkg = packageName || "tokenusage-cli";
1460
- const trackerBinPath = path.join(trackerDir, "app", "bin", "tracker.js");
1461
-
1462
- return `#!/usr/bin/env node
1463
- 'use strict';
1464
-
1465
- const fs = require('node:fs');
1466
- const os = require('node:os');
1467
- const path = require('node:path');
1468
- const cp = require('node:child_process');
1469
-
1470
- const rawArgs = process.argv.slice(2);
1471
- let source = 'codex';
1472
- const payloadArgs = [];
1473
- for (let i = 0; i < rawArgs.length; i++) {
1474
- const arg = rawArgs[i];
1475
- if (arg === '--source') {
1476
- source = rawArgs[i + 1] || source;
1477
- i += 1;
1478
- continue;
1479
- }
1480
- if (arg.startsWith('--source=')) {
1481
- source = arg.slice('--source='.length) || source;
1482
- continue;
1483
- }
1484
- payloadArgs.push(arg);
1485
- }
1486
-
1487
- const trackerDir = ${JSON.stringify(trackerDir)};
1488
- const signalPath = ${JSON.stringify(queueSignalPath)};
1489
- const codexOriginalPath = ${JSON.stringify(originalPath)};
1490
- const acodeOriginalPath = ${JSON.stringify(path.join(trackerDir, "acode_notify_original.json"))};
1491
- const codeOriginalPath = ${JSON.stringify(path.join(trackerDir, "code_notify_original.json"))};
1492
- const trackerBinPath = ${JSON.stringify(trackerBinPath)};
1493
- const depsMarkerPath = path.join(trackerDir, 'app', 'bin', 'tracker.js');
1494
- const fallbackPkg = ${JSON.stringify(fallbackPkg)};
1495
- const selfPath = path.resolve(__filename);
1496
- const home = os.homedir();
1497
- const debugLogPath = path.join(trackerDir, 'notify.debug.jsonl');
1498
- const debugEnabled = ['1', 'true'].includes((process.env.TOKENUSAGE_NOTIFY_DEBUG || '').toLowerCase());
1499
- const debugMaxBytesRaw = Number.parseInt(process.env.TOKENUSAGE_NOTIFY_DEBUG_MAX_BYTES || '', 10);
1500
- const debugMaxBytes = Number.isFinite(debugMaxBytesRaw) && debugMaxBytesRaw > 0
1501
- ? debugMaxBytesRaw
1502
- : 1_000_000;
1503
-
1504
- try {
1505
- fs.mkdirSync(trackerDir, { recursive: true });
1506
- fs.writeFileSync(signalPath, new Date().toISOString(), { encoding: 'utf8' });
1507
- } catch (_) {}
1508
-
1509
- if (debugEnabled) {
1510
- try {
1511
- let size = 0;
1512
- try {
1513
- size = fs.statSync(debugLogPath).size;
1514
- } catch (err) {
1515
- if (err && err.code !== 'ENOENT') throw err;
1516
- }
1517
- if (size < debugMaxBytes) {
1518
- const entry = {
1519
- ts: new Date().toISOString(),
1520
- source,
1521
- cwd: process.cwd()
1522
- };
1523
- fs.appendFileSync(debugLogPath, JSON.stringify(entry) + os.EOL, 'utf8');
1524
- }
1525
- } catch (_) {}
1526
- }
1527
-
1528
- // Throttle spawn: at most once per 20 seconds.
1529
- try {
1530
- const throttlePath = path.join(trackerDir, 'sync.throttle');
1531
- const now = Date.now();
1532
- let last = 0;
1533
- try { last = Number(fs.readFileSync(throttlePath, 'utf8')) || 0; } catch (_) {}
1534
- if (now - last > 20_000) {
1535
- try { fs.writeFileSync(throttlePath, String(now), 'utf8'); } catch (_) {}
1536
- const hasLocalRuntime = fs.existsSync(trackerBinPath);
1537
- const hasLocalDeps = fs.existsSync(depsMarkerPath);
1538
- const syncArgs = ['sync', '--auto', '--from-notify', '--source', source];
1539
- if (hasLocalRuntime && hasLocalDeps) {
1540
- spawnDetached([process.execPath, trackerBinPath, ...syncArgs]);
1541
- } else {
1542
- spawnDetached(['npx', '--yes', fallbackPkg, ...syncArgs]);
1543
- }
1544
- }
1545
- } catch (_) {}
1546
-
1547
- // Chain the existing Codex, AStudio, or Every Code notify hook.
1548
- try {
1549
- const originalPath =
1550
- source === 'every-code'
1551
- ? codeOriginalPath
1552
- : source === 'acode'
1553
- ? acodeOriginalPath
1554
- : source === 'claude' || source === 'opencode' || source === 'gemini' || source === 'codebuddy' || source === 'workbuddy' || source === 'workbuddy-ai'
1555
- ? null
1556
- : codexOriginalPath;
1557
- if (originalPath) {
1558
- const original = JSON.parse(fs.readFileSync(originalPath, 'utf8'));
1559
- const cmd = Array.isArray(original?.notify) ? original.notify : null;
1560
- if (cmd && cmd.length > 0 && !isSelfNotify(cmd) && shouldChainNotify(cmd)) {
1561
- const args = cmd.slice(1);
1562
- if (payloadArgs.length > 0 && !containsSequence(args, payloadArgs)) {
1563
- args.push(...payloadArgs);
1564
- }
1565
- spawnDetached([cmd[0], ...args]);
1566
- }
1567
- }
1568
- } catch (_) {}
1569
-
1570
- process.exit(0);
1571
-
1572
- function spawnDetached(argv) {
1573
- try {
1574
- const child = cp.spawn(argv[0], argv.slice(1), {
1575
- detached: true,
1576
- windowsHide: true,
1577
- stdio: 'ignore',
1578
- env: process.env
1579
- });
1580
- child.unref();
1581
- } catch (_) {}
1582
- }
1583
-
1584
- function resolveMaybeHome(p, baseDir = null) {
1585
- if (typeof p !== 'string') return null;
1586
- if (p.startsWith('~/')) return path.join(home, p.slice(2));
1587
- if (p.startsWith('~\\\\')) return path.join(home, p.slice(2));
1588
- if (path.isAbsolute(p)) return p;
1589
- return path.resolve(baseDir || process.cwd(), p);
1590
- }
1591
-
1592
- function isSelfNotify(cmd) {
1593
- for (const part of cmd) {
1594
- if (typeof part !== 'string') continue;
1595
- if (!part.includes('notify.cjs')) continue;
1596
- const resolved = resolveMaybeHome(part);
1597
- if (resolved && isSelfNotifyPath(resolved)) return true;
1598
- try {
1599
- const nested = JSON.parse(part);
1600
- if (Array.isArray(nested) && isSelfNotify(nested)) return true;
1601
- } catch (_) {}
1602
- }
1603
- return false;
1604
- }
1605
-
1606
- function isSelfNotifyPath(resolved) {
1607
- if (resolved === selfPath) return true;
1608
- // selfPath is realpath-resolved by Node; stored paths may reach the same
1609
- // file through a symlink (e.g. a symlinked home directory).
1610
- try {
1611
- if (fs.realpathSync(resolved) === selfPath) return true;
1612
- } catch (_) {}
1613
- // Any notify.cjs under a .tokenusage dir is ours (matches the repair-time
1614
- // isTokenUsageNotify heuristic), even if that copy no longer exists.
1615
- return resolved.replace(/\\\\/g, '/').includes('/.tokenusage/');
1616
- }
1617
-
1618
- function shouldChainNotify(cmd) {
1619
- if (!Array.isArray(cmd) || cmd.length === 0) return false;
1620
- if (!isRunnableCommand(cmd[0])) return false;
1621
- return hasRunnableInterpreterTarget(cmd);
1622
- }
1623
-
1624
- function isRunnableCommand(command, baseDir = null) {
1625
- if (typeof command !== 'string' || command.length === 0) return false;
1626
- const explicitPath = isExplicitPath(command);
1627
- if (!explicitPath) return true;
1628
- const resolved = resolveMaybeHome(command, baseDir);
1629
- if (!resolved) return false;
1630
- try {
1631
- fs.accessSync(resolved, fs.constants.X_OK);
1632
- return true;
1633
- } catch (_) {
1634
- return false;
1635
- }
1636
- }
1637
-
1638
- function hasRunnableInterpreterTarget(cmd) {
1639
- const normalized = normalizeInterpreterCommand(cmd);
1640
- const interpreterCmd = normalized?.cmd;
1641
- if (!interpreterCmd || interpreterCmd.length === 0) return false;
1642
- const targetIndex = findInterpreterTargetIndex(interpreterCmd);
1643
- if (targetIndex == null) {
1644
- const command = interpreterCmd[0];
1645
- if (!isExplicitPath(command)) return true;
1646
- return isRunnableCommand(command, normalized.cwd);
1647
- }
1648
- if (targetIndex === -2) return true;
1649
- if (targetIndex === -1) return false;
1650
- const target = interpreterCmd[targetIndex];
1651
- if (!isExplicitPath(target)) return false;
1652
- const targetCwd = isBunCommand(interpreterCmd[0])
1653
- ? findBunScriptCwd(interpreterCmd, 1, normalized.cwd)
1654
- : normalized.cwd;
1655
- return isReadablePath(target, targetCwd);
1656
- }
1657
-
1658
- function normalizeInterpreterCommand(cmd) {
1659
- if (!isEnvCommand(cmd[0])) return { cmd, cwd: null };
1660
- return extractEnvCommand(cmd);
1661
- }
1662
-
1663
- function findInterpreterTargetIndex(cmd) {
1664
- const command = cmd[0];
1665
- if (isNodeCommand(command)) {
1666
- return findNodeLikeScriptIndex(cmd, 1);
1667
- }
1668
- if (isBunCommand(command)) {
1669
- return findBunScriptIndex(cmd, 1);
1670
- }
1671
- if (isDenoCommand(command)) {
1672
- return findDenoScriptIndex(cmd, 1);
1673
- }
1674
- return null;
1675
- }
1676
-
1677
- function isEnvCommand(command) {
1678
- const base = commandBase(command);
1679
- return base === 'env';
1680
- }
1681
-
1682
- function extractEnvCommand(cmd) {
1683
- return normalizeEnvArgs(cmd.slice(1));
1684
- }
1685
-
1686
- function normalizeEnvArgs(args, cwd = null) {
1687
- for (let i = 0; i < args.length; i++) {
1688
- const arg = args[i];
1689
- if (typeof arg !== 'string' || arg.length === 0) return null;
1690
- if (arg === '-' || arg === '--ignore-environment' || isEnvValuelessShortOption(arg)) continue;
1691
- if (arg === '--') return normalizeEnvCommandOperands(args.slice(i + 1), cwd);
1692
- if (arg === '-S' || arg === '--split-string') {
1693
- const split = splitEnvString(args[i + 1]);
1694
- if (!split) return null;
1695
- return normalizeEnvArgs(split.concat(args.slice(i + 2)), cwd);
1696
- }
1697
- if (arg.startsWith('--split-string=')) {
1698
- const split = splitEnvString(arg.slice('--split-string='.length));
1699
- if (!split) return null;
1700
- return normalizeEnvArgs(split.concat(args.slice(i + 1)), cwd);
1701
- }
1702
- if (arg === '-u' || arg === '--unset') {
1703
- i += 1;
1704
- continue;
1705
- }
1706
- if (arg.startsWith('--unset=')) continue;
1707
- if (arg === '-C' || arg === '--chdir') {
1708
- const next = args[i + 1];
1709
- if (typeof next !== 'string' || next.length === 0) return null;
1710
- cwd = resolveMaybeHome(next, cwd);
1711
- i += 1;
1712
- continue;
1713
- }
1714
- if (arg.startsWith('--chdir=')) {
1715
- const dir = arg.slice('--chdir='.length);
1716
- if (dir.length === 0) return null;
1717
- cwd = resolveMaybeHome(dir, cwd);
1718
- continue;
1719
- }
1720
- if (isEnvValueOption(arg)) {
1721
- i += 1;
1722
- continue;
1723
- }
1724
- if (isEnvInlineValueOption(arg)) continue;
1725
- if (arg.startsWith('-')) return null;
1726
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) continue;
1727
- return { cmd: args.slice(i), cwd };
1728
- }
1729
- return null;
1730
- }
1731
-
1732
- function normalizeEnvCommandOperands(args, cwd) {
1733
- for (let i = 0; i < args.length; i++) {
1734
- const arg = args[i];
1735
- if (typeof arg !== 'string' || arg.length === 0) return null;
1736
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) continue;
1737
- if (arg.startsWith('-')) return null;
1738
- return { cmd: args.slice(i), cwd };
1739
- }
1740
- return null;
1741
- }
1742
-
1743
- function isEnvValuelessShortOption(arg) {
1744
- return /^-[0iv]+$/.test(arg);
1745
- }
1746
-
1747
- function isEnvValueOption(arg) {
1748
- return arg === '-P' || arg === '--path';
1749
- }
1750
-
1751
- function isEnvInlineValueOption(arg) {
1752
- return (
1753
- arg.startsWith('--path=')
1754
- );
1755
- }
1756
-
1757
- function splitEnvString(value) {
1758
- if (typeof value !== 'string' || value.length === 0) return null;
1759
- const parts = [];
1760
- let current = '';
1761
- let quote = null;
1762
- let escaped = false;
1763
- for (let i = 0; i < value.length; i++) {
1764
- const ch = value[i];
1765
- if (escaped) {
1766
- current += ch;
1767
- escaped = false;
1768
- continue;
1769
- }
1770
- if (ch === '\\\\' && quote !== "'") {
1771
- escaped = true;
1772
- continue;
1773
- }
1774
- if (quote) {
1775
- if (ch === quote) quote = null;
1776
- else current += ch;
1777
- continue;
1778
- }
1779
- if (ch === '"' || ch === "'") {
1780
- quote = ch;
1781
- continue;
1782
- }
1783
- if (/\\s/.test(ch)) {
1784
- if (current.length > 0) {
1785
- parts.push(current);
1786
- current = '';
1787
- }
1788
- continue;
1789
- }
1790
- current += ch;
1791
- }
1792
- if (escaped || quote) return null;
1793
- if (current.length > 0) parts.push(current);
1794
- return parts.length > 0 ? parts : null;
1795
- }
1796
-
1797
- function isNodeCommand(command) {
1798
- const base = commandBase(command);
1799
- return base === 'node';
1800
- }
1801
-
1802
- function isBunCommand(command) {
1803
- const base = commandBase(command);
1804
- return base === 'bun';
1805
- }
1806
-
1807
- function isDenoCommand(command) {
1808
- const base = commandBase(command);
1809
- return base === 'deno';
1810
- }
1811
-
1812
- function commandBase(command) {
1813
- if (typeof command !== 'string' || command.length === 0) return '';
1814
- const posixBase = path.basename(command);
1815
- const winBase = path.win32.basename(command);
1816
- const base = winBase.length < posixBase.length ? winBase : posixBase;
1817
- return base.replace(/\\.exe$/i, '').toLowerCase();
1818
- }
1819
-
1820
- function findNodeLikeScriptIndex(cmd, startIndex) {
1821
- for (let i = startIndex; i < cmd.length; i++) {
1822
- const arg = cmd[i];
1823
- if (typeof arg !== 'string' || arg.length === 0) return -1;
1824
- if (arg === '-e' || arg === '--eval' || arg === '-p' || arg === '--print') return -2;
1825
- if (arg.startsWith('--eval=') || arg.startsWith('--print=')) return -2;
1826
- if (isNodeLikeOptionWithValue(arg)) {
1827
- i += 1;
1828
- continue;
1829
- }
1830
- if (hasInlineNodeLikeOptionValue(arg)) continue;
1831
- if (isNodeLikeValuelessOption(arg)) continue;
1832
- if (arg.startsWith('-')) return -1;
1833
- return i;
1834
- }
1835
- return -1;
1836
- }
1837
-
1838
- function findBunScriptIndex(cmd, startIndex) {
1839
- for (let i = startIndex; i < cmd.length; i++) {
1840
- const arg = cmd[i];
1841
- if (typeof arg !== 'string' || arg.length === 0) return -1;
1842
- if (arg === '-e' || arg === '--eval' || arg === '-p' || arg === '--print') return -2;
1843
- if (arg.startsWith('--eval=') || arg.startsWith('--print=')) return -2;
1844
- if (isBunOptionWithValue(arg)) {
1845
- i += 1;
1846
- continue;
1847
- }
1848
- if (hasInlineBunOptionValue(arg)) continue;
1849
- if (isBunValuelessOption(arg)) continue;
1850
- if (arg === 'run') {
1851
- return findScriptAfterSubcommand(cmd, i + 1, 'bun');
1852
- }
1853
- if (arg.startsWith('-')) return -1;
1854
- return i;
1855
- }
1856
- return -1;
1857
- }
1858
-
1859
- function findBunScriptCwd(cmd, startIndex, baseDir = null) {
1860
- let cwd = baseDir;
1861
- for (let i = startIndex; i < cmd.length; i++) {
1862
- const arg = cmd[i];
1863
- if (typeof arg !== 'string' || arg.length === 0) return cwd;
1864
- if (arg === '--cwd') {
1865
- const next = cmd[i + 1];
1866
- if (typeof next !== 'string' || next.length === 0) return cwd;
1867
- cwd = resolveMaybeHome(next, cwd);
1868
- i += 1;
1869
- continue;
1870
- }
1871
- if (arg.startsWith('--cwd=')) {
1872
- const next = arg.slice('--cwd='.length);
1873
- if (next.length === 0) return cwd;
1874
- cwd = resolveMaybeHome(next, cwd);
1875
- continue;
1876
- }
1877
- if (arg === '-e' || arg === '--eval' || arg === '-p' || arg === '--print') return cwd;
1878
- if (arg.startsWith('--eval=') || arg.startsWith('--print=')) return cwd;
1879
- if (isBunOptionWithValue(arg)) {
1880
- i += 1;
1881
- continue;
1882
- }
1883
- if (hasInlineBunOptionValue(arg)) continue;
1884
- if (isBunValuelessOption(arg)) continue;
1885
- if (arg === 'run') return findBunScriptCwd(cmd, i + 1, cwd);
1886
- return cwd;
1887
- }
1888
- return cwd;
1889
- }
1890
-
1891
- function findDenoScriptIndex(cmd, startIndex) {
1892
- for (let i = startIndex; i < cmd.length; i++) {
1893
- const arg = cmd[i];
1894
- if (typeof arg !== 'string' || arg.length === 0) return -1;
1895
- if (arg === 'eval') return -2;
1896
- if (arg === 'run' || arg === 'test' || arg === 'bench' || arg === 'check') {
1897
- return findScriptAfterSubcommand(cmd, i + 1, 'deno');
1898
- }
1899
- if (isDenoOptionWithValue(arg)) {
1900
- i += 1;
1901
- continue;
1902
- }
1903
- if (hasInlineDenoOptionValue(arg)) continue;
1904
- if (isDenoValuelessOption(arg)) continue;
1905
- if (arg.startsWith('-')) return -1;
1906
- return i;
1907
- }
1908
- return -1;
1909
- }
1910
-
1911
- function findScriptAfterSubcommand(cmd, startIndex, runtime) {
1912
- for (let i = startIndex; i < cmd.length; i++) {
1913
- const arg = cmd[i];
1914
- if (typeof arg !== 'string' || arg.length === 0) return -1;
1915
- if (runtime === 'bun' && isBunOptionWithValue(arg)) {
1916
- i += 1;
1917
- continue;
1918
- }
1919
- if (runtime === 'deno' && isDenoOptionWithValue(arg)) {
1920
- i += 1;
1921
- continue;
1922
- }
1923
- if (runtime === 'bun' && hasInlineBunOptionValue(arg)) continue;
1924
- if (runtime === 'deno' && hasInlineDenoOptionValue(arg)) continue;
1925
- if (runtime === 'bun' && isBunValuelessOption(arg)) continue;
1926
- if (runtime === 'deno' && isDenoValuelessOption(arg)) continue;
1927
- if (arg.startsWith('-')) return -1;
1928
- return i;
1929
- }
1930
- return -1;
1931
- }
1932
-
1933
- function isNodeLikeOptionWithValue(arg) {
1934
- return (
1935
- arg === '-C' ||
1936
- arg === '-r' ||
1937
- arg === '--conditions' ||
1938
- arg === '--debug-port' ||
1939
- arg === '--disable-warning' ||
1940
- arg === '--env-file' ||
1941
- arg === '--env-file-if-exists' ||
1942
- arg === '--experimental-config-file' ||
1943
- arg === '--experimental-loader' ||
1944
- arg === '--import' ||
1945
- arg === '--inspect-publish-uid' ||
1946
- arg === '--loader' ||
1947
- arg === '--localstorage-file' ||
1948
- arg === '--require'
1949
- );
1950
- }
1951
-
1952
- function hasInlineNodeLikeOptionValue(arg) {
1953
- return (
1954
- arg.startsWith('--conditions=') ||
1955
- arg.startsWith('--debug-port=') ||
1956
- arg.startsWith('--disable-warning=') ||
1957
- arg.startsWith('--env-file=') ||
1958
- arg.startsWith('--env-file-if-exists=') ||
1959
- arg.startsWith('--experimental-config-file=') ||
1960
- arg.startsWith('--experimental-loader=') ||
1961
- arg.startsWith('--import=') ||
1962
- arg.startsWith('--inspect-publish-uid=') ||
1963
- arg.startsWith('--loader=') ||
1964
- arg.startsWith('--localstorage-file=') ||
1965
- arg.startsWith('--require=')
1966
- );
1967
- }
1968
-
1969
- function isNodeLikeValuelessOption(arg) {
1970
- return (
1971
- arg === '-' ||
1972
- arg === '-c' ||
1973
- arg === '--' ||
1974
- arg === '--check' ||
1975
- arg === '--cpu-prof' ||
1976
- arg === '--enable-source-maps' ||
1977
- arg === '--expose-gc' ||
1978
- arg === '--inspect' ||
1979
- arg === '--inspect-brk' ||
1980
- arg === '--inspect-wait' ||
1981
- arg === '--no-deprecation' ||
1982
- arg === '--no-warnings' ||
1983
- arg === '--preserve-symlinks' ||
1984
- arg === '--preserve-symlinks-main' ||
1985
- arg === '--throw-deprecation' ||
1986
- arg === '--trace-deprecation' ||
1987
- arg === '--trace-warnings'
1988
- );
1989
- }
1990
-
1991
- function isBunOptionWithValue(arg) {
1992
- return (
1993
- arg === '-c' ||
1994
- arg === '-d' ||
1995
- arg === '-F' ||
1996
- arg === '-l' ||
1997
- arg === '-r' ||
1998
- arg === '--config' ||
1999
- arg === '--conditions' ||
2000
- arg === '--console-depth' ||
2001
- arg === '--cpu-prof-dir' ||
2002
- arg === '--cpu-prof-interval' ||
2003
- arg === '--cpu-prof-name' ||
2004
- arg === '--cwd' ||
2005
- arg === '--define' ||
2006
- arg === '--dns-result-order' ||
2007
- arg === '--drop' ||
2008
- arg === '--elide-lines' ||
2009
- arg === '--env-file' ||
2010
- arg === '--extension-order' ||
2011
- arg === '--feature' ||
2012
- arg === '--fetch-preconnect' ||
2013
- arg === '--filter' ||
2014
- arg === '--import' ||
2015
- arg === '--inspect' ||
2016
- arg === '--inspect-brk' ||
2017
- arg === '--inspect-wait' ||
2018
- arg === '--install' ||
2019
- arg === '--jsx-factory' ||
2020
- arg === '--jsx-fragment' ||
2021
- arg === '--jsx-import-source' ||
2022
- arg === '--jsx-runtime' ||
2023
- arg === '--loader' ||
2024
- arg === '--main-fields' ||
2025
- arg === '--max-http-header-size' ||
2026
- arg === '--port' ||
2027
- arg === '--preload' ||
2028
- arg === '--require' ||
2029
- arg === '--shell' ||
2030
- arg === '--title' ||
2031
- arg === '--tsconfig-override' ||
2032
- arg === '--unhandled-rejections' ||
2033
- arg === '--user-agent'
2034
- );
2035
- }
2036
-
2037
- function hasInlineBunOptionValue(arg) {
2038
- return (
2039
- arg.startsWith('--config=') ||
2040
- arg.startsWith('--conditions=') ||
2041
- arg.startsWith('--console-depth=') ||
2042
- arg.startsWith('--cpu-prof-dir=') ||
2043
- arg.startsWith('--cpu-prof-interval=') ||
2044
- arg.startsWith('--cpu-prof-name=') ||
2045
- arg.startsWith('--cwd=') ||
2046
- arg.startsWith('--define=') ||
2047
- arg.startsWith('--dns-result-order=') ||
2048
- arg.startsWith('--drop=') ||
2049
- arg.startsWith('--elide-lines=') ||
2050
- arg.startsWith('--env-file=') ||
2051
- arg.startsWith('--extension-order=') ||
2052
- arg.startsWith('--feature=') ||
2053
- arg.startsWith('--fetch-preconnect=') ||
2054
- arg.startsWith('--filter=') ||
2055
- arg.startsWith('--import=') ||
2056
- arg.startsWith('--inspect=') ||
2057
- arg.startsWith('--inspect-brk=') ||
2058
- arg.startsWith('--inspect-wait=') ||
2059
- arg.startsWith('--install=') ||
2060
- arg.startsWith('--jsx-factory=') ||
2061
- arg.startsWith('--jsx-fragment=') ||
2062
- arg.startsWith('--jsx-import-source=') ||
2063
- arg.startsWith('--jsx-runtime=') ||
2064
- arg.startsWith('--loader=') ||
2065
- arg.startsWith('--main-fields=') ||
2066
- arg.startsWith('--max-http-header-size=') ||
2067
- arg.startsWith('--port=') ||
2068
- arg.startsWith('--preload=') ||
2069
- arg.startsWith('--require=') ||
2070
- arg.startsWith('--shell=') ||
2071
- arg.startsWith('--title=') ||
2072
- arg.startsWith('--tsconfig-override=') ||
2073
- arg.startsWith('--unhandled-rejections=') ||
2074
- arg.startsWith('--user-agent=')
2075
- );
2076
- }
2077
-
2078
- function isBunValuelessOption(arg) {
2079
- return (
2080
- arg === '-b' ||
2081
- arg === '-i' ||
2082
- arg === '--bun' ||
2083
- arg === '--cpu-prof' ||
2084
- arg === '--cpu-prof-md' ||
2085
- arg === '--expose-gc' ||
2086
- arg === '--heap-prof' ||
2087
- arg === '--heap-prof-md' ||
2088
- arg === '--hot' ||
2089
- arg === '--if-present' ||
2090
- arg === '--ignore-dce-annotations' ||
2091
- arg === '--jsx-side-effects' ||
2092
- arg === '--no-addons' ||
2093
- arg === '--no-clear-screen' ||
2094
- arg === '--no-deprecation' ||
2095
- arg === '--no-env-file' ||
2096
- arg === '--no-exit-on-error' ||
2097
- arg === '--no-install' ||
2098
- arg === '--no-macros' ||
2099
- arg === '--parallel' ||
2100
- arg === '--prefer-latest' ||
2101
- arg === '--prefer-offline' ||
2102
- arg === '--preserve-symlinks' ||
2103
- arg === '--preserve-symlinks-main' ||
2104
- arg === '--redis-preconnect' ||
2105
- arg === '--sequential' ||
2106
- arg === '--silent' ||
2107
- arg === '--smol' ||
2108
- arg === '--sql-preconnect' ||
2109
- arg === '--throw-deprecation' ||
2110
- arg === '--use-bundled-ca' ||
2111
- arg === '--use-openssl-ca' ||
2112
- arg === '--use-system-ca' ||
2113
- arg === '--watch' ||
2114
- arg === '--workspaces' ||
2115
- arg === '--zero-fill-buffers'
2116
- );
2117
- }
2118
-
2119
- function isDenoOptionWithValue(arg) {
2120
- return (
2121
- arg === '-c' ||
2122
- arg === '--cert' ||
2123
- arg === '--conditions' ||
2124
- arg === '--config' ||
2125
- arg === '--cpu-prof-dir' ||
2126
- arg === '--cpu-prof-interval' ||
2127
- arg === '--cpu-prof-name' ||
2128
- arg === '--ext' ||
2129
- arg === '--import-map' ||
2130
- arg === '--location' ||
2131
- arg === '--lock' ||
2132
- arg === '--minimum-dependency-age' ||
2133
- arg === '--preload' ||
2134
- arg === '--require' ||
2135
- arg === '--seed'
2136
- );
2137
- }
2138
-
2139
- function hasInlineDenoOptionValue(arg) {
2140
- return (
2141
- arg.startsWith('--cert=') ||
2142
- arg.startsWith('--conditions=') ||
2143
- arg.startsWith('--config=') ||
2144
- arg.startsWith('--coverage=') ||
2145
- arg.startsWith('--cpu-prof-dir=') ||
2146
- arg.startsWith('--cpu-prof-interval=') ||
2147
- arg.startsWith('--cpu-prof-name=') ||
2148
- arg.startsWith('--env-file=') ||
2149
- arg.startsWith('--ext=') ||
2150
- arg.startsWith('--import-map=') ||
2151
- arg.startsWith('--location=') ||
2152
- arg.startsWith('--lock=') ||
2153
- arg.startsWith('--minimum-dependency-age=') ||
2154
- arg.startsWith('--node-modules-dir=') ||
2155
- arg.startsWith('--preload=') ||
2156
- arg.startsWith('--require=') ||
2157
- arg.startsWith('--seed=') ||
2158
- arg.startsWith('--vendor=') ||
2159
- arg.startsWith('--v8-flags=') ||
2160
- /^--(allow|deny|ignore)-[A-Za-z-]+=/.test(arg) ||
2161
- arg.startsWith('--permission-set=') ||
2162
- arg.startsWith('--reload=') ||
2163
- arg.startsWith('--tunnel=') ||
2164
- arg.startsWith('--watch=') ||
2165
- arg.startsWith('--watch-exclude=') ||
2166
- arg.startsWith('--watch-hmr=')
2167
- );
2168
- }
2169
-
2170
- function isDenoValuelessOption(arg) {
2171
- return (
2172
- arg === '-A' ||
2173
- arg === '-P' ||
2174
- arg === '-q' ||
2175
- arg === '-r' ||
2176
- arg === '-t' ||
2177
- arg === '--allow-all' ||
2178
- arg === '--cached-only' ||
2179
- arg === '--coverage' ||
2180
- arg === '--cpu-prof' ||
2181
- arg === '--cpu-prof-flamegraph' ||
2182
- arg === '--cpu-prof-md' ||
2183
- arg === '--env-file' ||
2184
- arg === '--frozen' ||
2185
- arg === '--no-check' ||
2186
- arg === '--no-clear-screen' ||
2187
- arg === '--no-code-cache' ||
2188
- arg === '--no-config' ||
2189
- arg === '--no-lock' ||
2190
- arg === '--no-npm' ||
2191
- arg === '--no-prompt' ||
2192
- arg === '--no-remote' ||
2193
- arg === '--node-modules-dir' ||
2194
- arg === '--quiet' ||
2195
- arg === '--reload' ||
2196
- arg === '--tunnel' ||
2197
- arg === '--unstable' ||
2198
- arg === '--v8-flags' ||
2199
- arg === '--vendor' ||
2200
- arg === '--watch' ||
2201
- arg === '--watch-exclude' ||
2202
- arg === '--watch-hmr' ||
2203
- /^-[RWINESA]$/.test(arg) ||
2204
- /^--(allow|deny|ignore)-[A-Za-z-]+$/.test(arg) ||
2205
- arg === '--permission-set'
2206
- );
2207
- }
2208
-
2209
- function isReadablePath(target, baseDir = null) {
2210
- const resolved = resolveMaybeHome(target, baseDir);
2211
- if (!resolved) return false;
2212
- try {
2213
- fs.accessSync(resolved, fs.constants.R_OK);
2214
- return true;
2215
- } catch (_) {
2216
- return false;
2217
- }
2218
- }
2219
-
2220
- function isExplicitPath(value) {
2221
- if (typeof value !== 'string' || value.length === 0) return false;
2222
- return value.startsWith('~/') || value.startsWith('~\\\\') || value.includes('/') || value.includes('\\\\') || /^[A-Za-z]:/.test(value);
2223
- }
2224
-
2225
- function containsSequence(haystack, needle) {
2226
- if (!Array.isArray(haystack) || !Array.isArray(needle) || needle.length === 0) return false;
2227
- if (needle.length > haystack.length) return false;
2228
- for (let i = 0; i <= haystack.length - needle.length; i++) {
2229
- let matched = true;
2230
- for (let j = 0; j < needle.length; j++) {
2231
- if (haystack[i + j] !== needle[j]) {
2232
- matched = false;
2233
- break;
2234
- }
2235
- }
2236
- if (matched) return true;
2237
- }
2238
- return false;
2239
- }
2240
- `;
2241
- }
2242
-
2243
- module.exports = {
2244
- cmdInit,
2245
- buildNotifyHandler,
2246
- installLocalTrackerApp,
2247
- repairCodexNotifyIntegration,
2248
- repairAcodeNotifyIntegration,
2249
- repairRuntimeIntegrations,
2250
- applyIntegrationSetup,
2251
- };
2252
-
2253
- async function probeFile(p) {
2254
- try {
2255
- const st = await fs.stat(p);
2256
- if (st.isFile()) return { exists: true, reason: null };
2257
- return { exists: false, reason: "not-file" };
2258
- } catch (e) {
2259
- if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return { exists: false, reason: "missing" };
2260
- if (e?.code === "EACCES" || e?.code === "EPERM")
2261
- return { exists: false, reason: "permission-denied" };
2262
- return { exists: false, reason: "error", code: e?.code || "unknown" };
2263
- }
2264
- }
2265
-
2266
- async function isDir(p) {
2267
- try {
2268
- const st = await fs.stat(p);
2269
- return st.isDirectory();
2270
- } catch (_e) {
2271
- return false;
2272
- }
2273
- }
2274
-
2275
- async function installLocalTrackerApp({ appDir }) {
2276
- // Test-only escape hatch: skip the ~10 MB runtime copy (src + dashboard/dist +
2277
- // node_modules) when a test only exercises hook/config/notify wiring. Copying
2278
- // the bundle per test case dominates the init test suite's wall time. Tests
2279
- // that assert on the copied runtime simply leave this unset.
2280
- if (process.env.TOKENUSAGE_SKIP_LOCAL_RUNTIME_COPY === "1") return;
2281
- // Copy the current package's runtime (bin + src) into ~/.tokenusage so notify can run sync without npx.
2282
- const packageRoot = path.resolve(__dirname, "../..");
2283
- const srcFrom = path.join(packageRoot, "src");
2284
- const binFrom = path.join(packageRoot, "bin", "tracker.js");
2285
- const packageJsonFrom = path.join(packageRoot, "package.json");
2286
- const nodeModulesFrom = path.join(packageRoot, "node_modules");
2287
- const dashboardDistFrom = path.join(packageRoot, "dashboard", "dist");
2288
-
2289
- // When running from the installed local runtime (or when appDir is symlinked to this package),
2290
- // source and destination resolve to the same place. Do not delete appDir in that case.
2291
- if (await pathsPointToSameLocation(packageRoot, appDir)) {
2292
- return;
2293
- }
2294
-
2295
- const srcTo = path.join(appDir, "src");
2296
- const binToDir = path.join(appDir, "bin");
2297
- const binTo = path.join(binToDir, "tracker.js");
2298
- const nodeModulesTo = path.join(appDir, "node_modules");
2299
- const dashboardDistTo = path.join(appDir, "dashboard", "dist");
2300
-
2301
- await fs.rm(appDir, { recursive: true, force: true }).catch(() => {});
2302
- await ensureDir(appDir);
2303
- await fs.cp(srcFrom, srcTo, { recursive: true });
2304
- await ensureDir(binToDir);
2305
- await fs.copyFile(binFrom, binTo);
2306
- await fs.chmod(binTo, 0o755).catch(() => {});
2307
- await fs.copyFile(packageJsonFrom, path.join(appDir, "package.json")).catch(() => {});
2308
- if (await isDir(dashboardDistFrom)) {
2309
- await fs.cp(dashboardDistFrom, dashboardDistTo, { recursive: true });
2310
- }
2311
- await copyRuntimeDependencies({ from: nodeModulesFrom, to: nodeModulesTo });
2312
- }
2313
-
2314
- async function pathsPointToSameLocation(a, b) {
2315
- const aReal = await safeRealpath(a);
2316
- const bReal = await safeRealpath(b);
2317
- if (aReal && bReal) return aReal === bReal;
2318
- return path.resolve(a) === path.resolve(b);
2319
- }
2320
-
2321
- async function safeRealpath(p) {
2322
- try {
2323
- return await fs.realpath(p);
2324
- } catch (_err) {
2325
- return null;
2326
- }
2327
- }
2328
-
2329
- // Run the first sync inline so we can show the user their real token total
2330
- // immediately. Caps wall-time at FIRST_SYNC_TIMEOUT_MS — past that we let the
2331
- // child continue detached and surrender the wait. Returns aggregate stats
2332
- // derived from queue.jsonl after the wait window closes.
2333
- const FIRST_SYNC_TIMEOUT_MS = 15_000;
2334
-
2335
- async function runFirstSyncAndRead({ trackerBinPath, trackerDir, packageName }) {
2336
- // Test-only escape hatch: skip spawning a real `sync --drain` subprocess when
2337
- // a test only exercises init wiring. Returns the same shape derived from an
2338
- // (empty) queue so callers behave identically without the ~1s spawn per case.
2339
- if (process.env.TOKENUSAGE_SKIP_FIRST_SYNC === "1") {
2340
- return readFirstSyncTotals(trackerDir);
2341
- }
2342
- const fallbackPkg = packageName || "tokenusage-cli";
2343
- const argv = ["sync", "--auto", "--drain"];
2344
- const hasLocalRuntime = typeof trackerBinPath === "string" && fssync.existsSync(trackerBinPath);
2345
- const cmd = hasLocalRuntime
2346
- ? [process.execPath, trackerBinPath, ...argv]
2347
- : ["npx", "--yes", fallbackPkg, ...argv];
2348
-
2349
- await new Promise((resolve) => {
2350
- let settled = false;
2351
- let timer = null;
2352
- const settle = () => {
2353
- if (settled) return;
2354
- settled = true;
2355
- if (timer) clearTimeout(timer);
2356
- resolve();
2357
- };
2358
- let child;
2359
- try {
2360
- child = cp.spawn(cmd[0], cmd.slice(1), {
2361
- // detached so we can let it keep running past our timeout — the user
2362
- // still gets data later via dashboard auto-refresh.
2363
- detached: true,
2364
- stdio: "ignore",
2365
- env: process.env,
2366
- });
2367
- } catch (err) {
2368
- if (isDebugEnabled()) {
2369
- process.stderr.write(`first-sync spawn failed: ${err?.message || err}\n`);
2370
- }
2371
- settle();
2372
- return;
2373
- }
2374
- child.on("error", () => settle());
2375
- child.on("exit", () => settle());
2376
- timer = setTimeout(() => {
2377
- try {
2378
- child.unref();
2379
- } catch (_e) {}
2380
- settle();
2381
- }, FIRST_SYNC_TIMEOUT_MS);
2382
- });
2383
-
2384
- return readFirstSyncTotals(trackerDir);
2385
- }
2386
-
2387
- function readFirstSyncTotals(trackerDir) {
2388
- const queuePath = path.join(trackerDir, "queue.jsonl");
2389
- let raw;
2390
- try {
2391
- raw = fssync.readFileSync(queuePath, "utf8");
2392
- } catch (_e) {
2393
- return { totalTokens: 0, sources: [] };
2394
- }
2395
- let totalTokens = 0;
2396
- const sources = new Set();
2397
- // Each sync appends cumulative totals per (source, model, hour_start); keep
2398
- // the last entry per bucket to match what the dashboard shows.
2399
- const latest = new Map();
2400
- for (const line of raw.split("\n")) {
2401
- const trimmed = line.trim();
2402
- if (!trimmed) continue;
2403
- try {
2404
- const row = JSON.parse(trimmed);
2405
- const key = `${row.source || ""}|${row.model || ""}|${row.hour_start || ""}`;
2406
- latest.set(key, row);
2407
- } catch {
2408
- // skip malformed
2409
- }
2410
- }
2411
- for (const row of latest.values()) {
2412
- const n = Number(row.total_tokens);
2413
- if (Number.isFinite(n) && n > 0) totalTokens += n;
2414
- if (row.source) sources.add(row.source);
2415
- }
2416
- return { totalTokens, sources: Array.from(sources) };
2417
- }
2418
-
2419
- async function copyRuntimeDependencies({ from, to }) {
2420
- try {
2421
- const st = await fs.stat(from);
2422
- if (!st.isDirectory()) return;
2423
- } catch (_e) {
2424
- return;
2425
- }
2426
-
2427
- try {
2428
- await fs.cp(from, to, { recursive: true });
2429
- } catch (_e) {
2430
- // Best-effort: missing dependencies will fall back to npx at notify time.
2431
- }
2432
- }
2433
-
2434
- function isDebugEnabled() {
2435
- return process.env.TOKENUSAGE_DEBUG === "1";
2436
- }
1
+ const os = require("node:os");
2
+ const path = require("node:path");
3
+ const fs = require("node:fs/promises");
4
+ const fssync = require("node:fs");
5
+ const cp = require("node:child_process");
6
+ const crypto = require("node:crypto");
7
+
8
+ const {
9
+ ensureDir,
10
+ writeFileAtomic,
11
+ readJson,
12
+ writeJson,
13
+ chmod600IfPossible,
14
+ } = require("../lib/fs");
15
+ const { resolveMimoNativeDbPath } = require("../lib/install-resolver");
16
+ const { resolveDumateDbPaths } = require("../lib/dumate");
17
+ const { expandHome } = require("../lib/scan-roots");
18
+ const { prompt, promptHidden } = require("../lib/prompt");
19
+ const {
20
+ upsertCodexNotify,
21
+ upsertAcodeNotify,
22
+ upsertEveryCodeNotify,
23
+ readCodexNotify,
24
+ readAcodeNotify,
25
+ readEveryCodeNotify,
26
+ buildCodexNotifyCmd,
27
+ buildAcodeNotifyCmd,
28
+ buildEveryCodeNotifyCmd,
29
+ isManagedNotifyCmd,
30
+ } = require("../lib/codex-config");
31
+ const {
32
+ upsertClaudeHook,
33
+ upsertClaudeUsageHooks,
34
+ buildClaudeHookCommand,
35
+ buildHookCommand,
36
+ isClaudeHookConfigured,
37
+ areClaudeUsageHooksConfigured,
38
+ } = require("../lib/claude-config");
39
+ const {
40
+ resolveGeminiConfigDir,
41
+ resolveGeminiSettingsPath,
42
+ buildGeminiHookCommand,
43
+ upsertGeminiHook,
44
+ isGeminiHookConfigured,
45
+ } = require("../lib/gemini-config");
46
+ const {
47
+ resolveOpencodeConfigDir,
48
+ upsertOpencodePlugin,
49
+ isOpencodePluginInstalled,
50
+ } = require("../lib/opencode-config");
51
+ const { isCursorInstalled, extractCursorSessionToken } = require("../lib/cursor-config");
52
+ const { removeOpenclawHookConfig, probeOpenclawHookState } = require("../lib/openclaw-hook");
53
+ const {
54
+ installOpenclawSessionPlugin,
55
+ probeOpenclawSessionPluginState,
56
+ } = require("../lib/openclaw-session-plugin");
57
+ const {
58
+ resolveGrokHome,
59
+ resolveGrokHooksDir,
60
+ upsertGrokHook,
61
+ probeGrokHookState,
62
+ removeGrokHook,
63
+ GROK_HOOK_FILENAME
64
+ } = require("../lib/grok-hook");
65
+ const {
66
+ upsertOmpHook,
67
+ probeOmpHookState,
68
+ } = require("../lib/omp-hook");
69
+ const { resolveTrackerPaths } = require("../lib/tracker-paths");
70
+ const {
71
+ resolveOmpAgentDir,
72
+ resolvePiAgentDir,
73
+ piAgentDirCollidesWithOmp,
74
+ resolvePrimeAgentDir,
75
+ resolveMinimaxCodeSessionsDir,
76
+ resolveCommandCodeHome,
77
+ resolveLmstudioLogFiles,
78
+ resolveUnslothDbPath,
79
+ resolveAnythingllmDbPath,
80
+ resolveDevinDbPath,
81
+ resolveReasonixHome,
82
+ resolveMuseHome,
83
+ resolveTraeStoragePath,
84
+ } = require("../lib/rollout");
85
+ const { resolveRuntimeConfig, DEFAULT_BASE_URL, normalizeInstanceBaseUrl, assertInsforgeRuntime,
86
+ clearDeviceIdentity, resetInstanceState } = require("../lib/runtime-config");
87
+ const { registerWindowsScheduledTask, TASK_NAME } = require("../lib/scheduled-task");
88
+ const {
89
+ BOLD,
90
+ DIM,
91
+ CYAN,
92
+ RESET,
93
+ color,
94
+ isInteractive,
95
+ promptMenu,
96
+ createSpinner,
97
+ } = require("../lib/cli-ui");
98
+ const { renderLocalReport, renderAuthTransition, renderSuccessBox } = require("../lib/init-flow");
99
+ const { maybeShowStarCta } = require("../lib/star-cta");
100
+
101
+ const ASCII_LOGO = [
102
+ "████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗",
103
+ "╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║",
104
+ " ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║",
105
+ " ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║",
106
+ " ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║",
107
+ " ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝",
108
+ " ████████╗██████╗ █████╗ ██████╗██╗ ██╗███████╗██████╗",
109
+ " ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗",
110
+ " ██║ ██████╔╝███████║██║ █████╔╝ █████╗ ██████╔╝",
111
+ " ██║ ██╔══██╗██╔══██║██║ ██╔═██╗ ██╔══╝ ██╔══██╗",
112
+ " ██║ ██║ ██║██║ ██║╚██████╗██║ ██╗███████╗██║ ██║",
113
+ " ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝",
114
+ ].join("\n");
115
+
116
+ const DIVIDER = "----------------------------------------------";
117
+ // NOTE: the effective default dashboard/base URL lives in lib/runtime-config
118
+ // (DEFAULT_DASHBOARD_URL = the production deployment). A local copy here went
119
+ // stale when the deployment moved (audit fix: the dead hardcoded landing
120
+ // domain was removed and guarded against by test/audit-fixes.test.js) —
121
+ // resolve it through runtime-config, never re-declare it.
122
+
123
+ // Single source of truth for the welcome screen's provider count + sample list.
124
+ // test/discovery-metadata.test.js keeps this aligned with public tool copy.
125
+ const SUPPORTED_PROVIDERS = [
126
+ "Claude Code",
127
+ "Codex CLI",
128
+ "AStudio",
129
+ "Cursor",
130
+ "Gemini CLI",
131
+ "Antigravity",
132
+ "Kiro",
133
+ "OpenCode",
134
+ "OpenClaw",
135
+ "Every Code",
136
+ "Hermes Agent",
137
+ "GitHub Copilot",
138
+ "Kimi Code",
139
+ "CodeBuddy",
140
+ "WorkBuddy",
141
+ "WorkBuddy AI",
142
+ "Grok Build",
143
+ "oh-my-pi",
144
+ "OmO",
145
+ "pi",
146
+ "Dots",
147
+ "Prime Agent",
148
+ "Craft Agents",
149
+ "Reasonix",
150
+ "Muse Code",
151
+ "Kilo CLI",
152
+ "Kilo Code",
153
+ "Roo Code",
154
+ "Zed Agent",
155
+ "Goose",
156
+ "Droid",
157
+ "Mimo",
158
+ "DuMate",
159
+ "ZCode",
160
+ "Qoder",
161
+ "AnythingLLM Desktop",
162
+ "Claude Science",
163
+ "DeepSeek Harness",
164
+ "TRAE Work CN",
165
+ "TRAE",
166
+ "LM Studio",
167
+ "Unsloth Studio",
168
+ "Devin CLI",
169
+ "Cline",
170
+ "MiniMax Code",
171
+ "Command Code",
172
+ ];
173
+
174
+ async function cmdInit(argv, options = {}) {
175
+ const opts = parseArgs(argv);
176
+ const home = options.home || os.homedir();
177
+ if (opts.anonKeyFile) opts.anonKey = (await fs.readFile(opts.anonKeyFile, "utf8")).trim();
178
+
179
+ const { rootDir, trackerDir, binDir } = await resolveTrackerPaths({ home });
180
+
181
+ const configPath = path.join(trackerDir, "config.json");
182
+ const notifyOriginalPath = path.join(trackerDir, "codex_notify_original.json");
183
+ const linkCodeStatePath = path.join(trackerDir, "link_code_state.json");
184
+
185
+ const existingConfig = await readJson(configPath);
186
+ const runtime = resolveRuntimeConfig({
187
+ cli: { baseUrl: opts.baseUrl, dashboardUrl: opts.dashboardUrl, anonKey: opts.anonKey },
188
+ config: existingConfig || {},
189
+ env: process.env,
190
+ });
191
+ assertInsforgeRuntime(runtime);
192
+ const notifyPath = path.join(binDir, "notify.cjs");
193
+ const appDir = path.join(trackerDir, "app");
194
+ const trackerBinPath = path.join(appDir, "bin", "tracker.js");
195
+
196
+ renderWelcome();
197
+
198
+ if (opts.dryRun) {
199
+ process.stdout.write(`${color("Dry run: preview only (no changes applied).", DIM)}\n\n`);
200
+ }
201
+
202
+ if (isInteractive() && !opts.yes && !opts.dryRun) {
203
+ const choice = await promptMenu({
204
+ message: "? Proceed with installation?",
205
+ options: ["Yes, configure my environment", "No, exit"],
206
+ defaultIndex: 0,
207
+ });
208
+ const normalizedChoice = String(choice || "")
209
+ .trim()
210
+ .toLowerCase();
211
+ if (normalizedChoice.startsWith("no") || normalizedChoice.includes("exit")) {
212
+ process.stdout.write("Setup cancelled.\n");
213
+ return;
214
+ }
215
+ }
216
+
217
+ if (opts.dryRun) {
218
+ const preview = await buildDryRunSummary({
219
+ opts,
220
+ home,
221
+ trackerDir,
222
+ notifyPath,
223
+ runtime,
224
+ });
225
+ renderLocalReport({ summary: preview.summary, isDryRun: true });
226
+ renderAccountNotLinked({ context: "dry-run" });
227
+ return;
228
+ }
229
+
230
+ const spinner = createSpinner({ text: "Analyzing and configuring local environment..." });
231
+ spinner.start();
232
+ let setup;
233
+ try {
234
+ setup = await runSetup({
235
+ opts,
236
+ home,
237
+ trackerDir,
238
+ binDir,
239
+ configPath,
240
+ notifyOriginalPath,
241
+ linkCodeStatePath,
242
+ notifyPath,
243
+ appDir,
244
+ trackerBinPath,
245
+ runtime,
246
+ existingConfig,
247
+ });
248
+ } catch (err) {
249
+ spinner.stop();
250
+ throw err;
251
+ }
252
+ spinner.stop();
253
+
254
+ renderLocalReport({ summary: setup.summary, isDryRun: false });
255
+
256
+ // Run first sync inline (with a generous timeout) so we can render the
257
+ // *actual* token total in the success message — the aha moment. If the
258
+ // sync exceeds the timeout we surrender the wait but leave it running, so
259
+ // the dashboard still picks up data shortly after.
260
+ const ahaSpinner = createSpinner({ text: "Running first sync..." });
261
+ ahaSpinner.start();
262
+ let firstSync = null;
263
+ try {
264
+ firstSync = await runFirstSyncAndRead({
265
+ trackerBinPath,
266
+ trackerDir,
267
+ packageName: "tokenusage",
268
+ });
269
+ } catch (err) {
270
+ const msg = err && err.message ? err.message : "unknown error";
271
+ process.stderr.write(`Initial sync issue: ${msg}\n`);
272
+ } finally {
273
+ ahaSpinner.stop();
274
+ }
275
+
276
+ renderLocalSuccess({ firstSync });
277
+ await maybeShowStarCta({ trackerDir });
278
+ }
279
+
280
+ function renderWelcome() {
281
+ const providerCount = SUPPORTED_PROVIDERS.length;
282
+ // Show first 5 by name for grounding, then "+N more" so the line stays one row.
283
+ const previewNames = SUPPORTED_PROVIDERS.slice(0, 5).join(", ");
284
+ const remaining = providerCount - 5;
285
+ const providerLine =
286
+ remaining > 0
287
+ ? `${previewNames} +${remaining} more`
288
+ : previewNames;
289
+ process.stdout.write(
290
+ [
291
+ ASCII_LOGO,
292
+ "",
293
+ `${BOLD}Token Tracker${RESET} ${color("Local-first usage across " + providerCount + " AI CLIs", DIM)}`,
294
+ DIVIDER,
295
+ `${CYAN}Nothing leaves your machine — token counts only, never prompts or responses.${RESET}`,
296
+ DIVIDER,
297
+ "",
298
+ ` Tracks: ${providerLine}`,
299
+ ` Dashboard: http://localhost:7680`,
300
+ "",
301
+ ].join("\n"),
302
+ );
303
+ }
304
+
305
+ function renderLocalSuccess({ firstSync } = {}) {
306
+ const lines = ["", `${BOLD}Setup complete!${RESET}`, ""];
307
+
308
+ if (firstSync && firstSync.totalTokens > 0) {
309
+ const tokens = firstSync.totalTokens.toLocaleString("en-US");
310
+ const sourceCount = firstSync.sources.length;
311
+ const sourceWord = sourceCount === 1 ? "provider" : "providers";
312
+ lines.push(
313
+ ` ${BOLD}${tokens}${RESET} tokens tracked across ${sourceCount} ${sourceWord}.`,
314
+ );
315
+ } else {
316
+ lines.push(
317
+ " No usage history yet — run any AI CLI and tokens appear within a minute.",
318
+ );
319
+ }
320
+
321
+ lines.push(
322
+ "",
323
+ ` Dashboard: ${CYAN}http://localhost:7680${RESET}`,
324
+ "",
325
+ );
326
+ process.stdout.write(lines.join("\n"));
327
+ }
328
+
329
+ function renderAccountNotLinked({ context } = {}) {
330
+ if (context === "dry-run") {
331
+ process.stdout.write(
332
+ [
333
+ "",
334
+ "Dry run complete. Run init without --dry-run to apply changes.",
335
+ "",
336
+ ].join("\n"),
337
+ );
338
+ return;
339
+ }
340
+ renderLocalSuccess();
341
+ }
342
+
343
+ function shouldUseBrowserAuth({ deviceToken, opts }) {
344
+ if (deviceToken) return false;
345
+ if (opts.noAuth) return false;
346
+ if (opts.linkCode) return false;
347
+ if (opts.email || opts.password) return false;
348
+ return true;
349
+ }
350
+
351
+ async function buildDryRunSummary({ opts, home, trackerDir, notifyPath, runtime }) {
352
+ const deviceToken = runtime?.deviceToken || null;
353
+ const pendingBrowserAuth = shouldUseBrowserAuth({ deviceToken, opts });
354
+ const context = buildIntegrationTargets({ home, trackerDir, notifyPath });
355
+ const summary = await previewIntegrations({ context });
356
+ return { summary, pendingBrowserAuth, deviceToken };
357
+ }
358
+
359
+ async function runSetup({
360
+ opts,
361
+ home,
362
+ trackerDir,
363
+ binDir,
364
+ configPath,
365
+ notifyOriginalPath,
366
+ linkCodeStatePath,
367
+ notifyPath,
368
+ appDir,
369
+ trackerBinPath,
370
+ runtime,
371
+ existingConfig,
372
+ }) {
373
+ await ensureDir(trackerDir);
374
+ await ensureDir(binDir);
375
+ let deviceToken = runtime?.deviceToken || null;
376
+ let deviceId = existingConfig?.deviceId || null;
377
+ const installedAt = existingConfig?.installedAt || new Date().toISOString();
378
+ let pendingBrowserAuth = false;
379
+
380
+ await installLocalTrackerApp({ appDir });
381
+
382
+ const existingPlainConfig =
383
+ existingConfig && typeof existingConfig === "object" && !Array.isArray(existingConfig)
384
+ ? existingConfig
385
+ : {};
386
+ const previousRuntime = resolveRuntimeConfig({ config: existingPlainConfig, env: {} });
387
+ const changedInstance = normalizeInstanceBaseUrl(previousRuntime.baseUrl) !== runtime.baseUrl ||
388
+ previousRuntime.anonKey !== runtime.anonKey;
389
+ if (changedInstance) {
390
+ resetInstanceState(trackerDir);
391
+ deviceToken = null; deviceId = null;
392
+ }
393
+ const config = {
394
+ ...(changedInstance ? clearDeviceIdentity(existingPlainConfig) : existingPlainConfig),
395
+ installedAt,
396
+ // Keep a persisted legacy URL until the first sync. sync owns the migration
397
+ // lock and must reset the upload offset/backoff before removing this marker;
398
+ // rewriting it here would skip the historical replay permanently.
399
+ baseUrl: opts.baseUrl || existingPlainConfig.baseUrl || DEFAULT_BASE_URL,
400
+ };
401
+ if (changedInstance || opts.dashboardUrl) {
402
+ config.dashboardUrl = runtime.dashboardUrl;
403
+ }
404
+ if (changedInstance || opts.anonKey || runtime.sources.anonKey === "env") config.anonKey = runtime.anonKey;
405
+ if (runtime.baseUrl !== DEFAULT_BASE_URL) {
406
+ config.baseUrl = runtime.baseUrl;
407
+ config.dashboardUrl = runtime.dashboardUrl;
408
+ }
409
+ // §2.11 run-report persistence (default on; --run-report=off disables the
410
+ // per-run telemetry POST).
411
+ if (opts.runReport != null) config.runReport = opts.runReport;
412
+
413
+ await writeJson(configPath, config);
414
+ await chmod600IfPossible(configPath);
415
+
416
+ await writeNotifyHandler({ trackerDir, notifyPath });
417
+
418
+ const summary = await applyIntegrationSetup({
419
+ home,
420
+ trackerDir,
421
+ notifyPath,
422
+ notifyOriginalPath,
423
+ dryRun: Boolean(opts.dryRun),
424
+ });
425
+
426
+ // Windows scheduled task takeover (0.2.0): hourly auto sync behind a hidden
427
+ // VBS runner — no conhost flash, no shell redirect (sync self-logs to the
428
+ // rolling logs/sync.log). Best-effort; pause/resume toggle this task.
429
+ if (opts.noTask) {
430
+ summary.push({
431
+ label: "Scheduled task",
432
+ status: "skipped",
433
+ detail: "Skipped (--no-task); auto syncs stay manual",
434
+ });
435
+ } else {
436
+ const taskOutcome = registerWindowsScheduledTask({
437
+ binDir,
438
+ cliJs: path.resolve(__dirname, "..", "cli.js"),
439
+ });
440
+ summary.push({
441
+ label: "Scheduled task",
442
+ status: taskOutcome.registered ? "installed" : "skipped",
443
+ detail: taskOutcome.registered
444
+ ? `${TASK_NAME}: hourly, hidden window (pause/resume toggles it)`
445
+ : taskOutcome.reason === "not_windows"
446
+ ? "Windows-only; use cron/launchd + `tokenusage pause` elsewhere"
447
+ : `Not registered: ${taskOutcome.reason}`,
448
+ });
449
+ }
450
+
451
+ return {
452
+ summary,
453
+ pendingBrowserAuth,
454
+ deviceToken,
455
+ deviceId,
456
+ installedAt,
457
+ };
458
+ }
459
+
460
+ async function writeNotifyHandler({ trackerDir, binDir, notifyPath, packageName = "tokenusage-cli" }) {
461
+ const resolvedNotifyPath =
462
+ notifyPath || path.join(binDir || path.join(path.dirname(trackerDir), "bin"), "notify.cjs");
463
+ await ensureDir(path.dirname(resolvedNotifyPath));
464
+ await writeFileAtomic(
465
+ resolvedNotifyPath,
466
+ buildNotifyHandler({ trackerDir, packageName }),
467
+ );
468
+ await fs.chmod(resolvedNotifyPath, 0o755).catch(() => {});
469
+ return resolvedNotifyPath;
470
+ }
471
+
472
+ async function repairCodexNotifyIntegration({ home = os.homedir(), trackerDir, binDir, safeMode = true } = {}) {
473
+ const paths = trackerDir && binDir ? { trackerDir, binDir } : await resolveTrackerPaths({ home });
474
+ const resolvedTrackerDir = trackerDir || paths.trackerDir;
475
+ const resolvedBinDir = binDir || paths.binDir;
476
+ const notifyPath = await writeNotifyHandler({
477
+ trackerDir: resolvedTrackerDir,
478
+ binDir: resolvedBinDir,
479
+ });
480
+ const context = buildIntegrationTargets({
481
+ home,
482
+ trackerDir: resolvedTrackerDir,
483
+ notifyPath,
484
+ });
485
+ const codexProbe = await probeFile(context.codexConfigPath);
486
+ if (!codexProbe.exists) {
487
+ return { changed: false, skippedReason: "config-missing", notifyPath };
488
+ }
489
+
490
+ const currentNotify = await readCodexNotify(context.codexConfigPath);
491
+ if (arraysEqual(currentNotify, context.notifyCmd)) {
492
+ return { changed: false, skippedReason: null, notifyPath };
493
+ }
494
+
495
+ const repairDecision = safeMode
496
+ ? await shouldRepairCodexNotify({
497
+ currentNotify,
498
+ expectedNotify: context.notifyCmd,
499
+ notifyOriginalPath: context.notifyOriginalPath,
500
+ })
501
+ : { repair: true, captureOriginal: true, replaceOriginal: false };
502
+ if (!repairDecision.repair) {
503
+ return { changed: false, skippedReason: repairDecision.reason || "external-notify", notifyPath };
504
+ }
505
+
506
+ const result = await upsertCodexNotify({
507
+ codexConfigPath: context.codexConfigPath,
508
+ notifyCmd: context.notifyCmd,
509
+ notifyOriginalPath: context.notifyOriginalPath,
510
+ captureOriginal: repairDecision.captureOriginal,
511
+ replaceOriginal: repairDecision.replaceOriginal,
512
+ });
513
+ return { ...result, skippedReason: null, notifyPath };
514
+ }
515
+
516
+ async function repairAcodeNotifyIntegration({ home = os.homedir(), trackerDir, binDir, safeMode = true } = {}) {
517
+ const paths = trackerDir && binDir ? { trackerDir, binDir } : await resolveTrackerPaths({ home });
518
+ const resolvedTrackerDir = trackerDir || paths.trackerDir;
519
+ const resolvedBinDir = binDir || paths.binDir;
520
+ const notifyPath = await writeNotifyHandler({
521
+ trackerDir: resolvedTrackerDir,
522
+ binDir: resolvedBinDir,
523
+ });
524
+ const context = buildIntegrationTargets({
525
+ home,
526
+ trackerDir: resolvedTrackerDir,
527
+ notifyPath,
528
+ });
529
+ const acodeProbe = await probeFile(context.acodeConfigPath);
530
+ if (!acodeProbe.exists) {
531
+ return { changed: false, skippedReason: "config-missing", notifyPath };
532
+ }
533
+
534
+ const currentNotify = await readAcodeNotify(context.acodeConfigPath);
535
+ if (arraysEqual(currentNotify, context.acodeNotifyCmd)) {
536
+ return { changed: false, skippedReason: null, notifyPath };
537
+ }
538
+
539
+ const repairDecision = safeMode
540
+ ? await shouldRepairCodexNotify({
541
+ currentNotify,
542
+ expectedNotify: context.acodeNotifyCmd,
543
+ notifyOriginalPath: context.acodeNotifyOriginalPath,
544
+ })
545
+ : { repair: true, captureOriginal: true, replaceOriginal: false };
546
+ if (!repairDecision.repair) {
547
+ return { changed: false, skippedReason: repairDecision.reason || "external-notify", notifyPath };
548
+ }
549
+
550
+ const result = await upsertAcodeNotify({
551
+ acodeConfigPath: context.acodeConfigPath,
552
+ notifyCmd: context.acodeNotifyCmd,
553
+ notifyOriginalPath: context.acodeNotifyOriginalPath,
554
+ captureOriginal: repairDecision.captureOriginal,
555
+ replaceOriginal: repairDecision.replaceOriginal,
556
+ });
557
+ return { ...result, skippedReason: null, notifyPath };
558
+ }
559
+
560
+ async function repairRuntimeIntegrations({
561
+ home = os.homedir(),
562
+ trackerDir,
563
+ binDir,
564
+ safeMode = true,
565
+ } = {}) {
566
+ const paths = trackerDir && binDir ? { trackerDir, binDir } : await resolveTrackerPaths({ home });
567
+ const resolvedTrackerDir = trackerDir || paths.trackerDir;
568
+ const resolvedBinDir = binDir || paths.binDir;
569
+ const notifyPath = await writeNotifyHandler({
570
+ trackerDir: resolvedTrackerDir,
571
+ binDir: resolvedBinDir,
572
+ });
573
+ const context = buildIntegrationTargets({
574
+ home,
575
+ trackerDir: resolvedTrackerDir,
576
+ notifyPath,
577
+ });
578
+ const integrations = {};
579
+ const warnings = [];
580
+
581
+ const attempt = async (key, work) => {
582
+ try {
583
+ integrations[key] = await work();
584
+ } catch (error) {
585
+ integrations[key] = { changed: false, skippedReason: "repair-failed" };
586
+ warnings.push({ integration: key, error: error?.message || String(error) });
587
+ }
588
+ };
589
+
590
+ await attempt("codex", () => repairCodexNotifyIntegration({
591
+ home,
592
+ trackerDir: resolvedTrackerDir,
593
+ binDir: resolvedBinDir,
594
+ safeMode,
595
+ }));
596
+ await attempt("acode", () => repairAcodeNotifyIntegration({
597
+ home,
598
+ trackerDir: resolvedTrackerDir,
599
+ binDir: resolvedBinDir,
600
+ safeMode,
601
+ }));
602
+
603
+ const hookRepairs = [
604
+ ["claude", context.claudeDir, () => upsertClaudeUsageHooks({
605
+ settingsPath: context.claudeSettingsPath,
606
+ hookCommand: context.claudeHookCommand,
607
+ })],
608
+ ["gemini", context.geminiConfigDir, () => upsertGeminiHook({
609
+ settingsPath: context.geminiSettingsPath,
610
+ hookCommand: context.geminiHookCommand,
611
+ })],
612
+ ["codebuddy", context.codebuddyDir, () => upsertClaudeHook({
613
+ settingsPath: context.codebuddySettingsPath,
614
+ hookCommand: context.codebuddyHookCommand,
615
+ })],
616
+ ["workbuddy", context.workbuddyDir, () => upsertClaudeHook({
617
+ settingsPath: context.workbuddySettingsPath,
618
+ hookCommand: context.workbuddyHookCommand,
619
+ })],
620
+ ["workbuddy-ai", context.workbuddyAiDir, () => upsertClaudeHook({
621
+ settingsPath: context.workbuddyAiSettingsPath,
622
+ hookCommand: context.workbuddyAiHookCommand,
623
+ })],
624
+ ];
625
+ for (const [key, configDir, repair] of hookRepairs) {
626
+ if (await isDir(configDir)) await attempt(key, repair);
627
+ else integrations[key] = { changed: false, skippedReason: "config-missing" };
628
+ }
629
+
630
+ if (await isDir(context.opencodeConfigDir)) {
631
+ await attempt("opencode", () => upsertOpencodePlugin({
632
+ configDir: context.opencodeConfigDir,
633
+ notifyPath,
634
+ }));
635
+ } else {
636
+ integrations.opencode = { changed: false, skippedReason: "config-missing" };
637
+ }
638
+
639
+ return { notifyPath, integrations, warnings };
640
+ }
641
+
642
+ function buildIntegrationTargets({ home, trackerDir, notifyPath }) {
643
+ const codexHome = process.env.CODEX_HOME || path.join(home, ".codex");
644
+ const codexConfigPath = path.join(codexHome, "config.toml");
645
+ const acodeHome = process.env.TOKENUSAGE_ACODE_HOME || path.join(home, ".acode");
646
+ const acodeConfigPath = path.join(acodeHome, "config.toml");
647
+ const codeHome = process.env.CODE_HOME || path.join(home, ".code");
648
+ const codeConfigPath = path.join(codeHome, "config.toml");
649
+ const notifyOriginalPath = path.join(trackerDir, "codex_notify_original.json");
650
+ const acodeNotifyOriginalPath = path.join(trackerDir, "acode_notify_original.json");
651
+ const codeNotifyOriginalPath = path.join(trackerDir, "code_notify_original.json");
652
+ const notifyCmd = buildCodexNotifyCmd(notifyPath);
653
+ const acodeNotifyCmd = buildAcodeNotifyCmd(notifyPath);
654
+ const codeNotifyCmd = buildEveryCodeNotifyCmd(notifyPath);
655
+ const claudeDir = path.join(home, ".claude");
656
+ const claudeSettingsPath = path.join(claudeDir, "settings.json");
657
+ const claudeHookCommand = buildClaudeHookCommand(notifyPath);
658
+ // CodeBuddy CLI (Tencent) is a Claude-Code fork — same settings.json hook
659
+ // schema, same SessionEnd event. We install the same hook with a different
660
+ // --source token so notify.cjs / sync know which provider triggered.
661
+ const codebuddyDir = process.env.CODEBUDDY_HOME || path.join(home, ".codebuddy");
662
+ const codebuddySettingsPath = path.join(codebuddyDir, "settings.json");
663
+ const codebuddyHookCommand = buildHookCommand(notifyPath, "codebuddy");
664
+ // WorkBuddy CLI (Tencent) is the same Claude-Code-fork hook schema as CodeBuddy.
665
+ const workbuddyDir = process.env.WORKBUDDY_HOME || path.join(home, ".workbuddy");
666
+ const workbuddySettingsPath = path.join(workbuddyDir, "settings.json");
667
+ const workbuddyHookCommand = buildHookCommand(notifyPath, "workbuddy");
668
+ // WorkBuddy AI is the international build of the very same CLI. It keeps its
669
+ // data in a sibling home (~/.workbuddy-ai), so it needs its own hook install
670
+ // and its own --source token to be attributed separately from the CN build.
671
+ const workbuddyAiDir = expandHome(process.env.WORKBUDDY_AI_HOME, home) || path.join(home, ".workbuddy-ai");
672
+ const workbuddyAiSettingsPath = path.join(workbuddyAiDir, "settings.json");
673
+ const workbuddyAiHookCommand = buildHookCommand(notifyPath, "workbuddy-ai");
674
+ const geminiConfigDir = resolveGeminiConfigDir({ home, env: process.env });
675
+ const geminiSettingsPath = resolveGeminiSettingsPath({ configDir: geminiConfigDir });
676
+ const geminiHookCommand = buildGeminiHookCommand(notifyPath);
677
+ const opencodeConfigDir = resolveOpencodeConfigDir({ home, env: process.env });
678
+
679
+ return {
680
+ trackerDir,
681
+ codexConfigPath,
682
+ acodeConfigPath,
683
+ codeConfigPath,
684
+ notifyOriginalPath,
685
+ acodeNotifyOriginalPath,
686
+ codeNotifyOriginalPath,
687
+ notifyCmd,
688
+ acodeNotifyCmd,
689
+ codeNotifyCmd,
690
+ claudeDir,
691
+ claudeSettingsPath,
692
+ claudeHookCommand,
693
+ codebuddyDir,
694
+ codebuddySettingsPath,
695
+ codebuddyHookCommand,
696
+ workbuddyDir,
697
+ workbuddySettingsPath,
698
+ workbuddyHookCommand,
699
+ workbuddyAiDir,
700
+ workbuddyAiSettingsPath,
701
+ workbuddyAiHookCommand,
702
+ geminiConfigDir,
703
+ geminiSettingsPath,
704
+ geminiHookCommand,
705
+ opencodeConfigDir,
706
+ };
707
+ }
708
+
709
+ async function applyIntegrationSetup({
710
+ home,
711
+ trackerDir,
712
+ notifyPath,
713
+ notifyOriginalPath,
714
+ dryRun = false,
715
+ }) {
716
+ const context = buildIntegrationTargets({ home, trackerDir, notifyPath });
717
+ context.notifyOriginalPath = notifyOriginalPath;
718
+
719
+ const summary = [];
720
+
721
+ const codexProbe = await probeFile(context.codexConfigPath);
722
+ if (codexProbe.exists) {
723
+ const currentNotify = await readCodexNotify(context.codexConfigPath);
724
+ const result = await upsertCodexNotify({
725
+ codexConfigPath: context.codexConfigPath,
726
+ notifyCmd: context.notifyCmd,
727
+ notifyOriginalPath: context.notifyOriginalPath,
728
+ replaceOriginal: shouldReplaceStoredOriginalNotify(currentNotify, context.notifyCmd),
729
+ });
730
+ summary.push({
731
+ label: "Codex CLI",
732
+ status: result.changed ? "updated" : "set",
733
+ detail: result.changed ? "Updated config" : "Config already set",
734
+ });
735
+ } else {
736
+ summary.push({ label: "Codex CLI", status: "skipped", detail: renderSkipDetail(codexProbe) });
737
+ }
738
+
739
+ const acodeProbe = await probeFile(context.acodeConfigPath);
740
+ if (acodeProbe.exists) {
741
+ const currentNotify = await readAcodeNotify(context.acodeConfigPath);
742
+ const result = await upsertAcodeNotify({
743
+ acodeConfigPath: context.acodeConfigPath,
744
+ notifyCmd: context.acodeNotifyCmd,
745
+ notifyOriginalPath: context.acodeNotifyOriginalPath,
746
+ replaceOriginal: shouldReplaceStoredOriginalNotify(currentNotify, context.acodeNotifyCmd),
747
+ });
748
+ summary.push({
749
+ label: "AStudio",
750
+ status: result.changed ? "updated" : "set",
751
+ detail: result.changed ? "Updated config" : "Config already set",
752
+ });
753
+ } else {
754
+ summary.push({ label: "AStudio", status: "skipped", detail: renderSkipDetail(acodeProbe) });
755
+ }
756
+
757
+ const claudeDirExists = await isDir(context.claudeDir);
758
+ if (claudeDirExists) {
759
+ await upsertClaudeUsageHooks({
760
+ settingsPath: context.claudeSettingsPath,
761
+ hookCommand: context.claudeHookCommand,
762
+ });
763
+ summary.push({ label: "Claude", status: "installed", detail: "Hooks installed" });
764
+ } else {
765
+ summary.push({ label: "Claude", status: "skipped", detail: "Config not found" });
766
+ }
767
+
768
+ const geminiConfigExists = await isDir(context.geminiConfigDir);
769
+ if (geminiConfigExists) {
770
+ await upsertGeminiHook({
771
+ settingsPath: context.geminiSettingsPath,
772
+ hookCommand: context.geminiHookCommand,
773
+ });
774
+ summary.push({ label: "Gemini", status: "installed", detail: "Hooks installed" });
775
+ } else {
776
+ summary.push({ label: "Gemini", status: "skipped", detail: "Config not found" });
777
+ }
778
+
779
+ const opencodeResult = await upsertOpencodePlugin({
780
+ configDir: context.opencodeConfigDir,
781
+ notifyPath,
782
+ });
783
+ if (opencodeResult?.skippedReason === "config-missing") {
784
+ summary.push({ label: "Opencode Plugin", status: "skipped", detail: "Config not found" });
785
+ } else {
786
+ summary.push({
787
+ label: "Opencode Plugin",
788
+ status: opencodeResult?.changed ? "installed" : "set",
789
+ detail: "Plugin installed",
790
+ });
791
+ }
792
+
793
+ // Cursor (API-based, no hooks needed)
794
+ if (isCursorInstalled({ home })) {
795
+ const cursorAuth = extractCursorSessionToken({ home });
796
+ if (cursorAuth) {
797
+ summary.push({
798
+ label: "Cursor",
799
+ status: "detected",
800
+ detail: "Usage synced via Cursor API (no hooks needed)",
801
+ });
802
+ } else {
803
+ summary.push({
804
+ label: "Cursor",
805
+ status: "skipped",
806
+ detail: "Installed but not logged in (login in Cursor to enable)",
807
+ });
808
+ }
809
+ } else {
810
+ summary.push({ label: "Cursor", status: "skipped", detail: "Not installed" });
811
+ }
812
+
813
+ // Kimi: passive reader — no hook installation needed.
814
+ // Token Usage reads both legacy ~/.kimi/ and official ~/.kimi-code/ sessions.
815
+ {
816
+ const kimiHome = process.env.KIMI_HOME || path.join(home, ".kimi");
817
+ const kimiCodeHome = process.env.KIMI_CODE_HOME || path.join(home, ".kimi-code");
818
+ const fssync = require("node:fs");
819
+ if (fssync.existsSync(path.join(kimiHome, "sessions")) || fssync.existsSync(path.join(kimiCodeHome, "sessions"))) {
820
+ summary.push({ label: "Kimi Code", status: "detected", detail: "Passive reader (no hook needed)" });
821
+ }
822
+ }
823
+
824
+ // oh-my-pi: passive session scan always works; also install an optional
825
+ // notify extension so turn_end triggers sync --source omp near-real-time.
826
+ {
827
+ const fssyncLocal = require("node:fs");
828
+ const ompAgentDir = resolveOmpAgentDir(process.env);
829
+ const ompSessions = ompAgentDir && fssyncLocal.existsSync(path.join(ompAgentDir, "sessions"));
830
+ if (ompAgentDir && (ompSessions || fssyncLocal.existsSync(ompAgentDir))) {
831
+ if (dryRun) {
832
+ const probe = await probeOmpHookState({ home, trackerDir, env: process.env });
833
+ summary.push({
834
+ label: "oh-my-pi",
835
+ status: "detected",
836
+ detail: probe.configured
837
+ ? "Notify extension already installed (passive scan still runs)"
838
+ : "Will install notify extension + keep passive scan",
839
+ });
840
+ } else {
841
+ const result = await upsertOmpHook({ home, trackerDir, env: process.env });
842
+ if (result.written) {
843
+ summary.push({
844
+ label: "oh-my-pi",
845
+ status: "installed",
846
+ detail: `Notify extension → ${result.extensionPath} (passive scan still runs)`,
847
+ });
848
+ } else if (result.skippedReason === "unmanaged-extension-present") {
849
+ summary.push({
850
+ label: "oh-my-pi",
851
+ status: "skipped",
852
+ detail: "Existing unmanaged tokenusage-notify extension left untouched",
853
+ });
854
+ } else {
855
+ summary.push({
856
+ label: "oh-my-pi",
857
+ status: "detected",
858
+ detail: "Passive reader (notify extension not written)",
859
+ });
860
+ }
861
+ }
862
+ }
863
+ }
864
+
865
+ // pi (@mariozechner/pi-coding-agent): passive reader — no hook installation needed.
866
+ // Token Usage reads ~/.pi/agent/sessions/**/*.jsonl directly. Skip when its
867
+ // agent dir collides with omp's so the summary matches what sync will scan.
868
+ if (!piAgentDirCollidesWithOmp(process.env)) {
869
+ // Same win32 nullability as oh-my-pi above: resolvePiAgentDir is null when
870
+ // ~/.pi doesn't exist, so guard before joining.
871
+ const piAgentDir = resolvePiAgentDir(process.env);
872
+ if (piAgentDir && fssync.existsSync(path.join(piAgentDir, "sessions"))) {
873
+ summary.push({ label: "pi", status: "detected", detail: "Passive reader (no hook needed)" });
874
+ }
875
+ }
876
+
877
+ // Prime Agent: metadata-only passive reader — no hook installation needed.
878
+ {
879
+ const primeAgentDir = resolvePrimeAgentDir(process.env);
880
+ if (primeAgentDir && fssync.existsSync(path.join(primeAgentDir, "sessions"))) {
881
+ summary.push({ label: "Prime Agent", status: "detected", detail: "Passive usage reader (no hook needed)" });
882
+ }
883
+ }
884
+
885
+ // MiniMax Code: passive reader of ~/.minimax/v2/sessions — no hook installation needed.
886
+ {
887
+ const minimaxCodeSessionsDir = resolveMinimaxCodeSessionsDir(process.env);
888
+ if (minimaxCodeSessionsDir && fssync.existsSync(minimaxCodeSessionsDir)) {
889
+ summary.push({ label: "MiniMax Code", status: "detected", detail: "Passive usage reader (no hook needed)" });
890
+ }
891
+ }
892
+
893
+ // Command Code (`cmd`): passive reader of ~/.commandcode/projects — no hook
894
+ // installation needed, and none exists to install.
895
+ {
896
+ const commandCodeProjectsDir = path.join(resolveCommandCodeHome(process.env), "projects");
897
+ if (fssync.existsSync(commandCodeProjectsDir)) {
898
+ summary.push({ label: "Command Code", status: "detected", detail: "Passive session reader (no hook needed)" });
899
+ }
900
+ }
901
+
902
+ // Craft Agents: passive reader — no hook installation needed.
903
+ // Token Usage reads ~/.craft-agent/workspaces/<id>/sessions/**/session.jsonl
904
+ // (and any user-relocated workspace listed in ~/.craft-agent/config.json).
905
+ {
906
+ const craftConfigDir = process.env.CRAFT_CONFIG_DIR || path.join(home, ".craft-agent");
907
+ if (fssync.existsSync(craftConfigDir)) {
908
+ summary.push({ label: "Craft Agents", status: "detected", detail: "Passive reader (no hook needed)" });
909
+ }
910
+ }
911
+
912
+ // Reasonix: passive reader of content-free *.jsonl.telemetry.json sidecars.
913
+ {
914
+ const reasonixHome = resolveReasonixHome(process.env);
915
+ if (fssync.existsSync(reasonixHome)) {
916
+ summary.push({ label: "Reasonix", status: "detected", detail: "Passive telemetry reader (no hook needed)" });
917
+ }
918
+ }
919
+
920
+ // Muse Code: passive reader of ~/.local/share/muse/sessions/**/session.jsonl.
921
+ {
922
+ if (fssync.existsSync(path.join(resolveMuseHome(process.env), "sessions"))) {
923
+ summary.push({ label: "Muse Code", status: "detected", detail: "Passive session reader (no hook needed)" });
924
+ }
925
+ }
926
+
927
+ // International TRAE usage is read locally; no hook or vendor login is needed.
928
+ {
929
+ const { resolveTraeDbPaths } = require("../lib/trae-db");
930
+ const traeDbPaths = resolveTraeDbPaths(process.env);
931
+ const traeStoragePath = resolveTraeStoragePath(process.env);
932
+ if (traeDbPaths.length || traeStoragePath) {
933
+ summary.push({
934
+ label: "TRAE",
935
+ status: "detected",
936
+ detail: traeDbPaths.length
937
+ ? "Local usage reader (shared application key; optional TOKENUSAGE_TRAE_SQLCIPHER_KEY override)"
938
+ : "Plan info only — no local usage database found",
939
+ });
940
+ }
941
+ }
942
+
943
+ // Grok Build (xAI): SessionEnd hook in ~/.grok/hooks/ + handler in ~/.tokenusage/bin/
944
+ {
945
+ try {
946
+ const grokState = await probeGrokHookState({ home, trackerDir, env: process.env });
947
+ if (grokState.hasGrokInstall) {
948
+ const grokRes = await upsertGrokHook({ home, trackerDir, env: process.env });
949
+ summary.push({
950
+ label: "Grok Build",
951
+ status: grokRes.configured ? "installed" : "detected",
952
+ detail: grokRes.configured ? "SessionEnd hook installed (99-tokenusage-usage.json)" : "Grok detected"
953
+ });
954
+ }
955
+ } catch (err) {
956
+ summary.push({ label: "Grok Build", status: "error", detail: String(err?.message || err) });
957
+ }
958
+ }
959
+
960
+ // Kilo CLI (kilo.ai @kilocode/plugin): passive reader — no hook installation
961
+ // needed. Reuses OpenCode-fork SQLite schema at ~/.local/share/kilo/kilo.db
962
+ // (override via KILO_HOME).
963
+ {
964
+ const xdgDataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
965
+ const kiloHome = process.env.KILO_HOME || path.join(xdgDataHome, "kilo");
966
+ const kiloDbPath = path.join(kiloHome, "kilo.db");
967
+ if (fssync.existsSync(kiloDbPath)) {
968
+ summary.push({ label: "Kilo CLI", status: "detected", detail: "Passive reader (no hook needed)" });
969
+ }
970
+ }
971
+
972
+ {
973
+ const dumateDbPaths = resolveDumateDbPaths({ home });
974
+ if (dumateDbPaths.length > 0) {
975
+ summary.push({ label: "DuMate", status: "detected", detail: "Passive reader (no hook needed)" });
976
+ }
977
+ }
978
+
979
+ // Mimo (mimocode): passive reader — no hook installation needed. Reuses the
980
+ // OpenCode-fork SQLite schema at ~/.local/share/mimocode/mimocode.db
981
+ // (override via MIMO_HOME).
982
+ {
983
+ const mimoDbPath = resolveMimoNativeDbPath({ home });
984
+ if (fssync.existsSync(mimoDbPath)) {
985
+ summary.push({ label: "Mimo", status: "detected", detail: "Passive reader (no hook needed)" });
986
+ }
987
+ }
988
+
989
+ // LM Studio and Unsloth Studio: passive readers — no hooks needed.
990
+ {
991
+ const lmstudioLogFiles = await resolveLmstudioLogFiles(process.env);
992
+ if (lmstudioLogFiles.length > 0) {
993
+ summary.push({
994
+ label: "LM Studio",
995
+ status: "detected",
996
+ detail: `Passive reader · ${lmstudioLogFiles.length} log${lmstudioLogFiles.length !== 1 ? "s" : ""}`,
997
+ });
998
+ }
999
+ }
1000
+
1001
+ {
1002
+ const unslothDbPath = resolveUnslothDbPath(process.env);
1003
+ if (unslothDbPath && fssync.existsSync(unslothDbPath)) {
1004
+ summary.push({
1005
+ label: "Unsloth Studio",
1006
+ status: "detected",
1007
+ detail: "Passive reader (no hook needed)",
1008
+ });
1009
+ }
1010
+ }
1011
+
1012
+ // AnythingLLM Desktop: passive SQLite reader — no hook installation needed.
1013
+ {
1014
+ const anythingllmDbPath = resolveAnythingllmDbPath(process.env);
1015
+ if (anythingllmDbPath && fssync.existsSync(anythingllmDbPath)) {
1016
+ summary.push({
1017
+ label: "AnythingLLM Desktop",
1018
+ status: "detected",
1019
+ detail: "Passive reader (no hook needed)",
1020
+ });
1021
+ }
1022
+ }
1023
+
1024
+ // Devin CLI (Cognition): passive SQLite reader — no hook installation needed.
1025
+ {
1026
+ const devinDbPath = resolveDevinDbPath(process.env);
1027
+ if (devinDbPath && fssync.existsSync(devinDbPath)) {
1028
+ summary.push({
1029
+ label: "Devin CLI",
1030
+ status: "detected",
1031
+ detail: "Passive reader (no hook needed)",
1032
+ });
1033
+ }
1034
+ }
1035
+
1036
+ // Kilo Code VS Code extension (kilocode.kilo-code): passive reader — no hook
1037
+ // installation needed. Scans ui_messages.json under every detected VS Code-
1038
+ // family install (Code, Cursor, CodeBuddy, Windsurf, …).
1039
+ {
1040
+ const { resolveKilocodeTaskFiles } = require("../lib/rollout");
1041
+ const taskFiles = resolveKilocodeTaskFiles(process.env);
1042
+ if (taskFiles.length > 0) {
1043
+ const ides = Array.from(new Set(taskFiles.map((t) => t.ide))).join(", ");
1044
+ summary.push({
1045
+ label: "Kilo Code (VS Code extension)",
1046
+ status: "detected",
1047
+ detail: `Passive reader · ${taskFiles.length} task${taskFiles.length !== 1 ? "s" : ""} in ${ides}`,
1048
+ });
1049
+ }
1050
+ }
1051
+
1052
+ // Cline CLI v3 / desktop app: passive reader — no hook installation needed.
1053
+ // Cline keeps its own data dir (~/.cline/data/sessions, overridable through
1054
+ // CLINE_DIR/CLINE_DATA_DIR/CLINE_SESSION_DATA_DIR); the VS Code extension's
1055
+ // globalStorage layout is a separate, older install we do not read.
1056
+ {
1057
+ const { resolveClineSessionFilesWithStatus } = require("../lib/rollout");
1058
+ const clineScan = resolveClineSessionFilesWithStatus(process.env);
1059
+ const sessionFiles = clineScan.files;
1060
+ if (sessionFiles.length > 0) {
1061
+ summary.push({
1062
+ label: "Cline",
1063
+ status: "detected",
1064
+ detail: `Passive reader · ${sessionFiles.length} transcript${sessionFiles.length !== 1 ? "s" : ""}`,
1065
+ });
1066
+ }
1067
+ for (const failure of clineScan.errors) {
1068
+ summary.push({
1069
+ label: "Cline",
1070
+ status: "error",
1071
+ detail: `Passive reader discovery failed · ${failure.root}: ${failure.error.code ? `${failure.error.code}: ` : ""}${failure.error.message}`,
1072
+ });
1073
+ }
1074
+ }
1075
+
1076
+ // CodeBuddy: Claude-Code fork. Install the SessionEnd hook so finished
1077
+ // sessions trigger notify.cjs → tracker sync; passive scan still runs as a
1078
+ // safety net for sessions that don't fire SessionEnd cleanly.
1079
+ const codebuddyDirExists = await isDir(context.codebuddyDir);
1080
+ if (codebuddyDirExists) {
1081
+ await upsertClaudeHook({
1082
+ settingsPath: context.codebuddySettingsPath,
1083
+ hookCommand: context.codebuddyHookCommand,
1084
+ });
1085
+ summary.push({ label: "CodeBuddy", status: "installed", detail: "Hooks installed" });
1086
+ } else {
1087
+ summary.push({ label: "CodeBuddy", status: "skipped", detail: "Config not found" });
1088
+ }
1089
+
1090
+ // WorkBuddy: sibling Claude-Code fork. Same SessionEnd hook → notify.cjs →
1091
+ // tracker sync; passive scan still runs as a safety net.
1092
+ const workbuddyDirExists = await isDir(context.workbuddyDir);
1093
+ if (workbuddyDirExists) {
1094
+ await upsertClaudeHook({
1095
+ settingsPath: context.workbuddySettingsPath,
1096
+ hookCommand: context.workbuddyHookCommand,
1097
+ });
1098
+ summary.push({ label: "WorkBuddy", status: "installed", detail: "Hooks installed" });
1099
+ } else {
1100
+ summary.push({ label: "WorkBuddy", status: "skipped", detail: "Config not found" });
1101
+ }
1102
+
1103
+ // WorkBuddy AI: international build, same hook schema, sibling home.
1104
+ const workbuddyAiDirExists = await isDir(context.workbuddyAiDir);
1105
+ if (workbuddyAiDirExists) {
1106
+ await upsertClaudeHook({
1107
+ settingsPath: context.workbuddyAiSettingsPath,
1108
+ hookCommand: context.workbuddyAiHookCommand,
1109
+ });
1110
+ summary.push({ label: "WorkBuddy AI", status: "installed", detail: "Hooks installed" });
1111
+ } else {
1112
+ summary.push({ label: "WorkBuddy AI", status: "skipped", detail: "Config not found" });
1113
+ }
1114
+
1115
+ const openclawBefore = await probeOpenclawSessionPluginState({
1116
+ home,
1117
+ trackerDir,
1118
+ env: process.env,
1119
+ });
1120
+ const openclawInstall = await installOpenclawSessionPlugin({
1121
+ home,
1122
+ trackerDir,
1123
+ packageName: "tokenusage-cli",
1124
+ env: process.env,
1125
+ });
1126
+ if (openclawInstall?.skippedReason === "openclaw-cli-missing") {
1127
+ summary.push({
1128
+ label: "OpenClaw Session Plugin",
1129
+ status: "skipped",
1130
+ detail: "OpenClaw CLI not found",
1131
+ });
1132
+ } else if (openclawInstall?.skippedReason === "openclaw-plugins-install-failed") {
1133
+ summary.push({
1134
+ label: "OpenClaw Session Plugin",
1135
+ status: "skipped",
1136
+ detail: `Install failed${openclawInstall.error ? `: ${openclawInstall.error}` : ""}`,
1137
+ });
1138
+ } else if (openclawInstall?.skippedReason === "openclaw-config-unreadable") {
1139
+ summary.push({
1140
+ label: "OpenClaw Session Plugin",
1141
+ status: "skipped",
1142
+ detail: openclawInstall.error
1143
+ ? `OpenClaw config unreadable: ${openclawInstall.error}`
1144
+ : "OpenClaw config unreadable",
1145
+ });
1146
+ } else if (openclawInstall?.configured) {
1147
+ summary.push({
1148
+ label: "OpenClaw Session Plugin",
1149
+ status: openclawBefore?.configured ? "set" : "installed",
1150
+ detail: openclawBefore?.configured
1151
+ ? "Session plugin already linked"
1152
+ : "Session plugin linked (restart OpenClaw gateway to activate)",
1153
+ });
1154
+ } else {
1155
+ summary.push({
1156
+ label: "OpenClaw Session Plugin",
1157
+ status: "skipped",
1158
+ detail: "OpenClaw session plugin unavailable",
1159
+ });
1160
+ }
1161
+
1162
+ const legacyHookState = await probeOpenclawHookState({ home, trackerDir, env: process.env });
1163
+ if (legacyHookState?.configured || legacyHookState?.linked || legacyHookState?.enabled) {
1164
+ await removeOpenclawHookConfig({ home, trackerDir, env: process.env });
1165
+ summary.push({
1166
+ label: "OpenClaw Hook (legacy)",
1167
+ status: "updated",
1168
+ detail: "Removed legacy command hook (migrated to session plugin)",
1169
+ });
1170
+ }
1171
+
1172
+ const codeProbe = await probeFile(context.codeConfigPath);
1173
+ if (codeProbe.exists) {
1174
+ const currentNotify = await readEveryCodeNotify(context.codeConfigPath);
1175
+ const result = await upsertEveryCodeNotify({
1176
+ codeConfigPath: context.codeConfigPath,
1177
+ notifyCmd: context.codeNotifyCmd,
1178
+ notifyOriginalPath: context.codeNotifyOriginalPath,
1179
+ replaceOriginal: shouldReplaceStoredOriginalNotify(currentNotify, context.codeNotifyCmd),
1180
+ });
1181
+ summary.push({
1182
+ label: "Every Code",
1183
+ status: result.changed ? "updated" : "set",
1184
+ detail: result.changed ? "Updated config" : "Config already set",
1185
+ });
1186
+ } else {
1187
+ summary.push({ label: "Every Code", status: "skipped", detail: renderSkipDetail(codeProbe) });
1188
+ }
1189
+
1190
+ return summary;
1191
+ }
1192
+
1193
+ async function previewIntegrations({ context }) {
1194
+ const summary = [];
1195
+ const home = os.homedir();
1196
+
1197
+ const codexProbe = await probeFile(context.codexConfigPath);
1198
+ if (codexProbe.exists) {
1199
+ const existing = await readCodexNotify(context.codexConfigPath);
1200
+ const matches = arraysEqual(existing, context.notifyCmd);
1201
+ summary.push({
1202
+ label: "Codex CLI",
1203
+ status: matches ? "set" : "updated",
1204
+ detail: matches ? "Already configured" : "Will update config",
1205
+ });
1206
+ } else {
1207
+ summary.push({ label: "Codex CLI", status: "skipped", detail: renderSkipDetail(codexProbe) });
1208
+ }
1209
+
1210
+ const acodeProbe = await probeFile(context.acodeConfigPath);
1211
+ if (acodeProbe.exists) {
1212
+ const existing = await readAcodeNotify(context.acodeConfigPath);
1213
+ const matches = arraysEqual(existing, context.acodeNotifyCmd);
1214
+ summary.push({
1215
+ label: "AStudio",
1216
+ status: matches ? "set" : "updated",
1217
+ detail: matches ? "Already configured" : "Will update config",
1218
+ });
1219
+ } else {
1220
+ summary.push({ label: "AStudio", status: "skipped", detail: renderSkipDetail(acodeProbe) });
1221
+ }
1222
+
1223
+ const claudeDirExists = await isDir(context.claudeDir);
1224
+ if (claudeDirExists) {
1225
+ const configured = await areClaudeUsageHooksConfigured({
1226
+ settingsPath: context.claudeSettingsPath,
1227
+ hookCommand: context.claudeHookCommand,
1228
+ });
1229
+ summary.push({
1230
+ label: "Claude",
1231
+ status: "installed",
1232
+ detail: configured ? "Hooks already installed" : "Will install hooks",
1233
+ });
1234
+ } else {
1235
+ summary.push({ label: "Claude", status: "skipped", detail: "Config not found" });
1236
+ }
1237
+
1238
+ const codebuddyDirExists = await isDir(context.codebuddyDir);
1239
+ if (codebuddyDirExists) {
1240
+ const configured = await isClaudeHookConfigured({
1241
+ settingsPath: context.codebuddySettingsPath,
1242
+ hookCommand: context.codebuddyHookCommand,
1243
+ });
1244
+ summary.push({
1245
+ label: "CodeBuddy",
1246
+ status: "installed",
1247
+ detail: configured ? "Hooks already installed" : "Will install hooks",
1248
+ });
1249
+ } else {
1250
+ summary.push({ label: "CodeBuddy", status: "skipped", detail: "Config not found" });
1251
+ }
1252
+
1253
+ const workbuddyDirExists = await isDir(context.workbuddyDir);
1254
+ if (workbuddyDirExists) {
1255
+ const configured = await isClaudeHookConfigured({
1256
+ settingsPath: context.workbuddySettingsPath,
1257
+ hookCommand: context.workbuddyHookCommand,
1258
+ });
1259
+ summary.push({
1260
+ label: "WorkBuddy",
1261
+ status: "installed",
1262
+ detail: configured ? "Hooks already installed" : "Will install hooks",
1263
+ });
1264
+ } else {
1265
+ summary.push({ label: "WorkBuddy", status: "skipped", detail: "Config not found" });
1266
+ }
1267
+
1268
+ const workbuddyAiDirExists = await isDir(context.workbuddyAiDir);
1269
+ if (workbuddyAiDirExists) {
1270
+ const configured = await isClaudeHookConfigured({
1271
+ settingsPath: context.workbuddyAiSettingsPath,
1272
+ hookCommand: context.workbuddyAiHookCommand,
1273
+ });
1274
+ summary.push({
1275
+ label: "WorkBuddy AI",
1276
+ status: "installed",
1277
+ detail: configured ? "Hooks already installed" : "Will install hooks",
1278
+ });
1279
+ } else {
1280
+ summary.push({ label: "WorkBuddy AI", status: "skipped", detail: "Config not found" });
1281
+ }
1282
+
1283
+ const geminiConfigExists = await isDir(context.geminiConfigDir);
1284
+ if (geminiConfigExists) {
1285
+ const configured = await isGeminiHookConfigured({
1286
+ settingsPath: context.geminiSettingsPath,
1287
+ hookCommand: context.geminiHookCommand,
1288
+ });
1289
+ summary.push({
1290
+ label: "Gemini",
1291
+ status: "installed",
1292
+ detail: configured ? "Hooks already installed" : "Will install hooks",
1293
+ });
1294
+ } else {
1295
+ summary.push({ label: "Gemini", status: "skipped", detail: "Config not found" });
1296
+ }
1297
+
1298
+ const opencodeDirExists = await isDir(context.opencodeConfigDir);
1299
+ const installed = await isOpencodePluginInstalled({ configDir: context.opencodeConfigDir });
1300
+ const opencodeDetail = installed
1301
+ ? "Plugin already installed"
1302
+ : opencodeDirExists
1303
+ ? "Will install plugin"
1304
+ : "Will create config and install plugin";
1305
+ summary.push({
1306
+ label: "Opencode Plugin",
1307
+ status: "installed",
1308
+ detail: opencodeDetail,
1309
+ });
1310
+
1311
+ const openclawState = await probeOpenclawSessionPluginState({
1312
+ home,
1313
+ trackerDir: context.trackerDir,
1314
+ env: process.env,
1315
+ });
1316
+ if (openclawState?.skippedReason === "openclaw-config-missing") {
1317
+ summary.push({
1318
+ label: "OpenClaw Session Plugin",
1319
+ status: "skipped",
1320
+ detail: "OpenClaw config not found",
1321
+ });
1322
+ } else if (openclawState?.skippedReason === "openclaw-config-unreadable") {
1323
+ summary.push({
1324
+ label: "OpenClaw Session Plugin",
1325
+ status: "skipped",
1326
+ detail: openclawState.error
1327
+ ? `OpenClaw config unreadable: ${openclawState.error}`
1328
+ : "OpenClaw config unreadable",
1329
+ });
1330
+ } else {
1331
+ summary.push({
1332
+ label: "OpenClaw Session Plugin",
1333
+ status: openclawState?.configured ? "set" : "installed",
1334
+ detail: openclawState?.configured
1335
+ ? "Session plugin already linked"
1336
+ : "Will link session plugin (restart OpenClaw gateway to activate)",
1337
+ });
1338
+ }
1339
+
1340
+ const legacyHookState = await probeOpenclawHookState({
1341
+ home,
1342
+ trackerDir: context.trackerDir,
1343
+ env: process.env,
1344
+ });
1345
+ if (legacyHookState?.configured || legacyHookState?.linked || legacyHookState?.enabled) {
1346
+ summary.push({
1347
+ label: "OpenClaw Hook (legacy)",
1348
+ status: "updated",
1349
+ detail: "Will remove legacy command hook during migration",
1350
+ });
1351
+ }
1352
+
1353
+ const codeProbe = await probeFile(context.codeConfigPath);
1354
+ if (codeProbe.exists) {
1355
+ const existing = await readEveryCodeNotify(context.codeConfigPath);
1356
+ const matches = arraysEqual(existing, context.codeNotifyCmd);
1357
+ summary.push({
1358
+ label: "Every Code",
1359
+ status: matches ? "set" : "updated",
1360
+ detail: matches ? "Already configured" : "Will update config",
1361
+ });
1362
+ } else {
1363
+ summary.push({ label: "Every Code", status: "skipped", detail: renderSkipDetail(codeProbe) });
1364
+ }
1365
+
1366
+ return summary;
1367
+ }
1368
+
1369
+ function renderSkipDetail(probe) {
1370
+ if (!probe || probe.reason === "missing") return "Config not found";
1371
+ if (probe.reason === "permission-denied") return "Permission denied";
1372
+ if (probe.reason === "not-file") return "Invalid config";
1373
+ return "Unavailable";
1374
+ }
1375
+
1376
+ function arraysEqual(a, b) {
1377
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
1378
+ if (a.length !== b.length) return false;
1379
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1380
+ return true;
1381
+ }
1382
+
1383
+ async function shouldRepairCodexNotify({ currentNotify, expectedNotify, notifyOriginalPath }) {
1384
+ if (!Array.isArray(currentNotify) || currentNotify.length === 0) {
1385
+ return { repair: true, captureOriginal: true, replaceOriginal: true };
1386
+ }
1387
+ if (arraysEqual(currentNotify, expectedNotify)) {
1388
+ return { repair: false, reason: "already-set" };
1389
+ }
1390
+ if (isTokenUsageNotify(currentNotify, expectedNotify)) {
1391
+ return { repair: true, captureOriginal: false };
1392
+ }
1393
+ if (
1394
+ isSkyComputerUseNotify(currentNotify)
1395
+ && containsNestedTokenUsageNotify(currentNotify, expectedNotify)
1396
+ ) {
1397
+ return { repair: false, reason: "already-wrapped" };
1398
+ }
1399
+ if (isSkyComputerUseNotify(currentNotify)) {
1400
+ return { repair: true, captureOriginal: true, replaceOriginal: true };
1401
+ }
1402
+
1403
+ const original = await readJson(notifyOriginalPath);
1404
+ const originalNotify = Array.isArray(original?.notify) ? original.notify : null;
1405
+ if (arraysEqual(currentNotify, originalNotify)) {
1406
+ return { repair: true, captureOriginal: true, replaceOriginal: false };
1407
+ }
1408
+
1409
+ return { repair: false, reason: "external-notify" };
1410
+ }
1411
+
1412
+ function shouldReplaceStoredOriginalNotify(currentNotify, expectedNotify) {
1413
+ if (isTokenUsageNotify(currentNotify, expectedNotify)) return false;
1414
+ return currentNotify === null || Array.isArray(currentNotify);
1415
+ }
1416
+
1417
+ // Single source of truth for "is this notify command ours?", shared with
1418
+ // status (configured check) and uninstall (restore gate) so the three cannot
1419
+ // drift apart. See isManagedNotifyCmd in src/lib/codex-config.js.
1420
+ function isTokenUsageNotify(cmd, expectedNotify) {
1421
+ return isManagedNotifyCmd(cmd, expectedNotify);
1422
+ }
1423
+
1424
+ function isSkyComputerUseNotify(cmd) {
1425
+ if (!Array.isArray(cmd)) return false;
1426
+ return cmd.some((part) => typeof part === "string" && part.includes("SkyComputerUseClient"));
1427
+ }
1428
+
1429
+ function containsNestedTokenUsageNotify(cmd, expectedNotify) {
1430
+ if (!Array.isArray(cmd)) return false;
1431
+ for (const part of cmd) {
1432
+ if (typeof part !== "string") continue;
1433
+ try {
1434
+ if (isTokenUsageNotify(JSON.parse(part), expectedNotify)) return true;
1435
+ } catch (_) {}
1436
+ }
1437
+ return false;
1438
+ }
1439
+
1440
+ function parseArgs(argv) {
1441
+ const out = {
1442
+ baseUrl: null,
1443
+ dashboardUrl: null,
1444
+ anonKey: null,
1445
+ anonKeyFile: null,
1446
+ email: null,
1447
+ password: null,
1448
+ deviceName: null,
1449
+ linkCode: null,
1450
+ noAuth: false,
1451
+ noOpen: false,
1452
+ yes: false,
1453
+ dryRun: false,
1454
+ runReport: null,
1455
+ noTask: false,
1456
+ };
1457
+
1458
+ for (let i = 0; i < argv.length; i++) {
1459
+ const a = argv[i];
1460
+ if (a === "--base-url") out.baseUrl = argv[++i] || null;
1461
+ else if (a === "--dashboard-url") out.dashboardUrl = argv[++i] || null;
1462
+ else if (a === "--anon-key") out.anonKey = argv[++i] || null;
1463
+ else if (a === "--anon-key-file") out.anonKeyFile = argv[++i] || null;
1464
+ else if (a === "--email") out.email = argv[++i] || null;
1465
+ else if (a === "--password") out.password = argv[++i] || null;
1466
+ else if (a === "--device-name") out.deviceName = argv[++i] || null;
1467
+ else if (a === "--link-code") out.linkCode = argv[++i] || null;
1468
+ else if (a === "--run-report") out.runReport = normalizeRunReportFlag(argv[++i]);
1469
+ else if (a.startsWith("--run-report=")) out.runReport = normalizeRunReportFlag(a.slice("--run-report=".length));
1470
+ else if (a === "--no-task") out.noTask = true;
1471
+ else if (a === "--no-auth") out.noAuth = true;
1472
+ else if (a === "--no-open") out.noOpen = true;
1473
+ else if (a === "--yes") out.yes = true;
1474
+ else if (a === "--dry-run") out.dryRun = true;
1475
+ else throw new Error(`Unknown option: ${a}`);
1476
+ }
1477
+ return out;
1478
+ }
1479
+
1480
+ function sleep(ms) {
1481
+ if (!ms || ms <= 0) return Promise.resolve();
1482
+ return new Promise((resolve) => setTimeout(resolve, ms));
1483
+ }
1484
+
1485
+ // §2.11 run-report persistence: `--run-report=off` writes runReport:false into
1486
+ // config.json so every later sync skips the POST; absent leaves the default
1487
+ // (enabled) untouched. Invalid values fail loudly like unknown options.
1488
+ function normalizeRunReportFlag(value) {
1489
+ const normalized = String(value ?? "").trim().toLowerCase();
1490
+ if (normalized === "on" || normalized === "true" || normalized === "1") return true;
1491
+ if (normalized === "off" || normalized === "false" || normalized === "0") return false;
1492
+ throw new Error(`Unknown value for --run-report: ${value} (use on|off)`);
1493
+ }
1494
+
1495
+ function normalizePlatform(value) {
1496
+ if (value === "darwin") return "macos";
1497
+ if (value === "win32") return "windows";
1498
+ if (value === "linux") return "linux";
1499
+ return "unknown";
1500
+ }
1501
+
1502
+ function buildNotifyHandler({ trackerDir, packageName }) {
1503
+ // Keep this file dependency-free: Node built-ins only.
1504
+ // It must never block Codex; it spawns sync in the background and exits 0.
1505
+ const queueSignalPath = path.join(trackerDir, "notify.signal");
1506
+ const originalPath = path.join(trackerDir, "codex_notify_original.json");
1507
+ const fallbackPkg = packageName || "tokenusage-cli";
1508
+ const trackerBinPath = path.join(trackerDir, "app", "bin", "tracker.js");
1509
+
1510
+ return `#!/usr/bin/env node
1511
+ 'use strict';
1512
+
1513
+ const fs = require('node:fs');
1514
+ const os = require('node:os');
1515
+ const path = require('node:path');
1516
+ const cp = require('node:child_process');
1517
+
1518
+ const rawArgs = process.argv.slice(2);
1519
+ let source = 'codex';
1520
+ const payloadArgs = [];
1521
+ for (let i = 0; i < rawArgs.length; i++) {
1522
+ const arg = rawArgs[i];
1523
+ if (arg === '--source') {
1524
+ source = rawArgs[i + 1] || source;
1525
+ i += 1;
1526
+ continue;
1527
+ }
1528
+ if (arg.startsWith('--source=')) {
1529
+ source = arg.slice('--source='.length) || source;
1530
+ continue;
1531
+ }
1532
+ payloadArgs.push(arg);
1533
+ }
1534
+
1535
+ const trackerDir = ${JSON.stringify(trackerDir)};
1536
+ const signalPath = ${JSON.stringify(queueSignalPath)};
1537
+ const codexOriginalPath = ${JSON.stringify(originalPath)};
1538
+ const acodeOriginalPath = ${JSON.stringify(path.join(trackerDir, "acode_notify_original.json"))};
1539
+ const codeOriginalPath = ${JSON.stringify(path.join(trackerDir, "code_notify_original.json"))};
1540
+ const trackerBinPath = ${JSON.stringify(trackerBinPath)};
1541
+ const depsMarkerPath = path.join(trackerDir, 'app', 'bin', 'tracker.js');
1542
+ const fallbackPkg = ${JSON.stringify(fallbackPkg)};
1543
+ const selfPath = path.resolve(__filename);
1544
+ const home = os.homedir();
1545
+ const debugLogPath = path.join(trackerDir, 'notify.debug.jsonl');
1546
+ const debugEnabled = ['1', 'true'].includes((process.env.TOKENUSAGE_NOTIFY_DEBUG || '').toLowerCase());
1547
+ const debugMaxBytesRaw = Number.parseInt(process.env.TOKENUSAGE_NOTIFY_DEBUG_MAX_BYTES || '', 10);
1548
+ const debugMaxBytes = Number.isFinite(debugMaxBytesRaw) && debugMaxBytesRaw > 0
1549
+ ? debugMaxBytesRaw
1550
+ : 1_000_000;
1551
+
1552
+ try {
1553
+ fs.mkdirSync(trackerDir, { recursive: true });
1554
+ fs.writeFileSync(signalPath, new Date().toISOString(), { encoding: 'utf8' });
1555
+ } catch (_) {}
1556
+
1557
+ if (debugEnabled) {
1558
+ try {
1559
+ let size = 0;
1560
+ try {
1561
+ size = fs.statSync(debugLogPath).size;
1562
+ } catch (err) {
1563
+ if (err && err.code !== 'ENOENT') throw err;
1564
+ }
1565
+ if (size < debugMaxBytes) {
1566
+ const entry = {
1567
+ ts: new Date().toISOString(),
1568
+ source,
1569
+ cwd: process.cwd()
1570
+ };
1571
+ fs.appendFileSync(debugLogPath, JSON.stringify(entry) + os.EOL, 'utf8');
1572
+ }
1573
+ } catch (_) {}
1574
+ }
1575
+
1576
+ // Throttle spawn: at most once per 20 seconds.
1577
+ try {
1578
+ const throttlePath = path.join(trackerDir, 'sync.throttle');
1579
+ const now = Date.now();
1580
+ let last = 0;
1581
+ try { last = Number(fs.readFileSync(throttlePath, 'utf8')) || 0; } catch (_) {}
1582
+ if (now - last > 20_000) {
1583
+ try { fs.writeFileSync(throttlePath, String(now), 'utf8'); } catch (_) {}
1584
+ const hasLocalRuntime = fs.existsSync(trackerBinPath);
1585
+ const hasLocalDeps = fs.existsSync(depsMarkerPath);
1586
+ const syncArgs = ['sync', '--auto', '--from-notify', '--source', source];
1587
+ if (hasLocalRuntime && hasLocalDeps) {
1588
+ spawnDetached([process.execPath, trackerBinPath, ...syncArgs]);
1589
+ } else {
1590
+ spawnDetached(['npx', '--yes', fallbackPkg, ...syncArgs]);
1591
+ }
1592
+ }
1593
+ } catch (_) {}
1594
+
1595
+ // Chain the existing Codex, AStudio, or Every Code notify hook.
1596
+ try {
1597
+ const originalPath =
1598
+ source === 'every-code'
1599
+ ? codeOriginalPath
1600
+ : source === 'acode'
1601
+ ? acodeOriginalPath
1602
+ : source === 'claude' || source === 'opencode' || source === 'gemini' || source === 'codebuddy' || source === 'workbuddy' || source === 'workbuddy-ai'
1603
+ ? null
1604
+ : codexOriginalPath;
1605
+ if (originalPath) {
1606
+ const original = JSON.parse(fs.readFileSync(originalPath, 'utf8'));
1607
+ const cmd = Array.isArray(original?.notify) ? original.notify : null;
1608
+ if (cmd && cmd.length > 0 && !isSelfNotify(cmd) && shouldChainNotify(cmd)) {
1609
+ const args = cmd.slice(1);
1610
+ if (payloadArgs.length > 0 && !containsSequence(args, payloadArgs)) {
1611
+ args.push(...payloadArgs);
1612
+ }
1613
+ spawnDetached([cmd[0], ...args]);
1614
+ }
1615
+ }
1616
+ } catch (_) {}
1617
+
1618
+ process.exit(0);
1619
+
1620
+ function spawnDetached(argv) {
1621
+ try {
1622
+ const child = cp.spawn(argv[0], argv.slice(1), {
1623
+ detached: true,
1624
+ windowsHide: true,
1625
+ stdio: 'ignore',
1626
+ env: process.env
1627
+ });
1628
+ child.unref();
1629
+ } catch (_) {}
1630
+ }
1631
+
1632
+ function resolveMaybeHome(p, baseDir = null) {
1633
+ if (typeof p !== 'string') return null;
1634
+ if (p.startsWith('~/')) return path.join(home, p.slice(2));
1635
+ if (p.startsWith('~\\\\')) return path.join(home, p.slice(2));
1636
+ if (path.isAbsolute(p)) return p;
1637
+ return path.resolve(baseDir || process.cwd(), p);
1638
+ }
1639
+
1640
+ function isSelfNotify(cmd) {
1641
+ for (const part of cmd) {
1642
+ if (typeof part !== 'string') continue;
1643
+ if (!part.includes('notify.cjs')) continue;
1644
+ const resolved = resolveMaybeHome(part);
1645
+ if (resolved && isSelfNotifyPath(resolved)) return true;
1646
+ try {
1647
+ const nested = JSON.parse(part);
1648
+ if (Array.isArray(nested) && isSelfNotify(nested)) return true;
1649
+ } catch (_) {}
1650
+ }
1651
+ return false;
1652
+ }
1653
+
1654
+ function isSelfNotifyPath(resolved) {
1655
+ if (resolved === selfPath) return true;
1656
+ // selfPath is realpath-resolved by Node; stored paths may reach the same
1657
+ // file through a symlink (e.g. a symlinked home directory).
1658
+ try {
1659
+ if (fs.realpathSync(resolved) === selfPath) return true;
1660
+ } catch (_) {}
1661
+ // Any notify.cjs under a .tokenusage dir is ours (matches the repair-time
1662
+ // isTokenUsageNotify heuristic), even if that copy no longer exists.
1663
+ return resolved.replace(/\\\\/g, '/').includes('/.tokenusage/');
1664
+ }
1665
+
1666
+ function shouldChainNotify(cmd) {
1667
+ if (!Array.isArray(cmd) || cmd.length === 0) return false;
1668
+ if (!isRunnableCommand(cmd[0])) return false;
1669
+ return hasRunnableInterpreterTarget(cmd);
1670
+ }
1671
+
1672
+ function isRunnableCommand(command, baseDir = null) {
1673
+ if (typeof command !== 'string' || command.length === 0) return false;
1674
+ const explicitPath = isExplicitPath(command);
1675
+ if (!explicitPath) return true;
1676
+ const resolved = resolveMaybeHome(command, baseDir);
1677
+ if (!resolved) return false;
1678
+ try {
1679
+ fs.accessSync(resolved, fs.constants.X_OK);
1680
+ return true;
1681
+ } catch (_) {
1682
+ return false;
1683
+ }
1684
+ }
1685
+
1686
+ function hasRunnableInterpreterTarget(cmd) {
1687
+ const normalized = normalizeInterpreterCommand(cmd);
1688
+ const interpreterCmd = normalized?.cmd;
1689
+ if (!interpreterCmd || interpreterCmd.length === 0) return false;
1690
+ const targetIndex = findInterpreterTargetIndex(interpreterCmd);
1691
+ if (targetIndex == null) {
1692
+ const command = interpreterCmd[0];
1693
+ if (!isExplicitPath(command)) return true;
1694
+ return isRunnableCommand(command, normalized.cwd);
1695
+ }
1696
+ if (targetIndex === -2) return true;
1697
+ if (targetIndex === -1) return false;
1698
+ const target = interpreterCmd[targetIndex];
1699
+ if (!isExplicitPath(target)) return false;
1700
+ const targetCwd = isBunCommand(interpreterCmd[0])
1701
+ ? findBunScriptCwd(interpreterCmd, 1, normalized.cwd)
1702
+ : normalized.cwd;
1703
+ return isReadablePath(target, targetCwd);
1704
+ }
1705
+
1706
+ function normalizeInterpreterCommand(cmd) {
1707
+ if (!isEnvCommand(cmd[0])) return { cmd, cwd: null };
1708
+ return extractEnvCommand(cmd);
1709
+ }
1710
+
1711
+ function findInterpreterTargetIndex(cmd) {
1712
+ const command = cmd[0];
1713
+ if (isNodeCommand(command)) {
1714
+ return findNodeLikeScriptIndex(cmd, 1);
1715
+ }
1716
+ if (isBunCommand(command)) {
1717
+ return findBunScriptIndex(cmd, 1);
1718
+ }
1719
+ if (isDenoCommand(command)) {
1720
+ return findDenoScriptIndex(cmd, 1);
1721
+ }
1722
+ return null;
1723
+ }
1724
+
1725
+ function isEnvCommand(command) {
1726
+ const base = commandBase(command);
1727
+ return base === 'env';
1728
+ }
1729
+
1730
+ function extractEnvCommand(cmd) {
1731
+ return normalizeEnvArgs(cmd.slice(1));
1732
+ }
1733
+
1734
+ function normalizeEnvArgs(args, cwd = null) {
1735
+ for (let i = 0; i < args.length; i++) {
1736
+ const arg = args[i];
1737
+ if (typeof arg !== 'string' || arg.length === 0) return null;
1738
+ if (arg === '-' || arg === '--ignore-environment' || isEnvValuelessShortOption(arg)) continue;
1739
+ if (arg === '--') return normalizeEnvCommandOperands(args.slice(i + 1), cwd);
1740
+ if (arg === '-S' || arg === '--split-string') {
1741
+ const split = splitEnvString(args[i + 1]);
1742
+ if (!split) return null;
1743
+ return normalizeEnvArgs(split.concat(args.slice(i + 2)), cwd);
1744
+ }
1745
+ if (arg.startsWith('--split-string=')) {
1746
+ const split = splitEnvString(arg.slice('--split-string='.length));
1747
+ if (!split) return null;
1748
+ return normalizeEnvArgs(split.concat(args.slice(i + 1)), cwd);
1749
+ }
1750
+ if (arg === '-u' || arg === '--unset') {
1751
+ i += 1;
1752
+ continue;
1753
+ }
1754
+ if (arg.startsWith('--unset=')) continue;
1755
+ if (arg === '-C' || arg === '--chdir') {
1756
+ const next = args[i + 1];
1757
+ if (typeof next !== 'string' || next.length === 0) return null;
1758
+ cwd = resolveMaybeHome(next, cwd);
1759
+ i += 1;
1760
+ continue;
1761
+ }
1762
+ if (arg.startsWith('--chdir=')) {
1763
+ const dir = arg.slice('--chdir='.length);
1764
+ if (dir.length === 0) return null;
1765
+ cwd = resolveMaybeHome(dir, cwd);
1766
+ continue;
1767
+ }
1768
+ if (isEnvValueOption(arg)) {
1769
+ i += 1;
1770
+ continue;
1771
+ }
1772
+ if (isEnvInlineValueOption(arg)) continue;
1773
+ if (arg.startsWith('-')) return null;
1774
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) continue;
1775
+ return { cmd: args.slice(i), cwd };
1776
+ }
1777
+ return null;
1778
+ }
1779
+
1780
+ function normalizeEnvCommandOperands(args, cwd) {
1781
+ for (let i = 0; i < args.length; i++) {
1782
+ const arg = args[i];
1783
+ if (typeof arg !== 'string' || arg.length === 0) return null;
1784
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) continue;
1785
+ if (arg.startsWith('-')) return null;
1786
+ return { cmd: args.slice(i), cwd };
1787
+ }
1788
+ return null;
1789
+ }
1790
+
1791
+ function isEnvValuelessShortOption(arg) {
1792
+ return /^-[0iv]+$/.test(arg);
1793
+ }
1794
+
1795
+ function isEnvValueOption(arg) {
1796
+ return arg === '-P' || arg === '--path';
1797
+ }
1798
+
1799
+ function isEnvInlineValueOption(arg) {
1800
+ return (
1801
+ arg.startsWith('--path=')
1802
+ );
1803
+ }
1804
+
1805
+ function splitEnvString(value) {
1806
+ if (typeof value !== 'string' || value.length === 0) return null;
1807
+ const parts = [];
1808
+ let current = '';
1809
+ let quote = null;
1810
+ let escaped = false;
1811
+ for (let i = 0; i < value.length; i++) {
1812
+ const ch = value[i];
1813
+ if (escaped) {
1814
+ current += ch;
1815
+ escaped = false;
1816
+ continue;
1817
+ }
1818
+ if (ch === '\\\\' && quote !== "'") {
1819
+ escaped = true;
1820
+ continue;
1821
+ }
1822
+ if (quote) {
1823
+ if (ch === quote) quote = null;
1824
+ else current += ch;
1825
+ continue;
1826
+ }
1827
+ if (ch === '"' || ch === "'") {
1828
+ quote = ch;
1829
+ continue;
1830
+ }
1831
+ if (/\\s/.test(ch)) {
1832
+ if (current.length > 0) {
1833
+ parts.push(current);
1834
+ current = '';
1835
+ }
1836
+ continue;
1837
+ }
1838
+ current += ch;
1839
+ }
1840
+ if (escaped || quote) return null;
1841
+ if (current.length > 0) parts.push(current);
1842
+ return parts.length > 0 ? parts : null;
1843
+ }
1844
+
1845
+ function isNodeCommand(command) {
1846
+ const base = commandBase(command);
1847
+ return base === 'node';
1848
+ }
1849
+
1850
+ function isBunCommand(command) {
1851
+ const base = commandBase(command);
1852
+ return base === 'bun';
1853
+ }
1854
+
1855
+ function isDenoCommand(command) {
1856
+ const base = commandBase(command);
1857
+ return base === 'deno';
1858
+ }
1859
+
1860
+ function commandBase(command) {
1861
+ if (typeof command !== 'string' || command.length === 0) return '';
1862
+ const posixBase = path.basename(command);
1863
+ const winBase = path.win32.basename(command);
1864
+ const base = winBase.length < posixBase.length ? winBase : posixBase;
1865
+ return base.replace(/\\.exe$/i, '').toLowerCase();
1866
+ }
1867
+
1868
+ function findNodeLikeScriptIndex(cmd, startIndex) {
1869
+ for (let i = startIndex; i < cmd.length; i++) {
1870
+ const arg = cmd[i];
1871
+ if (typeof arg !== 'string' || arg.length === 0) return -1;
1872
+ if (arg === '-e' || arg === '--eval' || arg === '-p' || arg === '--print') return -2;
1873
+ if (arg.startsWith('--eval=') || arg.startsWith('--print=')) return -2;
1874
+ if (isNodeLikeOptionWithValue(arg)) {
1875
+ i += 1;
1876
+ continue;
1877
+ }
1878
+ if (hasInlineNodeLikeOptionValue(arg)) continue;
1879
+ if (isNodeLikeValuelessOption(arg)) continue;
1880
+ if (arg.startsWith('-')) return -1;
1881
+ return i;
1882
+ }
1883
+ return -1;
1884
+ }
1885
+
1886
+ function findBunScriptIndex(cmd, startIndex) {
1887
+ for (let i = startIndex; i < cmd.length; i++) {
1888
+ const arg = cmd[i];
1889
+ if (typeof arg !== 'string' || arg.length === 0) return -1;
1890
+ if (arg === '-e' || arg === '--eval' || arg === '-p' || arg === '--print') return -2;
1891
+ if (arg.startsWith('--eval=') || arg.startsWith('--print=')) return -2;
1892
+ if (isBunOptionWithValue(arg)) {
1893
+ i += 1;
1894
+ continue;
1895
+ }
1896
+ if (hasInlineBunOptionValue(arg)) continue;
1897
+ if (isBunValuelessOption(arg)) continue;
1898
+ if (arg === 'run') {
1899
+ return findScriptAfterSubcommand(cmd, i + 1, 'bun');
1900
+ }
1901
+ if (arg.startsWith('-')) return -1;
1902
+ return i;
1903
+ }
1904
+ return -1;
1905
+ }
1906
+
1907
+ function findBunScriptCwd(cmd, startIndex, baseDir = null) {
1908
+ let cwd = baseDir;
1909
+ for (let i = startIndex; i < cmd.length; i++) {
1910
+ const arg = cmd[i];
1911
+ if (typeof arg !== 'string' || arg.length === 0) return cwd;
1912
+ if (arg === '--cwd') {
1913
+ const next = cmd[i + 1];
1914
+ if (typeof next !== 'string' || next.length === 0) return cwd;
1915
+ cwd = resolveMaybeHome(next, cwd);
1916
+ i += 1;
1917
+ continue;
1918
+ }
1919
+ if (arg.startsWith('--cwd=')) {
1920
+ const next = arg.slice('--cwd='.length);
1921
+ if (next.length === 0) return cwd;
1922
+ cwd = resolveMaybeHome(next, cwd);
1923
+ continue;
1924
+ }
1925
+ if (arg === '-e' || arg === '--eval' || arg === '-p' || arg === '--print') return cwd;
1926
+ if (arg.startsWith('--eval=') || arg.startsWith('--print=')) return cwd;
1927
+ if (isBunOptionWithValue(arg)) {
1928
+ i += 1;
1929
+ continue;
1930
+ }
1931
+ if (hasInlineBunOptionValue(arg)) continue;
1932
+ if (isBunValuelessOption(arg)) continue;
1933
+ if (arg === 'run') return findBunScriptCwd(cmd, i + 1, cwd);
1934
+ return cwd;
1935
+ }
1936
+ return cwd;
1937
+ }
1938
+
1939
+ function findDenoScriptIndex(cmd, startIndex) {
1940
+ for (let i = startIndex; i < cmd.length; i++) {
1941
+ const arg = cmd[i];
1942
+ if (typeof arg !== 'string' || arg.length === 0) return -1;
1943
+ if (arg === 'eval') return -2;
1944
+ if (arg === 'run' || arg === 'test' || arg === 'bench' || arg === 'check') {
1945
+ return findScriptAfterSubcommand(cmd, i + 1, 'deno');
1946
+ }
1947
+ if (isDenoOptionWithValue(arg)) {
1948
+ i += 1;
1949
+ continue;
1950
+ }
1951
+ if (hasInlineDenoOptionValue(arg)) continue;
1952
+ if (isDenoValuelessOption(arg)) continue;
1953
+ if (arg.startsWith('-')) return -1;
1954
+ return i;
1955
+ }
1956
+ return -1;
1957
+ }
1958
+
1959
+ function findScriptAfterSubcommand(cmd, startIndex, runtime) {
1960
+ for (let i = startIndex; i < cmd.length; i++) {
1961
+ const arg = cmd[i];
1962
+ if (typeof arg !== 'string' || arg.length === 0) return -1;
1963
+ if (runtime === 'bun' && isBunOptionWithValue(arg)) {
1964
+ i += 1;
1965
+ continue;
1966
+ }
1967
+ if (runtime === 'deno' && isDenoOptionWithValue(arg)) {
1968
+ i += 1;
1969
+ continue;
1970
+ }
1971
+ if (runtime === 'bun' && hasInlineBunOptionValue(arg)) continue;
1972
+ if (runtime === 'deno' && hasInlineDenoOptionValue(arg)) continue;
1973
+ if (runtime === 'bun' && isBunValuelessOption(arg)) continue;
1974
+ if (runtime === 'deno' && isDenoValuelessOption(arg)) continue;
1975
+ if (arg.startsWith('-')) return -1;
1976
+ return i;
1977
+ }
1978
+ return -1;
1979
+ }
1980
+
1981
+ function isNodeLikeOptionWithValue(arg) {
1982
+ return (
1983
+ arg === '-C' ||
1984
+ arg === '-r' ||
1985
+ arg === '--conditions' ||
1986
+ arg === '--debug-port' ||
1987
+ arg === '--disable-warning' ||
1988
+ arg === '--env-file' ||
1989
+ arg === '--env-file-if-exists' ||
1990
+ arg === '--experimental-config-file' ||
1991
+ arg === '--experimental-loader' ||
1992
+ arg === '--import' ||
1993
+ arg === '--inspect-publish-uid' ||
1994
+ arg === '--loader' ||
1995
+ arg === '--localstorage-file' ||
1996
+ arg === '--require'
1997
+ );
1998
+ }
1999
+
2000
+ function hasInlineNodeLikeOptionValue(arg) {
2001
+ return (
2002
+ arg.startsWith('--conditions=') ||
2003
+ arg.startsWith('--debug-port=') ||
2004
+ arg.startsWith('--disable-warning=') ||
2005
+ arg.startsWith('--env-file=') ||
2006
+ arg.startsWith('--env-file-if-exists=') ||
2007
+ arg.startsWith('--experimental-config-file=') ||
2008
+ arg.startsWith('--experimental-loader=') ||
2009
+ arg.startsWith('--import=') ||
2010
+ arg.startsWith('--inspect-publish-uid=') ||
2011
+ arg.startsWith('--loader=') ||
2012
+ arg.startsWith('--localstorage-file=') ||
2013
+ arg.startsWith('--require=')
2014
+ );
2015
+ }
2016
+
2017
+ function isNodeLikeValuelessOption(arg) {
2018
+ return (
2019
+ arg === '-' ||
2020
+ arg === '-c' ||
2021
+ arg === '--' ||
2022
+ arg === '--check' ||
2023
+ arg === '--cpu-prof' ||
2024
+ arg === '--enable-source-maps' ||
2025
+ arg === '--expose-gc' ||
2026
+ arg === '--inspect' ||
2027
+ arg === '--inspect-brk' ||
2028
+ arg === '--inspect-wait' ||
2029
+ arg === '--no-deprecation' ||
2030
+ arg === '--no-warnings' ||
2031
+ arg === '--preserve-symlinks' ||
2032
+ arg === '--preserve-symlinks-main' ||
2033
+ arg === '--throw-deprecation' ||
2034
+ arg === '--trace-deprecation' ||
2035
+ arg === '--trace-warnings'
2036
+ );
2037
+ }
2038
+
2039
+ function isBunOptionWithValue(arg) {
2040
+ return (
2041
+ arg === '-c' ||
2042
+ arg === '-d' ||
2043
+ arg === '-F' ||
2044
+ arg === '-l' ||
2045
+ arg === '-r' ||
2046
+ arg === '--config' ||
2047
+ arg === '--conditions' ||
2048
+ arg === '--console-depth' ||
2049
+ arg === '--cpu-prof-dir' ||
2050
+ arg === '--cpu-prof-interval' ||
2051
+ arg === '--cpu-prof-name' ||
2052
+ arg === '--cwd' ||
2053
+ arg === '--define' ||
2054
+ arg === '--dns-result-order' ||
2055
+ arg === '--drop' ||
2056
+ arg === '--elide-lines' ||
2057
+ arg === '--env-file' ||
2058
+ arg === '--extension-order' ||
2059
+ arg === '--feature' ||
2060
+ arg === '--fetch-preconnect' ||
2061
+ arg === '--filter' ||
2062
+ arg === '--import' ||
2063
+ arg === '--inspect' ||
2064
+ arg === '--inspect-brk' ||
2065
+ arg === '--inspect-wait' ||
2066
+ arg === '--install' ||
2067
+ arg === '--jsx-factory' ||
2068
+ arg === '--jsx-fragment' ||
2069
+ arg === '--jsx-import-source' ||
2070
+ arg === '--jsx-runtime' ||
2071
+ arg === '--loader' ||
2072
+ arg === '--main-fields' ||
2073
+ arg === '--max-http-header-size' ||
2074
+ arg === '--port' ||
2075
+ arg === '--preload' ||
2076
+ arg === '--require' ||
2077
+ arg === '--shell' ||
2078
+ arg === '--title' ||
2079
+ arg === '--tsconfig-override' ||
2080
+ arg === '--unhandled-rejections' ||
2081
+ arg === '--user-agent'
2082
+ );
2083
+ }
2084
+
2085
+ function hasInlineBunOptionValue(arg) {
2086
+ return (
2087
+ arg.startsWith('--config=') ||
2088
+ arg.startsWith('--conditions=') ||
2089
+ arg.startsWith('--console-depth=') ||
2090
+ arg.startsWith('--cpu-prof-dir=') ||
2091
+ arg.startsWith('--cpu-prof-interval=') ||
2092
+ arg.startsWith('--cpu-prof-name=') ||
2093
+ arg.startsWith('--cwd=') ||
2094
+ arg.startsWith('--define=') ||
2095
+ arg.startsWith('--dns-result-order=') ||
2096
+ arg.startsWith('--drop=') ||
2097
+ arg.startsWith('--elide-lines=') ||
2098
+ arg.startsWith('--env-file=') ||
2099
+ arg.startsWith('--extension-order=') ||
2100
+ arg.startsWith('--feature=') ||
2101
+ arg.startsWith('--fetch-preconnect=') ||
2102
+ arg.startsWith('--filter=') ||
2103
+ arg.startsWith('--import=') ||
2104
+ arg.startsWith('--inspect=') ||
2105
+ arg.startsWith('--inspect-brk=') ||
2106
+ arg.startsWith('--inspect-wait=') ||
2107
+ arg.startsWith('--install=') ||
2108
+ arg.startsWith('--jsx-factory=') ||
2109
+ arg.startsWith('--jsx-fragment=') ||
2110
+ arg.startsWith('--jsx-import-source=') ||
2111
+ arg.startsWith('--jsx-runtime=') ||
2112
+ arg.startsWith('--loader=') ||
2113
+ arg.startsWith('--main-fields=') ||
2114
+ arg.startsWith('--max-http-header-size=') ||
2115
+ arg.startsWith('--port=') ||
2116
+ arg.startsWith('--preload=') ||
2117
+ arg.startsWith('--require=') ||
2118
+ arg.startsWith('--shell=') ||
2119
+ arg.startsWith('--title=') ||
2120
+ arg.startsWith('--tsconfig-override=') ||
2121
+ arg.startsWith('--unhandled-rejections=') ||
2122
+ arg.startsWith('--user-agent=')
2123
+ );
2124
+ }
2125
+
2126
+ function isBunValuelessOption(arg) {
2127
+ return (
2128
+ arg === '-b' ||
2129
+ arg === '-i' ||
2130
+ arg === '--bun' ||
2131
+ arg === '--cpu-prof' ||
2132
+ arg === '--cpu-prof-md' ||
2133
+ arg === '--expose-gc' ||
2134
+ arg === '--heap-prof' ||
2135
+ arg === '--heap-prof-md' ||
2136
+ arg === '--hot' ||
2137
+ arg === '--if-present' ||
2138
+ arg === '--ignore-dce-annotations' ||
2139
+ arg === '--jsx-side-effects' ||
2140
+ arg === '--no-addons' ||
2141
+ arg === '--no-clear-screen' ||
2142
+ arg === '--no-deprecation' ||
2143
+ arg === '--no-env-file' ||
2144
+ arg === '--no-exit-on-error' ||
2145
+ arg === '--no-install' ||
2146
+ arg === '--no-macros' ||
2147
+ arg === '--parallel' ||
2148
+ arg === '--prefer-latest' ||
2149
+ arg === '--prefer-offline' ||
2150
+ arg === '--preserve-symlinks' ||
2151
+ arg === '--preserve-symlinks-main' ||
2152
+ arg === '--redis-preconnect' ||
2153
+ arg === '--sequential' ||
2154
+ arg === '--silent' ||
2155
+ arg === '--smol' ||
2156
+ arg === '--sql-preconnect' ||
2157
+ arg === '--throw-deprecation' ||
2158
+ arg === '--use-bundled-ca' ||
2159
+ arg === '--use-openssl-ca' ||
2160
+ arg === '--use-system-ca' ||
2161
+ arg === '--watch' ||
2162
+ arg === '--workspaces' ||
2163
+ arg === '--zero-fill-buffers'
2164
+ );
2165
+ }
2166
+
2167
+ function isDenoOptionWithValue(arg) {
2168
+ return (
2169
+ arg === '-c' ||
2170
+ arg === '--cert' ||
2171
+ arg === '--conditions' ||
2172
+ arg === '--config' ||
2173
+ arg === '--cpu-prof-dir' ||
2174
+ arg === '--cpu-prof-interval' ||
2175
+ arg === '--cpu-prof-name' ||
2176
+ arg === '--ext' ||
2177
+ arg === '--import-map' ||
2178
+ arg === '--location' ||
2179
+ arg === '--lock' ||
2180
+ arg === '--minimum-dependency-age' ||
2181
+ arg === '--preload' ||
2182
+ arg === '--require' ||
2183
+ arg === '--seed'
2184
+ );
2185
+ }
2186
+
2187
+ function hasInlineDenoOptionValue(arg) {
2188
+ return (
2189
+ arg.startsWith('--cert=') ||
2190
+ arg.startsWith('--conditions=') ||
2191
+ arg.startsWith('--config=') ||
2192
+ arg.startsWith('--coverage=') ||
2193
+ arg.startsWith('--cpu-prof-dir=') ||
2194
+ arg.startsWith('--cpu-prof-interval=') ||
2195
+ arg.startsWith('--cpu-prof-name=') ||
2196
+ arg.startsWith('--env-file=') ||
2197
+ arg.startsWith('--ext=') ||
2198
+ arg.startsWith('--import-map=') ||
2199
+ arg.startsWith('--location=') ||
2200
+ arg.startsWith('--lock=') ||
2201
+ arg.startsWith('--minimum-dependency-age=') ||
2202
+ arg.startsWith('--node-modules-dir=') ||
2203
+ arg.startsWith('--preload=') ||
2204
+ arg.startsWith('--require=') ||
2205
+ arg.startsWith('--seed=') ||
2206
+ arg.startsWith('--vendor=') ||
2207
+ arg.startsWith('--v8-flags=') ||
2208
+ /^--(allow|deny|ignore)-[A-Za-z-]+=/.test(arg) ||
2209
+ arg.startsWith('--permission-set=') ||
2210
+ arg.startsWith('--reload=') ||
2211
+ arg.startsWith('--tunnel=') ||
2212
+ arg.startsWith('--watch=') ||
2213
+ arg.startsWith('--watch-exclude=') ||
2214
+ arg.startsWith('--watch-hmr=')
2215
+ );
2216
+ }
2217
+
2218
+ function isDenoValuelessOption(arg) {
2219
+ return (
2220
+ arg === '-A' ||
2221
+ arg === '-P' ||
2222
+ arg === '-q' ||
2223
+ arg === '-r' ||
2224
+ arg === '-t' ||
2225
+ arg === '--allow-all' ||
2226
+ arg === '--cached-only' ||
2227
+ arg === '--coverage' ||
2228
+ arg === '--cpu-prof' ||
2229
+ arg === '--cpu-prof-flamegraph' ||
2230
+ arg === '--cpu-prof-md' ||
2231
+ arg === '--env-file' ||
2232
+ arg === '--frozen' ||
2233
+ arg === '--no-check' ||
2234
+ arg === '--no-clear-screen' ||
2235
+ arg === '--no-code-cache' ||
2236
+ arg === '--no-config' ||
2237
+ arg === '--no-lock' ||
2238
+ arg === '--no-npm' ||
2239
+ arg === '--no-prompt' ||
2240
+ arg === '--no-remote' ||
2241
+ arg === '--node-modules-dir' ||
2242
+ arg === '--quiet' ||
2243
+ arg === '--reload' ||
2244
+ arg === '--tunnel' ||
2245
+ arg === '--unstable' ||
2246
+ arg === '--v8-flags' ||
2247
+ arg === '--vendor' ||
2248
+ arg === '--watch' ||
2249
+ arg === '--watch-exclude' ||
2250
+ arg === '--watch-hmr' ||
2251
+ /^-[RWINESA]$/.test(arg) ||
2252
+ /^--(allow|deny|ignore)-[A-Za-z-]+$/.test(arg) ||
2253
+ arg === '--permission-set'
2254
+ );
2255
+ }
2256
+
2257
+ function isReadablePath(target, baseDir = null) {
2258
+ const resolved = resolveMaybeHome(target, baseDir);
2259
+ if (!resolved) return false;
2260
+ try {
2261
+ fs.accessSync(resolved, fs.constants.R_OK);
2262
+ return true;
2263
+ } catch (_) {
2264
+ return false;
2265
+ }
2266
+ }
2267
+
2268
+ function isExplicitPath(value) {
2269
+ if (typeof value !== 'string' || value.length === 0) return false;
2270
+ return value.startsWith('~/') || value.startsWith('~\\\\') || value.includes('/') || value.includes('\\\\') || /^[A-Za-z]:/.test(value);
2271
+ }
2272
+
2273
+ function containsSequence(haystack, needle) {
2274
+ if (!Array.isArray(haystack) || !Array.isArray(needle) || needle.length === 0) return false;
2275
+ if (needle.length > haystack.length) return false;
2276
+ for (let i = 0; i <= haystack.length - needle.length; i++) {
2277
+ let matched = true;
2278
+ for (let j = 0; j < needle.length; j++) {
2279
+ if (haystack[i + j] !== needle[j]) {
2280
+ matched = false;
2281
+ break;
2282
+ }
2283
+ }
2284
+ if (matched) return true;
2285
+ }
2286
+ return false;
2287
+ }
2288
+ `;
2289
+ }
2290
+
2291
+ module.exports = {
2292
+ cmdInit,
2293
+ buildNotifyHandler,
2294
+ installLocalTrackerApp,
2295
+ repairCodexNotifyIntegration,
2296
+ repairAcodeNotifyIntegration,
2297
+ repairRuntimeIntegrations,
2298
+ applyIntegrationSetup,
2299
+ };
2300
+
2301
+ async function probeFile(p) {
2302
+ try {
2303
+ const st = await fs.stat(p);
2304
+ if (st.isFile()) return { exists: true, reason: null };
2305
+ return { exists: false, reason: "not-file" };
2306
+ } catch (e) {
2307
+ if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return { exists: false, reason: "missing" };
2308
+ if (e?.code === "EACCES" || e?.code === "EPERM")
2309
+ return { exists: false, reason: "permission-denied" };
2310
+ return { exists: false, reason: "error", code: e?.code || "unknown" };
2311
+ }
2312
+ }
2313
+
2314
+ async function isDir(p) {
2315
+ try {
2316
+ const st = await fs.stat(p);
2317
+ return st.isDirectory();
2318
+ } catch (_e) {
2319
+ return false;
2320
+ }
2321
+ }
2322
+
2323
+ async function installLocalTrackerApp({ appDir }) {
2324
+ // Test-only escape hatch: skip the ~10 MB runtime copy (src + dashboard/dist +
2325
+ // node_modules) when a test only exercises hook/config/notify wiring. Copying
2326
+ // the bundle per test case dominates the init test suite's wall time. Tests
2327
+ // that assert on the copied runtime simply leave this unset.
2328
+ if (process.env.TOKENUSAGE_SKIP_LOCAL_RUNTIME_COPY === "1") return;
2329
+ // Copy the current package's runtime (bin + src) into ~/.tokenusage so notify can run sync without npx.
2330
+ const packageRoot = path.resolve(__dirname, "../..");
2331
+ const srcFrom = path.join(packageRoot, "src");
2332
+ const binFrom = path.join(packageRoot, "bin", "tracker.js");
2333
+ const packageJsonFrom = path.join(packageRoot, "package.json");
2334
+ const nodeModulesFrom = path.join(packageRoot, "node_modules");
2335
+ const dashboardDistFrom = path.join(packageRoot, "dashboard", "dist");
2336
+
2337
+ // When running from the installed local runtime (or when appDir is symlinked to this package),
2338
+ // source and destination resolve to the same place. Do not delete appDir in that case.
2339
+ if (await pathsPointToSameLocation(packageRoot, appDir)) {
2340
+ return;
2341
+ }
2342
+
2343
+ const srcTo = path.join(appDir, "src");
2344
+ const binToDir = path.join(appDir, "bin");
2345
+ const binTo = path.join(binToDir, "tracker.js");
2346
+ const nodeModulesTo = path.join(appDir, "node_modules");
2347
+ const dashboardDistTo = path.join(appDir, "dashboard", "dist");
2348
+
2349
+ await fs.rm(appDir, { recursive: true, force: true }).catch(() => {});
2350
+ await ensureDir(appDir);
2351
+ await fs.cp(srcFrom, srcTo, { recursive: true });
2352
+ await ensureDir(binToDir);
2353
+ await fs.copyFile(binFrom, binTo);
2354
+ await fs.chmod(binTo, 0o755).catch(() => {});
2355
+ await fs.copyFile(packageJsonFrom, path.join(appDir, "package.json")).catch(() => {});
2356
+ if (await isDir(dashboardDistFrom)) {
2357
+ await fs.cp(dashboardDistFrom, dashboardDistTo, { recursive: true });
2358
+ }
2359
+ await copyRuntimeDependencies({ from: nodeModulesFrom, to: nodeModulesTo });
2360
+ }
2361
+
2362
+ async function pathsPointToSameLocation(a, b) {
2363
+ const aReal = await safeRealpath(a);
2364
+ const bReal = await safeRealpath(b);
2365
+ if (aReal && bReal) return aReal === bReal;
2366
+ return path.resolve(a) === path.resolve(b);
2367
+ }
2368
+
2369
+ async function safeRealpath(p) {
2370
+ try {
2371
+ return await fs.realpath(p);
2372
+ } catch (_err) {
2373
+ return null;
2374
+ }
2375
+ }
2376
+
2377
+ // Run the first sync inline so we can show the user their real token total
2378
+ // immediately. Caps wall-time at FIRST_SYNC_TIMEOUT_MS — past that we let the
2379
+ // child continue detached and surrender the wait. Returns aggregate stats
2380
+ // derived from queue.jsonl after the wait window closes.
2381
+ const FIRST_SYNC_TIMEOUT_MS = 15_000;
2382
+
2383
+ async function runFirstSyncAndRead({ trackerBinPath, trackerDir, packageName }) {
2384
+ // Test-only escape hatch: skip spawning a real `sync --drain` subprocess when
2385
+ // a test only exercises init wiring. Returns the same shape derived from an
2386
+ // (empty) queue so callers behave identically without the ~1s spawn per case.
2387
+ if (process.env.TOKENUSAGE_SKIP_FIRST_SYNC === "1") {
2388
+ return readFirstSyncTotals(trackerDir);
2389
+ }
2390
+ const fallbackPkg = packageName || "tokenusage-cli";
2391
+ const argv = ["sync", "--auto", "--drain"];
2392
+ const hasLocalRuntime = typeof trackerBinPath === "string" && fssync.existsSync(trackerBinPath);
2393
+ const cmd = hasLocalRuntime
2394
+ ? [process.execPath, trackerBinPath, ...argv]
2395
+ : ["npx", "--yes", fallbackPkg, ...argv];
2396
+
2397
+ await new Promise((resolve) => {
2398
+ let settled = false;
2399
+ let timer = null;
2400
+ const settle = () => {
2401
+ if (settled) return;
2402
+ settled = true;
2403
+ if (timer) clearTimeout(timer);
2404
+ resolve();
2405
+ };
2406
+ let child;
2407
+ try {
2408
+ child = cp.spawn(cmd[0], cmd.slice(1), {
2409
+ // detached so we can let it keep running past our timeout — the user
2410
+ // still gets data later via dashboard auto-refresh.
2411
+ detached: true,
2412
+ stdio: "ignore",
2413
+ env: process.env,
2414
+ });
2415
+ } catch (err) {
2416
+ if (isDebugEnabled()) {
2417
+ process.stderr.write(`first-sync spawn failed: ${err?.message || err}\n`);
2418
+ }
2419
+ settle();
2420
+ return;
2421
+ }
2422
+ child.on("error", () => settle());
2423
+ child.on("exit", () => settle());
2424
+ timer = setTimeout(() => {
2425
+ try {
2426
+ child.unref();
2427
+ } catch (_e) {}
2428
+ settle();
2429
+ }, FIRST_SYNC_TIMEOUT_MS);
2430
+ });
2431
+
2432
+ return readFirstSyncTotals(trackerDir);
2433
+ }
2434
+
2435
+ function readFirstSyncTotals(trackerDir) {
2436
+ const queuePath = path.join(trackerDir, "queue.jsonl");
2437
+ let raw;
2438
+ try {
2439
+ raw = fssync.readFileSync(queuePath, "utf8");
2440
+ } catch (_e) {
2441
+ return { totalTokens: 0, sources: [] };
2442
+ }
2443
+ let totalTokens = 0;
2444
+ const sources = new Set();
2445
+ // Each sync appends cumulative totals per (source, model, hour_start); keep
2446
+ // the last entry per bucket to match what the dashboard shows.
2447
+ const latest = new Map();
2448
+ for (const line of raw.split("\n")) {
2449
+ const trimmed = line.trim();
2450
+ if (!trimmed) continue;
2451
+ try {
2452
+ const row = JSON.parse(trimmed);
2453
+ const key = `${row.source || ""}|${row.model || ""}|${row.hour_start || ""}`;
2454
+ latest.set(key, row);
2455
+ } catch {
2456
+ // skip malformed
2457
+ }
2458
+ }
2459
+ for (const row of latest.values()) {
2460
+ const n = Number(row.total_tokens);
2461
+ if (Number.isFinite(n) && n > 0) totalTokens += n;
2462
+ if (row.source) sources.add(row.source);
2463
+ }
2464
+ return { totalTokens, sources: Array.from(sources) };
2465
+ }
2466
+
2467
+ async function copyRuntimeDependencies({ from, to }) {
2468
+ try {
2469
+ const st = await fs.stat(from);
2470
+ if (!st.isDirectory()) return;
2471
+ } catch (_e) {
2472
+ return;
2473
+ }
2474
+
2475
+ try {
2476
+ await fs.cp(from, to, { recursive: true });
2477
+ } catch (_e) {
2478
+ // Best-effort: missing dependencies will fall back to npx at notify time.
2479
+ }
2480
+ }
2481
+
2482
+ function isDebugEnabled() {
2483
+ return process.env.TOKENUSAGE_DEBUG === "1";
2484
+ }