agent-dag 3.22.0 → 3.22.3

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