@abhishek944/pi-classifier 0.0.0-stage → 0.3.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/CHANGELOG.md +37 -0
- package/LICENSE +201 -0
- package/README.md +425 -2
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +56 -0
- package/dist/choices.d.ts +8 -0
- package/dist/choices.js +131 -0
- package/dist/classification-tree.d.ts +4 -0
- package/dist/classification-tree.js +143 -0
- package/dist/classify.d.ts +10 -0
- package/dist/classify.js +120 -0
- package/dist/config.d.ts +82 -0
- package/dist/config.js +338 -0
- package/dist/cost.d.ts +8 -0
- package/dist/cost.js +202 -0
- package/dist/extension.d.ts +249 -0
- package/dist/extension.js +380 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.js +85 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/inputs.d.ts +4 -0
- package/dist/inputs.js +184 -0
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +624 -0
- package/dist/settings-write.d.ts +10 -0
- package/dist/settings-write.js +110 -0
- package/dist/tree.d.ts +4 -0
- package/dist/tree.js +136 -0
- package/dist/types.d.ts +228 -0
- package/dist/types.js +18 -0
- package/dist/validation.d.ts +3 -0
- package/dist/validation.js +94 -0
- package/package.json +72 -4
- package/src/auth.ts +74 -0
- package/src/choices.ts +173 -0
- package/src/classification-tree.ts +181 -0
- package/src/classify.ts +167 -0
- package/src/config.ts +442 -0
- package/src/cost.ts +250 -0
- package/src/extension.ts +511 -0
- package/src/http.ts +108 -0
- package/src/index.ts +25 -0
- package/src/inputs.ts +239 -0
- package/src/providers.ts +905 -0
- package/src/settings-write.ts +145 -0
- package/src/tree.ts +157 -0
- package/src/types.ts +248 -0
- package/src/validation.ts +138 -0
package/src/extension.ts
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
import { isProjectTrusted } from "@amaster.ai/pi-shared/settings";
|
|
2
|
+
import {
|
|
3
|
+
defineTool,
|
|
4
|
+
type ExtensionAPI,
|
|
5
|
+
type ExtensionContext,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
import { classify, compareClassifiers } from "./classify.js";
|
|
9
|
+
import { classifyTree } from "./tree.js";
|
|
10
|
+
import {
|
|
11
|
+
configuredRoutes,
|
|
12
|
+
listModels,
|
|
13
|
+
loadClassifierSettings,
|
|
14
|
+
resolveModel,
|
|
15
|
+
} from "./config.js";
|
|
16
|
+
import { updateProjectClassifierSettings } from "./settings-write.js";
|
|
17
|
+
import { ClassifierError, userError } from "./types.js";
|
|
18
|
+
|
|
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
|
+
});
|
|
215
|
+
|
|
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
|
+
});
|
|
274
|
+
|
|
275
|
+
export default function piClassifier(pi: ExtensionAPI): void {
|
|
276
|
+
pi.registerTool(
|
|
277
|
+
defineTool({
|
|
278
|
+
name: "classify",
|
|
279
|
+
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.",
|
|
282
|
+
promptSnippet:
|
|
283
|
+
"Classify text, JSON or supported images into typed probabilistic decisions.",
|
|
284
|
+
promptGuidelines: [
|
|
285
|
+
"Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
|
|
286
|
+
"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
|
+
"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.",
|
|
289
|
+
"Ask /classifier status for the active model. Do not change provider settings without user direction.",
|
|
290
|
+
],
|
|
291
|
+
parameters: classifyParameters,
|
|
292
|
+
outputSchema: classifyOutput,
|
|
293
|
+
annotations: {
|
|
294
|
+
readOnlyHint: true,
|
|
295
|
+
destructiveHint: false,
|
|
296
|
+
openWorldHint: true,
|
|
297
|
+
},
|
|
298
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
299
|
+
try {
|
|
300
|
+
const result = await classify(params, {
|
|
301
|
+
settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
302
|
+
cwd: ctx.cwd,
|
|
303
|
+
...(signal ? { signal } : {}),
|
|
304
|
+
});
|
|
305
|
+
return {
|
|
306
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
307
|
+
details: result,
|
|
308
|
+
structuredContent: { ...result },
|
|
309
|
+
};
|
|
310
|
+
} catch (error) {
|
|
311
|
+
console.error(
|
|
312
|
+
"[pi-classifier] classify failed: " +
|
|
313
|
+
(error instanceof ClassifierError ? error.code : "unexpected"),
|
|
314
|
+
);
|
|
315
|
+
throw new Error(userError(error));
|
|
316
|
+
}
|
|
317
|
+
},
|
|
318
|
+
}),
|
|
319
|
+
);
|
|
320
|
+
|
|
321
|
+
pi.registerTool(
|
|
322
|
+
defineTool({
|
|
323
|
+
name: "classify_compare",
|
|
324
|
+
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.",
|
|
327
|
+
promptSnippet:
|
|
328
|
+
"Compare configured decision models only when the user explicitly requests a model comparison.",
|
|
329
|
+
promptGuidelines: [
|
|
330
|
+
"Use only when the user explicitly asks to compare classifier models; never use automatically for low confidence or refusals.",
|
|
331
|
+
"Each configured comparison route receives the submitted data and may incur a charge.",
|
|
332
|
+
],
|
|
333
|
+
parameters: classifyParameters,
|
|
334
|
+
outputSchema: classifyCompareOutput,
|
|
335
|
+
annotations: {
|
|
336
|
+
readOnlyHint: true,
|
|
337
|
+
destructiveHint: false,
|
|
338
|
+
openWorldHint: true,
|
|
339
|
+
},
|
|
340
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
341
|
+
try {
|
|
342
|
+
const result = await compareClassifiers(params, {
|
|
343
|
+
settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
344
|
+
cwd: ctx.cwd,
|
|
345
|
+
...(signal ? { signal } : {}),
|
|
346
|
+
});
|
|
347
|
+
return {
|
|
348
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
349
|
+
details: result,
|
|
350
|
+
structuredContent: { ...result },
|
|
351
|
+
};
|
|
352
|
+
} catch (error) {
|
|
353
|
+
throw new Error(userError(error));
|
|
354
|
+
}
|
|
355
|
+
},
|
|
356
|
+
}),
|
|
357
|
+
);
|
|
358
|
+
|
|
359
|
+
pi.registerTool(
|
|
360
|
+
defineTool({
|
|
361
|
+
name: "classify_tree",
|
|
362
|
+
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.",
|
|
365
|
+
promptSnippet: "Classify through a supplied classification tree and return the selected levels.",
|
|
366
|
+
promptGuidelines: [
|
|
367
|
+
"Use classify_tree only when the user supplies or requests a classification tree; do not invent category branches.",
|
|
368
|
+
"Use meaningful node descriptions. Only the current siblings and selected parent path are submitted per decision, not every descendant.",
|
|
369
|
+
"Inspect status and steps: automatic steps have no model confidence, and partial paths are not complete classifications.",
|
|
370
|
+
"Configured choice batching may cause multiple billable requests per level. No fallback may replay completed model decisions.",
|
|
371
|
+
],
|
|
372
|
+
parameters: classifyTreeParameters,
|
|
373
|
+
outputSchema: classifyTreeOutput,
|
|
374
|
+
annotations: {
|
|
375
|
+
readOnlyHint: true,
|
|
376
|
+
destructiveHint: false,
|
|
377
|
+
openWorldHint: true,
|
|
378
|
+
},
|
|
379
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
380
|
+
try {
|
|
381
|
+
const result = await classifyTree(params, {
|
|
382
|
+
settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
|
|
383
|
+
cwd: ctx.cwd,
|
|
384
|
+
...(signal ? { signal } : {}),
|
|
385
|
+
});
|
|
386
|
+
return {
|
|
387
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
388
|
+
details: result,
|
|
389
|
+
structuredContent: { ...result },
|
|
390
|
+
};
|
|
391
|
+
} catch (error) {
|
|
392
|
+
throw new Error(userError(error));
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
}),
|
|
396
|
+
);
|
|
397
|
+
|
|
398
|
+
pi.registerCommand("classifier", {
|
|
399
|
+
description:
|
|
400
|
+
"Classifier: status, list, reload, use <route> <model>, compare <JSON params>. Use writes trusted project defaults; compare makes potentially billable calls.",
|
|
401
|
+
handler: async (args, ctx) => {
|
|
402
|
+
try {
|
|
403
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
404
|
+
const command = parts[0] ?? "status";
|
|
405
|
+
const settings = loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx));
|
|
406
|
+
if (command === "compare") {
|
|
407
|
+
let params: unknown;
|
|
408
|
+
try {
|
|
409
|
+
params = JSON.parse(args.trim().slice("compare".length).trim());
|
|
410
|
+
} catch {
|
|
411
|
+
throw new ClassifierError(
|
|
412
|
+
"input",
|
|
413
|
+
"Usage: /classifier compare <JSON with state, questions and optional images>.",
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
const result = await compareClassifiers(params, {
|
|
417
|
+
settings,
|
|
418
|
+
cwd: ctx.cwd,
|
|
419
|
+
...(ctx.signal ? { signal: ctx.signal } : {}),
|
|
420
|
+
});
|
|
421
|
+
reply(pi, ctx, JSON.stringify(result, null, 2));
|
|
422
|
+
} else if (command === "list" && parts.length === 1) {
|
|
423
|
+
reply(
|
|
424
|
+
pi,
|
|
425
|
+
ctx,
|
|
426
|
+
listModels(settings) +
|
|
427
|
+
"\n\nFallback: " +
|
|
428
|
+
JSON.stringify(configuredRoutes(settings, "fallback")) +
|
|
429
|
+
"\nCompare: " +
|
|
430
|
+
JSON.stringify(configuredRoutes(settings, "compare")),
|
|
431
|
+
);
|
|
432
|
+
} else if (
|
|
433
|
+
(command === "status" || command === "reload") &&
|
|
434
|
+
parts.length <= 1
|
|
435
|
+
) {
|
|
436
|
+
const route = resolveModel(settings);
|
|
437
|
+
reply(
|
|
438
|
+
pi,
|
|
439
|
+
ctx,
|
|
440
|
+
JSON.stringify(
|
|
441
|
+
{
|
|
442
|
+
provider: route.route,
|
|
443
|
+
model: route.model,
|
|
444
|
+
images: route.images,
|
|
445
|
+
box: route.box,
|
|
446
|
+
requestTimeoutMs: route.requestTimeoutMs,
|
|
447
|
+
none_of_above_choice: settings.none_of_above_choice ?? false,
|
|
448
|
+
remove_choice_limits: settings.remove_choice_limits ?? false,
|
|
449
|
+
maxChoicesPerRequest: route.maxChoices ?? "provider-defined",
|
|
450
|
+
authentication: "API key only; independent of chat login",
|
|
451
|
+
fallback: configuredRoutes(settings, "fallback"),
|
|
452
|
+
compare: configuredRoutes(settings, "compare"),
|
|
453
|
+
},
|
|
454
|
+
null,
|
|
455
|
+
2,
|
|
456
|
+
),
|
|
457
|
+
);
|
|
458
|
+
} else if (command === "use" && parts.length === 3) {
|
|
459
|
+
const selected = {
|
|
460
|
+
...settings,
|
|
461
|
+
default: { provider: parts[1]!, model: parts[2]! },
|
|
462
|
+
};
|
|
463
|
+
const route = resolveModel(selected);
|
|
464
|
+
await updateProjectClassifierSettings(
|
|
465
|
+
ctx.cwd,
|
|
466
|
+
isProjectTrusted(ctx),
|
|
467
|
+
{ default: { provider: route.route, model: route.model } },
|
|
468
|
+
);
|
|
469
|
+
reply(
|
|
470
|
+
pi,
|
|
471
|
+
ctx,
|
|
472
|
+
"Selected " +
|
|
473
|
+
route.route +
|
|
474
|
+
" / " +
|
|
475
|
+
route.model +
|
|
476
|
+
" in project settings. Chat login is unchanged.",
|
|
477
|
+
);
|
|
478
|
+
} else {
|
|
479
|
+
reply(
|
|
480
|
+
pi,
|
|
481
|
+
ctx,
|
|
482
|
+
"Usage: /classifier status | list | reload | use <route> <model> | compare <JSON params>",
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
} catch (error) {
|
|
486
|
+
console.error(
|
|
487
|
+
"[pi-classifier] command failed: " +
|
|
488
|
+
(error instanceof ClassifierError ? error.code : "configuration"),
|
|
489
|
+
);
|
|
490
|
+
reply(
|
|
491
|
+
pi,
|
|
492
|
+
ctx,
|
|
493
|
+
error instanceof ClassifierError
|
|
494
|
+
? error.message
|
|
495
|
+
: "Could not update classifier settings. Check project trust and settings JSON.",
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
},
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function reply(pi: ExtensionAPI, ctx: ExtensionContext, text: string): void {
|
|
503
|
+
const bounded =
|
|
504
|
+
text.length > 16000 ? text.slice(0, 16000) + "\n[truncated]" : text;
|
|
505
|
+
if (ctx.hasUI) ctx.ui.notify(bounded, "info");
|
|
506
|
+
else
|
|
507
|
+
pi.sendMessage(
|
|
508
|
+
{ customType: "pi-classifier", content: bounded, display: true },
|
|
509
|
+
{ triggerTurn: false },
|
|
510
|
+
);
|
|
511
|
+
}
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { ClassifierError, type ResolvedModel } from "./types.js";
|
|
2
|
+
|
|
3
|
+
export async function postJson(
|
|
4
|
+
route: ResolvedModel,
|
|
5
|
+
path: string,
|
|
6
|
+
body: unknown,
|
|
7
|
+
apiKey: string,
|
|
8
|
+
signal?: AbortSignal,
|
|
9
|
+
extraHeaders?: Record<string, string>,
|
|
10
|
+
): Promise<{ body: unknown; requestId?: string }> {
|
|
11
|
+
if (signal?.aborted)
|
|
12
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
13
|
+
const encoded = JSON.stringify(body);
|
|
14
|
+
if (Buffer.byteLength(encoded) > 20 * 1024 * 1024)
|
|
15
|
+
throw new ClassifierError(
|
|
16
|
+
"input",
|
|
17
|
+
"Encoded classifier request exceeds 20 MiB.",
|
|
18
|
+
);
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
const abort = () => controller.abort();
|
|
21
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
22
|
+
const timer = setTimeout(() => controller.abort(), route.requestTimeoutMs);
|
|
23
|
+
try {
|
|
24
|
+
const headers = new Headers(route.headers);
|
|
25
|
+
for (const [key, value] of Object.entries(extraHeaders ?? {}))
|
|
26
|
+
headers.set(key, value);
|
|
27
|
+
if (route.api === "microsoft-system-one") {
|
|
28
|
+
headers.set("api-key", apiKey);
|
|
29
|
+
} else {
|
|
30
|
+
headers.set("authorization", "Bearer " + apiKey);
|
|
31
|
+
}
|
|
32
|
+
headers.set("content-type", "application/json");
|
|
33
|
+
headers.set("accept", "application/json");
|
|
34
|
+
const response = await fetch(route.baseUrl + "/" + path, {
|
|
35
|
+
method: "POST",
|
|
36
|
+
headers,
|
|
37
|
+
body: encoded,
|
|
38
|
+
signal: controller.signal,
|
|
39
|
+
redirect: "error",
|
|
40
|
+
});
|
|
41
|
+
if (!response.ok) {
|
|
42
|
+
await response.body?.cancel();
|
|
43
|
+
throw new ClassifierError(
|
|
44
|
+
"http",
|
|
45
|
+
"Classifier request failed (HTTP " +
|
|
46
|
+
response.status +
|
|
47
|
+
"). Check credentials, model, limits and provider availability.",
|
|
48
|
+
response.status,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const reader = response.body?.getReader();
|
|
52
|
+
if (!reader)
|
|
53
|
+
throw new ClassifierError(
|
|
54
|
+
"response",
|
|
55
|
+
"Classifier returned an empty response.",
|
|
56
|
+
);
|
|
57
|
+
const chunks: Uint8Array[] = [];
|
|
58
|
+
let size = 0;
|
|
59
|
+
try {
|
|
60
|
+
while (true) {
|
|
61
|
+
const next = await reader.read();
|
|
62
|
+
if (next.done) break;
|
|
63
|
+
size += next.value.length;
|
|
64
|
+
if (size > 1024 * 1024) {
|
|
65
|
+
await reader.cancel();
|
|
66
|
+
throw new ClassifierError(
|
|
67
|
+
"response",
|
|
68
|
+
"Classifier response exceeds 1 MiB.",
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
chunks.push(next.value);
|
|
72
|
+
}
|
|
73
|
+
} finally {
|
|
74
|
+
reader.releaseLock();
|
|
75
|
+
}
|
|
76
|
+
let parsed: unknown;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
79
|
+
} catch {
|
|
80
|
+
throw new ClassifierError(
|
|
81
|
+
"response",
|
|
82
|
+
"Classifier returned invalid JSON.",
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const result: { body: unknown; requestId?: string } = { body: parsed };
|
|
86
|
+
const id =
|
|
87
|
+
response.headers.get("x-request-id") ??
|
|
88
|
+
response.headers.get("request-id");
|
|
89
|
+
if (id && /^[a-zA-Z0-9_.:-]{1,128}$/.test(id)) result.requestId = id;
|
|
90
|
+
return result;
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (controller.signal.aborted)
|
|
93
|
+
throw new ClassifierError(
|
|
94
|
+
signal?.aborted ? "aborted" : "timeout",
|
|
95
|
+
signal?.aborted
|
|
96
|
+
? "Classification was cancelled."
|
|
97
|
+
: "Classifier request timed out. This request was not retried.",
|
|
98
|
+
);
|
|
99
|
+
if (error instanceof ClassifierError) throw error;
|
|
100
|
+
throw new ClassifierError(
|
|
101
|
+
"network",
|
|
102
|
+
"Classifier service could not be reached. This request was not retried.",
|
|
103
|
+
);
|
|
104
|
+
} finally {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
signal?.removeEventListener("abort", abort);
|
|
107
|
+
}
|
|
108
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export { classify, compareClassifiers } from "./classify.js";
|
|
2
|
+
export { classifyTree } from "./tree.js";
|
|
3
|
+
export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
|
|
4
|
+
export type {
|
|
5
|
+
Answer,
|
|
6
|
+
Question,
|
|
7
|
+
ClassifierResult,
|
|
8
|
+
ClassifierCost,
|
|
9
|
+
TokenPricing,
|
|
10
|
+
ClassifierRoute,
|
|
11
|
+
ClassifierComparisonEntry,
|
|
12
|
+
ClassifierComparisonResult,
|
|
13
|
+
ClassifierSettings,
|
|
14
|
+
ClassifyParams,
|
|
15
|
+
ClassifyTreeParams,
|
|
16
|
+
ClassifierTreeResult,
|
|
17
|
+
ClassificationTree,
|
|
18
|
+
ClassificationTreeNode,
|
|
19
|
+
TreeStep,
|
|
20
|
+
CustomProviderSettings,
|
|
21
|
+
ModelDefinition,
|
|
22
|
+
ProviderSettings,
|
|
23
|
+
ApiStyle,
|
|
24
|
+
} from "./types.js";
|
|
25
|
+
export { ClassifierError } from "./types.js";
|