tokenusage-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +22 -0
- package/README.md +94 -0
- package/THIRD_PARTY_NOTICES.md +140 -0
- package/bin/tokenusage.js +69 -0
- package/package.json +59 -0
- package/src/cli.js +134 -0
- package/src/commands/device-login.js +205 -0
- package/src/commands/diagnostics.js +38 -0
- package/src/commands/doctor.js +110 -0
- package/src/commands/init.js +2436 -0
- package/src/commands/sessions.js +29 -0
- package/src/commands/status.js +1747 -0
- package/src/commands/sync.js +7934 -0
- package/src/commands/uninstall.js +312 -0
- package/src/lib/account-usage-dedup.js +267 -0
- package/src/lib/antigravity-paths.js +48 -0
- package/src/lib/ark-agent-plan-limits.js +438 -0
- package/src/lib/ark-coding-plan-limits.js +537 -0
- package/src/lib/async-queue-reader.js +138 -0
- package/src/lib/atomic-json.js +27 -0
- package/src/lib/bearer-token.js +11 -0
- package/src/lib/categorizer-utils.js +232 -0
- package/src/lib/claude-categorizer.js +1343 -0
- package/src/lib/claude-config.js +279 -0
- package/src/lib/claude-user-identity.js +56 -0
- package/src/lib/cli-ui.js +179 -0
- package/src/lib/cloud-account.js +541 -0
- package/src/lib/cloud-device-token.js +141 -0
- package/src/lib/cloud-sync-prefs.js +14 -0
- package/src/lib/cloud-usage-reset.js +115 -0
- package/src/lib/codex-config.js +595 -0
- package/src/lib/codex-context-breakdown.js +806 -0
- package/src/lib/codex-model-attribution.js +128 -0
- package/src/lib/codex-rollout-parser.js +1471 -0
- package/src/lib/codex-service-tier.js +49 -0
- package/src/lib/codex-token-refresh.js +140 -0
- package/src/lib/codex-token-usage.js +195 -0
- package/src/lib/codex-usage-record.js +195 -0
- package/src/lib/command-runner.js +313 -0
- package/src/lib/commandcode-limits.js +317 -0
- package/src/lib/context-health.js +124 -0
- package/src/lib/cursor-config.js +605 -0
- package/src/lib/cursor-store.js +1918 -0
- package/src/lib/debug-flags.js +7 -0
- package/src/lib/devin-limits.js +249 -0
- package/src/lib/devin-usage.js +212 -0
- package/src/lib/diagnostics.js +383 -0
- package/src/lib/doctor.js +385 -0
- package/src/lib/dumate.js +95 -0
- package/src/lib/fs.js +455 -0
- package/src/lib/function-url.js +14 -0
- package/src/lib/gemini-config.js +291 -0
- package/src/lib/git-outcomes.js +243 -0
- package/src/lib/grok-context-breakdown.js +890 -0
- package/src/lib/grok-hook.js +360 -0
- package/src/lib/grok-limits.js +865 -0
- package/src/lib/grok-usage.js +98 -0
- package/src/lib/heatmap-compact.js +114 -0
- package/src/lib/ingest-sanitize.js +41 -0
- package/src/lib/init-flow.js +42 -0
- package/src/lib/install-resolver.js +170 -0
- package/src/lib/jsonl-lines.js +134 -0
- package/src/lib/kimi-model-repair.js +173 -0
- package/src/lib/kimi-profile.js +61 -0
- package/src/lib/kimi-session.js +216 -0
- package/src/lib/local-api.js +3588 -0
- package/src/lib/machine-id.js +238 -0
- package/src/lib/multi-install-parser.js +113 -0
- package/src/lib/notify-command.js +38 -0
- package/src/lib/omp-hook.js +589 -0
- package/src/lib/openclaw-cli.js +104 -0
- package/src/lib/openclaw-hook.js +375 -0
- package/src/lib/openclaw-session-plugin.js +560 -0
- package/src/lib/opencode-config.js +121 -0
- package/src/lib/opencode-go-limits.js +807 -0
- package/src/lib/outcomes-engine.js +253 -0
- package/src/lib/passive-mode.js +219 -0
- package/src/lib/pet-packages.js +722 -0
- package/src/lib/pricing/curated-overrides.json +822 -0
- package/src/lib/pricing/index.js +379 -0
- package/src/lib/pricing/litellm-fetcher.js +172 -0
- package/src/lib/pricing/matcher.js +456 -0
- package/src/lib/pricing/seed-snapshot.json +1 -0
- package/src/lib/progress.js +76 -0
- package/src/lib/project-usage-purge.js +117 -0
- package/src/lib/prompt.js +24 -0
- package/src/lib/provider-status.js +104 -0
- package/src/lib/proxy-env.js +489 -0
- package/src/lib/proxy-settings.js +163 -0
- package/src/lib/qoder-cn-cli-limits.js +119 -0
- package/src/lib/qoder-limits.js +880 -0
- package/src/lib/quiet-warnings.js +26 -0
- package/src/lib/rollout.js +25966 -0
- package/src/lib/runtime-config.js +259 -0
- package/src/lib/scan-roots.js +277 -0
- package/src/lib/sentry.js +231 -0
- package/src/lib/session-analytics.js +2972 -0
- package/src/lib/session-performance.js +237 -0
- package/src/lib/session-upload.js +379 -0
- package/src/lib/skill-usage.js +267 -0
- package/src/lib/skills-manager.js +1591 -0
- package/src/lib/source-metadata.js +48 -0
- package/src/lib/sqlite-reader.js +215 -0
- package/src/lib/star-cta.js +73 -0
- package/src/lib/subscription-manager.js +293 -0
- package/src/lib/subscriptions.js +508 -0
- package/src/lib/telemetry.js +193 -0
- package/src/lib/tracker-paths.js +16 -0
- package/src/lib/trae-cn-config.js +548 -0
- package/src/lib/trae-db.js +127 -0
- package/src/lib/trae-snapshot.js +230 -0
- package/src/lib/trae-sqlite.js +143 -0
- package/src/lib/trae-usage.js +121 -0
- package/src/lib/upload-queue.js +134 -0
- package/src/lib/upload-throttle.js +171 -0
- package/src/lib/usage-limits.js +4552 -0
- package/src/lib/wrapped-aggregator.js +236 -0
- package/src/lib/wsl-probe.js +281 -0
- package/src/lib/zcode-limits.js +1172 -0
- package/src/lib/zcode-reset-credits.js +66 -0
- package/test/cli-smoke.test.js +53 -0
- package/test/ingest-sanitize.test.js +162 -0
- package/test/quiet-warnings.test.js +53 -0
- package/test/session-upload.test.js +427 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wrapped aggregator — turns a list of queue.jsonl rows into a year-end
|
|
5
|
+
* summary suitable for the `tracker wrapped` CLI command and the
|
|
6
|
+
* /wrapped dashboard page.
|
|
7
|
+
*
|
|
8
|
+
* Input rows: { source, model, hour_start, input_tokens, cached_input_tokens,
|
|
9
|
+
* cache_creation_input_tokens, output_tokens,
|
|
10
|
+
* reasoning_output_tokens, total_tokens, conversation_count, ... }
|
|
11
|
+
*
|
|
12
|
+
* Output is a plain object (JSON-serializable) — no UI or stringification
|
|
13
|
+
* concerns leak in here so the same aggregator powers the CLI and the
|
|
14
|
+
* React Wrapped page.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// Lazy require to avoid loading the full local-api module (and its pricing
|
|
18
|
+
// tables) until rows are actually aggregated. local-api.js itself requires
|
|
19
|
+
// this module lazily inside a handler, so there is no top-level cycle either
|
|
20
|
+
// way — but keeping this lazy preserves wrapped-aggregator as a light import.
|
|
21
|
+
function normalizeQueueRow(row) {
|
|
22
|
+
return require("./local-api").normalizeQueueRow(row);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function isFiniteNumber(n) {
|
|
26
|
+
return typeof n === "number" && Number.isFinite(n);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function rowTokens(row) {
|
|
30
|
+
return isFiniteNumber(row.billable_total_tokens)
|
|
31
|
+
? row.billable_total_tokens
|
|
32
|
+
: isFiniteNumber(row.total_tokens)
|
|
33
|
+
? row.total_tokens
|
|
34
|
+
: 0;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function rowDay(row) {
|
|
38
|
+
// hour_start is ISO 8601 UTC. Slice to YYYY-MM-DD.
|
|
39
|
+
return typeof row.hour_start === "string" ? row.hour_start.slice(0, 10) : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function rowYear(row) {
|
|
43
|
+
const d = rowDay(row);
|
|
44
|
+
if (!d) return null;
|
|
45
|
+
return Number(d.slice(0, 4));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isoHour(row) {
|
|
49
|
+
// "2026-04-05T14:30:00.000Z" → 14
|
|
50
|
+
if (typeof row.hour_start !== "string") return null;
|
|
51
|
+
const m = /T(\d{2}):/.exec(row.hour_start);
|
|
52
|
+
return m ? Number(m[1]) : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function topByValue(map, n) {
|
|
56
|
+
return Array.from(map.entries())
|
|
57
|
+
.sort((a, b) => b[1] - a[1])
|
|
58
|
+
.slice(0, n);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Compute a year-end Wrapped summary from queue rows.
|
|
63
|
+
*
|
|
64
|
+
* @param {Array} rows — Array of queue.jsonl objects.
|
|
65
|
+
* @param {Object} [opts]
|
|
66
|
+
* @param {number} [opts.year] — Restrict to a single calendar year (UTC).
|
|
67
|
+
* Defaults to the most-recent year present.
|
|
68
|
+
* @returns {Object} Wrapped summary.
|
|
69
|
+
*/
|
|
70
|
+
function aggregateWrapped(rows, opts = {}) {
|
|
71
|
+
// queue.jsonl is append-only: each sync re-emits the cumulative totals for
|
|
72
|
+
// every touched (source, model, hour_start). Naively summing every row
|
|
73
|
+
// double-counts every previously synced bucket. Keep only the latest entry
|
|
74
|
+
// per tuple — same dedup rule that local-api.js readQueueData enforces for
|
|
75
|
+
// the dashboard. This makes `tracker wrapped` totals match what the
|
|
76
|
+
// /wrapped dashboard page shows.
|
|
77
|
+
const dedup = new Map();
|
|
78
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
79
|
+
if (!row || typeof row !== "object") continue;
|
|
80
|
+
const key = `${row.source || ""}|${row.model || ""}|${row.hour_start || ""}`;
|
|
81
|
+
// Apply the same legacy-row corrections (codex inclusive-input, cursor
|
|
82
|
+
// billable=0) as local-api.js readQueueData so `tracker wrapped` matches
|
|
83
|
+
// the dashboard for identical data.
|
|
84
|
+
dedup.set(key, normalizeQueueRow(row));
|
|
85
|
+
}
|
|
86
|
+
const all = Array.from(dedup.values());
|
|
87
|
+
|
|
88
|
+
// Decide year to summarize. Prefer caller's year; otherwise the most
|
|
89
|
+
// recent year that has data — which during a sync rollover may be the
|
|
90
|
+
// current year (even if it has only a week of data).
|
|
91
|
+
let year = isFiniteNumber(opts.year) ? Math.floor(opts.year) : null;
|
|
92
|
+
if (year == null) {
|
|
93
|
+
let latest = null;
|
|
94
|
+
for (const r of all) {
|
|
95
|
+
const y = rowYear(r);
|
|
96
|
+
if (y != null && (latest == null || y > latest)) latest = y;
|
|
97
|
+
}
|
|
98
|
+
year = latest ?? new Date().getUTCFullYear();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const filtered = all.filter((r) => rowYear(r) === year);
|
|
102
|
+
|
|
103
|
+
if (filtered.length === 0) {
|
|
104
|
+
return {
|
|
105
|
+
year,
|
|
106
|
+
range: { from: null, to: null },
|
|
107
|
+
totals: { tokens: 0, conversations: 0, sources: 0, models: 0, active_days: 0 },
|
|
108
|
+
top: { sources: [], models: [], days: [] },
|
|
109
|
+
peak_hour: null,
|
|
110
|
+
longest_streak: { days: 0, from: null, to: null },
|
|
111
|
+
highlights: [],
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Group: source, model, day, hour-of-day
|
|
116
|
+
const tokensBySource = new Map();
|
|
117
|
+
const tokensByModel = new Map();
|
|
118
|
+
const tokensByDay = new Map();
|
|
119
|
+
const tokensByHourOfDay = new Map();
|
|
120
|
+
let totalTokens = 0;
|
|
121
|
+
let totalConvs = 0;
|
|
122
|
+
let earliest = null;
|
|
123
|
+
let latest = null;
|
|
124
|
+
|
|
125
|
+
for (const row of filtered) {
|
|
126
|
+
const t = rowTokens(row);
|
|
127
|
+
totalTokens += t;
|
|
128
|
+
if (isFiniteNumber(row.conversation_count)) totalConvs += row.conversation_count;
|
|
129
|
+
if (row.source) tokensBySource.set(row.source, (tokensBySource.get(row.source) || 0) + t);
|
|
130
|
+
if (row.model) tokensByModel.set(row.model, (tokensByModel.get(row.model) || 0) + t);
|
|
131
|
+
const day = rowDay(row);
|
|
132
|
+
if (day) tokensByDay.set(day, (tokensByDay.get(day) || 0) + t);
|
|
133
|
+
const h = isoHour(row);
|
|
134
|
+
if (h != null) tokensByHourOfDay.set(h, (tokensByHourOfDay.get(h) || 0) + t);
|
|
135
|
+
if (row.hour_start) {
|
|
136
|
+
if (!earliest || row.hour_start < earliest) earliest = row.hour_start;
|
|
137
|
+
if (!latest || row.hour_start > latest) latest = row.hour_start;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Longest consecutive day streak among days with non-zero tokens.
|
|
142
|
+
const activeDays = Array.from(tokensByDay.keys()).sort();
|
|
143
|
+
let longestStreak = { days: 0, from: null, to: null };
|
|
144
|
+
if (activeDays.length > 0) {
|
|
145
|
+
let runStart = activeDays[0];
|
|
146
|
+
let runPrev = activeDays[0];
|
|
147
|
+
let runLen = 1;
|
|
148
|
+
const stepDay = (iso, delta) => {
|
|
149
|
+
const dt = new Date(iso + "T00:00:00Z");
|
|
150
|
+
dt.setUTCDate(dt.getUTCDate() + delta);
|
|
151
|
+
return dt.toISOString().slice(0, 10);
|
|
152
|
+
};
|
|
153
|
+
longestStreak = { days: 1, from: runStart, to: runStart };
|
|
154
|
+
for (let i = 1; i < activeDays.length; i++) {
|
|
155
|
+
const day = activeDays[i];
|
|
156
|
+
if (day === stepDay(runPrev, 1)) {
|
|
157
|
+
runLen++;
|
|
158
|
+
runPrev = day;
|
|
159
|
+
} else {
|
|
160
|
+
runStart = day;
|
|
161
|
+
runPrev = day;
|
|
162
|
+
runLen = 1;
|
|
163
|
+
}
|
|
164
|
+
if (runLen > longestStreak.days) {
|
|
165
|
+
longestStreak = { days: runLen, from: runStart, to: runPrev };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Peak hour-of-day (UTC).
|
|
171
|
+
let peakHour = null;
|
|
172
|
+
if (tokensByHourOfDay.size > 0) {
|
|
173
|
+
const top = topByValue(tokensByHourOfDay, 1)[0];
|
|
174
|
+
peakHour = { hour: top[0], tokens: top[1] };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const topSources = topByValue(tokensBySource, 5).map(([source, tokens]) => ({
|
|
178
|
+
source,
|
|
179
|
+
tokens,
|
|
180
|
+
share: totalTokens > 0 ? tokens / totalTokens : 0,
|
|
181
|
+
}));
|
|
182
|
+
const topModels = topByValue(tokensByModel, 5).map(([model, tokens]) => ({
|
|
183
|
+
model,
|
|
184
|
+
tokens,
|
|
185
|
+
share: totalTokens > 0 ? tokens / totalTokens : 0,
|
|
186
|
+
}));
|
|
187
|
+
const topDays = topByValue(tokensByDay, 5).map(([day, tokens]) => ({ day, tokens }));
|
|
188
|
+
|
|
189
|
+
// Highlights — short, share-friendly one-liners derived from the numbers.
|
|
190
|
+
const highlights = [];
|
|
191
|
+
if (topModels.length > 0) {
|
|
192
|
+
const m = topModels[0];
|
|
193
|
+
highlights.push(`${m.model} powered ${(m.share * 100).toFixed(0)}% of your year.`);
|
|
194
|
+
}
|
|
195
|
+
if (topDays.length > 0) {
|
|
196
|
+
const d = topDays[0];
|
|
197
|
+
highlights.push(`Your busiest day was ${d.day} (${formatCompact(d.tokens)} tokens).`);
|
|
198
|
+
}
|
|
199
|
+
if (peakHour) {
|
|
200
|
+
highlights.push(`You hit peak flow around ${String(peakHour.hour).padStart(2, "0")}:00 UTC.`);
|
|
201
|
+
}
|
|
202
|
+
if (longestStreak.days >= 2) {
|
|
203
|
+
highlights.push(`Longest streak: ${longestStreak.days} consecutive days of coding with AI.`);
|
|
204
|
+
}
|
|
205
|
+
if (tokensBySource.size >= 4) {
|
|
206
|
+
highlights.push(`You touched ${tokensBySource.size} different AI tools — that's range.`);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
year,
|
|
211
|
+
range: { from: earliest, to: latest },
|
|
212
|
+
totals: {
|
|
213
|
+
tokens: totalTokens,
|
|
214
|
+
conversations: totalConvs,
|
|
215
|
+
sources: tokensBySource.size,
|
|
216
|
+
models: tokensByModel.size,
|
|
217
|
+
active_days: activeDays.length,
|
|
218
|
+
},
|
|
219
|
+
top: { sources: topSources, models: topModels, days: topDays },
|
|
220
|
+
peak_hour: peakHour,
|
|
221
|
+
longest_streak: longestStreak,
|
|
222
|
+
highlights,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function formatCompact(n) {
|
|
227
|
+
if (!Number.isFinite(n)) return "0";
|
|
228
|
+
const abs = Math.abs(n);
|
|
229
|
+
if (abs >= 1e12) return (n / 1e12).toFixed(2).replace(/\.?0+$/, "") + "T";
|
|
230
|
+
if (abs >= 1e9) return (n / 1e9).toFixed(2).replace(/\.?0+$/, "") + "B";
|
|
231
|
+
if (abs >= 1e6) return (n / 1e6).toFixed(2).replace(/\.?0+$/, "") + "M";
|
|
232
|
+
if (abs >= 1e3) return (n / 1e3).toFixed(2).replace(/\.?0+$/, "") + "K";
|
|
233
|
+
return String(Math.round(n));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
module.exports = { aggregateWrapped, formatCompact };
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
const fssync = require("node:fs");
|
|
2
|
+
const path = require("node:path");
|
|
3
|
+
|
|
4
|
+
const DEFAULT_EXEC_OPTS = { timeout: 15000, windowsHide: true, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] };
|
|
5
|
+
|
|
6
|
+
let _cachedDistros = null;
|
|
7
|
+
let _cachedDistrosError = null;
|
|
8
|
+
const _cachedWslUsers = new Map();
|
|
9
|
+
const _cachedWslUserErrors = new Map();
|
|
10
|
+
|
|
11
|
+
function resetWslProbeCache() {
|
|
12
|
+
_cachedDistros = null;
|
|
13
|
+
_cachedDistrosError = null;
|
|
14
|
+
_cachedWslUsers.clear();
|
|
15
|
+
_cachedWslUserErrors.clear();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const WSL_MODES = new Set([
|
|
19
|
+
"wsl-first",
|
|
20
|
+
"native-first",
|
|
21
|
+
"wsl-only",
|
|
22
|
+
"native-only",
|
|
23
|
+
"both",
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
function defaultRunWsl(args, { utf16 = false } = {}) {
|
|
27
|
+
const { execFileSync } = require("node:child_process");
|
|
28
|
+
const buf = execFileSync("wsl.exe", args, DEFAULT_EXEC_OPTS);
|
|
29
|
+
return utf16 ? buf.toString("utf16le") : buf.toString("utf8");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function cleanWslOutput(raw) {
|
|
33
|
+
return raw.replace(/\0/g, "").replace(/\uFEFF/g, "").trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parseWslListVerbose(raw) {
|
|
37
|
+
if (typeof raw !== "string") return [];
|
|
38
|
+
const distros = [];
|
|
39
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
40
|
+
const clean = cleanWslOutput(line);
|
|
41
|
+
if (!clean) continue;
|
|
42
|
+
const cells = clean.split(/\s+/);
|
|
43
|
+
let isDefault = false;
|
|
44
|
+
let idx = 0;
|
|
45
|
+
if (cells[0] === "*") {
|
|
46
|
+
isDefault = true;
|
|
47
|
+
idx = 1;
|
|
48
|
+
}
|
|
49
|
+
const name = cells[idx];
|
|
50
|
+
if (!name || name === "NAME") continue;
|
|
51
|
+
const version = parseInt(cells[cells.length - 1], 10);
|
|
52
|
+
distros.push({ name, version: Number.isFinite(version) ? version : null, isDefault });
|
|
53
|
+
}
|
|
54
|
+
return distros;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function probeWslDistros(deps = {}) {
|
|
58
|
+
const strict = deps.strict === true;
|
|
59
|
+
const hasDeps = Object.keys(deps).some((key) => key !== "strict");
|
|
60
|
+
// Legacy callers retain their fail-safe cache. Strict observers may reuse
|
|
61
|
+
// successful empty results, but must retry a failure cached by any caller.
|
|
62
|
+
if (!hasDeps && _cachedDistros && (!strict || !_cachedDistrosError)) return _cachedDistros;
|
|
63
|
+
const runWsl = deps.runWsl || defaultRunWsl;
|
|
64
|
+
let raw;
|
|
65
|
+
try {
|
|
66
|
+
raw = runWsl(["-l", "-v"], { utf16: true });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
let confirmedEmpty = false;
|
|
69
|
+
if (
|
|
70
|
+
strict && Number.isInteger(error?.status) && error.status !== 0 &&
|
|
71
|
+
error.signal == null && (error.code == null || error.code === error.status)
|
|
72
|
+
) {
|
|
73
|
+
// Some WSL builds exit nonzero for an empty verbose list. Confirm that
|
|
74
|
+
// case with a successful empty quiet list, not localized diagnostic text.
|
|
75
|
+
// Transport/permission/signal failures must never reach this fallback.
|
|
76
|
+
try {
|
|
77
|
+
const quiet = runWsl(["-l", "-q"], { utf16: true });
|
|
78
|
+
confirmedEmpty = typeof quiet === "string" && cleanWslOutput(quiet) === "";
|
|
79
|
+
} catch (_quietError) { }
|
|
80
|
+
}
|
|
81
|
+
if (!hasDeps) {
|
|
82
|
+
_cachedDistros = [];
|
|
83
|
+
_cachedDistrosError = confirmedEmpty ? null : error;
|
|
84
|
+
}
|
|
85
|
+
// ENOENT confirms wsl.exe is not installed. A failed invocation of an
|
|
86
|
+
// existing executable is not evidence of an empty distro list.
|
|
87
|
+
if (strict && error?.code !== "ENOENT" && !confirmedEmpty) throw error;
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
const distros = parseWslListVerbose(raw);
|
|
91
|
+
const sorted = distros.sort((a, b) => (b.isDefault ? 1 : 0) - (a.isDefault ? 1 : 0));
|
|
92
|
+
if (!hasDeps) {
|
|
93
|
+
_cachedDistros = sorted;
|
|
94
|
+
_cachedDistrosError = null;
|
|
95
|
+
}
|
|
96
|
+
return sorted;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function normalizeWslMode(value) {
|
|
100
|
+
return String(value ?? "")
|
|
101
|
+
.trim()
|
|
102
|
+
.toLowerCase()
|
|
103
|
+
.replaceAll("_", "-");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function getWslMode(env = process.env) {
|
|
107
|
+
const raw = normalizeWslMode(env.TOKENUSAGE_WSL_MODE);
|
|
108
|
+
return WSL_MODES.has(raw) ? raw : "wsl-first";
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function isInvalidWslMode(env = process.env) {
|
|
112
|
+
const value = env.TOKENUSAGE_WSL_MODE;
|
|
113
|
+
if (value == null || String(value).trim() === "") return false;
|
|
114
|
+
return !WSL_MODES.has(normalizeWslMode(value));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function shouldProbeWsl(env = process.env) {
|
|
118
|
+
return getWslMode(env) !== "native-only";
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function shouldProbeNative(env = process.env) {
|
|
122
|
+
return getWslMode(env) !== "wsl-only";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function pickWin32Path({
|
|
126
|
+
wslValue,
|
|
127
|
+
nativeValue,
|
|
128
|
+
env = process.env,
|
|
129
|
+
platform = process.platform,
|
|
130
|
+
}) {
|
|
131
|
+
if (platform !== "win32") return null;
|
|
132
|
+
|
|
133
|
+
const mode = getWslMode(env);
|
|
134
|
+
|
|
135
|
+
if (mode === "both") return wslValue ?? nativeValue ?? null;
|
|
136
|
+
if (mode === "wsl-only") return wslValue ?? null;
|
|
137
|
+
if (mode === "native-only") return nativeValue ?? null;
|
|
138
|
+
if (mode === "native-first") return nativeValue ?? wslValue ?? null;
|
|
139
|
+
|
|
140
|
+
return wslValue ?? nativeValue ?? null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function resolveAllWin32Paths({
|
|
144
|
+
nativeValue,
|
|
145
|
+
wslValue,
|
|
146
|
+
env = process.env,
|
|
147
|
+
platform = process.platform,
|
|
148
|
+
}) {
|
|
149
|
+
if (platform !== "win32") return { native: null, wsl: null };
|
|
150
|
+
|
|
151
|
+
const mode = getWslMode(env);
|
|
152
|
+
|
|
153
|
+
if (mode === "both") {
|
|
154
|
+
return { native: nativeValue ?? null, wsl: wslValue ?? null };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const single = pickWin32Path({ wslValue, nativeValue, env, platform });
|
|
158
|
+
return { native: single, wsl: null };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function lookupWslUser(distroName, runWsl, useCache, strict = false) {
|
|
162
|
+
if (useCache && _cachedWslUsers.has(distroName) && (!strict || !_cachedWslUserErrors.has(distroName))) {
|
|
163
|
+
return _cachedWslUsers.get(distroName);
|
|
164
|
+
}
|
|
165
|
+
let user = "";
|
|
166
|
+
let error = null;
|
|
167
|
+
try {
|
|
168
|
+
user = String(runWsl(["-d", distroName, "-e", "whoami"], { utf16: false }) || "").trim();
|
|
169
|
+
if (!user) error = Object.assign(new Error("WSL identity probe returned no user"), { code: "EWSLIDENTITY" });
|
|
170
|
+
} catch (cause) { error = cause; }
|
|
171
|
+
if (useCache) {
|
|
172
|
+
_cachedWslUsers.set(distroName, user);
|
|
173
|
+
if (error) _cachedWslUserErrors.set(distroName, error);
|
|
174
|
+
else _cachedWslUserErrors.delete(distroName);
|
|
175
|
+
}
|
|
176
|
+
if (strict && error) throw error;
|
|
177
|
+
return user;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function discoverWslHome(providerDir, deps = {}) {
|
|
181
|
+
if (!shouldProbeWsl(deps.env)) return null;
|
|
182
|
+
|
|
183
|
+
const runWsl = deps.runWsl || defaultRunWsl;
|
|
184
|
+
const existsSync = deps.existsSync || fssync.existsSync;
|
|
185
|
+
const strict = deps.strict === true;
|
|
186
|
+
const distros = deps.runWsl
|
|
187
|
+
? probeWslDistros({ runWsl: deps.runWsl, strict })
|
|
188
|
+
: probeWslDistros(strict ? { strict } : undefined);
|
|
189
|
+
const useCache = !deps.runWsl;
|
|
190
|
+
for (const distro of distros) {
|
|
191
|
+
const user = lookupWslUser(distro.name, runWsl, useCache, strict);
|
|
192
|
+
if (!user) continue;
|
|
193
|
+
const roots = distro.version === 1
|
|
194
|
+
? ["\\\\wsl.localhost\\", "\\\\wsl$\\"]
|
|
195
|
+
: ["\\\\wsl$\\", "\\\\wsl.localhost\\"];
|
|
196
|
+
for (const root of roots) {
|
|
197
|
+
const candidate = `${root}${distro.name}\\home\\${user}\\${providerDir}`;
|
|
198
|
+
try {
|
|
199
|
+
if (existsSync(candidate)) return candidate;
|
|
200
|
+
} catch (_e) { }
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function isUncPath(p) {
|
|
207
|
+
return typeof p === "string" && (p.startsWith("\\\\") || p.startsWith("//"));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const WSL_UNC_ROOT_RE = /^[\\/]{2}(wsl\$|wsl\.localhost)[\\/]([^\\/]+)[\\/]/i;
|
|
211
|
+
const WINDOWS_DRIVE_PREFIX_RE = /^\/[A-Za-z]:[\\/]/;
|
|
212
|
+
|
|
213
|
+
// `\\wsl$\Ubuntu-24.04\home\u\...` -> `\\wsl$\Ubuntu-24.04\`. Returns null for
|
|
214
|
+
// native and non-WSL UNC paths.
|
|
215
|
+
function wslUncRoot(p) {
|
|
216
|
+
if (typeof p !== "string") return null;
|
|
217
|
+
const match = WSL_UNC_ROOT_RE.exec(p);
|
|
218
|
+
return match ? `\\\\${match[1]}\\${match[2]}\\` : null;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// A WSL session records its cwd as a POSIX path (`/home/u/dev/app`) while the
|
|
222
|
+
// transcript itself is read over the distro's UNC bridge. Probing that raw
|
|
223
|
+
// POSIX path from Windows resolves it against the current drive
|
|
224
|
+
// (`C:\home\u\dev\app`), which never exists — so project attribution finds no
|
|
225
|
+
// `.git`, and every WSL session ends up with a null projectKey (#374).
|
|
226
|
+
// Re-anchor the cwd onto the UNC prefix the transcript came from.
|
|
227
|
+
//
|
|
228
|
+
// The prefix is taken from the transcript path rather than re-probed, which
|
|
229
|
+
// also picks whichever of `\\wsl$` / `\\wsl.localhost` actually resolves on
|
|
230
|
+
// this machine — they are not interchangeable everywhere. Anything that isn't
|
|
231
|
+
// a POSIX cwd from a WSL-hosted file is returned untouched.
|
|
232
|
+
function mapWslCwdToUnc(cwd, transcriptPath) {
|
|
233
|
+
if (typeof cwd !== "string" || !cwd.startsWith("/")) return cwd;
|
|
234
|
+
// `new URL("file:///C:/dev/app").pathname` is "/C:/dev/app" — a leading
|
|
235
|
+
// slash, but a Windows path rather than a POSIX one. Qoder feeds exactly
|
|
236
|
+
// that shape in via `project_uri`; re-anchoring it would invent
|
|
237
|
+
// `\\wsl$\Distro\C:\dev\app`.
|
|
238
|
+
if (WINDOWS_DRIVE_PREFIX_RE.test(cwd)) return cwd;
|
|
239
|
+
const root = wslUncRoot(transcriptPath);
|
|
240
|
+
if (!root) return cwd;
|
|
241
|
+
return root + cwd.slice(1).replaceAll("/", "\\");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function snapshotSqliteDb(dbPath) {
|
|
245
|
+
const tmpRoot = fssync.mkdtempSync(
|
|
246
|
+
path.join(require("node:os").tmpdir(), "tokenusage-wsl-snap-"),
|
|
247
|
+
);
|
|
248
|
+
const target = path.join(tmpRoot, path.basename(dbPath));
|
|
249
|
+
fssync.copyFileSync(dbPath, target);
|
|
250
|
+
for (const suffix of ["-wal", "-shm", "-journal"]) {
|
|
251
|
+
const src = dbPath + suffix;
|
|
252
|
+
try {
|
|
253
|
+
if (fssync.existsSync(src)) fssync.copyFileSync(src, target + suffix);
|
|
254
|
+
} catch (_e) { }
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
path: target,
|
|
258
|
+
cleanup() {
|
|
259
|
+
try { fssync.rmSync(tmpRoot, { recursive: true, force: true }); } catch (_e) { }
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
module.exports = {
|
|
265
|
+
defaultRunWsl,
|
|
266
|
+
parseWslListVerbose,
|
|
267
|
+
probeWslDistros,
|
|
268
|
+
resetWslProbeCache,
|
|
269
|
+
discoverWslHome,
|
|
270
|
+
isUncPath,
|
|
271
|
+
wslUncRoot,
|
|
272
|
+
mapWslCwdToUnc,
|
|
273
|
+
snapshotSqliteDb,
|
|
274
|
+
getWslMode,
|
|
275
|
+
isInvalidWslMode,
|
|
276
|
+
shouldProbeWsl,
|
|
277
|
+
shouldProbeNative,
|
|
278
|
+
pickWin32Path,
|
|
279
|
+
resolveAllWin32Paths,
|
|
280
|
+
normalizeWslMode,
|
|
281
|
+
};
|