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

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
@@ -1,10 +1,23 @@
1
+ import {
2
+ isSecret,
3
+ parseFrame,
4
+ pathKey,
5
+ revealSecret,
6
+ samePath,
7
+ scriptRegistry,
8
+ secret,
9
+ sourceInFile,
10
+ test
11
+ } from "./chunk-C32TDS2U.js";
12
+
1
13
  // src/run-result.ts
2
14
  import { z } from "zod";
3
15
  var probability = z.number().finite().min(0).max(1);
4
16
  var nonnegative = z.number().finite().nonnegative();
5
17
  var count = z.number().int().nonnegative();
6
18
  var verdict = z.enum(["passed", "failed"]);
7
- var flag = z.enum(["low_confidence", "contradiction"]);
19
+ var stepFlag = z.enum(["low_confidence", "contradiction"]);
20
+ var flag = z.enum(["low_confidence", "contradiction", "flaky"]);
8
21
  var state = z.enum(["running", "completed", "interrupted", "error"]);
9
22
  var ResultSourceSchema = z.strictObject({
10
23
  file: z.string().min(1),
@@ -74,6 +87,7 @@ var ResultLocatorSchema = z.strictObject({
74
87
  vision: z.strictObject({
75
88
  outcome: z.enum(["selected", "abstained", "failed"]).optional(),
76
89
  reason: z.string().max(120).optional(),
90
+ abstentionReason: z.string().max(120).optional(),
77
91
  elapsedMs: nonnegative,
78
92
  failure: z.enum([
79
93
  "timeout",
@@ -84,7 +98,8 @@ var ResultLocatorSchema = z.strictObject({
84
98
  "invalid_json",
85
99
  "invalid_selection",
86
100
  "truncated_response",
87
- "unknown"
101
+ "unknown",
102
+ "stale_page"
88
103
  ]).optional(),
89
104
  httpStatus: z.number().int().min(100).max(599).optional()
90
105
  }).optional(),
@@ -120,10 +135,12 @@ var ResultStepSchema = z.strictObject({
120
135
  phase: z.enum(["before", "steps", "after"]),
121
136
  sentence: z.string().max(512),
122
137
  detail: z.string().max(512),
138
+ /** Enclosing `ai.group` names, outermost first; absent outside a group. */
139
+ group: z.array(z.string().max(120)).max(16).optional(),
123
140
  sourceStack: z.array(ResultSourceSchema).min(1),
124
141
  state,
125
142
  verdict: verdict.nullable(),
126
- flags: z.array(flag),
143
+ flags: z.array(stepFlag),
127
144
  elapsedMs: nonnegative,
128
145
  page: ResultPageSchema,
129
146
  locator: ResultLocatorSchema.nullable(),
@@ -205,7 +222,12 @@ var ResultExecutionSchema = z.strictObject({
205
222
  count: z.number().int().positive(),
206
223
  globalSelectedTests: count
207
224
  }).nullable(),
208
- providerConcurrency: z.number().int().positive()
225
+ providerConcurrency: z.number().int().positive(),
226
+ /** Present when vision fallback is enabled; `key` is checked before tests run. */
227
+ vision: z.strictObject({
228
+ model: z.string().min(1).max(200),
229
+ key: z.enum(["accepted", "rejected", "unreachable"])
230
+ }).optional()
209
231
  });
210
232
  var RunResultSchema = z.strictObject({
211
233
  schemaVersion: z.literal(1),
@@ -236,13 +258,13 @@ var RunResultSchema = z.strictObject({
236
258
  });
237
259
  function resultTotals(tests, setupCalls = [], selectedTestCount = tests.length) {
238
260
  const selected = tests.flatMap(
239
- (test) => test.attempts.filter((attempt) => attempt.id === test.selectedAttemptId)
261
+ (test2) => test2.attempts.filter((attempt) => attempt.id === test2.selectedAttemptId)
240
262
  );
241
263
  const steps = selected.flatMap((attempt) => attempt.steps);
242
264
  const calls = [
243
265
  ...setupCalls,
244
266
  ...tests.flatMap(
245
- (test) => test.attempts.flatMap((attempt) => [
267
+ (test2) => test2.attempts.flatMap((attempt) => [
246
268
  ...attempt.calls ?? [],
247
269
  ...attempt.steps.flatMap((step) => step.calls)
248
270
  ])
@@ -251,13 +273,13 @@ function resultTotals(tests, setupCalls = [], selectedTestCount = tests.length)
251
273
  const complete = calls.every((call2) => call2.costUsd !== null);
252
274
  return {
253
275
  selectedTests: selectedTestCount,
254
- executedTests: tests.filter((test) => test.attempts.length > 0).length,
255
- passedTests: tests.filter((test) => test.verdict === "passed").length,
256
- failedTests: tests.filter((test) => test.verdict === "failed").length,
276
+ executedTests: tests.filter((test2) => test2.attempts.length > 0).length,
277
+ passedTests: tests.filter((test2) => test2.verdict === "passed").length,
278
+ failedTests: tests.filter((test2) => test2.verdict === "failed").length,
257
279
  passedSteps: steps.filter((step) => step.verdict === "passed").length,
258
280
  failedSteps: steps.filter((step) => step.verdict === "failed").length,
259
281
  historicalAttempts: tests.reduce(
260
- (sum, test) => sum + Math.max(0, test.attempts.length - 1),
282
+ (sum, test2) => sum + Math.max(0, test2.attempts.length - 1),
261
283
  0
262
284
  ),
263
285
  flaggedSteps: steps.filter((step) => step.flags.length > 0).length,
@@ -283,11 +305,11 @@ function validateRunResult(value) {
283
305
  ids.add(id);
284
306
  };
285
307
  addId(result.runId);
286
- for (const test of result.tests) {
287
- addId(test.id);
288
- if (test.state === "completed" && (test.verdict === null || test.attempts.some((attempt) => attempt.state === "running")))
308
+ for (const test2 of result.tests) {
309
+ addId(test2.id);
310
+ if (test2.state === "completed" && (test2.verdict === null || test2.attempts.some((attempt) => attempt.state === "running")))
289
311
  throw new Error("Completed test has incomplete attempts");
290
- for (const attempt of test.attempts) {
312
+ for (const attempt of test2.attempts) {
291
313
  addId(attempt.id);
292
314
  if (attempt.state === "completed" && (attempt.verdict === null || attempt.finishedAt === null))
293
315
  throw new Error("Completed attempt has no verdict or finish time");
@@ -334,14 +356,14 @@ function validateRunResult(value) {
334
356
  if (attempt.state === "error" && attempt.problems.length > 0 && primary?.outcome !== "error")
335
357
  throw new Error("Error attempt needs an error primary problem");
336
358
  }
337
- const selected = test.attempts.find(
338
- (attempt) => attempt.id === test.selectedAttemptId
359
+ const selected = test2.attempts.find(
360
+ (attempt) => attempt.id === test2.selectedAttemptId
339
361
  );
340
- if (test.selectedAttemptId !== null && !selected)
362
+ if (test2.selectedAttemptId !== null && !selected)
341
363
  throw new Error("Selected attempt is missing");
342
- if (test.verdict !== (selected?.verdict ?? null))
364
+ if (test2.verdict !== (selected?.verdict ?? null))
343
365
  throw new Error("Test verdict differs from selected attempt");
344
- if (JSON.stringify(test.flags) !== JSON.stringify(selected?.flags ?? []))
366
+ if (JSON.stringify(test2.flags) !== JSON.stringify(selected?.flags ?? []))
345
367
  throw new Error("Test flags differ from selected attempt");
346
368
  }
347
369
  if (JSON.stringify(result.totals) !== JSON.stringify(
@@ -352,13 +374,13 @@ function validateRunResult(value) {
352
374
  )
353
375
  ))
354
376
  throw new Error("Run totals differ from children");
355
- const finalVerdict = result.error || result.state !== "completed" || result.tests.length === 0 ? null : result.tests.some((test) => test.verdict === "failed") ? "failed" : result.tests.every((test) => test.verdict === "passed") ? "passed" : null;
377
+ const finalVerdict = result.error || result.state !== "completed" || result.tests.length === 0 ? null : result.tests.some((test2) => test2.verdict === "failed") ? "failed" : result.tests.every((test2) => test2.verdict === "passed") ? "passed" : null;
356
378
  if (result.verdict !== finalVerdict)
357
379
  throw new Error("Run verdict differs from tests");
358
- const runFlags = [...new Set(result.tests.flatMap((test) => test.flags))];
380
+ const runFlags = [...new Set(result.tests.flatMap((test2) => test2.flags))];
359
381
  if (JSON.stringify(result.flags) !== JSON.stringify(runFlags))
360
382
  throw new Error("Run flags differ from tests");
361
- if (result.state === "completed" && (result.error !== null || result.tests.length === 0 || result.tests.some((test) => test.state !== "completed")))
383
+ if (result.state === "completed" && (result.error !== null || result.tests.length === 0 || result.tests.some((test2) => test2.state !== "completed")))
362
384
  throw new Error("Completed run has no completed tests");
363
385
  if (result.state === "running" && result.finishedAt !== null)
364
386
  throw new Error("Running run has finish time");
@@ -419,6 +441,10 @@ var TestRecording = class {
419
441
  finishTest(verdict2) {
420
442
  return this.recorder.finishTestFor(this.testId, verdict2);
421
443
  }
444
+ /** Ends a running attempt that could not run; the run itself continues. */
445
+ errorTest(error2) {
446
+ return this.recorder.errorTestFor(this.testId, error2);
447
+ }
422
448
  };
423
449
  function newAttempt(runId, ordinal, lane) {
424
450
  return {
@@ -483,28 +509,28 @@ var RunRecorder = class {
483
509
  Math.max(this.value.selectedTestCount ?? 0, this.value.tests.length)
484
510
  ),
485
511
  flags: [
486
- ...new Set(this.value.tests.flatMap((test) => test.flags))
512
+ ...new Set(this.value.tests.flatMap((test2) => test2.flags))
487
513
  ]
488
514
  };
489
515
  await this.sink(validateRunResult(this.value));
490
516
  }
491
517
  /** @internal Handles read their test through here. */
492
518
  testById(testId) {
493
- const test = this.value.tests.find((entry) => entry.id === testId);
494
- if (!test) throw new Error("Unknown test");
495
- return test;
519
+ const test2 = this.value.tests.find((entry) => entry.id === testId);
520
+ if (!test2) throw new Error("Unknown test");
521
+ return test2;
496
522
  }
497
523
  replaceTest(testId, update) {
498
524
  this.value = {
499
525
  ...this.value,
500
526
  tests: this.value.tests.map(
501
- (test) => test.id === testId ? update(test) : test
527
+ (test2) => test2.id === testId ? update(test2) : test2
502
528
  )
503
529
  };
504
530
  }
505
531
  replaceRunningAttempt(testId, update) {
506
- const test = this.testById(testId);
507
- const attempt = test.attempts.at(-1);
532
+ const test2 = this.testById(testId);
533
+ const attempt = test2.attempts.at(-1);
508
534
  if (!attempt || attempt.state !== "running")
509
535
  throw new Error("No running attempt");
510
536
  this.replaceTest(testId, (current) => ({
@@ -566,7 +592,7 @@ var RunRecorder = class {
566
592
  if ([...this.ordinals.values()].includes(ordinal))
567
593
  throw new Error("Test ordinal already started");
568
594
  const attempt = newAttempt(this.value.runId, 1, input.lane);
569
- const test = {
595
+ const test2 = {
570
596
  id: input.id,
571
597
  file: input.file,
572
598
  description: input.description ?? "",
@@ -580,9 +606,9 @@ var RunRecorder = class {
580
606
  const position2 = this.value.tests.findIndex(
581
607
  (entry) => (this.ordinals.get(entry.id) ?? 0) > ordinal
582
608
  );
583
- const tests = position2 === -1 ? [...this.value.tests, test] : [
609
+ const tests = position2 === -1 ? [...this.value.tests, test2] : [
584
610
  ...this.value.tests.slice(0, position2),
585
- test,
611
+ test2,
586
612
  ...this.value.tests.slice(position2)
587
613
  ];
588
614
  this.ordinals.set(input.id, ordinal);
@@ -603,7 +629,7 @@ var RunRecorder = class {
603
629
  }
604
630
  /** @internal Use `TestRecording.setGoal` after resolving secret bindings. */
605
631
  async setGoalFor(testId, goal) {
606
- this.replaceTest(testId, (test) => ({ ...test, goal }));
632
+ this.replaceTest(testId, (test2) => ({ ...test2, goal }));
607
633
  await this.publish();
608
634
  }
609
635
  /** @internal Use `TestRecording.addAttemptCalls`. */
@@ -670,12 +696,12 @@ var RunRecorder = class {
670
696
  */
671
697
  async startAttemptFor(testId, lane) {
672
698
  if (this.value.state !== "running") throw new Error("Run already finished");
673
- const test = this.testById(testId);
674
- if (test.attempts.at(-1)?.state === "running")
699
+ const test2 = this.testById(testId);
700
+ if (test2.attempts.at(-1)?.state === "running")
675
701
  throw new Error("No terminal attempt to retry");
676
702
  const attempt = newAttempt(
677
703
  this.value.runId,
678
- test.attempts.length + 1,
704
+ test2.attempts.length + 1,
679
705
  lane
680
706
  );
681
707
  this.replaceTest(testId, (current) => ({
@@ -696,11 +722,15 @@ var RunRecorder = class {
696
722
  }
697
723
  /** @internal Use `TestRecording.finishTest`. */
698
724
  async finishTestFor(testId, verdict2) {
699
- const test = this.testById(testId);
700
- const attempt = test.attempts.at(-1);
725
+ const test2 = this.testById(testId);
726
+ const attempt = test2.attempts.at(-1);
701
727
  if (!attempt) throw new Error("No test to finish");
728
+ const retriedPass = verdict2 === "passed" && test2.attempts.slice(0, -1).some((prior) => prior.verdict === "failed");
702
729
  const flags = [
703
- ...new Set(attempt.steps.flatMap((step) => step.flags))
730
+ .../* @__PURE__ */ new Set([
731
+ ...attempt.steps.flatMap((step) => step.flags),
732
+ ...retriedPass ? ["flaky"] : []
733
+ ])
704
734
  ];
705
735
  const finished = (/* @__PURE__ */ new Date()).toISOString();
706
736
  const updatedAttempt = {
@@ -723,6 +753,31 @@ var RunRecorder = class {
723
753
  }));
724
754
  await this.publish();
725
755
  }
756
+ /** @internal Use `TestRecording.errorTest`. */
757
+ async errorTestFor(testId, error2) {
758
+ const test2 = this.testById(testId);
759
+ const attempt = test2.attempts.at(-1);
760
+ if (attempt?.state !== "running") return;
761
+ const finished = (/* @__PURE__ */ new Date()).toISOString();
762
+ const updatedAttempt = {
763
+ ...attempt,
764
+ state: "error",
765
+ verdict: null,
766
+ error: error2,
767
+ finishedAt: finished,
768
+ elapsedMs: Math.max(
769
+ 0,
770
+ Date.parse(finished) - Date.parse(attempt.startedAt)
771
+ )
772
+ };
773
+ this.replaceTest(testId, (current) => ({
774
+ ...current,
775
+ state: "error",
776
+ verdict: null,
777
+ attempts: [...current.attempts.slice(0, -1), updatedAttempt]
778
+ }));
779
+ await this.publish();
780
+ }
726
781
  async finishTest(verdict2) {
727
782
  if (this.lastTestId === null) throw new Error("No test to finish");
728
783
  await this.finishTestFor(this.lastTestId, verdict2);
@@ -735,9 +790,9 @@ var RunRecorder = class {
735
790
  const runError = error2;
736
791
  this.value = {
737
792
  ...this.value,
738
- tests: this.value.tests.map((test) => {
739
- const attempt = test.attempts.at(-1);
740
- if (attempt?.state !== "running") return test;
793
+ tests: this.value.tests.map((test2) => {
794
+ const attempt = test2.attempts.at(-1);
795
+ if (attempt?.state !== "running") return test2;
741
796
  const updatedAttempt = {
742
797
  ...attempt,
743
798
  state: terminalState,
@@ -750,22 +805,22 @@ var RunRecorder = class {
750
805
  )
751
806
  };
752
807
  return {
753
- ...test,
808
+ ...test2,
754
809
  state: terminalState,
755
- attempts: [...test.attempts.slice(0, -1), updatedAttempt]
810
+ attempts: [...test2.attempts.slice(0, -1), updatedAttempt]
756
811
  };
757
812
  })
758
813
  };
759
814
  }
760
815
  const tests = this.value.tests;
761
- const verdict2 = error2 || tests.length === 0 || tests.some((test) => test.verdict === null) ? null : tests.some((test) => test.verdict === "failed") ? "failed" : "passed";
816
+ const verdict2 = error2 || tests.length === 0 || tests.some((test2) => test2.verdict === null) ? null : tests.some((test2) => test2.verdict === "failed") ? "failed" : "passed";
762
817
  this.value = {
763
818
  ...this.value,
764
819
  state: error2 ? terminalState : "completed",
765
820
  error: error2,
766
821
  verdict: verdict2,
767
822
  flags: [
768
- ...new Set(tests.flatMap((test) => test.flags))
823
+ ...new Set(tests.flatMap((test2) => test2.flags))
769
824
  ],
770
825
  finishedAt: at2
771
826
  };
@@ -1128,8 +1183,8 @@ async function matchLiveEntry(page, entry, key, operation, sentence, runtimeDepe
1128
1183
  // src/report-privacy.ts
1129
1184
  function safeText(value, privacy, limit) {
1130
1185
  let text = value;
1131
- for (const secret of [...privacy.secretValues].filter((item) => item.length > 0).sort((a, b) => b.length - a.length)) {
1132
- text = text.split(secret).join("[REDACTED]");
1186
+ for (const secret2 of [...privacy.secretValues].filter((item) => item.length > 0).sort((a, b) => b.length - a.length)) {
1187
+ text = text.split(secret2).join("[REDACTED]");
1133
1188
  }
1134
1189
  const points = Array.from(text);
1135
1190
  if (points.length <= limit) return text;
@@ -1348,9 +1403,10 @@ function operationError(error2, state2, subject) {
1348
1403
  function safeOperationError(error2, state2, operation) {
1349
1404
  const code = state2.crashed ? "page-crashed" : state2.disconnected ? "browser-disconnected" : state2.closed ? "page-closed" : "operation-failed";
1350
1405
  const lines = safeCallLog(error2);
1406
+ const network = error2 instanceof Error ? /net::ERR_[A-Z_]+/.exec(error2.message)?.[0] ?? (/Timeout \d+ms exceeded/.test(error2.message) ? "timeout" : null) : null;
1351
1407
  return new BrowserDriverError(
1352
1408
  code,
1353
- `${operation} failed.${lines.length ? `
1409
+ `${operation} failed${network ? ` (${network})` : ""}.${lines.length ? `
1354
1410
  Call log:
1355
1411
  ${lines.join("\n")}` : ""}`
1356
1412
  );
@@ -1376,6 +1432,9 @@ var PlaywrightPage = class {
1376
1432
  get url() {
1377
1433
  return this.page.url();
1378
1434
  }
1435
+ playwright() {
1436
+ return { page: this.page, context: this.page.context() };
1437
+ }
1379
1438
  async title() {
1380
1439
  return this.page.title();
1381
1440
  }
@@ -1552,6 +1611,42 @@ var PlaywrightPage = class {
1552
1611
  reason: "stale"
1553
1612
  }));
1554
1613
  if (!ready.actionable) return ready;
1614
+ if (options.chooseOption) {
1615
+ const native = await element.evaluate(
1616
+ (node) => node instanceof HTMLSelectElement && !node.multiple ? Array.from(node.options).map((option) => ({
1617
+ label: (option.label || option.text).replace(/\s+/g, " ").trim(),
1618
+ disabled: option.disabled || option.parentElement instanceof HTMLOptGroupElement && option.parentElement.disabled
1619
+ })) : null
1620
+ ).catch(() => null);
1621
+ if (native) {
1622
+ const label = options.chooseOption(
1623
+ native.map((option) => option.label)
1624
+ );
1625
+ const index = native.findIndex((option) => option.label === label);
1626
+ if (label === null || index < 0)
1627
+ return {
1628
+ actionable: false,
1629
+ reason: "option_not_named",
1630
+ options: native.filter((option) => !option.disabled).map((option) => option.label)
1631
+ };
1632
+ if (native[index].disabled)
1633
+ return { actionable: false, reason: "not_actionable" };
1634
+ const hide2 = await this.highlight(element);
1635
+ try {
1636
+ await element.selectOption({ index }, { timeout: remaining() });
1637
+ return { actionable: true, aim };
1638
+ } catch (error2) {
1639
+ return {
1640
+ actionable: false,
1641
+ reason: "action_started",
1642
+ retryable: false,
1643
+ callLog: safeCallLog(error2)
1644
+ };
1645
+ } finally {
1646
+ await hide2();
1647
+ }
1648
+ }
1649
+ }
1555
1650
  const hide = await this.highlight(element);
1556
1651
  try {
1557
1652
  await element.click({ position: aim.point, timeout: remaining() });
@@ -1941,8 +2036,8 @@ var StepExecutionError = class extends Error {
1941
2036
  phase;
1942
2037
  retryable;
1943
2038
  callLog;
1944
- constructor(op, code, phase, callLog = []) {
1945
- super(`${op} failed: ${code}`);
2039
+ constructor(op, code, phase, callLog = [], detail) {
2040
+ super(detail ?? `${op} failed: ${code}`);
1946
2041
  this.name = "StepExecutionError";
1947
2042
  this.op = op;
1948
2043
  this.code = code;
@@ -2063,7 +2158,20 @@ async function executeStep(page, command, options = {}) {
2063
2158
  if (options.signal?.aborted)
2064
2159
  throw new StepExecutionError(op, "canceled", phase);
2065
2160
  phase = "post_dispatch";
2066
- const result = await active(page.clickRef(aimed.aim, { timeoutMs }));
2161
+ const result = await active(
2162
+ page.clickRef(aimed.aim, {
2163
+ timeoutMs,
2164
+ ...command.chooseOption ? { chooseOption: command.chooseOption } : {}
2165
+ })
2166
+ );
2167
+ if (!result.actionable && result.reason === "option_not_named")
2168
+ throw new StepExecutionError(
2169
+ op,
2170
+ "invalid_input",
2171
+ "pre_dispatch",
2172
+ [],
2173
+ result.options.length ? `This is a dropdown. Name the option to choose, one of: ${result.options.slice(0, 12).map((label) => `"${label}"`).join(", ")}${result.options.length > 12 ? ", \u2026" : ""}.` : "This is a dropdown with no option that can be chosen."
2174
+ );
2067
2175
  if (!result.actionable)
2068
2176
  throw new StepExecutionError(
2069
2177
  op,
@@ -2166,16 +2274,21 @@ ${(result.callLog ?? []).join("\n")}`)
2166
2274
  };
2167
2275
  } catch (error2) {
2168
2276
  if (error2 instanceof StepExecutionError) throw error2;
2277
+ const network = error2 instanceof Error ? /\((net::ERR_[A-Z_]+|timeout)\)/.exec(error2.message)?.[1] : void 0;
2169
2278
  throw new StepExecutionError(
2170
2279
  op,
2171
2280
  "operation_failed",
2172
2281
  phase,
2173
- safeCallLog(error2)
2282
+ safeCallLog(error2),
2283
+ network ? `${op} failed: ${network}` : void 0
2174
2284
  );
2175
2285
  }
2176
2286
  }
2177
2287
 
2178
2288
  // src/provider.ts
2289
+ function isRunWideProviderError(error2) {
2290
+ return error2 instanceof ProviderError && (error2.code === "authentication" || error2.code === "configuration" || error2.code === "rate-limited");
2291
+ }
2179
2292
  var ProviderError = class extends Error {
2180
2293
  constructor(code, message, attempts = 0, failedCall) {
2181
2294
  super(message);
@@ -2396,6 +2509,9 @@ function sameVisualVersion(a, b) {
2396
2509
  }
2397
2510
  async function captureVisionObservation(page, candidates, version, instruction, projectText = (text) => text) {
2398
2511
  if (!page.captureFrame) return null;
2512
+ const settled = await quietPage(page, 1e3, 4e3);
2513
+ if (!settled.quiet || !sameVisualVersion(settled.version, version))
2514
+ return null;
2399
2515
  const visual = await visualCandidates(page);
2400
2516
  if (!sameVisualVersion(visual.version, version)) return null;
2401
2517
  const boxes = visual.boxes.filter(
@@ -2434,6 +2550,22 @@ async function captureVisionObservation(page, candidates, version, instruction,
2434
2550
  }
2435
2551
  };
2436
2552
  }
2553
+ async function probeOpenRouterKey(apiKey, options = {}) {
2554
+ try {
2555
+ const response = await fetch("https://openrouter.ai/api/v1/key", {
2556
+ headers: { Authorization: `Bearer ${apiKey}` },
2557
+ signal: AbortSignal.any([
2558
+ AbortSignal.timeout(options.timeoutMs ?? 5e3),
2559
+ ...options.signal ? [options.signal] : []
2560
+ ])
2561
+ });
2562
+ await response.body?.cancel().catch(() => void 0);
2563
+ if (response.ok) return "accepted";
2564
+ return response.status === 401 || response.status === 403 ? "rejected" : "unreachable";
2565
+ } catch {
2566
+ return "unreachable";
2567
+ }
2568
+ }
2437
2569
 
2438
2570
  // src/locator.ts
2439
2571
  var MAX_CANDIDATES = 4096;
@@ -3220,7 +3352,14 @@ async function resolveTarget(page, resolver, options) {
3220
3352
  confidence = decision.confidence;
3221
3353
  if (decision.selection.kind === "none") {
3222
3354
  const fallback = codeFallback ? codeAfterNone(options.sentence, candidates) : null;
3223
- if (!fallback) return unresolved("none");
3355
+ if (!fallback) {
3356
+ if (options.visionResolver && options.operation === "click") {
3357
+ gate = "none";
3358
+ const seen = await ambiguous(candidates);
3359
+ return seen.kind === "unresolved" && seen.reason === "ambiguous" ? { ...seen, reason: "none" } : seen;
3360
+ }
3361
+ return unresolved("none");
3362
+ }
3224
3363
  gate = "resolved_in_code_after_none";
3225
3364
  if (options.operation === "fill" && !fallback.editable)
3226
3365
  return unresolved("not_fillable");
@@ -3390,7 +3529,13 @@ async function resolveTarget(page, resolver, options) {
3390
3529
  options.projectText
3391
3530
  );
3392
3531
  ensureActive();
3393
- if (!captured) return unresolved("ambiguous");
3532
+ if (!captured) {
3533
+ if (!sameVersion3(await pageVersion(page), source.version)) {
3534
+ gate = `${gate}:vision_stale_capture`;
3535
+ return unresolved("stale");
3536
+ }
3537
+ return unresolved("ambiguous");
3538
+ }
3394
3539
  let answer;
3395
3540
  const visionStarted = performance.now();
3396
3541
  try {
@@ -3423,11 +3568,16 @@ async function resolveTarget(page, resolver, options) {
3423
3568
  };
3424
3569
  ensureActive();
3425
3570
  if (!sameVersion3(await pageVersion(page), source.version)) {
3571
+ visionDiagnostic = { ...visionDiagnostic, failure: "stale_page" };
3426
3572
  gate = `${gate}:vision_stale`;
3427
3573
  return unresolved("ambiguous");
3428
3574
  }
3429
3575
  if (answer.decision.kind !== "candidate") {
3430
- visionDiagnostic = { ...visionDiagnostic, outcome: "abstained" };
3576
+ visionDiagnostic = {
3577
+ ...visionDiagnostic,
3578
+ outcome: "abstained",
3579
+ abstentionReason: answer.decision.reason
3580
+ };
3431
3581
  gate = `${gate}:vision_abstained`;
3432
3582
  return unresolved("ambiguous");
3433
3583
  }
@@ -3446,8 +3596,13 @@ async function resolveTarget(page, resolver, options) {
3446
3596
  diagnostic: { ...result.diagnostic, vision: visionDiagnostic }
3447
3597
  };
3448
3598
  }
3599
+ visionDiagnostic = { ...visionDiagnostic, failure: "stale_page" };
3449
3600
  return unresolved("ambiguous");
3450
3601
  } catch {
3602
+ if (!sameVersion3(await pageVersion(page), source.version)) {
3603
+ gate = `${gate}:vision_stale_capture`;
3604
+ return unresolved("stale");
3605
+ }
3451
3606
  gate = `${gate}:vision_unavailable`;
3452
3607
  return unresolved("ambiguous");
3453
3608
  }
@@ -3533,6 +3688,7 @@ async function resolveTarget(page, resolver, options) {
3533
3688
  targetChanged: false
3534
3689
  };
3535
3690
  if (controller.signal.aborted) return unresolved("timeout");
3691
+ if (isRunWideProviderError(error2)) throw error2;
3536
3692
  if (error2 instanceof LocatorError) return unresolved(error2.reason);
3537
3693
  if (error2 instanceof PageScriptError) return unresolved("incomplete");
3538
3694
  return unresolved("provider_error");
@@ -3544,11 +3700,11 @@ async function resolveTarget(page, resolver, options) {
3544
3700
 
3545
3701
  // src/flow-types.ts
3546
3702
  function isFullyValidated(coverage, diagnostics) {
3547
- return coverage.format === "passed" && coverage.steps === "checked" && (coverage.modules === "not_needed" || coverage.modules === "checked") && !diagnostics.some((diagnostic2) => diagnostic2.severity === "error");
3703
+ return coverage.format === "passed" && coverage.steps === "checked" && (coverage.modules === "not_needed" || coverage.modules === "checked") && !diagnostics.some((diagnostic3) => diagnostic3.severity === "error");
3548
3704
  }
3549
- function formatFlowDiagnostic(diagnostic2) {
3550
- const { file, line, col } = diagnostic2.source;
3551
- return `${file}:${line}:${col}: ${diagnostic2.message} ${diagnostic2.fix}`;
3705
+ function formatFlowDiagnostic(diagnostic3) {
3706
+ const { file, line, col } = diagnostic3.source;
3707
+ return `${file}:${line}:${col}: ${diagnostic3.message} ${diagnostic3.fix}`;
3552
3708
  }
3553
3709
 
3554
3710
  // src/flow-values.ts
@@ -3570,8 +3726,8 @@ function redactOpaqueText(text, entries) {
3570
3726
  }
3571
3727
  var DataResolutionError = class extends Error {
3572
3728
  code = "missing_environment_variable";
3573
- constructor(dataKey, variable, declared) {
3574
- const { file, line, col } = declared.source;
3729
+ constructor(dataKey, variable, declared2) {
3730
+ const { file, line, col } = declared2.source;
3575
3731
  super(
3576
3732
  `${file}:${line}:${col}: data.${dataKey} needs $${variable}, which is not set`
3577
3733
  );
@@ -3635,11 +3791,11 @@ function parseDataTemplate(value) {
3635
3791
  if (literal) parts.push({ literal });
3636
3792
  return { parts };
3637
3793
  }
3638
- function resolveData(declared, env) {
3794
+ function resolveData(declared2, env) {
3639
3795
  const resolved = /* @__PURE__ */ Object.create(
3640
3796
  null
3641
3797
  );
3642
- for (const [key, item] of Object.entries(declared)) {
3798
+ for (const [key, item] of Object.entries(declared2)) {
3643
3799
  if (typeof item.value !== "string") {
3644
3800
  resolved[key] = {
3645
3801
  value: new RuntimeValue(String(item.value), `{{${key}}}`),
@@ -3881,8 +4037,11 @@ import { z as z3 } from "zod";
3881
4037
  // src/project-discovery.ts
3882
4038
  import { readdir, realpath, stat } from "fs/promises";
3883
4039
  import path2 from "path";
3884
- var TEST_SUFFIX = ".test.yaml";
4040
+ var TEST_SUFFIXES = [".test.yaml", ".test.ts"];
3885
4041
  var MODULE_SUFFIX = ".module.yaml";
4042
+ function isTestFile(name) {
4043
+ return TEST_SUFFIXES.some((suffix) => name.endsWith(suffix));
4044
+ }
3886
4045
  function contains(root, candidate) {
3887
4046
  const relative = path2.relative(root, candidate);
3888
4047
  return relative === "" || relative !== ".." && !relative.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative);
@@ -3924,7 +4083,7 @@ async function discoverProjectFiles(paths, options) {
3924
4083
  fix: "Run the command from the project root, or pass paths inside it."
3925
4084
  });
3926
4085
  const add2 = (file) => {
3927
- if (file.endsWith(TEST_SUFFIX)) tests.add(file);
4086
+ if (isTestFile(file)) tests.add(file);
3928
4087
  else modules.add(file);
3929
4088
  };
3930
4089
  for (const requested of paths.length ? paths : ["."]) {
@@ -3949,7 +4108,7 @@ async function discoverProjectFiles(paths, options) {
3949
4108
  }
3950
4109
  const found = await walkSuiteFiles(
3951
4110
  real,
3952
- [TEST_SUFFIX, MODULE_SUFFIX],
4111
+ [...TEST_SUFFIXES, MODULE_SUFFIX],
3953
4112
  (folder) => problems.push({
3954
4113
  code: "unreadable_directory",
3955
4114
  path: path2.relative(root, folder) || ".",
@@ -3961,11 +4120,11 @@ async function discoverProjectFiles(paths, options) {
3961
4120
  continue;
3962
4121
  }
3963
4122
  const name = path2.basename(absolute);
3964
- if (!name.endsWith(TEST_SUFFIX) && !name.endsWith(MODULE_SUFFIX)) {
4123
+ if (!isTestFile(name) && !name.endsWith(MODULE_SUFFIX)) {
3965
4124
  problems.push({
3966
4125
  code: "unsupported_file",
3967
4126
  path: requested,
3968
- message: `${requested} is not a *.test.yaml or *.module.yaml file.`,
4127
+ message: `${requested} is not a *.test.ts, *.test.yaml, or *.module.yaml file.`,
3969
4128
  fix: "Pass a test file, a module file, or a directory."
3970
4129
  });
3971
4130
  continue;
@@ -4439,7 +4598,7 @@ function parseFlow(source, file, options) {
4439
4598
  "error",
4440
4599
  "invalid_test_mode",
4441
4600
  at(file, counter, nodes, []),
4442
- "This test needs either a `steps` list or a `goal`, but not both.",
4601
+ plain.goal === void 0 ? "This test has neither a `steps` list nor a `goal`." : "This test has both a `steps` list and a `goal`; use one.",
4443
4602
  "Use `steps` for authored actions, or `goal` with a required `verify` claim."
4444
4603
  );
4445
4604
  if (plain.goal === void 0 !== (plain.verify === void 0))
@@ -4553,7 +4712,7 @@ function parseFlow(source, file, options) {
4553
4712
  (step) => step.kind === "module"
4554
4713
  );
4555
4714
  const format = diagnostics.some(
4556
- (diagnostic2) => diagnostic2.severity === "error"
4715
+ (diagnostic3) => diagnostic3.severity === "error"
4557
4716
  ) ? "failed" : "passed";
4558
4717
  if (!input)
4559
4718
  return {
@@ -4647,7 +4806,7 @@ function validateFlows(inputs, options) {
4647
4806
  files,
4648
4807
  diagnostics,
4649
4808
  coverage: {
4650
- format: diagnostics.some((diagnostic2) => diagnostic2.severity === "error") ? "failed" : "passed",
4809
+ format: diagnostics.some((diagnostic3) => diagnostic3.severity === "error") ? "failed" : "passed",
4651
4810
  steps: "not_checked",
4652
4811
  modules: files.some((file) => file.coverage.modules === "not_checked") ? "not_checked" : "not_needed"
4653
4812
  }
@@ -4831,7 +4990,7 @@ async function loadFlowFile(file, options) {
4831
4990
  await handle.close();
4832
4991
  }
4833
4992
  } catch {
4834
- const diagnostic2 = {
4993
+ const diagnostic3 = {
4835
4994
  severity: "error",
4836
4995
  code: "unreadable_file",
4837
4996
  source: { file, line: 1, col: 1 },
@@ -4839,7 +4998,7 @@ async function loadFlowFile(file, options) {
4839
4998
  fix: "Check the path and file permissions."
4840
4999
  };
4841
5000
  return {
4842
- diagnostics: [diagnostic2],
5001
+ diagnostics: [diagnostic3],
4843
5002
  coverage: {
4844
5003
  format: "failed",
4845
5004
  steps: "not_checked",
@@ -4979,14 +5138,14 @@ async function resolveFlowModules(parsed, options) {
4979
5138
  expanded2.push({ ...step, phase, sourceStack: stack });
4980
5139
  continue;
4981
5140
  }
4982
- const loaded = await load(canonical);
4983
- diagnostics.push(...loaded.diagnostics);
4984
- const module = loaded.value;
5141
+ const loaded2 = await load(canonical);
5142
+ diagnostics.push(...loaded2.diagnostics);
5143
+ const module = loaded2.value;
4985
5144
  if (!module) {
4986
5145
  expanded2.push({ ...step, phase, sourceStack: stack });
4987
5146
  continue;
4988
5147
  }
4989
- const declared = new Set(module.parameters);
5148
+ const declared2 = new Set(module.parameters);
4990
5149
  const supplied = Object.keys(step.with);
4991
5150
  for (const parameter of module.parameters)
4992
5151
  if (!Object.hasOwn(step.with, parameter))
@@ -4998,7 +5157,7 @@ async function resolveFlowModules(parsed, options) {
4998
5157
  `Add \`${parameter}\` under with.`
4999
5158
  );
5000
5159
  for (const argument of supplied)
5001
- if (!declared.has(argument))
5160
+ if (!declared2.has(argument))
5002
5161
  diagnostics.push({
5003
5162
  severity: "error",
5004
5163
  code: "unknown_module_argument",
@@ -5150,12 +5309,16 @@ function preflightSentence(sentence) {
5150
5309
  function patternOperation(sentence) {
5151
5310
  const text = canonicalSentence(sentence);
5152
5311
  if (preflightSentence(text)) return null;
5153
- if (/^(?:click|type|enter|fill|press|goto|go\s+to|navigate\s+to|scroll|wait|remember)\b/iu.test(
5312
+ if (/^(?:click|type|enter|fill|press|goto|go\s+to|navigate\s+to|scroll|wait|remember|select|choose|pick)\b/iu.test(
5154
5313
  text
5155
5314
  ) && (withoutQuotes(text).match(SECOND_ACTION_CONNECTOR) !== null || /;|,\s*[A-Za-z]/u.test(withoutQuotes(text))))
5156
5315
  return null;
5157
5316
  if (/^remember\b/iu.test(text) && BINDING.test(text)) return "remember";
5158
5317
  if (/^click\s+\S/iu.test(text)) return "click";
5318
+ if (/^(?:select|choose|pick)\s+(?:"[^"]+"|“[^”]+”)\s+(?:in|from)\s+\S/iu.test(
5319
+ text
5320
+ ))
5321
+ return "click";
5159
5322
  if (VALUE.test(text)) return "type";
5160
5323
  if (/^press\s+(?:the\s+)?(?:"[^"]+"|\S+)/iu.test(text)) return "press";
5161
5324
  if (/^(?:goto|go\s+to|navigate\s+to)\s+https?:\/\/\S+/iu.test(text))
@@ -5445,8 +5608,8 @@ function validEntry2(value) {
5445
5608
  return decision.accepted;
5446
5609
  }
5447
5610
  var FileClassificationCache = class _FileClassificationCache {
5448
- constructor(path7, requestedModel, entries, loadReason, invalidKeys) {
5449
- this.path = path7;
5611
+ constructor(path11, requestedModel, entries, loadReason, invalidKeys) {
5612
+ this.path = path11;
5450
5613
  this.requestedModel = requestedModel;
5451
5614
  this.loadReason = loadReason;
5452
5615
  this.invalidKeys = invalidKeys;
@@ -5458,12 +5621,12 @@ var FileClassificationCache = class _FileClassificationCache {
5458
5621
  invalidKeys;
5459
5622
  entries;
5460
5623
  dirty = false;
5461
- static async load(path7, requestedModel) {
5624
+ static async load(path11, requestedModel) {
5462
5625
  try {
5463
- const value = JSON.parse(await fs.readFile(path7, "utf8"));
5626
+ const value = JSON.parse(await fs.readFile(path11, "utf8"));
5464
5627
  if (!value || typeof value !== "object" || Array.isArray(value))
5465
5628
  return new _FileClassificationCache(
5466
- path7,
5629
+ path11,
5467
5630
  requestedModel,
5468
5631
  {},
5469
5632
  "corrupt",
@@ -5472,7 +5635,7 @@ var FileClassificationCache = class _FileClassificationCache {
5472
5635
  const file = value;
5473
5636
  if (file.version !== FORMAT_VERSION)
5474
5637
  return new _FileClassificationCache(
5475
- path7,
5638
+ path11,
5476
5639
  requestedModel,
5477
5640
  {},
5478
5641
  "format_mismatch",
@@ -5480,7 +5643,7 @@ var FileClassificationCache = class _FileClassificationCache {
5480
5643
  );
5481
5644
  if (!file.entries || typeof file.entries !== "object" || Array.isArray(file.entries))
5482
5645
  return new _FileClassificationCache(
5483
- path7,
5646
+ path11,
5484
5647
  requestedModel,
5485
5648
  {},
5486
5649
  "corrupt",
@@ -5494,7 +5657,7 @@ var FileClassificationCache = class _FileClassificationCache {
5494
5657
  else invalidKeys[key] = "invalid_or_incompatible";
5495
5658
  }
5496
5659
  return new _FileClassificationCache(
5497
- path7,
5660
+ path11,
5498
5661
  requestedModel,
5499
5662
  entries,
5500
5663
  "ok",
@@ -5503,14 +5666,14 @@ var FileClassificationCache = class _FileClassificationCache {
5503
5666
  } catch (error2) {
5504
5667
  if (error2.code === "ENOENT")
5505
5668
  return new _FileClassificationCache(
5506
- path7,
5669
+ path11,
5507
5670
  requestedModel,
5508
5671
  {},
5509
5672
  "absent",
5510
5673
  {}
5511
5674
  );
5512
5675
  return new _FileClassificationCache(
5513
- path7,
5676
+ path11,
5514
5677
  requestedModel,
5515
5678
  {},
5516
5679
  "corrupt",
@@ -5697,7 +5860,9 @@ async function classifyParsedFlow(parsed, options) {
5697
5860
  }
5698
5861
 
5699
5862
  // src/project-validation.ts
5863
+ import { existsSync as existsSync3, realpathSync, statSync as statSync2 } from "fs";
5700
5864
  import { readFile as readFile2 } from "fs/promises";
5865
+ import path7 from "path";
5701
5866
 
5702
5867
  // src/flow-runner.ts
5703
5868
  import path5 from "path";
@@ -5886,6 +6051,7 @@ async function judgePage(page, judge, claim2, timeoutMs, signal, projectText) {
5886
6051
  probability2(decision.contradicted, "contradicted");
5887
6052
  } catch (error2) {
5888
6053
  if (error2 instanceof AssertionEngineError) throw error2;
6054
+ if (isRunWideProviderError(error2)) throw error2;
5889
6055
  if (decision)
5890
6056
  throw new AssertionEngineError(
5891
6057
  signal?.aborted ? "canceled" : "provider_failure",
@@ -6005,7 +6171,7 @@ function goalOperations(state2) {
6005
6171
  ])
6006
6172
  ),
6007
6173
  DONE: "All goal requirements are visibly satisfied; request independent verification",
6008
- BLOCKED: "No supported operation can safely progress; abstain"
6174
+ BLOCKED: "No offered element or field can move the goal forward from this page; abstain"
6009
6175
  };
6010
6176
  }
6011
6177
  function goalChoiceAccepted(answer, ids, minMargin = 0.1) {
@@ -6076,7 +6242,7 @@ async function runGoal(page, planner, judge, options) {
6076
6242
  let actions = 0;
6077
6243
  let pendingCall = false;
6078
6244
  let reportedCalls = 0;
6079
- const result = (reason) => ({
6245
+ const result = (reason, detail) => ({
6080
6246
  status: reason === "verified" ? "passed" : "failed",
6081
6247
  reason,
6082
6248
  requests,
@@ -6084,8 +6250,18 @@ async function runGoal(page, planner, judge, options) {
6084
6250
  elapsedMs: Math.round(performance.now() - started),
6085
6251
  calls,
6086
6252
  history,
6253
+ ...detail ? { detail } : {},
6087
6254
  verification
6088
6255
  });
6256
+ const uncertain = (what, answer, route, label = (choice) => choice) => {
6257
+ let where = route;
6258
+ try {
6259
+ where = new URL(route).pathname || route;
6260
+ } catch {
6261
+ }
6262
+ 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
+ return project(`${what} on ${where}: ${top}`);
6264
+ };
6089
6265
  const seen = /* @__PURE__ */ new Map();
6090
6266
  try {
6091
6267
  while (!signal.aborted) {
@@ -6182,7 +6358,10 @@ async function runGoal(page, planner, judge, options) {
6182
6358
  Object.keys(goalOperations(state2)),
6183
6359
  operationMinMargin
6184
6360
  ))
6185
- return result("operation_abstention");
6361
+ return result(
6362
+ "operation_abstention",
6363
+ uncertain("operation", decision.operation, digest.version.route)
6364
+ );
6186
6365
  if (!same(digest.version, await active(pageVersion(page)))) continue;
6187
6366
  const op = decision.operation.choice;
6188
6367
  if (op === "BLOCKED") return result("blocked");
@@ -6222,7 +6401,19 @@ async function runGoal(page, planner, judge, options) {
6222
6401
  }
6223
6402
  const head = decision.target;
6224
6403
  if (!head || !goalChoiceAccepted(head, Object.keys(state2.targets[op] ?? {})))
6225
- return result("target_abstention");
6404
+ return result(
6405
+ "target_abstention",
6406
+ uncertain(`${op} target`, head, digest.version.route, (id) => {
6407
+ const name = (() => {
6408
+ try {
6409
+ return JSON.parse(state2.targets[op]?.[id] ?? "{}").name;
6410
+ } catch {
6411
+ return void 0;
6412
+ }
6413
+ })();
6414
+ return name ? `"${name}"` : id;
6415
+ })
6416
+ );
6226
6417
  const command = commands.get(head.choice);
6227
6418
  if (!command) return result("invalid_target");
6228
6419
  if (actions >= maxActions) return result("action_limit");
@@ -6265,6 +6456,11 @@ async function runGoal(page, planner, judge, options) {
6265
6456
  failed = true;
6266
6457
  failure = error2;
6267
6458
  }
6459
+ if (failed && failure instanceof StepExecutionError && failure.code === "stale" && failure.phase === "pre_dispatch" && !signal.aborted) {
6460
+ actions--;
6461
+ history.pop();
6462
+ continue;
6463
+ }
6268
6464
  await options.onAction?.({
6269
6465
  operation: command.op,
6270
6466
  sentence,
@@ -6293,6 +6489,130 @@ async function runGoal(page, planner, judge, options) {
6293
6489
  }
6294
6490
  }
6295
6491
 
6492
+ // src/dropdown-option.ts
6493
+ function chooseOption(sentence, labels) {
6494
+ const norm = (text2) => text2.normalize("NFC").replace(/\s+/gu, " ").trim().toLowerCase();
6495
+ const usable = [...new Set(labels.filter((label) => norm(label)))];
6496
+ const quoted = [...sentence.matchAll(/"([^"]+)"|“([^”]+)”/gu)].map(
6497
+ (match) => norm(match[1] ?? match[2] ?? "")
6498
+ );
6499
+ const byQuote = usable.filter((label) => quoted.includes(norm(label)));
6500
+ if (byQuote.length === 1) return byQuote[0];
6501
+ if (byQuote.length > 1) return null;
6502
+ const text = ` ${norm(sentence).replace(/[.,;:!?]+$/u, "")} `;
6503
+ const named = usable.filter((label) => {
6504
+ const needle = norm(label);
6505
+ let index = text.indexOf(needle);
6506
+ while (index >= 0) {
6507
+ const before = text[index - 1] ?? " ";
6508
+ const after = text[index + needle.length] ?? " ";
6509
+ if (!/[\p{L}\p{N}]/u.test(before) && !/[\p{L}\p{N}]/u.test(after))
6510
+ return true;
6511
+ index = text.indexOf(needle, index + 1);
6512
+ }
6513
+ return false;
6514
+ });
6515
+ const distinct = named.filter(
6516
+ (label) => !named.some(
6517
+ (other) => other !== label && norm(other).includes(norm(label))
6518
+ )
6519
+ );
6520
+ return distinct.length === 1 ? distinct[0] : null;
6521
+ }
6522
+
6523
+ // src/step-operands.ts
6524
+ var PLAYWRIGHT_KEYS = {
6525
+ enter: "Enter",
6526
+ return: "Enter",
6527
+ tab: "Tab",
6528
+ escape: "Escape",
6529
+ esc: "Escape",
6530
+ space: "Space",
6531
+ spacebar: "Space",
6532
+ backspace: "Backspace",
6533
+ delete: "Delete",
6534
+ del: "Delete",
6535
+ home: "Home",
6536
+ end: "End",
6537
+ pageup: "PageUp",
6538
+ pagedown: "PageDown",
6539
+ arrowup: "ArrowUp",
6540
+ arrowdown: "ArrowDown",
6541
+ arrowleft: "ArrowLeft",
6542
+ arrowright: "ArrowRight",
6543
+ up: "ArrowUp",
6544
+ down: "ArrowDown",
6545
+ left: "ArrowLeft",
6546
+ right: "ArrowRight",
6547
+ ...Object.fromEntries(
6548
+ Array.from({ length: 12 }, (_, index) => [
6549
+ `f${index + 1}`,
6550
+ `F${index + 1}`
6551
+ ])
6552
+ )
6553
+ };
6554
+ var MODIFIERS = {
6555
+ ctrl: "Control",
6556
+ control: "Control",
6557
+ shift: "Shift",
6558
+ alt: "Alt",
6559
+ option: "Alt",
6560
+ cmd: "Meta",
6561
+ command: "Meta",
6562
+ meta: "Meta",
6563
+ controlormeta: "ControlOrMeta"
6564
+ };
6565
+ function playwrightKey(name) {
6566
+ const parts = name.trim().split(/\s*\+\s*/u);
6567
+ if (parts.some((part) => !part)) return null;
6568
+ const key = parts.pop();
6569
+ const modifiers = parts.map((part) => MODIFIERS[part.toLowerCase()]);
6570
+ if (modifiers.some((modifier) => modifier === void 0)) return null;
6571
+ const main = PLAYWRIGHT_KEYS[key.toLowerCase()] ?? (Array.from(key).length === 1 ? key : null);
6572
+ return main ? [...modifiers, main].join("+") : null;
6573
+ }
6574
+ function pressKey(sentence) {
6575
+ const text = canonicalSentence(sentence);
6576
+ const quoted = /"([^"]+)"/u.exec(text);
6577
+ if (quoted) return playwrightKey(quoted[1]);
6578
+ const keyMention = /\b([\w+-]+)\s+key\b/iu.exec(text);
6579
+ if (keyMention) return playwrightKey(keyMention[1]);
6580
+ const explicit = /^(?:press|hit|strike)\s+(?:the\s+)?([\w+-]+)\s*\.?$/iu.exec(
6581
+ text
6582
+ );
6583
+ return explicit ? playwrightKey(explicit[1]) : null;
6584
+ }
6585
+ function waitDurationMs(sentence) {
6586
+ const match = /\b(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|seconds?)\b/iu.exec(
6587
+ canonicalSentence(sentence)
6588
+ );
6589
+ if (!match) return null;
6590
+ const amount = Number(match[1]);
6591
+ const ms = match[2].toLowerCase().startsWith("m") ? amount : amount * 1e3;
6592
+ return Number.isFinite(ms) && ms > 0 && ms <= 3e4 ? Math.round(ms) : null;
6593
+ }
6594
+ function scrollDirection(sentence) {
6595
+ const match = /\b(up|down)\b/iu.exec(canonicalSentence(sentence));
6596
+ return match ? match[1].toLowerCase() : null;
6597
+ }
6598
+ function gotoUrlParts(sentence) {
6599
+ const urls = canonicalSentence(sentence).match(/https?:\/\/\S+/giu) ?? [];
6600
+ if (urls.length !== 1) return null;
6601
+ const url = urls[0].replace(/[.,;]+$/u, "");
6602
+ const literals = [];
6603
+ const names = [];
6604
+ let rest = url;
6605
+ for (; ; ) {
6606
+ const match = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/u.exec(rest);
6607
+ if (!match) break;
6608
+ literals.push(rest.slice(0, match.index));
6609
+ names.push(match[1]);
6610
+ rest = rest.slice(match.index + match[0].length);
6611
+ }
6612
+ literals.push(rest);
6613
+ return { literals, names };
6614
+ }
6615
+
6296
6616
  // src/flow-runner.ts
6297
6617
  function resultCall(call2, purpose, apiMs = null) {
6298
6618
  return {
@@ -6315,14 +6635,14 @@ function resultCall(call2, purpose, apiMs = null) {
6315
6635
  };
6316
6636
  }
6317
6637
  function firstDiagnostic(diagnostics) {
6318
- const diagnostic2 = diagnostics.find((item) => item.severity === "error");
6638
+ const diagnostic3 = diagnostics.find((item) => item.severity === "error");
6319
6639
  return {
6320
6640
  status: "could_not_run",
6321
- file: diagnostic2?.source.file ?? "",
6641
+ file: diagnostic3?.source.file ?? "",
6322
6642
  code: "invalid_test",
6323
- message: diagnostic2?.message ?? "The test file could not be validated.",
6324
- ...diagnostic2?.fix ? { fix: diagnostic2.fix } : {},
6325
- ...diagnostic2 ? { source: diagnostic2.source } : {}
6643
+ message: diagnostic3?.message ?? "The test file could not be validated.",
6644
+ ...diagnostic3?.fix ? { fix: diagnostic3.fix } : {},
6645
+ ...diagnostic3 ? { source: diagnostic3.source } : {}
6326
6646
  };
6327
6647
  }
6328
6648
  function unsupported(file, source, message) {
@@ -6334,6 +6654,46 @@ function unsupported(file, source, message) {
6334
6654
  message
6335
6655
  };
6336
6656
  }
6657
+ function providerFailure(file, error2) {
6658
+ const details = {
6659
+ "rate-limited": {
6660
+ message: "The provider kept rate limiting requests for five minutes.",
6661
+ fix: "Lower --parallel or --provider-concurrency, or retry later."
6662
+ },
6663
+ authentication: {
6664
+ 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."
6666
+ },
6667
+ configuration: {
6668
+ 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."
6670
+ }
6671
+ };
6672
+ return {
6673
+ status: "could_not_run",
6674
+ file,
6675
+ code: error2.code === "rate-limited" ? "provider_rate_limited" : `provider_${error2.code}`,
6676
+ ...details[error2.code] ?? {
6677
+ message: "The model provider could not complete the run safely.",
6678
+ fix: "Check provider availability and the test input, then rerun the test."
6679
+ }
6680
+ };
6681
+ }
6682
+ function navigationWhy(error2) {
6683
+ const code = /(net::ERR_[A-Z_]+|timeout)$/.exec(error2.message)?.[1];
6684
+ if (!code) return "the browser could not load it";
6685
+ if (code === "timeout" || code.includes("TIMED_OUT"))
6686
+ return "it took too long to respond";
6687
+ if (code === "net::ERR_NAME_NOT_RESOLVED")
6688
+ return "the host name could not be resolved (DNS)";
6689
+ if (code === "net::ERR_CONNECTION_REFUSED")
6690
+ return "the server refused the connection";
6691
+ if (code === "net::ERR_INTERNET_DISCONNECTED")
6692
+ return "there is no network connection";
6693
+ if (code.startsWith("net::ERR_CERT_"))
6694
+ return "its TLS certificate was rejected";
6695
+ return `the browser reported ${code}`;
6696
+ }
6337
6697
  function runtimeFailure(file, error2) {
6338
6698
  if (error2 instanceof BrowserDriverError) {
6339
6699
  const details = {
@@ -6377,23 +6737,15 @@ function runtimeFailure(file, error2) {
6377
6737
  ...details[error2.code]
6378
6738
  };
6379
6739
  }
6380
- if (error2 instanceof ProviderError) {
6381
- if (error2.code === "rate-limited")
6382
- return {
6383
- status: "could_not_run",
6384
- file,
6385
- code: "provider_rate_limited",
6386
- message: "The provider kept rate limiting requests for five minutes.",
6387
- fix: "Lower --parallel or --provider-concurrency, or retry later."
6388
- };
6740
+ if (error2 instanceof ProviderError) return providerFailure(file, error2);
6741
+ if (error2 instanceof StepExecutionError && error2.op === "goto")
6389
6742
  return {
6390
6743
  status: "could_not_run",
6391
6744
  file,
6392
- code: `provider_${error2.code}`,
6393
- message: "The model provider could not complete the run safely.",
6394
- fix: error2.code === "configuration" || error2.code === "authentication" ? "Check the configured provider API key and access, then rerun the test." : "Check provider availability and the test input, then rerun the test."
6745
+ code: "navigation_failed",
6746
+ message: `Could not open the test's page: ${navigationWhy(error2)}.`,
6747
+ fix: "Check the test's url (or baseUrl), your network or VPN, and that the site is up."
6395
6748
  };
6396
- }
6397
6749
  return {
6398
6750
  status: "could_not_run",
6399
6751
  file,
@@ -6404,7 +6756,7 @@ function runtimeFailure(file, error2) {
6404
6756
  }
6405
6757
  function claim(step, data) {
6406
6758
  return step.text.replace(
6407
- /^\s*(?:verify|assert|check|confirm|ensure|expect)\b\s*(?:that\s+)?/iu,
6759
+ /^\s*(?:verify|assert|check|confirm|ensure|expect|measure|note|observe)\b\s*(?:that\s+|whether\s+|if\s+)?/iu,
6408
6760
  ""
6409
6761
  ).trim().replace(
6410
6762
  /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu,
@@ -6440,7 +6792,51 @@ function resolveEntryUrl(testUrl, baseUrl, urlOverride) {
6440
6792
  async function closeQuietly(resource) {
6441
6793
  await resource?.close().catch(() => void 0);
6442
6794
  }
6443
- async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6795
+ var LocateRetryError = class extends Error {
6796
+ constructor(priorCalls) {
6797
+ super("The target could not be resolved.");
6798
+ this.priorCalls = priorCalls;
6799
+ }
6800
+ priorCalls;
6801
+ };
6802
+ async function reobserve(page, first, locate, options) {
6803
+ let resolved = first;
6804
+ if (options.staleRetry && resolved.kind === "unresolved" && resolved.reason === "stale") {
6805
+ const priorCalls = resolved.calls;
6806
+ const settled = await quietPage(page, 1e3, 4e3).catch(() => ({
6807
+ quiet: false
6808
+ }));
6809
+ if (settled.quiet) {
6810
+ try {
6811
+ const retried = await locate();
6812
+ resolved = { ...retried, calls: [...priorCalls, ...retried.calls] };
6813
+ } catch (error2) {
6814
+ if (isRunWideProviderError(error2)) throw error2;
6815
+ throw new LocateRetryError(priorCalls);
6816
+ }
6817
+ }
6818
+ }
6819
+ if (resolved.kind === "unresolved" && resolved.reason === "no_candidates") {
6820
+ const deadline = performance.now() + 8e3;
6821
+ while (performance.now() < deadline && !options.signal?.aborted) {
6822
+ await new Promise((resolve) => setTimeout(resolve, 400));
6823
+ const settled = await quietPage(page, 80, 1e3).catch(() => ({
6824
+ quiet: false
6825
+ }));
6826
+ if (!settled.quiet) continue;
6827
+ try {
6828
+ const fresh = await locate();
6829
+ resolved = { ...fresh, calls: [...resolved.calls, ...fresh.calls] };
6830
+ if (resolved.kind !== "unresolved" || resolved.reason !== "no_candidates")
6831
+ break;
6832
+ } catch (error2) {
6833
+ if (isRunWideProviderError(error2)) throw error2;
6834
+ }
6835
+ }
6836
+ }
6837
+ return resolved;
6838
+ }
6839
+ async function executeSentence(page, step, dependencies, data, opaqueEntries, presentation = {}) {
6444
6840
  const started = performance.now();
6445
6841
  const report = dependencies.report;
6446
6842
  const currentAttempt = report?.test.currentAttempt ?? void 0;
@@ -6476,7 +6872,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6476
6872
  const sensitive = facts.page?.status === "omitted" && facts.page.reason === "sensitive_page" || acceptedVersion !== void 0 && safeUrl(acceptedVersion.route, privacy).sensitive || safeUrl(page.url, privacy).sensitive;
6477
6873
  const isError = typeof outcome === "object" && outcome.status === "could_not_run";
6478
6874
  const failed = outcome === "failed" || typeof outcome === "object" && outcome.status === "failed";
6479
- const flags = facts.verify?.flags ?? [];
6875
+ const flags = facts.verify?.kind === "verify" ? facts.verify.flags : [];
6480
6876
  const needsEvidence = failed || isError || flags.length > 0;
6481
6877
  const evidence = !needsEvidence ? { status: "omitted", reason: "clean_step" } : sensitive ? { status: "omitted", reason: "sensitive_page" } : !report.evidenceEnabled ? { status: "omitted", reason: "disabled" } : await capture("evidence", acceptedVersion);
6482
6878
  const replayFrame2 = !report.replay ? null : sensitive ? { status: "omitted", reason: "sensitive_page" } : facts.replayFrame ?? await capture("replay", acceptedVersion);
@@ -6492,12 +6888,13 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6492
6888
  ...facts.failedCalls ?? [],
6493
6889
  ...facts.verify ? [resultCall(facts.verify.call, "judge", facts.verify.elapsedMs)] : []
6494
6890
  ];
6891
+ const policy = facts.verify?.kind === "verify" ? facts.verify : null;
6495
6892
  const judgement = facts.verify ? {
6496
6893
  holds: facts.verify.holds,
6497
6894
  contradicted: facts.verify.contradicted,
6498
- threshold: facts.verify.minP,
6499
- band: facts.verify.band,
6500
- contradictionCutoff: facts.verify.contradictionCutoff,
6895
+ threshold: policy?.minP ?? null,
6896
+ band: policy?.band ?? null,
6897
+ contradictionCutoff: policy?.contradictionCutoff ?? null,
6501
6898
  judgedExcerpt: !sensitive && facts.verify.judgedExcerpt ? safeText(facts.verify.judgedExcerpt, privacy, 1500) : null
6502
6899
  } : null;
6503
6900
  const result = {
@@ -6506,8 +6903,13 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6506
6903
  kind,
6507
6904
  operation: step.op,
6508
6905
  phase: step.phase,
6509
- sentence: safeText(step.text, privacy, 512),
6906
+ sentence: safeText(presentation.display ?? step.text, privacy, 512),
6510
6907
  detail: safeText(facts.detail ?? "", privacy, 512),
6908
+ ...presentation.group?.length ? {
6909
+ group: presentation.group.map(
6910
+ (name) => safeText(name, privacy, 120)
6911
+ )
6912
+ } : {},
6511
6913
  sourceStack: (step.sourceStack ?? [step.source]).map(
6512
6914
  (source) => safeSource(source, dependencies.repoRoot, privacy)
6513
6915
  ),
@@ -6553,6 +6955,13 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6553
6955
  await report.test.addStep(result);
6554
6956
  return outcome;
6555
6957
  };
6958
+ const runWide = async (error2) => {
6959
+ const outcome = providerFailure(step.source.file, error2);
6960
+ await record(outcome, {
6961
+ error: { code: outcome.code, message: outcome.message }
6962
+ });
6963
+ return error2;
6964
+ };
6556
6965
  const quiet = await quietPage(page, 80, 4e3).catch(() => ({
6557
6966
  quiet: false
6558
6967
  }));
@@ -6592,6 +7001,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6592
7001
  }
6593
7002
  }
6594
7003
  if (step.op === "remember") {
7004
+ const targetLabel = presentation.display?.startsWith("extract ") ? "extract" : "remember";
6595
7005
  const match = /^(?:remember|capture)\s+(.+?)\s+as\s+\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}\s*\.?$/iu.exec(
6596
7006
  step.text.trim()
6597
7007
  );
@@ -6615,27 +7025,44 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6615
7025
  if (/^(?:the\s+)?page\s+text$/iu.test(match[1].trim())) {
6616
7026
  remembered = await page.text();
6617
7027
  } else {
6618
- locator = await resolveTarget(page, dependencies.provider, {
7028
+ const locateRead = () => resolveTarget(page, dependencies.provider, {
6619
7029
  operation: "read",
6620
7030
  sentence: match[1],
6621
7031
  projectText: (text) => redactOpaqueText(text, opaqueEntries),
6622
7032
  ...dependencies.signal ? { signal: dependencies.signal } : {}
6623
7033
  });
7034
+ locator = await reobserve(page, await locateRead(), locateRead, {
7035
+ staleRetry: true,
7036
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
7037
+ });
6624
7038
  if (locator.kind !== "resolved")
6625
7039
  return record("failed", {
6626
7040
  locator,
6627
7041
  error: {
6628
7042
  code: locator.reason,
6629
- message: "The remember target could not be resolved."
7043
+ message: `The ${targetLabel} target could not be resolved.`
6630
7044
  }
6631
7045
  });
6632
- const read = await readTarget(page, locator.target.driverTarget());
7046
+ let read = await readTarget(page, locator.target.driverTarget());
7047
+ if (read.status === "stale") {
7048
+ locator = await reobserve(
7049
+ page,
7050
+ { ...locator, kind: "unresolved", reason: "stale" },
7051
+ locateRead,
7052
+ {
7053
+ staleRetry: true,
7054
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
7055
+ }
7056
+ );
7057
+ if (locator.kind === "resolved")
7058
+ read = await readTarget(page, locator.target.driverTarget());
7059
+ }
6633
7060
  if (read.status !== "ok")
6634
7061
  return record("failed", {
6635
7062
  locator,
6636
7063
  error: {
6637
7064
  code: `remember_${read.status}`,
6638
- message: "The remember target did not contain usable text."
7065
+ message: `The ${targetLabel} target did not contain usable text.`
6639
7066
  }
6640
7067
  });
6641
7068
  remembered = read.text;
@@ -6645,22 +7072,24 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6645
7072
  ...locator ? { locator } : {},
6646
7073
  error: {
6647
7074
  code: "remember_invalid_text",
6648
- message: "The remember target did not contain usable text."
7075
+ message: `The ${targetLabel} target did not contain usable text.`
6649
7076
  }
6650
7077
  });
6651
7078
  const echoedSecrets = opaqueMatches(remembered, opaqueEntries);
6652
7079
  const sensitivePage = report ? safeUrl(page.url, report.privacy).sensitive : false;
6653
7080
  const opaqueValues = sensitivePage ? [...echoedSecrets, new RuntimeValue(remembered, `{{${match[2]}}}`)] : echoedSecrets;
7081
+ const secret2 = opaqueValues.length > 0;
6654
7082
  data[match[2]] = {
6655
7083
  value: new RuntimeValue(remembered, `{{${match[2]}}}`),
6656
- sensitive: true,
6657
- modelVisible: opaqueValues.length === 0,
7084
+ sensitive: secret2,
7085
+ modelVisible: !secret2,
6658
7086
  opaqueValues
6659
7087
  };
6660
7088
  opaqueEntries.push(data[match[2]]);
6661
- report?.privacy.secretValues.push(remembered);
7089
+ if (secret2) report?.privacy.secretValues.push(remembered);
6662
7090
  return record("continue", locator ? { locator } : {});
6663
- } catch {
7091
+ } catch (error2) {
7092
+ if (isRunWideProviderError(error2)) throw await runWide(error2);
6664
7093
  return record(
6665
7094
  unsupported(
6666
7095
  step.source.file,
@@ -6676,18 +7105,23 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6676
7105
  );
6677
7106
  }
6678
7107
  }
6679
- if (step.op === "verify") {
6680
- const judge = () => verify(page, dependencies.provider, claim(step, data), {
7108
+ if (step.op === "verify" || step.op === "measure") {
7109
+ const assertion = {
6681
7110
  ...dependencies.signal ? { signal: dependencies.signal } : {},
6682
- projectText: (text) => redactOpaqueText(text, opaqueEntries),
7111
+ projectText: (text) => redactOpaqueText(text, opaqueEntries)
7112
+ };
7113
+ const judge = () => step.op === "measure" ? measure(page, dependencies.provider, claim(step, data), assertion) : verify(page, dependencies.provider, claim(step, data), {
7114
+ ...assertion,
6683
7115
  ...dependencies.verifyPolicy ?? {}
6684
7116
  });
7117
+ const outcome = (result) => result.kind === "verify" && result.verdict === "failed" ? "failed" : "continue";
6685
7118
  try {
6686
7119
  const result = await judge();
6687
- return record(result.verdict === "failed" ? "failed" : "continue", {
7120
+ return record(outcome(result), {
6688
7121
  verify: result
6689
7122
  });
6690
7123
  } catch (error2) {
7124
+ if (isRunWideProviderError(error2)) throw await runWide(error2);
6691
7125
  const priorCalls = error2 instanceof AssertionEngineError && error2.failedCall ? [resultCall(error2.failedCall, "judge")] : [];
6692
7126
  if (error2 instanceof AssertionEngineError && error2.code === "stale_observation") {
6693
7127
  const settled = await quietPage(page, 80, 4e3).catch(() => ({
@@ -6696,11 +7130,13 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6696
7130
  if (settled.quiet) {
6697
7131
  try {
6698
7132
  const result = await judge();
6699
- return record(result.verdict === "failed" ? "failed" : "continue", {
7133
+ return record(outcome(result), {
6700
7134
  verify: result,
6701
7135
  failedCalls: priorCalls
6702
7136
  });
6703
7137
  } catch (retryError) {
7138
+ if (isRunWideProviderError(retryError))
7139
+ throw await runWide(retryError);
6704
7140
  return record(
6705
7141
  unsupported(
6706
7142
  step.source.file,
@@ -6737,20 +7173,85 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6737
7173
  );
6738
7174
  }
6739
7175
  }
6740
- if (step.op !== "click" && step.op !== "type")
6741
- return record(
6742
- unsupported(
6743
- step.source.file,
6744
- step.source,
6745
- `The ${step.op} operation is not part of this walking skeleton.`
6746
- ),
7176
+ if (step.op === "wait" || step.op === "press" || step.op === "scroll" || step.op === "goto") {
7177
+ let command2;
7178
+ let detail = "";
7179
+ const invalid = (message) => record(
6747
7180
  {
7181
+ status: "could_not_run",
7182
+ file: step.source.file,
7183
+ code: "invalid_test",
7184
+ source: step.source,
7185
+ message
7186
+ },
7187
+ { error: { code: "invalid_operand", message } }
7188
+ );
7189
+ if (step.op === "wait") {
7190
+ const durationMs = waitDurationMs(step.text);
7191
+ if (durationMs === null)
7192
+ return invalid("Use a positive wait duration of at most 30 seconds.");
7193
+ command2 = { op: "wait", durationMs };
7194
+ } else if (step.op === "press") {
7195
+ const key = pressKey(step.text);
7196
+ if (key === null)
7197
+ return invalid(
7198
+ 'Name one key to press, such as Enter, Tab, Escape, or "Control+A".'
7199
+ );
7200
+ command2 = { op: "press", key };
7201
+ detail = `Pressed ${key}.`;
7202
+ } else if (step.op === "scroll") {
7203
+ const direction = scrollDirection(step.text);
7204
+ if (direction === null) return invalid("Say scroll up or scroll down.");
7205
+ const height = await page.evaluate("window.innerHeight").catch(() => 800);
7206
+ const deltaY = Math.round(Math.max(200, height * 0.8));
7207
+ command2 = {
7208
+ op: "scroll",
7209
+ deltaY: direction === "down" ? deltaY : -deltaY
7210
+ };
7211
+ } 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.");
7227
+ }
7228
+ command2 = { op: "goto", url };
7229
+ detail = `Opened ${url.toString()}.`;
7230
+ }
7231
+ try {
7232
+ await executeStep(page, command2, {
7233
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
7234
+ });
7235
+ return record("continue", detail ? { detail } : {});
7236
+ } catch (error2) {
7237
+ const actionError = error2 instanceof StepExecutionError ? error2 : null;
7238
+ const facts = {
6748
7239
  error: {
6749
- code: "unsupported_operation",
6750
- message: `The ${step.op} operation is not supported.`
7240
+ code: actionError?.code ?? "action_error",
7241
+ message: actionError?.message ?? "The action could not complete.",
7242
+ callLog: actionError?.callLog
6751
7243
  }
6752
- }
6753
- );
7244
+ };
7245
+ return actionError?.code === "invalid_input" ? record("failed", facts) : record(
7246
+ unsupported(
7247
+ step.source.file,
7248
+ step.source,
7249
+ actionError?.op === "goto" ? `Could not open the address: ${navigationWhy(actionError)}.` : `The ${step.op} step could not complete.`
7250
+ ),
7251
+ facts
7252
+ );
7253
+ }
7254
+ }
6754
7255
  const typeOperand = step.op === "type" ? validateTypeOperand(step) : null;
6755
7256
  const runtimeDependent = step.tokens.some(
6756
7257
  (token) => token.kind === "placeholder" && (step.op === "click" || !typeOperand || "diagnostic" in typeOperand || token.start < typeOperand.operand.start || token.end > typeOperand.operand.end)
@@ -6780,7 +7281,8 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6780
7281
  let resolved;
6781
7282
  try {
6782
7283
  resolved = await locate();
6783
- } catch {
7284
+ } catch (error2) {
7285
+ if (isRunWideProviderError(error2)) throw await runWide(error2);
6784
7286
  return record(
6785
7287
  unsupported(
6786
7288
  step.source.file,
@@ -6795,57 +7297,43 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6795
7297
  }
6796
7298
  );
6797
7299
  }
6798
- if (!visionAttempted && resolved.kind === "unresolved" && resolved.reason === "stale") {
6799
- const priorCalls = resolved.calls;
6800
- const settled = await quietPage(page, 1e3, 4e3).catch(() => ({
6801
- quiet: false
6802
- }));
6803
- if (settled.quiet) {
6804
- try {
6805
- const retried = await locate();
6806
- resolved = { ...retried, calls: [...priorCalls, ...retried.calls] };
6807
- } catch {
6808
- return record(
6809
- unsupported(
6810
- step.source.file,
6811
- step.source,
6812
- "The target could not be resolved."
6813
- ),
6814
- {
6815
- failedCalls: priorCalls.map((call2) => resultCall(call2, "locator")),
6816
- error: {
6817
- code: "locator_error",
6818
- message: "The target could not be resolved."
6819
- }
6820
- }
6821
- );
6822
- }
6823
- }
6824
- }
6825
- if (resolved.kind === "unresolved" && resolved.reason === "no_candidates") {
6826
- const deadline = performance.now() + 8e3;
6827
- while (performance.now() < deadline && !dependencies.signal?.aborted) {
6828
- await new Promise((resolve) => setTimeout(resolve, 400));
6829
- const settled = await quietPage(page, 80, 1e3).catch(() => ({
6830
- quiet: false
6831
- }));
6832
- if (!settled.quiet) continue;
6833
- try {
6834
- const fresh = await locate();
6835
- resolved = { ...fresh, calls: [...resolved.calls, ...fresh.calls] };
6836
- if (resolved.kind !== "unresolved" || resolved.reason !== "no_candidates")
6837
- break;
6838
- } catch {
7300
+ try {
7301
+ resolved = await reobserve(page, resolved, locate, {
7302
+ staleRetry: !visionAttempted,
7303
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
7304
+ });
7305
+ } catch (error2) {
7306
+ if (isRunWideProviderError(error2)) throw await runWide(error2);
7307
+ if (!(error2 instanceof LocateRetryError)) throw error2;
7308
+ return record(
7309
+ unsupported(
7310
+ step.source.file,
7311
+ step.source,
7312
+ "The target could not be resolved."
7313
+ ),
7314
+ {
7315
+ failedCalls: error2.priorCalls.map(
7316
+ (call2) => resultCall(call2, "locator")
7317
+ ),
7318
+ error: {
7319
+ code: "locator_error",
7320
+ message: "The target could not be resolved."
7321
+ }
6839
7322
  }
6840
- }
7323
+ );
6841
7324
  }
6842
7325
  if (resolved.kind !== "resolved") {
6843
7326
  if (resolved.reason === "none" || resolved.reason === "ambiguous" || resolved.reason === "no_candidates")
6844
7327
  return record("failed", {
6845
7328
  locator: resolved,
6846
7329
  error: {
6847
- code: resolved.reason,
6848
- message: resolved.diagnostic.vision?.failure ? `Could not resolve this ${step.op} step: vision ${resolved.diagnostic.vision.failure}${resolved.diagnostic.vision.httpStatus ? ` (HTTP ${resolved.diagnostic.vision.httpStatus})` : ""}.` : `Could not resolve this ${step.op} step.`
7330
+ // "none" reads like "no error"; say what happened.
7331
+ code: resolved.reason === "none" ? "no_match" : resolved.reason,
7332
+ message: `Could not resolve this ${step.op} step: ${unresolvedWhy(
7333
+ resolved,
7334
+ step.op,
7335
+ Boolean(dependencies.visionResolver) && step.op === "click"
7336
+ )}.`
6849
7337
  }
6850
7338
  });
6851
7339
  return record(
@@ -6863,7 +7351,12 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6863
7351
  }
6864
7352
  );
6865
7353
  }
6866
- const commandFor = (target) => step.op === "click" ? { op: "click", target } : { op: "type", target, value: typeValue };
7354
+ let chosenOption = null;
7355
+ const commandFor = (target) => step.op === "click" ? {
7356
+ op: "click",
7357
+ target,
7358
+ chooseOption: (labels) => chosenOption = chooseOption(step.text, labels)
7359
+ } : { op: "type", target, value: typeValue };
6867
7360
  let command = commandFor(resolved.target);
6868
7361
  let locatedPage = report ? await reportPage(
6869
7362
  page,
@@ -6931,7 +7424,12 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6931
7424
  );
6932
7425
  await dependencies.locatorCache.put(seed.key, entry);
6933
7426
  } catch (error2) {
6934
- if (error2 instanceof Error && error2.message !== "candidate_not_distinguishable" && resolved.cache)
7427
+ if (error2 instanceof Error && error2.message === "candidate_not_distinguishable" && resolved.cache?.reason === "absent")
7428
+ recordedLocator = {
7429
+ ...resolved,
7430
+ cache: { ...resolved.cache, reason: "not_cacheable" }
7431
+ };
7432
+ else if (error2 instanceof Error && error2.message !== "candidate_not_distinguishable" && resolved.cache)
6935
7433
  recordedLocator = {
6936
7434
  ...resolved,
6937
7435
  cache: {
@@ -6945,9 +7443,11 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6945
7443
  locator: recordedLocator,
6946
7444
  replayFrame,
6947
7445
  targetBox,
6948
- page: locatedPage
7446
+ page: locatedPage,
7447
+ ...chosenOption === null ? {} : { detail: `Chose "${chosenOption}" in the dropdown.` }
6949
7448
  });
6950
7449
  } catch (error2) {
7450
+ if (isRunWideProviderError(error2)) throw await runWide(error2);
6951
7451
  const actionError = error2 instanceof StepExecutionError ? error2 : null;
6952
7452
  const failed = actionError && (actionError.code === "not_actionable" || actionError.code === "invalid_input");
6953
7453
  const facts = {
@@ -6971,6 +7471,18 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
6971
7471
  );
6972
7472
  }
6973
7473
  }
7474
+ function unresolvedWhy(resolved, op, visionEnabled) {
7475
+ const vision = resolved.diagnostic.vision;
7476
+ const why = resolved.reason === "none" ? "no element on the page matches it; check the wording against the page" : resolved.reason === "no_candidates" ? `the page had nothing to ${op === "type" ? "type into" : op}` : "several elements match it; name the one you mean more precisely";
7477
+ if (vision?.failure)
7478
+ return `${why} (vision ${vision.failure}${vision.httpStatus ? `, HTTP ${vision.httpStatus}` : ""})`;
7479
+ if (!visionEnabled) return why;
7480
+ if (vision?.outcome === "abstained")
7481
+ return `${why}; the vision model did not find it either`;
7482
+ if (!vision && resolved.reason !== "no_candidates")
7483
+ return `${why}; vision fallback could not run (it needs 2 to 40 fully visible, unobscured controls on screen)`;
7484
+ return why;
7485
+ }
6974
7486
  async function recordGoalAction(page, action, report, repoRoot, source) {
6975
7487
  const attempt = report.test.currentAttempt;
6976
7488
  const index = attempt.stepCount + 1;
@@ -7035,11 +7547,11 @@ async function recordGoalAction(page, action, report, repoRoot, source) {
7035
7547
  }
7036
7548
  async function runFlow(file, runDependencies) {
7037
7549
  const absolute = path5.resolve(file);
7038
- const loaded = await loadFlowFile(absolute, {
7550
+ const loaded2 = await loadFlowFile(absolute, {
7039
7551
  repoRoot: runDependencies.repoRoot,
7040
7552
  rejectSymlinks: true
7041
7553
  });
7042
- const parsed = await resolveFlowModules(loaded, {
7554
+ const parsed = await resolveFlowModules(loaded2, {
7043
7555
  repoRoot: runDependencies.repoRoot
7044
7556
  });
7045
7557
  if (!parsed.value) return firstDiagnostic(parsed.diagnostics);
@@ -7081,7 +7593,7 @@ async function runFlow(file, runDependencies) {
7081
7593
  ).file;
7082
7594
  const existing = slot ? recorder.testAt(slot.ordinal) : recorder.latestTest();
7083
7595
  const retrying = existing?.file === file2 && existing.currentAttempt?.running === true;
7084
- const test = retrying ? existing : await recorder.beginTest({
7596
+ const test2 = retrying ? existing : await recorder.beginTest({
7085
7597
  id: parsed.value.identity,
7086
7598
  file: file2,
7087
7599
  description: safeText(parsed.value.description ?? "", privacy, 512),
@@ -7089,7 +7601,7 @@ async function runFlow(file, runDependencies) {
7089
7601
  ...slot ? { ordinal: slot.ordinal } : {},
7090
7602
  ...slot?.lane === void 0 ? {} : { lane: slot.lane }
7091
7603
  });
7092
- dependencies = { ...runBase, report: { ...shared, privacy, test } };
7604
+ dependencies = { ...runBase, report: { ...shared, privacy, test: test2 } };
7093
7605
  } else dependencies = runBase;
7094
7606
  const classified = await classifyParsedFlow(parsed, {
7095
7607
  mode: "allow-model",
@@ -7119,8 +7631,8 @@ async function runFlow(file, runDependencies) {
7119
7631
  ...Object.values(data).filter((entry) => entry.sensitive).map((entry) => entry.value.reveal())
7120
7632
  );
7121
7633
  if (dependencies.report && classified.value.goal) {
7122
- const { test, privacy } = dependencies.report;
7123
- await test.setGoal({
7634
+ const { test: test2, privacy } = dependencies.report;
7635
+ await test2.setGoal({
7124
7636
  text: safeText(classified.value.goal.text, privacy, Infinity),
7125
7637
  verify: safeText(classified.value.goal.verify, privacy, Infinity)
7126
7638
  });
@@ -7275,10 +7787,10 @@ async function runFlow(file, runDependencies) {
7275
7787
  );
7276
7788
  const goalSource = goalResult.reason === "verification_failed" ? goal.verifySource : goal.source;
7277
7789
  if (dependencies.report) {
7278
- const { test, privacy } = dependencies.report;
7279
- const attempt = test.currentAttempt;
7790
+ const { test: test2, privacy } = dependencies.report;
7791
+ const attempt = test2.currentAttempt;
7280
7792
  const checked = goalResult.verification[0];
7281
- await test.addStep({
7793
+ await test2.addStep({
7282
7794
  id: `${attempt.id}:step:${attempt.stepCount + 1}`,
7283
7795
  index: attempt.stepCount + 1,
7284
7796
  kind: "verify",
@@ -7315,7 +7827,11 @@ async function runFlow(file, runDependencies) {
7315
7827
  ),
7316
7828
  error: goalResult.status === "failed" ? {
7317
7829
  code: goalResult.reason,
7318
- message: `Goal did not pass: ${goalResult.reason}.`
7830
+ 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." : ""}`,
7832
+ privacy,
7833
+ 512
7834
+ )
7319
7835
  } : null,
7320
7836
  evidence: { status: "omitted", reason: "goal_summary" },
7321
7837
  replayFrame: null,
@@ -7350,19 +7866,951 @@ async function runFlow(file, runDependencies) {
7350
7866
  }
7351
7867
  }
7352
7868
 
7353
- // src/project-validation.ts
7354
- var NOT_CHECKED_OFFLINE_CODE = "unavailable";
7355
- var OPERATIONAL_CODES = /* @__PURE__ */ new Set([
7356
- "provider_error",
7357
- "cache_error",
7358
- "unreadable_file"
7359
- ]);
7360
- function compareDiagnostics3(a, b) {
7361
- const text = (left, right) => left < right ? -1 : left > right ? 1 : 0;
7362
- return text(a.source.file, b.source.file) || a.source.line - b.source.line || a.source.col - b.source.col || text(a.code, b.code) || text(a.message, b.message);
7363
- }
7364
- function dedupeDiagnostics(diagnostics) {
7365
- const seen = /* @__PURE__ */ new Set();
7869
+ // src/script-loader.ts
7870
+ import { existsSync as existsSync2 } from "fs";
7871
+ import path6 from "path";
7872
+ import { fileURLToPath as fileURLToPath2 } from "url";
7873
+ import { createJiti } from "jiti";
7874
+ var SCRIPT_TEST_SUFFIX = ".test.ts";
7875
+ function isScriptTestFile(file) {
7876
+ return file.endsWith(SCRIPT_TEST_SUFFIX);
7877
+ }
7878
+ var ID = /^[A-Za-z0-9][A-Za-z0-9._/#:-]{0,199}$/u;
7879
+ var TAG = /^[^\s,][^,]{0,119}$/u;
7880
+ var OPTION_KEYS = /* @__PURE__ */ new Set(["id", "url", "tags"]);
7881
+ var jiti;
7882
+ var loaded = /* @__PURE__ */ new Map();
7883
+ var declared = /* @__PURE__ */ new Map();
7884
+ var queue = Promise.resolve();
7885
+ function diagnostic2(code, source, message, fix) {
7886
+ return { severity: "error", code, source, message, fix };
7887
+ }
7888
+ function checkRegistrations(file, registrations, repoRoot) {
7889
+ const relative = path6.relative(repoRoot, file).split(path6.sep).join("/");
7890
+ const top = { file, line: 1, col: 1 };
7891
+ const diagnostics = [];
7892
+ const tests = [];
7893
+ const titles = /* @__PURE__ */ new Map();
7894
+ const ids = /* @__PURE__ */ new Map();
7895
+ if (registrations.length === 0)
7896
+ diagnostics.push(
7897
+ diagnostic2(
7898
+ "no_tests",
7899
+ top,
7900
+ "This file declares no test.",
7901
+ 'Call test("title", async ({ page, ai }) => { ... }) at the top level of the file.'
7902
+ )
7903
+ );
7904
+ for (const registration of registrations) {
7905
+ const called = registration.callSite ? parseFrame(registration.callSite) : void 0;
7906
+ const source = called && samePath(called.file, file) ? { ...called, file } : top;
7907
+ const problems = [];
7908
+ const { title, options, body } = registration;
7909
+ if (typeof title !== "string" || !title.trim() || title.length > 512)
7910
+ problems.push(
7911
+ diagnostic2(
7912
+ "invalid_title",
7913
+ source,
7914
+ "A test title must be a nonblank string of at most 512 characters.",
7915
+ 'Write test("a customer signs in", ...).'
7916
+ )
7917
+ );
7918
+ if (typeof body !== "function")
7919
+ problems.push(
7920
+ diagnostic2(
7921
+ "missing_body",
7922
+ source,
7923
+ "This test has no body function.",
7924
+ "Pass an async function as the last argument to test()."
7925
+ )
7926
+ );
7927
+ if (typeof options !== "object" || options === null)
7928
+ problems.push(
7929
+ diagnostic2(
7930
+ "invalid_options",
7931
+ source,
7932
+ "Test options must be an object.",
7933
+ "Pass { url, id, tags } or omit the options."
7934
+ )
7935
+ );
7936
+ else {
7937
+ for (const key of Object.keys(options))
7938
+ if (!OPTION_KEYS.has(key))
7939
+ problems.push(
7940
+ diagnostic2(
7941
+ "unknown_option",
7942
+ source,
7943
+ `Unknown test option \`${key}\`.`,
7944
+ "Use only `url`, `id`, and `tags`."
7945
+ )
7946
+ );
7947
+ if (options.id !== void 0 && (typeof options.id !== "string" || !ID.test(options.id)))
7948
+ problems.push(
7949
+ diagnostic2(
7950
+ "invalid_id",
7951
+ source,
7952
+ "A test id uses letters, digits, and . _ / # : - (at most 200).",
7953
+ "Choose an id such as `checkout-new-user`."
7954
+ )
7955
+ );
7956
+ if (options.url !== void 0 && (typeof options.url !== "string" || !options.url.trim()))
7957
+ problems.push(
7958
+ diagnostic2(
7959
+ "invalid_url",
7960
+ source,
7961
+ "The test url must be a nonblank string.",
7962
+ "Use an absolute URL, or a path relative to baseUrl."
7963
+ )
7964
+ );
7965
+ if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !TAG.test(tag))))
7966
+ problems.push(
7967
+ diagnostic2(
7968
+ "invalid_tags",
7969
+ source,
7970
+ "Tags must be a list of nonblank strings without commas.",
7971
+ 'Write tags: ["checkout", "smoke"].'
7972
+ )
7973
+ );
7974
+ }
7975
+ if (problems.length) {
7976
+ diagnostics.push(...problems);
7977
+ continue;
7978
+ }
7979
+ const identity = options.id ?? `${relative}#${title}`;
7980
+ const earlierTitle = titles.get(title);
7981
+ if (earlierTitle) {
7982
+ diagnostics.push(
7983
+ diagnostic2(
7984
+ "duplicate_title",
7985
+ source,
7986
+ `Duplicate test title ${JSON.stringify(title)}; first used on line ${earlierTitle.line}.`,
7987
+ "Give each test in a file its own title."
7988
+ )
7989
+ );
7990
+ continue;
7991
+ }
7992
+ titles.set(title, source);
7993
+ const earlierId = ids.get(identity);
7994
+ if (earlierId) {
7995
+ diagnostics.push(
7996
+ diagnostic2(
7997
+ "duplicate_id",
7998
+ source,
7999
+ `Duplicate test id \`${identity}\`; first used on line ${earlierId.line}.`,
8000
+ "Give each test a unique id."
8001
+ )
8002
+ );
8003
+ continue;
8004
+ }
8005
+ ids.set(identity, source);
8006
+ tests.push({
8007
+ file,
8008
+ title,
8009
+ identity,
8010
+ ...options.id === void 0 ? {} : { explicitId: options.id },
8011
+ ...options.url === void 0 ? {} : { url: options.url },
8012
+ tags: [...options.tags ?? []],
8013
+ body,
8014
+ source
8015
+ });
8016
+ }
8017
+ return { file, tests, diagnostics };
8018
+ }
8019
+ function authoringEntry() {
8020
+ for (const name of ["./script-api.js", "./script-api.ts"]) {
8021
+ const candidate = fileURLToPath2(new URL(name, import.meta.url));
8022
+ if (existsSync2(candidate)) return candidate;
8023
+ }
8024
+ throw new Error("The Sedum authoring API is missing from this install.");
8025
+ }
8026
+ async function importOnce(file, repoRoot) {
8027
+ jiti ??= createJiti(import.meta.url, {
8028
+ moduleCache: true,
8029
+ alias: { "sedum-cli": authoringEntry() }
8030
+ });
8031
+ const registry = scriptRegistry();
8032
+ registry.pending = [];
8033
+ let failure;
8034
+ try {
8035
+ await jiti.import(file);
8036
+ } catch (error2) {
8037
+ const stack = error2 instanceof Error ? error2.stack : void 0;
8038
+ const message = error2 instanceof Error ? error2.message.split("\n")[0] : String(error2);
8039
+ failure = {
8040
+ file,
8041
+ tests: [],
8042
+ diagnostics: [
8043
+ diagnostic2(
8044
+ "load_error",
8045
+ sourceInFile(stack, file) ?? { file, line: 1, col: 1 },
8046
+ `The test file could not be loaded: ${message.slice(0, 300)}`,
8047
+ "Fix the error, or check that its imports are installed."
8048
+ )
8049
+ ]
8050
+ };
8051
+ }
8052
+ const evaluated = /* @__PURE__ */ new Map();
8053
+ for (const registration of registry.pending) {
8054
+ const called = registration.callSite ? parseFrame(registration.callSite) : void 0;
8055
+ const owner = pathKey(
8056
+ called && isScriptTestFile(called.file) ? called.file : file
8057
+ );
8058
+ evaluated.set(owner, [...evaluated.get(owner) ?? [], registration]);
8059
+ }
8060
+ for (const [owner, registrations] of evaluated)
8061
+ declared.set(owner, registrations);
8062
+ registry.pending = [];
8063
+ return failure ?? checkRegistrations(file, declared.get(pathKey(file)) ?? [], repoRoot);
8064
+ }
8065
+ function loadScriptFile(file, options) {
8066
+ const absolute = path6.resolve(file);
8067
+ let pending = loaded.get(absolute);
8068
+ if (!pending) {
8069
+ pending = queue.then(() => importOnce(absolute, options.repoRoot));
8070
+ queue = pending.catch(() => void 0);
8071
+ loaded.set(absolute, pending);
8072
+ }
8073
+ return pending;
8074
+ }
8075
+ function scriptListingEntries(script) {
8076
+ const coverage = {
8077
+ format: "passed",
8078
+ steps: "not_checked",
8079
+ modules: "not_needed"
8080
+ };
8081
+ const problems = script.diagnostics.length ? [
8082
+ {
8083
+ file: script.file,
8084
+ result: {
8085
+ diagnostics: script.diagnostics,
8086
+ coverage: { ...coverage, format: "failed" }
8087
+ }
8088
+ }
8089
+ ] : [];
8090
+ return [
8091
+ ...problems,
8092
+ ...script.tests.map((test2) => {
8093
+ const header = {
8094
+ version: 1,
8095
+ file: test2.file,
8096
+ identity: test2.identity,
8097
+ ...test2.explicitId === void 0 ? {} : { explicitId: test2.explicitId, idSource: test2.source },
8098
+ description: test2.title,
8099
+ ...test2.url === void 0 ? {} : { url: test2.url },
8100
+ tags: test2.tags,
8101
+ meta: {},
8102
+ data: {},
8103
+ before: [],
8104
+ steps: [],
8105
+ after: []
8106
+ };
8107
+ return {
8108
+ file: test2.file,
8109
+ result: { value: header, diagnostics: [], coverage }
8110
+ };
8111
+ })
8112
+ ];
8113
+ }
8114
+
8115
+ // src/script-sentences.ts
8116
+ var IDENT_START = /[A-Za-z_$]/u;
8117
+ var IDENT_PART = /[A-Za-z0-9_$]/u;
8118
+ var REGEX_AFTER = /* @__PURE__ */ new Set([
8119
+ "(",
8120
+ ",",
8121
+ "=",
8122
+ ":",
8123
+ "[",
8124
+ "!",
8125
+ "&",
8126
+ "|",
8127
+ "?",
8128
+ "{",
8129
+ "}",
8130
+ ";",
8131
+ "+",
8132
+ "-",
8133
+ "*",
8134
+ "%",
8135
+ "<",
8136
+ ">",
8137
+ "~",
8138
+ "^",
8139
+ "=>",
8140
+ "return",
8141
+ "typeof",
8142
+ "case",
8143
+ "do",
8144
+ "else",
8145
+ "in",
8146
+ "of",
8147
+ "new",
8148
+ "delete",
8149
+ "void",
8150
+ "throw",
8151
+ "yield",
8152
+ "await"
8153
+ ]);
8154
+ function tokenize(source) {
8155
+ const tokens = [];
8156
+ let index = 0;
8157
+ let line = 1;
8158
+ let col = 1;
8159
+ const advance = (count2 = 1) => {
8160
+ for (let step = 0; step < count2 && index < source.length; step++) {
8161
+ if (source[index] === "\n") {
8162
+ line++;
8163
+ col = 1;
8164
+ } else col++;
8165
+ index++;
8166
+ }
8167
+ };
8168
+ const readQuoted = (quote) => {
8169
+ let value = "";
8170
+ let dynamic = false;
8171
+ let depth = 0;
8172
+ advance();
8173
+ while (index < source.length) {
8174
+ const char = source[index];
8175
+ if (char === "\\") {
8176
+ const next = source[index + 1] ?? "";
8177
+ const hex = next === "x" ? /^[0-9A-Fa-f]{2}/u.exec(source.slice(index + 2))?.[0] : next === "u" ? /^\{([0-9A-Fa-f]{1,6})\}/u.exec(source.slice(index + 2)) ?? /^([0-9A-Fa-f]{4})/u.exec(source.slice(index + 2)) : void 0;
8178
+ if (typeof hex === "string") {
8179
+ value += String.fromCharCode(parseInt(hex, 16));
8180
+ advance(4);
8181
+ } else if (hex) {
8182
+ const code = parseInt(hex[1], 16);
8183
+ value += code <= 1114111 ? String.fromCodePoint(code) : "";
8184
+ advance(2 + hex[0].length);
8185
+ } else {
8186
+ const escapes = {
8187
+ n: "\n",
8188
+ t: " ",
8189
+ r: "\r",
8190
+ b: "\b",
8191
+ f: "\f",
8192
+ v: "\v",
8193
+ "0": "\0",
8194
+ "\n": ""
8195
+ };
8196
+ value += escapes[next] ?? next;
8197
+ advance(2);
8198
+ }
8199
+ continue;
8200
+ }
8201
+ if (quote === "`" && char === "$" && source[index + 1] === "{") {
8202
+ dynamic = true;
8203
+ depth = 1;
8204
+ advance(2);
8205
+ while (index < source.length && depth > 0) {
8206
+ const inner = source[index];
8207
+ if (inner === "{") depth++;
8208
+ else if (inner === "}") depth--;
8209
+ else if (inner === '"' || inner === "'" || inner === "`") {
8210
+ readQuoted(inner);
8211
+ continue;
8212
+ }
8213
+ advance();
8214
+ }
8215
+ continue;
8216
+ }
8217
+ if (char === quote) {
8218
+ advance();
8219
+ break;
8220
+ }
8221
+ if (quote !== "`" && char === "\n") break;
8222
+ value += char;
8223
+ advance();
8224
+ }
8225
+ return { value, dynamic };
8226
+ };
8227
+ while (index < source.length) {
8228
+ const char = source[index];
8229
+ const next = source[index + 1];
8230
+ if (/\s/u.test(char)) {
8231
+ advance();
8232
+ continue;
8233
+ }
8234
+ if (char === "/" && next === "/") {
8235
+ while (index < source.length && source[index] !== "\n") advance();
8236
+ continue;
8237
+ }
8238
+ if (char === "/" && next === "*") {
8239
+ advance(2);
8240
+ while (index < source.length && !(source[index] === "*" && source[index + 1] === "/"))
8241
+ advance();
8242
+ advance(2);
8243
+ continue;
8244
+ }
8245
+ const startLine = line;
8246
+ const startCol = col;
8247
+ if (char === '"' || char === "'" || char === "`") {
8248
+ const { value, dynamic } = readQuoted(char);
8249
+ tokens.push({
8250
+ kind: "string",
8251
+ value,
8252
+ dynamic,
8253
+ line: startLine,
8254
+ col: startCol
8255
+ });
8256
+ continue;
8257
+ }
8258
+ if (char === "/") {
8259
+ const previous = tokens.at(-1);
8260
+ const before = tokens.at(-2);
8261
+ const postfix = (previous?.value === "+" || previous?.value === "-") && before?.value === previous.value;
8262
+ if (!postfix && (!previous || REGEX_AFTER.has(previous.value))) {
8263
+ let inClass = false;
8264
+ advance();
8265
+ while (index < source.length && source[index] !== "\n") {
8266
+ const inner = source[index];
8267
+ if (inner === "\\") {
8268
+ advance(2);
8269
+ continue;
8270
+ }
8271
+ if (inner === "[") inClass = true;
8272
+ else if (inner === "]") inClass = false;
8273
+ else if (inner === "/" && !inClass) {
8274
+ advance();
8275
+ break;
8276
+ }
8277
+ advance();
8278
+ }
8279
+ while (index < source.length && IDENT_PART.test(source[index]))
8280
+ advance();
8281
+ tokens.push({
8282
+ kind: "punct",
8283
+ value: "/re/",
8284
+ line: startLine,
8285
+ col: startCol
8286
+ });
8287
+ continue;
8288
+ }
8289
+ }
8290
+ if (IDENT_START.test(char)) {
8291
+ let value = "";
8292
+ while (index < source.length && IDENT_PART.test(source[index])) {
8293
+ value += source[index];
8294
+ advance();
8295
+ }
8296
+ tokens.push({ kind: "ident", value, line: startLine, col: startCol });
8297
+ continue;
8298
+ }
8299
+ if (char === "=" && next === ">") {
8300
+ advance(2);
8301
+ tokens.push({
8302
+ kind: "punct",
8303
+ value: "=>",
8304
+ line: startLine,
8305
+ col: startCol
8306
+ });
8307
+ continue;
8308
+ }
8309
+ advance();
8310
+ tokens.push({ kind: "punct", value: char, line: startLine, col: startCol });
8311
+ }
8312
+ return tokens;
8313
+ }
8314
+ function scanScriptSentences(source, file) {
8315
+ const tokens = tokenize(source);
8316
+ const sentences = [];
8317
+ const warnings = [];
8318
+ const at2 = (index) => tokens[index];
8319
+ const isPunct = (index, value2) => at2(index)?.kind === "punct" && at2(index).value === value2;
8320
+ const dynamic = (token) => warnings.push({
8321
+ severity: "warning",
8322
+ code: "dynamic_sentence",
8323
+ source: { file, line: token.line, col: token.col },
8324
+ 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
+ fix: 'Write a literal sentence with {{name}} and pass the value separately: ai("type {{email}} into the Email field", { email }).'
8326
+ });
8327
+ const TERMINATORS = /* @__PURE__ */ new Set([",", ")", "]", ";"]);
8328
+ const skipExpression = (index) => {
8329
+ let depth = 0;
8330
+ let cursor = index;
8331
+ for (; cursor < tokens.length; cursor++) {
8332
+ const token = tokens[cursor];
8333
+ if (token.kind !== "punct") continue;
8334
+ if (depth === 0 && TERMINATORS.has(token.value)) return cursor;
8335
+ if ("([{".includes(token.value)) depth++;
8336
+ else if (")]}".includes(token.value)) depth--;
8337
+ }
8338
+ return cursor;
8339
+ };
8340
+ const match = /* @__PURE__ */ new Map();
8341
+ const parentOf = [];
8342
+ {
8343
+ const open2 = [];
8344
+ tokens.forEach((token, index) => {
8345
+ parentOf[index] = open2.at(-1);
8346
+ if (token.kind !== "punct") return;
8347
+ if ("([{".includes(token.value)) open2.push(index);
8348
+ else if (")]}".includes(token.value)) {
8349
+ const opener = open2.pop();
8350
+ if (opener !== void 0) match.set(opener, index);
8351
+ }
8352
+ });
8353
+ }
8354
+ const value = (index) => at2(index)?.value;
8355
+ const DECLARE = /* @__PURE__ */ new Set(["const", "let", "var", "function", "class"]);
8356
+ const COMPOUND = /* @__PURE__ */ new Set([
8357
+ "+",
8358
+ "-",
8359
+ "*",
8360
+ "/",
8361
+ "%",
8362
+ "&",
8363
+ "|",
8364
+ "^",
8365
+ "<",
8366
+ ">",
8367
+ "?"
8368
+ ]);
8369
+ const CONTROL = /* @__PURE__ */ new Set(["if", "while", "for", "switch", "with"]);
8370
+ const MUTATORS = /* @__PURE__ */ new Set([
8371
+ "push",
8372
+ "unshift",
8373
+ "splice",
8374
+ "pop",
8375
+ "shift",
8376
+ "sort",
8377
+ "reverse",
8378
+ "fill",
8379
+ "copyWithin"
8380
+ ]);
8381
+ const binds = (index) => {
8382
+ const next = value(index + 1);
8383
+ const prev = value(index - 1);
8384
+ if (DECLARE.has(prev ?? "") || next === "=>") return true;
8385
+ if (next === "=" && value(index + 2) !== "=") return true;
8386
+ if (COMPOUND.has(next ?? "") && value(index + 2) === "=") return true;
8387
+ if (next === "+" && value(index + 2) === "+" || next === "-" && value(index + 2) === "-" || prev === "+" && value(index - 2) === "+" || prev === "-" && value(index - 2) === "-")
8388
+ return true;
8389
+ if (next === "." && MUTATORS.has(value(index + 2) ?? "")) return true;
8390
+ if (next === "[") {
8391
+ const close = match.get(index + 1);
8392
+ if (close !== void 0 && value(close + 1) === "=" && value(close + 2) !== "=")
8393
+ return true;
8394
+ }
8395
+ for (let parent = parentOf[index]; parent !== void 0; ) {
8396
+ const close = match.get(parent);
8397
+ const after = close === void 0 ? void 0 : value(close + 1);
8398
+ if (value(parent) === "(") {
8399
+ if (after === "=>") return true;
8400
+ if (after === "{" && !CONTROL.has(value(parent - 1) ?? "")) return true;
8401
+ if (after === ":" && close !== void 0) {
8402
+ for (let cursor = close + 2; cursor < close + 40; cursor++) {
8403
+ const token = value(cursor);
8404
+ if (token === "=>" || token === "{") return true;
8405
+ if (token === void 0 || token === ";" || token === ")") break;
8406
+ const skip = match.get(cursor);
8407
+ if (skip !== void 0 && token !== "{") cursor = skip;
8408
+ }
8409
+ }
8410
+ return false;
8411
+ }
8412
+ if (after === "=" && value((close ?? 0) + 2) !== "=") return true;
8413
+ if (DECLARE.has(value(parent - 1) ?? "")) return true;
8414
+ parent = parentOf[parent];
8415
+ }
8416
+ return false;
8417
+ };
8418
+ const endsCleanly = (last) => {
8419
+ const next = at2(last + 1);
8420
+ return next === void 0 || next.line > at2(last).line && !".[(?".includes(next.value) || next.value === ";" || next.value === "," || next.value === "as" && value(last + 2) === "const";
8421
+ };
8422
+ const constants3 = /* @__PURE__ */ new Map();
8423
+ {
8424
+ const bindings = /* @__PURE__ */ new Map();
8425
+ tokens.forEach((token, index) => {
8426
+ if (token.kind === "ident" && binds(index) && value(index - 1) !== ".")
8427
+ bindings.set(token.value, (bindings.get(token.value) ?? 0) + 1);
8428
+ });
8429
+ tokens.forEach((token, index) => {
8430
+ const name = at2(index + 1);
8431
+ if (token.kind !== "ident" || token.value !== "const" || name?.kind !== "ident" || !isPunct(index + 2, "=") || bindings.get(name.value) !== 1)
8432
+ return;
8433
+ const start = index + 3;
8434
+ const last = at2(start)?.kind === "string" ? start : isPunct(start, "[") ? match.get(start) : void 0;
8435
+ if (last !== void 0 && endsCleanly(last))
8436
+ constants3.set(name.value, start);
8437
+ });
8438
+ }
8439
+ const MAX_SENTENCES = 1e4;
8440
+ const MAX_DEPTH = 32;
8441
+ let truncated = false;
8442
+ const reading = /* @__PURE__ */ new Set();
8443
+ const argument = (index) => {
8444
+ const token = at2(index);
8445
+ if (!token) return index;
8446
+ const end = skipExpression(index);
8447
+ if (token.kind === "string" && end === index + 1) {
8448
+ if (token.dynamic) dynamic(token);
8449
+ else if (sentences.length >= MAX_SENTENCES) truncated = true;
8450
+ else
8451
+ sentences.push({
8452
+ text: token.value,
8453
+ source: { file, line: token.line, col: token.col }
8454
+ });
8455
+ return end;
8456
+ }
8457
+ const declared2 = token.kind === "ident" && end === index + 1 ? constants3.get(token.value) : void 0;
8458
+ if (declared2 !== void 0 && (reading.size >= MAX_DEPTH || sentences.length >= MAX_SENTENCES)) {
8459
+ truncated = true;
8460
+ return end;
8461
+ }
8462
+ if (declared2 !== void 0 && !reading.has(token.value)) {
8463
+ reading.add(token.value);
8464
+ if (isPunct(declared2, "[")) list(declared2);
8465
+ else argument(declared2);
8466
+ reading.delete(token.value);
8467
+ return end;
8468
+ }
8469
+ dynamic(token);
8470
+ return end;
8471
+ };
8472
+ const list = (index) => {
8473
+ let cursor = index + 1;
8474
+ while (cursor < tokens.length && !isPunct(cursor, "]")) {
8475
+ cursor = argument(cursor);
8476
+ if (isPunct(cursor, ",")) cursor++;
8477
+ else if (!isPunct(cursor, "]")) cursor++;
8478
+ }
8479
+ };
8480
+ const call2 = (open2) => {
8481
+ const first = open2 + 1;
8482
+ if (isPunct(first, ")")) return;
8483
+ if (isPunct(first, "[")) list(first);
8484
+ else argument(first);
8485
+ };
8486
+ const inlineFunction = (index) => {
8487
+ let cursor = index;
8488
+ if (value(cursor) === "async") cursor++;
8489
+ if (value(cursor) === "function") return true;
8490
+ if (at2(cursor)?.kind === "ident" && value(cursor + 1) === "=>") return true;
8491
+ const close = isPunct(cursor, "(") ? match.get(cursor) : void 0;
8492
+ return close !== void 0 && value(close + 1) === "=>";
8493
+ };
8494
+ const parameters = (paren) => {
8495
+ const close = match.get(paren);
8496
+ if (close === void 0) return [];
8497
+ const names = [];
8498
+ let expectName = true;
8499
+ for (let cursor = paren + 1; cursor < close; cursor++) {
8500
+ if (expectName) {
8501
+ const token = at2(cursor);
8502
+ names.push(token?.kind === "ident" ? token.value : "");
8503
+ expectName = false;
8504
+ }
8505
+ const skip = match.get(cursor);
8506
+ if (skip !== void 0) cursor = skip;
8507
+ else if (isPunct(cursor, ",")) expectName = true;
8508
+ }
8509
+ return names;
8510
+ };
8511
+ const bindingCount = /* @__PURE__ */ new Map();
8512
+ tokens.forEach((token, index) => {
8513
+ if (token.kind === "ident" && value(index - 1) !== "." && binds(index))
8514
+ bindingCount.set(token.value, (bindingCount.get(token.value) ?? 0) + 1);
8515
+ });
8516
+ const functions = /* @__PURE__ */ new Map();
8517
+ const ambiguous = /* @__PURE__ */ new Set();
8518
+ tokens.forEach((token, index) => {
8519
+ const name = at2(index + 1);
8520
+ if (token.kind !== "ident" || name?.kind !== "ident") return;
8521
+ if ((bindingCount.get(name.value) ?? 0) > 1) {
8522
+ if (token.value === "function" && isPunct(index + 2, "(") || ["const", "let", "var"].includes(token.value) && isPunct(index + 2, "=") && inlineFunction(index + 3))
8523
+ ambiguous.add(name.value);
8524
+ return;
8525
+ }
8526
+ if (token.value === "function" && isPunct(index + 2, "("))
8527
+ functions.set(name.value, parameters(index + 2));
8528
+ else if (["const", "let", "var"].includes(token.value) && isPunct(index + 2, "=") && inlineFunction(index + 3)) {
8529
+ let start = index + 3;
8530
+ if (value(start) === "async") start++;
8531
+ if (value(start) === "function") start++;
8532
+ if (isPunct(start, "(")) functions.set(name.value, parameters(start));
8533
+ else if (at2(start)?.kind === "ident" && isPunct(start + 1, "("))
8534
+ functions.set(name.value, parameters(start + 1));
8535
+ else if (at2(start)?.kind === "ident")
8536
+ functions.set(name.value, [value(start)]);
8537
+ }
8538
+ });
8539
+ const helperCalls = [];
8540
+ const aliasUse = (index) => {
8541
+ const next = value(index + 1);
8542
+ const prev = value(index - 1);
8543
+ if (next === "(" || next === "?") return void 0;
8544
+ if (next === ".") {
8545
+ const member = value(index + 2);
8546
+ return ["call", "apply", "bind"].includes(member ?? "") ? "This ai call is written indirectly, so its sentences are not checked before a run." : void 0;
8547
+ }
8548
+ if (next === ":") {
8549
+ const brace = parentOf[index];
8550
+ return brace !== void 0 && DECLARE.has(value(brace - 1) ?? "") && at2(index + 2)?.kind === "ident" ? "`ai` is renamed here, so the steps called through the new name are not checked before a run." : void 0;
8551
+ }
8552
+ if ((prev === "{" || prev === ",") && (next === "}" || next === ",")) {
8553
+ const brace = parentOf[index];
8554
+ if (brace !== void 0 && value(brace) === "{")
8555
+ return handedOver(brace, "`{ ai }`");
8556
+ }
8557
+ const parent = parentOf[index];
8558
+ if (parent !== void 0 && value(parent) === "(") {
8559
+ const close = match.get(parent);
8560
+ const after = close === void 0 ? void 0 : value(close + 1);
8561
+ if (after === "=>" || after === "{" || after === ":") return void 0;
8562
+ const callee = at2(parent - 1);
8563
+ if (callee?.kind === "ident" && value(parent - 2) !== "." && !CONTROL.has(callee.value) && (next === "," || next === ")")) {
8564
+ let position2 = 0;
8565
+ for (let cursor = parent + 1; cursor < index; cursor++) {
8566
+ const skip = match.get(cursor);
8567
+ if (skip !== void 0) cursor = skip;
8568
+ else if (isPunct(cursor, ",")) position2++;
8569
+ }
8570
+ if (ambiguous.has(callee.value))
8571
+ return `\`${callee.value}\` is declared more than once in this file, so validation cannot tell which one receives the test's ai.`;
8572
+ const local = functions.get(callee.value);
8573
+ if (local)
8574
+ return local[position2] === "ai" ? void 0 : `\`${callee.value}\` receives the test's ai under another name, so the steps it runs are not checked before a run.`;
8575
+ const token = at2(index);
8576
+ helperCalls.push({
8577
+ callee: callee.value,
8578
+ position: position2,
8579
+ source: { file, line: token.line, col: token.col },
8580
+ passes: "ai"
8581
+ });
8582
+ return void 0;
8583
+ }
8584
+ }
8585
+ return "`ai` is passed on as a value here, so the steps it runs are not checked before a run.";
8586
+ };
8587
+ const handedOver = (index, what) => {
8588
+ const parent = parentOf[index];
8589
+ if (parent === void 0 || value(parent) !== "(") return void 0;
8590
+ const close = match.get(parent);
8591
+ const after = close === void 0 ? void 0 : value(close + 1);
8592
+ if (after === "=>" || after === "{" || after === ":") return void 0;
8593
+ const callee = at2(parent - 1);
8594
+ if (callee?.kind !== "ident" || CONTROL.has(callee.value)) return void 0;
8595
+ if (value(parent - 2) === ".")
8596
+ return `${what} is handed to \`${callee.value}\` through another object, so the steps it runs are not checked before a run.`;
8597
+ if (ambiguous.has(callee.value))
8598
+ return `\`${callee.value}\` is declared more than once in this file, so validation cannot tell which one receives ${what}.`;
8599
+ if (functions.has(callee.value)) return void 0;
8600
+ let position2 = 0;
8601
+ for (let cursor = parent + 1; cursor < index; cursor++) {
8602
+ const skip = match.get(cursor);
8603
+ if (skip !== void 0) cursor = skip;
8604
+ else if (isPunct(cursor, ",")) position2++;
8605
+ }
8606
+ const token = at2(index);
8607
+ helperCalls.push({
8608
+ callee: callee.value,
8609
+ position: position2,
8610
+ source: { file, line: token.line, col: token.col },
8611
+ passes: "context"
8612
+ });
8613
+ return void 0;
8614
+ };
8615
+ const unchecked = (token, message) => warnings.push({
8616
+ severity: "warning",
8617
+ code: "unchecked_call",
8618
+ source: { file, line: token.line, col: token.col },
8619
+ message,
8620
+ fix: "Call the test's `ai` directly, as ai(...) or ai.group(...), so its sentences can be checked before a run."
8621
+ });
8622
+ const renamedParameter = (index) => {
8623
+ if (!isPunct(index + 1, ":") || at2(index + 2)?.kind !== "ident")
8624
+ return false;
8625
+ const brace = parentOf[index];
8626
+ if (brace === void 0 || value(brace) !== "{") return false;
8627
+ if (value(brace - 1) === ":") return false;
8628
+ const paren = parentOf[brace];
8629
+ if (paren === void 0 || value(paren) !== "(") return false;
8630
+ const close = match.get(paren);
8631
+ return close !== void 0 && (value(close + 1) === "=>" || value(close + 1) === "{");
8632
+ };
8633
+ tokens.forEach((token, index) => {
8634
+ if (token.kind === "string" && !token.dynamic && token.value === "ai" && isPunct(index - 1, "[") && isPunct(index + 1, "]") && value(index - 2) !== "TestContext")
8635
+ unchecked(
8636
+ token,
8637
+ "This reaches ai through another object, so the steps it runs are not checked before a run."
8638
+ );
8639
+ });
8640
+ const contexts = /* @__PURE__ */ new Set();
8641
+ tokens.forEach((token, index) => {
8642
+ if (token.kind !== "ident" || token.value !== "test" || !isPunct(index + 1, "("))
8643
+ return;
8644
+ const close = match.get(index + 1);
8645
+ if (close === void 0) return;
8646
+ for (let cursor = index + 2; cursor < close; cursor++) {
8647
+ if (parentOf[cursor] !== index + 1) continue;
8648
+ let start = cursor;
8649
+ if (value(start) === "async") start++;
8650
+ if (value(start) === "function") start++;
8651
+ const inner = isPunct(start, "(") ? match.get(start) : void 0;
8652
+ if (inner !== void 0 && (value(inner + 1) === "=>" || value(start - 1) === "function")) {
8653
+ const first = parameters(start)[0];
8654
+ if (first) contexts.add(first);
8655
+ }
8656
+ }
8657
+ });
8658
+ tokens.forEach((token, index) => {
8659
+ if (token.kind !== "ident" || !contexts.has(token.value) || value(index - 1) === "." || !["(", ","].includes(value(index - 1) ?? "") || ![")", ","].includes(value(index + 1) ?? ""))
8660
+ return;
8661
+ const reason = handedOver(index, `The test's context \`${token.value}\``);
8662
+ if (reason) unchecked(token, reason);
8663
+ });
8664
+ tokens.forEach((token, index) => {
8665
+ if (token.kind === "ident" && token.value !== "ai" && value(index - 1) !== "." && isPunct(index + 1, ":") && (value(index + 2) === "Ai" || value(index + 2) === "TestContext" && isPunct(index + 3, "[") && at2(index + 4)?.kind === "string" && value(index + 4) === "ai"))
8666
+ unchecked(
8667
+ token,
8668
+ `\`${token.value}\` holds the test's ai, so the steps called through it are not checked before a run.`
8669
+ );
8670
+ });
8671
+ for (let index = 0; index < tokens.length; index++) {
8672
+ const token = tokens[index];
8673
+ if (token.kind !== "ident" || token.value !== "ai") continue;
8674
+ if (isPunct(index - 1, ".")) {
8675
+ unchecked(
8676
+ token,
8677
+ "This reaches ai through another object, so the steps it runs are not checked before a run."
8678
+ );
8679
+ continue;
8680
+ }
8681
+ if (renamedParameter(index)) {
8682
+ unchecked(
8683
+ token,
8684
+ "`ai` is renamed here, so the steps called through the new name are not checked before a run."
8685
+ );
8686
+ continue;
8687
+ }
8688
+ if (isPunct(index + 1, "?") && isPunct(index + 2, ".") && isPunct(index + 3, "(") || isPunct(index - 1, "(") && isPunct(index + 1, ")") && isPunct(index + 2, "(")) {
8689
+ unchecked(
8690
+ token,
8691
+ "This ai call is written indirectly, so its sentences are not checked before a run."
8692
+ );
8693
+ continue;
8694
+ }
8695
+ const alias = aliasUse(index);
8696
+ if (alias) {
8697
+ unchecked(token, alias);
8698
+ continue;
8699
+ }
8700
+ if (isPunct(index + 1, "(")) {
8701
+ call2(index + 1);
8702
+ continue;
8703
+ }
8704
+ if (isPunct(index + 1, ".") && at2(index + 2)?.kind === "ident" && at2(index + 2).value === "group" && isPunct(index + 3, "(")) {
8705
+ const afterName = skipExpression(index + 4);
8706
+ if (!isPunct(afterName, ",")) continue;
8707
+ const second = afterName + 1;
8708
+ const first = at2(second);
8709
+ if (isPunct(second, "[")) list(second);
8710
+ else if (first?.kind === "string" || first?.kind === "ident" && constants3.has(first.value))
8711
+ argument(second);
8712
+ else if (!inlineFunction(second) && !(first?.kind === "ident" && functions.has(first.value) && skipExpression(second) === second + 1))
8713
+ argument(second);
8714
+ }
8715
+ }
8716
+ if (truncated)
8717
+ warnings.push({
8718
+ severity: "warning",
8719
+ code: "too_many_sentences",
8720
+ source: { file, line: 1, col: 1 },
8721
+ message: `This file's lists expand to more than ${MAX_SENTENCES} step sentences, or nest more than ${MAX_DEPTH} deep; the rest were not checked.`,
8722
+ fix: "Split the lists, or pass fewer copies of them to ai()."
8723
+ });
8724
+ return { sentences, warnings, functions, helperCalls };
8725
+ }
8726
+ function scanLocalImports(source) {
8727
+ const tokens = tokenize(source);
8728
+ const found = /* @__PURE__ */ new Set();
8729
+ tokens.forEach((token, index) => {
8730
+ const next = tokens[index + 1];
8731
+ const after = tokens[index + 2];
8732
+ let specifier;
8733
+ if (token.kind === "ident" && token.value === "from") specifier = next;
8734
+ else if (token.kind === "ident" && token.value === "import")
8735
+ specifier = next?.kind === "punct" && next.value === "(" ? after : next;
8736
+ else if (token.kind === "ident" && token.value === "require" && next?.kind === "punct" && next.value === "(")
8737
+ specifier = after;
8738
+ if (specifier?.kind === "string" && !specifier.dynamic && /^\.\.?\//u.test(specifier.value))
8739
+ found.add(specifier.value);
8740
+ });
8741
+ return [...found];
8742
+ }
8743
+ function scanImportBindings(source) {
8744
+ const tokens = tokenize(source);
8745
+ const bindings = [];
8746
+ tokens.forEach((token, index) => {
8747
+ if (token.kind !== "ident" || token.value !== "import") return;
8748
+ const names = [];
8749
+ let cursor = index + 1;
8750
+ if (tokens[cursor]?.kind === "ident" && tokens[cursor].value === "type")
8751
+ cursor++;
8752
+ if (tokens[cursor]?.kind === "ident" && tokens[cursor].value !== "from") {
8753
+ names.push({ local: tokens[cursor].value, imported: "default" });
8754
+ cursor++;
8755
+ if (tokens[cursor]?.value === ",") cursor++;
8756
+ }
8757
+ if (tokens[cursor]?.value === "{") {
8758
+ cursor++;
8759
+ while (cursor < tokens.length && tokens[cursor].value !== "}") {
8760
+ const name = tokens[cursor];
8761
+ if (name?.kind === "ident" && name.value !== "type") {
8762
+ if (tokens[cursor + 1]?.value === "as" && tokens[cursor + 2]?.kind === "ident") {
8763
+ names.push({
8764
+ local: tokens[cursor + 2].value,
8765
+ imported: name.value
8766
+ });
8767
+ cursor += 3;
8768
+ continue;
8769
+ }
8770
+ names.push({ local: name.value, imported: name.value });
8771
+ }
8772
+ cursor++;
8773
+ }
8774
+ cursor++;
8775
+ }
8776
+ const from = tokens[cursor];
8777
+ const specifier = tokens[cursor + 1];
8778
+ if (from?.kind === "ident" && from.value === "from" && specifier?.kind === "string" && !specifier.dynamic)
8779
+ for (const name of names)
8780
+ bindings.push({ ...name, specifier: specifier.value });
8781
+ });
8782
+ return bindings;
8783
+ }
8784
+ function callExtent(source, line) {
8785
+ const tokens = tokenize(source);
8786
+ const open2 = [];
8787
+ let best;
8788
+ tokens.forEach((token, index) => {
8789
+ if (token.kind !== "punct") return;
8790
+ if ("([{".includes(token.value)) open2.push(index);
8791
+ else if (")]}".includes(token.value)) {
8792
+ const opener = open2.pop();
8793
+ if (opener === void 0 || tokens[opener].value !== "(" || tokens[opener].line !== line || tokens[opener - 1]?.kind !== "ident")
8794
+ return;
8795
+ if (best === void 0 || token.line > tokens[best].line) best = index;
8796
+ }
8797
+ });
8798
+ return best === void 0 ? void 0 : { start: line, end: tokens[best].line };
8799
+ }
8800
+
8801
+ // src/project-validation.ts
8802
+ var NOT_CHECKED_OFFLINE_CODE = "unavailable";
8803
+ var OPERATIONAL_CODES = /* @__PURE__ */ new Set([
8804
+ "provider_error",
8805
+ "cache_error",
8806
+ "unreadable_file"
8807
+ ]);
8808
+ function compareDiagnostics3(a, b) {
8809
+ const text = (left, right) => left < right ? -1 : left > right ? 1 : 0;
8810
+ return text(a.source.file, b.source.file) || a.source.line - b.source.line || a.source.col - b.source.col || text(a.code, b.code) || text(a.message, b.message);
8811
+ }
8812
+ function dedupeDiagnostics(diagnostics) {
8813
+ const seen = /* @__PURE__ */ new Set();
7366
8814
  const unique = [];
7367
8815
  for (const item of diagnostics) {
7368
8816
  const key = JSON.stringify([
@@ -7396,35 +8844,186 @@ function entryUrlDiagnostic(flow, baseUrl) {
7396
8844
  };
7397
8845
  }
7398
8846
  }
7399
- async function checkUnreferencedModule(file, options) {
8847
+ async function validateScriptFile(file, options, classify) {
8848
+ const script = await loadScriptFile(file, { repoRoot: options.repoRoot });
8849
+ const headers = scriptListingEntries(script).flatMap(
8850
+ (entry) => entry.result.value ? [entry.result.value] : []
8851
+ );
8852
+ const diagnostics = [...script.diagnostics];
8853
+ for (const header of headers) {
8854
+ if (header.url === void 0 || options.baseUrl === void 0) continue;
8855
+ const entry = entryUrlDiagnostic(header, options.baseUrl);
8856
+ if (entry)
8857
+ diagnostics.push({
8858
+ ...entry,
8859
+ source: script.tests.find((test2) => test2.identity === header.identity)?.source ?? entry.source
8860
+ });
8861
+ }
7400
8862
  let source;
7401
8863
  try {
7402
8864
  source = await readFile2(file, "utf8");
7403
8865
  } catch {
7404
8866
  return {
8867
+ headers,
7405
8868
  diagnostics: [
8869
+ ...diagnostics,
7406
8870
  {
7407
8871
  severity: "error",
7408
8872
  code: "unreadable_file",
7409
8873
  source: { file, line: 1, col: 1 },
7410
- message: "Could not read this module file.",
7411
- fix: "Check the path and file permissions."
8874
+ message: "The test file could not be read.",
8875
+ fix: "Check the file permissions and rerun."
7412
8876
  }
7413
8877
  ],
7414
- calls: []
8878
+ calls: [],
8879
+ coverage: {
8880
+ format: "failed",
8881
+ steps: "not_checked",
8882
+ modules: "not_needed"
8883
+ }
7415
8884
  };
7416
8885
  }
7417
- const parsed = parseModule(source, file);
7418
- if (!parsed.value) return { diagnostics: parsed.diagnostics, calls: [] };
7419
- const checked = await classifySentenceSteps(
7420
- directSentences(parsed.value.steps),
7421
- options
8886
+ const read = [{ file, source, scan: scanScriptSentences(source, file) }];
8887
+ const { helpers, truncated } = await localHelpers(
8888
+ file,
8889
+ source,
8890
+ options.repoRoot
7422
8891
  );
8892
+ for (const helper of helpers) {
8893
+ const text = await readFile2(helper, "utf8").catch(() => "");
8894
+ read.push({
8895
+ file: helper,
8896
+ source: text,
8897
+ scan: scanScriptSentences(text, helper)
8898
+ });
8899
+ }
8900
+ const scans = read.map((item) => item.scan);
8901
+ const warnings = [
8902
+ ...scans.flatMap((scan) => scan.warnings),
8903
+ ...unresolvedHelperCalls(read)
8904
+ ];
8905
+ if (truncated)
8906
+ warnings.push({
8907
+ severity: "warning",
8908
+ code: "too_many_helpers",
8909
+ source: { file, line: 1, col: 1 },
8910
+ message: `This test imports more than ${MAX_HELPERS} local modules; the sentences in the rest were not checked.`,
8911
+ fix: "Keep shared steps in fewer modules."
8912
+ });
8913
+ diagnostics.push(...warnings);
8914
+ const sentences = scans.flatMap((scan) => scan.sentences).map((item) => ({
8915
+ kind: "sentence",
8916
+ phase: "steps",
8917
+ text: item.text,
8918
+ tokens: tokenizeStep(item.text).tokens,
8919
+ source: item.source
8920
+ }));
8921
+ const checked = await classifySentenceSteps(sentences, classify);
8922
+ diagnostics.push(...checked.diagnostics);
8923
+ const complete = checked.classification.steps.every((step) => step !== null) && checked.diagnostics.length === 0 && warnings.length === 0;
7423
8924
  return {
7424
- diagnostics: [...parsed.diagnostics, ...checked.diagnostics],
7425
- calls: checked.classification.calls
7426
- };
7427
- }
8925
+ headers,
8926
+ diagnostics,
8927
+ calls: checked.classification.calls,
8928
+ coverage: {
8929
+ format: script.diagnostics.length ? "failed" : "passed",
8930
+ steps: complete ? "checked" : "incomplete",
8931
+ modules: "not_needed"
8932
+ }
8933
+ };
8934
+ }
8935
+ var HELPER_EXTENSIONS = [".ts", ".mts", ".cts", ".tsx", ".js", ".mjs"];
8936
+ var MAX_HELPERS = 64;
8937
+ function resolveHelper(from, specifier) {
8938
+ const base = path7.resolve(path7.dirname(from), specifier);
8939
+ const stem = base.replace(/\.(?:m|c)?js$/u, "");
8940
+ const candidates = [
8941
+ base,
8942
+ ...HELPER_EXTENSIONS.map((extension) => stem + extension),
8943
+ ...HELPER_EXTENSIONS.map(
8944
+ (extension) => path7.join(base, `index${extension}`)
8945
+ )
8946
+ ];
8947
+ return candidates.find(
8948
+ (candidate) => HELPER_EXTENSIONS.some((extension) => candidate.endsWith(extension)) && existsSync3(candidate) && statSync2(candidate).isFile()
8949
+ );
8950
+ }
8951
+ function unresolvedHelperCalls(read) {
8952
+ const byPath = new Map(
8953
+ read.map((item) => [realpathSync.native(item.file), item.scan])
8954
+ );
8955
+ const warnings = [];
8956
+ for (const { file, source, scan } of read) {
8957
+ if (!scan.helperCalls.length) continue;
8958
+ const imports = scanImportBindings(source);
8959
+ for (const call2 of scan.helperCalls) {
8960
+ const binding = imports.find((item) => item.local === call2.callee);
8961
+ const target = binding ? resolveHelper(file, binding.specifier) : void 0;
8962
+ const helper = target ? byPath.get(realpathSync.native(target)) : void 0;
8963
+ const parameters = binding && helper ? helper.functions.get(binding.imported) : void 0;
8964
+ if (call2.passes === "context" ? parameters : parameters?.[call2.position] === "ai")
8965
+ continue;
8966
+ warnings.push({
8967
+ severity: "warning",
8968
+ code: "unchecked_call",
8969
+ source: call2.source,
8970
+ message: parameters ? `\`${call2.callee}\` receives the test's ai under another name, so the steps it runs are not checked before a run.` : `Validation cannot follow \`${call2.callee}\` to a local module, so the steps it runs with the test's ai are not checked before a run.`,
8971
+ fix: "Declare the helper in the test file or a local module, with its parameter named `ai`."
8972
+ });
8973
+ }
8974
+ }
8975
+ return warnings;
8976
+ }
8977
+ async function localHelpers(file, source, repoRoot) {
8978
+ const root = realpathSync.native(repoRoot);
8979
+ const seen = /* @__PURE__ */ new Set([realpathSync.native(file)]);
8980
+ const helpers = [];
8981
+ const queue2 = [[file, source]];
8982
+ while (queue2.length) {
8983
+ const [from, text] = queue2.shift();
8984
+ for (const specifier of scanLocalImports(text)) {
8985
+ const found = resolveHelper(from, specifier);
8986
+ const target = found && realpathSync.native(found);
8987
+ const relative = target && path7.relative(root, target);
8988
+ if (!target || seen.has(target) || !relative || relative.startsWith("..") || path7.isAbsolute(relative) || relative.split(path7.sep).includes("node_modules"))
8989
+ continue;
8990
+ if (helpers.length >= MAX_HELPERS) return { helpers, truncated: true };
8991
+ seen.add(target);
8992
+ helpers.push(target);
8993
+ queue2.push([target, await readFile2(target, "utf8").catch(() => "")]);
8994
+ }
8995
+ }
8996
+ return { helpers, truncated: false };
8997
+ }
8998
+ async function checkUnreferencedModule(file, options) {
8999
+ let source;
9000
+ try {
9001
+ source = await readFile2(file, "utf8");
9002
+ } catch {
9003
+ return {
9004
+ diagnostics: [
9005
+ {
9006
+ severity: "error",
9007
+ code: "unreadable_file",
9008
+ source: { file, line: 1, col: 1 },
9009
+ message: "Could not read this module file.",
9010
+ fix: "Check the path and file permissions."
9011
+ }
9012
+ ],
9013
+ calls: []
9014
+ };
9015
+ }
9016
+ const parsed = parseModule(source, file);
9017
+ if (!parsed.value) return { diagnostics: parsed.diagnostics, calls: [] };
9018
+ const checked = await classifySentenceSteps(
9019
+ directSentences(parsed.value.steps),
9020
+ options
9021
+ );
9022
+ return {
9023
+ diagnostics: [...parsed.diagnostics, ...checked.diagnostics],
9024
+ calls: checked.classification.calls
9025
+ };
9026
+ }
7428
9027
  async function validateProject(input, options) {
7429
9028
  const classify = {
7430
9029
  mode: options.mode,
@@ -7439,18 +9038,33 @@ async function validateProject(input, options) {
7439
9038
  const flows = [];
7440
9039
  let allTestsValidated = true;
7441
9040
  for (const file of input.tests) {
7442
- const loaded = await loadFlowFile(file, {
9041
+ if (isScriptTestFile(file)) {
9042
+ const checked = await validateScriptFile(file, options, classify);
9043
+ flows.push(...checked.headers);
9044
+ diagnostics.push(...checked.diagnostics);
9045
+ calls.push(...checked.calls);
9046
+ if (!isFullyValidated(checked.coverage, checked.diagnostics))
9047
+ allTestsValidated = false;
9048
+ files.push({
9049
+ file,
9050
+ kind: "test",
9051
+ ...checked.headers[0] ? { identity: checked.headers[0].identity } : {},
9052
+ coverage: checked.coverage
9053
+ });
9054
+ continue;
9055
+ }
9056
+ const loaded2 = await loadFlowFile(file, {
7443
9057
  repoRoot: options.repoRoot,
7444
9058
  ...options.baseUrl ? { baseUrl: options.baseUrl } : {}
7445
9059
  });
7446
- const flow = loaded.value ?? loaded.candidate;
9060
+ const flow = loaded2.value ?? loaded2.candidate;
7447
9061
  if (flow) flows.push(flow);
7448
9062
  const entry = flow && options.baseUrl !== void 0 ? entryUrlDiagnostic(flow, options.baseUrl) : null;
7449
9063
  if (entry) {
7450
9064
  diagnostics.push(entry);
7451
9065
  allTestsValidated = false;
7452
9066
  }
7453
- const resolved = await resolveFlowModules(loaded, {
9067
+ const resolved = await resolveFlowModules(loaded2, {
7454
9068
  repoRoot: options.repoRoot,
7455
9069
  partial: true
7456
9070
  });
@@ -7504,9 +9118,9 @@ async function validateProject(input, options) {
7504
9118
  }
7505
9119
 
7506
9120
  // src/project-listing.ts
7507
- import path6 from "path";
9121
+ import path8 from "path";
7508
9122
  function displayPath(root, file) {
7509
- return path6.relative(root, file).split(path6.sep).join("/");
9123
+ return path8.relative(root, file).split(path8.sep).join("/");
7510
9124
  }
7511
9125
  function listTests(parsed, options) {
7512
9126
  const collisions = findIdentityCollisions(
@@ -7550,6 +9164,803 @@ function listTests(parsed, options) {
7550
9164
  }
7551
9165
  return { tests, invalid };
7552
9166
  }
9167
+ async function loadListingEntries(files, options) {
9168
+ const entries = [];
9169
+ for (const file of files) {
9170
+ if (isScriptTestFile(file))
9171
+ entries.push(
9172
+ ...scriptListingEntries(
9173
+ await loadScriptFile(file, { repoRoot: options.repoRoot })
9174
+ )
9175
+ );
9176
+ else
9177
+ entries.push({
9178
+ file,
9179
+ result: await loadFlowFile(file, {
9180
+ repoRoot: options.repoRoot,
9181
+ ...options.rejectSymlinks ? { rejectSymlinks: true } : {}
9182
+ })
9183
+ });
9184
+ }
9185
+ return entries;
9186
+ }
9187
+
9188
+ // src/script-runner.ts
9189
+ import { readFile as readFile3 } from "fs/promises";
9190
+ import path10 from "path";
9191
+
9192
+ // src/script-rejections.ts
9193
+ import path9 from "path";
9194
+ function insideProject(file, root) {
9195
+ const relative = path9.relative(root, file);
9196
+ return relative !== "" && !relative.startsWith("..") && !path9.isAbsolute(relative) && !relative.split(/[\\/]/u).includes("node_modules");
9197
+ }
9198
+ function attributeRejection(reason, running, known, projectRoot) {
9199
+ const stack = reason instanceof Error ? reason.stack : void 0;
9200
+ const frames = (stack?.split("\n").slice(1) ?? []).flatMap((frame) => {
9201
+ const source = parseFrame(frame);
9202
+ return source ? [source] : [];
9203
+ });
9204
+ const root = pathKey(projectRoot);
9205
+ const project = frames.filter(
9206
+ (frame) => insideProject(pathKey(frame.file), root)
9207
+ );
9208
+ const inside2 = (line, lines) => line >= lines.start && line <= lines.end;
9209
+ for (const frame of project) {
9210
+ if (!frame.file.endsWith(".test.ts")) continue;
9211
+ const key = pathKey(frame.file);
9212
+ const holders = (known.get(key) ?? []).filter(
9213
+ (lines) => inside2(frame.line, lines)
9214
+ );
9215
+ const owners = running.flatMap(
9216
+ (test2, index) => pathKey(test2.file) === key && inside2(frame.line, test2.lines) ? [index] : []
9217
+ );
9218
+ if (holders.length > 1 || owners.length > 1)
9219
+ return { kind: "run", reason: "shared", source: frame };
9220
+ if (owners.length === 1) return { kind: "attempt", index: owners[0] };
9221
+ if (holders.length === 1)
9222
+ return {
9223
+ kind: "run",
9224
+ reason: "finished",
9225
+ source: frame,
9226
+ ...holders[0].id ? { test: holders[0].id } : {}
9227
+ };
9228
+ }
9229
+ if (project[0]) return { kind: "run", reason: "outside", source: project[0] };
9230
+ return { kind: "run", reason: frames.length ? "internal" : "unknown" };
9231
+ }
9232
+ function describeRejection(reason) {
9233
+ const text = reason instanceof Error ? `${reason.name}: ${reason.message}` : typeof reason === "string" ? reason : "a non-Error value";
9234
+ return (text.split("\n")[0] ?? text).slice(0, 300);
9235
+ }
9236
+ var RejectionRouter = class _RejectionRouter {
9237
+ constructor(projectRoot) {
9238
+ this.projectRoot = projectRoot;
9239
+ }
9240
+ projectRoot;
9241
+ #attempts = /* @__PURE__ */ new Map();
9242
+ /** Every test's lines seen this run, by file, kept after it finishes. */
9243
+ #known = /* @__PURE__ */ new Map();
9244
+ #unattributed = [];
9245
+ #installed = false;
9246
+ static #routing = 0;
9247
+ /**
9248
+ * Whether any router is listening. A process-wide fallback for rejections
9249
+ * that arrive after a run (the `sedum` binary installs one) stands aside
9250
+ * while a router owns them.
9251
+ */
9252
+ static get routing() {
9253
+ return _RejectionRouter.#routing > 0;
9254
+ }
9255
+ /** Rejections no running test could own, in arrival order. */
9256
+ get unattributed() {
9257
+ return this.#unattributed;
9258
+ }
9259
+ #handle = (reason) => {
9260
+ const attempts = [...this.#attempts.values()];
9261
+ const owner = attributeRejection(
9262
+ reason,
9263
+ attempts,
9264
+ this.#known,
9265
+ this.projectRoot
9266
+ );
9267
+ if (owner.kind === "attempt") {
9268
+ attempts[owner.index].receive(reason);
9269
+ return;
9270
+ }
9271
+ this.#unattributed.push({
9272
+ reason: owner.reason,
9273
+ message: describeRejection(reason),
9274
+ ...owner.source ? { source: owner.source } : {},
9275
+ ...owner.test ? { test: owner.test } : {}
9276
+ });
9277
+ };
9278
+ install() {
9279
+ if (this.#installed) return;
9280
+ process.on("unhandledRejection", this.#handle);
9281
+ this.#installed = true;
9282
+ _RejectionRouter.#routing++;
9283
+ }
9284
+ dispose() {
9285
+ if (!this.#installed) return;
9286
+ process.off("unhandledRejection", this.#handle);
9287
+ this.#installed = false;
9288
+ _RejectionRouter.#routing--;
9289
+ }
9290
+ /**
9291
+ * Route rejections from one running test to `receive` until released.
9292
+ * `lines` is that test's range; `fileTests` are all of its file's tests.
9293
+ */
9294
+ register(test2, fileTests, receive) {
9295
+ this.#known.set(pathKey(test2.file), fileTests);
9296
+ const key = Symbol(test2.file);
9297
+ this.#attempts.set(key, { ...test2, receive });
9298
+ return () => {
9299
+ this.#attempts.delete(key);
9300
+ };
9301
+ }
9302
+ };
9303
+
9304
+ // src/script-runner.ts
9305
+ var KEY = /^[A-Za-z_][A-Za-z0-9_]*$/u;
9306
+ var EXTRACT_KEY = "sedum_extracted";
9307
+ var MAX_GROUP_DEPTH = 16;
9308
+ var REMEMBER_AS = /^(?:remember|capture)\b.*\bas\s+\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}\s*\.?$/iu;
9309
+ var STEP_ERROR = /* @__PURE__ */ Symbol.for("sedum.script.stepError");
9310
+ var THROWN_IN = /* @__PURE__ */ Symbol("sedum.script.thrownIn");
9311
+ var ScriptUsageError = class extends Error {
9312
+ constructor(code, message, fix) {
9313
+ super(message);
9314
+ this.code = code;
9315
+ this.fix = fix;
9316
+ this.name = "ScriptUsageError";
9317
+ }
9318
+ code;
9319
+ fix;
9320
+ };
9321
+ var StepStop = class extends Error {
9322
+ constructor(problem) {
9323
+ super(
9324
+ problem.status === "failed" ? "A Sedum step failed; see the run report." : `A Sedum step could not run: ${problem.message}`
9325
+ );
9326
+ this.problem = problem;
9327
+ this.name = "SedumStepError";
9328
+ }
9329
+ problem;
9330
+ [STEP_ERROR] = true;
9331
+ };
9332
+ function isStepStop(error2) {
9333
+ return typeof error2 === "object" && error2 !== null && error2[STEP_ERROR] === true;
9334
+ }
9335
+ var StepPromise = class extends Promise {
9336
+ observed = false;
9337
+ static get [Symbol.species]() {
9338
+ return Promise;
9339
+ }
9340
+ then(onFulfilled, onRejected) {
9341
+ this.observed = true;
9342
+ return super.then(onFulfilled, onRejected);
9343
+ }
9344
+ };
9345
+ function testLines(tests, test2, source) {
9346
+ const call2 = source ? callExtent(source, test2.source.line) : void 0;
9347
+ if (call2) return { ...call2, id: test2.identity };
9348
+ const later = tests.map((other) => other.source.line).filter((line) => line > test2.source.line);
9349
+ return {
9350
+ start: test2.source.line,
9351
+ end: later.length ? Math.min(...later) - 1 : Number.MAX_SAFE_INTEGER,
9352
+ id: test2.identity
9353
+ };
9354
+ }
9355
+ function valueEntries(values) {
9356
+ const entries = /* @__PURE__ */ Object.create(
9357
+ null
9358
+ );
9359
+ if (values === void 0) return entries;
9360
+ if (typeof values !== "object" || values === null || Array.isArray(values))
9361
+ throw new ScriptUsageError(
9362
+ "invalid_values",
9363
+ "The values argument must be an object of {{name}} values.",
9364
+ 'Pass values as an object: ai("type {{email}} into the Email field", { email }).'
9365
+ );
9366
+ for (const [key, value] of Object.entries(values)) {
9367
+ if (!KEY.test(key))
9368
+ throw new ScriptUsageError(
9369
+ "invalid_value_name",
9370
+ `\`${key}\` is not a valid placeholder name.`,
9371
+ "Use letters, digits, and underscores, starting with a letter or underscore."
9372
+ );
9373
+ const display = `{{${key}}}`;
9374
+ if (isSecret(value)) {
9375
+ const text = revealSecret(value);
9376
+ entries[key] = {
9377
+ value: new RuntimeValue(text, display),
9378
+ sensitive: true,
9379
+ modelVisible: false,
9380
+ opaqueValues: [new RuntimeValue(text, display)]
9381
+ };
9382
+ } else if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value))
9383
+ entries[key] = {
9384
+ value: new RuntimeValue(String(value), display),
9385
+ sensitive: false,
9386
+ modelVisible: true
9387
+ };
9388
+ else
9389
+ throw new ScriptUsageError(
9390
+ "invalid_value",
9391
+ `The value for {{${key}}} must be a string, a finite number, a boolean, or secret().`,
9392
+ "Convert it with String(...) or wrap sensitive text in secret()."
9393
+ );
9394
+ }
9395
+ return entries;
9396
+ }
9397
+ function inlineValues(step, op, values) {
9398
+ const operand = op === "type" ? validateTypeOperand(step) : null;
9399
+ const span = operand && "operand" in operand ? operand.operand : { start: -1, end: -1 };
9400
+ let text = step.text;
9401
+ for (const token of [...step.tokens].reverse()) {
9402
+ if (token.kind !== "placeholder") continue;
9403
+ if (token.start >= span.start && token.end <= span.end) continue;
9404
+ const entry = values[token.key];
9405
+ if (!entry || entry.sensitive) continue;
9406
+ const value = entry.value.reveal();
9407
+ if (/["\n]|\{\{|\}\}/u.test(value)) continue;
9408
+ text = text.slice(0, token.start) + value + text.slice(token.end);
9409
+ }
9410
+ return text;
9411
+ }
9412
+ function sentenceStep(text, source) {
9413
+ return {
9414
+ kind: "sentence",
9415
+ phase: "steps",
9416
+ text,
9417
+ tokens: tokenizeStep(text).tokens,
9418
+ source,
9419
+ sourceStack: [source]
9420
+ };
9421
+ }
9422
+ async function runScriptTest(file, identity, runDependencies) {
9423
+ const absolute = path10.resolve(file);
9424
+ const script = await loadScriptFile(absolute, {
9425
+ repoRoot: runDependencies.repoRoot
9426
+ });
9427
+ const test2 = identity === void 0 ? script.tests.length === 1 ? script.tests[0] : void 0 : script.tests.find((candidate) => candidate.identity === identity);
9428
+ if (!test2) {
9429
+ if (script.diagnostics.length) return firstDiagnostic(script.diagnostics);
9430
+ return {
9431
+ status: "could_not_run",
9432
+ file: absolute,
9433
+ code: "test_not_found",
9434
+ message: identity === void 0 ? "This file declares several tests; one must be selected." : `No test with id ${JSON.stringify(identity)} is declared in this file.`,
9435
+ fix: "Run `sedum list` to see the test ids in this file."
9436
+ };
9437
+ }
9438
+ let entryUrl;
9439
+ if (test2.url !== void 0 || runDependencies.baseUrl) {
9440
+ try {
9441
+ entryUrl = resolveEntryUrl(
9442
+ test2.url,
9443
+ runDependencies.baseUrl,
9444
+ runDependencies.urlOverride
9445
+ );
9446
+ } catch (error2) {
9447
+ return {
9448
+ status: "could_not_run",
9449
+ file: absolute,
9450
+ code: "invalid_test",
9451
+ source: test2.source,
9452
+ message: error2 instanceof Error ? error2.message : "The test entry URL could not be resolved.",
9453
+ fix: "Use an absolute test url or configure baseUrl in sedum.config.yaml."
9454
+ };
9455
+ }
9456
+ }
9457
+ let dependencies;
9458
+ const { report: runReport, ...runBase } = runDependencies;
9459
+ if (runReport) {
9460
+ const { recorder, slot, ...shared } = runReport;
9461
+ const privacy = {
9462
+ ...shared.privacy,
9463
+ secretValues: [...shared.privacy.secretValues]
9464
+ };
9465
+ const shownFile = safeSource(
9466
+ { file: absolute, line: 1, col: 1 },
9467
+ runDependencies.repoRoot,
9468
+ privacy
9469
+ ).file;
9470
+ const existing = slot ? recorder.testAt(slot.ordinal) : recorder.latestTest();
9471
+ const retrying = existing?.file === shownFile && existing.test.id === test2.identity && existing.currentAttempt?.running === true;
9472
+ const recording = retrying ? existing : await recorder.beginTest({
9473
+ id: test2.identity,
9474
+ file: shownFile,
9475
+ description: safeText(test2.title, privacy, 512),
9476
+ tags: test2.tags.map((tag) => safeText(tag, privacy, 120)),
9477
+ ...slot ? { ordinal: slot.ordinal } : {},
9478
+ ...slot?.lane === void 0 ? {} : { lane: slot.lane }
9479
+ });
9480
+ dependencies = {
9481
+ ...runBase,
9482
+ report: { ...shared, privacy, test: recording }
9483
+ };
9484
+ } else dependencies = runBase;
9485
+ const report = dependencies.report;
9486
+ const classifyOptions = {
9487
+ mode: "allow-model",
9488
+ cache: dependencies.classificationCache,
9489
+ provider: dependencies.provider,
9490
+ ...dependencies.signal ? { signal: dependencies.signal } : {}
9491
+ };
9492
+ const source = await readFile3(absolute, "utf8").catch(() => void 0);
9493
+ try {
9494
+ const scan = scanScriptSentences(source ?? "", absolute);
9495
+ if (scan.sentences.length) {
9496
+ const warm = await classifySentenceSteps(
9497
+ scan.sentences.map((item) => sentenceStep(item.text, item.source)),
9498
+ classifyOptions
9499
+ );
9500
+ if (report && warm.classification.calls.length)
9501
+ await report.test.addAttemptCalls(
9502
+ warm.classification.calls.map(
9503
+ (call2) => resultCall(call2, "classification")
9504
+ )
9505
+ );
9506
+ }
9507
+ } catch {
9508
+ }
9509
+ const bindings = /* @__PURE__ */ Object.create(
9510
+ null
9511
+ );
9512
+ const opaqueEntries = [];
9513
+ let firstProblem = null;
9514
+ let inFlight = null;
9515
+ const outstanding = /* @__PURE__ */ new Set();
9516
+ const rejected = [];
9517
+ const unhandled = [];
9518
+ let stopListening;
9519
+ const ownRouter = runDependencies.rejections ? void 0 : new RejectionRouter(runDependencies.repoRoot);
9520
+ const router = runDependencies.rejections ?? ownRouter;
9521
+ ownRouter?.install();
9522
+ let finished = false;
9523
+ const groups = [];
9524
+ let session;
9525
+ let context;
9526
+ let page;
9527
+ try {
9528
+ session = await dependencies.browser.launch({
9529
+ ...dependencies.browserKind === void 0 ? {} : { browser: dependencies.browserKind },
9530
+ ...dependencies.headless === void 0 ? {} : { headless: dependencies.headless },
9531
+ ...dependencies.slowMoMs === void 0 ? {} : { slowMoMs: dependencies.slowMoMs },
9532
+ ...dependencies.headedOverlay ? { overlay: true } : {}
9533
+ });
9534
+ context = await session.newContext(
9535
+ dependencies.viewport === void 0 ? {} : { viewport: dependencies.viewport }
9536
+ );
9537
+ page = await context.newPage();
9538
+ const activePage = page;
9539
+ if (entryUrl !== void 0)
9540
+ await executeStep(
9541
+ activePage,
9542
+ { op: "goto", url: new RuntimeUrl([entryUrl]) },
9543
+ dependencies.signal ? { signal: dependencies.signal } : {}
9544
+ );
9545
+ const where = (stack) => sourceInFile(stack, absolute) ?? test2.source;
9546
+ const stop = (problem) => {
9547
+ firstProblem ??= problem;
9548
+ throw new StepStop(problem);
9549
+ };
9550
+ const usage = (error2, source2) => stop({
9551
+ status: "could_not_run",
9552
+ file: absolute,
9553
+ code: "invalid_test",
9554
+ source: source2,
9555
+ message: error2.message,
9556
+ fix: error2.fix
9557
+ });
9558
+ const exclusive = async (source2, work) => {
9559
+ if (finished)
9560
+ usage(
9561
+ new ScriptUsageError(
9562
+ "step_after_test",
9563
+ "An ai step ran after the test body had finished.",
9564
+ "Await every ai(...) call inside the test body."
9565
+ ),
9566
+ source2
9567
+ );
9568
+ if (inFlight)
9569
+ usage(
9570
+ new ScriptUsageError(
9571
+ "step_not_awaited",
9572
+ "An ai step started while the previous one was still running.",
9573
+ "Add `await` before each ai(...) call."
9574
+ ),
9575
+ source2
9576
+ );
9577
+ if (dependencies.signal?.aborted)
9578
+ stop({
9579
+ status: "could_not_run",
9580
+ file: absolute,
9581
+ code: "canceled",
9582
+ source: source2,
9583
+ message: "The run was interrupted."
9584
+ });
9585
+ const running = work();
9586
+ inFlight = running;
9587
+ try {
9588
+ return await running;
9589
+ } finally {
9590
+ inFlight = null;
9591
+ }
9592
+ };
9593
+ const runStep = async (step, scope, presentation) => {
9594
+ let outcome;
9595
+ try {
9596
+ outcome = await executeSentence(
9597
+ activePage,
9598
+ step,
9599
+ dependencies,
9600
+ scope,
9601
+ opaqueEntries,
9602
+ presentation
9603
+ );
9604
+ } catch (error2) {
9605
+ return stop(runtimeFailure(absolute, error2));
9606
+ }
9607
+ if (outcome === "continue") return;
9608
+ if (outcome === "failed")
9609
+ stop({ status: "failed", file: absolute, source: step.source });
9610
+ else if (outcome.status !== "passed") stop(outcome);
9611
+ };
9612
+ const sentence = async (text, values, source2) => {
9613
+ try {
9614
+ if (typeof text !== "string" || !text.trim())
9615
+ throw new ScriptUsageError(
9616
+ "invalid_sentence",
9617
+ "An ai step must be a nonblank sentence.",
9618
+ 'Write one action or claim, such as ai("click the Login button").'
9619
+ );
9620
+ const own = valueEntries(values);
9621
+ const tokenized = tokenizeStep(text);
9622
+ const problem = tokenized.problems[0];
9623
+ if (problem)
9624
+ throw new ScriptUsageError(
9625
+ problem.code,
9626
+ problem.message,
9627
+ problem.fix
9628
+ );
9629
+ const binds = REMEMBER_AS.exec(text.trim())?.[1];
9630
+ for (const token of tokenized.tokens)
9631
+ if (token.kind === "placeholder" && token.key !== binds && !(token.key in own) && !(token.key in bindings))
9632
+ throw new ScriptUsageError(
9633
+ "missing_value",
9634
+ `{{${token.key}}} has no value.`,
9635
+ `Pass it as the second argument: ai(${JSON.stringify(text)}, { ${token.key}: ... }).`
9636
+ );
9637
+ const template = sentenceStep(text, source2);
9638
+ const checked = await classifySentenceSteps(
9639
+ [template],
9640
+ classifyOptions
9641
+ );
9642
+ if (report && checked.classification.calls.length)
9643
+ await report.test.addAttemptCalls(
9644
+ checked.classification.calls.map(
9645
+ (call2) => resultCall(call2, "classification")
9646
+ )
9647
+ );
9648
+ const classified = checked.classification.steps[0];
9649
+ if (checked.diagnostics.length || !classified) {
9650
+ const diagnostic3 = checked.diagnostics[0];
9651
+ stop({
9652
+ status: "could_not_run",
9653
+ file: absolute,
9654
+ code: "invalid_test",
9655
+ source: source2,
9656
+ message: diagnostic3?.message ?? "This step could not be classified.",
9657
+ fix: diagnostic3?.fix ?? "Rewrite it as one action or one claim."
9658
+ });
9659
+ }
9660
+ const secrets = Object.values(own).filter((entry) => entry.sensitive);
9661
+ opaqueEntries.push(...secrets);
9662
+ report?.privacy.secretValues.push(
9663
+ ...secrets.map((entry) => entry.value.reveal())
9664
+ );
9665
+ const scope = Object.assign(
9666
+ /* @__PURE__ */ Object.create(null),
9667
+ bindings,
9668
+ own
9669
+ );
9670
+ const shown = sentenceStep(
9671
+ inlineValues(template, classified.op, own),
9672
+ source2
9673
+ );
9674
+ await runStep(
9675
+ {
9676
+ ...shown,
9677
+ op: classified.op,
9678
+ classificationSource: classified.classificationSource,
9679
+ probability: classified.probability
9680
+ },
9681
+ scope,
9682
+ { group: [...groups] }
9683
+ );
9684
+ for (const [key, entry] of Object.entries(scope))
9685
+ if (!(key in own) && !(key in bindings)) bindings[key] = entry;
9686
+ } catch (error2) {
9687
+ if (error2 instanceof ScriptUsageError) usage(error2, source2);
9688
+ throw error2;
9689
+ }
9690
+ };
9691
+ const sentences = async (input, values, source2) => {
9692
+ if (Array.isArray(input)) {
9693
+ if (!input.length)
9694
+ usage(
9695
+ new ScriptUsageError(
9696
+ "empty_steps",
9697
+ "An ai step list is empty.",
9698
+ "Pass at least one sentence."
9699
+ ),
9700
+ source2
9701
+ );
9702
+ for (const item of input)
9703
+ await exclusive(source2, () => sentence(item, values, source2));
9704
+ } else await exclusive(source2, () => sentence(input, values, source2));
9705
+ };
9706
+ const track = (work) => {
9707
+ const step = new StepPromise(
9708
+ (resolve, reject) => work.then(resolve, reject)
9709
+ );
9710
+ outstanding.add(step);
9711
+ Promise.prototype.then.call(
9712
+ step,
9713
+ () => outstanding.delete(step),
9714
+ (error2) => {
9715
+ outstanding.delete(step);
9716
+ rejected.push({ step, error: error2 });
9717
+ }
9718
+ );
9719
+ return step;
9720
+ };
9721
+ const ai = ((input, values) => track(sentences(input, values, where(new Error().stack))));
9722
+ const group = async (name, body, values, source2) => {
9723
+ if (finished)
9724
+ usage(
9725
+ new ScriptUsageError(
9726
+ "step_after_test",
9727
+ "An ai.group ran after the test body had finished.",
9728
+ "Await every ai.group(...) call inside the test body."
9729
+ ),
9730
+ source2
9731
+ );
9732
+ if (groups.length >= MAX_GROUP_DEPTH)
9733
+ usage(
9734
+ new ScriptUsageError(
9735
+ "invalid_group",
9736
+ `Groups nest at most ${MAX_GROUP_DEPTH} deep.`,
9737
+ "Flatten the inner groups."
9738
+ ),
9739
+ source2
9740
+ );
9741
+ if (typeof name !== "string" || !name.trim() || name.length > 120)
9742
+ usage(
9743
+ new ScriptUsageError(
9744
+ "invalid_group",
9745
+ "A group name must be a nonblank string of at most 120 characters.",
9746
+ 'Write ai.group("Checkout", async () => { ... }).'
9747
+ ),
9748
+ source2
9749
+ );
9750
+ if (typeof body !== "function" && !Array.isArray(body))
9751
+ usage(
9752
+ new ScriptUsageError(
9753
+ "invalid_group",
9754
+ "A group needs a list of sentences or an async function.",
9755
+ 'Write ai.group("Log in", ["click the Login button"]).'
9756
+ ),
9757
+ source2
9758
+ );
9759
+ groups.push(name);
9760
+ try {
9761
+ return typeof body === "function" ? await body() : await sentences(body, values, source2);
9762
+ } catch (error2) {
9763
+ if (typeof error2 === "object" && error2 !== null && !(THROWN_IN in error2))
9764
+ Object.defineProperty(error2, THROWN_IN, { value: [...groups] });
9765
+ throw error2;
9766
+ } finally {
9767
+ groups.pop();
9768
+ }
9769
+ };
9770
+ ai.group = ((name, body, values) => track(
9771
+ group(name, body, values, where(new Error().stack))
9772
+ ));
9773
+ const extract = async (description, parser, source2) => {
9774
+ if (typeof description !== "string" || !description.trim() || /[\n{}]/u.test(description))
9775
+ usage(
9776
+ new ScriptUsageError(
9777
+ "invalid_extract",
9778
+ "ai.extract takes a one-line description without placeholders.",
9779
+ 'Write ai.extract("the order total").'
9780
+ ),
9781
+ source2
9782
+ );
9783
+ const text = await exclusive(source2, async () => {
9784
+ const scope = Object.assign(
9785
+ /* @__PURE__ */ Object.create(null),
9786
+ bindings
9787
+ );
9788
+ delete scope[EXTRACT_KEY];
9789
+ const step = sentenceStep(
9790
+ `remember ${description.trim()} as {{${EXTRACT_KEY}}}`,
9791
+ source2
9792
+ );
9793
+ await runStep(
9794
+ {
9795
+ ...step,
9796
+ op: "remember",
9797
+ classificationSource: "pattern",
9798
+ probability: null
9799
+ },
9800
+ scope,
9801
+ { group: [...groups], display: `extract ${description.trim()}` }
9802
+ );
9803
+ return scope[EXTRACT_KEY].value.reveal();
9804
+ });
9805
+ return parser ? parser.parse(text) : text;
9806
+ };
9807
+ ai.extract = ((description, parser) => track(
9808
+ extract(description, parser, where(new Error().stack))
9809
+ ));
9810
+ const raw = activePage.playwright?.();
9811
+ const unavailable = () => {
9812
+ throw new Error(
9813
+ "The Playwright page is not available with this browser driver."
9814
+ );
9815
+ };
9816
+ const env = Object.freeze({ ...dependencies.env });
9817
+ const attemptOrdinal = report?.test.currentAttempt?.ordinal ?? 1;
9818
+ const testContext = {
9819
+ get page() {
9820
+ return raw?.page ?? unavailable();
9821
+ },
9822
+ get context() {
9823
+ return raw?.context ?? unavailable();
9824
+ },
9825
+ ai,
9826
+ env,
9827
+ testInfo: Object.freeze({
9828
+ id: test2.identity,
9829
+ title: test2.title,
9830
+ file: absolute,
9831
+ tags: [...test2.tags],
9832
+ attempt: attemptOrdinal
9833
+ })
9834
+ };
9835
+ let thrown;
9836
+ let threw = false;
9837
+ stopListening = router.register(
9838
+ { file: absolute, lines: testLines(script.tests, test2, source) },
9839
+ script.tests.map((other) => testLines(script.tests, other, source)),
9840
+ (reason) => unhandled.push(reason)
9841
+ );
9842
+ try {
9843
+ await test2.body(testContext);
9844
+ } catch (error2) {
9845
+ thrown = error2;
9846
+ threw = true;
9847
+ }
9848
+ if (outstanding.size) {
9849
+ while (outstanding.size)
9850
+ await Promise.allSettled(
9851
+ [...outstanding].map(
9852
+ (step) => new Promise(
9853
+ (settle) => Promise.prototype.then.call(step, settle, settle)
9854
+ )
9855
+ )
9856
+ );
9857
+ firstProblem ??= {
9858
+ status: "could_not_run",
9859
+ file: absolute,
9860
+ code: "invalid_test",
9861
+ source: test2.source,
9862
+ message: "The test body finished while an ai step was still running.",
9863
+ fix: "Add `await` before each ai(...) call."
9864
+ };
9865
+ }
9866
+ finished = true;
9867
+ const groupsOf = (error2) => typeof error2 === "object" && error2 !== null && THROWN_IN in error2 ? error2[THROWN_IN] : [];
9868
+ const codeFailure = async (error2) => {
9869
+ if (error2 instanceof BrowserDriverError || error2 instanceof ProviderError)
9870
+ return runtimeFailure(absolute, error2);
9871
+ const source2 = error2 instanceof Error ? where(error2.stack) : test2.source;
9872
+ await recordCodeFailure(
9873
+ activePage,
9874
+ dependencies,
9875
+ source2,
9876
+ error2,
9877
+ groupsOf(error2)
9878
+ );
9879
+ return { status: "failed", file: absolute, source: source2 };
9880
+ };
9881
+ let primary = firstProblem;
9882
+ const ignored = rejected.find(
9883
+ ({ step, error: error2 }) => !step.observed && !isStepStop(error2)
9884
+ );
9885
+ if (!primary && threw && !isStepStop(thrown))
9886
+ primary = await codeFailure(thrown);
9887
+ else if (!primary && ignored) primary = await codeFailure(ignored.error);
9888
+ await closeQuietly(page);
9889
+ await closeQuietly(context);
9890
+ await new Promise((resolve) => setTimeout(resolve, 50));
9891
+ stopListening();
9892
+ const ownedOnlyByRun = ownRouter?.unattributed[0];
9893
+ const stray = unhandled[0] ?? (ownedOnlyByRun ? new Error(ownedOnlyByRun.message) : void 0);
9894
+ if (!primary && stray !== void 0) primary = await codeFailure(stray);
9895
+ if (!primary) {
9896
+ await report?.test.finishTest("passed");
9897
+ return { status: "passed", file: absolute };
9898
+ }
9899
+ if (primary.status === "failed") await report?.test.finishTest("failed");
9900
+ return primary;
9901
+ } catch (error2) {
9902
+ if (isStepStop(error2)) return error2.problem;
9903
+ return runtimeFailure(absolute, error2);
9904
+ } finally {
9905
+ finished = true;
9906
+ stopListening?.();
9907
+ ownRouter?.dispose();
9908
+ await closeQuietly(page);
9909
+ await closeQuietly(context);
9910
+ await closeQuietly(session);
9911
+ }
9912
+ }
9913
+ async function recordCodeFailure(page, dependencies, source, error2, group) {
9914
+ const report = dependencies.report;
9915
+ if (!report) return;
9916
+ const attempt = report.test.currentAttempt;
9917
+ if (!attempt) return;
9918
+ const privacy = report.privacy;
9919
+ const index = attempt.stepCount + 1;
9920
+ const id = `${attempt.id}:step:${index}`;
9921
+ const message = error2 instanceof Error ? error2.message : typeof error2 === "string" ? error2 : "The test body threw a non-Error value.";
9922
+ const expectation = error2 instanceof Error && "matcherResult" in error2 ? "expect_failed" : "code_error";
9923
+ const firstLine = message.split("\n").find((line) => line.trim()) ?? message;
9924
+ let evidence = !report.evidenceEnabled ? { status: "omitted", reason: "disabled" } : page.closed ? { status: "unavailable", reason: "page_closed" } : !page.captureFrame ? { status: "unavailable", reason: "capture_unavailable" } : { status: "unavailable", reason: "capture_failed" };
9925
+ if (report.evidenceEnabled && page.captureFrame && !page.closed)
9926
+ try {
9927
+ evidence = await report.saveFrame(
9928
+ attempt,
9929
+ `${id}:evidence`,
9930
+ await page.captureFrame()
9931
+ );
9932
+ } catch {
9933
+ evidence = { status: "unavailable", reason: "capture_failed" };
9934
+ }
9935
+ await report.test.addStep({
9936
+ id,
9937
+ index,
9938
+ kind: "verify",
9939
+ operation: "code",
9940
+ phase: "steps",
9941
+ sentence: safeText(firstLine.trim(), privacy, 512),
9942
+ detail: safeText(
9943
+ error2 instanceof Error ? `${error2.name} thrown by the test code.` : "",
9944
+ privacy,
9945
+ 512
9946
+ ),
9947
+ ...group.length ? { group: group.map((name) => safeText(name, privacy, 120)) } : {},
9948
+ sourceStack: [safeSource(source, dependencies.repoRoot, privacy)],
9949
+ state: "completed",
9950
+ verdict: "failed",
9951
+ flags: [],
9952
+ elapsedMs: 0,
9953
+ page: { status: "omitted", reason: "code_step" },
9954
+ locator: null,
9955
+ judgement: null,
9956
+ observations: [],
9957
+ calls: [],
9958
+ error: { code: expectation, message: safeText(message, privacy, 512) },
9959
+ evidence,
9960
+ replayFrame: null,
9961
+ targetBox: null
9962
+ });
9963
+ }
7553
9964
  export {
7554
9965
  ACCEPTANCE_POLICY_VERSION,
7555
9966
  AssertionEngineError,
@@ -7583,6 +9994,7 @@ export {
7583
9994
  PageScriptError,
7584
9995
  PlaywrightBrowserDriver,
7585
9996
  ProviderError,
9997
+ RejectionRouter,
7586
9998
  ResolvedStepTarget,
7587
9999
  ResultAttemptSchema,
7588
10000
  ResultCallSchema,
@@ -7603,45 +10015,62 @@ export {
7603
10015
  RunResultSchema,
7604
10016
  RuntimeUrl,
7605
10017
  RuntimeValue,
10018
+ SCRIPT_TEST_SUFFIX,
10019
+ ScriptUsageError,
7606
10020
  StepExecutionError,
10021
+ TEST_SUFFIXES,
7607
10022
  TestRecording,
7608
10023
  VISION_PROMPT,
7609
10024
  VisionRequestError,
10025
+ attributeRejection,
10026
+ callExtent,
7610
10027
  canonicalSentence,
7611
10028
  captureVisionObservation,
10029
+ checkRegistrations,
7612
10030
  classificationKey,
7613
10031
  classifyParsedFlow,
7614
10032
  classifySentenceSteps,
7615
10033
  classifySteps,
7616
10034
  clearPageRefs,
7617
10035
  clickTarget,
10036
+ closeQuietly,
7618
10037
  codePoints,
7619
10038
  collectCandidates,
7620
10039
  compareDiagnostics3 as compareDiagnostics,
7621
10040
  dedupeDiagnostics,
10041
+ describeRejection,
7622
10042
  discoverFlowFiles,
7623
10043
  discoverProjectFiles,
7624
10044
  displayPath,
7625
10045
  evaluateModelAnswer,
7626
10046
  evaluateVerifyScores,
10047
+ executeSentence,
7627
10048
  executeStep,
7628
10049
  findBrowserExecutable,
7629
10050
  findIdentityCollisions,
10051
+ firstDiagnostic,
7630
10052
  formatFlowDiagnostic,
7631
10053
  goalChoiceAccepted,
7632
10054
  goalOperations,
10055
+ inlineValues,
7633
10056
  installChromium,
7634
10057
  isFlowScalar,
7635
10058
  isFullyValidated,
10059
+ isRunWideProviderError,
7636
10060
  isSafeRole,
10061
+ isScriptTestFile,
10062
+ isSecret,
7637
10063
  isWeakPeer,
7638
10064
  keyedDigest,
7639
10065
  listTests,
7640
10066
  liveCandidates,
7641
10067
  loadFlowFile,
10068
+ loadListingEntries,
10069
+ loadScriptFile,
7642
10070
  matchEntry,
7643
10071
  matchLiveEntry,
7644
10072
  measure,
10073
+ navigationWhy,
7645
10074
  normalizeSignal,
7646
10075
  opaqueMatches,
7647
10076
  pageDigest,
@@ -7649,9 +10078,12 @@ export {
7649
10078
  pageVersion,
7650
10079
  parseDataTemplate,
7651
10080
  parseFlow,
10081
+ parseFrame,
7652
10082
  parseModule,
10083
+ pathKey,
7653
10084
  patternOperation,
7654
10085
  preflightSentence,
10086
+ probeOpenRouterKey,
7655
10087
  projectCandidates,
7656
10088
  projectDigest,
7657
10089
  quietPage,
@@ -7664,22 +10096,38 @@ export {
7664
10096
  resolveModuleBindings,
7665
10097
  resolveTarget,
7666
10098
  resolveTypeOperand,
10099
+ resultCall,
7667
10100
  resultTotals,
10101
+ revealSecret,
7668
10102
  runFlow,
7669
10103
  runGoal,
7670
10104
  runResultJsonSchema,
10105
+ runScriptTest,
10106
+ runtimeFailure,
7671
10107
  safeSource,
7672
10108
  safeText,
7673
10109
  safeUrl,
10110
+ samePath,
7674
10111
  sameVisualVersion,
10112
+ scanImportBindings,
10113
+ scanLocalImports,
10114
+ scanScriptSentences,
10115
+ scriptListingEntries,
10116
+ scriptRegistry,
10117
+ secret,
10118
+ sourceInFile,
7675
10119
  stageEntry,
10120
+ test,
10121
+ tokenize,
7676
10122
  tokenizeStep,
7677
10123
  unknownCostCall,
10124
+ unsupported,
7678
10125
  validateFlows,
7679
10126
  validateOperand,
7680
10127
  validateProject,
7681
10128
  validateRunResult,
7682
10129
  validateTypeOperand,
10130
+ valueEntries,
7683
10131
  verify,
7684
10132
  visualCandidates,
7685
10133
  walkSuiteFiles