Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/agent/__tests__/agent-lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { expect, test } from "bun:test";

import { Model, type ModelProvider, type UserMessage } from "@/foundation";

import { Agent } from "../agent";
import type { AgentMiddleware } from "../agent-middleware";

const provider: ModelProvider = {
async invoke() {
return { role: "assistant", content: [{ type: "text", text: "done" }] };
},
async *stream() {
yield { role: "assistant", content: [{ type: "text", text: "done" }] };
},
};

test("runs afterAgentStep before afterAgentRun for a final step without tools", async () => {
const lifecycle: string[] = [];
const middleware: AgentMiddleware = {
afterAgentStep: async ({ step }) => {
lifecycle.push(`afterAgentStep:${step}`);
},
afterAgentRun: async () => {
lifecycle.push("afterAgentRun");
},
};
const agent = new Agent({
model: new Model("test-model", provider),
prompt: "test",
middlewares: [middleware],
});
const userMessage: UserMessage = {
role: "user",
content: [{ type: "text", text: "hello" }],
};

const stream = agent.stream(userMessage);
while (!(await stream.next()).done) {
// Drain the stream so the generator reaches the final lifecycle hooks.
}

expect(lifecycle).toEqual(["afterAgentStep:1", "afterAgentRun"]);
});
1 change: 1 addition & 0 deletions src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ export class Agent {

const toolUses = this._extractToolUses(assistantMessage);
if (toolUses.length === 0) {
await this._afterAgentStep(step);
await this._afterAgentRun();
return;
}
Expand Down