@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.
Files changed (46) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +82 -6
  4. package/dist/box-tool.d.ts +26 -0
  5. package/dist/box-tool.js +109 -0
  6. package/dist/box.d.ts +32 -0
  7. package/dist/box.js +148 -0
  8. package/dist/classify.d.ts +3 -0
  9. package/dist/classify.js +1 -1
  10. package/dist/computer-use-state.d.ts +9 -0
  11. package/dist/computer-use-state.js +160 -0
  12. package/dist/computer-use-tool.d.ts +52 -0
  13. package/dist/computer-use-tool.js +78 -0
  14. package/dist/computer-use-types.d.ts +132 -0
  15. package/dist/computer-use-types.js +1 -0
  16. package/dist/computer-use.d.ts +22 -0
  17. package/dist/computer-use.js +223 -0
  18. package/dist/config.js +4 -0
  19. package/dist/extension.d.ts +38 -10
  20. package/dist/extension.js +36 -11
  21. package/dist/image-content.d.ts +12 -0
  22. package/dist/image-content.js +90 -0
  23. package/dist/index.d.ts +8 -1
  24. package/dist/index.js +2 -0
  25. package/dist/inputs.d.ts +9 -2
  26. package/dist/inputs.js +154 -130
  27. package/dist/providers.js +90 -87
  28. package/dist/types.d.ts +30 -12
  29. package/dist/validation.js +63 -38
  30. package/package.json +2 -1
  31. package/src/box-tool.ts +145 -0
  32. package/src/box.ts +253 -0
  33. package/src/choices.ts +2 -1
  34. package/src/classify.ts +4 -2
  35. package/src/computer-use-state.ts +145 -0
  36. package/src/computer-use-tool.ts +76 -0
  37. package/src/computer-use-types.ts +127 -0
  38. package/src/computer-use.ts +216 -0
  39. package/src/config.ts +4 -0
  40. package/src/extension.ts +39 -12
  41. package/src/image-content.ts +77 -0
  42. package/src/index.ts +10 -0
  43. package/src/inputs.ts +163 -185
  44. package/src/providers.ts +92 -105
  45. package/src/types.ts +20 -9
  46. package/src/validation.ts +62 -94
package/src/extension.ts CHANGED
@@ -7,6 +7,8 @@ import {
7
7
  import { Type } from "typebox";
8
8
  import { classify, compareClassifiers } from "./classify.js";
9
9
  import { classifyTree } from "./tree.js";
10
+ import { registerBoxTool } from "./box-tool.js";
11
+ import { registerComputerUseTool } from "./computer-use-tool.js";
10
12
  import {
11
13
  configuredRoutes,
12
14
  listModels,
@@ -16,12 +18,26 @@ import {
16
18
  import { updateProjectClassifierSettings } from "./settings-write.js";
17
19
  import { ClassifierError, userError } from "./types.js";
18
20
 
19
- const shortText = Type.String({ maxLength: 4096 });
21
+ const imageReference = Type.Object(
22
+ { $image: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }) },
23
+ { additionalProperties: false },
24
+ );
25
+ function imageContent(maxLength: number, nonempty = false) {
26
+ return Type.Union([
27
+ Type.String({ maxLength, ...(nonempty ? { minLength: 1 } : {}) }),
28
+ Type.Array(Type.Union([Type.String({ maxLength }), imageReference]), {
29
+ minItems: 1, maxItems: 128,
30
+ description: "Ordered text and explicit {$image:id} references. References require named images; supported placements depend on the route.",
31
+ }),
32
+ ]);
33
+ }
34
+ const shortText = imageContent(4096);
35
+ const instructionContent = imageContent(16384, true);
20
36
  const question = Type.Union([
21
37
  Type.Object(
22
38
  {
23
39
  type: Type.Literal("bool"),
24
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
40
+ instructions: instructionContent,
25
41
  criteria: Type.Optional(
26
42
  Type.Object(
27
43
  { true: Type.Optional(shortText), false: Type.Optional(shortText) },
@@ -34,7 +50,7 @@ const question = Type.Union([
34
50
  Type.Object(
35
51
  {
36
52
  type: Type.Literal("choice"),
37
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
53
+ instructions: instructionContent,
38
54
  criteria: Type.Record(
39
55
  Type.String({ minLength: 1, maxLength: 128 }),
40
56
  shortText,
@@ -46,8 +62,8 @@ const question = Type.Union([
46
62
  Type.Object(
47
63
  {
48
64
  type: Type.Literal("score"),
49
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
50
- criteria: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
65
+ instructions: instructionContent,
66
+ criteria: Type.Array(imageContent(4096, true), {
51
67
  minItems: 2,
52
68
  maxItems: 10,
53
69
  }),
@@ -57,7 +73,7 @@ const question = Type.Union([
57
73
  Type.Object(
58
74
  {
59
75
  type: Type.Literal("box"),
60
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
76
+ instructions: instructionContent,
61
77
  },
62
78
  { additionalProperties: false },
63
79
  ),
@@ -73,7 +89,7 @@ export const classifyParameters = Type.Object(
73
89
  ],
74
90
  {
75
91
  description:
76
- "Text or JSON data to classify. All questions refer to this same state.",
92
+ "Text or JSON data to classify. Use explicit {$image:id} objects to place named images in state on Jev, OpenAI or Perplexity. Other JSON remains data. All questions refer to this same state.",
77
93
  },
78
94
  ),
79
95
  questions: Type.Record(
@@ -82,10 +98,19 @@ export const classifyParameters = Type.Object(
82
98
  { minProperties: 1, maxProperties: 32 },
83
99
  ),
84
100
  images: Type.Optional(
85
- Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
86
- maxItems: 5,
87
- description:
88
- "Local PNG/JPEG/WebP files inside cwd, in order. No URLs, symlinks or inline base64. Requires an image-capable model.",
101
+ Type.Array(Type.Union([
102
+ Type.String({ minLength: 1, maxLength: 4096 }),
103
+ Type.Object({
104
+ id: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
105
+ path: Type.String({ minLength: 1, maxLength: 4096 }),
106
+ }, { additionalProperties: false }),
107
+ Type.Object({
108
+ id: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
109
+ url: Type.String({ minLength: 1, maxLength: 4096 }),
110
+ }, { additionalProperties: false }),
111
+ ]), {
112
+ maxItems: 8,
113
+ description: "Legacy local paths are shared in order. Named {id,path} or {id,url} images must be referenced using {$image:id} in state or supported question content. URLs are OpenAI-only and sent to the provider, never fetched locally. No inline base64 or symlinks. Limits: Perplexity 8 images, Clef 4, others 5.",
89
114
  }),
90
115
  ),
91
116
  },
@@ -273,12 +298,14 @@ export const classifyTreeOutput = Type.Object({
273
298
  });
274
299
 
275
300
  export default function piClassifier(pi: ExtensionAPI): void {
301
+ registerBoxTool(pi);
302
+ registerComputerUseTool(pi);
276
303
  pi.registerTool(
277
304
  defineTool({
278
305
  name: "classify",
279
306
  label: "Classify",
280
307
  description:
281
- "Ask a decision model typed questions about text, JSON and supported local images. Returns bool probabilities, choices with probabilities, or scores, plus reported token usage and estimated USD cost (or an explicit unavailable reason). 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 before any batch has completed; never after uncertainty, refusals, timeouts or network failures. Use /classifier list or status to inspect configuration.",
308
+ "Ask a decision model typed questions about text, JSON and supported images. Legacy image paths are shared; named path/url descriptors require explicit {$image:id} references. Jev supports images in instructions/criteria; OpenAI supports instruction images and hosted URLs. Unsupported placements fail locally. Returns bool probabilities, choices with probabilities, or scores, plus reported token usage and estimated USD cost (or an explicit unavailable reason). 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 before any batch has completed; never after uncertainty, refusals, timeouts or network failures. Use /classifier list or status to inspect configuration.",
282
309
  promptSnippet:
283
310
  "Classify text, JSON or supported images into typed probabilistic decisions.",
284
311
  promptGuidelines: [
@@ -0,0 +1,77 @@
1
+ import { ClassifierError, isRecord, type ImageReference, type PreparedImage, type Question } from "./types.js";
2
+
3
+ export function isImageReference(value: unknown): value is ImageReference {
4
+ return isRecord(value) && Object.hasOwn(value, "$image");
5
+ }
6
+
7
+ /** Only explicit reference objects are special; provider-native-looking user JSON stays data. */
8
+ export function imageReferences(value: unknown): string[] {
9
+ if (isImageReference(value)) return [value.$image];
10
+ if (Array.isArray(value)) return value.flatMap(imageReferences);
11
+ if (isRecord(value)) return Object.values(value).flatMap(imageReferences);
12
+ return [];
13
+ }
14
+
15
+ export function questionImageReferences(questions: Record<string, Question>): string[] {
16
+ return Object.values(questions).flatMap((question) => [
17
+ ...imageReferences(question.instructions),
18
+ ...("criteria" in question && question.criteria ? Object.values(question.criteria).flatMap(imageReferences) : []),
19
+ ]);
20
+ }
21
+
22
+ export function mapImageReferences(value: unknown, image: (id: string) => unknown): unknown {
23
+ if (isImageReference(value)) return image(value.$image);
24
+ if (Array.isArray(value)) return value.map((entry) => mapImageReferences(entry, image));
25
+ if (isRecord(value)) return Object.fromEntries(
26
+ Object.entries(value).map(([key, entry]) => [key, mapImageReferences(entry, image)]),
27
+ );
28
+ return value;
29
+ }
30
+
31
+ export function namedImage(images: PreparedImage[], id: string): PreparedImage {
32
+ const image = images.find((entry) => entry.id === id);
33
+ if (!image) throw new ClassifierError("input", "Unknown named image reference.");
34
+ return image;
35
+ }
36
+
37
+ export function imageUrl(image: PreparedImage): string {
38
+ return "url" in image ? image.url : "data:" + image.mimeType + ";base64," + image.data;
39
+ }
40
+
41
+ /** Preserve JSON punctuation as text, interleaving only explicitly referenced images.
42
+ * Raw user objects never become provider-native content parts.
43
+ */
44
+ export function imageContentParts(
45
+ value: unknown,
46
+ image: (id: string) => unknown,
47
+ ): unknown[] {
48
+ const parts: unknown[] = [];
49
+ let text = "";
50
+ const flush = () => { if (text) { parts.push(text); text = ""; } };
51
+ const visit = (entry: unknown): void => {
52
+ if (isImageReference(entry)) { flush(); parts.push(image(entry.$image)); }
53
+ else if (Array.isArray(entry)) {
54
+ text += "[";
55
+ entry.forEach((child, i) => { if (i) text += ","; visit(child); });
56
+ text += "]";
57
+ } else if (isRecord(entry)) {
58
+ text += "{";
59
+ Object.entries(entry).forEach(([key, child], i) => {
60
+ if (i) text += ",";
61
+ text += JSON.stringify(key) + ":";
62
+ visit(child);
63
+ });
64
+ text += "}";
65
+ } else text += JSON.stringify(entry);
66
+ };
67
+ // Ordered content arrays are convenient for instructions and simple multimodal state.
68
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string" || isImageReference(entry))) {
69
+ for (const entry of value) {
70
+ if (typeof entry === "string") text += entry;
71
+ else { flush(); parts.push(image(entry.$image)); }
72
+ }
73
+ } else if (typeof value === "string") text = value;
74
+ else visit(value);
75
+ flush();
76
+ return parts;
77
+ }
package/src/index.ts CHANGED
@@ -1,9 +1,19 @@
1
1
  export { classify, compareClassifiers } from "./classify.js";
2
+ export type { ClassifyOptions } from "./classify.js";
3
+ export type { MemoryImage } from "./inputs.js";
4
+ export { runComputerUse } from "./computer-use.js";
5
+ export type { ComputerUseOptions } from "./computer-use.js";
6
+ export type { ComputerUseParams, ComputerUseResult, ComputerUseSettings, ComputerControl, ComputerExpectation, DriverCall, DriverReply } from "./computer-use-types.js";
2
7
  export { classifyTree } from "./tree.js";
8
+ export { renderClassifierBox } from "./box.js";
9
+ export type { ClassifierBoxMode, ClassifierBoxEdges, ClassifierBoxPixelBox, ClassifierBoxResult } from "./box.js";
3
10
  export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
4
11
  export type {
5
12
  Answer,
6
13
  Question,
14
+ QuestionContent,
15
+ ImageInput,
16
+ ImageReference,
7
17
  ClassifierResult,
8
18
  ClassifierCost,
9
19
  TokenPricing,
package/src/inputs.ts CHANGED
@@ -8,187 +8,187 @@ import {
8
8
  ClassifierError,
9
9
  type ClassifyParams,
10
10
  type PreparedImage,
11
+ type PreparedLocalImage,
11
12
  type PreparedInput,
12
13
  type ResolvedModel,
13
14
  } from "./types.js";
14
15
  import { hasBox } from "./validation.js";
16
+ import { imageReferences } from "./image-content.js";
17
+
18
+ /** Programmatic image ingress. Never accepted as model-facing tool arguments. */
19
+ export interface MemoryImage {
20
+ bytes: Uint8Array;
21
+ mimeType: "image/png" | "image/jpeg" | "image/webp";
22
+ }
15
23
 
16
24
  export async function prepareInput(
17
25
  params: ClassifyParams,
18
26
  route: ResolvedModel,
19
27
  cwd: string,
20
28
  signal?: AbortSignal,
29
+ memoryImages: readonly MemoryImage[] = [],
21
30
  ): Promise<PreparedInput> {
22
- if (params.images?.length && !route.images)
23
- throw new ClassifierError(
24
- "capability",
25
- "The selected model does not support images, or experimental Jev images are disabled.",
26
- );
27
- if (hasBox(params.questions) && (!route.box || !params.images?.length))
28
- throw new ClassifierError(
29
- "capability",
30
- "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.",
31
- );
32
- const images: PreparedImage[] = [];
31
+ const imageCount = (params.images?.length ?? 0) + memoryImages.length;
32
+ if (imageCount && !route.images)
33
+ throw new ClassifierError("capability", "The selected model does not support images, or experimental Jev images are disabled.");
34
+ if (hasBox(params.questions) && (!route.box || !imageCount))
35
+ throw new ClassifierError("capability", "box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.");
33
36
  const clef = route.api === "cloudflare-system-one" && route.images;
34
- const perImageLimit = (clef ? 4 : 5) * 1024 * 1024;
35
- const totalLimit = (clef ? 8 : 10) * 1024 * 1024;
36
- if (clef && (params.images?.length ?? 0) > 4)
37
- throw new ClassifierError("input", "Clef accepts at most four images.");
38
- let totalBytes = 0;
39
- for (const path of params.images ?? []) {
40
- if (signal?.aborted)
41
- throw new ClassifierError("aborted", "Classification was cancelled.");
42
- try {
43
- if (/^[a-z]+:/i.test(path)) throw new Error();
44
- const root = await realpath(cwd);
45
- const target = resolve(root, path);
46
- const inside = relative(root, target);
47
- if (
48
- !inside ||
49
- inside === ".." ||
50
- inside.startsWith(".." + sep) ||
51
- isAbsolute(inside)
52
- )
53
- throw new Error();
54
- // Reject symlink components, not just the final image.
55
- let current = root;
56
- for (const part of inside.split(sep)) {
57
- current = resolve(current, part);
58
- const entry = await lstat(current);
59
- if (
60
- entry.isSymbolicLink() ||
61
- (current === target && !entry.isFile()) ||
62
- (current !== target && !entry.isDirectory())
63
- )
64
- throw new Error();
65
- }
66
- const canonical = await realpath(target);
67
- if (canonical !== target) throw new Error();
68
- const file = await open(
69
- target,
70
- constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
71
- );
72
- let bytes: Buffer;
37
+ const maxImages = clef ? 4 : route.api === "perplexity-decisions" ? 8 : 5;
38
+ if (imageCount > maxImages)
39
+ throw new ClassifierError("input", "The selected route accepts at most " + maxImages + " images in this package.");
40
+ if (imageReferences(params.state).length && !["system-one", "openai-decisions", "perplexity-decisions"].includes(route.api))
41
+ throw new ClassifierError("capability", "This route does not support explicit image references in state; use shared image paths instead.");
42
+ for (const question of Object.values(params.questions)) {
43
+ if (imageReferences(question.instructions).length && !["system-one", "openai-decisions"].includes(route.api))
44
+ throw new ClassifierError("capability", "Image references in question instructions require Jev or OpenAI Decisions.");
45
+ if ("criteria" in question && question.criteria && Object.values(question.criteria).some((entry) => imageReferences(entry).length) && route.api !== "system-one")
46
+ throw new ClassifierError("capability", "Image references in criteria require a Jev assets-protocol route.");
47
+ }
48
+ // Reject unsupported URL placement before opening any local files.
49
+ for (const source of params.images ?? []) {
50
+ if (typeof source !== "string" && "url" in source) {
51
+ if (route.api !== "openai-decisions")
52
+ throw new ClassifierError("capability", "Hosted image URLs are supported only by OpenAI Decisions routes. No URL was fetched.");
73
53
  try {
74
- // Validate the actual opened object: checking the path before open is raceable.
75
- await verifyOpenedPath(file.fd, root, signal);
76
- const stat = await file.stat();
77
- if (!stat.isFile() || stat.size < 1 || stat.size > perImageLimit)
54
+ const url = new URL(source.url);
55
+ if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.hash)
78
56
  throw new Error();
79
- // Read a bounded number of bytes even if another process grows the file.
80
- const buffer = Buffer.alloc(perImageLimit + 1);
81
- let offset = 0;
82
- while (offset < buffer.length) {
83
- if (signal?.aborted)
84
- throw new ClassifierError(
85
- "aborted",
86
- "Classification was cancelled.",
87
- );
88
- const read = await file.read(
89
- buffer,
90
- offset,
91
- buffer.length - offset,
92
- null,
93
- );
94
- if (!read.bytesRead) break;
95
- offset += read.bytesRead;
96
- }
97
- if (offset > perImageLimit) throw new Error();
98
- bytes = buffer.subarray(0, offset);
99
- } finally {
100
- await file.close();
57
+ } catch {
58
+ throw new ClassifierError("input", "Image URLs must be absolute HTTP(S) URLs without credentials or fragments.");
101
59
  }
102
- totalBytes += bytes.length;
103
- if (totalBytes > totalLimit) throw new Error();
104
- const meta = await sharp(bytes, {
105
- limitInputPixels: 16_777_216,
106
- }).metadata();
107
- if (
108
- !meta.width ||
109
- !meta.height ||
110
- !["png", "jpeg", "webp"].includes(meta.format ?? "") ||
111
- (meta.pages ?? 1) > 1
112
- )
113
- throw new Error();
114
- if (route.api === "system-one") {
115
- if (meta.format === "webp")
116
- throw new ClassifierError(
117
- "input",
118
- "Jev image assets accept PNG and JPEG only.",
119
- );
120
- const pixels = meta.width * meta.height;
121
- if (
122
- meta.width < 256 ||
123
- meta.width > 1568 ||
124
- meta.height < 256 ||
125
- meta.height > 1568 ||
126
- pixels < 78_400 ||
127
- pixels > 2_458_624
128
- ) {
129
- throw new ClassifierError(
130
- "input",
131
- "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.",
132
- );
133
- }
60
+ }
61
+ }
62
+ const images: PreparedImage[] = [];
63
+ let totalBytes = 0;
64
+ const sources = [
65
+ ...(params.images ?? []).map((source) => ({ source })),
66
+ ...memoryImages.map((memory) => ({ memory })),
67
+ ];
68
+ for (const entry of sources) {
69
+ cancelled(signal);
70
+ const maxBytes = (clef ? 4 : 5) * 1024 * 1024;
71
+ let image: PreparedLocalImage;
72
+ let id: string | undefined;
73
+ if ("memory" in entry) {
74
+ image = await prepareImageBytes(entry.memory.bytes, signal, maxBytes, entry.memory.mimeType);
75
+ } else {
76
+ const source = entry.source;
77
+ if (typeof source !== "string" && "url" in source) {
78
+ images.push({ id: source.id, url: source.url });
79
+ continue;
134
80
  }
135
- if (
136
- route.api === "perplexity-decisions" &&
137
- Math.ceil(meta.width / 32) * Math.ceil(meta.height / 32) > 2048
138
- )
139
- throw new ClassifierError(
140
- "input",
141
- "Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.",
142
- );
143
- await decodeImage(bytes, signal);
144
- images.push({
145
- data: bytes.toString("base64"),
146
- mimeType:
147
- meta.format === "jpeg"
148
- ? "image/jpeg"
149
- : meta.format === "png"
150
- ? "image/png"
151
- : "image/webp",
152
- width: meta.width,
153
- height: meta.height,
154
- });
155
- } catch (error) {
156
- if (signal?.aborted)
157
- throw new ClassifierError("aborted", "Classification was cancelled.");
158
- if (error instanceof ClassifierError) throw error;
159
- throw new ClassifierError(
160
- "input",
161
- "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).",
162
- );
81
+ image = await loadLocalImage(typeof source === "string" ? source : source.path, cwd, signal, maxBytes);
82
+ if (typeof source !== "string") id = source.id;
163
83
  }
84
+ totalBytes += Buffer.byteLength(image.data, "base64");
85
+ if (totalBytes > (clef ? 8 : 10) * 1024 * 1024)
86
+ throw new ClassifierError("input", "Images exceed the selected route's total upload byte limit.");
87
+ if (route.api === "system-one") {
88
+ if (image.mimeType === "image/webp")
89
+ throw new ClassifierError("input", "Jev image assets accept PNG and JPEG only.");
90
+ const pixels = image.width * image.height;
91
+ if (image.width < 280 || image.width > 1568 || image.height < 280 || image.height > 1568 || pixels < 78_400 || pixels > 2_458_624)
92
+ throw new ClassifierError("input", "Resize or pad Jev images before sending: each side must be 280–1568 pixels and total area 78400–2458624 pixels. Images are not silently resized.");
93
+ }
94
+ if (route.api === "perplexity-decisions" && Math.ceil(image.width / 32) * Math.ceil(image.height / 32) > 2048)
95
+ throw new ClassifierError("input", "Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.");
96
+ images.push(id === undefined ? image : { ...image, id });
164
97
  }
165
98
  return { state: params.state, questions: params.questions, images };
166
99
  }
167
100
 
101
+ /** Bounded, fully decoded local image; shared by uploads and local box rendering. */
102
+ export async function loadLocalImage(
103
+ path: string,
104
+ cwd: string,
105
+ signal?: AbortSignal,
106
+ maxBytes = 5 * 1024 * 1024,
107
+ ): Promise<PreparedLocalImage> {
108
+ cancelled(signal);
109
+ try {
110
+ if (/^[a-z]+:/i.test(path)) throw new Error();
111
+ const root = await realpath(cwd);
112
+ const target = resolve(root, path);
113
+ const inside = relative(root, target);
114
+ if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside)) throw new Error();
115
+ // Reject symlink components, not just the final image.
116
+ let current = root;
117
+ for (const part of inside.split(sep)) {
118
+ current = resolve(current, part);
119
+ const entry = await lstat(current);
120
+ if (entry.isSymbolicLink() || (current === target && !entry.isFile()) || (current !== target && !entry.isDirectory())) throw new Error();
121
+ }
122
+ if (await realpath(target) !== target) throw new Error();
123
+ const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
124
+ let bytes: Buffer;
125
+ try {
126
+ // Verify the opened object as well: pre-open path checks alone are raceable.
127
+ await verifyOpenedPath(file.fd, root, signal);
128
+ const stat = await file.stat();
129
+ if (!stat.isFile() || stat.size < 1 || stat.size > maxBytes) throw new Error();
130
+ // A bounded read also handles files grown concurrently after stat().
131
+ const buffer = Buffer.alloc(maxBytes + 1);
132
+ let offset = 0;
133
+ while (offset < buffer.length) {
134
+ cancelled(signal);
135
+ const read = await file.read(buffer, offset, buffer.length - offset, null);
136
+ if (!read.bytesRead) break;
137
+ offset += read.bytesRead;
138
+ }
139
+ if (offset > maxBytes) throw new Error();
140
+ bytes = buffer.subarray(0, offset);
141
+ } finally { await file.close(); }
142
+ return await prepareImageBytes(bytes, signal, maxBytes);
143
+ } catch (error) {
144
+ cancelled(signal);
145
+ if (error instanceof ClassifierError) throw error;
146
+ 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.");
147
+ }
148
+ }
149
+
150
+ /** The same full-decode boundary for files and transient Driver captures. */
151
+ async function prepareImageBytes(
152
+ input: Uint8Array,
153
+ signal: AbortSignal | undefined,
154
+ maxBytes: number,
155
+ declaredMime?: MemoryImage["mimeType"],
156
+ ): Promise<PreparedLocalImage> {
157
+ cancelled(signal);
158
+ if (!(input instanceof Uint8Array) || input.byteLength < 1 || input.byteLength > maxBytes)
159
+ throw new ClassifierError("input", "Image bytes exceed the selected route's limit.");
160
+ try {
161
+ const bytes = Buffer.from(input);
162
+ const meta = await sharp(bytes, { limitInputPixels: 16_777_216 }).metadata();
163
+ if (!meta.width || !meta.height || !["png", "jpeg", "webp"].includes(meta.format ?? "") || (meta.pages ?? 1) > 1) throw new Error();
164
+ const mimeType = meta.format === "jpeg" ? "image/jpeg" : meta.format === "png" ? "image/png" : "image/webp";
165
+ if (declaredMime !== undefined && declaredMime !== mimeType) throw new Error();
166
+ await decodeImage(bytes, signal);
167
+ cancelled(signal);
168
+ return { data: bytes.toString("base64"), mimeType, width: meta.width, height: meta.height };
169
+ } catch (error) {
170
+ cancelled(signal);
171
+ if (error instanceof ClassifierError) throw error;
172
+ throw new ClassifierError("input", "Image bytes must decode as a still PNG/JPEG/WebP matching the declared MIME type, within 16 megapixels.");
173
+ }
174
+ }
175
+
176
+ function cancelled(signal?: AbortSignal): void {
177
+ if (signal?.aborted) throw new ClassifierError("aborted", "Classification was cancelled.");
178
+ }
179
+
168
180
  async function decodeImage(bytes: Buffer, signal?: AbortSignal): Promise<void> {
169
- if (signal?.aborted)
170
- throw new ClassifierError("aborted", "Classification was cancelled.");
171
- // A real output pipeline decodes every pixel and honors libvips' native timeout.
172
- const decoder = sharp(bytes, {
173
- limitInputPixels: 16_777_216,
174
- failOn: "warning",
175
- })
176
- .timeout({ seconds: 10 })
177
- .raw();
181
+ cancelled(signal);
182
+ // Output through a raw pipeline decodes every pixel and honors the native timeout.
183
+ const decoder = sharp(bytes, { limitInputPixels: 16_777_216, failOn: "warning" }).timeout({ seconds: 10 }).raw();
178
184
  let cancel = () => {};
179
185
  let timer: ReturnType<typeof setTimeout> | undefined;
180
186
  try {
181
187
  await new Promise<void>((resolve, reject) => {
182
- cancel = () => {
183
- decoder.destroy();
184
- reject(new ClassifierError("aborted", "Classification was cancelled."));
185
- };
188
+ cancel = () => { decoder.destroy(); reject(new ClassifierError("aborted", "Classification was cancelled.")); };
186
189
  signal?.addEventListener("abort", cancel, { once: true });
187
- timer = setTimeout(() => {
188
- decoder.destroy();
189
- reject(new ClassifierError("input", "Image decoding timed out."));
190
- }, 10_000);
191
- // Attach both handlers even after cancellation so the native callback cannot reject unhandled.
190
+ timer = setTimeout(() => { decoder.destroy(); reject(new ClassifierError("input", "Image decoding timed out.")); }, 10_000);
191
+ // Keep a rejection handler attached even after cancellation destroys the pipeline.
192
192
  decoder.toBuffer().then(() => resolve(), reject);
193
193
  });
194
194
  } finally {
@@ -200,40 +200,18 @@ async function decodeImage(bytes: Buffer, signal?: AbortSignal): Promise<void> {
200
200
  const execFileAsync = promisify(execFile);
201
201
 
202
202
  /** Verify containment of the opened descriptor, not a raceable pre-open path. */
203
- export async function verifyOpenedPath(
204
- fd: number,
205
- root: string,
206
- signal?: AbortSignal,
207
- ): Promise<void> {
203
+ export async function verifyOpenedPath(fd: number, root: string, signal?: AbortSignal): Promise<void> {
208
204
  let openedPath: string;
209
- if (process.platform === "linux") {
210
- openedPath = await realpath("/proc/self/fd/" + fd);
211
- } else if (process.platform === "darwin") {
212
- // Node does not expose F_GETPATH; the OS lsof utility queries it for this exact fd.
213
- const { stdout } = await execFileAsync(
214
- "/usr/sbin/lsof",
215
- ["-a", "-p", String(process.pid), "-d", String(fd), "-Fn"],
216
- {
217
- timeout: 3000,
218
- maxBuffer: 8192,
219
- ...(signal ? { signal } : {}),
220
- },
221
- );
205
+ if (process.platform === "linux") openedPath = await realpath("/proc/self/fd/" + fd);
206
+ else if (process.platform === "darwin") {
207
+ // Node does not expose F_GETPATH; the OS utility queries this exact descriptor.
208
+ const { stdout } = await execFileAsync("/usr/sbin/lsof", ["-a", "-p", String(process.pid), "-d", String(fd), "-Fn"], {
209
+ timeout: 3000, maxBuffer: 8192, ...(signal ? { signal } : {}),
210
+ });
222
211
  const paths = stdout.split("\n").filter((line) => line.startsWith("n"));
223
212
  if (paths.length !== 1) throw new Error();
224
213
  openedPath = paths[0]!.slice(1);
225
- } else {
226
- throw new ClassifierError(
227
- "capability",
228
- "Safe local file loading currently supports macOS and Linux only. Inline text/JSON classification remains available.",
229
- );
230
- }
214
+ } else throw new ClassifierError("capability", "Safe local file loading currently supports macOS and Linux only. Inline text/JSON and hosted-image classification remain available.");
231
215
  const inside = relative(root, openedPath);
232
- if (
233
- !inside ||
234
- inside === ".." ||
235
- inside.startsWith(".." + sep) ||
236
- isAbsolute(inside)
237
- )
238
- throw new Error();
216
+ if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside)) throw new Error();
239
217
  }