agent-session-bash-persistence.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { Buffer } from "node:buffer";
  2. import type { AgentTool } from "@earendil-works/pi-agent-core";
  3. import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
  4. import { Type } from "typebox";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import type { BashOperations } from "../../src/core/tools/bash.ts";
  7. import { createHarness, type Harness } from "./harness.ts";
  8. function getEntryTypes(harness: Harness): string[] {
  9. return harness.sessionManager.getEntries().map((entry) => entry.type);
  10. }
  11. describe("AgentSession bash and persistence characterization", () => {
  12. const harnesses: Harness[] = [];
  13. afterEach(() => {
  14. while (harnesses.length > 0) {
  15. harnesses.pop()?.cleanup();
  16. }
  17. });
  18. it("records bash results immediately while idle", async () => {
  19. const harness = await createHarness();
  20. harnesses.push(harness);
  21. harness.session.recordBashResult("echo hi", {
  22. output: "hi",
  23. exitCode: 0,
  24. cancelled: false,
  25. truncated: false,
  26. });
  27. expect(harness.session.hasPendingBashMessages).toBe(false);
  28. expect(harness.session.messages[harness.session.messages.length - 1]?.role).toBe("bashExecution");
  29. expect(getEntryTypes(harness)).toContain("message");
  30. });
  31. it("defers bash results while streaming and flushes them before the next prompt", async () => {
  32. let releaseToolExecution: (() => void) | undefined;
  33. const toolRelease = new Promise<void>((resolve) => {
  34. releaseToolExecution = resolve;
  35. });
  36. const waitTool: AgentTool = {
  37. name: "wait",
  38. label: "Wait",
  39. description: "Wait for release",
  40. parameters: Type.Object({}),
  41. execute: async () => {
  42. await toolRelease;
  43. return {
  44. content: [{ type: "text", text: "released" }],
  45. details: {},
  46. };
  47. },
  48. };
  49. const harness = await createHarness({ tools: [waitTool] });
  50. harnesses.push(harness);
  51. harness.setResponses([
  52. fauxAssistantMessage([fauxToolCall("wait", {})], { stopReason: "toolUse" }),
  53. fauxAssistantMessage("done"),
  54. fauxAssistantMessage("after flush"),
  55. ]);
  56. const sawToolStart = new Promise<void>((resolve) => {
  57. const unsubscribe = harness.session.subscribe((event) => {
  58. if (event.type === "tool_execution_start") {
  59. unsubscribe();
  60. resolve();
  61. }
  62. });
  63. });
  64. const firstPrompt = harness.session.prompt("start");
  65. await sawToolStart;
  66. harness.session.recordBashResult("echo hi", {
  67. output: "hi",
  68. exitCode: 0,
  69. cancelled: false,
  70. truncated: false,
  71. });
  72. expect(harness.session.hasPendingBashMessages).toBe(true);
  73. expect(harness.session.messages.some((message) => message.role === "bashExecution")).toBe(false);
  74. releaseToolExecution?.();
  75. await firstPrompt;
  76. expect(harness.session.hasPendingBashMessages).toBe(false);
  77. expect(harness.session.messages.some((message) => message.role === "bashExecution")).toBe(true);
  78. await harness.session.prompt("next turn");
  79. expect(harness.session.hasPendingBashMessages).toBe(false);
  80. expect(harness.session.messages.some((message) => message.role === "bashExecution")).toBe(true);
  81. expect(getEntryTypes(harness).filter((type) => type === "message").length).toBeGreaterThan(0);
  82. });
  83. it("executes bash commands and records the result", async () => {
  84. const harness = await createHarness();
  85. harnesses.push(harness);
  86. const result = await harness.session.executeBash("printf 'hello'");
  87. expect(result.output).toContain("hello");
  88. expect(harness.session.messages[harness.session.messages.length - 1]?.role).toBe("bashExecution");
  89. });
  90. it("cancels running bash commands with abortBash", async () => {
  91. const harness = await createHarness();
  92. harnesses.push(harness);
  93. const operations: BashOperations = {
  94. exec: async (_command, _cwd, options) => {
  95. return await new Promise<{ exitCode: number | null }>((_resolve, reject) => {
  96. options.signal?.addEventListener(
  97. "abort",
  98. () => {
  99. reject(new Error("aborted"));
  100. },
  101. { once: true },
  102. );
  103. });
  104. },
  105. };
  106. const bashPromise = harness.session.executeBash("sleep", undefined, { operations });
  107. await new Promise((resolve) => setTimeout(resolve, 0));
  108. expect(harness.session.isBashRunning).toBe(true);
  109. harness.session.abortBash();
  110. const result = await bashPromise;
  111. expect(result.cancelled).toBe(true);
  112. expect(harness.session.isBashRunning).toBe(false);
  113. });
  114. it("persists user, assistant, toolResult, and custom messages in order", async () => {
  115. const echoTool: AgentTool = {
  116. name: "echo",
  117. label: "Echo",
  118. description: "Echo text back",
  119. parameters: Type.Object({ text: Type.String() }),
  120. execute: async (_toolCallId, params) => {
  121. const text = typeof params === "object" && params !== null && "text" in params ? String(params.text) : "";
  122. return { content: [{ type: "text", text: `echo:${text}` }], details: { text } };
  123. },
  124. };
  125. const harness = await createHarness({ tools: [echoTool] });
  126. harnesses.push(harness);
  127. harness.setResponses([
  128. fauxAssistantMessage([fauxToolCall("echo", { text: "hello" })], { stopReason: "toolUse" }),
  129. fauxAssistantMessage("done"),
  130. ]);
  131. await harness.session.sendCustomMessage({
  132. customType: "note",
  133. content: "hello",
  134. display: true,
  135. details: { a: 1 },
  136. });
  137. await harness.session.prompt("start");
  138. const entries = harness.sessionManager.getEntries();
  139. expect(entries.map((entry) => entry.type)).toEqual([
  140. "custom_message",
  141. "message",
  142. "message",
  143. "message",
  144. "message",
  145. ]);
  146. expect(harness.session.messages.map((message) => message.role)).toEqual([
  147. "custom",
  148. "user",
  149. "assistant",
  150. "toolResult",
  151. "assistant",
  152. ]);
  153. });
  154. it("does not emit message_end for bash execution messages", async () => {
  155. const harness = await createHarness();
  156. harnesses.push(harness);
  157. const messageEndRoles: string[] = [];
  158. harness.session.subscribe((event) => {
  159. if (event.type === "message_end") {
  160. messageEndRoles.push(event.message.role);
  161. }
  162. });
  163. harness.session.recordBashResult("echo hi", {
  164. output: "hi",
  165. exitCode: 0,
  166. cancelled: false,
  167. truncated: false,
  168. });
  169. expect(messageEndRoles).toEqual([]);
  170. });
  171. it("persists aborted assistant messages", async () => {
  172. const harness = await createHarness();
  173. harnesses.push(harness);
  174. harness.setResponses([fauxAssistantMessage("x".repeat(20_000))]);
  175. const sawMessageUpdate = new Promise<void>((resolve) => {
  176. const unsubscribe = harness.session.subscribe((event) => {
  177. if (event.type === "message_update") {
  178. unsubscribe();
  179. resolve();
  180. }
  181. });
  182. });
  183. const promptPromise = harness.session.prompt("hi");
  184. await sawMessageUpdate;
  185. await harness.session.abort();
  186. await promptPromise;
  187. const lastEntry = harness.sessionManager.getEntries()[harness.sessionManager.getEntries().length - 1];
  188. expect(lastEntry?.type).toBe("message");
  189. if (lastEntry?.type === "message") {
  190. expect(lastEntry.message.role).toBe("assistant");
  191. if (lastEntry.message.role === "assistant") {
  192. expect(lastEntry.message.stopReason).toBe("aborted");
  193. }
  194. }
  195. });
  196. it("records bash output through custom operations", async () => {
  197. const harness = await createHarness();
  198. harnesses.push(harness);
  199. const operations: BashOperations = {
  200. exec: async (_command, _cwd, options) => {
  201. options.onData(Buffer.from("hello from custom ops"));
  202. return { exitCode: 0 };
  203. },
  204. };
  205. const result = await harness.session.executeBash("custom", undefined, { operations });
  206. expect(result.output).toContain("hello from custom ops");
  207. expect(harness.session.messages[harness.session.messages.length - 1]?.role).toBe("bashExecution");
  208. });
  209. });