@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.
- package/CHANGELOG.md +33 -0
- package/README.md +269 -31
- package/dist/auth.d.ts +4 -2
- package/dist/auth.js +18 -2
- package/dist/box-tool.d.ts +2 -24
- package/dist/box-tool.js +5 -35
- package/dist/choices.js +35 -1
- package/dist/classify.d.ts +3 -0
- package/dist/classify.js +3 -3
- package/dist/config.d.ts +140 -3
- package/dist/config.js +401 -20
- package/dist/cost.js +42 -4
- package/dist/durable.d.ts +34 -0
- package/dist/durable.js +237 -0
- package/dist/extension.d.ts +2 -275
- package/dist/extension.js +49 -211
- package/dist/extract.d.ts +11 -0
- package/dist/extract.js +191 -0
- package/dist/http.d.ts +6 -1
- package/dist/http.js +64 -28
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/dist/inputs.d.ts +16 -1
- package/dist/inputs.js +421 -14
- package/dist/mcp-cli.d.ts +2 -0
- package/dist/mcp-cli.js +39 -0
- package/dist/mcp-server.d.ts +28 -0
- package/dist/mcp-server.js +121 -0
- package/dist/mcp-tool-definitions.d.ts +19 -0
- package/dist/mcp-tool-definitions.js +64 -0
- package/dist/providers.d.ts +1 -0
- package/dist/providers.js +1144 -53
- package/dist/tool-contracts.d.ts +785 -0
- package/dist/tool-contracts.js +530 -0
- package/dist/tree.js +1 -1
- package/dist/types.d.ts +284 -8
- package/dist/validation.js +122 -10
- package/package.json +34 -6
- package/src/auth.ts +26 -2
- package/src/box-tool.ts +12 -47
- package/src/choices.ts +42 -1
- package/src/classify.ts +6 -4
- package/src/config.ts +450 -23
- package/src/cost.ts +42 -4
- package/src/durable.ts +298 -0
- package/src/extension.ts +75 -288
- package/src/extract.ts +228 -0
- package/src/http.ts +63 -32
- package/src/index.ts +15 -0
- package/src/inputs.ts +454 -13
- package/src/mcp-cli.ts +44 -0
- package/src/mcp-server.ts +179 -0
- package/src/mcp-tool-definitions.ts +104 -0
- package/src/providers.ts +1323 -56
- package/src/tool-contracts.ts +785 -0
- package/src/tree.ts +1 -1
- package/src/types.ts +231 -5
- package/src/validation.ts +114 -9
package/src/extension.ts
CHANGED
|
@@ -4,8 +4,25 @@ 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";
|
|
10
27
|
import { registerBoxTool } from "./box-tool.js";
|
|
11
28
|
import { registerComputerUseTool } from "./computer-use-tool.js";
|
|
@@ -18,301 +35,39 @@ import {
|
|
|
18
35
|
import { updateProjectClassifierSettings } from "./settings-write.js";
|
|
19
36
|
import { ClassifierError, userError } from "./types.js";
|
|
20
37
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}),
|
|
32
|
-
]);
|
|
33
|
-
}
|
|
34
|
-
const shortText = imageContent(4096);
|
|
35
|
-
const instructionContent = imageContent(16384, true);
|
|
36
|
-
const question = Type.Union([
|
|
37
|
-
Type.Object(
|
|
38
|
-
{
|
|
39
|
-
type: Type.Literal("bool"),
|
|
40
|
-
instructions: instructionContent,
|
|
41
|
-
criteria: Type.Optional(
|
|
42
|
-
Type.Object(
|
|
43
|
-
{ true: Type.Optional(shortText), false: Type.Optional(shortText) },
|
|
44
|
-
{ additionalProperties: false },
|
|
45
|
-
),
|
|
46
|
-
),
|
|
47
|
-
},
|
|
48
|
-
{ additionalProperties: false },
|
|
49
|
-
),
|
|
50
|
-
Type.Object(
|
|
51
|
-
{
|
|
52
|
-
type: Type.Literal("choice"),
|
|
53
|
-
instructions: instructionContent,
|
|
54
|
-
criteria: Type.Record(
|
|
55
|
-
Type.String({ minLength: 1, maxLength: 128 }),
|
|
56
|
-
shortText,
|
|
57
|
-
{ minProperties: 1 },
|
|
58
|
-
),
|
|
59
|
-
},
|
|
60
|
-
{ additionalProperties: false },
|
|
61
|
-
),
|
|
62
|
-
Type.Object(
|
|
63
|
-
{
|
|
64
|
-
type: Type.Literal("score"),
|
|
65
|
-
instructions: instructionContent,
|
|
66
|
-
criteria: Type.Array(imageContent(4096, true), {
|
|
67
|
-
minItems: 2,
|
|
68
|
-
maxItems: 10,
|
|
69
|
-
}),
|
|
70
|
-
},
|
|
71
|
-
{ additionalProperties: false },
|
|
72
|
-
),
|
|
73
|
-
Type.Object(
|
|
74
|
-
{
|
|
75
|
-
type: Type.Literal("box"),
|
|
76
|
-
instructions: instructionContent,
|
|
77
|
-
},
|
|
78
|
-
{ additionalProperties: false },
|
|
79
|
-
),
|
|
80
|
-
]);
|
|
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
|
+
};
|
|
81
48
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
Type.String(),
|
|
87
|
-
Type.Record(Type.String(), Type.Unknown()),
|
|
88
|
-
Type.Array(Type.Unknown()),
|
|
89
|
-
],
|
|
90
|
-
{
|
|
91
|
-
description:
|
|
92
|
-
"Text or JSON data to classify. Use explicit {$image:id} objects to place named images in state on Jev, OpenAI or Perplexity. Other JSON remains data. All questions refer to this same state.",
|
|
93
|
-
},
|
|
94
|
-
),
|
|
95
|
-
questions: Type.Record(
|
|
96
|
-
Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
|
|
97
|
-
question,
|
|
98
|
-
{ minProperties: 1, maxProperties: 32 },
|
|
99
|
-
),
|
|
100
|
-
images: Type.Optional(
|
|
101
|
-
Type.Array(Type.Union([
|
|
102
|
-
Type.String({ minLength: 1, maxLength: 4096 }),
|
|
103
|
-
Type.Object({
|
|
104
|
-
id: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
|
|
105
|
-
path: Type.String({ minLength: 1, maxLength: 4096 }),
|
|
106
|
-
}, { additionalProperties: false }),
|
|
107
|
-
Type.Object({
|
|
108
|
-
id: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
|
|
109
|
-
url: Type.String({ minLength: 1, maxLength: 4096 }),
|
|
110
|
-
}, { additionalProperties: false }),
|
|
111
|
-
]), {
|
|
112
|
-
maxItems: 8,
|
|
113
|
-
description: "Legacy local paths are shared in order. Named {id,path} or {id,url} images must be referenced using {$image:id} in state or supported question content. URLs are OpenAI-only and sent to the provider, never fetched locally. No inline base64 or symlinks. Limits: Perplexity 8 images, Clef 4, others 5.",
|
|
114
|
-
}),
|
|
115
|
-
),
|
|
116
|
-
},
|
|
117
|
-
{ additionalProperties: false },
|
|
118
|
-
);
|
|
119
|
-
|
|
120
|
-
const tokenPricing = Type.Object({
|
|
121
|
-
inputPerMillion: Type.Number({ minimum: 0 }),
|
|
122
|
-
outputPerMillion: Type.Number({ minimum: 0 }),
|
|
123
|
-
cachedInputPerMillion: Type.Optional(Type.Number({ minimum: 0 })),
|
|
124
|
-
cacheWritePerMillion: Type.Optional(Type.Number({ minimum: 0 })),
|
|
125
|
-
});
|
|
126
|
-
|
|
127
|
-
export const classifyOutput = Type.Object({
|
|
128
|
-
provider: Type.String(),
|
|
129
|
-
model: Type.String(),
|
|
130
|
-
answers: Type.Record(
|
|
131
|
-
Type.String(),
|
|
132
|
-
Type.Union([
|
|
133
|
-
Type.Object({
|
|
134
|
-
type: Type.Literal("bool"),
|
|
135
|
-
probability: Type.Number({ minimum: 0, maximum: 1 }),
|
|
136
|
-
}),
|
|
137
|
-
Type.Object({
|
|
138
|
-
type: Type.Literal("choice"),
|
|
139
|
-
choice: Type.String(),
|
|
140
|
-
probabilities: Type.Record(
|
|
141
|
-
Type.String(),
|
|
142
|
-
Type.Number({ minimum: 0, maximum: 1 }),
|
|
143
|
-
),
|
|
144
|
-
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
145
|
-
probabilityScope: Type.Optional(Type.Literal("batch")),
|
|
146
|
-
noneOfAboveProbability: Type.Optional(
|
|
147
|
-
Type.Number({ minimum: 0, maximum: 1 }),
|
|
148
|
-
),
|
|
149
|
-
}),
|
|
150
|
-
Type.Object({
|
|
151
|
-
type: Type.Literal("score"),
|
|
152
|
-
score: Type.Number(),
|
|
153
|
-
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
154
|
-
probabilities: Type.Optional(
|
|
155
|
-
Type.Record(Type.String(), Type.Number({ minimum: 0, maximum: 1 })),
|
|
156
|
-
),
|
|
157
|
-
}),
|
|
158
|
-
Type.Object({
|
|
159
|
-
type: Type.Literal("box"),
|
|
160
|
-
box: Type.Object({
|
|
161
|
-
top: Type.Number(),
|
|
162
|
-
bottom: Type.Number(),
|
|
163
|
-
left: Type.Number(),
|
|
164
|
-
right: Type.Number(),
|
|
165
|
-
}),
|
|
166
|
-
confidence: Type.Number({ minimum: 0, maximum: 1 }),
|
|
167
|
-
}),
|
|
168
|
-
Type.Object({ type: Type.Literal("refusal") }),
|
|
169
|
-
Type.Object({ type: Type.Literal("no_match") }),
|
|
170
|
-
Type.Object({ type: Type.Literal("ambiguous") }),
|
|
171
|
-
]),
|
|
172
|
-
),
|
|
173
|
-
providerCalls: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
174
|
-
usage: Type.Optional(
|
|
175
|
-
Type.Object({
|
|
176
|
-
inputTokens: Type.Number(),
|
|
177
|
-
outputTokens: Type.Number(),
|
|
178
|
-
totalTokens: Type.Number(),
|
|
179
|
-
cachedInputTokens: Type.Optional(Type.Number()),
|
|
180
|
-
cacheWriteTokens: Type.Optional(Type.Number()),
|
|
181
|
-
}),
|
|
182
|
-
),
|
|
183
|
-
cost: Type.Union([
|
|
184
|
-
Type.Object({
|
|
185
|
-
status: Type.Literal("estimated"),
|
|
186
|
-
currency: Type.Literal("USD"),
|
|
187
|
-
input: Type.Number({ minimum: 0 }),
|
|
188
|
-
output: Type.Number({ minimum: 0 }),
|
|
189
|
-
total: Type.Number({ minimum: 0 }),
|
|
190
|
-
source: Type.Union([Type.Literal("builtin"), Type.Literal("configured")]),
|
|
191
|
-
rates: tokenPricing,
|
|
192
|
-
}),
|
|
193
|
-
Type.Object({
|
|
194
|
-
status: Type.Literal("estimated"),
|
|
195
|
-
currency: Type.Literal("USD"),
|
|
196
|
-
input: Type.Number({ minimum: 0 }),
|
|
197
|
-
output: Type.Number({ minimum: 0 }),
|
|
198
|
-
total: Type.Number({ minimum: 0 }),
|
|
199
|
-
source: Type.Literal("aggregated"),
|
|
200
|
-
}),
|
|
201
|
-
Type.Object({
|
|
202
|
-
status: Type.Literal("unavailable"),
|
|
203
|
-
currency: Type.Literal("USD"),
|
|
204
|
-
reason: Type.Union([
|
|
205
|
-
Type.Literal("unknown_pricing"),
|
|
206
|
-
Type.Literal("missing_usage"),
|
|
207
|
-
Type.Literal("invalid_usage"),
|
|
208
|
-
Type.Literal("missing_cache_pricing"),
|
|
209
|
-
Type.Literal("calculation_overflow"),
|
|
210
|
-
]),
|
|
211
|
-
}),
|
|
212
|
-
]),
|
|
213
|
-
requestId: Type.Optional(Type.String()),
|
|
214
|
-
attemptedRoutes: Type.Optional(
|
|
215
|
-
Type.Array(Type.Object({ provider: Type.String(), model: Type.String() })),
|
|
216
|
-
),
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
export const classifyCompareOutput = Type.Object({
|
|
220
|
-
cancelled: Type.Boolean(),
|
|
221
|
-
results: Type.Array(
|
|
222
|
-
Type.Union([
|
|
223
|
-
Type.Object({
|
|
224
|
-
provider: Type.String(),
|
|
225
|
-
model: Type.String(),
|
|
226
|
-
durationMs: Type.Number(),
|
|
227
|
-
status: Type.Literal("success"),
|
|
228
|
-
result: classifyOutput,
|
|
229
|
-
}),
|
|
230
|
-
Type.Object({
|
|
231
|
-
provider: Type.String(),
|
|
232
|
-
model: Type.String(),
|
|
233
|
-
durationMs: Type.Number(),
|
|
234
|
-
status: Type.Literal("error"),
|
|
235
|
-
error: Type.Object({ code: Type.String(), message: Type.String() }),
|
|
236
|
-
}),
|
|
237
|
-
]),
|
|
238
|
-
),
|
|
239
|
-
});
|
|
240
|
-
|
|
241
|
-
const classificationTreeNode = Type.Object(
|
|
242
|
-
{
|
|
243
|
-
id: Type.String({ minLength: 1, maxLength: 128 }),
|
|
244
|
-
description: Type.Optional(Type.String({ maxLength: 4096 })),
|
|
245
|
-
children: Type.Optional(Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"))),
|
|
246
|
-
},
|
|
247
|
-
{ additionalProperties: false },
|
|
248
|
-
);
|
|
249
|
-
|
|
250
|
-
export const classifyTreeParameters = Type.Object(
|
|
251
|
-
{
|
|
252
|
-
state: classifyParameters.properties.state,
|
|
253
|
-
tree: Type.Union([
|
|
254
|
-
Type.String({
|
|
255
|
-
minLength: 1,
|
|
256
|
-
maxLength: 4096,
|
|
257
|
-
description: "Local UTF-8 JSON file inside cwd; no URLs or symlinks.",
|
|
258
|
-
}),
|
|
259
|
-
Type.Object(
|
|
260
|
-
{ roots: Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"), { minItems: 1 }) },
|
|
261
|
-
{ additionalProperties: false },
|
|
262
|
-
),
|
|
263
|
-
]),
|
|
264
|
-
instructions: Type.Optional(Type.String({ minLength: 1, maxLength: 8192 })),
|
|
265
|
-
images: classifyParameters.properties.images,
|
|
266
|
-
},
|
|
267
|
-
{ additionalProperties: false, $defs: { ClassificationTreeNode: classificationTreeNode } },
|
|
268
|
-
);
|
|
269
|
-
|
|
270
|
-
export const classifyTreeOutput = Type.Object({
|
|
271
|
-
provider: Type.String(),
|
|
272
|
-
model: Type.String(),
|
|
273
|
-
status: Type.Union([
|
|
274
|
-
Type.Literal("complete"),
|
|
275
|
-
Type.Literal("no_match"),
|
|
276
|
-
Type.Literal("ambiguous"),
|
|
277
|
-
Type.Literal("refusal"),
|
|
278
|
-
]),
|
|
279
|
-
levels: Type.Record(Type.String({ pattern: "^Level[1-9][0-9]*$" }), Type.String()),
|
|
280
|
-
steps: Type.Array(
|
|
281
|
-
Type.Object({
|
|
282
|
-
level: Type.Integer({ minimum: 1 }),
|
|
283
|
-
id: Type.String(),
|
|
284
|
-
source: Type.Union([Type.Literal("automatic"), Type.Literal("model")]),
|
|
285
|
-
confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
|
|
286
|
-
probabilityScope: Type.Optional(
|
|
287
|
-
Type.Union([Type.Literal("siblings"), Type.Literal("batch")]),
|
|
288
|
-
),
|
|
289
|
-
noneOfAboveProbability: Type.Optional(
|
|
290
|
-
Type.Number({ minimum: 0, maximum: 1 }),
|
|
291
|
-
),
|
|
292
|
-
}),
|
|
293
|
-
),
|
|
294
|
-
providerCalls: Type.Integer({ minimum: 0 }),
|
|
295
|
-
cost: classifyOutput.properties.cost,
|
|
296
|
-
usage: classifyOutput.properties.usage,
|
|
297
|
-
attemptedRoutes: classifyOutput.properties.attemptedRoutes,
|
|
298
|
-
});
|
|
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.
|
|
299
53
|
|
|
300
54
|
export default function piClassifier(pi: ExtensionAPI): void {
|
|
301
55
|
registerBoxTool(pi);
|
|
302
56
|
registerComputerUseTool(pi);
|
|
303
57
|
pi.registerTool(
|
|
304
58
|
defineTool({
|
|
305
|
-
name:
|
|
59
|
+
name: CLASSIFY_TOOL,
|
|
306
60
|
label: "Classify",
|
|
307
|
-
description:
|
|
308
|
-
"Ask a decision model typed questions about text, JSON and supported images. Legacy image paths are shared; named path/url descriptors require explicit {$image:id} references. Jev supports images in instructions/criteria; OpenAI supports instruction images and hosted URLs. Unsupported placements fail locally. 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,
|
|
309
62
|
promptSnippet:
|
|
310
63
|
"Classify text, JSON or supported images into typed probabilistic decisions.",
|
|
311
64
|
promptGuidelines: [
|
|
312
65
|
"Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
|
|
313
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.",
|
|
314
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.",
|
|
315
|
-
"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.",
|
|
316
71
|
"Ask /classifier status for the active model. Do not change provider settings without user direction.",
|
|
317
72
|
],
|
|
318
73
|
parameters: classifyParameters,
|
|
@@ -347,10 +102,9 @@ export default function piClassifier(pi: ExtensionAPI): void {
|
|
|
347
102
|
|
|
348
103
|
pi.registerTool(
|
|
349
104
|
defineTool({
|
|
350
|
-
name:
|
|
105
|
+
name: CLASSIFY_COMPARE_TOOL,
|
|
351
106
|
label: "Compare classifiers",
|
|
352
|
-
description:
|
|
353
|
-
"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,
|
|
354
108
|
promptSnippet:
|
|
355
109
|
"Compare configured decision models only when the user explicitly requests a model comparison.",
|
|
356
110
|
promptGuidelines: [
|
|
@@ -385,10 +139,9 @@ export default function piClassifier(pi: ExtensionAPI): void {
|
|
|
385
139
|
|
|
386
140
|
pi.registerTool(
|
|
387
141
|
defineTool({
|
|
388
|
-
name:
|
|
142
|
+
name: CLASSIFY_TREE_TOOL,
|
|
389
143
|
label: "Classify tree",
|
|
390
|
-
description:
|
|
391
|
-
"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,
|
|
392
145
|
promptSnippet: "Classify through a supplied classification tree and return the selected levels.",
|
|
393
146
|
promptGuidelines: [
|
|
394
147
|
"Use classify_tree only when the user supplies or requests a classification tree; do not invent category branches.",
|
|
@@ -422,6 +175,40 @@ export default function piClassifier(pi: ExtensionAPI): void {
|
|
|
422
175
|
}),
|
|
423
176
|
);
|
|
424
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
|
+
|
|
425
212
|
pi.registerCommand("classifier", {
|
|
426
213
|
description:
|
|
427
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 };
|