Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): evals - add scoped assertion API (#314)

Andrew Barba194a8bb7bd03
diff --git a/.changeset/channel-copy-identity.md b/.changeset/channel-copy-identity.md
new file mode 100644
index 000000000..fb044e56b
--- /dev/null
+++ b/.changeset/channel-copy-identity.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Make `isChannel` recognize authored channel imports evaluated in a different local runtime bundle from the route instance.
diff --git a/.changeset/fresh-evals-scope.md b/.changeset/fresh-evals-scope.md
new file mode 100644
index 000000000..ab989250e
--- /dev/null
+++ b/.changeset/fresh-evals-scope.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Add snapshot-based turn and session assertions, lifecycle-aware tool and subagent matching, typed event checks, recorded requirements, and explicit skipped results. The simplified API uses `succeeded`/`parked`, completed calls by default, exact `count` options, and `require*` lookups so evals no longer need manual event scans or thrown assertion errors.
diff --git a/docs/evals/assertions.mdx b/docs/evals/assertions.mdx
index 51835237d..d5f15eeba 100644
--- a/docs/evals/assertions.mdx
+++ b/docs/evals/assertions.mdx
@@ -1,39 +1,51 @@
---
title: "Assertions"
-description: "Run-level methods, t.check value assertions, the matcher mini-language, and gate vs soft severity."
+description: "Scoped methods, value assertions, the matcher mini-language, and gate vs soft severity."
---
-Assertions are how an eval grades what its `test(t)` function produced. Each one **records** a result onto `t` and returns a chainable handle. The runner reads the recorded results to compute the verdict, so a single run reports every failing assertion rather than dying on the first. There are two deterministic surfaces: run-level methods on `t`, and `t.check` for grading a specific value. For model-graded assertions, see [Judge](./judge).
+Assertions are how an eval grades what its `test(t)` function produced. Each one records a result and returns a chainable handle. The runner reads every recorded result to compute the verdict, so a single run reports every failing assertion rather than dying on the first. There are two deterministic surfaces: scoped methods and `t.check` for grading a specific value. For model-graded assertions, see [Judge](./judge).
-## Run-level assertions
+## Scoped assertions
-Run-level assertions read the whole run, so they take no value. They are methods on `t` and gate by default. Several key off whether a run **parked**: paused on an unanswered human-in-the-loop (HITL) input request, waiting for an approval or answer before it can continue.
+Scoped assertions take no explicit value and gate by default. Assertions on `t` inspect the whole run after `test` finishes. Session assertions snapshot that session when called, and turn assertions inspect one immutable response. A scope is **parked** when it paused on unanswered human-in-the-loop (HITL) input.
-| Assertion | Asserts |
-| --------------------------------------------------- | --------------------------------------------------------------------------------------- |
-| `t.completed()` | The run did not fail and did not park on unanswered HITL input |
-| `t.didNotFail()` | No terminal failure and no `turn.failed`/`step.failed` events (parked runs pass) |
-| `t.waiting()` | The run parked on HITL input (for approval-shaped evals) |
-| `t.messageIncludes(token)` | Joined assistant text contains `token` (string or RegExp) |
-| `t.outputEquals(value)` / `t.outputMatches(schema)` | Deep equality or Standard Schema (e.g. Zod) validation of the agent's structured output |
-| `t.calledTool(name, opts?)` | A matching tool call happened (`input`, `output`, `isError`, `times` constraints) |
-| `t.loadedSkill(skill, opts?)` | Sugar for `t.calledTool("load_skill", { input: { skill }, ...opts })` |
-| `t.notCalledTool(name)` | No call to `name` |
-| `t.toolOrder([...names])` | Tool names appear in order (other calls may interleave) |
-| `t.usedNoTools()` | No tool calls at all |
-| `t.maxToolCalls(n)` | At most `n` tool calls |
-| `t.noFailedActions()` | No tool, subagent, or skill action reported a failure |
-| `t.calledSubagent(name, opts?)` | A subagent delegation happened (`remoteUrl`, `output` constraints) |
-| `t.event(predicate, label)` | Escape hatch: any predicate over the typed event stream |
+| Assertion | Asserts |
+| ----------------------------------------------------- | ----------------------------------------------------------------------------- |
+| `t.succeeded()` | The run did not fail and did not park on unanswered HITL input |
+| `t.parked()` | The run cleanly parked on HITL input |
+| `t.messageIncludes(token)` | Joined assistant text contains `token` (string or RegExp) |
+| `turn.outputEquals(value)` / `.outputMatches(schema)` | Deep equality or Standard Schema validation of turn/session structured output |
+| `t.calledTool(name, opts?)` | A matching tool call completed (`input`, `output`, `status`, `count`) |
+| `t.loadedSkill(skill, opts?)` | Sugar for `t.calledTool("load_skill", { input: { skill }, ...opts })` |
+| `t.notCalledTool(name)` | No request for `name` in any lifecycle state |
+| `t.toolOrder([...names])` | Tool requests appear in order |
+| `t.usedNoTools()` | No tool calls at all |
+| `t.maxToolCalls(n)` | At most `n` tool calls |
+| `t.noFailedActions()` | No tool, subagent, or skill action reported a failure |
+| `t.calledSubagent(name, opts?)` | A subagent delegation happened (`remoteUrl`, `output` constraints) |
+| `t.event(type, opts?)` / `t.notEvent(type, opts?)` | Typed event presence, data, and count matching |
+| `t.eventOrder([...matchers])` | Matching event groups occur in order |
+| `t.eventsSatisfy(label, predicate)` | Escape hatch: any predicate over the typed event stream |
-`t.completed()` subsumes `t.didNotFail()`, so reach for `completed` unless you specifically want to allow a parked run. The structured output that `t.outputEquals` and `t.outputMatches` read is the agent's structured output (see the [output schema guide](../guides/client/output-schema)).
+`succeeded()` accepts both a closed session and a healthy session left open for the next user message; it rejects protocol failures and unanswered HITL. `parked()` requires a clean HITL park. Structured output assertions live on turns and independent sessions, where the output is unambiguous (see the [output schema guide](../guides/client/output-schema)).
```ts
await t.send("What is the weather in Brooklyn?");
-t.completed();
+t.succeeded();
t.calledTool("get_weather");
```
+The same vocabulary narrows naturally in multi-turn and externally-created session evals:
+
+```ts
+const first = await t.send("Call get_weather for Brooklyn");
+first.calledTool("get_weather", { count: 1 });
+
+const attached = await t.target.attachSession(sessionId);
+attached.succeeded();
+attached.messageIncludes("Sunny");
+```
+
`t.calledTool` and `t.usedNoTools` are mutually exclusive; assert one or the other, never both in the same run.
## Value assertions with `t.check`
@@ -41,52 +53,98 @@ t.calledTool("get_weather");
`t.check(value, assertion)` grades an explicit value against a builder from `eve/evals/expect`. The value can be `t.reply`, a turn's `.message`, parsed JSON, or any local you computed:
```ts
-import { includes, equals, matches, similarity } from "eve/evals/expect";
+import { includes, equals, matches, satisfies, similarity } from "eve/evals/expect";
-t.check(t.reply, includes("sunny")); // substring (gate)
+t.check(t.reply, includes(/sunny/i)); // substring or RegExp (gate)
t.check(parsed, equals({ city: "Brooklyn" })); // deep structural equality (gate)
t.check(parsed, matches(WeatherSchema)); // Standard Schema, e.g. Zod (gate)
t.check(t.reply, similarity("Sunny, 72F")); // fuzzy 0–1 Levenshtein (soft)
+t.check(
+ latencyMs,
+ satisfies((value) => value < 1_000, "latency under one second"),
+);
```
-| Builder | Scores | Default |
-| ---------------------- | ------------------------------------------------ | ------- |
-| `includes(substring)` | value (coerced to string) contains `substring` | gate |
-| `equals(value)` | deep structural equality | gate |
-| `matches(schema)` | validates against a Standard Schema | gate |
-| `similarity(expected)` | normalized Levenshtein similarity, 1 = identical | soft |
+| Builder | Scores | Default |
+| ---------------------- | ------------------------------------------------------- | ------- |
+| `includes(value)` | coerced string contains a substring or matches a RegExp | gate |
+| `equals(value)` | deep structural equality | gate |
+| `matches(schema)` | validates against a Standard Schema | gate |
+| `similarity(expected)` | normalized Levenshtein similarity, 1 = identical | soft |
+| `satisfies(fn, label)` | custom boolean predicate | gate |
Pick the cheapest builder that captures what "correct" means. When exact match is too strict but a judge model is overkill, `similarity` is the middle ground. For nuanced grading, reach for the [judge](./judge).
## The matcher mini-language
-`t.calledTool` and `t.calledSubagent` take a matcher object: `{ input, output, isError, times }` for tools, `{ remoteUrl, output }` for subagents. Each field accepts a literal (objects partial-deep-match), a RegExp, or a function. A matcher function receives the value and returns either a boolean (acts as a predicate) or an expected value to compare against (handy for runner-assigned values like environment-provided URLs):
+`t.calledTool` and `t.calledSubagent` take matcher objects. Tools accept `{ input, output, status, count }`; subagents accept `{ remoteUrl, output, status, count }`. Calls match `status: "completed"` by default; use `"pending"`, `"failed"`, or `"rejected"` explicitly for lifecycle checks. `count` is the exact number of calls matching every supplied constraint.
+
+Matcher values accept a literal (objects partial-deep-match), a RegExp, or a predicate function that returns a boolean:
```ts
-t.calledTool("bash", { input: { command: /^pwd/ }, isError: false, times: 1 });
+t.calledTool("bash", { input: { command: /^pwd/ }, count: 1 });
t.calledTool("echo", { output: (value) => String(value).includes(marker) });
+parked.calledTool("guarded", { status: "pending", count: 1 });
+t.calledTool("guarded", { output: /approved/, count: 1 });
+
t.calledSubagent("weather", {
- remoteUrl: () => process.env.WEATHER_AGENT_URL!,
+ remoteUrl: (value) => value === process.env.WEATHER_AGENT_URL,
output: /72F/,
});
```
+`requireInputRequest` uses the same matcher language for `input`, `prompt`, and `display`. Its `optionIds` matcher receives option ids in request order; a literal array must match that complete ordered list exactly:
+
+```ts
+const request = session.requireInputRequest({
+ toolName: "ask_question",
+ optionIds: ["red", "blue"],
+});
+```
+
## Run state and derived facts
-Beyond the raw `t.events` stream, the runner derives typed facts the assertions read: tool calls (name, input, output, error state), subagent calls, and HITL input requests. A turn that leaves the session open for a next message is the normal end state of a successful turn; parking on unanswered HITL input is tracked separately, and that is what `t.completed()` and `t.waiting()` key off.
+Beyond the raw `t.events` stream, the runner derives typed facts the assertions read: tool calls (name, input, output, lifecycle status), subagent calls, and HITL input requests. A turn that leaves the session open for a next message is the normal end state of a successful turn; parking on unanswered HITL input is tracked separately.
-The built-in assertions cover almost everything. When you need to read the stream directly, `t.event(predicate, label)` is the escape hatch:
+Typed event matching covers presence, absence, exact counts, partial event data, and ordering:
```ts
-t.event(
- (events) =>
- events.some((e) => e.type === "message.completed" && e.data.message?.includes(marker)),
- "assistant reply includes the marker",
+turn.notEvent("result.completed");
+turn.eventOrder([
+ { type: "subagent.called", data: { name: "researcher" }, count: 2 },
+ { type: "subagent.completed", data: { subagentName: "researcher" }, count: 2 },
+]);
+```
+
+When a protocol invariant needs cross-event correlation, `eventsSatisfy` remains the escape hatch:
+
+```ts
+t.eventsSatisfy("assistant reply includes the marker", (events) =>
+ events.some((e) => e.type === "message.completed" && e.data.message?.includes(marker)),
);
```
+## Required preconditions
+
+Recorded assertions never throw and are not awaitable. When later control flow depends on a value, use `await t.require(value, assertion)`. It records a gate, returns the original value when it passes, and stops the test body without adding a duplicate execution error when it fails:
+
+```ts
+await t.require(
+ sessionIds,
+ satisfies((ids) => ids.length > 0, "dispatch started a session"),
+);
+await t.target.attachSession(sessionIds[0]!);
+```
+
+Use the matching `require*` lookups when dependent code needs protocol data:
+
+```ts
+const call = turn.requireToolCall("search");
+const request = session.requireInputRequest({ toolName: "guarded" });
+```
+
## Severity
Every assertion returns a chainable handle. Severity rides on the assertion, so there is no separate thresholds map to keep in sync.
diff --git a/docs/evals/cases.mdx b/docs/evals/cases.mdx
index e58df528a..762b38dc6 100644
--- a/docs/evals/cases.mdx
+++ b/docs/evals/cases.mdx
@@ -5,6 +5,14 @@ description: "Author single-turn and multi-turn evals with test(t), and fan one
Each eval file is one graded case by default, and a single file can fan out over a dataset by default-exporting an array (covered below). The runner executes each `test(t)` function against the target, captures every event, and computes a verdict from the [assertions](./assertions) you recorded. Every eval shares one shape, whether single-turn, multi-turn, human-in-the-loop (HITL), or dataset-driven: one `async test(t)` function that drives the agent and asserts inline.
+Before adding a case, create the required config at the root of `evals/`. An empty config is enough when you do not need shared judge, reporter, concurrency, or timeout settings:
+
+```ts title="evals/evals.config.ts"
+import { defineEvalConfig } from "eve/evals";
+
+export default defineEvalConfig({});
+```
+
## Single-turn evals
The common case sends one turn and asserts on the reply. `t.send(input)` resolves once the turn settles, and `t.reply` is the last assistant message:
@@ -16,7 +24,7 @@ import { includes } from "eve/evals/expect";
export default defineEval({
async test(t) {
await t.send("What is the weather in Brooklyn?");
- t.completed();
+ t.succeeded();
t.check(t.reply, includes("Sunny"));
},
});
@@ -30,7 +38,7 @@ import { defineEval } from "eve/evals";
export default defineEval({
async test(t) {
await t.send("Hello!");
- t.completed();
+ t.succeeded();
t.notCalledTool("get_weather");
},
});
@@ -42,6 +50,7 @@ Identity is the file path, so directories are the grouping mechanism. `evals/wea
```text
evals/
+├── evals.config.ts
├── weather/
│ ├── shared.ts # helpers, not an eval
│ ├── brooklyn-forecast.eval.ts
@@ -69,25 +78,21 @@ export default defineEval({
});
```
-For a precondition no built-in assertion expresses, `throw`. A thrown error marks the eval `failed` with the message in the result:
+Use scoped assertions for intermediate turns. When later control flow depends on a value-level check, `t.require` records a gate and stops the script if it fails:
```ts title="evals/session-continuity.eval.ts"
import { defineEval } from "eve/evals";
-import { includes } from "eve/evals/expect";
+import { equals } from "eve/evals/expect";
export default defineEval({
async test(t) {
- await t.send("My favorite word is marigold.");
- const firstSessionId = t.sessionId;
+ const first = await t.send("My favorite word is marigold.");
const second = await t.send("Thanks for remembering.");
- second.expectOk();
- if (t.sessionId !== firstSessionId) {
- throw new Error(`Expected one session; got ${firstSessionId} then ${t.sessionId}.`);
- }
+ await t.require(second.sessionId, equals(first.sessionId));
- t.completed();
- t.check(second.message, includes("Thanks for remembering."));
+ t.succeeded();
+ second.messageIncludes("Thanks for remembering.");
},
});
```
@@ -98,12 +103,16 @@ export default defineEval({
- `t.send(input)` sends a turn and waits for it to settle. It accepts the same input as `ClientSession.send()` (a string or a structured message) and resolves to a turn carrying `.message` and `.expectOk()`.
- `t.sendFile(text, path, mediaType?)` attaches a local file as a data URL.
-- `t.expectInputRequests(filter?)` asserts the previous turn parked on HITL input and returns the pending requests.
+- `t.requireInputRequest(filter?)` records a gate, requires exactly one pending request, and returns it. Filters match tool name, action input, prompt, display, and option ids.
- `t.respond(...responses)` answers specific pending input requests and sends them as the next turn.
- `t.respondAll(optionId)` answers every pending input request with the same option and sends the responses as the next turn.
- `t.reply` is the last assistant message (or `null`); `t.sessionId` is the current session id; `t.events` is the full typed event stream captured so far.
-Each `send` (and `respond`/`respondAll`) resolves to a turn whose `expectOk()` throws only when the turn ended failed. A session left open for a next message is the normal end state of a successful turn.
+Each `send` (and `respond`/`respondAll`) resolves to an immutable turn with `.message`, `.data`, `.events`, `.inputRequests`, `.toolCalls`, `.sessionId`, `.status`, and `.expectOk()`. Use `.sessionId` to relate turns or attach follow-up work to the session that produced a specific turn. `expectOk()` throws only when the turn ended failed; a session left open for a next message is the normal end state of a successful turn.
+
+Use `expectOk()` only when the next operation depends on that intermediate turn succeeding. A final `t.succeeded()` already records a complete-run gate.
+
+To intentionally omit an eval for the current target, call `t.skip(reason)` before sending messages or recording assertions. Skipped evals are reported separately and do not affect the exit code.
Events from every session are captured in the result and artifacts. `t.log(message)` records debug lines into the eval artifact; `--verbose` also streams them to stdout as evals run. `t.signal` is an `AbortSignal` that fires on timeout.
@@ -126,7 +135,7 @@ export default rows.map((row) =>
description: row.task,
async test(t) {
await t.send(row.prompt);
- t.completed();
+ t.succeeded();
t.check(t.reply, equals(row.sql));
},
}),
diff --git a/docs/evals/judge.mdx b/docs/evals/judge.mdx
index 5560d8fe3..810eb73a2 100644
--- a/docs/evals/judge.mdx
+++ b/docs/evals/judge.mdx
@@ -11,7 +11,7 @@ import { defineEval } from "eve/evals";
export default defineEval({
async test(t) {
await t.send("Explain quantum tunneling to a 10-year-old.");
- t.completed();
+ t.succeeded();
t.judge.autoevals.closedQA("uses no math beyond arithmetic").atLeast(0.8);
},
});
@@ -52,7 +52,7 @@ t.judge.autoevals.closedQA("cites a source").atLeast(0.6); // soft, fails under
t.judge.autoevals.factuality(reference).gate(0.8); // hard gate at 0.8
```
-A judge runs once per assertion and burns tokens, so reach for one only when nothing deterministic will do. Several slow judge calls in one eval can fan out with `await Promise.all([...])`.
+A judge runs once per assertion and burns tokens, so reach for one only when nothing deterministic will do. Judge calls start when recorded, and the runner waits for all of them during finalization; assertion handles themselves are intentionally not awaitable.
## Configuring the judge model
diff --git a/docs/evals/overview.mdx b/docs/evals/overview.mdx
index c6936038e..4c38bbdf1 100644
--- a/docs/evals/overview.mdx
+++ b/docs/evals/overview.mdx
@@ -33,7 +33,7 @@ export default defineEval({
description: "Basic message and tool-usage coverage for the weather agent.",
async test(t) {
await t.send("What is the weather in Brooklyn?");
- t.completed();
+ t.succeeded();
t.calledTool("get_weather");
t.check(t.reply, includes("Sunny"));
},
@@ -62,14 +62,14 @@ Everything is optional. `judge` sets the default model for [LLM-as-judge](./judg
`t` is both the driver and the assertion surface. There are no separate `input`, `run`, `checks`, or `scores` fields. You write ordinary control flow, sending turns and asserting inline.
-- **Drive** the agent: `t.send(...)`, `t.respond(...)`, `t.respondAll(...)`, `t.sendFile(...)`, `t.expectInputRequests(...)`, `t.newSession()`. Read what came back with `t.reply` (the last assistant message), `t.sessionId`, and `t.events`. See [Cases](./cases).
+- **Drive** the agent: `t.send(...)`, `t.respond(...)`, `t.respondAll(...)`, `t.sendFile(...)`, `t.requireInputRequest(...)`, `t.newSession()`. Read what came back with `t.reply` (the last assistant message), `t.sessionId`, and `t.events`. See [Cases](./cases).
- **Assert** with three surfaces, covered next.
## Three assertion surfaces
Each surface matches a genuinely different kind of judgment:
-- **Run-level methods** read the whole run, like `t.completed()`, `t.calledTool("get_weather")`, `t.usedNoTools()`, and `t.toolOrder([...])`. They take no value because they observe the run itself. See [Assertions](./assertions).
+- **Scoped methods** read the final whole run on `t`, snapshot one independent session when invoked there, or inspect one immutable `EveEvalTurn`. See [Assertions](./assertions).
- **`t.check(value, assertion)`** grades an explicit value with a deterministic builder from `eve/evals/expect`, such as `t.check(t.reply, includes("sunny"))`. Grade `t.reply`, an intermediate draft, parsed JSON, or anything else. See [Assertions](./assertions).
- **`t.judge.autoevals.*`** is the LLM-as-judge surface, like `t.judge.autoevals.closedQA("cites a source")`. It grades `t.reply` by default and uses the configured judge model, never the agent under test. See [Judge](./judge).
@@ -83,12 +83,14 @@ Every assertion returns a chainable handle, so severity rides on the assertion i
Override per assertion: `.gate(threshold?)` promotes to a hard gate, `.soft(threshold?)` demotes to tracked, and `.atLeast(threshold)` is a soft assertion with a bar.
```ts
-t.completed(); // gate
+t.succeeded(); // gate
t.calledTool("get_weather").soft(); // record as a metric, don't gate
t.judge.autoevals.closedQA("cites a source"); // soft, tracked (no threshold)
t.judge.autoevals.factuality(reference).atLeast(0.7); // soft, gated under --strict at 0.7
```
+Use `await t.require(value, assertion)` for a gate that must pass before the script can safely continue. Use `t.skip(reason)` as the first operation for an intentionally unsupported target capability.
+
## Run evals with eve eval
```bash
@@ -101,7 +103,7 @@ Exit code `0` means every eval passed its gates. See [Running evals](./running)
## A good baseline
-Most apps do fine with a few small smoke evals. Assert behavior with `t.completed()` plus one or two content checks, keep dataset fixtures in `evals/data/`, and reach for a judge or Braintrust only when you need fuzzy grading or shared result review. In CI, run `eve eval --strict` so soft threshold misses fail the build too.
+Most apps do fine with a few small smoke evals. Assert behavior with `t.succeeded()` plus one or two content checks, keep dataset fixtures in `evals/data/`, and reach for a judge or Braintrust only when you need fuzzy grading or shared result review. In CI, run `eve eval --strict` so soft threshold misses fail the build too.
## What to read next
diff --git a/docs/evals/reporters.mdx b/docs/evals/reporters.mdx
index 0bfc055a9..46349a170 100644
--- a/docs/evals/reporters.mdx
+++ b/docs/evals/reporters.mdx
@@ -33,7 +33,7 @@ export default defineEval({
reporters: [Braintrust({ projectName: "weather-agent" })],
async test(t) {
await t.send("What is the weather in Brooklyn?");
- t.completed();
+ t.succeeded();
},
});
```
@@ -52,7 +52,7 @@ Braintrust needs its SDK installed in the app and credentials in the environment
eve eval --strict --junit .eve/junit.xml
```
-Each eval becomes one `<testcase>` named by its path-derived id; failed gates and execution errors land as failure messages on the matching test case, so CI surfaces them inline.
+Each eval becomes one `<testcase>` named by its path-derived id; failed gates and execution errors become failures, while `t.skip(reason)` produces a JUnit `<skipped>` result.
## Custom reporters
diff --git a/docs/evals/running.mdx b/docs/evals/running.mdx
index 1b1a28d1d..7a64659dc 100644
--- a/docs/evals/running.mdx
+++ b/docs/evals/running.mdx
@@ -26,10 +26,12 @@ Positional ids match exactly or by directory prefix: `eve eval weather` runs `ev
| Code | Means |
| ---- | ------------------------------------------------------------------------------- |
-| `0` | Every eval passed its gates (and soft thresholds, under `--strict`) |
+| `0` | Every non-skipped eval passed its gates (and soft thresholds, under `--strict`) |
| `1` | Any eval failed (a failed gate, an execution error, or a strict threshold miss) |
| `2` | Configuration error |
+An eval that calls `t.skip(reason)` is reported as skipped, does not count as passed or failed, and never changes the exit code.
+
## Artifacts
Each run drops artifacts under `.eve/evals/<timestamp>/`: a run `summary.json`, a `results.jsonl` index, and per-eval assertion results, verdicts, captured event streams, and `t.log` lines under `evals/`. The console output stays tight on purpose; when an eval fails, the artifact has the full story.
diff --git a/docs/evals/targets.mdx b/docs/evals/targets.mdx
index 9a3d14315..63ece9d31 100644
--- a/docs/evals/targets.mdx
+++ b/docs/evals/targets.mdx
@@ -16,7 +16,7 @@ export default defineEval({
async test(t) {
const { sessionIds } = await t.target.dispatchSchedule("heartbeat");
await t.target.attachSession(sessionIds[0]!);
- t.completed();
+ t.succeeded();
t.calledTool("send_report");
},
});
@@ -26,7 +26,7 @@ export default defineEval({
- `t.target.dispatchSchedule(id)` triggers a [schedule](../schedules) through the dev-only schedule route and returns the session ids it created. It works only against a target with dev routes enabled (the local `eve eval` dev server, or a deployment running in development mode), and throws otherwise.
- `t.target.attachSession(sessionId, { startIndex? })` consumes one turn from a session created outside the eval, by a channel or a schedule, so its events feed the run-level assertions. `startIndex` skips events before that position, so a session already partway through its stream resumes from where you left off rather than replaying from the start.
-Sessions attached this way are full `EveEvalSession`s: you can keep driving them with `send` and read their event streams. The run-level assertions on `t` (`t.completed()`, `t.calledTool(...)`) read the whole run, including attached sessions.
+Sessions attached this way are full `EveEvalSession`s: you can keep driving them and assert directly on that session (`session.succeeded()`, `session.calledTool(...)`). Aggregate assertions on `t` continue to read the whole run, including every attached session.
## Authentication
diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.ts
index ac64d532f..4d7935e36 100644
--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.ts
+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.ts
@@ -13,14 +13,12 @@ export default defineEval({
description: "Session runtime smoke: client context.",
async test(t) {
- const turn = await t.send({
+ await t.send({
clientContext: [`include the exact token ${CLIENT_CONTEXT_TOKEN} verbatim`],
message: "Say hello.",
});
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.messageIncludes(CLIENT_CONTEXT_TOKEN);
},
});
diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/image-attachment.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/image-attachment.eval.ts
index a3be592ad..0499f090e 100644
--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/image-attachment.eval.ts
+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/image-attachment.eval.ts
@@ -16,15 +16,13 @@ export default defineEval({
// Eval modules execute from a build cache, so assets resolve against
// the app root (`eve eval` runs with the app as cwd), not import.meta.
const filePath = join(process.cwd(), "evals/assets/cat-image.png");
- const turn = await t.sendFile(
+ await t.sendFile(
"What animal is in this image? Answer in one short sentence.",
filePath,
"image/png",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.messageIncludes(/cat/i);
},
});
diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.ts
index c2f1181a4..696133678 100644
--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.ts
+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/multi-turn-session.eval.ts
@@ -1,4 +1,5 @@
import { defineEval } from "eve/evals";
+import { equals } from "eve/evals/expect";
/**
* Core session-route runtime behavior: multi-turn session continuity.
@@ -10,20 +11,13 @@ export default defineEval({
description: "Session runtime smoke: multi-turn.",
async test(t) {
- await t.send("My favorite word is marigold. Remember it.");
- const firstSessionId = t.sessionId;
+ const first = await t.send("My favorite word is marigold. Remember it.");
const second = await t.send("What is my favorite word? Reply with just the word.");
- second.expectOk();
- if (t.sessionId !== firstSessionId) {
- throw new Error(
- `Expected both turns in one session; got ${String(firstSessionId)} then ${String(t.sessionId)}.`,
- );
- }
+ await t.require(second.sessionId, equals(first.sessionId));
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.messageIncludes(/marigold/i);
},
});
diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.ts
index 232a03ccc..c9ba22d3b 100644
--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.ts
+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.ts
@@ -1,5 +1,4 @@
import { defineEval } from "eve/evals";
-import { matches } from "eve/evals/expect";
import { z } from "zod";
const StructuredOutput = z.object({ count: z.number().int(), title: z.string() });
@@ -26,14 +25,11 @@ export default defineEval({
const plain = await t.send("Reply normally without structured output.");
plain.expectOk();
- if (plain.events.some((event) => event.type === "result.completed")) {
- throw new Error("outputSchema leaked into the following turn: saw result.completed.");
- }
+ plain.notEvent("result.completed");
- t.didNotFail();
- t.completed();
+ t.succeeded();
// Real models choose their own field values; assert schema conformance
// rather than an exact payload.
- t.check(structured.data, matches(StructuredOutput));
+ structured.outputMatches(StructuredOutput);
},
});
diff --git a/e2e/fixtures/agent-basic-runtime/evals/text-reply.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/text-reply.eval.ts
index a1ee612f2..f40d8b784 100644
--- a/e2e/fixtures/agent-basic-runtime/evals/text-reply.eval.ts
+++ b/e2e/fixtures/agent-basic-runtime/evals/text-reply.eval.ts
@@ -14,8 +14,7 @@ export default defineEval({
// the model would otherwise phrase its reply.
async test(t) {
await t.send('Reply with exactly the text "smoke ping" and nothing else.');
- t.completed();
- t.didNotFail();
+ t.succeeded();
t.messageIncludes("smoke ping");
t.usedNoTools();
},
diff --git a/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts b/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts
index f9e0cd603..353d2ce49 100644
--- a/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts
+++ b/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts
@@ -1,4 +1,5 @@
import { defineEval } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
import { postChannel } from "./shared.js";
@@ -16,29 +17,20 @@ export default defineEval({
const payload = await postChannel<{ ok: boolean; sessionId?: string }>(t.target, "/webhook", {
message: "Reply with the single word: hello.",
});
- if (payload.ok !== true || typeof payload.sessionId !== "string") {
- throw new Error(`Unexpected webhook response: ${JSON.stringify(payload)}`);
- }
-
- const session = await t.target.attachSession(payload.sessionId);
-
- const failures = session.events.filter(
- (event) =>
- event.type === "session.failed" ||
- event.type === "turn.failed" ||
- event.type === "step.failed",
+ await t.require(
+ payload,
+ satisfies(
+ (value: { ok: boolean; sessionId?: string }) =>
+ value.ok === true && typeof value.sessionId === "string",
+ "webhook returns a session id",
+ ),
);
- if (failures.length > 0) {
- throw new Error(`Cross-channel turn failed: ${JSON.stringify(failures)}`);
- }
- const completed = session.events.filter((event) => event.type === "message.completed");
- if (completed.length === 0) {
- throw new Error("Expected at least one message.completed event in the handoff session.");
- }
+ const session = await t.target.attachSession(payload.sessionId!);
+ session.succeeded();
+ session.event("message.completed");
+ session.messageIncludes("hello");
- t.didNotFail();
- t.completed();
- t.messageIncludes("hello");
+ t.succeeded();
},
});
diff --git a/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger-approval.eval.ts b/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger-approval.eval.ts
index a263f2667..6ec1f961b 100644
--- a/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger-approval.eval.ts
+++ b/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger-approval.eval.ts
@@ -1,4 +1,3 @@
-import type { HandleMessageStreamEvent } from "eve/client";
import { defineEval } from "eve/evals";
const SEARCH_TOOL = "connection_search";
@@ -19,68 +18,39 @@ export default defineEval({
);
parked.expectOk();
- const [request] = t.expectInputRequests({
+ t.requireInputRequest({
display: "confirmation",
+ optionIds: ["approve", "deny"],
toolName: TFL_APPROVAL_JOURNEY_MODES_TOOL,
});
- if (request === undefined) {
- throw new Error("Expected the OpenAPI connection tool to request approval.");
- }
-
- const optionIds = (request.options ?? []).map((option) => option.id);
- if (!optionIds.includes("approve") || !optionIds.includes("deny")) {
- throw new Error(`Expected approve/deny options, got [${optionIds.join(", ")}].`);
- }
- if (toolResultOutputs(parked.events, TFL_APPROVAL_JOURNEY_MODES_TOOL).length > 0) {
- throw new Error("Approval-gated OpenAPI tool executed before approval.");
- }
+ parked.calledTool(TFL_APPROVAL_JOURNEY_MODES_TOOL, { status: "pending", count: 1 });
const approved = await t.respondAll("approve");
approved.expectOk();
- const outputs = toolResultOutputs(t.events, TFL_APPROVAL_JOURNEY_MODES_TOOL);
- if (outputs.length !== 1) {
- throw new Error(
- `Expected "${TFL_APPROVAL_JOURNEY_MODES_TOOL}" to execute exactly once after approval; saw ${outputs.length}.`,
- );
- }
- const [output] = outputs;
- const modes = extractModeNames(output.body);
- if (!modes.has("bus") || !modes.has("tube")) {
- throw new Error(
- `Expected TfL modes to include bus and tube after approval, got ${JSON.stringify([...modes])}`,
- );
- }
+ approved.event("action.result", {
+ data: {
+ result: { kind: "tool-result", toolName: TFL_APPROVAL_JOURNEY_MODES_TOOL },
+ status: "completed",
+ },
+ count: 1,
+ });
- t.didNotFail();
- t.completed();
- t.calledTool(SEARCH_TOOL, { isError: false });
+ t.succeeded();
+ t.calledTool(SEARCH_TOOL);
+ t.calledTool(TFL_APPROVAL_JOURNEY_MODES_TOOL, {
+ output: hasBusAndTube,
+ count: 1,
+ });
t.messageIncludes(/\bbus\b/iu);
t.messageIncludes(/\btube\b/iu);
},
});
-function toolResultOutputs(
- events: readonly HandleMessageStreamEvent[],
- toolName: string,
-): Record<string, unknown>[] {
- const outputs: Record<string, unknown>[] = [];
- for (const event of events) {
- if (event.type !== "action.result" || event.data.status === "rejected") {
- continue;
- }
- const result = event.data.result;
- if (result.kind !== "tool-result" || result.toolName !== toolName) {
- continue;
- }
- if (typeof result.output !== "object" || result.output === null) {
- throw new Error(
- `Expected object output from "${toolName}"; got ${JSON.stringify(result.output)}.`,
- );
- }
- outputs.push(result.output as Record<string, unknown>);
- }
- return outputs;
+function hasBusAndTube(value: unknown): boolean {
+ if (typeof value !== "object" || value === null) return false;
+ const modes = extractModeNames((value as { body?: unknown }).body);
+ return modes.has("bus") && modes.has("tube");
}
function extractModeNames(body: unknown): Set<string> {
diff --git a/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger.eval.ts b/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger.eval.ts
index d2fef78be..c7a009f88 100644
--- a/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger.eval.ts
+++ b/e2e/fixtures/agent-openapi-swagger/evals/tfl-swagger.eval.ts
@@ -1,4 +1,3 @@
-import type { EveEvalTurn } from "eve/evals";
import { defineEval } from "eve/evals";
const SEARCH_TOOL = "connection_search";
@@ -16,38 +15,28 @@ export default defineEval({
"Reply with the exact words `bus` and `tube` if both mode names are present in the tool result.",
].join("\n"),
);
- turn.expectOk();
- const output = requireToolOutput(turn, TFL_JOURNEY_MODES_TOOL);
- const modes = extractModeNames(output.body);
- if (!modes.has("bus") || !modes.has("tube")) {
- throw new Error(
- `Expected TfL modes to include bus and tube, got ${JSON.stringify([...modes])}`,
- );
- }
+ turn.calledTool(TFL_JOURNEY_MODES_TOOL, {
+ output: hasBusAndTube,
+ count: 1,
+ });
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.toolOrder([SEARCH_TOOL, TFL_JOURNEY_MODES_TOOL]);
- t.calledTool(SEARCH_TOOL, { isError: false });
- t.calledTool(TFL_JOURNEY_MODES_TOOL, { isError: false, times: 1 });
+ t.calledTool(SEARCH_TOOL);
+ t.calledTool(TFL_JOURNEY_MODES_TOOL, {
+ output: hasBusAndTube,
+ count: 1,
+ });
t.messageIncludes(/\bbus\b/iu);
t.messageIncludes(/\btube\b/iu);
},
});
-function requireToolOutput(turn: EveEvalTurn, toolName: string): Record<string, unknown> {
- const call = turn.toolCalls.find((candidate) => candidate.name === toolName);
- if (call === undefined) {
- const seen = turn.toolCalls.map((candidate) => candidate.name).join(", ");
- throw new Error(`Expected a "${toolName}" call in this turn; saw [${seen}].`);
- }
- if (typeof call.output !== "object" || call.output === null) {
- throw new Error(
- `Expected object output from "${toolName}"; got ${JSON.stringify(call.output)}.`,
- );
- }
- return call.output as Record<string, unknown>;
+function hasBusAndTube(value: unknown): boolean {
+ if (typeof value !== "object" || value === null) return false;
+ const modes = extractModeNames((value as { body?: unknown }).body);
+ return modes.has("bus") && modes.has("tube");
}
function extractModeNames(body: unknown): Set<string> {
diff --git a/e2e/fixtures/agent-schedules/evals/quiet-delivery.eval.ts b/e2e/fixtures/agent-schedules/evals/quiet-delivery.eval.ts
index 1e5660cfb..17d116d38 100644
--- a/e2e/fixtures/agent-schedules/evals/quiet-delivery.eval.ts
+++ b/e2e/fixtures/agent-schedules/evals/quiet-delivery.eval.ts
@@ -1,5 +1,5 @@
-import type { HandleMessageStreamEvent } from "eve/client";
import { defineEval } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
/** Proves an every-minute polling schedule can leave its target channel silent. */
export default defineEval({
@@ -7,71 +7,32 @@ export default defineEval({
async test(t) {
if (!t.target.capabilities.devRoutes) {
- t.log("Target has no dev routes (deployed build); schedule dispatch is dev-only. Skipping.");
- return;
+ t.skip("Target has no dev routes; schedule dispatch is dev-only.");
}
const dispatch = await t.target.dispatchSchedule("quiet-alerts");
- if (dispatch.scheduleId !== "quiet-alerts") {
- throw new Error(
- `Expected quiet-alerts dispatch, got ${JSON.stringify(dispatch.scheduleId)}.`,
- );
- }
- const [sessionId] = dispatch.sessionIds;
- if (sessionId === undefined) {
- throw new Error("Quiet schedule dispatch returned no session ids.");
- }
-
- const session = await t.target.attachSession(sessionId);
- const failures = session.events.filter(isFailure);
- if (failures.length > 0) {
- throw new Error(`Quiet schedule session failed: ${formatTypes(failures)}`);
- }
-
- const checkedAlerts = session.events.some(
- (event) =>
- event.type === "action.result" &&
- event.data.result.kind === "tool-result" &&
- event.data.result.toolName === "check-alerts",
- );
- if (!checkedAlerts) {
- throw new Error(`Expected check-alerts to run; saw ${formatTypes(session.events)}.`);
- }
-
- if (!session.events.some((event) => event.type === "session.waiting")) {
- throw new Error(
- `Expected the target channel session to reach its waiting boundary; saw ${formatTypes(session.events)}.`,
- );
- }
-
- const terminalMessages = session.events.flatMap((event) =>
- event.type === "message.completed" && event.data.finishReason !== "tool-calls"
- ? [event.data.message]
- : [],
+ await t.require(dispatch.scheduleId, equals("quiet-alerts"));
+ await t.require(
+ dispatch.sessionIds,
+ satisfies(
+ (sessionIds: readonly string[]) => sessionIds.length > 0,
+ "schedule started a session",
+ ),
);
- if (!terminalMessages.includes(null)) {
- throw new Error(
- `Expected an empty-delivery completion; saw ${JSON.stringify(terminalMessages)}.`,
- );
- }
- const delivered = terminalMessages.filter((message) => message !== null);
- if (delivered.length > 0) {
- throw new Error(
- `Expected empty delivery, but the schedule produced ${JSON.stringify(delivered)}.`,
- );
- }
+ const sessionId = dispatch.sessionIds[0]!;
- t.didNotFail();
- t.completed();
+ const session = await t.target.attachSession(sessionId);
+ session.succeeded();
+ session.calledTool("check-alerts");
+ session.event("session.waiting");
+ session.event("message.completed", {
+ data: (data) => data.finishReason !== "tool-calls" && data.message === null,
+ count: 1,
+ });
+ session.notEvent("message.completed", {
+ data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
+ });
+
+ t.succeeded();
},
});
-
-function isFailure(event: HandleMessageStreamEvent): boolean {
- return (
- event.type === "session.failed" || event.type === "turn.failed" || event.type === "step.failed"
- );
-}
-
-function formatTypes(events: readonly HandleMessageStreamEvent[]): string {
- return JSON.stringify(events.map((event) => event.type));
-}
diff --git a/e2e/fixtures/agent-schedules/evals/schedule-dispatch.eval.ts b/e2e/fixtures/agent-schedules/evals/schedule-dispatch.eval.ts
index 73eca9b45..9f1be2007 100644
--- a/e2e/fixtures/agent-schedules/evals/schedule-dispatch.eval.ts
+++ b/e2e/fixtures/agent-schedules/evals/schedule-dispatch.eval.ts
@@ -1,5 +1,5 @@
-import type { HandleMessageStreamEvent } from "eve/client";
import { defineEval } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
// Token returned by agent/tools/record-heartbeat.ts; mirrored here because the
// agent tree compiles independently of the eval tree.
@@ -20,64 +20,30 @@ export default defineEval({
async test(t) {
if (!t.target.capabilities.devRoutes) {
- t.log("Target has no dev routes (deployed build); schedule dispatch is dev-only. Skipping.");
- return;
+ t.skip("Target has no dev routes; schedule dispatch is dev-only.");
}
const dispatch = await t.target.dispatchSchedule("heartbeat");
- if (dispatch.scheduleId !== "heartbeat") {
- throw new Error(
- `Expected scheduleId "heartbeat"; got ${JSON.stringify(dispatch.scheduleId)}.`,
- );
- }
- const [sessionId] = dispatch.sessionIds;
- if (sessionId === undefined) {
- throw new Error("Schedule dispatch returned no session ids.");
- }
+ await t.require(dispatch.scheduleId, equals("heartbeat"));
+ await t.require(
+ dispatch.sessionIds,
+ satisfies(
+ (sessionIds: readonly string[]) => sessionIds.length > 0,
+ "schedule started a session",
+ ),
+ );
+ const sessionId = dispatch.sessionIds[0]!;
t.log(`heartbeat dispatched session ${sessionId}`);
// Replay the dispatched session's stream from durable storage and drive it
// to a turn boundary.
const session = await t.target.attachSession(sessionId);
- const failures = session.events.filter(
- (event) =>
- event.type === "session.failed" ||
- event.type === "turn.failed" ||
- event.type === "step.failed",
- );
- if (failures.length > 0) {
- throw new Error(`Dispatched schedule session failed: ${formatTypes(failures)}`);
- }
-
- const heartbeat = heartbeatToolResults(session.events);
- if (heartbeat.length === 0) {
- throw new Error(
- `Expected at least one record-heartbeat result in the dispatched session; saw event types ${formatTypes(session.events)}.`,
- );
- }
- if (!heartbeat.some((output) => output.includes(HEARTBEAT_TOKEN))) {
- throw new Error(
- `record-heartbeat ran but no result carried the token ${HEARTBEAT_TOKEN}: ${JSON.stringify(heartbeat)}`,
- );
- }
+ session.succeeded();
+ session.calledTool("record-heartbeat", {
+ output: new RegExp(HEARTBEAT_TOKEN),
+ });
- t.didNotFail();
- t.completed();
+ t.succeeded();
},
});
-
-function heartbeatToolResults(events: readonly HandleMessageStreamEvent[]): string[] {
- const results: string[] = [];
- for (const event of events) {
- if (event.type !== "action.result") continue;
- const result = event.data.result;
- if (result.kind !== "tool-result" || result.toolName !== "record-heartbeat") continue;
- results.push(JSON.stringify(result.output ?? ""));
- }
- return results;
-}
-
-function formatTypes(events: readonly HandleMessageStreamEvent[]): string {
- return JSON.stringify(events.map((event) => event.type));
-}
diff --git a/e2e/fixtures/agent-schedules/evals/stream-resume.eval.ts b/e2e/fixtures/agent-schedules/evals/stream-resume.eval.ts
index 4fc509a85..0c4ad6173 100644
--- a/e2e/fixtures/agent-schedules/evals/stream-resume.eval.ts
+++ b/e2e/fixtures/agent-schedules/evals/stream-resume.eval.ts
@@ -1,5 +1,5 @@
-import type { HandleMessageStreamEvent } from "eve/client";
import { defineEval } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
/**
* Proof that `GET /eve/v1/session/:id/stream?startIndex=N` replays missed
@@ -22,22 +22,17 @@ export default defineEval({
"3. Reply with the final `value` from `lookup-step-b` verbatim, with no extra commentary.",
].join("\n"),
);
- turn.expectOk();
- const sessionId = t.sessionId;
- if (sessionId === undefined) {
- throw new Error("Session did not produce a session id after the first turn.");
- }
+ const sessionId = turn.sessionId;
const fullLog = turn.events;
// Split at the first actions.requested so the replay tail spans tool
// execution and the final assistant message.
const cutoff = fullLog.findIndex((event) => event.type === "actions.requested");
- if (cutoff <= 0) {
- throw new Error(
- `Expected an actions.requested event after index 0. Event types: ${formatTypes(fullLog)}`,
- );
- }
+ await t.require(
+ cutoff,
+ satisfies((value: number) => value > 0, "actions.requested appears after index 0"),
+ );
t.log(`full turn produced ${fullLog.length} events; replaying from index ${cutoff}`);
// Reconnect at startIndex=cutoff through the authenticated client and
@@ -46,25 +41,11 @@ export default defineEval({
const replayed = resumed.events;
const expected = fullLog.slice(cutoff);
- if (replayed.length !== expected.length) {
- throw new Error(
- `Replayed tail length (${replayed.length}) does not match expected (${expected.length}). ` +
- `replayed: ${formatTypes(replayed)} expected: ${formatTypes(expected)}`,
- );
- }
- for (let i = 0; i < expected.length; i += 1) {
- if (replayed[i]!.type !== expected[i]!.type) {
- throw new Error(
- `Event order divergence at tail index ${i}: replayed=${replayed[i]!.type} expected=${expected[i]!.type}`,
- );
- }
- }
+ t.check(
+ replayed.map((event) => event.type),
+ equals(expected.map((event) => event.type)),
+ );
t.log(`replayed ${replayed.length} events from index ${cutoff}; matches the durable log`);
-
- t.didNotFail();
+ t.succeeded();
},
});
-
-function formatTypes(events: readonly HandleMessageStreamEvent[]): string {
- return JSON.stringify(events.map((event) => event.type));
-}
diff --git a/e2e/fixtures/agent-skills/evals/skills/auto-invocation.eval.ts b/e2e/fixtures/agent-skills/evals/skills/auto-invocation.eval.ts
index 8abaf710e..2d23d3762 100644
--- a/e2e/fixtures/agent-skills/evals/skills/auto-invocation.eval.ts
+++ b/e2e/fixtures/agent-skills/evals/skills/auto-invocation.eval.ts
@@ -1,24 +1,7 @@
-import type { ActionResultStreamEvent, HandleMessageStreamEvent } from "eve/client";
import { defineEval } from "eve/evals";
const ECHO_MARKER_TOKEN = "skill-echo-marker-ok-V8Y2";
-/**
- * Every `load_skill` action.result in the stream must report
- * `status: "completed"`, and at least one must exist. A load that resolves
- * but fails inside the runtime resolver still emits a result event, so a
- * presence-only check would miss it.
- */
-function loadSkillResultsCompleted(events: readonly HandleMessageStreamEvent[]): boolean {
- const results = events.filter(
- (event): event is ActionResultStreamEvent =>
- event.type === "action.result" &&
- event.data.result.kind === "tool-result" &&
- event.data.result.toolName === "load_skill",
- );
- return results.length > 0 && results.every((event) => event.data.status === "completed");
-}
-
/**
* Skill smoke eval:
* a flat markdown skill (skills/echo-marker.md) is advertised, loaded on
@@ -28,15 +11,11 @@ function loadSkillResultsCompleted(events: readonly HandleMessageStreamEvent[]):
export default defineEval({
description: "Skills smoke: markdown skill auto-invocation via load_skill.",
async test(t) {
- const turn = await t.send(
- "Please use the echo marker skill and follow its instructions exactly.",
- );
- turn.expectOk();
+ await t.send("Please use the echo marker skill and follow its instructions exactly.");
- t.didNotFail();
- t.completed();
- t.calledTool("load_skill");
- t.event(loadSkillResultsCompleted, "all load_skill results completed");
+ t.succeeded();
+ t.loadedSkill("echo-marker");
+ t.noFailedActions();
t.messageIncludes(ECHO_MARKER_TOKEN);
},
});
diff --git a/e2e/fixtures/agent-skills/evals/skills/dynamic-instructions.eval.ts b/e2e/fixtures/agent-skills/evals/skills/dynamic-instructions.eval.ts
index a866a178f..2288f93f4 100644
--- a/e2e/fixtures/agent-skills/evals/skills/dynamic-instructions.eval.ts
+++ b/e2e/fixtures/agent-skills/evals/skills/dynamic-instructions.eval.ts
@@ -11,11 +11,9 @@ const DYNAMIC_INSTRUCTIONS_TOKEN = "dynamic-instructions-ok-M3K8";
export default defineEval({
description: "Skills smoke: dynamic instructions injection at session start.",
async test(t) {
- const turn = await t.send("Acknowledge this message.");
- turn.expectOk();
+ await t.send("Acknowledge this message.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.messageIncludes(DYNAMIC_INSTRUCTIONS_TOKEN);
},
});
diff --git a/e2e/fixtures/agent-skills/evals/skills/dynamic-skill-map.eval.ts b/e2e/fixtures/agent-skills/evals/skills/dynamic-skill-map.eval.ts
index dbbf97545..0139dbda1 100644
--- a/e2e/fixtures/agent-skills/evals/skills/dynamic-skill-map.eval.ts
+++ b/e2e/fixtures/agent-skills/evals/skills/dynamic-skill-map.eval.ts
@@ -11,13 +11,9 @@ const DYNAMIC_MULTI_ALPHA_TOKEN = "dynamic-multi-alpha-Q8V3";
export default defineEval({
description: "Skills smoke: dynamic skill-map resolution.",
async test(t) {
- const turn = await t.send(
- "Please use the dynamic multi alpha skill and follow its instructions exactly.",
- );
- turn.expectOk();
+ await t.send("Please use the dynamic multi alpha skill and follow its instructions exactly.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.loadedSkill("alpha", {
output: new RegExp(DYNAMIC_MULTI_ALPHA_TOKEN, "u"),
});
diff --git a/e2e/fixtures/agent-skills/evals/skills/dynamic-skill.eval.ts b/e2e/fixtures/agent-skills/evals/skills/dynamic-skill.eval.ts
index 09aad628d..b6b98a3c6 100644
--- a/e2e/fixtures/agent-skills/evals/skills/dynamic-skill.eval.ts
+++ b/e2e/fixtures/agent-skills/evals/skills/dynamic-skill.eval.ts
@@ -11,13 +11,9 @@ const DYNAMIC_SKILL_TOKEN = "dynamic-skill-ok-P4K9";
export default defineEval({
description: "Skills smoke: dynamic single-skill resolution.",
async test(t) {
- const turn = await t.send(
- "Please use the dynamic tenant policy skill and follow its instructions exactly.",
- );
- turn.expectOk();
+ await t.send("Please use the dynamic tenant policy skill and follow its instructions exactly.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.loadedSkill("dynamic-tenant-policy", {
output: new RegExp(DYNAMIC_SKILL_TOKEN, "u"),
});
diff --git a/e2e/fixtures/agent-skills/evals/skills/skill-override.eval.ts b/e2e/fixtures/agent-skills/evals/skills/skill-override.eval.ts
index cabf1dfb3..580475cc7 100644
--- a/e2e/fixtures/agent-skills/evals/skills/skill-override.eval.ts
+++ b/e2e/fixtures/agent-skills/evals/skills/skill-override.eval.ts
@@ -12,13 +12,9 @@ const HOUSE_RULES_OVERRIDE_TOKEN = "house-rules-dynamic-ok-M5T8";
export default defineEval({
description: "Skills smoke: a dynamic skill overrides a same-named authored skill.",
async test(t) {
- const turn = await t.send(
- "Please use the house rules skill and follow its instructions exactly.",
- );
- turn.expectOk();
+ await t.send("Please use the house rules skill and follow its instructions exactly.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.loadedSkill("house-rules", { output: new RegExp(HOUSE_RULES_OVERRIDE_TOKEN, "u") });
t.messageIncludes(HOUSE_RULES_OVERRIDE_TOKEN);
},
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
index f26c7f1ef..4c89788d4 100644
--- a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
+++ b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
@@ -1,22 +1,8 @@
-import type { HandleMessageStreamEvent } from "eve/client";
import { defineEval } from "eve/evals";
+import { equals } from "eve/evals/expect";
const GOOG_PRICE = "178.92";
-/**
- * The child's executed tool result does not surface as a parent-stream
- * `action.result`; the child's output reaches the parent through
- * `subagent.completed`.
- */
-function subagentOutputs(events: readonly HandleMessageStreamEvent[]): string[] {
- const outputs: string[] = [];
- for (const event of events) {
- if (event.type !== "subagent.completed") continue;
- outputs.push(JSON.stringify(event.data.output ?? ""));
- }
- return outputs;
-}
-
/**
* Parent/child HITL proxying: the stock-price subagent's tool approval
* (`approval: once()`) surfaces on the parent stream, the approval
@@ -32,51 +18,18 @@ export default defineEval({
);
// The child's approval request must surface on the parent stream.
- t.expectInputRequests({ toolName: "get_stock_price" });
+ t.requireInputRequest({ toolName: "get_stock_price" });
await t.sleep();
const resumed = await t.respondAll("approve");
- resumed.expectOk();
- t.event(
- (events) =>
- events.filter(
- (event) => event.type === "subagent.called" && event.data.name === "stock-price",
- ).length === 1,
- "stock-price subagent was called exactly once",
- );
-
- if (resumed.inputRequests.length > 0) {
- const requests = resumed.inputRequests.map((request) => ({
- requestId: request.requestId,
- toolName: request.action.kind === "tool-call" ? request.action.toolName : undefined,
- }));
- throw new Error(
- `Subagent re-parked after approval with input requests: ${JSON.stringify(requests)}.`,
- );
- }
-
- const outputs = subagentOutputs(t.events);
- if (!outputs.some((output) => output.includes(GOOG_PRICE))) {
- const failedActions = t.events.flatMap((event) => {
- if (event.type !== "action.result") return [];
- if (event.data.status !== "failed" && event.data.result.isError !== true) return [];
- return [event.data.result];
- });
- const recentEventTypes = t.events.slice(-20).map((event) => event.type);
- throw new Error(
- [
- `No subagent.completed output contained the GOOG price; got [${outputs.join(", ")}].`,
- `Resumed turn status: ${resumed.status}.`,
- `Failed actions: ${JSON.stringify(failedActions)}.`,
- `Recent events: [${recentEventTypes.join(", ")}].`,
- ].join(" "),
- );
- }
-
+ t.check(resumed.inputRequests, equals([]));
t.noFailedActions();
- t.didNotFail();
- t.completed();
+ t.succeeded();
+ t.calledSubagent("stock-price", {
+ output: new RegExp(GOOG_PRICE),
+ count: 1,
+ });
t.messageIncludes(GOOG_PRICE);
},
});
diff --git a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
index c7a644e70..cf6fe838e 100644
--- a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
@@ -23,25 +23,17 @@ export default defineEval({
const turn = await t.send(
"Use the Workflow tool exactly once to fan out two independent echo-marker subagent calls. In its JavaScript, create the messages 'workflow alpha' and 'workflow beta', map them through echo-marker inside Promise.all, and return the resulting two-element array. Do not call echo-marker outside Workflow. Then reply with the returned array verbatim as JSON.",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
- t.calledTool("Workflow", { input: isFanOutProgram, times: 1 });
- t.event((events) => {
- const calledIndexes = events.flatMap((event, index) =>
- event.type === "subagent.called" && event.data.name === "echo-marker" ? [index] : [],
- );
- const firstCompletedIndex = events.findIndex(
- (event) => event.type === "subagent.completed" && event.data.subagentName === "echo-marker",
- );
- return (
- calledIndexes.length === 2 &&
- firstCompletedIndex >= 0 &&
- calledIndexes.every((index) => index < firstCompletedIndex)
- );
- }, "Workflow dispatched exactly two echo-marker children before either completed");
- t.calledSubagent("echo-marker", { output: /SUBAGENT_TOKEN=echo-marker-9F2X/ });
+ t.succeeded();
+ t.calledTool("Workflow", { input: isFanOutProgram, count: 1 });
+ turn.eventOrder([
+ { type: "subagent.called", data: { name: "echo-marker" }, count: 2 },
+ { type: "subagent.completed", data: { subagentName: "echo-marker" }, count: 2 },
+ ]);
+ t.calledSubagent("echo-marker", {
+ output: /SUBAGENT_TOKEN=echo-marker-9F2X/,
+ count: 2,
+ });
t.messageIncludes(DOUBLE_SUBAGENT_TOKEN);
t.noFailedActions();
},
diff --git a/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts b/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
index 5e1f09969..12ae3629f 100644
--- a/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
@@ -10,13 +10,11 @@ const SUBAGENT_TOKEN = "SUBAGENT_TOKEN=echo-marker-9F2X";
export default defineEval({
description: "Local subagent delegation smoke: child output reaches the parent reply verbatim.",
async test(t) {
- const turn = await t.send(
+ await t.send(
"Use the echo-marker subagent with message 'ping'. Once it returns, reply with the subagent's exact output included verbatim.",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledSubagent("echo-marker", { output: /SUBAGENT_TOKEN=echo-marker-9F2X/ });
t.messageIncludes(SUBAGENT_TOKEN);
},
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/approve-then-no-regate.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/approve-then-no-regate.eval.ts
index 8357484f0..1adf6dff6 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/approve-then-no-regate.eval.ts
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/approve-then-no-regate.eval.ts
@@ -1,6 +1,6 @@
import { defineEval } from "eve/evals";
-import { GUARDED_ECHO_TOKEN, guardedEchoResults } from "./shared.js";
+import { GUARDED_ECHO_TOKEN } from "./shared.js";
/**
* HITL flow: `once()` approval semantics — a grant persists for the session,
@@ -10,33 +10,33 @@ import { GUARDED_ECHO_TOKEN, guardedEchoResults } from "./shared.js";
export default defineEval({
description: "HITL smoke: an approved once() grant persists for the session.",
async test(t) {
- await t.send('Call the guarded-echo tool with note "first-call".');
- t.expectInputRequests({ toolName: "guarded-echo" });
+ const parked = await t.send('Call the guarded-echo tool with note "first-call".');
+ t.requireInputRequest({ toolName: "guarded-echo" });
+ parked.calledTool("guarded-echo", { status: "pending", count: 1 });
const approved = await t.respondAll("approve");
approved.expectOk();
- const [firstResult] = guardedEchoResults(t.events);
- if (firstResult === undefined || !firstResult.includes(GUARDED_ECHO_TOKEN)) {
- throw new Error("Approved guarded-echo call did not execute.");
- }
+ approved.event("action.result", {
+ data: {
+ result: {
+ kind: "tool-result",
+ toolName: "guarded-echo",
+ output: new RegExp(GUARDED_ECHO_TOKEN),
+ },
+ status: "completed",
+ },
+ count: 1,
+ });
// A successful turn in an open session ends "waiting"; a re-park
// would surface as pending input requests.
const second = await t.send('Call the guarded-echo tool again with note "second-call".');
- second.expectOk();
- if (second.inputRequests.length > 0) {
- throw new Error(
- `once() grant did not persist: turn re-parked on ${second.inputRequests.length} request(s).`,
- );
- }
- const results = guardedEchoResults(t.events);
- if (results.length !== 2 || !results[1]!.includes(GUARDED_ECHO_TOKEN)) {
- throw new Error(
- `Second guarded-echo call did not execute without re-approval (saw ${results.length} result(s)).`,
- );
- }
+ second.succeeded();
- t.didNotFail();
- t.completed();
+ t.succeeded();
+ t.calledTool("guarded-echo", {
+ output: new RegExp(GUARDED_ECHO_TOKEN),
+ count: 2,
+ });
},
});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.ts
index 99f7000d2..ab6406499 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.ts
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/ask-question-select.eval.ts
@@ -17,23 +17,15 @@ export default defineEval({
].join("\n"),
);
- const [request] = t.expectInputRequests({ toolName: "ask_question" });
- if (request === undefined) {
- throw new Error("Expected a pending ask_question input request.");
- }
- if (request.display !== undefined && request.display !== "select") {
- throw new Error(`Expected select display, got ${String(request.display)}.`);
- }
- const optionIds = (request.options ?? []).map((option) => option.id);
- if (!optionIds.includes("red") || !optionIds.includes("blue")) {
- throw new Error(`Expected red/blue options, got [${optionIds.join(", ")}].`);
- }
+ t.requireInputRequest({
+ display: (value) => value === undefined || value === "select",
+ optionIds: ["red", "blue"],
+ toolName: "ask_question",
+ });
- const resumed = await t.respondAll("blue");
- resumed.expectOk();
+ await t.respondAll("blue");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.messageIncludes(/\bblue\b/i);
},
});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/deny-then-regate.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/deny-then-regate.eval.ts
index 106fac031..49a345bfb 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/deny-then-regate.eval.ts
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/deny-then-regate.eval.ts
@@ -1,7 +1,5 @@
import { defineEval } from "eve/evals";
-import { guardedEchoResults } from "./shared.js";
-
/**
* HITL flow: `once()` approval semantics — a denial does not grant, so the
* follow-up guarded call re-parks. Parking is server-side, so every
@@ -11,13 +9,14 @@ export default defineEval({
description: "HITL smoke: a denied once() call does not execute and re-gates the next call.",
async test(t) {
await t.send('Call the guarded-echo tool with note "denied-call".');
- t.expectInputRequests({ toolName: "guarded-echo" });
+ t.requireInputRequest({ toolName: "guarded-echo" });
const denied = await t.respondAll("deny");
denied.expectOk();
- if (guardedEchoResults(t.events).length > 0) {
- throw new Error("Denied guarded-echo call must not execute.");
- }
+ denied.event("action.result", {
+ data: { result: { kind: "tool-result", toolName: "guarded-echo" }, status: "rejected" },
+ count: 1,
+ });
// The denial returns to the model as context; real models paraphrase it,
// so judge the acknowledgment instead of matching literal wording.
t.judge.autoevals
@@ -31,9 +30,10 @@ export default defineEval({
await t.send('Call the guarded-echo tool once more with note "retry-call".');
// Denial does not grant: the follow-up call must re-park.
- t.expectInputRequests({ toolName: "guarded-echo" });
+ t.requireInputRequest({ toolName: "guarded-echo" });
- t.didNotFail();
- t.waiting();
+ t.parked();
+ t.calledTool("guarded-echo", { status: "rejected", count: 1 });
+ t.calledTool("guarded-echo", { status: "pending", count: 1 });
},
});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts
index cb5ec7a42..fa3f2c3ca 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts
@@ -1,5 +1,4 @@
import { defineEval } from "eve/evals";
-import type { HandleMessageStreamEvent } from "eve/client";
const DYNAMIC_GUARDED_ECHO_TOKEN = "dynamic-guarded-echo-ok-L8R6";
const TOOL_NAME = "dynamic_guarded_echo";
@@ -12,38 +11,31 @@ const TOOL_NAME = "dynamic_guarded_echo";
export default defineEval({
description: "HITL smoke: replayed dynamic tools preserve approval.",
async test(t) {
- await t.send(`Call the \`${TOOL_NAME}\` tool with note "before-approval".`);
- const [request] = t.expectInputRequests({
+ const parked = await t.send(`Call the \`${TOOL_NAME}\` tool with note "before-approval".`);
+ t.requireInputRequest({
display: "confirmation",
toolName: TOOL_NAME,
});
- if (request === undefined) {
- throw new Error(`Expected ${TOOL_NAME} to park for approval.`);
- }
- if (dynamicGuardedEchoResults(t.events).length > 0) {
- throw new Error(`${TOOL_NAME} executed before approval.`);
- }
+ parked.calledTool(TOOL_NAME, { status: "pending", count: 1 });
const approved = await t.respondAll("approve");
approved.expectOk();
- const results = dynamicGuardedEchoResults(t.events);
- if (results.length !== 1 || !results[0]!.includes(DYNAMIC_GUARDED_ECHO_TOKEN)) {
- throw new Error(`Approved ${TOOL_NAME} call did not execute with the expected token.`);
- }
+ approved.event("action.result", {
+ data: {
+ result: {
+ kind: "tool-result",
+ toolName: TOOL_NAME,
+ output: new RegExp(DYNAMIC_GUARDED_ECHO_TOKEN),
+ },
+ status: "completed",
+ },
+ count: 1,
+ });
- t.didNotFail();
- t.completed();
+ t.succeeded();
+ t.calledTool(TOOL_NAME, {
+ output: new RegExp(DYNAMIC_GUARDED_ECHO_TOKEN),
+ count: 1,
+ });
},
});
-
-function dynamicGuardedEchoResults(events: readonly HandleMessageStreamEvent[]): string[] {
- const results: string[] = [];
- for (const event of events) {
- if (event.type !== "action.result") continue;
- if (event.data.status === "rejected") continue;
- const result = event.data.result;
- if (result.kind !== "tool-result" || result.toolName !== TOOL_NAME) continue;
- results.push(JSON.stringify(result.output ?? ""));
- }
- return results;
-}
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/shared.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/shared.ts
index 052847844..652afad1c 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/shared.ts
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/shared.ts
@@ -1,22 +1 @@
-import type { HandleMessageStreamEvent } from "eve/client";
-
export const GUARDED_ECHO_TOKEN = "guarded-echo-ok-T4Q9";
-
-/**
- * Approval results resolve in the turn AFTER the request was raised, so
- * per-turn `toolCalls` cannot pair them; scan the whole session stream for
- * executed `guarded-echo` action results instead. A denied call executes
- * nothing: it surfaces as a `rejected` `action.result` (skipped here) while
- * the execution-denied output returns to the model as message context.
- */
-export function guardedEchoResults(events: readonly HandleMessageStreamEvent[]): string[] {
- const results: string[] = [];
- for (const event of events) {
- if (event.type !== "action.result") continue;
- if (event.data.status === "rejected") continue;
- const result = event.data.result;
- if (result.kind !== "tool-result" || result.toolName !== "guarded-echo") continue;
- results.push(JSON.stringify(result.output ?? ""));
- }
- return results;
-}
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/bootstrap.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/bootstrap.eval.ts
index e6e9b25fd..7f072fce8 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/bootstrap.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/bootstrap.eval.ts
@@ -8,15 +8,12 @@ import { BOOTSTRAP_MARKER_PATH, BOOTSTRAP_MARKER_TOKEN } from "./shared.js";
export default defineEval({
description: "Sandbox smoke: `defineSandbox({ bootstrap })` runs before the first bash call.",
async test(t) {
- const turn = await t.send(
+ await t.send(
`Run the bash command \`cat ${BOOTSTRAP_MARKER_PATH}\` and reply with the file contents verbatim.`,
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("bash", {
- isError: false,
output: new RegExp(BOOTSTRAP_MARKER_TOKEN),
});
},
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts
index f36e51093..94740b4be 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/cli-install.eval.ts
@@ -9,15 +9,12 @@ import { SANDBOX_CLI_NAME, SANDBOX_CLI_TOKEN } from "./shared.js";
export default defineEval({
description: "Sandbox: a custom CLI installed in `bootstrap` is on the PATH for later sessions.",
async test(t) {
- const turn = await t.send(
+ await t.send(
`Run the bash command \`${SANDBOX_CLI_NAME} sandbox\` and reply with its output verbatim.`,
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("bash", {
- isError: false,
output: new RegExp(`${SANDBOX_CLI_TOKEN}:sandbox`),
});
t.messageIncludes(`${SANDBOX_CLI_TOKEN}:sandbox`);
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.ts
index b58fd9fdd..ee5ece0b0 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.ts
@@ -10,20 +10,17 @@ const FILE_TOOLS_PATH = "/workspace/file-tools-note.txt";
export default defineEval({
description: "Sandbox: built-in write_file/grep tools operate on the sandbox filesystem.",
async test(t) {
- const turn = await t.send(
+ await t.send(
[
`Use the write_file tool to create the file ${FILE_TOOLS_PATH} with exactly this content: ${FILE_TOOLS_TOKEN}`,
`Then use the grep tool to search for ${FILE_TOOLS_TOKEN} under /workspace.`,
"Reply with the matching line verbatim.",
].join("\n"),
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
- t.calledTool("write_file", { isError: false });
+ t.succeeded();
+ t.calledTool("write_file");
t.calledTool("grep", {
- isError: false,
output: new RegExp(FILE_TOOLS_TOKEN),
});
t.messageIncludes(FILE_TOOLS_TOKEN);
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts
index c5984f1b9..5527bb50e 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/network-policy.eval.ts
@@ -23,15 +23,12 @@ function isBlocked(value: unknown): boolean {
export default defineEval({
description: "Sandbox: setNetworkPolicy('deny-all') blocks sandbox egress mid-turn.",
async test(t) {
- const turn = await t.send(
+ await t.send(
"Use the `network-probe` tool and tell me whether sandbox network egress was blocked.",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("network-probe", {
- isError: false,
output: isBlocked,
});
},
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/python-tool.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/python-tool.eval.ts
index be0f27fa4..1baaef5d2 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/python-tool.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/python-tool.eval.ts
@@ -7,17 +7,14 @@ import { defineEval } from "eve/evals";
export default defineEval({
description: "Sandbox: an authored tool runs real Python via ctx.getSandbox().",
async test(t) {
- const turn = await t.send(
+ await t.send(
"Use the `run_python` tool to compute the sum of these integers: 2, 3, and 4. " +
"Reply with just the resulting number.",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("run_python", {
input: { numbers: [2, 3, 4] },
- isError: false,
output: { sum: 9 },
});
t.messageIncludes(/\b9\b/);
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-persistence.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-persistence.eval.ts
index 246cb6655..37e9e5c4f 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-persistence.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-persistence.eval.ts
@@ -1,4 +1,5 @@
import { defineEval } from "eve/evals";
+import { equals } from "eve/evals/expect";
// Durable sessions keep their sandbox filesystem across turns: a file written
// in turn one must still be readable in turn two of the same session. The
@@ -15,23 +16,15 @@ export default defineEval({
"Reply with the single word: done.",
);
first.expectOk();
- const firstSessionId = t.sessionId;
const second = await t.send(
`Run the bash command \`cat ${PERSIST_PATH}\` and reply with the file contents verbatim.`,
);
- second.expectOk();
- if (t.sessionId !== firstSessionId) {
- throw new Error(
- `Expected both turns in one session; got ${String(firstSessionId)} then ${String(t.sessionId)}.`,
- );
- }
+ await t.require(second.sessionId, equals(first.sessionId));
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("bash", {
- isError: false,
output: new RegExp(PERSIST_TOKEN),
});
t.messageIncludes(PERSIST_TOKEN);
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts
index 4615c916d..d0d743bf0 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/session-setup.eval.ts
@@ -15,16 +15,13 @@ import {
export default defineEval({
description: "Sandbox: onSession marker and seeded workspace file are both present per session.",
async test(t) {
- const turn = await t.send(
+ await t.send(
`Run the bash command \`cat ${SESSION_MARKER_PATH} ${WORKSPACE_SEED_PATH}\` ` +
"and reply with the combined file contents verbatim.",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("bash", {
- isError: false,
output: new RegExp(`${SESSION_MARKER_TOKEN}[\\s\\S]*${WORKSPACE_SEED_TOKEN}`),
});
t.messageIncludes(SESSION_MARKER_TOKEN);
diff --git a/e2e/fixtures/agent-tools/agent/channels/action-narration.ts b/e2e/fixtures/agent-tools/agent/channels/action-narration.ts
index 9b49a57b6..3b4c8ed76 100644
--- a/e2e/fixtures/agent-tools/agent/channels/action-narration.ts
+++ b/e2e/fixtures/agent-tools/agent/channels/action-narration.ts
@@ -74,16 +74,6 @@ export default defineChannel({
});
return Response.json({ sessionId: session.id });
}),
-
- POST<ActionNarrationState>("/action-narration/continue", async (request, { send }) => {
- const input = await readRequest(request);
- const session = await send(input.message, {
- auth: null,
- continuationToken: continuationToken(input.token),
- state: initialState(),
- });
- return Response.json({ sessionId: session.id });
- }),
],
events: {
diff --git a/e2e/fixtures/agent-tools/agent/tools/dynamic-channel-action-narration.ts b/e2e/fixtures/agent-tools/agent/tools/dynamic-channel-action-narration.ts
index 0e07f22b5..f22f1fcce 100644
--- a/e2e/fixtures/agent-tools/agent/tools/dynamic-channel-action-narration.ts
+++ b/e2e/fixtures/agent-tools/agent/tools/dynamic-channel-action-narration.ts
@@ -5,13 +5,12 @@ import { z } from "zod";
import actionNarration from "../channels/action-narration.js";
/**
- * Exposes the previous turn's channel-side observation only after a streamed
- * action request consumed pre-tool narration. The e2e eval drives a second
- * turn to read this value through the real dynamic-tool lifecycle.
+ * Exposes the channel-side observation on the next model step after a streamed
+ * action request consumed pre-tool narration.
*/
export default defineDynamic({
events: {
- "turn.started": (_event, ctx) => {
+ "step.started": (_event, ctx) => {
if (!isChannel(ctx.channel, actionNarration)) return null;
const narration = ctx.channel.metadata.observedNarration;
diff --git a/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts b/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
index d7f495125..60569b14c 100644
--- a/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
@@ -2,6 +2,7 @@ import { randomBytes } from "node:crypto";
import type { HandleMessageStreamEvent } from "eve/client";
import { defineEval, type EveEvalTargetHandle } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
const STREAMED_ACTION_TOOL = "streamed-action";
const OBSERVATION_TOOL = "read-channel-action-narration";
@@ -41,19 +42,6 @@ function preToolNarration(events: readonly HandleMessageStreamEvent[]): string |
return undefined;
}
-function observedNarration(events: readonly HandleMessageStreamEvent[]): string | undefined {
- for (const event of events) {
- if (event.type !== "action.result" || event.data.result.kind !== "tool-result") continue;
- if (event.data.result.toolName !== OBSERVATION_TOOL) continue;
-
- const output = event.data.result.output;
- if (typeof output !== "object" || output === null || Array.isArray(output)) continue;
- const narration = Reflect.get(output, "narration");
- if (typeof narration === "string" && narration.length > 0) return narration;
- }
- return undefined;
-}
-
async function postChannel(
target: EveEvalTargetHandle,
path: string,
@@ -81,8 +69,8 @@ async function postChannel(
/**
* End-to-end channel contract: the adapter receives the pre-tool completion
- * before the matching action request, then preserves its observation across
- * the next inbound channel turn.
+ * before the matching action request, then exposes that observation to the
+ * next model step.
*/
export default defineEval({
description: "Channel event smoke: pre-tool narration is visible when an action is requested.",
@@ -91,40 +79,30 @@ export default defineEval({
const started = await postChannel(t.target, "/action-narration/start", {
message:
"Before calling `streamed-action`, write one short plain-text sentence explaining the action. " +
- `Then call it exactly once with label "${token}". After it returns, reply with the label verbatim.`,
+ `Then call it exactly once with label "${token}". After it returns, call ` +
+ `\`${OBSERVATION_TOOL}\` exactly once. Finally, reply with the label verbatim.`,
token,
});
- const firstTurn = await t.target.attachSession(started.sessionId);
- const narration = preToolNarration(firstTurn.events);
- if (narration === undefined) {
- throw new Error(
- "Expected a non-empty tool-calls message.completed event before the streamed-action request.",
- );
- }
+ const session = await t.target.attachSession(started.sessionId);
+ const narration = await t.require(
+ preToolNarration(session.events) ?? "",
+ satisfies((value: string) => value.length > 0, "pre-tool narration is non-empty"),
+ );
- const continued = await postChannel(t.target, "/action-narration/continue", {
- message: `Call \`${OBSERVATION_TOOL}\` exactly once, then reply with the narration value it returned.`,
- token,
+ session.event("action.result", {
+ count: 1,
+ data: {
+ result: {
+ kind: "tool-result",
+ output: { narration },
+ toolName: OBSERVATION_TOOL,
+ },
+ status: "completed",
+ },
});
- if (continued.sessionId !== started.sessionId) {
- throw new Error(
- `Expected the channel continuation to resume ${started.sessionId}, received ${continued.sessionId}.`,
- );
- }
-
- const secondTurn = await t.target.attachSession(continued.sessionId, {
- startIndex: firstTurn.events.length,
- });
- const observed = observedNarration(secondTurn.events);
- if (observed !== narration) {
- throw new Error(
- `Expected the channel to observe ${JSON.stringify(narration)}, received ${JSON.stringify(observed)}.`,
- );
- }
- t.didNotFail();
- t.completed();
- t.calledTool(STREAMED_ACTION_TOOL, { isError: false, times: 1 });
- t.calledTool(OBSERVATION_TOOL, { isError: false, times: 1 });
+ session.succeeded();
+ t.succeeded();
+ t.calledTool(STREAMED_ACTION_TOOL, { count: 1 });
},
});
diff --git a/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.ts b/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.ts
index 6c50afc47..141425203 100644
--- a/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/channel-metadata/anchored-no-topic.eval.ts
@@ -2,7 +2,7 @@ import { randomBytes } from "node:crypto";
import { defineEval } from "eve/evals";
-import { METADATA_TOOL, PROMPT, extractToolOutput, startChannelSession } from "./shared.js";
+import { METADATA_TOOL, PROMPT, startChannelSession } from "./shared.js";
// The anchored channel's metadata has no `topic`, so the resolver
// returns null and no tool registers: the turn completes without a
@@ -17,25 +17,11 @@ export default defineEval({
});
const session = await t.target.attachSession(sessionId);
- const output = extractToolOutput(session.events, METADATA_TOOL);
- if (output !== undefined) {
- throw new Error(
- "The anchored channel sets no `topic`, so the resolver should return null and " +
- `register no tool; saw a ${METADATA_TOOL} result: ${JSON.stringify(output)}`,
- );
- }
+ session.succeeded();
+ session.notCalledTool(METADATA_TOOL);
+ session.noFailedActions();
- const failedActions = session.events.filter(
- (event) =>
- event.type === "action.result" &&
- (event.data.status === "failed" || event.data.result.isError === true),
- );
- if (failedActions.length > 0) {
- throw new Error(`Expected no failed actions; saw ${failedActions.length}.`);
- }
-
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.notCalledTool(METADATA_TOOL);
},
});
diff --git a/e2e/fixtures/agent-tools/evals/channel-metadata/shared.ts b/e2e/fixtures/agent-tools/evals/channel-metadata/shared.ts
index 41fc72b96..c281bc67a 100644
--- a/e2e/fixtures/agent-tools/evals/channel-metadata/shared.ts
+++ b/e2e/fixtures/agent-tools/evals/channel-metadata/shared.ts
@@ -1,4 +1,3 @@
-import type { HandleMessageStreamEvent } from "eve/client";
import type { EveEvalTargetHandle } from "eve/evals";
/**
@@ -33,22 +32,3 @@ export async function startChannelSession(
}
return parsed.sessionId;
}
-
-export function extractToolOutput(
- events: readonly HandleMessageStreamEvent[],
- toolName: string,
-): Record<string, unknown> | undefined {
- for (const event of events) {
- if (event.type !== "action.result") continue;
- const result = event.data.result;
- if (
- result.kind === "tool-result" &&
- result.toolName === toolName &&
- typeof result.output === "object" &&
- result.output !== null
- ) {
- return result.output as Record<string, unknown>;
- }
- }
- return undefined;
-}
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/authored-override.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/authored-override.eval.ts
index 3d088b176..05b55fda3 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/authored-override.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/authored-override.eval.ts
@@ -9,15 +9,10 @@ const OVERRIDE_TOKEN = "dynamic-override-ok-K2P7";
export default defineEval({
description: "Dynamic tools smoke: a dynamic tool overrides a same-named authored tool.",
async test(t) {
- const turn = await t.send(
- "Call the `override-target` tool and report the `source` value it returns.",
- );
- turn.expectOk();
+ await t.send("Call the `override-target` tool and report the `source` value it returns.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("override-target", {
- isError: false,
output: { source: "dynamic", token: OVERRIDE_TOKEN },
});
},
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/conditional.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/conditional.eval.ts
index c3d831519..e03c76bb2 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/conditional.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/conditional.eval.ts
@@ -1,7 +1,5 @@
import { defineEval } from "eve/evals";
-import { requireToolOutput } from "./shared.js";
-
// The resolver increments a state counter and branches on it. If it
// truly runs once per session, both turns see { branch: "first" }; a
// re-run would surface { branch: "reran" }.
@@ -12,29 +10,21 @@ export default defineEval({
"Use the `check_stability` tool and tell me the branch and invocations values.",
);
first.expectOk();
- const firstOutput = requireToolOutput(first, "check_stability");
- if (firstOutput.branch !== "first") {
- throw new Error(`Turn 1: expected branch="first", got ${JSON.stringify(firstOutput.branch)}`);
- }
+ first.calledTool("check_stability", {
+ output: { branch: "first" },
+ });
const second = await t.send(
"Use the `check_stability` tool to check stability. Call it now and report the branch and invocations values.",
);
- second.expectOk();
- const secondOutput = requireToolOutput(second, "check_stability");
- if (secondOutput.branch !== "first") {
- throw new Error(
- `Turn 2: expected branch="first" (resolver should not re-run conditional logic), ` +
- `got branch=${JSON.stringify(secondOutput.branch)}, invocations=${JSON.stringify(secondOutput.invocations)}.`,
- );
- }
+ second.calledTool("check_stability", {
+ output: { branch: "first" },
+ });
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("check_stability", {
- isError: false,
output: { branch: "first" },
- times: 2,
+ count: 2,
});
},
});
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/echo.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/echo.eval.ts
index b5d1b9f6c..5a998c810 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/echo.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/echo.eval.ts
@@ -7,15 +7,12 @@ import { DYNAMIC_ECHO_TOKEN, ECHO_TOOL } from "./shared.js";
export default defineEval({
description: "Dynamic tools smoke: resolver registers the echo tool and it returns the token.",
async test(t) {
- const turn = await t.send(
+ await t.send(
`Please call the \`${ECHO_TOOL}\` tool with message 'hello from smoke test' and tell me what it returned.`,
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool(ECHO_TOOL, {
- isError: false,
output: { echoed: "hello from smoke test", token: DYNAMIC_ECHO_TOKEN },
});
},
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/io-once.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/io-once.eval.ts
index 8dee7b708..43748af9a 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/io-once.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/io-once.eval.ts
@@ -1,7 +1,5 @@
import { defineEval } from "eve/evals";
-import { requireToolOutput } from "./shared.js";
-
// The resolver's simulated I/O runs once; the durable cache replays its
// result on the second turn so ioCallCount stays at 1.
export default defineEval({
@@ -11,26 +9,19 @@ export default defineEval({
"Use the `get_io_count` tool and tell me the ioCallCount number from the result.",
);
first.expectOk();
- const firstCount = requireToolOutput(first, "get_io_count").ioCallCount;
- if (firstCount !== 1) {
- throw new Error(`Turn 1: expected ioCallCount=1, got ${JSON.stringify(firstCount)}`);
- }
+ first.calledTool("get_io_count", {
+ output: { ioCallCount: 1 },
+ });
const second = await t.send(
"Use the `get_io_count` tool again right now and tell me the ioCallCount value from the result.",
);
- second.expectOk();
- const secondCount = requireToolOutput(second, "get_io_count").ioCallCount;
- if (secondCount !== 1) {
- throw new Error(
- `Turn 2: expected ioCallCount=1 (resolver I/O should not re-run), got ${JSON.stringify(secondCount)}.`,
- );
- }
+ second.calledTool("get_io_count", {
+ output: { ioCallCount: 1 },
+ });
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("get_io_count", {
- isError: false,
output: { ioCallCount: 1 },
});
},
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/loop.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/loop.eval.ts
index a34988375..a95073d85 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/loop.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/loop.eval.ts
@@ -4,13 +4,10 @@ import { defineEval } from "eve/evals";
export default defineEval({
description: "Dynamic tools smoke: loop-generated tools keep per-iteration closures.",
async test(t) {
- const turn = await t.send("Call the `alpha` tool and tell me the name and index it returned.");
- turn.expectOk();
+ await t.send("Call the `alpha` tool and tell me the name and index it returned.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("alpha", {
- isError: false,
output: { name: "alpha", index: 0 },
});
},
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/messages.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/messages.eval.ts
index d2d82ee9d..440ff6b38 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/messages.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/messages.eval.ts
@@ -1,6 +1,5 @@
import { defineEval } from "eve/evals";
-
-import { requireToolOutput } from "./shared.js";
+import { satisfies } from "eve/evals/expect";
// The step.started resolver sees the accumulated message history: the
// second turn's count must exceed the first.
@@ -11,32 +10,37 @@ export default defineEval({
"Use the `check_messages` tool with label 'turn1' and tell me the messageCount.",
);
first.expectOk();
- const firstCount = requireToolOutput(first, "check_messages").messageCount;
- if (typeof firstCount !== "number" || firstCount < 1) {
- throw new Error(
- `Turn 1: expected messageCount >= 1, got ${JSON.stringify(firstCount)}. ` +
- "Resolver should see at least the user message.",
- );
- }
+ const firstOutput = first.requireToolCall("check_messages").output;
const second = await t.send(
"Use the `check_messages` tool again with label 'turn2' and tell me the messageCount.",
);
- second.expectOk();
- const secondCount = requireToolOutput(second, "check_messages").messageCount;
- if (typeof secondCount !== "number" || secondCount <= firstCount) {
- throw new Error(
- `Turn 2: expected messageCount > ${firstCount}, got ${JSON.stringify(secondCount)}. ` +
- "Resolver should see accumulated history.",
- );
- }
+ const secondOutput = second.requireToolCall("check_messages").output;
+ t.check(
+ [firstOutput, secondOutput],
+ satisfies(([firstValue, secondValue]: readonly unknown[]) => {
+ const firstCount = readMessageCount(firstValue);
+ const secondCount = readMessageCount(secondValue);
+ return (
+ firstCount !== undefined &&
+ secondCount !== undefined &&
+ firstCount >= 1 &&
+ secondCount > firstCount
+ );
+ }, "message count increases across turns"),
+ );
- t.didNotFail();
- t.completed();
+ t.succeeded();
// The accumulated-history property is verified per-turn above
// (firstCount >= 1, secondCount > firstCount). The model may call the
// tool more than once in a turn, so assert it was called without error
// rather than pinning an exact count.
- t.calledTool("check_messages", { isError: false });
+ t.calledTool("check_messages");
},
});
+
+function readMessageCount(value: unknown): number | undefined {
+ if (typeof value !== "object" || value === null) return undefined;
+ const count = (value as { messageCount?: unknown }).messageCount;
+ return typeof count === "number" ? count : undefined;
+}
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/model-output.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/model-output.eval.ts
index ad8312c87..1544a6fc0 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/model-output.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/model-output.eval.ts
@@ -5,15 +5,12 @@ import { defineEval } from "eve/evals";
export default defineEval({
description: "Dynamic tools smoke: action.result carries the raw execute output.",
async test(t) {
- const turn = await t.send(
+ await t.send(
"Use the `check_model_output` tool with value 'hello' and tell me what the result contains.",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("check_model_output", {
- isError: false,
output: { raw: true, secret: "internal-only-data", value: "hello" },
});
},
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/multi-turn.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/multi-turn.eval.ts
index 05cd8321f..8aff6e9b4 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/multi-turn.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/multi-turn.eval.ts
@@ -1,6 +1,6 @@
import { defineEval } from "eve/evals";
-import { DYNAMIC_ECHO_TOKEN, ECHO_TOOL, requireToolOutput } from "./shared.js";
+import { DYNAMIC_ECHO_TOKEN, ECHO_TOOL } from "./shared.js";
// The dynamic tool must survive serialization/deserialization (lazy
// replay of the resolver): both turns call it and see the token.
@@ -11,27 +11,21 @@ export default defineEval({
`Please call the \`${ECHO_TOOL}\` tool with message 'turn one' and tell me the token it returned.`,
);
first.expectOk();
- if (requireToolOutput(first, ECHO_TOOL).token !== DYNAMIC_ECHO_TOKEN) {
- throw new Error("Turn 1: echo tool result did not contain the expected token.");
- }
+ first.calledTool(ECHO_TOOL, {
+ output: { token: DYNAMIC_ECHO_TOKEN },
+ });
const second = await t.send(
`I need you to call the \`${ECHO_TOOL}\` tool right now with message 'turn two', do not answer from memory. Call it and tell me the token from the result.`,
);
- second.expectOk();
- if (requireToolOutput(second, ECHO_TOOL).token !== DYNAMIC_ECHO_TOKEN) {
- throw new Error(
- "Turn 2: echo tool result did not contain the expected token. " +
- "The dynamic tool may not have survived serialization.",
- );
- }
+ second.calledTool(ECHO_TOOL, {
+ output: { token: DYNAMIC_ECHO_TOKEN },
+ });
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool(ECHO_TOOL, {
- isError: false,
output: { token: DYNAMIC_ECHO_TOKEN },
- times: 2,
+ count: 2,
});
},
});
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/nested.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/nested.eval.ts
index 5e67f2cba..c20256c3d 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/nested.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/nested.eval.ts
@@ -11,19 +11,13 @@ export default defineEval({
);
first.expectOk();
- const second = await t.send(
- "Now call the `nested_status` tool and tell me exactly what it returned.",
- );
- second.expectOk();
+ await t.send("Now call the `nested_status` tool and tell me exactly what it returned.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("nested_query", {
- isError: false,
output: { action: "query", endpoint: "/v2/query", source: "helper" },
});
t.calledTool("nested_status", {
- isError: false,
output: { tier: "premium", source: "inline" },
});
},
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/null.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/null.eval.ts
index 5e8fedf21..58df218c8 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/null.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/null.eval.ts
@@ -5,13 +5,11 @@ import { defineEval } from "eve/evals";
export default defineEval({
description: "Dynamic tools smoke: a null-returning resolver registers no tools.",
async test(t) {
- const turn = await t.send(
+ await t.send(
"List every tool you have access to. Is there a tool called 'dynamic-null'? Answer yes or no.",
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.notCalledTool("dynamic-null");
},
});
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/overwrite.eval.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/overwrite.eval.ts
index 694d83867..b46e1c14c 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/overwrite.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/overwrite.eval.ts
@@ -9,17 +9,13 @@ export default defineEval({
const first = await t.send("Call the `shared` tool and report the source and turn values.");
first.expectOk();
- const second = await t.send("Call the `session_only` tool and report the source value.");
- second.expectOk();
+ await t.send("Call the `session_only` tool and report the source value.");
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("shared", {
- isError: false,
output: { source: "turn" },
});
t.calledTool("session_only", {
- isError: false,
output: { source: "session" },
});
},
diff --git a/e2e/fixtures/agent-tools/evals/dynamic-tools/shared.ts b/e2e/fixtures/agent-tools/evals/dynamic-tools/shared.ts
index c66731fd0..40b77381f 100644
--- a/e2e/fixtures/agent-tools/evals/dynamic-tools/shared.ts
+++ b/e2e/fixtures/agent-tools/evals/dynamic-tools/shared.ts
@@ -1,5 +1,3 @@
-import type { EveEvalTurn } from "eve/evals";
-
/**
* Shared constants and helpers for the dynamic tool (`defineDynamic`) smoke
* evals. A map resolver names each entry by its bare key, so each case names
@@ -7,22 +5,3 @@ import type { EveEvalTurn } from "eve/evals";
*/
export const DYNAMIC_ECHO_TOKEN = "dynamic-echo-ok-X7R2";
export const ECHO_TOOL = "echo_dynamic";
-
-/**
- * Finds the named tool call inside one turn and returns its object output.
- * Per-turn inspection matters here: the derived `toolCalls` checks see span
- * every turn in the case, so cross-turn comparisons must read `turn.toolCalls`.
- */
-export function requireToolOutput(turn: EveEvalTurn, toolName: string): Record<string, unknown> {
- const call = turn.toolCalls.find((candidate) => candidate.name === toolName);
- if (call === undefined) {
- const seen = turn.toolCalls.map((candidate) => candidate.name).join(", ");
- throw new Error(`Expected a "${toolName}" call in this turn; saw [${seen}].`);
- }
- if (typeof call.output !== "object" || call.output === null) {
- throw new Error(
- `Expected object output from "${toolName}"; got ${JSON.stringify(call.output)}.`,
- );
- }
- return call.output as Record<string, unknown>;
-}
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/fanout-authored.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/fanout-authored.eval.ts
index 4905058f5..30fcbd98b 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/fanout-authored.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/fanout-authored.eval.ts
@@ -34,21 +34,17 @@ export default defineEval({
);
turn.expectOk();
- t.didNotFail();
- t.completed();
- t.calledTool(TOOL_NAME, { isError: false, times: FANOUT_SIZE });
+ t.succeeded();
+ t.calledTool(TOOL_NAME, { count: FANOUT_SIZE });
t.noFailedActions();
- t.event(
- (events) => fanoutRequestsPrecedeFirstResult({ events, toolName: TOOL_NAME }),
- "ten authored requests precede the first authored result",
+ turn.eventsSatisfy("ten authored requests precede the first authored result", (events) =>
+ fanoutRequestsPrecedeFirstResult({ events, toolName: TOOL_NAME }),
);
- t.event(
- (events) => fanoutRequestsUseExpectedLabels({ events, labels: LABELS, toolName: TOOL_NAME }),
- "ten authored requests use their distinct labels",
+ turn.eventsSatisfy("ten authored requests use their distinct labels", (events) =>
+ fanoutRequestsUseExpectedLabels({ events, labels: LABELS, toolName: TOOL_NAME }),
);
- t.event(
- (events) => authoredFanoutExecutionsOverlap({ events, toolName: TOOL_NAME }),
- "ten authored executions overlap",
+ turn.eventsSatisfy("ten authored executions overlap", (events) =>
+ authoredFanoutExecutionsOverlap({ events, toolName: TOOL_NAME }),
);
},
});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/multi-step-loop.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/multi-step-loop.eval.ts
index 82832da32..acbf951e9 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/multi-step-loop.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/multi-step-loop.eval.ts
@@ -1,46 +1,14 @@
-import type {
- ActionResultStreamEvent,
- ActionsRequestedStreamEvent,
- HandleMessageStreamEvent,
-} from "eve/client";
import { defineEval } from "eve/evals";
const MULTI_STEP_FINAL_VALUE = "phoenix-rising-9F2X";
-/**
- * The i-th `actions.requested` tool call must pair with the i-th
- * `action.result` by callId. A regression that mis-pairs results with calls
- * still produces the same toolName sequence, so `toolOrder` alone cannot
- * catch it.
- */
-function toolCallIdsPairInOrder(events: readonly HandleMessageStreamEvent[]): boolean {
- const requestedIds = events
- .filter((event): event is ActionsRequestedStreamEvent => event.type === "actions.requested")
- .flatMap((event) =>
- event.data.actions
- .filter((action) => action.kind === "tool-call")
- .map((action) => action.callId),
- );
- const resultIds = events
- .filter((event): event is ActionResultStreamEvent => event.type === "action.result")
- .flatMap((event) =>
- event.data.result.kind === "tool-result" ? [event.data.result.callId] : [],
- );
-
- return (
- requestedIds.length === 2 &&
- resultIds.length === 2 &&
- requestedIds.every((callId, index) => resultIds[index] === callId)
- );
-}
-
// Deterministic two-step tool loop: lookup-step-a's stepKey feeds
-// lookup-step-b, in order, with results paired by callId, and the
-// final value flows back into the user-visible reply.
+// lookup-step-b in order, and the final value flows back into the
+// user-visible reply.
export default defineEval({
- description: "Static tools smoke: deterministic two-step tool loop with paired callIds.",
+ description: "Static tools smoke: deterministic two-step tool loop.",
async test(t) {
- const turn = await t.send(
+ await t.send(
[
"Follow these steps exactly:",
"1. Call the `lookup-step-a` tool with topic 'demo'.",
@@ -48,23 +16,18 @@ export default defineEval({
"3. Reply with the final `value` from `lookup-step-b` verbatim, with no extra commentary.",
].join("\n"),
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.toolOrder(["lookup-step-a", "lookup-step-b"]);
t.calledTool("lookup-step-a", {
input: { topic: "demo" },
- isError: false,
- times: 1,
+ count: 1,
});
t.calledTool("lookup-step-b", {
input: { stepKey: "K-9F2X" },
- isError: false,
- times: 1,
+ count: 1,
});
t.noFailedActions();
- t.event(toolCallIdsPairInOrder, "tool call/result callIds pair in order");
t.messageIncludes(MULTI_STEP_FINAL_VALUE);
},
});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts
index 2299e1e4c..cfa5879bd 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts
@@ -73,13 +73,11 @@ export default defineEval({
);
turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool(TOOL_NAME, {
input: { label: LABEL },
- isError: false,
- times: 1,
+ count: 1,
});
- t.event(streamedBeforeLocalExecution, "local action request precedes execution");
+ turn.eventsSatisfy("local action request precedes execution", streamedBeforeLocalExecution);
},
});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/structured-echo-narrowing.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/structured-echo-narrowing.eval.ts
index 54d746ddc..5938fb97e 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/structured-echo-narrowing.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/structured-echo-narrowing.eval.ts
@@ -3,19 +3,16 @@ import { defineEval } from "eve/evals";
// The action.result must carry the structured object (not a JSON
// string), and the fixture's tool-result-narrowing hook matches it via
// toolResultFrom: a symbol-identity miss throws inside the hook, which
-// surfaces as turn.failed and trips the didNotFail check.
+// surfaces as turn.failed and trips the succeeded check.
export default defineEval({
description: "Static tools smoke: structured tool-result narrowing via toolResultFrom.",
async test(t) {
- const turn = await t.send(
+ await t.send(
'Call the `structured-echo` tool with label "smoke-test". Reply with the echoed value verbatim.',
);
- turn.expectOk();
- t.didNotFail();
- t.completed();
+ t.succeeded();
t.calledTool("structured-echo", {
- isError: false,
output: (value: unknown) =>
typeof value === "object" &&
value !== null &&
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/throw-recover.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/throw-recover.eval.ts
index 29166e778..1ffc58e74 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/throw-recover.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/throw-recover.eval.ts
@@ -1,36 +1,24 @@
import { defineEval } from "eve/evals";
-// An authored tool throw surfaces as action.result with isError: true
-// (no turn.failed), and the session stays responsive for a follow-up.
+// An authored tool throw surfaces as a failed action result (no turn.failed),
+// and the session stays responsive for a follow-up.
export default defineEval({
- description: "Static tools smoke: tool throw surfaces as isError and the session recovers.",
+ description: "Static tools smoke: tool throw surfaces as failed and the session recovers.",
async test(t) {
const first = await t.send(
'Call the `always-throws` tool exactly once with reason "smoke". ' +
"After it fails, reply with a one-line acknowledgement that the tool failed.",
);
first.expectOk();
- const throwingCall = first.toolCalls.find((call) => call.name === "always-throws");
- if (throwingCall === undefined) {
- throw new Error("Turn 1: expected an always-throws call; saw none.");
- }
- if (throwingCall.isError !== true) {
- throw new Error("Turn 1: expected the always-throws result to report isError=true.");
- }
+ first.calledTool("always-throws", { status: "failed", count: 1 });
const second = await t.send(
"Are you still responsive? Reply with exactly the single word: yes.",
);
- second.expectOk();
- if (second.message === undefined || !/\byes\b/iu.test(second.message)) {
- throw new Error(
- `Expected follow-up reply to contain "yes"; got: ${JSON.stringify(second.message)}`,
- );
- }
+ second.messageIncludes(/\byes\b/iu);
- t.didNotFail();
- t.completed();
- t.calledTool("always-throws", { isError: true, times: 1 });
+ t.succeeded();
+ t.calledTool("always-throws", { status: "failed", count: 1 });
t.messageIncludes(/\byes\b/iu);
},
});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/web-search.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/web-search.eval.ts
index e38c47c40..bc862b4f8 100644
--- a/e2e/fixtures/agent-tools/evals/static-tools/web-search.eval.ts
+++ b/e2e/fixtures/agent-tools/evals/static-tools/web-search.eval.ts
@@ -4,11 +4,9 @@ export default defineEval({
description: "Provider tools smoke: gateway web search answers a current-events question.",
async test(t) {
const turn = await t.send("Who won the 2026 NBA finals");
- turn.expectOk();
- t.didNotFail();
- t.completed();
- t.calledTool("web_search", { isError: false });
+ t.succeeded();
+ t.calledTool("web_search");
t.noFailedActions();
t.messageIncludes(/New York Knicks/iu);
t.judge.autoevals
diff --git a/packages/eve/src/channel/compiled-channel.ts b/packages/eve/src/channel/compiled-channel.ts
index abec098b7..a2592e98a 100644
--- a/packages/eve/src/channel/compiled-channel.ts
+++ b/packages/eve/src/channel/compiled-channel.ts
@@ -5,6 +5,17 @@ import type { SessionAuthContext } from "#channel/types.js";
export const CHANNEL_SENTINEL = "eve:channel" as const;
const CHANNEL_INSTRUMENTATION_KIND = Symbol.for("eve.channel.instrumentationKind");
+const CHANNEL_INSTRUMENTATION_KINDS = Symbol.for("eve.channel.instrumentationKinds");
+
+// Nitro dev can evaluate a channel once for its route and again for a resolver
+// import, so separately created channel objects need a process-wide identity.
+type ChannelInstrumentationKindGlobal = typeof globalThis & {
+ [CHANNEL_INSTRUMENTATION_KINDS]?: Map<string, string>;
+};
+
+const channelInstrumentationKindGlobal = globalThis as ChannelInstrumentationKindGlobal;
+channelInstrumentationKindGlobal[CHANNEL_INSTRUMENTATION_KINDS] ??= new Map();
+const channelInstrumentationKinds = channelInstrumentationKindGlobal[CHANNEL_INSTRUMENTATION_KINDS];
export interface CompiledChannel<
TState = undefined,
@@ -44,9 +55,12 @@ export function getChannelInstrumentationKind(value: unknown): string | undefine
}
const adapterKind = value.adapter.kind;
- return typeof adapterKind === "string" && adapterKind.startsWith("channel:")
- ? adapterKind
- : undefined;
+ if (typeof adapterKind === "string" && adapterKind.startsWith("channel:")) {
+ return adapterKind;
+ }
+
+ const routeSignature = channelRouteSignature(value);
+ return routeSignature === undefined ? undefined : channelInstrumentationKinds.get(routeSignature);
}
export function setChannelInstrumentationKind(channel: CompiledChannel, kind: string): void {
@@ -55,4 +69,16 @@ export function setChannelInstrumentationKind(channel: CompiledChannel, kind: st
enumerable: false,
value: kind,
});
+ const routeSignature = channelRouteSignature(channel);
+ if (routeSignature !== undefined) {
+ channelInstrumentationKinds.set(routeSignature, kind);
+ }
+}
+
+function channelRouteSignature(channel: CompiledChannel): string | undefined {
+ if (channel.routes.length === 0) return undefined;
+ return channel.routes
+ .map((route) => `${route.method.toUpperCase()} ${route.path}`)
+ .sort()
+ .join("\n");
}
diff --git a/packages/eve/src/evals/assertions/collector.ts b/packages/eve/src/evals/assertions/collector.ts
index 473c52713..64a7b43e0 100644
--- a/packages/eve/src/evals/assertions/collector.ts
+++ b/packages/eve/src/evals/assertions/collector.ts
@@ -5,6 +5,7 @@ import type {
AssertionSeverity,
EveEvalTaskResult,
} from "#evals/types.js";
+import type { EveEvalAssertionSubject } from "#evals/assertions/run.js";
/**
* Outcome of evaluating one assertion: a 0–1 score (boolean assertions use
@@ -17,13 +18,12 @@ export interface AssertionOutcome {
}
/**
- * A run-level assertion (e.g. `t.completed()`), evaluated lazily against the
- * final task result after `test(t)` returns. The evaluation is deferred so
- * the assertion always sees the complete run regardless of call order.
+ * A scoped assertion evaluated lazily after `test(t)` returns. The selected
+ * subject may be the aggregate run, one session, or one immutable turn.
*/
export interface RunAssertion {
readonly name: string;
- evaluate(result: EveEvalTaskResult): AssertionOutcome | Promise<AssertionOutcome>;
+ evaluate(result: EveEvalAssertionSubject): AssertionOutcome | Promise<AssertionOutcome>;
}
interface MutableEntry {
@@ -32,6 +32,7 @@ interface MutableEntry {
threshold: number | undefined;
readonly kind: "deferred" | "resolved";
readonly spec?: RunAssertion;
+ readonly selectSubject?: (result: EveEvalTaskResult) => EveEvalAssertionSubject;
score: number;
message?: string;
metadata?: Readonly<Record<string, unknown>>;
@@ -50,19 +51,29 @@ export class AssertionCollector {
readonly #entries: MutableEntry[] = [];
readonly #pending: Promise<void>[] = [];
- /** Register a run-level assertion evaluated against the final result. */
- recordRun(spec: RunAssertion, severity: AssertionSeverity = "gate"): AssertionHandle {
+ /** Whether the eval has already recorded an assertion. */
+ get hasEntries(): boolean {
+ return this.#entries.length > 0;
+ }
+
+ /** Register a deferred assertion against a turn or session scope. */
+ recordScoped(
+ spec: RunAssertion,
+ selectSubject: (result: EveEvalTaskResult) => EveEvalAssertionSubject,
+ severity: AssertionSeverity = "gate",
+ ): AssertionHandle {
const entry: MutableEntry = {
name: spec.name,
severity,
threshold: undefined,
kind: "deferred",
spec,
+ selectSubject,
score: 0,
failed: false,
};
this.#entries.push(entry);
- return makeHandle(entry, Promise.resolve());
+ return makeHandle(entry);
}
/** Register a value/judge assertion, evaluating the captured value now. */
@@ -82,25 +93,45 @@ export class AssertionCollector {
};
this.#entries.push(entry);
- const pending = input
- .score()
- .then((outcome) => {
- entry.score = outcome.score;
- entry.message = outcome.message;
- entry.metadata = outcome.metadata;
- })
- .catch((error: unknown) => {
- // A judge/value assertion that throws (e.g. a judge model error) is a
- // hard failure, surfaced as a failed gate rather than aborting the run.
- entry.score = 0;
- entry.severity = "gate";
- entry.threshold = undefined;
- entry.message = toErrorMessage(error);
- entry.failed = true;
- });
+ const pending = settleEntry(entry, input.score);
this.#pending.push(pending);
- return makeHandle(entry, pending);
+ return makeHandle(entry);
+ }
+
+ /** Record an already-computed assertion outcome and return whether it passed. */
+ recordOutcome(input: { readonly name: string; readonly outcome: AssertionOutcome }): boolean {
+ const entry: MutableEntry = {
+ name: input.name,
+ severity: "gate",
+ threshold: undefined,
+ kind: "resolved",
+ score: input.outcome.score,
+ message: input.outcome.message,
+ metadata: input.outcome.metadata,
+ failed: false,
+ };
+ this.#entries.push(entry);
+ return computePassed(entry.severity, entry.threshold, entry.score, entry.failed);
+ }
+
+ /** Record and await a required value assertion, returning whether it passed. */
+ async recordRequirement(input: {
+ readonly name: string;
+ readonly threshold?: number;
+ readonly score: () => Promise<AssertionOutcome>;
+ }): Promise<boolean> {
+ const entry: MutableEntry = {
+ name: input.name,
+ severity: "gate",
+ threshold: input.threshold,
+ kind: "resolved",
+ score: 0,
+ failed: false,
+ };
+ this.#entries.push(entry);
+ await settleEntry(entry, input.score);
+ return computePassed(entry.severity, entry.threshold, entry.score, entry.failed);
}
/**
@@ -113,7 +144,7 @@ export class AssertionCollector {
const results: AssertionResult[] = [];
for (const entry of this.#entries) {
if (entry.kind === "deferred" && entry.spec !== undefined) {
- const outcome = await entry.spec.evaluate(result);
+ const outcome = await entry.spec.evaluate(entry.selectSubject?.(result) ?? result);
entry.score = outcome.score;
entry.message = outcome.message;
entry.metadata = outcome.metadata;
@@ -148,7 +179,27 @@ function computePassed(
return min === undefined || score >= min;
}
-function makeHandle(entry: MutableEntry, pending: Promise<void>): AssertionHandle {
+async function settleEntry(
+ entry: MutableEntry,
+ score: () => Promise<AssertionOutcome>,
+): Promise<void> {
+ try {
+ const outcome = await score();
+ entry.score = outcome.score;
+ entry.message = outcome.message;
+ entry.metadata = outcome.metadata;
+ } catch (error: unknown) {
+ // A judge/value assertion that throws (e.g. a judge model error) is a
+ // hard failure, surfaced as a failed gate rather than aborting the run.
+ entry.score = 0;
+ entry.severity = "gate";
+ entry.threshold = undefined;
+ entry.message = toErrorMessage(error);
+ entry.failed = true;
+ }
+}
+
+function makeHandle(entry: MutableEntry): AssertionHandle {
const handle: AssertionHandle = {
gate(threshold) {
entry.severity = "gate";
@@ -165,12 +216,6 @@ function makeHandle(entry: MutableEntry, pending: Promise<void>): AssertionHandl
entry.threshold = threshold;
return handle;
},
- // The handle is intentionally a PromiseLike so `await t.judge.…()` resolves
- // the judge call and surfaces its errors before the run continues.
- // oxlint-disable-next-line no-thenable
- then(onfulfilled, onrejected) {
- return pending.then(onfulfilled, onrejected);
- },
};
return handle;
}
diff --git a/packages/eve/src/evals/assertions/run.test.ts b/packages/eve/src/evals/assertions/run.test.ts
index 92bd8f94f..e9ee68697 100644
--- a/packages/eve/src/evals/assertions/run.test.ts
+++ b/packages/eve/src/evals/assertions/run.test.ts
@@ -2,7 +2,12 @@ import { describe, expect, it } from "vitest";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import { createEmptyDerivedFacts } from "#evals/runner/derive-run-facts.js";
-import type { EveEvalDerivedFacts, EveEvalTaskResult, EveEvalToolCall } from "#evals/types.js";
+import type {
+ EveEvalDerivedFacts,
+ EveEvalSubagentCall,
+ EveEvalTaskResult,
+ EveEvalToolCall,
+} from "#evals/types.js";
import * as Run from "#evals/assertions/run.js";
function makeResult(overrides: {
@@ -21,7 +26,20 @@ function makeResult(overrides: {
}
function toolCall(name: string, input: EveEvalToolCall["input"] = {}): EveEvalToolCall {
- return { name, input, output: undefined, isError: false, turnIndex: 0 };
+ return { name, input, output: undefined, status: "pending", turnIndex: 0 };
+}
+
+function completedToolCall(name: string): EveEvalToolCall {
+ return { ...toolCall(name), output: "ok", status: "completed" };
+}
+
+function subagentCall(name: string, status: EveEvalSubagentCall["status"]): EveEvalSubagentCall {
+ return {
+ name,
+ output: status === "completed" ? "ok" : undefined,
+ status,
+ turnIndex: 0,
+ };
}
function message(text: string): HandleMessageStreamEvent {
@@ -31,15 +49,69 @@ function message(text: string): HandleMessageStreamEvent {
} as HandleMessageStreamEvent;
}
+function actionsRequested(
+ actions: readonly { readonly callId: string; readonly toolName: string }[],
+): HandleMessageStreamEvent {
+ return {
+ type: "actions.requested",
+ data: {
+ actions: actions.map((action) => ({ ...action, input: {}, kind: "tool-call" as const })),
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "t1",
+ },
+ };
+}
+
+function actionResult(callId: string, toolName: string): HandleMessageStreamEvent {
+ return {
+ type: "action.result",
+ data: {
+ result: { callId, kind: "tool-result", output: null, toolName },
+ sequence: 2,
+ status: "completed",
+ stepIndex: 0,
+ turnId: "t1",
+ },
+ };
+}
+
describe("run assertions", () => {
- it("completed passes a clean run and fails a failed or parked run", async () => {
- expect((await Run.completed().evaluate(makeResult({ status: "completed" }))).score).toBe(1);
- expect((await Run.completed().evaluate(makeResult({ status: "failed" }))).score).toBe(0);
- expect((await Run.completed().evaluate(makeResult({ derived: { parked: true } }))).score).toBe(
+ it("succeeded passes a clean run and fails a failed or parked run", async () => {
+ expect((await Run.succeeded().evaluate(makeResult({ status: "completed" }))).score).toBe(1);
+ expect((await Run.succeeded().evaluate(makeResult({ status: "failed" }))).score).toBe(0);
+ expect((await Run.succeeded().evaluate(makeResult({ derived: { parked: true } }))).score).toBe(
0,
);
});
+ it("succeeded rejects failure events even when the terminal status is completed", async () => {
+ const failedEvent = {
+ type: "step.failed",
+ data: {
+ code: "STEP_FAILED",
+ message: "step failed",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "t1",
+ },
+ } as HandleMessageStreamEvent;
+
+ expect(
+ (await Run.succeeded().evaluate(makeResult({ status: "completed", events: [failedEvent] })))
+ .score,
+ ).toBe(0);
+ });
+
+ it("parked requires a clean HITL park", async () => {
+ expect((await Run.parked().evaluate(makeResult({ derived: { parked: true } }))).score).toBe(1);
+ expect((await Run.parked().evaluate(makeResult({}))).score).toBe(0);
+ expect(
+ (await Run.parked().evaluate(makeResult({ status: "failed", derived: { parked: true } })))
+ .score,
+ ).toBe(0);
+ });
+
it("messageIncludes matches substrings of completed messages", async () => {
const result = makeResult({ events: [message("hello there")] });
expect((await Run.messageIncludes("hello").evaluate(result)).score).toBe(1);
@@ -48,7 +120,10 @@ describe("run assertions", () => {
it("calledTool matches by name and input, with an exact-count option", async () => {
const result = makeResult({
- derived: { toolCalls: [toolCall("get_weather", { city: "SF" })], toolCallCount: 1 },
+ derived: {
+ toolCalls: [{ ...completedToolCall("get_weather"), input: { city: "SF" } }],
+ toolCallCount: 1,
+ },
});
expect((await Run.calledTool("get_weather").evaluate(result)).score).toBe(1);
expect(
@@ -60,10 +135,172 @@ describe("run assertions", () => {
expect((await Run.calledTool("missing").evaluate(result)).score).toBe(0);
});
+ it("calledTool defaults to completed while notCalledTool rejects every lifecycle state", async () => {
+ const result = makeResult({
+ derived: {
+ toolCalls: [toolCall("guarded"), completedToolCall("done")],
+ toolCallCount: 2,
+ },
+ });
+ expect((await Run.calledTool("guarded", { status: "pending" }).evaluate(result)).score).toBe(1);
+ expect((await Run.calledTool("guarded").evaluate(result)).score).toBe(0);
+ expect(
+ (await Run.calledTool("done", { output: (value) => value === "ok" }).evaluate(result)).score,
+ ).toBe(1);
+ expect((await Run.notCalledTool("guarded").evaluate(result)).score).toBe(0);
+ expect((await Run.notCalledTool("missing").evaluate(result)).score).toBe(1);
+ });
+
+ it("validates exact-count options", () => {
+ expect(() => Run.calledTool("search", { count: -1 })).toThrow(/non-negative integer/);
+ expect(() => Run.calledSubagent("child", { count: 1.5 })).toThrow(/non-negative integer/);
+ expect(() => Run.typedEvent({ type: "turn.completed", count: Number.NaN })).toThrow(
+ /non-negative integer/,
+ );
+ });
+
+ it("calledSubagent matches every lifecycle status and exact counts", async () => {
+ const result = makeResult({
+ derived: {
+ subagentCalls: [
+ subagentCall("child", "pending"),
+ subagentCall("child", "completed"),
+ subagentCall("child", "failed"),
+ subagentCall("child", "rejected"),
+ ],
+ subagentCallCount: 4,
+ },
+ });
+
+ expect((await Run.calledSubagent("child").evaluate(result)).score).toBe(1);
+ for (const status of ["pending", "completed", "failed", "rejected"] as const) {
+ expect((await Run.calledSubagent("child", { status, count: 1 }).evaluate(result)).score).toBe(
+ 1,
+ );
+ }
+ expect(
+ (await Run.calledSubagent("child", { status: "completed", count: 2 }).evaluate(result)).score,
+ ).toBe(0);
+ });
+
+ it("toolOrder checks request order", async () => {
+ const ordered = makeResult({
+ events: [
+ actionsRequested([
+ { callId: "call-a", toolName: "step-a" },
+ { callId: "call-b", toolName: "step-b" },
+ ]),
+ ],
+ });
+ const reversed = makeResult({
+ events: [
+ actionsRequested([
+ { callId: "call-b", toolName: "step-b" },
+ { callId: "call-a", toolName: "step-a" },
+ ]),
+ ],
+ });
+
+ expect((await Run.toolOrder(["step-a", "step-b"]).evaluate(ordered)).score).toBe(1);
+ expect((await Run.toolOrder(["step-a", "step-b"]).evaluate(reversed)).score).toBe(0);
+ });
+
+ it("toolOrder ignores calls synthesized from result-only events", async () => {
+ const result = makeResult({
+ events: [actionResult("call-a", "step-a")],
+ derived: { toolCalls: [completedToolCall("step-a")], toolCallCount: 1 },
+ });
+
+ expect((await Run.toolOrder(["step-a"]).evaluate(result)).score).toBe(0);
+ });
+
+ it("matches typed event counts and ordered event groups", async () => {
+ const called = {
+ type: "subagent.called",
+ data: {
+ name: "child",
+ callId: "c",
+ childSessionId: "s",
+ sessionId: "p",
+ sequence: 1,
+ toolName: "subagent",
+ turnId: "t",
+ workflowId: "w",
+ },
+ } as HandleMessageStreamEvent;
+ const completed = {
+ type: "subagent.completed",
+ data: { callId: "c", output: "ok", sequence: 2, subagentName: "child", turnId: "t" },
+ } as HandleMessageStreamEvent;
+ const result = makeResult({ events: [called, called, completed] });
+
+ expect(
+ (
+ await Run.typedEvent({
+ type: "subagent.called",
+ data: { name: "child" },
+ count: 2,
+ }).evaluate(result)
+ ).score,
+ ).toBe(1);
+ expect((await Run.notEvent({ type: "turn.failed" }).evaluate(result)).score).toBe(1);
+ expect(
+ (
+ await Run.eventOrder([
+ { type: "subagent.called", data: { name: "child" }, count: 2 },
+ { type: "subagent.completed", data: { subagentName: "child" } },
+ ]).evaluate(result)
+ ).score,
+ ).toBe(1);
+ expect(
+ (
+ await Run.eventsSatisfy(
+ "completion follows delegation",
+ (events) => events.at(-1)?.type === "subagent.completed",
+ ).evaluate(result)
+ ).score,
+ ).toBe(1);
+ });
+
+ it("eventOrder rejects interleaved event groups", async () => {
+ const called = {
+ type: "subagent.called",
+ data: {
+ name: "child",
+ callId: "c",
+ childSessionId: "s",
+ sessionId: "p",
+ sequence: 1,
+ toolName: "subagent",
+ turnId: "t",
+ workflowId: "w",
+ },
+ } as HandleMessageStreamEvent;
+ const completed = {
+ type: "subagent.completed",
+ data: { callId: "c", output: "ok", sequence: 2, subagentName: "child", turnId: "t" },
+ } as HandleMessageStreamEvent;
+ const result = makeResult({ events: [called, completed, called] });
+
+ expect(
+ (
+ await Run.eventOrder([
+ { type: "subagent.called", data: { name: "child" }, count: 2 },
+ { type: "subagent.completed", data: { subagentName: "child" } },
+ ]).evaluate(result)
+ ).score,
+ ).toBe(0);
+ });
+
it("loadedSkill matches a load_skill call by skill id", async () => {
const result = makeResult({
derived: {
- toolCalls: [toolCall("load_skill", { skill: "custom__talk-like-a-dog" })],
+ toolCalls: [
+ {
+ ...completedToolCall("load_skill"),
+ input: { skill: "custom__talk-like-a-dog" },
+ },
+ ],
toolCallCount: 1,
},
});
diff --git a/packages/eve/src/evals/assertions/run.ts b/packages/eve/src/evals/assertions/run.ts
index 7aeb63179..e2aa87837 100644
--- a/packages/eve/src/evals/assertions/run.ts
+++ b/packages/eve/src/evals/assertions/run.ts
@@ -2,6 +2,7 @@ import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js"
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import {
deepEquals,
+ eventMatches,
subagentCallMatches,
testRegExp,
toolCallMatches,
@@ -9,9 +10,18 @@ import {
type EveEvalSubagentCallMatchOptions,
type EveEvalToolCallMatchOptions,
} from "#evals/match.js";
+import type { EveEvalEventMatch } from "#evals/match.js";
import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
import type { AssertionOutcome, RunAssertion } from "#evals/assertions/collector.js";
+/** Minimal captured scope consumed by deterministic eval assertions. */
+export interface EveEvalAssertionSubject {
+ readonly derived: import("#evals/types.js").EveEvalDerivedFacts;
+ readonly events: readonly HandleMessageStreamEvent[];
+ readonly output: unknown;
+ readonly status: "completed" | "failed" | "waiting";
+}
+
const PASS: AssertionOutcome = { score: 1 };
const fail = (message: string, metadata?: Readonly<Record<string, unknown>>): AssertionOutcome => ({
score: 0,
@@ -20,16 +30,15 @@ const fail = (message: string, metadata?: Readonly<Record<string, unknown>>): As
});
/**
- * Asserts the run ran to completion: it did not fail and did not park on an
+ * Asserts the run finished successfully: it did not fail and did not park on an
* unanswered HITL input request.
*/
-export function completed(): RunAssertion {
+export function succeeded(): RunAssertion {
return {
- name: "completed",
+ name: "succeeded",
evaluate(result) {
- if (result.status === "failed") {
- return fail(failureDetail("run failed", result.derived.failureCode));
- }
+ const failure = runFailure(result);
+ if (failure !== undefined) return failure;
if (result.derived.parked) {
return fail(
`run parked on ${result.derived.inputRequests.length} unanswered input request(s)`,
@@ -41,13 +50,14 @@ export function completed(): RunAssertion {
}
/**
- * Asserts the run ended parked on HITL input. For approval gates and
- * ask-question flows.
+ * Asserts the run ended cleanly parked on HITL input.
*/
-export function waiting(): RunAssertion {
+export function parked(): RunAssertion {
return {
- name: "waiting",
+ name: "parked",
evaluate(result) {
+ const failure = runFailure(result);
+ if (failure !== undefined) return failure;
if (result.derived.parked) return PASS;
return fail(
`expected the run to park on HITL input; it ended "${result.status}" with no pending requests`,
@@ -56,32 +66,6 @@ export function waiting(): RunAssertion {
};
}
-/**
- * Asserts the run did not fail: terminal status is not `"failed"` and no
- * `turn.failed` / `step.failed` events were emitted. Parked runs pass; use
- * {@link completed} to also reject parking.
- */
-export function didNotFail(): RunAssertion {
- return {
- name: "didNotFail",
- evaluate(result) {
- if (result.status === "failed") {
- return fail(failureDetail("run failed", result.derived.failureCode));
- }
- const failedEvent = result.events.find(
- (
- event,
- ): event is Extract<HandleMessageStreamEvent, { type: "step.failed" | "turn.failed" }> =>
- event.type === "turn.failed" || event.type === "step.failed",
- );
- if (failedEvent !== undefined) {
- return fail(`${failedEvent.type} (${failedEvent.data.code}): ${failedEvent.data.message}`);
- }
- return PASS;
- },
- };
-}
-
/**
* Asserts the joined assistant message text contains `token` (substring for
* strings, `test` for RegExps).
@@ -99,18 +83,19 @@ export function messageIncludes(token: string | RegExp): RunAssertion {
}
/**
- * Asserts a tool call with `name` happened. Options constrain the call
- * further: `input` partial-deep-matches, `output` matches the result,
- * `isError` constrains error state, and `times` requires an exact count.
+ * Asserts a completed tool call with `name` happened. Options constrain the
+ * call further: `input` partial-deep-matches, `output` matches the result,
+ * `status` overrides the lifecycle state, and `count` requires an exact count.
*/
export function calledTool(name: string, options: EveEvalToolCallMatchOptions = {}): RunAssertion {
+ validateCount(options.count);
return {
name: `calledTool(${name})`,
evaluate(result) {
const named = result.derived.toolCalls.filter((call) => call.name === name);
const matching = named.filter((call) => toolCallMatches(call, options));
const passed =
- options.times !== undefined ? matching.length === options.times : matching.length > 0;
+ options.count !== undefined ? matching.length === options.count : matching.length > 0;
if (passed) return { score: 1, metadata: { matchingCalls: matching.length } };
const observed =
@@ -118,8 +103,8 @@ export function calledTool(name: string, options: EveEvalToolCallMatchOptions =
? `observed ${name} calls: ${named.map((call) => truncate(JSON.stringify(call.input))).join(", ")}`
: `observed tools: [${result.derived.toolCalls.map((call) => call.name).join(", ")}]`;
const expectation =
- options.times !== undefined
- ? `expected exactly ${options.times} matching call(s), found ${matching.length}`
+ options.count !== undefined
+ ? `expected exactly ${options.count} matching call(s), found ${matching.length}`
: `expected a matching call to "${name}"`;
return fail(`${expectation}; ${observed}`);
},
@@ -128,7 +113,7 @@ export function calledTool(name: string, options: EveEvalToolCallMatchOptions =
/**
* Sugar over {@link calledTool} for the framework `load_skill` tool: asserts a
- * skill with id `skill` was loaded. `output`/`isError`/`times` constrain the
+ * skill with id `skill` was loaded. `output`/`status`/`count` constrain the
* matching call exactly as for `calledTool`.
*/
export function loadedSkill(
@@ -154,23 +139,22 @@ export function notCalledTool(name: string): RunAssertion {
}
/**
- * Asserts the named tools were called in the given order (subsequence match:
+ * Asserts the named tools were requested in the given order (subsequence match:
* other calls may interleave).
*/
export function toolOrder(names: readonly string[]): RunAssertion {
return {
name: `toolOrder(${names.join(" → ")})`,
evaluate(result) {
- const observed = result.derived.toolCalls.map((call) => call.name);
- let cursor = 0;
- for (const name of observed) {
- if (name === names[cursor]) cursor += 1;
- if (cursor === names.length) break;
+ const requested = requestedTools(result.events);
+ const observed = requested.map((entry) => entry.name);
+ const missing = missingOrderedName(names, observed);
+ if (missing !== undefined) {
+ return fail(
+ `missing "${missing.name}" after [${names.slice(0, missing.cursor).join(", ")}]; observed request order: [${observed.join(", ")}]`,
+ );
}
- if (cursor === names.length) return PASS;
- return fail(
- `missing "${names[cursor]}" after [${names.slice(0, cursor).join(", ")}]; observed order: [${observed.join(", ")}]`,
- );
+ return PASS;
},
};
}
@@ -193,6 +177,7 @@ export function usedNoTools(): RunAssertion {
* Asserts the run made at most `max` tool calls.
*/
export function maxToolCalls(max: number): RunAssertion {
+ validateCount(max);
return {
name: `maxToolCalls(${max})`,
evaluate(result) {
@@ -236,12 +221,15 @@ export function calledSubagent(
name: string,
options: EveEvalSubagentCallMatchOptions = {},
): RunAssertion {
+ validateCount(options.count);
return {
name: `calledSubagent(${name})`,
evaluate(result) {
const named = result.derived.subagentCalls.filter((call) => call.name === name);
const matching = named.filter((call) => subagentCallMatches(call, options));
- if (matching.length > 0) return PASS;
+ const passed =
+ options.count === undefined ? matching.length > 0 : matching.length === options.count;
+ if (passed) return { score: 1, metadata: { matchingCalls: matching.length } };
if (named.length === 0) {
const observed = result.derived.subagentCalls.map((call) => call.name);
@@ -249,9 +237,12 @@ export function calledSubagent(
observedSubagentCalls: result.derived.subagentCalls,
});
}
- return fail(`subagent "${name}" was called but no call matched the constraints`, {
- observedSubagentCalls: named,
- });
+ return fail(
+ `subagent "${name}" was called but ${matching.length} call(s) matched the constraints`,
+ {
+ observedSubagentCalls: named,
+ },
+ );
},
};
}
@@ -260,12 +251,12 @@ export function calledSubagent(
* Escape hatch: asserts an arbitrary predicate over the full typed event
* stream. `label` names the assertion in reports.
*/
-export function event(
- predicate: (events: readonly HandleMessageStreamEvent[]) => boolean,
+export function eventsSatisfy(
label: string,
+ predicate: (events: readonly HandleMessageStreamEvent[]) => boolean,
): RunAssertion {
return {
- name: `event(${label})`,
+ name: `eventsSatisfy(${label})`,
evaluate(result) {
if (predicate(result.events)) return PASS;
return fail(`event predicate "${label}" did not hold`);
@@ -273,6 +264,68 @@ export function event(
};
}
+/** Asserts a typed stream event exists, optionally with an exact count. */
+export function typedEvent(matcher: EveEvalEventMatch): RunAssertion {
+ validateCount(matcher.count);
+ return {
+ name: `event(${matcher.type})`,
+ evaluate(result) {
+ const matching = result.events.filter((entry) => eventMatches(entry, matcher));
+ const passed =
+ matcher.count === undefined ? matching.length > 0 : matching.length === matcher.count;
+ if (passed) return { score: 1, metadata: { matchingEvents: matching.length } };
+ const expected = matcher.count === undefined ? "at least one" : `exactly ${matcher.count}`;
+ return fail(
+ `expected ${expected} matching ${matcher.type} event(s), found ${matching.length}; observed: [${result.events.map((entry) => entry.type).join(", ")}]`,
+ );
+ },
+ };
+}
+
+/** Asserts no typed stream event matches. */
+export function notEvent(matcher: EveEvalEventMatch): RunAssertion {
+ return {
+ name: `notEvent(${matcher.type})`,
+ evaluate(result) {
+ const matching = result.events.filter((entry) => eventMatches(entry, matcher));
+ return matching.length === 0
+ ? PASS
+ : fail(`expected no matching ${matcher.type} events, found ${matching.length}`);
+ },
+ };
+}
+
+/** Asserts typed event groups occur in order, ignoring unrelated events. */
+export function eventOrder(matchers: readonly EveEvalEventMatch[]): RunAssertion {
+ for (const matcher of matchers) validateCount(matcher.count);
+ return {
+ name: `eventOrder(${matchers.map((matcher) => matcher.type).join(" → ")})`,
+ evaluate(result) {
+ let previousLast = -1;
+ for (const matcher of matchers) {
+ const indexes = result.events.flatMap((entry, index) =>
+ eventMatches(entry, matcher) ? [index] : [],
+ );
+ const countPassed =
+ matcher.count === undefined ? indexes.length > 0 : indexes.length === matcher.count;
+ if (!countPassed) {
+ const expected =
+ matcher.count === undefined ? "at least one" : `exactly ${matcher.count}`;
+ return fail(
+ `expected ${expected} matching ${matcher.type} event(s), found ${indexes.length}`,
+ );
+ }
+ const first = indexes[0];
+ if (first === undefined || first <= previousLast) {
+ return fail(`event group ${matcher.type} did not occur after the previous group`);
+ }
+ previousLast = indexes[indexes.length - 1] ?? previousLast;
+ }
+ return PASS;
+ },
+ };
+}
+
/**
* Asserts `result.output` (the final assistant message) deep-equals `value`.
*/
@@ -318,7 +371,68 @@ function failureDetail(prefix: string, code: string | undefined): string {
return code === undefined ? prefix : `${prefix} (code: ${code})`;
}
+function runFailure(result: EveEvalAssertionSubject): AssertionOutcome | undefined {
+ if (result.status === "failed") {
+ return fail(failureDetail("run failed", result.derived.failureCode));
+ }
+ const failedEvent = result.events.find(
+ (event): event is Extract<HandleMessageStreamEvent, { type: "step.failed" | "turn.failed" }> =>
+ event.type === "turn.failed" || event.type === "step.failed",
+ );
+ return failedEvent === undefined
+ ? undefined
+ : fail(`${failedEvent.type} (${failedEvent.data.code}): ${failedEvent.data.message}`);
+}
+
function truncate(text: string | undefined, max = 200): string {
if (text === undefined) return "undefined";
return text.length <= max ? text : `${text.slice(0, max)}…`;
}
+
+function validateCount(count: number | undefined): void {
+ if (count !== undefined && (!Number.isInteger(count) || count < 0)) {
+ throw new TypeError(`Assertion count must be a non-negative integer; received ${count}.`);
+ }
+}
+
+function missingOrderedName(
+ expected: readonly string[],
+ observed: readonly string[],
+): { readonly cursor: number; readonly name: string } | undefined {
+ let cursor = 0;
+ for (const name of observed) {
+ if (name === expected[cursor]) cursor += 1;
+ if (cursor === expected.length) return undefined;
+ }
+ const name = expected[cursor];
+ return name === undefined ? undefined : { cursor, name };
+}
+
+interface ToolRequestEntry {
+ readonly callId: string;
+ readonly name: string;
+}
+
+function requestedTools(events: readonly HandleMessageStreamEvent[]): readonly ToolRequestEntry[] {
+ const entries: ToolRequestEntry[] = [];
+ const seenCallIds = new Set<string>();
+ const append = (callId: string, name: string): void => {
+ if (seenCallIds.has(callId)) return;
+ seenCallIds.add(callId);
+ entries.push({ callId, name });
+ };
+
+ for (const event of events) {
+ if (event.type === "actions.requested") {
+ for (const action of event.data.actions) {
+ if (action.kind === "tool-call") append(action.callId, action.toolName);
+ }
+ } else if (event.type === "input.requested") {
+ for (const request of event.data.requests) {
+ const { action } = request;
+ if (action.kind === "tool-call") append(action.callId, action.toolName);
+ }
+ }
+ }
+ return entries;
+}
diff --git a/packages/eve/src/evals/assertions/scoped.ts b/packages/eve/src/evals/assertions/scoped.ts
new file mode 100644
index 000000000..b100e86c7
--- /dev/null
+++ b/packages/eve/src/evals/assertions/scoped.ts
@@ -0,0 +1,72 @@
+import { AssertionCollector, type RunAssertion } from "#evals/assertions/collector.js";
+import * as RunAssertions from "#evals/assertions/run.js";
+import type { EveEvalAssertionSubject } from "#evals/assertions/run.js";
+import type { EveEvalEventMatch } from "#evals/match.js";
+import type {
+ EveEvalAssertions,
+ EveEvalOutputAssertions,
+ EveEvalTaskResult,
+} from "#evals/types.js";
+
+type AssertionScope =
+ | {
+ readonly timing: "final";
+ select(result: EveEvalTaskResult): EveEvalAssertionSubject;
+ }
+ | {
+ readonly timing: "snapshot";
+ select(): EveEvalAssertionSubject;
+ };
+
+/** Binds the shared assertion vocabulary to one aggregate, session, or turn scope. */
+export function createScopedAssertions(
+ collector: AssertionCollector,
+ scope: AssertionScope,
+): EveEvalAssertions {
+ const record = createRecorder(collector, scope);
+
+ return {
+ succeeded: () => record(RunAssertions.succeeded()),
+ parked: () => record(RunAssertions.parked()),
+ messageIncludes: (token) => record(RunAssertions.messageIncludes(token)),
+ calledTool: (name, options) => record(RunAssertions.calledTool(name, options)),
+ loadedSkill: (skill, options) => record(RunAssertions.loadedSkill(skill, options)),
+ notCalledTool: (name) => record(RunAssertions.notCalledTool(name)),
+ toolOrder: (names) => record(RunAssertions.toolOrder(names)),
+ usedNoTools: () => record(RunAssertions.usedNoTools()),
+ maxToolCalls: (max) => record(RunAssertions.maxToolCalls(max)),
+ calledSubagent: (name, options) => record(RunAssertions.calledSubagent(name, options)),
+ noFailedActions: () => record(RunAssertions.noFailedActions()),
+ event: (type, options) =>
+ record(RunAssertions.typedEvent({ ...options, type } as EveEvalEventMatch)),
+ notEvent: (type, options) =>
+ record(RunAssertions.notEvent({ ...options, type } as EveEvalEventMatch)),
+ eventOrder: (matchers) => record(RunAssertions.eventOrder(matchers)),
+ eventsSatisfy: (label, predicate) => record(RunAssertions.eventsSatisfy(label, predicate)),
+ };
+}
+
+/** Binds output-only assertions to a session or immutable turn snapshot. */
+export function createOutputAssertions(
+ collector: AssertionCollector,
+ scope: Extract<AssertionScope, { timing: "snapshot" }>,
+): EveEvalOutputAssertions {
+ const record = createRecorder(collector, scope);
+ return {
+ outputEquals: (value) => record(RunAssertions.outputEquals(value)),
+ outputMatches: (schema) => record(RunAssertions.outputMatches(schema)),
+ };
+}
+
+function createRecorder(
+ collector: AssertionCollector,
+ scope: AssertionScope,
+): (assertion: RunAssertion) => import("#evals/types.js").AssertionHandle {
+ if (scope.timing === "final") {
+ return (assertion) => collector.recordScoped(assertion, scope.select);
+ }
+ return (assertion) => {
+ const subject = scope.select();
+ return collector.recordScoped(assertion, () => subject);
+ };
+}
diff --git a/packages/eve/src/evals/context.ts b/packages/eve/src/evals/context.ts
index 9d3d864fe..62985a443 100644
--- a/packages/eve/src/evals/context.ts
+++ b/packages/eve/src/evals/context.ts
@@ -1,8 +1,9 @@
import type { SendTurnInput } from "#client/types.js";
import { EvalSessionManager } from "#evals/session.js";
import { AssertionCollector } from "#evals/assertions/collector.js";
-import * as RunAssertions from "#evals/assertions/run.js";
+import { createScopedAssertions } from "#evals/assertions/scoped.js";
import { buildJudgeContext } from "#evals/judge.js";
+import { EvalRequirementFailed, EvalSkipped } from "#evals/control-flow.js";
import type {
Assertion,
AssertionHandle,
@@ -19,12 +20,13 @@ import type {
*/
export function createEvalContext(deps: {
readonly manager: EvalSessionManager;
+ readonly collector: AssertionCollector;
readonly target: EveEvalTargetHandle;
readonly signal: AbortSignal;
readonly judge: EveEvalJudgeConfig | undefined;
readonly log: (message: string) => void;
}): { readonly context: EveEvalContext; readonly collector: AssertionCollector } {
- const collector = new AssertionCollector();
+ const collector = deps.collector;
let lastPrompt = "";
const primary = () => deps.manager.primary;
@@ -51,7 +53,7 @@ export function createEvalContext(deps: {
get sessionId() {
return primary().sessionId;
},
- expectInputRequests: (filter) => primary().expectInputRequests(filter),
+ requireInputRequest: (filter) => primary().requireInputRequest(filter),
respond: (...responses) => primary().respond(...responses),
respondAll: (optionId) => primary().respondAll(optionId),
send: (input) => {
@@ -72,27 +74,18 @@ export function createEvalContext(deps: {
log: deps.log,
sleep: (ms) => sleep(ms, deps.signal),
newSession: () => deps.manager.newSession(),
-
- // Run-level assertions (lazy; default gate).
- completed: () => collector.recordRun(RunAssertions.completed()),
- didNotFail: () => collector.recordRun(RunAssertions.didNotFail()),
- waiting: () => collector.recordRun(RunAssertions.waiting()),
- messageIncludes: (token) => collector.recordRun(RunAssertions.messageIncludes(token)),
- calledTool: (name, options) => collector.recordRun(RunAssertions.calledTool(name, options)),
- loadedSkill: (skill, options) => collector.recordRun(RunAssertions.loadedSkill(skill, options)),
- notCalledTool: (name) => collector.recordRun(RunAssertions.notCalledTool(name)),
- toolOrder: (names) => collector.recordRun(RunAssertions.toolOrder(names)),
- usedNoTools: () => collector.recordRun(RunAssertions.usedNoTools()),
- maxToolCalls: (max) => collector.recordRun(RunAssertions.maxToolCalls(max)),
- calledSubagent: (name, options) =>
- collector.recordRun(RunAssertions.calledSubagent(name, options)),
- noFailedActions: () => collector.recordRun(RunAssertions.noFailedActions()),
- event: (predicate, label) => collector.recordRun(RunAssertions.event(predicate, label)),
- outputEquals: (value) => collector.recordRun(RunAssertions.outputEquals(value)),
- outputMatches: (schema) => collector.recordRun(RunAssertions.outputMatches(schema)),
+ ...createScopedAssertions(collector, { timing: "final", select: (result) => result }),
// Value-level assertion over an explicit value.
check: (value, assertion) => recordCheck(collector, value, assertion),
+ require: (value, assertion) => requireCheck(collector, value, assertion),
+ skip: (reason) => {
+ if (reason.trim().length === 0) throw new Error("skip() requires a non-empty reason.");
+ if (collector.hasEntries || deps.manager.hasActivity()) {
+ throw new Error("skip() must be called before sending messages or recording assertions.");
+ }
+ throw new EvalSkipped(reason);
+ },
judge,
};
@@ -100,6 +93,23 @@ export function createEvalContext(deps: {
return { context, collector };
}
+async function requireCheck<T>(
+ collector: AssertionCollector,
+ value: T,
+ assertion: Assertion,
+): Promise<T> {
+ const gated = assertion.gate(assertion.threshold);
+ const passed = await collector.recordRequirement({
+ name: gated.name,
+ threshold: gated.threshold,
+ score: async () => {
+ return { score: await gated.score(value) };
+ },
+ });
+ if (!passed) throw new EvalRequirementFailed();
+ return value;
+}
+
function recordCheck(
collector: AssertionCollector,
value: unknown,
diff --git a/packages/eve/src/evals/control-flow.ts b/packages/eve/src/evals/control-flow.ts
new file mode 100644
index 000000000..40c10824e
--- /dev/null
+++ b/packages/eve/src/evals/control-flow.ts
@@ -0,0 +1,18 @@
+/** Internal signal used to stop an eval after a recorded required assertion fails. */
+export class EvalRequirementFailed extends Error {
+ constructor() {
+ super("A required eval assertion failed.");
+ this.name = "EvalRequirementFailed";
+ }
+}
+
+/** Internal signal used by `t.skip()` to produce a skipped verdict. */
+export class EvalSkipped extends Error {
+ readonly reason: string;
+
+ constructor(reason: string) {
+ super(reason);
+ this.name = "EvalSkipped";
+ this.reason = reason;
+ }
+}
diff --git a/packages/eve/src/evals/define-eval.ts b/packages/eve/src/evals/define-eval.ts
index f57a703d6..c12f31f09 100644
--- a/packages/eve/src/evals/define-eval.ts
+++ b/packages/eve/src/evals/define-eval.ts
@@ -3,7 +3,7 @@ import type { EveEvalDefinition, EveEvalInput } from "#evals/types.js";
/**
* Defines one eve eval. Each eval file is exactly one case: an imperative
* `test(t)` function that drives the agent (`t.send`, `t.respond`, …) and
- * asserts on what it produced (`t.completed()`, `t.check(...)`,
+ * asserts on what it produced (`t.succeeded()`, `t.check(...)`,
* `t.judge.autoevals.*`). Organize related evals with directory nesting under
* `evals/`, or default-export an array of evals to fan one file out over a
* dataset.
@@ -49,7 +49,7 @@ function validateEvalInput(input: EveEvalInput): void {
rejectLegacyKey(
input,
"checks",
- "Assert inline inside `test` (e.g. `t.completed()`, `t.calledTool(...)`).",
+ "Assert inline inside `test` (e.g. `t.succeeded()`, `t.calledTool(...)`).",
);
rejectLegacyKey(
input,
diff --git a/packages/eve/src/evals/expect/index.test.ts b/packages/eve/src/evals/expect/index.test.ts
index 711546ef4..e79023f2f 100644
--- a/packages/eve/src/evals/expect/index.test.ts
+++ b/packages/eve/src/evals/expect/index.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { equals, includes, similarity } from "#evals/expect/index.js";
+import { equals, includes, satisfies, similarity } from "#evals/expect/index.js";
describe("expect builders", () => {
it("includes scores 1 on substring, 0 otherwise, gate by default", () => {
@@ -11,6 +11,18 @@ describe("expect builders", () => {
expect(assertion.score(undefined)).toBe(0);
});
+ it("includes accepts regular expressions", () => {
+ expect(includes(/hello/iu).score("Hello there")).toBe(1);
+ expect(includes(/missing/iu).score("Hello there")).toBe(0);
+ });
+
+ it("satisfies names and evaluates a custom predicate", () => {
+ const assertion = satisfies<number>((value) => value > 2, "greater than two");
+ expect(assertion.name).toBe("satisfies(greater than two)");
+ expect(assertion.score(3)).toBe(1);
+ expect(assertion.score(2)).toBe(0);
+ });
+
it("equals deep-compares structurally, gate by default", () => {
const assertion = equals({ a: 1, b: [2, 3] });
expect(assertion.severity).toBe("gate");
diff --git a/packages/eve/src/evals/expect/index.ts b/packages/eve/src/evals/expect/index.ts
index 7185eff29..2f0701100 100644
--- a/packages/eve/src/evals/expect/index.ts
+++ b/packages/eve/src/evals/expect/index.ts
@@ -2,6 +2,7 @@ import { Levenshtein as AutoevalsLevenshtein } from "autoevals";
import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
import { deepEquals } from "#evals/match.js";
+import { testRegExp } from "#evals/match.js";
import type { Assertion, AssertionSeverity } from "#evals/types.js";
export type { Assertion, AssertionHandle, AssertionSeverity } from "#evals/types.js";
@@ -32,14 +33,31 @@ function makeAssertion(spec: AssertionSpec): Assertion {
}
/**
- * Passes when the value (coerced to a string) contains `substring`. A hard
- * gate by default. Apply with `t.check(value, includes("..."))`.
+ * Passes when the value (coerced to a string) contains a substring or matches
+ * a RegExp. A hard gate by default.
*/
-export function includes(substring: string): Assertion {
+export function includes(substring: string | RegExp): Assertion {
return makeAssertion({
name: `includes(${substring})`,
severity: "gate",
- score: (value) => (String(value ?? "").includes(substring) ? 1 : 0),
+ score: (value) => {
+ const text = String(value ?? "");
+ return (
+ typeof substring === "string" ? text.includes(substring) : testRegExp(substring, text)
+ )
+ ? 1
+ : 0;
+ },
+ });
+}
+
+/** Passes when `predicate` returns true for the supplied value. */
+export function satisfies<T = unknown>(predicate: (value: T) => boolean, label: string): Assertion {
+ if (label.trim().length === 0) throw new Error("satisfies() requires a non-empty label.");
+ return makeAssertion({
+ name: `satisfies(${label})`,
+ severity: "gate",
+ score: (value) => (predicate(value as T) ? 1 : 0),
});
}
diff --git a/packages/eve/src/evals/index.ts b/packages/eve/src/evals/index.ts
index 3ce66391b..6f9892f02 100644
--- a/packages/eve/src/evals/index.ts
+++ b/packages/eve/src/evals/index.ts
@@ -14,6 +14,8 @@ export type { RuntimeIdentity } from "#protocol/message.js";
export type { InputRequest } from "#runtime/input/types.js";
export type {
+ EveEvalEventMatch,
+ EveEvalInputRequestMatchOptions,
EveEvalValueMatcher,
EveEvalToolCallMatchOptions,
EveEvalSkillLoadMatchOptions,
@@ -26,6 +28,8 @@ export type {
AssertionResult,
AssertionSeverity,
AutoevalsJudges,
+ EveEvalActionStatus,
+ EveEvalAssertions,
EveEvalContext,
EveEvalDerivedFacts,
EveEvalJudgeConfig,
diff --git a/packages/eve/src/evals/match.ts b/packages/eve/src/evals/match.ts
index 8ca72efd8..e4b558324 100644
--- a/packages/eve/src/evals/match.ts
+++ b/packages/eve/src/evals/match.ts
@@ -1,3 +1,6 @@
+import type { HandleMessageStreamEvent } from "#protocol/message.js";
+import type { InputRequest } from "#runtime/input/types.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
import type { EveEvalSubagentCall, EveEvalToolCall } from "#evals/types.js";
/**
@@ -10,13 +13,18 @@ import type { EveEvalSubagentCall, EveEvalToolCall } from "#evals/types.js";
* compare with `Object.is`
* - a **RegExp** tests string values directly and the JSON serialization of
* anything else
- * - a **function** receives the observed value and either returns a boolean
- * verdict, or returns a resolved expected value that is then compared like a
- * literal — e.g. `(o) => o === process.env.EVE_WEATHER_AGENT_HOST`. To assert
- * a literal boolean field, use the literal directly; boolean returns are
- * always treated as verdicts.
+ * - a **function** receives the observed value and returns a boolean verdict
*/
-export type EveEvalValueMatcher<T = unknown> = T | RegExp | ((value: T) => unknown);
+export type EveEvalValueMatcher<T = JsonValue | undefined> = EveEvalDeepMatcher<T>;
+
+type EveEvalDeepMatcher<T> =
+ | RegExp
+ | ((value: T) => boolean)
+ | (T extends readonly (infer TEntry)[]
+ ? readonly EveEvalDeepMatcher<TEntry>[]
+ : T extends object
+ ? { readonly [K in keyof T]?: EveEvalDeepMatcher<T[K]> }
+ : T);
/**
* Constraints applied to tool calls by `t.calledTool`. All provided
@@ -24,13 +32,13 @@ export type EveEvalValueMatcher<T = unknown> = T | RegExp | ((value: T) => unkno
*/
export interface EveEvalToolCallMatchOptions {
/** Partial-deep matcher over the call input (see {@link EveEvalValueMatcher}). */
- readonly input?: EveEvalValueMatcher;
+ readonly input?: EveEvalValueMatcher<JsonObject>;
/** Matcher over the call output. */
readonly output?: EveEvalValueMatcher;
- /** Required error state of matching calls. */
- readonly isError?: boolean;
+ /** Required lifecycle outcome. Defaults to `"completed"`. */
+ readonly status?: EveEvalToolCall["status"];
/** Exact number of matching calls required. Defaults to "at least one". */
- readonly times?: number;
+ readonly count?: number;
}
/**
@@ -45,11 +53,47 @@ export type EveEvalSkillLoadMatchOptions = Omit<EveEvalToolCallMatchOptions, "in
*/
export interface EveEvalSubagentCallMatchOptions {
/** Matcher over the `subagent.called` remote URL. */
- readonly remoteUrl?: EveEvalValueMatcher;
+ readonly remoteUrl?: EveEvalValueMatcher<string | undefined>;
/** Matcher over the `subagent.completed` output. */
readonly output?: EveEvalValueMatcher;
+ /** Required lifecycle outcome. Defaults to `"completed"`. */
+ readonly status?: EveEvalSubagentCall["status"];
+ /** Exact number of matching delegations required. Defaults to "at least one". */
+ readonly count?: number;
+}
+
+/** Constraints accepted by `requireInputRequest`. */
+export interface EveEvalInputRequestMatchOptions {
+ /** Matcher over the request's display hint. */
+ readonly display?: EveEvalValueMatcher<InputRequest["display"]>;
+ /** Partial-deep matcher over a tool-call action's input. */
+ readonly input?: EveEvalValueMatcher<JsonObject>;
+ /** Matcher over the complete option-id list in request order. */
+ readonly optionIds?: EveEvalValueMatcher<readonly string[]>;
+ /** Matcher over the request prompt. */
+ readonly prompt?: EveEvalValueMatcher<string>;
+ /** Required tool name for a tool-call action. */
+ readonly toolName?: string;
}
+/** One typed stream-event matcher used by scoped event assertions. */
+export type EveEvalEventMatch<
+ TType extends HandleMessageStreamEvent["type"] = HandleMessageStreamEvent["type"],
+> = TType extends HandleMessageStreamEvent["type"]
+ ? {
+ /** Stream-event type to match. */
+ readonly type: TType;
+ /** Partial-deep matcher over the event data. */
+ readonly data?: EveEvalDeepMatcher<
+ Extract<HandleMessageStreamEvent, { type: TType }> extends { data: infer TData }
+ ? TData
+ : never
+ >;
+ /** Exact number of matching events required. Defaults to "at least one". */
+ readonly count?: number;
+ }
+ : never;
+
/**
* Returns true when the observed value satisfies a matcher (literal, RegExp,
* or function — see {@link EveEvalValueMatcher}).
@@ -60,12 +104,7 @@ export function matchesValue(matcher: unknown, value: unknown): boolean {
}
if (typeof matcher === "function") {
- const outcome = (matcher as (value: unknown) => unknown)(value);
- if (typeof outcome === "boolean") return outcome;
- // A resolver returned an expected value; functions compare by identity to
- // keep resolved values from recursing forever.
- if (typeof outcome === "function") return Object.is(outcome, value);
- return matchesValue(outcome, value);
+ return (matcher as (value: unknown) => boolean)(value);
}
if (Array.isArray(matcher)) {
@@ -83,7 +122,7 @@ export function matchesValue(matcher: unknown, value: unknown): boolean {
/**
* Returns true when one derived tool call satisfies the `input`/`output`/
- * `isError` constraints (the `times` count is the caller's concern).
+ * lifecycle constraints (the `count` option is the caller's concern).
*/
export function toolCallMatches(
call: EveEvalToolCall,
@@ -93,7 +132,7 @@ export function toolCallMatches(
if (options.output !== undefined && !matchesValue(options.output, call.output)) {
return false;
}
- if (options.isError !== undefined && call.isError !== options.isError) return false;
+ if (call.status !== (options.status ?? "completed")) return false;
return true;
}
@@ -111,11 +150,46 @@ export function subagentCallMatches(
if (options.output !== undefined && !matchesValue(options.output, call.output)) {
return false;
}
+ if (call.status !== (options.status ?? "completed")) return false;
+ return true;
+}
+
+/** Returns true when one HITL request satisfies every supplied constraint. */
+export function inputRequestMatches(
+ request: InputRequest,
+ options: EveEvalInputRequestMatchOptions,
+): boolean {
+ if (options.display !== undefined && !matchesValue(options.display, request.display))
+ return false;
+ if (options.prompt !== undefined && !matchesValue(options.prompt, request.prompt)) return false;
+ if (options.optionIds !== undefined) {
+ const optionIds = (request.options ?? []).map((option) => option.id);
+ if (!matchesValue(options.optionIds, optionIds)) return false;
+ }
+ if (options.toolName !== undefined) {
+ if (request.action.kind !== "tool-call" || request.action.toolName !== options.toolName) {
+ return false;
+ }
+ }
+ if (options.input !== undefined) {
+ if (request.action.kind !== "tool-call" || !matchesValue(options.input, request.action.input)) {
+ return false;
+ }
+ }
return true;
}
+/** Returns true when one stream event satisfies a typed event matcher. */
+export function eventMatches(event: HandleMessageStreamEvent, matcher: EveEvalEventMatch): boolean {
+ return (
+ event.type === matcher.type &&
+ (matcher.data === undefined ||
+ matchesValue(matcher.data, "data" in event ? event.data : undefined))
+ );
+}
+
/**
- * Strict structural equality used by `t.outputEquals`: unlike matcher
+ * Strict structural equality used by scoped `outputEquals`: unlike matcher
* comparison, objects must carry exactly the same keys on both sides.
*/
export function deepEquals(a: unknown, b: unknown): boolean {
diff --git a/packages/eve/src/evals/runner/artifacts.test.ts b/packages/eve/src/evals/runner/artifacts.test.ts
new file mode 100644
index 000000000..470578ad6
--- /dev/null
+++ b/packages/eve/src/evals/runner/artifacts.test.ts
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createEmptyDerivedFacts } from "#evals/runner/derive-run-facts.js";
+import { writeArtifacts } from "#evals/runner/artifacts.js";
+import type { EveEvalResult, EveEvalRunSummary } from "#evals/types.js";
+
+const fsMocks = vi.hoisted(() => ({
+ mkdir: vi.fn(),
+ writeFile: vi.fn(),
+}));
+
+vi.mock("node:fs/promises", () => fsMocks);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("eval artifacts", () => {
+ it("persists skipped counts and reasons in every JSON artifact", async () => {
+ await writeArtifacts("/tmp/eve-evals", skippedSummary());
+
+ const summary = writtenJson("/tmp/eve-evals/summary.json");
+ expect(summary).toMatchObject({
+ skipped: 1,
+ evals: [{ id: "runtime/skipped", skipReason: "dev routes unavailable" }],
+ });
+
+ const result = writtenJson("/tmp/eve-evals/results.jsonl");
+ expect(result).toMatchObject({
+ id: "runtime/skipped",
+ skipReason: "dev routes unavailable",
+ });
+
+ const detail = writtenJson("/tmp/eve-evals/evals/runtime/skipped.json");
+ expect(detail).toMatchObject({
+ id: "runtime/skipped",
+ skipReason: "dev routes unavailable",
+ });
+ });
+});
+
+function writtenJson(path: string): Record<string, unknown> {
+ const call = fsMocks.writeFile.mock.calls.find(([writtenPath]) => writtenPath === path);
+ expect(call, `expected ${path} to be written`).toBeDefined();
+ return JSON.parse(call?.[1] as string) as Record<string, unknown>;
+}
+
+function skippedSummary(): EveEvalRunSummary {
+ const result: EveEvalResult = {
+ id: "runtime/skipped",
+ assertions: [],
+ result: {
+ derived: createEmptyDerivedFacts(),
+ events: [],
+ finalMessage: null,
+ output: null,
+ status: "completed",
+ },
+ verdict: "skipped",
+ skipReason: "dev routes unavailable",
+ startedAt: "2026-01-01T00:00:00.000Z",
+ completedAt: "2026-01-01T00:00:01.000Z",
+ };
+ return {
+ target: { capabilities: { devRoutes: true }, kind: "local", url: "http://localhost:3000" },
+ results: [result],
+ startedAt: result.startedAt,
+ completedAt: result.completedAt,
+ passed: 0,
+ failed: 0,
+ scored: 0,
+ skipped: 1,
+ errored: 0,
+ };
+}
diff --git a/packages/eve/src/evals/runner/artifacts.ts b/packages/eve/src/evals/runner/artifacts.ts
index 8da3c304b..4e0c2b11e 100644
--- a/packages/eve/src/evals/runner/artifacts.ts
+++ b/packages/eve/src/evals/runner/artifacts.ts
@@ -57,6 +57,7 @@ function buildSummaryArtifact(summary: EveEvalRunSummary): Record<string, unknow
passed: summary.passed,
failed: summary.failed,
scored: summary.scored,
+ skipped: summary.skipped,
errored: summary.errored,
totalEvals: summary.results.length,
evals: summary.results.map((result) => ({
@@ -70,6 +71,7 @@ function buildSummaryArtifact(summary: EveEvalRunSummary): Record<string, unknow
passed: a.passed,
})),
error: result.error,
+ skipReason: result.skipReason,
})),
};
}
@@ -82,6 +84,7 @@ function buildResultLine(result: EveEvalResult): Record<string, unknown> {
output: result.result.output,
assertions: result.assertions,
error: result.error,
+ skipReason: result.skipReason,
};
}
@@ -100,6 +103,7 @@ function buildEvalArtifact(result: EveEvalResult): Record<string, unknown> {
verdict: result.verdict,
assertions: result.assertions,
error: result.error,
+ skipReason: result.skipReason,
};
}
diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.ts
index d9c0de0a6..56a082073 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts
@@ -31,7 +31,7 @@ function actionResult(input: {
callId: string;
toolName: string;
output?: unknown;
- status?: "completed" | "failed";
+ status?: "completed" | "failed" | "rejected";
isError?: boolean;
}): HandleMessageStreamEvent {
return {
@@ -46,7 +46,30 @@ function actionResult(input: {
},
sequence: 1,
stepIndex: 0,
- status: input.status ?? "completed",
+ status: input.status ?? (input.isError === true ? "failed" : "completed"),
+ turnId: "t1",
+ },
+ };
+}
+
+function subagentResult(input: {
+ callId: string;
+ subagentName: string;
+ output: unknown;
+ status: "completed" | "failed" | "rejected";
+}): HandleMessageStreamEvent {
+ return {
+ type: "action.result",
+ data: {
+ result: {
+ callId: input.callId,
+ kind: "subagent-result",
+ output: input.output as never,
+ subagentName: input.subagentName,
+ },
+ sequence: 1,
+ stepIndex: 0,
+ status: input.status,
turnId: "t1",
},
};
@@ -102,7 +125,7 @@ describe("deriveRunFacts", () => {
name: "get_weather",
input: { city: "Brooklyn" },
output: { tempF: 72 },
- isError: false,
+ status: "completed",
turnIndex: 0,
sessionId: "s1",
},
@@ -110,7 +133,7 @@ describe("deriveRunFacts", () => {
name: "bash",
input: { command: "pwd" },
output: "command denied",
- isError: true,
+ status: "failed",
turnIndex: 0,
sessionId: "s1",
},
@@ -118,14 +141,102 @@ describe("deriveRunFacts", () => {
expect(facts.toolCallCount).toBe(2);
});
- it("marks tool calls failed when the result carries isError", () => {
+ it("uses the normalized failed lifecycle status for error results", () => {
const events: HandleMessageStreamEvent[] = [
actionsRequested([{ callId: "c1", toolName: "bash" }]),
actionResult({ callId: "c1", toolName: "bash", isError: true }),
];
const facts = deriveRunFacts(events);
- expect(facts.toolCalls[0]?.isError).toBe(true);
+ expect(facts.toolCalls[0]?.status).toBe("failed");
+ });
+
+ it("distinguishes pending, completed, failed, and rejected tool calls", () => {
+ const events: HandleMessageStreamEvent[] = [
+ actionsRequested([
+ { callId: "pending", toolName: "pending" },
+ { callId: "completed", toolName: "completed" },
+ { callId: "failed", toolName: "failed" },
+ { callId: "rejected", toolName: "rejected" },
+ ]),
+ actionResult({ callId: "completed", toolName: "completed" }),
+ actionResult({ callId: "failed", toolName: "failed", status: "failed" }),
+ actionResult({ callId: "rejected", toolName: "rejected", status: "rejected" }),
+ ];
+
+ expect(deriveRunFacts(events).toolCalls.map((call) => call.status)).toEqual([
+ "pending",
+ "completed",
+ "failed",
+ "rejected",
+ ]);
+ });
+
+ it("derives pending tool calls from HITL input requests", () => {
+ const facts = deriveRunFacts([turnStarted("t1", 0), inputRequested(["approval"])]);
+
+ expect(facts.toolCalls).toEqual([
+ {
+ name: "bash",
+ input: {},
+ output: undefined,
+ status: "pending",
+ turnIndex: 0,
+ sessionId: undefined,
+ },
+ ]);
+ });
+
+ it("pairs HITL tool calls with resumed results by call id", () => {
+ const events: HandleMessageStreamEvent[] = [
+ turnStarted("t1", 0),
+ inputRequested(["approval"]),
+ turnStarted("t2", 1),
+ actionResult({
+ callId: "approval-call",
+ toolName: "bash",
+ output: "approved",
+ }),
+ ];
+
+ expect(deriveRunFacts(events).toolCalls).toEqual([
+ {
+ name: "bash",
+ input: {},
+ output: "approved",
+ status: "completed",
+ turnIndex: 0,
+ sessionId: undefined,
+ },
+ ]);
+ });
+
+ it("derives resolved tool calls from result-only turn events", () => {
+ const facts = deriveRunFacts([
+ turnStarted("t2", 1),
+ actionResult({ callId: "approval-call", toolName: "bash", status: "rejected" }),
+ ]);
+
+ expect(facts.toolCalls).toEqual([
+ {
+ name: "bash",
+ input: {},
+ output: null,
+ status: "rejected",
+ turnIndex: 0,
+ sessionId: undefined,
+ },
+ ]);
+ });
+
+ it("deduplicates tool calls surfaced by request and HITL events", () => {
+ const events: HandleMessageStreamEvent[] = [
+ turnStarted("t1", 0),
+ actionsRequested([{ callId: "approval-call", toolName: "bash" }]),
+ inputRequested(["approval"]),
+ ];
+
+ expect(deriveRunFacts(events).toolCalls).toHaveLength(1);
});
it("stamps the turn index from turn.started boundaries", () => {
@@ -211,7 +322,7 @@ describe("deriveRunFacts", () => {
name: "weather",
remoteUrl: "http://127.0.0.1:4001",
output: "Sunny, 72F",
- isError: false,
+ status: "completed",
turnIndex: 0,
sessionId: "s0",
},
@@ -219,6 +330,28 @@ describe("deriveRunFacts", () => {
expect(facts.subagentCallCount).toBe(1);
});
+ it("derives failed subagent calls from result-only events", () => {
+ const facts = deriveRunFacts([
+ turnStarted("t1", 0),
+ subagentResult({
+ callId: "c1",
+ subagentName: "weather",
+ output: { code: "REMOTE_AGENT_START_FAILED" },
+ status: "failed",
+ }),
+ ]);
+
+ expect(facts.subagentCalls).toEqual([
+ {
+ name: "weather",
+ output: { code: "REMOTE_AGENT_START_FAILED" },
+ status: "failed",
+ turnIndex: 0,
+ sessionId: undefined,
+ },
+ ]);
+ });
+
it("extracts inline subagent calls from subagent.started events", () => {
const events: HandleMessageStreamEvent[] = [
{
diff --git a/packages/eve/src/evals/runner/derive-run-facts.ts b/packages/eve/src/evals/runner/derive-run-facts.ts
index 031913eac..b6660314f 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.ts
@@ -1,13 +1,13 @@
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import type { InputRequest } from "#runtime/input/types.js";
-import type { JsonObject } from "#shared/json.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
import type { EveEvalDerivedFacts, EveEvalSubagentCall, EveEvalToolCall } from "#evals/types.js";
interface MutableToolCall {
name: string;
input: JsonObject;
- output: unknown;
- isError: boolean;
+ output: JsonValue | undefined;
+ status: EveEvalToolCall["status"];
turnIndex: number;
sessionId?: string;
}
@@ -15,8 +15,8 @@ interface MutableToolCall {
interface MutableSubagentCall {
name: string;
remoteUrl?: string;
- output?: unknown;
- isError: boolean;
+ output?: JsonValue;
+ status: EveEvalSubagentCall["status"];
turnIndex: number;
sessionId?: string;
}
@@ -63,13 +63,30 @@ export function deriveRunFacts(
let reasoningBlockCount = 0;
let failureCode: string | undefined;
+ const ensureToolCall = (callId: string, name: string, input: JsonObject): MutableToolCall => {
+ const existing = toolCallsByCallId.get(callId);
+ if (existing !== undefined) return existing;
+
+ const call: MutableToolCall = {
+ name,
+ input,
+ output: undefined,
+ status: "pending",
+ turnIndex: Math.max(turnIndex, 0),
+ sessionId,
+ };
+ toolCalls.push(call);
+ toolCallsByCallId.set(callId, call);
+ return call;
+ };
+
const ensureSubagentCall = (callId: string, name: string): MutableSubagentCall => {
const existing = subagentCallsByCallId.get(callId);
if (existing !== undefined) return existing;
const call: MutableSubagentCall = {
name,
- isError: false,
+ status: "pending",
turnIndex: Math.max(turnIndex, 0),
sessionId,
};
@@ -88,36 +105,21 @@ export function deriveRunFacts(
case "actions.requested": {
for (const action of event.data.actions) {
if (action.kind !== "tool-call") continue;
- const call: MutableToolCall = {
- name: action.toolName,
- input: action.input,
- output: undefined,
- isError: false,
- turnIndex: Math.max(turnIndex, 0),
- sessionId,
- };
- toolCalls.push(call);
- toolCallsByCallId.set(action.callId, call);
+ ensureToolCall(action.callId, action.toolName, action.input);
}
break;
}
case "action.result": {
const { result, status } = event.data;
- const failed = status === "failed" || result.isError === true;
-
if (result.kind === "tool-result") {
- const call = toolCallsByCallId.get(result.callId);
- if (call !== undefined) {
- call.output = result.output;
- call.isError = failed;
- }
+ const call = ensureToolCall(result.callId, result.toolName, {});
+ call.output = result.output;
+ call.status = status;
} else if (result.kind === "subagent-result") {
- const call = subagentCallsByCallId.get(result.callId);
- if (call !== undefined) {
- call.output = call.output ?? result.output;
- call.isError = failed;
- }
+ const call = ensureSubagentCall(result.callId, result.subagentName);
+ call.output = call.output ?? result.output;
+ call.status = status;
}
break;
}
@@ -138,11 +140,15 @@ export function deriveRunFacts(
case "subagent.completed": {
const call = ensureSubagentCall(event.data.callId, event.data.subagentName);
call.output = event.data.output;
+ if (call.status === "pending") call.status = "completed";
break;
}
case "input.requested": {
inputRequests.push(...event.data.requests);
+ for (const request of event.data.requests) {
+ ensureToolCall(request.action.callId, request.action.toolName, request.action.input);
+ }
break;
}
diff --git a/packages/eve/src/evals/runner/execute-eval.ts b/packages/eve/src/evals/runner/execute-eval.ts
index 12f18a519..b2216365e 100644
--- a/packages/eve/src/evals/runner/execute-eval.ts
+++ b/packages/eve/src/evals/runner/execute-eval.ts
@@ -40,6 +40,7 @@ export async function executeEval(options: ExecuteEvalOptions): Promise<EveEvalR
let result: EveEvalTaskResult;
let assertions: readonly AssertionResult[] = [];
let error: string | undefined;
+ let skipReason: string | undefined;
try {
const outcome = await executeTask({
@@ -52,6 +53,7 @@ export async function executeEval(options: ExecuteEvalOptions): Promise<EveEvalR
result = outcome.result;
assertions = outcome.assertions;
error = outcome.error;
+ skipReason = outcome.skipReason;
} catch (err) {
error = toErrorMessage(err);
result = {
@@ -63,7 +65,7 @@ export async function executeEval(options: ExecuteEvalOptions): Promise<EveEvalR
};
}
- const verdict = computeEvalVerdict({ error, assertions });
+ const verdict = computeEvalVerdict({ error, assertions, skipReason });
return {
id: evaluation.id,
@@ -71,6 +73,7 @@ export async function executeEval(options: ExecuteEvalOptions): Promise<EveEvalR
assertions,
verdict,
error,
+ skipReason,
startedAt,
completedAt: new Date().toISOString(),
};
diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.ts
index 78a8cedf2..50b6b44b7 100644
--- a/packages/eve/src/evals/runner/execute-task.test.ts
+++ b/packages/eve/src/evals/runner/execute-task.test.ts
@@ -5,6 +5,8 @@ import type { HandleMessageStreamEvent } from "#protocol/message.js";
import { executeTask } from "#evals/runner/execute-task.js";
import type { EveEval, EveEvalContext } from "#evals/types.js";
import { createEvalTargetHandle } from "#evals/target.js";
+import { satisfies } from "#evals/expect/index.js";
+import { z } from "zod";
const target = createEvalTargetHandle({
capabilities: { devRoutes: true },
@@ -61,6 +63,7 @@ describe("executeTask", () => {
sessionId: "session_1",
events: [
turnStarted("turn_2"),
+ actionResult("turn_2", "bash", "approved"),
messageCompleted("approved", "turn_2"),
turnCompleted("turn_2"),
sessionCompleted(),
@@ -73,10 +76,19 @@ describe("executeTask", () => {
client: new Client({ host: target.url }),
target,
evaluation: createTestEval(async (t) => {
- await t.send("run pwd");
- const [request] = t.expectInputRequests({ toolName: "bash" });
- expect(request?.requestId).toBe("approval_1");
- await t.respondAll("approve");
+ const parked = await t.send("run pwd");
+ parked.calledTool("bash", { status: "pending", count: 1 });
+ const request = t.requireInputRequest({
+ display: "confirmation",
+ input: { command: "pwd" },
+ optionIds: ["approve", "deny"],
+ prompt: /Approve/,
+ toolName: "bash",
+ });
+ expect(request.requestId).toBe("approval_1");
+ const approved = await t.respondAll("approve");
+ approved.calledTool("bash", { status: "completed", count: 1 });
+ t.calledTool("bash", { status: "completed", count: 1 });
}, "approve"),
});
@@ -160,6 +172,161 @@ describe("executeTask", () => {
expect(result.derived.toolCalls.map((call) => call.sessionId)).toEqual(["secondary"]);
});
+ it("records assertions against individual turns without leaking other turns", async () => {
+ const server = createScriptedServer([
+ {
+ sessionId: "session_1",
+ events: [
+ turnStarted("turn_1"),
+ actionsRequested("turn_1", "alpha"),
+ turnCompleted("turn_1"),
+ sessionWaiting(),
+ ],
+ },
+ {
+ sessionId: "session_1",
+ events: [
+ turnStarted("turn_2"),
+ messageCompleted("done", "turn_2"),
+ turnCompleted("turn_2"),
+ sessionCompleted(),
+ ],
+ },
+ ]);
+ vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ const first = await t.send("first");
+ const second = await t.send("second");
+ expect(first.requireToolCall("alpha", { status: "pending" }).name).toBe("alpha");
+ first.calledTool("alpha", { status: "pending", count: 1 });
+ second.notCalledTool("alpha");
+ t.calledTool("alpha", { status: "pending", count: 1 });
+ }, "turn-scopes"),
+ });
+
+ expect(outcome.assertions).toHaveLength(4);
+ expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);
+ });
+
+ it("snapshots session assertions when they are recorded", async () => {
+ const server = createScriptedServer([
+ {
+ sessionId: "session_1",
+ events: [
+ turnStarted("turn_1"),
+ actionsRequested("turn_1", "alpha", "call_1"),
+ turnCompleted("turn_1"),
+ sessionWaiting(),
+ ],
+ },
+ {
+ sessionId: "session_1",
+ events: [
+ turnStarted("turn_2"),
+ actionsRequested("turn_2", "alpha", "call_2"),
+ turnCompleted("turn_2"),
+ sessionWaiting(),
+ ],
+ },
+ ]);
+ vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ const session = t.newSession();
+ await session.send("first");
+ session.calledTool("alpha", { status: "pending", count: 1 });
+ session.event("turn.started", { count: 1 });
+ await session.send("second");
+ }, "session-snapshot"),
+ });
+
+ expect(outcome.assertions).toHaveLength(2);
+ expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);
+ });
+
+ it("records a required assertion and stops dependent control flow", async () => {
+ let continued = false;
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ await t.require(
+ 1,
+ satisfies<number>((value) => value > 2, "greater than two"),
+ );
+ continued = true;
+ }, "require"),
+ });
+
+ expect(continued).toBe(false);
+ expect(outcome.error).toBeUndefined();
+ expect(outcome.assertions[0]).toMatchObject({ passed: false, severity: "gate" });
+ });
+
+ it("records a failed required tool lookup without an execution error", async () => {
+ const server = createScriptedServer([
+ {
+ sessionId: "session_1",
+ events: [
+ turnStarted("turn_1"),
+ messageCompleted("done", "turn_1"),
+ turnCompleted("turn_1"),
+ sessionCompleted(),
+ ],
+ },
+ ]);
+ vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ const turn = await t.send("run");
+ turn.requireToolCall("missing");
+ }, "required-tool"),
+ });
+
+ expect(outcome.error).toBeUndefined();
+ expect(outcome.assertions).toEqual([
+ expect.objectContaining({ name: "requireToolCall", passed: false, severity: "gate" }),
+ ]);
+ });
+
+ it("captures an explicit skip without an execution error", async () => {
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval((t) => t.skip("dev routes unavailable"), "skip"),
+ });
+
+ expect(outcome.error).toBeUndefined();
+ expect(outcome.skipReason).toBe("dev routes unavailable");
+ });
+
+ it("rejects a skip after an assertion has already been recorded", async () => {
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval((t) => {
+ t.check(
+ 1,
+ satisfies((value: number) => value === 1, "equals one"),
+ );
+ t.skip("too late");
+ }, "late-skip"),
+ });
+
+ expect(outcome.skipReason).toBeUndefined();
+ expect(outcome.error).toContain("skip() must be called before");
+ });
+
it("attaches to a target-created session and captures its stream", async () => {
const server = createScriptedServer([], {
streams: [
@@ -176,17 +343,57 @@ describe("executeTask", () => {
});
vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
- const { result } = await executeTask({
+ const outcome = await executeTask({
client: new Client({ host: target.url }),
target,
evaluation: createTestEval(async (t) => {
- await t.target.attachSession("channel-session");
+ const session = await t.target.attachSession("channel-session");
+ session.succeeded();
+ session.messageIncludes("channel done");
}, "attach"),
});
+ const { result } = outcome;
expect(result.output).toBe("channel done");
expect(result.sessions?.map((session) => session.sessionId)).toEqual(["channel-session"]);
expect(result.events.map((event) => event.type)).toContain("message.completed");
+ expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);
+ });
+
+ it("uses structured turn data as the scoped and aggregate output", async () => {
+ const server = createScriptedServer([
+ {
+ sessionId: "structured",
+ events: [
+ turnStarted("turn_1"),
+ {
+ type: "result.completed",
+ data: {
+ result: { count: 2, title: "Done" },
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn_1",
+ },
+ },
+ turnCompleted("turn_1"),
+ sessionCompleted(),
+ ],
+ },
+ ]);
+ vi.spyOn(globalThis, "fetch").mockImplementation(server.fetch);
+
+ const outcome = await executeTask({
+ client: new Client({ host: target.url }),
+ target,
+ evaluation: createTestEval(async (t) => {
+ const turn = await t.send({ message: "structured", outputSchema: { type: "object" } });
+ turn.outputMatches(z.object({ count: z.number(), title: z.string() }));
+ turn.outputEquals({ count: 2, title: "Done" });
+ }, "structured-output"),
+ });
+
+ expect(outcome.result.output).toEqual({ count: 2, title: "Done" });
+ expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);
});
it("captures a schedule-dispatch capability failure as the task error", async () => {
@@ -334,10 +541,27 @@ function inputRequested(
};
}
-function actionsRequested(turnId: string, toolName: string): HandleMessageStreamEvent {
+function actionResult(turnId: string, toolName: string, output: string): HandleMessageStreamEvent {
+ return {
+ data: {
+ result: { callId: "call_1", kind: "tool-result", output, toolName },
+ sequence: 1,
+ status: "completed",
+ stepIndex: 0,
+ turnId,
+ },
+ type: "action.result",
+ };
+}
+
+function actionsRequested(
+ turnId: string,
+ toolName: string,
+ callId = "call_weather",
+): HandleMessageStreamEvent {
return {
data: {
- actions: [{ callId: "call_weather", input: { city: "Lisbon" }, kind: "tool-call", toolName }],
+ actions: [{ callId, input: { city: "Lisbon" }, kind: "tool-call", toolName }],
sequence: 2,
stepIndex: 0,
turnId,
diff --git a/packages/eve/src/evals/runner/execute-task.ts b/packages/eve/src/evals/runner/execute-task.ts
index 50c4e2233..3c93a823e 100644
--- a/packages/eve/src/evals/runner/execute-task.ts
+++ b/packages/eve/src/evals/runner/execute-task.ts
@@ -14,6 +14,8 @@ import { createEmptyDerivedFacts } from "#evals/runner/derive-run-facts.js";
import { EvalSessionManager } from "#evals/session.js";
import { createEvalContext } from "#evals/context.js";
import { scopeEvalTargetHandle } from "#evals/target.js";
+import { AssertionCollector } from "#evals/assertions/collector.js";
+import { EvalRequirementFailed, EvalSkipped } from "#evals/control-flow.js";
/**
* Options for executing one eval's task.
@@ -36,6 +38,7 @@ export interface ExecuteTaskResult {
readonly result: EveEvalTaskResult;
readonly assertions: readonly AssertionResult[];
readonly error?: string;
+ readonly skipReason?: string;
}
/**
@@ -46,13 +49,15 @@ export interface ExecuteTaskResult {
export async function executeTask(options: ExecuteTaskOptions): Promise<ExecuteTaskResult> {
const { client, evaluation, target, timeoutMs } = options;
const signal = timeoutMs !== undefined ? AbortSignal.timeout(timeoutMs) : neverAbortSignal();
- const manager = new EvalSessionManager({ client, signal });
+ const collector = new AssertionCollector();
+ const manager = new EvalSessionManager({ client, collector, signal });
const targetForRun = scopeEvalTargetHandle(target, {
sessions: manager,
});
const logs: string[] = [];
- const { context, collector } = createEvalContext({
+ const { context } = createEvalContext({
+ collector,
manager,
target: targetForRun,
signal,
@@ -64,10 +69,15 @@ export async function executeTask(options: ExecuteTaskOptions): Promise<ExecuteT
});
let error: string | undefined;
+ let skipReason: string | undefined;
try {
await evaluation.test(context);
} catch (err) {
- error = toErrorMessage(err);
+ if (err instanceof EvalSkipped) {
+ skipReason = err.reason;
+ } else if (!(err instanceof EvalRequirementFailed)) {
+ error = toErrorMessage(err);
+ }
}
const result = buildTaskResult({
@@ -77,7 +87,7 @@ export async function executeTask(options: ExecuteTaskOptions): Promise<ExecuteT
});
const assertions = await collector.finalize(result);
- return { result, assertions, error };
+ return { result, assertions, error, skipReason };
}
function buildTaskResult(input: {
@@ -88,7 +98,7 @@ function buildTaskResult(input: {
const events = input.sessions.flatMap((session) => session.events);
const finalMessage = input.turn?.message ?? null;
return {
- output: finalMessage,
+ output: input.turn?.data === undefined ? finalMessage : input.turn.data,
finalMessage,
sessionId: selectPrimarySessionId(input.sessions),
status: input.turn?.status ?? "completed",
diff --git a/packages/eve/src/evals/runner/reporters/braintrust.test.ts b/packages/eve/src/evals/runner/reporters/braintrust.test.ts
index 91d033fe3..9dbc1cc64 100644
--- a/packages/eve/src/evals/runner/reporters/braintrust.test.ts
+++ b/packages/eve/src/evals/runner/reporters/braintrust.test.ts
@@ -36,7 +36,7 @@ function makeEvalResult(overrides: Partial<EveEvalResult> = {}): EveEvalResult {
name: "search",
input: { query: "test" },
output: null,
- isError: false,
+ status: "completed",
turnIndex: 0,
sessionId: "session-123",
},
@@ -52,7 +52,7 @@ function makeEvalResult(overrides: Partial<EveEvalResult> = {}): EveEvalResult {
sessionId: "session-123",
},
assertions: [
- { name: "completed", score: 1, severity: "gate", passed: true },
+ { name: "succeeded", score: 1, severity: "gate", passed: true },
{ name: "similarity", score: 1, severity: "soft", threshold: 0.6, passed: true },
],
verdict: "passed",
@@ -94,6 +94,7 @@ describe("Braintrust", () => {
passed: 0,
failed: 0,
scored: 0,
+ skipped: 0,
errored: 0,
});
});
diff --git a/packages/eve/src/evals/runner/reporters/braintrust.ts b/packages/eve/src/evals/runner/reporters/braintrust.ts
index 10c587d8f..7d86122e8 100644
--- a/packages/eve/src/evals/runner/reporters/braintrust.ts
+++ b/packages/eve/src/evals/runner/reporters/braintrust.ts
@@ -147,6 +147,7 @@ class BraintrustReporter implements EvalReporter {
eveSessionId: result.result.sessionId,
eveStatus: result.result.status,
eveVerdict: result.verdict,
+ eveSkipReason: result.skipReason,
eveToolCalls: result.result.derived.toolCalls.map((call) => call.name),
eveSubagentCalls: result.result.derived.subagentCalls.map((call) => call.name),
eveParked: result.result.derived.parked,
diff --git a/packages/eve/src/evals/runner/reporters/console.test.ts b/packages/eve/src/evals/runner/reporters/console.test.ts
new file mode 100644
index 000000000..c4b5e2572
--- /dev/null
+++ b/packages/eve/src/evals/runner/reporters/console.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+
+import { createEmptyDerivedFacts } from "#evals/runner/derive-run-facts.js";
+import { ConsoleReporter } from "#evals/runner/reporters/console.js";
+import type { EveEvalResult, EveEvalRunSummary } from "#evals/types.js";
+
+describe("ConsoleReporter", () => {
+ it("reports skipped evals and their reason", () => {
+ const lines: string[] = [];
+ const reporter = new ConsoleReporter({ color: false, log: (line) => lines.push(line) });
+ const result = skippedResult();
+
+ reporter.onEvalComplete(result);
+ reporter.onRunComplete(summary(result));
+
+ expect(lines.join("\n")).toContain("dev routes unavailable");
+ expect(lines.join("\n")).toContain("1 skipped");
+ });
+});
+
+function skippedResult(): EveEvalResult {
+ return {
+ assertions: [],
+ completedAt: "2026-01-01T00:00:01.000Z",
+ id: "schedule",
+ result: {
+ derived: createEmptyDerivedFacts(),
+ events: [],
+ finalMessage: null,
+ output: null,
+ status: "completed",
+ },
+ skipReason: "dev routes unavailable",
+ startedAt: "2026-01-01T00:00:00.000Z",
+ verdict: "skipped",
+ };
+}
+
+function summary(result: EveEvalResult): EveEvalRunSummary {
+ return {
+ completedAt: result.completedAt,
+ errored: 0,
+ failed: 0,
+ passed: 0,
+ results: [result],
+ scored: 0,
+ skipped: 1,
+ startedAt: result.startedAt,
+ target: { capabilities: { devRoutes: false }, kind: "remote", url: "https://eve.test" },
+ };
+}
diff --git a/packages/eve/src/evals/runner/reporters/console.ts b/packages/eve/src/evals/runner/reporters/console.ts
index 5669da848..cccbf873f 100644
--- a/packages/eve/src/evals/runner/reporters/console.ts
+++ b/packages/eve/src/evals/runner/reporters/console.ts
@@ -33,7 +33,7 @@ export class ConsoleReporter implements EvalReporter {
}
onEvalComplete(result: EveEvalResult): void {
- const { assertions, verdict, error } = result;
+ const { assertions, verdict, error, skipReason } = result;
const gates = assertions.filter((assertion) => assertion.severity === "gate");
const softs = assertions.filter((assertion) => assertion.severity === "soft");
@@ -60,12 +60,15 @@ export class ConsoleReporter implements EvalReporter {
if (error) {
this.#log(` ${this.#colors.red(error)}`);
}
+ if (skipReason) {
+ this.#log(` ${this.#colors.dim(skipReason)}`);
+ }
}
onRunComplete(summary: EveEvalRunSummary): void {
this.#log("");
- const { passed, failed, scored, results } = summary;
+ const { passed, failed, scored, skipped, results } = summary;
const total = results.length;
const parts: string[] = [];
@@ -78,6 +81,9 @@ export class ConsoleReporter implements EvalReporter {
if (scored > 0) {
parts.push(this.#colors.yellow(`${scored} scored`));
}
+ if (skipped > 0) {
+ parts.push(this.#colors.dim(`${skipped} skipped`));
+ }
if (parts.length === 0) {
parts.push(this.#colors.dim("0 evals"));
}
@@ -117,6 +123,8 @@ export class ConsoleReporter implements EvalReporter {
return this.#colors.red("✗");
case "scored":
return this.#colors.yellow("○");
+ case "skipped":
+ return this.#colors.dim("–");
}
}
diff --git a/packages/eve/src/evals/runner/reporters/junit.test.ts b/packages/eve/src/evals/runner/reporters/junit.test.ts
index ee760c5e0..d834e7f15 100644
--- a/packages/eve/src/evals/runner/reporters/junit.test.ts
+++ b/packages/eve/src/evals/runner/reporters/junit.test.ts
@@ -37,6 +37,28 @@ describe("JUnit", () => {
const [, xml] = fsMocks.writeFile.mock.calls[0]!;
expect(xml).toContain('<testsuite name="eve evals" tests="2" failures="1" skipped="0"');
});
+
+ it("renders skipped evals as skipped test cases", async () => {
+ const reporter = JUnit({ filePath: "/tmp/eve/junit.xml" });
+ const summary = makeSummary();
+ await reporter.onRunComplete({
+ ...summary,
+ failed: 0,
+ passed: 0,
+ results: [
+ makeEvalResult({
+ id: "runtime/skips",
+ skipReason: "dev routes unavailable",
+ verdict: "skipped",
+ }),
+ ],
+ skipped: 1,
+ });
+
+ const [, xml] = fsMocks.writeFile.mock.calls[0]!;
+ expect(xml).toContain('tests="1" failures="0" skipped="1"');
+ expect(xml).toContain('<skipped message="dev routes unavailable"/>');
+ });
});
function makeSummary(): EveEvalRunSummary {
@@ -62,6 +84,7 @@ function makeSummary(): EveEvalRunSummary {
failed: 1,
passed: 1,
scored: 0,
+ skipped: 0,
startedAt: "2026-01-01T00:00:00.000Z",
target: makeTarget(),
};
diff --git a/packages/eve/src/evals/runner/reporters/junit.ts b/packages/eve/src/evals/runner/reporters/junit.ts
index 3c0f2be73..d84e7c8aa 100644
--- a/packages/eve/src/evals/runner/reporters/junit.ts
+++ b/packages/eve/src/evals/runner/reporters/junit.ts
@@ -45,7 +45,7 @@ function renderJUnit(summary: EveEvalRunSummary, input: { readonly suiteName?: s
return [
'<?xml version="1.0" encoding="UTF-8"?>',
- `<testsuite name="${escapeXml(input.suiteName ?? "eve evals")}" tests="${summary.results.length}" failures="${failures}" skipped="0" time="${formatSeconds(durationSeconds(summary))}">`,
+ `<testsuite name="${escapeXml(input.suiteName ?? "eve evals")}" tests="${summary.results.length}" failures="${failures}" skipped="${summary.skipped}" time="${formatSeconds(durationSeconds(summary))}">`,
...cases,
"</testsuite>",
"",
@@ -58,6 +58,13 @@ function renderTestCase(result: EveEvalResult): string {
if (result.verdict === "passed") {
return ` <testcase ${attrs}/>`;
}
+ if (result.verdict === "skipped") {
+ return [
+ ` <testcase ${attrs}>`,
+ ` <skipped message="${escapeXml(result.skipReason ?? "skipped")}"/>`,
+ " </testcase>",
+ ].join("\n");
+ }
const message = failureMessage(result);
return [
diff --git a/packages/eve/src/evals/runner/run-evals.ts b/packages/eve/src/evals/runner/run-evals.ts
index e9e46ddde..522a32fee 100644
--- a/packages/eve/src/evals/runner/run-evals.ts
+++ b/packages/eve/src/evals/runner/run-evals.ts
@@ -212,6 +212,7 @@ function buildSummary(
passed: countVerdicts(results, "passed"),
failed: countVerdicts(results, "failed"),
scored: countVerdicts(results, "scored"),
+ skipped: countVerdicts(results, "skipped"),
errored: results.filter((r) => r.error !== undefined).length,
};
}
@@ -229,6 +230,7 @@ function scopeSummary(summary: EveEvalRunSummary, evalIds: ReadonlySet<string>):
passed: countVerdicts(results, "passed"),
failed: countVerdicts(results, "failed"),
scored: countVerdicts(results, "scored"),
+ skipped: countVerdicts(results, "skipped"),
errored: results.filter((r) => r.error !== undefined).length,
};
}
diff --git a/packages/eve/src/evals/runner/verdict.test.ts b/packages/eve/src/evals/runner/verdict.test.ts
index c92f546c6..e49128b27 100644
--- a/packages/eve/src/evals/runner/verdict.test.ts
+++ b/packages/eve/src/evals/runner/verdict.test.ts
@@ -63,4 +63,23 @@ describe("computeEvalVerdict", () => {
}),
).toBe("passed");
});
+
+ it("returns skipped when an eval intentionally skips without another failure", () => {
+ expect(
+ computeEvalVerdict({
+ assertions: [],
+ skipReason: "unsupported target",
+ }),
+ ).toBe("skipped");
+ });
+
+ it("never lets an explicit skip mask errors or failed gates", () => {
+ expect(
+ computeEvalVerdict({
+ assertions: [assertion({ severity: "gate", score: 0, passed: false })],
+ error: "ignored",
+ skipReason: "unsupported target",
+ }),
+ ).toBe("failed");
+ });
});
diff --git a/packages/eve/src/evals/runner/verdict.ts b/packages/eve/src/evals/runner/verdict.ts
index 3468378e0..27ed56539 100644
--- a/packages/eve/src/evals/runner/verdict.ts
+++ b/packages/eve/src/evals/runner/verdict.ts
@@ -11,6 +11,7 @@ import type { AssertionResult, EveEvalVerdict } from "#evals/types.js";
export function computeEvalVerdict(input: {
readonly error?: string;
readonly assertions: readonly AssertionResult[];
+ readonly skipReason?: string;
}): EveEvalVerdict {
if (input.error !== undefined) return "failed";
@@ -21,5 +22,6 @@ export function computeEvalVerdict(input: {
demoted = true;
}
+ if (input.skipReason !== undefined) return "skipped";
return demoted ? "scored" : "passed";
}
diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.ts
index 6d418f7d2..6e78178b2 100644
--- a/packages/eve/src/evals/session.ts
+++ b/packages/eve/src/evals/session.ts
@@ -15,12 +15,22 @@ import {
import { extractCompletedResult } from "#client/output-schema.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
import { deriveRunFacts } from "#evals/runner/derive-run-facts.js";
+import { AssertionCollector } from "#evals/assertions/collector.js";
+import { createOutputAssertions, createScopedAssertions } from "#evals/assertions/scoped.js";
+import { EvalRequirementFailed } from "#evals/control-flow.js";
+import { inputRequestMatches, toolCallMatches } from "#evals/match.js";
import type {
+ EveEvalAssertions,
+ EveEvalDerivedFacts,
+ EveEvalOutputAssertions,
EveEvalSession,
EveEvalSessionResult,
EveEvalToolCall,
EveEvalTurn,
} from "#evals/types.js";
+import type { EveEvalInputRequestMatchOptions, EveEvalToolCallMatchOptions } from "#evals/match.js";
+
+/* oxlint-disable typescript/no-unsafe-declaration-merging */
/**
* Error thrown by {@link EveEvalTurn.expectOk} when a turn failed.
@@ -42,16 +52,35 @@ export class EveEvalTurnFailedError extends Error {
}
}
+export interface EvalSessionDriver extends EveEvalAssertions, EveEvalOutputAssertions {}
+
export class EvalSessionDriver implements EveEvalSession {
readonly #session: ClientSession;
readonly #signal: AbortSignal | undefined;
+ readonly #collector: AssertionCollector;
readonly #events: HandleMessageStreamEvent[] = [];
#lastTurn: EvalTurn | undefined;
#pendingInputRequests: readonly InputRequest[] = [];
- constructor(input: { readonly session: ClientSession; readonly signal?: AbortSignal }) {
+ constructor(input: {
+ readonly collector: AssertionCollector;
+ readonly session: ClientSession;
+ readonly signal?: AbortSignal;
+ }) {
+ this.#collector = input.collector;
this.#session = input.session;
this.#signal = input.signal;
+ Object.assign(
+ this,
+ createScopedAssertions(this.#collector, {
+ timing: "snapshot",
+ select: () => this.#assertionSubject(),
+ }),
+ createOutputAssertions(this.#collector, {
+ timing: "snapshot",
+ select: () => this.#assertionSubject(),
+ }),
+ );
}
get events(): readonly HandleMessageStreamEvent[] {
@@ -74,22 +103,26 @@ export class EvalSessionDriver implements EveEvalSession {
return this.#session.state;
}
- expectInputRequests(filter?: {
- readonly display?: InputRequest["display"];
- readonly toolName?: string;
- }): readonly InputRequest[] {
+ requireInputRequest(filter: EveEvalInputRequestMatchOptions = {}): InputRequest {
if (this.#pendingInputRequests.length === 0) {
- throw new Error("Expected pending input requests, but the last turn did not park.");
+ this.#failRequirement(
+ "requireInputRequest",
+ "expected one pending input request, but the last turn did not park",
+ );
}
const matching = this.#pendingInputRequests.filter((request) =>
inputRequestMatches(request, filter),
);
- if (matching.length === 0) {
- throw new Error(`No pending input requests matched ${formatInputRequestFilter(filter)}.`);
+ if (this.#pendingInputRequests.length !== 1 || matching.length !== 1) {
+ this.#failRequirement(
+ "requireInputRequest",
+ `expected exactly one pending input request matching ${formatInputRequestFilter(filter)}, found ${matching.length} match(es) across ${this.#pendingInputRequests.length} pending request(s)`,
+ );
}
- return matching;
+ this.#collector.recordOutcome({ name: "requireInputRequest", outcome: { score: 1 } });
+ return matching[0]!;
}
async respond(...responses: InputResponse[]): Promise<EveEvalTurn> {
@@ -101,7 +134,10 @@ export class EvalSessionDriver implements EveEvalSession {
}
async respondAll(optionId: string): Promise<EveEvalTurn> {
- const requests = this.expectInputRequests();
+ const requests = this.#pendingInputRequests;
+ if (requests.length === 0) {
+ throw new Error("respondAll() requires at least one pending input request.");
+ }
for (const request of requests) {
assertRequestHasOption(request, optionId);
}
@@ -166,7 +202,7 @@ export class EvalSessionDriver implements EveEvalSession {
events,
inputRequests: extractInputRequests(events),
message: extractCompletedMessage(events),
- sessionId,
+ sessionId: requireSessionId(sessionId),
status: deriveResultStatus(events),
});
}
@@ -187,7 +223,7 @@ export class EvalSessionDriver implements EveEvalSession {
readonly events: readonly HandleMessageStreamEvent[];
readonly inputRequests: readonly InputRequest[];
readonly message: string | undefined;
- readonly sessionId: string | undefined;
+ readonly sessionId: string;
readonly status: "completed" | "failed" | "waiting";
}): EveEvalTurn {
this.#events.push(...input.events);
@@ -195,19 +231,39 @@ export class EvalSessionDriver implements EveEvalSession {
const derived = deriveRunFacts(input.events, { sessionId: input.sessionId });
const turn = new EvalTurn({
+ collector: this.#collector,
data: input.data,
+ derived,
events: input.events,
inputRequests: input.inputRequests,
message: input.message,
- sessionId: input.sessionId ?? this.sessionId ?? "",
+ sessionId: input.sessionId,
status: input.status,
toolCalls: derived.toolCalls,
});
this.#lastTurn = turn;
return turn;
}
+
+ #assertionSubject() {
+ const sessionId = this.sessionId;
+ const derived = deriveRunFacts(this.#events, { sessionId });
+ return {
+ derived,
+ events: [...this.#events],
+ output: outputOf(this.#lastTurn),
+ status: this.#lastTurn?.status ?? "completed",
+ } as const;
+ }
+
+ #failRequirement(name: string, message: string): never {
+ this.#collector.recordOutcome({ name, outcome: { score: 0, message } });
+ throw new EvalRequirementFailed();
+ }
}
+interface EvalTurn extends EveEvalAssertions, EveEvalOutputAssertions {}
+
class EvalTurn implements EveEvalTurn {
readonly data: unknown;
readonly events: readonly HandleMessageStreamEvent[];
@@ -216,9 +272,13 @@ class EvalTurn implements EveEvalTurn {
readonly sessionId: string;
readonly status: "completed" | "failed" | "waiting";
readonly toolCalls: readonly EveEvalToolCall[];
+ readonly #collector: AssertionCollector;
+ readonly #derived: EveEvalDerivedFacts;
constructor(input: {
+ readonly collector: AssertionCollector;
readonly data: unknown;
+ readonly derived: EveEvalDerivedFacts;
readonly events: readonly HandleMessageStreamEvent[];
readonly inputRequests: readonly InputRequest[];
readonly message: string | undefined;
@@ -233,22 +293,68 @@ class EvalTurn implements EveEvalTurn {
this.sessionId = input.sessionId;
this.status = input.status;
this.toolCalls = input.toolCalls;
+ this.#collector = input.collector;
+ this.#derived = input.derived;
+ Object.assign(
+ this,
+ createScopedAssertions(input.collector, {
+ timing: "snapshot",
+ select: () => this.#assertionSubject(),
+ }),
+ createOutputAssertions(input.collector, {
+ timing: "snapshot",
+ select: () => this.#assertionSubject(),
+ }),
+ );
}
expectOk(): this {
if (this.status !== "failed") return this;
throw new EveEvalTurnFailedError(this);
}
+
+ requireToolCall(
+ name: string,
+ options: Omit<EveEvalToolCallMatchOptions, "count"> = {},
+ ): EveEvalToolCall {
+ const matching = this.toolCalls.filter(
+ (call) => call.name === name && toolCallMatches(call, options),
+ );
+ if (matching.length !== 1) {
+ inputRequirementFailed(
+ this.#collector,
+ "requireToolCall",
+ `expected exactly one matching "${name}" tool call in this turn, found ${matching.length}; observed [${this.toolCalls.map((call) => call.name).join(", ")}]`,
+ );
+ }
+ this.#collector.recordOutcome({ name: "requireToolCall", outcome: { score: 1 } });
+ return matching[0]!;
+ }
+
+ #assertionSubject() {
+ return {
+ derived: this.#derived,
+ events: this.events,
+ output: outputOf(this),
+ status: this.status,
+ } as const;
+ }
}
export class EvalSessionManager {
readonly #client: Client;
readonly #signal: AbortSignal | undefined;
+ readonly #collector: AssertionCollector;
readonly #sessions: EvalSessionDriver[] = [];
#primary: EvalSessionDriver | undefined;
- constructor(input: { readonly client: Client; readonly signal?: AbortSignal }) {
+ constructor(input: {
+ readonly client: Client;
+ readonly collector?: AssertionCollector;
+ readonly signal?: AbortSignal;
+ }) {
this.#client = input.client;
+ this.#collector = input.collector ?? new AssertionCollector();
this.#signal = input.signal;
}
@@ -266,6 +372,7 @@ export class EvalSessionManager {
options?: { readonly startIndex?: number },
): Promise<EvalSessionDriver> {
const session = new EvalSessionDriver({
+ collector: this.#collector,
session: this.#client.session({ sessionId, streamIndex: options?.startIndex ?? 0 }),
signal: this.#signal,
});
@@ -286,8 +393,13 @@ export class EvalSessionManager {
return this.#sessions.find((session) => session.lastTurn !== undefined);
}
+ hasActivity(): boolean {
+ return this.#sessions.length > 0;
+ }
+
#createSession(): EvalSessionDriver {
const session = new EvalSessionDriver({
+ collector: this.#collector,
session: this.#client.session(),
signal: this.#signal,
});
@@ -307,23 +419,29 @@ function attachSignal(input: SendTurnInput, signal: AbortSignal | undefined): Se
return payload.signal === undefined ? { ...payload, signal } : payload;
}
-function inputRequestMatches(
- request: InputRequest,
- filter: { readonly display?: InputRequest["display"]; readonly toolName?: string } | undefined,
-): boolean {
- if (filter === undefined) return true;
- if (filter.display !== undefined && request.display !== filter.display) return false;
- if (filter.toolName !== undefined) {
- return request.action.kind === "tool-call" && request.action.toolName === filter.toolName;
- }
- return true;
+function formatInputRequestFilter(filter: EveEvalInputRequestMatchOptions): string {
+ return JSON.stringify(filter);
}
-function formatInputRequestFilter(
- filter: { readonly display?: InputRequest["display"]; readonly toolName?: string } | undefined,
-): string {
- if (filter === undefined) return "{}";
- return JSON.stringify(filter);
+function inputRequirementFailed(
+ collector: AssertionCollector,
+ name: string,
+ message: string,
+): never {
+ collector.recordOutcome({ name, outcome: { score: 0, message } });
+ throw new EvalRequirementFailed();
+}
+
+function outputOf(turn: EveEvalTurn | undefined): unknown {
+ if (turn === undefined) return null;
+ return turn.data === undefined ? (turn.message ?? null) : turn.data;
+}
+
+function requireSessionId(sessionId: string | undefined): string {
+ if (sessionId === undefined) {
+ throw new Error("Eval session produced a turn without a session id.");
+ }
+ return sessionId;
}
function assertRequestHasOption(request: InputRequest, optionId: string): void {
diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.ts
index d6919a1f4..1e8577ef6 100644
--- a/packages/eve/src/evals/types.ts
+++ b/packages/eve/src/evals/types.ts
@@ -4,15 +4,20 @@ import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js"
import type { HandleMessageStreamEvent, RuntimeIdentity } from "#protocol/message.js";
import type { SendTurnInput, SessionState } from "#client/types.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
-import type { JsonObject } from "#shared/json.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
import type { AgentModelOptionsDefinition } from "#shared/agent-definition.js";
import type { EvalReporter } from "#evals/runner/reporters/types.js";
import type {
+ EveEvalEventMatch,
+ EveEvalInputRequestMatchOptions,
EveEvalSkillLoadMatchOptions,
EveEvalSubagentCallMatchOptions,
EveEvalToolCallMatchOptions,
} from "#evals/match.js";
+/** Lifecycle outcome of an eval-observed tool or subagent action. */
+export type EveEvalActionStatus = "pending" | "completed" | "failed" | "rejected";
+
/**
* One tool call extracted from the captured stream, pairing the
* `actions.requested` request with its matching `action.result`.
@@ -23,9 +28,9 @@ export interface EveEvalToolCall {
/** Tool input as requested by the model. */
readonly input: JsonObject;
/** Tool output from the matching `action.result`; `undefined` when the call never resolved. */
- readonly output: unknown;
- /** True when the matching `action.result` reported a failure. */
- readonly isError: boolean;
+ readonly output: JsonValue | undefined;
+ /** Whether the request is unresolved, completed, failed, or user-rejected. */
+ readonly status: EveEvalActionStatus;
/** Zero-based index of the turn the call happened in. */
readonly turnIndex: number;
/** Owning session id, when the runner knows it. */
@@ -42,9 +47,9 @@ export interface EveEvalSubagentCall {
/** Remote agent URL for remote delegations (`subagent.called` remote metadata). */
readonly remoteUrl?: string;
/** Output from the matching `subagent.completed` event; `undefined` when the call never completed. */
- readonly output?: unknown;
- /** True when the matching subagent action result reported a failure. */
- readonly isError: boolean;
+ readonly output?: JsonValue;
+ /** Whether the delegation is unresolved, completed, failed, or rejected. */
+ readonly status: EveEvalActionStatus;
/** Zero-based index of the turn the delegation happened in. */
readonly turnIndex: number;
/** Owning session id, when the runner knows it. */
@@ -84,9 +89,8 @@ export interface EveEvalSessionResult {
*/
export interface EveEvalTaskResult {
/**
- * The agent's last assistant message (same as {@link finalMessage}), retained
- * for reporters and artifacts that log a single "output" value. Mutable
- * because the runner assigns it after the run completes.
+ * The final turn's structured data when present, otherwise its last assistant
+ * message. Retained for reporters and artifacts that log one output value.
*/
output: unknown;
/** The agent's last assistant message, or null when none was produced. */
@@ -148,10 +152,10 @@ export interface Assertion {
/**
* Handle to a recorded assertion, returned by every `t` assertion method.
* Chain `gate`/`soft`/`atLeast` to override the recorded severity or
- * threshold, and `await` it to surface model-backed (judge) errors and ensure
- * the assertion has resolved before the run continues.
+ * threshold. Recorded assertions are finalized by the runner; use `t.require`
+ * or a `require*` lookup when later control flow depends on a passing result.
*/
-export interface AssertionHandle extends PromiseLike<void> {
+export interface AssertionHandle {
gate(threshold?: number): this;
soft(threshold?: number): this;
atLeast(threshold: number): this;
@@ -172,10 +176,44 @@ export interface AssertionResult {
readonly metadata?: Readonly<Record<string, unknown>>;
}
-/**
- * Driver for one session, exposed on the eval context and by `t.newSession()`.
- */
-export interface EveEvalSession {
+/** Recorded assertions shared by aggregate, session, and turn scopes. */
+export interface EveEvalAssertions {
+ succeeded(): AssertionHandle;
+ parked(): AssertionHandle;
+ messageIncludes(token: string | RegExp): AssertionHandle;
+ calledTool(name: string, options?: EveEvalToolCallMatchOptions): AssertionHandle;
+ /** Sugar for `calledTool("load_skill", { input: { skill }, ... })`. */
+ loadedSkill(skill: string, options?: EveEvalSkillLoadMatchOptions): AssertionHandle;
+ notCalledTool(name: string): AssertionHandle;
+ /** Asserts that tool requests appeared in order, allowing unrelated requests between them. */
+ toolOrder(names: readonly string[]): AssertionHandle;
+ usedNoTools(): AssertionHandle;
+ maxToolCalls(max: number): AssertionHandle;
+ calledSubagent(name: string, options?: EveEvalSubagentCallMatchOptions): AssertionHandle;
+ noFailedActions(): AssertionHandle;
+ event<TType extends HandleMessageStreamEvent["type"]>(
+ type: TType,
+ options?: Omit<Extract<EveEvalEventMatch, { type: TType }>, "type">,
+ ): AssertionHandle;
+ notEvent<TType extends HandleMessageStreamEvent["type"]>(
+ type: TType,
+ options?: Omit<Extract<EveEvalEventMatch, { type: TType }>, "type" | "count">,
+ ): AssertionHandle;
+ eventOrder(matchers: readonly EveEvalEventMatch[]): AssertionHandle;
+ eventsSatisfy(
+ label: string,
+ predicate: (events: readonly HandleMessageStreamEvent[]) => boolean,
+ ): AssertionHandle;
+}
+
+/** Assertions over the final output captured by one session or immutable turn. */
+export interface EveEvalOutputAssertions {
+ outputEquals(value: unknown): AssertionHandle;
+ outputMatches(schema: StandardSchemaV1): AssertionHandle;
+}
+
+/** Operations and state shared by the primary eval context and independent sessions. */
+export interface EveEvalSessionDriver {
/** All events observed on this session so far. */
readonly events: readonly HandleMessageStreamEvent[];
/** Input requests left pending by the last parked turn. */
@@ -184,11 +222,8 @@ export interface EveEvalSession {
readonly state: SessionState;
/** eve session id after the first successful send. */
readonly sessionId: string | undefined;
- /** Assert the last turn parked on HITL input and return matching requests. */
- expectInputRequests(filter?: {
- readonly display?: InputRequest["display"];
- readonly toolName?: string;
- }): readonly InputRequest[];
+ /** Require exactly one pending input request matching `filter`, or abort dependent control flow. */
+ requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;
/** Resolve specific pending requests and run the resumed turn. */
respond(...responses: InputResponse[]): Promise<EveEvalTurn>;
/** Resolve every pending request with the same option id. */
@@ -199,16 +234,26 @@ export interface EveEvalSession {
sendFile(text: string, filePath: string, mediaType?: string): Promise<EveEvalTurn>;
}
+/** Driver for one independent session, exposed by `t.newSession()` and target attachment helpers. */
+export interface EveEvalSession
+ extends EveEvalSessionDriver, EveEvalAssertions, EveEvalOutputAssertions {}
+
/**
* One completed eval-driver turn.
*/
-export interface EveEvalTurn {
+export interface EveEvalTurn extends EveEvalAssertions, EveEvalOutputAssertions {
readonly data: unknown;
readonly events: readonly HandleMessageStreamEvent[];
readonly inputRequests: readonly InputRequest[];
readonly message: string | undefined;
+ readonly sessionId: string;
readonly status: "completed" | "failed" | "waiting";
readonly toolCalls: readonly EveEvalToolCall[];
+ /** Require exactly one matching tool call, record a gate, and return it for dependent checks. */
+ requireToolCall(
+ name: string,
+ options?: Omit<EveEvalToolCallMatchOptions, "count">,
+ ): EveEvalToolCall;
expectOk(): this;
}
@@ -261,15 +306,13 @@ export interface JudgeContext {
/**
* The single context passed to an eval's `test(t)` function. It drives the
- * primary session (it extends {@link EveEvalSession}), carries the run-level
+ * primary session, carries the run-level
* and value-level assertion vocabulary, and exposes `judge` for LLM-as-judge.
*
- * Run-level assertions (`completed`, `calledTool`, …) record an entry
- * evaluated against the final run and never throw; `check` and `judge`
- * evaluate the supplied value immediately. Use plain `throw` /
- * `turn.expectOk()` for bespoke preconditions that should abort the run.
+ * Scoped assertions (`succeeded`, `calledTool`, …) record an entry evaluated
+ * after the test body; `check`, `require`, and `judge` evaluate explicit values.
*/
-export interface EveEvalContext extends EveEvalSession {
+export interface EveEvalContext extends EveEvalSessionDriver, EveEvalAssertions {
/** Eval timeout signal. */
readonly signal: AbortSignal;
/** Current target under test. */
@@ -283,29 +326,12 @@ export interface EveEvalContext extends EveEvalSession {
/** Create an additional independent session against the same target. */
newSession(): EveEvalSession;
- // Run-level assertions (lazy: evaluated against the final run; default gate).
- completed(): AssertionHandle;
- didNotFail(): AssertionHandle;
- waiting(): AssertionHandle;
- messageIncludes(token: string | RegExp): AssertionHandle;
- calledTool(name: string, options?: EveEvalToolCallMatchOptions): AssertionHandle;
- /** Sugar for `calledTool("load_skill", { input: { skill }, ... })`. */
- loadedSkill(skill: string, options?: EveEvalSkillLoadMatchOptions): AssertionHandle;
- notCalledTool(name: string): AssertionHandle;
- toolOrder(names: readonly string[]): AssertionHandle;
- usedNoTools(): AssertionHandle;
- maxToolCalls(max: number): AssertionHandle;
- calledSubagent(name: string, options?: EveEvalSubagentCallMatchOptions): AssertionHandle;
- noFailedActions(): AssertionHandle;
- event(
- predicate: (events: readonly HandleMessageStreamEvent[]) => boolean,
- label: string,
- ): AssertionHandle;
- outputEquals(value: unknown): AssertionHandle;
- outputMatches(schema: StandardSchemaV1): AssertionHandle;
-
/** Apply a value-level assertion (from `eve/evals/expect`) to a value. */
check(value: unknown, assertion: Assertion): AssertionHandle;
+ /** Record an immediate gate and abort dependent control flow when it fails. */
+ require<T>(value: T, assertion: Assertion): Promise<T>;
+ /** Mark this eval as intentionally skipped and stop executing its test body. */
+ skip(reason: string): never;
/** LLM-as-judge assertions, bound to the resolved judge model. */
readonly judge: JudgeContext;
@@ -423,8 +449,9 @@ export type EveEval = EveEvalDefinition & {
* - `"passed"` — no execution error, every gate held, every soft threshold met
* - `"failed"` — a gate assertion failed or execution errored (timeout, transport, thrown task)
* - `"scored"` — every gate held but a soft assertion fell below its threshold
+ * - `"skipped"` — the test body intentionally called `t.skip(reason)`
*/
-export type EveEvalVerdict = "passed" | "failed" | "scored";
+export type EveEvalVerdict = "passed" | "failed" | "scored" | "skipped";
/**
* Result of executing and asserting one eval.
@@ -440,6 +467,8 @@ export interface EveEvalResult {
/** Per-eval verdict; see {@link EveEvalVerdict}. */
readonly verdict: EveEvalVerdict;
readonly error?: string;
+ /** Why the eval intentionally skipped, present only for a `"skipped"` verdict. */
+ readonly skipReason?: string;
readonly startedAt: string;
readonly completedAt: string;
}
@@ -458,6 +487,8 @@ export interface EveEvalRunSummary {
readonly failed: number;
/** Evals with verdict `"scored"` (below-threshold soft assertions only). */
readonly scored: number;
+ /** Evals intentionally skipped by their test body. */
+ readonly skipped: number;
/** The execution-error subset of `failed` (timeouts, connection failures, exceptions). */
readonly errored: number;
}
diff --git a/packages/eve/src/internal/testing/scenario-apps/weather-agent.ts b/packages/eve/src/internal/testing/scenario-apps/weather-agent.ts
index 0ece22e69..99729327b 100644
--- a/packages/eve/src/internal/testing/scenario-apps/weather-agent.ts
+++ b/packages/eve/src/internal/testing/scenario-apps/weather-agent.ts
@@ -106,7 +106,7 @@ export default rows.map((row) =>
},
async test(t) {
await t.send(row.prompt);
- t.didNotFail();
+ t.succeeded();
},
}),
);
diff --git a/packages/eve/src/public/instrumentation/index.test.ts b/packages/eve/src/public/instrumentation/index.test.ts
index 96cc5f3df..4a8e0b208 100644
--- a/packages/eve/src/public/instrumentation/index.test.ts
+++ b/packages/eve/src/public/instrumentation/index.test.ts
@@ -84,6 +84,24 @@ describe("isChannel", () => {
expect(isChannel(resolveCtxChannel, supportChannel)).toBe(true);
});
+ it("recognizes a separately evaluated copy of the authored channel", () => {
+ setChannelInstrumentationKind(supportChannel, "channel:is-channel-test");
+ const importedCopy: typeof supportChannel = {
+ ...supportChannel,
+ adapter: { kind: "defineChannel" },
+ };
+
+ expect(
+ isChannel(
+ {
+ kind: "channel:is-channel-test",
+ metadata: { priority: "high", queueId: null },
+ },
+ importedCopy,
+ ),
+ ).toBe(true);
+ });
+
it("returns false for DynamicResolveContext.channel with undefined kind", () => {
setChannelInstrumentationKind(supportChannel, "channel:is-channel-test");