compaction-openai-transport.integration.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. import { createServer } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { streamSimple, type Context, type Model } from "@earendil-works/pi-ai";
  4. import { Type } from "typebox";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. import { compactContext } from "../../src/service/turn-system/compaction/algorithm/compact-context.js";
  7. import { createCheckpointSession } from "../../src/service/turn-system/compaction/execution/checkpoint-provider.js";
  8. const summary =
  9. "The synthetic file was read. Continue with the pending user request.";
  10. const missingTools =
  11. "litellm.UnsupportedParamsError: Anthropic doesn't support tool calling without `tools=` param specified";
  12. interface Rejection {
  13. status: number;
  14. message: string;
  15. param?: string;
  16. code?: string;
  17. }
  18. function history(model: Model<"openai-completions">): Context["messages"] {
  19. return [
  20. { role: "user", content: "Read the synthetic file.", timestamp: 1 },
  21. {
  22. role: "assistant",
  23. content: [
  24. {
  25. type: "toolCall",
  26. id: "read-1",
  27. name: "read",
  28. arguments: { path: "fixture.txt" },
  29. },
  30. ],
  31. api: model.api,
  32. provider: model.provider,
  33. model: model.id,
  34. stopReason: "toolUse",
  35. timestamp: 2,
  36. usage: {
  37. input: 100,
  38. output: 10,
  39. cacheRead: 0,
  40. cacheWrite: 0,
  41. totalTokens: 110,
  42. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  43. },
  44. },
  45. {
  46. role: "toolResult",
  47. toolCallId: "read-1",
  48. toolName: "read",
  49. content: [{ type: "text", text: "Synthetic file contents." }],
  50. isError: false,
  51. timestamp: 3,
  52. },
  53. ];
  54. }
  55. describe("OpenAI compaction HTTP transport", () => {
  56. let server: ReturnType<typeof createServer>;
  57. let model: Model<"openai-completions">;
  58. let requests: Record<string, unknown>[];
  59. let allowEmptyTools: boolean;
  60. let rejectRequest: (body: Record<string, unknown>) => Rejection | undefined;
  61. let incompleteStream: boolean;
  62. beforeEach(async () => {
  63. requests = [];
  64. allowEmptyTools = false;
  65. rejectRequest = () => undefined;
  66. incompleteStream = false;
  67. // Exercise the real SDK serializer and stream parser with a local fixture.
  68. // This models the reported validation rule, not acceptance by a live service.
  69. server = createServer(async (request, response) => {
  70. let raw = "";
  71. for await (const chunk of request) raw += chunk;
  72. const body = JSON.parse(raw);
  73. requests.push(body);
  74. const rejection = rejectRequest(body);
  75. if (rejection) {
  76. const { status, ...error } = rejection;
  77. response
  78. .writeHead(status, { "content-type": "application/json" })
  79. .end(JSON.stringify({ error }));
  80. return;
  81. }
  82. if (
  83. !allowEmptyTools &&
  84. Array.isArray(body.tools) &&
  85. body.tools.length === 0
  86. ) {
  87. response.writeHead(400, { "content-type": "application/json" }).end(
  88. JSON.stringify({
  89. error: {
  90. message: "tools must not be an empty array",
  91. type: "invalid_request_error",
  92. param: "tools",
  93. },
  94. }),
  95. );
  96. return;
  97. }
  98. response.writeHead(200, { "content-type": "text/event-stream" });
  99. response.write(
  100. `data: ${JSON.stringify({
  101. id: "synthetic-checkpoint",
  102. object: "chat.completion.chunk",
  103. model: body.model,
  104. choices: [
  105. { index: 0, delta: { content: summary }, finish_reason: null },
  106. ],
  107. })}\n\n`,
  108. );
  109. if (incompleteStream) {
  110. response.end();
  111. return;
  112. }
  113. response.end(
  114. `data: ${JSON.stringify({
  115. choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
  116. usage: {
  117. prompt_tokens: 100,
  118. completion_tokens: 15,
  119. total_tokens: 115,
  120. },
  121. })}\n\ndata: [DONE]\n\n`,
  122. );
  123. });
  124. await new Promise<void>((resolve, reject) => {
  125. server.once("error", reject);
  126. server.listen(0, "127.0.0.1", resolve);
  127. });
  128. model = {
  129. id: "fixture-model",
  130. name: "Fixture model",
  131. api: "openai-completions",
  132. provider: "custom",
  133. baseUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`,
  134. reasoning: false,
  135. input: ["text"],
  136. contextWindow: 32_768,
  137. maxTokens: 4096,
  138. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  139. };
  140. });
  141. afterEach(async () => {
  142. if (!server?.listening) return;
  143. server.closeAllConnections();
  144. await new Promise<void>((resolve, reject) =>
  145. server.close((error) => (error ? reject(error) : resolve())),
  146. );
  147. });
  148. it.each([
  149. { provider: "custom", requiresTools: false },
  150. { provider: "openai", requiresTools: false },
  151. { provider: "custom", requiresTools: true },
  152. ])(
  153. "compacts tool history through $provider (backend requires tools: $requiresTools)",
  154. async ({ provider, requiresTools }) => {
  155. model = { ...model, provider };
  156. if (requiresTools) {
  157. allowEmptyTools = true;
  158. rejectRequest = (body) =>
  159. body.tools === undefined
  160. ? { status: 400, message: missingTools }
  161. : undefined;
  162. }
  163. const result = await compactContext({
  164. history: history(model),
  165. allowLegacyToolTrim: false,
  166. limits: {
  167. providerInputLimit: 20_000,
  168. maxSerializedInputBytes: 100_000,
  169. },
  170. // Admission is synthetic; checkpoint generation and HTTP transport are real.
  171. measurePair: async () => ({
  172. before: { inputTokens: 1000, serializedBytes: 10_000 },
  173. after: { inputTokens: 100, serializedBytes: 1000 },
  174. }),
  175. checkpoint: {
  176. tokensBefore: 1000,
  177. timestamp: 4,
  178. open: () =>
  179. createCheckpointSession({
  180. model,
  181. streamFn: streamSimple,
  182. thinkingLevel: "off",
  183. apiKey: "synthetic-key",
  184. maxOutputTokens: 1024,
  185. providerInputLimit: 20_000,
  186. }),
  187. },
  188. });
  189. expect(requests).toHaveLength(requiresTools ? 2 : 1);
  190. expect(requests[0]).not.toHaveProperty("tools");
  191. if (requiresTools)
  192. expect(requests[1]).toEqual({ ...requests[0], tools: [] });
  193. expect(requests[0]).not.toHaveProperty("tool_choice");
  194. expect(requests[0].messages).toEqual(
  195. expect.arrayContaining([
  196. expect.objectContaining({
  197. role: "assistant",
  198. tool_calls: [expect.objectContaining({ id: "read-1" })],
  199. }),
  200. expect.objectContaining({
  201. role: "tool",
  202. tool_call_id: "read-1",
  203. content: "Synthetic file contents.",
  204. }),
  205. ]),
  206. );
  207. expect(result).toMatchObject({
  208. method: "llm_checkpoint",
  209. summary,
  210. generationAttempts: 1,
  211. });
  212. expect(result.replacementMessages[0]).toMatchObject({
  213. role: "compactionSummary",
  214. });
  215. },
  216. );
  217. it.each([
  218. { label: "absent", tools: undefined },
  219. { label: "empty", tools: [] },
  220. ])("omits $label tool definitions with tool history", async ({ tools }) => {
  221. const result = await streamSimple(
  222. model,
  223. { messages: history(model), tools },
  224. { apiKey: "synthetic-key" },
  225. ).result();
  226. expect(requests).toHaveLength(1);
  227. expect(requests[0]).not.toHaveProperty("tools");
  228. expect(result.stopReason).toBe("stop");
  229. });
  230. it.each(["short", "none"] as const)(
  231. "honors the independent tools requirement with cache retention %s",
  232. async (cacheRetention) => {
  233. allowEmptyTools = true;
  234. model = { ...model, compat: { requiresToolsForToolHistory: true } };
  235. rejectRequest = (body) =>
  236. body.tools === undefined &&
  237. JSON.stringify(body.messages).includes("tool_calls")
  238. ? { status: 400, message: missingTools }
  239. : undefined;
  240. const result = await streamSimple(
  241. model,
  242. { messages: history(model) },
  243. {
  244. apiKey: "synthetic-key",
  245. cacheRetention,
  246. },
  247. ).result();
  248. expect(result.stopReason).toBe("stop");
  249. expect(requests).toHaveLength(1);
  250. expect(requests[0].tools).toEqual([]);
  251. await streamSimple(
  252. model,
  253. {
  254. messages: [{ role: "user", content: "Hello", timestamp: 1 }],
  255. tools: [],
  256. },
  257. {
  258. apiKey: "synthetic-key",
  259. cacheRetention,
  260. },
  261. ).result();
  262. expect(requests[1]).not.toHaveProperty("tools");
  263. },
  264. );
  265. it.each(["explicit", "detected"])(
  266. "does not infer a tools requirement from %s Anthropic caching",
  267. async (mode) => {
  268. model =
  269. mode === "explicit"
  270. ? { ...model, compat: { cacheControlFormat: "anthropic" } }
  271. : { ...model, provider: "openrouter", id: "anthropic/fixture-model" };
  272. const result = await streamSimple(
  273. model,
  274. { messages: history(model) },
  275. { apiKey: "synthetic-key" },
  276. ).result();
  277. expect(result.stopReason).toBe("stop");
  278. expect(requests).toHaveLength(1);
  279. expect(requests[0]).not.toHaveProperty("tools");
  280. },
  281. );
  282. it.each(["missing_required_parameter", "missing_required_argument"])(
  283. "recovers once from structured %s for tools",
  284. async (code) => {
  285. allowEmptyTools = true;
  286. rejectRequest = (body) =>
  287. body.tools === undefined
  288. ? {
  289. status: 400,
  290. message: "Required field missing",
  291. param: "tools",
  292. code,
  293. }
  294. : undefined;
  295. const onPayload = vi.fn((payload: unknown) => ({
  296. ...(payload as Record<string, unknown>),
  297. user: "synthetic-user",
  298. }));
  299. const result = await streamSimple(
  300. model,
  301. { messages: history(model) },
  302. { apiKey: "synthetic-key", onPayload },
  303. ).result();
  304. expect(result.stopReason).toBe("stop");
  305. expect(requests).toHaveLength(2);
  306. expect(onPayload).toHaveBeenCalledTimes(2);
  307. expect(requests[1]).toEqual({ ...requests[0], tools: [] });
  308. },
  309. );
  310. it("does not retry again if the recovery request also fails", async () => {
  311. rejectRequest = () => ({ status: 400, message: missingTools });
  312. const result = await streamSimple(
  313. model,
  314. { messages: history(model) },
  315. { apiKey: "synthetic-key" },
  316. ).result();
  317. expect(requests).toHaveLength(2);
  318. expect(requests[1].tools).toEqual([]);
  319. expect(result.stopReason).toBe("error");
  320. });
  321. it("disables SDK retries on the recovery request", async () => {
  322. rejectRequest = (body) =>
  323. body.tools === undefined
  324. ? { status: 400, message: missingTools }
  325. : { status: 500, message: "Synthetic server failure" };
  326. const result = await streamSimple(
  327. model,
  328. { messages: history(model) },
  329. {
  330. apiKey: "synthetic-key",
  331. maxRetries: 3,
  332. },
  333. ).result();
  334. expect(requests).toHaveLength(2);
  335. expect(result.stopReason).toBe("error");
  336. });
  337. it.each([
  338. "no history",
  339. "nonempty definitions",
  340. "explicit true",
  341. "hook tools",
  342. ])("does not recover with %s", async (mode) => {
  343. rejectRequest = () => ({ status: 400, message: missingTools });
  344. if (mode === "explicit true")
  345. model = { ...model, compat: { requiresToolsForToolHistory: true } };
  346. const context: Context = {
  347. messages:
  348. mode === "no history"
  349. ? [{ role: "user", content: "Hello", timestamp: 1 }]
  350. : history(model),
  351. };
  352. if (mode === "nonempty definitions")
  353. context.tools = [
  354. {
  355. name: "read",
  356. description: "Read a file",
  357. parameters: Type.Object({}),
  358. },
  359. ];
  360. const result = await streamSimple(model, context, {
  361. apiKey: "synthetic-key",
  362. onPayload:
  363. mode === "hook tools"
  364. ? (payload) => ({
  365. ...(payload as Record<string, unknown>),
  366. tools: [],
  367. })
  368. : undefined,
  369. }).result();
  370. expect(requests).toHaveLength(1);
  371. expect(result.stopReason).toBe("error");
  372. });
  373. it.each([
  374. {
  375. status: 400,
  376. message: "tools must not be an empty array",
  377. param: "tools",
  378. },
  379. { status: 400, message: "invalid tool schema", param: "tools" },
  380. { status: 400, message: `Invalid user content: ${missingTools}` },
  381. {
  382. status: 400,
  383. message: "Required field missing",
  384. param: "messages",
  385. code: "missing_required_parameter",
  386. },
  387. ...[401, 403, 429, 500].map((status) => ({
  388. status,
  389. message: missingTools,
  390. })),
  391. ])(
  392. "does not recover unrelated error $status: $message ($param)",
  393. async (rejection) => {
  394. rejectRequest = () => rejection;
  395. const result = await streamSimple(
  396. model,
  397. { messages: history(model) },
  398. { apiKey: "synthetic-key" },
  399. ).result();
  400. expect(requests).toHaveLength(1);
  401. expect(result.stopReason).toBe("error");
  402. },
  403. );
  404. it("honors explicit false even when the backend requires tools", async () => {
  405. model = { ...model, compat: { requiresToolsForToolHistory: false } };
  406. rejectRequest = () => ({ status: 400, message: missingTools });
  407. const result = await streamSimple(
  408. model,
  409. { messages: history(model) },
  410. { apiKey: "synthetic-key" },
  411. ).result();
  412. expect(requests).toHaveLength(1);
  413. expect(result.stopReason).toBe("error");
  414. });
  415. it("does not recover without tool history in the final payload", async () => {
  416. rejectRequest = () => ({ status: 400, message: missingTools });
  417. const result = await streamSimple(
  418. model,
  419. { messages: history(model) },
  420. {
  421. apiKey: "synthetic-key",
  422. onPayload: (payload) => ({
  423. ...(payload as Record<string, unknown>),
  424. messages: [{ role: "user", content: "Hello" }],
  425. }),
  426. },
  427. ).result();
  428. expect(requests).toHaveLength(1);
  429. expect(result.stopReason).toBe("error");
  430. });
  431. it("does not resend when a payload hook removes the recovery tools", async () => {
  432. rejectRequest = () => ({ status: 400, message: missingTools });
  433. const onPayload = vi.fn((payload: unknown) => {
  434. const { tools: _tools, ...rest } = payload as Record<string, unknown>;
  435. return rest;
  436. });
  437. const result = await streamSimple(
  438. model,
  439. { messages: history(model) },
  440. { apiKey: "synthetic-key", onPayload },
  441. ).result();
  442. expect(onPayload).toHaveBeenCalledTimes(2);
  443. expect(requests).toHaveLength(1);
  444. expect(result.stopReason).toBe("error");
  445. });
  446. it("honors cancellation during the recovery payload hook", async () => {
  447. rejectRequest = () => ({ status: 400, message: missingTools });
  448. const controller = new AbortController();
  449. const onPayload = vi.fn((payload: unknown) => {
  450. if (Array.isArray((payload as Record<string, unknown>).tools))
  451. controller.abort();
  452. });
  453. const result = await streamSimple(
  454. model,
  455. { messages: history(model) },
  456. {
  457. apiKey: "synthetic-key",
  458. signal: controller.signal,
  459. onPayload,
  460. },
  461. ).result();
  462. expect(onPayload).toHaveBeenCalledTimes(2);
  463. expect(requests).toHaveLength(1);
  464. expect(result.stopReason).toBe("aborted");
  465. });
  466. it("does not restart a response stream that ended without a finish reason", async () => {
  467. incompleteStream = true;
  468. const result = await streamSimple(
  469. model,
  470. { messages: history(model) },
  471. { apiKey: "synthetic-key" },
  472. ).result();
  473. expect(requests).toHaveLength(1);
  474. expect(result.content).toEqual([
  475. expect.objectContaining({ type: "text", text: summary }),
  476. ]);
  477. expect(result.stopReason).toBe("error");
  478. });
  479. it("preserves nonempty tool definitions on ordinary agent requests", async () => {
  480. const result = await streamSimple(
  481. model,
  482. {
  483. messages: history(model),
  484. tools: [
  485. {
  486. name: "read",
  487. description: "Read a synthetic file",
  488. parameters: Type.Object({ path: Type.String() }),
  489. },
  490. ],
  491. },
  492. { apiKey: "synthetic-key" },
  493. ).result();
  494. expect(result.stopReason).toBe("stop");
  495. expect(requests[0].tools).toEqual([
  496. expect.objectContaining({
  497. type: "function",
  498. function: expect.objectContaining({ name: "read" }),
  499. }),
  500. ]);
  501. });
  502. });