@abhishek944/pi-classifier 0.3.0 → 0.5.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 (77) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +344 -30
  4. package/dist/auth.d.ts +4 -2
  5. package/dist/auth.js +18 -2
  6. package/dist/box-tool.d.ts +4 -0
  7. package/dist/box-tool.js +79 -0
  8. package/dist/box.d.ts +32 -0
  9. package/dist/box.js +148 -0
  10. package/dist/choices.js +35 -1
  11. package/dist/classify.d.ts +6 -0
  12. package/dist/classify.js +4 -4
  13. package/dist/computer-use-state.d.ts +9 -0
  14. package/dist/computer-use-state.js +160 -0
  15. package/dist/computer-use-tool.d.ts +52 -0
  16. package/dist/computer-use-tool.js +78 -0
  17. package/dist/computer-use-types.d.ts +132 -0
  18. package/dist/computer-use-types.js +1 -0
  19. package/dist/computer-use.d.ts +22 -0
  20. package/dist/computer-use.js +223 -0
  21. package/dist/config.d.ts +140 -3
  22. package/dist/config.js +405 -20
  23. package/dist/cost.js +42 -4
  24. package/dist/durable.d.ts +34 -0
  25. package/dist/durable.js +237 -0
  26. package/dist/extension.d.ts +2 -247
  27. package/dist/extension.js +53 -190
  28. package/dist/extract.d.ts +11 -0
  29. package/dist/extract.js +191 -0
  30. package/dist/http.d.ts +6 -1
  31. package/dist/http.js +64 -28
  32. package/dist/image-content.d.ts +12 -0
  33. package/dist/image-content.js +90 -0
  34. package/dist/index.d.ts +10 -1
  35. package/dist/index.js +3 -0
  36. package/dist/inputs.d.ts +24 -2
  37. package/dist/inputs.js +565 -134
  38. package/dist/mcp-cli.d.ts +2 -0
  39. package/dist/mcp-cli.js +39 -0
  40. package/dist/mcp-server.d.ts +28 -0
  41. package/dist/mcp-server.js +121 -0
  42. package/dist/mcp-tool-definitions.d.ts +19 -0
  43. package/dist/mcp-tool-definitions.js +64 -0
  44. package/dist/providers.d.ts +1 -0
  45. package/dist/providers.js +1218 -124
  46. package/dist/tool-contracts.d.ts +785 -0
  47. package/dist/tool-contracts.js +530 -0
  48. package/dist/tree.js +1 -1
  49. package/dist/types.d.ts +314 -20
  50. package/dist/validation.js +181 -44
  51. package/package.json +33 -5
  52. package/src/auth.ts +26 -2
  53. package/src/box-tool.ts +110 -0
  54. package/src/box.ts +253 -0
  55. package/src/choices.ts +44 -2
  56. package/src/classify.ts +10 -6
  57. package/src/computer-use-state.ts +145 -0
  58. package/src/computer-use-tool.ts +76 -0
  59. package/src/computer-use-types.ts +127 -0
  60. package/src/computer-use.ts +216 -0
  61. package/src/config.ts +454 -23
  62. package/src/cost.ts +42 -4
  63. package/src/durable.ts +298 -0
  64. package/src/extension.ts +79 -265
  65. package/src/extract.ts +228 -0
  66. package/src/http.ts +63 -32
  67. package/src/image-content.ts +77 -0
  68. package/src/index.ts +25 -0
  69. package/src/inputs.ts +603 -184
  70. package/src/mcp-cli.ts +44 -0
  71. package/src/mcp-server.ts +179 -0
  72. package/src/mcp-tool-definitions.ts +104 -0
  73. package/src/providers.ts +1398 -144
  74. package/src/tool-contracts.ts +785 -0
  75. package/src/tree.ts +1 -1
  76. package/src/types.ts +248 -11
  77. package/src/validation.ts +169 -96
@@ -1,76 +1,215 @@
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)))
8
- 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)))
19
+ if (!isRecord(value) || Object.keys(value).some((key) => !["state", "questions", "images", "media", "mode", "conversation", "imageDetail", "promptCache"].includes(key)))
20
+ invalid("Expected state, questions and optional images, media, mode, conversation, imageDetail or promptCache; provider/model are selected in settings.");
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))
15
25
  invalid("questions must be a map keyed by question ID.");
16
26
  const entries = Object.entries(value.questions);
17
- if (entries.length < 1 || entries.length > 32)
18
- invalid("Supply between 1 and 32 questions.");
27
+ if (entries.length < 1 || entries.length > 1000)
28
+ invalid("Supply between 1 and 1000 questions; the selected route enforces its own lower limit.");
19
29
  for (const [id, question] of entries) {
20
30
  if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
21
31
  invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
22
- if (Object.keys(question).some((key) => !["type", "instructions", "criteria"].includes(key)))
23
- 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.");
32
+ const allowed = question.type === "number" || question.type === "estimate"
33
+ ? ["type", "instructions", "unit", "range", "step"]
34
+ : question.type === "spans" || question.type === "boxes"
35
+ ? ["type", "instructions", "max"]
36
+ : question.type === "choice"
37
+ ? ["type", "instructions", "criteria", "booleanValues"]
38
+ : question.type === "score"
39
+ ? ["type", "instructions", "criteria", "descriptions"]
40
+ : question.type === "extract"
41
+ ? ["type", "instructions", "criteria", "source", "threshold", "snapToWords", "debug"]
42
+ : ["type", "instructions", "criteria"];
43
+ if (Object.keys(question).some((key) => !allowed.includes(key)))
44
+ invalid("Unknown question field for " + String(question.type) + ".");
45
+ if (question.type !== "extract" && !content(question.instructions, 16_384, true))
46
+ invalid("Each question needs non-empty text or ordered text/image-reference instructions, at most 16384 characters/bytes.");
47
+ if (question.type === "extract" && question.instructions !== undefined && !content(question.instructions, 16_384))
48
+ invalid("Extract instructions must be text or ordered text/image-reference content, at most 16384 characters/bytes.");
28
49
  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.");
50
+ if (question.criteria !== undefined && (!isRecord(question.criteria) ||
51
+ Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) || !content(entry, 4096))))
52
+ invalid("bool criteria must contain optional true/false descriptions or image content.");
35
53
  }
36
54
  else if (question.type === "choice") {
37
55
  if (!isRecord(question.criteria))
38
56
  invalid("choice criteria must map labels to descriptions.");
39
57
  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.");
58
+ if (criteria.length < 1 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
59
+ invalid("choice requires at least one label with a text or image-content description.");
60
+ if (question.booleanValues !== undefined) {
61
+ if (typeof question.booleanValues !== "boolean")
62
+ invalid("choice.booleanValues must be a boolean.");
63
+ if (question.booleanValues && criteria.some(([key]) => key !== "true" && key !== "false"))
64
+ invalid("Boolean-valued choices must use the labels true and false.");
65
+ }
46
66
  }
47
67
  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.");
68
+ if (!Array.isArray(question.criteria) || question.criteria.length < 2 || question.criteria.length > 10 ||
69
+ question.criteria.some((entry) => !content(entry, 4096, true)))
70
+ invalid("score criteria must contain 2–10 non-empty ordered descriptions or image content.");
71
+ if (question.descriptions !== undefined &&
72
+ (!Array.isArray(question.descriptions) || question.descriptions.length !== question.criteria.length ||
73
+ question.descriptions.some((entry) => typeof entry !== "string" || entry.length > 4096)))
74
+ invalid("score descriptions must contain one string per criterion, at most 4096 characters each.");
53
75
  }
54
76
  else if (question.type === "box") {
55
77
  if (question.criteria !== undefined)
56
78
  invalid("box does not accept criteria.");
57
79
  }
80
+ else if (question.type === "locate" || question.type === "text" || question.type === "date") {
81
+ if (question.criteria !== undefined)
82
+ invalid(question.type + " does not accept criteria.");
83
+ }
84
+ else if (question.type === "spans" || question.type === "boxes") {
85
+ if (question.criteria !== undefined)
86
+ invalid(question.type + " does not accept criteria.");
87
+ if (question.max !== undefined &&
88
+ (!Number.isSafeInteger(question.max) || question.max < 1 || question.max > 64))
89
+ invalid(question.type + ".max must be an integer from 1 to 64.");
90
+ }
91
+ else if (question.type === "number" || question.type === "estimate") {
92
+ if (question.unit !== undefined && (typeof question.unit !== "string" || question.unit.length > 128))
93
+ invalid("unit must be a string of at most 128 characters.");
94
+ if (question.step !== undefined && (typeof question.step !== "number" || !Number.isFinite(question.step) || question.step <= 0))
95
+ invalid("step must be a positive finite number.");
96
+ const range = question.range;
97
+ if (question.type === "estimate" && !Array.isArray(range))
98
+ invalid("estimate requires a [low, high] range.");
99
+ if (range !== undefined && (!Array.isArray(range) || range.length !== 2 ||
100
+ range.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)) ||
101
+ range[0] >= range[1]))
102
+ invalid("range must be a finite [low, high] pair with low below high.");
103
+ }
104
+ else if (question.type === "extract") {
105
+ if (!isRecord(question.criteria))
106
+ invalid("extract criteria must map field names to descriptions.");
107
+ const criteria = Object.entries(question.criteria);
108
+ if (criteria.length < 1 || criteria.length > 26 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
109
+ invalid("extract requires 1–26 fields with text descriptions.");
110
+ if (question.source !== undefined && (typeof question.source !== "string" || !question.source.trim() || question.source.length > 4096))
111
+ invalid("extract.source must be a non-empty string of at most 4096 characters.");
112
+ if (question.threshold !== undefined && (typeof question.threshold !== "number" || !Number.isFinite(question.threshold) || question.threshold < 0 || question.threshold > 1))
113
+ invalid("extract.threshold must be a number between 0 and 1.");
114
+ if (question.snapToWords !== undefined && typeof question.snapToWords !== "boolean")
115
+ invalid("extract.snapToWords must be a boolean.");
116
+ if (question.debug !== undefined && typeof question.debug !== "boolean")
117
+ invalid("extract.debug must be a boolean.");
118
+ }
119
+ else if (question.type === "multi_choice") {
120
+ if (!isRecord(question.criteria))
121
+ invalid("multi_choice criteria must map labels to descriptions.");
122
+ const criteria = Object.entries(question.criteria);
123
+ if (criteria.length < 2 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
124
+ invalid("multi_choice requires at least two labels with text or image-content descriptions.");
125
+ }
58
126
  else
59
- invalid("Question type must be bool, choice, score or box.");
127
+ invalid("Question type must be a supported typed decision or read.");
128
+ }
129
+ if (value.media !== undefined) {
130
+ if (!Array.isArray(value.media))
131
+ invalid("media must be an array of audio/video descriptors.");
132
+ for (const item of value.media) {
133
+ if (!isRecord(item) || (item.type !== "audio" && item.type !== "video") ||
134
+ Object.keys(item).some((key) => key !== "type" && key !== "path") ||
135
+ typeof item.path !== "string" || !item.path.trim() || item.path.length > 4096)
136
+ invalid("Each media descriptor needs a type of audio or video and a local path.");
137
+ }
138
+ }
139
+ if (value.conversation !== undefined) {
140
+ if (!Array.isArray(value.conversation))
141
+ invalid("conversation must be an array of OpenAI Decisions input items.");
142
+ const types = ["message", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output"];
143
+ for (const item of value.conversation) {
144
+ if (!isRecord(item) || typeof item.type !== "string" || !types.includes(item.type))
145
+ invalid("Each conversation item needs a documented OpenAI Decisions input type.");
146
+ }
60
147
  }
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)
148
+ if (value.mode !== undefined && value.mode !== "web_grounding")
149
+ invalid("mode must be omitted or \"web_grounding\".");
150
+ if (value.imageDetail !== undefined &&
151
+ (typeof value.imageDetail !== "string" || !["auto", "low", "high", "original"].includes(value.imageDetail)))
152
+ invalid("imageDetail must be auto, low, high or original.");
153
+ if (value.promptCache !== undefined) {
154
+ if (!isRecord(value.promptCache) ||
155
+ Object.keys(value.promptCache).some((key) => !["key", "mode", "ttl", "breakpoints"].includes(key)))
156
+ invalid("promptCache may only set key, mode, ttl and breakpoints.");
157
+ if (value.promptCache.key !== undefined &&
158
+ (typeof value.promptCache.key !== "string" || value.promptCache.key.length < 1 || value.promptCache.key.length > 64))
159
+ invalid("promptCache.key must be 1–64 characters.");
160
+ if (value.promptCache.mode !== undefined &&
161
+ (typeof value.promptCache.mode !== "string" || !["implicit", "explicit"].includes(value.promptCache.mode)))
162
+ invalid("promptCache.mode must be implicit or explicit.");
163
+ if (value.promptCache.ttl !== undefined && value.promptCache.ttl !== "30m")
164
+ invalid("promptCache.ttl may only be 30m.");
165
+ if (value.promptCache.breakpoints !== undefined && typeof value.promptCache.breakpoints !== "boolean")
166
+ invalid("promptCache.breakpoints must be a boolean.");
167
+ }
168
+ const ids = new Set();
169
+ if (value.images !== undefined) {
170
+ if (!Array.isArray(value.images) || value.images.length > 128)
171
+ invalid("images must contain at most 128 local paths or named path/url descriptors; route-specific limits also apply.");
172
+ for (const image of value.images) {
173
+ if (typeof image === "string") {
174
+ if (!image.trim() || image.length > 4096)
175
+ invalid("Image paths must be non-empty, at most 4096 characters.");
176
+ continue;
177
+ }
178
+ if (!isRecord(image) || typeof image.id !== "string" || !imageId.test(image.id) ||
179
+ Object.keys(image).some((key) => !["id", "path", "url"].includes(key)) ||
180
+ (Object.hasOwn(image, "path") === Object.hasOwn(image, "url")))
181
+ invalid("Named images require a unique id and exactly one path or url.");
182
+ const source = image.path ?? image.url;
183
+ if (typeof source !== "string" || !source.trim() || source.length > 4096)
184
+ invalid("Image path/url must be non-empty, at most 4096 characters.");
185
+ if (ids.has(image.id))
186
+ invalid("Named image IDs must be unique.");
187
+ ids.add(image.id);
188
+ }
189
+ }
190
+ const references = [...imageReferences(value.state), ...questionImageReferences(value.questions)];
191
+ for (const id of references)
192
+ if (!ids.has(id))
193
+ invalid("Every image reference must name an image descriptor in images.");
194
+ for (const id of ids)
195
+ if (!references.includes(id))
196
+ invalid("Every named image must be referenced in state, instructions or criteria.");
197
+ if (value.mode === "web_grounding" &&
198
+ Object.values(value.questions).some((question) => isRecord(question) && question.type === "locate") &&
199
+ typeof value.state !== "string")
200
+ invalid("web grounding with locate requires a string state.");
201
+ if (Buffer.byteLength(JSON.stringify(value)) > 2 * 1024 * 1024)
68
202
  invalid("Classification text and questions must be at most 2 MiB.");
69
203
  return value;
70
204
  }
71
205
  function validateJson(value, depth) {
72
206
  if (depth > 32)
73
- invalid("state must be at most 32 levels deep.");
207
+ invalid("JSON content must be at most 32 levels deep.");
208
+ if (isImageReference(value)) {
209
+ if (Object.keys(value).length !== 1 || typeof value.$image !== "string" || !imageId.test(value.$image))
210
+ invalid("An image reference must be exactly {$image: id} with a 1–64 character image ID.");
211
+ return;
212
+ }
74
213
  if (value === null || typeof value === "string" || typeof value === "boolean")
75
214
  return;
76
215
  if (typeof value === "number" && Number.isFinite(value))
@@ -80,14 +219,12 @@ function validateJson(value, depth) {
80
219
  validateJson(entry, depth + 1);
81
220
  return;
82
221
  }
83
- if (isRecord(value) &&
84
- (Object.getPrototypeOf(value) === Object.prototype ||
85
- Object.getPrototypeOf(value) === null)) {
222
+ if (isRecord(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
86
223
  for (const entry of Object.values(value))
87
224
  validateJson(entry, depth + 1);
88
225
  return;
89
226
  }
90
- invalid("state must contain only finite JSON values.");
227
+ invalid("Content must contain only finite JSON values.");
91
228
  }
92
229
  export function hasBox(questions) {
93
230
  return Object.values(questions).some((question) => question.type === "box");
package/package.json CHANGED
@@ -1,14 +1,22 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-classifier",
3
- "version": "0.3.0",
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.",
3
+ "version": "0.5.0",
4
+ "description": "Config-driven typed classification and extraction for Pi via Microsoft Foundry, OpenAI Decisions, Perplexity, Sarvam, TypeSafe Jev, Liquid, Cloudflare Clef and Clairic, Gemini, Inception, Parallel, OpenRouter, Vercel and local System One runtimes.",
5
5
  "keywords": [
6
6
  "pi-package",
7
7
  "pi",
8
8
  "classifier",
9
9
  "decisions",
10
+ "sarvam",
11
+ "gemini",
12
+ "inception",
13
+ "parallel",
14
+ "openrouter",
10
15
  "jev",
11
- "clef"
16
+ "liquid",
17
+ "clef",
18
+ "clairic",
19
+ "mcp"
12
20
  ],
13
21
  "license": "Apache-2.0",
14
22
  "repository": {
@@ -26,6 +34,9 @@
26
34
  "sideEffects": false,
27
35
  "main": "./dist/index.js",
28
36
  "types": "./dist/index.d.ts",
37
+ "bin": {
38
+ "pi-classifier-mcp": "./dist/mcp-cli.js"
39
+ },
29
40
  "exports": {
30
41
  ".": {
31
42
  "types": "./dist/index.d.ts",
@@ -34,6 +45,14 @@
34
45
  "./extension": {
35
46
  "types": "./dist/extension.d.ts",
36
47
  "import": "./dist/extension.js"
48
+ },
49
+ "./durable": {
50
+ "types": "./dist/durable.d.ts",
51
+ "import": "./dist/durable.js"
52
+ },
53
+ "./mcp": {
54
+ "types": "./dist/mcp-server.d.ts",
55
+ "import": "./dist/mcp-server.js"
37
56
  }
38
57
  },
39
58
  "files": [
@@ -41,6 +60,7 @@
41
60
  "src",
42
61
  "CHANGELOG.md",
43
62
  "README.md",
63
+ "COMPUTER_USE.md",
44
64
  "LICENSE",
45
65
  "THIRD_PARTY_NOTICES.md"
46
66
  ],
@@ -59,16 +79,24 @@
59
79
  },
60
80
  "dependencies": {
61
81
  "@amaster.ai/pi-shared": "^0.1.10",
82
+ "@modelcontextprotocol/sdk": "1.32.1",
62
83
  "sharp": "^0.35.5"
63
84
  },
64
85
  "peerDependencies": {
65
86
  "@earendil-works/pi-coding-agent": ">=1.2.0",
87
+ "@earendil-works/pi-durable": "1.1.0",
66
88
  "typebox": "*"
67
89
  },
90
+ "peerDependenciesMeta": {
91
+ "@earendil-works/pi-durable": {
92
+ "optional": true
93
+ }
94
+ },
68
95
  "devDependencies": {
69
96
  "@earendil-works/pi-coding-agent": "1.2.0",
97
+ "@earendil-works/pi-durable": "1.1.0",
98
+ "@types/node": "^22.0.0",
70
99
  "typebox": "*",
71
- "typescript": "^5.9.3",
72
- "@types/node": "^22.0.0"
100
+ "typescript": "^5.9.3"
73
101
  }
74
102
  }
package/src/auth.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { readStoredCredential } from "@earendil-works/pi-coding-agent";
2
2
  import { ClassifierError, type ResolvedModel } from "./types.js";
3
3
 
4
+ /** Where provider credentials may come from. Desktop keeps the "pi-store" default; the native Durable factory uses "explicit" only. */
5
+ export type CredentialSource = "pi-store" | "explicit";
6
+
4
7
  /** Read the API-key entry only. Never resolve OAuth or mutate Pi's login state. */
5
8
  export function storedApiCredential(provider: string) {
6
9
  try {
@@ -41,8 +44,19 @@ function storedValue(
41
44
  return missing ? undefined : resolved.trim() || undefined;
42
45
  }
43
46
 
44
- export function resolveApiKey(route: ResolvedModel): string {
47
+ export function resolveApiKey(route: ResolvedModel, source: CredentialSource = "pi-store"): string {
48
+ if (route.authMode === "none") return "";
45
49
  if (route.configuredApiKey) return route.configuredApiKey;
50
+ if (source === "explicit") {
51
+ const key = route.envVar ? process.env[route.envVar]?.trim() : undefined;
52
+ if (!key) {
53
+ throw new ClassifierError(
54
+ "missing_credentials",
55
+ "No API key is configured for the selected classifier. Set providers.<id>.apiKey or the provider environment variable. Pi credential-store lookup is disabled on the explicit native path.",
56
+ );
57
+ }
58
+ return key;
59
+ }
46
60
  const credential = storedApiCredential(route.credentialProvider);
47
61
  const key =
48
62
  storedValue(credential?.key, credential?.env) ??
@@ -56,7 +70,17 @@ export function resolveApiKey(route: ResolvedModel): string {
56
70
  return key;
57
71
  }
58
72
 
59
- export function cloudflareAccountId(configured: string | undefined): string {
73
+ export function cloudflareAccountId(configured: string | undefined, source: CredentialSource = "pi-store"): string {
74
+ if (source === "explicit") {
75
+ const id = configured?.trim() ?? process.env.CLOUDFLARE_ACCOUNT_ID?.trim();
76
+ if (!id || !/^[a-zA-Z0-9_-]+$/.test(id)) {
77
+ throw new ClassifierError(
78
+ "configuration",
79
+ "Cloudflare requires a valid accountId or CLOUDFLARE_ACCOUNT_ID.",
80
+ );
81
+ }
82
+ return id;
83
+ }
60
84
  const stored = configured
61
85
  ? undefined
62
86
  : storedApiCredential("cloudflare-workers-ai");
@@ -0,0 +1,110 @@
1
+ import {
2
+ defineTool,
3
+ type ExtensionAPI,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ renderClassifierBox,
7
+ type ClassifierBoxMode,
8
+ type ClassifierBoxPixelBox,
9
+ } from "./box.js";
10
+ import {
11
+ CLASSIFIER_BOX_TOOL,
12
+ CLASSIFIER_BOX_TOOL_DESCRIPTION,
13
+ boxOutput,
14
+ boxParameters,
15
+ } from "./tool-contracts.js";
16
+ import { ClassifierError, userError } from "./types.js";
17
+
18
+ // Re-exported so existing deep imports from "./box-tool.js" keep working.
19
+ export { boxOutput, boxParameters };
20
+
21
+ // Box parameters and result schemas are shared with the native Durable factory
22
+ // through ./tool-contracts.js so the two surfaces cannot drift.
23
+
24
+ type BoxToolDetails = {
25
+ mode: ClassifierBoxMode;
26
+ mimeType: "image/png";
27
+ width: number;
28
+ height: number;
29
+ pixelBox: ClassifierBoxPixelBox;
30
+ byteLength: number;
31
+ };
32
+
33
+ export function registerBoxTool(pi: ExtensionAPI): void {
34
+ pi.registerTool(
35
+ defineTool<typeof boxParameters, BoxToolDetails>({
36
+ name: CLASSIFIER_BOX_TOOL,
37
+ label: "Box image",
38
+ description: CLASSIFIER_BOX_TOOL_DESCRIPTION,
39
+ promptSnippet:
40
+ "Render or crop a local image using normalized box coordinates.",
41
+ promptGuidelines: [
42
+ "Use classifier_box_image only for local images inside cwd and normalized boxes between 0 and 1.",
43
+ "A returned box does not by itself confirm that the object exists.",
44
+ ],
45
+ parameters: boxParameters,
46
+ outputSchema: boxOutput,
47
+ annotations: {
48
+ readOnlyHint: true,
49
+ destructiveHint: false,
50
+ openWorldHint: false,
51
+ },
52
+ async execute(_id, params, signal, _onUpdate, ctx) {
53
+ try {
54
+ const result = await renderClassifierBox(params, {
55
+ cwd: ctx.cwd,
56
+ ...(signal ? { signal } : {}),
57
+ });
58
+ const byteLength = Buffer.from(result.data, "base64").byteLength;
59
+ const details: BoxToolDetails = {
60
+ mode: result.mode,
61
+ mimeType: result.mimeType,
62
+ width: result.width,
63
+ height: result.height,
64
+ pixelBox: result.pixelBox,
65
+ byteLength,
66
+ };
67
+ const box = result.pixelBox;
68
+ return {
69
+ content: [
70
+ {
71
+ type: "text",
72
+ text:
73
+ "Rendered " +
74
+ result.mode +
75
+ " box as a " +
76
+ result.width +
77
+ "×" +
78
+ result.height +
79
+ " PNG (" +
80
+ byteLength +
81
+ " bytes). Source pixel box: left=" +
82
+ box.left +
83
+ ", top=" +
84
+ box.top +
85
+ ", width=" +
86
+ box.width +
87
+ ", height=" +
88
+ box.height +
89
+ ". A box is a localization hint, not proof that the object exists.",
90
+ },
91
+ {
92
+ type: "image",
93
+ data: result.data,
94
+ mimeType: result.mimeType,
95
+ },
96
+ ],
97
+ details,
98
+ structuredContent: details,
99
+ };
100
+ } catch (error) {
101
+ console.error(
102
+ "[pi-classifier] box image failed: " +
103
+ (error instanceof ClassifierError ? error.code : "unexpected"),
104
+ );
105
+ throw new Error(userError(error));
106
+ }
107
+ },
108
+ }),
109
+ );
110
+ }