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,238 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const os = require("node:os");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
const crypto = require("node:crypto");
|
|
7
|
+
const { execFileSync } = require("node:child_process");
|
|
8
|
+
|
|
9
|
+
function resolveQueuePath() {
|
|
10
|
+
return path.join(os.homedir(), ".tokenusage", "tracker", "queue.jsonl");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Path of the purge-surviving identity seed file.
|
|
15
|
+
*
|
|
16
|
+
* `uninstall --purge` removes all of `~/.tokenusage` including config.json,
|
|
17
|
+
* which used to destroy the machineId: the reinstall minted a fresh id, the
|
|
18
|
+
* cloud created a brand-new device row, and the full history replay was
|
|
19
|
+
* double-counted next to the still-active old device (issue #176). The seed
|
|
20
|
+
* lives OUTSIDE the purged tree so a reinstall recovers the exact id the
|
|
21
|
+
* existing cloud device row is anchored to — including legacy random UUIDs
|
|
22
|
+
* that cannot be re-derived from hardware.
|
|
23
|
+
*
|
|
24
|
+
* Derived from the queue path's home when it follows the standard
|
|
25
|
+
* `<home>/.tokenusage/tracker/queue.jsonl` layout (keeps tests sandboxed in
|
|
26
|
+
* their temp homes), falling back to the real home directory otherwise.
|
|
27
|
+
*/
|
|
28
|
+
function defaultSeedPath(queuePath) {
|
|
29
|
+
const rootDir = path.dirname(path.dirname(queuePath));
|
|
30
|
+
const home = path.basename(rootDir) === ".tokenusage" ? path.dirname(rootDir) : os.homedir();
|
|
31
|
+
return path.join(home, ".config", "tokenusage", "machine-id");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isValidMachineIdString(value) {
|
|
35
|
+
return typeof value === "string" && /^[A-Za-z0-9_-]{8,128}$/.test(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readSeedFile(seedPath) {
|
|
39
|
+
try {
|
|
40
|
+
const v = fs.readFileSync(seedPath, "utf8").trim();
|
|
41
|
+
return isValidMachineIdString(v) ? v : null;
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Best-effort: keep the seed file mirroring the active machineId. */
|
|
48
|
+
function mirrorSeedFile(seedPath, machineId) {
|
|
49
|
+
if (!isValidMachineIdString(machineId)) return;
|
|
50
|
+
if (readSeedFile(seedPath) === machineId) return;
|
|
51
|
+
try {
|
|
52
|
+
fs.mkdirSync(path.dirname(seedPath), { recursive: true });
|
|
53
|
+
fs.writeFileSync(seedPath, `${machineId}\n`);
|
|
54
|
+
try { fs.chmodSync(seedPath, 0o600); } catch { /* best effort */ }
|
|
55
|
+
} catch {
|
|
56
|
+
// Read-only home etc. — identity still works, it just won't survive purge.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* dbus machine-id format: 32 lowercase hex chars. Rejects placeholder values
|
|
62
|
+
* (all-zeros / a single repeated character) that cloned images sometimes ship.
|
|
63
|
+
*/
|
|
64
|
+
function isValidLinuxMachineId(value) {
|
|
65
|
+
const v = String(value || "").trim().toLowerCase();
|
|
66
|
+
if (!/^[0-9a-f]{32}$/.test(v)) return false;
|
|
67
|
+
if (/^(.)\1+$/.test(v)) return false;
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Containers routinely share the image's (or host's) /etc/machine-id, so it is
|
|
73
|
+
* NOT a per-machine identity there — two containers on one cloud account would
|
|
74
|
+
* collapse onto one device row and their hourly upserts would overwrite each
|
|
75
|
+
* other. Treat any container signal as "no stable id available".
|
|
76
|
+
*/
|
|
77
|
+
function isLinuxContainer({ env = process.env, pathExists = fs.existsSync, readFile = fs.readFileSync } = {}) {
|
|
78
|
+
try {
|
|
79
|
+
if (env.container) return true;
|
|
80
|
+
if (pathExists("/.dockerenv") || pathExists("/run/.containerenv")) return true;
|
|
81
|
+
const cgroup = String(readFile("/proc/1/cgroup", "utf8"));
|
|
82
|
+
if (/docker|containerd|kubepods|lxc/i.test(cgroup)) return true;
|
|
83
|
+
} catch {
|
|
84
|
+
// Detection failure → assume not a container; the dbus-format validity
|
|
85
|
+
// check still filters placeholder ids.
|
|
86
|
+
}
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Hardware-derived machine fingerprint, or null when no stable OS identifier
|
|
92
|
+
* is available (containers, cloned-image placeholder ids, stripped-down hosts).
|
|
93
|
+
*
|
|
94
|
+
* Used as the machineId for FRESH generations (no seed to recover) so the id
|
|
95
|
+
* survives `uninstall --purge` even when the seed file was deleted too: the
|
|
96
|
+
* post-reinstall login lands on the SAME cloud device row and the history
|
|
97
|
+
* replay upserts onto existing rows instead of duplicating them (issue #176).
|
|
98
|
+
*
|
|
99
|
+
* Privacy: the raw OS identifier never leaves the machine — it is hashed with
|
|
100
|
+
* a fixed namespace plus the OS username (so two OS users sharing one machine
|
|
101
|
+
* and one cloud account keep separate device rows and don't clobber each
|
|
102
|
+
* other's hourly upserts).
|
|
103
|
+
*/
|
|
104
|
+
function computeStableMachineId({
|
|
105
|
+
platform = process.platform,
|
|
106
|
+
execFile = execFileSync,
|
|
107
|
+
username,
|
|
108
|
+
env = process.env,
|
|
109
|
+
pathExists = fs.existsSync,
|
|
110
|
+
readFile = fs.readFileSync,
|
|
111
|
+
} = {}) {
|
|
112
|
+
let raw = null;
|
|
113
|
+
try {
|
|
114
|
+
if (platform === "darwin") {
|
|
115
|
+
const out = execFile("/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"], {
|
|
116
|
+
encoding: "utf8",
|
|
117
|
+
timeout: 5000,
|
|
118
|
+
});
|
|
119
|
+
const m = String(out).match(/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]+)"/);
|
|
120
|
+
raw = m ? m[1] : null;
|
|
121
|
+
} else if (platform === "linux") {
|
|
122
|
+
if (isLinuxContainer({ env, pathExists, readFile })) return null;
|
|
123
|
+
for (const p of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
|
|
124
|
+
try {
|
|
125
|
+
const v = String(readFile(p, "utf8")).trim();
|
|
126
|
+
if (isValidLinuxMachineId(v)) {
|
|
127
|
+
raw = v.toLowerCase();
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
} catch {
|
|
131
|
+
// try next candidate
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
} else if (platform === "win32") {
|
|
135
|
+
const out = execFile("reg", ["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid"], {
|
|
136
|
+
encoding: "utf8",
|
|
137
|
+
timeout: 5000,
|
|
138
|
+
});
|
|
139
|
+
const m = String(out).match(/MachineGuid\s+REG_SZ\s+(\S+)/);
|
|
140
|
+
raw = m ? m[1] : null;
|
|
141
|
+
}
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
if (!raw) return null;
|
|
146
|
+
let user = username;
|
|
147
|
+
if (user == null) {
|
|
148
|
+
try {
|
|
149
|
+
user = os.userInfo().username;
|
|
150
|
+
} catch {
|
|
151
|
+
user = "";
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return crypto.createHash("sha256").update(`tokenusage-machine-v1:${raw}:${user}`).digest("hex");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Stable per-MACHINE identifier, persisted in config.json next to the queue
|
|
159
|
+
* and mirrored to a purge-surviving seed file (see defaultSeedPath).
|
|
160
|
+
*
|
|
161
|
+
* The dashboard uses this (not a per-browser localStorage id) as the cloud
|
|
162
|
+
* device_name suffix, so every browser / WKWebView / cleared-cache session on
|
|
163
|
+
* the SAME machine resolves to ONE cloud device_id. That keeps cross-device
|
|
164
|
+
* SUM aggregation correct: one physical machine = one device (its cumulative
|
|
165
|
+
* queue upserts onto a single row), while genuinely distinct machines stay
|
|
166
|
+
* distinct devices that legitimately sum. Browser-keyed ids conflated one
|
|
167
|
+
* machine into several device_ids and inflated the account-view total.
|
|
168
|
+
*
|
|
169
|
+
* Fresh-generation priority: seed file (recovers the exact id the existing
|
|
170
|
+
* cloud device row is anchored to, including legacy random UUIDs) → hardware
|
|
171
|
+
* fingerprint → random UUID. Existing config.json ids are never migrated —
|
|
172
|
+
* their cloud device row is anchored to the old value.
|
|
173
|
+
*
|
|
174
|
+
* Returns null only when the id cannot be persisted (read-only home), in which
|
|
175
|
+
* case the caller falls back to its own client id (prior behavior).
|
|
176
|
+
*/
|
|
177
|
+
function getOrCreateMachineId(queuePath, { seedPath, stableMachineId } = {}) {
|
|
178
|
+
const resolvedQueuePath = queuePath || resolveQueuePath();
|
|
179
|
+
const configPath = path.join(path.dirname(resolvedQueuePath), "config.json");
|
|
180
|
+
const resolvedSeedPath = seedPath || defaultSeedPath(resolvedQueuePath);
|
|
181
|
+
let config = {};
|
|
182
|
+
let raw = null;
|
|
183
|
+
try {
|
|
184
|
+
raw = fs.readFileSync(configPath, "utf8");
|
|
185
|
+
} catch (e) {
|
|
186
|
+
// Missing file is fine (fresh install → create config below). Any other
|
|
187
|
+
// read error means an existing config we must NOT clobber.
|
|
188
|
+
if (e && e.code !== "ENOENT") return null;
|
|
189
|
+
}
|
|
190
|
+
if (raw != null) {
|
|
191
|
+
try {
|
|
192
|
+
config = JSON.parse(raw) || {};
|
|
193
|
+
} catch {
|
|
194
|
+
// Corrupt / partially-written config.json — refuse to overwrite it (that
|
|
195
|
+
// would destroy deviceToken and other keys). Caller falls back to the
|
|
196
|
+
// per-browser client id.
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const existing = config.machineId;
|
|
201
|
+
if (typeof existing === "string" && existing.length >= 8) {
|
|
202
|
+
// Migration for installs that predate the seed file: mirror the active id
|
|
203
|
+
// so it survives a future `uninstall --purge` (issue #176).
|
|
204
|
+
mirrorSeedFile(resolvedSeedPath, existing);
|
|
205
|
+
return existing;
|
|
206
|
+
}
|
|
207
|
+
// Fresh generation: recover the previous identity from the seed first, then
|
|
208
|
+
// fall back to the hardware fingerprint, then to a random UUID.
|
|
209
|
+
let generated = readSeedFile(resolvedSeedPath);
|
|
210
|
+
if (!generated) {
|
|
211
|
+
generated = stableMachineId === undefined ? computeStableMachineId() : stableMachineId;
|
|
212
|
+
}
|
|
213
|
+
if (!generated) {
|
|
214
|
+
try {
|
|
215
|
+
generated = crypto.randomUUID();
|
|
216
|
+
} catch {
|
|
217
|
+
generated = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
config.machineId = generated;
|
|
222
|
+
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
|
223
|
+
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
|
224
|
+
try { fs.chmodSync(configPath, 0o600); } catch { /* best effort */ }
|
|
225
|
+
} catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
mirrorSeedFile(resolvedSeedPath, generated);
|
|
229
|
+
return generated;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
module.exports = {
|
|
233
|
+
getOrCreateMachineId,
|
|
234
|
+
computeStableMachineId,
|
|
235
|
+
isLinuxContainer,
|
|
236
|
+
isValidLinuxMachineId,
|
|
237
|
+
defaultSeedPath,
|
|
238
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
const wsl = require("./wsl-probe");
|
|
2
|
+
const { ensureNamespacedCursors, ensureFlatCursor } = require("./install-resolver");
|
|
3
|
+
|
|
4
|
+
function emptyResult() {
|
|
5
|
+
return { recordsProcessed: 0, eventsAggregated: 0, bucketsQueued: 0 };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
async function multiInstallParse({ paths, parserFn, providerName, cursors, getParams, onProgress, detectInstall, ...shared }) {
|
|
9
|
+
const installKeys = Object.keys(paths).filter(k => paths[k]);
|
|
10
|
+
if (installKeys.length === 0) return emptyResult();
|
|
11
|
+
const env = shared.env || process.env;
|
|
12
|
+
|
|
13
|
+
if (installKeys.length === 1) {
|
|
14
|
+
// Flatten toward the SURVIVING install's namespace, not the mode
|
|
15
|
+
// preference: under wsl-first a vanished WSL install (deleted distro,
|
|
16
|
+
// transient wsl.exe probe failure) must not donate its cursor to the
|
|
17
|
+
// remaining native install. Non-both modes park the pick in the `native`
|
|
18
|
+
// slot regardless of identity, so the slot name is unreliable — WSL
|
|
19
|
+
// installs are always addressed via UNC paths, which identifies the
|
|
20
|
+
// survivor directly.
|
|
21
|
+
const survivorKey = wsl.isUncPath(paths[installKeys[0]]) ? "wsl" : "native";
|
|
22
|
+
ensureFlatCursor(cursors, providerName, env, survivorKey);
|
|
23
|
+
return await parserFn({
|
|
24
|
+
...getParams(paths[installKeys[0]], installKeys[0]),
|
|
25
|
+
...shared,
|
|
26
|
+
cursors,
|
|
27
|
+
onProgress,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const activeKeys = resolveMigrationSeedKeys({ paths, installKeys, providerName, cursors, detectInstall });
|
|
32
|
+
const ns = ensureNamespacedCursors(cursors, providerName, activeKeys);
|
|
33
|
+
let recordsProcessed = 0;
|
|
34
|
+
let eventsAggregated = 0;
|
|
35
|
+
let bucketsQueued = 0;
|
|
36
|
+
|
|
37
|
+
for (let i = 0; i < installKeys.length; i++) {
|
|
38
|
+
const key = installKeys[i];
|
|
39
|
+
cursors[providerName] = ns[key];
|
|
40
|
+
try {
|
|
41
|
+
const result = await parserFn({
|
|
42
|
+
...getParams(paths[key], key), ...shared, cursors,
|
|
43
|
+
onProgress: wrapProgress(onProgress, key),
|
|
44
|
+
});
|
|
45
|
+
ns[key] = cursors[providerName];
|
|
46
|
+
recordsProcessed += result.recordsProcessed || 0;
|
|
47
|
+
eventsAggregated += result.eventsAggregated || 0;
|
|
48
|
+
bucketsQueued += result.bucketsQueued || 0;
|
|
49
|
+
} catch (parseErr) {
|
|
50
|
+
if (parseErr?.code !== "TOKENUSAGE_CURSOR_STORE_RETRY") {
|
|
51
|
+
cursors[providerName] = ns;
|
|
52
|
+
}
|
|
53
|
+
throw parseErr;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
cursors[providerName] = ns;
|
|
57
|
+
|
|
58
|
+
return { recordsProcessed, eventsAggregated, bucketsQueued };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Decide which namespaces the one-time flat→namespaced cursor migration seeds
|
|
62
|
+
// with the flat state. `detectInstall(installPath, flatState, installKey)` is
|
|
63
|
+
// a provider-specific probe answering "does this install's DB contain the
|
|
64
|
+
// flat cursor's session ids?". Only when EXACTLY ONE install matches do we
|
|
65
|
+
// know who owned the flat cursor — the other namespace then starts empty so
|
|
66
|
+
// its full history backfills. No probe, no match, multiple matches, or a
|
|
67
|
+
// probe error all fall back to seeding every namespace: an install re-parsed
|
|
68
|
+
// without its dedup state would double-count its entire history, and a
|
|
69
|
+
// bounded backfill gap is the cheaper failure.
|
|
70
|
+
function resolveMigrationSeedKeys({ paths, installKeys, providerName, cursors, detectInstall }) {
|
|
71
|
+
if (typeof detectInstall !== "function") return installKeys;
|
|
72
|
+
const state = cursors[providerName] && typeof cursors[providerName] === "object" ? cursors[providerName] : {};
|
|
73
|
+
const isFlat = state.native === undefined && state.wsl === undefined;
|
|
74
|
+
if (!isFlat || Object.keys(state).length === 0) return installKeys;
|
|
75
|
+
|
|
76
|
+
const hits = [];
|
|
77
|
+
for (const key of installKeys) {
|
|
78
|
+
let owns = false;
|
|
79
|
+
try {
|
|
80
|
+
owns = detectInstall(paths[key], state, key) === true;
|
|
81
|
+
} catch (_e) { }
|
|
82
|
+
if (owns) hits.push(key);
|
|
83
|
+
}
|
|
84
|
+
return hits.length === 1 ? hits : installKeys;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function wrapProgress(onProgress, installKey) {
|
|
88
|
+
if (!onProgress) return undefined;
|
|
89
|
+
return (p) => onProgress({ ...p, install: installKey });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function mergeBothFileSources({ resolveFiles, env }) {
|
|
93
|
+
const isBoth = process.platform === "win32" && wsl.getWslMode(env) === "both";
|
|
94
|
+
if (!isBoth) {
|
|
95
|
+
const files = resolveFiles(env);
|
|
96
|
+
return files;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const nativeEnv = { ...env, TOKENUSAGE_WSL_MODE: "native-only" };
|
|
100
|
+
const wslEnv = { ...env, TOKENUSAGE_WSL_MODE: "wsl-only" };
|
|
101
|
+
|
|
102
|
+
const nativeFiles = resolveFiles(nativeEnv);
|
|
103
|
+
const wslFiles = resolveFiles(wslEnv);
|
|
104
|
+
|
|
105
|
+
const seen = new Set();
|
|
106
|
+
const merged = [];
|
|
107
|
+
for (const f of [...nativeFiles, ...wslFiles]) {
|
|
108
|
+
if (!seen.has(f)) { seen.add(f); merged.push(f); }
|
|
109
|
+
}
|
|
110
|
+
return merged;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = { multiInstallParse, emptyResult, mergeBothFileSources };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
function powershellLiteral(value) {
|
|
4
|
+
return `'${String(value || "").replace(/'/g, "''")}'`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function quotePosix(value) {
|
|
8
|
+
const text = String(value || "");
|
|
9
|
+
if (/^[A-Za-z0-9_\-./:@]+$/.test(text)) return text;
|
|
10
|
+
return `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, '\\$').replace(/`/g, '\\`')}"`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function buildNotifyCommand(notifyPath, source, { platform = process.platform, execPath = process.execPath } = {}) {
|
|
14
|
+
if (!/^[a-z0-9-]+$/i.test(source)) throw new Error("Invalid notify source");
|
|
15
|
+
if (platform === "win32") {
|
|
16
|
+
return `& ${powershellLiteral(execPath)} ${powershellLiteral(notifyPath)} --source=${source}`;
|
|
17
|
+
}
|
|
18
|
+
return `/usr/bin/env node ${quotePosix(notifyPath)} --source=${source}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Recognize only our complete notify invocation, never a user command merely
|
|
22
|
+
// containing notify.cjs or additional shell actions. Used to repair old hooks.
|
|
23
|
+
function notifyIdentity(command) {
|
|
24
|
+
if (typeof command !== "string") return null;
|
|
25
|
+
const tokens = command.match(/"(?:\\.|[^"\\])*"|'(?:''|[^'])*'|[^\s]+/g) || [];
|
|
26
|
+
const decode = (token) => token.startsWith("'")
|
|
27
|
+
? token.slice(1, -1).replace(/''/g, "'")
|
|
28
|
+
: token.startsWith('"') ? token.slice(1, -1).replace(/\\([\\"$`])/g, "$1") : token;
|
|
29
|
+
const args = tokens.map(decode);
|
|
30
|
+
if (args[0] === "&") args.shift();
|
|
31
|
+
if (args[0] === "/usr/bin/env" && args[1] === "node") args.shift();
|
|
32
|
+
if (args.length !== 3 || !/(?:^|[\\/])node(?:\.exe)?$/i.test(args[0])) return null;
|
|
33
|
+
if (!/(?:^|[\\/])notify\.cjs$/i.test(args[1]) || !/^--source=[a-z0-9-]+$/i.test(args[2])) return null;
|
|
34
|
+
const file = args[1].replace(/\\/g, "/");
|
|
35
|
+
return `${/^[a-z]:\//i.test(file) ? file.toLowerCase() : file}\u0000${args[2]}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { buildNotifyCommand, notifyIdentity };
|