test-harness.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /**
  2. * Test harness for AgentSession runtime testing.
  3. *
  4. * Provides:
  5. * - A faux stream function with declarative response sequencing
  6. * - A one-call factory for a fully wired AgentSession with real in-memory dependencies
  7. * - Event capture for assertions
  8. */
  9. import { existsSync, mkdirSync, rmSync } from "node:fs";
  10. import { tmpdir } from "node:os";
  11. import { join } from "node:path";
  12. import type { AgentTool } from "@earendil-works/pi-agent-core";
  13. import { Agent } from "@earendil-works/pi-agent-core";
  14. import type {
  15. AssistantMessage,
  16. AssistantMessageEvent,
  17. AssistantMessageEventStream,
  18. Context,
  19. Model,
  20. SimpleStreamOptions,
  21. StopReason,
  22. TextContent,
  23. ThinkingContent,
  24. ToolCall,
  25. Usage,
  26. } from "@earendil-works/pi-ai";
  27. import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
  28. import { AgentSession, type AgentSessionEvent } from "../src/core/agent-session.ts";
  29. import { AuthStorage } from "../src/core/auth-storage.ts";
  30. import { ModelRegistry } from "../src/core/model-registry.ts";
  31. import { SessionManager } from "../src/core/session-manager.ts";
  32. import type { Settings } from "../src/core/settings-manager.ts";
  33. import { SettingsManager } from "../src/core/settings-manager.ts";
  34. import type { ExtensionFactory, ResourceLoader } from "../src/index.ts";
  35. import {
  36. type CreateTestExtensionsResultInput,
  37. createTestExtensionsResult,
  38. createTestResourceLoader,
  39. } from "./utilities.ts";
  40. // ============================================================================
  41. // Faux model
  42. // ============================================================================
  43. const FAUX_PROVIDER = "faux";
  44. const FAUX_MODEL_ID = "faux-1";
  45. const FAUX_API = "anthropic-messages" as const;
  46. export const fauxModel: Model<typeof FAUX_API> = {
  47. id: FAUX_MODEL_ID,
  48. name: "Faux Model",
  49. api: FAUX_API,
  50. provider: FAUX_PROVIDER,
  51. baseUrl: "http://localhost:0",
  52. reasoning: false,
  53. input: ["text", "image"],
  54. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  55. contextWindow: 128000,
  56. maxTokens: 16384,
  57. };
  58. // ============================================================================
  59. // Response description
  60. // ============================================================================
  61. export interface FauxResponse {
  62. /** Text content blocks. String shorthand becomes a single text block. */
  63. text?: string;
  64. /** Tool calls to include in the response. */
  65. toolCalls?: Array<{ id?: string; name: string; args: Record<string, unknown> }>;
  66. /** Thinking content. */
  67. thinking?: string;
  68. /** Stop reason. Defaults to "stop", or "toolUse" if toolCalls are present, or "error" if error is set. */
  69. stopReason?: StopReason;
  70. /** Error message. Sets stopReason to "error" if not explicitly set. */
  71. error?: string;
  72. /** Usage numbers. Merged with defaults (input: 100, output: 50). */
  73. usage?: Partial<Usage>;
  74. /** Delay in ms before the response starts. */
  75. delayMs?: number;
  76. /** Model overrides (provider, model id) for responses that should look like they came from a different model. */
  77. model?: { provider?: string; id?: string };
  78. }
  79. /** Shorthand: a string becomes a simple text response. */
  80. export type FauxResponseInput = FauxResponse | string;
  81. // ============================================================================
  82. // Faux stream function
  83. // ============================================================================
  84. function normalizeResponse(input: FauxResponseInput): FauxResponse {
  85. if (typeof input === "string") {
  86. return { text: input };
  87. }
  88. return input;
  89. }
  90. function buildUsage(partial?: Partial<Usage>): Usage {
  91. const input = partial?.input ?? 100;
  92. const output = partial?.output ?? 50;
  93. const cacheRead = partial?.cacheRead ?? 0;
  94. const cacheWrite = partial?.cacheWrite ?? 0;
  95. return {
  96. input,
  97. output,
  98. cacheRead,
  99. cacheWrite,
  100. totalTokens: partial?.totalTokens ?? input + output + cacheRead + cacheWrite,
  101. cost: partial?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  102. };
  103. }
  104. let toolCallIdCounter = 0;
  105. function buildAssistantMessage(resp: FauxResponse): AssistantMessage {
  106. const content: (TextContent | ThinkingContent | ToolCall)[] = [];
  107. if (resp.thinking) {
  108. content.push({ type: "thinking", thinking: resp.thinking });
  109. }
  110. if (resp.text !== undefined) {
  111. content.push({ type: "text", text: resp.text });
  112. }
  113. if (resp.toolCalls) {
  114. for (const tc of resp.toolCalls) {
  115. content.push({
  116. type: "toolCall",
  117. id: tc.id ?? `faux_tc_${++toolCallIdCounter}`,
  118. name: tc.name,
  119. arguments: tc.args,
  120. });
  121. }
  122. }
  123. // If no content was added at all, add empty text
  124. if (content.length === 0 && !resp.error) {
  125. content.push({ type: "text", text: "" });
  126. }
  127. let stopReason: StopReason;
  128. if (resp.stopReason) {
  129. stopReason = resp.stopReason;
  130. } else if (resp.error) {
  131. stopReason = "error";
  132. } else if (resp.toolCalls && resp.toolCalls.length > 0) {
  133. stopReason = "toolUse";
  134. } else {
  135. stopReason = "stop";
  136. }
  137. return {
  138. role: "assistant",
  139. content,
  140. api: FAUX_API,
  141. provider: resp.model?.provider ?? FAUX_PROVIDER,
  142. model: resp.model?.id ?? FAUX_MODEL_ID,
  143. usage: buildUsage(resp.usage),
  144. stopReason,
  145. errorMessage: resp.error,
  146. timestamp: Date.now(),
  147. };
  148. }
  149. // ============================================================================
  150. // Token-level streaming
  151. // ============================================================================
  152. /** Split a string into chunks of varying size (3-5 chars) for simulating token-by-token streaming. */
  153. function chunkString(text: string): string[] {
  154. const chunks: string[] = [];
  155. let i = 0;
  156. while (i < text.length) {
  157. const size = 3 + Math.floor(Math.random() * 3); // 3, 4, or 5
  158. chunks.push(text.slice(i, i + size));
  159. i += size;
  160. }
  161. return chunks.length > 0 ? chunks : [""];
  162. }
  163. /**
  164. * Stream a complete AssistantMessage through an EventStream with realistic
  165. * intermediate delta events for each content block.
  166. */
  167. function streamWithDeltas(stream: AssistantMessageEventStream, message: AssistantMessage): void {
  168. const isError = message.stopReason === "error" || message.stopReason === "aborted";
  169. // Build partial progressively as we stream content blocks
  170. const partial: AssistantMessage = { ...message, content: [] };
  171. stream.push({ type: "start", partial: { ...partial } });
  172. for (let i = 0; i < message.content.length; i++) {
  173. const block = message.content[i];
  174. if (block.type === "thinking") {
  175. partial.content = [...partial.content, { type: "thinking", thinking: "" }];
  176. stream.push({ type: "thinking_start", contentIndex: i, partial: { ...partial } });
  177. for (const chunk of chunkString(block.thinking)) {
  178. (partial.content[i] as ThinkingContent).thinking += chunk;
  179. stream.push(makeEvent("thinking_delta", i, chunk, partial));
  180. }
  181. stream.push({
  182. type: "thinking_end",
  183. contentIndex: i,
  184. content: block.thinking,
  185. partial: { ...partial },
  186. });
  187. } else if (block.type === "text") {
  188. partial.content = [...partial.content, { type: "text", text: "" }];
  189. stream.push({ type: "text_start", contentIndex: i, partial: { ...partial } });
  190. for (const chunk of chunkString(block.text)) {
  191. (partial.content[i] as TextContent).text += chunk;
  192. stream.push(makeEvent("text_delta", i, chunk, partial));
  193. }
  194. stream.push({
  195. type: "text_end",
  196. contentIndex: i,
  197. content: block.text,
  198. partial: { ...partial },
  199. });
  200. } else if (block.type === "toolCall") {
  201. const argsJson = JSON.stringify(block.arguments);
  202. partial.content = [...partial.content, { type: "toolCall", id: block.id, name: block.name, arguments: {} }];
  203. stream.push({ type: "toolcall_start", contentIndex: i, partial: { ...partial } });
  204. for (const chunk of chunkString(argsJson)) {
  205. stream.push(makeEvent("toolcall_delta", i, chunk, partial));
  206. }
  207. // Final toolcall has the real parsed arguments
  208. (partial.content[i] as ToolCall).arguments = block.arguments;
  209. stream.push({
  210. type: "toolcall_end",
  211. contentIndex: i,
  212. toolCall: block,
  213. partial: { ...partial },
  214. });
  215. }
  216. }
  217. if (isError) {
  218. stream.push({ type: "error", reason: message.stopReason as "error" | "aborted", error: message });
  219. } else {
  220. stream.push({ type: "done", reason: message.stopReason as "stop" | "length" | "toolUse", message });
  221. }
  222. }
  223. function makeEvent(
  224. type: "text_delta" | "thinking_delta" | "toolcall_delta",
  225. contentIndex: number,
  226. delta: string,
  227. partial: AssistantMessage,
  228. ): AssistantMessageEvent {
  229. return { type, contentIndex, delta, partial: { ...partial } };
  230. }
  231. // ============================================================================
  232. // Stream function factory
  233. // ============================================================================
  234. export interface FauxStreamFnState {
  235. /** Number of times the stream function has been called. */
  236. callCount: number;
  237. /** The context passed to each call, in order. */
  238. contexts: Context[];
  239. }
  240. /**
  241. * Create a faux stream function from a sequence of response descriptions.
  242. *
  243. * The function cycles through responses in order. If more calls are made than
  244. * responses provided, it wraps around.
  245. *
  246. * Returns the stream function and a state object for inspection.
  247. */
  248. export function createFauxStreamFn(responses: FauxResponseInput[]): {
  249. streamFn: (model: Model<any>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;
  250. state: FauxStreamFnState;
  251. } {
  252. if (responses.length === 0) {
  253. throw new Error("createFauxStreamFn requires at least one response");
  254. }
  255. const state: FauxStreamFnState = { callCount: 0, contexts: [] };
  256. const streamFn = (_model: Model<any>, context: Context, _options?: SimpleStreamOptions) => {
  257. const index = state.callCount % responses.length;
  258. state.callCount++;
  259. state.contexts.push(context);
  260. const resp = normalizeResponse(responses[index]);
  261. const message = buildAssistantMessage(resp);
  262. const stream = createAssistantMessageEventStream();
  263. const emit = () => {
  264. streamWithDeltas(stream, message);
  265. };
  266. if (resp.delayMs && resp.delayMs > 0) {
  267. setTimeout(emit, resp.delayMs);
  268. } else {
  269. queueMicrotask(emit);
  270. }
  271. return stream;
  272. };
  273. return { streamFn, state };
  274. }
  275. // ============================================================================
  276. // Session harness
  277. // ============================================================================
  278. export interface HarnessOptions {
  279. /** Response sequence for the faux provider. Default: single "ok" response. */
  280. responses?: FauxResponseInput[];
  281. /** Model to use. Default: fauxModel. */
  282. model?: Model<any>;
  283. /** Context window override (applied to the model). */
  284. contextWindow?: number;
  285. /** Settings overrides (retry, compaction, etc.). */
  286. settings?: Partial<Settings>;
  287. /** System prompt. Default: "You are a test assistant." */
  288. systemPrompt?: string;
  289. /** Custom tools to register on the agent. */
  290. tools?: AgentTool[];
  291. /** Base tools override (replaces built-in read/bash/edit/write). */
  292. baseToolsOverride?: Record<string, AgentTool>;
  293. /** Optional resource loader override. */
  294. resourceLoader?: ResourceLoader;
  295. /** Inline extensions to load into the session resource loader. */
  296. extensionFactories?: Array<ExtensionFactory | CreateTestExtensionsResultInput>;
  297. }
  298. export interface Harness {
  299. session: AgentSession;
  300. agent: Agent;
  301. sessionManager: SessionManager;
  302. settingsManager: SettingsManager;
  303. /** Faux stream function state (call count, captured contexts). */
  304. faux: FauxStreamFnState;
  305. /** All events emitted by the session, in order. */
  306. events: AgentSessionEvent[];
  307. /** Filter captured events by type. */
  308. eventsOfType<T extends AgentSessionEvent["type"]>(type: T): Extract<AgentSessionEvent, { type: T }>[];
  309. /** Temp directory (cleaned up by cleanup()). */
  310. tempDir: string;
  311. /** Dispose session and remove temp directory. */
  312. cleanup: () => void;
  313. }
  314. function createTempDir(): string {
  315. const tempDir = join(tmpdir(), `pi-harness-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  316. mkdirSync(tempDir, { recursive: true });
  317. return tempDir;
  318. }
  319. function createHarnessWithResourceLoader(
  320. options: HarnessOptions,
  321. resourceLoader: ResourceLoader,
  322. tempDir: string,
  323. ): Harness {
  324. const baseModel = options.model ?? fauxModel;
  325. const model: Model<any> = options.contextWindow ? { ...baseModel, contextWindow: options.contextWindow } : baseModel;
  326. const { streamFn, state: fauxState } = createFauxStreamFn(options.responses ?? ["ok"]);
  327. const agent = new Agent({
  328. getApiKey: () => "faux-key",
  329. initialState: {
  330. model,
  331. systemPrompt: options.systemPrompt ?? "You are a test assistant.",
  332. tools: options.tools ?? [],
  333. },
  334. streamFn,
  335. });
  336. const sessionManager = SessionManager.inMemory();
  337. const settingsManager = SettingsManager.create(tempDir, tempDir);
  338. if (options.settings) {
  339. settingsManager.applyOverrides(options.settings);
  340. }
  341. const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
  342. authStorage.setRuntimeApiKey(model.provider, "faux-key");
  343. const modelRegistry = ModelRegistry.create(authStorage, tempDir);
  344. const session = new AgentSession({
  345. agent,
  346. sessionManager,
  347. settingsManager,
  348. cwd: tempDir,
  349. modelRegistry,
  350. resourceLoader,
  351. baseToolsOverride: options.baseToolsOverride,
  352. });
  353. const events: AgentSessionEvent[] = [];
  354. session.subscribe((event) => {
  355. events.push(event);
  356. });
  357. const cleanup = () => {
  358. session.dispose();
  359. if (existsSync(tempDir)) {
  360. rmSync(tempDir, { recursive: true });
  361. }
  362. };
  363. return {
  364. session,
  365. agent,
  366. sessionManager,
  367. settingsManager,
  368. faux: fauxState,
  369. events,
  370. eventsOfType<T extends AgentSessionEvent["type"]>(type: T) {
  371. return events.filter((e): e is Extract<AgentSessionEvent, { type: T }> => e.type === type);
  372. },
  373. tempDir,
  374. cleanup,
  375. };
  376. }
  377. export function createHarness(options: HarnessOptions = {}): Harness {
  378. if (options.extensionFactories?.length) {
  379. throw new Error("createHarness does not support extensionFactories. Use createHarnessWithExtensions().");
  380. }
  381. const tempDir = createTempDir();
  382. return createHarnessWithResourceLoader(options, options.resourceLoader ?? createTestResourceLoader(), tempDir);
  383. }
  384. export async function createHarnessWithExtensions(options: HarnessOptions = {}): Promise<Harness> {
  385. const tempDir = createTempDir();
  386. const extensionsResult = await createTestExtensionsResult(options.extensionFactories ?? [], tempDir);
  387. const resourceLoader = options.resourceLoader ?? createTestResourceLoader({ extensionsResult });
  388. return createHarnessWithResourceLoader(options, resourceLoader, tempDir);
  389. }