@abhishek944/pi-classifier 0.4.0 → 0.5.0

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 +32 -5
  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/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { classify, compareClassifiers } from "./classify.js";
2
+ export { extract } from "./extract.js";
2
3
  export { runComputerUse } from "./computer-use.js";
3
4
  export { classifyTree } from "./tree.js";
4
5
  export { renderClassifierBox } from "./box.js";
package/dist/inputs.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ClassifyParams, type PreparedLocalImage, type PreparedInput, type ResolvedModel } from "./types.js";
1
+ import { type ClassifyParams, type ExtractParams, type PreparedLocalImage, type PreparedInput, type ResolvedModel } from "./types.js";
2
2
  /** Programmatic image ingress. Never accepted as model-facing tool arguments. */
3
3
  export interface MemoryImage {
4
4
  bytes: Uint8Array;
@@ -9,3 +9,18 @@ export declare function prepareInput(params: ClassifyParams, route: ResolvedMode
9
9
  export declare function loadLocalImage(path: string, cwd: string, signal?: AbortSignal, maxBytes?: number): Promise<PreparedLocalImage>;
10
10
  /** Verify containment of the opened descriptor, not a raceable pre-open path. */
11
11
  export declare function verifyOpenedPath(fd: number, root: string, signal?: AbortSignal): Promise<void>;
12
+ export type PreparedExtractionImage = PreparedLocalImage & {
13
+ rotation?: 0 | 90 | 180 | 270;
14
+ };
15
+ export type PreparedExtractionInput = {
16
+ state: string | Record<string, unknown> | unknown[];
17
+ fields: NonNullable<ExtractParams["fields"]>;
18
+ images: PreparedExtractionImage[];
19
+ documents: {
20
+ mimeType: "application/pdf";
21
+ data: string;
22
+ }[];
23
+ referenceDate?: string;
24
+ options?: ExtractParams["options"];
25
+ };
26
+ export declare function prepareExtractionInput(params: ExtractParams, route: ResolvedModel, cwd: string, signal?: AbortSignal): Promise<PreparedExtractionInput>;
package/dist/inputs.js CHANGED
@@ -4,32 +4,109 @@ import { lstat, open, realpath } from "node:fs/promises";
4
4
  import { isAbsolute, relative, resolve, sep } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import sharp from "sharp";
7
- import { ClassifierError, } from "./types.js";
7
+ import { ClassifierError, isRecord, } from "./types.js";
8
8
  import { hasBox } from "./validation.js";
9
- import { imageReferences } from "./image-content.js";
9
+ import { imageReferences, isImageReference } from "./image-content.js";
10
+ import { openRouterDecisionCapabilities, openRouterExtractionCapabilities } from "./config.js";
11
+ function topLevelImagePartsOnly(value) {
12
+ if (isImageReference(value))
13
+ return true;
14
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string" || isImageReference(entry));
15
+ }
10
16
  export async function prepareInput(params, route, cwd, signal, memoryImages = []) {
17
+ const questionCount = Object.keys(params.questions).length;
18
+ if (questionCount > route.limits.maxQuestions)
19
+ throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxQuestions + " questions in this package.");
20
+ if (route.api === "perplexity-decisions" && params.mode === "web_grounding" && questionCount > 100)
21
+ throw new ClassifierError("input", "Perplexity web grounding accepts at most 100 questions.");
22
+ const openRouter = route.api === "openrouter-decisions" ? openRouterDecisionCapabilities(route.model) : undefined;
11
23
  const imageCount = (params.images?.length ?? 0) + memoryImages.length;
12
24
  if (imageCount && !route.images)
13
25
  throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
14
26
  if (hasBox(params.questions) && (!route.box || !imageCount))
15
27
  throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
28
+ if (params.mode === "web_grounding" && route.api !== "perplexity-decisions")
29
+ throw new ClassifierError("capability", "Web grounding is supported only by Perplexity Decisions routes.");
30
+ if (route.api === "cloudflare-clairic")
31
+ throw new ClassifierError("capability", "Clairic extraction uses classify_extract with fields, not classify questions.");
32
+ if (params.imageDetail !== undefined && !["openai-decisions", "openrouter-decisions"].includes(route.api))
33
+ throw new ClassifierError("capability", "imageDetail is supported only by OpenAI-compatible and OpenRouter Decisions routes.");
34
+ if (params.promptCache !== undefined && route.api !== "openai-decisions")
35
+ throw new ClassifierError("capability", "promptCache is supported only by the OpenAI Decisions wire contract.");
36
+ if (params.conversation !== undefined && route.api !== "openai-decisions")
37
+ throw new ClassifierError("capability", "conversation input is supported only by the OpenAI Decisions wire contract.");
38
+ const liquidQuestions = ["bool", "choice", "score", "text", "number", "date", "spans", "boxes", "estimate", "multi_choice", "box"];
39
+ const decisionQuestions = ["bool", "choice", "score", "box", "locate"];
40
+ const coreQuestions = ["bool", "choice", "score"];
41
+ const sarvamQuestions = ["bool", "choice", "score"];
42
+ const openRouterQuestions = route.box
43
+ ? ["bool", "choice", "score", "box"]
44
+ : ["bool", "choice", "score"];
45
+ const allowed = route.api === "liquid-system-one"
46
+ ? liquidQuestions
47
+ : route.api === "sarvam-system-one"
48
+ ? sarvamQuestions
49
+ : route.api === "inception-decisions"
50
+ ? [...coreQuestions, "extract"]
51
+ : ["gemini-decisions", "parallel-decisions", "local-system-one"].includes(route.api)
52
+ ? coreQuestions
53
+ : openRouter
54
+ ? openRouterQuestions
55
+ : decisionQuestions;
56
+ const unsupported = Object.values(params.questions).find((question) => !allowed.includes(question.type));
57
+ if (unsupported)
58
+ throw new ClassifierError("capability", "The selected route does not support " + unsupported.type + " questions.");
59
+ const extracts = Object.values(params.questions).filter((question) => question.type === "extract");
60
+ if (extracts.length > 0 && route.api !== "inception-decisions")
61
+ throw new ClassifierError("capability", "extract questions are supported only by Inception Mercury Decide.");
62
+ if (extracts.length > 0) {
63
+ if (imageCount > 0 || (params.media?.length ?? 0) > 0)
64
+ throw new ClassifierError("input", "Inception extract questions cannot be combined with images or media.");
65
+ if (typeof params.state !== "string") {
66
+ if (!isRecord(params.state) && !Array.isArray(params.state))
67
+ throw new ClassifierError("input", "Inception extract questions require text or JSON state.");
68
+ for (const question of extracts) {
69
+ if (typeof question.source !== "string" || !question.source.trim())
70
+ throw new ClassifierError("input", "Inception extract questions require source when state is JSON.");
71
+ const value = params.state[question.source];
72
+ if (typeof value !== "string")
73
+ throw new ClassifierError("input", "Inception extract source must name a string field in the JSON state.");
74
+ }
75
+ }
76
+ }
77
+ const locate = Object.values(params.questions).some((question) => question.type === "locate");
78
+ if (locate) {
79
+ const v13 = ["pplx-decider-v1.3", "pplx-decider-flash-v1.3", "pplx-decider-latest", "pplx-decider-flash-latest"];
80
+ if (route.api !== "perplexity-decisions" || !v13.includes(route.model))
81
+ throw new ClassifierError("capability", "locate requires a Perplexity v1.3 model or its latest alias.");
82
+ if (imageCount > 0)
83
+ throw new ClassifierError("input", "locate requires a string state without images.");
84
+ if (typeof params.state !== "string")
85
+ throw new ClassifierError("input", "locate requires a string state. Offsets are defined only for text.");
86
+ }
16
87
  const clef = route.api === "cloudflare-system-one" && route.images;
17
- const maxImages = clef ? 4 : route.api === "perplexity-decisions" ? 8 : 5;
18
- if (imageCount > maxImages)
19
- throw new ClassifierError("input", "The selected route accepts at most " + maxImages + " images in this package.");
20
- if (imageReferences(params.state).length && !["system-one", "openai-decisions", "perplexity-decisions"].includes(route.api))
21
- throw new ClassifierError("capability", "This route does not support explicit image references in state; use shared image paths instead.");
88
+ const liquid = route.api === "liquid-system-one";
89
+ if (imageCount > route.limits.maxImages)
90
+ throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxImages + " images in this package.");
91
+ const flexibleReferences = openRouter?.flexibleImagePlacement === true;
92
+ if (imageReferences(params.state).length && !flexibleReferences && !["system-one", "openai-decisions", "perplexity-decisions", "microsoft-system-one", "gemini-decisions", "inception-decisions", "openrouter-decisions"].includes(route.api))
93
+ throw new ClassifierError("capability", "This route does not support explicit image references in state; use shared image parts instead.");
94
+ if (route.api === "openrouter-decisions" &&
95
+ !flexibleReferences &&
96
+ imageReferences(params.state).length > 0 &&
97
+ !topLevelImagePartsOnly(params.state))
98
+ 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.");
22
99
  for (const question of Object.values(params.questions)) {
23
- if (imageReferences(question.instructions).length && !["system-one", "openai-decisions"].includes(route.api))
24
- throw new ClassifierError("capability", "Image references in question instructions require Jev or OpenAI Decisions.");
25
- if ("criteria" in question && question.criteria && Object.values(question.criteria).some((entry) => imageReferences(entry).length) && route.api !== "system-one")
26
- throw new ClassifierError("capability", "Image references in criteria require a Jev assets-protocol route.");
100
+ if (imageReferences(question.instructions).length && !flexibleReferences && !["system-one", "openai-decisions", "microsoft-system-one", "inception-decisions"].includes(route.api))
101
+ throw new ClassifierError("capability", "Image references in question instructions require Jev, OpenAI Decisions or a flexible OpenRouter Decisions endpoint.");
102
+ 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)
103
+ throw new ClassifierError("capability", "Image references in criteria require a Jev assets-protocol route or a flexible OpenRouter Decisions endpoint.");
27
104
  }
28
105
  // Reject unsupported URL placement before opening any local files.
29
106
  for (const source of params.images ?? []) {
30
107
  if (typeof source !== "string" && "url" in source) {
31
- if (route.api !== "openai-decisions")
32
- throw new ClassifierError("capability", "Hosted image URLs are supported only by OpenAI Decisions routes. No URL was fetched.");
108
+ if (route.api !== "openai-decisions" && openRouter?.remoteImageUrls !== true)
109
+ throw new ClassifierError("capability", "Hosted image URLs are supported only by OpenAI Decisions and documented OpenRouter Decisions endpoints. No URL was fetched.");
33
110
  try {
34
111
  const url = new URL(source.url);
35
112
  if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.hash)
@@ -67,6 +144,8 @@ export async function prepareInput(params, route, cwd, signal, memoryImages = []
67
144
  totalBytes += Buffer.byteLength(image.data, "base64");
68
145
  if (totalBytes > (clef ? 8 : 10) * 1024 * 1024)
69
146
  throw new ClassifierError("input", "Images exceed the selected route's total upload byte limit.");
147
+ if (route.api === "microsoft-system-one" && image.mimeType === "image/webp")
148
+ throw new ClassifierError("input", "Microsoft Foundry Decision-1.1 image assets accept PNG and JPEG only.");
70
149
  if (route.api === "system-one") {
71
150
  if (image.mimeType === "image/webp")
72
151
  throw new ClassifierError("input", "Jev image assets accept PNG and JPEG only.");
@@ -74,11 +153,34 @@ export async function prepareInput(params, route, cwd, signal, memoryImages = []
74
153
  if (image.width < 280 || image.width > 1568 || image.height < 280 || image.height > 1568 || pixels < 78_400 || pixels > 2_458_624)
75
154
  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.");
76
155
  }
156
+ if (openRouter?.flexibleImagePlacement) {
157
+ if (image.mimeType === "image/webp")
158
+ throw new ClassifierError("input", "OpenRouter TypeSafe and Microsoft Decisions endpoints accept PNG and JPEG only.");
159
+ const minimum = /typesafe\/jev/.test(route.model) ? 256 : 280;
160
+ if (image.width < minimum || image.width > 1568 || image.height < minimum || image.height > 1568 ||
161
+ image.width * image.height < minimum * minimum || image.width * image.height > 2_458_624)
162
+ 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.");
163
+ }
164
+ if (liquid) {
165
+ const patches = Math.ceil(image.width / 32) * Math.ceil(image.height / 32);
166
+ if (patches > 10_000 || image.width > image.height * 100 || image.height > image.width * 100)
167
+ throw new ClassifierError("input", "Liquid images must stay within 10000 32×32 patches and a 100:1 aspect ratio. Images are not silently resized.");
168
+ }
77
169
  if (route.api === "perplexity-decisions" && Math.ceil(image.width / 32) * Math.ceil(image.height / 32) > 2048)
78
170
  throw new ClassifierError("input", "Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.");
79
171
  images.push(id === undefined ? image : { ...image, id });
80
172
  }
81
- return { state: params.state, questions: params.questions, images };
173
+ const media = await prepareMedia(params.media ?? [], route, cwd, signal);
174
+ return {
175
+ state: params.state,
176
+ questions: params.questions,
177
+ images,
178
+ media,
179
+ ...(params.mode !== undefined ? { mode: params.mode } : {}),
180
+ ...(params.conversation !== undefined ? { conversation: params.conversation } : {}),
181
+ ...(params.imageDetail !== undefined ? { imageDetail: params.imageDetail } : {}),
182
+ ...(params.promptCache !== undefined ? { promptCache: params.promptCache } : {}),
183
+ };
82
184
  }
83
185
  /** Bounded, fully decoded local image; shared by uploads and local box rendering. */
84
186
  export async function loadLocalImage(path, cwd, signal, maxBytes = 5 * 1024 * 1024) {
@@ -206,3 +308,308 @@ export async function verifyOpenedPath(fd, root, signal) {
206
308
  if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
207
309
  throw new Error();
208
310
  }
311
+ /** Detect container types by magic bytes; duration and codec compatibility remain provider-owned. */
312
+ function mediaMime(bytes, type) {
313
+ const ascii = (start, value) => bytes.subarray(start, start + value.length).toString("ascii") === value;
314
+ if (type === "audio") {
315
+ if (ascii(0, "RIFF") && ascii(8, "WAVE"))
316
+ return "audio/wav";
317
+ if (ascii(0, "ID3") || (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0))
318
+ return "audio/mpeg";
319
+ if (ascii(0, "fLaC"))
320
+ return "audio/flac";
321
+ if (ascii(0, "OggS"))
322
+ return "audio/ogg";
323
+ throw new ClassifierError("input", "Audio must be WAV, MP3, FLAC or OGG with matching container bytes.");
324
+ }
325
+ if (ascii(4, "ftyp"))
326
+ return "video/mp4";
327
+ if (bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3)
328
+ return "video/webm";
329
+ throw new ClassifierError("input", "Video must be MP4 or WebM with matching container bytes.");
330
+ }
331
+ async function loadMediaFile(path, cwd, signal, maxBytes) {
332
+ cancelled(signal);
333
+ try {
334
+ if (/^[a-z]+:/i.test(path))
335
+ throw new Error();
336
+ const root = await realpath(cwd);
337
+ const target = resolve(root, path);
338
+ const inside = relative(root, target);
339
+ if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
340
+ throw new Error();
341
+ let current = root;
342
+ for (const part of inside.split(sep)) {
343
+ cancelled(signal);
344
+ current = resolve(current, part);
345
+ const entry = await lstat(current);
346
+ if (entry.isSymbolicLink() || (current === target ? !entry.isFile() : !entry.isDirectory()))
347
+ throw new Error();
348
+ }
349
+ if (await realpath(target) !== target)
350
+ throw new Error();
351
+ const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
352
+ try {
353
+ await verifyOpenedPath(file.fd, root, signal);
354
+ const stat = await file.stat();
355
+ if (!stat.isFile() || stat.size < 1 || stat.size > maxBytes)
356
+ throw new Error();
357
+ const buffer = Buffer.alloc(maxBytes + 1);
358
+ let offset = 0;
359
+ while (offset < buffer.length) {
360
+ cancelled(signal);
361
+ const read = await file.read(buffer, offset, buffer.length - offset, null);
362
+ if (!read.bytesRead)
363
+ break;
364
+ offset += read.bytesRead;
365
+ }
366
+ if (offset > maxBytes)
367
+ throw new Error();
368
+ return buffer.subarray(0, offset);
369
+ }
370
+ finally {
371
+ await file.close();
372
+ }
373
+ }
374
+ catch (error) {
375
+ cancelled(signal);
376
+ if (error instanceof ClassifierError)
377
+ throw error;
378
+ throw new ClassifierError("input", "Media must be a regular file inside cwd without symlinks, within the provider's documented byte limit.");
379
+ }
380
+ }
381
+ async function prepareMedia(sources, route, cwd, signal) {
382
+ const audio = sources.filter((source) => source.type === "audio");
383
+ const video = sources.filter((source) => source.type === "video");
384
+ if (audio.length && !route.audio)
385
+ throw new ClassifierError("capability", "The selected route does not support audio input.");
386
+ if (video.length && !route.video)
387
+ throw new ClassifierError("capability", "The selected route does not support video input.");
388
+ if (audio.length > route.limits.maxAudio)
389
+ throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxAudio + " audio clips.");
390
+ if (video.length > route.limits.maxVideo)
391
+ throw new ClassifierError("input", "The selected route accepts at most " + route.limits.maxVideo + " videos.");
392
+ const result = [];
393
+ for (const source of [...audio, ...video]) {
394
+ const maxBytes = source.type === "video" ? 16 * 1024 * 1024 : route.api === "cloudflare-system-one" ? 8 * 1024 * 1024 : 20 * 1024 * 1024;
395
+ const bytes = await loadMediaFile(source.path, cwd, signal, maxBytes);
396
+ result.push({
397
+ type: source.type,
398
+ mimeType: mediaMime(bytes, source.type),
399
+ data: bytes.toString("base64"),
400
+ });
401
+ }
402
+ return result;
403
+ }
404
+ const EXTRACTION_TYPES = new Set([
405
+ "text", "number", "compute", "date", "time", "datetime", "duration",
406
+ "boolean", "enum", "object", "list", "estimate", "forecast",
407
+ ]);
408
+ const OPENROUTER_EXTRACTION_FIELD_KEYS = {
409
+ text: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
410
+ number: { allowed: ["type", "decimals", "instructions", "integer", "null_threshold", "unit"], required: ["type"] },
411
+ date: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
412
+ time: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
413
+ datetime: { allowed: ["type", "instructions", "null_threshold", "unit"], required: ["type"] },
414
+ duration: { allowed: ["type", "decimals", "instructions", "integer", "null_threshold", "unit"], required: ["type"] },
415
+ list: { allowed: ["type", "decimals", "instructions", "integer", "items", "null_threshold", "unit"], required: ["type", "items"] },
416
+ estimate: { allowed: ["type", "instructions", "max", "min", "scale", "step", "unit"], required: ["type", "min", "max"] },
417
+ forecast: { allowed: ["type", "horizon", "instructions", "interval", "max", "min", "scale", "step", "unit"], required: ["type", "min", "max", "horizon", "interval"] },
418
+ };
419
+ function validateOpenRouterExtractionFields(fields, model) {
420
+ const isClairic = model === "cloudflare/clairic";
421
+ const isLiquid = /^liquid\/d1\.2/.test(model);
422
+ const isScaleDown = model === "scaledown/extract";
423
+ const textItemsOnly = isScaleDown || isLiquid || model.startsWith("inception/") || model.startsWith("perplexity/");
424
+ const noNullThreshold = isScaleDown || model.startsWith("perplexity/") || model.startsWith("inference-net/");
425
+ for (const [name, field] of Object.entries(fields)) {
426
+ if (!isRecord(field) || typeof field.type !== "string")
427
+ throw new ClassifierError("input", "Each extraction field needs a type.");
428
+ const schema = OPENROUTER_EXTRACTION_FIELD_KEYS[field.type];
429
+ if (!schema)
430
+ throw new ClassifierError("input", "OpenRouter extraction does not support field type " + field.type + ".");
431
+ const keys = Object.keys(field);
432
+ const unknown = keys.filter((key) => !schema.allowed.includes(key));
433
+ if (unknown.length > 0)
434
+ throw new ClassifierError("input", "Field " + name + " uses keys OpenRouter does not accept: " + unknown.join(", ") + ".");
435
+ const missing = schema.required.filter((key) => !Object.hasOwn(field, key));
436
+ if (missing.length > 0)
437
+ throw new ClassifierError("input", "Field " + name + " is missing required OpenRouter keys: " + missing.join(", ") + ".");
438
+ if (field.null_threshold !== undefined) {
439
+ const threshold = field.null_threshold;
440
+ if (typeof threshold !== "number" || !Number.isFinite(threshold) || threshold < 0 || threshold > 1)
441
+ throw new ClassifierError("input", "Field " + name + " has an invalid null_threshold.");
442
+ if (noNullThreshold || (isClairic && ["list", "estimate", "forecast"].includes(field.type)) || (isLiquid && field.type === "list"))
443
+ throw new ClassifierError("capability", "The selected extraction model does not accept null_threshold on this field.");
444
+ if (isClairic && threshold === 0)
445
+ throw new ClassifierError("input", "Clairic requires null_threshold above zero.");
446
+ if (isLiquid && ["text", "number", "date"].includes(field.type) && threshold <= 0)
447
+ throw new ClassifierError("input", "Liquid extraction requires null_threshold above zero on text, number and date fields.");
448
+ }
449
+ else if (isLiquid && ["text", "number", "date"].includes(field.type)) {
450
+ throw new ClassifierError("input", "Liquid extraction requires null_threshold above zero on text, number and date fields.");
451
+ }
452
+ if (field.unit !== undefined && !isClairic && !(isLiquid && field.type === "estimate"))
453
+ throw new ClassifierError("capability", "The selected extraction model does not accept unit on this field.");
454
+ if (field.type === "list") {
455
+ if (typeof field.items !== "string" || !["text", "number", "date"].includes(field.items))
456
+ throw new ClassifierError("input", "OpenRouter list fields require items of text, number or date.");
457
+ if (textItemsOnly && field.items !== "text")
458
+ throw new ClassifierError("capability", "The selected extraction model supports only text list items.");
459
+ if (isLiquid && (field.unit !== undefined || field.integer !== undefined || field.decimals !== undefined))
460
+ throw new ClassifierError("capability", "Liquid list fields accept only items: text.");
461
+ }
462
+ if (field.type === "estimate" && isLiquid) {
463
+ if ((typeof field.min !== "number" || !Number.isFinite(field.min)) ||
464
+ (typeof field.max !== "number" || !Number.isFinite(field.max)) ||
465
+ (field.step !== undefined && typeof field.step !== "number"))
466
+ throw new ClassifierError("input", "Liquid estimate fields require numeric min, max and optional numeric step.");
467
+ if (field.scale !== undefined && field.scale !== "linear")
468
+ throw new ClassifierError("capability", "Liquid extraction accepts only linear estimates.");
469
+ }
470
+ }
471
+ }
472
+ function validateExtractionFields(value, allowedTypes = EXTRACTION_TYPES, maxFields = 128) {
473
+ if (!isRecord(value) || Object.keys(value).length === 0 || Object.keys(value).length > maxFields)
474
+ throw new ClassifierError("input", "fields must be a non-empty map of at most " + maxFields + " named field specifications.");
475
+ for (const [name, field] of Object.entries(value)) {
476
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/.test(name) || !isRecord(field) || typeof field.type !== "string" || !allowedTypes.has(field.type))
477
+ throw new ClassifierError("input", "Each field needs a provider field name and a documented type for the selected extraction model.");
478
+ if (field.properties !== undefined)
479
+ validateExtractionFields(field.properties, allowedTypes, maxFields);
480
+ if (field.items !== undefined && isRecord(field.items) && field.items.properties !== undefined)
481
+ validateExtractionFields(field.items.properties, allowedTypes, maxFields);
482
+ }
483
+ return value;
484
+ }
485
+ async function loadDocumentFile(path, cwd, signal) {
486
+ cancelled(signal);
487
+ try {
488
+ if (/^[a-z]+:/i.test(path))
489
+ throw new Error();
490
+ const root = await realpath(cwd);
491
+ const target = resolve(root, path);
492
+ const inside = relative(root, target);
493
+ if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
494
+ throw new Error();
495
+ let current = root;
496
+ for (const part of inside.split(sep)) {
497
+ cancelled(signal);
498
+ current = resolve(current, part);
499
+ const entry = await lstat(current);
500
+ if (entry.isSymbolicLink() || (current === target ? !entry.isFile() : !entry.isDirectory()))
501
+ throw new Error();
502
+ }
503
+ if (await realpath(target) !== target)
504
+ throw new Error();
505
+ const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
506
+ try {
507
+ await verifyOpenedPath(file.fd, root, signal);
508
+ const stat = await file.stat();
509
+ if (!stat.isFile() || stat.size < 5 || stat.size > 4 * 1024 * 1024)
510
+ throw new Error();
511
+ const buffer = Buffer.alloc(4 * 1024 * 1024 + 1);
512
+ let offset = 0;
513
+ while (offset < buffer.length) {
514
+ cancelled(signal);
515
+ const read = await file.read(buffer, offset, buffer.length - offset, null);
516
+ if (!read.bytesRead)
517
+ break;
518
+ offset += read.bytesRead;
519
+ }
520
+ if (offset > 4 * 1024 * 1024 || buffer.subarray(0, 5).toString("ascii") !== "%PDF-")
521
+ throw new Error();
522
+ return buffer.subarray(0, offset);
523
+ }
524
+ finally {
525
+ await file.close();
526
+ }
527
+ }
528
+ catch (error) {
529
+ cancelled(signal);
530
+ if (error instanceof ClassifierError)
531
+ throw error;
532
+ throw new ClassifierError("input", "Documents must be unencrypted PDF regular files inside cwd without symlinks, within 4 MiB.");
533
+ }
534
+ }
535
+ export async function prepareExtractionInput(params, route, cwd, signal) {
536
+ if (!["cloudflare-clairic", "openrouter-extractions", "litellm-extraction"].includes(route.api))
537
+ throw new ClassifierError("capability", "Extraction requires a clairic-api, openrouter-extractions-api or litellm-extraction-api route.");
538
+ if (params.state !== undefined &&
539
+ !(typeof params.state === "string" || Array.isArray(params.state) || isRecord(params.state)))
540
+ throw new ClassifierError("input", "state must be text, a JSON object or an array.");
541
+ const extractionCaps = route.api === "openrouter-extractions" ? openRouterExtractionCapabilities(route.model) : undefined;
542
+ const fields = validateExtractionFields(params.fields, extractionCaps ? new Set(extractionCaps.fieldTypes) : EXTRACTION_TYPES, extractionCaps?.maxFields);
543
+ if (route.api === "openrouter-extractions")
544
+ validateOpenRouterExtractionFields(fields, route.model);
545
+ if (extractionCaps?.referenceDate === false && params.referenceDate !== undefined)
546
+ throw new ClassifierError("capability", "The selected extraction model does not accept referenceDate.");
547
+ if (params.referenceDate !== undefined &&
548
+ (typeof params.referenceDate !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(params.referenceDate)))
549
+ throw new ClassifierError("input", "referenceDate must use YYYY-MM-DD.");
550
+ if (params.options !== undefined) {
551
+ if (!isRecord(params.options) ||
552
+ Object.keys(params.options).some((key) => !["includeQuantiles", "returnStateText"].includes(key)) ||
553
+ Object.values(params.options).some((value) => typeof value !== "boolean"))
554
+ throw new ClassifierError("input", "options may only set includeQuantiles and returnStateText to booleans.");
555
+ }
556
+ if (params.images !== undefined && (!Array.isArray(params.images) || params.images.some((image) => typeof image === "string"
557
+ ? !image.trim() || image.length > 4096
558
+ : !isRecord(image) || Object.keys(image).some((key) => key !== "path" && key !== "rotation") ||
559
+ typeof image.path !== "string" || !image.path.trim() || image.path.length > 4096 ||
560
+ (image.rotation !== undefined && ![0, 90, 180, 270].includes(image.rotation)))))
561
+ throw new ClassifierError("input", "images must be local path strings or {path, rotation} objects with rotation 0, 90, 180 or 270.");
562
+ if (route.api !== "cloudflare-clairic" && (params.images ?? []).some((image) => typeof image !== "string" && image.rotation !== undefined))
563
+ throw new ClassifierError("capability", "Image rotation is documented only for direct Cloudflare Clairic.");
564
+ if (params.documents !== undefined && (!Array.isArray(params.documents) || params.documents.some((document) => typeof document !== "string" || !document.trim() || document.length > 4096)))
565
+ throw new ClassifierError("input", "documents must be local PDF path strings inside cwd.");
566
+ const maxDocuments = route.api === "cloudflare-clairic"
567
+ ? 4
568
+ : route.api === "openrouter-extractions"
569
+ ? extractionCaps?.maxDocuments ?? 0
570
+ : 0;
571
+ if ((params.documents?.length ?? 0) > maxDocuments)
572
+ throw new ClassifierError("capability", "The selected extraction route accepts at most " + maxDocuments + " PDF documents.");
573
+ const isScaleDown = route.api === "openrouter-extractions" && route.model === "scaledown/extract";
574
+ if (isScaleDown && (params.images?.length ?? 0) + (params.documents?.length ?? 0) > 0 && params.state !== undefined && params.state !== "")
575
+ throw new ClassifierError("input", "ScaleDown Extract reads either text state or one asset, not both. Omit state when sending a PDF or image.");
576
+ const images = await Promise.all((params.images ?? []).map(async (image) => {
577
+ const spec = typeof image === "string" ? { path: image } : image;
578
+ const loaded = await loadLocalImage(spec.path, cwd, signal, 4 * 1024 * 1024);
579
+ return spec.rotation === undefined ? loaded : { ...loaded, rotation: spec.rotation };
580
+ }));
581
+ const documents = await Promise.all((params.documents ?? []).map(async (document) => ({
582
+ mimeType: "application/pdf",
583
+ data: (await loadDocumentFile(document, cwd, signal)).toString("base64"),
584
+ })));
585
+ if (route.api === "openrouter-extractions" && /^liquid\/d1\.2/.test(route.model) && images.length > 0 &&
586
+ Object.values(fields).some((field) => isRecord(field) && field.type !== "estimate"))
587
+ throw new ClassifierError("capability", "OpenRouter Liquid extraction models read images only for estimate fields.");
588
+ if (isScaleDown && images.some((image) => image.mimeType === "image/webp"))
589
+ throw new ClassifierError("capability", "ScaleDown Extract does not read WebP images.");
590
+ if (images.length > route.limits.maxImages)
591
+ throw new ClassifierError("input", "The selected extraction model accepts at most " + route.limits.maxImages + " images.");
592
+ const maxAssets = route.api === "cloudflare-clairic"
593
+ ? 4
594
+ : extractionCaps?.maxAssets ?? route.limits.maxImages;
595
+ if (images.length + documents.length > maxAssets)
596
+ throw new ClassifierError("input", "The selected extraction model accepts at most " + maxAssets + " media assets in total.");
597
+ if (route.api === "cloudflare-clairic" && images.length + documents.length > 4)
598
+ throw new ClassifierError("input", "Direct Clairic accepts at most four rendered images and PDF pages combined.");
599
+ let bytes = 0;
600
+ for (const media of [...images.map((image) => Buffer.from(image.data, "base64")), ...documents.map((document) => Buffer.from(document.data, "base64"))]) {
601
+ bytes += media.byteLength;
602
+ if (bytes > 8 * 1024 * 1024)
603
+ throw new ClassifierError("input", "Extraction media exceeds the provider's 8 MiB combined decoded limit.");
604
+ }
605
+ if ((params.state === undefined || params.state === "") && images.length === 0 && documents.length === 0)
606
+ throw new ClassifierError("input", "Extraction requires a non-empty state or media input.");
607
+ return {
608
+ state: params.state ?? "",
609
+ fields,
610
+ images,
611
+ documents,
612
+ ...(params.referenceDate !== undefined ? { referenceDate: params.referenceDate } : {}),
613
+ ...(params.options !== undefined ? { options: params.options } : {}),
614
+ };
615
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,39 @@
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
+ import { createRequire } from 'node:module';
5
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import { createClassifierMcpServer } from './mcp-server.js';
7
+ const require = createRequire(import.meta.url);
8
+ const manifest = require('../package.json');
9
+ const version = typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
10
+ ? manifest.version
11
+ : '0.0.0';
12
+ // Keep stray dependency output off the JSON-RPC stream.
13
+ console.log = console.info = console.debug = console.error;
14
+ const server = createClassifierMcpServer({ cwd: process.cwd(), info: { name: 'pi-classifier', version } });
15
+ const transport = new StdioServerTransport();
16
+ let closing = false;
17
+ async function shutdown(code) {
18
+ if (closing)
19
+ return;
20
+ closing = true;
21
+ try {
22
+ await server.close();
23
+ }
24
+ catch (error) {
25
+ console.error('pi-classifier-mcp: error during shutdown:', error);
26
+ }
27
+ process.exit(code);
28
+ }
29
+ process.stdin.once('end', () => void shutdown(0));
30
+ process.stdin.once('close', () => void shutdown(0));
31
+ process.once('SIGINT', () => void shutdown(0));
32
+ process.once('SIGTERM', () => void shutdown(0));
33
+ try {
34
+ await server.connect(transport);
35
+ }
36
+ catch (error) {
37
+ console.error('pi-classifier-mcp: failed to start:', error);
38
+ process.exit(1);
39
+ }
@@ -0,0 +1,28 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import type { CredentialSource } from './auth.js';
3
+ import { type ClassifierSettings } from './types.js';
4
+ import { type ClassifierMcpToolName } from './mcp-tool-definitions.js';
5
+ export interface McpServerInfo {
6
+ name: string;
7
+ version: string;
8
+ }
9
+ export interface ClassifierMcpServerOptions {
10
+ /** Directory for relative image, media, tree and output paths. Defaults to process.cwd(). */
11
+ cwd?: string;
12
+ /** Preloaded settings; otherwise read by the owning package. */
13
+ settings?: ClassifierSettings;
14
+ /** Project settings are not loaded unless the caller supplies trust explicitly. */
15
+ projectTrusted?: boolean;
16
+ /**
17
+ * Credential origin. The standalone server defaults to explicit provider keys
18
+ * so a non-Pi MCP client cannot silently use Pi chat login credentials.
19
+ */
20
+ credentialSource?: CredentialSource;
21
+ /** Optional allowlist of MCP tool names. */
22
+ enabledTools?: readonly ClassifierMcpToolName[];
23
+ info?: McpServerInfo;
24
+ }
25
+ export declare const classifierMcpServerInfo: McpServerInfo;
26
+ /** Create an MCP Server. The CLI connects it to stdio; embedders own any other transport. */
27
+ export declare function createClassifierMcpServer(options?: ClassifierMcpServerOptions): Server;
28
+ export { CLASSIFIER_MCP_TOOL_DEFINITIONS, validateMcpToolArguments, type ClassifierMcpToolDefinition, type ClassifierMcpToolName, } from './mcp-tool-definitions.js';