| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877 |
- /**
- * Agent loop that works with AgentMessage throughout.
- * Transforms to Message[] only at the LLM call boundary.
- */
- import {
- type AssistantMessage,
- type Context,
- EventStream,
- streamSimple,
- type ToolResultMessage,
- validateToolArguments,
- } from "@earendil-works/pi-ai";
- import type {
- AgentContext,
- AgentEvent,
- AgentLoopConfig,
- AgentMessage,
- AgentTool,
- AgentToolCall,
- AgentToolResult,
- StreamFn,
- } from "./types.ts";
- export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
- /**
- * Start an agent loop with a new prompt message.
- * The prompt is added to the context and events are emitted for it.
- */
- export function agentLoop(
- prompts: AgentMessage[],
- context: AgentContext,
- config: AgentLoopConfig,
- signal?: AbortSignal,
- streamFn?: StreamFn,
- ): EventStream<AgentEvent, AgentMessage[]> {
- const stream = createAgentStream();
- void runAgentLoop(
- prompts,
- context,
- config,
- async (event) => {
- stream.push(event);
- },
- signal,
- streamFn,
- ).then((messages) => {
- stream.end(messages);
- });
- return stream;
- }
- /**
- * Continue an agent loop from the current context without adding a new message.
- * Used for retries - context already has user message or tool results.
- *
- * **Important:** The last message in context must convert to a `user` or `toolResult` message
- * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
- * This cannot be validated here since `convertToLlm` is only called once per turn.
- */
- export function agentLoopContinue(
- context: AgentContext,
- config: AgentLoopConfig,
- signal?: AbortSignal,
- streamFn?: StreamFn,
- ): EventStream<AgentEvent, AgentMessage[]> {
- if (context.messages.length === 0) {
- throw new Error("Cannot continue: no messages in context");
- }
- if (context.messages[context.messages.length - 1].role === "assistant") {
- throw new Error("Cannot continue from message role: assistant");
- }
- const stream = createAgentStream();
- void runAgentLoopContinue(
- context,
- config,
- async (event) => {
- stream.push(event);
- },
- signal,
- streamFn,
- ).then((messages) => {
- stream.end(messages);
- });
- return stream;
- }
- export async function runAgentLoop(
- prompts: AgentMessage[],
- context: AgentContext,
- config: AgentLoopConfig,
- emit: AgentEventSink,
- signal?: AbortSignal,
- streamFn?: StreamFn,
- ): Promise<AgentMessage[]> {
- const newMessages: AgentMessage[] = [...prompts];
- const currentContext: AgentContext = {
- ...context,
- messages: [...context.messages, ...prompts],
- };
- await emit({ type: "agent_start" });
- await emit({ type: "turn_start" });
- for (const prompt of prompts) {
- await emit({ type: "message_start", message: prompt });
- await emit({ type: "message_end", message: prompt });
- }
- await runLoop(currentContext, newMessages, config, signal, emit, streamFn);
- return newMessages;
- }
- export async function runAgentLoopContinue(
- context: AgentContext,
- config: AgentLoopConfig,
- emit: AgentEventSink,
- signal?: AbortSignal,
- streamFn?: StreamFn,
- ): Promise<AgentMessage[]> {
- if (context.messages.length === 0) {
- throw new Error("Cannot continue: no messages in context");
- }
- if (context.messages[context.messages.length - 1].role === "assistant") {
- throw new Error("Cannot continue from message role: assistant");
- }
- const newMessages: AgentMessage[] = [];
- const currentContext: AgentContext = { ...context };
- await emit({ type: "agent_start" });
- await emit({ type: "turn_start" });
- await runLoop(currentContext, newMessages, config, signal, emit, streamFn);
- return newMessages;
- }
- function createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {
- return new EventStream<AgentEvent, AgentMessage[]>(
- (event: AgentEvent) => event.type === "agent_end",
- (event: AgentEvent) => (event.type === "agent_end" ? event.messages : []),
- );
- }
- /**
- * Main loop logic shared by agentLoop and agentLoopContinue.
- */
- async function runLoop(
- initialContext: AgentContext,
- newMessages: AgentMessage[],
- initialConfig: AgentLoopConfig,
- signal: AbortSignal | undefined,
- emit: AgentEventSink,
- streamFn?: StreamFn,
- ): Promise<void> {
- let currentContext = initialContext;
- let config = initialConfig;
- let firstTurn = true;
- // Check for steering messages at start (user may have typed while waiting)
- let pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];
- // Outer loop: continues when queued follow-up messages arrive after agent would stop
- while (true) {
- let hasMoreToolCalls = true;
- // Inner loop: process tool calls and steering messages
- while (hasMoreToolCalls || pendingMessages.length > 0) {
- if (!firstTurn) {
- await emit({ type: "turn_start" });
- } else {
- firstTurn = false;
- }
- // Process pending messages (inject before next assistant response)
- if (pendingMessages.length > 0) {
- for (const message of pendingMessages) {
- await emit({ type: "message_start", message });
- await emit({ type: "message_end", message });
- currentContext.messages.push(message);
- newMessages.push(message);
- }
- pendingMessages = [];
- }
- // Stream assistant response
- const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);
- newMessages.push(message);
- if (message.stopReason === "error" || message.stopReason === "aborted") {
- await emit({ type: "turn_end", message, toolResults: [] });
- await emit({ type: "agent_end", messages: newMessages });
- return;
- }
- // Check for tool calls
- const toolCalls = message.content.filter((c) => c.type === "toolCall");
- const toolResults: ToolResultMessage[] = [];
- hasMoreToolCalls = false;
- if (toolCalls.length > 0) {
- const executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit);
- toolResults.push(...executedToolBatch.messages);
- hasMoreToolCalls = !executedToolBatch.terminate;
- for (const result of toolResults) {
- currentContext.messages.push(result);
- newMessages.push(result);
- }
- }
- await emit({ type: "turn_end", message, toolResults });
- const nextTurnContext = {
- message,
- toolResults,
- context: currentContext,
- newMessages,
- };
- const nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);
- if (nextTurnSnapshot) {
- currentContext = nextTurnSnapshot.context ?? currentContext;
- config = {
- ...config,
- model: nextTurnSnapshot.model ?? config.model,
- reasoning:
- nextTurnSnapshot.thinkingLevel === undefined
- ? config.reasoning
- : nextTurnSnapshot.thinkingLevel === "off"
- ? undefined
- : nextTurnSnapshot.thinkingLevel,
- };
- }
- if (
- await config.shouldStopAfterTurn?.({
- message,
- toolResults,
- context: currentContext,
- newMessages,
- })
- ) {
- await emit({ type: "agent_end", messages: newMessages });
- return;
- }
- pendingMessages = (await config.getSteeringMessages?.()) || [];
- if ((await config.shouldStopAfterSteering?.()) === true) {
- await emit({ type: "agent_end", messages: newMessages });
- return;
- }
- }
- // Agent would stop here. Check for follow-up messages.
- const followUpMessages = (await config.getFollowUpMessages?.()) || [];
- if (followUpMessages.length > 0) {
- // Set as pending so inner loop processes them
- pendingMessages = followUpMessages;
- continue;
- }
- // No more messages, exit
- break;
- }
- await emit({ type: "agent_end", messages: newMessages });
- }
- /**
- * Stream an assistant response from the LLM.
- * This is where AgentMessage[] gets transformed to Message[] for the LLM.
- */
- async function streamAssistantResponse(
- context: AgentContext,
- config: AgentLoopConfig,
- signal: AbortSignal | undefined,
- emit: AgentEventSink,
- streamFn?: StreamFn,
- ): Promise<AssistantMessage> {
- // Apply context transform if configured (AgentMessage[] → AgentMessage[])
- let messages = context.messages;
- if (config.transformContext) {
- messages = await config.transformContext(messages, signal);
- }
- // Convert to LLM-compatible messages (AgentMessage[] → Message[])
- const llmMessages = await config.convertToLlm(messages);
- // Build LLM context
- const llmContext: Context = {
- systemPrompt: context.systemPrompt,
- messages: llmMessages,
- tools: context.tools,
- };
- const streamFunction = streamFn || streamSimple;
- // Resolve API key (important for expiring tokens)
- const resolvedApiKey =
- (config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;
- const response = await streamFunction(config.model, llmContext, {
- ...config,
- apiKey: resolvedApiKey,
- signal,
- });
- let partialMessage: AssistantMessage | null = null;
- let addedPartial = false;
- for await (const event of response) {
- switch (event.type) {
- case "start":
- partialMessage = event.partial;
- context.messages.push(partialMessage);
- addedPartial = true;
- await emit({ type: "message_start", message: { ...partialMessage } });
- break;
- case "text_start":
- case "text_delta":
- case "text_end":
- case "thinking_start":
- case "thinking_delta":
- case "thinking_end":
- case "toolcall_start":
- case "toolcall_delta":
- case "toolcall_end":
- if (partialMessage) {
- partialMessage = event.partial;
- context.messages[context.messages.length - 1] = partialMessage;
- await emit({
- type: "message_update",
- assistantMessageEvent: event,
- message: { ...partialMessage },
- });
- }
- break;
- case "done":
- case "error": {
- const finalMessage = await response.result();
- if (addedPartial) {
- context.messages[context.messages.length - 1] = finalMessage;
- } else {
- context.messages.push(finalMessage);
- }
- if (!addedPartial) {
- await emit({ type: "message_start", message: { ...finalMessage } });
- }
- await emit({ type: "message_end", message: finalMessage });
- return finalMessage;
- }
- }
- }
- const finalMessage = await response.result();
- if (addedPartial) {
- context.messages[context.messages.length - 1] = finalMessage;
- } else {
- context.messages.push(finalMessage);
- await emit({ type: "message_start", message: { ...finalMessage } });
- }
- await emit({ type: "message_end", message: finalMessage });
- return finalMessage;
- }
- /**
- * 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);
- }
- type ExecutedToolCallBatch = {
- messages: ToolResultMessage[];
- terminate: boolean;
- };
- 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 [toolIndex, toolCall] of toolCalls.entries()) {
- 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,
- terminateAgent: preparation.terminateAgent,
- };
- } else {
- const executed = await executePreparedToolCall(
- currentContext,
- assistantMessage,
- preparation,
- config,
- signal,
- 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);
- if (finalized.terminateAgent === true || signal?.aborted) {
- for (const skippedToolCall of toolCalls.slice(toolIndex + 1)) {
- await emit({
- type: "tool_execution_start",
- toolCallId: skippedToolCall.id,
- toolName: skippedToolCall.name,
- args: skippedToolCall.arguments,
- });
- const skipped = {
- toolCall: skippedToolCall,
- result: createErrorToolResult(
- finalized.terminateAgent === true
- ? "Tool execution skipped because the agent was stopped by a hook"
- : "Tool execution skipped because the operation was aborted",
- ),
- isError: true,
- } satisfies FinalizedToolCallOutcome;
- await emitToolExecutionEnd(skipped, emit);
- const skippedMessage = createToolResultMessage(skipped);
- await emitToolResultMessage(skippedMessage, emit);
- finalizedCalls.push(skipped);
- messages.push(skippedMessage);
- }
- break;
- }
- }
- return {
- messages,
- terminate: shouldTerminateToolBatch(finalizedCalls),
- };
- }
- async function executeToolCallsParallel(
- currentContext: AgentContext,
- assistantMessage: AssistantMessage,
- toolCalls: AgentToolCall[],
- config: AgentLoopConfig,
- signal: AbortSignal | undefined,
- emit: AgentEventSink,
- ): Promise<ExecutedToolCallBatch> {
- const finalizedCalls: FinalizedToolCallEntry[] = [];
- for (const [toolIndex, toolCall] of toolCalls.entries()) {
- await emit({
- type: "tool_execution_start",
- toolCallId: toolCall.id,
- toolName: toolCall.name,
- args: toolCall.arguments,
- });
- const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
- if (preparation.kind === "immediate") {
- const finalized = {
- toolCall,
- result: preparation.result,
- isError: preparation.isError,
- terminateAgent: preparation.terminateAgent,
- } satisfies FinalizedToolCallOutcome;
- await emitToolExecutionEnd(finalized, emit);
- finalizedCalls.push(finalized);
- if (preparation.terminateAgent === true || signal?.aborted) {
- await skipPreparedParallelToolCalls(
- finalizedCalls,
- preparation.terminateAgent === true
- ? "Tool execution skipped because the agent was stopped by a hook"
- : "Tool execution skipped because the operation was aborted",
- emit,
- );
- await appendSkippedParallelToolCalls(
- finalizedCalls,
- toolCalls.slice(toolIndex + 1),
- preparation.terminateAgent === true
- ? "Tool execution skipped because the agent was stopped by a hook"
- : "Tool execution skipped because the operation was aborted",
- emit,
- );
- break;
- }
- continue;
- }
- finalizedCalls.push({ kind: "prepared-entry", preparation });
- if (signal?.aborted) {
- await skipPreparedParallelToolCalls(
- finalizedCalls,
- "Tool execution skipped because the operation was aborted",
- emit,
- );
- await appendSkippedParallelToolCalls(
- finalizedCalls,
- toolCalls.slice(toolIndex + 1),
- "Tool execution skipped because the operation was aborted",
- emit,
- );
- break;
- }
- }
- const orderedFinalizedCalls = await Promise.all(
- finalizedCalls.map(async (entry) => {
- if (!isPreparedToolCallEntry(entry)) return entry;
- const executed = await executePreparedToolCall(
- currentContext,
- assistantMessage,
- entry.preparation,
- config,
- signal,
- emit,
- );
- const finalized = await finalizeExecutedToolCall(
- currentContext,
- assistantMessage,
- entry.preparation,
- executed,
- config,
- signal,
- );
- await emitToolExecutionEnd(finalized, emit);
- return finalized;
- }),
- );
- const messages: ToolResultMessage[] = [];
- for (const finalized of orderedFinalizedCalls) {
- const toolResultMessage = createToolResultMessage(finalized);
- await emitToolResultMessage(toolResultMessage, emit);
- messages.push(toolResultMessage);
- }
- return {
- messages,
- terminate: shouldTerminateToolBatch(orderedFinalizedCalls),
- };
- }
- type PreparedToolCall = {
- kind: "prepared";
- toolCall: AgentToolCall;
- tool: AgentTool<any>;
- args: unknown;
- };
- type ImmediateToolCallOutcome = {
- kind: "immediate";
- result: AgentToolResult<any>;
- isError: boolean;
- terminateAgent?: boolean;
- };
- type ExecutedToolCallOutcome = {
- result: AgentToolResult<any>;
- isError: boolean;
- };
- type FinalizedToolCallOutcome = {
- toolCall: AgentToolCall;
- result: AgentToolResult<any>;
- isError: boolean;
- terminateAgent?: boolean;
- };
- type FinalizedToolCallEntry =
- | FinalizedToolCallOutcome
- | { kind: "prepared-entry"; preparation: PreparedToolCall };
- function isPreparedToolCallEntry(
- entry: FinalizedToolCallEntry,
- ): entry is { kind: "prepared-entry"; preparation: PreparedToolCall } {
- return "kind" in entry && entry.kind === "prepared-entry";
- }
- async function skipPreparedParallelToolCalls(
- finalizedCalls: FinalizedToolCallEntry[],
- reason: string,
- emit: AgentEventSink,
- ): Promise<void> {
- for (const [index, entry] of finalizedCalls.entries()) {
- if (!isPreparedToolCallEntry(entry)) continue;
- const skipped = {
- toolCall: entry.preparation.toolCall,
- result: createErrorToolResult(reason),
- isError: true,
- } satisfies FinalizedToolCallOutcome;
- await emitToolExecutionEnd(skipped, emit);
- finalizedCalls[index] = skipped;
- }
- }
- async function appendSkippedParallelToolCalls(
- finalizedCalls: FinalizedToolCallEntry[],
- toolCalls: readonly AgentToolCall[],
- reason: string,
- emit: AgentEventSink,
- ): Promise<void> {
- for (const toolCall of toolCalls) {
- await emit({
- type: "tool_execution_start",
- toolCallId: toolCall.id,
- toolName: toolCall.name,
- args: toolCall.arguments,
- });
- const skipped = {
- toolCall,
- result: createErrorToolResult(reason),
- isError: true,
- } satisfies FinalizedToolCallOutcome;
- await emitToolExecutionEnd(skipped, emit);
- finalizedCalls.push(skipped);
- }
- }
- function shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {
- return (
- finalizedCalls.some((finalized) => finalized.terminateAgent === true) ||
- (finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true))
- );
- }
- function prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {
- if (!tool.prepareArguments) {
- return toolCall;
- }
- const preparedArguments = tool.prepareArguments(toolCall.arguments);
- if (preparedArguments === toolCall.arguments) {
- return toolCall;
- }
- return {
- ...toolCall,
- arguments: preparedArguments as Record<string, any>,
- };
- }
- async function prepareToolCall(
- currentContext: AgentContext,
- assistantMessage: AssistantMessage,
- toolCall: AgentToolCall,
- config: AgentLoopConfig,
- signal: AbortSignal | undefined,
- ): Promise<PreparedToolCall | ImmediateToolCallOutcome> {
- const tool = currentContext.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) {
- return {
- kind: "immediate",
- result: createErrorToolResult(beforeResult.reason || "Tool execution was blocked"),
- isError: true,
- terminateAgent: beforeResult.terminateAgent,
- };
- }
- }
- if (signal?.aborted) {
- return {
- kind: "immediate",
- result: createErrorToolResult("Operation aborted"),
- 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,
- };
- }
- }
- async function executePreparedToolCall(
- currentContext: AgentContext,
- assistantMessage: AssistantMessage,
- prepared: PreparedToolCall,
- config: AgentLoopConfig,
- signal: AbortSignal | undefined,
- emit: AgentEventSink,
- ): Promise<ExecutedToolCallOutcome> {
- const updateEvents: Promise<void>[] = [];
- try {
- config.onToolExecutionStart?.({
- assistantMessage,
- toolCall: prepared.toolCall,
- args: prepared.args,
- context: currentContext,
- });
- const result = await prepared.tool.execute(
- prepared.toolCall.id,
- prepared.args as never,
- signal,
- (partialResult) => {
- updateEvents.push(
- Promise.resolve(
- emit({
- type: "tool_execution_update",
- toolCallId: prepared.toolCall.id,
- toolName: prepared.toolCall.name,
- args: prepared.toolCall.arguments,
- partialResult,
- }),
- ),
- );
- },
- );
- await Promise.all(updateEvents);
- return { result, isError: false };
- } catch (error) {
- await Promise.all(updateEvents);
- return {
- result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
- isError: true,
- };
- }
- }
- async function finalizeExecutedToolCall(
- currentContext: AgentContext,
- assistantMessage: AssistantMessage,
- prepared: PreparedToolCall,
- executed: ExecutedToolCallOutcome,
- config: AgentLoopConfig,
- signal: AbortSignal | undefined,
- ): Promise<FinalizedToolCallOutcome> {
- let result = executed.result;
- let isError = executed.isError;
- let terminateAgent = false;
- if (config.afterToolCall) {
- try {
- const afterResult = await config.afterToolCall(
- {
- assistantMessage,
- toolCall: prepared.toolCall,
- args: prepared.args,
- result,
- isError,
- context: currentContext,
- },
- signal,
- );
- if (afterResult) {
- result = {
- content: afterResult.content ?? result.content,
- details: afterResult.details ?? result.details,
- terminate: afterResult.terminate ?? result.terminate,
- };
- isError = afterResult.isError ?? isError;
- terminateAgent = afterResult.terminateAgent === true;
- }
- } catch (error) {
- result = createErrorToolResult(error instanceof Error ? error.message : String(error));
- isError = true;
- }
- }
- return {
- toolCall: prepared.toolCall,
- result,
- isError,
- terminateAgent,
- };
- }
- function createErrorToolResult(message: string): AgentToolResult<any> {
- return {
- content: [{ type: "text", text: message }],
- details: {},
- };
- }
- async function emitToolExecutionEnd(finalized: FinalizedToolCallOutcome, emit: AgentEventSink): Promise<void> {
- await emit({
- type: "tool_execution_end",
- toolCallId: finalized.toolCall.id,
- toolName: finalized.toolCall.name,
- result: finalized.result,
- isError: finalized.isError,
- });
- }
- function createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {
- return {
- role: "toolResult",
- toolCallId: finalized.toolCall.id,
- toolName: finalized.toolCall.name,
- content: finalized.result.content,
- details: finalized.result.details,
- isError: finalized.isError,
- timestamp: Date.now(),
- };
- }
- async function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {
- await emit({ type: "message_start", message: toolResultMessage });
- await emit({ type: "message_end", message: toolResultMessage });
- }
|