The Open Framework for Building Agents
Let SDK clients and evals set tool stubs at session creation (3/3) (#4370)
Philipp Comansa3c2f4058621
diff --git a/.changeset/declarative-tool-stubs.md b/.changeset/declarative-tool-stubs.mdnew file mode 100644index 000000000..6477908be--- /dev/null+++ b/.changeset/declarative-tool-stubs.md@@ -0,0 +1,9 @@+---+"eve": patch+---++Add explicitly authorized, session-scoped JSON tool stubs with argument matching and outcome sequences that continue across turns within the same session. Each rule specifies `outcome` or nonempty `outcomes`, with a JSON `response` in each outcome; eve's internal workflow recovery reuses recorded outcomes without consuming another entry.++Rules use first-match-wins ordering and explicit slash-separated paths for local child tools. Grant replacement permission on individual `vercelOidc` subject entries or in a custom authenticator's result; existing sessions follow normal channel authentication.++Invalid static tool paths and unsupported matcher features fail session creation. Unused rules produce eval warnings. Deployment handoffs use a new checkpoint version for all sessions, so sessions cannot hand off to deployments running an older version.diff --git a/docs/evals/meta.json b/docs/evals/meta.jsonindex 68d3c12be..61872c89e 100644--- a/docs/evals/meta.json+++ b/docs/evals/meta.json@@ -1,5 +1,14 @@{"title": "Evals","defaultOpen": false,- "pages": ["overview", "cases", "assertions", "judge", "targets", "reporters", "running"]+ "pages": [+ "overview",+ "cases",+ "assertions",+ "tool-stubs",+ "judge",+ "targets",+ "reporters",+ "running"+ ]}diff --git a/docs/evals/overview.mdx b/docs/evals/overview.mdxindex f23fd825e..088b143cb 100644--- a/docs/evals/overview.mdx+++ b/docs/evals/overview.mdx@@ -7,6 +7,8 @@ An eval is a scored check that runs your agent against real sessions and gradesEvals exercise the same HTTP surface your users hit. The runner boots (or targets) a real agent server, drives sessions through the [TypeScript client](../guides/client/overview) protocol, and grades what comes back, so a passing eval means the agent booted, accepted a request, and produced the result you asserted.+Define [tool stubs](./tool-stubs) in your eval to control tool results, then assert on the agent's tool calls and responses.+## `defineEval`eve discovers evals under the app-root `evals/` directory, in `.eval.ts` files. Each file is one eval by default. A file can also default-export an array to fan out over a dataset (see [Cases](./cases)). The file path is the eval's identity, so you don't author an `id` or `name`. Directories group related evals (`evals/weather/brooklyn-forecast.eval.ts` becomes id `weather/brooklyn-forecast`).diff --git a/docs/evals/tool-stubs.mdx b/docs/evals/tool-stubs.mdxnew file mode 100644index 000000000..7438e633f--- /dev/null+++ b/docs/evals/tool-stubs.mdx@@ -0,0 +1,238 @@+---+title: "Tool Stubs"+description: "Define tool outcomes and outcome sequences in your evals."+---++Pass `stubs` when creating an eval session to replace selected tool executions with JSON responses. The same rules work against local and deployed agents, without deploying mock functions or keeping the runner connected to answer tool calls.++Stubs specify what tools return. [Assertions](./assertions) check what the agent does and tells the user. Unused stubs produce a warning without failing the eval.++## Author an eval++```ts title="evals/complete-task.eval.ts"+import { defineEval } from "eve/evals";++export default defineEval({+ async test(t) {+ const session = await t.session({+ stubs: [+ {+ id: "tasks",+ tool: "list_tasks",+ outcomes: [+ {+ response: {+ tasks: [+ { id: "milk", title: "Buy milk" },+ { id: "dog", title: "Walk dog" },+ { id: "rent", title: "Pay rent" },+ ],+ },+ },+ {+ response: {+ tasks: [+ { id: "dog", title: "Walk dog" },+ { id: "rent", title: "Pay rent" },+ ],+ },+ },+ ],+ },+ {+ id: "complete-milk",+ tool: "complete_task",+ match: { task_id: { const: "milk" } },+ outcome: { response: { success: true } },+ },+ ],+ });++ const first = await session.send("What tasks do I have?");+ first.expectOk();+ first.calledTool("list_tasks", { count: 1 });+ first.messageIncludes("Buy milk");++ const second = await session.send("Complete Buy milk, then list my remaining tasks.");+ second.expectOk();+ second.calledTool("complete_task", { input: { task_id: "milk" }, count: 1 });+ second.toolOrder(["complete_task", "list_tasks"]);+ second.messageIncludes("Walk dog");+ second.messageIncludes("Pay rent");+ },+});+```++Use your agent's actual tool names and response shapes. The client accepts the same option on `client.sessions.create({ stubs })` or `client.sessions.create({ message, stubs })`.++These responses describe a sequence, not a simulated task database. The second `list_tasks` call returns two tasks even if `complete_task` was never called. The completion and order assertions check that the agent actually requested the write; testing a real database update requires the real tool.++## Stub fields++| Field | Meaning |+| ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |+| `id` | Your session-unique rule identifier. eve uses it to track this rule's response sequence. It is neither a tool name nor a tool-call ID. |+| `tool` | The existing tool's name, optionally qualified by its local subagent path. |+| `match` | Optional input-property constraints, expressed as JSON Schema. Omit it or use `{}` to match any valid input. |+| `outcome` | One outcome repeated on every matching call, such as `{ response: { tasks: [] } }`. |+| `outcomes` | A nonempty array of outcomes returned in sequence. Use exactly one of `outcome` or `outcomes`. |++Each outcome currently contains exactly one field: `response`, whose value is the JSON returned by the tool. The enclosing outcome is not part of the tool's response. Top-level `response` and `responses` are not accepted.++Exposing rule IDs and response positions in traces is a follow-up: [AX-5157](https://linear.app/vercel/issue/AX-5157).++Stubs are plain JSON and can be shared between evals:++```ts title="evals/fixtures/tasks.ts"+import type { ToolStub } from "eve/evals";++export const taskStubs = [+ { id: "tasks", tool: "list_tasks", outcome: { response: { tasks: [] } } },+] satisfies readonly ToolStub[];+```++Pass the fixture to `t.session({ stubs: taskStubs })`. Each session has its own sequence position. Both `eve/evals` and `eve/client` export `ToolStub` and `ToolStubOutcome`. These types check the JSON contract; they do not infer the response type from your tool definition.++## Match tool arguments++**Rules are evaluated from top to bottom. The first matching stub wins.** Put specific rules before an unconditional fallback:++```ts+const stubs = [+ {+ id: "milk",+ tool: "complete_task",+ match: { task_id: { const: "milk" } },+ outcome: { response: { success: true } },+ },+ { id: "other-tasks", tool: "complete_task", outcome: { response: { success: false } } },+];+```++A call for milk receives success; other valid calls receive the fallback. Reversing these rules makes the unconditional rule win every time. If no rule matches, eve executes the real tool. A selected stub failure fails the eval, even if the agent recovers; it never falls back to real execution.++If eve cannot record an output-processing failure, it cancels the workflow serving stubs. The original tool error or fallback is preserved, but verification rejects the eval. Failed or cancelled stub sessions cannot pass verification.++Every property listed in `match` must exist and satisfy its constraint. Extra top-level properties are allowed:++```json+{+ "id": "open-tasks",+ "tool": "search_tasks",+ "match": {+ "filter": {+ "type": "object",+ "properties": { "status": { "const": "open" } },+ "required": ["status"]+ },+ "query": { "type": "string", "pattern": "\\b(?i:milk)\\b" },+ "tags": { "type": "array", "contains": { "const": "urgent" } }+ },+ "outcome": { "response": { "tasks": ["Buy milk"] } }+}+```++Nested properties are optional unless listed in `required`. Matching does not coerce values, apply defaults, or change arguments. The real tool schema validates input before replacement; normal approvals and output processing still apply.++Constraints use a reference-free subset of JSON Schema 2020-12: types, scalar `const` and `enum`, string patterns and bounds, numeric bounds, array items/contains, object properties/required/additionalProperties, and logical/conditional schemas. `pattern` uses JavaScript regular expressions. Schema validation, regex syntax checks, and validator initialization run before session creation.++Unsupported constraints fail setup: `patternProperties`, references, formats, `multipleOf`, `minContains`, `maxContains`, `uniqueItems`, dependencies, and object/array values in `const` or `enum`. Nested `properties` and `required` cannot use inherited property names such as `constructor` or `toString`. Use nested properties or array items to match structured values.++Unknown static tool names, invalid local-agent paths, and paths into remote agents fail session creation. Dynamic names and connection operations are checked where possible; unresolved names are allowed. After the eval, unused rule IDs are reported as warnings. Use tool assertions when a call must happen.++Configuration is limited to 100 rules, 20,000 JSON nodes, nesting depth 32, and approximately one million characters. The `__proto__` property name is reserved.++## Sequences and session scope++`outcome` repeats on every matching call. `outcomes` advances on each new matching call, then repeats its final entry. For example, `outcomes: [{ response: "pending" }, { response: "completed" }]` returns `"pending"` once and `"completed"` thereafter. Only the selected rule advances; exhaustion never selects a later rule.++Two calls within one agent turn consume two entries. Later turns continue the same sequence. Calls awaiting or denied approval do not consume entries. Each session supports up to 10,000 recorded calls.++Choose the rules at session creation; they stay fixed for that session. Local subagents share playback through explicit tool paths, and deployment handoffs preserve it. An independent session starts at the first response.++eve's transparent internal workflow replay reuses the recorded outcome without consuming another entry.++Parallel calls consume responses in arrival order, which can vary. Use separate argument matchers when particular arguments must receive particular responses.++## Permit tool replacement++Tool replacement is denied by default, including in development. With [Vercel OIDC](../guides/auth-and-route-protection#verceloidc), put the permission on the eval runner's verified subject:++```ts title="agent/channels/eve.ts"+import { vercelOidc, vercelSubject } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";++export default eveChannel({+ auth: [+ vercelOidc({+ subjects: [+ vercelSubject({ teamSlug: "acme", projectName: "app" }),+ {+ subject: vercelSubject({ teamSlug: "acme", projectName: "eval-runner" }),+ allowToolStubs: true,+ },+ ],+ }),+ ],+});+```++Both projects can authenticate; only the eval runner receives replacement permission. `vercelSubject` defaults to production; pass `environment: "*"` to include all environments. The target's server configuration supplies the grant after token verification. Request JSON cannot grant permission, and user principals do not inherit project grants.++Custom authenticators can return the same `allowToolStubs: true` after verifying the caller. See [authentication and route protection](../guides/auth-and-route-protection#tool-replacement-permission) for the grant rules and a local development example.++Permission is checked at session creation before identity projection. Later messages and result reads use normal channel authentication. Anyone your channel admits to an existing session can use its stubs. Your application's session-access policy must provide the required isolation; an isolated eval deployment can use the same agent code.++The stub verification endpoint also requires `allowToolStubs`, checked before reading workflow status.++## Supported tools and subagents++Stubs replace execution of existing ordinary, dynamic, and workflow tools. They retain the real tool's input schema, approvals, and output processing. A stub does not register a new tool or make it visible to the model.++Ordinary tools with configured stub rules can emit an extra `action.partial` containing the final response. This also applies when no rule matches and the real tool returns a non-streaming result. The final `action.result` remains correct, and real streaming still delivers progress. Use `action.result` for final-result assertions. Removing the extra event is tracked in [AX-5164](https://linear.app/vercel/issue/AX-5164).++### Subagents++Stubbing a delegation tool returns its configured result without starting the subagent. Persistent tools implemented with `serve`, including the built-in `agent`, require an unconditional stub: omit `match` or use `{}`. Mixing real and mocked calls to the same persistent tool is unsupported.++To let a local subagent run but replace its tools, use `/` to qualify the delegation path:++```ts+const stubs = [+ { id: "root-tasks", tool: "list_tasks", outcome: { response: ["Root task"] } },+ { id: "research-tasks", tool: "researcher/list_tasks", outcome: { response: ["Research task"] } },+ { id: "nested-tasks", tool: "researcher/assistant/list_tasks", outcome: { response: [] } },+];+```++`researcher` replaces the whole delegation; `researcher/list_tasks` replaces only that subagent's list tool. The built-in `agent` uses `agent/list_tasks`. Model-visible names stay unchanged. A root rule never implicitly matches a subagent's same-named tool.++Repeated subagent sessions at the same path share that rule's sequence. Different paths use different rules. Remote agents do not receive the configuration; replace their whole delegation tool instead.++### Connections and provider tools++Use the qualified operation name, such as `linear__list_issues` or `researcher/linear__list_issues`. Put operation arguments in `match` and its JSON result in `outcome.response`, or in each sequence entry's `response`.++Connection authentication and discovery stay live so eve can validate the operation and its arguments. Stubs do not provide an offline connection. The framework's `connection_search` and `connection_execute` tools cannot themselves be replaced.++Tools executed by the model provider, such as provider-hosted web search, have no eve executor to replace. A search tool implemented in your own agent can be stubbed.++## Planned error outcomes++Error injection is a separate follow-up: [AX-5144](https://linear.app/vercel/issue/AX-5144). It will add `throw` as an alternative to `response` inside an outcome:++```ts+// Planned API; throw outcomes are not accepted yet.+const stubs = [+ {+ id: "tasks",+ tool: "list_tasks",+ outcomes: [+ { throw: { name: "TimeoutError", message: "Task service timed out" } },+ { response: { tasks: [] } },+ ],+ },+];+```++Each outcome will contain exactly one of `response` or `throw`. Exceptions will be injected immediately, without artificial delays or hanging calls. Expected tool failures will remain distinct from broken stub infrastructure: an eval can pass when the agent handles an injected failure correctly, but an infrastructure failure must fail verification. Returning `{ response: { error: "timeout" } }` today is ordinary JSON, not a thrown error.diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex 3e9f8a6d0..0e7fe4a4d 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -113,6 +113,8 @@ Verifies a bearer JWT against the [Vercel OIDC issuer](https://vercel.com/docs/oAuth fails closed: routes reject unauthenticated traffic by default, and the OIDC user branch verifies `external_sub` against `VERCEL_PROJECT_ID` and the deployment environment, returning `false` when either is unset. An external-subject token cannot authenticate on a deployment that hasn't pinned its project.+Subject entries can also be objects: `{ subject: vercelSubject({ teamSlug: "acme", projectName: "eval-runner" }), allowToolStubs: true }`. This explicitly permits that verified service/runtime caller to create [stubbed eval sessions](../evals/tool-stubs). Plain subject strings and implicit current-project acceptance grant ordinary access only. Custom authenticators can return the same permission in their authentication result; it is not part of persisted or forwarded session identity.+#### `subjects` patterns and `vercelSubject(...)`Each `subjects` entry is matched against the token's `sub` claim, which Vercel shapes as `owner:<team>:project:<name>:environment:<env>`. Hand-writing that string is a footgun: a typo silently rejects every caller, and an over-broad `*` wildcard silently lets unrelated ones in. Build the pattern with `vercelSubject(...)` instead. It rejects malformed input at construction time, and defaults `environment` to `"production"` when you omit it, so an unspecified environment cannot silently accept preview or development tokens:@@ -298,6 +300,29 @@ Use the principal on `auth.current` (or `auth.initiator`) to scope tools, resolvRoute auth does not enforce session ownership. If multiple users or tenants can reach the same route, you must implement the per-user, per-tenant, or per-session authorization your application requires.+## Tool replacement permission++Creating a [stubbed eval session](../evals/tool-stubs) requires an explicit `allowToolStubs: true` in the verified route authentication result. The target's server configuration grants permission; request JSON cannot. With `vercelOidc`, put the grant on a `subjects` entry as shown above. Any matching entry with the grant permits replacement; other entries do not revoke it. Implicit current-project acceptance and user principals do not inherit project grants.++Custom authenticators return the same grant after verifying their caller. For example, this alternative channel permits stubs only in local development:++```ts+import { localDev } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";++const authenticate = localDev();+export default eveChannel({+ auth: async (request) => {+ const caller = await authenticate(request);+ return caller ? { ...caller, allowToolStubs: true } : null;+ },+});+```++The channel checks the grant before forwarded-principal handling or `onMessage` projection. It removes the grant before using the identity for forwarding, audience classification, or session persistence. This is an authentication-result permission, not a session attribute.++Later messages, approvals, controls, and result reads use normal channel authentication. There is no additional creator-only rule or replacement-permission recheck. Anyone your channel admits to an existing session can use its configured stubs; apply the same application-specific session-access policy you need for ordinary sessions.+## Tool and connection authTool and connection auth is how your agent reaches an external service that wants an interactive sign-in, like an OAuth MCP server. Connections declare `auth` on the connection definition. Tools should resolve providers inline with `ctx.getToken(provider)` and call `ctx.requireAuth(provider)` only when a downstream service rejects a token; eve drives the sign-in, caches the token per step, and re-runs the call once the caller authorizes.diff --git a/e2e/fixtures/agent-tool-stubs/README.md b/e2e/fixtures/agent-tool-stubs/README.mdnew file mode 100644index 000000000..e00892d4e--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/README.md@@ -0,0 +1,29 @@+# Declarative tool stub verification++This fixture runs consumer evals with every real model in the `e2e-local`+matrix (`modelMatrix: full`). The tasks journey uses a semantic judge to+distinguish acknowledging a completed task from listing it as still open;+it carries the `real-model` tag. Matching and cross-turn playback also run+with the shared scripted responder in the Postgres and Vercel world suites.+A passing scripted world run is transport/durability evidence, not live-model evidence.++| Contract | Primary proof |+| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| List three tasks, complete the intended task, list two remaining tasks on a later turn | `evals/tasks.eval.ts`: tool arguments, counts, order, outputs, and final user-visible task list |+| Nested partial matching, string and array membership, extra input fields | `evals/matching.eval.ts`: actual model-generated arguments select the expected response |+| Overlapping rules select the first match | `evals/matching.eval.ts`: a specific rule precedes a broader matching fallback |+| Several calls to one tool within a turn, then continuation on a later turn | `evals/matching.eval.ts`: pending → first result → next result |+| An unmatched call invokes the real executor | `evals/matching.eval.ts`: distinct live marker |+| Supported matcher shapes and setup rejection | `packages/eve/src/tool-stubs/schema.test.ts`: representative matching, rejected keywords and values, no coercion/default mutation |+| Independent rule sequences, first-match precedence, replay, persistent-tool restrictions, bounds | `packages/eve/src/tool-stubs/rules.test.ts` and existing runtime integration tests |+| Root, child, and nested child paths stay distinct | `execution/tool-stubs/execution.integration.test.ts` and `test/scenarios/nested-tool-stubs.scenario.test.ts`: ordinary and workflow tools through compiled HTTP |+| Concurrent admission, separate session state, multi-turn continuation | `agent-workflow-stress/evals/tool-stubs.eval.ts` with its deliberately scripted model |++Matcher tests cover eve's supported subset and reject features affected by known+validator defects. They do not duplicate the dependency's conformance suite.+The runtime and compiled HTTP tests cover early rejection of invalid tool paths,+permission to inspect stub results, and recording which rules matched. The eval+runner warns about unused rules without turning them into call expectations.++Live-model evals verify the model/runtime boundary. They do not prove every+schema combination or every possible model response.diff --git a/e2e/fixtures/agent-tool-stubs/agent/agent.ts b/e2e/fixtures/agent-tool-stubs/agent/agent.tsnew file mode 100644index 000000000..f2e41da50--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/agent/agent.ts@@ -0,0 +1,35 @@+import { e2eAgentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++export default defineAgent({+ ...e2eAgentConfig({+ mock: (request) => {+ const roles = request.messages.map((message) => message.role);+ const hasResult = roles.lastIndexOf("tool") > roles.lastIndexOf("user");+ const result = request.toolResults.at(-1);+ const message = request.lastUserMessage ?? "";+ const lookupInput = () => JSON.parse(message.split("Lookup input: ")[1]!);+ if (hasResult) {+ if (result?.name === "complete_task") {+ return { toolCalls: [{ name: "list_tasks", input: {} }] };+ }+ if (+ result?.name === "lookup_record" &&+ JSON.stringify(result.output) === '{"marker":"pending"}'+ ) {+ return { toolCalls: [{ name: "lookup_record", input: lookupInput() }] };+ }+ return JSON.stringify(result?.output);+ }+ if (message.includes("Lookup input: ")) {+ return {+ toolCalls: [{ name: "lookup_record", input: lookupInput() }],+ };+ }+ if (message.includes("complete Buy milk")) {+ return { toolCalls: [{ name: "complete_task", input: { task_id: "milk" } }] };+ }+ return { toolCalls: [{ name: "list_tasks", input: {} }] };+ },+ }),+});diff --git a/e2e/fixtures/agent-tool-stubs/agent/channels/eve.ts b/e2e/fixtures/agent-tool-stubs/agent/channels/eve.tsnew file mode 100644index 000000000..79758b753--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/agent/channels/eve.ts@@ -0,0 +1,10 @@+import { localDev, vercelOidc } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";++export default eveChannel({+ // This isolated fixture has no production tools or data.+ auth: [vercelOidc(), localDev()].map((authenticate) => async (request) => {+ const auth = await authenticate(request);+ return auth ? { ...auth, allowToolStubs: true } : null;+ }),+});diff --git a/e2e/fixtures/agent-tool-stubs/agent/instructions.md b/e2e/fixtures/agent-tool-stubs/agent/instructions.mdnew file mode 100644index 000000000..96fafd588--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/agent/instructions.md@@ -0,0 +1,5 @@+Help Alice manage tasks and look up records. Use tools for current information.+For a task listing, call list_tasks once and return only the open task titles.+To complete a named task, use its ID from the conversation, call complete_task,+then call list_tasks once and return only the remaining task titles.+For a record lookup, use the input Alice provides and include the returned marker in your reply.diff --git a/e2e/fixtures/agent-tool-stubs/agent/tools/complete_task.ts b/e2e/fixtures/agent-tool-stubs/agent/tools/complete_task.tsnew file mode 100644index 000000000..d9d16687e--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/agent/tools/complete_task.ts@@ -0,0 +1,8 @@+import { defineTool } from "eve/tools";+import { z } from "zod";++export default defineTool({+ description: "Complete a task by its ID. Returns whether completion succeeded.",+ inputSchema: z.object({ task_id: z.string() }),+ execute: () => ({ success: false }),+});diff --git a/e2e/fixtures/agent-tool-stubs/agent/tools/list_tasks.ts b/e2e/fixtures/agent-tool-stubs/agent/tools/list_tasks.tsnew file mode 100644index 000000000..79bcdba18--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/agent/tools/list_tasks.ts@@ -0,0 +1,8 @@+import { defineTool } from "eve/tools";+import { z } from "zod";++export default defineTool({+ description: "List the currently open tasks with their IDs and titles.",+ inputSchema: z.object({}),+ execute: () => ({ tasks: [] }),+});diff --git a/e2e/fixtures/agent-tool-stubs/agent/tools/lookup_record.ts b/e2e/fixtures/agent-tool-stubs/agent/tools/lookup_record.tsnew file mode 100644index 000000000..e3fdcbae4--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/agent/tools/lookup_record.ts@@ -0,0 +1,13 @@+import { defineTool } from "eve/tools";+import { z } from "zod";++export default defineTool({+ description: "Look up records matching a filter and return a result marker.",+ inputSchema: z.object({+ filter: z.object({ status: z.enum(["open", "closed"]), owner: z.string() }),+ query: z.string(),+ tags: z.array(z.string()),+ limit: z.number().int().positive(),+ }),+ execute: () => ({ marker: "LIVE-LOOKUP" }),+});diff --git a/e2e/fixtures/agent-tool-stubs/evals/evals.config.ts b/e2e/fixtures/agent-tool-stubs/evals/evals.config.tsnew file mode 100644index 000000000..ae4971e2c--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/evals/evals.config.ts@@ -0,0 +1,3 @@+import { defineEvalConfig } from "eve/evals";++export default defineEvalConfig({ timeoutMs: 240_000 });diff --git a/e2e/fixtures/agent-tool-stubs/evals/matching.eval.ts b/e2e/fixtures/agent-tool-stubs/evals/matching.eval.tsnew file mode 100644index 000000000..0c829e894--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/evals/matching.eval.ts@@ -0,0 +1,76 @@+import { defineEval } from "eve/evals";++export default defineEval({+ description:+ "A model consumes a response sequence within and across turns and executes unmatched calls live.",+ async test(t) {+ const session = await t.session({+ stubs: [+ {+ id: "urgent-open",+ tool: "lookup_record",+ match: {+ filter: {+ type: "object",+ properties: { status: { const: "open" } },+ required: ["status"],+ },+ query: { type: "string", pattern: "\\b[Mm]ilk\\b" },+ tags: { type: "array", contains: { const: "urgent" } },+ },+ outcomes: [+ { response: { marker: "pending" } },+ { response: { marker: "MATCH-FIRST" } },+ { response: { marker: "MATCH-NEXT" } },+ ],+ },+ {+ id: "open-fallback",+ tool: "lookup_record",+ match: {+ filter: {+ type: "object",+ properties: { status: { const: "open" } },+ required: ["status"],+ },+ },+ outcome: { response: { marker: "FALLBACK" } },+ },+ ],+ });+ const matching = {+ filter: { status: "open", owner: "alice" },+ query: "buy milk",+ tags: ["personal", "urgent"],+ limit: 10,+ };+ const first = await session.send(+ `Alice is checking a record. Call lookup_record with this input. If its marker is pending, call it again with the same input. Report the final marker. Lookup input: ${JSON.stringify(matching)}`,+ );+ first.expectOk();+ first.calledTool("lookup_record", { input: matching, count: 2 });+ first.calledTool("lookup_record", { output: { marker: "pending" }, count: 1 });+ first.calledTool("lookup_record", { output: { marker: "MATCH-FIRST" }, count: 1 });+ first.messageIncludes("MATCH-FIRST");++ const next = await session.send(+ `Alice needs a fresh lookup of the same record. Call lookup_record once and report its marker. Lookup input: ${JSON.stringify(matching)}`,+ );+ next.expectOk();+ next.calledTool("lookup_record", { output: { marker: "MATCH-NEXT" }, count: 1 });+ next.messageIncludes("MATCH-NEXT");++ const unmatched = { ...matching, filter: { status: "closed", owner: "alice" } };+ const live = await session.send(+ `Alice also needs the closed record. Call lookup_record once and report its marker. Lookup input: ${JSON.stringify(unmatched)}`,+ );+ live.expectOk();+ live.calledTool("lookup_record", {+ input: unmatched,+ output: { marker: "LIVE-LOOKUP" },+ count: 1,+ });+ live.messageIncludes("LIVE-LOOKUP");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tool-stubs/evals/tasks.eval.ts b/e2e/fixtures/agent-tool-stubs/evals/tasks.eval.tsnew file mode 100644index 000000000..6a23db357--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/evals/tasks.eval.ts@@ -0,0 +1,72 @@+import { e2eJudgeModel } from "@eve-e2e/config";+import { defineEval } from "eve/evals";++export default defineEval({+ tags: ["real-model"],+ judge: { model: e2eJudgeModel() },+ description:+ "A model lists stubbed tasks, completes the intended task, and reports the remaining tasks in a follow-up turn.",+ async test(t) {+ const session = await t.session({+ stubs: [+ {+ id: "tasks",+ tool: "list_tasks",+ outcomes: [+ {+ response: {+ tasks: [+ { id: "milk", title: "Buy milk" },+ { id: "dog", title: "Walk dog" },+ { id: "rent", title: "Pay rent" },+ ],+ },+ },+ {+ response: {+ tasks: [+ { id: "dog", title: "Walk dog" },+ { id: "rent", title: "Pay rent" },+ ],+ },+ },+ ],+ },+ {+ id: "complete-milk",+ tool: "complete_task",+ match: { task_id: { const: "milk" } },+ outcome: { response: { success: true } },+ },+ ],+ });++ const first = await session.send("Alice asks: what open tasks do I have?");+ first.expectOk();+ first.calledTool("list_tasks", { count: 1 });+ first.notCalledTool("complete_task");+ first.messageIncludes("Buy milk");+ first.messageIncludes("Walk dog");+ first.messageIncludes("Pay rent");++ const second = await session.send(+ "Please complete Buy milk, then list only the tasks that are still open.",+ );+ second.expectOk();+ second.calledTool("complete_task", {+ input: { task_id: "milk" },+ output: { success: true },+ count: 1,+ });+ second.calledTool("list_tasks", { count: 1 });+ second.toolOrder(["complete_task", "list_tasks"]);+ second.messageIncludes("Walk dog");+ second.messageIncludes("Pay rent");+ t.judge(+ "The response identifies Walk dog and Pay rent as the only remaining open tasks. " ++ "It may acknowledge that Buy milk was completed, but must not present Buy milk as still open.",+ { on: second.message },+ ).gate(0.8);+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tool-stubs/package.json b/e2e/fixtures/agent-tool-stubs/package.jsonnew file mode 100644index 000000000..67cd46922--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/package.json@@ -0,0 +1,26 @@+{+ "name": "agent-tool-stubs",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "eve build",+ "dev": "eve dev",+ "start": "eve start",+ "typecheck": "eve build --skip-sandbox-prewarm && tsc",+ "test:e2e": "eve eval --strict"+ },+ "dependencies": {+ "@eve-e2e/config": "workspace:*",+ "@workflow/world-postgres": "catalog:",+ "eve": "workspace:*",+ "zod": "catalog:"+ },+ "devDependencies": {+ "@types/node": "catalog:",+ "typescript": "catalog:"+ },+ "e2e": {+ "modelMatrix": "full"+ }+}diff --git a/e2e/fixtures/agent-tool-stubs/tsconfig.json b/e2e/fixtures/agent-tool-stubs/tsconfig.jsonnew file mode 100644index 000000000..6fe20870f--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/tsconfig.json@@ -0,0 +1,12 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "esnext",+ "moduleResolution": "bundler",+ "strict": true,+ "skipLibCheck": true,+ "noEmit": true,+ "types": ["node"]+ },+ "include": ["agent/**/*.ts", "evals/**/*.ts"]+}diff --git a/e2e/fixtures/agent-workflow-stress/agent/channels/eve.ts b/e2e/fixtures/agent-workflow-stress/agent/channels/eve.tsnew file mode 100644index 000000000..79758b753--- /dev/null+++ b/e2e/fixtures/agent-workflow-stress/agent/channels/eve.ts@@ -0,0 +1,10 @@+import { localDev, vercelOidc } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";++export default eveChannel({+ // This isolated fixture has no production tools or data.+ auth: [vercelOidc(), localDev()].map((authenticate) => async (request) => {+ const auth = await authenticate(request);+ return auth ? { ...auth, allowToolStubs: true } : null;+ }),+});diff --git a/e2e/fixtures/agent-workflow-stress/evals/tool-stubs.eval.ts b/e2e/fixtures/agent-workflow-stress/evals/tool-stubs.eval.tsnew file mode 100644index 000000000..369d699a5--- /dev/null+++ b/e2e/fixtures/agent-workflow-stress/evals/tool-stubs.eval.ts@@ -0,0 +1,59 @@+import type { MessageStreamEvent, ToolStub } from "eve/client";+import { defineEval } from "eve/evals";++import { FANOUT_TOOL_NAME } from "../agent/lib/fanout";++export default defineEval({+ description: "Concurrent tool stubs consume a shared sequence across turns and isolate sessions.",+ tags: ["workflow", "tools", "stubs"],+ async test(t) {+ const stubs: readonly ToolStub[] = [+ {+ id: "fanout",+ tool: FANOUT_TOOL_NAME,+ outcomes: [+ { response: 0 },+ { response: 1 },+ { response: 2 },+ { response: 3 },+ { response: 4 },+ { response: 5 },+ { response: 6 },+ { response: 7 },+ { response: 8 },+ { response: 9 },+ ],+ },+ ];+ const session = await t.session({ stubs });+ const prompt = `Alice asks you to call \`${FANOUT_TOOL_NAME}\` once for each label.`;+ const first = await session.send(prompt);+ first.expectOk();+ first.calledTool(FANOUT_TOOL_NAME, { count: 10 });+ first.eventsSatisfy(+ "ten concurrent calls receive distinct sequence entries",+ (events) => JSON.stringify(outputs(events).sort()) === "[0,1,2,3,4,5,6,7,8,9]",+ );+ const second = await session.send(prompt);+ second.expectOk();+ second.calledTool(FANOUT_TOOL_NAME, { output: 9, count: 10 });++ const independent = await t.session({ stubs });+ const fresh = await independent.send(prompt);+ fresh.expectOk();+ fresh.eventsSatisfy(+ "a new session starts its own sequence",+ (events) => JSON.stringify(outputs(events).sort()) === "[0,1,2,3,4,5,6,7,8,9]",+ );+ },+});++function outputs(events: readonly MessageStreamEvent[]): unknown[] {+ return events.flatMap((event) =>+ event.type === "action.result" &&+ event.data.result.kind === "tool-result" &&+ event.data.result.toolName === FANOUT_TOOL_NAME+ ? [event.data.result.output]+ : [],+ );+}diff --git a/packages/eve/src/channel/auth/result.ts b/packages/eve/src/channel/auth/result.tsnew file mode 100644index 000000000..2af9c3b0f--- /dev/null+++ b/packages/eve/src/channel/auth/result.ts@@ -0,0 +1,8 @@+import type { SessionAuthContext } from "#channel/types.js";+import type { AuthResult } from "#public/channels/auth.js";++/** Do not save this request's stub permission or forward it to another agent. */+export function sessionAuthFromResult(result: AuthResult): SessionAuthContext {+ const { allowToolStubs: _allowToolStubs, ...auth } = result;+ return auth;+}diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex cc2ab555a..f4edecc4e 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -166,3 +166,4 @@ export {} from "#shared/input.js";export { resolveTextToResponse, resolveTextToResponses } from "#channel/resolve-text.js";+export type { ToolStub, ToolStubOutcome } from "#tool-stubs/types.js";diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex 937bd083e..5e6006bce 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -71,9 +71,9 @@ export class ClientSession {/** @internal */static async create<TOutput = unknown>(context: ClientSessionContext,- input: SendTurnInput<TOutput>,+ input: SendTurnInput<TOutput> & CreateSessionOptions,): Promise<{ readonly response: MessageResponse<TOutput>; readonly session: ClientSession }> {- const response = await postTurn(context, EVE_SESSION_ROUTE_PATH, input, true);+ const response = await postTurn(context, EVE_SESSION_ROUTE_PATH, input, true, input.stubs);const { sessionId } = await readAcceptedMessage(response);const session = new ClientSession(context, { sessionId, streamIndex: 0 });@@ -382,7 +382,10 @@ async function postCreateSession(options: CreateSessionOptions,): Promise<Response> {const headers = await context.resolveHeaders(options.headers);+ const body = options.stubs === undefined ? undefined : JSON.stringify({ stubs: options.stubs });+ if (body !== undefined) headers.set("content-type", "application/json");const response = await fetch(createClientUrl(context.host, EVE_SESSION_ROUTE_PATH), {+ body,headers,method: "POST",redirect: context.redirect,@@ -404,6 +407,7 @@ async function postTurn(path: string,input: SendTurnPayload,requireMessage: boolean,+ stubs?: CreateSessionOptions["stubs"],): Promise<Response> {const body = createMessageBody(input, requireMessage);if (body === null) {@@ -413,6 +417,7 @@ async function postTurn(: "A session turn requires a non-empty message or inputResponses.",);}+ if (stubs !== undefined) body.stubs = stubs;const headers = await context.resolveHeaders(input.headers);headers.set("content-type", "application/json");diff --git a/packages/eve/src/client/sessions.ts b/packages/eve/src/client/sessions.tsindex f9668ee4e..ff85f6fdf 100644--- a/packages/eve/src/client/sessions.ts+++ b/packages/eve/src/client/sessions.ts@@ -24,12 +24,12 @@ export class ClientSessions {/** Creates a session and starts its first turn with a message. */async create<TOutput = unknown>(- input: SendTurnInput<TOutput>,+ input: SendTurnInput<TOutput> & CreateSessionOptions,): Promise<CreatedClientSession<TOutput>>;/** Creates a conversation session before its first turn. */async create(options?: CreateSessionOptions): Promise<CreatedIdleClientSession>;async create<TOutput = unknown>(- input: CreateSessionOptions | SendTurnInput<TOutput> = {},+ input: CreateSessionOptions | (SendTurnInput<TOutput> & CreateSessionOptions) = {},): Promise<CreatedClientSession<TOutput> | CreatedIdleClientSession> {if ("message" in input) return await ClientSession.create(this.#context, input);return { session: await ClientSession.prewarm(this.#context, input) };diff --git a/packages/eve/src/client/tool-stubs.test.ts b/packages/eve/src/client/tool-stubs.test.tsnew file mode 100644index 000000000..533787625--- /dev/null+++ b/packages/eve/src/client/tool-stubs.test.ts@@ -0,0 +1,44 @@+import { afterEach, expect, expectTypeOf, it, vi } from "vitest";+import { Client } from "#client/client.js";+import type { CreatedClientSession } from "#client/sessions.js";+import type { ToolStub } from "#tool-stubs/types.js";++afterEach(() => vi.restoreAllMocks());++it.each([undefined, "Complete the milk task."])(+ "sends declarative rules when creating a session with message %s",+ async (message) => {+ let sent: unknown;+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) => {+ sent = JSON.parse(String(init?.body));+ return Response.json({ ok: true, sessionId: "session", status: "accepted" }, { status: 202 });+ });+ const client = new Client({ host: "https://agent.test" });+ const stubs = [+ {+ id: "milk",+ tool: "complete_task",+ match: { task_id: { const: "milk" } },+ outcomes: [{ response: { success: true } }, { response: { success: false } }],+ },+ ] satisfies ToolStub[];+ if (message === undefined) {+ await client.sessions.create({ stubs });+ } else {+ const created = await client.sessions.create({ message, stubs });+ expectTypeOf(created).toEqualTypeOf<CreatedClientSession>();+ }+ const expected: Record<string, unknown> = {+ stubs: [+ {+ id: "milk",+ tool: "complete_task",+ match: { task_id: { const: "milk" } },+ outcomes: [{ response: { success: true } }, { response: { success: false } }],+ },+ ],+ };+ if (message !== undefined) expected.message = message;+ expect(sent).toEqual(expected);+ },+);diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex 57adc9883..3b144e95c 100644--- a/packages/eve/src/client/types.ts+++ b/packages/eve/src/client/types.ts@@ -9,6 +9,7 @@ import type { ResetStatus } from "#protocol/reset-session.js";import type { TurnPolicy } from "#channel/types.js";import type { InputRequest, InputResponse } from "#shared/input.js";import type { JsonObject } from "#shared/json.js";+import type { ToolStub } from "#tool-stubs/types.js";export type { HealthResult } from "#client/health-schema.js";export type {@@ -110,6 +111,11 @@ export interface SendTurnInput<TOutput = unknown> extends SendTurnOptions<TOutpu/** Request options for creating a conversation session before its first turn. */export interface CreateSessionOptions {+ /**+ * Tool stubs stay fixed for this session and its local subagents.+ * The server must authorize their use.+ */+ readonly stubs?: readonly ToolStub[];/** Abort signal for cancelling the creation request. */readonly signal?: AbortSignal;/** Additional headers for this request only. */diff --git a/packages/eve/src/evals/index.ts b/packages/eve/src/evals/index.tsindex 75eafea72..7a463e086 100644--- a/packages/eve/src/evals/index.ts+++ b/packages/eve/src/evals/index.ts@@ -78,3 +78,4 @@ export type {MockModelToolResult,MockModelUsage,} from "#evals/mock-model.js";+export type { ToolStub, ToolStubOutcome } from "#tool-stubs/types.js";diff --git a/packages/eve/src/evals/runner/execute-task.ts b/packages/eve/src/evals/runner/execute-task.tsindex c81d16b11..9ff257d31 100644--- a/packages/eve/src/evals/runner/execute-task.ts+++ b/packages/eve/src/evals/runner/execute-task.ts@@ -88,6 +88,7 @@ export async function executeTask(options: ExecuteTaskOptions): Promise<ExecuteTlet skipReason: string | undefined;try {await runUntilAborted(evaluation.test(context), signal);+ await runUntilAborted(manager.verifyStubs(), signal);} catch (err) {if (err instanceof EvalSkipped) {skipReason = err.reason;diff --git a/packages/eve/src/evals/session-manager.ts b/packages/eve/src/evals/session-manager.tsindex 443f0aa36..218352705 100644--- a/packages/eve/src/evals/session-manager.ts+++ b/packages/eve/src/evals/session-manager.ts@@ -1,3 +1,4 @@+import { createLogger } from "#internal/logging.js";import type { ClientSession } from "#client/session.js";import type { CreateSessionOptions, SendTurnInput, SendTurnOptions } from "#client/types.js";import type { Client } from "#client/client.js";@@ -5,6 +6,9 @@ import { AssertionCollector } from "#evals/assertions/collector.js";import { EvalSessionDriver, type EvalSessionStartedEvent } from "#evals/session.js";import { cleanupEvalSessions } from "#evals/session-cleanup.js";import type { EveEvalLiveTurn, EveEvalSessionResult } from "#evals/types.js";+import { createEveSessionStubsRoutePath } from "#protocol/routes.js";++const log = createLogger("eve.evals");export class EvalSessionManager {readonly #client: Client;@@ -12,6 +16,11 @@ export class EvalSessionManager {readonly #collector: AssertionCollector;readonly #onSessionStart: ((event: EvalSessionStartedEvent) => void) | undefined;readonly #sessions: EvalSessionDriver[] = [];+ readonly #stubbedSessions: {+ readonly sessionId: string;+ readonly ruleIds: readonly string[];+ readonly headers?: Readonly<Record<string, string>>;+ }[] = [];#lastTurnSession: EvalSessionDriver | undefined;constructor(input: {@@ -31,9 +40,46 @@ export class EvalSessionManager {...options,signal: options.signal ?? this.#signal,});+ if (options.stubs !== undefined)+ this.#stubbedSessions.push({+ sessionId: session.state.sessionId,+ headers: options.headers,+ ruleIds: options.stubs.map((rule) => rule.id),+ });return this.#register(session);}+ /** A recorded stub failure always fails the eval, even if the agent recovers. */+ async verifyStubs(): Promise<void> {+ for (const session of this.#stubbedSessions) {+ const response = await this.#client.fetch(createEveSessionStubsRoutePath(session.sessionId), {+ headers: session.headers,+ signal: this.#signal,+ });+ if (!response.ok)+ throw new Error(+ `Could not verify tool stubs for session ${session.sessionId} (HTTP ${response.status}).`,+ );+ const result: unknown = await response.json();+ if (typeof result !== "object" || result === null || !("error" in result))+ throw new Error("Invalid tool stub verification response.");+ if (result.error !== null) throw new Error(`Tool stubbing failed: ${String(result.error)}`);+ if (+ !("matchedRuleIds" in result) ||+ !Array.isArray(result.matchedRuleIds) ||+ !result.matchedRuleIds.every((id) => typeof id === "string")+ )+ throw new Error("Invalid tool stub verification response.");+ const matchedRuleIds = result.matchedRuleIds;+ const unused = session.ruleIds.filter((id) => !matchedRuleIds.includes(id));+ if (unused.length > 0) {+ log.warn(`Tool stubs did not match any calls: ${unused.join(", ")}.`, {+ sessionId: session.sessionId,+ });+ }+ }+ }+async send(message: SendTurnInput["message"], options: SendTurnOptions = {}) {const { session, response } = await this.#client.sessions.create({turnPolicy: "queue",diff --git a/packages/eve/src/evals/session.test.ts b/packages/eve/src/evals/session.test.tsindex eaa9ce233..845be475d 100644--- a/packages/eve/src/evals/session.test.ts+++ b/packages/eve/src/evals/session.test.ts@@ -1,3 +1,4 @@+import { captureLogRecords } from "#internal/testing/log-records.js";import { readFile } from "node:fs/promises";import { afterEach, describe, expect, it, vi } from "vitest";@@ -186,3 +187,25 @@ async function* events() {},]);}++it("warns about unused stubs without failing verification", async () => {+ const { records } = captureLogRecords();+ const client = new Client({ host: "https://eve.test" });+ vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(Response.json({ sessionId: "session_1" }, { status: 202 }))+ .mockResolvedValueOnce(Response.json({ error: null, matchedRuleIds: ["used"] }));+ const manager = new EvalSessionManager({ client });+ await manager.session({+ stubs: [+ { id: "used", tool: "dynamic_tool", outcome: { response: true } },+ { id: "unused", tool: "connection__operation", outcome: { response: true } },+ ],+ });+ await expect(manager.verifyStubs()).resolves.toBeUndefined();+ expect(records).toContainEqual(+ expect.objectContaining({+ level: "warn",+ message: "Tool stubs did not match any calls: unused.",+ }),+ );+});diff --git a/packages/eve/src/evals/tool-stubs.integration.test.ts b/packages/eve/src/evals/tool-stubs.integration.test.tsnew file mode 100644index 000000000..f61f6d3e0--- /dev/null+++ b/packages/eve/src/evals/tool-stubs.integration.test.ts@@ -0,0 +1,157 @@+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";+import { expect, it, vi } from "vitest";+import { Client } from "#client/client.js";+import { eveChannel } from "#eve-channel/index.js";+import { executeTask } from "#evals/runner/execute-task.js";+import { createEvalTargetHandle } from "#evals/target.js";+import { workflowEntry } from "#execution/session/entry.js";+import { reportStubFailureStep } from "#execution/tool-stubs/steps.js";+import { dispatchWorkflowSessionCommand } from "#execution/workflow-runtime.js";+import { waitForHook } from "#internal/testing/workflow-test-helpers.js";+import { createTestRuntime } from "#internal/testing/app-harness.js";+import { buildSerializedContext, handoffFollowUp } from "#internal/testing/entry-test-helpers.js";+import { mockAgentRouteArgs } from "#internal/testing/mocks/mock-route-args.js";+import { failingDeployWorkflow } from "#internal/testing/workflow-tool-fixtures.js";+import { start, type Run } from "#internal/workflow/runtime.js";+import { EVE_MESSAGE_STREAM_VERSION, EVE_STREAM_VERSION_HEADER } from "#protocol/message.js";+import { parseToolStubs } from "#tool-stubs/rules.js";+import { STUB_CONTEXT_KEY } from "#tool-stubs/types.js";+import { defineWorkflowTool } from "#tools/workflow-definition.js";++it.each(["output processing", "failure reporting"])(+ "fails an otherwise passing eval after %s fails",+ async (failure) => {+ const runtime = await createTestRuntime({+ modules: [+ {+ logicalPath: "tools/deploy_service.ts",+ loadNamespace: async () => ({+ default: defineWorkflowTool({+ description: "Deploy a service.",+ inputSchema: {+ type: "object",+ properties: { service: { type: "string" } },+ required: ["service"],+ },+ task: failingDeployWorkflow,+ toModelOutput: () => {+ if (failure === "output processing") throw new Error("Invalid deployment result.");+ return { type: "text", value: "stubbed" };+ },+ }),+ }),+ },+ ],+ });+ const statusRoute = eveChannel({+ auth: () => ({+ allowToolStubs: true,+ principalId: "eval-runner",+ principalType: "service",+ authenticator: "test",+ attributes: {},+ }),+ }).routes!.find((route) => route.path.endsWith("/stubs"))!;+ await runtime.run(async () => {+ let run: Run<unknown> | undefined;+ // Simulate HTTP requests in memory while running the real workflow and status route.+ const originalFetch = globalThis.fetch;+ const fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {+ const url = new URL(request instanceof Request ? request.url : String(request));+ if (url.origin !== "https://eve.test") return await originalFetch(request, init);+ if (url.pathname === "/eve/v1/session") {+ const body = JSON.parse(String(init?.body));+ run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: {},+ serializedContext: {+ ...buildSerializedContext({ channelKind: "http" }),+ [STUB_CONTEXT_KEY]: {+ token: "runner-output-failure",+ rules: parseToolStubs(body.stubs),+ },+ },+ },+ ]);+ await waitForHook({ runId: run.runId }, { token: "runner-output-failure" });+ return Response.json({ sessionId: run.runId }, { status: 202 });+ }+ if (url.pathname.endsWith("/stubs")) {+ return (await statusRoute.handler(new Request(url), {+ ...mockAgentRouteArgs(),+ ...mockChannelContext(() => {+ throw new Error("Unexpected channel dispatch.");+ }),+ attachSession: () => {+ throw new Error("Unexpected session attachment.");+ },+ to: () => {+ throw new Error("Unexpected remote dispatch.");+ },+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ params: { sessionId: run!.runId },+ })) as Response;+ }+ if (url.pathname.endsWith("/stream")) {+ return new Response(run!.getReadable<Uint8Array>(), {+ headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },+ });+ }+ const body = JSON.parse(String(init?.body));+ await dispatchWorkflowSessionCommand({+ sessionId: run!.runId,+ command: handoffFollowUp("dpl_inline", body.message, "eval-message"),+ });+ return Response.json(+ { sessionId: run!.runId, deliveryId: "eval-message" },+ { status: 200 },+ );+ });+ try {+ const client = new Client({ host: "https://eve.test" });+ const outcome = await executeTask({+ client,+ target: createEvalTargetHandle({+ capabilities: { devRoutes: true },+ client,+ kind: "local",+ url: "https://eve.test",+ }),+ evaluation: {+ _tag: "EveEval",+ id: "bad-task-output",+ async test(t) {+ const session = await t.session({+ stubs: [{ id: "deploy", tool: "deploy_service", outcome: { response: "stubbed" } }],+ });+ const turn = await session.send('Run deploy_service with service "api"');+ turn.expectOk();+ turn.calledTool("deploy_service", { count: 1 });+ if (failure === "failure reporting") {+ await reportStubFailureStep(+ { token: "unavailable-playback", rootSessionId: run!.runId, rules: [] },+ "deploy",+ "Invalid deployment result.",+ );+ }+ },+ },+ });+ expect(outcome.result.status).toBe("waiting");+ expect(outcome.assertions.length).toBeGreaterThan(0);+ expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);+ expect(outcome.error).toContain(+ failure === "output processing"+ ? 'Stubbed tool "deploy_service" failed during output processing.'+ : "Tool stub session failed before verification.",+ );+ } finally {+ fetch.mockRestore();+ await run?.cancel();+ }+ });+ },+);diff --git a/packages/eve/src/eve-channel/create-request.ts b/packages/eve/src/eve-channel/create-request.tsindex 9f8c238c8..d0dc64408 100644--- a/packages/eve/src/eve-channel/create-request.ts+++ b/packages/eve/src/eve-channel/create-request.ts@@ -3,8 +3,10 @@ import type { UserContent } from "ai";import type { SessionCallback, SessionCapabilities } from "#channel/types.js";import type { LegacyRemoteAgentCaller } from "#execution/legacy-remote-agent/protocol.js";import type { JsonObject } from "#shared/json.js";+import type { ToolStub } from "#tool-stubs/types.js";export interface ParsedCreateBody {+ stubs?: readonly ToolStub[];callback?: SessionCallback;capabilities?: SessionCapabilities;message?: string | UserContent;diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex b632e0773..19f203b18 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -1,3 +1,6 @@+import { InvalidToolStubTargetError } from "#tool-stubs/validate-targets.js";+import { readStubFailure, readMatchedStubRules } from "#execution/tool-stubs/steps.js";+import { getRun } from "#internal/workflow/runtime.js";import { handleExpiredLegacyAuthorization } from "#execution/legacy-session/authorization.js";import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";import type { SessionAuthContext, SessionParent, SessionTraceContext } from "#channel/types.js";@@ -35,6 +38,7 @@ import {EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,+ EVE_SESSION_STUBS_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath,@@ -53,6 +57,7 @@ import {FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling,} from "#shared/forwarded-trace-policy.js";+import { sessionAuthFromResult } from "#channel/auth/result.js";import { routeAuth } from "#public/channels/auth.js";import { defaultEveAudience } from "#eve-channel/audience.js";import { mergeUploadPolicy } from "#public/channels/upload-policy.js";@@ -159,15 +164,22 @@ export function eveChannel(input: EveChannelInput): EveChannel {POST(EVE_SESSION_ROUTE_PATH, async (req, args) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;+ const auth = sessionAuthFromResult(authResult);const payload = await parseOptionalJsonRequest(req);if (payload instanceof Response) return payload;+ if (payload.stubs !== undefined && authResult.allowToolStubs !== true) {+ return Response.json(+ { ok: false, error: "Tool stubbing is not permitted for this caller." },+ { status: 403 },+ );+ }const tokenRejection = rejectSessionContinuationToken(payload);if (tokenRejection !== null) return tokenRejection;const forwarded = await resolveForwardedPrincipal({trustedForwarders: input.trustedForwarders,- forwarder: authResult,+ forwarder: auth,payload,});if (forwarded instanceof Response) return forwarded;@@ -194,7 +206,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {let accepted = forwarded.accepted;if (!accepted && input.trustedForwarders !== undefined) {try {- accepted = await input.trustedForwarders(authResult, {});+ accepted = await input.trustedForwarders(auth, {});} catch (error) {const errorId = logError(log, "trustedForwarders handler failed", error, {forwarder: authResult.principalId,@@ -324,7 +336,14 @@ export function eveChannel(input: EveChannelInput): EveChannel {let handle: Awaited<ReturnType<typeof createSession>>;try {handle = await createSession({- audienceAuth: authResult,+ audienceAuth: auth,+ toolStubs:+ body.stubs === undefined+ ? undefined+ : {+ rules: body.stubs,+ token: crypto.randomUUID(),+ },auth: messageResult.auth,capabilities: body.capabilities ?? { requestInput: true },callback: body.callback,@@ -351,6 +370,9 @@ export function eveChannel(input: EveChannelInput): EveChannel {title: messageResult.title,});} catch (error) {+ if (error instanceof InvalidToolStubTargetError) {+ return Response.json({ error: error.message, ok: false }, { status: 400 });+ }const errorId = logError(log, "session-create request failed", error);return Response.json({ error: "Failed to create the session.", errorId, ok: false },@@ -377,7 +399,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {if (payload instanceof Response) return payload;const forwarded = await resolveForwardedPrincipal({trustedForwarders: input.trustedForwarders,- forwarder: authResult,+ forwarder: sessionAuthFromResult(authResult),payload,});if (forwarded instanceof Response) return forwarded;@@ -585,6 +607,39 @@ export function eveChannel(input: EveChannelInput): EveChannel {);}),+ GET(EVE_SESSION_STUBS_ROUTE_PATTERN, async (req, { params }) => {+ const authResult = await routeAuth(req, input.auth);+ if (authResult instanceof Response) return authResult;+ if (authResult.allowToolStubs !== true) {+ return Response.json(+ { error: "Tool stubbing is not permitted for this caller.", ok: false },+ { status: 403 },+ );+ }+ const sessionId = requireSessionId(params);+ if (sessionId instanceof Response) return sessionId;+ try {+ if (!(await getRun(sessionId).exists)) {+ return Response.json({ error: "Session not found.", ok: false }, { status: 404 });+ }+ return Response.json(+ {+ error: (await readStubFailure(sessionId)) ?? null,+ matchedRuleIds: await readMatchedStubRules(sessionId),+ },+ { headers: { "cache-control": "no-store" } },+ );+ } catch (error) {+ const errorId = logError(log, "tool-stub verification request failed", error, {+ sessionId,+ });+ return Response.json(+ { error: "Failed to verify tool stubs.", errorId, ok: false },+ { status: 500 },+ );+ }+ }),+GET(EVE_SESSION_STREAM_ROUTE_PATTERN, async (req, { attachSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.tsindex a2164d04b..f17efe5ab 100644--- a/packages/eve/src/eve-channel/request.ts+++ b/packages/eve/src/eve-channel/request.ts@@ -1,3 +1,4 @@+import { parseToolStubs } from "#tool-stubs/rules.js";import type { FilePart, TextPart, UserContent } from "ai";import type {@@ -114,6 +115,16 @@ export function parseCreateBody(input: Record<string, unknown>): ParsedCreateBodcontext,outputSchema,};+ if (payload.stubs !== undefined) {+ try {+ result.stubs = parseToolStubs(payload.stubs);+ } catch (error) {+ return Response.json(+ { ok: false, error: error instanceof Error ? error.message : "Invalid tool stubs." },+ { status: 400 },+ );+ }+ }if (message !== undefined) result.message = message;if (typeof rawOperationId === "string") result.operationId = rawOperationId;if (protocolVersion !== undefined) result.protocolVersion = protocolVersion;@@ -136,6 +147,12 @@ export function parseSessionMessageBody(input: Record<string, unknown>,): ParsedSessionMessageBody | Response {const { payload } = splitLegacyTaskFields(input);+ if (Object.hasOwn(payload, "stubs")) {+ return Response.json(+ { ok: false, error: "Tool stubs are fixed at session creation." },+ { status: 400 },+ );+ }const tokenRejection = rejectSessionContinuationToken(payload);if (tokenRejection !== null) return tokenRejection;diff --git a/packages/eve/src/eve-channel/tool-stubs.test.ts b/packages/eve/src/eve-channel/tool-stubs.test.tsnew file mode 100644index 000000000..3c5326a03--- /dev/null+++ b/packages/eve/src/eve-channel/tool-stubs.test.ts@@ -0,0 +1,216 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { eveChannel } from "#eve-channel/index.js";+import type { EveChannelInput } from "#eve-channel/types.js";+import type { RouteHandlerArgs } from "#channel/routes.js";+import { mockAgentRouteArgs } from "#internal/testing/mocks/mock-route-args.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";+import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";+import { captureLogRecords } from "#internal/testing/log-records.js";++const storage = vi.hoisted(() => ({+ exists: vi.fn<() => Promise<boolean>>(),+ failure: vi.fn<() => Promise<string | undefined>>(),+ matched: vi.fn<() => Promise<readonly string[]>>(),+}));++vi.mock("#execution/tool-stubs/steps.js", () => ({+ readStubFailure: storage.failure,+ readMatchedStubRules: storage.matched,+}));+vi.mock("#internal/workflow/runtime.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#internal/workflow/runtime.js")>()),+ getRun: () => ({+ get exists() {+ return storage.exists();+ },+ }),+}));++beforeEach(() => {+ storage.exists.mockReset().mockResolvedValue(true);+ storage.failure.mockReset().mockResolvedValue(undefined);+ storage.matched.mockReset().mockResolvedValue(["used"]);+});++const alice = {+ authenticator: "verified-token",+ issuer: "tests",+ principalId: "alice",+ principalType: "user",+ subject: "eval-a",+ attributes: { role: "eval" },+};+const bob = { ...alice, principalId: "bob", subject: "eval-b", attributes: { role: "user" } };++describe("tool stub authorization", () => {+ it("rejects authenticated callers without explicit override permission before session creation", async () => {+ const response = await request(+ { auth: () => alice },+ "POST",+ "/eve/v1/session",+ {},+ { stubs: [{ id: "auth", tool: "authenticate", outcome: { response: true } }] },+ );+ expect(response.status).toBe(403);+ });++ it("binds the grant to route authentication before onMessage projects the session principal", async () => {+ let scope: unknown;+ const response = await request(+ {+ auth: () => ({ ...alice, allowToolStubs: true }),+ onMessage: (ctx) => {+ expect(ctx.eve.caller).not.toHaveProperty("allowToolStubs");+ return { auth: bob };+ },+ },+ "POST",+ "/eve/v1/session",+ {},+ {+ message: "Hello",+ stubs: [{ id: "auth", tool: "authenticate", outcome: { response: true } }],+ },+ (input) => {+ expect(input.audienceAuth).not.toHaveProperty("allowToolStubs");+ scope = input.toolStubs;+ return { sessionId: "created" } as never;+ },+ );+ expect(response.status).toBe(202);+ expect(scope).toMatchObject({+ rules: [{ id: "auth", tool: "authenticate", outcome: { response: true } }],+ });+ expect(scope).toHaveProperty("token", expect.any(String));+ });++ it("does not accept permission supplied in a request body or projected by onMessage", async () => {+ const response = await request(+ { auth: () => bob, onMessage: () => ({ auth: { ...alice, allowToolStubs: true } }) },+ "POST",+ "/eve/v1/session",+ {},+ {+ allowToolStubs: true,+ stubs: [{ id: "auth", tool: "authenticate", outcome: { response: true } }],+ },+ );+ expect(response.status).toBe(403);+ });++ it.each([+ ["POST", "/eve/v1/session/:sessionId"],+ ["POST", "/eve/v1/session/:sessionId/compact"],+ ["POST", "/eve/v1/session/:sessionId/clear"],+ ["GET", "/eve/v1/session/:sessionId/stream"],+ ["GET", "/eve/v1/session/:sessionId/stubs"],+ ])("requires channel authentication for %s %s", async (method, path) => {+ const response = await request(+ { auth: () => null },+ method,+ path,+ { sessionId: "session", parentSessionId: "parent", childSessionId: "child", callId: "call" },+ { message: "Hello" },+ );+ expect(response.status).toBe(401);+ });+});++describe("tool stub verification", () => {+ it("requires the stub grant before reading any workflow", async () => {+ const response = await request(+ { auth: () => alice },+ "GET",+ "/eve/v1/session/:sessionId/stubs",+ { sessionId: "arbitrary-run" },+ );+ expect(response.status).toBe(403);+ expect(storage.exists).not.toHaveBeenCalled();+ expect(storage.failure).not.toHaveBeenCalled();+ expect(storage.matched).not.toHaveBeenCalled();+ });+ it("does not report success for a missing session", async () => {+ storage.exists.mockResolvedValue(false);+ const response = await request(+ { auth: () => ({ ...alice, allowToolStubs: true }) },+ "GET",+ "/eve/v1/session/:sessionId/stubs",+ { sessionId: "missing" },+ );+ expect(response.status).toBe(404);+ });++ it.each([undefined, "Stubbed tool output was invalid."])(+ "reports the recorded failure for an existing session: %s",+ async (failure) => {+ storage.failure.mockResolvedValue(failure);+ const response = await request(+ { auth: () => ({ ...alice, allowToolStubs: true }) },+ "GET",+ "/eve/v1/session/:sessionId/stubs",+ { sessionId: "session" },+ );+ expect(response.status).toBe(200);+ expect(response.headers.get("cache-control")).toBe("no-store");+ expect(await response.json()).toEqual({ error: failure ?? null, matchedRuleIds: ["used"] });+ },+ );++ it.each(["exists", "failure", "matched"] as const)(+ "returns a safe error when the %s read fails",+ async (operation) => {+ captureLogRecords();+ storage[operation].mockRejectedValue(new Error("private backend details"));+ const response = await request(+ { auth: () => ({ ...alice, allowToolStubs: true }) },+ "GET",+ "/eve/v1/session/:sessionId/stubs",+ { sessionId: "session" },+ );+ expect(response.status).toBe(500);+ expect(await response.json()).toEqual({+ error: "Failed to verify tool stubs.",+ errorId: expect.any(String),+ ok: false,+ });+ },+ );+});++async function request(+ config: EveChannelInput,+ method: string,+ path: string,+ params: Record<string, string>,+ body?: unknown,+ create?: Parameters<typeof attachRouteSessionCreator>[1],+): Promise<Response> {+ const route = eveChannel(config).routes!.find(+ (route) => route.method === method && route.path === path,+ )!;+ const args = {+ ...mockAgentRouteArgs(),+ ...mockChannelContext(() => {+ throw new Error("Unexpected channel dispatch.");+ }),+ params,+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ attachSession: () => {+ throw new Error("Unauthorized session access reached the runtime.");+ },+ to: () => {+ throw new Error("Unexpected remote dispatch.");+ },+ } satisfies RouteHandlerArgs;+ if (create !== undefined) attachRouteSessionCreator(args, create);+ return (await route.handler(+ new Request("https://agent.test" + path, {+ method,+ ...(method === "GET"+ ? {}+ : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),+ }),+ args,+ )) as Response;+}diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex c0681f950..64874c6c1 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -1,3 +1,4 @@+import { validateToolStubTargets } from "#tool-stubs/validate-targets.js";import { context, trace } from "#compiled/@opentelemetry/api/index.js";import {EntityConflictError,@@ -124,6 +125,9 @@ export function createWorkflowRuntime(config: {compiledArtifactsSource: config.compiledArtifactsSource,nodeId: config.nodeId,});+ if (input.toolStubs !== undefined && input.toolStubs.rootSessionId === undefined) {+ validateToolStubTargets(input.toolStubs.rules, bundle.graph);+ }const ctx = buildRunContext({bundle,dynamicSubagentAgentConfig: config.dynamicSubagentAgentConfig,diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.tsindex 1ebd02dbf..2773bf5e8 100644--- a/packages/eve/src/protocol/routes.ts+++ b/packages/eve/src/protocol/routes.ts@@ -37,6 +37,9 @@ export const EVE_SESSION_CLEAR_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessi/** Stable route pattern for resetting one exact session ID. */export const EVE_SESSION_RESET_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/reset`;+/** Stable route pattern for eval tool-stub verification. */+export const EVE_SESSION_STUBS_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/stubs`;+/** Stable event-stream route pattern for one exact session ID. */export const EVE_SESSION_STREAM_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/stream`;@@ -183,3 +186,8 @@ export function createEveCallbackRoutePath(token: string): string {export function createEveTaskInputRoutePath(token: string): string {return `${EVE_ROUTE_PREFIX}/task-input/${encodeURIComponent(token)}`;}++/** Builds the tool-stub verification route for one session. */+export function createEveSessionStubsRoutePath(sessionId: string): string {+ return `${createEveSessionRoutePath(sessionId)}/stubs`;+}diff --git a/packages/eve/src/public/channels/auth.test.ts b/packages/eve/src/public/channels/auth.test.tsindex 20f6e5e77..95c7ed0fe 100644--- a/packages/eve/src/public/channels/auth.test.ts+++ b/packages/eve/src/public/channels/auth.test.ts@@ -1460,6 +1460,54 @@ describe("vercelOidc strategy helper", () => {await expect(Promise.resolve(authFn(request))).resolves.toBeNull();});+ it("grants stubs only through an explicitly granting matched subject entry", async () => {+ const issuer = await installMockedVercelIssuer("stub-subject-grants");+ const subject = "owner:acme:project:eval-runner:environment:preview";+ const wildcard = "owner:acme:project:eval-runner:environment:*";+ try {+ const token = await issuer.signToken({+ environment: "preview",+ project_id: "prj_eval",+ sub: subject,+ });+ const request = new Request(TEST_ROUTE_URL, {+ headers: { authorization: `Bearer ${token}` },+ });+ const cases = [+ { subjects: undefined, allowed: false },+ { subjects: [], allowed: false },+ { subjects: [subject], allowed: false },+ { subjects: [{ subject }], allowed: false },+ { subjects: [{ subject, allowToolStubs: false }], allowed: false },+ { subjects: [{ subject: "another-project", allowToolStubs: true }], allowed: false },+ { subjects: [{ subject: wildcard, allowToolStubs: true }], allowed: true },+ { subjects: [subject, { subject: wildcard, allowToolStubs: true }], allowed: true },+ ];+ for (const { subjects, allowed } of cases) {+ const auth = await vercelOidc({+ currentVercelProject: { projectId: "prj_eval", environment: "preview" },+ subjects,+ })(request);+ expect(auth?.principalType).toBe("runtime");+ expect(auth?.allowToolStubs === true).toBe(allowed);+ }+ const userToken = await issuer.signToken({+ environment: "development",+ project_id: "prj_eval",+ sub: subject,+ user_id: "user_alice",+ });+ const user = await vercelOidc({+ currentVercelProject: { projectId: "prj_eval", environment: "development" },+ subjects: [{ subject: "*", allowToolStubs: true }],+ })(new Request(TEST_ROUTE_URL, { headers: { authorization: `Bearer ${userToken}` } }));+ expect(user?.principalType).toBe("user");+ expect(user?.allowToolStubs).toBeUndefined();+ } finally {+ issuer.restore();+ }+ });+it("uses the local host's linked project binding only for bearer requests", async () => {vi.stubEnv("VERCEL_PROJECT_ID", "");vi.stubEnv("VERCEL_TARGET_ENV", "");diff --git a/packages/eve/src/public/channels/auth.ts b/packages/eve/src/public/channels/auth.tsindex ca2487e8f..77017050f 100644--- a/packages/eve/src/public/channels/auth.ts+++ b/packages/eve/src/public/channels/auth.ts@@ -5,6 +5,7 @@* helpers are lower-level pure functions for custom `fetch` handlers.*/+import { areTokenClaimMatchersSatisfied } from "#channel/auth/token-claims.js";import { decodeJwt } from "#compiled/jose/index.js";import type { SessionAuthContext } from "#channel/types.js";@@ -508,6 +509,14 @@ export class ForbiddenError extends Error {}}+export interface AuthResult extends SessionAuthContext {+ /**+ * Set to true to let this authenticated caller create sessions with tool stubs.+ * Callers without this permission cannot supply stubs.+ */+ readonly allowToolStubs?: boolean;+}+/*** Route auth callback. Returned value semantics inside {@link routeAuth}:*@@ -521,7 +530,7 @@ export class ForbiddenError extends Error {*/export type AuthFn<TEvent = Request> = (event: TEvent,-) => SessionAuthContext | null | undefined | Promise<SessionAuthContext | null | undefined>;+) => AuthResult | null | undefined | Promise<AuthResult | null | undefined>;/*** OAuth protected-resource metadata attached to an inbound auth policy.@@ -702,7 +711,7 @@ function collectDeclaredChallenges(export async function routeAuth(request: Request,auth: AuthFn<Request> | readonly AuthFn<Request>[],-): Promise<SessionAuthContext | Response> {+): Promise<AuthResult | Response> {const list: readonly AuthFn<Request>[] = Array.isArray(auth)? (auth as readonly AuthFn<Request>[]): [auth as AuthFn<Request>];@@ -861,7 +870,7 @@ const LOCAL_DEV_SESSION_AUTH_CONTEXT: SessionAuthContext = {const VERCEL_OIDC_AUDIENCE_PREFIX = "https://vercel.com/";/**- * Options for {@link verifyVercelOidc} and {@link vercelOidc}.+ * Options for verifying a Vercel OIDC token with {@link verifyVercelOidc}.*/export interface VerifyVercelOidcOptions {/**@@ -1084,13 +1093,32 @@ function assertVercelSubjectSegment(field: "teamSlug" | "projectName", value: st}}+export interface VercelOidcOptions extends Omit<VerifyVercelOidcOptions, "subjects"> {+ /**+ * Additional token subjects allowed to authenticate.+ * To allow stubs, use { subject, allowToolStubs: true } for that subject.+ */+ readonly subjects?: readonly (+ | string+ | {+ readonly subject: string;+ readonly allowToolStubs?: boolean;+ }+ )[];+}+/*** Returns an HTTP route auth callback backed by Vercel OIDC. See* {@link verifyVercelOidc} for the always-on current-project bypass and how* `subjects` extends acceptance to other Vercel projects. Declares a* `Bearer` {@link withAuthChallenges} challenge for {@link routeAuth}'s 401.*/-export function vercelOidc(opts: VerifyVercelOidcOptions = {}): AuthFn<Request> {+export function vercelOidc(opts: VercelOidcOptions = {}): AuthFn<Request> {+ const { subjects, ...verification } = opts;+ const verifyOptions = {+ ...verification,+ subjects: subjects?.map((entry) => (typeof entry === "string" ? entry : entry.subject)),+ };return withAuthChallenges(async (request) => {const token = extractBearerToken(request.headers.get("authorization"));@@ -1101,9 +1129,21 @@ export function vercelOidc(opts: VerifyVercelOidcOptions = {}): AuthFn<Request>: undefined);const result = await verifyVercelOidc(token,- currentVercelProject === undefined ? opts : { ...opts, currentVercelProject },+ currentVercelProject === undefined+ ? verifyOptions+ : { ...verifyOptions, currentVercelProject },);- return result.ok ? result.sessionAuth : null;+ if (!result.ok) return null;+ const auth = result.sessionAuth;+ const allowed =+ (auth.principalType === "service" || auth.principalType === "runtime") &&+ subjects?.some(+ (entry) =>+ typeof entry !== "string" &&+ entry.allowToolStubs === true &&+ areTokenClaimMatchersSatisfied({ sub: auth.subject }, { subjects: [entry.subject] }),+ );+ return allowed ? { ...auth, allowToolStubs: true } : auth;},[{ scheme: "Bearer" }],);diff --git a/packages/eve/src/public/channels/mcp.test.ts b/packages/eve/src/public/channels/mcp.test.tsindex 513b5f08b..597128632 100644--- a/packages/eve/src/public/channels/mcp.test.ts+++ b/packages/eve/src/public/channels/mcp.test.ts@@ -703,7 +703,9 @@ describe("mcpChannel tools", () => {// Unpadded base64url of 12,288 bytes is exactly the 16 KiB cap; JSON whitespace pads it.const sized = (bytes: number) => encode(json + " ".repeat(bytes - Buffer.byteLength(json)));const trusted = {- trustedForwarders: (forwarder: SessionAuthContext) => forwarder === principal,+ trustedForwarders: (forwarder: SessionAuthContext) =>+ forwarder.authenticator === principal.authenticator &&+ forwarder.principalId === principal.principalId,};const forwardedAlice = {...alice,@@ -720,7 +722,11 @@ describe("mcpChannel tools", () => {describe: async () => ({ name: "compiled-agent", skills: [], tools: [note] }),invokeTool: overrides.invokeTool,});- const route = mcpChannel({ auth: () => principal, tools: true, ...options }).routes[1]!;+ const route = mcpChannel({+ auth: () => ({ ...principal, allowToolStubs: true }),+ tools: true,+ ...options,+ }).routes[1]!;if (route.transport === "websocket") throw new Error("expected HTTP route");const params = { arguments: tool === "agent_start" ? { message: "hi" } : {}, name: tool };const body = { id: 1, jsonrpc: "2.0", method: "tools/call", params };@@ -783,7 +789,7 @@ describe("mcpChannel tools", () => {throw new Error("stop after createSession");});await post(trusted, valid, "agent_start", { createSession: createSession as never });- expect(createSession.mock.calls[0]![0]).toMatchObject({ auth: principal });+ expect((createSession.mock.calls[0]![0] as { auth: unknown }).auth).toEqual(principal);});it("advertises tool sessions and honours a key only from clients that declare them", async () => {diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.tsindex 856b563ef..24a6681a7 100644--- a/packages/eve/src/public/channels/mcp.ts+++ b/packages/eve/src/public/channels/mcp.ts@@ -1,3 +1,4 @@+import { sessionAuthFromResult } from "#channel/auth/result.js";import { parseJsonObject } from "#shared/json.js";import { z } from "#compiled/zod/index.js";import {@@ -381,9 +382,14 @@ async function authenticateMcpRequest(if (auth instanceof Response) {return oauth === undefined ? auth : addResourceChallenge(auth, request, oauth);}- const principals = await resolveMcpRequestPrincipals(request, auth, input.trustedForwarders);+ const sessionAuth = sessionAuthFromResult(auth);+ const principals = await resolveMcpRequestPrincipals(+ request,+ sessionAuth,+ input.trustedForwarders,+ );if (principals instanceof Response) return principals;- return await handleMcpRequest(request, args, auth, principals, publish);+ return await handleMcpRequest(request, args, sessionAuth, principals, publish);}interface McpPublishOptions {diff --git a/packages/eve/src/tool-stubs/validate-targets.integration.test.ts b/packages/eve/src/tool-stubs/validate-targets.integration.test.tsnew file mode 100644index 000000000..5008419a5--- /dev/null+++ b/packages/eve/src/tool-stubs/validate-targets.integration.test.ts@@ -0,0 +1,61 @@+import { expect, it, vi } from "vitest";+import { createTestRuntime } from "#internal/testing/app-harness.js";+import { defineTool } from "#tools/definition.js";+import { defineDynamic } from "#dynamic/definition.js";+import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+import { validateToolStubTargets } from "#tool-stubs/validate-targets.js";++it.each([false, true])(+ "checks paths without resolving dynamic tools (dynamic: %s)",+ async (dynamic) => {+ const resolve = vi.fn(() => ({}));+ const lookup = defineTool({+ description: "List tasks.",+ inputSchema: { type: "object" },+ execute: () => [],+ });+ const runtime = await createTestRuntime({+ modules: [+ { logicalPath: "tools/list_tasks.ts", loadNamespace: async () => ({ default: lookup }) },+ {+ logicalPath: "connections/tasks.ts",+ loadNamespace: async () => ({+ default: defineMcpClientConnection({+ url: "https://tasks.invalid/mcp",+ description: "Tasks.",+ }),+ }),+ },+ ...(dynamic+ ? [+ {+ logicalPath: "tools/dynamic.ts",+ loadNamespace: async () => ({+ default: defineDynamic({ events: { "session.started": resolve } }),+ }),+ },+ ]+ : []),+ ],+ });+ await runtime.run(async () => {+ const { graph } = await getCompiledRuntimeAgentBundle({+ compiledArtifactsSource: { kind: "bundled" },+ });+ const check = (tool: string) =>+ validateToolStubTargets([{ id: "rule", tool, outcome: { response: [] } }], graph);+ for (const tool of ["list_tasks", "agent/list_tasks", "tasks__list"]) {+ expect(() => check(tool), tool).not.toThrow();+ }+ for (const tool of ["lsit_tasks", "absent__list"]) {+ if (dynamic) expect(() => check(tool), tool).not.toThrow();+ else expect(() => check(tool), tool).toThrow(/unknown or unsupported tool path/);+ }+ for (const tool of ["unknown/list_tasks", "list_tasks/nested", "agent//list_tasks"]) {+ expect(() => check(tool), tool).toThrow(/unknown or unsupported tool path/);+ }+ expect(resolve).not.toHaveBeenCalled();+ });+ },+);diff --git a/packages/eve/src/tool-stubs/validate-targets.ts b/packages/eve/src/tool-stubs/validate-targets.tsnew file mode 100644index 000000000..be3360cbc--- /dev/null+++ b/packages/eve/src/tool-stubs/validate-targets.ts@@ -0,0 +1,54 @@+import type { ResolvedAgentGraphBundle } from "#runtime/graph.js";+import type { ToolStub } from "#tool-stubs/types.js";++export class InvalidToolStubTargetError extends Error {}++/** Check compiled tools without running dynamic resolvers or contacting connections. */+export function validateToolStubTargets(+ rules: readonly ToolStub[],+ graph: ResolvedAgentGraphBundle,+): void {+ for (const rule of rules) {+ if (!hasToolPath(graph, rule.tool.split("/"))) {+ throw new InvalidToolStubTargetError(+ `Tool stub "${rule.id}" names an unknown or unsupported tool path "${rule.tool}".`,+ );+ }+ }+}++function hasToolPath(graph: ResolvedAgentGraphBundle, path: readonly string[]): boolean {+ if (path.some((part) => part.length === 0)) return false;+ let node = graph.root;+ for (const [index, name] of path.entries()) {+ const tool = node.turnAgent.tools.find((tool) => tool.name === name);+ if (index === path.length - 1) {+ if (tool !== undefined) return tool.behavior?.handling?.kind !== "provider-tool";+ return (+ // The reserved connection resolver only supplies the two framework wrappers.+ node.agent.dynamicToolResolvers.some(+ (resolver) =>+ resolver.slug !== "connection_tools" &&+ (resolver.extensionNamespace === undefined ||+ name.startsWith(`${resolver.extensionNamespace}__`)),+ ) ||+ node.subagentRegistry.dynamicResolvers.some((resolver) => resolver.name === name) ||+ (name.includes("__") &&+ ((node.agent.dynamicConnectionResolvers?.length ?? 0) > 0 ||+ node.agent.connections.some((connection) =>+ name.startsWith(`${connection.connectionName}__`),+ )))+ );+ }+ if (tool === undefined)+ return node.subagentRegistry.dynamicResolvers.some((resolver) => resolver.name === name);+ const handling = tool.behavior?.handling;+ if (+ handling?.kind !== "dispatch" ||+ (handling.target.kind !== "subagent-call" && handling.target.kind !== "self-agent-call")+ )+ return false;+ node = graph.nodesByNodeId.get(handling.target.nodeId)!;+ }+ return false;+}diff --git a/packages/eve/test/scenarios/nested-tool-stubs.scenario.test.ts b/packages/eve/test/scenarios/nested-tool-stubs.scenario.test.tsnew file mode 100644index 000000000..7f54a1dcb--- /dev/null+++ b/packages/eve/test/scenarios/nested-tool-stubs.scenario.test.ts@@ -0,0 +1,106 @@+import { expect, it } from "vitest";+import { Client } from "../../src/client/client.js";+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";+import { startEveDev } from "./dev-server-harness.js";++const scenarioApp = useScenarioApp();++it.each(["ordinary", "workflow"] as const)(+ "routes a nested child's %s tool to its full stub path through compiled HTTP",+ async (kind) => {+ const lookup = `import { ${kind === "workflow" ? "defineWorkflowTool" : "defineTool"} } from "eve/tools";+export default ${kind === "workflow" ? "defineWorkflowTool" : "defineTool"}({+ description: "Look up Alice's assigned tasks.",+ inputSchema: { type: "object", properties: {} },+ async execute() {+ ${kind === "workflow" ? '"use workflow";' : ""}+ throw new Error("The nested lookup must be stubbed.");+ },+});`;+ const app = await scenarioApp({+ name: `nested-${kind}-tool-stubs`,+ installDependencies: true,+ files: {+ "agent/instructions.md": "Help Alice look up assigned tasks.\n",+ "agent/subagents/researcher/instructions.md": "Delegate task lookup to your assistant.\n",+ "agent/subagents/researcher/subagents/assistant/instructions.md":+ "Look up Alice's tasks.\n",+ "agent/agent.ts": delegatingAgent("researcher"),+ "agent/tools/lookup.ts": lookup,+ "agent/subagents/remote.ts": `import { defineRemoteAgent } from "eve";+export default defineRemoteAgent({ url: "https://remote.invalid", description: "Remote tasks." });`,+ "agent/subagents/researcher/agent.ts": delegatingAgent("assistant"),+ "agent/subagents/researcher/tools/lookup.ts": lookup,+ "agent/subagents/researcher/subagents/assistant/agent.ts": delegatingAgent("lookup"),+ "agent/subagents/researcher/subagents/assistant/tools/lookup.ts": lookup,+ "agent/channels/eve.ts": `import { httpBasic } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";+const authenticate = httpBasic({ username: "alice", password: "fixture" });+export default eveChannel({+ auth: async request => {+ const auth = await authenticate(request);+ return auth ? { ...auth, allowToolStubs: true } : null;+ },+});`,+ },+ });+ const server = await startEveDev(app.appRoot, {+ env: { EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },+ });+ try {+ const client = new Client({+ host: server.url,+ auth: { basic: { username: "alice", password: "fixture" } },+ });+ for (const tool of ["assistant/lookup", "researcher/lookpu", "remote/lookup"]) {+ await expect(+ client.sessions.create({+ stubs: [{ id: "invalid", tool, outcome: { response: "INVALID" } }],+ }),+ ).rejects.toThrow(tool);+ }+ const { session } = await client.sessions.create({+ stubs: [+ { id: "root", tool: "lookup", outcome: { response: "ROOT" } },+ { id: "remote", tool: "remote", outcome: { response: "REMOTE" } },+ { id: "child", tool: "researcher/lookup", outcome: { response: "CHILD" } },+ {+ id: "grandchild",+ tool: "researcher/assistant/lookup",+ outcome: { response: "GRANDCHILD" },+ },+ ],+ });+ const result = await (await session.send("Look up Alice's assigned tasks.")).result();+ expect(+ result.events.flatMap((event) => (event.type === "task.settled" ? [event.data] : [])),+ ).toContainEqual(+ expect.objectContaining({ name: "researcher", status: "completed", output: "GRANDCHILD" }),+ );+ expect(result.events.filter((event) => event.type === "turn.failed")).toEqual([]);+ } finally {+ await server.stop();+ }+ },+ 360_000,+);++/** The mock models choose tools; eve creates the child sessions and runs their tools. */+function delegatingAgent(tool: "researcher" | "assistant" | "lookup"): string {+ return `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";+export default defineAgent({+ description: "Help Alice look up assigned tasks.",+ modelContextWindowTokens: 32000,+ model: mockModel(request => {+ const completed = request.messages.find(message => message.role === "user" && message.text.startsWith("<task_result"));+ if (completed) return completed.text.slice(completed.text.indexOf(">") + 1, completed.text.lastIndexOf("</task_result>"));+ const result = request.toolResults.find(result => result.name === ${JSON.stringify(tool)});+ if (result && ${tool !== "lookup"}) return { toolCalls: [{ name: "task_wait", input: {} }] };+ if (result) return typeof result.output === "string" ? result.output : JSON.stringify(result.output);+ return { toolCalls: [{ name: ${JSON.stringify(tool)}, input: ${+ tool === "lookup" ? "{}" : '{ message: "Look up Alice\'s assigned tasks." }'+ } }] };+ }),+});`;+}diff --git a/packages/eve/test/scenarios/tool-stubs.scenario.test.ts b/packages/eve/test/scenarios/tool-stubs.scenario.test.tsnew file mode 100644index 000000000..9b970e82f--- /dev/null+++ b/packages/eve/test/scenarios/tool-stubs.scenario.test.ts@@ -0,0 +1,138 @@+import { expect, it } from "vitest";+import { Client } from "../../src/client/client.js";+import type { MessageStreamEvent } from "../../src/protocol/message.js";+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";+import { startEveDev } from "./dev-server-harness.js";++const scenarioApp = useScenarioApp();++it("separates stub creation permission from session access through compiled HTTP", async () => {+ const app = await scenarioApp({+ name: "declarative-tool-stubs",+ installDependencies: true,+ files: {+ "agent/instructions.md": "Help Alice deploy services.\n",+ "agent/agent.ts": `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";+export default defineAgent({+ modelContextWindowTokens: 32000,+ model: mockModel(request => {+ const roles = request.messages.map(message => message.role);+ if (roles.lastIndexOf("tool") > roles.lastIndexOf("user")) return "Done";+ return { toolCalls: [{ name: "deploy", input: {+ service: request.lastUserMessage?.includes("web") ? "web" : "api", note: "Alice approved",+ } }] };+ }),+});`,+ "agent/tools/deploy.ts": `import { defineTool } from "eve/tools";+export default defineTool({+ description: "Deploy a service.",+ inputSchema: { type: "object", properties: { service: { type: "string" }, note: { type: "string" } }, required: ["service"] },+ execute: () => "live",+});`,+ "agent/channels/eve.ts": `import { httpBasic } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";+export default eveChannel({+ auth: [httpBasic({ username: "alice", password: "fixture" }), httpBasic({ username: "bob", password: "fixture" })].map(authenticate => async request => {+ const auth = await authenticate(request);+ return auth ? { ...auth, allowToolStubs: auth.principalId === "alice" } : null;+ }),+});`,+ },+ });+ const server = await startEveDev(app.appRoot, {+ env: { EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },+ });+ try {+ const alice = new Client({+ host: server.url,+ auth: { basic: { username: "alice", password: "fixture" } },+ });+ const bob = new Client({+ host: server.url,+ auth: { basic: { username: "bob", password: "fixture" } },+ });+ const stubs = [+ {+ id: "deploy",+ tool: "deploy",+ match: { service: { const: "api" } },+ outcomes: [{ response: "pending" }, { response: "completed" }] as const,+ },+ ];+ for (const tool of ["deply", "unknown/deploy", "deploy/child"]) {+ const invalid = await alice.fetch("/eve/v1/session", {+ method: "POST",+ body: JSON.stringify({ stubs: [{ id: "typo", tool, outcome: { response: "fake" } }] }),+ });+ expect(invalid.status).toBe(400);+ expect(await invalid.json()).toMatchObject({ error: expect.stringContaining(tool) });+ }+ const { session } = await alice.sessions.create({ stubs });+ const path = `/eve/v1/session/${session.state.sessionId}`;+ const forbidden = await bob.fetch("/eve/v1/session", {+ method: "POST",+ body: JSON.stringify({ stubs }),+ });+ expect(forbidden.status).toBe(403);++ const first = await (await session.send("Alice asks to deploy api.")).result();+ expect(results(first.events)).toEqual(["pending"]);+ const shared = bob.sessions.attach(session.state.sessionId, {+ streamIndex: session.state.streamIndex,+ });+ const next = await (await shared.send("Bob asks for another api deployment.")).result();+ expect(results(next.events)).toEqual(["completed"]);+ const exhausted = await (await shared.send("Bob asks for one more api deployment.")).result();+ expect(results(exhausted.events)).toEqual(["completed"]);+ const live = await (await shared.send("Bob asks to deploy web.")).result();+ expect(results(live.events)).toEqual(["live"]);+ expect((await bob.fetch(path + "/stubs")).status).toBe(403);+ const status = await alice.fetch(path + "/stubs");+ expect(status.status).toBe(200);+ expect(await status.json()).toEqual({ error: null, matchedRuleIds: ["deploy"] });+ const replacement = await bob.fetch(path, {+ method: "POST",+ body: JSON.stringify({ message: "Next", stubs }),+ });+ expect(replacement.status).toBe(400);++ const invalid = await alice.fetch("/eve/v1/session", {+ method: "POST",+ body: JSON.stringify({+ stubs: [+ {+ id: "bad",+ tool: "deploy",+ match: { service: { type: "strng" } },+ outcome: { response: null },+ },+ ],+ }),+ });+ expect(invalid.status).toBe(400);+ const { session: overlapping } = await alice.sessions.create({+ stubs: [+ { id: "a", tool: "deploy", outcome: { response: "a" } },+ { id: "b", tool: "deploy", outcome: { response: "b" } },+ ],+ });+ const selected = await (await overlapping.send("Alice asks to deploy api.")).result();+ expect(results(selected.events)).toEqual(["a"]);+ const failure = await alice.fetch(`/eve/v1/session/${overlapping.state.sessionId}/stubs`);+ expect(failure.status).toBe(200);+ expect(await failure.json()).toEqual({ error: null, matchedRuleIds: ["a"] });+ } finally {+ await server.stop();+ }+}, 360_000);++function results(events: readonly MessageStreamEvent[]): unknown[] {+ return events.flatMap((event) =>+ event.type === "action.result" &&+ event.data.result.kind === "tool-result" &&+ event.data.result.toolName === "deploy"+ ? [event.data.result.output]+ : [],+ );+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3dd43445c..c1efba4e9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1339,6 +1339,28 @@ importers:specifier: 'catalog:'version: 7.0.2+ e2e/fixtures/agent-tool-stubs:+ dependencies:+ '@eve-e2e/config':+ specifier: workspace:*+ version: link:../e2e-config+ '@workflow/world-postgres':+ specifier: 'catalog:'+ version: 5.0.2(@opentelemetry/[email protected])(@types/[email protected])(@upstash/[email protected])([email protected])([email protected])([email protected])+ eve:+ specifier: workspace:*+ version: link:../../../packages/eve+ zod:+ specifier: 'catalog:'+ version: 4.5.4+ devDependencies:+ '@types/node':+ specifier: 'catalog:'+ version: 24.13.3+ typescript:+ specifier: 'catalog:'+ version: 7.0.2+e2e/fixtures/agent-tools:dependencies:'@eve-e2e/config':