CH 02 · The Agent Loop Pattern · 14/15
Read as one pageReal code: pi turns every tool failure into a result
pi handles the last two items on the list, malformed arguments and tool exceptions, with one rule: no failure leaves the tool step as an exception. Every failure becomes a tool result marked isError: true that goes back to the model. Two functions in pi's loop file enforce it. The first checks a call before it runs:
const tool = tools.find((t) => t.name === toolCall.name); // [1]
if (!tool) {
return {
kind: "immediate",
result: createErrorToolResult(`Tool ${toolCall.name} not found`),
isError: true,
};
}
try {
const preparedToolCall = prepareToolCallArguments(tool, toolCall);
const validatedArgs = validateToolArguments(tool, preparedToolCall); // [2]
// ... (36 lines: a permission hook may block the call; checks for a cancelled run)
return {
kind: "prepared",
toolCall,
tool,
args: validatedArgs,
};
} catch (error) {
return {
kind: "immediate",
result: createErrorToolResult(error instanceof Error ? error.message : String(error)), // [3]
isError: true,
};
}
Source: earendil-works/pi, packages/agent/src/agent-loop.ts (MIT)
The second runs it:
try {
const result = await prepared.tool.execute( // [4]
prepared.toolCall.id,
prepared.args as never,
signal,
// ... (4 lines: pass progress updates through)
);
// ... (3 lines: stop the timer, stop accepting progress updates)
return { result, isError: result.isError === true, durationMs };
} catch (error) {
// ... (3 lines: the same timer and progress cleanup)
return {
result: createErrorToolResult(error instanceof Error ? error.message : String(error)), // [5]
isError: true,
durationMs,
};
Source: earendil-works/pi, packages/agent/src/agent-loop.ts (MIT)
What to notice
- [1] The model can name a tool that does not exist. The answer is an
"immediate"outcome, a result that is ready without running anything.createErrorToolResultjust wraps a message as text. - [2]
prepareToolCallArgumentsruns first. If the tool definesprepareArguments, that hook may rewritetoolCall.argumentsbefore the check.validateToolArgumentsthen checks the arguments against the tool's schema. On a mismatch it throws a message that lists each bad field and repeats the arguments the model sent: exactly what the model needs to fix its next call. - [3] The
catchturns that throw into an error result. A"prepared"outcome means the call passed every check and may run. - [4]
executeis the tool's own code.signalis the run's abort signal, and it may be undefined. The comment onexecuteintypes.tstells tool authors to throw on failure or return a result withisError: true, so a throw is a normal way for a tool to fail, not an accident. - [5] The error's message becomes the result, and
durationMsis still recorded.
On these two paths the loop emits tool_execution_end and appends a result with the call's id. If the run is aborted mid-batch, the sequential runner stops and the remaining calls in that batch get no result. A loop that lets the exception escape loses the whole turn over one bad file path, and the model never learns what went wrong.
Read it yourself: in the same file, read failToolCallsFromTruncatedMessage. When a reply is cut off by the output token limit, the arguments may parse but be incomplete, so pi runs none of the calls and asks the model to re-issue them. Then read finalizeExecutedToolCall: what happens if your own afterToolCall hook throws?
Finished this idea?
Your learning progress stays in this browser.