tokenusage-cli 0.1.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.
- package/CHANGELOG.md +19 -0
- package/LICENSE +22 -0
- package/README.md +94 -0
- package/THIRD_PARTY_NOTICES.md +140 -0
- package/bin/tokenusage.js +69 -0
- package/package.json +59 -0
- package/src/cli.js +134 -0
- package/src/commands/device-login.js +205 -0
- package/src/commands/diagnostics.js +38 -0
- package/src/commands/doctor.js +110 -0
- package/src/commands/init.js +2436 -0
- package/src/commands/sessions.js +29 -0
- package/src/commands/status.js +1747 -0
- package/src/commands/sync.js +7934 -0
- package/src/commands/uninstall.js +312 -0
- package/src/lib/account-usage-dedup.js +267 -0
- package/src/lib/antigravity-paths.js +48 -0
- package/src/lib/ark-agent-plan-limits.js +438 -0
- package/src/lib/ark-coding-plan-limits.js +537 -0
- package/src/lib/async-queue-reader.js +138 -0
- package/src/lib/atomic-json.js +27 -0
- package/src/lib/bearer-token.js +11 -0
- package/src/lib/categorizer-utils.js +232 -0
- package/src/lib/claude-categorizer.js +1343 -0
- package/src/lib/claude-config.js +279 -0
- package/src/lib/claude-user-identity.js +56 -0
- package/src/lib/cli-ui.js +179 -0
- package/src/lib/cloud-account.js +541 -0
- package/src/lib/cloud-device-token.js +141 -0
- package/src/lib/cloud-sync-prefs.js +14 -0
- package/src/lib/cloud-usage-reset.js +115 -0
- package/src/lib/codex-config.js +595 -0
- package/src/lib/codex-context-breakdown.js +806 -0
- package/src/lib/codex-model-attribution.js +128 -0
- package/src/lib/codex-rollout-parser.js +1471 -0
- package/src/lib/codex-service-tier.js +49 -0
- package/src/lib/codex-token-refresh.js +140 -0
- package/src/lib/codex-token-usage.js +195 -0
- package/src/lib/codex-usage-record.js +195 -0
- package/src/lib/command-runner.js +313 -0
- package/src/lib/commandcode-limits.js +317 -0
- package/src/lib/context-health.js +124 -0
- package/src/lib/cursor-config.js +605 -0
- package/src/lib/cursor-store.js +1918 -0
- package/src/lib/debug-flags.js +7 -0
- package/src/lib/devin-limits.js +249 -0
- package/src/lib/devin-usage.js +212 -0
- package/src/lib/diagnostics.js +383 -0
- package/src/lib/doctor.js +385 -0
- package/src/lib/dumate.js +95 -0
- package/src/lib/fs.js +455 -0
- package/src/lib/function-url.js +14 -0
- package/src/lib/gemini-config.js +291 -0
- package/src/lib/git-outcomes.js +243 -0
- package/src/lib/grok-context-breakdown.js +890 -0
- package/src/lib/grok-hook.js +360 -0
- package/src/lib/grok-limits.js +865 -0
- package/src/lib/grok-usage.js +98 -0
- package/src/lib/heatmap-compact.js +114 -0
- package/src/lib/ingest-sanitize.js +41 -0
- package/src/lib/init-flow.js +42 -0
- package/src/lib/install-resolver.js +170 -0
- package/src/lib/jsonl-lines.js +134 -0
- package/src/lib/kimi-model-repair.js +173 -0
- package/src/lib/kimi-profile.js +61 -0
- package/src/lib/kimi-session.js +216 -0
- package/src/lib/local-api.js +3588 -0
- package/src/lib/machine-id.js +238 -0
- package/src/lib/multi-install-parser.js +113 -0
- package/src/lib/notify-command.js +38 -0
- package/src/lib/omp-hook.js +589 -0
- package/src/lib/openclaw-cli.js +104 -0
- package/src/lib/openclaw-hook.js +375 -0
- package/src/lib/openclaw-session-plugin.js +560 -0
- package/src/lib/opencode-config.js +121 -0
- package/src/lib/opencode-go-limits.js +807 -0
- package/src/lib/outcomes-engine.js +253 -0
- package/src/lib/passive-mode.js +219 -0
- package/src/lib/pet-packages.js +722 -0
- package/src/lib/pricing/curated-overrides.json +822 -0
- package/src/lib/pricing/index.js +379 -0
- package/src/lib/pricing/litellm-fetcher.js +172 -0
- package/src/lib/pricing/matcher.js +456 -0
- package/src/lib/pricing/seed-snapshot.json +1 -0
- package/src/lib/progress.js +76 -0
- package/src/lib/project-usage-purge.js +117 -0
- package/src/lib/prompt.js +24 -0
- package/src/lib/provider-status.js +104 -0
- package/src/lib/proxy-env.js +489 -0
- package/src/lib/proxy-settings.js +163 -0
- package/src/lib/qoder-cn-cli-limits.js +119 -0
- package/src/lib/qoder-limits.js +880 -0
- package/src/lib/quiet-warnings.js +26 -0
- package/src/lib/rollout.js +25966 -0
- package/src/lib/runtime-config.js +259 -0
- package/src/lib/scan-roots.js +277 -0
- package/src/lib/sentry.js +231 -0
- package/src/lib/session-analytics.js +2972 -0
- package/src/lib/session-performance.js +237 -0
- package/src/lib/session-upload.js +379 -0
- package/src/lib/skill-usage.js +267 -0
- package/src/lib/skills-manager.js +1591 -0
- package/src/lib/source-metadata.js +48 -0
- package/src/lib/sqlite-reader.js +215 -0
- package/src/lib/star-cta.js +73 -0
- package/src/lib/subscription-manager.js +293 -0
- package/src/lib/subscriptions.js +508 -0
- package/src/lib/telemetry.js +193 -0
- package/src/lib/tracker-paths.js +16 -0
- package/src/lib/trae-cn-config.js +548 -0
- package/src/lib/trae-db.js +127 -0
- package/src/lib/trae-snapshot.js +230 -0
- package/src/lib/trae-sqlite.js +143 -0
- package/src/lib/trae-usage.js +121 -0
- package/src/lib/upload-queue.js +134 -0
- package/src/lib/upload-throttle.js +171 -0
- package/src/lib/usage-limits.js +4552 -0
- package/src/lib/wrapped-aggregator.js +236 -0
- package/src/lib/wsl-probe.js +281 -0
- package/src/lib/zcode-limits.js +1172 -0
- package/src/lib/zcode-reset-credits.js +66 -0
- package/test/cli-smoke.test.js +53 -0
- package/test/ingest-sanitize.test.js +162 -0
- package/test/quiet-warnings.test.js +53 -0
- package/test/session-upload.test.js +427 -0
|
@@ -0,0 +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 {
|
|
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
|
+
}
|