@linguacode/cli 1.2.0 → 1.4.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.
Files changed (3) hide show
  1. package/README.md +19 -4
  2. package/bin/lingua.cjs +904 -531
  3. package/package.json +1 -1
package/bin/lingua.cjs CHANGED
@@ -337,6 +337,7 @@ var TOOLCHAIN_KEYS = [
337
337
  "NODE_PATH",
338
338
  "NPM_CONFIG_CACHE",
339
339
  "NPM_CONFIG_PREFIX",
340
+ "PYTHON",
340
341
  "VIRTUAL_ENV",
341
342
  "PYTHONPATH",
342
343
  "PYENV_VERSION",
@@ -410,6 +411,103 @@ var MAX_STDIN_WRITE_BYTES = 256 * 1024;
410
411
  var MAX_COMPILE_OUTPUT_BYTES = 1024 * 1024;
411
412
  var MAX_GO_WASM_BYTES = 10 * 1024 * 1024;
412
413
 
414
+ // src/cli/runtime/runtimeRecovery.ts
415
+ var import_node_path = __toESM(require("node:path"));
416
+ var CLI_RUNTIME_HELP_URL = "https://linguacode.dev/cli/troubleshooting#missing-runtimes";
417
+ var RUNTIMES = {
418
+ python: {
419
+ name: "Python",
420
+ verifyExecutable: "python3",
421
+ homebrewFormula: "python",
422
+ installGuide: "https://www.python.org/downloads/"
423
+ },
424
+ go: {
425
+ name: "Go",
426
+ verifyExecutable: "go",
427
+ homebrewFormula: "go",
428
+ installGuide: "https://go.dev/doc/install"
429
+ },
430
+ rust: {
431
+ name: "Rust",
432
+ verifyExecutable: "rustc",
433
+ homebrewFormula: "rust",
434
+ installGuide: "https://www.rust-lang.org/tools/install"
435
+ },
436
+ ruby: {
437
+ name: "Ruby",
438
+ verifyExecutable: "ruby",
439
+ homebrewFormula: "ruby",
440
+ installGuide: "https://www.ruby-lang.org/en/documentation/installation/"
441
+ },
442
+ lua: {
443
+ name: "Lua",
444
+ verifyExecutable: "lua",
445
+ homebrewFormula: "lua",
446
+ installGuide: "https://www.lua.org/download.html"
447
+ },
448
+ node: {
449
+ name: "Node.js",
450
+ verifyExecutable: "node",
451
+ homebrewFormula: "node@24",
452
+ installGuide: "https://nodejs.org/en/download"
453
+ }
454
+ };
455
+ function buildMissingRuntimeRecovery(command, runtime, platform = process.platform) {
456
+ const executable = executableName(command);
457
+ const key = runtimeKey(executable, runtime);
458
+ const descriptor = RUNTIMES[key] ?? {
459
+ name: runtime || executable,
460
+ verifyExecutable: executable,
461
+ installGuide: CLI_RUNTIME_HELP_URL
462
+ };
463
+ const verifyExecutable = key === "python" ? executable : descriptor.verifyExecutable;
464
+ const installCommand = platform === "darwin" && descriptor.homebrewFormula ? `brew install ${descriptor.homebrewFormula}` : void 0;
465
+ const verifyCommand = `${verifyExecutable} --version`;
466
+ const recovery = {
467
+ runtime: descriptor.name,
468
+ executable,
469
+ ...installCommand ? { installCommand } : {},
470
+ installGuide: descriptor.installGuide,
471
+ verifyCommand
472
+ };
473
+ const install = installCommand ? `Install on macOS with Homebrew:
474
+ ${installCommand}` : `Install ${descriptor.name} for your operating system:
475
+ ${descriptor.installGuide}`;
476
+ const guide = descriptor.installGuide === CLI_RUNTIME_HELP_URL ? "" : `
477
+ Setup guide:
478
+ ${descriptor.installGuide}`;
479
+ return {
480
+ detail: [
481
+ `${descriptor.name} is required for this run, but Lingua could not find \`${executable}\` on PATH.`,
482
+ install,
483
+ `Verify the setup:
484
+ ${verifyCommand}`,
485
+ `Then retry the same Lingua command.${guide}`,
486
+ `Lingua runtime help:
487
+ ${CLI_RUNTIME_HELP_URL}`
488
+ ].join("\n\n"),
489
+ recovery
490
+ };
491
+ }
492
+ function executableName(command) {
493
+ const basename = import_node_path.default.basename(command).toLowerCase();
494
+ return basename.replace(/\.exe$/u, "").replace(/\.cmd$/u, "");
495
+ }
496
+ function runtimeKey(executable, runtime) {
497
+ const normalizedRuntime = runtime.toLowerCase();
498
+ if (executable === "py" || executable.startsWith("python") || normalizedRuntime.startsWith("python")) {
499
+ return "python";
500
+ }
501
+ if (executable === "go" || normalizedRuntime.startsWith("go")) return "go";
502
+ if (["rustc", "cargo"].includes(executable) || normalizedRuntime.startsWith("rust")) return "rust";
503
+ if (executable === "ruby" || normalizedRuntime.startsWith("ruby")) return "ruby";
504
+ if (executable === "lua" || normalizedRuntime.startsWith("lua")) return "lua";
505
+ if (["node", "npm", "npx"].includes(executable) || normalizedRuntime.startsWith("node")) {
506
+ return "node";
507
+ }
508
+ return normalizedRuntime;
509
+ }
510
+
413
511
  // src/cli/runtime/execution.ts
414
512
  var DEFAULT_CLI_RUN_TIMEOUT_MS = 3e4;
415
513
  var MIN_CLI_RUN_TIMEOUT_MS = 100;
@@ -439,9 +537,11 @@ async function executeCliPlan(plan, options) {
439
537
  });
440
538
  if (result.spawnError) {
441
539
  const missing = result.spawnError.code === "ENOENT";
540
+ const missingRuntime = missing ? buildMissingRuntimeRecovery(step.command, plan.runtime) : void 0;
442
541
  return finish(plan, startedAt, result, stdout.value, stderr.value, "error", {
443
542
  reason: missing ? "missing-runtime" : "spawn-failed",
444
- detail: missing ? `Required runtime ${step.command} was not found on PATH.` : `Failed to start ${step.command}: ${result.spawnError.message}`
543
+ detail: missingRuntime?.detail ?? `Failed to start ${step.command}: ${result.spawnError.message}`,
544
+ ...missingRuntime ? { recovery: missingRuntime.recovery } : {}
445
545
  });
446
546
  }
447
547
  if (result.timedOut) {
@@ -638,9 +738,11 @@ function killProcessTree(child, signal) {
638
738
  }
639
739
 
640
740
  // src/cli/runtime/targets.ts
741
+ var import_node_fs = require("node:fs");
641
742
  var import_promises2 = require("node:fs/promises");
642
743
  var import_node_os = __toESM(require("node:os"));
643
- var import_node_path = __toESM(require("node:path"));
744
+ var import_node_path2 = __toESM(require("node:path"));
745
+ var import_node_sea = require("node:sea");
644
746
 
645
747
  // node_modules/acorn/dist/acorn.mjs
646
748
  var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
@@ -6346,8 +6448,8 @@ var ExecutionTargetError = class extends Error {
6346
6448
  }
6347
6449
  reason;
6348
6450
  };
6349
- async function resolveExecutionTarget(target, programArgs) {
6350
- const absolute = import_node_path.default.resolve(target);
6451
+ async function resolveExecutionTarget(target, programArgs, env = process.env) {
6452
+ const absolute = import_node_path2.default.resolve(target);
6351
6453
  let targetStat;
6352
6454
  try {
6353
6455
  targetStat = await (0, import_promises2.stat)(absolute);
@@ -6359,17 +6461,17 @@ async function resolveExecutionTarget(target, programArgs) {
6359
6461
  );
6360
6462
  }
6361
6463
  if (targetStat.isFile()) {
6362
- return planFile(absolute, target, programArgs);
6464
+ return planFile(absolute, target, programArgs, env);
6363
6465
  }
6364
6466
  if (targetStat.isDirectory()) {
6365
- return planProject(absolute, target, programArgs);
6467
+ return planProject(absolute, target, programArgs, env);
6366
6468
  }
6367
6469
  throw new ExecutionTargetError(
6368
6470
  "unsupported-file-type",
6369
6471
  `Target must be a regular file or directory: ${target}`
6370
6472
  );
6371
6473
  }
6372
- async function resolveCapsuleSource(input, programArgs) {
6474
+ async function resolveCapsuleSource(input, programArgs, env = process.env) {
6373
6475
  if (input.runtimeMode === "browser-preview") {
6374
6476
  throw new ExecutionTargetError(
6375
6477
  "unsupported-runtime-mode",
@@ -6386,7 +6488,7 @@ async function resolveCapsuleSource(input, programArgs) {
6386
6488
  return planJavaScriptCapsule(displayTarget, cwd, input, programArgs, true);
6387
6489
  }
6388
6490
  case "python":
6389
- return singleStep(displayTarget, "python", cwd, await findPython(cwd), [
6491
+ return singleStep(displayTarget, "python", cwd, await findPython(cwd, env), [
6390
6492
  "-c",
6391
6493
  input.source,
6392
6494
  ...programArgs
@@ -6414,8 +6516,8 @@ async function resolveCapsuleSource(input, programArgs) {
6414
6516
  );
6415
6517
  }
6416
6518
  }
6417
- async function planProject(root, displayTarget, programArgs) {
6418
- const packageJson = import_node_path.default.join(root, "package.json");
6519
+ async function planProject(root, displayTarget, programArgs, env) {
6520
+ const packageJson = import_node_path2.default.join(root, "package.json");
6419
6521
  if (await exists(packageJson)) {
6420
6522
  let manifest;
6421
6523
  try {
@@ -6437,18 +6539,18 @@ async function planProject(root, displayTarget, programArgs) {
6437
6539
  ]);
6438
6540
  }
6439
6541
  if (isRecord2(manifest) && typeof manifest.main === "string") {
6440
- const mainPath = import_node_path.default.resolve(root, manifest.main);
6441
- if (await isFile(mainPath)) return planFile(mainPath, displayTarget, programArgs);
6542
+ const mainPath = import_node_path2.default.resolve(root, manifest.main);
6543
+ if (await isFile(mainPath)) return planFile(mainPath, displayTarget, programArgs, env);
6442
6544
  }
6443
6545
  }
6444
- if (await exists(import_node_path.default.join(root, "go.mod"))) {
6546
+ if (await exists(import_node_path2.default.join(root, "go.mod"))) {
6445
6547
  return singleStep(displayTarget, "go-project", root, commandName("go"), [
6446
6548
  "run",
6447
6549
  ".",
6448
6550
  ...programArgs
6449
6551
  ]);
6450
6552
  }
6451
- if (await exists(import_node_path.default.join(root, "Cargo.toml"))) {
6553
+ if (await exists(import_node_path2.default.join(root, "Cargo.toml"))) {
6452
6554
  return singleStep(displayTarget, "cargo", root, commandName("cargo"), [
6453
6555
  "run",
6454
6556
  "--quiet",
@@ -6457,8 +6559,8 @@ async function planProject(root, displayTarget, programArgs) {
6457
6559
  ]);
6458
6560
  }
6459
6561
  for (const candidate of PROJECT_ENTRY_CANDIDATES) {
6460
- const entry = import_node_path.default.join(root, candidate);
6461
- if (await isFile(entry)) return planFile(entry, displayTarget, programArgs);
6562
+ const entry = import_node_path2.default.join(root, candidate);
6563
+ if (await isFile(entry)) return planFile(entry, displayTarget, programArgs, env);
6462
6564
  }
6463
6565
  throw new ExecutionTargetError(
6464
6566
  "no-project-entry",
@@ -6483,24 +6585,27 @@ var PROJECT_ENTRY_CANDIDATES = [
6483
6585
  "index.ts",
6484
6586
  "src/index.ts"
6485
6587
  ];
6486
- async function planFile(absolute, displayTarget, programArgs) {
6487
- const cwd = import_node_path.default.dirname(absolute);
6488
- const extension = import_node_path.default.extname(absolute).toLowerCase();
6588
+ async function planFile(absolute, displayTarget, programArgs, env) {
6589
+ const cwd = import_node_path2.default.dirname(absolute);
6590
+ const extension = import_node_path2.default.extname(absolute).toLowerCase();
6489
6591
  switch (extension) {
6490
6592
  case ".js":
6491
6593
  case ".mjs":
6492
6594
  case ".cjs":
6493
- return singleStep(displayTarget, "node", cwd, process.execPath, [absolute, ...programArgs]);
6595
+ return singleStep(displayTarget, "node", cwd, nodeRuntimeExecutable(), [
6596
+ absolute,
6597
+ ...programArgs
6598
+ ]);
6494
6599
  case ".ts":
6495
6600
  case ".mts":
6496
6601
  case ".cts":
6497
- return singleStep(displayTarget, "node-typescript", cwd, process.execPath, [
6602
+ return singleStep(displayTarget, "node-typescript", cwd, nodeRuntimeExecutable(), [
6498
6603
  "--experimental-strip-types",
6499
6604
  absolute,
6500
6605
  ...programArgs
6501
6606
  ]);
6502
6607
  case ".py":
6503
- return singleStep(displayTarget, "python", cwd, await findPython(cwd), [
6608
+ return singleStep(displayTarget, "python", cwd, await findPython(cwd, env), [
6504
6609
  absolute,
6505
6610
  ...programArgs
6506
6611
  ]);
@@ -6518,8 +6623,8 @@ async function planFile(absolute, displayTarget, programArgs) {
6518
6623
  case ".lua":
6519
6624
  return singleStep(displayTarget, "lua", cwd, commandName("lua"), [absolute, ...programArgs]);
6520
6625
  case ".rs": {
6521
- const temporaryRoot = await (0, import_promises2.mkdtemp)(import_node_path.default.join(import_node_os.default.tmpdir(), "lingua-cli-rust-"));
6522
- const binary = import_node_path.default.join(
6626
+ const temporaryRoot = await (0, import_promises2.mkdtemp)(import_node_path2.default.join(import_node_os.default.tmpdir(), "lingua-cli-rust-"));
6627
+ const binary = import_node_path2.default.join(
6523
6628
  temporaryRoot,
6524
6629
  process.platform === "win32" ? "program.exe" : "program"
6525
6630
  );
@@ -6546,8 +6651,8 @@ async function planFile(absolute, displayTarget, programArgs) {
6546
6651
  }
6547
6652
  }
6548
6653
  async function stageCompiledSource(displayTarget, language, filename, source, programArgs) {
6549
- const temporaryRoot = await (0, import_promises2.mkdtemp)(import_node_path.default.join(import_node_os.default.tmpdir(), `lingua-cli-${language}-`));
6550
- const sourcePath = import_node_path.default.join(temporaryRoot, filename);
6654
+ const temporaryRoot = await (0, import_promises2.mkdtemp)(import_node_path2.default.join(import_node_os.default.tmpdir(), `lingua-cli-${language}-`));
6655
+ const sourcePath = import_node_path2.default.join(temporaryRoot, filename);
6551
6656
  await (0, import_promises2.writeFile)(sourcePath, source, "utf8");
6552
6657
  if (language === "go") {
6553
6658
  return {
@@ -6564,7 +6669,7 @@ async function stageCompiledSource(displayTarget, language, filename, source, pr
6564
6669
  ]
6565
6670
  };
6566
6671
  }
6567
- const binary = import_node_path.default.join(temporaryRoot, process.platform === "win32" ? "program.exe" : "program");
6672
+ const binary = import_node_path2.default.join(temporaryRoot, process.platform === "win32" ? "program.exe" : "program");
6568
6673
  return {
6569
6674
  displayTarget,
6570
6675
  runtime: "rust",
@@ -6598,7 +6703,7 @@ function planJavaScriptCapsule(displayTarget, cwd, input, programArgs, typescrip
6598
6703
  displayTarget,
6599
6704
  typescript ? "node-typescript-worker" : "node-worker",
6600
6705
  cwd,
6601
- process.execPath,
6706
+ nodeRuntimeExecutable(),
6602
6707
  [
6603
6708
  ...typescript ? ["--experimental-strip-types"] : [],
6604
6709
  "--input-type=commonjs",
@@ -6613,7 +6718,7 @@ function planJavaScriptCapsule(displayTarget, cwd, input, programArgs, typescrip
6613
6718
  displayTarget,
6614
6719
  typescript ? "node-typescript" : "node",
6615
6720
  cwd,
6616
- process.execPath,
6721
+ nodeRuntimeExecutable(),
6617
6722
  [
6618
6723
  ...typescript ? ["--experimental-strip-types"] : [],
6619
6724
  `--input-type=${sourceRequiresModuleInput(input.source) ? "module" : "commonjs"}`,
@@ -6628,16 +6733,47 @@ function planJavaScriptCapsule(displayTarget, cwd, input, programArgs, typescrip
6628
6733
  `Capsule runtime mode ${JSON.stringify(input.runtimeMode)} is not replayable by the CLI for ${typescript ? "TypeScript" : "JavaScript"}; supported modes are worker and node.`
6629
6734
  );
6630
6735
  }
6631
- async function findPython(startDirectory) {
6736
+ function pythonCommandCandidates(platform = process.platform) {
6737
+ return platform === "win32" ? ["python", "py", "python3"] : ["python3", "python"];
6738
+ }
6739
+ function nodeRuntimeExecutable(options) {
6740
+ const sea = options?.sea ?? (0, import_node_sea.isSea)();
6741
+ return sea ? commandName("node") : options?.execPath ?? process.execPath;
6742
+ }
6743
+ async function findPython(startDirectory, env = process.env) {
6632
6744
  let current2 = startDirectory;
6633
6745
  while (true) {
6634
- const local = process.platform === "win32" ? import_node_path.default.join(current2, ".venv", "Scripts", "python.exe") : import_node_path.default.join(current2, ".venv", "bin", "python");
6746
+ const local = process.platform === "win32" ? import_node_path2.default.join(current2, ".venv", "Scripts", "python.exe") : import_node_path2.default.join(current2, ".venv", "bin", "python");
6635
6747
  if (await isFile(local)) return local;
6636
- const parent = import_node_path.default.dirname(current2);
6748
+ const parent = import_node_path2.default.dirname(current2);
6637
6749
  if (parent === current2) break;
6638
6750
  current2 = parent;
6639
6751
  }
6640
- return process.env.PYTHON || commandName("python3");
6752
+ if (env.PYTHON) return env.PYTHON;
6753
+ const candidates = pythonCommandCandidates();
6754
+ for (const candidate of candidates) {
6755
+ if (await executableIsOnPath(candidate, process.platform, env)) return commandName(candidate);
6756
+ }
6757
+ return commandName(candidates[0]);
6758
+ }
6759
+ async function executableIsOnPath(executable, platform = process.platform, env = process.env) {
6760
+ const pathValue = env.PATH ?? env.Path ?? env.path;
6761
+ if (!pathValue) return false;
6762
+ const windows = platform === "win32";
6763
+ const pathApi = windows ? import_node_path2.default.win32 : import_node_path2.default.posix;
6764
+ const delimiter = windows ? ";" : ":";
6765
+ const extensions = windows ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((extension) => extension.toLowerCase()) : [""];
6766
+ const hasExtension = pathApi.extname(executable).length > 0;
6767
+ for (const rawEntry of pathValue.split(delimiter)) {
6768
+ const entry = rawEntry.trim().replace(/^"|"$/gu, "");
6769
+ if (!entry) continue;
6770
+ const base = pathApi.join(entry, executable);
6771
+ const candidates = windows && !hasExtension ? extensions.map((extension) => base + extension) : [base];
6772
+ for (const candidate of candidates) {
6773
+ if (await isExecutableFile(candidate, platform)) return true;
6774
+ }
6775
+ }
6776
+ return false;
6641
6777
  }
6642
6778
  function commandName(name) {
6643
6779
  return process.platform === "win32" && ["npm", "npx"].includes(name) ? `${name}.cmd` : name;
@@ -6657,6 +6793,16 @@ async function isFile(filePath) {
6657
6793
  return false;
6658
6794
  }
6659
6795
  }
6796
+ async function isExecutableFile(filePath, platform = process.platform) {
6797
+ if (!await isFile(filePath)) return false;
6798
+ if (platform === "win32") return true;
6799
+ try {
6800
+ await (0, import_promises2.access)(filePath, import_node_fs.constants.X_OK);
6801
+ return true;
6802
+ } catch {
6803
+ return false;
6804
+ }
6805
+ }
6660
6806
  function isRecord2(value) {
6661
6807
  return typeof value === "object" && value !== null && !Array.isArray(value);
6662
6808
  }
@@ -6704,7 +6850,7 @@ async function runTargetCommand(args, io) {
6704
6850
  }
6705
6851
  let plan;
6706
6852
  try {
6707
- plan = await resolveExecutionTarget(args.target, args.programArgs);
6853
+ plan = await resolveExecutionTarget(args.target, args.programArgs, env);
6708
6854
  } catch (error) {
6709
6855
  if (error instanceof ExecutionTargetError) {
6710
6856
  const unsupported = [
@@ -6743,7 +6889,8 @@ function emitExecution(args, io, result, extra = {}, label = "lingua run", strea
6743
6889
  if (args.json) {
6744
6890
  const failure = result.status === "success" ? {} : {
6745
6891
  reason: result.reason ?? result.status,
6746
- detail: result.detail ?? `Run failed with status ${result.status}.`
6892
+ detail: result.detail ?? `Run failed with status ${result.status}.`,
6893
+ ...result.recovery ? { recovery: result.recovery } : {}
6747
6894
  };
6748
6895
  io.writeStdout(
6749
6896
  `${JSON.stringify({ ok: result.status === "success", ...extra, ...failure, run: result })}
@@ -6840,7 +6987,8 @@ async function runReplayCapsuleCommand(args, io) {
6840
6987
  source: capsule.source.content,
6841
6988
  capsuleId: capsule.capsuleId
6842
6989
  },
6843
- capsule.input.args ?? []
6990
+ capsule.input.args ?? [],
6991
+ env
6844
6992
  );
6845
6993
  } catch (error) {
6846
6994
  if (error instanceof ExecutionTargetError) {
@@ -6938,6 +7086,24 @@ function errorMessage3(error) {
6938
7086
  return error instanceof Error ? error.message : String(error);
6939
7087
  }
6940
7088
 
7089
+ // src/cli/commands/completionInstall.ts
7090
+ var import_node_fs2 = require("node:fs");
7091
+ var import_promises3 = require("node:fs/promises");
7092
+ var import_node_os2 = __toESM(require("node:os"));
7093
+ var import_node_path3 = __toESM(require("node:path"));
7094
+
7095
+ // src/cli/commandModel.ts
7096
+ var CLI_COLOR_MODES = ["auto", "always", "never"];
7097
+ var CLI_COMPLETION_SHELLS = ["bash", "zsh", "fish"];
7098
+ var CLI_COMPLETION_TARGETS = [...CLI_COMPLETION_SHELLS, "install"];
7099
+ var CLI_TOP_LEVEL_COMMANDS = ["utility", "run", "capsule", "list", "completion"];
7100
+ function isCliColorMode(value) {
7101
+ return CLI_COLOR_MODES.includes(value);
7102
+ }
7103
+ function isCliCompletionShell(value) {
7104
+ return CLI_COMPLETION_SHELLS.includes(value);
7105
+ }
7106
+
6941
7107
  // src/shared/utilities/types.ts
6942
7108
  var UTILITY_ADAPTER_IDS = [
6943
7109
  "json-format",
@@ -6980,106 +7146,605 @@ var UTILITY_ADAPTER_IDS = [
6980
7146
  "cron-phrase"
6981
7147
  ];
6982
7148
 
6983
- // src/shared/utilities/base64.ts
6984
- function bytesToBase64(bytes) {
6985
- let binary = "";
6986
- for (let i2 = 0; i2 < bytes.byteLength; i2 += 1) {
6987
- binary += String.fromCharCode(bytes[i2] ?? 0);
7149
+ // src/cli/completion.ts
7150
+ var commandWords = CLI_TOP_LEVEL_COMMANDS.join(" ");
7151
+ var colorWords = CLI_COLOR_MODES.join(" ");
7152
+ var shellWords = CLI_COMPLETION_TARGETS.join(" ");
7153
+ var utilityWords = [...UTILITY_ADAPTER_IDS].sort().join(" ");
7154
+ function renderCompletion(shell) {
7155
+ switch (shell) {
7156
+ case "bash":
7157
+ return renderBashCompletion();
7158
+ case "zsh":
7159
+ return renderZshCompletion();
7160
+ case "fish":
7161
+ return renderFishCompletion();
6988
7162
  }
6989
- return btoa(binary);
6990
- }
6991
- function base64ToBytes(value) {
6992
- const binary = atob(value);
6993
- return Uint8Array.from(binary, (char) => char.charCodeAt(0));
6994
- }
6995
- function parseEmptyOptions(raw) {
6996
- if (raw === void 0 || raw === null) return {};
6997
- if (typeof raw !== "object" || Array.isArray(raw)) return null;
6998
- return {};
6999
7163
  }
7000
- var base64EncodeAdapter = {
7001
- id: "base64-encode",
7002
- titleKey: "utilityPipeline.adapter.base64Encode.title",
7003
- descriptionKey: "utilityPipeline.adapter.base64Encode.description",
7004
- inputKind: "text",
7005
- outputKind: "text",
7006
- optionsSchema: [],
7007
- defaultOptions: () => ({}),
7008
- parseOptions: parseEmptyOptions,
7009
- run: async (input) => {
7010
- try {
7011
- const value = bytesToBase64(new TextEncoder().encode(input));
7012
- return { ok: true, value };
7013
- } catch (err) {
7014
- return {
7015
- ok: false,
7016
- reason: "execution-error",
7017
- detail: err instanceof Error ? err.message : "encode failed"
7018
- };
7019
- }
7020
- }
7021
- };
7022
- var base64DecodeAdapter = {
7023
- id: "base64-decode",
7024
- titleKey: "utilityPipeline.adapter.base64Decode.title",
7025
- descriptionKey: "utilityPipeline.adapter.base64Decode.description",
7026
- inputKind: "text",
7027
- outputKind: "text",
7028
- optionsSchema: [],
7029
- defaultOptions: () => ({}),
7030
- parseOptions: parseEmptyOptions,
7031
- run: async (input) => {
7032
- if (input.trim().length === 0) {
7033
- return { ok: true, value: "" };
7034
- }
7035
- try {
7036
- const sanitized = input.replace(/\s+/gu, "");
7037
- const bytes = base64ToBytes(sanitized);
7038
- const value = new TextDecoder().decode(bytes);
7039
- return { ok: true, value };
7040
- } catch (err) {
7041
- return {
7042
- ok: false,
7043
- reason: "invalid-input",
7044
- detail: err instanceof Error ? err.message : "invalid base64"
7045
- };
7046
- }
7047
- }
7048
- };
7164
+ function renderBashCompletion() {
7165
+ return `# lingua bash completion
7166
+ _lingua() {
7167
+ local cur prev command command_index index relative word
7168
+ COMPREPLY=()
7169
+ cur="\${COMP_WORDS[COMP_CWORD]}"
7170
+ prev=""
7171
+ if (( COMP_CWORD > 0 )); then
7172
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
7173
+ fi
7174
+ command=""
7175
+ command_index=0
7176
+ for (( index=1; index<COMP_CWORD; index++ )); do
7177
+ word="\${COMP_WORDS[index]}"
7178
+ case "$word" in
7179
+ --color)
7180
+ (( index++ ))
7181
+ ;;
7182
+ --color=*)
7183
+ ;;
7184
+ utility|run|capsule|list|completion)
7185
+ command="$word"
7186
+ command_index=$index
7187
+ break
7188
+ ;;
7189
+ esac
7190
+ done
7049
7191
 
7050
- // src/shared/utilities/colorConvert.ts
7051
- function parseEmptyOptions2(raw) {
7052
- if (raw === void 0 || raw === null) return {};
7053
- if (typeof raw !== "object" || Array.isArray(raw)) return null;
7054
- return {};
7192
+ case "$cur" in
7193
+ --color=*)
7194
+ local value="\${cur#--color=}"
7195
+ COMPREPLY=( $(compgen -W "${colorWords}" -- "$value") )
7196
+ COMPREPLY=( "\${COMPREPLY[@]/#/--color=}" )
7197
+ return
7198
+ ;;
7199
+ esac
7200
+
7201
+ case "$prev" in
7202
+ --color)
7203
+ COMPREPLY=( $(compgen -W "${colorWords}" -- "$cur") )
7204
+ return
7205
+ ;;
7206
+ --input|--stdin)
7207
+ compopt -o filenames 2>/dev/null || true
7208
+ COMPREPLY=( $(compgen -f -- "$cur") )
7209
+ return
7210
+ ;;
7211
+ --timeout)
7212
+ return
7213
+ ;;
7214
+ --env|--option)
7215
+ return
7216
+ ;;
7217
+ esac
7218
+
7219
+ if [[ -z "$command" ]]; then
7220
+ COMPREPLY=( $(compgen -W "${commandWords} --help --version --color" -- "$cur") )
7221
+ return
7222
+ fi
7223
+
7224
+ case "$command" in
7225
+ utility)
7226
+ relative=$(( COMP_CWORD - command_index ))
7227
+ if (( relative == 1 )); then
7228
+ COMPREPLY=( $(compgen -W "${utilityWords}" -- "$cur") )
7229
+ elif [[ "$cur" == -* ]]; then
7230
+ COMPREPLY=( $(compgen -W "--input --option --json --quiet --color --help" -- "$cur") )
7231
+ fi
7232
+ ;;
7233
+ run)
7234
+ if [[ "$cur" == -* ]]; then
7235
+ COMPREPLY=( $(compgen -W "--stdin --timeout --env --json --quiet --color --help --" -- "$cur") )
7236
+ else
7237
+ compopt -o filenames 2>/dev/null || true
7238
+ COMPREPLY=( $(compgen -f -- "$cur") )
7239
+ fi
7240
+ ;;
7241
+ capsule)
7242
+ relative=$(( COMP_CWORD - command_index ))
7243
+ if (( relative == 1 )); then
7244
+ COMPREPLY=( $(compgen -W "validate replay" -- "$cur") )
7245
+ elif [[ "$cur" == -* ]]; then
7246
+ COMPREPLY=( $(compgen -W "--timeout --env --json --quiet --color --help" -- "$cur") )
7247
+ else
7248
+ compopt -o filenames 2>/dev/null || true
7249
+ COMPREPLY=( $(compgen -f -- "$cur") )
7250
+ fi
7251
+ ;;
7252
+ list)
7253
+ relative=$(( COMP_CWORD - command_index ))
7254
+ if (( relative == 1 )); then
7255
+ COMPREPLY=( $(compgen -W "utilities" -- "$cur") )
7256
+ else
7257
+ COMPREPLY=( $(compgen -W "--json --quiet --color --help" -- "$cur") )
7258
+ fi
7259
+ ;;
7260
+ completion)
7261
+ relative=$(( COMP_CWORD - command_index ))
7262
+ if (( relative == 1 )); then
7263
+ COMPREPLY=( $(compgen -W "${shellWords}" -- "$cur") )
7264
+ else
7265
+ COMPREPLY=( $(compgen -W "--yes --dry-run --color --help" -- "$cur") )
7266
+ fi
7267
+ ;;
7268
+ esac
7055
7269
  }
7056
- function clampByte(value) {
7057
- return Math.max(0, Math.min(255, Math.round(value)));
7270
+ complete -F _lingua lingua
7271
+ `;
7058
7272
  }
7059
- function parseColor(input) {
7060
- const trimmed = input.trim().toLowerCase();
7061
- const hexMatch = /^#([0-9a-f]{3,8})$/u.exec(trimmed);
7062
- if (hexMatch) {
7063
- const hex = hexMatch[1];
7064
- if (hex.length === 3 || hex.length === 4) {
7065
- const r = parseInt(hex[0] + hex[0], 16);
7066
- const g = parseInt(hex[1] + hex[1], 16);
7067
- const b = parseInt(hex[2] + hex[2], 16);
7068
- const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
7069
- return { r, g, b, a };
7070
- }
7071
- if (hex.length === 6 || hex.length === 8) {
7072
- const r = parseInt(hex.slice(0, 2), 16);
7073
- const g = parseInt(hex.slice(2, 4), 16);
7074
- const b = parseInt(hex.slice(4, 6), 16);
7075
- const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
7076
- return { r, g, b, a };
7077
- }
7078
- return null;
7079
- }
7080
- const rgbMatch = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/u.exec(
7081
- trimmed
7082
- );
7273
+ function renderZshCompletion() {
7274
+ return `#compdef lingua
7275
+ # lingua zsh completion
7276
+ _lingua() {
7277
+ local context state state_descr line
7278
+ typeset -A opt_args
7279
+ local -a commands utilities color_modes completion_targets
7280
+ local command_index index
7281
+ commands=(
7282
+ 'utility:Run a shared utility adapter'
7283
+ 'run:Execute a source file or project root'
7284
+ 'capsule:Validate or replay a Run Capsule'
7285
+ 'list:List available capabilities'
7286
+ 'completion:Generate a shell completion script'
7287
+ )
7288
+ utilities=(${utilityWords})
7289
+ color_modes=(${colorWords})
7290
+ completion_targets=(${shellWords})
7291
+
7292
+ _arguments -C \\
7293
+ '(-h --help)'{-h,--help}'[Show help]' \\
7294
+ '(-v --version)'{-v,--version}'[Print the CLI version]' \\
7295
+ '--color=[Control diagnostic color]:mode:(auto always never)' \\
7296
+ '1:command:->command' \\
7297
+ '*::argument:->arguments'
7298
+
7299
+ case "$state" in
7300
+ command)
7301
+ _describe -t commands 'lingua command' commands
7302
+ ;;
7303
+ arguments)
7304
+ command_index=0
7305
+ for (( index=2; index<CURRENT; index++ )); do
7306
+ case "\${words[index]}" in
7307
+ --color)
7308
+ (( index++ ))
7309
+ ;;
7310
+ --color=*)
7311
+ ;;
7312
+ utility|run|capsule|list|completion)
7313
+ command_index=$index
7314
+ break
7315
+ ;;
7316
+ esac
7317
+ done
7318
+ if (( command_index == 0 )); then
7319
+ return 0
7320
+ fi
7321
+ words=("\${(@)words[$command_index,-1]}")
7322
+ (( CURRENT -= command_index - 1 ))
7323
+ case "\${words[1]}" in
7324
+ utility)
7325
+ if (( CURRENT == 2 )); then
7326
+ _describe -t utilities 'utility' utilities
7327
+ else
7328
+ _arguments \\
7329
+ '--input=[Read input from a file]:file:_files' \\
7330
+ '*--option=[Pass an adapter key=value option]:option:' \\
7331
+ '--json[Emit structured JSON]' \\
7332
+ '--quiet[Suppress Lingua diagnostics]' \\
7333
+ '--color=[Control diagnostic color]:mode:(auto always never)' \\
7334
+ '(-h --help)'{-h,--help}'[Show help]'
7335
+ fi
7336
+ ;;
7337
+ run)
7338
+ _arguments \\
7339
+ '1:source file or project:_files' \\
7340
+ '--stdin=[Forward a file as program stdin]:file:_files' \\
7341
+ '--timeout=[Set wall-clock timeout in milliseconds]:milliseconds:' \\
7342
+ '*--env=[Add an explicit NAME=value environment entry]:environment:' \\
7343
+ '--json[Emit structured JSON]' \\
7344
+ '--quiet[Suppress Lingua diagnostics]' \\
7345
+ '--color=[Control diagnostic color]:mode:(auto always never)' \\
7346
+ '(-h --help)'{-h,--help}'[Show help]' \\
7347
+ '*::program argument:'
7348
+ ;;
7349
+ capsule)
7350
+ if (( CURRENT == 2 )); then
7351
+ _values 'capsule action' validate replay
7352
+ else
7353
+ _arguments \\
7354
+ '2:capsule file:_files' \\
7355
+ '--timeout=[Set replay timeout in milliseconds]:milliseconds:' \\
7356
+ '*--env=[Add an explicit NAME=value environment entry]:environment:' \\
7357
+ '--json[Emit structured JSON]' \\
7358
+ '--quiet[Suppress Lingua diagnostics]' \\
7359
+ '--color=[Control diagnostic color]:mode:(auto always never)' \\
7360
+ '(-h --help)'{-h,--help}'[Show help]'
7361
+ fi
7362
+ ;;
7363
+ list)
7364
+ _values 'list target' utilities
7365
+ ;;
7366
+ completion)
7367
+ _arguments '1:completion target:(bash zsh fish install)' '--yes[Install without an interactive confirmation]' '--dry-run[Show detected shells and target files without writing]' '--color=[Control diagnostic color]:mode:(auto always never)' '(-h --help)'{-h,--help}'[Show help]'
7368
+ ;;
7369
+ esac
7370
+ ;;
7371
+ esac
7372
+ }
7373
+ if (( $+functions[compdef] )); then
7374
+ compdef _lingua lingua
7375
+ fi
7376
+ `;
7377
+ }
7378
+ function renderFishCompletion() {
7379
+ const utilityLines = [...UTILITY_ADAPTER_IDS].sort().map((id) => `complete -c lingua -n '__fish_lingua_needs_first_argument utility' -a '${id}'`).join("\n");
7380
+ return `# lingua fish completion
7381
+ function __fish_lingua_needs_command
7382
+ set -l command_index (__fish_lingua_command_index)
7383
+ test -z "$command_index"
7384
+ end
7385
+
7386
+ function __fish_lingua_command_index
7387
+ set -l tokens (commandline -opc)
7388
+ set -l skip_next 0
7389
+ for index in (seq 2 (count $tokens))
7390
+ set -l token $tokens[$index]
7391
+ if test $skip_next -eq 1
7392
+ set skip_next 0
7393
+ continue
7394
+ end
7395
+ switch $token
7396
+ case --color
7397
+ set skip_next 1
7398
+ case '--color=*' --json --quiet --help -h --version -v
7399
+ continue
7400
+ case utility run capsule list completion
7401
+ echo $index
7402
+ return 0
7403
+ end
7404
+ end
7405
+ return 1
7406
+ end
7407
+
7408
+ function __fish_lingua_using_command
7409
+ set -l tokens (commandline -opc)
7410
+ set -l command_index (__fish_lingua_command_index)
7411
+ test -n "$command_index"; and test "$tokens[$command_index]" = "$argv[1]"
7412
+ end
7413
+
7414
+ function __fish_lingua_needs_first_argument
7415
+ set -l tokens (commandline -opc)
7416
+ set -l command_index (__fish_lingua_command_index)
7417
+ if test -z "$command_index"; or test "$tokens[$command_index]" != "$argv[1]"
7418
+ return 1
7419
+ end
7420
+ set -l skip_next 0
7421
+ for index in (seq (math $command_index + 1) (count $tokens))
7422
+ set -l token $tokens[$index]
7423
+ if test $skip_next -eq 1
7424
+ set skip_next 0
7425
+ continue
7426
+ end
7427
+ switch $token
7428
+ case --color --input --option --stdin --timeout --env
7429
+ set skip_next 1
7430
+ case '--color=*' '--input=*' '--option=*' '--stdin=*' '--timeout=*' '--env=*' --json --quiet --help -h
7431
+ continue
7432
+ case '*'
7433
+ return 1
7434
+ end
7435
+ end
7436
+ return 0
7437
+ end
7438
+
7439
+ complete -c lingua -f -n __fish_lingua_needs_command -a 'utility' -d 'Run a shared utility adapter'
7440
+ complete -c lingua -f -n __fish_lingua_needs_command -a 'run' -d 'Execute a source file or project root'
7441
+ complete -c lingua -f -n __fish_lingua_needs_command -a 'capsule' -d 'Validate or replay a Run Capsule'
7442
+ complete -c lingua -f -n __fish_lingua_needs_command -a 'list' -d 'List available capabilities'
7443
+ complete -c lingua -f -n __fish_lingua_needs_command -a 'completion' -d 'Generate a shell completion script'
7444
+
7445
+ complete -c lingua -l help -s h -d 'Show help'
7446
+ complete -c lingua -l version -s v -d 'Print the CLI version'
7447
+ complete -c lingua -l color -r -f -a '${colorWords}' -d 'Control diagnostic color'
7448
+ complete -c lingua -l json -d 'Emit structured JSON'
7449
+ complete -c lingua -l quiet -d 'Suppress Lingua diagnostics'
7450
+
7451
+ ${utilityLines}
7452
+ complete -c lingua -n '__fish_lingua_using_command utility' -l input -r -F -d 'Read input from a file'
7453
+ complete -c lingua -n '__fish_lingua_using_command utility' -l option -r -d 'Pass an adapter key=value option'
7454
+
7455
+ complete -c lingua -n '__fish_lingua_using_command run' -l stdin -r -F -d 'Forward a file as program stdin'
7456
+ complete -c lingua -n '__fish_lingua_using_command run' -l timeout -r -d 'Set wall-clock timeout in milliseconds'
7457
+ complete -c lingua -n '__fish_lingua_using_command run' -l env -r -d 'Add an explicit NAME=value environment entry'
7458
+
7459
+ complete -c lingua -n '__fish_lingua_needs_first_argument capsule' -a 'validate replay'
7460
+ complete -c lingua -n '__fish_lingua_using_command capsule' -l timeout -r -d 'Set replay timeout in milliseconds'
7461
+ complete -c lingua -n '__fish_lingua_using_command capsule' -l env -r -d 'Add an explicit NAME=value environment entry'
7462
+
7463
+ complete -c lingua -n '__fish_lingua_needs_first_argument list' -a 'utilities'
7464
+ complete -c lingua -n '__fish_lingua_needs_first_argument completion' -a '${shellWords}'
7465
+ complete -c lingua -n '__fish_lingua_using_command completion' -l yes -d 'Install without interactive confirmation'
7466
+ complete -c lingua -n '__fish_lingua_using_command completion' -l dry-run -d 'Show the install plan without writing files'
7467
+ `;
7468
+ }
7469
+
7470
+ // src/cli/commands/completionInstall.ts
7471
+ var ZSH_BLOCK_START = "# >>> lingua completion >>>";
7472
+ var ZSH_BLOCK_END = "# <<< lingua completion <<<";
7473
+ var ZSH_BLOCK = `${ZSH_BLOCK_START}
7474
+ fpath=("\${ZDOTDIR:-$HOME}/.zfunc" $fpath)
7475
+ autoload -Uz compinit
7476
+ compinit
7477
+ ${ZSH_BLOCK_END}`;
7478
+ var defaultDependencies = {
7479
+ homedir: import_node_os2.default.homedir,
7480
+ async isExecutable(filePath) {
7481
+ try {
7482
+ await (0, import_promises3.access)(filePath, import_node_fs2.constants.X_OK);
7483
+ return true;
7484
+ } catch {
7485
+ return false;
7486
+ }
7487
+ },
7488
+ async mkdir(directoryPath) {
7489
+ await (0, import_promises3.mkdir)(directoryPath, { recursive: true });
7490
+ },
7491
+ async writeFile(filePath, contents) {
7492
+ await (0, import_promises3.writeFile)(filePath, contents, "utf8");
7493
+ },
7494
+ async readFileIfPresent(filePath) {
7495
+ try {
7496
+ return await (0, import_promises3.readFile)(filePath, "utf8");
7497
+ } catch (error) {
7498
+ if (error.code === "ENOENT") return null;
7499
+ throw error;
7500
+ }
7501
+ },
7502
+ async appendFile(filePath, contents) {
7503
+ await (0, import_promises3.appendFile)(filePath, contents, "utf8");
7504
+ }
7505
+ };
7506
+ function shellFromExecutable(executablePath) {
7507
+ if (!executablePath) return void 0;
7508
+ const name = import_node_path3.default.basename(executablePath);
7509
+ return CLI_COMPLETION_SHELLS.includes(name) ? name : void 0;
7510
+ }
7511
+ function completionPathForShell(shell, io, dependencies) {
7512
+ const home = io.getEnvironmentValue("HOME") || dependencies.homedir();
7513
+ switch (shell) {
7514
+ case "bash": {
7515
+ const dataHome = io.getEnvironmentValue("XDG_DATA_HOME") || import_node_path3.default.join(home, ".local/share");
7516
+ return {
7517
+ completionPath: import_node_path3.default.join(dataHome, "bash-completion/completions/lingua")
7518
+ };
7519
+ }
7520
+ case "zsh": {
7521
+ const zshHome = io.getEnvironmentValue("ZDOTDIR") || home;
7522
+ return {
7523
+ completionPath: import_node_path3.default.join(zshHome, ".zfunc/_lingua"),
7524
+ activationPath: import_node_path3.default.join(zshHome, ".zshrc")
7525
+ };
7526
+ }
7527
+ case "fish": {
7528
+ const configHome = io.getEnvironmentValue("XDG_CONFIG_HOME") || import_node_path3.default.join(home, ".config");
7529
+ return {
7530
+ completionPath: import_node_path3.default.join(configHome, "fish/completions/lingua.fish")
7531
+ };
7532
+ }
7533
+ }
7534
+ }
7535
+ async function resolveExecutable(shell, io, dependencies) {
7536
+ const currentShellPath = io.getEnvironmentValue("SHELL");
7537
+ if (shellFromExecutable(currentShellPath) === shell && currentShellPath !== void 0 && await dependencies.isExecutable(currentShellPath)) {
7538
+ return currentShellPath;
7539
+ }
7540
+ const pathEntries = (io.getEnvironmentValue("PATH") || "").split(import_node_path3.default.delimiter).filter(Boolean);
7541
+ for (const directory of pathEntries) {
7542
+ const candidate = import_node_path3.default.join(directory, shell);
7543
+ if (await dependencies.isExecutable(candidate)) return candidate;
7544
+ }
7545
+ return void 0;
7546
+ }
7547
+ async function detectCompletionTargets(io, dependencies = defaultDependencies) {
7548
+ const currentShell = shellFromExecutable(io.getEnvironmentValue("SHELL"));
7549
+ const targets = [];
7550
+ for (const shell of CLI_COMPLETION_SHELLS) {
7551
+ const executablePath = await resolveExecutable(shell, io, dependencies);
7552
+ if (!executablePath) continue;
7553
+ const paths = completionPathForShell(shell, io, dependencies);
7554
+ targets.push({
7555
+ shell,
7556
+ executablePath,
7557
+ completionPath: paths.completionPath,
7558
+ current: shell === currentShell,
7559
+ ...paths.activationPath ? { activationPath: paths.activationPath } : {}
7560
+ });
7561
+ }
7562
+ return targets;
7563
+ }
7564
+ function renderPlan(targets) {
7565
+ const lines = ["Lingua detected these supported shells:"];
7566
+ for (const target of targets) {
7567
+ lines.push(
7568
+ ` ${target.current ? "\u25CF" : "\u25CB"} ${target.shell}${target.current ? " (current)" : ""}`,
7569
+ ` completion: ${target.completionPath}`
7570
+ );
7571
+ if (target.activationPath) lines.push(` activation: ${target.activationPath}`);
7572
+ }
7573
+ return `${lines.join("\n")}
7574
+ `;
7575
+ }
7576
+ async function ensureZshActivation(rcPath, dependencies) {
7577
+ const current2 = await dependencies.readFileIfPresent(rcPath);
7578
+ if (current2?.includes(ZSH_BLOCK_START) && current2.includes(ZSH_BLOCK_END)) {
7579
+ const start = current2.indexOf(ZSH_BLOCK_START);
7580
+ const end = current2.indexOf(ZSH_BLOCK_END, start) + ZSH_BLOCK_END.length;
7581
+ const updated = `${current2.slice(0, start)}${ZSH_BLOCK}${current2.slice(end)}`;
7582
+ if (updated !== current2) await dependencies.writeFile(rcPath, updated);
7583
+ return;
7584
+ }
7585
+ const prefix = current2 && !current2.endsWith("\n") ? "\n" : "";
7586
+ await dependencies.appendFile(rcPath, `${prefix}${ZSH_BLOCK}
7587
+ `);
7588
+ }
7589
+ async function runCompletionInstallCommand(options, io, dependencies = defaultDependencies) {
7590
+ try {
7591
+ const targets = await detectCompletionTargets(io, dependencies);
7592
+ if (targets.length === 0) {
7593
+ emitCliFailure(io, { json: false, quiet: false, color: "auto" }, {
7594
+ label: "lingua completion",
7595
+ reason: "no-supported-shells",
7596
+ detail: "Lingua could not find bash, zsh, or fish on PATH. Install a supported shell or run `lingua completion <shell>` to print its script."
7597
+ });
7598
+ return CLI_EXIT_CODES.unsupportedCapability;
7599
+ }
7600
+ io.writeStdout(renderPlan(targets));
7601
+ if (options.dryRun) {
7602
+ io.writeStdout("Dry run: no files were changed.\n");
7603
+ return CLI_EXIT_CODES.ok;
7604
+ }
7605
+ if (!options.assumeYes) {
7606
+ const shellNames = targets.map((target) => target.shell).join(", ");
7607
+ const confirmed = await io.confirm(
7608
+ `Install completion support for ${shellNames}?`,
7609
+ true
7610
+ );
7611
+ if (confirmed === null) {
7612
+ emitCliFailure(io, { json: false, quiet: false, color: "auto" }, {
7613
+ label: "lingua completion",
7614
+ reason: "confirmation-required",
7615
+ detail: "Interactive confirmation is unavailable. Re-run `lingua completion install --yes` to approve these changes, or use `--dry-run` to inspect them."
7616
+ });
7617
+ return CLI_EXIT_CODES.userInputError;
7618
+ }
7619
+ if (!confirmed) {
7620
+ io.writeStdout("Cancelled. No files were changed.\n");
7621
+ return CLI_EXIT_CODES.ok;
7622
+ }
7623
+ }
7624
+ for (const target of targets) {
7625
+ await dependencies.mkdir(import_node_path3.default.dirname(target.completionPath));
7626
+ await dependencies.writeFile(target.completionPath, renderCompletion(target.shell));
7627
+ if (target.shell === "zsh" && target.activationPath) {
7628
+ await ensureZshActivation(target.activationPath, dependencies);
7629
+ }
7630
+ }
7631
+ io.writeStdout(
7632
+ `Installed completion support for ${targets.map((target) => target.shell).join(", ")}.
7633
+ Start a new shell session to load it.
7634
+ `
7635
+ );
7636
+ return CLI_EXIT_CODES.ok;
7637
+ } catch (error) {
7638
+ const detail = error instanceof Error ? error.message : String(error);
7639
+ emitCliFailure(io, { json: false, quiet: false, color: "auto" }, {
7640
+ label: "lingua completion",
7641
+ reason: "completion-install-failed",
7642
+ detail: `Could not install shell completion: ${detail}`
7643
+ });
7644
+ return CLI_EXIT_CODES.runtimeError;
7645
+ }
7646
+ }
7647
+
7648
+ // src/shared/utilities/base64.ts
7649
+ function bytesToBase64(bytes) {
7650
+ let binary = "";
7651
+ for (let i2 = 0; i2 < bytes.byteLength; i2 += 1) {
7652
+ binary += String.fromCharCode(bytes[i2] ?? 0);
7653
+ }
7654
+ return btoa(binary);
7655
+ }
7656
+ function base64ToBytes(value) {
7657
+ const binary = atob(value);
7658
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
7659
+ }
7660
+ function parseEmptyOptions(raw) {
7661
+ if (raw === void 0 || raw === null) return {};
7662
+ if (typeof raw !== "object" || Array.isArray(raw)) return null;
7663
+ return {};
7664
+ }
7665
+ var base64EncodeAdapter = {
7666
+ id: "base64-encode",
7667
+ titleKey: "utilityPipeline.adapter.base64Encode.title",
7668
+ descriptionKey: "utilityPipeline.adapter.base64Encode.description",
7669
+ inputKind: "text",
7670
+ outputKind: "text",
7671
+ optionsSchema: [],
7672
+ defaultOptions: () => ({}),
7673
+ parseOptions: parseEmptyOptions,
7674
+ run: async (input) => {
7675
+ try {
7676
+ const value = bytesToBase64(new TextEncoder().encode(input));
7677
+ return { ok: true, value };
7678
+ } catch (err) {
7679
+ return {
7680
+ ok: false,
7681
+ reason: "execution-error",
7682
+ detail: err instanceof Error ? err.message : "encode failed"
7683
+ };
7684
+ }
7685
+ }
7686
+ };
7687
+ var base64DecodeAdapter = {
7688
+ id: "base64-decode",
7689
+ titleKey: "utilityPipeline.adapter.base64Decode.title",
7690
+ descriptionKey: "utilityPipeline.adapter.base64Decode.description",
7691
+ inputKind: "text",
7692
+ outputKind: "text",
7693
+ optionsSchema: [],
7694
+ defaultOptions: () => ({}),
7695
+ parseOptions: parseEmptyOptions,
7696
+ run: async (input) => {
7697
+ if (input.trim().length === 0) {
7698
+ return { ok: true, value: "" };
7699
+ }
7700
+ try {
7701
+ const sanitized = input.replace(/\s+/gu, "");
7702
+ const bytes = base64ToBytes(sanitized);
7703
+ const value = new TextDecoder().decode(bytes);
7704
+ return { ok: true, value };
7705
+ } catch (err) {
7706
+ return {
7707
+ ok: false,
7708
+ reason: "invalid-input",
7709
+ detail: err instanceof Error ? err.message : "invalid base64"
7710
+ };
7711
+ }
7712
+ }
7713
+ };
7714
+
7715
+ // src/shared/utilities/colorConvert.ts
7716
+ function parseEmptyOptions2(raw) {
7717
+ if (raw === void 0 || raw === null) return {};
7718
+ if (typeof raw !== "object" || Array.isArray(raw)) return null;
7719
+ return {};
7720
+ }
7721
+ function clampByte(value) {
7722
+ return Math.max(0, Math.min(255, Math.round(value)));
7723
+ }
7724
+ function parseColor(input) {
7725
+ const trimmed = input.trim().toLowerCase();
7726
+ const hexMatch = /^#([0-9a-f]{3,8})$/u.exec(trimmed);
7727
+ if (hexMatch) {
7728
+ const hex = hexMatch[1];
7729
+ if (hex.length === 3 || hex.length === 4) {
7730
+ const r = parseInt(hex[0] + hex[0], 16);
7731
+ const g = parseInt(hex[1] + hex[1], 16);
7732
+ const b = parseInt(hex[2] + hex[2], 16);
7733
+ const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
7734
+ return { r, g, b, a };
7735
+ }
7736
+ if (hex.length === 6 || hex.length === 8) {
7737
+ const r = parseInt(hex.slice(0, 2), 16);
7738
+ const g = parseInt(hex.slice(2, 4), 16);
7739
+ const b = parseInt(hex.slice(4, 6), 16);
7740
+ const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
7741
+ return { r, g, b, a };
7742
+ }
7743
+ return null;
7744
+ }
7745
+ const rgbMatch = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/u.exec(
7746
+ trimmed
7747
+ );
7083
7748
  if (rgbMatch) {
7084
7749
  const r = Number(rgbMatch[1]);
7085
7750
  const g = Number(rgbMatch[2]);
@@ -9544,387 +10209,57 @@ async function runUtilityCommand(args, io) {
9544
10209
  function buildOptionsBlob(adapter, cliOptions) {
9545
10210
  const blob = {
9546
10211
  ...adapter.defaultOptions()
9547
- };
9548
- const allowedKeys = new Set(adapter.optionsSchema.map((field) => field.key));
9549
- for (const { key, value } of cliOptions) {
9550
- if (!allowedKeys.has(key)) {
9551
- throw new Error(
9552
- `Adapter "${adapter.id}" has no option "${key}". Allowed: ${[...allowedKeys].sort().join(", ") || "(none)"}`
9553
- );
9554
- }
9555
- blob[key] = coerceOptionValue(adapter, key, value);
9556
- }
9557
- return blob;
9558
- }
9559
- function coerceOptionValue(adapter, key, raw) {
9560
- const field = adapter.optionsSchema.find((entry) => entry.key === key);
9561
- if (!field) return raw;
9562
- switch (field.type) {
9563
- case "text":
9564
- case "textarea":
9565
- case "select":
9566
- return raw;
9567
- case "boolean": {
9568
- if (raw === "true" || raw === "1" || raw === "yes") return true;
9569
- if (raw === "false" || raw === "0" || raw === "no") return false;
9570
- throw new Error(`Option "${key}" expects a boolean (true|false|1|0|yes|no); got "${raw}"`);
9571
- }
9572
- }
9573
- }
9574
- function emitError(io, args, reason, detail) {
9575
- emitCliFailure(io, args, { label: "lingua utility", reason, detail });
9576
- }
9577
- function runListUtilitiesCommand(args, io) {
9578
- const entries = listAdapters().map((adapter) => ({
9579
- id: adapter.id,
9580
- inputKind: adapter.inputKind,
9581
- outputKind: adapter.outputKind,
9582
- titleKey: adapter.titleKey,
9583
- descriptionKey: adapter.descriptionKey,
9584
- optionKeys: adapter.optionsSchema.map((field) => field.key)
9585
- }));
9586
- if (args.json) {
9587
- io.writeStdout(`${JSON.stringify({ utilities: entries }, null, 2)}
9588
- `);
9589
- return CLI_EXIT_CODES.ok;
9590
- }
9591
- if (args.quiet) return CLI_EXIT_CODES.ok;
9592
- for (const entry of entries) {
9593
- io.writeStdout(
9594
- `${entry.id} ${entry.inputKind} \u2192 ${entry.outputKind}` + (entry.optionKeys.length > 0 ? ` options: ${entry.optionKeys.join(", ")}` : "") + "\n"
9595
- );
9596
- }
9597
- return CLI_EXIT_CODES.ok;
9598
- }
9599
-
9600
- // src/cli/commandModel.ts
9601
- var CLI_COLOR_MODES = ["auto", "always", "never"];
9602
- var CLI_COMPLETION_SHELLS = ["bash", "zsh", "fish"];
9603
- var CLI_TOP_LEVEL_COMMANDS = ["utility", "run", "capsule", "list", "completion"];
9604
- function isCliColorMode(value) {
9605
- return CLI_COLOR_MODES.includes(value);
9606
- }
9607
- function isCliCompletionShell(value) {
9608
- return CLI_COMPLETION_SHELLS.includes(value);
9609
- }
9610
-
9611
- // src/cli/completion.ts
9612
- var commandWords = CLI_TOP_LEVEL_COMMANDS.join(" ");
9613
- var colorWords = CLI_COLOR_MODES.join(" ");
9614
- var shellWords = CLI_COMPLETION_SHELLS.join(" ");
9615
- var utilityWords = [...UTILITY_ADAPTER_IDS].sort().join(" ");
9616
- function renderCompletion(shell) {
9617
- switch (shell) {
9618
- case "bash":
9619
- return renderBashCompletion();
9620
- case "zsh":
9621
- return renderZshCompletion();
9622
- case "fish":
9623
- return renderFishCompletion();
9624
- }
9625
- }
9626
- function renderBashCompletion() {
9627
- return `# lingua bash completion
9628
- _lingua() {
9629
- local cur prev command command_index index relative word
9630
- COMPREPLY=()
9631
- cur="\${COMP_WORDS[COMP_CWORD]}"
9632
- prev=""
9633
- if (( COMP_CWORD > 0 )); then
9634
- prev="\${COMP_WORDS[COMP_CWORD-1]}"
9635
- fi
9636
- command=""
9637
- command_index=0
9638
- for (( index=1; index<COMP_CWORD; index++ )); do
9639
- word="\${COMP_WORDS[index]}"
9640
- case "$word" in
9641
- --color)
9642
- (( index++ ))
9643
- ;;
9644
- --color=*)
9645
- ;;
9646
- utility|run|capsule|list|completion)
9647
- command="$word"
9648
- command_index=$index
9649
- break
9650
- ;;
9651
- esac
9652
- done
9653
-
9654
- case "$cur" in
9655
- --color=*)
9656
- local value="\${cur#--color=}"
9657
- COMPREPLY=( $(compgen -W "${colorWords}" -- "$value") )
9658
- COMPREPLY=( "\${COMPREPLY[@]/#/--color=}" )
9659
- return
9660
- ;;
9661
- esac
9662
-
9663
- case "$prev" in
9664
- --color)
9665
- COMPREPLY=( $(compgen -W "${colorWords}" -- "$cur") )
9666
- return
9667
- ;;
9668
- --input|--stdin)
9669
- compopt -o filenames 2>/dev/null || true
9670
- COMPREPLY=( $(compgen -f -- "$cur") )
9671
- return
9672
- ;;
9673
- --timeout)
9674
- return
9675
- ;;
9676
- --env|--option)
9677
- return
9678
- ;;
9679
- esac
9680
-
9681
- if [[ -z "$command" ]]; then
9682
- COMPREPLY=( $(compgen -W "${commandWords} --help --version --color" -- "$cur") )
9683
- return
9684
- fi
9685
-
9686
- case "$command" in
9687
- utility)
9688
- relative=$(( COMP_CWORD - command_index ))
9689
- if (( relative == 1 )); then
9690
- COMPREPLY=( $(compgen -W "${utilityWords}" -- "$cur") )
9691
- elif [[ "$cur" == -* ]]; then
9692
- COMPREPLY=( $(compgen -W "--input --option --json --quiet --color --help" -- "$cur") )
9693
- fi
9694
- ;;
9695
- run)
9696
- if [[ "$cur" == -* ]]; then
9697
- COMPREPLY=( $(compgen -W "--stdin --timeout --env --json --quiet --color --help --" -- "$cur") )
9698
- else
9699
- compopt -o filenames 2>/dev/null || true
9700
- COMPREPLY=( $(compgen -f -- "$cur") )
9701
- fi
9702
- ;;
9703
- capsule)
9704
- relative=$(( COMP_CWORD - command_index ))
9705
- if (( relative == 1 )); then
9706
- COMPREPLY=( $(compgen -W "validate replay" -- "$cur") )
9707
- elif [[ "$cur" == -* ]]; then
9708
- COMPREPLY=( $(compgen -W "--timeout --env --json --quiet --color --help" -- "$cur") )
9709
- else
9710
- compopt -o filenames 2>/dev/null || true
9711
- COMPREPLY=( $(compgen -f -- "$cur") )
9712
- fi
9713
- ;;
9714
- list)
9715
- relative=$(( COMP_CWORD - command_index ))
9716
- if (( relative == 1 )); then
9717
- COMPREPLY=( $(compgen -W "utilities" -- "$cur") )
9718
- else
9719
- COMPREPLY=( $(compgen -W "--json --quiet --color --help" -- "$cur") )
9720
- fi
9721
- ;;
9722
- completion)
9723
- relative=$(( COMP_CWORD - command_index ))
9724
- if (( relative == 1 )); then
9725
- COMPREPLY=( $(compgen -W "${shellWords}" -- "$cur") )
9726
- else
9727
- COMPREPLY=( $(compgen -W "--color --help" -- "$cur") )
9728
- fi
9729
- ;;
9730
- esac
9731
- }
9732
- complete -F _lingua lingua
9733
- `;
10212
+ };
10213
+ const allowedKeys = new Set(adapter.optionsSchema.map((field) => field.key));
10214
+ for (const { key, value } of cliOptions) {
10215
+ if (!allowedKeys.has(key)) {
10216
+ throw new Error(
10217
+ `Adapter "${adapter.id}" has no option "${key}". Allowed: ${[...allowedKeys].sort().join(", ") || "(none)"}`
10218
+ );
10219
+ }
10220
+ blob[key] = coerceOptionValue(adapter, key, value);
10221
+ }
10222
+ return blob;
9734
10223
  }
9735
- function renderZshCompletion() {
9736
- return `#compdef lingua
9737
- # lingua zsh completion
9738
- _lingua() {
9739
- local context state state_descr line
9740
- typeset -A opt_args
9741
- local -a commands utilities color_modes shells
9742
- local command_index index
9743
- commands=(
9744
- 'utility:Run a shared utility adapter'
9745
- 'run:Execute a source file or project root'
9746
- 'capsule:Validate or replay a Run Capsule'
9747
- 'list:List available capabilities'
9748
- 'completion:Generate a shell completion script'
9749
- )
9750
- utilities=(${utilityWords})
9751
- color_modes=(${colorWords})
9752
- shells=(${shellWords})
9753
-
9754
- _arguments -C \\
9755
- '(-h --help)'{-h,--help}'[Show help]' \\
9756
- '(-v --version)'{-v,--version}'[Print the CLI version]' \\
9757
- '--color=[Control diagnostic color]:mode:(auto always never)' \\
9758
- '1:command:->command' \\
9759
- '*::argument:->arguments'
9760
-
9761
- case "$state" in
9762
- command)
9763
- _describe -t commands 'lingua command' commands
9764
- ;;
9765
- arguments)
9766
- command_index=0
9767
- for (( index=2; index<CURRENT; index++ )); do
9768
- case "\${words[index]}" in
9769
- --color)
9770
- (( index++ ))
9771
- ;;
9772
- --color=*)
9773
- ;;
9774
- utility|run|capsule|list|completion)
9775
- command_index=$index
9776
- break
9777
- ;;
9778
- esac
9779
- done
9780
- if (( command_index == 0 )); then
9781
- return 0
9782
- fi
9783
- words=("\${(@)words[$command_index,-1]}")
9784
- (( CURRENT -= command_index - 1 ))
9785
- case "\${words[1]}" in
9786
- utility)
9787
- if (( CURRENT == 2 )); then
9788
- _describe -t utilities 'utility' utilities
9789
- else
9790
- _arguments \\
9791
- '--input=[Read input from a file]:file:_files' \\
9792
- '*--option=[Pass an adapter key=value option]:option:' \\
9793
- '--json[Emit structured JSON]' \\
9794
- '--quiet[Suppress Lingua diagnostics]' \\
9795
- '--color=[Control diagnostic color]:mode:(auto always never)' \\
9796
- '(-h --help)'{-h,--help}'[Show help]'
9797
- fi
9798
- ;;
9799
- run)
9800
- _arguments \\
9801
- '1:source file or project:_files' \\
9802
- '--stdin=[Forward a file as program stdin]:file:_files' \\
9803
- '--timeout=[Set wall-clock timeout in milliseconds]:milliseconds:' \\
9804
- '*--env=[Add an explicit NAME=value environment entry]:environment:' \\
9805
- '--json[Emit structured JSON]' \\
9806
- '--quiet[Suppress Lingua diagnostics]' \\
9807
- '--color=[Control diagnostic color]:mode:(auto always never)' \\
9808
- '(-h --help)'{-h,--help}'[Show help]' \\
9809
- '*::program argument:'
9810
- ;;
9811
- capsule)
9812
- if (( CURRENT == 2 )); then
9813
- _values 'capsule action' validate replay
9814
- else
9815
- _arguments \\
9816
- '2:capsule file:_files' \\
9817
- '--timeout=[Set replay timeout in milliseconds]:milliseconds:' \\
9818
- '*--env=[Add an explicit NAME=value environment entry]:environment:' \\
9819
- '--json[Emit structured JSON]' \\
9820
- '--quiet[Suppress Lingua diagnostics]' \\
9821
- '--color=[Control diagnostic color]:mode:(auto always never)' \\
9822
- '(-h --help)'{-h,--help}'[Show help]'
9823
- fi
9824
- ;;
9825
- list)
9826
- _values 'list target' utilities
9827
- ;;
9828
- completion)
9829
- _describe -t shells 'shell' shells
9830
- ;;
9831
- esac
9832
- ;;
9833
- esac
10224
+ function coerceOptionValue(adapter, key, raw) {
10225
+ const field = adapter.optionsSchema.find((entry) => entry.key === key);
10226
+ if (!field) return raw;
10227
+ switch (field.type) {
10228
+ case "text":
10229
+ case "textarea":
10230
+ case "select":
10231
+ return raw;
10232
+ case "boolean": {
10233
+ if (raw === "true" || raw === "1" || raw === "yes") return true;
10234
+ if (raw === "false" || raw === "0" || raw === "no") return false;
10235
+ throw new Error(`Option "${key}" expects a boolean (true|false|1|0|yes|no); got "${raw}"`);
10236
+ }
10237
+ }
9834
10238
  }
9835
- if (( $+functions[compdef] )); then
9836
- compdef _lingua lingua
9837
- fi
9838
- `;
10239
+ function emitError(io, args, reason, detail) {
10240
+ emitCliFailure(io, args, { label: "lingua utility", reason, detail });
9839
10241
  }
9840
- function renderFishCompletion() {
9841
- const utilityLines = [...UTILITY_ADAPTER_IDS].sort().map((id) => `complete -c lingua -n '__fish_lingua_needs_first_argument utility' -a '${id}'`).join("\n");
9842
- return `# lingua fish completion
9843
- function __fish_lingua_needs_command
9844
- set -l command_index (__fish_lingua_command_index)
9845
- test -z "$command_index"
9846
- end
9847
-
9848
- function __fish_lingua_command_index
9849
- set -l tokens (commandline -opc)
9850
- set -l skip_next 0
9851
- for index in (seq 2 (count $tokens))
9852
- set -l token $tokens[$index]
9853
- if test $skip_next -eq 1
9854
- set skip_next 0
9855
- continue
9856
- end
9857
- switch $token
9858
- case --color
9859
- set skip_next 1
9860
- case '--color=*' --json --quiet --help -h --version -v
9861
- continue
9862
- case utility run capsule list completion
9863
- echo $index
9864
- return 0
9865
- end
9866
- end
9867
- return 1
9868
- end
9869
-
9870
- function __fish_lingua_using_command
9871
- set -l tokens (commandline -opc)
9872
- set -l command_index (__fish_lingua_command_index)
9873
- test -n "$command_index"; and test "$tokens[$command_index]" = "$argv[1]"
9874
- end
9875
-
9876
- function __fish_lingua_needs_first_argument
9877
- set -l tokens (commandline -opc)
9878
- set -l command_index (__fish_lingua_command_index)
9879
- if test -z "$command_index"; or test "$tokens[$command_index]" != "$argv[1]"
9880
- return 1
9881
- end
9882
- set -l skip_next 0
9883
- for index in (seq (math $command_index + 1) (count $tokens))
9884
- set -l token $tokens[$index]
9885
- if test $skip_next -eq 1
9886
- set skip_next 0
9887
- continue
9888
- end
9889
- switch $token
9890
- case --color --input --option --stdin --timeout --env
9891
- set skip_next 1
9892
- case '--color=*' '--input=*' '--option=*' '--stdin=*' '--timeout=*' '--env=*' --json --quiet --help -h
9893
- continue
9894
- case '*'
9895
- return 1
9896
- end
9897
- end
9898
- return 0
9899
- end
9900
-
9901
- complete -c lingua -f -n __fish_lingua_needs_command -a 'utility' -d 'Run a shared utility adapter'
9902
- complete -c lingua -f -n __fish_lingua_needs_command -a 'run' -d 'Execute a source file or project root'
9903
- complete -c lingua -f -n __fish_lingua_needs_command -a 'capsule' -d 'Validate or replay a Run Capsule'
9904
- complete -c lingua -f -n __fish_lingua_needs_command -a 'list' -d 'List available capabilities'
9905
- complete -c lingua -f -n __fish_lingua_needs_command -a 'completion' -d 'Generate a shell completion script'
9906
-
9907
- complete -c lingua -l help -s h -d 'Show help'
9908
- complete -c lingua -l version -s v -d 'Print the CLI version'
9909
- complete -c lingua -l color -r -f -a '${colorWords}' -d 'Control diagnostic color'
9910
- complete -c lingua -l json -d 'Emit structured JSON'
9911
- complete -c lingua -l quiet -d 'Suppress Lingua diagnostics'
9912
-
9913
- ${utilityLines}
9914
- complete -c lingua -n '__fish_lingua_using_command utility' -l input -r -F -d 'Read input from a file'
9915
- complete -c lingua -n '__fish_lingua_using_command utility' -l option -r -d 'Pass an adapter key=value option'
9916
-
9917
- complete -c lingua -n '__fish_lingua_using_command run' -l stdin -r -F -d 'Forward a file as program stdin'
9918
- complete -c lingua -n '__fish_lingua_using_command run' -l timeout -r -d 'Set wall-clock timeout in milliseconds'
9919
- complete -c lingua -n '__fish_lingua_using_command run' -l env -r -d 'Add an explicit NAME=value environment entry'
9920
-
9921
- complete -c lingua -n '__fish_lingua_needs_first_argument capsule' -a 'validate replay'
9922
- complete -c lingua -n '__fish_lingua_using_command capsule' -l timeout -r -d 'Set replay timeout in milliseconds'
9923
- complete -c lingua -n '__fish_lingua_using_command capsule' -l env -r -d 'Add an explicit NAME=value environment entry'
9924
-
9925
- complete -c lingua -n '__fish_lingua_needs_first_argument list' -a 'utilities'
9926
- complete -c lingua -n '__fish_lingua_needs_first_argument completion' -a '${shellWords}'
9927
- `;
10242
+ function runListUtilitiesCommand(args, io) {
10243
+ const entries = listAdapters().map((adapter) => ({
10244
+ id: adapter.id,
10245
+ inputKind: adapter.inputKind,
10246
+ outputKind: adapter.outputKind,
10247
+ titleKey: adapter.titleKey,
10248
+ descriptionKey: adapter.descriptionKey,
10249
+ optionKeys: adapter.optionsSchema.map((field) => field.key)
10250
+ }));
10251
+ if (args.json) {
10252
+ io.writeStdout(`${JSON.stringify({ utilities: entries }, null, 2)}
10253
+ `);
10254
+ return CLI_EXIT_CODES.ok;
10255
+ }
10256
+ if (args.quiet) return CLI_EXIT_CODES.ok;
10257
+ for (const entry of entries) {
10258
+ io.writeStdout(
10259
+ `${entry.id} ${entry.inputKind} \u2192 ${entry.outputKind}` + (entry.optionKeys.length > 0 ? ` options: ${entry.optionKeys.join(", ")}` : "") + "\n"
10260
+ );
10261
+ }
10262
+ return CLI_EXIT_CODES.ok;
9928
10263
  }
9929
10264
 
9930
10265
  // src/cli/helpCatalog.ts
@@ -10015,14 +10350,18 @@ var CLI_HELP_CATALOG = {
10015
10350
  {
10016
10351
  id: "completion",
10017
10352
  topLevel: "completion",
10018
- invocation: "lingua completion bash|zsh|fish",
10019
- summary: "Generate a deterministic shell completion script.",
10020
- description: "Prints network-free Bash, Zsh, or Fish completion source without ANSI styling.",
10021
- flags: ["color", "help"],
10353
+ invocation: "lingua completion [bash|zsh|fish|install] [--yes] [--dry-run]",
10354
+ summary: "Install completions interactively or print one shell script.",
10355
+ description: "With no target or with install, detects Bash, Zsh, and Fish, shows the target files, and asks before writing. A shell target prints deterministic network-free source.",
10356
+ flags: ["yes", "dry-run", "color", "help"],
10022
10357
  examples: [
10023
10358
  {
10024
- command: "lingua completion zsh > ~/.zfunc/_lingua",
10025
- description: "Install the Zsh completion file."
10359
+ command: "lingua completion",
10360
+ description: "Detect supported shells and offer to install their completions."
10361
+ },
10362
+ {
10363
+ command: "lingua completion install --yes",
10364
+ description: "Install every detected completion without prompting."
10026
10365
  }
10027
10366
  ]
10028
10367
  }
@@ -10035,6 +10374,8 @@ var CLI_HELP_CATALOG = {
10035
10374
  { id: "option", syntax: "--option key=value", summary: "Repeat to pass an adapter option.", commands: ["utility"] },
10036
10375
  { id: "json", syntax: "--json", summary: "Emit a stable structured JSON body instead of plain text.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities"] },
10037
10376
  { id: "quiet", syntax: "--quiet", summary: "Suppress Lingua diagnostics while preserving command output.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities"] },
10377
+ { id: "yes", syntax: "--yes", summary: "Approve detected shell-completion changes without prompting.", commands: ["completion"] },
10378
+ { id: "dry-run", syntax: "--dry-run", summary: "Show detected shells and target files without writing.", commands: ["completion"] },
10038
10379
  { id: "color", syntax: "--color <auto|always|never>", summary: "Control diagnostic color. The default is auto.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities", "completion"] },
10039
10380
  { id: "separator", syntax: "--", summary: "Forward every remaining token to the executed program unchanged.", commands: ["run"] },
10040
10381
  { id: "help", syntax: "--help, -h", summary: "Show help.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities", "completion"] },
@@ -10079,7 +10420,8 @@ ${examples}
10079
10420
  }
10080
10421
 
10081
10422
  // src/cli/io.ts
10082
- var import_promises3 = require("node:fs/promises");
10423
+ var import_promises4 = require("node:fs/promises");
10424
+ var import_promises5 = require("node:readline/promises");
10083
10425
  function createDefaultIo() {
10084
10426
  return {
10085
10427
  stdoutSupportsColor: process.stdout.isTTY === true && (typeof process.stdout.hasColors !== "function" || process.stdout.hasColors()),
@@ -10087,14 +10429,28 @@ function createDefaultIo() {
10087
10429
  getEnvironmentValue(name) {
10088
10430
  return process.env[name];
10089
10431
  },
10432
+ async confirm(message, defaultAnswer) {
10433
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
10434
+ return null;
10435
+ }
10436
+ const choices = defaultAnswer ? "Y/n" : "y/N";
10437
+ const readline = (0, import_promises5.createInterface)({ input: process.stdin, output: process.stdout });
10438
+ try {
10439
+ const answer = (await readline.question(`${message} [${choices}] `)).trim().toLowerCase();
10440
+ if (answer.length === 0) return defaultAnswer;
10441
+ return answer === "y" || answer === "yes";
10442
+ } finally {
10443
+ readline.close();
10444
+ }
10445
+ },
10090
10446
  writeStdout(text) {
10091
10447
  process.stdout.write(text);
10092
10448
  },
10093
10449
  writeStderr(text) {
10094
10450
  process.stderr.write(text);
10095
10451
  },
10096
- async readFile(path2) {
10097
- return (0, import_promises3.readFile)(path2, "utf8");
10452
+ async readFile(path4) {
10453
+ return (0, import_promises4.readFile)(path4, "utf8");
10098
10454
  },
10099
10455
  async readStdin() {
10100
10456
  if (process.stdin.isTTY) {
@@ -10163,7 +10519,9 @@ function freshFlags(color = "auto") {
10163
10519
  options: [],
10164
10520
  env: [],
10165
10521
  programArgs: [],
10166
- help: false
10522
+ help: false,
10523
+ yes: false,
10524
+ dryRun: false
10167
10525
  };
10168
10526
  }
10169
10527
  function finalize(command, positionals, flags) {
@@ -10180,7 +10538,9 @@ function finalize(command, positionals, flags) {
10180
10538
  options: flags.options,
10181
10539
  env: flags.env,
10182
10540
  programArgs: flags.programArgs,
10183
- help: flags.help
10541
+ help: flags.help,
10542
+ yes: flags.yes,
10543
+ dryRun: flags.dryRun
10184
10544
  }
10185
10545
  };
10186
10546
  }
@@ -10420,30 +10780,37 @@ function parseCompletion(rest, color) {
10420
10780
  flags.help = true;
10421
10781
  continue;
10422
10782
  }
10783
+ if (arg === "--yes") {
10784
+ flags.yes = true;
10785
+ continue;
10786
+ }
10787
+ if (arg === "--dry-run") {
10788
+ flags.dryRun = true;
10789
+ continue;
10790
+ }
10423
10791
  if (arg.startsWith("-")) {
10424
10792
  throw new CliUsageError(
10425
- `Unknown flag "${arg}" for "lingua completion". Allowed: --color, --help`
10793
+ `Unknown flag "${arg}" for "lingua completion". Allowed: --yes, --dry-run, --color, --help`
10426
10794
  );
10427
10795
  }
10428
10796
  positionals.push(arg);
10429
10797
  }
10430
- if (!flags.help && positionals.length === 0) {
10431
- throw new CliUsageError(
10432
- `lingua completion requires a <shell> positional. Available: ${CLI_COMPLETION_SHELLS.join(", ")}`
10433
- );
10434
- }
10435
10798
  if (positionals.length > 1) {
10436
10799
  throw new CliUsageError(
10437
10800
  `lingua completion accepts one <shell>; got ${positionals.length}: ${positionals.join(", ")}`
10438
10801
  );
10439
10802
  }
10440
10803
  const shell = positionals[0];
10441
- if (!flags.help && shell !== void 0 && !isCliCompletionShell(shell)) {
10804
+ if (!flags.help && shell !== void 0 && shell !== "install" && !isCliCompletionShell(shell)) {
10442
10805
  throw new CliUsageError(
10443
- `Unknown completion shell "${shell}". Available: ${CLI_COMPLETION_SHELLS.join(", ")}`
10806
+ `Unknown completion target "${shell}". Available: install, ${CLI_COMPLETION_SHELLS.join(", ")}`
10444
10807
  );
10445
10808
  }
10446
- return finalize("completion", positionals, flags);
10809
+ const installing = shell === void 0 || shell === "install";
10810
+ if (!installing && (flags.yes || flags.dryRun)) {
10811
+ throw new CliUsageError("--yes and --dry-run are only valid for completion installation");
10812
+ }
10813
+ return finalize(installing ? "completion-install" : "completion", positionals, flags);
10447
10814
  }
10448
10815
  function extractColorFlag(argv) {
10449
10816
  const separator = argv.indexOf("--");
@@ -10554,8 +10921,8 @@ function assertSingleTarget(command, positionals, help, label) {
10554
10921
 
10555
10922
  // src/cli/lingua.ts
10556
10923
  function resolveCliVersion() {
10557
- if ("1.2.0".length > 0) {
10558
- return "1.2.0";
10924
+ if ("1.4.1".length > 0) {
10925
+ return "1.4.1";
10559
10926
  }
10560
10927
  return "0.0.0-dev";
10561
10928
  }
@@ -10610,6 +10977,12 @@ async function dispatch(argv, io) {
10610
10977
  io.writeStdout(renderCompletion(shell));
10611
10978
  return CLI_EXIT_CODES.ok;
10612
10979
  }
10980
+ if (parsed.command === "completion-install") {
10981
+ return runCompletionInstallCommand(
10982
+ { assumeYes: parsed.flags.yes, dryRun: parsed.flags.dryRun },
10983
+ io
10984
+ );
10985
+ }
10613
10986
  if (parsed.command === "utility") {
10614
10987
  const utilityId = parsed.positionals[0];
10615
10988
  if (utilityId === void 0) {