read-pdf-executor.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. CoreErrorType,
  4. PdfDocumentPortError,
  5. createModelId,
  6. createModelProviderId,
  7. createRootTraceContext,
  8. createSessionId,
  9. createToolCallId,
  10. createTurnId,
  11. type FileSystemPort,
  12. type ImageProcessorPort,
  13. type PdfDocumentPort,
  14. } from "@zcode/contracts";
  15. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  16. import { type AgentRuntime } from "../src/runtime.js";
  17. import { createTurnModel } from "../src/runtime/methods/turn-model.js";
  18. import { createToolExecutor } from "../src/tool/executor.js";
  19. import { readToolEntry } from "../src/tool/handlers/read.js";
  20. import { createToolRegistry } from "../src/tool/registry.js";
  21. import { createTestSessionEventStore } from "./test-event-store.js";
  22. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  23. import { createTestModelFactory, createTestRuntimeModel } from "./test-runtime-model.js";
  24. describe("Read PDF executor schema", () => {
  25. it("keeps the 120-second Poppler timeout inside a 150-second PDF tool budget", () => {
  26. const input = { file_path: "/tmp/report.pdf", pages: "1" };
  27. expect(
  28. readToolEntry.resolveTimeoutBudgetMs?.(input, {
  29. model: modelWith({ supportsPdf: true }),
  30. }),
  31. ).toBe(150_000);
  32. expect(
  33. readToolEntry.resolveTimeoutBudgetMs?.(input, {
  34. model: modelWith({ supportsPdf: false }),
  35. }),
  36. ).toBeUndefined();
  37. });
  38. it("projects the PDF schema and description from the same model capability snapshot", () => {
  39. const runtime = createTestAgentRuntime(
  40. createSessionId("read-pdf-tool-shape"),
  41. {},
  42. { eventStore: createTestSessionEventStore() },
  43. );
  44. const supported = readTool(runtime, { supportsPdf: true, supportsImages: true });
  45. const unsupported = readTool(runtime, { supportsPdf: false, supportsImages: true });
  46. expect(supported.description.split("\n")).toContain(
  47. '- Reads PDFs via the `pages` parameter (e.g. "1-5", max 20 pages/request; required for PDFs over 10 pages).',
  48. );
  49. expect(supported.inputSchema.properties).toHaveProperty("pages");
  50. expect(unsupported.description).not.toContain("Reads PDFs via the `pages` parameter");
  51. expect(unsupported.inputSchema.properties).not.toHaveProperty("pages");
  52. });
  53. it("uses the same capability-matched pages schema as the provider tool shape", async () => {
  54. const renderPages = vi.fn(async () => [
  55. {
  56. pageNumber: 1,
  57. data: new Uint8Array(Buffer.from("page-one")),
  58. mediaType: "image/jpeg" as const,
  59. },
  60. ]);
  61. const supported = await execute({ supportsPdf: true, supportsImages: true }, { renderPages });
  62. expect(supported.success).toBe(true);
  63. expect(renderPages).toHaveBeenCalledTimes(1);
  64. const unsupported = await execute(
  65. { supportsPdf: false, supportsImages: true },
  66. { renderPages },
  67. );
  68. expect(unsupported.success).toBe(false);
  69. expect(renderPages).toHaveBeenCalledTimes(1);
  70. });
  71. it("classifies adapter-side PDF cancellation through the executor", async () => {
  72. const result = await execute(
  73. { supportsPdf: true, supportsImages: true },
  74. {
  75. renderPages: async () => {
  76. throw new PdfDocumentPortError("cancelled", "PDF extraction cancelled");
  77. },
  78. },
  79. );
  80. expect(result).toMatchObject({
  81. error: {
  82. type: CoreErrorType.ToolCancelled,
  83. },
  84. success: false,
  85. });
  86. });
  87. it.each([
  88. {
  89. errorCode: 7,
  90. message:
  91. 'Invalid pages parameter: "invalid". Use formats like "1-5", "3", or "10-20". Pages are 1-indexed.',
  92. pages: "invalid",
  93. },
  94. {
  95. errorCode: 8,
  96. message:
  97. 'Page range "1-21" exceeds maximum of 20 pages per request. Please use a smaller range.',
  98. pages: "1-21",
  99. },
  100. ])(
  101. "rejects PDF pages with error $errorCode before hooks, permission, and I/O",
  102. async ({ errorCode, message, pages }) => {
  103. const renderPages = vi.fn();
  104. const stat = vi.fn();
  105. const hookRun = vi.fn(async () => ({ additionalContexts: [] }));
  106. const permissionService = new PermissionService(defaultPermissionConfig);
  107. const permissionCheck = vi.spyOn(permissionService, "checkPermission");
  108. const result = await execute(
  109. { supportsPdf: true, supportsImages: true },
  110. { renderPages },
  111. {
  112. fileSystemPort: { stat } as unknown as FileSystemPort,
  113. hookRun,
  114. input: { file_path: "/tmp/report.pdf", pages },
  115. permissionService,
  116. },
  117. );
  118. expect(result).toMatchObject({
  119. error: { code: String(errorCode), message },
  120. modelContent: `<tool_use_error>${message}</tool_use_error>`,
  121. success: false,
  122. });
  123. expect(hookRun).not.toHaveBeenCalled();
  124. expect(permissionCheck).not.toHaveBeenCalled();
  125. expect(stat).not.toHaveBeenCalled();
  126. expect(renderPages).not.toHaveBeenCalled();
  127. },
  128. );
  129. it("does not fall back to session PDF support when the current turn snapshot is unknown", () => {
  130. const runtime = createTestAgentRuntime(
  131. createSessionId("read-pdf-turn-snapshot"),
  132. {},
  133. {
  134. eventStore: createTestSessionEventStore(),
  135. modelFactory: createTestModelFactory({
  136. properties: {
  137. inputFormat: {
  138. supportsText: true,
  139. supportsImage: true,
  140. supportsVideo: false,
  141. supportsAudio: false,
  142. supportsPdf: false,
  143. },
  144. },
  145. }),
  146. },
  147. );
  148. const turnModel = createTurnModel(runtime as never);
  149. const read = turnModel
  150. ? runtime.getTools(turnModel).find((candidate) => candidate.name === "Read")
  151. : undefined;
  152. expect(turnModel.properties.inputFormat.supportsPdf).toBe(false);
  153. expect(read?.inputSchema.properties).not.toHaveProperty("pages");
  154. });
  155. });
  156. function readTool(
  157. runtime: AgentRuntime,
  158. capabilities: { supportsPdf?: boolean; supportsImages?: boolean },
  159. ) {
  160. const tool = runtime
  161. .getTools(modelWith(capabilities))
  162. .find((candidate) => candidate.name === "Read");
  163. if (!tool) throw new Error("Read tool was not registered");
  164. return tool;
  165. }
  166. function modelWith(capabilities: { supportsPdf?: boolean; supportsImages?: boolean }) {
  167. return createTestRuntimeModel({
  168. generateText: async () => ({ finishReason: "stop", text: "", usage: {} }),
  169. inputFormat: {
  170. supportsPdf: capabilities.supportsPdf ?? false,
  171. supportsImage: capabilities.supportsImages ?? false,
  172. },
  173. modelId: "pdf-shape-model",
  174. });
  175. }
  176. async function execute(
  177. capabilities: { supportsPdf?: boolean; supportsImages?: boolean },
  178. pdfPort: Partial<PdfDocumentPort>,
  179. options: {
  180. fileSystemPort?: FileSystemPort;
  181. hookRun?: ReturnType<typeof vi.fn>;
  182. input?: { file_path: string; pages: string };
  183. permissionService?: PermissionService;
  184. } = {},
  185. ) {
  186. const sessionId = createSessionId("read-pdf-executor");
  187. const turnId = createTurnId("read-pdf-executor");
  188. const traceContext = createRootTraceContext({ sessionId, turnId });
  189. const registry = createToolRegistry();
  190. registry.register(readToolEntry);
  191. return createToolExecutor({
  192. emitEvent: async () => {},
  193. fileSystemPort: options.fileSystemPort ?? fileSystemPort(),
  194. ...(options.hookRun ? { hookRunner: { run: options.hookRun } } : {}),
  195. imageProcessorPort: imageProcessorPort(),
  196. pdfDocumentPort: pdfPort as PdfDocumentPort,
  197. model: modelWith(capabilities),
  198. permissionService: options.permissionService ?? new PermissionService(defaultPermissionConfig),
  199. registry,
  200. sessionId,
  201. traceContext,
  202. turnId,
  203. workingDirectory: "/tmp",
  204. workspaceRoot: "/tmp",
  205. }).execute(
  206. {
  207. id: createToolCallId("read-pdf-executor"),
  208. input: options.input ?? { file_path: "/tmp/report.pdf", pages: "1" },
  209. name: "Read",
  210. },
  211. { traceContext },
  212. );
  213. }
  214. function fileSystemPort(): FileSystemPort {
  215. return {
  216. async stat(request) {
  217. return { path: request.path, kind: "file", sizeBytes: 10 };
  218. },
  219. } as FileSystemPort;
  220. }
  221. function imageProcessorPort(): ImageProcessorPort {
  222. return {
  223. async prepareForModel(request) {
  224. return {
  225. data: request.data,
  226. mediaType: request.mediaType,
  227. originalSizeBytes: request.data.byteLength,
  228. transformedSizeBytes: request.data.byteLength,
  229. resized: false,
  230. compressed: false,
  231. strategy: "original" as const,
  232. };
  233. },
  234. };
  235. }