@sedum-dev/core 0.1.0-alpha.5 → 0.1.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -87,6 +87,7 @@ var ResultLocatorSchema = z.strictObject({
87
87
  vision: z.strictObject({
88
88
  outcome: z.enum(["selected", "abstained", "failed"]).optional(),
89
89
  reason: z.string().max(120).optional(),
90
+ abstentionReason: z.string().max(120).optional(),
90
91
  elapsedMs: nonnegative,
91
92
  failure: z.enum([
92
93
  "timeout",
@@ -97,7 +98,8 @@ var ResultLocatorSchema = z.strictObject({
97
98
  "invalid_json",
98
99
  "invalid_selection",
99
100
  "truncated_response",
100
- "unknown"
101
+ "unknown",
102
+ "stale_page"
101
103
  ]).optional(),
102
104
  httpStatus: z.number().int().min(100).max(599).optional()
103
105
  }).optional(),
@@ -1091,6 +1093,7 @@ async function call(page, method, argument) {
1091
1093
  const bridge = window.__sedum;
1092
1094
  if (!bridge) return { installed: false };
1093
1095
  if (bridge.protocol !== ${PAGE_PROTOCOL}) return { installed: true, protocol: bridge.protocol };
1096
+ if (typeof bridge[${JSON.stringify(method)}] !== "function") return { installed: true, protocol: bridge.protocol, missingMethod: true };
1094
1097
  return Promise.resolve(bridge[${JSON.stringify(method)}](argument)).then(value => ({ installed: true, protocol: bridge.protocol, value: value ?? null }));
1095
1098
  })(${JSON.stringify(argument ?? null)})`);
1096
1099
  if (!result || !result.installed)
@@ -1098,7 +1101,7 @@ async function call(page, method, argument) {
1098
1101
  "missing",
1099
1102
  "Sedum page script was not installed in this document."
1100
1103
  );
1101
- if (result.protocol !== PAGE_PROTOCOL)
1104
+ if (result.protocol !== PAGE_PROTOCOL || result.missingMethod)
1102
1105
  throw new PageScriptError(
1103
1106
  "incompatible",
1104
1107
  `Sedum page script protocol ${result.protocol} is incompatible with ${PAGE_PROTOCOL}.`
@@ -1177,6 +1180,16 @@ async function matchLiveEntry(page, entry, key, operation, sentence, runtimeDepe
1177
1180
  runtimeDependent
1178
1181
  );
1179
1182
  }
1183
+ async function controlState(page, target) {
1184
+ const result = await call(page, "controlState", target);
1185
+ if (!result || result.status !== "stale" && !(result.status === "ok" && typeof result.disabled === "boolean" && (typeof result.checked === "boolean" || result.checked === null) && typeof result.focused === "boolean" && (typeof result.value === "string" || result.value === null)))
1186
+ throw new PageScriptError("invalid-result", "Invalid control state.");
1187
+ return result;
1188
+ }
1189
+ async function visibleText(page) {
1190
+ const result = await call(page, "visibleText");
1191
+ return result && result.complete && typeof result.text === "string" ? result.text : null;
1192
+ }
1180
1193
 
1181
1194
  // src/report-privacy.ts
1182
1195
  function safeText(value, privacy, limit) {
@@ -1480,6 +1493,28 @@ var PlaywrightPage = class {
1480
1493
  throw operationError(error2, this.state(), "page");
1481
1494
  }
1482
1495
  }
1496
+ async history(move, options = {}) {
1497
+ const currentState = this.state();
1498
+ if (currentState.closed || currentState.crashed || currentState.disconnected) {
1499
+ throw operationError(
1500
+ new Error("page is not available"),
1501
+ currentState,
1502
+ "page"
1503
+ );
1504
+ }
1505
+ const navigation = {
1506
+ timeout: options.timeoutMs ?? DEFAULT_NAVIGATION_TIMEOUT_MS,
1507
+ waitUntil: options.waitUntil ?? "domcontentloaded"
1508
+ };
1509
+ try {
1510
+ if (move === "back") await this.page.goBack(navigation);
1511
+ else if (move === "forward") await this.page.goForward(navigation);
1512
+ else await this.page.reload(navigation);
1513
+ return { url: this.page.url() };
1514
+ } catch (error2) {
1515
+ throw safeOperationError(error2, this.state(), "History navigation");
1516
+ }
1517
+ }
1483
1518
  async settle(options = {}) {
1484
1519
  const currentState = this.state();
1485
1520
  if (currentState.closed || currentState.crashed || currentState.disconnected) {
@@ -1594,6 +1629,18 @@ var PlaywrightPage = class {
1594
1629
  },
1595
1630
  { expected: aim, element }
1596
1631
  );
1632
+ if (aim.hover) {
1633
+ const box = await element.boundingBox().catch(() => null);
1634
+ if (!box) return { actionable: false, reason: "not_actionable" };
1635
+ await this.page.mouse.move(box.x + aim.point.x, box.y + aim.point.y);
1636
+ try {
1637
+ await element.waitForElementState("visible", {
1638
+ timeout: Math.min(2e3, remaining())
1639
+ });
1640
+ } catch {
1641
+ return { actionable: false, reason: "not_actionable" };
1642
+ }
1643
+ }
1597
1644
  const still = await validateElement().catch(() => ({
1598
1645
  actionable: false,
1599
1646
  reason: "stale"
@@ -2221,6 +2268,16 @@ ${(result.callLog ?? []).join("\n")}`)
2221
2268
  );
2222
2269
  break;
2223
2270
  }
2271
+ case "history": {
2272
+ const before = await active(pageVersion(page));
2273
+ const timeoutMs = remaining(3e4, phase);
2274
+ phase = "post_dispatch";
2275
+ await active(page.history(command.move, { timeoutMs }));
2276
+ outcome = await active(
2277
+ observeRoute(page, "history", before, remaining)
2278
+ );
2279
+ break;
2280
+ }
2224
2281
  case "press": {
2225
2282
  if (!command.key.trim())
2226
2283
  throw new StepExecutionError(op, "invalid_input", phase);
@@ -2507,6 +2564,9 @@ function sameVisualVersion(a, b) {
2507
2564
  }
2508
2565
  async function captureVisionObservation(page, candidates, version, instruction, projectText = (text) => text) {
2509
2566
  if (!page.captureFrame) return null;
2567
+ const settled = await quietPage(page, 1e3, 4e3);
2568
+ if (!settled.quiet || !sameVisualVersion(settled.version, version))
2569
+ return null;
2510
2570
  const visual = await visualCandidates(page);
2511
2571
  if (!sameVisualVersion(visual.version, version)) return null;
2512
2572
  const boxes = visual.boxes.filter(
@@ -3524,7 +3584,13 @@ async function resolveTarget(page, resolver, options) {
3524
3584
  options.projectText
3525
3585
  );
3526
3586
  ensureActive();
3527
- if (!captured) return unresolved("ambiguous");
3587
+ if (!captured) {
3588
+ if (!sameVersion3(await pageVersion(page), source.version)) {
3589
+ gate = `${gate}:vision_stale_capture`;
3590
+ return unresolved("stale");
3591
+ }
3592
+ return unresolved("ambiguous");
3593
+ }
3528
3594
  let answer;
3529
3595
  const visionStarted = performance.now();
3530
3596
  try {
@@ -3557,11 +3623,16 @@ async function resolveTarget(page, resolver, options) {
3557
3623
  };
3558
3624
  ensureActive();
3559
3625
  if (!sameVersion3(await pageVersion(page), source.version)) {
3626
+ visionDiagnostic = { ...visionDiagnostic, failure: "stale_page" };
3560
3627
  gate = `${gate}:vision_stale`;
3561
3628
  return unresolved("ambiguous");
3562
3629
  }
3563
3630
  if (answer.decision.kind !== "candidate") {
3564
- visionDiagnostic = { ...visionDiagnostic, outcome: "abstained" };
3631
+ visionDiagnostic = {
3632
+ ...visionDiagnostic,
3633
+ outcome: "abstained",
3634
+ abstentionReason: answer.decision.reason
3635
+ };
3565
3636
  gate = `${gate}:vision_abstained`;
3566
3637
  return unresolved("ambiguous");
3567
3638
  }
@@ -3580,6 +3651,7 @@ async function resolveTarget(page, resolver, options) {
3580
3651
  diagnostic: { ...result.diagnostic, vision: visionDiagnostic }
3581
3652
  };
3582
3653
  }
3654
+ visionDiagnostic = { ...visionDiagnostic, failure: "stale_page" };
3583
3655
  return unresolved("ambiguous");
3584
3656
  } catch {
3585
3657
  if (!sameVersion3(await pageVersion(page), source.version)) {
@@ -4437,11 +4509,11 @@ function parseSteps(phase, raw, file, counter, nodes, knownData, diagnostics) {
4437
4509
  "A use step must reference a .module.yaml file.",
4438
4510
  "Write `use: path/to/login.module.yaml`."
4439
4511
  );
4440
- const withValues = mapping.with ?? {};
4512
+ const withValues2 = mapping.with ?? {};
4441
4513
  const withSources = /* @__PURE__ */ Object.create(
4442
4514
  null
4443
4515
  );
4444
- for (const [key, value] of Object.entries(withValues)) {
4516
+ for (const [key, value] of Object.entries(withValues2)) {
4445
4517
  withSources[key] = at(file, counter, nodes, [
4446
4518
  phase,
4447
4519
  index,
@@ -4467,7 +4539,7 @@ function parseSteps(phase, raw, file, counter, nodes, knownData, diagnostics) {
4467
4539
  kind: "module",
4468
4540
  phase,
4469
4541
  use: mapping.use,
4470
- with: withValues,
4542
+ with: withValues2,
4471
4543
  withSources,
4472
4544
  source,
4473
4545
  sourceStack: [source]
@@ -5244,6 +5316,8 @@ var VALUE_OPERAND = new RegExp(
5244
5316
  var BINDING = new RegExp(`\\bas\\s+${PLACEHOLDER}\\s*\\.?$`, "iu");
5245
5317
  var HTTP_URL = /https?:\/\/\S+/giu;
5246
5318
  var WAIT_DURATION = /^wait\s+(?:for\s+)?(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|seconds?)\s*\.?$/iu;
5319
+ var WAIT_UNTIL = /^wait\s+(?:up\s+to\s+\d+(?:\.\d+)?\s*(?:s|secs?|seconds?)\s+)?(?:until|for)\s+(?!\d+(?:\.\d+)?\s*(?:ms|milliseconds?|s|seconds?)\s*\.?$)\S/iu;
5320
+ var HISTORY_MOVE = /^(?:(?:go|navigate)\s+(?:back(?:\s+to\s+the\s+previous\s+page)?|forward)|(?:reload|refresh)(?:\s+the\s+page)?)\s*\.?$/iu;
5247
5321
  var DURATION_OPERAND = /\b(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|seconds?)\b/giu;
5248
5322
  var KNOWN_KEY = /\b(?:Enter|Tab|Escape|Esc|Space|Backspace|Delete|Arrow(?:Up|Down|Left|Right)|F(?:[1-9]|1[0-2]))\b/giu;
5249
5323
  var SECOND_ACTION_CONNECTOR = /\b(and|or|but|then|after|before|while|once|when|until|afterwards|subsequently|next|later|finally|followed\s+by|as\s+soon\s+as)\b\s+/giu;
@@ -5292,6 +5366,9 @@ function preflightSentence(sentence) {
5292
5366
  function patternOperation(sentence) {
5293
5367
  const text = canonicalSentence(sentence);
5294
5368
  if (preflightSentence(text)) return null;
5369
+ if (WAIT_UNTIL.test(text)) return "verify";
5370
+ if (HISTORY_MOVE.test(text) || /^(?:goto|go\s+to|navigate\s+to)\s+\/\S*\s*$/iu.test(text))
5371
+ return "goto";
5295
5372
  if (/^(?:click|type|enter|fill|press|goto|go\s+to|navigate\s+to|scroll|wait|remember|select|choose|pick)\b/iu.test(
5296
5373
  text
5297
5374
  ) && (withoutQuotes(text).match(SECOND_ACTION_CONNECTOR) !== null || /;|,\s*[A-Za-z]/u.test(withoutQuotes(text))))
@@ -5333,8 +5410,11 @@ function validateOperand(sentence, op) {
5333
5410
  if (!operand || quotes.length + placeholders.length !== 1)
5334
5411
  return 'Name one value, such as {{key}} or "{{user}}@example.com", and a field.';
5335
5412
  } else if (op === "goto") {
5413
+ if (HISTORY_MOVE.test(text) || /^(?:goto|go\s+to|navigate\s+to)\s+\/\S*\s*$/iu.test(text))
5414
+ return null;
5336
5415
  const urls = text.match(HTTP_URL) ?? [];
5337
- if (urls.length !== 1) return "Name exactly one http(s) address.";
5416
+ if (urls.length !== 1)
5417
+ return "Name exactly one http(s) address or a /path on this site.";
5338
5418
  } else if (op === "press") {
5339
5419
  const explicit = /^(?:press|hit|strike)\s+(?:the\s+)?(?:"[^"]+"|[\w-]+)(?:\s+key)?\s*\.?$/iu.test(
5340
5420
  text
@@ -5436,7 +5516,7 @@ async function classifySteps(input, options) {
5436
5516
  }
5437
5517
  const leading = canonicalSentence(step.sentence).match(/^(type|enter|fill|press|remember|goto|wait|scroll)\b/iu)?.[1]?.toLowerCase();
5438
5518
  const lexicalOp = leading === "type" || leading === "enter" || leading === "fill" ? "type" : leading === "press" || leading === "remember" || leading === "goto" || leading === "wait" || leading === "scroll" ? leading : null;
5439
- if (lexicalOp) {
5519
+ if (lexicalOp && !(lexicalOp === "wait" && WAIT_UNTIL.test(step.sentence))) {
5440
5520
  const operandError = validateOperand(step.sentence, lexicalOp);
5441
5521
  if (operandError) {
5442
5522
  fail(index, "invalid_operand", operandError);
@@ -6595,6 +6675,157 @@ function gotoUrlParts(sentence) {
6595
6675
  literals.push(rest);
6596
6676
  return { literals, names };
6597
6677
  }
6678
+ var WAIT_UNTIL_DEFAULT_MS = 3e4;
6679
+ var WAIT_UNTIL_MAX_MS = 12e4;
6680
+ function waitUntilTimeoutMs(sentence) {
6681
+ const text = canonicalSentence(sentence);
6682
+ if (!WAIT_UNTIL.test(text)) return null;
6683
+ const limit = /^wait\s+up\s+to\s+(\d+(?:\.\d+)?)/iu.exec(text);
6684
+ if (!limit) return WAIT_UNTIL_DEFAULT_MS;
6685
+ return Math.min(WAIT_UNTIL_MAX_MS, Math.max(1e3, Number(limit[1]) * 1e3));
6686
+ }
6687
+ var CONTROL_NOUN = "button|link|field|input|text\\s*box|search\\s*box|box|checkbox|check\\s*box|radio(?:\\s+button)?|toggle|switch|dropdown|select|tab|menu\\s+item|option|icon";
6688
+ var FIELD_NOUN = /\b(?:field|input|text\s*box|search\s*box|box)$/iu;
6689
+ var STATE_CLAIM = new RegExp(
6690
+ `^(?:the\\s+|a\\s+|an\\s+)?(.+?\\b(?:${CONTROL_NOUN}))\\s+(?:is|are)\\s+(not\\s+)?(shown|visible|displayed|present|enabled|disabled|checked|unchecked|ticked|focused|empty)\\s*\\.?$`,
6691
+ "iu"
6692
+ );
6693
+ var VALUE_CLAIM = new RegExp(
6694
+ `^(?:the\\s+)?(.+?\\b(?:field|input|text\\s*box|search\\s*box|box))\\s+(?:contains|shows|has\\s+the\\s+value|has\\s+value|is\\s+set\\s+to|reads)\\s+(.+?)\\s*\\.?$`,
6695
+ "iu"
6696
+ );
6697
+ function elementClaim(claim2) {
6698
+ const text = canonicalSentence(claim2);
6699
+ if (/^(?:there\s+is\s+)?no\s+/iu.test(text)) return null;
6700
+ const valued = VALUE_CLAIM.exec(text);
6701
+ if (valued)
6702
+ return {
6703
+ target: valued[1],
6704
+ operation: "fill",
6705
+ expect: {
6706
+ kind: "value",
6707
+ value: valued[2].replace(/^(["“'])(.*)(["”'])$/u, "$2")
6708
+ }
6709
+ };
6710
+ const state2 = STATE_CLAIM.exec(text);
6711
+ if (!state2) return null;
6712
+ const target = state2[1];
6713
+ const negated = !!state2[2];
6714
+ const word = state2[3].toLowerCase();
6715
+ const fill = FIELD_NOUN.test(target);
6716
+ const expect = [
6717
+ "shown",
6718
+ "visible",
6719
+ "displayed",
6720
+ "present"
6721
+ ].includes(word) ? negated ? null : { kind: "present", present: true } : word === "enabled" ? { kind: "disabled", disabled: negated } : word === "disabled" ? { kind: "disabled", disabled: !negated } : ["checked", "ticked"].includes(word) ? { kind: "checked", checked: !negated } : word === "unchecked" ? { kind: "checked", checked: negated } : word === "focused" ? { kind: "focused", focused: !negated } : word === "empty" && fill ? { kind: "empty", empty: !negated } : null;
6722
+ if (!expect) return null;
6723
+ return {
6724
+ target,
6725
+ operation: fill && expect.kind !== "disabled" ? "fill" : "click",
6726
+ expect
6727
+ };
6728
+ }
6729
+ var QUOTED = `(?:"([^"]+)"|\u201C([^\u201D]+)\u201D)`;
6730
+ var SHOWN = "(?:shown|visible|displayed|present|on\\s+the\\s+page)";
6731
+ var QUOTED_LIST = `((?:"[^"]+"|\u201C[^\u201D]+\u201D)(?:\\s*(?:,|or|,\\s*or)\\s*(?:"[^"]+"|\u201C[^\u201D]+\u201D))*)`;
6732
+ var TEXT_PRESENCE = new RegExp(
6733
+ `^(?:the\\s+)?(?:texts?\\s+)?${QUOTED_LIST}\\s+(?:is|are)\\s+(not\\s+)?${SHOWN}\\s*\\.?$`,
6734
+ "iu"
6735
+ );
6736
+ var quotedTexts = (list) => [...list.matchAll(/"([^"]+)"|“([^”]+)”/gu)].map((m) => m[1] ?? m[2]);
6737
+ var TEXT_ABSENCE = new RegExp(
6738
+ `^(?:there\\s+is\\s+)?no\\s+(?:text\\s+)?${QUOTED}(?:\\s+is)?\\s+${SHOWN}\\s*\\.?$|^(?:the\\s+)?(?:text\\s+)?${QUOTED}\\s+does\\s+not\\s+appear\\s*\\.?$`,
6739
+ "iu"
6740
+ );
6741
+ var TEXT_COUNT = new RegExp(
6742
+ `^(?:the\\s+)?(?:text\\s+)?${QUOTED}\\s+(?:appears|is\\s+shown|occurs)\\s+(?:exactly\\s+)?(once|twice|\\d+\\s+times?)\\s*\\.?$`,
6743
+ "iu"
6744
+ );
6745
+ function literalShown(claim2) {
6746
+ const text = canonicalSentence(claim2);
6747
+ if (/["“]/u.test(text)) return null;
6748
+ const literal = LITERAL_PRESENCE.exec(text);
6749
+ return literal && !literal[2] ? literal[1] : null;
6750
+ }
6751
+ var LITERAL_PRESENCE = /^the\s+text\s+(.+?)\s+(?:is|are)\s+(not\s+)?(?:shown|visible|displayed|present|on\s+the\s+page)\s*$/iu;
6752
+ var URL_CLAIM = new RegExp(
6753
+ `^(?:the\\s+)?(?:page\\s+|current\\s+)?(?:url|address)\\s+(does\\s+not\\s+contain|contains|includes)\\s+${QUOTED_LIST}\\s*\\.?$`,
6754
+ "iu"
6755
+ );
6756
+ function textClaim(claim2) {
6757
+ const text = canonicalSentence(claim2);
6758
+ const url = URL_CLAIM.exec(text);
6759
+ if (url) {
6760
+ const texts = quotedTexts(url[2]);
6761
+ return {
6762
+ text: texts[0],
6763
+ ...texts.length > 1 ? { alternatives: texts } : {},
6764
+ expect: { kind: "url", contains: !/not/iu.test(url[1]) }
6765
+ };
6766
+ }
6767
+ const presence = TEXT_PRESENCE.exec(text);
6768
+ if (presence) {
6769
+ const texts = quotedTexts(presence[1]);
6770
+ return {
6771
+ text: texts[0],
6772
+ ...texts.length > 1 ? { alternatives: texts } : {},
6773
+ expect: { kind: "present", present: !presence[2] }
6774
+ };
6775
+ }
6776
+ const absence = TEXT_ABSENCE.exec(text);
6777
+ if (absence)
6778
+ return {
6779
+ text: absence[1] ?? absence[2] ?? absence[3] ?? absence[4],
6780
+ expect: { kind: "present", present: false }
6781
+ };
6782
+ const counted = TEXT_COUNT.exec(text);
6783
+ if (!counted) return null;
6784
+ const word = counted[3].toLowerCase();
6785
+ return {
6786
+ text: counted[1] ?? counted[2],
6787
+ expect: {
6788
+ kind: "count",
6789
+ count: word === "once" ? 1 : word === "twice" ? 2 : Number.parseInt(word, 10)
6790
+ }
6791
+ };
6792
+ }
6793
+ function countText(haystack, needle, ignoreCase = false) {
6794
+ const space = (text) => {
6795
+ const spaced = text.replace(/\s+/gu, " ").trim();
6796
+ return ignoreCase ? spaced.toLocaleLowerCase() : spaced;
6797
+ };
6798
+ const page = space(haystack);
6799
+ const wanted = space(needle);
6800
+ if (!wanted) return 0;
6801
+ return page.split(wanted).length - 1;
6802
+ }
6803
+ function historyMove(sentence) {
6804
+ const text = canonicalSentence(sentence).replace(/\.$/u, "");
6805
+ if (/^(?:go|navigate)\s+back(?:\s+to\s+the\s+previous\s+page)?$/iu.test(text))
6806
+ return "back";
6807
+ if (/^(?:go|navigate)\s+forward$/iu.test(text)) return "forward";
6808
+ if (/^(?:reload|refresh)(?:\s+the\s+page)?$/iu.test(text)) return "reload";
6809
+ return null;
6810
+ }
6811
+ function gotoPathParts(sentence) {
6812
+ const path11 = /^(?:goto|go\s+to|navigate\s+to|open)\s+(\/\S*)\s*$/iu.exec(
6813
+ canonicalSentence(sentence)
6814
+ )?.[1];
6815
+ if (!path11) return null;
6816
+ const literals = [];
6817
+ const names = [];
6818
+ let rest = path11.replace(/[.,;]+$/u, "");
6819
+ for (; ; ) {
6820
+ const match = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/u.exec(rest);
6821
+ if (!match) break;
6822
+ literals.push(rest.slice(0, match.index));
6823
+ names.push(match[1]);
6824
+ rest = rest.slice(match.index + match[0].length);
6825
+ }
6826
+ literals.push(rest);
6827
+ return { literals, names };
6828
+ }
6598
6829
 
6599
6830
  // src/flow-runner.ts
6600
6831
  function resultCall(call2, purpose, apiMs = null) {
@@ -6737,9 +6968,16 @@ function runtimeFailure(file, error2) {
6737
6968
  fix: "Check the browser, provider, and test input, then rerun the test."
6738
6969
  };
6739
6970
  }
6971
+ var CLAIM_PREFIX = /^\s*(?:verify|assert|check|confirm|ensure|expect|measure|note|observe|wait\s+(?:up\s+to\s+\d+(?:\.\d+)?\s*(?:s|secs?|seconds?)\s+)?(?:until|for))\b\s*(?:that\s+|whether\s+|if\s+)?/iu;
6972
+ function withValues(text, data) {
6973
+ return text.replace(
6974
+ /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
6975
+ (placeholder, key) => data[key]?.modelVisible ? data[key].value.reveal() : placeholder
6976
+ );
6977
+ }
6740
6978
  function claim(step, data) {
6741
6979
  return step.text.replace(
6742
- /^\s*(?:verify|assert|check|confirm|ensure|expect|measure|note|observe)\b\s*(?:that\s+|whether\s+|if\s+)?/iu,
6980
+ /^\s*(?:verify|assert|check|confirm|ensure|expect|measure|note|observe|wait\s+(?:up\s+to\s+\d+(?:\.\d+)?\s*(?:s|secs?|seconds?)\s+)?(?:until|for))\b\s*(?:that\s+|whether\s+|if\s+)?/iu,
6743
6981
  ""
6744
6982
  ).trim().replace(
6745
6983
  /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
@@ -6854,12 +7092,12 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
6854
7092
  const acceptedVersion = facts.verify?.observationVersion ?? (locator?.kind === "resolved" ? locator.target.driverTarget().version : locator?.diagnostic.observationVersion);
6855
7093
  const sensitive = facts.page?.status === "omitted" && facts.page.reason === "sensitive_page" || acceptedVersion !== void 0 && safeUrl(acceptedVersion.route, privacy).sensitive || safeUrl(page.url, privacy).sensitive;
6856
7094
  const isError = typeof outcome === "object" && outcome.status === "could_not_run";
6857
- const failed = outcome === "failed" || typeof outcome === "object" && outcome.status === "failed";
7095
+ const failed = outcome === "failed" && !presentation.check || typeof outcome === "object" && outcome.status === "failed";
6858
7096
  const flags = facts.verify?.kind === "verify" ? facts.verify.flags : [];
6859
7097
  const needsEvidence = failed || isError || flags.length > 0;
6860
7098
  const evidence = !needsEvidence ? { status: "omitted", reason: "clean_step" } : sensitive ? { status: "omitted", reason: "sensitive_page" } : !report.evidenceEnabled ? { status: "omitted", reason: "disabled" } : await capture("evidence", acceptedVersion);
6861
7099
  const replayFrame2 = !report.replay ? null : sensitive ? { status: "omitted", reason: "sensitive_page" } : facts.replayFrame ?? await capture("replay", acceptedVersion);
6862
- const kind = step.op === "verify" ? "verify" : step.op === "measure" ? "measure" : "action";
7100
+ const kind = step.op === "measure" || step.op === "verify" && presentation.check ? "measure" : step.op === "verify" ? "verify" : "action";
6863
7101
  const pageInfo = facts.page ?? await reportPage(
6864
7102
  page,
6865
7103
  `${stepId}:observation:1`,
@@ -6938,9 +7176,15 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
6938
7176
  await report.test.addStep(result);
6939
7177
  return outcome;
6940
7178
  };
6941
- const runWide = async (error2) => {
7179
+ const runWide = async (error2, facts = {}) => {
6942
7180
  const outcome = providerFailure(step.source.file, error2);
7181
+ const modality = step.op === "verify" || step.op === "measure" ? "judge" : "locator";
6943
7182
  await record(outcome, {
7183
+ ...facts,
7184
+ failedCalls: [
7185
+ ...facts.failedCalls ?? [],
7186
+ resultCall(unknownCostCall(error2), modality)
7187
+ ],
6944
7188
  error: { code: outcome.code, message: outcome.message }
6945
7189
  });
6946
7190
  return error2;
@@ -6948,7 +7192,8 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
6948
7192
  const quiet = await quietPage(page, 80, 4e3).catch(() => ({
6949
7193
  quiet: false
6950
7194
  }));
6951
- if (!quiet.quiet)
7195
+ const waits = step.op === "verify" && waitUntilTimeoutMs(step.text) !== null;
7196
+ if (!quiet.quiet && !waits)
6952
7197
  return record(
6953
7198
  unsupported(
6954
7199
  step.source.file,
@@ -6984,6 +7229,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
6984
7229
  }
6985
7230
  }
6986
7231
  if (step.op === "remember") {
7232
+ const targetLabel = presentation.display?.startsWith("extract ") ? "extract" : "remember";
6987
7233
  const match = /^(?:remember|capture)\s+(.+?)\s+as\s+\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}\s*\.?$/iu.exec(
6988
7234
  step.text.trim()
6989
7235
  );
@@ -7022,16 +7268,29 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7022
7268
  locator,
7023
7269
  error: {
7024
7270
  code: locator.reason,
7025
- message: "The remember target could not be resolved."
7271
+ message: `The ${targetLabel} target could not be resolved.`
7026
7272
  }
7027
7273
  });
7028
- const read = await readTarget(page, locator.target.driverTarget());
7274
+ let read = await readTarget(page, locator.target.driverTarget());
7275
+ if (read.status === "stale") {
7276
+ locator = await reobserve(
7277
+ page,
7278
+ { ...locator, kind: "unresolved", reason: "stale" },
7279
+ locateRead,
7280
+ {
7281
+ staleRetry: true,
7282
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
7283
+ }
7284
+ );
7285
+ if (locator.kind === "resolved")
7286
+ read = await readTarget(page, locator.target.driverTarget());
7287
+ }
7029
7288
  if (read.status !== "ok")
7030
7289
  return record("failed", {
7031
7290
  locator,
7032
7291
  error: {
7033
7292
  code: `remember_${read.status}`,
7034
- message: "The remember target did not contain usable text."
7293
+ message: `The ${targetLabel} target did not contain usable text.`
7035
7294
  }
7036
7295
  });
7037
7296
  remembered = read.text;
@@ -7041,7 +7300,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7041
7300
  ...locator ? { locator } : {},
7042
7301
  error: {
7043
7302
  code: "remember_invalid_text",
7044
- message: "The remember target did not contain usable text."
7303
+ message: `The ${targetLabel} target did not contain usable text.`
7045
7304
  }
7046
7305
  });
7047
7306
  const echoedSecrets = opaqueMatches(remembered, opaqueEntries);
@@ -7079,11 +7338,286 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7079
7338
  ...dependencies.signal ? { signal: dependencies.signal } : {},
7080
7339
  projectText: (text) => redactOpaqueText(text, opaqueEntries)
7081
7340
  };
7082
- const judge = () => step.op === "measure" ? measure(page, dependencies.provider, claim(step, data), assertion) : verify(page, dependencies.provider, claim(step, data), {
7341
+ const judge = (signal = dependencies.signal, observationTimeoutMs) => step.op === "measure" ? measure(page, dependencies.provider, claim(step, data), {
7083
7342
  ...assertion,
7343
+ ...signal ? { signal } : {},
7344
+ ...observationTimeoutMs === void 0 ? {} : { observationTimeoutMs }
7345
+ }) : verify(page, dependencies.provider, claim(step, data), {
7346
+ ...assertion,
7347
+ ...signal ? { signal } : {},
7348
+ ...observationTimeoutMs === void 0 ? {} : { observationTimeoutMs },
7084
7349
  ...dependencies.verifyPolicy ?? {}
7085
7350
  });
7086
7351
  const outcome = (result) => result.kind === "verify" && result.verdict === "failed" ? "failed" : "continue";
7352
+ const readableText = async () => {
7353
+ const text = await visibleText(page);
7354
+ if (text === null) throw new Error("The page text could not be read.");
7355
+ return text;
7356
+ };
7357
+ const literalText = step.op === "verify" ? literalShown(step.text.replace(CLAIM_PREFIX, "")) : null;
7358
+ const literal = literalText ? withValues(literalText, data) : null;
7359
+ const waitUntil = async (limitMs, pollUnchangedMs) => {
7360
+ const bounded = limitMs > 0;
7361
+ const deadline = performance.now() + limitMs;
7362
+ const earlier = [];
7363
+ let last;
7364
+ let lastError;
7365
+ for (; ; ) {
7366
+ if (dependencies.signal?.aborted) {
7367
+ if (last)
7368
+ earlier.push(resultCall(last.call, "judge", last.elapsedMs));
7369
+ last = void 0;
7370
+ lastError = new AssertionEngineError("canceled");
7371
+ break;
7372
+ }
7373
+ const before = await pageVersion(page).catch(() => null);
7374
+ if (literal) {
7375
+ await quietPage(page, 80, 2e3).catch(() => void 0);
7376
+ const shown = await readableText().then((text) => countText(text, literal, true) > 0).catch(() => false);
7377
+ if (shown) return record("continue", { failedCalls: earlier });
7378
+ }
7379
+ try {
7380
+ let result;
7381
+ if (!bounded) result = await judge();
7382
+ else {
7383
+ const remainingMs = Math.max(
7384
+ 1,
7385
+ Math.ceil(deadline - performance.now())
7386
+ );
7387
+ const deadlineSignal = AbortSignal.timeout(remainingMs);
7388
+ const signal = dependencies.signal ? AbortSignal.any([dependencies.signal, deadlineSignal]) : deadlineSignal;
7389
+ result = await judge(signal, remainingMs);
7390
+ }
7391
+ if (outcome(result) === "continue")
7392
+ return record("continue", {
7393
+ verify: result,
7394
+ // Every earlier judgement was billed too.
7395
+ failedCalls: last ? [...earlier, resultCall(last.call, "judge", last.elapsedMs)] : earlier
7396
+ });
7397
+ if (last)
7398
+ earlier.push(resultCall(last.call, "judge", last.elapsedMs));
7399
+ last = result;
7400
+ lastError = void 0;
7401
+ } catch (error2) {
7402
+ if (isRunWideProviderError(error2)) {
7403
+ const failedCalls = [...earlier];
7404
+ if (last)
7405
+ failedCalls.push(resultCall(last.call, "judge", last.elapsedMs));
7406
+ throw await runWide(error2, { failedCalls });
7407
+ }
7408
+ if (error2 instanceof AssertionEngineError && error2.failedCall)
7409
+ earlier.push(resultCall(error2.failedCall, "judge"));
7410
+ if (bounded && performance.now() >= deadline && !dependencies.signal?.aborted) {
7411
+ lastError = error2 instanceof AssertionEngineError ? new AssertionEngineError(
7412
+ "observation_timeout",
7413
+ error2.failedCall
7414
+ ) : new AssertionEngineError("observation_timeout");
7415
+ break;
7416
+ }
7417
+ if (!(error2 instanceof AssertionEngineError) || ![
7418
+ "stale_observation",
7419
+ "observation_timeout",
7420
+ "browser_failure",
7421
+ // Too much text to judge: the literal can still turn up.
7422
+ ...literal ? ["oversize_digest", "resource_ceiling"] : []
7423
+ ].includes(error2.code)) {
7424
+ lastError = error2;
7425
+ break;
7426
+ }
7427
+ lastError = error2;
7428
+ }
7429
+ let changed = false;
7430
+ const pollBy = pollUnchangedMs === null ? deadline : Math.min(deadline, performance.now() + pollUnchangedMs);
7431
+ while (performance.now() < pollBy) {
7432
+ await new Promise((resolve) => setTimeout(resolve, 200));
7433
+ if (dependencies.signal?.aborted) break;
7434
+ const now = await pageVersion(page).catch(() => null);
7435
+ if (!before || !now) {
7436
+ changed = true;
7437
+ break;
7438
+ }
7439
+ if (now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
7440
+ changed = true;
7441
+ break;
7442
+ }
7443
+ }
7444
+ if (dependencies.signal?.aborted) {
7445
+ if (last)
7446
+ earlier.push(resultCall(last.call, "judge", last.elapsedMs));
7447
+ last = void 0;
7448
+ lastError = new AssertionEngineError("canceled");
7449
+ break;
7450
+ }
7451
+ if (performance.now() >= deadline && !changed) break;
7452
+ if (!changed && pollUnchangedMs === null) break;
7453
+ await quietPage(page, 80, 2e3).catch(() => void 0);
7454
+ if (performance.now() >= deadline) break;
7455
+ }
7456
+ if (last)
7457
+ return record(outcome(last), { verify: last, failedCalls: earlier });
7458
+ return record(
7459
+ unsupported(
7460
+ step.source.file,
7461
+ step.source,
7462
+ lastError instanceof Error ? lastError.message : "The assertion could not be judged."
7463
+ ),
7464
+ {
7465
+ failedCalls: earlier,
7466
+ error: {
7467
+ code: lastError instanceof AssertionEngineError ? lastError.code : "assertion_error",
7468
+ message: "The assertion could not be judged."
7469
+ }
7470
+ }
7471
+ );
7472
+ };
7473
+ const checkElement = async (element2, limitMs) => {
7474
+ const deadline = performance.now() + limitMs;
7475
+ const earlier = [];
7476
+ let last;
7477
+ let message = "The control is not in the expected state.";
7478
+ let staleRetried = false;
7479
+ const target = withValues(element2.target, data);
7480
+ const locateAs = (operation) => resolveTarget(page, dependencies.provider, {
7481
+ operation,
7482
+ sentence: operation === "fill" ? `type into ${target}` : `click ${target}`,
7483
+ projectText: (text) => redactOpaqueText(text, opaqueEntries),
7484
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
7485
+ });
7486
+ const locate2 = async () => {
7487
+ const found = await locateAs(element2.operation);
7488
+ if (element2.operation !== "fill" || found.kind === "resolved" || found.reason !== "none" && found.reason !== "no_candidates")
7489
+ return found;
7490
+ const control = await locateAs("click");
7491
+ return control.kind === "resolved" && ["input", "textarea"].includes(control.target.driverTarget().tag) ? { ...control, calls: [...found.calls, ...control.calls] } : { ...found, calls: [...found.calls, ...control.calls] };
7492
+ };
7493
+ const expected = element2.expect;
7494
+ for (; ; ) {
7495
+ if (dependencies.signal?.aborted) break;
7496
+ const before = await pageVersion(page).catch(() => null);
7497
+ if (last)
7498
+ earlier.push(
7499
+ ...last.calls.map((call2) => resultCall(call2, "locator"))
7500
+ );
7501
+ last = await reobserve(page, await locate2(), locate2, {
7502
+ staleRetry: true,
7503
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
7504
+ });
7505
+ let holds = false;
7506
+ if (last.kind !== "resolved") {
7507
+ const missing2 = last.reason === "none" || last.reason === "no_candidates";
7508
+ holds = missing2 && expected.kind === "present" && !expected.present;
7509
+ message = missing2 ? "No such control is on the page." : `The control could not be found (${last.reason}).`;
7510
+ } else if (expected.kind === "present") {
7511
+ holds = expected.present;
7512
+ message = "The control is on the page.";
7513
+ } else {
7514
+ const state2 = await controlState(page, last.target.driverTarget());
7515
+ if (state2.status === "ok") {
7516
+ const value = (text) => text.replace(/\s+/gu, " ").trim();
7517
+ const wanted = expected.kind === "value" ? value(
7518
+ expected.value.replace(
7519
+ /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
7520
+ (placeholder, key) => data[key]?.value.reveal() ?? placeholder
7521
+ )
7522
+ ) : "";
7523
+ holds = expected.kind === "disabled" ? state2.disabled === expected.disabled : expected.kind === "checked" ? state2.checked === expected.checked : expected.kind === "focused" ? state2.focused === expected.focused : expected.kind === "empty" ? state2.value !== null && value(state2.value) === "" === expected.empty : state2.value !== null && value(state2.value) === wanted;
7524
+ message = expected.kind === "disabled" ? `The control is ${state2.disabled ? "disabled" : "enabled"}.` : expected.kind === "checked" ? state2.checked === null ? "The control cannot be checked." : `The control is ${state2.checked ? "checked" : "unchecked"}.` : expected.kind === "focused" ? `The control is ${state2.focused ? "" : "not "}focused.` : state2.value === null ? "The control holds no readable value." : "The field holds a different value.";
7525
+ } else {
7526
+ message = "The page changed while the control was read.";
7527
+ if (!staleRetried) {
7528
+ staleRetried = true;
7529
+ await quietPage(page, 80, 2e3).catch(() => void 0);
7530
+ continue;
7531
+ }
7532
+ }
7533
+ }
7534
+ if (holds)
7535
+ return record("continue", { locator: last, failedCalls: earlier });
7536
+ let changed = false;
7537
+ while (performance.now() < deadline) {
7538
+ await new Promise((resolve) => setTimeout(resolve, 200));
7539
+ const now = await pageVersion(page).catch(() => null);
7540
+ if (!before || !now) {
7541
+ changed = true;
7542
+ break;
7543
+ }
7544
+ if (now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
7545
+ changed = true;
7546
+ break;
7547
+ }
7548
+ }
7549
+ if (!changed) break;
7550
+ await quietPage(page, 80, 2e3).catch(() => void 0);
7551
+ }
7552
+ return record("failed", {
7553
+ ...last ? { locator: last } : {},
7554
+ failedCalls: earlier,
7555
+ error: { code: "element_state", message }
7556
+ });
7557
+ };
7558
+ const checkText = async (claimed, limitMs) => {
7559
+ const deadline = performance.now() + limitMs;
7560
+ const reveal = (text) => text.replace(
7561
+ /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
7562
+ (placeholder, key) => data[key]?.value.reveal() ?? placeholder
7563
+ );
7564
+ const wanted = (claimed.alternatives ?? [claimed.text]).map(reveal);
7565
+ let message = "";
7566
+ for (; ; ) {
7567
+ const before = await pageVersion(page).catch(() => null);
7568
+ await quietPage(page, 80, 2e3).catch(() => void 0);
7569
+ let found;
7570
+ try {
7571
+ const haystack = claimed.expect.kind === "url" ? "" : await readableText();
7572
+ found = wanted.reduce(
7573
+ (sum, text) => sum + (claimed.expect.kind === "url" ? Number(page.url.includes(text)) : countText(haystack, text, claimed.ignoreCase)),
7574
+ 0
7575
+ );
7576
+ } catch {
7577
+ return record(
7578
+ unsupported(
7579
+ step.source.file,
7580
+ step.source,
7581
+ "The page text could not be read."
7582
+ ),
7583
+ {
7584
+ error: {
7585
+ code: "text_unreadable",
7586
+ message: "The page text could not be read."
7587
+ }
7588
+ }
7589
+ );
7590
+ }
7591
+ const expected = claimed.expect;
7592
+ const holds = expected.kind === "present" ? found > 0 === expected.present : expected.kind === "url" ? found > 0 === expected.contains : found === expected.count;
7593
+ if (holds) return record("continue", {});
7594
+ message = expected.kind === "url" ? `The page address ${found ? "contains" : "does not contain"} the text.` : found === 0 ? "The text is not on the page." : `The text appears ${found === 1 ? "once" : `${found} times`} on the page.`;
7595
+ let changed = false;
7596
+ while (performance.now() < deadline) {
7597
+ await new Promise((resolve) => setTimeout(resolve, 200));
7598
+ const now = await pageVersion(page).catch(() => null);
7599
+ if (!before || !now) {
7600
+ changed = true;
7601
+ break;
7602
+ }
7603
+ if (now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
7604
+ changed = true;
7605
+ break;
7606
+ }
7607
+ }
7608
+ if (!changed) break;
7609
+ }
7610
+ return record("failed", { error: { code: "text_check", message } });
7611
+ };
7612
+ const until = step.op === "verify" ? waitUntilTimeoutMs(step.text) : null;
7613
+ const quoted = step.op === "verify" ? textClaim(step.text.replace(CLAIM_PREFIX, "")) : null;
7614
+ const graceMs = presentation.check ? 0 : dependencies.verifyGraceMs ?? 0;
7615
+ if (quoted) return checkText(quoted, until ?? graceMs);
7616
+ const element = step.op === "verify" ? elementClaim(step.text.replace(CLAIM_PREFIX, "")) : null;
7617
+ if (element) return checkElement(element, until ?? graceMs);
7618
+ if (until !== null) return waitUntil(until, 5e3);
7619
+ if (step.op === "verify" && (graceMs > 0 || literal))
7620
+ return waitUntil(graceMs, null);
7087
7621
  try {
7088
7622
  const result = await judge();
7089
7623
  return record(outcome(result), {
@@ -7105,7 +7639,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7105
7639
  });
7106
7640
  } catch (retryError) {
7107
7641
  if (isRunWideProviderError(retryError))
7108
- throw await runWide(retryError);
7642
+ throw await runWide(retryError, { failedCalls: priorCalls });
7109
7643
  return record(
7110
7644
  unsupported(
7111
7645
  step.source.file,
@@ -7178,24 +7712,47 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7178
7712
  deltaY: direction === "down" ? deltaY : -deltaY
7179
7713
  };
7180
7714
  } else {
7181
- const parts = gotoUrlParts(step.text);
7182
- if (parts === null) return invalid("Name exactly one http(s) address.");
7183
- const values = parts.names.map((name) => data[name]?.value);
7184
- if (values.some((value) => value === void 0))
7185
- return record("failed", {
7186
- error: {
7187
- code: "missing_remembered_binding",
7188
- message: "This step needs a value that is unavailable in this attempt."
7189
- }
7190
- });
7191
- const url = new RuntimeUrl(parts.literals, values);
7192
- try {
7193
- new URL(url.reveal());
7194
- } catch {
7195
- return invalid("The goto address is not a valid URL.");
7715
+ const move = historyMove(step.text);
7716
+ const path11 = move ? null : gotoPathParts(step.text);
7717
+ let origin = "";
7718
+ if (path11) {
7719
+ try {
7720
+ origin = new URL(page.url).origin;
7721
+ } catch {
7722
+ return invalid("A /path needs a page on a site to start from.");
7723
+ }
7724
+ if (!/^https?:/u.test(origin))
7725
+ return invalid("A /path needs a page on a site to start from.");
7726
+ }
7727
+ const parts = move ? null : path11 ? {
7728
+ ...path11,
7729
+ literals: [origin + path11.literals[0], ...path11.literals.slice(1)]
7730
+ } : gotoUrlParts(step.text);
7731
+ if (move) {
7732
+ command2 = { op: "history", move };
7733
+ detail = move === "reload" ? "Reloaded the page." : `Went ${move} in history.`;
7734
+ } else if (parts === null)
7735
+ return invalid(
7736
+ "Name exactly one http(s) address or a /path on this site."
7737
+ );
7738
+ else {
7739
+ const values = parts.names.map((name) => data[name]?.value);
7740
+ if (values.some((value) => value === void 0))
7741
+ return record("failed", {
7742
+ error: {
7743
+ code: "missing_remembered_binding",
7744
+ message: "This step needs a value that is unavailable in this attempt."
7745
+ }
7746
+ });
7747
+ const url = new RuntimeUrl(parts.literals, values);
7748
+ try {
7749
+ new URL(url.reveal());
7750
+ } catch {
7751
+ return invalid("The goto address is not a valid URL.");
7752
+ }
7753
+ command2 = { op: "goto", url };
7754
+ detail = `Opened ${url.toString()}.`;
7196
7755
  }
7197
- command2 = { op: "goto", url };
7198
- detail = `Opened ${url.toString()}.`;
7199
7756
  }
7200
7757
  try {
7201
7758
  await executeStep(page, command2, {
@@ -7291,6 +7848,56 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7291
7848
  }
7292
7849
  );
7293
7850
  }
7851
+ const missing = (result) => result.kind !== "resolved" && (result.reason === "none" || result.reason === "no_candidates");
7852
+ const actionGraceMs = dependencies.verifyGraceMs ?? 0;
7853
+ if (missing(resolved) && actionGraceMs > 0) {
7854
+ const deadline = performance.now() + actionGraceMs;
7855
+ const earlier = [];
7856
+ while (missing(resolved) && performance.now() < deadline && !dependencies.signal?.aborted) {
7857
+ const before = (resolved.kind !== "resolved" ? resolved.diagnostic.observationVersion : void 0) ?? await pageVersion(page).catch(() => null);
7858
+ let changed = false;
7859
+ while (performance.now() < deadline) {
7860
+ if (dependencies.signal?.aborted) break;
7861
+ const now = await pageVersion(page).catch(() => null);
7862
+ if (!before || !now || now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
7863
+ changed = true;
7864
+ break;
7865
+ }
7866
+ await new Promise((resolve) => setTimeout(resolve, 200));
7867
+ }
7868
+ if (!changed) break;
7869
+ await quietPage(page, 80, 2e3).catch(() => void 0);
7870
+ earlier.push(...resolved.calls);
7871
+ try {
7872
+ resolved = await locate();
7873
+ } catch (error2) {
7874
+ if (isRunWideProviderError(error2)) {
7875
+ const failedCalls = earlier.map(
7876
+ (call2) => resultCall(call2, "locator")
7877
+ );
7878
+ throw await runWide(error2, { failedCalls });
7879
+ }
7880
+ break;
7881
+ }
7882
+ }
7883
+ if (earlier.length)
7884
+ resolved = { ...resolved, calls: [...earlier, ...resolved.calls] };
7885
+ }
7886
+ if (dependencies.signal?.aborted)
7887
+ return record(
7888
+ unsupported(
7889
+ step.source.file,
7890
+ step.source,
7891
+ "The target could not be resolved because the run was canceled."
7892
+ ),
7893
+ {
7894
+ locator: resolved,
7895
+ error: {
7896
+ code: "canceled",
7897
+ message: "The target could not be resolved because the run was canceled."
7898
+ }
7899
+ }
7900
+ );
7294
7901
  if (resolved.kind !== "resolved") {
7295
7902
  if (resolved.reason === "none" || resolved.reason === "ambiguous" || resolved.reason === "no_candidates")
7296
7903
  return record("failed", {
@@ -8670,6 +9277,52 @@ function scanScriptSentences(source, file) {
8670
9277
  call2(index + 1);
8671
9278
  continue;
8672
9279
  }
9280
+ const member = isPunct(index + 1, ".") ? index + 2 : isPunct(index + 1, "?") && isPunct(index + 2, ".") ? index + 3 : void 0;
9281
+ let holdsOpen;
9282
+ if (member !== void 0 && at2(member)?.kind === "ident" && at2(member).value === "holds") {
9283
+ const after = member + 1;
9284
+ if (isPunct(after, "(")) holdsOpen = after;
9285
+ else if (isPunct(after, "?") && isPunct(after + 1, ".") && isPunct(after + 2, "("))
9286
+ holdsOpen = after + 2;
9287
+ }
9288
+ if (holdsOpen !== void 0) {
9289
+ const first = holdsOpen + 1;
9290
+ const firstToken = at2(first);
9291
+ const declared2 = firstToken?.kind === "ident" ? constants3.get(firstToken.value) : void 0;
9292
+ if (isPunct(first, ")") || isPunct(first, "[") || declared2 !== void 0 && isPunct(declared2, "[")) {
9293
+ unchecked(
9294
+ token,
9295
+ "ai.holds requires one string claim, so this value is not checked before a run."
9296
+ );
9297
+ continue;
9298
+ }
9299
+ const afterClaim = skipExpression(first);
9300
+ if (isPunct(afterClaim, ",")) {
9301
+ const valuesIndex = afterClaim + 1;
9302
+ const values = at2(valuesIndex);
9303
+ const afterValues = skipExpression(valuesIndex);
9304
+ const validValues = isPunct(valuesIndex, "{") || values?.kind === "ident" && values.value !== "null";
9305
+ if (!validValues || isPunct(afterValues, ",")) {
9306
+ unchecked(
9307
+ token,
9308
+ "This ai.holds call has invalid or extra arguments, so its claim is not checked before a run."
9309
+ );
9310
+ continue;
9311
+ }
9312
+ }
9313
+ const before = sentences.length;
9314
+ call2(holdsOpen);
9315
+ for (let found = before; found < sentences.length; found++)
9316
+ sentences[found] = { ...sentences[found], check: true };
9317
+ continue;
9318
+ }
9319
+ if (member !== void 0 && at2(member)?.kind === "ident" && at2(member).value === "holds") {
9320
+ unchecked(
9321
+ token,
9322
+ "This ai.holds call is written indirectly, so its claim is not checked before a run."
9323
+ );
9324
+ continue;
9325
+ }
8673
9326
  if (isPunct(index + 1, ".") && at2(index + 2)?.kind === "ident" && at2(index + 2).value === "group" && isPunct(index + 3, "(")) {
8674
9327
  const afterName = skipExpression(index + 4);
8675
9328
  if (!isPunct(afterName, ",")) continue;
@@ -8880,7 +9533,8 @@ async function validateScriptFile(file, options, classify) {
8880
9533
  fix: "Keep shared steps in fewer modules."
8881
9534
  });
8882
9535
  diagnostics.push(...warnings);
8883
- const sentences = scans.flatMap((scan) => scan.sentences).map((item) => ({
9536
+ const scanned = scans.flatMap((scan) => scan.sentences);
9537
+ const sentences = scanned.map((item) => ({
8884
9538
  kind: "sentence",
8885
9539
  phase: "steps",
8886
9540
  text: item.text,
@@ -8889,7 +9543,21 @@ async function validateScriptFile(file, options, classify) {
8889
9543
  }));
8890
9544
  const checked = await classifySentenceSteps(sentences, classify);
8891
9545
  diagnostics.push(...checked.diagnostics);
8892
- const complete = checked.classification.steps.every((step) => step !== null) && checked.diagnostics.length === 0 && warnings.length === 0;
9546
+ const invalidChecks = [];
9547
+ scanned.forEach((item, index) => {
9548
+ const classified = checked.classification.steps[index];
9549
+ if (!item.check || !classified || classified.op === "verify" && !WAIT_UNTIL.test(item.text))
9550
+ return;
9551
+ invalidChecks.push({
9552
+ severity: "error",
9553
+ code: "invalid_check",
9554
+ source: item.source,
9555
+ message: "ai.holds takes one claim about the page.",
9556
+ fix: 'Write ai.holds("the passkey screen is shown").'
9557
+ });
9558
+ });
9559
+ diagnostics.push(...invalidChecks);
9560
+ const complete = checked.classification.steps.every((step) => step !== null) && checked.diagnostics.length === 0 && invalidChecks.length === 0 && warnings.length === 0;
8893
9561
  return {
8894
9562
  headers,
8895
9563
  diagnostics,
@@ -9573,12 +10241,14 @@ async function runScriptTest(file, identity, runDependencies) {
9573
10241
  } catch (error2) {
9574
10242
  return stop(runtimeFailure(absolute, error2));
9575
10243
  }
9576
- if (outcome === "continue") return;
10244
+ if (outcome === "continue") return true;
10245
+ if (outcome === "failed" && presentation.check) return false;
9577
10246
  if (outcome === "failed")
9578
10247
  stop({ status: "failed", file: absolute, source: step.source });
9579
10248
  else if (outcome.status !== "passed") stop(outcome);
10249
+ return true;
9580
10250
  };
9581
- const sentence = async (text, values, source2) => {
10251
+ const sentence = async (text, values, source2, check = false) => {
9582
10252
  try {
9583
10253
  if (typeof text !== "string" || !text.trim())
9584
10254
  throw new ScriptUsageError(
@@ -9615,6 +10285,12 @@ async function runScriptTest(file, identity, runDependencies) {
9615
10285
  )
9616
10286
  );
9617
10287
  const classified = checked.classification.steps[0];
10288
+ if (check && classified && (classified.op !== "verify" || WAIT_UNTIL.test(text)))
10289
+ throw new ScriptUsageError(
10290
+ "invalid_check",
10291
+ "ai.holds takes one claim about the page.",
10292
+ 'Write ai.holds("the passkey screen is shown").'
10293
+ );
9618
10294
  if (checked.diagnostics.length || !classified) {
9619
10295
  const diagnostic3 = checked.diagnostics[0];
9620
10296
  stop({
@@ -9640,7 +10316,7 @@ async function runScriptTest(file, identity, runDependencies) {
9640
10316
  inlineValues(template, classified.op, own),
9641
10317
  source2
9642
10318
  );
9643
- await runStep(
10319
+ const held = await runStep(
9644
10320
  {
9645
10321
  ...shown,
9646
10322
  op: classified.op,
@@ -9648,10 +10324,11 @@ async function runScriptTest(file, identity, runDependencies) {
9648
10324
  probability: classified.probability
9649
10325
  },
9650
10326
  scope,
9651
- { group: [...groups] }
10327
+ { group: [...groups], ...check ? { check: true } : {} }
9652
10328
  );
9653
10329
  for (const [key, entry] of Object.entries(scope))
9654
10330
  if (!(key in own) && !(key in bindings)) bindings[key] = entry;
10331
+ return held;
9655
10332
  } catch (error2) {
9656
10333
  if (error2 instanceof ScriptUsageError) usage(error2, source2);
9657
10334
  throw error2;
@@ -9672,6 +10349,11 @@ async function runScriptTest(file, identity, runDependencies) {
9672
10349
  await exclusive(source2, () => sentence(item, values, source2));
9673
10350
  } else await exclusive(source2, () => sentence(input, values, source2));
9674
10351
  };
10352
+ const holds = (claim2, values, source2) => (
10353
+ // Classify the caller's words before treating them as a check. Prefixing
10354
+ // `verify` would turn an action into a claim and make it look read-only.
10355
+ exclusive(source2, () => sentence(claim2, values, source2, true))
10356
+ );
9675
10357
  const track = (work) => {
9676
10358
  const step = new StepPromise(
9677
10359
  (resolve, reject) => work.then(resolve, reject)
@@ -9773,6 +10455,7 @@ async function runScriptTest(file, identity, runDependencies) {
9773
10455
  });
9774
10456
  return parser ? parser.parse(text) : text;
9775
10457
  };
10458
+ ai.holds = ((claim2, values) => track(holds(claim2, values, where(new Error().stack))));
9776
10459
  ai.extract = ((description, parser) => track(
9777
10460
  extract(description, parser, where(new Error().stack))
9778
10461
  ));
@@ -9991,6 +10674,7 @@ export {
9991
10674
  TestRecording,
9992
10675
  VISION_PROMPT,
9993
10676
  VisionRequestError,
10677
+ WAIT_UNTIL,
9994
10678
  attributeRejection,
9995
10679
  callExtent,
9996
10680
  canonicalSentence,
@@ -10006,6 +10690,7 @@ export {
10006
10690
  codePoints,
10007
10691
  collectCandidates,
10008
10692
  compareDiagnostics3 as compareDiagnostics,
10693
+ controlState,
10009
10694
  dedupeDiagnostics,
10010
10695
  describeRejection,
10011
10696
  discoverFlowFiles,
@@ -10098,6 +10783,7 @@ export {
10098
10783
  validateTypeOperand,
10099
10784
  valueEntries,
10100
10785
  verify,
10786
+ visibleText,
10101
10787
  visualCandidates,
10102
10788
  walkSuiteFiles
10103
10789
  };