blastproof 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ indexRefs,
4
+ withoutRefs
5
+ } from "./chunk-RA4N57HA.js";
2
6
 
3
7
  // src/cli.ts
4
8
  import { Command, InvalidArgumentError } from "commander";
@@ -30,7 +34,7 @@ base_url: http://localhost:4173
30
34
  llm:
31
35
  # anthropic | openai | ollama
32
36
  provider: anthropic
33
- # Optional. Defaults: anthropic=claude-haiku-4-5, openai=gpt-4o-mini, ollama=qwen2.5
37
+ # Optional. Defaults: anthropic=claude-haiku-4-5, openai=gpt-6-luna, ollama=gpt-oss:20b
34
38
  # model: claude-haiku-4-5
35
39
  # Env var holding your API key (not needed for ollama).
36
40
  api_key_env: ANTHROPIC_API_KEY
@@ -257,10 +261,23 @@ var ProviderRefusedError = class extends RunStoppedError {
257
261
  this.statusCode = statusCode;
258
262
  }
259
263
  };
264
+ var ModelCallTimeoutError = class extends RunStoppedError {
265
+ timeoutMs;
266
+ constructor(timeoutMs) {
267
+ const seconds3 = Number((timeoutMs / 1e3).toFixed(1));
268
+ super(
269
+ `model call timed out: no answer within ${seconds3}s (llm.timeout_s). For a slow local model, raise llm.timeout_s in .blastproof/config.yaml or set BLASTPROOF_LLM_TIMEOUT_S; otherwise check that the provider is answering, then run again.`
270
+ );
271
+ this.name = "ModelCallTimeoutError";
272
+ this.timeoutMs = timeoutMs;
273
+ }
274
+ };
260
275
  var RunBudget = class {
261
276
  maxCalls;
262
277
  maxTokens;
263
278
  maxDurationMs;
279
+ /** How long one model call may take; read by `countedGenerate` (design bound-every-model-call, D2). */
280
+ callTimeoutMs;
264
281
  now;
265
282
  startedAt;
266
283
  calls = 0;
@@ -270,6 +287,7 @@ var RunBudget = class {
270
287
  this.maxCalls = options.maxCalls;
271
288
  this.maxTokens = options.maxTokens;
272
289
  this.maxDurationMs = options.maxDurationMs;
290
+ this.callTimeoutMs = options.callTimeoutMs;
273
291
  this.now = options.now ?? Date.now;
274
292
  this.startedAt = this.now();
275
293
  }
@@ -301,6 +319,15 @@ var RunBudget = class {
301
319
  }
302
320
  }
303
321
  }
322
+ /**
323
+ * Milliseconds left before the deadline, or undefined without one (design
324
+ * bound-every-model-call, D3). Lets a call in flight be aborted when the
325
+ * deadline passes, rather than only the next call being refused.
326
+ */
327
+ remainingMs() {
328
+ if (this.maxDurationMs === void 0) return void 0;
329
+ return Math.max(0, this.maxDurationMs - (this.now() - this.startedAt));
330
+ }
304
331
  /** Records what a completed model call spent. */
305
332
  record(usage) {
306
333
  this.calls += 1;
@@ -496,39 +523,68 @@ function describeTarget(target) {
496
523
  const parts = [];
497
524
  if (target.role) parts.push(`role=${target.role}`);
498
525
  if (target.name) parts.push(`name="${target.name}"`);
499
- if (target.text) parts.push(`text="${target.text}"`);
500
526
  return parts.join(" ") || "(no target)";
501
527
  }
502
- async function resolveTarget(page, target, resolveTimeoutMs = 2e3) {
503
- const candidates = [];
504
- if (target.role) {
505
- if (target.name) {
506
- candidates.push(page.getByRole(target.role, { name: target.name, exact: true }));
507
- }
508
- candidates.push(page.getByRole(target.role, target.name ? { name: target.name } : {}));
528
+ function normaliseName(text) {
529
+ return (text ?? "").replace(/\s+/g, " ").trim().toLowerCase();
530
+ }
531
+ function bareRef(ref) {
532
+ return ref.trim().replace(/^\[/, "").replace(/^ref=/, "").replace(/\]$/, "");
533
+ }
534
+ function describeElement(element) {
535
+ const name = element.name ?? element.text;
536
+ return name === void 0 ? element.role : `${element.role} "${name}"`;
537
+ }
538
+ function bindTarget(action, refs) {
539
+ const target = action.target;
540
+ if (!target || !target.ref && !target.role && !target.name) return { ...action, target: void 0 };
541
+ const fix = "Use the [ref=\u2026] on the line of the element you mean in the current snapshot.";
542
+ if (!target.ref) {
543
+ throw new ActionError(`refused: the target names no ref, so nothing was done. ${fix}`);
544
+ }
545
+ const ref = bareRef(target.ref);
546
+ const element = refs.get(ref);
547
+ if (!element) {
548
+ throw new ActionError(`refused: no element in the current snapshot has ref "${ref}". ${fix}`);
549
+ }
550
+ const shown = element.name ?? element.text;
551
+ const sameRole = normaliseName(target.role) === normaliseName(element.role);
552
+ const sameName = normaliseName(target.name) === normaliseName(shown);
553
+ if (!sameRole || !sameName) {
554
+ const said = [target.role ?? "(no role)", target.name === void 0 ? "" : `"${target.name}"`].filter(Boolean).join(" ");
555
+ throw new ActionError(
556
+ `refused: ref ${ref} is ${describeElement(element)}, not ${said}, so nothing was done. ${fix}`
557
+ );
509
558
  }
510
- if (target.name) {
511
- candidates.push(page.getByLabel(target.name, { exact: true }));
512
- candidates.push(page.getByLabel(target.name));
559
+ return { ...action, target: { ref, role: element.role, name: shown } };
560
+ }
561
+ async function resolveTarget(page, target, resolveTimeoutMs = 2e3) {
562
+ if (!target.ref) throw new ActionError(`Element not found: ${describeTarget(target)} has no ref`);
563
+ const ref = bareRef(target.ref);
564
+ const locator = page.locator(`aria-ref=${ref}`);
565
+ let count;
566
+ try {
567
+ count = await locator.count();
568
+ } catch {
569
+ count = 0;
513
570
  }
514
- const text = target.text ?? target.name;
515
- if (text) {
516
- candidates.push(page.getByText(text, { exact: true }));
517
- candidates.push(page.getByText(text));
571
+ if (count === 0) {
572
+ throw new ActionError(
573
+ `Element not found: ${describeTarget(target)} (ref ${ref}) is no longer on the page; it changed since the snapshot. Choose the element again from the fresh snapshot.`
574
+ );
518
575
  }
519
- for (const candidate of candidates) {
520
- const locator = candidate.first();
521
- try {
522
- await locator.waitFor({ state: "visible", timeout: resolveTimeoutMs });
523
- return locator;
524
- } catch {
525
- }
576
+ try {
577
+ await locator.waitFor({ state: "visible", timeout: resolveTimeoutMs });
578
+ } catch {
579
+ throw new ActionError(
580
+ `Element not found: ${describeTarget(target)} (ref ${ref}) is on the page but did not become visible within ${resolveTimeoutMs}ms.`
581
+ );
526
582
  }
527
- throw new ActionError(`Element not found: ${describeTarget(target)}`);
583
+ return locator;
528
584
  }
529
585
  function requireTarget(action) {
530
- if (!action.target || !action.target.role && !action.target.name && !action.target.text) {
531
- throw new ActionError(`Action "${action.action}" requires a target (role/name/text)`);
586
+ if (!action.target?.ref) {
587
+ throw new ActionError(`Action "${action.action}" requires a target (its ref in the snapshot)`);
532
588
  }
533
589
  return action.target;
534
590
  }
@@ -587,7 +643,7 @@ async function performResolvedAction(page, action, ctx) {
587
643
  }
588
644
  case "press": {
589
645
  const key = action.value ? resolve(action.value, ctx) : "Enter";
590
- if (action.target && (action.target.role || action.target.name || action.target.text)) {
646
+ if (action.target?.ref) {
591
647
  const locator = await resolveTarget(page, action.target, ctx.resolveTimeoutMs);
592
648
  await locator.press(key);
593
649
  return `ok: pressed ${key} on ${describeTarget(action.target)}`;
@@ -609,9 +665,52 @@ async function performResolvedAction(page, action, ctx) {
609
665
  }
610
666
  }
611
667
 
668
+ // src/runner/authoring.ts
669
+ var VALUE_VERBS = ["fill", "enter", "type", "input", "set"];
670
+ var LEADING_VALUE_VERB = new RegExp(`^\\s*(?:${VALUE_VERBS.join("|")})\\b`, "i");
671
+ var CONNECTOR_WORDS = ["with", "to", "as", "using", "into", "from", "in"];
672
+ var CONNECTOR_WORD = new RegExp(`\\b(?:${CONNECTOR_WORDS.join("|")})\\b`, "i");
673
+ var CONNECTOR_SYMBOL = /["'`:=]|\{\{env\./i;
674
+ var PHRASAL_IN = new RegExp(`^(\\s*(?:${VALUE_VERBS.join("|")}))\\s+in\\b`, "i");
675
+ function namesAValue(step) {
676
+ const withoutPhrasal = step.replace(PHRASAL_IN, "$1");
677
+ return CONNECTOR_WORD.test(withoutPhrasal) || CONNECTOR_SYMBOL.test(withoutPhrasal);
678
+ }
679
+ function namesNoValue(step) {
680
+ return LEADING_VALUE_VERB.test(step) && !namesAValue(step);
681
+ }
682
+ var LEADING_CHECK_VERB = /^\s*(?:(?:then|and)\s+)?(?:verify|check|confirm|ensure|assert|expect|validate|make\s+sure|see\s+that)\b/i;
683
+ function isVerificationStep(step) {
684
+ return LEADING_CHECK_VERB.test(step);
685
+ }
686
+ function entersNamedValue(step) {
687
+ return LEADING_VALUE_VERB.test(step) && namesAValue(step);
688
+ }
689
+ function detectMissingValues(tests) {
690
+ const findings = [];
691
+ for (const test of tests) {
692
+ for (const origin of ["setup", "steps"]) {
693
+ const steps = origin === "setup" ? test.setup ?? [] : test.steps;
694
+ steps.forEach((step, position) => {
695
+ if (namesNoValue(step)) {
696
+ findings.push({ test, origin, index: position + 1, step });
697
+ }
698
+ });
699
+ }
700
+ }
701
+ return { findings };
702
+ }
703
+ function suggestValueClause(step) {
704
+ return `${step.trimEnd()} with <value>`;
705
+ }
706
+
612
707
  // src/runner/recovery.ts
613
708
  var COMMIT_ACTIONS = /* @__PURE__ */ new Set(["click", "press"]);
614
709
  var COMMIT_KEYS = /* @__PURE__ */ new Set(["Enter", "NumpadEnter", " ", "Space", "Spacebar"]);
710
+ function isCommit(action) {
711
+ if (!COMMIT_ACTIONS.has(action.action)) return false;
712
+ return action.action !== "press" || COMMIT_KEYS.has(action.value ?? "");
713
+ }
615
714
  var SOURCED_VALUE_ACTIONS = /* @__PURE__ */ new Set(["fill", "select"]);
616
715
  function referencesOnlyNamedVars(value, step) {
617
716
  const named = new Set(referencedEnvVars(step));
@@ -621,20 +720,14 @@ function normalise(text) {
621
720
  return text.replace(/\s+/g, " ").trim().toLowerCase();
622
721
  }
623
722
  function describeAction(action) {
624
- const target = action.target ? ` ${action.target.role ?? ""} "${action.target.name ?? action.target.text ?? ""}"` : "";
723
+ const target = action.target ? ` ${action.target.role ?? ""} "${action.target.name ?? ""}"` : "";
625
724
  const value = action.value ? ` [${action.value}]` : "";
626
725
  return `${action.action}${target}${value}`;
627
726
  }
628
727
  function identity(action) {
629
728
  const role = action.target?.role ?? "";
630
729
  const name = action.target?.name ?? "";
631
- return JSON.stringify([
632
- action.action,
633
- role,
634
- normalise(name),
635
- role || name ? "" : action.target?.text ?? "",
636
- action.value ?? ""
637
- ]);
730
+ return JSON.stringify([action.action, role, normalise(name), action.value ?? ""]);
638
731
  }
639
732
  var StepRecovery = class {
640
733
  performed = /* @__PURE__ */ new Set();
@@ -662,9 +755,15 @@ var StepRecovery = class {
662
755
  * stay distinguishable in the one place that decides which secret gets typed.
663
756
  */
664
757
  step;
758
+ /**
759
+ * Whether the step asks only for a check (design a-verification-step-only-looks,
760
+ * D1). Read by the executor too, which refuses `done` in such a step.
761
+ */
762
+ verifies;
665
763
  constructor(step) {
666
764
  this.step = step;
667
765
  this.readable = [normalise(step)];
766
+ this.verifies = isVerificationStep(step);
668
767
  }
669
768
  /**
670
769
  * Records a snapshot the model was shown, as a source it may quote from.
@@ -718,7 +817,7 @@ var StepRecovery = class {
718
817
  * and #28 has now produced one on three applications.
719
818
  */
720
819
  refusalFor(action) {
721
- return this.repeatedCommitRefusal(action) ?? this.redactionLabelRefusal(action) ?? this.unsourcedValueRefusal(action);
820
+ return this.verificationRefusal(action) ?? this.repeatedCommitRefusal(action) ?? this.redactionLabelRefusal(action) ?? this.unsourcedValueRefusal(action);
722
821
  }
723
822
  /**
724
823
  * Refuses a typed value containing a redaction label (design
@@ -739,11 +838,24 @@ var StepRecovery = class {
739
838
  if (!action.value?.includes(REDACTION_PREFIX)) return void 0;
740
839
  return `refused: the value was NOT typed, because it contains a redaction label. ${REDACTION_PREFIX} NAME] stands for the value of {{env.NAME}}, withheld from you; it is never a value the application should receive. To enter an environment value, use the {{env.*}} placeholder this step names. If the step names none, use a value it supplies, or fail the step.`;
741
840
  }
841
+ /**
842
+ * Refuses a commit in a step that only checks (design
843
+ * a-verification-step-only-looks, D2). Without it the agent could make a check
844
+ * true by producing what it checks: a click on "Add to cart" put the message a
845
+ * verification looked for on the page, and the step passed (#139). Navigation
846
+ * stays allowed, since a check may need another page; a link click does not,
847
+ * since a link and a logout item look alike from here and `navigate` covers it.
848
+ * First among the refusals, because it holds whatever was done before.
849
+ */
850
+ verificationRefusal(action) {
851
+ if (!this.verifies || !isCommit(action)) return void 0;
852
+ return "refused: this step only verifies \u2014 it does not ask you to change anything, so clicking or pressing here could make the check pass by producing what it checks. Assert what the page shows. If what the step names is on another page, navigate there. If it is not shown, fail the step.";
853
+ }
742
854
  repeatedCommitRefusal(action) {
743
- if (!COMMIT_ACTIONS.has(action.action)) return void 0;
744
- if (action.action === "press" && !COMMIT_KEYS.has(action.value ?? "")) return void 0;
855
+ if (!isCommit(action)) return void 0;
745
856
  if (!this.performed.has(identity(action))) return void 0;
746
- return `refused: this exact action already succeeded earlier in this step, so it was NOT performed again. Repeating something that commits repeats whatever it changed in the application. If the page no longer shows that it worked, that is normal for a submit answered by a redirect \u2014 check the record of what you have already done. Verify the step's outcome another way, or fail the step.`;
857
+ const target = action.target ? ` on ${action.target.role ?? ""} "${action.target.name ?? ""}"` : "";
858
+ return `refused: this ${action.action}${target} already succeeded earlier in this step, so it was NOT performed again. It is the same control even under a new ref: refs are renumbered when the page changes. Repeating something that commits repeats whatever it changed in the application. If the page no longer shows that it worked, that is normal for a submit answered by a redirect \u2014 check the record of what you have already done. Verify the step's outcome another way, or fail the step.`;
747
859
  }
748
860
  /**
749
861
  * Refuses a typed value that came from nowhere the model was entitled to read
@@ -800,7 +912,7 @@ async function waitForSettled(page) {
800
912
  }
801
913
  }
802
914
  async function defaultSnapshot(page, maxLines) {
803
- const { captureSnapshot } = await import("./snapshot-CAIB2OHX.js");
915
+ const { captureSnapshot } = await import("./snapshot-PYB4N7E7.js");
804
916
  return captureSnapshot(page, { maxLines });
805
917
  }
806
918
  function slugify(text) {
@@ -808,6 +920,7 @@ function slugify(text) {
808
920
  return slug || "test";
809
921
  }
810
922
  var NOTHING_DONE_REFUSAL = "refused: nothing succeeded during this step, so it was NOT closed. A step closes on what was done in it, not on being declared finished. If the outcome already holds \u2014 there was nothing left to do \u2014 assert that it holds and let the judgment close the step; an assertion is evidence, a declaration is not. If the step cannot be carried out at all, fail it and say why.";
923
+ var VERIFICATION_DONE_REFUSAL = "refused: this step only verifies, so it closes on a passing assertion, not on being declared finished. Assert what the page shows; if it does not show what the step names, fail the step and say why.";
811
924
  var StepFailure = class extends Error {
812
925
  };
813
926
  async function executeTest(page, test, options) {
@@ -845,6 +958,7 @@ async function executeTest(page, test, options) {
845
958
  let failure;
846
959
  const boundary = allowedOriginsFor(baseUrl, allowedOrigins);
847
960
  await page.goto(new URL(baseUrl).toString());
961
+ const usedEarlier = /* @__PURE__ */ new Set();
848
962
  for (let index = 0; index < allSteps.length; index++) {
849
963
  const { step, setup } = allSteps[index];
850
964
  const stepStartedAt = Date.now();
@@ -867,7 +981,9 @@ async function executeTest(page, test, options) {
867
981
  }
868
982
  const snap = await takeSnapshot(page);
869
983
  const maskedSnap = mask(snap);
870
- recovery.observe(maskedSnap);
984
+ const refs = indexRefs(maskedSnap);
985
+ const pageSnap = withoutRefs(maskedSnap);
986
+ recovery.observe(pageSnap);
871
987
  let action;
872
988
  try {
873
989
  action = await brain.nextAction({
@@ -892,9 +1008,9 @@ async function executeTest(page, test, options) {
892
1008
  }
893
1009
  iterations++;
894
1010
  if (action.action === "done") {
895
- if (!recovery.acted) {
1011
+ if (!recovery.acted || recovery.verifies) {
896
1012
  failedAttempts++;
897
- lastResult = NOTHING_DONE_REFUSAL;
1013
+ lastResult = recovery.verifies ? VERIFICATION_DONE_REFUSAL : NOTHING_DONE_REFUSAL;
898
1014
  emitAction(index, action, lastResult);
899
1015
  if (failedAttempts >= maxRetries) {
900
1016
  throw new StepFailure(lastResult);
@@ -915,19 +1031,21 @@ async function executeTest(page, test, options) {
915
1031
  judgment = await brain.judge(
916
1032
  mask(step),
917
1033
  mask(expectation),
918
- maskedSnap,
919
- recovery.stepHistory()
1034
+ pageSnap,
1035
+ recovery.stepHistory(),
1036
+ [...usedEarlier]
920
1037
  );
921
1038
  if (!judgment.pass) {
922
1039
  await waitForSettled(page);
923
1040
  const freshSnap = await takeSnapshot(page);
924
- const maskedFresh = mask(freshSnap);
1041
+ const maskedFresh = withoutRefs(mask(freshSnap));
925
1042
  recovery.observe(maskedFresh);
926
1043
  judgment = await brain.judge(
927
1044
  mask(step),
928
1045
  mask(expectation),
929
1046
  maskedFresh,
930
- recovery.stepHistory()
1047
+ recovery.stepHistory(),
1048
+ [...usedEarlier]
931
1049
  );
932
1050
  }
933
1051
  } catch (error) {
@@ -953,6 +1071,17 @@ async function executeTest(page, test, options) {
953
1071
  }
954
1072
  continue;
955
1073
  }
1074
+ try {
1075
+ action = bindTarget(action, refs);
1076
+ } catch (error) {
1077
+ failedAttempts++;
1078
+ lastResult = error instanceof Error ? error.message : String(error);
1079
+ emitAction(index, action, lastResult);
1080
+ if (failedAttempts >= maxRetries) {
1081
+ throw new StepFailure(lastResult);
1082
+ }
1083
+ continue;
1084
+ }
956
1085
  const refusal = recovery.refusalFor(action);
957
1086
  if (refusal) {
958
1087
  failedAttempts++;
@@ -986,6 +1115,9 @@ async function executeTest(page, test, options) {
986
1115
  if (error instanceof RunStoppedError) throw error;
987
1116
  stepFailedReason = mask(error instanceof Error ? error.message : String(error));
988
1117
  }
1118
+ for (const entry of recovery.stepHistory()) {
1119
+ for (const name of referencedEnvVars(entry.action)) usedEarlier.add(name);
1120
+ }
989
1121
  const status = stepFailedReason ? "failed" : "passed";
990
1122
  stepResults.push({
991
1123
  step: mask(step),
@@ -1142,7 +1274,8 @@ async function fromSteps(options) {
1142
1274
  const judgment = await verifyJudgment(
1143
1275
  brain,
1144
1276
  auth.verify,
1145
- async () => mask.mask(await takeSnapshot(page)),
1277
+ // The judge reads the page without refs (design act-on-the-element-the-model-read, D3).
1278
+ async () => withoutRefs(mask.mask(await takeSnapshot(page))),
1146
1279
  (text) => mask.mask(text),
1147
1280
  maxRetries
1148
1281
  );
@@ -1202,7 +1335,30 @@ var llmSchema = z.object({
1202
1335
  provider: z.enum(["anthropic", "openai", "ollama"]).default("anthropic"),
1203
1336
  model: z.string().min(1).optional(),
1204
1337
  api_key_env: z.string().min(1).optional(),
1205
- base_url: z.string().url().optional()
1338
+ base_url: z.string().url().optional(),
1339
+ /**
1340
+ * Seconds a single model call may take before it is aborted and the run stops
1341
+ * (design bound-every-model-call, D2). Optional: undefined takes the provider's
1342
+ * default from `DEFAULT_TIMEOUT_SECONDS`, because only the user knows how fast
1343
+ * their local hardware is. Coerced, since `BLASTPROOF_LLM_TIMEOUT_S` is text.
1344
+ */
1345
+ timeout_s: z.coerce.number().positive().optional(),
1346
+ /**
1347
+ * Fields merged into every request body for an OpenAI-compatible endpoint
1348
+ * (design route-a-gateway-from-the-config, D1): a gateway's own extensions,
1349
+ * such as OpenRouter's `provider` routing, which the SDK does not know. The
1350
+ * fields blastproof sets always win (D2). Opaque on purpose: its keys are the
1351
+ * gateway's API, not ours.
1352
+ */
1353
+ extra_body: z.record(z.unknown()).optional()
1354
+ }).superRefine((llm, ctx) => {
1355
+ if (llm.extra_body !== void 0 && llm.provider === "anthropic") {
1356
+ ctx.addIssue({
1357
+ code: z.ZodIssueCode.custom,
1358
+ path: ["extra_body"],
1359
+ message: "applies only to the OpenAI-compatible providers (openai, ollama); the Anthropic API rejects unknown fields. Remove llm.extra_body, or reach the model through a gateway with provider: openai and llm.base_url."
1360
+ });
1361
+ }
1206
1362
  });
1207
1363
  var browserSchema = z.object({
1208
1364
  headless: z.boolean().default(true),
@@ -1313,6 +1469,7 @@ var ENV_OVERRIDES = {
1313
1469
  BLASTPROOF_LLM_MODEL: ["llm", "model"],
1314
1470
  BLASTPROOF_LLM_BASE_URL: ["llm", "base_url"],
1315
1471
  BLASTPROOF_LLM_API_KEY_ENV: ["llm", "api_key_env"],
1472
+ BLASTPROOF_LLM_TIMEOUT_S: ["llm", "timeout_s"],
1316
1473
  BLASTPROOF_MAX_LLM_CALLS: ["budget", "max_llm_calls"],
1317
1474
  BLASTPROOF_MAX_TOKENS: ["budget", "max_tokens"],
1318
1475
  BLASTPROOF_MAX_DURATION_S: ["budget", "max_duration_s"]
@@ -1517,7 +1674,7 @@ warning: ${findings.length} file(s) changed in the working tree are not in the d
1517
1674
  }
1518
1675
 
1519
1676
  // src/llm/brain.ts
1520
- import { APICallError, generateObject, RetryError } from "ai";
1677
+ import { APICallError, generateObject, NoObjectGeneratedError, RetryError } from "ai";
1521
1678
 
1522
1679
  // src/llm/prompts.ts
1523
1680
  function agentSystemPrompt() {
@@ -1530,9 +1687,10 @@ The snapshot is a description of what is on screen. It is the thing you are test
1530
1687
  Rules:
1531
1688
  - Return exactly ONE action per response. Never batch actions.
1532
1689
  - Placeholders like {{env.SOME_NAME}} are secrets that are filled in after you answer. Pass them through in your action exactly as written, never expanded, never guessed at.
1533
- - Pick target elements exclusively from the current snapshot, using their exact role and accessible name. Never invent CSS selectors or guess elements not in the snapshot.
1690
+ - Pick target elements exclusively from the current snapshot. Every element there carries a ref, like \`[ref=f1e25]\`: name your target by that ref, and give its role and name exactly as that same line shows them (the text after the colon when it has no quoted name). The ref decides which element is acted on, so copy it from the line of the element you mean; a role or name that does not match that line is refused. Refs change when the page changes, so always take them from the current snapshot. Never invent CSS selectors or guess elements not in the snapshot.
1534
1691
  - Use "navigate" only with a URL or path as value. Use "fill" to type into textboxes/inputs. Use "press" for keyboard keys (value e.g. "Enter"). Use "select" for dropdowns (value = option label).
1535
1692
  - Use "assert" with an expectation to verify page state (visible text, counts, URLs). Assertions never modify the page.
1693
+ - A step that begins with "verify", "check", "confirm", "ensure", "assert", "expect", "validate", "make sure" or "see that" only looks. Never click or press in it: making the page show what the step checks would hide the very thing it checks. Assert what the page shows, navigate if what it names is on another page, or fail. It closes on a passing assertion, never on "done". This is enforced: a click, a press or "done" in such a step is refused.
1536
1694
  - Return "done" when the current step's outcome holds \u2014 including when it already held before you acted, or was achieved by your previous action. "Already true" is done, never failure. Do not return "done" for work belonging to later steps.
1537
1695
  - Return "fail" only when the step's outcome cannot be reached: the element is still absent after retries, the page cannot support the step, or an error blocks progress. Never return "fail" because the work appears to have been done already.
1538
1696
  - If your previous action errored, re-read the fresh snapshot and choose an alternative element or approach. Do not repeat the exact same failing action.
@@ -1565,6 +1723,8 @@ function agentUserPrompt(input) {
1565
1723
  function assertSystemPrompt() {
1566
1724
  return `You are a QA judge. You receive a test step, the model's expectation for the current page, and a page accessibility snapshot. Decide whether the STEP's own outcome holds \u2014 the expectation is the claim the model is offering in support of that, not a substitute question of its own. A claim can be true of the snapshot and still fail the step, if it does not establish what the step actually describes: only pass when the snapshot itself shows the step's outcome, never merely because the expectation offered happens to be true of something else on the page.
1567
1725
 
1726
+ When the step says where its outcome must appear (in the confirmation message, in the list, in the cart, for this order), that place is part of the outcome. Identify the element the step names from the snapshot itself, and look for the value there. The same value elsewhere on the page (another order, another row, another section) does not satisfy the step, even when the expectation describes that other place by the step's words.
1727
+
1568
1728
  A value sitting in a control that was just typed into \u2014 an open dialog's textbox, an unsubmitted form field \u2014 is not the same as a committed outcome. When the step describes an outcome (something now appears in a list, is saved, is confirmed, is created), text visible only inside an editable, not-yet-submitted control does not satisfy it; look for the outcome committed outside that control (the dialog closed, the item is listed on its own, a confirmation appeared). This is specifically about that confusion, not a license to fail anything you are merely unsure about \u2014 if the snapshot plainly shows the step's outcome, pass it.
1569
1729
 
1570
1730
  A step that names an ACTION (submit, click, create, add, ...) is satisfied by evidence the action took effect, not by the action's own control still being on the page. A successful action ordinarily replaces or moves past exactly the form, button or field the step names, so that control's absence is normal evidence of success, not evidence the step is unverifiable \u2014 do not fail such a step only because you can no longer see the thing it names. Fail it instead when the snapshot shows the action did NOT take effect: an error message, a validation warning, or the very same pre-action page still in front of you with nothing changed. A different page, a new state, or the result the action was meant to produce counts as evidence it worked.
@@ -1640,17 +1800,19 @@ var agentActionSchema = z2.object({
1640
1800
  action: z2.enum(ACTION_NAMES).describe("The next browser action to perform for the current step."),
1641
1801
  target: absentAsNull(
1642
1802
  z2.object({
1803
+ ref: absentAsNull(
1804
+ z2.string().describe('The ref of the target element, copied from its [ref=...] in the snapshot, e.g. "f1e25".')
1805
+ ),
1643
1806
  role: absentAsNull(
1644
- z2.string().describe('ARIA role of the target element, e.g. "button", "link", "textbox".')
1807
+ z2.string().describe('ARIA role of that element, as its snapshot line shows it, e.g. "button", "link", "textbox".')
1645
1808
  ),
1646
1809
  name: absentAsNull(
1647
- z2.string().describe("Accessible name of the target element, exactly as shown in the snapshot.")
1648
- ),
1649
- text: absentAsNull(
1650
- z2.string().describe("Visible text of the target element, used as a fallback when no role matches.")
1810
+ z2.string().describe(
1811
+ "Accessible name of that element, exactly as its snapshot line shows it; its text after the colon when it has no quoted name."
1812
+ )
1651
1813
  )
1652
1814
  })
1653
- ).describe("Element to act on, resolved from the accessibility snapshot. Null for navigate/done/fail."),
1815
+ ).describe("Element to act on, named by its ref in the accessibility snapshot. Null for navigate/done/fail, and for press on the focused element."),
1654
1816
  value: absentAsNull(
1655
1817
  z2.string().describe(
1656
1818
  'Action payload: URL/path for navigate, text for fill, key for press (e.g. "Enter"), option label for select.'
@@ -1664,9 +1826,9 @@ var agentActionSchema = z2.object({
1664
1826
  var parsedAgentActionSchema = z2.object({
1665
1827
  action: z2.enum(ACTION_NAMES),
1666
1828
  target: z2.object({
1829
+ ref: z2.string().optional(),
1667
1830
  role: z2.string().optional(),
1668
- name: z2.string().optional(),
1669
- text: z2.string().optional()
1831
+ name: z2.string().optional()
1670
1832
  }).optional(),
1671
1833
  value: z2.string().optional(),
1672
1834
  reasoning: z2.string(),
@@ -1681,7 +1843,7 @@ var assertJudgmentSchema = z2.object({
1681
1843
  ),
1682
1844
  reason: z2.string().describe("One sentence: whether the snapshot shows that outcome."),
1683
1845
  pass: z2.boolean().describe(
1684
- "Whether the snapshot shows that outcome. The expectation is only a claim offered in support; it never replaces the step. False if any part of the outcome the step asks for is not shown, or cannot be assessed from this snapshot. An action the step names (click, dismiss, submit) is how its outcome is reached, not part of it: an outcome that holds passes whether or not that action was needed. An outcome that is an absence (gone, closed, dismissed, removed) is shown by the thing being absent."
1846
+ "Whether the snapshot shows that outcome. The expectation is only a claim offered in support; it never replaces the step. False if any part of the outcome the step asks for is not shown, or cannot be assessed from this snapshot. An action the step names (click, dismiss, submit) is how its outcome is reached, not part of it: an outcome that holds passes whether or not that action was needed. An outcome that is an absence (gone, closed, dismissed, removed) is shown by the thing being absent. Where the step says the outcome appears (in the confirmation, in the list, for this order) is part of it: a value found only somewhere else on the page is false."
1685
1847
  )
1686
1848
  });
1687
1849
  var generatedTestSchema = z2.object({
@@ -1694,6 +1856,7 @@ var generatedTestSchema = z2.object({
1694
1856
  });
1695
1857
 
1696
1858
  // src/llm/brain.ts
1859
+ var MAX_OUTPUT_TOKENS = 4096;
1697
1860
  var MalformedModelOutputError = class extends Error {
1698
1861
  constructor(message) {
1699
1862
  super(message);
@@ -1717,13 +1880,35 @@ function asProviderRefusal(error) {
1717
1880
  withProviderDetail(cause);
1718
1881
  return new ProviderRefusedError(cause.statusCode, cause.message);
1719
1882
  }
1883
+ function callAbort(budget) {
1884
+ const limits = [budget.callTimeoutMs, budget.remainingMs()].filter((ms) => ms !== void 0);
1885
+ if (limits.length === 0) return void 0;
1886
+ const controller = new AbortController();
1887
+ const timer = setTimeout(() => controller.abort(), Math.min(...limits));
1888
+ return { signal: controller.signal, clear: () => clearTimeout(timer) };
1889
+ }
1890
+ function spentAndExplained(error, budget) {
1891
+ if (!NoObjectGeneratedError.isInstance(error)) return error;
1892
+ budget.record(error.usage);
1893
+ if (error.finishReason !== "length") return error;
1894
+ return new MalformedModelOutputError(
1895
+ `the answer reached the ${MAX_OUTPUT_TOKENS}-token output limit before its JSON was complete`
1896
+ );
1897
+ }
1720
1898
  async function countedGenerate(generate, budget, options) {
1721
1899
  budget.check();
1900
+ const abort = callAbort(budget);
1722
1901
  let result;
1723
1902
  try {
1724
- result = await generate(options);
1903
+ result = await generate({ ...options, maxOutputTokens: MAX_OUTPUT_TOKENS, abortSignal: abort?.signal });
1725
1904
  } catch (error) {
1726
- throw asProviderRefusal(withProviderDetail(error));
1905
+ if (abort?.signal.aborted) {
1906
+ budget.check();
1907
+ if (budget.callTimeoutMs !== void 0) throw new ModelCallTimeoutError(budget.callTimeoutMs);
1908
+ }
1909
+ throw asProviderRefusal(withProviderDetail(spentAndExplained(error, budget)));
1910
+ } finally {
1911
+ abort?.clear();
1727
1912
  }
1728
1913
  budget.record(result.usage);
1729
1914
  return result;
@@ -1745,7 +1930,7 @@ function createBrain(model, generate = generateObject, budget) {
1745
1930
  }
1746
1931
  return parsed.data;
1747
1932
  },
1748
- async judge(step, expectation, snapshot, stepHistory) {
1933
+ async judge(step, expectation, snapshot, stepHistory, usedEarlier) {
1749
1934
  const asJudged = stepHistory?.map((entry) => ({
1750
1935
  action: placeholdersAsLabels(entry.action),
1751
1936
  result: placeholdersAsLabels(entry.result)
@@ -1768,18 +1953,20 @@ function createBrain(model, generate = generateObject, budget) {
1768
1953
  `Model returned an invalid assert judgment: ${parsed.error.issues[0]?.message ?? "unknown"}`
1769
1954
  );
1770
1955
  }
1771
- return secretMismatch(placeholdersAsLabels(step), snapshot, asJudged, parsed.data);
1956
+ return secretMismatch(placeholdersAsLabels(step), snapshot, asJudged, usedEarlier ?? [], parsed.data);
1772
1957
  }
1773
1958
  };
1774
1959
  }
1775
- function secretMismatch(judgedStep, snapshot, judgedRecord, judgment) {
1960
+ function secretMismatch(judgedStep, snapshot, judgedRecord, usedEarlier, judgment) {
1776
1961
  if (!judgment.pass) return judgment;
1777
1962
  const onPage = labelledVariables(snapshot);
1778
1963
  const inRecord = labelledVariables((judgedRecord ?? []).map((e) => `${e.action}
1779
1964
  ${e.result}`).join("\n"));
1780
1965
  for (const name of labelledVariables(judgedStep)) {
1781
1966
  const others = onPage.filter((other) => other !== name);
1782
- if (onPage.includes(name) || inRecord.includes(name) || others.length === 0) continue;
1967
+ if (onPage.includes(name) || inRecord.includes(name) || usedEarlier.includes(name) || others.length === 0) {
1968
+ continue;
1969
+ }
1783
1970
  const shown = others.map((other) => redactionLabel(other)).join(", ");
1784
1971
  return {
1785
1972
  ...judgment,
@@ -1814,14 +2001,35 @@ import { createAnthropic } from "@ai-sdk/anthropic";
1814
2001
  import { createOpenAI } from "@ai-sdk/openai";
1815
2002
  var DEFAULT_MODELS = {
1816
2003
  anthropic: "claude-haiku-4-5",
1817
- openai: "gpt-4o-mini",
1818
- ollama: "qwen2.5"
2004
+ openai: "gpt-6-luna",
2005
+ ollama: "gpt-oss:20b"
1819
2006
  };
1820
2007
  var DEFAULT_API_KEY_ENVS = {
1821
2008
  anthropic: "ANTHROPIC_API_KEY",
1822
2009
  openai: "OPENAI_API_KEY"
1823
2010
  };
1824
2011
  var DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434/v1";
2012
+ var DEFAULT_TIMEOUT_SECONDS = {
2013
+ anthropic: 300,
2014
+ openai: 300,
2015
+ ollama: 900
2016
+ };
2017
+ function timeoutSeconds(llm) {
2018
+ return llm.timeout_s ?? DEFAULT_TIMEOUT_SECONDS[llm.provider];
2019
+ }
2020
+ function withExtraBody(extra, base = fetch) {
2021
+ return (input, init) => {
2022
+ if (typeof init?.body !== "string") return base(input, init);
2023
+ let body;
2024
+ try {
2025
+ body = JSON.parse(init.body);
2026
+ } catch {
2027
+ return base(input, init);
2028
+ }
2029
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return base(input, init);
2030
+ return base(input, { ...init, body: JSON.stringify({ ...extra, ...body }) });
2031
+ };
2032
+ }
1825
2033
  var MissingApiKeyError = class extends Error {
1826
2034
  constructor(variable, provider) {
1827
2035
  super(
@@ -1841,6 +2049,7 @@ function createModel(llm, env = process.env) {
1841
2049
  throw new MissingApiKeyError(keyEnv, llm.provider);
1842
2050
  }
1843
2051
  const baseURL = llm.base_url ? { baseURL: llm.base_url } : {};
2052
+ const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
1844
2053
  const model = llm.provider === "anthropic" ? (
1845
2054
  // A configured endpoint applies to whichever provider is selected —
1846
2055
  // dropping it here routed corporate-proxy configs to the public API
@@ -1849,13 +2058,14 @@ function createModel(llm, env = process.env) {
1849
2058
  ) : (
1850
2059
  // `.chat` = Chat Completions: works with official OpenAI and any
1851
2060
  // OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM) via base_url.
1852
- createOpenAI({ apiKey, ...baseURL }).chat(modelId)
2061
+ createOpenAI({ apiKey, ...baseURL, ...extra }).chat(modelId)
1853
2062
  );
1854
2063
  return { model, provider: llm.provider, modelId };
1855
2064
  }
1856
2065
  case "ollama": {
1857
2066
  const baseURL = llm.base_url ?? DEFAULT_OLLAMA_BASE_URL;
1858
- const model = createOpenAI({ baseURL, apiKey: "ollama" }).chat(modelId);
2067
+ const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
2068
+ const model = createOpenAI({ baseURL, apiKey: "ollama", ...extra }).chat(modelId);
1859
2069
  return { model, provider: "ollama", modelId };
1860
2070
  }
1861
2071
  }
@@ -1866,41 +2076,6 @@ import { mkdir as mkdir4, writeFile as writeFile3 } from "fs/promises";
1866
2076
  import path6 from "path";
1867
2077
  import { stringify } from "yaml";
1868
2078
 
1869
- // src/runner/authoring.ts
1870
- var VALUE_VERBS = ["fill", "enter", "type", "input", "set"];
1871
- var LEADING_VALUE_VERB = new RegExp(`^\\s*(?:${VALUE_VERBS.join("|")})\\b`, "i");
1872
- var CONNECTOR_WORDS = ["with", "to", "as", "using", "into", "from", "in"];
1873
- var CONNECTOR_WORD = new RegExp(`\\b(?:${CONNECTOR_WORDS.join("|")})\\b`, "i");
1874
- var CONNECTOR_SYMBOL = /["'`:=]|\{\{env\./i;
1875
- var PHRASAL_IN = new RegExp(`^(\\s*(?:${VALUE_VERBS.join("|")}))\\s+in\\b`, "i");
1876
- function namesAValue(step) {
1877
- const withoutPhrasal = step.replace(PHRASAL_IN, "$1");
1878
- return CONNECTOR_WORD.test(withoutPhrasal) || CONNECTOR_SYMBOL.test(withoutPhrasal);
1879
- }
1880
- function namesNoValue(step) {
1881
- return LEADING_VALUE_VERB.test(step) && !namesAValue(step);
1882
- }
1883
- function entersNamedValue(step) {
1884
- return LEADING_VALUE_VERB.test(step) && namesAValue(step);
1885
- }
1886
- function detectMissingValues(tests) {
1887
- const findings = [];
1888
- for (const test of tests) {
1889
- for (const origin of ["setup", "steps"]) {
1890
- const steps = origin === "setup" ? test.setup ?? [] : test.steps;
1891
- steps.forEach((step, position) => {
1892
- if (namesNoValue(step)) {
1893
- findings.push({ test, origin, index: position + 1, step });
1894
- }
1895
- });
1896
- }
1897
- }
1898
- return { findings };
1899
- }
1900
- function suggestValueClause(step) {
1901
- return `${step.trimEnd()} with <value>`;
1902
- }
1903
-
1904
2079
  // src/runner/testfile.ts
1905
2080
  import { readFile as readFile3, readdir } from "fs/promises";
1906
2081
  import path5 from "path";
@@ -2021,7 +2196,7 @@ async function generateForRoute(page, options) {
2021
2196
  `Cannot load ${url}: ${error instanceof Error ? error.message : String(error)}`
2022
2197
  );
2023
2198
  }
2024
- const pageSnapshot = mask(await takeSnapshot(page));
2199
+ const pageSnapshot = withoutRefs(mask(await takeSnapshot(page)));
2025
2200
  const generated = await brain.planTest({
2026
2201
  route,
2027
2202
  snapshot: pageSnapshot,
@@ -2550,7 +2725,8 @@ function resolveBudgetOptions(config, options) {
2550
2725
  return {
2551
2726
  maxCalls: options.maxLlmCalls ?? config.budget?.max_llm_calls,
2552
2727
  maxTokens: options.maxTokens ?? config.budget?.max_tokens,
2553
- maxDurationMs: maxDurationSeconds === void 0 ? void 0 : maxDurationSeconds * 1e3
2728
+ maxDurationMs: maxDurationSeconds === void 0 ? void 0 : maxDurationSeconds * 1e3,
2729
+ callTimeoutMs: timeoutSeconds(config.llm) * 1e3
2554
2730
  };
2555
2731
  }
2556
2732
  function sessionId() {
@@ -3363,7 +3539,7 @@ function parsePositiveNumber(flag) {
3363
3539
  };
3364
3540
  }
3365
3541
  var program = new Command();
3366
- program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.23.0");
3542
+ program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.25.0");
3367
3543
  program.command("init").description("Scaffold .blastproof/ (config, tests, sample tests) in the current directory").action(async () => {
3368
3544
  try {
3369
3545
  const result = await initProject(process.cwd());
@@ -3498,6 +3674,8 @@ program.command("test").description("Full PR pipeline: run the tests covering th
3498
3674
  );
3499
3675
  program.exitOverride();
3500
3676
  for (const command of program.commands) command.exitOverride();
3677
+ process.once("SIGTERM", () => process.exit(143));
3678
+ process.once("SIGHUP", () => process.exit(129));
3501
3679
  try {
3502
3680
  await program.parseAsync(process.argv);
3503
3681
  } catch (error) {