@xiaolikt/ai-vault 0.11.0 → 0.12.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.
@@ -46,7 +46,7 @@
46
46
  */
47
47
 
48
48
  import { spawn, spawnSync } from "node:child_process";
49
- import { constants as fsConstants, accessSync, readFileSync, promises as fs } from "node:fs";
49
+ import { constants as fsConstants, accessSync, existsSync, readFileSync, promises as fs } from "node:fs";
50
50
  import { homedir, tmpdir } from "node:os";
51
51
  import path from "node:path";
52
52
  import type { ExtensionAPI, ExtensionContext, ToolDefinition, ToolResultEventResult } from "@earendil-works/pi-coding-agent";
@@ -56,7 +56,8 @@ import { bitwardenItems, filterItems } from "./import-map.js";
56
56
  import type { Draft } from "./types.js";
57
57
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
58
58
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
59
- import { getSettingsSafe, settingsCli } from "./settings.js";
59
+ import { npmShimLaunch, type CliLaunch } from "./cli.js";
60
+ import { getSettingsSafe, settingsCli, settingsToken } from "./settings.js";
60
61
  import { tr } from "./i18n.js";
61
62
  import { scrubDeep, scrubText } from "./scrub.js";
62
63
 
@@ -292,6 +293,62 @@ function childEnv(extra?: Record<string, string>): NodeJS.ProcessEnv {
292
293
  return env;
293
294
  }
294
295
 
296
+ const WIN32 = process.platform === "win32";
297
+
298
+ /** A file under the Windows directory: `%SystemRoot%` already is `C:\Windows`. */
299
+ const systemFile = (...parts: string[]): string => path.join(process.env.SystemRoot ?? "C:/Windows", ...parts);
300
+
301
+ /** `taskkill /T /F`: the process and everything it started. Windows has no process groups. Exported for tests. */
302
+ export function killTree(pid: number): void {
303
+ const taskkill = systemFile("System32", "taskkill.exe");
304
+ try {
305
+ spawnSync(taskkill, ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
306
+ } catch {
307
+ /* best-effort: the caller still kills the process itself */
308
+ }
309
+ }
310
+
311
+ /** How long a copy command may take to set the clipboard and exit. */
312
+ const COPY_TIMEOUT_MS = 15_000;
313
+
314
+ let bashLaunch: CliLaunch | undefined;
315
+
316
+ /**
317
+ * The shell `bw_run` runs a command in. Git for Windows keeps `bash.exe` in
318
+ * `<install>\bin` and does not put that on PATH (`git.exe` is what is found
319
+ * there), so the installation git.exe came from is searched as well.
320
+ * Exported for tests.
321
+ */
322
+ export function resolveBash(): CliLaunch {
323
+ if (bashLaunch) return bashLaunch;
324
+ bashLaunch = { program: "bash", pre: [] };
325
+ if (WIN32) {
326
+ const onPath = (exe: string): string | undefined => {
327
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
328
+ if (dir && existsSync(path.join(dir, exe))) return path.join(dir, exe);
329
+ }
330
+ return undefined;
331
+ };
332
+ const roots = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "Programs")];
333
+ bashLaunch.program =
334
+ onPath("bash.exe") ??
335
+ bashBeside(onPath("git.exe")) ??
336
+ roots.filter((base): base is string => !!base).map((base) => path.join(base, "Git", "bin", "bash.exe")).find((candidate) => existsSync(candidate)) ??
337
+ "bash";
338
+ }
339
+ return bashLaunch;
340
+ }
341
+
342
+ /** `<install>\bin\bash.exe`, from whichever directory of a Git for Windows installation one starts. */
343
+ function bashBeside(gitExe: string | undefined): string | undefined {
344
+ for (let dir = gitExe && path.dirname(gitExe); dir; dir = path.dirname(dir)) {
345
+ const candidate = path.join(dir, "bin", "bash.exe");
346
+ if (existsSync(candidate)) return candidate;
347
+ if (path.dirname(dir) === dir) break;
348
+ }
349
+ return undefined;
350
+ }
351
+
295
352
  function exec(cmd: string, args: string[], opts: ExecOptions = {}): Promise<ExecResult> {
296
353
  if (opts.signal?.aborted) return Promise.reject(new Error(`${cmd} cancelled`));
297
354
  const { promise, resolve, reject } = Promise.withResolvers<ExecResult>();
@@ -300,12 +357,20 @@ function exec(cmd: string, args: string[], opts: ExecOptions = {}): Promise<Exec
300
357
  cwd: opts.cwd,
301
358
  stdio: ["pipe", "pipe", "pipe"],
302
359
  detached: opts.group === true,
360
+ windowsHide: true,
303
361
  });
304
362
  let out = "";
305
363
  let err = "";
306
364
  let truncated = false;
307
365
  let settled = false;
308
366
  const kill = () => {
367
+ if (WIN32) {
368
+ // No process groups on Windows: take the whole tree down, or a command
369
+ // that timed out leaves what it started running with the secret in its environment.
370
+ if (child.pid) killTree(child.pid);
371
+ child.kill("SIGKILL");
372
+ return;
373
+ }
309
374
  if (opts.group && child.pid) {
310
375
  try {
311
376
  process.kill(-child.pid, "SIGKILL");
@@ -388,16 +453,42 @@ export async function auditEvent(event: string, detail: string, session?: string
388
453
  // ---------------------------------------------------------------------------
389
454
  // Bitwarden CLI plumbing (secrets only ever travel via env vars / pipes)
390
455
  // ---------------------------------------------------------------------------
391
- let bwBin: string | undefined;
456
+ /** How to start the Bitwarden CLI; `pre` is empty unless an npm wrapper had to be unwrapped. Exported for tests. */
457
+ let bwLaunch: CliLaunch | undefined;
392
458
 
393
- async function resolveBw(): Promise<string> {
394
- if (bwBin) return bwBin;
459
+ /** Runs at all: answers `--version` with exit 0. */
460
+ async function bwRuns(launch: CliLaunch): Promise<boolean> {
395
461
  try {
396
- await exec("bw", ["--version"], { timeout: 20_000 });
397
- bwBin = "bw";
398
- return bwBin;
462
+ const r = await exec(launch.program, [...launch.pre, "--version"], { timeout: 20_000 });
463
+ return r.code === 0;
399
464
  } catch {
400
- /* fall through to nvm scan */
465
+ return false;
466
+ }
467
+ }
468
+
469
+ export async function resolveBw(): Promise<CliLaunch> {
470
+ if (bwLaunch) return bwLaunch;
471
+ // `bw.exe` is found by the bare name on Windows, `bw` elsewhere.
472
+ if (await bwRuns({ program: "bw", pre: [] })) {
473
+ bwLaunch = { program: "bw", pre: [] };
474
+ return bwLaunch;
475
+ }
476
+ // npm installs `bw` as bw.cmd (with a .ps1 and a sh script beside it), which
477
+ // Windows cannot start without a shell: start the JavaScript it wraps with
478
+ // this Node instead.
479
+ if (WIN32) {
480
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
481
+ if (!dir) continue;
482
+ for (const name of ["bw.exe", "bw.cmd", "bw.bat"]) {
483
+ const candidate = path.join(dir, name);
484
+ if (!existsSync(candidate)) continue;
485
+ const launch = name === "bw.exe" ? { program: candidate, pre: [] } : npmShimLaunch(candidate);
486
+ if (launch && (await bwRuns(launch))) {
487
+ bwLaunch = launch;
488
+ return bwLaunch;
489
+ }
490
+ }
491
+ }
401
492
  }
402
493
  try {
403
494
  const nvmDir = path.join(homedir(), ".nvm", "versions", "node");
@@ -408,8 +499,8 @@ async function resolveBw(): Promise<string> {
408
499
  for (const v of versions) {
409
500
  const p = path.join(nvmDir, v, "bin", "bw");
410
501
  if (await fs.access(p).then(() => true, () => false)) {
411
- bwBin = p;
412
- return bwBin;
502
+ bwLaunch = { program: p, pre: [] };
503
+ return bwLaunch;
413
504
  }
414
505
  }
415
506
  } catch {
@@ -422,10 +513,10 @@ async function runBw(
422
513
  args: string[],
423
514
  opts: { session?: string; extraEnv?: Record<string, string>; signal?: AbortSignal } = {},
424
515
  ): Promise<string> {
425
- const bin = await resolveBw();
516
+ const bw = await resolveBw();
426
517
  const env: Record<string, string> = { ...opts.extraEnv };
427
518
  if (opts.session) env.BW_SESSION = opts.session;
428
- const r = await exec(bin, [...args, "--nointeraction"], { env, signal: opts.signal });
519
+ const r = await exec(bw.program, [...bw.pre, ...args, "--nointeraction"], { env, signal: opts.signal });
429
520
  if (r.code !== 0) {
430
521
  const hint = tail(r.stderr) || `exit ${r.code}`;
431
522
  // Never include stdout in errors — some commands print secrets on success-ish paths.
@@ -522,8 +613,8 @@ async function lock(st: BwState, reason: string): Promise<void> {
522
613
  await auditEvent("lock", `reason=${reason}`, st.sessionLabel);
523
614
  if (!releaseSessionKey()) return; // another binding still uses its own key
524
615
  try {
525
- const bin = await resolveBw();
526
- await exec(bin, ["lock", "--nointeraction"], { timeout: 15_000 });
616
+ const bw = await resolveBw();
617
+ await exec(bw.program, [...bw.pre, "lock", "--nointeraction"], { timeout: 15_000 });
527
618
  } catch {
528
619
  /* best-effort; dropping our session key is what matters */
529
620
  }
@@ -580,8 +671,8 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
580
671
  if (status?.status === "unauthenticated") throw new Error(BW_LOGIN_HINT);
581
672
 
582
673
  const pw = await askMasterPassword(ctx, signal);
583
- const bin = await resolveBw();
584
- const r = await exec(bin, ["unlock", "--passwordenv", "BW_MASTER_PASSWORD", "--raw"], {
674
+ const bw = await resolveBw();
675
+ const r = await exec(bw.program, [...bw.pre, "unlock", "--passwordenv", "BW_MASTER_PASSWORD", "--raw"], {
585
676
  env: { BW_MASTER_PASSWORD: pw },
586
677
  timeout: 60_000,
587
678
  signal,
@@ -603,7 +694,8 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
603
694
  if (policy.unlock !== "session") {
604
695
  // Keep the key where the CLI can hand it back; the file's expiry comes
605
696
  // from the bitwarden.hours policy.
606
- await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
697
+ const token = settingsToken();
698
+ await settingsCli().run(["bw-session", "put", ...(token ? ["--token", token] : [])], { stdin: key }).catch(() => undefined);
607
699
  }
608
700
  await auditEvent("unlock", "ok", st.sessionLabel);
609
701
  // Refresh in the background: a full sync can take seconds on large vaults.
@@ -880,8 +972,26 @@ type ClipboardBackend = {
880
972
  copy: [string, string[]];
881
973
  clear: [string, string[]];
882
974
  read: [string, string[]];
975
+ /** wl-copy and xclip keep running to own the selection; the others set it and exit. */
976
+ lingers: boolean;
883
977
  };
884
978
 
979
+ /**
980
+ * Windows: Windows PowerShell with WinForms. The value travels as UTF-8
981
+ * bytes on stdin and stdout: never on a command line, and never through the
982
+ * console's code page, which is not UTF-8 on a Chinese Windows.
983
+ */
984
+ const PS_CLIP_ARGS = ["-NoProfile", "-NonInteractive", "-STA", "-Command"];
985
+ const PS_SET_CLIP =
986
+ "Add-Type -AssemblyName System.Windows.Forms; $stdin = [Console]::OpenStandardInput(); $buffer = New-Object System.IO.MemoryStream; " +
987
+ "$stdin.CopyTo($buffer); $text = [System.Text.Encoding]::UTF8.GetString($buffer.ToArray()); " +
988
+ "if ($text.Length -eq 0) { exit 1 }; [System.Windows.Forms.Clipboard]::SetText($text); exit 0";
989
+ const PS_GET_CLIP =
990
+ "Add-Type -AssemblyName System.Windows.Forms; $bytes = [System.Text.Encoding]::UTF8.GetBytes([System.Windows.Forms.Clipboard]::GetText()); " +
991
+ "$stdout = [Console]::OpenStandardOutput(); $stdout.Write($bytes, 0, $bytes.Length); $stdout.Flush(); exit 0";
992
+ const PS_CLEAR_CLIP =
993
+ "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::Clear(); exit 0";
994
+
885
995
  /** Whether an executable is on PATH, so a Wayland session can fall back to X11. */
886
996
  function commandExists(command: string): boolean {
887
997
  for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
@@ -896,15 +1006,25 @@ function commandExists(command: string): boolean {
896
1006
  return false;
897
1007
  }
898
1008
 
899
- function clipboardBackend(): ClipboardBackend | undefined {
1009
+ export function clipboardBackend(): ClipboardBackend | undefined {
1010
+ if (WIN32) {
1011
+ const powershell = systemFile("System32", "WindowsPowerShell", "v1.0", "powershell.exe");
1012
+ return {
1013
+ copy: [powershell, [...PS_CLIP_ARGS, PS_SET_CLIP]],
1014
+ clear: [powershell, [...PS_CLIP_ARGS, PS_CLEAR_CLIP]],
1015
+ read: [powershell, [...PS_CLIP_ARGS, PS_GET_CLIP]],
1016
+ lingers: false,
1017
+ };
1018
+ }
900
1019
  if (process.platform === "darwin") {
901
- return { copy: ["pbcopy", []], clear: ["pbcopy", []], read: ["pbpaste", []] };
1020
+ return { copy: ["pbcopy", []], clear: ["pbcopy", []], read: ["pbpaste", []], lingers: false };
902
1021
  }
903
1022
  if (process.env.WAYLAND_DISPLAY && commandExists("wl-copy") && commandExists("wl-paste")) {
904
1023
  return {
905
1024
  copy: ["wl-copy", []],
906
1025
  clear: ["wl-copy", ["-c"]],
907
1026
  read: ["wl-paste", ["--no-newline"]],
1027
+ lingers: true,
908
1028
  };
909
1029
  }
910
1030
  if (process.env.DISPLAY && commandExists("xclip")) {
@@ -912,6 +1032,7 @@ function clipboardBackend(): ClipboardBackend | undefined {
912
1032
  copy: ["xclip", ["-selection", "clipboard"]],
913
1033
  clear: ["xclip", ["-selection", "clipboard", "/dev/null"]],
914
1034
  read: ["xclip", ["-selection", "clipboard", "-o"]],
1035
+ lingers: true,
915
1036
  };
916
1037
  }
917
1038
  return undefined;
@@ -935,17 +1056,19 @@ function clipboardMatches(current: string, value: string): boolean {
935
1056
 
936
1057
  async function copyToClipboard(value: string): Promise<void> {
937
1058
  const backend = clipboardBackend();
938
- if (!backend) throw new Error("No clipboard available (need Wayland, X11, or macOS).");
1059
+ if (!backend) throw new Error("No clipboard available (need Wayland, X11, macOS, or Windows PowerShell).");
939
1060
  const drops = clipboardDrops;
940
1061
  const [cmd, args] = backend.copy;
941
1062
  const { promise, resolve, reject } = Promise.withResolvers<void>();
942
- // wl-copy/xclip stay alive to own the selection; a quick clean exit also means success.
943
- const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "pipe"], detached: true, env: childEnv() });
1063
+ // A backend that owns the selection stays alive, detached from this process.
1064
+ const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "pipe"], detached: backend.lingers, env: childEnv(), windowsHide: true });
944
1065
  let settled = false;
945
1066
  let stderr = "";
1067
+ const watchdog = setTimeout(() => finish(new Error(`${cmd} did not finish`)), COPY_TIMEOUT_MS);
946
1068
  const finish = (err?: Error) => {
947
1069
  if (settled) return;
948
1070
  settled = true;
1071
+ clearTimeout(watchdog);
949
1072
  if (err) reject(err);
950
1073
  else {
951
1074
  child.unref();
@@ -965,7 +1088,10 @@ async function copyToClipboard(value: string): Promise<void> {
965
1088
  return;
966
1089
  }
967
1090
  child.stdin?.end();
968
- setTimeout(() => finish(), 500);
1091
+ // A backend that owns the selection never exits: after a moment without an
1092
+ // error, the value is in place. Every other backend is waited for, so that
1093
+ // a copy that failed is reported and never looks like success.
1094
+ if (backend.lingers) setTimeout(() => finish(), 500);
969
1095
  });
970
1096
  clipboardPending = value;
971
1097
  try {
@@ -1028,13 +1154,13 @@ function clearClipboardSync(): void {
1028
1154
  clipboardPending = undefined;
1029
1155
  if (!value || !backend) return;
1030
1156
  try {
1031
- const r = spawnSync(backend.read[0], backend.read[1], { encoding: "utf8", timeout: 1000, env: childEnv() });
1157
+ const r = spawnSync(backend.read[0], backend.read[1], { encoding: "utf8", timeout: WIN32 ? 3000 : 1000, env: childEnv(), windowsHide: true });
1032
1158
  if (r.status === 0 && typeof r.stdout === "string" && r.stdout.length > 0 && !clipboardMatches(r.stdout, value)) return;
1033
1159
  } catch {
1034
1160
  /* clear anyway */
1035
1161
  }
1036
1162
  try {
1037
- spawnSync(backend.clear[0], backend.clear[1], { input: "", timeout: 2000, env: childEnv() });
1163
+ spawnSync(backend.clear[0], backend.clear[1], { input: "", timeout: WIN32 ? 3000 : 2000, env: childEnv(), windowsHide: true });
1038
1164
  } catch {
1039
1165
  /* best-effort */
1040
1166
  }
@@ -1315,7 +1441,8 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
1315
1441
  if (!approved) throw new Error("User declined the command.");
1316
1442
  const { value, itemName } = await secretOf(approved.session, approved.item, field, signal);
1317
1443
  rememberScrubValue(envName, value);
1318
- const r = await exec("bash", ["-c", params.command], {
1444
+ const bash = resolveBash();
1445
+ const r = await exec(bash.program, [...bash.pre, "-c", params.command], {
1319
1446
  env: { [envName]: value },
1320
1447
  cwd,
1321
1448
  timeout: seconds * 1000,
@@ -8,10 +8,11 @@
8
8
  * dialog takes over here.
9
9
  */
10
10
  import { createHmac, randomBytes } from "node:crypto";
11
- import { spawn } from "node:child_process";
12
- import { existsSync } from "node:fs";
11
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
+ import { existsSync, readFileSync } from "node:fs";
13
+ import { createRequire } from "node:module";
13
14
  import { homedir } from "node:os";
14
- import { delimiter, dirname, join } from "node:path";
15
+ import { delimiter, dirname, extname, join } from "node:path";
15
16
  import { lang } from "./i18n.js";
16
17
  import { fileURLToPath } from "node:url";
17
18
 
@@ -58,45 +59,132 @@ export class CliError extends Error {
58
59
  }
59
60
  }
60
61
 
62
+ /** How to start the CLI: a program, plus what has to precede our arguments. */
63
+ export interface CliLaunch {
64
+ program: string;
65
+ pre: string[];
66
+ }
67
+
68
+ const WIN32 = process.platform === "win32";
69
+ /** The file npm links for the bin: an `.exe` where there is one, else its `.cmd` wrapper. */
70
+ const BIN_NAMES = WIN32 ? ["ai-vault.exe", "ai-vault.cmd"] : ["ai-vault"];
71
+
61
72
  /**
62
- * `AI_VAULT_BIN`, then the copy this package depends on (npm puts the shim in
63
- * a node_modules/.bin next to or above the plugin), then PATH, then the usual
64
- * install spots.
73
+ * What an npm `.cmd` wrapper starts, so that that can be started instead.
74
+ *
75
+ * npm links a package's bin as a sh script, a `.cmd` and a `.ps1` beside the
76
+ * real thing. Node refuses to run any of them without a shell on Windows
77
+ * (`spawn EINVAL`), and a shell would hand every argument to cmd.exe's parser.
78
+ * A `.cmd` is a fixed format, though; it ends with
79
+ *
80
+ * "%_prog%" "%dp0%\node_modules\pkg\bin\tool.js" %*
81
+ *
82
+ * so it is read, and what it names is started directly: a script with this
83
+ * very Node, anything else as the program it is.
65
84
  */
66
- export function resolveBinary(): string | undefined {
85
+ export function npmShimLaunch(shim: string): CliLaunch | undefined {
86
+ let text: string;
87
+ try {
88
+ text = readFileSync(shim, "utf8");
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ const target = /"%dp0%([^"\r\n]+)"\s*%\*/.exec(text)?.[1];
93
+ if (!target) return undefined;
94
+ const wrapped = join(dirname(shim), target);
95
+ if (!existsSync(wrapped)) return undefined;
96
+ return /\.[cm]?js$/i.test(wrapped) ? { program: process.execPath, pre: [wrapped] } : { program: wrapped, pre: [] };
97
+ }
98
+
99
+ /** A file that was found, as something `spawn` can start. */
100
+ function launchOf(candidate: string): CliLaunch | undefined {
101
+ if (!existsSync(candidate)) return undefined;
102
+ if (!WIN32) return { program: candidate, pre: [] };
103
+ const ext = extname(candidate).toLowerCase();
104
+ if (ext === ".exe" || ext === ".com") return { program: candidate, pre: [] };
105
+ if (ext === ".cmd" || ext === ".bat") return npmShimLaunch(candidate);
106
+ return undefined; // the sh script and the .ps1 need a shell as well
107
+ }
108
+
109
+ /**
110
+ * The prebuilt binary that came with this package: `@xiaolikt/ai-vault`
111
+ * depends on `@xiaolikt/ai-vault-<os>-<arch>`, resolved by Node from here, so
112
+ * a hoisted and a nested node_modules layout both work.
113
+ */
114
+ function platformBinary(): CliLaunch | undefined {
115
+ const id = `@xiaolikt/ai-vault-${process.platform}-${process.arch}/package.json`;
116
+ try {
117
+ const manifest = createRequire(import.meta.url).resolve(id);
118
+ const binary = join(dirname(manifest), "bin", WIN32 ? "ai-vault.exe" : "ai-vault");
119
+ return existsSync(binary) ? { program: binary, pre: [] } : undefined;
120
+ } catch {
121
+ return undefined; // no prebuilt binary for this platform
122
+ }
123
+ }
124
+
125
+ /**
126
+ * `AI_VAULT_BIN`, then the prebuilt binary that came with this package, then
127
+ * the wrappers npm links in a node_modules/.bin next to or above the plugin,
128
+ * then PATH, then the usual install spots.
129
+ *
130
+ * On Windows the program is always a real executable: a wrapper is unwrapped
131
+ * to what it starts, never handed to `spawn` as it is.
132
+ */
133
+ export function resolveLaunch(): CliLaunch | undefined {
67
134
  const explicit = process.env.AI_VAULT_BIN;
68
- if (explicit) return existsSync(explicit) ? explicit : undefined;
135
+ if (explicit) return launchOf(explicit);
136
+
137
+ const bundled = platformBinary();
138
+ if (bundled) return bundled;
69
139
 
70
- // pip/npm layouts hoist differently: walk up from packages/pi-ai-vault/src.
140
+ // npm layouts hoist differently: walk up from packages/pi-ai-vault/src.
71
141
  let dir = dirname(fileURLToPath(import.meta.url));
72
142
  for (let depth = 0; depth < 5; depth++) {
73
- for (const name of process.platform === "win32" ? ["ai-vault.exe", "ai-vault.cmd", "ai-vault.ps1"] : ["ai-vault"]) {
74
- const bundled = join(dir, "node_modules", ".bin", name);
75
- if (existsSync(bundled)) return bundled;
143
+ for (const name of BIN_NAMES) {
144
+ const found = launchOf(join(dir, "node_modules", ".bin", name));
145
+ if (found) return found;
76
146
  }
77
147
  const parent = dirname(dir);
78
148
  if (parent === dir) break;
79
149
  dir = parent;
80
150
  }
81
151
 
82
- // Windows has no execute bit and npm links .cmd/.ps1 wrappers beside the exe.
83
- const names = process.platform === "win32" ? ["ai-vault.exe", "ai-vault.cmd", "ai-vault.ps1", "ai-vault"] : ["ai-vault"];
84
152
  for (const entry of (process.env.PATH ?? "").split(delimiter)) {
85
153
  if (!entry) continue;
86
- for (const name of names) {
87
- const candidate = join(entry, name);
88
- if (existsSync(candidate)) return candidate;
154
+ for (const name of BIN_NAMES) {
155
+ const found = launchOf(join(entry, name));
156
+ if (found) return found;
89
157
  }
90
158
  }
91
159
  for (const base of [join(homedir(), ".local", "bin"), join(homedir(), ".cargo", "bin"), join(homedir(), ".ai-vault", "bin")]) {
92
- for (const name of names) {
93
- const candidate = join(base, name);
94
- if (existsSync(candidate)) return candidate;
160
+ for (const name of BIN_NAMES) {
161
+ const found = launchOf(join(base, name));
162
+ if (found) return found;
95
163
  }
96
164
  }
97
165
  return undefined;
98
166
  }
99
167
 
168
+ /** The program `resolveLaunch()` would start, for messages and the like. */
169
+ export function resolveBinary(): string | undefined {
170
+ return resolveLaunch()?.program;
171
+ }
172
+
173
+ /**
174
+ * Start one CLI call. A program Node will not start is reported through
175
+ * `CliError` like every other failure, not thrown from inside the promise.
176
+ */
177
+ function startCli(launch: CliLaunch, args: string[], env: NodeJS.ProcessEnv): ChildProcessWithoutNullStreams {
178
+ try {
179
+ // windowsHide: the CLI is a console program, and gets no window of its
180
+ // own when the host has none. The dialogs it opens are windows it opens
181
+ // on purpose, and show regardless.
182
+ return spawn(launch.program, [...launch.pre, ...args], { stdio: ["pipe", "pipe", "pipe"], env, windowsHide: true });
183
+ } catch (error) {
184
+ throw new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${error instanceof Error ? error.message : String(error)}`, "");
185
+ }
186
+ }
187
+
100
188
  const NEEDS_UI = /^needs-ui:\s*(\w+)(?:\s+field=(\S+))?/m;
101
189
 
102
190
  function message(stderr: string, fallback: string): string {
@@ -152,7 +240,9 @@ export class HostSecret {
152
240
  }
153
241
 
154
242
  export class VaultCli {
155
- readonly bin = resolveBinary();
243
+ private readonly launch = resolveLaunch();
244
+ /** The program that gets started: `AI_VAULT_BIN` when that was set. */
245
+ readonly bin = this.launch?.program;
156
246
  /** Set by the extension at startup; the same secret for every binding. */
157
247
  host = new HostSecret();
158
248
 
@@ -166,15 +256,17 @@ export class VaultCli {
166
256
  }
167
257
 
168
258
  async run(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<CliRun> {
169
- const bin = this.bin;
170
- if (!bin) {
259
+ const launch = this.launch;
260
+ if (!launch) {
171
261
  throw new CliError(EXIT.error, undefined, "ai-vault CLI not found", "");
172
262
  }
173
263
  if (opts.signal?.aborted) {
174
264
  throw new CliError(EXIT.denied, undefined, "aborted", "");
175
265
  }
176
266
  const run = await new Promise<CliRun>((resolve, reject) => {
177
- const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...this.host.env() } });
267
+ // A program Node will not start fails here like any other CLI failure,
268
+ // not as a bare exception from inside the promise.
269
+ const child = startCli(launch, args, { ...process.env, ...this.host.env() });
178
270
  let stdout = "";
179
271
  let stderr = "";
180
272
  const onAbort = () => child.kill("SIGKILL");
@@ -187,7 +279,7 @@ export class VaultCli {
187
279
  });
188
280
  child.on("error", (error) => {
189
281
  opts.signal?.removeEventListener("abort", onAbort);
190
- reject(new CliError(EXIT.error, undefined, `cannot run ${bin}: ${error.message}`, ""));
282
+ reject(new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${error.message}`, ""));
191
283
  });
192
284
  child.on("close", (code) => {
193
285
  opts.signal?.removeEventListener("abort", onAbort);
@@ -57,8 +57,11 @@ export function resolveEnte(): string | undefined {
57
57
  if (explicit) return existsSync(explicit) ? explicit : undefined;
58
58
  for (const dir of (process.env.PATH ?? "").split(delimiter)) {
59
59
  if (!dir) continue;
60
- const candidate = join(dir, "ente");
61
- if (existsSync(candidate)) return candidate;
60
+ // Windows: the program is ente.exe; the bare name matches no file there.
61
+ for (const name of process.platform === "win32" ? ["ente.exe", "ente"] : ["ente"]) {
62
+ const candidate = join(dir, name);
63
+ if (existsSync(candidate)) return candidate;
64
+ }
62
65
  }
63
66
  for (const candidate of [
64
67
  join(homedir(), ".local", "opt", "ente-cli", "bin", "ente"),