@cyfsh/discovery 0.3.5 → 0.3.7

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.
@@ -1,5 +1,7 @@
1
+ import { execFileSync } from "node:child_process";
1
2
  import * as fs from "node:fs";
2
3
  import * as fsp from "node:fs/promises";
4
+ import * as os from "node:os";
3
5
  import * as path from "node:path";
4
6
  import { buildSanitizedCapsule, redactSecrets } from "../sanitizer.js";
5
7
  export function isJsonRecord(value) {
@@ -260,7 +262,261 @@ export async function runWithConcurrency(items, concurrency, worker) {
260
262
  };
261
263
  await Promise.all(Array.from({ length: laneCount }, () => runLane()));
262
264
  }
263
- function resolveDashSegmentsOnDisk(rootPrefix, rawRest) {
265
+ const IGNORED_WSL_DISTROS = new Set([
266
+ "docker-desktop",
267
+ "docker-desktop-data",
268
+ "rancher-desktop",
269
+ "rancher-desktop-data",
270
+ "podman-machine-default",
271
+ ]);
272
+ function parseConfiguredWslRootsEnv() {
273
+ const raw = process.env.CYF_WSL_ROOTS?.trim();
274
+ if (!raw) {
275
+ return [];
276
+ }
277
+ const items = [];
278
+ for (const token of raw.split(/[;|]/)) {
279
+ const trimmed = token.trim();
280
+ if (!trimmed)
281
+ continue;
282
+ const eqIdx = trimmed.indexOf("=");
283
+ if (eqIdx > 0) {
284
+ const distro = trimmed.slice(0, eqIdx).trim();
285
+ const rootDir = trimmed.slice(eqIdx + 1).trim();
286
+ if (distro && rootDir) {
287
+ items.push({ distro, uncRoot: path.resolve(rootDir) });
288
+ }
289
+ }
290
+ else {
291
+ const resolved = path.resolve(trimmed);
292
+ items.push({ distro: path.basename(resolved) || "WSL", uncRoot: resolved });
293
+ }
294
+ }
295
+ return items;
296
+ }
297
+ let cachedWslDiscovery = null;
298
+ function enumerateHostWslDistroNames() {
299
+ if (process.platform !== "win32") {
300
+ return [];
301
+ }
302
+ const names = [];
303
+ const seen = new Set();
304
+ const addName = (raw) => {
305
+ const cleaned = raw.replace(/\0/g, "").replace(/^\uFEFF/, "").trim();
306
+ if (!cleaned)
307
+ return;
308
+ const lower = cleaned.toLowerCase();
309
+ if (IGNORED_WSL_DISTROS.has(lower) || seen.has(lower))
310
+ return;
311
+ seen.add(lower);
312
+ names.push(cleaned);
313
+ };
314
+ // 1. Fast non-blocking Registry lookup (~20ms, never cold-boots stopped WSL VMs)
315
+ try {
316
+ const regOut = execFileSync("reg.exe", [
317
+ "query",
318
+ "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss",
319
+ "/s",
320
+ "/v",
321
+ "DistributionName",
322
+ ], { encoding: "utf8", timeout: 1500, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
323
+ for (const match of regOut.matchAll(/DistributionName\s+REG_SZ\s+([^\r\n]+)/gi)) {
324
+ if (match[1])
325
+ addName(match[1]);
326
+ }
327
+ }
328
+ catch {
329
+ // Fall through to wsl.exe -l -q
330
+ }
331
+ // 2. Fallback to `wsl.exe --list --quiet` (UTF-16LE output on Windows)
332
+ if (names.length === 0) {
333
+ try {
334
+ const wslOut = execFileSync("wsl.exe", ["--list", "--quiet"], {
335
+ encoding: "utf16le",
336
+ timeout: 2000,
337
+ windowsHide: true,
338
+ stdio: ["ignore", "pipe", "ignore"],
339
+ });
340
+ for (const line of wslOut.split(/\r?\n/)) {
341
+ addName(line);
342
+ }
343
+ }
344
+ catch {
345
+ // WSL not installed or unavailable
346
+ }
347
+ }
348
+ return names;
349
+ }
350
+ function collectHomesUnderWslRoot(distro, uncRoot) {
351
+ const found = [];
352
+ const seenHomes = new Set();
353
+ const pushHome = (posixHome, uncHome) => {
354
+ const key = uncHome.toLowerCase();
355
+ if (seenHomes.has(key))
356
+ return;
357
+ seenHomes.add(key);
358
+ found.push({ distro, uncRoot, posixHome, uncHome });
359
+ };
360
+ const homeParent = path.join(uncRoot, "home");
361
+ try {
362
+ const entries = fs.readdirSync(homeParent, { withFileTypes: true });
363
+ for (const entry of entries) {
364
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
365
+ continue;
366
+ if (entry.name.startsWith(".") || entry.name === "lost+found")
367
+ continue;
368
+ const userUnc = path.join(homeParent, entry.name);
369
+ try {
370
+ if (fs.statSync(userUnc).isDirectory()) {
371
+ pushHome(`/home/${entry.name}`, userUnc);
372
+ }
373
+ }
374
+ catch {
375
+ // Skip unreadable home directory
376
+ }
377
+ }
378
+ }
379
+ catch {
380
+ // `/home` missing or inaccessible
381
+ }
382
+ // Also check `/root` when readable (e.g. root-default Debian/Alpine/Ubuntu WSL distros); gracefully ignore EPERM
383
+ const rootUnc = path.join(uncRoot, "root");
384
+ try {
385
+ if (fs.statSync(rootUnc).isDirectory()) {
386
+ fs.readdirSync(rootUnc);
387
+ pushHome("/root", rootUnc);
388
+ }
389
+ }
390
+ catch {
391
+ // EPERM when default WSL user is non-root — expected and ignored
392
+ }
393
+ return found;
394
+ }
395
+ /**
396
+ * Discovers user home directories inside installed WSL distributions on Windows
397
+ * (or deterministic `CYF_WSL_ROOTS` overrides in tests/custom environments).
398
+ */
399
+ export function discoverWslDistroHomes() {
400
+ if (process.env.CYF_DISABLE_WSL === "1") {
401
+ return [];
402
+ }
403
+ const envRoots = parseConfiguredWslRootsEnv();
404
+ const isAutomatedTest = process.env.VITEST === "true" || process.env.NODE_ENV === "test";
405
+ if (envRoots.length === 0 && (process.platform !== "win32" || isAutomatedTest)) {
406
+ return [];
407
+ }
408
+ const cacheKey = `${process.platform}|${process.env.CYF_WSL_ROOTS ?? ""}`;
409
+ const now = Date.now();
410
+ if (cachedWslDiscovery &&
411
+ cachedWslDiscovery.cacheKey === cacheKey &&
412
+ now < cachedWslDiscovery.expiresAt) {
413
+ return cachedWslDiscovery.entries;
414
+ }
415
+ const entries = [];
416
+ if (envRoots.length > 0) {
417
+ for (const { distro, uncRoot } of envRoots) {
418
+ try {
419
+ if (fs.statSync(uncRoot).isDirectory()) {
420
+ entries.push(...collectHomesUnderWslRoot(distro, uncRoot));
421
+ }
422
+ }
423
+ catch {
424
+ // Ignore missing override root
425
+ }
426
+ }
427
+ }
428
+ else {
429
+ for (const distro of enumerateHostWslDistroNames()) {
430
+ for (const prefix of [`\\\\wsl.localhost\\${distro}`, `\\\\wsl$\\${distro}`]) {
431
+ try {
432
+ if (fs.statSync(prefix).isDirectory()) {
433
+ entries.push(...collectHomesUnderWslRoot(distro, prefix));
434
+ break;
435
+ }
436
+ }
437
+ catch {
438
+ // Try next UNC prefix
439
+ }
440
+ }
441
+ }
442
+ }
443
+ cachedWslDiscovery = {
444
+ cacheKey,
445
+ expiresAt: now + 30_000,
446
+ entries,
447
+ };
448
+ return entries;
449
+ }
450
+ export function parseWslUncRoot(targetPath) {
451
+ if (!targetPath) {
452
+ return null;
453
+ }
454
+ const clean = targetPath
455
+ .replace(/^\\\\\?\\UNC\\/i, "\\\\")
456
+ .replace(/^\\\\\?\\/, "");
457
+ const uncMatch = /^(?:\\\\|\/\/)(wsl\.localhost|wsl\$)[\\/]([^\\/]+)(?:[\\/](.*))?$/i.exec(clean);
458
+ if (uncMatch && uncMatch[1] && uncMatch[2]) {
459
+ const host = uncMatch[1];
460
+ const distro = uncMatch[2];
461
+ const rest = uncMatch[3] ?? "";
462
+ return {
463
+ distro,
464
+ uncRoot: `\\\\${host}\\${distro}`,
465
+ posixSubpath: `/${rest.replace(/\\/g, "/").replace(/^\/+/, "")}`,
466
+ };
467
+ }
468
+ for (const { distro, uncRoot } of parseConfiguredWslRootsEnv()) {
469
+ const normRoot = path.resolve(uncRoot);
470
+ const normTarget = path.resolve(clean);
471
+ const cmpRoot = process.platform === "win32" ? normRoot.toLowerCase() : normRoot;
472
+ const cmpTarget = process.platform === "win32" ? normTarget.toLowerCase() : normTarget;
473
+ if (cmpTarget === cmpRoot || cmpTarget.startsWith(cmpRoot + path.sep)) {
474
+ const rel = normTarget.slice(normRoot.length).replace(/\\/g, "/");
475
+ return {
476
+ distro,
477
+ uncRoot: normRoot,
478
+ posixSubpath: rel.startsWith("/") ? rel : `/${rel}`,
479
+ };
480
+ }
481
+ }
482
+ return null;
483
+ }
484
+ /**
485
+ * Normalizes `workspacePath` when a session originates inside WSL:
486
+ * - `/mnt/<drive>/foo/bar` -> `<DRIVE>:/foo/bar`
487
+ * - `/home/<user>/repo` -> `\\wsl.localhost\<Distro>\home\<user>\repo`
488
+ */
489
+ export function normalizeSessionWorkspacePath(rawWorkspacePath, sourceFilePath) {
490
+ const trimmed = rawWorkspacePath.trim();
491
+ if (!trimmed || trimmed === "/unknown-workspace") {
492
+ return "/unknown-workspace";
493
+ }
494
+ const wslInfo = sourceFilePath ? parseWslUncRoot(sourceFilePath) : null;
495
+ if (!wslInfo) {
496
+ return trimmed;
497
+ }
498
+ const normUnc = wslInfo.uncRoot.replace(/\\/g, "/").replace(/\/+$/, "");
499
+ const normTrimmed = trimmed.replace(/\\/g, "/");
500
+ if (normTrimmed === normUnc ||
501
+ normTrimmed.startsWith(`${normUnc}/`) ||
502
+ (process.platform === "win32" &&
503
+ (normTrimmed.toLowerCase() === normUnc.toLowerCase() ||
504
+ normTrimmed.toLowerCase().startsWith(`${normUnc.toLowerCase()}/`)))) {
505
+ return trimmed;
506
+ }
507
+ const mntMatch = /^\/mnt\/([a-zA-Z])(?:\/(.*))?$/.exec(trimmed);
508
+ if (mntMatch && mntMatch[1]) {
509
+ const drive = mntMatch[1].toUpperCase();
510
+ const rest = (mntMatch[2] ?? "").replace(/\/+$/, "");
511
+ return rest ? `${drive}:/${rest}` : `${drive}:/`;
512
+ }
513
+ if (trimmed.startsWith("/") && !trimmed.startsWith("//")) {
514
+ const parts = trimmed.split("/").filter(Boolean);
515
+ return parts.length > 0 ? path.join(wslInfo.uncRoot, ...parts) : wslInfo.uncRoot;
516
+ }
517
+ return trimmed;
518
+ }
519
+ function resolveDashSegmentsOnDisk(rootPrefix, rawRest, preserveNativeSlashes = false) {
264
520
  const parts = rawRest.split("-").filter(Boolean);
265
521
  if (parts.length === 0) {
266
522
  return null;
@@ -293,24 +549,27 @@ function resolveDashSegmentsOnDisk(rootPrefix, rawRest) {
293
549
  i += 1;
294
550
  }
295
551
  }
296
- return fs.existsSync(current) ? current.replace(/\\/g, "/") : null;
552
+ if (!fs.existsSync(current)) {
553
+ return null;
554
+ }
555
+ return preserveNativeSlashes ? current : current.replace(/\\/g, "/");
297
556
  }
298
557
  catch {
299
558
  return null;
300
559
  }
301
560
  }
302
561
  /**
303
- * Decodes mangled workspace folder names used by Claude Code (`-Users-alice-app`)
562
+ * Decodes mangled workspace folder names used by Claude Code (`-Users-alice-app`, `-home-alice-app`)
304
563
  * and CodeBuddy (`C--Codes-app`, `c-Codes-ai-app`, or `%2FUsers%2Falice%2Fapp`) when JSONL lines omit `cwd`.
305
564
  */
306
- export function decodeEncodedCwd(encodedDirName) {
565
+ export function decodeEncodedCwd(encodedDirName, sourceFilePath) {
307
566
  const trimmed = encodedDirName.trim();
308
567
  if (!trimmed) {
309
568
  return "";
310
569
  }
311
570
  if (/%2f|%5c|%3a/i.test(trimmed)) {
312
571
  try {
313
- return decodeURIComponent(trimmed);
572
+ return normalizeSessionWorkspacePath(decodeURIComponent(trimmed), sourceFilePath);
314
573
  }
315
574
  catch {
316
575
  // Ignore malformed URI sequence and fall through
@@ -338,6 +597,16 @@ export function decodeEncodedCwd(encodedDirName) {
338
597
  }
339
598
  if (trimmed.startsWith("-")) {
340
599
  const rest = trimmed.slice(1);
600
+ const wslInfo = sourceFilePath ? parseWslUncRoot(sourceFilePath) : null;
601
+ if (wslInfo) {
602
+ const wslResolved = resolveDashSegmentsOnDisk(wslInfo.uncRoot, rest, true);
603
+ if (wslResolved) {
604
+ return normalizeSessionWorkspacePath(wslResolved.startsWith(wslInfo.uncRoot)
605
+ ? `/${wslResolved.slice(wslInfo.uncRoot.length).replace(/\\/g, "/").replace(/^\/+/, "")}`
606
+ : wslResolved, sourceFilePath);
607
+ }
608
+ return normalizeSessionWorkspacePath(`/${rest.replace(/-/g, "/")}`, sourceFilePath);
609
+ }
341
610
  return resolveDashSegmentsOnDisk("/", rest) ?? `/${rest.replace(/-/g, "/")}`;
342
611
  }
343
612
  return trimmed;
@@ -706,7 +975,7 @@ export function finalizeSessionSummary(params) {
706
975
  if (msgCount === 0 && canonicalMessages.length === 0) {
707
976
  return null;
708
977
  }
709
- const normalizedWorkspace = params.workspacePath.trim().length > 0 ? params.workspacePath.trim() : "/unknown-workspace";
978
+ const normalizedWorkspace = normalizeSessionWorkspacePath(params.workspacePath.trim().length > 0 ? params.workspacePath.trim() : "/unknown-workspace", params.sourcePath);
710
979
  const workspaceName = extractWorkspaceName(normalizedWorkspace);
711
980
  const firstMsg = canonicalMessages[0];
712
981
  const lastMsg = canonicalMessages[canonicalMessages.length - 1];
@@ -871,15 +1140,312 @@ export async function safeStatDates(filePath) {
871
1140
  return { createdAt: nowIso, updatedAt: nowIso };
872
1141
  }
873
1142
  }
1143
+ const CLI_BINARY_ENV_OVERRIDES = {
1144
+ claude: ["CE_CLAUDE_CLI_PATH", "CE_CLAUDE_BIN", "CLAUDE_BIN"],
1145
+ codex: ["CE_CODEX_BIN", "CODEX_BIN"],
1146
+ opencode: ["CE_OPENCODE_BIN", "OPENCODE_BIN"],
1147
+ dsh: ["CE_DSH_BIN", "DSH_BIN"],
1148
+ codebuddy: ["CE_CODEBUDDY_BIN", "CODEBUDDY_BIN"],
1149
+ };
1150
+ function listSortedSubdirsDesc(parentDir) {
1151
+ if (!parentDir)
1152
+ return [];
1153
+ try {
1154
+ return fs
1155
+ .readdirSync(parentDir, { withFileTypes: true })
1156
+ .filter((e) => e.isDirectory() || e.isSymbolicLink())
1157
+ .map((e) => e.name)
1158
+ .sort((a, b) => b.localeCompare(a, undefined, { numeric: true, sensitivity: "base" }));
1159
+ }
1160
+ catch {
1161
+ return [];
1162
+ }
1163
+ }
1164
+ export function buildPosixCandidateBinDirsForHome(home, binaryName, opts) {
1165
+ const rootPrefix = opts?.rootPrefix ?? "";
1166
+ const sysPath = (...segs) => rootPrefix ? path.join(rootPrefix, ...segs) : `/${segs.join("/")}`;
1167
+ const dirs = [
1168
+ path.join(home, ".local", "bin"),
1169
+ ];
1170
+ if (binaryName === "claude") {
1171
+ dirs.push(path.join(home, ".claude", "local"), path.join(home, ".claude", "local", "node_modules", ".bin"), path.join(home, ".claude", "bin"));
1172
+ }
1173
+ else if (binaryName === "dsh") {
1174
+ dirs.push(path.join(home, ".dsh", "bin"));
1175
+ if (!rootPrefix) {
1176
+ dirs.push("/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin", "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/bin", path.join(home, "Applications", "DeepSeek Harness.app", "Contents", "Resources", "runtime", "cli", "bin"), path.join(home, "Applications", "DeepSeek Harness.app", "Contents", "Resources", "runtime", "bin"));
1177
+ }
1178
+ }
1179
+ else if (binaryName === "codex") {
1180
+ dirs.push(path.join(home, ".codex", "bin"));
1181
+ if (!rootPrefix) {
1182
+ dirs.push("/Applications/Codex.app/Contents/Resources/bin", path.join(home, "Applications", "Codex.app", "Contents", "Resources", "bin"));
1183
+ }
1184
+ }
1185
+ else if (binaryName === "opencode") {
1186
+ dirs.push(path.join(home, ".opencode", "bin"));
1187
+ if (!rootPrefix) {
1188
+ dirs.push("/Applications/OpenCode.app/Contents/Resources/bin", "/Applications/OpenCode.app/Contents/MacOS", path.join(home, "Applications", "OpenCode.app", "Contents", "Resources", "bin"));
1189
+ }
1190
+ }
1191
+ else if (binaryName === "codebuddy") {
1192
+ dirs.push(path.join(home, ".codebuddy", "bin"), path.join(home, ".workbuddy", "bin"));
1193
+ if (!rootPrefix) {
1194
+ dirs.push("/Applications/CodeBuddy.app/Contents/Resources/app.asar.unpacked/cli/bin", "/Applications/CodeBuddy CN.app/Contents/Resources/app.asar.unpacked/cli/bin", "/Applications/WorkBuddy.app/Contents/Resources/app.asar.unpacked/cli/bin", path.join(home, "Applications", "CodeBuddy.app", "Contents", "Resources", "app.asar.unpacked", "cli", "bin"), path.join(home, "Applications", "WorkBuddy.app", "Contents", "Resources", "app.asar.unpacked", "cli", "bin"));
1195
+ }
1196
+ }
1197
+ // Package & runtime version managers (non-interactive daemon PATH safe)
1198
+ if (opts?.pnpmHome) {
1199
+ dirs.push(opts.pnpmHome);
1200
+ }
1201
+ dirs.push(path.join(home, "Library", "pnpm"), path.join(home, ".local", "share", "pnpm"), path.join(home, ".bun", "bin"), path.join(home, ".volta", "bin"), path.join(home, ".npm-global", "bin"), path.join(home, ".npm-packages", "bin"), path.join(home, ".cargo", "bin"), path.join(home, ".local", "share", "mise", "shims"), path.join(home, ".asdf", "shims"), path.join(home, ".nodenv", "shims"), path.join(home, ".n", "bin"), path.join(home, "bin"));
1202
+ // nvm (`$NVM_DIR/versions/node/*/bin` & `~/.nvm/versions/node/*/bin`)
1203
+ const nvmBases = Array.from(new Set([
1204
+ opts?.nvmDir ? path.join(opts.nvmDir, "versions", "node") : "",
1205
+ path.join(home, ".nvm", "versions", "node"),
1206
+ ].filter(Boolean)));
1207
+ for (const nvmBase of nvmBases) {
1208
+ for (const ver of listSortedSubdirsDesc(nvmBase)) {
1209
+ dirs.push(path.join(nvmBase, ver, "bin"));
1210
+ }
1211
+ }
1212
+ // fnm (Linux XDG, macOS Application Support, & ~/.fnm)
1213
+ const fnmBases = Array.from(new Set([
1214
+ opts?.fnmDir ? path.join(opts.fnmDir, "node-versions") : "",
1215
+ path.join(home, ".local", "share", "fnm", "node-versions"),
1216
+ path.join(home, "Library", "Application Support", "fnm", "node-versions"),
1217
+ path.join(home, ".fnm", "node-versions"),
1218
+ ].filter(Boolean)));
1219
+ for (const fnmBase of fnmBases) {
1220
+ for (const ver of listSortedSubdirsDesc(fnmBase)) {
1221
+ dirs.push(path.join(fnmBase, ver, "installation", "bin"));
1222
+ }
1223
+ }
1224
+ // mise & asdf direct node installs (when shims are not regenerated)
1225
+ const miseNodeBase = path.join(home, ".local", "share", "mise", "installs", "node");
1226
+ for (const ver of listSortedSubdirsDesc(miseNodeBase)) {
1227
+ dirs.push(path.join(miseNodeBase, ver, "bin"));
1228
+ }
1229
+ const asdfNodeBase = path.join(home, ".asdf", "installs", "nodejs");
1230
+ for (const ver of listSortedSubdirsDesc(asdfNodeBase)) {
1231
+ dirs.push(path.join(asdfNodeBase, ver, "bin"));
1232
+ }
1233
+ // Homebrew (Apple Silicon + Intel + Linuxbrew) & system locations
1234
+ if (!rootPrefix) {
1235
+ dirs.push("/opt/homebrew/bin");
1236
+ }
1237
+ dirs.push(sysPath("usr", "local", "bin"), sysPath("home", "linuxbrew", ".linuxbrew", "bin"), sysPath("snap", "bin"), sysPath("usr", "bin"), sysPath("bin"));
1238
+ return dirs;
1239
+ }
1240
+ function extraCliInstallDirs(binaryName) {
1241
+ const home = process.env.CYF_HOME_OVERRIDE?.trim() || os.homedir();
1242
+ if (process.platform !== "win32") {
1243
+ return buildPosixCandidateBinDirsForHome(home, binaryName, {
1244
+ ...(process.env.NVM_DIR ? { nvmDir: process.env.NVM_DIR } : {}),
1245
+ ...(process.env.FNM_DIR ? { fnmDir: process.env.FNM_DIR } : {}),
1246
+ ...(process.env.PNPM_HOME ? { pnpmHome: process.env.PNPM_HOME } : {}),
1247
+ });
1248
+ }
1249
+ const dirs = [path.join(home, ".local", "bin")];
1250
+ const localAppData = process.env.LOCALAPPDATA ?? path.join(home, "AppData", "Local");
1251
+ const appData = process.env.APPDATA ?? path.join(home, "AppData", "Roaming");
1252
+ const progFiles = process.env.ProgramFiles;
1253
+ const programData = process.env.ProgramData;
1254
+ if (process.env.PNPM_HOME) {
1255
+ dirs.push(process.env.PNPM_HOME);
1256
+ }
1257
+ dirs.push(path.join(appData, "npm"), path.join(appData, "pnpm"), path.join(localAppData, "pnpm"), path.join(localAppData, "Volta", "bin"), path.join(home, ".volta", "bin"), path.join(home, ".bun", "bin"), path.join(home, "scoop", "shims"), path.join(home, ".cargo", "bin"));
1258
+ if (process.env.NVM_SYMLINK) {
1259
+ dirs.push(process.env.NVM_SYMLINK);
1260
+ }
1261
+ const sysDrive = process.env.SystemDrive ?? "C:";
1262
+ dirs.push(path.join(`${sysDrive}\\`, "nvm4w", "nodejs"));
1263
+ if (progFiles) {
1264
+ dirs.push(path.join(progFiles, "nodejs"));
1265
+ }
1266
+ // nvm-windows & fnm on Windows
1267
+ const winNvmRoots = Array.from(new Set([
1268
+ process.env.NVM_HOME ?? "",
1269
+ path.join(appData, "nvm"),
1270
+ path.join(localAppData, "nvm"),
1271
+ programData ? path.join(programData, "nvm") : "",
1272
+ ].filter(Boolean)));
1273
+ for (const nvmRoot of winNvmRoots) {
1274
+ for (const ver of listSortedSubdirsDesc(nvmRoot)) {
1275
+ dirs.push(path.join(nvmRoot, ver));
1276
+ }
1277
+ }
1278
+ const winFnmRoots = Array.from(new Set([
1279
+ process.env.FNM_DIR ? path.join(process.env.FNM_DIR, "node-versions") : "",
1280
+ path.join(appData, "fnm", "node-versions"),
1281
+ path.join(localAppData, "fnm", "node-versions"),
1282
+ path.join(home, ".fnm", "node-versions"),
1283
+ ].filter(Boolean)));
1284
+ for (const fnmRoot of winFnmRoots) {
1285
+ for (const ver of listSortedSubdirsDesc(fnmRoot)) {
1286
+ dirs.push(path.join(fnmRoot, ver, "installation"));
1287
+ }
1288
+ }
1289
+ if (binaryName === "claude") {
1290
+ dirs.push(path.join(home, ".claude", "local"), path.join(home, ".claude", "bin"));
1291
+ }
1292
+ else if (binaryName === "dsh") {
1293
+ dirs.push(path.join(localAppData, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin"), path.join(localAppData, "Programs", "DeepSeek Harness", "resources", "runtime", "bin"), ...(progFiles
1294
+ ? [
1295
+ path.join(progFiles, "DeepSeek Harness", "resources", "runtime", "cli", "bin"),
1296
+ path.join(progFiles, "DeepSeek Harness", "resources", "runtime", "bin"),
1297
+ ]
1298
+ : []), path.join(home, ".dsh", "bin"));
1299
+ }
1300
+ else if (binaryName === "codex") {
1301
+ dirs.push(path.join(localAppData, "Programs", "OpenAI", "Codex", "bin"), path.join(home, ".codex", "bin"));
1302
+ }
1303
+ else if (binaryName === "opencode") {
1304
+ dirs.push(path.join(home, ".opencode", "bin"));
1305
+ }
1306
+ else if (binaryName === "codebuddy") {
1307
+ dirs.push(path.join(localAppData, "codebuddy", "bin"), path.join(localAppData, "Programs", "CodeBuddy", "resources", "app.asar.unpacked", "cli", "bin"), path.join(localAppData, "Programs", "WorkBuddy", "resources", "app.asar.unpacked", "cli", "bin"), path.join(home, ".codebuddy", "bin"), path.join(home, ".workbuddy", "bin"));
1308
+ }
1309
+ return dirs;
1310
+ }
1311
+ function isWslFileOrSymlinkValid(uncCandidate, uncRoot) {
1312
+ try {
1313
+ if (fs.statSync(uncCandidate).isFile()) {
1314
+ return true;
1315
+ }
1316
+ }
1317
+ catch {
1318
+ // Absolute Linux symlinks over Windows 9P (`\\wsl.localhost\...`) fail statSync because Windows
1319
+ // resolves `/target` against `C:\target` instead of `uncRoot\target`; inspect via lstatSync + readlinkSync.
1320
+ try {
1321
+ const lstat = fs.lstatSync(uncCandidate);
1322
+ if (lstat.isSymbolicLink()) {
1323
+ const target = fs.readlinkSync(uncCandidate);
1324
+ if (target.startsWith("/")) {
1325
+ const mapped = path.join(uncRoot, ...target.split("/").filter(Boolean));
1326
+ return fs.statSync(mapped).isFile();
1327
+ }
1328
+ const relMapped = path.resolve(path.dirname(uncCandidate), target);
1329
+ return fs.statSync(relMapped).isFile();
1330
+ }
1331
+ }
1332
+ catch {
1333
+ return false;
1334
+ }
1335
+ }
1336
+ return false;
1337
+ }
1338
+ export function detectWslCliBinary(binaryName, preferredDistro) {
1339
+ if (!/^[a-zA-Z0-9_.-]+$/.test(binaryName)) {
1340
+ return null;
1341
+ }
1342
+ const wslHomes = discoverWslDistroHomes();
1343
+ if (wslHomes.length === 0) {
1344
+ return null;
1345
+ }
1346
+ const orderedHomes = preferredDistro
1347
+ ? [
1348
+ ...wslHomes.filter((h) => h.distro.toLowerCase() === preferredDistro.toLowerCase()),
1349
+ ...wslHomes.filter((h) => h.distro.toLowerCase() !== preferredDistro.toLowerCase()),
1350
+ ]
1351
+ : wslHomes;
1352
+ for (const wslHome of orderedHomes) {
1353
+ const candidateDirs = buildPosixCandidateBinDirsForHome(wslHome.uncHome, binaryName, { rootPrefix: wslHome.uncRoot });
1354
+ for (const dir of candidateDirs) {
1355
+ const uncCandidate = path.join(dir, binaryName);
1356
+ if (isWslFileOrSymlinkValid(uncCandidate, wslHome.uncRoot)) {
1357
+ const rel = uncCandidate
1358
+ .slice(wslHome.uncRoot.length)
1359
+ .replace(/\\/g, "/")
1360
+ .replace(/^\/+/, "");
1361
+ const posixPath = `/${rel}`;
1362
+ return {
1363
+ distro: wslHome.distro,
1364
+ posixPath,
1365
+ uncPath: uncCandidate,
1366
+ formatted: `wsl:${wslHome.distro}:${posixPath}`,
1367
+ };
1368
+ }
1369
+ }
1370
+ }
1371
+ return null;
1372
+ }
1373
+ const posixLoginShellProbeCache = new Map();
1374
+ function probePosixLoginShellBinary(binaryName) {
1375
+ if (process.platform === "win32" ||
1376
+ !/^[a-zA-Z0-9_.-]+$/.test(binaryName) ||
1377
+ ((process.env.VITEST === "true" || process.env.NODE_ENV === "test") &&
1378
+ process.env.CYF_ENABLE_LOGIN_SHELL_PROBE !== "1")) {
1379
+ return null;
1380
+ }
1381
+ const now = Date.now();
1382
+ const cached = posixLoginShellProbeCache.get(binaryName);
1383
+ if (cached && now < cached.expiresAt) {
1384
+ return cached.binaryPath;
1385
+ }
1386
+ const shells = [];
1387
+ const envShell = process.env.SHELL?.trim();
1388
+ if (envShell && /^(?:zsh|bash|sh)$/i.test(path.basename(envShell)) && fs.existsSync(envShell)) {
1389
+ shells.push(envShell);
1390
+ }
1391
+ for (const fallback of ["/bin/zsh", "/bin/bash", "/usr/bin/zsh", "/usr/bin/bash"]) {
1392
+ if (!shells.includes(fallback) && fs.existsSync(fallback)) {
1393
+ shells.push(fallback);
1394
+ }
1395
+ }
1396
+ let found = null;
1397
+ for (const shBin of shells) {
1398
+ try {
1399
+ const out = execFileSync(shBin, ["-lc", `command -v ${binaryName}`], {
1400
+ encoding: "utf8",
1401
+ timeout: 1500,
1402
+ stdio: ["ignore", "pipe", "ignore"],
1403
+ });
1404
+ const lines = out
1405
+ .split(/\r?\n/)
1406
+ .map((l) => l.trim())
1407
+ .filter(Boolean);
1408
+ const last = lines[lines.length - 1];
1409
+ if (last && path.isAbsolute(last) && fs.statSync(last).isFile()) {
1410
+ found = last;
1411
+ break;
1412
+ }
1413
+ }
1414
+ catch {
1415
+ // Try next login shell
1416
+ }
1417
+ }
1418
+ posixLoginShellProbeCache.set(binaryName, {
1419
+ expiresAt: now + 30_000,
1420
+ binaryPath: found,
1421
+ });
1422
+ return found;
1423
+ }
874
1424
  /**
875
- * Pure filesystem PATH probe without spawning shell processes.
1425
+ * Pure filesystem PATH + version managers + official Desktop bundles + WSL cross-subsystem probe.
876
1426
  */
877
1427
  export function detectCliBinary(binaryName) {
878
- const rawPath = process.env.PATH ?? process.env.Path ?? "";
879
- if (!rawPath) {
880
- return { binaryInstalled: false };
1428
+ for (const envKey of CLI_BINARY_ENV_OVERRIDES[binaryName] ?? []) {
1429
+ const explicit = process.env[envKey]?.trim();
1430
+ if (explicit) {
1431
+ if (explicit.toLowerCase().startsWith("wsl:")) {
1432
+ return { binaryInstalled: true, binaryPath: explicit };
1433
+ }
1434
+ try {
1435
+ if (fs.statSync(explicit).isFile()) {
1436
+ return { binaryInstalled: true, binaryPath: explicit };
1437
+ }
1438
+ }
1439
+ catch {
1440
+ // Fall through to PATH scan
1441
+ }
1442
+ }
881
1443
  }
882
- const pathDirs = rawPath.split(path.delimiter).filter(Boolean);
1444
+ const rawPath = process.env.PATH ?? process.env.Path ?? "";
1445
+ const pathDirs = [
1446
+ ...rawPath.split(path.delimiter).filter(Boolean),
1447
+ ...extraCliInstallDirs(binaryName),
1448
+ ];
883
1449
  const extensions = process.platform === "win32"
884
1450
  ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.PS1")
885
1451
  .split(";")
@@ -900,6 +1466,17 @@ export function detectCliBinary(binaryName) {
900
1466
  }
901
1467
  }
902
1468
  }
1469
+ if (process.platform !== "win32") {
1470
+ const shellHit = probePosixLoginShellBinary(binaryName);
1471
+ if (shellHit) {
1472
+ return { binaryInstalled: true, binaryPath: shellHit };
1473
+ }
1474
+ return { binaryInstalled: false };
1475
+ }
1476
+ const wslHit = detectWslCliBinary(binaryName);
1477
+ if (wslHit) {
1478
+ return { binaryInstalled: true, binaryPath: wslHit.formatted };
1479
+ }
903
1480
  return { binaryInstalled: false };
904
1481
  }
905
1482
  //# sourceMappingURL=common.js.map