Interrupting & cancelling
There are four mechanisms here, and they're genuinely not interchangeable: agent.stop(), agent.cancel(), agent.clear() and handle.cancel() (a signal on the send behaves like handle.cancel()). Agent → Interrupting is where the four are compared; this page is the recipes.
stop(): let the work finish
const running = agent.send("Refactor the auth module.");
// later, from a UI event
const wasRunning = agent.stop(); // false if nothing was executingThe tool batch that's in flight — including parallel calls — runs to completion and commits. Then the handle settles without another provider request. Nothing gets wasted, and the history stays coherent.
What comes back may surprise you the first time: a stopped turn ends on its tool-call exchange, so there is often no final answer to resolve with. stop() also won't interrupt a provider request or a tool that's already running — if you need a hard stop, that's cancel().
The steer playbook
Three calls, in this order. This is the pattern you'll use most:
agent.stop(); // active turn wraps up cleanly
agent.clear(); // drop anything queued behind it
agent.send("Actually, make the button blue."); // becomes the very next turnStop, clear, send. It gracefully halts what the agent is doing and inserts the user's new instruction as the next turn — which is exactly what a user expects when they interrupt.
Wiring it to a chat box is about as simple as it looks:
function onUserSubmit(text: string) {
agent.stop();
agent.clear();
return agent.send(text);
}That's safe to call whether or not the agent is busy. stop() returns false and clear() returns 0 when there's nothing to interrupt, so the same handler covers the idle case.
The new turn runs against a linear committed history that includes the tools that already finished — so the agent knows what it did before you redirected it, and won't repeat that work.
Order matters
Call clear() before stop() and you leave a window where the active turn can finish and pull in the queued work you were about to drop.
cancel(): stop now
const handle = agent.send("Write a very long essay.");
setTimeout(() => handle.cancel({ reason: "timeout", afterMs: 5000 }), 5000);
try {
const result = await handle.final;
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
console.log("cancelled");
} else {
throw error;
}
}This is local to that one handle — other sends carry on unaffected.
What survives
import { AxleAgentAbortError } from "@fifthrevision/axle";
catch (error) {
if (error instanceof AxleAgentAbortError) {
error.reason; // what you passed to cancel()
error.usage; // tokens already spent — still billable
error.partial; // the partially-streamed assistant message (undefined when nothing was written)
error.messages; // messages completed before the abort
error.turn; // the cancelled turn, for rendering
}
}Showing partial output after a cancel is usually the right call. Your user paid for those tokens, and half an essay beats a blank screen.
const text = error.partial?.content.find((p) => p.type === "text");
if (text?.type === "text") render(text.text);What commits
Whether the user message sticks around depends on timing, and the line is whether the turn opened:
- Before it — queued, or during MCP setup — the handle is dropped and nothing commits. The transcript shows
pending:queuedfollowed bypending:dropped. - After it, the user message stays committed and the turn is marked
cancelled— alwayscancelled, even when the provider rethrows something that doesn't look like an abort. This includes cancelling duringbeforeTurncompaction: compaction is work inside an already-open turn, and cancelling does not unwind the transcript. - Cancelling mid-tool-batch still commits the tool results. When the abort lands while tool calls are running, the batch answers every call before the handle rejects — finished calls keep their real results, the rest read
cancelled(fatalfor the call that threwAxleToolFatalError). So the history ends in thetoolmessage rather than in unanswered calls, and the next send is accepted. The same holds for aturnTimeoutMselapsing mid-batch, and forstream()/generate()(where the error'smessagesends in thetoolmessage too). - Cancelling mid-response keeps only what was written. When the abort lands while the model is still writing its reply, the partial assistant message holds just the parts with content in them: a
tool-callpart is never kept, atextpart only when its text is non-empty, athinkingpart only when it holds text, a summary, redacted content, orcontinuity. Text written before a cut-short tool call is kept without the call. When nothing was written, there is no partial at all (error.partialisundefined, no assistant message commits) — and the next send is accepted either way. The turn still records what was shown: its action part settlescancelledeven though the call never reaches the conversation.
agent.cancel(): stop the active operation
agent.cancel("user-navigated-away"); // false if nothing was runningSame immediacy as handle.cancel(), but aimed at whatever is active rather than one handle. The active operation aborts, an opened turn settles cancelled with its partial work committed, and queued operations are unaffected — the next one starts. Use stop() when you want the in-flight tool batch to finish first, and agent.cancel() when you don't care about it. While onSettled callbacks run, the operation is already done, so both cancel() and stop() return false in that window.
AbortSignal
If you already have abort plumbing, it slots straight in:
const controller = new AbortController();
const result = await agent.send("...", { signal: controller.signal }).final;A signal that's already aborted fails the send before anything commits.
clear(): drain the queue
const dropped = agent.clear();
console.log(`cancelled ${dropped} queued sends`);Each cleared handle rejects with AxleAgentAbortError, having committed nothing. The active turn is left alone.
Cancelling a stream()
Same shape, one class up the hierarchy:
import { stream, AxleAbortError } from "@fifthrevision/axle";
const handle = stream({ provider, model, messages });
setTimeout(() => handle.cancel("timeout"), 4000);
try {
await handle.final;
} catch (error) {
if (error instanceof AxleAbortError) {
console.log(error.reason, error.usage, error.partial);
}
}AxleAgentAbortError extends AxleAbortError, so an instanceof AxleAbortError check catches both.
Cancellation inside tools
Your tools have to cooperate here. Without forwarding the signal, cancelling stops the agent while your work keeps running in the background. ctx.signal also aborts when a sibling call in the same batch throws AxleToolFatalError, so forwarding it is what keeps a doomed batch from being held open by the calls that were still working. (In a deferred handler the same signal also aborts when anything else settles that call — see Deferred tools.)
async execute({ url }, ctx) {
const res = await fetch(url, { signal: ctx.signal }); // forward it
return await res.text();
}For a long CPU-bound loop, poll it:
for (const item of items) {
if (ctx.signal.aborted) throw new Error("Aborted");
await handleItem(item);
}Timeouts
const result = await agent.send("...", { signal: AbortSignal.timeout(30_000) }).final;That's a wall-clock cap on the whole send, tool loop included. If you'd rather cap the number of model requests, use maxSteps with stream() — which is a stop rather than an error, so you keep everything produced so far.
Two built-in timeouts cover the cases a signal can't. turnTimeoutMs bounds a whole turn — every model step, tool call, and deferred wait included — and cancels it with { type: "timeout", limitMs } as the abort reason (narrow it with isTimeoutReason) when it elapses. streamStallMs fails a step whose provider stream goes silent, without retrying. Both are unset by default, and both can be set on the agent or per send:
const agent = new Agent({ provider, model, turnTimeoutMs: 120_000 });
await agent.send("...", { streamStallMs: 15_000 }).final;