| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398 |
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import type { AgentTool } from "@earendil-works/pi-agent-core";
- import { fauxAssistantMessage, fauxToolCall, type Model } from "@earendil-works/pi-ai";
- import { Type } from "typebox";
- import { afterEach, describe, expect, it } from "vitest";
- import type { InputEvent } from "../../src/core/extensions/index.ts";
- import type { PromptTemplate } from "../../src/core/prompt-templates.ts";
- import { createSyntheticSourceInfo } from "../../src/core/source-info.ts";
- import { createTestResourceLoader } from "../utilities.ts";
- import { createHarness, getMessageText, type Harness } from "./harness.ts";
- describe("AgentSession prompt characterization", () => {
- const harnesses: Harness[] = [];
- const tempDirs: string[] = [];
- afterEach(() => {
- while (harnesses.length > 0) {
- harnesses.pop()?.cleanup();
- }
- while (tempDirs.length > 0) {
- const tempDir = tempDirs.pop();
- if (tempDir) {
- rmSync(tempDir, { recursive: true, force: true });
- }
- }
- });
- it("prompts while idle and records a single text response", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- harness.setResponses([fauxAssistantMessage("hello")]);
- await harness.session.prompt("hi");
- expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
- expect(getMessageText(harness.session.messages[0]!)).toBe("hi");
- expect(harness.getPendingResponseCount()).toBe(0);
- });
- it("handles a tool call turn and waits for the follow-up LLM response", async () => {
- const toolRuns: string[] = [];
- const echoTool: AgentTool = {
- name: "echo",
- label: "Echo",
- description: "Echo text back",
- parameters: Type.Object({ text: Type.String() }),
- execute: async (_toolCallId, params) => {
- const text = typeof params === "object" && params !== null && "text" in params ? String(params.text) : "";
- toolRuns.push(text);
- return {
- content: [{ type: "text", text: `echo:${text}` }],
- details: { text },
- };
- },
- };
- const harness = await createHarness({ tools: [echoTool] });
- harnesses.push(harness);
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("echo", { text: "hello" }), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
- ]);
- await harness.session.prompt("start");
- expect(toolRuns).toEqual(["hello"]);
- expect(harness.session.messages.map((message) => message.role)).toEqual([
- "user",
- "assistant",
- "toolResult",
- "assistant",
- ]);
- expect(harness.session.messages[2]?.role).toBe("toolResult");
- expect(harness.session.messages[3]?.role).toBe("assistant");
- });
- it("executes multiple tool calls from one response and continues with a single follow-up response", async () => {
- const toolRuns: string[] = [];
- const makeTool = (name: string, delayMs: number): AgentTool => ({
- name,
- label: name,
- description: `${name} tool`,
- parameters: Type.Object({ value: Type.String() }),
- execute: async (_toolCallId, params) => {
- const value =
- typeof params === "object" && params !== null && "value" in params ? String(params.value) : "";
- await new Promise((resolve) => setTimeout(resolve, delayMs));
- toolRuns.push(`${name}:${value}`);
- return {
- content: [{ type: "text", text: `${name}:${value}` }],
- details: { value },
- };
- },
- });
- const harness = await createHarness({ tools: [makeTool("slow", 25), makeTool("fast", 0)] });
- harnesses.push(harness);
- harness.setResponses([
- fauxAssistantMessage([fauxToolCall("slow", { value: "a" }), fauxToolCall("fast", { value: "b" })], {
- stopReason: "toolUse",
- }),
- (context) => {
- const toolResults = context.messages.filter((message) => message.role === "toolResult");
- return fauxAssistantMessage(`tool results: ${toolResults.length}`);
- },
- ]);
- await harness.session.prompt("run tools");
- expect(toolRuns.sort()).toEqual(["fast:b", "slow:a"]);
- expect(harness.session.messages.filter((message) => message.role === "toolResult")).toHaveLength(2);
- expect(harness.session.messages[harness.session.messages.length - 1]?.role).toBe("assistant");
- });
- it("preserves image attachments in the provider context", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- let sawImage = false;
- harness.setResponses([
- (context) => {
- const user = context.messages.find((message) => message.role === "user");
- sawImage =
- user?.role === "user" &&
- typeof user.content !== "string" &&
- user.content.some((part) => part.type === "image");
- return fauxAssistantMessage("ok");
- },
- ]);
- await harness.session.prompt("describe", {
- images: [
- {
- type: "image",
- mimeType: "image/png",
- data: "ZmFrZQ==",
- },
- ],
- });
- expect(sawImage).toBe(true);
- });
- it("expands skill commands before sending the prompt", async () => {
- const tempDir = join(tmpdir(), `pi-skill-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- mkdirSync(tempDir, { recursive: true });
- tempDirs.push(tempDir);
- const skillPath = join(tempDir, "test-skill.md");
- writeFileSync(skillPath, "# Test Skill\n\nUse the skill body.");
- const resourceLoader = {
- ...createTestResourceLoader(),
- getSkills: () => ({
- skills: [
- {
- name: "test",
- description: "Test skill",
- filePath: skillPath,
- disableModelInvocation: false,
- baseDir: tempDir,
- sourceInfo: createSyntheticSourceInfo(skillPath, {
- source: "local",
- scope: "project",
- origin: "top-level",
- baseDir: tempDir,
- }),
- },
- ],
- diagnostics: [],
- }),
- };
- const harness = await createHarness({ resourceLoader });
- harnesses.push(harness);
- let expandedPrompt = "";
- harness.setResponses([
- (context) => {
- const user = context.messages.find((message) => message.role === "user");
- expandedPrompt = user ? getMessageText(user) : "";
- return fauxAssistantMessage("ok");
- },
- ]);
- await harness.session.prompt("/skill:test explain this");
- expect(expandedPrompt).toContain('<skill name="test" location="');
- expect(expandedPrompt).toContain("Use the skill body.");
- expect(expandedPrompt).toContain("explain this");
- });
- it("expands prompt templates before sending the prompt", async () => {
- const template: PromptTemplate = {
- name: "review",
- description: "Review template",
- content: "Review this code: $1",
- filePath: "/virtual/review.md",
- sourceInfo: createSyntheticSourceInfo("/virtual/review.md", {
- source: "local",
- scope: "temporary",
- origin: "top-level",
- }),
- };
- const resourceLoader = {
- ...createTestResourceLoader(),
- getPrompts: () => ({ prompts: [template], diagnostics: [] }),
- };
- const harness = await createHarness({ resourceLoader });
- harnesses.push(harness);
- let expandedPrompt = "";
- harness.setResponses([
- (context) => {
- const user = context.messages.find((message) => message.role === "user");
- expandedPrompt = user ? getMessageText(user) : "";
- return fauxAssistantMessage("ok");
- },
- ]);
- await harness.session.prompt("/review src/index.ts");
- expect(expandedPrompt).toBe("Review this code: src/index.ts");
- });
- it("dispatches extension commands without consuming a provider response", async () => {
- const commandRuns: string[] = [];
- const harness = await createHarness({
- extensionFactories: [
- (pi) => {
- pi.registerCommand("testcmd", {
- description: "Test command",
- handler: async (args) => {
- commandRuns.push(args);
- },
- });
- },
- ],
- });
- harnesses.push(harness);
- harness.setResponses([fauxAssistantMessage("should stay queued")]);
- await harness.session.prompt("/testcmd hello world");
- expect(commandRuns).toEqual(["hello world"]);
- expect(harness.session.messages).toEqual([]);
- expect(harness.getPendingResponseCount()).toBe(1);
- });
- it("sendUserMessage while idle triggers a turn", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- harness.setResponses([fauxAssistantMessage("response")]);
- await harness.session.sendUserMessage("from extension");
- expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
- expect(getMessageText(harness.session.messages[0]!)).toBe("from extension");
- });
- it("does not report streamingBehavior to input handlers while idle", async () => {
- const inputEvents: InputEvent[] = [];
- const harness = await createHarness({
- extensionFactories: [
- (pi) => {
- pi.on("input", (event) => {
- inputEvents.push(event);
- });
- },
- ],
- });
- harnesses.push(harness);
- harness.setResponses([fauxAssistantMessage("ok")]);
- await harness.session.prompt("idle", { streamingBehavior: "followUp" });
- expect(inputEvents).toHaveLength(1);
- expect(inputEvents[0]?.streamingBehavior).toBeUndefined();
- });
- it("reports streamingBehavior to input handlers while streaming", async () => {
- let releaseToolExecution: (() => void) | undefined;
- const toolRelease = new Promise<void>((resolve) => {
- releaseToolExecution = resolve;
- });
- const inputEvents: InputEvent[] = [];
- const waitTool: AgentTool = {
- name: "wait",
- label: "Wait",
- description: "Wait for release",
- parameters: Type.Object({}),
- execute: async () => {
- await toolRelease;
- return {
- content: [{ type: "text", text: "released" }],
- details: {},
- };
- },
- };
- const harness = await createHarness({
- tools: [waitTool],
- extensionFactories: [
- (pi) => {
- pi.on("input", (event) => {
- inputEvents.push(event);
- });
- },
- ],
- });
- harnesses.push(harness);
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
- ]);
- const sawToolStart = new Promise<void>((resolve) => {
- const unsubscribe = harness.session.subscribe((event) => {
- if (event.type === "tool_execution_start") {
- unsubscribe();
- resolve();
- }
- });
- });
- const promptPromise = harness.session.prompt("start");
- await sawToolStart;
- await harness.session.prompt("queued", { streamingBehavior: "followUp" });
- expect(inputEvents.map((event) => event.streamingBehavior)).toEqual([undefined, "followUp"]);
- releaseToolExecution?.();
- await promptPromise;
- });
- it("throws when prompted during streaming without a streamingBehavior", async () => {
- let releaseToolExecution: (() => void) | undefined;
- const toolRelease = new Promise<void>((resolve) => {
- releaseToolExecution = resolve;
- });
- const waitTool: AgentTool = {
- name: "wait",
- label: "Wait",
- description: "Wait for release",
- parameters: Type.Object({}),
- execute: async () => {
- await toolRelease;
- return {
- content: [{ type: "text", text: "released" }],
- details: {},
- };
- },
- };
- const harness = await createHarness({ tools: [waitTool] });
- harnesses.push(harness);
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
- ]);
- const sawToolStart = new Promise<void>((resolve) => {
- const unsubscribe = harness.session.subscribe((event) => {
- if (event.type === "tool_execution_start") {
- unsubscribe();
- resolve();
- }
- });
- });
- const promptPromise = harness.session.prompt("start");
- await sawToolStart;
- await expect(harness.session.prompt("second")).rejects.toThrow(
- "Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
- );
- releaseToolExecution?.();
- await promptPromise;
- });
- it("throws when prompting without a model", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- harness.session.agent.state.model = undefined as unknown as Model<any>;
- await expect(harness.session.prompt("hi")).rejects.toThrow("No model selected.");
- });
- it("throws when prompting without configured auth", async () => {
- const harness = await createHarness({ withConfiguredAuth: false });
- harnesses.push(harness);
- await expect(harness.session.prompt("hi")).rejects.toThrow(
- `No API key found for ${harness.getModel().provider}.`,
- );
- });
- });
|