@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
package/src/extension.ts CHANGED
@@ -4,9 +4,28 @@ import {
4
4
  type ExtensionAPI,
5
5
  type ExtensionContext,
6
6
  } from "@earendil-works/pi-coding-agent";
7
- import { Type } from "typebox";
8
7
  import { classify, compareClassifiers } from "./classify.js";
8
+ import { extract } from "./extract.js";
9
+ import {
10
+ CLASSIFY_EXTRACT_TOOL,
11
+ CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
12
+ classifyExtractOutput,
13
+ classifyExtractParameters,
14
+ CLASSIFY_COMPARE_TOOL,
15
+ CLASSIFY_COMPARE_TOOL_DESCRIPTION,
16
+ CLASSIFY_TOOL,
17
+ CLASSIFY_TOOL_DESCRIPTION,
18
+ CLASSIFY_TREE_TOOL,
19
+ CLASSIFY_TREE_TOOL_DESCRIPTION,
20
+ classifyCompareOutput,
21
+ classifyOutput,
22
+ classifyParameters,
23
+ classifyTreeOutput,
24
+ classifyTreeParameters,
25
+ } from "./tool-contracts.js";
9
26
  import { classifyTree } from "./tree.js";
27
+ import { registerBoxTool } from "./box-tool.js";
28
+ import { registerComputerUseTool } from "./computer-use-tool.js";
10
29
  import {
11
30
  configuredRoutes,
12
31
  listModels,
@@ -16,276 +35,39 @@ import {
16
35
  import { updateProjectClassifierSettings } from "./settings-write.js";
17
36
  import { ClassifierError, userError } from "./types.js";
18
37
 
19
- const shortText = Type.String({ maxLength: 4096 });
20
- const question = Type.Union([
21
- Type.Object(
22
- {
23
- type: Type.Literal("bool"),
24
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
25
- criteria: Type.Optional(
26
- Type.Object(
27
- { true: Type.Optional(shortText), false: Type.Optional(shortText) },
28
- { additionalProperties: false },
29
- ),
30
- ),
31
- },
32
- { additionalProperties: false },
33
- ),
34
- Type.Object(
35
- {
36
- type: Type.Literal("choice"),
37
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
38
- criteria: Type.Record(
39
- Type.String({ minLength: 1, maxLength: 128 }),
40
- shortText,
41
- { minProperties: 1 },
42
- ),
43
- },
44
- { additionalProperties: false },
45
- ),
46
- Type.Object(
47
- {
48
- type: Type.Literal("score"),
49
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
50
- criteria: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
51
- minItems: 2,
52
- maxItems: 10,
53
- }),
54
- },
55
- { additionalProperties: false },
56
- ),
57
- Type.Object(
58
- {
59
- type: Type.Literal("box"),
60
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
61
- },
62
- { additionalProperties: false },
63
- ),
64
- ]);
65
-
66
- export const classifyParameters = Type.Object(
67
- {
68
- state: Type.Union(
69
- [
70
- Type.String(),
71
- Type.Record(Type.String(), Type.Unknown()),
72
- Type.Array(Type.Unknown()),
73
- ],
74
- {
75
- description:
76
- "Text or JSON data to classify. All questions refer to this same state.",
77
- },
78
- ),
79
- questions: Type.Record(
80
- Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
81
- question,
82
- { minProperties: 1, maxProperties: 32 },
83
- ),
84
- images: Type.Optional(
85
- Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
86
- maxItems: 5,
87
- description:
88
- "Local PNG/JPEG/WebP files inside cwd, in order. No URLs, symlinks or inline base64. Requires an image-capable model.",
89
- }),
90
- ),
91
- },
92
- { additionalProperties: false },
93
- );
94
-
95
- const tokenPricing = Type.Object({
96
- inputPerMillion: Type.Number({ minimum: 0 }),
97
- outputPerMillion: Type.Number({ minimum: 0 }),
98
- cachedInputPerMillion: Type.Optional(Type.Number({ minimum: 0 })),
99
- cacheWritePerMillion: Type.Optional(Type.Number({ minimum: 0 })),
100
- });
101
-
102
- export const classifyOutput = Type.Object({
103
- provider: Type.String(),
104
- model: Type.String(),
105
- answers: Type.Record(
106
- Type.String(),
107
- Type.Union([
108
- Type.Object({
109
- type: Type.Literal("bool"),
110
- probability: Type.Number({ minimum: 0, maximum: 1 }),
111
- }),
112
- Type.Object({
113
- type: Type.Literal("choice"),
114
- choice: Type.String(),
115
- probabilities: Type.Record(
116
- Type.String(),
117
- Type.Number({ minimum: 0, maximum: 1 }),
118
- ),
119
- confidence: Type.Number({ minimum: 0, maximum: 1 }),
120
- probabilityScope: Type.Optional(Type.Literal("batch")),
121
- noneOfAboveProbability: Type.Optional(
122
- Type.Number({ minimum: 0, maximum: 1 }),
123
- ),
124
- }),
125
- Type.Object({
126
- type: Type.Literal("score"),
127
- score: Type.Number(),
128
- confidence: Type.Number({ minimum: 0, maximum: 1 }),
129
- probabilities: Type.Optional(
130
- Type.Record(Type.String(), Type.Number({ minimum: 0, maximum: 1 })),
131
- ),
132
- }),
133
- Type.Object({
134
- type: Type.Literal("box"),
135
- box: Type.Object({
136
- top: Type.Number(),
137
- bottom: Type.Number(),
138
- left: Type.Number(),
139
- right: Type.Number(),
140
- }),
141
- confidence: Type.Number({ minimum: 0, maximum: 1 }),
142
- }),
143
- Type.Object({ type: Type.Literal("refusal") }),
144
- Type.Object({ type: Type.Literal("no_match") }),
145
- Type.Object({ type: Type.Literal("ambiguous") }),
146
- ]),
147
- ),
148
- providerCalls: Type.Optional(Type.Integer({ minimum: 1 })),
149
- usage: Type.Optional(
150
- Type.Object({
151
- inputTokens: Type.Number(),
152
- outputTokens: Type.Number(),
153
- totalTokens: Type.Number(),
154
- cachedInputTokens: Type.Optional(Type.Number()),
155
- cacheWriteTokens: Type.Optional(Type.Number()),
156
- }),
157
- ),
158
- cost: Type.Union([
159
- Type.Object({
160
- status: Type.Literal("estimated"),
161
- currency: Type.Literal("USD"),
162
- input: Type.Number({ minimum: 0 }),
163
- output: Type.Number({ minimum: 0 }),
164
- total: Type.Number({ minimum: 0 }),
165
- source: Type.Union([Type.Literal("builtin"), Type.Literal("configured")]),
166
- rates: tokenPricing,
167
- }),
168
- Type.Object({
169
- status: Type.Literal("estimated"),
170
- currency: Type.Literal("USD"),
171
- input: Type.Number({ minimum: 0 }),
172
- output: Type.Number({ minimum: 0 }),
173
- total: Type.Number({ minimum: 0 }),
174
- source: Type.Literal("aggregated"),
175
- }),
176
- Type.Object({
177
- status: Type.Literal("unavailable"),
178
- currency: Type.Literal("USD"),
179
- reason: Type.Union([
180
- Type.Literal("unknown_pricing"),
181
- Type.Literal("missing_usage"),
182
- Type.Literal("invalid_usage"),
183
- Type.Literal("missing_cache_pricing"),
184
- Type.Literal("calculation_overflow"),
185
- ]),
186
- }),
187
- ]),
188
- requestId: Type.Optional(Type.String()),
189
- attemptedRoutes: Type.Optional(
190
- Type.Array(Type.Object({ provider: Type.String(), model: Type.String() })),
191
- ),
192
- });
193
-
194
- export const classifyCompareOutput = Type.Object({
195
- cancelled: Type.Boolean(),
196
- results: Type.Array(
197
- Type.Union([
198
- Type.Object({
199
- provider: Type.String(),
200
- model: Type.String(),
201
- durationMs: Type.Number(),
202
- status: Type.Literal("success"),
203
- result: classifyOutput,
204
- }),
205
- Type.Object({
206
- provider: Type.String(),
207
- model: Type.String(),
208
- durationMs: Type.Number(),
209
- status: Type.Literal("error"),
210
- error: Type.Object({ code: Type.String(), message: Type.String() }),
211
- }),
212
- ]),
213
- ),
214
- });
38
+ // Re-exported so existing deep imports from "./extension.js" keep working.
39
+ export {
40
+ classifyCompareOutput,
41
+ classifyOutput,
42
+ classifyParameters,
43
+ classifyTreeOutput,
44
+ classifyTreeParameters,
45
+ classifyExtractOutput,
46
+ classifyExtractParameters,
47
+ };
215
48
 
216
- const classificationTreeNode = Type.Object(
217
- {
218
- id: Type.String({ minLength: 1, maxLength: 128 }),
219
- description: Type.Optional(Type.String({ maxLength: 4096 })),
220
- children: Type.Optional(Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"))),
221
- },
222
- { additionalProperties: false },
223
- );
224
-
225
- export const classifyTreeParameters = Type.Object(
226
- {
227
- state: classifyParameters.properties.state,
228
- tree: Type.Union([
229
- Type.String({
230
- minLength: 1,
231
- maxLength: 4096,
232
- description: "Local UTF-8 JSON file inside cwd; no URLs or symlinks.",
233
- }),
234
- Type.Object(
235
- { roots: Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"), { minItems: 1 }) },
236
- { additionalProperties: false },
237
- ),
238
- ]),
239
- instructions: Type.Optional(Type.String({ minLength: 1, maxLength: 8192 })),
240
- images: classifyParameters.properties.images,
241
- },
242
- { additionalProperties: false, $defs: { ClassificationTreeNode: classificationTreeNode } },
243
- );
244
-
245
- export const classifyTreeOutput = Type.Object({
246
- provider: Type.String(),
247
- model: Type.String(),
248
- status: Type.Union([
249
- Type.Literal("complete"),
250
- Type.Literal("no_match"),
251
- Type.Literal("ambiguous"),
252
- Type.Literal("refusal"),
253
- ]),
254
- levels: Type.Record(Type.String({ pattern: "^Level[1-9][0-9]*$" }), Type.String()),
255
- steps: Type.Array(
256
- Type.Object({
257
- level: Type.Integer({ minimum: 1 }),
258
- id: Type.String(),
259
- source: Type.Union([Type.Literal("automatic"), Type.Literal("model")]),
260
- confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
261
- probabilityScope: Type.Optional(
262
- Type.Union([Type.Literal("siblings"), Type.Literal("batch")]),
263
- ),
264
- noneOfAboveProbability: Type.Optional(
265
- Type.Number({ minimum: 0, maximum: 1 }),
266
- ),
267
- }),
268
- ),
269
- providerCalls: Type.Integer({ minimum: 0 }),
270
- cost: classifyOutput.properties.cost,
271
- usage: classifyOutput.properties.usage,
272
- attemptedRoutes: classifyOutput.properties.attemptedRoutes,
273
- });
49
+ // Tool names, descriptions, parameters and result schemas are shared with the
50
+ // native Durable factory through ./tool-contracts.js so the two surfaces cannot drift.
51
+ // Pi-only registration fields (label, prompt guidance, annotations, outputSchema)
52
+ // stay with these desktop registrations.
274
53
 
275
54
  export default function piClassifier(pi: ExtensionAPI): void {
55
+ registerBoxTool(pi);
56
+ registerComputerUseTool(pi);
276
57
  pi.registerTool(
277
58
  defineTool({
278
- name: "classify",
59
+ name: CLASSIFY_TOOL,
279
60
  label: "Classify",
280
- description:
281
- "Ask a decision model typed questions about text, JSON and supported local images. Returns bool probabilities, choices with probabilities, or scores, plus reported token usage and estimated USD cost (or an explicit unavailable reason). Experimental box answers require explicit Jev configuration. Provider/model are fixed by pi-classifier.default (or legacy defaultProvider/defaultModel); this tool cannot override them. API-key authentication is independent of Codex chat login. Only explicitly configured fallback routes may be used after a missing key or HTTP 401/404/429 before any batch has completed; never after uncertainty, refusals, timeouts or network failures. Use /classifier list or status to inspect configuration.",
61
+ description: CLASSIFY_TOOL_DESCRIPTION,
282
62
  promptSnippet:
283
63
  "Classify text, JSON or supported images into typed probabilistic decisions.",
284
64
  promptGuidelines: [
285
65
  "Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
286
66
  "Treat low confidence as uncertainty, not permission to switch models or retry. Only configured remove_choice_limits with none_of_above_choice permits internal sequential choice batches; this is first-match selection, not a global ranking.",
287
67
  "Handle no_match and ambiguous answers explicitly. probabilityScope=batch and noneOfAboveProbability describe only the winning batch; they are not a full-list probability distribution.",
288
- "Send only data the user intends to share with the configured provider.",
68
+ "Send only data the user intends to share with the configured provider. Web grounding sends question text and the start of state to Perplexity Search and incurs per-search fees.",
69
+ "Liquid reads and estimates are provider-rendered values, not conversions. Spans and locate offsets count Unicode characters; boxes are localization hints, not proof of presence.",
70
+ "Audio and video are accepted only by routes with documented media contracts. Duration and codec compatibility remain provider-owned.",
289
71
  "Ask /classifier status for the active model. Do not change provider settings without user direction.",
290
72
  ],
291
73
  parameters: classifyParameters,
@@ -320,10 +102,9 @@ export default function piClassifier(pi: ExtensionAPI): void {
320
102
 
321
103
  pi.registerTool(
322
104
  defineTool({
323
- name: "classify_compare",
105
+ name: CLASSIFY_COMPARE_TOOL,
324
106
  label: "Compare classifiers",
325
- description:
326
- "Explicitly compare the same typed questions and state using exactly pi-classifier.compare provider/model pairs. Each entry makes potentially billable requests, including multiple requests when choice batching is configured. No fallback, default substitution, provider/model overrides, or default changes. Returns labeled results, duration, usage, estimated USD costs (or unavailable reasons) and safe per-entry failures; cancellation retains completed results and prevents later requests.",
107
+ description: CLASSIFY_COMPARE_TOOL_DESCRIPTION,
327
108
  promptSnippet:
328
109
  "Compare configured decision models only when the user explicitly requests a model comparison.",
329
110
  promptGuidelines: [
@@ -358,10 +139,9 @@ export default function piClassifier(pi: ExtensionAPI): void {
358
139
 
359
140
  pi.registerTool(
360
141
  defineTool({
361
- name: "classify_tree",
142
+ name: CLASSIFY_TREE_TOOL,
362
143
  label: "Classify tree",
363
- description:
364
- "Classify text, JSON or supported images through a nested classification tree. tree is an inline roots/id/description/children object or a local JSON file inside cwd. Choose among siblings, automatically follow sole children without model calls, and return Level1/Level2/etc under levels with per-step provenance, total providerCalls, reported usage and estimated USD cost. NONE, batching and initial fallback follow configured settings; after a successful decision the route is pinned. no_match, ambiguous and refusal retain only the selected prefix. Automatic steps are structural, not model confirmation; greedy traversal is not a global best-path guarantee. No provider/model override or comparison.",
144
+ description: CLASSIFY_TREE_TOOL_DESCRIPTION,
365
145
  promptSnippet: "Classify through a supplied classification tree and return the selected levels.",
366
146
  promptGuidelines: [
367
147
  "Use classify_tree only when the user supplies or requests a classification tree; do not invent category branches.",
@@ -395,6 +175,40 @@ export default function piClassifier(pi: ExtensionAPI): void {
395
175
  }),
396
176
  );
397
177
 
178
+ pi.registerTool(
179
+ defineTool({
180
+ name: CLASSIFY_EXTRACT_TOOL,
181
+ label: "Extract structured fields",
182
+ description: CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
183
+ promptSnippet: "Extract typed fields with Cloudflare Clairic into a caller-defined field contract.",
184
+ promptGuidelines: [
185
+ "Use fields that describe the value you need; do not invent provider field types or keys.",
186
+ "Clairic renders values from text and media. A result is not proof that a fact is correct; use grounded spans and confidence when available.",
187
+ "truncated means generated fields are incomplete or invalid. Do not treat truncated output as complete extraction.",
188
+ "The configured clairic-api route receives state, fields and media. Do not send data the user does not intend to share with Cloudflare.",
189
+ ],
190
+ parameters: classifyExtractParameters,
191
+ outputSchema: classifyExtractOutput,
192
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
193
+ async execute(_id, params, signal, _onUpdate, ctx) {
194
+ try {
195
+ const result = await extract(params, {
196
+ settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
197
+ cwd: ctx.cwd,
198
+ ...(signal ? { signal } : {}),
199
+ });
200
+ return {
201
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
202
+ details: result,
203
+ structuredContent: { ...result },
204
+ };
205
+ } catch (error) {
206
+ throw new Error(userError(error));
207
+ }
208
+ },
209
+ }),
210
+ );
211
+
398
212
  pi.registerCommand("classifier", {
399
213
  description:
400
214
  "Classifier: status, list, reload, use <route> <model>, compare <JSON params>. Use writes trusted project defaults; compare makes potentially billable calls.",
package/src/extract.ts ADDED
@@ -0,0 +1,228 @@
1
+ import { resolveApiKey, type CredentialSource } from "./auth.js";
2
+ import { resolveModel } from "./config.js";
3
+ import { estimateCost, tokenCount } from "./cost.js";
4
+ import { postJson } from "./http.js";
5
+ import { prepareExtractionInput, type PreparedExtractionInput } from "./inputs.js";
6
+ import { unwrapCloudflare } from "./providers.js";
7
+ import {
8
+ ClassifierError,
9
+ isRecord,
10
+ userError,
11
+ type ClassifierCost,
12
+ type ExtractParams,
13
+ type JsonLike,
14
+ type ExtractResult,
15
+ } from "./types.js";
16
+
17
+ export type ExtractOptions = {
18
+ settings: import("./types.js").ClassifierSettings;
19
+ cwd: string;
20
+ signal?: AbortSignal;
21
+ credentialSource?: CredentialSource;
22
+ };
23
+
24
+ const CLAIRIC_LABEL = "Cloudflare Clairic";
25
+ const ANSWER_METADATA = [
26
+ "valid", "complete", "decoder", "tokens", "raw", "retry_input_tokens", "null_recovered",
27
+ "guess", "p_null", "p_null_method", "p_nulls", "confidence", "confidences", "confidence_method", "log_probability",
28
+ "span", "spans", "path", "property_spans", "span_method", "grounding_method", "printed_value", "normalization_method", "failure_reason", "source",
29
+ "unit", "mean", "median", "p10", "p90", "p_below", "p_above", "quantiles", "steps",
30
+ ] as const;
31
+
32
+ function usageFrom(value: unknown): ExtractResult["usage"] {
33
+ if (!isRecord(value)) return undefined;
34
+ const input = tokenCount(value.input_tokens);
35
+ const output = tokenCount(value.output_tokens);
36
+ if (input === undefined || output === undefined) return undefined;
37
+ return { inputTokens: input, outputTokens: output, totalTokens: input + output };
38
+ }
39
+
40
+ function reportedCost(value: unknown): ExtractResult["providerCost"] {
41
+ if (!isRecord(value) || typeof value.cost !== "number" || !Number.isFinite(value.cost) || value.cost < 0)
42
+ return undefined;
43
+ return { currency: "USD", total: value.cost, source: "provider" };
44
+ }
45
+
46
+ function jsonLike(value: unknown): value is JsonLike {
47
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
48
+ if (typeof value === "number") return Number.isFinite(value);
49
+ if (Array.isArray(value)) return value.every(jsonLike);
50
+ if (!isRecord(value)) return false;
51
+ return Object.values(value).every(jsonLike);
52
+ }
53
+
54
+ function parseAnswers(value: unknown, fields: ExtractParams["fields"]): Record<string, ExtractResult["answers"][string]> {
55
+ if (!isRecord(value)) throw new ClassifierError("response", CLAIRIC_LABEL + " returned invalid answers.");
56
+ const answers: Record<string, ExtractResult["answers"][string]> = Object.create(null);
57
+ for (const name of Object.keys(fields)) {
58
+ const answer = Object.hasOwn(value, name) ? value[name] : undefined;
59
+ if (!isRecord(answer) || typeof answer.type !== "string" || !Object.hasOwn(answer, "value"))
60
+ throw new ClassifierError("response", CLAIRIC_LABEL + " returned an invalid answer for " + name + ".");
61
+ if (!jsonLike(answer.value))
62
+ throw new ClassifierError("response", CLAIRIC_LABEL + " returned a non-JSON value for " + name + ".");
63
+ const parsed: ExtractResult["answers"][string] = { type: answer.type, value: answer.value };
64
+ for (const field of ANSWER_METADATA) {
65
+ const metadata = answer[field];
66
+ if (metadata !== undefined && jsonLike(metadata)) parsed[field] = metadata;
67
+ }
68
+ answers[name] = parsed;
69
+ }
70
+ return answers;
71
+ }
72
+
73
+ /** Cloudflare Clairic structured extraction through the configured clairic-api route. */
74
+ export async function extract(params: unknown, options: ExtractOptions): Promise<ExtractResult> {
75
+ if (params === null || typeof params !== "object" || Array.isArray(params))
76
+ throw new ClassifierError("input", "extract requires an object with fields and optional state/media.");
77
+ const input = params as ExtractParams;
78
+ if (options.signal?.aborted)
79
+ throw new ClassifierError("aborted", "Extraction was cancelled.");
80
+ const route = resolveModel(options.settings, undefined, options.credentialSource ?? "pi-store");
81
+ const apiKey = route.authMode === "none" ? "" : resolveApiKey(route, options.credentialSource ?? "pi-store");
82
+ const prepared = await prepareExtractionInput(
83
+ input,
84
+ route,
85
+ options.cwd,
86
+ options.signal,
87
+ );
88
+ if (options.signal?.aborted)
89
+ throw new ClassifierError("aborted", "Extraction was cancelled.");
90
+ if (route.api === "openrouter-extractions")
91
+ return extractWithOpenRouter(route, prepared, apiKey, options.signal);
92
+ if (route.api === "litellm-extraction")
93
+ return extractWithLiteLLM(route, prepared, apiKey, options.signal);
94
+ const payload: Record<string, unknown> = {
95
+ model: "clairic",
96
+ fields: prepared.fields,
97
+ };
98
+ if (prepared.state !== "") payload.state = prepared.state;
99
+ if (prepared.referenceDate !== undefined) payload.reference_date = prepared.referenceDate;
100
+ if (prepared.options !== undefined) {
101
+ // Public callers use camelCase; Clairic's wire contract uses snake_case.
102
+ const wireOptions: Record<string, boolean> = {};
103
+ if (prepared.options.includeQuantiles !== undefined)
104
+ wireOptions.include_quantiles = prepared.options.includeQuantiles;
105
+ if (prepared.options.returnStateText !== undefined)
106
+ wireOptions.return_state_text = prepared.options.returnStateText;
107
+ if (Object.keys(wireOptions).length > 0) payload.options = wireOptions;
108
+ }
109
+ if (prepared.images.length)
110
+ payload.images = prepared.images.map((image) => ({
111
+ content_type: image.mimeType,
112
+ base64: image.data,
113
+ ...(image.rotation !== undefined ? { rotation: image.rotation } : {}),
114
+ }));
115
+ if (prepared.documents.length)
116
+ payload.documents = prepared.documents.map((document) => ({
117
+ content_type: document.mimeType,
118
+ base64: document.data,
119
+ }));
120
+ const { body, requestId } = await postJson(
121
+ route,
122
+ "run/" + route.model,
123
+ payload,
124
+ apiKey,
125
+ options.signal,
126
+ );
127
+ const result = unwrapCloudflare(CLAIRIC_LABEL, body);
128
+ return finalizeExtraction(route, result, prepared, costOf(route, result.usage), requestId);
129
+ }
130
+
131
+ function costOf(route: import("./types.js").ResolvedModel, usage: unknown): ClassifierCost {
132
+ return estimateCost(route, usage);
133
+ }
134
+
135
+ function finalizeExtraction(
136
+ route: import("./types.js").ResolvedModel,
137
+ result: Record<string, unknown>,
138
+ prepared: PreparedExtractionInput,
139
+ cost: ClassifierCost,
140
+ requestId?: string,
141
+ providerCost?: ExtractResult["providerCost"],
142
+ stateText?: string,
143
+ ): ExtractResult {
144
+ if (typeof result.truncated !== "boolean")
145
+ throw new ClassifierError("response", "Extraction did not report whether output was truncated.");
146
+ const extracted: ExtractResult = {
147
+ provider: route.route,
148
+ model: route.model,
149
+ answers: parseAnswers(result.answers, prepared.fields),
150
+ truncated: result.truncated,
151
+ cost,
152
+ };
153
+ const usage = usageFrom(result.usage);
154
+ if (usage !== undefined) extracted.usage = usage;
155
+ if (requestId !== undefined) extracted.requestId = requestId;
156
+ if (providerCost !== undefined) extracted.providerCost = providerCost;
157
+ const text = stateText ?? (prepared.options?.returnStateText && typeof result.state_text === "string" ? result.state_text : undefined);
158
+ if (text !== undefined) extracted.stateText = text;
159
+ if (Buffer.byteLength(JSON.stringify(extracted, null, 2)) > 40 * 1024)
160
+ throw new ClassifierError("response", "Extraction result exceeds the 40 KiB tool output limit. Ask for fewer or smaller fields.");
161
+ return extracted;
162
+ }
163
+
164
+ function extractionOptions(prepared: PreparedExtractionInput): Record<string, boolean> | undefined {
165
+ if (prepared.options === undefined) return undefined;
166
+ const wire: Record<string, boolean> = {};
167
+ if (prepared.options.includeQuantiles !== undefined) wire.include_quantiles = prepared.options.includeQuantiles;
168
+ if (prepared.options.returnStateText !== undefined) wire.return_state_text = prepared.options.returnStateText;
169
+ return Object.keys(wire).length > 0 ? wire : undefined;
170
+ }
171
+
172
+ async function extractWithOpenRouter(
173
+ route: import("./types.js").ResolvedModel,
174
+ prepared: PreparedExtractionInput,
175
+ apiKey: string,
176
+ signal?: AbortSignal,
177
+ ): Promise<ExtractResult> {
178
+ const payload: Record<string, unknown> = { model: route.model, fields: prepared.fields };
179
+ const media = [
180
+ ...prepared.images.map((image) => ({
181
+ type: "image",
182
+ format: image.mimeType === "image/png" ? "png" : image.mimeType === "image/jpeg" ? "jpg" : "webp",
183
+ data_base64: image.data,
184
+ })),
185
+ ...prepared.documents.map((document) => ({ type: "document", format: "pdf", data_base64: document.data })),
186
+ ];
187
+ const refs = media.map((_, index) => "asset-" + index);
188
+ let state = typeof prepared.state === "string" ? prepared.state : JSON.stringify(prepared.state);
189
+ if (refs.length > 0 && state !== "") state = state + "\n" + refs.join(" ");
190
+ if (state !== "") payload.state = state;
191
+ if (refs.length > 0)
192
+ payload.assets = Object.fromEntries(media.map((entry, index) => [refs[index], entry]));
193
+ if (prepared.referenceDate !== undefined) payload.reference_date = prepared.referenceDate;
194
+ const options = extractionOptions(prepared);
195
+ if (options)
196
+ payload.provider = { options: { cloudflare: options } };
197
+ const { body, requestId } = await postJson(route, "alpha/extractions", payload, apiKey, signal);
198
+ if (!isRecord(body)) throw new ClassifierError("response", "OpenRouter Extractions returned an unexpected response.");
199
+ return finalizeExtraction(
200
+ route,
201
+ body,
202
+ prepared,
203
+ estimateCost(route, body.usage),
204
+ requestId,
205
+ reportedCost(body.usage),
206
+ );
207
+ }
208
+
209
+ async function extractWithLiteLLM(
210
+ route: import("./types.js").ResolvedModel,
211
+ prepared: PreparedExtractionInput,
212
+ apiKey: string,
213
+ signal?: AbortSignal,
214
+ ): Promise<ExtractResult> {
215
+ const payload: Record<string, unknown> = { model: route.model, fields: prepared.fields };
216
+ if (prepared.state !== "") payload.state = prepared.state;
217
+ if (prepared.referenceDate !== undefined) payload.reference_date = prepared.referenceDate;
218
+ const options = extractionOptions(prepared);
219
+ if (options) payload.options = options;
220
+ if (prepared.images.length)
221
+ payload.images = prepared.images.map((image) => ({ content_type: image.mimeType, base64: image.data }));
222
+ const { body, requestId, costHeader } = await postJson(route, "extraction", payload, apiKey, signal);
223
+ if (!isRecord(body)) throw new ClassifierError("response", "LiteLLM extraction returned an unexpected response.");
224
+ const providerCost = costHeader ? { currency: "USD" as const, total: Number(costHeader), source: "gateway" as const } : undefined;
225
+ return finalizeExtraction(route, body, prepared, estimateCost(route, body.usage), requestId, providerCost);
226
+ }
227
+
228
+ export { userError };