@abhishek944/pi-classifier 0.4.0 → 0.5.1

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 (58) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +269 -31
  3. package/dist/auth.d.ts +4 -2
  4. package/dist/auth.js +18 -2
  5. package/dist/box-tool.d.ts +2 -24
  6. package/dist/box-tool.js +5 -35
  7. package/dist/choices.js +35 -1
  8. package/dist/classify.d.ts +3 -0
  9. package/dist/classify.js +3 -3
  10. package/dist/config.d.ts +140 -3
  11. package/dist/config.js +401 -20
  12. package/dist/cost.js +42 -4
  13. package/dist/durable.d.ts +34 -0
  14. package/dist/durable.js +237 -0
  15. package/dist/extension.d.ts +2 -275
  16. package/dist/extension.js +49 -211
  17. package/dist/extract.d.ts +11 -0
  18. package/dist/extract.js +191 -0
  19. package/dist/http.d.ts +6 -1
  20. package/dist/http.js +64 -28
  21. package/dist/index.d.ts +3 -1
  22. package/dist/index.js +1 -0
  23. package/dist/inputs.d.ts +16 -1
  24. package/dist/inputs.js +421 -14
  25. package/dist/mcp-cli.d.ts +2 -0
  26. package/dist/mcp-cli.js +39 -0
  27. package/dist/mcp-server.d.ts +28 -0
  28. package/dist/mcp-server.js +121 -0
  29. package/dist/mcp-tool-definitions.d.ts +19 -0
  30. package/dist/mcp-tool-definitions.js +64 -0
  31. package/dist/providers.d.ts +1 -0
  32. package/dist/providers.js +1144 -53
  33. package/dist/tool-contracts.d.ts +785 -0
  34. package/dist/tool-contracts.js +530 -0
  35. package/dist/tree.js +1 -1
  36. package/dist/types.d.ts +284 -8
  37. package/dist/validation.js +122 -10
  38. package/package.json +34 -6
  39. package/src/auth.ts +26 -2
  40. package/src/box-tool.ts +12 -47
  41. package/src/choices.ts +42 -1
  42. package/src/classify.ts +6 -4
  43. package/src/config.ts +450 -23
  44. package/src/cost.ts +42 -4
  45. package/src/durable.ts +298 -0
  46. package/src/extension.ts +75 -288
  47. package/src/extract.ts +228 -0
  48. package/src/http.ts +63 -32
  49. package/src/index.ts +15 -0
  50. package/src/inputs.ts +454 -13
  51. package/src/mcp-cli.ts +44 -0
  52. package/src/mcp-server.ts +179 -0
  53. package/src/mcp-tool-definitions.ts +104 -0
  54. package/src/providers.ts +1323 -56
  55. package/src/tool-contracts.ts +785 -0
  56. package/src/tree.ts +1 -1
  57. package/src/types.ts +231 -5
  58. package/src/validation.ts +114 -9
package/src/tree.ts CHANGED
@@ -20,7 +20,7 @@ export async function classifyTree(
20
20
  ): Promise<ClassifierTreeResult> {
21
21
  choicePolicy(options.settings);
22
22
  const input = await loadTreeInput(params, options.cwd, options.signal);
23
- const initial = resolveModel(options.settings);
23
+ const initial = resolveModel(options.settings, undefined, options.credentialSource ?? "pi-store");
24
24
  const result: ClassifierTreeResult = {
25
25
  provider: initial.route,
26
26
  model: initial.model,
package/src/types.ts CHANGED
@@ -1,8 +1,18 @@
1
1
  export type ApiStyle =
2
2
  | "openai-decisions"
3
+ | "openrouter-decisions"
4
+ | "gemini-decisions"
5
+ | "inception-decisions"
6
+ | "parallel-decisions"
7
+ | "local-system-one"
3
8
  | "perplexity-decisions"
9
+ | "sarvam-system-one"
4
10
  | "system-one"
11
+ | "liquid-system-one"
5
12
  | "cloudflare-system-one"
13
+ | "cloudflare-clairic"
14
+ | "openrouter-extractions"
15
+ | "litellm-extraction"
6
16
  | "microsoft-system-one";
7
17
 
8
18
  /** Explicit references are resolved only from the request's named images. */
@@ -13,15 +23,79 @@ export type ImageInput =
13
23
  | { id: string; path: string }
14
24
  | { id: string; url: string };
15
25
 
26
+ export type MediaInput = { type: "audio" | "video"; path: string };
27
+ export type CharSpan = [number, number];
28
+ export type BoxEdges = { top: number; bottom: number; left: number; right: number };
29
+
16
30
  export type Question =
17
31
  | {
18
32
  type: "bool";
19
33
  instructions: QuestionContent;
20
34
  criteria?: { true?: QuestionContent; false?: QuestionContent };
21
35
  }
22
- | { type: "choice"; instructions: QuestionContent; criteria: Record<string, QuestionContent> }
23
- | { type: "score"; instructions: QuestionContent; criteria: QuestionContent[] }
24
- | { type: "box"; instructions: QuestionContent };
36
+ | { type: "choice"; instructions: QuestionContent; criteria: Record<string, QuestionContent>; booleanValues?: boolean }
37
+ | { type: "score"; instructions: QuestionContent; criteria: QuestionContent[]; descriptions?: string[] }
38
+ | { type: "extract"; instructions?: QuestionContent; criteria: Record<string, QuestionContent>; source?: string; threshold?: number; snapToWords?: boolean; debug?: boolean }
39
+ | { type: "box"; instructions: QuestionContent }
40
+ | { type: "locate"; instructions: QuestionContent }
41
+ | { type: "text"; instructions: QuestionContent }
42
+ | { type: "number"; instructions: QuestionContent; unit?: string; range?: CharSpan; step?: number }
43
+ | { type: "date"; instructions: QuestionContent }
44
+ | { type: "spans"; instructions: QuestionContent; max?: number }
45
+ | { type: "boxes"; instructions: QuestionContent; max?: number }
46
+ | { type: "estimate"; instructions: QuestionContent; range: CharSpan; step?: number; unit?: string }
47
+ | { type: "multi_choice"; instructions: QuestionContent; criteria: Record<string, QuestionContent> };
48
+
49
+ export type TextSpan = {
50
+ start: number;
51
+ end: number;
52
+ text: string;
53
+ score: number;
54
+ /** Index into webGrounding.searchResults when the span came from search evidence. */
55
+ searchResult?: number;
56
+ };
57
+
58
+ export type WebSearchResult = {
59
+ title: string;
60
+ url: string;
61
+ snippet: string;
62
+ date?: string;
63
+ lastUpdated?: string;
64
+ };
65
+
66
+ export type WebFetchedResult = {
67
+ title: string;
68
+ url: string;
69
+ snippet: string;
70
+ };
71
+
72
+ export type DecisionCitation = {
73
+ url: string;
74
+ title?: string;
75
+ excerpts?: string[];
76
+ };
77
+
78
+ export type NonTokenCost = {
79
+ currency: "USD";
80
+ webGrounding: {
81
+ status: "estimated_maximum";
82
+ /** One search is requested per question; duplicate queries and failed searches may not be billed. */
83
+ searchesRequested: number;
84
+ searchFeeMaximum: number;
85
+ /** A successful URL fetch is reported by the provider and is billable. */
86
+ successfulFetches: number;
87
+ fetchFee: number;
88
+ totalMaximum: number;
89
+ note: string;
90
+ };
91
+ };
92
+
93
+ export type ProviderCost = {
94
+ currency: "USD";
95
+ total: number;
96
+ source: "provider" | "gateway";
97
+ note?: string;
98
+ };
25
99
 
26
100
  export type Answer =
27
101
  | { type: "bool"; probability: number }
@@ -42,9 +116,31 @@ export type Answer =
42
116
  }
43
117
  | {
44
118
  type: "box";
45
- box: { top: number; bottom: number; left: number; right: number };
119
+ box: BoxEdges;
46
120
  confidence: number;
121
+ found?: number;
122
+ }
123
+ | { type: "locate"; spans: TextSpan[] }
124
+ | { type: "extract"; spans: Record<string, TextSpan[]>; notStated: Record<string, number> }
125
+ | { type: "text"; text: string; span?: CharSpan | null; found?: number; path?: string }
126
+ | { type: "number"; value: number | null; unit?: string | null; text?: string | null; span?: CharSpan | null; found?: number; path?: string }
127
+ | { type: "date"; date: string | null; text?: string | null; span?: CharSpan | null; found?: number; path?: string }
128
+ | {
129
+ type: "spans";
130
+ spans: { text: string; span: CharSpan; found: number }[];
131
+ count: number;
132
+ atLeast: boolean;
133
+ presence: number[];
47
134
  }
135
+ | {
136
+ type: "boxes";
137
+ boxes: { box: BoxEdges; found: number; confidence: number }[];
138
+ count: number;
139
+ atLeast: boolean;
140
+ presence: number[];
141
+ }
142
+ | { type: "estimate"; value: number; interval: CharSpan; unit?: string | null }
143
+ | { type: "multi_choice"; choices: string[]; probabilities: Record<string, number> }
48
144
  | { type: "refusal" }
49
145
  | { type: "no_match" }
50
146
  | { type: "ambiguous" };
@@ -54,6 +150,21 @@ export interface ClassifyParams {
54
150
  questions: Record<string, Question>;
55
151
  /** Legacy paths are shared in order. Named images require explicit {$image:id} references. */
56
152
  images?: ImageInput[];
153
+ /** Shared audio/video inputs for providers that document media support. */
154
+ media?: MediaInput[];
155
+ /** OpenAI Decisions input items: messages, function calls/outputs and custom tool calls/outputs. */
156
+ conversation?: unknown[];
157
+ /** Explicit opt-in to Perplexity web search and page fetching. This can upload state text and incur per-search fees. */
158
+ mode?: "web_grounding";
159
+ /** Image detail hint for adapters that publish one; ignored by routes without a documented field. */
160
+ imageDetail?: "auto" | "low" | "high" | "original";
161
+ /** OpenAI-compatible prompt-cache controls; rejected by routes without a documented contract. */
162
+ promptCache?: {
163
+ key?: string;
164
+ mode?: "implicit" | "explicit";
165
+ ttl?: "30m";
166
+ breakpoints?: boolean;
167
+ };
57
168
  }
58
169
 
59
170
  export type ClassificationTreeNode = {
@@ -95,7 +206,7 @@ export type ClassifierTreeResult = {
95
206
  export interface ModelDefinition {
96
207
  id: string;
97
208
  name?: string;
98
- input?: ("text" | "image")[];
209
+ input?: ("text" | "image" | "audio" | "video")[];
99
210
  box?: boolean;
100
211
  }
101
212
 
@@ -116,6 +227,7 @@ export type ClassifierCost =
116
227
  total: number;
117
228
  source: "builtin" | "configured";
118
229
  rates: TokenPricing;
230
+ nonToken?: NonTokenCost;
119
231
  }
120
232
  | {
121
233
  status: "estimated";
@@ -124,6 +236,7 @@ export type ClassifierCost =
124
236
  output: number;
125
237
  total: number;
126
238
  source: "aggregated";
239
+ nonToken?: NonTokenCost;
127
240
  }
128
241
  | {
129
242
  status: "unavailable";
@@ -136,17 +249,32 @@ export type ClassifierCost =
136
249
  | "calculation_overflow";
137
250
  };
138
251
 
252
+ export type RouteLimits = {
253
+ maxQuestions: number;
254
+ maxImages: number;
255
+ maxAudio: number;
256
+ maxVideo: number;
257
+ };
258
+
139
259
  export interface ProviderSettings {
140
260
  apiKey?: string;
141
261
  baseUrl?: string;
142
262
  headers?: Record<string, string>;
143
263
  accountId?: string;
264
+ /** Cloudflare AI Gateway selection; emitted as `cf-aig-gateway-id`. */
265
+ gatewayId?: string;
144
266
  experimentalImages?: boolean;
145
267
  experimentalBox?: boolean;
268
+ /** Microsoft Foundry accepts API-key or Entra bearer credentials on the same endpoint. */
269
+ authMode?: "api-key" | "bearer" | "google-api-key" | "parallel-api-key" | "none";
270
+ /** TypeSafe Jev long-context opt-in; sends `TypeSafe-Danger-Zone-Long-Context: true`. */
271
+ longContext?: boolean;
146
272
  /** Model ID (or Azure deployment name) to explicit token rates. */
147
273
  pricing?: Record<string, TokenPricing>;
148
274
  /** Verified wire choice limit; needed for batching on endpoints without a known limit. */
149
275
  maxChoices?: number;
276
+ /** Verified per-request envelope overrides for custom or account-specific endpoints. */
277
+ limits?: Partial<RouteLimits>;
150
278
  }
151
279
 
152
280
  export interface CustomProviderSettings extends ProviderSettings {
@@ -178,15 +306,24 @@ export interface ResolvedModel {
178
306
  provider: string;
179
307
  model: string;
180
308
  api: ApiStyle;
309
+ /** Provider wire format used by the selected route. */
310
+ mediaFormat: "jev-assets" | "base64-object" | "openrouter-parts";
181
311
  baseUrl: string;
182
312
  headers: Record<string, string>;
313
+ gatewayId?: string;
183
314
  configuredApiKey?: string;
184
315
  credentialProvider: string;
185
316
  envVar?: string;
186
317
  images: boolean;
318
+ audio: boolean;
319
+ video: boolean;
187
320
  box: boolean;
188
321
  experimentalImages: boolean;
322
+ authMode: "api-key" | "bearer" | "subscription-key" | "google-api-key" | "parallel-api-key" | "none";
323
+ longContext: boolean;
189
324
  requestTimeoutMs: number;
325
+ /** Envelope used before a request; values come from verified route contracts or explicit settings. */
326
+ limits: RouteLimits;
190
327
  pricing?: { rates: TokenPricing; source: "builtin" | "configured" };
191
328
  maxChoices?: number;
192
329
  }
@@ -200,10 +337,21 @@ export interface PreparedLocalImage {
200
337
 
201
338
  export type PreparedImage = (PreparedLocalImage | { url: string }) & { id?: string };
202
339
 
340
+ export type PreparedMedia = {
341
+ type: "audio" | "video";
342
+ mimeType: string;
343
+ data: string;
344
+ };
345
+
203
346
  export interface PreparedInput {
204
347
  state: ClassifyParams["state"];
205
348
  questions: Record<string, Question>;
206
349
  images: PreparedImage[];
350
+ media: PreparedMedia[];
351
+ mode?: ClassifyParams["mode"];
352
+ conversation?: ClassifyParams["conversation"];
353
+ imageDetail?: ClassifyParams["imageDetail"];
354
+ promptCache?: ClassifyParams["promptCache"];
207
355
  }
208
356
 
209
357
  export type ClassifierResult = {
@@ -221,7 +369,16 @@ export type ClassifierResult = {
221
369
  providerCalls?: number;
222
370
  /** Estimate for completed requests in this result, not an invoice or total of failed attempts. */
223
371
  cost: ClassifierCost;
372
+ /** Gateway/provider-reported charge when the API exposes one; never substituted for the token estimate. */
373
+ providerCost?: ProviderCost;
374
+ /** Request-wide web evidence returned by grounded Decision APIs such as Parallel. */
375
+ citations?: DecisionCitation[];
224
376
  requestId?: string;
377
+ /** Evidence returned by Perplexity web grounding, with the same order and counts as the provider response. */
378
+ webGrounding?: {
379
+ searchResults: WebSearchResult[];
380
+ fetchedResults?: WebFetchedResult[];
381
+ };
225
382
  attemptedRoutes?: ClassifierRoute[];
226
383
  };
227
384
 
@@ -257,3 +414,72 @@ export function userError(error: unknown): string {
257
414
  ? error.message
258
415
  : "Classification failed unexpectedly. Check the selected provider configuration.";
259
416
  }
417
+
418
+ /** Cloudflare Clairic field specifications. Keys use the provider's documented names. */
419
+ export type ExtractionField = {
420
+ type:
421
+ | "text" | "number" | "compute" | "date" | "time" | "datetime" | "duration"
422
+ | "boolean" | "enum" | "object" | "list" | "estimate" | "forecast";
423
+ instructions?: string;
424
+ nullable?: boolean;
425
+ unit?: string;
426
+ integer?: boolean;
427
+ decimals?: number;
428
+ minimum?: number;
429
+ maximum?: number;
430
+ exclusiveMinimum?: number;
431
+ exclusiveMaximum?: number;
432
+ minLength?: number;
433
+ maxLength?: number;
434
+ pattern?: string;
435
+ enum?: unknown[];
436
+ knowledge?: boolean;
437
+ source_only?: boolean;
438
+ null_threshold?: number;
439
+ properties?: Record<string, ExtractionField>;
440
+ items?: "text" | "number" | "date" | { type: "object"; properties: Record<string, ExtractionField> };
441
+ max_items?: number;
442
+ min?: number | string;
443
+ max?: number | string;
444
+ step?:
445
+ | number
446
+ | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year";
447
+ scale?: "linear" | "log";
448
+ horizon?: number;
449
+ interval?: "step" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year";
450
+ };
451
+
452
+ export type ExtractParams = {
453
+ state?: ClassifyParams["state"];
454
+ fields: Record<string, ExtractionField>;
455
+ images?: (string | { path: string; rotation?: 0 | 90 | 180 | 270 })[];
456
+ documents?: string[];
457
+ referenceDate?: string;
458
+ options?: { includeQuantiles?: boolean; returnStateText?: boolean };
459
+ };
460
+
461
+ export type JsonLike =
462
+ | string
463
+ | number
464
+ | boolean
465
+ | null
466
+ | JsonLike[]
467
+ | { [key: string]: JsonLike };
468
+
469
+ export type ExtractionAnswer = {
470
+ type: string;
471
+ value: JsonLike;
472
+ [key: string]: JsonLike;
473
+ };
474
+
475
+ export type ExtractResult = {
476
+ provider: string;
477
+ model: string;
478
+ answers: Record<string, ExtractionAnswer>;
479
+ truncated: boolean;
480
+ usage?: NonNullable<ClassifierResult["usage"]>;
481
+ cost: ClassifierCost;
482
+ providerCost?: ProviderCost;
483
+ requestId?: string;
484
+ stateText?: string;
485
+ };
package/src/validation.ts CHANGED
@@ -21,21 +21,34 @@ function content(value: unknown, maxLength: number, nonempty = false): boolean {
21
21
  }
22
22
 
23
23
  export function validateParams(value: unknown): ClassifyParams {
24
- if (!isRecord(value) || Object.keys(value).some((key) => !["state", "questions", "images"].includes(key)))
25
- invalid("Expected state, questions and optional images; provider/model are selected in settings.");
24
+ if (!isRecord(value) || Object.keys(value).some((key) => !["state", "questions", "images", "media", "mode", "conversation", "imageDetail", "promptCache"].includes(key)))
25
+ invalid("Expected state, questions and optional images, media, mode, conversation, imageDetail or promptCache; provider/model are selected in settings.");
26
26
  if (!(typeof value.state === "string" || Array.isArray(value.state) || isRecord(value.state)))
27
27
  invalid("state must be text, a JSON object or an array.");
28
28
  validateJson(value.state, 0);
29
29
  if (!isRecord(value.questions)) invalid("questions must be a map keyed by question ID.");
30
30
  const entries = Object.entries(value.questions);
31
- if (entries.length < 1 || entries.length > 32) invalid("Supply between 1 and 32 questions.");
31
+ if (entries.length < 1 || entries.length > 1000) invalid("Supply between 1 and 1000 questions; the selected route enforces its own lower limit.");
32
32
  for (const [id, question] of entries) {
33
33
  if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
34
34
  invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
35
- if (Object.keys(question).some((key) => !["type", "instructions", "criteria"].includes(key)))
36
- invalid("Unknown question field.");
37
- if (!content(question.instructions, 16_384, true))
35
+ const allowed = question.type === "number" || question.type === "estimate"
36
+ ? ["type", "instructions", "unit", "range", "step"]
37
+ : question.type === "spans" || question.type === "boxes"
38
+ ? ["type", "instructions", "max"]
39
+ : question.type === "choice"
40
+ ? ["type", "instructions", "criteria", "booleanValues"]
41
+ : question.type === "score"
42
+ ? ["type", "instructions", "criteria", "descriptions"]
43
+ : question.type === "extract"
44
+ ? ["type", "instructions", "criteria", "source", "threshold", "snapToWords", "debug"]
45
+ : ["type", "instructions", "criteria"];
46
+ if (Object.keys(question).some((key) => !allowed.includes(key)))
47
+ invalid("Unknown question field for " + String(question.type) + ".");
48
+ if (question.type !== "extract" && !content(question.instructions, 16_384, true))
38
49
  invalid("Each question needs non-empty text or ordered text/image-reference instructions, at most 16384 characters/bytes.");
50
+ if (question.type === "extract" && question.instructions !== undefined && !content(question.instructions, 16_384))
51
+ invalid("Extract instructions must be text or ordered text/image-reference content, at most 16384 characters/bytes.");
39
52
  if (question.type === "bool") {
40
53
  if (question.criteria !== undefined && (!isRecord(question.criteria) ||
41
54
  Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) || !content(entry, 4096))))
@@ -45,18 +58,106 @@ export function validateParams(value: unknown): ClassifyParams {
45
58
  const criteria = Object.entries(question.criteria);
46
59
  if (criteria.length < 1 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
47
60
  invalid("choice requires at least one label with a text or image-content description.");
61
+ if (question.booleanValues !== undefined) {
62
+ if (typeof question.booleanValues !== "boolean")
63
+ invalid("choice.booleanValues must be a boolean.");
64
+ if (question.booleanValues && criteria.some(([key]) => key !== "true" && key !== "false"))
65
+ invalid("Boolean-valued choices must use the labels true and false.");
66
+ }
48
67
  } else if (question.type === "score") {
49
68
  if (!Array.isArray(question.criteria) || question.criteria.length < 2 || question.criteria.length > 10 ||
50
69
  question.criteria.some((entry) => !content(entry, 4096, true)))
51
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.");
52
75
  } else if (question.type === "box") {
53
76
  if (question.criteria !== undefined) invalid("box does not accept criteria.");
54
- } else invalid("Question type must be bool, choice, score or box.");
77
+ } else if (question.type === "locate" || question.type === "text" || question.type === "date") {
78
+ if (question.criteria !== undefined) invalid(question.type + " does not accept criteria.");
79
+ } else if (question.type === "spans" || question.type === "boxes") {
80
+ if (question.criteria !== undefined) invalid(question.type + " does not accept criteria.");
81
+ if (question.max !== undefined &&
82
+ (!Number.isSafeInteger(question.max) || (question.max as number) < 1 || (question.max as number) > 64))
83
+ invalid(question.type + ".max must be an integer from 1 to 64.");
84
+ } else if (question.type === "number" || question.type === "estimate") {
85
+ if (question.unit !== undefined && (typeof question.unit !== "string" || question.unit.length > 128))
86
+ invalid("unit must be a string of at most 128 characters.");
87
+ if (question.step !== undefined && (typeof question.step !== "number" || !Number.isFinite(question.step) || question.step <= 0))
88
+ invalid("step must be a positive finite number.");
89
+ const range = question.range;
90
+ if (question.type === "estimate" && !Array.isArray(range))
91
+ invalid("estimate requires a [low, high] range.");
92
+ if (range !== undefined && (!Array.isArray(range) || range.length !== 2 ||
93
+ range.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)) ||
94
+ (range[0] as number) >= (range[1] as number)))
95
+ invalid("range must be a finite [low, high] pair with low below high.");
96
+ } else if (question.type === "extract") {
97
+ if (!isRecord(question.criteria))
98
+ invalid("extract criteria must map field names to descriptions.");
99
+ const criteria = Object.entries(question.criteria);
100
+ if (criteria.length < 1 || criteria.length > 26 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
101
+ invalid("extract requires 1–26 fields with text descriptions.");
102
+ if (question.source !== undefined && (typeof question.source !== "string" || !question.source.trim() || question.source.length > 4096))
103
+ invalid("extract.source must be a non-empty string of at most 4096 characters.");
104
+ if (question.threshold !== undefined && (typeof question.threshold !== "number" || !Number.isFinite(question.threshold) || question.threshold < 0 || question.threshold > 1))
105
+ invalid("extract.threshold must be a number between 0 and 1.");
106
+ if (question.snapToWords !== undefined && typeof question.snapToWords !== "boolean")
107
+ invalid("extract.snapToWords must be a boolean.");
108
+ if (question.debug !== undefined && typeof question.debug !== "boolean")
109
+ invalid("extract.debug must be a boolean.");
110
+ } else if (question.type === "multi_choice") {
111
+ if (!isRecord(question.criteria))
112
+ invalid("multi_choice criteria must map labels to descriptions.");
113
+ const criteria = Object.entries(question.criteria);
114
+ if (criteria.length < 2 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
115
+ invalid("multi_choice requires at least two labels with text or image-content descriptions.");
116
+ } else invalid("Question type must be a supported typed decision or read.");
117
+ }
118
+ if (value.media !== undefined) {
119
+ if (!Array.isArray(value.media))
120
+ invalid("media must be an array of audio/video descriptors.");
121
+ for (const item of value.media) {
122
+ if (!isRecord(item) || (item.type !== "audio" && item.type !== "video") ||
123
+ Object.keys(item).some((key) => key !== "type" && key !== "path") ||
124
+ typeof item.path !== "string" || !item.path.trim() || item.path.length > 4096)
125
+ invalid("Each media descriptor needs a type of audio or video and a local path.");
126
+ }
127
+ }
128
+ if (value.conversation !== undefined) {
129
+ if (!Array.isArray(value.conversation))
130
+ invalid("conversation must be an array of OpenAI Decisions input items.");
131
+ const types = ["message", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output"];
132
+ for (const item of value.conversation) {
133
+ if (!isRecord(item) || typeof item.type !== "string" || !types.includes(item.type))
134
+ invalid("Each conversation item needs a documented OpenAI Decisions input type.");
135
+ }
136
+ }
137
+ if (value.mode !== undefined && value.mode !== "web_grounding")
138
+ invalid("mode must be omitted or \"web_grounding\".");
139
+ if (value.imageDetail !== undefined &&
140
+ (typeof value.imageDetail !== "string" || !["auto", "low", "high", "original"].includes(value.imageDetail)))
141
+ invalid("imageDetail must be auto, low, high or original.");
142
+ if (value.promptCache !== undefined) {
143
+ if (!isRecord(value.promptCache) ||
144
+ Object.keys(value.promptCache).some((key) => !["key", "mode", "ttl", "breakpoints"].includes(key)))
145
+ invalid("promptCache may only set key, mode, ttl and breakpoints.");
146
+ if (value.promptCache.key !== undefined &&
147
+ (typeof value.promptCache.key !== "string" || value.promptCache.key.length < 1 || value.promptCache.key.length > 64))
148
+ invalid("promptCache.key must be 1–64 characters.");
149
+ if (value.promptCache.mode !== undefined &&
150
+ (typeof value.promptCache.mode !== "string" || !["implicit", "explicit"].includes(value.promptCache.mode)))
151
+ invalid("promptCache.mode must be implicit or explicit.");
152
+ if (value.promptCache.ttl !== undefined && value.promptCache.ttl !== "30m")
153
+ invalid("promptCache.ttl may only be 30m.");
154
+ if (value.promptCache.breakpoints !== undefined && typeof value.promptCache.breakpoints !== "boolean")
155
+ invalid("promptCache.breakpoints must be a boolean.");
55
156
  }
56
157
  const ids = new Set<string>();
57
158
  if (value.images !== undefined) {
58
- if (!Array.isArray(value.images) || value.images.length > 8)
59
- invalid("images must contain at most eight local paths or named path/url descriptors; route-specific limits also apply.");
159
+ if (!Array.isArray(value.images) || value.images.length > 128)
160
+ invalid("images must contain at most 128 local paths or named path/url descriptors; route-specific limits also apply.");
60
161
  for (const image of value.images) {
61
162
  if (typeof image === "string") {
62
163
  if (!image.trim() || image.length > 4096) invalid("Image paths must be non-empty, at most 4096 characters.");
@@ -76,6 +177,10 @@ export function validateParams(value: unknown): ClassifyParams {
76
177
  const references = [...imageReferences(value.state), ...questionImageReferences(value.questions as Record<string, Question>)];
77
178
  for (const id of references) if (!ids.has(id)) invalid("Every image reference must name an image descriptor in images.");
78
179
  for (const id of ids) if (!references.includes(id)) invalid("Every named image must be referenced in state, instructions or criteria.");
180
+ if (value.mode === "web_grounding" &&
181
+ Object.values(value.questions).some((question) => isRecord(question) && question.type === "locate") &&
182
+ typeof value.state !== "string")
183
+ invalid("web grounding with locate requires a string state.");
79
184
  if (Buffer.byteLength(JSON.stringify(value)) > 2 * 1024 * 1024)
80
185
  invalid("Classification text and questions must be at most 2 MiB.");
81
186
  return value as unknown as ClassifyParams;