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.
- package/CHANGELOG.md +46 -19
- package/LICENSE +22 -22
- package/README.md +123 -94
- package/THIRD_PARTY_NOTICES.md +140 -140
- package/bin/tokenusage.js +69 -69
- package/package.json +59 -59
- package/src/cli.js +146 -134
- package/src/commands/device-login.js +205 -205
- package/src/commands/diagnostics.js +38 -38
- package/src/commands/doctor.js +110 -110
- package/src/commands/init.js +2484 -2436
- package/src/commands/pause.js +77 -0
- package/src/commands/sessions.js +29 -29
- package/src/commands/status.js +1758 -1747
- package/src/commands/sync.js +8048 -7934
- package/src/commands/uninstall.js +322 -312
- package/src/lib/account-usage-dedup.js +267 -267
- package/src/lib/antigravity-paths.js +48 -48
- package/src/lib/ark-agent-plan-limits.js +438 -438
- package/src/lib/ark-coding-plan-limits.js +537 -537
- package/src/lib/async-queue-reader.js +138 -138
- package/src/lib/atomic-json.js +27 -27
- package/src/lib/bearer-token.js +11 -11
- package/src/lib/categorizer-utils.js +232 -232
- package/src/lib/claude-categorizer.js +1343 -1343
- package/src/lib/claude-config.js +279 -279
- package/src/lib/claude-user-identity.js +56 -56
- package/src/lib/cli-ui.js +179 -179
- package/src/lib/cloud-account.js +541 -541
- package/src/lib/cloud-device-token.js +141 -141
- package/src/lib/cloud-sync-prefs.js +14 -14
- package/src/lib/cloud-usage-reset.js +115 -115
- package/src/lib/codex-config.js +595 -595
- package/src/lib/codex-context-breakdown.js +806 -806
- package/src/lib/codex-model-attribution.js +128 -128
- package/src/lib/codex-rollout-parser.js +1471 -1471
- package/src/lib/codex-service-tier.js +49 -49
- package/src/lib/codex-token-refresh.js +140 -140
- package/src/lib/codex-token-usage.js +195 -195
- package/src/lib/codex-usage-record.js +195 -195
- package/src/lib/collection-pause.js +77 -0
- package/src/lib/command-runner.js +313 -313
- package/src/lib/commandcode-limits.js +317 -317
- package/src/lib/context-health.js +124 -124
- package/src/lib/cursor-config.js +605 -605
- package/src/lib/cursor-store.js +1918 -1918
- package/src/lib/debug-flags.js +7 -7
- package/src/lib/devin-limits.js +249 -249
- package/src/lib/devin-usage.js +212 -212
- package/src/lib/diagnostics.js +383 -383
- package/src/lib/doctor.js +385 -385
- package/src/lib/dumate.js +95 -95
- package/src/lib/fs.js +455 -455
- package/src/lib/function-url.js +14 -14
- package/src/lib/gemini-config.js +291 -291
- package/src/lib/git-outcomes.js +243 -243
- package/src/lib/grok-context-breakdown.js +890 -890
- package/src/lib/grok-hook.js +360 -360
- package/src/lib/grok-limits.js +865 -865
- package/src/lib/grok-usage.js +98 -98
- package/src/lib/heatmap-compact.js +114 -114
- package/src/lib/ingest-sanitize.js +41 -41
- package/src/lib/init-flow.js +42 -42
- package/src/lib/install-resolver.js +170 -170
- package/src/lib/jsonl-lines.js +134 -134
- package/src/lib/kimi-model-repair.js +173 -173
- package/src/lib/kimi-profile.js +61 -61
- package/src/lib/kimi-session.js +216 -216
- package/src/lib/local-api.js +3588 -3588
- package/src/lib/machine-id.js +238 -238
- package/src/lib/multi-install-parser.js +113 -113
- package/src/lib/notify-command.js +38 -38
- package/src/lib/omp-hook.js +589 -589
- package/src/lib/openclaw-cli.js +104 -104
- package/src/lib/openclaw-hook.js +375 -375
- package/src/lib/openclaw-session-plugin.js +560 -560
- package/src/lib/opencode-config.js +121 -121
- package/src/lib/opencode-go-limits.js +807 -807
- package/src/lib/outcomes-engine.js +253 -253
- package/src/lib/passive-mode.js +219 -219
- package/src/lib/pet-packages.js +722 -722
- package/src/lib/pricing/curated-overrides.json +822 -822
- package/src/lib/pricing/index.js +379 -379
- package/src/lib/pricing/litellm-fetcher.js +172 -172
- package/src/lib/pricing/matcher.js +456 -456
- package/src/lib/pricing/seed-snapshot.json +1 -1
- package/src/lib/progress.js +76 -76
- package/src/lib/project-usage-purge.js +117 -117
- package/src/lib/prompt.js +24 -24
- package/src/lib/provider-status.js +104 -104
- package/src/lib/proxy-env.js +489 -489
- package/src/lib/proxy-settings.js +163 -163
- package/src/lib/qoder-cn-cli-limits.js +119 -119
- package/src/lib/qoder-limits.js +880 -880
- package/src/lib/quiet-warnings.js +26 -26
- package/src/lib/rollout.js +26005 -25966
- package/src/lib/runtime-config.js +9 -4
- package/src/lib/scan-roots.js +277 -277
- package/src/lib/scheduled-task.js +145 -0
- package/src/lib/sentry.js +231 -231
- package/src/lib/session-analytics.js +2972 -2972
- package/src/lib/session-performance.js +237 -237
- package/src/lib/session-upload.js +379 -379
- package/src/lib/skill-usage.js +267 -267
- package/src/lib/skills-manager.js +1591 -1591
- package/src/lib/source-metadata.js +48 -48
- package/src/lib/sqlite-reader.js +215 -215
- package/src/lib/star-cta.js +73 -73
- package/src/lib/subscription-manager.js +293 -293
- package/src/lib/subscriptions.js +508 -508
- package/src/lib/sync-report.js +138 -0
- package/src/lib/telemetry.js +193 -193
- package/src/lib/tracker-paths.js +16 -16
- package/src/lib/trae-cn-config.js +548 -548
- package/src/lib/trae-db.js +127 -127
- package/src/lib/trae-snapshot.js +230 -230
- package/src/lib/trae-sqlite.js +143 -143
- package/src/lib/trae-usage.js +121 -121
- package/src/lib/upload-queue.js +134 -134
- package/src/lib/upload-throttle.js +171 -171
- package/src/lib/usage-limits.js +4552 -4552
- package/src/lib/wrapped-aggregator.js +236 -236
- package/src/lib/wsl-probe.js +281 -281
- package/src/lib/zcode-limits.js +1172 -1172
- package/src/lib/zcode-reset-credits.js +66 -66
- package/test/audit-fixes.test.js +200 -0
- package/test/cli-smoke.test.js +53 -53
- package/test/collection-controls.test.js +210 -0
- package/test/ingest-sanitize.test.js +162 -162
- package/test/quiet-warnings.test.js +53 -53
- package/test/session-upload.test.js +427 -427
|
@@ -1,313 +1,313 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
// Shared command runner for local-CLI limit providers.
|
|
4
|
-
//
|
|
5
|
-
// Extracted from usage-limits.js (which keeps a require of it) so
|
|
6
|
-
// ark-coding-plan-limits.js and future providers don't have to copy it.
|
|
7
|
-
// This is a superset of both former copies: the original's `completeWhen`
|
|
8
|
-
// early-settlement hook, plus the hardening that previously only lived in
|
|
9
|
-
// the ark copy — an abort `signal` wired into the spawn lifecycle, a
|
|
10
|
-
// `platform` override with `where.exe` discovery on native Windows, and a
|
|
11
|
-
// byte-capped maxBuffer for piped spawn output.
|
|
12
|
-
|
|
13
|
-
const cp = require("node:child_process");
|
|
14
|
-
const fs = require("node:fs");
|
|
15
|
-
const os = require("node:os");
|
|
16
|
-
const path = require("node:path");
|
|
17
|
-
|
|
18
|
-
/** Run a command without a shell by default, optionally piping options.input to stdin. */
|
|
19
|
-
function runCommand(commandRunner, command, args, options = {}) {
|
|
20
|
-
const merged = {
|
|
21
|
-
encoding: "utf8",
|
|
22
|
-
maxBuffer: 10 * 1024 * 1024,
|
|
23
|
-
useShell: false,
|
|
24
|
-
...options,
|
|
25
|
-
};
|
|
26
|
-
if (typeof commandRunner === "function") {
|
|
27
|
-
return Promise.resolve(commandRunner(command, args, merged));
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const {
|
|
31
|
-
timeout,
|
|
32
|
-
maxBuffer,
|
|
33
|
-
input,
|
|
34
|
-
completeWhen,
|
|
35
|
-
completionGraceMs = 250,
|
|
36
|
-
killProcessGroup = false,
|
|
37
|
-
platform = process.platform,
|
|
38
|
-
signal,
|
|
39
|
-
useShell = false,
|
|
40
|
-
...spawnOptions
|
|
41
|
-
} = merged;
|
|
42
|
-
return new Promise((resolve) => {
|
|
43
|
-
if (signal?.aborted) {
|
|
44
|
-
const error = new Error(`spawn ${command} aborted`);
|
|
45
|
-
error.name = "AbortError";
|
|
46
|
-
resolve({ status: null, stdout: "", stderr: "", error });
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const useProcessGroup = killProcessGroup && platform !== "win32";
|
|
51
|
-
// `useShell` is opt-in per call site. It exists for npm's Windows .cmd
|
|
52
|
-
// shims, which Node's spawn cannot execute directly — but shell
|
|
53
|
-
// execution means cmd.exe re-parses the joined command line, so any
|
|
54
|
-
// argument carrying shell metacharacters (e.g. a powershell -Command
|
|
55
|
-
// script with `|`) would be split. Default false keeps direct spawns,
|
|
56
|
-
// which is what every pre-existing usage-limits call site expects.
|
|
57
|
-
// Under shell execution quote the command unconditionally: cmd.exe
|
|
58
|
-
// metacharacters are not limited to whitespace (`C:\Users\a&b\...`
|
|
59
|
-
// has none yet splits at `&`), and Windows account names allow them.
|
|
60
|
-
const shellCommand = useShell && !command.startsWith('"')
|
|
61
|
-
? `"${command}"`
|
|
62
|
-
: command;
|
|
63
|
-
let child;
|
|
64
|
-
try {
|
|
65
|
-
child = cp.spawn(shellCommand, args, {
|
|
66
|
-
...spawnOptions,
|
|
67
|
-
detached: useProcessGroup || spawnOptions.detached,
|
|
68
|
-
shell: useShell,
|
|
69
|
-
stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
|
70
|
-
});
|
|
71
|
-
} catch (error) {
|
|
72
|
-
resolve({ status: null, stdout: "", stderr: "", error });
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
let stdout = "";
|
|
77
|
-
let stderr = "";
|
|
78
|
-
let outputBytes = 0;
|
|
79
|
-
let settled = false;
|
|
80
|
-
let timedOut = false;
|
|
81
|
-
let timer = null;
|
|
82
|
-
let hardTimer = null;
|
|
83
|
-
let completionTimer = null;
|
|
84
|
-
let abortListener = null;
|
|
85
|
-
|
|
86
|
-
const settle = ({ status = null, error = null } = {}) => {
|
|
87
|
-
if (settled) return;
|
|
88
|
-
settled = true;
|
|
89
|
-
if (timer) clearTimeout(timer);
|
|
90
|
-
if (hardTimer) clearTimeout(hardTimer);
|
|
91
|
-
if (completionTimer) clearTimeout(completionTimer);
|
|
92
|
-
if (abortListener) signal?.removeEventListener("abort", abortListener);
|
|
93
|
-
let finalError = error;
|
|
94
|
-
if (!finalError && timedOut) {
|
|
95
|
-
finalError = new Error(`spawn ${command} ETIMEDOUT`);
|
|
96
|
-
finalError.code = "ETIMEDOUT";
|
|
97
|
-
}
|
|
98
|
-
const result = { status, stdout, stderr };
|
|
99
|
-
if (finalError) result.error = finalError;
|
|
100
|
-
resolve(result);
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
const signalChild = (killSignal) => {
|
|
104
|
-
try {
|
|
105
|
-
if (useProcessGroup && Number.isInteger(child.pid)) {
|
|
106
|
-
process.kill(-child.pid, killSignal);
|
|
107
|
-
} else {
|
|
108
|
-
child.kill(killSignal);
|
|
109
|
-
}
|
|
110
|
-
} catch (_error) {}
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
const stopChild = ({ timeoutExpired = false } = {}) => {
|
|
114
|
-
if (settled) return;
|
|
115
|
-
if (timeoutExpired) timedOut = true;
|
|
116
|
-
signalChild("SIGTERM");
|
|
117
|
-
// A CLI may leave descendants or inherited stdio alive after SIGTERM.
|
|
118
|
-
// Escalate after a short grace period and settle even if close never fires.
|
|
119
|
-
hardTimer = setTimeout(() => {
|
|
120
|
-
signalChild("SIGKILL");
|
|
121
|
-
settle({ status: null });
|
|
122
|
-
}, 1000);
|
|
123
|
-
if (typeof hardTimer.unref === "function") hardTimer.unref();
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
const scheduleCompletion = () => {
|
|
127
|
-
if (typeof completeWhen !== "function" || settled) return;
|
|
128
|
-
let complete = false;
|
|
129
|
-
try {
|
|
130
|
-
complete = Boolean(completeWhen(stdout, stderr));
|
|
131
|
-
} catch (_error) {}
|
|
132
|
-
if (!complete) return;
|
|
133
|
-
if (completionTimer) clearTimeout(completionTimer);
|
|
134
|
-
completionTimer = setTimeout(
|
|
135
|
-
() => stopChild(),
|
|
136
|
-
Math.max(0, Number(completionGraceMs) || 0),
|
|
137
|
-
);
|
|
138
|
-
};
|
|
139
|
-
|
|
140
|
-
const appendOutput = (key, chunk) => {
|
|
141
|
-
if (settled) return;
|
|
142
|
-
if (key === "stdout") stdout += chunk;
|
|
143
|
-
else stderr += chunk;
|
|
144
|
-
outputBytes += Buffer.byteLength(chunk, "utf8");
|
|
145
|
-
// Unlike exec/execFile, spawn does not apply a maxBuffer guard to piped
|
|
146
|
-
// streams. Enforce the combined byte cap here so a verbose CLI cannot
|
|
147
|
-
// grow this process without bound.
|
|
148
|
-
if (outputBytes > maxBuffer) {
|
|
149
|
-
const error = new Error(`spawn ${command} maxBuffer length exceeded`);
|
|
150
|
-
error.code = "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
|
|
151
|
-
signalChild("SIGKILL");
|
|
152
|
-
settle({ status: null, error });
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
scheduleCompletion();
|
|
156
|
-
};
|
|
157
|
-
|
|
158
|
-
child.stdout?.setEncoding("utf8");
|
|
159
|
-
child.stderr?.setEncoding("utf8");
|
|
160
|
-
child.stdout?.on("data", (chunk) => appendOutput("stdout", chunk));
|
|
161
|
-
child.stderr?.on("data", (chunk) => appendOutput("stderr", chunk));
|
|
162
|
-
child.on("error", (error) => settle({ status: null, error }));
|
|
163
|
-
child.on("close", (code) => settle({ status: timedOut ? null : code }));
|
|
164
|
-
|
|
165
|
-
if (signal) {
|
|
166
|
-
abortListener = () => stopChild();
|
|
167
|
-
signal.addEventListener("abort", abortListener, { once: true });
|
|
168
|
-
if (signal.aborted) abortListener();
|
|
169
|
-
}
|
|
170
|
-
if (Number.isFinite(timeout) && timeout > 0) {
|
|
171
|
-
timer = setTimeout(() => stopChild({ timeoutExpired: true }), timeout);
|
|
172
|
-
}
|
|
173
|
-
if (input !== undefined) {
|
|
174
|
-
child.stdin?.on("error", (error) => {
|
|
175
|
-
signalChild("SIGKILL");
|
|
176
|
-
settle({ error });
|
|
177
|
-
});
|
|
178
|
-
try {
|
|
179
|
-
child.stdin?.end(input);
|
|
180
|
-
} catch (error) {
|
|
181
|
-
signalChild("SIGKILL");
|
|
182
|
-
settle({ error });
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// Locate a binary on PATH. Unix uses `which`; native Windows ships no `which`
|
|
189
|
-
// (it has `where.exe` instead), so blindly spawning `which` there returns
|
|
190
|
-
// ENOENT and every provider would report itself unconfigured even when the
|
|
191
|
-
// binary is installed and signed in.
|
|
192
|
-
async function whichBinary(binary, { commandRunner, platform = process.platform, signal } = {}) {
|
|
193
|
-
const probe = platform === "win32" ? "where" : "which";
|
|
194
|
-
const result = await runCommand(commandRunner, probe, [binary], {
|
|
195
|
-
timeout: 2000,
|
|
196
|
-
signal,
|
|
197
|
-
platform,
|
|
198
|
-
killProcessGroup: true,
|
|
199
|
-
});
|
|
200
|
-
if (result?.error || result?.status !== 0) return null;
|
|
201
|
-
const stdout = typeof result?.stdout === "string" ? result.stdout.trim() : "";
|
|
202
|
-
if (!stdout) return null;
|
|
203
|
-
// `where` on Windows emits CRLF and may list several matches across PATH
|
|
204
|
-
// entries; take the first line without the trailing `\r`, or the polluted
|
|
205
|
-
// path would fail at spawn time.
|
|
206
|
-
return stdout
|
|
207
|
-
.split(/\r?\n/)
|
|
208
|
-
.map((line) => line.trim())
|
|
209
|
-
.find(Boolean) || null;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async function isBinaryAvailable(binary, { commandRunner, platform, signal } = {}) {
|
|
213
|
-
return (await whichBinary(binary, { commandRunner, platform, signal })) !== null;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// Expand a versioned install root (e.g. ~/.nvm/versions/node/<ver>/ or
|
|
217
|
-
// fnm's node-versions/<ver>/installation/) into its per-version bin
|
|
218
|
-
// directories. Returns [] when the root does not exist.
|
|
219
|
-
function versionedBinDirs(root, inner) {
|
|
220
|
-
try {
|
|
221
|
-
return fs.readdirSync(root, { withFileTypes: true })
|
|
222
|
-
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
|
|
223
|
-
.sort((a, b) => b.name.localeCompare(a.name, "en", { numeric: true }))
|
|
224
|
-
.map((entry) => path.join(root, entry.name, ...inner));
|
|
225
|
-
} catch (_error) {
|
|
226
|
-
return [];
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
// Directories where globally installed CLIs commonly live even when the
|
|
231
|
-
// current process has a minimal PATH (e.g. a Finder-launched macOS app does
|
|
232
|
-
// not inherit the login-shell PATH, so Homebrew and npm global binaries are
|
|
233
|
-
// unreachable through `which`). Probed with statSync — no spawn.
|
|
234
|
-
function commonGlobalBinDirectories({ home = os.homedir(), platform = process.platform } = {}) {
|
|
235
|
-
if (platform === "win32") {
|
|
236
|
-
return [
|
|
237
|
-
path.join(home, "AppData", "Roaming", "npm"),
|
|
238
|
-
];
|
|
239
|
-
}
|
|
240
|
-
return [
|
|
241
|
-
"/opt/homebrew/bin",
|
|
242
|
-
"/usr/local/bin",
|
|
243
|
-
path.join(home, ".local", "bin"),
|
|
244
|
-
path.join(home, ".bun", "bin"),
|
|
245
|
-
path.join(home, ".npm-global", "bin"),
|
|
246
|
-
// volta keeps shims for every global install here
|
|
247
|
-
path.join(home, ".volta", "bin"),
|
|
248
|
-
// nvm / fnm install npm globals under a per-version prefix that a
|
|
249
|
-
// minimal PATH never sees; newest version first.
|
|
250
|
-
...versionedBinDirs(path.join(home, ".nvm", "versions", "node"), ["bin"]),
|
|
251
|
-
...versionedBinDirs(path.join(home, ".local", "share", "fnm", "node-versions"), ["installation", "bin"]),
|
|
252
|
-
...(platform === "darwin"
|
|
253
|
-
? versionedBinDirs(path.join(home, "Library", "Application Support", "fnm", "node-versions"), ["installation", "bin"])
|
|
254
|
-
: []),
|
|
255
|
-
];
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// Probe `binary` inside the given directories with statSync — no spawn.
|
|
259
|
-
// Exported so providers can treat a hit as install evidence without
|
|
260
|
-
// paying for a `which` process.
|
|
261
|
-
function statBinaryInDirs(binary, searchDirs, platform = process.platform) {
|
|
262
|
-
for (const dir of searchDirs) {
|
|
263
|
-
const candidate = path.join(dir, binary);
|
|
264
|
-
for (const suffix of platform === "win32" ? ["", ".cmd", ".exe"] : [""]) {
|
|
265
|
-
try {
|
|
266
|
-
if (fs.statSync(candidate + suffix).isFile()) return candidate + suffix;
|
|
267
|
-
} catch (_error) {}
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
return null;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* Resolve a binary to an absolute path: `which`/`where` first, then a
|
|
275
|
-
* spawn-free probe of the common global-install directories above. Returns
|
|
276
|
-
* null when the binary cannot be found. Callers should spawn the returned
|
|
277
|
-
* path (not the bare name): a bare name goes through PATH search again —
|
|
278
|
-
* and on Windows cmd.exe searches the current directory first, which would
|
|
279
|
-
* let an `arkcli.bat` dropped in the server cwd hijack the spawn.
|
|
280
|
-
*/
|
|
281
|
-
async function resolveBinaryPath(binary, { commandRunner, home, platform = process.platform, signal, globalBinDirs } = {}) {
|
|
282
|
-
let resolved = null;
|
|
283
|
-
try {
|
|
284
|
-
resolved = await whichBinary(binary, { commandRunner, platform, signal });
|
|
285
|
-
} catch (_error) {
|
|
286
|
-
resolved = null;
|
|
287
|
-
}
|
|
288
|
-
if (resolved) return resolved;
|
|
289
|
-
const searchDirs = Array.isArray(globalBinDirs)
|
|
290
|
-
? globalBinDirs
|
|
291
|
-
: commonGlobalBinDirectories({ home, platform });
|
|
292
|
-
return statBinaryInDirs(binary, searchDirs, platform);
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
// Resolving an npm CLI's absolute path does not resolve its /usr/bin/env node
|
|
296
|
-
// shebang. Finder-launched apps have a minimal PATH even when the CLI lives
|
|
297
|
-
// beside a working nvm/fnm/Homebrew Node. Scope this environment to the child;
|
|
298
|
-
// preserve the install's own runtime and use our running Node as a fallback.
|
|
299
|
-
function resolvedCliEnvironment(binaryPath, { env = process.env, platform = process.platform } = {}) {
|
|
300
|
-
if (platform === "win32") return { ...env };
|
|
301
|
-
const dirs = [path.dirname(binaryPath), ...(env.PATH || "/usr/bin:/bin").split(path.delimiter), path.dirname(process.execPath)];
|
|
302
|
-
return { ...env, PATH: [...new Set(dirs.filter(Boolean))].join(path.delimiter) };
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
module.exports = {
|
|
306
|
-
runCommand,
|
|
307
|
-
whichBinary,
|
|
308
|
-
isBinaryAvailable,
|
|
309
|
-
commonGlobalBinDirectories,
|
|
310
|
-
statBinaryInDirs,
|
|
311
|
-
resolveBinaryPath,
|
|
312
|
-
resolvedCliEnvironment,
|
|
313
|
-
};
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Shared command runner for local-CLI limit providers.
|
|
4
|
+
//
|
|
5
|
+
// Extracted from usage-limits.js (which keeps a require of it) so
|
|
6
|
+
// ark-coding-plan-limits.js and future providers don't have to copy it.
|
|
7
|
+
// This is a superset of both former copies: the original's `completeWhen`
|
|
8
|
+
// early-settlement hook, plus the hardening that previously only lived in
|
|
9
|
+
// the ark copy — an abort `signal` wired into the spawn lifecycle, a
|
|
10
|
+
// `platform` override with `where.exe` discovery on native Windows, and a
|
|
11
|
+
// byte-capped maxBuffer for piped spawn output.
|
|
12
|
+
|
|
13
|
+
const cp = require("node:child_process");
|
|
14
|
+
const fs = require("node:fs");
|
|
15
|
+
const os = require("node:os");
|
|
16
|
+
const path = require("node:path");
|
|
17
|
+
|
|
18
|
+
/** Run a command without a shell by default, optionally piping options.input to stdin. */
|
|
19
|
+
function runCommand(commandRunner, command, args, options = {}) {
|
|
20
|
+
const merged = {
|
|
21
|
+
encoding: "utf8",
|
|
22
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
23
|
+
useShell: false,
|
|
24
|
+
...options,
|
|
25
|
+
};
|
|
26
|
+
if (typeof commandRunner === "function") {
|
|
27
|
+
return Promise.resolve(commandRunner(command, args, merged));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const {
|
|
31
|
+
timeout,
|
|
32
|
+
maxBuffer,
|
|
33
|
+
input,
|
|
34
|
+
completeWhen,
|
|
35
|
+
completionGraceMs = 250,
|
|
36
|
+
killProcessGroup = false,
|
|
37
|
+
platform = process.platform,
|
|
38
|
+
signal,
|
|
39
|
+
useShell = false,
|
|
40
|
+
...spawnOptions
|
|
41
|
+
} = merged;
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
if (signal?.aborted) {
|
|
44
|
+
const error = new Error(`spawn ${command} aborted`);
|
|
45
|
+
error.name = "AbortError";
|
|
46
|
+
resolve({ status: null, stdout: "", stderr: "", error });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const useProcessGroup = killProcessGroup && platform !== "win32";
|
|
51
|
+
// `useShell` is opt-in per call site. It exists for npm's Windows .cmd
|
|
52
|
+
// shims, which Node's spawn cannot execute directly — but shell
|
|
53
|
+
// execution means cmd.exe re-parses the joined command line, so any
|
|
54
|
+
// argument carrying shell metacharacters (e.g. a powershell -Command
|
|
55
|
+
// script with `|`) would be split. Default false keeps direct spawns,
|
|
56
|
+
// which is what every pre-existing usage-limits call site expects.
|
|
57
|
+
// Under shell execution quote the command unconditionally: cmd.exe
|
|
58
|
+
// metacharacters are not limited to whitespace (`C:\Users\a&b\...`
|
|
59
|
+
// has none yet splits at `&`), and Windows account names allow them.
|
|
60
|
+
const shellCommand = useShell && !command.startsWith('"')
|
|
61
|
+
? `"${command}"`
|
|
62
|
+
: command;
|
|
63
|
+
let child;
|
|
64
|
+
try {
|
|
65
|
+
child = cp.spawn(shellCommand, args, {
|
|
66
|
+
...spawnOptions,
|
|
67
|
+
detached: useProcessGroup || spawnOptions.detached,
|
|
68
|
+
shell: useShell,
|
|
69
|
+
stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
resolve({ status: null, stdout: "", stderr: "", error });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let stdout = "";
|
|
77
|
+
let stderr = "";
|
|
78
|
+
let outputBytes = 0;
|
|
79
|
+
let settled = false;
|
|
80
|
+
let timedOut = false;
|
|
81
|
+
let timer = null;
|
|
82
|
+
let hardTimer = null;
|
|
83
|
+
let completionTimer = null;
|
|
84
|
+
let abortListener = null;
|
|
85
|
+
|
|
86
|
+
const settle = ({ status = null, error = null } = {}) => {
|
|
87
|
+
if (settled) return;
|
|
88
|
+
settled = true;
|
|
89
|
+
if (timer) clearTimeout(timer);
|
|
90
|
+
if (hardTimer) clearTimeout(hardTimer);
|
|
91
|
+
if (completionTimer) clearTimeout(completionTimer);
|
|
92
|
+
if (abortListener) signal?.removeEventListener("abort", abortListener);
|
|
93
|
+
let finalError = error;
|
|
94
|
+
if (!finalError && timedOut) {
|
|
95
|
+
finalError = new Error(`spawn ${command} ETIMEDOUT`);
|
|
96
|
+
finalError.code = "ETIMEDOUT";
|
|
97
|
+
}
|
|
98
|
+
const result = { status, stdout, stderr };
|
|
99
|
+
if (finalError) result.error = finalError;
|
|
100
|
+
resolve(result);
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const signalChild = (killSignal) => {
|
|
104
|
+
try {
|
|
105
|
+
if (useProcessGroup && Number.isInteger(child.pid)) {
|
|
106
|
+
process.kill(-child.pid, killSignal);
|
|
107
|
+
} else {
|
|
108
|
+
child.kill(killSignal);
|
|
109
|
+
}
|
|
110
|
+
} catch (_error) {}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const stopChild = ({ timeoutExpired = false } = {}) => {
|
|
114
|
+
if (settled) return;
|
|
115
|
+
if (timeoutExpired) timedOut = true;
|
|
116
|
+
signalChild("SIGTERM");
|
|
117
|
+
// A CLI may leave descendants or inherited stdio alive after SIGTERM.
|
|
118
|
+
// Escalate after a short grace period and settle even if close never fires.
|
|
119
|
+
hardTimer = setTimeout(() => {
|
|
120
|
+
signalChild("SIGKILL");
|
|
121
|
+
settle({ status: null });
|
|
122
|
+
}, 1000);
|
|
123
|
+
if (typeof hardTimer.unref === "function") hardTimer.unref();
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const scheduleCompletion = () => {
|
|
127
|
+
if (typeof completeWhen !== "function" || settled) return;
|
|
128
|
+
let complete = false;
|
|
129
|
+
try {
|
|
130
|
+
complete = Boolean(completeWhen(stdout, stderr));
|
|
131
|
+
} catch (_error) {}
|
|
132
|
+
if (!complete) return;
|
|
133
|
+
if (completionTimer) clearTimeout(completionTimer);
|
|
134
|
+
completionTimer = setTimeout(
|
|
135
|
+
() => stopChild(),
|
|
136
|
+
Math.max(0, Number(completionGraceMs) || 0),
|
|
137
|
+
);
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const appendOutput = (key, chunk) => {
|
|
141
|
+
if (settled) return;
|
|
142
|
+
if (key === "stdout") stdout += chunk;
|
|
143
|
+
else stderr += chunk;
|
|
144
|
+
outputBytes += Buffer.byteLength(chunk, "utf8");
|
|
145
|
+
// Unlike exec/execFile, spawn does not apply a maxBuffer guard to piped
|
|
146
|
+
// streams. Enforce the combined byte cap here so a verbose CLI cannot
|
|
147
|
+
// grow this process without bound.
|
|
148
|
+
if (outputBytes > maxBuffer) {
|
|
149
|
+
const error = new Error(`spawn ${command} maxBuffer length exceeded`);
|
|
150
|
+
error.code = "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
|
|
151
|
+
signalChild("SIGKILL");
|
|
152
|
+
settle({ status: null, error });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
scheduleCompletion();
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
child.stdout?.setEncoding("utf8");
|
|
159
|
+
child.stderr?.setEncoding("utf8");
|
|
160
|
+
child.stdout?.on("data", (chunk) => appendOutput("stdout", chunk));
|
|
161
|
+
child.stderr?.on("data", (chunk) => appendOutput("stderr", chunk));
|
|
162
|
+
child.on("error", (error) => settle({ status: null, error }));
|
|
163
|
+
child.on("close", (code) => settle({ status: timedOut ? null : code }));
|
|
164
|
+
|
|
165
|
+
if (signal) {
|
|
166
|
+
abortListener = () => stopChild();
|
|
167
|
+
signal.addEventListener("abort", abortListener, { once: true });
|
|
168
|
+
if (signal.aborted) abortListener();
|
|
169
|
+
}
|
|
170
|
+
if (Number.isFinite(timeout) && timeout > 0) {
|
|
171
|
+
timer = setTimeout(() => stopChild({ timeoutExpired: true }), timeout);
|
|
172
|
+
}
|
|
173
|
+
if (input !== undefined) {
|
|
174
|
+
child.stdin?.on("error", (error) => {
|
|
175
|
+
signalChild("SIGKILL");
|
|
176
|
+
settle({ error });
|
|
177
|
+
});
|
|
178
|
+
try {
|
|
179
|
+
child.stdin?.end(input);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
signalChild("SIGKILL");
|
|
182
|
+
settle({ error });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Locate a binary on PATH. Unix uses `which`; native Windows ships no `which`
|
|
189
|
+
// (it has `where.exe` instead), so blindly spawning `which` there returns
|
|
190
|
+
// ENOENT and every provider would report itself unconfigured even when the
|
|
191
|
+
// binary is installed and signed in.
|
|
192
|
+
async function whichBinary(binary, { commandRunner, platform = process.platform, signal } = {}) {
|
|
193
|
+
const probe = platform === "win32" ? "where" : "which";
|
|
194
|
+
const result = await runCommand(commandRunner, probe, [binary], {
|
|
195
|
+
timeout: 2000,
|
|
196
|
+
signal,
|
|
197
|
+
platform,
|
|
198
|
+
killProcessGroup: true,
|
|
199
|
+
});
|
|
200
|
+
if (result?.error || result?.status !== 0) return null;
|
|
201
|
+
const stdout = typeof result?.stdout === "string" ? result.stdout.trim() : "";
|
|
202
|
+
if (!stdout) return null;
|
|
203
|
+
// `where` on Windows emits CRLF and may list several matches across PATH
|
|
204
|
+
// entries; take the first line without the trailing `\r`, or the polluted
|
|
205
|
+
// path would fail at spawn time.
|
|
206
|
+
return stdout
|
|
207
|
+
.split(/\r?\n/)
|
|
208
|
+
.map((line) => line.trim())
|
|
209
|
+
.find(Boolean) || null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function isBinaryAvailable(binary, { commandRunner, platform, signal } = {}) {
|
|
213
|
+
return (await whichBinary(binary, { commandRunner, platform, signal })) !== null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Expand a versioned install root (e.g. ~/.nvm/versions/node/<ver>/ or
|
|
217
|
+
// fnm's node-versions/<ver>/installation/) into its per-version bin
|
|
218
|
+
// directories. Returns [] when the root does not exist.
|
|
219
|
+
function versionedBinDirs(root, inner) {
|
|
220
|
+
try {
|
|
221
|
+
return fs.readdirSync(root, { withFileTypes: true })
|
|
222
|
+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
|
|
223
|
+
.sort((a, b) => b.name.localeCompare(a.name, "en", { numeric: true }))
|
|
224
|
+
.map((entry) => path.join(root, entry.name, ...inner));
|
|
225
|
+
} catch (_error) {
|
|
226
|
+
return [];
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Directories where globally installed CLIs commonly live even when the
|
|
231
|
+
// current process has a minimal PATH (e.g. a Finder-launched macOS app does
|
|
232
|
+
// not inherit the login-shell PATH, so Homebrew and npm global binaries are
|
|
233
|
+
// unreachable through `which`). Probed with statSync — no spawn.
|
|
234
|
+
function commonGlobalBinDirectories({ home = os.homedir(), platform = process.platform } = {}) {
|
|
235
|
+
if (platform === "win32") {
|
|
236
|
+
return [
|
|
237
|
+
path.join(home, "AppData", "Roaming", "npm"),
|
|
238
|
+
];
|
|
239
|
+
}
|
|
240
|
+
return [
|
|
241
|
+
"/opt/homebrew/bin",
|
|
242
|
+
"/usr/local/bin",
|
|
243
|
+
path.join(home, ".local", "bin"),
|
|
244
|
+
path.join(home, ".bun", "bin"),
|
|
245
|
+
path.join(home, ".npm-global", "bin"),
|
|
246
|
+
// volta keeps shims for every global install here
|
|
247
|
+
path.join(home, ".volta", "bin"),
|
|
248
|
+
// nvm / fnm install npm globals under a per-version prefix that a
|
|
249
|
+
// minimal PATH never sees; newest version first.
|
|
250
|
+
...versionedBinDirs(path.join(home, ".nvm", "versions", "node"), ["bin"]),
|
|
251
|
+
...versionedBinDirs(path.join(home, ".local", "share", "fnm", "node-versions"), ["installation", "bin"]),
|
|
252
|
+
...(platform === "darwin"
|
|
253
|
+
? versionedBinDirs(path.join(home, "Library", "Application Support", "fnm", "node-versions"), ["installation", "bin"])
|
|
254
|
+
: []),
|
|
255
|
+
];
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Probe `binary` inside the given directories with statSync — no spawn.
|
|
259
|
+
// Exported so providers can treat a hit as install evidence without
|
|
260
|
+
// paying for a `which` process.
|
|
261
|
+
function statBinaryInDirs(binary, searchDirs, platform = process.platform) {
|
|
262
|
+
for (const dir of searchDirs) {
|
|
263
|
+
const candidate = path.join(dir, binary);
|
|
264
|
+
for (const suffix of platform === "win32" ? ["", ".cmd", ".exe"] : [""]) {
|
|
265
|
+
try {
|
|
266
|
+
if (fs.statSync(candidate + suffix).isFile()) return candidate + suffix;
|
|
267
|
+
} catch (_error) {}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Resolve a binary to an absolute path: `which`/`where` first, then a
|
|
275
|
+
* spawn-free probe of the common global-install directories above. Returns
|
|
276
|
+
* null when the binary cannot be found. Callers should spawn the returned
|
|
277
|
+
* path (not the bare name): a bare name goes through PATH search again —
|
|
278
|
+
* and on Windows cmd.exe searches the current directory first, which would
|
|
279
|
+
* let an `arkcli.bat` dropped in the server cwd hijack the spawn.
|
|
280
|
+
*/
|
|
281
|
+
async function resolveBinaryPath(binary, { commandRunner, home, platform = process.platform, signal, globalBinDirs } = {}) {
|
|
282
|
+
let resolved = null;
|
|
283
|
+
try {
|
|
284
|
+
resolved = await whichBinary(binary, { commandRunner, platform, signal });
|
|
285
|
+
} catch (_error) {
|
|
286
|
+
resolved = null;
|
|
287
|
+
}
|
|
288
|
+
if (resolved) return resolved;
|
|
289
|
+
const searchDirs = Array.isArray(globalBinDirs)
|
|
290
|
+
? globalBinDirs
|
|
291
|
+
: commonGlobalBinDirectories({ home, platform });
|
|
292
|
+
return statBinaryInDirs(binary, searchDirs, platform);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Resolving an npm CLI's absolute path does not resolve its /usr/bin/env node
|
|
296
|
+
// shebang. Finder-launched apps have a minimal PATH even when the CLI lives
|
|
297
|
+
// beside a working nvm/fnm/Homebrew Node. Scope this environment to the child;
|
|
298
|
+
// preserve the install's own runtime and use our running Node as a fallback.
|
|
299
|
+
function resolvedCliEnvironment(binaryPath, { env = process.env, platform = process.platform } = {}) {
|
|
300
|
+
if (platform === "win32") return { ...env };
|
|
301
|
+
const dirs = [path.dirname(binaryPath), ...(env.PATH || "/usr/bin:/bin").split(path.delimiter), path.dirname(process.execPath)];
|
|
302
|
+
return { ...env, PATH: [...new Set(dirs.filter(Boolean))].join(path.delimiter) };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
module.exports = {
|
|
306
|
+
runCommand,
|
|
307
|
+
whichBinary,
|
|
308
|
+
isBinaryAvailable,
|
|
309
|
+
commonGlobalBinDirectories,
|
|
310
|
+
statBinaryInDirs,
|
|
311
|
+
resolveBinaryPath,
|
|
312
|
+
resolvedCliEnvironment,
|
|
313
|
+
};
|