| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614 |
- import {
- type AssistantMessage,
- type AssistantMessageEvent,
- EventStream,
- type Message,
- type Model,
- type UserMessage,
- } from "@earendil-works/pi-ai";
- import { Type } from "typebox";
- import { describe, expect, it } from "vitest";
- import { agentLoop, agentLoopContinue } from "../src/agent-loop.ts";
- import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool } from "../src/types.ts";
- // Mock stream for testing - mimics MockAssistantStream
- class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
- constructor() {
- super(
- (event) => event.type === "done" || event.type === "error",
- (event) => {
- if (event.type === "done") return event.message;
- if (event.type === "error") return event.error;
- throw new Error("Unexpected event type");
- },
- );
- }
- }
- function createUsage() {
- return {
- input: 0,
- output: 0,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 0,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- };
- }
- function createModel(): Model<"openai-responses"> {
- return {
- id: "mock",
- name: "mock",
- api: "openai-responses",
- provider: "openai",
- baseUrl: "https://example.invalid",
- reasoning: false,
- input: ["text"],
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- contextWindow: 8192,
- maxTokens: 2048,
- };
- }
- function createAssistantMessage(
- content: AssistantMessage["content"],
- stopReason: AssistantMessage["stopReason"] = "stop",
- ): AssistantMessage {
- return {
- role: "assistant",
- content,
- api: "openai-responses",
- provider: "openai",
- model: "mock",
- usage: createUsage(),
- stopReason,
- timestamp: Date.now(),
- };
- }
- function createUserMessage(text: string): UserMessage {
- return {
- role: "user",
- content: text,
- timestamp: Date.now(),
- };
- }
- // Simple identity converter for tests - just passes through standard messages
- function identityConverter(messages: AgentMessage[]): Message[] {
- return messages.filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
- }
- describe("agentLoop with AgentMessage", () => {
- it("should emit events with AgentMessage types", async () => {
- const context: AgentContext = {
- systemPrompt: "You are helpful.",
- messages: [],
- tools: [],
- };
- const userPrompt: AgentMessage = createUserMessage("Hello");
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- const message = createAssistantMessage([{ type: "text", text: "Hi there!" }]);
- stream.push({ type: "done", reason: "stop", message });
- });
- return stream;
- };
- const events: AgentEvent[] = [];
- const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
- for await (const event of stream) {
- events.push(event);
- }
- const messages = await stream.result();
- // Should have user message and assistant message
- expect(messages.length).toBe(2);
- expect(messages[0].role).toBe("user");
- expect(messages[1].role).toBe("assistant");
- // Verify event sequence
- const eventTypes = events.map((e) => e.type);
- expect(eventTypes).toContain("agent_start");
- expect(eventTypes).toContain("turn_start");
- expect(eventTypes).toContain("message_start");
- expect(eventTypes).toContain("message_end");
- expect(eventTypes).toContain("turn_end");
- expect(eventTypes).toContain("agent_end");
- });
- it("should handle custom message types via convertToLlm", async () => {
- // Create a custom message type
- interface CustomNotification {
- role: "notification";
- text: string;
- timestamp: number;
- }
- const notification: CustomNotification = {
- role: "notification",
- text: "This is a notification",
- timestamp: Date.now(),
- };
- const context: AgentContext = {
- systemPrompt: "You are helpful.",
- messages: [notification as unknown as AgentMessage], // Custom message in context
- tools: [],
- };
- const userPrompt: AgentMessage = createUserMessage("Hello");
- let convertedMessages: Message[] = [];
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: (messages) => {
- // Filter out notifications, convert rest
- convertedMessages = messages
- .filter((m) => (m as { role: string }).role !== "notification")
- .filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
- return convertedMessages;
- },
- };
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- const message = createAssistantMessage([{ type: "text", text: "Response" }]);
- stream.push({ type: "done", reason: "stop", message });
- });
- return stream;
- };
- const events: AgentEvent[] = [];
- const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
- for await (const event of stream) {
- events.push(event);
- }
- // The notification should have been filtered out in convertToLlm
- expect(convertedMessages.length).toBe(1); // Only user message
- expect(convertedMessages[0].role).toBe("user");
- });
- it("should apply transformContext before convertToLlm", async () => {
- const context: AgentContext = {
- systemPrompt: "You are helpful.",
- messages: [
- createUserMessage("old message 1"),
- createAssistantMessage([{ type: "text", text: "old response 1" }]),
- createUserMessage("old message 2"),
- createAssistantMessage([{ type: "text", text: "old response 2" }]),
- ],
- tools: [],
- };
- const userPrompt: AgentMessage = createUserMessage("new message");
- let transformedMessages: AgentMessage[] = [];
- let convertedMessages: Message[] = [];
- const config: AgentLoopConfig = {
- model: createModel(),
- transformContext: async (messages) => {
- // Keep only last 2 messages (prune old ones)
- transformedMessages = messages.slice(-2);
- return transformedMessages;
- },
- convertToLlm: (messages) => {
- convertedMessages = messages.filter(
- (m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult",
- ) as Message[];
- return convertedMessages;
- },
- };
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- const message = createAssistantMessage([{ type: "text", text: "Response" }]);
- stream.push({ type: "done", reason: "stop", message });
- });
- return stream;
- };
- const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
- for await (const _ of stream) {
- // consume
- }
- // transformContext should have been called first, keeping only last 2
- expect(transformedMessages.length).toBe(2);
- // Then convertToLlm receives the pruned messages
- expect(convertedMessages.length).toBe(2);
- });
- it("should handle tool calls and results", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const executed: string[] = [];
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- executed.push(params.value);
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const userPrompt: AgentMessage = createUserMessage("echo something");
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- let callIndex = 0;
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- // First call: return tool call
- const message = createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
- "toolUse",
- );
- stream.push({ type: "done", reason: "toolUse", message });
- } else {
- // Second call: return final response
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- stream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return stream;
- };
- const events: AgentEvent[] = [];
- const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
- for await (const event of stream) {
- events.push(event);
- }
- // Tool should have been executed
- expect(executed).toEqual(["hello"]);
- // Should have tool execution events
- const toolStart = events.find((e) => e.type === "tool_execution_start");
- const toolEnd = events.find((e) => e.type === "tool_execution_end");
- expect(toolStart).toBeDefined();
- expect(toolEnd).toBeDefined();
- if (toolEnd?.type === "tool_execution_end") {
- expect(toolEnd.isError).toBe(false);
- }
- });
- it("should execute mutated beforeToolCall args without revalidation", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const executed: Array<string | number> = [];
- const tool: AgentTool<typeof toolSchema, { value: string | number }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- executed.push(params.value as string | number);
- return {
- content: [{ type: "text", text: `echoed: ${String(params.value)}` }],
- details: { value: params.value as string | number },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const userPrompt: AgentMessage = createUserMessage("echo something");
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- beforeToolCall: async ({ args }) => {
- const mutableArgs = args as { value: string | number };
- mutableArgs.value = 123;
- return undefined;
- },
- };
- let callIndex = 0;
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- const message = createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
- "toolUse",
- );
- stream.push({ type: "done", reason: "toolUse", message });
- } else {
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- stream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return stream;
- };
- const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
- for await (const _event of stream) {
- // consume
- }
- expect(executed).toEqual([123]);
- });
- it("should prepare tool arguments for validation", async () => {
- const replaceSchema = Type.Object({ oldText: Type.String(), newText: Type.String() });
- const toolSchema = Type.Object({ edits: Type.Array(replaceSchema) });
- const executed: Array<Array<{ oldText: string; newText: string }>> = [];
- const tool: AgentTool<typeof toolSchema, { count: number }> = {
- name: "edit",
- label: "Edit",
- description: "Edit tool",
- parameters: toolSchema,
- prepareArguments(args) {
- if (!args || typeof args !== "object") {
- return args as { edits: { oldText: string; newText: string }[] };
- }
- const input = args as {
- edits?: Array<{ oldText: string; newText: string }>;
- oldText?: string;
- newText?: string;
- };
- if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
- return args as { edits: { oldText: string; newText: string }[] };
- }
- return {
- edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
- };
- },
- async execute(_toolCallId, params) {
- executed.push(params.edits);
- return {
- content: [{ type: "text", text: `edited ${params.edits.length}` }],
- details: { count: params.edits.length },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const userPrompt: AgentMessage = createUserMessage("edit something");
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- let callIndex = 0;
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- const message = createAssistantMessage(
- [
- {
- type: "toolCall",
- id: "tool-1",
- name: "edit",
- arguments: { oldText: "before", newText: "after" },
- },
- ],
- "toolUse",
- );
- stream.push({ type: "done", reason: "toolUse", message });
- } else {
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- stream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return stream;
- };
- const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
- for await (const _event of stream) {
- // consume
- }
- expect(executed).toEqual([[{ oldText: "before", newText: "after" }]]);
- });
- it("should emit tool_execution_end in completion order but persist tool results in source order", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- let firstResolved = false;
- let parallelObserved = false;
- let releaseFirst: (() => void) | undefined;
- const firstDone = new Promise<void>((resolve) => {
- releaseFirst = resolve;
- });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- if (params.value === "first") {
- await firstDone;
- firstResolved = true;
- }
- if (params.value === "second" && !firstResolved) {
- parallelObserved = true;
- }
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const userPrompt: AgentMessage = createUserMessage("echo both");
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- toolExecution: "parallel",
- };
- let callIndex = 0;
- const stream = agentLoop([userPrompt], context, config, undefined, () => {
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- const message = createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
- ],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- setTimeout(() => releaseFirst?.(), 20);
- } else {
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- mockStream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return mockStream;
- });
- const events: AgentEvent[] = [];
- for await (const event of stream) {
- events.push(event);
- }
- const toolExecutionEndIds = events.flatMap((event) => {
- if (event.type !== "tool_execution_end") {
- return [];
- }
- return [event.toolCallId];
- });
- const toolResultIds = events.flatMap((event) => {
- if (event.type !== "message_end" || event.message.role !== "toolResult") {
- return [];
- }
- return [event.message.toolCallId];
- });
- const turnToolResultIds = events.flatMap((event) => {
- if (event.type !== "turn_end") {
- return [];
- }
- return event.toolResults.map((toolResult) => toolResult.toolCallId);
- });
- expect(parallelObserved).toBe(true);
- expect(toolExecutionEndIds).toEqual(["tool-2", "tool-1"]);
- expect(toolResultIds).toEqual(["tool-1", "tool-2"]);
- expect(turnToolResultIds).toEqual(["tool-1", "tool-2"]);
- });
- it("should inject queued messages after all tool calls complete", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const executed: string[] = [];
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- executed.push(params.value);
- return {
- content: [{ type: "text", text: `ok:${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const userPrompt: AgentMessage = createUserMessage("start");
- const queuedUserMessage: AgentMessage = createUserMessage("interrupt");
- let queuedDelivered = false;
- let callIndex = 0;
- let sawInterruptInContext = false;
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- toolExecution: "sequential",
- getSteeringMessages: async () => {
- // Return steering message after tool execution has started.
- if (executed.length >= 1 && !queuedDelivered) {
- queuedDelivered = true;
- return [queuedUserMessage];
- }
- return [];
- },
- };
- const events: AgentEvent[] = [];
- const stream = agentLoop([userPrompt], context, config, undefined, (_model, ctx, _options) => {
- // Check if interrupt message is in context on second call
- if (callIndex === 1) {
- sawInterruptInContext = ctx.messages.some(
- (m) => m.role === "user" && typeof m.content === "string" && m.content === "interrupt",
- );
- }
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- // First call: return two tool calls
- const message = createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
- ],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- } else {
- // Second call: return final response
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- mockStream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return mockStream;
- });
- for await (const event of stream) {
- events.push(event);
- }
- // Both tools should execute before steering is injected
- expect(executed).toEqual(["first", "second"]);
- const toolEnds = events.filter(
- (e): e is Extract<AgentEvent, { type: "tool_execution_end" }> => e.type === "tool_execution_end",
- );
- expect(toolEnds.length).toBe(2);
- expect(toolEnds[0].isError).toBe(false);
- expect(toolEnds[1].isError).toBe(false);
- // Queued message should appear in events after both tool result messages
- const eventSequence = events.flatMap((event) => {
- if (event.type !== "message_start") return [];
- if (event.message.role === "toolResult") return [`tool:${event.message.toolCallId}`];
- if (event.message.role === "user" && typeof event.message.content === "string") {
- return [event.message.content];
- }
- return [];
- });
- expect(eventSequence).toContain("interrupt");
- expect(eventSequence.indexOf("tool:tool-1")).toBeLessThan(eventSequence.indexOf("interrupt"));
- expect(eventSequence.indexOf("tool:tool-2")).toBeLessThan(eventSequence.indexOf("interrupt"));
- // Interrupt message should be in context when second LLM call is made
- expect(sawInterruptInContext).toBe(true);
- });
- it("should force sequential execution when a tool has executionMode=sequential even with default parallel config", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- let firstResolved = false;
- let parallelObserved = false;
- let releaseFirst: (() => void) | undefined;
- const firstDone = new Promise<void>((resolve) => {
- releaseFirst = resolve;
- });
- const slowTool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "slow",
- label: "Slow",
- description: "Slow tool",
- parameters: toolSchema,
- executionMode: "sequential",
- async execute(_toolCallId, params) {
- if (params.value === "first") {
- await firstDone;
- firstResolved = true;
- }
- if (params.value === "second" && !firstResolved) {
- parallelObserved = true;
- }
- return {
- content: [{ type: "text", text: `slow: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [slowTool],
- };
- const userPrompt: AgentMessage = createUserMessage("run both");
- // config is parallel (default), but tool forces sequential
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- let callIndex = 0;
- const stream = agentLoop([userPrompt], context, config, undefined, () => {
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- const message = createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "slow", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "slow", arguments: { value: "second" } },
- ],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- setTimeout(() => releaseFirst?.(), 20);
- } else {
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- mockStream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return mockStream;
- });
- const events: AgentEvent[] = [];
- for await (const event of stream) {
- events.push(event);
- }
- // With sequential execution, second tool should NOT start before first finishes
- expect(parallelObserved).toBe(false);
- const toolResultIds = events.flatMap((event) => {
- if (event.type !== "message_end" || event.message.role !== "toolResult") {
- return [];
- }
- return [event.message.toolCallId];
- });
- expect(toolResultIds).toEqual(["tool-1", "tool-2"]);
- });
- it("should force sequential execution when one of multiple tools has executionMode=sequential", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const executionOrder: string[] = [];
- let releaseSlow: (() => void) | undefined;
- const slowDone = new Promise<void>((resolve) => {
- releaseSlow = resolve;
- });
- const slowTool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "slow",
- label: "Slow",
- description: "Slow tool",
- parameters: toolSchema,
- executionMode: "sequential",
- async execute(_toolCallId, params) {
- executionOrder.push(`slow:${params.value}`);
- if (params.value === "a") {
- await slowDone;
- }
- return {
- content: [{ type: "text", text: `slow: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const fastTool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "fast",
- label: "Fast",
- description: "Fast tool",
- parameters: toolSchema,
- // no executionMode = defaults to parallel
- async execute(_toolCallId, params) {
- executionOrder.push(`fast:${params.value}`);
- return {
- content: [{ type: "text", text: `fast: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [slowTool, fastTool],
- };
- const userPrompt: AgentMessage = createUserMessage("run both");
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- // parallel by default, but slowTool forces sequential
- };
- let callIndex = 0;
- const stream = agentLoop([userPrompt], context, config, undefined, () => {
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- const message = createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "slow", arguments: { value: "a" } },
- { type: "toolCall", id: "tool-2", name: "fast", arguments: { value: "b" } },
- ],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- setTimeout(() => releaseSlow?.(), 20);
- } else {
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- mockStream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return mockStream;
- });
- const events: AgentEvent[] = [];
- for await (const event of stream) {
- events.push(event);
- }
- // Fast tool should NOT run before slow tool finishes
- expect(executionOrder[0]).toBe("slow:a");
- expect(executionOrder).toContain("fast:b");
- });
- it("should allow parallel execution when all tools have executionMode=parallel", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- let firstResolved = false;
- let parallelObserved = false;
- let releaseFirst: (() => void) | undefined;
- const firstDone = new Promise<void>((resolve) => {
- releaseFirst = resolve;
- });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- executionMode: "parallel",
- async execute(_toolCallId, params) {
- if (params.value === "first") {
- await firstDone;
- firstResolved = true;
- }
- if (params.value === "second" && !firstResolved) {
- parallelObserved = true;
- }
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const userPrompt: AgentMessage = createUserMessage("echo both");
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- let callIndex = 0;
- const stream = agentLoop([userPrompt], context, config, undefined, () => {
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- const message = createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
- ],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- setTimeout(() => releaseFirst?.(), 20);
- } else {
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- mockStream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return mockStream;
- });
- const events: AgentEvent[] = [];
- for await (const event of stream) {
- events.push(event);
- }
- // With executionMode=parallel, second tool should start before first finishes
- expect(parallelObserved).toBe(true);
- });
- it("should use prepareNextTurn snapshot before continuing", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "first prompt",
- messages: [],
- tools: [tool],
- };
- let convertedSecondTurnSystemPrompt = "";
- let prepared = false;
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- prepareNextTurn: async ({ context: currentContext }) => {
- if (prepared) return undefined;
- prepared = true;
- return {
- context: {
- systemPrompt: "second prompt",
- messages: currentContext.messages.slice(),
- tools: currentContext.tools,
- },
- };
- },
- };
- let llmCalls = 0;
- const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, (_model, ctx) => {
- llmCalls++;
- if (llmCalls === 2) {
- convertedSecondTurnSystemPrompt = ctx.systemPrompt ?? "";
- }
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (llmCalls === 1) {
- mockStream.push({
- type: "done",
- reason: "toolUse",
- message: createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
- "toolUse",
- ),
- });
- } else {
- mockStream.push({
- type: "done",
- reason: "stop",
- message: createAssistantMessage([{ type: "text", text: "done" }]),
- });
- }
- });
- return mockStream;
- });
- for await (const _event of stream) {
- // consume
- }
- expect(llmCalls).toBe(2);
- expect(convertedSecondTurnSystemPrompt).toBe("second prompt");
- });
- it("should stop after the current turn when shouldStopAfterTurn returns true", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const executed: string[] = [];
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- executed.push(params.value);
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- let steeringPolls = 0;
- let followUpPolls = 0;
- let callbackToolResultIds: string[] = [];
- let callbackContextRoles: string[] = [];
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- getSteeringMessages: async () => {
- steeringPolls++;
- return [];
- },
- getFollowUpMessages: async () => {
- followUpPolls++;
- return [createUserMessage("follow up should stay queued")];
- },
- shouldStopAfterTurn: async ({ message, toolResults, context }) => {
- expect(message.role).toBe("assistant");
- callbackToolResultIds = toolResults.map((toolResult) => toolResult.toolCallId);
- callbackContextRoles = context.messages.map((contextMessage) => contextMessage.role);
- return true;
- },
- };
- let llmCalls = 0;
- const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, () => {
- llmCalls++;
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (llmCalls === 1) {
- const message = createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- } else {
- mockStream.push({
- type: "done",
- reason: "stop",
- message: createAssistantMessage([{ type: "text", text: "should not run" }]),
- });
- }
- });
- return mockStream;
- });
- const events: AgentEvent[] = [];
- for await (const event of stream) {
- events.push(event);
- }
- const messages = await stream.result();
- expect(llmCalls).toBe(1);
- expect(executed).toEqual(["hello"]);
- expect(steeringPolls).toBe(1);
- expect(followUpPolls).toBe(0);
- expect(callbackToolResultIds).toEqual(["tool-1"]);
- expect(callbackContextRoles).toEqual(["user", "assistant", "toolResult"]);
- expect(messages.map((message) => message.role)).toEqual(["user", "assistant", "toolResult"]);
- expect(events.map((event) => event.type)).toEqual([
- "agent_start",
- "turn_start",
- "message_start",
- "message_end",
- "message_start",
- "message_end",
- "tool_execution_start",
- "tool_execution_end",
- "message_start",
- "message_end",
- "turn_end",
- "agent_end",
- ]);
- });
- it("should stop after a tool batch when every tool result sets terminate=true", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- terminate: true,
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- let llmCalls = 0;
- const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, () => {
- llmCalls++;
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- const message = createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- });
- return mockStream;
- });
- const events: AgentEvent[] = [];
- for await (const event of stream) {
- events.push(event);
- }
- const messages = await stream.result();
- expect(llmCalls).toBe(1);
- expect(messages.map((message) => message.role)).toEqual(["user", "assistant", "toolResult"]);
- expect(events.filter((event) => event.type === "turn_end")).toHaveLength(1);
- });
- it("should continue after parallel tool calls when not all tool results terminate", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- terminate: params.value === "first",
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- toolExecution: "parallel",
- };
- let callIndex = 0;
- const stream = agentLoop([createUserMessage("echo both")], context, config, undefined, () => {
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- if (callIndex === 0) {
- const message = createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
- ],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- } else {
- const message = createAssistantMessage([{ type: "text", text: "done" }]);
- mockStream.push({ type: "done", reason: "stop", message });
- }
- callIndex++;
- });
- return mockStream;
- });
- for await (const _event of stream) {
- // consume
- }
- const messages = await stream.result();
- expect(callIndex).toBe(2);
- expect(messages.map((message) => message.role)).toEqual([
- "user",
- "assistant",
- "toolResult",
- "toolResult",
- "assistant",
- ]);
- });
- it("should not execute later sequential calls after a hook requests global termination", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const executed: string[] = [];
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- executed.push(params.value);
- return { content: [{ type: "text", text: params.value }], details: {} };
- },
- };
- let llmCalls = 0;
- const stream = agentLoop(
- [createUserMessage("echo both")],
- { systemPrompt: "", messages: [], tools: [tool] },
- {
- model: createModel(),
- convertToLlm: identityConverter,
- toolExecution: "sequential",
- beforeToolCall: async ({ toolCall }) =>
- toolCall.id === "tool-1"
- ? { block: true, reason: "stop now", terminateAgent: true }
- : undefined,
- },
- undefined,
- () => {
- llmCalls += 1;
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- mockStream.push({
- type: "done",
- reason: "toolUse",
- message: createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
- ],
- "toolUse",
- ),
- });
- });
- return mockStream;
- },
- );
- for await (const _event of stream) {
- // consume
- }
- expect(llmCalls).toBe(1);
- expect(executed).toEqual([]);
- const toolResults = (await stream.result()).filter((message) => message.role === "toolResult");
- expect(toolResults).toHaveLength(2);
- expect(toolResults[1]).toMatchObject({
- toolCallId: "tool-2",
- isError: true,
- content: [{ type: "text", text: expect.stringContaining("skipped") }],
- });
- });
- it("should observe execution start only after before-tool admission succeeds", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const order: string[] = [];
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- order.push("execute");
- return { content: [{ type: "text", text: params.value }], details: {} };
- },
- };
- const stream = agentLoop(
- [createUserMessage("echo")],
- { systemPrompt: "", messages: [], tools: [tool] },
- {
- model: createModel(),
- convertToLlm: identityConverter,
- beforeToolCall: async () => {
- order.push("before");
- return undefined;
- },
- onToolExecutionStart: () => order.push("execution-start"),
- afterToolCall: async () => {
- order.push("after");
- return { terminate: true };
- },
- },
- undefined,
- () => {
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- mockStream.push({
- type: "done",
- reason: "toolUse",
- message: createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "one" } }],
- "toolUse",
- ),
- });
- });
- return mockStream;
- },
- );
- for await (const _event of stream) {
- // consume
- }
- expect(order).toEqual(["before", "execution-start", "execute", "after"]);
- });
- it("should stop every prepared parallel call when a later blocked call requests global termination", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const executed: string[] = [];
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- executed.push(params.value);
- return { content: [{ type: "text", text: params.value }], details: {} };
- },
- };
- const context: AgentContext = { systemPrompt: "", messages: [], tools: [tool] };
- let llmCalls = 0;
- const stream = agentLoop(
- [createUserMessage("echo both")],
- context,
- {
- model: createModel(),
- convertToLlm: identityConverter,
- toolExecution: "parallel",
- beforeToolCall: async ({ toolCall }) =>
- toolCall.id === "tool-2" ? { block: true, reason: "stop now", terminateAgent: true } : undefined,
- },
- undefined,
- () => {
- llmCalls += 1;
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- mockStream.push({
- type: "done",
- reason: "toolUse",
- message: createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
- ],
- "toolUse",
- ),
- });
- });
- return mockStream;
- },
- );
- for await (const _event of stream) {
- // consume
- }
- expect(llmCalls).toBe(1);
- expect(executed).toEqual([]);
- expect((await stream.result()).filter((message) => message.role === "toolResult")).toHaveLength(2);
- });
- it("should keep an ordinary blocked tool call non-terminal", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- return { content: [{ type: "text", text: params.value }], details: {} };
- },
- };
- let llmCalls = 0;
- const stream = agentLoop(
- [createUserMessage("echo")],
- { systemPrompt: "", messages: [], tools: [tool] },
- {
- model: createModel(),
- convertToLlm: identityConverter,
- beforeToolCall: async () => ({ block: true, reason: "ordinary block" }),
- },
- undefined,
- () => {
- llmCalls += 1;
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- const message =
- llmCalls === 1
- ? createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } }],
- "toolUse",
- )
- : createAssistantMessage([{ type: "text", text: "done" }]);
- mockStream.push({ type: "done", reason: message.stopReason, message });
- });
- return mockStream;
- },
- );
- for await (const _event of stream) {
- // consume
- }
- expect(llmCalls).toBe(2);
- });
- it("should stop a mixed parallel batch when one after-tool hook requests global termination", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- return { content: [{ type: "text", text: params.value }], details: {} };
- },
- };
- let llmCalls = 0;
- const stream = agentLoop(
- [createUserMessage("echo both")],
- { systemPrompt: "", messages: [], tools: [tool] },
- {
- model: createModel(),
- convertToLlm: identityConverter,
- toolExecution: "parallel",
- afterToolCall: async ({ toolCall }) => ({ terminateAgent: toolCall.id === "tool-1" }),
- },
- undefined,
- () => {
- llmCalls += 1;
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- mockStream.push({
- type: "done",
- reason: "toolUse",
- message: createAssistantMessage(
- [
- { type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
- { type: "toolCall", id: "tool-2", name: "echo", arguments: { value: "second" } },
- ],
- "toolUse",
- ),
- });
- });
- return mockStream;
- },
- );
- for await (const _event of stream) {
- // consume
- }
- expect(llmCalls).toBe(1);
- });
- it("should allow afterToolCall to mark a tool batch as terminating", async () => {
- const toolSchema = Type.Object({ value: Type.String() });
- const tool: AgentTool<typeof toolSchema, { value: string }> = {
- name: "echo",
- label: "Echo",
- description: "Echo tool",
- parameters: toolSchema,
- async execute(_toolCallId, params) {
- return {
- content: [{ type: "text", text: `echoed: ${params.value}` }],
- details: { value: params.value },
- };
- },
- };
- const context: AgentContext = {
- systemPrompt: "",
- messages: [],
- tools: [tool],
- };
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- afterToolCall: async () => ({ terminate: true }),
- };
- let llmCalls = 0;
- const stream = agentLoop([createUserMessage("echo something")], context, config, undefined, () => {
- llmCalls++;
- const mockStream = new MockAssistantStream();
- queueMicrotask(() => {
- const message = createAssistantMessage(
- [{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "hello" } }],
- "toolUse",
- );
- mockStream.push({ type: "done", reason: "toolUse", message });
- });
- return mockStream;
- });
- for await (const _event of stream) {
- // consume
- }
- expect(llmCalls).toBe(1);
- });
- });
- describe("agentLoopContinue with AgentMessage", () => {
- it("should throw when context has no messages", () => {
- const context: AgentContext = {
- systemPrompt: "You are helpful.",
- messages: [],
- tools: [],
- };
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- expect(() => agentLoopContinue(context, config)).toThrow("Cannot continue: no messages in context");
- });
- it("should continue from existing context without emitting user message events", async () => {
- const userMessage: AgentMessage = createUserMessage("Hello");
- const context: AgentContext = {
- systemPrompt: "You are helpful.",
- messages: [userMessage],
- tools: [],
- };
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: identityConverter,
- };
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- const message = createAssistantMessage([{ type: "text", text: "Response" }]);
- stream.push({ type: "done", reason: "stop", message });
- });
- return stream;
- };
- const events: AgentEvent[] = [];
- const stream = agentLoopContinue(context, config, undefined, streamFn);
- for await (const event of stream) {
- events.push(event);
- }
- const messages = await stream.result();
- // Should only return the new assistant message (not the existing user message)
- expect(messages.length).toBe(1);
- expect(messages[0].role).toBe("assistant");
- // Should NOT have user message events (that's the key difference from agentLoop)
- const messageEndEvents = events.filter((e) => e.type === "message_end");
- expect(messageEndEvents.length).toBe(1);
- expect((messageEndEvents[0] as any).message.role).toBe("assistant");
- });
- it("should allow custom message types as last message (caller responsibility)", async () => {
- // Custom message that will be converted to user message by convertToLlm
- interface CustomMessage {
- role: "custom";
- text: string;
- timestamp: number;
- }
- const customMessage: CustomMessage = {
- role: "custom",
- text: "Hook content",
- timestamp: Date.now(),
- };
- const context: AgentContext = {
- systemPrompt: "You are helpful.",
- messages: [customMessage as unknown as AgentMessage],
- tools: [],
- };
- const config: AgentLoopConfig = {
- model: createModel(),
- convertToLlm: (messages) => {
- // Convert custom to user message
- return messages
- .map((m) => {
- if ((m as any).role === "custom") {
- return {
- role: "user" as const,
- content: (m as any).text,
- timestamp: m.timestamp,
- };
- }
- return m;
- })
- .filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
- },
- };
- const streamFn = () => {
- const stream = new MockAssistantStream();
- queueMicrotask(() => {
- const message = createAssistantMessage([{ type: "text", text: "Response to custom message" }]);
- stream.push({ type: "done", reason: "stop", message });
- });
- return stream;
- };
- // Should not throw - the custom message will be converted to user message
- const stream = agentLoopContinue(context, config, undefined, streamFn);
- const events: AgentEvent[] = [];
- for await (const event of stream) {
- events.push(event);
- }
- const messages = await stream.result();
- expect(messages.length).toBe(1);
- expect(messages[0].role).toBe("assistant");
- });
- });
|