tokenusage-cli 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,1747 +1,1758 @@
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 pkg = require("../../package.json");
6
- const { resolveDumateDbPaths } = require("../lib/dumate");
7
-
8
- const { readJson } = require("../lib/fs");
9
- const { readCursorStateSummary } = require("../lib/cursor-store");
10
- const {
11
- readCodexNotify,
12
- readAcodeNotify,
13
- readEveryCodeNotify,
14
- buildCodexNotifyCmd,
15
- buildAcodeNotifyCmd,
16
- isManagedNotifyCmd,
17
- } = require("../lib/codex-config");
18
- const { countRecordOnlyFiles, formatRecordOnlyWarning } = require("../lib/codex-usage-record");
19
- const {
20
- isClaudeHookConfigured,
21
- areClaudeUsageHooksConfigured,
22
- buildClaudeHookCommand,
23
- buildHookCommand,
24
- } = require("../lib/claude-config");
25
- const {
26
- resolveGeminiConfigDir,
27
- resolveGeminiSettingsPath,
28
- isGeminiHookConfigured,
29
- buildGeminiHookCommand,
30
- } = require("../lib/gemini-config");
31
- const {
32
- resolveOpencodeConfigDir,
33
- isOpencodePluginInstalled,
34
- } = require("../lib/opencode-config");
35
- const { collectLocalSubscriptions } = require("../lib/subscriptions");
36
- const {
37
- describeCopilotOtelStatus,
38
- readCopilotOauthToken,
39
- } = require("../lib/usage-limits");
40
- const {
41
- normalizeState: normalizeUploadState,
42
- } = require("../lib/upload-throttle");
43
- const { collectTrackerDiagnostics } = require("../lib/diagnostics");
44
- const { detectPassiveProviders, isPassiveModeActive } = require("../lib/passive-mode");
45
- const { probeOpenclawHookState } = require("../lib/openclaw-hook");
46
- const {
47
- probeOpenclawSessionPluginState,
48
- } = require("../lib/openclaw-session-plugin");
49
- const { resolveTrackerPaths } = require("../lib/tracker-paths");
50
- const { resolveDeviceTokenPresence } = require("../lib/cloud-device-token");
51
- const {
52
- resolveKimiWireFiles,
53
- resolveKimiCodeWireFiles,
54
- resolveKiroCliDbPath,
55
- resolveKiroCliSessionFiles,
56
- resolveKiroBasePath,
57
- resolveKiroDbPath,
58
- resolveKiroJsonlPath,
59
- resolveCodebuddyHome,
60
- resolveCodebuddyProjectFiles,
61
- resolveWorkbuddyHome,
62
- resolveWorkbuddyProjectFiles,
63
- resolveOmpSessionFiles,
64
- resolveOmpAgentDir,
65
- resolveOmoSessionFiles,
66
- resolveOmoAgentDir,
67
- resolveMinimaxCodeSessionFiles,
68
- resolveMinimaxCodeSessionsDir,
69
- resolvePiSessionFiles,
70
- resolvePiAgentDir,
71
- piAgentDirCollidesWithOmp,
72
- resolvePrimeAgentSessionFiles,
73
- resolvePrimeAgentDir,
74
- resolveCraftSessionFiles,
75
- resolveCraftConfigDir,
76
- resolveReasonixHome,
77
- resolveReasonixTelemetryFiles,
78
- resolveMuseHome,
79
- resolveMuseSessionFiles,
80
- resolveKilocodeTaskFiles,
81
- resolveRoocodeTaskFiles,
82
- resolveClineSessionFilesWithStatus,
83
- resolveZedDbPath,
84
- resolveLmstudioHome,
85
- resolveLmstudioLogFiles,
86
- resolveUnslothDbPath,
87
- resolveQoderDbPaths,
88
- resolveQoderCnDbPaths,
89
- resolveQoderProjectsDir,
90
- resolveQoderCnProjectsDir,
91
- listQoderNewSessionFiles,
92
- resolveClaudeScienceDbPaths,
93
- resolveAnythingllmDbPath,
94
- resolveDevinDbPath,
95
- resolveGooseDbPath,
96
- listDroidSettingsFiles,
97
- resolveDroidSessionsDir,
98
- resolveDshHomes,
99
- resolveDshSessionFiles,
100
- resolveCommandCodeHomes,
101
- resolveCommandCodeSessionFiles,
102
- resolveTraeStoragePath,
103
- readTraeEntitlementFromStorage,
104
- resolveGrokBuildSessions,
105
- resolveHermesPath,
106
- resolveHermesDbPath,
107
- resolveCopilotSessionStorePaths,
108
- describeCopilotSessionStoreDb,
109
- resolveCopilotAppDbPath,
110
- resolveCopilotAppDbPaths,
111
- probeWslDistros,
112
- resolveZcodeInstallPaths,
113
- } = require("../lib/rollout");
114
- const {
115
- TRAE_CN_USAGE_ENV,
116
- isTraeCnUsageEnabled,
117
- resolveTraeCnStoragePath,
118
- readTraeCnAuthFromStorage,
119
- extractTraeCnToken,
120
- } = require("../lib/trae-cn-config");
121
- const wsl = require("../lib/wsl-probe");
122
- const { getWslMode, isInvalidWslMode, shouldProbeWsl, discoverWslHome } = wsl;
123
- const { resolveInstallPaths, resolveZcodeNativeDbPath, resolveMimoNativeDbPath } = require("../lib/install-resolver");
124
- const {
125
- describeScanRootOrigin,
126
- describeScanRootState,
127
- hasAnyScanChild,
128
- resolveEnvRoot,
129
- resolveScanRoots,
130
- } = require("../lib/scan-roots");
131
- const { probeGrokHookState, resolveGrokHome } = require("../lib/grok-hook");
132
- const { probeOmpHookState } = require("../lib/omp-hook");
133
-
134
- // `filename` may be a list, in which case the first child that exists wins. A
135
- // resolver using requireAnyChild accepts a root that holds ANY of several
136
- // children, so probing only the first one here would report "not detected" for
137
- // an install sync happily counts (e.g. Codex with archived_sessions/ but no
138
- // live sessions/).
139
- function formatResolvedPaths(paths, filename) {
140
- const candidates = filename == null ? [] : (Array.isArray(filename) ? filename : [filename]);
141
- const resolveFile = (root) => {
142
- if (candidates.length === 0) return root;
143
- for (const candidate of candidates) {
144
- const file = path.join(root, candidate);
145
- try { if (fssync.existsSync(file)) return file; } catch (_e) {}
146
- }
147
- return null;
148
- };
149
- const active = [];
150
- for (const [label, root] of [["native", paths.native], ["WSL", paths.wsl]]) {
151
- if (!root) continue;
152
- const file = resolveFile(root);
153
- if (!file) continue;
154
- try { if (fssync.existsSync(file)) active.push(`${label}: ${file}`); } catch (_e) {}
155
- }
156
- return active;
157
- }
158
-
159
- // Combine a legacy DB path with its new-JSONL projects-dir path for the
160
- // machine-readable summary. Either side may be "" (absent); both absent
161
- // yields "" so callers can fall back to "not found".
162
- function summarizeQoderDetail(dbPath, newPath) {
163
- return [dbPath, newPath].filter(Boolean).join(" + ") || "";
164
- }
165
-
166
- // The Trae SOLO entitlement snapshot is read directly from the Trae Local
167
- // State storage.json via the shared parser (readTraeEntitlementFromStorage).
168
- // The queue.jsonl contract is token-count-only (CLAUDE.md privacy rule), so
169
- // plan/limits metadata is never persisted into queue rows — this is the read
170
- // side of that contract so users can actually see the advertised plan data.
171
- function formatTraeEntitlementLine(ent) {
172
- const parts = [];
173
- if (ent.identity) parts.push(`plan ${ent.identity}`);
174
- if (ent.pro_period) parts.push(`${ent.pro_period} period`);
175
- if (typeof ent.is_dollar_billing === "boolean") {
176
- parts.push(ent.is_dollar_billing ? "dollar billing" : "package billing");
177
- }
178
- if (typeof ent.enable_solo_builder === "boolean") {
179
- parts.push(`solo builder: ${ent.enable_solo_builder ? "yes" : "no"}`);
180
- }
181
- if (typeof ent.enable_solo_coder === "boolean") {
182
- parts.push(`solo coder: ${ent.enable_solo_coder ? "yes" : "no"}`);
183
- }
184
- if (typeof ent.fast_request_per === "number") {
185
- parts.push(`${ent.fast_request_per} fast requests/hr`);
186
- }
187
- if (ent.in_waitlist === true) parts.push("in waitlist");
188
- if (ent.captured_at) parts.push(`snapshot ${ent.captured_at}`);
189
- return parts.length ? parts.join(", ") : "unknown";
190
- }
191
-
192
- async function cmdStatus(argv = []) {
193
- const opts = parseArgs(argv);
194
- if (opts.diagnostics) {
195
- const diagnostics = await collectTrackerDiagnostics();
196
- process.stdout.write(JSON.stringify(diagnostics, null, 2) + "\n");
197
- return;
198
- }
199
-
200
- const home = os.homedir();
201
- const { trackerDir, binDir } = await resolveTrackerPaths({ home });
202
- const configPath = path.join(trackerDir, "config.json");
203
- const queuePath = path.join(trackerDir, "queue.jsonl");
204
- const queueStatePath = path.join(trackerDir, "queue.state.json");
205
- const cursorsPath = path.join(trackerDir, "cursors.json");
206
- const notifySignalPath = path.join(trackerDir, "notify.signal");
207
- const openclawSignalPath = path.join(trackerDir, "openclaw.signal");
208
- const throttlePath = path.join(trackerDir, "sync.throttle");
209
- const uploadThrottlePath = path.join(trackerDir, "upload.throttle.json");
210
- const autoRetryPath = path.join(trackerDir, "auto.retry.json");
211
- const syncSkipPath = path.join(trackerDir, "sync.skip.json");
212
- // Normalized like sync (a relative CODEX_HOME is anchored to home, not cwd)
213
- // so status lists exactly the root sync walks.
214
- const codexHome = resolveEnvRoot("codex", { env: process.env, home }) || path.join(home, ".codex");
215
- const codexConfigPath = path.join(codexHome, "config.toml");
216
- const acodeHome = process.env.TOKENUSAGE_ACODE_HOME || path.join(home, ".acode");
217
- const acodeConfigPath = path.join(acodeHome, "config.toml");
218
- const codeHome = process.env.CODE_HOME || path.join(home, ".code");
219
- const codeConfigPath = path.join(codeHome, "config.toml");
220
- const claudeSettingsPath = path.join(home, ".claude", "settings.json");
221
- const codebuddySettingsPath = path.join(
222
- resolveCodebuddyHome(process.env) || path.join(home, ".codebuddy"),
223
- "settings.json",
224
- );
225
- const workbuddySettingsPath = path.join(
226
- resolveWorkbuddyHome(process.env) || path.join(home, ".workbuddy"),
227
- "settings.json",
228
- );
229
- // WorkBuddy AI — international build, sibling home (~/.workbuddy-ai).
230
- const workbuddyAiSettingsPath = path.join(
231
- resolveWorkbuddyHome(process.env, "workbuddy-ai") || path.join(home, ".workbuddy-ai"),
232
- "settings.json",
233
- );
234
- const geminiConfigDir = resolveGeminiConfigDir({ home, env: process.env });
235
- const geminiSettingsPath = resolveGeminiSettingsPath({
236
- configDir: geminiConfigDir,
237
- });
238
- const opencodeConfigDir = resolveOpencodeConfigDir({
239
- home,
240
- env: process.env,
241
- });
242
- const notifyPath = path.join(binDir, "notify.cjs");
243
- const codexNotifyCmd = buildCodexNotifyCmd(notifyPath);
244
- const acodeNotifyCmd = buildAcodeNotifyCmd(notifyPath);
245
- const claudeHookCommand = buildClaudeHookCommand(notifyPath);
246
- const codebuddyHookCommand = buildHookCommand(notifyPath, "codebuddy");
247
- const workbuddyHookCommand = buildHookCommand(notifyPath, "workbuddy");
248
- const workbuddyAiHookCommand = buildHookCommand(notifyPath, "workbuddy-ai");
249
- const geminiHookCommand = buildGeminiHookCommand(notifyPath);
250
-
251
- const config = await readJson(configPath);
252
- // Extra scan roots (#657): CODEX_HOME / CLAUDE_CONFIG_DIR of this process
253
- // plus config.scanRoots, resolved exactly as sync does, so status lists every
254
- // root sync walks — this is the output users paste when usage looks wrong.
255
- const scanRoots = resolveScanRoots({
256
- home,
257
- env: process.env,
258
- config,
259
- base: { codex: [codexHome], claude: [path.join(home, ".claude")] },
260
- });
261
- const extraScanRoots = [];
262
- for (const provider of ["codex", "claude"]) {
263
- for (const entry of scanRoots[provider]) {
264
- if (entry.origin === "native") continue;
265
- extraScanRoots.push({
266
- provider,
267
- origin: describeScanRootOrigin(entry, provider),
268
- path: entry.path,
269
- exists: entry.exists,
270
- error: entry.error || null,
271
- });
272
- }
273
- }
274
- const describeExtraScanRoot = (root) =>
275
- `${root.provider} ${root.origin}: ${root.path}${describeScanRootState(root)}`;
276
- const scanRootsLine = extraScanRoots.length > 0
277
- ? `- Extra scan roots: ${extraScanRoots.map(describeExtraScanRoot).join(" | ")}`
278
- : null;
279
- const { cursors } = await readCursorStateSummary({ trackerDir, cursorsPath });
280
- const codexRecordOnlyWarning = formatRecordOnlyWarning(countRecordOnlyFiles(cursors));
281
- const queueState = (await readJson(queueStatePath)) || { offset: 0 };
282
- const uploadThrottle = normalizeUploadState(
283
- await readJson(uploadThrottlePath),
284
- );
285
- const autoRetry = await readJson(autoRetryPath);
286
- // Written by sync whenever it had to skip a run. Present here so a stalled
287
- // parse has a visible cause instead of only a frozen "Last parse".
288
- const syncSkip = await readJson(syncSkipPath);
289
-
290
- const queueSize = await safeStatSize(queuePath);
291
- const pendingBytes = Math.max(0, queueSize - (queueState.offset || 0));
292
-
293
- const lastNotify = (await safeReadText(notifySignalPath))?.trim() || null;
294
- const lastOpenclawSync =
295
- (await safeReadText(openclawSignalPath))?.trim() || null;
296
- const lastNotifySpawn = parseEpochMsToIso(
297
- (await safeReadText(throttlePath))?.trim() || null,
298
- );
299
-
300
- const codexNotify = await readCodexNotify(codexConfigPath);
301
- // Not arraysEqual: argv[0] and binDir differ between the desktop app and a
302
- // terminal `tokenusage` run, so a correctly-installed integration would
303
- // otherwise report as not configured. See isManagedNotifyCmd.
304
- const notifyConfigured = isManagedNotifyCmd(codexNotify, codexNotifyCmd);
305
- const acodeNotify = await readAcodeNotify(acodeConfigPath);
306
- const acodeConfigured = isManagedNotifyCmd(acodeNotify, acodeNotifyCmd);
307
- const everyCodeNotify = await readEveryCodeNotify(codeConfigPath);
308
- const everyCodeConfigured =
309
- Array.isArray(everyCodeNotify) && everyCodeNotify.length > 0;
310
- const claudeHookConfigured = await areClaudeUsageHooksConfigured({
311
- settingsPath: claudeSettingsPath,
312
- hookCommand: claudeHookCommand,
313
- });
314
- const codebuddyHookConfigured = await isClaudeHookConfigured({
315
- settingsPath: codebuddySettingsPath,
316
- hookCommand: codebuddyHookCommand,
317
- });
318
- const workbuddyHookConfigured = await isClaudeHookConfigured({
319
- settingsPath: workbuddySettingsPath,
320
- hookCommand: workbuddyHookCommand,
321
- });
322
- const workbuddyAiHookConfigured = await isClaudeHookConfigured({
323
- settingsPath: workbuddyAiSettingsPath,
324
- hookCommand: workbuddyAiHookCommand,
325
- });
326
- const geminiHookConfigured = await isGeminiHookConfigured({
327
- settingsPath: geminiSettingsPath,
328
- hookCommand: geminiHookCommand,
329
- });
330
- const opencodePluginConfigured = await isOpencodePluginInstalled({
331
- configDir: opencodeConfigDir,
332
- });
333
- const openclawSessionPluginState = await probeOpenclawSessionPluginState({
334
- home,
335
- trackerDir,
336
- env: process.env,
337
- });
338
- const openclawHookState = await probeOpenclawHookState({
339
- home,
340
- trackerDir,
341
- env: process.env,
342
- });
343
-
344
- const lastUpload = uploadThrottle.lastSuccessMs
345
- ? parseEpochMsToIso(uploadThrottle.lastSuccessMs)
346
- : typeof queueState.updatedAt === "string"
347
- ? queueState.updatedAt
348
- : null;
349
- const nextUpload = parseEpochMsToIso(uploadThrottle.nextAllowedAtMs || null);
350
- const backoffUntil = parseEpochMsToIso(uploadThrottle.backoffUntilMs || null);
351
- const lastUploadError = uploadThrottle.lastError
352
- ? `${uploadThrottle.lastErrorAt || "unknown"} ${uploadThrottle.lastError}`
353
- : null;
354
- const syncSkipLine = syncSkip?.at
355
- ? `- Last sync skipped: ${syncSkip.at} (${syncSkip.reason || "unknown"}${
356
- syncSkip.detail ? `, ${syncSkip.detail}` : ""
357
- })`
358
- : null;
359
- const autoRetryAt = parseEpochMsToIso(autoRetry?.retryAtMs || null);
360
- const autoRetryLine = autoRetryAt
361
- ? `- Auto retry after: ${autoRetryAt} (${autoRetry?.reason || "scheduled"}, pending ${Number(
362
- autoRetry?.pendingBytes || 0,
363
- )} bytes)`
364
- : null;
365
-
366
- const subscriptions = await collectLocalSubscriptions({
367
- home,
368
- env: process.env,
369
- probeKeychain: opts.probeKeychain,
370
- probeKeychainDetails: opts.probeKeychainDetails,
371
- });
372
- const subscriptionLines =
373
- subscriptions.length > 0 ? subscriptions.map(formatSubscriptionLine) : [];
374
-
375
- const kimiWireFiles = resolveKimiWireFiles(process.env);
376
- const kimiHome = process.env.KIMI_HOME || path.join(home, ".kimi");
377
- const kimiInstalled = fssync.existsSync(path.join(kimiHome, "sessions"));
378
-
379
- const kimiCodeWireFiles = resolveKimiCodeWireFiles(process.env);
380
- const kimiCodeHome = process.env.KIMI_CODE_HOME || path.join(home, ".kimi-code");
381
- const kimiCodeInstalled = fssync.existsSync(path.join(kimiCodeHome, "sessions"));
382
-
383
- // Kiro CLI — reads the legacy SQLite/session files and Kiro CLI 2.13+
384
- // event sessions. End-user dashboards show them merged under "Kiro"; this
385
- // status line surfaces which passive sources are actually present.
386
- const kiroCliDbPath = resolveKiroCliDbPath(process.env);
387
- const kiroCliSessionFiles = resolveKiroCliSessionFiles(process.env);
388
- const kiroCliNativePresent =
389
- fssync.existsSync(kiroCliDbPath) || kiroCliSessionFiles.length > 0;
390
- // WSL install discovery mirrors sync: overrides pin a single install.
391
- let kiroCliWsl = null; // { db, sessionFiles }
392
- if (
393
- process.platform === "win32" &&
394
- !process.env.KIRO_CLI_DB_PATH && !process.env.KIRO_HOME &&
395
- wsl.shouldProbeWsl(process.env)
396
- ) {
397
- const wslKiroHomeDir = wsl.discoverWslHome(".kiro");
398
- const wslCliDataDir = wsl.discoverWslHome(".local/share/kiro-cli");
399
- const wslHomeRoot = wslKiroHomeDir
400
- ? path.dirname(wslKiroHomeDir)
401
- : (wslCliDataDir ? path.dirname(path.dirname(path.dirname(wslCliDataDir))) : null);
402
- if (wslHomeRoot) {
403
- const wslDb = path.join(wslHomeRoot, ".local", "share", "kiro-cli", "data.sqlite3");
404
- const wslFiles = resolveKiroCliSessionFiles({
405
- ...process.env,
406
- KIRO_CLI_DB_PATH: wslDb,
407
- KIRO_HOME: path.join(wslHomeRoot, ".kiro"),
408
- });
409
- if (fssync.existsSync(wslDb) || wslFiles.length > 0) {
410
- kiroCliWsl = { db: wslDb, sessionFiles: wslFiles };
411
- }
412
- }
413
- }
414
- const kiroCliPaths = process.platform === "win32"
415
- ? wsl.resolveAllWin32Paths({
416
- nativeValue: kiroCliNativePresent ? kiroCliDbPath : null,
417
- wslValue: kiroCliWsl ? kiroCliWsl.db : null,
418
- env: process.env,
419
- platform: "win32",
420
- })
421
- : { native: kiroCliNativePresent ? kiroCliDbPath : null, wsl: null };
422
- // Non-both modes park the picked value in the native slot — label by
423
- // marker identity, not slot name. A session-files-only install has no DB
424
- // on disk; show the sessions dir instead of a nonexistent DB path.
425
- const kiroCliMarkers = [kiroCliPaths.native, kiroCliPaths.wsl].filter(Boolean);
426
- const kiroCliActive = kiroCliMarkers.map((m) => {
427
- if (kiroCliWsl && m === kiroCliWsl.db) {
428
- const shown = fssync.existsSync(m) || kiroCliWsl.sessionFiles.length === 0
429
- ? m
430
- : path.dirname(kiroCliWsl.sessionFiles[0]);
431
- return `WSL: ${shown}`;
432
- }
433
- const shown = fssync.existsSync(m) || kiroCliSessionFiles.length === 0
434
- ? m
435
- : path.dirname(kiroCliSessionFiles[0]);
436
- return `native: ${shown}`;
437
- });
438
- const kiroCliFileCount =
439
- (kiroCliMarkers.includes(kiroCliDbPath) ? kiroCliSessionFiles.length : 0) +
440
- (kiroCliWsl && kiroCliMarkers.includes(kiroCliWsl.db) ? kiroCliWsl.sessionFiles.length : 0);
441
- const kiroCliDbFound = kiroCliMarkers.some((m) => {
442
- try { return fssync.existsSync(m); } catch (_e) { return false; }
443
- });
444
- const kiroCliInstalled = kiroCliMarkers.length > 0;
445
-
446
- // Kiro IDE — passive scan of globalStorage dev_data (SQLite or JSONL).
447
- const kiroIdeNativeBase = resolveKiroBasePath(process.env);
448
- const wslKiroIdeBase = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
449
- ? wsl.discoverWslHome(".config/Kiro/User/globalStorage/kiro.kiroagent")
450
- : null;
451
- const kiroIdePaths = resolveInstallPaths({ nativeValue: kiroIdeNativeBase, wslValue: wslKiroIdeBase });
452
- const kiroIdeHasData = (base) => Boolean(base)
453
- && (fssync.existsSync(resolveKiroDbPath(base)) || fssync.existsSync(resolveKiroJsonlPath(base)));
454
- const kiroIdeActive = [kiroIdePaths.native, kiroIdePaths.wsl]
455
- .filter((base) => kiroIdeHasData(base))
456
- .map((base) => (wslKiroIdeBase && base === wslKiroIdeBase ? `WSL: ${base}` : `native: ${base}`));
457
- const kiroIdeInstalled = kiroIdeActive.length > 0;
458
-
459
- // Claude Code — dual-install aware projects scan (#307). Mirrors sync:
460
- // installs are UNIONED (not single-picked by mode) so a WSL ~/.claude
461
- // never hides the native one from view, and labels come from install
462
- // identity rather than resolveAllWin32Paths' slot names.
463
- const claudeCodeActive = [];
464
- {
465
- const claudeHomesStatus = [];
466
- if (process.platform !== "win32" || wsl.shouldProbeNative(process.env)) {
467
- claudeHomesStatus.push({ dir: path.join(home, ".claude"), label: "native" });
468
- }
469
- const wslClaudeHomeStatus = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
470
- ? wsl.discoverWslHome(".claude")
471
- : null;
472
- if (wslClaudeHomeStatus) claudeHomesStatus.push({ dir: wslClaudeHomeStatus, label: "WSL" });
473
- for (const entry of scanRoots.claude) {
474
- if (entry.origin === "native" || !entry.exists) continue;
475
- claudeHomesStatus.push({ dir: entry.path, label: describeScanRootOrigin(entry, "claude") });
476
- }
477
- for (const { dir, label } of claudeHomesStatus) {
478
- const projects = path.join(dir, "projects");
479
- try {
480
- if (fssync.existsSync(projects)) claudeCodeActive.push(`${label}: ${projects}`);
481
- } catch (_e) {}
482
- }
483
- }
484
- const claudeCodeInstalled = claudeCodeActive.length > 0;
485
-
486
- // AnythingLLM Desktop — per-message token metrics in workspace_chats.
487
- const anythingllmDbPath = resolveAnythingllmDbPath(process.env);
488
- const anythingllmInstalled = Boolean(
489
- anythingllmDbPath && fssync.existsSync(anythingllmDbPath),
490
- );
491
-
492
- // CodeBuddy — passive scan only (no hooks). Surface the file count so
493
- // operators can confirm JSONL sessions and extension logs are discovered.
494
- const codebuddyHome = resolveCodebuddyHome(process.env);
495
- const codebuddyInstalled = Boolean(codebuddyHome && fssync.existsSync(codebuddyHome));
496
- const codebuddyFiles = codebuddyInstalled
497
- ? resolveCodebuddyProjectFiles(process.env)
498
- : [];
499
-
500
- // WorkBuddy — passive scan (sibling Claude-Code fork). Surface both the
501
- // recursive JSONL count and SQLite fallback so operators can confirm coverage.
502
- const workbuddyHome = resolveWorkbuddyHome(process.env);
503
- const workbuddyInstalled = Boolean(workbuddyHome && fssync.existsSync(workbuddyHome));
504
- const workbuddyFiles = workbuddyInstalled
505
- ? resolveWorkbuddyProjectFiles(process.env)
506
- : [];
507
- const workbuddyDbExists = workbuddyInstalled
508
- ? fssync.existsSync(path.join(workbuddyHome, "workbuddy.db"))
509
- : false;
510
-
511
- const workbuddyAiHome = resolveWorkbuddyHome(process.env, "workbuddy-ai");
512
- const workbuddyAiInstalled = Boolean(workbuddyAiHome && fssync.existsSync(workbuddyAiHome));
513
- const workbuddyAiFiles = workbuddyAiInstalled
514
- ? resolveWorkbuddyProjectFiles(process.env, "workbuddy-ai")
515
- : [];
516
- const workbuddyAiDbExists = workbuddyAiInstalled
517
- ? fssync.existsSync(path.join(workbuddyAiHome, "workbuddy.db"))
518
- : false;
519
-
520
- // oh-my-pi — passive scan + optional notify extension.
521
- const ompAgentDir = resolveOmpAgentDir(process.env);
522
- const ompInstalled = Boolean(ompAgentDir) && fssync.existsSync(path.join(ompAgentDir, "sessions"));
523
- const ompFiles = ompInstalled ? resolveOmpSessionFiles(process.env) : [];
524
- const ompHookState = await probeOmpHookState({ home, trackerDir, env: process.env });
525
-
526
- // OmO — passive scan only (no hooks).
527
- const omoAgentDir = resolveOmoAgentDir(process.env);
528
- const omoInstalled = Boolean(omoAgentDir) && fssync.existsSync(path.join(omoAgentDir, "sessions"));
529
- const omoFiles = omoInstalled ? resolveOmoSessionFiles(process.env) : [];
530
-
531
- // MiniMax Code — passive scan only (no hooks).
532
- const minimaxCodeSessionsDir = resolveMinimaxCodeSessionsDir(process.env);
533
- const minimaxCodeInstalled = Boolean(minimaxCodeSessionsDir) && fssync.existsSync(minimaxCodeSessionsDir);
534
- const minimaxCodeFiles = minimaxCodeInstalled ? resolveMinimaxCodeSessionFiles(process.env) : [];
535
-
536
- // pi (@mariozechner/pi-coding-agent) — passive scan only (no hooks).
537
- // Skip when its agent dir collides with omp's; sync would dedupe anyway.
538
- const piCollides = piAgentDirCollidesWithOmp(process.env);
539
- const piAgentDir = resolvePiAgentDir(process.env);
540
- const piInstalled = !piCollides && Boolean(piAgentDir) && fssync.existsSync(path.join(piAgentDir, "sessions"));
541
- const piFiles = piInstalled ? resolvePiSessionFiles(process.env) : [];
542
-
543
- // Prime Agent — passive scan only (no hooks).
544
- const primeAgentDir = resolvePrimeAgentDir(process.env);
545
- const primeAgentInstalled = Boolean(primeAgentDir) && fssync.existsSync(path.join(primeAgentDir, "sessions"));
546
- const primeAgentFiles = primeAgentInstalled ? resolvePrimeAgentSessionFiles(process.env) : [];
547
-
548
- // Craft Agents — passive scan only (no hooks).
549
- const craftConfigDir = resolveCraftConfigDir(process.env);
550
- const craftInstalled = Boolean(craftConfigDir && fssync.existsSync(craftConfigDir));
551
- const craftFiles = craftInstalled ? resolveCraftSessionFiles(process.env) : [];
552
-
553
- // Reasonix — passive scan of content-free cumulative telemetry sidecars.
554
- const reasonixHome = resolveReasonixHome(process.env);
555
- const reasonixInstalled = Boolean(reasonixHome && fssync.existsSync(reasonixHome));
556
- const reasonixFiles = reasonixInstalled ? resolveReasonixTelemetryFiles(process.env) : [];
557
-
558
- // Muse Code (Meta) — passive scan of per-session session.jsonl logs.
559
- const museInstalled = fssync.existsSync(path.join(resolveMuseHome(process.env), "sessions"));
560
- const museFiles = museInstalled ? resolveMuseSessionFiles(process.env) : [];
561
-
562
- // Kilo CLI (kilo.ai @kilocode/plugin) — passive scan of kilo.db.
563
- const xdgDataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
564
- const kiloHome = process.env.KILO_HOME || path.join(xdgDataHome, "kilo");
565
- const kiloNativeValue = process.platform === "win32" && typeof process.env.APPDATA === "string"
566
- ? path.join(process.env.APPDATA.trim(), "kilo", "kilo.db")
567
- : path.join(kiloHome, "kilo.db");
568
- const wslKiloDir = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
569
- ? wsl.discoverWslHome(".local/share/kilo")
570
- : null;
571
- const kiloPaths = resolveInstallPaths({ nativeValue: kiloNativeValue, wslValue: wslKiloDir ? path.join(wslKiloDir, "kilo.db") : null });
572
- const kiloActive = formatResolvedPaths(kiloPaths);
573
- const kiloInstalled = kiloActive.length > 0;
574
- const kiloDbPath = kiloActive.join(" | ");
575
-
576
- const dumateDbPaths = resolveDumateDbPaths({ home });
577
- const dumateInstalled = dumateDbPaths.length > 0;
578
- const dumateDbPath = dumateDbPaths.join(" | ");
579
-
580
- // Mimo (mimocode — OpenCode-fork SQLite) — passive scan of mimocode.db.
581
- const mimoNativeValue = resolveMimoNativeDbPath({ home });
582
- const wslMimoDir = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
583
- ? wsl.discoverWslHome(".local/share/mimocode")
584
- : null;
585
- const mimoPaths = resolveInstallPaths({ nativeValue: mimoNativeValue, wslValue: wslMimoDir ? path.join(wslMimoDir, "mimocode.db") : null });
586
- const mimoActive = formatResolvedPaths(mimoPaths);
587
- const mimoInstalled = mimoActive.length > 0;
588
- const mimoDbPath = mimoActive.join(" | ");
589
-
590
- // ZCode (Z.ai's coding agent — OpenCode-fork SQLite) — passive scan of db.sqlite.
591
- const zcodeNativeValue = resolveZcodeNativeDbPath({ home });
592
- const wslZcodeDir = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
593
- ? wsl.discoverWslHome(".zcode")
594
- : null;
595
- const zcodePaths = resolveZcodeInstallPaths(
596
- { nativeValue: zcodeNativeValue, wslValue: wslZcodeDir ? path.join(wslZcodeDir, "cli", "db", "db.sqlite") : null },
597
- process.env, { cursors },
598
- );
599
- const zcodeActive = formatResolvedPaths(zcodePaths);
600
- const zcodeInstalled = zcodeActive.length > 0;
601
- const zcodeDbPath = zcodeActive.join(" | ");
602
-
603
- // Qoder Desktop 1.18+ — token usage lives in SharedClientCache/local.db (legacy)
604
- // and since 2026-08 (app 0.1.2+) also in ~/.qoder/projects JSONL (credit-based).
605
- const qoderPaths = resolveQoderDbPaths({
606
- home,
607
- env: process.env,
608
- platform: process.platform,
609
- });
610
- const qoderActive = formatResolvedPaths(qoderPaths);
611
- // New JSONL location (com.qoder.app.stable + ~/.qoder/projects)
612
- const qoderProjectsDirResolved = resolveQoderProjectsDir({ home, env: process.env });
613
- let qoderNewFiles = [];
614
- try {
615
- qoderNewFiles = await listQoderNewSessionFiles(qoderProjectsDirResolved);
616
- } catch (_e) {
617
- qoderNewFiles = [];
618
- }
619
- const qoderNewInstalled = qoderNewFiles.length > 0;
620
- const qoderInstalled = qoderActive.length > 0 || qoderNewInstalled;
621
- const qoderDbPath = qoderActive.join(" | ");
622
- const qoderNewPath = qoderNewFiles.length > 0
623
- ? `${qoderProjectsDirResolved} (${qoderNewFiles.length} sessions)`
624
- : "";
625
-
626
- // Qoder CN (国内版) — same schema, separate Application Support/QoderCN dir.
627
- const qoderCnPaths = resolveQoderCnDbPaths({
628
- home,
629
- env: process.env,
630
- platform: process.platform,
631
- });
632
- const qoderCnActive = formatResolvedPaths(qoderCnPaths);
633
- // CN new-JSONL mirrors sync.js: the new CN app writes ~/.qoder-cn/projects,
634
- // but sync only parses the CN dir when it diverges from the international
635
- // one (same files must not count under two sources). Only report CN JSONL
636
- // when the dirs diverge.
637
- const qoderCnProjectsDirResolved = resolveQoderCnProjectsDir({ home, env: process.env });
638
- const qoderCnSharesIntlDir = path.normalize(qoderCnProjectsDirResolved) === path.normalize(qoderProjectsDirResolved)
639
- || (process.platform === "win32"
640
- && path.normalize(qoderCnProjectsDirResolved).toLowerCase() === path.normalize(qoderProjectsDirResolved).toLowerCase());
641
- let qoderCnNewFiles = [];
642
- if (!qoderCnSharesIntlDir) {
643
- try {
644
- qoderCnNewFiles = await listQoderNewSessionFiles(qoderCnProjectsDirResolved);
645
- } catch (_e) {
646
- qoderCnNewFiles = [];
647
- }
648
- }
649
- const qoderCnNewInstalled = qoderCnNewFiles.length > 0;
650
- const qoderCnInstalled = qoderCnActive.length > 0 || qoderCnNewInstalled;
651
- const qoderCnDbPath = qoderCnActive.join(" | ");
652
- const qoderCnNewPath = qoderCnNewFiles.length > 0
653
- ? `${qoderCnProjectsDirResolved} (${qoderCnNewFiles.length} sessions)`
654
- : "";
655
-
656
- // Claude Science — token usage lives on the `frames` table of operon-cli.db.
657
- // Unlike the native/WSL pair other providers resolve to, this is an open-ended
658
- // list: multi-org installs keep one DB per org (and on Windows they all sit
659
- // inside WSL), so the resolver already returns only paths that exist.
660
- const claudeScienceActive = resolveClaudeScienceDbPaths({ home, env: process.env });
661
- const claudeScienceInstalled = claudeScienceActive.length > 0;
662
- const claudeScienceDbPath = claudeScienceActive.join(" | ");
663
-
664
- // OpenCode (JSON files + SQLite DB) — passive scan of storage/message/ and opencode.db.
665
- const opencodeStorageNativeValue = process.env.OPENCODE_HOME || path.join(xdgDataHome, "opencode");
666
- const wslOpencodeStorageDir = process.platform === "win32" && shouldProbeWsl(process.env)
667
- ? discoverWslHome(".local/share/opencode")
668
- : null;
669
- const opencodeStoragePaths = resolveInstallPaths({
670
- nativeValue: opencodeStorageNativeValue,
671
- wslValue: wslOpencodeStorageDir,
672
- });
673
- const opencodeStorageActive = formatResolvedPaths(opencodeStoragePaths);
674
-
675
- const opencodeDbNativeValue = process.env.OPENCODE_HOME || path.join(xdgDataHome, "opencode");
676
- const wslOpencodeDbDir = process.platform === "win32" && shouldProbeWsl(process.env)
677
- ? discoverWslHome(".local/share/opencode")
678
- : null;
679
- const opencodeDbPaths = resolveInstallPaths({
680
- nativeValue: opencodeDbNativeValue,
681
- wslValue: wslOpencodeDbDir,
682
- });
683
- const opencodeDbActive = formatResolvedPaths(opencodeDbPaths, "opencode.db");
684
- const opencodeInstalled = opencodeStorageActive.length > 0 || opencodeDbActive.length > 0;
685
-
686
- // Every Code (passive sessions scan)
687
- const codePaths = resolveInstallPaths({
688
- nativeValue: process.env.CODE_HOME || path.join(home, ".code"),
689
- wslDir: ".code",
690
- });
691
- const codeActive = formatResolvedPaths(codePaths, "sessions");
692
- const codeInstalled = codeActive.length > 0;
693
-
694
- // Gemini CLI & Antigravity (shared home)
695
- const geminiPaths = resolveInstallPaths({
696
- nativeValue: process.env.GEMINI_HOME || path.join(home, ".gemini"),
697
- wslDir: ".gemini",
698
- });
699
- const geminiActive = formatResolvedPaths(geminiPaths);
700
- const geminiInstalledStatus = geminiActive.length > 0;
701
-
702
- // Gemini CLI (passive sessions scan)
703
- const geminiCliActive = formatResolvedPaths(geminiPaths, "tmp");
704
- const geminiCliInstalled = geminiCliActive.length > 0;
705
-
706
- // Antigravity (passive brains scan)
707
- const antigravityActive = [];
708
- if (geminiPaths.native) {
709
- const dirs = [
710
- path.join(geminiPaths.native, "antigravity", "brain"),
711
- path.join(geminiPaths.native, "antigravity-ide", "brain"),
712
- path.join(geminiPaths.native, "antigravity-cli", "brain"),
713
- ];
714
- if (dirs.some(d => { try { return fssync.existsSync(d); } catch (_) { return false; } })) {
715
- antigravityActive.push(`native: ${geminiPaths.native}`);
716
- }
717
- }
718
- if (geminiPaths.wsl) {
719
- const dirs = [
720
- path.join(geminiPaths.wsl, "antigravity", "brain"),
721
- path.join(geminiPaths.wsl, "antigravity-ide", "brain"),
722
- path.join(geminiPaths.wsl, "antigravity-cli", "brain"),
723
- ];
724
- if (dirs.some(d => { try { return fssync.existsSync(d); } catch (_) { return false; } })) {
725
- antigravityActive.push(`WSL: ${geminiPaths.wsl}`);
726
- }
727
- }
728
- const antigravityInstalled = antigravityActive.length > 0;
729
-
730
- // Codex CLI (passive sessions scan). Mirrors the sync resolution exactly
731
- // (union + requireAnyChild, see src/commands/sync.js): status is the tool
732
- // users are asked to paste when Codex usage looks wrong, so it must list
733
- // every root sync actually walks — and no empty shell sync would skip.
734
- const codexPaths = resolveInstallPaths({
735
- nativeValue: codexHome,
736
- wslDir: ".codex",
737
- requireAnyChild: ["sessions", "archived_sessions"],
738
- union: true,
739
- });
740
- // Both children, matching requireAnyChild above: an install holding only
741
- // archived_sessions/ is counted by sync and must not read as "not detected".
742
- const codexActive = formatResolvedPaths(codexPaths, ["sessions", "archived_sessions"]);
743
- for (const entry of scanRoots.codex) {
744
- if (entry.origin === "native" || !entry.exists) continue;
745
- if (!hasAnyScanChild(entry.path, ["sessions", "archived_sessions"])) continue;
746
- codexActive.push(`${describeScanRootOrigin(entry, "codex")}: ${entry.path}`);
747
- }
748
- const codexInstalledStatus = codexActive.length > 0;
749
-
750
- const acodePaths = resolveInstallPaths({
751
- nativeValue: acodeHome,
752
- wslDir: ".acode",
753
- requireAnyChild: ["sessions", "archived_sessions"],
754
- union: true,
755
- });
756
- const acodeActive = formatResolvedPaths(acodePaths, ["sessions", "archived_sessions"]);
757
- const acodeInstalled = acodeActive.length > 0;
758
-
759
- // Kimi (passive sessions scan)
760
- const kimiPaths = resolveInstallPaths({
761
- nativeValue: path.join(home, ".kimi"),
762
- wslDir: ".kimi",
763
- });
764
- const kimiActive = formatResolvedPaths(kimiPaths, "sessions");
765
-
766
- // Kilo Code VS Code extension — passive scan of all VS Code-family
767
- // globalStorage/kilocode.kilo-code/tasks/ ui_messages.json files.
768
- const kilocodeTaskFiles = resolveKilocodeTaskFiles(process.env);
769
- const kilocodeInstalled = kilocodeTaskFiles.length > 0;
770
-
771
- // Roo Code VS Code extension — same Cline-derived ui_messages.json format,
772
- // different globalStorage subdir (rooveterinaryinc.roo-cline).
773
- const roocodeTaskFiles = resolveRoocodeTaskFiles(process.env);
774
- const roocodeInstalled = roocodeTaskFiles.length > 0;
775
-
776
- // Cline CLI v3 / desktop app — passive scan of
777
- // <home>/data/sessions/*/<session>.messages.json (Cline's own data dir, not
778
- // the VS Code globalStorage the Roo/Kilo forks still use).
779
- const clineScan = resolveClineSessionFilesWithStatus(process.env);
780
- const clineSessionFiles = clineScan.files;
781
- const clineInstalled = clineSessionFiles.length > 0;
782
- const clineSessionsDirCount = new Set(
783
- clineSessionFiles.map((file) => path.dirname(path.dirname(file.filePath))),
784
- ).size;
785
- const clineDiscoveryError = clineScan.errors.length > 0
786
- ? clineScan.errors
787
- .map(({ root, error }) => `${root}: ${error.code ? `${error.code}: ` : ""}${error.message}`)
788
- .join("; ")
789
- : null;
790
-
791
- // Zed Agent — passive read of threads.db across all model providers
792
- // (hosted "zed.dev" and bring-your-own alike). threadTotals tracks one entry
793
- // per thread we've surfaced usage for, so its size distinguishes "DB present
794
- // with usage" from "DB present but nothing counted yet" (fresh/undecodable).
795
- const zedDbPath = resolveZedDbPath(process.env);
796
- const zedInstalled = Boolean(zedDbPath && fssync.existsSync(zedDbPath));
797
- const zedThreadsCounted =
798
- cursors?.zed?.threadTotals && typeof cursors.zed.threadTotals === "object"
799
- ? Object.keys(cursors.zed.threadTotals).length
800
- : 0;
801
-
802
- // Goose (Block) — passive cumulative-delta read of sessions.db.
803
- const gooseDbPath = resolveGooseDbPath(process.env);
804
- const gooseInstalled = Boolean(gooseDbPath && fssync.existsSync(gooseDbPath));
805
-
806
- // Droid (Factory CLI) — passive cumulative-delta read of *.settings.json.
807
- const droidSessionsDir = resolveDroidSessionsDir(process.env);
808
- const droidSettingsFiles = listDroidSettingsFiles(process.env);
809
- const droidInstalled = droidSettingsFiles.length > 0;
810
- const dshHomes = resolveDshHomes(process.env);
811
- const dshSessionsDir = dshHomes.map((homeDir) => path.join(homeDir, "sessions")).join(", ");
812
- const dshSessionFiles = await resolveDshSessionFiles(process.env);
813
- const dshInstalled = dshSessionFiles.length > 0;
814
- let commandCodeProjectsDir = "";
815
- let commandCodeSessionFiles = [];
816
- let commandCodeDiscoveryError = null;
817
- try {
818
- commandCodeProjectsDir = resolveCommandCodeHomes(process.env)
819
- .map((homeDir) => path.join(homeDir, "projects"))
820
- .join(", ");
821
- commandCodeSessionFiles = await resolveCommandCodeSessionFiles(process.env);
822
- } catch (error) {
823
- // Discovery stays strict for sync, but a provider read error must not
824
- // suppress the rest of the status diagnostics.
825
- commandCodeDiscoveryError = `${error?.code ? `${error.code}: ` : ""}${error?.message || String(error)}`;
826
- }
827
- const commandCodeInstalled = commandCodeSessionFiles.length > 0;
828
- const lmstudioHome = resolveLmstudioHome(process.env);
829
- const lmstudioLogFiles = await resolveLmstudioLogFiles(process.env);
830
- const lmstudioInstalled = lmstudioLogFiles.length > 0;
831
- const unslothDbPath = resolveUnslothDbPath(process.env);
832
- const unslothInstalled = Boolean(unslothDbPath && fssync.existsSync(unslothDbPath));
833
-
834
- // Devin CLI (Cognition) — passive reader of message_nodes usage metrics.
835
- const devinDbPath = resolveDevinDbPath(process.env);
836
- const devinInstalled = Boolean(devinDbPath && fssync.existsSync(devinDbPath));
837
-
838
- const { resolveTraeDbPaths } = require("../lib/trae-db");
839
- const traeDbPaths = resolveTraeDbPaths(process.env);
840
- const traeStoragePath = resolveTraeStoragePath(process.env);
841
- const traeInstalled = Boolean(traeStoragePath || traeDbPaths.length);
842
- // Render path for the entitlement snapshot: read it straight from the
843
- // Trae Local State storage.json via the shared parser. The queue stays
844
- // token-count-only, so the status read path never depends on queue rows
845
- // carrying plan/limits metadata.
846
- const traeEntitlement = traeInstalled
847
- ? readTraeEntitlementFromStorage(traeStoragePath)
848
- : null;
849
-
850
- // Trae SOLO CN — opt-in usage-API reader. Unlike the passive entitlement
851
- // reader above, this source sends the locally stored sign-in JWT to TRAE's
852
- // official API, so status surfaces the opt-in flag, the resolved storage
853
- // path, and whether the auth blob decrypts — the three inputs a "why is my
854
- // TRAE CN data missing" diagnosis needs.
855
- // A resolvable default path does NOT mean the app is installed - the
856
- // macOS/Windows resolver always derives one. Match the sync path semantics
857
- // exactly: installed iff the storage file actually exists on disk.
858
- const traeCnStoragePath = resolveTraeCnStoragePath({ env: process.env, home });
859
- const traeCnInstalled = Boolean(
860
- traeCnStoragePath && fssync.existsSync(traeCnStoragePath),
861
- );
862
- let traeCnAuthState = "not-signed-in";
863
- if (traeCnInstalled) {
864
- try {
865
- const traeCnAuth = readTraeCnAuthFromStorage({ env: process.env, home, platform: process.platform });
866
- if (traeCnAuth) {
867
- extractTraeCnToken(traeCnAuth);
868
- traeCnAuthState = "readable";
869
- }
870
- } catch (error) {
871
- // Distinguish a real IO failure (unreadable) from present-but-bad
872
- // data (malformed); neither ever carries storage contents.
873
- traeCnAuthState = error?.code === "TRAE_CN_STORAGE_UNREADABLE" ? "unreadable" : "malformed";
874
- }
875
- }
876
- const traeCnUsageOptIn = isTraeCnUsageEnabled(process.env);
877
-
878
- // Grok Build (xAI TUI)
879
- const grokHookState = await probeGrokHookState({ home, trackerDir, env: process.env });
880
- const grokSessions = grokHookState.hasGrokInstall || grokHookState.sessionsDir
881
- ? resolveGrokBuildSessions(process.env)
882
- : [];
883
- const grokInstalled = grokHookState.hasGrokInstall || grokSessions.length > 0;
884
-
885
- // Hermes Agent — SQLite state.db, resolved via override / native Windows
886
- // install / WSL auto-discovery. Surface the resolved path (UNC included) and,
887
- // on Windows, the discovered distros so WSL users can debug "why no sync"
888
- // without guessing the right UNC alias (#87).
889
- const hermesPaths = resolveInstallPaths({
890
- nativeValue: process.env.TOKENUSAGE_HERMES_HOME || (process.platform === "win32" && typeof process.env.LOCALAPPDATA === "string"
891
- ? path.join(process.env.LOCALAPPDATA.trim(), "hermes")
892
- : path.join(home, ".hermes")),
893
- wslDir: ".hermes",
894
- });
895
- const hermesActive = formatResolvedPaths(hermesPaths, "state.db");
896
- const hermesInstalled = hermesActive.length > 0;
897
- const hermesPath = hermesActive.join(" | ");
898
- const wslDistros = process.platform === "win32" && shouldProbeWsl(process.env) ? probeWslDistros() : [];
899
-
900
- const copilotToken = readCopilotOauthToken({ home });
901
- const copilotOtel = describeCopilotOtelStatus({ home, env: process.env });
902
- const copilotAppDbPaths = resolveCopilotAppDbPaths(process.env);
903
- const copilotAppExistingPaths = copilotAppDbPaths.filter((p) => {
904
- try { return fssync.existsSync(p); } catch (_e) { return false; }
905
- });
906
- const copilotStorePaths = Array.from(
907
- new Set([
908
- ...resolveCopilotSessionStorePaths(process.env),
909
- ...Object.keys(cursors?.copilotStore?.dbs || {}),
910
- ]),
911
- );
912
- const copilotStoreExistingPaths = copilotStorePaths.filter((p) => {
913
- try { return fssync.existsSync(p); } catch (_e) { return false; }
914
- });
915
- const copilotStoreDetails = [];
916
- const copilotStoreInspectionErrors = [];
917
- for (const storePath of copilotStoreExistingPaths) {
918
- try {
919
- copilotStoreDetails.push(describeCopilotSessionStoreDb(storePath));
920
- } catch (err) {
921
- copilotStoreInspectionErrors.push(
922
- `${storePath}: ${err && err.message ? err.message : String(err)}`,
923
- );
924
- }
925
- }
926
- const copilotStoreCursor =
927
- cursors?.copilotStore && typeof cursors.copilotStore === "object"
928
- ? cursors.copilotStore
929
- : {};
930
- const copilotStoreDbStates =
931
- copilotStoreCursor.dbs && typeof copilotStoreCursor.dbs === "object"
932
- ? copilotStoreCursor.dbs
933
- : {};
934
- const copilotStatusPathKey = (dbPath) => {
935
- const normalized = path.normalize(dbPath);
936
- return process.platform === "win32" ? normalized.toLowerCase() : normalized;
937
- };
938
- const existingCopilotStoreKeys = new Set(
939
- copilotStoreExistingPaths.map(copilotStatusPathKey),
940
- );
941
- const adoptedCopilotStores = Object.entries(copilotStoreDbStates).filter(
942
- ([, state]) => state?.adoptedAt,
943
- );
944
- const missingAdoptedCopilotStores = adoptedCopilotStores
945
- .map(([dbPath]) => dbPath)
946
- .filter((dbPath) => !existingCopilotStoreKeys.has(copilotStatusPathKey(dbPath)));
947
- const copilotStoreDegradedReasons = [
948
- ...missingAdoptedCopilotStores.map(
949
- (dbPath) => `canonical store unavailable: ${dbPath}`,
950
- ),
951
- ...copilotStoreInspectionErrors.map(
952
- (message) => `store inspection failed: ${message}`,
953
- ),
954
- ...Object.entries(copilotStoreDbStates)
955
- .filter(([, state]) => state?.lastError)
956
- .map(([dbPath, state]) => `${dbPath}: ${state.lastError}`),
957
- ];
958
- const malformedCopilotEvents = Object.values(copilotStoreDbStates).reduce(
959
- (sum, state) => sum + Math.max(0, Number(state?.malformedEventCount) || 0),
960
- 0,
961
- );
962
- if (malformedCopilotEvents > 0) {
963
- copilotStoreDegradedReasons.push(
964
- `${malformedCopilotEvents} event${malformedCopilotEvents === 1 ? "" : "s"} lack a valid timestamp`,
965
- );
966
- }
967
- const copilotResetGapEvents = Object.values(copilotStoreDbStates).reduce(
968
- (sum, state) => sum + Math.max(0, Number(state?.resetGapEventCount) || 0),
969
- 0,
970
- );
971
- if (copilotResetGapEvents > 0) {
972
- copilotStoreDegradedReasons.push(
973
- `${copilotResetGapEvents} event${copilotResetGapEvents === 1 ? "" : "s"} were baselined during a legacy cursor/reset race`,
974
- );
975
- }
976
- const copilotStoreCanonical =
977
- copilotStoreCursor.active === true && adoptedCopilotStores.length > 0;
978
- const copilotStoreDegraded = copilotStoreDegradedReasons.length > 0;
979
- const copilotStoreStatus = {
980
- store_paths: copilotStoreExistingPaths,
981
- store_path: copilotStorePaths[0] || null,
982
- store_has_file: copilotStoreExistingPaths.length > 0,
983
- store_details: copilotStoreDetails.map((detail) => ({
984
- path: detail.path,
985
- schema_version: detail.schemaVersion,
986
- event_count: detail.eventCount,
987
- last_event_id: detail.lastEventId,
988
- last_event_at: detail.lastEventAt,
989
- })),
990
- canonical: copilotStoreCanonical,
991
- source_mode: copilotStoreCanonical
992
- ? copilotStoreDegraded
993
- ? "canonical-degraded"
994
- : "canonical"
995
- : copilotStoreExistingPaths.length > 0
996
- ? "awaiting-adoption"
997
- : "legacy",
998
- precision: copilotStoreCanonical
999
- ? "exact-post-adoption; aggregate-pre-adoption"
1000
- : "aggregate",
1001
- coverage: copilotStoreCanonical
1002
- ? "per-request-post-adoption; legacy-aggregate-pre-adoption"
1003
- : "legacy-aggregate",
1004
- malformed_event_count: malformedCopilotEvents,
1005
- reset_gap_event_count: copilotResetGapEvents,
1006
- degraded: copilotStoreDegraded,
1007
- degraded_reasons: copilotStoreDegradedReasons,
1008
- recommended_action: copilotStoreDegraded
1009
- ? "Restore or repair the Copilot session store, then run `tokenusage sync`."
1010
- : null,
1011
- };
1012
- const copilotAppStatus = {
1013
- app_db_path: resolveCopilotAppDbPath(process.env),
1014
- app_db_paths: copilotAppExistingPaths,
1015
- app_db_has_file: copilotAppExistingPaths.length > 0,
1016
- app_db_mode: copilotStoreCanonical ? "observe-only" : "legacy-writer",
1017
- };
1018
- const copilotLines = formatCopilotLines({
1019
- token: copilotToken,
1020
- otel: copilotOtel,
1021
- sessionStore: copilotStoreStatus,
1022
- appDb: copilotAppStatus,
1023
- });
1024
-
1025
- // Detect passive-mode providers exactly once — both the JSON/light path
1026
- // and the human-readable path consume this, and each call hits 5 readdir
1027
- // syscalls (~5–10ms cold). Memoize.
1028
- const passiveProviders = detectPassiveProviders({
1029
- home,
1030
- env: process.env,
1031
- hookStatus: {
1032
- codex_notify: notifyConfigured,
1033
- acode_notify: acodeConfigured,
1034
- every_code_notify: everyCodeConfigured,
1035
- claude: claudeHookConfigured,
1036
- gemini: geminiHookConfigured,
1037
- opencode_plugin: opencodePluginConfigured,
1038
- openclaw_session_plugin: Boolean(openclawSessionPluginState?.configured),
1039
- codebuddy: Boolean(codebuddyHookConfigured),
1040
- workbuddy: Boolean(workbuddyHookConfigured),
1041
- "workbuddy-ai": Boolean(workbuddyAiHookConfigured),
1042
- grok: Boolean(grokHookState?.configured),
1043
- },
1044
- });
1045
-
1046
- const deviceTokenPresence = resolveDeviceTokenPresence({
1047
- trackerDir,
1048
- config: config || {},
1049
- });
1050
-
1051
- if (opts.json || opts.light) {
1052
- const summary = {
1053
- version: pkg.version,
1054
- generated_at: new Date().toISOString(),
1055
- base_url: config?.baseUrl || null,
1056
- device_token_set: deviceTokenPresence.set,
1057
- queue: {
1058
- pending_bytes: pendingBytes,
1059
- size_bytes: queueSize,
1060
- offset: queueState.offset || 0,
1061
- },
1062
- last_parse: cursors?.updatedAt || null,
1063
- last_notify: lastNotify || null,
1064
- last_openclaw_sync: lastOpenclawSync || null,
1065
- last_notify_spawn: lastNotifySpawn || null,
1066
- last_upload: lastUpload || null,
1067
- next_upload_after: nextUpload || null,
1068
- backoff_until: backoffUntil || null,
1069
- last_upload_error: lastUploadError || null,
1070
- last_sync_skipped: syncSkip?.at ? syncSkip : null,
1071
- auto_retry: autoRetry || null,
1072
- // Extra scan roots (#657): CODEX_HOME / CLAUDE_CONFIG_DIR of this process
1073
- // plus config.scanRoots; `exists` false + `error` null means absent,
1074
- // `error` set means present but unreadable.
1075
- extra_scan_roots: extraScanRoots,
1076
- hooks: {
1077
- codex_notify: notifyConfigured,
1078
- acode_notify: acodeConfigured,
1079
- every_code_notify: everyCodeConfigured,
1080
- claude: claudeHookConfigured,
1081
- gemini: geminiHookConfigured,
1082
- opencode_plugin: opencodePluginConfigured,
1083
- openclaw_session_plugin: Boolean(openclawSessionPluginState?.configured),
1084
- openclaw_session_plugin_conversation_access: Boolean(
1085
- openclawSessionPluginState?.conversationAccess,
1086
- ),
1087
- openclaw_legacy: Boolean(openclawHookState?.configured),
1088
- codebuddy: codebuddyInstalled ? Boolean(codebuddyHookConfigured) : null,
1089
- workbuddy: workbuddyInstalled ? Boolean(workbuddyHookConfigured) : null,
1090
- "workbuddy-ai": workbuddyAiInstalled ? Boolean(workbuddyAiHookConfigured) : null,
1091
- grok: grokInstalled ? Boolean(grokHookState?.configured) : null,
1092
- },
1093
- providers: {
1094
- acode: acodeInstalled
1095
- ? { installed: true, detail: acodeActive.join(" | ") }
1096
- : { installed: false },
1097
- kimi_code: kimiInstalled || kimiCodeInstalled
1098
- ? { installed: true, files: kimiWireFiles.length + kimiCodeWireFiles.length }
1099
- : { installed: false },
1100
- kiro_cli: kiroCliInstalled
1101
- ? {
1102
- installed: true,
1103
- detail: kiroCliActive.join(" | "),
1104
- database: kiroCliMarkers.find((m) => {
1105
- try { return fssync.existsSync(m); } catch (_e) { return false; }
1106
- }) || null,
1107
- files: kiroCliFileCount,
1108
- }
1109
- : { installed: false },
1110
- kiro_ide: kiroIdeInstalled
1111
- ? { installed: true, detail: kiroIdeActive.join(" | ") }
1112
- : { installed: false },
1113
- claude_code: claudeCodeInstalled
1114
- ? { installed: true, detail: claudeCodeActive.join(" | ") }
1115
- : { installed: false },
1116
- codebuddy: codebuddyInstalled
1117
- ? { installed: true, files: codebuddyFiles.length }
1118
- : { installed: false },
1119
- workbuddy: workbuddyInstalled
1120
- ? { installed: true, files: workbuddyFiles.length }
1121
- : { installed: false },
1122
- workbuddy_ai: workbuddyAiInstalled
1123
- ? { installed: true, files: workbuddyAiFiles.length }
1124
- : { installed: false },
1125
- omp: ompInstalled || ompHookState.ompPresent
1126
- ? {
1127
- installed: true,
1128
- files: ompFiles.length,
1129
- notify_extension: Boolean(ompHookState.configured),
1130
- notify_extension_path: ompHookState.extensionPath || null,
1131
- }
1132
- : { installed: false },
1133
- omo: omoInstalled
1134
- ? { installed: true, files: omoFiles.length }
1135
- : { installed: false },
1136
- minimax_code: minimaxCodeInstalled
1137
- ? { installed: true, files: minimaxCodeFiles.length }
1138
- : { installed: false },
1139
- pi: piInstalled
1140
- ? { installed: true, files: piFiles.length }
1141
- : { installed: false },
1142
- prime_agent: primeAgentInstalled
1143
- ? { installed: true, files: primeAgentFiles.length }
1144
- : { installed: false },
1145
- craft: craftInstalled
1146
- ? { installed: true, files: craftFiles.length }
1147
- : { installed: false },
1148
- reasonix: reasonixInstalled
1149
- ? { installed: true, files: reasonixFiles.length }
1150
- : { installed: false },
1151
- muse: museInstalled
1152
- ? { installed: true, files: museFiles.length }
1153
- : { installed: false },
1154
- anythingllm: anythingllmInstalled
1155
- ? { installed: true, detail: anythingllmDbPath }
1156
- : { installed: false },
1157
- kilo_cli: kiloInstalled
1158
- ? { installed: true, detail: kiloDbPath }
1159
- : { installed: false },
1160
- dumate: dumateInstalled
1161
- ? { installed: true, detail: dumateDbPath }
1162
- : { installed: false },
1163
- mimo: mimoInstalled
1164
- ? { installed: true, detail: mimoDbPath }
1165
- : { installed: false },
1166
- zcode: zcodeInstalled
1167
- ? { installed: true, detail: zcodeDbPath }
1168
- : { installed: false },
1169
- qoder: qoderInstalled
1170
- ? { installed: true, detail: summarizeQoderDetail(qoderDbPath, qoderNewPath) }
1171
- : { installed: false },
1172
- "qoder-cn": qoderCnInstalled
1173
- ? { installed: true, detail: summarizeQoderDetail(qoderCnDbPath, qoderCnNewPath) }
1174
- : { installed: false },
1175
- "claude-science": claudeScienceInstalled
1176
- ? { installed: true, detail: claudeScienceDbPath }
1177
- : { installed: false },
1178
- kilocode: kilocodeInstalled
1179
- ? { installed: true, files: kilocodeTaskFiles.length }
1180
- : { installed: false },
1181
- roocode: roocodeInstalled
1182
- ? { installed: true, files: roocodeTaskFiles.length }
1183
- : { installed: false },
1184
- cline: clineInstalled
1185
- ? {
1186
- installed: true,
1187
- files: clineSessionFiles.length,
1188
- ...(clineDiscoveryError ? { error: clineDiscoveryError } : {}),
1189
- }
1190
- : clineDiscoveryError
1191
- ? { installed: false, error: clineDiscoveryError }
1192
- : { installed: false },
1193
- zed: zedInstalled ? { installed: true, detail: zedDbPath } : { installed: false },
1194
- goose: gooseInstalled
1195
- ? { installed: true, detail: gooseDbPath }
1196
- : { installed: false },
1197
- droid: droidInstalled
1198
- ? { installed: true, files: droidSettingsFiles.length, detail: droidSessionsDir }
1199
- : { installed: false },
1200
- dsh: dshInstalled
1201
- ? { installed: true, files: dshSessionFiles.length, detail: dshSessionsDir }
1202
- : { installed: false },
1203
- "command-code": commandCodeInstalled
1204
- ? {
1205
- installed: true,
1206
- files: commandCodeSessionFiles.length,
1207
- detail: commandCodeProjectsDir,
1208
- }
1209
- : commandCodeDiscoveryError
1210
- ? { installed: false, error: commandCodeDiscoveryError }
1211
- : { installed: false },
1212
- lmstudio: lmstudioInstalled
1213
- ? {
1214
- installed: true,
1215
- files: lmstudioLogFiles.length,
1216
- detail: path.join(lmstudioHome, "server-logs"),
1217
- }
1218
- : { installed: false },
1219
- unsloth: unslothInstalled
1220
- ? { installed: true, detail: unslothDbPath }
1221
- : { installed: false },
1222
- devin: devinInstalled
1223
- ? { installed: true, detail: devinDbPath }
1224
- : { installed: false },
1225
- trae: traeInstalled
1226
- ? {
1227
- installed: true,
1228
- detail: traeDbPaths[0] || traeStoragePath,
1229
- usage_databases: traeDbPaths.length,
1230
- usage_key_source: process.env.TOKENUSAGE_TRAE_SQLCIPHER_KEY?.trim() ? "environment" : "application",
1231
- ...(traeEntitlement ? { entitlement: traeEntitlement } : {}),
1232
- }
1233
- : { installed: false },
1234
- "trae-cn": traeCnInstalled
1235
- ? {
1236
- installed: true,
1237
- detail: traeCnStoragePath,
1238
- auth: traeCnAuthState,
1239
- usage_opt_in: traeCnUsageOptIn,
1240
- }
1241
- : { installed: false },
1242
- grok_build: grokInstalled
1243
- ? {
1244
- installed: true,
1245
- files: grokSessions.length,
1246
- detail: grokHookState.configured ? "hook installed" : "detected",
1247
- }
1248
- : { installed: false },
1249
- hermes: {
1250
- installed: hermesInstalled,
1251
- detail: hermesPath,
1252
- },
1253
- },
1254
- copilot: {
1255
- token_set: Boolean(copilotToken),
1256
- otel_has_files: Boolean(copilotOtel.otel_has_files),
1257
- otel_path: copilotOtel.otel_path || null,
1258
- otel_enabled: Boolean(copilotOtel.otel_enabled),
1259
- ...copilotStoreStatus,
1260
- ...copilotAppStatus,
1261
- },
1262
- passive_mode: {
1263
- active: isPassiveModeActive(passiveProviders),
1264
- providers: passiveProviders,
1265
- },
1266
- ...(process.platform === "win32"
1267
- ? {
1268
- wsl_mode: getWslMode(),
1269
- wsl_mode_invalid: isInvalidWslMode(),
1270
- wsl_distros: wslDistros.map((d) => ({ name: d.name, version: d.version })),
1271
- }
1272
- : {}),
1273
- subscriptions,
1274
- };
1275
-
1276
- if (opts.json) {
1277
- process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
1278
- return;
1279
- }
1280
- process.stdout.write(renderLightTable(summary) + "\n");
1281
- return;
1282
- }
1283
-
1284
- process.stdout.write(
1285
- [
1286
- `tokenusage v${pkg.version}`,
1287
- "Status:",
1288
- `- Base URL: ${config?.baseUrl || "unset"}`,
1289
- `- Device token: ${deviceTokenPresence.set ? "set" : "unset"}`,
1290
- `- Queue: ${pendingBytes} bytes pending`,
1291
- `- Last parse: ${cursors?.updatedAt || "never"}`,
1292
- `- Last notify: ${lastNotify || "never"}`,
1293
- `- Last OpenClaw-triggered sync: ${lastOpenclawSync || "never"}`,
1294
- `- Last notify-triggered sync: ${lastNotifySpawn || "never"}`,
1295
- `- Last upload: ${lastUpload || "never"}`,
1296
- `- Next upload after: ${nextUpload || "never"}`,
1297
- `- Backoff until: ${backoffUntil || "never"}`,
1298
- lastUploadError ? `- Last upload error: ${lastUploadError}` : null,
1299
- syncSkipLine,
1300
- autoRetryLine,
1301
- scanRootsLine,
1302
- `- Codex notify: ${notifyConfigured ? JSON.stringify(codexNotify) : "unset"}`,
1303
- `- AStudio notify: ${acodeConfigured ? JSON.stringify(acodeNotify) : "unset"}`,
1304
- `- Every Code notify: ${everyCodeConfigured ? JSON.stringify(everyCodeNotify) : "unset"}`,
1305
- `- Claude hooks: ${claudeHookConfigured ? "set" : "unset"}`,
1306
- claudeCodeInstalled
1307
- ? `- Claude Code: projects found (${claudeCodeActive.join(" | ")})`
1308
- : null,
1309
- `- Gemini hooks: ${geminiHookConfigured ? "set" : "unset"}`,
1310
- `- Opencode plugin: ${opencodePluginConfigured ? "set" : "unset"}`,
1311
- `- OpenClaw session plugin: ${openclawSessionPluginState?.configured ? "set" : "unset"}`,
1312
- `- OpenClaw session plugin conversation access: ${openclawSessionPluginState?.conversationAccess ? "set" : "unset"}`,
1313
- `- OpenClaw hook (legacy): ${openclawHookState?.configured ? "set" : "unset"}`,
1314
- kimiInstalled || kimiCodeInstalled
1315
- ? `- Kimi Code: passive reader (${kimiWireFiles.length + kimiCodeWireFiles.length} wire.jsonl file${(kimiWireFiles.length + kimiCodeWireFiles.length) !== 1 ? "s" : ""} found, directories: ${kimiActive.join(" | ") || "none"})`
1316
- : null,
1317
- kiroCliInstalled
1318
- ? `- Kiro CLI: passive reader (${kiroCliFileCount} session file${kiroCliFileCount !== 1 ? "s" : ""} found, SQLite ${kiroCliDbFound ? "found" : "not found"}, installs: ${kiroCliActive.join(" | ")}; missing token counts use new-text estimates at ~4 chars/token, excluding re-sent history, system context and cache usage; model-rate costs are separate from Kiro credit charges; merged under 'kiro')`
1319
- : null,
1320
- kiroIdeInstalled
1321
- ? `- Kiro IDE: passive reader (${kiroIdeActive.join(" | ")})`
1322
- : null,
1323
- codebuddyInstalled
1324
- ? `- CodeBuddy hooks: ${codebuddyHookConfigured ? "set" : "unset"} (${codebuddyFiles.length} usage file${codebuddyFiles.length !== 1 ? "s" : ""} found)`
1325
- : null,
1326
- workbuddyInstalled
1327
- ? `- WorkBuddy hooks: ${workbuddyHookConfigured ? "set" : "unset"} (${workbuddyFiles.length} session jsonl file${workbuddyFiles.length !== 1 ? "s" : ""} found, SQLite DB ${workbuddyDbExists ? "found" : "not found"})`
1328
- : null,
1329
- workbuddyAiInstalled
1330
- ? `- WorkBuddy AI hooks: ${workbuddyAiHookConfigured ? "set" : "unset"} (${workbuddyAiFiles.length} session jsonl file${workbuddyAiFiles.length !== 1 ? "s" : ""} found, SQLite DB ${workbuddyAiDbExists ? "found" : "not found"})`
1331
- : null,
1332
- ompInstalled || ompHookState.ompPresent
1333
- ? `- oh-my-pi: passive reader (${ompFiles.length} session jsonl file${ompFiles.length !== 1 ? "s" : ""} found${ompHookState.configured ? ", notify extension: yes" : ", notify extension: no"})`
1334
- : null,
1335
- omoInstalled
1336
- ? `- OmO: passive reader (${omoFiles.length} session jsonl file${omoFiles.length !== 1 ? "s" : ""} found)`
1337
- : null,
1338
- minimaxCodeInstalled
1339
- ? `- MiniMax Code: passive reader (${minimaxCodeFiles.length} session jsonl file${minimaxCodeFiles.length !== 1 ? "s" : ""} found)`
1340
- : null,
1341
- piInstalled
1342
- ? `- pi: passive reader (${piFiles.length} session jsonl file${piFiles.length !== 1 ? "s" : ""} found)`
1343
- : null,
1344
- primeAgentInstalled
1345
- ? `- Prime Agent: passive reader (${primeAgentFiles.length} session jsonl file${primeAgentFiles.length !== 1 ? "s" : ""} found)`
1346
- : null,
1347
- craftInstalled
1348
- ? `- Craft Agents: passive reader (${craftFiles.length} session jsonl file${craftFiles.length !== 1 ? "s" : ""} found)`
1349
- : null,
1350
- reasonixInstalled
1351
- ? `- Reasonix: passive reader (${reasonixFiles.length} telemetry file${reasonixFiles.length !== 1 ? "s" : ""} found)`
1352
- : null,
1353
- museInstalled
1354
- ? `- Muse Code: passive reader (${museFiles.length} session jsonl file${museFiles.length !== 1 ? "s" : ""} found)`
1355
- : null,
1356
- anythingllmInstalled
1357
- ? `- AnythingLLM Desktop: passive reader (${anythingllmDbPath})`
1358
- : null,
1359
- kiloInstalled
1360
- ? `- Kilo CLI: passive reader (${kiloDbPath})`
1361
- : null,
1362
- dumateInstalled
1363
- ? `- DuMate: passive reader (${dumateDbPath})`
1364
- : null,
1365
- mimoInstalled
1366
- ? `- Mimo: passive reader (${mimoDbPath})`
1367
- : null,
1368
- zcodeInstalled
1369
- ? `- ZCode: passive reader (${zcodeDbPath})`
1370
- : null,
1371
- qoderInstalled
1372
- ? `- Qoder: passive reader (${[qoderDbPath, qoderNewPath].filter(Boolean).join(" + ") || "not found"}${qoderNewInstalled && qoderActive.length > 0 ? " [legacy DB + new JSONL (both tracked)]" : ""}${qoderNewInstalled && qoderActive.length === 0 ? " [new JSONL only]" : ""})`
1373
- : null,
1374
- qoderCnInstalled
1375
- ? `- Qoder CN: passive reader (${summarizeQoderDetail(qoderCnDbPath, qoderCnNewPath) || "not found"}${qoderCnNewInstalled && qoderCnActive.length > 0 ? " [legacy DB + new JSONL (both tracked)]" : ""}${qoderCnNewInstalled && qoderCnActive.length === 0 ? " [new JSONL only]" : ""})`
1376
- : null,
1377
- claudeScienceInstalled
1378
- ? `- Claude Science: passive reader (${claudeScienceDbPath})`
1379
- : null,
1380
- opencodeInstalled
1381
- ? `- OpenCode: passive reader (storage: ${opencodeStorageActive.join(" | ") || "not found"}, DB: ${opencodeDbActive.join(" | ") || "not found"})`
1382
- : null,
1383
- codeInstalled
1384
- ? `- Every Code: sessions found (${codeActive.join(" | ")})`
1385
- : null,
1386
- geminiCliInstalled
1387
- ? `- Gemini CLI: sessions found (${geminiCliActive.join(" | ")})`
1388
- : null,
1389
- antigravityInstalled
1390
- ? `- Antigravity: brain found (${antigravityActive.join(" | ")})`
1391
- : null,
1392
- (!geminiCliInstalled && !antigravityInstalled && geminiInstalledStatus)
1393
- ? `- Gemini CLI / Antigravity: home found (${geminiActive.join(" | ")})`
1394
- : null,
1395
- codexInstalledStatus
1396
- ? `- Codex CLI: sessions found (${codexActive.join(" | ")})`
1397
- : null,
1398
- codexRecordOnlyWarning ? `- ⚠ ${codexRecordOnlyWarning}` : null,
1399
- acodeInstalled
1400
- ? `- AStudio: sessions found (${acodeActive.join(" | ")})`
1401
- : null,
1402
- kilocodeInstalled
1403
- ? `- Kilo Code (VS Code extension): passive reader (${kilocodeTaskFiles.length} task${kilocodeTaskFiles.length !== 1 ? "s" : ""} across ${new Set(kilocodeTaskFiles.map((t) => t.ide)).size} IDE${new Set(kilocodeTaskFiles.map((t) => t.ide)).size !== 1 ? "s" : ""})`
1404
- : null,
1405
- roocodeInstalled
1406
- ? `- Roo Code (VS Code extension): passive reader (${roocodeTaskFiles.length} task${roocodeTaskFiles.length !== 1 ? "s" : ""} across ${new Set(roocodeTaskFiles.map((t) => t.ide)).size} IDE${new Set(roocodeTaskFiles.map((t) => t.ide)).size !== 1 ? "s" : ""})`
1407
- : null,
1408
- clineInstalled
1409
- ? `- Cline: passive reader (${clineSessionFiles.length} transcript${clineSessionFiles.length !== 1 ? "s" : ""} in ${clineSessionsDirCount} sessions dir${clineSessionsDirCount !== 1 ? "s" : ""})${clineDiscoveryError ? `; discovery failed (${clineDiscoveryError})` : ""}`
1410
- : clineDiscoveryError
1411
- ? `- Cline: discovery failed (${clineDiscoveryError})`
1412
- : null,
1413
- zedInstalled
1414
- ? `- Zed Agent: passive reader (threads.db, all providers${
1415
- zedThreadsCounted > 0
1416
- ? `, ${zedThreadsCounted} thread${zedThreadsCounted !== 1 ? "s" : ""} counted`
1417
- : ", no usage counted yet"
1418
- })`
1419
- : null,
1420
- gooseInstalled
1421
- ? `- Goose (Block): passive reader (sessions.db, cumulative-delta)`
1422
- : null,
1423
- droidInstalled
1424
- ? `- Droid (Factory): passive reader (${droidSettingsFiles.length} session${droidSettingsFiles.length !== 1 ? "s" : ""} in ${droidSessionsDir}, cumulative-delta)`
1425
- : null,
1426
- dshInstalled
1427
- ? `- DeepSeek Harness: passive reader (${dshSessionFiles.length} session${dshSessionFiles.length !== 1 ? "s" : ""} in ${dshSessionsDir})`
1428
- : null,
1429
- commandCodeInstalled
1430
- ? `- Command Code: passive reader (${commandCodeSessionFiles.length} session${commandCodeSessionFiles.length !== 1 ? "s" : ""} in ${commandCodeProjectsDir})`
1431
- : commandCodeDiscoveryError
1432
- ? `- Command Code: discovery failed (${commandCodeDiscoveryError})`
1433
- : null,
1434
- lmstudioInstalled
1435
- ? `- LM Studio: passive reader (${lmstudioLogFiles.length} log${lmstudioLogFiles.length !== 1 ? "s" : ""} in ${path.join(lmstudioHome, "server-logs")})`
1436
- : null,
1437
- unslothInstalled
1438
- ? `- Unsloth Studio: passive reader (${unslothDbPath})`
1439
- : null,
1440
- devinInstalled
1441
- ? `- Devin CLI: passive reader (${devinDbPath})`
1442
- : null,
1443
- traeInstalled
1444
- ? traeDbPaths.length
1445
- ? `- TRAE: local usage reader, ${traeDbPaths.length} database(s) (shared application key; optional key override)`
1446
- : `- TRAE: plan info only, no local usage database found (${traeStoragePath})`
1447
- : null,
1448
- traeEntitlement
1449
- ? `- Trae SOLO plan: ${formatTraeEntitlementLine(traeEntitlement)}`
1450
- : null,
1451
- traeCnInstalled
1452
- // Installed, signed in, and one env var away from usage data is the
1453
- // one actionable state on this line — mark it so it does not read
1454
- // like the ~30 neutral install lines around it (#492). Every other
1455
- // combination (opted in, or no readable auth to send) is neutral.
1456
- ? `- ${traeCnAuthState === "readable" && !traeCnUsageOptIn ? "⚠ " : ""}Trae SOLO CN: usage sync ${traeCnUsageOptIn ? "opted in" : `off (set ${TRAE_CN_USAGE_ENV}=1 to enable)`}, auth ${traeCnAuthState} (${traeCnStoragePath})`
1457
- : null,
1458
- ...(() => {
1459
- if (!hermesInstalled) return [];
1460
- return [`- Hermes Agent: state.db found (${hermesPath})`];
1461
- })(),
1462
- ...(() => {
1463
- const passive = passiveProviders.filter((p) => p.passive);
1464
- if (passive.length === 0) return [];
1465
- return [
1466
- `- Passive mode: ${passive.length} provider${passive.length !== 1 ? "s" : ""} reading logs without hooks (${passive.map((p) => `${p.name}: ${p.hook_failure_reason || "hook unset"}`).join("; ")})`,
1467
- ];
1468
- })(),
1469
- grokInstalled
1470
- ? `- Grok Build (xAI): ${grokHookState.configured ? "hook installed" : "detected"} (${grokSessions.length} session${grokSessions.length !== 1 ? "s" : ""} found, hook: ${grokHookState.configured ? "yes" : "no"})`
1471
- : null,
1472
- ...copilotLines,
1473
- ...(process.platform === "win32" ? (() => {
1474
- const wslMode = getWslMode();
1475
- const modeInvalid = isInvalidWslMode();
1476
- const modeSuffix = modeInvalid ? ` (invalid TOKENUSAGE_WSL_MODE ignored)` : "";
1477
- const lines = [
1478
- `- WSL mode: ${wslMode}${modeSuffix}`,
1479
- ];
1480
- if (wslDistros.length > 0) {
1481
- lines.push(` distros: ${wslDistros.map((d) => `${d.name} (v${d.version ?? "?"})`).join(", ")}`);
1482
- }
1483
- return lines;
1484
- })() : []),
1485
- ...subscriptionLines,
1486
- "",
1487
- ]
1488
- .filter(Boolean)
1489
- .join("\n"),
1490
- );
1491
- }
1492
-
1493
- function formatCopilotStoreDetail(detail) {
1494
- return `${detail.path} (schema ${detail.schema_version ?? "?"}, ${detail.event_count ?? 0} events, last id ${detail.last_event_id ?? 0}${detail.last_event_at ? ` at ${detail.last_event_at}` : ""})`;
1495
- }
1496
-
1497
- function formatCopilotLines({ token, otel, sessionStore, appDb }) {
1498
- if (
1499
- !token &&
1500
- !otel.otel_has_files &&
1501
- !sessionStore?.store_has_file &&
1502
- !appDb?.app_db_has_file
1503
- ) {
1504
- return [];
1505
- }
1506
- const limitsState = token
1507
- ? "set (via GitHub OAuth)"
1508
- : "unset (no Copilot OAuth token found)";
1509
- const storeDetail = (sessionStore?.store_details || [])
1510
- .map(formatCopilotStoreDetail)
1511
- .join(", ");
1512
- const storeState = sessionStore?.store_has_file
1513
- ? `${sessionStore.source_mode || "set"} (${storeDetail || (sessionStore.store_paths || []).join(", ")}; precision ${sessionStore.precision || "unknown"}; coverage ${sessionStore.coverage || "unknown"})`
1514
- : `not found (${sessionStore?.store_path || "unknown"})`;
1515
- const appDbState = appDb?.app_db_has_file
1516
- ? `${appDb.app_db_mode || "set"} (${(appDb.app_db_paths || []).join(", ")})`
1517
- : `not found (${appDb?.app_db_path || "unknown"})`;
1518
- const otelLocation =
1519
- otel.otel_path || otel.otel_detected_paths?.[0] || otel.otel_default_dir;
1520
- const usageState = otel.otel_has_files
1521
- ? `set (${otelLocation})`
1522
- : otel.otel_enabled
1523
- ? "enabled but no files yet"
1524
- : "unset (OTEL export not enabled)";
1525
- const lines = [
1526
- `- GitHub Copilot limits: ${limitsState}`,
1527
- `- GitHub Copilot usage (App/CLI store): ${storeState}`,
1528
- `- GitHub Copilot usage (App DB legacy baseline): ${appDbState}`,
1529
- `- GitHub Copilot usage (OTEL Chat/legacy CLI): ${usageState}`,
1530
- ];
1531
- for (const reason of sessionStore?.degraded_reasons || []) {
1532
- lines.push(` Degraded: ${reason}`);
1533
- }
1534
- if (sessionStore?.recommended_action) {
1535
- lines.push(` Action: ${sessionStore.recommended_action}`);
1536
- }
1537
- if (!sessionStore?.store_has_file && !otel.otel_has_files) {
1538
- lines.push(
1539
- " To track older Copilot CLI / Chat extension token usage, add to your shell profile:",
1540
- " export COPILOT_OTEL_ENABLED=true",
1541
- " export COPILOT_OTEL_EXPORTER_TYPE=file",
1542
- ` export COPILOT_OTEL_FILE_EXPORTER_PATH="${otel.otel_default_dir}/copilot-otel-$(date +%Y%m%d).jsonl"`,
1543
- );
1544
- }
1545
- return lines;
1546
- }
1547
-
1548
- function formatSubscriptionLine(entry = {}) {
1549
- const tool = String(entry.tool || "");
1550
- const provider = String(entry.provider || "");
1551
- const product = String(entry.product || "");
1552
- const planType = String(entry.planType || "");
1553
- const rateLimitTier = String(entry.rateLimitTier || "");
1554
- const toolLabel =
1555
- tool === "codex"
1556
- ? "Codex"
1557
- : tool === "opencode"
1558
- ? "OpenCode"
1559
- : tool === "claude"
1560
- ? "Claude Code"
1561
- : tool;
1562
-
1563
- if (!planType) return null;
1564
-
1565
- if (
1566
- tool === "claude" &&
1567
- provider === "anthropic" &&
1568
- product === "subscription"
1569
- ) {
1570
- const suffix = rateLimitTier ? ` (rate limit tier: ${rateLimitTier})` : "";
1571
- return `- ${toolLabel} subscription: ${planType}${suffix}`;
1572
- }
1573
-
1574
- if (provider === "openai" && product === "chatgpt") {
1575
- return `- ${toolLabel} ChatGPT plan: ${planType}`;
1576
- }
1577
-
1578
- const productLabel = product ? product.replace(/_/g, " ") : "subscription";
1579
- return `- ${toolLabel} ${productLabel}: ${planType}`;
1580
- }
1581
-
1582
- function parseArgs(argv) {
1583
- const out = {
1584
- diagnostics: false,
1585
- json: false,
1586
- light: false,
1587
- noSpinner: false,
1588
- probeKeychain: false,
1589
- probeKeychainDetails: false,
1590
- };
1591
-
1592
- for (let i = 0; i < argv.length; i++) {
1593
- const a = argv[i];
1594
- if (a === "--diagnostics") out.diagnostics = true;
1595
- else if (a === "--json") out.json = true;
1596
- else if (a === "--light") out.light = true;
1597
- else if (a === "--no-spinner") out.noSpinner = true;
1598
- else if (a === "--probe-keychain") out.probeKeychain = true;
1599
- else if (a === "--probe-keychain-details") {
1600
- out.probeKeychainDetails = true;
1601
- out.probeKeychain = true;
1602
- } else throw new Error(`Unknown option: ${a}`);
1603
- }
1604
-
1605
- return out;
1606
- }
1607
-
1608
- // Pure renderer: turn the structured summary into a fixed-width ASCII table.
1609
- // "light" output is for AI agents and CI: deterministic columns, no emoji or
1610
- // spinner side effects, easy to grep. Returns a string (caller adds trailing
1611
- // newline).
1612
- function renderLightTable(summary) {
1613
- const rows = [];
1614
- const push = (k, v) => rows.push([k, v == null || v === "" ? "—" : String(v)]);
1615
-
1616
- push("Version", summary.version);
1617
- push("Base URL", summary.base_url);
1618
- push("Device token", summary.device_token_set ? "set" : "unset");
1619
- push("Queue pending (bytes)", summary.queue.pending_bytes);
1620
- push("Queue size (bytes)", summary.queue.size_bytes);
1621
- push("Last parse", summary.last_parse);
1622
- push("Last notify", summary.last_notify);
1623
- push("Last upload", summary.last_upload);
1624
- push("Next upload after", summary.next_upload_after);
1625
- push("Backoff until", summary.backoff_until);
1626
- if (summary.last_upload_error) push("Last upload error", summary.last_upload_error);
1627
- if (summary.last_sync_skipped) {
1628
- push(
1629
- "Last sync skipped",
1630
- `${summary.last_sync_skipped.at} (${summary.last_sync_skipped.reason || "unknown"})`,
1631
- );
1632
- }
1633
-
1634
- for (const [name, state] of Object.entries(summary.hooks || {})) {
1635
- push(`Hook · ${name}`, state ? "set" : "unset");
1636
- }
1637
-
1638
- for (const root of summary.extra_scan_roots || []) {
1639
- const state = root.exists ? "" : (root.error ? ` (unreadable: ${root.error})` : " (missing)");
1640
- push(`Scan root · ${root.provider}`, `${root.origin}: ${root.path}${state}`);
1641
- }
1642
-
1643
- for (const [name, info] of Object.entries(summary.providers || {})) {
1644
- const detail = [];
1645
- if (typeof info.installed === "boolean") detail.push(info.installed ? "installed" : "not installed");
1646
- if (typeof info.files === "number") detail.push(`${info.files} file${info.files !== 1 ? "s" : ""}`);
1647
- if (info.detail) detail.push(info.detail);
1648
- if (info.error) detail.push(info.error);
1649
- if (Array.isArray(info.wsl_distros) && info.wsl_distros.length) {
1650
- detail.push(`WSL: ${info.wsl_distros.map((d) => `${d.name} (v${d.version ?? "?"})`).join(", ")}`);
1651
- }
1652
- push(`Provider · ${name}`, detail.length ? detail.join(", ") : "—");
1653
- }
1654
-
1655
- // Mirror formatCopilotLines(): stay silent for machines with no Copilot
1656
- // signal at all instead of printing "not found" rows for everyone.
1657
- const copilotDetected =
1658
- summary.copilot &&
1659
- (summary.copilot.token_set ||
1660
- summary.copilot.otel_enabled ||
1661
- summary.copilot.otel_has_files ||
1662
- summary.copilot.store_has_file ||
1663
- summary.copilot.app_db_has_file);
1664
- if (copilotDetected) {
1665
- push(
1666
- "Copilot App/CLI store",
1667
- summary.copilot.store_has_file
1668
- ? `${summary.copilot.source_mode || "set"}: ${
1669
- (summary.copilot.store_details || [])
1670
- .map(formatCopilotStoreDetail)
1671
- .join(", ") ||
1672
- (summary.copilot.store_paths || [summary.copilot.store_path])
1673
- .filter(Boolean)
1674
- .join(", ")
1675
- }`
1676
- : `not found (${summary.copilot.store_path || "unknown"})`,
1677
- );
1678
- push(
1679
- "Copilot App DB legacy baseline",
1680
- summary.copilot.app_db_has_file
1681
- ? `${summary.copilot.app_db_mode || "set"}: ${(summary.copilot.app_db_paths || [summary.copilot.app_db_path]).filter(Boolean).join(", ")}`
1682
- : `not found (${summary.copilot.app_db_path || "unknown"})`,
1683
- );
1684
- push(
1685
- "Copilot OTEL Chat/legacy CLI",
1686
- summary.copilot.otel_has_files
1687
- ? summary.copilot.otel_path || "files found"
1688
- : summary.copilot.otel_enabled
1689
- ? "enabled, no files"
1690
- : "not enabled",
1691
- );
1692
- push("Copilot precision", summary.copilot.precision);
1693
- push("Copilot coverage", summary.copilot.coverage);
1694
- for (const reason of summary.copilot.degraded_reasons || []) {
1695
- push("Copilot degraded", reason);
1696
- }
1697
- if (summary.copilot.recommended_action) {
1698
- push("Copilot action", summary.copilot.recommended_action);
1699
- }
1700
- }
1701
-
1702
- if (summary.passive_mode) {
1703
- push("Passive mode active", summary.passive_mode.active ? "yes" : "no");
1704
- for (const p of summary.passive_mode.providers || []) {
1705
- if (p.passive) {
1706
- push(`Passive · ${p.name}`, `hook ${p.hook_failure_reason || "missing"}, logs present`);
1707
- }
1708
- }
1709
- }
1710
-
1711
- const keyWidth = Math.max(...rows.map(([k]) => k.length), 8);
1712
- const valWidth = Math.max(...rows.map(([, v]) => v.length), 8);
1713
- const sep = `+${"-".repeat(keyWidth + 2)}+${"-".repeat(valWidth + 2)}+`;
1714
- const lines = [sep, `| ${"Key".padEnd(keyWidth)} | ${"Value".padEnd(valWidth)} |`, sep];
1715
- for (const [k, v] of rows) {
1716
- lines.push(`| ${k.padEnd(keyWidth)} | ${v.padEnd(valWidth)} |`);
1717
- }
1718
- lines.push(sep);
1719
- return lines.join("\n");
1720
- }
1721
-
1722
- async function safeStatSize(p) {
1723
- try {
1724
- const st = await fs.stat(p);
1725
- return st.size || 0;
1726
- } catch (_e) {
1727
- return 0;
1728
- }
1729
- }
1730
-
1731
- async function safeReadText(p) {
1732
- try {
1733
- return await fs.readFile(p, "utf8");
1734
- } catch (_e) {
1735
- return null;
1736
- }
1737
- }
1738
-
1739
- function parseEpochMsToIso(v) {
1740
- const ms = Number(v);
1741
- if (!Number.isFinite(ms) || ms <= 0) return null;
1742
- const d = new Date(ms);
1743
- if (Number.isNaN(d.getTime())) return null;
1744
- return d.toISOString();
1745
- }
1746
-
1747
- module.exports = { cmdStatus, summarizeQoderDetail };
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 pkg = require("../../package.json");
6
+ const { resolveDumateDbPaths } = require("../lib/dumate");
7
+
8
+ const { readJson } = require("../lib/fs");
9
+ const { readCursorStateSummary } = require("../lib/cursor-store");
10
+ const {
11
+ readCodexNotify,
12
+ readAcodeNotify,
13
+ readEveryCodeNotify,
14
+ buildCodexNotifyCmd,
15
+ buildAcodeNotifyCmd,
16
+ isManagedNotifyCmd,
17
+ } = require("../lib/codex-config");
18
+ const { countRecordOnlyFiles, formatRecordOnlyWarning } = require("../lib/codex-usage-record");
19
+ const {
20
+ isClaudeHookConfigured,
21
+ areClaudeUsageHooksConfigured,
22
+ buildClaudeHookCommand,
23
+ buildHookCommand,
24
+ } = require("../lib/claude-config");
25
+ const {
26
+ resolveGeminiConfigDir,
27
+ resolveGeminiSettingsPath,
28
+ isGeminiHookConfigured,
29
+ buildGeminiHookCommand,
30
+ } = require("../lib/gemini-config");
31
+ const {
32
+ resolveOpencodeConfigDir,
33
+ isOpencodePluginInstalled,
34
+ } = require("../lib/opencode-config");
35
+ const { collectLocalSubscriptions } = require("../lib/subscriptions");
36
+ const {
37
+ describeCopilotOtelStatus,
38
+ readCopilotOauthToken,
39
+ } = require("../lib/usage-limits");
40
+ const {
41
+ normalizeState: normalizeUploadState,
42
+ } = require("../lib/upload-throttle");
43
+ const { collectTrackerDiagnostics } = require("../lib/diagnostics");
44
+ const { detectPassiveProviders, isPassiveModeActive } = require("../lib/passive-mode");
45
+ const { probeOpenclawHookState } = require("../lib/openclaw-hook");
46
+ const {
47
+ probeOpenclawSessionPluginState,
48
+ } = require("../lib/openclaw-session-plugin");
49
+ const { resolveTrackerPaths } = require("../lib/tracker-paths");
50
+ const { resolveDeviceTokenPresence } = require("../lib/cloud-device-token");
51
+ const {
52
+ isCollectionPaused,
53
+ isRunReportEnabled,
54
+ } = require("../lib/collection-pause");
55
+ const {
56
+ resolveKimiWireFiles,
57
+ resolveKimiCodeWireFiles,
58
+ resolveKiroCliDbPath,
59
+ resolveKiroCliSessionFiles,
60
+ resolveKiroBasePath,
61
+ resolveKiroDbPath,
62
+ resolveKiroJsonlPath,
63
+ resolveCodebuddyHome,
64
+ resolveCodebuddyProjectFiles,
65
+ resolveWorkbuddyHome,
66
+ resolveWorkbuddyProjectFiles,
67
+ resolveOmpSessionFiles,
68
+ resolveOmpAgentDir,
69
+ resolveOmoSessionFiles,
70
+ resolveOmoAgentDir,
71
+ resolveMinimaxCodeSessionFiles,
72
+ resolveMinimaxCodeSessionsDir,
73
+ resolvePiSessionFiles,
74
+ resolvePiAgentDir,
75
+ piAgentDirCollidesWithOmp,
76
+ resolvePrimeAgentSessionFiles,
77
+ resolvePrimeAgentDir,
78
+ resolveCraftSessionFiles,
79
+ resolveCraftConfigDir,
80
+ resolveReasonixHome,
81
+ resolveReasonixTelemetryFiles,
82
+ resolveMuseHome,
83
+ resolveMuseSessionFiles,
84
+ resolveKilocodeTaskFiles,
85
+ resolveRoocodeTaskFiles,
86
+ resolveClineSessionFilesWithStatus,
87
+ resolveZedDbPath,
88
+ resolveLmstudioHome,
89
+ resolveLmstudioLogFiles,
90
+ resolveUnslothDbPath,
91
+ resolveQoderDbPaths,
92
+ resolveQoderCnDbPaths,
93
+ resolveQoderProjectsDir,
94
+ resolveQoderCnProjectsDir,
95
+ listQoderNewSessionFiles,
96
+ resolveClaudeScienceDbPaths,
97
+ resolveAnythingllmDbPath,
98
+ resolveDevinDbPath,
99
+ resolveGooseDbPath,
100
+ listDroidSettingsFiles,
101
+ resolveDroidSessionsDir,
102
+ resolveDshHomes,
103
+ resolveDshSessionFiles,
104
+ resolveCommandCodeHomes,
105
+ resolveCommandCodeSessionFiles,
106
+ resolveTraeStoragePath,
107
+ readTraeEntitlementFromStorage,
108
+ resolveGrokBuildSessions,
109
+ resolveHermesPath,
110
+ resolveHermesDbPath,
111
+ resolveCopilotSessionStorePaths,
112
+ describeCopilotSessionStoreDb,
113
+ resolveCopilotAppDbPath,
114
+ resolveCopilotAppDbPaths,
115
+ probeWslDistros,
116
+ resolveZcodeInstallPaths,
117
+ } = require("../lib/rollout");
118
+ const {
119
+ TRAE_CN_USAGE_ENV,
120
+ isTraeCnUsageEnabled,
121
+ resolveTraeCnStoragePath,
122
+ readTraeCnAuthFromStorage,
123
+ extractTraeCnToken,
124
+ } = require("../lib/trae-cn-config");
125
+ const wsl = require("../lib/wsl-probe");
126
+ const { getWslMode, isInvalidWslMode, shouldProbeWsl, discoverWslHome } = wsl;
127
+ const { resolveInstallPaths, resolveZcodeNativeDbPath, resolveMimoNativeDbPath } = require("../lib/install-resolver");
128
+ const {
129
+ describeScanRootOrigin,
130
+ describeScanRootState,
131
+ hasAnyScanChild,
132
+ resolveEnvRoot,
133
+ resolveScanRoots,
134
+ } = require("../lib/scan-roots");
135
+ const { probeGrokHookState, resolveGrokHome } = require("../lib/grok-hook");
136
+ const { probeOmpHookState } = require("../lib/omp-hook");
137
+
138
+ // `filename` may be a list, in which case the first child that exists wins. A
139
+ // resolver using requireAnyChild accepts a root that holds ANY of several
140
+ // children, so probing only the first one here would report "not detected" for
141
+ // an install sync happily counts (e.g. Codex with archived_sessions/ but no
142
+ // live sessions/).
143
+ function formatResolvedPaths(paths, filename) {
144
+ const candidates = filename == null ? [] : (Array.isArray(filename) ? filename : [filename]);
145
+ const resolveFile = (root) => {
146
+ if (candidates.length === 0) return root;
147
+ for (const candidate of candidates) {
148
+ const file = path.join(root, candidate);
149
+ try { if (fssync.existsSync(file)) return file; } catch (_e) {}
150
+ }
151
+ return null;
152
+ };
153
+ const active = [];
154
+ for (const [label, root] of [["native", paths.native], ["WSL", paths.wsl]]) {
155
+ if (!root) continue;
156
+ const file = resolveFile(root);
157
+ if (!file) continue;
158
+ try { if (fssync.existsSync(file)) active.push(`${label}: ${file}`); } catch (_e) {}
159
+ }
160
+ return active;
161
+ }
162
+
163
+ // Combine a legacy DB path with its new-JSONL projects-dir path for the
164
+ // machine-readable summary. Either side may be "" (absent); both absent
165
+ // yields "" so callers can fall back to "not found".
166
+ function summarizeQoderDetail(dbPath, newPath) {
167
+ return [dbPath, newPath].filter(Boolean).join(" + ") || "";
168
+ }
169
+
170
+ // The Trae SOLO entitlement snapshot is read directly from the Trae Local
171
+ // State storage.json via the shared parser (readTraeEntitlementFromStorage).
172
+ // The queue.jsonl contract is token-count-only (CLAUDE.md privacy rule), so
173
+ // plan/limits metadata is never persisted into queue rows — this is the read
174
+ // side of that contract so users can actually see the advertised plan data.
175
+ function formatTraeEntitlementLine(ent) {
176
+ const parts = [];
177
+ if (ent.identity) parts.push(`plan ${ent.identity}`);
178
+ if (ent.pro_period) parts.push(`${ent.pro_period} period`);
179
+ if (typeof ent.is_dollar_billing === "boolean") {
180
+ parts.push(ent.is_dollar_billing ? "dollar billing" : "package billing");
181
+ }
182
+ if (typeof ent.enable_solo_builder === "boolean") {
183
+ parts.push(`solo builder: ${ent.enable_solo_builder ? "yes" : "no"}`);
184
+ }
185
+ if (typeof ent.enable_solo_coder === "boolean") {
186
+ parts.push(`solo coder: ${ent.enable_solo_coder ? "yes" : "no"}`);
187
+ }
188
+ if (typeof ent.fast_request_per === "number") {
189
+ parts.push(`${ent.fast_request_per} fast requests/hr`);
190
+ }
191
+ if (ent.in_waitlist === true) parts.push("in waitlist");
192
+ if (ent.captured_at) parts.push(`snapshot ${ent.captured_at}`);
193
+ return parts.length ? parts.join(", ") : "unknown";
194
+ }
195
+
196
+ async function cmdStatus(argv = []) {
197
+ const opts = parseArgs(argv);
198
+ if (opts.diagnostics) {
199
+ const diagnostics = await collectTrackerDiagnostics();
200
+ process.stdout.write(JSON.stringify(diagnostics, null, 2) + "\n");
201
+ return;
202
+ }
203
+
204
+ const home = os.homedir();
205
+ const { trackerDir, binDir } = await resolveTrackerPaths({ home });
206
+ const configPath = path.join(trackerDir, "config.json");
207
+ const queuePath = path.join(trackerDir, "queue.jsonl");
208
+ const queueStatePath = path.join(trackerDir, "queue.state.json");
209
+ const cursorsPath = path.join(trackerDir, "cursors.json");
210
+ const notifySignalPath = path.join(trackerDir, "notify.signal");
211
+ const openclawSignalPath = path.join(trackerDir, "openclaw.signal");
212
+ const throttlePath = path.join(trackerDir, "sync.throttle");
213
+ const uploadThrottlePath = path.join(trackerDir, "upload.throttle.json");
214
+ const autoRetryPath = path.join(trackerDir, "auto.retry.json");
215
+ const syncSkipPath = path.join(trackerDir, "sync.skip.json");
216
+ // Normalized like sync (a relative CODEX_HOME is anchored to home, not cwd)
217
+ // so status lists exactly the root sync walks.
218
+ const codexHome = resolveEnvRoot("codex", { env: process.env, home }) || path.join(home, ".codex");
219
+ const codexConfigPath = path.join(codexHome, "config.toml");
220
+ const acodeHome = process.env.TOKENUSAGE_ACODE_HOME || path.join(home, ".acode");
221
+ const acodeConfigPath = path.join(acodeHome, "config.toml");
222
+ const codeHome = process.env.CODE_HOME || path.join(home, ".code");
223
+ const codeConfigPath = path.join(codeHome, "config.toml");
224
+ const claudeSettingsPath = path.join(home, ".claude", "settings.json");
225
+ const codebuddySettingsPath = path.join(
226
+ resolveCodebuddyHome(process.env) || path.join(home, ".codebuddy"),
227
+ "settings.json",
228
+ );
229
+ const workbuddySettingsPath = path.join(
230
+ resolveWorkbuddyHome(process.env) || path.join(home, ".workbuddy"),
231
+ "settings.json",
232
+ );
233
+ // WorkBuddy AI — international build, sibling home (~/.workbuddy-ai).
234
+ const workbuddyAiSettingsPath = path.join(
235
+ resolveWorkbuddyHome(process.env, "workbuddy-ai") || path.join(home, ".workbuddy-ai"),
236
+ "settings.json",
237
+ );
238
+ const geminiConfigDir = resolveGeminiConfigDir({ home, env: process.env });
239
+ const geminiSettingsPath = resolveGeminiSettingsPath({
240
+ configDir: geminiConfigDir,
241
+ });
242
+ const opencodeConfigDir = resolveOpencodeConfigDir({
243
+ home,
244
+ env: process.env,
245
+ });
246
+ const notifyPath = path.join(binDir, "notify.cjs");
247
+ const codexNotifyCmd = buildCodexNotifyCmd(notifyPath);
248
+ const acodeNotifyCmd = buildAcodeNotifyCmd(notifyPath);
249
+ const claudeHookCommand = buildClaudeHookCommand(notifyPath);
250
+ const codebuddyHookCommand = buildHookCommand(notifyPath, "codebuddy");
251
+ const workbuddyHookCommand = buildHookCommand(notifyPath, "workbuddy");
252
+ const workbuddyAiHookCommand = buildHookCommand(notifyPath, "workbuddy-ai");
253
+ const geminiHookCommand = buildGeminiHookCommand(notifyPath);
254
+
255
+ const config = await readJson(configPath);
256
+ // Extra scan roots (#657): CODEX_HOME / CLAUDE_CONFIG_DIR of this process
257
+ // plus config.scanRoots, resolved exactly as sync does, so status lists every
258
+ // root sync walks — this is the output users paste when usage looks wrong.
259
+ const scanRoots = resolveScanRoots({
260
+ home,
261
+ env: process.env,
262
+ config,
263
+ base: { codex: [codexHome], claude: [path.join(home, ".claude")] },
264
+ });
265
+ const extraScanRoots = [];
266
+ for (const provider of ["codex", "claude"]) {
267
+ for (const entry of scanRoots[provider]) {
268
+ if (entry.origin === "native") continue;
269
+ extraScanRoots.push({
270
+ provider,
271
+ origin: describeScanRootOrigin(entry, provider),
272
+ path: entry.path,
273
+ exists: entry.exists,
274
+ error: entry.error || null,
275
+ });
276
+ }
277
+ }
278
+ const describeExtraScanRoot = (root) =>
279
+ `${root.provider} ${root.origin}: ${root.path}${describeScanRootState(root)}`;
280
+ const scanRootsLine = extraScanRoots.length > 0
281
+ ? `- Extra scan roots: ${extraScanRoots.map(describeExtraScanRoot).join(" | ")}`
282
+ : null;
283
+ const { cursors } = await readCursorStateSummary({ trackerDir, cursorsPath });
284
+ const codexRecordOnlyWarning = formatRecordOnlyWarning(countRecordOnlyFiles(cursors));
285
+ const queueState = (await readJson(queueStatePath)) || { offset: 0 };
286
+ const uploadThrottle = normalizeUploadState(
287
+ await readJson(uploadThrottlePath),
288
+ );
289
+ const autoRetry = await readJson(autoRetryPath);
290
+ // Written by sync whenever it had to skip a run. Present here so a stalled
291
+ // parse has a visible cause instead of only a frozen "Last parse".
292
+ const syncSkip = await readJson(syncSkipPath);
293
+ // Collection controls (0.2.0): pause flag + per-run report preference.
294
+ const collectionPaused = isCollectionPaused(trackerDir);
295
+ const runReportEnabled = isRunReportEnabled(trackerDir);
296
+
297
+ const queueSize = await safeStatSize(queuePath);
298
+ const pendingBytes = Math.max(0, queueSize - (queueState.offset || 0));
299
+
300
+ const lastNotify = (await safeReadText(notifySignalPath))?.trim() || null;
301
+ const lastOpenclawSync =
302
+ (await safeReadText(openclawSignalPath))?.trim() || null;
303
+ const lastNotifySpawn = parseEpochMsToIso(
304
+ (await safeReadText(throttlePath))?.trim() || null,
305
+ );
306
+
307
+ const codexNotify = await readCodexNotify(codexConfigPath);
308
+ // Not arraysEqual: argv[0] and binDir differ between the desktop app and a
309
+ // terminal `tokenusage` run, so a correctly-installed integration would
310
+ // otherwise report as not configured. See isManagedNotifyCmd.
311
+ const notifyConfigured = isManagedNotifyCmd(codexNotify, codexNotifyCmd);
312
+ const acodeNotify = await readAcodeNotify(acodeConfigPath);
313
+ const acodeConfigured = isManagedNotifyCmd(acodeNotify, acodeNotifyCmd);
314
+ const everyCodeNotify = await readEveryCodeNotify(codeConfigPath);
315
+ const everyCodeConfigured =
316
+ Array.isArray(everyCodeNotify) && everyCodeNotify.length > 0;
317
+ const claudeHookConfigured = await areClaudeUsageHooksConfigured({
318
+ settingsPath: claudeSettingsPath,
319
+ hookCommand: claudeHookCommand,
320
+ });
321
+ const codebuddyHookConfigured = await isClaudeHookConfigured({
322
+ settingsPath: codebuddySettingsPath,
323
+ hookCommand: codebuddyHookCommand,
324
+ });
325
+ const workbuddyHookConfigured = await isClaudeHookConfigured({
326
+ settingsPath: workbuddySettingsPath,
327
+ hookCommand: workbuddyHookCommand,
328
+ });
329
+ const workbuddyAiHookConfigured = await isClaudeHookConfigured({
330
+ settingsPath: workbuddyAiSettingsPath,
331
+ hookCommand: workbuddyAiHookCommand,
332
+ });
333
+ const geminiHookConfigured = await isGeminiHookConfigured({
334
+ settingsPath: geminiSettingsPath,
335
+ hookCommand: geminiHookCommand,
336
+ });
337
+ const opencodePluginConfigured = await isOpencodePluginInstalled({
338
+ configDir: opencodeConfigDir,
339
+ });
340
+ const openclawSessionPluginState = await probeOpenclawSessionPluginState({
341
+ home,
342
+ trackerDir,
343
+ env: process.env,
344
+ });
345
+ const openclawHookState = await probeOpenclawHookState({
346
+ home,
347
+ trackerDir,
348
+ env: process.env,
349
+ });
350
+
351
+ const lastUpload = uploadThrottle.lastSuccessMs
352
+ ? parseEpochMsToIso(uploadThrottle.lastSuccessMs)
353
+ : typeof queueState.updatedAt === "string"
354
+ ? queueState.updatedAt
355
+ : null;
356
+ const nextUpload = parseEpochMsToIso(uploadThrottle.nextAllowedAtMs || null);
357
+ const backoffUntil = parseEpochMsToIso(uploadThrottle.backoffUntilMs || null);
358
+ const lastUploadError = uploadThrottle.lastError
359
+ ? `${uploadThrottle.lastErrorAt || "unknown"} ${uploadThrottle.lastError}`
360
+ : null;
361
+ const syncSkipLine = syncSkip?.at
362
+ ? `- Last sync skipped: ${syncSkip.at} (${syncSkip.reason || "unknown"}${
363
+ syncSkip.detail ? `, ${syncSkip.detail}` : ""
364
+ })`
365
+ : null;
366
+ const autoRetryAt = parseEpochMsToIso(autoRetry?.retryAtMs || null);
367
+ const autoRetryLine = autoRetryAt
368
+ ? `- Auto retry after: ${autoRetryAt} (${autoRetry?.reason || "scheduled"}, pending ${Number(
369
+ autoRetry?.pendingBytes || 0,
370
+ )} bytes)`
371
+ : null;
372
+
373
+ const subscriptions = await collectLocalSubscriptions({
374
+ home,
375
+ env: process.env,
376
+ probeKeychain: opts.probeKeychain,
377
+ probeKeychainDetails: opts.probeKeychainDetails,
378
+ });
379
+ const subscriptionLines =
380
+ subscriptions.length > 0 ? subscriptions.map(formatSubscriptionLine) : [];
381
+
382
+ const kimiWireFiles = resolveKimiWireFiles(process.env);
383
+ const kimiHome = process.env.KIMI_HOME || path.join(home, ".kimi");
384
+ const kimiInstalled = fssync.existsSync(path.join(kimiHome, "sessions"));
385
+
386
+ const kimiCodeWireFiles = resolveKimiCodeWireFiles(process.env);
387
+ const kimiCodeHome = process.env.KIMI_CODE_HOME || path.join(home, ".kimi-code");
388
+ const kimiCodeInstalled = fssync.existsSync(path.join(kimiCodeHome, "sessions"));
389
+
390
+ // Kiro CLI — reads the legacy SQLite/session files and Kiro CLI 2.13+
391
+ // event sessions. End-user dashboards show them merged under "Kiro"; this
392
+ // status line surfaces which passive sources are actually present.
393
+ const kiroCliDbPath = resolveKiroCliDbPath(process.env);
394
+ const kiroCliSessionFiles = resolveKiroCliSessionFiles(process.env);
395
+ const kiroCliNativePresent =
396
+ fssync.existsSync(kiroCliDbPath) || kiroCliSessionFiles.length > 0;
397
+ // WSL install discovery mirrors sync: overrides pin a single install.
398
+ let kiroCliWsl = null; // { db, sessionFiles }
399
+ if (
400
+ process.platform === "win32" &&
401
+ !process.env.KIRO_CLI_DB_PATH && !process.env.KIRO_HOME &&
402
+ wsl.shouldProbeWsl(process.env)
403
+ ) {
404
+ const wslKiroHomeDir = wsl.discoverWslHome(".kiro");
405
+ const wslCliDataDir = wsl.discoverWslHome(".local/share/kiro-cli");
406
+ const wslHomeRoot = wslKiroHomeDir
407
+ ? path.dirname(wslKiroHomeDir)
408
+ : (wslCliDataDir ? path.dirname(path.dirname(path.dirname(wslCliDataDir))) : null);
409
+ if (wslHomeRoot) {
410
+ const wslDb = path.join(wslHomeRoot, ".local", "share", "kiro-cli", "data.sqlite3");
411
+ const wslFiles = resolveKiroCliSessionFiles({
412
+ ...process.env,
413
+ KIRO_CLI_DB_PATH: wslDb,
414
+ KIRO_HOME: path.join(wslHomeRoot, ".kiro"),
415
+ });
416
+ if (fssync.existsSync(wslDb) || wslFiles.length > 0) {
417
+ kiroCliWsl = { db: wslDb, sessionFiles: wslFiles };
418
+ }
419
+ }
420
+ }
421
+ const kiroCliPaths = process.platform === "win32"
422
+ ? wsl.resolveAllWin32Paths({
423
+ nativeValue: kiroCliNativePresent ? kiroCliDbPath : null,
424
+ wslValue: kiroCliWsl ? kiroCliWsl.db : null,
425
+ env: process.env,
426
+ platform: "win32",
427
+ })
428
+ : { native: kiroCliNativePresent ? kiroCliDbPath : null, wsl: null };
429
+ // Non-both modes park the picked value in the native slot — label by
430
+ // marker identity, not slot name. A session-files-only install has no DB
431
+ // on disk; show the sessions dir instead of a nonexistent DB path.
432
+ const kiroCliMarkers = [kiroCliPaths.native, kiroCliPaths.wsl].filter(Boolean);
433
+ const kiroCliActive = kiroCliMarkers.map((m) => {
434
+ if (kiroCliWsl && m === kiroCliWsl.db) {
435
+ const shown = fssync.existsSync(m) || kiroCliWsl.sessionFiles.length === 0
436
+ ? m
437
+ : path.dirname(kiroCliWsl.sessionFiles[0]);
438
+ return `WSL: ${shown}`;
439
+ }
440
+ const shown = fssync.existsSync(m) || kiroCliSessionFiles.length === 0
441
+ ? m
442
+ : path.dirname(kiroCliSessionFiles[0]);
443
+ return `native: ${shown}`;
444
+ });
445
+ const kiroCliFileCount =
446
+ (kiroCliMarkers.includes(kiroCliDbPath) ? kiroCliSessionFiles.length : 0) +
447
+ (kiroCliWsl && kiroCliMarkers.includes(kiroCliWsl.db) ? kiroCliWsl.sessionFiles.length : 0);
448
+ const kiroCliDbFound = kiroCliMarkers.some((m) => {
449
+ try { return fssync.existsSync(m); } catch (_e) { return false; }
450
+ });
451
+ const kiroCliInstalled = kiroCliMarkers.length > 0;
452
+
453
+ // Kiro IDE — passive scan of globalStorage dev_data (SQLite or JSONL).
454
+ const kiroIdeNativeBase = resolveKiroBasePath(process.env);
455
+ const wslKiroIdeBase = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
456
+ ? wsl.discoverWslHome(".config/Kiro/User/globalStorage/kiro.kiroagent")
457
+ : null;
458
+ const kiroIdePaths = resolveInstallPaths({ nativeValue: kiroIdeNativeBase, wslValue: wslKiroIdeBase });
459
+ const kiroIdeHasData = (base) => Boolean(base)
460
+ && (fssync.existsSync(resolveKiroDbPath(base)) || fssync.existsSync(resolveKiroJsonlPath(base)));
461
+ const kiroIdeActive = [kiroIdePaths.native, kiroIdePaths.wsl]
462
+ .filter((base) => kiroIdeHasData(base))
463
+ .map((base) => (wslKiroIdeBase && base === wslKiroIdeBase ? `WSL: ${base}` : `native: ${base}`));
464
+ const kiroIdeInstalled = kiroIdeActive.length > 0;
465
+
466
+ // Claude Code — dual-install aware projects scan (#307). Mirrors sync:
467
+ // installs are UNIONED (not single-picked by mode) so a WSL ~/.claude
468
+ // never hides the native one from view, and labels come from install
469
+ // identity rather than resolveAllWin32Paths' slot names.
470
+ const claudeCodeActive = [];
471
+ {
472
+ const claudeHomesStatus = [];
473
+ if (process.platform !== "win32" || wsl.shouldProbeNative(process.env)) {
474
+ claudeHomesStatus.push({ dir: path.join(home, ".claude"), label: "native" });
475
+ }
476
+ const wslClaudeHomeStatus = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
477
+ ? wsl.discoverWslHome(".claude")
478
+ : null;
479
+ if (wslClaudeHomeStatus) claudeHomesStatus.push({ dir: wslClaudeHomeStatus, label: "WSL" });
480
+ for (const entry of scanRoots.claude) {
481
+ if (entry.origin === "native" || !entry.exists) continue;
482
+ claudeHomesStatus.push({ dir: entry.path, label: describeScanRootOrigin(entry, "claude") });
483
+ }
484
+ for (const { dir, label } of claudeHomesStatus) {
485
+ const projects = path.join(dir, "projects");
486
+ try {
487
+ if (fssync.existsSync(projects)) claudeCodeActive.push(`${label}: ${projects}`);
488
+ } catch (_e) {}
489
+ }
490
+ }
491
+ const claudeCodeInstalled = claudeCodeActive.length > 0;
492
+
493
+ // AnythingLLM Desktop — per-message token metrics in workspace_chats.
494
+ const anythingllmDbPath = resolveAnythingllmDbPath(process.env);
495
+ const anythingllmInstalled = Boolean(
496
+ anythingllmDbPath && fssync.existsSync(anythingllmDbPath),
497
+ );
498
+
499
+ // CodeBuddy — passive scan only (no hooks). Surface the file count so
500
+ // operators can confirm JSONL sessions and extension logs are discovered.
501
+ const codebuddyHome = resolveCodebuddyHome(process.env);
502
+ const codebuddyInstalled = Boolean(codebuddyHome && fssync.existsSync(codebuddyHome));
503
+ const codebuddyFiles = codebuddyInstalled
504
+ ? resolveCodebuddyProjectFiles(process.env)
505
+ : [];
506
+
507
+ // WorkBuddy — passive scan (sibling Claude-Code fork). Surface both the
508
+ // recursive JSONL count and SQLite fallback so operators can confirm coverage.
509
+ const workbuddyHome = resolveWorkbuddyHome(process.env);
510
+ const workbuddyInstalled = Boolean(workbuddyHome && fssync.existsSync(workbuddyHome));
511
+ const workbuddyFiles = workbuddyInstalled
512
+ ? resolveWorkbuddyProjectFiles(process.env)
513
+ : [];
514
+ const workbuddyDbExists = workbuddyInstalled
515
+ ? fssync.existsSync(path.join(workbuddyHome, "workbuddy.db"))
516
+ : false;
517
+
518
+ const workbuddyAiHome = resolveWorkbuddyHome(process.env, "workbuddy-ai");
519
+ const workbuddyAiInstalled = Boolean(workbuddyAiHome && fssync.existsSync(workbuddyAiHome));
520
+ const workbuddyAiFiles = workbuddyAiInstalled
521
+ ? resolveWorkbuddyProjectFiles(process.env, "workbuddy-ai")
522
+ : [];
523
+ const workbuddyAiDbExists = workbuddyAiInstalled
524
+ ? fssync.existsSync(path.join(workbuddyAiHome, "workbuddy.db"))
525
+ : false;
526
+
527
+ // oh-my-pi — passive scan + optional notify extension.
528
+ const ompAgentDir = resolveOmpAgentDir(process.env);
529
+ const ompInstalled = Boolean(ompAgentDir) && fssync.existsSync(path.join(ompAgentDir, "sessions"));
530
+ const ompFiles = ompInstalled ? resolveOmpSessionFiles(process.env) : [];
531
+ const ompHookState = await probeOmpHookState({ home, trackerDir, env: process.env });
532
+
533
+ // OmO — passive scan only (no hooks).
534
+ const omoAgentDir = resolveOmoAgentDir(process.env);
535
+ const omoInstalled = Boolean(omoAgentDir) && fssync.existsSync(path.join(omoAgentDir, "sessions"));
536
+ const omoFiles = omoInstalled ? resolveOmoSessionFiles(process.env) : [];
537
+
538
+ // MiniMax Code — passive scan only (no hooks).
539
+ const minimaxCodeSessionsDir = resolveMinimaxCodeSessionsDir(process.env);
540
+ const minimaxCodeInstalled = Boolean(minimaxCodeSessionsDir) && fssync.existsSync(minimaxCodeSessionsDir);
541
+ const minimaxCodeFiles = minimaxCodeInstalled ? resolveMinimaxCodeSessionFiles(process.env) : [];
542
+
543
+ // pi (@mariozechner/pi-coding-agent) — passive scan only (no hooks).
544
+ // Skip when its agent dir collides with omp's; sync would dedupe anyway.
545
+ const piCollides = piAgentDirCollidesWithOmp(process.env);
546
+ const piAgentDir = resolvePiAgentDir(process.env);
547
+ const piInstalled = !piCollides && Boolean(piAgentDir) && fssync.existsSync(path.join(piAgentDir, "sessions"));
548
+ const piFiles = piInstalled ? resolvePiSessionFiles(process.env) : [];
549
+
550
+ // Prime Agent — passive scan only (no hooks).
551
+ const primeAgentDir = resolvePrimeAgentDir(process.env);
552
+ const primeAgentInstalled = Boolean(primeAgentDir) && fssync.existsSync(path.join(primeAgentDir, "sessions"));
553
+ const primeAgentFiles = primeAgentInstalled ? resolvePrimeAgentSessionFiles(process.env) : [];
554
+
555
+ // Craft Agents — passive scan only (no hooks).
556
+ const craftConfigDir = resolveCraftConfigDir(process.env);
557
+ const craftInstalled = Boolean(craftConfigDir && fssync.existsSync(craftConfigDir));
558
+ const craftFiles = craftInstalled ? resolveCraftSessionFiles(process.env) : [];
559
+
560
+ // Reasonix — passive scan of content-free cumulative telemetry sidecars.
561
+ const reasonixHome = resolveReasonixHome(process.env);
562
+ const reasonixInstalled = Boolean(reasonixHome && fssync.existsSync(reasonixHome));
563
+ const reasonixFiles = reasonixInstalled ? resolveReasonixTelemetryFiles(process.env) : [];
564
+
565
+ // Muse Code (Meta) — passive scan of per-session session.jsonl logs.
566
+ const museInstalled = fssync.existsSync(path.join(resolveMuseHome(process.env), "sessions"));
567
+ const museFiles = museInstalled ? resolveMuseSessionFiles(process.env) : [];
568
+
569
+ // Kilo CLI (kilo.ai @kilocode/plugin) — passive scan of kilo.db.
570
+ const xdgDataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
571
+ const kiloHome = process.env.KILO_HOME || path.join(xdgDataHome, "kilo");
572
+ const kiloNativeValue = process.platform === "win32" && typeof process.env.APPDATA === "string"
573
+ ? path.join(process.env.APPDATA.trim(), "kilo", "kilo.db")
574
+ : path.join(kiloHome, "kilo.db");
575
+ const wslKiloDir = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
576
+ ? wsl.discoverWslHome(".local/share/kilo")
577
+ : null;
578
+ const kiloPaths = resolveInstallPaths({ nativeValue: kiloNativeValue, wslValue: wslKiloDir ? path.join(wslKiloDir, "kilo.db") : null });
579
+ const kiloActive = formatResolvedPaths(kiloPaths);
580
+ const kiloInstalled = kiloActive.length > 0;
581
+ const kiloDbPath = kiloActive.join(" | ");
582
+
583
+ const dumateDbPaths = resolveDumateDbPaths({ home });
584
+ const dumateInstalled = dumateDbPaths.length > 0;
585
+ const dumateDbPath = dumateDbPaths.join(" | ");
586
+
587
+ // Mimo (mimocode — OpenCode-fork SQLite) — passive scan of mimocode.db.
588
+ const mimoNativeValue = resolveMimoNativeDbPath({ home });
589
+ const wslMimoDir = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
590
+ ? wsl.discoverWslHome(".local/share/mimocode")
591
+ : null;
592
+ const mimoPaths = resolveInstallPaths({ nativeValue: mimoNativeValue, wslValue: wslMimoDir ? path.join(wslMimoDir, "mimocode.db") : null });
593
+ const mimoActive = formatResolvedPaths(mimoPaths);
594
+ const mimoInstalled = mimoActive.length > 0;
595
+ const mimoDbPath = mimoActive.join(" | ");
596
+
597
+ // ZCode (Z.ai's coding agent — OpenCode-fork SQLite) — passive scan of db.sqlite.
598
+ const zcodeNativeValue = resolveZcodeNativeDbPath({ home });
599
+ const wslZcodeDir = process.platform === "win32" && wsl.shouldProbeWsl(process.env)
600
+ ? wsl.discoverWslHome(".zcode")
601
+ : null;
602
+ const zcodePaths = resolveZcodeInstallPaths(
603
+ { nativeValue: zcodeNativeValue, wslValue: wslZcodeDir ? path.join(wslZcodeDir, "cli", "db", "db.sqlite") : null },
604
+ process.env, { cursors },
605
+ );
606
+ const zcodeActive = formatResolvedPaths(zcodePaths);
607
+ const zcodeInstalled = zcodeActive.length > 0;
608
+ const zcodeDbPath = zcodeActive.join(" | ");
609
+
610
+ // Qoder Desktop 1.18+ — token usage lives in SharedClientCache/local.db (legacy)
611
+ // and since 2026-08 (app 0.1.2+) also in ~/.qoder/projects JSONL (credit-based).
612
+ const qoderPaths = resolveQoderDbPaths({
613
+ home,
614
+ env: process.env,
615
+ platform: process.platform,
616
+ });
617
+ const qoderActive = formatResolvedPaths(qoderPaths);
618
+ // New JSONL location (com.qoder.app.stable + ~/.qoder/projects)
619
+ const qoderProjectsDirResolved = resolveQoderProjectsDir({ home, env: process.env });
620
+ let qoderNewFiles = [];
621
+ try {
622
+ qoderNewFiles = await listQoderNewSessionFiles(qoderProjectsDirResolved);
623
+ } catch (_e) {
624
+ qoderNewFiles = [];
625
+ }
626
+ const qoderNewInstalled = qoderNewFiles.length > 0;
627
+ const qoderInstalled = qoderActive.length > 0 || qoderNewInstalled;
628
+ const qoderDbPath = qoderActive.join(" | ");
629
+ const qoderNewPath = qoderNewFiles.length > 0
630
+ ? `${qoderProjectsDirResolved} (${qoderNewFiles.length} sessions)`
631
+ : "";
632
+
633
+ // Qoder CN (国内版) — same schema, separate Application Support/QoderCN dir.
634
+ const qoderCnPaths = resolveQoderCnDbPaths({
635
+ home,
636
+ env: process.env,
637
+ platform: process.platform,
638
+ });
639
+ const qoderCnActive = formatResolvedPaths(qoderCnPaths);
640
+ // CN new-JSONL mirrors sync.js: the new CN app writes ~/.qoder-cn/projects,
641
+ // but sync only parses the CN dir when it diverges from the international
642
+ // one (same files must not count under two sources). Only report CN JSONL
643
+ // when the dirs diverge.
644
+ const qoderCnProjectsDirResolved = resolveQoderCnProjectsDir({ home, env: process.env });
645
+ const qoderCnSharesIntlDir = path.normalize(qoderCnProjectsDirResolved) === path.normalize(qoderProjectsDirResolved)
646
+ || (process.platform === "win32"
647
+ && path.normalize(qoderCnProjectsDirResolved).toLowerCase() === path.normalize(qoderProjectsDirResolved).toLowerCase());
648
+ let qoderCnNewFiles = [];
649
+ if (!qoderCnSharesIntlDir) {
650
+ try {
651
+ qoderCnNewFiles = await listQoderNewSessionFiles(qoderCnProjectsDirResolved);
652
+ } catch (_e) {
653
+ qoderCnNewFiles = [];
654
+ }
655
+ }
656
+ const qoderCnNewInstalled = qoderCnNewFiles.length > 0;
657
+ const qoderCnInstalled = qoderCnActive.length > 0 || qoderCnNewInstalled;
658
+ const qoderCnDbPath = qoderCnActive.join(" | ");
659
+ const qoderCnNewPath = qoderCnNewFiles.length > 0
660
+ ? `${qoderCnProjectsDirResolved} (${qoderCnNewFiles.length} sessions)`
661
+ : "";
662
+
663
+ // Claude Science — token usage lives on the `frames` table of operon-cli.db.
664
+ // Unlike the native/WSL pair other providers resolve to, this is an open-ended
665
+ // list: multi-org installs keep one DB per org (and on Windows they all sit
666
+ // inside WSL), so the resolver already returns only paths that exist.
667
+ const claudeScienceActive = resolveClaudeScienceDbPaths({ home, env: process.env });
668
+ const claudeScienceInstalled = claudeScienceActive.length > 0;
669
+ const claudeScienceDbPath = claudeScienceActive.join(" | ");
670
+
671
+ // OpenCode (JSON files + SQLite DB) — passive scan of storage/message/ and opencode.db.
672
+ const opencodeStorageNativeValue = process.env.OPENCODE_HOME || path.join(xdgDataHome, "opencode");
673
+ const wslOpencodeStorageDir = process.platform === "win32" && shouldProbeWsl(process.env)
674
+ ? discoverWslHome(".local/share/opencode")
675
+ : null;
676
+ const opencodeStoragePaths = resolveInstallPaths({
677
+ nativeValue: opencodeStorageNativeValue,
678
+ wslValue: wslOpencodeStorageDir,
679
+ });
680
+ const opencodeStorageActive = formatResolvedPaths(opencodeStoragePaths);
681
+
682
+ const opencodeDbNativeValue = process.env.OPENCODE_HOME || path.join(xdgDataHome, "opencode");
683
+ const wslOpencodeDbDir = process.platform === "win32" && shouldProbeWsl(process.env)
684
+ ? discoverWslHome(".local/share/opencode")
685
+ : null;
686
+ const opencodeDbPaths = resolveInstallPaths({
687
+ nativeValue: opencodeDbNativeValue,
688
+ wslValue: wslOpencodeDbDir,
689
+ });
690
+ const opencodeDbActive = formatResolvedPaths(opencodeDbPaths, "opencode.db");
691
+ const opencodeInstalled = opencodeStorageActive.length > 0 || opencodeDbActive.length > 0;
692
+
693
+ // Every Code (passive sessions scan)
694
+ const codePaths = resolveInstallPaths({
695
+ nativeValue: process.env.CODE_HOME || path.join(home, ".code"),
696
+ wslDir: ".code",
697
+ });
698
+ const codeActive = formatResolvedPaths(codePaths, "sessions");
699
+ const codeInstalled = codeActive.length > 0;
700
+
701
+ // Gemini CLI & Antigravity (shared home)
702
+ const geminiPaths = resolveInstallPaths({
703
+ nativeValue: process.env.GEMINI_HOME || path.join(home, ".gemini"),
704
+ wslDir: ".gemini",
705
+ });
706
+ const geminiActive = formatResolvedPaths(geminiPaths);
707
+ const geminiInstalledStatus = geminiActive.length > 0;
708
+
709
+ // Gemini CLI (passive sessions scan)
710
+ const geminiCliActive = formatResolvedPaths(geminiPaths, "tmp");
711
+ const geminiCliInstalled = geminiCliActive.length > 0;
712
+
713
+ // Antigravity (passive brains scan)
714
+ const antigravityActive = [];
715
+ if (geminiPaths.native) {
716
+ const dirs = [
717
+ path.join(geminiPaths.native, "antigravity", "brain"),
718
+ path.join(geminiPaths.native, "antigravity-ide", "brain"),
719
+ path.join(geminiPaths.native, "antigravity-cli", "brain"),
720
+ ];
721
+ if (dirs.some(d => { try { return fssync.existsSync(d); } catch (_) { return false; } })) {
722
+ antigravityActive.push(`native: ${geminiPaths.native}`);
723
+ }
724
+ }
725
+ if (geminiPaths.wsl) {
726
+ const dirs = [
727
+ path.join(geminiPaths.wsl, "antigravity", "brain"),
728
+ path.join(geminiPaths.wsl, "antigravity-ide", "brain"),
729
+ path.join(geminiPaths.wsl, "antigravity-cli", "brain"),
730
+ ];
731
+ if (dirs.some(d => { try { return fssync.existsSync(d); } catch (_) { return false; } })) {
732
+ antigravityActive.push(`WSL: ${geminiPaths.wsl}`);
733
+ }
734
+ }
735
+ const antigravityInstalled = antigravityActive.length > 0;
736
+
737
+ // Codex CLI (passive sessions scan). Mirrors the sync resolution exactly
738
+ // (union + requireAnyChild, see src/commands/sync.js): status is the tool
739
+ // users are asked to paste when Codex usage looks wrong, so it must list
740
+ // every root sync actually walks — and no empty shell sync would skip.
741
+ const codexPaths = resolveInstallPaths({
742
+ nativeValue: codexHome,
743
+ wslDir: ".codex",
744
+ requireAnyChild: ["sessions", "archived_sessions"],
745
+ union: true,
746
+ });
747
+ // Both children, matching requireAnyChild above: an install holding only
748
+ // archived_sessions/ is counted by sync and must not read as "not detected".
749
+ const codexActive = formatResolvedPaths(codexPaths, ["sessions", "archived_sessions"]);
750
+ for (const entry of scanRoots.codex) {
751
+ if (entry.origin === "native" || !entry.exists) continue;
752
+ if (!hasAnyScanChild(entry.path, ["sessions", "archived_sessions"])) continue;
753
+ codexActive.push(`${describeScanRootOrigin(entry, "codex")}: ${entry.path}`);
754
+ }
755
+ const codexInstalledStatus = codexActive.length > 0;
756
+
757
+ const acodePaths = resolveInstallPaths({
758
+ nativeValue: acodeHome,
759
+ wslDir: ".acode",
760
+ requireAnyChild: ["sessions", "archived_sessions"],
761
+ union: true,
762
+ });
763
+ const acodeActive = formatResolvedPaths(acodePaths, ["sessions", "archived_sessions"]);
764
+ const acodeInstalled = acodeActive.length > 0;
765
+
766
+ // Kimi (passive sessions scan)
767
+ const kimiPaths = resolveInstallPaths({
768
+ nativeValue: path.join(home, ".kimi"),
769
+ wslDir: ".kimi",
770
+ });
771
+ const kimiActive = formatResolvedPaths(kimiPaths, "sessions");
772
+
773
+ // Kilo Code VS Code extension — passive scan of all VS Code-family
774
+ // globalStorage/kilocode.kilo-code/tasks/ ui_messages.json files.
775
+ const kilocodeTaskFiles = resolveKilocodeTaskFiles(process.env);
776
+ const kilocodeInstalled = kilocodeTaskFiles.length > 0;
777
+
778
+ // Roo Code VS Code extension — same Cline-derived ui_messages.json format,
779
+ // different globalStorage subdir (rooveterinaryinc.roo-cline).
780
+ const roocodeTaskFiles = resolveRoocodeTaskFiles(process.env);
781
+ const roocodeInstalled = roocodeTaskFiles.length > 0;
782
+
783
+ // Cline CLI v3 / desktop app — passive scan of
784
+ // <home>/data/sessions/*/<session>.messages.json (Cline's own data dir, not
785
+ // the VS Code globalStorage the Roo/Kilo forks still use).
786
+ const clineScan = resolveClineSessionFilesWithStatus(process.env);
787
+ const clineSessionFiles = clineScan.files;
788
+ const clineInstalled = clineSessionFiles.length > 0;
789
+ const clineSessionsDirCount = new Set(
790
+ clineSessionFiles.map((file) => path.dirname(path.dirname(file.filePath))),
791
+ ).size;
792
+ const clineDiscoveryError = clineScan.errors.length > 0
793
+ ? clineScan.errors
794
+ .map(({ root, error }) => `${root}: ${error.code ? `${error.code}: ` : ""}${error.message}`)
795
+ .join("; ")
796
+ : null;
797
+
798
+ // Zed Agent — passive read of threads.db across all model providers
799
+ // (hosted "zed.dev" and bring-your-own alike). threadTotals tracks one entry
800
+ // per thread we've surfaced usage for, so its size distinguishes "DB present
801
+ // with usage" from "DB present but nothing counted yet" (fresh/undecodable).
802
+ const zedDbPath = resolveZedDbPath(process.env);
803
+ const zedInstalled = Boolean(zedDbPath && fssync.existsSync(zedDbPath));
804
+ const zedThreadsCounted =
805
+ cursors?.zed?.threadTotals && typeof cursors.zed.threadTotals === "object"
806
+ ? Object.keys(cursors.zed.threadTotals).length
807
+ : 0;
808
+
809
+ // Goose (Block) — passive cumulative-delta read of sessions.db.
810
+ const gooseDbPath = resolveGooseDbPath(process.env);
811
+ const gooseInstalled = Boolean(gooseDbPath && fssync.existsSync(gooseDbPath));
812
+
813
+ // Droid (Factory CLI) — passive cumulative-delta read of *.settings.json.
814
+ const droidSessionsDir = resolveDroidSessionsDir(process.env);
815
+ const droidSettingsFiles = listDroidSettingsFiles(process.env);
816
+ const droidInstalled = droidSettingsFiles.length > 0;
817
+ const dshHomes = resolveDshHomes(process.env);
818
+ const dshSessionsDir = dshHomes.map((homeDir) => path.join(homeDir, "sessions")).join(", ");
819
+ const dshSessionFiles = await resolveDshSessionFiles(process.env);
820
+ const dshInstalled = dshSessionFiles.length > 0;
821
+ let commandCodeProjectsDir = "";
822
+ let commandCodeSessionFiles = [];
823
+ let commandCodeDiscoveryError = null;
824
+ try {
825
+ commandCodeProjectsDir = resolveCommandCodeHomes(process.env)
826
+ .map((homeDir) => path.join(homeDir, "projects"))
827
+ .join(", ");
828
+ commandCodeSessionFiles = await resolveCommandCodeSessionFiles(process.env);
829
+ } catch (error) {
830
+ // Discovery stays strict for sync, but a provider read error must not
831
+ // suppress the rest of the status diagnostics.
832
+ commandCodeDiscoveryError = `${error?.code ? `${error.code}: ` : ""}${error?.message || String(error)}`;
833
+ }
834
+ const commandCodeInstalled = commandCodeSessionFiles.length > 0;
835
+ const lmstudioHome = resolveLmstudioHome(process.env);
836
+ const lmstudioLogFiles = await resolveLmstudioLogFiles(process.env);
837
+ const lmstudioInstalled = lmstudioLogFiles.length > 0;
838
+ const unslothDbPath = resolveUnslothDbPath(process.env);
839
+ const unslothInstalled = Boolean(unslothDbPath && fssync.existsSync(unslothDbPath));
840
+
841
+ // Devin CLI (Cognition) — passive reader of message_nodes usage metrics.
842
+ const devinDbPath = resolveDevinDbPath(process.env);
843
+ const devinInstalled = Boolean(devinDbPath && fssync.existsSync(devinDbPath));
844
+
845
+ const { resolveTraeDbPaths } = require("../lib/trae-db");
846
+ const traeDbPaths = resolveTraeDbPaths(process.env);
847
+ const traeStoragePath = resolveTraeStoragePath(process.env);
848
+ const traeInstalled = Boolean(traeStoragePath || traeDbPaths.length);
849
+ // Render path for the entitlement snapshot: read it straight from the
850
+ // Trae Local State storage.json via the shared parser. The queue stays
851
+ // token-count-only, so the status read path never depends on queue rows
852
+ // carrying plan/limits metadata.
853
+ const traeEntitlement = traeInstalled
854
+ ? readTraeEntitlementFromStorage(traeStoragePath)
855
+ : null;
856
+
857
+ // Trae SOLO CN — opt-in usage-API reader. Unlike the passive entitlement
858
+ // reader above, this source sends the locally stored sign-in JWT to TRAE's
859
+ // official API, so status surfaces the opt-in flag, the resolved storage
860
+ // path, and whether the auth blob decrypts — the three inputs a "why is my
861
+ // TRAE CN data missing" diagnosis needs.
862
+ // A resolvable default path does NOT mean the app is installed - the
863
+ // macOS/Windows resolver always derives one. Match the sync path semantics
864
+ // exactly: installed iff the storage file actually exists on disk.
865
+ const traeCnStoragePath = resolveTraeCnStoragePath({ env: process.env, home });
866
+ const traeCnInstalled = Boolean(
867
+ traeCnStoragePath && fssync.existsSync(traeCnStoragePath),
868
+ );
869
+ let traeCnAuthState = "not-signed-in";
870
+ if (traeCnInstalled) {
871
+ try {
872
+ const traeCnAuth = readTraeCnAuthFromStorage({ env: process.env, home, platform: process.platform });
873
+ if (traeCnAuth) {
874
+ extractTraeCnToken(traeCnAuth);
875
+ traeCnAuthState = "readable";
876
+ }
877
+ } catch (error) {
878
+ // Distinguish a real IO failure (unreadable) from present-but-bad
879
+ // data (malformed); neither ever carries storage contents.
880
+ traeCnAuthState = error?.code === "TRAE_CN_STORAGE_UNREADABLE" ? "unreadable" : "malformed";
881
+ }
882
+ }
883
+ const traeCnUsageOptIn = isTraeCnUsageEnabled(process.env);
884
+
885
+ // Grok Build (xAI TUI)
886
+ const grokHookState = await probeGrokHookState({ home, trackerDir, env: process.env });
887
+ const grokSessions = grokHookState.hasGrokInstall || grokHookState.sessionsDir
888
+ ? resolveGrokBuildSessions(process.env)
889
+ : [];
890
+ const grokInstalled = grokHookState.hasGrokInstall || grokSessions.length > 0;
891
+
892
+ // Hermes Agent — SQLite state.db, resolved via override / native Windows
893
+ // install / WSL auto-discovery. Surface the resolved path (UNC included) and,
894
+ // on Windows, the discovered distros so WSL users can debug "why no sync"
895
+ // without guessing the right UNC alias (#87).
896
+ const hermesPaths = resolveInstallPaths({
897
+ nativeValue: process.env.TOKENUSAGE_HERMES_HOME || (process.platform === "win32" && typeof process.env.LOCALAPPDATA === "string"
898
+ ? path.join(process.env.LOCALAPPDATA.trim(), "hermes")
899
+ : path.join(home, ".hermes")),
900
+ wslDir: ".hermes",
901
+ });
902
+ const hermesActive = formatResolvedPaths(hermesPaths, "state.db");
903
+ const hermesInstalled = hermesActive.length > 0;
904
+ const hermesPath = hermesActive.join(" | ");
905
+ const wslDistros = process.platform === "win32" && shouldProbeWsl(process.env) ? probeWslDistros() : [];
906
+
907
+ const copilotToken = readCopilotOauthToken({ home });
908
+ const copilotOtel = describeCopilotOtelStatus({ home, env: process.env });
909
+ const copilotAppDbPaths = resolveCopilotAppDbPaths(process.env);
910
+ const copilotAppExistingPaths = copilotAppDbPaths.filter((p) => {
911
+ try { return fssync.existsSync(p); } catch (_e) { return false; }
912
+ });
913
+ const copilotStorePaths = Array.from(
914
+ new Set([
915
+ ...resolveCopilotSessionStorePaths(process.env),
916
+ ...Object.keys(cursors?.copilotStore?.dbs || {}),
917
+ ]),
918
+ );
919
+ const copilotStoreExistingPaths = copilotStorePaths.filter((p) => {
920
+ try { return fssync.existsSync(p); } catch (_e) { return false; }
921
+ });
922
+ const copilotStoreDetails = [];
923
+ const copilotStoreInspectionErrors = [];
924
+ for (const storePath of copilotStoreExistingPaths) {
925
+ try {
926
+ copilotStoreDetails.push(describeCopilotSessionStoreDb(storePath));
927
+ } catch (err) {
928
+ copilotStoreInspectionErrors.push(
929
+ `${storePath}: ${err && err.message ? err.message : String(err)}`,
930
+ );
931
+ }
932
+ }
933
+ const copilotStoreCursor =
934
+ cursors?.copilotStore && typeof cursors.copilotStore === "object"
935
+ ? cursors.copilotStore
936
+ : {};
937
+ const copilotStoreDbStates =
938
+ copilotStoreCursor.dbs && typeof copilotStoreCursor.dbs === "object"
939
+ ? copilotStoreCursor.dbs
940
+ : {};
941
+ const copilotStatusPathKey = (dbPath) => {
942
+ const normalized = path.normalize(dbPath);
943
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
944
+ };
945
+ const existingCopilotStoreKeys = new Set(
946
+ copilotStoreExistingPaths.map(copilotStatusPathKey),
947
+ );
948
+ const adoptedCopilotStores = Object.entries(copilotStoreDbStates).filter(
949
+ ([, state]) => state?.adoptedAt,
950
+ );
951
+ const missingAdoptedCopilotStores = adoptedCopilotStores
952
+ .map(([dbPath]) => dbPath)
953
+ .filter((dbPath) => !existingCopilotStoreKeys.has(copilotStatusPathKey(dbPath)));
954
+ const copilotStoreDegradedReasons = [
955
+ ...missingAdoptedCopilotStores.map(
956
+ (dbPath) => `canonical store unavailable: ${dbPath}`,
957
+ ),
958
+ ...copilotStoreInspectionErrors.map(
959
+ (message) => `store inspection failed: ${message}`,
960
+ ),
961
+ ...Object.entries(copilotStoreDbStates)
962
+ .filter(([, state]) => state?.lastError)
963
+ .map(([dbPath, state]) => `${dbPath}: ${state.lastError}`),
964
+ ];
965
+ const malformedCopilotEvents = Object.values(copilotStoreDbStates).reduce(
966
+ (sum, state) => sum + Math.max(0, Number(state?.malformedEventCount) || 0),
967
+ 0,
968
+ );
969
+ if (malformedCopilotEvents > 0) {
970
+ copilotStoreDegradedReasons.push(
971
+ `${malformedCopilotEvents} event${malformedCopilotEvents === 1 ? "" : "s"} lack a valid timestamp`,
972
+ );
973
+ }
974
+ const copilotResetGapEvents = Object.values(copilotStoreDbStates).reduce(
975
+ (sum, state) => sum + Math.max(0, Number(state?.resetGapEventCount) || 0),
976
+ 0,
977
+ );
978
+ if (copilotResetGapEvents > 0) {
979
+ copilotStoreDegradedReasons.push(
980
+ `${copilotResetGapEvents} event${copilotResetGapEvents === 1 ? "" : "s"} were baselined during a legacy cursor/reset race`,
981
+ );
982
+ }
983
+ const copilotStoreCanonical =
984
+ copilotStoreCursor.active === true && adoptedCopilotStores.length > 0;
985
+ const copilotStoreDegraded = copilotStoreDegradedReasons.length > 0;
986
+ const copilotStoreStatus = {
987
+ store_paths: copilotStoreExistingPaths,
988
+ store_path: copilotStorePaths[0] || null,
989
+ store_has_file: copilotStoreExistingPaths.length > 0,
990
+ store_details: copilotStoreDetails.map((detail) => ({
991
+ path: detail.path,
992
+ schema_version: detail.schemaVersion,
993
+ event_count: detail.eventCount,
994
+ last_event_id: detail.lastEventId,
995
+ last_event_at: detail.lastEventAt,
996
+ })),
997
+ canonical: copilotStoreCanonical,
998
+ source_mode: copilotStoreCanonical
999
+ ? copilotStoreDegraded
1000
+ ? "canonical-degraded"
1001
+ : "canonical"
1002
+ : copilotStoreExistingPaths.length > 0
1003
+ ? "awaiting-adoption"
1004
+ : "legacy",
1005
+ precision: copilotStoreCanonical
1006
+ ? "exact-post-adoption; aggregate-pre-adoption"
1007
+ : "aggregate",
1008
+ coverage: copilotStoreCanonical
1009
+ ? "per-request-post-adoption; legacy-aggregate-pre-adoption"
1010
+ : "legacy-aggregate",
1011
+ malformed_event_count: malformedCopilotEvents,
1012
+ reset_gap_event_count: copilotResetGapEvents,
1013
+ degraded: copilotStoreDegraded,
1014
+ degraded_reasons: copilotStoreDegradedReasons,
1015
+ recommended_action: copilotStoreDegraded
1016
+ ? "Restore or repair the Copilot session store, then run `tokenusage sync`."
1017
+ : null,
1018
+ };
1019
+ const copilotAppStatus = {
1020
+ app_db_path: resolveCopilotAppDbPath(process.env),
1021
+ app_db_paths: copilotAppExistingPaths,
1022
+ app_db_has_file: copilotAppExistingPaths.length > 0,
1023
+ app_db_mode: copilotStoreCanonical ? "observe-only" : "legacy-writer",
1024
+ };
1025
+ const copilotLines = formatCopilotLines({
1026
+ token: copilotToken,
1027
+ otel: copilotOtel,
1028
+ sessionStore: copilotStoreStatus,
1029
+ appDb: copilotAppStatus,
1030
+ });
1031
+
1032
+ // Detect passive-mode providers exactly once — both the JSON/light path
1033
+ // and the human-readable path consume this, and each call hits 5 readdir
1034
+ // syscalls (~5–10ms cold). Memoize.
1035
+ const passiveProviders = detectPassiveProviders({
1036
+ home,
1037
+ env: process.env,
1038
+ hookStatus: {
1039
+ codex_notify: notifyConfigured,
1040
+ acode_notify: acodeConfigured,
1041
+ every_code_notify: everyCodeConfigured,
1042
+ claude: claudeHookConfigured,
1043
+ gemini: geminiHookConfigured,
1044
+ opencode_plugin: opencodePluginConfigured,
1045
+ openclaw_session_plugin: Boolean(openclawSessionPluginState?.configured),
1046
+ codebuddy: Boolean(codebuddyHookConfigured),
1047
+ workbuddy: Boolean(workbuddyHookConfigured),
1048
+ "workbuddy-ai": Boolean(workbuddyAiHookConfigured),
1049
+ grok: Boolean(grokHookState?.configured),
1050
+ },
1051
+ });
1052
+
1053
+ const deviceTokenPresence = resolveDeviceTokenPresence({
1054
+ trackerDir,
1055
+ config: config || {},
1056
+ });
1057
+
1058
+ if (opts.json || opts.light) {
1059
+ const summary = {
1060
+ version: pkg.version,
1061
+ generated_at: new Date().toISOString(),
1062
+ base_url: config?.baseUrl || null,
1063
+ device_token_set: deviceTokenPresence.set,
1064
+ queue: {
1065
+ pending_bytes: pendingBytes,
1066
+ size_bytes: queueSize,
1067
+ offset: queueState.offset || 0,
1068
+ },
1069
+ last_parse: cursors?.updatedAt || null,
1070
+ last_notify: lastNotify || null,
1071
+ last_openclaw_sync: lastOpenclawSync || null,
1072
+ last_notify_spawn: lastNotifySpawn || null,
1073
+ last_upload: lastUpload || null,
1074
+ next_upload_after: nextUpload || null,
1075
+ backoff_until: backoffUntil || null,
1076
+ last_upload_error: lastUploadError || null,
1077
+ last_sync_skipped: syncSkip?.at ? syncSkip : null,
1078
+ auto_retry: autoRetry || null,
1079
+ // Extra scan roots (#657): CODEX_HOME / CLAUDE_CONFIG_DIR of this process
1080
+ // plus config.scanRoots; `exists` false + `error` null means absent,
1081
+ // `error` set means present but unreadable.
1082
+ extra_scan_roots: extraScanRoots,
1083
+ hooks: {
1084
+ codex_notify: notifyConfigured,
1085
+ acode_notify: acodeConfigured,
1086
+ every_code_notify: everyCodeConfigured,
1087
+ claude: claudeHookConfigured,
1088
+ gemini: geminiHookConfigured,
1089
+ opencode_plugin: opencodePluginConfigured,
1090
+ openclaw_session_plugin: Boolean(openclawSessionPluginState?.configured),
1091
+ openclaw_session_plugin_conversation_access: Boolean(
1092
+ openclawSessionPluginState?.conversationAccess,
1093
+ ),
1094
+ openclaw_legacy: Boolean(openclawHookState?.configured),
1095
+ codebuddy: codebuddyInstalled ? Boolean(codebuddyHookConfigured) : null,
1096
+ workbuddy: workbuddyInstalled ? Boolean(workbuddyHookConfigured) : null,
1097
+ "workbuddy-ai": workbuddyAiInstalled ? Boolean(workbuddyAiHookConfigured) : null,
1098
+ grok: grokInstalled ? Boolean(grokHookState?.configured) : null,
1099
+ },
1100
+ providers: {
1101
+ acode: acodeInstalled
1102
+ ? { installed: true, detail: acodeActive.join(" | ") }
1103
+ : { installed: false },
1104
+ kimi_code: kimiInstalled || kimiCodeInstalled
1105
+ ? { installed: true, files: kimiWireFiles.length + kimiCodeWireFiles.length }
1106
+ : { installed: false },
1107
+ kiro_cli: kiroCliInstalled
1108
+ ? {
1109
+ installed: true,
1110
+ detail: kiroCliActive.join(" | "),
1111
+ database: kiroCliMarkers.find((m) => {
1112
+ try { return fssync.existsSync(m); } catch (_e) { return false; }
1113
+ }) || null,
1114
+ files: kiroCliFileCount,
1115
+ }
1116
+ : { installed: false },
1117
+ kiro_ide: kiroIdeInstalled
1118
+ ? { installed: true, detail: kiroIdeActive.join(" | ") }
1119
+ : { installed: false },
1120
+ claude_code: claudeCodeInstalled
1121
+ ? { installed: true, detail: claudeCodeActive.join(" | ") }
1122
+ : { installed: false },
1123
+ codebuddy: codebuddyInstalled
1124
+ ? { installed: true, files: codebuddyFiles.length }
1125
+ : { installed: false },
1126
+ workbuddy: workbuddyInstalled
1127
+ ? { installed: true, files: workbuddyFiles.length }
1128
+ : { installed: false },
1129
+ workbuddy_ai: workbuddyAiInstalled
1130
+ ? { installed: true, files: workbuddyAiFiles.length }
1131
+ : { installed: false },
1132
+ omp: ompInstalled || ompHookState.ompPresent
1133
+ ? {
1134
+ installed: true,
1135
+ files: ompFiles.length,
1136
+ notify_extension: Boolean(ompHookState.configured),
1137
+ notify_extension_path: ompHookState.extensionPath || null,
1138
+ }
1139
+ : { installed: false },
1140
+ omo: omoInstalled
1141
+ ? { installed: true, files: omoFiles.length }
1142
+ : { installed: false },
1143
+ minimax_code: minimaxCodeInstalled
1144
+ ? { installed: true, files: minimaxCodeFiles.length }
1145
+ : { installed: false },
1146
+ pi: piInstalled
1147
+ ? { installed: true, files: piFiles.length }
1148
+ : { installed: false },
1149
+ prime_agent: primeAgentInstalled
1150
+ ? { installed: true, files: primeAgentFiles.length }
1151
+ : { installed: false },
1152
+ craft: craftInstalled
1153
+ ? { installed: true, files: craftFiles.length }
1154
+ : { installed: false },
1155
+ reasonix: reasonixInstalled
1156
+ ? { installed: true, files: reasonixFiles.length }
1157
+ : { installed: false },
1158
+ muse: museInstalled
1159
+ ? { installed: true, files: museFiles.length }
1160
+ : { installed: false },
1161
+ anythingllm: anythingllmInstalled
1162
+ ? { installed: true, detail: anythingllmDbPath }
1163
+ : { installed: false },
1164
+ kilo_cli: kiloInstalled
1165
+ ? { installed: true, detail: kiloDbPath }
1166
+ : { installed: false },
1167
+ dumate: dumateInstalled
1168
+ ? { installed: true, detail: dumateDbPath }
1169
+ : { installed: false },
1170
+ mimo: mimoInstalled
1171
+ ? { installed: true, detail: mimoDbPath }
1172
+ : { installed: false },
1173
+ zcode: zcodeInstalled
1174
+ ? { installed: true, detail: zcodeDbPath }
1175
+ : { installed: false },
1176
+ qoder: qoderInstalled
1177
+ ? { installed: true, detail: summarizeQoderDetail(qoderDbPath, qoderNewPath) }
1178
+ : { installed: false },
1179
+ "qoder-cn": qoderCnInstalled
1180
+ ? { installed: true, detail: summarizeQoderDetail(qoderCnDbPath, qoderCnNewPath) }
1181
+ : { installed: false },
1182
+ "claude-science": claudeScienceInstalled
1183
+ ? { installed: true, detail: claudeScienceDbPath }
1184
+ : { installed: false },
1185
+ kilocode: kilocodeInstalled
1186
+ ? { installed: true, files: kilocodeTaskFiles.length }
1187
+ : { installed: false },
1188
+ roocode: roocodeInstalled
1189
+ ? { installed: true, files: roocodeTaskFiles.length }
1190
+ : { installed: false },
1191
+ cline: clineInstalled
1192
+ ? {
1193
+ installed: true,
1194
+ files: clineSessionFiles.length,
1195
+ ...(clineDiscoveryError ? { error: clineDiscoveryError } : {}),
1196
+ }
1197
+ : clineDiscoveryError
1198
+ ? { installed: false, error: clineDiscoveryError }
1199
+ : { installed: false },
1200
+ zed: zedInstalled ? { installed: true, detail: zedDbPath } : { installed: false },
1201
+ goose: gooseInstalled
1202
+ ? { installed: true, detail: gooseDbPath }
1203
+ : { installed: false },
1204
+ droid: droidInstalled
1205
+ ? { installed: true, files: droidSettingsFiles.length, detail: droidSessionsDir }
1206
+ : { installed: false },
1207
+ dsh: dshInstalled
1208
+ ? { installed: true, files: dshSessionFiles.length, detail: dshSessionsDir }
1209
+ : { installed: false },
1210
+ "command-code": commandCodeInstalled
1211
+ ? {
1212
+ installed: true,
1213
+ files: commandCodeSessionFiles.length,
1214
+ detail: commandCodeProjectsDir,
1215
+ }
1216
+ : commandCodeDiscoveryError
1217
+ ? { installed: false, error: commandCodeDiscoveryError }
1218
+ : { installed: false },
1219
+ lmstudio: lmstudioInstalled
1220
+ ? {
1221
+ installed: true,
1222
+ files: lmstudioLogFiles.length,
1223
+ detail: path.join(lmstudioHome, "server-logs"),
1224
+ }
1225
+ : { installed: false },
1226
+ unsloth: unslothInstalled
1227
+ ? { installed: true, detail: unslothDbPath }
1228
+ : { installed: false },
1229
+ devin: devinInstalled
1230
+ ? { installed: true, detail: devinDbPath }
1231
+ : { installed: false },
1232
+ trae: traeInstalled
1233
+ ? {
1234
+ installed: true,
1235
+ detail: traeDbPaths[0] || traeStoragePath,
1236
+ usage_databases: traeDbPaths.length,
1237
+ usage_key_source: process.env.TOKENUSAGE_TRAE_SQLCIPHER_KEY?.trim() ? "environment" : "application",
1238
+ ...(traeEntitlement ? { entitlement: traeEntitlement } : {}),
1239
+ }
1240
+ : { installed: false },
1241
+ "trae-cn": traeCnInstalled
1242
+ ? {
1243
+ installed: true,
1244
+ detail: traeCnStoragePath,
1245
+ auth: traeCnAuthState,
1246
+ usage_opt_in: traeCnUsageOptIn,
1247
+ }
1248
+ : { installed: false },
1249
+ grok_build: grokInstalled
1250
+ ? {
1251
+ installed: true,
1252
+ files: grokSessions.length,
1253
+ detail: grokHookState.configured ? "hook installed" : "detected",
1254
+ }
1255
+ : { installed: false },
1256
+ hermes: {
1257
+ installed: hermesInstalled,
1258
+ detail: hermesPath,
1259
+ },
1260
+ },
1261
+ copilot: {
1262
+ token_set: Boolean(copilotToken),
1263
+ otel_has_files: Boolean(copilotOtel.otel_has_files),
1264
+ otel_path: copilotOtel.otel_path || null,
1265
+ otel_enabled: Boolean(copilotOtel.otel_enabled),
1266
+ ...copilotStoreStatus,
1267
+ ...copilotAppStatus,
1268
+ },
1269
+ passive_mode: {
1270
+ active: isPassiveModeActive(passiveProviders),
1271
+ providers: passiveProviders,
1272
+ },
1273
+ ...(process.platform === "win32"
1274
+ ? {
1275
+ wsl_mode: getWslMode(),
1276
+ wsl_mode_invalid: isInvalidWslMode(),
1277
+ wsl_distros: wslDistros.map((d) => ({ name: d.name, version: d.version })),
1278
+ }
1279
+ : {}),
1280
+ subscriptions,
1281
+ };
1282
+
1283
+ if (opts.json) {
1284
+ process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
1285
+ return;
1286
+ }
1287
+ process.stdout.write(renderLightTable(summary) + "\n");
1288
+ return;
1289
+ }
1290
+
1291
+ process.stdout.write(
1292
+ [
1293
+ `tokenusage v${pkg.version}`,
1294
+ "Status:",
1295
+ `- Base URL: ${config?.baseUrl || "unset"}`,
1296
+ `- Device token: ${deviceTokenPresence.set ? "set" : "unset"}`,
1297
+ collectionPaused
1298
+ ? "- Collection: PAUSED (auto/notify/watch syncs skip; manual sync runs; `tokenusage resume` to re-enable)"
1299
+ : "- Collection: active",
1300
+ `- Run report: ${runReportEnabled ? "on (each sync reports a run record)" : "off"}`,
1301
+ `- Queue: ${pendingBytes} bytes pending`,
1302
+ `- Last parse: ${cursors?.updatedAt || "never"}`,
1303
+ `- Last notify: ${lastNotify || "never"}`,
1304
+ `- Last OpenClaw-triggered sync: ${lastOpenclawSync || "never"}`,
1305
+ `- Last notify-triggered sync: ${lastNotifySpawn || "never"}`,
1306
+ `- Last upload: ${lastUpload || "never"}`,
1307
+ `- Next upload after: ${nextUpload || "never"}`,
1308
+ `- Backoff until: ${backoffUntil || "never"}`,
1309
+ lastUploadError ? `- Last upload error: ${lastUploadError}` : null,
1310
+ syncSkipLine,
1311
+ autoRetryLine,
1312
+ scanRootsLine,
1313
+ `- Codex notify: ${notifyConfigured ? JSON.stringify(codexNotify) : "unset"}`,
1314
+ `- AStudio notify: ${acodeConfigured ? JSON.stringify(acodeNotify) : "unset"}`,
1315
+ `- Every Code notify: ${everyCodeConfigured ? JSON.stringify(everyCodeNotify) : "unset"}`,
1316
+ `- Claude hooks: ${claudeHookConfigured ? "set" : "unset"}`,
1317
+ claudeCodeInstalled
1318
+ ? `- Claude Code: projects found (${claudeCodeActive.join(" | ")})`
1319
+ : null,
1320
+ `- Gemini hooks: ${geminiHookConfigured ? "set" : "unset"}`,
1321
+ `- Opencode plugin: ${opencodePluginConfigured ? "set" : "unset"}`,
1322
+ `- OpenClaw session plugin: ${openclawSessionPluginState?.configured ? "set" : "unset"}`,
1323
+ `- OpenClaw session plugin conversation access: ${openclawSessionPluginState?.conversationAccess ? "set" : "unset"}`,
1324
+ `- OpenClaw hook (legacy): ${openclawHookState?.configured ? "set" : "unset"}`,
1325
+ kimiInstalled || kimiCodeInstalled
1326
+ ? `- Kimi Code: passive reader (${kimiWireFiles.length + kimiCodeWireFiles.length} wire.jsonl file${(kimiWireFiles.length + kimiCodeWireFiles.length) !== 1 ? "s" : ""} found, directories: ${kimiActive.join(" | ") || "none"})`
1327
+ : null,
1328
+ kiroCliInstalled
1329
+ ? `- Kiro CLI: passive reader (${kiroCliFileCount} session file${kiroCliFileCount !== 1 ? "s" : ""} found, SQLite ${kiroCliDbFound ? "found" : "not found"}, installs: ${kiroCliActive.join(" | ")}; missing token counts use new-text estimates at ~4 chars/token, excluding re-sent history, system context and cache usage; model-rate costs are separate from Kiro credit charges; merged under 'kiro')`
1330
+ : null,
1331
+ kiroIdeInstalled
1332
+ ? `- Kiro IDE: passive reader (${kiroIdeActive.join(" | ")})`
1333
+ : null,
1334
+ codebuddyInstalled
1335
+ ? `- CodeBuddy hooks: ${codebuddyHookConfigured ? "set" : "unset"} (${codebuddyFiles.length} usage file${codebuddyFiles.length !== 1 ? "s" : ""} found)`
1336
+ : null,
1337
+ workbuddyInstalled
1338
+ ? `- WorkBuddy hooks: ${workbuddyHookConfigured ? "set" : "unset"} (${workbuddyFiles.length} session jsonl file${workbuddyFiles.length !== 1 ? "s" : ""} found, SQLite DB ${workbuddyDbExists ? "found" : "not found"})`
1339
+ : null,
1340
+ workbuddyAiInstalled
1341
+ ? `- WorkBuddy AI hooks: ${workbuddyAiHookConfigured ? "set" : "unset"} (${workbuddyAiFiles.length} session jsonl file${workbuddyAiFiles.length !== 1 ? "s" : ""} found, SQLite DB ${workbuddyAiDbExists ? "found" : "not found"})`
1342
+ : null,
1343
+ ompInstalled || ompHookState.ompPresent
1344
+ ? `- oh-my-pi: passive reader (${ompFiles.length} session jsonl file${ompFiles.length !== 1 ? "s" : ""} found${ompHookState.configured ? ", notify extension: yes" : ", notify extension: no"})`
1345
+ : null,
1346
+ omoInstalled
1347
+ ? `- OmO: passive reader (${omoFiles.length} session jsonl file${omoFiles.length !== 1 ? "s" : ""} found)`
1348
+ : null,
1349
+ minimaxCodeInstalled
1350
+ ? `- MiniMax Code: passive reader (${minimaxCodeFiles.length} session jsonl file${minimaxCodeFiles.length !== 1 ? "s" : ""} found)`
1351
+ : null,
1352
+ piInstalled
1353
+ ? `- pi: passive reader (${piFiles.length} session jsonl file${piFiles.length !== 1 ? "s" : ""} found)`
1354
+ : null,
1355
+ primeAgentInstalled
1356
+ ? `- Prime Agent: passive reader (${primeAgentFiles.length} session jsonl file${primeAgentFiles.length !== 1 ? "s" : ""} found)`
1357
+ : null,
1358
+ craftInstalled
1359
+ ? `- Craft Agents: passive reader (${craftFiles.length} session jsonl file${craftFiles.length !== 1 ? "s" : ""} found)`
1360
+ : null,
1361
+ reasonixInstalled
1362
+ ? `- Reasonix: passive reader (${reasonixFiles.length} telemetry file${reasonixFiles.length !== 1 ? "s" : ""} found)`
1363
+ : null,
1364
+ museInstalled
1365
+ ? `- Muse Code: passive reader (${museFiles.length} session jsonl file${museFiles.length !== 1 ? "s" : ""} found)`
1366
+ : null,
1367
+ anythingllmInstalled
1368
+ ? `- AnythingLLM Desktop: passive reader (${anythingllmDbPath})`
1369
+ : null,
1370
+ kiloInstalled
1371
+ ? `- Kilo CLI: passive reader (${kiloDbPath})`
1372
+ : null,
1373
+ dumateInstalled
1374
+ ? `- DuMate: passive reader (${dumateDbPath})`
1375
+ : null,
1376
+ mimoInstalled
1377
+ ? `- Mimo: passive reader (${mimoDbPath})`
1378
+ : null,
1379
+ zcodeInstalled
1380
+ ? `- ZCode: passive reader (${zcodeDbPath})`
1381
+ : null,
1382
+ qoderInstalled
1383
+ ? `- Qoder: passive reader (${[qoderDbPath, qoderNewPath].filter(Boolean).join(" + ") || "not found"}${qoderNewInstalled && qoderActive.length > 0 ? " [legacy DB + new JSONL (both tracked)]" : ""}${qoderNewInstalled && qoderActive.length === 0 ? " [new JSONL only]" : ""})`
1384
+ : null,
1385
+ qoderCnInstalled
1386
+ ? `- Qoder CN: passive reader (${summarizeQoderDetail(qoderCnDbPath, qoderCnNewPath) || "not found"}${qoderCnNewInstalled && qoderCnActive.length > 0 ? " [legacy DB + new JSONL (both tracked)]" : ""}${qoderCnNewInstalled && qoderCnActive.length === 0 ? " [new JSONL only]" : ""})`
1387
+ : null,
1388
+ claudeScienceInstalled
1389
+ ? `- Claude Science: passive reader (${claudeScienceDbPath})`
1390
+ : null,
1391
+ opencodeInstalled
1392
+ ? `- OpenCode: passive reader (storage: ${opencodeStorageActive.join(" | ") || "not found"}, DB: ${opencodeDbActive.join(" | ") || "not found"})`
1393
+ : null,
1394
+ codeInstalled
1395
+ ? `- Every Code: sessions found (${codeActive.join(" | ")})`
1396
+ : null,
1397
+ geminiCliInstalled
1398
+ ? `- Gemini CLI: sessions found (${geminiCliActive.join(" | ")})`
1399
+ : null,
1400
+ antigravityInstalled
1401
+ ? `- Antigravity: brain found (${antigravityActive.join(" | ")})`
1402
+ : null,
1403
+ (!geminiCliInstalled && !antigravityInstalled && geminiInstalledStatus)
1404
+ ? `- Gemini CLI / Antigravity: home found (${geminiActive.join(" | ")})`
1405
+ : null,
1406
+ codexInstalledStatus
1407
+ ? `- Codex CLI: sessions found (${codexActive.join(" | ")})`
1408
+ : null,
1409
+ codexRecordOnlyWarning ? `- ⚠ ${codexRecordOnlyWarning}` : null,
1410
+ acodeInstalled
1411
+ ? `- AStudio: sessions found (${acodeActive.join(" | ")})`
1412
+ : null,
1413
+ kilocodeInstalled
1414
+ ? `- Kilo Code (VS Code extension): passive reader (${kilocodeTaskFiles.length} task${kilocodeTaskFiles.length !== 1 ? "s" : ""} across ${new Set(kilocodeTaskFiles.map((t) => t.ide)).size} IDE${new Set(kilocodeTaskFiles.map((t) => t.ide)).size !== 1 ? "s" : ""})`
1415
+ : null,
1416
+ roocodeInstalled
1417
+ ? `- Roo Code (VS Code extension): passive reader (${roocodeTaskFiles.length} task${roocodeTaskFiles.length !== 1 ? "s" : ""} across ${new Set(roocodeTaskFiles.map((t) => t.ide)).size} IDE${new Set(roocodeTaskFiles.map((t) => t.ide)).size !== 1 ? "s" : ""})`
1418
+ : null,
1419
+ clineInstalled
1420
+ ? `- Cline: passive reader (${clineSessionFiles.length} transcript${clineSessionFiles.length !== 1 ? "s" : ""} in ${clineSessionsDirCount} sessions dir${clineSessionsDirCount !== 1 ? "s" : ""})${clineDiscoveryError ? `; discovery failed (${clineDiscoveryError})` : ""}`
1421
+ : clineDiscoveryError
1422
+ ? `- Cline: discovery failed (${clineDiscoveryError})`
1423
+ : null,
1424
+ zedInstalled
1425
+ ? `- Zed Agent: passive reader (threads.db, all providers${
1426
+ zedThreadsCounted > 0
1427
+ ? `, ${zedThreadsCounted} thread${zedThreadsCounted !== 1 ? "s" : ""} counted`
1428
+ : ", no usage counted yet"
1429
+ })`
1430
+ : null,
1431
+ gooseInstalled
1432
+ ? `- Goose (Block): passive reader (sessions.db, cumulative-delta)`
1433
+ : null,
1434
+ droidInstalled
1435
+ ? `- Droid (Factory): passive reader (${droidSettingsFiles.length} session${droidSettingsFiles.length !== 1 ? "s" : ""} in ${droidSessionsDir}, cumulative-delta)`
1436
+ : null,
1437
+ dshInstalled
1438
+ ? `- DeepSeek Harness: passive reader (${dshSessionFiles.length} session${dshSessionFiles.length !== 1 ? "s" : ""} in ${dshSessionsDir})`
1439
+ : null,
1440
+ commandCodeInstalled
1441
+ ? `- Command Code: passive reader (${commandCodeSessionFiles.length} session${commandCodeSessionFiles.length !== 1 ? "s" : ""} in ${commandCodeProjectsDir})`
1442
+ : commandCodeDiscoveryError
1443
+ ? `- Command Code: discovery failed (${commandCodeDiscoveryError})`
1444
+ : null,
1445
+ lmstudioInstalled
1446
+ ? `- LM Studio: passive reader (${lmstudioLogFiles.length} log${lmstudioLogFiles.length !== 1 ? "s" : ""} in ${path.join(lmstudioHome, "server-logs")})`
1447
+ : null,
1448
+ unslothInstalled
1449
+ ? `- Unsloth Studio: passive reader (${unslothDbPath})`
1450
+ : null,
1451
+ devinInstalled
1452
+ ? `- Devin CLI: passive reader (${devinDbPath})`
1453
+ : null,
1454
+ traeInstalled
1455
+ ? traeDbPaths.length
1456
+ ? `- TRAE: local usage reader, ${traeDbPaths.length} database(s) (shared application key; optional key override)`
1457
+ : `- TRAE: plan info only, no local usage database found (${traeStoragePath})`
1458
+ : null,
1459
+ traeEntitlement
1460
+ ? `- Trae SOLO plan: ${formatTraeEntitlementLine(traeEntitlement)}`
1461
+ : null,
1462
+ traeCnInstalled
1463
+ // Installed, signed in, and one env var away from usage data is the
1464
+ // one actionable state on this line — mark it so it does not read
1465
+ // like the ~30 neutral install lines around it (#492). Every other
1466
+ // combination (opted in, or no readable auth to send) is neutral.
1467
+ ? `- ${traeCnAuthState === "readable" && !traeCnUsageOptIn ? "⚠ " : ""}Trae SOLO CN: usage sync ${traeCnUsageOptIn ? "opted in" : `off (set ${TRAE_CN_USAGE_ENV}=1 to enable)`}, auth ${traeCnAuthState} (${traeCnStoragePath})`
1468
+ : null,
1469
+ ...(() => {
1470
+ if (!hermesInstalled) return [];
1471
+ return [`- Hermes Agent: state.db found (${hermesPath})`];
1472
+ })(),
1473
+ ...(() => {
1474
+ const passive = passiveProviders.filter((p) => p.passive);
1475
+ if (passive.length === 0) return [];
1476
+ return [
1477
+ `- Passive mode: ${passive.length} provider${passive.length !== 1 ? "s" : ""} reading logs without hooks (${passive.map((p) => `${p.name}: ${p.hook_failure_reason || "hook unset"}`).join("; ")})`,
1478
+ ];
1479
+ })(),
1480
+ grokInstalled
1481
+ ? `- Grok Build (xAI): ${grokHookState.configured ? "hook installed" : "detected"} (${grokSessions.length} session${grokSessions.length !== 1 ? "s" : ""} found, hook: ${grokHookState.configured ? "yes" : "no"})`
1482
+ : null,
1483
+ ...copilotLines,
1484
+ ...(process.platform === "win32" ? (() => {
1485
+ const wslMode = getWslMode();
1486
+ const modeInvalid = isInvalidWslMode();
1487
+ const modeSuffix = modeInvalid ? ` (invalid TOKENUSAGE_WSL_MODE ignored)` : "";
1488
+ const lines = [
1489
+ `- WSL mode: ${wslMode}${modeSuffix}`,
1490
+ ];
1491
+ if (wslDistros.length > 0) {
1492
+ lines.push(` distros: ${wslDistros.map((d) => `${d.name} (v${d.version ?? "?"})`).join(", ")}`);
1493
+ }
1494
+ return lines;
1495
+ })() : []),
1496
+ ...subscriptionLines,
1497
+ "",
1498
+ ]
1499
+ .filter(Boolean)
1500
+ .join("\n"),
1501
+ );
1502
+ }
1503
+
1504
+ function formatCopilotStoreDetail(detail) {
1505
+ return `${detail.path} (schema ${detail.schema_version ?? "?"}, ${detail.event_count ?? 0} events, last id ${detail.last_event_id ?? 0}${detail.last_event_at ? ` at ${detail.last_event_at}` : ""})`;
1506
+ }
1507
+
1508
+ function formatCopilotLines({ token, otel, sessionStore, appDb }) {
1509
+ if (
1510
+ !token &&
1511
+ !otel.otel_has_files &&
1512
+ !sessionStore?.store_has_file &&
1513
+ !appDb?.app_db_has_file
1514
+ ) {
1515
+ return [];
1516
+ }
1517
+ const limitsState = token
1518
+ ? "set (via GitHub OAuth)"
1519
+ : "unset (no Copilot OAuth token found)";
1520
+ const storeDetail = (sessionStore?.store_details || [])
1521
+ .map(formatCopilotStoreDetail)
1522
+ .join(", ");
1523
+ const storeState = sessionStore?.store_has_file
1524
+ ? `${sessionStore.source_mode || "set"} (${storeDetail || (sessionStore.store_paths || []).join(", ")}; precision ${sessionStore.precision || "unknown"}; coverage ${sessionStore.coverage || "unknown"})`
1525
+ : `not found (${sessionStore?.store_path || "unknown"})`;
1526
+ const appDbState = appDb?.app_db_has_file
1527
+ ? `${appDb.app_db_mode || "set"} (${(appDb.app_db_paths || []).join(", ")})`
1528
+ : `not found (${appDb?.app_db_path || "unknown"})`;
1529
+ const otelLocation =
1530
+ otel.otel_path || otel.otel_detected_paths?.[0] || otel.otel_default_dir;
1531
+ const usageState = otel.otel_has_files
1532
+ ? `set (${otelLocation})`
1533
+ : otel.otel_enabled
1534
+ ? "enabled but no files yet"
1535
+ : "unset (OTEL export not enabled)";
1536
+ const lines = [
1537
+ `- GitHub Copilot limits: ${limitsState}`,
1538
+ `- GitHub Copilot usage (App/CLI store): ${storeState}`,
1539
+ `- GitHub Copilot usage (App DB legacy baseline): ${appDbState}`,
1540
+ `- GitHub Copilot usage (OTEL Chat/legacy CLI): ${usageState}`,
1541
+ ];
1542
+ for (const reason of sessionStore?.degraded_reasons || []) {
1543
+ lines.push(` Degraded: ${reason}`);
1544
+ }
1545
+ if (sessionStore?.recommended_action) {
1546
+ lines.push(` Action: ${sessionStore.recommended_action}`);
1547
+ }
1548
+ if (!sessionStore?.store_has_file && !otel.otel_has_files) {
1549
+ lines.push(
1550
+ " To track older Copilot CLI / Chat extension token usage, add to your shell profile:",
1551
+ " export COPILOT_OTEL_ENABLED=true",
1552
+ " export COPILOT_OTEL_EXPORTER_TYPE=file",
1553
+ ` export COPILOT_OTEL_FILE_EXPORTER_PATH="${otel.otel_default_dir}/copilot-otel-$(date +%Y%m%d).jsonl"`,
1554
+ );
1555
+ }
1556
+ return lines;
1557
+ }
1558
+
1559
+ function formatSubscriptionLine(entry = {}) {
1560
+ const tool = String(entry.tool || "");
1561
+ const provider = String(entry.provider || "");
1562
+ const product = String(entry.product || "");
1563
+ const planType = String(entry.planType || "");
1564
+ const rateLimitTier = String(entry.rateLimitTier || "");
1565
+ const toolLabel =
1566
+ tool === "codex"
1567
+ ? "Codex"
1568
+ : tool === "opencode"
1569
+ ? "OpenCode"
1570
+ : tool === "claude"
1571
+ ? "Claude Code"
1572
+ : tool;
1573
+
1574
+ if (!planType) return null;
1575
+
1576
+ if (
1577
+ tool === "claude" &&
1578
+ provider === "anthropic" &&
1579
+ product === "subscription"
1580
+ ) {
1581
+ const suffix = rateLimitTier ? ` (rate limit tier: ${rateLimitTier})` : "";
1582
+ return `- ${toolLabel} subscription: ${planType}${suffix}`;
1583
+ }
1584
+
1585
+ if (provider === "openai" && product === "chatgpt") {
1586
+ return `- ${toolLabel} ChatGPT plan: ${planType}`;
1587
+ }
1588
+
1589
+ const productLabel = product ? product.replace(/_/g, " ") : "subscription";
1590
+ return `- ${toolLabel} ${productLabel}: ${planType}`;
1591
+ }
1592
+
1593
+ function parseArgs(argv) {
1594
+ const out = {
1595
+ diagnostics: false,
1596
+ json: false,
1597
+ light: false,
1598
+ noSpinner: false,
1599
+ probeKeychain: false,
1600
+ probeKeychainDetails: false,
1601
+ };
1602
+
1603
+ for (let i = 0; i < argv.length; i++) {
1604
+ const a = argv[i];
1605
+ if (a === "--diagnostics") out.diagnostics = true;
1606
+ else if (a === "--json") out.json = true;
1607
+ else if (a === "--light") out.light = true;
1608
+ else if (a === "--no-spinner") out.noSpinner = true;
1609
+ else if (a === "--probe-keychain") out.probeKeychain = true;
1610
+ else if (a === "--probe-keychain-details") {
1611
+ out.probeKeychainDetails = true;
1612
+ out.probeKeychain = true;
1613
+ } else throw new Error(`Unknown option: ${a}`);
1614
+ }
1615
+
1616
+ return out;
1617
+ }
1618
+
1619
+ // Pure renderer: turn the structured summary into a fixed-width ASCII table.
1620
+ // "light" output is for AI agents and CI: deterministic columns, no emoji or
1621
+ // spinner side effects, easy to grep. Returns a string (caller adds trailing
1622
+ // newline).
1623
+ function renderLightTable(summary) {
1624
+ const rows = [];
1625
+ const push = (k, v) => rows.push([k, v == null || v === "" ? "—" : String(v)]);
1626
+
1627
+ push("Version", summary.version);
1628
+ push("Base URL", summary.base_url);
1629
+ push("Device token", summary.device_token_set ? "set" : "unset");
1630
+ push("Queue pending (bytes)", summary.queue.pending_bytes);
1631
+ push("Queue size (bytes)", summary.queue.size_bytes);
1632
+ push("Last parse", summary.last_parse);
1633
+ push("Last notify", summary.last_notify);
1634
+ push("Last upload", summary.last_upload);
1635
+ push("Next upload after", summary.next_upload_after);
1636
+ push("Backoff until", summary.backoff_until);
1637
+ if (summary.last_upload_error) push("Last upload error", summary.last_upload_error);
1638
+ if (summary.last_sync_skipped) {
1639
+ push(
1640
+ "Last sync skipped",
1641
+ `${summary.last_sync_skipped.at} (${summary.last_sync_skipped.reason || "unknown"})`,
1642
+ );
1643
+ }
1644
+
1645
+ for (const [name, state] of Object.entries(summary.hooks || {})) {
1646
+ push(`Hook · ${name}`, state ? "set" : "unset");
1647
+ }
1648
+
1649
+ for (const root of summary.extra_scan_roots || []) {
1650
+ const state = root.exists ? "" : (root.error ? ` (unreadable: ${root.error})` : " (missing)");
1651
+ push(`Scan root · ${root.provider}`, `${root.origin}: ${root.path}${state}`);
1652
+ }
1653
+
1654
+ for (const [name, info] of Object.entries(summary.providers || {})) {
1655
+ const detail = [];
1656
+ if (typeof info.installed === "boolean") detail.push(info.installed ? "installed" : "not installed");
1657
+ if (typeof info.files === "number") detail.push(`${info.files} file${info.files !== 1 ? "s" : ""}`);
1658
+ if (info.detail) detail.push(info.detail);
1659
+ if (info.error) detail.push(info.error);
1660
+ if (Array.isArray(info.wsl_distros) && info.wsl_distros.length) {
1661
+ detail.push(`WSL: ${info.wsl_distros.map((d) => `${d.name} (v${d.version ?? "?"})`).join(", ")}`);
1662
+ }
1663
+ push(`Provider · ${name}`, detail.length ? detail.join(", ") : "—");
1664
+ }
1665
+
1666
+ // Mirror formatCopilotLines(): stay silent for machines with no Copilot
1667
+ // signal at all instead of printing "not found" rows for everyone.
1668
+ const copilotDetected =
1669
+ summary.copilot &&
1670
+ (summary.copilot.token_set ||
1671
+ summary.copilot.otel_enabled ||
1672
+ summary.copilot.otel_has_files ||
1673
+ summary.copilot.store_has_file ||
1674
+ summary.copilot.app_db_has_file);
1675
+ if (copilotDetected) {
1676
+ push(
1677
+ "Copilot App/CLI store",
1678
+ summary.copilot.store_has_file
1679
+ ? `${summary.copilot.source_mode || "set"}: ${
1680
+ (summary.copilot.store_details || [])
1681
+ .map(formatCopilotStoreDetail)
1682
+ .join(", ") ||
1683
+ (summary.copilot.store_paths || [summary.copilot.store_path])
1684
+ .filter(Boolean)
1685
+ .join(", ")
1686
+ }`
1687
+ : `not found (${summary.copilot.store_path || "unknown"})`,
1688
+ );
1689
+ push(
1690
+ "Copilot App DB legacy baseline",
1691
+ summary.copilot.app_db_has_file
1692
+ ? `${summary.copilot.app_db_mode || "set"}: ${(summary.copilot.app_db_paths || [summary.copilot.app_db_path]).filter(Boolean).join(", ")}`
1693
+ : `not found (${summary.copilot.app_db_path || "unknown"})`,
1694
+ );
1695
+ push(
1696
+ "Copilot OTEL Chat/legacy CLI",
1697
+ summary.copilot.otel_has_files
1698
+ ? summary.copilot.otel_path || "files found"
1699
+ : summary.copilot.otel_enabled
1700
+ ? "enabled, no files"
1701
+ : "not enabled",
1702
+ );
1703
+ push("Copilot precision", summary.copilot.precision);
1704
+ push("Copilot coverage", summary.copilot.coverage);
1705
+ for (const reason of summary.copilot.degraded_reasons || []) {
1706
+ push("Copilot degraded", reason);
1707
+ }
1708
+ if (summary.copilot.recommended_action) {
1709
+ push("Copilot action", summary.copilot.recommended_action);
1710
+ }
1711
+ }
1712
+
1713
+ if (summary.passive_mode) {
1714
+ push("Passive mode active", summary.passive_mode.active ? "yes" : "no");
1715
+ for (const p of summary.passive_mode.providers || []) {
1716
+ if (p.passive) {
1717
+ push(`Passive · ${p.name}`, `hook ${p.hook_failure_reason || "missing"}, logs present`);
1718
+ }
1719
+ }
1720
+ }
1721
+
1722
+ const keyWidth = Math.max(...rows.map(([k]) => k.length), 8);
1723
+ const valWidth = Math.max(...rows.map(([, v]) => v.length), 8);
1724
+ const sep = `+${"-".repeat(keyWidth + 2)}+${"-".repeat(valWidth + 2)}+`;
1725
+ const lines = [sep, `| ${"Key".padEnd(keyWidth)} | ${"Value".padEnd(valWidth)} |`, sep];
1726
+ for (const [k, v] of rows) {
1727
+ lines.push(`| ${k.padEnd(keyWidth)} | ${v.padEnd(valWidth)} |`);
1728
+ }
1729
+ lines.push(sep);
1730
+ return lines.join("\n");
1731
+ }
1732
+
1733
+ async function safeStatSize(p) {
1734
+ try {
1735
+ const st = await fs.stat(p);
1736
+ return st.size || 0;
1737
+ } catch (_e) {
1738
+ return 0;
1739
+ }
1740
+ }
1741
+
1742
+ async function safeReadText(p) {
1743
+ try {
1744
+ return await fs.readFile(p, "utf8");
1745
+ } catch (_e) {
1746
+ return null;
1747
+ }
1748
+ }
1749
+
1750
+ function parseEpochMsToIso(v) {
1751
+ const ms = Number(v);
1752
+ if (!Number.isFinite(ms) || ms <= 0) return null;
1753
+ const d = new Date(ms);
1754
+ if (Number.isNaN(d.getTime())) return null;
1755
+ return d.toISOString();
1756
+ }
1757
+
1758
+ module.exports = { cmdStatus, summarizeQoderDetail };