@abhishek944/pi-classifier 0.3.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.
- package/CHANGELOG.md +48 -0
- package/COMPUTER_USE.md +117 -0
- package/README.md +344 -30
- package/dist/auth.d.ts +4 -2
- package/dist/auth.js +18 -2
- package/dist/box-tool.d.ts +4 -0
- package/dist/box-tool.js +79 -0
- package/dist/box.d.ts +32 -0
- package/dist/box.js +148 -0
- package/dist/choices.js +35 -1
- package/dist/classify.d.ts +6 -0
- package/dist/classify.js +4 -4
- package/dist/computer-use-state.d.ts +9 -0
- package/dist/computer-use-state.js +160 -0
- package/dist/computer-use-tool.d.ts +52 -0
- package/dist/computer-use-tool.js +78 -0
- package/dist/computer-use-types.d.ts +132 -0
- package/dist/computer-use-types.js +1 -0
- package/dist/computer-use.d.ts +22 -0
- package/dist/computer-use.js +223 -0
- package/dist/config.d.ts +140 -3
- package/dist/config.js +405 -20
- package/dist/cost.js +42 -4
- package/dist/durable.d.ts +34 -0
- package/dist/durable.js +237 -0
- package/dist/extension.d.ts +2 -247
- package/dist/extension.js +53 -190
- package/dist/extract.d.ts +11 -0
- package/dist/extract.js +191 -0
- package/dist/http.d.ts +6 -1
- package/dist/http.js +64 -28
- package/dist/image-content.d.ts +12 -0
- package/dist/image-content.js +90 -0
- package/dist/index.d.ts +10 -1
- package/dist/index.js +3 -0
- package/dist/inputs.d.ts +24 -2
- package/dist/inputs.js +565 -134
- package/dist/mcp-cli.d.ts +2 -0
- package/dist/mcp-cli.js +39 -0
- package/dist/mcp-server.d.ts +28 -0
- package/dist/mcp-server.js +121 -0
- package/dist/mcp-tool-definitions.d.ts +19 -0
- package/dist/mcp-tool-definitions.js +64 -0
- package/dist/providers.d.ts +1 -0
- package/dist/providers.js +1218 -124
- package/dist/tool-contracts.d.ts +785 -0
- package/dist/tool-contracts.js +530 -0
- package/dist/tree.js +1 -1
- package/dist/types.d.ts +314 -20
- package/dist/validation.js +181 -44
- package/package.json +33 -5
- package/src/auth.ts +26 -2
- package/src/box-tool.ts +110 -0
- package/src/box.ts +253 -0
- package/src/choices.ts +44 -2
- package/src/classify.ts +10 -6
- package/src/computer-use-state.ts +145 -0
- package/src/computer-use-tool.ts +76 -0
- package/src/computer-use-types.ts +127 -0
- package/src/computer-use.ts +216 -0
- package/src/config.ts +454 -23
- package/src/cost.ts +42 -4
- package/src/durable.ts +298 -0
- package/src/extension.ts +79 -265
- package/src/extract.ts +228 -0
- package/src/http.ts +63 -32
- package/src/image-content.ts +77 -0
- package/src/index.ts +25 -0
- package/src/inputs.ts +603 -184
- package/src/mcp-cli.ts +44 -0
- package/src/mcp-server.ts +179 -0
- package/src/mcp-tool-definitions.ts +104 -0
- package/src/providers.ts +1398 -144
- package/src/tool-contracts.ts +785 -0
- package/src/tree.ts +1 -1
- package/src/types.ts +248 -11
- package/src/validation.ts +169 -96
package/dist/inputs.js
CHANGED
|
@@ -4,146 +4,279 @@ 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
|
-
|
|
10
|
-
|
|
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
|
+
}
|
|
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;
|
|
23
|
+
const imageCount = (params.images?.length ?? 0) + memoryImages.length;
|
|
24
|
+
if (imageCount && !route.images)
|
|
11
25
|
throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
|
|
12
|
-
if (hasBox(params.questions) && (!route.box || !
|
|
26
|
+
if (hasBox(params.questions) && (!route.box || !imageCount))
|
|
13
27
|
throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
if (
|
|
19
|
-
throw new ClassifierError("
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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.");
|
|
44
74
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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
|
+
}
|
|
87
|
+
const clef = route.api === "cloudflare-system-one" && route.images;
|
|
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.");
|
|
99
|
+
for (const question of Object.values(params.questions)) {
|
|
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.");
|
|
104
|
+
}
|
|
105
|
+
// Reject unsupported URL placement before opening any local files.
|
|
106
|
+
for (const source of params.images ?? []) {
|
|
107
|
+
if (typeof source !== "string" && "url" in source) {
|
|
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.");
|
|
50
110
|
try {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const stat = await file.stat();
|
|
54
|
-
if (!stat.isFile() || stat.size < 1 || stat.size > perImageLimit)
|
|
55
|
-
throw new Error();
|
|
56
|
-
// Read a bounded number of bytes even if another process grows the file.
|
|
57
|
-
const buffer = Buffer.alloc(perImageLimit + 1);
|
|
58
|
-
let offset = 0;
|
|
59
|
-
while (offset < buffer.length) {
|
|
60
|
-
if (signal?.aborted)
|
|
61
|
-
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
62
|
-
const read = await file.read(buffer, offset, buffer.length - offset, null);
|
|
63
|
-
if (!read.bytesRead)
|
|
64
|
-
break;
|
|
65
|
-
offset += read.bytesRead;
|
|
66
|
-
}
|
|
67
|
-
if (offset > perImageLimit)
|
|
111
|
+
const url = new URL(source.url);
|
|
112
|
+
if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.hash)
|
|
68
113
|
throw new Error();
|
|
69
|
-
bytes = buffer.subarray(0, offset);
|
|
70
114
|
}
|
|
71
|
-
|
|
72
|
-
|
|
115
|
+
catch {
|
|
116
|
+
throw new ClassifierError("input", "Image URLs must be absolute HTTP(S) URLs without credentials or fragments.");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const images = [];
|
|
121
|
+
let totalBytes = 0;
|
|
122
|
+
const sources = [
|
|
123
|
+
...(params.images ?? []).map((source) => ({ source })),
|
|
124
|
+
...memoryImages.map((memory) => ({ memory })),
|
|
125
|
+
];
|
|
126
|
+
for (const entry of sources) {
|
|
127
|
+
cancelled(signal);
|
|
128
|
+
const maxBytes = (clef ? 4 : 5) * 1024 * 1024;
|
|
129
|
+
let image;
|
|
130
|
+
let id;
|
|
131
|
+
if ("memory" in entry) {
|
|
132
|
+
image = await prepareImageBytes(entry.memory.bytes, signal, maxBytes, entry.memory.mimeType);
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
const source = entry.source;
|
|
136
|
+
if (typeof source !== "string" && "url" in source) {
|
|
137
|
+
images.push({ id: source.id, url: source.url });
|
|
138
|
+
continue;
|
|
73
139
|
}
|
|
74
|
-
|
|
75
|
-
if (
|
|
140
|
+
image = await loadLocalImage(typeof source === "string" ? source : source.path, cwd, signal, maxBytes);
|
|
141
|
+
if (typeof source !== "string")
|
|
142
|
+
id = source.id;
|
|
143
|
+
}
|
|
144
|
+
totalBytes += Buffer.byteLength(image.data, "base64");
|
|
145
|
+
if (totalBytes > (clef ? 8 : 10) * 1024 * 1024)
|
|
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.");
|
|
149
|
+
if (route.api === "system-one") {
|
|
150
|
+
if (image.mimeType === "image/webp")
|
|
151
|
+
throw new ClassifierError("input", "Jev image assets accept PNG and JPEG only.");
|
|
152
|
+
const pixels = image.width * image.height;
|
|
153
|
+
if (image.width < 280 || image.width > 1568 || image.height < 280 || image.height > 1568 || pixels < 78_400 || pixels > 2_458_624)
|
|
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.");
|
|
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
|
+
}
|
|
169
|
+
if (route.api === "perplexity-decisions" && Math.ceil(image.width / 32) * Math.ceil(image.height / 32) > 2048)
|
|
170
|
+
throw new ClassifierError("input", "Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.");
|
|
171
|
+
images.push(id === undefined ? image : { ...image, id });
|
|
172
|
+
}
|
|
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
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/** Bounded, fully decoded local image; shared by uploads and local box rendering. */
|
|
186
|
+
export async function loadLocalImage(path, cwd, signal, maxBytes = 5 * 1024 * 1024) {
|
|
187
|
+
cancelled(signal);
|
|
188
|
+
try {
|
|
189
|
+
if (/^[a-z]+:/i.test(path))
|
|
190
|
+
throw new Error();
|
|
191
|
+
const root = await realpath(cwd);
|
|
192
|
+
const target = resolve(root, path);
|
|
193
|
+
const inside = relative(root, target);
|
|
194
|
+
if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
|
|
195
|
+
throw new Error();
|
|
196
|
+
// Reject symlink components, not just the final image.
|
|
197
|
+
let current = root;
|
|
198
|
+
for (const part of inside.split(sep)) {
|
|
199
|
+
current = resolve(current, part);
|
|
200
|
+
const entry = await lstat(current);
|
|
201
|
+
if (entry.isSymbolicLink() || (current === target && !entry.isFile()) || (current !== target && !entry.isDirectory()))
|
|
76
202
|
throw new Error();
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
203
|
+
}
|
|
204
|
+
if (await realpath(target) !== target)
|
|
205
|
+
throw new Error();
|
|
206
|
+
const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
207
|
+
let bytes;
|
|
208
|
+
try {
|
|
209
|
+
// Verify the opened object as well: pre-open path checks alone are raceable.
|
|
210
|
+
await verifyOpenedPath(file.fd, root, signal);
|
|
211
|
+
const stat = await file.stat();
|
|
212
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > maxBytes)
|
|
84
213
|
throw new Error();
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
pixels > 2_458_624) {
|
|
95
|
-
throw new ClassifierError("input", "Resize or pad Jev images before sending: each side must be 256–1568 pixels and total area 78400–2458624 pixels. Images are not silently resized.");
|
|
96
|
-
}
|
|
214
|
+
// A bounded read also handles files grown concurrently after stat().
|
|
215
|
+
const buffer = Buffer.alloc(maxBytes + 1);
|
|
216
|
+
let offset = 0;
|
|
217
|
+
while (offset < buffer.length) {
|
|
218
|
+
cancelled(signal);
|
|
219
|
+
const read = await file.read(buffer, offset, buffer.length - offset, null);
|
|
220
|
+
if (!read.bytesRead)
|
|
221
|
+
break;
|
|
222
|
+
offset += read.bytesRead;
|
|
97
223
|
}
|
|
98
|
-
if (
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
catch (error) {
|
|
114
|
-
if (signal?.aborted)
|
|
115
|
-
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
116
|
-
if (error instanceof ClassifierError)
|
|
117
|
-
throw error;
|
|
118
|
-
throw new ClassifierError("input", "Images must be non-animated PNG/JPEG/WebP regular files inside cwd, without symlinks, and fit the documented byte and pixel limits (Clef: 4 MiB each/8 MiB total; others: 5 MiB each/10 MiB total; 16 megapixels each).");
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
return { state: params.state, questions: params.questions, images };
|
|
224
|
+
if (offset > maxBytes)
|
|
225
|
+
throw new Error();
|
|
226
|
+
bytes = buffer.subarray(0, offset);
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
await file.close();
|
|
230
|
+
}
|
|
231
|
+
return await prepareImageBytes(bytes, signal, maxBytes);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
cancelled(signal);
|
|
235
|
+
if (error instanceof ClassifierError)
|
|
236
|
+
throw error;
|
|
237
|
+
throw new ClassifierError("input", "Images must be non-animated PNG/JPEG/WebP regular files inside cwd, without symlinks, within the documented byte limit and 16 megapixels each.");
|
|
238
|
+
}
|
|
122
239
|
}
|
|
123
|
-
|
|
240
|
+
/** The same full-decode boundary for files and transient Driver captures. */
|
|
241
|
+
async function prepareImageBytes(input, signal, maxBytes, declaredMime) {
|
|
242
|
+
cancelled(signal);
|
|
243
|
+
if (!(input instanceof Uint8Array) || input.byteLength < 1 || input.byteLength > maxBytes)
|
|
244
|
+
throw new ClassifierError("input", "Image bytes exceed the selected route's limit.");
|
|
245
|
+
try {
|
|
246
|
+
const bytes = Buffer.from(input);
|
|
247
|
+
const meta = await sharp(bytes, { limitInputPixels: 16_777_216 }).metadata();
|
|
248
|
+
if (!meta.width || !meta.height || !["png", "jpeg", "webp"].includes(meta.format ?? "") || (meta.pages ?? 1) > 1)
|
|
249
|
+
throw new Error();
|
|
250
|
+
const mimeType = meta.format === "jpeg" ? "image/jpeg" : meta.format === "png" ? "image/png" : "image/webp";
|
|
251
|
+
if (declaredMime !== undefined && declaredMime !== mimeType)
|
|
252
|
+
throw new Error();
|
|
253
|
+
await decodeImage(bytes, signal);
|
|
254
|
+
cancelled(signal);
|
|
255
|
+
return { data: bytes.toString("base64"), mimeType, width: meta.width, height: meta.height };
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
cancelled(signal);
|
|
259
|
+
if (error instanceof ClassifierError)
|
|
260
|
+
throw error;
|
|
261
|
+
throw new ClassifierError("input", "Image bytes must decode as a still PNG/JPEG/WebP matching the declared MIME type, within 16 megapixels.");
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function cancelled(signal) {
|
|
124
265
|
if (signal?.aborted)
|
|
125
266
|
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
})
|
|
131
|
-
.timeout({ seconds: 10 })
|
|
132
|
-
.raw();
|
|
267
|
+
}
|
|
268
|
+
async function decodeImage(bytes, signal) {
|
|
269
|
+
cancelled(signal);
|
|
270
|
+
// Output through a raw pipeline decodes every pixel and honors the native timeout.
|
|
271
|
+
const decoder = sharp(bytes, { limitInputPixels: 16_777_216, failOn: "warning" }).timeout({ seconds: 10 }).raw();
|
|
133
272
|
let cancel = () => { };
|
|
134
273
|
let timer;
|
|
135
274
|
try {
|
|
136
275
|
await new Promise((resolve, reject) => {
|
|
137
|
-
cancel = () => {
|
|
138
|
-
decoder.destroy();
|
|
139
|
-
reject(new ClassifierError("aborted", "Classification was cancelled."));
|
|
140
|
-
};
|
|
276
|
+
cancel = () => { decoder.destroy(); reject(new ClassifierError("aborted", "Classification was cancelled.")); };
|
|
141
277
|
signal?.addEventListener("abort", cancel, { once: true });
|
|
142
|
-
timer = setTimeout(() => {
|
|
143
|
-
|
|
144
|
-
reject(new ClassifierError("input", "Image decoding timed out."));
|
|
145
|
-
}, 10_000);
|
|
146
|
-
// Attach both handlers even after cancellation so the native callback cannot reject unhandled.
|
|
278
|
+
timer = setTimeout(() => { decoder.destroy(); reject(new ClassifierError("input", "Image decoding timed out.")); }, 10_000);
|
|
279
|
+
// Keep a rejection handler attached even after cancellation destroys the pipeline.
|
|
147
280
|
decoder.toBuffer().then(() => resolve(), reject);
|
|
148
281
|
});
|
|
149
282
|
}
|
|
@@ -157,28 +290,326 @@ const execFileAsync = promisify(execFile);
|
|
|
157
290
|
/** Verify containment of the opened descriptor, not a raceable pre-open path. */
|
|
158
291
|
export async function verifyOpenedPath(fd, root, signal) {
|
|
159
292
|
let openedPath;
|
|
160
|
-
if (process.platform === "linux")
|
|
293
|
+
if (process.platform === "linux")
|
|
161
294
|
openedPath = await realpath("/proc/self/fd/" + fd);
|
|
162
|
-
}
|
|
163
295
|
else if (process.platform === "darwin") {
|
|
164
|
-
// Node does not expose F_GETPATH; the OS
|
|
296
|
+
// Node does not expose F_GETPATH; the OS utility queries this exact descriptor.
|
|
165
297
|
const { stdout } = await execFileAsync("/usr/sbin/lsof", ["-a", "-p", String(process.pid), "-d", String(fd), "-Fn"], {
|
|
166
|
-
timeout: 3000,
|
|
167
|
-
maxBuffer: 8192,
|
|
168
|
-
...(signal ? { signal } : {}),
|
|
298
|
+
timeout: 3000, maxBuffer: 8192, ...(signal ? { signal } : {}),
|
|
169
299
|
});
|
|
170
300
|
const paths = stdout.split("\n").filter((line) => line.startsWith("n"));
|
|
171
301
|
if (paths.length !== 1)
|
|
172
302
|
throw new Error();
|
|
173
303
|
openedPath = paths[0].slice(1);
|
|
174
304
|
}
|
|
175
|
-
else
|
|
176
|
-
throw new ClassifierError("capability", "Safe local file loading currently supports macOS and Linux only. Inline text/JSON classification
|
|
177
|
-
}
|
|
305
|
+
else
|
|
306
|
+
throw new ClassifierError("capability", "Safe local file loading currently supports macOS and Linux only. Inline text/JSON and hosted-image classification remain available.");
|
|
178
307
|
const inside = relative(root, openedPath);
|
|
179
|
-
if (!inside ||
|
|
180
|
-
inside === ".." ||
|
|
181
|
-
inside.startsWith(".." + sep) ||
|
|
182
|
-
isAbsolute(inside))
|
|
308
|
+
if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
|
|
183
309
|
throw new Error();
|
|
184
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
|
+
}
|