The Open Framework for Building Agents
fix(eve): harness - return failed tool results for tool errors (#489)
Andrew Barba0498252631dd
diff --git a/.changeset/tidy-tool-errors.md b/.changeset/tidy-tool-errors.mdnew file mode 100644index 000000000..044a0f299--- /dev/null+++ b/.changeset/tidy-tool-errors.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Tool execution failures now return failed tool results to the model instead of leaving streamed tool calls without matching result history. Agents can recover from failed calls such as a missing `load_skill` target within the same turn.diff --git a/packages/eve/src/harness/action-result-helpers.test.ts b/packages/eve/src/harness/action-result-helpers.test.tsindex 25507c5bd..ea9506008 100644--- a/packages/eve/src/harness/action-result-helpers.test.ts+++ b/packages/eve/src/harness/action-result-helpers.test.ts@@ -1,6 +1,9 @@import { describe, expect, it } from "vitest";-import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";+import {+ createRuntimeToolResultFromToolError,+ createRuntimeToolResultFromValue,+} from "#harness/action-result-helpers.js";describe("createRuntimeToolResultFromValue", () => {it("rejects non-JSON-serializable successful action results", () => {@@ -47,3 +50,23 @@ describe("createRuntimeToolResultFromValue", () => {});});});++describe("createRuntimeToolResultFromToolError", () => {+ it("projects AI SDK tool-error parts as failed action results", () => {+ expect(+ createRuntimeToolResultFromToolError({+ error: new Error('No skill named "demo"'),+ input: { skill: "demo" },+ toolCallId: "call_load_skill",+ toolName: "load_skill",+ type: "tool-error",+ }),+ ).toEqual({+ callId: "call_load_skill",+ isError: true,+ kind: "tool-result",+ output: 'No skill named "demo"',+ toolName: "load_skill",+ });+ });+});diff --git a/packages/eve/src/harness/action-result-helpers.ts b/packages/eve/src/harness/action-result-helpers.tsindex 38d727d0d..f2be49fe5 100644--- a/packages/eve/src/harness/action-result-helpers.ts+++ b/packages/eve/src/harness/action-result-helpers.ts@@ -1,6 +1,7 @@-import type { ModelMessage, ToolSet, TypedToolResult } from "ai";+import type { ModelMessage, ToolSet, TypedToolError, TypedToolResult } from "ai";import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";+import { toError } from "#shared/errors.js";import { parseJsonValue, type JsonValue } from "#shared/json.js";import {authorizationPendingAsJsonObject,@@ -85,6 +86,36 @@ export function createRuntimeToolResultFromStepResult(});}+/**+ * Builds a failed `RuntimeToolResultActionResult` from one AI SDK+ * `tool-error` part.+ */+export function createRuntimeToolResultFromToolError(+ toolError: TypedToolError<ToolSet>,+): RuntimeToolResultActionResult {+ return createRuntimeToolResultFromValue({+ callId: toolError.toolCallId,+ isError: true,+ output: toError(toolError.error),+ toolName: toolError.toolName,+ });+}++/**+ * Builds the inline tool-result message part that repairs model history after a+ * local tool execution error.+ */+export function createToolResultMessagePartFromToolError(+ toolError: TypedToolError<ToolSet>,+): ToolResultPart {+ return {+ type: "tool-result",+ toolCallId: toolError.toolCallId,+ toolName: toolError.toolName,+ output: { type: "error-text", value: toError(toolError.error).message },+ };+}+/*** Builds a `RuntimeToolResultActionResult` from one tool-result message* part as it appears on `step.response.messages`. Used as a fallback whendiff --git a/packages/eve/src/harness/emission.test.ts b/packages/eve/src/harness/emission.test.tsindex 61490f076..a8afe5440 100644--- a/packages/eve/src/harness/emission.test.ts+++ b/packages/eve/src/harness/emission.test.ts@@ -452,14 +452,19 @@ describe("emitStreamContent action requests", () => {const localEmit = createEmitStub();const providerEmit = createEmitStub();- await emitStreamContent(localEmit, EMISSION_STATE, streamOf(parts(false)), {- excludedActionToolNames: new Set(),- tools,- });- await emitStreamContent(providerEmit, EMISSION_STATE, streamOf(parts(true)), {+ const localResult = await emitStreamContent(localEmit, EMISSION_STATE, streamOf(parts(false)), {excludedActionToolNames: new Set(),tools,});+ const providerResult = await emitStreamContent(+ providerEmit,+ EMISSION_STATE,+ streamOf(parts(true)),+ {+ excludedActionToolNames: new Set(),+ tools,+ },+ );const localEvents = vi.mocked(localEmit).mock.calls.map(([event]) => event);const providerEvents = vi.mocked(providerEmit).mock.calls.map(([event]) => event);@@ -478,6 +483,15 @@ describe("emitStreamContent action requests", () => {},type: "action.result",});+ expect(localResult.trailingInlineToolResultParts).toEqual([+ {+ output: { type: "error-text", value: "Search failed" },+ toolCallId: "call-1",+ toolName: "web_search",+ type: "tool-result",+ },+ ]);+ expect(providerResult.trailingInlineToolResultParts).toEqual([]);});});diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.tsindex 8355cd282..18778023a 100644--- a/packages/eve/src/harness/emission.ts+++ b/packages/eve/src/harness/emission.ts@@ -36,7 +36,8 @@ import { toError } from "#shared/errors.js";import type { JsonObject } from "#shared/json.js";import {createRuntimeToolResultFromStepResult,- createRuntimeToolResultFromValue,+ createRuntimeToolResultFromToolError,+ createToolResultMessagePartFromToolError,} from "#harness/action-result-helpers.js";import {createRuntimeActionRequestFromToolCall,@@ -333,6 +334,7 @@ interface EmittedStreamContent {readonly handledInlineToolResultCallIds: ReadonlySet<string>;readonly inlineAuthorizationResults: readonly TypedToolResult<ToolSet>[];readonly inlineToolResultParts: readonly InlineToolResultPart[];+ readonly trailingInlineToolResultParts: readonly InlineToolResultPart[];}interface StreamActionEmissionOptions {@@ -366,6 +368,7 @@ export async function emitStreamContent(const handledInlineToolResultCallIds = new Set<string>();const inlineAuthorizationResults: TypedToolResult<ToolSet>[] = [];const inlineToolResultParts: InlineToolResultPart[] = [];+ const trailingInlineToolResultParts: InlineToolResultPart[] = [];const flushCurrentMessage = async (): Promise<void> => {if (currentMessage.length === 0) {@@ -590,24 +593,11 @@ export async function emitStreamContent(if (toolError.providerExecuted === true) {await collectProviderToolCall(toolError);await providerActionBatch.flush();- await emitActionResult(- createRuntimeToolResultFromValue({- callId: toolError.toolCallId,- isError: true,- output: toError(toolError.error),- toolName: toolError.toolName,- }),- );+ await emitActionResult(createRuntimeToolResultFromToolError(toolError));} else if (emittedActionCallIds.has(toolError.toolCallId)) {- await emitActionResult(- createRuntimeToolResultFromValue({- callId: toolError.toolCallId,- isError: true,- output: toError(toolError.error),- toolName: toolError.toolName,- }),- );+ await emitActionResult(createRuntimeToolResultFromToolError(toolError));handledInlineToolResultCallIds.add(toolError.toolCallId);+ trailingInlineToolResultParts.push(createToolResultMessagePartFromToolError(toolError));}break;}@@ -675,6 +665,7 @@ export async function emitStreamContent(handledInlineToolResultCallIds,inlineAuthorizationResults,inlineToolResultParts,+ trailingInlineToolResultParts,};}diff --git a/packages/eve/src/harness/step-hooks.ts b/packages/eve/src/harness/step-hooks.tsindex 176d90053..b117579dd 100644--- a/packages/eve/src/harness/step-hooks.ts+++ b/packages/eve/src/harness/step-hooks.ts@@ -15,6 +15,7 @@ import {createStepCompletedEvent,} from "#protocol/message.js";import {+ createRuntimeToolResultFromToolError,createRuntimeToolResultFromMessagePart,createRuntimeToolResultFromStepResult,} from "#harness/action-result-helpers.js";@@ -325,6 +326,18 @@ function reconcileToolResults(step: HarnessStepResult): readonly RuntimeToolResuresultsByCallId.set(toolResult.toolCallId, createRuntimeToolResultFromStepResult(toolResult));}+ for (const part of step.content ?? []) {+ if (part.type !== "tool-error" || part.providerExecuted === true) {+ continue;+ }++ if (resultsByCallId.has(part.toolCallId)) {+ continue;+ }++ resultsByCallId.set(part.toolCallId, createRuntimeToolResultFromToolError(part));+ }+for (const part of extractToolResultParts(step.response.messages)) {if ((part as { readonly providerExecuted?: boolean }).providerExecuted === true) {continue;diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex a204ef4fa..619a4e8e3 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -2379,6 +2379,146 @@ describe("createToolLoopHarness", () => {});});+ it("continues the tool loop when load_skill fails during local tool execution", async () => {+ setupMockAgent({+ content: [+ {+ input: { skill: "missing-demo-skill" },+ toolCallId: "call-load-skill",+ toolName: "load_skill",+ type: "tool-call",+ },+ ],+ finishReason: "tool-calls",+ fullStreamParts: [+ {+ input: { skill: "missing-demo-skill" },+ toolCallId: "call-load-skill",+ toolName: "load_skill",+ type: "tool-call",+ },+ {+ error: new Error(+ 'No skill named "missing-demo-skill" at /workspace/skills/missing-demo-skill/SKILL.md.',+ ),+ input: { skill: "missing-demo-skill" },+ toolCallId: "call-load-skill",+ toolName: "load_skill",+ type: "tool-error",+ },+ { finishReason: "tool-calls", type: "finish-step" },+ ],+ response: {+ messages: [+ {+ content: [+ {+ input: { skill: "missing-demo-skill" },+ toolCallId: "call-load-skill",+ toolName: "load_skill",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ ],+ },+ text: "",+ toolCalls: [+ {+ input: { skill: "missing-demo-skill" },+ toolCallId: "call-load-skill",+ toolName: "load_skill",+ type: "tool-call",+ },+ ],+ toolResults: [],+ });++ const { emit, events } = createEventCollector();+ const config = createTestConfig("conversation", emit, {+ tools: new Map([+ [+ "load_skill",+ {+ description: "Load a skill.",+ execute: vi.fn(),+ inputSchema: jsonSchema({ type: "object" }),+ name: "load_skill",+ },+ ],+ ]),+ });+ const session = createTestSession({+ agent: {+ modelReference: { id: "test-model" },+ system: "You are a test assistant.",+ tools: [+ {+ description: "Load a skill.",+ inputSchema: { type: "object" },+ name: "load_skill",+ },+ ],+ },+ });++ const result = await createToolLoopHarness(config)(session, {+ message: "Use the missing demo skill.",+ });++ expect(typeof result.next).toBe("function");+ expect(events.find((event) => event.type === "action.result")?.data).toEqual({+ error: {+ code: "ACTION_RESULT_FAILED",+ message:+ 'No skill named "missing-demo-skill" at /workspace/skills/missing-demo-skill/SKILL.md.',+ },+ result: {+ callId: "call-load-skill",+ isError: true,+ kind: "tool-result",+ output:+ 'No skill named "missing-demo-skill" at /workspace/skills/missing-demo-skill/SKILL.md.',+ toolName: "load_skill",+ },+ sequence: 0,+ stepIndex: 0,+ status: "failed",+ turnId: "turn_0",+ });+ expect(result.session.history.slice(-2)).toEqual([+ {+ content: [+ {+ input: { skill: "missing-demo-skill" },+ toolCallId: "call-load-skill",+ toolName: "load_skill",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ {+ content: [+ {+ output: {+ type: "error-text",+ value:+ 'No skill named "missing-demo-skill" at /workspace/skills/missing-demo-skill/SKILL.md.',+ },+ toolCallId: "call-load-skill",+ toolName: "load_skill",+ type: "tool-result",+ },+ ],+ role: "tool",+ },+ ]);+ expect(events.some((event) => event.type === "turn.failed")).toBe(false);+ expect(events.some((event) => event.type === "session.failed")).toBe(false);+ });+it("prefers toolResults over response messages when the stream omits the result", async () => {setupMockAgent({finishReason: "tool-calls",diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 923597db9..b08903b1a 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -753,6 +753,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {handledInlineToolResultCallIds,inlineAuthorizationResults,inlineToolResultParts,+ trailingInlineToolResultParts,} = await emitStreamContent(emit, emissionState, streamResult.fullStream, {excludedActionToolNames,tools: config.tools,@@ -761,7 +762,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {if (isEmptyModelResponse(stepResult) &&inlineToolResultParts.length === 0 &&- inlineAuthorizationResults.length === 0+ inlineAuthorizationResults.length === 0 &&+ trailingInlineToolResultParts.length === 0) {throw new EmptyModelResponseError();}@@ -771,7 +773,11 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {handledInlineToolResultCallIds,tools: advertisedHarnessTools,});- if (inlineToolResultParts.length > 0 || inlineAuthorizationResults.length > 0) {+ if (+ inlineToolResultParts.length > 0 ||+ inlineAuthorizationResults.length > 0 ||+ trailingInlineToolResultParts.length > 0+ ) {const existingToolResults = stepResult.toolResults as TypedToolResult<ToolSet>[];const toolResultsByCallId = new Map(existingToolResults.map((toolResult) => [toolResult.toolCallId, toolResult]),@@ -793,12 +799,13 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {finishReason: stepResult.finishReason,response: {...stepResult.response,- ...(inlineToolResultParts.length > 0+ ...(inlineToolResultParts.length > 0 || trailingInlineToolResultParts.length > 0? {- messages: [- { role: "tool" as const, content: [...inlineToolResultParts] },- ...stepResult.response.messages,- ],+ messages: insertInlineToolResultMessages({+ append: trailingInlineToolResultParts,+ prepend: inlineToolResultParts,+ responseMessages: stepResult.response.messages,+ }),}: {}),},@@ -1308,6 +1315,44 @@ async function runModelCallRecoveryPipeline(input: {return { outcome: "failed", error };}+type ToolResponsePart = Extract<ModelMessage, { role: "tool" }>["content"][number];+type ToolResultPart = Extract<ToolResponsePart, { type: "tool-result" }>;+type StepResponseMessage = HarnessStepResult["response"]["messages"][number];++function insertInlineToolResultMessages(input: {+ readonly append: readonly ToolResultPart[];+ readonly prepend: readonly ToolResultPart[];+ readonly responseMessages: readonly StepResponseMessage[];+}): StepResponseMessage[] {+ const existingCallIds = extractToolResultCallIds(input.responseMessages);+ const prepend = input.prepend.filter((part) => !existingCallIds.has(part.toolCallId));+ const append = input.append.filter((part) => !existingCallIds.has(part.toolCallId));++ return [+ ...(prepend.length > 0 ? [{ role: "tool" as const, content: [...prepend] }] : []),+ ...input.responseMessages,+ ...(append.length > 0 ? [{ role: "tool" as const, content: [...append] }] : []),+ ] satisfies StepResponseMessage[];+}++function extractToolResultCallIds(messages: readonly StepResponseMessage[]): ReadonlySet<string> {+ const callIds = new Set<string>();++ for (const message of messages) {+ if (message.role !== "tool" || !Array.isArray(message.content)) {+ continue;+ }++ for (const part of message.content) {+ if (part.type === "tool-result") {+ callIds.add(part.toolCallId);+ }+ }+ }++ return callIds;+}+/*** Inspects a model-call failure for the "tool type 'X' is not supported"* provider-attempt rejection that AI Gateway returns when a fallback