agent-loop.test.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. import {
  2. type AssistantMessage,
  3. type AssistantMessageEvent,
  4. EventStream,
  5. type Message,
  6. type Model,
  7. type UserMessage,
  8. } from "@earendil-works/pi-ai";
  9. import { Type } from "typebox";
  10. import { describe, expect, it } from "vitest";
  11. import { agentLoop, agentLoopContinue } from "../src/agent-loop.ts";
  12. import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool } from "../src/types.ts";
  13. // Mock stream for testing - mimics MockAssistantStream
  14. class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
  15. constructor() {
  16. super(
  17. (event) => event.type === "done" || event.type === "error",
  18. (event) => {
  19. if (event.type === "done") return event.message;
  20. if (event.type === "error") return event.error;
  21. throw new Error("Unexpected event type");
  22. },
  23. );
  24. }
  25. }
  26. function createUsage() {
  27. return {
  28. input: 0,
  29. output: 0,
  30. cacheRead: 0,
  31. cacheWrite: 0,
  32. totalTokens: 0,
  33. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  34. };
  35. }
  36. function createModel(): Model<"openai-responses"> {
  37. return {
  38. id: "mock",
  39. name: "mock",
  40. api: "openai-responses",
  41. provider: "openai",
  42. baseUrl: "https://example.invalid",
  43. reasoning: false,
  44. input: ["text"],
  45. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  46. contextWindow: 8192,
  47. maxTokens: 2048,
  48. };
  49. }
  50. function createAssistantMessage(
  51. content: AssistantMessage["content"],
  52. stopReason: AssistantMessage["stopReason"] = "stop",
  53. ): AssistantMessage {
  54. return {
  55. role: "assistant",
  56. content,
  57. api: "openai-responses",
  58. provider: "openai",
  59. model: "mock",
  60. usage: createUsage(),
  61. stopReason,
  62. timestamp: Date.now(),
  63. };
  64. }
  65. function createUserMessage(text: string): UserMessage {
  66. return {
  67. role: "user",
  68. content: text,
  69. timestamp: Date.now(),
  70. };
  71. }
  72. // Simple identity converter for tests - just passes through standard messages
  73. function identityConverter(messages: AgentMessage[]): Message[] {
  74. return messages.filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
  75. }
  76. describe("agentLoop with AgentMessage", () => {
  77. it("should emit events with AgentMessage types", async () => {
  78. const context: AgentContext = {
  79. systemPrompt: "You are helpful.",
  80. messages: [],
  81. tools: [],
  82. };
  83. const userPrompt: AgentMessage = createUserMessage("Hello");
  84. const config: AgentLoopConfig = {
  85. model: createModel(),
  86. convertToLlm: identityConverter,
  87. };
  88. const streamFn = () => {
  89. const stream = new MockAssistantStream();
  90. queueMicrotask(() => {
  91. const message = createAssistantMessage([{ type: "text", text: "Hi there!" }]);
  92. stream.push({ type: "done", reason: "stop", message });
  93. });
  94. return stream;
  95. };
  96. const events: AgentEvent[] = [];
  97. const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
  98. for await (const event of stream) {
  99. events.push(event);
  100. }
  101. const messages = await stream.result();
  102. // Should have user message and assistant message
  103. expect(messages.length).toBe(2);
  104. expect(messages[0].role).toBe("user");
  105. expect(messages[1].role).toBe("assistant");
  106. // Verify event sequence
  107. const eventTypes = events.map((e) => e.type);
  108. expect(eventTypes).toContain("agent_start");
  109. expect(eventTypes).toContain("turn_start");
  110. expect(eventTypes).toContain("message_start");
  111. expect(eventTypes).toContain("message_end");
  112. expect(eventTypes).toContain("turn_end");
  113. expect(eventTypes).toContain("agent_end");
  114. });
  115. it("should handle custom message types via convertToLlm", async () => {
  116. // Create a custom message type
  117. interface CustomNotification {
  118. role: "notification";
  119. text: string;
  120. timestamp: number;
  121. }
  122. const notification: CustomNotification = {
  123. role: "notification",
  124. text: "This is a notification",
  125. timestamp: Date.now(),
  126. };
  127. const context: AgentContext = {
  128. systemPrompt: "You are helpful.",
  129. messages: [notification as unknown as AgentMessage], // Custom message in context
  130. tools: [],
  131. };
  132. const userPrompt: AgentMessage = createUserMessage("Hello");
  133. let convertedMessages: Message[] = [];
  134. const config: AgentLoopConfig = {
  135. model: createModel(),
  136. convertToLlm: (messages) => {
  137. // Filter out notifications, convert rest
  138. convertedMessages = messages
  139. .filter((m) => (m as { role: string }).role !== "notification")
  140. .filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
  141. return convertedMessages;
  142. },
  143. };
  144. const streamFn = () => {
  145. const stream = new MockAssistantStream();
  146. queueMicrotask(() => {
  147. const message = createAssistantMessage([{ type: "text", text: "Response" }]);
  148. stream.push({ type: "done", reason: "stop", message });
  149. });
  150. return stream;
  151. };
  152. const events: AgentEvent[] = [];
  153. const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
  154. for await (const event of stream) {
  155. events.push(event);
  156. }
  157. // The notification should have been filtered out in convertToLlm
  158. expect(convertedMessages.length).toBe(1); // Only user message
  159. expect(convertedMessages[0].role).toBe("user");
  160. });
  161. it("should apply transformContext before convertToLlm", async () => {
  162. const context: AgentContext = {
  163. systemPrompt: "You are helpful.",
  164. messages: [
  165. createUserMessage("old message 1"),
  166. createAssistantMessage([{ type: "text", text: "old response 1" }]),
  167. createUserMessage("old message 2"),
  168. createAssistantMessage([{ type: "text", text: "old response 2" }]),
  169. ],
  170. tools: [],
  171. };
  172. const userPrompt: AgentMessage = createUserMessage("new message");
  173. let transformedMessages: AgentMessage[] = [];
  174. let convertedMessages: Message[] = [];
  175. const config: AgentLoopConfig = {
  176. model: createModel(),
  177. transformContext: async (messages) => {
  178. // Keep only last 2 messages (prune old ones)
  179. transformedMessages = messages.slice(-2);
  180. return transformedMessages;
  181. },
  182. convertToLlm: (messages) => {
  183. convertedMessages = messages.filter(
  184. (m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult",
  185. ) as Message[];
  186. return convertedMessages;
  187. },
  188. };
  189. const streamFn = () => {
  190. const stream = new MockAssistantStream();
  191. queueMicrotask(() => {
  192. const message = createAssistantMessage([{ type: "text", text: "Response" }]);
  193. stream.push({ type: "done", reason: "stop", message });
  194. });
  195. return stream;
  196. };
  197. const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
  198. for await (const _ of stream) {
  199. // consume
  200. }
  201. // transformContext should have been called first, keeping only last 2
  202. expect(transformedMessages.length).toBe(2);
  203. // Then convertToLlm receives the pruned messages
  204. expect(convertedMessages.length).toBe(2);
  205. });
  206. it("should handle tool calls and results", async () => {
  207. const toolSchema = Type.Object({ value: Type.String() });
  208. const executed: string[] = [];
  209. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  210. name: "echo",
  211. label: "Echo",
  212. description: "Echo tool",
  213. parameters: toolSchema,
  214. async execute(_toolCallId, params) {
  215. executed.push(params.value);
  216. return {
  217. content: [{ type: "text", text: `echoed: ${params.value}` }],
  218. details: { value: params.value },
  219. };
  220. },
  221. };
  222. const context: AgentContext = {
  223. systemPrompt: "",
  224. messages: [],
  225. tools: [tool],
  226. };
  227. const userPrompt: AgentMessage = createUserMessage("echo something");
  228. const config: AgentLoopConfig = {
  229. model: createModel(),
  230. convertToLlm: identityConverter,
  231. };
  232. let callIndex = 0;
  233. const streamFn = () => {
  234. const stream = new MockAssistantStream();
  235. queueMicrotask(() => {
  236. if (callIndex === 0) {
  237. // First call: return tool call
  238. const message = createAssistantMessage(
  239. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
  240. "toolUse",
  241. );
  242. stream.push({ type: "done", reason: "toolUse", message });
  243. } else {
  244. // Second call: return final response
  245. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  246. stream.push({ type: "done", reason: "stop", message });
  247. }
  248. callIndex++;
  249. });
  250. return stream;
  251. };
  252. const events: AgentEvent[] = [];
  253. const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
  254. for await (const event of stream) {
  255. events.push(event);
  256. }
  257. // Tool should have been executed
  258. expect(executed).toEqual(["hello"]);
  259. // Should have tool execution events
  260. const toolStart = events.find((e) => e.type === "tool_execution_start");
  261. const toolEnd = events.find((e) => e.type === "tool_execution_end");
  262. expect(toolStart).toBeDefined();
  263. expect(toolEnd).toBeDefined();
  264. if (toolEnd?.type === "tool_execution_end") {
  265. expect(toolEnd.isError).toBe(false);
  266. }
  267. });
  268. it("should execute mutated beforeToolCall args without revalidation", async () => {
  269. const toolSchema = Type.Object({ value: Type.String() });
  270. const executed: Array<string | number> = [];
  271. const tool: AgentTool<typeof toolSchema, { value: string | number }> = {
  272. name: "echo",
  273. label: "Echo",
  274. description: "Echo tool",
  275. parameters: toolSchema,
  276. async execute(_toolCallId, params) {
  277. executed.push(params.value as string | number);
  278. return {
  279. content: [{ type: "text", text: `echoed: ${String(params.value)}` }],
  280. details: { value: params.value as string | number },
  281. };
  282. },
  283. };
  284. const context: AgentContext = {
  285. systemPrompt: "",
  286. messages: [],
  287. tools: [tool],
  288. };
  289. const userPrompt: AgentMessage = createUserMessage("echo something");
  290. const config: AgentLoopConfig = {
  291. model: createModel(),
  292. convertToLlm: identityConverter,
  293. beforeToolCall: async ({ args }) => {
  294. const mutableArgs = args as { value: string | number };
  295. mutableArgs.value = 123;
  296. return undefined;
  297. },
  298. };
  299. let callIndex = 0;
  300. const streamFn = () => {
  301. const stream = new MockAssistantStream();
  302. queueMicrotask(() => {
  303. if (callIndex === 0) {
  304. const message = createAssistantMessage(
  305. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
  306. "toolUse",
  307. );
  308. stream.push({ type: "done", reason: "toolUse", message });
  309. } else {
  310. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  311. stream.push({ type: "done", reason: "stop", message });
  312. }
  313. callIndex++;
  314. });
  315. return stream;
  316. };
  317. const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
  318. for await (const _event of stream) {
  319. // consume
  320. }
  321. expect(executed).toEqual([123]);
  322. });
  323. it("should prepare tool arguments for validation", async () => {
  324. const replaceSchema = Type.Object({ oldText: Type.String(), newText: Type.String() });
  325. const toolSchema = Type.Object({ edits: Type.Array(replaceSchema) });
  326. const executed: Array<Array<{ oldText: string; newText: string }>> = [];
  327. const tool: AgentTool<typeof toolSchema, { count: number }> = {
  328. name: "edit",
  329. label: "Edit",
  330. description: "Edit tool",
  331. parameters: toolSchema,
  332. prepareArguments(args) {
  333. if (!args || typeof args !== "object") {
  334. return args as { edits: { oldText: string; newText: string }[] };
  335. }
  336. const input = args as {
  337. edits?: Array<{ oldText: string; newText: string }>;
  338. oldText?: string;
  339. newText?: string;
  340. };
  341. if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
  342. return args as { edits: { oldText: string; newText: string }[] };
  343. }
  344. return {
  345. edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
  346. };
  347. },
  348. async execute(_toolCallId, params) {
  349. executed.push(params.edits);
  350. return {
  351. content: [{ type: "text", text: `edited ${params.edits.length}` }],
  352. details: { count: params.edits.length },
  353. };
  354. },
  355. };
  356. const context: AgentContext = {
  357. systemPrompt: "",
  358. messages: [],
  359. tools: [tool],
  360. };
  361. const userPrompt: AgentMessage = createUserMessage("edit something");
  362. const config: AgentLoopConfig = {
  363. model: createModel(),
  364. convertToLlm: identityConverter,
  365. };
  366. let callIndex = 0;
  367. const streamFn = () => {
  368. const stream = new MockAssistantStream();
  369. queueMicrotask(() => {
  370. if (callIndex === 0) {
  371. const message = createAssistantMessage(
  372. [
  373. {
  374. type: "toolCall",
  375. id: "tool-1",
  376. name: "edit",
  377. arguments: { oldText: "before", newText: "after" },
  378. },
  379. ],
  380. "toolUse",
  381. );
  382. stream.push({ type: "done", reason: "toolUse", message });
  383. } else {
  384. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  385. stream.push({ type: "done", reason: "stop", message });
  386. }
  387. callIndex++;
  388. });
  389. return stream;
  390. };
  391. const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
  392. for await (const _event of stream) {
  393. // consume
  394. }
  395. expect(executed).toEqual([[{ oldText: "before", newText: "after" }]]);
  396. });
  397. it("should emit tool_execution_end in completion order but persist tool results in source order", async () => {
  398. const toolSchema = Type.Object({ value: Type.String() });
  399. let firstResolved = false;
  400. let parallelObserved = false;
  401. let releaseFirst: (() => void) | undefined;
  402. const firstDone = new Promise<void>((resolve) => {
  403. releaseFirst = resolve;
  404. });
  405. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  406. name: "echo",
  407. label: "Echo",
  408. description: "Echo tool",
  409. parameters: toolSchema,
  410. async execute(_toolCallId, params) {
  411. if (params.value === "first") {
  412. await firstDone;
  413. firstResolved = true;
  414. }
  415. if (params.value === "second" && !firstResolved) {
  416. parallelObserved = true;
  417. }
  418. return {
  419. content: [{ type: "text", text: `echoed: ${params.value}` }],
  420. details: { value: params.value },
  421. };
  422. },
  423. };
  424. const context: AgentContext = {
  425. systemPrompt: "",
  426. messages: [],
  427. tools: [tool],
  428. };
  429. const userPrompt: AgentMessage = createUserMessage("echo both");
  430. const config: AgentLoopConfig = {
  431. model: createModel(),
  432. convertToLlm: identityConverter,
  433. toolExecution: "parallel",
  434. };
  435. let callIndex = 0;
  436. const stream = agentLoop([userPrompt], context, config, undefined, () => {
  437. const mockStream = new MockAssistantStream();
  438. queueMicrotask(() => {
  439. if (callIndex === 0) {
  440. const message = createAssistantMessage(
  441. [
  442. { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
  443. { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
  444. ],
  445. "toolUse",
  446. );
  447. mockStream.push({ type: "done", reason: "toolUse", message });
  448. setTimeout(() => releaseFirst?.(), 20);
  449. } else {
  450. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  451. mockStream.push({ type: "done", reason: "stop", message });
  452. }
  453. callIndex++;
  454. });
  455. return mockStream;
  456. });
  457. const events: AgentEvent[] = [];
  458. for await (const event of stream) {
  459. events.push(event);
  460. }
  461. const toolExecutionEndIds = events.flatMap((event) => {
  462. if (event.type !== "tool_execution_end") {
  463. return [];
  464. }
  465. return [event.toolCallId];
  466. });
  467. const toolResultIds = events.flatMap((event) => {
  468. if (event.type !== "message_end" || event.message.role !== "toolResult") {
  469. return [];
  470. }
  471. return [event.message.toolCallId];
  472. });
  473. const turnToolResultIds = events.flatMap((event) => {
  474. if (event.type !== "turn_end") {
  475. return [];
  476. }
  477. return event.toolResults.map((toolResult) => toolResult.toolCallId);
  478. });
  479. expect(parallelObserved).toBe(true);
  480. expect(toolExecutionEndIds).toEqual(["tool-2", "tool-1"]);
  481. expect(toolResultIds).toEqual(["tool-1", "tool-2"]);
  482. expect(turnToolResultIds).toEqual(["tool-1", "tool-2"]);
  483. });
  484. it("should inject queued messages after all tool calls complete", async () => {
  485. const toolSchema = Type.Object({ value: Type.String() });
  486. const executed: string[] = [];
  487. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  488. name: "echo",
  489. label: "Echo",
  490. description: "Echo tool",
  491. parameters: toolSchema,
  492. async execute(_toolCallId, params) {
  493. executed.push(params.value);
  494. return {
  495. content: [{ type: "text", text: `ok:${params.value}` }],
  496. details: { value: params.value },
  497. };
  498. },
  499. };
  500. const context: AgentContext = {
  501. systemPrompt: "",
  502. messages: [],
  503. tools: [tool],
  504. };
  505. const userPrompt: AgentMessage = createUserMessage("start");
  506. const queuedUserMessage: AgentMessage = createUserMessage("interrupt");
  507. let queuedDelivered = false;
  508. let callIndex = 0;
  509. let sawInterruptInContext = false;
  510. const config: AgentLoopConfig = {
  511. model: createModel(),
  512. convertToLlm: identityConverter,
  513. toolExecution: "sequential",
  514. getSteeringMessages: async () => {
  515. // Return steering message after tool execution has started.
  516. if (executed.length >= 1 && !queuedDelivered) {
  517. queuedDelivered = true;
  518. return [queuedUserMessage];
  519. }
  520. return [];
  521. },
  522. };
  523. const events: AgentEvent[] = [];
  524. const stream = agentLoop([userPrompt], context, config, undefined, (_model, ctx, _options) => {
  525. // Check if interrupt message is in context on second call
  526. if (callIndex === 1) {
  527. sawInterruptInContext = ctx.messages.some(
  528. (m) => m.role === "user" && typeof m.content === "string" && m.content === "interrupt",
  529. );
  530. }
  531. const mockStream = new MockAssistantStream();
  532. queueMicrotask(() => {
  533. if (callIndex === 0) {
  534. // First call: return two tool calls
  535. const message = createAssistantMessage(
  536. [
  537. { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
  538. { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
  539. ],
  540. "toolUse",
  541. );
  542. mockStream.push({ type: "done", reason: "toolUse", message });
  543. } else {
  544. // Second call: return final response
  545. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  546. mockStream.push({ type: "done", reason: "stop", message });
  547. }
  548. callIndex++;
  549. });
  550. return mockStream;
  551. });
  552. for await (const event of stream) {
  553. events.push(event);
  554. }
  555. // Both tools should execute before steering is injected
  556. expect(executed).toEqual(["first", "second"]);
  557. const toolEnds = events.filter(
  558. (e): e is Extract<AgentEvent, { type: "tool_execution_end" }> => e.type === "tool_execution_end",
  559. );
  560. expect(toolEnds.length).toBe(2);
  561. expect(toolEnds[0].isError).toBe(false);
  562. expect(toolEnds[1].isError).toBe(false);
  563. // Queued message should appear in events after both tool result messages
  564. const eventSequence = events.flatMap((event) => {
  565. if (event.type !== "message_start") return [];
  566. if (event.message.role === "toolResult") return [`tool:${event.message.toolCallId}`];
  567. if (event.message.role === "user" && typeof event.message.content === "string") {
  568. return [event.message.content];
  569. }
  570. return [];
  571. });
  572. expect(eventSequence).toContain("interrupt");
  573. expect(eventSequence.indexOf("tool:tool-1")).toBeLessThan(eventSequence.indexOf("interrupt"));
  574. expect(eventSequence.indexOf("tool:tool-2")).toBeLessThan(eventSequence.indexOf("interrupt"));
  575. // Interrupt message should be in context when second LLM call is made
  576. expect(sawInterruptInContext).toBe(true);
  577. });
  578. it("should force sequential execution when a tool has executionMode=sequential even with default parallel config", async () => {
  579. const toolSchema = Type.Object({ value: Type.String() });
  580. let firstResolved = false;
  581. let parallelObserved = false;
  582. let releaseFirst: (() => void) | undefined;
  583. const firstDone = new Promise<void>((resolve) => {
  584. releaseFirst = resolve;
  585. });
  586. const slowTool: AgentTool<typeof toolSchema, { value: string }> = {
  587. name: "slow",
  588. label: "Slow",
  589. description: "Slow tool",
  590. parameters: toolSchema,
  591. executionMode: "sequential",
  592. async execute(_toolCallId, params) {
  593. if (params.value === "first") {
  594. await firstDone;
  595. firstResolved = true;
  596. }
  597. if (params.value === "second" && !firstResolved) {
  598. parallelObserved = true;
  599. }
  600. return {
  601. content: [{ type: "text", text: `slow: ${params.value}` }],
  602. details: { value: params.value },
  603. };
  604. },
  605. };
  606. const context: AgentContext = {
  607. systemPrompt: "",
  608. messages: [],
  609. tools: [slowTool],
  610. };
  611. const userPrompt: AgentMessage = createUserMessage("run both");
  612. // config is parallel (default), but tool forces sequential
  613. const config: AgentLoopConfig = {
  614. model: createModel(),
  615. convertToLlm: identityConverter,
  616. };
  617. let callIndex = 0;
  618. const stream = agentLoop([userPrompt], context, config, undefined, () => {
  619. const mockStream = new MockAssistantStream();
  620. queueMicrotask(() => {
  621. if (callIndex === 0) {
  622. const message = createAssistantMessage(
  623. [
  624. { type: "toolCall", id: "tool-1", name: "slow", arguments: { value: "first" } },
  625. { type: "toolCall", id: "tool-2", name: "slow", arguments: { value: "second" } },
  626. ],
  627. "toolUse",
  628. );
  629. mockStream.push({ type: "done", reason: "toolUse", message });
  630. setTimeout(() => releaseFirst?.(), 20);
  631. } else {
  632. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  633. mockStream.push({ type: "done", reason: "stop", message });
  634. }
  635. callIndex++;
  636. });
  637. return mockStream;
  638. });
  639. const events: AgentEvent[] = [];
  640. for await (const event of stream) {
  641. events.push(event);
  642. }
  643. // With sequential execution, second tool should NOT start before first finishes
  644. expect(parallelObserved).toBe(false);
  645. const toolResultIds = events.flatMap((event) => {
  646. if (event.type !== "message_end" || event.message.role !== "toolResult") {
  647. return [];
  648. }
  649. return [event.message.toolCallId];
  650. });
  651. expect(toolResultIds).toEqual(["tool-1", "tool-2"]);
  652. });
  653. it("should force sequential execution when one of multiple tools has executionMode=sequential", async () => {
  654. const toolSchema = Type.Object({ value: Type.String() });
  655. const executionOrder: string[] = [];
  656. let releaseSlow: (() => void) | undefined;
  657. const slowDone = new Promise<void>((resolve) => {
  658. releaseSlow = resolve;
  659. });
  660. const slowTool: AgentTool<typeof toolSchema, { value: string }> = {
  661. name: "slow",
  662. label: "Slow",
  663. description: "Slow tool",
  664. parameters: toolSchema,
  665. executionMode: "sequential",
  666. async execute(_toolCallId, params) {
  667. executionOrder.push(`slow:${params.value}`);
  668. if (params.value === "a") {
  669. await slowDone;
  670. }
  671. return {
  672. content: [{ type: "text", text: `slow: ${params.value}` }],
  673. details: { value: params.value },
  674. };
  675. },
  676. };
  677. const fastTool: AgentTool<typeof toolSchema, { value: string }> = {
  678. name: "fast",
  679. label: "Fast",
  680. description: "Fast tool",
  681. parameters: toolSchema,
  682. // no executionMode = defaults to parallel
  683. async execute(_toolCallId, params) {
  684. executionOrder.push(`fast:${params.value}`);
  685. return {
  686. content: [{ type: "text", text: `fast: ${params.value}` }],
  687. details: { value: params.value },
  688. };
  689. },
  690. };
  691. const context: AgentContext = {
  692. systemPrompt: "",
  693. messages: [],
  694. tools: [slowTool, fastTool],
  695. };
  696. const userPrompt: AgentMessage = createUserMessage("run both");
  697. const config: AgentLoopConfig = {
  698. model: createModel(),
  699. convertToLlm: identityConverter,
  700. // parallel by default, but slowTool forces sequential
  701. };
  702. let callIndex = 0;
  703. const stream = agentLoop([userPrompt], context, config, undefined, () => {
  704. const mockStream = new MockAssistantStream();
  705. queueMicrotask(() => {
  706. if (callIndex === 0) {
  707. const message = createAssistantMessage(
  708. [
  709. { type: "toolCall", id: "tool-1", name: "slow", arguments: { value: "a" } },
  710. { type: "toolCall", id: "tool-2", name: "fast", arguments: { value: "b" } },
  711. ],
  712. "toolUse",
  713. );
  714. mockStream.push({ type: "done", reason: "toolUse", message });
  715. setTimeout(() => releaseSlow?.(), 20);
  716. } else {
  717. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  718. mockStream.push({ type: "done", reason: "stop", message });
  719. }
  720. callIndex++;
  721. });
  722. return mockStream;
  723. });
  724. const events: AgentEvent[] = [];
  725. for await (const event of stream) {
  726. events.push(event);
  727. }
  728. // Fast tool should NOT run before slow tool finishes
  729. expect(executionOrder[0]).toBe("slow:a");
  730. expect(executionOrder).toContain("fast:b");
  731. });
  732. it("should allow parallel execution when all tools have executionMode=parallel", async () => {
  733. const toolSchema = Type.Object({ value: Type.String() });
  734. let firstResolved = false;
  735. let parallelObserved = false;
  736. let releaseFirst: (() => void) | undefined;
  737. const firstDone = new Promise<void>((resolve) => {
  738. releaseFirst = resolve;
  739. });
  740. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  741. name: "echo",
  742. label: "Echo",
  743. description: "Echo tool",
  744. parameters: toolSchema,
  745. executionMode: "parallel",
  746. async execute(_toolCallId, params) {
  747. if (params.value === "first") {
  748. await firstDone;
  749. firstResolved = true;
  750. }
  751. if (params.value === "second" && !firstResolved) {
  752. parallelObserved = true;
  753. }
  754. return {
  755. content: [{ type: "text", text: `echoed: ${params.value}` }],
  756. details: { value: params.value },
  757. };
  758. },
  759. };
  760. const context: AgentContext = {
  761. systemPrompt: "",
  762. messages: [],
  763. tools: [tool],
  764. };
  765. const userPrompt: AgentMessage = createUserMessage("echo both");
  766. const config: AgentLoopConfig = {
  767. model: createModel(),
  768. convertToLlm: identityConverter,
  769. };
  770. let callIndex = 0;
  771. const stream = agentLoop([userPrompt], context, config, undefined, () => {
  772. const mockStream = new MockAssistantStream();
  773. queueMicrotask(() => {
  774. if (callIndex === 0) {
  775. const message = createAssistantMessage(
  776. [
  777. { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
  778. { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
  779. ],
  780. "toolUse",
  781. );
  782. mockStream.push({ type: "done", reason: "toolUse", message });
  783. setTimeout(() => releaseFirst?.(), 20);
  784. } else {
  785. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  786. mockStream.push({ type: "done", reason: "stop", message });
  787. }
  788. callIndex++;
  789. });
  790. return mockStream;
  791. });
  792. const events: AgentEvent[] = [];
  793. for await (const event of stream) {
  794. events.push(event);
  795. }
  796. // With executionMode=parallel, second tool should start before first finishes
  797. expect(parallelObserved).toBe(true);
  798. });
  799. it("should use prepareNextTurn snapshot before continuing", async () => {
  800. const toolSchema = Type.Object({ value: Type.String() });
  801. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  802. name: "echo",
  803. label: "Echo",
  804. description: "Echo tool",
  805. parameters: toolSchema,
  806. async execute(_toolCallId, params) {
  807. return {
  808. content: [{ type: "text", text: `echoed: ${params.value}` }],
  809. details: { value: params.value },
  810. };
  811. },
  812. };
  813. const context: AgentContext = {
  814. systemPrompt: "first prompt",
  815. messages: [],
  816. tools: [tool],
  817. };
  818. let convertedSecondTurnSystemPrompt = "";
  819. let prepared = false;
  820. const config: AgentLoopConfig = {
  821. model: createModel(),
  822. convertToLlm: identityConverter,
  823. prepareNextTurn: async ({ context: currentContext }) => {
  824. if (prepared) return undefined;
  825. prepared = true;
  826. return {
  827. context: {
  828. systemPrompt: "second prompt",
  829. messages: currentContext.messages.slice(),
  830. tools: currentContext.tools,
  831. },
  832. };
  833. },
  834. };
  835. let llmCalls = 0;
  836. const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, (_model, ctx) => {
  837. llmCalls++;
  838. if (llmCalls === 2) {
  839. convertedSecondTurnSystemPrompt = ctx.systemPrompt ?? "";
  840. }
  841. const mockStream = new MockAssistantStream();
  842. queueMicrotask(() => {
  843. if (llmCalls === 1) {
  844. mockStream.push({
  845. type: "done",
  846. reason: "toolUse",
  847. message: createAssistantMessage(
  848. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
  849. "toolUse",
  850. ),
  851. });
  852. } else {
  853. mockStream.push({
  854. type: "done",
  855. reason: "stop",
  856. message: createAssistantMessage([{ type: "text", text: "done" }]),
  857. });
  858. }
  859. });
  860. return mockStream;
  861. });
  862. for await (const _event of stream) {
  863. // consume
  864. }
  865. expect(llmCalls).toBe(2);
  866. expect(convertedSecondTurnSystemPrompt).toBe("second prompt");
  867. });
  868. it("should stop after the current turn when shouldStopAfterTurn returns true", async () => {
  869. const toolSchema = Type.Object({ value: Type.String() });
  870. const executed: string[] = [];
  871. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  872. name: "echo",
  873. label: "Echo",
  874. description: "Echo tool",
  875. parameters: toolSchema,
  876. async execute(_toolCallId, params) {
  877. executed.push(params.value);
  878. return {
  879. content: [{ type: "text", text: `echoed: ${params.value}` }],
  880. details: { value: params.value },
  881. };
  882. },
  883. };
  884. const context: AgentContext = {
  885. systemPrompt: "",
  886. messages: [],
  887. tools: [tool],
  888. };
  889. let steeringPolls = 0;
  890. let followUpPolls = 0;
  891. let callbackToolResultIds: string[] = [];
  892. let callbackContextRoles: string[] = [];
  893. const config: AgentLoopConfig = {
  894. model: createModel(),
  895. convertToLlm: identityConverter,
  896. getSteeringMessages: async () => {
  897. steeringPolls++;
  898. return [];
  899. },
  900. getFollowUpMessages: async () => {
  901. followUpPolls++;
  902. return [createUserMessage("follow up should stay queued")];
  903. },
  904. shouldStopAfterTurn: async ({ message, toolResults, context }) => {
  905. expect(message.role).toBe("assistant");
  906. callbackToolResultIds = toolResults.map((toolResult) => toolResult.toolCallId);
  907. callbackContextRoles = context.messages.map((contextMessage) => contextMessage.role);
  908. return true;
  909. },
  910. };
  911. let llmCalls = 0;
  912. const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, () => {
  913. llmCalls++;
  914. const mockStream = new MockAssistantStream();
  915. queueMicrotask(() => {
  916. if (llmCalls === 1) {
  917. const message = createAssistantMessage(
  918. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
  919. "toolUse",
  920. );
  921. mockStream.push({ type: "done", reason: "toolUse", message });
  922. } else {
  923. mockStream.push({
  924. type: "done",
  925. reason: "stop",
  926. message: createAssistantMessage([{ type: "text", text: "should not run" }]),
  927. });
  928. }
  929. });
  930. return mockStream;
  931. });
  932. const events: AgentEvent[] = [];
  933. for await (const event of stream) {
  934. events.push(event);
  935. }
  936. const messages = await stream.result();
  937. expect(llmCalls).toBe(1);
  938. expect(executed).toEqual(["hello"]);
  939. expect(steeringPolls).toBe(1);
  940. expect(followUpPolls).toBe(0);
  941. expect(callbackToolResultIds).toEqual(["tool-1"]);
  942. expect(callbackContextRoles).toEqual(["user", "assistant", "toolResult"]);
  943. expect(messages.map((message) => message.role)).toEqual(["user", "assistant", "toolResult"]);
  944. expect(events.map((event) => event.type)).toEqual([
  945. "agent_start",
  946. "turn_start",
  947. "message_start",
  948. "message_end",
  949. "message_start",
  950. "message_end",
  951. "tool_execution_start",
  952. "tool_execution_end",
  953. "message_start",
  954. "message_end",
  955. "turn_end",
  956. "agent_end",
  957. ]);
  958. });
  959. it("should stop after a tool batch when every tool result sets terminate=true", async () => {
  960. const toolSchema = Type.Object({ value: Type.String() });
  961. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  962. name: "echo",
  963. label: "Echo",
  964. description: "Echo tool",
  965. parameters: toolSchema,
  966. async execute(_toolCallId, params) {
  967. return {
  968. content: [{ type: "text", text: `echoed: ${params.value}` }],
  969. details: { value: params.value },
  970. terminate: true,
  971. };
  972. },
  973. };
  974. const context: AgentContext = {
  975. systemPrompt: "",
  976. messages: [],
  977. tools: [tool],
  978. };
  979. const config: AgentLoopConfig = {
  980. model: createModel(),
  981. convertToLlm: identityConverter,
  982. };
  983. let llmCalls = 0;
  984. const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, () => {
  985. llmCalls++;
  986. const mockStream = new MockAssistantStream();
  987. queueMicrotask(() => {
  988. const message = createAssistantMessage(
  989. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
  990. "toolUse",
  991. );
  992. mockStream.push({ type: "done", reason: "toolUse", message });
  993. });
  994. return mockStream;
  995. });
  996. const events: AgentEvent[] = [];
  997. for await (const event of stream) {
  998. events.push(event);
  999. }
  1000. const messages = await stream.result();
  1001. expect(llmCalls).toBe(1);
  1002. expect(messages.map((message) => message.role)).toEqual(["user", "assistant", "toolResult"]);
  1003. expect(events.filter((event) => event.type === "turn_end")).toHaveLength(1);
  1004. });
  1005. it("should continue after parallel tool calls when not all tool results terminate", async () => {
  1006. const toolSchema = Type.Object({ value: Type.String() });
  1007. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  1008. name: "echo",
  1009. label: "Echo",
  1010. description: "Echo tool",
  1011. parameters: toolSchema,
  1012. async execute(_toolCallId, params) {
  1013. return {
  1014. content: [{ type: "text", text: `echoed: ${params.value}` }],
  1015. details: { value: params.value },
  1016. terminate: params.value === "first",
  1017. };
  1018. },
  1019. };
  1020. const context: AgentContext = {
  1021. systemPrompt: "",
  1022. messages: [],
  1023. tools: [tool],
  1024. };
  1025. const config: AgentLoopConfig = {
  1026. model: createModel(),
  1027. convertToLlm: identityConverter,
  1028. toolExecution: "parallel",
  1029. };
  1030. let callIndex = 0;
  1031. const stream = agentLoop([createUserMessage("echo both")], context, config, undefined, () => {
  1032. const mockStream = new MockAssistantStream();
  1033. queueMicrotask(() => {
  1034. if (callIndex === 0) {
  1035. const message = createAssistantMessage(
  1036. [
  1037. { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
  1038. { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
  1039. ],
  1040. "toolUse",
  1041. );
  1042. mockStream.push({ type: "done", reason: "toolUse", message });
  1043. } else {
  1044. const message = createAssistantMessage([{ type: "text", text: "done" }]);
  1045. mockStream.push({ type: "done", reason: "stop", message });
  1046. }
  1047. callIndex++;
  1048. });
  1049. return mockStream;
  1050. });
  1051. for await (const _event of stream) {
  1052. // consume
  1053. }
  1054. const messages = await stream.result();
  1055. expect(callIndex).toBe(2);
  1056. expect(messages.map((message) => message.role)).toEqual([
  1057. "user",
  1058. "assistant",
  1059. "toolResult",
  1060. "toolResult",
  1061. "assistant",
  1062. ]);
  1063. });
  1064. it("should not execute later sequential calls after a hook requests global termination", async () => {
  1065. const toolSchema = Type.Object({ value: Type.String() });
  1066. const executed: string[] = [];
  1067. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  1068. name: "echo",
  1069. label: "Echo",
  1070. description: "Echo tool",
  1071. parameters: toolSchema,
  1072. async execute(_toolCallId, params) {
  1073. executed.push(params.value);
  1074. return { content: [{ type: "text", text: params.value }], details: {} };
  1075. },
  1076. };
  1077. let llmCalls = 0;
  1078. const stream = agentLoop(
  1079. [createUserMessage("echo both")],
  1080. { systemPrompt: "", messages: [], tools: [tool] },
  1081. {
  1082. model: createModel(),
  1083. convertToLlm: identityConverter,
  1084. toolExecution: "sequential",
  1085. beforeToolCall: async ({ toolCall }) =>
  1086. toolCall.id === "tool-1"
  1087. ? { block: true, reason: "stop now", terminateAgent: true }
  1088. : undefined,
  1089. },
  1090. undefined,
  1091. () => {
  1092. llmCalls += 1;
  1093. const mockStream = new MockAssistantStream();
  1094. queueMicrotask(() => {
  1095. mockStream.push({
  1096. type: "done",
  1097. reason: "toolUse",
  1098. message: createAssistantMessage(
  1099. [
  1100. { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
  1101. { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
  1102. ],
  1103. "toolUse",
  1104. ),
  1105. });
  1106. });
  1107. return mockStream;
  1108. },
  1109. );
  1110. for await (const _event of stream) {
  1111. // consume
  1112. }
  1113. expect(llmCalls).toBe(1);
  1114. expect(executed).toEqual([]);
  1115. const toolResults = (await stream.result()).filter((message) => message.role === "toolResult");
  1116. expect(toolResults).toHaveLength(2);
  1117. expect(toolResults[1]).toMatchObject({
  1118. toolCallId: "tool-2",
  1119. isError: true,
  1120. content: [{ type: "text", text: expect.stringContaining("skipped") }],
  1121. });
  1122. });
  1123. it("should observe execution start only after before-tool admission succeeds", async () => {
  1124. const toolSchema = Type.Object({ value: Type.String() });
  1125. const order: string[] = [];
  1126. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  1127. name: "echo",
  1128. label: "Echo",
  1129. description: "Echo tool",
  1130. parameters: toolSchema,
  1131. async execute(_toolCallId, params) {
  1132. order.push("execute");
  1133. return { content: [{ type: "text", text: params.value }], details: {} };
  1134. },
  1135. };
  1136. const stream = agentLoop(
  1137. [createUserMessage("echo")],
  1138. { systemPrompt: "", messages: [], tools: [tool] },
  1139. {
  1140. model: createModel(),
  1141. convertToLlm: identityConverter,
  1142. beforeToolCall: async () => {
  1143. order.push("before");
  1144. return undefined;
  1145. },
  1146. onToolExecutionStart: () => order.push("execution-start"),
  1147. afterToolCall: async () => {
  1148. order.push("after");
  1149. return { terminate: true };
  1150. },
  1151. },
  1152. undefined,
  1153. () => {
  1154. const mockStream = new MockAssistantStream();
  1155. queueMicrotask(() => {
  1156. mockStream.push({
  1157. type: "done",
  1158. reason: "toolUse",
  1159. message: createAssistantMessage(
  1160. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "one" } }],
  1161. "toolUse",
  1162. ),
  1163. });
  1164. });
  1165. return mockStream;
  1166. },
  1167. );
  1168. for await (const _event of stream) {
  1169. // consume
  1170. }
  1171. expect(order).toEqual(["before", "execution-start", "execute", "after"]);
  1172. });
  1173. it("should stop every prepared parallel call when a later blocked call requests global termination", async () => {
  1174. const toolSchema = Type.Object({ value: Type.String() });
  1175. const executed: string[] = [];
  1176. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  1177. name: "echo",
  1178. label: "Echo",
  1179. description: "Echo tool",
  1180. parameters: toolSchema,
  1181. async execute(_toolCallId, params) {
  1182. executed.push(params.value);
  1183. return { content: [{ type: "text", text: params.value }], details: {} };
  1184. },
  1185. };
  1186. const context: AgentContext = { systemPrompt: "", messages: [], tools: [tool] };
  1187. let llmCalls = 0;
  1188. const stream = agentLoop(
  1189. [createUserMessage("echo both")],
  1190. context,
  1191. {
  1192. model: createModel(),
  1193. convertToLlm: identityConverter,
  1194. toolExecution: "parallel",
  1195. beforeToolCall: async ({ toolCall }) =>
  1196. toolCall.id === "tool-2" ? { block: true, reason: "stop now", terminateAgent: true } : undefined,
  1197. },
  1198. undefined,
  1199. () => {
  1200. llmCalls += 1;
  1201. const mockStream = new MockAssistantStream();
  1202. queueMicrotask(() => {
  1203. mockStream.push({
  1204. type: "done",
  1205. reason: "toolUse",
  1206. message: createAssistantMessage(
  1207. [
  1208. { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
  1209. { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
  1210. ],
  1211. "toolUse",
  1212. ),
  1213. });
  1214. });
  1215. return mockStream;
  1216. },
  1217. );
  1218. for await (const _event of stream) {
  1219. // consume
  1220. }
  1221. expect(llmCalls).toBe(1);
  1222. expect(executed).toEqual([]);
  1223. expect((await stream.result()).filter((message) => message.role === "toolResult")).toHaveLength(2);
  1224. });
  1225. it("should keep an ordinary blocked tool call non-terminal", async () => {
  1226. const toolSchema = Type.Object({ value: Type.String() });
  1227. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  1228. name: "echo",
  1229. label: "Echo",
  1230. description: "Echo tool",
  1231. parameters: toolSchema,
  1232. async execute(_toolCallId, params) {
  1233. return { content: [{ type: "text", text: params.value }], details: {} };
  1234. },
  1235. };
  1236. let llmCalls = 0;
  1237. const stream = agentLoop(
  1238. [createUserMessage("echo")],
  1239. { systemPrompt: "", messages: [], tools: [tool] },
  1240. {
  1241. model: createModel(),
  1242. convertToLlm: identityConverter,
  1243. beforeToolCall: async () => ({ block: true, reason: "ordinary block" }),
  1244. },
  1245. undefined,
  1246. () => {
  1247. llmCalls += 1;
  1248. const mockStream = new MockAssistantStream();
  1249. queueMicrotask(() => {
  1250. const message =
  1251. llmCalls === 1
  1252. ? createAssistantMessage(
  1253. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } }],
  1254. "toolUse",
  1255. )
  1256. : createAssistantMessage([{ type: "text", text: "done" }]);
  1257. mockStream.push({ type: "done", reason: message.stopReason, message });
  1258. });
  1259. return mockStream;
  1260. },
  1261. );
  1262. for await (const _event of stream) {
  1263. // consume
  1264. }
  1265. expect(llmCalls).toBe(2);
  1266. });
  1267. it("should stop a mixed parallel batch when one after-tool hook requests global termination", async () => {
  1268. const toolSchema = Type.Object({ value: Type.String() });
  1269. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  1270. name: "echo",
  1271. label: "Echo",
  1272. description: "Echo tool",
  1273. parameters: toolSchema,
  1274. async execute(_toolCallId, params) {
  1275. return { content: [{ type: "text", text: params.value }], details: {} };
  1276. },
  1277. };
  1278. let llmCalls = 0;
  1279. const stream = agentLoop(
  1280. [createUserMessage("echo both")],
  1281. { systemPrompt: "", messages: [], tools: [tool] },
  1282. {
  1283. model: createModel(),
  1284. convertToLlm: identityConverter,
  1285. toolExecution: "parallel",
  1286. afterToolCall: async ({ toolCall }) => ({ terminateAgent: toolCall.id === "tool-1" }),
  1287. },
  1288. undefined,
  1289. () => {
  1290. llmCalls += 1;
  1291. const mockStream = new MockAssistantStream();
  1292. queueMicrotask(() => {
  1293. mockStream.push({
  1294. type: "done",
  1295. reason: "toolUse",
  1296. message: createAssistantMessage(
  1297. [
  1298. { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
  1299. { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
  1300. ],
  1301. "toolUse",
  1302. ),
  1303. });
  1304. });
  1305. return mockStream;
  1306. },
  1307. );
  1308. for await (const _event of stream) {
  1309. // consume
  1310. }
  1311. expect(llmCalls).toBe(1);
  1312. });
  1313. it("should allow afterToolCall to mark a tool batch as terminating", async () => {
  1314. const toolSchema = Type.Object({ value: Type.String() });
  1315. const tool: AgentTool<typeof toolSchema, { value: string }> = {
  1316. name: "echo",
  1317. label: "Echo",
  1318. description: "Echo tool",
  1319. parameters: toolSchema,
  1320. async execute(_toolCallId, params) {
  1321. return {
  1322. content: [{ type: "text", text: `echoed: ${params.value}` }],
  1323. details: { value: params.value },
  1324. };
  1325. },
  1326. };
  1327. const context: AgentContext = {
  1328. systemPrompt: "",
  1329. messages: [],
  1330. tools: [tool],
  1331. };
  1332. const config: AgentLoopConfig = {
  1333. model: createModel(),
  1334. convertToLlm: identityConverter,
  1335. afterToolCall: async () => ({ terminate: true }),
  1336. };
  1337. let llmCalls = 0;
  1338. const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, () => {
  1339. llmCalls++;
  1340. const mockStream = new MockAssistantStream();
  1341. queueMicrotask(() => {
  1342. const message = createAssistantMessage(
  1343. [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
  1344. "toolUse",
  1345. );
  1346. mockStream.push({ type: "done", reason: "toolUse", message });
  1347. });
  1348. return mockStream;
  1349. });
  1350. for await (const _event of stream) {
  1351. // consume
  1352. }
  1353. expect(llmCalls).toBe(1);
  1354. });
  1355. });
  1356. describe("agentLoopContinue with AgentMessage", () => {
  1357. it("should throw when context has no messages", () => {
  1358. const context: AgentContext = {
  1359. systemPrompt: "You are helpful.",
  1360. messages: [],
  1361. tools: [],
  1362. };
  1363. const config: AgentLoopConfig = {
  1364. model: createModel(),
  1365. convertToLlm: identityConverter,
  1366. };
  1367. expect(() => agentLoopContinue(context, config)).toThrow("Cannot continue: no messages in context");
  1368. });
  1369. it("should continue from existing context without emitting user message events", async () => {
  1370. const userMessage: AgentMessage = createUserMessage("Hello");
  1371. const context: AgentContext = {
  1372. systemPrompt: "You are helpful.",
  1373. messages: [userMessage],
  1374. tools: [],
  1375. };
  1376. const config: AgentLoopConfig = {
  1377. model: createModel(),
  1378. convertToLlm: identityConverter,
  1379. };
  1380. const streamFn = () => {
  1381. const stream = new MockAssistantStream();
  1382. queueMicrotask(() => {
  1383. const message = createAssistantMessage([{ type: "text", text: "Response" }]);
  1384. stream.push({ type: "done", reason: "stop", message });
  1385. });
  1386. return stream;
  1387. };
  1388. const events: AgentEvent[] = [];
  1389. const stream = agentLoopContinue(context, config, undefined, streamFn);
  1390. for await (const event of stream) {
  1391. events.push(event);
  1392. }
  1393. const messages = await stream.result();
  1394. // Should only return the new assistant message (not the existing user message)
  1395. expect(messages.length).toBe(1);
  1396. expect(messages[0].role).toBe("assistant");
  1397. // Should NOT have user message events (that's the key difference from agentLoop)
  1398. const messageEndEvents = events.filter((e) => e.type === "message_end");
  1399. expect(messageEndEvents.length).toBe(1);
  1400. expect((messageEndEvents[0] as any).message.role).toBe("assistant");
  1401. });
  1402. it("should allow custom message types as last message (caller responsibility)", async () => {
  1403. // Custom message that will be converted to user message by convertToLlm
  1404. interface CustomMessage {
  1405. role: "custom";
  1406. text: string;
  1407. timestamp: number;
  1408. }
  1409. const customMessage: CustomMessage = {
  1410. role: "custom",
  1411. text: "Hook content",
  1412. timestamp: Date.now(),
  1413. };
  1414. const context: AgentContext = {
  1415. systemPrompt: "You are helpful.",
  1416. messages: [customMessage as unknown as AgentMessage],
  1417. tools: [],
  1418. };
  1419. const config: AgentLoopConfig = {
  1420. model: createModel(),
  1421. convertToLlm: (messages) => {
  1422. // Convert custom to user message
  1423. return messages
  1424. .map((m) => {
  1425. if ((m as any).role === "custom") {
  1426. return {
  1427. role: "user" as const,
  1428. content: (m as any).text,
  1429. timestamp: m.timestamp,
  1430. };
  1431. }
  1432. return m;
  1433. })
  1434. .filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
  1435. },
  1436. };
  1437. const streamFn = () => {
  1438. const stream = new MockAssistantStream();
  1439. queueMicrotask(() => {
  1440. const message = createAssistantMessage([{ type: "text", text: "Response to custom message" }]);
  1441. stream.push({ type: "done", reason: "stop", message });
  1442. });
  1443. return stream;
  1444. };
  1445. // Should not throw - the custom message will be converted to user message
  1446. const stream = agentLoopContinue(context, config, undefined, streamFn);
  1447. const events: AgentEvent[] = [];
  1448. for await (const event of stream) {
  1449. events.push(event);
  1450. }
  1451. const messages = await stream.result();
  1452. expect(messages.length).toBe(1);
  1453. expect(messages[0].role).toBe("assistant");
  1454. });
  1455. });