Cancelling during tool-call repair still allows the repaired tool to run
Description
When repairToolCall is waiting, cancelling the request doesn't stop the SDK from waiting for it. If repair later succeeds, the SDK can execute the repaired tool with an already-aborted signal.
Actual: The operation stays pending until repair finishes, then executes the tool.
Expected: Cancellation stops waiting for repair, and its late result does not execute a tool.
I reproduced this with caller cancellation and timeout.totalMs in generateText, streamText, and ToolLoopAgent.stream. The example below isolates generateText with caller cancellation.
Proposed fix
Observe the effective cancellation signal while waiting for repair, discard late results, and preserve cancellation through error handling without retrying.
An optional abortSignal on the repair callback would also let it cancel its own requests. Callbacks that ignore the signal could still continue their own work.
I have a tested local fix. Happy to open a PR with regression tests and documentation if this behavior and approach look right.
Related: #12878 and #8107 cover cancellation during tool execution. This report concerns pending input repair, before execution.
Investigation and local fix prepared with OpenAI Codex assistance.
Reproduction
Save this as repro.mjs in an empty directory. It uses a mock model and needs no API keys.
import { setImmediate } from 'node:timers/promises';
import { generateText } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod/v4';
const controller = new AbortController();
const repairStarted = Promise.withResolvers();
const pendingRepair = Promise.withResolvers();
let settled = false;
let toolExecutions = 0;
const generation = generateText({
model: new MockLanguageModelV4({
doGenerate: {
content: [{
type: 'tool-call',
toolCallId: 'call-1',
toolName: 'example',
input: '{"value":"invalid"}',
}],
finishReason: { unified: 'tool-calls', raw: 'tool-calls' },
usage: {
inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
outputTokens: { total: 1, text: 1, reasoning: 0 },
},
warnings: [],
},
}),
prompt: 'Run the example tool.',
abortSignal: controller.signal,
tools: {
example: {
inputSchema: z.object({ value: z.number() }),
execute: async () => {
toolExecutions++;
return 'executed';
},
},
},
repairToolCall: async ({ toolCall }) => {
repairStarted.resolve();
await pendingRepair.promise;
return { ...toolCall, input: '{"value":1}' };
},
}).catch(error => {
if (error.name !== 'AbortError') throw error;
}).finally(() => {
settled = true;
});
await repairStarted.promise;
controller.abort();
await setImmediate();
const settledBeforeRepair = settled;
pendingRepair.resolve();
await generation;
console.log({ settledBeforeRepair, toolExecutions });
Run with Node 24:
npm install --ignore-scripts [email protected] [email protected]
node repro.mjs
Actual output:
{ settledBeforeRepair: false, toolExecutions: 1 }
Expected output, also observed with the local proposed fix:
{ settledBeforeRepair: true, toolExecutions: 0 }
AI SDK Version
- ai: 7.0.101
- zod: 4.4.3
- Node.js: 24
- OS: macOS, Apple Silicon
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Identify issue type
Identified as Bug
Confidence: High
Rationale
This is a concrete cancellation-handling failure in existing SDK behavior: an aborted operation continues waiting and subsequently performs tool execution.
Evidence
- Cancelling while
repairToolCallis pending does not settle the operation promptly. - After cancellation, a successful late repair still executes the tool with an aborted signal.
- The report includes a reproducible
generateTextcase on AI SDK 7.0.101 and states the same behavior occurs instreamTextandToolLoopAgent.stream.
Bug Reproduction - AI SDK 7
Bug was reproduced.
Branch: main
PR: successful reproduction pull request
Details
- Reproduced on current
mainwithai7.0.105, so upgrading from the reported 7.0.101 does not resolve the behavior. - Added
examples/ai-functions/src/reproduction/issue-20938-cancel-tool-call-repair.ts, covering caller abort andtimeout.totalMsingenerateText,streamText, andToolLoopAgent.stream. - All six scenarios remained unsettled while repair was pending, then executed the repaired tool once after cancellation; every execution received an already-aborted signal.
- Expected behavior is prompt cancellation settlement and zero tool executions after the late repair result.
Bugfix - AI SDK 7
Created bugfix and opened PR: #20942
Root Cause
Tool-call parsing directly awaited repairToolCall without observing the effective abort signal, and its broad error handling converted cancellation into an invalid tool call. The original reproduction confirmed this across six generateText, streamText, and ToolLoopAgent.stream scenarios.
Summary
Tool-call repair now races against the effective abort signal, preserves cancellation errors, forwards the signal to repairToolCall, and discards late repair results.
Testing
Added regression coverage verifying pending repair stops on cancellation and receives the operation's abort signal, plus a patch changeset for ai.
I checked the parser in #20942 at b8ead33. The ordinary pending-repair cancellation case works, but two edge cases remain:
1. Aborting inside the repair callback leaves its rejection unhandled.
With an initially active caller signal, use this repair callback:
repairToolCall: async () => {
controller.abort(cancellationReason);
throw new Error('Synthetic repair rejection');
},
parseToolCall rejects with the cancellation reason, but Node also emits an unhandledRejection for the repair error. This is a new failure relative to the original parser, which observes the rejection.
The callback is evaluated before waitForPromiseWithAbortSignal starts. Its already-aborted branch returns before attaching a rejection handler to the supplied promise. The repair promise needs to remain observed even when the signal is already aborted by the time the helper receives it.
2. Cancellation during repaired-input validation still returns a valid call.
Use invalid initial JSON, return valid JSON from repair, and hold the subsequent schema validation open:
const validationStarted = new DelayedPromise<void>();
const validationFinished = new DelayedPromise<void>();
const inputSchema = z.object({ value: z.string() }).superRefine(async () => {
validationStarted.resolve(undefined);
await validationFinished.promise;
});
const parsed = parseToolCall({
toolCall: {
type: 'tool-call',
toolName: 'lookup',
toolCallId: 'call-synthetic',
input: 'invalid-json',
},
tools: { lookup: tool({ inputSchema }) },
messages: [],
instructions: undefined,
abortSignal: controller.signal,
repairToolCall: async ({ toolCall }) => ({
...toolCall,
input: '{"value":"repaired"}',
}),
});
await validationStarted.promise;
controller.abort(cancellationReason);
validationFinished.resolve(undefined);
await expect(parsed).rejects.toBe(cancellationReason);
That last assertion fails: parsing resolves to a valid repaired call even though the signal is aborted. Checking cancellation after repaired-input parsing/refinement, before returning the call, covers this case.
I verified both against the exact PR parser source bundled locally, with successful repair and ordinary late rejection as controls. Both cases pass against the cancellation handling in my existing local patch. This was a parser-level check; I have not run the full upstream suites against the PR or re-tested subsequent tool execution for these two cases. AI assistance was used in preparing these checks.
:rocket: Published in:
| Package | Version |
|---|---|
ai |
7.0.108 github npm |
@ai-sdk/amazon-bedrock |
5.0.89 github npm |
@ai-sdk/angular |
3.0.108 github npm |
@ai-sdk/azure |
4.0.76 github npm |
@ai-sdk/code-mode |
1.0.65 github npm |
@ai-sdk/deepseek |
3.0.50 github npm |
@ai-sdk/gateway |
4.0.88 github npm |
@ai-sdk/harness |
1.0.118 github npm |
@ai-sdk/harness-acp |
1.0.56 github npm |
@ai-sdk/harness-claude-code |
1.0.122 github npm |
@ai-sdk/harness-cline |
1.0.45 github npm |
@ai-sdk/harness-codex |
1.0.120 github npm |
@ai-sdk/harness-cursor |
1.0.31 github npm |
@ai-sdk/harness-deepagents |
1.0.118 github npm |
@ai-sdk/harness-fx |
1.0.31 github npm |
@ai-sdk/harness-github-copilot |
1.0.13 github npm |
@ai-sdk/harness-grok-build |
1.0.55 github npm |
@ai-sdk/harness-opencode |
1.0.120 github npm |
@ai-sdk/harness-pi |
1.0.120 github npm |
@ai-sdk/langchain |
3.0.108 github npm |
@ai-sdk/llamaindex |
3.0.108 github npm |
@ai-sdk/mcp |
2.0.55 github npm |
@ai-sdk/openai |
4.0.72 github npm |
@ai-sdk/otel |
1.0.108 github npm |
@ai-sdk/policy-opa |
1.0.108 github npm |
@ai-sdk/react |
4.0.111 github npm |
@ai-sdk/rsc |
3.0.108 github npm |
@ai-sdk/sandbox-just-bash |
1.0.118 github npm |
@ai-sdk/sandbox-vercel |
1.0.118 github npm |
@ai-sdk/svelte |
5.0.108 github npm |
@ai-sdk/tui |
1.0.109 github npm |
@ai-sdk/vue |
4.0.108 github npm |
@ai-sdk/workflow |
2.0.39 github npm |
@ai-sdk/workflow-harness |
1.0.118 github npm |
@ai-sdk/xai |
5.0.5 github npm |