@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/box.ts ADDED
@@ -0,0 +1,253 @@
1
+ import sharp, { type Sharp } from "sharp";
2
+ import { loadLocalImage } from "./inputs.js";
3
+ import { ClassifierError, isRecord } from "./types.js";
4
+
5
+ export type ClassifierBoxMode = "overlay" | "crop";
6
+
7
+ export type ClassifierBoxEdges = {
8
+ top: number;
9
+ bottom: number;
10
+ left: number;
11
+ right: number;
12
+ };
13
+
14
+ /** Pixel coordinates in the source image. */
15
+ export type ClassifierBoxPixelBox = {
16
+ left: number;
17
+ top: number;
18
+ width: number;
19
+ height: number;
20
+ };
21
+
22
+ export type ClassifierBoxResult = {
23
+ data: string;
24
+ mimeType: "image/png";
25
+ width: number;
26
+ height: number;
27
+ pixelBox: ClassifierBoxPixelBox;
28
+ mode: ClassifierBoxMode;
29
+ };
30
+
31
+ type ClassifierBoxParams = {
32
+ image: string;
33
+ box: ClassifierBoxEdges;
34
+ mode: ClassifierBoxMode;
35
+ };
36
+
37
+ const MAX_PIXELS = 16_777_216;
38
+ const MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
39
+ const RENDER_TIMEOUT_SECONDS = 10;
40
+ const RENDER_TIMEOUT_MS = RENDER_TIMEOUT_SECONDS * 1000;
41
+ const MAX_PATH_LENGTH = 4096;
42
+
43
+ /**
44
+ * Render a normalized box on a local image, or crop to it, without a provider
45
+ * request or disk write. File containment, byte limits and full decoding are
46
+ * owned by loadLocalImage; this module owns coordinates, rendering and output
47
+ * limits.
48
+ */
49
+ export async function renderClassifierBox(
50
+ params: unknown,
51
+ options: { cwd: string; signal?: AbortSignal },
52
+ ): Promise<ClassifierBoxResult> {
53
+ cancelled(options.signal);
54
+ const parsed = validateBoxParams(params);
55
+ const image = await loadLocalImage(
56
+ parsed.image,
57
+ options.cwd,
58
+ options.signal,
59
+ );
60
+ cancelled(options.signal);
61
+ const pixelBox = toPixelBox(parsed.box, image.width, image.height);
62
+
63
+ let rendered: { data: Buffer; width: number; height: number };
64
+ try {
65
+ const source = sharp(Buffer.from(image.data, "base64"), {
66
+ limitInputPixels: MAX_PIXELS,
67
+ failOn: "warning",
68
+ }).timeout({ seconds: RENDER_TIMEOUT_SECONDS });
69
+ rendered =
70
+ parsed.mode === "crop"
71
+ ? await renderPng(source.extract(pixelBox), options.signal)
72
+ : await renderPng(
73
+ source.composite([
74
+ {
75
+ input: Buffer.from(
76
+ overlaySvg(image.width, image.height, pixelBox),
77
+ ),
78
+ top: 0,
79
+ left: 0,
80
+ },
81
+ ]),
82
+ options.signal,
83
+ );
84
+ } catch (error) {
85
+ cancelled(options.signal);
86
+ if (error instanceof ClassifierError) throw error;
87
+ if (error instanceof Error && /time(d)?\s*out/i.test(error.message))
88
+ throw new ClassifierError("input", "Box rendering timed out.");
89
+ throw new ClassifierError(
90
+ "input",
91
+ "Could not render the box image. Use a non-animated PNG/JPEG/WebP inside cwd and a valid box.",
92
+ );
93
+ }
94
+ cancelled(options.signal);
95
+ if (rendered.data.length > MAX_OUTPUT_BYTES)
96
+ throw new ClassifierError(
97
+ "input",
98
+ "The box output PNG is larger than 10 MiB. Use crop or a smaller region.",
99
+ );
100
+ return {
101
+ data: rendered.data.toString("base64"),
102
+ mimeType: "image/png",
103
+ width: rendered.width,
104
+ height: rendered.height,
105
+ pixelBox,
106
+ mode: parsed.mode,
107
+ };
108
+ }
109
+
110
+ function validateBoxParams(value: unknown): ClassifierBoxParams {
111
+ if (
112
+ !isRecord(value) ||
113
+ Object.keys(value).some((key) => !["image", "box", "mode"].includes(key))
114
+ )
115
+ invalid("Expected image, box and optional mode; unknown fields are rejected.");
116
+ const image = value.image;
117
+ if (
118
+ typeof image !== "string" ||
119
+ !image.trim() ||
120
+ image.length > MAX_PATH_LENGTH
121
+ )
122
+ invalid("image must be a local PNG/JPEG/WebP path inside cwd.");
123
+ const candidate = value.box;
124
+ if (
125
+ !isRecord(candidate) ||
126
+ Object.keys(candidate).some(
127
+ (key) => !["top", "bottom", "left", "right"].includes(key),
128
+ )
129
+ )
130
+ invalid("box must contain only top, bottom, left and right.");
131
+ const { top, bottom, left, right } = candidate;
132
+ if (
133
+ !isNormalized(top) ||
134
+ !isNormalized(bottom) ||
135
+ !isNormalized(left) ||
136
+ !isNormalized(right)
137
+ )
138
+ invalid(
139
+ "box edges must be finite normalized numbers between 0 and 1.",
140
+ );
141
+ if (top >= bottom || left >= right)
142
+ invalid("box must have top < bottom and left < right.");
143
+ const mode = value.mode ?? "overlay";
144
+ if (mode !== "overlay" && mode !== "crop")
145
+ invalid("mode must be overlay or crop.");
146
+ return { image, box: { top, bottom, left, right }, mode };
147
+ }
148
+
149
+ function isNormalized(value: unknown): value is number {
150
+ return (
151
+ typeof value === "number" &&
152
+ Number.isFinite(value) &&
153
+ value >= 0 &&
154
+ value <= 1
155
+ );
156
+ }
157
+
158
+ /** Floor/ceil edges, then clamp to the source so the region always has pixels. */
159
+ function toPixelBox(
160
+ box: ClassifierBoxEdges,
161
+ width: number,
162
+ height: number,
163
+ ): ClassifierBoxPixelBox {
164
+ const left = Math.min(Math.max(Math.floor(box.left * width), 0), width - 1);
165
+ const top = Math.min(Math.max(Math.floor(box.top * height), 0), height - 1);
166
+ const right = Math.min(
167
+ Math.max(Math.ceil(box.right * width), left + 1),
168
+ width,
169
+ );
170
+ const bottom = Math.min(
171
+ Math.max(Math.ceil(box.bottom * height), top + 1),
172
+ height,
173
+ );
174
+ return { left, top, width: right - left, height: bottom - top };
175
+ }
176
+
177
+ /** Fixed rectangle built only from computed integers, so no caller text enters the SVG. */
178
+ function overlaySvg(
179
+ width: number,
180
+ height: number,
181
+ box: ClassifierBoxPixelBox,
182
+ ): string {
183
+ const stroke = Math.max(
184
+ 2,
185
+ Math.min(8, Math.round(Math.min(width, height) / 200)),
186
+ );
187
+ const inset = Math.floor(stroke / 2);
188
+ const insetFits = box.width > inset * 2 && box.height > inset * 2;
189
+ const x = insetFits ? box.left + inset : box.left;
190
+ const y = insetFits ? box.top + inset : box.top;
191
+ const rectWidth = Math.max(1, box.width - (insetFits ? inset * 2 : 0));
192
+ const rectHeight = Math.max(1, box.height - (insetFits ? inset * 2 : 0));
193
+ return (
194
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
195
+ `<rect x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}" fill="none" stroke="#ff2d55" stroke-width="${stroke}"/>` +
196
+ `</svg>`
197
+ );
198
+ }
199
+
200
+ async function renderPng(
201
+ pipeline: Sharp,
202
+ signal?: AbortSignal,
203
+ ): Promise<{ data: Buffer; width: number; height: number }> {
204
+ cancelled(signal);
205
+ let cancel = () => {};
206
+ let timer: ReturnType<typeof setTimeout> | undefined;
207
+ try {
208
+ return await new Promise<{ data: Buffer; width: number; height: number }>(
209
+ (resolve, reject) => {
210
+ let settled = false;
211
+ const settle = (action: () => void) => {
212
+ if (settled) return;
213
+ settled = true;
214
+ action();
215
+ };
216
+ cancel = () => {
217
+ pipeline.destroy();
218
+ settle(() =>
219
+ reject(
220
+ new ClassifierError("aborted", "Box rendering was cancelled."),
221
+ ),
222
+ );
223
+ };
224
+ signal?.addEventListener("abort", cancel, { once: true });
225
+ timer = setTimeout(() => {
226
+ pipeline.destroy();
227
+ settle(() =>
228
+ reject(new ClassifierError("input", "Box rendering timed out.")),
229
+ );
230
+ }, RENDER_TIMEOUT_MS);
231
+ pipeline.png().toBuffer({ resolveWithObject: true }).then(
232
+ ({ data, info }) =>
233
+ settle(() =>
234
+ resolve({ data, width: info.width, height: info.height }),
235
+ ),
236
+ (error: unknown) => settle(() => reject(error)),
237
+ );
238
+ },
239
+ );
240
+ } finally {
241
+ if (timer) clearTimeout(timer);
242
+ signal?.removeEventListener("abort", cancel);
243
+ }
244
+ }
245
+
246
+ function invalid(message: string): never {
247
+ throw new ClassifierError("input", message);
248
+ }
249
+
250
+ function cancelled(signal?: AbortSignal): void {
251
+ if (signal?.aborted)
252
+ throw new ClassifierError("aborted", "Box rendering was cancelled.");
253
+ }
package/src/choices.ts ADDED
@@ -0,0 +1,174 @@
1
+ import { sumCost, sumUsage } from "./cost.js";
2
+ import {
3
+ ClassifierError,
4
+ type Answer,
5
+ type ClassifierCost,
6
+ type ClassifierResult,
7
+ type ClassifierSettings,
8
+ type PreparedInput,
9
+ type Question,
10
+ type QuestionContent,
11
+ type ResolvedModel,
12
+ } from "./types.js";
13
+
14
+ export type ChoicePolicy = { none: boolean; batch: boolean };
15
+
16
+ export function choicePolicy(settings: ClassifierSettings): ChoicePolicy {
17
+ for (const key of ["none_of_above_choice", "remove_choice_limits"] as const) {
18
+ if (settings[key] !== undefined && typeof settings[key] !== "boolean")
19
+ throw new ClassifierError("configuration", key + " must be a boolean.");
20
+ }
21
+ const none = settings.none_of_above_choice === true;
22
+ const batch = settings.remove_choice_limits === true;
23
+ if (batch && !none)
24
+ throw new ClassifierError(
25
+ "configuration",
26
+ "remove_choice_limits requires none_of_above_choice: true. No classifier request was sent.",
27
+ );
28
+ return { none, batch };
29
+ }
30
+
31
+ type ChoicePlan = {
32
+ question: Extract<Question, { type: "choice" }>;
33
+ entries: [string, QuestionContent][];
34
+ offset: number;
35
+ sentinel: string;
36
+ };
37
+
38
+ const NONE_DESCRIPTION =
39
+ "None of the other options in this question applies to the supplied state. Select this only when every listed real option is unsuitable.";
40
+
41
+ /** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
42
+ export async function executeChoices(
43
+ input: PreparedInput,
44
+ route: ResolvedModel,
45
+ policy: ChoicePolicy,
46
+ call: (questions: Record<string, Question>) => Promise<ClassifierResult>,
47
+ signal?: AbortSignal,
48
+ ): Promise<ClassifierResult> {
49
+ const plans = new Map<string, ChoicePlan>();
50
+ for (const [id, question] of Object.entries(input.questions)) {
51
+ if (question.type !== "choice") continue;
52
+ const entries = Object.entries(question.criteria);
53
+ if (policy.batch && route.maxChoices === undefined)
54
+ throw new ClassifierError(
55
+ "configuration",
56
+ "Automatic choice batching needs a verified provider limit. Set providers.<id>.maxChoices (or customProviders.<id>.maxChoices) for this endpoint. No classifier request was sent.",
57
+ );
58
+ const size = entries.length + (policy.none ? 1 : 0);
59
+ if (
60
+ !policy.batch &&
61
+ route.maxChoices !== undefined &&
62
+ size > route.maxChoices
63
+ )
64
+ throw new ClassifierError(
65
+ "input",
66
+ "Choice question " + id + " exceeds the selected provider's " +
67
+ route.maxChoices + " options per request" +
68
+ (policy.none ? " (including NONE OF THE ABOVE)" : "") +
69
+ ". Enable both none_of_above_choice and remove_choice_limits to batch choices, or reduce the list. No classifier request was sent.",
70
+ );
71
+ let sentinel = "__pi_none_of_above";
72
+ let suffix = 0;
73
+ while (Object.hasOwn(question.criteria, sentinel))
74
+ sentinel = "__pi_none_of_above_" + ++suffix;
75
+ plans.set(id, { question, entries, offset: 0, sentinel });
76
+ }
77
+ if (!policy.none || plans.size === 0) return call(input.questions);
78
+
79
+ const answers = Object.create(null) as Record<string, Answer>;
80
+ let calls = 0;
81
+ let last: ClassifierResult | undefined;
82
+ let usage: ClassifierResult["usage"];
83
+ let cost: ClassifierCost | undefined;
84
+ while (plans.size > 0) {
85
+ if (signal?.aborted)
86
+ throw new ClassifierError("aborted", "Classification was cancelled.");
87
+ const questions = Object.create(null) as Record<string, Question>;
88
+ // A bool/score/box is evaluated once, not charged again for later choice batches.
89
+ if (calls === 0) {
90
+ for (const [id, question] of Object.entries(input.questions))
91
+ if (question.type !== "choice") questions[id] = question;
92
+ }
93
+ for (const [id, plan] of plans) {
94
+ const capacity =
95
+ route.maxChoices === undefined
96
+ ? plan.entries.length
97
+ : route.maxChoices - 1;
98
+ const batch = plan.entries.slice(plan.offset, plan.offset + capacity);
99
+ plan.offset += batch.length;
100
+ questions[id] = {
101
+ ...plan.question,
102
+ criteria: Object.fromEntries([...batch, [plan.sentinel, NONE_DESCRIPTION]]),
103
+ };
104
+ }
105
+ let result: ClassifierResult;
106
+ try {
107
+ result = await call(questions);
108
+ } catch (error) {
109
+ // Never replay completed batches on another billing route after a later throttling/auth error.
110
+ if (
111
+ calls > 0 &&
112
+ error instanceof ClassifierError &&
113
+ error.code === "http" &&
114
+ [401, 404, 429].includes(error.httpStatus ?? 0)
115
+ )
116
+ throw new ClassifierError(
117
+ "partial_classification",
118
+ "Choice batching stopped after " + calls +
119
+ " completed provider request(s). No fallback was attempted after partial completion; completed requests may be billed.",
120
+ );
121
+ throw error;
122
+ }
123
+ usage = calls === 0 ? result.usage : sumUsage(usage, result.usage);
124
+ cost = cost === undefined ? result.cost : sumCost(cost, result.cost);
125
+ calls++;
126
+ last = result;
127
+ for (const [id, answer] of Object.entries(result.answers)) {
128
+ const plan = plans.get(id);
129
+ if (!plan) {
130
+ answers[id] = answer;
131
+ continue;
132
+ }
133
+ if (answer.type !== "choice") {
134
+ answers[id] = answer;
135
+ plans.delete(id);
136
+ continue;
137
+ }
138
+ const none = answer.probabilities[plan.sentinel]!;
139
+ const real = Object.entries(answer.probabilities).filter(
140
+ ([label]) => label !== plan.sentinel,
141
+ );
142
+ const maximum = Math.max(...real.map(([, probability]) => probability));
143
+ if (none > maximum) {
144
+ if (plan.offset < plan.entries.length) continue;
145
+ answers[id] = { type: "no_match" };
146
+ } else if (
147
+ none === maximum || real.filter(([, p]) => p === maximum).length !== 1
148
+ ) {
149
+ answers[id] = { type: "ambiguous" };
150
+ } else {
151
+ answers[id] = {
152
+ ...answer,
153
+ choice: real.find(([, p]) => p === maximum)![0],
154
+ probabilities: Object.fromEntries(real),
155
+ probabilityScope: "batch",
156
+ noneOfAboveProbability: none,
157
+ };
158
+ }
159
+ plans.delete(id);
160
+ }
161
+ }
162
+ // Validated inputs always contain questions; this loop executes at least once.
163
+ const combined: ClassifierResult = {
164
+ provider: last!.provider,
165
+ model: last!.model,
166
+ answers,
167
+ providerCalls: calls,
168
+ cost: cost!,
169
+ };
170
+ if (usage !== undefined) combined.usage = usage;
171
+ if (calls === 1 && last!.requestId !== undefined)
172
+ combined.requestId = last!.requestId;
173
+ return combined;
174
+ }
@@ -0,0 +1,181 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, realpath } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { verifyOpenedPath } from "./inputs.js";
5
+ import {
6
+ ClassifierError,
7
+ isRecord,
8
+ type ClassifyTreeParams,
9
+ type ClassificationTree,
10
+ type ClassificationTreeNode,
11
+ } from "./types.js";
12
+ import { validateParams } from "./validation.js";
13
+
14
+ const MAX_TREE_BYTES = 2 * 1024 * 1024;
15
+ const MAX_DEPTH = 32;
16
+
17
+ function invalid(message: string): never {
18
+ throw new ClassifierError("input", message);
19
+ }
20
+
21
+ export async function loadTreeInput(
22
+ value: unknown,
23
+ cwd: string,
24
+ signal?: AbortSignal,
25
+ ): Promise<Omit<ClassifyTreeParams, "tree"> & { tree: ClassificationTree }> {
26
+ cancelled(signal);
27
+ if (
28
+ !isRecord(value) ||
29
+ Object.keys(value).some(
30
+ (key) => !["state", "tree", "instructions", "images"].includes(key),
31
+ )
32
+ )
33
+ invalid(
34
+ "Expected state, tree and optional instructions/images; the route is selected in settings.",
35
+ );
36
+ if (
37
+ value.instructions !== undefined &&
38
+ (typeof value.instructions !== "string" ||
39
+ !value.instructions.trim() || value.instructions.length > 8192)
40
+ )
41
+ invalid("Tree instructions must be a non-empty string of at most 8192 characters.");
42
+ // Reuse existing state/image-path validation without making a provider request.
43
+ const base = validateParams({
44
+ state: value.state,
45
+ questions: { tree: { type: "bool", instructions: "Validate tree input." } },
46
+ ...(value.images !== undefined ? { images: value.images } : {}),
47
+ });
48
+ const raw =
49
+ typeof value.tree === "string"
50
+ ? await readTreeFile(value.tree, cwd, signal)
51
+ : value.tree;
52
+ if (!isRecord(raw) || Object.keys(raw).some((key) => key !== "roots"))
53
+ invalid("Classification tree must be an object containing roots.");
54
+ const ancestors = new Set<object>();
55
+ const roots = nodes(raw.roots, 1, ancestors, { bytes: 0 });
56
+ const tree = { roots };
57
+ if (Buffer.byteLength(JSON.stringify(tree)) > MAX_TREE_BYTES)
58
+ invalid("Classification tree must be at most 2 MiB.");
59
+ cancelled(signal);
60
+ const result: Omit<ClassifyTreeParams, "tree"> & { tree: ClassificationTree } = {
61
+ state: base.state,
62
+ tree,
63
+ };
64
+ if (typeof value.instructions === "string")
65
+ result.instructions = value.instructions;
66
+ if (base.images !== undefined) result.images = base.images;
67
+ return result;
68
+ }
69
+
70
+ function nodes(
71
+ value: unknown,
72
+ depth: number,
73
+ ancestors: Set<object>,
74
+ budget: { bytes: number },
75
+ ): ClassificationTreeNode[] {
76
+ if (!Array.isArray(value) || (depth === 1 && value.length === 0))
77
+ invalid(
78
+ "Classification tree roots must be non-empty and children must be arrays when supplied.",
79
+ );
80
+ if (depth > MAX_DEPTH && value.length > 0)
81
+ invalid("Classification tree must be at most 32 levels deep.");
82
+ const ids = new Set<string>();
83
+ return value.map((entry) => {
84
+ if (
85
+ !isRecord(entry) ||
86
+ Object.keys(entry).some((key) => !["id", "description", "children"].includes(key)) ||
87
+ typeof entry.id !== "string" ||
88
+ !entry.id.trim() || entry.id.length > 128 ||
89
+ (entry.description !== undefined &&
90
+ (typeof entry.description !== "string" || entry.description.length > 4096))
91
+ )
92
+ invalid(
93
+ "Each classification tree node needs a non-empty id of at most 128 characters, optional description up to 4096 characters, and optional children.",
94
+ );
95
+ if (ids.has(entry.id)) invalid("Classification tree node IDs must be unique among siblings.");
96
+ if (ancestors.has(entry)) invalid("Classification tree must not contain cycles.");
97
+ ids.add(entry.id);
98
+ ancestors.add(entry);
99
+ const node: ClassificationTreeNode = { id: entry.id };
100
+ if (typeof entry.description === "string") node.description = entry.description;
101
+ // Bound normalization itself, including shared JS subtrees that expand when serialized.
102
+ budget.bytes += Buffer.byteLength(JSON.stringify(node));
103
+ if (budget.bytes > MAX_TREE_BYTES) invalid("Classification tree must be at most 2 MiB.");
104
+ if (entry.children !== undefined)
105
+ node.children = nodes(entry.children, depth + 1, ancestors, budget);
106
+ ancestors.delete(entry);
107
+ return node;
108
+ });
109
+ }
110
+
111
+ async function readTreeFile(
112
+ path: string,
113
+ cwd: string,
114
+ signal?: AbortSignal,
115
+ ): Promise<unknown> {
116
+ if (!path.trim() || path.length > 4096 || /^[a-z]+:/i.test(path))
117
+ invalid(
118
+ "Classification tree must be an inline roots object or a local JSON path inside cwd, not a URL.",
119
+ );
120
+ let bytes: Buffer;
121
+ try {
122
+ const root = await realpath(cwd);
123
+ const target = resolve(root, path);
124
+ const inside = relative(root, target);
125
+ if (
126
+ !inside || inside === ".." ||
127
+ inside.startsWith(".." + sep) || isAbsolute(inside)
128
+ )
129
+ throw new Error();
130
+ let current = root;
131
+ for (const part of inside.split(sep)) {
132
+ cancelled(signal);
133
+ current = resolve(current, part);
134
+ const entry = await lstat(current);
135
+ if (
136
+ entry.isSymbolicLink() ||
137
+ (current === target ? !entry.isFile() : !entry.isDirectory())
138
+ )
139
+ throw new Error();
140
+ }
141
+ if (await realpath(target) !== target) throw new Error();
142
+ const file = await open(
143
+ target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
144
+ );
145
+ try {
146
+ await verifyOpenedPath(file.fd, root, signal);
147
+ const stat = await file.stat();
148
+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_TREE_BYTES)
149
+ throw new Error();
150
+ const buffer = Buffer.alloc(MAX_TREE_BYTES + 1);
151
+ let offset = 0;
152
+ while (offset < buffer.length) {
153
+ cancelled(signal);
154
+ const next = await file.read(buffer, offset, buffer.length - offset, null);
155
+ if (!next.bytesRead) break;
156
+ offset += next.bytesRead;
157
+ }
158
+ if (offset > MAX_TREE_BYTES) throw new Error();
159
+ bytes = buffer.subarray(0, offset);
160
+ } finally {
161
+ await file.close();
162
+ }
163
+ } catch (error) {
164
+ cancelled(signal);
165
+ if (error instanceof ClassifierError) throw error;
166
+ invalid(
167
+ "Classification tree must be a readable regular file inside cwd, without symlink components, and at most 2 MiB.",
168
+ );
169
+ }
170
+ cancelled(signal);
171
+ try {
172
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
173
+ } catch {
174
+ invalid("Classification tree file must contain valid UTF-8 JSON.");
175
+ }
176
+ }
177
+
178
+ function cancelled(signal?: AbortSignal): void {
179
+ if (signal?.aborted)
180
+ throw new ClassifierError("aborted", "Classification was cancelled.");
181
+ }
package/src/classify.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { performance } from "node:perf_hooks";
2
2
  import { resolveApiKey } from "./auth.js";
3
3
  import { configuredDefault, configuredRoutes, resolveModel } from "./config.js";
4
- import { prepareInput } from "./inputs.js";
4
+ import { prepareInput, type MemoryImage } from "./inputs.js";
5
+ import { choicePolicy, executeChoices } from "./choices.js";
5
6
  import { classifyWithProvider } from "./providers.js";
6
7
  import {
7
8
  ClassifierError,
@@ -15,10 +16,12 @@ import {
15
16
  } from "./types.js";
16
17
  import { validateParams } from "./validation.js";
17
18
 
18
- type ClassifyOptions = {
19
+ export type ClassifyOptions = {
19
20
  settings: ClassifierSettings;
20
21
  cwd: string;
21
22
  signal?: AbortSignal;
23
+ /** Trusted programmatic ingress; all bytes still pass normal image validation. */
24
+ memoryImages?: readonly MemoryImage[];
22
25
  };
23
26
 
24
27
  function checkCancelled(signal?: AbortSignal): void {
@@ -40,10 +43,17 @@ async function classifyOnce(
40
43
  options: ClassifyOptions,
41
44
  ): Promise<ClassifierResult> {
42
45
  checkCancelled(options.signal);
43
- const prepared = await prepareInput(input, route, options.cwd, options.signal);
46
+ const prepared = await prepareInput(input, route, options.cwd, options.signal, options.memoryImages);
44
47
  checkCancelled(options.signal);
45
48
  const key = resolveApiKey(route);
46
- const result = await classifyWithProvider(route, prepared, key, options.signal);
49
+ const result = await executeChoices(
50
+ prepared,
51
+ route,
52
+ choicePolicy(options.settings),
53
+ (questions) =>
54
+ classifyWithProvider(route, { ...prepared, questions }, key, options.signal),
55
+ options.signal,
56
+ );
47
57
  if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
48
58
  throw new ClassifierError(
49
59
  "response",
@@ -65,6 +75,7 @@ export async function classify(
65
75
  params: unknown,
66
76
  options: ClassifyOptions,
67
77
  ): Promise<ClassifierResult> {
78
+ choicePolicy(options.settings);
68
79
  const input = validateParams(params);
69
80
  const candidates = [
70
81
  configuredDefault(options.settings),
@@ -98,6 +109,7 @@ export async function compareClassifiers(
98
109
  params: unknown,
99
110
  options: ClassifyOptions,
100
111
  ): Promise<ClassifierComparisonResult> {
112
+ choicePolicy(options.settings);
101
113
  const input = validateParams(params);
102
114
  const candidates = configuredRoutes(options.settings, "compare");
103
115
  if (candidates.length === 0)