blastproof 0.26.0 → 0.28.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 +15 -7
- package/dist/cli.js +425 -151
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -207,7 +207,7 @@ function formatInitGuidance(result) {
|
|
|
207
207
|
}
|
|
208
208
|
|
|
209
209
|
// src/commands/plan.ts
|
|
210
|
-
import
|
|
210
|
+
import path11 from "path";
|
|
211
211
|
|
|
212
212
|
// src/auth.ts
|
|
213
213
|
import { readFile, writeFile as writeFile2, mkdir as mkdir3 } from "fs/promises";
|
|
@@ -363,12 +363,13 @@ var RunBudget = class {
|
|
|
363
363
|
};
|
|
364
364
|
}
|
|
365
365
|
};
|
|
366
|
-
function estimateMaxModelCalls(tests, maxIterationsPerStep, maxRetriesPerStep) {
|
|
366
|
+
function estimateMaxModelCalls(tests, maxIterationsPerStep, maxRetriesPerStep, judgeCalls = 1) {
|
|
367
367
|
const totalSteps = tests.reduce(
|
|
368
368
|
(sum, test) => sum + (test.setup?.length ?? 0) + test.steps.length,
|
|
369
369
|
0
|
|
370
370
|
);
|
|
371
|
-
|
|
371
|
+
const bundled = (2 * judgeCalls - 1) * Math.min(maxIterationsPerStep, maxRetriesPerStep);
|
|
372
|
+
return totalSteps * (maxIterationsPerStep + maxRetriesPerStep + bundled);
|
|
372
373
|
}
|
|
373
374
|
|
|
374
375
|
// src/runner/env.ts
|
|
@@ -690,10 +691,16 @@ function namesAValue(step) {
|
|
|
690
691
|
function namesNoValue(step) {
|
|
691
692
|
return LEADING_VALUE_VERB.test(step) && !namesAValue(step);
|
|
692
693
|
}
|
|
693
|
-
var
|
|
694
|
+
var CHECK_VERB = String.raw`(?:verify|check|confirm|ensure|assert|expect|validate|make\s+sure|see\s+that)\b`;
|
|
695
|
+
var LEADING_CHECK_VERB = new RegExp(String.raw`^\s*(?:(?:then|and)\s+)?` + CHECK_VERB, "i");
|
|
696
|
+
var CHECK_CLAUSE = new RegExp(String.raw`(?:\band\b|\bthen\b|[,;])\s+` + CHECK_VERB, "i");
|
|
694
697
|
function isVerificationStep(step) {
|
|
695
698
|
return LEADING_CHECK_VERB.test(step);
|
|
696
699
|
}
|
|
700
|
+
function hasVerificationClause(step) {
|
|
701
|
+
const unquoted = step.replace(/"[^"]*"|“[^”]*”/g, '""');
|
|
702
|
+
return !isVerificationStep(step) && CHECK_CLAUSE.test(unquoted);
|
|
703
|
+
}
|
|
697
704
|
function entersNamedValue(step) {
|
|
698
705
|
return LEADING_VALUE_VERB.test(step) && namesAValue(step);
|
|
699
706
|
}
|
|
@@ -779,10 +786,17 @@ var StepRecovery = class {
|
|
|
779
786
|
* D1). Read by the executor too, which refuses `done` in such a step.
|
|
780
787
|
*/
|
|
781
788
|
verifies;
|
|
789
|
+
/**
|
|
790
|
+
* Whether the step acts first and asks for a check after (design
|
|
791
|
+
* judge-a-done-that-closes-a-check, D2). The executor judges a `done` in such
|
|
792
|
+
* a step instead of closing it.
|
|
793
|
+
*/
|
|
794
|
+
checksAfterActing;
|
|
782
795
|
constructor(step) {
|
|
783
796
|
this.step = step;
|
|
784
797
|
this.readable = [normalise(step)];
|
|
785
798
|
this.verifies = isVerificationStep(step);
|
|
799
|
+
this.checksAfterActing = hasVerificationClause(step);
|
|
786
800
|
}
|
|
787
801
|
/**
|
|
788
802
|
* Records a snapshot the model was shown, as a source it may quote from.
|
|
@@ -1061,6 +1075,8 @@ async function executeTest(page, test, options) {
|
|
|
1061
1075
|
continue;
|
|
1062
1076
|
}
|
|
1063
1077
|
iterations++;
|
|
1078
|
+
let judgingDone = false;
|
|
1079
|
+
const shown = () => judgingDone ? { ...action, action: "done" } : action;
|
|
1064
1080
|
if (action.action === "done") {
|
|
1065
1081
|
if (!recovery.acted || recovery.verifies) {
|
|
1066
1082
|
failedAttempts++;
|
|
@@ -1071,8 +1087,12 @@ async function executeTest(page, test, options) {
|
|
|
1071
1087
|
}
|
|
1072
1088
|
continue;
|
|
1073
1089
|
}
|
|
1074
|
-
|
|
1075
|
-
|
|
1090
|
+
if (!recovery.checksAfterActing) {
|
|
1091
|
+
emitAction(index, action, action.reasoning);
|
|
1092
|
+
break;
|
|
1093
|
+
}
|
|
1094
|
+
judgingDone = true;
|
|
1095
|
+
action = { ...action, action: "assert", expectation: action.reasoning };
|
|
1076
1096
|
}
|
|
1077
1097
|
if (action.action === "fail") {
|
|
1078
1098
|
if (!recovery.acted && !lookedAgain) {
|
|
@@ -1118,14 +1138,14 @@ async function executeTest(page, test, options) {
|
|
|
1118
1138
|
if (error instanceof RunStoppedError) throw error;
|
|
1119
1139
|
failedAttempts++;
|
|
1120
1140
|
lastResult = `error: ${error instanceof Error ? error.message : String(error)}`;
|
|
1121
|
-
emitAction(index,
|
|
1141
|
+
emitAction(index, shown(), lastResult);
|
|
1122
1142
|
if (failedAttempts >= maxRetries) {
|
|
1123
1143
|
throw new StepFailure(lastResult);
|
|
1124
1144
|
}
|
|
1125
1145
|
continue;
|
|
1126
1146
|
}
|
|
1127
1147
|
const result = judgment.pass ? `ok: assertion passed: ${judgment.reason}` : `assertion failed: ${judgment.reason}`;
|
|
1128
|
-
emitAction(index,
|
|
1148
|
+
emitAction(index, shown(), result);
|
|
1129
1149
|
if (judgment.pass) {
|
|
1130
1150
|
lastResult = result;
|
|
1131
1151
|
break;
|
|
@@ -1230,6 +1250,25 @@ async function executeTest(page, test, options) {
|
|
|
1230
1250
|
};
|
|
1231
1251
|
}
|
|
1232
1252
|
|
|
1253
|
+
// src/runner/device.ts
|
|
1254
|
+
import { devices } from "playwright";
|
|
1255
|
+
function isDevice(name) {
|
|
1256
|
+
return Object.hasOwn(devices, name);
|
|
1257
|
+
}
|
|
1258
|
+
function unknownDeviceMessage(name) {
|
|
1259
|
+
const words = name.toLowerCase().split(/\s+/).filter(Boolean);
|
|
1260
|
+
const same = Object.keys(devices).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
|
|
1261
|
+
if (same) return `"${name}" is not a device Playwright knows; did you mean "${same}"? Names are case-sensitive`;
|
|
1262
|
+
const close = Object.keys(devices).filter((candidate) => !candidate.endsWith(" landscape")).filter((candidate) => words.length > 0 && words.every((word) => candidate.toLowerCase().includes(word))).slice(-3);
|
|
1263
|
+
const hint = close.length ? `did you mean ${close.map((c) => `"${c}"`).join(", ")}?` : "see the device names in Playwright's registry: https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json";
|
|
1264
|
+
return `"${name}" is not a device Playwright knows; ${hint}`;
|
|
1265
|
+
}
|
|
1266
|
+
function deviceOptions(name) {
|
|
1267
|
+
if (!name) return {};
|
|
1268
|
+
const { defaultBrowserType: _browser, ...options } = devices[name];
|
|
1269
|
+
return options;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1233
1272
|
// src/auth.ts
|
|
1234
1273
|
var AUTH_STATE_RELATIVE_PATH = path3.join(".blastproof", ".auth-state.json");
|
|
1235
1274
|
var AuthError = class extends Error {
|
|
@@ -1308,7 +1347,7 @@ async function fromSteps(options) {
|
|
|
1308
1347
|
const { auth, baseUrl, browser, brain, maxRetries, snapshot, timeoutMs, maxSnapshotLines, onEvent, mask } = options;
|
|
1309
1348
|
const steps = auth.steps;
|
|
1310
1349
|
const takeSnapshot = snapshot ?? ((page) => defaultSnapshot(page, maxSnapshotLines));
|
|
1311
|
-
const context = await browser.newContext();
|
|
1350
|
+
const context = await browser.newContext(deviceOptions(options.device));
|
|
1312
1351
|
try {
|
|
1313
1352
|
const page = await context.newPage();
|
|
1314
1353
|
const result = await runJourney(
|
|
@@ -1387,9 +1426,10 @@ async function authenticate(options) {
|
|
|
1387
1426
|
if (auth.cache) await writeCached(cwd, session);
|
|
1388
1427
|
return session;
|
|
1389
1428
|
}
|
|
1390
|
-
function contextOptions(session) {
|
|
1391
|
-
if (!session) return
|
|
1429
|
+
function contextOptions(session, device) {
|
|
1430
|
+
if (!session) return deviceOptions(device);
|
|
1392
1431
|
return {
|
|
1432
|
+
...deviceOptions(device),
|
|
1393
1433
|
...session.storageState ? { storageState: session.storageState } : {},
|
|
1394
1434
|
...session.extraHTTPHeaders ? { extraHTTPHeaders: session.extraHTTPHeaders } : {}
|
|
1395
1435
|
};
|
|
@@ -1430,6 +1470,9 @@ var llmSchema = z.object({
|
|
|
1430
1470
|
});
|
|
1431
1471
|
}
|
|
1432
1472
|
});
|
|
1473
|
+
var deviceSchema = z.string().superRefine((name, ctx) => {
|
|
1474
|
+
if (!isDevice(name)) ctx.addIssue({ code: "custom", message: unknownDeviceMessage(name) });
|
|
1475
|
+
});
|
|
1433
1476
|
var browserSchema = z.object({
|
|
1434
1477
|
headless: z.boolean().default(true),
|
|
1435
1478
|
/**
|
|
@@ -1444,7 +1487,13 @@ var browserSchema = z.object({
|
|
|
1444
1487
|
* undefined lets `runner/snapshot.ts`'s own default (200) apply, so a config
|
|
1445
1488
|
* that never mentions this behaves exactly as before it existed.
|
|
1446
1489
|
*/
|
|
1447
|
-
max_snapshot_lines: z.number().int().positive().optional()
|
|
1490
|
+
max_snapshot_lines: z.number().int().positive().optional(),
|
|
1491
|
+
/**
|
|
1492
|
+
* The device every test runs as unless its file names its own (spec
|
|
1493
|
+
* device-emulation). Optional: undefined is Playwright's desktop default, so a
|
|
1494
|
+
* config that never mentions it behaves exactly as before it existed.
|
|
1495
|
+
*/
|
|
1496
|
+
device: deviceSchema.optional()
|
|
1448
1497
|
});
|
|
1449
1498
|
var budgetSchema = z.object({
|
|
1450
1499
|
max_llm_calls: z.coerce.number().int().positive().optional(),
|
|
@@ -1452,6 +1501,11 @@ var budgetSchema = z.object({
|
|
|
1452
1501
|
/** Seconds, not milliseconds, to match how a human would set a deadline. */
|
|
1453
1502
|
max_duration_s: z.coerce.number().positive().optional()
|
|
1454
1503
|
});
|
|
1504
|
+
var firstJudgeSchema = z.object({
|
|
1505
|
+
model: z.string().min(1),
|
|
1506
|
+
api_key_env: z.string().min(1).default("OPENROUTER_API_KEY"),
|
|
1507
|
+
threshold: z.coerce.number().gt(0, "must be a probability above 0").lt(1, "must be a probability below 1").default(0.7)
|
|
1508
|
+
});
|
|
1455
1509
|
var cookieSchema = z.object({
|
|
1456
1510
|
name: z.string().min(1),
|
|
1457
1511
|
value: z.string(),
|
|
@@ -1531,7 +1585,8 @@ var configSchema = z.object({
|
|
|
1531
1585
|
* those tests, not of the runner. Opted into by the person who knows.
|
|
1532
1586
|
*/
|
|
1533
1587
|
concurrency: z.number().int().min(1, "concurrency must be at least 1").default(1),
|
|
1534
|
-
budget: budgetSchema.optional()
|
|
1588
|
+
budget: budgetSchema.optional(),
|
|
1589
|
+
first_judge: firstJudgeSchema.optional()
|
|
1535
1590
|
});
|
|
1536
1591
|
var ENV_OVERRIDES = {
|
|
1537
1592
|
BLASTPROOF_BASE_URL: ["base_url"],
|
|
@@ -1542,7 +1597,10 @@ var ENV_OVERRIDES = {
|
|
|
1542
1597
|
BLASTPROOF_LLM_TIMEOUT_S: ["llm", "timeout_s"],
|
|
1543
1598
|
BLASTPROOF_MAX_LLM_CALLS: ["budget", "max_llm_calls"],
|
|
1544
1599
|
BLASTPROOF_MAX_TOKENS: ["budget", "max_tokens"],
|
|
1545
|
-
BLASTPROOF_MAX_DURATION_S: ["budget", "max_duration_s"]
|
|
1600
|
+
BLASTPROOF_MAX_DURATION_S: ["budget", "max_duration_s"],
|
|
1601
|
+
BLASTPROOF_FIRST_JUDGE_MODEL: ["first_judge", "model"],
|
|
1602
|
+
BLASTPROOF_FIRST_JUDGE_THRESHOLD: ["first_judge", "threshold"],
|
|
1603
|
+
BLASTPROOF_BROWSER_DEVICE: ["browser", "device"]
|
|
1546
1604
|
};
|
|
1547
1605
|
function applyEnvOverrides(data, env = process.env) {
|
|
1548
1606
|
const merged = data && typeof data === "object" ? { ...data } : {};
|
|
@@ -1588,13 +1646,13 @@ function unwrapToObjectSchema(schema) {
|
|
|
1588
1646
|
}
|
|
1589
1647
|
return current instanceof z.ZodObject ? current : void 0;
|
|
1590
1648
|
}
|
|
1591
|
-
function findUnknownConfigKeys(data, schema = configSchema,
|
|
1649
|
+
function findUnknownConfigKeys(data, schema = configSchema, path12 = []) {
|
|
1592
1650
|
const object = unwrapToObjectSchema(schema);
|
|
1593
1651
|
if (!object || data === null || typeof data !== "object" || Array.isArray(data)) return [];
|
|
1594
1652
|
const shape = object.shape;
|
|
1595
1653
|
const warnings = [];
|
|
1596
1654
|
for (const key of Object.keys(data)) {
|
|
1597
|
-
const fieldPath = [...
|
|
1655
|
+
const fieldPath = [...path12, key];
|
|
1598
1656
|
const fieldSchema = shape[key];
|
|
1599
1657
|
if (!fieldSchema) {
|
|
1600
1658
|
warnings.push(fieldPath.join("."));
|
|
@@ -1744,7 +1802,7 @@ warning: ${findings.length} file(s) changed in the working tree are not in the d
|
|
|
1744
1802
|
}
|
|
1745
1803
|
|
|
1746
1804
|
// src/llm/brain.ts
|
|
1747
|
-
import { APICallError, generateObject, NoObjectGeneratedError, RetryError } from "ai";
|
|
1805
|
+
import { APICallError as APICallError2, generateObject, NoObjectGeneratedError, RetryError } from "ai";
|
|
1748
1806
|
|
|
1749
1807
|
// src/llm/prompts.ts
|
|
1750
1808
|
function agentSystemPrompt() {
|
|
@@ -1829,6 +1887,16 @@ function assertUserPrompt(step, expectation, snapshot, stepHistory) {
|
|
|
1829
1887
|
);
|
|
1830
1888
|
return parts.join("\n");
|
|
1831
1889
|
}
|
|
1890
|
+
function firstJudgeQuestion() {
|
|
1891
|
+
const system = assertSystemPrompt();
|
|
1892
|
+
return {
|
|
1893
|
+
instructions: system.slice(0, system.indexOf("Answer with pass=true/false")).trim(),
|
|
1894
|
+
criteria: {
|
|
1895
|
+
true: "The snapshot shows the state the step asks for. Every value the step names appears where the step places it, committed (not only typed into an open, unsubmitted field). An outcome that is an absence is shown by the thing being absent.",
|
|
1896
|
+
false: "Some part of the outcome the step asks for is not shown, or cannot be assessed from this snapshot: a value is missing or different, appears only somewhere else on the page, or only inside an unsubmitted control, or the claim is true of something other than what the step asks."
|
|
1897
|
+
}
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1832
1900
|
function plannerSystemPrompt() {
|
|
1833
1901
|
return `You are a QA engineer writing one end-to-end test for a web page, in plain English.
|
|
1834
1902
|
|
|
@@ -1860,6 +1928,223 @@ function plannerUserPrompt(input) {
|
|
|
1860
1928
|
return parts.join("\n");
|
|
1861
1929
|
}
|
|
1862
1930
|
|
|
1931
|
+
// src/llm/decision.ts
|
|
1932
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
1933
|
+
import path5 from "path";
|
|
1934
|
+
import { APICallError } from "ai";
|
|
1935
|
+
|
|
1936
|
+
// src/llm/provider.ts
|
|
1937
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
1938
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
1939
|
+
var DEFAULT_MODELS = {
|
|
1940
|
+
anthropic: "claude-haiku-4-5",
|
|
1941
|
+
openai: "gpt-6-luna",
|
|
1942
|
+
ollama: "gpt-oss:20b"
|
|
1943
|
+
};
|
|
1944
|
+
var DEFAULT_API_KEY_ENVS = {
|
|
1945
|
+
anthropic: "ANTHROPIC_API_KEY",
|
|
1946
|
+
openai: "OPENAI_API_KEY"
|
|
1947
|
+
};
|
|
1948
|
+
var DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434/v1";
|
|
1949
|
+
var DEFAULT_TIMEOUT_SECONDS = {
|
|
1950
|
+
anthropic: 300,
|
|
1951
|
+
openai: 300,
|
|
1952
|
+
ollama: 900
|
|
1953
|
+
};
|
|
1954
|
+
function timeoutSeconds(llm) {
|
|
1955
|
+
return llm.timeout_s ?? DEFAULT_TIMEOUT_SECONDS[llm.provider];
|
|
1956
|
+
}
|
|
1957
|
+
function withExtraBody(extra, base = fetch) {
|
|
1958
|
+
return (input, init) => {
|
|
1959
|
+
if (typeof init?.body !== "string") return base(input, init);
|
|
1960
|
+
let body;
|
|
1961
|
+
try {
|
|
1962
|
+
body = JSON.parse(init.body);
|
|
1963
|
+
} catch {
|
|
1964
|
+
return base(input, init);
|
|
1965
|
+
}
|
|
1966
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) return base(input, init);
|
|
1967
|
+
return base(input, { ...init, body: JSON.stringify({ ...extra, ...body }) });
|
|
1968
|
+
};
|
|
1969
|
+
}
|
|
1970
|
+
var MissingApiKeyError = class extends Error {
|
|
1971
|
+
constructor(variable, provider) {
|
|
1972
|
+
super(
|
|
1973
|
+
`Missing API key: environment variable ${variable} is not set (required for provider "${provider}"). Export it before running, e.g. \`export ${variable}=...\`, or change llm.provider / llm.api_key_env in .blastproof/config.yaml.`
|
|
1974
|
+
);
|
|
1975
|
+
this.name = "MissingApiKeyError";
|
|
1976
|
+
}
|
|
1977
|
+
};
|
|
1978
|
+
function createModel(llm, env = process.env) {
|
|
1979
|
+
const modelId = llm.model ?? DEFAULT_MODELS[llm.provider];
|
|
1980
|
+
switch (llm.provider) {
|
|
1981
|
+
case "anthropic":
|
|
1982
|
+
case "openai": {
|
|
1983
|
+
const keyEnv = llm.api_key_env ?? DEFAULT_API_KEY_ENVS[llm.provider];
|
|
1984
|
+
const apiKey = env[keyEnv];
|
|
1985
|
+
if (!apiKey) {
|
|
1986
|
+
throw new MissingApiKeyError(keyEnv, llm.provider);
|
|
1987
|
+
}
|
|
1988
|
+
const baseURL = llm.base_url ? { baseURL: llm.base_url } : {};
|
|
1989
|
+
const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
|
|
1990
|
+
const model = llm.provider === "anthropic" ? (
|
|
1991
|
+
// A configured endpoint applies to whichever provider is selected —
|
|
1992
|
+
// dropping it here routed corporate-proxy configs to the public API
|
|
1993
|
+
// with no error (design D2).
|
|
1994
|
+
createAnthropic({ apiKey, ...baseURL })(modelId)
|
|
1995
|
+
) : (
|
|
1996
|
+
// `.chat` = Chat Completions: works with official OpenAI and any
|
|
1997
|
+
// OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM) via base_url.
|
|
1998
|
+
createOpenAI({ apiKey, ...baseURL, ...extra }).chat(modelId)
|
|
1999
|
+
);
|
|
2000
|
+
return { model, provider: llm.provider, modelId };
|
|
2001
|
+
}
|
|
2002
|
+
case "ollama": {
|
|
2003
|
+
const baseURL = llm.base_url ?? DEFAULT_OLLAMA_BASE_URL;
|
|
2004
|
+
const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
|
|
2005
|
+
const model = createOpenAI({ baseURL, apiKey: "ollama", ...extra }).chat(modelId);
|
|
2006
|
+
return { model, provider: "ollama", modelId };
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
// src/llm/decision.ts
|
|
2012
|
+
var DECISIONS_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
|
|
2013
|
+
var MAX_DECISION_CHARS = 6e4;
|
|
2014
|
+
var RETRY_DELAYS_MS = [2e3, 4e3];
|
|
2015
|
+
var sleep = (ms, signal) => new Promise((resolve2, reject) => {
|
|
2016
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
2017
|
+
const timer = setTimeout(resolve2, ms);
|
|
2018
|
+
signal?.addEventListener(
|
|
2019
|
+
"abort",
|
|
2020
|
+
() => {
|
|
2021
|
+
clearTimeout(timer);
|
|
2022
|
+
reject(signal.reason);
|
|
2023
|
+
},
|
|
2024
|
+
{ once: true }
|
|
2025
|
+
);
|
|
2026
|
+
});
|
|
2027
|
+
function retryable(status) {
|
|
2028
|
+
return status === 408 || status === 409 || status === 429 || status >= 500;
|
|
2029
|
+
}
|
|
2030
|
+
function readAnswer(text) {
|
|
2031
|
+
let body;
|
|
2032
|
+
try {
|
|
2033
|
+
body = JSON.parse(text);
|
|
2034
|
+
} catch {
|
|
2035
|
+
return { p: void 0 };
|
|
2036
|
+
}
|
|
2037
|
+
const root = body ?? {};
|
|
2038
|
+
const raw = root.answers?.pass?.noul;
|
|
2039
|
+
const p = typeof raw === "number" && raw >= 0 && raw <= 1 ? raw : void 0;
|
|
2040
|
+
const input = root.usage?.input_tokens;
|
|
2041
|
+
const output = root.usage?.output_tokens;
|
|
2042
|
+
const totalTokens = typeof input === "number" ? input + (typeof output === "number" ? output : 0) : void 0;
|
|
2043
|
+
return { p, usage: { totalTokens } };
|
|
2044
|
+
}
|
|
2045
|
+
function createDecisionClient(options) {
|
|
2046
|
+
const doFetch = options.fetch ?? fetch;
|
|
2047
|
+
const wait = options.sleep ?? sleep;
|
|
2048
|
+
const url = options.endpoint ?? DECISIONS_ENDPOINT;
|
|
2049
|
+
return async (question, state, signal) => {
|
|
2050
|
+
const requestBodyValues = {
|
|
2051
|
+
model: options.model,
|
|
2052
|
+
state,
|
|
2053
|
+
questions: { pass: { type: "noul", ...question } }
|
|
2054
|
+
};
|
|
2055
|
+
for (let attempt = 0; ; attempt++) {
|
|
2056
|
+
let response;
|
|
2057
|
+
try {
|
|
2058
|
+
response = await doFetch(url, {
|
|
2059
|
+
method: "POST",
|
|
2060
|
+
headers: { Authorization: `Bearer ${options.apiKey}`, "Content-Type": "application/json" },
|
|
2061
|
+
body: JSON.stringify(requestBodyValues),
|
|
2062
|
+
signal
|
|
2063
|
+
});
|
|
2064
|
+
} catch (error) {
|
|
2065
|
+
if (signal?.aborted) throw error;
|
|
2066
|
+
if (attempt < RETRY_DELAYS_MS.length) {
|
|
2067
|
+
await wait(RETRY_DELAYS_MS[attempt], signal);
|
|
2068
|
+
continue;
|
|
2069
|
+
}
|
|
2070
|
+
throw new APICallError({
|
|
2071
|
+
message: `first judge ${options.model}: ${error instanceof Error ? error.message : String(error)}`,
|
|
2072
|
+
url,
|
|
2073
|
+
requestBodyValues,
|
|
2074
|
+
cause: error
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
const text = await response.text();
|
|
2078
|
+
if (response.ok) return readAnswer(text);
|
|
2079
|
+
if (retryable(response.status) && attempt < RETRY_DELAYS_MS.length) {
|
|
2080
|
+
await wait(RETRY_DELAYS_MS[attempt], signal);
|
|
2081
|
+
continue;
|
|
2082
|
+
}
|
|
2083
|
+
throw new APICallError({
|
|
2084
|
+
message: `first judge ${options.model}`,
|
|
2085
|
+
url,
|
|
2086
|
+
requestBodyValues,
|
|
2087
|
+
statusCode: response.status,
|
|
2088
|
+
responseBody: text
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
2091
|
+
};
|
|
2092
|
+
}
|
|
2093
|
+
var MissingFirstJudgeKeyError = class extends MissingApiKeyError {
|
|
2094
|
+
constructor(variable, model) {
|
|
2095
|
+
super(variable, model);
|
|
2096
|
+
this.message = `Missing API key: environment variable ${variable} is not set (required for the first judge "${model}"). Export it before running, e.g. \`export ${variable}=...\`, or remove first_judge from .blastproof/config.yaml (and unset BLASTPROOF_FIRST_JUDGE_MODEL).`;
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
2099
|
+
var FirstJudgeLog = class {
|
|
2100
|
+
constructor(model, threshold, file) {
|
|
2101
|
+
this.model = model;
|
|
2102
|
+
this.threshold = threshold;
|
|
2103
|
+
this.file = file;
|
|
2104
|
+
}
|
|
2105
|
+
model;
|
|
2106
|
+
threshold;
|
|
2107
|
+
file;
|
|
2108
|
+
passed = 0;
|
|
2109
|
+
failedByLabelCheck = 0;
|
|
2110
|
+
toLlm = 0;
|
|
2111
|
+
dirReady = false;
|
|
2112
|
+
record(test, entry) {
|
|
2113
|
+
if (entry.outcome === "passed") this.passed++;
|
|
2114
|
+
else if (entry.outcome === "label-check") this.failedByLabelCheck++;
|
|
2115
|
+
else this.toLlm++;
|
|
2116
|
+
if (entry.outcome === "too-large" || !this.file) return;
|
|
2117
|
+
if (!this.dirReady) {
|
|
2118
|
+
mkdirSync(path5.dirname(this.file), { recursive: true });
|
|
2119
|
+
this.dirReady = true;
|
|
2120
|
+
}
|
|
2121
|
+
const line = {
|
|
2122
|
+
test,
|
|
2123
|
+
step: entry.step,
|
|
2124
|
+
claim: entry.claim,
|
|
2125
|
+
model: this.model,
|
|
2126
|
+
p: entry.p ?? null,
|
|
2127
|
+
threshold: this.threshold,
|
|
2128
|
+
outcome: entry.outcome,
|
|
2129
|
+
snapshot: entry.snapshot
|
|
2130
|
+
};
|
|
2131
|
+
appendFileSync(this.file, `${JSON.stringify(line)}
|
|
2132
|
+
`, "utf8");
|
|
2133
|
+
}
|
|
2134
|
+
summaryLine() {
|
|
2135
|
+
const labelCheck = this.failedByLabelCheck > 0 ? `, ${this.failedByLabelCheck} failed by the label check` : "";
|
|
2136
|
+
return `First judge (experimental, ${this.model} at ${this.threshold}): ${this.passed} passed${labelCheck}, ${this.toLlm} to the LLM judge`;
|
|
2137
|
+
}
|
|
2138
|
+
};
|
|
2139
|
+
function firstJudgeLogPath(sessionDir) {
|
|
2140
|
+
return path5.join(sessionDir, "first-judge.jsonl");
|
|
2141
|
+
}
|
|
2142
|
+
function createFirstJudgeClient(config, env = process.env, fetchImpl) {
|
|
2143
|
+
const apiKey = env[config.api_key_env];
|
|
2144
|
+
if (!apiKey) throw new MissingFirstJudgeKeyError(config.api_key_env, config.model);
|
|
2145
|
+
return createDecisionClient({ model: config.model, apiKey, fetch: fetchImpl });
|
|
2146
|
+
}
|
|
2147
|
+
|
|
1863
2148
|
// src/llm/schemas.ts
|
|
1864
2149
|
import { z as z2 } from "zod";
|
|
1865
2150
|
function absentAsNull(schema) {
|
|
@@ -1945,7 +2230,7 @@ function withProviderDetail(error) {
|
|
|
1945
2230
|
}
|
|
1946
2231
|
function asProviderRefusal(error) {
|
|
1947
2232
|
const cause = RetryError.isInstance(error) ? error.lastError : error;
|
|
1948
|
-
if (!
|
|
2233
|
+
if (!APICallError2.isInstance(cause)) return error;
|
|
1949
2234
|
if (cause.statusCode !== void 0 && cause.statusCode < 400) return error;
|
|
1950
2235
|
withProviderDetail(cause);
|
|
1951
2236
|
return new ProviderRefusedError(cause.statusCode, cause.message);
|
|
@@ -1967,12 +2252,12 @@ function spentAndExplained(error, budget) {
|
|
|
1967
2252
|
`the answer reached the ${MAX_OUTPUT_TOKENS}-token output limit before its JSON was complete`
|
|
1968
2253
|
);
|
|
1969
2254
|
}
|
|
1970
|
-
async function
|
|
2255
|
+
async function counted(budget, call) {
|
|
1971
2256
|
budget.check();
|
|
1972
2257
|
const abort = callAbort(budget);
|
|
1973
2258
|
let result;
|
|
1974
2259
|
try {
|
|
1975
|
-
result = await
|
|
2260
|
+
result = await call(abort?.signal);
|
|
1976
2261
|
} catch (error) {
|
|
1977
2262
|
if (abort?.signal.aborted) {
|
|
1978
2263
|
if (abort.byDeadline) throw budget.deadlineReached();
|
|
@@ -1985,7 +2270,29 @@ async function countedGenerate(generate, budget, options) {
|
|
|
1985
2270
|
budget.record(result.usage);
|
|
1986
2271
|
return result;
|
|
1987
2272
|
}
|
|
1988
|
-
function
|
|
2273
|
+
function countedGenerate(generate, budget, options) {
|
|
2274
|
+
return counted(budget, (abortSignal) => generate({ ...options, maxOutputTokens: MAX_OUTPUT_TOKENS, abortSignal }));
|
|
2275
|
+
}
|
|
2276
|
+
async function firstJudgment(firstJudge, budget, judged, label) {
|
|
2277
|
+
const question = firstJudgeQuestion();
|
|
2278
|
+
const entry = { step: judged.step, claim: judged.claim, snapshot: judged.snapshot };
|
|
2279
|
+
if (judged.prompt.length + question.instructions.length > MAX_DECISION_CHARS) {
|
|
2280
|
+
firstJudge.record({ ...entry, p: void 0, outcome: "too-large" });
|
|
2281
|
+
return void 0;
|
|
2282
|
+
}
|
|
2283
|
+
const { p } = await counted(budget, (signal) => firstJudge.decide(question, judged.prompt, signal));
|
|
2284
|
+
if (p === void 0 || p < firstJudge.threshold) {
|
|
2285
|
+
firstJudge.record({ ...entry, p, outcome: "to-llm" });
|
|
2286
|
+
return void 0;
|
|
2287
|
+
}
|
|
2288
|
+
const judgment = label({
|
|
2289
|
+
pass: true,
|
|
2290
|
+
reason: `passed by the first judge, ${firstJudge.model}, at p(yes) ${p.toFixed(2)} (threshold ${firstJudge.threshold}); a decision model gives no reason`
|
|
2291
|
+
});
|
|
2292
|
+
firstJudge.record({ ...entry, p, outcome: judgment.pass ? "passed" : "label-check" });
|
|
2293
|
+
return judgment;
|
|
2294
|
+
}
|
|
2295
|
+
function createBrain(model, generate = generateObject, budget, firstJudge) {
|
|
1989
2296
|
return {
|
|
1990
2297
|
async nextAction(input) {
|
|
1991
2298
|
const result = await countedGenerate(generate, budget, {
|
|
@@ -2007,16 +2314,19 @@ function createBrain(model, generate = generateObject, budget) {
|
|
|
2007
2314
|
action: placeholdersAsLabels(entry.action),
|
|
2008
2315
|
result: placeholdersAsLabels(entry.result)
|
|
2009
2316
|
}));
|
|
2317
|
+
const judgedStep = placeholdersAsLabels(step);
|
|
2318
|
+
const claim = placeholdersAsLabels(expectation);
|
|
2319
|
+
const prompt = assertUserPrompt(judgedStep, claim, snapshot, asJudged);
|
|
2320
|
+
const label = (judgment) => secretMismatch(judgedStep, snapshot, asJudged, usedEarlier ?? [], judgment);
|
|
2321
|
+
if (firstJudge) {
|
|
2322
|
+
const decided = await firstJudgment(firstJudge, budget, { step: judgedStep, claim, snapshot, prompt }, label);
|
|
2323
|
+
if (decided) return decided;
|
|
2324
|
+
}
|
|
2010
2325
|
const result = await countedGenerate(generate, budget, {
|
|
2011
2326
|
model,
|
|
2012
2327
|
schema: assertJudgmentSchema,
|
|
2013
2328
|
system: assertSystemPrompt(),
|
|
2014
|
-
prompt
|
|
2015
|
-
placeholdersAsLabels(step),
|
|
2016
|
-
placeholdersAsLabels(expectation),
|
|
2017
|
-
snapshot,
|
|
2018
|
-
asJudged
|
|
2019
|
-
),
|
|
2329
|
+
prompt,
|
|
2020
2330
|
temperature: 0
|
|
2021
2331
|
});
|
|
2022
2332
|
const parsed = assertJudgmentSchema.safeParse(result.object);
|
|
@@ -2025,7 +2335,7 @@ function createBrain(model, generate = generateObject, budget) {
|
|
|
2025
2335
|
`Model returned an invalid assert judgment: ${parsed.error.issues[0]?.message ?? "unknown"}`
|
|
2026
2336
|
);
|
|
2027
2337
|
}
|
|
2028
|
-
return
|
|
2338
|
+
return label(parsed.data);
|
|
2029
2339
|
}
|
|
2030
2340
|
};
|
|
2031
2341
|
}
|
|
@@ -2068,92 +2378,17 @@ function createPlanner(model, generate = generateObject, budget) {
|
|
|
2068
2378
|
};
|
|
2069
2379
|
}
|
|
2070
2380
|
|
|
2071
|
-
// src/llm/provider.ts
|
|
2072
|
-
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
2073
|
-
import { createOpenAI } from "@ai-sdk/openai";
|
|
2074
|
-
var DEFAULT_MODELS = {
|
|
2075
|
-
anthropic: "claude-haiku-4-5",
|
|
2076
|
-
openai: "gpt-6-luna",
|
|
2077
|
-
ollama: "gpt-oss:20b"
|
|
2078
|
-
};
|
|
2079
|
-
var DEFAULT_API_KEY_ENVS = {
|
|
2080
|
-
anthropic: "ANTHROPIC_API_KEY",
|
|
2081
|
-
openai: "OPENAI_API_KEY"
|
|
2082
|
-
};
|
|
2083
|
-
var DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434/v1";
|
|
2084
|
-
var DEFAULT_TIMEOUT_SECONDS = {
|
|
2085
|
-
anthropic: 300,
|
|
2086
|
-
openai: 300,
|
|
2087
|
-
ollama: 900
|
|
2088
|
-
};
|
|
2089
|
-
function timeoutSeconds(llm) {
|
|
2090
|
-
return llm.timeout_s ?? DEFAULT_TIMEOUT_SECONDS[llm.provider];
|
|
2091
|
-
}
|
|
2092
|
-
function withExtraBody(extra, base = fetch) {
|
|
2093
|
-
return (input, init) => {
|
|
2094
|
-
if (typeof init?.body !== "string") return base(input, init);
|
|
2095
|
-
let body;
|
|
2096
|
-
try {
|
|
2097
|
-
body = JSON.parse(init.body);
|
|
2098
|
-
} catch {
|
|
2099
|
-
return base(input, init);
|
|
2100
|
-
}
|
|
2101
|
-
if (body === null || typeof body !== "object" || Array.isArray(body)) return base(input, init);
|
|
2102
|
-
return base(input, { ...init, body: JSON.stringify({ ...extra, ...body }) });
|
|
2103
|
-
};
|
|
2104
|
-
}
|
|
2105
|
-
var MissingApiKeyError = class extends Error {
|
|
2106
|
-
constructor(variable, provider) {
|
|
2107
|
-
super(
|
|
2108
|
-
`Missing API key: environment variable ${variable} is not set (required for provider "${provider}"). Export it before running, e.g. \`export ${variable}=...\`, or change llm.provider / llm.api_key_env in .blastproof/config.yaml.`
|
|
2109
|
-
);
|
|
2110
|
-
this.name = "MissingApiKeyError";
|
|
2111
|
-
}
|
|
2112
|
-
};
|
|
2113
|
-
function createModel(llm, env = process.env) {
|
|
2114
|
-
const modelId = llm.model ?? DEFAULT_MODELS[llm.provider];
|
|
2115
|
-
switch (llm.provider) {
|
|
2116
|
-
case "anthropic":
|
|
2117
|
-
case "openai": {
|
|
2118
|
-
const keyEnv = llm.api_key_env ?? DEFAULT_API_KEY_ENVS[llm.provider];
|
|
2119
|
-
const apiKey = env[keyEnv];
|
|
2120
|
-
if (!apiKey) {
|
|
2121
|
-
throw new MissingApiKeyError(keyEnv, llm.provider);
|
|
2122
|
-
}
|
|
2123
|
-
const baseURL = llm.base_url ? { baseURL: llm.base_url } : {};
|
|
2124
|
-
const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
|
|
2125
|
-
const model = llm.provider === "anthropic" ? (
|
|
2126
|
-
// A configured endpoint applies to whichever provider is selected —
|
|
2127
|
-
// dropping it here routed corporate-proxy configs to the public API
|
|
2128
|
-
// with no error (design D2).
|
|
2129
|
-
createAnthropic({ apiKey, ...baseURL })(modelId)
|
|
2130
|
-
) : (
|
|
2131
|
-
// `.chat` = Chat Completions: works with official OpenAI and any
|
|
2132
|
-
// OpenAI-compatible endpoint (OpenRouter, LiteLLM, vLLM) via base_url.
|
|
2133
|
-
createOpenAI({ apiKey, ...baseURL, ...extra }).chat(modelId)
|
|
2134
|
-
);
|
|
2135
|
-
return { model, provider: llm.provider, modelId };
|
|
2136
|
-
}
|
|
2137
|
-
case "ollama": {
|
|
2138
|
-
const baseURL = llm.base_url ?? DEFAULT_OLLAMA_BASE_URL;
|
|
2139
|
-
const extra = llm.extra_body ? { fetch: withExtraBody(llm.extra_body) } : {};
|
|
2140
|
-
const model = createOpenAI({ baseURL, apiKey: "ollama", ...extra }).chat(modelId);
|
|
2141
|
-
return { model, provider: "ollama", modelId };
|
|
2142
|
-
}
|
|
2143
|
-
}
|
|
2144
|
-
}
|
|
2145
|
-
|
|
2146
2381
|
// src/planner.ts
|
|
2147
2382
|
import { mkdir as mkdir4, writeFile as writeFile3 } from "fs/promises";
|
|
2148
|
-
import
|
|
2383
|
+
import path7 from "path";
|
|
2149
2384
|
import { stringify } from "yaml";
|
|
2150
2385
|
|
|
2151
2386
|
// src/runner/testfile.ts
|
|
2152
2387
|
import { readFile as readFile3, readdir } from "fs/promises";
|
|
2153
|
-
import
|
|
2388
|
+
import path6 from "path";
|
|
2154
2389
|
import { parse as parseYaml2 } from "yaml";
|
|
2155
2390
|
import { z as z3 } from "zod";
|
|
2156
|
-
var TESTS_RELATIVE_DIR =
|
|
2391
|
+
var TESTS_RELATIVE_DIR = path6.join(".blastproof", "tests");
|
|
2157
2392
|
var prioritySchema = z3.enum(["P0", "P1", "P2"]);
|
|
2158
2393
|
var testFileSchema = z3.object({
|
|
2159
2394
|
summary: z3.string().min(1),
|
|
@@ -2162,7 +2397,8 @@ var testFileSchema = z3.object({
|
|
|
2162
2397
|
tags: z3.array(z3.string()).default([]),
|
|
2163
2398
|
setup: z3.array(z3.string().min(1)).optional(),
|
|
2164
2399
|
routes: z3.array(z3.string()).default([]),
|
|
2165
|
-
auth: z3.boolean().default(true)
|
|
2400
|
+
auth: z3.boolean().default(true),
|
|
2401
|
+
device: deviceSchema.optional()
|
|
2166
2402
|
});
|
|
2167
2403
|
var TestFileError = class extends Error {
|
|
2168
2404
|
constructor(message) {
|
|
@@ -2200,7 +2436,7 @@ async function discoverTestFiles(root) {
|
|
|
2200
2436
|
async function walk(dir) {
|
|
2201
2437
|
const entries = await readdir(dir, { withFileTypes: true });
|
|
2202
2438
|
for (const entry of entries) {
|
|
2203
|
-
const full =
|
|
2439
|
+
const full = path6.join(dir, entry.name);
|
|
2204
2440
|
if (entry.isDirectory()) {
|
|
2205
2441
|
await walk(full);
|
|
2206
2442
|
} else if (/\.ya?ml$/i.test(entry.name)) {
|
|
@@ -2287,8 +2523,8 @@ async function generateForRoute(page, options) {
|
|
|
2287
2523
|
};
|
|
2288
2524
|
}
|
|
2289
2525
|
async function writeDraft(cwd, draft, meta) {
|
|
2290
|
-
const dir =
|
|
2291
|
-
const file =
|
|
2526
|
+
const dir = path7.join(cwd, TESTS_RELATIVE_DIR);
|
|
2527
|
+
const file = path7.join(dir, `${routeToSlug(meta.route)}.yaml`);
|
|
2292
2528
|
try {
|
|
2293
2529
|
await mkdir4(dir, { recursive: true });
|
|
2294
2530
|
await writeFile3(file, renderTestYaml(draft, meta), { flag: "wx" });
|
|
@@ -2296,11 +2532,11 @@ async function writeDraft(cwd, draft, meta) {
|
|
|
2296
2532
|
const err = error;
|
|
2297
2533
|
if (err.code === "EEXIST" && err.syscall !== "mkdir") {
|
|
2298
2534
|
throw new PlannerError(
|
|
2299
|
-
`Refusing to overwrite ${
|
|
2535
|
+
`Refusing to overwrite ${path7.relative(cwd, file)} (route ${meta.route}). Delete or rename it to regenerate.`
|
|
2300
2536
|
);
|
|
2301
2537
|
}
|
|
2302
2538
|
throw new PlannerError(
|
|
2303
|
-
`Cannot write draft to ${file}: ${fsReason(error)}. Check that ${
|
|
2539
|
+
`Cannot write draft to ${file}: ${fsReason(error)}. Check that ${path7.dirname(file)} is a directory you can write to, not a file.`
|
|
2304
2540
|
);
|
|
2305
2541
|
}
|
|
2306
2542
|
return file;
|
|
@@ -2463,11 +2699,11 @@ function formatSpendLine(spend) {
|
|
|
2463
2699
|
}
|
|
2464
2700
|
|
|
2465
2701
|
// src/commands/run.ts
|
|
2466
|
-
import
|
|
2702
|
+
import path10 from "path";
|
|
2467
2703
|
|
|
2468
2704
|
// src/report/html.ts
|
|
2469
2705
|
import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
|
|
2470
|
-
import
|
|
2706
|
+
import path8 from "path";
|
|
2471
2707
|
var ESCAPES = {
|
|
2472
2708
|
"&": "&",
|
|
2473
2709
|
"<": "<",
|
|
@@ -2543,7 +2779,7 @@ function renderSteps(steps) {
|
|
|
2543
2779
|
</ol>`;
|
|
2544
2780
|
}
|
|
2545
2781
|
function withheldScreenshot(file, reportDir) {
|
|
2546
|
-
const href =
|
|
2782
|
+
const href = path8.relative(reportDir, file).split(path8.sep).join("/");
|
|
2547
2783
|
return ` <p class="note">Screenshot withheld: this run handled secrets ({{env.*}}), and a screenshot cannot be masked. <a href="${escapeHtml(href)}">${escapeHtml(href)}</a></p>`;
|
|
2548
2784
|
}
|
|
2549
2785
|
async function renderTest(result, screenshots, cwd) {
|
|
@@ -2551,10 +2787,11 @@ async function renderTest(result, screenshots, cwd) {
|
|
|
2551
2787
|
const notRun = result.status === "not-run";
|
|
2552
2788
|
const tagClass = failed ? "fail" : notRun ? "skip" : "pass";
|
|
2553
2789
|
const label = failed ? "FAIL" : notRun ? "NOT RUN" : "PASS";
|
|
2554
|
-
const file = cwd ?
|
|
2790
|
+
const file = cwd ? path8.relative(cwd, result.file) : result.file;
|
|
2791
|
+
const device = result.device ? ` \xB7 ${escapeHtml(result.device)}` : "";
|
|
2555
2792
|
const parts = [
|
|
2556
2793
|
` <details${failed || notRun ? " open" : ""}>`,
|
|
2557
|
-
` <summary><span class="tag ${tagClass}">${label}</span> ${escapeHtml(result.summary)} <span class="note">${escapeHtml(result.priority)} \xB7 ${escapeHtml(file)}</span></summary>`
|
|
2794
|
+
` <summary><span class="tag ${tagClass}">${label}</span> ${escapeHtml(result.summary)} <span class="note">${escapeHtml(result.priority)}${device} \xB7 ${escapeHtml(file)}</span></summary>`
|
|
2558
2795
|
];
|
|
2559
2796
|
if (failed) {
|
|
2560
2797
|
if (result.failedStep) {
|
|
@@ -2591,14 +2828,14 @@ async function renderHtml(results, skipped, meta) {
|
|
|
2591
2828
|
|
|
2592
2829
|
`;
|
|
2593
2830
|
const rows = results.map((r) => {
|
|
2594
|
-
const file = meta.cwd ?
|
|
2831
|
+
const file = meta.cwd ? path8.relative(meta.cwd, r.file) : r.file;
|
|
2595
2832
|
const tagClass = r.status === "failed" ? "fail" : r.status === "not-run" ? "skip" : "pass";
|
|
2596
2833
|
const label = r.status === "failed" ? "FAIL" : r.status === "not-run" ? "NOT RUN" : "PASS";
|
|
2597
2834
|
const time = r.status === "not-run" ? "\u2014" : seconds(r.durationMs);
|
|
2598
2835
|
return ` <tr><td><span class="tag ${tagClass}">${label}</span></td><td>${escapeHtml(r.priority)}</td><td>${escapeHtml(r.summary)}</td><td>${escapeHtml(file)}</td><td class="num">${time}</td></tr>`;
|
|
2599
2836
|
}).join("\n");
|
|
2600
2837
|
const skippedRows = skipped.map((s) => {
|
|
2601
|
-
const file = meta.cwd ?
|
|
2838
|
+
const file = meta.cwd ? path8.relative(meta.cwd, s.path) : s.path;
|
|
2602
2839
|
return ` <tr><td><span class="tag skip">SKIP</span></td><td>\u2014</td><td>${escapeHtml(s.summary)}</td><td>${escapeHtml(file)}</td><td class="num">\u2014</td></tr>`;
|
|
2603
2840
|
}).join("\n");
|
|
2604
2841
|
return `<!doctype html>
|
|
@@ -2637,7 +2874,7 @@ ${detail}
|
|
|
2637
2874
|
}
|
|
2638
2875
|
async function writeHtml(file, html) {
|
|
2639
2876
|
try {
|
|
2640
|
-
await mkdir5(
|
|
2877
|
+
await mkdir5(path8.dirname(file), { recursive: true });
|
|
2641
2878
|
await writeFile4(file, html, "utf8");
|
|
2642
2879
|
return file;
|
|
2643
2880
|
} catch (error) {
|
|
@@ -2649,7 +2886,7 @@ async function writeHtml(file, html) {
|
|
|
2649
2886
|
|
|
2650
2887
|
// src/report/junit.ts
|
|
2651
2888
|
import { mkdir as mkdir6, writeFile as writeFile5 } from "fs/promises";
|
|
2652
|
-
import
|
|
2889
|
+
import path9 from "path";
|
|
2653
2890
|
var ESCAPES2 = {
|
|
2654
2891
|
"&": "&",
|
|
2655
2892
|
"<": "<",
|
|
@@ -2664,7 +2901,7 @@ function seconds2(ms) {
|
|
|
2664
2901
|
return (ms / 1e3).toFixed(3);
|
|
2665
2902
|
}
|
|
2666
2903
|
function renderJUnit(results, skipped, meta) {
|
|
2667
|
-
const relative = (file) => meta.cwd ?
|
|
2904
|
+
const relative = (file) => meta.cwd ? path9.relative(meta.cwd, file) : file;
|
|
2668
2905
|
const failures = results.filter((result) => result.status === "failed").length;
|
|
2669
2906
|
const notRun = results.filter((result) => result.status === "not-run");
|
|
2670
2907
|
const lines = [
|
|
@@ -2719,7 +2956,7 @@ ${reason}` : reason;
|
|
|
2719
2956
|
}
|
|
2720
2957
|
async function writeJUnit(file, xml) {
|
|
2721
2958
|
try {
|
|
2722
|
-
await mkdir6(
|
|
2959
|
+
await mkdir6(path9.dirname(file), { recursive: true });
|
|
2723
2960
|
await writeFile5(file, xml, "utf8");
|
|
2724
2961
|
return file;
|
|
2725
2962
|
} catch (error) {
|
|
@@ -2907,8 +3144,12 @@ ${notRun.length} test(s) not run (run stopped: ${notRun[0].reason}):`);
|
|
|
2907
3144
|
for (const r of notRun) console.log(` - ${r.summary} (${r.file})`);
|
|
2908
3145
|
}
|
|
2909
3146
|
}
|
|
2910
|
-
|
|
2911
|
-
const
|
|
3147
|
+
function deviceTag(test, config) {
|
|
3148
|
+
const device = test.device ?? config.browser.device;
|
|
3149
|
+
return device ? ` [${device}]` : "";
|
|
3150
|
+
}
|
|
3151
|
+
async function runOne(browser, test, config, sessionDir, session, runMask, budget, write, firstJudge) {
|
|
3152
|
+
const brain = createBrain(createModel(config.llm).model, void 0, budget, firstJudge);
|
|
2912
3153
|
let resolved;
|
|
2913
3154
|
const mask = runMask;
|
|
2914
3155
|
try {
|
|
@@ -2928,11 +3169,12 @@ async function runOne(browser, test, config, sessionDir, session, runMask, budge
|
|
|
2928
3169
|
}
|
|
2929
3170
|
throw error;
|
|
2930
3171
|
}
|
|
2931
|
-
const
|
|
3172
|
+
const device = test.device ?? config.browser.device;
|
|
3173
|
+
const context = await browser.newContext(contextOptions(test.auth ? session : void 0, device));
|
|
2932
3174
|
try {
|
|
2933
3175
|
const page = await context.newPage();
|
|
2934
3176
|
page.setDefaultTimeout(config.browser.timeout_ms);
|
|
2935
|
-
|
|
3177
|
+
const result = await executeTest(page, resolved, {
|
|
2936
3178
|
brain,
|
|
2937
3179
|
sessionDir,
|
|
2938
3180
|
baseUrl: config.base_url,
|
|
@@ -2944,6 +3186,7 @@ async function runOne(browser, test, config, sessionDir, session, runMask, budge
|
|
|
2944
3186
|
mask: (text) => mask.mask(text),
|
|
2945
3187
|
onEvent: (event) => printEvent(event, write)
|
|
2946
3188
|
});
|
|
3189
|
+
return device ? { ...result, device } : result;
|
|
2947
3190
|
} finally {
|
|
2948
3191
|
await context.close();
|
|
2949
3192
|
}
|
|
@@ -2964,7 +3207,7 @@ function printImpactReport(impact, selection, cwd) {
|
|
|
2964
3207
|
if (selection.unroutedSkipped.length > 0) {
|
|
2965
3208
|
console.log("Unrouted tests (skipped):");
|
|
2966
3209
|
for (const test of selection.unroutedSkipped) {
|
|
2967
|
-
console.log(` ${test.summary} (${
|
|
3210
|
+
console.log(` ${test.summary} (${path10.relative(cwd, test.path)})`);
|
|
2968
3211
|
}
|
|
2969
3212
|
}
|
|
2970
3213
|
if (selection.uncoveredRoutes.length > 0) {
|
|
@@ -2980,16 +3223,17 @@ function reportNearMissedSecrets(variables) {
|
|
|
2980
3223
|
);
|
|
2981
3224
|
}
|
|
2982
3225
|
}
|
|
2983
|
-
async function finalize(results, skipped, options, sessionDir, secretsHeld, nearMissedSecrets, durationMs, impact, incomplete, spend) {
|
|
3226
|
+
async function finalize(results, skipped, options, sessionDir, secretsHeld, nearMissedSecrets, durationMs, impact, incomplete, spend, firstJudgeLog) {
|
|
2984
3227
|
if (results.length > 0) printSummary(results);
|
|
2985
3228
|
reportNearMissedSecrets(nearMissedSecrets);
|
|
2986
3229
|
if (spend) console.log(formatSpendLine(spend));
|
|
3230
|
+
if (firstJudgeLog) console.log(firstJudgeLog.summaryLine());
|
|
2987
3231
|
const score = scoreOf(results, incomplete !== void 0);
|
|
2988
3232
|
console.log(
|
|
2989
3233
|
incomplete ? formatIncompleteLine(score, incomplete.message) : formatScoreLine(computeScore(results), results, options.minScore)
|
|
2990
3234
|
);
|
|
2991
3235
|
if (options.junit) {
|
|
2992
|
-
const target = typeof options.junit === "string" ?
|
|
3236
|
+
const target = typeof options.junit === "string" ? path10.resolve(options.cwd, options.junit) : path10.join(sessionDir, "junit.xml");
|
|
2993
3237
|
const xml = renderJUnit(results, skipped, {
|
|
2994
3238
|
score,
|
|
2995
3239
|
durationMs,
|
|
@@ -2998,10 +3242,10 @@ async function finalize(results, skipped, options, sessionDir, secretsHeld, near
|
|
|
2998
3242
|
spend
|
|
2999
3243
|
});
|
|
3000
3244
|
await writeJUnit(target, xml);
|
|
3001
|
-
console.log(`JUnit report: ${
|
|
3245
|
+
console.log(`JUnit report: ${path10.relative(options.cwd, target)}`);
|
|
3002
3246
|
}
|
|
3003
3247
|
if (options.html) {
|
|
3004
|
-
const target = typeof options.html === "string" ?
|
|
3248
|
+
const target = typeof options.html === "string" ? path10.resolve(options.cwd, options.html) : path10.join(sessionDir, "report.html");
|
|
3005
3249
|
const html = await renderHtml(results, skipped, {
|
|
3006
3250
|
score,
|
|
3007
3251
|
durationMs,
|
|
@@ -3014,10 +3258,10 @@ async function finalize(results, skipped, options, sessionDir, secretsHeld, near
|
|
|
3014
3258
|
// withhold-a-screenshot-that-saw-a-secret, D1): the run's mask, not the
|
|
3015
3259
|
// failed test's own placeholders, because a login credential is echoed by
|
|
3016
3260
|
// the pages of every test that comes after it.
|
|
3017
|
-
screenshots: secretsHeld ? { withheldRelativeTo:
|
|
3261
|
+
screenshots: secretsHeld ? { withheldRelativeTo: path10.dirname(target) } : "embed"
|
|
3018
3262
|
});
|
|
3019
3263
|
await writeHtml(target, html);
|
|
3020
|
-
console.log(`HTML report: ${
|
|
3264
|
+
console.log(`HTML report: ${path10.relative(options.cwd, target)}`);
|
|
3021
3265
|
}
|
|
3022
3266
|
if (incomplete) return EXIT_FAILED;
|
|
3023
3267
|
if (reportUnclassified(options, impact)) return EXIT_FAILED;
|
|
@@ -3048,7 +3292,7 @@ function printRouteDrift(drift, cwd) {
|
|
|
3048
3292
|
"Route drift (test routes declared by no routes: mapping \u2014 contribute nothing to --impacted selection):"
|
|
3049
3293
|
);
|
|
3050
3294
|
for (const { test, routes } of drift.drifted) {
|
|
3051
|
-
console.error(` ${test.summary} (${
|
|
3295
|
+
console.error(` ${test.summary} (${path10.relative(cwd, test.path)}): ${routes.join(", ")}`);
|
|
3052
3296
|
}
|
|
3053
3297
|
console.error("Fix the route typo, or add the route to a routes: mapping in .blastproof/config.yaml.");
|
|
3054
3298
|
}
|
|
@@ -3057,7 +3301,7 @@ function printAuthoring(result, cwd) {
|
|
|
3057
3301
|
console.error("\nAuthoring (a step enters a value but names none):");
|
|
3058
3302
|
for (const { test, origin, index, step } of result.findings) {
|
|
3059
3303
|
const where = origin === "setup" ? `setup step ${index}` : `step ${index}`;
|
|
3060
|
-
console.error(` ${test.summary} (${
|
|
3304
|
+
console.error(` ${test.summary} (${path10.relative(cwd, test.path)}) ${where}:`);
|
|
3061
3305
|
console.error(` ${step}`);
|
|
3062
3306
|
console.error(` \u2192 ${suggestValueClause(step)}`);
|
|
3063
3307
|
}
|
|
@@ -3070,7 +3314,7 @@ function printDryRun(selected, config, cwd) {
|
|
|
3070
3314
|
console.log(`
|
|
3071
3315
|
Dry run: ${selected.length} test(s) selected, base_url=${config.base_url}`);
|
|
3072
3316
|
for (const test of selected) {
|
|
3073
|
-
console.log(` ${test.summary} [${test.priority}] (${
|
|
3317
|
+
console.log(` ${test.summary} [${test.priority}]${deviceTag(test, config)} (${path10.relative(cwd, test.path)})`);
|
|
3074
3318
|
}
|
|
3075
3319
|
const needsLogin = selected.some((test) => test.auth);
|
|
3076
3320
|
const authSteps = needsLogin ? config.auth?.steps ?? [] : [];
|
|
@@ -3078,7 +3322,10 @@ Dry run: ${selected.length} test(s) selected, base_url=${config.base_url}`);
|
|
|
3078
3322
|
const ceiling = estimateMaxModelCalls(
|
|
3079
3323
|
withAuth,
|
|
3080
3324
|
DEFAULT_MAX_ITERATIONS_PER_STEP,
|
|
3081
|
-
config.max_retries_per_step
|
|
3325
|
+
config.max_retries_per_step,
|
|
3326
|
+
// A judgment the first judge does not pass makes two calls (design
|
|
3327
|
+
// a-decision-model-judges-first, D8).
|
|
3328
|
+
config.first_judge ? 2 : 1
|
|
3082
3329
|
);
|
|
3083
3330
|
const authNote = authSteps.length > 0 ? ", including the login journey" : "";
|
|
3084
3331
|
console.log(
|
|
@@ -3120,7 +3367,7 @@ async function runCommand(options) {
|
|
|
3120
3367
|
impact = mapImpact(changedFiles, config.routes ?? {}, config.ignore ?? []);
|
|
3121
3368
|
printUncommitted(await getUncommittedFiles(options.cwd), changedFiles, config, base);
|
|
3122
3369
|
}
|
|
3123
|
-
const testsDir =
|
|
3370
|
+
const testsDir = path10.join(options.cwd, TESTS_RELATIVE_DIR);
|
|
3124
3371
|
let files;
|
|
3125
3372
|
try {
|
|
3126
3373
|
files = await discoverTestFiles(testsDir);
|
|
@@ -3136,8 +3383,8 @@ async function runCommand(options) {
|
|
|
3136
3383
|
} catch (error) {
|
|
3137
3384
|
if (error instanceof TestFileError) {
|
|
3138
3385
|
results.push({
|
|
3139
|
-
file:
|
|
3140
|
-
summary:
|
|
3386
|
+
file: path10.relative(options.cwd, file),
|
|
3387
|
+
summary: path10.basename(file),
|
|
3141
3388
|
priority: "P1",
|
|
3142
3389
|
tags: [],
|
|
3143
3390
|
status: "failed",
|
|
@@ -3179,7 +3426,7 @@ ${results.length} test file(s) could not be parsed:`);
|
|
|
3179
3426
|
}
|
|
3180
3427
|
return reportUnclassified(options, impact) ? EXIT_FAILED : EXIT_OK;
|
|
3181
3428
|
}
|
|
3182
|
-
const sessionDir =
|
|
3429
|
+
const sessionDir = path10.join(options.cwd, ".blastproof", "reports", sessionId());
|
|
3183
3430
|
const startedAt = Date.now();
|
|
3184
3431
|
if (selected.length === 0) {
|
|
3185
3432
|
console.log(
|
|
@@ -3187,8 +3434,10 @@ ${results.length} test file(s) could not be parsed:`);
|
|
|
3187
3434
|
);
|
|
3188
3435
|
return finalize(results, selection.unroutedSkipped, options, sessionDir, false, [], Date.now() - startedAt, impact);
|
|
3189
3436
|
}
|
|
3437
|
+
let decide;
|
|
3190
3438
|
try {
|
|
3191
3439
|
createModel(config.llm);
|
|
3440
|
+
if (config.first_judge) decide = createFirstJudgeClient(config.first_judge);
|
|
3192
3441
|
} catch (error) {
|
|
3193
3442
|
if (error instanceof MissingApiKeyError) {
|
|
3194
3443
|
console.error(`error: ${error.message}`);
|
|
@@ -3200,6 +3449,18 @@ ${results.length} test file(s) could not be parsed:`);
|
|
|
3200
3449
|
console.log(
|
|
3201
3450
|
`blastproof run: ${selected.length} test(s), provider=${provider} model=${modelId}, base_url=${config.base_url}`
|
|
3202
3451
|
);
|
|
3452
|
+
const firstJudgeLog = config.first_judge && decide ? new FirstJudgeLog(config.first_judge.model, config.first_judge.threshold, firstJudgeLogPath(sessionDir)) : void 0;
|
|
3453
|
+
const firstJudgeFor = (test) => firstJudgeLog && decide ? {
|
|
3454
|
+
model: firstJudgeLog.model,
|
|
3455
|
+
threshold: firstJudgeLog.threshold,
|
|
3456
|
+
decide,
|
|
3457
|
+
record: (entry) => firstJudgeLog.record(test, entry)
|
|
3458
|
+
} : void 0;
|
|
3459
|
+
if (firstJudgeLog) {
|
|
3460
|
+
console.log(
|
|
3461
|
+
`First judge (experimental): ${firstJudgeLog.model}, passing at p(yes) >= ${firstJudgeLog.threshold}; its decisions are kept in ${path10.relative(options.cwd, firstJudgeLogPath(sessionDir))}`
|
|
3462
|
+
);
|
|
3463
|
+
}
|
|
3203
3464
|
const runMask = buildRunMask(config, parsed);
|
|
3204
3465
|
const budget = options.budget ?? new RunBudget(resolveBudgetOptions(config, options));
|
|
3205
3466
|
const preflight = await runPreflight({ browser: true, model: true, baseUrl: true }, config);
|
|
@@ -3220,10 +3481,11 @@ ${results.length} test file(s) could not be parsed:`);
|
|
|
3220
3481
|
baseUrl: config.base_url,
|
|
3221
3482
|
allowedOrigins: config.allowed_origins,
|
|
3222
3483
|
browser,
|
|
3223
|
-
brain: createBrain(createModel(config.llm).model, void 0, budget),
|
|
3484
|
+
brain: createBrain(createModel(config.llm).model, void 0, budget, firstJudgeFor("(login)")),
|
|
3224
3485
|
maxRetries: config.max_retries_per_step,
|
|
3225
3486
|
timeoutMs: config.browser.timeout_ms,
|
|
3226
3487
|
maxSnapshotLines: config.browser.max_snapshot_lines,
|
|
3488
|
+
device: config.browser.device,
|
|
3227
3489
|
mask: runMask,
|
|
3228
3490
|
onEvent: printEvent
|
|
3229
3491
|
});
|
|
@@ -3248,13 +3510,23 @@ ${results.length} test file(s) could not be parsed:`);
|
|
|
3248
3510
|
if (stoppedBy) return { index, stopped: stoppedBy };
|
|
3249
3511
|
const lines = [];
|
|
3250
3512
|
const header = `
|
|
3251
|
-
> ${test.summary} [${test.priority}] (${
|
|
3513
|
+
> ${test.summary} [${test.priority}]${deviceTag(test, config)} (${path10.relative(options.cwd, test.path)})`;
|
|
3252
3514
|
const write = streaming ? console.log : (line) => lines.push(line);
|
|
3253
3515
|
if (streaming) console.log(header);
|
|
3254
3516
|
else lines.push(header);
|
|
3255
3517
|
try {
|
|
3256
3518
|
budget.check();
|
|
3257
|
-
const result = await runOne(
|
|
3519
|
+
const result = await runOne(
|
|
3520
|
+
browser,
|
|
3521
|
+
test,
|
|
3522
|
+
config,
|
|
3523
|
+
sessionDir,
|
|
3524
|
+
session,
|
|
3525
|
+
runMask,
|
|
3526
|
+
budget,
|
|
3527
|
+
write,
|
|
3528
|
+
firstJudgeFor(path10.relative(options.cwd, test.path))
|
|
3529
|
+
);
|
|
3258
3530
|
if (!streaming) for (const line of lines) console.log(line);
|
|
3259
3531
|
return { index, result };
|
|
3260
3532
|
} catch (error) {
|
|
@@ -3293,7 +3565,8 @@ ${results.length} test file(s) could not be parsed:`);
|
|
|
3293
3565
|
// phases deliberately, so reporting at the point of use rather than the
|
|
3294
3566
|
// point of ownership would print the running total twice for a single
|
|
3295
3567
|
// allowance, the second line silently including the first.
|
|
3296
|
-
options.budget === void 0 ? budget.spend() : void 0
|
|
3568
|
+
options.budget === void 0 ? budget.spend() : void 0,
|
|
3569
|
+
firstJudgeLog
|
|
3297
3570
|
);
|
|
3298
3571
|
}
|
|
3299
3572
|
|
|
@@ -3308,7 +3581,7 @@ function printAuthEvent(event) {
|
|
|
3308
3581
|
}
|
|
3309
3582
|
}
|
|
3310
3583
|
async function loadSuite(cwd) {
|
|
3311
|
-
const testsDir =
|
|
3584
|
+
const testsDir = path11.join(cwd, TESTS_RELATIVE_DIR);
|
|
3312
3585
|
let files;
|
|
3313
3586
|
try {
|
|
3314
3587
|
files = await discoverTestFiles(testsDir);
|
|
@@ -3438,6 +3711,7 @@ async function planCommand(options) {
|
|
|
3438
3711
|
maxRetries: config.max_retries_per_step,
|
|
3439
3712
|
timeoutMs: config.browser.timeout_ms,
|
|
3440
3713
|
maxSnapshotLines: config.browser.max_snapshot_lines,
|
|
3714
|
+
device: config.browser.device,
|
|
3441
3715
|
mask,
|
|
3442
3716
|
onEvent: printAuthEvent
|
|
3443
3717
|
});
|
|
@@ -3456,7 +3730,7 @@ async function planCommand(options) {
|
|
|
3456
3730
|
console.log(`
|
|
3457
3731
|
> ${route}`);
|
|
3458
3732
|
let draft;
|
|
3459
|
-
const context = await browser.newContext(contextOptions(session));
|
|
3733
|
+
const context = await browser.newContext(contextOptions(session, config.browser.device));
|
|
3460
3734
|
try {
|
|
3461
3735
|
const page = await context.newPage();
|
|
3462
3736
|
page.setDefaultTimeout(config.browser.timeout_ms);
|
|
@@ -3490,8 +3764,8 @@ async function planCommand(options) {
|
|
|
3490
3764
|
if (options.write) {
|
|
3491
3765
|
try {
|
|
3492
3766
|
const file = await writeDraft(options.cwd, draft, { route, base });
|
|
3493
|
-
written.push(
|
|
3494
|
-
console.log(` wrote ${
|
|
3767
|
+
written.push(path11.relative(options.cwd, file));
|
|
3768
|
+
console.log(` wrote ${path11.relative(options.cwd, file)}`);
|
|
3495
3769
|
} catch (error) {
|
|
3496
3770
|
generated.pop();
|
|
3497
3771
|
const reason = error instanceof Error ? error.message : String(error);
|
|
@@ -3618,7 +3892,7 @@ function parsePositiveNumber(flag) {
|
|
|
3618
3892
|
};
|
|
3619
3893
|
}
|
|
3620
3894
|
var program = new Command();
|
|
3621
|
-
program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.
|
|
3895
|
+
program.name("blastproof").description("Open-source AI testing agent: plain-English YAML tests executed agentically on a real browser.").version("0.28.0");
|
|
3622
3896
|
program.command("init").description("Scaffold .blastproof/ (config, tests, sample tests) in the current directory").action(async () => {
|
|
3623
3897
|
try {
|
|
3624
3898
|
const result = await initProject(process.cwd());
|