@sedum-dev/core 0.1.0-alpha.6 → 0.1.0-alpha.9

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
@@ -55,6 +55,7 @@ var ResultFrameSchema = z.discriminatedUnion("status", [
55
55
  })
56
56
  ]);
57
57
  var ResultCallSchema = z.strictObject({
58
+ provider: z.string().trim().min(1).max(120).optional(),
58
59
  modality: z.literal("vision").optional(),
59
60
  purpose: z.enum(["classification", "locator", "judge", "planner"]),
60
61
  requestedModel: z.string().max(120),
@@ -137,6 +138,15 @@ var ResultStepSchema = z.strictObject({
137
138
  detail: z.string().max(512),
138
139
  /** Enclosing `ai.group` names, outermost first; absent outside a group. */
139
140
  group: z.array(z.string().max(120)).max(16).optional(),
141
+ /** TypeScript goal execution is planner-reported, not independently verified. */
142
+ goal: z.strictObject({
143
+ completion: z.literal("planner"),
144
+ text: z.string(),
145
+ actions: count,
146
+ requests: count,
147
+ reason: z.string(),
148
+ dataSeed: z.number().int().optional()
149
+ }).optional(),
140
150
  sourceStack: z.array(ResultSourceSchema).min(1),
141
151
  state,
142
152
  verdict: verdict.nullable(),
@@ -1093,6 +1103,7 @@ async function call(page, method, argument) {
1093
1103
  const bridge = window.__sedum;
1094
1104
  if (!bridge) return { installed: false };
1095
1105
  if (bridge.protocol !== ${PAGE_PROTOCOL}) return { installed: true, protocol: bridge.protocol };
1106
+ if (typeof bridge[${JSON.stringify(method)}] !== "function") return { installed: true, protocol: bridge.protocol, missingMethod: true };
1096
1107
  return Promise.resolve(bridge[${JSON.stringify(method)}](argument)).then(value => ({ installed: true, protocol: bridge.protocol, value: value ?? null }));
1097
1108
  })(${JSON.stringify(argument ?? null)})`);
1098
1109
  if (!result || !result.installed)
@@ -1100,7 +1111,7 @@ async function call(page, method, argument) {
1100
1111
  "missing",
1101
1112
  "Sedum page script was not installed in this document."
1102
1113
  );
1103
- if (result.protocol !== PAGE_PROTOCOL)
1114
+ if (result.protocol !== PAGE_PROTOCOL || result.missingMethod)
1104
1115
  throw new PageScriptError(
1105
1116
  "incompatible",
1106
1117
  `Sedum page script protocol ${result.protocol} is incompatible with ${PAGE_PROTOCOL}.`
@@ -1179,6 +1190,16 @@ async function matchLiveEntry(page, entry, key, operation, sentence, runtimeDepe
1179
1190
  runtimeDependent
1180
1191
  );
1181
1192
  }
1193
+ async function controlState(page, target) {
1194
+ const result = await call(page, "controlState", target);
1195
+ 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)))
1196
+ throw new PageScriptError("invalid-result", "Invalid control state.");
1197
+ return result;
1198
+ }
1199
+ async function visibleText(page) {
1200
+ const result = await call(page, "visibleText");
1201
+ return result && result.complete && typeof result.text === "string" ? result.text : null;
1202
+ }
1182
1203
 
1183
1204
  // src/report-privacy.ts
1184
1205
  function safeText(value, privacy, limit) {
@@ -1482,6 +1503,28 @@ var PlaywrightPage = class {
1482
1503
  throw operationError(error2, this.state(), "page");
1483
1504
  }
1484
1505
  }
1506
+ async history(move, options = {}) {
1507
+ const currentState = this.state();
1508
+ if (currentState.closed || currentState.crashed || currentState.disconnected) {
1509
+ throw operationError(
1510
+ new Error("page is not available"),
1511
+ currentState,
1512
+ "page"
1513
+ );
1514
+ }
1515
+ const navigation = {
1516
+ timeout: options.timeoutMs ?? DEFAULT_NAVIGATION_TIMEOUT_MS,
1517
+ waitUntil: options.waitUntil ?? "domcontentloaded"
1518
+ };
1519
+ try {
1520
+ if (move === "back") await this.page.goBack(navigation);
1521
+ else if (move === "forward") await this.page.goForward(navigation);
1522
+ else await this.page.reload(navigation);
1523
+ return { url: this.page.url() };
1524
+ } catch (error2) {
1525
+ throw safeOperationError(error2, this.state(), "History navigation");
1526
+ }
1527
+ }
1485
1528
  async settle(options = {}) {
1486
1529
  const currentState = this.state();
1487
1530
  if (currentState.closed || currentState.crashed || currentState.disconnected) {
@@ -1568,6 +1611,7 @@ var PlaywrightPage = class {
1568
1611
  aim
1569
1612
  ).catch(() => ({ actionable: false, reason: "stale" }));
1570
1613
  if (!checked.actionable) return checked;
1614
+ let dispatchAim = checked.aim;
1571
1615
  const handle = await this.page.evaluateHandle((ref) => {
1572
1616
  const matches = [];
1573
1617
  const roots = [document];
@@ -1596,21 +1640,51 @@ var PlaywrightPage = class {
1596
1640
  },
1597
1641
  { expected: aim, element }
1598
1642
  );
1643
+ if (aim.hover) {
1644
+ const hoverHandle = await this.page.evaluateHandle(
1645
+ (expected) => window.__sedum?.hoverElement(expected) ?? null,
1646
+ aim
1647
+ ).catch(() => null);
1648
+ const hoverElement = hoverHandle?.asElement();
1649
+ if (!hoverElement) {
1650
+ await hoverHandle?.dispose().catch(() => void 0);
1651
+ return { actionable: false, reason: "not_actionable" };
1652
+ }
1653
+ try {
1654
+ await hoverElement.hover({ timeout: remaining() });
1655
+ await element.waitForElementState("visible", {
1656
+ timeout: Math.min(2e3, remaining())
1657
+ });
1658
+ } catch (error2) {
1659
+ return {
1660
+ actionable: false,
1661
+ reason: "action_started",
1662
+ retryable: false,
1663
+ callLog: safeCallLog(error2)
1664
+ };
1665
+ } finally {
1666
+ await hoverHandle.dispose().catch(() => void 0);
1667
+ }
1668
+ }
1599
1669
  const still = await validateElement().catch(() => ({
1600
1670
  actionable: false,
1601
1671
  reason: "stale"
1602
1672
  }));
1603
- if (!still.actionable) return still;
1673
+ if (!still.actionable)
1674
+ return aim.hover ? { actionable: false, reason: "action_started", retryable: false } : still;
1675
+ dispatchAim = still.aim;
1604
1676
  try {
1605
1677
  await element.waitForElementState("stable", { timeout: remaining() });
1606
1678
  } catch {
1607
- return { actionable: false, reason: "not_actionable" };
1679
+ return aim.hover ? { actionable: false, reason: "action_started", retryable: false } : { actionable: false, reason: "not_actionable" };
1608
1680
  }
1609
1681
  const ready = await validateElement().catch(() => ({
1610
1682
  actionable: false,
1611
1683
  reason: "stale"
1612
1684
  }));
1613
- if (!ready.actionable) return ready;
1685
+ if (!ready.actionable)
1686
+ return aim.hover ? { actionable: false, reason: "action_started", retryable: false } : ready;
1687
+ dispatchAim = ready.aim;
1614
1688
  if (options.chooseOption) {
1615
1689
  const native = await element.evaluate(
1616
1690
  (node) => node instanceof HTMLSelectElement && !node.multiple ? Array.from(node.options).map((option) => ({
@@ -1623,14 +1697,31 @@ var PlaywrightPage = class {
1623
1697
  native.map((option) => option.label)
1624
1698
  );
1625
1699
  const index = native.findIndex((option) => option.label === label);
1626
- if (label === null || index < 0)
1700
+ if (label === null || index < 0) {
1701
+ if (aim.hover)
1702
+ return {
1703
+ actionable: false,
1704
+ reason: "action_started",
1705
+ retryable: false
1706
+ };
1627
1707
  return {
1628
1708
  actionable: false,
1629
1709
  reason: "option_not_named",
1630
1710
  options: native.filter((option) => !option.disabled).map((option) => option.label)
1631
1711
  };
1632
- if (native[index].disabled)
1633
- return { actionable: false, reason: "not_actionable" };
1712
+ }
1713
+ if (native[index].disabled) {
1714
+ if (aim.hover)
1715
+ return {
1716
+ actionable: false,
1717
+ reason: "action_started",
1718
+ retryable: false
1719
+ };
1720
+ return {
1721
+ actionable: false,
1722
+ reason: "not_actionable"
1723
+ };
1724
+ }
1634
1725
  const hide2 = await this.highlight(element);
1635
1726
  try {
1636
1727
  await element.selectOption({ index }, { timeout: remaining() });
@@ -1649,8 +1740,11 @@ var PlaywrightPage = class {
1649
1740
  }
1650
1741
  const hide = await this.highlight(element);
1651
1742
  try {
1652
- await element.click({ position: aim.point, timeout: remaining() });
1653
- return { actionable: true, aim };
1743
+ await element.click({
1744
+ position: dispatchAim.point,
1745
+ timeout: remaining()
1746
+ });
1747
+ return { actionable: true, aim: dispatchAim };
1654
1748
  } catch (error2) {
1655
1749
  return {
1656
1750
  actionable: false,
@@ -2223,6 +2317,16 @@ ${(result.callLog ?? []).join("\n")}`)
2223
2317
  );
2224
2318
  break;
2225
2319
  }
2320
+ case "history": {
2321
+ const before = await active(pageVersion(page));
2322
+ const timeoutMs = remaining(3e4, phase);
2323
+ phase = "post_dispatch";
2324
+ await active(page.history(command.move, { timeoutMs }));
2325
+ outcome = await active(
2326
+ observeRoute(page, "history", before, remaining)
2327
+ );
2328
+ break;
2329
+ }
2226
2330
  case "press": {
2227
2331
  if (!command.key.trim())
2228
2332
  throw new StepExecutionError(op, "invalid_input", phase);
@@ -2322,6 +2426,157 @@ function unknownCostCall(error2) {
2322
2426
  };
2323
2427
  }
2324
2428
 
2429
+ // src/provider-gate.ts
2430
+ import PQueue from "p-queue";
2431
+ var MAX_COOLDOWN_MS = 6e4;
2432
+ var RATE_LIMIT_BUDGET_MS = 3e5;
2433
+ var BACKOFF_JITTER = 0.25;
2434
+ var DEFAULT_PROVIDER_CONCURRENCY = 4;
2435
+ var MAX_PROVIDER_CONCURRENCY = 32;
2436
+ function parseRetryAfter(headers, now) {
2437
+ const ms = headers?.get("retry-after-ms")?.trim();
2438
+ if (ms && /^\d+(?:\.\d+)?$/u.test(ms)) return Math.ceil(Number(ms));
2439
+ const value = headers?.get("retry-after")?.trim();
2440
+ if (!value) return null;
2441
+ if (/^\d+(?:\.\d+)?$/u.test(value)) return Math.ceil(Number(value) * 1e3);
2442
+ if (!/[a-z]/iu.test(value)) return null;
2443
+ const date = Date.parse(value);
2444
+ if (Number.isNaN(date)) return null;
2445
+ return Math.max(0, date - now);
2446
+ }
2447
+ function backoffDelay(failures, initialMs, random) {
2448
+ const base2 = Math.min(
2449
+ MAX_COOLDOWN_MS,
2450
+ initialMs * 2 ** Math.max(0, failures - 1)
2451
+ );
2452
+ return Math.max(1, Math.round(base2 * (1 - BACKOFF_JITTER * random)));
2453
+ }
2454
+ function cooldownDelay(retryAfterMs, rateLimitCount, initialMs, random) {
2455
+ const requested = retryAfterMs ?? backoffDelay(rateLimitCount, initialMs, random);
2456
+ const jittered = retryAfterMs === null ? requested : requested + Math.round(requested * BACKOFF_JITTER * random);
2457
+ return Math.min(MAX_COOLDOWN_MS, Math.max(1, jittered));
2458
+ }
2459
+ function nextConcurrency(current, cap, event) {
2460
+ return event === "rate-limited" ? 1 : Math.min(cap, current + 1);
2461
+ }
2462
+ var GateWaitExceeded = class extends Error {
2463
+ constructor() {
2464
+ super("Provider gate wait exceeded its budget");
2465
+ this.name = "GateWaitExceeded";
2466
+ }
2467
+ };
2468
+ var GateAborted = class extends Error {
2469
+ constructor() {
2470
+ super("Provider gate wait was canceled");
2471
+ this.name = "GateAborted";
2472
+ }
2473
+ };
2474
+ var ProviderGate = class {
2475
+ cap;
2476
+ queue;
2477
+ now;
2478
+ cooldownUntil = 0;
2479
+ timer;
2480
+ constructor(options = {}) {
2481
+ const cap = options.concurrency ?? DEFAULT_PROVIDER_CONCURRENCY;
2482
+ if (!Number.isSafeInteger(cap) || cap < 1 || cap > MAX_PROVIDER_CONCURRENCY)
2483
+ throw new RangeError(
2484
+ `Provider concurrency must be an integer from 1 to ${MAX_PROVIDER_CONCURRENCY}.`
2485
+ );
2486
+ this.cap = cap;
2487
+ this.now = options.now ?? Date.now;
2488
+ this.queue = new PQueue({ concurrency: cap });
2489
+ }
2490
+ /** Current admission limit; below the cap while ramping after a cooldown. */
2491
+ get concurrency() {
2492
+ return this.queue.concurrency;
2493
+ }
2494
+ get coolingDown() {
2495
+ return this.queue.isPaused;
2496
+ }
2497
+ get inFlight() {
2498
+ return this.queue.pending;
2499
+ }
2500
+ /**
2501
+ * Run `task` once a slot is free and no cooldown is active. Waiting ends
2502
+ * with `GateAborted` when `signal` aborts, or `GateWaitExceeded` after
2503
+ * `maxWaitMs`; neither consumes a slot.
2504
+ */
2505
+ async run(task, options = {}) {
2506
+ const started = this.now();
2507
+ const controller = new AbortController();
2508
+ let reason = null;
2509
+ const onAbort = () => {
2510
+ reason ??= "abort";
2511
+ controller.abort();
2512
+ };
2513
+ if (options.signal?.aborted) onAbort();
2514
+ options.signal?.addEventListener("abort", onAbort, { once: true });
2515
+ const budget = options.maxWaitMs === void 0 || !Number.isFinite(options.maxWaitMs) ? void 0 : setTimeout(
2516
+ () => {
2517
+ reason ??= "budget";
2518
+ controller.abort();
2519
+ },
2520
+ Math.max(0, options.maxWaitMs)
2521
+ );
2522
+ let admittedAt = null;
2523
+ try {
2524
+ const value = await this.queue.add(
2525
+ async () => {
2526
+ admittedAt = this.now();
2527
+ if (budget) clearTimeout(budget);
2528
+ return task();
2529
+ },
2530
+ { signal: controller.signal }
2531
+ );
2532
+ return { value, waitedMs: (admittedAt ?? this.now()) - started };
2533
+ } catch (error2) {
2534
+ if (admittedAt === null && reason === "budget")
2535
+ throw new GateWaitExceeded();
2536
+ if (admittedAt === null && reason === "abort") throw new GateAborted();
2537
+ throw error2;
2538
+ } finally {
2539
+ if (budget) clearTimeout(budget);
2540
+ options.signal?.removeEventListener("abort", onAbort);
2541
+ }
2542
+ }
2543
+ /** Pause admission for every lane until at least `until`; later requests extend it. */
2544
+ cooldown(until) {
2545
+ this.queue.concurrency = nextConcurrency(
2546
+ this.queue.concurrency,
2547
+ this.cap,
2548
+ "rate-limited"
2549
+ );
2550
+ if (until <= this.cooldownUntil && this.timer) return;
2551
+ this.cooldownUntil = Math.max(this.cooldownUntil, until);
2552
+ this.queue.pause();
2553
+ if (this.timer) clearTimeout(this.timer);
2554
+ this.timer = setTimeout(
2555
+ () => {
2556
+ this.timer = void 0;
2557
+ this.queue.start();
2558
+ },
2559
+ Math.max(0, this.cooldownUntil - this.now())
2560
+ );
2561
+ }
2562
+ /**
2563
+ * Release the pending cooldown timer when the run ends, so an interrupted
2564
+ * or timed-out run does not keep the process alive until the window closes.
2565
+ */
2566
+ close() {
2567
+ if (this.timer) clearTimeout(this.timer);
2568
+ this.timer = void 0;
2569
+ }
2570
+ /** One successful response widens admission by one, up to the cap. */
2571
+ succeeded() {
2572
+ this.queue.concurrency = nextConcurrency(
2573
+ this.queue.concurrency,
2574
+ this.cap,
2575
+ "success"
2576
+ );
2577
+ }
2578
+ };
2579
+
2325
2580
  // src/vision.ts
2326
2581
  import { z as z2 } from "zod";
2327
2582
  var DEFAULT_VISION_MODEL = "google/gemini-3.8-flash";
@@ -4454,11 +4709,11 @@ function parseSteps(phase, raw, file, counter, nodes, knownData, diagnostics) {
4454
4709
  "A use step must reference a .module.yaml file.",
4455
4710
  "Write `use: path/to/login.module.yaml`."
4456
4711
  );
4457
- const withValues = mapping.with ?? {};
4712
+ const withValues2 = mapping.with ?? {};
4458
4713
  const withSources = /* @__PURE__ */ Object.create(
4459
4714
  null
4460
4715
  );
4461
- for (const [key, value] of Object.entries(withValues)) {
4716
+ for (const [key, value] of Object.entries(withValues2)) {
4462
4717
  withSources[key] = at(file, counter, nodes, [
4463
4718
  phase,
4464
4719
  index,
@@ -4484,7 +4739,7 @@ function parseSteps(phase, raw, file, counter, nodes, knownData, diagnostics) {
4484
4739
  kind: "module",
4485
4740
  phase,
4486
4741
  use: mapping.use,
4487
- with: withValues,
4742
+ with: withValues2,
4488
4743
  withSources,
4489
4744
  source,
4490
4745
  sourceStack: [source]
@@ -5261,6 +5516,8 @@ var VALUE_OPERAND = new RegExp(
5261
5516
  var BINDING = new RegExp(`\\bas\\s+${PLACEHOLDER}\\s*\\.?$`, "iu");
5262
5517
  var HTTP_URL = /https?:\/\/\S+/giu;
5263
5518
  var WAIT_DURATION = /^wait\s+(?:for\s+)?(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|seconds?)\s*\.?$/iu;
5519
+ 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;
5520
+ var HISTORY_MOVE = /^(?:(?:go|navigate)\s+(?:back(?:\s+to\s+the\s+previous\s+page)?|forward)|(?:reload|refresh)(?:\s+the\s+page)?)\s*\.?$/iu;
5264
5521
  var DURATION_OPERAND = /\b(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|seconds?)\b/giu;
5265
5522
  var KNOWN_KEY = /\b(?:Enter|Tab|Escape|Esc|Space|Backspace|Delete|Arrow(?:Up|Down|Left|Right)|F(?:[1-9]|1[0-2]))\b/giu;
5266
5523
  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;
@@ -5277,9 +5534,38 @@ var GERUND_SECOND_ACTION = /^(?:clicking|typing|entering|filling|pressing|scroll
5277
5534
  var PASSIVE_INTERACTION = /\b(?:is|are|was|were|has|have|had)(?:\s+been)?\s+(?:clicked|typed|entered|filled|pressed|scrolled|selected|submitted|opened|uploaded|downloaded)\b/iu;
5278
5535
  var ACTION_VERBS = "click|type|enter|fill|press|goto|go\\s+to|navigate|verify|assert|measure|note|observe|scroll|wait|remember|capture|record|select|tap|activate|close|drag|drop|upload|download|hover|swipe|double[ -]?click|right[ -]?click";
5279
5536
  var DIRECT_SECOND_ACTION = new RegExp(`^(?:${ACTION_VERBS})\\b`, "iu");
5537
+ var CLAIM_PREDICATE = /\b(is|are|was|were|contains|includes|shows|displays|reads|says|matches|appears|exists|remains|looks)\b/iu;
5538
+ var CLAIM_SUBJECT_WORD = /^(?:the|a|an|this|that|these|those|there|it|I|we|you|they)\b/iu;
5539
+ var BOUND_CLAIM_SUBJECT = /^(?:["']|\{\{)/u;
5540
+ var CLAIM_STATE = /^(?:not\s+)?(?:(?:being\s+)?shown|visible|hidden|ready|complete|completed|open|closed|enabled|disabled|selected|checked|empty|available|present|absent|active|inactive|valid|invalid|successful|failed|loading|displayed|focused|required|expanded|collapsed|on|off|correct|incorrect)$/iu;
5541
+ var CLAIM_VALUE = /^(?:""|''|\{\{\s*[A-Za-z_]\w*\s*\}\}|true|false|[£$€¥]?\s*[+-]?\d+(?:[.,]\d+)?%?)$/iu;
5280
5542
  function canonicalSentence(sentence) {
5281
5543
  return sentence.normalize("NFC").replace(/\s+/gu, " ").trim();
5282
5544
  }
5545
+ function isClaimSentence(sentence) {
5546
+ const text = canonicalSentence(sentence);
5547
+ if (!CLAIM_SUBJECT_WORD.test(text) && !BOUND_CLAIM_SUBJECT.test(text))
5548
+ return false;
5549
+ const structural = withoutQuotes(text).replace(/\.$/u, "");
5550
+ const predicate = CLAIM_PREDICATE.exec(structural);
5551
+ if (!predicate || predicate.index === 0) return false;
5552
+ const tail = structural.slice(predicate.index + predicate[0].length).trim();
5553
+ switch (predicate[1].toLowerCase()) {
5554
+ case "appears":
5555
+ case "exists":
5556
+ return tail === "";
5557
+ case "contains":
5558
+ case "includes":
5559
+ case "shows":
5560
+ case "displays":
5561
+ case "reads":
5562
+ case "says":
5563
+ case "matches":
5564
+ return CLAIM_VALUE.test(tail);
5565
+ default:
5566
+ return CLAIM_STATE.test(tail) || CLAIM_VALUE.test(tail);
5567
+ }
5568
+ }
5283
5569
  function withoutQuotes(sentence) {
5284
5570
  return sentence.replace(/"[^"]*"|'[^']*'/gu, '""');
5285
5571
  }
@@ -5309,6 +5595,9 @@ function preflightSentence(sentence) {
5309
5595
  function patternOperation(sentence) {
5310
5596
  const text = canonicalSentence(sentence);
5311
5597
  if (preflightSentence(text)) return null;
5598
+ if (WAIT_UNTIL.test(text)) return "verify";
5599
+ if (HISTORY_MOVE.test(text) || /^(?:goto|go\s+to|navigate\s+to)\s+\/\S*\s*$/iu.test(text))
5600
+ return "goto";
5312
5601
  if (/^(?:click|type|enter|fill|press|goto|go\s+to|navigate\s+to|scroll|wait|remember|select|choose|pick)\b/iu.test(
5313
5602
  text
5314
5603
  ) && (withoutQuotes(text).match(SECOND_ACTION_CONNECTOR) !== null || /;|,\s*[A-Za-z]/u.test(withoutQuotes(text))))
@@ -5350,8 +5639,11 @@ function validateOperand(sentence, op) {
5350
5639
  if (!operand || quotes.length + placeholders.length !== 1)
5351
5640
  return 'Name one value, such as {{key}} or "{{user}}@example.com", and a field.';
5352
5641
  } else if (op === "goto") {
5642
+ if (HISTORY_MOVE.test(text) || /^(?:goto|go\s+to|navigate\s+to)\s+\/\S*\s*$/iu.test(text))
5643
+ return null;
5353
5644
  const urls = text.match(HTTP_URL) ?? [];
5354
- if (urls.length !== 1) return "Name exactly one http(s) address.";
5645
+ if (urls.length !== 1)
5646
+ return "Name exactly one http(s) address or a /path on this site.";
5355
5647
  } else if (op === "press") {
5356
5648
  const explicit = /^(?:press|hit|strike)\s+(?:the\s+)?(?:"[^"]+"|[\w-]+)(?:\s+key)?\s*\.?$/iu.test(
5357
5649
  text
@@ -5453,7 +5745,7 @@ async function classifySteps(input, options) {
5453
5745
  }
5454
5746
  const leading = canonicalSentence(step.sentence).match(/^(type|enter|fill|press|remember|goto|wait|scroll)\b/iu)?.[1]?.toLowerCase();
5455
5747
  const lexicalOp = leading === "type" || leading === "enter" || leading === "fill" ? "type" : leading === "press" || leading === "remember" || leading === "goto" || leading === "wait" || leading === "scroll" ? leading : null;
5456
- if (lexicalOp) {
5748
+ if (lexicalOp && !(lexicalOp === "wait" && WAIT_UNTIL.test(step.sentence))) {
5457
5749
  const operandError = validateOperand(step.sentence, lexicalOp);
5458
5750
  if (operandError) {
5459
5751
  fail(index, "invalid_operand", operandError);
@@ -5594,6 +5886,9 @@ var KEY_DOMAIN = "sedum-classification-v1\0";
5594
5886
  function classificationKey(sentence) {
5595
5887
  return createHash("sha256").update(KEY_DOMAIN).update(canonicalSentence(sentence)).digest("hex");
5596
5888
  }
5889
+ function providerClassificationKey(provider, sentence) {
5890
+ return provider === "typesafe" ? classificationKey(sentence) : createHash("sha256").update(KEY_DOMAIN).update(provider).update("\0").update(canonicalSentence(sentence)).digest("hex");
5891
+ }
5597
5892
  function validEntry2(value) {
5598
5893
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
5599
5894
  const entry = value;
@@ -5608,26 +5903,31 @@ function validEntry2(value) {
5608
5903
  return decision.accepted;
5609
5904
  }
5610
5905
  var FileClassificationCache = class _FileClassificationCache {
5611
- constructor(path11, requestedModel, entries, loadReason, invalidKeys) {
5906
+ constructor(path11, requestedModel, provider, entries, loadReason, invalidKeys) {
5612
5907
  this.path = path11;
5613
5908
  this.requestedModel = requestedModel;
5909
+ this.provider = provider;
5614
5910
  this.loadReason = loadReason;
5615
5911
  this.invalidKeys = invalidKeys;
5616
5912
  this.entries = entries;
5617
5913
  }
5618
5914
  path;
5619
5915
  requestedModel;
5916
+ provider;
5620
5917
  loadReason;
5621
5918
  invalidKeys;
5622
5919
  entries;
5623
5920
  dirty = false;
5624
- static async load(path11, requestedModel) {
5921
+ static async load(path11, requestedModel, provider = "typesafe") {
5922
+ if (!provider.trim())
5923
+ throw new TypeError("Cache provider must be nonempty");
5625
5924
  try {
5626
5925
  const value = JSON.parse(await fs.readFile(path11, "utf8"));
5627
5926
  if (!value || typeof value !== "object" || Array.isArray(value))
5628
5927
  return new _FileClassificationCache(
5629
5928
  path11,
5630
5929
  requestedModel,
5930
+ provider,
5631
5931
  {},
5632
5932
  "corrupt",
5633
5933
  {}
@@ -5637,6 +5937,7 @@ var FileClassificationCache = class _FileClassificationCache {
5637
5937
  return new _FileClassificationCache(
5638
5938
  path11,
5639
5939
  requestedModel,
5940
+ provider,
5640
5941
  {},
5641
5942
  "format_mismatch",
5642
5943
  {}
@@ -5645,6 +5946,7 @@ var FileClassificationCache = class _FileClassificationCache {
5645
5946
  return new _FileClassificationCache(
5646
5947
  path11,
5647
5948
  requestedModel,
5949
+ provider,
5648
5950
  {},
5649
5951
  "corrupt",
5650
5952
  {}
@@ -5659,6 +5961,7 @@ var FileClassificationCache = class _FileClassificationCache {
5659
5961
  return new _FileClassificationCache(
5660
5962
  path11,
5661
5963
  requestedModel,
5964
+ provider,
5662
5965
  entries,
5663
5966
  "ok",
5664
5967
  invalidKeys
@@ -5668,6 +5971,7 @@ var FileClassificationCache = class _FileClassificationCache {
5668
5971
  return new _FileClassificationCache(
5669
5972
  path11,
5670
5973
  requestedModel,
5974
+ provider,
5671
5975
  {},
5672
5976
  "absent",
5673
5977
  {}
@@ -5675,6 +5979,7 @@ var FileClassificationCache = class _FileClassificationCache {
5675
5979
  return new _FileClassificationCache(
5676
5980
  path11,
5677
5981
  requestedModel,
5982
+ provider,
5678
5983
  {},
5679
5984
  "corrupt",
5680
5985
  {}
@@ -5682,14 +5987,17 @@ var FileClassificationCache = class _FileClassificationCache {
5682
5987
  }
5683
5988
  }
5684
5989
  get(sentence) {
5685
- const entry = this.entries[classificationKey(sentence)];
5990
+ const key = providerClassificationKey(this.provider, sentence);
5991
+ const entry = this.entries[key];
5686
5992
  if (!entry)
5687
5993
  return {
5688
5994
  answer: null,
5689
- reason: this.invalidKeys[classificationKey(sentence)] ?? (this.loadReason === "ok" ? "absent" : this.loadReason)
5995
+ reason: this.invalidKeys[key] ?? (this.loadReason === "ok" ? "absent" : this.loadReason)
5690
5996
  };
5691
5997
  if (entry.requestedModel !== this.requestedModel)
5692
5998
  return { answer: null, reason: "model_mismatch" };
5999
+ if ((entry.provider ?? "typesafe") !== this.provider)
6000
+ return { answer: null, reason: "provider_mismatch" };
5693
6001
  const decision = evaluateModelAnswer(entry);
5694
6002
  if (!decision.accepted)
5695
6003
  return { answer: null, reason: "acceptance_policy" };
@@ -5701,11 +6009,12 @@ var FileClassificationCache = class _FileClassificationCache {
5701
6009
  const probabilities = Object.fromEntries(
5702
6010
  MODEL_CHOICES.map((key) => [key, answer.probabilities[key]])
5703
6011
  );
5704
- this.entries[classificationKey(sentence)] = {
6012
+ this.entries[providerClassificationKey(this.provider, sentence)] = {
5705
6013
  op: answer.op,
5706
6014
  probabilities,
5707
6015
  model: answer.model,
5708
6016
  requestedModel: answer.requestedModel,
6017
+ provider: this.provider,
5709
6018
  source: "model",
5710
6019
  promptVersion: CLASSIFICATION_PROMPT_VERSION,
5711
6020
  operationSetVersion: OPERATION_SET_VERSION,
@@ -5736,7 +6045,8 @@ var FileClassificationCache = class _FileClassificationCache {
5736
6045
  try {
5737
6046
  const latest = await _FileClassificationCache.load(
5738
6047
  this.path,
5739
- this.requestedModel
6048
+ this.requestedModel,
6049
+ this.provider
5740
6050
  );
5741
6051
  const merged = { ...latest.entries, ...this.entries };
5742
6052
  const sorted = Object.fromEntries(
@@ -6162,15 +6472,76 @@ async function measure(page, judge, claim2, options = {}) {
6162
6472
  }
6163
6473
 
6164
6474
  // src/goal-runner.ts
6475
+ import { randomInt } from "crypto";
6476
+
6477
+ // src/goal-data.ts
6478
+ import { Faker, en, base } from "@faker-js/faker";
6479
+ var methods = {
6480
+ person: "firstName lastName middleName fullName gender sex prefix suffix bio jobTitle jobDescriptor jobArea jobType zodiacSign",
6481
+ location: "zipCode city buildingNumber street streetAddress secondaryAddress county country continent countryCode state direction cardinalDirection ordinalDirection timeZone latitude longitude",
6482
+ internet: "exampleEmail username displayName protocol httpMethod httpStatusCode domainSuffix domainWord ipv4 ipv6 port userAgent mac password emoji jwtAlgorithm",
6483
+ company: "name catchPhrase buzzPhrase catchPhraseAdjective catchPhraseDescriptor catchPhraseNoun buzzAdjective buzzVerb buzzNoun",
6484
+ commerce: "department productName price productAdjective productMaterial product productDescription isbn upc",
6485
+ lorem: "word words sentence slug sentences paragraph paragraphs text lines",
6486
+ animal: "dog cat snake bear lion cetacean horse bird cow fish crocodilia insect rabbit rodent type petName",
6487
+ book: "author format genre publisher series title",
6488
+ food: "adjective description dish ethnicCategory fruit ingredient meat spice vegetable",
6489
+ music: "album artist genre songName",
6490
+ vehicle: "vehicle manufacturer model type fuel vin color vrm bicycle",
6491
+ finance: "accountName amount transactionType currencyCode currencyName currencySymbol currencyNumericCode transactionDescription",
6492
+ database: "column type collation engine mongodbObjectId",
6493
+ hacker: "abbreviation adjective noun verb ingverb phrase",
6494
+ git: "branch commitMessage commitSha",
6495
+ system: "fileName commonFileName mimeType commonFileType commonFileExt fileType fileExt directoryPath filePath semver networkInterface cron",
6496
+ string: "alpha alphanumeric numeric uuid nanoid",
6497
+ number: "int float binary octal hex romanNumeral",
6498
+ color: "human rgb",
6499
+ phone: "number imei",
6500
+ airline: "recordLocator seat aircraftType flightNumber",
6501
+ word: "adjective adverb conjunction interjection noun preposition verb sample words"
6502
+ };
6503
+ function goalGenerators(seed) {
6504
+ const faker = new Faker({ locale: [en, base] });
6505
+ faker.seed(seed);
6506
+ const functions = /* @__PURE__ */ new Map();
6507
+ const descriptions = {};
6508
+ for (const [module, names] of Object.entries(methods)) {
6509
+ const instance = faker[module];
6510
+ for (const name of names.split(" ")) {
6511
+ const id = `faker.${module}.${name}`;
6512
+ descriptions[id] = `Generate NEW synthetic ${module}: ${name.replace(/[A-Z]/g, (letter) => ` ${letter.toLowerCase()}`)}`;
6513
+ functions.set(id, () => instance[name]());
6514
+ }
6515
+ }
6516
+ descriptions["faker.internet.exampleEmail"] = "Generate NEW synthetic email on a reserved example domain; not an existing account or inbox";
6517
+ descriptions["faker.internet.password"] = "Generate NEW account password; NEVER an existing login credential or OTP";
6518
+ return {
6519
+ descriptions,
6520
+ generate(id) {
6521
+ const fn = functions.get(id);
6522
+ if (!fn) throw new Error("Unknown goal generator");
6523
+ const value = fn();
6524
+ if (!["string", "number", "boolean"].includes(typeof value))
6525
+ throw new Error("Generator did not return a scalar");
6526
+ const text = String(value);
6527
+ if (!text.trim() || text.length > 2e3)
6528
+ throw new Error("Generator returned an unsupported value");
6529
+ return text;
6530
+ }
6531
+ };
6532
+ }
6533
+
6534
+ // src/goal-runner.ts
6535
+ var GOAL_NO_MATCH = "__sedum_no_match";
6165
6536
  function goalOperations(state2) {
6166
6537
  return {
6167
6538
  ...Object.fromEntries(
6168
6539
  Object.keys(state2.targets).map((op) => [
6169
6540
  op,
6170
- op === "TYPE" ? "Fill one field with a supplied data binding" : "Click one observed element"
6541
+ op === "TYPE" ? state2.automaticData ? "Fill one field using supplied, remembered, or automatically generated synthetic data" : "Fill one field with a supplied data binding" : "Click one observed element"
6171
6542
  ])
6172
6543
  ),
6173
- DONE: "All goal requirements are visibly satisfied; request independent verification",
6544
+ DONE: state2.completion === "planner" ? "All goal requirements are visibly satisfied; finish the task" : "All goal requirements are visibly satisfied; request independent verification",
6174
6545
  BLOCKED: "No offered element or field can move the goal forward from this page; abstain"
6175
6546
  };
6176
6547
  }
@@ -6190,11 +6561,28 @@ function same(a, b) {
6190
6561
  return a.document === b.document && a.revision === b.revision && a.route === b.route;
6191
6562
  }
6192
6563
  async function runGoal(page, planner, judge, options) {
6564
+ return executeGoal(page, planner, options, {
6565
+ kind: "verified",
6566
+ judge,
6567
+ claims: options.verify
6568
+ });
6569
+ }
6570
+ function runGoalTask(page, planner, options) {
6571
+ return executeGoal(page, planner, options, { kind: "planner" });
6572
+ }
6573
+ async function executeGoal(page, planner, options, completion) {
6193
6574
  const started = performance.now();
6194
6575
  const maxRequests = options.maxRequests ?? 24;
6195
6576
  const maxActions = options.maxActions ?? 18;
6196
6577
  const timeoutMs = options.timeoutMs ?? 12e4;
6197
6578
  const operationMinMargin = options.operationMinMargin ?? 0.1;
6579
+ const dataSeed = options.dataSeed ?? randomInt(2147483647);
6580
+ if (!Number.isSafeInteger(dataSeed))
6581
+ throw new RangeError("Invalid data seed");
6582
+ const generators = planner.chooseGoalValue ? goalGenerators(dataSeed) : void 0;
6583
+ const data = { ...options.data };
6584
+ const generated = /* @__PURE__ */ new Map();
6585
+ let pendingValue;
6198
6586
  if (!Number.isFinite(operationMinMargin) || operationMinMargin < 0 || operationMinMargin > 1)
6199
6587
  throw new RangeError("Invalid goal operation margin");
6200
6588
  for (const [value, cap] of [
@@ -6204,7 +6592,7 @@ async function runGoal(page, planner, judge, options) {
6204
6592
  ])
6205
6593
  if (!Number.isSafeInteger(value) || value < 1 || value > cap)
6206
6594
  throw new RangeError("Invalid goal budget");
6207
- if (!options.goal.trim() || !options.verify.length || options.verify.some((s) => !s.trim()))
6595
+ if (!options.goal.trim() || completion.kind === "verified" && (!completion.claims.length || completion.claims.some((s) => !s.trim())))
6208
6596
  throw new TypeError(
6209
6597
  "Goal and independent verification claims are required"
6210
6598
  );
@@ -6230,7 +6618,10 @@ async function runGoal(page, planner, judge, options) {
6230
6618
  signal.removeEventListener("abort", onAbort);
6231
6619
  }
6232
6620
  };
6233
- const entries = Object.values(options.data ?? {});
6621
+ const entries = [
6622
+ ...Object.values(options.data ?? {}),
6623
+ ...options.opaqueEntries ?? []
6624
+ ];
6234
6625
  const taints = entries.map(
6235
6626
  (entry) => entry.sensitive ? { ...entry, opaqueValues: [...entry.opaqueValues ?? [], entry.value] } : entry
6236
6627
  );
@@ -6242,8 +6633,11 @@ async function runGoal(page, planner, judge, options) {
6242
6633
  let actions = 0;
6243
6634
  let pendingCall = false;
6244
6635
  let reportedCalls = 0;
6636
+ let failure;
6637
+ let staleDetail;
6245
6638
  const result = (reason, detail) => ({
6246
- status: reason === "verified" ? "passed" : "failed",
6639
+ ...generators ? { dataSeed } : {},
6640
+ status: reason === "verified" || reason === "completed" ? "passed" : "failed",
6247
6641
  reason,
6248
6642
  requests,
6249
6643
  actions,
@@ -6251,14 +6645,18 @@ async function runGoal(page, planner, judge, options) {
6251
6645
  calls,
6252
6646
  history,
6253
6647
  ...detail ? { detail } : {},
6648
+ ...failure ? { failure } : {},
6254
6649
  verification
6255
6650
  });
6256
- const uncertain = (what, answer, route, label = (choice) => choice) => {
6257
- let where = route;
6651
+ const routeName = (route) => {
6258
6652
  try {
6259
- where = new URL(route).pathname || route;
6653
+ return new URL(route).pathname || route;
6260
6654
  } catch {
6655
+ return route;
6261
6656
  }
6657
+ };
6658
+ const uncertain = (what, answer, route, label = (choice) => choice) => {
6659
+ const where = routeName(route);
6262
6660
  const top = answer ? Object.entries(answer.probabilities).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([choice, p]) => `${label(choice)} ${p.toFixed(2)}`).join(", ") : "no answer";
6263
6661
  return project(`${what} on ${where}: ${top}`);
6264
6662
  };
@@ -6283,16 +6681,45 @@ async function runGoal(page, planner, judge, options) {
6283
6681
  `(({ refs, bindings }) => refs.map(ref => {
6284
6682
  const element = [...document.querySelectorAll('[data-sedum-ref]')].find(e => e.getAttribute('data-sedum-ref') === ref);
6285
6683
  const value = element && ('value' in element ? element.value : element.textContent);
6286
- return { populated: !!value, bindings: bindings.filter(([,text]) => value === text).map(([key]) => key) };
6684
+ const constraints = Object.fromEntries(['autocomplete', 'minlength', 'maxlength', 'pattern', 'min', 'max', 'step', 'required'].filter(key => element?.hasAttribute(key)).map(key => [key, element.getAttribute(key)]));
6685
+ return { populated: !!value, bindings: bindings.filter(([,text]) => value === text).map(([key]) => key), constraints };
6287
6686
  }))(${JSON.stringify({
6288
6687
  refs: fills.candidates.map((c) => c.ref),
6289
- bindings: Object.entries(options.data ?? {}).map(([key, entry]) => [
6688
+ bindings: Object.entries(data).map(([key, entry]) => [
6290
6689
  key,
6291
6690
  entry.value.reveal()
6292
6691
  ])
6293
6692
  })})`
6294
6693
  )
6295
6694
  );
6695
+ const valueObservation = JSON.stringify([
6696
+ digest.version.document,
6697
+ digest.version.route,
6698
+ digest.text,
6699
+ fills.candidates.map((c) => ({
6700
+ ...c,
6701
+ ref: void 0,
6702
+ signals: { ...c.signals, nodeId: void 0 }
6703
+ })),
6704
+ fieldState
6705
+ ]);
6706
+ if (pendingValue && pendingValue.observation !== valueObservation) {
6707
+ failure = {
6708
+ version: pendingValue.version,
6709
+ operation: "type",
6710
+ targetName: project(pendingValue.fieldName),
6711
+ targetRole: pendingValue.fieldRole,
6712
+ confidence: pendingValue.confidence,
6713
+ probability: pendingValue.probability,
6714
+ ...pendingValue.generator ? { generator: pendingValue.generator } : {}
6715
+ };
6716
+ return result(
6717
+ "stale_value_target",
6718
+ project(
6719
+ `The page or fillable-field surface changed before typing into ${pendingValue.fieldName} on ${routeName(pendingValue.route)}; no action was dispatched.${pendingValue.generator ? ` The retained synthetic value came from ${pendingValue.generator}; its value remains hidden.` : ""}`
6720
+ )
6721
+ );
6722
+ }
6296
6723
  const describe = (c) => JSON.stringify({
6297
6724
  name: project(c.name),
6298
6725
  role: c.role,
@@ -6312,10 +6739,21 @@ async function runGoal(page, planner, judge, options) {
6312
6739
  (targets.CLICK ??= {})[id] = describe(c);
6313
6740
  commands.set(id, { op: "click", target: target(c) });
6314
6741
  }
6315
- for (const [index2, c] of fills.candidates.entries()) {
6742
+ for (const [index, c] of fills.candidates.entries()) {
6316
6743
  if (c.disabled || !c.editable) continue;
6317
- const current = fieldState[index2];
6318
- for (const [key, entry] of Object.entries(options.data ?? {})) {
6744
+ const current = fieldState[index];
6745
+ if (generators) {
6746
+ if (current.populated && current.bindings.length) continue;
6747
+ const id = `t${commands.size}`;
6748
+ (targets.TYPE ??= {})[id] = `${describe(c)} inputType=${c.inputType} constraints=${project(JSON.stringify(current.constraints ?? {}))} current=${current.populated ? "populated (unknown value)" : "empty"}`;
6749
+ commands.set(id, {
6750
+ op: "type",
6751
+ target: target(c),
6752
+ value: new RuntimeValue("")
6753
+ });
6754
+ continue;
6755
+ }
6756
+ for (const [key, entry] of Object.entries(data)) {
6319
6757
  if (current.bindings.includes(key)) continue;
6320
6758
  const id = `t${commands.size}`;
6321
6759
  (targets.TYPE ??= {})[id] = `${describe(c)} current=${current.populated ? `populated (${current.bindings.join(",")})` : "empty"} \u2190 {{${key}}}${entry.sensitive ? " (secret)" : ` = ${project(entry.value.reveal())}`}`;
@@ -6337,12 +6775,23 @@ async function runGoal(page, planner, judge, options) {
6337
6775
  ]);
6338
6776
  const visits = (seen.get(fingerprint) ?? 0) + 1;
6339
6777
  seen.set(fingerprint, visits);
6340
- if (visits > 3) return result("no_progress");
6778
+ if (visits > 3)
6779
+ return staleDetail ? result("stale_observation", staleDetail) : result("no_progress");
6341
6780
  const state2 = {
6781
+ ...completion.kind === "planner" ? { completion: "planner" } : {},
6782
+ ...generators ? { automaticData: true, declaredDataKeys: Object.keys(data) } : {},
6342
6783
  goal: project(options.goal),
6343
6784
  page: project(digest.text),
6344
6785
  recentActions: history.slice(-10),
6345
- targets
6786
+ targets: planner.targetChoiceMinOptions === 2 ? Object.fromEntries(
6787
+ Object.entries(targets).map(([op2, choices]) => [
6788
+ op2,
6789
+ Object.keys(choices).length === 1 ? {
6790
+ ...choices,
6791
+ [GOAL_NO_MATCH]: "No offered target is appropriate for this operation; abstain"
6792
+ } : choices
6793
+ ])
6794
+ ) : targets
6346
6795
  };
6347
6796
  if (Buffer.byteLength(JSON.stringify(state2)) > 60 * 1024)
6348
6797
  return result("request_too_large");
@@ -6364,15 +6813,42 @@ async function runGoal(page, planner, judge, options) {
6364
6813
  );
6365
6814
  if (!same(digest.version, await active(pageVersion(page)))) continue;
6366
6815
  const op = decision.operation.choice;
6367
- if (op === "BLOCKED") return result("blocked");
6816
+ if (pendingValue && op !== "TYPE") {
6817
+ failure = {
6818
+ version: pendingValue.version,
6819
+ operation: "type",
6820
+ targetName: project(pendingValue.fieldName),
6821
+ targetRole: pendingValue.fieldRole,
6822
+ confidence: pendingValue.confidence,
6823
+ probability: pendingValue.probability,
6824
+ ...pendingValue.generator ? { generator: pendingValue.generator } : {}
6825
+ };
6826
+ return result(
6827
+ "stale_value_target",
6828
+ project(
6829
+ `The planner no longer selected the pending fill for ${pendingValue.fieldName} on ${routeName(pendingValue.route)}; no action was dispatched.${pendingValue.generator ? ` The retained synthetic value came from ${pendingValue.generator}; its value remains hidden.` : ""}`
6830
+ )
6831
+ );
6832
+ }
6833
+ if (op === "BLOCKED") {
6834
+ failure = { version: digest.version };
6835
+ const offered = Object.entries(targets).filter(([, choices]) => Object.keys(choices).length).map(([name, choices]) => `${name} (${Object.keys(choices).length})`).join(", ");
6836
+ return result(
6837
+ "blocked",
6838
+ project(
6839
+ `The planner could not find a safe next action on ${routeName(digest.version.route)} after ${actions} dispatched action${actions === 1 ? "" : "s"}; ${offered ? `available targets were ${offered}` : "no click or fill targets were available"}.`
6840
+ )
6841
+ );
6842
+ }
6368
6843
  if (op === "DONE") {
6369
- for (const claim2 of options.verify) {
6844
+ if (completion.kind === "planner") return result("completed");
6845
+ for (const claim2 of completion.claims) {
6370
6846
  if (requests >= maxRequests) return result("request_limit");
6371
6847
  requests++;
6372
6848
  const singleAttemptJudge = {
6373
6849
  holds: (text, snapshot, callOptions) => {
6374
6850
  pendingCall = true;
6375
- return judge.holds(text, snapshot, {
6851
+ return completion.judge.holds(text, snapshot, {
6376
6852
  ...callOptions,
6377
6853
  maxAttempts: 1
6378
6854
  });
@@ -6414,9 +6890,122 @@ async function runGoal(page, planner, judge, options) {
6414
6890
  return name ? `"${name}"` : id;
6415
6891
  })
6416
6892
  );
6417
- const command = commands.get(head.choice);
6893
+ if (head.choice === GOAL_NO_MATCH) return result("target_abstention");
6894
+ let command = commands.get(head.choice);
6418
6895
  if (!command) return result("invalid_target");
6419
6896
  if (actions >= maxActions) return result("action_limit");
6897
+ if (command.op === "type" && generators && planner.chooseGoalValue) {
6898
+ const ref = command.target.driverTarget().ref;
6899
+ const index = fills.candidates.findIndex((c) => c.ref === ref);
6900
+ const field = fills.candidates[index];
6901
+ if (pendingValue && pendingValue.index !== index) {
6902
+ failure = {
6903
+ version: pendingValue.version,
6904
+ operation: "type",
6905
+ targetName: project(pendingValue.fieldName),
6906
+ targetRole: pendingValue.fieldRole,
6907
+ confidence: pendingValue.confidence,
6908
+ probability: pendingValue.probability,
6909
+ ...pendingValue.generator ? { generator: pendingValue.generator } : {}
6910
+ };
6911
+ return result(
6912
+ "stale_value_target",
6913
+ project(
6914
+ `The pending fill target moved from its observed position before dispatch on ${routeName(pendingValue.route)}; no action was dispatched.${pendingValue.generator ? ` The retained synthetic value came from ${pendingValue.generator}; its value remains hidden.` : ""}`
6915
+ )
6916
+ );
6917
+ }
6918
+ let key = pendingValue?.key;
6919
+ let generator = pendingValue?.generator;
6920
+ if (!key) {
6921
+ const choices = {
6922
+ BLOCKED: "Requires unavailable real credentials, OTP, specific factual text, or unsupported constraints; do not invent it",
6923
+ ...Object.fromEntries(
6924
+ Object.entries(data).map(([id2, entry]) => [
6925
+ `use.${id2}`,
6926
+ generated.has(id2) ? `REUSE ${id2}: ${project(generated.get(id2))}` : `USE supplied {{${id2}}}${entry.sensitive ? " (secret)" : ` = ${project(entry.value.reveal())}`}`
6927
+ ])
6928
+ ),
6929
+ ...generators.descriptions
6930
+ };
6931
+ if (Object.keys(choices).length > 255)
6932
+ return result("value_candidate_limit");
6933
+ if (requests >= maxRequests) return result("request_limit");
6934
+ requests++;
6935
+ pendingCall = true;
6936
+ const selected2 = await active(
6937
+ planner.chooseGoalValue(
6938
+ {
6939
+ goal: project(options.goal),
6940
+ page: project(digest.text),
6941
+ field: targets.TYPE[head.choice],
6942
+ choices
6943
+ },
6944
+ { signal, maxAttempts: 1 }
6945
+ )
6946
+ );
6947
+ calls.push(selected2.call);
6948
+ pendingCall = false;
6949
+ if (!goalChoiceAccepted(selected2.value, Object.keys(choices)))
6950
+ return result(
6951
+ "value_abstention",
6952
+ uncertain(
6953
+ `value for ${field.name}`,
6954
+ selected2.value,
6955
+ digest.version.route
6956
+ )
6957
+ );
6958
+ const id = selected2.value.choice;
6959
+ if (id === "BLOCKED") {
6960
+ failure = {
6961
+ version: digest.version,
6962
+ operation: "type",
6963
+ targetName: project(field.name),
6964
+ targetRole: field.role,
6965
+ confidence: head.confidence,
6966
+ probability: head.probabilities[head.choice]
6967
+ };
6968
+ return result(
6969
+ "value_blocked",
6970
+ project(
6971
+ `No safe supplied or synthetic value was available for ${field.name} on ${routeName(digest.version.route)}; no action was dispatched. Supply test data explicitly or disable this goal's automatic generation.`
6972
+ )
6973
+ );
6974
+ }
6975
+ if (id.startsWith("use.")) key = id.slice(4);
6976
+ else {
6977
+ generator = id;
6978
+ key = `generated_${generated.size + 1}`;
6979
+ while (key in data) key = `_${key}`;
6980
+ const value = new RuntimeValue(
6981
+ generators.generate(id),
6982
+ `{{${key}}}`
6983
+ );
6984
+ data[key] = { value, sensitive: true, opaqueValues: [value] };
6985
+ taints.push(data[key]);
6986
+ options.onGeneratedValue?.(value);
6987
+ generated.set(
6988
+ key,
6989
+ `${id} selected for ${describe(field)} on ${project(digest.version.route)} (not yet filled)`
6990
+ );
6991
+ }
6992
+ pendingValue = {
6993
+ observation: valueObservation,
6994
+ index,
6995
+ key,
6996
+ ...generator ? { generator } : {},
6997
+ fieldName: field.name,
6998
+ fieldRole: field.role,
6999
+ route: digest.version.route,
7000
+ version: digest.version,
7001
+ confidence: head.confidence,
7002
+ probability: head.probabilities[head.choice]
7003
+ };
7004
+ }
7005
+ bindingKeys.set(head.choice, key);
7006
+ command = { ...command, value: data[key].value };
7007
+ targets.TYPE[head.choice] += ` \u2190 {{${key}}}`;
7008
+ }
6420
7009
  if (command.op !== "click" && command.op !== "type")
6421
7010
  return result("invalid_target");
6422
7011
  const source = command.op === "click" ? clicks : fills;
@@ -6424,14 +7013,49 @@ async function runGoal(page, planner, judge, options) {
6424
7013
  collectCandidates(page, command.op === "click" ? "click" : "fill")
6425
7014
  );
6426
7015
  const surface = (candidates) => JSON.stringify(candidates.map((c) => ({ ...c, ref: void 0 })));
6427
- if (!fresh.complete || fresh.next !== null || !same(source.version, fresh.version) || surface(source.candidates) !== surface(fresh.candidates))
6428
- return result("stale_observation");
6429
- const index = source.candidates.findIndex(
7016
+ const selectedIndex = source.candidates.findIndex(
6430
7017
  (c) => c.ref === command.target.driverTarget().ref
6431
7018
  );
6432
- const chosen = fresh.candidates[index];
7019
+ const selected = source.candidates[selectedIndex];
7020
+ if (!fresh.complete || fresh.next !== null || !same(source.version, fresh.version) || surface(source.candidates) !== surface(fresh.candidates)) {
7021
+ failure = {
7022
+ version: source.version,
7023
+ operation: command.op,
7024
+ ...selected ? {
7025
+ targetName: project(selected.name),
7026
+ targetRole: selected.role,
7027
+ confidence: head.confidence,
7028
+ probability: head.probabilities[head.choice],
7029
+ ...pendingValue?.generator ? { generator: pendingValue.generator } : {}
7030
+ } : {}
7031
+ };
7032
+ const changed = !same(source.version, fresh.version) ? `the page version changed from revision ${source.version.revision} to ${fresh.version.revision}` : !fresh.complete || fresh.next !== null ? "the refreshed candidate list was incomplete" : "the available target surface changed";
7033
+ staleDetail = project(
7034
+ `Before ${command.op === "type" ? "typing into" : "clicking"} ${selected?.name ?? "the selected target"} on ${routeName(source.version.route)}, ${changed}; the stale target was not dispatched and Sedum re-observed the page.${pendingValue?.generator ? ` The retained synthetic value came from ${pendingValue.generator}; its value remains hidden.` : ""}`
7035
+ );
7036
+ continue;
7037
+ }
7038
+ const chosen = fresh.candidates[selectedIndex];
6433
7039
  if (!chosen) return result("invalid_target");
7040
+ failure = void 0;
7041
+ staleDetail = void 0;
6434
7042
  const refreshed = { ...command, target: target(chosen) };
7043
+ if (generators && command.op === "type") {
7044
+ const valid = await active(
7045
+ page.evaluate(`(({ ref, value }) => {
7046
+ const original = [...document.querySelectorAll('[data-sedum-ref]')].find(e => e.getAttribute('data-sedum-ref') === ref);
7047
+ if (!original) return false;
7048
+ const input = original.cloneNode(false);
7049
+ if (!('value' in input)) return true;
7050
+ input.value = value;
7051
+ return input.value === value &&
7052
+ (input.maxLength === undefined || input.maxLength < 0 || value.length <= input.maxLength) &&
7053
+ (input.minLength === undefined || input.minLength < 0 || value.length >= input.minLength) &&
7054
+ input.checkValidity();
7055
+ })(${JSON.stringify({ ref: chosen.ref, value: command.value.reveal() })})`)
7056
+ );
7057
+ if (!valid) return result("value_constraint_mismatch");
7058
+ }
6435
7059
  if (signal.aborted) return result("timeout");
6436
7060
  actions++;
6437
7061
  history.push(project(`${op} ${targets[op][head.choice]}`));
@@ -6440,7 +7064,7 @@ async function runGoal(page, planner, judge, options) {
6440
7064
  const sentence = project(
6441
7065
  command.op === "type" ? `Type {{${binding}}} into ${chosen.name}` : `Click ${chosen.name}${chosen.peers[0] ? ` (${chosen.peers[0]})` : ""}`
6442
7066
  );
6443
- let failure;
7067
+ let actionFailure;
6444
7068
  let failed = false;
6445
7069
  try {
6446
7070
  await active(
@@ -6454,9 +7078,9 @@ async function runGoal(page, planner, judge, options) {
6454
7078
  );
6455
7079
  } catch (error2) {
6456
7080
  failed = true;
6457
- failure = error2;
7081
+ actionFailure = error2;
6458
7082
  }
6459
- if (failed && failure instanceof StepExecutionError && failure.code === "stale" && failure.phase === "pre_dispatch" && !signal.aborted) {
7083
+ if (failed && actionFailure instanceof StepExecutionError && actionFailure.code === "stale" && actionFailure.phase === "pre_dispatch" && !signal.aborted) {
6460
7084
  actions--;
6461
7085
  history.pop();
6462
7086
  continue;
@@ -6470,12 +7094,18 @@ async function runGoal(page, planner, judge, options) {
6470
7094
  probability: head.probabilities[head.choice],
6471
7095
  beforeVersion: fresh.version,
6472
7096
  status: failed ? "failed" : "passed",
6473
- reason: !failed ? null : signal.aborted ? "timeout" : failure instanceof StepExecutionError ? `${failure.code}:${failure.phase}` : "action_failed",
7097
+ reason: !failed ? null : signal.aborted ? "timeout" : actionFailure instanceof StepExecutionError ? `${actionFailure.code}:${actionFailure.phase}` : "action_failed",
6474
7098
  elapsedMs: performance.now() - actionStarted,
6475
7099
  calls: calls.slice(reportedCalls)
6476
7100
  });
6477
7101
  reportedCalls = calls.length;
6478
- if (failed) throw failure;
7102
+ if (failed) throw actionFailure;
7103
+ pendingValue = void 0;
7104
+ if (binding && generated.has(binding))
7105
+ generated.set(
7106
+ binding,
7107
+ `${generated.get(binding).replace(" (not yet filled)", "")}; filled ${describe(chosen)} on ${project(digest.version.route)}`
7108
+ );
6479
7109
  }
6480
7110
  return result("timeout");
6481
7111
  } catch (error2) {
@@ -6612,11 +7242,163 @@ function gotoUrlParts(sentence) {
6612
7242
  literals.push(rest);
6613
7243
  return { literals, names };
6614
7244
  }
7245
+ var WAIT_UNTIL_DEFAULT_MS = 3e4;
7246
+ var WAIT_UNTIL_MAX_MS = 12e4;
7247
+ function waitUntilTimeoutMs(sentence) {
7248
+ const text = canonicalSentence(sentence);
7249
+ if (!WAIT_UNTIL.test(text)) return null;
7250
+ const limit = /^wait\s+up\s+to\s+(\d+(?:\.\d+)?)/iu.exec(text);
7251
+ if (!limit) return WAIT_UNTIL_DEFAULT_MS;
7252
+ return Math.min(WAIT_UNTIL_MAX_MS, Math.max(1e3, Number(limit[1]) * 1e3));
7253
+ }
7254
+ 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";
7255
+ var FIELD_NOUN = /\b(?:field|input|text\s*box|search\s*box|box)$/iu;
7256
+ var STATE_CLAIM = new RegExp(
7257
+ `^(?: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*\\.?$`,
7258
+ "iu"
7259
+ );
7260
+ var VALUE_CLAIM = new RegExp(
7261
+ `^(?: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*\\.?$`,
7262
+ "iu"
7263
+ );
7264
+ function elementClaim(claim2) {
7265
+ const text = canonicalSentence(claim2);
7266
+ if (/^(?:there\s+is\s+)?no\s+/iu.test(text)) return null;
7267
+ const valued = VALUE_CLAIM.exec(text);
7268
+ if (valued)
7269
+ return {
7270
+ target: valued[1],
7271
+ operation: "fill",
7272
+ expect: {
7273
+ kind: "value",
7274
+ value: valued[2].replace(/^(["“'])(.*)(["”'])$/u, "$2")
7275
+ }
7276
+ };
7277
+ const state2 = STATE_CLAIM.exec(text);
7278
+ if (!state2) return null;
7279
+ const target = state2[1];
7280
+ const negated = !!state2[2];
7281
+ const word = state2[3].toLowerCase();
7282
+ const fill = FIELD_NOUN.test(target);
7283
+ const expect = [
7284
+ "shown",
7285
+ "visible",
7286
+ "displayed",
7287
+ "present"
7288
+ ].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;
7289
+ if (!expect) return null;
7290
+ return {
7291
+ target,
7292
+ operation: fill && expect.kind !== "disabled" ? "fill" : "click",
7293
+ expect
7294
+ };
7295
+ }
7296
+ var QUOTED = `(?:"([^"]+)"|\u201C([^\u201D]+)\u201D)`;
7297
+ var SHOWN = "(?:shown|visible|displayed|present|on\\s+the\\s+page)";
7298
+ var QUOTED_LIST = `((?:"[^"]+"|\u201C[^\u201D]+\u201D)(?:\\s*(?:,|or|,\\s*or)\\s*(?:"[^"]+"|\u201C[^\u201D]+\u201D))*)`;
7299
+ var TEXT_PRESENCE = new RegExp(
7300
+ `^(?:the\\s+)?(?:texts?\\s+)?${QUOTED_LIST}\\s+(?:is|are)\\s+(not\\s+)?${SHOWN}\\s*\\.?$`,
7301
+ "iu"
7302
+ );
7303
+ var quotedTexts = (list) => [...list.matchAll(/"([^"]+)"|“([^”]+)”/gu)].map((m) => m[1] ?? m[2]);
7304
+ var TEXT_ABSENCE = new RegExp(
7305
+ `^(?: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*\\.?$`,
7306
+ "iu"
7307
+ );
7308
+ var TEXT_COUNT = new RegExp(
7309
+ `^(?:the\\s+)?(?:text\\s+)?${QUOTED}\\s+(?:appears|is\\s+shown|occurs)\\s+(?:exactly\\s+)?(once|twice|\\d+\\s+times?)\\s*\\.?$`,
7310
+ "iu"
7311
+ );
7312
+ function literalShown(claim2) {
7313
+ const text = canonicalSentence(claim2);
7314
+ if (/["“]/u.test(text)) return null;
7315
+ const literal = LITERAL_PRESENCE.exec(text);
7316
+ return literal && !literal[2] ? literal[1] : null;
7317
+ }
7318
+ var LITERAL_PRESENCE = /^the\s+text\s+(.+?)\s+(?:is|are)\s+(not\s+)?(?:shown|visible|displayed|present|on\s+the\s+page)\s*$/iu;
7319
+ var URL_CLAIM = new RegExp(
7320
+ `^(?:the\\s+)?(?:page\\s+|current\\s+)?(?:url|address)\\s+(does\\s+not\\s+contain|contains|includes)\\s+${QUOTED_LIST}\\s*\\.?$`,
7321
+ "iu"
7322
+ );
7323
+ function textClaim(claim2) {
7324
+ const text = canonicalSentence(claim2);
7325
+ const url = URL_CLAIM.exec(text);
7326
+ if (url) {
7327
+ const texts = quotedTexts(url[2]);
7328
+ return {
7329
+ text: texts[0],
7330
+ ...texts.length > 1 ? { alternatives: texts } : {},
7331
+ expect: { kind: "url", contains: !/not/iu.test(url[1]) }
7332
+ };
7333
+ }
7334
+ const presence = TEXT_PRESENCE.exec(text);
7335
+ if (presence) {
7336
+ const texts = quotedTexts(presence[1]);
7337
+ return {
7338
+ text: texts[0],
7339
+ ...texts.length > 1 ? { alternatives: texts } : {},
7340
+ expect: { kind: "present", present: !presence[2] }
7341
+ };
7342
+ }
7343
+ const absence = TEXT_ABSENCE.exec(text);
7344
+ if (absence)
7345
+ return {
7346
+ text: absence[1] ?? absence[2] ?? absence[3] ?? absence[4],
7347
+ expect: { kind: "present", present: false }
7348
+ };
7349
+ const counted = TEXT_COUNT.exec(text);
7350
+ if (!counted) return null;
7351
+ const word = counted[3].toLowerCase();
7352
+ return {
7353
+ text: counted[1] ?? counted[2],
7354
+ expect: {
7355
+ kind: "count",
7356
+ count: word === "once" ? 1 : word === "twice" ? 2 : Number.parseInt(word, 10)
7357
+ }
7358
+ };
7359
+ }
7360
+ function countText(haystack, needle, ignoreCase = false) {
7361
+ const space = (text) => {
7362
+ const spaced = text.replace(/\s+/gu, " ").trim();
7363
+ return ignoreCase ? spaced.toLocaleLowerCase() : spaced;
7364
+ };
7365
+ const page = space(haystack);
7366
+ const wanted = space(needle);
7367
+ if (!wanted) return 0;
7368
+ return page.split(wanted).length - 1;
7369
+ }
7370
+ function historyMove(sentence) {
7371
+ const text = canonicalSentence(sentence).replace(/\.$/u, "");
7372
+ if (/^(?:go|navigate)\s+back(?:\s+to\s+the\s+previous\s+page)?$/iu.test(text))
7373
+ return "back";
7374
+ if (/^(?:go|navigate)\s+forward$/iu.test(text)) return "forward";
7375
+ if (/^(?:reload|refresh)(?:\s+the\s+page)?$/iu.test(text)) return "reload";
7376
+ return null;
7377
+ }
7378
+ function gotoPathParts(sentence) {
7379
+ const path11 = /^(?:goto|go\s+to|navigate\s+to|open)\s+(\/\S*)\s*$/iu.exec(
7380
+ canonicalSentence(sentence)
7381
+ )?.[1];
7382
+ if (!path11) return null;
7383
+ const literals = [];
7384
+ const names = [];
7385
+ let rest = path11.replace(/[.,;]+$/u, "");
7386
+ for (; ; ) {
7387
+ const match = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/u.exec(rest);
7388
+ if (!match) break;
7389
+ literals.push(rest.slice(0, match.index));
7390
+ names.push(match[1]);
7391
+ rest = rest.slice(match.index + match[0].length);
7392
+ }
7393
+ literals.push(rest);
7394
+ return { literals, names };
7395
+ }
6615
7396
 
6616
7397
  // src/flow-runner.ts
6617
7398
  function resultCall(call2, purpose, apiMs = null) {
6618
7399
  return {
6619
7400
  purpose,
7401
+ ...call2.provider ? { provider: call2.provider } : {},
6620
7402
  ...call2.modality ? { modality: call2.modality } : {},
6621
7403
  requestedModel: call2.requestedModel,
6622
7404
  model: call2.model,
@@ -6662,11 +7444,11 @@ function providerFailure(file, error2) {
6662
7444
  },
6663
7445
  authentication: {
6664
7446
  message: "The model provider rejected the API key.",
6665
- fix: "Set TYPESAFE_API_KEY to a valid key, check it with `sedum doctor`, then rerun."
7447
+ fix: "Set the selected provider's API key (TYPESAFE_API_KEY or CLOUDFLARE_AUTH_TOKEN), check it with `sedum doctor`, then rerun."
6666
7448
  },
6667
7449
  configuration: {
6668
7450
  message: "The model provider is not configured correctly.",
6669
- fix: "Check TYPESAFE_API_KEY, TYPESAFE_BASE_URL and the model with `sedum doctor`, then rerun."
7451
+ fix: "Check the selected provider's credentials, account or endpoint, and model with `sedum doctor`, then rerun."
6670
7452
  }
6671
7453
  };
6672
7454
  return {
@@ -6754,9 +7536,16 @@ function runtimeFailure(file, error2) {
6754
7536
  fix: "Check the browser, provider, and test input, then rerun the test."
6755
7537
  };
6756
7538
  }
7539
+ 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;
7540
+ function withValues(text, data) {
7541
+ return text.replace(
7542
+ /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
7543
+ (placeholder, key) => data[key]?.modelVisible ? data[key].value.reveal() : placeholder
7544
+ );
7545
+ }
6757
7546
  function claim(step, data) {
6758
7547
  return step.text.replace(
6759
- /^\s*(?:verify|assert|check|confirm|ensure|expect|measure|note|observe)\b\s*(?:that\s+|whether\s+|if\s+)?/iu,
7548
+ /^\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,
6760
7549
  ""
6761
7550
  ).trim().replace(
6762
7551
  /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
@@ -6871,12 +7660,12 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
6871
7660
  const acceptedVersion = facts.verify?.observationVersion ?? (locator?.kind === "resolved" ? locator.target.driverTarget().version : locator?.diagnostic.observationVersion);
6872
7661
  const sensitive = facts.page?.status === "omitted" && facts.page.reason === "sensitive_page" || acceptedVersion !== void 0 && safeUrl(acceptedVersion.route, privacy).sensitive || safeUrl(page.url, privacy).sensitive;
6873
7662
  const isError = typeof outcome === "object" && outcome.status === "could_not_run";
6874
- const failed = outcome === "failed" || typeof outcome === "object" && outcome.status === "failed";
7663
+ const failed = outcome === "failed" && !presentation.check || typeof outcome === "object" && outcome.status === "failed";
6875
7664
  const flags = facts.verify?.kind === "verify" ? facts.verify.flags : [];
6876
7665
  const needsEvidence = failed || isError || flags.length > 0;
6877
7666
  const evidence = !needsEvidence ? { status: "omitted", reason: "clean_step" } : sensitive ? { status: "omitted", reason: "sensitive_page" } : !report.evidenceEnabled ? { status: "omitted", reason: "disabled" } : await capture("evidence", acceptedVersion);
6878
7667
  const replayFrame2 = !report.replay ? null : sensitive ? { status: "omitted", reason: "sensitive_page" } : facts.replayFrame ?? await capture("replay", acceptedVersion);
6879
- const kind = step.op === "verify" ? "verify" : step.op === "measure" ? "measure" : "action";
7668
+ const kind = step.op === "measure" || step.op === "verify" && presentation.check ? "measure" : step.op === "verify" ? "verify" : "action";
6880
7669
  const pageInfo = facts.page ?? await reportPage(
6881
7670
  page,
6882
7671
  `${stepId}:observation:1`,
@@ -6955,9 +7744,15 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
6955
7744
  await report.test.addStep(result);
6956
7745
  return outcome;
6957
7746
  };
6958
- const runWide = async (error2) => {
7747
+ const runWide = async (error2, facts = {}) => {
6959
7748
  const outcome = providerFailure(step.source.file, error2);
7749
+ const modality = step.op === "verify" || step.op === "measure" ? "judge" : "locator";
6960
7750
  await record(outcome, {
7751
+ ...facts,
7752
+ failedCalls: [
7753
+ ...facts.failedCalls ?? [],
7754
+ resultCall(unknownCostCall(error2), modality)
7755
+ ],
6961
7756
  error: { code: outcome.code, message: outcome.message }
6962
7757
  });
6963
7758
  return error2;
@@ -6965,7 +7760,8 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
6965
7760
  const quiet = await quietPage(page, 80, 4e3).catch(() => ({
6966
7761
  quiet: false
6967
7762
  }));
6968
- if (!quiet.quiet)
7763
+ const waits = step.op === "verify" && waitUntilTimeoutMs(step.text) !== null;
7764
+ if (!quiet.quiet && !waits)
6969
7765
  return record(
6970
7766
  unsupported(
6971
7767
  step.source.file,
@@ -7110,11 +7906,286 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7110
7906
  ...dependencies.signal ? { signal: dependencies.signal } : {},
7111
7907
  projectText: (text) => redactOpaqueText(text, opaqueEntries)
7112
7908
  };
7113
- const judge = () => step.op === "measure" ? measure(page, dependencies.provider, claim(step, data), assertion) : verify(page, dependencies.provider, claim(step, data), {
7909
+ const judge = (signal = dependencies.signal, observationTimeoutMs) => step.op === "measure" ? measure(page, dependencies.provider, claim(step, data), {
7114
7910
  ...assertion,
7911
+ ...signal ? { signal } : {},
7912
+ ...observationTimeoutMs === void 0 ? {} : { observationTimeoutMs }
7913
+ }) : verify(page, dependencies.provider, claim(step, data), {
7914
+ ...assertion,
7915
+ ...signal ? { signal } : {},
7916
+ ...observationTimeoutMs === void 0 ? {} : { observationTimeoutMs },
7115
7917
  ...dependencies.verifyPolicy ?? {}
7116
7918
  });
7117
7919
  const outcome = (result) => result.kind === "verify" && result.verdict === "failed" ? "failed" : "continue";
7920
+ const readableText = async () => {
7921
+ const text = await visibleText(page);
7922
+ if (text === null) throw new Error("The page text could not be read.");
7923
+ return text;
7924
+ };
7925
+ const literalText = step.op === "verify" ? literalShown(step.text.replace(CLAIM_PREFIX, "")) : null;
7926
+ const literal = literalText ? withValues(literalText, data) : null;
7927
+ const waitUntil = async (limitMs, pollUnchangedMs) => {
7928
+ const bounded = limitMs > 0;
7929
+ const deadline = performance.now() + limitMs;
7930
+ const earlier = [];
7931
+ let last;
7932
+ let lastError;
7933
+ for (; ; ) {
7934
+ if (dependencies.signal?.aborted) {
7935
+ if (last)
7936
+ earlier.push(resultCall(last.call, "judge", last.elapsedMs));
7937
+ last = void 0;
7938
+ lastError = new AssertionEngineError("canceled");
7939
+ break;
7940
+ }
7941
+ const before = await pageVersion(page).catch(() => null);
7942
+ if (literal) {
7943
+ await quietPage(page, 80, 2e3).catch(() => void 0);
7944
+ const shown = await readableText().then((text) => countText(text, literal, true) > 0).catch(() => false);
7945
+ if (shown) return record("continue", { failedCalls: earlier });
7946
+ }
7947
+ try {
7948
+ let result;
7949
+ if (!bounded) result = await judge();
7950
+ else {
7951
+ const remainingMs = Math.max(
7952
+ 1,
7953
+ Math.ceil(deadline - performance.now())
7954
+ );
7955
+ const deadlineSignal = AbortSignal.timeout(remainingMs);
7956
+ const signal = dependencies.signal ? AbortSignal.any([dependencies.signal, deadlineSignal]) : deadlineSignal;
7957
+ result = await judge(signal, remainingMs);
7958
+ }
7959
+ if (outcome(result) === "continue")
7960
+ return record("continue", {
7961
+ verify: result,
7962
+ // Every earlier judgement was billed too.
7963
+ failedCalls: last ? [...earlier, resultCall(last.call, "judge", last.elapsedMs)] : earlier
7964
+ });
7965
+ if (last)
7966
+ earlier.push(resultCall(last.call, "judge", last.elapsedMs));
7967
+ last = result;
7968
+ lastError = void 0;
7969
+ } catch (error2) {
7970
+ if (isRunWideProviderError(error2)) {
7971
+ const failedCalls = [...earlier];
7972
+ if (last)
7973
+ failedCalls.push(resultCall(last.call, "judge", last.elapsedMs));
7974
+ throw await runWide(error2, { failedCalls });
7975
+ }
7976
+ if (error2 instanceof AssertionEngineError && error2.failedCall)
7977
+ earlier.push(resultCall(error2.failedCall, "judge"));
7978
+ if (bounded && performance.now() >= deadline && !dependencies.signal?.aborted) {
7979
+ lastError = error2 instanceof AssertionEngineError ? new AssertionEngineError(
7980
+ "observation_timeout",
7981
+ error2.failedCall
7982
+ ) : new AssertionEngineError("observation_timeout");
7983
+ break;
7984
+ }
7985
+ if (!(error2 instanceof AssertionEngineError) || ![
7986
+ "stale_observation",
7987
+ "observation_timeout",
7988
+ "browser_failure",
7989
+ // Too much text to judge: the literal can still turn up.
7990
+ ...literal ? ["oversize_digest", "resource_ceiling"] : []
7991
+ ].includes(error2.code)) {
7992
+ lastError = error2;
7993
+ break;
7994
+ }
7995
+ lastError = error2;
7996
+ }
7997
+ let changed = false;
7998
+ const pollBy = pollUnchangedMs === null ? deadline : Math.min(deadline, performance.now() + pollUnchangedMs);
7999
+ while (performance.now() < pollBy) {
8000
+ await new Promise((resolve) => setTimeout(resolve, 200));
8001
+ if (dependencies.signal?.aborted) break;
8002
+ const now = await pageVersion(page).catch(() => null);
8003
+ if (!before || !now) {
8004
+ changed = true;
8005
+ break;
8006
+ }
8007
+ if (now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
8008
+ changed = true;
8009
+ break;
8010
+ }
8011
+ }
8012
+ if (dependencies.signal?.aborted) {
8013
+ if (last)
8014
+ earlier.push(resultCall(last.call, "judge", last.elapsedMs));
8015
+ last = void 0;
8016
+ lastError = new AssertionEngineError("canceled");
8017
+ break;
8018
+ }
8019
+ if (performance.now() >= deadline && !changed) break;
8020
+ if (!changed && pollUnchangedMs === null) break;
8021
+ await quietPage(page, 80, 2e3).catch(() => void 0);
8022
+ if (performance.now() >= deadline) break;
8023
+ }
8024
+ if (last)
8025
+ return record(outcome(last), { verify: last, failedCalls: earlier });
8026
+ return record(
8027
+ unsupported(
8028
+ step.source.file,
8029
+ step.source,
8030
+ lastError instanceof Error ? lastError.message : "The assertion could not be judged."
8031
+ ),
8032
+ {
8033
+ failedCalls: earlier,
8034
+ error: {
8035
+ code: lastError instanceof AssertionEngineError ? lastError.code : "assertion_error",
8036
+ message: "The assertion could not be judged."
8037
+ }
8038
+ }
8039
+ );
8040
+ };
8041
+ const checkElement = async (element2, limitMs) => {
8042
+ const deadline = performance.now() + limitMs;
8043
+ const earlier = [];
8044
+ let last;
8045
+ let message = "The control is not in the expected state.";
8046
+ let staleRetried = false;
8047
+ const target = withValues(element2.target, data);
8048
+ const locateAs = (operation) => resolveTarget(page, dependencies.provider, {
8049
+ operation,
8050
+ sentence: operation === "fill" ? `type into ${target}` : `click ${target}`,
8051
+ projectText: (text) => redactOpaqueText(text, opaqueEntries),
8052
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
8053
+ });
8054
+ const locate2 = async () => {
8055
+ const found = await locateAs(element2.operation);
8056
+ if (element2.operation !== "fill" || found.kind === "resolved" || found.reason !== "none" && found.reason !== "no_candidates")
8057
+ return found;
8058
+ const control = await locateAs("click");
8059
+ return control.kind === "resolved" && ["input", "textarea"].includes(control.target.driverTarget().tag) ? { ...control, calls: [...found.calls, ...control.calls] } : { ...found, calls: [...found.calls, ...control.calls] };
8060
+ };
8061
+ const expected = element2.expect;
8062
+ for (; ; ) {
8063
+ if (dependencies.signal?.aborted) break;
8064
+ const before = await pageVersion(page).catch(() => null);
8065
+ if (last)
8066
+ earlier.push(
8067
+ ...last.calls.map((call2) => resultCall(call2, "locator"))
8068
+ );
8069
+ last = await reobserve(page, await locate2(), locate2, {
8070
+ staleRetry: true,
8071
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
8072
+ });
8073
+ let holds = false;
8074
+ if (last.kind !== "resolved") {
8075
+ const missing2 = last.reason === "none" || last.reason === "no_candidates";
8076
+ holds = missing2 && expected.kind === "present" && !expected.present;
8077
+ message = missing2 ? "No such control is on the page." : `The control could not be found (${last.reason}).`;
8078
+ } else if (expected.kind === "present") {
8079
+ holds = expected.present;
8080
+ message = "The control is on the page.";
8081
+ } else {
8082
+ const state2 = await controlState(page, last.target.driverTarget());
8083
+ if (state2.status === "ok") {
8084
+ const value = (text) => text.replace(/\s+/gu, " ").trim();
8085
+ const wanted = expected.kind === "value" ? value(
8086
+ expected.value.replace(
8087
+ /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
8088
+ (placeholder, key) => data[key]?.value.reveal() ?? placeholder
8089
+ )
8090
+ ) : "";
8091
+ 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;
8092
+ 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.";
8093
+ } else {
8094
+ message = "The page changed while the control was read.";
8095
+ if (!staleRetried) {
8096
+ staleRetried = true;
8097
+ await quietPage(page, 80, 2e3).catch(() => void 0);
8098
+ continue;
8099
+ }
8100
+ }
8101
+ }
8102
+ if (holds)
8103
+ return record("continue", { locator: last, failedCalls: earlier });
8104
+ let changed = false;
8105
+ while (performance.now() < deadline) {
8106
+ await new Promise((resolve) => setTimeout(resolve, 200));
8107
+ const now = await pageVersion(page).catch(() => null);
8108
+ if (!before || !now) {
8109
+ changed = true;
8110
+ break;
8111
+ }
8112
+ if (now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
8113
+ changed = true;
8114
+ break;
8115
+ }
8116
+ }
8117
+ if (!changed) break;
8118
+ await quietPage(page, 80, 2e3).catch(() => void 0);
8119
+ }
8120
+ return record("failed", {
8121
+ ...last ? { locator: last } : {},
8122
+ failedCalls: earlier,
8123
+ error: { code: "element_state", message }
8124
+ });
8125
+ };
8126
+ const checkText = async (claimed, limitMs) => {
8127
+ const deadline = performance.now() + limitMs;
8128
+ const reveal = (text) => text.replace(
8129
+ /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
8130
+ (placeholder, key) => data[key]?.value.reveal() ?? placeholder
8131
+ );
8132
+ const wanted = (claimed.alternatives ?? [claimed.text]).map(reveal);
8133
+ let message = "";
8134
+ for (; ; ) {
8135
+ const before = await pageVersion(page).catch(() => null);
8136
+ await quietPage(page, 80, 2e3).catch(() => void 0);
8137
+ let found;
8138
+ try {
8139
+ const haystack = claimed.expect.kind === "url" ? "" : await readableText();
8140
+ found = wanted.reduce(
8141
+ (sum, text) => sum + (claimed.expect.kind === "url" ? Number(page.url.includes(text)) : countText(haystack, text, claimed.ignoreCase)),
8142
+ 0
8143
+ );
8144
+ } catch {
8145
+ return record(
8146
+ unsupported(
8147
+ step.source.file,
8148
+ step.source,
8149
+ "The page text could not be read."
8150
+ ),
8151
+ {
8152
+ error: {
8153
+ code: "text_unreadable",
8154
+ message: "The page text could not be read."
8155
+ }
8156
+ }
8157
+ );
8158
+ }
8159
+ const expected = claimed.expect;
8160
+ const holds = expected.kind === "present" ? found > 0 === expected.present : expected.kind === "url" ? found > 0 === expected.contains : found === expected.count;
8161
+ if (holds) return record("continue", {});
8162
+ 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.`;
8163
+ let changed = false;
8164
+ while (performance.now() < deadline) {
8165
+ await new Promise((resolve) => setTimeout(resolve, 200));
8166
+ const now = await pageVersion(page).catch(() => null);
8167
+ if (!before || !now) {
8168
+ changed = true;
8169
+ break;
8170
+ }
8171
+ if (now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
8172
+ changed = true;
8173
+ break;
8174
+ }
8175
+ }
8176
+ if (!changed) break;
8177
+ }
8178
+ return record("failed", { error: { code: "text_check", message } });
8179
+ };
8180
+ const until = step.op === "verify" ? waitUntilTimeoutMs(step.text) : null;
8181
+ const quoted = step.op === "verify" ? textClaim(step.text.replace(CLAIM_PREFIX, "")) : null;
8182
+ const graceMs = presentation.check ? 0 : dependencies.verifyGraceMs ?? 0;
8183
+ if (quoted) return checkText(quoted, until ?? graceMs);
8184
+ const element = step.op === "verify" ? elementClaim(step.text.replace(CLAIM_PREFIX, "")) : null;
8185
+ if (element) return checkElement(element, until ?? graceMs);
8186
+ if (until !== null) return waitUntil(until, 5e3);
8187
+ if (step.op === "verify" && (graceMs > 0 || literal))
8188
+ return waitUntil(graceMs, null);
7118
8189
  try {
7119
8190
  const result = await judge();
7120
8191
  return record(outcome(result), {
@@ -7136,7 +8207,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7136
8207
  });
7137
8208
  } catch (retryError) {
7138
8209
  if (isRunWideProviderError(retryError))
7139
- throw await runWide(retryError);
8210
+ throw await runWide(retryError, { failedCalls: priorCalls });
7140
8211
  return record(
7141
8212
  unsupported(
7142
8213
  step.source.file,
@@ -7209,24 +8280,47 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7209
8280
  deltaY: direction === "down" ? deltaY : -deltaY
7210
8281
  };
7211
8282
  } else {
7212
- const parts = gotoUrlParts(step.text);
7213
- if (parts === null) return invalid("Name exactly one http(s) address.");
7214
- const values = parts.names.map((name) => data[name]?.value);
7215
- if (values.some((value) => value === void 0))
7216
- return record("failed", {
7217
- error: {
7218
- code: "missing_remembered_binding",
7219
- message: "This step needs a value that is unavailable in this attempt."
7220
- }
7221
- });
7222
- const url = new RuntimeUrl(parts.literals, values);
7223
- try {
7224
- new URL(url.reveal());
7225
- } catch {
7226
- return invalid("The goto address is not a valid URL.");
8283
+ const move = historyMove(step.text);
8284
+ const path11 = move ? null : gotoPathParts(step.text);
8285
+ let origin = "";
8286
+ if (path11) {
8287
+ try {
8288
+ origin = new URL(page.url).origin;
8289
+ } catch {
8290
+ return invalid("A /path needs a page on a site to start from.");
8291
+ }
8292
+ if (!/^https?:/u.test(origin))
8293
+ return invalid("A /path needs a page on a site to start from.");
8294
+ }
8295
+ const parts = move ? null : path11 ? {
8296
+ ...path11,
8297
+ literals: [origin + path11.literals[0], ...path11.literals.slice(1)]
8298
+ } : gotoUrlParts(step.text);
8299
+ if (move) {
8300
+ command2 = { op: "history", move };
8301
+ detail = move === "reload" ? "Reloaded the page." : `Went ${move} in history.`;
8302
+ } else if (parts === null)
8303
+ return invalid(
8304
+ "Name exactly one http(s) address or a /path on this site."
8305
+ );
8306
+ else {
8307
+ const values = parts.names.map((name) => data[name]?.value);
8308
+ if (values.some((value) => value === void 0))
8309
+ return record("failed", {
8310
+ error: {
8311
+ code: "missing_remembered_binding",
8312
+ message: "This step needs a value that is unavailable in this attempt."
8313
+ }
8314
+ });
8315
+ const url = new RuntimeUrl(parts.literals, values);
8316
+ try {
8317
+ new URL(url.reveal());
8318
+ } catch {
8319
+ return invalid("The goto address is not a valid URL.");
8320
+ }
8321
+ command2 = { op: "goto", url };
8322
+ detail = `Opened ${url.toString()}.`;
7227
8323
  }
7228
- command2 = { op: "goto", url };
7229
- detail = `Opened ${url.toString()}.`;
7230
8324
  }
7231
8325
  try {
7232
8326
  await executeStep(page, command2, {
@@ -7322,6 +8416,56 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
7322
8416
  }
7323
8417
  );
7324
8418
  }
8419
+ const missing = (result) => result.kind !== "resolved" && (result.reason === "none" || result.reason === "no_candidates");
8420
+ const actionGraceMs = dependencies.verifyGraceMs ?? 0;
8421
+ if (missing(resolved) && actionGraceMs > 0) {
8422
+ const deadline = performance.now() + actionGraceMs;
8423
+ const earlier = [];
8424
+ while (missing(resolved) && performance.now() < deadline && !dependencies.signal?.aborted) {
8425
+ const before = (resolved.kind !== "resolved" ? resolved.diagnostic.observationVersion : void 0) ?? await pageVersion(page).catch(() => null);
8426
+ let changed = false;
8427
+ while (performance.now() < deadline) {
8428
+ if (dependencies.signal?.aborted) break;
8429
+ const now = await pageVersion(page).catch(() => null);
8430
+ if (!before || !now || now.revision !== before.revision || now.document !== before.document || now.route !== before.route) {
8431
+ changed = true;
8432
+ break;
8433
+ }
8434
+ await new Promise((resolve) => setTimeout(resolve, 200));
8435
+ }
8436
+ if (!changed) break;
8437
+ await quietPage(page, 80, 2e3).catch(() => void 0);
8438
+ earlier.push(...resolved.calls);
8439
+ try {
8440
+ resolved = await locate();
8441
+ } catch (error2) {
8442
+ if (isRunWideProviderError(error2)) {
8443
+ const failedCalls = earlier.map(
8444
+ (call2) => resultCall(call2, "locator")
8445
+ );
8446
+ throw await runWide(error2, { failedCalls });
8447
+ }
8448
+ break;
8449
+ }
8450
+ }
8451
+ if (earlier.length)
8452
+ resolved = { ...resolved, calls: [...earlier, ...resolved.calls] };
8453
+ }
8454
+ if (dependencies.signal?.aborted)
8455
+ return record(
8456
+ unsupported(
8457
+ step.source.file,
8458
+ step.source,
8459
+ "The target could not be resolved because the run was canceled."
8460
+ ),
8461
+ {
8462
+ locator: resolved,
8463
+ error: {
8464
+ code: "canceled",
8465
+ message: "The target could not be resolved because the run was canceled."
8466
+ }
8467
+ }
8468
+ );
7325
8469
  if (resolved.kind !== "resolved") {
7326
8470
  if (resolved.reason === "none" || resolved.reason === "ambiguous" || resolved.reason === "no_candidates")
7327
8471
  return record("failed", {
@@ -7483,7 +8627,7 @@ function unresolvedWhy(resolved, op, visionEnabled) {
7483
8627
  return `${why}; vision fallback could not run (it needs 2 to 40 fully visible, unobscured controls on screen)`;
7484
8628
  return why;
7485
8629
  }
7486
- async function recordGoalAction(page, action, report, repoRoot, source) {
8630
+ async function recordGoalAction(page, action, report, repoRoot, source, group, canceled2 = false) {
7487
8631
  const attempt = report.test.currentAttempt;
7488
8632
  const index = attempt.stepCount + 1;
7489
8633
  const id = `${attempt.id}:step:${index}`;
@@ -7515,9 +8659,10 @@ async function recordGoalAction(page, action, report, repoRoot, source) {
7515
8659
  phase: "steps",
7516
8660
  sentence: safeText(action.sentence, privacy, 512),
7517
8661
  detail: failed ? `Goal action failed: ${action.reason}.` : "Goal action; replay shows the resulting page.",
8662
+ ...group ? { group: group.map((name) => safeText(name, privacy, 120)) } : {},
7518
8663
  sourceStack: [safeSource(source, repoRoot, privacy)],
7519
- state: "completed",
7520
- verdict: action.status,
8664
+ state: canceled2 ? "error" : "completed",
8665
+ verdict: canceled2 ? null : action.status,
7521
8666
  flags: [],
7522
8667
  elapsedMs: action.elapsedMs,
7523
8668
  page: sensitive ? { status: "omitted", reason: "sensitive_page" } : await reportPage(page, `${id}:observation:1`, privacy),
@@ -7545,6 +8690,58 @@ async function recordGoalAction(page, action, report, repoRoot, source) {
7545
8690
  targetBox: null
7546
8691
  });
7547
8692
  }
8693
+ async function goalFailureArtifacts(page, result, report, id) {
8694
+ const privacy = report.privacy;
8695
+ const context = result.failure;
8696
+ const sensitive = safeUrl(page.url, privacy).sensitive || (context ? safeUrl(context.version.route, privacy).sensitive : false);
8697
+ const sameFailureVersion = (version) => !!context && version.document === context.version.document && version.revision === context.version.revision && version.route === context.version.route;
8698
+ const reportedPage = sensitive ? { status: "omitted", reason: "sensitive_page" } : await reportPage(page, `${id}:observation:1`, privacy, context?.version);
8699
+ const capture = async () => {
8700
+ if (sensitive) return { status: "omitted", reason: "sensitive_page" };
8701
+ if (!report.evidenceEnabled)
8702
+ return { status: "omitted", reason: "disabled" };
8703
+ if (!page.captureFrame)
8704
+ return { status: "unavailable", reason: "capture_unavailable" };
8705
+ try {
8706
+ const before = await pageVersion(page);
8707
+ if (!sameFailureVersion(before))
8708
+ return { status: "unavailable", reason: "stale_frame" };
8709
+ if (safeUrl(before.route, privacy).sensitive)
8710
+ return { status: "omitted", reason: "sensitive_page" };
8711
+ const bytes = await page.captureFrame();
8712
+ const after = await pageVersion(page);
8713
+ if (!sameFailureVersion(after))
8714
+ return { status: "unavailable", reason: "stale_frame" };
8715
+ return await report.saveFrame(
8716
+ report.test.currentAttempt,
8717
+ `${id}:evidence`,
8718
+ bytes
8719
+ );
8720
+ } catch {
8721
+ return { status: "unavailable", reason: "capture_failed" };
8722
+ }
8723
+ };
8724
+ return {
8725
+ page: reportedPage,
8726
+ locator: reportedPage.status === "available" && context?.targetName && context.targetRole ? {
8727
+ confidence: context.confidence ?? null,
8728
+ source: "model",
8729
+ cache: null,
8730
+ options: [
8731
+ {
8732
+ label: safeText(context.targetName, privacy, 120),
8733
+ role: safeText(context.targetRole, privacy, 80),
8734
+ probability: context.probability ?? 0
8735
+ }
8736
+ ]
8737
+ } : null,
8738
+ evidence: await capture(),
8739
+ targetBox: null,
8740
+ ...sensitive ? {
8741
+ detail: `The goal stopped on a sensitive page; page and target context were omitted.${context?.generator ? ` The retained synthetic value came from ${context.generator}; its value remains hidden.` : ""}`
8742
+ } : result.detail ? { detail: result.detail } : {}
8743
+ };
8744
+ }
7548
8745
  async function runFlow(file, runDependencies) {
7549
8746
  const absolute = path5.resolve(file);
7550
8747
  const loaded2 = await loadFlowFile(absolute, {
@@ -7749,10 +8946,19 @@ async function runFlow(file, runDependencies) {
7749
8946
  const goalResult = await runGoal(
7750
8947
  activePage,
7751
8948
  {
8949
+ ...dependencies.provider.targetChoiceMinOptions ? {
8950
+ targetChoiceMinOptions: dependencies.provider.targetChoiceMinOptions
8951
+ } : {},
7752
8952
  chooseGoal: (state2, options) => {
7753
8953
  purposes.push("planner");
7754
8954
  return dependencies.provider.chooseGoal(state2, options);
7755
- }
8955
+ },
8956
+ ...dependencies.provider.chooseGoalValue ? {
8957
+ chooseGoalValue: (state2, options) => {
8958
+ purposes.push("planner");
8959
+ return dependencies.provider.chooseGoalValue(state2, options);
8960
+ }
8961
+ } : {}
7756
8962
  },
7757
8963
  {
7758
8964
  holds: (text, digest, options) => {
@@ -7769,6 +8975,14 @@ async function runFlow(file, runDependencies) {
7769
8975
  )
7770
8976
  ],
7771
8977
  data,
8978
+ onGeneratedValue: (value) => {
8979
+ opaqueEntries.push({
8980
+ value,
8981
+ sensitive: true,
8982
+ opaqueValues: [value]
8983
+ });
8984
+ dependencies.report?.privacy.secretValues.push(value.reveal());
8985
+ },
7772
8986
  ...dependencies.report ? {
7773
8987
  onAction: async (action) => {
7774
8988
  await recordGoalAction(
@@ -7790,15 +9004,23 @@ async function runFlow(file, runDependencies) {
7790
9004
  const { test: test2, privacy } = dependencies.report;
7791
9005
  const attempt = test2.currentAttempt;
7792
9006
  const checked = goalResult.verification[0];
9007
+ const id = `${attempt.id}:step:${attempt.stepCount + 1}`;
9008
+ const failureArtifacts = goalResult.status === "failed" && goalResult.failure ? await goalFailureArtifacts(
9009
+ activePage,
9010
+ goalResult,
9011
+ dependencies.report,
9012
+ id
9013
+ ) : void 0;
9014
+ const failureDetail = failureArtifacts?.detail ?? goalResult.detail;
7793
9015
  await test2.addStep({
7794
- id: `${attempt.id}:step:${attempt.stepCount + 1}`,
9016
+ id,
7795
9017
  index: attempt.stepCount + 1,
7796
9018
  kind: "verify",
7797
9019
  operation: "goal",
7798
9020
  phase: "steps",
7799
9021
  sentence: safeText(goal.text, privacy, 512),
7800
9022
  detail: safeText(
7801
- `${goalResult.actions} actions, ${goalResult.requests} requests; ${goalResult.reason}. Verify: ${goal.verify}`,
9023
+ `${goalResult.actions} actions, ${goalResult.requests} requests; ${goalResult.reason}.${failureDetail ? ` ${failureDetail}` : ""} Verify: ${goal.verify}`,
7802
9024
  privacy,
7803
9025
  512
7804
9026
  ),
@@ -7811,8 +9033,11 @@ async function runFlow(file, runDependencies) {
7811
9033
  (flag2) => flag2 === "low_confidence" || flag2 === "contradiction"
7812
9034
  ) ?? [],
7813
9035
  elapsedMs: goalResult.elapsedMs,
7814
- page: { status: "omitted", reason: "goal_summary" },
7815
- locator: null,
9036
+ page: failureArtifacts?.page ?? {
9037
+ status: "omitted",
9038
+ reason: "goal_summary"
9039
+ },
9040
+ locator: failureArtifacts?.locator ?? null,
7816
9041
  judgement: checked ? {
7817
9042
  holds: checked.holds,
7818
9043
  contradicted: checked.contradicted,
@@ -7828,14 +9053,17 @@ async function runFlow(file, runDependencies) {
7828
9053
  error: goalResult.status === "failed" ? {
7829
9054
  code: goalResult.reason,
7830
9055
  message: safeText(
7831
- `Goal did not pass: ${goalResult.reason}.${goalResult.detail ? ` The planner was unsure of the ${goalResult.detail}.` : ""}${goalResult.reason.endsWith("_abstention") ? " Name the page or control for that step in the goal, or split the goal into authored steps around it." : ""}`,
9056
+ `Goal did not pass: ${goalResult.reason}.${failureDetail ? ` ${failureDetail}` : ""}${goalResult.reason.endsWith("_abstention") ? " Name the page or control for that step in the goal, or split the goal into authored steps around it." : ""}`,
7832
9057
  privacy,
7833
9058
  512
7834
9059
  )
7835
9060
  } : null,
7836
- evidence: { status: "omitted", reason: "goal_summary" },
9061
+ evidence: failureArtifacts?.evidence ?? {
9062
+ status: "omitted",
9063
+ reason: "goal_summary"
9064
+ },
7837
9065
  replayFrame: null,
7838
- targetBox: null
9066
+ targetBox: failureArtifacts?.targetBox ?? null
7839
9067
  });
7840
9068
  }
7841
9069
  if (goalResult.status === "failed")
@@ -8165,6 +9393,15 @@ function tokenize(source) {
8165
9393
  index++;
8166
9394
  }
8167
9395
  };
9396
+ const identifierEscape = () => {
9397
+ const escaped = /^\\u(?:\{([0-9A-Fa-f]{1,6})\}|([0-9A-Fa-f]{4}))/u.exec(
9398
+ source.slice(index)
9399
+ );
9400
+ if (!escaped) return void 0;
9401
+ const code = parseInt(escaped[1] ?? escaped[2], 16);
9402
+ if (code > 1114111) return void 0;
9403
+ return { value: String.fromCodePoint(code), length: escaped[0].length };
9404
+ };
8168
9405
  const readQuoted = (quote) => {
8169
9406
  let value = "";
8170
9407
  let dynamic = false;
@@ -8287,11 +9524,20 @@ function tokenize(source) {
8287
9524
  continue;
8288
9525
  }
8289
9526
  }
8290
- if (IDENT_START.test(char)) {
9527
+ const escapedStart = char === "\\" ? identifierEscape() : void 0;
9528
+ if (IDENT_START.test(char) || escapedStart && IDENT_START.test(escapedStart.value)) {
8291
9529
  let value = "";
8292
- while (index < source.length && IDENT_PART.test(source[index])) {
8293
- value += source[index];
8294
- advance();
9530
+ while (index < source.length) {
9531
+ const part = source[index];
9532
+ if (IDENT_PART.test(part)) {
9533
+ value += part;
9534
+ advance();
9535
+ continue;
9536
+ }
9537
+ const escaped = part === "\\" ? identifierEscape() : void 0;
9538
+ if (!escaped || !IDENT_PART.test(escaped.value)) break;
9539
+ value += escaped.value;
9540
+ advance(escaped.length);
8295
9541
  }
8296
9542
  tokens.push({ kind: "ident", value, line: startLine, col: startCol });
8297
9543
  continue;
@@ -8324,6 +9570,13 @@ function scanScriptSentences(source, file) {
8324
9570
  message: "This step sentence is not a literal, so it cannot be checked before a run, and a sentence built from values is classified again for every value.",
8325
9571
  fix: 'Write a literal sentence with {{name}} and pass the value separately: ai("type {{email}} into the Email field", { email }).'
8326
9572
  });
9573
+ const goalDiagnostic = (token, severity, code, message, fix) => warnings.push({
9574
+ severity,
9575
+ code,
9576
+ source: { file, line: token.line, col: token.col },
9577
+ message,
9578
+ fix
9579
+ });
8327
9580
  const TERMINATORS = /* @__PURE__ */ new Set([",", ")", "]", ";"]);
8328
9581
  const skipExpression = (index) => {
8329
9582
  let depth = 0;
@@ -8419,7 +9672,48 @@ function scanScriptSentences(source, file) {
8419
9672
  const next = at2(last + 1);
8420
9673
  return next === void 0 || next.line > at2(last).line && !".[(?".includes(next.value) || next.value === ";" || next.value === "," || next.value === "as" && value(last + 2) === "const";
8421
9674
  };
9675
+ const isDirectGoalValues = (index) => {
9676
+ const open2 = parentOf[index];
9677
+ if (open2 === void 0 || !isPunct(open2, "(")) return false;
9678
+ const member = value(open2 - 1) === "goal" ? open2 - 1 : value(open2 - 1) === "." && value(open2 - 2) === "?" && value(open2 - 3) === "goal" ? open2 - 3 : void 0;
9679
+ if (member === void 0) return false;
9680
+ const receiver = value(member - 1) === "." && value(member - 2) === "?" ? member - 3 : value(member - 1) === "." ? member - 2 : void 0;
9681
+ if (value(receiver ?? -1) !== "ai") return false;
9682
+ const afterGoal = skipExpression(open2 + 1);
9683
+ return isPunct(afterGoal, ",") && index === afterGoal + 1 && skipExpression(index) === index + 1;
9684
+ };
9685
+ const objectKeys = (open2) => {
9686
+ const close = match.get(open2);
9687
+ if (close === void 0) return void 0;
9688
+ const keys = /* @__PURE__ */ new Set();
9689
+ let cursor = open2 + 1;
9690
+ while (cursor < close) {
9691
+ if (isPunct(cursor, ",")) {
9692
+ cursor++;
9693
+ continue;
9694
+ }
9695
+ const key = at2(cursor);
9696
+ if (!key || key.kind !== "ident" && key.kind !== "string" || key.kind === "string" && key.dynamic || isPunct(cursor, "[") || value(cursor) === "." && value(cursor + 1) === "." && value(cursor + 2) === ".")
9697
+ return void 0;
9698
+ const next = cursor + 1;
9699
+ if (isPunct(next, ":")) {
9700
+ if (key.value !== "__proto__") keys.add(key.value);
9701
+ cursor = next + 1;
9702
+ while (cursor < close && !(parentOf[cursor] === open2 && isPunct(cursor, ",")))
9703
+ cursor++;
9704
+ continue;
9705
+ }
9706
+ if (key.kind === "ident" && (cursor + 1 === close || isPunct(cursor + 1, ","))) {
9707
+ keys.add(key.value);
9708
+ cursor++;
9709
+ continue;
9710
+ }
9711
+ return void 0;
9712
+ }
9713
+ return keys;
9714
+ };
8422
9715
  const constants3 = /* @__PURE__ */ new Map();
9716
+ const objectConstants = /* @__PURE__ */ new Map();
8423
9717
  {
8424
9718
  const bindings = /* @__PURE__ */ new Map();
8425
9719
  tokens.forEach((token, index) => {
@@ -8434,6 +9728,11 @@ function scanScriptSentences(source, file) {
8434
9728
  const last = at2(start)?.kind === "string" ? start : isPunct(start, "[") ? match.get(start) : void 0;
8435
9729
  if (last !== void 0 && endsCleanly(last))
8436
9730
  constants3.set(name.value, start);
9731
+ const objectClose = isPunct(start, "{") ? match.get(start) : void 0;
9732
+ if (objectClose !== void 0 && endsCleanly(objectClose) && objectKeys(start) !== void 0 && tokens.every(
9733
+ (candidate, candidateIndex) => candidate.kind !== "ident" || candidate.value !== name.value || candidateIndex === index + 1 || isDirectGoalValues(candidateIndex)
9734
+ ))
9735
+ objectConstants.set(name.value, start);
8437
9736
  });
8438
9737
  }
8439
9738
  const MAX_SENTENCES = 1e4;
@@ -8483,6 +9782,114 @@ function scanScriptSentences(source, file) {
8483
9782
  if (isPunct(first, "[")) list(first);
8484
9783
  else argument(first);
8485
9784
  };
9785
+ const goalCall = (open2, aiToken) => {
9786
+ const first = open2 + 1;
9787
+ if (isPunct(first, ")")) {
9788
+ goalDiagnostic(
9789
+ aiToken,
9790
+ "error",
9791
+ "invalid_goal",
9792
+ "ai.goal requires one nonblank string goal.",
9793
+ 'Write ai.goal("Describe the outcome to achieve").'
9794
+ );
9795
+ return;
9796
+ }
9797
+ const firstToken = at2(first);
9798
+ const end = skipExpression(first);
9799
+ const declared2 = firstToken.kind === "ident" && end === first + 1 ? constants3.get(firstToken.value) : void 0;
9800
+ const literal = firstToken.kind === "string" && end === first + 1 ? firstToken : declared2 !== void 0 && at2(declared2)?.kind === "string" ? at2(declared2) : void 0;
9801
+ let placeholders;
9802
+ if (!literal || literal.kind !== "string" || literal.dynamic) {
9803
+ const provablyNonString = (isPunct(first, "[") || isPunct(first, "{")) && match.get(first) === end - 1 || end === first + 1 && (/^\d/u.test(firstToken.value) || ["null", "true", "false"].includes(firstToken.value));
9804
+ goalDiagnostic(
9805
+ firstToken,
9806
+ provablyNonString ? "error" : "warning",
9807
+ provablyNonString ? "invalid_goal" : "dynamic_goal",
9808
+ provablyNonString ? "ai.goal requires a string, not this statically readable value." : "This goal is built at run time, so its text and placeholders cannot be checked before a run.",
9809
+ 'Pass a literal or a single-use const string to ai.goal("Describe the outcome").'
9810
+ );
9811
+ } else if (!literal.value.trim()) {
9812
+ goalDiagnostic(
9813
+ literal,
9814
+ "error",
9815
+ "invalid_goal",
9816
+ "ai.goal cannot be blank.",
9817
+ "Describe the outcome the planner should achieve."
9818
+ );
9819
+ } else {
9820
+ const tokenized = tokenizeStep(literal.value);
9821
+ placeholders = new Set(
9822
+ tokenized.tokens.flatMap(
9823
+ (token) => token.kind === "placeholder" && token.key ? [token.key] : []
9824
+ )
9825
+ );
9826
+ for (const problem of tokenized.problems) {
9827
+ if (problem.code !== "invalid_placeholder") continue;
9828
+ goalDiagnostic(
9829
+ literal,
9830
+ "error",
9831
+ problem.code,
9832
+ problem.message,
9833
+ problem.fix
9834
+ );
9835
+ }
9836
+ }
9837
+ if (!isPunct(end, ",")) return;
9838
+ const valuesIndex = end + 1;
9839
+ if (isPunct(valuesIndex, ")")) return;
9840
+ const valuesToken = at2(valuesIndex);
9841
+ const afterValues = skipExpression(valuesIndex);
9842
+ const objectIndex = isPunct(valuesIndex, "{") && match.get(valuesIndex) === afterValues - 1 ? valuesIndex : valuesToken?.kind === "ident" && afterValues === valuesIndex + 1 ? objectConstants.get(valuesToken.value) : void 0;
9843
+ const keys = objectIndex === void 0 ? void 0 : objectKeys(objectIndex);
9844
+ const readableObject = keys !== void 0;
9845
+ const invalidValues = isPunct(valuesIndex, "[") && match.get(valuesIndex) === afterValues - 1 || afterValues === valuesIndex + 1 && (valuesToken?.kind === "string" || /^(?:\d|null$|true$|false$)/u.test(valuesToken?.value ?? ""));
9846
+ if (invalidValues)
9847
+ goalDiagnostic(
9848
+ valuesToken ?? aiToken,
9849
+ "error",
9850
+ "invalid_goal_values",
9851
+ "ai.goal values must be an object when supplied.",
9852
+ "Pass values as { name: value }, or omit the second argument."
9853
+ );
9854
+ else if (!readableObject && valuesToken?.value !== "undefined")
9855
+ goalDiagnostic(
9856
+ valuesToken ?? aiToken,
9857
+ "warning",
9858
+ "dynamic_goal_values",
9859
+ "These values are built at run time and will be validated when the goal runs.",
9860
+ "Use a plain object with statically named properties where practical."
9861
+ );
9862
+ else if (readableObject && placeholders) {
9863
+ for (const placeholder of placeholders)
9864
+ if (!keys.has(placeholder))
9865
+ goalDiagnostic(
9866
+ literal ?? aiToken,
9867
+ "error",
9868
+ "missing_value",
9869
+ `{{${placeholder}}} has no value.`,
9870
+ "Pass its value as the second argument to ai.goal."
9871
+ );
9872
+ }
9873
+ if (!isPunct(afterValues, ",") || isPunct(afterValues + 1, ")")) return;
9874
+ const optionsIndex = afterValues + 1;
9875
+ const afterOptions = skipExpression(optionsIndex);
9876
+ if (!isPunct(optionsIndex, "{") && value(optionsIndex) !== "undefined")
9877
+ goalDiagnostic(
9878
+ at2(optionsIndex),
9879
+ "warning",
9880
+ "dynamic_goal_options",
9881
+ "These goal options will be validated at run time.",
9882
+ "Pass { generateData: false } to disable automatic data generation."
9883
+ );
9884
+ if (isPunct(afterOptions, ",") && !isPunct(afterOptions + 1, ")"))
9885
+ goalDiagnostic(
9886
+ at2(afterOptions),
9887
+ "error",
9888
+ "invalid_goal",
9889
+ "ai.goal accepts at most a goal, values, and options object.",
9890
+ "Remove the extra argument."
9891
+ );
9892
+ };
8486
9893
  const inlineFunction = (index) => {
8487
9894
  let cursor = index;
8488
9895
  if (value(cursor) === "async") cursor++;
@@ -8701,6 +10108,63 @@ function scanScriptSentences(source, file) {
8701
10108
  call2(index + 1);
8702
10109
  continue;
8703
10110
  }
10111
+ const member = isPunct(index + 1, ".") ? index + 2 : isPunct(index + 1, "?") && isPunct(index + 2, ".") ? index + 3 : void 0;
10112
+ let holdsOpen;
10113
+ if (member !== void 0 && at2(member)?.kind === "ident" && at2(member).value === "holds") {
10114
+ const after = member + 1;
10115
+ if (isPunct(after, "(")) holdsOpen = after;
10116
+ else if (isPunct(after, "?") && isPunct(after + 1, ".") && isPunct(after + 2, "("))
10117
+ holdsOpen = after + 2;
10118
+ }
10119
+ if (holdsOpen !== void 0) {
10120
+ const first = holdsOpen + 1;
10121
+ const firstToken = at2(first);
10122
+ const declared2 = firstToken?.kind === "ident" ? constants3.get(firstToken.value) : void 0;
10123
+ if (isPunct(first, ")") || isPunct(first, "[") || declared2 !== void 0 && isPunct(declared2, "[")) {
10124
+ unchecked(
10125
+ token,
10126
+ "ai.holds requires one string claim, so this value is not checked before a run."
10127
+ );
10128
+ continue;
10129
+ }
10130
+ const afterClaim = skipExpression(first);
10131
+ if (isPunct(afterClaim, ",")) {
10132
+ const valuesIndex = afterClaim + 1;
10133
+ const values = at2(valuesIndex);
10134
+ const afterValues = skipExpression(valuesIndex);
10135
+ const validValues = isPunct(valuesIndex, "{") || values?.kind === "ident" && values.value !== "null";
10136
+ if (!validValues || isPunct(afterValues, ",")) {
10137
+ unchecked(
10138
+ token,
10139
+ "This ai.holds call has invalid or extra arguments, so its claim is not checked before a run."
10140
+ );
10141
+ continue;
10142
+ }
10143
+ }
10144
+ const before = sentences.length;
10145
+ call2(holdsOpen);
10146
+ for (let found = before; found < sentences.length; found++)
10147
+ sentences[found] = { ...sentences[found], check: true };
10148
+ continue;
10149
+ }
10150
+ if (member !== void 0 && at2(member)?.kind === "ident" && at2(member).value === "goal") {
10151
+ const after = member + 1;
10152
+ const open2 = isPunct(after, "(") ? after : isPunct(after, "?") && isPunct(after + 1, ".") && isPunct(after + 2, "(") ? after + 2 : void 0;
10153
+ if (open2 === void 0)
10154
+ unchecked(
10155
+ token,
10156
+ "This ai.goal use is indirect, so its goal cannot be checked before a run."
10157
+ );
10158
+ else goalCall(open2, token);
10159
+ continue;
10160
+ }
10161
+ if (member !== void 0 && at2(member)?.kind === "ident" && at2(member).value === "holds") {
10162
+ unchecked(
10163
+ token,
10164
+ "This ai.holds call is written indirectly, so its claim is not checked before a run."
10165
+ );
10166
+ continue;
10167
+ }
8704
10168
  if (isPunct(index + 1, ".") && at2(index + 2)?.kind === "ident" && at2(index + 2).value === "group" && isPunct(index + 3, "(")) {
8705
10169
  const afterName = skipExpression(index + 4);
8706
10170
  if (!isPunct(afterName, ",")) continue;
@@ -8830,6 +10294,31 @@ function dedupeDiagnostics(diagnostics) {
8830
10294
  function directSentences(steps) {
8831
10295
  return steps.filter((step) => step.kind === "sentence");
8832
10296
  }
10297
+ function checkDiagnostics(item) {
10298
+ const tokenized = tokenizeStep(item.text);
10299
+ if (tokenized.problems.length)
10300
+ return tokenized.problems.map((problem) => ({
10301
+ severity: "error",
10302
+ code: problem.code,
10303
+ source: item.source,
10304
+ message: problem.message,
10305
+ fix: problem.fix
10306
+ }));
10307
+ const text = canonicalSentence(item.text);
10308
+ const operation = patternOperation(text);
10309
+ const preflight = preflightSentence(text);
10310
+ if (!text || preflight !== null && preflight !== "unsupported" || WAIT_UNTIL.test(text) || operation !== null && operation !== "verify" || !isClaimSentence(text))
10311
+ return [
10312
+ {
10313
+ severity: "error",
10314
+ code: "invalid_check",
10315
+ source: item.source,
10316
+ message: "ai.holds takes one claim about the page.",
10317
+ fix: 'Write ai.holds("the passkey screen is shown").'
10318
+ }
10319
+ ];
10320
+ return [];
10321
+ }
8833
10322
  function entryUrlDiagnostic(flow, baseUrl) {
8834
10323
  try {
8835
10324
  resolveEntryUrl(flow.url, baseUrl ?? void 0);
@@ -8911,7 +10400,8 @@ async function validateScriptFile(file, options, classify) {
8911
10400
  fix: "Keep shared steps in fewer modules."
8912
10401
  });
8913
10402
  diagnostics.push(...warnings);
8914
- const sentences = scans.flatMap((scan) => scan.sentences).map((item) => ({
10403
+ const scanned = scans.flatMap((scan) => scan.sentences);
10404
+ const sentences = scanned.filter((item) => !item.check).map((item) => ({
8915
10405
  kind: "sentence",
8916
10406
  phase: "steps",
8917
10407
  text: item.text,
@@ -8920,7 +10410,9 @@ async function validateScriptFile(file, options, classify) {
8920
10410
  }));
8921
10411
  const checked = await classifySentenceSteps(sentences, classify);
8922
10412
  diagnostics.push(...checked.diagnostics);
8923
- const complete = checked.classification.steps.every((step) => step !== null) && checked.diagnostics.length === 0 && warnings.length === 0;
10413
+ const invalidChecks = scanned.filter((item) => item.check).flatMap(checkDiagnostics);
10414
+ diagnostics.push(...invalidChecks);
10415
+ const complete = checked.classification.steps.every((step) => step !== null) && checked.diagnostics.length === 0 && invalidChecks.length === 0 && warnings.length === 0;
8924
10416
  return {
8925
10417
  headers,
8926
10418
  diagnostics,
@@ -8935,13 +10427,13 @@ async function validateScriptFile(file, options, classify) {
8935
10427
  var HELPER_EXTENSIONS = [".ts", ".mts", ".cts", ".tsx", ".js", ".mjs"];
8936
10428
  var MAX_HELPERS = 64;
8937
10429
  function resolveHelper(from, specifier) {
8938
- const base = path7.resolve(path7.dirname(from), specifier);
8939
- const stem = base.replace(/\.(?:m|c)?js$/u, "");
10430
+ const base2 = path7.resolve(path7.dirname(from), specifier);
10431
+ const stem = base2.replace(/\.(?:m|c)?js$/u, "");
8940
10432
  const candidates = [
8941
- base,
10433
+ base2,
8942
10434
  ...HELPER_EXTENSIONS.map((extension) => stem + extension),
8943
10435
  ...HELPER_EXTENSIONS.map(
8944
- (extension) => path7.join(base, `index${extension}`)
10436
+ (extension) => path7.join(base2, `index${extension}`)
8945
10437
  )
8946
10438
  ];
8947
10439
  return candidates.find(
@@ -9511,6 +11003,7 @@ async function runScriptTest(file, identity, runDependencies) {
9511
11003
  );
9512
11004
  const opaqueEntries = [];
9513
11005
  let firstProblem = null;
11006
+ let goalStarted = false;
9514
11007
  let inFlight = null;
9515
11008
  const outstanding = /* @__PURE__ */ new Set();
9516
11009
  const rejected = [];
@@ -9604,12 +11097,14 @@ async function runScriptTest(file, identity, runDependencies) {
9604
11097
  } catch (error2) {
9605
11098
  return stop(runtimeFailure(absolute, error2));
9606
11099
  }
9607
- if (outcome === "continue") return;
11100
+ if (outcome === "continue") return true;
11101
+ if (outcome === "failed" && presentation.check) return false;
9608
11102
  if (outcome === "failed")
9609
11103
  stop({ status: "failed", file: absolute, source: step.source });
9610
11104
  else if (outcome.status !== "passed") stop(outcome);
11105
+ return true;
9611
11106
  };
9612
- const sentence = async (text, values, source2) => {
11107
+ const sentence = async (text, values, source2, check = false) => {
9613
11108
  try {
9614
11109
  if (typeof text !== "string" || !text.trim())
9615
11110
  throw new ScriptUsageError(
@@ -9646,6 +11141,12 @@ async function runScriptTest(file, identity, runDependencies) {
9646
11141
  )
9647
11142
  );
9648
11143
  const classified = checked.classification.steps[0];
11144
+ if (check && classified && (classified.op !== "verify" || WAIT_UNTIL.test(text)))
11145
+ throw new ScriptUsageError(
11146
+ "invalid_check",
11147
+ "ai.holds takes one claim about the page.",
11148
+ 'Write ai.holds("the passkey screen is shown").'
11149
+ );
9649
11150
  if (checked.diagnostics.length || !classified) {
9650
11151
  const diagnostic3 = checked.diagnostics[0];
9651
11152
  stop({
@@ -9671,7 +11172,7 @@ async function runScriptTest(file, identity, runDependencies) {
9671
11172
  inlineValues(template, classified.op, own),
9672
11173
  source2
9673
11174
  );
9674
- await runStep(
11175
+ const held = await runStep(
9675
11176
  {
9676
11177
  ...shown,
9677
11178
  op: classified.op,
@@ -9679,10 +11180,11 @@ async function runScriptTest(file, identity, runDependencies) {
9679
11180
  probability: classified.probability
9680
11181
  },
9681
11182
  scope,
9682
- { group: [...groups] }
11183
+ { group: [...groups], ...check ? { check: true } : {} }
9683
11184
  );
9684
11185
  for (const [key, entry] of Object.entries(scope))
9685
11186
  if (!(key in own) && !(key in bindings)) bindings[key] = entry;
11187
+ return held;
9686
11188
  } catch (error2) {
9687
11189
  if (error2 instanceof ScriptUsageError) usage(error2, source2);
9688
11190
  throw error2;
@@ -9703,6 +11205,11 @@ async function runScriptTest(file, identity, runDependencies) {
9703
11205
  await exclusive(source2, () => sentence(item, values, source2));
9704
11206
  } else await exclusive(source2, () => sentence(input, values, source2));
9705
11207
  };
11208
+ const holds = (claim2, values, source2) => (
11209
+ // Classify the caller's words before treating them as a check. Prefixing
11210
+ // `verify` would turn an action into a claim and make it look read-only.
11211
+ exclusive(source2, () => sentence(claim2, values, source2, true))
11212
+ );
9706
11213
  const track = (work) => {
9707
11214
  const step = new StepPromise(
9708
11215
  (resolve, reject) => work.then(resolve, reject)
@@ -9719,6 +11226,177 @@ async function runScriptTest(file, identity, runDependencies) {
9719
11226
  return step;
9720
11227
  };
9721
11228
  const ai = ((input, values) => track(sentences(input, values, where(new Error().stack))));
11229
+ const goal = async (text, values, source2, options) => {
11230
+ try {
11231
+ if (options !== void 0 && (options === null || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "generateData") || options.generateData !== void 0 && typeof options.generateData !== "boolean"))
11232
+ throw new ScriptUsageError(
11233
+ "invalid_goal_options",
11234
+ "Goal options must be an object with an optional boolean generateData.",
11235
+ "Pass { generateData: false } to disable automatic data generation."
11236
+ );
11237
+ if (typeof text !== "string" || !text.trim())
11238
+ throw new ScriptUsageError(
11239
+ "invalid_goal",
11240
+ "A goal must be a nonblank string.",
11241
+ 'Write ai.goal("Complete the profile").'
11242
+ );
11243
+ const own = valueEntries(values);
11244
+ const scope = { ...bindings, ...own };
11245
+ const tokens = tokenizeStep(text);
11246
+ const problem = tokens.problems[0];
11247
+ if (problem)
11248
+ throw new ScriptUsageError(
11249
+ problem.code,
11250
+ problem.message,
11251
+ problem.fix
11252
+ );
11253
+ for (const token of tokens.tokens)
11254
+ if (token.kind === "placeholder" && !Object.hasOwn(scope, token.key))
11255
+ throw new ScriptUsageError(
11256
+ "missing_value",
11257
+ `{{${token.key}}} has no value.`,
11258
+ "Pass its value as the second argument to ai.goal."
11259
+ );
11260
+ if (!dependencies.provider.chooseGoal)
11261
+ stop({
11262
+ status: "could_not_run",
11263
+ file: absolute,
11264
+ code: "unsupported",
11265
+ source: source2,
11266
+ message: "The configured provider does not support goal planning."
11267
+ });
11268
+ const register = (entry) => {
11269
+ opaqueEntries.push(entry);
11270
+ report?.privacy.secretValues.push(entry.value.reveal());
11271
+ };
11272
+ for (const entry of Object.values(own))
11273
+ if (entry.sensitive) register(entry);
11274
+ goalStarted = true;
11275
+ let reportedCalls = 0;
11276
+ let operationalError;
11277
+ const providerFailure2 = (error2) => {
11278
+ if (isRunWideProviderError(error2)) operationalError = error2;
11279
+ throw error2;
11280
+ };
11281
+ const result = await runGoalTask(
11282
+ activePage,
11283
+ {
11284
+ ...dependencies.provider.targetChoiceMinOptions ? {
11285
+ targetChoiceMinOptions: dependencies.provider.targetChoiceMinOptions
11286
+ } : {},
11287
+ chooseGoal: (state2, options2) => dependencies.provider.chooseGoal(state2, options2).catch(
11288
+ providerFailure2
11289
+ ),
11290
+ ...options?.generateData !== false && dependencies.provider.chooseGoalValue ? {
11291
+ chooseGoalValue: (state2, options2) => dependencies.provider.chooseGoalValue(
11292
+ state2,
11293
+ options2
11294
+ ).catch(providerFailure2)
11295
+ } : {}
11296
+ },
11297
+ {
11298
+ goal: text,
11299
+ data: scope,
11300
+ opaqueEntries,
11301
+ ...dependencies.signal ? { signal: dependencies.signal } : {},
11302
+ onGeneratedValue: (value) => register({ value, sensitive: true, opaqueValues: [value] }),
11303
+ ...report ? {
11304
+ onAction: async (action) => {
11305
+ await recordGoalAction(
11306
+ activePage,
11307
+ action,
11308
+ report,
11309
+ dependencies.repoRoot,
11310
+ source2,
11311
+ groups,
11312
+ action.status === "failed" && dependencies.signal?.aborted
11313
+ );
11314
+ reportedCalls += action.calls.length;
11315
+ }
11316
+ } : {}
11317
+ }
11318
+ );
11319
+ const operational = dependencies.signal?.aborted ? {
11320
+ status: "could_not_run",
11321
+ file: absolute,
11322
+ code: "canceled",
11323
+ source: source2,
11324
+ message: "The run was interrupted."
11325
+ } : operationalError ? runtimeFailure(absolute, operationalError) : void 0;
11326
+ if (report) {
11327
+ const attempt = report.test.currentAttempt;
11328
+ const index = attempt.stepCount + 1;
11329
+ const shown = safeText(text, report.privacy, Number.MAX_SAFE_INTEGER);
11330
+ const id = `${attempt.id}:step:${index}`;
11331
+ const failureArtifacts = result.status === "failed" && result.failure ? await goalFailureArtifacts(activePage, result, report, id) : void 0;
11332
+ const failureDetail = failureArtifacts?.detail ?? result.detail;
11333
+ const detail = result.status === "passed" ? "Planner reported completion; verify the outcome separately." : `Goal did not complete: ${result.reason}.${failureDetail ? ` ${failureDetail}` : ""}`;
11334
+ await report.test.addStep({
11335
+ id,
11336
+ index,
11337
+ kind: "action",
11338
+ operation: "goal",
11339
+ phase: "steps",
11340
+ sentence: safeText(text, report.privacy, 512),
11341
+ detail: safeText(
11342
+ `${detail} ${result.actions} actions, ${result.requests} requests.`,
11343
+ report.privacy,
11344
+ 512
11345
+ ),
11346
+ group: groups.map((name) => safeText(name, report.privacy, 120)),
11347
+ goal: {
11348
+ completion: "planner",
11349
+ text: shown,
11350
+ actions: result.actions,
11351
+ requests: result.requests,
11352
+ reason: result.reason,
11353
+ ...result.dataSeed === void 0 ? {} : { dataSeed: result.dataSeed }
11354
+ },
11355
+ sourceStack: [
11356
+ safeSource(source2, dependencies.repoRoot, report.privacy)
11357
+ ],
11358
+ state: operational ? "error" : "completed",
11359
+ verdict: operational ? null : result.status,
11360
+ flags: [],
11361
+ elapsedMs: result.elapsedMs,
11362
+ page: failureArtifacts?.page ?? {
11363
+ status: "omitted",
11364
+ reason: "goal_summary"
11365
+ },
11366
+ locator: failureArtifacts?.locator ?? null,
11367
+ judgement: null,
11368
+ observations: [],
11369
+ calls: result.calls.slice(reportedCalls).map((call2) => resultCall(call2, "planner")),
11370
+ error: operational?.status === "could_not_run" ? {
11371
+ code: operational.code,
11372
+ message: safeText(operational.message, report.privacy, 512)
11373
+ } : result.status === "passed" ? null : {
11374
+ code: result.reason,
11375
+ message: safeText(detail, report.privacy, 512)
11376
+ },
11377
+ evidence: failureArtifacts?.evidence ?? {
11378
+ status: "omitted",
11379
+ reason: "goal_summary"
11380
+ },
11381
+ replayFrame: null,
11382
+ targetBox: failureArtifacts?.targetBox ?? null
11383
+ });
11384
+ }
11385
+ if (operational) stop(operational);
11386
+ if (result.status === "failed")
11387
+ stop({ status: "failed", file: absolute, source: source2, retryable: false });
11388
+ } catch (error2) {
11389
+ if (error2 instanceof ScriptUsageError) usage(error2, source2);
11390
+ if (isStepStop(error2)) throw error2;
11391
+ stop(runtimeFailure(absolute, error2));
11392
+ }
11393
+ };
11394
+ ai.goal = (text, values, options) => {
11395
+ const source2 = where(new Error().stack);
11396
+ return track(
11397
+ exclusive(source2, () => goal(text, values, source2, options))
11398
+ );
11399
+ };
9722
11400
  const group = async (name, body, values, source2) => {
9723
11401
  if (finished)
9724
11402
  usage(
@@ -9804,6 +11482,7 @@ async function runScriptTest(file, identity, runDependencies) {
9804
11482
  });
9805
11483
  return parser ? parser.parse(text) : text;
9806
11484
  };
11485
+ ai.holds = ((claim2, values) => track(holds(claim2, values, where(new Error().stack))));
9807
11486
  ai.extract = ((description, parser) => track(
9808
11487
  extract(description, parser, where(new Error().stack))
9809
11488
  ));
@@ -9897,9 +11576,10 @@ async function runScriptTest(file, identity, runDependencies) {
9897
11576
  return { status: "passed", file: absolute };
9898
11577
  }
9899
11578
  if (primary.status === "failed") await report?.test.finishTest("failed");
9900
- return primary;
11579
+ return primary.status === "failed" && goalStarted ? { ...primary, retryable: false } : primary;
9901
11580
  } catch (error2) {
9902
- if (isStepStop(error2)) return error2.problem;
11581
+ if (isStepStop(error2))
11582
+ return error2.problem.status === "failed" && goalStarted ? { ...error2.problem, retryable: false } : error2.problem;
9903
11583
  return runtimeFailure(absolute, error2);
9904
11584
  } finally {
9905
11585
  finished = true;
@@ -9964,6 +11644,7 @@ async function recordCodeFailure(page, dependencies, source, error2, group) {
9964
11644
  export {
9965
11645
  ACCEPTANCE_POLICY_VERSION,
9966
11646
  AssertionEngineError,
11647
+ BACKOFF_JITTER,
9967
11648
  BrowserDriverError,
9968
11649
  CACHE_FORMAT,
9969
11650
  CANDIDATE_LIMIT,
@@ -9972,12 +11653,18 @@ export {
9972
11653
  DEFAULT_BAND,
9973
11654
  DEFAULT_CONTRADICTION_CUTOFF,
9974
11655
  DEFAULT_MIN_P,
11656
+ DEFAULT_PROVIDER_CONCURRENCY,
9975
11657
  DEFAULT_VISION_MODEL,
9976
11658
  DIGEST_LIMIT,
9977
11659
  DataResolutionError,
9978
11660
  FileClassificationCache,
11661
+ GOAL_NO_MATCH,
11662
+ GateAborted,
11663
+ GateWaitExceeded,
9979
11664
  LocatorCacheConflict,
9980
11665
  MATCHER_VERSION,
11666
+ MAX_COOLDOWN_MS,
11667
+ MAX_PROVIDER_CONCURRENCY,
9981
11668
  MIN_MODEL_MARGIN,
9982
11669
  MIN_MODEL_PROBABILITY,
9983
11670
  MODEL_CHOICES,
@@ -9994,6 +11681,8 @@ export {
9994
11681
  PageScriptError,
9995
11682
  PlaywrightBrowserDriver,
9996
11683
  ProviderError,
11684
+ ProviderGate,
11685
+ RATE_LIMIT_BUDGET_MS,
9997
11686
  RejectionRouter,
9998
11687
  ResolvedStepTarget,
9999
11688
  ResultAttemptSchema,
@@ -10022,7 +11711,9 @@ export {
10022
11711
  TestRecording,
10023
11712
  VISION_PROMPT,
10024
11713
  VisionRequestError,
11714
+ WAIT_UNTIL,
10025
11715
  attributeRejection,
11716
+ backoffDelay,
10026
11717
  callExtent,
10027
11718
  canonicalSentence,
10028
11719
  captureVisionObservation,
@@ -10037,6 +11728,8 @@ export {
10037
11728
  codePoints,
10038
11729
  collectCandidates,
10039
11730
  compareDiagnostics3 as compareDiagnostics,
11731
+ controlState,
11732
+ cooldownDelay,
10040
11733
  dedupeDiagnostics,
10041
11734
  describeRejection,
10042
11735
  discoverFlowFiles,
@@ -10051,9 +11744,11 @@ export {
10051
11744
  firstDiagnostic,
10052
11745
  formatFlowDiagnostic,
10053
11746
  goalChoiceAccepted,
11747
+ goalFailureArtifacts,
10054
11748
  goalOperations,
10055
11749
  inlineValues,
10056
11750
  installChromium,
11751
+ isClaimSentence,
10057
11752
  isFlowScalar,
10058
11753
  isFullyValidated,
10059
11754
  isRunWideProviderError,
@@ -10071,6 +11766,7 @@ export {
10071
11766
  matchLiveEntry,
10072
11767
  measure,
10073
11768
  navigationWhy,
11769
+ nextConcurrency,
10074
11770
  normalizeSignal,
10075
11771
  opaqueMatches,
10076
11772
  pageDigest,
@@ -10080,6 +11776,7 @@ export {
10080
11776
  parseFlow,
10081
11777
  parseFrame,
10082
11778
  parseModule,
11779
+ parseRetryAfter,
10083
11780
  pathKey,
10084
11781
  patternOperation,
10085
11782
  preflightSentence,
@@ -10088,6 +11785,7 @@ export {
10088
11785
  projectDigest,
10089
11786
  quietPage,
10090
11787
  readTarget,
11788
+ recordGoalAction,
10091
11789
  redactOpaqueText,
10092
11790
  reportPage,
10093
11791
  resolveData,
@@ -10129,6 +11827,7 @@ export {
10129
11827
  validateTypeOperand,
10130
11828
  valueEntries,
10131
11829
  verify,
11830
+ visibleText,
10132
11831
  visualCandidates,
10133
11832
  walkSuiteFiles
10134
11833
  };