poe-code 8.0.1 → 9.0.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 (46) hide show
  1. package/dist/cli/commands/harness.js +12 -3
  2. package/dist/cli/commands/harness.js.map +1 -1
  3. package/dist/index.js +1501 -711
  4. package/dist/index.js.map +4 -4
  5. package/dist/metafile.json +1 -1
  6. package/package.json +1 -1
  7. package/packages/safejs/dist/chunks/chunk-4YIDX44G.js +40 -0
  8. package/packages/safejs/dist/chunks/chunk-4YIDX44G.js.map +7 -0
  9. package/packages/safejs/dist/chunks/chunk-55ZK3CR7.js +7802 -0
  10. package/packages/safejs/dist/chunks/chunk-55ZK3CR7.js.map +7 -0
  11. package/packages/safejs/dist/chunks/{chunk-ME5BTAZT.js → chunk-GQBEEFVQ.js} +150 -19
  12. package/packages/safejs/dist/chunks/{chunk-ME5BTAZT.js.map → chunk-GQBEEFVQ.js.map} +4 -4
  13. package/packages/safejs/dist/chunks/chunk-NI4WFFTL.js +5701 -0
  14. package/packages/safejs/dist/chunks/chunk-NI4WFFTL.js.map +7 -0
  15. package/packages/safejs/dist/chunks/inMemory-RLZ4QGDZ.js +48 -0
  16. package/packages/safejs/dist/chunks/inMemory-RLZ4QGDZ.js.map +7 -0
  17. package/packages/safejs/dist/chunks/server-3SNT3RE2.js +12518 -0
  18. package/packages/safejs/dist/chunks/server-3SNT3RE2.js.map +7 -0
  19. package/packages/safejs/dist/chunks/types-BTF37PZ6.js +348 -0
  20. package/packages/safejs/dist/chunks/types-BTF37PZ6.js.map +7 -0
  21. package/packages/safejs/dist/cli.d.ts +2 -0
  22. package/packages/safejs/dist/cli.js +26 -2
  23. package/packages/safejs/dist/cli.js.map +2 -2
  24. package/packages/safejs/dist/core.js +2 -1
  25. package/packages/safejs/dist/index.d.ts +3 -0
  26. package/packages/safejs/dist/index.js +6 -287
  27. package/packages/safejs/dist/index.js.map +4 -4
  28. package/packages/safejs/dist/interp/host-bridge.d.ts +2 -0
  29. package/packages/safejs/dist/interp/host-bridge.js +20 -9
  30. package/packages/safejs/dist/interp/host-call.d.ts +5 -0
  31. package/packages/safejs/dist/interp/host-call.js +48 -3
  32. package/packages/safejs/dist/interp/resources.d.ts +7 -0
  33. package/packages/safejs/dist/interp/resources.js +36 -0
  34. package/packages/safejs/dist/modules/mcp-transport.d.ts +26 -0
  35. package/packages/safejs/dist/modules/mcp-transport.js +259 -0
  36. package/packages/safejs/dist/modules/mcp.d.ts +15 -1
  37. package/packages/safejs/dist/modules/mcp.js +107 -0
  38. package/packages/safejs/dist/run.js +6 -3
  39. package/packages/safejs/dist/snapshot/dump-format.d.ts +1 -1
  40. package/packages/safejs/dist/snapshot/dump-format.js +1 -1
  41. package/packages/safejs/dist/snapshot/replay-data.d.ts +1 -0
  42. package/packages/safejs/dist/snapshot/replay-data.js +3 -1
  43. package/packages/safejs/dist/snapshot/replay-inputs.d.ts +2 -2
  44. package/packages/safejs/dist/snapshot/replay-inputs.js +2 -1
  45. package/packages/safejs/dist/chunks/chunk-AVDRLE3Y.js +0 -3461
  46. package/packages/safejs/dist/chunks/chunk-AVDRLE3Y.js.map +0 -7
package/dist/index.js CHANGED
@@ -16370,17 +16370,17 @@ function validate(schema, value) {
16370
16370
  }
16371
16371
  return { ok: true, value: result.present ? result.value : void 0 };
16372
16372
  }
16373
- function walkSchema(schema, value, path189, state) {
16373
+ function walkSchema(schema, value, path190, state) {
16374
16374
  if (schema.kind === "optional") {
16375
- return walkOptional(schema, value, path189, state);
16375
+ return walkOptional(schema, value, path190, state);
16376
16376
  }
16377
16377
  if (value === missingValue) {
16378
16378
  addIssue(
16379
16379
  state,
16380
- path189,
16380
+ path190,
16381
16381
  expectedFor(schema),
16382
16382
  "missing",
16383
- `Expected ${expectedFor(schema)} at ${formatPath(path189)}`
16383
+ `Expected ${expectedFor(schema)} at ${formatPath(path190)}`
16384
16384
  );
16385
16385
  return { present: false };
16386
16386
  }
@@ -16389,149 +16389,149 @@ function walkSchema(schema, value, path189, state) {
16389
16389
  }
16390
16390
  switch (schema.kind) {
16391
16391
  case "string":
16392
- return walkString(schema, value, path189, state);
16392
+ return walkString(schema, value, path190, state);
16393
16393
  case "number":
16394
- return walkNumber(schema, value, path189, state);
16394
+ return walkNumber(schema, value, path190, state);
16395
16395
  case "boolean":
16396
- return walkBoolean(value, path189, state);
16396
+ return walkBoolean(value, path190, state);
16397
16397
  case "enum":
16398
- return walkEnum(schema, value, path189, state);
16398
+ return walkEnum(schema, value, path190, state);
16399
16399
  case "array":
16400
- return walkArray(schema, value, path189, state);
16400
+ return walkArray(schema, value, path190, state);
16401
16401
  case "object":
16402
- return walkObject(schema, value, path189, state);
16402
+ return walkObject(schema, value, path190, state);
16403
16403
  case "oneOf":
16404
- return walkOneOf(schema, value, path189, state);
16404
+ return walkOneOf(schema, value, path190, state);
16405
16405
  case "union":
16406
- return walkUnion(schema, value, path189, state);
16406
+ return walkUnion(schema, value, path190, state);
16407
16407
  case "record":
16408
- return walkRecord(schema, value, path189, state);
16408
+ return walkRecord(schema, value, path190, state);
16409
16409
  case "json":
16410
- return walkJson(value, path189, state);
16410
+ return walkJson(value, path190, state);
16411
16411
  }
16412
16412
  }
16413
- function walkOptional(schema, value, path189, state) {
16413
+ function walkOptional(schema, value, path190, state) {
16414
16414
  if (value === missingValue || value === void 0) {
16415
16415
  const defaultValue = getDefault(schema.inner);
16416
16416
  if (defaultValue.present) {
16417
- return walkSchema(schema.inner, cloneDefault(defaultValue.value), path189, state);
16417
+ return walkSchema(schema.inner, cloneDefault(defaultValue.value), path190, state);
16418
16418
  }
16419
16419
  return { present: false };
16420
16420
  }
16421
- return walkSchema(schema.inner, value, path189, state);
16421
+ return walkSchema(schema.inner, value, path190, state);
16422
16422
  }
16423
- function walkString(schema, value, path189, state) {
16423
+ function walkString(schema, value, path190, state) {
16424
16424
  if (typeof value !== "string") {
16425
- addExpectedIssue(state, path189, "string", value);
16425
+ addExpectedIssue(state, path190, "string", value);
16426
16426
  return { present: true, value };
16427
16427
  }
16428
16428
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
16429
16429
  const expected = `string with length at least ${schema.minLength}`;
16430
16430
  addIssue(
16431
16431
  state,
16432
- path189,
16432
+ path190,
16433
16433
  expected,
16434
16434
  `string with length ${value.length}`,
16435
- `Expected ${expected} at ${formatPath(path189)}`
16435
+ `Expected ${expected} at ${formatPath(path190)}`
16436
16436
  );
16437
16437
  }
16438
16438
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
16439
16439
  const expected = `string with length at most ${schema.maxLength}`;
16440
16440
  addIssue(
16441
16441
  state,
16442
- path189,
16442
+ path190,
16443
16443
  expected,
16444
16444
  `string with length ${value.length}`,
16445
- `Expected ${expected} at ${formatPath(path189)}`
16445
+ `Expected ${expected} at ${formatPath(path190)}`
16446
16446
  );
16447
16447
  }
16448
16448
  if (schema.pattern !== void 0) {
16449
16449
  const pattern = compilePattern(schema.pattern);
16450
16450
  if (pattern === void 0 || !pattern.test(value)) {
16451
16451
  const expected = `string matching pattern ${schema.pattern}`;
16452
- addIssue(state, path189, expected, value, `Expected ${expected} at ${formatPath(path189)}`);
16452
+ addIssue(state, path190, expected, value, `Expected ${expected} at ${formatPath(path190)}`);
16453
16453
  }
16454
16454
  }
16455
16455
  return { present: true, value };
16456
16456
  }
16457
- function walkNumber(schema, value, path189, state) {
16457
+ function walkNumber(schema, value, path190, state) {
16458
16458
  if (typeof value !== "number" || !Number.isFinite(value)) {
16459
- addExpectedIssue(state, path189, schema.jsonType === "integer" ? "integer" : "number", value);
16459
+ addExpectedIssue(state, path190, schema.jsonType === "integer" ? "integer" : "number", value);
16460
16460
  return { present: true, value };
16461
16461
  }
16462
16462
  if (schema.jsonType === "integer" && !Number.isInteger(value)) {
16463
- addExpectedIssue(state, path189, "integer", value);
16463
+ addExpectedIssue(state, path190, "integer", value);
16464
16464
  }
16465
16465
  if (schema.minimum !== void 0 && value < schema.minimum) {
16466
16466
  const expected = `number greater than or equal to ${schema.minimum}`;
16467
- addIssue(state, path189, expected, String(value), `Expected ${expected} at ${formatPath(path189)}`);
16467
+ addIssue(state, path190, expected, String(value), `Expected ${expected} at ${formatPath(path190)}`);
16468
16468
  }
16469
16469
  if (schema.maximum !== void 0 && value > schema.maximum) {
16470
16470
  const expected = `number less than or equal to ${schema.maximum}`;
16471
- addIssue(state, path189, expected, String(value), `Expected ${expected} at ${formatPath(path189)}`);
16471
+ addIssue(state, path190, expected, String(value), `Expected ${expected} at ${formatPath(path190)}`);
16472
16472
  }
16473
16473
  return { present: true, value };
16474
16474
  }
16475
- function walkBoolean(value, path189, state) {
16475
+ function walkBoolean(value, path190, state) {
16476
16476
  if (typeof value !== "boolean") {
16477
- addExpectedIssue(state, path189, "boolean", value);
16477
+ addExpectedIssue(state, path190, "boolean", value);
16478
16478
  }
16479
16479
  return { present: true, value };
16480
16480
  }
16481
- function walkEnum(schema, value, path189, state) {
16481
+ function walkEnum(schema, value, path190, state) {
16482
16482
  if (!schema.values.includes(value)) {
16483
16483
  const expected = `one of ${schema.values.join(", ")}`;
16484
16484
  addIssue(
16485
16485
  state,
16486
- path189,
16486
+ path190,
16487
16487
  expected,
16488
16488
  receivedValue(value),
16489
- `Expected ${expected} at ${formatPath(path189)}`
16489
+ `Expected ${expected} at ${formatPath(path190)}`
16490
16490
  );
16491
16491
  }
16492
16492
  return { present: true, value };
16493
16493
  }
16494
- function walkArray(schema, value, path189, state) {
16494
+ function walkArray(schema, value, path190, state) {
16495
16495
  if (!Array.isArray(value)) {
16496
- addExpectedIssue(state, path189, "array", value);
16496
+ addExpectedIssue(state, path190, "array", value);
16497
16497
  return { present: true, value };
16498
16498
  }
16499
16499
  if (schema.minItems !== void 0 && value.length < schema.minItems) {
16500
16500
  const expected = `array with at least ${schema.minItems} items`;
16501
16501
  addIssue(
16502
16502
  state,
16503
- path189,
16503
+ path190,
16504
16504
  expected,
16505
16505
  `array with ${value.length} items`,
16506
- `Expected ${expected} at ${formatPath(path189)}`
16506
+ `Expected ${expected} at ${formatPath(path190)}`
16507
16507
  );
16508
16508
  }
16509
16509
  if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
16510
16510
  const expected = `array with at most ${schema.maxItems} items`;
16511
16511
  addIssue(
16512
16512
  state,
16513
- path189,
16513
+ path190,
16514
16514
  expected,
16515
16515
  `array with ${value.length} items`,
16516
- `Expected ${expected} at ${formatPath(path189)}`
16516
+ `Expected ${expected} at ${formatPath(path190)}`
16517
16517
  );
16518
16518
  }
16519
16519
  const nextValue = value.map((item, index) => {
16520
- const result = walkSchema(schema.item, item, [...path189, String(index)], state);
16520
+ const result = walkSchema(schema.item, item, [...path190, String(index)], state);
16521
16521
  return result.present ? result.value : item;
16522
16522
  });
16523
16523
  return { present: true, value: nextValue };
16524
16524
  }
16525
- function walkObject(schema, value, path189, state, injectedProperties = {}) {
16525
+ function walkObject(schema, value, path190, state, injectedProperties = {}) {
16526
16526
  if (!isPlainRecord3(value)) {
16527
- addExpectedIssue(state, path189, "object", value);
16527
+ addExpectedIssue(state, path190, "object", value);
16528
16528
  return { present: true, value };
16529
16529
  }
16530
16530
  const nextValue = {};
16531
16531
  const allowedKeys = /* @__PURE__ */ new Set([...Object.keys(schema.shape), ...Object.keys(injectedProperties)]);
16532
16532
  for (const [key3, propertySchema] of Object.entries(schema.shape)) {
16533
16533
  const propertyValue = Object.hasOwn(value, key3) ? value[key3] : missingValue;
16534
- const result = walkSchema(propertySchema, propertyValue, [...path189, key3], state);
16534
+ const result = walkSchema(propertySchema, propertyValue, [...path190, key3], state);
16535
16535
  if (result.present) {
16536
16536
  setOwnValue(nextValue, key3, result.value);
16537
16537
  }
@@ -16550,18 +16550,18 @@ function walkObject(schema, value, path189, state, injectedProperties = {}) {
16550
16550
  if (schema.additionalProperties === true) {
16551
16551
  setOwnValue(nextValue, key3, propertyValue);
16552
16552
  } else {
16553
- addUnexpectedPropertyIssue(state, [...path189, key3]);
16553
+ addUnexpectedPropertyIssue(state, [...path190, key3]);
16554
16554
  }
16555
16555
  }
16556
16556
  return { present: true, value: nextValue };
16557
16557
  }
16558
- function walkOneOf(schema, value, path189, state) {
16558
+ function walkOneOf(schema, value, path190, state) {
16559
16559
  if (!isPlainRecord3(value)) {
16560
- addExpectedIssue(state, path189, "object", value);
16560
+ addExpectedIssue(state, path190, "object", value);
16561
16561
  return { present: true, value };
16562
16562
  }
16563
16563
  const discriminatorValue = value[schema.discriminator];
16564
- const discriminatorPath = [...path189, schema.discriminator];
16564
+ const discriminatorPath = [...path190, schema.discriminator];
16565
16565
  const branchValues = Object.keys(schema.branches);
16566
16566
  const expected = `one of ${branchValues.join(", ")}`;
16567
16567
  if (!Object.hasOwn(value, schema.discriminator)) {
@@ -16570,7 +16570,7 @@ function walkOneOf(schema, value, path189, state) {
16570
16570
  discriminatorPath,
16571
16571
  expected,
16572
16572
  "missing",
16573
- `Missing discriminator "${schema.discriminator}" at ${formatPath(path189)}. Expected one of: ${branchValues.join(", ")}.`
16573
+ `Missing discriminator "${schema.discriminator}" at ${formatPath(path190)}. Expected one of: ${branchValues.join(", ")}.`
16574
16574
  );
16575
16575
  return { present: true, value };
16576
16576
  }
@@ -16584,21 +16584,21 @@ function walkOneOf(schema, value, path189, state) {
16584
16584
  );
16585
16585
  return { present: true, value };
16586
16586
  }
16587
- return walkObject(schema.branches[discriminatorValue], value, path189, state, {
16587
+ return walkObject(schema.branches[discriminatorValue], value, path190, state, {
16588
16588
  [schema.discriminator]: discriminatorValue
16589
16589
  });
16590
16590
  }
16591
- function walkUnion(schema, value, path189, state) {
16591
+ function walkUnion(schema, value, path190, state) {
16592
16592
  if (isPlainRecord3(value)) {
16593
16593
  const candidateBranches = schema.branches.filter((branch) => hasRequiredKeys(branch, value));
16594
16594
  if (candidateBranches.length === 1) {
16595
- return walkObject(candidateBranches[0], value, path189, state);
16595
+ return walkObject(candidateBranches[0], value, path190, state);
16596
16596
  }
16597
16597
  }
16598
16598
  const matches = [];
16599
16599
  for (const branch of schema.branches) {
16600
16600
  const branchState = { issues: [] };
16601
- const result = walkObject(branch, value, path189, branchState);
16601
+ const result = walkObject(branch, value, path190, branchState);
16602
16602
  if (branchState.issues.length === 0 && result.present) {
16603
16603
  matches.push({ fingerprint: getRequiredKeyFingerprint(branch), value: result.value });
16604
16604
  }
@@ -16610,19 +16610,19 @@ function walkUnion(schema, value, path189, state) {
16610
16610
  const branchDescriptions = schema.branches.map((branch) => getRequiredKeyFingerprint(branch));
16611
16611
  addIssueWithMessage(
16612
16612
  state,
16613
- path189,
16613
+ path190,
16614
16614
  "exactly one union branch",
16615
16615
  "0 matching branches",
16616
- `No union branch matched at ${formatPath(path189)}. Tried ${schema.branches.length} branches. Expected one of: ${branchDescriptions.join(" | ")}.`
16616
+ `No union branch matched at ${formatPath(path190)}. Tried ${schema.branches.length} branches. Expected one of: ${branchDescriptions.join(" | ")}.`
16617
16617
  );
16618
16618
  return { present: true, value };
16619
16619
  }
16620
16620
  addIssueWithMessage(
16621
16621
  state,
16622
- path189,
16622
+ path190,
16623
16623
  "exactly one union branch",
16624
16624
  `${matches.length} matching branches`,
16625
- `Expected exactly one union branch at ${formatPath(path189)}, but matched more than one branch: ${matches.map((match) => match.fingerprint).join(" | ")}`
16625
+ `Expected exactly one union branch at ${formatPath(path190)}, but matched more than one branch: ${matches.map((match) => match.fingerprint).join(" | ")}`
16626
16626
  );
16627
16627
  return { present: true, value };
16628
16628
  }
@@ -16634,25 +16634,25 @@ function hasRequiredKeys(schema, value) {
16634
16634
  }
16635
16635
  return true;
16636
16636
  }
16637
- function walkRecord(schema, value, path189, state) {
16637
+ function walkRecord(schema, value, path190, state) {
16638
16638
  if (!isPlainRecord3(value)) {
16639
- addExpectedIssue(state, path189, "object", value);
16639
+ addExpectedIssue(state, path190, "object", value);
16640
16640
  return { present: true, value };
16641
16641
  }
16642
16642
  const nextValue = {};
16643
16643
  for (const [key3, propertyValue] of Object.entries(value)) {
16644
- const result = walkSchema(schema.value, propertyValue, [...path189, key3], state);
16644
+ const result = walkSchema(schema.value, propertyValue, [...path190, key3], state);
16645
16645
  if (result.present) {
16646
16646
  setOwnValue(nextValue, key3, result.value);
16647
16647
  }
16648
16648
  }
16649
16649
  return { present: true, value: nextValue };
16650
16650
  }
16651
- function walkJson(value, path189, state) {
16651
+ function walkJson(value, path190, state) {
16652
16652
  if (isJsonValue(value)) {
16653
16653
  return { present: true, value };
16654
16654
  }
16655
- addExpectedIssue(state, path189, "JSON value", value);
16655
+ addExpectedIssue(state, path190, "JSON value", value);
16656
16656
  return { present: true, value };
16657
16657
  }
16658
16658
  function getDefault(schema) {
@@ -16730,45 +16730,45 @@ function expectedFor(schema) {
16730
16730
  return expectedFor(schema.inner);
16731
16731
  }
16732
16732
  }
16733
- function addExpectedIssue(state, path189, expected, value) {
16733
+ function addExpectedIssue(state, path190, expected, value) {
16734
16734
  addIssue(
16735
16735
  state,
16736
- path189,
16736
+ path190,
16737
16737
  expected,
16738
16738
  receivedType(value),
16739
- `Expected ${expected} at ${formatPath(path189)}`
16739
+ `Expected ${expected} at ${formatPath(path190)}`
16740
16740
  );
16741
16741
  }
16742
- function addUnexpectedPropertyIssue(state, path189) {
16742
+ function addUnexpectedPropertyIssue(state, path190) {
16743
16743
  addIssue(
16744
16744
  state,
16745
- path189,
16745
+ path190,
16746
16746
  "no additional properties",
16747
16747
  "unknown property",
16748
- `Unexpected property ${formatPath(path189)}`
16748
+ `Unexpected property ${formatPath(path190)}`
16749
16749
  );
16750
16750
  }
16751
- function addIssue(state, path189, expected, received, _message) {
16751
+ function addIssue(state, path190, expected, received, _message) {
16752
16752
  state.issues.push({
16753
- path: path189,
16753
+ path: path190,
16754
16754
  expected,
16755
16755
  received,
16756
- message: formatIssueMessage(expected, path189, received)
16756
+ message: formatIssueMessage(expected, path190, received)
16757
16757
  });
16758
16758
  }
16759
- function addIssueWithMessage(state, path189, expected, received, message2) {
16759
+ function addIssueWithMessage(state, path190, expected, received, message2) {
16760
16760
  state.issues.push({
16761
- path: path189,
16761
+ path: path190,
16762
16762
  expected,
16763
16763
  received,
16764
16764
  message: message2
16765
16765
  });
16766
16766
  }
16767
- function formatIssueMessage(expected, path189, received) {
16768
- return `Expected ${expected} at ${formatPath(path189)}, got ${received}`;
16767
+ function formatIssueMessage(expected, path190, received) {
16768
+ return `Expected ${expected} at ${formatPath(path190)}, got ${received}`;
16769
16769
  }
16770
- function formatPath(path189) {
16771
- return path189.length === 0 ? "value" : path189.join(".");
16770
+ function formatPath(path190) {
16771
+ return path190.length === 0 ? "value" : path190.join(".");
16772
16772
  }
16773
16773
  function compilePattern(pattern) {
16774
16774
  try {
@@ -16882,8 +16882,8 @@ function receivedType2(value) {
16882
16882
  }
16883
16883
  return typeof value;
16884
16884
  }
16885
- function issue(path189, expected, value, message2, keyword = keywordFor(expected)) {
16886
- return { path: path189, expected, received: receivedType2(value), message: message2, keyword };
16885
+ function issue(path190, expected, value, message2, keyword = keywordFor(expected)) {
16886
+ return { path: path190, expected, received: receivedType2(value), message: message2, keyword };
16887
16887
  }
16888
16888
  function keywordFor(expected) {
16889
16889
  if (["null", "boolean", "object", "array", "number", "integer", "string"].includes(expected)) {
@@ -17715,44 +17715,44 @@ function evaluateArrayApplicators(graph, node, schema, value, context) {
17715
17715
  }
17716
17716
  return results;
17717
17717
  }
17718
- function evaluateValidationKeywords(node, schema, value, path189) {
17718
+ function evaluateValidationKeywords(node, schema, value, path190) {
17719
17719
  const results = [];
17720
17720
  if (schema.nullable === true && value === null) {
17721
17721
  return results;
17722
17722
  }
17723
17723
  const types2 = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
17724
17724
  if (types2.length > 0 && !types2.some((type) => typeof type === "string" && typeMatches(type, value))) {
17725
- results.push(invalidResult(issue(path189, types2.join(","), value, `must be ${types2.join(",")}`)));
17725
+ results.push(invalidResult(issue(path190, types2.join(","), value, `must be ${types2.join(",")}`)));
17726
17726
  return results;
17727
17727
  }
17728
17728
  if (schema.const !== void 0 && !deepEqual(schema.const, value)) {
17729
- results.push(invalidResult(issue(path189, "const", value, "must be equal to constant")));
17729
+ results.push(invalidResult(issue(path190, "const", value, "must be equal to constant")));
17730
17730
  }
17731
17731
  if (Array.isArray(schema.enum) && !schema.enum.some((entry) => deepEqual(entry, value))) {
17732
17732
  results.push(
17733
- invalidResult(issue(path189, "enum", value, "must be equal to one of the allowed values"))
17733
+ invalidResult(issue(path190, "enum", value, "must be equal to one of the allowed values"))
17734
17734
  );
17735
17735
  }
17736
17736
  if (typeof value === "number" && Number.isFinite(value)) {
17737
- evaluateNumberKeywords(schema, value, path189, results);
17737
+ evaluateNumberKeywords(schema, value, path190, results);
17738
17738
  }
17739
17739
  if (typeof value === "string") {
17740
- evaluateStringKeywords(schema, value, path189, results);
17740
+ evaluateStringKeywords(schema, value, path190, results);
17741
17741
  }
17742
17742
  if (Array.isArray(value)) {
17743
- evaluateArrayKeywords(schema, value, path189, results);
17743
+ evaluateArrayKeywords(schema, value, path190, results);
17744
17744
  }
17745
17745
  if (isObject(value)) {
17746
- evaluateObjectKeywords(node, schema, value, path189, results);
17746
+ evaluateObjectKeywords(node, schema, value, path190, results);
17747
17747
  }
17748
17748
  return results;
17749
17749
  }
17750
- function evaluateNumberKeywords(schema, value, path189, results) {
17750
+ function evaluateNumberKeywords(schema, value, path190, results) {
17751
17751
  if (typeof schema.multipleOf === "number" && !isMultipleOf(value, schema.multipleOf)) {
17752
17752
  results.push(
17753
17753
  invalidResult(
17754
17754
  issue(
17755
- path189,
17755
+ path190,
17756
17756
  `multiple of ${schema.multipleOf}`,
17757
17757
  value,
17758
17758
  `must be multiple of ${schema.multipleOf}`
@@ -17762,36 +17762,36 @@ function evaluateNumberKeywords(schema, value, path189, results) {
17762
17762
  }
17763
17763
  if (typeof schema.maximum === "number" && value > schema.maximum) {
17764
17764
  results.push(
17765
- invalidResult(issue(path189, `<= ${schema.maximum}`, value, `must be <= ${schema.maximum}`))
17765
+ invalidResult(issue(path190, `<= ${schema.maximum}`, value, `must be <= ${schema.maximum}`))
17766
17766
  );
17767
17767
  }
17768
17768
  if (typeof schema.minimum === "number" && value < schema.minimum) {
17769
17769
  results.push(
17770
- invalidResult(issue(path189, `>= ${schema.minimum}`, value, `must be >= ${schema.minimum}`))
17770
+ invalidResult(issue(path190, `>= ${schema.minimum}`, value, `must be >= ${schema.minimum}`))
17771
17771
  );
17772
17772
  }
17773
17773
  if (typeof schema.exclusiveMaximum === "number" && value >= schema.exclusiveMaximum) {
17774
17774
  results.push(
17775
17775
  invalidResult(
17776
- issue(path189, `< ${schema.exclusiveMaximum}`, value, `must be < ${schema.exclusiveMaximum}`)
17776
+ issue(path190, `< ${schema.exclusiveMaximum}`, value, `must be < ${schema.exclusiveMaximum}`)
17777
17777
  )
17778
17778
  );
17779
17779
  }
17780
17780
  if (typeof schema.exclusiveMinimum === "number" && value <= schema.exclusiveMinimum) {
17781
17781
  results.push(
17782
17782
  invalidResult(
17783
- issue(path189, `> ${schema.exclusiveMinimum}`, value, `must be > ${schema.exclusiveMinimum}`)
17783
+ issue(path190, `> ${schema.exclusiveMinimum}`, value, `must be > ${schema.exclusiveMinimum}`)
17784
17784
  )
17785
17785
  );
17786
17786
  }
17787
17787
  }
17788
- function evaluateStringKeywords(schema, value, path189, results) {
17788
+ function evaluateStringKeywords(schema, value, path190, results) {
17789
17789
  const length = unicodeLength(value);
17790
17790
  if (typeof schema.maxLength === "number" && length > schema.maxLength) {
17791
17791
  results.push(
17792
17792
  invalidResult(
17793
17793
  issue(
17794
- path189,
17794
+ path190,
17795
17795
  `length <= ${schema.maxLength}`,
17796
17796
  value,
17797
17797
  `must NOT have more than ${schema.maxLength} characters`
@@ -17803,7 +17803,7 @@ function evaluateStringKeywords(schema, value, path189, results) {
17803
17803
  results.push(
17804
17804
  invalidResult(
17805
17805
  issue(
17806
- path189,
17806
+ path190,
17807
17807
  `length >= ${schema.minLength}`,
17808
17808
  value,
17809
17809
  `must NOT have fewer than ${schema.minLength} characters`
@@ -17814,17 +17814,17 @@ function evaluateStringKeywords(schema, value, path189, results) {
17814
17814
  if (typeof schema.pattern === "string" && !new RegExp(schema.pattern, "u").test(value)) {
17815
17815
  results.push(
17816
17816
  invalidResult(
17817
- issue(path189, `pattern ${schema.pattern}`, value, `must match pattern ${schema.pattern}`)
17817
+ issue(path190, `pattern ${schema.pattern}`, value, `must match pattern ${schema.pattern}`)
17818
17818
  )
17819
17819
  );
17820
17820
  }
17821
17821
  }
17822
- function evaluateArrayKeywords(schema, value, path189, results) {
17822
+ function evaluateArrayKeywords(schema, value, path190, results) {
17823
17823
  if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
17824
17824
  results.push(
17825
17825
  invalidResult(
17826
17826
  issue(
17827
- path189,
17827
+ path190,
17828
17828
  `items <= ${schema.maxItems}`,
17829
17829
  value,
17830
17830
  `must NOT have more than ${schema.maxItems} items`
@@ -17836,7 +17836,7 @@ function evaluateArrayKeywords(schema, value, path189, results) {
17836
17836
  results.push(
17837
17837
  invalidResult(
17838
17838
  issue(
17839
- path189,
17839
+ path190,
17840
17840
  `items >= ${schema.minItems}`,
17841
17841
  value,
17842
17842
  `must NOT have fewer than ${schema.minItems} items`
@@ -17849,7 +17849,7 @@ function evaluateArrayKeywords(schema, value, path189, results) {
17849
17849
  for (let right = left + 1; right < value.length; right += 1) {
17850
17850
  if (deepEqual(value[left], value[right])) {
17851
17851
  results.push(
17852
- invalidResult(issue(path189, "unique items", value, "must NOT have duplicate items"))
17852
+ invalidResult(issue(path190, "unique items", value, "must NOT have duplicate items"))
17853
17853
  );
17854
17854
  return;
17855
17855
  }
@@ -17857,13 +17857,13 @@ function evaluateArrayKeywords(schema, value, path189, results) {
17857
17857
  }
17858
17858
  }
17859
17859
  }
17860
- function evaluateObjectKeywords(node, schema, value, path189, results) {
17860
+ function evaluateObjectKeywords(node, schema, value, path190, results) {
17861
17861
  const keys = Object.keys(value);
17862
17862
  if (typeof schema.maxProperties === "number" && keys.length > schema.maxProperties) {
17863
17863
  results.push(
17864
17864
  invalidResult(
17865
17865
  issue(
17866
- path189,
17866
+ path190,
17867
17867
  `properties <= ${schema.maxProperties}`,
17868
17868
  value,
17869
17869
  `must NOT have more than ${schema.maxProperties} properties`
@@ -17875,7 +17875,7 @@ function evaluateObjectKeywords(node, schema, value, path189, results) {
17875
17875
  results.push(
17876
17876
  invalidResult(
17877
17877
  issue(
17878
- path189,
17878
+ path190,
17879
17879
  `properties >= ${schema.minProperties}`,
17880
17880
  value,
17881
17881
  `must NOT have fewer than ${schema.minProperties} properties`
@@ -17888,7 +17888,7 @@ function evaluateObjectKeywords(node, schema, value, path189, results) {
17888
17888
  if (typeof key3 === "string" && !Object.prototype.hasOwnProperty.call(value, key3)) {
17889
17889
  results.push(
17890
17890
  invalidResult(
17891
- issue([...path189, key3], "required", void 0, `must have required property '${key3}'`)
17891
+ issue([...path190, key3], "required", void 0, `must have required property '${key3}'`)
17892
17892
  )
17893
17893
  );
17894
17894
  }
@@ -17897,24 +17897,24 @@ function evaluateObjectKeywords(node, schema, value, path189, results) {
17897
17897
  const dependentRequired = isObject(schema.dependentRequired) ? schema.dependentRequired : {};
17898
17898
  for (const [key3, dependencies] of Object.entries(dependentRequired)) {
17899
17899
  if (Object.prototype.hasOwnProperty.call(value, key3) && Array.isArray(dependencies)) {
17900
- addMissingDependencies(value, dependencies, path189, results);
17900
+ addMissingDependencies(value, dependencies, path190, results);
17901
17901
  }
17902
17902
  }
17903
17903
  if (node.dialect === "draft7" && isObject(schema.dependencies)) {
17904
17904
  for (const [key3, dependencies] of Object.entries(schema.dependencies)) {
17905
17905
  if (Object.prototype.hasOwnProperty.call(value, key3) && Array.isArray(dependencies)) {
17906
- addMissingDependencies(value, dependencies, path189, results);
17906
+ addMissingDependencies(value, dependencies, path190, results);
17907
17907
  }
17908
17908
  }
17909
17909
  }
17910
17910
  }
17911
- function addMissingDependencies(value, dependencies, path189, results) {
17911
+ function addMissingDependencies(value, dependencies, path190, results) {
17912
17912
  for (const dependency of dependencies) {
17913
17913
  if (typeof dependency === "string" && !Object.prototype.hasOwnProperty.call(value, dependency)) {
17914
17914
  results.push(
17915
17915
  invalidResult(
17916
17916
  issue(
17917
- [...path189, dependency],
17917
+ [...path190, dependency],
17918
17918
  "dependency",
17919
17919
  void 0,
17920
17920
  `must have property '${dependency}'`
@@ -18036,8 +18036,8 @@ function compileJsonSchema(schema, options = {}) {
18036
18036
  }
18037
18037
  function formatIssues(issues) {
18038
18038
  return issues.map((current) => {
18039
- const path189 = current.path.length === 0 ? "data" : `data/${current.path.join("/")}`;
18040
- return `${path189} ${current.message}`;
18039
+ const path190 = current.path.length === 0 ? "data" : `data/${current.path.join("/")}`;
18040
+ return `${path190} ${current.message}`;
18041
18041
  }).join(", ");
18042
18042
  }
18043
18043
  var init_json_schema = __esm({
@@ -18547,11 +18547,11 @@ function mergeLayers(layers) {
18547
18547
  }
18548
18548
  return mergeObjectLayers(layers, []);
18549
18549
  }
18550
- function mergeObjectLayers(layers, path189) {
18550
+ function mergeObjectLayers(layers, path190) {
18551
18551
  const data = {};
18552
18552
  const sources = {};
18553
18553
  for (const key3 of collectKeys(layers)) {
18554
- const resolved = resolveKey(layers, key3, path189);
18554
+ const resolved = resolveKey(layers, key3, path190);
18555
18555
  if (resolved === void 0) {
18556
18556
  continue;
18557
18557
  }
@@ -18571,7 +18571,7 @@ function collectKeys(layers) {
18571
18571
  }
18572
18572
  return [...keys];
18573
18573
  }
18574
- function resolveKey(layers, key3, path189) {
18574
+ function resolveKey(layers, key3, path190) {
18575
18575
  let winningSource;
18576
18576
  let winningValue;
18577
18577
  const objectLayers = [];
@@ -18604,9 +18604,9 @@ function resolveKey(layers, key3, path189) {
18604
18604
  if (winningValue === null) {
18605
18605
  return void 0;
18606
18606
  }
18607
- const fullPath = buildPath(path189, key3);
18607
+ const fullPath = buildPath(path190, key3);
18608
18608
  if (isPlainObject(winningValue)) {
18609
- const merged = mergeObjectLayers(objectLayers, [...path189, key3]);
18609
+ const merged = mergeObjectLayers(objectLayers, [...path190, key3]);
18610
18610
  return {
18611
18611
  value: merged.data,
18612
18612
  sources: {
@@ -18634,8 +18634,8 @@ function isWinningCandidate(key3, value) {
18634
18634
  function getOwnEntry2(record2, key3) {
18635
18635
  return Object.prototype.hasOwnProperty.call(record2, key3) ? record2[key3] : void 0;
18636
18636
  }
18637
- function buildPath(path189, key3) {
18638
- return [...path189, key3].map(escapePathSegment).join(".");
18637
+ function buildPath(path190, key3) {
18638
+ return [...path190, key3].map(escapePathSegment).join(".");
18639
18639
  }
18640
18640
  function escapePathSegment(segment) {
18641
18641
  return segment.replaceAll("\\", "\\\\").replaceAll(".", "\\.");
@@ -19499,22 +19499,22 @@ function prune2(obj, shape) {
19499
19499
  }
19500
19500
  return { changed, result };
19501
19501
  }
19502
- function modifyAtPath(content, path189, value) {
19502
+ function modifyAtPath(content, path190, value) {
19503
19503
  const indent = detectIndent(content);
19504
19504
  const formattingOptions = {
19505
19505
  tabSize: indent === " " ? 1 : indent.length,
19506
19506
  insertSpaces: indent !== " ",
19507
19507
  eol: "\n"
19508
19508
  };
19509
- const edits = jsonc.modify(content, path189, value, { formattingOptions });
19509
+ const edits = jsonc.modify(content, path190, value, { formattingOptions });
19510
19510
  let result = jsonc.applyEdits(content, edits);
19511
19511
  if (!result.endsWith("\n")) {
19512
19512
  result += "\n";
19513
19513
  }
19514
19514
  return result;
19515
19515
  }
19516
- function removeAtPath(content, path189) {
19517
- return modifyAtPath(content, path189, void 0);
19516
+ function removeAtPath(content, path190) {
19517
+ return modifyAtPath(content, path190, void 0);
19518
19518
  }
19519
19519
  function serializeUpdate(content, current, next) {
19520
19520
  let result = content || "{}";
@@ -19524,15 +19524,15 @@ function serializeUpdate(content, current, next) {
19524
19524
  }
19525
19525
  return result;
19526
19526
  }
19527
- function applyObjectUpdate(content, path189, current, next) {
19527
+ function applyObjectUpdate(content, path190, current, next) {
19528
19528
  let result = content;
19529
19529
  for (const key3 of Object.keys(current)) {
19530
19530
  if (!hasConfigEntry(next, key3)) {
19531
- result = removeAtPath(result, [...path189, key3]);
19531
+ result = removeAtPath(result, [...path190, key3]);
19532
19532
  }
19533
19533
  }
19534
19534
  for (const [key3, nextValue] of Object.entries(next)) {
19535
- const nextPath = [...path189, key3];
19535
+ const nextPath = [...path190, key3];
19536
19536
  const hasCurrent = hasConfigEntry(current, key3);
19537
19537
  const currentValue = hasCurrent ? current[key3] : void 0;
19538
19538
  if (hasCurrent && isConfigObject(currentValue) && isConfigObject(nextValue)) {
@@ -19739,16 +19739,16 @@ function getConfigFormat(pathOrFormat) {
19739
19739
  }
19740
19740
  return formatRegistry[formatName];
19741
19741
  }
19742
- function detectFormat2(path189) {
19743
- const ext = getExtension(path189);
19742
+ function detectFormat2(path190) {
19743
+ const ext = getExtension(path190);
19744
19744
  return extensionMap[ext];
19745
19745
  }
19746
- function getExtension(path189) {
19747
- const lastDot = path189.lastIndexOf(".");
19746
+ function getExtension(path190) {
19747
+ const lastDot = path190.lastIndexOf(".");
19748
19748
  if (lastDot === -1) {
19749
19749
  return "";
19750
19750
  }
19751
- return path189.slice(lastDot).toLowerCase();
19751
+ return path190.slice(lastDot).toLowerCase();
19752
19752
  }
19753
19753
  var formatRegistry, extensionMap;
19754
19754
  var init_formats = __esm({
@@ -21138,7 +21138,7 @@ function mergeScope(scope, baseScope, overrideScope) {
21138
21138
  }
21139
21139
  return merged;
21140
21140
  }
21141
- function mergeRuntimeScope(baseScope, overrideScope, path189 = []) {
21141
+ function mergeRuntimeScope(baseScope, overrideScope, path190 = []) {
21142
21142
  const merged = {};
21143
21143
  const keys = /* @__PURE__ */ new Set([...Object.keys(baseScope), ...Object.keys(overrideScope)]);
21144
21144
  for (const key3 of keys) {
@@ -21151,7 +21151,7 @@ function mergeRuntimeScope(baseScope, overrideScope, path189 = []) {
21151
21151
  continue;
21152
21152
  }
21153
21153
  if (isRecord4(baseValue) && isRecord4(overrideValue)) {
21154
- setOwnEntry(merged, key3, mergeRuntimeScope(baseValue, overrideValue, [...path189, key3]));
21154
+ setOwnEntry(merged, key3, mergeRuntimeScope(baseValue, overrideValue, [...path190, key3]));
21155
21155
  continue;
21156
21156
  }
21157
21157
  setOwnEntry(merged, key3, overrideValue);
@@ -22742,45 +22742,45 @@ import { createTwoFilesPatch } from "diff";
22742
22742
  import chalk from "chalk";
22743
22743
  function createDryRunFileSystem(base, recorder) {
22744
22744
  const proxy = {
22745
- async readFile(path189, encoding) {
22745
+ async readFile(path190, encoding) {
22746
22746
  if (encoding) {
22747
- return base.readFile(path189, encoding);
22747
+ return base.readFile(path190, encoding);
22748
22748
  }
22749
- return base.readFile(path189);
22749
+ return base.readFile(path190);
22750
22750
  },
22751
- async writeFile(path189, data, options) {
22752
- const previousContent = await tryReadText(base, path189);
22751
+ async writeFile(path190, data, options) {
22752
+ const previousContent = await tryReadText(base, path190);
22753
22753
  const nextContent = formatData(data, options?.encoding);
22754
22754
  recorder.record({
22755
22755
  type: "writeFile",
22756
- path: path189,
22756
+ path: path190,
22757
22757
  nextContent,
22758
22758
  previousContent
22759
22759
  });
22760
22760
  },
22761
- async symlink(target, path189) {
22762
- recorder.record({ type: "symlink", target, path: path189 });
22761
+ async symlink(target, path190) {
22762
+ recorder.record({ type: "symlink", target, path: path190 });
22763
22763
  },
22764
- async readlink(path189) {
22765
- return base.readlink(path189);
22764
+ async readlink(path190) {
22765
+ return base.readlink(path190);
22766
22766
  },
22767
- async realpath(path189) {
22768
- return base.realpath(path189);
22767
+ async realpath(path190) {
22768
+ return base.realpath(path190);
22769
22769
  },
22770
- async mkdir(path189, options) {
22770
+ async mkdir(path190, options) {
22771
22771
  recorder.record({
22772
22772
  type: "mkdir",
22773
- path: path189,
22773
+ path: path190,
22774
22774
  options,
22775
22775
  // Matches how the mutation layer itself decides the mkdir is a no-op.
22776
- existing: await pathExists(base, path189)
22776
+ existing: await pathExists(base, path190)
22777
22777
  });
22778
22778
  },
22779
- async stat(path189) {
22780
- return base.stat(path189);
22779
+ async stat(path190) {
22780
+ return base.stat(path190);
22781
22781
  },
22782
- async lstat(path189) {
22783
- return base.lstat(path189);
22782
+ async lstat(path190) {
22783
+ return base.lstat(path190);
22784
22784
  },
22785
22785
  async rename(from, to) {
22786
22786
  const staged = recorder.takeStagedWrite(from);
@@ -22795,16 +22795,16 @@ function createDryRunFileSystem(base, recorder) {
22795
22795
  }
22796
22796
  recorder.record({ type: "rename", from, to });
22797
22797
  },
22798
- async unlink(path189) {
22799
- recorder.record({ type: "unlink", path: path189 });
22798
+ async unlink(path190) {
22799
+ recorder.record({ type: "unlink", path: path190 });
22800
22800
  },
22801
- async readdir(path189) {
22802
- return base.readdir(path189);
22801
+ async readdir(path190) {
22802
+ return base.readdir(path190);
22803
22803
  }
22804
22804
  };
22805
22805
  if (typeof base.rm === "function") {
22806
- proxy.rm = async (path189, options) => {
22807
- recorder.record({ type: "rm", path: path189, options });
22806
+ proxy.rm = async (path190, options) => {
22807
+ recorder.record({ type: "rm", path: path190, options });
22808
22808
  };
22809
22809
  }
22810
22810
  if (typeof base.copyFile === "function") {
@@ -22949,8 +22949,8 @@ function describeWriteChange(previous, next) {
22949
22949
  }
22950
22950
  return "update";
22951
22951
  }
22952
- function renderWriteCommand(path189, change) {
22953
- const command = `cat > ${quoteShellArgument(path189)}`;
22952
+ function renderWriteCommand(path190, change) {
22953
+ const command = `cat > ${quoteShellArgument(path190)}`;
22954
22954
  if (change === "create") {
22955
22955
  return renderOperationCommand(command, chalk.green, "# create");
22956
22956
  }
@@ -23157,9 +23157,9 @@ function describesChange(operation) {
23157
23157
  }
23158
23158
  return true;
23159
23159
  }
23160
- async function tryReadText(base, path189) {
23160
+ async function tryReadText(base, path190) {
23161
23161
  try {
23162
- return await base.readFile(path189, "utf8");
23162
+ return await base.readFile(path190, "utf8");
23163
23163
  } catch (error3) {
23164
23164
  if (isNotFound(error3)) {
23165
23165
  return null;
@@ -23213,10 +23213,10 @@ var init_dry_run = __esm({
23213
23213
  // Atomic writers stage content in a temp file and rename it over the target.
23214
23214
  // Pulling the staged write back out lets the rename re-record it against the
23215
23215
  // real target, so the preview diffs the delta instead of the whole file.
23216
- takeStagedWrite(path189) {
23216
+ takeStagedWrite(path190) {
23217
23217
  for (let index = this.operations.length - 1; index >= 0; index -= 1) {
23218
23218
  const operation = this.operations[index];
23219
- if (operation.type === "writeFile" && operation.path === path189) {
23219
+ if (operation.type === "writeFile" && operation.path === path190) {
23220
23220
  this.operations.splice(index, 1);
23221
23221
  return operation;
23222
23222
  }
@@ -34906,21 +34906,21 @@ async function* adaptClaude(lines) {
34906
34906
  if (blockType !== "tool_result") continue;
34907
34907
  const kind = toolKindsById.get(item.tool_use_id);
34908
34908
  toolKindsById.delete(item.tool_use_id);
34909
- let path189;
34909
+ let path190;
34910
34910
  if (typeof item.content === "string") {
34911
- path189 = item.content;
34911
+ path190 = item.content;
34912
34912
  } else {
34913
34913
  try {
34914
- path189 = JSON.stringify(item.content);
34914
+ path190 = JSON.stringify(item.content);
34915
34915
  } catch {
34916
- path189 = String(item.content);
34916
+ path190 = String(item.content);
34917
34917
  }
34918
34918
  }
34919
34919
  yield {
34920
34920
  event: "tool_complete",
34921
34921
  id: item.tool_use_id,
34922
34922
  kind,
34923
- path: path189
34923
+ path: path190
34924
34924
  };
34925
34925
  }
34926
34926
  }
@@ -35043,10 +35043,10 @@ async function* adaptCodex(lines) {
35043
35043
  const kindFromStart = toolKindById.get(item.id);
35044
35044
  const kind = kindFromStart ?? (itemType === "command_execution" ? "exec" : itemType === "file_edit" ? "edit" : "other");
35045
35045
  const titleFromEvent = isNonEmptyString(item.path) ? item.path : itemType === "mcp_tool_call" ? `${isNonEmptyString(item.server) ? item.server : "unknown"}.${isNonEmptyString(item.tool) ? item.tool : "unknown"}` : void 0;
35046
- const path189 = titleFromEvent ?? toolTitleById.get(item.id) ?? "";
35046
+ const path190 = titleFromEvent ?? toolTitleById.get(item.id) ?? "";
35047
35047
  toolTitleById.delete(item.id);
35048
35048
  toolKindById.delete(item.id);
35049
- yield { event: "tool_complete", id: item.id, kind, path: path189 };
35049
+ yield { event: "tool_complete", id: item.id, kind, path: path190 };
35050
35050
  }
35051
35051
  }
35052
35052
  }
@@ -35425,14 +35425,14 @@ function toolInfo(event) {
35425
35425
  const [toolName = "tool", rawTool = {}] = Object.entries(toolCall)[0] ?? [];
35426
35426
  const tool = asObject2(rawTool) ?? {};
35427
35427
  const args = asObject2(tool.args) ?? asObject2(tool.arguments) ?? tool;
35428
- const path189 = typeof args.path === "string" ? args.path : "";
35428
+ const path190 = typeof args.path === "string" ? args.path : "";
35429
35429
  const kinds = {
35430
35430
  editToolCall: "edit",
35431
35431
  readToolCall: "read",
35432
35432
  shellToolCall: "exec",
35433
35433
  bashToolCall: "exec"
35434
35434
  };
35435
- return { kind: kinds[toolName] ?? "other", title: path189 || toolName, path: path189 };
35435
+ return { kind: kinds[toolName] ?? "other", title: path190 || toolName, path: path190 };
35436
35436
  }
35437
35437
  async function* adaptCursor(lines) {
35438
35438
  for await (const rawLine of lines) {
@@ -37316,13 +37316,13 @@ var init_acp_transport = __esm({
37316
37316
  cwd,
37317
37317
  env,
37318
37318
  firstRequestId,
37319
- spawn: spawn11 = spawnChildProcess3
37319
+ spawn: spawn12 = spawnChildProcess3
37320
37320
  } = options;
37321
37321
  this.command = command;
37322
37322
  this.closed = new Promise((resolve17) => {
37323
37323
  this.resolveClosed = resolve17;
37324
37324
  });
37325
- this.child = spawn11(command, [...args], {
37325
+ this.child = spawn12(command, [...args], {
37326
37326
  cwd,
37327
37327
  env,
37328
37328
  stdio: ["pipe", "pipe", "pipe"]
@@ -37783,8 +37783,8 @@ function resourceNotFound(resource) {
37783
37783
  `Resource not found: ${resource}`
37784
37784
  );
37785
37785
  }
37786
- function assertAbsolutePath(path189) {
37787
- if (!isAbsolute(path189)) {
37786
+ function assertAbsolutePath(path190) {
37787
+ if (!isAbsolute(path190)) {
37788
37788
  throw invalidParams('"path" must be an absolute path');
37789
37789
  }
37790
37790
  }
@@ -39196,7 +39196,7 @@ function updateSessionFromEvent(ctx, event, toolCallsById) {
39196
39196
  }
39197
39197
  const id = readString(event.id);
39198
39198
  const kind = readString(event.kind);
39199
- const path189 = readString(event.path);
39199
+ const path190 = readString(event.path);
39200
39200
  let toolCall = id ? toolCallsById.get(id) : void 0;
39201
39201
  if (!toolCall) {
39202
39202
  toolCall = {};
@@ -39211,8 +39211,8 @@ function updateSessionFromEvent(ctx, event, toolCallsById) {
39211
39211
  if (kind) {
39212
39212
  toolCall.kind = kind;
39213
39213
  }
39214
- if (path189) {
39215
- toolCall.path = path189;
39214
+ if (path190) {
39215
+ toolCall.path = path190;
39216
39216
  }
39217
39217
  }
39218
39218
  var sessionCapture;
@@ -55184,7 +55184,7 @@ function isWorktree(value) {
55184
55184
  return false;
55185
55185
  }
55186
55186
  const name = getOwnEntry18(value, "name");
55187
- const path189 = getOwnEntry18(value, "path");
55187
+ const path190 = getOwnEntry18(value, "path");
55188
55188
  const branch = getOwnEntry18(value, "branch");
55189
55189
  const baseBranch = getOwnEntry18(value, "baseBranch");
55190
55190
  const createdAt2 = getOwnEntry18(value, "createdAt");
@@ -55198,7 +55198,7 @@ function isWorktree(value) {
55198
55198
  const baseHead = getOwnEntry18(value, "baseHead");
55199
55199
  const reconciledAt = getOwnEntry18(value, "reconciledAt");
55200
55200
  const reconciliation = getOwnEntry18(value, "reconciliation");
55201
- return typeof name === "string" && typeof path189 === "string" && typeof branch === "string" && typeof baseBranch === "string" && typeof createdAt2 === "string" && typeof source === "string" && typeof agent3 === "string" && (status === "active" || status === "reconciling" || status === "conflicted" || status === "cleanup_failed" || status === "done" || status === "failed" || status === "removing") && (storyId === void 0 || typeof storyId === "string") && (planPath === void 0 || typeof planPath === "string") && (prompt === void 0 || typeof prompt === "string") && (sourceCwd === void 0 || typeof sourceCwd === "string") && (baseHead === void 0 || typeof baseHead === "string") && (reconciledAt === void 0 || typeof reconciledAt === "string") && (reconciliation === void 0 || isReconciliationSummary(reconciliation));
55201
+ return typeof name === "string" && typeof path190 === "string" && typeof branch === "string" && typeof baseBranch === "string" && typeof createdAt2 === "string" && typeof source === "string" && typeof agent3 === "string" && (status === "active" || status === "reconciling" || status === "conflicted" || status === "cleanup_failed" || status === "done" || status === "failed" || status === "removing") && (storyId === void 0 || typeof storyId === "string") && (planPath === void 0 || typeof planPath === "string") && (prompt === void 0 || typeof prompt === "string") && (sourceCwd === void 0 || typeof sourceCwd === "string") && (baseHead === void 0 || typeof baseHead === "string") && (reconciledAt === void 0 || typeof reconciledAt === "string") && (reconciliation === void 0 || isReconciliationSummary(reconciliation));
55202
55202
  }
55203
55203
  function isReconciliationSummary(value) {
55204
55204
  if (typeof value !== "object" || value === null) {
@@ -55639,9 +55639,9 @@ function parsePorcelainPaths(output) {
55639
55639
  const entries = output.split("\0").filter((entry) => entry.length > 0);
55640
55640
  for (let index = 0; index < entries.length; index += 1) {
55641
55641
  const entry = entries[index];
55642
- const path189 = entry.length > 3 ? entry.slice(3) : entry;
55643
- if (path189.length > 0) {
55644
- paths.push(path189);
55642
+ const path190 = entry.length > 3 ? entry.slice(3) : entry;
55643
+ if (path190.length > 0) {
55644
+ paths.push(path190);
55645
55645
  }
55646
55646
  if ((entry.startsWith("R ") || entry.startsWith("C ")) && index + 1 < entries.length) {
55647
55647
  const sourcePath = entries[index + 1];
@@ -59063,10 +59063,10 @@ function parseReviewDiff(diffText) {
59063
59063
  finalizeFile();
59064
59064
  const paths = parseDiffGitPaths(line);
59065
59065
  const previousPath = paths?.previousPath ?? "";
59066
- const path189 = paths?.path ?? previousPath;
59066
+ const path190 = paths?.path ?? previousPath;
59067
59067
  currentFile = {
59068
- path: path189,
59069
- previousPath: previousPath && previousPath !== path189 ? previousPath : null,
59068
+ path: path190,
59069
+ previousPath: previousPath && previousPath !== path190 ? previousPath : null,
59070
59070
  status: "modified",
59071
59071
  hunks: [],
59072
59072
  reviewableLines: [],
@@ -59096,9 +59096,9 @@ function parseReviewDiff(diffText) {
59096
59096
  continue;
59097
59097
  }
59098
59098
  if (line.startsWith("+++ ")) {
59099
- const path189 = normalizeDiffPath(line.slice(4).trim());
59100
- if (path189) {
59101
- currentFile.path = path189;
59099
+ const path190 = normalizeDiffPath(line.slice(4).trim());
59100
+ if (path190) {
59101
+ currentFile.path = path190;
59102
59102
  }
59103
59103
  continue;
59104
59104
  }
@@ -59157,31 +59157,31 @@ function validateInlineComments(comments, context) {
59157
59157
  const accepted = [];
59158
59158
  const seen = /* @__PURE__ */ new Set();
59159
59159
  for (const comment of comments) {
59160
- const path189 = comment.path;
59160
+ const path190 = comment.path;
59161
59161
  const body = comment.body.trim();
59162
- if (path189.length === 0 || !body || !Number.isInteger(comment.line) || comment.line < 1) {
59162
+ if (path190.length === 0 || !body || !Number.isInteger(comment.line) || comment.line < 1) {
59163
59163
  throw new Error("Inline review comments require path, positive line, and body.");
59164
59164
  }
59165
59165
  if (comment.side === "LEFT") {
59166
59166
  throw new Error(
59167
- `Inline comment target ${path189}:${comment.line} is a left-side diff target; only right-side comments are supported.`
59167
+ `Inline comment target ${path190}:${comment.line} is a left-side diff target; only right-side comments are supported.`
59168
59168
  );
59169
59169
  }
59170
- if (!context.reviewableLinesByPath.get(path189)?.has(comment.line)) {
59170
+ if (!context.reviewableLinesByPath.get(path190)?.has(comment.line)) {
59171
59171
  throw new Error(
59172
- `Inline comment target ${path189}:${comment.line} is not a valid right-side diff target.`
59172
+ `Inline comment target ${path190}:${comment.line} is not a valid right-side diff target.`
59173
59173
  );
59174
59174
  }
59175
- if (!comment.side && context.leftLinesByPath.get(path189)?.has(comment.line) && context.rightContextLinesByPath.get(path189)?.has(comment.line)) {
59175
+ if (!comment.side && context.leftLinesByPath.get(path190)?.has(comment.line) && context.rightContextLinesByPath.get(path190)?.has(comment.line)) {
59176
59176
  throw new Error(
59177
- `Inline comment target ${path189}:${comment.line} is ambiguous; specify side RIGHT to target the right-side diff line.`
59177
+ `Inline comment target ${path190}:${comment.line} is ambiguous; specify side RIGHT to target the right-side diff line.`
59178
59178
  );
59179
59179
  }
59180
- const key3 = `${path189}\0${comment.line}\0${body}`;
59180
+ const key3 = `${path190}\0${comment.line}\0${body}`;
59181
59181
  if (!seen.has(key3)) {
59182
59182
  seen.add(key3);
59183
59183
  accepted.push({
59184
- path: path189,
59184
+ path: path190,
59185
59185
  line: comment.line,
59186
59186
  ...comment.side ? { side: comment.side } : {},
59187
59187
  body
@@ -59682,9 +59682,9 @@ function reviewEndpoint(prUrl) {
59682
59682
  }
59683
59683
  function normalizeReviewComments(comments) {
59684
59684
  return comments.map((comment) => {
59685
- const path189 = comment.path.trim();
59685
+ const path190 = comment.path.trim();
59686
59686
  const body = comment.body.trim();
59687
- if (!path189) {
59687
+ if (!path190) {
59688
59688
  throw new Error("Review comment path must be non-empty.");
59689
59689
  }
59690
59690
  if (!Number.isSafeInteger(comment.line) || comment.line <= 0) {
@@ -59693,7 +59693,7 @@ function normalizeReviewComments(comments) {
59693
59693
  if (!body) {
59694
59694
  throw new Error("Review comment body must be non-empty.");
59695
59695
  }
59696
- return { path: path189, line: comment.line, body };
59696
+ return { path: path190, line: comment.line, body };
59697
59697
  });
59698
59698
  }
59699
59699
  function submissionFromResponse(response) {
@@ -59988,10 +59988,10 @@ var init_review_history = __esm({
59988
59988
  kind,
59989
59989
  body
59990
59990
  };
59991
- const path189 = text4(record2, "path");
59991
+ const path190 = text4(record2, "path");
59992
59992
  const line = integer(record2, "line") ?? integer(record2, "original_line");
59993
59993
  const diffHunk = text4(record2, "diff_hunk");
59994
- if (path189) normalized.path = path189;
59994
+ if (path190) normalized.path = path190;
59995
59995
  if (line !== null) normalized.line = line;
59996
59996
  if (diffHunk) normalized.diffHunk = diffHunk;
59997
59997
  return normalized;
@@ -60701,9 +60701,9 @@ function containedPath(directory, name) {
60701
60701
  }
60702
60702
  return target;
60703
60703
  }
60704
- async function pathExists7(path189) {
60704
+ async function pathExists7(path190) {
60705
60705
  try {
60706
- await access(path189);
60706
+ await access(path190);
60707
60707
  return true;
60708
60708
  } catch (error3) {
60709
60709
  if (isMissingFileError4(error3)) {
@@ -64100,9 +64100,9 @@ function normalizeToolResult2(handlerResult, outputSchema) {
64100
64100
  structuredContent
64101
64101
  };
64102
64102
  }
64103
- function assertObjectRootSchema(schema, path189) {
64103
+ function assertObjectRootSchema(schema, path190) {
64104
64104
  if (schema.type !== "object") {
64105
- throw new Error(`${path189} root type must be "object"`);
64105
+ throw new Error(`${path190} root type must be "object"`);
64106
64106
  }
64107
64107
  }
64108
64108
  function isJsonObject(value) {
@@ -64441,23 +64441,23 @@ function extractFieldErrors(body) {
64441
64441
  const flattened = candidates.flatMap((candidate) => flattenFieldErrors(candidate, []));
64442
64442
  return flattened.length === 0 ? void 0 : flattened;
64443
64443
  }
64444
- function flattenFieldErrors(value, path189) {
64444
+ function flattenFieldErrors(value, path190) {
64445
64445
  if (typeof value === "string") {
64446
- return [{ path: formatPath2(path189), message: value }];
64446
+ return [{ path: formatPath2(path190), message: value }];
64447
64447
  }
64448
64448
  if (Array.isArray(value)) {
64449
64449
  if (value.every((entry) => typeof entry === "string")) {
64450
- return value.map((message2) => ({ path: formatPath2(path189), message: message2 }));
64450
+ return value.map((message2) => ({ path: formatPath2(path190), message: message2 }));
64451
64451
  }
64452
- return value.flatMap((entry, index) => flattenFieldErrors(entry, [...path189, String(index)]));
64452
+ return value.flatMap((entry, index) => flattenFieldErrors(entry, [...path190, String(index)]));
64453
64453
  }
64454
64454
  if (!isPlainObject4(value)) {
64455
64455
  return [];
64456
64456
  }
64457
- return Object.entries(value).flatMap(([key3, nested]) => flattenFieldErrors(nested, [...path189, key3]));
64457
+ return Object.entries(value).flatMap(([key3, nested]) => flattenFieldErrors(nested, [...path190, key3]));
64458
64458
  }
64459
- function formatPath2(path189) {
64460
- return path189.length === 0 ? "error" : path189.join(".");
64459
+ function formatPath2(path190) {
64460
+ return path190.length === 0 ? "error" : path190.join(".");
64461
64461
  }
64462
64462
  function extractFirstString(body, fields) {
64463
64463
  if (!isPlainObject4(body)) {
@@ -64999,12 +64999,12 @@ function mergeApprovalsRoot(root, options) {
64999
64999
  }
65000
65000
  return options.humanInLoop.mergeApprovalsGroup(root);
65001
65001
  }
65002
- function findHumanInLoopCommandPath(node, path189) {
65002
+ function findHumanInLoopCommandPath(node, path190) {
65003
65003
  if (node.kind === "command") {
65004
- return node.humanInLoop ? path189.join(".") || node.name : void 0;
65004
+ return node.humanInLoop ? path190.join(".") || node.name : void 0;
65005
65005
  }
65006
65006
  for (const child of node.children) {
65007
- const found = findHumanInLoopCommandPath(child, [...path189, child.name]);
65007
+ const found = findHumanInLoopCommandPath(child, [...path190, child.name]);
65008
65008
  if (found !== void 0) {
65009
65009
  return found;
65010
65010
  }
@@ -65039,13 +65039,13 @@ function convertJsonSchema(schema) {
65039
65039
  }
65040
65040
  return convertSchema(schema, schema, []);
65041
65041
  }
65042
- function convertSchema(schema, root, path189) {
65043
- const resolvedSchema = resolveReferencedSchema(schema, root, path189);
65042
+ function convertSchema(schema, root, path190) {
65043
+ const resolvedSchema = resolveReferencedSchema(schema, root, path190);
65044
65044
  const normalizedSchema = normalizeNullability(resolvedSchema);
65045
65045
  const composition = getComposition(normalizedSchema.schema);
65046
65046
  if (Array.isArray(normalizedSchema.schema.type)) {
65047
65047
  throw new Error(
65048
- `JSON Schema "${formatJsonSchemaPath(path189)}" has an unsupported type "${formatJsonSchemaType(
65048
+ `JSON Schema "${formatJsonSchemaPath(path190)}" has an unsupported type "${formatJsonSchemaType(
65049
65049
  normalizedSchema.schema.type
65050
65050
  )}". Supported: string, number, integer, boolean, array, object.`
65051
65051
  );
@@ -65057,13 +65057,13 @@ function convertSchema(schema, root, path189) {
65057
65057
  return convertEnumSchema(resolvedSchema, normalizedSchema.nullable);
65058
65058
  }
65059
65059
  if (composition !== void 0) {
65060
- return convertCompositionSchema(normalizedSchema.schema, root, normalizedSchema.nullable, path189);
65060
+ return convertCompositionSchema(normalizedSchema.schema, root, normalizedSchema.nullable, path190);
65061
65061
  }
65062
65062
  if (isRecordSchema(normalizedSchema.schema)) {
65063
65063
  return applyMetadata(
65064
65064
  S.Record(
65065
65065
  convertSchema(normalizedSchema.schema.additionalProperties, root, [
65066
- ...path189,
65066
+ ...path190,
65067
65067
  "additionalProperties"
65068
65068
  ])
65069
65069
  ),
@@ -65112,12 +65112,12 @@ function convertSchema(schema, root, path189) {
65112
65112
  if (normalizedSchema.schema.items === void 0) {
65113
65113
  throw new Error(
65114
65114
  `JSON Schema "${formatJsonSchemaPath(
65115
- path189
65115
+ path190
65116
65116
  )}" is an array but is missing the "items" field. Add "items": { ... } to declare the element type.`
65117
65117
  );
65118
65118
  }
65119
65119
  return S.Array(
65120
- convertSchema(normalizedSchema.schema.items, root, [...path189, "items"]),
65120
+ convertSchema(normalizedSchema.schema.items, root, [...path190, "items"]),
65121
65121
  createCommonOptions(
65122
65122
  normalizedSchema.schema,
65123
65123
  normalizedSchema.nullable,
@@ -65127,7 +65127,7 @@ function convertSchema(schema, root, path189) {
65127
65127
  case "object":
65128
65128
  return convertObjectSchema(normalizedSchema.schema, root, {
65129
65129
  nullable: normalizedSchema.nullable,
65130
- path: path189
65130
+ path: path190
65131
65131
  });
65132
65132
  case "null":
65133
65133
  return applyMetadata(S.Json(), normalizedSchema.schema, {
@@ -65142,12 +65142,12 @@ function convertSchema(schema, root, path189) {
65142
65142
  }
65143
65143
  throw new Error(
65144
65144
  `JSON Schema "${formatJsonSchemaPath(
65145
- path189
65145
+ path190
65146
65146
  )}" must declare one of: "type", "enum", "const", "oneOf", "anyOf", or "allOf".`
65147
65147
  );
65148
65148
  }
65149
65149
  throw new Error(
65150
- `JSON Schema "${formatJsonSchemaPath(path189)}" has an unsupported type "${formatJsonSchemaType(
65150
+ `JSON Schema "${formatJsonSchemaPath(path190)}" has an unsupported type "${formatJsonSchemaType(
65151
65151
  normalizedSchema.schema.type
65152
65152
  )}". Supported: string, number, integer, boolean, array, object.`
65153
65153
  );
@@ -65191,21 +65191,21 @@ function convertEnumSchema(schema, nullable) {
65191
65191
  )
65192
65192
  });
65193
65193
  }
65194
- function convertCompositionSchema(schema, root, nullable, path189) {
65194
+ function convertCompositionSchema(schema, root, nullable, path190) {
65195
65195
  const composition = getComposition(schema);
65196
65196
  const branchSchemas = composition?.branches ?? [];
65197
65197
  const keyword = composition?.keyword ?? "oneOf";
65198
65198
  const branches = branchSchemas.map(
65199
- (branch, index) => resolveReferencedSchema(branch, root, [...path189, keyword, String(index)])
65199
+ (branch, index) => resolveReferencedSchema(branch, root, [...path190, keyword, String(index)])
65200
65200
  );
65201
- const discriminator = findDiscriminator(branches, root, path189);
65201
+ const discriminator = findDiscriminator(branches, root, path190);
65202
65202
  if (discriminator !== void 0) {
65203
65203
  const convertedBranches = Object.fromEntries(
65204
65204
  branches.map((branch, index) => [
65205
65205
  getDiscriminatorLiteral(branch, discriminator, root),
65206
65206
  convertObjectSchema(branch, root, {
65207
65207
  omitProperty: discriminator,
65208
- path: [...path189, keyword, String(index)]
65208
+ path: [...path190, keyword, String(index)]
65209
65209
  })
65210
65210
  ])
65211
65211
  );
@@ -65224,7 +65224,7 @@ function convertCompositionSchema(schema, root, nullable, path189) {
65224
65224
  S.Union(
65225
65225
  branches.map(
65226
65226
  (branch, index) => convertObjectSchema(branch, root, {
65227
- path: [...path189, keyword, String(index)]
65227
+ path: [...path190, keyword, String(index)]
65228
65228
  })
65229
65229
  )
65230
65230
  ),
@@ -65338,11 +65338,11 @@ function getComposition(schema) {
65338
65338
  }
65339
65339
  return void 0;
65340
65340
  }
65341
- function formatJsonSchemaPath(path189) {
65342
- if (path189.length === 0) {
65341
+ function formatJsonSchemaPath(path190) {
65342
+ if (path190.length === 0) {
65343
65343
  return "#";
65344
65344
  }
65345
- return `#/${path189.map(escapeJsonPointerSegment).join("/")}`;
65345
+ return `#/${path190.map(escapeJsonPointerSegment).join("/")}`;
65346
65346
  }
65347
65347
  function formatJsonSchemaType(type) {
65348
65348
  return Array.isArray(type) ? JSON.stringify(type) : String(type);
@@ -65358,11 +65358,11 @@ function isRecordSchema(schema) {
65358
65358
  const propertyKeys = Object.keys(schema.properties ?? {});
65359
65359
  return schema.type === "object" && propertyKeys.length === 0 && typeof schema.additionalProperties === "object" && schema.additionalProperties !== null;
65360
65360
  }
65361
- function findDiscriminator(branches, root, path189) {
65361
+ function findDiscriminator(branches, root, path190) {
65362
65362
  const [firstBranch] = branches;
65363
65363
  if (firstBranch === void 0) {
65364
65364
  throw new Error(
65365
- `JSON Schema "${formatJsonSchemaPath(path189)}" uses oneOf/anyOf/allOf but has no branches.`
65365
+ `JSON Schema "${formatJsonSchemaPath(path190)}" uses oneOf/anyOf/allOf but has no branches.`
65366
65366
  );
65367
65367
  }
65368
65368
  const candidateKeys = Object.keys(firstBranch.properties ?? {});
@@ -65402,19 +65402,19 @@ function getDiscriminatorLiteral(branch, key3, root) {
65402
65402
  }
65403
65403
  return void 0;
65404
65404
  }
65405
- function resolveReferencedSchema(schema, root, path189) {
65405
+ function resolveReferencedSchema(schema, root, path190) {
65406
65406
  if (schema.$ref === void 0) {
65407
65407
  return schema;
65408
65408
  }
65409
65409
  const resolvedTarget = resolveLocalRef(root, schema.$ref);
65410
65410
  if (resolvedTarget === void 0) {
65411
65411
  throw new Error(
65412
- `JSON Schema "${formatJsonSchemaPath(path189)}" uses "$ref": ${schema.$ref}. toolcraft only supports internal refs like "#/components/schemas/Foo".`
65412
+ `JSON Schema "${formatJsonSchemaPath(path190)}" uses "$ref": ${schema.$ref}. toolcraft only supports internal refs like "#/components/schemas/Foo".`
65413
65413
  );
65414
65414
  }
65415
65415
  const { $ref: ignoredRef, ...siblingKeywords } = schema;
65416
65416
  void ignoredRef;
65417
- const resolvedSchema = resolveReferencedSchema(resolvedTarget, root, path189);
65417
+ const resolvedSchema = resolveReferencedSchema(resolvedTarget, root, path190);
65418
65418
  if (Object.keys(siblingKeywords).length === 0) {
65419
65419
  return resolvedSchema;
65420
65420
  }
@@ -65438,9 +65438,9 @@ function mergeJsonSchemas(base, overlay) {
65438
65438
  ...mergedRequired === void 0 ? {} : { required: mergedRequired }
65439
65439
  };
65440
65440
  }
65441
- function hasSelfReferencingRef(schema, root, path189 = "#", activePaths = /* @__PURE__ */ new Set()) {
65441
+ function hasSelfReferencingRef(schema, root, path190 = "#", activePaths = /* @__PURE__ */ new Set()) {
65442
65442
  const nextActivePaths = new Set(activePaths);
65443
- nextActivePaths.add(path189);
65443
+ nextActivePaths.add(path190);
65444
65444
  const localRefPath = getLocalRefPath(schema.$ref);
65445
65445
  if (localRefPath !== void 0) {
65446
65446
  if (nextActivePaths.has(localRefPath)) {
@@ -65451,13 +65451,13 @@ function hasSelfReferencingRef(schema, root, path189 = "#", activePaths = /* @__
65451
65451
  return true;
65452
65452
  }
65453
65453
  }
65454
- if (schema.items !== void 0 && hasSelfReferencingRef(schema.items, root, `${path189}/items`, nextActivePaths)) {
65454
+ if (schema.items !== void 0 && hasSelfReferencingRef(schema.items, root, `${path190}/items`, nextActivePaths)) {
65455
65455
  return true;
65456
65456
  }
65457
65457
  if (typeof schema.additionalProperties === "object" && schema.additionalProperties !== null && hasSelfReferencingRef(
65458
65458
  schema.additionalProperties,
65459
65459
  root,
65460
- `${path189}/additionalProperties`,
65460
+ `${path190}/additionalProperties`,
65461
65461
  nextActivePaths
65462
65462
  )) {
65463
65463
  return true;
@@ -65466,7 +65466,7 @@ function hasSelfReferencingRef(schema, root, path189 = "#", activePaths = /* @__
65466
65466
  if (hasSelfReferencingRef(
65467
65467
  childSchema,
65468
65468
  root,
65469
- `${path189}/properties/${escapeJsonPointerSegment(key3)}`,
65469
+ `${path190}/properties/${escapeJsonPointerSegment(key3)}`,
65470
65470
  nextActivePaths
65471
65471
  )) {
65472
65472
  return true;
@@ -65476,24 +65476,24 @@ function hasSelfReferencingRef(schema, root, path189 = "#", activePaths = /* @__
65476
65476
  if (hasSelfReferencingRef(
65477
65477
  childSchema,
65478
65478
  root,
65479
- `${path189}/$defs/${escapeJsonPointerSegment(key3)}`,
65479
+ `${path190}/$defs/${escapeJsonPointerSegment(key3)}`,
65480
65480
  nextActivePaths
65481
65481
  )) {
65482
65482
  return true;
65483
65483
  }
65484
65484
  }
65485
65485
  for (const [index, childSchema] of (schema.oneOf ?? []).entries()) {
65486
- if (hasSelfReferencingRef(childSchema, root, `${path189}/oneOf/${index}`, nextActivePaths)) {
65486
+ if (hasSelfReferencingRef(childSchema, root, `${path190}/oneOf/${index}`, nextActivePaths)) {
65487
65487
  return true;
65488
65488
  }
65489
65489
  }
65490
65490
  for (const [index, childSchema] of (schema.anyOf ?? []).entries()) {
65491
- if (hasSelfReferencingRef(childSchema, root, `${path189}/anyOf/${index}`, nextActivePaths)) {
65491
+ if (hasSelfReferencingRef(childSchema, root, `${path190}/anyOf/${index}`, nextActivePaths)) {
65492
65492
  return true;
65493
65493
  }
65494
65494
  }
65495
65495
  for (const [index, childSchema] of (schema.allOf ?? []).entries()) {
65496
- if (hasSelfReferencingRef(childSchema, root, `${path189}/allOf/${index}`, nextActivePaths)) {
65496
+ if (hasSelfReferencingRef(childSchema, root, `${path190}/allOf/${index}`, nextActivePaths)) {
65497
65497
  return true;
65498
65498
  }
65499
65499
  }
@@ -65509,14 +65509,14 @@ function getLocalRefPath(ref) {
65509
65509
  return ref.startsWith("#/") ? ref : void 0;
65510
65510
  }
65511
65511
  function resolveLocalRef(root, ref) {
65512
- const path189 = getLocalRefPath(ref);
65513
- if (path189 === void 0) {
65512
+ const path190 = getLocalRefPath(ref);
65513
+ if (path190 === void 0) {
65514
65514
  return void 0;
65515
65515
  }
65516
- if (path189 === "#") {
65516
+ if (path190 === "#") {
65517
65517
  return root;
65518
65518
  }
65519
- const segments = path189.slice(2).split("/").map(unescapeJsonPointerSegment);
65519
+ const segments = path190.slice(2).split("/").map(unescapeJsonPointerSegment);
65520
65520
  let current = root;
65521
65521
  for (const segment of segments) {
65522
65522
  if (Array.isArray(current)) {
@@ -66269,21 +66269,21 @@ function createFs(fs31) {
66269
66269
  return fs31;
66270
66270
  }
66271
66271
  return {
66272
- readFile: async (path189, encoding = "utf8") => readFile13(path189, { encoding }),
66273
- writeFile: async (path189, contents, options) => {
66274
- await writeFile9(path189, contents, options);
66272
+ readFile: async (path190, encoding = "utf8") => readFile13(path190, { encoding }),
66273
+ writeFile: async (path190, contents, options) => {
66274
+ await writeFile9(path190, contents, options);
66275
66275
  },
66276
- exists: async (path189) => {
66276
+ exists: async (path190) => {
66277
66277
  try {
66278
- await access2(path189);
66278
+ await access2(path190);
66279
66279
  return true;
66280
66280
  } catch {
66281
66281
  return false;
66282
66282
  }
66283
66283
  },
66284
- lstat: async (path189) => lstat12(path189),
66284
+ lstat: async (path190) => lstat12(path190),
66285
66285
  rename: async (fromPath, toPath) => rename10(fromPath, toPath),
66286
- unlink: async (path189) => unlink9(path189)
66286
+ unlink: async (path190) => unlink9(path190)
66287
66287
  };
66288
66288
  }
66289
66289
  function createEnv(values = process.env) {
@@ -66421,11 +66421,11 @@ function applySchemaCasing(schema, casing) {
66421
66421
  ...oneOf === void 0 ? {} : { oneOf }
66422
66422
  };
66423
66423
  }
66424
- function collectParamSummaries(schema, casing, path189 = [], inheritedOptional = false) {
66424
+ function collectParamSummaries(schema, casing, path190 = [], inheritedOptional = false) {
66425
66425
  const summaries = [];
66426
66426
  for (const [key3, rawChildSchema] of Object.entries(schema.shape)) {
66427
66427
  const childSchema = unwrapOptional3(rawChildSchema);
66428
- const nextPath = [...path189, formatSegment(key3, casing)];
66428
+ const nextPath = [...path190, formatSegment(key3, casing)];
66429
66429
  const optional = inheritedOptional || isOptional(rawChildSchema);
66430
66430
  if (childSchema.kind === "object") {
66431
66431
  summaries.push(...collectParamSummaries(childSchema, casing, nextPath, optional));
@@ -66469,8 +66469,8 @@ function matchesAllowlist(toolName, allowlist) {
66469
66469
  const candidates = segments.map((_segment, index) => segments.slice(0, index + 1).join("__"));
66470
66470
  return candidates.some((candidate) => allowlist.includes(candidate));
66471
66471
  }
66472
- function formatToolName(path189) {
66473
- return path189.map((segment) => formatSegment(segment, "snake")).join("__");
66472
+ function formatToolName(path190) {
66473
+ return path190.map((segment) => formatSegment(segment, "snake")).join("__");
66474
66474
  }
66475
66475
  function validateUniqueMCPParameterFields(schema, casing) {
66476
66476
  const sourceKeysByField = /* @__PURE__ */ new Map();
@@ -69066,14 +69066,14 @@ function parseDockerLocator(input) {
69066
69066
  throw new Error(`Invalid docker workspace locator "${input}".`);
69067
69067
  }
69068
69068
  const container = input.slice(0, slashIndex);
69069
- const path189 = input.slice(slashIndex);
69070
- if (container.length === 0 || path189.length === 0) {
69069
+ const path190 = input.slice(slashIndex);
69070
+ if (container.length === 0 || path190.length === 0) {
69071
69071
  throw new Error(`Invalid docker workspace locator "${input}".`);
69072
69072
  }
69073
69073
  return {
69074
69074
  scheme: "docker",
69075
69075
  container,
69076
- path: path189
69076
+ path: path190
69077
69077
  };
69078
69078
  }
69079
69079
  function splitOnce(input, separator) {
@@ -69937,8 +69937,8 @@ async function checkAuth(options) {
69937
69937
  }
69938
69938
  function createCurrentBalanceUrl(baseUrl) {
69939
69939
  const url = new URL(baseUrl);
69940
- const path189 = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
69941
- url.pathname = `${path189}/usage/current_balance`;
69940
+ const path190 = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
69941
+ url.pathname = `${path190}/usage/current_balance`;
69942
69942
  return url.toString();
69943
69943
  }
69944
69944
  function isCurrentBalanceResponse(value) {
@@ -71404,26 +71404,26 @@ function createSdkContainer(options) {
71404
71404
  });
71405
71405
  loggerFactory.setErrorLogger(errorLogger);
71406
71406
  const asyncFs = {
71407
- readFile: ((path189, encoding) => {
71407
+ readFile: ((path190, encoding) => {
71408
71408
  if (encoding) {
71409
- return fs9.readFile(path189, encoding);
71409
+ return fs9.readFile(path190, encoding);
71410
71410
  }
71411
- return fs9.readFile(path189);
71411
+ return fs9.readFile(path190);
71412
71412
  }),
71413
- symlink: (target, path189) => fs9.symlink(target, path189),
71414
- readlink: (path189) => fs9.readlink(path189, { encoding: "utf8" }),
71415
- realpath: (path189) => fs9.realpath(path189),
71416
- writeFile: (path189, data, opts) => fs9.writeFile(path189, data, opts),
71417
- mkdir: (path189, opts) => fs9.mkdir(path189, opts).then(() => {
71413
+ symlink: (target, path190) => fs9.symlink(target, path190),
71414
+ readlink: (path190) => fs9.readlink(path190, { encoding: "utf8" }),
71415
+ realpath: (path190) => fs9.realpath(path190),
71416
+ writeFile: (path190, data, opts) => fs9.writeFile(path190, data, opts),
71417
+ mkdir: (path190, opts) => fs9.mkdir(path190, opts).then(() => {
71418
71418
  }),
71419
- stat: (path189) => fs9.stat(path189),
71420
- lstat: (path189) => fs9.lstat(path189),
71419
+ stat: (path190) => fs9.stat(path190),
71420
+ lstat: (path190) => fs9.lstat(path190),
71421
71421
  rename: (oldPath, newPath) => fs9.rename(oldPath, newPath),
71422
- rm: (path189, opts) => fs9.rm(path189, opts),
71423
- unlink: (path189) => fs9.unlink(path189),
71424
- readdir: (path189) => fs9.readdir(path189),
71422
+ rm: (path190, opts) => fs9.rm(path190, opts),
71423
+ unlink: (path190) => fs9.unlink(path190),
71424
+ readdir: (path190) => fs9.readdir(path190),
71425
71425
  copyFile: (src, dest) => fs9.copyFile(src, dest),
71426
- chmod: (path189, mode) => fs9.chmod(path189, mode)
71426
+ chmod: (path190, mode) => fs9.chmod(path190, mode)
71427
71427
  };
71428
71428
  const contextFactory = createCommandContextFactory({ fs: asyncFs });
71429
71429
  const authProviders = allAuthProviders;
@@ -71878,8 +71878,8 @@ function createNodeWorktreeDeps2() {
71878
71878
  };
71879
71879
  }
71880
71880
  async function defaultSpawnAgent(service, options) {
71881
- const { spawn: spawn11 } = await init_spawn4().then(() => spawn_exports);
71882
- return await spawn11(service, options).result;
71881
+ const { spawn: spawn12 } = await init_spawn4().then(() => spawn_exports);
71882
+ return await spawn12(service, options).result;
71883
71883
  }
71884
71884
  var execShell2;
71885
71885
  var init_worktree = __esm({
@@ -86847,7 +86847,7 @@ async function ingestGaslight(options) {
86847
86847
  const cwd = options.cwd ?? process.cwd();
86848
86848
  const homeDir = options.homeDir ?? os17.homedir();
86849
86849
  const fs31 = options.fs ?? nodeFs14;
86850
- const spawn11 = options.spawn ?? spawn4;
86850
+ const spawn12 = options.spawn ?? spawn4;
86851
86851
  const collectHumanPrompts2 = options.collectHumanPrompts ?? collectHumanPromptsWithStats;
86852
86852
  const analysisAgent = requireNonEmptyString3(options.analysisAgent, "analysisAgent");
86853
86853
  const model = resolveOptionalNonEmptyString(options.model, "model");
@@ -86890,7 +86890,7 @@ async function ingestGaslight(options) {
86890
86890
  agent: analysisAgent,
86891
86891
  dataPath: dataPath.absolutePath
86892
86892
  });
86893
- const result = await spawn11(analysisAgent, {
86893
+ const result = await spawn12(analysisAgent, {
86894
86894
  prompt: buildAnalysisPrompt(dataPath.absolutePath),
86895
86895
  cwd,
86896
86896
  mode: "read",
@@ -87092,7 +87092,7 @@ async function runGaslight(options) {
87092
87092
  const cwd = options.cwd ?? process.cwd();
87093
87093
  const homeDir = options.homeDir ?? os18.homedir();
87094
87094
  const fs31 = options.fs ?? nodeFs15;
87095
- const spawn11 = options.spawn ?? spawn4;
87095
+ const spawn12 = options.spawn ?? spawn4;
87096
87096
  const model = resolveModel(options.model);
87097
87097
  const mode = options.mode ?? "auto";
87098
87098
  const inlineSetup = resolveOptionalPrompt(options.setup, "setup");
@@ -87137,7 +87137,7 @@ async function runGaslight(options) {
87137
87137
  planIndex: planIndex + 1,
87138
87138
  totalPlans: planPaths.length
87139
87139
  });
87140
- const result = await spawn11(agent3, {
87140
+ const result = await spawn12(agent3, {
87141
87141
  prompt,
87142
87142
  cwd,
87143
87143
  mode,
@@ -88043,15 +88043,15 @@ async function publishFiles(fs31, files) {
88043
88043
  function isAlreadyExistsError12(error3) {
88044
88044
  return hasOwnErrorCode24(error3, "EEXIST");
88045
88045
  }
88046
- async function assertNotSymbolicLinkIfSet(fs31, path189) {
88047
- if (path189 !== void 0 && path189 !== "") {
88048
- await assertNotSymbolicLink2(fs31, path189);
88046
+ async function assertNotSymbolicLinkIfSet(fs31, path190) {
88047
+ if (path190 !== void 0 && path190 !== "") {
88048
+ await assertNotSymbolicLink2(fs31, path190);
88049
88049
  }
88050
88050
  }
88051
- async function assertNotSymbolicLink2(fs31, path189) {
88051
+ async function assertNotSymbolicLink2(fs31, path190) {
88052
88052
  try {
88053
- if ((await fs31.lstat(path189)).isSymbolicLink()) {
88054
- throw new UserError2(`Refusing to use symbolic link path: ${path189}`);
88053
+ if ((await fs31.lstat(path190)).isSymbolicLink()) {
88054
+ throw new UserError2(`Refusing to use symbolic link path: ${path190}`);
88055
88055
  }
88056
88056
  } catch (error3) {
88057
88057
  if (isMissingFileError8(error3)) {
@@ -89459,12 +89459,12 @@ function validateNonBlankStrings(value) {
89459
89459
  }
89460
89460
  return issues;
89461
89461
  }
89462
- function blankStringIssue(path189, value) {
89462
+ function blankStringIssue(path190, value) {
89463
89463
  return {
89464
- path: path189,
89464
+ path: path190,
89465
89465
  expected: "non-blank string",
89466
89466
  received: JSON.stringify(value),
89467
- message: `${path189.join(".")} must not be blank.`
89467
+ message: `${path190.join(".")} must not be blank.`
89468
89468
  };
89469
89469
  }
89470
89470
  function validateTarget(target) {
@@ -89515,8 +89515,8 @@ function validateMetrics(metrics) {
89515
89515
  function formatIssues2(filePath, issues) {
89516
89516
  return issues.map((issue2) => `${filePath} (${formatPath3(issue2.path)}): ${issue2.message}`).join("\n");
89517
89517
  }
89518
- function formatPath3(path189) {
89519
- return path189.join(".") || "value";
89518
+ function formatPath3(path190) {
89519
+ return path190.join(".") || "value";
89520
89520
  }
89521
89521
  var nonEmptyString2, positiveInteger, nonNegativeInteger, scoringWeight, metricEvaluatorSchema, metricSchema, evalYamlSchema, EvalYamlValidationError;
89522
89522
  var init_schema5 = __esm({
@@ -89920,9 +89920,9 @@ async function loadEval(source, id, fs31 = nodeFs17) {
89920
89920
  plan
89921
89921
  };
89922
89922
  }
89923
- async function isFile2(path189, fs31) {
89923
+ async function isFile2(path190, fs31) {
89924
89924
  try {
89925
- const stat36 = await fs31.stat(path189);
89925
+ const stat36 = await fs31.stat(path190);
89926
89926
  return typeof stat36.isFile === "function" ? stat36.isFile() : !stat36.isDirectory();
89927
89927
  } catch (error3) {
89928
89928
  if (isMissingPath4(error3)) {
@@ -91805,19 +91805,19 @@ function validateRunResult(value, filePath) {
91805
91805
  requireRecord2(result.cheatReport, filePath, "result.json", ["cheatReport"]);
91806
91806
  return result;
91807
91807
  }
91808
- function validateScoringComponent(value, filePath, path189) {
91809
- const component = requireRecord2(value, filePath, "result.json", path189);
91810
- requireBoolean(component.configured, filePath, "result.json", [...path189, "configured"]);
91811
- requireBoolean(component.required, filePath, "result.json", [...path189, "required"]);
91808
+ function validateScoringComponent(value, filePath, path190) {
91809
+ const component = requireRecord2(value, filePath, "result.json", path190);
91810
+ requireBoolean(component.configured, filePath, "result.json", [...path190, "configured"]);
91811
+ requireBoolean(component.required, filePath, "result.json", [...path190, "required"]);
91812
91812
  requireRange(component.configuredWeight, 0, 1, filePath, "result.json", [
91813
- ...path189,
91813
+ ...path190,
91814
91814
  "configuredWeight"
91815
91815
  ]);
91816
91816
  requireRange(component.effectiveWeight, 0, 1, filePath, "result.json", [
91817
- ...path189,
91817
+ ...path190,
91818
91818
  "effectiveWeight"
91819
91819
  ]);
91820
- requireString(component.status, filePath, "result.json", [...path189, "status"]);
91820
+ requireString(component.status, filePath, "result.json", [...path190, "status"]);
91821
91821
  }
91822
91822
  function validateTrace(value, filePath) {
91823
91823
  const trace = requireRecord2(value, filePath, "trace.json", []);
@@ -91826,48 +91826,48 @@ function validateTrace(value, filePath) {
91826
91826
  }
91827
91827
  return trace;
91828
91828
  }
91829
- function requireRecord2(value, filePath, artifact, path189) {
91829
+ function requireRecord2(value, filePath, artifact, path190) {
91830
91830
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
91831
91831
  return value;
91832
91832
  }
91833
- throw invalidArtifactField(filePath, artifact, path189, "object", value);
91833
+ throw invalidArtifactField(filePath, artifact, path190, "object", value);
91834
91834
  }
91835
- function requireString(value, filePath, artifact, path189) {
91835
+ function requireString(value, filePath, artifact, path190) {
91836
91836
  if (typeof value === "string" && value.length > 0) {
91837
91837
  return value;
91838
91838
  }
91839
- throw invalidArtifactField(filePath, artifact, path189, "non-empty string", value);
91839
+ throw invalidArtifactField(filePath, artifact, path190, "non-empty string", value);
91840
91840
  }
91841
- function requireBoolean(value, filePath, artifact, path189) {
91841
+ function requireBoolean(value, filePath, artifact, path190) {
91842
91842
  if (typeof value !== "boolean") {
91843
- throw invalidArtifactField(filePath, artifact, path189, "boolean", value);
91843
+ throw invalidArtifactField(filePath, artifact, path190, "boolean", value);
91844
91844
  }
91845
91845
  }
91846
- function requireNonNegativeInteger2(value, filePath, artifact, path189) {
91846
+ function requireNonNegativeInteger2(value, filePath, artifact, path190) {
91847
91847
  if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
91848
91848
  return value;
91849
91849
  }
91850
- throw invalidArtifactField(filePath, artifact, path189, "non-negative integer", value);
91850
+ throw invalidArtifactField(filePath, artifact, path190, "non-negative integer", value);
91851
91851
  }
91852
- function requireNonNegativeNumber(value, filePath, artifact, path189) {
91852
+ function requireNonNegativeNumber(value, filePath, artifact, path190) {
91853
91853
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
91854
91854
  return value;
91855
91855
  }
91856
- throw invalidArtifactField(filePath, artifact, path189, "non-negative number", value);
91856
+ throw invalidArtifactField(filePath, artifact, path190, "non-negative number", value);
91857
91857
  }
91858
- function requireRange(value, min, max, filePath, artifact, path189) {
91858
+ function requireRange(value, min, max, filePath, artifact, path190) {
91859
91859
  if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) {
91860
91860
  return;
91861
91861
  }
91862
- throw invalidArtifactField(filePath, artifact, path189, `number from ${min} through ${max}`, value);
91862
+ throw invalidArtifactField(filePath, artifact, path190, `number from ${min} through ${max}`, value);
91863
91863
  }
91864
- function invalidArtifactField(filePath, artifact, path189, expected, received) {
91864
+ function invalidArtifactField(filePath, artifact, path190, expected, received) {
91865
91865
  return new Error(
91866
- `Invalid ${artifact} in ${filePath} (${formatIssuePath(path189)}): expected ${expected}, received ${formatReceived2(received)}.`
91866
+ `Invalid ${artifact} in ${filePath} (${formatIssuePath(path190)}): expected ${expected}, received ${formatReceived2(received)}.`
91867
91867
  );
91868
91868
  }
91869
- function formatIssuePath(path189) {
91870
- return path189.join(".") || "value";
91869
+ function formatIssuePath(path190) {
91870
+ return path190.join(".") || "value";
91871
91871
  }
91872
91872
  function formatReceived2(value) {
91873
91873
  if (typeof value === "string") {
@@ -96660,11 +96660,11 @@ function formatSegment2(segment, casing) {
96660
96660
  const separator = casing === "snake" ? "_" : "-";
96661
96661
  return splitWords4(segment).join(separator);
96662
96662
  }
96663
- function toOptionFlag(path189, casing) {
96664
- return `--${path189.map((segment) => formatSegment2(segment, casing)).join(".")}`;
96663
+ function toOptionFlag(path190, casing) {
96664
+ return `--${path190.map((segment) => formatSegment2(segment, casing)).join(".")}`;
96665
96665
  }
96666
- function toOptionAttribute(path189, casing) {
96667
- return path189.map((segment) => {
96666
+ function toOptionAttribute(path190, casing) {
96667
+ return path190.map((segment) => {
96668
96668
  const formatted = formatSegment2(segment, casing);
96669
96669
  if (casing === "snake") {
96670
96670
  return formatted;
@@ -96675,23 +96675,23 @@ function toOptionAttribute(path189, casing) {
96675
96675
  ).join("");
96676
96676
  }).join(".");
96677
96677
  }
96678
- function toDisplayPath(path189) {
96679
- return path189.join(".");
96678
+ function toDisplayPath(path190) {
96679
+ return path190.join(".");
96680
96680
  }
96681
- function toUnionKindControlPath(path189) {
96682
- if (path189.length === 0) {
96681
+ function toUnionKindControlPath(path190) {
96682
+ if (path190.length === 0) {
96683
96683
  return ["kind"];
96684
96684
  }
96685
- const head = path189.slice(0, -1);
96686
- const tail = path189[path189.length - 1] ?? "";
96685
+ const head = path190.slice(0, -1);
96686
+ const tail = path190[path190.length - 1] ?? "";
96687
96687
  return [...head, `${tail}Kind`];
96688
96688
  }
96689
- function toUnionKindDisplayPath(path189) {
96690
- if (path189.length === 0) {
96689
+ function toUnionKindDisplayPath(path190) {
96690
+ if (path190.length === 0) {
96691
96691
  return "kind";
96692
96692
  }
96693
- const head = path189.slice(0, -1);
96694
- const tail = path189[path189.length - 1] ?? "";
96693
+ const head = path190.slice(0, -1);
96694
+ const tail = path190[path190.length - 1] ?? "";
96695
96695
  return [...head, `${tail}-kind`].join(".");
96696
96696
  }
96697
96697
  function createSyntheticEnumSchema(values) {
@@ -96707,14 +96707,14 @@ function getRequiredBranchFingerprint(branch, casing) {
96707
96707
  const requiredKeys = Object.entries(branch.shape).filter(([, schema]) => schema.kind !== "optional").map(([key3]) => formatSegment2(key3, casing)).sort();
96708
96708
  return requiredKeys.join("+");
96709
96709
  }
96710
- function collectFields(schema, casing, globalLongOptionFlags, path189 = [], inheritedOptional = false, variantContext) {
96710
+ function collectFields(schema, casing, globalLongOptionFlags, path190 = [], inheritedOptional = false, variantContext) {
96711
96711
  const collected = {
96712
96712
  dynamicFields: [],
96713
96713
  fields: [],
96714
96714
  variants: []
96715
96715
  };
96716
96716
  for (const [key3, rawChildSchema] of Object.entries(schema.shape)) {
96717
- const nextPath = [...path189, key3];
96717
+ const nextPath = [...path190, key3];
96718
96718
  const runtimeOptional = inheritedOptional || rawChildSchema.kind === "optional";
96719
96719
  const childSchema = unwrapOptional4(rawChildSchema);
96720
96720
  const requiredWhenActive = rawChildSchema.kind !== "optional" && childSchema.default === void 0;
@@ -96900,9 +96900,9 @@ function collectFields(schema, casing, globalLongOptionFlags, path189 = [], inhe
96900
96900
  }
96901
96901
  return collected;
96902
96902
  }
96903
- function toCommanderOptionAttribute(path189, casing, globalLongOptionFlags) {
96904
- const optionAttribute = toOptionAttribute(path189, casing);
96905
- const optionFlag = toOptionFlag(path189, casing);
96903
+ function toCommanderOptionAttribute(path190, casing, globalLongOptionFlags) {
96904
+ const optionAttribute = toOptionAttribute(path190, casing);
96905
+ const optionFlag = toOptionFlag(path190, casing);
96906
96906
  if (!globalLongOptionFlags.has(optionFlag)) {
96907
96907
  return optionAttribute;
96908
96908
  }
@@ -98496,10 +98496,10 @@ function writeCLIDiagnosticEvent(event) {
98496
98496
  process.stderr.write(`${event.message}
98497
98497
  `);
98498
98498
  }
98499
- function setNestedValue(target, path189, value) {
98499
+ function setNestedValue(target, path190, value) {
98500
98500
  let cursor2 = target;
98501
- for (let index = 0; index < path189.length - 1; index += 1) {
98502
- const segment = path189[index] ?? "";
98501
+ for (let index = 0; index < path190.length - 1; index += 1) {
98502
+ const segment = path190[index] ?? "";
98503
98503
  const existing = Object.prototype.hasOwnProperty.call(cursor2, segment) ? cursor2[segment] : void 0;
98504
98504
  if (typeof existing === "object" && existing !== null) {
98505
98505
  cursor2 = existing;
@@ -98514,7 +98514,7 @@ function setNestedValue(target, path189, value) {
98514
98514
  });
98515
98515
  cursor2 = next;
98516
98516
  }
98517
- const leaf = path189[path189.length - 1];
98517
+ const leaf = path190[path190.length - 1];
98518
98518
  if (leaf !== void 0) {
98519
98519
  Object.defineProperty(cursor2, leaf, {
98520
98520
  value,
@@ -98696,9 +98696,9 @@ function isPlainObject8(value) {
98696
98696
  function hasFieldValue(value) {
98697
98697
  return value !== void 0;
98698
98698
  }
98699
- function hasNestedField(fields, path189) {
98699
+ function hasNestedField(fields, path190) {
98700
98700
  return fields.some(
98701
- (field) => path189.length < field.path.length && path189.every((segment, index) => field.path[index] === segment)
98701
+ (field) => path190.length < field.path.length && path190.every((segment, index) => field.path[index] === segment)
98702
98702
  );
98703
98703
  }
98704
98704
  function describeExpectedPresetValue(schema) {
@@ -98827,9 +98827,9 @@ async function loadPresetValues(fields, presetPath) {
98827
98827
  }
98828
98828
  const fieldByPath = new Map(fields.map((field) => [field.displayPath, field]));
98829
98829
  const presetValues = {};
98830
- function visitObject(current, path189) {
98830
+ function visitObject(current, path190) {
98831
98831
  for (const [key3, value] of Object.entries(current)) {
98832
- const nextPath = [...path189, key3];
98832
+ const nextPath = [...path190, key3];
98833
98833
  const displayPath = toDisplayPath(nextPath);
98834
98834
  const field = fieldByPath.get(displayPath);
98835
98835
  if (field !== void 0) {
@@ -99212,8 +99212,8 @@ This is a bug in toolcraft or in the command definition; it cannot be worked aro
99212
99212
  }
99213
99213
  process.exitCode = 1;
99214
99214
  }
99215
- function getNestedValue(target, path189) {
99216
- return path189.reduce(
99215
+ function getNestedValue(target, path190) {
99216
+ return path190.reduce(
99217
99217
  (current, segment) => current !== null && typeof current === "object" ? current[segment] : void 0,
99218
99218
  target
99219
99219
  );
@@ -101277,13 +101277,13 @@ function formatAvailableApprovalCommandPaths(root) {
101277
101277
  }
101278
101278
  function enumerateApprovalCommandPaths(root) {
101279
101279
  const paths = [];
101280
- const visit = (node, path189) => {
101280
+ const visit = (node, path190) => {
101281
101281
  if (node.kind === "command") {
101282
- paths.push(path189.join("."));
101282
+ paths.push(path190.join("."));
101283
101283
  return;
101284
101284
  }
101285
101285
  for (const child of getVisibleCliChildren(node)) {
101286
- visit(child, [...path189, child.name]);
101286
+ visit(child, [...path190, child.name]);
101287
101287
  }
101288
101288
  };
101289
101289
  if (root.kind === "command") {
@@ -105158,9 +105158,9 @@ var init_config8 = __esm({
105158
105158
 
105159
105159
  // src/cli/commands/utils-symlink-ops.ts
105160
105160
  import { dirname as dirname10 } from "node:path";
105161
- async function tryLstat(fs31, path189) {
105161
+ async function tryLstat(fs31, path190) {
105162
105162
  try {
105163
- return await fs31.lstat(path189);
105163
+ return await fs31.lstat(path190);
105164
105164
  } catch (error3) {
105165
105165
  if (isNotFound(error3)) {
105166
105166
  return null;
@@ -105244,13 +105244,13 @@ function formatUnknownError6(error3) {
105244
105244
  }
105245
105245
  return String(error3);
105246
105246
  }
105247
- async function isSymlinkPointingTo(fs31, path189, expectedTarget) {
105247
+ async function isSymlinkPointingTo(fs31, path190, expectedTarget) {
105248
105248
  try {
105249
- const stats2 = await fs31.lstat(path189);
105249
+ const stats2 = await fs31.lstat(path190);
105250
105250
  if (!stats2.isSymbolicLink()) {
105251
105251
  return false;
105252
105252
  }
105253
- return await fs31.readlink(path189) === expectedTarget;
105253
+ return await fs31.readlink(path190) === expectedTarget;
105254
105254
  } catch (error3) {
105255
105255
  if (isNotFound(error3)) {
105256
105256
  return false;
@@ -109721,28 +109721,28 @@ function detectTraceFile(firstLine) {
109721
109721
  }
109722
109722
  return void 0;
109723
109723
  }
109724
- async function loadTraceFromFile(path189, options) {
109725
- const stat36 = await options.fs.stat(path189).catch(() => void 0);
109724
+ async function loadTraceFromFile(path190, options) {
109725
+ const stat36 = await options.fs.stat(path190).catch(() => void 0);
109726
109726
  if (stat36 === void 0) {
109727
109727
  throw new UserError(
109728
- `Trace file not found: ${path189}
109728
+ `Trace file not found: ${path190}
109729
109729
  Pass a path to an existing trace file, or run "poe-code traces" to list the traces found.`
109730
109730
  );
109731
109731
  }
109732
109732
  if (stat36.isDirectory()) {
109733
109733
  throw new UserError(
109734
- `Trace path is a directory: ${path189}
109734
+ `Trace path is a directory: ${path190}
109735
109735
  Pass a path to a trace file, or run "poe-code traces" to list the traces found.`
109736
109736
  );
109737
109737
  }
109738
- const contents = await options.fs.readFile(path189, "utf8");
109738
+ const contents = await options.fs.readFile(path190, "utf8");
109739
109739
  const firstLineEnd = contents.indexOf("\n");
109740
109740
  const firstLine = firstLineEnd === -1 ? contents : contents.slice(0, firstLineEnd);
109741
109741
  const source = detectTraceFile(firstLine);
109742
109742
  if (source === void 0) {
109743
- throw new Error(`Unable to detect trace source for file: ${path189}`);
109743
+ throw new Error(`Unable to detect trace source for file: ${path190}`);
109744
109744
  }
109745
- return loadTrace({ source, id: path189, path: path189 }, options);
109745
+ return loadTrace({ source, id: path190, path: path190 }, options);
109746
109746
  }
109747
109747
  function dateValue(date) {
109748
109748
  return date?.getTime() ?? 0;
@@ -114351,7 +114351,7 @@ function parseSources(value) {
114351
114351
  'Invalid "sources" frontmatter. Expected each source to be a string or object.'
114352
114352
  );
114353
114353
  }
114354
- const path189 = readRequiredString(getOwnEntry35(item, "path"), "sources[].path");
114354
+ const path190 = readRequiredString(getOwnEntry35(item, "path"), "sources[].path");
114355
114355
  const startLine = readOptionalPositiveInteger(
114356
114356
  getOwnEntry35(item, "startLine"),
114357
114357
  "sources[].startLine"
@@ -114359,7 +114359,7 @@ function parseSources(value) {
114359
114359
  const endLine = readOptionalPositiveInteger(getOwnEntry35(item, "endLine"), "sources[].endLine");
114360
114360
  return parseSourceRef(
114361
114361
  serializeSourceRef({
114362
- path: path189,
114362
+ path: path190,
114363
114363
  ...startLine === void 0 ? {} : { startLine },
114364
114364
  ...endLine === void 0 ? {} : { endLine }
114365
114365
  })
@@ -130879,9 +130879,9 @@ function findPathToModule(currentModuleName, targetModuleName, dependencyGraph,
130879
130879
  }
130880
130880
  visited.add(currentModuleName);
130881
130881
  for (const dependencyModuleName of dependencyGraph.get(currentModuleName) ?? []) {
130882
- const path189 = findPathToModule(dependencyModuleName, targetModuleName, dependencyGraph, visited);
130883
- if (path189 !== void 0) {
130884
- return [currentModuleName, ...path189];
130882
+ const path190 = findPathToModule(dependencyModuleName, targetModuleName, dependencyGraph, visited);
130883
+ if (path190 !== void 0) {
130884
+ return [currentModuleName, ...path190];
130885
130885
  }
130886
130886
  }
130887
130887
  visited.delete(currentModuleName);
@@ -135699,6 +135699,47 @@ var init_hash = __esm({
135699
135699
  }
135700
135700
  });
135701
135701
 
135702
+ // packages/safejs/src/interp/resources.ts
135703
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
135704
+ async function withRunResources(signal, execute2) {
135705
+ const controller = new AbortController();
135706
+ const cancel2 = () => controller.abort(signal?.reason);
135707
+ const cleanups = /* @__PURE__ */ new Set();
135708
+ const resources = {
135709
+ signal: controller.signal,
135710
+ add(close) {
135711
+ cleanups.add(close);
135712
+ }
135713
+ };
135714
+ signal?.addEventListener("abort", cancel2, { once: true });
135715
+ if (signal?.aborted) cancel2();
135716
+ let result;
135717
+ let failure;
135718
+ let errors2 = [];
135719
+ try {
135720
+ result = await runResources.run(resources, execute2);
135721
+ } catch (error3) {
135722
+ failure = { reason: error3 };
135723
+ } finally {
135724
+ signal?.removeEventListener("abort", cancel2);
135725
+ controller.abort(new Error("SafeJS run finished."));
135726
+ const outcomes = await Promise.allSettled(
135727
+ [...cleanups].map((close) => Promise.resolve().then(close))
135728
+ );
135729
+ errors2 = outcomes.flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
135730
+ }
135731
+ if (failure !== void 0) throw failure.reason;
135732
+ if (errors2.length > 0) throw new AggregateError(errors2, "SafeJS resource cleanup failed.");
135733
+ return result;
135734
+ }
135735
+ var runResources;
135736
+ var init_resources = __esm({
135737
+ "packages/safejs/src/interp/resources.ts"() {
135738
+ "use strict";
135739
+ runResources = new AsyncLocalStorage3();
135740
+ }
135741
+ });
135742
+
135702
135743
  // packages/safejs/src/observability/otel.ts
135703
135744
  function bindOtelSpan(value, span) {
135704
135745
  spanByAsyncValue.set(value, span);
@@ -136047,7 +136088,7 @@ var init_budget2 = __esm({
136047
136088
  });
136048
136089
 
136049
136090
  // packages/safejs/src/interp/promise-tracker.ts
136050
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
136091
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
136051
136092
  function assertPromiseExecutionAllowed() {
136052
136093
  const failure = activePromiseTracker.getStore()?.failure;
136053
136094
  if (failure !== void 0 && fatalRejectionCleanup.getStore() !== true) throw failure;
@@ -136161,8 +136202,8 @@ var init_promise_tracker = __esm({
136161
136202
  return void 0;
136162
136203
  }
136163
136204
  };
136164
- activePromiseTracker = new AsyncLocalStorage3();
136165
- fatalRejectionCleanup = new AsyncLocalStorage3();
136205
+ activePromiseTracker = new AsyncLocalStorage4();
136206
+ fatalRejectionCleanup = new AsyncLocalStorage4();
136166
136207
  }
136167
136208
  });
136168
136209
 
@@ -136223,11 +136264,11 @@ function assertSandboxDataDepth(depth) {
136223
136264
  throw new SandboxError({ budget: "dataDepth", current: depth, limit: MAX_DATA_DEPTH });
136224
136265
  }
136225
136266
  }
136226
- function assertSnapshotDataDepth(depth, path189) {
136227
- if (depth > MAX_DATA_DEPTH) throw new SnapshotBudgetError(path189, depth);
136267
+ function assertSnapshotDataDepth(depth, path190) {
136268
+ if (depth > MAX_DATA_DEPTH) throw new SnapshotBudgetError(path190, depth);
136228
136269
  }
136229
136270
  function assertSnapshotGraphDepth(value, rootPath = "$") {
136230
- walkGraphDepth(value, rootPath, (depth, path189) => assertSnapshotDataDepth(depth, path189));
136271
+ walkGraphDepth(value, rootPath, (depth, path190) => assertSnapshotDataDepth(depth, path190));
136231
136272
  }
136232
136273
  function assertSandboxGraphDepth(value) {
136233
136274
  walkGraphDepth(value, "<root>", (depth) => assertSandboxDataDepth(depth));
@@ -136294,12 +136335,12 @@ var init_graph_depth = __esm({
136294
136335
  current;
136295
136336
  limit;
136296
136337
  path;
136297
- constructor(path189, current, limit = MAX_DATA_DEPTH) {
136298
- super(`Snapshot budget exceeded for dataDepth at ${path189}: ${current} > ${limit}.`);
136338
+ constructor(path190, current, limit = MAX_DATA_DEPTH) {
136339
+ super(`Snapshot budget exceeded for dataDepth at ${path190}: ${current} > ${limit}.`);
136299
136340
  this.name = "SnapshotBudgetError";
136300
136341
  this.current = current;
136301
136342
  this.limit = limit;
136302
- this.path = path189;
136343
+ this.path = path190;
136303
136344
  replaceErrorStack(this);
136304
136345
  }
136305
136346
  };
@@ -136382,7 +136423,7 @@ function createDumpFile(snapshot2) {
136382
136423
  }
136383
136424
  return dumped;
136384
136425
  }
136385
- function serializeDumpValue(value, path189, state) {
136426
+ function serializeDumpValue(value, path190, state) {
136386
136427
  if (value === null || typeof value === "string" || typeof value === "boolean") {
136387
136428
  return value;
136388
136429
  }
@@ -136399,22 +136440,22 @@ function serializeDumpValue(value, path189, state) {
136399
136440
  return SKIP_VALUE;
136400
136441
  }
136401
136442
  if (Array.isArray(value)) {
136402
- const reference2 = serializeHeapReference(value, path189, state);
136443
+ const reference2 = serializeHeapReference(value, path190, state);
136403
136444
  if (reference2 !== void 0) {
136404
136445
  return reference2;
136405
136446
  }
136406
- return serializeArrayItems(value, path189, state);
136447
+ return serializeArrayItems(value, path190, state);
136407
136448
  }
136408
136449
  if (!isPlainObject9(value)) {
136409
136450
  return SKIP_VALUE;
136410
136451
  }
136411
- const reference = serializeHeapReference(value, path189, state);
136452
+ const reference = serializeHeapReference(value, path190, state);
136412
136453
  if (reference !== void 0) {
136413
136454
  return reference;
136414
136455
  }
136415
- return serializeObjectEntries(value, path189, state);
136456
+ return serializeObjectEntries(value, path190, state);
136416
136457
  }
136417
- function serializeHeapReference(value, path189, state) {
136458
+ function serializeHeapReference(value, path190, state) {
136418
136459
  const id = state.heapIds.get(value);
136419
136460
  if (id === void 0) {
136420
136461
  return void 0;
@@ -136423,19 +136464,19 @@ function serializeHeapReference(value, path189, state) {
136423
136464
  state.serializedHeapIds.add(id);
136424
136465
  if (isSandboxArguments(value)) {
136425
136466
  state.heap[String(id)] = serializeArguments(value, (entry, key3) => {
136426
- const serialized = serializeDumpValue(entry, `${path189}.${key3}`, state);
136467
+ const serialized = serializeDumpValue(entry, `${path190}.${key3}`, state);
136427
136468
  return serialized === SKIP_VALUE ? { kind: "undefined" } : serialized;
136428
136469
  });
136429
136470
  } else if (Array.isArray(value)) {
136430
136471
  state.heap[String(id)] = {
136431
136472
  kind: "array",
136432
- items: serializeArrayItems(value, path189, state)
136473
+ items: serializeArrayItems(value, path190, state)
136433
136474
  };
136434
136475
  } else {
136435
136476
  const errorType = sandboxErrorTypes.get(value);
136436
136477
  state.heap[String(id)] = {
136437
136478
  kind: "object",
136438
- entries: serializeObjectEntries(value, path189, state),
136479
+ entries: serializeObjectEntries(value, path190, state),
136439
136480
  ...errorType === void 0 ? {} : { errorType }
136440
136481
  };
136441
136482
  }
@@ -136445,10 +136486,10 @@ function serializeHeapReference(value, path189, state) {
136445
136486
  id
136446
136487
  };
136447
136488
  }
136448
- function serializeObjectEntries(value, path189, state) {
136489
+ function serializeObjectEntries(value, path190, state) {
136449
136490
  const serialized = {};
136450
136491
  for (const [key3, entry] of getEnumerableDataEntries(value)) {
136451
- const dumped = serializeDumpValue(entry, `${path189}.${key3}`, state);
136492
+ const dumped = serializeDumpValue(entry, `${path190}.${key3}`, state);
136452
136493
  if (dumped !== SKIP_VALUE) {
136453
136494
  serialized[key3] = dumped;
136454
136495
  }
@@ -136510,9 +136551,9 @@ function isPlainObject9(value) {
136510
136551
  const prototype = Object.getPrototypeOf(value);
136511
136552
  return prototype === Object.prototype || prototype === null;
136512
136553
  }
136513
- function serializeArrayItems(value, path189, state) {
136554
+ function serializeArrayItems(value, path190, state) {
136514
136555
  return getArrayDataItems(value).map((entry, index) => {
136515
- const serialized = serializeDumpValue(entry, `${path189}[${index}]`, state);
136556
+ const serialized = serializeDumpValue(entry, `${path190}[${index}]`, state);
136516
136557
  return serialized === SKIP_VALUE ? { kind: "undefined" } : serialized;
136517
136558
  });
136518
136559
  }
@@ -136546,7 +136587,7 @@ var init_dump_format = __esm({
136546
136587
  init_arguments();
136547
136588
  init_arguments2();
136548
136589
  DUMP_FORMAT_VERSION = 1;
136549
- EXECUTION_SEMANTICS = "jobs-v4";
136590
+ EXECUTION_SEMANTICS = "jobs-v5";
136550
136591
  SKIP_VALUE = /* @__PURE__ */ Symbol("SafeJS.skip-dump-value");
136551
136592
  }
136552
136593
  });
@@ -136593,44 +136634,44 @@ function validateDumpHeap(root, state) {
136593
136634
  const heap = root.heap === void 0 ? /* @__PURE__ */ Object.create(null) : requireRecord3(root.heap, "$.heap");
136594
136635
  const heapIds = /* @__PURE__ */ new Set();
136595
136636
  for (const [key3, value] of Object.entries(heap)) {
136596
- const path189 = `$.heap${formatKey(key3)}`;
136597
- const id = parseHeapId(key3, path189);
136598
- addUnique2(heapIds, id, path189);
136599
- const entry = requireRecord3(value, path189);
136600
- validateErrorType(entry, path189);
136637
+ const path190 = `$.heap${formatKey(key3)}`;
136638
+ const id = parseHeapId(key3, path190);
136639
+ addUnique2(heapIds, id, path190);
136640
+ const entry = requireRecord3(value, path190);
136641
+ validateErrorType(entry, path190);
136601
136642
  if (entry.kind === "arguments") {
136602
- validateArgumentsProperties(entry, path189);
136643
+ validateArgumentsProperties(entry, path190);
136603
136644
  continue;
136604
136645
  }
136605
136646
  if (entry.kind === "array") {
136606
- requireArray(entry.items, `${path189}.items`, state);
136647
+ requireArray(entry.items, `${path190}.items`, state);
136607
136648
  continue;
136608
136649
  }
136609
136650
  if (entry.kind === "object") {
136610
- requireRecord3(entry.entries, `${path189}.entries`);
136651
+ requireRecord3(entry.entries, `${path190}.entries`);
136611
136652
  continue;
136612
136653
  }
136613
- fail2("unknownTag", `${path189}.kind`, "unknown dump heap tag");
136654
+ fail2("unknownTag", `${path190}.kind`, "unknown dump heap tag");
136614
136655
  }
136615
136656
  validateDumpReferences(root, "$", 0, state, heapIds);
136616
136657
  }
136617
- function validateDumpReferences(value, path189, depth, state, heapIds) {
136658
+ function validateDumpReferences(value, path190, depth, state, heapIds) {
136618
136659
  if (value === null || typeof value !== "object") return;
136619
136660
  if (depth > state.limits.maxDepth)
136620
- fail2("budgetExceeded", path189, `exceeds nesting limit ${state.limits.maxDepth}`);
136661
+ fail2("budgetExceeded", path190, `exceeds nesting limit ${state.limits.maxDepth}`);
136621
136662
  if (Array.isArray(value)) {
136622
136663
  value.forEach(
136623
- (entry, index) => validateDumpReferences(entry, `${path189}[${index}]`, depth + 1, state, heapIds)
136664
+ (entry, index) => validateDumpReferences(entry, `${path190}[${index}]`, depth + 1, state, heapIds)
136624
136665
  );
136625
136666
  return;
136626
136667
  }
136627
136668
  const record2 = value;
136628
136669
  if (record2.kind === "ref") {
136629
- const id = requireSafeInteger(record2.id, `${path189}.id`, 1);
136630
- if (!heapIds.has(id)) fail2("danglingReference", `${path189}.id`, `unknown heap value ${id}`);
136670
+ const id = requireSafeInteger(record2.id, `${path190}.id`, 1);
136671
+ if (!heapIds.has(id)) fail2("danglingReference", `${path190}.id`, `unknown heap value ${id}`);
136631
136672
  }
136632
136673
  for (const [key3, entry] of Object.entries(record2)) {
136633
- validateDumpReferences(entry, `${path189}${formatKey(key3)}`, depth + 1, state, heapIds);
136674
+ validateDumpReferences(entry, `${path190}${formatKey(key3)}`, depth + 1, state, heapIds);
136634
136675
  }
136635
136676
  }
136636
136677
  function validateRunSnapshotState(root, state) {
@@ -136649,64 +136690,64 @@ function validateRunSnapshotState(root, state) {
136649
136690
  if (root.loopIterations !== void 0) {
136650
136691
  const iterations = requireRecord3(root.loopIterations, "$.loopIterations");
136651
136692
  for (const [nodeId, value] of Object.entries(iterations)) {
136652
- const path189 = `$.loopIterations${formatKey(nodeId)}`;
136653
- requireSafeInteger(Number(nodeId), `${path189}#key`, 0);
136693
+ const path190 = `$.loopIterations${formatKey(nodeId)}`;
136694
+ requireSafeInteger(Number(nodeId), `${path190}#key`, 0);
136654
136695
  if (typeof value === "number") {
136655
- requireSafeInteger(value, path189, 0);
136696
+ requireSafeInteger(value, path190, 0);
136656
136697
  continue;
136657
136698
  }
136658
- const iteration = requireRecord3(value, path189);
136659
- requireSafeInteger(iteration.index, `${path189}.index`, 0);
136660
- requireArray(iteration.values, `${path189}.values`, state);
136699
+ const iteration = requireRecord3(value, path190);
136700
+ requireSafeInteger(iteration.index, `${path190}.index`, 0);
136701
+ requireArray(iteration.values, `${path190}.values`, state);
136661
136702
  }
136662
136703
  }
136663
136704
  if (root.pendingAwaits !== void 0) {
136664
136705
  const pendingAwaits = requireArray(root.pendingAwaits, "$.pendingAwaits", state);
136665
136706
  pendingAwaits.forEach((value, index) => {
136666
- const path189 = `$.pendingAwaits[${index}]`;
136667
- const pending = requireRecord3(value, path189);
136668
- if (pending.nodeId !== void 0) requireSafeInteger(pending.nodeId, `${path189}.nodeId`, 0);
136669
- const span = requireRecord3(pending.span, `${path189}.span`);
136670
- const start = validatePosition(span.start, `${path189}.span.start`);
136671
- const end = validatePosition(span.end, `${path189}.span.end`);
136707
+ const path190 = `$.pendingAwaits[${index}]`;
136708
+ const pending = requireRecord3(value, path190);
136709
+ if (pending.nodeId !== void 0) requireSafeInteger(pending.nodeId, `${path190}.nodeId`, 0);
136710
+ const span = requireRecord3(pending.span, `${path190}.span`);
136711
+ const start = validatePosition(span.start, `${path190}.span.start`);
136712
+ const end = validatePosition(span.end, `${path190}.span.end`);
136672
136713
  if (start > end) {
136673
- fail2("invalidValue", `${path189}.span`, "start must not exceed end");
136714
+ fail2("invalidValue", `${path190}.span`, "start must not exceed end");
136674
136715
  }
136675
136716
  });
136676
136717
  }
136677
136718
  }
136678
- function validatePosition(value, path189) {
136679
- const position = requireRecord3(value, path189);
136680
- requireSafeInteger(position.line, `${path189}.line`, 1);
136681
- requireSafeInteger(position.column, `${path189}.column`, 0);
136682
- return requireSafeInteger(position.offset, `${path189}.offset`, 0);
136719
+ function validatePosition(value, path190) {
136720
+ const position = requireRecord3(value, path190);
136721
+ requireSafeInteger(position.line, `${path190}.line`, 1);
136722
+ requireSafeInteger(position.column, `${path190}.column`, 0);
136723
+ return requireSafeInteger(position.offset, `${path190}.offset`, 0);
136683
136724
  }
136684
- function validateTaggedValue(record2, path189, state) {
136725
+ function validateTaggedValue(record2, path190, state) {
136685
136726
  switch (record2.kind) {
136686
136727
  case "undefined":
136687
136728
  return;
136688
136729
  case "number":
136689
136730
  if (!["-Infinity", "Infinity", "NaN"].includes(String(record2.value))) {
136690
- fail2("invalidValue", `${path189}.value`, "unknown non-finite number value");
136731
+ fail2("invalidValue", `${path190}.value`, "unknown non-finite number value");
136691
136732
  }
136692
136733
  return;
136693
136734
  case "fn":
136694
- requireSafeInteger(record2.astNodeId, `${path189}.astNodeId`, 0);
136695
- requireSnapshotId(record2.capturedScopeId, `${path189}.capturedScopeId`);
136735
+ requireSafeInteger(record2.astNodeId, `${path190}.astNodeId`, 0);
136736
+ requireSnapshotId(record2.capturedScopeId, `${path190}.capturedScopeId`);
136696
136737
  return;
136697
136738
  case "generator":
136698
- validateGeneratorShape(record2, path189, state);
136739
+ validateGeneratorShape(record2, path190, state);
136699
136740
  return;
136700
136741
  case "promise":
136701
- requireSnapshotId(record2.id, `${path189}.id`);
136742
+ requireSnapshotId(record2.id, `${path190}.id`);
136702
136743
  return;
136703
136744
  case "ref":
136704
- requireSafeInteger(record2.id, `${path189}.id`, 1);
136745
+ requireSafeInteger(record2.id, `${path190}.id`, 1);
136705
136746
  return;
136706
136747
  case "regex":
136707
- requireString2(record2.source, `${path189}.source`, state.limits);
136708
- requireString2(record2.flags, `${path189}.flags`, state.limits);
136709
- requireSafeInteger(record2.lastIndex, `${path189}.lastIndex`, 0);
136748
+ requireString2(record2.source, `${path190}.source`, state.limits);
136749
+ requireString2(record2.flags, `${path190}.flags`, state.limits);
136750
+ requireSafeInteger(record2.lastIndex, `${path190}.lastIndex`, 0);
136710
136751
  return;
136711
136752
  case "array":
136712
136753
  case "arguments":
@@ -136716,28 +136757,28 @@ function validateTaggedValue(record2, path189, state) {
136716
136757
  return;
136717
136758
  }
136718
136759
  }
136719
- function validateGeneratorShape(record2, path189, state) {
136760
+ function validateGeneratorShape(record2, path190, state) {
136720
136761
  if (!["start", "suspended", "done"].includes(String(record2.state))) {
136721
- fail2("invalidState", `${path189}.state`, "unknown generator state");
136762
+ fail2("invalidState", `${path190}.state`, "unknown generator state");
136722
136763
  }
136723
136764
  if (record2.state === "done") {
136724
136765
  if (record2.astNodeId !== void 0 || record2.capturedScopeId !== void 0 || record2.sent !== void 0 || record2.yieldNodeId !== void 0) {
136725
- fail2("invalidState", path189, "done generator cannot contain resume state");
136766
+ fail2("invalidState", path190, "done generator cannot contain resume state");
136726
136767
  }
136727
136768
  return;
136728
136769
  }
136729
- requireSafeInteger(record2.astNodeId, `${path189}.astNodeId`, 0);
136730
- requireSnapshotId(record2.capturedScopeId, `${path189}.capturedScopeId`);
136770
+ requireSafeInteger(record2.astNodeId, `${path190}.astNodeId`, 0);
136771
+ requireSnapshotId(record2.capturedScopeId, `${path190}.capturedScopeId`);
136731
136772
  if (record2.state === "start") {
136732
136773
  if (record2.sent !== void 0 || record2.yieldNodeId !== void 0) {
136733
- fail2("invalidState", path189, "unstarted generator cannot contain a resume cursor");
136774
+ fail2("invalidState", path190, "unstarted generator cannot contain a resume cursor");
136734
136775
  }
136735
136776
  return;
136736
136777
  }
136737
- requireSafeInteger(record2.yieldNodeId, `${path189}.yieldNodeId`, 0);
136738
- const sent = requireArray(record2.sent, `${path189}.sent`, state);
136778
+ requireSafeInteger(record2.yieldNodeId, `${path190}.yieldNodeId`, 0);
136779
+ const sent = requireArray(record2.sent, `${path190}.sent`, state);
136739
136780
  sent.forEach((completion, index) => {
136740
- const completionPath = `${path189}.sent[${index}]`;
136781
+ const completionPath = `${path190}.sent[${index}]`;
136741
136782
  const candidate = requireRecord3(completion, completionPath);
136742
136783
  if (!Object.hasOwn(candidate, "type")) {
136743
136784
  fail2("invalidValue", `${completionPath}.type`, "completion type is required");
@@ -136750,41 +136791,41 @@ function validateGeneratorShape(record2, path189, state) {
136750
136791
  }
136751
136792
  });
136752
136793
  }
136753
- function validateErrorType(record2, path189) {
136794
+ function validateErrorType(record2, path190) {
136754
136795
  if (!Object.hasOwn(record2, "errorType")) return;
136755
136796
  if (record2.kind !== "object" || !sandboxErrorNames.includes(record2.errorType)) {
136756
- fail2("invalidValue", `${path189}.errorType`, "invalid error metadata");
136797
+ fail2("invalidValue", `${path190}.errorType`, "invalid error metadata");
136757
136798
  }
136758
136799
  }
136759
- function validateArgumentsProperties(record2, path189) {
136800
+ function validateArgumentsProperties(record2, path190) {
136760
136801
  if (typeof record2.extensible !== "boolean") {
136761
- fail2("invalidType", `${path189}.extensible`, "expected boolean");
136802
+ fail2("invalidType", `${path190}.extensible`, "expected boolean");
136762
136803
  }
136763
136804
  if (typeof record2.lengthBeforeCallee !== "boolean") {
136764
- fail2("invalidType", `${path189}.lengthBeforeCallee`, "expected boolean");
136805
+ fail2("invalidType", `${path190}.lengthBeforeCallee`, "expected boolean");
136765
136806
  }
136766
- const properties = requireRecord3(record2.properties, `${path189}.properties`);
136807
+ const properties = requireRecord3(record2.properties, `${path190}.properties`);
136767
136808
  if (record2.iterator !== null) {
136768
- const iterator = requireRecord3(record2.iterator, `${path189}.iterator`);
136809
+ const iterator = requireRecord3(record2.iterator, `${path190}.iterator`);
136769
136810
  for (const key3 of Object.keys(iterator)) {
136770
136811
  if (!["configurable", "enumerable", "writable"].includes(key3)) {
136771
136812
  fail2(
136772
136813
  "invalidValue",
136773
- `${path189}.iterator${formatKey(key3)}`,
136814
+ `${path190}.iterator${formatKey(key3)}`,
136774
136815
  "unknown iterator descriptor field"
136775
136816
  );
136776
136817
  }
136777
136818
  }
136778
136819
  for (const flag of ["configurable", "enumerable", "writable"]) {
136779
136820
  if (typeof iterator[flag] !== "boolean")
136780
- fail2("invalidType", `${path189}.iterator.${flag}`, "expected boolean");
136821
+ fail2("invalidType", `${path190}.iterator.${flag}`, "expected boolean");
136781
136822
  }
136782
136823
  }
136783
136824
  if (record2.lengthBeforeCallee && !Object.hasOwn(properties, "length")) {
136784
- fail2("invalidValue", `${path189}.properties`, "initial length property is required");
136825
+ fail2("invalidValue", `${path190}.properties`, "initial length property is required");
136785
136826
  }
136786
136827
  for (const [key3, value] of Object.entries(properties)) {
136787
- const propertyPath = `${path189}.properties${formatKey(key3)}`;
136828
+ const propertyPath = `${path190}.properties${formatKey(key3)}`;
136788
136829
  if (key3 === "callee")
136789
136830
  fail2("invalidValue", propertyPath, "strict callee accessor cannot be replaced");
136790
136831
  const descriptor = requireRecord3(value, propertyPath);
@@ -136805,71 +136846,71 @@ function validateArgumentsProperties(record2, path189) {
136805
136846
  }
136806
136847
  }
136807
136848
  }
136808
- function validateGenericValue(value, path189, depth, state) {
136849
+ function validateGenericValue(value, path190, depth, state) {
136809
136850
  if (state.dataPropertiesOnly && types.isProxy(value)) {
136810
- fail2("invalidType", path189, "proxy objects are not snapshot data");
136851
+ fail2("invalidType", path190, "proxy objects are not snapshot data");
136811
136852
  }
136812
136853
  if (depth > state.limits.maxDepth)
136813
- fail2("budgetExceeded", path189, `exceeds nesting limit ${state.limits.maxDepth}`);
136854
+ fail2("budgetExceeded", path190, `exceeds nesting limit ${state.limits.maxDepth}`);
136814
136855
  state.entries += 1;
136815
136856
  if (state.entries > state.limits.maxAggregateEntries)
136816
136857
  fail2(
136817
136858
  "budgetExceeded",
136818
- path189,
136859
+ path190,
136819
136860
  `exceeds aggregate entry limit ${state.limits.maxAggregateEntries}`
136820
136861
  );
136821
136862
  if (typeof value === "string") {
136822
- requireString2(value, path189, state.limits);
136863
+ requireString2(value, path190, state.limits);
136823
136864
  state.dataSize += value.length;
136824
136865
  } else if (typeof value === "number") {
136825
136866
  if (Number.isInteger(value) && !Number.isSafeInteger(value))
136826
- fail2("invalidValue", path189, "integer must be safe");
136867
+ fail2("invalidValue", path190, "integer must be safe");
136827
136868
  } else if (Array.isArray(value)) {
136828
- if (value.length > state.limits.maxEntries) fail2("budgetExceeded", path189, "array is too large");
136869
+ if (value.length > state.limits.maxEntries) fail2("budgetExceeded", path190, "array is too large");
136829
136870
  if (state.dataPropertiesOnly) {
136830
- const entries = snapshotDataEntries(value, path189).filter(([key3]) => key3 !== "length");
136871
+ const entries = snapshotDataEntries(value, path190).filter(([key3]) => key3 !== "length");
136831
136872
  if (entries.length !== value.length)
136832
- fail2("invalidType", path189, "snapshot arrays must be dense");
136873
+ fail2("invalidType", path190, "snapshot arrays must be dense");
136833
136874
  for (const [key3, entry] of entries) {
136834
136875
  const index = Number(key3);
136835
136876
  if (!Number.isInteger(index) || index < 0 || index >= value.length || String(index) !== key3) {
136836
- fail2("invalidType", path189, "snapshot arrays cannot have named properties");
136877
+ fail2("invalidType", path190, "snapshot arrays cannot have named properties");
136837
136878
  }
136838
- validateGenericValue(entry, `${path189}[${key3}]`, depth + 1, state);
136879
+ validateGenericValue(entry, `${path190}[${key3}]`, depth + 1, state);
136839
136880
  }
136840
136881
  } else {
136841
136882
  value.forEach(
136842
- (entry, index) => validateGenericValue(entry, `${path189}[${index}]`, depth + 1, state)
136883
+ (entry, index) => validateGenericValue(entry, `${path190}[${index}]`, depth + 1, state)
136843
136884
  );
136844
136885
  }
136845
136886
  } else if (value !== null && typeof value === "object") {
136846
136887
  const record2 = value;
136847
136888
  if (state.validateTaggedPayloads && isTaggedValueShape(record2)) {
136848
- validateTaggedValue(record2, path189, state);
136889
+ validateTaggedValue(record2, path190, state);
136849
136890
  }
136850
- const entries = state.dataPropertiesOnly ? snapshotDataEntries(value, path189) : Object.entries(value);
136891
+ const entries = state.dataPropertiesOnly ? snapshotDataEntries(value, path190) : Object.entries(value);
136851
136892
  for (const [key3, entry] of entries) {
136852
- requireString2(key3, `${path189}${formatKey(key3)}`, state.limits);
136893
+ requireString2(key3, `${path190}${formatKey(key3)}`, state.limits);
136853
136894
  state.dataSize += key3.length;
136854
- validateGenericValue(entry, `${path189}${formatKey(key3)}`, depth + 1, state);
136895
+ validateGenericValue(entry, `${path190}${formatKey(key3)}`, depth + 1, state);
136855
136896
  }
136856
136897
  } else if (!["boolean", "number"].includes(typeof value) && !(state.allowFunctions && typeof value === "function") && !(state.allowUndefined && value === void 0) && value !== null) {
136857
- fail2("invalidType", path189, "contains an unsupported value");
136898
+ fail2("invalidType", path190, "contains an unsupported value");
136858
136899
  }
136859
136900
  if (state.dataSize > state.limits.maxDataSize)
136860
- fail2("budgetExceeded", path189, `exceeds aggregate data limit ${state.limits.maxDataSize}`);
136901
+ fail2("budgetExceeded", path190, `exceeds aggregate data limit ${state.limits.maxDataSize}`);
136861
136902
  }
136862
- function snapshotDataEntries(value, path189) {
136903
+ function snapshotDataEntries(value, path190) {
136863
136904
  const prototype = Object.getPrototypeOf(value);
136864
136905
  if (prototype !== null && prototype !== (Array.isArray(value) ? Array.prototype : Object.prototype)) {
136865
- fail2("invalidType", path189, "snapshot data must not have a custom prototype");
136906
+ fail2("invalidType", path190, "snapshot data must not have a custom prototype");
136866
136907
  }
136867
136908
  if (Object.getOwnPropertySymbols(value).length > 0) {
136868
- fail2("invalidType", path189, "snapshot data must not have symbol properties");
136909
+ fail2("invalidType", path190, "snapshot data must not have symbol properties");
136869
136910
  }
136870
136911
  return Object.entries(Object.getOwnPropertyDescriptors(value)).map(([key3, descriptor]) => {
136871
136912
  if (!("value" in descriptor))
136872
- fail2("invalidType", `${path189}${formatKey(key3)}`, "snapshot data must not have accessors");
136913
+ fail2("invalidType", `${path190}${formatKey(key3)}`, "snapshot data must not have accessors");
136873
136914
  return [key3, descriptor.value];
136874
136915
  });
136875
136916
  }
@@ -136883,48 +136924,48 @@ function defaultLimits() {
136883
136924
  maxDataSize: DEFAULT_MAX_DATA_SIZE
136884
136925
  };
136885
136926
  }
136886
- function requireArray(value, path189, state) {
136887
- if (!Array.isArray(value)) fail2("invalidType", path189, "must be an array");
136927
+ function requireArray(value, path190, state) {
136928
+ if (!Array.isArray(value)) fail2("invalidType", path190, "must be an array");
136888
136929
  if (value.length > state.limits.maxEntries)
136889
- fail2("budgetExceeded", path189, `exceeds collection entry limit ${state.limits.maxEntries}`);
136930
+ fail2("budgetExceeded", path190, `exceeds collection entry limit ${state.limits.maxEntries}`);
136890
136931
  return value;
136891
136932
  }
136892
- function requireRecord3(value, path189) {
136933
+ function requireRecord3(value, path190) {
136893
136934
  if (typeof value !== "object" || value === null || Array.isArray(value))
136894
- fail2("invalidType", path189, "must be an object");
136935
+ fail2("invalidType", path190, "must be an object");
136895
136936
  return value;
136896
136937
  }
136897
- function requireSnapshotId(value, path189) {
136938
+ function requireSnapshotId(value, path190) {
136898
136939
  if (typeof value === "string") {
136899
- if (value.length === 0) fail2("invalidValue", path189, "id must not be empty");
136940
+ if (value.length === 0) fail2("invalidValue", path190, "id must not be empty");
136900
136941
  return value;
136901
136942
  }
136902
- return requireSafeInteger(value, path189, 0);
136943
+ return requireSafeInteger(value, path190, 0);
136903
136944
  }
136904
- function requireSafeInteger(value, path189, minimum) {
136945
+ function requireSafeInteger(value, path190, minimum) {
136905
136946
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum)
136906
- fail2("invalidValue", path189, `must be a safe integer >= ${minimum}`);
136947
+ fail2("invalidValue", path190, `must be a safe integer >= ${minimum}`);
136907
136948
  return value;
136908
136949
  }
136909
- function requireNonEmptyString5(value, path189, limits) {
136910
- const text5 = requireString2(value, path189, limits);
136911
- if (text5.length === 0) fail2("invalidValue", path189, "must not be empty");
136950
+ function requireNonEmptyString5(value, path190, limits) {
136951
+ const text5 = requireString2(value, path190, limits);
136952
+ if (text5.length === 0) fail2("invalidValue", path190, "must not be empty");
136912
136953
  return text5;
136913
136954
  }
136914
- function requireString2(value, path189, limits) {
136915
- if (typeof value !== "string") fail2("invalidType", path189, "must be a string");
136955
+ function requireString2(value, path190, limits) {
136956
+ if (typeof value !== "string") fail2("invalidType", path190, "must be a string");
136916
136957
  if (value.length > limits.maxStringLength)
136917
- fail2("budgetExceeded", path189, `exceeds string limit ${limits.maxStringLength}`);
136958
+ fail2("budgetExceeded", path190, `exceeds string limit ${limits.maxStringLength}`);
136918
136959
  return value;
136919
136960
  }
136920
- function addUnique2(values, value, path189) {
136921
- if (values.has(value)) fail2("duplicateId", path189, `duplicate id ${String(value)}`);
136961
+ function addUnique2(values, value, path190) {
136962
+ if (values.has(value)) fail2("duplicateId", path190, `duplicate id ${String(value)}`);
136922
136963
  values.add(value);
136923
136964
  }
136924
- function parseHeapId(value, path189) {
136965
+ function parseHeapId(value, path190) {
136925
136966
  if (String(Number(value)) !== value)
136926
- fail2("invalidValue", path189, "heap key must be a canonical positive integer");
136927
- return requireSafeInteger(Number(value), path189, 1);
136967
+ fail2("invalidValue", path190, "heap key must be a canonical positive integer");
136968
+ return requireSafeInteger(Number(value), path190, 1);
136928
136969
  }
136929
136970
  function formatKey(key3) {
136930
136971
  return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key3) ? `.${key3}` : `[${JSON.stringify(key3)}]`;
@@ -136932,8 +136973,8 @@ function formatKey(key3) {
136932
136973
  function isTaggedValueShape(value) {
136933
136974
  return typeof value.kind === "string" && TAGGED_VALUE_KINDS.has(value.kind);
136934
136975
  }
136935
- function fail2(code, path189, detail) {
136936
- throw new SnapshotValidationError(code, path189, detail);
136976
+ function fail2(code, path190, detail) {
136977
+ throw new SnapshotValidationError(code, path190, detail);
136937
136978
  }
136938
136979
  var DEFAULT_MAX_DEPTH, DEFAULT_MAX_ENTRIES, DEFAULT_MAX_STRING_LENGTH, DEFAULT_MAX_DATA_SIZE, TAGGED_VALUE_KINDS, SnapshotValidationError;
136939
136980
  var init_validation = __esm({
@@ -136964,11 +137005,11 @@ var init_validation = __esm({
136964
137005
  SnapshotValidationError = class extends Error {
136965
137006
  code;
136966
137007
  path;
136967
- constructor(code, path189, detail) {
136968
- super(`Invalid snapshot at ${path189}: ${detail}`);
137008
+ constructor(code, path190, detail) {
137009
+ super(`Invalid snapshot at ${path190}: ${detail}`);
136969
137010
  this.name = "SnapshotValidationError";
136970
137011
  this.code = code;
136971
- this.path = path189;
137012
+ this.path = path190;
136972
137013
  replaceErrorStack(this);
136973
137014
  }
136974
137015
  };
@@ -136976,7 +137017,7 @@ var init_validation = __esm({
136976
137017
  });
136977
137018
 
136978
137019
  // packages/safejs/src/interp/promise-replay.ts
136979
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
137020
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
136980
137021
  function validateReplay(value) {
136981
137022
  validateSnapshotData(value);
136982
137023
  if (value === null || typeof value !== "object" || !("version" in value) || value.version !== 1 || !("steps" in value) || !isCounter(value.steps) || !("promises" in value) || !isCounter(value.promises) || !("settlements" in value) || !Array.isArray(value.settlements)) {
@@ -137314,7 +137355,7 @@ var init_promise_replay = __esm({
137314
137355
  this.liveWaiters.clear();
137315
137356
  }
137316
137357
  };
137317
- promiseReplayContext = new AsyncLocalStorage4();
137358
+ promiseReplayContext = new AsyncLocalStorage5();
137318
137359
  }
137319
137360
  });
137320
137361
 
@@ -137322,7 +137363,7 @@ var init_promise_replay = __esm({
137322
137363
  function encodeReplayData(value, options = {}) {
137323
137364
  const nodes = [];
137324
137365
  const seen = /* @__PURE__ */ new WeakMap();
137325
- const encode = (entry, depth, path189) => {
137366
+ const encode = (entry, depth, path190) => {
137326
137367
  if (depth > MAX_DATA_DEPTH) throw new TypeError("Replay data exceeds the nesting limit.");
137327
137368
  if (entry === null || typeof entry === "boolean" || typeof entry === "string") return entry;
137328
137369
  if (entry === void 0) return { tag: "undefined" };
@@ -137335,12 +137376,12 @@ function encodeReplayData(value, options = {}) {
137335
137376
  };
137336
137377
  }
137337
137378
  if (isSandboxPromise(entry)) {
137338
- const id2 = options.identifyPromise?.(entry, path189);
137379
+ const id2 = options.identifyPromise?.(entry, path190);
137339
137380
  if (typeof id2 === "string" && id2.length > 0) return { tag: "promise-capability", id: id2 };
137340
137381
  }
137341
137382
  let capabilityId;
137342
137383
  if (isSandboxClosure(entry)) {
137343
- capabilityId = options.identifyCapability?.(entry, path189);
137384
+ capabilityId = options.identifyCapability?.(entry, path190);
137344
137385
  if (typeof capabilityId !== "string" || capabilityId.length === 0)
137345
137386
  throw new MissingReplayCapabilityError("A callable needs an explicit resume capability.");
137346
137387
  if (!options.captureCapabilityProperties) return { tag: "capability", id: capabilityId };
@@ -137355,7 +137396,7 @@ function encodeReplayData(value, options = {}) {
137355
137396
  const id = nodes.length;
137356
137397
  seen.set(entry, id);
137357
137398
  nodes.push(void 0);
137358
- const child = (value2, key3) => encode(value2, depth + 1, [...path189, key3]);
137399
+ const child = (value2, key3) => encode(value2, depth + 1, [...path190, key3]);
137359
137400
  if (isSandboxClosure(entry)) {
137360
137401
  nodes[id] = {
137361
137402
  kind: "capability",
@@ -137477,7 +137518,7 @@ function decodeReplayData(input, options = {}) {
137477
137518
  restored.set(id, capability);
137478
137519
  return capability;
137479
137520
  }
137480
- return createSandboxClosure({
137521
+ const copy = createSandboxClosure({
137481
137522
  ...capability,
137482
137523
  boundTarget: capability.boundTarget,
137483
137524
  cancellationSignal: capability.cancellationSignal,
@@ -137491,6 +137532,8 @@ function decodeReplayData(input, options = {}) {
137491
137532
  return properties;
137492
137533
  }
137493
137534
  });
137535
+ options.onCapabilityRestored?.(capability, copy);
137536
+ return copy;
137494
137537
  }
137495
137538
  if (kind === "map") {
137496
137539
  const result2 = createSandboxMap();
@@ -137648,7 +137691,7 @@ import { createHash as createHash13, randomUUID as randomUUID49 } from "node:cry
137648
137691
  function copyOutcome(outcome) {
137649
137692
  return outcome.status === "fulfilled" ? { status: "fulfilled", value: deepCopyToSandbox(outcome.value) } : { status: "rejected", reason: deepCopyToSandbox(outcome.reason) };
137650
137693
  }
137651
- function restoreReplayCalls(input, encodedOutcomes, callbackSizes) {
137694
+ function restoreReplayCalls(input, encodedOutcomes, callbackSizes, requiredHostCapabilities = /* @__PURE__ */ new Set()) {
137652
137695
  validateSnapshotData(input);
137653
137696
  if (input === null || typeof input !== "object" || !("version" in input) || input.version !== 1 || !("calls" in input) || !Array.isArray(input.calls)) {
137654
137697
  throw new TypeError("Invalid host call replay header.");
@@ -137669,7 +137712,23 @@ function restoreReplayCalls(input, encodedOutcomes, callbackSizes) {
137669
137712
  );
137670
137713
  }
137671
137714
  }
137672
- const resolveCapability = (id) => capabilities.get(id);
137715
+ const resolveCapability = (id) => {
137716
+ if (!capabilities.has(id) && id.startsWith("host:")) {
137717
+ const path190 = JSON.parse(id.slice(5));
137718
+ if (!Array.isArray(path190) || path190.length < 2 || path190.some((value) => typeof value !== "string"))
137719
+ throw new TypeError("Invalid host capability identity.");
137720
+ requiredHostCapabilities.add(id);
137721
+ capabilities.set(
137722
+ id,
137723
+ createSandboxClosure({
137724
+ call: () => {
137725
+ throw new TypeError("Host capability has not been reconstructed.");
137726
+ }
137727
+ })
137728
+ );
137729
+ }
137730
+ return capabilities.get(id);
137731
+ };
137673
137732
  return input.calls.map((entry, index) => {
137674
137733
  if (entry === null || typeof entry !== "object" || Array.isArray(entry))
137675
137734
  throw new TypeError("Invalid replay call.");
@@ -137842,7 +137901,12 @@ var init_host_call = __esm({
137842
137901
  this.budget = budget;
137843
137902
  this.recordedReplay = replay !== void 0;
137844
137903
  if (replay !== void 0) {
137845
- const replayRecords = restoreReplayCalls(replay, this.encodedOutcomes, this.callbackSizes);
137904
+ const replayRecords = restoreReplayCalls(
137905
+ replay,
137906
+ this.encodedOutcomes,
137907
+ this.callbackSizes,
137908
+ this.requiredHostCapabilities
137909
+ );
137846
137910
  const restoredRunId = replayRecords[0]?.runId ?? records[0]?.runId ?? randomUUID49();
137847
137911
  validateRestoredRecords(records, restoredRunId, sourceHash);
137848
137912
  for (const record2 of records) {
@@ -137894,8 +137958,10 @@ var init_host_call = __esm({
137894
137958
  retainedSize = 0;
137895
137959
  outcomeSizes = /* @__PURE__ */ new Map();
137896
137960
  capabilities = /* @__PURE__ */ new Map();
137961
+ requiredHostCapabilities = /* @__PURE__ */ new Set();
137897
137962
  capabilityIds = /* @__PURE__ */ new WeakMap();
137898
137963
  nativeClosures = /* @__PURE__ */ new WeakMap();
137964
+ hostSources = /* @__PURE__ */ new WeakMap();
137899
137965
  encodedOutcomes = /* @__PURE__ */ new Map();
137900
137966
  callbackSizes = /* @__PURE__ */ new Map();
137901
137967
  completedCallbackOwners = /* @__PURE__ */ new Set();
@@ -138048,6 +138114,30 @@ var init_host_call = __esm({
138048
138114
  if (!this.capabilityIds.has(closure)) this.capabilityIds.set(closure, identity);
138049
138115
  this.nativeClosures.set(native, closure);
138050
138116
  }
138117
+ registerHostCapability(path190, closure, native) {
138118
+ const identity = `host:${path190}`;
138119
+ const existing = this.capabilities.get(identity);
138120
+ if (existing !== void 0 && existing !== closure)
138121
+ throw new TypeError(`Conflicting replay capability '${identity}'.`);
138122
+ this.capabilities.set(identity, closure);
138123
+ if (!this.capabilityIds.has(closure)) this.capabilityIds.set(closure, identity);
138124
+ if (!this.nativeClosures.has(native)) this.nativeClosures.set(native, closure);
138125
+ this.hostSources.set(closure, native);
138126
+ }
138127
+ rebindHostCapability(original, restored) {
138128
+ const identity = this.capabilityIds.get(original);
138129
+ const source = this.hostSources.get(original);
138130
+ if (identity === void 0 || source === void 0) return;
138131
+ this.capabilities.set(identity, restored);
138132
+ this.capabilityIds.set(restored, identity);
138133
+ this.nativeClosures.set(source, restored);
138134
+ this.hostSources.set(restored, source);
138135
+ }
138136
+ validateHostCapabilities() {
138137
+ for (const identity of this.requiredHostCapabilities) {
138138
+ if (!this.capabilities.has(identity)) throw new UnresolvedReplayCapabilityError(identity);
138139
+ }
138140
+ }
138051
138141
  waitForCapability(id) {
138052
138142
  if (this.capabilities.has(id)) return Promise.resolve();
138053
138143
  const owner = id.slice(0, id.lastIndexOf("/function/"));
@@ -138716,7 +138806,7 @@ var init_iteration = __esm({
138716
138806
  });
138717
138807
 
138718
138808
  // packages/safejs/src/interp/jobs.ts
138719
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
138809
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
138720
138810
  function runPromiseJob(task) {
138721
138811
  const job = activeJob.getStore();
138722
138812
  return job === void 0 ? Promise.resolve().then(task) : job.queue.run(task);
@@ -138750,7 +138840,7 @@ var activeJob, SandboxJobQueue;
138750
138840
  var init_jobs4 = __esm({
138751
138841
  "packages/safejs/src/interp/jobs.ts"() {
138752
138842
  "use strict";
138753
- activeJob = new AsyncLocalStorage5();
138843
+ activeJob = new AsyncLocalStorage6();
138754
138844
  SandboxJobQueue = class {
138755
138845
  running = false;
138756
138846
  pending = [];
@@ -139558,7 +139648,7 @@ var init_promise = __esm({
139558
139648
  });
139559
139649
 
139560
139650
  // packages/safejs/src/interp/cancel.ts
139561
- import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
139651
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
139562
139652
  function withCancellationSignal(signal, task) {
139563
139653
  return activeCancellation.run({ signal, host: false }, task);
139564
139654
  }
@@ -139738,7 +139828,7 @@ var init_cancel2 = __esm({
139738
139828
  init_promise_tracker();
139739
139829
  init_shape();
139740
139830
  init_promise();
139741
- activeCancellation = new AsyncLocalStorage6();
139831
+ activeCancellation = new AsyncLocalStorage7();
139742
139832
  sandboxPromises = /* @__PURE__ */ new WeakSet();
139743
139833
  cancelableOutcomes = /* @__PURE__ */ new WeakMap();
139744
139834
  }
@@ -139981,7 +140071,7 @@ function deepCopyFromSandbox(value, options = {}) {
139981
140071
  options
139982
140072
  );
139983
140073
  }
139984
- function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections = false, depth = 0) {
140074
+ function copyToSandbox(value, state, path190 = "<root>", cloneSandboxCollections = false, depth = 0) {
139985
140075
  assertSandboxDataDepth(depth);
139986
140076
  if (isSandboxPrimitive(value)) {
139987
140077
  return value;
@@ -139997,8 +140087,8 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
139997
140087
  state.seen.set(value, copy);
139998
140088
  for (const [key3, entry] of value.entries) {
139999
140089
  copy.entries.set(
140000
- copyToSandbox(key3, state, `${path189}.<key>`, true, depth + 1),
140001
- copyToSandbox(entry, state, `${path189}.<value>`, true, depth + 1)
140090
+ copyToSandbox(key3, state, `${path190}.<key>`, true, depth + 1),
140091
+ copyToSandbox(entry, state, `${path190}.<value>`, true, depth + 1)
140002
140092
  );
140003
140093
  }
140004
140094
  return copy;
@@ -140010,7 +140100,7 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
140010
140100
  const copy = createSandboxSet();
140011
140101
  state.seen.set(value, copy);
140012
140102
  for (const entry of value.values) {
140013
- copy.values.add(copyToSandbox(entry, state, `${path189}.<value>`, true, depth + 1));
140103
+ copy.values.add(copyToSandbox(entry, state, `${path190}.<value>`, true, depth + 1));
140014
140104
  }
140015
140105
  return copy;
140016
140106
  }
@@ -140036,8 +140126,8 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
140036
140126
  state.seen.set(value, copy);
140037
140127
  for (const [key3, entry] of value) {
140038
140128
  copy.entries.set(
140039
- copyToSandbox(key3, state, `${path189}.<key>`, cloneSandboxCollections, depth + 1),
140040
- copyToSandbox(entry, state, `${path189}.<value>`, cloneSandboxCollections, depth + 1)
140129
+ copyToSandbox(key3, state, `${path190}.<key>`, cloneSandboxCollections, depth + 1),
140130
+ copyToSandbox(entry, state, `${path190}.<value>`, cloneSandboxCollections, depth + 1)
140041
140131
  );
140042
140132
  }
140043
140133
  return copy;
@@ -140051,7 +140141,7 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
140051
140141
  state.seen.set(value, copy);
140052
140142
  for (const entry of value) {
140053
140143
  copy.values.add(
140054
- copyToSandbox(entry, state, `${path189}.<value>`, cloneSandboxCollections, depth + 1)
140144
+ copyToSandbox(entry, state, `${path190}.<value>`, cloneSandboxCollections, depth + 1)
140055
140145
  );
140056
140146
  }
140057
140147
  return copy;
@@ -140063,14 +140153,14 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
140063
140153
  }
140064
140154
  const copy = new Array(value.length);
140065
140155
  state.seen.set(value, copy);
140066
- for (const entry of getEnumerableArrayEntries(value, path189)) {
140156
+ for (const entry of getEnumerableArrayEntries(value, path190)) {
140067
140157
  defineOwnDataProperty(
140068
140158
  copy,
140069
140159
  entry.key,
140070
140160
  copyToSandbox(
140071
140161
  entry.value,
140072
140162
  state,
140073
- joinArrayPath(path189, entry.key),
140163
+ joinArrayPath(path190, entry.key),
140074
140164
  cloneSandboxCollections,
140075
140165
  depth + 1
140076
140166
  )
@@ -140086,7 +140176,7 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
140086
140176
  copySandboxArgumentProperties(
140087
140177
  value,
140088
140178
  copy,
140089
- (entry, key3) => copyToSandbox(entry, state, joinPath(path189, key3), cloneSandboxCollections, depth + 1)
140179
+ (entry, key3) => copyToSandbox(entry, state, joinPath(path190, key3), cloneSandboxCollections, depth + 1)
140090
140180
  );
140091
140181
  return copy;
140092
140182
  }
@@ -140099,14 +140189,14 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
140099
140189
  state.seen.set(value, copy);
140100
140190
  const errorType = sandboxErrorTypes.get(value);
140101
140191
  if (errorType !== void 0) sandboxErrorTypes.set(copy, errorType);
140102
- for (const entry of getEnumerableObjectEntries(value, path189)) {
140192
+ for (const entry of getEnumerableObjectEntries(value, path190)) {
140103
140193
  defineOwnDataProperty(
140104
140194
  copy,
140105
140195
  entry.key,
140106
140196
  copyToSandbox(
140107
140197
  entry.value,
140108
140198
  state,
140109
- joinPath(path189, entry.key),
140199
+ joinPath(path190, entry.key),
140110
140200
  cloneSandboxCollections,
140111
140201
  depth + 1
140112
140202
  )
@@ -140114,9 +140204,9 @@ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections
140114
140204
  }
140115
140205
  return copy;
140116
140206
  }
140117
- throw new TypeError(`Unsupported sandbox value at ${path189}: ${describeValue(value)}`);
140207
+ throw new TypeError(`Unsupported sandbox value at ${path190}: ${describeValue(value)}`);
140118
140208
  }
140119
- function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
140209
+ function copyFromSandbox(value, state, path190 = "<root>", options, depth = 0) {
140120
140210
  assertSandboxDataDepth(depth);
140121
140211
  if (isSandboxPrimitive(value)) {
140122
140212
  return value;
@@ -140161,8 +140251,8 @@ function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
140161
140251
  state.seen.set(value, copy);
140162
140252
  for (const [key3, entry] of value.entries) {
140163
140253
  copy.set(
140164
- copyFromSandbox(key3, state, `${path189}.<key>`, options, depth + 1),
140165
- copyFromSandbox(entry, state, `${path189}.<value>`, options, depth + 1)
140254
+ copyFromSandbox(key3, state, `${path190}.<key>`, options, depth + 1),
140255
+ copyFromSandbox(entry, state, `${path190}.<value>`, options, depth + 1)
140166
140256
  );
140167
140257
  }
140168
140258
  return copy;
@@ -140175,7 +140265,7 @@ function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
140175
140265
  const copy = /* @__PURE__ */ new Set();
140176
140266
  state.seen.set(value, copy);
140177
140267
  for (const entry of value.values) {
140178
- copy.add(copyFromSandbox(entry, state, `${path189}.<value>`, options, depth + 1));
140268
+ copy.add(copyFromSandbox(entry, state, `${path190}.<value>`, options, depth + 1));
140179
140269
  }
140180
140270
  return copy;
140181
140271
  }
@@ -140186,11 +140276,11 @@ function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
140186
140276
  }
140187
140277
  const copy = new Array(value.length);
140188
140278
  state.seen.set(value, copy);
140189
- for (const entry of getEnumerableArrayEntries(value, path189)) {
140279
+ for (const entry of getEnumerableArrayEntries(value, path190)) {
140190
140280
  defineOwnDataProperty(
140191
140281
  copy,
140192
140282
  entry.key,
140193
- copyFromSandbox(entry.value, state, joinArrayPath(path189, entry.key), options, depth + 1)
140283
+ copyFromSandbox(entry.value, state, joinArrayPath(path190, entry.key), options, depth + 1)
140194
140284
  );
140195
140285
  }
140196
140286
  return copy;
@@ -140203,7 +140293,7 @@ function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
140203
140293
  copySandboxArgumentProperties(
140204
140294
  value,
140205
140295
  copy,
140206
- (entry, key3) => copyFromSandbox(entry, state, joinPath(path189, key3), options, depth + 1)
140296
+ (entry, key3) => copyFromSandbox(entry, state, joinPath(path190, key3), options, depth + 1)
140207
140297
  );
140208
140298
  return copy;
140209
140299
  }
@@ -140214,16 +140304,16 @@ function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
140214
140304
  }
140215
140305
  const copy = createPlainObject(Object.getPrototypeOf(value) === null);
140216
140306
  state.seen.set(value, copy);
140217
- for (const entry of getEnumerableObjectEntries(value, path189)) {
140307
+ for (const entry of getEnumerableObjectEntries(value, path190)) {
140218
140308
  defineOwnDataProperty(
140219
140309
  copy,
140220
140310
  entry.key,
140221
- copyFromSandbox(entry.value, state, joinPath(path189, entry.key), options, depth + 1)
140311
+ copyFromSandbox(entry.value, state, joinPath(path190, entry.key), options, depth + 1)
140222
140312
  );
140223
140313
  }
140224
140314
  return copy;
140225
140315
  }
140226
- throw new TypeError(`Unsupported sandbox value at ${path189}: ${describeValue(value)}`);
140316
+ throw new TypeError(`Unsupported sandbox value at ${path190}: ${describeValue(value)}`);
140227
140317
  }
140228
140318
  function isSandboxPrimitive(value) {
140229
140319
  return value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -140303,7 +140393,7 @@ function defineOwnDataProperty(target, key3, value) {
140303
140393
  value
140304
140394
  });
140305
140395
  }
140306
- function getEnumerableObjectEntries(value, path189) {
140396
+ function getEnumerableObjectEntries(value, path190) {
140307
140397
  const descriptors = Object.getOwnPropertyDescriptors(value);
140308
140398
  const entries = [];
140309
140399
  for (const [key3, descriptor] of Object.entries(descriptors)) {
@@ -140311,7 +140401,7 @@ function getEnumerableObjectEntries(value, path189) {
140311
140401
  continue;
140312
140402
  }
140313
140403
  if ("get" in descriptor || "set" in descriptor) {
140314
- throw new TypeError(`Unsupported sandbox value at ${joinPath(path189, key3)}: accessor property`);
140404
+ throw new TypeError(`Unsupported sandbox value at ${joinPath(path190, key3)}: accessor property`);
140315
140405
  }
140316
140406
  entries.push({
140317
140407
  key: key3,
@@ -140320,7 +140410,7 @@ function getEnumerableObjectEntries(value, path189) {
140320
140410
  }
140321
140411
  return entries;
140322
140412
  }
140323
- function getEnumerableArrayEntries(value, path189) {
140413
+ function getEnumerableArrayEntries(value, path190) {
140324
140414
  const descriptors = Object.getOwnPropertyDescriptors(value);
140325
140415
  const entries = [];
140326
140416
  for (const [key3, descriptor] of Object.entries(descriptors)) {
@@ -140329,7 +140419,7 @@ function getEnumerableArrayEntries(value, path189) {
140329
140419
  }
140330
140420
  if ("get" in descriptor || "set" in descriptor) {
140331
140421
  throw new TypeError(
140332
- `Unsupported sandbox value at ${joinArrayPath(path189, key3)}: accessor property`
140422
+ `Unsupported sandbox value at ${joinArrayPath(path190, key3)}: accessor property`
140333
140423
  );
140334
140424
  }
140335
140425
  entries.push({
@@ -140358,11 +140448,11 @@ function describeValue(value) {
140358
140448
  }
140359
140449
  return typeof value;
140360
140450
  }
140361
- function joinPath(path189, key3) {
140362
- return path189 === "<root>" ? `<root>.${key3}` : `${path189}.${key3}`;
140451
+ function joinPath(path190, key3) {
140452
+ return path190 === "<root>" ? `<root>.${key3}` : `${path190}.${key3}`;
140363
140453
  }
140364
- function joinArrayPath(path189, key3) {
140365
- return isArrayIndexKey(key3) ? `${path189}[${key3}]` : joinPath(path189, key3);
140454
+ function joinArrayPath(path190, key3) {
140455
+ return isArrayIndexKey(key3) ? `${path190}[${key3}]` : joinPath(path190, key3);
140366
140456
  }
140367
140457
  var sandboxClosureBrand, sandboxGeneratorBrand, sandboxMapBrand, sandboxPromiseBrand, sandboxRegexBrand, sandboxRegexPattern, sandboxSetBrand, sandboxRetainedValues;
140368
140458
  var init_values = __esm({
@@ -141164,18 +141254,25 @@ function readHostOperationPolicy(operation) {
141164
141254
  return hostOperationPolicies.get(operation);
141165
141255
  }
141166
141256
  function wrapCallerInjectedBindings(bindings, options) {
141257
+ options = { ...options, registerCapabilities: true };
141167
141258
  const state = { seen: /* @__PURE__ */ new WeakMap() };
141168
141259
  const copied = Object.fromEntries(
141169
141260
  Object.entries(bindings).map(([name, value]) => [
141170
141261
  name,
141171
- typeof value === "function" ? wrapCallerInjectedFunction(name, value, options, state) : copyHostValueToSandbox(value, [], { ...options, operation: name }, state, "<root>")
141262
+ typeof value === "function" ? wrapCallerInjectedFunction(name, value, { ...options, capabilityPath: [name] }, state) : copyHostValueToSandbox(
141263
+ value,
141264
+ [],
141265
+ { ...options, operation: name, capabilityPath: [name] },
141266
+ state,
141267
+ "<root>"
141268
+ )
141172
141269
  ])
141173
141270
  );
141174
141271
  options.budget.provisionDataUsage(measureSandboxData(Object.values(copied)));
141175
141272
  return copied;
141176
141273
  }
141177
141274
  function wrapCallerInjectedFunction(name, value, options, state) {
141178
- const existing = state.seen.get(value);
141275
+ const existing = state.seen.get(value) ?? options.hostCalls?.nativeClosures.get(value);
141179
141276
  if (existing !== void 0) return existing;
141180
141277
  const bindingName = name === "default" && value.name.length > 0 ? value.name : name;
141181
141278
  const callable = value;
@@ -141290,6 +141387,16 @@ function wrapCallerInjectedFunction(name, value, options, state) {
141290
141387
  name: bindingName,
141291
141388
  properties: (closure) => {
141292
141389
  state.seen.set(value, closure);
141390
+ if (options.registerCapabilities) {
141391
+ options.hostCalls?.registerHostCapability(
141392
+ JSON.stringify([
141393
+ options.moduleId ?? "<bindings>",
141394
+ ...options.capabilityPath ?? [bindingName]
141395
+ ]),
141396
+ closure,
141397
+ value
141398
+ );
141399
+ }
141293
141400
  return copyFunctionProperties(callable, [], options, state, options.operation ?? bindingName) ?? {};
141294
141401
  }
141295
141402
  });
@@ -141460,7 +141567,7 @@ function copyHostResultToSandbox(result, stackFrames, options) {
141460
141567
  const value = copyHostValueToSandbox(
141461
141568
  result,
141462
141569
  stackFrames,
141463
- options,
141570
+ { ...options, registerCapabilities: false },
141464
141571
  {
141465
141572
  seen: /* @__PURE__ */ new WeakMap()
141466
141573
  },
@@ -141673,7 +141780,7 @@ function wrapHostPromiseWithSignal(promise, signal) {
141673
141780
  );
141674
141781
  });
141675
141782
  }
141676
- function copyHostValueToSandbox(value, stackFrames, options, state, path189) {
141783
+ function copyHostValueToSandbox(value, stackFrames, options, state, path190) {
141677
141784
  const { budget } = options;
141678
141785
  if (value === null || value === void 0 || typeof value === "number" || typeof value === "boolean") {
141679
141786
  return value;
@@ -141699,11 +141806,11 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path189) {
141699
141806
  return existing;
141700
141807
  }
141701
141808
  return wrapCallerInjectedFunction(
141702
- callable.name.length > 0 ? callable.name : readPathName(path189),
141809
+ callable.name.length > 0 ? callable.name : readPathName(path190),
141703
141810
  callable,
141704
141811
  {
141705
141812
  ...options,
141706
- operation: path189.startsWith("<root>") ? `${options.operation ?? "<root>"}${path189.slice(6)}` : path189
141813
+ operation: path190.startsWith("<root>") ? `${options.operation ?? "<root>"}${path190.slice(6)}` : path190
141707
141814
  },
141708
141815
  state
141709
141816
  );
@@ -141755,14 +141862,14 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path189) {
141755
141862
  const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
141756
141863
  if (descriptor === void 0) continue;
141757
141864
  if (!("value" in descriptor)) {
141758
- throw new TypeError(`Unsupported sandbox value at ${path189}[${index}]: accessor property`);
141865
+ throw new TypeError(`Unsupported sandbox value at ${path190}[${index}]: accessor property`);
141759
141866
  }
141760
141867
  copy[index] = copyHostValueToSandbox(
141761
141868
  descriptor.value,
141762
141869
  stackFrames,
141763
- options,
141870
+ { ...options, capabilityPath: [...options.capabilityPath ?? [], String(index)] },
141764
141871
  state,
141765
- `${path189}[${index}]`
141872
+ `${path190}[${index}]`
141766
141873
  );
141767
141874
  }
141768
141875
  return copy;
@@ -141776,9 +141883,22 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path189) {
141776
141883
  state.seen.set(value, copy);
141777
141884
  budget.allocateCollectionEntries(value.size);
141778
141885
  for (const [key3, entry] of value) {
141886
+ const ordinal = copy.entries.size;
141779
141887
  copy.entries.set(
141780
- copyHostValueToSandbox(key3, stackFrames, options, state, `${path189}.<key>`),
141781
- copyHostValueToSandbox(entry, stackFrames, options, state, `${path189}.<value>`)
141888
+ copyHostValueToSandbox(
141889
+ key3,
141890
+ stackFrames,
141891
+ { ...options, capabilityPath: [...options.capabilityPath ?? [], `key:${ordinal}`] },
141892
+ state,
141893
+ `${path190}.<key>`
141894
+ ),
141895
+ copyHostValueToSandbox(
141896
+ entry,
141897
+ stackFrames,
141898
+ { ...options, capabilityPath: [...options.capabilityPath ?? [], `value:${ordinal}`] },
141899
+ state,
141900
+ `${path190}.<value>`
141901
+ )
141782
141902
  );
141783
141903
  }
141784
141904
  return copy;
@@ -141793,7 +141913,16 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path189) {
141793
141913
  budget.allocateCollectionEntries(value.size);
141794
141914
  for (const entry of value) {
141795
141915
  copy.values.add(
141796
- copyHostValueToSandbox(entry, stackFrames, options, state, `${path189}.<value>`)
141916
+ copyHostValueToSandbox(
141917
+ entry,
141918
+ stackFrames,
141919
+ {
141920
+ ...options,
141921
+ capabilityPath: [...options.capabilityPath ?? [], String(copy.values.size)]
141922
+ },
141923
+ state,
141924
+ `${path190}.<value>`
141925
+ )
141797
141926
  );
141798
141927
  }
141799
141928
  return copy;
@@ -141811,7 +141940,7 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path189) {
141811
141940
  }
141812
141941
  if ("get" in descriptor || "set" in descriptor) {
141813
141942
  throw new TypeError(
141814
- `Unsupported sandbox value at ${joinPath2(path189, key3)}: accessor property`
141943
+ `Unsupported sandbox value at ${joinPath2(path190, key3)}: accessor property`
141815
141944
  );
141816
141945
  }
141817
141946
  Object.defineProperty(copy, budget.allocateString(key3), {
@@ -141821,15 +141950,15 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path189) {
141821
141950
  value: copyHostValueToSandbox(
141822
141951
  descriptor.value,
141823
141952
  stackFrames,
141824
- options,
141953
+ { ...options, capabilityPath: [...options.capabilityPath ?? [], key3] },
141825
141954
  state,
141826
- joinPath2(path189, key3)
141955
+ joinPath2(path190, key3)
141827
141956
  )
141828
141957
  });
141829
141958
  }
141830
141959
  return copy;
141831
141960
  }
141832
- throw new TypeError(`Unsupported sandbox value at ${path189}: ${describeValue2(value)}`);
141961
+ throw new TypeError(`Unsupported sandbox value at ${path190}: ${describeValue2(value)}`);
141833
141962
  }
141834
141963
  function readAbortReason2(signal) {
141835
141964
  return signal.reason ?? createAbortError11();
@@ -141878,7 +142007,7 @@ function readStringProperty(value, key3) {
141878
142007
  const entry = value[key3];
141879
142008
  return typeof entry === "string" ? entry : void 0;
141880
142009
  }
141881
- function copyFunctionProperties(callable, stackFrames, options, state, path189) {
142010
+ function copyFunctionProperties(callable, stackFrames, options, state, path190) {
141882
142011
  const properties = {};
141883
142012
  for (const key3 of Object.getOwnPropertyNames(callable)) {
141884
142013
  const descriptor = Object.getOwnPropertyDescriptor(callable, key3);
@@ -141894,9 +142023,9 @@ function copyFunctionProperties(callable, stackFrames, options, state, path189)
141894
142023
  properties[key3] = copyHostValueToSandbox(
141895
142024
  descriptor.value,
141896
142025
  stackFrames,
141897
- options,
142026
+ { ...options, capabilityPath: [...options.capabilityPath ?? [], key3] },
141898
142027
  state,
141899
- joinPath2(path189, key3)
142028
+ joinPath2(path190, key3)
141900
142029
  );
141901
142030
  }
141902
142031
  return Object.keys(properties).length > 0 ? properties : void 0;
@@ -141908,11 +142037,11 @@ function isPlainObject11(value) {
141908
142037
  const prototype = Object.getPrototypeOf(value);
141909
142038
  return prototype === Object.prototype || prototype === null;
141910
142039
  }
141911
- function joinPath2(path189, key3) {
141912
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key3) ? `${path189}.${key3}` : `${path189}[${JSON.stringify(key3)}]`;
142040
+ function joinPath2(path190, key3) {
142041
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key3) ? `${path190}.${key3}` : `${path190}[${JSON.stringify(key3)}]`;
141913
142042
  }
141914
- function readPathName(path189) {
141915
- const segment = path189.replace(/^.*\./u, "");
142043
+ function readPathName(path190) {
142044
+ const segment = path190.replace(/^.*\./u, "");
141916
142045
  return segment === "<root>" ? "host" : segment;
141917
142046
  }
141918
142047
  function describeValue2(value) {
@@ -147430,16 +147559,16 @@ async function writeSnapshotOnce(temporaryPath, snapshotPath, contents) {
147430
147559
  }
147431
147560
  }
147432
147561
  }
147433
- async function enqueueOperation(path189, operation) {
147434
- const previous = pendingOperations.get(path189) ?? Promise.resolve();
147562
+ async function enqueueOperation(path190, operation) {
147563
+ const previous = pendingOperations.get(path190) ?? Promise.resolve();
147435
147564
  const pending = previous.catch(() => void 0).then(operation);
147436
147565
  const queued = pending.catch(() => void 0);
147437
- pendingOperations.set(path189, queued);
147566
+ pendingOperations.set(path190, queued);
147438
147567
  try {
147439
147568
  await pending;
147440
147569
  } finally {
147441
- if (pendingOperations.get(path189) === queued) {
147442
- pendingOperations.delete(path189);
147570
+ if (pendingOperations.get(path190) === queued) {
147571
+ pendingOperations.delete(path190);
147443
147572
  }
147444
147573
  }
147445
147574
  }
@@ -147476,8 +147605,8 @@ var init_backend = __esm({
147476
147605
  LOCKED_FILE_ERROR_CODES = /* @__PURE__ */ new Set(["EACCES", "EBUSY", "EPERM"]);
147477
147606
  pendingOperations = /* @__PURE__ */ new Map();
147478
147607
  FileSnapshotBackend = class {
147479
- constructor(path189, options = {}) {
147480
- this.path = path189;
147608
+ constructor(path190, options = {}) {
147609
+ this.path = path190;
147481
147610
  this.#writeMaxAttempts = options.writeMaxAttempts ?? DEFAULT_WRITE_MAX_ATTEMPTS;
147482
147611
  this.#writeRetryDelayMs = options.writeRetryDelayMs ?? DEFAULT_WRITE_RETRY_DELAY_MS;
147483
147612
  }
@@ -147625,34 +147754,34 @@ var init_serialize = __esm({
147625
147754
  init_values();
147626
147755
  UnsnapshotableValueError = class extends Error {
147627
147756
  path;
147628
- constructor(path189) {
147757
+ constructor(path190) {
147629
147758
  super(
147630
147759
  "Cannot snapshot a generator suspended mid-iteration; drain or discard it before the await boundary."
147631
147760
  );
147632
147761
  this.name = "UnsnapshotableValueError";
147633
- this.path = path189;
147762
+ this.path = path190;
147634
147763
  }
147635
147764
  };
147636
147765
  }
147637
147766
  });
147638
147767
 
147639
147768
  // packages/safejs/src/snapshot/replay-inputs.ts
147640
- function prepareReplayInputs(current, saved, preparePromise) {
147769
+ function prepareReplayInputs(current, saved, preparePromise, onCapabilityRestored) {
147641
147770
  const identities = /* @__PURE__ */ new WeakMap();
147642
147771
  const capabilities = /* @__PURE__ */ new Map();
147643
147772
  const promises = /* @__PURE__ */ new Map();
147644
147773
  if (saved === void 0) {
147645
147774
  const snapshot2 = encodeReplayData(current, {
147646
147775
  captureCapabilityProperties: true,
147647
- identifyCapability: (closure, path189) => {
147648
- const id = identities.get(closure) ?? JSON.stringify(path189);
147776
+ identifyCapability: (closure, path190) => {
147777
+ const id = identities.get(closure) ?? JSON.stringify(path190);
147649
147778
  identities.set(closure, id);
147650
147779
  capabilities.set(id, closure);
147651
147780
  return id;
147652
147781
  },
147653
- identifyPromise: (promise, path189) => {
147782
+ identifyPromise: (promise, path190) => {
147654
147783
  if (preparePromise === void 0) return void 0;
147655
- const id = identities.get(promise) ?? JSON.stringify(path189);
147784
+ const id = identities.get(promise) ?? JSON.stringify(path190);
147656
147785
  identities.set(promise, id);
147657
147786
  if (!promises.has(id)) promises.set(id, preparePromise(promise, id));
147658
147787
  return id;
@@ -147667,11 +147796,11 @@ function prepareReplayInputs(current, saved, preparePromise) {
147667
147796
  };
147668
147797
  }
147669
147798
  const readCapability = (id) => {
147670
- const path189 = JSON.parse(id);
147671
- if (!Array.isArray(path189) || path189.length === 0 || path189.some((key3) => typeof key3 !== "string"))
147799
+ const path190 = JSON.parse(id);
147800
+ if (!Array.isArray(path190) || path190.length === 0 || path190.some((key3) => typeof key3 !== "string"))
147672
147801
  throw new TypeError("Invalid replay input capability path.");
147673
147802
  let value = current;
147674
- for (const key3 of path189) {
147803
+ for (const key3 of path190) {
147675
147804
  if (isSandboxMap(value)) {
147676
147805
  const [kind, ordinal] = key3.split(":");
147677
147806
  const index = Number(ordinal);
@@ -147708,6 +147837,7 @@ function prepareReplayInputs(current, saved, preparePromise) {
147708
147837
  assertReplayInputShape(validated);
147709
147838
  const restored = decodeReplayData(saved, {
147710
147839
  resolveCapability,
147840
+ onCapabilityRestored,
147711
147841
  resolvePromise: (id) => {
147712
147842
  const value = readCapability(id);
147713
147843
  if (!promises.has(id) && preparePromise !== void 0)
@@ -147743,7 +147873,7 @@ function run(source, options = {}) {
147743
147873
  const lifecycle = { hostCallbackDepth: 0 };
147744
147874
  const dumpController = createDumpController(lifecycle);
147745
147875
  const promiseTracker = createSandboxPromiseRejectionTracker();
147746
- const result = withSandboxPromiseRejectionTracker(promiseTracker, async () => {
147876
+ const execute2 = async () => {
147747
147877
  const promiseReplay = new PromiseReplay(options.snapshot?.promiseReplay);
147748
147878
  return promiseReplayContext.run(promiseReplay, async () => {
147749
147879
  const deactivateOtelSink = activateOtelSink(options.otelSink);
@@ -147843,8 +147973,10 @@ function run(source, options = {}) {
147843
147973
  if (!isSandboxClosure(binding))
147844
147974
  throw new TypeError("Invalid initial promise operation.");
147845
147975
  return binding.call([]);
147846
- }
147976
+ },
147977
+ hostCalls.rebindHostCapability.bind(hostCalls)
147847
147978
  );
147979
+ hostCalls.validateHostCapabilities();
147848
147980
  budget.setRetainedDataUsage(
147849
147981
  initialInputs,
147850
147982
  measureSandboxData(
@@ -148023,7 +148155,11 @@ function run(source, options = {}) {
148023
148155
  deactivateOtelSink();
148024
148156
  }
148025
148157
  });
148026
- });
148158
+ };
148159
+ const result = withRunResources(
148160
+ options.signal,
148161
+ () => withSandboxPromiseRejectionTracker(promiseTracker, execute2)
148162
+ );
148027
148163
  return attachDumpController(result, dumpController);
148028
148164
  }
148029
148165
  async function throwIfReturnedPromiseRejected(result) {
@@ -148201,6 +148337,7 @@ var init_run7 = __esm({
148201
148337
  "packages/safejs/src/run.ts"() {
148202
148338
  "use strict";
148203
148339
  init_hash();
148340
+ init_resources();
148204
148341
  init_random();
148205
148342
  init_shape();
148206
148343
  init_parser3();
@@ -148399,7 +148536,7 @@ var init_find_exported = __esm({
148399
148536
  });
148400
148537
 
148401
148538
  // packages/safejs/src/modules/agent.ts
148402
- import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
148539
+ import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
148403
148540
  function createSpawnUsageAccumulator() {
148404
148541
  let inputTokens = 0;
148405
148542
  let outputTokens = 0;
@@ -149302,7 +149439,7 @@ var init_agent3 = __esm({
149302
149439
  hostErrorData.set(this, { result });
149303
149440
  }
149304
149441
  };
149305
- activeUsageAccumulator = new AsyncLocalStorage7();
149442
+ activeUsageAccumulator = new AsyncLocalStorage8();
149306
149443
  oneAttemptRetryOptions = {
149307
149444
  maxAttempts: 1,
149308
149445
  backoffMs: 0,
@@ -149352,9 +149489,9 @@ var init_fail = __esm({
149352
149489
 
149353
149490
  // packages/safejs/src/modules/canonical-path.ts
149354
149491
  import { basename as basename8, dirname as dirname13, isAbsolute as isAbsolute9, relative as relative7, resolve as resolve13, sep as sep6 } from "node:path";
149355
- async function resolveCanonicalPath({ realpath: realpath20, readlink: readlink5 }, path189) {
149492
+ async function resolveCanonicalPath({ realpath: realpath20, readlink: readlink5 }, path190) {
149356
149493
  const missingSegments = [];
149357
- let current = path189;
149494
+ let current = path190;
149358
149495
  let follows = 0;
149359
149496
  while (true) {
149360
149497
  try {
@@ -149367,23 +149504,23 @@ async function resolveCanonicalPath({ realpath: realpath20, readlink: readlink5
149367
149504
  const target = await readSymlinkTarget2(readlink5, current);
149368
149505
  if (target !== void 0) {
149369
149506
  if (++follows > MAX_SYMLINK_FOLLOWS) {
149370
- throw createLoopError(path189);
149507
+ throw createLoopError(path190);
149371
149508
  }
149372
149509
  current = isAbsolute9(target) ? resolve13(target) : resolve13(dirname13(current), target);
149373
149510
  continue;
149374
149511
  }
149375
149512
  const parent = dirname13(current);
149376
149513
  if (parent === current) {
149377
- return resolve13(path189);
149514
+ return resolve13(path190);
149378
149515
  }
149379
149516
  missingSegments.push(basename8(current));
149380
149517
  current = parent;
149381
149518
  }
149382
149519
  }
149383
149520
  }
149384
- async function readSymlinkTarget2(readlink5, path189) {
149521
+ async function readSymlinkTarget2(readlink5, path190) {
149385
149522
  try {
149386
- return await readlink5(path189);
149523
+ return await readlink5(path190);
149387
149524
  } catch (error3) {
149388
149525
  if (NOT_A_SYMLINK_CODES.includes(getOwnErrorCode2(error3) ?? "")) {
149389
149526
  return void 0;
@@ -149391,9 +149528,9 @@ async function readSymlinkTarget2(readlink5, path189) {
149391
149528
  throw error3;
149392
149529
  }
149393
149530
  }
149394
- function createLoopError(path189) {
149531
+ function createLoopError(path190) {
149395
149532
  const error3 = new Error(
149396
- `ELOOP: too many symbolic links encountered, realpath '${path189}'`
149533
+ `ELOOP: too many symbolic links encountered, realpath '${path190}'`
149397
149534
  );
149398
149535
  error3.code = "ELOOP";
149399
149536
  return error3;
@@ -149436,9 +149573,9 @@ async function descendsFromRoot(stat36, canonicalRoot, canonicalPath) {
149436
149573
  current = parent;
149437
149574
  }
149438
149575
  }
149439
- async function readIdentity(stat36, path189) {
149576
+ async function readIdentity(stat36, path190) {
149440
149577
  try {
149441
- const { dev, ino } = await stat36(path189);
149578
+ const { dev, ino } = await stat36(path190);
149442
149579
  return { dev, ino };
149443
149580
  } catch (error3) {
149444
149581
  if (MISSING_PATH_CODES.includes(getOwnErrorCode2(error3) ?? "")) {
@@ -149586,32 +149723,32 @@ async function resolvePathArguments(fs31, root, name, args) {
149586
149723
  return resolved;
149587
149724
  }
149588
149725
  const paths = FS_PATH_ARGUMENTS[name].map((_, index) => {
149589
- const path189 = readPath(canonicalRoot, args[index]);
149590
- resolved[index] = path189;
149591
- return path189;
149726
+ const path190 = readPath(canonicalRoot, args[index]);
149727
+ resolved[index] = path190;
149728
+ return path190;
149592
149729
  });
149593
149730
  await assertInsideRoot2(fs31, canonicalRoot, name, paths);
149594
149731
  return resolved;
149595
149732
  }
149596
149733
  async function assertInsideRoot2(fs31, canonicalRoot, name, paths) {
149597
- for (const path189 of paths) {
149598
- if (await escapesRoot(fs31, canonicalRoot, path189)) {
149734
+ for (const path190 of paths) {
149735
+ if (await escapesRoot(fs31, canonicalRoot, path190)) {
149599
149736
  throw createAccessDeniedError(name, paths[0], paths[1]);
149600
149737
  }
149601
149738
  }
149602
149739
  }
149603
- async function escapesRoot(fs31, canonicalRoot, path189) {
149604
- const canonicalPath = await resolveCanonicalPath(readCanonicalPathFs(fs31), path189);
149740
+ async function escapesRoot(fs31, canonicalRoot, path190) {
149741
+ const canonicalPath = await resolveCanonicalPath(readCanonicalPathFs(fs31), path190);
149605
149742
  return !await containsPath(readStat(fs31), canonicalRoot, canonicalPath);
149606
149743
  }
149607
149744
  function readCanonicalPathFs(fs31) {
149608
149745
  return {
149609
- realpath: async (path189) => await invoke(fs31, "realpath", [path189]),
149610
- readlink: async (path189) => await invoke(fs31, "readlink", [path189])
149746
+ realpath: async (path190) => await invoke(fs31, "realpath", [path190]),
149747
+ readlink: async (path190) => await invoke(fs31, "readlink", [path190])
149611
149748
  };
149612
149749
  }
149613
149750
  function readStat(fs31) {
149614
- return async (path189) => await invoke(fs31, "stat", [path189]);
149751
+ return async (path190) => await invoke(fs31, "stat", [path190]);
149615
149752
  }
149616
149753
  function assertSupportedPath(name, argument, value) {
149617
149754
  if (typeof value === "string") {
@@ -149662,19 +149799,19 @@ function describeReceivedValue(value) {
149662
149799
  return `type ${typeof value} (${inspect(value)})`;
149663
149800
  }
149664
149801
  function readPath(base, value) {
149665
- const path189 = value;
149666
- return isAbsolute10(path189) ? resolve14(path189) : resolve14(base, path189);
149802
+ const path190 = value;
149803
+ return isAbsolute10(path190) ? resolve14(path190) : resolve14(base, path190);
149667
149804
  }
149668
- function createAccessDeniedError(name, path189, dest) {
149805
+ function createAccessDeniedError(name, path190, dest) {
149669
149806
  const syscall = FS_SYSCALLS[name];
149670
- const target = dest === void 0 ? `'${path189}'` : `'${path189}' -> '${dest}'`;
149807
+ const target = dest === void 0 ? `'${path190}'` : `'${path190}' -> '${dest}'`;
149671
149808
  const error3 = new Error(
149672
149809
  `${ACCESS_DENIED_CODE}: ${ACCESS_DENIED_MESSAGE}, ${syscall} ${target}`
149673
149810
  );
149674
149811
  error3.code = ACCESS_DENIED_CODE;
149675
149812
  error3.errno = ACCESS_DENIED_ERRNO;
149676
149813
  error3.syscall = syscall;
149677
- error3.path = path189;
149814
+ error3.path = path190;
149678
149815
  if (dest !== void 0) {
149679
149816
  error3.dest = dest;
149680
149817
  }
@@ -150032,9 +150169,9 @@ function makeGitModule(cwd) {
150032
150169
  branch: normalizedBranch
150033
150170
  };
150034
150171
  },
150035
- async worktreeRemove(path189) {
150172
+ async worktreeRemove(path190) {
150036
150173
  const repoRoot = await getRepoRoot(normalizedCwd);
150037
- const worktreePath = await resolveWorktreePath(repoRoot, path189, "Git worktree path");
150174
+ const worktreePath = await resolveWorktreePath(repoRoot, path190, "Git worktree path");
150038
150175
  const worktrees = await listWorktrees2(normalizedCwd);
150039
150176
  if (!worktrees.some((worktree) => resolve15(worktree.path) === worktreePath)) {
150040
150177
  return;
@@ -150081,10 +150218,10 @@ function normalizeWorktreeCreateOptions(options) {
150081
150218
  throw new Error("Git worktree create options must be an object.");
150082
150219
  }
150083
150220
  const base = getOwnProperty8(options, "base");
150084
- const path189 = getOwnProperty8(options, "path");
150221
+ const path190 = getOwnProperty8(options, "path");
150085
150222
  return {
150086
150223
  base: base === void 0 ? "HEAD" : readNonEmptyString6(base, "Git worktree create options base"),
150087
- path: path189 === void 0 ? void 0 : readNonEmptyString6(path189, "Git worktree create options path")
150224
+ path: path190 === void 0 ? void 0 : readNonEmptyString6(path190, "Git worktree create options path")
150088
150225
  };
150089
150226
  }
150090
150227
  function createSavepointRef() {
@@ -150144,9 +150281,9 @@ function parseBranchRef(ref) {
150144
150281
  const branchPrefix = "refs/heads/";
150145
150282
  return ref.startsWith(branchPrefix) ? ref.slice(branchPrefix.length) : ref;
150146
150283
  }
150147
- async function resolveWorktreePath(repoRoot, path189, label) {
150284
+ async function resolveWorktreePath(repoRoot, path190, label) {
150148
150285
  const resolvedRoot = resolve15(repoRoot);
150149
- const resolvedPath = isAbsolute11(path189) ? resolve15(path189) : resolve15(resolvedRoot, path189);
150286
+ const resolvedPath = isAbsolute11(path190) ? resolve15(path190) : resolve15(resolvedRoot, path190);
150150
150287
  const canonicalRoot = await realpath19(resolvedRoot);
150151
150288
  const canonicalPath = await resolveCanonicalPath({ realpath: realpath19, readlink: readlink4 }, resolvedPath);
150152
150289
  const [inside, isRootItself] = await Promise.all([
@@ -150512,10 +150649,650 @@ var init_metric = __esm({
150512
150649
  }
150513
150650
  });
150514
150651
 
150652
+ // packages/safejs/src/modules/mcp-transport.ts
150653
+ import { spawn as spawn11 } from "node:child_process";
150654
+ import path184 from "node:path";
150655
+ function parseMcpConfig3(source, directory) {
150656
+ const parsed = JSON.parse(source);
150657
+ const options = normalizeMcpOptions(parsed, [
150658
+ "servers",
150659
+ "requestTimeoutMs",
150660
+ "closeTimeoutMs",
150661
+ "maxToolPages"
150662
+ ]);
150663
+ for (const server of Object.values(options.servers)) {
150664
+ if ("command" in server) {
150665
+ server.cwd = path184.resolve(directory, server.cwd ?? ".");
150666
+ if (server.command.includes("/") || server.command.includes("\\")) {
150667
+ server.command = path184.resolve(directory, server.command);
150668
+ }
150669
+ }
150670
+ }
150671
+ return options;
150672
+ }
150673
+ function normalizeMcpOptions(value, keys = [
150674
+ "servers",
150675
+ "requestTimeoutMs",
150676
+ "closeTimeoutMs",
150677
+ "maxToolPages",
150678
+ "signal",
150679
+ "fetch",
150680
+ "spawn"
150681
+ ]) {
150682
+ const options = readRecord2(value, "MCP options", keys);
150683
+ const servers = readRecord2(options.servers, "MCP servers");
150684
+ const normalized = /* @__PURE__ */ Object.create(null);
150685
+ for (const [name, input] of Object.entries(servers)) {
150686
+ if (name.length === 0 || name.trim() !== name)
150687
+ throw new TypeError("MCP server names must be non-empty without surrounding whitespace.");
150688
+ const server = readRecord2(input, `MCP server ${name}`);
150689
+ if (Object.hasOwn(server, "command")) {
150690
+ readRecord2(server, `MCP server ${name}`, ["command", "args", "cwd", "env"]);
150691
+ const command = readText(server.command, "MCP command");
150692
+ if (server.args !== void 0 && (!Array.isArray(server.args) || server.args.some((argument) => typeof argument !== "string")))
150693
+ throw new TypeError("MCP args must be an array of strings.");
150694
+ normalized[name] = {
150695
+ command,
150696
+ ...server.args === void 0 ? {} : { args: [...server.args] },
150697
+ ...server.cwd === void 0 ? {} : { cwd: readText(server.cwd, "MCP cwd") },
150698
+ env: readStrings(server.env ?? {}, "MCP environment")
150699
+ };
150700
+ } else {
150701
+ readRecord2(server, `MCP server ${name}`, ["url", "headers"]);
150702
+ const url = new URL(readText(server.url, "MCP URL"));
150703
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash)
150704
+ throw new TypeError("MCP URL must use HTTP or HTTPS without credentials or a fragment.");
150705
+ const headers = readStrings(server.headers ?? {}, "MCP headers");
150706
+ new Headers(headers);
150707
+ normalized[name] = { url: url.href, headers };
150708
+ }
150709
+ }
150710
+ for (const name of ["fetch", "spawn"])
150711
+ if (options[name] !== void 0 && typeof options[name] !== "function")
150712
+ throw new TypeError(`MCP ${name} must be a function.`);
150713
+ if (options.signal !== void 0 && !(options.signal instanceof AbortSignal))
150714
+ throw new TypeError("MCP signal must be an AbortSignal.");
150715
+ return {
150716
+ servers: normalized,
150717
+ requestTimeoutMs: readTimeout(options.requestTimeoutMs, 3e4),
150718
+ closeTimeoutMs: readTimeout(options.closeTimeoutMs, 1e3),
150719
+ maxToolPages: readTimeout(options.maxToolPages, 100),
150720
+ ...options.signal === void 0 ? {} : { signal: options.signal },
150721
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch },
150722
+ ...options.spawn === void 0 ? {} : { spawn: options.spawn }
150723
+ };
150724
+ }
150725
+ function readRecord2(value, label, keys) {
150726
+ if (typeof value !== "object" || value === null || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
150727
+ throw new TypeError(`${label} must be a plain object.`);
150728
+ const result = /* @__PURE__ */ Object.create(null);
150729
+ for (const [key3, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
150730
+ if (!("value" in descriptor) || keys !== void 0 && !keys.includes(key3))
150731
+ throw new TypeError(`${label} contains unsupported field ${key3}.`);
150732
+ result[key3] = descriptor.value;
150733
+ }
150734
+ return result;
150735
+ }
150736
+ function readText(value, label) {
150737
+ if (typeof value !== "string" || value.trim().length === 0 || value.includes("\0"))
150738
+ throw new TypeError(`${label} must be a non-empty string without NUL characters.`);
150739
+ return value;
150740
+ }
150741
+ function readStrings(value, label) {
150742
+ const entries = readRecord2(value, label);
150743
+ for (const [name, entry] of Object.entries(entries))
150744
+ if (typeof entry !== "string" || name.includes("\0") || entry.includes("\0"))
150745
+ throw new TypeError(`${label} must contain strings without NUL characters.`);
150746
+ return entries;
150747
+ }
150748
+ function readTimeout(value, fallback) {
150749
+ if (value === void 0) return fallback;
150750
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0 || value > 2147483647)
150751
+ throw new TypeError("MCP timeouts must be positive 32-bit integers.");
150752
+ return value;
150753
+ }
150754
+ function connectMcpTransport(server, options, signal) {
150755
+ signal?.throwIfAborted();
150756
+ options.signal?.throwIfAborted();
150757
+ const client = new McpClient({
150758
+ clientInfo: { name: "safejs", version: "1" },
150759
+ requestTimeoutMs: options.requestTimeoutMs
150760
+ });
150761
+ let child;
150762
+ const activeRequests = /* @__PURE__ */ new Set();
150763
+ const transport = "command" in server ? new StdioTransport({
150764
+ ...server,
150765
+ spawn(command, args, spawnOptions) {
150766
+ child = options.spawn === void 0 ? spawn11(command, args, spawnOptions) : options.spawn(command, args, spawnOptions);
150767
+ return child;
150768
+ }
150769
+ }) : new HttpTransport({
150770
+ ...server,
150771
+ async fetch(input, init) {
150772
+ const controller = new AbortController();
150773
+ activeRequests.add(controller);
150774
+ const cancel3 = () => controller.abort(init?.signal?.reason);
150775
+ init?.signal?.addEventListener("abort", cancel3, { once: true });
150776
+ if (init?.signal?.aborted) cancel3();
150777
+ const timeout = setTimeout(
150778
+ () => controller.abort(new Error("MCP HTTP request timed out.")),
150779
+ init?.method === "DELETE" ? options.closeTimeoutMs : options.requestTimeoutMs
150780
+ );
150781
+ const finish = () => {
150782
+ clearTimeout(timeout);
150783
+ activeRequests.delete(controller);
150784
+ init?.signal?.removeEventListener("abort", cancel3);
150785
+ };
150786
+ try {
150787
+ const response = await (options.fetch ?? fetch)(input, {
150788
+ ...init,
150789
+ signal: controller.signal,
150790
+ redirect: "error"
150791
+ });
150792
+ if (response.body === null) {
150793
+ finish();
150794
+ return response;
150795
+ }
150796
+ const reader = response.body.getReader();
150797
+ let stopReading;
150798
+ const release2 = () => {
150799
+ finish();
150800
+ if (stopReading !== void 0)
150801
+ controller.signal.removeEventListener("abort", stopReading);
150802
+ };
150803
+ const body = new ReadableStream({
150804
+ start(stream) {
150805
+ stopReading = () => {
150806
+ void reader.cancel(controller.signal.reason).catch(() => void 0);
150807
+ stream.error(controller.signal.reason);
150808
+ release2();
150809
+ };
150810
+ controller.signal.addEventListener("abort", stopReading, { once: true });
150811
+ if (controller.signal.aborted) stopReading();
150812
+ },
150813
+ async pull(stream) {
150814
+ try {
150815
+ const result = await reader.read();
150816
+ if (controller.signal.aborted) return;
150817
+ if (result.done) {
150818
+ release2();
150819
+ stream.close();
150820
+ } else stream.enqueue(result.value);
150821
+ } catch (error3) {
150822
+ release2();
150823
+ stream.error(error3);
150824
+ }
150825
+ },
150826
+ async cancel(reason) {
150827
+ release2();
150828
+ await reader.cancel(reason);
150829
+ }
150830
+ });
150831
+ return new Response(body, {
150832
+ status: response.status,
150833
+ statusText: response.statusText,
150834
+ headers: response.headers
150835
+ });
150836
+ } catch (error3) {
150837
+ finish();
150838
+ throw error3;
150839
+ }
150840
+ }
150841
+ });
150842
+ let closing;
150843
+ const cancel2 = () => {
150844
+ void close().catch(() => void 0);
150845
+ };
150846
+ function close() {
150847
+ closing ??= (async () => {
150848
+ signal?.removeEventListener("abort", cancel2);
150849
+ options.signal?.removeEventListener("abort", cancel2);
150850
+ for (const request of activeRequests) request.abort(new Error("MCP connection closed."));
150851
+ await client.close();
150852
+ transport.dispose();
150853
+ await new Promise((resolve17, reject) => {
150854
+ let forced;
150855
+ const timeout = setTimeout(() => {
150856
+ if (child !== void 0 && child.exitCode === null && child.signalCode === null)
150857
+ child.kill("SIGKILL");
150858
+ forced = setTimeout(
150859
+ () => reject(new Error("MCP transport did not close.")),
150860
+ options.closeTimeoutMs
150861
+ );
150862
+ }, options.closeTimeoutMs);
150863
+ void transport.closed.then(
150864
+ () => {
150865
+ clearTimeout(timeout);
150866
+ clearTimeout(forced);
150867
+ resolve17();
150868
+ },
150869
+ (error3) => {
150870
+ clearTimeout(timeout);
150871
+ clearTimeout(forced);
150872
+ reject(error3);
150873
+ }
150874
+ );
150875
+ });
150876
+ })();
150877
+ return closing;
150878
+ }
150879
+ signal?.addEventListener("abort", cancel2, { once: true });
150880
+ options.signal?.addEventListener("abort", cancel2, { once: true });
150881
+ const aborted = signal?.aborted || options.signal?.aborted;
150882
+ if (aborted) cancel2();
150883
+ const connecting = aborted ? Promise.reject(signal?.aborted ? signal.reason : options.signal?.reason) : client.connect(transport);
150884
+ const ready = connecting.then(
150885
+ () => client,
150886
+ async (error3) => {
150887
+ await close().catch(() => void 0);
150888
+ throw signal?.aborted ? signal.reason : options.signal?.aborted ? options.signal.reason : error3;
150889
+ }
150890
+ );
150891
+ return { ready, close };
150892
+ }
150893
+ var init_mcp_transport = __esm({
150894
+ "packages/safejs/src/modules/mcp-transport.ts"() {
150895
+ "use strict";
150896
+ init_src19();
150897
+ }
150898
+ });
150899
+
150515
150900
  // packages/safejs/src/modules/mcp.ts
150901
+ function makeMcpModule(connectMcp) {
150902
+ if (typeof connectMcp !== "function") {
150903
+ const options = normalizeMcpOptions(connectMcp);
150904
+ const servers = /* @__PURE__ */ Object.create(null);
150905
+ for (const [name, config2] of Object.entries(options.servers)) {
150906
+ const connections = /* @__PURE__ */ new WeakMap();
150907
+ const directScope = {};
150908
+ const connection = () => {
150909
+ const scope = runResources.getStore();
150910
+ scope?.signal.throwIfAborted();
150911
+ options.signal?.throwIfAborted();
150912
+ const owner = scope ?? directScope;
150913
+ let current = connections.get(owner);
150914
+ if (current === void 0) {
150915
+ current = connectMcpTransport(config2, options, scope?.signal);
150916
+ connections.set(owner, current);
150917
+ scope?.add(current.close);
150918
+ }
150919
+ return current.ready;
150920
+ };
150921
+ const invoke2 = async (operation) => {
150922
+ try {
150923
+ const result = await operation(await connection());
150924
+ runResources.getStore()?.signal.throwIfAborted();
150925
+ options.signal?.throwIfAborted();
150926
+ return result;
150927
+ } catch (error3) {
150928
+ runResources.getStore()?.signal.throwIfAborted();
150929
+ options.signal?.throwIfAborted();
150930
+ if (error3 instanceof McpError) {
150931
+ hostErrorData.set(error3, {
150932
+ code: error3.code,
150933
+ ...error3.data === void 0 ? {} : { data: error3.data }
150934
+ });
150935
+ }
150936
+ throw error3;
150937
+ }
150938
+ };
150939
+ servers[name] = {
150940
+ tools: declareHostOperation(
150941
+ async () => invoke2(async (client) => {
150942
+ const tools = [];
150943
+ const cursors = /* @__PURE__ */ new Set();
150944
+ let pages = 0;
150945
+ let cursor2;
150946
+ do {
150947
+ const result = await client.listTools(
150948
+ cursor2 === void 0 ? void 0 : { cursor: cursor2 }
150949
+ );
150950
+ pages += 1;
150951
+ tools.push(...normalizeToolsResult(result));
150952
+ cursor2 = result.nextCursor;
150953
+ if (cursor2 !== void 0) {
150954
+ if (typeof cursor2 !== "string" || cursors.has(cursor2))
150955
+ throw new Error("MCP tools pagination did not advance.");
150956
+ cursors.add(cursor2);
150957
+ if (pages >= options.maxToolPages)
150958
+ throw new Error("MCP tools page limit exceeded.");
150959
+ }
150960
+ } while (cursor2 !== void 0);
150961
+ return tools;
150962
+ }),
150963
+ "re-issue"
150964
+ ),
150965
+ tool: declareHostOperation(async (toolName, args) => {
150966
+ const request = createNullRecord7({
150967
+ name: readNonEmptyTrimmedString(toolName, "MCP tool name"),
150968
+ ...args === void 0 ? {} : { arguments: readToolArguments(args) }
150969
+ });
150970
+ return invoke2((client) => client.callTool(request));
150971
+ }, "read-side-effect"),
150972
+ toolBatch: declareHostOperation(async (calls) => {
150973
+ const normalized = readToolBatchCalls(calls);
150974
+ if (normalized.length === 0) return [];
150975
+ return invoke2((client) => executeToolBatch(client, normalized));
150976
+ }, "read-side-effect"),
150977
+ close: declareHostOperation(async () => {
150978
+ const owner = runResources.getStore() ?? directScope;
150979
+ const current = connections.get(owner);
150980
+ if (current !== void 0) {
150981
+ await current.close();
150982
+ connections.delete(owner);
150983
+ }
150984
+ }, "re-issue")
150985
+ };
150986
+ }
150987
+ const readName = (value) => {
150988
+ const name = readNonEmptyString9(value, "MCP server name");
150989
+ if (!Object.hasOwn(servers, name)) throw new Error(`MCP server '${name}' is not configured.`);
150990
+ return name;
150991
+ };
150992
+ return {
150993
+ servers,
150994
+ server(name) {
150995
+ return createNullRecord7({ name: readName(name) });
150996
+ },
150997
+ async client(handle) {
150998
+ if (typeof handle === "string") return servers[readName(handle)];
150999
+ if (!isRecord44(handle) || Object.keys(handle).length !== 1 || !Object.hasOwn(handle, "name"))
151000
+ throw new TypeError("MCP client requires a named server handle.");
151001
+ return servers[readName(getOwnProperty9(handle, "name"))];
151002
+ }
151003
+ };
151004
+ }
151005
+ return {
151006
+ server(server) {
151007
+ return normalizeServerHandle(server);
151008
+ },
151009
+ async client(handle) {
151010
+ const connection = validateConnection(await connectMcp(normalizeServerHandle(handle)));
151011
+ return {
151012
+ async tools() {
151013
+ return normalizeToolsResult(await connection.listTools());
151014
+ },
151015
+ async tool(name, args) {
151016
+ return connection.callTool(
151017
+ createNullRecord7({
151018
+ name: readNonEmptyTrimmedString(name, "MCP tool name"),
151019
+ ...args === void 0 ? {} : { arguments: readToolArguments(args) }
151020
+ })
151021
+ );
151022
+ },
151023
+ async toolBatch(calls) {
151024
+ return executeToolBatch(connection, readToolBatchCalls(calls));
151025
+ }
151026
+ };
151027
+ }
151028
+ };
151029
+ }
151030
+ async function executeToolBatch(connection, calls) {
151031
+ if (calls.length === 0) {
151032
+ return [];
151033
+ }
151034
+ if (connection.callToolBatch !== void 0 && calls.every((call) => call.ok)) {
151035
+ try {
151036
+ return normalizeProtocolBatchResults(
151037
+ await connection.callToolBatch(calls.map((call) => call.request)),
151038
+ calls.length
151039
+ );
151040
+ } catch (error3) {
151041
+ const batchError = normalizeToolBatchError(error3);
151042
+ return calls.map(
151043
+ () => createNullRecord7({
151044
+ ok: false,
151045
+ error: batchError
151046
+ })
151047
+ );
151048
+ }
151049
+ }
151050
+ return executeToolBatchWithConcurrency(connection, calls, DEFAULT_TOOL_BATCH_CONCURRENCY);
151051
+ }
151052
+ async function executeToolBatchWithConcurrency(connection, calls, concurrency) {
151053
+ const results = new Array(calls.length);
151054
+ let nextIndex = 0;
151055
+ let disconnectError;
151056
+ const workerCount = Math.min(concurrency, calls.length);
151057
+ const workers = Array.from({ length: workerCount }, async () => {
151058
+ while (nextIndex < calls.length) {
151059
+ const index = nextIndex;
151060
+ nextIndex += 1;
151061
+ const call = calls[index];
151062
+ if (call === void 0) {
151063
+ continue;
151064
+ }
151065
+ if (!call.ok) {
151066
+ results[index] = createNullRecord7({
151067
+ ok: false,
151068
+ error: call.error
151069
+ });
151070
+ continue;
151071
+ }
151072
+ if (disconnectError !== void 0) {
151073
+ results[index] = createNullRecord7({
151074
+ ok: false,
151075
+ error: disconnectError
151076
+ });
151077
+ continue;
151078
+ }
151079
+ try {
151080
+ results[index] = createNullRecord7({
151081
+ ok: true,
151082
+ value: await connection.callTool(call.request)
151083
+ });
151084
+ } catch (error3) {
151085
+ const toolError = normalizeToolBatchError(error3);
151086
+ results[index] = createNullRecord7({
151087
+ ok: false,
151088
+ error: toolError
151089
+ });
151090
+ if (isMcpDisconnectError(toolError)) {
151091
+ disconnectError = toolError;
151092
+ }
151093
+ }
151094
+ }
151095
+ });
151096
+ await Promise.all(workers);
151097
+ return results;
151098
+ }
151099
+ function normalizeProtocolBatchResults(value, expectedLength) {
151100
+ if (!Array.isArray(value) || value.length !== expectedLength) {
151101
+ throw new Error(
151102
+ "MCP callToolBatch() must resolve to a result array matching the input length."
151103
+ );
151104
+ }
151105
+ return value.map((entry, index) => normalizeProtocolBatchResult(entry, index));
151106
+ }
151107
+ function normalizeProtocolBatchResult(value, index) {
151108
+ if (!isRecord44(value)) {
151109
+ throw new Error(`MCP callToolBatch()[${index}] must be a result envelope.`);
151110
+ }
151111
+ const ok = getOwnProperty9(value, "ok");
151112
+ if (typeof ok !== "boolean") {
151113
+ throw new Error(`MCP callToolBatch()[${index}] must be a result envelope.`);
151114
+ }
151115
+ if (ok === true) {
151116
+ return createNullRecord7({
151117
+ ok: true,
151118
+ value: getOwnProperty9(value, "value")
151119
+ });
151120
+ }
151121
+ return createNullRecord7({
151122
+ ok: false,
151123
+ error: normalizeToolBatchError(getOwnProperty9(value, "error"))
151124
+ });
151125
+ }
151126
+ function normalizeServerHandle(value) {
151127
+ if (!isRecord44(value)) {
151128
+ throw new Error("MCP server must be an object.");
151129
+ }
151130
+ const command = getOwnProperty9(value, "command");
151131
+ const args = getOwnProperty9(value, "args");
151132
+ const env = getOwnProperty9(value, "env");
151133
+ return createNullRecord7({
151134
+ command: readNonEmptyTrimmedString(command, "MCP server command"),
151135
+ ...args === void 0 ? {} : { args: readStringArray2(args, "MCP server args") },
151136
+ ...env === void 0 ? {} : { env: readStringRecord2(env, "MCP server env") }
151137
+ });
151138
+ }
151139
+ function validateConnection(value) {
151140
+ if (!isRecord44(value) || typeof value.listTools !== "function" || typeof value.callTool !== "function") {
151141
+ throw new Error("connectMcp must resolve to an object with listTools() and callTool().");
151142
+ }
151143
+ const callToolBatch = getOwnProperty9(value, "callToolBatch");
151144
+ return createNullRecord7({
151145
+ listTools: () => value.listTools(),
151146
+ callTool: (params) => value.callTool(params),
151147
+ ...typeof callToolBatch === "function" ? {
151148
+ callToolBatch: (params) => callToolBatch(params)
151149
+ } : {}
151150
+ });
151151
+ }
151152
+ function normalizeToolsResult(value) {
151153
+ const tools = isRecord44(value) ? getOwnProperty9(value, "tools") : void 0;
151154
+ if (!Array.isArray(tools)) {
151155
+ throw new Error("MCP listTools() must resolve to an object with a tools array.");
151156
+ }
151157
+ return tools.map((tool, index) => normalizeTool3(tool, index));
151158
+ }
151159
+ function normalizeTool3(value, index) {
151160
+ if (!isRecord44(value)) {
151161
+ throw new Error(`MCP tool[${index}] must be an object.`);
151162
+ }
151163
+ const description = getOwnProperty9(value, "description");
151164
+ const inputSchema = getOwnProperty9(value, "inputSchema");
151165
+ return createNullRecord7({
151166
+ name: readNonEmptyString9(getOwnProperty9(value, "name"), `MCP tool[${index}] name`),
151167
+ ...description === void 0 ? {} : { description: readOptionalString8(description, `MCP tool[${index}] description`) },
151168
+ ...inputSchema === void 0 ? {} : { schema: inputSchema }
151169
+ });
151170
+ }
151171
+ function readStringArray2(value, label) {
151172
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
151173
+ throw new Error(`${label} must be an array of strings.`);
151174
+ }
151175
+ return [...value];
151176
+ }
151177
+ function readStringRecord2(value, label) {
151178
+ if (!isRecord44(value)) {
151179
+ throw new Error(`${label} must be an object.`);
151180
+ }
151181
+ const entries = Object.entries(value);
151182
+ if (entries.some(([, entry]) => typeof entry !== "string")) {
151183
+ throw new Error(`${label} must be a string record.`);
151184
+ }
151185
+ return createNullRecord7(Object.fromEntries(entries));
151186
+ }
151187
+ function readOptionalString8(value, label) {
151188
+ if (value === void 0) {
151189
+ return void 0;
151190
+ }
151191
+ if (typeof value !== "string") {
151192
+ throw new Error(`${label} must be a string.`);
151193
+ }
151194
+ return value;
151195
+ }
151196
+ function readNonEmptyString9(value, label) {
151197
+ const text5 = readOptionalString8(value, label);
151198
+ if (text5 === void 0 || text5.trim().length === 0) {
151199
+ throw new Error(`${label} must be a non-empty string.`);
151200
+ }
151201
+ return text5;
151202
+ }
151203
+ function readNonEmptyTrimmedString(value, label) {
151204
+ return readNonEmptyString9(value, label).trim();
151205
+ }
151206
+ function readToolArguments(value) {
151207
+ if (!isPlainObjectRecord(value)) {
151208
+ throw new Error("MCP tool arguments must be an object.");
151209
+ }
151210
+ return createNullRecord7(Object.fromEntries(Object.entries(value)));
151211
+ }
151212
+ function readToolBatchCalls(value) {
151213
+ if (!Array.isArray(value)) {
151214
+ throw new Error("MCP toolBatch calls must be an array.");
151215
+ }
151216
+ return value.map((entry, index) => normalizeToolBatchCall(entry, index));
151217
+ }
151218
+ function normalizeToolBatchCall(value, index) {
151219
+ try {
151220
+ if (!isRecord44(value)) {
151221
+ throw new Error(`MCP toolBatch call[${index}] must be an object.`);
151222
+ }
151223
+ const args = getOwnProperty9(value, "args");
151224
+ return createNullRecord7({
151225
+ ok: true,
151226
+ request: createNullRecord7({
151227
+ name: readNonEmptyTrimmedString(
151228
+ getOwnProperty9(value, "name"),
151229
+ `MCP toolBatch call[${index}] name`
151230
+ ),
151231
+ ...args === void 0 ? {} : { arguments: readToolArguments(args) }
151232
+ })
151233
+ });
151234
+ } catch (error3) {
151235
+ return createNullRecord7({
151236
+ ok: false,
151237
+ error: normalizeToolBatchError(error3)
151238
+ });
151239
+ }
151240
+ }
151241
+ function normalizeToolBatchError(error3) {
151242
+ if (error3 instanceof Error) {
151243
+ return createNullRecord7({
151244
+ name: error3.name.length === 0 ? "Error" : error3.name,
151245
+ message: error3.message
151246
+ });
151247
+ }
151248
+ if (isRecord44(error3)) {
151249
+ const nameValue = getOwnProperty9(error3, "name");
151250
+ const messageValue2 = getOwnProperty9(error3, "message");
151251
+ const name = typeof nameValue === "string" && nameValue.trim().length > 0 ? nameValue : "Error";
151252
+ const message2 = typeof messageValue2 === "string" ? messageValue2 : String(error3);
151253
+ return createNullRecord7({
151254
+ name,
151255
+ message: message2
151256
+ });
151257
+ }
151258
+ return createNullRecord7({
151259
+ name: "Error",
151260
+ message: error3 === void 0 ? "" : String(error3)
151261
+ });
151262
+ }
151263
+ function isMcpDisconnectError(error3) {
151264
+ const message2 = error3.message.toLowerCase();
151265
+ return message2.includes("disconnected") || message2.includes("connection closed") || message2.includes("transport closed") || message2.includes("disposed") || message2.includes("eof");
151266
+ }
151267
+ function isRecord44(value) {
151268
+ return typeof value === "object" && value !== null;
151269
+ }
151270
+ function getOwnProperty9(value, name) {
151271
+ return hasOwnProperty18(value, name) ? value[name] : void 0;
151272
+ }
151273
+ function hasOwnProperty18(value, name) {
151274
+ return Object.prototype.hasOwnProperty.call(value, name);
151275
+ }
151276
+ function createNullRecord7(value) {
151277
+ return Object.assign(/* @__PURE__ */ Object.create(null), value);
151278
+ }
151279
+ function isPlainObjectRecord(value) {
151280
+ if (!isRecord44(value) || Array.isArray(value)) {
151281
+ return false;
151282
+ }
151283
+ const prototype = Object.getPrototypeOf(value);
151284
+ return prototype === Object.prototype || prototype === null;
151285
+ }
151286
+ var DEFAULT_TOOL_BATCH_CONCURRENCY;
150516
151287
  var init_mcp5 = __esm({
150517
151288
  "packages/safejs/src/modules/mcp.ts"() {
150518
151289
  "use strict";
151290
+ init_src19();
151291
+ init_shape();
151292
+ init_host_bridge();
151293
+ init_resources();
151294
+ init_mcp_transport();
151295
+ DEFAULT_TOOL_BATCH_CONCURRENCY = 4;
150519
151296
  }
150520
151297
  });
150521
151298
 
@@ -150629,6 +151406,7 @@ var init_src49 = __esm({
150629
151406
  init_log2();
150630
151407
  init_metric();
150631
151408
  init_mcp5();
151409
+ init_mcp_transport();
150632
151410
  init_time();
150633
151411
  }
150634
151412
  });
@@ -150712,7 +151490,7 @@ function readVariableDeclaration(statement) {
150712
151490
  return void 0;
150713
151491
  }
150714
151492
  function readUnboundIdentifierName(error3) {
150715
- if (typeof error3 !== "object" || error3 === null || !hasOwnProperty18(error3, "code") || error3.code !== "UNBOUND_IDENTIFIER") {
151493
+ if (typeof error3 !== "object" || error3 === null || !hasOwnProperty19(error3, "code") || error3.code !== "UNBOUND_IDENTIFIER") {
150716
151494
  return void 0;
150717
151495
  }
150718
151496
  const message2 = readErrorMessage4(error3);
@@ -150727,12 +151505,12 @@ function readErrorMessage4(error3) {
150727
151505
  if (error3 instanceof Error) {
150728
151506
  return error3.message;
150729
151507
  }
150730
- if (typeof error3 === "object" && error3 !== null && hasOwnProperty18(error3, "message") && typeof error3.message === "string") {
151508
+ if (typeof error3 === "object" && error3 !== null && hasOwnProperty19(error3, "message") && typeof error3.message === "string") {
150731
151509
  return error3.message;
150732
151510
  }
150733
151511
  return String(error3);
150734
151512
  }
150735
- function hasOwnProperty18(value, name) {
151513
+ function hasOwnProperty19(value, name) {
150736
151514
  return Object.prototype.hasOwnProperty.call(value, name);
150737
151515
  }
150738
151516
  var SCHEMA_EXTRACTION_BUDGET;
@@ -150754,7 +151532,7 @@ var init_extract_schema = __esm({
150754
151532
  // packages/agent-harness/src/codegen/emit-schemas.ts
150755
151533
  import { randomUUID as randomUUID51 } from "node:crypto";
150756
151534
  import * as nodeFs21 from "node:fs/promises";
150757
- import path184 from "node:path";
151535
+ import path185 from "node:path";
150758
151536
  import { fileURLToPath as fileURLToPath14 } from "node:url";
150759
151537
  var init_emit_schemas = __esm({
150760
151538
  "packages/agent-harness/src/codegen/emit-schemas.ts"() {
@@ -150812,23 +151590,23 @@ var init_pair = __esm({
150812
151590
  MissingPairError = class extends UserError {
150813
151591
  side;
150814
151592
  path;
150815
- constructor(side, path189) {
151593
+ constructor(side, path190) {
150816
151594
  super(
150817
- `Missing harness ${side} file: ${path189}
151595
+ `Missing harness ${side} file: ${path190}
150818
151596
  Run \`poe-code harness list\` to see available harnesses, or \`poe-code harness new <name>\` to scaffold this pair.`
150819
151597
  );
150820
151598
  this.side = side;
150821
- this.path = path189;
151599
+ this.path = path190;
150822
151600
  }
150823
151601
  };
150824
151602
  InvalidPairExtensionError = class extends Error {
150825
151603
  extension;
150826
151604
  path;
150827
- constructor(path189, extension) {
150828
- super(`Harness pair input must be a .md or .ajs file: ${path189}`);
151605
+ constructor(path190, extension) {
151606
+ super(`Harness pair input must be a .md or .ajs file: ${path190}`);
150829
151607
  this.name = "InvalidPairExtensionError";
150830
151608
  this.extension = extension;
150831
- this.path = path189;
151609
+ this.path = path190;
150832
151610
  }
150833
151611
  };
150834
151612
  }
@@ -150895,8 +151673,8 @@ function validateFrontmatter(schema, frontmatter, mdPath) {
150895
151673
  function formatIssues3(mdPath, issues) {
150896
151674
  return issues.map((issue2) => `${mdPath} (${formatPath4(issue2.path)}): ${issue2.message}`).join("\n");
150897
151675
  }
150898
- function formatPath4(path189) {
150899
- return path189.join(".") || "frontmatter";
151676
+ function formatPath4(path190) {
151677
+ return path190.join(".") || "frontmatter";
150900
151678
  }
150901
151679
  var FrontmatterValidationError;
150902
151680
  var init_validate4 = __esm({
@@ -151120,10 +151898,10 @@ function restoreRandomState(random) {
151120
151898
  };
151121
151899
  }
151122
151900
  function isClockState(value) {
151123
- if (!hasOwnProperty19(value, "next")) return false;
151901
+ if (!hasOwnProperty20(value, "next")) return false;
151124
151902
  return typeof value.next === "number" && Number.isFinite(value.next);
151125
151903
  }
151126
- function hasOwnProperty19(value, name) {
151904
+ function hasOwnProperty20(value, name) {
151127
151905
  return typeof value === "object" && value !== null && Object.hasOwn(value, name);
151128
151906
  }
151129
151907
  async function createHostCallReplay(snapshotPath, statefulBindings = {}, opts = {}) {
@@ -151281,9 +152059,9 @@ async function writeTextFileAtomically2(filePath, content) {
151281
152059
  async function cleanupCompletedSnapshot(snapshotBackend, snapshotPath) {
151282
152060
  await Promise.all([snapshotBackend.remove(), unlinkIfExists(hostCallStorePath(snapshotPath))]);
151283
152061
  }
151284
- async function unlinkIfExists(path189) {
152062
+ async function unlinkIfExists(path190) {
151285
152063
  try {
151286
- await unlink25(path189);
152064
+ await unlink25(path190);
151287
152065
  } catch (error3) {
151288
152066
  if (!hasErrorCode6(error3, "ENOENT")) {
151289
152067
  throw error3;
@@ -151347,8 +152125,8 @@ async function assertDefaultSnapshotPathIsRegular(snapshotPath) {
151347
152125
  }
151348
152126
  }
151349
152127
  }
151350
- async function readTextFile(path189) {
151351
- const source = await readFile55(path189, "utf8");
152128
+ async function readTextFile(path190) {
152129
+ const source = await readFile55(path190, "utf8");
151352
152130
  return source.startsWith("\uFEFF") ? source.slice(1) : source;
151353
152131
  }
151354
152132
  function formatLintErrorMessage(diagnostics) {
@@ -151503,7 +152281,7 @@ var init_harness_spawn_retry = __esm({
151503
152281
  });
151504
152282
 
151505
152283
  // src/cli/commands/harness.ts
151506
- import path185 from "node:path";
152284
+ import path186 from "node:path";
151507
152285
  import { readFile as readFile57 } from "node:fs/promises";
151508
152286
  import { Argument } from "commander";
151509
152287
  function registerHarnessCommand(program, container) {
@@ -151512,7 +152290,7 @@ function registerHarnessCommand(program, container) {
151512
152290
  harness.command("run").description("Run a harness pair.").argument("[md-paths...]", "Paths to harness .md files to run sequentially").option("--dir <path>", "Directory to search for harness pairs when no md-path is given.").option("--fix", "Apply supported lint fixes to the harness .ajs file before running.").option("--fs", "Give the harness a real filesystem module, confined to --fs-root.").option(
151513
152291
  "--fs-root <path>",
151514
152292
  "Directory --fs confines the harness to (default: the harness directory)."
151515
- ).option("--snapshot-path <path>", "File to write/read harness snapshots.").option("--resume", "Resume from the snapshot file when it exists.").option("--agent <name>", "Override the agent id from the harness frontmatter agent block.").option("--model <name>", "Override the model from the harness frontmatter agent block.").option(
152293
+ ).option("--snapshot-path <path>", "File to write/read harness snapshots.").option("--mcp-config <path>", "Give the harness named MCP servers from a JSON config.").option("--resume", "Resume from the snapshot file when it exists.").option("--agent <name>", "Override the agent id from the harness frontmatter agent block.").option("--model <name>", "Override the model from the harness frontmatter agent block.").option(
151516
152294
  "--mode <mode>",
151517
152295
  "Override the mode from the harness frontmatter agent block (read|edit|auto|yolo)."
151518
152296
  ).option("-y, --yes", "Accept defaults without prompting.")
@@ -151533,7 +152311,17 @@ async function executeHarnessRun(program, container, mdPath, options) {
151533
152311
  const flags = resolveHarnessFlags(program, options.yes);
151534
152312
  const resources = createExecutionResources(container, flags, "harness:run");
151535
152313
  const fsOptions = resolveHarnessFsOptions(container, options);
151536
- const selectedPath = mdPath ? path185.resolve(container.env.cwd, mdPath) : (await resolveDiscoveredHarness(container, options.dir, flags.assumeYes)).mdPath;
152314
+ let mcpOptions;
152315
+ if (options.mcpConfig !== void 0) {
152316
+ if (options.mcpConfig.trim().length === 0)
152317
+ throw new ValidationError("--mcp-config needs a JSON file path.");
152318
+ const configPath = path186.resolve(container.env.cwd, options.mcpConfig);
152319
+ mcpOptions = parseMcpConfig3(
152320
+ await container.fs.readFile(configPath, "utf8"),
152321
+ path186.dirname(configPath)
152322
+ );
152323
+ }
152324
+ const selectedPath = mdPath ? path186.resolve(container.env.cwd, mdPath) : (await resolveDiscoveredHarness(container, options.dir, flags.assumeYes)).mdPath;
151537
152325
  if (flags.dryRun) {
151538
152326
  await resolvePair(selectedPath, container.fs);
151539
152327
  resources.logger.dryRun(
@@ -151541,7 +152329,7 @@ async function executeHarnessRun(program, container, mdPath, options) {
151541
152329
  );
151542
152330
  if (fsOptions !== void 0) {
151543
152331
  resources.logger.dryRun(
151544
- `Dry run: would enable the fs module rooted at ${formatDisplayPath3(container, resolveFsRoot(fsOptions, path185.dirname(selectedPath)))}.`
152332
+ `Dry run: would enable the fs module rooted at ${formatDisplayPath3(container, resolveFsRoot(fsOptions, path186.dirname(selectedPath)))}.`
151545
152333
  );
151546
152334
  }
151547
152335
  return;
@@ -151588,7 +152376,8 @@ async function executeHarnessRun(program, container, mdPath, options) {
151588
152376
  (error3) => {
151589
152377
  reportedSpawnFailures.add(error3);
151590
152378
  },
151591
- runFsOptions
152379
+ runFsOptions,
152380
+ mcpOptions
151592
152381
  ),
151593
152382
  onDiagnostics: (diagnostics) => {
151594
152383
  lintDiagnostics.push(...diagnostics);
@@ -151639,9 +152428,9 @@ async function resolveHarnessWorktreeAgent(container, selectedPath, options) {
151639
152428
  );
151640
152429
  }
151641
152430
  function mapSourcePathIntoWorktree3(sourceCwd, sourcePath, worktreeCwd) {
151642
- const relativePath = path185.relative(sourceCwd, sourcePath);
151643
- if (relativePath === "" || !relativePath.startsWith("..") && !path185.isAbsolute(relativePath)) {
151644
- return path185.join(worktreeCwd, relativePath);
152431
+ const relativePath = path186.relative(sourceCwd, sourcePath);
152432
+ if (relativePath === "" || !relativePath.startsWith("..") && !path186.isAbsolute(relativePath)) {
152433
+ return path186.join(worktreeCwd, relativePath);
151645
152434
  }
151646
152435
  return sourcePath;
151647
152436
  }
@@ -151785,10 +152574,10 @@ function buildAgentFrontmatterOverrides(options) {
151785
152574
  }
151786
152575
  function resolveRunSnapshotPath(container, mdPath, snapshotPath) {
151787
152576
  if (snapshotPath !== void 0) {
151788
- return path185.resolve(container.env.cwd, snapshotPath);
152577
+ return path186.resolve(container.env.cwd, snapshotPath);
151789
152578
  }
151790
- const basename10 = path185.basename(mdPath, path185.extname(mdPath));
151791
- return path185.join(container.env.cwd, ".poe-code", "harnesses", basename10, "snapshot.json");
152579
+ const basename10 = path186.basename(mdPath, path186.extname(mdPath));
152580
+ return path186.join(container.env.cwd, ".poe-code", "harnesses", basename10, "snapshot.json");
151792
152581
  }
151793
152582
  async function prepareHarnessSnapshot(container, mdPath, snapshotPath, resumeRequested) {
151794
152583
  const snapshotExists = await pathExists17(container, snapshotPath);
@@ -151857,8 +152646,8 @@ function formatRunMessage(baseMessage, progress) {
151857
152646
  return progress === void 0 ? baseMessage : `${baseMessage} (${progress})`;
151858
152647
  }
151859
152648
  function resolveAjsPath(mdPath) {
151860
- const parsed = path185.parse(mdPath);
151861
- return path185.join(parsed.dir, `${parsed.name}.ajs`);
152649
+ const parsed = path186.parse(mdPath);
152650
+ return path186.join(parsed.dir, `${parsed.name}.ajs`);
151862
152651
  }
151863
152652
  async function pathExists17(container, targetPath) {
151864
152653
  try {
@@ -151884,16 +152673,16 @@ async function executeHarnessNew(program, container, kind, basename10, options)
151884
152673
  `Unknown harness template "${kind}". Available kinds: ${builtinKinds().join(", ")}.`
151885
152674
  );
151886
152675
  }
151887
- if (basename10.length === 0 || basename10 === "." || basename10 === ".." || path185.basename(basename10) !== basename10) {
152676
+ if (basename10.length === 0 || basename10 === "." || basename10 === ".." || path186.basename(basename10) !== basename10) {
151888
152677
  throw new ValidationError(
151889
152678
  `Invalid harness basename "${basename10}". Use a single directory name.`
151890
152679
  );
151891
152680
  }
151892
- const defaultDir = path185.join(".poe-code", "harnesses", basename10);
152681
+ const defaultDir = path186.join(".poe-code", "harnesses", basename10);
151893
152682
  const outputDir = options.dir ?? await resolveOutputDir(defaultDir, flags.assumeYes);
151894
- const resolvedDir = path185.resolve(container.env.cwd, outputDir);
151895
- const mdPath = path185.join(resolvedDir, `${basename10}.md`);
151896
- const ajsPath = path185.join(resolvedDir, `${basename10}.ajs`);
152683
+ const resolvedDir = path186.resolve(container.env.cwd, outputDir);
152684
+ const mdPath = path186.join(resolvedDir, `${basename10}.md`);
152685
+ const ajsPath = path186.join(resolvedDir, `${basename10}.ajs`);
151897
152686
  await assertFilesDoNotExist(container, [mdPath, ajsPath]);
151898
152687
  if (flags.dryRun) {
151899
152688
  resources.logger.dryRun(`Would create ${formatDisplayPath3(container, mdPath)}`);
@@ -152011,10 +152800,10 @@ async function resolveDiscoveredHarness(container, dir, assumeYes) {
152011
152800
  }
152012
152801
  function harnessDiscoveryRoots(container, dir) {
152013
152802
  const roots = [
152014
- path185.join(container.env.cwd, ".poe-code", "harnesses"),
152015
- path185.join(container.env.homeDir, ".poe-code", "harnesses")
152803
+ path186.join(container.env.cwd, ".poe-code", "harnesses"),
152804
+ path186.join(container.env.homeDir, ".poe-code", "harnesses")
152016
152805
  ];
152017
- return dir === void 0 ? roots : [path185.resolve(container.env.cwd, dir), ...roots];
152806
+ return dir === void 0 ? roots : [path186.resolve(container.env.cwd, dir), ...roots];
152018
152807
  }
152019
152808
  function formatSearchedRoots(container, dir) {
152020
152809
  return harnessDiscoveryRoots(container, dir).map((root) => formatDisplayPath3(container, root)).join(", ");
@@ -152036,7 +152825,7 @@ async function discoverPairsDirectlyIn(container, root) {
152036
152825
  for (const entry of entries.filter((name) => name.endsWith(".md")).sort()) {
152037
152826
  try {
152038
152827
  pairs.push(
152039
- await resolvePair(path185.join(root, entry), container.fs)
152828
+ await resolvePair(path186.join(root, entry), container.fs)
152040
152829
  );
152041
152830
  } catch (error3) {
152042
152831
  if (error3 instanceof MissingPairError) {
@@ -152058,7 +152847,7 @@ async function discoverProjectThenUserHarnesses(container, dir) {
152058
152847
  const stat36 = await container.fs.stat(pair.mdPath);
152059
152848
  discovered.push({
152060
152849
  ...pair,
152061
- dir: path185.dirname(pair.mdPath),
152850
+ dir: path186.dirname(pair.mdPath),
152062
152851
  mdMtimeMs: stat36.mtimeMs
152063
152852
  });
152064
152853
  }
@@ -152114,12 +152903,12 @@ function resolveHarnessFsOptions(container, options) {
152114
152903
  "--fs-root needs a directory path. Pass --fs-root <path> to confine the harness to that directory, or drop --fs-root to confine it to the harness directory."
152115
152904
  );
152116
152905
  }
152117
- return { root: path185.resolve(container.env.cwd, options.fsRoot) };
152906
+ return { root: path186.resolve(container.env.cwd, options.fsRoot) };
152118
152907
  }
152119
152908
  function resolveFsRoot(fsOptions, harnessDir) {
152120
152909
  return fsOptions.root ?? harnessDir;
152121
152910
  }
152122
- function createHarnessModules(container, logger2, frontmatter, meta, onSpawnFailure, fsOptions) {
152911
+ function createHarnessModules(container, logger2, frontmatter, meta, onSpawnFailure, fsOptions, mcpOptions) {
152123
152912
  const harnessMeta = {
152124
152913
  kind: meta.kind,
152125
152914
  version: meta.version,
@@ -152172,6 +152961,7 @@ function createHarnessModules(container, logger2, frontmatter, meta, onSpawnFail
152172
152961
  });
152173
152962
  return {
152174
152963
  agent: toModuleExports(agent3),
152964
+ ...mcpOptions === void 0 ? {} : { mcp: toModuleExports(makeMcpModule(mcpOptions)) },
152175
152965
  fail: toModuleExports(/* @__PURE__ */ new Map([["default", fail3]])),
152176
152966
  ...fsOptions === void 0 ? {} : { fs: toModuleExports(makeFsModule({ root: resolveFsRoot(fsOptions, meta.dirname) })) },
152177
152967
  git: toModuleExports(git2),
@@ -152268,8 +153058,8 @@ function toModuleExports(moduleExports) {
152268
153058
  return new Map(Object.entries(moduleExports));
152269
153059
  }
152270
153060
  function formatDisplayPath3(container, filePath) {
152271
- const relative8 = path185.relative(container.env.cwd, filePath);
152272
- return relative8.length > 0 && !relative8.startsWith("..") && !path185.isAbsolute(relative8) ? relative8 : filePath.replace(container.env.homeDir, "~");
153061
+ const relative8 = path186.relative(container.env.cwd, filePath);
153062
+ return relative8.length > 0 && !relative8.startsWith("..") && !path186.isAbsolute(relative8) ? relative8 : filePath.replace(container.env.homeDir, "~");
152273
153063
  }
152274
153064
  var init_harness3 = __esm({
152275
153065
  async "src/cli/commands/harness.ts"() {
@@ -152576,7 +153366,7 @@ import { Argument as Argument2 } from "commander";
152576
153366
  function isVisible(command) {
152577
153367
  return Reflect.get(command, "_hidden") !== true;
152578
153368
  }
152579
- function collectNodes(command, path189 = []) {
153369
+ function collectNodes(command, path190 = []) {
152580
153370
  const children2 = command.commands.filter(isVisible).map((child) => ({
152581
153371
  name: child.name(),
152582
153372
  aliases: [...child.aliases()],
@@ -152607,10 +153397,10 @@ function collectNodes(command, path189 = []) {
152607
153397
  return [];
152608
153398
  }
152609
153399
  return [
152610
- { path: path189, children: children2, options, requiredValueFlags, isPositionalLeaf, positionalChildren },
153400
+ { path: path190, children: children2, options, requiredValueFlags, isPositionalLeaf, positionalChildren },
152611
153401
  ...command.commands.filter(isVisible).flatMap(
152612
153402
  (child) => [child.name(), ...child.aliases()].flatMap(
152613
- (name) => collectNodes(child, [...path189, name])
153403
+ (name) => collectNodes(child, [...path190, name])
152614
153404
  )
152615
153405
  )
152616
153406
  ];
@@ -152742,8 +153532,8 @@ function renderZsh(nodes) {
152742
153532
  function quoteFish(value) {
152743
153533
  return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
152744
153534
  }
152745
- function fishCondition(path189) {
152746
- return path189.length === 0 ? '"__fish_use_subcommand"' : `"__fish_seen_subcommand_from ${path189.at(-1)}"`;
153535
+ function fishCondition(path190) {
153536
+ return path190.length === 0 ? '"__fish_use_subcommand"' : `"__fish_seen_subcommand_from ${path190.at(-1)}"`;
152747
153537
  }
152748
153538
  function renderFish(nodes) {
152749
153539
  const lines = nodes.flatMap((node) => {
@@ -152800,7 +153590,7 @@ var init_completion = __esm({
152800
153590
 
152801
153591
  // src/cli/commands/tasks-options.ts
152802
153592
  import * as fsPromises27 from "node:fs/promises";
152803
- import path186 from "node:path";
153593
+ import path187 from "node:path";
152804
153594
  async function resolveWorkflowTaskListOptions(workflowPath) {
152805
153595
  const frontmatter = await readWorkflowFrontmatter(workflowPath);
152806
153596
  return readTaskListOptions(frontmatter, workflowPath);
@@ -152951,14 +153741,14 @@ function readMaestroStates(frontmatter) {
152951
153741
  return [];
152952
153742
  }
152953
153743
  return unique3([
152954
- ...readStringArray2(getOwnEntry37(maestro, "active_states")),
152955
- ...readStringArray2(getOwnEntry37(maestro, "terminal_states"))
153744
+ ...readStringArray3(getOwnEntry37(maestro, "active_states")),
153745
+ ...readStringArray3(getOwnEntry37(maestro, "terminal_states"))
152956
153746
  ]);
152957
153747
  }
152958
153748
  function readLegacyTopLevelStates(frontmatter) {
152959
153749
  return unique3([
152960
- ...readStringArray2(getOwnEntry37(frontmatter, "active_states")),
152961
- ...readStringArray2(getOwnEntry37(frontmatter, "terminal_states"))
153750
+ ...readStringArray3(getOwnEntry37(frontmatter, "active_states")),
153751
+ ...readStringArray3(getOwnEntry37(frontmatter, "terminal_states"))
152962
153752
  ]);
152963
153753
  }
152964
153754
  function readDeclaredStates(value) {
@@ -152994,7 +153784,7 @@ function referencesMaestroTaskStateMachine(value) {
152994
153784
  const record2 = asRecord6(value);
152995
153785
  return record2 === void 0 ? false : Object.values(record2).some((item) => referencesMaestroTaskStateMachine(item));
152996
153786
  }
152997
- function readStringArray2(value) {
153787
+ function readStringArray3(value) {
152998
153788
  if (!Array.isArray(value)) {
152999
153789
  return [];
153000
153790
  }
@@ -153038,7 +153828,7 @@ function resolveStringValue2(value) {
153038
153828
  return process.env[value.slice(envPrefix.length)] ?? value;
153039
153829
  }
153040
153830
  function resolveWorkflowRelativePath(value, workflowPath) {
153041
- return path186.isAbsolute(value) ? value : path186.resolve(path186.dirname(workflowPath), value);
153831
+ return path187.isAbsolute(value) ? value : path187.resolve(path187.dirname(workflowPath), value);
153042
153832
  }
153043
153833
  function asRecord6(value) {
153044
153834
  return isPlainRecord6(value) ? value : void 0;
@@ -153083,7 +153873,7 @@ var init_tasks_options = __esm({
153083
153873
  });
153084
153874
 
153085
153875
  // src/cli/commands/tasks.ts
153086
- import path187 from "node:path";
153876
+ import path188 from "node:path";
153087
153877
  function registerTasksCommand(program, container) {
153088
153878
  const tasks = program.command("tasks").description("Read and mutate configured workflow tasks.");
153089
153879
  tasks.command("verify").description("Verify a task GitHub Project.").argument("<list>", "Project list in <owner>/<number> format.").option("--workflow <path>", "Workflow file path.", "./WORKFLOW.md").option("--repo <owner/name>", "GitHub repository owner/name.").option("--project <owner/number>", "GitHub project owner/number.").option("--states <csv>", "Required task state names.").option("--json", jsonOptionDescription).action(async (list2, options, command) => {
@@ -153233,7 +154023,7 @@ async function runImport(options, container) {
153233
154023
  const limit = options.limit === void 0 ? void 0 : parseNonNegativeInteger3(options.limit, "--limit");
153234
154024
  const source = {
153235
154025
  type: "markdown-dir",
153236
- path: path187.resolve(options.from),
154026
+ path: path188.resolve(options.from),
153237
154027
  singleList: "import",
153238
154028
  frontmatterMode: "passthrough"
153239
154029
  };
@@ -153449,7 +154239,7 @@ async function openConfiguredTaskList2(options, container) {
153449
154239
  }
153450
154240
  function addRuntimeTaskOptions(resolved, container) {
153451
154241
  const options = resolved.taskListOptions;
153452
- if (!hasOwnProperty20(options, "path")) {
154242
+ if (!hasOwnProperty21(options, "path")) {
153453
154243
  return options;
153454
154244
  }
153455
154245
  return {
@@ -153536,7 +154326,7 @@ function logTask(logger2, task) {
153536
154326
  logger2.info(`metadata: ${JSON.stringify(task.metadata)}`);
153537
154327
  }
153538
154328
  function writeField(task, field) {
153539
- if (!hasOwnProperty20(task, field)) {
154329
+ if (!hasOwnProperty21(task, field)) {
153540
154330
  throw new TasksCommandUsageError(`Task field "${field}" does not exist.`);
153541
154331
  }
153542
154332
  const value = task[field];
@@ -153644,7 +154434,7 @@ function readCommentMethod(tasks) {
153644
154434
  const candidate = tasks.comment;
153645
154435
  return typeof candidate === "function" ? candidate : void 0;
153646
154436
  }
153647
- function hasOwnProperty20(value, key3) {
154437
+ function hasOwnProperty21(value, key3) {
153648
154438
  return Object.prototype.hasOwnProperty.call(value, key3);
153649
154439
  }
153650
154440
  var TasksCommandUsageError;
@@ -153667,7 +154457,7 @@ var init_tasks2 = __esm({
153667
154457
  });
153668
154458
 
153669
154459
  // src/cli/commands/gaslight.ts
153670
- import path188 from "node:path";
154460
+ import path189 from "node:path";
153671
154461
  import { Option as Option10 } from "commander";
153672
154462
  async function resolveGaslightCommandConfig(container) {
153673
154463
  const configDoc = await readMergedDocumentReadonly(
@@ -153686,9 +154476,9 @@ async function resolveGaslightCommandConfig(container) {
153686
154476
  }
153687
154477
  function resolveConfiguredPath(cwd, homeDir, value) {
153688
154478
  if (value.startsWith("~/")) {
153689
- return path188.join(homeDir, value.slice(2));
154479
+ return path189.join(homeDir, value.slice(2));
153690
154480
  }
153691
- return path188.isAbsolute(value) ? value : path188.resolve(cwd, value);
154481
+ return path189.isAbsolute(value) ? value : path189.resolve(cwd, value);
153692
154482
  }
153693
154483
  function formatPlanDirectoryDetails(container, planDirectory, absoluteDirectory) {
153694
154484
  return [
@@ -153803,7 +154593,7 @@ function formatCompletedPlans(result) {
153803
154593
  return [
153804
154594
  "Completed plans:",
153805
154595
  ...result.plans.map(
153806
- (plan) => `- ${path188.basename(plan.planPath)}${plan.durationMs === void 0 ? "" : ` \xB7 ${formatDuration3(plan.durationMs)}`}`
154596
+ (plan) => `- ${path189.basename(plan.planPath)}${plan.durationMs === void 0 ? "" : ` \xB7 ${formatDuration3(plan.durationMs)}`}`
153807
154597
  )
153808
154598
  ].join("\n");
153809
154599
  }
@@ -153869,8 +154659,8 @@ async function resolveInstallScope(options, assumeYes) {
153869
154659
  }
153870
154660
  async function scaffoldConfig(container, scope, force, dryRun) {
153871
154661
  const root = scope === "global" ? container.env.homeDir : container.env.cwd;
153872
- const configPath = path188.join(root, ".poe-code", "gaslight.yaml");
153873
- const configDirectory = path188.dirname(configPath);
154662
+ const configPath = path189.join(root, ".poe-code", "gaslight.yaml");
154663
+ const configDirectory = path189.dirname(configPath);
153874
154664
  try {
153875
154665
  const stats2 = await container.fs.lstat(configDirectory);
153876
154666
  if (stats2.isSymbolicLink()) {
@@ -154265,7 +155055,7 @@ var init_package2 = __esm({
154265
155055
  "package.json"() {
154266
155056
  package_default2 = {
154267
155057
  name: "poe-code",
154268
- version: "8.0.1",
155058
+ version: "9.0.0",
154269
155059
  description: "CLI tool to configure Poe API for developer workflows.",
154270
155060
  license: "MIT",
154271
155061
  type: "module",
@@ -154899,11 +155689,11 @@ function readCommandTreeOption(command, optionName) {
154899
155689
  }
154900
155690
  return void 0;
154901
155691
  }
154902
- function assertPathIsNotOptionName(path189, command) {
154903
- const named = command.options.find((option) => option.long === `--${path189}`);
155692
+ function assertPathIsNotOptionName(path190, command) {
155693
+ const named = command.options.find((option) => option.long === `--${path190}`);
154904
155694
  if (named !== void 0) {
154905
155695
  throw new ValidationError(
154906
- `\`${path189}\` is not a workflow path. Did you mean \`${named.long}\`?`
155696
+ `\`${path190}\` is not a workflow path. Did you mean \`${named.long}\`?`
154907
155697
  );
154908
155698
  }
154909
155699
  }
@@ -154964,14 +155754,14 @@ function registerMaestroCommand(program, container) {
154964
155754
  "--log-level <level>",
154965
155755
  maestroCommandSchema.shape.logLevel.description ?? "Log level"
154966
155756
  ).choices(maestroCommandSchema.shape.logLevel.values.map(String)).default(maestroCommandSchema.shape.logLevel.default)
154967
- ).action(async (path189, options, command) => {
154968
- assertPathIsNotOptionName(path189, command);
155757
+ ).action(async (path190, options, command) => {
155758
+ assertPathIsNotOptionName(path190, command);
154969
155759
  const mergedOptions = {
154970
155760
  ...options,
154971
155761
  ...command.optsWithGlobals()
154972
155762
  };
154973
155763
  await runMaestro({
154974
- workflowPath: mergedOptions.config ?? path189,
155764
+ workflowPath: mergedOptions.config ?? path190,
154975
155765
  maxConcurrent: mergedOptions.maxConcurrent,
154976
155766
  pollIntervalMs: mergedOptions.pollIntervalMs,
154977
155767
  list: mergedOptions.list,
@@ -155132,7 +155922,7 @@ function createProgram(dependencies) {
155132
155922
  }
155133
155923
  function assertKnownHelpPath(program, container, argv) {
155134
155924
  let target = program;
155135
- const path189 = [];
155925
+ const path190 = [];
155136
155926
  for (const token of argv.filter((arg) => !arg.startsWith("-"))) {
155137
155927
  if (target.commands.length === 0) {
155138
155928
  return;
@@ -155140,7 +155930,7 @@ function assertKnownHelpPath(program, container, argv) {
155140
155930
  const child = findCommand2(target, token);
155141
155931
  if (child !== void 0) {
155142
155932
  target = child;
155143
- path189.push(token);
155933
+ path190.push(token);
155144
155934
  continue;
155145
155935
  }
155146
155936
  if (target !== program && target.registeredArguments.length > 0) {
@@ -155150,7 +155940,7 @@ function assertKnownHelpPath(program, container, argv) {
155150
155940
  container,
155151
155941
  scope: target === program ? "cli" : target.name(),
155152
155942
  unknownCommand: token,
155153
- helpArgs: [...path189, "--help"],
155943
+ helpArgs: [...path190, "--help"],
155154
155944
  candidates: commandCandidates(target),
155155
155945
  moduleUrl: import.meta.url
155156
155946
  });
@@ -155181,16 +155971,16 @@ function commandCandidates(parent) {
155181
155971
  return parent.commands.flatMap((command) => [command.name(), ...command.aliases()]);
155182
155972
  }
155183
155973
  function registerHelpCommand(program, container) {
155184
- program.command("help").description("Display help for a command.").argument("[command...]", "Command path to describe, for example `maestro tui`.").action((path189) => {
155974
+ program.command("help").description("Display help for a command.").argument("[command...]", "Command path to describe, for example `maestro tui`.").action((path190) => {
155185
155975
  let target = program;
155186
- for (const name of path189) {
155976
+ for (const name of path190) {
155187
155977
  const child = findCommand2(target, name);
155188
155978
  if (child === void 0) {
155189
155979
  throwCommandNotFound({
155190
155980
  container,
155191
155981
  scope: "cli",
155192
155982
  unknownCommand: name,
155193
- helpArgs: [...path189.slice(0, path189.indexOf(name)), "--help"],
155983
+ helpArgs: [...path190.slice(0, path190.indexOf(name)), "--help"],
155194
155984
  candidates: commandCandidates(target),
155195
155985
  moduleUrl: import.meta.url
155196
155986
  });