@sedum-dev/core 0.1.0-alpha.7 → 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(),
@@ -1601,6 +1611,7 @@ var PlaywrightPage = class {
1601
1611
  aim
1602
1612
  ).catch(() => ({ actionable: false, reason: "stale" }));
1603
1613
  if (!checked.actionable) return checked;
1614
+ let dispatchAim = checked.aim;
1604
1615
  const handle = await this.page.evaluateHandle((ref) => {
1605
1616
  const matches = [];
1606
1617
  const roots = [document];
@@ -1630,32 +1641,50 @@ var PlaywrightPage = class {
1630
1641
  { expected: aim, element }
1631
1642
  );
1632
1643
  if (aim.hover) {
1633
- const box = await element.boundingBox().catch(() => null);
1634
- if (!box) return { actionable: false, reason: "not_actionable" };
1635
- await this.page.mouse.move(box.x + aim.point.x, box.y + aim.point.y);
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
+ }
1636
1653
  try {
1654
+ await hoverElement.hover({ timeout: remaining() });
1637
1655
  await element.waitForElementState("visible", {
1638
1656
  timeout: Math.min(2e3, remaining())
1639
1657
  });
1640
- } catch {
1641
- return { actionable: false, reason: "not_actionable" };
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);
1642
1667
  }
1643
1668
  }
1644
1669
  const still = await validateElement().catch(() => ({
1645
1670
  actionable: false,
1646
1671
  reason: "stale"
1647
1672
  }));
1648
- 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;
1649
1676
  try {
1650
1677
  await element.waitForElementState("stable", { timeout: remaining() });
1651
1678
  } catch {
1652
- return { actionable: false, reason: "not_actionable" };
1679
+ return aim.hover ? { actionable: false, reason: "action_started", retryable: false } : { actionable: false, reason: "not_actionable" };
1653
1680
  }
1654
1681
  const ready = await validateElement().catch(() => ({
1655
1682
  actionable: false,
1656
1683
  reason: "stale"
1657
1684
  }));
1658
- 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;
1659
1688
  if (options.chooseOption) {
1660
1689
  const native = await element.evaluate(
1661
1690
  (node) => node instanceof HTMLSelectElement && !node.multiple ? Array.from(node.options).map((option) => ({
@@ -1668,14 +1697,31 @@ var PlaywrightPage = class {
1668
1697
  native.map((option) => option.label)
1669
1698
  );
1670
1699
  const index = native.findIndex((option) => option.label === label);
1671
- 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
+ };
1672
1707
  return {
1673
1708
  actionable: false,
1674
1709
  reason: "option_not_named",
1675
1710
  options: native.filter((option) => !option.disabled).map((option) => option.label)
1676
1711
  };
1677
- if (native[index].disabled)
1678
- 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
+ }
1679
1725
  const hide2 = await this.highlight(element);
1680
1726
  try {
1681
1727
  await element.selectOption({ index }, { timeout: remaining() });
@@ -1694,8 +1740,11 @@ var PlaywrightPage = class {
1694
1740
  }
1695
1741
  const hide = await this.highlight(element);
1696
1742
  try {
1697
- await element.click({ position: aim.point, timeout: remaining() });
1698
- return { actionable: true, aim };
1743
+ await element.click({
1744
+ position: dispatchAim.point,
1745
+ timeout: remaining()
1746
+ });
1747
+ return { actionable: true, aim: dispatchAim };
1699
1748
  } catch (error2) {
1700
1749
  return {
1701
1750
  actionable: false,
@@ -2377,6 +2426,157 @@ function unknownCostCall(error2) {
2377
2426
  };
2378
2427
  }
2379
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
+
2380
2580
  // src/vision.ts
2381
2581
  import { z as z2 } from "zod";
2382
2582
  var DEFAULT_VISION_MODEL = "google/gemini-3.8-flash";
@@ -5334,9 +5534,38 @@ var GERUND_SECOND_ACTION = /^(?:clicking|typing|entering|filling|pressing|scroll
5334
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;
5335
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";
5336
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;
5337
5542
  function canonicalSentence(sentence) {
5338
5543
  return sentence.normalize("NFC").replace(/\s+/gu, " ").trim();
5339
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
+ }
5340
5569
  function withoutQuotes(sentence) {
5341
5570
  return sentence.replace(/"[^"]*"|'[^']*'/gu, '""');
5342
5571
  }
@@ -5657,6 +5886,9 @@ var KEY_DOMAIN = "sedum-classification-v1\0";
5657
5886
  function classificationKey(sentence) {
5658
5887
  return createHash("sha256").update(KEY_DOMAIN).update(canonicalSentence(sentence)).digest("hex");
5659
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
+ }
5660
5892
  function validEntry2(value) {
5661
5893
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
5662
5894
  const entry = value;
@@ -5671,26 +5903,31 @@ function validEntry2(value) {
5671
5903
  return decision.accepted;
5672
5904
  }
5673
5905
  var FileClassificationCache = class _FileClassificationCache {
5674
- constructor(path11, requestedModel, entries, loadReason, invalidKeys) {
5906
+ constructor(path11, requestedModel, provider, entries, loadReason, invalidKeys) {
5675
5907
  this.path = path11;
5676
5908
  this.requestedModel = requestedModel;
5909
+ this.provider = provider;
5677
5910
  this.loadReason = loadReason;
5678
5911
  this.invalidKeys = invalidKeys;
5679
5912
  this.entries = entries;
5680
5913
  }
5681
5914
  path;
5682
5915
  requestedModel;
5916
+ provider;
5683
5917
  loadReason;
5684
5918
  invalidKeys;
5685
5919
  entries;
5686
5920
  dirty = false;
5687
- 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");
5688
5924
  try {
5689
5925
  const value = JSON.parse(await fs.readFile(path11, "utf8"));
5690
5926
  if (!value || typeof value !== "object" || Array.isArray(value))
5691
5927
  return new _FileClassificationCache(
5692
5928
  path11,
5693
5929
  requestedModel,
5930
+ provider,
5694
5931
  {},
5695
5932
  "corrupt",
5696
5933
  {}
@@ -5700,6 +5937,7 @@ var FileClassificationCache = class _FileClassificationCache {
5700
5937
  return new _FileClassificationCache(
5701
5938
  path11,
5702
5939
  requestedModel,
5940
+ provider,
5703
5941
  {},
5704
5942
  "format_mismatch",
5705
5943
  {}
@@ -5708,6 +5946,7 @@ var FileClassificationCache = class _FileClassificationCache {
5708
5946
  return new _FileClassificationCache(
5709
5947
  path11,
5710
5948
  requestedModel,
5949
+ provider,
5711
5950
  {},
5712
5951
  "corrupt",
5713
5952
  {}
@@ -5722,6 +5961,7 @@ var FileClassificationCache = class _FileClassificationCache {
5722
5961
  return new _FileClassificationCache(
5723
5962
  path11,
5724
5963
  requestedModel,
5964
+ provider,
5725
5965
  entries,
5726
5966
  "ok",
5727
5967
  invalidKeys
@@ -5731,6 +5971,7 @@ var FileClassificationCache = class _FileClassificationCache {
5731
5971
  return new _FileClassificationCache(
5732
5972
  path11,
5733
5973
  requestedModel,
5974
+ provider,
5734
5975
  {},
5735
5976
  "absent",
5736
5977
  {}
@@ -5738,6 +5979,7 @@ var FileClassificationCache = class _FileClassificationCache {
5738
5979
  return new _FileClassificationCache(
5739
5980
  path11,
5740
5981
  requestedModel,
5982
+ provider,
5741
5983
  {},
5742
5984
  "corrupt",
5743
5985
  {}
@@ -5745,14 +5987,17 @@ var FileClassificationCache = class _FileClassificationCache {
5745
5987
  }
5746
5988
  }
5747
5989
  get(sentence) {
5748
- const entry = this.entries[classificationKey(sentence)];
5990
+ const key = providerClassificationKey(this.provider, sentence);
5991
+ const entry = this.entries[key];
5749
5992
  if (!entry)
5750
5993
  return {
5751
5994
  answer: null,
5752
- reason: this.invalidKeys[classificationKey(sentence)] ?? (this.loadReason === "ok" ? "absent" : this.loadReason)
5995
+ reason: this.invalidKeys[key] ?? (this.loadReason === "ok" ? "absent" : this.loadReason)
5753
5996
  };
5754
5997
  if (entry.requestedModel !== this.requestedModel)
5755
5998
  return { answer: null, reason: "model_mismatch" };
5999
+ if ((entry.provider ?? "typesafe") !== this.provider)
6000
+ return { answer: null, reason: "provider_mismatch" };
5756
6001
  const decision = evaluateModelAnswer(entry);
5757
6002
  if (!decision.accepted)
5758
6003
  return { answer: null, reason: "acceptance_policy" };
@@ -5764,11 +6009,12 @@ var FileClassificationCache = class _FileClassificationCache {
5764
6009
  const probabilities = Object.fromEntries(
5765
6010
  MODEL_CHOICES.map((key) => [key, answer.probabilities[key]])
5766
6011
  );
5767
- this.entries[classificationKey(sentence)] = {
6012
+ this.entries[providerClassificationKey(this.provider, sentence)] = {
5768
6013
  op: answer.op,
5769
6014
  probabilities,
5770
6015
  model: answer.model,
5771
6016
  requestedModel: answer.requestedModel,
6017
+ provider: this.provider,
5772
6018
  source: "model",
5773
6019
  promptVersion: CLASSIFICATION_PROMPT_VERSION,
5774
6020
  operationSetVersion: OPERATION_SET_VERSION,
@@ -5799,7 +6045,8 @@ var FileClassificationCache = class _FileClassificationCache {
5799
6045
  try {
5800
6046
  const latest = await _FileClassificationCache.load(
5801
6047
  this.path,
5802
- this.requestedModel
6048
+ this.requestedModel,
6049
+ this.provider
5803
6050
  );
5804
6051
  const merged = { ...latest.entries, ...this.entries };
5805
6052
  const sorted = Object.fromEntries(
@@ -6225,15 +6472,76 @@ async function measure(page, judge, claim2, options = {}) {
6225
6472
  }
6226
6473
 
6227
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";
6228
6536
  function goalOperations(state2) {
6229
6537
  return {
6230
6538
  ...Object.fromEntries(
6231
6539
  Object.keys(state2.targets).map((op) => [
6232
6540
  op,
6233
- 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"
6234
6542
  ])
6235
6543
  ),
6236
- 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",
6237
6545
  BLOCKED: "No offered element or field can move the goal forward from this page; abstain"
6238
6546
  };
6239
6547
  }
@@ -6253,11 +6561,28 @@ function same(a, b) {
6253
6561
  return a.document === b.document && a.revision === b.revision && a.route === b.route;
6254
6562
  }
6255
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) {
6256
6574
  const started = performance.now();
6257
6575
  const maxRequests = options.maxRequests ?? 24;
6258
6576
  const maxActions = options.maxActions ?? 18;
6259
6577
  const timeoutMs = options.timeoutMs ?? 12e4;
6260
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;
6261
6586
  if (!Number.isFinite(operationMinMargin) || operationMinMargin < 0 || operationMinMargin > 1)
6262
6587
  throw new RangeError("Invalid goal operation margin");
6263
6588
  for (const [value, cap] of [
@@ -6267,7 +6592,7 @@ async function runGoal(page, planner, judge, options) {
6267
6592
  ])
6268
6593
  if (!Number.isSafeInteger(value) || value < 1 || value > cap)
6269
6594
  throw new RangeError("Invalid goal budget");
6270
- 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())))
6271
6596
  throw new TypeError(
6272
6597
  "Goal and independent verification claims are required"
6273
6598
  );
@@ -6293,7 +6618,10 @@ async function runGoal(page, planner, judge, options) {
6293
6618
  signal.removeEventListener("abort", onAbort);
6294
6619
  }
6295
6620
  };
6296
- const entries = Object.values(options.data ?? {});
6621
+ const entries = [
6622
+ ...Object.values(options.data ?? {}),
6623
+ ...options.opaqueEntries ?? []
6624
+ ];
6297
6625
  const taints = entries.map(
6298
6626
  (entry) => entry.sensitive ? { ...entry, opaqueValues: [...entry.opaqueValues ?? [], entry.value] } : entry
6299
6627
  );
@@ -6305,8 +6633,11 @@ async function runGoal(page, planner, judge, options) {
6305
6633
  let actions = 0;
6306
6634
  let pendingCall = false;
6307
6635
  let reportedCalls = 0;
6636
+ let failure;
6637
+ let staleDetail;
6308
6638
  const result = (reason, detail) => ({
6309
- status: reason === "verified" ? "passed" : "failed",
6639
+ ...generators ? { dataSeed } : {},
6640
+ status: reason === "verified" || reason === "completed" ? "passed" : "failed",
6310
6641
  reason,
6311
6642
  requests,
6312
6643
  actions,
@@ -6314,14 +6645,18 @@ async function runGoal(page, planner, judge, options) {
6314
6645
  calls,
6315
6646
  history,
6316
6647
  ...detail ? { detail } : {},
6648
+ ...failure ? { failure } : {},
6317
6649
  verification
6318
6650
  });
6319
- const uncertain = (what, answer, route, label = (choice) => choice) => {
6320
- let where = route;
6651
+ const routeName = (route) => {
6321
6652
  try {
6322
- where = new URL(route).pathname || route;
6653
+ return new URL(route).pathname || route;
6323
6654
  } catch {
6655
+ return route;
6324
6656
  }
6657
+ };
6658
+ const uncertain = (what, answer, route, label = (choice) => choice) => {
6659
+ const where = routeName(route);
6325
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";
6326
6661
  return project(`${what} on ${where}: ${top}`);
6327
6662
  };
@@ -6346,16 +6681,45 @@ async function runGoal(page, planner, judge, options) {
6346
6681
  `(({ refs, bindings }) => refs.map(ref => {
6347
6682
  const element = [...document.querySelectorAll('[data-sedum-ref]')].find(e => e.getAttribute('data-sedum-ref') === ref);
6348
6683
  const value = element && ('value' in element ? element.value : element.textContent);
6349
- 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 };
6350
6686
  }))(${JSON.stringify({
6351
6687
  refs: fills.candidates.map((c) => c.ref),
6352
- bindings: Object.entries(options.data ?? {}).map(([key, entry]) => [
6688
+ bindings: Object.entries(data).map(([key, entry]) => [
6353
6689
  key,
6354
6690
  entry.value.reveal()
6355
6691
  ])
6356
6692
  })})`
6357
6693
  )
6358
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
+ }
6359
6723
  const describe = (c) => JSON.stringify({
6360
6724
  name: project(c.name),
6361
6725
  role: c.role,
@@ -6375,10 +6739,21 @@ async function runGoal(page, planner, judge, options) {
6375
6739
  (targets.CLICK ??= {})[id] = describe(c);
6376
6740
  commands.set(id, { op: "click", target: target(c) });
6377
6741
  }
6378
- for (const [index2, c] of fills.candidates.entries()) {
6742
+ for (const [index, c] of fills.candidates.entries()) {
6379
6743
  if (c.disabled || !c.editable) continue;
6380
- const current = fieldState[index2];
6381
- 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)) {
6382
6757
  if (current.bindings.includes(key)) continue;
6383
6758
  const id = `t${commands.size}`;
6384
6759
  (targets.TYPE ??= {})[id] = `${describe(c)} current=${current.populated ? `populated (${current.bindings.join(",")})` : "empty"} \u2190 {{${key}}}${entry.sensitive ? " (secret)" : ` = ${project(entry.value.reveal())}`}`;
@@ -6400,12 +6775,23 @@ async function runGoal(page, planner, judge, options) {
6400
6775
  ]);
6401
6776
  const visits = (seen.get(fingerprint) ?? 0) + 1;
6402
6777
  seen.set(fingerprint, visits);
6403
- if (visits > 3) return result("no_progress");
6778
+ if (visits > 3)
6779
+ return staleDetail ? result("stale_observation", staleDetail) : result("no_progress");
6404
6780
  const state2 = {
6781
+ ...completion.kind === "planner" ? { completion: "planner" } : {},
6782
+ ...generators ? { automaticData: true, declaredDataKeys: Object.keys(data) } : {},
6405
6783
  goal: project(options.goal),
6406
6784
  page: project(digest.text),
6407
6785
  recentActions: history.slice(-10),
6408
- 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
6409
6795
  };
6410
6796
  if (Buffer.byteLength(JSON.stringify(state2)) > 60 * 1024)
6411
6797
  return result("request_too_large");
@@ -6427,15 +6813,42 @@ async function runGoal(page, planner, judge, options) {
6427
6813
  );
6428
6814
  if (!same(digest.version, await active(pageVersion(page)))) continue;
6429
6815
  const op = decision.operation.choice;
6430
- 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
+ }
6431
6843
  if (op === "DONE") {
6432
- for (const claim2 of options.verify) {
6844
+ if (completion.kind === "planner") return result("completed");
6845
+ for (const claim2 of completion.claims) {
6433
6846
  if (requests >= maxRequests) return result("request_limit");
6434
6847
  requests++;
6435
6848
  const singleAttemptJudge = {
6436
6849
  holds: (text, snapshot, callOptions) => {
6437
6850
  pendingCall = true;
6438
- return judge.holds(text, snapshot, {
6851
+ return completion.judge.holds(text, snapshot, {
6439
6852
  ...callOptions,
6440
6853
  maxAttempts: 1
6441
6854
  });
@@ -6477,9 +6890,122 @@ async function runGoal(page, planner, judge, options) {
6477
6890
  return name ? `"${name}"` : id;
6478
6891
  })
6479
6892
  );
6480
- const command = commands.get(head.choice);
6893
+ if (head.choice === GOAL_NO_MATCH) return result("target_abstention");
6894
+ let command = commands.get(head.choice);
6481
6895
  if (!command) return result("invalid_target");
6482
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
+ }
6483
7009
  if (command.op !== "click" && command.op !== "type")
6484
7010
  return result("invalid_target");
6485
7011
  const source = command.op === "click" ? clicks : fills;
@@ -6487,14 +7013,49 @@ async function runGoal(page, planner, judge, options) {
6487
7013
  collectCandidates(page, command.op === "click" ? "click" : "fill")
6488
7014
  );
6489
7015
  const surface = (candidates) => JSON.stringify(candidates.map((c) => ({ ...c, ref: void 0 })));
6490
- if (!fresh.complete || fresh.next !== null || !same(source.version, fresh.version) || surface(source.candidates) !== surface(fresh.candidates))
6491
- return result("stale_observation");
6492
- const index = source.candidates.findIndex(
7016
+ const selectedIndex = source.candidates.findIndex(
6493
7017
  (c) => c.ref === command.target.driverTarget().ref
6494
7018
  );
6495
- 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];
6496
7039
  if (!chosen) return result("invalid_target");
7040
+ failure = void 0;
7041
+ staleDetail = void 0;
6497
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
+ }
6498
7059
  if (signal.aborted) return result("timeout");
6499
7060
  actions++;
6500
7061
  history.push(project(`${op} ${targets[op][head.choice]}`));
@@ -6503,7 +7064,7 @@ async function runGoal(page, planner, judge, options) {
6503
7064
  const sentence = project(
6504
7065
  command.op === "type" ? `Type {{${binding}}} into ${chosen.name}` : `Click ${chosen.name}${chosen.peers[0] ? ` (${chosen.peers[0]})` : ""}`
6505
7066
  );
6506
- let failure;
7067
+ let actionFailure;
6507
7068
  let failed = false;
6508
7069
  try {
6509
7070
  await active(
@@ -6517,9 +7078,9 @@ async function runGoal(page, planner, judge, options) {
6517
7078
  );
6518
7079
  } catch (error2) {
6519
7080
  failed = true;
6520
- failure = error2;
7081
+ actionFailure = error2;
6521
7082
  }
6522
- 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) {
6523
7084
  actions--;
6524
7085
  history.pop();
6525
7086
  continue;
@@ -6533,12 +7094,18 @@ async function runGoal(page, planner, judge, options) {
6533
7094
  probability: head.probabilities[head.choice],
6534
7095
  beforeVersion: fresh.version,
6535
7096
  status: failed ? "failed" : "passed",
6536
- 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",
6537
7098
  elapsedMs: performance.now() - actionStarted,
6538
7099
  calls: calls.slice(reportedCalls)
6539
7100
  });
6540
7101
  reportedCalls = calls.length;
6541
- 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
+ );
6542
7109
  }
6543
7110
  return result("timeout");
6544
7111
  } catch (error2) {
@@ -6831,6 +7398,7 @@ function gotoPathParts(sentence) {
6831
7398
  function resultCall(call2, purpose, apiMs = null) {
6832
7399
  return {
6833
7400
  purpose,
7401
+ ...call2.provider ? { provider: call2.provider } : {},
6834
7402
  ...call2.modality ? { modality: call2.modality } : {},
6835
7403
  requestedModel: call2.requestedModel,
6836
7404
  model: call2.model,
@@ -6876,11 +7444,11 @@ function providerFailure(file, error2) {
6876
7444
  },
6877
7445
  authentication: {
6878
7446
  message: "The model provider rejected the API key.",
6879
- 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."
6880
7448
  },
6881
7449
  configuration: {
6882
7450
  message: "The model provider is not configured correctly.",
6883
- 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."
6884
7452
  }
6885
7453
  };
6886
7454
  return {
@@ -8059,7 +8627,7 @@ function unresolvedWhy(resolved, op, visionEnabled) {
8059
8627
  return `${why}; vision fallback could not run (it needs 2 to 40 fully visible, unobscured controls on screen)`;
8060
8628
  return why;
8061
8629
  }
8062
- async function recordGoalAction(page, action, report, repoRoot, source) {
8630
+ async function recordGoalAction(page, action, report, repoRoot, source, group, canceled2 = false) {
8063
8631
  const attempt = report.test.currentAttempt;
8064
8632
  const index = attempt.stepCount + 1;
8065
8633
  const id = `${attempt.id}:step:${index}`;
@@ -8091,9 +8659,10 @@ async function recordGoalAction(page, action, report, repoRoot, source) {
8091
8659
  phase: "steps",
8092
8660
  sentence: safeText(action.sentence, privacy, 512),
8093
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)) } : {},
8094
8663
  sourceStack: [safeSource(source, repoRoot, privacy)],
8095
- state: "completed",
8096
- verdict: action.status,
8664
+ state: canceled2 ? "error" : "completed",
8665
+ verdict: canceled2 ? null : action.status,
8097
8666
  flags: [],
8098
8667
  elapsedMs: action.elapsedMs,
8099
8668
  page: sensitive ? { status: "omitted", reason: "sensitive_page" } : await reportPage(page, `${id}:observation:1`, privacy),
@@ -8121,6 +8690,58 @@ async function recordGoalAction(page, action, report, repoRoot, source) {
8121
8690
  targetBox: null
8122
8691
  });
8123
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
+ }
8124
8745
  async function runFlow(file, runDependencies) {
8125
8746
  const absolute = path5.resolve(file);
8126
8747
  const loaded2 = await loadFlowFile(absolute, {
@@ -8325,10 +8946,19 @@ async function runFlow(file, runDependencies) {
8325
8946
  const goalResult = await runGoal(
8326
8947
  activePage,
8327
8948
  {
8949
+ ...dependencies.provider.targetChoiceMinOptions ? {
8950
+ targetChoiceMinOptions: dependencies.provider.targetChoiceMinOptions
8951
+ } : {},
8328
8952
  chooseGoal: (state2, options) => {
8329
8953
  purposes.push("planner");
8330
8954
  return dependencies.provider.chooseGoal(state2, options);
8331
- }
8955
+ },
8956
+ ...dependencies.provider.chooseGoalValue ? {
8957
+ chooseGoalValue: (state2, options) => {
8958
+ purposes.push("planner");
8959
+ return dependencies.provider.chooseGoalValue(state2, options);
8960
+ }
8961
+ } : {}
8332
8962
  },
8333
8963
  {
8334
8964
  holds: (text, digest, options) => {
@@ -8345,6 +8975,14 @@ async function runFlow(file, runDependencies) {
8345
8975
  )
8346
8976
  ],
8347
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
+ },
8348
8986
  ...dependencies.report ? {
8349
8987
  onAction: async (action) => {
8350
8988
  await recordGoalAction(
@@ -8366,15 +9004,23 @@ async function runFlow(file, runDependencies) {
8366
9004
  const { test: test2, privacy } = dependencies.report;
8367
9005
  const attempt = test2.currentAttempt;
8368
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;
8369
9015
  await test2.addStep({
8370
- id: `${attempt.id}:step:${attempt.stepCount + 1}`,
9016
+ id,
8371
9017
  index: attempt.stepCount + 1,
8372
9018
  kind: "verify",
8373
9019
  operation: "goal",
8374
9020
  phase: "steps",
8375
9021
  sentence: safeText(goal.text, privacy, 512),
8376
9022
  detail: safeText(
8377
- `${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}`,
8378
9024
  privacy,
8379
9025
  512
8380
9026
  ),
@@ -8387,8 +9033,11 @@ async function runFlow(file, runDependencies) {
8387
9033
  (flag2) => flag2 === "low_confidence" || flag2 === "contradiction"
8388
9034
  ) ?? [],
8389
9035
  elapsedMs: goalResult.elapsedMs,
8390
- page: { status: "omitted", reason: "goal_summary" },
8391
- locator: null,
9036
+ page: failureArtifacts?.page ?? {
9037
+ status: "omitted",
9038
+ reason: "goal_summary"
9039
+ },
9040
+ locator: failureArtifacts?.locator ?? null,
8392
9041
  judgement: checked ? {
8393
9042
  holds: checked.holds,
8394
9043
  contradicted: checked.contradicted,
@@ -8404,14 +9053,17 @@ async function runFlow(file, runDependencies) {
8404
9053
  error: goalResult.status === "failed" ? {
8405
9054
  code: goalResult.reason,
8406
9055
  message: safeText(
8407
- `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." : ""}`,
8408
9057
  privacy,
8409
9058
  512
8410
9059
  )
8411
9060
  } : null,
8412
- evidence: { status: "omitted", reason: "goal_summary" },
9061
+ evidence: failureArtifacts?.evidence ?? {
9062
+ status: "omitted",
9063
+ reason: "goal_summary"
9064
+ },
8413
9065
  replayFrame: null,
8414
- targetBox: null
9066
+ targetBox: failureArtifacts?.targetBox ?? null
8415
9067
  });
8416
9068
  }
8417
9069
  if (goalResult.status === "failed")
@@ -8741,6 +9393,15 @@ function tokenize(source) {
8741
9393
  index++;
8742
9394
  }
8743
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
+ };
8744
9405
  const readQuoted = (quote) => {
8745
9406
  let value = "";
8746
9407
  let dynamic = false;
@@ -8863,11 +9524,20 @@ function tokenize(source) {
8863
9524
  continue;
8864
9525
  }
8865
9526
  }
8866
- if (IDENT_START.test(char)) {
9527
+ const escapedStart = char === "\\" ? identifierEscape() : void 0;
9528
+ if (IDENT_START.test(char) || escapedStart && IDENT_START.test(escapedStart.value)) {
8867
9529
  let value = "";
8868
- while (index < source.length && IDENT_PART.test(source[index])) {
8869
- value += source[index];
8870
- 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);
8871
9541
  }
8872
9542
  tokens.push({ kind: "ident", value, line: startLine, col: startCol });
8873
9543
  continue;
@@ -8900,6 +9570,13 @@ function scanScriptSentences(source, file) {
8900
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.",
8901
9571
  fix: 'Write a literal sentence with {{name}} and pass the value separately: ai("type {{email}} into the Email field", { email }).'
8902
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
+ });
8903
9580
  const TERMINATORS = /* @__PURE__ */ new Set([",", ")", "]", ";"]);
8904
9581
  const skipExpression = (index) => {
8905
9582
  let depth = 0;
@@ -8995,7 +9672,48 @@ function scanScriptSentences(source, file) {
8995
9672
  const next = at2(last + 1);
8996
9673
  return next === void 0 || next.line > at2(last).line && !".[(?".includes(next.value) || next.value === ";" || next.value === "," || next.value === "as" && value(last + 2) === "const";
8997
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
+ };
8998
9715
  const constants3 = /* @__PURE__ */ new Map();
9716
+ const objectConstants = /* @__PURE__ */ new Map();
8999
9717
  {
9000
9718
  const bindings = /* @__PURE__ */ new Map();
9001
9719
  tokens.forEach((token, index) => {
@@ -9010,6 +9728,11 @@ function scanScriptSentences(source, file) {
9010
9728
  const last = at2(start)?.kind === "string" ? start : isPunct(start, "[") ? match.get(start) : void 0;
9011
9729
  if (last !== void 0 && endsCleanly(last))
9012
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);
9013
9736
  });
9014
9737
  }
9015
9738
  const MAX_SENTENCES = 1e4;
@@ -9059,6 +9782,114 @@ function scanScriptSentences(source, file) {
9059
9782
  if (isPunct(first, "[")) list(first);
9060
9783
  else argument(first);
9061
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
+ };
9062
9893
  const inlineFunction = (index) => {
9063
9894
  let cursor = index;
9064
9895
  if (value(cursor) === "async") cursor++;
@@ -9316,6 +10147,17 @@ function scanScriptSentences(source, file) {
9316
10147
  sentences[found] = { ...sentences[found], check: true };
9317
10148
  continue;
9318
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
+ }
9319
10161
  if (member !== void 0 && at2(member)?.kind === "ident" && at2(member).value === "holds") {
9320
10162
  unchecked(
9321
10163
  token,
@@ -9452,6 +10294,31 @@ function dedupeDiagnostics(diagnostics) {
9452
10294
  function directSentences(steps) {
9453
10295
  return steps.filter((step) => step.kind === "sentence");
9454
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
+ }
9455
10322
  function entryUrlDiagnostic(flow, baseUrl) {
9456
10323
  try {
9457
10324
  resolveEntryUrl(flow.url, baseUrl ?? void 0);
@@ -9534,7 +10401,7 @@ async function validateScriptFile(file, options, classify) {
9534
10401
  });
9535
10402
  diagnostics.push(...warnings);
9536
10403
  const scanned = scans.flatMap((scan) => scan.sentences);
9537
- const sentences = scanned.map((item) => ({
10404
+ const sentences = scanned.filter((item) => !item.check).map((item) => ({
9538
10405
  kind: "sentence",
9539
10406
  phase: "steps",
9540
10407
  text: item.text,
@@ -9543,19 +10410,7 @@ async function validateScriptFile(file, options, classify) {
9543
10410
  }));
9544
10411
  const checked = await classifySentenceSteps(sentences, classify);
9545
10412
  diagnostics.push(...checked.diagnostics);
9546
- const invalidChecks = [];
9547
- scanned.forEach((item, index) => {
9548
- const classified = checked.classification.steps[index];
9549
- if (!item.check || !classified || classified.op === "verify" && !WAIT_UNTIL.test(item.text))
9550
- return;
9551
- invalidChecks.push({
9552
- severity: "error",
9553
- code: "invalid_check",
9554
- source: item.source,
9555
- message: "ai.holds takes one claim about the page.",
9556
- fix: 'Write ai.holds("the passkey screen is shown").'
9557
- });
9558
- });
10413
+ const invalidChecks = scanned.filter((item) => item.check).flatMap(checkDiagnostics);
9559
10414
  diagnostics.push(...invalidChecks);
9560
10415
  const complete = checked.classification.steps.every((step) => step !== null) && checked.diagnostics.length === 0 && invalidChecks.length === 0 && warnings.length === 0;
9561
10416
  return {
@@ -9572,13 +10427,13 @@ async function validateScriptFile(file, options, classify) {
9572
10427
  var HELPER_EXTENSIONS = [".ts", ".mts", ".cts", ".tsx", ".js", ".mjs"];
9573
10428
  var MAX_HELPERS = 64;
9574
10429
  function resolveHelper(from, specifier) {
9575
- const base = path7.resolve(path7.dirname(from), specifier);
9576
- 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, "");
9577
10432
  const candidates = [
9578
- base,
10433
+ base2,
9579
10434
  ...HELPER_EXTENSIONS.map((extension) => stem + extension),
9580
10435
  ...HELPER_EXTENSIONS.map(
9581
- (extension) => path7.join(base, `index${extension}`)
10436
+ (extension) => path7.join(base2, `index${extension}`)
9582
10437
  )
9583
10438
  ];
9584
10439
  return candidates.find(
@@ -10148,6 +11003,7 @@ async function runScriptTest(file, identity, runDependencies) {
10148
11003
  );
10149
11004
  const opaqueEntries = [];
10150
11005
  let firstProblem = null;
11006
+ let goalStarted = false;
10151
11007
  let inFlight = null;
10152
11008
  const outstanding = /* @__PURE__ */ new Set();
10153
11009
  const rejected = [];
@@ -10370,6 +11226,177 @@ async function runScriptTest(file, identity, runDependencies) {
10370
11226
  return step;
10371
11227
  };
10372
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
+ };
10373
11400
  const group = async (name, body, values, source2) => {
10374
11401
  if (finished)
10375
11402
  usage(
@@ -10549,9 +11576,10 @@ async function runScriptTest(file, identity, runDependencies) {
10549
11576
  return { status: "passed", file: absolute };
10550
11577
  }
10551
11578
  if (primary.status === "failed") await report?.test.finishTest("failed");
10552
- return primary;
11579
+ return primary.status === "failed" && goalStarted ? { ...primary, retryable: false } : primary;
10553
11580
  } catch (error2) {
10554
- if (isStepStop(error2)) return error2.problem;
11581
+ if (isStepStop(error2))
11582
+ return error2.problem.status === "failed" && goalStarted ? { ...error2.problem, retryable: false } : error2.problem;
10555
11583
  return runtimeFailure(absolute, error2);
10556
11584
  } finally {
10557
11585
  finished = true;
@@ -10616,6 +11644,7 @@ async function recordCodeFailure(page, dependencies, source, error2, group) {
10616
11644
  export {
10617
11645
  ACCEPTANCE_POLICY_VERSION,
10618
11646
  AssertionEngineError,
11647
+ BACKOFF_JITTER,
10619
11648
  BrowserDriverError,
10620
11649
  CACHE_FORMAT,
10621
11650
  CANDIDATE_LIMIT,
@@ -10624,12 +11653,18 @@ export {
10624
11653
  DEFAULT_BAND,
10625
11654
  DEFAULT_CONTRADICTION_CUTOFF,
10626
11655
  DEFAULT_MIN_P,
11656
+ DEFAULT_PROVIDER_CONCURRENCY,
10627
11657
  DEFAULT_VISION_MODEL,
10628
11658
  DIGEST_LIMIT,
10629
11659
  DataResolutionError,
10630
11660
  FileClassificationCache,
11661
+ GOAL_NO_MATCH,
11662
+ GateAborted,
11663
+ GateWaitExceeded,
10631
11664
  LocatorCacheConflict,
10632
11665
  MATCHER_VERSION,
11666
+ MAX_COOLDOWN_MS,
11667
+ MAX_PROVIDER_CONCURRENCY,
10633
11668
  MIN_MODEL_MARGIN,
10634
11669
  MIN_MODEL_PROBABILITY,
10635
11670
  MODEL_CHOICES,
@@ -10646,6 +11681,8 @@ export {
10646
11681
  PageScriptError,
10647
11682
  PlaywrightBrowserDriver,
10648
11683
  ProviderError,
11684
+ ProviderGate,
11685
+ RATE_LIMIT_BUDGET_MS,
10649
11686
  RejectionRouter,
10650
11687
  ResolvedStepTarget,
10651
11688
  ResultAttemptSchema,
@@ -10676,6 +11713,7 @@ export {
10676
11713
  VisionRequestError,
10677
11714
  WAIT_UNTIL,
10678
11715
  attributeRejection,
11716
+ backoffDelay,
10679
11717
  callExtent,
10680
11718
  canonicalSentence,
10681
11719
  captureVisionObservation,
@@ -10691,6 +11729,7 @@ export {
10691
11729
  collectCandidates,
10692
11730
  compareDiagnostics3 as compareDiagnostics,
10693
11731
  controlState,
11732
+ cooldownDelay,
10694
11733
  dedupeDiagnostics,
10695
11734
  describeRejection,
10696
11735
  discoverFlowFiles,
@@ -10705,9 +11744,11 @@ export {
10705
11744
  firstDiagnostic,
10706
11745
  formatFlowDiagnostic,
10707
11746
  goalChoiceAccepted,
11747
+ goalFailureArtifacts,
10708
11748
  goalOperations,
10709
11749
  inlineValues,
10710
11750
  installChromium,
11751
+ isClaimSentence,
10711
11752
  isFlowScalar,
10712
11753
  isFullyValidated,
10713
11754
  isRunWideProviderError,
@@ -10725,6 +11766,7 @@ export {
10725
11766
  matchLiveEntry,
10726
11767
  measure,
10727
11768
  navigationWhy,
11769
+ nextConcurrency,
10728
11770
  normalizeSignal,
10729
11771
  opaqueMatches,
10730
11772
  pageDigest,
@@ -10734,6 +11776,7 @@ export {
10734
11776
  parseFlow,
10735
11777
  parseFrame,
10736
11778
  parseModule,
11779
+ parseRetryAfter,
10737
11780
  pathKey,
10738
11781
  patternOperation,
10739
11782
  preflightSentence,
@@ -10742,6 +11785,7 @@ export {
10742
11785
  projectDigest,
10743
11786
  quietPage,
10744
11787
  readTarget,
11788
+ recordGoalAction,
10745
11789
  redactOpaqueText,
10746
11790
  reportPage,
10747
11791
  resolveData,