agent-loop.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. /**
  2. * Agent loop that works with AgentMessage throughout.
  3. * Transforms to Message[] only at the LLM call boundary.
  4. */
  5. import {
  6. type AssistantMessage,
  7. type Context,
  8. EventStream,
  9. streamSimple,
  10. type ToolResultMessage,
  11. validateToolArguments,
  12. } from "@earendil-works/pi-ai";
  13. import type {
  14. AgentContext,
  15. AgentEvent,
  16. AgentLoopConfig,
  17. AgentMessage,
  18. AgentTool,
  19. AgentToolCall,
  20. AgentToolResult,
  21. StreamFn,
  22. } from "./types.ts";
  23. export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
  24. /**
  25. * Start an agent loop with a new prompt message.
  26. * The prompt is added to the context and events are emitted for it.
  27. */
  28. export function agentLoop(
  29. prompts: AgentMessage[],
  30. context: AgentContext,
  31. config: AgentLoopConfig,
  32. signal?: AbortSignal,
  33. streamFn?: StreamFn,
  34. ): EventStream<AgentEvent, AgentMessage[]> {
  35. const stream = createAgentStream();
  36. void runAgentLoop(
  37. prompts,
  38. context,
  39. config,
  40. async (event) => {
  41. stream.push(event);
  42. },
  43. signal,
  44. streamFn,
  45. ).then((messages) => {
  46. stream.end(messages);
  47. });
  48. return stream;
  49. }
  50. /**
  51. * Continue an agent loop from the current context without adding a new message.
  52. * Used for retries - context already has user message or tool results.
  53. *
  54. * **Important:** The last message in context must convert to a `user` or `toolResult` message
  55. * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
  56. * This cannot be validated here since `convertToLlm` is only called once per turn.
  57. */
  58. export function agentLoopContinue(
  59. context: AgentContext,
  60. config: AgentLoopConfig,
  61. signal?: AbortSignal,
  62. streamFn?: StreamFn,
  63. ): EventStream<AgentEvent, AgentMessage[]> {
  64. if (context.messages.length === 0) {
  65. throw new Error("Cannot continue: no messages in context");
  66. }
  67. if (context.messages[context.messages.length - 1].role === "assistant") {
  68. throw new Error("Cannot continue from message role: assistant");
  69. }
  70. const stream = createAgentStream();
  71. void runAgentLoopContinue(
  72. context,
  73. config,
  74. async (event) => {
  75. stream.push(event);
  76. },
  77. signal,
  78. streamFn,
  79. ).then((messages) => {
  80. stream.end(messages);
  81. });
  82. return stream;
  83. }
  84. export async function runAgentLoop(
  85. prompts: AgentMessage[],
  86. context: AgentContext,
  87. config: AgentLoopConfig,
  88. emit: AgentEventSink,
  89. signal?: AbortSignal,
  90. streamFn?: StreamFn,
  91. ): Promise<AgentMessage[]> {
  92. const newMessages: AgentMessage[] = [...prompts];
  93. const currentContext: AgentContext = {
  94. ...context,
  95. messages: [...context.messages, ...prompts],
  96. };
  97. await emit({ type: "agent_start" });
  98. await emit({ type: "turn_start" });
  99. for (const prompt of prompts) {
  100. await emit({ type: "message_start", message: prompt });
  101. await emit({ type: "message_end", message: prompt });
  102. }
  103. await runLoop(currentContext, newMessages, config, signal, emit, streamFn);
  104. return newMessages;
  105. }
  106. export async function runAgentLoopContinue(
  107. context: AgentContext,
  108. config: AgentLoopConfig,
  109. emit: AgentEventSink,
  110. signal?: AbortSignal,
  111. streamFn?: StreamFn,
  112. ): Promise<AgentMessage[]> {
  113. if (context.messages.length === 0) {
  114. throw new Error("Cannot continue: no messages in context");
  115. }
  116. if (context.messages[context.messages.length - 1].role === "assistant") {
  117. throw new Error("Cannot continue from message role: assistant");
  118. }
  119. const newMessages: AgentMessage[] = [];
  120. const currentContext: AgentContext = { ...context };
  121. await emit({ type: "agent_start" });
  122. await emit({ type: "turn_start" });
  123. await runLoop(currentContext, newMessages, config, signal, emit, streamFn);
  124. return newMessages;
  125. }
  126. function createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {
  127. return new EventStream<AgentEvent, AgentMessage[]>(
  128. (event: AgentEvent) => event.type === "agent_end",
  129. (event: AgentEvent) => (event.type === "agent_end" ? event.messages : []),
  130. );
  131. }
  132. /**
  133. * Main loop logic shared by agentLoop and agentLoopContinue.
  134. */
  135. async function runLoop(
  136. initialContext: AgentContext,
  137. newMessages: AgentMessage[],
  138. initialConfig: AgentLoopConfig,
  139. signal: AbortSignal | undefined,
  140. emit: AgentEventSink,
  141. streamFn?: StreamFn,
  142. ): Promise<void> {
  143. let currentContext = initialContext;
  144. let config = initialConfig;
  145. let firstTurn = true;
  146. // Check for steering messages at start (user may have typed while waiting)
  147. let pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];
  148. // Outer loop: continues when queued follow-up messages arrive after agent would stop
  149. while (true) {
  150. let hasMoreToolCalls = true;
  151. // Inner loop: process tool calls and steering messages
  152. while (hasMoreToolCalls || pendingMessages.length > 0) {
  153. if (!firstTurn) {
  154. await emit({ type: "turn_start" });
  155. } else {
  156. firstTurn = false;
  157. }
  158. // Process pending messages (inject before next assistant response)
  159. if (pendingMessages.length > 0) {
  160. for (const message of pendingMessages) {
  161. await emit({ type: "message_start", message });
  162. await emit({ type: "message_end", message });
  163. currentContext.messages.push(message);
  164. newMessages.push(message);
  165. }
  166. pendingMessages = [];
  167. }
  168. // Stream assistant response
  169. const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);
  170. newMessages.push(message);
  171. if (message.stopReason === "error" || message.stopReason === "aborted") {
  172. await emit({ type: "turn_end", message, toolResults: [] });
  173. await emit({ type: "agent_end", messages: newMessages });
  174. return;
  175. }
  176. // Check for tool calls
  177. const toolCalls = message.content.filter((c) => c.type === "toolCall");
  178. const toolResults: ToolResultMessage[] = [];
  179. hasMoreToolCalls = false;
  180. if (toolCalls.length > 0) {
  181. const executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit);
  182. toolResults.push(...executedToolBatch.messages);
  183. hasMoreToolCalls = !executedToolBatch.terminate;
  184. for (const result of toolResults) {
  185. currentContext.messages.push(result);
  186. newMessages.push(result);
  187. }
  188. }
  189. await emit({ type: "turn_end", message, toolResults });
  190. const nextTurnContext = {
  191. message,
  192. toolResults,
  193. context: currentContext,
  194. newMessages,
  195. };
  196. const nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);
  197. if (nextTurnSnapshot) {
  198. currentContext = nextTurnSnapshot.context ?? currentContext;
  199. config = {
  200. ...config,
  201. model: nextTurnSnapshot.model ?? config.model,
  202. reasoning:
  203. nextTurnSnapshot.thinkingLevel === undefined
  204. ? config.reasoning
  205. : nextTurnSnapshot.thinkingLevel === "off"
  206. ? undefined
  207. : nextTurnSnapshot.thinkingLevel,
  208. };
  209. }
  210. if (
  211. await config.shouldStopAfterTurn?.({
  212. message,
  213. toolResults,
  214. context: currentContext,
  215. newMessages,
  216. })
  217. ) {
  218. await emit({ type: "agent_end", messages: newMessages });
  219. return;
  220. }
  221. pendingMessages = (await config.getSteeringMessages?.()) || [];
  222. if ((await config.shouldStopAfterSteering?.()) === true) {
  223. await emit({ type: "agent_end", messages: newMessages });
  224. return;
  225. }
  226. }
  227. // Agent would stop here. Check for follow-up messages.
  228. const followUpMessages = (await config.getFollowUpMessages?.()) || [];
  229. if (followUpMessages.length > 0) {
  230. // Set as pending so inner loop processes them
  231. pendingMessages = followUpMessages;
  232. continue;
  233. }
  234. // No more messages, exit
  235. break;
  236. }
  237. await emit({ type: "agent_end", messages: newMessages });
  238. }
  239. /**
  240. * Stream an assistant response from the LLM.
  241. * This is where AgentMessage[] gets transformed to Message[] for the LLM.
  242. */
  243. async function streamAssistantResponse(
  244. context: AgentContext,
  245. config: AgentLoopConfig,
  246. signal: AbortSignal | undefined,
  247. emit: AgentEventSink,
  248. streamFn?: StreamFn,
  249. ): Promise<AssistantMessage> {
  250. // Apply context transform if configured (AgentMessage[] → AgentMessage[])
  251. let messages = context.messages;
  252. if (config.transformContext) {
  253. messages = await config.transformContext(messages, signal);
  254. }
  255. // Convert to LLM-compatible messages (AgentMessage[] → Message[])
  256. const llmMessages = await config.convertToLlm(messages);
  257. // Build LLM context
  258. const llmContext: Context = {
  259. systemPrompt: context.systemPrompt,
  260. messages: llmMessages,
  261. tools: context.tools,
  262. };
  263. const streamFunction = streamFn || streamSimple;
  264. // Resolve API key (important for expiring tokens)
  265. const resolvedApiKey =
  266. (config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;
  267. const response = await streamFunction(config.model, llmContext, {
  268. ...config,
  269. apiKey: resolvedApiKey,
  270. signal,
  271. });
  272. let partialMessage: AssistantMessage | null = null;
  273. let addedPartial = false;
  274. for await (const event of response) {
  275. switch (event.type) {
  276. case "start":
  277. partialMessage = event.partial;
  278. context.messages.push(partialMessage);
  279. addedPartial = true;
  280. await emit({ type: "message_start", message: { ...partialMessage } });
  281. break;
  282. case "text_start":
  283. case "text_delta":
  284. case "text_end":
  285. case "thinking_start":
  286. case "thinking_delta":
  287. case "thinking_end":
  288. case "toolcall_start":
  289. case "toolcall_delta":
  290. case "toolcall_end":
  291. if (partialMessage) {
  292. partialMessage = event.partial;
  293. context.messages[context.messages.length - 1] = partialMessage;
  294. await emit({
  295. type: "message_update",
  296. assistantMessageEvent: event,
  297. message: { ...partialMessage },
  298. });
  299. }
  300. break;
  301. case "done":
  302. case "error": {
  303. const finalMessage = await response.result();
  304. if (addedPartial) {
  305. context.messages[context.messages.length - 1] = finalMessage;
  306. } else {
  307. context.messages.push(finalMessage);
  308. }
  309. if (!addedPartial) {
  310. await emit({ type: "message_start", message: { ...finalMessage } });
  311. }
  312. await emit({ type: "message_end", message: finalMessage });
  313. return finalMessage;
  314. }
  315. }
  316. }
  317. const finalMessage = await response.result();
  318. if (addedPartial) {
  319. context.messages[context.messages.length - 1] = finalMessage;
  320. } else {
  321. context.messages.push(finalMessage);
  322. await emit({ type: "message_start", message: { ...finalMessage } });
  323. }
  324. await emit({ type: "message_end", message: finalMessage });
  325. return finalMessage;
  326. }
  327. /**
  328. * Execute tool calls from an assistant message.
  329. */
  330. async function executeToolCalls(
  331. currentContext: AgentContext,
  332. assistantMessage: AssistantMessage,
  333. config: AgentLoopConfig,
  334. signal: AbortSignal | undefined,
  335. emit: AgentEventSink,
  336. ): Promise<ExecutedToolCallBatch> {
  337. const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
  338. const hasSequentialToolCall = toolCalls.some(
  339. (tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === "sequential",
  340. );
  341. if (config.toolExecution === "sequential" || hasSequentialToolCall) {
  342. return executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);
  343. }
  344. return executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);
  345. }
  346. type ExecutedToolCallBatch = {
  347. messages: ToolResultMessage[];
  348. terminate: boolean;
  349. };
  350. async function executeToolCallsSequential(
  351. currentContext: AgentContext,
  352. assistantMessage: AssistantMessage,
  353. toolCalls: AgentToolCall[],
  354. config: AgentLoopConfig,
  355. signal: AbortSignal | undefined,
  356. emit: AgentEventSink,
  357. ): Promise<ExecutedToolCallBatch> {
  358. const finalizedCalls: FinalizedToolCallOutcome[] = [];
  359. const messages: ToolResultMessage[] = [];
  360. for (const [toolIndex, toolCall] of toolCalls.entries()) {
  361. await emit({
  362. type: "tool_execution_start",
  363. toolCallId: toolCall.id,
  364. toolName: toolCall.name,
  365. args: toolCall.arguments,
  366. });
  367. const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
  368. let finalized: FinalizedToolCallOutcome;
  369. if (preparation.kind === "immediate") {
  370. finalized = {
  371. toolCall,
  372. result: preparation.result,
  373. isError: preparation.isError,
  374. terminateAgent: preparation.terminateAgent,
  375. };
  376. } else {
  377. const executed = await executePreparedToolCall(
  378. currentContext,
  379. assistantMessage,
  380. preparation,
  381. config,
  382. signal,
  383. emit,
  384. );
  385. finalized = await finalizeExecutedToolCall(
  386. currentContext,
  387. assistantMessage,
  388. preparation,
  389. executed,
  390. config,
  391. signal,
  392. );
  393. }
  394. await emitToolExecutionEnd(finalized, emit);
  395. const toolResultMessage = createToolResultMessage(finalized);
  396. await emitToolResultMessage(toolResultMessage, emit);
  397. finalizedCalls.push(finalized);
  398. messages.push(toolResultMessage);
  399. if (finalized.terminateAgent === true || signal?.aborted) {
  400. for (const skippedToolCall of toolCalls.slice(toolIndex + 1)) {
  401. await emit({
  402. type: "tool_execution_start",
  403. toolCallId: skippedToolCall.id,
  404. toolName: skippedToolCall.name,
  405. args: skippedToolCall.arguments,
  406. });
  407. const skipped = {
  408. toolCall: skippedToolCall,
  409. result: createErrorToolResult(
  410. finalized.terminateAgent === true
  411. ? "Tool execution skipped because the agent was stopped by a hook"
  412. : "Tool execution skipped because the operation was aborted",
  413. ),
  414. isError: true,
  415. } satisfies FinalizedToolCallOutcome;
  416. await emitToolExecutionEnd(skipped, emit);
  417. const skippedMessage = createToolResultMessage(skipped);
  418. await emitToolResultMessage(skippedMessage, emit);
  419. finalizedCalls.push(skipped);
  420. messages.push(skippedMessage);
  421. }
  422. break;
  423. }
  424. }
  425. return {
  426. messages,
  427. terminate: shouldTerminateToolBatch(finalizedCalls),
  428. };
  429. }
  430. async function executeToolCallsParallel(
  431. currentContext: AgentContext,
  432. assistantMessage: AssistantMessage,
  433. toolCalls: AgentToolCall[],
  434. config: AgentLoopConfig,
  435. signal: AbortSignal | undefined,
  436. emit: AgentEventSink,
  437. ): Promise<ExecutedToolCallBatch> {
  438. const finalizedCalls: FinalizedToolCallEntry[] = [];
  439. for (const [toolIndex, toolCall] of toolCalls.entries()) {
  440. await emit({
  441. type: "tool_execution_start",
  442. toolCallId: toolCall.id,
  443. toolName: toolCall.name,
  444. args: toolCall.arguments,
  445. });
  446. const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
  447. if (preparation.kind === "immediate") {
  448. const finalized = {
  449. toolCall,
  450. result: preparation.result,
  451. isError: preparation.isError,
  452. terminateAgent: preparation.terminateAgent,
  453. } satisfies FinalizedToolCallOutcome;
  454. await emitToolExecutionEnd(finalized, emit);
  455. finalizedCalls.push(finalized);
  456. if (preparation.terminateAgent === true || signal?.aborted) {
  457. await skipPreparedParallelToolCalls(
  458. finalizedCalls,
  459. preparation.terminateAgent === true
  460. ? "Tool execution skipped because the agent was stopped by a hook"
  461. : "Tool execution skipped because the operation was aborted",
  462. emit,
  463. );
  464. await appendSkippedParallelToolCalls(
  465. finalizedCalls,
  466. toolCalls.slice(toolIndex + 1),
  467. preparation.terminateAgent === true
  468. ? "Tool execution skipped because the agent was stopped by a hook"
  469. : "Tool execution skipped because the operation was aborted",
  470. emit,
  471. );
  472. break;
  473. }
  474. continue;
  475. }
  476. finalizedCalls.push({ kind: "prepared-entry", preparation });
  477. if (signal?.aborted) {
  478. await skipPreparedParallelToolCalls(
  479. finalizedCalls,
  480. "Tool execution skipped because the operation was aborted",
  481. emit,
  482. );
  483. await appendSkippedParallelToolCalls(
  484. finalizedCalls,
  485. toolCalls.slice(toolIndex + 1),
  486. "Tool execution skipped because the operation was aborted",
  487. emit,
  488. );
  489. break;
  490. }
  491. }
  492. const orderedFinalizedCalls = await Promise.all(
  493. finalizedCalls.map(async (entry) => {
  494. if (!isPreparedToolCallEntry(entry)) return entry;
  495. const executed = await executePreparedToolCall(
  496. currentContext,
  497. assistantMessage,
  498. entry.preparation,
  499. config,
  500. signal,
  501. emit,
  502. );
  503. const finalized = await finalizeExecutedToolCall(
  504. currentContext,
  505. assistantMessage,
  506. entry.preparation,
  507. executed,
  508. config,
  509. signal,
  510. );
  511. await emitToolExecutionEnd(finalized, emit);
  512. return finalized;
  513. }),
  514. );
  515. const messages: ToolResultMessage[] = [];
  516. for (const finalized of orderedFinalizedCalls) {
  517. const toolResultMessage = createToolResultMessage(finalized);
  518. await emitToolResultMessage(toolResultMessage, emit);
  519. messages.push(toolResultMessage);
  520. }
  521. return {
  522. messages,
  523. terminate: shouldTerminateToolBatch(orderedFinalizedCalls),
  524. };
  525. }
  526. type PreparedToolCall = {
  527. kind: "prepared";
  528. toolCall: AgentToolCall;
  529. tool: AgentTool<any>;
  530. args: unknown;
  531. };
  532. type ImmediateToolCallOutcome = {
  533. kind: "immediate";
  534. result: AgentToolResult<any>;
  535. isError: boolean;
  536. terminateAgent?: boolean;
  537. };
  538. type ExecutedToolCallOutcome = {
  539. result: AgentToolResult<any>;
  540. isError: boolean;
  541. };
  542. type FinalizedToolCallOutcome = {
  543. toolCall: AgentToolCall;
  544. result: AgentToolResult<any>;
  545. isError: boolean;
  546. terminateAgent?: boolean;
  547. };
  548. type FinalizedToolCallEntry =
  549. | FinalizedToolCallOutcome
  550. | { kind: "prepared-entry"; preparation: PreparedToolCall };
  551. function isPreparedToolCallEntry(
  552. entry: FinalizedToolCallEntry,
  553. ): entry is { kind: "prepared-entry"; preparation: PreparedToolCall } {
  554. return "kind" in entry && entry.kind === "prepared-entry";
  555. }
  556. async function skipPreparedParallelToolCalls(
  557. finalizedCalls: FinalizedToolCallEntry[],
  558. reason: string,
  559. emit: AgentEventSink,
  560. ): Promise<void> {
  561. for (const [index, entry] of finalizedCalls.entries()) {
  562. if (!isPreparedToolCallEntry(entry)) continue;
  563. const skipped = {
  564. toolCall: entry.preparation.toolCall,
  565. result: createErrorToolResult(reason),
  566. isError: true,
  567. } satisfies FinalizedToolCallOutcome;
  568. await emitToolExecutionEnd(skipped, emit);
  569. finalizedCalls[index] = skipped;
  570. }
  571. }
  572. async function appendSkippedParallelToolCalls(
  573. finalizedCalls: FinalizedToolCallEntry[],
  574. toolCalls: readonly AgentToolCall[],
  575. reason: string,
  576. emit: AgentEventSink,
  577. ): Promise<void> {
  578. for (const toolCall of toolCalls) {
  579. await emit({
  580. type: "tool_execution_start",
  581. toolCallId: toolCall.id,
  582. toolName: toolCall.name,
  583. args: toolCall.arguments,
  584. });
  585. const skipped = {
  586. toolCall,
  587. result: createErrorToolResult(reason),
  588. isError: true,
  589. } satisfies FinalizedToolCallOutcome;
  590. await emitToolExecutionEnd(skipped, emit);
  591. finalizedCalls.push(skipped);
  592. }
  593. }
  594. function shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {
  595. return (
  596. finalizedCalls.some((finalized) => finalized.terminateAgent === true) ||
  597. (finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true))
  598. );
  599. }
  600. function prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {
  601. if (!tool.prepareArguments) {
  602. return toolCall;
  603. }
  604. const preparedArguments = tool.prepareArguments(toolCall.arguments);
  605. if (preparedArguments === toolCall.arguments) {
  606. return toolCall;
  607. }
  608. return {
  609. ...toolCall,
  610. arguments: preparedArguments as Record<string, any>,
  611. };
  612. }
  613. async function prepareToolCall(
  614. currentContext: AgentContext,
  615. assistantMessage: AssistantMessage,
  616. toolCall: AgentToolCall,
  617. config: AgentLoopConfig,
  618. signal: AbortSignal | undefined,
  619. ): Promise<PreparedToolCall | ImmediateToolCallOutcome> {
  620. const tool = currentContext.tools?.find((t) => t.name === toolCall.name);
  621. if (!tool) {
  622. return {
  623. kind: "immediate",
  624. result: createErrorToolResult(`Tool ${toolCall.name} not found`),
  625. isError: true,
  626. };
  627. }
  628. try {
  629. const preparedToolCall = prepareToolCallArguments(tool, toolCall);
  630. const validatedArgs = validateToolArguments(tool, preparedToolCall);
  631. if (config.beforeToolCall) {
  632. const beforeResult = await config.beforeToolCall(
  633. {
  634. assistantMessage,
  635. toolCall,
  636. args: validatedArgs,
  637. context: currentContext,
  638. },
  639. signal,
  640. );
  641. if (signal?.aborted) {
  642. return {
  643. kind: "immediate",
  644. result: createErrorToolResult("Operation aborted"),
  645. isError: true,
  646. };
  647. }
  648. if (beforeResult?.block) {
  649. return {
  650. kind: "immediate",
  651. result: createErrorToolResult(beforeResult.reason || "Tool execution was blocked"),
  652. isError: true,
  653. terminateAgent: beforeResult.terminateAgent,
  654. };
  655. }
  656. }
  657. if (signal?.aborted) {
  658. return {
  659. kind: "immediate",
  660. result: createErrorToolResult("Operation aborted"),
  661. isError: true,
  662. };
  663. }
  664. return {
  665. kind: "prepared",
  666. toolCall,
  667. tool,
  668. args: validatedArgs,
  669. };
  670. } catch (error) {
  671. return {
  672. kind: "immediate",
  673. result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
  674. isError: true,
  675. };
  676. }
  677. }
  678. async function executePreparedToolCall(
  679. currentContext: AgentContext,
  680. assistantMessage: AssistantMessage,
  681. prepared: PreparedToolCall,
  682. config: AgentLoopConfig,
  683. signal: AbortSignal | undefined,
  684. emit: AgentEventSink,
  685. ): Promise<ExecutedToolCallOutcome> {
  686. const updateEvents: Promise<void>[] = [];
  687. try {
  688. config.onToolExecutionStart?.({
  689. assistantMessage,
  690. toolCall: prepared.toolCall,
  691. args: prepared.args,
  692. context: currentContext,
  693. });
  694. const result = await prepared.tool.execute(
  695. prepared.toolCall.id,
  696. prepared.args as never,
  697. signal,
  698. (partialResult) => {
  699. updateEvents.push(
  700. Promise.resolve(
  701. emit({
  702. type: "tool_execution_update",
  703. toolCallId: prepared.toolCall.id,
  704. toolName: prepared.toolCall.name,
  705. args: prepared.toolCall.arguments,
  706. partialResult,
  707. }),
  708. ),
  709. );
  710. },
  711. );
  712. await Promise.all(updateEvents);
  713. return { result, isError: false };
  714. } catch (error) {
  715. await Promise.all(updateEvents);
  716. return {
  717. result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
  718. isError: true,
  719. };
  720. }
  721. }
  722. async function finalizeExecutedToolCall(
  723. currentContext: AgentContext,
  724. assistantMessage: AssistantMessage,
  725. prepared: PreparedToolCall,
  726. executed: ExecutedToolCallOutcome,
  727. config: AgentLoopConfig,
  728. signal: AbortSignal | undefined,
  729. ): Promise<FinalizedToolCallOutcome> {
  730. let result = executed.result;
  731. let isError = executed.isError;
  732. let terminateAgent = false;
  733. if (config.afterToolCall) {
  734. try {
  735. const afterResult = await config.afterToolCall(
  736. {
  737. assistantMessage,
  738. toolCall: prepared.toolCall,
  739. args: prepared.args,
  740. result,
  741. isError,
  742. context: currentContext,
  743. },
  744. signal,
  745. );
  746. if (afterResult) {
  747. result = {
  748. content: afterResult.content ?? result.content,
  749. details: afterResult.details ?? result.details,
  750. terminate: afterResult.terminate ?? result.terminate,
  751. };
  752. isError = afterResult.isError ?? isError;
  753. terminateAgent = afterResult.terminateAgent === true;
  754. }
  755. } catch (error) {
  756. result = createErrorToolResult(error instanceof Error ? error.message : String(error));
  757. isError = true;
  758. }
  759. }
  760. return {
  761. toolCall: prepared.toolCall,
  762. result,
  763. isError,
  764. terminateAgent,
  765. };
  766. }
  767. function createErrorToolResult(message: string): AgentToolResult<any> {
  768. return {
  769. content: [{ type: "text", text: message }],
  770. details: {},
  771. };
  772. }
  773. async function emitToolExecutionEnd(finalized: FinalizedToolCallOutcome, emit: AgentEventSink): Promise<void> {
  774. await emit({
  775. type: "tool_execution_end",
  776. toolCallId: finalized.toolCall.id,
  777. toolName: finalized.toolCall.name,
  778. result: finalized.result,
  779. isError: finalized.isError,
  780. });
  781. }
  782. function createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {
  783. return {
  784. role: "toolResult",
  785. toolCallId: finalized.toolCall.id,
  786. toolName: finalized.toolCall.name,
  787. content: finalized.result.content,
  788. details: finalized.result.details,
  789. isError: finalized.isError,
  790. timestamp: Date.now(),
  791. };
  792. }
  793. async function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {
  794. await emit({ type: "message_start", message: toolResultMessage });
  795. await emit({ type: "message_end", message: toolResultMessage });
  796. }