read-pdf-executor.test.ts 8.4 KB

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