@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.
Files changed (58) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +269 -31
  3. package/dist/auth.d.ts +4 -2
  4. package/dist/auth.js +18 -2
  5. package/dist/box-tool.d.ts +2 -24
  6. package/dist/box-tool.js +5 -35
  7. package/dist/choices.js +35 -1
  8. package/dist/classify.d.ts +3 -0
  9. package/dist/classify.js +3 -3
  10. package/dist/config.d.ts +140 -3
  11. package/dist/config.js +401 -20
  12. package/dist/cost.js +42 -4
  13. package/dist/durable.d.ts +34 -0
  14. package/dist/durable.js +237 -0
  15. package/dist/extension.d.ts +2 -275
  16. package/dist/extension.js +49 -211
  17. package/dist/extract.d.ts +11 -0
  18. package/dist/extract.js +191 -0
  19. package/dist/http.d.ts +6 -1
  20. package/dist/http.js +64 -28
  21. package/dist/index.d.ts +3 -1
  22. package/dist/index.js +1 -0
  23. package/dist/inputs.d.ts +16 -1
  24. package/dist/inputs.js +421 -14
  25. package/dist/mcp-cli.d.ts +2 -0
  26. package/dist/mcp-cli.js +39 -0
  27. package/dist/mcp-server.d.ts +28 -0
  28. package/dist/mcp-server.js +121 -0
  29. package/dist/mcp-tool-definitions.d.ts +19 -0
  30. package/dist/mcp-tool-definitions.js +64 -0
  31. package/dist/providers.d.ts +1 -0
  32. package/dist/providers.js +1144 -53
  33. package/dist/tool-contracts.d.ts +785 -0
  34. package/dist/tool-contracts.js +530 -0
  35. package/dist/tree.js +1 -1
  36. package/dist/types.d.ts +284 -8
  37. package/dist/validation.js +122 -10
  38. package/package.json +34 -6
  39. package/src/auth.ts +26 -2
  40. package/src/box-tool.ts +12 -47
  41. package/src/choices.ts +42 -1
  42. package/src/classify.ts +6 -4
  43. package/src/config.ts +450 -23
  44. package/src/cost.ts +42 -4
  45. package/src/durable.ts +298 -0
  46. package/src/extension.ts +75 -288
  47. package/src/extract.ts +228 -0
  48. package/src/http.ts +63 -32
  49. package/src/index.ts +15 -0
  50. package/src/inputs.ts +454 -13
  51. package/src/mcp-cli.ts +44 -0
  52. package/src/mcp-server.ts +179 -0
  53. package/src/mcp-tool-definitions.ts +104 -0
  54. package/src/providers.ts +1323 -56
  55. package/src/tool-contracts.ts +785 -0
  56. package/src/tree.ts +1 -1
  57. package/src/types.ts +231 -5
  58. package/src/validation.ts +114 -9
package/src/cost.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
 
10
10
  // Standard public USD rates, not account-specific billing. Sources and caveats are in README.
11
11
  // Keep exact model matches: newer IDs and other hosts must not inherit guessed prices.
12
+ // Sarvam publishes INR rates, so it has no automatic USD entry here; use explicit pricing overrides.
12
13
  const PRICES: Record<string, Record<string, TokenPricing>> = {
13
14
  openai: {
14
15
  "gpt-6-luna": {
@@ -25,6 +26,8 @@ const PRICES: Record<string, Record<string, TokenPricing>> = {
25
26
  ]),
26
27
  ),
27
28
  perplexity: {
29
+ "pplx-decider-v1.3": { inputPerMillion: 0.02, outputPerMillion: 0 },
30
+ "pplx-decider-flash-v1.3": { inputPerMillion: 0.01, outputPerMillion: 0 },
28
31
  "pplx-decider-v1.1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
29
32
  "pplx-decider-v1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
30
33
  "pplx-decider-v1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
@@ -32,9 +35,15 @@ const PRICES: Record<string, Record<string, TokenPricing>> = {
32
35
  "pplx-decider-flash-v1.2": { inputPerMillion: 0.01, outputPerMillion: 0 },
33
36
  "pplx-decider-flash-latest": { inputPerMillion: 0.01, outputPerMillion: 0 },
34
37
  },
38
+ liquid: {
39
+ "d1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
40
+ "d1.2-ultra": { inputPerMillion: 0.042, outputPerMillion: 0 },
41
+ },
35
42
  cloudflare: {
36
43
  "@cf/cloudflare/clef": { inputPerMillion: 0.24, outputPerMillion: 0 },
37
44
  "@cf/cloudflare/clef-flash": { inputPerMillion: 0.038, outputPerMillion: 0 },
45
+ "@cf/cloudflare/clef-omni": { inputPerMillion: 0.15, outputPerMillion: 0 },
46
+ "@cf/cloudflare/clairic": { inputPerMillion: 0.1, outputPerMillion: 0 },
38
47
  "typesafe/jev": {
39
48
  inputPerMillion: 0.042,
40
49
  outputPerMillion: 0,
@@ -92,14 +101,24 @@ export function resolvePricing(
92
101
  (provider === "openai" && baseUrl === "https://api.openai.com/v1") ||
93
102
  (provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
94
103
  (provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
95
- (provider === "cloudflare" &&
104
+ (provider === "liquid" && baseUrl === "https://api.liquid.ai/decisions/v1") ||
105
+ ((provider === "cloudflare" || provider === "clairic") &&
96
106
  /^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(baseUrl));
97
- const catalog = Object.hasOwn(PRICES, provider) ? PRICES[provider] : undefined;
107
+ const catalogKey = provider === "clairic" ? "cloudflare" : provider;
108
+ const catalog = Object.hasOwn(PRICES, catalogKey) ? PRICES[catalogKey] : undefined;
98
109
  const rates =
99
110
  official && catalog && Object.hasOwn(catalog, model)
100
111
  ? catalog[model]
101
112
  : undefined;
102
- return rates ? { rates: { ...rates }, source: "builtin" } : undefined;
113
+ if (!rates) return undefined;
114
+ // Cloudflare announced a scheduled list-price increase for Clairic on 2026-12-01.
115
+ const scheduledClairic =
116
+ (provider === "cloudflare" || provider === "clairic") &&
117
+ model === "@cf/cloudflare/clairic" &&
118
+ new Date().toISOString().slice(0, 10) >= "2026-12-01"
119
+ ? { ...rates, inputPerMillion: 0.24 }
120
+ : rates;
121
+ return { rates: { ...scheduledClairic }, source: "builtin" };
103
122
  }
104
123
 
105
124
  function validRate(value: unknown): value is number {
@@ -239,7 +258,7 @@ export function sumCost(left: ClassifierCost, right: ClassifierCost): Classifier
239
258
  currency: "USD",
240
259
  reason: "calculation_overflow",
241
260
  };
242
- return {
261
+ const result: Extract<ClassifierCost, { status: "estimated"; source: "aggregated" }> = {
243
262
  status: "estimated",
244
263
  currency: "USD",
245
264
  source: "aggregated",
@@ -247,4 +266,23 @@ export function sumCost(left: ClassifierCost, right: ClassifierCost): Classifier
247
266
  output,
248
267
  total,
249
268
  };
269
+ const leftNonToken = left.nonToken?.webGrounding;
270
+ const rightNonToken = right.nonToken?.webGrounding;
271
+ if (leftNonToken && rightNonToken) {
272
+ const searchFeeMaximum = leftNonToken.searchFeeMaximum + rightNonToken.searchFeeMaximum;
273
+ const fetchFee = leftNonToken.fetchFee + rightNonToken.fetchFee;
274
+ result.nonToken = {
275
+ currency: "USD",
276
+ webGrounding: {
277
+ status: "estimated_maximum",
278
+ searchesRequested: leftNonToken.searchesRequested + rightNonToken.searchesRequested,
279
+ searchFeeMaximum,
280
+ successfulFetches: leftNonToken.successfulFetches + rightNonToken.successfulFetches,
281
+ fetchFee,
282
+ totalMaximum: searchFeeMaximum + fetchFee,
283
+ note: leftNonToken.note,
284
+ },
285
+ };
286
+ }
287
+ return result;
250
288
  }
package/src/durable.ts ADDED
@@ -0,0 +1,298 @@
1
+ import { defineExtension, defineTool } from "@earendil-works/pi-durable";
2
+ import type {
3
+ Extension,
4
+ ToolExecutionApi,
5
+ ToolExecutionResult,
6
+ } from "@earendil-works/pi-durable";
7
+ import type { Context } from "@earendil-works/chord";
8
+ import { classify, compareClassifiers } from "./classify.js";
9
+ import { classifyTree } from "./tree.js";
10
+ import { extract } from "./extract.js";
11
+ import { renderClassifierBox } from "./box.js";
12
+ import {
13
+ CLASSIFIER_BOX_TOOL,
14
+ CLASSIFY_EXTRACT_TOOL,
15
+ CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
16
+ classifyExtractParameters,
17
+ CLASSIFIER_BOX_TOOL_DESCRIPTION,
18
+ CLASSIFY_COMPARE_TOOL,
19
+ CLASSIFY_COMPARE_TOOL_DESCRIPTION,
20
+ CLASSIFY_TOOL,
21
+ CLASSIFY_TOOL_DESCRIPTION,
22
+ CLASSIFY_TREE_TOOL,
23
+ CLASSIFY_TREE_TOOL_DESCRIPTION,
24
+ boxParameters,
25
+ classifyParameters,
26
+ classifyTreeParameters,
27
+ } from "./tool-contracts.js";
28
+ import { userError, type ClassifierSettings } from "./types.js";
29
+
30
+ /**
31
+ * Settings-only native Durable classifier extension.
32
+ *
33
+ * The factory accepts ordinary serializable settings at initialization and uses the
34
+ * existing Node provider and file handling internally (the same operations as the
35
+ * desktop entry). There are no admission, quota, authorization, credential-store, or
36
+ * host callbacks: the model only supplies classification arguments, never a provider,
37
+ * endpoint, credential, or local path outside the working directory.
38
+ *
39
+ * Provider credentials must be explicit: `providers.<id>.apiKey` (and
40
+ * `providers.cloudflare.accountId` for Cloudflare) or the provider environment
41
+ * variable. The native path never reads Pi settings files or Pi's stored API-key
42
+ * credentials; it fails closed with the existing actionable error when no explicit
43
+ * credential resolves.
44
+ *
45
+ * Per-call files (tree JSON, local images) resolve under `options.cwd`, the Durable
46
+ * environment cwd, the conversation agent `cwd`, or the process cwd (in that order).
47
+ * Cancellation follows the invocation `context.abortSignal`.
48
+ *
49
+ * `classifier_computer_use` is intentionally not registered here. It needs to invoke
50
+ * the Cua Driver MCP tools between classifier decisions, and Durable 1.1.0 exposes no
51
+ * generic tool-invocation API (a tool task requires an existing assistant entry and
52
+ * call id), so the loop cannot run natively. No placeholder tool is shipped; use the
53
+ * desktop extension for computer use.
54
+ */
55
+
56
+ export type DurableClassifierOptions = {
57
+ /** Preferred working directory; falls back to the Durable environment cwd, the conversation agent cwd, then the process cwd. */
58
+ cwd?: string;
59
+ };
60
+
61
+ /** Settings are plain data: clone once, then deep-freeze so calls cannot observe later mutation. */
62
+ function freezeSettings(settings: ClassifierSettings): ClassifierSettings {
63
+ const copy = structuredClone(settings);
64
+ const freeze = (node: unknown): void => {
65
+ if (!node || typeof node !== "object") return;
66
+ for (const child of Object.values(node)) freeze(child);
67
+ Object.freeze(node);
68
+ };
69
+ freeze(copy);
70
+ return copy;
71
+ }
72
+
73
+ async function resolveCwd(
74
+ api: ToolExecutionApi,
75
+ context: Context,
76
+ configured?: string,
77
+ ): Promise<string> {
78
+ if (configured?.trim()) return configured;
79
+ const envCwd = api.env?.cwd;
80
+ if (typeof envCwd === "string" && envCwd.trim()) return envCwd;
81
+ try {
82
+ const agent = await api.agent(context);
83
+ if (agent.cwd?.trim()) return agent.cwd;
84
+ } catch {
85
+ // Agent metadata is observational; fall through to the process cwd.
86
+ }
87
+ return process.cwd();
88
+ }
89
+
90
+ function toJson<T>(value: T): T {
91
+ return JSON.parse(JSON.stringify(value)) as T;
92
+ }
93
+
94
+ /** Native classifier tools through the existing operations with explicit credentials only. */
95
+ export function createClassifierExtension(
96
+ settings: ClassifierSettings,
97
+ options: DurableClassifierOptions = {},
98
+ ): Extension {
99
+ const frozenSettings = freezeSettings(settings);
100
+ const { cwd: configuredCwd } = options;
101
+
102
+ const classifyTool = defineTool({
103
+ name: CLASSIFY_TOOL,
104
+ description: CLASSIFY_TOOL_DESCRIPTION,
105
+ parameters: classifyParameters,
106
+ replay: "unsafe",
107
+ executionMode: "parallel",
108
+ async execute(args, api, context) {
109
+ const cwd = await resolveCwd(api, context, configuredCwd);
110
+ try {
111
+ const result = await classify(args, {
112
+ settings: frozenSettings,
113
+ cwd,
114
+ credentialSource: "explicit",
115
+ ...(context.abortSignal ? { signal: context.abortSignal } : {}),
116
+ });
117
+ return {
118
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
119
+ details: toJson(result),
120
+ };
121
+ } catch (error) {
122
+ return {
123
+ isError: true,
124
+ content: [
125
+ { type: "text", text: "classify failed: " + userError(error) },
126
+ ],
127
+ };
128
+ }
129
+ },
130
+ });
131
+
132
+ const compareTool = defineTool({
133
+ name: CLASSIFY_COMPARE_TOOL,
134
+ description: CLASSIFY_COMPARE_TOOL_DESCRIPTION,
135
+ parameters: classifyParameters,
136
+ replay: "unsafe",
137
+ executionMode: "parallel",
138
+ async execute(args, api, context) {
139
+ const cwd = await resolveCwd(api, context, configuredCwd);
140
+ try {
141
+ const result = await compareClassifiers(args, {
142
+ settings: frozenSettings,
143
+ cwd,
144
+ credentialSource: "explicit",
145
+ ...(context.abortSignal ? { signal: context.abortSignal } : {}),
146
+ });
147
+ return {
148
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
149
+ details: toJson(result),
150
+ };
151
+ } catch (error) {
152
+ return {
153
+ isError: true,
154
+ content: [
155
+ {
156
+ type: "text",
157
+ text: "classify_compare failed: " + userError(error),
158
+ },
159
+ ],
160
+ };
161
+ }
162
+ },
163
+ });
164
+
165
+ const treeTool = defineTool({
166
+ name: CLASSIFY_TREE_TOOL,
167
+ description: CLASSIFY_TREE_TOOL_DESCRIPTION,
168
+ parameters: classifyTreeParameters,
169
+ replay: "unsafe",
170
+ executionMode: "parallel",
171
+ async execute(args, api, context) {
172
+ const cwd = await resolveCwd(api, context, configuredCwd);
173
+ try {
174
+ const result = await classifyTree(args, {
175
+ settings: frozenSettings,
176
+ cwd,
177
+ credentialSource: "explicit",
178
+ ...(context.abortSignal ? { signal: context.abortSignal } : {}),
179
+ });
180
+ return {
181
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
182
+ details: toJson(result),
183
+ };
184
+ } catch (error) {
185
+ return {
186
+ isError: true,
187
+ content: [
188
+ { type: "text", text: "classify_tree failed: " + userError(error) },
189
+ ],
190
+ };
191
+ }
192
+ },
193
+ });
194
+
195
+ const extractTool = defineTool({
196
+ name: CLASSIFY_EXTRACT_TOOL,
197
+ description: CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
198
+ parameters: classifyExtractParameters,
199
+ replay: "unsafe",
200
+ executionMode: "parallel",
201
+ async execute(args, api, context) {
202
+ const cwd = await resolveCwd(api, context, configuredCwd);
203
+ try {
204
+ const result = await extract(args, {
205
+ settings: frozenSettings,
206
+ cwd,
207
+ credentialSource: "explicit",
208
+ ...(context.abortSignal ? { signal: context.abortSignal } : {}),
209
+ });
210
+ return {
211
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
212
+ details: toJson(result),
213
+ };
214
+ } catch (error) {
215
+ return {
216
+ isError: true,
217
+ content: [{ type: "text", text: "classify_extract failed: " + userError(error) }],
218
+ };
219
+ }
220
+ },
221
+ });
222
+
223
+ const boxTool = defineTool({
224
+ name: CLASSIFIER_BOX_TOOL,
225
+ description: CLASSIFIER_BOX_TOOL_DESCRIPTION,
226
+ parameters: boxParameters,
227
+ // Pure local render: no provider request, upload, or disk write, so recovery may rerun it.
228
+ replay: "safe",
229
+ executionMode: "parallel",
230
+ async execute(args, api, context) {
231
+ const cwd = await resolveCwd(api, context, configuredCwd);
232
+ try {
233
+ const result = await renderClassifierBox(args, {
234
+ cwd,
235
+ ...(context.abortSignal ? { signal: context.abortSignal } : {}),
236
+ });
237
+ const byteLength = Buffer.from(result.data, "base64").byteLength;
238
+ const details = {
239
+ mode: result.mode,
240
+ mimeType: result.mimeType,
241
+ width: result.width,
242
+ height: result.height,
243
+ pixelBox: { ...result.pixelBox },
244
+ byteLength,
245
+ };
246
+ const box = result.pixelBox;
247
+ return {
248
+ content: [
249
+ {
250
+ type: "text",
251
+ text:
252
+ "Rendered " +
253
+ result.mode +
254
+ " box as a " +
255
+ result.width +
256
+ "×" +
257
+ result.height +
258
+ " PNG (" +
259
+ byteLength +
260
+ " bytes). Source pixel box: left=" +
261
+ box.left +
262
+ ", top=" +
263
+ box.top +
264
+ ", width=" +
265
+ box.width +
266
+ ", height=" +
267
+ box.height +
268
+ ". A box is a localization hint, not proof that the object exists.",
269
+ },
270
+ {
271
+ type: "image",
272
+ data: result.data,
273
+ mimeType: result.mimeType,
274
+ },
275
+ ],
276
+ details: toJson(details),
277
+ };
278
+ } catch (error) {
279
+ return {
280
+ isError: true,
281
+ content: [
282
+ {
283
+ type: "text",
284
+ text: "classifier_box_image failed: " + userError(error),
285
+ },
286
+ ],
287
+ };
288
+ }
289
+ },
290
+ });
291
+
292
+ return defineExtension({
293
+ name: "classifier",
294
+ tools: [classifyTool, compareTool, treeTool, extractTool, boxTool],
295
+ });
296
+ }
297
+
298
+ export type { ToolExecutionResult } from "@earendil-works/pi-durable";