ccdeck 1.43.0 → 1.44.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.
@@ -0,0 +1,850 @@
1
+ // Running an external command the same way on Linux, macOS and Windows.
2
+ //
3
+ // On POSIX, `spawn("cswap", …)` finds cswap on PATH. On Windows it does not:
4
+ // the thing on PATH is `cswap.exe` or a `cswap.cmd` shim, and Node only
5
+ // applies PATHEXT when it goes through a shell. So the naive call fails with
6
+ // ENOENT on Windows even though the tool is installed and on PATH — which
7
+ // looks exactly like "not installed" and is why this is worth a module.
8
+ //
9
+ // Resolving the extension ourselves keeps the argument vector intact, which
10
+ // blanket `shell: true` would not: it concatenates arguments into a command
11
+ // line, so an argument containing a quote or an ampersand stops being an
12
+ // argument.
13
+ //
14
+ // The exception is .cmd and .bat, which since Node 20.12 CANNOT be spawned
15
+ // without a shell at all — the fix for CVE-2024-27980 makes that throw EINVAL,
16
+ // synchronously, from inside execFile. Those are routed through cmd.exe the
17
+ // same way Node's own `shell: true` does it, with the arguments quoted here
18
+ // rather than pasted together. Getting this wrong is not a degraded feature:
19
+ // the throw escaped the retry path and took the whole process down on Windows
20
+ // before the server ever started.
21
+ //
22
+ // Going through cmd.exe then raises a question a direct spawn never has to ask:
23
+ // under what NAME. A `.cmd` shim finds its own payload relative to `%~dp0`, so a
24
+ // bare name — which carries no directory — makes it look under the deck's
25
+ // working directory instead of its own. Every batch candidate is therefore
26
+ // launched by its full path where one can be found; see shimPath and
27
+ // candidateSpec.
28
+ import { execFile, spawn } from "node:child_process";
29
+ import { existsSync } from "node:fs";
30
+
31
+ // Extensions Windows will execute, most specific first. `.com` is omitted —
32
+ // nothing ships one, and every extra candidate costs a failed spawn.
33
+ const WIN_EXTS = [".exe", ".cmd", ".bat", ""];
34
+
35
+ // Which spelling worked, per command name. A failed spawn is cheap but not
36
+ // free, and these run on a poll.
37
+ const resolved = new Map();
38
+
39
+ /**
40
+ * The spellings to try for `cmd`, best first.
41
+ *
42
+ * Exported with the platform as a parameter for the reason everything else in
43
+ * this file is: the Windows answer decides which candidate becomes a batch one,
44
+ * and a batch candidate is the only kind #457 touches — so a test that wants to
45
+ * follow a caller's bare name all the way to the command line cmd.exe receives
46
+ * has to be able to ask for the Windows list from a machine that is not Windows.
47
+ */
48
+ export function candidates(cmd, platform = process.platform) {
49
+ if (platform !== "win32") return [cmd];
50
+ // An explicit extension is respected as given.
51
+ if (/\.[a-z]+$/i.test(cmd)) return [cmd];
52
+ const known = resolved.get(cmd);
53
+ return known ? [known] : WIN_EXTS.map(ext => cmd + ext);
54
+ }
55
+
56
+ /** Exported for tests: the platform is a parameter so both can be checked. */
57
+ export const isBatch = (file, platform = process.platform) =>
58
+ platform === "win32" && /\.(cmd|bat)$/i.test(file);
59
+
60
+ /**
61
+ * Rewrite a batch-file invocation as a cmd.exe one.
62
+ *
63
+ * Mirrors what Node does internally for `shell: true` on Windows — comspec,
64
+ * /d /s /c, the whole command line as a single quoted argument, and
65
+ * windowsVerbatimArguments so Node does not quote it a second time. Each
66
+ * argument is quoted here, with embedded quotes doubled, which is the escape
67
+ * cmd.exe understands inside a quoted string.
68
+ */
69
+ export function viaCmd(file, args) {
70
+ const line = [file, ...args].map(a => shellQuoteArg(a, "win32")).join(" ");
71
+ return {
72
+ file: process.env.comspec || process.env.ComSpec || "cmd.exe",
73
+ args: ["/d", "/s", "/c", `"${line}"`],
74
+ opts: { windowsVerbatimArguments: true },
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Quote ONE argument into a command line a shell will parse.
80
+ *
81
+ * Everything else in this module exists to avoid needing this: an argument
82
+ * vector is handed to spawn untouched and nothing in it is ever read as syntax.
83
+ * Two callers cannot take that route, and they are the reason this is exported.
84
+ * A Claude Code hook is registered as `{type:"command", command:"<string>"}` —
85
+ * the host CLI runs that string THROUGH A SHELL on every tool call, and the
86
+ * format has no argv form to emit instead. So the string has to be built here,
87
+ * correctly, once.
88
+ *
89
+ * The inputs are not user input in the web sense, but they are not constants
90
+ * either: the hook path is built from $CLAUDE_CONFIG_DIR and homedir(), and the
91
+ * node path from process.execPath. Wrapping those in double quotes — what this
92
+ * used to do — is not escaping on POSIX at all: `$(…)`, a backtick and `\` are
93
+ * all still live inside them, so a config dir named `/tmp/a$(id)b` became shell
94
+ * code written into the user's settings.json and executed on every hook fire.
95
+ * A bare `$` in a path is the same bug wearing a duller hat — `$HOME` expands to
96
+ * nothing, the hook path silently becomes wrong, and hooks stop firing with no
97
+ * error anywhere.
98
+ *
99
+ * POSIX gets single quotes, inside which NOTHING is special, with the one
100
+ * escape that form has: close the quote, emit a backslash-quote, reopen.
101
+ * Windows gets cmd.exe's rule — the same one viaCmd applies above, so this file
102
+ * has one Windows quoting rule rather than two — with the same single residual
103
+ * exec.mjs already documents: cmd.exe expands `%VAR%` inside quotes too, and a
104
+ * command line has no escape for it. That is narrower than it sounds, since
105
+ * `%foo%` with no variable `foo` is left alone, and it is a limit of the
106
+ * platform rather than of this function.
107
+ */
108
+ export function shellQuoteArg(arg, platform = process.platform) {
109
+ const s = String(arg ?? "");
110
+ if (platform === "win32") return `"${s.replace(/"/g, '""')}"`;
111
+ return `'${s.split("'").join("'\\''")}'`;
112
+ }
113
+
114
+ /**
115
+ * The absolute path of a Windows command shim, or null when nothing answers to
116
+ * that name.
117
+ *
118
+ * Why a bare name is not good enough, which is the whole of #456. npm's `.cmd`
119
+ * shims locate every file they need relative to THEMSELVES:
120
+ *
121
+ * SET "NPM_PREFIX_JS=%~dp0\node_modules\npm\bin\npm-prefix.js"
122
+ * SET "NPX_CLI_JS=%~dp0\node_modules\npm\bin\npx-cli.js"
123
+ *
124
+ * `%~dp0` is the drive and path of `%0`, and `%0` is the command token cmd.exe
125
+ * was given. Handed `cmd.exe /d /s /c ""npm.cmd" "install" …`, that token
126
+ * carries no directory of its own, so `%~dp0` came out as the deck's WORKING
127
+ * DIRECTORY instead of the shim's. Reported from Windows 10 with the deck
128
+ * started from `C:\Users\vceban`:
129
+ *
130
+ * Error: Cannot find module 'C:\Users\vceban\node_modules\npm\bin\npm-prefix.js'
131
+ * Error: Cannot find module 'C:\Users\vceban\node_modules\npm\bin\npx-cli.js'
132
+ *
133
+ * — two stacks, one defect, and `C:\Users\vceban` is the cwd rather than
134
+ * anything to do with npm: `where npx` on that machine printed
135
+ * `C:\Program Files\nodejs\npx.cmd` and `npx ccdeck` ran perfectly from a
136
+ * prompt. It is ours, introduced when #362 replaced `shell: true` with viaCmd:
137
+ * the quoting was the fix and the bare name was the cost, and it broke the
138
+ * managed install and the npx fallback in the same stroke, which is why every
139
+ * diagnosis of one half kept half-fitting.
140
+ *
141
+ * Node's own directory is tried before PATH because node and npm ship together
142
+ * and that is where the shims are — the same preference npxCliCandidates in
143
+ * npx.mjs states for npm's CLI scripts, so the repo has one rule rather than
144
+ * two. PATH is then walked in its own order, which is what cmd.exe would have
145
+ * done, minus the current directory it searches first: a deck that resolves its
146
+ * npm out of whatever folder it happens to be sitting in is the bug above
147
+ * wearing a hat.
148
+ *
149
+ * The path arithmetic is spelled out rather than done through `node:path` for
150
+ * the reason npxCliCandidates gives: `path` is the platform running the SUITE,
151
+ * so a Windows layout checked from macOS would come back with forward slashes.
152
+ * `execPath`, `pathEnv` and `exists` are injected for the same reason — the
153
+ * Windows answer has to be checkable from an OS that cannot run it.
154
+ *
155
+ * The walk itself now lives in `pathLookup` below, because #433 needed the same
156
+ * one for a tool that is not a shim; this is that walk with the two answers a
157
+ * shim needs — Windows, and node's own directory first.
158
+ */
159
+ export const shimPath = (name, deps) =>
160
+ pathLookup(name, "win32", { besideNode: true, ...deps });
161
+
162
+ /**
163
+ * Where `name` actually lives on PATH, as an absolute path, or null when
164
+ * nothing on PATH answers to it.
165
+ *
166
+ * This is the general form of shimPath above, and it exists because #433 asked
167
+ * for a third way to reach ccusage: the copy a user installed themselves. The
168
+ * deck's own error text has told people to "put ccusage on PATH yourself" since
169
+ * before there was anything that looked, so the choice was to either look or
170
+ * stop saying it — see getRunner in ccusage.mjs for which way that went.
171
+ *
172
+ * Writing it as ONE walk rather than a second one is the point. A PATH search
173
+ * on Windows is not a PATH search plus a note: `ccusage` there is `ccusage.cmd`
174
+ * or `ccusage.exe` and never the bare name, because PATHEXT is a shell's job
175
+ * and spawn is not a shell — which is the whole reason `candidates` exists, so
176
+ * that is what supplies the spellings here. And a `.cmd` found this way is
177
+ * returned as a FULL PATH, which is what keeps #456 fixed: launched by its bare
178
+ * name through cmd.exe, a shim computes `%~dp0` from the deck's working
179
+ * directory and goes hunting for its payload there.
180
+ *
181
+ * `besideNode` is the one thing a shim wants and a tool does not. npm ships
182
+ * beside node, so looking there first is right for `npm.cmd`; for anything else
183
+ * it would quietly overrule the order the user put their own PATH in, which is
184
+ * the one statement of preference they actually made.
185
+ *
186
+ * The check is existence, not executability. That is what `run`'s candidate
187
+ * loop effectively asks too — it spawns and moves on if the spawn fails — and
188
+ * an executable bit is not a thing Windows has. The residue is a directory on
189
+ * PATH that happens to be named after the tool; it would be resolved here and
190
+ * fail on spawn, with the failure naming the path, which is a better place to
191
+ * find out than a silent miss.
192
+ */
193
+ export function pathLookup(name, platform = process.platform, {
194
+ execPath = process.execPath,
195
+ pathEnv = process.env.PATH ?? process.env.Path ?? "",
196
+ exists = existsSync,
197
+ besideNode = false,
198
+ } = {}) {
199
+ // A name that already carries a directory needs no lookup, and re-rooting it
200
+ // would be a way to run something else entirely.
201
+ if (typeof name !== "string" || !name || /[\\/]/.test(name)) return null;
202
+ const win = platform === "win32";
203
+ const sep = win ? "\\" : "/";
204
+ const dirs = [];
205
+ if (besideNode) {
206
+ const beside = String(execPath ?? "").split(/[\\/]/).slice(0, -1).join(sep);
207
+ if (beside) dirs.push(beside);
208
+ }
209
+ // `;` on Windows, `:` everywhere else. Splitting on the wrong one is not a
210
+ // near miss: a POSIX PATH read with `;` is one enormous directory that
211
+ // exists nowhere, so every lookup would answer null and the feature would
212
+ // look like it had never been written.
213
+ for (const raw of String(pathEnv ?? "").split(win ? ";" : ":")) {
214
+ // A PATH entry may be quoted, and may end in a separator; neither is part
215
+ // of the directory, and both would produce a path nothing exists at.
216
+ const dir = raw.trim().replace(/^"|"$/g, "").replace(/[\\/]+$/, "");
217
+ if (dir) dirs.push(dir);
218
+ }
219
+ // On POSIX this is `[name]`, so the inner loop runs once and the cost is one
220
+ // stat per directory, exactly as before.
221
+ const spellings = candidates(name, platform);
222
+ for (const dir of dirs) {
223
+ for (const spelling of spellings) {
224
+ const full = `${dir}${sep}${spelling}`;
225
+ try {
226
+ if (exists(full)) return full;
227
+ } catch {
228
+ // An entry that cannot even be stat'ed — a disconnected network drive
229
+ // is the usual one — is a miss, not a reason to stop looking.
230
+ }
231
+ }
232
+ }
233
+ return null;
234
+ }
235
+
236
+ /**
237
+ * What to hand `spawn`/`execFile` for `file` and `args` on this platform, with
238
+ * the argument vector intact and no shell.
239
+ *
240
+ * The alternative every caller reaches for first — `shell: true`, because a
241
+ * .cmd cannot be spawned any other way — is the one thing that must not be
242
+ * used: Node joins the array into a command line with a single space and no
243
+ * per-argument quoting, so `--workspace C:\Users\John Smith\proj` arrives as
244
+ * two arguments and an `&` in a path ends the command early. Batch files go
245
+ * through cmd.exe with each argument quoted; everything else is spawned as
246
+ * given. The platform is a parameter so both branches can be tested.
247
+ *
248
+ * The one thing quoting cannot cover: cmd.exe expands `%VAR%` inside quotes
249
+ * too, and a command line has no escape for it. Every other metacharacter —
250
+ * `&`, `|`, `>`, `^`, `(` — is inert once quoted.
251
+ */
252
+ export const spawnSpec = (file, args, platform = process.platform) =>
253
+ isBatch(file, platform) ? viaCmd(file, args) : { file, args, opts: {} };
254
+
255
+ /**
256
+ * The same thing for ONE CANDIDATE SPELLING out of the list above — which on
257
+ * Windows means deciding the NAME the shim is launched under before deciding
258
+ * how, because those are not the same question.
259
+ *
260
+ * `spawnSpec` answers "how". This answers what #457 put in front of it. A batch
261
+ * candidate runs THROUGH cmd.exe (see viaCmd), and a `.cmd` shim locates its own
262
+ * payload relative to `%~dp0` — the drive and path of the command token cmd.exe
263
+ * was handed. A bare `claude.cmd` carries no directory at all, so `%~dp0` came
264
+ * out as the deck's WORKING DIRECTORY and the shim went hunting for its
265
+ * JavaScript under whatever folder the deck happened to be started from. #456
266
+ * proved exactly that for ccusage's `npm.cmd` and `npx.cmd`; it left the three
267
+ * helpers below alone, and they carry the shims the panels depend on — the
268
+ * `claude.cmd` behind the quota poll and the sign-in, and whatever `.cmd` a
269
+ * Python installer left for cswap. Same defect, same machine, wider blast
270
+ * radius.
271
+ *
272
+ * `?? raw` is the whole safety story and is not optional: when shimPath can see
273
+ * no layout it answers null, and the candidate stays the bare name today's code
274
+ * already uses, so nothing that works now can start failing. It is the same
275
+ * `?? name` ccusage.mjs and npx.mjs spell, so the repo has one rule rather than
276
+ * three. shimPath also refuses any name that already carries a directory, which
277
+ * is what keeps a caller's own absolute candidate — quotaClaudeBin's
278
+ * `%APPDATA%\npm\claude.cmd`, cswapCandidates' `~/.local/bin/cswap.exe` — from
279
+ * being re-rooted somewhere else entirely.
280
+ *
281
+ * `launch` comes back beside the spec because looksMissing has to be told the
282
+ * spelling cmd.exe was ACTUALLY GIVEN rather than the one the loop started
283
+ * from; its own header explains what breaks otherwise, and that coupling is the
284
+ * reason #456 stopped short of doing this.
285
+ *
286
+ * On POSIX `isBatch` is false, so no lookup happens, no filesystem is touched,
287
+ * `launch` is `raw`, and the spec is the object spawnSpec always returned —
288
+ * byte-identical, which is the point.
289
+ */
290
+ export function candidateSpec(raw, args, platform = process.platform, deps) {
291
+ const launch = isBatch(raw, platform) ? (shimPath(raw, deps) ?? raw) : raw;
292
+ return { ...spawnSpec(launch, args, platform), launch };
293
+ }
294
+
295
+ /**
296
+ * Stop a child AND everything it started.
297
+ *
298
+ * On POSIX the child is the tool, so a signal to it is the whole job and this
299
+ * is exactly the `child.kill()` it replaces. On Windows a .cmd or .bat runs
300
+ * THROUGH cmd.exe (see viaCmd), so the tool — node, for the claude and npm
301
+ * shims — is a grandchild, and a kill is one TerminateProcess against the
302
+ * wrapper. Windows terminates no descendants and libuv's job object lets them
303
+ * break away, so the wrapper vanished and the work carried on: every cancelled
304
+ * or expired `claude auth login` left a node.exe blocked forever on the stdin
305
+ * pipe this process holds, and because that node.exe kept the inherited stdout
306
+ * handle open, the wrapper's 'close' never arrived either — the run that was
307
+ * reported dead never settled.
308
+ *
309
+ * `taskkill /T` is the descendant walk Windows does have, and `/F` is what
310
+ * stops a console app that is not pumping its message queue. Taking it from
311
+ * System32 rather than from PATH matters here: PATH is the user's, and this is
312
+ * the program we hand a pid to kill. If it cannot run at all, the plain kill
313
+ * still happens, which is no worse than before.
314
+ *
315
+ * A process group would be the tidier answer and is the wrong one on Windows:
316
+ * `detached` there only means CREATE_NEW_PROCESS_GROUP, and Node cannot signal
317
+ * a group — `process.kill(-pid)` is POSIX-only.
318
+ */
319
+ export function killTree(child, signal) {
320
+ const plain = () => { try { child?.kill(signal); } catch { /* already gone */ } };
321
+ if (process.platform !== "win32" || !child?.pid) return plain();
322
+ try {
323
+ const root = process.env.SystemRoot || process.env.systemroot;
324
+ const exe = root ? `${root}\\System32\\taskkill.exe` : "taskkill";
325
+ const killer = spawn(exe, ["/pid", String(child.pid), "/T", "/F"], {
326
+ stdio: "ignore", windowsHide: true,
327
+ });
328
+ killer.on("error", plain);
329
+ killer.on("exit", (code) => { if (code !== 0) plain(); });
330
+ killer.unref?.();
331
+ } catch {
332
+ plain();
333
+ }
334
+ }
335
+
336
+ // Reasons to try the next candidate spelling rather than give up. EINVAL and
337
+ // UNKNOWN show up on Windows for a file that exists but cannot be executed the
338
+ // way it was asked for; both mean "not this one", not "no such tool".
339
+ export const tryNext = (err) =>
340
+ Boolean(err) && (err.code === "ENOENT" || err.code === "EACCES" ||
341
+ err.code === "EINVAL" || err.code === "UNKNOWN");
342
+
343
+ // The three lines an ENGLISH cmd.exe prints when it cannot find what it was
344
+ // asked to run, anchored to a whole line each. First the two-line pair for a
345
+ // bare name, then the one it uses when a directory in an explicit path does not
346
+ // exist.
347
+ //
348
+ // These are one signal out of three rather than the whole answer — see
349
+ // looksMissing. Windows ships cmd.exe in every language it ships in, and these
350
+ // sentences are translated with it.
351
+ const CMD_UNKNOWN = /^'(.+)' is not recognized as an internal or external command,?$/i;
352
+ const CMD_UNKNOWN_TAIL = /^operable program or batch file\.?$/i;
353
+ const CMD_NO_PATH = /^the system cannot find the (?:path|file) specified\.?$/i;
354
+
355
+ // cmd.exe's own errorlevel for a command token it could not resolve — the one
356
+ // signal here that is not a human sentence, and therefore the only one that is
357
+ // the same on a German install as on an English one. It is the number every CI
358
+ // log in the world prints beside "is not recognized".
359
+ //
360
+ // Not every path reports it: some Windows builds answer a bare `cmd /c missing`
361
+ // with a plain 1 instead, which is why this is a sufficient signal and never a
362
+ // necessary one. A number this large cannot arrive from POSIX at all — a process
363
+ // exit status there is masked to 0-255 before Node ever sees it — so nothing
364
+ // outside cmd.exe can reach it by accident.
365
+ const CMD_NOT_FOUND_EXIT = 9009;
366
+
367
+ /** True when an exit status is cmd.exe saying "no such command", in any locale. */
368
+ export const notFoundExit = (code) => Number(code) === CMD_NOT_FOUND_EXIT;
369
+
370
+ // Every run of text this line wrapped in quotes. cmd.exe quotes the command
371
+ // token it could not find in EVERY locale, and the quote character is the only
372
+ // part of the message that is not a translation: `'…'` in English and French,
373
+ // `"…"` in German, Spanish, Italian, Portuguese, Polish and Russian.
374
+ const quotedRuns = (line) =>
375
+ [...String(line).matchAll(/'([^']+)'|"([^"]+)"/g)].map(m => m[1] ?? m[2]);
376
+
377
+ // cmd.exe echoes the command token exactly as it was given, so an exact match
378
+ // is what we expect; the comparison is only case- and quote-insensitive because
379
+ // Windows paths are.
380
+ const sameCommand = (quoted, name) => {
381
+ const norm = (s) => String(s).trim().replace(/^"+|"+$/g, "").toLowerCase();
382
+ return norm(quoted) === norm(name);
383
+ };
384
+
385
+ /**
386
+ * cmd.exe's way of saying ENOENT — and only cmd.exe's.
387
+ *
388
+ * A .cmd or .bat candidate is launched THROUGH cmd.exe, and cmd.exe exists — so
389
+ * a missing tool is not a spawn error at all. It is a healthy shell exiting 1
390
+ * after printing two lines:
391
+ *
392
+ * 'cswap' is not recognized as an internal or external command,
393
+ * operable program or batch file.
394
+ *
395
+ * Read as a real failure, that stops the candidate loop early AND puts the
396
+ * second line — on its own, meaningless — in front of the user. Reported from
397
+ * Windows on 2026-08-14: the accounts panel said only "operable program or
398
+ * batch file." when sharing an account.
399
+ *
400
+ * The fussiness is about the other direction, which is worse. "The system
401
+ * cannot find the file specified" is Windows' generic text for ENOENT, and it
402
+ * appears INSIDE the output of tools that ran perfectly well — cswap is a
403
+ * Python CLI, and a FileNotFoundError traceback ends in that exact sentence.
404
+ * Believed there, it threw the real error away, told the user the tool was not
405
+ * on PATH when PATH was fine, and — the dangerous half — sent the candidate
406
+ * loop on to re-run the entire command, which for `cswap remove 3` means asking
407
+ * to delete an account a second time.
408
+ *
409
+ * So the output has to be cmd.exe's message and nothing else: cmd.exe prints it
410
+ * INSTEAD of running anything, so any other line, or any prefix on the line,
411
+ * means something ran and this is its report. And when cmd.exe names the
412
+ * command it could not find, that name must be the candidate we asked for — a
413
+ * tool that shells out itself can forward the message about some other command.
414
+ *
415
+ * `name` is the spelling cmd.exe was ACTUALLY GIVEN — which since #457 is the
416
+ * shim's absolute path whenever shimPath found one, not the bare candidate the
417
+ * loop started from. That distinction is the coupling #456 named as its reason
418
+ * for stopping short, and it is a one-way trap rather than a detail: cmd.exe
419
+ * echoes the command token back exactly as it received it, so a check against
420
+ * the bare name stops matching the instant the token becomes a path. What that
421
+ * costs is not a cosmetic mismatch — it is the honesty of the whole answer. A
422
+ * shim that shimPath saw and that is gone by the time cmd.exe looks for it (a
423
+ * stale memo, an uninstall mid-session, a network drive that dropped, a roaming
424
+ * profile still syncing) would come back as an ordinary exit 1 whose stderr is
425
+ * cmd.exe's two-line "is not recognized / operable program or batch file."
426
+ * instead of the `code: "ENOENT"` every panel keys its "not installed" message
427
+ * off. The user would be told their CLI failed, and shown half a sentence about
428
+ * batch files, when the truthful answer is that it is not there.
429
+ *
430
+ * Feeding it the launch spelling keeps the comparison EXACT, which is what the
431
+ * paragraph above is protecting: matching loosely — on the basename, say —
432
+ * would let a tool that shells out itself have its own child's "is not
433
+ * recognized" read as the tool's absence, re-running a command that may be
434
+ * `cswap remove 3`. So the rule is not "compare less", it is "compare against
435
+ * what was actually asked for".
436
+ *
437
+ * Callers that only have the text (failureText) omit it and get the shape rules
438
+ * alone.
439
+ *
440
+ * ── AND NOT ONLY IN ENGLISH (#552) ──────────────────────────────────────────
441
+ *
442
+ * Everything above was written against three English sentences, and cmd.exe is
443
+ * translated. On a German install with cswap genuinely absent it prints
444
+ *
445
+ * Der Befehl "cswap" ist entweder falsch geschrieben oder konnte nicht
446
+ * gefunden werden.
447
+ *
448
+ * — so this answered false, `run` resolved `{ ok: false, code: 1 }`,
449
+ * claude-accounts.mjs picked `reason: "switch_failed"` over `"no_cswap"` and the
450
+ * panel's install affordance never appeared. failureText then fell through to
451
+ * firstUseful, which puts the LAST line of a localized sentence on screen by
452
+ * itself: #457's symptom reproduced for every non-English locale. It also
453
+ * stopped the candidate loop early, so a `.bat` installed after a missing `.cmd`
454
+ * was never reached.
455
+ *
456
+ * Adding the German sentence, and then the French and the Japanese ones, is not
457
+ * a fix — it is the same defect with a longer list. So two signals that are not
458
+ * sentences carry the answer instead, and the English text is what remains when
459
+ * neither is available:
460
+ *
461
+ * 1. THE EXIT STATUS. `exitCode` 9009 is cmd.exe's own errorlevel for a
462
+ * command token it could not resolve, identical in every language. See
463
+ * CMD_NOT_FOUND_EXIT for why it is not required, and the paragraph below
464
+ * for the two cases where it is not believed either. It is subject to the
465
+ * same "cmd.exe printed nothing else" cap as rule 2, because a status is
466
+ * forwarded as easily as a sentence is.
467
+ *
468
+ * 2. THE SHAPE. cmd.exe quotes the command it could not find, in every locale,
469
+ * and prints that INSTEAD of running anything — so the whole output is at
470
+ * most the two lines of one wrapped sentence. Text of at most two lines
471
+ * whose FIRST line quotes exactly the spelling we launched is cmd.exe's
472
+ * verdict about our command whatever the words around it say.
473
+ *
474
+ * Rule 2 needs `name`, and refuses without it. That is the same principle the
475
+ * paragraphs above argue for and not a limitation bolted on: `Error: "account-9"
476
+ * does not exist` is one line with a quoted token in it, and read as an absence
477
+ * it would send the candidate loop back round to re-run `cswap remove 3`. What
478
+ * makes the rule safe is that the quoted token has to be the exact spelling
479
+ * cmd.exe was handed — `cswap.cmd`, or the absolute path shimPath found — which
480
+ * is a string the tool underneath has no reason to print. The two-line cap is
481
+ * the other half: a Python traceback ending in "The system cannot find the file
482
+ * specified" is four lines and can never qualify.
483
+ *
484
+ * THE SAME TRAP THE ENGLISH RULE ALREADY AVOIDS, NOW FOR THE EXIT STATUS. A
485
+ * `.cmd` shim is itself a batch file, so a shim that EXISTS and whose payload
486
+ * interpreter does not — a scoop or npm-style `cswap.cmd` in front of a python
487
+ * that was uninstalled — has cmd.exe print "is not recognized" about PYTHON and
488
+ * hands the shim's caller that same 9009. Believed on its own, the deck would
489
+ * call the tool absent and re-run the command under the next spelling. So a text
490
+ * that positively names a command OTHER than ours vetoes every rule here,
491
+ * including the status: the check that made #457 safe, applied one level up.
492
+ *
493
+ * What is deliberately still missed: a LOCALIZED "the system cannot find the
494
+ * path specified", which carries no quoted token and no structure to key off.
495
+ * That case only arises when shimPath found a shim that then vanished, and it
496
+ * fails in the safe direction — an honest exit 1 rather than a wrong ENOENT.
497
+ */
498
+ export function looksMissing(text, name = "", exitCode = null) {
499
+ const lines = String(text ?? "").split(/\r?\n/).map(l => l.trim()).filter(Boolean);
500
+ // Whatever cmd.exe named, in whatever language it said the rest — the quoting
501
+ // is the part that is not a translation.
502
+ const named = lines.length ? quotedRuns(lines[0]) : [];
503
+ const namesUs = named.some(q => sameCommand(q, name));
504
+
505
+ // The veto, before anything is believed: a message about somebody else's
506
+ // command is not evidence about ours, and neither is the status that came
507
+ // with it. See the header — a `.cmd` shim in front of a missing interpreter
508
+ // forwards both.
509
+ if (name && named.length > 0 && !namesUs) return false;
510
+
511
+ // cmd.exe says this INSTEAD of running anything, so anything longer than one
512
+ // wrapped sentence came from something that DID run — and that outranks both
513
+ // signals below. A shim can forward its child's 9009 after printing pages of
514
+ // its own; a Python traceback is four lines and one of them quotes the very
515
+ // shim we launched.
516
+ const saidNothingElse = lines.length <= 2;
517
+
518
+ // The signal that is not a sentence. It does not need to READ the text, which
519
+ // is the whole reason it exists: on a non-English install there may be nothing
520
+ // in the text this can read.
521
+ if (saidNothingElse && notFoundExit(exitCode)) return true;
522
+ if (!lines.length) return false;
523
+
524
+ // The English shapes, whole-line anchored, exactly as before.
525
+ let english = true;
526
+ for (const line of lines) {
527
+ const unknown = CMD_UNKNOWN.exec(line);
528
+ if (unknown) {
529
+ if (name && !sameCommand(unknown[1], name)) return false;
530
+ continue;
531
+ }
532
+ if (CMD_UNKNOWN_TAIL.test(line) || CMD_NO_PATH.test(line)) continue;
533
+ english = false;
534
+ break;
535
+ }
536
+ if (english) return true;
537
+
538
+ // Otherwise: cmd.exe in some other language, recognised by its shape and by
539
+ // the one word in it that is ours.
540
+ return Boolean(name) && saidNothingElse && namesUs;
541
+ }
542
+
543
+ // How much of a hung child's output the deadline keeps. The full buffers belong
544
+ // to execFile's callback, which a timed-out run never waits for, and the tail is
545
+ // where a tool puts the line that explains itself.
546
+ const TIMEOUT_TAIL = 8 << 10;
547
+
548
+ /**
549
+ * Run a command and collect its output. Never rejects, and never throws —
550
+ * failures come back as `{ ok: false }`, because every caller here is a poll or
551
+ * a UI action where a missing tool is an expected state rather than an
552
+ * exception. execFile can throw synchronously on Windows, so the call itself is
553
+ * guarded as well as its callback.
554
+ *
555
+ * A run stopped by its deadline answers `{ ok: false, code: "ETIMEDOUT",
556
+ * killed: true, timedOut: true }` — never ok, whatever the child said on its
557
+ * way out.
558
+ *
559
+ * `env` replaces the child's environment wholesale, the way spawn's does; pass
560
+ * `{...process.env, X: "1"}` to add to it. It exists because the quota probe
561
+ * runs a whole Claude Code and has to mark the run as the deck's own, and that
562
+ * marker is what stops every poll drawing itself onto the canvas.
563
+ */
564
+ export function run(cmd, args, { timeout = 20_000, maxBuffer = 4 << 20, env } = {}) {
565
+ const tries = candidates(cmd);
566
+ return new Promise((resolve) => {
567
+ const attempt = (i) => {
568
+ if (i >= tries.length) {
569
+ return resolve({ ok: false, code: "ENOENT", killed: false, timedOut: false, stdout: "", stderr: "" });
570
+ }
571
+ const raw = tries[i];
572
+ // `launch` is what cmd.exe is handed and `raw` is what the loop is
573
+ // reasoning about; on Windows those differ for a batch candidate whose
574
+ // shim was found (#457) and are the same everywhere else.
575
+ const { file, args: argv, opts, launch } = candidateSpec(raw, args);
576
+
577
+ const tree = isBatch(raw);
578
+ let timer = null, timedOut = false;
579
+ // A tail of what the child managed to say. The deadline below answers
580
+ // before execFile's callback does, and the callback owns the full
581
+ // buffers, so without this copy a timed-out run reports nothing at all —
582
+ // and the last line a hung tool printed is usually the only clue why it
583
+ // hung.
584
+ let sawOut = "", sawErr = "";
585
+
586
+ const done = (err, stdout, stderr) => {
587
+ clearTimeout(timer);
588
+ // The deadline already gave this attempt its verdict, and killed the
589
+ // child to make it stop. What the corpse reports is not news, and
590
+ // believing it is what put "cswap export exited 0" in front of the
591
+ // user: execFile calls a signalled exit `code: null`, which `?? 0`
592
+ // turns into a success code, and a tool that handles SIGTERM by
593
+ // exiting 0 — the well-behaved kind — arrives here with no error at
594
+ // all, so the run we cut short came back `ok: true` and got its
595
+ // spelling remembered as one that works.
596
+ if (timedOut) return;
597
+ // cmd.exe's "is not recognized" counts as "not this spelling" too, and
598
+ // it arrives as a normal non-zero exit rather than a spawn error. Only
599
+ // a batch candidate goes through a shell, so only there can the output
600
+ // be a shell's verdict rather than the tool's own words — spawned
601
+ // directly, a missing file is a plain ENOENT and anything printed came
602
+ // from a tool that ran.
603
+ // `err.code` is the exit STATUS for a child that ran and failed, which
604
+ // is where cmd.exe's language-independent 9009 arrives; for a spawn
605
+ // failure it is an errno string, and Number() of that is NaN. Either
606
+ // way looksMissing is handed what the attempt actually reported.
607
+ const missing = Boolean(err) && tree && looksMissing(`${stderr ?? ""}\n${stdout ?? ""}`, launch, err.code);
608
+ if (err && (tryNext(err) || missing) && i + 1 < tries.length) return attempt(i + 1);
609
+ // The CANDIDATE is what gets remembered, never the resolved path. The
610
+ // memo is the only entry `candidates` offers afterwards, so recording an
611
+ // absolute path would pin this process to one install location for its
612
+ // whole life — an upgrade that moves the shim would then fail forever
613
+ // where today it simply gets found again. Re-running the lookup per
614
+ // attempt costs a handful of stats against a process spawn.
615
+ if (!err) resolved.set(cmd, raw);
616
+ resolve({
617
+ ok: !err,
618
+ // A tool cmd.exe could not find is missing, not "exited 1" — callers
619
+ // key their message off this.
620
+ code: missing ? "ENOENT" : (err?.code ?? 0),
621
+ killed: Boolean(err?.killed),
622
+ timedOut: false,
623
+ stdout: String(stdout ?? ""),
624
+ stderr: String(stderr ?? ""),
625
+ });
626
+ };
627
+
628
+ try {
629
+ const cp = execFile(file, argv,
630
+ { timeout: 0, shell: false, windowsHide: true, maxBuffer, ...(env ? { env } : {}), ...opts }, done);
631
+ // Give the child EOF on stdin straight away, which is what this
632
+ // function's contract has always claimed ("run closes stdin", says
633
+ // runInteractive's header) and what execFile does not do: it leaves the
634
+ // pipe open with nobody at the writing end, so a tool that reads stdin
635
+ // waits for a writer that will never arrive. `claude --print /usage`
636
+ // waits three seconds for exactly that before giving up, which is why
637
+ // the shell command it replaced had to end in `< /dev/null`. Closing
638
+ // the pipe is that redirection without a shell to parse it.
639
+ try { cp.stdin?.on("error", () => {}); cp.stdin?.end(); } catch { /* no stdin to close */ }
640
+ cp.stdout?.on("data", (d) => { sawOut = (sawOut + d).slice(-TIMEOUT_TAIL); });
641
+ cp.stderr?.on("data", (d) => { sawErr = (sawErr + d).slice(-TIMEOUT_TAIL); });
642
+ // The deadline states the outcome itself and only then kills, which is
643
+ // the order startUpgrade needs for the same reason: the answer must not
644
+ // depend on the killed child cooperating.
645
+ //
646
+ // execFile's own `timeout` is not used at all. It ends with one signal
647
+ // to the process it started, which for a batch candidate is the cmd.exe
648
+ // wrapper — the deadline was reported as enforced while the tool
649
+ // underneath went on running — and it reports through the callback,
650
+ // which waits for the stdio pipes. On Windows those are held by the
651
+ // grandchild under the wrapper, so when the tree kill could not reach
652
+ // it the callback never came and the run never settled at all: the
653
+ // accounts panel sat on a request that had already timed out.
654
+ timer = setTimeout(() => {
655
+ timedOut = true;
656
+ resolve({ ok: false, code: "ETIMEDOUT", killed: true, timedOut: true, stdout: sawOut, stderr: sawErr });
657
+ killTree(cp);
658
+ }, timeout);
659
+ timer.unref?.();
660
+ } catch (err) {
661
+ // Synchronous throw — the EINVAL case. Same handling as a callback
662
+ // error; letting it propagate here is what crashed the server, because
663
+ // this runs inside the previous attempt's error handler.
664
+ done(err, "", "");
665
+ }
666
+ };
667
+ attempt(0);
668
+ });
669
+ }
670
+
671
+ /**
672
+ * Run a command whose stdin stays open, so the caller can answer it.
673
+ *
674
+ * `run` above closes stdin and waits for the end; that is right for everything
675
+ * that only reports. It is useless for the two commands the accounts panel has
676
+ * to drive: `claude auth login` prints a URL and then blocks reading the code
677
+ * the user pastes back, and `cswap remove` blocks on its own `[y/N]` — there is
678
+ * no `--yes` flag to avoid it. Both need a child that outlives one request and
679
+ * can be written to.
680
+ *
681
+ * Returns immediately with a handle:
682
+ * write(text) — into the child's stdin
683
+ * kill() — give up; `done` still settles
684
+ * onLine(cb) — every complete stdout/stderr line as it arrives
685
+ * done — Promise<{ok, code, killed, timedOut, stdout, stderr}>
686
+ *
687
+ * Never rejects, for the same reason `run` never does. Same Windows candidate
688
+ * resolution, since `claude` and `cswap` are `.cmd` shims there.
689
+ */
690
+ export function runInteractive(cmd, args, { timeout = 300_000, maxOutput = 256 << 10 } = {}) {
691
+ const tries = candidates(cmd);
692
+ const lineSubs = [];
693
+ let child = null;
694
+ let pending = ""; // partial line carried between chunks
695
+ let stdout = "", stderr = "";
696
+ let timedOut = false, killed = false;
697
+ let settle;
698
+ const done = new Promise((resolve) => { settle = resolve; });
699
+
700
+ // Subscribers get `(text, partial)`. A subscriber must not throw and must
701
+ // tolerate repeats: `partial` is the still-unterminated tail, re-offered as
702
+ // it grows, because a prompt is written WITHOUT a newline —
703
+ // "Paste code here if prompted > " never terminates a line, so a
704
+ // newline-only reader would wait for it forever.
705
+ const emitLines = (text) => {
706
+ pending += text;
707
+ let nl;
708
+ while ((nl = pending.indexOf("\n")) !== -1) {
709
+ const line = pending.slice(0, nl).replace(/\r$/, "");
710
+ pending = pending.slice(nl + 1);
711
+ for (const cb of lineSubs) { try { cb(line, false); } catch { /* a subscriber must not kill the child */ } }
712
+ }
713
+ if (pending) {
714
+ for (const cb of lineSubs) { try { cb(pending, true); } catch { /* ignore */ } }
715
+ }
716
+ };
717
+
718
+ const finish = (code, err) => {
719
+ if (!settle) return;
720
+ const s = settle; settle = null;
721
+ clearTimeout(timer);
722
+ s({ ok: code === 0 && !err && !timedOut, code: err?.code ?? code ?? -1, killed, timedOut, stdout, stderr });
723
+ };
724
+
725
+ const timer = setTimeout(() => {
726
+ timedOut = true;
727
+ killTree(child);
728
+ }, timeout);
729
+ timer.unref?.();
730
+
731
+ const attempt = (i) => {
732
+ if (i >= tries.length) return finish(-1, { code: "ENOENT" });
733
+ const raw = tries[i];
734
+ // Same split as in `run`: `launch` is the spelling cmd.exe receives — an
735
+ // absolute `.cmd` once shimPath can see one — and `raw` stays the candidate
736
+ // the loop and the memo are about.
737
+ const { file, args: argv, opts, launch } = candidateSpec(raw, args);
738
+ let proc;
739
+ try {
740
+ proc = spawn(file, argv, { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, ...opts });
741
+ } catch (err) {
742
+ return tryNext(err) ? attempt(i + 1) : finish(-1, err);
743
+ }
744
+ child = proc;
745
+ // A spelling that fails to spawn emits 'error' AND THEN 'close' — with code
746
+ // -2 after an ENOENT. Once the error handler has moved on to the next
747
+ // candidate, that trailing 'close' is news about a child nobody is waiting
748
+ // for any more, and answering it settled `done` with ok:false while the
749
+ // real child was still running. On Windows that is the normal path, not a
750
+ // corner case: `claude.exe` does not exist, `claude.cmd` does, so the very
751
+ // first login reported "the code was not accepted" while the child it had
752
+ // abandoned went on to complete the OAuth and switch the live account.
753
+ // Every listener below therefore speaks only while its own child is the
754
+ // current one.
755
+ const stale = () => proc !== child;
756
+ proc.on("error", (err) => {
757
+ if (stale()) return;
758
+ // Only retry another spelling while nothing has run yet; a mid-run error
759
+ // is this child's failure, not evidence the name was wrong.
760
+ if (tryNext(err) && !stdout && !stderr) { child = null; return attempt(i + 1); }
761
+ finish(-1, err);
762
+ });
763
+ // Spawning proves a spelling exists — except a .cmd/.bat one, which is
764
+ // launched THROUGH cmd.exe. cmd.exe is always there, so it spawns just as
765
+ // happily for a batch file that is not, and only says so later by exiting
766
+ // non-zero with "is not recognized". Caching at spawn time therefore
767
+ // remembered a spelling that never existed, and since `candidates` then
768
+ // offers only the remembered one, the tool stayed unrunnable — with the
769
+ // false message "not on PATH" — even after it was installed. A batch
770
+ // spelling is confirmed by the clean exit below instead, which is the rule
771
+ // `run` already applies with `if (!err)`.
772
+ if (!isBatch(raw)) proc.on("spawn", () => resolved.set(cmd, raw));
773
+ // Capped so a runaway child cannot grow the heap without bound; the tail is
774
+ // what carries the error, so the head is what gets dropped.
775
+ const keep = (buf, text) => (buf + text).slice(-maxOutput);
776
+ proc.stdout?.on("data", (d) => { if (stale()) return; const t = String(d); stdout = keep(stdout, t); emitLines(t); });
777
+ proc.stderr?.on("data", (d) => { if (stale()) return; const t = String(d); stderr = keep(stderr, t); emitLines(t); });
778
+ proc.on("close", (code) => {
779
+ if (stale()) return;
780
+ // Same cmd.exe case as in `run`: exit 1 with "is not recognized" means
781
+ // this spelling does not exist, not that the tool failed. Restricted to a
782
+ // batch candidate, which is the only kind launched through a shell, and
783
+ // to output that is cmd.exe's message alone — everything below re-runs
784
+ // the whole command, and these commands remove accounts.
785
+ if (code !== 0 && isBatch(raw) && looksMissing(`${stderr}\n${stdout}`, launch, code)) {
786
+ if (i + 1 < tries.length) {
787
+ stdout = ""; stderr = ""; pending = "";
788
+ child = null;
789
+ return attempt(i + 1);
790
+ }
791
+ return finish(-1, { code: "ENOENT" });
792
+ }
793
+ // Ran to a clean exit, so this spelling is real — the only confirmation a
794
+ // batch one ever gets.
795
+ if (code === 0 && !killed && !timedOut) resolved.set(cmd, raw);
796
+ finish(code ?? -1, null);
797
+ });
798
+ };
799
+ attempt(0);
800
+
801
+ return {
802
+ write(text) {
803
+ try { child?.stdin?.write(text); } catch { /* the child is gone; `done` says so */ }
804
+ },
805
+ /** Close stdin. A command that reads to EOF (`cswap import -`) needs this
806
+ * to start work at all; a prompting one must never see it. */
807
+ end() {
808
+ try { child?.stdin?.end(); } catch { /* already closed */ }
809
+ },
810
+ /** Stop the run. On Windows that means the tool under the cmd.exe wrapper
811
+ * too — see killTree; a cancelled sign-in used to leave it running. */
812
+ kill() {
813
+ killed = true;
814
+ killTree(child);
815
+ },
816
+ onLine(cb) { lineSubs.push(cb); },
817
+ done,
818
+ };
819
+ }
820
+
821
+ /**
822
+ * Start a command and don't wait for it. Same resolution, no output captured.
823
+ * Used where the result lands somewhere else — a file the next poll reads, or
824
+ * a sound the user hears.
825
+ */
826
+ export function runDetached(cmd, args) {
827
+ const tries = candidates(cmd);
828
+ const attempt = (i) => {
829
+ if (i >= tries.length) return;
830
+ const raw = tries[i];
831
+ // Nothing here reads output, so there is no looksMissing call to keep
832
+ // honest — but the shim still has to be launched by its full path, or the
833
+ // detached `cswap list` this exists for computes `%~dp0` from the deck's cwd
834
+ // exactly like every other caller.
835
+ const { file, args: argv, opts } = candidateSpec(raw, args);
836
+ try {
837
+ const child = spawn(file, argv, { stdio: "ignore", shell: false, windowsHide: true, ...opts });
838
+ child.on("error", (err) => { if (tryNext(err)) attempt(i + 1); });
839
+ // Same trap as above: a batch spelling is spawned through cmd.exe, which
840
+ // succeeds whether or not the batch file is there, so only a clean exit
841
+ // proves this one is worth remembering.
842
+ if (isBatch(raw)) child.on("exit", (code) => { if (code === 0) resolved.set(cmd, raw); });
843
+ else child.on("spawn", () => resolved.set(cmd, raw));
844
+ child.unref?.();
845
+ } catch {
846
+ attempt(i + 1);
847
+ }
848
+ };
849
+ attempt(0);
850
+ }