@abhishek944/pi-classifier 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +32 -5
  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/auth.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { readStoredCredential } from "@earendil-works/pi-coding-agent";
2
2
  import { ClassifierError, type ResolvedModel } from "./types.js";
3
3
 
4
+ /** Where provider credentials may come from. Desktop keeps the "pi-store" default; the native Durable factory uses "explicit" only. */
5
+ export type CredentialSource = "pi-store" | "explicit";
6
+
4
7
  /** Read the API-key entry only. Never resolve OAuth or mutate Pi's login state. */
5
8
  export function storedApiCredential(provider: string) {
6
9
  try {
@@ -41,8 +44,19 @@ function storedValue(
41
44
  return missing ? undefined : resolved.trim() || undefined;
42
45
  }
43
46
 
44
- export function resolveApiKey(route: ResolvedModel): string {
47
+ export function resolveApiKey(route: ResolvedModel, source: CredentialSource = "pi-store"): string {
48
+ if (route.authMode === "none") return "";
45
49
  if (route.configuredApiKey) return route.configuredApiKey;
50
+ if (source === "explicit") {
51
+ const key = route.envVar ? process.env[route.envVar]?.trim() : undefined;
52
+ if (!key) {
53
+ throw new ClassifierError(
54
+ "missing_credentials",
55
+ "No API key is configured for the selected classifier. Set providers.<id>.apiKey or the provider environment variable. Pi credential-store lookup is disabled on the explicit native path.",
56
+ );
57
+ }
58
+ return key;
59
+ }
46
60
  const credential = storedApiCredential(route.credentialProvider);
47
61
  const key =
48
62
  storedValue(credential?.key, credential?.env) ??
@@ -56,7 +70,17 @@ export function resolveApiKey(route: ResolvedModel): string {
56
70
  return key;
57
71
  }
58
72
 
59
- export function cloudflareAccountId(configured: string | undefined): string {
73
+ export function cloudflareAccountId(configured: string | undefined, source: CredentialSource = "pi-store"): string {
74
+ if (source === "explicit") {
75
+ const id = configured?.trim() ?? process.env.CLOUDFLARE_ACCOUNT_ID?.trim();
76
+ if (!id || !/^[a-zA-Z0-9_-]+$/.test(id)) {
77
+ throw new ClassifierError(
78
+ "configuration",
79
+ "Cloudflare requires a valid accountId or CLOUDFLARE_ACCOUNT_ID.",
80
+ );
81
+ }
82
+ return id;
83
+ }
60
84
  const stored = configured
61
85
  ? undefined
62
86
  : storedApiCredential("cloudflare-workers-ai");
package/src/box-tool.ts CHANGED
@@ -2,58 +2,24 @@ import {
2
2
  defineTool,
3
3
  type ExtensionAPI,
4
4
  } from "@earendil-works/pi-coding-agent";
5
- import { Type } from "typebox";
6
5
  import {
7
6
  renderClassifierBox,
8
7
  type ClassifierBoxMode,
9
8
  type ClassifierBoxPixelBox,
10
9
  } from "./box.js";
10
+ import {
11
+ CLASSIFIER_BOX_TOOL,
12
+ CLASSIFIER_BOX_TOOL_DESCRIPTION,
13
+ boxOutput,
14
+ boxParameters,
15
+ } from "./tool-contracts.js";
11
16
  import { ClassifierError, userError } from "./types.js";
12
17
 
13
- export const boxParameters = Type.Object(
14
- {
15
- image: Type.String({
16
- minLength: 1,
17
- maxLength: 4096,
18
- description:
19
- "Local PNG, JPEG or WebP file inside cwd. No URLs, symlinks or inline base64.",
20
- }),
21
- box: Type.Object(
22
- {
23
- top: Type.Number({ minimum: 0, maximum: 1 }),
24
- bottom: Type.Number({ minimum: 0, maximum: 1 }),
25
- left: Type.Number({ minimum: 0, maximum: 1 }),
26
- right: Type.Number({ minimum: 0, maximum: 1 }),
27
- },
28
- {
29
- additionalProperties: false,
30
- description:
31
- "Normalized edges between 0 and 1, with top < bottom and left < right.",
32
- },
33
- ),
34
- mode: Type.Optional(
35
- Type.Union([Type.Literal("overlay"), Type.Literal("crop")], {
36
- description:
37
- "overlay draws the box on the image (default); crop returns only the boxed region.",
38
- }),
39
- ),
40
- },
41
- { additionalProperties: false },
42
- );
18
+ // Re-exported so existing deep imports from "./box-tool.js" keep working.
19
+ export { boxOutput, boxParameters };
43
20
 
44
- export const boxOutput = Type.Object({
45
- mode: Type.Union([Type.Literal("overlay"), Type.Literal("crop")]),
46
- mimeType: Type.Literal("image/png"),
47
- width: Type.Integer({ minimum: 1 }),
48
- height: Type.Integer({ minimum: 1 }),
49
- pixelBox: Type.Object({
50
- left: Type.Integer({ minimum: 0 }),
51
- top: Type.Integer({ minimum: 0 }),
52
- width: Type.Integer({ minimum: 1 }),
53
- height: Type.Integer({ minimum: 1 }),
54
- }),
55
- byteLength: Type.Integer({ minimum: 1 }),
56
- });
21
+ // Box parameters and result schemas are shared with the native Durable factory
22
+ // through ./tool-contracts.js so the two surfaces cannot drift.
57
23
 
58
24
  type BoxToolDetails = {
59
25
  mode: ClassifierBoxMode;
@@ -67,10 +33,9 @@ type BoxToolDetails = {
67
33
  export function registerBoxTool(pi: ExtensionAPI): void {
68
34
  pi.registerTool(
69
35
  defineTool<typeof boxParameters, BoxToolDetails>({
70
- name: "classifier_box_image",
36
+ name: CLASSIFIER_BOX_TOOL,
71
37
  label: "Box image",
72
- description:
73
- "Render a normalized bounding box on a local image, or crop to it, entirely locally. Use to inspect a box answer from classify. overlay keeps the image and draws a rectangle; crop returns only the clamped region. Returns a PNG plus exact source-pixel box metadata. No provider request, upload, resizing or disk write. A box is a localization hint, not proof that the object exists.",
38
+ description: CLASSIFIER_BOX_TOOL_DESCRIPTION,
74
39
  promptSnippet:
75
40
  "Render or crop a local image using normalized box coordinates.",
76
41
  promptGuidelines: [
package/src/choices.ts CHANGED
@@ -38,6 +38,33 @@ type ChoicePlan = {
38
38
  const NONE_DESCRIPTION =
39
39
  "None of the other options in this question applies to the supplied state. Select this only when every listed real option is unsuitable.";
40
40
 
41
+ /**
42
+ * Each provider call returns its own web evidence. `searchResult` indexes that call's array,
43
+ * so spans must be rebased onto the accumulated evidence assembled by this orchestrator.
44
+ */
45
+ function remapGroundedAnswers(
46
+ answers: Record<string, Answer>,
47
+ offset: number,
48
+ ): Record<string, Answer> {
49
+ if (offset === 0) return answers;
50
+ const mapped = Object.create(null) as Record<string, Answer>;
51
+ for (const [id, answer] of Object.entries(answers)) {
52
+ if (answer.type !== "locate" || !answer.spans.some((span) => span.searchResult !== undefined)) {
53
+ mapped[id] = answer;
54
+ continue;
55
+ }
56
+ mapped[id] = {
57
+ ...answer,
58
+ spans: answer.spans.map((span) =>
59
+ span.searchResult === undefined
60
+ ? span
61
+ : { ...span, searchResult: span.searchResult + offset },
62
+ ),
63
+ };
64
+ }
65
+ return mapped;
66
+ }
67
+
41
68
  /** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
42
69
  export async function executeChoices(
43
70
  input: PreparedInput,
@@ -81,6 +108,7 @@ export async function executeChoices(
81
108
  let last: ClassifierResult | undefined;
82
109
  let usage: ClassifierResult["usage"];
83
110
  let cost: ClassifierCost | undefined;
111
+ let webGrounding: NonNullable<ClassifierResult["webGrounding"]> | undefined;
84
112
  while (plans.size > 0) {
85
113
  if (signal?.aborted)
86
114
  throw new ClassifierError("aborted", "Classification was cancelled.");
@@ -122,9 +150,21 @@ export async function executeChoices(
122
150
  }
123
151
  usage = calls === 0 ? result.usage : sumUsage(usage, result.usage);
124
152
  cost = cost === undefined ? result.cost : sumCost(cost, result.cost);
153
+ const callAnswers = remapGroundedAnswers(
154
+ result.answers,
155
+ webGrounding?.searchResults.length ?? 0,
156
+ );
157
+ if (result.webGrounding !== undefined) {
158
+ webGrounding ??= { searchResults: [] };
159
+ webGrounding.searchResults.push(...result.webGrounding.searchResults);
160
+ if (result.webGrounding.fetchedResults?.length) {
161
+ webGrounding.fetchedResults ??= [];
162
+ webGrounding.fetchedResults.push(...result.webGrounding.fetchedResults);
163
+ }
164
+ }
125
165
  calls++;
126
166
  last = result;
127
- for (const [id, answer] of Object.entries(result.answers)) {
167
+ for (const [id, answer] of Object.entries(callAnswers)) {
128
168
  const plan = plans.get(id);
129
169
  if (!plan) {
130
170
  answers[id] = answer;
@@ -168,6 +208,7 @@ export async function executeChoices(
168
208
  cost: cost!,
169
209
  };
170
210
  if (usage !== undefined) combined.usage = usage;
211
+ if (webGrounding !== undefined) combined.webGrounding = webGrounding;
171
212
  if (calls === 1 && last!.requestId !== undefined)
172
213
  combined.requestId = last!.requestId;
173
214
  return combined;
package/src/classify.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { performance } from "node:perf_hooks";
2
- import { resolveApiKey } from "./auth.js";
2
+ import { resolveApiKey, type CredentialSource } from "./auth.js";
3
3
  import { configuredDefault, configuredRoutes, resolveModel } from "./config.js";
4
4
  import { prepareInput, type MemoryImage } from "./inputs.js";
5
5
  import { choicePolicy, executeChoices } from "./choices.js";
@@ -20,6 +20,8 @@ export type ClassifyOptions = {
20
20
  settings: ClassifierSettings;
21
21
  cwd: string;
22
22
  signal?: AbortSignal;
23
+ /** Credential origin. Desktop keeps the default; the native Durable factory passes "explicit". */
24
+ credentialSource?: CredentialSource;
23
25
  /** Trusted programmatic ingress; all bytes still pass normal image validation. */
24
26
  memoryImages?: readonly MemoryImage[];
25
27
  };
@@ -45,7 +47,7 @@ async function classifyOnce(
45
47
  checkCancelled(options.signal);
46
48
  const prepared = await prepareInput(input, route, options.cwd, options.signal, options.memoryImages);
47
49
  checkCancelled(options.signal);
48
- const key = resolveApiKey(route);
50
+ const key = resolveApiKey(route, options.credentialSource ?? "pi-store");
49
51
  const result = await executeChoices(
50
52
  prepared,
51
53
  route,
@@ -86,7 +88,7 @@ export async function classify(
86
88
  let lastError: unknown;
87
89
  for (const candidate of candidates) {
88
90
  checkCancelled(options.signal);
89
- const route = resolveModel(options.settings, candidate);
91
+ const route = resolveModel(options.settings, candidate, options.credentialSource ?? "pi-store");
90
92
  const key = routeKey(route);
91
93
  if (seen.has(key)) continue;
92
94
  seen.add(key);
@@ -130,7 +132,7 @@ export async function compareClassifiers(
130
132
  const start = performance.now();
131
133
  let selected = candidate;
132
134
  try {
133
- const route = resolveModel(options.settings, candidate);
135
+ const route = resolveModel(options.settings, candidate, options.credentialSource ?? "pi-store");
134
136
  selected = routePair(route);
135
137
  const key = routeKey(route);
136
138
  if (seen.has(key))