The Open Framework for Building Agents
AX-4930: Allow tool stubs to throw errors and recover on retry (#4528)
Philipp Comans1cfb21298b5e
diff --git a/.changeset/tool-stub-errors.md b/.changeset/tool-stub-errors.mdnew file mode 100644index 000000000..5b216cf4a--- /dev/null+++ b/.changeset/tool-stub-errors.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Tool stubs can now throw an error immediately or mix errors and responses in an outcome sequence. Evals can assert expected tool failures and recovery without treating injected errors as broken stubs.diff --git a/docs/evals/tool-stubs.mdx b/docs/evals/tool-stubs.mdxindex 7438e633f..f01f35d16 100644--- a/docs/evals/tool-stubs.mdx+++ b/docs/evals/tool-stubs.mdx@@ -77,7 +77,7 @@ These responses describe a sequence, not a simulated task database. The second `| `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.+Each outcome contains exactly one of `response` or `throw`. `response` holds the JSON returned by the tool; `throw` describes an error raised immediately instead. 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).@@ -109,7 +109,7 @@ const stubs = [];```-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.+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 broken stub or failure processing its response fails the eval, even if the agent recovers. An intentional `throw` outcome is a normal tool failure that the eval can assert on. Neither 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.@@ -217,12 +217,11 @@ Connection authentication and discovery stay live so eve can validate the operatTools 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+## Inject tool errors-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:+Use `throw` to test how the agent handles a failed tool call. Mix errors and responses to test recovery:```ts-// Planned API; throw outcomes are not accepted yet.const stubs = [{id: "tasks",@@ -235,4 +234,24 @@ const stubs = [];```-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.+`throw.message` is required. `throw.name` is optional and defaults to `"Error"`. eve creates an ordinary JavaScript `Error` with that name and message; it does not instantiate custom error classes. `TimeoutError` reports a timeout immediately, without delaying the call or testing an actual deadline.++Ordinary tools and connection operations expose the error message to the model, without the error name. Workflow task errors also retain the name. Put any details the model needs to act on in `message`.++Use `outcome: { throw: { message: "Service unavailable" } }` to fail every matching call. A sequence consumes one entry per new call, whether it returns or throws, and repeats its final entry. Workflow replay reuses the same recorded outcome.++An injected exception follows the tool's normal error handling. Ordinary and blocking workflow calls are recorded as failed; background tasks report failure when they settle. The model can report the failure or try again. Assert the failed call explicitly:++```ts+const turn = await session.send(+ "List my tasks once. If the service fails, explain the failure and wait for me to retry.",+);+turn.expectOk();+turn.calledTool("list_tasks", { status: "failed", count: 1 });+```++The eval can pass when the agent handles the failure correctly. `noFailedActions()` still rejects the failed call, so use explicit assertions for expected failures. Stub infrastructure and response-processing failures still fail verification.++This works for ordinary tools, workflow tools, whole-agent replacements, and qualified connection operations. An exception in a persistent workflow tool ends that task; retry with a new call, rather than its failed task ID. Normal approvals apply before an outcome is consumed.++Returning `{ response: { error: "timeout" } }` remains ordinary JSON. Only `throw` raises an exception.diff --git a/e2e/fixtures/agent-tool-stubs/README.md b/e2e/fixtures/agent-tool-stubs/README.mdindex e00892d4e..d0755ba70 100644--- a/e2e/fixtures/agent-tool-stubs/README.md+++ b/e2e/fixtures/agent-tool-stubs/README.md@@ -3,7 +3,10 @@This fixture runs consumer evals with every real model in the `e2e-local`matrix (`modelMatrix: full`). The tasks journey uses a semantic judge todistinguish acknowledging a completed task from listing it as still open;-it carries the `real-model` tag. Matching and cross-turn playback also run+it carries the `real-model` tag. The error-recovery eval also carries that tag:+one ordinary lookup request must lead the model to recover from a tool timeout+and return the record marker, without instructions to retry or a follow-up prompt.+Matching and cross-turn playback also runwith the shared scripted responder in the Postgres and Vercel world suites.A passing scripted world run is transport/durability evidence, not live-model evidence.@@ -14,6 +17,7 @@ A passing scripted world run is transport/durability evidence, not live-model ev| 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 |+| Recover from an injected timeout without a retry instruction | `evals/errors.eval.ts`: one user turn, failed call, successful retry, and recovered 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 |diff --git a/e2e/fixtures/agent-tool-stubs/evals/errors.eval.ts b/e2e/fixtures/agent-tool-stubs/evals/errors.eval.tsnew file mode 100644index 000000000..e6092b090--- /dev/null+++ b/e2e/fixtures/agent-tool-stubs/evals/errors.eval.ts@@ -0,0 +1,33 @@+import { defineEval } from "eve/evals";++export default defineEval({+ tags: ["real-model"],+ description: "The agent recovers from an injected lookup timeout without a follow-up prompt.",+ async test(t) {+ const session = await t.session({+ stubs: [+ {+ id: "lookup",+ tool: "lookup_record",+ outcomes: [+ { throw: { name: "TimeoutError", message: "Record service timed out" } },+ { response: { marker: "RECOVERED-RECORD" } },+ ],+ },+ ],+ });+ const input = { filter: { status: "open", owner: "alice" }, query: "milk", tags: [], limit: 1 };+ const turn = await session.send(+ `Alice asks: what is the marker for my open milk record? Lookup input: ${JSON.stringify(input)}`,+ );+ turn.expectOk();+ turn.calledTool("lookup_record", { input, status: "failed", count: 1 });+ turn.calledTool("lookup_record", {+ input,+ status: "completed",+ output: { marker: "RECOVERED-RECORD" },+ count: 1,+ });+ turn.messageIncludes("RECOVERED-RECORD");+ },+});diff --git a/packages/eve/src/client/tool-stubs.test.ts b/packages/eve/src/client/tool-stubs.test.tsindex 533787625..60efb5f32 100644--- a/packages/eve/src/client/tool-stubs.test.ts+++ b/packages/eve/src/client/tool-stubs.test.ts@@ -19,7 +19,10 @@ it.each([undefined, "Complete the milk task."])(id: "milk",tool: "complete_task",match: { task_id: { const: "milk" } },- outcomes: [{ response: { success: true } }, { response: { success: false } }],+ outcomes: [+ { throw: { name: "TimeoutError", message: "Service timed out" } },+ { response: { success: true } },+ ],},] satisfies ToolStub[];if (message === undefined) {@@ -34,7 +37,10 @@ it.each([undefined, "Complete the milk task."])(id: "milk",tool: "complete_task",match: { task_id: { const: "milk" } },- outcomes: [{ response: { success: true } }, { response: { success: false } }],+ outcomes: [+ { throw: { name: "TimeoutError", message: "Service timed out" } },+ { response: { success: true } },+ ],},],};diff --git a/packages/eve/src/evals/tool-stubs.integration.test.ts b/packages/eve/src/evals/tool-stubs.integration.test.tsindex f61f6d3e0..7507b57bd 100644--- a/packages/eve/src/evals/tool-stubs.integration.test.ts+++ b/packages/eve/src/evals/tool-stubs.integration.test.ts@@ -18,8 +18,8 @@ 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",+it.each(["output processing", "failure reporting", "injected error"])(+ "verifies an eval with a failure in %s",async (failure) => {const runtime = await createTestRuntime({modules: [@@ -125,11 +125,27 @@ it.each(["output processing", "failure reporting"])(id: "bad-task-output",async test(t) {const session = await t.session({- stubs: [{ id: "deploy", tool: "deploy_service", outcome: { response: "stubbed" } }],+ stubs: [+ {+ id: "deploy",+ tool: "deploy_service",+ outcome:+ failure === "injected error"+ ? { throw: { message: "Service unavailable" } }+ : { response: "stubbed" },+ },+ ],});const turn = await session.send('Run deploy_service with service "api"');turn.expectOk();turn.calledTool("deploy_service", { count: 1 });+ if (failure === "injected error") {+ turn.eventsSatisfy("the background task failed", (events) =>+ events.some(+ (event) => event.type === "task.settled" && event.data.status === "failed",+ ),+ );+ }if (failure === "failure reporting") {await reportStubFailureStep({ token: "unavailable-playback", rootSessionId: run!.runId, rules: [] },@@ -142,7 +158,11 @@ it.each(["output processing", "failure reporting"])(});expect(outcome.result.status).toBe("waiting");expect(outcome.assertions.length).toBeGreaterThan(0);- expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);+ expect(outcome.assertions.filter((assertion) => !assertion.passed)).toEqual([]);+ if (failure === "injected error") {+ expect(outcome.error).toBeUndefined();+ return;+ }expect(outcome.error).toContain(failure === "output processing"? 'Stubbed tool "deploy_service" failed during output processing.'diff --git a/packages/eve/src/execution/tool-stubs/connection.integration.test.ts b/packages/eve/src/execution/tool-stubs/connection.integration.test.tsindex f40160574..e163dbe07 100644--- a/packages/eve/src/execution/tool-stubs/connection.integration.test.ts+++ b/packages/eve/src/execution/tool-stubs/connection.integration.test.ts@@ -9,6 +9,12 @@ import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { getWorld, start } from "#internal/workflow/runtime.js";import { workflowEntry } from "#execution/session/entry.js";import { resolveConnectionTools } from "#execution/tools/connection-tools.js";+import { calledTool } from "#evals/assertions/run.js";+import { deriveRunFacts } from "#evals/runner/derive-run-facts.js";+import type { EveEvalTaskResult } from "#evals/types.js";+import { emitNestedToolActions } from "#harness/nested-actions.js";+import { stampTestEvents } from "#internal/testing/events.js";+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { recordToolStubFailure } from "#tool-stubs/execute.js";import { readStubFailure } from "#execution/tool-stubs/steps.js";import { STUB_CONTEXT_KEY, STUB_FAILURE_NAMESPACE, type ToolStub } from "#tool-stubs/types.js";@@ -16,7 +22,7 @@ import type { ConnectionClient } from "#shared/connection-types.js";import type { ToolContext } from "#tools/definition.js";describe("connection operation stubs", () => {- it("validates input before replacing a child-scoped connection operation and leaves unmatched calls live", async () => {+ it("reports child-scoped failures and recovery, validates input, and executes unmatched calls", async () => {let liveCalls = 0;const runtime = await createTestRuntime();await runtime.run(async () => {@@ -25,7 +31,11 @@ describe("connection operation stubs", () => {id: "open",tool: "researcher/linear__list_issues",match: { status: { const: "open" } },- outcome: { response: { issues: ["milk"] } },+ outcomes: [+ { throw: { name: "TimeoutError", message: "Issue service timed out" } },+ { throw: { name: "ConnectionAuthorizationRequiredError", message: "Access denied" } },+ { response: { issues: ["milk"] } },+ ],},];const token = "connection-stub-playback";@@ -92,14 +102,76 @@ describe("connection operation stubs", () => {context.setVirtualContext(toolStubProvider.key, toolStubProvider.create(context)!.value);await contextStorage.run(context, async () => {const execute = resolveConnectionTools()!.connection_execute!.execute!;- const call = (callId: string, input: unknown) =>- execute({ connection: "linear", tool: "list_issues", input }, {- callId,- } as ToolContext);+ const events: UnstampedMessageStreamEvent[] = [];+ const call = async (callId: string, input: unknown) => {+ try {+ return await execute({ connection: "linear", tool: "list_issues", input }, {+ callId,+ } as ToolContext);+ } finally {+ await emitNestedToolActions(+ async (event) => {+ events.push(event);+ },+ { sequence: 0, stepIndex: 0, turnId: "turn-0" },+ callId,+ );+ }+ };+ const evalResult = (): EveEvalTaskResult => {+ const stamped = stampTestEvents(events);+ return {+ events: stamped,+ derived: deriveRunFacts(stamped),+ status: "completed",+ output: null,+ finalMessage: null,+ traceContexts: [],+ };+ };await expect(call("invalid", { status: 42 })).rejects.toThrow(/Invalid input/);+ await expect(call("failed", { status: "open" })).rejects.toMatchObject({+ name: "TimeoutError",+ message: "Issue service timed out",+ });+ expect(+ await calledTool("linear__list_issues", {+ status: "failed",+ input: { status: "open" },+ output: "Issue service timed out",+ count: 1,+ }).evaluate(evalResult()),+ ).toMatchObject({ score: 1 });+ expect(events[0]).toMatchObject({+ type: "actions.requested",+ data: {+ actions: [{ parentCallId: "failed", toolName: "linear__list_issues" }],+ },+ });+ expect(await readStubFailure(run.runId)).toBeUndefined();+ expect(liveCalls).toBe(0);+ await expect(call("auth-named-failure", { status: "open" })).rejects.toMatchObject({+ name: "ConnectionAuthorizationRequiredError",+ message: "Access denied",+ });+ expect(+ await calledTool("linear__list_issues", {+ status: "failed",+ output: "Access denied",+ count: 1,+ }).evaluate(evalResult()),+ ).toMatchObject({ score: 1 });expect(await call("stubbed", { status: "open", limit: 10 })).toEqual({issues: ["milk"],});+ expect(+ await calledTool("linear__list_issues", {+ status: "completed",+ input: { status: "open", limit: 10 },+ output: { issues: ["milk"] },+ count: 1,+ }).evaluate(evalResult()),+ ).toMatchObject({ score: 1 });expect(liveCalls).toBe(0);await call("live", { status: "closed" });expect(liveCalls).toBe(1);diff --git a/packages/eve/src/execution/tool-stubs/execution.integration.test.ts b/packages/eve/src/execution/tool-stubs/execution.integration.test.tsindex b32da0505..3b972debc 100644--- a/packages/eve/src/execution/tool-stubs/execution.integration.test.ts+++ b/packages/eve/src/execution/tool-stubs/execution.integration.test.ts@@ -96,6 +96,102 @@ describe("tool replacement through the session runtime", () => {},);+ it.each(["ordinary", "execute", "task", "serve"] as const)(+ "reports an injected %s failure and lets a new call succeed after handoff",+ async (entryPoint) => {+ const live = vi.fn(() => "live");+ const definition = {+ description: "Deploy a service.",+ inputSchema: {+ type: "object" as const,+ properties: { service: { type: "string" as const } },+ required: ["service"],+ },+ };+ const runtime = await createTestRuntime({+ modules: [+ {+ logicalPath: "tools/deploy_service.ts",+ loadNamespace: async () => {+ switch (entryPoint) {+ case "ordinary":+ return { default: defineTool({ ...definition, execute: live }) };+ case "execute":+ return {+ default: defineWorkflowTool({ ...definition, execute: failingDeployWorkflow }),+ };+ case "task":+ return {+ default: defineWorkflowTool({ ...definition, task: failingDeployWorkflow }),+ };+ case "serve":+ return {+ default: defineWorkflowTool({ ...definition, serve: failingServeWorkflow }),+ };+ }+ },+ },+ ],+ });+ await runtime.run(async () => {+ const message = 'Run deploy_service with service "api"';+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message },+ serializedContext: {+ ...buildSerializedContext({ channelKind: "http" }),+ [STUB_CONTEXT_KEY]: {+ token: "injected-error-playback",+ rules: [+ {+ id: "deploy",+ tool: "deploy_service",+ outcomes: [+ { throw: { name: "TimeoutError", message: "Deployment service timed out" } },+ { response: { state: "recovered" } },+ ],+ },+ ],+ },+ },+ },+ ]);+ const stream = captureTurnEvents(run);+ try {+ const events = await stream.nextTurn();+ const failures =+ entryPoint === "task" || entryPoint === "serve"+ ? filterEventsByType(events, "task.settled").map((event) => event.data)+ : filterEventsByType(events, "action.result").map((event) => event.data);+ expect(failures).toContainEqual(expect.objectContaining({ status: "failed" }));+ expect(JSON.stringify(failures)).toContain("Deployment service timed out");+ expect(filterEventsByType(events, "turn.failed")).toEqual([]);+ expect(await readStubFailure(run.runId)).toBeUndefined();+ await dispatchWorkflowSessionCommand({+ sessionId: run.runId,+ command: handoffFollowUp("dpl_successor", message, "retry-after-injected-error"),+ });+ const retried = await stream.nextTurn();+ const results =+ entryPoint === "task" || entryPoint === "serve"+ ? filterEventsByType(retried, "task.settled").map((event) => event.data)+ : filterEventsByType(retried, "action.result").map((event) => event.data.result);+ expect(results).toContainEqual(+ expect.objectContaining({ output: { state: "recovered" } }),+ );+ expect(filterEventsByType(retried, "turn.failed")).toEqual([]);+ expect(live).not.toHaveBeenCalled();+ expect(await readStubFailure(run.runId)).toBeUndefined();+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ },+ );+it.each([false, true])("ends the active session when playback fails (handoff: %s)",async (handoff) => {diff --git a/packages/eve/src/execution/tool-stubs/playback.integration.test.ts b/packages/eve/src/execution/tool-stubs/playback.integration.test.tsindex 55e10932d..b38c737a5 100644--- a/packages/eve/src/execution/tool-stubs/playback.integration.test.ts+++ b/packages/eve/src/execution/tool-stubs/playback.integration.test.ts@@ -32,7 +32,7 @@ describe("durable tool stub playback", () => {{id: "list",tool: "list_tasks",- outcomes: [{ response: ["milk", "dog"] }, { response: ["dog"] }],+ outcomes: [{ throw: { message: "Task service unavailable" } }, { response: ["dog"] }],},] as const;const run = await start(workflowEntry, [diff --git a/packages/eve/src/execution/tools/connection-tools.ts b/packages/eve/src/execution/tools/connection-tools.tsindex 22e5b1b1d..6a02a5785 100644--- a/packages/eve/src/execution/tools/connection-tools.ts+++ b/packages/eve/src/execution/tools/connection-tools.ts@@ -1,4 +1,5 @@import { connectionToolStub } from "#tool-stubs/execute.js";+import { toolStubOutput } from "#tool-stubs/output.js";/*** `connection_search` and `connection_execute`: fixed tools that reach every* connection tool without adding definitions to the model's tool list, so@@ -371,18 +372,20 @@ async function executeConnectionTool(const toolName = qualifiedToolName(target);const stub = await connectionToolStub(toolName, input, ctx.callId);if (stub.kind === "error") throw new Error(stub.error);- if (stub.kind === "stub") {- reportNestedToolAction(ctx.callId, { input, output: stub.outcome.response, toolName });- return stub.outcome.response;- }let raw: unknown;try {+ if (stub.kind === "stub") {+ const output = toolStubOutput(stub.outcome);+ reportNestedToolAction(ctx.callId, { input, output, toolName });+ return output;+ }raw = await client.executeTool(tool.name, input, {abortSignal: ctx.abortSignal,callId: ctx.callId,});} catch (error) {- if (isConnectionAuthorizationRequiredError(error)) return await auth.handleError(error, scoped);+ if (stub.kind === "real" && isConnectionAuthorizationRequiredError(error))+ return await auth.handleError(error, scoped);reportNestedToolAction(ctx.callId, {input,isError: true,diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.tsindex 35fcdc69f..e66f6e5d3 100644--- a/packages/eve/src/execution/tools/workflow/body.ts+++ b/packages/eve/src/execution/tools/workflow/body.ts@@ -1,4 +1,5 @@import { findStubTarget, stubCallId } from "#tool-stubs/target.js";+import { toolStubOutput } from "#tool-stubs/output.js";import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";import { callToolStubStep } from "#execution/tool-stubs/steps.js";@@ -182,7 +183,8 @@ async function executeCallBody(input: input.input,});if (result.kind === "error") throw new Error(result.error);- if (result.kind === "stub") return { output: result.outcome.response, status: "completed" };+ if (result.kind === "stub")+ return { output: toolStubOutput(result.outcome), status: "completed" };}const entryPoint = resolveWorkflowEntryPoint<WorkflowCallEntryPoint>(input);const result = entryPoint(input.executeInput ?? input.input, ctx);diff --git a/packages/eve/src/execution/tools/workflow/serve.ts b/packages/eve/src/execution/tools/workflow/serve.tsindex dc95bcfd5..08e97d7af 100644--- a/packages/eve/src/execution/tools/workflow/serve.ts+++ b/packages/eve/src/execution/tools/workflow/serve.ts@@ -1,4 +1,5 @@import { findStubTarget, stubCallId } from "#tool-stubs/target.js";+import { toolStubOutput } from "#tool-stubs/output.js";import type { StubScope } from "#tool-stubs/types.js";import type { SessionContext } from "#context/session-context.js";import { callToolStubStep } from "#execution/tool-stubs/steps.js";@@ -458,6 +459,6 @@ async function serveStub(throw new Error(result.kind === "error" ? result.error : "Persistent stub configuration changed.",);- ctx.reply(result.outcome.response);+ ctx.reply(toolStubOutput(result.outcome));}}diff --git a/packages/eve/src/tool-stubs/execute.ts b/packages/eve/src/tool-stubs/execute.tsindex c631c871a..362ba2613 100644--- a/packages/eve/src/tool-stubs/execute.ts+++ b/packages/eve/src/tool-stubs/execute.ts@@ -1,4 +1,5 @@import { findStubTarget, stubCallId } from "#tool-stubs/target.js";+import { toolStubOutput } from "#tool-stubs/output.js";import { contextStorage } from "#context/container.js";import { SessionKey, ToolStubsKey } from "#context/keys.js";import { ToolStubPlaybackKey, type ToolStubPlayback } from "#context/providers/tool-stubs-key.js";@@ -28,7 +29,7 @@ async function* executeStubbedTool(const result = await playback.call(call);if (result.kind === "error") throw new Error(result.error);if (result.kind === "stub") {- yield result.outcome.response;+ yield toolStubOutput(result.outcome);return;}const output = await execute();diff --git a/packages/eve/src/tool-stubs/output.ts b/packages/eve/src/tool-stubs/output.tsnew file mode 100644index 000000000..62d839d3e--- /dev/null+++ b/packages/eve/src/tool-stubs/output.ts@@ -0,0 +1,12 @@+import type { JsonValue } from "#shared/json.js";+import type { ToolStubOutcome } from "#tool-stubs/types.js";++/** Throws at the tool boundary, after the outcome has been recorded for replay. */+export function toolStubOutput(outcome: ToolStubOutcome): JsonValue {+ if (outcome.throw !== undefined) {+ const error = new Error(outcome.throw.message);+ error.name = outcome.throw.name ?? "Error";+ throw error;+ }+ return outcome.response;+}diff --git a/packages/eve/src/tool-stubs/rules.test.ts b/packages/eve/src/tool-stubs/rules.test.tsindex ea730ea32..605bbfa3a 100644--- a/packages/eve/src/tool-stubs/rules.test.ts+++ b/packages/eve/src/tool-stubs/rules.test.ts@@ -196,11 +196,15 @@ describe("tool stubs", () => {[{ id: "a", tool: "list", outcome: {} }],[{ id: "a", tool: "list", outcome: { response: undefined } }],[{ id: "a", tool: "list", outcome: { response: null, extra: true } }],- [{ id: "a", tool: "list", outcome: { throw: { name: "Error", message: "Not yet" } } }],[{ id: "a", tool: "list", outcome: { response: null, throw: { message: "Not yet" } } }],+ [{ id: "a", tool: "list", outcome: { throw: {} } }],+ [{ id: "a", tool: "list", outcome: { throw: "Unavailable" } }],+ [{ id: "a", tool: "list", outcome: { throw: { message: 42 } } }],+ [{ id: "a", tool: "list", outcome: { throw: { message: "Unavailable", name: "" } } }],+ [{ id: "a", tool: "list", outcome: { throw: { message: "Unavailable", delayMs: 100 } } }],[{ id: "a", tool: "list", outcomes: [] }],[{ id: "a", tool: "list", outcomes: [{ response: null }, {}] }],- [{ id: "a", tool: "list", outcomes: [{ response: null }, { throw: { message: "Not yet" } }] }],+ [{ id: "a", tool: "list", outcomes: [{ response: null }, { throw: { message: false } }] }],[{ id: "a", tool: "list", outcome: { response: null }, outcomes: [{ response: null }] }],[{ id: "a", tool: "list", outcome: { response: null }, typo: true }],[{ id: "a", tool: "list", match: [], outcome: { response: null } }],@@ -225,7 +229,7 @@ describe("tool stubs", () => {expect(() => parseToolStubs(rules)).toThrow();});- it("normalizes absent options and preserves falsy JSON responses", () => {+ it("normalizes absent options and preserves response and error outcomes", () => {expect(parseToolStubs([{@@ -241,6 +245,15 @@ describe("tool stubs", () => {outcome: undefined,outcomes: [{ response: false }, { response: 0 }, { response: "" }, { response: null }],},+ { id: "failure", tool: "list", outcome: { throw: { message: "Unavailable" } } },+ {+ id: "recovery",+ tool: "list",+ outcomes: [+ { throw: { name: "TimeoutError", message: "Timed out" } },+ { response: { tasks: [] } },+ ],+ },]),).toEqual([{ id: "constant", tool: "list", outcome: { response: null } },@@ -249,6 +262,15 @@ describe("tool stubs", () => {tool: "list",outcomes: [{ response: false }, { response: 0 }, { response: "" }, { response: null }],},+ { id: "failure", tool: "list", outcome: { throw: { message: "Unavailable" } } },+ {+ id: "recovery",+ tool: "list",+ outcomes: [+ { throw: { name: "TimeoutError", message: "Timed out" } },+ { response: { tasks: [] } },+ ],+ },]);});diff --git a/packages/eve/src/tool-stubs/rules.ts b/packages/eve/src/tool-stubs/rules.tsindex 6ba74c379..3749a137a 100644--- a/packages/eve/src/tool-stubs/rules.ts+++ b/packages/eve/src/tool-stubs/rules.ts@@ -9,7 +9,12 @@ const ruleSchema = z.strictObject({match: z.record(z.string(), z.union([z.boolean(), z.record(z.string(), z.json())])).optional(),});-const outcomeSchema = z.strictObject({ response: z.json() });+const outcomeSchema = z.union([+ z.strictObject({ response: z.json() }),+ z.strictObject({+ throw: z.strictObject({ message: z.string(), name: z.string().min(1).optional() }),+ }),+]);const toolStubsSchema = z.array(diff --git a/packages/eve/src/tool-stubs/types.ts b/packages/eve/src/tool-stubs/types.tsindex ad06b60e6..dbd63b2c4 100644--- a/packages/eve/src/tool-stubs/types.ts+++ b/packages/eve/src/tool-stubs/types.ts@@ -1,9 +1,16 @@import type { JsonObject, JsonValue } from "#shared/json.js";-/** The JSON response returned for a matching tool call. */-export interface ToolStubOutcome {- readonly response: JsonValue;-}+/** Return JSON or immediately throw an error for a matching tool call. */+export type ToolStubOutcome =+ | { readonly response: JsonValue; readonly throw?: never }+ | {+ readonly response?: never;+ readonly throw: {+ readonly message: string;+ /** Defaults to Error. Sets the name, not a custom JavaScript class. */+ readonly name?: string;+ };+ };/** Stub outcomes selected by tool name and input fields. */export type ToolStub = {diff --git a/packages/eve/test/scenarios/tool-stubs.scenario.test.ts b/packages/eve/test/scenarios/tool-stubs.scenario.test.tsindex 9b970e82f..c373fc753 100644--- a/packages/eve/test/scenarios/tool-stubs.scenario.test.ts+++ b/packages/eve/test/scenarios/tool-stubs.scenario.test.ts@@ -91,6 +91,35 @@ export default eveChannel({const status = await alice.fetch(path + "/stubs");expect(status.status).toBe(200);expect(await status.json()).toEqual({ error: null, matchedRuleIds: ["deploy"] });+ const { session: recovery } = await alice.sessions.create({+ stubs: [+ {+ id: "retry",+ tool: "deploy",+ outcomes: [+ { throw: { name: "TimeoutError", message: "Deployment service timed out" } },+ { response: "recovered" },+ ],+ },+ ],+ });+ const failed = await (await recovery.send("Alice asks to deploy api.")).result();+ expect(failed.events).toContainEqual(+ expect.objectContaining({+ type: "action.result",+ data: expect.objectContaining({+ status: "failed",+ result: expect.objectContaining({+ toolName: "deploy",+ output: expect.stringContaining("Deployment service timed out"),+ }),+ }),+ }),+ );+ const retried = await (await recovery.send("Alice asks to deploy api again.")).result();+ expect(results(retried.events)).toEqual(["recovered"]);+ const verification = await alice.fetch(`/eve/v1/session/${recovery.state.sessionId}/stubs`);+ expect(await verification.json()).toEqual({ error: null, matchedRuleIds: ["retry"] });const replacement = await bob.fetch(path, {method: "POST",body: JSON.stringify({ message: "Next", stubs }),