@abhishek944/pi-classifier 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +269 -31
  3. package/dist/auth.d.ts +4 -2
  4. package/dist/auth.js +18 -2
  5. package/dist/box-tool.d.ts +2 -24
  6. package/dist/box-tool.js +5 -35
  7. package/dist/choices.js +35 -1
  8. package/dist/classify.d.ts +3 -0
  9. package/dist/classify.js +3 -3
  10. package/dist/config.d.ts +140 -3
  11. package/dist/config.js +401 -20
  12. package/dist/cost.js +42 -4
  13. package/dist/durable.d.ts +34 -0
  14. package/dist/durable.js +237 -0
  15. package/dist/extension.d.ts +2 -275
  16. package/dist/extension.js +49 -211
  17. package/dist/extract.d.ts +11 -0
  18. package/dist/extract.js +191 -0
  19. package/dist/http.d.ts +6 -1
  20. package/dist/http.js +64 -28
  21. package/dist/index.d.ts +3 -1
  22. package/dist/index.js +1 -0
  23. package/dist/inputs.d.ts +16 -1
  24. package/dist/inputs.js +421 -14
  25. package/dist/mcp-cli.d.ts +2 -0
  26. package/dist/mcp-cli.js +39 -0
  27. package/dist/mcp-server.d.ts +28 -0
  28. package/dist/mcp-server.js +121 -0
  29. package/dist/mcp-tool-definitions.d.ts +19 -0
  30. package/dist/mcp-tool-definitions.js +64 -0
  31. package/dist/providers.d.ts +1 -0
  32. package/dist/providers.js +1144 -53
  33. package/dist/tool-contracts.d.ts +785 -0
  34. package/dist/tool-contracts.js +530 -0
  35. package/dist/tree.js +1 -1
  36. package/dist/types.d.ts +284 -8
  37. package/dist/validation.js +122 -10
  38. package/package.json +34 -6
  39. package/src/auth.ts +26 -2
  40. package/src/box-tool.ts +12 -47
  41. package/src/choices.ts +42 -1
  42. package/src/classify.ts +6 -4
  43. package/src/config.ts +450 -23
  44. package/src/cost.ts +42 -4
  45. package/src/durable.ts +298 -0
  46. package/src/extension.ts +75 -288
  47. package/src/extract.ts +228 -0
  48. package/src/http.ts +63 -32
  49. package/src/index.ts +15 -0
  50. package/src/inputs.ts +454 -13
  51. package/src/mcp-cli.ts +44 -0
  52. package/src/mcp-server.ts +179 -0
  53. package/src/mcp-tool-definitions.ts +104 -0
  54. package/src/providers.ts +1323 -56
  55. package/src/tool-contracts.ts +785 -0
  56. package/src/tree.ts +1 -1
  57. package/src/types.ts +231 -5
  58. package/src/validation.ts +114 -9
package/src/inputs.ts CHANGED
@@ -6,14 +6,23 @@ import { promisify } from "node:util";
6
6
  import sharp from "sharp";
7
7
  import {
8
8
  ClassifierError,
9
+ isRecord,
9
10
  type ClassifyParams,
11
+ type ExtractParams,
10
12
  type PreparedImage,
11
13
  type PreparedLocalImage,
12
14
  type PreparedInput,
15
+ type PreparedMedia,
13
16
  type ResolvedModel,
14
17
  } from "./types.js";
15
18
  import { hasBox } from "./validation.js";
16
- import { imageReferences } from "./image-content.js";
19
+ import { imageReferences, isImageReference } from "./image-content.js";
20
+ import { openRouterDecisionCapabilities, openRouterExtractionCapabilities } from "./config.js";
21
+
22
+ function topLevelImagePartsOnly(value: unknown): boolean {
23
+ if (isImageReference(value)) return true;
24
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string" || isImageReference(entry));
25
+ }
17
26
 
18
27
  /** Programmatic image ingress. Never accepted as model-facing tool arguments. */
19
28
  export interface MemoryImage {
@@ -28,28 +37,105 @@ export async function prepareInput(
28
37
  signal?: AbortSignal,
29
38
  memoryImages: readonly MemoryImage[] = [],
30
39
  ): Promise<PreparedInput> {
40
+ const questionCount = Object.keys(params.questions).length;
41
+ if (questionCount > route.limits.maxQuestions)
42
+ throw new ClassifierError(
43
+ "input",
44
+ "The selected route accepts at most " + route.limits.maxQuestions + " questions in this package.",
45
+ );
46
+ if (route.api === "perplexity-decisions" && params.mode === "web_grounding" && questionCount > 100)
47
+ throw new ClassifierError("input", "Perplexity web grounding accepts at most 100 questions.");
48
+ const openRouter = route.api === "openrouter-decisions" ? openRouterDecisionCapabilities(route.model) : undefined;
31
49
  const imageCount = (params.images?.length ?? 0) + memoryImages.length;
32
50
  if (imageCount && !route.images)
33
51
  throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
34
52
  if (hasBox(params.questions) && (!route.box || !imageCount))
35
53
  throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
54
+ if (params.mode === "web_grounding" && route.api !== "perplexity-decisions")
55
+ throw new ClassifierError("capability", "Web grounding is supported only by Perplexity Decisions routes.");
56
+ if (route.api === "cloudflare-clairic")
57
+ throw new ClassifierError("capability", "Clairic extraction uses classify_extract with fields, not classify questions.");
58
+ if (params.imageDetail !== undefined && !["openai-decisions", "openrouter-decisions"].includes(route.api))
59
+ throw new ClassifierError("capability", "imageDetail is supported only by OpenAI-compatible and OpenRouter Decisions routes.");
60
+ if (params.promptCache !== undefined && route.api !== "openai-decisions")
61
+ throw new ClassifierError("capability", "promptCache is supported only by the OpenAI Decisions wire contract.");
62
+ if (params.conversation !== undefined && route.api !== "openai-decisions")
63
+ throw new ClassifierError("capability", "conversation input is supported only by the OpenAI Decisions wire contract.");
64
+ const liquidQuestions = ["bool", "choice", "score", "text", "number", "date", "spans", "boxes", "estimate", "multi_choice", "box"];
65
+ const decisionQuestions = ["bool", "choice", "score", "box", "locate"];
66
+ const coreQuestions = ["bool", "choice", "score"];
67
+ const sarvamQuestions = ["bool", "choice", "score"];
68
+ const openRouterQuestions = route.box
69
+ ? ["bool", "choice", "score", "box"]
70
+ : ["bool", "choice", "score"];
71
+ const allowed =
72
+ route.api === "liquid-system-one"
73
+ ? liquidQuestions
74
+ : route.api === "sarvam-system-one"
75
+ ? sarvamQuestions
76
+ : route.api === "inception-decisions"
77
+ ? [...coreQuestions, "extract"]
78
+ : ["gemini-decisions", "parallel-decisions", "local-system-one"].includes(route.api)
79
+ ? coreQuestions
80
+ : openRouter
81
+ ? openRouterQuestions
82
+ : decisionQuestions;
83
+ const unsupported = Object.values(params.questions).find((question) => !allowed.includes(question.type));
84
+ if (unsupported)
85
+ throw new ClassifierError("capability", "The selected route does not support " + unsupported.type + " questions.");
86
+ const extracts = Object.values(params.questions).filter((question) => question.type === "extract");
87
+ if (extracts.length > 0 && route.api !== "inception-decisions")
88
+ throw new ClassifierError("capability", "extract questions are supported only by Inception Mercury Decide.");
89
+ if (extracts.length > 0) {
90
+ if (imageCount > 0 || (params.media?.length ?? 0) > 0)
91
+ throw new ClassifierError("input", "Inception extract questions cannot be combined with images or media.");
92
+ if (typeof params.state !== "string") {
93
+ if (!isRecord(params.state) && !Array.isArray(params.state))
94
+ throw new ClassifierError("input", "Inception extract questions require text or JSON state.");
95
+ for (const question of extracts) {
96
+ if (typeof question.source !== "string" || !question.source.trim())
97
+ throw new ClassifierError("input", "Inception extract questions require source when state is JSON.");
98
+ const value = (params.state as Record<string, unknown>)[question.source];
99
+ if (typeof value !== "string")
100
+ throw new ClassifierError("input", "Inception extract source must name a string field in the JSON state.");
101
+ }
102
+ }
103
+ }
104
+ const locate = Object.values(params.questions).some((question) => question.type === "locate");
105
+ if (locate) {
106
+ const v13 = ["pplx-decider-v1.3", "pplx-decider-flash-v1.3", "pplx-decider-latest", "pplx-decider-flash-latest"];
107
+ if (route.api !== "perplexity-decisions" || !v13.includes(route.model))
108
+ throw new ClassifierError("capability", "locate requires a Perplexity v1.3 model or its latest alias.");
109
+ if (imageCount > 0)
110
+ throw new ClassifierError("input", "locate requires a string state without images.");
111
+ if (typeof params.state !== "string")
112
+ throw new ClassifierError("input", "locate requires a string state. Offsets are defined only for text.");
113
+ }
36
114
  const clef = route.api === "cloudflare-system-one" && route.images;
37
- const maxImages = clef ? 4 : route.api === "perplexity-decisions" ? 8 : 5;
38
- if (imageCount > maxImages)
39
- throw new ClassifierError("input", "The selected route accepts at most " + maxImages + " images in this package.");
40
- if (imageReferences(params.state).length && !["system-one", "openai-decisions", "perplexity-decisions"].includes(route.api))
41
- throw new ClassifierError("capability", "This route does not support explicit image references in state; use shared image paths instead.");
115
+ const liquid = route.api === "liquid-system-one";
116
+ if (imageCount > route.limits.maxImages)
117
+ throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxImages + " images in this package.");
118
+ const flexibleReferences = openRouter?.flexibleImagePlacement === true;
119
+ if (imageReferences(params.state).length && !flexibleReferences && !["system-one", "openai-decisions", "perplexity-decisions", "microsoft-system-one", "gemini-decisions", "inception-decisions", "openrouter-decisions"].includes(route.api))
120
+ throw new ClassifierError("capability", "This route does not support explicit image references in state; use shared image parts instead.");
121
+ if (
122
+ route.api === "openrouter-decisions" &&
123
+ !flexibleReferences &&
124
+ imageReferences(params.state).length > 0 &&
125
+ !topLevelImagePartsOnly(params.state)
126
+ )
127
+ throw new ClassifierError("capability", "OpenRouter adapters other than TypeSafe and Microsoft read images only as top-level state parts. Put each {$image:id} directly in a state array, not inside an object or another array.");
42
128
  for (const question of Object.values(params.questions)) {
43
- if (imageReferences(question.instructions).length && !["system-one", "openai-decisions"].includes(route.api))
44
- throw new ClassifierError("capability", "Image references in question instructions require Jev or OpenAI Decisions.");
45
- if ("criteria" in question && question.criteria && Object.values(question.criteria).some((entry) => imageReferences(entry).length) && route.api !== "system-one")
46
- throw new ClassifierError("capability", "Image references in criteria require a Jev assets-protocol route.");
129
+ if (imageReferences(question.instructions).length && !flexibleReferences && !["system-one", "openai-decisions", "microsoft-system-one", "inception-decisions"].includes(route.api))
130
+ throw new ClassifierError("capability", "Image references in question instructions require Jev, OpenAI Decisions or a flexible OpenRouter Decisions endpoint.");
131
+ if (question.type !== "extract" && "criteria" in question && question.criteria && Object.values(question.criteria).some((entry) => imageReferences(entry).length) && route.api !== "system-one" && route.api !== "microsoft-system-one" && !flexibleReferences)
132
+ throw new ClassifierError("capability", "Image references in criteria require a Jev assets-protocol route or a flexible OpenRouter Decisions endpoint.");
47
133
  }
48
134
  // Reject unsupported URL placement before opening any local files.
49
135
  for (const source of params.images ?? []) {
50
136
  if (typeof source !== "string" && "url" in source) {
51
- if (route.api !== "openai-decisions")
52
- throw new ClassifierError("capability", "Hosted image URLs are supported only by OpenAI Decisions routes. No URL was fetched.");
137
+ if (route.api !== "openai-decisions" && openRouter?.remoteImageUrls !== true)
138
+ throw new ClassifierError("capability", "Hosted image URLs are supported only by OpenAI Decisions and documented OpenRouter Decisions endpoints. No URL was fetched.");
53
139
  try {
54
140
  const url = new URL(source.url);
55
141
  if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.hash)
@@ -84,6 +170,8 @@ export async function prepareInput(
84
170
  totalBytes += Buffer.byteLength(image.data, "base64");
85
171
  if (totalBytes > (clef ? 8 : 10) * 1024 * 1024)
86
172
  throw new ClassifierError("input", "Images exceed the selected route's total upload byte limit.");
173
+ if (route.api === "microsoft-system-one" && image.mimeType === "image/webp")
174
+ throw new ClassifierError("input", "Microsoft Foundry Decision-1.1 image assets accept PNG and JPEG only.");
87
175
  if (route.api === "system-one") {
88
176
  if (image.mimeType === "image/webp")
89
177
  throw new ClassifierError("input", "Jev image assets accept PNG and JPEG only.");
@@ -91,11 +179,34 @@ export async function prepareInput(
91
179
  if (image.width < 280 || image.width > 1568 || image.height < 280 || image.height > 1568 || pixels < 78_400 || pixels > 2_458_624)
92
180
  throw new ClassifierError("input", "Resize or pad Jev images before sending: each side must be 280–1568 pixels and total area 78400–2458624 pixels. Images are not silently resized.");
93
181
  }
182
+ if (openRouter?.flexibleImagePlacement) {
183
+ if (image.mimeType === "image/webp")
184
+ throw new ClassifierError("input", "OpenRouter TypeSafe and Microsoft Decisions endpoints accept PNG and JPEG only.");
185
+ const minimum = /typesafe\/jev/.test(route.model) ? 256 : 280;
186
+ if (image.width < minimum || image.width > 1568 || image.height < minimum || image.height > 1568 ||
187
+ image.width * image.height < minimum * minimum || image.width * image.height > 2_458_624)
188
+ throw new ClassifierError("input", "Resize or pad this OpenRouter Decisions image: each side must be " + minimum + "–1568 pixels and the area must stay within the endpoint's documented range.");
189
+ }
190
+ if (liquid) {
191
+ const patches = Math.ceil(image.width / 32) * Math.ceil(image.height / 32);
192
+ if (patches > 10_000 || image.width > image.height * 100 || image.height > image.width * 100)
193
+ throw new ClassifierError("input", "Liquid images must stay within 10000 32×32 patches and a 100:1 aspect ratio. Images are not silently resized.");
194
+ }
94
195
  if (route.api === "perplexity-decisions" && Math.ceil(image.width / 32) * Math.ceil(image.height / 32) > 2048)
95
196
  throw new ClassifierError("input", "Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.");
96
197
  images.push(id === undefined ? image : { ...image, id });
97
198
  }
98
- return { state: params.state, questions: params.questions, images };
199
+ const media = await prepareMedia(params.media ?? [], route, cwd, signal);
200
+ return {
201
+ state: params.state,
202
+ questions: params.questions,
203
+ images,
204
+ media,
205
+ ...(params.mode !== undefined ? { mode: params.mode } : {}),
206
+ ...(params.conversation !== undefined ? { conversation: params.conversation } : {}),
207
+ ...(params.imageDetail !== undefined ? { imageDetail: params.imageDetail } : {}),
208
+ ...(params.promptCache !== undefined ? { promptCache: params.promptCache } : {}),
209
+ };
99
210
  }
100
211
 
101
212
  /** Bounded, fully decoded local image; shared by uploads and local box rendering. */
@@ -215,3 +326,333 @@ export async function verifyOpenedPath(fd: number, root: string, signal?: AbortS
215
326
  const inside = relative(root, openedPath);
216
327
  if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside)) throw new Error();
217
328
  }
329
+
330
+ /** Detect container types by magic bytes; duration and codec compatibility remain provider-owned. */
331
+ function mediaMime(bytes: Buffer, type: "audio" | "video"): string {
332
+ const ascii = (start: number, value: string) =>
333
+ bytes.subarray(start, start + value.length).toString("ascii") === value;
334
+ if (type === "audio") {
335
+ if (ascii(0, "RIFF") && ascii(8, "WAVE")) return "audio/wav";
336
+ if (ascii(0, "ID3") || (bytes[0] === 0xff && (bytes[1]! & 0xe0) === 0xe0)) return "audio/mpeg";
337
+ if (ascii(0, "fLaC")) return "audio/flac";
338
+ if (ascii(0, "OggS")) return "audio/ogg";
339
+ throw new ClassifierError("input", "Audio must be WAV, MP3, FLAC or OGG with matching container bytes.");
340
+ }
341
+ if (ascii(4, "ftyp")) return "video/mp4";
342
+ if (bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3)
343
+ return "video/webm";
344
+ throw new ClassifierError("input", "Video must be MP4 or WebM with matching container bytes.");
345
+ }
346
+
347
+ async function loadMediaFile(
348
+ path: string,
349
+ cwd: string,
350
+ signal: AbortSignal | undefined,
351
+ maxBytes: number,
352
+ ): Promise<Buffer> {
353
+ cancelled(signal);
354
+ try {
355
+ if (/^[a-z]+:/i.test(path)) throw new Error();
356
+ const root = await realpath(cwd);
357
+ const target = resolve(root, path);
358
+ const inside = relative(root, target);
359
+ if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside)) throw new Error();
360
+ let current = root;
361
+ for (const part of inside.split(sep)) {
362
+ cancelled(signal);
363
+ current = resolve(current, part);
364
+ const entry = await lstat(current);
365
+ if (entry.isSymbolicLink() || (current === target ? !entry.isFile() : !entry.isDirectory())) throw new Error();
366
+ }
367
+ if (await realpath(target) !== target) throw new Error();
368
+ const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
369
+ try {
370
+ await verifyOpenedPath(file.fd, root, signal);
371
+ const stat = await file.stat();
372
+ if (!stat.isFile() || stat.size < 1 || stat.size > maxBytes) throw new Error();
373
+ const buffer = Buffer.alloc(maxBytes + 1);
374
+ let offset = 0;
375
+ while (offset < buffer.length) {
376
+ cancelled(signal);
377
+ const read = await file.read(buffer, offset, buffer.length - offset, null);
378
+ if (!read.bytesRead) break;
379
+ offset += read.bytesRead;
380
+ }
381
+ if (offset > maxBytes) throw new Error();
382
+ return buffer.subarray(0, offset);
383
+ } finally {
384
+ await file.close();
385
+ }
386
+ } catch (error) {
387
+ cancelled(signal);
388
+ if (error instanceof ClassifierError) throw error;
389
+ throw new ClassifierError("input", "Media must be a regular file inside cwd without symlinks, within the provider's documented byte limit.");
390
+ }
391
+ }
392
+
393
+ async function prepareMedia(
394
+ sources: NonNullable<ClassifyParams["media"]>,
395
+ route: ResolvedModel,
396
+ cwd: string,
397
+ signal?: AbortSignal,
398
+ ): Promise<PreparedMedia[]> {
399
+ const audio = sources.filter((source) => source.type === "audio");
400
+ const video = sources.filter((source) => source.type === "video");
401
+ if (audio.length && !route.audio)
402
+ throw new ClassifierError("capability", "The selected route does not support audio input.");
403
+ if (video.length && !route.video)
404
+ throw new ClassifierError("capability", "The selected route does not support video input.");
405
+ if (audio.length > route.limits.maxAudio)
406
+ throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxAudio + " audio clips.");
407
+ if (video.length > route.limits.maxVideo)
408
+ throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxVideo + " videos.");
409
+ const result: PreparedMedia[] = [];
410
+ for (const source of [...audio, ...video]) {
411
+ const maxBytes = source.type === "video" ? 16 * 1024 * 1024 : route.api === "cloudflare-system-one" ? 8 * 1024 * 1024 : 20 * 1024 * 1024;
412
+ const bytes = await loadMediaFile(source.path, cwd, signal, maxBytes);
413
+ result.push({
414
+ type: source.type,
415
+ mimeType: mediaMime(bytes, source.type),
416
+ data: bytes.toString("base64"),
417
+ });
418
+ }
419
+ return result;
420
+ }
421
+
422
+ export type PreparedExtractionImage = PreparedLocalImage & { rotation?: 0 | 90 | 180 | 270 };
423
+
424
+ export type PreparedExtractionInput = {
425
+ state: string | Record<string, unknown> | unknown[];
426
+ fields: NonNullable<ExtractParams["fields"]>;
427
+ images: PreparedExtractionImage[];
428
+ documents: { mimeType: "application/pdf"; data: string }[];
429
+ referenceDate?: string;
430
+ options?: ExtractParams["options"];
431
+ };
432
+
433
+ const EXTRACTION_TYPES = new Set([
434
+ "text", "number", "compute", "date", "time", "datetime", "duration",
435
+ "boolean", "enum", "object", "list", "estimate", "forecast",
436
+ ]);
437
+
438
+ const OPENROUTER_EXTRACTION_FIELD_KEYS: Record<string, { allowed: string[]; required: string[] }> = {
439
+ text: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
440
+ number: { allowed: ["type", "decimals", "instructions", "integer", "null_threshold", "unit"], required: ["type"] },
441
+ date: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
442
+ time: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
443
+ datetime: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
444
+ duration: { allowed: ["type", "decimals", "instructions", "integer", "null_threshold", "unit"], required: ["type"] },
445
+ list: { allowed: ["type", "decimals", "instructions", "integer", "items", "null_threshold", "unit"], required: ["type", "items"] },
446
+ estimate: { allowed: ["type", "instructions", "max", "min", "scale", "step", "unit"], required: ["type", "min", "max"] },
447
+ forecast: { allowed: ["type", "horizon", "instructions", "interval", "max", "min", "scale", "step", "unit"], required: ["type", "min", "max", "horizon", "interval"] },
448
+ };
449
+
450
+ function validateOpenRouterExtractionFields(
451
+ fields: NonNullable<ExtractParams["fields"]>,
452
+ model: string,
453
+ ): void {
454
+ const isClairic = model === "cloudflare/clairic";
455
+ const isLiquid = /^liquid\/d1\.2/.test(model);
456
+ const isScaleDown = model === "scaledown/extract";
457
+ const textItemsOnly = isScaleDown || isLiquid || model.startsWith("inception/") || model.startsWith("perplexity/");
458
+ const noNullThreshold = isScaleDown || model.startsWith("perplexity/") || model.startsWith("inference-net/");
459
+ for (const [name, field] of Object.entries(fields)) {
460
+ if (!isRecord(field) || typeof field.type !== "string")
461
+ throw new ClassifierError("input", "Each extraction field needs a type.");
462
+ const schema = OPENROUTER_EXTRACTION_FIELD_KEYS[field.type];
463
+ if (!schema)
464
+ throw new ClassifierError("input", "OpenRouter extraction does not support field type " + field.type + ".");
465
+ const keys = Object.keys(field);
466
+ const unknown = keys.filter((key) => !schema.allowed.includes(key));
467
+ if (unknown.length > 0)
468
+ throw new ClassifierError("input", "Field " + name + " uses keys OpenRouter does not accept: " + unknown.join(", ") + ".");
469
+ const missing = schema.required.filter((key) => !Object.hasOwn(field, key));
470
+ if (missing.length > 0)
471
+ throw new ClassifierError("input", "Field " + name + " is missing required OpenRouter keys: " + missing.join(", ") + ".");
472
+ if (field.null_threshold !== undefined) {
473
+ const threshold = field.null_threshold;
474
+ if (typeof threshold !== "number" || !Number.isFinite(threshold) || threshold < 0 || threshold > 1)
475
+ throw new ClassifierError("input", "Field " + name + " has an invalid null_threshold.");
476
+ if (noNullThreshold || (isClairic && ["list", "estimate", "forecast"].includes(field.type)) || (isLiquid && field.type === "list"))
477
+ throw new ClassifierError("capability", "The selected extraction model does not accept null_threshold on this field.");
478
+ if (isClairic && threshold === 0)
479
+ throw new ClassifierError("input", "Clairic requires null_threshold above zero.");
480
+ if (isLiquid && ["text", "number", "date"].includes(field.type) && threshold <= 0)
481
+ throw new ClassifierError("input", "Liquid extraction requires null_threshold above zero on text, number and date fields.");
482
+ } else if (isLiquid && ["text", "number", "date"].includes(field.type)) {
483
+ throw new ClassifierError("input", "Liquid extraction requires null_threshold above zero on text, number and date fields.");
484
+ }
485
+ if (field.unit !== undefined && !isClairic && !(isLiquid && field.type === "estimate"))
486
+ throw new ClassifierError("capability", "The selected extraction model does not accept unit on this field.");
487
+ if (field.type === "list") {
488
+ if (typeof field.items !== "string" || !["text", "number", "date"].includes(field.items))
489
+ throw new ClassifierError("input", "OpenRouter list fields require items of text, number or date.");
490
+ if (textItemsOnly && field.items !== "text")
491
+ throw new ClassifierError("capability", "The selected extraction model supports only text list items.");
492
+ if (isLiquid && (field.unit !== undefined || field.integer !== undefined || field.decimals !== undefined))
493
+ throw new ClassifierError("capability", "Liquid list fields accept only items: text.");
494
+ }
495
+ if (field.type === "estimate" && isLiquid) {
496
+ if ((typeof field.min !== "number" || !Number.isFinite(field.min)) ||
497
+ (typeof field.max !== "number" || !Number.isFinite(field.max)) ||
498
+ (field.step !== undefined && typeof field.step !== "number"))
499
+ throw new ClassifierError("input", "Liquid estimate fields require numeric min, max and optional numeric step.");
500
+ if (field.scale !== undefined && field.scale !== "linear")
501
+ throw new ClassifierError("capability", "Liquid extraction accepts only linear estimates.");
502
+ }
503
+ }
504
+ }
505
+
506
+ function validateExtractionFields(
507
+ value: unknown,
508
+ allowedTypes: ReadonlySet<string> = EXTRACTION_TYPES,
509
+ maxFields = 128,
510
+ ): NonNullable<ExtractParams["fields"]> {
511
+ if (!isRecord(value) || Object.keys(value).length === 0 || Object.keys(value).length > maxFields)
512
+ throw new ClassifierError("input", "fields must be a non-empty map of at most " + maxFields + " named field specifications.");
513
+ for (const [name, field] of Object.entries(value)) {
514
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/.test(name) || !isRecord(field) || typeof field.type !== "string" || !allowedTypes.has(field.type))
515
+ throw new ClassifierError("input", "Each field needs a provider field name and a documented type for the selected extraction model.");
516
+ if (field.properties !== undefined) validateExtractionFields(field.properties, allowedTypes, maxFields);
517
+ if (field.items !== undefined && isRecord(field.items) && field.items.properties !== undefined)
518
+ validateExtractionFields(field.items.properties, allowedTypes, maxFields);
519
+ }
520
+ return value as NonNullable<ExtractParams["fields"]>;
521
+ }
522
+
523
+ async function loadDocumentFile(
524
+ path: string,
525
+ cwd: string,
526
+ signal: AbortSignal | undefined,
527
+ ): Promise<Buffer> {
528
+ cancelled(signal);
529
+ try {
530
+ if (/^[a-z]+:/i.test(path)) throw new Error();
531
+ const root = await realpath(cwd);
532
+ const target = resolve(root, path);
533
+ const inside = relative(root, target);
534
+ if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside)) throw new Error();
535
+ let current = root;
536
+ for (const part of inside.split(sep)) {
537
+ cancelled(signal);
538
+ current = resolve(current, part);
539
+ const entry = await lstat(current);
540
+ if (entry.isSymbolicLink() || (current === target ? !entry.isFile() : !entry.isDirectory())) throw new Error();
541
+ }
542
+ if (await realpath(target) !== target) throw new Error();
543
+ const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
544
+ try {
545
+ await verifyOpenedPath(file.fd, root, signal);
546
+ const stat = await file.stat();
547
+ if (!stat.isFile() || stat.size < 5 || stat.size > 4 * 1024 * 1024) throw new Error();
548
+ const buffer = Buffer.alloc(4 * 1024 * 1024 + 1);
549
+ let offset = 0;
550
+ while (offset < buffer.length) {
551
+ cancelled(signal);
552
+ const read = await file.read(buffer, offset, buffer.length - offset, null);
553
+ if (!read.bytesRead) break;
554
+ offset += read.bytesRead;
555
+ }
556
+ if (offset > 4 * 1024 * 1024 || buffer.subarray(0, 5).toString("ascii") !== "%PDF-") throw new Error();
557
+ return buffer.subarray(0, offset);
558
+ } finally {
559
+ await file.close();
560
+ }
561
+ } catch (error) {
562
+ cancelled(signal);
563
+ if (error instanceof ClassifierError) throw error;
564
+ throw new ClassifierError("input", "Documents must be unencrypted PDF regular files inside cwd without symlinks, within 4 MiB.");
565
+ }
566
+ }
567
+
568
+ export async function prepareExtractionInput(
569
+ params: ExtractParams,
570
+ route: ResolvedModel,
571
+ cwd: string,
572
+ signal?: AbortSignal,
573
+ ): Promise<PreparedExtractionInput> {
574
+ if (!["cloudflare-clairic", "openrouter-extractions", "litellm-extraction"].includes(route.api))
575
+ throw new ClassifierError("capability", "Extraction requires a clairic-api, openrouter-extractions-api or litellm-extraction-api route.");
576
+ if (params.state !== undefined &&
577
+ !(typeof params.state === "string" || Array.isArray(params.state) || isRecord(params.state)))
578
+ throw new ClassifierError("input", "state must be text, a JSON object or an array.");
579
+ const extractionCaps = route.api === "openrouter-extractions" ? openRouterExtractionCapabilities(route.model) : undefined;
580
+ const fields = validateExtractionFields(
581
+ params.fields,
582
+ extractionCaps ? new Set(extractionCaps.fieldTypes) : EXTRACTION_TYPES,
583
+ extractionCaps?.maxFields,
584
+ );
585
+ if (route.api === "openrouter-extractions")
586
+ validateOpenRouterExtractionFields(fields, route.model);
587
+ if (extractionCaps?.referenceDate === false && params.referenceDate !== undefined)
588
+ throw new ClassifierError("capability", "The selected extraction model does not accept referenceDate.");
589
+ if (params.referenceDate !== undefined &&
590
+ (typeof params.referenceDate !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(params.referenceDate)))
591
+ throw new ClassifierError("input", "referenceDate must use YYYY-MM-DD.");
592
+ if (params.options !== undefined) {
593
+ if (!isRecord(params.options) ||
594
+ Object.keys(params.options).some((key) => !["includeQuantiles", "returnStateText"].includes(key)) ||
595
+ Object.values(params.options).some((value) => typeof value !== "boolean"))
596
+ throw new ClassifierError("input", "options may only set includeQuantiles and returnStateText to booleans.");
597
+ }
598
+ if (params.images !== undefined && (!Array.isArray(params.images) || params.images.some((image) =>
599
+ typeof image === "string"
600
+ ? !image.trim() || image.length > 4096
601
+ : !isRecord(image) || Object.keys(image).some((key) => key !== "path" && key !== "rotation") ||
602
+ typeof image.path !== "string" || !image.path.trim() || image.path.length > 4096 ||
603
+ (image.rotation !== undefined && ![0, 90, 180, 270].includes(image.rotation as number)))))
604
+ throw new ClassifierError("input", "images must be local path strings or {path, rotation} objects with rotation 0, 90, 180 or 270.");
605
+ if (route.api !== "cloudflare-clairic" && (params.images ?? []).some((image) => typeof image !== "string" && image.rotation !== undefined))
606
+ throw new ClassifierError("capability", "Image rotation is documented only for direct Cloudflare Clairic.");
607
+ if (params.documents !== undefined && (!Array.isArray(params.documents) || params.documents.some((document) => typeof document !== "string" || !document.trim() || document.length > 4096)))
608
+ throw new ClassifierError("input", "documents must be local PDF path strings inside cwd.");
609
+ const maxDocuments = route.api === "cloudflare-clairic"
610
+ ? 4
611
+ : route.api === "openrouter-extractions"
612
+ ? extractionCaps?.maxDocuments ?? 0
613
+ : 0;
614
+ if ((params.documents?.length ?? 0) > maxDocuments)
615
+ throw new ClassifierError("capability", "The selected extraction route accepts at most " + maxDocuments + " PDF documents.");
616
+ const isScaleDown = route.api === "openrouter-extractions" && route.model === "scaledown/extract";
617
+ if (isScaleDown && (params.images?.length ?? 0) + (params.documents?.length ?? 0) > 0 && params.state !== undefined && params.state !== "")
618
+ throw new ClassifierError("input", "ScaleDown Extract reads either text state or one asset, not both. Omit state when sending a PDF or image.");
619
+ const images = await Promise.all((params.images ?? []).map(async (image) => {
620
+ const spec = typeof image === "string" ? { path: image } : image;
621
+ const loaded = await loadLocalImage(spec.path, cwd, signal, 4 * 1024 * 1024);
622
+ return spec.rotation === undefined ? loaded : { ...loaded, rotation: spec.rotation as 0 | 90 | 180 | 270 };
623
+ }));
624
+ const documents = await Promise.all((params.documents ?? []).map(async (document) => ({
625
+ mimeType: "application/pdf" as const,
626
+ data: (await loadDocumentFile(document, cwd, signal)).toString("base64"),
627
+ })));
628
+ if (route.api === "openrouter-extractions" && /^liquid\/d1\.2/.test(route.model) && images.length > 0 &&
629
+ Object.values(fields).some((field) => isRecord(field) && field.type !== "estimate"))
630
+ throw new ClassifierError("capability", "OpenRouter Liquid extraction models read images only for estimate fields.");
631
+ if (isScaleDown && images.some((image) => image.mimeType === "image/webp"))
632
+ throw new ClassifierError("capability", "ScaleDown Extract does not read WebP images.");
633
+ if (images.length > route.limits.maxImages)
634
+ throw new ClassifierError("input", "The selected extraction model accepts at most " + route.limits.maxImages + " images.");
635
+ const maxAssets = route.api === "cloudflare-clairic"
636
+ ? 4
637
+ : extractionCaps?.maxAssets ?? route.limits.maxImages;
638
+ if (images.length + documents.length > maxAssets)
639
+ throw new ClassifierError("input", "The selected extraction model accepts at most " + maxAssets + " media assets in total.");
640
+ if (route.api === "cloudflare-clairic" && images.length + documents.length > 4)
641
+ throw new ClassifierError("input", "Direct Clairic accepts at most four rendered images and PDF pages combined.");
642
+ let bytes = 0;
643
+ for (const media of [...images.map((image) => Buffer.from(image.data, "base64")), ...documents.map((document) => Buffer.from(document.data, "base64"))]) {
644
+ bytes += media.byteLength;
645
+ if (bytes > 8 * 1024 * 1024)
646
+ throw new ClassifierError("input", "Extraction media exceeds the provider's 8 MiB combined decoded limit.");
647
+ }
648
+ if ((params.state === undefined || params.state === "") && images.length === 0 && documents.length === 0)
649
+ throw new ClassifierError("input", "Extraction requires a non-empty state or media input.");
650
+ return {
651
+ state: params.state ?? "",
652
+ fields,
653
+ images,
654
+ documents,
655
+ ...(params.referenceDate !== undefined ? { referenceDate: params.referenceDate } : {}),
656
+ ...(params.options !== undefined ? { options: params.options } : {}),
657
+ };
658
+ }
package/src/mcp-cli.ts ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ // pi-classifier-mcp: serves the classifier tools over MCP stdio. stdout carries
3
+ // only JSON-RPC, so every diagnostic goes to stderr.
4
+
5
+ import { createRequire } from 'node:module';
6
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
+ import { createClassifierMcpServer } from './mcp-server.js';
8
+
9
+ const require = createRequire(import.meta.url);
10
+ const manifest: unknown = require('../package.json');
11
+ const version =
12
+ typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
13
+ ? manifest.version
14
+ : '0.0.0';
15
+
16
+ // Keep stray dependency output off the JSON-RPC stream.
17
+ console.log = console.info = console.debug = console.error;
18
+
19
+ const server = createClassifierMcpServer({ cwd: process.cwd(), info: { name: 'pi-classifier', version } });
20
+ const transport = new StdioServerTransport();
21
+
22
+ let closing = false;
23
+ async function shutdown(code: number): Promise<void> {
24
+ if (closing) return;
25
+ closing = true;
26
+ try {
27
+ await server.close();
28
+ } catch (error) {
29
+ console.error('pi-classifier-mcp: error during shutdown:', error);
30
+ }
31
+ process.exit(code);
32
+ }
33
+
34
+ process.stdin.once('end', () => void shutdown(0));
35
+ process.stdin.once('close', () => void shutdown(0));
36
+ process.once('SIGINT', () => void shutdown(0));
37
+ process.once('SIGTERM', () => void shutdown(0));
38
+
39
+ try {
40
+ await server.connect(transport);
41
+ } catch (error) {
42
+ console.error('pi-classifier-mcp: failed to start:', error);
43
+ process.exit(1);
44
+ }