agentperf 0.1.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # agentperf
2
+
3
+ **Measure what AI agents pay to use a website.** Same page, same model, same
4
+ task, same verification — two lanes:
5
+
6
+ - **dom** — the agent reads the accessibility tree and clicks/types, the way
7
+ browser-driving agents work today. (Text-based driving is *cheaper* than
8
+ screenshots, so this baseline is conservative in the DOM lane's favor.)
9
+ - **tools** — the agent calls the page's own WebMCP tools. The harness injects
10
+ a `document.modelContext` host before page load, so it benchmarks any
11
+ WebMCP page in stock Chromium — no browser flag, no origin trial.
12
+
13
+ Success is verified by the harness against the rendered page, never claimed by
14
+ the model. Failed runs are reported, not discarded.
15
+
16
+ ```bash
17
+ npm i -g agentperf
18
+ npx playwright install chromium
19
+ export OPENAI_API_KEY=sk-… # any OpenAI-compatible endpoint works
20
+ agentperf run --url https://your-app.example --runs 3
21
+ ```
22
+
23
+ Output: per-run and median wall-clock, tokens (prompt+completion), model
24
+ round-trips, actions, success rate — as a markdown table and JSON under
25
+ `results/`.
26
+
27
+ Options: `--lane both|tools|dom` · `--runs N` · `--model <id>` (default
28
+ `gpt-5.6-luna`) · `--base-url <url>` for compatible providers · `--task
29
+ booking|path/to/task.json` · `--max-turns N` · `--out dir`. A task file is
30
+ `{ id, prompt, successPattern, maxTurns }` — the prompt is handed to both
31
+ lanes verbatim and `successPattern` is a regex the page's visible text must
32
+ match when the task is truly done.
33
+
34
+ Instrument your app with [`@agentperf/react`](https://www.npmjs.com/package/@agentperf/react)
35
+ to give it the tools lane.
36
+
37
+ Apache-2.0
@@ -0,0 +1,395 @@
1
+ // src/llm.ts
2
+ async function chat(config, messages, tools) {
3
+ const response = await fetch(`${config.baseUrl}/chat/completions`, {
4
+ method: "POST",
5
+ headers: {
6
+ "content-type": "application/json",
7
+ authorization: `Bearer ${config.apiKey}`
8
+ },
9
+ body: JSON.stringify({
10
+ model: config.model,
11
+ messages,
12
+ // gpt-5.6 models 400 on function tools unless reasoning is off.
13
+ ...config.model.startsWith("gpt-5.6") && { reasoning_effort: "none" },
14
+ tools: tools.map((tool) => ({
15
+ type: "function",
16
+ function: {
17
+ name: tool.name,
18
+ description: tool.description,
19
+ parameters: tool.parameters
20
+ }
21
+ })),
22
+ tool_choice: "auto"
23
+ })
24
+ });
25
+ if (!response.ok) {
26
+ const body = await response.text();
27
+ throw new Error(`LLM request failed (${response.status}): ${body.slice(0, 400)}`);
28
+ }
29
+ const data = await response.json();
30
+ const message = data.choices[0]?.message;
31
+ if (!message) throw new Error("LLM response had no choices");
32
+ const toolCalls = (message.tool_calls ?? []).map((call) => {
33
+ let args = {};
34
+ try {
35
+ args = JSON.parse(call.function.arguments || "{}");
36
+ } catch {
37
+ }
38
+ return { id: call.id, name: call.function.name, args, raw: call };
39
+ });
40
+ return {
41
+ content: message.content,
42
+ toolCalls,
43
+ rawMessage: message,
44
+ promptTokens: data.usage?.prompt_tokens ?? 0,
45
+ completionTokens: data.usage?.completion_tokens ?? 0
46
+ };
47
+ }
48
+
49
+ // src/agent-loop.ts
50
+ var TASK_COMPLETE = {
51
+ name: "task_complete",
52
+ description: "Call this exactly once, when the task is fully done and its outcome is visible on the page. Summarize the outcome (include any code or value the task asked for).",
53
+ parameters: {
54
+ type: "object",
55
+ properties: { summary: { type: "string" } },
56
+ required: ["summary"]
57
+ }
58
+ };
59
+ async function runAgentLoop(options) {
60
+ const messages = [
61
+ { role: "system", content: options.systemPrompt },
62
+ { role: "user", content: options.taskPrompt }
63
+ ];
64
+ const tools = [...options.tools, TASK_COMPLETE];
65
+ const outcome = {
66
+ turns: 0,
67
+ actions: 0,
68
+ promptTokens: 0,
69
+ completionTokens: 0,
70
+ claimedDone: false,
71
+ claimSummary: ""
72
+ };
73
+ let nudged = false;
74
+ while (outcome.turns < options.maxTurns) {
75
+ outcome.turns += 1;
76
+ const turn = await chat(options.llm, messages, tools);
77
+ outcome.promptTokens += turn.promptTokens;
78
+ outcome.completionTokens += turn.completionTokens;
79
+ messages.push(turn.rawMessage);
80
+ if (turn.toolCalls.length === 0) {
81
+ if (nudged) {
82
+ outcome.failure = "model stopped calling tools before claiming completion";
83
+ return outcome;
84
+ }
85
+ nudged = true;
86
+ messages.push({
87
+ role: "user",
88
+ content: "Continue using the tools. When the task is done, call task_complete."
89
+ });
90
+ continue;
91
+ }
92
+ for (const call of turn.toolCalls) {
93
+ if (call.name === TASK_COMPLETE.name) {
94
+ outcome.claimedDone = true;
95
+ outcome.claimSummary = String(call.args.summary ?? "");
96
+ messages.push({ role: "tool", tool_call_id: call.id, content: "Recorded." });
97
+ return outcome;
98
+ }
99
+ outcome.actions += 1;
100
+ let result;
101
+ try {
102
+ result = await options.invoke(call.name, call.args);
103
+ } catch (error) {
104
+ result = `ACTION FAILED: ${error instanceof Error ? error.message : String(error)}`;
105
+ }
106
+ messages.push({ role: "tool", tool_call_id: call.id, content: result });
107
+ }
108
+ }
109
+ outcome.failure = `hit the ${options.maxTurns}-turn cap without claiming completion`;
110
+ return outcome;
111
+ }
112
+
113
+ // src/shim.ts
114
+ var HOST_SHIM = `
115
+ (() => {
116
+ const tools = new Map();
117
+ const api = {
118
+ listTools: () =>
119
+ Array.from(tools.values()).map((t) => ({
120
+ name: t.name,
121
+ description: t.description,
122
+ inputSchema: t.inputSchema || { type: "object", properties: {} },
123
+ annotations: t.annotations || {}
124
+ })),
125
+ call: async (name, args) => {
126
+ const tool = tools.get(name);
127
+ if (!tool) {
128
+ return {
129
+ content: [{ type: "text", text: "No tool named \\"" + name + "\\" is registered on this page." }],
130
+ isError: true
131
+ };
132
+ }
133
+ const result = await tool.execute(args || {});
134
+ if (typeof result === "string") return { content: [{ type: "text", text: result }] };
135
+ return result;
136
+ }
137
+ };
138
+ Object.defineProperty(window, "__agentperf", { value: api });
139
+
140
+ const modelContext = {
141
+ registerTool: (tool, options) => {
142
+ tools.set(tool.name, tool);
143
+ if (options && options.signal) {
144
+ options.signal.addEventListener("abort", () => { tools.delete(tool.name); });
145
+ }
146
+ },
147
+ getTools: async () => api.listTools()
148
+ };
149
+ Object.defineProperty(document, "modelContext", { value: modelContext, configurable: true });
150
+ Object.defineProperty(navigator, "modelContext", { value: modelContext, configurable: true });
151
+ })();
152
+ `;
153
+
154
+ // src/lanes.ts
155
+ import { chromium } from "playwright";
156
+ async function verify(page, task) {
157
+ const text = await page.evaluate(() => document.body.innerText);
158
+ return new RegExp(task.successPattern).test(text);
159
+ }
160
+ function metrics(lane, task) {
161
+ return {
162
+ lane,
163
+ taskId: task.id,
164
+ success: false,
165
+ wallClockMs: 0,
166
+ turns: 0,
167
+ actions: 0,
168
+ promptTokens: 0,
169
+ completionTokens: 0,
170
+ totalTokens: 0
171
+ };
172
+ }
173
+ function finish(run, startedMs, loop, verified, claimedDone) {
174
+ run.wallClockMs = Math.round(performance.now() - startedMs);
175
+ run.turns = loop.turns;
176
+ run.actions = loop.actions;
177
+ run.promptTokens = loop.promptTokens;
178
+ run.completionTokens = loop.completionTokens;
179
+ run.totalTokens = loop.promptTokens + loop.completionTokens;
180
+ run.success = verified;
181
+ if (!verified) {
182
+ run.failure = loop.failure ?? (claimedDone ? "model claimed completion but the page does not show the expected outcome" : "run ended without completion");
183
+ }
184
+ return run;
185
+ }
186
+ async function runToolsLane(url, task, llm) {
187
+ const browser = await chromium.launch();
188
+ const run = metrics("tools", task);
189
+ const startedMs = performance.now();
190
+ try {
191
+ const context = await browser.newContext();
192
+ await context.addInitScript(HOST_SHIM);
193
+ const page = await context.newPage();
194
+ await page.goto(url, { waitUntil: "load" });
195
+ await page.waitForFunction(() => window.__agentperf?.listTools().length > 0, void 0, {
196
+ timeout: 15e3
197
+ });
198
+ const pageTools = await page.evaluate(() => window.__agentperf.listTools());
199
+ const tools = pageTools.map((tool) => ({
200
+ name: tool.name,
201
+ description: tool.description,
202
+ parameters: tool.inputSchema
203
+ }));
204
+ const loop = await runAgentLoop({
205
+ llm,
206
+ systemPrompt: "You complete tasks on a web page through the page's own tools (WebMCP). Call get_page_state first to orient when it exists. Use only the tools. When the task is fully done, call task_complete.",
207
+ taskPrompt: task.prompt,
208
+ tools,
209
+ maxTurns: task.maxTurns,
210
+ invoke: async (name, args) => {
211
+ const result = await page.evaluate(
212
+ ([toolName, toolArgs]) => window.__agentperf.call(
213
+ toolName,
214
+ toolArgs
215
+ ),
216
+ [name, args]
217
+ );
218
+ const text = result.content.map((c) => c.text).join("\n");
219
+ return result.isError ? `TOOL ERROR:
220
+ ${text}` : text;
221
+ }
222
+ });
223
+ const verified = loop.claimedDone && await verify(page, task);
224
+ return finish(run, startedMs, loop, verified, loop.claimedDone);
225
+ } catch (error) {
226
+ run.wallClockMs = Math.round(performance.now() - startedMs);
227
+ run.failure = error instanceof Error ? error.message : String(error);
228
+ return run;
229
+ } finally {
230
+ await browser.close();
231
+ }
232
+ }
233
+ var DOM_TOOLS = [
234
+ {
235
+ name: "read_page",
236
+ description: "Read the page's current accessibility tree (roles and names). Call after every action that changes the page.",
237
+ parameters: { type: "object", properties: {} }
238
+ },
239
+ {
240
+ name: "click",
241
+ description: "Click the element with this ARIA role and accessible name.",
242
+ parameters: {
243
+ type: "object",
244
+ properties: {
245
+ role: { type: "string", description: "ARIA role, e.g. button, link, textbox" },
246
+ name: { type: "string", description: "Accessible name, may be partial" }
247
+ },
248
+ required: ["role", "name"]
249
+ }
250
+ },
251
+ {
252
+ name: "fill",
253
+ description: "Type a value into the input with this ARIA role and accessible name (replaces content).",
254
+ parameters: {
255
+ type: "object",
256
+ properties: {
257
+ role: { type: "string" },
258
+ name: { type: "string" },
259
+ value: { type: "string" }
260
+ },
261
+ required: ["role", "name", "value"]
262
+ }
263
+ }
264
+ ];
265
+ var MAX_SNAPSHOT_CHARS = 24e3;
266
+ async function runDomLane(url, task, llm) {
267
+ const browser = await chromium.launch();
268
+ const run = metrics("dom", task);
269
+ const startedMs = performance.now();
270
+ try {
271
+ const context = await browser.newContext();
272
+ const page = await context.newPage();
273
+ await page.goto(url, { waitUntil: "load" });
274
+ const target = (role, name) => page.getByRole(String(role), {
275
+ name: String(name),
276
+ exact: false
277
+ }).first();
278
+ const loop = await runAgentLoop({
279
+ llm,
280
+ systemPrompt: "You complete tasks on a web page the way a browser-driving agent does: read the accessibility tree with read_page, then click and fill elements by role and name. Re-read the page after actions that change it. When the task is fully done, call task_complete.",
281
+ taskPrompt: task.prompt,
282
+ tools: DOM_TOOLS,
283
+ maxTurns: task.maxTurns,
284
+ invoke: async (name, args) => {
285
+ switch (name) {
286
+ case "read_page": {
287
+ const snapshot = await page.locator("body").ariaSnapshot();
288
+ return snapshot.length > MAX_SNAPSHOT_CHARS ? snapshot.slice(0, MAX_SNAPSHOT_CHARS) + "\n\u2026 (truncated)" : snapshot;
289
+ }
290
+ case "click": {
291
+ await target(args.role, args.name).click({ timeout: 5e3 });
292
+ await page.waitForTimeout(250);
293
+ return `Clicked ${String(args.role)} "${String(args.name)}".`;
294
+ }
295
+ case "fill": {
296
+ await target(args.role, args.name).fill(String(args.value ?? ""), { timeout: 5e3 });
297
+ return `Filled ${String(args.role)} "${String(args.name)}".`;
298
+ }
299
+ default:
300
+ return `ACTION FAILED: unknown action "${name}"`;
301
+ }
302
+ }
303
+ });
304
+ const verified = loop.claimedDone && await verify(page, task);
305
+ return finish(run, startedMs, loop, verified, loop.claimedDone);
306
+ } catch (error) {
307
+ run.wallClockMs = Math.round(performance.now() - startedMs);
308
+ run.failure = error instanceof Error ? error.message : String(error);
309
+ return run;
310
+ } finally {
311
+ await browser.close();
312
+ }
313
+ }
314
+
315
+ // src/report.ts
316
+ import { mkdirSync, writeFileSync } from "fs";
317
+ import { join } from "path";
318
+ function median(values) {
319
+ if (values.length === 0) return 0;
320
+ const sorted = [...values].sort((a, b) => a - b);
321
+ const mid = Math.floor(sorted.length / 2);
322
+ return sorted.length % 2 === 1 ? sorted[mid] : Math.round((sorted[mid - 1] + sorted[mid]) / 2);
323
+ }
324
+ function aggregate(lane, runs) {
325
+ return {
326
+ lane,
327
+ runs,
328
+ successRate: runs.length === 0 ? 0 : runs.filter((r) => r.success).length / runs.length,
329
+ medianWallClockMs: median(runs.map((r) => r.wallClockMs)),
330
+ medianTotalTokens: median(runs.map((r) => r.totalTokens)),
331
+ medianTurns: median(runs.map((r) => r.turns))
332
+ };
333
+ }
334
+ function seconds(ms) {
335
+ return (ms / 1e3).toFixed(1) + "s";
336
+ }
337
+ function toMarkdown(report) {
338
+ const lines = [
339
+ `# AgentPerf report \u2014 ${report.task.id}`,
340
+ "",
341
+ `- **URL:** ${report.url}`,
342
+ `- **Model:** ${report.model}`,
343
+ `- **Task:** ${report.task.prompt}`,
344
+ `- **Started:** ${report.startedAt}`,
345
+ "",
346
+ "| lane | success | median wall-clock | median tokens | median round-trips |",
347
+ "|------|---------|-------------------|---------------|--------------------|"
348
+ ];
349
+ for (const lane of report.lanes) {
350
+ const success = `${Math.round(lane.successRate * 100)}% (${lane.runs.filter((r) => r.success).length}/${lane.runs.length})`;
351
+ lines.push(
352
+ `| ${lane.lane} | ${success} | ${seconds(lane.medianWallClockMs)} | ${lane.medianTotalTokens.toLocaleString()} | ${lane.medianTurns} |`
353
+ );
354
+ }
355
+ const tools = report.lanes.find((l) => l.lane === "tools");
356
+ const dom = report.lanes.find((l) => l.lane === "dom");
357
+ if (tools && dom && tools.medianTotalTokens > 0 && tools.medianWallClockMs > 0) {
358
+ lines.push(
359
+ "",
360
+ `**DOM lane pays ${(dom.medianTotalTokens / tools.medianTotalTokens).toFixed(1)}x the tokens and ${(dom.medianWallClockMs / tools.medianWallClockMs).toFixed(1)}x the wall-clock of the tools lane** (medians; failed runs included in success rate, excluded from nothing).`
361
+ );
362
+ }
363
+ lines.push("", "## Runs", "");
364
+ lines.push("| lane | # | success | wall-clock | tokens | round-trips | actions | failure |");
365
+ lines.push("|------|---|---------|------------|--------|-------------|---------|---------|");
366
+ for (const lane of report.lanes) {
367
+ lane.runs.forEach((r, i) => {
368
+ lines.push(
369
+ `| ${r.lane} | ${i + 1} | ${r.success ? "\u2713" : "\u2717"} | ${seconds(r.wallClockMs)} | ${r.totalTokens.toLocaleString()} | ${r.turns} | ${r.actions} | ${r.failure ?? ""} |`
370
+ );
371
+ });
372
+ }
373
+ lines.push("");
374
+ return lines.join("\n");
375
+ }
376
+ function writeReport(report, outDir) {
377
+ const stamp = report.startedAt.replace(/[:.]/g, "-");
378
+ const dir = join(outDir, stamp);
379
+ mkdirSync(dir, { recursive: true });
380
+ const json = join(dir, "report.json");
381
+ const md = join(dir, "report.md");
382
+ writeFileSync(json, JSON.stringify(report, null, 2));
383
+ writeFileSync(md, toMarkdown(report));
384
+ return { json, md };
385
+ }
386
+
387
+ export {
388
+ runAgentLoop,
389
+ HOST_SHIM,
390
+ runToolsLane,
391
+ runDomLane,
392
+ aggregate,
393
+ toMarkdown,
394
+ writeReport
395
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ aggregate,
4
+ runDomLane,
5
+ runToolsLane,
6
+ toMarkdown,
7
+ writeReport
8
+ } from "./chunk-BGU3NILX.js";
9
+
10
+ // src/cli.ts
11
+ import { readFileSync } from "fs";
12
+ var BUILTIN_TASKS = {
13
+ booking: {
14
+ id: "booking",
15
+ prompt: "You are on the booking page of the Fringe & Co. salon. Book the 'Beard trim' service for Dana Smith (dana@example.com): pick any open slot on the earliest available day, complete the booking, and report the confirmation code the page shows.",
16
+ successPattern: "FR-[A-Z0-9]{5}",
17
+ maxTurns: 20
18
+ }
19
+ };
20
+ function arg(name, fallback) {
21
+ const index = process.argv.indexOf(`--${name}`);
22
+ if (index !== -1 && process.argv[index + 1]) return process.argv[index + 1];
23
+ return fallback;
24
+ }
25
+ async function main() {
26
+ if (process.argv[2] !== "run") {
27
+ console.log("Usage: agentperf run --url <url> [--lane both|tools|dom] [--runs 3] [--model <model>]");
28
+ process.exit(process.argv[2] ? 1 : 0);
29
+ }
30
+ const url = arg("url");
31
+ if (!url) throw new Error("--url is required");
32
+ const apiKey = process.env.AGENTPERF_API_KEY ?? process.env.OPENAI_API_KEY;
33
+ if (!apiKey) throw new Error("Set OPENAI_API_KEY (or AGENTPERF_API_KEY)");
34
+ const llm = {
35
+ apiKey,
36
+ baseUrl: arg("base-url", process.env.OPENAI_BASE_URL ?? "https://api.openai.com/v1"),
37
+ model: arg("model", process.env.AGENTPERF_MODEL ?? "gpt-5.6-luna")
38
+ };
39
+ const taskArg = arg("task", "booking");
40
+ const task = BUILTIN_TASKS[taskArg] ?? JSON.parse(readFileSync(taskArg, "utf8"));
41
+ task.maxTurns = Number(arg("max-turns", String(task.maxTurns)));
42
+ const laneArg = arg("lane", "both");
43
+ const lanes = laneArg === "both" ? ["dom", "tools"] : [laneArg];
44
+ const runs = Number(arg("runs", "3"));
45
+ const outDir = arg("out", "results");
46
+ console.log(`AgentPerf \u2014 ${task.id} @ ${url}`);
47
+ console.log(`model ${llm.model}, ${runs} run(s) per lane: ${lanes.join(", ")}
48
+ `);
49
+ const report = {
50
+ url,
51
+ model: llm.model,
52
+ task,
53
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
54
+ lanes: []
55
+ };
56
+ for (const lane of lanes) {
57
+ const results = [];
58
+ for (let i = 1; i <= runs; i++) {
59
+ process.stdout.write(`[${lane}] run ${i}/${runs}\u2026 `);
60
+ const result = lane === "tools" ? await runToolsLane(url, task, llm) : await runDomLane(url, task, llm);
61
+ results.push(result);
62
+ console.log(
63
+ result.success ? `\u2713 ${(result.wallClockMs / 1e3).toFixed(1)}s, ${result.totalTokens} tokens, ${result.turns} turns` : `\u2717 ${result.failure}`
64
+ );
65
+ }
66
+ report.lanes.push(aggregate(lane, results));
67
+ }
68
+ const files = writeReport(report, outDir);
69
+ console.log("\n" + toMarkdown(report));
70
+ console.log(`Report: ${files.md}`);
71
+ }
72
+ main().catch((error) => {
73
+ console.error(error instanceof Error ? error.message : error);
74
+ process.exit(1);
75
+ });
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Minimal OpenAI-compatible chat client with tool calling. No SDK — the
3
+ * harness talks to any /chat/completions endpoint (OpenAI, or a compatible
4
+ * provider via --base-url) and accounts every token it spends.
5
+ */
6
+ interface LlmConfig {
7
+ apiKey: string;
8
+ baseUrl: string;
9
+ model: string;
10
+ }
11
+ interface LlmToolDef {
12
+ name: string;
13
+ description: string;
14
+ parameters: Record<string, unknown>;
15
+ }
16
+
17
+ type Lane = "tools" | "dom";
18
+ interface TaskSpec {
19
+ id: string;
20
+ /** The instruction handed to the agent, identical across lanes. */
21
+ prompt: string;
22
+ /**
23
+ * Regex (source string) that must match the page's visible text when the
24
+ * task is genuinely done — checked by the harness, never by the model.
25
+ */
26
+ successPattern: string;
27
+ /** Hard cap on model round-trips before the run is failed. */
28
+ maxTurns: number;
29
+ }
30
+ interface RunMetrics {
31
+ lane: Lane;
32
+ taskId: string;
33
+ success: boolean;
34
+ /** Why a run failed, when it did. */
35
+ failure?: string;
36
+ wallClockMs: number;
37
+ /** Model round-trips (chat completions). */
38
+ turns: number;
39
+ /** Tool/browser actions executed. */
40
+ actions: number;
41
+ promptTokens: number;
42
+ completionTokens: number;
43
+ totalTokens: number;
44
+ }
45
+ interface LaneAggregate {
46
+ lane: Lane;
47
+ runs: RunMetrics[];
48
+ successRate: number;
49
+ medianWallClockMs: number;
50
+ medianTotalTokens: number;
51
+ medianTurns: number;
52
+ }
53
+ interface BenchmarkReport {
54
+ url: string;
55
+ model: string;
56
+ task: TaskSpec;
57
+ startedAt: string;
58
+ lanes: LaneAggregate[];
59
+ }
60
+
61
+ declare global {
62
+ interface Window {
63
+ __agentperf: {
64
+ listTools: () => Array<{
65
+ name: string;
66
+ description: string;
67
+ inputSchema: Record<string, unknown>;
68
+ }>;
69
+ call: (name: string, args: Record<string, unknown>) => Promise<{
70
+ content: Array<{
71
+ type: string;
72
+ text: string;
73
+ }>;
74
+ isError?: boolean;
75
+ }>;
76
+ };
77
+ }
78
+ }
79
+ declare function runToolsLane(url: string, task: TaskSpec, llm: LlmConfig): Promise<RunMetrics>;
80
+ declare function runDomLane(url: string, task: TaskSpec, llm: LlmConfig): Promise<RunMetrics>;
81
+
82
+ /**
83
+ * The agent loop both lanes share, so nothing about the driver differs
84
+ * between them except the tools it holds. task_complete is a harness tool —
85
+ * the model claims completion, the harness verifies it against the page.
86
+ */
87
+
88
+ interface LoopOutcome {
89
+ turns: number;
90
+ actions: number;
91
+ promptTokens: number;
92
+ completionTokens: number;
93
+ claimedDone: boolean;
94
+ claimSummary: string;
95
+ failure?: string;
96
+ }
97
+ declare function runAgentLoop(options: {
98
+ llm: LlmConfig;
99
+ systemPrompt: string;
100
+ taskPrompt: string;
101
+ tools: LlmToolDef[];
102
+ invoke: (name: string, args: Record<string, unknown>) => Promise<string>;
103
+ maxTurns: number;
104
+ }): Promise<LoopOutcome>;
105
+
106
+ declare function aggregate(lane: Lane, runs: RunMetrics[]): LaneAggregate;
107
+ declare function toMarkdown(report: BenchmarkReport): string;
108
+ declare function writeReport(report: BenchmarkReport, outDir: string): {
109
+ json: string;
110
+ md: string;
111
+ };
112
+
113
+ /**
114
+ * Injected before any page script runs. Implements enough of the WebMCP
115
+ * standard (`document.modelContext.registerTool`) that the harness can act
116
+ * as the agent host in stock Chromium — no browser flag, no origin trial.
117
+ * Registered tools are captured and called through `window.__agentperf`.
118
+ */
119
+ declare const HOST_SHIM = "\n(() => {\n const tools = new Map();\n const api = {\n listTools: () =>\n Array.from(tools.values()).map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema || { type: \"object\", properties: {} },\n annotations: t.annotations || {}\n })),\n call: async (name, args) => {\n const tool = tools.get(name);\n if (!tool) {\n return {\n content: [{ type: \"text\", text: \"No tool named \\\"\" + name + \"\\\" is registered on this page.\" }],\n isError: true\n };\n }\n const result = await tool.execute(args || {});\n if (typeof result === \"string\") return { content: [{ type: \"text\", text: result }] };\n return result;\n }\n };\n Object.defineProperty(window, \"__agentperf\", { value: api });\n\n const modelContext = {\n registerTool: (tool, options) => {\n tools.set(tool.name, tool);\n if (options && options.signal) {\n options.signal.addEventListener(\"abort\", () => { tools.delete(tool.name); });\n }\n },\n getTools: async () => api.listTools()\n };\n Object.defineProperty(document, \"modelContext\", { value: modelContext, configurable: true });\n Object.defineProperty(navigator, \"modelContext\", { value: modelContext, configurable: true });\n})();\n";
120
+
121
+ export { type BenchmarkReport, HOST_SHIM, type Lane, type LaneAggregate, type RunMetrics, type TaskSpec, aggregate, runAgentLoop, runDomLane, runToolsLane, toMarkdown, writeReport };
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ import {
2
+ HOST_SHIM,
3
+ aggregate,
4
+ runAgentLoop,
5
+ runDomLane,
6
+ runToolsLane,
7
+ toMarkdown,
8
+ writeReport
9
+ } from "./chunk-BGU3NILX.js";
10
+ export {
11
+ HOST_SHIM,
12
+ aggregate,
13
+ runAgentLoop,
14
+ runDomLane,
15
+ runToolsLane,
16
+ toMarkdown,
17
+ writeReport
18
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "agentperf",
3
+ "version": "0.1.0",
4
+ "description": "Measure what AI agents pay to use a website: the same task via DOM driving vs. WebMCP tool calls — wall-clock, tokens, round-trips, success rate.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/N-45div/AgentPerf.git",
9
+ "directory": "packages/harness"
10
+ },
11
+ "keywords": [
12
+ "webmcp",
13
+ "benchmark",
14
+ "agents",
15
+ "mcp",
16
+ "playwright",
17
+ "agentperf"
18
+ ],
19
+ "type": "module",
20
+ "bin": {
21
+ "agentperf": "./dist/cli.js"
22
+ },
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md"
34
+ ],
35
+ "dependencies": {
36
+ "playwright": "^1.49.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^22.0.0",
40
+ "tsup": "^8.3.0",
41
+ "typescript": "^5.7.0",
42
+ "vitest": "^3.0.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup src/cli.ts src/index.ts --format esm --dts --clean",
46
+ "test": "vitest run",
47
+ "typecheck": "tsc -p tsconfig.json"
48
+ }
49
+ }