@abhishek944/pi-classifier 0.3.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 (77) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +344 -30
  4. package/dist/auth.d.ts +4 -2
  5. package/dist/auth.js +18 -2
  6. package/dist/box-tool.d.ts +4 -0
  7. package/dist/box-tool.js +79 -0
  8. package/dist/box.d.ts +32 -0
  9. package/dist/box.js +148 -0
  10. package/dist/choices.js +35 -1
  11. package/dist/classify.d.ts +6 -0
  12. package/dist/classify.js +4 -4
  13. package/dist/computer-use-state.d.ts +9 -0
  14. package/dist/computer-use-state.js +160 -0
  15. package/dist/computer-use-tool.d.ts +52 -0
  16. package/dist/computer-use-tool.js +78 -0
  17. package/dist/computer-use-types.d.ts +132 -0
  18. package/dist/computer-use-types.js +1 -0
  19. package/dist/computer-use.d.ts +22 -0
  20. package/dist/computer-use.js +223 -0
  21. package/dist/config.d.ts +140 -3
  22. package/dist/config.js +405 -20
  23. package/dist/cost.js +42 -4
  24. package/dist/durable.d.ts +34 -0
  25. package/dist/durable.js +237 -0
  26. package/dist/extension.d.ts +2 -247
  27. package/dist/extension.js +53 -190
  28. package/dist/extract.d.ts +11 -0
  29. package/dist/extract.js +191 -0
  30. package/dist/http.d.ts +6 -1
  31. package/dist/http.js +64 -28
  32. package/dist/image-content.d.ts +12 -0
  33. package/dist/image-content.js +90 -0
  34. package/dist/index.d.ts +10 -1
  35. package/dist/index.js +3 -0
  36. package/dist/inputs.d.ts +24 -2
  37. package/dist/inputs.js +565 -134
  38. package/dist/mcp-cli.d.ts +2 -0
  39. package/dist/mcp-cli.js +39 -0
  40. package/dist/mcp-server.d.ts +28 -0
  41. package/dist/mcp-server.js +121 -0
  42. package/dist/mcp-tool-definitions.d.ts +19 -0
  43. package/dist/mcp-tool-definitions.js +64 -0
  44. package/dist/providers.d.ts +1 -0
  45. package/dist/providers.js +1218 -124
  46. package/dist/tool-contracts.d.ts +785 -0
  47. package/dist/tool-contracts.js +530 -0
  48. package/dist/tree.js +1 -1
  49. package/dist/types.d.ts +314 -20
  50. package/dist/validation.js +181 -44
  51. package/package.json +33 -5
  52. package/src/auth.ts +26 -2
  53. package/src/box-tool.ts +110 -0
  54. package/src/box.ts +253 -0
  55. package/src/choices.ts +44 -2
  56. package/src/classify.ts +10 -6
  57. package/src/computer-use-state.ts +145 -0
  58. package/src/computer-use-tool.ts +76 -0
  59. package/src/computer-use-types.ts +127 -0
  60. package/src/computer-use.ts +216 -0
  61. package/src/config.ts +454 -23
  62. package/src/cost.ts +42 -4
  63. package/src/durable.ts +298 -0
  64. package/src/extension.ts +79 -265
  65. package/src/extract.ts +228 -0
  66. package/src/http.ts +63 -32
  67. package/src/image-content.ts +77 -0
  68. package/src/index.ts +25 -0
  69. package/src/inputs.ts +603 -184
  70. package/src/mcp-cli.ts +44 -0
  71. package/src/mcp-server.ts +179 -0
  72. package/src/mcp-tool-definitions.ts +104 -0
  73. package/src/providers.ts +1398 -144
  74. package/src/tool-contracts.ts +785 -0
  75. package/src/tree.ts +1 -1
  76. package/src/types.ts +248 -11
  77. package/src/validation.ts +169 -96
package/src/http.ts CHANGED
@@ -1,5 +1,34 @@
1
1
  import { ClassifierError, type ResolvedModel } from "./types.js";
2
2
 
3
+ /** Optional bounded parser for provider error envelopes; receives the active key so echoed credentials can be omitted. */
4
+ export type JsonErrorDetail = (status: number, body: unknown, apiKey: string) => string | undefined;
5
+
6
+ /** Optional sanitizer for a validated response-header request ID; omitted values fall back to provider-body IDs. */
7
+ export type JsonRequestIdDetail = (value: string, apiKey: string) => string | undefined;
8
+
9
+ async function readBoundedText(response: Response): Promise<string> {
10
+ const reader = response.body?.getReader();
11
+ if (!reader)
12
+ throw new ClassifierError("response", "Classifier returned an empty response.");
13
+ const chunks: Uint8Array[] = [];
14
+ let size = 0;
15
+ try {
16
+ while (true) {
17
+ const next = await reader.read();
18
+ if (next.done) break;
19
+ size += next.value.length;
20
+ if (size > 1024 * 1024) {
21
+ await reader.cancel();
22
+ throw new ClassifierError("response", "Classifier response exceeds 1 MiB.");
23
+ }
24
+ chunks.push(next.value);
25
+ }
26
+ } finally {
27
+ reader.releaseLock();
28
+ }
29
+ return Buffer.concat(chunks).toString("utf8");
30
+ }
31
+
3
32
  export async function postJson(
4
33
  route: ResolvedModel,
5
34
  path: string,
@@ -7,7 +36,9 @@ export async function postJson(
7
36
  apiKey: string,
8
37
  signal?: AbortSignal,
9
38
  extraHeaders?: Record<string, string>,
10
- ): Promise<{ body: unknown; requestId?: string }> {
39
+ errorDetail?: JsonErrorDetail,
40
+ requestIdDetail?: JsonRequestIdDetail,
41
+ ): Promise<{ body: unknown; requestId?: string; costHeader?: string }> {
11
42
  if (signal?.aborted)
12
43
  throw new ClassifierError("aborted", "Classification was cancelled.");
13
44
  const encoded = JSON.stringify(body);
@@ -24,7 +55,15 @@ export async function postJson(
24
55
  const headers = new Headers(route.headers);
25
56
  for (const [key, value] of Object.entries(extraHeaders ?? {}))
26
57
  headers.set(key, value);
27
- if (route.api === "microsoft-system-one") {
58
+ if (route.authMode === "none") {
59
+ // Local runtimes are reached over loopback without an API key.
60
+ } else if (route.authMode === "subscription-key") {
61
+ headers.set("api-subscription-key", apiKey);
62
+ } else if (route.authMode === "google-api-key") {
63
+ headers.set("x-goog-api-key", apiKey);
64
+ } else if (route.authMode === "parallel-api-key") {
65
+ headers.set("x-api-key", apiKey);
66
+ } else if (route.authMode === "api-key") {
28
67
  headers.set("api-key", apiKey);
29
68
  } else {
30
69
  headers.set("authorization", "Bearer " + apiKey);
@@ -39,54 +78,46 @@ export async function postJson(
39
78
  redirect: "error",
40
79
  });
41
80
  if (!response.ok) {
42
- await response.body?.cancel();
81
+ let detail: string | undefined;
82
+ if (errorDetail) {
83
+ try {
84
+ const raw = await readBoundedText(response);
85
+ if (raw) detail = errorDetail(response.status, JSON.parse(raw), apiKey);
86
+ } catch {
87
+ // Keep the generic error when an error body is absent, oversized or not JSON.
88
+ }
89
+ } else {
90
+ await response.body?.cancel();
91
+ }
43
92
  throw new ClassifierError(
44
93
  "http",
45
94
  "Classifier request failed (HTTP " +
46
95
  response.status +
47
- "). Check credentials, model, limits and provider availability.",
96
+ "). Check credentials, model, limits and provider availability." +
97
+ (detail ? " " + detail : ""),
48
98
  response.status,
49
99
  );
50
100
  }
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
- }
101
+ const raw = await readBoundedText(response);
76
102
  let parsed: unknown;
77
103
  try {
78
- parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
104
+ parsed = JSON.parse(raw);
79
105
  } catch {
80
106
  throw new ClassifierError(
81
107
  "response",
82
108
  "Classifier returned invalid JSON.",
83
109
  );
84
110
  }
85
- const result: { body: unknown; requestId?: string } = { body: parsed };
111
+ const result: { body: unknown; requestId?: string; costHeader?: string } = { body: parsed };
86
112
  const id =
87
113
  response.headers.get("x-request-id") ??
88
114
  response.headers.get("request-id");
89
- if (id && /^[a-zA-Z0-9_.:-]{1,128}$/.test(id)) result.requestId = id;
115
+ if (id && /^[a-zA-Z0-9_.:-]{1,128}$/.test(id)) {
116
+ const safeId = requestIdDetail ? requestIdDetail(id, apiKey) : id;
117
+ if (safeId !== undefined) result.requestId = safeId;
118
+ }
119
+ const cost = response.headers.get("x-litellm-response-cost");
120
+ if (cost && /^\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(cost)) result.costHeader = cost;
90
121
  return result;
91
122
  } catch (error) {
92
123
  if (controller.signal.aborted)
@@ -0,0 +1,77 @@
1
+ import { ClassifierError, isRecord, type ImageReference, type PreparedImage, type Question } from "./types.js";
2
+
3
+ export function isImageReference(value: unknown): value is ImageReference {
4
+ return isRecord(value) && Object.hasOwn(value, "$image");
5
+ }
6
+
7
+ /** Only explicit reference objects are special; provider-native-looking user JSON stays data. */
8
+ export function imageReferences(value: unknown): string[] {
9
+ if (isImageReference(value)) return [value.$image];
10
+ if (Array.isArray(value)) return value.flatMap(imageReferences);
11
+ if (isRecord(value)) return Object.values(value).flatMap(imageReferences);
12
+ return [];
13
+ }
14
+
15
+ export function questionImageReferences(questions: Record<string, Question>): string[] {
16
+ return Object.values(questions).flatMap((question) => [
17
+ ...imageReferences(question.instructions),
18
+ ...("criteria" in question && question.criteria ? Object.values(question.criteria).flatMap(imageReferences) : []),
19
+ ]);
20
+ }
21
+
22
+ export function mapImageReferences(value: unknown, image: (id: string) => unknown): unknown {
23
+ if (isImageReference(value)) return image(value.$image);
24
+ if (Array.isArray(value)) return value.map((entry) => mapImageReferences(entry, image));
25
+ if (isRecord(value)) return Object.fromEntries(
26
+ Object.entries(value).map(([key, entry]) => [key, mapImageReferences(entry, image)]),
27
+ );
28
+ return value;
29
+ }
30
+
31
+ export function namedImage(images: PreparedImage[], id: string): PreparedImage {
32
+ const image = images.find((entry) => entry.id === id);
33
+ if (!image) throw new ClassifierError("input", "Unknown named image reference.");
34
+ return image;
35
+ }
36
+
37
+ export function imageUrl(image: PreparedImage): string {
38
+ return "url" in image ? image.url : "data:" + image.mimeType + ";base64," + image.data;
39
+ }
40
+
41
+ /** Preserve JSON punctuation as text, interleaving only explicitly referenced images.
42
+ * Raw user objects never become provider-native content parts.
43
+ */
44
+ export function imageContentParts(
45
+ value: unknown,
46
+ image: (id: string) => unknown,
47
+ ): unknown[] {
48
+ const parts: unknown[] = [];
49
+ let text = "";
50
+ const flush = () => { if (text) { parts.push(text); text = ""; } };
51
+ const visit = (entry: unknown): void => {
52
+ if (isImageReference(entry)) { flush(); parts.push(image(entry.$image)); }
53
+ else if (Array.isArray(entry)) {
54
+ text += "[";
55
+ entry.forEach((child, i) => { if (i) text += ","; visit(child); });
56
+ text += "]";
57
+ } else if (isRecord(entry)) {
58
+ text += "{";
59
+ Object.entries(entry).forEach(([key, child], i) => {
60
+ if (i) text += ",";
61
+ text += JSON.stringify(key) + ":";
62
+ visit(child);
63
+ });
64
+ text += "}";
65
+ } else text += JSON.stringify(entry);
66
+ };
67
+ // Ordered content arrays are convenient for instructions and simple multimodal state.
68
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string" || isImageReference(entry))) {
69
+ for (const entry of value) {
70
+ if (typeof entry === "string") text += entry;
71
+ else { flush(); parts.push(image(entry.$image)); }
72
+ }
73
+ } else if (typeof value === "string") text = value;
74
+ else visit(value);
75
+ flush();
76
+ return parts;
77
+ }
package/src/index.ts CHANGED
@@ -1,9 +1,21 @@
1
1
  export { classify, compareClassifiers } from "./classify.js";
2
+ export { extract } from "./extract.js";
3
+ export type { ExtractOptions } from "./extract.js";
4
+ export type { ClassifyOptions } from "./classify.js";
5
+ export type { MemoryImage } from "./inputs.js";
6
+ export { runComputerUse } from "./computer-use.js";
7
+ export type { ComputerUseOptions } from "./computer-use.js";
8
+ export type { ComputerUseParams, ComputerUseResult, ComputerUseSettings, ComputerControl, ComputerExpectation, DriverCall, DriverReply } from "./computer-use-types.js";
2
9
  export { classifyTree } from "./tree.js";
10
+ export { renderClassifierBox } from "./box.js";
11
+ export type { ClassifierBoxMode, ClassifierBoxEdges, ClassifierBoxPixelBox, ClassifierBoxResult } from "./box.js";
3
12
  export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
4
13
  export type {
5
14
  Answer,
6
15
  Question,
16
+ QuestionContent,
17
+ ImageInput,
18
+ ImageReference,
7
19
  ClassifierResult,
8
20
  ClassifierCost,
9
21
  TokenPricing,
@@ -21,5 +33,18 @@ export type {
21
33
  ModelDefinition,
22
34
  ProviderSettings,
23
35
  ApiStyle,
36
+ MediaInput,
37
+ PreparedMedia,
38
+ TextSpan,
39
+ BoxEdges,
40
+ CharSpan,
41
+ NonTokenCost,
42
+ WebSearchResult,
43
+ WebFetchedResult,
44
+ ExtractionField,
45
+ ExtractParams,
46
+ ExtractResult,
47
+ ExtractionAnswer,
48
+ JsonLike,
24
49
  } from "./types.js";
25
50
  export { ClassifierError } from "./types.js";