@abhishek944/pi-classifier 0.0.0-stage → 0.2.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 +25 -0
- package/LICENSE +201 -0
- package/README.md +241 -2
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +56 -0
- package/dist/classify.d.ts +11 -0
- package/dist/classify.js +117 -0
- package/dist/config.d.ts +82 -0
- package/dist/config.js +298 -0
- package/dist/extension.d.ts +122 -0
- package/dist/extension.js +255 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.js +85 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/inputs.d.ts +2 -0
- package/dist/inputs.js +184 -0
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +614 -0
- package/dist/settings-write.d.ts +10 -0
- package/dist/settings-write.js +110 -0
- package/dist/types.d.ts +144 -0
- package/dist/types.js +18 -0
- package/dist/validation.d.ts +3 -0
- package/dist/validation.js +95 -0
- package/package.json +72 -4
- package/src/auth.ts +74 -0
- package/src/classify.ts +157 -0
- package/src/config.ts +391 -0
- package/src/extension.ts +362 -0
- package/src/http.ts +108 -0
- package/src/index.ts +17 -0
- package/src/inputs.ts +239 -0
- package/src/providers.ts +898 -0
- package/src/settings-write.ts +145 -0
- package/src/types.ts +152 -0
- package/src/validation.ts +139 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { isProjectTrusted } from "@amaster.ai/pi-shared/settings";
|
|
2
|
+
import { defineTool, } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { classify, compareClassifiers } from "./classify.js";
|
|
5
|
+
import { configuredRoutes, listModels, loadClassifierSettings, resolveModel, } from "./config.js";
|
|
6
|
+
import { updateProjectClassifierSettings } from "./settings-write.js";
|
|
7
|
+
import { ClassifierError, userError } from "./types.js";
|
|
8
|
+
const shortText = Type.String({ maxLength: 4096 });
|
|
9
|
+
const question = Type.Union([
|
|
10
|
+
Type.Object({
|
|
11
|
+
type: Type.Literal("bool"),
|
|
12
|
+
instructions: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
13
|
+
criteria: Type.Optional(Type.Object({ true: Type.Optional(shortText), false: Type.Optional(shortText) }, { additionalProperties: false })),
|
|
14
|
+
}, { additionalProperties: false }),
|
|
15
|
+
Type.Object({
|
|
16
|
+
type: Type.Literal("choice"),
|
|
17
|
+
instructions: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
18
|
+
criteria: Type.Record(Type.String({ minLength: 1, maxLength: 128 }), shortText, { minProperties: 1, maxProperties: 64 }),
|
|
19
|
+
}, { additionalProperties: false }),
|
|
20
|
+
Type.Object({
|
|
21
|
+
type: Type.Literal("score"),
|
|
22
|
+
instructions: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
23
|
+
criteria: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
|
|
24
|
+
minItems: 2,
|
|
25
|
+
maxItems: 10,
|
|
26
|
+
}),
|
|
27
|
+
}, { additionalProperties: false }),
|
|
28
|
+
Type.Object({
|
|
29
|
+
type: Type.Literal("box"),
|
|
30
|
+
instructions: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
31
|
+
}, { additionalProperties: false }),
|
|
32
|
+
]);
|
|
33
|
+
export const classifyParameters = Type.Object({
|
|
34
|
+
state: Type.Union([
|
|
35
|
+
Type.String(),
|
|
36
|
+
Type.Record(Type.String(), Type.Unknown()),
|
|
37
|
+
Type.Array(Type.Unknown()),
|
|
38
|
+
], {
|
|
39
|
+
description: "Text or JSON data to classify. All questions refer to this same state.",
|
|
40
|
+
}),
|
|
41
|
+
questions: Type.Record(Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }), question, { minProperties: 1, maxProperties: 32 }),
|
|
42
|
+
images: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
|
|
43
|
+
maxItems: 5,
|
|
44
|
+
description: "Local PNG/JPEG/WebP files inside cwd, in order. No URLs, symlinks or inline base64. Requires an image-capable model.",
|
|
45
|
+
})),
|
|
46
|
+
}, { additionalProperties: false });
|
|
47
|
+
export const classifyOutput = Type.Object({
|
|
48
|
+
provider: Type.String(),
|
|
49
|
+
model: Type.String(),
|
|
50
|
+
answers: Type.Record(Type.String(), Type.Union([
|
|
51
|
+
Type.Object({
|
|
52
|
+
type: Type.Literal("bool"),
|
|
53
|
+
probability: Type.Number({ minimum: 0, maximum: 1 }),
|
|
54
|
+
}),
|
|
55
|
+
Type.Object({
|
|
56
|
+
type: Type.Literal("choice"),
|
|
57
|
+
choice: Type.String(),
|
|
58
|
+
probabilities: Type.Record(Type.String(), Type.Number({ minimum: 0, maximum: 1 })),
|
|
59
|
+
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
60
|
+
}),
|
|
61
|
+
Type.Object({
|
|
62
|
+
type: Type.Literal("score"),
|
|
63
|
+
score: Type.Number(),
|
|
64
|
+
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
65
|
+
probabilities: Type.Optional(Type.Record(Type.String(), Type.Number({ minimum: 0, maximum: 1 }))),
|
|
66
|
+
}),
|
|
67
|
+
Type.Object({
|
|
68
|
+
type: Type.Literal("box"),
|
|
69
|
+
box: Type.Object({
|
|
70
|
+
top: Type.Number(),
|
|
71
|
+
bottom: Type.Number(),
|
|
72
|
+
left: Type.Number(),
|
|
73
|
+
right: Type.Number(),
|
|
74
|
+
}),
|
|
75
|
+
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
76
|
+
}),
|
|
77
|
+
Type.Object({ type: Type.Literal("refusal") }),
|
|
78
|
+
])),
|
|
79
|
+
usage: Type.Optional(Type.Object({
|
|
80
|
+
inputTokens: Type.Number(),
|
|
81
|
+
outputTokens: Type.Number(),
|
|
82
|
+
totalTokens: Type.Number(),
|
|
83
|
+
})),
|
|
84
|
+
requestId: Type.Optional(Type.String()),
|
|
85
|
+
attemptedRoutes: Type.Optional(Type.Array(Type.Object({ provider: Type.String(), model: Type.String() }))),
|
|
86
|
+
});
|
|
87
|
+
export const classifyCompareOutput = Type.Object({
|
|
88
|
+
cancelled: Type.Boolean(),
|
|
89
|
+
results: Type.Array(Type.Union([
|
|
90
|
+
Type.Object({
|
|
91
|
+
provider: Type.String(),
|
|
92
|
+
model: Type.String(),
|
|
93
|
+
durationMs: Type.Number(),
|
|
94
|
+
status: Type.Literal("success"),
|
|
95
|
+
result: classifyOutput,
|
|
96
|
+
}),
|
|
97
|
+
Type.Object({
|
|
98
|
+
provider: Type.String(),
|
|
99
|
+
model: Type.String(),
|
|
100
|
+
durationMs: Type.Number(),
|
|
101
|
+
status: Type.Literal("error"),
|
|
102
|
+
error: Type.Object({ code: Type.String(), message: Type.String() }),
|
|
103
|
+
}),
|
|
104
|
+
])),
|
|
105
|
+
});
|
|
106
|
+
export default function piClassifier(pi) {
|
|
107
|
+
pi.registerTool(defineTool({
|
|
108
|
+
name: "classify",
|
|
109
|
+
label: "Classify",
|
|
110
|
+
description: "Ask a decision model typed questions about text, JSON and supported local images. Returns bool probabilities, choices with probabilities, or scores. Experimental box answers require explicit Jev configuration. Provider/model are fixed by pi-classifier.default (or legacy defaultProvider/defaultModel); this tool cannot override them. API-key authentication is independent of Codex chat login. Only explicitly configured fallback routes may be used after a missing key or HTTP 401/404/429; never after uncertainty, refusals, timeouts or network failures. Use /classifier list or status to inspect configuration.",
|
|
111
|
+
promptSnippet: "Classify text, JSON or supported images into typed probabilistic decisions.",
|
|
112
|
+
promptGuidelines: [
|
|
113
|
+
"Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
|
|
114
|
+
"Treat low confidence as uncertainty, not permission to switch models or retry.",
|
|
115
|
+
"Send only data the user intends to share with the configured provider.",
|
|
116
|
+
"Ask /classifier status for the active model. Do not change provider settings without user direction.",
|
|
117
|
+
],
|
|
118
|
+
parameters: classifyParameters,
|
|
119
|
+
outputSchema: classifyOutput,
|
|
120
|
+
annotations: {
|
|
121
|
+
readOnlyHint: true,
|
|
122
|
+
destructiveHint: false,
|
|
123
|
+
openWorldHint: true,
|
|
124
|
+
},
|
|
125
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
126
|
+
try {
|
|
127
|
+
const result = await classify(params, {
|
|
128
|
+
settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
129
|
+
cwd: ctx.cwd,
|
|
130
|
+
...(signal ? { signal } : {}),
|
|
131
|
+
});
|
|
132
|
+
return {
|
|
133
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
134
|
+
details: result,
|
|
135
|
+
structuredContent: { ...result },
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
console.error("[pi-classifier] classify failed: " +
|
|
140
|
+
(error instanceof ClassifierError ? error.code : "unexpected"));
|
|
141
|
+
throw new Error(userError(error));
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
}));
|
|
145
|
+
pi.registerTool(defineTool({
|
|
146
|
+
name: "classify_compare",
|
|
147
|
+
label: "Compare classifiers",
|
|
148
|
+
description: "Explicitly compare the same typed questions and state using exactly pi-classifier.compare provider/model pairs. Each entry is a separate potentially billable request. No fallback, default substitution, provider/model overrides, or default changes. Returns labeled results, duration, usage and safe per-entry failures; cancellation retains completed results and prevents later requests.",
|
|
149
|
+
promptSnippet: "Compare configured decision models only when the user explicitly requests a model comparison.",
|
|
150
|
+
promptGuidelines: [
|
|
151
|
+
"Use only when the user explicitly asks to compare classifier models; never use automatically for low confidence or refusals.",
|
|
152
|
+
"Each configured comparison route receives the submitted data and may incur a charge.",
|
|
153
|
+
],
|
|
154
|
+
parameters: classifyParameters,
|
|
155
|
+
outputSchema: classifyCompareOutput,
|
|
156
|
+
annotations: {
|
|
157
|
+
readOnlyHint: true,
|
|
158
|
+
destructiveHint: false,
|
|
159
|
+
openWorldHint: true,
|
|
160
|
+
},
|
|
161
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
162
|
+
try {
|
|
163
|
+
const result = await compareClassifiers(params, {
|
|
164
|
+
settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
165
|
+
cwd: ctx.cwd,
|
|
166
|
+
...(signal ? { signal } : {}),
|
|
167
|
+
});
|
|
168
|
+
return {
|
|
169
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
170
|
+
details: result,
|
|
171
|
+
structuredContent: { ...result },
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
throw new Error(userError(error));
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
}));
|
|
179
|
+
pi.registerCommand("classifier", {
|
|
180
|
+
description: "Classifier: status, list, reload, use <route> <model>, compare <JSON params>. Use writes trusted project defaults; compare makes potentially billable calls.",
|
|
181
|
+
handler: async (args, ctx) => {
|
|
182
|
+
try {
|
|
183
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
184
|
+
const command = parts[0] ?? "status";
|
|
185
|
+
const settings = loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx));
|
|
186
|
+
if (command === "compare") {
|
|
187
|
+
let params;
|
|
188
|
+
try {
|
|
189
|
+
params = JSON.parse(args.trim().slice("compare".length).trim());
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
throw new ClassifierError("input", "Usage: /classifier compare <JSON with state, questions and optional images>.");
|
|
193
|
+
}
|
|
194
|
+
const result = await compareClassifiers(params, {
|
|
195
|
+
settings,
|
|
196
|
+
cwd: ctx.cwd,
|
|
197
|
+
...(ctx.signal ? { signal: ctx.signal } : {}),
|
|
198
|
+
});
|
|
199
|
+
reply(pi, ctx, JSON.stringify(result, null, 2));
|
|
200
|
+
}
|
|
201
|
+
else if (command === "list" && parts.length === 1) {
|
|
202
|
+
reply(pi, ctx, listModels(settings) +
|
|
203
|
+
"\n\nFallback: " +
|
|
204
|
+
JSON.stringify(configuredRoutes(settings, "fallback")) +
|
|
205
|
+
"\nCompare: " +
|
|
206
|
+
JSON.stringify(configuredRoutes(settings, "compare")));
|
|
207
|
+
}
|
|
208
|
+
else if ((command === "status" || command === "reload") &&
|
|
209
|
+
parts.length <= 1) {
|
|
210
|
+
const route = resolveModel(settings);
|
|
211
|
+
reply(pi, ctx, JSON.stringify({
|
|
212
|
+
provider: route.route,
|
|
213
|
+
model: route.model,
|
|
214
|
+
images: route.images,
|
|
215
|
+
box: route.box,
|
|
216
|
+
requestTimeoutMs: route.requestTimeoutMs,
|
|
217
|
+
authentication: "API key only; independent of chat login",
|
|
218
|
+
fallback: configuredRoutes(settings, "fallback"),
|
|
219
|
+
compare: configuredRoutes(settings, "compare"),
|
|
220
|
+
}, null, 2));
|
|
221
|
+
}
|
|
222
|
+
else if (command === "use" && parts.length === 3) {
|
|
223
|
+
const selected = {
|
|
224
|
+
...settings,
|
|
225
|
+
default: { provider: parts[1], model: parts[2] },
|
|
226
|
+
};
|
|
227
|
+
const route = resolveModel(selected);
|
|
228
|
+
await updateProjectClassifierSettings(ctx.cwd, isProjectTrusted(ctx), { default: { provider: route.route, model: route.model } });
|
|
229
|
+
reply(pi, ctx, "Selected " +
|
|
230
|
+
route.route +
|
|
231
|
+
" / " +
|
|
232
|
+
route.model +
|
|
233
|
+
" in project settings. Chat login is unchanged.");
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
reply(pi, ctx, "Usage: /classifier status | list | reload | use <route> <model> | compare <JSON params>");
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
console.error("[pi-classifier] command failed: " +
|
|
241
|
+
(error instanceof ClassifierError ? error.code : "configuration"));
|
|
242
|
+
reply(pi, ctx, error instanceof ClassifierError
|
|
243
|
+
? error.message
|
|
244
|
+
: "Could not update classifier settings. Check project trust and settings JSON.");
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
function reply(pi, ctx, text) {
|
|
250
|
+
const bounded = text.length > 16000 ? text.slice(0, 16000) + "\n[truncated]" : text;
|
|
251
|
+
if (ctx.hasUI)
|
|
252
|
+
ctx.ui.notify(bounded, "info");
|
|
253
|
+
else
|
|
254
|
+
pi.sendMessage({ customType: "pi-classifier", content: bounded, display: true }, { triggerTurn: false });
|
|
255
|
+
}
|
package/dist/http.d.ts
ADDED
package/dist/http.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { ClassifierError } from "./types.js";
|
|
2
|
+
export async function postJson(route, path, body, apiKey, signal, extraHeaders) {
|
|
3
|
+
if (signal?.aborted)
|
|
4
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
5
|
+
const encoded = JSON.stringify(body);
|
|
6
|
+
if (Buffer.byteLength(encoded) > 20 * 1024 * 1024)
|
|
7
|
+
throw new ClassifierError("input", "Encoded classifier request exceeds 20 MiB.");
|
|
8
|
+
const controller = new AbortController();
|
|
9
|
+
const abort = () => controller.abort();
|
|
10
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
11
|
+
const timer = setTimeout(() => controller.abort(), route.requestTimeoutMs);
|
|
12
|
+
try {
|
|
13
|
+
const headers = new Headers(route.headers);
|
|
14
|
+
for (const [key, value] of Object.entries(extraHeaders ?? {}))
|
|
15
|
+
headers.set(key, value);
|
|
16
|
+
if (route.api === "microsoft-system-one") {
|
|
17
|
+
headers.set("api-key", apiKey);
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
headers.set("authorization", "Bearer " + apiKey);
|
|
21
|
+
}
|
|
22
|
+
headers.set("content-type", "application/json");
|
|
23
|
+
headers.set("accept", "application/json");
|
|
24
|
+
const response = await fetch(route.baseUrl + "/" + path, {
|
|
25
|
+
method: "POST",
|
|
26
|
+
headers,
|
|
27
|
+
body: encoded,
|
|
28
|
+
signal: controller.signal,
|
|
29
|
+
redirect: "error",
|
|
30
|
+
});
|
|
31
|
+
if (!response.ok) {
|
|
32
|
+
await response.body?.cancel();
|
|
33
|
+
throw new ClassifierError("http", "Classifier request failed (HTTP " +
|
|
34
|
+
response.status +
|
|
35
|
+
"). Check credentials, model, limits and provider availability.", response.status);
|
|
36
|
+
}
|
|
37
|
+
const reader = response.body?.getReader();
|
|
38
|
+
if (!reader)
|
|
39
|
+
throw new ClassifierError("response", "Classifier returned an empty response.");
|
|
40
|
+
const chunks = [];
|
|
41
|
+
let size = 0;
|
|
42
|
+
try {
|
|
43
|
+
while (true) {
|
|
44
|
+
const next = await reader.read();
|
|
45
|
+
if (next.done)
|
|
46
|
+
break;
|
|
47
|
+
size += next.value.length;
|
|
48
|
+
if (size > 1024 * 1024) {
|
|
49
|
+
await reader.cancel();
|
|
50
|
+
throw new ClassifierError("response", "Classifier response exceeds 1 MiB.");
|
|
51
|
+
}
|
|
52
|
+
chunks.push(next.value);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
reader.releaseLock();
|
|
57
|
+
}
|
|
58
|
+
let parsed;
|
|
59
|
+
try {
|
|
60
|
+
parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw new ClassifierError("response", "Classifier returned invalid JSON.");
|
|
64
|
+
}
|
|
65
|
+
const result = { body: parsed };
|
|
66
|
+
const id = response.headers.get("x-request-id") ??
|
|
67
|
+
response.headers.get("request-id");
|
|
68
|
+
if (id && /^[a-zA-Z0-9_.:-]{1,128}$/.test(id))
|
|
69
|
+
result.requestId = id;
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (controller.signal.aborted)
|
|
74
|
+
throw new ClassifierError(signal?.aborted ? "aborted" : "timeout", signal?.aborted
|
|
75
|
+
? "Classification was cancelled."
|
|
76
|
+
: "Classifier request timed out. This request was not retried.");
|
|
77
|
+
if (error instanceof ClassifierError)
|
|
78
|
+
throw error;
|
|
79
|
+
throw new ClassifierError("network", "Classifier service could not be reached. This request was not retried.");
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
signal?.removeEventListener("abort", abort);
|
|
84
|
+
}
|
|
85
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { classify, compareClassifiers } from "./classify.js";
|
|
2
|
+
export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
|
|
3
|
+
export type { Answer, Question, ClassifierResult, ClassifierRoute, ClassifierComparisonEntry, ClassifierComparisonResult, ClassifierSettings, ClassifyParams, CustomProviderSettings, ModelDefinition, ProviderSettings, ApiStyle, } from "./types.js";
|
|
4
|
+
export { ClassifierError } from "./types.js";
|
package/dist/index.js
ADDED
package/dist/inputs.d.ts
ADDED
package/dist/inputs.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { lstat, open, realpath } from "node:fs/promises";
|
|
4
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import sharp from "sharp";
|
|
7
|
+
import { ClassifierError, } from "./types.js";
|
|
8
|
+
import { hasBox } from "./validation.js";
|
|
9
|
+
export async function prepareInput(params, route, cwd, signal) {
|
|
10
|
+
if (params.images?.length && !route.images)
|
|
11
|
+
throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
|
|
12
|
+
if (hasBox(params.questions) && (!route.box || !params.images?.length))
|
|
13
|
+
throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
|
|
14
|
+
const images = [];
|
|
15
|
+
const clef = route.api === "cloudflare-system-one" && route.images;
|
|
16
|
+
const perImageLimit = (clef ? 4 : 5) * 1024 * 1024;
|
|
17
|
+
const totalLimit = (clef ? 8 : 10) * 1024 * 1024;
|
|
18
|
+
if (clef && (params.images?.length ?? 0) > 4)
|
|
19
|
+
throw new ClassifierError("input", "Clef accepts at most four images.");
|
|
20
|
+
let totalBytes = 0;
|
|
21
|
+
for (const path of params.images ?? []) {
|
|
22
|
+
if (signal?.aborted)
|
|
23
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
24
|
+
try {
|
|
25
|
+
if (/^[a-z]+:/i.test(path))
|
|
26
|
+
throw new Error();
|
|
27
|
+
const root = await realpath(cwd);
|
|
28
|
+
const target = resolve(root, path);
|
|
29
|
+
const inside = relative(root, target);
|
|
30
|
+
if (!inside ||
|
|
31
|
+
inside === ".." ||
|
|
32
|
+
inside.startsWith(".." + sep) ||
|
|
33
|
+
isAbsolute(inside))
|
|
34
|
+
throw new Error();
|
|
35
|
+
// Reject symlink components, not just the final image.
|
|
36
|
+
let current = root;
|
|
37
|
+
for (const part of inside.split(sep)) {
|
|
38
|
+
current = resolve(current, part);
|
|
39
|
+
const entry = await lstat(current);
|
|
40
|
+
if (entry.isSymbolicLink() ||
|
|
41
|
+
(current === target && !entry.isFile()) ||
|
|
42
|
+
(current !== target && !entry.isDirectory()))
|
|
43
|
+
throw new Error();
|
|
44
|
+
}
|
|
45
|
+
const canonical = await realpath(target);
|
|
46
|
+
if (canonical !== target)
|
|
47
|
+
throw new Error();
|
|
48
|
+
const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
49
|
+
let bytes;
|
|
50
|
+
try {
|
|
51
|
+
// Validate the actual opened object: checking the path before open is raceable.
|
|
52
|
+
await verifyOpenedPath(file.fd, root, signal);
|
|
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)
|
|
68
|
+
throw new Error();
|
|
69
|
+
bytes = buffer.subarray(0, offset);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
await file.close();
|
|
73
|
+
}
|
|
74
|
+
totalBytes += bytes.length;
|
|
75
|
+
if (totalBytes > totalLimit)
|
|
76
|
+
throw new Error();
|
|
77
|
+
const meta = await sharp(bytes, {
|
|
78
|
+
limitInputPixels: 16_777_216,
|
|
79
|
+
}).metadata();
|
|
80
|
+
if (!meta.width ||
|
|
81
|
+
!meta.height ||
|
|
82
|
+
!["png", "jpeg", "webp"].includes(meta.format ?? "") ||
|
|
83
|
+
(meta.pages ?? 1) > 1)
|
|
84
|
+
throw new Error();
|
|
85
|
+
if (route.api === "system-one") {
|
|
86
|
+
if (meta.format === "webp")
|
|
87
|
+
throw new ClassifierError("input", "Jev image assets accept PNG and JPEG only.");
|
|
88
|
+
const pixels = meta.width * meta.height;
|
|
89
|
+
if (meta.width < 256 ||
|
|
90
|
+
meta.width > 1568 ||
|
|
91
|
+
meta.height < 256 ||
|
|
92
|
+
meta.height > 1568 ||
|
|
93
|
+
pixels < 78_400 ||
|
|
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
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (route.api === "perplexity-decisions" &&
|
|
99
|
+
Math.ceil(meta.width / 32) * Math.ceil(meta.height / 32) > 2048)
|
|
100
|
+
throw new ClassifierError("input", "Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.");
|
|
101
|
+
await decodeImage(bytes, signal);
|
|
102
|
+
images.push({
|
|
103
|
+
data: bytes.toString("base64"),
|
|
104
|
+
mimeType: meta.format === "jpeg"
|
|
105
|
+
? "image/jpeg"
|
|
106
|
+
: meta.format === "png"
|
|
107
|
+
? "image/png"
|
|
108
|
+
: "image/webp",
|
|
109
|
+
width: meta.width,
|
|
110
|
+
height: meta.height,
|
|
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 };
|
|
122
|
+
}
|
|
123
|
+
async function decodeImage(bytes, signal) {
|
|
124
|
+
if (signal?.aborted)
|
|
125
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
126
|
+
// A real output pipeline decodes every pixel and honors libvips' native timeout.
|
|
127
|
+
const decoder = sharp(bytes, {
|
|
128
|
+
limitInputPixels: 16_777_216,
|
|
129
|
+
failOn: "warning",
|
|
130
|
+
})
|
|
131
|
+
.timeout({ seconds: 10 })
|
|
132
|
+
.raw();
|
|
133
|
+
let cancel = () => { };
|
|
134
|
+
let timer;
|
|
135
|
+
try {
|
|
136
|
+
await new Promise((resolve, reject) => {
|
|
137
|
+
cancel = () => {
|
|
138
|
+
decoder.destroy();
|
|
139
|
+
reject(new ClassifierError("aborted", "Classification was cancelled."));
|
|
140
|
+
};
|
|
141
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
142
|
+
timer = setTimeout(() => {
|
|
143
|
+
decoder.destroy();
|
|
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.
|
|
147
|
+
decoder.toBuffer().then(() => resolve(), reject);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
if (timer)
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
signal?.removeEventListener("abort", cancel);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const execFileAsync = promisify(execFile);
|
|
157
|
+
/** Verify containment of the opened descriptor, not a raceable pre-open path. */
|
|
158
|
+
async function verifyOpenedPath(fd, root, signal) {
|
|
159
|
+
let openedPath;
|
|
160
|
+
if (process.platform === "linux") {
|
|
161
|
+
openedPath = await realpath("/proc/self/fd/" + fd);
|
|
162
|
+
}
|
|
163
|
+
else if (process.platform === "darwin") {
|
|
164
|
+
// Node does not expose F_GETPATH; the OS lsof utility queries it for this exact fd.
|
|
165
|
+
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 } : {}),
|
|
169
|
+
});
|
|
170
|
+
const paths = stdout.split("\n").filter((line) => line.startsWith("n"));
|
|
171
|
+
if (paths.length !== 1)
|
|
172
|
+
throw new Error();
|
|
173
|
+
openedPath = paths[0].slice(1);
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
throw new ClassifierError("capability", "Safe local image loading currently supports macOS and Linux only. Text classification remains available.");
|
|
177
|
+
}
|
|
178
|
+
const inside = relative(root, openedPath);
|
|
179
|
+
if (!inside ||
|
|
180
|
+
inside === ".." ||
|
|
181
|
+
inside.startsWith(".." + sep) ||
|
|
182
|
+
isAbsolute(inside))
|
|
183
|
+
throw new Error();
|
|
184
|
+
}
|