@abhishek944/pi-classifier 0.2.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 (57) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +268 -8
  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/choices.d.ts +8 -0
  9. package/dist/choices.js +131 -0
  10. package/dist/classification-tree.d.ts +4 -0
  11. package/dist/classification-tree.js +143 -0
  12. package/dist/classify.d.ts +4 -2
  13. package/dist/classify.js +5 -2
  14. package/dist/computer-use-state.d.ts +9 -0
  15. package/dist/computer-use-state.js +160 -0
  16. package/dist/computer-use-tool.d.ts +52 -0
  17. package/dist/computer-use-tool.js +78 -0
  18. package/dist/computer-use-types.d.ts +132 -0
  19. package/dist/computer-use-types.js +1 -0
  20. package/dist/computer-use.d.ts +22 -0
  21. package/dist/computer-use.js +223 -0
  22. package/dist/config.js +44 -0
  23. package/dist/cost.d.ts +8 -0
  24. package/dist/cost.js +202 -0
  25. package/dist/extension.d.ts +164 -9
  26. package/dist/extension.js +164 -14
  27. package/dist/image-content.d.ts +12 -0
  28. package/dist/image-content.js +90 -0
  29. package/dist/index.d.ts +9 -1
  30. package/dist/index.js +3 -0
  31. package/dist/inputs.d.ts +11 -2
  32. package/dist/inputs.js +155 -131
  33. package/dist/providers.js +113 -100
  34. package/dist/tree.d.ts +4 -0
  35. package/dist/tree.js +136 -0
  36. package/dist/types.d.ts +113 -11
  37. package/dist/validation.js +63 -39
  38. package/package.json +2 -1
  39. package/src/box-tool.ts +145 -0
  40. package/src/box.ts +253 -0
  41. package/src/choices.ts +174 -0
  42. package/src/classification-tree.ts +181 -0
  43. package/src/classify.ts +16 -4
  44. package/src/computer-use-state.ts +145 -0
  45. package/src/computer-use-tool.ts +76 -0
  46. package/src/computer-use-types.ts +127 -0
  47. package/src/computer-use.ts +216 -0
  48. package/src/config.ts +55 -0
  49. package/src/cost.ts +250 -0
  50. package/src/extension.ts +191 -15
  51. package/src/image-content.ts +77 -0
  52. package/src/index.ts +18 -0
  53. package/src/inputs.ts +163 -185
  54. package/src/providers.ts +113 -119
  55. package/src/tree.ts +157 -0
  56. package/src/types.ts +117 -10
  57. package/src/validation.ts +62 -95
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
- 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 image loading currently supports macOS and Linux only. Text 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
  }