Tool-approval continuation: approved calls run before the first step, so onStepEnd checkpoints miss their results (crash, then resume re-executes the approved call)
Hi! Thanks for the SDK. While testing crash recovery for agents built with ToolLoopAgent and tool approval, we hit a gap that leads to an approved side effect running twice. It's reproducible with the mock model, so no API key is needed.
Versions
ai 7.0.162, @ai-sdk/provider 4.0.35, Node 24.
Pattern
The approve-and-continue pattern from the docs, with the conversation persisted so a new process can resume:
generate()returns atool-approval-requestforrefund. The app persists the messages.- The human approves. The app appends the
tool-approval-responseand callsgenerate({ messages }). - The app persists progress in
onStepEnd(step input messages plusstep.response.messages).
What happens
- In step 2, the approved
refundexecutes at the start ofgenerate(), before the first step. Its tool result is not in any step'sresponse.messages, so step-end checkpoints never contain it until the first continuation step ends. - If the process dies before that step ends (a crash in a later tool, here
send_email), the stored history still ends at "approved, no result". On resume the SDK sees an approved call with no result and runs the refund again without asking the human. - Related:
abortSignalis not checked before that pre-step execution, so a crash signalled during an approved call does not stopgenerate(). It returns normally, with a new approval request for the model's retry.
Checkpointing in onStepStart as well (its messages do include the approved results) closes the replay hole. That works, but it isn't obvious from the docs.
Suggestion
- Include the approved calls' results in the first step's
response.messages, or emit a callback such asonApprovedToolsExecutedthat apps can checkpoint on. - Check
abortSignalbefore executing approved calls. - Or, at minimum, document that apps persisting conversations should checkpoint in
onStepStart.
Reproduction
https://github.com/zennicalles/shakedown/blob/main/examples/ai-sdk/ai-sdk.test.ts, describe('AI SDK toolApproval ...'):
- "naive tools: approval does not prevent the duplicate" (crash in
send_email, 2 refunds, 1 approval prompt) - "naive tools + checkpoint in onStepStart: closes the replayed-approval hole"
- "a crash in an approved call does not stop generate()"
Run with npx vitest run examples/ai-sdk/ai-sdk.test.ts. Happy to help with a PR.
Identify issue type
Identified as Bug
Confidence: High
Rationale
The issue reports concrete crash-recovery and cancellation failures in existing tool-approval behavior, including duplicated side effects. Suggested callbacks and documentation changes are proposed remedies, not the primary request.
Evidence
- Approved tool calls execute before the first step, and their results are absent from step.response.messages used for checkpointing.
- After a crash before the continuation step completes, resuming from persisted history executes the approved refund again without another approval.
- The report also states that abortSignal is not checked before approved-call execution and provides mock-model reproductions.
Bug discovery clarification
@zennicalles, how did you discover this bug? Did you encounter it while using the AI SDK in production, find it while auditing or reviewing AI SDK source code, or discover it another way? Please describe the original discovery context.
The report describes crash-recovery testing, but does not establish actual production use or that inspecting AI SDK source code led to discovery. Ask the original author how they discovered the issue.
Hi, I'm interested in working on this issue. Could I open a PR for it?
Found while testing, not in production. We're building an open-source harness (Shakedown) that runs an agent's real loop and injects failures around side-effecting tools. We ran the documented approve-and-continue pattern, persisting messages so that a new process can resume, under a simulated crash between an approved tool call and the end of the next step. The approved refund ran twice. We then read the SDK source to confirm why: approved calls execute before the first step of the continuation, so their results are in no step's response.messages.
It reproduces with MockLanguageModelV4, so no API key is needed:
git clone https://github.com/zennicalles/shakedown && cd shakedown && pnpm install
cd examples/ai-sdk && pnpm install --ignore-workspace && cd ../..
npx vitest run examples/ai-sdk/ai-sdk.test.ts -t "toolApproval"
The relevant tests are "naive tools: approval does not prevent the duplicate", "naive tools + checkpoint in onStepStart: closes the replayed-approval hole" and "a crash in an approved call does not stop generate()".
Identify bug discovery
Discovery source: discovery:other (high confidence).
The author explicitly identified failure-injection testing in an open-source harness as the discovery source, not production use. SDK source inspection occurred afterward to explain the observed behavior.
- The author clarified: "Found while testing, not in production."
- Their Shakedown harness ran the documented approve-and-continue pattern under a simulated crash, revealing that the approved refund ran twice.
- The author stated: "We then read the SDK source to confirm why," establishing that source inspection followed discovery.
Hey @zennicalles, thanks for putting together the Shakedown reproduction suite.
I spent some time tracing this against [email protected] and wanted to share what I found on both the abort behavior and the persistence side:
1. The abort behavior in Test 3:
When I traced why generateText didn't halt in your third test, I noticed that executeToolCall wraps errors thrown inside an approved tool (including aborts) into a tool-error output. Pre-step approved tools run before Step 0 begins (steps.length === 0), and Step 0 deliberately skips throwing mergedAbortSignal?.throwIfAborted() so that tools in Step 0 can receive the forwarded signal (per #17461). Because of that, generateText proceeded directly into Step 0's model call.
Checking abortSignal directly at entry and exit of the pre-step execution block in generateText and streamText stops pre-aborted continuations from running and prevents Step 0 from firing if a pre-step tool aborts, without altering normal Step 0 signal forwarding.
2. Checkpointing approved tool results (onStepStart vs onStepEnd):
In AI SDK 7.0, step.response.messages was intentionally scoped to only contain messages produced by that specific step (per the 7.0 migration guide), while result.responseMessages holds the full history including pre-step approved results.
Attempting to attach pre-step results to step.response.messages at onStepEnd runs into two issues:
- If a subsequent tool crashes during Step 0 (like
send_emailin your repro),onStepEndnever fires. - Aggregators like
result.responseMessages,prepareStep, andonEndalready includeinitialResponseMessages. Prepending them to the step response duplicates therole: 'tool'message across message history.
Saving state at onStepStart({ messages }) avoids this because messages already includes the approved tool's result before Step 0's model call or any subsequent tools run.
I put together a signed patch with regression tests covering the abort behavior and docs clarification on my fork:
π jadibdev/ai@b393183
Happy to open a PR if that's helpful.
Thanks, this is really useful. It matches what we saw: checkpointing in onStepStart closed the replay hole in our repro. Your point that step.response.messages is per-step by design makes sense, so the abort check plus a docs note sounds like the right fix rather than changing the message scoping.
Once there's a PR or a build I can install, I'm happy to run the Shakedown repro against it and post the before/after here.
@zennicalles Appreciate it! Just opened #24911 (jadibdev/fix-tool-approval-abort-and-checkpoint-24624) with the pre-step abortSignal guards for both generateText and streamText plus the onStepStart continuation checkpointing docs note. Let me know how the Shakedown repro looks against it.
@jadibdev I ran the Shakedown repro against #24911. The runtime change for generateText is the two pre-step throwIfAborted() calls, so I applied exactly those to the published [email protected] and ran our approve-and-continue tests (mock model, examples/ai-sdk):
- Before (7.0.168): when the process "crashes" (the abort signal fires) inside the approved refund,
generateTextreturns normally, with a fresh approval request for the model's retry. - With the PR:
generateTextrejects with the abort reason and makes no further model call or approval request. β The test that asserted the old behaviour (threw: false,pendingApprovals: ['refund']) now getsthrew: true,pendingApprovals: []. - Unchanged, as expected: with
onStepEnd-only checkpointing, a crash in a later tool still replays the approval and re-runs the refund. Checkpointing inonStepStart, as your new docs section says, closes that. The other 13 tests are unchanged.
I only tested the generateText path, not the streamText change.
One suggestion for the docs section: passing toolCallId as the idempotency key dedupes a replay of the same call (the crash/approval-replay case). It doesn't catch a model retry after a timeout, because that's a new tool call with a new toolCallId. In our real-model runs that was the common case: an email whose send timed out after going out was re-sent in 25 of 28 runs. A key built from the business operation (e.g. refund:<ticketId>) covers both cases. Maybe worth one sentence?
@zennicalles Thanks for running the Shakedown tests against #24911 and flagging that distinction β agreed on toolCallId vs. a business-operation key on model retries. I added that note to the idempotency section in a1a2024.
One addition for the docs note in #24911, from the receipt side of this problem.
The state the persisted history shows after the crash, "approved, no result," gets read on resume as "not executed." That reading is the bug's second half. The refund may or may not have run; the record genuinely cannot say, because the result was produced outside the step structure the checkpoints capture. A resume that treats an ambiguous state as a safe retry will duplicate the effect some percentage of the time, which is what your Test 1 shows.
Two small things that help, both cheap. Name the state in the docs as an unknown outcome, not a pending one, so the reader's default is reconcile-first rather than retry-first. And the onApprovedToolsExecuted callback proposed above is the right seam if it ever lands, because execution time is the one moment a record of the call can be written that no later crash can strand outside the checkpoint.
For reference, AER-1, the agent execution receipt draft I work on (Brennan Zambo created agent execution receipts; Zambo is the origin product, and AER-1 is the defining standard), keeps "not checked" as a first-class outcome next to verified and verification failed, for exactly this cell of the table. https://datatracker.ietf.org/doc/draft-zambo-aer1/26/
Thanks, that's a sharper description of the state, and I agree with the framing. An approved call with no tool-result in persisted history is an unknown outcome, not an unexecuted one: the record can't tell whether execute reached the external service before the process stopped. I've added a short note to the idempotency section of #24911 that names it that way, so the default on resume is to check the external system or rely on the idempotency key rather than retry.
On onApprovedToolsExecuted: #24911 stays with the abort checks and the onStepStart checkpointing note, so it doesn't add or reference a new callback. Whether the SDK needs one is a call for the maintainers. For that discussion: a record written when execute returns comes after the external write, so it narrows the crash window rather than closing it. A record written before execute starts at least tells a resume that an attempt began, and the external service's idempotency is what makes a retry safe.
Even once onStepEnd checkpointing closes this specific gap, there's always an irreducible crash window between "external HTTP API committed the write" and "local process persisted the checkpoint" (the dual-write / commit-then-fail boundary).
Because at-least-once replay is unavoidable on crash/resume, the safest defense-in-depth for mutating tools in TypeScript/Node is passing a deterministic Idempotency-Key derived from (runId, toolCallId)βand testing the commit_then_fail boundary in CI by dropping/502-ing the first response after 201 Created and asserting the database still has exactly 1 row.
(Disclosure: I maintain agent-fault-check, a language-agnostic Apache-2.0 HTTP fault proxy for testing duplicate writes & retry budgets in CI: https://afc.evhu.net)
A related gap on the same pre-step path: an app can't learn which approved calls generateText / streamText are about to run, so it can't claim them before they run.
onStepStart (or prepareStep at step 0) closes the checkpoint hole, but it fires after executeTools. Two continuations of the same approval, or a crashed one and its retry, both read "approved, no result" and both run the call. Stopping that needs a record written before execute starts, and the only way to know which calls will run is to re-implement collectToolApprovals, which isn't exported. onToolExecutionStart fires at the right moment, but notify swallows a callback's error, so it can't stop a call. toolApproval revalidation runs before execution and can deny, but it's the same hook that decides new calls, and it can only approve or deny, not supply a result.
Any one of these would do:
- export
collectToolApprovals(or a helper that returns the approved local calls a prompt will run); - an awaited hook before
executeToolsfor the approved calls, which can skip a call by giving it a result.
How we found it: while building @convex-dev/agent (https://github.com/convex/agent), not in production. Our acceptance tests run two concurrent continuations of one approval, and a continuation that crashes while running the call followed by a retry, with the mock model (https://github.com/convex/agent/issues/570). On ai 7.0.173 the approved call ran twice in both cases. We now claim each approved call in our own storage before calling generateText, using a copy of collectToolApprovals' rule to know which calls to claim.
@robelest I read through this path on main (42a41f2a97) and agree with the gap: there is no awaited hook for approved calls that can skip a call and supply its result, and two continuations that both read "approved, no result" will both run it.
Two things that may help in the meantime:
collectToolApprovalsis exported fromai/internal(7.0.173 included), andWorkflowAgentuses it from there. It isn't a stable public API, so your request for a public helper still stands, but it may be better than keeping a copy. It returns the calls before revalidation, so some of them can still be denied or rejected, and provider-executed calls and calls to tools withoutexecuteneed filtering out.- For local tools, the claim can also live in a wrapper around
execute, which receivestoolCallId: claim it atomically, and return the saved result if there is one. The weak spot is a claim with no result yet. Throwing there doesn't stop the run, it becomes a tool error the model sees and may retry under a newtoolCallId. A hook that can stop or skip the call would handle that better.
Either way, a claim without a result is still an unknown outcome after a crash, so the external idempotency key stays necessary.
Your point about notify also applies to the docs in #24911: they recommend saving in onStepStart, where a failed save is swallowed too. I added a note there about using prepareStep when the checkpoint is required.
I'd keep the new hook or export out of #24911, since that's an API decision for the maintainers. A separate issue might be easier for them to pick up.