@abhishek944/pi-classifier 0.4.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 (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 +32 -5
  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/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type ApiStyle = "openai-decisions" | "perplexity-decisions" | "system-one" | "cloudflare-system-one" | "microsoft-system-one";
1
+ export type ApiStyle = "openai-decisions" | "openrouter-decisions" | "gemini-decisions" | "inception-decisions" | "parallel-decisions" | "local-system-one" | "perplexity-decisions" | "sarvam-system-one" | "system-one" | "liquid-system-one" | "cloudflare-system-one" | "cloudflare-clairic" | "openrouter-extractions" | "litellm-extraction" | "microsoft-system-one";
2
2
  /** Explicit references are resolved only from the request's named images. */
3
3
  export type ImageReference = {
4
4
  $image: string;
@@ -11,6 +11,17 @@ export type ImageInput = string | {
11
11
  id: string;
12
12
  url: string;
13
13
  };
14
+ export type MediaInput = {
15
+ type: "audio" | "video";
16
+ path: string;
17
+ };
18
+ export type CharSpan = [number, number];
19
+ export type BoxEdges = {
20
+ top: number;
21
+ bottom: number;
22
+ left: number;
23
+ right: number;
24
+ };
14
25
  export type Question = {
15
26
  type: "bool";
16
27
  instructions: QuestionContent;
@@ -22,13 +33,101 @@ export type Question = {
22
33
  type: "choice";
23
34
  instructions: QuestionContent;
24
35
  criteria: Record<string, QuestionContent>;
36
+ booleanValues?: boolean;
25
37
  } | {
26
38
  type: "score";
27
39
  instructions: QuestionContent;
28
40
  criteria: QuestionContent[];
41
+ descriptions?: string[];
42
+ } | {
43
+ type: "extract";
44
+ instructions?: QuestionContent;
45
+ criteria: Record<string, QuestionContent>;
46
+ source?: string;
47
+ threshold?: number;
48
+ snapToWords?: boolean;
49
+ debug?: boolean;
29
50
  } | {
30
51
  type: "box";
31
52
  instructions: QuestionContent;
53
+ } | {
54
+ type: "locate";
55
+ instructions: QuestionContent;
56
+ } | {
57
+ type: "text";
58
+ instructions: QuestionContent;
59
+ } | {
60
+ type: "number";
61
+ instructions: QuestionContent;
62
+ unit?: string;
63
+ range?: CharSpan;
64
+ step?: number;
65
+ } | {
66
+ type: "date";
67
+ instructions: QuestionContent;
68
+ } | {
69
+ type: "spans";
70
+ instructions: QuestionContent;
71
+ max?: number;
72
+ } | {
73
+ type: "boxes";
74
+ instructions: QuestionContent;
75
+ max?: number;
76
+ } | {
77
+ type: "estimate";
78
+ instructions: QuestionContent;
79
+ range: CharSpan;
80
+ step?: number;
81
+ unit?: string;
82
+ } | {
83
+ type: "multi_choice";
84
+ instructions: QuestionContent;
85
+ criteria: Record<string, QuestionContent>;
86
+ };
87
+ export type TextSpan = {
88
+ start: number;
89
+ end: number;
90
+ text: string;
91
+ score: number;
92
+ /** Index into webGrounding.searchResults when the span came from search evidence. */
93
+ searchResult?: number;
94
+ };
95
+ export type WebSearchResult = {
96
+ title: string;
97
+ url: string;
98
+ snippet: string;
99
+ date?: string;
100
+ lastUpdated?: string;
101
+ };
102
+ export type WebFetchedResult = {
103
+ title: string;
104
+ url: string;
105
+ snippet: string;
106
+ };
107
+ export type DecisionCitation = {
108
+ url: string;
109
+ title?: string;
110
+ excerpts?: string[];
111
+ };
112
+ export type NonTokenCost = {
113
+ currency: "USD";
114
+ webGrounding: {
115
+ status: "estimated_maximum";
116
+ /** One search is requested per question; duplicate queries and failed searches may not be billed. */
117
+ searchesRequested: number;
118
+ searchFeeMaximum: number;
119
+ /** A successful URL fetch is reported by the provider and is billable. */
120
+ successfulFetches: number;
121
+ fetchFee: number;
122
+ totalMaximum: number;
123
+ note: string;
124
+ };
125
+ };
126
+ export type ProviderCost = {
127
+ currency: "USD";
128
+ total: number;
129
+ source: "provider" | "gateway";
130
+ note?: string;
32
131
  };
33
132
  export type Answer = {
34
133
  type: "bool";
@@ -48,13 +147,66 @@ export type Answer = {
48
147
  probabilities?: Record<string, number>;
49
148
  } | {
50
149
  type: "box";
51
- box: {
52
- top: number;
53
- bottom: number;
54
- left: number;
55
- right: number;
56
- };
150
+ box: BoxEdges;
57
151
  confidence: number;
152
+ found?: number;
153
+ } | {
154
+ type: "locate";
155
+ spans: TextSpan[];
156
+ } | {
157
+ type: "extract";
158
+ spans: Record<string, TextSpan[]>;
159
+ notStated: Record<string, number>;
160
+ } | {
161
+ type: "text";
162
+ text: string;
163
+ span?: CharSpan | null;
164
+ found?: number;
165
+ path?: string;
166
+ } | {
167
+ type: "number";
168
+ value: number | null;
169
+ unit?: string | null;
170
+ text?: string | null;
171
+ span?: CharSpan | null;
172
+ found?: number;
173
+ path?: string;
174
+ } | {
175
+ type: "date";
176
+ date: string | null;
177
+ text?: string | null;
178
+ span?: CharSpan | null;
179
+ found?: number;
180
+ path?: string;
181
+ } | {
182
+ type: "spans";
183
+ spans: {
184
+ text: string;
185
+ span: CharSpan;
186
+ found: number;
187
+ }[];
188
+ count: number;
189
+ atLeast: boolean;
190
+ presence: number[];
191
+ } | {
192
+ type: "boxes";
193
+ boxes: {
194
+ box: BoxEdges;
195
+ found: number;
196
+ confidence: number;
197
+ }[];
198
+ count: number;
199
+ atLeast: boolean;
200
+ presence: number[];
201
+ } | {
202
+ type: "estimate";
203
+ value: number;
204
+ interval: CharSpan;
205
+ unit?: string | null;
206
+ } | {
207
+ type: "multi_choice";
208
+ choices: string[];
209
+ probabilities: Record<string, number>;
58
210
  } | {
59
211
  type: "refusal";
60
212
  } | {
@@ -67,6 +219,21 @@ export interface ClassifyParams {
67
219
  questions: Record<string, Question>;
68
220
  /** Legacy paths are shared in order. Named images require explicit {$image:id} references. */
69
221
  images?: ImageInput[];
222
+ /** Shared audio/video inputs for providers that document media support. */
223
+ media?: MediaInput[];
224
+ /** OpenAI Decisions input items: messages, function calls/outputs and custom tool calls/outputs. */
225
+ conversation?: unknown[];
226
+ /** Explicit opt-in to Perplexity web search and page fetching. This can upload state text and incur per-search fees. */
227
+ mode?: "web_grounding";
228
+ /** Image detail hint for adapters that publish one; ignored by routes without a documented field. */
229
+ imageDetail?: "auto" | "low" | "high" | "original";
230
+ /** OpenAI-compatible prompt-cache controls; rejected by routes without a documented contract. */
231
+ promptCache?: {
232
+ key?: string;
233
+ mode?: "implicit" | "explicit";
234
+ ttl?: "30m";
235
+ breakpoints?: boolean;
236
+ };
70
237
  }
71
238
  export type ClassificationTreeNode = {
72
239
  id: string;
@@ -104,7 +271,7 @@ export type ClassifierTreeResult = {
104
271
  export interface ModelDefinition {
105
272
  id: string;
106
273
  name?: string;
107
- input?: ("text" | "image")[];
274
+ input?: ("text" | "image" | "audio" | "video")[];
108
275
  box?: boolean;
109
276
  }
110
277
  /** USD per million tokens. Cache counts, when reported, are part of input tokens. */
@@ -122,6 +289,7 @@ export type ClassifierCost = {
122
289
  total: number;
123
290
  source: "builtin" | "configured";
124
291
  rates: TokenPricing;
292
+ nonToken?: NonTokenCost;
125
293
  } | {
126
294
  status: "estimated";
127
295
  currency: "USD";
@@ -129,22 +297,37 @@ export type ClassifierCost = {
129
297
  output: number;
130
298
  total: number;
131
299
  source: "aggregated";
300
+ nonToken?: NonTokenCost;
132
301
  } | {
133
302
  status: "unavailable";
134
303
  currency: "USD";
135
304
  reason: "unknown_pricing" | "missing_usage" | "invalid_usage" | "missing_cache_pricing" | "calculation_overflow";
136
305
  };
306
+ export type RouteLimits = {
307
+ maxQuestions: number;
308
+ maxImages: number;
309
+ maxAudio: number;
310
+ maxVideo: number;
311
+ };
137
312
  export interface ProviderSettings {
138
313
  apiKey?: string;
139
314
  baseUrl?: string;
140
315
  headers?: Record<string, string>;
141
316
  accountId?: string;
317
+ /** Cloudflare AI Gateway selection; emitted as `cf-aig-gateway-id`. */
318
+ gatewayId?: string;
142
319
  experimentalImages?: boolean;
143
320
  experimentalBox?: boolean;
321
+ /** Microsoft Foundry accepts API-key or Entra bearer credentials on the same endpoint. */
322
+ authMode?: "api-key" | "bearer" | "google-api-key" | "parallel-api-key" | "none";
323
+ /** TypeSafe Jev long-context opt-in; sends `TypeSafe-Danger-Zone-Long-Context: true`. */
324
+ longContext?: boolean;
144
325
  /** Model ID (or Azure deployment name) to explicit token rates. */
145
326
  pricing?: Record<string, TokenPricing>;
146
327
  /** Verified wire choice limit; needed for batching on endpoints without a known limit. */
147
328
  maxChoices?: number;
329
+ /** Verified per-request envelope overrides for custom or account-specific endpoints. */
330
+ limits?: Partial<RouteLimits>;
148
331
  }
149
332
  export interface CustomProviderSettings extends ProviderSettings {
150
333
  api: ApiStyle;
@@ -172,15 +355,24 @@ export interface ResolvedModel {
172
355
  provider: string;
173
356
  model: string;
174
357
  api: ApiStyle;
358
+ /** Provider wire format used by the selected route. */
359
+ mediaFormat: "jev-assets" | "base64-object" | "openrouter-parts";
175
360
  baseUrl: string;
176
361
  headers: Record<string, string>;
362
+ gatewayId?: string;
177
363
  configuredApiKey?: string;
178
364
  credentialProvider: string;
179
365
  envVar?: string;
180
366
  images: boolean;
367
+ audio: boolean;
368
+ video: boolean;
181
369
  box: boolean;
182
370
  experimentalImages: boolean;
371
+ authMode: "api-key" | "bearer" | "subscription-key" | "google-api-key" | "parallel-api-key" | "none";
372
+ longContext: boolean;
183
373
  requestTimeoutMs: number;
374
+ /** Envelope used before a request; values come from verified route contracts or explicit settings. */
375
+ limits: RouteLimits;
184
376
  pricing?: {
185
377
  rates: TokenPricing;
186
378
  source: "builtin" | "configured";
@@ -198,10 +390,20 @@ export type PreparedImage = (PreparedLocalImage | {
198
390
  }) & {
199
391
  id?: string;
200
392
  };
393
+ export type PreparedMedia = {
394
+ type: "audio" | "video";
395
+ mimeType: string;
396
+ data: string;
397
+ };
201
398
  export interface PreparedInput {
202
399
  state: ClassifyParams["state"];
203
400
  questions: Record<string, Question>;
204
401
  images: PreparedImage[];
402
+ media: PreparedMedia[];
403
+ mode?: ClassifyParams["mode"];
404
+ conversation?: ClassifyParams["conversation"];
405
+ imageDetail?: ClassifyParams["imageDetail"];
406
+ promptCache?: ClassifyParams["promptCache"];
205
407
  }
206
408
  export type ClassifierResult = {
207
409
  provider: string;
@@ -218,7 +420,16 @@ export type ClassifierResult = {
218
420
  providerCalls?: number;
219
421
  /** Estimate for completed requests in this result, not an invoice or total of failed attempts. */
220
422
  cost: ClassifierCost;
423
+ /** Gateway/provider-reported charge when the API exposes one; never substituted for the token estimate. */
424
+ providerCost?: ProviderCost;
425
+ /** Request-wide web evidence returned by grounded Decision APIs such as Parallel. */
426
+ citations?: DecisionCitation[];
221
427
  requestId?: string;
428
+ /** Evidence returned by Perplexity web grounding, with the same order and counts as the provider response. */
429
+ webGrounding?: {
430
+ searchResults: WebSearchResult[];
431
+ fetchedResults?: WebFetchedResult[];
432
+ };
222
433
  attemptedRoutes?: ClassifierRoute[];
223
434
  };
224
435
  export type ClassifierComparisonEntry = ClassifierRoute & {
@@ -244,3 +455,68 @@ export declare class ClassifierError extends Error {
244
455
  }
245
456
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
246
457
  export declare function userError(error: unknown): string;
458
+ /** Cloudflare Clairic field specifications. Keys use the provider's documented names. */
459
+ export type ExtractionField = {
460
+ type: "text" | "number" | "compute" | "date" | "time" | "datetime" | "duration" | "boolean" | "enum" | "object" | "list" | "estimate" | "forecast";
461
+ instructions?: string;
462
+ nullable?: boolean;
463
+ unit?: string;
464
+ integer?: boolean;
465
+ decimals?: number;
466
+ minimum?: number;
467
+ maximum?: number;
468
+ exclusiveMinimum?: number;
469
+ exclusiveMaximum?: number;
470
+ minLength?: number;
471
+ maxLength?: number;
472
+ pattern?: string;
473
+ enum?: unknown[];
474
+ knowledge?: boolean;
475
+ source_only?: boolean;
476
+ null_threshold?: number;
477
+ properties?: Record<string, ExtractionField>;
478
+ items?: "text" | "number" | "date" | {
479
+ type: "object";
480
+ properties: Record<string, ExtractionField>;
481
+ };
482
+ max_items?: number;
483
+ min?: number | string;
484
+ max?: number | string;
485
+ step?: number | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year";
486
+ scale?: "linear" | "log";
487
+ horizon?: number;
488
+ interval?: "step" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year";
489
+ };
490
+ export type ExtractParams = {
491
+ state?: ClassifyParams["state"];
492
+ fields: Record<string, ExtractionField>;
493
+ images?: (string | {
494
+ path: string;
495
+ rotation?: 0 | 90 | 180 | 270;
496
+ })[];
497
+ documents?: string[];
498
+ referenceDate?: string;
499
+ options?: {
500
+ includeQuantiles?: boolean;
501
+ returnStateText?: boolean;
502
+ };
503
+ };
504
+ export type JsonLike = string | number | boolean | null | JsonLike[] | {
505
+ [key: string]: JsonLike;
506
+ };
507
+ export type ExtractionAnswer = {
508
+ type: string;
509
+ value: JsonLike;
510
+ [key: string]: JsonLike;
511
+ };
512
+ export type ExtractResult = {
513
+ provider: string;
514
+ model: string;
515
+ answers: Record<string, ExtractionAnswer>;
516
+ truncated: boolean;
517
+ usage?: NonNullable<ClassifierResult["usage"]>;
518
+ cost: ClassifierCost;
519
+ providerCost?: ProviderCost;
520
+ requestId?: string;
521
+ stateText?: string;
522
+ };
@@ -16,23 +16,36 @@ function content(value, maxLength, nonempty = false) {
16
16
  (!nonempty || value.some((part) => typeof part !== "string" || Boolean(part.trim())));
17
17
  }
18
18
  export function validateParams(value) {
19
- if (!isRecord(value) || Object.keys(value).some((key) => !["state", "questions", "images"].includes(key)))
20
- invalid("Expected state, questions and optional images; provider/model are selected in settings.");
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
21
  if (!(typeof value.state === "string" || Array.isArray(value.state) || isRecord(value.state)))
22
22
  invalid("state must be text, a JSON object or an array.");
23
23
  validateJson(value.state, 0);
24
24
  if (!isRecord(value.questions))
25
25
  invalid("questions must be a map keyed by question ID.");
26
26
  const entries = Object.entries(value.questions);
27
- if (entries.length < 1 || entries.length > 32)
28
- 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.");
29
29
  for (const [id, question] of entries) {
30
30
  if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
31
31
  invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
32
- if (Object.keys(question).some((key) => !["type", "instructions", "criteria"].includes(key)))
33
- invalid("Unknown question field.");
34
- if (!content(question.instructions, 16_384, true))
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))
35
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.");
36
49
  if (question.type === "bool") {
37
50
  if (question.criteria !== undefined && (!isRecord(question.criteria) ||
38
51
  Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) || !content(entry, 4096))))
@@ -44,23 +57,118 @@ export function validateParams(value) {
44
57
  const criteria = Object.entries(question.criteria);
45
58
  if (criteria.length < 1 || criteria.some(([key, entry]) => !key.trim() || key.length > 128 || !content(entry, 4096)))
46
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
+ }
47
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
  }
53
76
  else if (question.type === "box") {
54
77
  if (question.criteria !== undefined)
55
78
  invalid("box does not accept criteria.");
56
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
+ }
57
126
  else
58
- 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
+ }
147
+ }
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.");
59
167
  }
60
168
  const ids = new Set();
61
169
  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.");
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.");
64
172
  for (const image of value.images) {
65
173
  if (typeof image === "string") {
66
174
  if (!image.trim() || image.length > 4096)
@@ -86,6 +194,10 @@ export function validateParams(value) {
86
194
  for (const id of ids)
87
195
  if (!references.includes(id))
88
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.");
89
201
  if (Buffer.byteLength(JSON.stringify(value)) > 2 * 1024 * 1024)
90
202
  invalid("Classification text and questions must be at most 2 MiB.");
91
203
  return value;
package/package.json CHANGED
@@ -1,14 +1,22 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-classifier",
3
- "version": "0.4.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": [
@@ -60,16 +79,24 @@
60
79
  },
61
80
  "dependencies": {
62
81
  "@amaster.ai/pi-shared": "^0.1.10",
82
+ "@modelcontextprotocol/sdk": "1.32.1",
63
83
  "sharp": "^0.35.5"
64
84
  },
65
85
  "peerDependencies": {
66
86
  "@earendil-works/pi-coding-agent": ">=1.2.0",
87
+ "@earendil-works/pi-durable": "1.1.0",
67
88
  "typebox": "*"
68
89
  },
90
+ "peerDependenciesMeta": {
91
+ "@earendil-works/pi-durable": {
92
+ "optional": true
93
+ }
94
+ },
69
95
  "devDependencies": {
70
96
  "@earendil-works/pi-coding-agent": "1.2.0",
97
+ "@earendil-works/pi-durable": "1.1.0",
98
+ "@types/node": "^22.0.0",
71
99
  "typebox": "*",
72
- "typescript": "^5.9.3",
73
- "@types/node": "^22.0.0"
100
+ "typescript": "^5.9.3"
74
101
  }
75
102
  }