@abhishek944/pi-classifier 0.3.0 → 0.4.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 +15 -0
- package/COMPUTER_USE.md +117 -0
- package/README.md +82 -6
- package/dist/box-tool.d.ts +26 -0
- package/dist/box-tool.js +109 -0
- package/dist/box.d.ts +32 -0
- package/dist/box.js +148 -0
- package/dist/classify.d.ts +3 -0
- package/dist/classify.js +1 -1
- 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.js +4 -0
- package/dist/extension.d.ts +38 -10
- package/dist/extension.js +36 -11
- package/dist/image-content.d.ts +12 -0
- package/dist/image-content.js +90 -0
- package/dist/index.d.ts +8 -1
- package/dist/index.js +2 -0
- package/dist/inputs.d.ts +9 -2
- package/dist/inputs.js +154 -130
- package/dist/providers.js +90 -87
- package/dist/types.d.ts +30 -12
- package/dist/validation.js +63 -38
- package/package.json +2 -1
- package/src/box-tool.ts +145 -0
- package/src/box.ts +253 -0
- package/src/choices.ts +2 -1
- package/src/classify.ts +4 -2
- 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 +4 -0
- package/src/extension.ts +39 -12
- package/src/image-content.ts +77 -0
- package/src/index.ts +10 -0
- package/src/inputs.ts +163 -185
- package/src/providers.ts +92 -105
- package/src/types.ts +20 -9
- package/src/validation.ts +62 -94
package/dist/inputs.js
CHANGED
|
@@ -6,144 +6,175 @@ import { promisify } from "node:util";
|
|
|
6
6
|
import sharp from "sharp";
|
|
7
7
|
import { ClassifierError, } from "./types.js";
|
|
8
8
|
import { hasBox } from "./validation.js";
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
import { imageReferences } from "./image-content.js";
|
|
10
|
+
export async function prepareInput(params, route, cwd, signal, memoryImages = []) {
|
|
11
|
+
const imageCount = (params.images?.length ?? 0) + memoryImages.length;
|
|
12
|
+
if (imageCount && !route.images)
|
|
11
13
|
throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
|
|
12
|
-
if (hasBox(params.questions) && (!route.box || !
|
|
14
|
+
if (hasBox(params.questions) && (!route.box || !imageCount))
|
|
13
15
|
throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
|
|
14
|
-
const images = [];
|
|
15
16
|
const clef = route.api === "cloudflare-system-one" && route.images;
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
for (const
|
|
22
|
-
if (
|
|
23
|
-
throw new ClassifierError("
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
if (
|
|
31
|
-
|
|
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;
|
|
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.");
|
|
22
|
+
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.");
|
|
27
|
+
}
|
|
28
|
+
// Reject unsupported URL placement before opening any local files.
|
|
29
|
+
for (const source of params.images ?? []) {
|
|
30
|
+
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.");
|
|
50
33
|
try {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const stat = await file.stat();
|
|
54
|
-
if (!stat.isFile() || stat.size < 1 || stat.size > perImageLimit)
|
|
34
|
+
const url = new URL(source.url);
|
|
35
|
+
if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.hash)
|
|
55
36
|
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
37
|
}
|
|
71
|
-
|
|
72
|
-
|
|
38
|
+
catch {
|
|
39
|
+
throw new ClassifierError("input", "Image URLs must be absolute HTTP(S) URLs without credentials or fragments.");
|
|
73
40
|
}
|
|
74
|
-
|
|
75
|
-
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const images = [];
|
|
44
|
+
let totalBytes = 0;
|
|
45
|
+
const sources = [
|
|
46
|
+
...(params.images ?? []).map((source) => ({ source })),
|
|
47
|
+
...memoryImages.map((memory) => ({ memory })),
|
|
48
|
+
];
|
|
49
|
+
for (const entry of sources) {
|
|
50
|
+
cancelled(signal);
|
|
51
|
+
const maxBytes = (clef ? 4 : 5) * 1024 * 1024;
|
|
52
|
+
let image;
|
|
53
|
+
let id;
|
|
54
|
+
if ("memory" in entry) {
|
|
55
|
+
image = await prepareImageBytes(entry.memory.bytes, signal, maxBytes, entry.memory.mimeType);
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const source = entry.source;
|
|
59
|
+
if (typeof source !== "string" && "url" in source) {
|
|
60
|
+
images.push({ id: source.id, url: source.url });
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
image = await loadLocalImage(typeof source === "string" ? source : source.path, cwd, signal, maxBytes);
|
|
64
|
+
if (typeof source !== "string")
|
|
65
|
+
id = source.id;
|
|
66
|
+
}
|
|
67
|
+
totalBytes += Buffer.byteLength(image.data, "base64");
|
|
68
|
+
if (totalBytes > (clef ? 8 : 10) * 1024 * 1024)
|
|
69
|
+
throw new ClassifierError("input", "Images exceed the selected route's total upload byte limit.");
|
|
70
|
+
if (route.api === "system-one") {
|
|
71
|
+
if (image.mimeType === "image/webp")
|
|
72
|
+
throw new ClassifierError("input", "Jev image assets accept PNG and JPEG only.");
|
|
73
|
+
const pixels = image.width * image.height;
|
|
74
|
+
if (image.width < 280 || image.width > 1568 || image.height < 280 || image.height > 1568 || pixels < 78_400 || pixels > 2_458_624)
|
|
75
|
+
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
|
+
}
|
|
77
|
+
if (route.api === "perplexity-decisions" && Math.ceil(image.width / 32) * Math.ceil(image.height / 32) > 2048)
|
|
78
|
+
throw new ClassifierError("input", "Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.");
|
|
79
|
+
images.push(id === undefined ? image : { ...image, id });
|
|
80
|
+
}
|
|
81
|
+
return { state: params.state, questions: params.questions, images };
|
|
82
|
+
}
|
|
83
|
+
/** Bounded, fully decoded local image; shared by uploads and local box rendering. */
|
|
84
|
+
export async function loadLocalImage(path, cwd, signal, maxBytes = 5 * 1024 * 1024) {
|
|
85
|
+
cancelled(signal);
|
|
86
|
+
try {
|
|
87
|
+
if (/^[a-z]+:/i.test(path))
|
|
88
|
+
throw new Error();
|
|
89
|
+
const root = await realpath(cwd);
|
|
90
|
+
const target = resolve(root, path);
|
|
91
|
+
const inside = relative(root, target);
|
|
92
|
+
if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
|
|
93
|
+
throw new Error();
|
|
94
|
+
// Reject symlink components, not just the final image.
|
|
95
|
+
let current = root;
|
|
96
|
+
for (const part of inside.split(sep)) {
|
|
97
|
+
current = resolve(current, part);
|
|
98
|
+
const entry = await lstat(current);
|
|
99
|
+
if (entry.isSymbolicLink() || (current === target && !entry.isFile()) || (current !== target && !entry.isDirectory()))
|
|
76
100
|
throw new Error();
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
101
|
+
}
|
|
102
|
+
if (await realpath(target) !== target)
|
|
103
|
+
throw new Error();
|
|
104
|
+
const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
105
|
+
let bytes;
|
|
106
|
+
try {
|
|
107
|
+
// Verify the opened object as well: pre-open path checks alone are raceable.
|
|
108
|
+
await verifyOpenedPath(file.fd, root, signal);
|
|
109
|
+
const stat = await file.stat();
|
|
110
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > maxBytes)
|
|
84
111
|
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
|
-
}
|
|
112
|
+
// A bounded read also handles files grown concurrently after stat().
|
|
113
|
+
const buffer = Buffer.alloc(maxBytes + 1);
|
|
114
|
+
let offset = 0;
|
|
115
|
+
while (offset < buffer.length) {
|
|
116
|
+
cancelled(signal);
|
|
117
|
+
const read = await file.read(buffer, offset, buffer.length - offset, null);
|
|
118
|
+
if (!read.bytesRead)
|
|
119
|
+
break;
|
|
120
|
+
offset += read.bytesRead;
|
|
97
121
|
}
|
|
98
|
-
if (
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
});
|
|
122
|
+
if (offset > maxBytes)
|
|
123
|
+
throw new Error();
|
|
124
|
+
bytes = buffer.subarray(0, offset);
|
|
112
125
|
}
|
|
113
|
-
|
|
114
|
-
|
|
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).");
|
|
126
|
+
finally {
|
|
127
|
+
await file.close();
|
|
119
128
|
}
|
|
129
|
+
return await prepareImageBytes(bytes, signal, maxBytes);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
cancelled(signal);
|
|
133
|
+
if (error instanceof ClassifierError)
|
|
134
|
+
throw error;
|
|
135
|
+
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.");
|
|
120
136
|
}
|
|
121
|
-
return { state: params.state, questions: params.questions, images };
|
|
122
137
|
}
|
|
123
|
-
|
|
138
|
+
/** The same full-decode boundary for files and transient Driver captures. */
|
|
139
|
+
async function prepareImageBytes(input, signal, maxBytes, declaredMime) {
|
|
140
|
+
cancelled(signal);
|
|
141
|
+
if (!(input instanceof Uint8Array) || input.byteLength < 1 || input.byteLength > maxBytes)
|
|
142
|
+
throw new ClassifierError("input", "Image bytes exceed the selected route's limit.");
|
|
143
|
+
try {
|
|
144
|
+
const bytes = Buffer.from(input);
|
|
145
|
+
const meta = await sharp(bytes, { limitInputPixels: 16_777_216 }).metadata();
|
|
146
|
+
if (!meta.width || !meta.height || !["png", "jpeg", "webp"].includes(meta.format ?? "") || (meta.pages ?? 1) > 1)
|
|
147
|
+
throw new Error();
|
|
148
|
+
const mimeType = meta.format === "jpeg" ? "image/jpeg" : meta.format === "png" ? "image/png" : "image/webp";
|
|
149
|
+
if (declaredMime !== undefined && declaredMime !== mimeType)
|
|
150
|
+
throw new Error();
|
|
151
|
+
await decodeImage(bytes, signal);
|
|
152
|
+
cancelled(signal);
|
|
153
|
+
return { data: bytes.toString("base64"), mimeType, width: meta.width, height: meta.height };
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
cancelled(signal);
|
|
157
|
+
if (error instanceof ClassifierError)
|
|
158
|
+
throw error;
|
|
159
|
+
throw new ClassifierError("input", "Image bytes must decode as a still PNG/JPEG/WebP matching the declared MIME type, within 16 megapixels.");
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function cancelled(signal) {
|
|
124
163
|
if (signal?.aborted)
|
|
125
164
|
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
})
|
|
131
|
-
.timeout({ seconds: 10 })
|
|
132
|
-
.raw();
|
|
165
|
+
}
|
|
166
|
+
async function decodeImage(bytes, signal) {
|
|
167
|
+
cancelled(signal);
|
|
168
|
+
// Output through a raw pipeline decodes every pixel and honors the native timeout.
|
|
169
|
+
const decoder = sharp(bytes, { limitInputPixels: 16_777_216, failOn: "warning" }).timeout({ seconds: 10 }).raw();
|
|
133
170
|
let cancel = () => { };
|
|
134
171
|
let timer;
|
|
135
172
|
try {
|
|
136
173
|
await new Promise((resolve, reject) => {
|
|
137
|
-
cancel = () => {
|
|
138
|
-
decoder.destroy();
|
|
139
|
-
reject(new ClassifierError("aborted", "Classification was cancelled."));
|
|
140
|
-
};
|
|
174
|
+
cancel = () => { decoder.destroy(); reject(new ClassifierError("aborted", "Classification was cancelled.")); };
|
|
141
175
|
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.
|
|
176
|
+
timer = setTimeout(() => { decoder.destroy(); reject(new ClassifierError("input", "Image decoding timed out.")); }, 10_000);
|
|
177
|
+
// Keep a rejection handler attached even after cancellation destroys the pipeline.
|
|
147
178
|
decoder.toBuffer().then(() => resolve(), reject);
|
|
148
179
|
});
|
|
149
180
|
}
|
|
@@ -157,28 +188,21 @@ const execFileAsync = promisify(execFile);
|
|
|
157
188
|
/** Verify containment of the opened descriptor, not a raceable pre-open path. */
|
|
158
189
|
export async function verifyOpenedPath(fd, root, signal) {
|
|
159
190
|
let openedPath;
|
|
160
|
-
if (process.platform === "linux")
|
|
191
|
+
if (process.platform === "linux")
|
|
161
192
|
openedPath = await realpath("/proc/self/fd/" + fd);
|
|
162
|
-
}
|
|
163
193
|
else if (process.platform === "darwin") {
|
|
164
|
-
// Node does not expose F_GETPATH; the OS
|
|
194
|
+
// Node does not expose F_GETPATH; the OS utility queries this exact descriptor.
|
|
165
195
|
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 } : {}),
|
|
196
|
+
timeout: 3000, maxBuffer: 8192, ...(signal ? { signal } : {}),
|
|
169
197
|
});
|
|
170
198
|
const paths = stdout.split("\n").filter((line) => line.startsWith("n"));
|
|
171
199
|
if (paths.length !== 1)
|
|
172
200
|
throw new Error();
|
|
173
201
|
openedPath = paths[0].slice(1);
|
|
174
202
|
}
|
|
175
|
-
else
|
|
176
|
-
throw new ClassifierError("capability", "Safe local file loading currently supports macOS and Linux only. Inline text/JSON classification
|
|
177
|
-
}
|
|
203
|
+
else
|
|
204
|
+
throw new ClassifierError("capability", "Safe local file loading currently supports macOS and Linux only. Inline text/JSON and hosted-image classification remain available.");
|
|
178
205
|
const inside = relative(root, openedPath);
|
|
179
|
-
if (!inside ||
|
|
180
|
-
inside === ".." ||
|
|
181
|
-
inside.startsWith(".." + sep) ||
|
|
182
|
-
isAbsolute(inside))
|
|
206
|
+
if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
|
|
183
207
|
throw new Error();
|
|
184
208
|
}
|
package/dist/providers.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { imageContentParts, imageReferences, imageUrl, mapImageReferences, namedImage, questionImageReferences } from "./image-content.js";
|
|
2
3
|
import { postJson } from "./http.js";
|
|
3
4
|
import { estimateCost, tokenCount } from "./cost.js";
|
|
4
5
|
import { ClassifierError, isRecord, } from "./types.js";
|
|
@@ -93,8 +94,16 @@ function finish(route, answers, rawUsage, requestId) {
|
|
|
93
94
|
result.requestId = requestId;
|
|
94
95
|
return result;
|
|
95
96
|
}
|
|
96
|
-
function
|
|
97
|
-
|
|
97
|
+
function textContent(value) {
|
|
98
|
+
if (typeof value === "string")
|
|
99
|
+
return value;
|
|
100
|
+
if (value.some((part) => typeof part !== "string"))
|
|
101
|
+
throw new ClassifierError("capability", "This content placement does not support images on the selected route.");
|
|
102
|
+
return value.join("");
|
|
103
|
+
}
|
|
104
|
+
function openAiContent(value, input) {
|
|
105
|
+
return imageContentParts(value, (id) => ({ type: "input_image", image_url: imageUrl(namedImage(input.images, id)) }))
|
|
106
|
+
.map((part) => typeof part === "string" ? { type: "input_text", text: part } : part);
|
|
98
107
|
}
|
|
99
108
|
/* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
|
|
100
109
|
function labelProbabilities(label, id, value, labels) {
|
|
@@ -263,54 +272,44 @@ function parseTypedAnswers(label, value, questions) {
|
|
|
263
272
|
function predicateInstructions(question) {
|
|
264
273
|
const meanings = [];
|
|
265
274
|
if (question.criteria?.true)
|
|
266
|
-
meanings.push("True means: " + question.criteria.true);
|
|
275
|
+
meanings.push("True means: " + textContent(question.criteria.true));
|
|
267
276
|
if (question.criteria?.false)
|
|
268
|
-
meanings.push("False means: " + question.criteria.false);
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
277
|
+
meanings.push("False means: " + textContent(question.criteria.false));
|
|
278
|
+
if (meanings.length === 0)
|
|
279
|
+
return question.instructions;
|
|
280
|
+
const suffix = "\n" + meanings.join("\n");
|
|
281
|
+
return typeof question.instructions === "string" ? question.instructions + suffix : [...question.instructions, suffix];
|
|
282
|
+
}
|
|
283
|
+
function openAiQuestion(id, question, input) {
|
|
284
|
+
const instructions = question.type === "bool" ? predicateInstructions(question) : question.instructions;
|
|
285
|
+
const wireInstructions = typeof instructions === "string" ? instructions : openAiContent(instructions, input);
|
|
274
286
|
if (question.type === "bool")
|
|
287
|
+
return { type: "predicate", name: id, instructions: wireInstructions };
|
|
288
|
+
if (question.type === "choice")
|
|
275
289
|
return {
|
|
276
|
-
type: "
|
|
277
|
-
|
|
278
|
-
instructions: predicateInstructions(question),
|
|
279
|
-
};
|
|
280
|
-
if (question.type === "choice") {
|
|
281
|
-
return {
|
|
282
|
-
type: "choice",
|
|
283
|
-
name: id,
|
|
284
|
-
instructions: question.instructions,
|
|
285
|
-
choices: Object.entries(question.criteria).map(([value, description]) => ({ value, description })),
|
|
290
|
+
type: "choice", name: id, instructions: wireInstructions,
|
|
291
|
+
choices: Object.entries(question.criteria).map(([value, description]) => ({ value, description: textContent(description) })),
|
|
286
292
|
};
|
|
287
|
-
|
|
288
|
-
if (question.type === "score") {
|
|
293
|
+
if (question.type === "score")
|
|
289
294
|
return {
|
|
290
|
-
type: "score",
|
|
291
|
-
|
|
292
|
-
instructions: question.instructions,
|
|
293
|
-
levels: question.criteria.map((label) => ({ label })),
|
|
295
|
+
type: "score", name: id, instructions: wireInstructions,
|
|
296
|
+
levels: question.criteria.map((label) => ({ label: textContent(label) })),
|
|
294
297
|
};
|
|
295
|
-
}
|
|
296
298
|
throw unsupportedBox();
|
|
297
299
|
}
|
|
298
300
|
function openAiInput(input) {
|
|
299
301
|
const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
|
|
300
|
-
|
|
302
|
+
const shared = input.images.filter((image) => image.id === undefined);
|
|
303
|
+
const references = imageReferences(input.state);
|
|
304
|
+
if (shared.length === 0 && references.length === 0)
|
|
301
305
|
return text;
|
|
302
|
-
return [
|
|
303
|
-
{
|
|
306
|
+
return [{
|
|
304
307
|
role: "user",
|
|
305
308
|
content: [
|
|
306
|
-
{ type: "input_text", text },
|
|
307
|
-
...
|
|
308
|
-
type: "input_image",
|
|
309
|
-
image_url: dataUrl(image),
|
|
310
|
-
})),
|
|
309
|
+
...(references.length ? openAiContent(input.state, input) : [{ type: "input_text", text }]),
|
|
310
|
+
...shared.map((image) => ({ type: "input_image", image_url: imageUrl(image) })),
|
|
311
311
|
],
|
|
312
|
-
}
|
|
313
|
-
];
|
|
312
|
+
}];
|
|
314
313
|
}
|
|
315
314
|
function openAiChoiceProbabilities(label, id, value, labels) {
|
|
316
315
|
if (!Array.isArray(value))
|
|
@@ -416,7 +415,7 @@ function parseOpenAiAnswers(label, value, questions) {
|
|
|
416
415
|
return answers;
|
|
417
416
|
}
|
|
418
417
|
async function classifyOpenAi(route, input, apiKey, signal) {
|
|
419
|
-
const questions = Object.entries(input.questions).map(([id, question]) => openAiQuestion(id, question));
|
|
418
|
+
const questions = Object.entries(input.questions).map(([id, question]) => openAiQuestion(id, question, input));
|
|
420
419
|
const { body, requestId } = await postJson(route, "decisions", {
|
|
421
420
|
model: route.model,
|
|
422
421
|
input: openAiInput(input),
|
|
@@ -427,54 +426,41 @@ async function classifyOpenAi(route, input, apiKey, signal) {
|
|
|
427
426
|
return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), body.usage, requestId);
|
|
428
427
|
}
|
|
429
428
|
/* Perplexity Decisions ---------------------------------------------------- */
|
|
430
|
-
function systemOneQuestions(questions, allowBox) {
|
|
431
|
-
// Question IDs may be "__proto__", so the wire map is collected without a prototype.
|
|
429
|
+
function systemOneQuestions(questions, allowBox, content = textContent) {
|
|
432
430
|
const result = Object.create(null);
|
|
433
431
|
for (const [id, question] of Object.entries(questions)) {
|
|
434
|
-
if (question.type === "
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
if (question.criteria !== undefined)
|
|
440
|
-
wire.criteria = question.criteria;
|
|
441
|
-
result[id] = wire;
|
|
442
|
-
}
|
|
443
|
-
else if (question.type === "choice") {
|
|
444
|
-
result[id] = {
|
|
445
|
-
type: "choice",
|
|
446
|
-
instructions: question.instructions,
|
|
447
|
-
criteria: question.criteria,
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
else if (question.type === "score") {
|
|
451
|
-
result[id] = {
|
|
452
|
-
type: "score",
|
|
453
|
-
instructions: question.instructions,
|
|
454
|
-
criteria: question.criteria,
|
|
455
|
-
};
|
|
456
|
-
}
|
|
457
|
-
else if (allowBox) {
|
|
458
|
-
result[id] = { type: "box", instructions: question.instructions };
|
|
459
|
-
}
|
|
460
|
-
else {
|
|
461
|
-
throw unsupportedBox();
|
|
432
|
+
if (question.type === "box") {
|
|
433
|
+
if (!allowBox)
|
|
434
|
+
throw unsupportedBox();
|
|
435
|
+
result[id] = { type: "box", instructions: content(question.instructions) };
|
|
436
|
+
continue;
|
|
462
437
|
}
|
|
438
|
+
const wire = {
|
|
439
|
+
type: question.type === "bool" ? "noul" : question.type,
|
|
440
|
+
instructions: content(question.instructions),
|
|
441
|
+
};
|
|
442
|
+
if (question.type === "score")
|
|
443
|
+
wire.criteria = question.criteria.map(content);
|
|
444
|
+
else if (question.criteria !== undefined)
|
|
445
|
+
wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
|
|
446
|
+
result[id] = wire;
|
|
463
447
|
}
|
|
464
448
|
return result;
|
|
465
449
|
}
|
|
466
450
|
function perplexityState(input) {
|
|
467
|
-
//
|
|
468
|
-
// only locally validated images may become provider-native image parts.
|
|
451
|
+
// Only explicit references become native image parts; other JSON stays text.
|
|
469
452
|
const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
|
|
470
|
-
|
|
453
|
+
const shared = input.images.filter((image) => image.id === undefined);
|
|
454
|
+
const references = imageReferences(input.state);
|
|
455
|
+
if (shared.length + references.length > 8)
|
|
456
|
+
throw new ClassifierError("input", "Perplexity accepts at most eight image occurrences per question.");
|
|
457
|
+
if (shared.length === 0 && references.length === 0)
|
|
471
458
|
return text;
|
|
472
459
|
return [
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
})),
|
|
460
|
+
...(references.length ? imageContentParts(input.state, (id) => ({
|
|
461
|
+
type: "image_url", image_url: { url: imageUrl(namedImage(input.images, id)) },
|
|
462
|
+
})) : [text]),
|
|
463
|
+
...shared.map((image) => ({ type: "image_url", image_url: { url: imageUrl(image) } })),
|
|
478
464
|
];
|
|
479
465
|
}
|
|
480
466
|
async function classifyPerplexity(route, input, apiKey, signal) {
|
|
@@ -532,24 +518,40 @@ function withImageRefs(state, refs) {
|
|
|
532
518
|
}
|
|
533
519
|
async function classifySystemOne(route, input, apiKey, signal) {
|
|
534
520
|
const assets = Object.create(null);
|
|
535
|
-
const
|
|
521
|
+
const sharedRefs = [];
|
|
522
|
+
const namedRefs = new Map();
|
|
523
|
+
const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
|
|
536
524
|
for (const image of input.images) {
|
|
525
|
+
// Batching can remove a question or a criterion. Jev rejects unused assets.
|
|
526
|
+
if (image.id !== undefined && !used.has(image.id))
|
|
527
|
+
continue;
|
|
528
|
+
if ("url" in image)
|
|
529
|
+
throw new ClassifierError("capability", "Jev assets require local images.");
|
|
537
530
|
const ref = randomUUID();
|
|
538
|
-
|
|
531
|
+
if (image.id === undefined)
|
|
532
|
+
sharedRefs.push(ref);
|
|
533
|
+
else
|
|
534
|
+
namedRefs.set(image.id, ref);
|
|
539
535
|
assets[ref] = {
|
|
540
|
-
type: "image",
|
|
541
|
-
format: image.mimeType === "image/png" ? "png" : "jpg",
|
|
536
|
+
type: "image", format: image.mimeType === "image/png" ? "png" : "jpg",
|
|
542
537
|
data_base64: image.data,
|
|
543
538
|
};
|
|
544
539
|
}
|
|
540
|
+
const reference = (id) => {
|
|
541
|
+
const ref = namedRefs.get(id);
|
|
542
|
+
if (!ref)
|
|
543
|
+
throw new ClassifierError("input", "Unknown named image reference.");
|
|
544
|
+
return ref;
|
|
545
|
+
};
|
|
546
|
+
const state = mapImageReferences(input.state, reference);
|
|
545
547
|
const payload = {
|
|
546
548
|
model: route.model,
|
|
547
|
-
state:
|
|
548
|
-
questions: systemOneQuestions(input.questions, true),
|
|
549
|
+
state: sharedRefs.length ? withImageRefs(state, sharedRefs) : state,
|
|
550
|
+
questions: systemOneQuestions(input.questions, true, (value) => mapImageReferences(value, reference)),
|
|
549
551
|
};
|
|
550
|
-
if (
|
|
552
|
+
if (Object.keys(assets).length > 0)
|
|
551
553
|
payload.assets = assets;
|
|
552
|
-
const experimentalHeader =
|
|
554
|
+
const experimentalHeader = Object.keys(assets).length > 0 ||
|
|
553
555
|
Object.values(input.questions).some((question) => question.type === "box");
|
|
554
556
|
const extraHeaders = experimentalHeader
|
|
555
557
|
? { "TypeSafe-Danger-Zone-Images": "true" }
|
|
@@ -594,10 +596,11 @@ async function classifyCloudflare(route, input, apiKey, signal) {
|
|
|
594
596
|
questions: systemOneQuestions(input.questions, false),
|
|
595
597
|
};
|
|
596
598
|
if (input.images.length > 0) {
|
|
597
|
-
payload.images = input.images.map((image) =>
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
599
|
+
payload.images = input.images.map((image) => {
|
|
600
|
+
if ("url" in image)
|
|
601
|
+
throw new ClassifierError("capability", "Clef requires local images.");
|
|
602
|
+
return { content_type: image.mimeType, base64: image.data };
|
|
603
|
+
});
|
|
601
604
|
}
|
|
602
605
|
path = "run/" + route.model;
|
|
603
606
|
}
|