@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.
Files changed (50) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/LICENSE +201 -0
  3. package/README.md +425 -2
  4. package/THIRD_PARTY_NOTICES.md +48 -0
  5. package/dist/auth.d.ts +5 -0
  6. package/dist/auth.js +56 -0
  7. package/dist/choices.d.ts +8 -0
  8. package/dist/choices.js +131 -0
  9. package/dist/classification-tree.d.ts +4 -0
  10. package/dist/classification-tree.js +143 -0
  11. package/dist/classify.d.ts +10 -0
  12. package/dist/classify.js +120 -0
  13. package/dist/config.d.ts +82 -0
  14. package/dist/config.js +338 -0
  15. package/dist/cost.d.ts +8 -0
  16. package/dist/cost.js +202 -0
  17. package/dist/extension.d.ts +249 -0
  18. package/dist/extension.js +380 -0
  19. package/dist/http.d.ts +5 -0
  20. package/dist/http.js +85 -0
  21. package/dist/index.d.ts +5 -0
  22. package/dist/index.js +4 -0
  23. package/dist/inputs.d.ts +4 -0
  24. package/dist/inputs.js +184 -0
  25. package/dist/providers.d.ts +2 -0
  26. package/dist/providers.js +624 -0
  27. package/dist/settings-write.d.ts +10 -0
  28. package/dist/settings-write.js +110 -0
  29. package/dist/tree.d.ts +4 -0
  30. package/dist/tree.js +136 -0
  31. package/dist/types.d.ts +228 -0
  32. package/dist/types.js +18 -0
  33. package/dist/validation.d.ts +3 -0
  34. package/dist/validation.js +94 -0
  35. package/package.json +72 -4
  36. package/src/auth.ts +74 -0
  37. package/src/choices.ts +173 -0
  38. package/src/classification-tree.ts +181 -0
  39. package/src/classify.ts +167 -0
  40. package/src/config.ts +442 -0
  41. package/src/cost.ts +250 -0
  42. package/src/extension.ts +511 -0
  43. package/src/http.ts +108 -0
  44. package/src/index.ts +25 -0
  45. package/src/inputs.ts +239 -0
  46. package/src/providers.ts +905 -0
  47. package/src/settings-write.ts +145 -0
  48. package/src/tree.ts +157 -0
  49. package/src/types.ts +248 -0
  50. package/src/validation.ts +138 -0
@@ -0,0 +1,110 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
3
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
4
+ import { join, resolve } from "node:path";
5
+ const SETTINGS_KEY = "pi-classifier";
6
+ export class SettingsWriteError extends Error {
7
+ }
8
+ /**
9
+ * Merge classifier defaults into trusted project settings without
10
+ * replacing unrelated top-level or extension-owned keys. The final rename is
11
+ * atomic on the project filesystem. Calls in this extension process are
12
+ * serialized by settings path so simultaneous commands cannot lose updates.
13
+ */
14
+ export function updateProjectClassifierSettings(cwd, projectTrusted, update) {
15
+ const settingsPath = resolve(cwd, ".pi", "settings.json");
16
+ return withFileMutationQueue(settingsPath, () => updateProjectClassifierSettingsNow(cwd, projectTrusted, update));
17
+ }
18
+ async function updateProjectClassifierSettingsNow(cwd, projectTrusted, update) {
19
+ if (!projectTrusted) {
20
+ throw new SettingsWriteError("Project settings are not trusted. Trust this project before changing .pi/settings.json.");
21
+ }
22
+ const settingsDir = join(cwd, ".pi");
23
+ const settingsPath = join(settingsDir, "settings.json");
24
+ await rejectSymlink(settingsDir, "The project .pi directory must not be a symbolic link.");
25
+ await mkdir(settingsDir, { recursive: true, mode: 0o700 });
26
+ await rejectSymlink(settingsPath, "The project settings file must not be a symbolic link.");
27
+ let root = {};
28
+ let mode = 0o600;
29
+ try {
30
+ const [text, stat] = await Promise.all([
31
+ readFile(settingsPath, "utf8"),
32
+ lstat(settingsPath),
33
+ ]);
34
+ const parsed = JSON.parse(text);
35
+ if (!isRecord(parsed))
36
+ throw new SettingsWriteError("Project settings must contain a JSON object.");
37
+ root = parsed;
38
+ mode = stat.mode & 0o777;
39
+ }
40
+ catch (error) {
41
+ if (error instanceof SettingsWriteError)
42
+ throw error;
43
+ if (error.code !== "ENOENT") {
44
+ if (error instanceof SyntaxError) {
45
+ throw new SettingsWriteError("Project settings contain invalid JSON. Fix .pi/settings.json before changing classifier settings.");
46
+ }
47
+ throw new SettingsWriteError("Could not read project settings.");
48
+ }
49
+ }
50
+ const current = root[SETTINGS_KEY];
51
+ if (current !== undefined && !isRecord(current)) {
52
+ throw new SettingsWriteError("pi-classifier settings must contain a JSON object.");
53
+ }
54
+ const next = {
55
+ ...(current ?? {}),
56
+ ...withoutUndefined(update),
57
+ };
58
+ delete next.defaultProvider;
59
+ delete next.defaultModel;
60
+ root[SETTINGS_KEY] = next;
61
+ const tempPath = join(settingsDir, `.settings.json.pi-classifier-${randomUUID()}`);
62
+ let handle;
63
+ let created = false;
64
+ try {
65
+ handle = await open(tempPath, "wx", mode);
66
+ created = true;
67
+ await handle.writeFile(`${JSON.stringify(root, null, 2)}\n`, "utf8");
68
+ await handle.close();
69
+ handle = undefined;
70
+ await rename(tempPath, settingsPath);
71
+ }
72
+ catch {
73
+ if (handle) {
74
+ try {
75
+ await handle.close();
76
+ }
77
+ catch {
78
+ // Best effort before unlinking the private temporary file.
79
+ }
80
+ }
81
+ if (created) {
82
+ try {
83
+ await unlink(tempPath);
84
+ }
85
+ catch {
86
+ // Best-effort cleanup only; preserve the fixed, path-free error below.
87
+ }
88
+ }
89
+ throw new SettingsWriteError("Could not update project settings.");
90
+ }
91
+ }
92
+ async function rejectSymlink(path, message) {
93
+ try {
94
+ if ((await lstat(path)).isSymbolicLink())
95
+ throw new SettingsWriteError(message);
96
+ }
97
+ catch (error) {
98
+ if (error instanceof SettingsWriteError)
99
+ throw error;
100
+ if (error.code !== "ENOENT") {
101
+ throw new SettingsWriteError("Could not inspect project settings.");
102
+ }
103
+ }
104
+ }
105
+ function isRecord(value) {
106
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107
+ }
108
+ function withoutUndefined(value) {
109
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
110
+ }
package/dist/tree.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { type ClassifyOptions } from "./classify.js";
2
+ import { type ClassifierTreeResult } from "./types.js";
3
+ /** Greedy sibling decisions over an already validated classification tree; forced edges make no model call. */
4
+ export declare function classifyTree(params: unknown, options: ClassifyOptions): Promise<ClassifierTreeResult>;
package/dist/tree.js ADDED
@@ -0,0 +1,136 @@
1
+ import { classify } from "./classify.js";
2
+ import { choicePolicy } from "./choices.js";
3
+ import { resolveModel } from "./config.js";
4
+ import { sumCost, sumUsage } from "./cost.js";
5
+ import { loadTreeInput } from "./classification-tree.js";
6
+ import { ClassifierError, userError, } from "./types.js";
7
+ /** Greedy sibling decisions over an already validated classification tree; forced edges make no model call. */
8
+ export async function classifyTree(params, options) {
9
+ choicePolicy(options.settings);
10
+ const input = await loadTreeInput(params, options.cwd, options.signal);
11
+ const initial = resolveModel(options.settings);
12
+ const result = {
13
+ provider: initial.route,
14
+ model: initial.model,
15
+ status: "complete",
16
+ levels: Object.create(null),
17
+ steps: [],
18
+ providerCalls: 0,
19
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
20
+ cost: {
21
+ status: "estimated",
22
+ currency: "USD",
23
+ source: "aggregated",
24
+ input: 0,
25
+ output: 0,
26
+ total: 0,
27
+ },
28
+ };
29
+ const path = [];
30
+ let siblings = input.tree.roots;
31
+ let pinned;
32
+ while (siblings.length > 0) {
33
+ if (options.signal?.aborted)
34
+ throw new ClassifierError("aborted", "Classification was cancelled.");
35
+ let selected;
36
+ let step;
37
+ const level = path.length + 1;
38
+ if (siblings.length === 1) {
39
+ selected = siblings[0];
40
+ step = { level, id: selected.id, source: "automatic" };
41
+ }
42
+ else {
43
+ // Non-numeric wire keys preserve array order through JS object enumeration and batching.
44
+ const candidates = new Map(siblings.map((node, index) => ["category_" + index, node]));
45
+ const instructions = (input.instructions ?? "Choose the most appropriate category for the supplied state.") +
46
+ "\nChoose one child of this selected parent path (JSON IDs): " + JSON.stringify(path) +
47
+ ". Use the option descriptions to decide which branch contains the best category. Do not choose a descendant directly.";
48
+ let branch;
49
+ try {
50
+ branch = await classify({
51
+ state: input.state,
52
+ questions: {
53
+ tree: {
54
+ type: "choice",
55
+ instructions,
56
+ criteria: Object.fromEntries([...candidates].map(([key, node]) => [
57
+ key, node.description?.trim() ? node.description : node.id,
58
+ ])),
59
+ },
60
+ },
61
+ ...(input.images !== undefined ? { images: input.images } : {}),
62
+ }, {
63
+ ...options,
64
+ // Only the first actual decision can select an explicitly configured fallback route.
65
+ settings: pinned
66
+ ? { ...options.settings, default: pinned, fallback: [] }
67
+ : options.settings,
68
+ });
69
+ }
70
+ catch (error) {
71
+ if (options.signal?.aborted ||
72
+ (error instanceof ClassifierError && error.code === "aborted"))
73
+ throw new ClassifierError("aborted", "Classification was cancelled.");
74
+ if (result.providerCalls > 0)
75
+ throw new ClassifierError("partial_classification", "Tree traversal stopped at Level" + level + " after " + result.providerCalls +
76
+ " completed provider request(s), which may be billed. No completed levels were replayed. " + userError(error));
77
+ throw error;
78
+ }
79
+ const usage = result.providerCalls === 0
80
+ ? branch.usage
81
+ : sumUsage(result.usage, branch.usage);
82
+ if (usage === undefined)
83
+ delete result.usage;
84
+ else
85
+ result.usage = usage;
86
+ result.cost = result.providerCalls === 0
87
+ ? branch.cost
88
+ : sumCost(result.cost, branch.cost);
89
+ result.providerCalls += branch.providerCalls ?? 1;
90
+ result.provider = branch.provider;
91
+ result.model = branch.model;
92
+ pinned = { provider: branch.provider, model: branch.model };
93
+ if (branch.attemptedRoutes !== undefined)
94
+ result.attemptedRoutes = branch.attemptedRoutes;
95
+ const answer = branch.answers.tree;
96
+ if (!answer)
97
+ throw new ClassifierError("response", "Tree branch returned no answer.");
98
+ if (answer.type === "no_match" || answer.type === "ambiguous" ||
99
+ answer.type === "refusal") {
100
+ result.status = answer.type;
101
+ break;
102
+ }
103
+ if (answer.type !== "choice")
104
+ throw new ClassifierError("response", "Tree branch did not return a choice answer.");
105
+ const probabilities = Object.entries(answer.probabilities);
106
+ const maximum = Math.max(...probabilities.map(([, probability]) => probability));
107
+ const winners = probabilities.filter(([, probability]) => probability === maximum);
108
+ if (winners.length !== 1) {
109
+ result.status = "ambiguous";
110
+ break;
111
+ }
112
+ const node = candidates.get(winners[0][0]);
113
+ if (!node)
114
+ throw new ClassifierError("response", "Tree branch selected an unknown category.");
115
+ selected = node;
116
+ step = {
117
+ level,
118
+ id: selected.id,
119
+ source: "model",
120
+ confidence: answer.confidence,
121
+ probabilityScope: answer.probabilityScope ?? "siblings",
122
+ };
123
+ if (answer.noneOfAboveProbability !== undefined)
124
+ step.noneOfAboveProbability = answer.noneOfAboveProbability;
125
+ }
126
+ path.push(selected.id);
127
+ result.levels["Level" + level] = selected.id;
128
+ result.steps.push(step);
129
+ siblings = selected.children ?? [];
130
+ }
131
+ if (options.signal?.aborted)
132
+ throw new ClassifierError("aborted", "Classification was cancelled.");
133
+ if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
134
+ throw new ClassifierError("response", "Tree result exceeds the 40 KiB tool output limit.");
135
+ return result;
136
+ }
@@ -0,0 +1,228 @@
1
+ export type ApiStyle = "openai-decisions" | "perplexity-decisions" | "system-one" | "cloudflare-system-one" | "microsoft-system-one";
2
+ export type Question = {
3
+ type: "bool";
4
+ instructions: string;
5
+ criteria?: {
6
+ true?: string;
7
+ false?: string;
8
+ };
9
+ } | {
10
+ type: "choice";
11
+ instructions: string;
12
+ criteria: Record<string, string>;
13
+ } | {
14
+ type: "score";
15
+ instructions: string;
16
+ criteria: string[];
17
+ } | {
18
+ type: "box";
19
+ instructions: string;
20
+ };
21
+ export type Answer = {
22
+ type: "bool";
23
+ probability: number;
24
+ } | {
25
+ type: "choice";
26
+ choice: string;
27
+ probabilities: Record<string, number>;
28
+ confidence: number;
29
+ /** Present when probabilities cover one internally processed batch, not the full list. */
30
+ probabilityScope?: "batch";
31
+ noneOfAboveProbability?: number;
32
+ } | {
33
+ type: "score";
34
+ score: number;
35
+ confidence: number;
36
+ probabilities?: Record<string, number>;
37
+ } | {
38
+ type: "box";
39
+ box: {
40
+ top: number;
41
+ bottom: number;
42
+ left: number;
43
+ right: number;
44
+ };
45
+ confidence: number;
46
+ } | {
47
+ type: "refusal";
48
+ } | {
49
+ type: "no_match";
50
+ } | {
51
+ type: "ambiguous";
52
+ };
53
+ export interface ClassifyParams {
54
+ state: string | Record<string, unknown> | unknown[];
55
+ questions: Record<string, Question>;
56
+ /** Regular PNG/JPEG/WebP files inside cwd; attached in this order. */
57
+ images?: string[];
58
+ }
59
+ export type ClassificationTreeNode = {
60
+ id: string;
61
+ description?: string;
62
+ children?: ClassificationTreeNode[];
63
+ };
64
+ export type ClassificationTree = {
65
+ roots: ClassificationTreeNode[];
66
+ };
67
+ export type ClassifyTreeParams = {
68
+ state: ClassifyParams["state"];
69
+ tree: string | ClassificationTree;
70
+ instructions?: string;
71
+ images?: string[];
72
+ };
73
+ export type TreeStep = {
74
+ level: number;
75
+ id: string;
76
+ source: "automatic" | "model";
77
+ confidence?: number;
78
+ probabilityScope?: "siblings" | "batch";
79
+ noneOfAboveProbability?: number;
80
+ };
81
+ export type ClassifierTreeResult = {
82
+ provider: string;
83
+ model: string;
84
+ status: "complete" | "no_match" | "ambiguous" | "refusal";
85
+ levels: Record<string, string>;
86
+ steps: TreeStep[];
87
+ providerCalls: number;
88
+ cost: ClassifierCost;
89
+ usage?: NonNullable<ClassifierResult["usage"]>;
90
+ attemptedRoutes?: ClassifierRoute[];
91
+ };
92
+ export interface ModelDefinition {
93
+ id: string;
94
+ name?: string;
95
+ input?: ("text" | "image")[];
96
+ box?: boolean;
97
+ }
98
+ /** USD per million tokens. Cache counts, when reported, are part of input tokens. */
99
+ export type TokenPricing = {
100
+ inputPerMillion: number;
101
+ outputPerMillion: number;
102
+ cachedInputPerMillion?: number;
103
+ cacheWritePerMillion?: number;
104
+ };
105
+ export type ClassifierCost = {
106
+ status: "estimated";
107
+ currency: "USD";
108
+ input: number;
109
+ output: number;
110
+ total: number;
111
+ source: "builtin" | "configured";
112
+ rates: TokenPricing;
113
+ } | {
114
+ status: "estimated";
115
+ currency: "USD";
116
+ input: number;
117
+ output: number;
118
+ total: number;
119
+ source: "aggregated";
120
+ } | {
121
+ status: "unavailable";
122
+ currency: "USD";
123
+ reason: "unknown_pricing" | "missing_usage" | "invalid_usage" | "missing_cache_pricing" | "calculation_overflow";
124
+ };
125
+ export interface ProviderSettings {
126
+ apiKey?: string;
127
+ baseUrl?: string;
128
+ headers?: Record<string, string>;
129
+ accountId?: string;
130
+ experimentalImages?: boolean;
131
+ experimentalBox?: boolean;
132
+ /** Model ID (or Azure deployment name) to explicit token rates. */
133
+ pricing?: Record<string, TokenPricing>;
134
+ /** Verified wire choice limit; needed for batching on endpoints without a known limit. */
135
+ maxChoices?: number;
136
+ }
137
+ export interface CustomProviderSettings extends ProviderSettings {
138
+ api: ApiStyle;
139
+ models: ModelDefinition[];
140
+ }
141
+ export type ClassifierRoute = {
142
+ provider: string;
143
+ model: string;
144
+ };
145
+ export interface ClassifierSettings {
146
+ none_of_above_choice?: boolean;
147
+ remove_choice_limits?: boolean;
148
+ default?: ClassifierRoute;
149
+ fallback?: ClassifierRoute[];
150
+ compare?: ClassifierRoute[];
151
+ defaultProvider?: string;
152
+ defaultModel?: string;
153
+ requestTimeoutMs?: number;
154
+ providers?: Record<string, ProviderSettings>;
155
+ customProviders?: Record<string, CustomProviderSettings>;
156
+ }
157
+ export interface ResolvedModel {
158
+ route: string;
159
+ provider: string;
160
+ model: string;
161
+ api: ApiStyle;
162
+ baseUrl: string;
163
+ headers: Record<string, string>;
164
+ configuredApiKey?: string;
165
+ credentialProvider: string;
166
+ envVar?: string;
167
+ images: boolean;
168
+ box: boolean;
169
+ experimentalImages: boolean;
170
+ requestTimeoutMs: number;
171
+ pricing?: {
172
+ rates: TokenPricing;
173
+ source: "builtin" | "configured";
174
+ };
175
+ maxChoices?: number;
176
+ }
177
+ export interface PreparedImage {
178
+ data: string;
179
+ mimeType: "image/png" | "image/jpeg" | "image/webp";
180
+ width: number;
181
+ height: number;
182
+ }
183
+ export interface PreparedInput {
184
+ state: ClassifyParams["state"];
185
+ questions: Record<string, Question>;
186
+ images: PreparedImage[];
187
+ }
188
+ export type ClassifierResult = {
189
+ provider: string;
190
+ model: string;
191
+ answers: Record<string, Answer>;
192
+ usage?: {
193
+ inputTokens: number;
194
+ outputTokens: number;
195
+ totalTokens: number;
196
+ cachedInputTokens?: number;
197
+ cacheWriteTokens?: number;
198
+ };
199
+ /** Successful provider requests made by automatic choice processing. */
200
+ providerCalls?: number;
201
+ /** Estimate for completed requests in this result, not an invoice or total of failed attempts. */
202
+ cost: ClassifierCost;
203
+ requestId?: string;
204
+ attemptedRoutes?: ClassifierRoute[];
205
+ };
206
+ export type ClassifierComparisonEntry = ClassifierRoute & {
207
+ durationMs: number;
208
+ } & ({
209
+ status: "success";
210
+ result: ClassifierResult;
211
+ } | {
212
+ status: "error";
213
+ error: {
214
+ code: string;
215
+ message: string;
216
+ };
217
+ });
218
+ export type ClassifierComparisonResult = {
219
+ results: ClassifierComparisonEntry[];
220
+ cancelled: boolean;
221
+ };
222
+ export declare class ClassifierError extends Error {
223
+ readonly code: string;
224
+ readonly httpStatus?: number | undefined;
225
+ constructor(code: string, message: string, httpStatus?: number | undefined);
226
+ }
227
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
228
+ export declare function userError(error: unknown): string;
package/dist/types.js ADDED
@@ -0,0 +1,18 @@
1
+ export class ClassifierError extends Error {
2
+ code;
3
+ httpStatus;
4
+ constructor(code, message, httpStatus) {
5
+ super(message);
6
+ this.code = code;
7
+ this.httpStatus = httpStatus;
8
+ this.name = "ClassifierError";
9
+ }
10
+ }
11
+ export function isRecord(value) {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13
+ }
14
+ export function userError(error) {
15
+ return error instanceof ClassifierError
16
+ ? error.message
17
+ : "Classification failed unexpectedly. Check the selected provider configuration.";
18
+ }
@@ -0,0 +1,3 @@
1
+ import { type ClassifyParams, type Question } from "./types.js";
2
+ export declare function validateParams(value: unknown): ClassifyParams;
3
+ export declare function hasBox(questions: Record<string, Question>): boolean;
@@ -0,0 +1,94 @@
1
+ import { ClassifierError, isRecord, } from "./types.js";
2
+ function invalid(message) {
3
+ throw new ClassifierError("input", message);
4
+ }
5
+ export function validateParams(value) {
6
+ if (!isRecord(value) ||
7
+ Object.keys(value).some((key) => !["state", "questions", "images"].includes(key)))
8
+ invalid("Expected state, questions and optional images; provider/model are selected in settings.");
9
+ if (!(typeof value.state === "string" ||
10
+ Array.isArray(value.state) ||
11
+ isRecord(value.state)))
12
+ invalid("state must be text, a JSON object or an array.");
13
+ validateJson(value.state, 0);
14
+ if (!isRecord(value.questions))
15
+ invalid("questions must be a map keyed by question ID.");
16
+ const entries = Object.entries(value.questions);
17
+ if (entries.length < 1 || entries.length > 32)
18
+ invalid("Supply between 1 and 32 questions.");
19
+ for (const [id, question] of entries) {
20
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
21
+ invalid("Question IDs must be 1–64 letters, digits, underscores or hyphens.");
22
+ if (Object.keys(question).some((key) => !["type", "instructions", "criteria"].includes(key)))
23
+ invalid("Unknown question field.");
24
+ if (typeof question.instructions !== "string" ||
25
+ !question.instructions.trim() ||
26
+ question.instructions.length > 16_384)
27
+ invalid("Each question needs non-empty instructions, at most 16384 characters.");
28
+ if (question.type === "bool") {
29
+ if (question.criteria !== undefined &&
30
+ (!isRecord(question.criteria) ||
31
+ Object.entries(question.criteria).some(([key, entry]) => !["true", "false"].includes(key) ||
32
+ typeof entry !== "string" ||
33
+ entry.length > 4096)))
34
+ invalid("bool criteria must contain optional true/false descriptions.");
35
+ }
36
+ else if (question.type === "choice") {
37
+ if (!isRecord(question.criteria))
38
+ invalid("choice criteria must map labels to descriptions.");
39
+ const criteria = Object.entries(question.criteria);
40
+ if (criteria.length < 1 ||
41
+ criteria.some(([key, entry]) => !key.trim() ||
42
+ key.length > 128 ||
43
+ typeof entry !== "string" ||
44
+ entry.length > 4096))
45
+ invalid("choice requires at least one label with a string description.");
46
+ }
47
+ else if (question.type === "score") {
48
+ if (!Array.isArray(question.criteria) ||
49
+ question.criteria.length < 2 ||
50
+ question.criteria.length > 10 ||
51
+ question.criteria.some((entry) => typeof entry !== "string" || !entry.trim() || entry.length > 4096))
52
+ invalid("score criteria must contain 2–10 non-empty ordered descriptions.");
53
+ }
54
+ else if (question.type === "box") {
55
+ if (question.criteria !== undefined)
56
+ invalid("box does not accept criteria.");
57
+ }
58
+ else
59
+ invalid("Question type must be bool, choice, score or box.");
60
+ }
61
+ if (value.images !== undefined &&
62
+ (!Array.isArray(value.images) ||
63
+ value.images.length > 5 ||
64
+ value.images.some((path) => typeof path !== "string" || !path.trim() || path.length > 4096)))
65
+ invalid("images must contain at most five local file paths.");
66
+ const encoded = JSON.stringify(value);
67
+ if (Buffer.byteLength(encoded) > 2 * 1024 * 1024)
68
+ invalid("Classification text and questions must be at most 2 MiB.");
69
+ return value;
70
+ }
71
+ function validateJson(value, depth) {
72
+ if (depth > 32)
73
+ invalid("state must be at most 32 levels deep.");
74
+ if (value === null || typeof value === "string" || typeof value === "boolean")
75
+ return;
76
+ if (typeof value === "number" && Number.isFinite(value))
77
+ return;
78
+ if (Array.isArray(value)) {
79
+ for (const entry of value)
80
+ validateJson(entry, depth + 1);
81
+ return;
82
+ }
83
+ if (isRecord(value) &&
84
+ (Object.getPrototypeOf(value) === Object.prototype ||
85
+ Object.getPrototypeOf(value) === null)) {
86
+ for (const entry of Object.values(value))
87
+ validateJson(entry, depth + 1);
88
+ return;
89
+ }
90
+ invalid("state must contain only finite JSON values.");
91
+ }
92
+ export function hasBox(questions) {
93
+ return Object.values(questions).some((question) => question.type === "box");
94
+ }
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@abhishek944/pi-classifier",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Config-driven typed classification for Pi via Microsoft Decision-1, OpenAI Decisions, Perplexity, TypeSafe Jev and Cloudflare Clef, with selective fallback and explicit comparisons.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "classifier",
9
+ "decisions",
10
+ "jev",
11
+ "clef"
12
+ ],
13
+ "license": "Apache-2.0",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/abhishek944/pi-classifier.git"
17
+ },
18
+ "homepage": "https://github.com/abhishek944/pi-classifier#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/abhishek944/pi-classifier/issues"
21
+ },
22
+ "type": "module",
23
+ "engines": {
24
+ "node": ">=22.19.0"
25
+ },
26
+ "sideEffects": false,
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ },
34
+ "./extension": {
35
+ "types": "./dist/extension.d.ts",
36
+ "import": "./dist/extension.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "src",
42
+ "CHANGELOG.md",
43
+ "README.md",
44
+ "LICENSE",
45
+ "THIRD_PARTY_NOTICES.md"
46
+ ],
47
+ "pi": {
48
+ "extensions": [
49
+ "./src/extension.ts"
50
+ ]
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "scripts": {
56
+ "build": "tsc -p tsconfig.build.json",
57
+ "typecheck": "tsc -p tsconfig.json --noEmit --pretty false",
58
+ "check": "npm run typecheck && npm run build && npm pack --dry-run"
59
+ },
60
+ "dependencies": {
61
+ "@amaster.ai/pi-shared": "^0.1.10",
62
+ "sharp": "^0.35.5"
63
+ },
64
+ "peerDependencies": {
65
+ "@earendil-works/pi-coding-agent": ">=1.2.0",
66
+ "typebox": "*"
67
+ },
68
+ "devDependencies": {
69
+ "@earendil-works/pi-coding-agent": "1.2.0",
70
+ "typebox": "*",
71
+ "typescript": "^5.9.3",
72
+ "@types/node": "^22.0.0"
73
+ }
74
+ }