blastproof 0.24.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/README.md CHANGED
@@ -77,7 +77,7 @@ Three questions. The first one decides most cases.
77
77
 
78
78
  **A hard requirement, not a preference.** blastproof finds elements the way a screen reader does — by role, by label, by visible text. That is what removes selectors and survives redesigns. The cost is that there is deliberately no CSS or XPath fallback, so anything the accessibility tree cannot describe cannot be driven at all.
79
79
 
80
- The name is matched **exactly first**, then by substring if nothing matches exactly — so a control named `Add` is found even when `Add New` sits above it. When several controls answer to the same name, the first one on the page wins. Give each control an accessible name no other control on the page shares; a page that cannot offer one cannot be driven unambiguously, and no matching rule fixes that.
80
+ The agent acts on the element it read, not on a search for its name. Each element in the snapshot it reads carries a ref, and an action names that ref: two controls called `Delete` are two different targets, and `Add` is never mistaken for `Add New`. If the role and name the agent gives do not match the element the ref points at, the action is refused rather than performed. A ref is valid only for the snapshot it came from, so nothing like a selector is ever stored.
81
81
 
82
82
  | works | cannot be driven |
83
83
  | --- | --- |
@@ -313,6 +313,8 @@ The bounds are 95% upper bounds: zero errors in 40 runs means "below about 9%",
313
313
 
314
314
  The demo app is small and well labelled, so these numbers flatter. Expect a real application to do worse. The point of this table is that it can be reproduced, and that every change claiming better verdicts has to move it.
315
315
 
316
+ The same benchmark over seven more models, and why it chose the OpenAI and Ollama defaults, is in [Choosing a model](./docs/configuration.md#choosing-a-model).
317
+
316
318
  Measured 2026-10-07 on `main` after 0.23.0 with #147's fix, 5 samples, through OpenRouter. To reproduce:
317
319
 
318
320
  ```bash
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/runner/snapshot.ts
4
+ var DEFAULT_MAX_LINES = 200;
5
+ function indentOf(line) {
6
+ return line.length - line.trimStart().length;
7
+ }
8
+ function trimSnapshot(snapshotYaml, maxLines = DEFAULT_MAX_LINES) {
9
+ let lines = snapshotYaml.split("\n").filter((line) => line.trim().length > 0);
10
+ for (let pass = 0; pass < 5; pass++) {
11
+ const kept = [];
12
+ let removed = 0;
13
+ for (let i = 0; i < lines.length; i++) {
14
+ const line = lines[i];
15
+ const isContainer = line.trimEnd().endsWith(":");
16
+ if (isContainer) {
17
+ const next = lines[i + 1];
18
+ const hasChildren = next !== void 0 && indentOf(next) > indentOf(line);
19
+ if (!hasChildren) {
20
+ removed++;
21
+ continue;
22
+ }
23
+ }
24
+ kept.push(line);
25
+ }
26
+ lines = kept;
27
+ if (removed === 0) break;
28
+ }
29
+ if (lines.length > maxLines) {
30
+ lines = [...lines.slice(0, maxLines), `- ... (snapshot truncated after ${maxLines} lines)`];
31
+ }
32
+ return lines.join("\n");
33
+ }
34
+ async function captureSnapshot(page, options = {}) {
35
+ const raw = await page.locator("body").ariaSnapshot({ mode: "ai" });
36
+ return `url: ${page.url()}
37
+ ${trimSnapshot(raw.replace(/ \[cursor=pointer\]/g, ""), options.maxLines)}`;
38
+ }
39
+ var REF_MARKER = / \[ref=[A-Za-z0-9_-]+\]/g;
40
+ function withoutRefs(snapshot) {
41
+ return snapshot.replace(REF_MARKER, "");
42
+ }
43
+ function unquote(value) {
44
+ const trimmed = value.trim();
45
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
46
+ return trimmed.slice(1, -1).replace(/\\(["\\])/g, "$1");
47
+ }
48
+ if (trimmed.length >= 2 && trimmed.startsWith("'") && trimmed.endsWith("'")) {
49
+ return trimmed.slice(1, -1).replace(/''/g, "'");
50
+ }
51
+ return trimmed;
52
+ }
53
+ var ELEMENT_LINE = /^\s*- ([a-z][a-zA-Z]*)(?: ("(?:[^"\\]|\\.)*"))?((?: \[[^\]]*\])*)(?::(?: (.*))?)?$/;
54
+ function indexRefs(snapshot) {
55
+ const index = /* @__PURE__ */ new Map();
56
+ for (const raw of snapshot.split("\n")) {
57
+ const quoted = /^(\s*- )'((?:[^']|'')*)'(:.*)?$/.exec(raw);
58
+ const line = quoted ? `${quoted[1]}${quoted[2].replace(/''/g, "'")}${quoted[3] ?? ""}` : raw;
59
+ const match = ELEMENT_LINE.exec(line);
60
+ if (!match) continue;
61
+ const ref = /\[ref=([A-Za-z0-9_-]+)\]/.exec(match[3] ?? "")?.[1];
62
+ if (!ref) continue;
63
+ const element = { role: match[1] };
64
+ if (match[2] !== void 0) element.name = unquote(match[2]);
65
+ if (match[4] !== void 0 && match[4].trim() !== "") element.text = unquote(match[4]);
66
+ index.set(ref, element);
67
+ }
68
+ return index;
69
+ }
70
+
71
+ export {
72
+ trimSnapshot,
73
+ captureSnapshot,
74
+ withoutRefs,
75
+ indexRefs
76
+ };
77
+ //# sourceMappingURL=chunk-RA4N57HA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runner/snapshot.ts"],"sourcesContent":["import type { Page } from 'playwright';\n\nexport interface SnapshotOptions {\n /** Maximum number of snapshot lines sent to the LLM. Default 200. */\n maxLines?: number;\n}\n\nconst DEFAULT_MAX_LINES = 200;\n\nfunction indentOf(line: string): number {\n return line.length - line.trimStart().length;\n}\n\n/**\n * Trims an aria snapshot: drops empty containers (e.g. `- group:` with no children)\n * and caps the line count. Pure function, exported for tests.\n */\nexport function trimSnapshot(snapshotYaml: string, maxLines: number = DEFAULT_MAX_LINES): string {\n let lines = snapshotYaml.split('\\n').filter((line) => line.trim().length > 0);\n\n // Removing empty containers can empty their parents; iterate until stable (bounded).\n for (let pass = 0; pass < 5; pass++) {\n const kept: string[] = [];\n let removed = 0;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const isContainer = line.trimEnd().endsWith(':');\n if (isContainer) {\n const next = lines[i + 1];\n const hasChildren = next !== undefined && indentOf(next) > indentOf(line);\n if (!hasChildren) {\n removed++;\n continue;\n }\n }\n kept.push(line);\n }\n lines = kept;\n if (removed === 0) break;\n }\n\n if (lines.length > maxLines) {\n lines = [...lines.slice(0, maxLines), `- ... (snapshot truncated after ${maxLines} lines)`];\n }\n return lines.join('\\n');\n}\n\n/**\n * Captures the current page as a compact accessibility snapshot (design D1),\n * prefixed with the page URL so the model can reason about navigation.\n *\n * Always in AI mode (design act-on-the-element-the-model-read, D3): every\n * element carries the `[ref=…]` an action names it by, and a plain\n * `ariaSnapshot()` invalidates the refs of the last AI-mode one, measured. The\n * `[cursor=pointer]` marker it adds is dropped: it is about the mouse, not the\n * element, and it was most of the growth that was not a ref.\n */\nexport async function captureSnapshot(page: Page, options: SnapshotOptions = {}): Promise<string> {\n const raw = await page.locator('body').ariaSnapshot({ mode: 'ai' });\n return `url: ${page.url()}\\n${trimSnapshot(raw.replace(/ \\[cursor=pointer\\]/g, ''), options.maxLines)}`;\n}\n\nconst REF_MARKER = / \\[ref=[A-Za-z0-9_-]+\\]/g;\n\n/**\n * The snapshot as a reader that chooses no element sees it: the judge and the\n * planner (design act-on-the-element-the-model-read, D3). Refs are ids, not\n * page content, and the judge corpus's stored snapshots have none.\n */\nexport function withoutRefs(snapshot: string): string {\n return snapshot.replace(REF_MARKER, '');\n}\n\n/** What the snapshot line holding a ref shows about its element. */\nexport interface SnapshotElement {\n role: string;\n /** The accessible name, unquoted; absent when the line has none. */\n name?: string;\n /** Inline text after the colon (`- generic [ref=e4]: Promo code`), unquoted. */\n text?: string;\n}\n\n/** Undoes YAML double-quote escaping, the form a name containing `\"` is printed in. */\nfunction unquote(value: string): string {\n const trimmed = value.trim();\n if (trimmed.length >= 2 && trimmed.startsWith('\"') && trimmed.endsWith('\"')) {\n return trimmed.slice(1, -1).replace(/\\\\([\"\\\\])/g, '$1');\n }\n if (trimmed.length >= 2 && trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\")) {\n return trimmed.slice(1, -1).replace(/''/g, \"'\");\n }\n return trimmed;\n}\n\n// `- role \"name\" [attr] [ref=x] [attr]: inline text`, every part after the role optional.\nconst ELEMENT_LINE =\n /^\\s*- ([a-z][a-zA-Z]*)(?: (\"(?:[^\"\\\\]|\\\\.)*\"))?((?: \\[[^\\]]*\\])*)(?::(?: (.*))?)?$/;\n\n/**\n * Each ref in a snapshot, with the role and name its line shows (design\n * act-on-the-element-the-model-read, D2). Read from the snapshot text the model\n * was given, masked as it was, so what is checked and recorded is what the\n * model read and no secret enters the record.\n */\nexport function indexRefs(snapshot: string): Map<string, SnapshotElement> {\n const index = new Map<string, SnapshotElement>();\n for (const raw of snapshot.split('\\n')) {\n // YAML single-quotes a whole entry whose text holds `: `, as in\n // `- 'heading \"Notes on file: 1\" [level=2] [ref=e16]'`.\n const quoted = /^(\\s*- )'((?:[^']|'')*)'(:.*)?$/.exec(raw);\n const line = quoted ? `${quoted[1]}${quoted[2]!.replace(/''/g, \"'\")}${quoted[3] ?? ''}` : raw;\n const match = ELEMENT_LINE.exec(line);\n if (!match) continue;\n const ref = /\\[ref=([A-Za-z0-9_-]+)\\]/.exec(match[3] ?? '')?.[1];\n if (!ref) continue;\n const element: SnapshotElement = { role: match[1]! };\n if (match[2] !== undefined) element.name = unquote(match[2]);\n if (match[4] !== undefined && match[4].trim() !== '') element.text = unquote(match[4]);\n index.set(ref, element);\n }\n return index;\n}\n"],"mappings":";;;AAOA,IAAM,oBAAoB;AAE1B,SAAS,SAAS,MAAsB;AACtC,SAAO,KAAK,SAAS,KAAK,UAAU,EAAE;AACxC;AAMO,SAAS,aAAa,cAAsB,WAAmB,mBAA2B;AAC/F,MAAI,QAAQ,aAAa,MAAM,IAAI,EAAE,OAAO,CAAC,SAAS,KAAK,KAAK,EAAE,SAAS,CAAC;AAG5E,WAAS,OAAO,GAAG,OAAO,GAAG,QAAQ;AACnC,UAAM,OAAiB,CAAC;AACxB,QAAI,UAAU;AACd,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAM,OAAO,MAAM,CAAC;AACpB,YAAM,cAAc,KAAK,QAAQ,EAAE,SAAS,GAAG;AAC/C,UAAI,aAAa;AACf,cAAM,OAAO,MAAM,IAAI,CAAC;AACxB,cAAM,cAAc,SAAS,UAAa,SAAS,IAAI,IAAI,SAAS,IAAI;AACxE,YAAI,CAAC,aAAa;AAChB;AACA;AAAA,QACF;AAAA,MACF;AACA,WAAK,KAAK,IAAI;AAAA,IAChB;AACA,YAAQ;AACR,QAAI,YAAY,EAAG;AAAA,EACrB;AAEA,MAAI,MAAM,SAAS,UAAU;AAC3B,YAAQ,CAAC,GAAG,MAAM,MAAM,GAAG,QAAQ,GAAG,mCAAmC,QAAQ,SAAS;AAAA,EAC5F;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;AAYA,eAAsB,gBAAgB,MAAY,UAA2B,CAAC,GAAoB;AAChG,QAAM,MAAM,MAAM,KAAK,QAAQ,MAAM,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAClE,SAAO,QAAQ,KAAK,IAAI,CAAC;AAAA,EAAK,aAAa,IAAI,QAAQ,wBAAwB,EAAE,GAAG,QAAQ,QAAQ,CAAC;AACvG;AAEA,IAAM,aAAa;AAOZ,SAAS,YAAY,UAA0B;AACpD,SAAO,SAAS,QAAQ,YAAY,EAAE;AACxC;AAYA,SAAS,QAAQ,OAAuB;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,UAAU,KAAK,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;AAC3E,WAAO,QAAQ,MAAM,GAAG,EAAE,EAAE,QAAQ,cAAc,IAAI;AAAA,EACxD;AACA,MAAI,QAAQ,UAAU,KAAK,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;AAC3E,WAAO,QAAQ,MAAM,GAAG,EAAE,EAAE,QAAQ,OAAO,GAAG;AAAA,EAChD;AACA,SAAO;AACT;AAGA,IAAM,eACJ;AAQK,SAAS,UAAU,UAAgD;AACxE,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,aAAW,OAAO,SAAS,MAAM,IAAI,GAAG;AAGtC,UAAM,SAAS,kCAAkC,KAAK,GAAG;AACzD,UAAM,OAAO,SAAS,GAAG,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,EAAG,QAAQ,OAAO,GAAG,CAAC,GAAG,OAAO,CAAC,KAAK,EAAE,KAAK;AAC1F,UAAM,QAAQ,aAAa,KAAK,IAAI;AACpC,QAAI,CAAC,MAAO;AACZ,UAAM,MAAM,2BAA2B,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC;AAC/D,QAAI,CAAC,IAAK;AACV,UAAM,UAA2B,EAAE,MAAM,MAAM,CAAC,EAAG;AACnD,QAAI,MAAM,CAAC,MAAM,OAAW,SAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC;AAC3D,QAAI,MAAM,CAAC,MAAM,UAAa,MAAM,CAAC,EAAE,KAAK,MAAM,GAAI,SAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC;AACrF,UAAM,IAAI,KAAK,OAAO;AAAA,EACxB;AACA,SAAO;AACT;","names":[]}
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)}`;
@@ -664,20 +720,14 @@ function normalise(text) {
664
720
  return text.replace(/\s+/g, " ").trim().toLowerCase();
665
721
  }
666
722
  function describeAction(action) {
667
- const target = action.target ? ` ${action.target.role ?? ""} "${action.target.name ?? action.target.text ?? ""}"` : "";
723
+ const target = action.target ? ` ${action.target.role ?? ""} "${action.target.name ?? ""}"` : "";
668
724
  const value = action.value ? ` [${action.value}]` : "";
669
725
  return `${action.action}${target}${value}`;
670
726
  }
671
727
  function identity(action) {
672
728
  const role = action.target?.role ?? "";
673
729
  const name = action.target?.name ?? "";
674
- return JSON.stringify([
675
- action.action,
676
- role,
677
- normalise(name),
678
- role || name ? "" : action.target?.text ?? "",
679
- action.value ?? ""
680
- ]);
730
+ return JSON.stringify([action.action, role, normalise(name), action.value ?? ""]);
681
731
  }
682
732
  var StepRecovery = class {
683
733
  performed = /* @__PURE__ */ new Set();
@@ -804,7 +854,8 @@ var StepRecovery = class {
804
854
  repeatedCommitRefusal(action) {
805
855
  if (!isCommit(action)) return void 0;
806
856
  if (!this.performed.has(identity(action))) return void 0;
807
- 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.`;
808
859
  }
809
860
  /**
810
861
  * Refuses a typed value that came from nowhere the model was entitled to read
@@ -861,7 +912,7 @@ async function waitForSettled(page) {
861
912
  }
862
913
  }
863
914
  async function defaultSnapshot(page, maxLines) {
864
- const { captureSnapshot } = await import("./snapshot-CAIB2OHX.js");
915
+ const { captureSnapshot } = await import("./snapshot-PYB4N7E7.js");
865
916
  return captureSnapshot(page, { maxLines });
866
917
  }
867
918
  function slugify(text) {
@@ -930,7 +981,9 @@ async function executeTest(page, test, options) {
930
981
  }
931
982
  const snap = await takeSnapshot(page);
932
983
  const maskedSnap = mask(snap);
933
- recovery.observe(maskedSnap);
984
+ const refs = indexRefs(maskedSnap);
985
+ const pageSnap = withoutRefs(maskedSnap);
986
+ recovery.observe(pageSnap);
934
987
  let action;
935
988
  try {
936
989
  action = await brain.nextAction({
@@ -978,14 +1031,14 @@ async function executeTest(page, test, options) {
978
1031
  judgment = await brain.judge(
979
1032
  mask(step),
980
1033
  mask(expectation),
981
- maskedSnap,
1034
+ pageSnap,
982
1035
  recovery.stepHistory(),
983
1036
  [...usedEarlier]
984
1037
  );
985
1038
  if (!judgment.pass) {
986
1039
  await waitForSettled(page);
987
1040
  const freshSnap = await takeSnapshot(page);
988
- const maskedFresh = mask(freshSnap);
1041
+ const maskedFresh = withoutRefs(mask(freshSnap));
989
1042
  recovery.observe(maskedFresh);
990
1043
  judgment = await brain.judge(
991
1044
  mask(step),
@@ -1018,6 +1071,17 @@ async function executeTest(page, test, options) {
1018
1071
  }
1019
1072
  continue;
1020
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
+ }
1021
1085
  const refusal = recovery.refusalFor(action);
1022
1086
  if (refusal) {
1023
1087
  failedAttempts++;
@@ -1210,7 +1274,8 @@ async function fromSteps(options) {
1210
1274
  const judgment = await verifyJudgment(
1211
1275
  brain,
1212
1276
  auth.verify,
1213
- 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))),
1214
1279
  (text) => mask.mask(text),
1215
1280
  maxRetries
1216
1281
  );
@@ -1270,7 +1335,30 @@ var llmSchema = z.object({
1270
1335
  provider: z.enum(["anthropic", "openai", "ollama"]).default("anthropic"),
1271
1336
  model: z.string().min(1).optional(),
1272
1337
  api_key_env: z.string().min(1).optional(),
1273
- 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
+ }
1274
1362
  });
1275
1363
  var browserSchema = z.object({
1276
1364
  headless: z.boolean().default(true),
@@ -1381,6 +1469,7 @@ var ENV_OVERRIDES = {
1381
1469
  BLASTPROOF_LLM_MODEL: ["llm", "model"],
1382
1470
  BLASTPROOF_LLM_BASE_URL: ["llm", "base_url"],
1383
1471
  BLASTPROOF_LLM_API_KEY_ENV: ["llm", "api_key_env"],
1472
+ BLASTPROOF_LLM_TIMEOUT_S: ["llm", "timeout_s"],
1384
1473
  BLASTPROOF_MAX_LLM_CALLS: ["budget", "max_llm_calls"],
1385
1474
  BLASTPROOF_MAX_TOKENS: ["budget", "max_tokens"],
1386
1475
  BLASTPROOF_MAX_DURATION_S: ["budget", "max_duration_s"]
@@ -1585,7 +1674,7 @@ warning: ${findings.length} file(s) changed in the working tree are not in the d
1585
1674
  }
1586
1675
 
1587
1676
  // src/llm/brain.ts
1588
- import { APICallError, generateObject, RetryError } from "ai";
1677
+ import { APICallError, generateObject, NoObjectGeneratedError, RetryError } from "ai";
1589
1678
 
1590
1679
  // src/llm/prompts.ts
1591
1680
  function agentSystemPrompt() {
@@ -1598,7 +1687,7 @@ The snapshot is a description of what is on screen. It is the thing you are test
1598
1687
  Rules:
1599
1688
  - Return exactly ONE action per response. Never batch actions.
1600
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.
1601
- - 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.
1602
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).
1603
1692
  - Use "assert" with an expectation to verify page state (visible text, counts, URLs). Assertions never modify the page.
1604
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.
@@ -1711,17 +1800,19 @@ var agentActionSchema = z2.object({
1711
1800
  action: z2.enum(ACTION_NAMES).describe("The next browser action to perform for the current step."),
1712
1801
  target: absentAsNull(
1713
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
+ ),
1714
1806
  role: absentAsNull(
1715
- 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".')
1716
1808
  ),
1717
1809
  name: absentAsNull(
1718
- z2.string().describe("Accessible name of the target element, exactly as shown in the snapshot.")
1719
- ),
1720
- text: absentAsNull(
1721
- 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
+ )
1722
1813
  )
1723
1814
  })
1724
- ).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."),
1725
1816
  value: absentAsNull(
1726
1817
  z2.string().describe(
1727
1818
  'Action payload: URL/path for navigate, text for fill, key for press (e.g. "Enter"), option label for select.'
@@ -1735,9 +1826,9 @@ var agentActionSchema = z2.object({
1735
1826
  var parsedAgentActionSchema = z2.object({
1736
1827
  action: z2.enum(ACTION_NAMES),
1737
1828
  target: z2.object({
1829
+ ref: z2.string().optional(),
1738
1830
  role: z2.string().optional(),
1739
- name: z2.string().optional(),
1740
- text: z2.string().optional()
1831
+ name: z2.string().optional()
1741
1832
  }).optional(),
1742
1833
  value: z2.string().optional(),
1743
1834
  reasoning: z2.string(),
@@ -1765,6 +1856,7 @@ var generatedTestSchema = z2.object({
1765
1856
  });
1766
1857
 
1767
1858
  // src/llm/brain.ts
1859
+ var MAX_OUTPUT_TOKENS = 4096;
1768
1860
  var MalformedModelOutputError = class extends Error {
1769
1861
  constructor(message) {
1770
1862
  super(message);
@@ -1788,13 +1880,35 @@ function asProviderRefusal(error) {
1788
1880
  withProviderDetail(cause);
1789
1881
  return new ProviderRefusedError(cause.statusCode, cause.message);
1790
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
+ }
1791
1898
  async function countedGenerate(generate, budget, options) {
1792
1899
  budget.check();
1900
+ const abort = callAbort(budget);
1793
1901
  let result;
1794
1902
  try {
1795
- result = await generate(options);
1903
+ result = await generate({ ...options, maxOutputTokens: MAX_OUTPUT_TOKENS, abortSignal: abort?.signal });
1796
1904
  } catch (error) {
1797
- 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();
1798
1912
  }
1799
1913
  budget.record(result.usage);
1800
1914
  return result;
@@ -1887,14 +2001,35 @@ import { createAnthropic } from "@ai-sdk/anthropic";
1887
2001
  import { createOpenAI } from "@ai-sdk/openai";
1888
2002
  var DEFAULT_MODELS = {
1889
2003
  anthropic: "claude-haiku-4-5",
1890
- openai: "gpt-4o-mini",
1891
- ollama: "qwen2.5"
2004
+ openai: "gpt-6-luna",
2005
+ ollama: "gpt-oss:20b"
1892
2006
  };
1893
2007
  var DEFAULT_API_KEY_ENVS = {
1894
2008
  anthropic: "ANTHROPIC_API_KEY",
1895
2009
  openai: "OPENAI_API_KEY"
1896
2010
  };
1897
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
+ }
1898
2033
  var MissingApiKeyError = class extends Error {
1899
2034
  constructor(variable, provider) {
1900
2035
  super(
@@ -1914,6 +2049,7 @@ function createModel(llm, env = process.env) {
1914
2049
  throw new MissingApiKeyError(keyEnv, llm.provider);
1915
2050
  }
1916
2051
  const baseURL = llm.base_url ? { baseURL: llm.base_url } : {};
2052
+ const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
1917
2053
  const model = llm.provider === "anthropic" ? (
1918
2054
  // A configured endpoint applies to whichever provider is selected —
1919
2055
  // dropping it here routed corporate-proxy configs to the public API
@@ -1922,13 +2058,14 @@ function createModel(llm, env = process.env) {
1922
2058
  ) : (
1923
2059
  // `.chat` = Chat Completions: works with official OpenAI and any
1924
2060
  // OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM) via base_url.
1925
- createOpenAI({ apiKey, ...baseURL }).chat(modelId)
2061
+ createOpenAI({ apiKey, ...baseURL, ...extra }).chat(modelId)
1926
2062
  );
1927
2063
  return { model, provider: llm.provider, modelId };
1928
2064
  }
1929
2065
  case "ollama": {
1930
2066
  const baseURL = llm.base_url ?? DEFAULT_OLLAMA_BASE_URL;
1931
- 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);
1932
2069
  return { model, provider: "ollama", modelId };
1933
2070
  }
1934
2071
  }
@@ -2059,7 +2196,7 @@ async function generateForRoute(page, options) {
2059
2196
  `Cannot load ${url}: ${error instanceof Error ? error.message : String(error)}`
2060
2197
  );
2061
2198
  }
2062
- const pageSnapshot = mask(await takeSnapshot(page));
2199
+ const pageSnapshot = withoutRefs(mask(await takeSnapshot(page)));
2063
2200
  const generated = await brain.planTest({
2064
2201
  route,
2065
2202
  snapshot: pageSnapshot,
@@ -2588,7 +2725,8 @@ function resolveBudgetOptions(config, options) {
2588
2725
  return {
2589
2726
  maxCalls: options.maxLlmCalls ?? config.budget?.max_llm_calls,
2590
2727
  maxTokens: options.maxTokens ?? config.budget?.max_tokens,
2591
- maxDurationMs: maxDurationSeconds === void 0 ? void 0 : maxDurationSeconds * 1e3
2728
+ maxDurationMs: maxDurationSeconds === void 0 ? void 0 : maxDurationSeconds * 1e3,
2729
+ callTimeoutMs: timeoutSeconds(config.llm) * 1e3
2592
2730
  };
2593
2731
  }
2594
2732
  function sessionId() {
@@ -3401,7 +3539,7 @@ function parsePositiveNumber(flag) {
3401
3539
  };
3402
3540
  }
3403
3541
  var program = new Command();
3404
- program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.24.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");
3405
3543
  program.command("init").description("Scaffold .blastproof/ (config, tests, sample tests) in the current directory").action(async () => {
3406
3544
  try {
3407
3545
  const result = await initProject(process.cwd());
@@ -3536,6 +3674,8 @@ program.command("test").description("Full PR pipeline: run the tests covering th
3536
3674
  );
3537
3675
  program.exitOverride();
3538
3676
  for (const command of program.commands) command.exitOverride();
3677
+ process.once("SIGTERM", () => process.exit(143));
3678
+ process.once("SIGHUP", () => process.exit(129));
3539
3679
  try {
3540
3680
  await program.parseAsync(process.argv);
3541
3681
  } catch (error) {