The Open Framework for Building Agents
perf: end benchmark turns when the agent is done (#2249)
OwenKephart5678b9ee0762
diff --git a/apps/benchmarks/README.md b/apps/benchmarks/README.mdindex 0f4ee6bd9..cbd12a8cc 100644--- a/apps/benchmarks/README.md+++ b/apps/benchmarks/README.md@@ -17,8 +17,17 @@ pnpm benchmark author-000-imessage --model kimi-k3pnpm benchmark author-000-imessage --treatment baselinepnpm benchmark author-000-imessage --drypnpm benchmark author-000-imessage --verbose+pnpm benchmark author-000-imessage --keep-failures```+`--keep-failures` keeps a run the runner judged an infrastructure failure — a stalled turn, a+sandbox error — as the final result instead of discarding it. Use it while iterating on the+harness, when the failure itself is what you want to read.++Set `EVE_BENCHMARK_TRACE_PARTS=1` to print every stream part the harness receives with the gap+since the previous one. The harness decides a turn is over by reading those parts, so this is what+to reach for when a turn ends too early or hangs past its closing message.+Use `--base` to compare a local Git revision with the working tree:```sh@@ -57,6 +66,17 @@ pnpm benchmark:timings results/current/<timestamp>/<case>/run-1Pass `--json` to print the original timing artifact. Vercel Sandbox and AI Gateway credentials arerequired.+To read a whole results directory at once — pass/fail, agent time against setup time, turn and tool+counts, tokens, and any stalled turns:++```sh+node scripts/analyze.mjs results/current/<timestamp>+```++Pass `--docs` to also list, per run, which docs page the agent entered at and every page it went on+to read. That is the fastest way to see whether a documentation change moved agents toward the page+that answers the task or sent them spidering.+## Publish canonical resultsCanonical publication compares the `baseline` and `guided` treatments with the same eve revision,@@ -77,8 +97,9 @@ results cannot be reproduced from committed source and should not be committed aWithout `--models`, publication covers the complete configured model matrix. Use `--models` topublish or refresh selected model rows. The published suite currently includes weather-tool,-new-project, OpenAPI connection, packaged skill, conditional approval, and custom channel cases.-The iMessage case remains available for local runs but is excluded from the published matrix. Each+new-project, OpenAPI connection, packaged skill, conditional approval, custom channel, and digest+schedule cases. The iMessage case remains available for local runs but is excluded from the+published matrix. Eachcell runs three times. Completed cells are memoized by `@vercel/agent-eval`; pass `--force` onlywhen every cell should run again. A successful run writes aggregate results to`apps/docs/lib/evals/benchmark-results.json`. The public file contains outcomes and timing, notdiff --git a/apps/benchmarks/evals/author-000-imessage/CASE.ts b/apps/benchmarks/evals/author-000-imessage/CASE.tsindex f0e0bd725..852e05da9 100644--- a/apps/benchmarks/evals/author-000-imessage/CASE.ts+++ b/apps/benchmarks/evals/author-000-imessage/CASE.ts@@ -7,20 +7,7 @@ export default defineAuthoringCase({startingPoint: simpleProject,setup: imessageSetup,async interact({ send }) {- const firstTurn = await send(- "Set up iMessage for this agent. I can provide a phone number if you need it.",- );- if (!asksForPhoneNumber(firstTurn.text)) {- throw new Error(- `Expected the agent to ask for the user's phone number on its first turn. Received: ${JSON.stringify(firstTurn.text)}`,- );- }+ await send("Set up iMessage for this agent. I can provide a phone number if you need it.");await send(PHONE_NUMBER);},});--function asksForPhoneNumber(text: string): boolean {- return /\b(?:what(?:'s| is)?|which)\s+(?:is\s+)?(?:your\s+)?(?:phone|imessage)\s+number\b|\b(?:please|can|could|would)\s+(?:you\s+)?(?:provide|share|enter|give|tell me)\b[\s\S]{0,40}\b(?:your\s+)?(?:phone|imessage)\s+number\b|\b(?:i\s+)?(?:need|require)\s+(?:your\s+)?(?:phone|imessage)\s+number\b/i.test(- text,- );-}diff --git a/apps/benchmarks/evals/author-000-imessage/EVAL.ts b/apps/benchmarks/evals/author-000-imessage/EVAL.tsindex 112385280..181f0e2e5 100644--- a/apps/benchmarks/evals/author-000-imessage/EVAL.ts+++ b/apps/benchmarks/evals/author-000-imessage/EVAL.ts@@ -12,11 +12,15 @@ test("installs the discovered iMessage registry item through the headless setupexpect(commandLog).toMatch(/--answer(?:=|\s+)["']?phoneNumber=/i);});-test("records the agent's phone-number request", () => {+test("asks the user for the phone number instead of inventing one", () => {+ const assistant = transcript.filter((entry) => entry.role === "assistant");+ const request = /phone number|imessage number|number to (?:use|register|receive)/i;expect(- transcript- .filter((entry) => entry.role === "assistant")- .some((entry) => /phone number|imessage number/i.test(entry.content)),+ assistant.some(+ (entry) =>+ request.test(entry.content) ||+ (entry.toolCalls ?? []).some((call) => request.test(JSON.stringify(call.input))),+ ),).toBe(true);});diff --git a/apps/benchmarks/evals/author-002-new-project/EVAL.ts b/apps/benchmarks/evals/author-002-new-project/EVAL.tsindex fb45b91c4..33d0d0168 100644--- a/apps/benchmarks/evals/author-002-new-project/EVAL.ts+++ b/apps/benchmarks/evals/author-002-new-project/EVAL.ts@@ -4,8 +4,7 @@ import { expect, test } from "vitest";import { subjectDefaultAgentModel } from "./grader.js";-test("creates a complete eve project", () => {- expect(existsSync("agent/agent.ts")).toBe(true);+test("creates a complete eve project in place", () => {expect(existsSync("agent/channels/eve.ts")).toBe(true);expect(existsSync("agent/instructions.md")).toBe(true);@@ -17,10 +16,17 @@ test("creates a complete eve project", () => {expect(packageJson.scripts?.build).toBe("eve build");});-test("authors the requested identity without replacing the default model", () => {- expect(readFileSync("agent/instructions.md", "utf8")).toMatch(/Wayfinder/i);- expect(readFileSync("agent/instructions.md", "utf8")).toMatch(/travel/i);- expect(readFileSync("agent/agent.ts", "utf8")).toContain(- `model: "${subjectDefaultAgentModel()}"`,- );+test("authors the requested identity without pinning a different model", () => {+ const instructions = readFileSync("agent/instructions.md", "utf8");+ expect(instructions).toMatch(/Wayfinder/i);+ expect(instructions).toMatch(/travel/i);++ // `agent/agent.ts` is optional, and omitting it selects the same default the+ // scaffold pins explicitly. Both shapes satisfy "use the default model"; a+ // different model id does not.+ if (existsSync("agent/agent.ts")) {+ expect(readFileSync("agent/agent.ts", "utf8")).toContain(+ `model: "${subjectDefaultAgentModel()}"`,+ );+ }});diff --git a/apps/benchmarks/evals/author-003-deploy-new-project/EVAL.ts b/apps/benchmarks/evals/author-003-deploy-new-project/EVAL.tsindex d9e789177..a991d3b56 100644--- a/apps/benchmarks/evals/author-003-deploy-new-project/EVAL.ts+++ b/apps/benchmarks/evals/author-003-deploy-new-project/EVAL.ts@@ -5,8 +5,11 @@ import { authoringEval } from "./grader.js";const { commands, worldEvents } = authoringEval();const commandLog = commands.join("\n");-test("uses eve deploy to create and link the named Vercel project without prompting", () => {- expect(commandLog).toMatch(/eve\s+deploy[^\n]*--project(?:=|\s+)field-notes/i);+test("reaches the named Vercel project through eve without prompting", () => {+ // The project name can be established by `eve link` or passed to `eve deploy`;+ // both end at the same linked project, so the world events below are what+ // decide whether the deployment actually happened.+ expect(commandLog).toMatch(/eve\s+(?:link|deploy)[^\n]*--project(?:=|\s+)field-notes/i);expect(commandLog).toMatch(/eve\s+deploy[^\n]*--non-interactive/i);expect(commandLog).toMatch(/eve\s+deploy[^\n]*--yes/i);expect(commands).not.toContainEqual(diff --git a/apps/benchmarks/evals/author-007-digest-schedule/CASE.ts b/apps/benchmarks/evals/author-007-digest-schedule/CASE.tsnew file mode 100644index 000000000..85a00f83d--- /dev/null+++ b/apps/benchmarks/evals/author-007-digest-schedule/CASE.ts@@ -0,0 +1,10 @@+import { defineAuthoringCase, simpleProject } from "../../lib/authoring-case.js";++export default defineAuthoringCase({+ startingPoint: simpleProject,+ async interact({ send }) {+ await send(+ "Put the agent on a cron: every weekday at 9am UTC, run it on a short prompt asking for a status digest. Nothing needs to be delivered anywhere — the run log is fine.",+ );+ },+});diff --git a/apps/benchmarks/evals/author-007-digest-schedule/EVAL.ts b/apps/benchmarks/evals/author-007-digest-schedule/EVAL.tsnew file mode 100644index 000000000..8efc4868b--- /dev/null+++ b/apps/benchmarks/evals/author-007-digest-schedule/EVAL.ts@@ -0,0 +1,35 @@+import { existsSync, readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { expect, test } from "vitest";++const schedulesPath = "agent/schedules";++function scheduleFiles(): ReadonlyArray<string> {+ if (!existsSync(schedulesPath)) return [];+ return readdirSync(schedulesPath, { recursive: true, withFileTypes: true })+ .filter((entry) => entry.isFile() && /\.(?:ts|md)$/.test(entry.name))+ .map((entry) => join(entry.parentPath, entry.name));+}++function scheduleSource(): string {+ const files = scheduleFiles();+ expect(files).toHaveLength(1);+ return readFileSync(files[0], "utf8");+}++test("declares the digest as a schedule under agent/schedules", () => {+ expect(scheduleFiles()).toHaveLength(1);+ const source = scheduleSource();+ // Either authoring form is fine: `defineSchedule` in TypeScript, or a plain+ // `.md` file whose frontmatter carries the cron.+ expect(source).toMatch(/defineSchedule\s*\(|^---$/m);+});++test("fires on a weekday 9am UTC cron", () => {+ expect(scheduleSource()).toMatch(/cron\s*:\s*["']0 9 \* \* (?:1-5|MON-FRI)["']/i);+});++test("takes the schedule name from its path", () => {+ expect(scheduleSource()).not.toMatch(/^\s*name\s*:/m);+});diff --git a/apps/benchmarks/lib/benchmark-config.test.mjs b/apps/benchmarks/lib/benchmark-config.test.mjsindex bf1756822..ed01bb1e0 100644--- a/apps/benchmarks/lib/benchmark-config.test.mjs+++ b/apps/benchmarks/lib/benchmark-config.test.mjs@@ -27,6 +27,7 @@ test("publishes only compatibility-validated models", () => {"author-004-packaged-skill","author-005-conditional-approval","author-006-custom-channel",+ "author-007-digest-schedule",]);assert.throws(() => findPublishedBenchmarkModel("grok-4-6"),diff --git a/apps/benchmarks/lib/benchmark-config.ts b/apps/benchmarks/lib/benchmark-config.tsindex 99137b74d..8b11d41f6 100644--- a/apps/benchmarks/lib/benchmark-config.ts+++ b/apps/benchmarks/lib/benchmark-config.ts@@ -97,6 +97,7 @@ export const publishedBenchmark = {"author-004-packaged-skill","author-005-conditional-approval","author-006-custom-channel",+ "author-007-digest-schedule",],runs: 3,} as const;diff --git a/apps/benchmarks/lib/experiment.ts b/apps/benchmarks/lib/experiment.tsindex f447286ac..f18c9a4bc 100644--- a/apps/benchmarks/lib/experiment.ts+++ b/apps/benchmarks/lib/experiment.ts@@ -30,7 +30,9 @@ export function authoringExperiment(options: {scripts: ["typecheck", "build"],runs: options.runs ?? 1,earlyExit: false,- timeout: 900,+ // Lower this when iterating on a case that stalls, so a hung turn surfaces+ // in minutes instead of consuming the full budget.+ timeout: Number(process.env.EVE_BENCHMARK_TIMEOUT ?? 900),sandbox: "vercel",copyFiles: "changed",agentOptions: {diff --git a/apps/benchmarks/lib/harness-agent.ts b/apps/benchmarks/lib/harness-agent.tsindex 8ba587c0d..b15b036c7 100644--- a/apps/benchmarks/lib/harness-agent.ts+++ b/apps/benchmarks/lib/harness-agent.ts@@ -4,6 +4,7 @@ import type { HarnessAgentSession } from "@ai-sdk/harness/agent";import { HarnessAgent } from "@ai-sdk/harness/agent";import { createOpenCode } from "@ai-sdk/harness-opencode";import type { Agent, AgentRunResult } from "@vercel/agent-eval";+import { z } from "zod";import type {AuthoringCase,@@ -26,7 +27,41 @@ import type { AuthoringTokenUsage, AuthoringTranscriptEntry } from "./protocol.jimport { BenchmarkTimings } from "./timing.js";const HARNESS_BRIDGE_PORT = 4172;-const BOOTSTRAP_VERSION = "v6";+const BOOTSTRAP_VERSION = "v8";+// A turn that stops producing output should end the turn, not the eval: the+// remaining turns still run and the graders still see what the agent did.+const TURN_TIMEOUT_SECONDS = Number(process.env.EVE_BENCHMARK_TURN_TIMEOUT ?? 480);+// A turn that has produced no chunk for this long is waiting on the runtime, not+// working. The bound is one slow tool call: the bridge reports a call and its+// result together once the call returns, so an install that takes minutes looks+// from here like silence rather than work in flight.+const TURN_STALL_SECONDS = Number(process.env.EVE_BENCHMARK_TURN_STALL ?? 240);+// The runtime frequently never closes a turn whose last act was the model+// talking, so silence after a closing message has to end the turn on its own.+// Long enough that a pause before the next tool call is not mistaken for one.+const CLOSING_IDLE_MILLIS = 45_000;+// How long to let an aborted turn settle before starting the next one.+const TURN_SETTLE_MILLIS = 15_000;++// The coding agent's own question tool is the one place it can ask the user+// mid-turn. Left unanswered it waits for a human and the runtime stops driving+// the turn, so the harness answers it immediately and points the agent at the+// channel this benchmark can answer on: its reply, which the case's next `send`+// responds to.+type AuthoringHarnessAgent = HarnessAgent<+ ReturnType<typeof createOpenCode>,+ typeof INTERACTIVE_QUESTION_TOOL+>;++const INTERACTIVE_QUESTION_TOOL = {+ question: {+ description: "Ask the user a question and wait for their answer.",+ inputSchema: z.looseObject({}),+ execute: async () =>+ "The user cannot answer an interactive prompt in this environment. Ask the question in your reply instead and end your turn; the user answers in their next message.",+ },+};+export function createAuthoringAgent(subject: {readonly model: string;readonly archive: Uint8Array;@@ -96,15 +131,13 @@ export function createAuthoringAgent(subject: {port: HARNESS_BRIDGE_PORT,}),sandbox,+ tools: INTERACTIVE_QUESTION_TOOL,sandboxConfig: {workDir: WORKSPACE,bootstrapHash: bootstrapHash(authoringCase, subject),onBootstrap: async ({ session: bootstrap, workDir }) => {const bootstrapSandbox = bootstrap as HarnessV1NetworkSandboxSession;const context = setupContext(bootstrapSandbox, workDir);- await timings.measure("subject.case-bootstrap", async () => {- for (const setup of setups) await setup.onBootstrap?.(context);- });log("[setup] building the selected eve source");await bootstrapSubject(bootstrapSandbox,@@ -113,6 +146,13 @@ export function createAuthoringAgent(subject: {subject.archive,timings,);+ // Case setup runs against the finished starting point. A setup that+ // installs a fixture dependency would otherwise create the project's+ // `package.json` itself, and `eve init` would then treat the+ // workspace as an existing package and skip its own scaffold.+ await timings.measure("subject.case-bootstrap", async () => {+ for (const setup of setups) await setup.onBootstrap?.(context);+ });},onSession: async ({ session: current, sessionWorkDir }) => {activeSandbox = current as HarnessV1NetworkSandboxSession;@@ -146,21 +186,34 @@ export function createAuthoringAgent(subject: {if (verbose) console.log(`[user] ${prompt}`);const turn = transcript.filter((entry) => entry.role === "user").length;const result = await timings.measure(`agent.turn.${turn}`, () =>- verbose- ? streamTurn(agent, session!, prompt, options.timeout, options.signal)- : generateTurn(agent, session!, prompt, options.timeout, options.signal),+ runTurn({+ agent,+ session: session!,+ prompt,+ timeout: options.timeout,+ verbose,+ abortSignal: options.signal,+ }),);const toolCalls = result.toolCalls;const usage = result.usage;transcript.push({ role: "assistant", content: result.text, toolCalls, usage });- timings.record(`agent.turn.${turn}.summary`, 0, "success", {+ const details: Record<string, string | number | boolean> = {promptCharacters: prompt.length,responseCharacters: result.text.length,toolCalls: toolCalls.length,inputTokens: usage.inputTokens,outputTokens: usage.outputTokens,reasoningTokens: usage.reasoningTokens,- });+ };+ if (result.stall !== undefined) details.stall = result.stall;+ timings.record(+ `agent.turn.${turn}.summary`,+ 0,+ result.stall === undefined ? "success" : "failure",+ details,+ );+ if (result.stall !== undefined) log(`[turn ${turn}] ${result.stall}`);commands.push(...shellCommands(result.toolCalls));return { text: result.text, toolCalls };},@@ -171,6 +224,7 @@ export function createAuthoringAgent(subject: {? workspace: `${workspace}/${authoringCase.projectDirectory}`;const context = setupContext(activeSandbox, workspace);+ await prepareGraderDirectory(context);await context.write(`${AGENT_EVAL_DIRECTORY}/results.json`,JSON.stringify({ o11y: { shellCommands: commands.map((command) => ({ command })) } }),@@ -243,6 +297,9 @@ export function createAuthoringAgent(subject: {} catch (error) {timings.record("run.total", Date.now() - startedAt, "failure");if (activeSandbox !== undefined && workspace !== undefined) {+ await prepareGraderDirectory(setupContext(activeSandbox, workspace)).catch(+ () => undefined,+ );await Promise.all([setupContext(activeSandbox, workspace).write(`${AGENT_EVAL_DIRECTORY}/harness-transcript.json`,@@ -272,49 +329,175 @@ export function createAuthoringAgent(subject: {};}-async function generateTurn(- agent: HarnessAgent,- session: HarnessAgentSession,- prompt: string,- timeout: number,- abortSignal?: AbortSignal,-): Promise<AuthoringTurn & { usage: AuthoringTokenUsage }> {- const result = await agent.generate({ session, prompt, timeout, abortSignal });- return {- text: result.text,- toolCalls: authoringToolCalls(result.toolCalls),- usage: normalizeUsage(result.usage),- };+interface AuthoringTurnResult extends AuthoringTurn {+ readonly usage: AuthoringTokenUsage;+ /** Set when the turn did not finish on its own and was cut short. */+ readonly stall?: string;}-async function streamTurn(- agent: HarnessAgent,- session: HarnessAgentSession,- prompt: string,- timeout: number,- abortSignal?: AbortSignal,-): Promise<AuthoringTurn & { usage: AuthoringTokenUsage }> {- const result = await agent.stream({ session, prompt, timeout, abortSignal });+// One streaming path for every turn, so a turn that never finishes still yields+// the text and tool calls it produced. The underlying runtime can leave a turn+// open indefinitely after the model's last message, and a turn that consumed the+// whole eval budget used to discard the transcript along with it.+async function runTurn(input: {+ readonly agent: AuthoringHarnessAgent;+ readonly session: HarnessAgentSession;+ readonly prompt: string;+ readonly timeout: number;+ readonly verbose: boolean;+ readonly abortSignal?: AbortSignal;+}): Promise<AuthoringTurnResult> {+ const { agent, session, prompt, timeout, verbose } = input;+ const steps: string[] = [];+ const toolCalls: Array<{ name: string; input: unknown }> = [];+ const usage = {+ inputTokens: 0,+ outputTokens: 0,+ reasoningTokens: 0,+ cachedInputTokens: 0,+ cacheWriteTokens: 0,+ };+ let current = "";let lineOpen = false;- for await (const part of result.fullStream) {- if (part.type === "text-delta") {- if (!lineOpen) {- process.stdout.write("[assistant] ");- lineOpen = true;+ const turnTimeout = Math.min(timeout, TURN_TIMEOUT_SECONDS);+ let stall: string | undefined;++ // The runtime routinely leaves a turn open after the model's last message and+ // honors neither the total nor the per-chunk budget the SDK passes down, so+ // the harness has to decide when a turn is over. Text the model never follows+ // with a tool call is its closing message, so silence after it ends the turn;+ // silence anywhere else can still be work in flight.+ const controller = new AbortController();+ const abort = () => controller.abort();+ input.abortSignal?.addEventListener("abort", abort, { once: true });+ const deadline = Date.now() + turnTimeout * 1000;++ try {+ const result = await agent.stream({+ session,+ prompt,+ timeout: { totalMs: turnTimeout * 1000, chunkMs: TURN_STALL_SECONDS * 1000 },+ abortSignal: controller.signal,+ });+ const stream = result.fullStream[Symbol.asyncIterator]();+ const tracing = process.env.EVE_BENCHMARK_TRACE_PARTS === "1";+ let lastPartAt = Date.now();+ let pendingTools = 0;+ let stepCalledTool = false;+ let turnLooksDone = false;+ for (;;) {+ const idle = pendingTools > 0 ? Number.POSITIVE_INFINITY : idleBudget(turnLooksDone);+ const budget = Math.min(idle, deadline - Date.now());+ const next = await withDeadline(stream.next(), budget);+ if (next === "expired") {+ if (Date.now() >= deadline) stall = `turn exceeded its ${turnTimeout}s budget`;+ else if (!turnLooksDone) stall = `turn produced no output for ${TURN_STALL_SECONDS}s`;+ await settleStalledTurn(stream, controller, stall ?? "turn ended on its closing message");+ break;+ }+ if (next.done === true) break;+ const part = next.value;+ if (tracing) {+ const now = Date.now();+ console.log(`[part] +${((now - lastPartAt) / 1000).toFixed(1)}s ${part.type}`);+ lastPartAt = now;}- process.stdout.write(part.text);- } else if (part.type === "tool-call") {- if (lineOpen) process.stdout.write("\n");+ if (part.type === "text-delta") {+ current += part.text;+ // Text the model is not following with a tool call is it signing off.+ // The runtime often emits nothing after that closing message, not even+ // the step boundary, so the text itself has to be the signal.+ turnLooksDone = true;+ if (verbose) {+ if (!lineOpen) process.stdout.write("[assistant] ");+ lineOpen = true;+ process.stdout.write(part.text);+ }+ continue;+ }+ if (verbose && lineOpen) process.stdout.write("\n");lineOpen = false;- console.log(`[tool] ${formatToolCall(part.toolName, part.input)}`);+ if (part.type === "tool-call") {+ // Only a tool call reopens the turn. The parts that bracket a message+ // (`text-start`, `text-end`) are not work, and treating them as work is+ // what used to hide a closing message behind the full stall budget.+ turnLooksDone = false;+ pendingTools += 1;+ stepCalledTool = true;+ toolCalls.push({ name: part.toolName, input: part.input });+ if (verbose) console.log(`[tool] ${formatToolCall(part.toolName, part.input)}`);+ } else if (part.type === "tool-result" || part.type === "tool-error") {+ pendingTools = Math.max(0, pendingTools - 1);+ } else if (part.type === "finish-step") {+ if (current.trim().length > 0) steps.push(current.trim());+ current = "";+ addUsage(usage, (part as { usage?: unknown }).usage);+ turnLooksDone = !stepCalledTool;+ stepCalledTool = false;+ } else if (part.type === "finish") {+ turnLooksDone = true;+ }+ }+ } catch (error) {+ stall = `turn did not finish: ${error instanceof Error ? error.message : String(error)}`;+ } finally {+ input.abortSignal?.removeEventListener("abort", abort);+ if (verbose && lineOpen) process.stdout.write("\n");+ }++ if (current.trim().length > 0) steps.push(current.trim());+ const turn: AuthoringTurnResult = { text: steps.join("\n\n"), toolCalls, usage };+ return stall === undefined ? turn : { ...turn, stall };+}++function idleBudget(turnLooksDone: boolean): number {+ return turnLooksDone ? CLOSING_IDLE_MILLIS : TURN_STALL_SECONDS * 1000;+}++// Aborting is what marks the turn finished. Walking away from the stream is not+// enough: the session keeps the turn open and rejects the next prompt as one+// already in progress, which loses every remaining turn of the case. Draining+// afterwards gives that settlement time to land before the next prompt.+async function settleStalledTurn(+ stream: AsyncIterator<unknown>,+ controller: AbortController,+ reason: string,+): Promise<void> {+ controller.abort(new Error(reason));+ await withDeadline(+ (async () => {+ try {+ while ((await stream.next()).done !== true);+ } catch {+ // The abort surfaces here as a rejection, which is the settlement.+ }+ })(),+ TURN_SETTLE_MILLIS,+ );+}++async function withDeadline<T>(promise: Promise<T>, millis: number): Promise<T | "expired"> {+ if (millis <= 0) return "expired";+ let timer: NodeJS.Timeout | undefined;+ try {+ return await Promise.race([+ promise,+ new Promise<"expired">((resolve) => {+ timer = setTimeout(() => resolve("expired"), millis);+ }),+ ]);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}++function addUsage(total: Record<string, number>, value: unknown): void {+ if (typeof value !== "object" || value === null) return;+ for (const [field, amount] of Object.entries(value as Record<string, unknown>)) {+ if (typeof amount === "number" && Number.isFinite(amount) && total[field] !== undefined) {+ total[field] += amount;}}- if (lineOpen) process.stdout.write("\n");- return {- text: await result.text,- toolCalls: authoringToolCalls(await result.toolCalls),- usage: normalizeUsage(await result.usage),- };}function openCodeModel(model: string): string {@@ -324,30 +507,6 @@ function openCodeModel(model: string): string {return `moonshotai/${gatewayModel}`;}-function normalizeUsage(value: unknown): AuthoringTokenUsage {- const usage = value as Record<string, unknown>;- const number = (field: string) => {- const value = usage[field];- return typeof value === "number" && Number.isFinite(value) ? value : 0;- };- return {- inputTokens: number("inputTokens"),- outputTokens: number("outputTokens"),- reasoningTokens: number("reasoningTokens"),- cachedInputTokens: number("cachedInputTokens"),- cacheWriteTokens: number("cacheWriteTokens"),- };-}--function authoringToolCalls(- toolCalls: ReadonlyArray<{ name?: string; toolName?: string; input: unknown }>,-): ReadonlyArray<{ name: string; input: unknown }> {- return toolCalls.flatMap((call) => {- const name = call.toolName ?? call.name;- return name === undefined ? [] : [{ name, input: call.input }];- });-}-function formatToolCall(name: string, input: unknown): string {if (typeof input === "object" && input !== null) {const command = (input as { command?: unknown }).command;@@ -381,16 +540,11 @@ async function bootstrapSubject(`mkdir -p /tmp/eve-package && pnpm --dir ${SOURCE_ROOT}/packages/eve pack --pack-destination /tmp/eve-package && mv $(find /tmp/eve-package -name '*.tgz' -print -quit) ${EVE_PACKAGE_PATH} && ln -sf ${SOURCE_ROOT}/packages/eve/bin/eve.js /usr/local/bin/eve && command -v eve`,),);- const artifactsRoot = `${workspace}/${AGENT_EVAL_DIRECTORY}`;const workspaceCommands: string[] = [];if (workspaceKind === "scaffolded") {workspaceCommands.push(`cd ${shellQuote(workspace)} && AI_AGENT=benchmark eve init .`);}- workspaceCommands.push(- `mkdir -p ${artifactsRoot}`,- `printf '{"private":true,"type":"module"}\\n' >${artifactsRoot}/package.json`,- "command -v vitest >/dev/null",- );+ workspaceCommands.push("command -v vitest >/dev/null");if (workspaceKind === "scaffolded") {workspaceCommands.push(`test -f ${workspace}/package.json`);}@@ -419,6 +573,15 @@ function setupContext(};}+// Created only after the agent's turns finish: an `empty` starting point has to+// look empty to `eve init .`, which refuses to scaffold into a directory that+// already holds entries it does not recognize.+async function prepareGraderDirectory(context: AuthoringSetupContext): Promise<void> {+ await context.run(+ `mkdir -p ${AGENT_EVAL_DIRECTORY} && printf '{"private":true,"type":"module"}\\n' >${AGENT_EVAL_DIRECTORY}/package.json`,+ );+}+async function installBaselineEveWrapper(context: AuthoringSetupContext): Promise<void> {await context.run(`cli_path="/usr/local/bin/eve"diff --git a/apps/benchmarks/lib/load-authoring-case.test.mjs b/apps/benchmarks/lib/load-authoring-case.test.mjsindex 467e2b18a..d8408c2e0 100644--- a/apps/benchmarks/lib/load-authoring-case.test.mjs+++ b/apps/benchmarks/lib/load-authoring-case.test.mjs@@ -34,36 +34,16 @@ test("loads the named project output directory", async () => {assert.equal(authoringCase.projectDirectory, "wayfinder");});-test("requires an iMessage phone-number request before supplying the number", async () => {- const authoringCase = await loadAuthoringCase(resolve(evalsRoot, "author-000-imessage"));- const prompts = [];- await assert.rejects(- authoringCase.interact({- send: async (prompt) => {- prompts.push(prompt);- return {- text: "iMessage needs a phone number with a carrier-level bridge.",- toolCalls: [],- };- },- }),- /Expected the agent to ask for the user's phone number/u,- );- assert.deepEqual(prompts, [- "Set up iMessage for this agent. I can provide a phone number if you need it.",- ]);-});--test("supplies the number after an iMessage phone-number request", async () => {+// Whether the agent actually asked for the number is graded by EVAL.ts against+// the recorded transcript, so the interaction itself must not depend on how the+// agent phrases its request.+test("supplies the phone number on the second turn regardless of phrasing", async () => {const authoringCase = await loadAuthoringCase(resolve(evalsRoot, "author-000-imessage"));const prompts = [];await authoringCase.interact({send: async (prompt) => {prompts.push(prompt);- return {- text: "What phone number should be registered for iMessage? (e.g., `+15551234567`)",- toolCalls: [],- };+ return { text: "Inspecting the available iMessage setup.", toolCalls: [] };},});assert.deepEqual(prompts, [diff --git a/apps/benchmarks/lib/setups/imessage.test.mjs b/apps/benchmarks/lib/setups/imessage.test.mjsindex 2f1209b0e..24dde5d56 100644--- a/apps/benchmarks/lib/setups/imessage.test.mjs+++ b/apps/benchmarks/lib/setups/imessage.test.mjs@@ -18,7 +18,7 @@ test("serves the deterministic iMessage registry item", async () => {const writes = new Map();const commands = [];const context = {- artifactsRoot: "__authoring_eval__",+ artifactsRoot: "/tmp/photon-test",run: async (command) => commands.push(command),write: async (path, content) => writes.set(path, content),};@@ -26,8 +26,8 @@ test("serves the deterministic iMessage registry item", async () => {await imessageSetup.onBootstrap(context);await imessageSetup.onSession(context);- const registry = JSON.parse(writes.get("__authoring_eval__/registry/registry.json"));- const item = JSON.parse(writes.get("__authoring_eval__/registry/channel/photon-imessage.json"));+ const registry = JSON.parse(writes.get("/tmp/photon-test/registry/registry.json"));+ const item = JSON.parse(writes.get("/tmp/photon-test/registry/channel/photon-imessage.json"));assert.deepEqual(registry.items, [{name: "channel/photon-imessage",@@ -38,10 +38,10 @@ test("serves the deterministic iMessage registry item", async () => {},]);assert.equal(item.meta.eve.setup.command, "mock-imessage-setup");+ // The absolute path must reach pnpm unprefixed; `./` in front of it would+ // normalize to a relative path and link a directory that does not exist.assert.ok(- commands.some((command) =>- command.includes("pnpm add ./__authoring_eval__/mock-imessage-setup"),- ),+ commands.some((command) => command === "pnpm add /tmp/photon-test/mock-imessage-setup"),);assert.ok(commands.some((command) => command.includes("python3 -m http.server 4173")));});diff --git a/apps/benchmarks/lib/setups/imessage.ts b/apps/benchmarks/lib/setups/imessage.tsindex 91a5f7a49..8ee733e71 100644--- a/apps/benchmarks/lib/setups/imessage.ts+++ b/apps/benchmarks/lib/setups/imessage.ts@@ -19,7 +19,11 @@ export const imessageSetup: AuthoringSetup = {),),);- await run(`pnpm add ./${setupRoot}`);+ // `setupRoot` is absolute, so this must not be prefixed with `./`: pnpm+ // would normalize the result to a relative path, link a directory that does+ // not exist, and name the dependency after the basename instead of the+ // package, leaving `eve add` unable to find the setup command.+ await run(`pnpm add ${setupRoot}`);await run(`mkdir -p ${artifactsRoot}/registry/channel`);const channel = {@@ -68,13 +72,9 @@ export const imessageSetup: AuthoringSetup = {write(`${artifactsRoot}/registry/channel/photon-imessage.json`, JSON.stringify(channel)),]);},- async onSession({ run, artifactsRoot, write }) {+ async onSession({ run, artifactsRoot }) {await run(`nohup python3 -m http.server ${REGISTRY_PORT} --directory ${artifactsRoot}/registry >${artifactsRoot}/registry.log 2>&1 </dev/null &`,);- await write(- ".claude/settings.json",- JSON.stringify({ env: { EVE_DEV_OFFICIAL_REGISTRY_URL: REGISTRY_URL } }),- );},};diff --git a/apps/benchmarks/package.json b/apps/benchmarks/package.jsonindex 5775b80ef..57b72d598 100644--- a/apps/benchmarks/package.json+++ b/apps/benchmarks/package.json@@ -17,7 +17,8 @@"@ai-sdk/sandbox-vercel": "1.0.72","@vercel/agent-eval": "1.5.0","@vercel/sandbox": "catalog:",- "jiti": "2.7.0"+ "jiti": "2.7.0",+ "zod": "catalog:"},"devDependencies": {"@types/node": "catalog:",diff --git a/apps/benchmarks/run.mjs b/apps/benchmarks/run.mjsindex 3f94640af..d12adbb1a 100644--- a/apps/benchmarks/run.mjs+++ b/apps/benchmarks/run.mjs@@ -30,6 +30,10 @@ const { values, positionals } = parseArgs({model: { type: "string", default: "claude-sonnet-5" },treatment: { type: "string", default: "guided" },verbose: { type: "boolean" },+ // The runner discards a run it decides failed for infrastructure reasons,+ // which throws away the transcript you need to tell a real stall from a+ // misjudged one.+ "keep-failures": { type: "boolean" },help: { type: "boolean", short: "h" },},strict: true,@@ -70,7 +74,9 @@ mkdirSync(join(appRoot, "results"), { recursive: true });writeExperiments(subjects, runs, benchmark, treatment, values.verbose ?? false);const executable = join(appRoot, "node_modules/.bin/agent-eval");const experimentNames = subjects.map((subject) => subject.label);-const args = values.dry ? ["status", ...experimentNames] : ["run", ...experimentNames, "--force"];+const args = values.dry+ ? ["status", ...experimentNames]+ : ["run", ...experimentNames, "--force", ...(values["keep-failures"] ? ["--ack-failures"] : [])];for (const subject of subjects) console.log(`> ${subject.label}: ${subject.description}`);const result = spawnSync(executable, args, {@@ -112,6 +118,6 @@ function parseRuns(value) {function usage() {console.log(`Usage:- pnpm benchmark [eval-name] [--model <id>] [--runs N] [--treatment baseline|guided] [--dry] [--verbose]+ pnpm benchmark [eval-name] [--model <id>] [--runs N] [--treatment baseline|guided] [--dry] [--verbose] [--keep-failures]pnpm benchmark [eval-name] --base <revision> [--head <revision>] [--model <id>] [--runs N] [--treatment baseline|guided] [--dry]`);}diff --git a/apps/benchmarks/scripts/analyze.mjs b/apps/benchmarks/scripts/analyze.mjsnew file mode 100644index 000000000..796a4c53b--- /dev/null+++ b/apps/benchmarks/scripts/analyze.mjs@@ -0,0 +1,250 @@+#!/usr/bin/env node++// Reads a benchmark results directory and reports, per case, the signals that+// matter when tuning the generated AGENTS.md and the shipped docs: outcome,+// agent cost, which docs pages the agent opened, and which grader assertions+// failed. Docs reads are recovered from shell commands because agents read+// `node_modules/eve/docs` with `cat`/`sed`/`grep` rather than a read tool.++import { existsSync, readdirSync, readFileSync } from "node:fs";+import { basename, join, resolve } from "node:path";+import { parseArgs } from "node:util";++const { values, positionals } = parseArgs({+ args: process.argv.slice(2),+ allowPositionals: true,+ options: { json: { type: "boolean" }, docs: { type: "boolean" }, help: { type: "boolean" } },+ strict: true,+});++if (values.help) {+ console.log(`Usage:+ node scripts/analyze.mjs [results-dir] [--docs] [--json]++ results-dir A run directory, a case directory, a timestamp directory, or a+ treatment directory. Defaults to the newest timestamp directory.+ --docs Aggregate docs-page reads across cases instead of per-case detail.+ --json Emit the collected records as JSON.`);+ process.exit(0);+}++const resultsRoot = resolve(import.meta.dirname, "../results");+const target =+ positionals[0] === undefined ? newestTimestamp(resultsRoot) : resolve(positionals[0]);+const runs = collectRuns(target);+if (runs.length === 0) throw new Error(`No benchmark runs found under ${target}.`);++const records = runs.map((run) => analyzeRun(run));+if (values.json) console.log(JSON.stringify(records, null, 2));+else if (values.docs) reportDocs(records);+else reportRuns(records, target);++function newestTimestamp(root) {+ const treatments = directories(root);+ const stamps = treatments.flatMap((treatment) =>+ directories(treatment).map((path) => ({ path, name: basename(path) })),+ );+ if (stamps.length === 0) throw new Error(`No results under ${root}.`);+ stamps.sort((a, b) => a.name.localeCompare(b.name));+ return stamps.at(-1).path;+}++function directories(root) {+ if (!existsSync(root)) return [];+ return readdirSync(root, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => join(root, entry.name));+}++// Accepts any depth: run dir, case dir, timestamp dir, or treatment dir.+function collectRuns(root) {+ if (existsSync(join(root, "result.json"))) return [root];+ return directories(root)+ .flatMap((child) => collectRuns(child))+ .sort();+}++function analyzeRun(runPath) {+ const result = readJson(join(runPath, "result.json"));+ const raw = readRawTranscript(join(runPath, "transcript-raw.jsonl"));+ const timings = readTimings(runPath);+ const toolCalls = raw.flatMap((entry) => entry.toolCalls);+ const commands = toolCalls.flatMap((call) => (call.command === undefined ? [] : [call.command]));+ const usage = raw.reduce(+ (total, entry) => ({+ inputTokens: total.inputTokens + (entry.usage?.inputTokens ?? 0),+ outputTokens: total.outputTokens + (entry.usage?.outputTokens ?? 0),+ reasoningTokens: total.reasoningTokens + (entry.usage?.reasoningTokens ?? 0),+ cachedInputTokens: total.cachedInputTokens + (entry.usage?.cachedInputTokens ?? 0),+ }),+ { inputTokens: 0, outputTokens: 0, reasoningTokens: 0, cachedInputTokens: 0 },+ );+ return {+ case: basename(resolve(runPath, "..")),+ run: basename(runPath),+ path: runPath,+ status: result.status,+ durationSeconds: round(result.duration),+ agentSeconds: round(sumPhases(timings, /^agent\.turn\.\d+$/) / 1000),+ setupSeconds: round(sumPhases(timings, /^(subject|session)\./) / 1000),+ turns: raw.filter((entry) => entry.role === "user").length,+ toolCalls: toolCalls.length,+ commands: commands.length,+ usage,+ docsRead: docsCounts(docsSequence(toolCalls)),+ // Which page the agent opened first. `README.md` means the routing index did+ // its job; anything else means the agent guessed or searched its way in.+ docsEntry: docsSequence(toolCalls)[0] ?? "(none)",+ registryCalls: commands.filter((command) => /\beve\s+(registry|add)\b/.test(command)).length,+ failedCommands: failedCommands(commands),+ stalls: timings+ .filter(+ (entry) => /^agent\.turn\.\d+\.summary$/.test(entry.phase) && entry.outcome !== "success",+ )+ .map((entry) => `${entry.phase}: ${entry.details?.stall ?? "did not finish"}`),+ failures: graderFailures(join(runPath, "outputs/eval.txt")),+ scriptFailures: scriptFailures(runPath),+ };+}++// Recovers `docs/<page>` paths from any tool input that mentions them, so a+// `cat`, `sed -n`, `grep -r`, or read-tool path all count as one read each. Call+// order is preserved: the first page tells you which entry point the agent used.+function docsSequence(toolCalls) {+ const pages = [];+ for (const call of toolCalls) {+ for (const text of [call.command ?? "", ...call.paths]) {+ for (const match of text.matchAll(/eve\/docs\/([\w./-]*\.mdx?)/g)) pages.push(match[1]);+ // A bare directory listing or a glob read counts as a directory probe.+ for (const match of text.matchAll(/eve\/docs\/([\w/-]+)\/(?:\*|$|\s)/g)) {+ pages.push(`${match[1]}/*`);+ }+ }+ }+ return pages;+}++function docsCounts(pages) {+ const counts = new Map();+ for (const page of pages) counts.set(page, (counts.get(page) ?? 0) + 1);+ return Object.fromEntries([...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])));+}++function failedCommands(commands) {+ // Cheap proxy for wasted effort: repeated identical commands and probes into+ // paths that the scaffold does not have.+ const seen = new Map();+ for (const command of commands) seen.set(command, (seen.get(command) ?? 0) + 1);+ return [...seen].filter(([, count]) => count > 1).map(([command, count]) => ({ command, count }));+}++function graderFailures(path) {+ if (!existsSync(path)) return [];+ const output = readFileSync(path, "utf8");+ const failures = [...output.matchAll(/^\s*(?:×|✕|FAIL)\s+(.+)$/gm)].map((match) =>+ match[1].trim(),+ );+ return [...new Set(failures)];+}++function scriptFailures(runPath) {+ const scripts = join(runPath, "outputs/scripts");+ if (!existsSync(scripts)) return [];+ return readdirSync(scripts)+ .filter((name) =>+ /error|not found|exit code [1-9]/i.test(readFileSync(join(scripts, name), "utf8")),+ )+ .map((name) => basename(name, ".txt"));+}++function readRawTranscript(path) {+ if (!existsSync(path)) return [];+ return readFileSync(path, "utf8")+ .trim()+ .split("\n")+ .filter((line) => line.length > 0)+ .map((line) => {+ const entry = JSON.parse(line);+ const content = entry.message?.content;+ const blocks = Array.isArray(content) ? content : [];+ return {+ role: entry.type,+ usage: entry.message?.usage,+ toolCalls: blocks+ .filter((block) => block.type === "tool_use")+ .map((block) => ({+ name: block.name,+ command: typeof block.input?.command === "string" ? block.input.command : undefined,+ paths: [block.input?.filePath, block.input?.path, block.input?.pattern].filter(+ (value) => typeof value === "string",+ ),+ })),+ };+ });+}++function readTimings(runPath) {+ const path = join(runPath, "project/benchmark/timings.json");+ return existsSync(path) ? readJson(path) : [];+}++function sumPhases(timings, pattern) {+ return timings+ .filter((entry) => pattern.test(entry.phase))+ .reduce((total, entry) => total + entry.durationMs, 0);+}++function readJson(path) {+ return JSON.parse(readFileSync(path, "utf8"));+}++function round(value) {+ return typeof value === "number" ? Math.round(value * 10) / 10 : 0;+}++function reportRuns(records, target) {+ console.log(`# ${target}\n`);+ for (const record of records) {+ const mark = record.status === "passed" ? "PASS" : "FAIL";+ console.log(+ `${mark} ${record.case} ${record.run} ${record.durationSeconds}s total / ${record.agentSeconds}s agent / ${record.setupSeconds}s setup`,+ );+ console.log(+ ` turns=${record.turns} tools=${record.toolCalls} in=${record.usage.inputTokens} out=${record.usage.outputTokens} reasoning=${record.usage.reasoningTokens} registry=${record.registryCalls}`,+ );+ const docs = Object.entries(record.docsRead);+ console.log(+ ` docs: entered at ${record.docsEntry}${docs.length === 0 ? "" : ` — ${docs.map(([page, count]) => (count > 1 ? `${page}×${count}` : page)).join(", ")}`}`,+ );+ for (const stall of record.stalls) console.log(` ! ${stall}`);+ for (const failure of record.failures) console.log(` ! ${failure}`);+ for (const script of record.scriptFailures) console.log(` ! script ${script}`);+ const repeats = record.failedCommands.filter((entry) => entry.count > 2);+ for (const repeat of repeats.slice(0, 3)) {+ console.log(` ~ repeated ×${repeat.count}: ${repeat.command.slice(0, 100)}`);+ }+ console.log("");+ }+ const passed = records.filter((record) => record.status === "passed").length;+ console.log(`${passed}/${records.length} passed`);+}++function reportDocs(records) {+ const totals = new Map();+ for (const record of records) {+ for (const [page, count] of Object.entries(record.docsRead)) {+ const entry = totals.get(page) ?? { reads: 0, cases: new Set() };+ entry.reads += count;+ entry.cases.add(record.case);+ totals.set(page, entry);+ }+ }+ const rows = [...totals].sort((a, b) => b[1].reads - a[1].reads || a[0].localeCompare(b[0]));+ console.log("reads cases page");+ for (const [page, entry] of rows) {+ console.log(+ `${String(entry.reads).padStart(5)} ${String(entry.cases.size).padStart(5)} ${page}`,+ );+ console.log(` ${[...entry.cases].sort().join(", ")}`);+ }+}diff --git a/apps/benchmarks/scripts/export-results.test.mjs b/apps/benchmarks/scripts/export-results.test.mjsindex c9cf59e68..2affc62bd 100644--- a/apps/benchmarks/scripts/export-results.test.mjs+++ b/apps/benchmarks/scripts/export-results.test.mjs@@ -38,7 +38,7 @@ test("exports missing cells without publishing private artifacts", () => {const output = JSON.parse(raw);assert.equal(output.schemaVersion, 1);- assert.equal(output.suite.caseCount, 6);+ assert.equal(output.suite.caseCount, 7);assert.match(output.suite.caseFingerprint, /^[0-9a-f]{64}$/u);assert.equal(output.experiments.length, 12);assert.deepEqual(@@ -52,7 +52,7 @@ test("exports missing cells without publishing private artifacts", () => {"Gemini 3.1 Pro Preview",],);- assert.equal(output.results.length, 72);+ assert.equal(output.results.length, 84);assert.ok(output.results.every((result) => result.status === "missing"));for (const privateField of ["transcript", "commands", "worldEvents", "files"]) {assert.equal(raw.includes(`"${privateField}"`), false);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 578d57514..0317d3e25 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -149,6 +149,9 @@ importers:jiti:specifier: 2.7.0version: 2.7.0+ zod:+ specifier: 'catalog:'+ version: 4.4.3devDependencies:'@types/node':specifier: 'catalog:'