@linguacode/cli 1.6.2 → 2.1.0

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 +3 -3
  2. package/bin/lingua.cjs +1740 -42
  3. package/package.json +2 -2
package/bin/lingua.cjs CHANGED
@@ -65,12 +65,111 @@ function decodePrefix(bytes, maxBytes) {
65
65
  return decoder.decode(bytes.subarray(0, end));
66
66
  }
67
67
 
68
+ // src/shared/redaction.ts
69
+ var DENY_SUBSTRINGS = [
70
+ "content",
71
+ "code",
72
+ "source",
73
+ "snippet",
74
+ "file",
75
+ "path",
76
+ "apikey",
77
+ "api_key",
78
+ "secret",
79
+ "credential",
80
+ "authorization",
81
+ "privatekey",
82
+ "private_key",
83
+ "accesskey",
84
+ "access_key",
85
+ "licensekey",
86
+ "license_key",
87
+ "token",
88
+ "password",
89
+ "email",
90
+ "name",
91
+ "project"
92
+ ];
93
+ function keyLooksSensitive(key) {
94
+ const lower = key.toLowerCase();
95
+ return DENY_SUBSTRINGS.some((deny) => lower.includes(deny));
96
+ }
97
+ function valueLooksSensitive(value) {
98
+ if (value === null) return false;
99
+ const t = typeof value;
100
+ if (t === "string" || t === "number" || t === "boolean") return false;
101
+ return true;
102
+ }
103
+ function redactFlatRecord(record) {
104
+ const surviving = {};
105
+ const dropped = [];
106
+ for (const [key, value] of Object.entries(record)) {
107
+ if (keyLooksSensitive(key)) {
108
+ dropped.push({ key, reason: "key" });
109
+ continue;
110
+ }
111
+ if (valueLooksSensitive(value)) {
112
+ dropped.push({ key, reason: "value" });
113
+ continue;
114
+ }
115
+ surviving[key] = value;
116
+ }
117
+ return { surviving, dropped };
118
+ }
119
+
68
120
  // src/shared/runCapsule.ts
69
121
  var MAX_STREAM_BYTES = 1048576;
70
122
  var MAX_CAPSULE_BYTES = 4194304;
71
123
  function isRecord(value) {
72
124
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
73
125
  }
126
+ function sanitizeRunCapsule(capsule) {
127
+ const omittedFields = [];
128
+ let stdout = capsule.result.stdout;
129
+ if (typeof stdout === "string" && utf8ByteLength(stdout) > MAX_STREAM_BYTES) {
130
+ stdout = truncateUtf8(stdout, MAX_STREAM_BYTES);
131
+ omittedFields.push("result.stdout");
132
+ }
133
+ let stderr = capsule.result.stderr;
134
+ if (typeof stderr === "string" && utf8ByteLength(stderr) > MAX_STREAM_BYTES) {
135
+ stderr = truncateUtf8(stderr, MAX_STREAM_BYTES);
136
+ omittedFields.push("result.stderr");
137
+ }
138
+ let dependencySummary = capsule.environment.dependencySummary;
139
+ if (dependencySummary !== void 0 && dependencySummary !== null) {
140
+ if (typeof dependencySummary === "object" && !Array.isArray(dependencySummary)) {
141
+ const { surviving, dropped } = redactFlatRecord(
142
+ dependencySummary
143
+ );
144
+ dependencySummary = surviving;
145
+ if (dropped.length > 0) {
146
+ omittedFields.push("environment.dependencySummary");
147
+ }
148
+ } else {
149
+ dependencySummary = void 0;
150
+ omittedFields.push("environment.dependencySummary");
151
+ }
152
+ }
153
+ const sanitisedResult = {
154
+ ...capsule.result,
155
+ ...stdout !== void 0 ? { stdout } : {},
156
+ ...stderr !== void 0 ? { stderr } : {}
157
+ };
158
+ return {
159
+ ...capsule,
160
+ result: sanitisedResult,
161
+ environment: {
162
+ ...capsule.environment,
163
+ ...dependencySummary !== void 0 ? { dependencySummary } : { dependencySummary: void 0 }
164
+ },
165
+ privacy: {
166
+ redactionVersion: capsule.privacy.redactionVersion,
167
+ omittedFields: [
168
+ .../* @__PURE__ */ new Set([...capsule.privacy.omittedFields, ...omittedFields])
169
+ ]
170
+ }
171
+ };
172
+ }
74
173
  var CURRENT_RUN_CAPSULE_VERSION = 1;
75
174
  var CAPSULE_MIGRATIONS = {};
76
175
  function applyCapsuleMigrations(candidate, fromVersion, toVersion, migrations) {
@@ -5762,14 +5861,14 @@ pp.readCodePoint = function() {
5762
5861
  }
5763
5862
  return code;
5764
5863
  };
5765
- pp.readString = function(quote) {
5864
+ pp.readString = function(quote2) {
5766
5865
  var out = "", chunkStart = ++this.pos;
5767
5866
  for (; ; ) {
5768
5867
  if (this.pos >= this.input.length) {
5769
5868
  this.raise(this.start, "Unterminated string constant");
5770
5869
  }
5771
5870
  var ch = this.input.charCodeAt(this.pos);
5772
- if (ch === quote) {
5871
+ if (ch === quote2) {
5773
5872
  break;
5774
5873
  }
5775
5874
  if (ch === 92) {
@@ -6124,9 +6223,9 @@ function pythonInterpreterCandidates(options) {
6124
6223
  }
6125
6224
  return candidates;
6126
6225
  }
6127
- async function resolvePythonInterpreter(options, probe) {
6226
+ async function resolvePythonInterpreter(options, probe2) {
6128
6227
  for (const candidate of pythonInterpreterCandidates(options)) {
6129
- const resolved = await probe(candidate);
6228
+ const resolved = await probe2(candidate);
6130
6229
  if (resolved !== null) return resolved;
6131
6230
  }
6132
6231
  return null;
@@ -6491,8 +6590,11 @@ async function findPython(startDirectory, env = process.env, platform = process.
6491
6590
  return resolved ?? commandName(pythonCommandCandidates(platform)[0]);
6492
6591
  }
6493
6592
  async function executableIsOnPath(executable, platform = process.platform, env = process.env) {
6593
+ return await findExecutableOnPath(executable, platform, env) !== null;
6594
+ }
6595
+ async function findExecutableOnPath(executable, platform = process.platform, env = process.env) {
6494
6596
  const pathValue = env.PATH ?? env.Path ?? env.path;
6495
- if (!pathValue) return false;
6597
+ if (!pathValue) return null;
6496
6598
  const windows = platform === "win32";
6497
6599
  const pathApi = windows ? import_node_path2.default.win32 : import_node_path2.default.posix;
6498
6600
  const delimiter = windows ? ";" : ":";
@@ -6504,10 +6606,10 @@ async function executableIsOnPath(executable, platform = process.platform, env =
6504
6606
  const base = pathApi.join(entry, executable);
6505
6607
  const candidates = windows && !hasExtension ? extensions.map((extension) => base + extension) : [base];
6506
6608
  for (const candidate of candidates) {
6507
- if (await isExecutableFile(candidate, platform)) return true;
6609
+ if (await isExecutableFile(candidate, platform)) return candidate;
6508
6610
  }
6509
6611
  }
6510
- return false;
6612
+ return null;
6511
6613
  }
6512
6614
  function commandName(name) {
6513
6615
  return process.platform === "win32" && ["npm", "npx"].includes(name) ? `${name}.cmd` : name;
@@ -6701,7 +6803,7 @@ var RUNTIMES = {
6701
6803
  node: {
6702
6804
  name: "Node.js",
6703
6805
  verifyExecutable: "node",
6704
- homebrewFormula: "node@24",
6806
+ homebrewFormula: "node@26",
6705
6807
  installGuide: "https://nodejs.org/en/download"
6706
6808
  }
6707
6809
  };
@@ -7043,7 +7145,7 @@ function emitCliFailure(io, options, failure) {
7043
7145
  if (options.quiet) return;
7044
7146
  const label2 = styleCliText(io, options.color, "stderr", "bold", failure.label);
7045
7147
  const marker = styleCliText(io, options.color, "stderr", "red", `error[${failure.reason}]`);
7046
- io.writeStderr(`${label2}: ${marker}: ${failure.detail}
7148
+ io.writeStderr(`${label2}: ${marker}: ${neutralizeControlCharacters(failure.detail)}
7047
7149
  `);
7048
7150
  }
7049
7151
  function renderCliHelp(io, mode, helpText) {
@@ -7061,7 +7163,22 @@ function renderCliSuccess(io, mode, text) {
7061
7163
  return styleCliText(io, mode, "stdout", "green", text);
7062
7164
  }
7063
7165
  function renderCliNotice(io, mode, text, tone = "warning") {
7064
- return styleCliText(io, mode, "stderr", tone === "success" ? "green" : "yellow", text);
7166
+ return styleCliText(
7167
+ io,
7168
+ mode,
7169
+ "stderr",
7170
+ tone === "success" ? "green" : "yellow",
7171
+ neutralizeControlCharacters(text)
7172
+ );
7173
+ }
7174
+ function neutralizeControlCharacters(text) {
7175
+ let result = "";
7176
+ for (const character of text) {
7177
+ const code = character.codePointAt(0) ?? 0;
7178
+ const control = code <= 31 && code !== 10 && code !== 9 || code >= 127 && code <= 159;
7179
+ result += control ? `\\x${code.toString(16).padStart(2, "0")}` : character;
7180
+ }
7181
+ return result;
7065
7182
  }
7066
7183
 
7067
7184
  // src/cli/runtime/environment.ts
@@ -7401,15 +7518,14 @@ async function loadCapsule(filePath, io) {
7401
7518
  try {
7402
7519
  raw = await io.readFile(filePath);
7403
7520
  } catch (error) {
7404
- const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
7405
- return {
7406
- ok: false,
7407
- reason: code === "ENOENT" ? "file-not-found" : "read-failed",
7408
- detail: errorMessage3(error)
7409
- };
7521
+ return { ok: false, reason: readFailureReason(error), detail: errorMessage3(error) };
7410
7522
  }
7411
7523
  return parseRunCapsule(raw);
7412
7524
  }
7525
+ function readFailureReason(error) {
7526
+ const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
7527
+ return code === "ENOENT" ? "file-not-found" : "read-failed";
7528
+ }
7413
7529
  function emit(io, args, ok, reasonOrSummary, detail) {
7414
7530
  if (args.json) {
7415
7531
  const body = ok ? { ok: true, summary: reasonOrSummary } : detail !== void 0 ? { ok: false, reason: reasonOrSummary, detail } : { ok: false, reason: reasonOrSummary };
@@ -7434,6 +7550,14 @@ function errorMessage3(error) {
7434
7550
  }
7435
7551
 
7436
7552
  // src/cli/commands/capsuleVerify.ts
7553
+ function strictCapsuleVerdict(capsule, run) {
7554
+ const comparison = compareCapsuleStreams(capsule, run);
7555
+ const incomplete = Boolean(
7556
+ run.truncated?.stdout || run.truncated?.stderr || run.status === "timeout" || run.status === "stopped" || run.reason === "missing-runtime" || run.reason === "spawn-failed" || run.reason === "prepare-failed"
7557
+ );
7558
+ const verdict = incomplete ? "inconclusive" : comparison.matches ? "pass" : "fail";
7559
+ return { comparison, incomplete, verdict };
7560
+ }
7437
7561
  var label = "lingua capsule verify";
7438
7562
  var preflightFields = { command: "capsule-verify", verdict: "inconclusive" };
7439
7563
  async function runVerifyCapsuleCommand(args, io) {
@@ -7526,11 +7650,7 @@ async function verifyCapsuleBaseline(capsule, args, io) {
7526
7650
  ...remaining !== void 0 ? { timeoutMs: Math.min(requestedTimeout, remaining) } : args.timeoutMs !== void 0 ? { timeoutMs: args.timeoutMs } : {}
7527
7651
  });
7528
7652
  const budgetExhausted = budgetCapped && run.status === "timeout";
7529
- const comparison = compareCapsuleStreams(capsule, run);
7530
- const incomplete = Boolean(
7531
- run.truncated?.stdout || run.truncated?.stderr || run.status === "timeout" || run.status === "stopped" || run.reason === "missing-runtime" || run.reason === "spawn-failed" || run.reason === "prepare-failed"
7532
- );
7533
- const verdict = incomplete ? "inconclusive" : comparison.matches ? "pass" : "fail";
7653
+ const { comparison, incomplete, verdict } = strictCapsuleVerdict(capsule, run);
7534
7654
  const result = {
7535
7655
  ok: verdict === "pass",
7536
7656
  command: "capsule-verify",
@@ -7674,7 +7794,14 @@ var import_node_path5 = __toESM(require("node:path"));
7674
7794
  var CLI_COLOR_MODES = ["auto", "always", "never"];
7675
7795
  var CLI_COMPLETION_SHELLS = ["bash", "zsh", "fish"];
7676
7796
  var CLI_COMPLETION_TARGETS = [...CLI_COMPLETION_SHELLS, "install"];
7677
- var CLI_TOP_LEVEL_COMMANDS = ["utility", "run", "capsule", "list", "completion"];
7797
+ var CLI_TOP_LEVEL_COMMANDS = [
7798
+ "utility",
7799
+ "run",
7800
+ "capsule",
7801
+ "repro",
7802
+ "list",
7803
+ "completion"
7804
+ ];
7678
7805
  function isCliColorMode(value) {
7679
7806
  return CLI_COLOR_MODES.includes(value);
7680
7807
  }
@@ -7726,6 +7853,7 @@ var UTILITY_ADAPTER_IDS = [
7726
7853
 
7727
7854
  // src/cli/completion.ts
7728
7855
  var commandWords = CLI_TOP_LEVEL_COMMANDS.join(" ");
7856
+ var commandPattern = CLI_TOP_LEVEL_COMMANDS.join("|");
7729
7857
  var colorWords = CLI_COLOR_MODES.join(" ");
7730
7858
  var shellWords = CLI_COMPLETION_TARGETS.join(" ");
7731
7859
  var utilityWords = [...UTILITY_ADAPTER_IDS].sort().join(" ");
@@ -7759,7 +7887,7 @@ _lingua() {
7759
7887
  ;;
7760
7888
  --color=*)
7761
7889
  ;;
7762
- utility|run|capsule|list|completion)
7890
+ ${commandPattern})
7763
7891
  command="$word"
7764
7892
  command_index=$index
7765
7893
  break
@@ -7781,12 +7909,12 @@ _lingua() {
7781
7909
  COMPREPLY=( $(compgen -W "${colorWords}" -- "$cur") )
7782
7910
  return
7783
7911
  ;;
7784
- --input|--stdin|--target|--root)
7912
+ --input|--stdin|--target|--root|--file)
7785
7913
  compopt -o filenames 2>/dev/null || true
7786
7914
  COMPREPLY=( $(compgen -f -- "$cur") )
7787
7915
  return
7788
7916
  ;;
7789
- --timeout)
7917
+ --timeout|--entry|--node|--approve)
7790
7918
  return
7791
7919
  ;;
7792
7920
  --env|--option)
@@ -7832,6 +7960,22 @@ _lingua() {
7832
7960
  COMPREPLY=( $(compgen -f -- "$cur") )
7833
7961
  fi
7834
7962
  ;;
7963
+ repro)
7964
+ relative=$(( COMP_CWORD - command_index ))
7965
+ if (( relative == 1 )); then
7966
+ COMPREPLY=( $(compgen -W "pack review run" -- "$cur") )
7967
+ elif [[ "$cur" == -* ]]; then
7968
+ local flags="--json --quiet --color --help"
7969
+ case "\${COMP_WORDS[command_index+1]}" in
7970
+ pack) flags="$flags --entry --file --root --node" ;;
7971
+ run) flags="$flags --approve" ;;
7972
+ esac
7973
+ COMPREPLY=( $(compgen -W "$flags" -- "$cur") )
7974
+ else
7975
+ compopt -o filenames 2>/dev/null || true
7976
+ COMPREPLY=( $(compgen -f -- "$cur") )
7977
+ fi
7978
+ ;;
7835
7979
  list)
7836
7980
  relative=$(( COMP_CWORD - command_index ))
7837
7981
  if (( relative == 1 )); then
@@ -7859,12 +8003,13 @@ function renderZshCompletion() {
7859
8003
  _lingua() {
7860
8004
  local context state state_descr line
7861
8005
  typeset -A opt_args
7862
- local -a commands utilities color_modes completion_targets capsule_flags
8006
+ local -a commands utilities color_modes completion_targets capsule_flags repro_flags
7863
8007
  local command_index index
7864
8008
  commands=(
7865
8009
  'utility:Run a shared utility adapter'
7866
8010
  'run:Execute a source file or project root'
7867
8011
  'capsule:Validate or replay a Run Capsule'
8012
+ 'repro:Pack, review or run a permissioned reproduction'
7868
8013
  'list:List available capabilities'
7869
8014
  'completion:Generate a shell completion script'
7870
8015
  )
@@ -7892,7 +8037,7 @@ _lingua() {
7892
8037
  ;;
7893
8038
  --color=*)
7894
8039
  ;;
7895
- utility|run|capsule|list|completion)
8040
+ ${commandPattern})
7896
8041
  command_index=$index
7897
8042
  break
7898
8043
  ;;
@@ -7949,6 +8094,29 @@ _lingua() {
7949
8094
  '(-h --help)'{-h,--help}'[Show help]'
7950
8095
  fi
7951
8096
  ;;
8097
+ repro)
8098
+ if (( CURRENT == 2 )); then
8099
+ _values 'repro action' pack review run
8100
+ else
8101
+ repro_flags=()
8102
+ case "\${words[2]}" in
8103
+ pack) repro_flags=(
8104
+ '--entry=[Relative .mjs or .cjs entry path]:path:'
8105
+ '*--file=[Supplemental file relative to --root]:file:_files'
8106
+ '--root=[Directory packed files are read from]:directory:_files -/'
8107
+ '--node=[Requested Node.js major]:major:'
8108
+ ) ;;
8109
+ run) repro_flags=('--approve=[Approval token from lingua repro review]:token:') ;;
8110
+ esac
8111
+ _arguments \\
8112
+ '2:file:_files' \\
8113
+ "\${repro_flags[@]}" \\
8114
+ '--json[Emit structured JSON]' \\
8115
+ '--quiet[Suppress Lingua diagnostics]' \\
8116
+ '--color=[Control diagnostic color]:mode:(auto always never)' \\
8117
+ '(-h --help)'{-h,--help}'[Show help]'
8118
+ fi
8119
+ ;;
7952
8120
  list)
7953
8121
  _values 'list target' utilities
7954
8122
  ;;
@@ -7986,7 +8154,7 @@ function __fish_lingua_command_index
7986
8154
  set skip_next 1
7987
8155
  case '--color=*' --json --quiet --help -h --version -v
7988
8156
  continue
7989
- case utility run capsule list completion
8157
+ case ${commandWords}
7990
8158
  echo $index
7991
8159
  return 0
7992
8160
  end
@@ -8008,6 +8176,14 @@ function __fish_lingua_using_capsule_action
8008
8176
  test "$tokens[$command_index]" = capsule; and test "$tokens[$action_index]" = "$argv[1]"
8009
8177
  end
8010
8178
 
8179
+ function __fish_lingua_using_repro_action
8180
+ set -l tokens (commandline -opc)
8181
+ set -l command_index (__fish_lingua_command_index)
8182
+ test -n "$command_index"; or return 1
8183
+ set -l action_index (math $command_index + 1)
8184
+ test "$tokens[$command_index]" = repro; and test "$tokens[$action_index]" = "$argv[1]"
8185
+ end
8186
+
8011
8187
  function __fish_lingua_needs_first_argument
8012
8188
  set -l tokens (commandline -opc)
8013
8189
  set -l command_index (__fish_lingua_command_index)
@@ -8036,6 +8212,7 @@ end
8036
8212
  complete -c lingua -f -n __fish_lingua_needs_command -a 'utility' -d 'Run a shared utility adapter'
8037
8213
  complete -c lingua -f -n __fish_lingua_needs_command -a 'run' -d 'Execute a source file or project root'
8038
8214
  complete -c lingua -f -n __fish_lingua_needs_command -a 'capsule' -d 'Validate or replay a Run Capsule'
8215
+ complete -c lingua -f -n __fish_lingua_needs_command -a 'repro' -d 'Pack, review or run a permissioned reproduction'
8039
8216
  complete -c lingua -f -n __fish_lingua_needs_command -a 'list' -d 'List available capabilities'
8040
8217
  complete -c lingua -f -n __fish_lingua_needs_command -a 'completion' -d 'Generate a shell completion script'
8041
8218
 
@@ -8059,6 +8236,13 @@ complete -c lingua -n '__fish_lingua_using_capsule_action verify-suite' -l root
8059
8236
  complete -c lingua -n '__fish_lingua_using_command capsule' -l timeout -r -d 'Set per-case execution timeout in milliseconds'
8060
8237
  complete -c lingua -n '__fish_lingua_using_command capsule' -l env -r -d 'Add an explicit NAME=value environment entry'
8061
8238
 
8239
+ complete -c lingua -n '__fish_lingua_needs_first_argument repro' -a 'pack review run'
8240
+ complete -c lingua -n '__fish_lingua_using_repro_action pack' -l entry -r -d 'Relative .mjs or .cjs entry path'
8241
+ complete -c lingua -n '__fish_lingua_using_repro_action pack' -l file -r -F -d 'Supplemental file relative to --root'
8242
+ complete -c lingua -n '__fish_lingua_using_repro_action pack' -l root -r -d 'Directory packed files are read from'
8243
+ complete -c lingua -n '__fish_lingua_using_repro_action pack' -l node -r -d 'Requested Node.js major'
8244
+ complete -c lingua -n '__fish_lingua_using_repro_action run' -l approve -r -d 'Approval token from lingua repro review'
8245
+
8062
8246
  complete -c lingua -n '__fish_lingua_needs_first_argument list' -a 'utilities'
8063
8247
  complete -c lingua -n '__fish_lingua_needs_first_argument completion' -a '${shellWords}'
8064
8248
  complete -c lingua -n '__fish_lingua_using_command completion' -l yes -d 'Install without interactive confirmation'
@@ -8244,6 +8428,1305 @@ Start a new shell session to load it.
8244
8428
  }
8245
8429
  }
8246
8430
 
8431
+ // src/cli/commands/repro.ts
8432
+ var import_node_os4 = require("node:os");
8433
+ var import_node_path9 = __toESM(require("node:path"));
8434
+
8435
+ // src/shared/httpWorkspaceSchema.ts
8436
+ var MAX_RESPONSE_BODY_BYTES = 4 * 1048576;
8437
+ var SNAPSHOT_MAX_BODY_BYTES = 256 * 1024;
8438
+ var MAX_REQUEST_TIMEOUT_MS = 5 * 60 * 1e3;
8439
+
8440
+ // src/shared/httpEnvironment.ts
8441
+ function looksSecret(key) {
8442
+ if (typeof key !== "string" || key.length === 0) return false;
8443
+ const normalised = key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
8444
+ return /(^|[^A-Z0-9])(TOKEN|KEY|APIKEY|SECRET|PASSWORD|JWT|BEARER|AUTH|COOKIE|SESSION|SESSION_ID|SID|CSRF|XSRF)$/.test(normalised) || normalised.includes("PASSWORD");
8445
+ }
8446
+
8447
+ // src/shared/ai/explainError.ts
8448
+ var REDACTED = "<redacted>";
8449
+ var TOKEN_PATTERNS = [
8450
+ /sk-[A-Za-z0-9_-]{16,}/g,
8451
+ // OpenAI-style
8452
+ /sk-ant-[A-Za-z0-9_-]{16,}/g,
8453
+ // Anthropic
8454
+ /ghp_[A-Za-z0-9]{20,}/g,
8455
+ // GitHub PAT
8456
+ /gho_[A-Za-z0-9]{20,}/g,
8457
+ /xox[baprs]-[A-Za-z0-9-]{10,}/g,
8458
+ // Slack
8459
+ /AKIA[0-9A-Z]{16}/g,
8460
+ // AWS access key id
8461
+ /AIza[0-9A-Za-z_-]{30,}/g,
8462
+ // Google API key
8463
+ /eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
8464
+ // JWT
8465
+ /(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g,
8466
+ // Stripe
8467
+ /github_pat_[A-Za-z0-9_]{20,}/g,
8468
+ /gh[sur]_[A-Za-z0-9]{20,}/g,
8469
+ /Bearer\s+[A-Za-z0-9._~+/-]{16,}=*/g,
8470
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
8471
+ ];
8472
+ var SECRET_ASSIGN = /^(\s*(?:const |let |var |export\s+(?:const |let |var )?)?)([A-Za-z_$][\w$.]*)(\s*[:=]\s*)(["'])(.*?)\4/;
8473
+ function redactSecretsFromCode(code) {
8474
+ let redactedCount = 0;
8475
+ const byLine = code.split(/\r?\n/u).map((line) => {
8476
+ const match = SECRET_ASSIGN.exec(line);
8477
+ if (match && looksSecret(match[2]) && match[5].length > 0) {
8478
+ redactedCount += 1;
8479
+ return `${match[1]}${match[2]}${match[3]}${match[4]}${REDACTED}${match[4]}`;
8480
+ }
8481
+ return line;
8482
+ });
8483
+ let out = byLine.join("\n");
8484
+ for (const pattern of TOKEN_PATTERNS) {
8485
+ out = out.replace(pattern, () => {
8486
+ redactedCount += 1;
8487
+ return REDACTED;
8488
+ });
8489
+ }
8490
+ return { code: out, redactedCount };
8491
+ }
8492
+
8493
+ // src/shared/capsuleWorkspace.ts
8494
+ var MAX_CAPSULE_WORKSPACE_FILES = 24;
8495
+ var MAX_CAPSULE_WORKSPACE_FILE_BYTES = 256 * 1024;
8496
+ var MAX_CAPSULE_WORKSPACE_TOTAL_FILE_BYTES = 2 * 1024 * 1024;
8497
+ var MAX_CAPSULE_WORKSPACE_BYTES = 6 * 1024 * 1024;
8498
+ var MAX_CAPSULE_WORKSPACE_PATH_BYTES = 240;
8499
+ var LANGUAGE_RE = /^[a-z][a-z0-9-]{0,31}$/u;
8500
+ function containsControlCharacter(value) {
8501
+ return Array.from(value).some((character) => {
8502
+ const codePoint = character.codePointAt(0) ?? 0;
8503
+ return codePoint <= 31 || codePoint === 127;
8504
+ });
8505
+ }
8506
+ function normalizeCapsuleWorkspacePath(rawPath) {
8507
+ if (typeof rawPath !== "string") return null;
8508
+ const value = rawPath.trim();
8509
+ if (value.length === 0 || value.startsWith("/") || value.startsWith("\\") || /^[a-z]:[\\/]/iu.test(value) || value.includes("\\") || containsControlCharacter(value) || utf8ByteLength(value) > MAX_CAPSULE_WORKSPACE_PATH_BYTES) {
8510
+ return null;
8511
+ }
8512
+ const parts = value.split("/");
8513
+ if (parts.some((part) => part.length === 0 || part === "." || part === "..")) {
8514
+ return null;
8515
+ }
8516
+ return parts.join("/");
8517
+ }
8518
+ function validateCapsuleWorkspaceFileInputs(files) {
8519
+ if (files.length === 0 || files.length > MAX_CAPSULE_WORKSPACE_FILES) {
8520
+ return {
8521
+ ok: false,
8522
+ reason: "too-many-files",
8523
+ detail: `files=${files.length}`
8524
+ };
8525
+ }
8526
+ const seen = /* @__PURE__ */ new Set();
8527
+ let totalBytes = 0;
8528
+ const normalized = [];
8529
+ for (const file of files) {
8530
+ const path10 = normalizeCapsuleWorkspacePath(file.path);
8531
+ if (!path10) {
8532
+ return { ok: false, reason: "invalid-path", detail: String(file.path) };
8533
+ }
8534
+ if (!LANGUAGE_RE.test(file.language) || typeof file.content !== "string") {
8535
+ return { ok: false, reason: "invalid-shape", detail: path10 };
8536
+ }
8537
+ const portableKey = path10.toLocaleLowerCase("en-US");
8538
+ if (seen.has(portableKey)) {
8539
+ return { ok: false, reason: "duplicate-path", detail: path10 };
8540
+ }
8541
+ seen.add(portableKey);
8542
+ const bytes = utf8ByteLength(file.content);
8543
+ if (bytes > MAX_CAPSULE_WORKSPACE_FILE_BYTES) {
8544
+ return { ok: false, reason: "file-too-large", detail: path10 };
8545
+ }
8546
+ totalBytes += bytes;
8547
+ if (totalBytes > MAX_CAPSULE_WORKSPACE_TOTAL_FILE_BYTES) {
8548
+ return {
8549
+ ok: false,
8550
+ reason: "files-too-large",
8551
+ detail: `bytes=${totalBytes}`
8552
+ };
8553
+ }
8554
+ normalized.push({ path: path10, language: file.language, content: file.content });
8555
+ }
8556
+ return { ok: true, files: normalized };
8557
+ }
8558
+
8559
+ // src/shared/reproPolicy.ts
8560
+ var MIB = 1024 * 1024;
8561
+ var REPRO_LIMIT_BOUNDS = {
8562
+ wallClockMs: { min: 100, max: 5 * 6e4 },
8563
+ // The most a supervisor captures before clipping; more could never compare cleanly.
8564
+ outputBytes: { min: 1, max: CLI_OUTPUT_PAYLOAD_BYTES },
8565
+ processes: { min: 1, max: 16 },
8566
+ memoryBytes: { min: 32 * MIB, max: 8 * 1024 * MIB },
8567
+ diskBytes: { min: 1 * MIB, max: 1024 * MIB }
8568
+ };
8569
+ var DEFAULT_REPRO_REQUEST = {
8570
+ filesystem: { inputs: "read-only", scratch: "read-write", output: "read-write" },
8571
+ network: "deny",
8572
+ limits: {
8573
+ wallClockMs: 3e4,
8574
+ outputBytes: CLI_OUTPUT_PAYLOAD_BYTES,
8575
+ processes: 1,
8576
+ memoryBytes: null,
8577
+ diskBytes: null
8578
+ },
8579
+ evidence: { denials: "if-available" }
8580
+ };
8581
+ var REPRO_CONTROLS = [
8582
+ "filesystem-isolation",
8583
+ "network-deny",
8584
+ "process-containment",
8585
+ "wall-clock-limit",
8586
+ "output-limit",
8587
+ "process-limit",
8588
+ "memory-limit",
8589
+ "disk-limit",
8590
+ "denial-evidence"
8591
+ ];
8592
+ function isRecord3(value) {
8593
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8594
+ }
8595
+ function findUnknownKey(value, allowed) {
8596
+ return Object.keys(value).find((key) => !allowed.includes(key)) ?? null;
8597
+ }
8598
+ function findMissingKey(value, required) {
8599
+ return required.find((key) => !Object.hasOwn(value, key)) ?? null;
8600
+ }
8601
+ function isLimitInRange(name, value) {
8602
+ const bounds = REPRO_LIMIT_BOUNDS[name];
8603
+ return typeof value === "number" && Number.isInteger(value) && value >= bounds.min && value <= bounds.max;
8604
+ }
8605
+ function isWritableArea(value) {
8606
+ return value === "none" || value === "read-write";
8607
+ }
8608
+ function parseReproPolicy(raw) {
8609
+ if (!isRecord3(raw)) return { ok: false, reason: "invalid-shape", detail: "policy" };
8610
+ const topKeys = ["filesystem", "network", "limits", "evidence"];
8611
+ const unknown = findUnknownKey(raw, topKeys);
8612
+ if (unknown) return { ok: false, reason: "unknown-key", detail: unknown };
8613
+ const missing = findMissingKey(raw, topKeys);
8614
+ if (missing) return { ok: false, reason: "invalid-shape", detail: missing };
8615
+ const { filesystem, limits, evidence } = raw;
8616
+ if (!isRecord3(filesystem)) return { ok: false, reason: "invalid-shape", detail: "filesystem" };
8617
+ const fsKeys = ["inputs", "scratch", "output"];
8618
+ const unknownFs = findUnknownKey(filesystem, fsKeys);
8619
+ if (unknownFs) return { ok: false, reason: "unknown-key", detail: `filesystem.${unknownFs}` };
8620
+ const missingFs = findMissingKey(filesystem, fsKeys);
8621
+ if (missingFs) return { ok: false, reason: "invalid-shape", detail: `filesystem.${missingFs}` };
8622
+ if (filesystem.inputs !== "read-only") {
8623
+ return { ok: false, reason: "unsupported-value", detail: "filesystem.inputs" };
8624
+ }
8625
+ for (const area of ["scratch", "output"]) {
8626
+ if (!isWritableArea(filesystem[area])) {
8627
+ return { ok: false, reason: "unsupported-value", detail: `filesystem.${area}` };
8628
+ }
8629
+ }
8630
+ if (raw.network !== "deny") {
8631
+ return { ok: false, reason: "unsupported-value", detail: "network" };
8632
+ }
8633
+ if (!isRecord3(limits)) return { ok: false, reason: "invalid-shape", detail: "limits" };
8634
+ const limitNames = Object.keys(REPRO_LIMIT_BOUNDS);
8635
+ const unknownLimit = findUnknownKey(limits, limitNames);
8636
+ if (unknownLimit) return { ok: false, reason: "unknown-key", detail: `limits.${unknownLimit}` };
8637
+ const missingLimit = findMissingKey(limits, limitNames);
8638
+ if (missingLimit) {
8639
+ return { ok: false, reason: "invalid-shape", detail: `limits.${missingLimit}` };
8640
+ }
8641
+ for (const name of limitNames) {
8642
+ const value = limits[name];
8643
+ const optional = name === "memoryBytes" || name === "diskBytes";
8644
+ if (optional && value === null) continue;
8645
+ if (!isLimitInRange(name, value)) {
8646
+ return { ok: false, reason: "limit-out-of-range", detail: `limits.${name}` };
8647
+ }
8648
+ }
8649
+ if (!isRecord3(evidence)) return { ok: false, reason: "invalid-shape", detail: "evidence" };
8650
+ const unknownEvidence = findUnknownKey(evidence, ["denials"]);
8651
+ if (unknownEvidence) {
8652
+ return { ok: false, reason: "unknown-key", detail: `evidence.${unknownEvidence}` };
8653
+ }
8654
+ if (!Object.hasOwn(evidence, "denials")) {
8655
+ return { ok: false, reason: "invalid-shape", detail: "evidence.denials" };
8656
+ }
8657
+ if (evidence.denials !== "required" && evidence.denials !== "if-available") {
8658
+ return { ok: false, reason: "unsupported-value", detail: "evidence.denials" };
8659
+ }
8660
+ return {
8661
+ ok: true,
8662
+ value: {
8663
+ filesystem: {
8664
+ inputs: "read-only",
8665
+ scratch: filesystem.scratch,
8666
+ output: filesystem.output
8667
+ },
8668
+ network: "deny",
8669
+ limits: {
8670
+ wallClockMs: limits.wallClockMs,
8671
+ outputBytes: limits.outputBytes,
8672
+ processes: limits.processes,
8673
+ memoryBytes: limits.memoryBytes,
8674
+ diskBytes: limits.diskBytes
8675
+ },
8676
+ evidence: { denials: evidence.denials }
8677
+ }
8678
+ };
8679
+ }
8680
+ function stricterArea(a, b) {
8681
+ return a === "read-write" && b === "read-write" ? "read-write" : "none";
8682
+ }
8683
+ function stricterOptionalLimit(a, b) {
8684
+ if (a === null) return b;
8685
+ if (b === null) return a;
8686
+ return Math.min(a, b);
8687
+ }
8688
+ function narrowReproPolicy(requested, localCeiling) {
8689
+ return {
8690
+ filesystem: {
8691
+ inputs: "read-only",
8692
+ scratch: stricterArea(requested.filesystem.scratch, localCeiling.filesystem.scratch),
8693
+ output: stricterArea(requested.filesystem.output, localCeiling.filesystem.output)
8694
+ },
8695
+ network: "deny",
8696
+ limits: {
8697
+ wallClockMs: Math.min(requested.limits.wallClockMs, localCeiling.limits.wallClockMs),
8698
+ outputBytes: Math.min(requested.limits.outputBytes, localCeiling.limits.outputBytes),
8699
+ processes: Math.min(requested.limits.processes, localCeiling.limits.processes),
8700
+ memoryBytes: stricterOptionalLimit(
8701
+ requested.limits.memoryBytes,
8702
+ localCeiling.limits.memoryBytes
8703
+ ),
8704
+ diskBytes: stricterOptionalLimit(requested.limits.diskBytes, localCeiling.limits.diskBytes)
8705
+ },
8706
+ evidence: {
8707
+ denials: requested.evidence.denials === "required" || localCeiling.evidence.denials === "required" ? "required" : "if-available"
8708
+ }
8709
+ };
8710
+ }
8711
+ function requiredReproControls(policy) {
8712
+ return REPRO_CONTROLS.filter((control) => {
8713
+ switch (control) {
8714
+ case "memory-limit":
8715
+ return policy.limits.memoryBytes !== null;
8716
+ case "disk-limit":
8717
+ return policy.limits.diskBytes !== null;
8718
+ case "denial-evidence":
8719
+ return policy.evidence.denials === "required";
8720
+ default:
8721
+ return true;
8722
+ }
8723
+ });
8724
+ }
8725
+ function canonicalReproPolicy(policy) {
8726
+ return {
8727
+ filesystem: {
8728
+ inputs: policy.filesystem.inputs,
8729
+ scratch: policy.filesystem.scratch,
8730
+ output: policy.filesystem.output
8731
+ },
8732
+ network: policy.network,
8733
+ limits: {
8734
+ wallClockMs: policy.limits.wallClockMs,
8735
+ outputBytes: policy.limits.outputBytes,
8736
+ processes: policy.limits.processes,
8737
+ memoryBytes: policy.limits.memoryBytes,
8738
+ diskBytes: policy.limits.diskBytes
8739
+ },
8740
+ evidence: { denials: policy.evidence.denials }
8741
+ };
8742
+ }
8743
+ function canonicalReproPolicyJson(policy) {
8744
+ return JSON.stringify(canonicalReproPolicy(policy));
8745
+ }
8746
+ function computeReproPolicyDigest(policy) {
8747
+ return computeContentHash(canonicalReproPolicyJson(policy));
8748
+ }
8749
+ function resolveReproEffectivePolicy(approved, probe2) {
8750
+ const required = new Set(requiredReproControls(approved));
8751
+ const controls = REPRO_CONTROLS.map((control) => ({
8752
+ control,
8753
+ support: probe2.controls[control] ?? "unsupported",
8754
+ required: required.has(control)
8755
+ }));
8756
+ const missing = controls.filter((status) => status.required && status.support !== "enforced").map((status) => status.control);
8757
+ if (missing.length > 0) return { ok: false, reason: "unenforceable", missing, controls };
8758
+ return {
8759
+ ok: true,
8760
+ value: {
8761
+ approved,
8762
+ backend: { id: probe2.backend.id, version: probe2.backend.version },
8763
+ controls,
8764
+ ambientGrants: [...probe2.ambientGrants]
8765
+ }
8766
+ };
8767
+ }
8768
+ function computeReproEffectivePolicyDigest(effective) {
8769
+ return computeContentHash(
8770
+ JSON.stringify({
8771
+ approved: canonicalReproPolicy(effective.approved),
8772
+ backend: { id: effective.backend.id, version: effective.backend.version },
8773
+ controls: effective.controls.map(({ control, support, required }) => ({
8774
+ control,
8775
+ support,
8776
+ required
8777
+ })),
8778
+ ambientGrants: [...effective.ambientGrants].sort()
8779
+ })
8780
+ );
8781
+ }
8782
+
8783
+ // src/shared/reproEnvelope.ts
8784
+ var REPRO_ENVELOPE_KIND = "lingua-repro-envelope";
8785
+ var REPRO_ENVELOPE_VERSION = 1;
8786
+ var MAX_REPRO_ENVELOPE_BYTES = MAX_CAPSULE_WORKSPACE_BYTES;
8787
+ var REPRO_NODE_MAJOR_RANGE = { min: 18, max: 99 };
8788
+ var HASH_RE = /^[a-f0-9]{64}$/u;
8789
+ var ENTRY_EXTENSION_RE = /\.(?:mjs|cjs)$/u;
8790
+ var ENVELOPE_KEYS = [
8791
+ "kind",
8792
+ "version",
8793
+ "createdAt",
8794
+ "entry",
8795
+ "runtime",
8796
+ "capsule",
8797
+ "files",
8798
+ "request",
8799
+ "privacy"
8800
+ ];
8801
+ function validateRuntime(raw) {
8802
+ if (!isRecord3(raw) || findUnknownKey(raw, ["name", "major"])) return null;
8803
+ const { name, major } = raw;
8804
+ if (name !== "node" || typeof major !== "number" || !Number.isInteger(major) || major < REPRO_NODE_MAJOR_RANGE.min || major > REPRO_NODE_MAJOR_RANGE.max) {
8805
+ return null;
8806
+ }
8807
+ return { name, major };
8808
+ }
8809
+ function isNfc(path10) {
8810
+ return path10.normalize("NFC") === path10;
8811
+ }
8812
+ function collisionKey(path10) {
8813
+ return path10.toLocaleUpperCase("en-US").toLocaleLowerCase("en-US");
8814
+ }
8815
+ function validateEntry(raw, files) {
8816
+ if (typeof raw !== "string") return null;
8817
+ const entry = normalizeCapsuleWorkspacePath(raw);
8818
+ if (!entry || entry !== raw || !isNfc(entry) || !ENTRY_EXTENSION_RE.test(entry)) return null;
8819
+ const key = collisionKey(entry);
8820
+ return files.some((file) => collisionKey(file.path) === key) ? null : entry;
8821
+ }
8822
+ function validateCapsule(raw) {
8823
+ let json;
8824
+ try {
8825
+ json = JSON.stringify(raw);
8826
+ } catch {
8827
+ return { ok: false, reason: "invalid-capsule", detail: "not serializable" };
8828
+ }
8829
+ if (typeof json !== "string" || utf8ByteLength(json) > MAX_CAPSULE_BYTES) {
8830
+ return { ok: false, reason: "invalid-capsule", detail: "oversized" };
8831
+ }
8832
+ const parsed = parseRunCapsule(json);
8833
+ if (!parsed.ok) return { ok: false, reason: "invalid-capsule", detail: parsed.reason };
8834
+ if (parsed.value.tab.language !== "javascript") {
8835
+ return { ok: false, reason: "unsupported-language", detail: parsed.value.tab.language };
8836
+ }
8837
+ return { ok: true, value: sanitizeRunCapsule(parsed.value) };
8838
+ }
8839
+ function countObviousSecrets(capsule, files) {
8840
+ return [capsule.source.content, ...files.map((file) => file.content)].reduce(
8841
+ (count, content) => count + redactSecretsFromCode(content).redactedCount,
8842
+ 0
8843
+ );
8844
+ }
8845
+ function validateFiles(files) {
8846
+ const notNfc = files.find((file) => typeof file.path === "string" && !isNfc(file.path));
8847
+ if (notNfc) return { ok: false, reason: "invalid-path", detail: notNfc.path };
8848
+ if (files.length === 0) return { ok: true, files: [] };
8849
+ const validated = validateCapsuleWorkspaceFileInputs(files);
8850
+ if (!validated.ok) return validated;
8851
+ const seen = /* @__PURE__ */ new Set();
8852
+ for (const file of validated.files) {
8853
+ const key = collisionKey(file.path);
8854
+ if (seen.has(key)) return { ok: false, reason: "duplicate-path", detail: file.path };
8855
+ seen.add(key);
8856
+ }
8857
+ return validated;
8858
+ }
8859
+ async function buildReproEnvelope(input) {
8860
+ const createdAtMs = input.createdAtMs ?? Date.now();
8861
+ if (!Number.isFinite(createdAtMs)) {
8862
+ return { ok: false, reason: "invalid-shape", detail: "createdAt" };
8863
+ }
8864
+ if (!Array.isArray(input.files)) return { ok: false, reason: "invalid-shape", detail: "files" };
8865
+ const files = validateFiles(input.files);
8866
+ if (!files.ok) return files;
8867
+ const capsule = validateCapsule(input.capsule);
8868
+ if (!capsule.ok) return capsule;
8869
+ const entry = validateEntry(input.entry, files.files);
8870
+ if (!entry) return { ok: false, reason: "invalid-entry", detail: String(input.entry) };
8871
+ const runtime = validateRuntime(input.runtime);
8872
+ if (!runtime) return { ok: false, reason: "unsupported-runtime" };
8873
+ const request = parseReproPolicy(input.request);
8874
+ if (!request.ok) {
8875
+ return { ok: false, reason: "invalid-policy", detail: `${request.reason}:${request.detail}` };
8876
+ }
8877
+ const hashedFiles = [];
8878
+ for (const file of files.files) {
8879
+ hashedFiles.push({ ...file, contentHash: await computeContentHash(file.content) });
8880
+ }
8881
+ const value = {
8882
+ kind: REPRO_ENVELOPE_KIND,
8883
+ version: REPRO_ENVELOPE_VERSION,
8884
+ createdAt: new Date(createdAtMs).toISOString(),
8885
+ entry,
8886
+ runtime,
8887
+ capsule: capsule.value,
8888
+ files: hashedFiles,
8889
+ request: request.value,
8890
+ privacy: {
8891
+ sourceReview: "explicit",
8892
+ absolutePathsIncluded: false,
8893
+ obviousSecretsDetected: countObviousSecrets(capsule.value, files.files)
8894
+ }
8895
+ };
8896
+ const json = JSON.stringify(value, null, 2);
8897
+ if (utf8ByteLength(json) > MAX_REPRO_ENVELOPE_BYTES) {
8898
+ return { ok: false, reason: "artifact-too-large" };
8899
+ }
8900
+ return { ok: true, value, json };
8901
+ }
8902
+ function parseReproEnvelope(json) {
8903
+ if (typeof json !== "string" || json.length === 0) {
8904
+ return { ok: false, reason: "invalid-json", detail: "empty input" };
8905
+ }
8906
+ if (utf8ByteLength(json) > MAX_REPRO_ENVELOPE_BYTES) {
8907
+ return { ok: false, reason: "artifact-too-large" };
8908
+ }
8909
+ let raw;
8910
+ try {
8911
+ raw = JSON.parse(json);
8912
+ } catch (error) {
8913
+ return {
8914
+ ok: false,
8915
+ reason: "invalid-json",
8916
+ detail: error instanceof Error ? error.message : String(error)
8917
+ };
8918
+ }
8919
+ if (!isRecord3(raw) || raw.kind !== REPRO_ENVELOPE_KIND) {
8920
+ return { ok: false, reason: "invalid-shape", detail: "kind" };
8921
+ }
8922
+ if (raw.version !== REPRO_ENVELOPE_VERSION) {
8923
+ return { ok: false, reason: "unsupported-version", detail: `version=${String(raw.version)}` };
8924
+ }
8925
+ const unknown = findUnknownKey(raw, ENVELOPE_KEYS);
8926
+ if (unknown) return { ok: false, reason: "unknown-key", detail: unknown };
8927
+ if (typeof raw.createdAt !== "string" || !Number.isFinite(Date.parse(raw.createdAt))) {
8928
+ return { ok: false, reason: "invalid-shape", detail: "createdAt" };
8929
+ }
8930
+ if (!isRecord3(raw.privacy) || findUnknownKey(raw.privacy, [
8931
+ "sourceReview",
8932
+ "absolutePathsIncluded",
8933
+ "obviousSecretsDetected"
8934
+ ]) || raw.privacy.sourceReview !== "explicit" || raw.privacy.absolutePathsIncluded !== false || !Number.isInteger(raw.privacy.obviousSecretsDetected) || raw.privacy.obviousSecretsDetected < 0) {
8935
+ return { ok: false, reason: "invalid-shape", detail: "privacy" };
8936
+ }
8937
+ if (!Array.isArray(raw.files)) return { ok: false, reason: "invalid-shape", detail: "files" };
8938
+ const inputs = [];
8939
+ const hashes = [];
8940
+ for (const file of raw.files) {
8941
+ if (!isRecord3(file) || findUnknownKey(file, ["path", "language", "content", "contentHash"]) || typeof file.path !== "string" || typeof file.language !== "string" || typeof file.content !== "string" || typeof file.contentHash !== "string" || !HASH_RE.test(file.contentHash)) {
8942
+ return { ok: false, reason: "invalid-shape", detail: "file fields" };
8943
+ }
8944
+ inputs.push({ path: file.path, language: file.language, content: file.content });
8945
+ hashes.push(file.contentHash);
8946
+ }
8947
+ const files = validateFiles(inputs);
8948
+ if (!files.ok) return files;
8949
+ if (files.files.some((file, index) => file.path !== inputs[index]?.path)) {
8950
+ return { ok: false, reason: "invalid-path" };
8951
+ }
8952
+ const capsule = validateCapsule(raw.capsule);
8953
+ if (!capsule.ok) return capsule;
8954
+ const entry = validateEntry(raw.entry, files.files);
8955
+ if (!entry) return { ok: false, reason: "invalid-entry", detail: String(raw.entry) };
8956
+ const runtime = validateRuntime(raw.runtime);
8957
+ if (!runtime) return { ok: false, reason: "unsupported-runtime" };
8958
+ const request = parseReproPolicy(raw.request);
8959
+ if (!request.ok) {
8960
+ return { ok: false, reason: "invalid-policy", detail: `${request.reason}:${request.detail}` };
8961
+ }
8962
+ return {
8963
+ ok: true,
8964
+ value: {
8965
+ kind: REPRO_ENVELOPE_KIND,
8966
+ version: REPRO_ENVELOPE_VERSION,
8967
+ createdAt: raw.createdAt,
8968
+ entry,
8969
+ runtime,
8970
+ capsule: capsule.value,
8971
+ files: files.files.map((file, index) => ({ ...file, contentHash: hashes[index] })),
8972
+ request: request.value,
8973
+ privacy: {
8974
+ sourceReview: "explicit",
8975
+ absolutePathsIncluded: false,
8976
+ obviousSecretsDetected: countObviousSecrets(capsule.value, files.files)
8977
+ }
8978
+ }
8979
+ };
8980
+ }
8981
+ async function computeReproContentDigest(envelope) {
8982
+ const entry = envelope.entry;
8983
+ const runtime = { name: envelope.runtime.name, major: envelope.runtime.major };
8984
+ const source = { ...envelope.capsule.source };
8985
+ const { input, result } = envelope.capsule;
8986
+ const invocation = { stdin: input.stdin ?? "", args: [...input.args ?? []] };
8987
+ const expected = {
8988
+ status: result.status,
8989
+ stdout: result.stdout ?? "",
8990
+ stderr: result.stderr ?? ""
8991
+ };
8992
+ const files = envelope.files.map(({ path: path10, content, contentHash }) => ({
8993
+ path: path10,
8994
+ content,
8995
+ contentHash
8996
+ }));
8997
+ if (await computeContentHash(source.content) !== source.contentHash) {
8998
+ return { ok: false, reason: "hash-mismatch", path: entry };
8999
+ }
9000
+ const inventory = [{ path: entry, contentHash: source.contentHash }];
9001
+ for (const file of files) {
9002
+ if (await computeContentHash(file.content) !== file.contentHash) {
9003
+ return { ok: false, reason: "hash-mismatch", path: file.path };
9004
+ }
9005
+ inventory.push({ path: file.path, contentHash: file.contentHash });
9006
+ }
9007
+ inventory.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
9008
+ return {
9009
+ ok: true,
9010
+ digest: await computeContentHash(
9011
+ JSON.stringify({ entry, runtime, invocation, expected, inventory })
9012
+ )
9013
+ };
9014
+ }
9015
+ function computeReproApprovalToken(approval) {
9016
+ return computeContentHash(`${approval.contentDigest}:${approval.policyDigest}`);
9017
+ }
9018
+ async function approveReproEnvelope(envelope, localCeiling) {
9019
+ const content = await computeReproContentDigest(envelope);
9020
+ if (!content.ok) return content;
9021
+ const policy = narrowReproPolicy(envelope.request, localCeiling);
9022
+ return {
9023
+ ok: true,
9024
+ policy,
9025
+ approval: {
9026
+ contentDigest: content.digest,
9027
+ policyDigest: await computeReproPolicyDigest(policy)
9028
+ }
9029
+ };
9030
+ }
9031
+
9032
+ // src/shared/reproReceipt.ts
9033
+ var MAX_REPRO_RECEIPT_BYTES = 256 * 1024;
9034
+ var BASE_KEYS = [
9035
+ "kind",
9036
+ "version",
9037
+ "createdAt",
9038
+ "contentDigest",
9039
+ "approvedPolicyDigest",
9040
+ "host",
9041
+ "launch"
9042
+ ];
9043
+ var REFUSED_KEYS = [...BASE_KEYS, "refusalReason", "missingControls"];
9044
+ var LAUNCHED_KEYS = [
9045
+ ...BASE_KEYS,
9046
+ "effectivePolicyDigest",
9047
+ "controls",
9048
+ "execution",
9049
+ "comparison",
9050
+ "evidence"
9051
+ ];
9052
+ function summarizeReproReceipt(receipt, approvedPolicy) {
9053
+ if (receipt.launch === "refused") {
9054
+ return {
9055
+ overall: "refused",
9056
+ output: "not-run",
9057
+ enforcement: "not-run",
9058
+ compliance: "not-run",
9059
+ evidence: "not-run"
9060
+ };
9061
+ }
9062
+ const { controls, comparison, evidence, execution } = receipt;
9063
+ const required = requiredReproControls(approvedPolicy);
9064
+ const enforcement = required.every(
9065
+ (control) => controls.find((status) => status.control === control)?.support === "enforced"
9066
+ ) ? "enforced" : "gaps";
9067
+ const compliance = evidence.denials.length > 0 ? "violated" : evidence.coverage === "complete" ? "clean" : "not-observed";
9068
+ const executionIncomplete = execution.outputTruncated || execution.status === "timeout" || execution.status === "stopped";
9069
+ let overall;
9070
+ if (compliance === "violated") {
9071
+ overall = "fail";
9072
+ } else if (executionIncomplete) {
9073
+ overall = "incomplete";
9074
+ } else if (comparison === "fail") {
9075
+ overall = "fail";
9076
+ } else if (enforcement === "gaps" || comparison === "inconclusive" || evidence.coverage === "collection-failed" || approvedPolicy.evidence.denials === "required" && evidence.coverage !== "complete") {
9077
+ overall = "incomplete";
9078
+ } else {
9079
+ overall = "pass";
9080
+ }
9081
+ return { overall, output: comparison, enforcement, compliance, evidence: evidence.coverage };
9082
+ }
9083
+
9084
+ // src/cli/runtime/containment.ts
9085
+ var import_node_child_process3 = require("node:child_process");
9086
+ var import_promises7 = require("node:fs/promises");
9087
+ var import_node_path7 = __toESM(require("node:path"));
9088
+
9089
+ // src/cli/runtime/seatbelt.ts
9090
+ var import_node_child_process2 = require("node:child_process");
9091
+ var import_promises6 = require("node:fs/promises");
9092
+ var import_node_fs4 = require("node:fs");
9093
+ var import_node_path6 = __toESM(require("node:path"));
9094
+ var SANDBOX_EXEC = "/usr/bin/sandbox-exec";
9095
+ var SYSTEM_READ_SUBPATHS = [
9096
+ "/usr/lib",
9097
+ "/System/Library",
9098
+ "/System/Volumes/Preboot/Cryptexes/OS",
9099
+ "/private/var/db/dyld"
9100
+ ];
9101
+ var DEVICE_READ_LITERALS = ["/dev/null", "/dev/random", "/dev/urandom"];
9102
+ var METADATA_DENIED_SUBPATHS = ["/Users", "/Volumes"];
9103
+ var SEATBELT_AMBIENT_GRANTS = [
9104
+ "exec and read the approved Node.js binary",
9105
+ ...SYSTEM_READ_SUBPATHS.map((subpath) => `read ${subpath}`),
9106
+ ...DEVICE_READ_LITERALS.map((literal2) => `read ${literal2}`),
9107
+ "write /dev/null",
9108
+ "list /",
9109
+ `read file metadata outside ${METADATA_DENIED_SUBPATHS.join(" and ")}`,
9110
+ "read file metadata of each parent directory of the Node.js binary and the staging root",
9111
+ "read sysctl values"
9112
+ ];
9113
+ function quote(value) {
9114
+ return JSON.stringify(value);
9115
+ }
9116
+ function ancestors(target) {
9117
+ const chain = [];
9118
+ for (let current2 = target; ; current2 = import_node_path6.default.dirname(current2)) {
9119
+ chain.push(current2);
9120
+ if (import_node_path6.default.dirname(current2) === current2) return chain;
9121
+ }
9122
+ }
9123
+ function compileSeatbeltProfile(input) {
9124
+ const { node, staging, policy } = input;
9125
+ const writable = ["scratch", "output"].filter((area) => policy.filesystem[area] === "read-write").map((area) => staging[area]);
9126
+ const metadataAllowed = [.../* @__PURE__ */ new Set([...ancestors(node), ...ancestors(staging.root)])];
9127
+ return [
9128
+ "(version 1)",
9129
+ "(deny default)",
9130
+ `(allow process-exec (literal ${quote(node)}))`,
9131
+ "(allow sysctl-read)",
9132
+ "(allow file-read*",
9133
+ ` (literal "/") (literal ${quote(node)})`,
9134
+ ...SYSTEM_READ_SUBPATHS.map((subpath) => ` (subpath ${quote(subpath)})`),
9135
+ ...DEVICE_READ_LITERALS.map((literal2) => ` (literal ${quote(literal2)})`),
9136
+ ...[staging.inputs, ...writable].map((area) => ` (subpath ${quote(area)})`),
9137
+ ")",
9138
+ "(allow file-read-metadata)",
9139
+ `(deny file-read-metadata ${METADATA_DENIED_SUBPATHS.map((subpath) => `(subpath ${quote(subpath)})`).join(" ")})`,
9140
+ `(allow file-read-metadata ${metadataAllowed.map((entry) => `(literal ${quote(entry)})`).join(" ")}`,
9141
+ ...[staging.inputs, ...writable].map((area) => ` (subpath ${quote(area)})`),
9142
+ ")",
9143
+ `(allow file-write* (literal "/dev/null")${writable.map((area) => ` (subpath ${quote(area)})`).join("")})`,
9144
+ "(deny network*)",
9145
+ ""
9146
+ ].join("\n");
9147
+ }
9148
+ function clip(result, maxBytes) {
9149
+ const stdoutClipped = utf8ByteLength(result.stdout) > maxBytes;
9150
+ const stderrClipped = utf8ByteLength(result.stderr) > maxBytes;
9151
+ if (!stdoutClipped && !stderrClipped) return result;
9152
+ return {
9153
+ ...result,
9154
+ stdout: stdoutClipped ? truncateUtf8(result.stdout, maxBytes) : result.stdout,
9155
+ stderr: stderrClipped ? truncateUtf8(result.stderr, maxBytes) : result.stderr,
9156
+ truncated: {
9157
+ stdout: stdoutClipped || (result.truncated?.stdout ?? false),
9158
+ stderr: stderrClipped || (result.truncated?.stderr ?? false)
9159
+ }
9160
+ };
9161
+ }
9162
+ async function sandboxExecWorks() {
9163
+ try {
9164
+ await (0, import_promises6.access)(SANDBOX_EXEC, import_node_fs4.constants.X_OK);
9165
+ } catch {
9166
+ return false;
9167
+ }
9168
+ return new Promise((resolve) => {
9169
+ (0, import_node_child_process2.execFile)(
9170
+ SANDBOX_EXEC,
9171
+ ["-p", "(version 1)(allow default)", "/usr/bin/true"],
9172
+ { timeout: 5e3, env: {} },
9173
+ (error) => resolve(!error)
9174
+ );
9175
+ });
9176
+ }
9177
+ async function probe() {
9178
+ if (process.platform !== "darwin" || !await sandboxExecWorks()) return null;
9179
+ return {
9180
+ backend: { id: seatbeltBackend.id, version: "1" },
9181
+ controls: {
9182
+ "filesystem-isolation": "enforced",
9183
+ "network-deny": "enforced",
9184
+ "process-containment": "enforced",
9185
+ "wall-clock-limit": "enforced",
9186
+ "output-limit": "enforced",
9187
+ // Fork is denied outright, so the workload is always a single process.
9188
+ "process-limit": "enforced",
9189
+ "memory-limit": "unsupported",
9190
+ "disk-limit": "unsupported",
9191
+ "denial-evidence": "unsupported"
9192
+ },
9193
+ ambientGrants: SEATBELT_AMBIENT_GRANTS
9194
+ };
9195
+ }
9196
+ async function launch(request) {
9197
+ const { staging, policy, node } = request;
9198
+ const cwd = policy.filesystem.scratch === "read-write" ? staging.scratch : staging.inputs;
9199
+ const startedAt = /* @__PURE__ */ new Date();
9200
+ const result = await executeCliPlan(
9201
+ {
9202
+ displayTarget: import_node_path6.default.basename(staging.entry),
9203
+ runtime: `node ${node.version}`,
9204
+ cwd,
9205
+ steps: [
9206
+ {
9207
+ command: SANDBOX_EXEC,
9208
+ args: [
9209
+ "-p",
9210
+ compileSeatbeltProfile({ node: node.path, staging, policy }),
9211
+ node.path,
9212
+ staging.entry,
9213
+ ...request.args
9214
+ ],
9215
+ kind: "execute"
9216
+ }
9217
+ ]
9218
+ },
9219
+ {
9220
+ env: { HOME: cwd, TMPDIR: cwd },
9221
+ timeoutMs: policy.limits.wallClockMs,
9222
+ ...request.stdin !== void 0 ? { stdin: request.stdin } : {}
9223
+ }
9224
+ );
9225
+ return {
9226
+ result: clip(result, policy.limits.outputBytes),
9227
+ startedAt,
9228
+ endedAt: /* @__PURE__ */ new Date(),
9229
+ evidence: { coverage: "unavailable", denials: [] }
9230
+ };
9231
+ }
9232
+ var seatbeltBackend = { id: "macos-seatbelt", probe, launch };
9233
+
9234
+ // src/cli/runtime/containment.ts
9235
+ var CONTAINMENT_BACKENDS = [seatbeltBackend];
9236
+ async function probeContainment(backends = CONTAINMENT_BACKENDS) {
9237
+ for (const backend of backends) {
9238
+ try {
9239
+ const probe2 = await backend.probe();
9240
+ if (probe2) return { backend, probe: probe2 };
9241
+ } catch {
9242
+ }
9243
+ }
9244
+ return null;
9245
+ }
9246
+ async function resolveReproNodeRuntime(executable = nodeRuntimeExecutable(), env = process.env) {
9247
+ const absolutePath = (env.PATH ?? "").split(import_node_path7.default.delimiter).filter((entry) => import_node_path7.default.isAbsolute(entry)).join(import_node_path7.default.delimiter);
9248
+ const found = import_node_path7.default.isAbsolute(executable) ? executable : await findExecutableOnPath(executable, process.platform, { ...env, PATH: absolutePath });
9249
+ if (!found) return null;
9250
+ try {
9251
+ const resolved = await (0, import_promises7.realpath)(found);
9252
+ const version2 = await new Promise((resolve, reject) => {
9253
+ (0, import_node_child_process3.execFile)(
9254
+ resolved,
9255
+ ["-p", "process.versions.node"],
9256
+ { timeout: 5e3, env: buildCliRuntimeEnvironment([]) },
9257
+ (error, stdout) => error ? reject(error) : resolve(stdout.trim())
9258
+ );
9259
+ });
9260
+ return /^\d+\.\d+\.\d+$/u.test(version2) ? { path: resolved, version: version2 } : null;
9261
+ } catch {
9262
+ return null;
9263
+ }
9264
+ }
9265
+
9266
+ // src/cli/runtime/reproStaging.ts
9267
+ var import_promises8 = require("node:fs/promises");
9268
+ var import_node_os3 = require("node:os");
9269
+ var import_node_path8 = __toESM(require("node:path"));
9270
+ var ReproStagingError = class extends Error {
9271
+ constructor(reason, message) {
9272
+ super(message);
9273
+ this.reason = reason;
9274
+ this.name = "ReproStagingError";
9275
+ }
9276
+ reason;
9277
+ };
9278
+ var strictUtf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
9279
+ function stagedPath(inputs, relative) {
9280
+ return import_node_path8.default.join(inputs, ...relative.split("/"));
9281
+ }
9282
+ async function stageReproEnvelope(envelope, parent = (0, import_node_os3.tmpdir)()) {
9283
+ const root = await (0, import_promises8.realpath)(await (0, import_promises8.mkdtemp)(import_node_path8.default.join(parent, "lingua-repro-")));
9284
+ const staging = {
9285
+ root,
9286
+ inputs: import_node_path8.default.join(root, "inputs"),
9287
+ scratch: import_node_path8.default.join(root, "scratch"),
9288
+ output: import_node_path8.default.join(root, "output"),
9289
+ entry: stagedPath(import_node_path8.default.join(root, "inputs"), envelope.entry)
9290
+ };
9291
+ const files = [
9292
+ {
9293
+ path: envelope.entry,
9294
+ content: envelope.capsule.source.content,
9295
+ contentHash: envelope.capsule.source.contentHash
9296
+ },
9297
+ ...envelope.files
9298
+ ];
9299
+ try {
9300
+ await writeStagedInputs(staging, files);
9301
+ await verifyStagedInputs(staging, files);
9302
+ return staging;
9303
+ } catch (error) {
9304
+ await disposeReproStaging(staging);
9305
+ throw error instanceof ReproStagingError ? error : new ReproStagingError(
9306
+ "staging-failed",
9307
+ error instanceof Error ? error.message : String(error)
9308
+ );
9309
+ }
9310
+ }
9311
+ async function writeStagedInputs(staging, files) {
9312
+ for (const area of [staging.inputs, staging.scratch, staging.output]) {
9313
+ await (0, import_promises8.mkdir)(area, { mode: 448 });
9314
+ }
9315
+ for (const file of files) {
9316
+ const target = stagedPath(staging.inputs, file.path);
9317
+ await (0, import_promises8.mkdir)(import_node_path8.default.dirname(target), { recursive: true, mode: 448 });
9318
+ await (0, import_promises8.writeFile)(target, file.content, { flag: "wx", mode: 384 });
9319
+ }
9320
+ }
9321
+ async function verifyStagedInputs(staging, files) {
9322
+ for (const file of files) {
9323
+ const target = stagedPath(staging.inputs, file.path);
9324
+ let staged;
9325
+ try {
9326
+ staged = strictUtf8.decode(await (0, import_promises8.readFile)(target));
9327
+ } catch {
9328
+ throw new ReproStagingError("staged-hash-mismatch", `${file.path} could not be read back.`);
9329
+ }
9330
+ if (await computeContentHash(staged) !== file.contentHash) {
9331
+ throw new ReproStagingError("staged-hash-mismatch", `${file.path} changed while staging.`);
9332
+ }
9333
+ await (0, import_promises8.chmod)(target, 292);
9334
+ }
9335
+ }
9336
+ async function disposeReproStaging(staging) {
9337
+ await (0, import_promises8.rm)(staging.root, { recursive: true, force: true });
9338
+ }
9339
+
9340
+ // src/cli/commands/repro.ts
9341
+ var LOCAL_CEILING = DEFAULT_REPRO_REQUEST;
9342
+ function languageForPath(filePath) {
9343
+ const extension = import_node_path9.default.extname(filePath).toLowerCase();
9344
+ if ([".mjs", ".cjs", ".js"].includes(extension)) return "javascript";
9345
+ if (extension === ".json") return "json";
9346
+ return "plaintext";
9347
+ }
9348
+ var strictUtf82 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
9349
+ function shellQuote(value) {
9350
+ return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
9351
+ }
9352
+ async function readPackedFile(io, root, realRoot, file) {
9353
+ if (normalizeCapsuleWorkspacePath(file) !== file) {
9354
+ return {
9355
+ ok: false,
9356
+ reason: "invalid-path",
9357
+ detail: `${file} must be a relative path inside the root, with / separators.`
9358
+ };
9359
+ }
9360
+ const target = import_node_path9.default.join(root, ...file.split("/"));
9361
+ let bytes;
9362
+ try {
9363
+ const realTarget = await io.realPath(target);
9364
+ if (!realTarget.startsWith(`${realRoot}${import_node_path9.default.sep}`)) {
9365
+ return {
9366
+ ok: false,
9367
+ reason: "outside-root",
9368
+ detail: `${file} resolves outside the root through a symbolic link.`
9369
+ };
9370
+ }
9371
+ bytes = await io.readFileBytes(target);
9372
+ } catch (error) {
9373
+ return { ok: false, reason: readFailureReason(error), detail: errorMessage3(error) };
9374
+ }
9375
+ try {
9376
+ return {
9377
+ ok: true,
9378
+ value: { path: file, language: languageForPath(file), content: strictUtf82.decode(bytes) }
9379
+ };
9380
+ } catch {
9381
+ return { ok: false, reason: "not-utf8", detail: `${file} is not UTF-8 text.` };
9382
+ }
9383
+ }
9384
+ async function runReproPackCommand(args, io) {
9385
+ const label2 = "lingua repro pack";
9386
+ const capsule = await loadCapsule(args.capsulePath, io);
9387
+ if (!capsule.ok) {
9388
+ emitCliFailure(io, args, {
9389
+ label: label2,
9390
+ reason: capsule.reason,
9391
+ detail: capsule.detail ?? `Could not read a Run Capsule from ${args.capsulePath}.`
9392
+ });
9393
+ return CLI_EXIT_CODES.userInputError;
9394
+ }
9395
+ const root = import_node_path9.default.resolve(args.root ?? ".");
9396
+ let realRoot;
9397
+ try {
9398
+ realRoot = await io.realPath(root);
9399
+ } catch (error) {
9400
+ emitCliFailure(io, args, {
9401
+ label: label2,
9402
+ reason: readFailureReason(error),
9403
+ detail: errorMessage3(error)
9404
+ });
9405
+ return CLI_EXIT_CODES.userInputError;
9406
+ }
9407
+ const files = [];
9408
+ for (const file of args.files) {
9409
+ const read = await readPackedFile(io, root, realRoot, file);
9410
+ if (!read.ok) {
9411
+ emitCliFailure(io, args, { label: label2, reason: read.reason, detail: read.detail });
9412
+ return CLI_EXIT_CODES.userInputError;
9413
+ }
9414
+ files.push(read.value);
9415
+ }
9416
+ const built = await buildReproEnvelope({
9417
+ capsule: capsule.value,
9418
+ entry: args.entry,
9419
+ runtime: { name: "node", major: args.nodeMajor ?? Number(process.versions.node.split(".")[0]) },
9420
+ files,
9421
+ request: DEFAULT_REPRO_REQUEST
9422
+ });
9423
+ if (!built.ok) {
9424
+ emitCliFailure(io, args, {
9425
+ label: label2,
9426
+ reason: built.reason,
9427
+ detail: built.detail ?? "The reproduction envelope was rejected."
9428
+ });
9429
+ return built.reason === "unsupported-language" || built.reason === "unsupported-runtime" ? CLI_EXIT_CODES.unsupportedCapability : CLI_EXIT_CODES.userInputError;
9430
+ }
9431
+ io.writeStdout(`${built.json}
9432
+ `);
9433
+ const secrets = built.value.privacy.obviousSecretsDetected;
9434
+ if (secrets > 0 && !args.quiet) {
9435
+ io.writeStderr(
9436
+ `${renderCliNotice(io, args.color, `${label2}: ${secrets} possible secret(s) in the packed files; review before sharing.`)}
9437
+ `
9438
+ );
9439
+ }
9440
+ return CLI_EXIT_CODES.ok;
9441
+ }
9442
+ async function prepareReview(args, io) {
9443
+ let raw;
9444
+ try {
9445
+ raw = await io.readFile(args.envelopePath);
9446
+ } catch (error) {
9447
+ return { ok: false, reason: readFailureReason(error), detail: errorMessage3(error) };
9448
+ }
9449
+ const parsed = parseReproEnvelope(raw);
9450
+ if (!parsed.ok) {
9451
+ return { ok: false, reason: parsed.reason, detail: parsed.detail ?? "Invalid envelope." };
9452
+ }
9453
+ const approval = await approveReproEnvelope(parsed.value, LOCAL_CEILING);
9454
+ if (!approval.ok) {
9455
+ return {
9456
+ ok: false,
9457
+ reason: "hash-mismatch",
9458
+ detail: `${approval.path} does not match its recorded hash.`
9459
+ };
9460
+ }
9461
+ const backend = await probeContainment(args.backends);
9462
+ const resolved = backend ? resolveReproEffectivePolicy(approval.policy, backend.probe) : null;
9463
+ return {
9464
+ ok: true,
9465
+ value: {
9466
+ envelope: parsed.value,
9467
+ approved: approval.policy,
9468
+ contentDigest: approval.approval.contentDigest,
9469
+ policyDigest: approval.approval.policyDigest,
9470
+ token: await computeReproApprovalToken(approval.approval),
9471
+ backend,
9472
+ effective: resolved?.ok ? resolved.value : null,
9473
+ controls: resolved ? resolved.ok ? resolved.value.controls : resolved.controls : [],
9474
+ missing: resolved ? resolved.ok ? [] : resolved.missing : requiredReproControls(approval.policy),
9475
+ node: await (args.resolveNode ?? resolveReproNodeRuntime)()
9476
+ }
9477
+ };
9478
+ }
9479
+ function hostLabel() {
9480
+ return `${process.platform} ${process.arch}`;
9481
+ }
9482
+ function nodeMajor(node) {
9483
+ return Number(node.version.split(".")[0]);
9484
+ }
9485
+ function runtimeMatches(review) {
9486
+ return review.node !== null && nodeMajor(review.node) === review.envelope.runtime.major;
9487
+ }
9488
+ function describeWrites(policy) {
9489
+ const areas = ["scratch", "output"].filter(
9490
+ (area) => policy.filesystem[area] === "read-write"
9491
+ );
9492
+ return areas.length > 0 ? areas.join(", ") : "none";
9493
+ }
9494
+ function describeLimits(policy) {
9495
+ const { wallClockMs, outputBytes, processes, memoryBytes, diskBytes } = policy.limits;
9496
+ return [
9497
+ `wall ${wallClockMs} ms`,
9498
+ `output ${outputBytes} B`,
9499
+ `processes ${processes}`,
9500
+ `memory ${memoryBytes === null ? "unbounded" : `${memoryBytes} B`}`,
9501
+ `disk ${diskBytes === null ? "unbounded" : `${diskBytes} B`}`
9502
+ ].join(" \xB7 ");
9503
+ }
9504
+ function describeBackend(review) {
9505
+ if (!review.backend) return `none on ${hostLabel()}; run refuses before launch`;
9506
+ const { id, version: version2 } = review.backend.probe.backend;
9507
+ return review.missing.length > 0 ? `${id} ${version2} cannot enforce ${review.missing.join(", ")}; run refuses before launch` : `${id} ${version2}`;
9508
+ }
9509
+ function describeRuntime(review) {
9510
+ const wanted = `node ${review.envelope.runtime.major}`;
9511
+ if (!review.node) return `${wanted} requested; Node.js not found; run refuses before launch`;
9512
+ return runtimeMatches(review) ? `node ${review.node.version}` : `${wanted} requested; found ${review.node.version}; run refuses before launch`;
9513
+ }
9514
+ function describeAmbient(review) {
9515
+ const grants = review.backend?.probe.ambientGrants ?? [];
9516
+ if (grants.length === 0)
9517
+ return [["ambient", review.backend ? "none" : "unavailable (no backend)"]];
9518
+ return grants.map((grant) => ["ambient", neutralizeControlCharacters(grant)]);
9519
+ }
9520
+ async function runReproReviewCommand(args, io) {
9521
+ const label2 = "lingua repro review";
9522
+ const prepared = await prepareReview(args, io);
9523
+ if (!prepared.ok) {
9524
+ emitCliFailure(io, args, { label: label2, reason: prepared.reason, detail: prepared.detail });
9525
+ return CLI_EXIT_CODES.userInputError;
9526
+ }
9527
+ const review = prepared.value;
9528
+ const { envelope } = review;
9529
+ const ambientGrants = review.backend?.probe.ambientGrants ?? [];
9530
+ if (args.json) {
9531
+ io.writeStdout(
9532
+ `${JSON.stringify({
9533
+ ok: true,
9534
+ entry: envelope.entry,
9535
+ runtime: envelope.runtime,
9536
+ hostRuntime: review.node?.version ?? null,
9537
+ files: envelope.files.map(({ path: filePath, contentHash }) => ({
9538
+ path: filePath,
9539
+ contentHash
9540
+ })),
9541
+ obviousSecretsDetected: envelope.privacy.obviousSecretsDetected,
9542
+ request: envelope.request,
9543
+ approvedPolicy: review.approved,
9544
+ requiredControls: requiredReproControls(review.approved),
9545
+ backend: review.backend?.probe.backend ?? null,
9546
+ missingControls: review.missing,
9547
+ effectivePolicy: review.effective,
9548
+ probedControls: review.controls,
9549
+ ambientGrants,
9550
+ approval: {
9551
+ contentDigest: review.contentDigest,
9552
+ policyDigest: review.policyDigest,
9553
+ token: review.token
9554
+ }
9555
+ })}
9556
+ `
9557
+ );
9558
+ return CLI_EXIT_CODES.ok;
9559
+ }
9560
+ if (args.quiet) return CLI_EXIT_CODES.ok;
9561
+ const rows = [
9562
+ ["entry", envelope.entry],
9563
+ ...envelope.files.map((file) => [
9564
+ "file",
9565
+ `${file.path} ${file.contentHash.slice(0, 12)}`
9566
+ ]),
9567
+ ["secrets", String(envelope.privacy.obviousSecretsDetected)],
9568
+ ["runtime", describeRuntime(review)],
9569
+ ["network", review.approved.network],
9570
+ ["writes", describeWrites(review.approved)],
9571
+ ["limits", describeLimits(review.approved)],
9572
+ ["evidence", `denials ${review.approved.evidence.denials}`],
9573
+ ["backend", describeBackend(review)],
9574
+ ["effective", review.effective ? "available" : "unavailable"],
9575
+ ...review.controls.map(({ control, support, required }) => [
9576
+ "control",
9577
+ `${control}: ${support} (${required ? "required" : "optional"})`
9578
+ ]),
9579
+ ...describeAmbient(review),
9580
+ ["approve", `lingua repro run ${shellQuote(args.envelopePath)} --approve ${review.token}`]
9581
+ ];
9582
+ const width = Math.max(...rows.map(([key]) => key.length)) + 1;
9583
+ io.writeStdout(rows.map(([key, value]) => `${key.padEnd(width)}${value}`).join("\n") + "\n");
9584
+ return CLI_EXIT_CODES.ok;
9585
+ }
9586
+ function receiptHost(review, args, launched) {
9587
+ return {
9588
+ lingua: args.linguaVersion,
9589
+ os: `${process.platform} kernel ${(0, import_node_os4.release)()}`,
9590
+ arch: process.arch,
9591
+ runtime: launched && review.node ? `node ${review.node.version}` : null,
9592
+ backend: review.backend?.probe.backend ?? null
9593
+ };
9594
+ }
9595
+ function refusedReceipt(review, refusalReason, args) {
9596
+ return {
9597
+ kind: "lingua-repro-receipt",
9598
+ version: 1,
9599
+ createdAt: (args.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
9600
+ contentDigest: review.contentDigest,
9601
+ approvedPolicyDigest: review.policyDigest,
9602
+ host: receiptHost(review, args, false),
9603
+ launch: "refused",
9604
+ refusalReason,
9605
+ missingControls: refusalReason === "unenforceable" ? review.missing : []
9606
+ };
9607
+ }
9608
+ var VERDICT_EXIT_CODES = {
9609
+ pass: CLI_EXIT_CODES.ok,
9610
+ fail: CLI_EXIT_CODES.verificationFailed,
9611
+ incomplete: CLI_EXIT_CODES.verificationInconclusive,
9612
+ refused: CLI_EXIT_CODES.unsupportedCapability
9613
+ };
9614
+ async function launchReproduction(review, backend, effective, node, args, io) {
9615
+ const label2 = "lingua repro run";
9616
+ const { capsule } = review.envelope;
9617
+ let staging;
9618
+ try {
9619
+ staging = await stageReproEnvelope(review.envelope, args.stagingParent);
9620
+ } catch (error) {
9621
+ emitCliFailure(io, args, {
9622
+ label: label2,
9623
+ reason: error instanceof ReproStagingError ? error.reason : "staging-failed",
9624
+ detail: errorMessage3(error)
9625
+ });
9626
+ return CLI_EXIT_CODES.runtimeError;
9627
+ }
9628
+ try {
9629
+ const outcome = await backend.backend.launch({
9630
+ staging,
9631
+ policy: review.approved,
9632
+ node,
9633
+ args: capsule.input.args ?? [],
9634
+ ...capsule.input.stdin !== void 0 ? { stdin: capsule.input.stdin } : {}
9635
+ });
9636
+ const { result } = outcome;
9637
+ const receipt = {
9638
+ kind: "lingua-repro-receipt",
9639
+ version: 1,
9640
+ createdAt: (args.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
9641
+ contentDigest: review.contentDigest,
9642
+ approvedPolicyDigest: review.policyDigest,
9643
+ host: receiptHost(review, args, true),
9644
+ launch: "launched",
9645
+ effectivePolicyDigest: await computeReproEffectivePolicyDigest(effective),
9646
+ controls: effective.controls,
9647
+ execution: {
9648
+ status: result.status,
9649
+ exitCode: result.exitCode,
9650
+ signal: result.signal,
9651
+ startedAt: outcome.startedAt.toISOString(),
9652
+ endedAt: outcome.endedAt.toISOString(),
9653
+ outputTruncated: Boolean(result.truncated?.stdout || result.truncated?.stderr)
9654
+ },
9655
+ comparison: capsuleStrictVerificationRefusal(capsule) ? "inconclusive" : strictCapsuleVerdict(capsule, result).verdict,
9656
+ evidence: outcome.evidence
9657
+ };
9658
+ const verdict = summarizeReproReceipt(receipt, review.approved);
9659
+ if (args.json) {
9660
+ io.writeStdout(
9661
+ `${JSON.stringify({
9662
+ ok: verdict.overall === "pass",
9663
+ receipt,
9664
+ verdict,
9665
+ stdout: result.stdout,
9666
+ stderr: result.stderr
9667
+ })}
9668
+ `
9669
+ );
9670
+ } else {
9671
+ io.writeStdout(neutralizeControlCharacters(result.stdout));
9672
+ io.writeStderr(neutralizeControlCharacters(result.stderr));
9673
+ if (!args.quiet) {
9674
+ const summary = `${label2}: ${verdict.overall} (output ${verdict.output}, enforcement ${verdict.enforcement}, compliance ${verdict.compliance}, evidence ${verdict.evidence})`;
9675
+ io.writeStderr(
9676
+ `${renderCliNotice(io, args.color, summary, verdict.overall === "pass" ? "success" : "warning")}
9677
+ `
9678
+ );
9679
+ }
9680
+ }
9681
+ return VERDICT_EXIT_CODES[verdict.overall];
9682
+ } finally {
9683
+ try {
9684
+ await disposeReproStaging(staging);
9685
+ } catch (error) {
9686
+ io.writeStderr(
9687
+ `${renderCliNotice(io, args.color, `${label2}: could not remove the staging directory ${staging.root}: ${errorMessage3(error)}`)}
9688
+ `
9689
+ );
9690
+ }
9691
+ }
9692
+ }
9693
+ async function runReproRunCommand(args, io) {
9694
+ const label2 = "lingua repro run";
9695
+ const prepared = await prepareReview(args, io);
9696
+ if (!prepared.ok) {
9697
+ emitCliFailure(io, args, { label: label2, reason: prepared.reason, detail: prepared.detail });
9698
+ return CLI_EXIT_CODES.userInputError;
9699
+ }
9700
+ const review = prepared.value;
9701
+ const { backend, effective, node } = review;
9702
+ let receipt;
9703
+ let detail;
9704
+ let exitCode = CLI_EXIT_CODES.unsupportedCapability;
9705
+ if (args.approve.trim().toLowerCase() !== review.token) {
9706
+ receipt = refusedReceipt(review, "approval-invalid", args);
9707
+ detail = `The approval does not match this envelope and policy. Review it again with lingua repro review ${shellQuote(args.envelopePath)}.`;
9708
+ exitCode = CLI_EXIT_CODES.userInputError;
9709
+ } else if (!backend) {
9710
+ receipt = refusedReceipt(review, "backend-unavailable", args);
9711
+ detail = `No containment backend is available on ${hostLabel()}; nothing was run.`;
9712
+ } else if (!effective) {
9713
+ receipt = refusedReceipt(review, "unenforceable", args);
9714
+ detail = `${backend.probe.backend.id} cannot enforce ${review.missing.join(", ")}; nothing was run.`;
9715
+ } else if (!node || !runtimeMatches(review)) {
9716
+ receipt = refusedReceipt(review, "runtime-unavailable", args);
9717
+ detail = `${describeRuntime(review).replace("; run refuses before launch", "")}; nothing was run.`;
9718
+ } else {
9719
+ return launchReproduction(review, backend, effective, node, args, io);
9720
+ }
9721
+ emitCliFailure(io, args, {
9722
+ label: label2,
9723
+ reason: receipt.refusalReason,
9724
+ detail,
9725
+ extra: { receipt, verdict: summarizeReproReceipt(receipt, review.approved) }
9726
+ });
9727
+ return exitCode;
9728
+ }
9729
+
8247
9730
  // src/shared/utilities/base64.ts
8248
9731
  function bytesToBase64(bytes) {
8249
9732
  let binary = "";
@@ -8677,8 +10160,7 @@ function decodeHtmlEntities(input) {
8677
10160
  return match;
8678
10161
  }
8679
10162
  }
8680
- const named = NAMED_DECODE[body];
8681
- return named ?? match;
10163
+ return Object.hasOwn(NAMED_DECODE, body) ? NAMED_DECODE[body] : match;
8682
10164
  }
8683
10165
  );
8684
10166
  }
@@ -10948,6 +12430,48 @@ var CLI_HELP_CATALOG = {
10948
12430
  }
10949
12431
  ]
10950
12432
  },
12433
+ {
12434
+ id: "repro-pack",
12435
+ topLevel: "repro",
12436
+ invocation: "lingua repro pack <capsule> --entry <path> [--file <path> ...] [--root <directory>] [--node <major>]",
12437
+ summary: "Wrap a JavaScript Run Capsule and chosen files into a reproduction envelope.",
12438
+ description: "Experimental. Prints the envelope to stdout with a deny-network request; nothing is executed. Files are read relative to --root.",
12439
+ flags: ["entry", "file", "root", "node", "json", "quiet", "color", "help"],
12440
+ examples: [
12441
+ {
12442
+ command: "lingua repro pack ./run.capsule.json --entry main.mjs --file lib/sum.mjs > repro.json",
12443
+ description: "Pack a capsule and one helper module."
12444
+ }
12445
+ ]
12446
+ },
12447
+ {
12448
+ id: "repro-review",
12449
+ topLevel: "repro",
12450
+ invocation: "lingua repro review <envelope> [--json] [--quiet]",
12451
+ summary: "Show what a reproduction asks for and the token that approves it.",
12452
+ description: "Experimental. Verifies every file hash, narrows the request to the local ceiling and reports which required controls this host can enforce. Nothing is executed.",
12453
+ flags: ["json", "quiet", "color", "help"],
12454
+ examples: [
12455
+ {
12456
+ command: "lingua repro review ./repro.json",
12457
+ description: "Review an envelope before approving it."
12458
+ }
12459
+ ]
12460
+ },
12461
+ {
12462
+ id: "repro-run",
12463
+ topLevel: "repro",
12464
+ invocation: "lingua repro run <envelope> --approve <token> [--json] [--quiet]",
12465
+ summary: "Run an approved reproduction inside a containment backend, or refuse.",
12466
+ description: "Experimental. Runs the reviewed bytes under macOS Seatbelt and compares the output with the capsule; refuses before launch on a stale approval, a missing backend or runtime, or an unenforced control. --json prints the receipt.",
12467
+ flags: ["approve", "json", "quiet", "color", "help"],
12468
+ examples: [
12469
+ {
12470
+ command: "lingua repro run ./repro.json --approve <token> --json",
12471
+ description: "Get the receipt for an approved reproduction."
12472
+ }
12473
+ ]
12474
+ },
10951
12475
  {
10952
12476
  id: "run",
10953
12477
  topLevel: "run",
@@ -11009,8 +12533,32 @@ var CLI_HELP_CATALOG = {
11009
12533
  {
11010
12534
  id: "root",
11011
12535
  syntax: "--root <directory>",
11012
- summary: "Resolve suite targets inside this directory; defaults to cwd.",
11013
- commands: ["capsule-verify-suite"]
12536
+ summary: "Resolve suite targets or packed files inside this directory; defaults to cwd.",
12537
+ commands: ["capsule-verify-suite", "repro-pack"]
12538
+ },
12539
+ {
12540
+ id: "entry",
12541
+ syntax: "--entry <path>",
12542
+ summary: "Relative .mjs or .cjs path the capsule source is staged at.",
12543
+ commands: ["repro-pack"]
12544
+ },
12545
+ {
12546
+ id: "file",
12547
+ syntax: "--file <path>",
12548
+ summary: "Repeat to add a supplemental file, relative to --root.",
12549
+ commands: ["repro-pack"]
12550
+ },
12551
+ {
12552
+ id: "node",
12553
+ syntax: "--node <major>",
12554
+ summary: "Node.js major the reproduction requests; defaults to the current one.",
12555
+ commands: ["repro-pack"]
12556
+ },
12557
+ {
12558
+ id: "approve",
12559
+ syntax: "--approve <token>",
12560
+ summary: "Approval token printed by lingua repro review.",
12561
+ commands: ["repro-run"]
11014
12562
  },
11015
12563
  {
11016
12564
  id: "input",
@@ -11052,6 +12600,9 @@ var CLI_HELP_CATALOG = {
11052
12600
  "capsule-replay",
11053
12601
  "capsule-verify",
11054
12602
  "capsule-verify-suite",
12603
+ "repro-pack",
12604
+ "repro-review",
12605
+ "repro-run",
11055
12606
  "run",
11056
12607
  "list-utilities"
11057
12608
  ]
@@ -11066,6 +12617,9 @@ var CLI_HELP_CATALOG = {
11066
12617
  "capsule-replay",
11067
12618
  "capsule-verify",
11068
12619
  "capsule-verify-suite",
12620
+ "repro-pack",
12621
+ "repro-review",
12622
+ "repro-run",
11069
12623
  "run",
11070
12624
  "list-utilities"
11071
12625
  ]
@@ -11092,6 +12646,9 @@ var CLI_HELP_CATALOG = {
11092
12646
  "capsule-replay",
11093
12647
  "capsule-verify",
11094
12648
  "capsule-verify-suite",
12649
+ "repro-pack",
12650
+ "repro-review",
12651
+ "repro-run",
11095
12652
  "run",
11096
12653
  "list-utilities",
11097
12654
  "completion"
@@ -11113,6 +12670,9 @@ var CLI_HELP_CATALOG = {
11113
12670
  "capsule-replay",
11114
12671
  "capsule-verify",
11115
12672
  "capsule-verify-suite",
12673
+ "repro-pack",
12674
+ "repro-review",
12675
+ "repro-run",
11116
12676
  "run",
11117
12677
  "list-utilities",
11118
12678
  "completion"
@@ -11173,8 +12733,8 @@ ${examples}
11173
12733
  }
11174
12734
 
11175
12735
  // src/cli/io.ts
11176
- var import_promises6 = require("node:fs/promises");
11177
- var import_promises7 = require("node:readline/promises");
12736
+ var import_promises9 = require("node:fs/promises");
12737
+ var import_promises10 = require("node:readline/promises");
11178
12738
  function createDefaultIo() {
11179
12739
  return {
11180
12740
  stdoutSupportsColor: process.stdout.isTTY === true && (typeof process.stdout.hasColors !== "function" || process.stdout.hasColors()),
@@ -11187,7 +12747,7 @@ function createDefaultIo() {
11187
12747
  return null;
11188
12748
  }
11189
12749
  const choices = defaultAnswer ? "Y/n" : "y/N";
11190
- const readline = (0, import_promises7.createInterface)({ input: process.stdin, output: process.stdout });
12750
+ const readline = (0, import_promises10.createInterface)({ input: process.stdin, output: process.stdout });
11191
12751
  try {
11192
12752
  const answer = (await readline.question(`${message} [${choices}] `)).trim().toLowerCase();
11193
12753
  if (answer.length === 0) return defaultAnswer;
@@ -11202,8 +12762,14 @@ function createDefaultIo() {
11202
12762
  writeStderr(text) {
11203
12763
  process.stderr.write(text);
11204
12764
  },
11205
- async readFile(path6) {
11206
- return (0, import_promises6.readFile)(path6, "utf8");
12765
+ async readFile(path10) {
12766
+ return (0, import_promises9.readFile)(path10, "utf8");
12767
+ },
12768
+ async readFileBytes(path10) {
12769
+ return (0, import_promises9.readFile)(path10);
12770
+ },
12771
+ async realPath(path10) {
12772
+ return (0, import_promises9.realpath)(path10);
11207
12773
  },
11208
12774
  async readStdin(options) {
11209
12775
  if (process.stdin.isTTY) {
@@ -11211,14 +12777,14 @@ function createDefaultIo() {
11211
12777
  }
11212
12778
  const chunks = [];
11213
12779
  const signal = options?.signal;
11214
- const release = () => process.stdin.destroy();
11215
- signal?.addEventListener("abort", release, { once: true });
12780
+ const release2 = () => process.stdin.destroy();
12781
+ signal?.addEventListener("abort", release2, { once: true });
11216
12782
  try {
11217
12783
  for await (const chunk of process.stdin) {
11218
12784
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
11219
12785
  }
11220
12786
  } finally {
11221
- signal?.removeEventListener("abort", release);
12787
+ signal?.removeEventListener("abort", release2);
11222
12788
  }
11223
12789
  return Buffer.concat(chunks).toString("utf8");
11224
12790
  }
@@ -11263,6 +12829,9 @@ function parseArgs(argv) {
11263
12829
  if (first === "capsule") {
11264
12830
  return parseCapsule(args.slice(1), extracted.color);
11265
12831
  }
12832
+ if (first === "repro") {
12833
+ return parseRepro(args.slice(1), extracted.color);
12834
+ }
11266
12835
  if (first === "list") {
11267
12836
  return parseList(args.slice(1), extracted.color);
11268
12837
  }
@@ -11278,6 +12847,7 @@ function freshFlags(color = "auto") {
11278
12847
  color,
11279
12848
  options: [],
11280
12849
  env: [],
12850
+ files: [],
11281
12851
  programArgs: [],
11282
12852
  help: false,
11283
12853
  yes: false,
@@ -11297,6 +12867,10 @@ function finalize(command, positionals, flags) {
11297
12867
  ...flags.timeoutMs !== void 0 ? { timeoutMs: flags.timeoutMs } : {},
11298
12868
  ...flags.target !== void 0 ? { target: flags.target } : {},
11299
12869
  ...flags.root !== void 0 ? { root: flags.root } : {},
12870
+ ...flags.entry !== void 0 ? { entry: flags.entry } : {},
12871
+ files: flags.files,
12872
+ ...flags.nodeMajor !== void 0 ? { nodeMajor: flags.nodeMajor } : {},
12873
+ ...flags.approve !== void 0 ? { approve: flags.approve } : {},
11300
12874
  options: flags.options,
11301
12875
  env: flags.env,
11302
12876
  programArgs: flags.programArgs,
@@ -11517,6 +13091,73 @@ function parseCapsuleReplay(rest, color, command = "capsule-replay") {
11517
13091
  assertSingleTarget(`lingua capsule ${command.slice(8)}`, positionals, flags.help, "<file>");
11518
13092
  return finalize(command, positionals, flags);
11519
13093
  }
13094
+ var REPRO_SUBCOMMANDS = "pack <capsule>, review <envelope>, run <envelope>";
13095
+ var REPRO_VALUE_FLAGS = {
13096
+ "repro-pack": ["--entry", "--file", "--root", "--node"],
13097
+ "repro-review": [],
13098
+ "repro-run": ["--approve"]
13099
+ };
13100
+ function parseRepro(rest, color) {
13101
+ if (rest.length === 0) {
13102
+ throw new CliUsageError(`lingua repro requires a subcommand. Available: ${REPRO_SUBCOMMANDS}`);
13103
+ }
13104
+ const sub = rest[0];
13105
+ if (sub === "--help" || sub === "-h") {
13106
+ return finalize("repro-review", [], { ...freshFlags(color), help: true });
13107
+ }
13108
+ const command = sub === "pack" ? "repro-pack" : sub === "review" ? "repro-review" : sub === "run" ? "repro-run" : null;
13109
+ if (!command) {
13110
+ throw new CliUsageError(`Unknown repro subcommand "${sub}". Available: ${REPRO_SUBCOMMANDS}`);
13111
+ }
13112
+ const allowed = REPRO_VALUE_FLAGS[command];
13113
+ const flags = freshFlags(color);
13114
+ const positionals = [];
13115
+ for (let index = 1; index < rest.length; index += 1) {
13116
+ const arg = rest[index];
13117
+ if (parseGlobalFlag(arg, flags)) continue;
13118
+ const name = arg.split("=")[0];
13119
+ if (allowed.includes(name)) {
13120
+ const value = arg.includes("=") ? nonEmptyInlineValue(arg, name) : requireFlagValue(rest, index++, name);
13121
+ if (name === "--file") {
13122
+ flags.files.push(value);
13123
+ } else if (name === "--node") {
13124
+ if (flags.nodeMajor !== void 0) throw new CliUsageError("--node may be supplied once.");
13125
+ flags.nodeMajor = parseNodeMajor(value);
13126
+ } else {
13127
+ const key = name.slice(2);
13128
+ if (flags[key] !== void 0) throw new CliUsageError(`${name} may be supplied once.`);
13129
+ flags[key] = value;
13130
+ }
13131
+ continue;
13132
+ }
13133
+ if (arg.startsWith("-")) {
13134
+ throw new CliUsageError(
13135
+ `Unknown flag "${arg}" for "lingua repro ${sub}". Allowed: ${[...allowed, "--json", "--quiet", "--color", "--help"].join(", ")}`
13136
+ );
13137
+ }
13138
+ positionals.push(arg);
13139
+ }
13140
+ assertSingleTarget(
13141
+ `lingua repro ${sub}`,
13142
+ positionals,
13143
+ flags.help,
13144
+ command === "repro-pack" ? "<capsule>" : "<envelope>"
13145
+ );
13146
+ if (!flags.help && command === "repro-pack" && flags.entry === void 0) {
13147
+ throw new CliUsageError("lingua repro pack requires --entry <path>.");
13148
+ }
13149
+ if (!flags.help && command === "repro-run" && flags.approve === void 0) {
13150
+ throw new CliUsageError(
13151
+ "lingua repro run requires --approve <token> from lingua repro review."
13152
+ );
13153
+ }
13154
+ return finalize(command, positionals, flags);
13155
+ }
13156
+ function parseNodeMajor(raw) {
13157
+ if (!/^\d+$/u.test(raw))
13158
+ throw new CliUsageError("--node must be a Node.js major version, such as 24");
13159
+ return Number(raw);
13160
+ }
11520
13161
  function parseList(rest, color) {
11521
13162
  if (rest.length === 0) {
11522
13163
  throw new CliUsageError("lingua list requires a subcommand. Available: utilities");
@@ -11698,8 +13339,8 @@ function assertSingleTarget(command, positionals, help, label2) {
11698
13339
 
11699
13340
  // src/cli/lingua.ts
11700
13341
  function resolveCliVersion() {
11701
- if ("1.6.2".length > 0) {
11702
- return "1.6.2";
13342
+ if ("2.1.0".length > 0) {
13343
+ return "2.1.0";
11703
13344
  }
11704
13345
  return "0.0.0-dev";
11705
13346
  }
@@ -11851,6 +13492,63 @@ async function dispatch(argv, io) {
11851
13492
  io
11852
13493
  );
11853
13494
  }
13495
+ if (parsed.command === "repro-pack" || parsed.command === "repro-review" || parsed.command === "repro-run") {
13496
+ const filePath = parsed.positionals[0];
13497
+ const output = {
13498
+ json: parsed.flags.json,
13499
+ quiet: parsed.flags.quiet,
13500
+ color: parsed.flags.color
13501
+ };
13502
+ if (parsed.command === "repro-pack") {
13503
+ if (filePath === void 0 || parsed.flags.entry === void 0) {
13504
+ emitCliFailure(io, parsed.flags, {
13505
+ label: "lingua repro pack",
13506
+ reason: "missing-argument",
13507
+ detail: "Expected a <capsule> positional and --entry <path>."
13508
+ });
13509
+ return CLI_EXIT_CODES.userInputError;
13510
+ }
13511
+ return runReproPackCommand(
13512
+ {
13513
+ ...output,
13514
+ capsulePath: filePath,
13515
+ entry: parsed.flags.entry,
13516
+ files: parsed.flags.files,
13517
+ ...parsed.flags.root !== void 0 ? { root: parsed.flags.root } : {},
13518
+ ...parsed.flags.nodeMajor !== void 0 ? { nodeMajor: parsed.flags.nodeMajor } : {}
13519
+ },
13520
+ io
13521
+ );
13522
+ }
13523
+ if (filePath === void 0) {
13524
+ emitCliFailure(io, parsed.flags, {
13525
+ label: `lingua repro ${parsed.command.slice("repro-".length)}`,
13526
+ reason: "missing-file",
13527
+ detail: "Expected an <envelope> positional."
13528
+ });
13529
+ return CLI_EXIT_CODES.userInputError;
13530
+ }
13531
+ if (parsed.command === "repro-review") {
13532
+ return runReproReviewCommand({ ...output, envelopePath: filePath }, io);
13533
+ }
13534
+ if (parsed.flags.approve === void 0) {
13535
+ emitCliFailure(io, parsed.flags, {
13536
+ label: "lingua repro run",
13537
+ reason: "missing-approval",
13538
+ detail: "Expected --approve <token> from lingua repro review."
13539
+ });
13540
+ return CLI_EXIT_CODES.userInputError;
13541
+ }
13542
+ return runReproRunCommand(
13543
+ {
13544
+ ...output,
13545
+ envelopePath: filePath,
13546
+ approve: parsed.flags.approve,
13547
+ linguaVersion: resolveCliVersion()
13548
+ },
13549
+ io
13550
+ );
13551
+ }
11854
13552
  const exhaustive = parsed.command;
11855
13553
  emitCliFailure(io, parsed.flags, {
11856
13554
  label: "lingua",