@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,131 @@
1
+ import { sumCost, sumUsage } from "./cost.js";
2
+ import { ClassifierError, } from "./types.js";
3
+ export function choicePolicy(settings) {
4
+ for (const key of ["none_of_above_choice", "remove_choice_limits"]) {
5
+ if (settings[key] !== undefined && typeof settings[key] !== "boolean")
6
+ throw new ClassifierError("configuration", key + " must be a boolean.");
7
+ }
8
+ const none = settings.none_of_above_choice === true;
9
+ const batch = settings.remove_choice_limits === true;
10
+ if (batch && !none)
11
+ throw new ClassifierError("configuration", "remove_choice_limits requires none_of_above_choice: true. No classifier request was sent.");
12
+ return { none, batch };
13
+ }
14
+ const NONE_DESCRIPTION = "None of the other options in this question applies to the supplied state. Select this only when every listed real option is unsuitable.";
15
+ /** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
16
+ export async function executeChoices(input, route, policy, call, signal) {
17
+ const plans = new Map();
18
+ for (const [id, question] of Object.entries(input.questions)) {
19
+ if (question.type !== "choice")
20
+ continue;
21
+ const entries = Object.entries(question.criteria);
22
+ if (policy.batch && route.maxChoices === undefined)
23
+ throw new ClassifierError("configuration", "Automatic choice batching needs a verified provider limit. Set providers.<id>.maxChoices (or customProviders.<id>.maxChoices) for this endpoint. No classifier request was sent.");
24
+ const size = entries.length + (policy.none ? 1 : 0);
25
+ if (!policy.batch &&
26
+ route.maxChoices !== undefined &&
27
+ size > route.maxChoices)
28
+ throw new ClassifierError("input", "Choice question " + id + " exceeds the selected provider's " +
29
+ route.maxChoices + " options per request" +
30
+ (policy.none ? " (including NONE OF THE ABOVE)" : "") +
31
+ ". Enable both none_of_above_choice and remove_choice_limits to batch choices, or reduce the list. No classifier request was sent.");
32
+ let sentinel = "__pi_none_of_above";
33
+ let suffix = 0;
34
+ while (Object.hasOwn(question.criteria, sentinel))
35
+ sentinel = "__pi_none_of_above_" + ++suffix;
36
+ plans.set(id, { question, entries, offset: 0, sentinel });
37
+ }
38
+ if (!policy.none || plans.size === 0)
39
+ return call(input.questions);
40
+ const answers = Object.create(null);
41
+ let calls = 0;
42
+ let last;
43
+ let usage;
44
+ let cost;
45
+ while (plans.size > 0) {
46
+ if (signal?.aborted)
47
+ throw new ClassifierError("aborted", "Classification was cancelled.");
48
+ const questions = Object.create(null);
49
+ // A bool/score/box is evaluated once, not charged again for later choice batches.
50
+ if (calls === 0) {
51
+ for (const [id, question] of Object.entries(input.questions))
52
+ if (question.type !== "choice")
53
+ questions[id] = question;
54
+ }
55
+ for (const [id, plan] of plans) {
56
+ const capacity = route.maxChoices === undefined
57
+ ? plan.entries.length
58
+ : route.maxChoices - 1;
59
+ const batch = plan.entries.slice(plan.offset, plan.offset + capacity);
60
+ plan.offset += batch.length;
61
+ questions[id] = {
62
+ ...plan.question,
63
+ criteria: Object.fromEntries([...batch, [plan.sentinel, NONE_DESCRIPTION]]),
64
+ };
65
+ }
66
+ let result;
67
+ try {
68
+ result = await call(questions);
69
+ }
70
+ catch (error) {
71
+ // Never replay completed batches on another billing route after a later throttling/auth error.
72
+ if (calls > 0 &&
73
+ error instanceof ClassifierError &&
74
+ error.code === "http" &&
75
+ [401, 404, 429].includes(error.httpStatus ?? 0))
76
+ throw new ClassifierError("partial_classification", "Choice batching stopped after " + calls +
77
+ " completed provider request(s). No fallback was attempted after partial completion; completed requests may be billed.");
78
+ throw error;
79
+ }
80
+ usage = calls === 0 ? result.usage : sumUsage(usage, result.usage);
81
+ cost = cost === undefined ? result.cost : sumCost(cost, result.cost);
82
+ calls++;
83
+ last = result;
84
+ for (const [id, answer] of Object.entries(result.answers)) {
85
+ const plan = plans.get(id);
86
+ if (!plan) {
87
+ answers[id] = answer;
88
+ continue;
89
+ }
90
+ if (answer.type !== "choice") {
91
+ answers[id] = answer;
92
+ plans.delete(id);
93
+ continue;
94
+ }
95
+ const none = answer.probabilities[plan.sentinel];
96
+ const real = Object.entries(answer.probabilities).filter(([label]) => label !== plan.sentinel);
97
+ const maximum = Math.max(...real.map(([, probability]) => probability));
98
+ if (none > maximum) {
99
+ if (plan.offset < plan.entries.length)
100
+ continue;
101
+ answers[id] = { type: "no_match" };
102
+ }
103
+ else if (none === maximum || real.filter(([, p]) => p === maximum).length !== 1) {
104
+ answers[id] = { type: "ambiguous" };
105
+ }
106
+ else {
107
+ answers[id] = {
108
+ ...answer,
109
+ choice: real.find(([, p]) => p === maximum)[0],
110
+ probabilities: Object.fromEntries(real),
111
+ probabilityScope: "batch",
112
+ noneOfAboveProbability: none,
113
+ };
114
+ }
115
+ plans.delete(id);
116
+ }
117
+ }
118
+ // Validated inputs always contain questions; this loop executes at least once.
119
+ const combined = {
120
+ provider: last.provider,
121
+ model: last.model,
122
+ answers,
123
+ providerCalls: calls,
124
+ cost: cost,
125
+ };
126
+ if (usage !== undefined)
127
+ combined.usage = usage;
128
+ if (calls === 1 && last.requestId !== undefined)
129
+ combined.requestId = last.requestId;
130
+ return combined;
131
+ }
@@ -0,0 +1,4 @@
1
+ import { type ClassifyTreeParams, type ClassificationTree } from "./types.js";
2
+ export declare function loadTreeInput(value: unknown, cwd: string, signal?: AbortSignal): Promise<Omit<ClassifyTreeParams, "tree"> & {
3
+ tree: ClassificationTree;
4
+ }>;
@@ -0,0 +1,143 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, realpath } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { verifyOpenedPath } from "./inputs.js";
5
+ import { ClassifierError, isRecord, } from "./types.js";
6
+ import { validateParams } from "./validation.js";
7
+ const MAX_TREE_BYTES = 2 * 1024 * 1024;
8
+ const MAX_DEPTH = 32;
9
+ function invalid(message) {
10
+ throw new ClassifierError("input", message);
11
+ }
12
+ export async function loadTreeInput(value, cwd, signal) {
13
+ cancelled(signal);
14
+ if (!isRecord(value) ||
15
+ Object.keys(value).some((key) => !["state", "tree", "instructions", "images"].includes(key)))
16
+ invalid("Expected state, tree and optional instructions/images; the route is selected in settings.");
17
+ if (value.instructions !== undefined &&
18
+ (typeof value.instructions !== "string" ||
19
+ !value.instructions.trim() || value.instructions.length > 8192))
20
+ invalid("Tree instructions must be a non-empty string of at most 8192 characters.");
21
+ // Reuse existing state/image-path validation without making a provider request.
22
+ const base = validateParams({
23
+ state: value.state,
24
+ questions: { tree: { type: "bool", instructions: "Validate tree input." } },
25
+ ...(value.images !== undefined ? { images: value.images } : {}),
26
+ });
27
+ const raw = typeof value.tree === "string"
28
+ ? await readTreeFile(value.tree, cwd, signal)
29
+ : value.tree;
30
+ if (!isRecord(raw) || Object.keys(raw).some((key) => key !== "roots"))
31
+ invalid("Classification tree must be an object containing roots.");
32
+ const ancestors = new Set();
33
+ const roots = nodes(raw.roots, 1, ancestors, { bytes: 0 });
34
+ const tree = { roots };
35
+ if (Buffer.byteLength(JSON.stringify(tree)) > MAX_TREE_BYTES)
36
+ invalid("Classification tree must be at most 2 MiB.");
37
+ cancelled(signal);
38
+ const result = {
39
+ state: base.state,
40
+ tree,
41
+ };
42
+ if (typeof value.instructions === "string")
43
+ result.instructions = value.instructions;
44
+ if (base.images !== undefined)
45
+ result.images = base.images;
46
+ return result;
47
+ }
48
+ function nodes(value, depth, ancestors, budget) {
49
+ if (!Array.isArray(value) || (depth === 1 && value.length === 0))
50
+ invalid("Classification tree roots must be non-empty and children must be arrays when supplied.");
51
+ if (depth > MAX_DEPTH && value.length > 0)
52
+ invalid("Classification tree must be at most 32 levels deep.");
53
+ const ids = new Set();
54
+ return value.map((entry) => {
55
+ if (!isRecord(entry) ||
56
+ Object.keys(entry).some((key) => !["id", "description", "children"].includes(key)) ||
57
+ typeof entry.id !== "string" ||
58
+ !entry.id.trim() || entry.id.length > 128 ||
59
+ (entry.description !== undefined &&
60
+ (typeof entry.description !== "string" || entry.description.length > 4096)))
61
+ invalid("Each classification tree node needs a non-empty id of at most 128 characters, optional description up to 4096 characters, and optional children.");
62
+ if (ids.has(entry.id))
63
+ invalid("Classification tree node IDs must be unique among siblings.");
64
+ if (ancestors.has(entry))
65
+ invalid("Classification tree must not contain cycles.");
66
+ ids.add(entry.id);
67
+ ancestors.add(entry);
68
+ const node = { id: entry.id };
69
+ if (typeof entry.description === "string")
70
+ node.description = entry.description;
71
+ // Bound normalization itself, including shared JS subtrees that expand when serialized.
72
+ budget.bytes += Buffer.byteLength(JSON.stringify(node));
73
+ if (budget.bytes > MAX_TREE_BYTES)
74
+ invalid("Classification tree must be at most 2 MiB.");
75
+ if (entry.children !== undefined)
76
+ node.children = nodes(entry.children, depth + 1, ancestors, budget);
77
+ ancestors.delete(entry);
78
+ return node;
79
+ });
80
+ }
81
+ async function readTreeFile(path, cwd, signal) {
82
+ if (!path.trim() || path.length > 4096 || /^[a-z]+:/i.test(path))
83
+ invalid("Classification tree must be an inline roots object or a local JSON path inside cwd, not a URL.");
84
+ let bytes;
85
+ try {
86
+ const root = await realpath(cwd);
87
+ const target = resolve(root, path);
88
+ const inside = relative(root, target);
89
+ if (!inside || inside === ".." ||
90
+ inside.startsWith(".." + sep) || isAbsolute(inside))
91
+ throw new Error();
92
+ let current = root;
93
+ for (const part of inside.split(sep)) {
94
+ cancelled(signal);
95
+ current = resolve(current, part);
96
+ const entry = await lstat(current);
97
+ if (entry.isSymbolicLink() ||
98
+ (current === target ? !entry.isFile() : !entry.isDirectory()))
99
+ throw new Error();
100
+ }
101
+ if (await realpath(target) !== target)
102
+ throw new Error();
103
+ const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
104
+ try {
105
+ await verifyOpenedPath(file.fd, root, signal);
106
+ const stat = await file.stat();
107
+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_TREE_BYTES)
108
+ throw new Error();
109
+ const buffer = Buffer.alloc(MAX_TREE_BYTES + 1);
110
+ let offset = 0;
111
+ while (offset < buffer.length) {
112
+ cancelled(signal);
113
+ const next = await file.read(buffer, offset, buffer.length - offset, null);
114
+ if (!next.bytesRead)
115
+ break;
116
+ offset += next.bytesRead;
117
+ }
118
+ if (offset > MAX_TREE_BYTES)
119
+ throw new Error();
120
+ bytes = buffer.subarray(0, offset);
121
+ }
122
+ finally {
123
+ await file.close();
124
+ }
125
+ }
126
+ catch (error) {
127
+ cancelled(signal);
128
+ if (error instanceof ClassifierError)
129
+ throw error;
130
+ invalid("Classification tree must be a readable regular file inside cwd, without symlink components, and at most 2 MiB.");
131
+ }
132
+ cancelled(signal);
133
+ try {
134
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
135
+ }
136
+ catch {
137
+ invalid("Classification tree file must contain valid UTF-8 JSON.");
138
+ }
139
+ }
140
+ function cancelled(signal) {
141
+ if (signal?.aborted)
142
+ throw new ClassifierError("aborted", "Classification was cancelled.");
143
+ }
@@ -0,0 +1,10 @@
1
+ import { type ClassifierComparisonResult, type ClassifierResult, type ClassifierSettings } from "./types.js";
2
+ export type ClassifyOptions = {
3
+ settings: ClassifierSettings;
4
+ cwd: string;
5
+ signal?: AbortSignal;
6
+ };
7
+ /** Default plus explicitly configured, selective fallback. Never retries a route. */
8
+ export declare function classify(params: unknown, options: ClassifyOptions): Promise<ClassifierResult>;
9
+ /** Explicit comparisons only: configured entries, no default substitution or fallback. */
10
+ export declare function compareClassifiers(params: unknown, options: ClassifyOptions): Promise<ClassifierComparisonResult>;
@@ -0,0 +1,120 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { resolveApiKey } from "./auth.js";
3
+ import { configuredDefault, configuredRoutes, resolveModel } from "./config.js";
4
+ import { prepareInput } from "./inputs.js";
5
+ import { choicePolicy, executeChoices } from "./choices.js";
6
+ import { classifyWithProvider } from "./providers.js";
7
+ import { ClassifierError, userError, } from "./types.js";
8
+ import { validateParams } from "./validation.js";
9
+ function checkCancelled(signal) {
10
+ if (signal?.aborted)
11
+ throw new ClassifierError("aborted", "Classification was cancelled.");
12
+ }
13
+ function routeKey(route) {
14
+ return JSON.stringify([route.api, route.baseUrl, route.model]);
15
+ }
16
+ function routePair(route) {
17
+ return { provider: route.route, model: route.model };
18
+ }
19
+ async function classifyOnce(input, route, options) {
20
+ checkCancelled(options.signal);
21
+ const prepared = await prepareInput(input, route, options.cwd, options.signal);
22
+ checkCancelled(options.signal);
23
+ const key = resolveApiKey(route);
24
+ const result = await executeChoices(prepared, route, choicePolicy(options.settings), (questions) => classifyWithProvider(route, { ...prepared, questions }, key, options.signal), options.signal);
25
+ if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
26
+ throw new ClassifierError("response", "Classifier result exceeds the 40 KiB tool output limit. Ask fewer questions.");
27
+ return result;
28
+ }
29
+ function permitsFallback(error) {
30
+ return (error instanceof ClassifierError &&
31
+ (error.code === "missing_credentials" ||
32
+ (error.code === "http" && [401, 404, 429].includes(error.httpStatus ?? 0))));
33
+ }
34
+ /** Default plus explicitly configured, selective fallback. Never retries a route. */
35
+ export async function classify(params, options) {
36
+ choicePolicy(options.settings);
37
+ const input = validateParams(params);
38
+ const candidates = [
39
+ configuredDefault(options.settings),
40
+ ...configuredRoutes(options.settings, "fallback"),
41
+ ];
42
+ const seen = new Set();
43
+ const attemptedRoutes = [];
44
+ let lastError;
45
+ for (const candidate of candidates) {
46
+ checkCancelled(options.signal);
47
+ const route = resolveModel(options.settings, candidate);
48
+ const key = routeKey(route);
49
+ if (seen.has(key))
50
+ continue;
51
+ seen.add(key);
52
+ attemptedRoutes.push(routePair(route));
53
+ try {
54
+ const result = await classifyOnce(input, route, options);
55
+ if (attemptedRoutes.length > 1)
56
+ result.attemptedRoutes = attemptedRoutes;
57
+ return result;
58
+ }
59
+ catch (error) {
60
+ checkCancelled(options.signal);
61
+ if (!permitsFallback(error))
62
+ throw error;
63
+ lastError = error;
64
+ }
65
+ }
66
+ throw lastError;
67
+ }
68
+ /** Explicit comparisons only: configured entries, no default substitution or fallback. */
69
+ export async function compareClassifiers(params, options) {
70
+ choicePolicy(options.settings);
71
+ const input = validateParams(params);
72
+ const candidates = configuredRoutes(options.settings, "compare");
73
+ if (candidates.length === 0)
74
+ throw new ClassifierError("configuration", "Set pi-classifier.compare to the provider/model pairs you explicitly want to compare. Each entry may incur a charge.");
75
+ const comparison = {
76
+ results: [],
77
+ cancelled: false,
78
+ };
79
+ const seen = new Set();
80
+ for (const candidate of candidates) {
81
+ if (options.signal?.aborted) {
82
+ comparison.cancelled = true;
83
+ break;
84
+ }
85
+ const start = performance.now();
86
+ let selected = candidate;
87
+ try {
88
+ const route = resolveModel(options.settings, candidate);
89
+ selected = routePair(route);
90
+ const key = routeKey(route);
91
+ if (seen.has(key))
92
+ throw new ClassifierError("configuration", "Duplicate comparison endpoint/model was not called again.");
93
+ seen.add(key);
94
+ const result = await classifyOnce(input, route, options);
95
+ comparison.results.push({
96
+ ...selected,
97
+ status: "success",
98
+ result,
99
+ durationMs: performance.now() - start,
100
+ });
101
+ }
102
+ catch (error) {
103
+ comparison.results.push({
104
+ ...selected,
105
+ status: "error",
106
+ error: {
107
+ code: error instanceof ClassifierError ? error.code : "unexpected",
108
+ message: userError(error),
109
+ },
110
+ durationMs: performance.now() - start,
111
+ });
112
+ if (options.signal?.aborted ||
113
+ (error instanceof ClassifierError && error.code === "aborted")) {
114
+ comparison.cancelled = true;
115
+ break;
116
+ }
117
+ }
118
+ }
119
+ return comparison;
120
+ }
@@ -0,0 +1,82 @@
1
+ import { type ClassifierSettings, type ClassifierRoute, type ResolvedModel } from "./types.js";
2
+ export declare const SETTINGS_KEY = "pi-classifier";
3
+ export declare const BUILT_INS: ({
4
+ id: string;
5
+ route: string;
6
+ api: "microsoft-system-one";
7
+ baseUrl: string;
8
+ credentialProvider: string;
9
+ envVar: string;
10
+ models: {
11
+ id: string;
12
+ input: "text"[];
13
+ }[];
14
+ } | {
15
+ id: string;
16
+ route: string;
17
+ api: "openai-decisions";
18
+ baseUrl: string;
19
+ credentialProvider: string;
20
+ envVar: string;
21
+ models: {
22
+ id: string;
23
+ input: ("text" | "image")[];
24
+ }[];
25
+ } | {
26
+ id: string;
27
+ route: string;
28
+ api: "perplexity-decisions";
29
+ baseUrl: string;
30
+ credentialProvider: string;
31
+ envVar: string;
32
+ models: {
33
+ id: string;
34
+ input: ("text" | "image")[];
35
+ }[];
36
+ } | {
37
+ id: string;
38
+ route: string;
39
+ api: "system-one";
40
+ baseUrl: string;
41
+ credentialProvider: string;
42
+ envVar: string;
43
+ models: ({
44
+ id: string;
45
+ input: ("text" | "image")[];
46
+ box?: never;
47
+ } | {
48
+ id: string;
49
+ input: ("text" | "image")[];
50
+ box: true;
51
+ })[];
52
+ } | {
53
+ id: string;
54
+ route: string;
55
+ api: "cloudflare-system-one";
56
+ baseUrl: string;
57
+ credentialProvider: string;
58
+ envVar: string;
59
+ models: ({
60
+ id: string;
61
+ input: ("text" | "image")[];
62
+ } | {
63
+ id: string;
64
+ input?: never;
65
+ })[];
66
+ } | {
67
+ id: string;
68
+ route: string;
69
+ api: "system-one";
70
+ baseUrl: string;
71
+ credentialProvider: string;
72
+ envVar: string;
73
+ models: {
74
+ id: string;
75
+ }[];
76
+ })[];
77
+ export declare function loadClassifierSettings(cwd: string, projectTrusted?: boolean): ClassifierSettings;
78
+ export declare function validateBaseUrl(raw: string): string;
79
+ export declare function configuredDefault(settings: ClassifierSettings): ClassifierRoute;
80
+ export declare function configuredRoutes(settings: ClassifierSettings, field: "fallback" | "compare"): ClassifierRoute[];
81
+ export declare function resolveModel(settings: ClassifierSettings, selected?: ClassifierRoute): ResolvedModel;
82
+ export declare function listModels(settings: ClassifierSettings): string;