@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/dist/types.d.ts CHANGED
@@ -1,22 +1,34 @@
1
1
  export type ApiStyle = "openai-decisions" | "perplexity-decisions" | "system-one" | "cloudflare-system-one" | "microsoft-system-one";
2
+ /** Explicit references are resolved only from the request's named images. */
3
+ export type ImageReference = {
4
+ $image: string;
5
+ };
6
+ export type QuestionContent = string | (string | ImageReference)[];
7
+ export type ImageInput = string | {
8
+ id: string;
9
+ path: string;
10
+ } | {
11
+ id: string;
12
+ url: string;
13
+ };
2
14
  export type Question = {
3
15
  type: "bool";
4
- instructions: string;
16
+ instructions: QuestionContent;
5
17
  criteria?: {
6
- true?: string;
7
- false?: string;
18
+ true?: QuestionContent;
19
+ false?: QuestionContent;
8
20
  };
9
21
  } | {
10
22
  type: "choice";
11
- instructions: string;
12
- criteria: Record<string, string>;
23
+ instructions: QuestionContent;
24
+ criteria: Record<string, QuestionContent>;
13
25
  } | {
14
26
  type: "score";
15
- instructions: string;
16
- criteria: string[];
27
+ instructions: QuestionContent;
28
+ criteria: QuestionContent[];
17
29
  } | {
18
30
  type: "box";
19
- instructions: string;
31
+ instructions: QuestionContent;
20
32
  };
21
33
  export type Answer = {
22
34
  type: "bool";
@@ -53,8 +65,8 @@ export type Answer = {
53
65
  export interface ClassifyParams {
54
66
  state: string | Record<string, unknown> | unknown[];
55
67
  questions: Record<string, Question>;
56
- /** Regular PNG/JPEG/WebP files inside cwd; attached in this order. */
57
- images?: string[];
68
+ /** Legacy paths are shared in order. Named images require explicit {$image:id} references. */
69
+ images?: ImageInput[];
58
70
  }
59
71
  export type ClassificationTreeNode = {
60
72
  id: string;
@@ -68,7 +80,7 @@ export type ClassifyTreeParams = {
68
80
  state: ClassifyParams["state"];
69
81
  tree: string | ClassificationTree;
70
82
  instructions?: string;
71
- images?: string[];
83
+ images?: ImageInput[];
72
84
  };
73
85
  export type TreeStep = {
74
86
  level: number;
@@ -143,6 +155,7 @@ export type ClassifierRoute = {
143
155
  model: string;
144
156
  };
145
157
  export interface ClassifierSettings {
158
+ computerUse?: import("./computer-use-types.js").ComputerUseSettings;
146
159
  none_of_above_choice?: boolean;
147
160
  remove_choice_limits?: boolean;
148
161
  default?: ClassifierRoute;
@@ -174,12 +187,17 @@ export interface ResolvedModel {
174
187
  };
175
188
  maxChoices?: number;
176
189
  }
177
- export interface PreparedImage {
190
+ export interface PreparedLocalImage {
178
191
  data: string;
179
192
  mimeType: "image/png" | "image/jpeg" | "image/webp";
180
193
  width: number;
181
194
  height: number;
182
195
  }
196
+ export type PreparedImage = (PreparedLocalImage | {
197
+ url: string;
198
+ }) & {
199
+ id?: string;
200
+ };
183
201
  export interface PreparedInput {
184
202
  state: ClassifyParams["state"];
185
203
  questions: Record<string, Question>;
@@ -1,14 +1,24 @@
1
1
  import { ClassifierError, isRecord, } from "./types.js";
2
+ import { imageReferences, isImageReference, questionImageReferences } from "./image-content.js";
2
3
  function invalid(message) {
3
4
  throw new ClassifierError("input", message);
4
5
  }
6
+ const imageId = /^[a-zA-Z0-9_-]{1,64}$/;
7
+ function content(value, maxLength, nonempty = false) {
8
+ if (typeof value === "string")
9
+ return value.length <= maxLength && (!nonempty || Boolean(value.trim()));
10
+ if (!Array.isArray(value) || value.length < 1 || value.length > 128)
11
+ return false;
12
+ if (!value.every((part) => typeof part === "string" || isImageReference(part)))
13
+ return false;
14
+ validateJson(value, 0);
15
+ return Buffer.byteLength(JSON.stringify(value)) <= maxLength &&
16
+ (!nonempty || value.some((part) => typeof part !== "string" || Boolean(part.trim())));
17
+ }
5
18
  export function validateParams(value) {
6
- if (!isRecord(value) ||
7
- Object.keys(value).some((key) => !["state", "questions", "images"].includes(key)))
19
+ if (!isRecord(value) || Object.keys(value).some((key) => !["state", "questions", "images"].includes(key)))
8
20
  invalid("Expected state, questions and optional images; provider/model are selected in settings.");
9
- if (!(typeof value.state === "string" ||
10
- Array.isArray(value.state) ||
11
- isRecord(value.state)))
21
+ if (!(typeof value.state === "string" || Array.isArray(value.state) || isRecord(value.state)))
12
22
  invalid("state must be text, a JSON object or an array.");
13
23
  validateJson(value.state, 0);
14
24
  if (!isRecord(value.questions))
@@ -21,35 +31,24 @@ export function validateParams(value) {
21
31
  invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
22
32
  if (Object.keys(question).some((key) => !["type", "instructions", "criteria"].includes(key)))
23
33
  invalid("Unknown question field.");
24
- if (typeof question.instructions !== "string" ||
25
- !question.instructions.trim() ||
26
- question.instructions.length > 16_384)
27
- invalid("Each question needs non-empty instructions, at most 16384 characters.");
34
+ if (!content(question.instructions, 16_384, true))
35
+ invalid("Each question needs non-empty text or ordered text/image-reference instructions, at most 16384 characters/bytes.");
28
36
  if (question.type === "bool") {
29
- if (question.criteria !== undefined &&
30
- (!isRecord(question.criteria) ||
31
- Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) ||
32
- typeof entry !== "string" ||
33
- entry.length > 4096)))
34
- invalid("bool criteria must contain optional true/false descriptions.");
37
+ if (question.criteria !== undefined && (!isRecord(question.criteria) ||
38
+ Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) || !content(entry, 4096))))
39
+ invalid("bool criteria must contain optional true/false descriptions or image content.");
35
40
  }
36
41
  else if (question.type === "choice") {
37
42
  if (!isRecord(question.criteria))
38
43
  invalid("choice criteria must map labels to descriptions.");
39
44
  const criteria = Object.entries(question.criteria);
40
- if (criteria.length < 1 ||
41
- criteria.some(([key, entry]) => !key.trim() ||
42
- key.length > 128 ||
43
- typeof entry !== "string" ||
44
- entry.length > 4096))
45
- invalid("choice requires at least one label with a string description.");
45
+ if (criteria.length < 1 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
46
+ invalid("choice requires at least one label with a text or image-content description.");
46
47
  }
47
48
  else if (question.type === "score") {
48
- if (!Array.isArray(question.criteria) ||
49
- question.criteria.length < 2 ||
50
- question.criteria.length > 10 ||
51
- question.criteria.some((entry) => typeof entry !== "string" || !entry.trim() || entry.length > 4096))
52
- invalid("score criteria must contain 2–10 non-empty ordered descriptions.");
49
+ if (!Array.isArray(question.criteria) || question.criteria.length < 2 || question.criteria.length > 10 ||
50
+ question.criteria.some((entry) => !content(entry, 4096, true)))
51
+ invalid("score criteria must contain 2–10 non-empty ordered descriptions or image content.");
53
52
  }
54
53
  else if (question.type === "box") {
55
54
  if (question.criteria !== undefined)
@@ -58,19 +57,47 @@ export function validateParams(value) {
58
57
  else
59
58
  invalid("Question type must be bool, choice, score or box.");
60
59
  }
61
- if (value.images !== undefined &&
62
- (!Array.isArray(value.images) ||
63
- value.images.length > 5 ||
64
- value.images.some((path) => typeof path !== "string" || !path.trim() || path.length > 4096)))
65
- invalid("images must contain at most five local file paths.");
66
- const encoded = JSON.stringify(value);
67
- if (Buffer.byteLength(encoded) > 2 * 1024 * 1024)
60
+ const ids = new Set();
61
+ if (value.images !== undefined) {
62
+ if (!Array.isArray(value.images) || value.images.length > 8)
63
+ invalid("images must contain at most eight local paths or named path/url descriptors; route-specific limits also apply.");
64
+ for (const image of value.images) {
65
+ if (typeof image === "string") {
66
+ if (!image.trim() || image.length > 4096)
67
+ invalid("Image paths must be non-empty, at most 4096 characters.");
68
+ continue;
69
+ }
70
+ if (!isRecord(image) || typeof image.id !== "string" || !imageId.test(image.id) ||
71
+ Object.keys(image).some((key) => !["id", "path", "url"].includes(key)) ||
72
+ (Object.hasOwn(image, "path") === Object.hasOwn(image, "url")))
73
+ invalid("Named images require a unique id and exactly one path or url.");
74
+ const source = image.path ?? image.url;
75
+ if (typeof source !== "string" || !source.trim() || source.length > 4096)
76
+ invalid("Image path/url must be non-empty, at most 4096 characters.");
77
+ if (ids.has(image.id))
78
+ invalid("Named image IDs must be unique.");
79
+ ids.add(image.id);
80
+ }
81
+ }
82
+ const references = [...imageReferences(value.state), ...questionImageReferences(value.questions)];
83
+ for (const id of references)
84
+ if (!ids.has(id))
85
+ invalid("Every image reference must name an image descriptor in images.");
86
+ for (const id of ids)
87
+ if (!references.includes(id))
88
+ invalid("Every named image must be referenced in state, instructions or criteria.");
89
+ if (Buffer.byteLength(JSON.stringify(value)) > 2 * 1024 * 1024)
68
90
  invalid("Classification text and questions must be at most 2 MiB.");
69
91
  return value;
70
92
  }
71
93
  function validateJson(value, depth) {
72
94
  if (depth > 32)
73
- invalid("state must be at most 32 levels deep.");
95
+ invalid("JSON content must be at most 32 levels deep.");
96
+ if (isImageReference(value)) {
97
+ if (Object.keys(value).length !== 1 || typeof value.$image !== "string" || !imageId.test(value.$image))
98
+ invalid("An image reference must be exactly {$image: id} with a 1–64 character image ID.");
99
+ return;
100
+ }
74
101
  if (value === null || typeof value === "string" || typeof value === "boolean")
75
102
  return;
76
103
  if (typeof value === "number" && Number.isFinite(value))
@@ -80,14 +107,12 @@ function validateJson(value, depth) {
80
107
  validateJson(entry, depth + 1);
81
108
  return;
82
109
  }
83
- if (isRecord(value) &&
84
- (Object.getPrototypeOf(value) === Object.prototype ||
85
- Object.getPrototypeOf(value) === null)) {
110
+ if (isRecord(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
86
111
  for (const entry of Object.values(value))
87
112
  validateJson(entry, depth + 1);
88
113
  return;
89
114
  }
90
- invalid("state must contain only finite JSON values.");
115
+ invalid("Content must contain only finite JSON values.");
91
116
  }
92
117
  export function hasBox(questions) {
93
118
  return Object.values(questions).some((question) => question.type === "box");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-classifier",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Config-driven typed classification for Pi via Microsoft Decision-1, OpenAI Decisions, Perplexity, TypeSafe Jev and Cloudflare Clef, with selective fallback and explicit comparisons.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -41,6 +41,7 @@
41
41
  "src",
42
42
  "CHANGELOG.md",
43
43
  "README.md",
44
+ "COMPUTER_USE.md",
44
45
  "LICENSE",
45
46
  "THIRD_PARTY_NOTICES.md"
46
47
  ],
@@ -0,0 +1,145 @@
1
+ import {
2
+ defineTool,
3
+ type ExtensionAPI,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
6
+ import {
7
+ renderClassifierBox,
8
+ type ClassifierBoxMode,
9
+ type ClassifierBoxPixelBox,
10
+ } from "./box.js";
11
+ import { ClassifierError, userError } from "./types.js";
12
+
13
+ export const boxParameters = Type.Object(
14
+ {
15
+ image: Type.String({
16
+ minLength: 1,
17
+ maxLength: 4096,
18
+ description:
19
+ "Local PNG, JPEG or WebP file inside cwd. No URLs, symlinks or inline base64.",
20
+ }),
21
+ box: Type.Object(
22
+ {
23
+ top: Type.Number({ minimum: 0, maximum: 1 }),
24
+ bottom: Type.Number({ minimum: 0, maximum: 1 }),
25
+ left: Type.Number({ minimum: 0, maximum: 1 }),
26
+ right: Type.Number({ minimum: 0, maximum: 1 }),
27
+ },
28
+ {
29
+ additionalProperties: false,
30
+ description:
31
+ "Normalized edges between 0 and 1, with top < bottom and left < right.",
32
+ },
33
+ ),
34
+ mode: Type.Optional(
35
+ Type.Union([Type.Literal("overlay"), Type.Literal("crop")], {
36
+ description:
37
+ "overlay draws the box on the image (default); crop returns only the boxed region.",
38
+ }),
39
+ ),
40
+ },
41
+ { additionalProperties: false },
42
+ );
43
+
44
+ export const boxOutput = Type.Object({
45
+ mode: Type.Union([Type.Literal("overlay"), Type.Literal("crop")]),
46
+ mimeType: Type.Literal("image/png"),
47
+ width: Type.Integer({ minimum: 1 }),
48
+ height: Type.Integer({ minimum: 1 }),
49
+ pixelBox: Type.Object({
50
+ left: Type.Integer({ minimum: 0 }),
51
+ top: Type.Integer({ minimum: 0 }),
52
+ width: Type.Integer({ minimum: 1 }),
53
+ height: Type.Integer({ minimum: 1 }),
54
+ }),
55
+ byteLength: Type.Integer({ minimum: 1 }),
56
+ });
57
+
58
+ type BoxToolDetails = {
59
+ mode: ClassifierBoxMode;
60
+ mimeType: "image/png";
61
+ width: number;
62
+ height: number;
63
+ pixelBox: ClassifierBoxPixelBox;
64
+ byteLength: number;
65
+ };
66
+
67
+ export function registerBoxTool(pi: ExtensionAPI): void {
68
+ pi.registerTool(
69
+ defineTool<typeof boxParameters, BoxToolDetails>({
70
+ name: "classifier_box_image",
71
+ label: "Box image",
72
+ description:
73
+ "Render a normalized bounding box on a local image, or crop to it, entirely locally. Use to inspect a box answer from classify. overlay keeps the image and draws a rectangle; crop returns only the clamped region. Returns a PNG plus exact source-pixel box metadata. No provider request, upload, resizing or disk write. A box is a localization hint, not proof that the object exists.",
74
+ promptSnippet:
75
+ "Render or crop a local image using normalized box coordinates.",
76
+ promptGuidelines: [
77
+ "Use classifier_box_image only for local images inside cwd and normalized boxes between 0 and 1.",
78
+ "A returned box does not by itself confirm that the object exists.",
79
+ ],
80
+ parameters: boxParameters,
81
+ outputSchema: boxOutput,
82
+ annotations: {
83
+ readOnlyHint: true,
84
+ destructiveHint: false,
85
+ openWorldHint: false,
86
+ },
87
+ async execute(_id, params, signal, _onUpdate, ctx) {
88
+ try {
89
+ const result = await renderClassifierBox(params, {
90
+ cwd: ctx.cwd,
91
+ ...(signal ? { signal } : {}),
92
+ });
93
+ const byteLength = Buffer.from(result.data, "base64").byteLength;
94
+ const details: BoxToolDetails = {
95
+ mode: result.mode,
96
+ mimeType: result.mimeType,
97
+ width: result.width,
98
+ height: result.height,
99
+ pixelBox: result.pixelBox,
100
+ byteLength,
101
+ };
102
+ const box = result.pixelBox;
103
+ return {
104
+ content: [
105
+ {
106
+ type: "text",
107
+ text:
108
+ "Rendered " +
109
+ result.mode +
110
+ " box as a " +
111
+ result.width +
112
+ "×" +
113
+ result.height +
114
+ " PNG (" +
115
+ byteLength +
116
+ " bytes). Source pixel box: left=" +
117
+ box.left +
118
+ ", top=" +
119
+ box.top +
120
+ ", width=" +
121
+ box.width +
122
+ ", height=" +
123
+ box.height +
124
+ ". A box is a localization hint, not proof that the object exists.",
125
+ },
126
+ {
127
+ type: "image",
128
+ data: result.data,
129
+ mimeType: result.mimeType,
130
+ },
131
+ ],
132
+ details,
133
+ structuredContent: details,
134
+ };
135
+ } catch (error) {
136
+ console.error(
137
+ "[pi-classifier] box image failed: " +
138
+ (error instanceof ClassifierError ? error.code : "unexpected"),
139
+ );
140
+ throw new Error(userError(error));
141
+ }
142
+ },
143
+ }),
144
+ );
145
+ }
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 CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  type ClassifierSettings,
8
8
  type PreparedInput,
9
9
  type Question,
10
+ type QuestionContent,
10
11
  type ResolvedModel,
11
12
  } from "./types.js";
12
13
 
@@ -29,7 +30,7 @@ export function choicePolicy(settings: ClassifierSettings): ChoicePolicy {
29
30
 
30
31
  type ChoicePlan = {
31
32
  question: Extract<Question, { type: "choice" }>;
32
- entries: [string, string][];
33
+ entries: [string, QuestionContent][];
33
34
  offset: number;
34
35
  sentinel: string;
35
36
  };