read-pdf-executor.test.ts 8.3 KB

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