agent-harness-stream.test.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import { fauxAssistantMessage, fauxToolCall, registerFauxProvider, type StreamOptions } from "@earendil-works/pi-ai";
  2. import { afterEach, describe, expect, it } from "vitest";
  3. import { AgentHarness } from "../../src/harness/agent-harness.ts";
  4. import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
  5. import { InMemorySessionStorage } from "../../src/harness/session/memory-storage.ts";
  6. import { Session } from "../../src/harness/session/session.ts";
  7. import { calculateTool } from "../utils/calculate.ts";
  8. const registrations: Array<{ unregister(): void }> = [];
  9. afterEach(() => {
  10. for (const registration of registrations.splice(0)) {
  11. registration.unregister();
  12. }
  13. });
  14. function createHarness(options: ConstructorParameters<typeof AgentHarness>[0]): AgentHarness {
  15. return new AgentHarness(options);
  16. }
  17. function captureOptions(options: StreamOptions | undefined): StreamOptions {
  18. return {
  19. ...options,
  20. headers: options?.headers ? { ...options.headers } : undefined,
  21. metadata: options?.metadata ? { ...options.metadata } : undefined,
  22. };
  23. }
  24. describe("AgentHarness stream configuration", () => {
  25. it("snapshots stream options and merges auth headers before provider request hooks", async () => {
  26. let capturedOptions: StreamOptions | undefined;
  27. const registration = registerFauxProvider();
  28. registrations.push(registration);
  29. registration.setResponses([
  30. (_context, options) => {
  31. capturedOptions = options;
  32. return fauxAssistantMessage("ok");
  33. },
  34. ]);
  35. const session = new Session(new InMemorySessionStorage({ metadata: { id: "session-1", createdAt: "now" } }));
  36. const harness = createHarness({
  37. env: new NodeExecutionEnv({ cwd: process.cwd() }),
  38. session,
  39. model: registration.getModel(),
  40. streamOptions: {
  41. timeoutMs: 1000,
  42. maxRetries: 2,
  43. maxRetryDelayMs: 3000,
  44. headers: { "x-base": "base" },
  45. metadata: { base: true },
  46. cacheRetention: "none",
  47. },
  48. getApiKeyAndHeaders: async () => ({ apiKey: "secret", headers: { "x-auth": "auth" } }),
  49. });
  50. harness.on("before_provider_request", (event) => {
  51. expect(event.sessionId).toBe("session-1");
  52. expect(event.streamOptions.headers).toEqual({ "x-base": "base", "x-auth": "auth" });
  53. return {
  54. streamOptions: {
  55. headers: { "x-hook": "hook" },
  56. metadata: { hook: true },
  57. },
  58. };
  59. });
  60. await harness.prompt("hello");
  61. expect(capturedOptions).toMatchObject({
  62. apiKey: "secret",
  63. timeoutMs: 1000,
  64. maxRetries: 2,
  65. maxRetryDelayMs: 3000,
  66. sessionId: "session-1",
  67. cacheRetention: "none",
  68. });
  69. expect(capturedOptions?.headers).toEqual({ "x-base": "base", "x-auth": "auth", "x-hook": "hook" });
  70. expect(capturedOptions?.metadata).toEqual({ base: true, hook: true });
  71. });
  72. it("chains provider request patches and supports deletion semantics", async () => {
  73. let capturedOptions: StreamOptions | undefined;
  74. const registration = registerFauxProvider();
  75. registrations.push(registration);
  76. registration.setResponses([
  77. (_context, options) => {
  78. capturedOptions = options;
  79. return fauxAssistantMessage("ok");
  80. },
  81. ]);
  82. const harness = createHarness({
  83. env: new NodeExecutionEnv({ cwd: process.cwd() }),
  84. session: new Session(new InMemorySessionStorage()),
  85. model: registration.getModel(),
  86. streamOptions: {
  87. timeoutMs: 1000,
  88. maxRetries: 2,
  89. headers: { keep: "base", remove: "base" },
  90. metadata: { keep: "base", remove: "base" },
  91. },
  92. });
  93. harness.on("before_provider_request", (event) => {
  94. expect(event.streamOptions.headers).toEqual({ keep: "base", remove: "base" });
  95. return {
  96. streamOptions: {
  97. headers: { first: "1", remove: undefined },
  98. metadata: { first: 1, remove: undefined },
  99. },
  100. };
  101. });
  102. harness.on("before_provider_request", (event) => {
  103. expect(event.streamOptions.headers).toEqual({ keep: "base", first: "1" });
  104. expect(event.streamOptions.metadata).toEqual({ keep: "base", first: 1 });
  105. return {
  106. streamOptions: {
  107. timeoutMs: undefined,
  108. headers: { second: "2" },
  109. metadata: undefined,
  110. },
  111. };
  112. });
  113. await harness.prompt("hello");
  114. expect(capturedOptions?.timeoutMs).toBeUndefined();
  115. expect(capturedOptions?.maxRetries).toBe(2);
  116. expect(capturedOptions?.headers).toEqual({ keep: "base", first: "1", second: "2" });
  117. expect(capturedOptions?.metadata).toBeUndefined();
  118. });
  119. it("uses updated stream options for save-point snapshots without mutating the active request", async () => {
  120. const capturedOptions: StreamOptions[] = [];
  121. const registration = registerFauxProvider();
  122. registrations.push(registration);
  123. registration.setResponses([
  124. (_context, options) => {
  125. capturedOptions.push(captureOptions(options));
  126. return fauxAssistantMessage(fauxToolCall("calculate", { expression: "1 + 1" }, { id: "call-1" }), {
  127. stopReason: "toolUse",
  128. });
  129. },
  130. (_context, options) => {
  131. capturedOptions.push(captureOptions(options));
  132. return fauxAssistantMessage("done");
  133. },
  134. ]);
  135. const harness = createHarness({
  136. env: new NodeExecutionEnv({ cwd: process.cwd() }),
  137. session: new Session(new InMemorySessionStorage()),
  138. model: registration.getModel(),
  139. tools: [calculateTool],
  140. streamOptions: { timeoutMs: 1000, headers: { turn: "first" } },
  141. });
  142. harness.subscribe((event) => {
  143. if (event.type === "tool_execution_start") {
  144. harness.setStreamOptions({ timeoutMs: 2000, headers: { turn: "second" } });
  145. }
  146. });
  147. await harness.prompt("hello");
  148. expect(capturedOptions).toHaveLength(2);
  149. expect(capturedOptions[0].timeoutMs).toBe(1000);
  150. expect(capturedOptions[0].headers).toEqual({ turn: "first" });
  151. expect(capturedOptions[1].timeoutMs).toBe(2000);
  152. expect(capturedOptions[1].headers).toEqual({ turn: "second" });
  153. });
  154. it("chains provider payload hooks", async () => {
  155. const seenPayloads: unknown[] = [];
  156. let finalPayload: unknown;
  157. const registration = registerFauxProvider();
  158. registrations.push(registration);
  159. registration.setResponses([
  160. async (_context, options, _state, model) => {
  161. finalPayload = await options?.onPayload?.({ steps: ["provider"] }, model);
  162. return fauxAssistantMessage("ok");
  163. },
  164. ]);
  165. const harness = createHarness({
  166. env: new NodeExecutionEnv({ cwd: process.cwd() }),
  167. session: new Session(new InMemorySessionStorage()),
  168. model: registration.getModel(),
  169. });
  170. harness.on("before_provider_payload", (event) => {
  171. seenPayloads.push(event.payload);
  172. return { payload: { steps: ["provider", "first"] } };
  173. });
  174. harness.on("before_provider_payload", (event) => {
  175. seenPayloads.push(event.payload);
  176. return { payload: { steps: ["provider", "first", "second"] } };
  177. });
  178. await harness.prompt("hello");
  179. expect(seenPayloads).toEqual([{ steps: ["provider"] }, { steps: ["provider", "first"] }]);
  180. expect(finalPayload).toEqual({ steps: ["provider", "first", "second"] });
  181. });
  182. });