agent-session-prompt.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import { mkdirSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type { AgentTool } from "@earendil-works/pi-agent-core";
  5. import { fauxAssistantMessage, fauxToolCall, type Model } from "@earendil-works/pi-ai";
  6. import { Type } from "typebox";
  7. import { afterEach, describe, expect, it } from "vitest";
  8. import type { InputEvent } from "../../src/core/extensions/index.ts";
  9. import type { PromptTemplate } from "../../src/core/prompt-templates.ts";
  10. import { createSyntheticSourceInfo } from "../../src/core/source-info.ts";
  11. import { createTestResourceLoader } from "../utilities.ts";
  12. import { createHarness, getMessageText, type Harness } from "./harness.ts";
  13. describe("AgentSession prompt characterization", () => {
  14. const harnesses: Harness[] = [];
  15. const tempDirs: string[] = [];
  16. afterEach(() => {
  17. while (harnesses.length > 0) {
  18. harnesses.pop()?.cleanup();
  19. }
  20. while (tempDirs.length > 0) {
  21. const tempDir = tempDirs.pop();
  22. if (tempDir) {
  23. rmSync(tempDir, { recursive: true, force: true });
  24. }
  25. }
  26. });
  27. it("prompts while idle and records a single text response", async () => {
  28. const harness = await createHarness();
  29. harnesses.push(harness);
  30. harness.setResponses([fauxAssistantMessage("hello")]);
  31. await harness.session.prompt("hi");
  32. expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
  33. expect(getMessageText(harness.session.messages[0]!)).toBe("hi");
  34. expect(harness.getPendingResponseCount()).toBe(0);
  35. });
  36. it("handles a tool call turn and waits for the follow-up LLM response", async () => {
  37. const toolRuns: string[] = [];
  38. const echoTool: AgentTool = {
  39. name: "echo",
  40. label: "Echo",
  41. description: "Echo text back",
  42. parameters: Type.Object({ text: Type.String() }),
  43. execute: async (_toolCallId, params) => {
  44. const text = typeof params === "object" && params !== null && "text" in params ? String(params.text) : "";
  45. toolRuns.push(text);
  46. return {
  47. content: [{ type: "text", text: `echo:${text}` }],
  48. details: { text },
  49. };
  50. },
  51. };
  52. const harness = await createHarness({ tools: [echoTool] });
  53. harnesses.push(harness);
  54. harness.setResponses([
  55. fauxAssistantMessage(fauxToolCall("echo", { text: "hello" }), { stopReason: "toolUse" }),
  56. fauxAssistantMessage("done"),
  57. ]);
  58. await harness.session.prompt("start");
  59. expect(toolRuns).toEqual(["hello"]);
  60. expect(harness.session.messages.map((message) => message.role)).toEqual([
  61. "user",
  62. "assistant",
  63. "toolResult",
  64. "assistant",
  65. ]);
  66. expect(harness.session.messages[2]?.role).toBe("toolResult");
  67. expect(harness.session.messages[3]?.role).toBe("assistant");
  68. });
  69. it("executes multiple tool calls from one response and continues with a single follow-up response", async () => {
  70. const toolRuns: string[] = [];
  71. const makeTool = (name: string, delayMs: number): AgentTool => ({
  72. name,
  73. label: name,
  74. description: `${name} tool`,
  75. parameters: Type.Object({ value: Type.String() }),
  76. execute: async (_toolCallId, params) => {
  77. const value =
  78. typeof params === "object" && params !== null && "value" in params ? String(params.value) : "";
  79. await new Promise((resolve) => setTimeout(resolve, delayMs));
  80. toolRuns.push(`${name}:${value}`);
  81. return {
  82. content: [{ type: "text", text: `${name}:${value}` }],
  83. details: { value },
  84. };
  85. },
  86. });
  87. const harness = await createHarness({ tools: [makeTool("slow", 25), makeTool("fast", 0)] });
  88. harnesses.push(harness);
  89. harness.setResponses([
  90. fauxAssistantMessage([fauxToolCall("slow", { value: "a" }), fauxToolCall("fast", { value: "b" })], {
  91. stopReason: "toolUse",
  92. }),
  93. (context) => {
  94. const toolResults = context.messages.filter((message) => message.role === "toolResult");
  95. return fauxAssistantMessage(`tool results: ${toolResults.length}`);
  96. },
  97. ]);
  98. await harness.session.prompt("run tools");
  99. expect(toolRuns.sort()).toEqual(["fast:b", "slow:a"]);
  100. expect(harness.session.messages.filter((message) => message.role === "toolResult")).toHaveLength(2);
  101. expect(harness.session.messages[harness.session.messages.length - 1]?.role).toBe("assistant");
  102. });
  103. it("preserves image attachments in the provider context", async () => {
  104. const harness = await createHarness();
  105. harnesses.push(harness);
  106. let sawImage = false;
  107. harness.setResponses([
  108. (context) => {
  109. const user = context.messages.find((message) => message.role === "user");
  110. sawImage =
  111. user?.role === "user" &&
  112. typeof user.content !== "string" &&
  113. user.content.some((part) => part.type === "image");
  114. return fauxAssistantMessage("ok");
  115. },
  116. ]);
  117. await harness.session.prompt("describe", {
  118. images: [
  119. {
  120. type: "image",
  121. mimeType: "image/png",
  122. data: "ZmFrZQ==",
  123. },
  124. ],
  125. });
  126. expect(sawImage).toBe(true);
  127. });
  128. it("expands skill commands before sending the prompt", async () => {
  129. const tempDir = join(tmpdir(), `pi-skill-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  130. mkdirSync(tempDir, { recursive: true });
  131. tempDirs.push(tempDir);
  132. const skillPath = join(tempDir, "test-skill.md");
  133. writeFileSync(skillPath, "# Test Skill\n\nUse the skill body.");
  134. const resourceLoader = {
  135. ...createTestResourceLoader(),
  136. getSkills: () => ({
  137. skills: [
  138. {
  139. name: "test",
  140. description: "Test skill",
  141. filePath: skillPath,
  142. disableModelInvocation: false,
  143. baseDir: tempDir,
  144. sourceInfo: createSyntheticSourceInfo(skillPath, {
  145. source: "local",
  146. scope: "project",
  147. origin: "top-level",
  148. baseDir: tempDir,
  149. }),
  150. },
  151. ],
  152. diagnostics: [],
  153. }),
  154. };
  155. const harness = await createHarness({ resourceLoader });
  156. harnesses.push(harness);
  157. let expandedPrompt = "";
  158. harness.setResponses([
  159. (context) => {
  160. const user = context.messages.find((message) => message.role === "user");
  161. expandedPrompt = user ? getMessageText(user) : "";
  162. return fauxAssistantMessage("ok");
  163. },
  164. ]);
  165. await harness.session.prompt("/skill:test explain this");
  166. expect(expandedPrompt).toContain('<skill name="test" location="');
  167. expect(expandedPrompt).toContain("Use the skill body.");
  168. expect(expandedPrompt).toContain("explain this");
  169. });
  170. it("expands prompt templates before sending the prompt", async () => {
  171. const template: PromptTemplate = {
  172. name: "review",
  173. description: "Review template",
  174. content: "Review this code: $1",
  175. filePath: "/virtual/review.md",
  176. sourceInfo: createSyntheticSourceInfo("/virtual/review.md", {
  177. source: "local",
  178. scope: "temporary",
  179. origin: "top-level",
  180. }),
  181. };
  182. const resourceLoader = {
  183. ...createTestResourceLoader(),
  184. getPrompts: () => ({ prompts: [template], diagnostics: [] }),
  185. };
  186. const harness = await createHarness({ resourceLoader });
  187. harnesses.push(harness);
  188. let expandedPrompt = "";
  189. harness.setResponses([
  190. (context) => {
  191. const user = context.messages.find((message) => message.role === "user");
  192. expandedPrompt = user ? getMessageText(user) : "";
  193. return fauxAssistantMessage("ok");
  194. },
  195. ]);
  196. await harness.session.prompt("/review src/index.ts");
  197. expect(expandedPrompt).toBe("Review this code: src/index.ts");
  198. });
  199. it("dispatches extension commands without consuming a provider response", async () => {
  200. const commandRuns: string[] = [];
  201. const harness = await createHarness({
  202. extensionFactories: [
  203. (pi) => {
  204. pi.registerCommand("testcmd", {
  205. description: "Test command",
  206. handler: async (args) => {
  207. commandRuns.push(args);
  208. },
  209. });
  210. },
  211. ],
  212. });
  213. harnesses.push(harness);
  214. harness.setResponses([fauxAssistantMessage("should stay queued")]);
  215. await harness.session.prompt("/testcmd hello world");
  216. expect(commandRuns).toEqual(["hello world"]);
  217. expect(harness.session.messages).toEqual([]);
  218. expect(harness.getPendingResponseCount()).toBe(1);
  219. });
  220. it("sendUserMessage while idle triggers a turn", async () => {
  221. const harness = await createHarness();
  222. harnesses.push(harness);
  223. harness.setResponses([fauxAssistantMessage("response")]);
  224. await harness.session.sendUserMessage("from extension");
  225. expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
  226. expect(getMessageText(harness.session.messages[0]!)).toBe("from extension");
  227. });
  228. it("does not report streamingBehavior to input handlers while idle", async () => {
  229. const inputEvents: InputEvent[] = [];
  230. const harness = await createHarness({
  231. extensionFactories: [
  232. (pi) => {
  233. pi.on("input", (event) => {
  234. inputEvents.push(event);
  235. });
  236. },
  237. ],
  238. });
  239. harnesses.push(harness);
  240. harness.setResponses([fauxAssistantMessage("ok")]);
  241. await harness.session.prompt("idle", { streamingBehavior: "followUp" });
  242. expect(inputEvents).toHaveLength(1);
  243. expect(inputEvents[0]?.streamingBehavior).toBeUndefined();
  244. });
  245. it("reports streamingBehavior to input handlers while streaming", async () => {
  246. let releaseToolExecution: (() => void) | undefined;
  247. const toolRelease = new Promise<void>((resolve) => {
  248. releaseToolExecution = resolve;
  249. });
  250. const inputEvents: InputEvent[] = [];
  251. const waitTool: AgentTool = {
  252. name: "wait",
  253. label: "Wait",
  254. description: "Wait for release",
  255. parameters: Type.Object({}),
  256. execute: async () => {
  257. await toolRelease;
  258. return {
  259. content: [{ type: "text", text: "released" }],
  260. details: {},
  261. };
  262. },
  263. };
  264. const harness = await createHarness({
  265. tools: [waitTool],
  266. extensionFactories: [
  267. (pi) => {
  268. pi.on("input", (event) => {
  269. inputEvents.push(event);
  270. });
  271. },
  272. ],
  273. });
  274. harnesses.push(harness);
  275. harness.setResponses([
  276. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  277. fauxAssistantMessage("done"),
  278. ]);
  279. const sawToolStart = new Promise<void>((resolve) => {
  280. const unsubscribe = harness.session.subscribe((event) => {
  281. if (event.type === "tool_execution_start") {
  282. unsubscribe();
  283. resolve();
  284. }
  285. });
  286. });
  287. const promptPromise = harness.session.prompt("start");
  288. await sawToolStart;
  289. await harness.session.prompt("queued", { streamingBehavior: "followUp" });
  290. expect(inputEvents.map((event) => event.streamingBehavior)).toEqual([undefined, "followUp"]);
  291. releaseToolExecution?.();
  292. await promptPromise;
  293. });
  294. it("throws when prompted during streaming without a streamingBehavior", async () => {
  295. let releaseToolExecution: (() => void) | undefined;
  296. const toolRelease = new Promise<void>((resolve) => {
  297. releaseToolExecution = resolve;
  298. });
  299. const waitTool: AgentTool = {
  300. name: "wait",
  301. label: "Wait",
  302. description: "Wait for release",
  303. parameters: Type.Object({}),
  304. execute: async () => {
  305. await toolRelease;
  306. return {
  307. content: [{ type: "text", text: "released" }],
  308. details: {},
  309. };
  310. },
  311. };
  312. const harness = await createHarness({ tools: [waitTool] });
  313. harnesses.push(harness);
  314. harness.setResponses([
  315. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  316. fauxAssistantMessage("done"),
  317. ]);
  318. const sawToolStart = new Promise<void>((resolve) => {
  319. const unsubscribe = harness.session.subscribe((event) => {
  320. if (event.type === "tool_execution_start") {
  321. unsubscribe();
  322. resolve();
  323. }
  324. });
  325. });
  326. const promptPromise = harness.session.prompt("start");
  327. await sawToolStart;
  328. await expect(harness.session.prompt("second")).rejects.toThrow(
  329. "Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
  330. );
  331. releaseToolExecution?.();
  332. await promptPromise;
  333. });
  334. it("throws when prompting without a model", async () => {
  335. const harness = await createHarness();
  336. harnesses.push(harness);
  337. harness.session.agent.state.model = undefined as unknown as Model<any>;
  338. await expect(harness.session.prompt("hi")).rejects.toThrow("No model selected.");
  339. });
  340. it("throws when prompting without configured auth", async () => {
  341. const harness = await createHarness({ withConfiguredAuth: false });
  342. harnesses.push(harness);
  343. await expect(harness.session.prompt("hi")).rejects.toThrow(
  344. `No API key found for ${harness.getModel().provider}.`,
  345. );
  346. });
  347. });