
上一篇我们看完了 agentloop,看到 agent turn message 的三层生命周期。现在展开看看tool的生命周期。
tools执行前会进行一次判断,决定当轮turn的工具执行是串行还是并行:
/**
* Execute tool calls from an assistant message.
*/
async function executeToolCalls(
currentContext: AgentContext,
assistantMessage: AssistantMessage,
config: AgentLoopConfig,
signal: AbortSignal | undefined,
emit: AgentEventSink,
): Promise<ExecutedToolCallBatch> {
const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
const hasSequentialToolCall = toolCalls.some(
(tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === "sequential",
);
if (config.toolExecution === "sequential" || hasSequentialToolCall) {
return executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);
}
return executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);
}先看串行执行 executeToolCallsSequential:
在for内部依次执行每一个toolCall
开始先emit tool_execution_start 事件。
然后进行了三个操作:
prepareToolCall:检查toolcall调用是否合法
executePreparedToolCall:执行toolcall调用
finalizeExecutedToolCall: 执行afterToolCall hook
结束后emit tool_execution_end 事件。
根据执行结果创建toolResultMessage。添加回messages。
async function executeToolCallsSequential(
currentContext: AgentContext,
assistantMessage: AssistantMessage,
toolCalls: AgentToolCall[],
config: AgentLoopConfig,
signal: AbortSignal | undefined,
emit: AgentEventSink,
): Promise<ExecutedToolCallBatch> {
const finalizedCalls: FinalizedToolCallOutcome[] = [];
const messages: ToolResultMessage[] = [];
for (const toolCall of toolCalls) {
await emit({
type: "tool_execution_start",
toolCallId: toolCall.id,
toolName: toolCall.name,
args: toolCall.arguments,
});
const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
let finalized: FinalizedToolCallOutcome;
if (preparation.kind === "immediate") {
finalized = {
toolCall,
result: preparation.result,
isError: preparation.isError,
};
} else {
const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit));
finalized = await finalizeExecutedToolCall(
currentContext,
assistantMessage,
preparation,
executed,
config,
signal,
);
}
await emitToolExecutionEnd(finalized, emit);
const toolResultMessage = createToolResultMessage(finalized);
await emitToolResultMessage(toolResultMessage, emit);
finalizedCalls.push(finalized);
messages.push(toolResultMessage);
}
return {
messages,
terminate: shouldTerminateToolBatch(finalizedCalls),
};
}细看一下prepareToolCall:
我第一个关注的是kind,在外层可以看到 preparation.kind ==="immediate" 的时候会快速失败,不执行这个tool,并生成对应的toolResult。
先检查 signal?.aborted 操作有没有取消。
检查tool 在不在 可用的tools 里。
validateToolArguments 校验 tool 的入参是否合法。注意这个校验失败的时候是采用throw error的方式抛出异常,在最后统一catch 生成kind:"immediate" 的toolResult。
执行 beforeToolCall hook。 类似于 cc 的 PreToolUse hook。我是用在沙箱环境 block一些不希望用户轻易执行的命令,比如读取env,rm等高危命令。
在完成 beforeToolCall 之后又检查了一遍 signal?.aborted 看看用户有没有取消操作。第一次读到这里的时候还感觉有一些啰嗦,前面刚检查完这里有必要立刻再检查一遍吗?
看了之前的代码可以感受到pi的基本理念是,写一系列幂等的检查函数。
在每一次await结束/移交控制权给扩展后,重新执行一遍幂等的检查函数。保证在经过任意时长的await之后,环境可能发生改变,仍然能够按顺序正确恢复状态。
hook本身的耗时是不确定的,如果执行hook事件的时间很长,在await期间用户取消了执行。在await结束后如果不再检查一次,用户就会发现自己的取消命令在本轮tool执行时没有正确取消。
async function prepareToolCall(
currentContext: AgentContext,
assistantMessage: AssistantMessage,
toolCall: AgentToolCall,
config: ToolCallHooks,
signal: AbortSignal | undefined,
tools: readonly AgentTool<any>[] = currentContext.tools ?? [],
): Promise<PreparedToolCall | ImmediateToolCallOutcome> {
// Once aborted, skip preparation and the hooks; callers still record this result, so no call
// is left without one (#9986).
if (signal?.aborted) {
return {
kind: "immediate",
result: createErrorToolResult("Operation aborted"),
isError: true,
};
}
const tool = tools.find((t) => t.name === toolCall.name);
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);
if (config.beforeToolCall) {
const beforeResult = await config.beforeToolCall(
{
assistantMessage,
toolCall,
args: validatedArgs,
context: currentContext,
},
signal,
);
if (signal?.aborted) {
return {
kind: "immediate",
result: createErrorToolResult("Operation aborted"),
isError: true,
};
}
if (beforeResult?.block) {
const result = createErrorToolResult(beforeResult.reason || "Tool execution was blocked");
if (beforeResult.terminate === true) {
result.terminate = true;
}
return {
kind: "immediate",
result,
isError: true,
};
}
}
return {
kind: "prepared",
toolCall,
tool,
args: validatedArgs,
};
} catch (error) {
return {
kind: "immediate",
result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
isError: true,
};
}
}工具执行过程就显得非常简单了,工具执行中可通过 onUpdate 回调推送部分结果(如长任务的流式进度),循环收集这些事件的 Promise 并在返回前统一等待,保证事件不丢。
async function executePreparedToolCall(
prepared: PreparedToolCall,
signal: AbortSignal | undefined,
onUpdate: ToolUpdateSink,
): Promise<ExecutedToolCallOutcome> {
const updateEvents: Promise<void>[] = [];
let acceptingUpdates = true;
const startedAt = performance.now();
const elapsed = () => Math.round(performance.now() - startedAt);
try {
const result = await prepared.tool.execute(
prepared.toolCall.id,
prepared.args as never,
signal,
(partialResult) => {
if (!acceptingUpdates) return;
updateEvents.push(Promise.resolve(onUpdate(partialResult)));
},
);
const durationMs = elapsed();
acceptingUpdates = false;
await Promise.all(updateEvents);
return { result, isError: result.isError === true, durationMs };
} catch (error) {
const durationMs = elapsed();
acceptingUpdates = false;
await Promise.all(updateEvents);
return {
result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
isError: true,
durationMs,
};
} finally {
acceptingUpdates = false;
}
}finalizeExecutedToolCall,有一个 afterToolCall hook,可以看出这个hook不但可以改写tool的执行结果,甚至可以通过抛异常的方式让执行结果从成功变成error。。
async function finalizeExecutedToolCall(
currentContext: AgentContext,
assistantMessage: AssistantMessage,
prepared: PreparedToolCall,
executed: ExecutedToolCallOutcome,
config: ToolCallHooks,
signal: AbortSignal | undefined,
): Promise<FinalizedToolCallOutcome> {
let result = executed.result;
let isError = executed.isError;
if (config.afterToolCall) {
try {
const afterResult = await config.afterToolCall(
{
assistantMessage,
toolCall: prepared.toolCall,
args: prepared.args,
result,
isError,
context: currentContext,
},
signal,
);
if (afterResult) {
// Structured content not replaced along with the content may no longer match it.
const structuredContent =
afterResult.structuredContent ?? (afterResult.content ? undefined : result.structuredContent);
result = {
...result,
content: afterResult.content ?? result.content,
details: afterResult.details ?? result.details,
usage: afterResult.usage ?? result.usage,
terminate: afterResult.terminate ?? result.terminate,
};
if (structuredContent === undefined) delete result.structuredContent;
else result.structuredContent = structuredContent;
isError = afterResult.isError ?? isError;
}
} catch (error) {
result = createErrorToolResult(error instanceof Error ? error.message : String(error));
isError = true;
}
}
return {
toolCall: prepared.toolCall,
result,
isError,
durationMs: executed.durationMs,
};
}最后返回本轮turn的tool执行有没有terminal,所有calls 均terminal 才视为terminal,否则还是投票开启下一轮:
function shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {
return finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);
}串行的看完再看并行的工具调用,就会发现其实大部分逻辑都是一致的,唯一的区别在这里,工具没有直接await 执行,而是放进了finalizedCalls,都添加完成后一起塞进promise.all 里面。
这里也可以补一个之前对并行的误解,prepareToolCall的执行仍然是串行的,因为prepareToolCall中的hook来自扩展,我们不能默认扩展的行为是并发安全的:
串行执行顺序:A prepare-> A execute -> B prepare -> B execute
并行执行顺序:A prepare -> B prepare -> A+B execute
乍一看A工具的执行时机 并行比串行更晚一些。 实际上我们下一轮turn必然是等到所有工具执行完成后(promise.all)。所以单工具执行时机晚一些并没有影响什么(反正先执行完也得等着)。
第二个观察是在finalizedCalls里面每个工具的匿名函数,又每个检查了一遍 signal?.aborted (作者你真的太谨慎了,我服了)。当然这么做是对的,毕竟从push函数到后面真正执行,间隔着剩余工具的所有 prepare过程。如果在prepare过程中用户取消了执行,那只有prepare当步的tool以及之后的tool会被取消。 在用户点击取消前的tool还是被正常的状态push进finalizedCalls里面了,所以在最后执行的时候还要每个tool自己检查一遍。
finalizedCalls.push(async () => {
if (signal?.aborted) {
const finalized = {
toolCall,
result: createErrorToolResult("Operation aborted"),
isError: true,
} satisfies FinalizedToolCallOutcome;
await emitToolExecutionEnd(finalized, emit);
return finalized;
}
const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit));
const finalized = await finalizeExecutedToolCall(
currentContext,
assistantMessage,
preparation,
executed,
config,
signal,
);
await emitToolExecutionEnd(finalized, emit);
return finalized;
});
const orderedFinalizedCalls = await Promise.all(
finalizedCalls.map((entry) => (typeof entry === "function" ? entry() : Promise.resolve(entry))),
);
const messages: ToolResultMessage[] = [];
for (const finalized of orderedFinalizedCalls) {
const toolResultMessage = createToolResultMessage(finalized);
await emitToolResultMessage(toolResultMessage, emit);
messages.push(toolResultMessage);
}最后翻到 ToolExecutionMode 配置项上面的注释, 其中 "parallel" 的注释和我们看到的代码实现是一致的。
还提到了一个值得注意的细节: tool_execution_end 事件会按照 tool实际结束的顺序上报,但是在messages里面是按照原始的调用顺序输出 (tool_execution_start 上报的顺序) 这和我们代码中看到的也是一致的,emitToolExecutionEnd发生在toolexecute的执行过程结束后,而messages的组装是在await promise.all 所有工具执行结束后才统一组装。
/**
* Configuration for how tool calls from a single assistant message are executed.
*
* - "sequential": each tool call is prepared, executed, and finalized before the next one starts.
* - "parallel": tool calls are prepared sequentially, then allowed tools execute concurrently.
* `tool_execution_end` is emitted in tool completion order after each tool is finalized,
* while tool-result message artifacts are emitted later in assistant source order.
*/
export type ToolExecutionMode = "sequential" | "parallel";原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。