Repository navigation
fix(ai): return tool failures to the model instead of ending the run #914
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Makisuo
merged 3 commits into
chore/effect-agent-beta-85
from
fix/ai-tool-failures-return-mode
Sep 17, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| /** | ||
| * What a failed tool call does to a whole run, through the real engine and a scripted model. | ||
| * | ||
| * The handler tests pin each tool's `failureMode`; this pins what the engine does with it. A rejected | ||
| * query must reach the model as a failed result it can rewrite, and a gated proposal must still end | ||
| * the run. | ||
| */ | ||
| import { OrgId, UserId } from "@maple/domain" | ||
| import { Effect, Exit, Layer, Schema, Stream } from "effect" | ||
| import { LanguageModel } from "effect/unstable/ai" | ||
| import type { Prompt, Response } from "effect/unstable/ai" | ||
| import * as AiModel from "effect/unstable/ai/Model" | ||
| import { assert, describe, it } from "vitest" | ||
| import type { TenantContext } from "@maple/backend/services/auth/tenant-context" | ||
| import type { McpToolExecutorApi } from "../mcp/dispatcher" | ||
| import type { ResolvedModel } from "../platform/Llm" | ||
| import type { ChatTurnEvent } from "./events" | ||
| import { runChatTurn } from "./run" | ||
| import { makeRunUsage } from "./tools" | ||
|
|
||
| const TENANT: TenantContext = { | ||
| orgId: Schema.decodeSync(OrgId)("org_test"), | ||
| userId: Schema.decodeSync(UserId)("user_test"), | ||
| roles: [], | ||
| authMode: "self_hosted", | ||
| } | ||
|
|
||
| const USAGE = { inputTokens: { total: 1, uncached: 1 }, outputTokens: { total: 1, text: 1 } } | ||
|
|
||
| const callTool = (name: string, params: unknown): ReadonlyArray<Response.StreamPartEncoded> => [ | ||
| { type: "tool-call", id: "call-1", name, params }, | ||
| { type: "finish", reason: "tool-calls", usage: USAGE }, | ||
| ] | ||
|
|
||
| const answer = (text: string): ReadonlyArray<Response.StreamPartEncoded> => [ | ||
| { type: "text-start", id: "text-1" }, | ||
| { type: "text-delta", id: "text-1", delta: text }, | ||
| { type: "text-end", id: "text-1" }, | ||
| { type: "finish", reason: "stop", usage: USAGE }, | ||
| ] | ||
|
|
||
| /** A model that plays `script` one response per call, recording every prompt it was sent. */ | ||
| const scriptedModel = (script: ReadonlyArray<ReadonlyArray<Response.StreamPartEncoded>>) => { | ||
| const prompts: Array<Prompt.Prompt> = [] | ||
| const respond = (options: LanguageModel.ProviderOptions) => { | ||
| prompts.push(options.prompt) | ||
| return script[prompts.length - 1] ?? answer("(script ran out)") | ||
| } | ||
| const model: ResolvedModel = { | ||
| provider: "openrouter", | ||
| name: "scripted", | ||
| limits: { context: 100_000, output: 4_000 }, | ||
| layer: AiModel.make( | ||
| "openrouter", | ||
| "scripted", | ||
| Layer.effect( | ||
| LanguageModel.LanguageModel, | ||
| LanguageModel.make({ | ||
| generateText: (options) => Effect.succeed([...respond(options)]), | ||
| streamText: (options) => Stream.suspend(() => Stream.fromIterable(respond(options))), | ||
| }), | ||
| ), | ||
| ), | ||
| } | ||
| return { model, prompts } | ||
| } | ||
|
|
||
| const run = (model: ResolvedModel, executor: McpToolExecutorApi) => { | ||
| const events: Array<ChatTurnEvent> = [] | ||
| const effect = runChatTurn({ | ||
| sessionId: "org_test:tab-1", | ||
| messageId: "msg-1", | ||
| tenant: TENANT, | ||
| toolExecutor: executor, | ||
| model, | ||
| submitDiagnosis: () => Effect.die("no investigation in a default session"), | ||
| text: "how many services?", | ||
| history: [], | ||
| usage: makeRunUsage(), | ||
| holdsTurn: () => true, | ||
| append: (event) => events.push(event), | ||
| }) | ||
| return { effect, events } | ||
| } | ||
|
|
||
| const rejectingExecutor: McpToolExecutorApi = { | ||
| execute: () => | ||
| Effect.succeed({ | ||
| isError: true, | ||
| content: [{ type: "text" as const, text: "SQL rejected (MissingOrgFilter)" }], | ||
| }), | ||
| } | ||
|
|
||
| describe("runChatTurn tool failures", () => { | ||
| it("hands a rejected query back to the model and finishes the run", async () => { | ||
| const { model, prompts } = scriptedModel([ | ||
| callTool("run_sql", { sql: "select 1" }), | ||
| answer("Rewrote it."), | ||
| ]) | ||
| const { effect, events } = run(model, rejectingExecutor) | ||
|
|
||
| const exit = await Effect.runPromiseExit(effect) | ||
|
|
||
| assert.isTrue(Exit.isSuccess(exit), `run failed: ${String(exit)}`) | ||
| assert.lengthOf(prompts, 2, "the model is called again after the failed tool") | ||
| const results = prompts[1]!.content.flatMap((message) => | ||
| message.role === "tool" ? message.content : [], | ||
| ) | ||
| assert.deepInclude( | ||
| results.map( | ||
| (part) => part.type === "tool-result" && { name: part.name, isFailure: part.isFailure }, | ||
| ), | ||
| { name: "run_sql", isFailure: true }, | ||
| ) | ||
| assert.deepInclude( | ||
| events.map( | ||
| (event) => event.type === "tool-result" && { output: event.output, isError: event.isError }, | ||
| ), | ||
| { output: "SQL rejected (MissingOrgFilter)", isError: true }, | ||
| ) | ||
| assert.deepEqual(events.at(-1), { type: "turn-end", messageId: "msg-1", reason: "stop" }) | ||
| }) | ||
|
|
||
| it("still ends the run on a gated proposal", async () => { | ||
| const { model, prompts } = scriptedModel([ | ||
| callTool("create_dashboard", { name: "Checkout" }), | ||
| answer("should never be asked"), | ||
| ]) | ||
| const { effect } = run(model, rejectingExecutor) | ||
|
|
||
| const exit = await Effect.runPromiseExit(effect) | ||
|
|
||
| assert.isTrue(Exit.isFailure(exit)) | ||
| assert.lengthOf(prompts, 1, "a proposal is the turn's last word") | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: MapleTechLabs/maple
Length of output: 47849
🏁 Script executed:
Repository: MapleTechLabs/maple
Length of output: 50376
🏁 Script executed:
Repository: MapleTechLabs/maple
Length of output: 50375
🏁 Script executed:
Repository: MapleTechLabs/maple
Length of output: 46628
🌐 Web query:
Effect TypeScript Effect.catchCause interruption semantics catchAllCause documentation💡 Result:
<search_synthesis>
In Effect TypeScript, Effect.catchCause (known as Effect.catchAllCause in v3) is a mechanism for handling the complete failure Cause, which includes typed failures, unexpected defects, and fiber interruptions [1][2]. Interruption Semantics and catchCause Interruption is represented within the Cause data type as an Interrupt reason, which contains the FiberId of the interrupted fiber [3][4][5]. When an Effect is interrupted, it produces a Cause that includes this interruption status [3][4]. Because Effect.catchCause allows you to inspect the entire Cause, it permits the handling of interruptions [1][3]. If you use this operator to recover from a failure, you are essentially intercepting the signal that would otherwise propagate the interruption [1][6]. Key Considerations 1. Naming: In modern Effect (v4+), the operator is named Effect.catchCause. It replaces the v3 name Effect.catchAllCause [2]. 2. Scope: Because it catches all possible causes (including interruptions and defects), it should be used with caution [1][7]. It is generally recommended to use typed recovery operators (like Effect.catch or Effect.catchTag) for domain-specific errors and reserve Effect.catchCause for application boundaries or intentional recovery from unexpected states [1][7]. 3. Handling Interruptions: When you catch a Cause containing an interruption, the fiber is technically "recovered" by your handler [1]. If you intend to propagate the interruption after performing some cleanup, you should re-fail with the original cause (e.g., using Effect.failCause(cause)) to ensure the runtime is aware that the fiber was meant to be interrupted [1][6]. 4. Inspection: You can use the Cause module&
#39;s guards, such as Cause.hasInterrupts or Cause.isInterruptReason, to specifically identify if an interruption has occurred within the caught Cause [3][4][5]. For detailed usage, refer to the Cause data type documentation, which explains how to inspect and pattern match on the various components of a failure, including interruptions [3][4][8].</search_synthesis>
<source_evidence>
Citations:
🏁 Script executed:
Repository: MapleTechLabs/maple
Length of output: 48306
🌐 Web query:
@effect-agent/engine 0.1.0-beta.85 failureMode return interruption ToolCallFailed source💡 Result:
<search_synthesis>
In the Effect AI ecosystem, the
failureMode: "return"configuration is designed to allow language models to receive and potentially correct tool execution errors by surfacing them as typed tool results rather than letting them propagate as fatal stream errors [1][2]. Regarding your query aboutfailureMode: "return"andToolCallFailed: 1. Role offailureMode: "return": When a tool is declared withfailureMode: "return", errors occurring during the tool's handler execution are captured and returned to the model as a tool result [2]. This allows the model to "see" the failure, enabling self-correction or alternative action paths without the entire runtime effect failing [1][3]. 2.ToolCallFailedand Parameter Validation: Historically, certain failures—specifically tool-call parameter decoding failures—could bypass thefailureModegate, causing a fatal error in thestreamTextstream even when"return"was configured [4][5]. However, subsequent updates (such as those addressed in PRs#6432and#7588) rectified this [6][5]. Now, parameter decode failures are routed through thefailureModelogic [6]. When configured with"return", these failures are caught and emitted as tool results (marked withisFailure: trueand including the encodedAiError), allowing the agent to handle the failure gracefully [6][5]. 3. Implementation: When using tools (such as MCP tools or customTool.makedeclarations),failureMode: "return"ensures that the tool'sfailureschema (or anAiError) is returned to the execution runtime as a tool output [3][2]. This prevents the "fatal error" path and enables the orchestration logic to treat the failed tool call as a piece of data to be interpreted by the model, rather than an unrecoverable system exception [1][5]. If you are encountering aToolCallFailedstate unexpectedly, ensure you are on a version of the Effect AI libraries that includes these fixes (specifically those post-dating the fixes for issues#6335and#7416) [4][6]. In current versions,failureMode: "return"should consistently route these errors back to the model as failed tool results [6].</search_synthesis>
<source_evidence>
Citations:
Preserve interruption when normalizing executor failures.
Effect.catchCausealso catches interruption causes fromexecutor.execute. A cancellation or timeout can becomeMapleToolFailure. Since ordinary tools usefailureMode: "return", the engine can return that failure to the model and continue the loop.Re-raise interruption-only causes with
Effect.failCause(cause). Normalize only typed failures and defects.🤖 Prompt for AI Agents