@abhishek944/pi-classifier 0.5.1 → 0.7.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.
package/dist/config.d.ts CHANGED
@@ -19,10 +19,15 @@ export declare const BUILT_INS: ({
19
19
  baseUrl: string;
20
20
  credentialProvider: string;
21
21
  envVar: string;
22
- models: {
22
+ models: ({
23
23
  id: string;
24
24
  input: ("text" | "image")[];
25
- }[];
25
+ shutdown?: never;
26
+ } | {
27
+ id: string;
28
+ input: "text"[];
29
+ shutdown: string;
30
+ })[];
26
31
  } | {
27
32
  id: string;
28
33
  route: string;
@@ -88,6 +93,7 @@ export declare const BUILT_INS: ({
88
93
  models: {
89
94
  id: string;
90
95
  input: ("text" | "image")[];
96
+ shutdown: string;
91
97
  }[];
92
98
  } | {
93
99
  id: string;
@@ -111,6 +117,39 @@ export declare const BUILT_INS: ({
111
117
  id: string;
112
118
  input: ("text" | "image")[];
113
119
  }[];
120
+ } | {
121
+ id: string;
122
+ route: string;
123
+ api: "subq-system-one";
124
+ baseUrl: string;
125
+ credentialProvider: string;
126
+ envVar: string;
127
+ models: {
128
+ id: string;
129
+ input: ("text" | "image")[];
130
+ }[];
131
+ } | {
132
+ id: string;
133
+ route: string;
134
+ api: "alibaba-system-one";
135
+ baseUrl: string;
136
+ credentialProvider: string;
137
+ envVar: string;
138
+ models: {
139
+ id: string;
140
+ input: ("text" | "image")[];
141
+ }[];
142
+ } | {
143
+ id: string;
144
+ route: string;
145
+ api: "fireworks-system-one";
146
+ baseUrl: string;
147
+ credentialProvider: string;
148
+ envVar: string;
149
+ models: {
150
+ id: string;
151
+ input: "text"[];
152
+ }[];
114
153
  } | {
115
154
  id: string;
116
155
  route: string;
@@ -185,10 +224,17 @@ export declare const BUILT_INS: ({
185
224
  id: string;
186
225
  input: ("text" | "image")[];
187
226
  box: true;
227
+ shutdown?: never;
188
228
  } | {
189
229
  id: string;
190
230
  input: ("audio" | "video" | "text" | "image")[];
191
231
  box?: never;
232
+ shutdown?: never;
233
+ } | {
234
+ id: string;
235
+ input: ("text" | "image")[];
236
+ shutdown: string;
237
+ box?: never;
192
238
  })[];
193
239
  })[];
194
240
  export type OpenRouterExtractionCapabilities = {
package/dist/config.js CHANGED
@@ -73,7 +73,7 @@ export const BUILT_INS = [
73
73
  envVar: "OPENROUTER_API_KEY",
74
74
  models: [
75
75
  { id: "cloudflare/clairic", input: ["text", "image"] },
76
- { id: "inception/mercury-decide", input: ["text"] },
76
+ { id: "inception/mercury-decide", input: ["text"], shutdown: "2026-12-28" },
77
77
  { id: "liquid/d1.2", input: ["text", "image"] },
78
78
  { id: "liquid/d1.2-ultra", input: ["text", "image"] },
79
79
  { id: "perplexity/pplx-decider-v1.3", input: ["text"] },
@@ -90,6 +90,16 @@ export const BUILT_INS = [
90
90
  envVar: "LITELLM_API_KEY",
91
91
  models: [{ id: "clairic", input: ["text", "image"] }],
92
92
  },
93
+ {
94
+ id: "litellm",
95
+ route: "litellm-decisions-api",
96
+ api: "openai-decisions",
97
+ baseUrl: "",
98
+ credentialProvider: "litellm",
99
+ envVar: "LITELLM_API_KEY",
100
+ // The declared alias is LiteLLM's own documentation example; any proxy model_name resolves.
101
+ models: [{ id: "luna", input: ["text"] }],
102
+ },
93
103
  {
94
104
  id: "microsoft",
95
105
  route: "microsoft-api",
@@ -146,6 +156,19 @@ export const BUILT_INS = [
146
156
  { id: "gemini-decision-1", input: ["text", "image", "audio", "video"] },
147
157
  ],
148
158
  },
159
+ {
160
+ id: "opencode-go",
161
+ route: "opencode-go-api",
162
+ api: "system-one",
163
+ baseUrl: "https://opencode.ai/inference/go/systemone/v1",
164
+ credentialProvider: "opencode-go",
165
+ envVar: "OPENCODE_API_KEY",
166
+ models: [
167
+ { id: "jev-1.14", input: ["text"] },
168
+ { id: "gemini-decision-1", input: ["text"] },
169
+ { id: "gpt-6-luna-decision", input: ["text"] },
170
+ ],
171
+ },
149
172
  {
150
173
  id: "inception",
151
174
  route: "inception-api",
@@ -153,7 +176,7 @@ export const BUILT_INS = [
153
176
  baseUrl: "https://api.inceptionlabs.ai/v1",
154
177
  credentialProvider: "inception",
155
178
  envVar: "INCEPTION_API_KEY",
156
- models: [{ id: "mercury-decide", input: ["text", "image"] }],
179
+ models: [{ id: "mercury-decide", input: ["text", "image"], shutdown: "2026-12-28" }],
157
180
  },
158
181
  {
159
182
  id: "parallel",
@@ -182,6 +205,37 @@ export const BUILT_INS = [
182
205
  { id: "pplx-decider-v1-27b", input: ["text", "image"] },
183
206
  ],
184
207
  },
208
+ {
209
+ id: "subq",
210
+ route: "subq-api",
211
+ api: "subq-system-one",
212
+ baseUrl: "https://api.subq.ai",
213
+ credentialProvider: "subq",
214
+ envVar: "SUBQ_API_KEY",
215
+ models: [
216
+ { id: "subq-snap-1.2", input: ["text", "image"] },
217
+ { id: "subq-snap-latest", input: ["text", "image"] },
218
+ ],
219
+ },
220
+ {
221
+ id: "dashscope",
222
+ route: "alibaba-api",
223
+ api: "alibaba-system-one",
224
+ // Decision Model endpoints are workspace- and region-scoped; the operator supplies the gateway host.
225
+ baseUrl: "",
226
+ credentialProvider: "dashscope",
227
+ envVar: "DASHSCOPE_API_KEY",
228
+ models: [{ id: "decision-model", input: ["text", "image"] }],
229
+ },
230
+ {
231
+ id: "fireworks",
232
+ route: "fireworks-api",
233
+ api: "fireworks-system-one",
234
+ baseUrl: "https://api.fireworks.ai/inference/v1",
235
+ credentialProvider: "fireworks",
236
+ envVar: "FIREWORKS_API_KEY",
237
+ models: [{ id: "accounts/fireworks/models/rune", input: ["text"] }],
238
+ },
185
239
  {
186
240
  id: "liquid",
187
241
  route: "liquid-api",
@@ -254,7 +308,7 @@ export const BUILT_INS = [
254
308
  { id: "microsoft/microsoft-decision-1.1", input: ["text", "image"] },
255
309
  { id: "cloudflare/clef-flash", input: ["text", "image"] },
256
310
  { id: "cloudflare/clef-omni", input: ["text", "image", "audio", "video"] },
257
- { id: "inception/mercury-decide", input: ["text", "image"] },
311
+ { id: "inception/mercury-decide", input: ["text", "image"], shutdown: "2026-12-28" },
258
312
  { id: "liquid/d1.2", input: ["text", "image"] },
259
313
  { id: "liquid/d1.2-ultra", input: ["text", "image"] },
260
314
  { id: "openai/gpt-6-luna-decisions", input: ["text", "image"] },
@@ -323,8 +377,18 @@ export function openRouterDecisionCapabilities(model) {
323
377
  return { flexibleImagePlacement: false, box: false, remoteImageUrls: false, images: 0, audio: 0, video: 0 };
324
378
  }
325
379
  function builtInLimits(api, provider, model) {
326
- if (api === "openai-decisions")
380
+ if (api === "openai-decisions") {
381
+ // LiteLLM validates 1-128 questions on both decision routes before calling a provider.
382
+ if (provider === "litellm")
383
+ return { ...DEFAULT_LIMITS, maxQuestions: 128 };
327
384
  return { ...DEFAULT_LIMITS, maxQuestions: 400 };
385
+ }
386
+ if (api === "subq-system-one")
387
+ return { ...DEFAULT_LIMITS, maxQuestions: 128, maxImages: 4, maxAudio: 0, maxVideo: 0 };
388
+ if (api === "alibaba-system-one")
389
+ return { ...DEFAULT_LIMITS, maxQuestions: 16, maxImages: 16, maxAudio: 0, maxVideo: 0 };
390
+ if (api === "fireworks-system-one")
391
+ return { ...DEFAULT_LIMITS, maxQuestions: 256, maxImages: 0, maxAudio: 0, maxVideo: 0 };
328
392
  if (api === "openrouter-extractions") {
329
393
  const caps = openRouterExtractionCapabilities(model);
330
394
  return { ...DEFAULT_LIMITS, maxImages: caps.maxImages, maxAudio: 0, maxVideo: 0 };
@@ -542,6 +606,9 @@ export function resolveModel(settings, selected = configuredDefault(settings), s
542
606
  "openrouter-extractions",
543
607
  "litellm-extraction",
544
608
  "microsoft-system-one",
609
+ "subq-system-one",
610
+ "alibaba-system-one",
611
+ "fireworks-system-one",
545
612
  ].includes(api))
546
613
  return configuration("Unsupported classifier API protocol.");
547
614
  const models = builtIn?.models ?? custom.models;
@@ -588,7 +655,7 @@ export function resolveModel(settings, selected = configuredDefault(settings), s
588
655
  cloudflareAccountId(optionalString(raw.accountId, "accountId"), source) +
589
656
  "/ai";
590
657
  if (!baseUrl)
591
- return configuration("The selected provider requires a baseUrl. Microsoft uses your Foundry resource endpoint; local runtimes use your server URL.");
658
+ return configuration("The selected provider requires a baseUrl. Microsoft uses your Foundry resource endpoint, Alibaba uses your Model Studio workspace gateway host, and local runtimes use your server URL.");
592
659
  const timeout = settings.requestTimeoutMs ?? 30_000;
593
660
  if (!Number.isInteger(timeout) || timeout < 100 || timeout > 300_000)
594
661
  return configuration("requestTimeoutMs must be between 100 and 300000.");
@@ -709,10 +776,27 @@ function knownMaxChoices(route) {
709
776
  const liquid = route.provider === "liquid" &&
710
777
  route.baseUrl === "https://api.liquid.ai/decisions/v1" &&
711
778
  ["d1.2", "d1.2-ultra"].includes(route.model);
779
+ const subq = route.provider === "subq" &&
780
+ route.baseUrl === "https://api.subq.ai" &&
781
+ ["subq-snap-1.2", "subq-snap-latest"].includes(route.model);
782
+ const alibaba = route.api === "alibaba-system-one" &&
783
+ route.provider === "dashscope" &&
784
+ route.model === "decision-model";
785
+ const fireworks = route.provider === "fireworks" &&
786
+ route.baseUrl === "https://api.fireworks.ai/inference/v1" &&
787
+ route.model === "accounts/fireworks/models/rune";
788
+ const litellm = route.route === "litellm-decisions-api";
789
+ if (subq || alibaba || litellm)
790
+ return 255;
791
+ if (fireworks)
792
+ return 208;
712
793
  return directJev || sarvam || openai || perplexity || clef || liquid ? 255 : undefined;
713
794
  }
714
795
  export function listModels(settings) {
715
- const lines = BUILT_INS.flatMap((provider) => provider.models.map((model) => provider.route + " " + model.id));
796
+ const lines = BUILT_INS.flatMap((provider) => provider.models.map((model) => provider.route +
797
+ " " +
798
+ model.id +
799
+ (model.shutdown ? " (shuts down " + model.shutdown + ")" : "")));
716
800
  for (const [id, provider] of Object.entries(settings.customProviders ?? {})) {
717
801
  if (Array.isArray(provider?.models))
718
802
  for (const model of provider.models)
package/dist/cost.js CHANGED
@@ -29,6 +29,20 @@ const PRICES = {
29
29
  "d1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
30
30
  "d1.2-ultra": { inputPerMillion: 0.042, outputPerMillion: 0 },
31
31
  },
32
+ subq: {
33
+ "subq-snap-1.2": { inputPerMillion: 0.04, outputPerMillion: 0 },
34
+ "subq-snap-latest": { inputPerMillion: 0.04, outputPerMillion: 0 },
35
+ },
36
+ "opencode-go": {
37
+ "jev-1.14": { inputPerMillion: 0.042, outputPerMillion: 0 },
38
+ "gemini-decision-1": { inputPerMillion: 0.1, outputPerMillion: 0 },
39
+ "gpt-6-luna-decision": {
40
+ inputPerMillion: 0.1,
41
+ outputPerMillion: 0,
42
+ cachedInputPerMillion: 0.01,
43
+ cacheWritePerMillion: 0.125,
44
+ },
45
+ },
32
46
  cloudflare: {
33
47
  "@cf/cloudflare/clef": { inputPerMillion: 0.24, outputPerMillion: 0 },
34
48
  "@cf/cloudflare/clef-flash": { inputPerMillion: 0.038, outputPerMillion: 0 },
@@ -75,6 +89,9 @@ export function resolvePricing(provider, model, baseUrl, overrides) {
75
89
  (provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
76
90
  (provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
77
91
  (provider === "liquid" && baseUrl === "https://api.liquid.ai/decisions/v1") ||
92
+ (provider === "subq" && baseUrl === "https://api.subq.ai") ||
93
+ (provider === "opencode-go" &&
94
+ baseUrl === "https://opencode.ai/inference/go/systemone/v1") ||
78
95
  ((provider === "cloudflare" || provider === "clairic") &&
79
96
  /^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(baseUrl));
80
97
  const catalogKey = provider === "clairic" ? "cloudflare" : provider;
@@ -150,8 +167,12 @@ export function estimateCost(route, usage) {
150
167
  if ((cached > 0 && rates.cachedInputPerMillion === undefined) ||
151
168
  (writes > 0 && rates.cacheWritePerMillion === undefined))
152
169
  return unavailable("missing_cache_pricing");
153
- // OpenAI doubles input rates for >272K context. Overrides already define effective rates.
154
- if (route.provider === "openai" &&
170
+ // OpenAI and OpenCode Go double these decision models' rates for >272K context.
171
+ // Overrides already define effective rates.
172
+ const longContextRoute = route.provider === "openai" ||
173
+ (route.provider === "opencode-go" &&
174
+ route.model === "gpt-6-luna-decision");
175
+ if (longContextRoute &&
155
176
  route.pricing.source === "builtin" &&
156
177
  inputTokens > 272_000) {
157
178
  rates.inputPerMillion *= 2;
package/dist/extension.js CHANGED
@@ -25,10 +25,10 @@ export default function piClassifier(pi) {
25
25
  promptSnippet: "Classify text, JSON or supported images into typed probabilistic decisions.",
26
26
  promptGuidelines: [
27
27
  "Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
28
+ "Use only bool, choice, multi_choice and score. Extraction reads (text, number, date, spans, box, boxes, locate, estimate, extract) belong to classify_extract and are rejected here.",
28
29
  "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.",
29
30
  "Handle no_match and ambiguous answers explicitly. probabilityScope=batch and noneOfAboveProbability describe only the winning batch; they are not a full-list probability distribution.",
30
31
  "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.",
31
- "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.",
32
32
  "Audio and video are accepted only by routes with documented media contracts. Duration and codec compatibility remain provider-owned.",
33
33
  "Ask /classifier status for the active model. Do not change provider settings without user direction.",
34
34
  ],
@@ -133,12 +133,14 @@ export default function piClassifier(pi) {
133
133
  name: CLASSIFY_EXTRACT_TOOL,
134
134
  label: "Extract structured fields",
135
135
  description: CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
136
- promptSnippet: "Extract typed fields with Cloudflare Clairic into a caller-defined field contract.",
136
+ promptSnippet: "Extract typed values with field specs or typed reads (text, number, date, spans, boxes, locate, estimate) on decision routes including direct Liquid.",
137
137
  promptGuidelines: [
138
+ "Use for reads, not decisions: yes/no, category, multi-choice and score questions belong to classify.",
139
+ "Supply exactly one of fields or questions. fields needs a clairic-api, openrouter-extractions-api or litellm-extraction-api route; questions uses the configured decision route, including direct liquid-api d1.2 and d1.2-ultra.",
138
140
  "Use fields that describe the value you need; do not invent provider field types or keys.",
139
- "Clairic renders values from text and media. A result is not proof that a fact is correct; use grounded spans and confidence when available.",
140
- "truncated means generated fields are incomplete or invalid. Do not treat truncated output as complete extraction.",
141
- "The configured clairic-api route receives state, fields and media. Do not send data the user does not intend to share with Cloudflare.",
141
+ "Liquid reads and spans point into the state text; a value that appears only in an image is not found. Spans and locate offsets count Unicode characters; boxes are localization hints, not proof of presence.",
142
+ "A result is not proof that a fact is correct; use grounded spans and confidence when available. truncated means generated field output is incomplete.",
143
+ "The configured route receives state, fields or questions and media. Do not send data the user does not intend to share with that provider.",
142
144
  ],
143
145
  parameters: classifyExtractParameters,
144
146
  outputSchema: classifyExtractOutput,
package/dist/extract.d.ts CHANGED
@@ -6,6 +6,10 @@ export type ExtractOptions = {
6
6
  signal?: AbortSignal;
7
7
  credentialSource?: CredentialSource;
8
8
  };
9
- /** Cloudflare Clairic structured extraction through the configured clairic-api route. */
9
+ /**
10
+ * `classify_extract` entry point. Two exclusive modes share the extraction result contract:
11
+ * `fields` for Clairic-shaped field specs on extraction routes, and `questions` for typed
12
+ * extraction reads on decision routes, including direct Liquid `d1.2`/`d1.2-ultra`.
13
+ */
10
14
  export declare function extract(params: unknown, options: ExtractOptions): Promise<ExtractResult>;
11
15
  export { userError };
package/dist/extract.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { resolveApiKey } from "./auth.js";
2
+ import { runDecisionRequest } from "./classify.js";
2
3
  import { resolveModel } from "./config.js";
3
4
  import { estimateCost, tokenCount } from "./cost.js";
4
5
  import { postJson } from "./http.js";
5
6
  import { prepareExtractionInput } from "./inputs.js";
6
- import { unwrapCloudflare } from "./providers.js";
7
+ import { classifyWithProvider, unwrapCloudflare } from "./providers.js";
8
+ import { validateExtractionQuestions, validateImageDescriptors } from "./validation.js";
7
9
  import { ClassifierError, isRecord, userError, } from "./types.js";
8
10
  const CLAIRIC_LABEL = "Cloudflare Clairic";
9
11
  const ANSWER_METADATA = [
@@ -57,13 +59,21 @@ function parseAnswers(value, fields) {
57
59
  }
58
60
  return answers;
59
61
  }
60
- /** Cloudflare Clairic structured extraction through the configured clairic-api route. */
62
+ /**
63
+ * `classify_extract` entry point. Two exclusive modes share the extraction result contract:
64
+ * `fields` for Clairic-shaped field specs on extraction routes, and `questions` for typed
65
+ * extraction reads on decision routes, including direct Liquid `d1.2`/`d1.2-ultra`.
66
+ */
61
67
  export async function extract(params, options) {
62
68
  if (params === null || typeof params !== "object" || Array.isArray(params))
63
- throw new ClassifierError("input", "extract requires an object with fields and optional state/media.");
69
+ throw new ClassifierError("input", "extract requires an object with fields or questions and optional state/media.");
64
70
  const input = params;
65
71
  if (options.signal?.aborted)
66
72
  throw new ClassifierError("aborted", "Extraction was cancelled.");
73
+ if ((input.fields === undefined) === (input.questions === undefined))
74
+ throw new ClassifierError("input", "classify_extract needs exactly one of fields (field specifications) or questions (typed extraction reads).");
75
+ if (input.questions !== undefined)
76
+ return extractQuestions(input, options);
67
77
  const route = resolveModel(options.settings, undefined, options.credentialSource ?? "pi-store");
68
78
  const apiKey = route.authMode === "none" ? "" : resolveApiKey(route, options.credentialSource ?? "pi-store");
69
79
  const prepared = await prepareExtractionInput(input, route, options.cwd, options.signal);
@@ -109,6 +119,183 @@ export async function extract(params, options) {
109
119
  function costOf(route, usage) {
110
120
  return estimateCost(route, usage);
111
121
  }
122
+ /** Result-value view of one extraction answer; the read itself stays in metadata. */
123
+ function extractionAnswer(answer) {
124
+ switch (answer.type) {
125
+ case "text": {
126
+ const parsed = { type: "text", value: answer.text };
127
+ if (answer.span !== undefined)
128
+ parsed.span = answer.span;
129
+ if (answer.found !== undefined)
130
+ parsed.found = answer.found;
131
+ if (answer.path !== undefined)
132
+ parsed.path = answer.path;
133
+ return parsed;
134
+ }
135
+ case "number": {
136
+ const parsed = { type: "number", value: answer.value };
137
+ if (answer.unit !== undefined)
138
+ parsed.unit = answer.unit;
139
+ if (answer.text !== undefined)
140
+ parsed.text = answer.text;
141
+ if (answer.span !== undefined)
142
+ parsed.span = answer.span;
143
+ if (answer.found !== undefined)
144
+ parsed.found = answer.found;
145
+ if (answer.path !== undefined)
146
+ parsed.path = answer.path;
147
+ return parsed;
148
+ }
149
+ case "date": {
150
+ const parsed = { type: "date", value: answer.date };
151
+ if (answer.text !== undefined)
152
+ parsed.text = answer.text;
153
+ if (answer.span !== undefined)
154
+ parsed.span = answer.span;
155
+ if (answer.found !== undefined)
156
+ parsed.found = answer.found;
157
+ if (answer.path !== undefined)
158
+ parsed.path = answer.path;
159
+ return parsed;
160
+ }
161
+ case "estimate": {
162
+ const parsed = { type: "estimate", value: answer.value, interval: answer.interval };
163
+ if (answer.unit !== undefined)
164
+ parsed.unit = answer.unit;
165
+ return parsed;
166
+ }
167
+ case "spans": {
168
+ const parsed = {
169
+ type: "spans",
170
+ value: answer.spans.map((span) => span.text),
171
+ spans: answer.spans.map((span) => ({ text: span.text, span: span.span, found: span.found })),
172
+ count: answer.count,
173
+ atLeast: answer.atLeast,
174
+ presence: answer.presence,
175
+ };
176
+ return parsed;
177
+ }
178
+ case "boxes": {
179
+ const parsed = {
180
+ type: "boxes",
181
+ value: answer.boxes.map((entry) => entry.box),
182
+ boxes: answer.boxes.map((entry) => ({ box: entry.box, found: entry.found, confidence: entry.confidence })),
183
+ count: answer.count,
184
+ atLeast: answer.atLeast,
185
+ presence: answer.presence,
186
+ };
187
+ return parsed;
188
+ }
189
+ case "box": {
190
+ const parsed = { type: "box", value: answer.box, confidence: answer.confidence };
191
+ if (answer.found !== undefined)
192
+ parsed.found = answer.found;
193
+ return parsed;
194
+ }
195
+ case "locate": {
196
+ const parsed = {
197
+ type: "locate",
198
+ value: answer.spans.map((span) => span.text),
199
+ spans: answer.spans.map((span) => ({
200
+ start: span.start,
201
+ end: span.end,
202
+ text: span.text,
203
+ score: span.score,
204
+ ...(span.searchResult !== undefined ? { searchResult: span.searchResult } : {}),
205
+ })),
206
+ };
207
+ return parsed;
208
+ }
209
+ case "extract": {
210
+ const parsed = {
211
+ type: "extract",
212
+ value: Object.fromEntries(Object.entries(answer.spans).map(([field, spans]) => [field, spans.map((span) => span.text)])),
213
+ spans: Object.fromEntries(Object.entries(answer.spans).map(([field, spans]) => [
214
+ field,
215
+ spans.map((span) => ({
216
+ start: span.start,
217
+ end: span.end,
218
+ text: span.text,
219
+ score: span.score,
220
+ ...(span.searchResult !== undefined ? { searchResult: span.searchResult } : {}),
221
+ })),
222
+ ])),
223
+ notStated: answer.notStated,
224
+ };
225
+ return parsed;
226
+ }
227
+ case "refusal":
228
+ case "no_match":
229
+ case "ambiguous":
230
+ return { type: answer.type, value: null };
231
+ default:
232
+ throw new ClassifierError("response", "Extraction questions returned a " + answer.type + " decision, which is not an extraction read.");
233
+ }
234
+ }
235
+ function questionExtractionResult(route, result, questions) {
236
+ const answers = Object.create(null);
237
+ for (const id of Object.keys(questions)) {
238
+ const answer = result.answers[id];
239
+ if (answer === undefined)
240
+ throw new ClassifierError("response", "The selected route did not return an answer for " + id + ".");
241
+ answers[id] = extractionAnswer(answer);
242
+ }
243
+ const extracted = {
244
+ provider: route.route,
245
+ model: route.model,
246
+ answers,
247
+ // Typed reads return provider-validated values; no generated field output can truncate.
248
+ truncated: false,
249
+ cost: result.cost,
250
+ };
251
+ if (result.usage !== undefined)
252
+ extracted.usage = result.usage;
253
+ if (result.providerCost !== undefined)
254
+ extracted.providerCost = result.providerCost;
255
+ if (result.requestId !== undefined)
256
+ extracted.requestId = result.requestId;
257
+ if (result.citations !== undefined)
258
+ extracted.citations = result.citations;
259
+ if (result.webGrounding !== undefined)
260
+ extracted.webGrounding = result.webGrounding;
261
+ if (result.attemptedRoutes !== undefined)
262
+ extracted.attemptedRoutes = result.attemptedRoutes;
263
+ if (Buffer.byteLength(JSON.stringify(extracted, null, 2)) > 40 * 1024)
264
+ throw new ClassifierError("response", "Extraction result exceeds the 40 KiB tool output limit. Ask for fewer or narrower reads.");
265
+ return extracted;
266
+ }
267
+ /** Typed extraction questions on a decision route; the route itself supplies the read primitives. */
268
+ async function extractQuestions(input, options) {
269
+ const questions = validateExtractionQuestions(input.questions);
270
+ if (input.documents !== undefined)
271
+ throw new ClassifierError("capability", "PDF documents are accepted only by field extraction. Send the document's text as state for typed reads.");
272
+ if (input.referenceDate !== undefined || input.options !== undefined)
273
+ throw new ClassifierError("capability", "referenceDate and options apply only to field extraction.");
274
+ if (input.state === undefined)
275
+ throw new ClassifierError("input", "Extraction questions require state: pass text or JSON. An empty string is allowed for image-only reads.");
276
+ const decision = { state: input.state, questions };
277
+ const images = [];
278
+ for (const image of input.images ?? []) {
279
+ if (typeof image === "string") {
280
+ images.push(image);
281
+ }
282
+ else if ("id" in image) {
283
+ images.push("path" in image ? { id: image.id, path: image.path } : { id: image.id, url: image.url });
284
+ }
285
+ else {
286
+ throw new ClassifierError("input", "Extraction question images must be local path strings or named {id, path}/{id, url} descriptors. Rotation applies only to direct Clairic field extraction.");
287
+ }
288
+ }
289
+ validateImageDescriptors(images, input.state, questions);
290
+ if (images.length > 0)
291
+ decision.images = images;
292
+ if (input.media !== undefined)
293
+ decision.media = input.media;
294
+ if (input.mode !== undefined)
295
+ decision.mode = input.mode;
296
+ const { result, route } = await runDecisionRequest(decision, options, (prepared, selected, apiKey) => classifyWithProvider(selected, prepared, apiKey, options.signal));
297
+ return questionExtractionResult(route, result, questions);
298
+ }
112
299
  function finalizeExtraction(route, result, prepared, cost, requestId, providerCost, stateText) {
113
300
  if (typeof result.truncated !== "boolean")
114
301
  throw new ClassifierError("response", "Extraction did not report whether output was truncated.");
package/dist/index.d.ts CHANGED
@@ -10,5 +10,5 @@ export { classifyTree } from "./tree.js";
10
10
  export { renderClassifierBox } from "./box.js";
11
11
  export type { ClassifierBoxMode, ClassifierBoxEdges, ClassifierBoxPixelBox, ClassifierBoxResult } from "./box.js";
12
12
  export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
13
- export type { Answer, Question, QuestionContent, ImageInput, ImageReference, ClassifierResult, ClassifierCost, TokenPricing, ClassifierRoute, ClassifierComparisonEntry, ClassifierComparisonResult, ClassifierSettings, ClassifyParams, ClassifyTreeParams, ClassifierTreeResult, ClassificationTree, ClassificationTreeNode, TreeStep, CustomProviderSettings, ModelDefinition, ProviderSettings, ApiStyle, MediaInput, PreparedMedia, TextSpan, BoxEdges, CharSpan, NonTokenCost, WebSearchResult, WebFetchedResult, ExtractionField, ExtractParams, ExtractResult, ExtractionAnswer, JsonLike, } from "./types.js";
13
+ export type { Answer, Question, ClassificationQuestion, ExtractionQuestion, DecisionInput, QuestionContent, ImageInput, ImageReference, ClassifierResult, ClassifierCost, TokenPricing, ClassifierRoute, ClassifierComparisonEntry, ClassifierComparisonResult, ClassifierSettings, ClassifyParams, ClassifyTreeParams, ClassifierTreeResult, ClassificationTree, ClassificationTreeNode, TreeStep, CustomProviderSettings, ModelDefinition, ProviderSettings, ApiStyle, MediaInput, PreparedMedia, TextSpan, BoxEdges, CharSpan, NonTokenCost, WebSearchResult, WebFetchedResult, ExtractionField, ExtractParams, ExtractResult, ExtractionAnswer, JsonLike, } from "./types.js";
14
14
  export { ClassifierError } from "./types.js";
package/dist/inputs.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { type ClassifyParams, type ExtractParams, type PreparedLocalImage, type PreparedInput, type ResolvedModel } from "./types.js";
1
+ import { type DecisionInput, type ExtractParams, type PreparedLocalImage, type PreparedInput, type ResolvedModel } from "./types.js";
2
2
  /** Programmatic image ingress. Never accepted as model-facing tool arguments. */
3
3
  export interface MemoryImage {
4
4
  bytes: Uint8Array;
5
5
  mimeType: "image/png" | "image/jpeg" | "image/webp";
6
6
  }
7
- export declare function prepareInput(params: ClassifyParams, route: ResolvedModel, cwd: string, signal?: AbortSignal, memoryImages?: readonly MemoryImage[]): Promise<PreparedInput>;
7
+ export declare function prepareInput(params: DecisionInput, route: ResolvedModel, cwd: string, signal?: AbortSignal, memoryImages?: readonly MemoryImage[]): Promise<PreparedInput>;
8
8
  /** Bounded, fully decoded local image; shared by uploads and local box rendering. */
9
9
  export declare function loadLocalImage(path: string, cwd: string, signal?: AbortSignal, maxBytes?: number): Promise<PreparedLocalImage>;
10
10
  /** Verify containment of the opened descriptor, not a raceable pre-open path. */