@nexface/evals 0.0.0-stage → 0.1.21-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLI.md +51 -0
- package/README.md +34 -2
- package/approved-task.mjs +32 -0
- package/cli.mjs +31 -0
- package/generated.mjs +72 -0
- package/judge.mjs +73 -0
- package/native-tools.mjs +149 -0
- package/package.json +52 -4
- package/playwright.cjs +1 -0
- package/playwright.d.mts +10 -0
- package/playwright.mjs +1 -0
- package/report-output.mjs +194 -0
- package/runner.mjs +153 -0
- package/session.mjs +89 -0
- package/site-run.mjs +127 -0
- package/spec-config.mjs +24 -0
- package/spec-reporter.mjs +63 -0
- package/spec-run.mjs +87 -0
- package/studio.html +613 -0
- package/studio.mjs +244 -0
- package/suite.mjs +112 -0
- package/task-fixture.mjs +314 -0
- package/task-session.mjs +97 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from "node:util";
|
|
2
|
+
|
|
3
|
+
export function redactText(value) {
|
|
4
|
+
const secrets = [
|
|
5
|
+
process.env.EVAL_PASSWORD,
|
|
6
|
+
process.env.NEXFACE_JUDGE_KEY,
|
|
7
|
+
process.env.NEXFACE_EVAL_KEY,
|
|
8
|
+
].filter(Boolean);
|
|
9
|
+
for (const secret of secrets) value = value.replaceAll(secret, "[redacted]");
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function gatewayReason(role, response) {
|
|
14
|
+
const status = role + " HTTP " + response.status;
|
|
15
|
+
const type = response.headers.get("content-type") || "";
|
|
16
|
+
if (!/json|text\/plain/i.test(type)) return status;
|
|
17
|
+
try {
|
|
18
|
+
const body = await response.text();
|
|
19
|
+
const data = /json/i.test(type) ? JSON.parse(body) : body;
|
|
20
|
+
const message = typeof data === "string" ? data : (data?.error?.message ?? data?.message);
|
|
21
|
+
if (typeof message !== "string" || !message.trim()) return status;
|
|
22
|
+
const clean = redactText(stripVTControlCharacters(message))
|
|
23
|
+
.replace(/Bearer\s+[^\s,;]+/gi, "Bearer [redacted]")
|
|
24
|
+
.replace(/\s+/g, " ")
|
|
25
|
+
.trim();
|
|
26
|
+
return status + " — " + clean.slice(0, 300);
|
|
27
|
+
} catch {
|
|
28
|
+
return status;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function safeJson(value) {
|
|
33
|
+
return JSON.stringify(value, (key, item) => {
|
|
34
|
+
if (/password|cookie|authorization|api.?key|access.?token|refresh.?token|secret/i.test(key))
|
|
35
|
+
return "[redacted]";
|
|
36
|
+
return typeof item === "string" ? redactText(item) : item;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function excerpt(text) {
|
|
41
|
+
const line = stripVTControlCharacters(text).replace(/\s+/g, " ").trim();
|
|
42
|
+
return line.length > 120 ? line.slice(0, 119) + "…" : line;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function summarizeTask(row) {
|
|
46
|
+
if (row.status === "blocked") {
|
|
47
|
+
if (row.startCheck?.status === "failed" && row.startCheck.quote)
|
|
48
|
+
return `Task did not start. Expected initial state: “${excerpt(row.startCheck.expect)}”. Page showed “${excerpt(row.startCheck.quote)}”.`;
|
|
49
|
+
return `Task blocked. ${excerpt(row.reason || "No reason recorded.")}`;
|
|
50
|
+
}
|
|
51
|
+
if (row.status === "unknown") {
|
|
52
|
+
const check = row.checks.find((item) => ["unknown", "unverified"].includes(item.status));
|
|
53
|
+
if (check)
|
|
54
|
+
return `Could not verify “${excerpt(check.expect)}”. ${excerpt(check.reason || row.reason || "Insufficient evidence.")}`;
|
|
55
|
+
return `Could not verify task outcome. ${excerpt(row.reason || "Insufficient evidence.")}`;
|
|
56
|
+
}
|
|
57
|
+
if (row.status === "failed" && row.failedStep)
|
|
58
|
+
return row.failedStep + (row.reason ? " · " + excerpt(row.reason) : "");
|
|
59
|
+
const failed = row.checks.filter((item) => item.status === "failed");
|
|
60
|
+
const check = failed[0] ?? row.checks.find((item) => item.kind === "page") ?? row.checks[0];
|
|
61
|
+
if (!check) return row.reason ?? "Task passed.";
|
|
62
|
+
const source = check.kind === "page" ? "Page showed" : "Agent replied";
|
|
63
|
+
if (!check.quote)
|
|
64
|
+
return failed.length
|
|
65
|
+
? (check.reason ?? "Check failed.")
|
|
66
|
+
: `Checks passed: ${row.checks.length}.`;
|
|
67
|
+
const evidence = `${source} “${excerpt(check.quote)}”.`;
|
|
68
|
+
if (failed.length)
|
|
69
|
+
return `Checks failed: ${failed.length} of ${row.checks.length}. Expected “${excerpt(check.expect)}”. ${evidence}`;
|
|
70
|
+
return `Checks passed: ${row.checks.length}. ${evidence}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const labels = { passed: "PASSED", failed: "FAILED", blocked: "BLOCKED", unknown: "UNVERIFIED" };
|
|
74
|
+
const checkLabels = { ...labels, unverified: "UNVERIFIED", "not-run": "NOT RUN" };
|
|
75
|
+
|
|
76
|
+
export function rerunCommand(ids) {
|
|
77
|
+
const args = ids.map((id) =>
|
|
78
|
+
/^[\w.-]+$/.test(id) ? id : "'" + id.replaceAll("'", "'\\''") + "'",
|
|
79
|
+
);
|
|
80
|
+
return "nexface eval" + args.map((id) => " --task " + id).join("");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function field(label, value) {
|
|
84
|
+
const prefix = " " + label.padEnd(11);
|
|
85
|
+
const indent = " ".repeat(prefix.length);
|
|
86
|
+
const width = Math.max(20, Math.min(process.stdout.columns || 96, 100) - prefix.length);
|
|
87
|
+
const lines = [];
|
|
88
|
+
for (const paragraph of stripVTControlCharacters(String(value)).trim().split(/\r?\n/)) {
|
|
89
|
+
let line = "",
|
|
90
|
+
size = 0;
|
|
91
|
+
for (const word of paragraph.match(/[\p{Script=Han}]|[^\s\p{Script=Han}]+|\s+/gu) ?? []) {
|
|
92
|
+
const length = /\p{Script=Han}/u.test(word) ? 2 : word.length;
|
|
93
|
+
if (size + length > width && line.trim()) {
|
|
94
|
+
lines.push(line.trimEnd());
|
|
95
|
+
line = "";
|
|
96
|
+
size = 0;
|
|
97
|
+
}
|
|
98
|
+
if (!size && !word.trim()) continue;
|
|
99
|
+
line += word;
|
|
100
|
+
size += length;
|
|
101
|
+
}
|
|
102
|
+
lines.push(line.trimEnd());
|
|
103
|
+
}
|
|
104
|
+
return prefix + lines.join("\n" + indent);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function formatReport(tasks, verbose = false) {
|
|
108
|
+
const counts = Object.entries(labels).flatMap(([status, label]) => {
|
|
109
|
+
const count = tasks.filter((task) => task.status === status).length;
|
|
110
|
+
return count ? [count + " " + label.toLowerCase()] : [];
|
|
111
|
+
});
|
|
112
|
+
const lines = [
|
|
113
|
+
tasks.length + (tasks.length === 1 ? " task" : " tasks") + " · " + counts.join(" · "),
|
|
114
|
+
];
|
|
115
|
+
for (const [index, task] of tasks.entries()) {
|
|
116
|
+
if (index) lines.push("", "─".repeat(Math.min(process.stdout.columns || 76, 76)));
|
|
117
|
+
lines.push("", labels[task.status] + " " + task.id, " " + task.goal);
|
|
118
|
+
if (task.failedStep) lines.push(field("Step", task.failedStep));
|
|
119
|
+
if (task.startCheck && ["failed", "unknown"].includes(task.startCheck.status)) {
|
|
120
|
+
const check = task.startCheck;
|
|
121
|
+
lines.push(
|
|
122
|
+
"",
|
|
123
|
+
" Starting condition " + (check.status === "failed" ? "NOT MET" : "UNVERIFIED"),
|
|
124
|
+
field("Reason", check.reason + " The task was not sent to the agent."),
|
|
125
|
+
field("Expected", check.expect),
|
|
126
|
+
);
|
|
127
|
+
if (check.status === "failed" && check.quote) lines.push(field("Evidence", check.quote));
|
|
128
|
+
} else if (task.reason) {
|
|
129
|
+
lines.push("", " " + (task.stage || "Task execution"), field("Reason", task.reason));
|
|
130
|
+
}
|
|
131
|
+
const { checks } = task;
|
|
132
|
+
if (
|
|
133
|
+
!verbose &&
|
|
134
|
+
task.status === "blocked" &&
|
|
135
|
+
task.reason &&
|
|
136
|
+
checks.length &&
|
|
137
|
+
checks.every((c) => c.status === "not-run")
|
|
138
|
+
) {
|
|
139
|
+
lines.push("", ` ${checks.length} ${checks.length === 1 ? "check" : "checks"} not run.`);
|
|
140
|
+
} else {
|
|
141
|
+
for (const check of checks) {
|
|
142
|
+
const source = { tool: "Tool", page: "Page", reply: "Reply" }[check.kind] ?? "Business";
|
|
143
|
+
const identified = check.criterionId ?? (check.check && check.id);
|
|
144
|
+
if (check.status === "passed" && !verbose && !identified) continue;
|
|
145
|
+
lines.push(
|
|
146
|
+
"",
|
|
147
|
+
" " +
|
|
148
|
+
source +
|
|
149
|
+
" check " +
|
|
150
|
+
checkLabels[check.status] +
|
|
151
|
+
(identified ? " " + identified : ""),
|
|
152
|
+
);
|
|
153
|
+
if (check.reason && (check.status !== "passed" || verbose))
|
|
154
|
+
lines.push(field("Reason", check.reason));
|
|
155
|
+
if (check.kind === "tool" && check.status === "failed") {
|
|
156
|
+
const reads = task.calls.filter(
|
|
157
|
+
(call) => call.status === "success" && check.evidenceRefs?.includes(call.id),
|
|
158
|
+
);
|
|
159
|
+
if (reads.length)
|
|
160
|
+
lines.push(field("Read with", reads.map((call) => call.name).join(", ")));
|
|
161
|
+
}
|
|
162
|
+
if (verbose || check.status === "failed" || check.status === "not-run")
|
|
163
|
+
lines.push(field("Expected", check.expect));
|
|
164
|
+
if (!["unknown", "unverified"].includes(check.status) && check.quote)
|
|
165
|
+
lines.push(field("Evidence", check.quote));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (task.status !== "passed" || verbose) lines.push("");
|
|
169
|
+
const lastTaskCall = task.calls.findLast((call) => call.phase === "task");
|
|
170
|
+
for (const call of task.calls) {
|
|
171
|
+
if (verbose) {
|
|
172
|
+
const outcome =
|
|
173
|
+
call.status === "success"
|
|
174
|
+
? "Returned " + JSON.stringify(call.result)
|
|
175
|
+
: JSON.stringify(call.error ?? call.result ?? call.status);
|
|
176
|
+
lines.push(
|
|
177
|
+
" " + call.phase + " " + call.name + " " + JSON.stringify(call.input) + " → " + outcome,
|
|
178
|
+
);
|
|
179
|
+
} else if (call.error) {
|
|
180
|
+
lines.push(" Tool error " + call.name + " " + excerpt(JSON.stringify(call.error)));
|
|
181
|
+
} else if (task.status === "failed" && call === lastTaskCall) {
|
|
182
|
+
lines.push(" Last call " + call.name);
|
|
183
|
+
if (call.status === "success")
|
|
184
|
+
lines.push(field("Returned", excerpt(JSON.stringify(call.result) ?? "undefined")));
|
|
185
|
+
else lines.push(field("Status", call.status));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (task.traceWarning) lines.push(" Tool trace " + excerpt(task.traceWarning));
|
|
189
|
+
if (task.status !== "passed") {
|
|
190
|
+
lines.push(" Rerun " + rerunCommand([task.id]));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return stripVTControlCharacters(lines.join("\n"));
|
|
194
|
+
}
|
package/runner.mjs
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { mkdir } from "node:fs/promises";
|
|
4
|
+
import { basename, join } from "node:path";
|
|
5
|
+
import { validateSuite, readSuite } from "./suite.mjs";
|
|
6
|
+
import { launch, authenticate, privateDir, atomicJson } from "./session.mjs";
|
|
7
|
+
import { redactText, summarizeTask, formatReport, rerunCommand } from "./report-output.mjs";
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
9
|
+
import { taskAssets } from "./generated.mjs";
|
|
10
|
+
import { runSpecs } from "./spec-run.mjs";
|
|
11
|
+
|
|
12
|
+
export async function run(root, ids, verbose = false) {
|
|
13
|
+
const suite = validateSuite(await readSuite(root), true);
|
|
14
|
+
for (const id of ids)
|
|
15
|
+
if (!suite.tasks.some((task) => task.id === id)) throw new Error("Unknown task: " + id);
|
|
16
|
+
const tasks = suite.tasks.filter((task) => !ids.length || ids.includes(task.id));
|
|
17
|
+
console.log(redactText("Nexface evaluation · " + basename(root)));
|
|
18
|
+
const problems = [];
|
|
19
|
+
const missing = ["NEXFACE_EVAL_URL", "NEXFACE_EVAL_MODEL"].filter(
|
|
20
|
+
(name) => !process.env[name]?.trim(),
|
|
21
|
+
);
|
|
22
|
+
if (missing.length)
|
|
23
|
+
problems.push(
|
|
24
|
+
" Execution model\n Reason Missing " +
|
|
25
|
+
missing.join(", ") +
|
|
26
|
+
".\n Fix Set " +
|
|
27
|
+
missing.join(" and ") +
|
|
28
|
+
" in the CLI environment.",
|
|
29
|
+
);
|
|
30
|
+
const endpoint = process.env.NEXFACE_EVAL_URL?.trim();
|
|
31
|
+
if (
|
|
32
|
+
endpoint &&
|
|
33
|
+
(!URL.canParse(endpoint) ||
|
|
34
|
+
!/^https?:$/.test(new URL(endpoint).protocol) ||
|
|
35
|
+
new URL(endpoint).username ||
|
|
36
|
+
new URL(endpoint).password)
|
|
37
|
+
) {
|
|
38
|
+
problems.push(
|
|
39
|
+
" Execution model\n Reason Invalid NEXFACE_EVAL_URL." +
|
|
40
|
+
"\n Fix Set an HTTP(S) completion endpoint without embedded credentials.",
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
if (problems.length) {
|
|
44
|
+
console.error(
|
|
45
|
+
tasks.length +
|
|
46
|
+
(tasks.length === 1 ? " task" : " tasks") +
|
|
47
|
+
" selected · 0 started\n\nRUN NOT STARTED\n" +
|
|
48
|
+
problems.join("\n\n") +
|
|
49
|
+
"\n\n Rerun " +
|
|
50
|
+
rerunCommand(ids),
|
|
51
|
+
);
|
|
52
|
+
return 1;
|
|
53
|
+
}
|
|
54
|
+
const baseURL = new URL(process.env.NEXFACE_BASE_URL ?? "http://localhost:3000").href;
|
|
55
|
+
let revision;
|
|
56
|
+
try {
|
|
57
|
+
revision = execFileSync("git", ["rev-parse", "HEAD"], {
|
|
58
|
+
cwd: root,
|
|
59
|
+
encoding: "utf8",
|
|
60
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
61
|
+
}).trim();
|
|
62
|
+
} catch {}
|
|
63
|
+
const report = {
|
|
64
|
+
id: randomUUID(),
|
|
65
|
+
at: new Date().toISOString(),
|
|
66
|
+
revision,
|
|
67
|
+
suite: createHash("sha256").update(JSON.stringify(suite)).digest("hex"),
|
|
68
|
+
tasks: [],
|
|
69
|
+
};
|
|
70
|
+
const runnable = [];
|
|
71
|
+
const fingerprints = Object.create(null);
|
|
72
|
+
for (const task of tasks) {
|
|
73
|
+
try {
|
|
74
|
+
const record = await taskAssets(root, task);
|
|
75
|
+
fingerprints[task.id] = record?.fingerprint ?? null;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
const row = {
|
|
78
|
+
id: task.id,
|
|
79
|
+
goal: task.goal,
|
|
80
|
+
status: "blocked",
|
|
81
|
+
stage: "Test assets",
|
|
82
|
+
reason: redactText(error.message),
|
|
83
|
+
checks: [],
|
|
84
|
+
calls: [],
|
|
85
|
+
};
|
|
86
|
+
row.summary = summarizeTask(row);
|
|
87
|
+
report.tasks.push(row);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
runnable.push(task);
|
|
91
|
+
}
|
|
92
|
+
let state;
|
|
93
|
+
let stage = "Browser launch";
|
|
94
|
+
if (runnable.length && existsSync(join(root, ".nexface/auth.mjs"))) {
|
|
95
|
+
let browser;
|
|
96
|
+
try {
|
|
97
|
+
browser = await launch();
|
|
98
|
+
stage = "Authentication";
|
|
99
|
+
state = await authenticate(root, baseURL, browser);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
for (const task of runnable) {
|
|
102
|
+
const row = {
|
|
103
|
+
id: task.id,
|
|
104
|
+
goal: task.goal,
|
|
105
|
+
status: "blocked",
|
|
106
|
+
stage,
|
|
107
|
+
reason: redactText(error.message),
|
|
108
|
+
checks: [],
|
|
109
|
+
calls: [],
|
|
110
|
+
};
|
|
111
|
+
row.summary = summarizeTask(row);
|
|
112
|
+
report.tasks.push(row);
|
|
113
|
+
}
|
|
114
|
+
runnable.length = 0;
|
|
115
|
+
} finally {
|
|
116
|
+
await browser?.close();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (runnable.length) {
|
|
120
|
+
const result = await runSpecs(root, runnable, baseURL, state, fingerprints);
|
|
121
|
+
if (result.errors.length) report.errors = result.errors.map(redactText);
|
|
122
|
+
for (const row of result.tasks) {
|
|
123
|
+
row.summary = summarizeTask(row);
|
|
124
|
+
report.tasks.push(row);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
for (const row of report.tasks) {
|
|
128
|
+
if (row.status !== "blocked" || row.checks.length) continue;
|
|
129
|
+
const task = tasks.find((task) => task.id === row.id);
|
|
130
|
+
row.checks = task.criteria.map((criterion) => ({
|
|
131
|
+
...criterion,
|
|
132
|
+
criterionId: criterion.id,
|
|
133
|
+
kind: criterion.check,
|
|
134
|
+
status: "not-run",
|
|
135
|
+
reason: row.reason,
|
|
136
|
+
evidenceRefs: [],
|
|
137
|
+
}));
|
|
138
|
+
}
|
|
139
|
+
const order = new Map(tasks.map((task, index) => [task.id, index]));
|
|
140
|
+
report.tasks.sort((a, b) => order.get(a.id) - order.get(b.id));
|
|
141
|
+
report.judge = report.tasks.find((task) => task.judge)?.judge ?? null;
|
|
142
|
+
const dir = join(privateDir(root), "runs");
|
|
143
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
144
|
+
const file = join(dir, report.id + ".json");
|
|
145
|
+
for (const row of report.tasks) row.id = redactText(row.id);
|
|
146
|
+
await atomicJson(file, report);
|
|
147
|
+
console.log(formatReport(report.tasks, verbose));
|
|
148
|
+
console.log("\nJudge: " + (report.judge ?? "not used"));
|
|
149
|
+
for (const error of report.errors ?? []) console.error("Playwright: " + error);
|
|
150
|
+
console.log("\nRun report");
|
|
151
|
+
console.log(redactText(file));
|
|
152
|
+
return !report.errors?.length && report.tasks.every((t) => t.status === "passed") ? 0 : 1;
|
|
153
|
+
}
|
package/session.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { readFile, mkdir, writeFile, rename, access } from "node:fs/promises";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { chromium } from "playwright-core";
|
|
7
|
+
|
|
8
|
+
export function privateDir(root) {
|
|
9
|
+
return join(
|
|
10
|
+
process.env.NEXFACE_STATE_DIR ?? join(homedir(), ".nexface-evals"),
|
|
11
|
+
createHash("sha256").update(root).digest("hex").slice(0, 24),
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
export async function atomicJson(path, data) {
|
|
15
|
+
const tmp = path + "." + randomUUID();
|
|
16
|
+
await writeFile(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
17
|
+
await rename(tmp, path);
|
|
18
|
+
}
|
|
19
|
+
export async function readJson(path, fallback) {
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (error.code === "ENOENT") return fallback;
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export async function bounded(operation, ms, message) {
|
|
28
|
+
let timer;
|
|
29
|
+
try {
|
|
30
|
+
return await Promise.race([
|
|
31
|
+
operation,
|
|
32
|
+
new Promise((_, reject) => {
|
|
33
|
+
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
34
|
+
}),
|
|
35
|
+
]);
|
|
36
|
+
} finally {
|
|
37
|
+
clearTimeout(timer);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function launch(headless = true) {
|
|
41
|
+
return chromium.launch({
|
|
42
|
+
headless,
|
|
43
|
+
channel: process.env.NEXFACE_BROWSER_CHANNEL || undefined,
|
|
44
|
+
executablePath: process.env.NEXFACE_BROWSER_PATH || undefined,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
export async function authenticate(root, baseURL, browser) {
|
|
48
|
+
const file = join(root, ".nexface/auth.mjs");
|
|
49
|
+
try {
|
|
50
|
+
await access(file);
|
|
51
|
+
} catch (e) {
|
|
52
|
+
if (e.code === "ENOENT") return;
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
const login = (await import(pathToFileURL(file))).default;
|
|
56
|
+
const dir = privateDir(root);
|
|
57
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
58
|
+
const path = join(
|
|
59
|
+
dir,
|
|
60
|
+
"auth-" + createHash("sha256").update(baseURL).digest("hex").slice(0, 16) + ".json",
|
|
61
|
+
);
|
|
62
|
+
let state = await readJson(path);
|
|
63
|
+
async function check(instance, mode) {
|
|
64
|
+
const context = await instance.newContext({ baseURL, storageState: state });
|
|
65
|
+
try {
|
|
66
|
+
const page = await context.newPage();
|
|
67
|
+
const result = await bounded(login({ page, baseURL, mode }), 180000, "Login timed out.");
|
|
68
|
+
if (result !== "ok" && result !== "manual") throw new Error("Invalid login result.");
|
|
69
|
+
if (result === "ok") state = await context.storageState({ indexedDB: true });
|
|
70
|
+
return result;
|
|
71
|
+
} finally {
|
|
72
|
+
await context.close();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if ((await check(browser, "headless")) === "manual") {
|
|
76
|
+
if (process.env.CI && process.env.CI !== "false")
|
|
77
|
+
throw new Error("Interactive login required.");
|
|
78
|
+
const visible = await launch(false);
|
|
79
|
+
try {
|
|
80
|
+
if ((await check(visible, "interactive")) !== "ok") throw new Error("Login incomplete.");
|
|
81
|
+
} finally {
|
|
82
|
+
await visible.close();
|
|
83
|
+
}
|
|
84
|
+
if ((await check(browser, "headless")) !== "ok")
|
|
85
|
+
throw new Error("Headless session verification failed.");
|
|
86
|
+
}
|
|
87
|
+
await atomicJson(path, state);
|
|
88
|
+
return state;
|
|
89
|
+
}
|
package/site-run.mjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { gatewayReason } from "./report-output.mjs";
|
|
3
|
+
import { createAgent } from "@nexface/agent";
|
|
4
|
+
import { createModelConfig } from "@nexface/agent/openai-completions";
|
|
5
|
+
import { createToolRuntime } from "@nexface/tools";
|
|
6
|
+
|
|
7
|
+
export class ConfirmationBlocked extends Error {}
|
|
8
|
+
|
|
9
|
+
// Preserve valid business names and consistently escape names reserved by either protocol.
|
|
10
|
+
function modelName(name) {
|
|
11
|
+
if (
|
|
12
|
+
/^[a-zA-Z0-9_-]{1,64}$/.test(name) &&
|
|
13
|
+
!/^(wmcp_alias_|nxf_(?:beginOperation|endOperation|applyAction|delegatePageTask|callAppTool|finish|getSnapshot|executeCode|executeAction|loadSkill)$)/.test(
|
|
14
|
+
name,
|
|
15
|
+
)
|
|
16
|
+
)
|
|
17
|
+
return name;
|
|
18
|
+
return "wmcp_alias_" + createHash("sha256").update(name).digest("hex").slice(0, 48);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function runSiteAgent(goal, timeout, connection, signal) {
|
|
22
|
+
const endpoint = new URL(process.env.NEXFACE_EVAL_URL);
|
|
23
|
+
if (!/^https?:$/.test(endpoint.protocol) || endpoint.username || endpoint.password)
|
|
24
|
+
throw new Error("Invalid NEXFACE_EVAL_URL.");
|
|
25
|
+
let requestFailure;
|
|
26
|
+
const model = createModelConfig({
|
|
27
|
+
model: process.env.NEXFACE_EVAL_MODEL,
|
|
28
|
+
baseURL: endpoint.origin,
|
|
29
|
+
apiKey: process.env.NEXFACE_EVAL_KEY,
|
|
30
|
+
async fetch(_url, init) {
|
|
31
|
+
requestFailure = undefined;
|
|
32
|
+
const response = await fetch(endpoint, { ...init, redirect: "error" });
|
|
33
|
+
if (!response.ok) requestFailure = await gatewayReason("Execution model", response.clone());
|
|
34
|
+
return response;
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
const runtime = createToolRuntime({ pageAutomation: false });
|
|
38
|
+
let blockedReason;
|
|
39
|
+
let timedOut = false;
|
|
40
|
+
const bindings = new Map();
|
|
41
|
+
let step = 0;
|
|
42
|
+
async function refresh(stepSignal) {
|
|
43
|
+
stepSignal.throwIfAborted();
|
|
44
|
+
const definitions = await connection.tools();
|
|
45
|
+
const published = [];
|
|
46
|
+
const removed = [];
|
|
47
|
+
step++;
|
|
48
|
+
const names = new Set(definitions.map((tool) => modelName(tool.name)));
|
|
49
|
+
for (const [name, binding] of bindings) {
|
|
50
|
+
if (!names.has(name)) {
|
|
51
|
+
removed.push(binding.siteName);
|
|
52
|
+
binding.remove();
|
|
53
|
+
bindings.delete(name);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const definition of definitions) {
|
|
57
|
+
const name = modelName(definition.name);
|
|
58
|
+
const signature = JSON.stringify(definition);
|
|
59
|
+
if (bindings.get(name)?.signature === signature) continue;
|
|
60
|
+
bindings.get(name)?.remove();
|
|
61
|
+
// The exact browser schema goes to the model and is validated by AJV at dispatch.
|
|
62
|
+
// WebMCP permits JSON Schema keywords beyond the SDK registration subset.
|
|
63
|
+
const remove = runtime.register(
|
|
64
|
+
{
|
|
65
|
+
name,
|
|
66
|
+
description: definition.description?.trim() || definition.name,
|
|
67
|
+
inputSchema: { type: "object" },
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
async execute(input, { signal: callSignal }) {
|
|
71
|
+
signal?.throwIfAborted();
|
|
72
|
+
if (timedOut) throw new Error("Task timed out.");
|
|
73
|
+
if (blockedReason) throw new Error(blockedReason);
|
|
74
|
+
try {
|
|
75
|
+
return await connection.execute(definition.name, input, "task", {
|
|
76
|
+
signal: callSignal,
|
|
77
|
+
});
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error instanceof ConfirmationBlocked) {
|
|
80
|
+
blockedReason = error.message;
|
|
81
|
+
run.cancel();
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
);
|
|
88
|
+
bindings.set(name, {
|
|
89
|
+
siteName: definition.name,
|
|
90
|
+
signature,
|
|
91
|
+
remove,
|
|
92
|
+
schema: definition.inputSchema,
|
|
93
|
+
});
|
|
94
|
+
published.push(name === definition.name ? definition : { ...definition, modelName: name });
|
|
95
|
+
}
|
|
96
|
+
if (step === 1 || published.length || removed.length)
|
|
97
|
+
connection.recordCatalogChange(step, published, removed);
|
|
98
|
+
}
|
|
99
|
+
runtime[Symbol.for("@nexface/evals/webmcp-catalog")] = {
|
|
100
|
+
refresh,
|
|
101
|
+
schemaFor: (name) => bindings.get(name)?.schema,
|
|
102
|
+
};
|
|
103
|
+
signal?.throwIfAborted();
|
|
104
|
+
const agent = createAgent({ model, toolRuntime: runtime });
|
|
105
|
+
const run = agent.run({ messages: [{ id: crypto.randomUUID(), role: "user", content: goal }] });
|
|
106
|
+
const cancel = () => {
|
|
107
|
+
timedOut = true;
|
|
108
|
+
run.cancel();
|
|
109
|
+
};
|
|
110
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
111
|
+
const timer = setTimeout(cancel, timeout);
|
|
112
|
+
try {
|
|
113
|
+
for await (const _event of run) {
|
|
114
|
+
/* Drain the run event stream. */
|
|
115
|
+
}
|
|
116
|
+
const result = await run.result;
|
|
117
|
+
if (timedOut) throw new Error("Task timed out.");
|
|
118
|
+
return { ...result, model: agent.model, blockedReason };
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (blockedReason) return { outcome: { type: "interrupt" }, model: agent.model, blockedReason };
|
|
121
|
+
if (requestFailure) throw new Error(requestFailure, { cause: error });
|
|
122
|
+
throw error;
|
|
123
|
+
} finally {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
signal?.removeEventListener("abort", cancel);
|
|
126
|
+
}
|
|
127
|
+
}
|
package/spec-config.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
|
|
4
|
+
const { dir, baseURL, storageState } = JSON.parse(process.env.NEXFACE_SPEC_OPTIONS);
|
|
5
|
+
export default {
|
|
6
|
+
testDir: fileURLToPath(new URL(".", import.meta.url)),
|
|
7
|
+
testMatch: "**/approved-task.mjs",
|
|
8
|
+
outputDir: join(dir, "artifacts"),
|
|
9
|
+
reporter: [[fileURLToPath(new URL("spec-reporter.mjs", import.meta.url))]],
|
|
10
|
+
workers: 1,
|
|
11
|
+
retries: 0,
|
|
12
|
+
timeout: 300000,
|
|
13
|
+
use: {
|
|
14
|
+
baseURL,
|
|
15
|
+
storageState,
|
|
16
|
+
actionTimeout: 10000,
|
|
17
|
+
navigationTimeout: 20000,
|
|
18
|
+
launchOptions: {
|
|
19
|
+
executablePath: process.env.NEXFACE_BROWSER_PATH || undefined,
|
|
20
|
+
channel: process.env.NEXFACE_BROWSER_CHANNEL || undefined,
|
|
21
|
+
args: ["--enable-features=WebMCP"],
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { atomicJson } from "./session.mjs";
|
|
4
|
+
import { safeJson } from "./report-output.mjs";
|
|
5
|
+
|
|
6
|
+
export default class SpecReporter {
|
|
7
|
+
rows = [];
|
|
8
|
+
errors = [];
|
|
9
|
+
onBegin(_config, suite) {
|
|
10
|
+
const { dir } = JSON.parse(process.env.NEXFACE_SPEC_OPTIONS);
|
|
11
|
+
const counts = new Map();
|
|
12
|
+
for (const test of suite.allTests()) {
|
|
13
|
+
const id = test.title;
|
|
14
|
+
counts.set(id, (counts.get(id) ?? 0) + 1);
|
|
15
|
+
}
|
|
16
|
+
writeFileSync(join(dir, "test-counts.json"), JSON.stringify(Object.fromEntries(counts)));
|
|
17
|
+
}
|
|
18
|
+
onError(error) {
|
|
19
|
+
this.errors.push(error.message ?? String(error));
|
|
20
|
+
}
|
|
21
|
+
onTestEnd(test, result) {
|
|
22
|
+
const { ids } = JSON.parse(process.env.NEXFACE_SPEC_OPTIONS);
|
|
23
|
+
const selectionIndex = ids.indexOf(test.title);
|
|
24
|
+
const attachment = result.attachments.find((item) => item.name === "nexface-task");
|
|
25
|
+
if (!attachment) {
|
|
26
|
+
this.rows.push({
|
|
27
|
+
selectionIndex,
|
|
28
|
+
status: "blocked",
|
|
29
|
+
stage: "Playwright",
|
|
30
|
+
reason: result.errors[0]?.message ?? "Test did not run the Nexface fixture.",
|
|
31
|
+
checks: [],
|
|
32
|
+
calls: [],
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const row = JSON.parse(attachment.body ?? readFileSync(attachment.path));
|
|
37
|
+
function collect(steps, parent) {
|
|
38
|
+
for (const step of steps) {
|
|
39
|
+
const title = step.category === "test.step" ? step.title : parent;
|
|
40
|
+
if (step.category === "expect" && step.error) {
|
|
41
|
+
row.failedStep = title ?? step.title;
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
if (collect(step.steps, title)) return true;
|
|
45
|
+
if (step.error && title) row.failedStep ??= title;
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
if (result.status === "failed") collect(result.steps);
|
|
50
|
+
if (result.status !== "passed" && row.status === "passed") {
|
|
51
|
+
row.status = "unknown";
|
|
52
|
+
row.reason = result.errors[0]?.message ?? result.status;
|
|
53
|
+
}
|
|
54
|
+
this.rows.push({ ...row, selectionIndex });
|
|
55
|
+
}
|
|
56
|
+
async onEnd() {
|
|
57
|
+
const { dir } = JSON.parse(process.env.NEXFACE_SPEC_OPTIONS);
|
|
58
|
+
await atomicJson(
|
|
59
|
+
join(dir, "results.json"),
|
|
60
|
+
JSON.parse(safeJson({ rows: this.rows, errors: this.errors })),
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|