@abhishek944/pi-classifier 0.0.0-stage → 0.2.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.
- package/CHANGELOG.md +25 -0
- package/LICENSE +201 -0
- package/README.md +241 -2
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +56 -0
- package/dist/classify.d.ts +11 -0
- package/dist/classify.js +117 -0
- package/dist/config.d.ts +82 -0
- package/dist/config.js +298 -0
- package/dist/extension.d.ts +122 -0
- package/dist/extension.js +255 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.js +85 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/inputs.d.ts +2 -0
- package/dist/inputs.js +184 -0
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +614 -0
- package/dist/settings-write.d.ts +10 -0
- package/dist/settings-write.js +110 -0
- package/dist/types.d.ts +144 -0
- package/dist/types.js +18 -0
- package/dist/validation.d.ts +3 -0
- package/dist/validation.js +95 -0
- package/package.json +72 -4
- package/src/auth.ts +74 -0
- package/src/classify.ts +157 -0
- package/src/config.ts +391 -0
- package/src/extension.ts +362 -0
- package/src/http.ts +108 -0
- package/src/index.ts +17 -0
- package/src/inputs.ts +239 -0
- package/src/providers.ts +898 -0
- package/src/settings-write.ts +145 -0
- package/src/types.ts +152 -0
- package/src/validation.ts +139 -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/types.d.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
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
|
+
} | {
|
|
30
|
+
type: "score";
|
|
31
|
+
score: number;
|
|
32
|
+
confidence: number;
|
|
33
|
+
probabilities?: Record<string, number>;
|
|
34
|
+
} | {
|
|
35
|
+
type: "box";
|
|
36
|
+
box: {
|
|
37
|
+
top: number;
|
|
38
|
+
bottom: number;
|
|
39
|
+
left: number;
|
|
40
|
+
right: number;
|
|
41
|
+
};
|
|
42
|
+
confidence: number;
|
|
43
|
+
} | {
|
|
44
|
+
type: "refusal";
|
|
45
|
+
};
|
|
46
|
+
export interface ClassifyParams {
|
|
47
|
+
state: string | Record<string, unknown> | unknown[];
|
|
48
|
+
questions: Record<string, Question>;
|
|
49
|
+
/** Regular PNG/JPEG/WebP files inside cwd; attached in this order. */
|
|
50
|
+
images?: string[];
|
|
51
|
+
}
|
|
52
|
+
export interface ModelDefinition {
|
|
53
|
+
id: string;
|
|
54
|
+
name?: string;
|
|
55
|
+
input?: ("text" | "image")[];
|
|
56
|
+
box?: boolean;
|
|
57
|
+
}
|
|
58
|
+
export interface ProviderSettings {
|
|
59
|
+
apiKey?: string;
|
|
60
|
+
baseUrl?: string;
|
|
61
|
+
headers?: Record<string, string>;
|
|
62
|
+
accountId?: string;
|
|
63
|
+
experimentalImages?: boolean;
|
|
64
|
+
experimentalBox?: boolean;
|
|
65
|
+
}
|
|
66
|
+
export interface CustomProviderSettings extends ProviderSettings {
|
|
67
|
+
api: ApiStyle;
|
|
68
|
+
models: ModelDefinition[];
|
|
69
|
+
}
|
|
70
|
+
export type ClassifierRoute = {
|
|
71
|
+
provider: string;
|
|
72
|
+
model: string;
|
|
73
|
+
};
|
|
74
|
+
export interface ClassifierSettings {
|
|
75
|
+
default?: ClassifierRoute;
|
|
76
|
+
fallback?: ClassifierRoute[];
|
|
77
|
+
compare?: ClassifierRoute[];
|
|
78
|
+
defaultProvider?: string;
|
|
79
|
+
defaultModel?: string;
|
|
80
|
+
requestTimeoutMs?: number;
|
|
81
|
+
providers?: Record<string, ProviderSettings>;
|
|
82
|
+
customProviders?: Record<string, CustomProviderSettings>;
|
|
83
|
+
}
|
|
84
|
+
export interface ResolvedModel {
|
|
85
|
+
route: string;
|
|
86
|
+
provider: string;
|
|
87
|
+
model: string;
|
|
88
|
+
api: ApiStyle;
|
|
89
|
+
baseUrl: string;
|
|
90
|
+
headers: Record<string, string>;
|
|
91
|
+
configuredApiKey?: string;
|
|
92
|
+
credentialProvider: string;
|
|
93
|
+
envVar?: string;
|
|
94
|
+
images: boolean;
|
|
95
|
+
box: boolean;
|
|
96
|
+
experimentalImages: boolean;
|
|
97
|
+
requestTimeoutMs: number;
|
|
98
|
+
}
|
|
99
|
+
export interface PreparedImage {
|
|
100
|
+
data: string;
|
|
101
|
+
mimeType: "image/png" | "image/jpeg" | "image/webp";
|
|
102
|
+
width: number;
|
|
103
|
+
height: number;
|
|
104
|
+
}
|
|
105
|
+
export interface PreparedInput {
|
|
106
|
+
state: ClassifyParams["state"];
|
|
107
|
+
questions: Record<string, Question>;
|
|
108
|
+
images: PreparedImage[];
|
|
109
|
+
}
|
|
110
|
+
export type ClassifierResult = {
|
|
111
|
+
provider: string;
|
|
112
|
+
model: string;
|
|
113
|
+
answers: Record<string, Answer>;
|
|
114
|
+
usage?: {
|
|
115
|
+
inputTokens: number;
|
|
116
|
+
outputTokens: number;
|
|
117
|
+
totalTokens: number;
|
|
118
|
+
};
|
|
119
|
+
requestId?: string;
|
|
120
|
+
attemptedRoutes?: ClassifierRoute[];
|
|
121
|
+
};
|
|
122
|
+
export type ClassifierComparisonEntry = ClassifierRoute & {
|
|
123
|
+
durationMs: number;
|
|
124
|
+
} & ({
|
|
125
|
+
status: "success";
|
|
126
|
+
result: ClassifierResult;
|
|
127
|
+
} | {
|
|
128
|
+
status: "error";
|
|
129
|
+
error: {
|
|
130
|
+
code: string;
|
|
131
|
+
message: string;
|
|
132
|
+
};
|
|
133
|
+
});
|
|
134
|
+
export type ClassifierComparisonResult = {
|
|
135
|
+
results: ClassifierComparisonEntry[];
|
|
136
|
+
cancelled: boolean;
|
|
137
|
+
};
|
|
138
|
+
export declare class ClassifierError extends Error {
|
|
139
|
+
readonly code: string;
|
|
140
|
+
readonly httpStatus?: number | undefined;
|
|
141
|
+
constructor(code: string, message: string, httpStatus?: number | undefined);
|
|
142
|
+
}
|
|
143
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
144
|
+
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,95 @@
|
|
|
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.length > 64 ||
|
|
42
|
+
criteria.some(([key, entry]) => !key.trim() ||
|
|
43
|
+
key.length > 128 ||
|
|
44
|
+
typeof entry !== "string" ||
|
|
45
|
+
entry.length > 4096))
|
|
46
|
+
invalid("choice requires 1–64 labels with string descriptions.");
|
|
47
|
+
}
|
|
48
|
+
else if (question.type === "score") {
|
|
49
|
+
if (!Array.isArray(question.criteria) ||
|
|
50
|
+
question.criteria.length < 2 ||
|
|
51
|
+
question.criteria.length > 10 ||
|
|
52
|
+
question.criteria.some((entry) => typeof entry !== "string" || !entry.trim() || entry.length > 4096))
|
|
53
|
+
invalid("score criteria must contain 2–10 non-empty ordered descriptions.");
|
|
54
|
+
}
|
|
55
|
+
else if (question.type === "box") {
|
|
56
|
+
if (question.criteria !== undefined)
|
|
57
|
+
invalid("box does not accept criteria.");
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
invalid("Question type must be bool, choice, score or box.");
|
|
61
|
+
}
|
|
62
|
+
if (value.images !== undefined &&
|
|
63
|
+
(!Array.isArray(value.images) ||
|
|
64
|
+
value.images.length > 5 ||
|
|
65
|
+
value.images.some((path) => typeof path !== "string" || !path.trim() || path.length > 4096)))
|
|
66
|
+
invalid("images must contain at most five local file paths.");
|
|
67
|
+
const encoded = JSON.stringify(value);
|
|
68
|
+
if (Buffer.byteLength(encoded) > 2 * 1024 * 1024)
|
|
69
|
+
invalid("Classification text and questions must be at most 2 MiB.");
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
function validateJson(value, depth) {
|
|
73
|
+
if (depth > 32)
|
|
74
|
+
invalid("state must be at most 32 levels deep.");
|
|
75
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
76
|
+
return;
|
|
77
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
78
|
+
return;
|
|
79
|
+
if (Array.isArray(value)) {
|
|
80
|
+
for (const entry of value)
|
|
81
|
+
validateJson(entry, depth + 1);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (isRecord(value) &&
|
|
85
|
+
(Object.getPrototypeOf(value) === Object.prototype ||
|
|
86
|
+
Object.getPrototypeOf(value) === null)) {
|
|
87
|
+
for (const entry of Object.values(value))
|
|
88
|
+
validateJson(entry, depth + 1);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
invalid("state must contain only finite JSON values.");
|
|
92
|
+
}
|
|
93
|
+
export function hasBox(questions) {
|
|
94
|
+
return Object.values(questions).some((question) => question.type === "box");
|
|
95
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abhishek944/pi-classifier",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.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
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { readStoredCredential } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { ClassifierError, type ResolvedModel } from "./types.js";
|
|
3
|
+
|
|
4
|
+
/** Read the API-key entry only. Never resolve OAuth or mutate Pi's login state. */
|
|
5
|
+
export function storedApiCredential(provider: string) {
|
|
6
|
+
try {
|
|
7
|
+
const value = readStoredCredential(provider);
|
|
8
|
+
return value?.type === "api_key" ? value : undefined;
|
|
9
|
+
} catch {
|
|
10
|
+
throw new ClassifierError(
|
|
11
|
+
"credentials",
|
|
12
|
+
"Could not read Pi API-key credentials.",
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function storedValue(
|
|
18
|
+
value: string | undefined,
|
|
19
|
+
env: Record<string, string> = {},
|
|
20
|
+
): string | undefined {
|
|
21
|
+
if (!value?.trim()) return undefined;
|
|
22
|
+
value = value.trim();
|
|
23
|
+
if (value.startsWith("!")) {
|
|
24
|
+
throw new ClassifierError(
|
|
25
|
+
"credentials",
|
|
26
|
+
"Stored API-key shell commands are not supported. Use a literal key or an environment reference.",
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
let missing = false;
|
|
30
|
+
const resolved = value.replace(
|
|
31
|
+
/\$\$|\$!|\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,
|
|
32
|
+
(match, braced: string | undefined, bare: string | undefined) => {
|
|
33
|
+
if (match === "$$") return "$";
|
|
34
|
+
if (match === "$!") return "!";
|
|
35
|
+
const name = braced ?? bare ?? "";
|
|
36
|
+
const replacement = env[name] ?? process.env[name];
|
|
37
|
+
if (!replacement) missing = true;
|
|
38
|
+
return replacement ?? "";
|
|
39
|
+
},
|
|
40
|
+
);
|
|
41
|
+
return missing ? undefined : resolved.trim() || undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function resolveApiKey(route: ResolvedModel): string {
|
|
45
|
+
if (route.configuredApiKey) return route.configuredApiKey;
|
|
46
|
+
const credential = storedApiCredential(route.credentialProvider);
|
|
47
|
+
const key =
|
|
48
|
+
storedValue(credential?.key, credential?.env) ??
|
|
49
|
+
(route.envVar ? process.env[route.envVar]?.trim() : undefined);
|
|
50
|
+
if (!key) {
|
|
51
|
+
throw new ClassifierError(
|
|
52
|
+
"missing_credentials",
|
|
53
|
+
"No API key is configured for the selected classifier. Set providers.<id>.apiKey, save an API-key credential in Pi, or set the provider environment variable. Codex/OAuth tokens are not used.",
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return key;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function cloudflareAccountId(configured: string | undefined): string {
|
|
60
|
+
const stored = configured
|
|
61
|
+
? undefined
|
|
62
|
+
: storedApiCredential("cloudflare-workers-ai");
|
|
63
|
+
const id =
|
|
64
|
+
configured?.trim() ??
|
|
65
|
+
storedValue(stored?.env?.CLOUDFLARE_ACCOUNT_ID, stored?.env) ??
|
|
66
|
+
process.env.CLOUDFLARE_ACCOUNT_ID?.trim();
|
|
67
|
+
if (!id || !/^[a-zA-Z0-9_-]+$/.test(id)) {
|
|
68
|
+
throw new ClassifierError(
|
|
69
|
+
"configuration",
|
|
70
|
+
"Cloudflare requires a valid accountId or CLOUDFLARE_ACCOUNT_ID.",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return id;
|
|
74
|
+
}
|
package/src/classify.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
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 { classifyWithProvider } from "./providers.js";
|
|
6
|
+
import {
|
|
7
|
+
ClassifierError,
|
|
8
|
+
userError,
|
|
9
|
+
type ClassifierComparisonResult,
|
|
10
|
+
type ClassifierResult,
|
|
11
|
+
type ClassifierRoute,
|
|
12
|
+
type ClassifierSettings,
|
|
13
|
+
type ClassifyParams,
|
|
14
|
+
type ResolvedModel,
|
|
15
|
+
} from "./types.js";
|
|
16
|
+
import { validateParams } from "./validation.js";
|
|
17
|
+
|
|
18
|
+
type ClassifyOptions = {
|
|
19
|
+
settings: ClassifierSettings;
|
|
20
|
+
cwd: string;
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function checkCancelled(signal?: AbortSignal): void {
|
|
25
|
+
if (signal?.aborted)
|
|
26
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function routeKey(route: ResolvedModel): string {
|
|
30
|
+
return JSON.stringify([route.api, route.baseUrl, route.model]);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function routePair(route: ResolvedModel): ClassifierRoute {
|
|
34
|
+
return { provider: route.route, model: route.model };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function classifyOnce(
|
|
38
|
+
input: ClassifyParams,
|
|
39
|
+
route: ResolvedModel,
|
|
40
|
+
options: ClassifyOptions,
|
|
41
|
+
): Promise<ClassifierResult> {
|
|
42
|
+
checkCancelled(options.signal);
|
|
43
|
+
const prepared = await prepareInput(input, route, options.cwd, options.signal);
|
|
44
|
+
checkCancelled(options.signal);
|
|
45
|
+
const key = resolveApiKey(route);
|
|
46
|
+
const result = await classifyWithProvider(route, prepared, key, options.signal);
|
|
47
|
+
if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
|
|
48
|
+
throw new ClassifierError(
|
|
49
|
+
"response",
|
|
50
|
+
"Classifier result exceeds the 40 KiB tool output limit. Ask fewer questions.",
|
|
51
|
+
);
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function permitsFallback(error: unknown): boolean {
|
|
56
|
+
return (
|
|
57
|
+
error instanceof ClassifierError &&
|
|
58
|
+
(error.code === "missing_credentials" ||
|
|
59
|
+
(error.code === "http" && [401, 404, 429].includes(error.httpStatus ?? 0)))
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Default plus explicitly configured, selective fallback. Never retries a route. */
|
|
64
|
+
export async function classify(
|
|
65
|
+
params: unknown,
|
|
66
|
+
options: ClassifyOptions,
|
|
67
|
+
): Promise<ClassifierResult> {
|
|
68
|
+
const input = validateParams(params);
|
|
69
|
+
const candidates = [
|
|
70
|
+
configuredDefault(options.settings),
|
|
71
|
+
...configuredRoutes(options.settings, "fallback"),
|
|
72
|
+
];
|
|
73
|
+
const seen = new Set<string>();
|
|
74
|
+
const attemptedRoutes: ClassifierRoute[] = [];
|
|
75
|
+
let lastError: unknown;
|
|
76
|
+
for (const candidate of candidates) {
|
|
77
|
+
checkCancelled(options.signal);
|
|
78
|
+
const route = resolveModel(options.settings, candidate);
|
|
79
|
+
const key = routeKey(route);
|
|
80
|
+
if (seen.has(key)) continue;
|
|
81
|
+
seen.add(key);
|
|
82
|
+
attemptedRoutes.push(routePair(route));
|
|
83
|
+
try {
|
|
84
|
+
const result = await classifyOnce(input, route, options);
|
|
85
|
+
if (attemptedRoutes.length > 1) result.attemptedRoutes = attemptedRoutes;
|
|
86
|
+
return result;
|
|
87
|
+
} catch (error) {
|
|
88
|
+
checkCancelled(options.signal);
|
|
89
|
+
if (!permitsFallback(error)) throw error;
|
|
90
|
+
lastError = error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
throw lastError;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Explicit comparisons only: configured entries, no default substitution or fallback. */
|
|
97
|
+
export async function compareClassifiers(
|
|
98
|
+
params: unknown,
|
|
99
|
+
options: ClassifyOptions,
|
|
100
|
+
): Promise<ClassifierComparisonResult> {
|
|
101
|
+
const input = validateParams(params);
|
|
102
|
+
const candidates = configuredRoutes(options.settings, "compare");
|
|
103
|
+
if (candidates.length === 0)
|
|
104
|
+
throw new ClassifierError(
|
|
105
|
+
"configuration",
|
|
106
|
+
"Set pi-classifier.compare to the provider/model pairs you explicitly want to compare. Each entry may incur a charge.",
|
|
107
|
+
);
|
|
108
|
+
const comparison: ClassifierComparisonResult = {
|
|
109
|
+
results: [],
|
|
110
|
+
cancelled: false,
|
|
111
|
+
};
|
|
112
|
+
const seen = new Set<string>();
|
|
113
|
+
for (const candidate of candidates) {
|
|
114
|
+
if (options.signal?.aborted) {
|
|
115
|
+
comparison.cancelled = true;
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
const start = performance.now();
|
|
119
|
+
let selected = candidate;
|
|
120
|
+
try {
|
|
121
|
+
const route = resolveModel(options.settings, candidate);
|
|
122
|
+
selected = routePair(route);
|
|
123
|
+
const key = routeKey(route);
|
|
124
|
+
if (seen.has(key))
|
|
125
|
+
throw new ClassifierError(
|
|
126
|
+
"configuration",
|
|
127
|
+
"Duplicate comparison endpoint/model was not called again.",
|
|
128
|
+
);
|
|
129
|
+
seen.add(key);
|
|
130
|
+
const result = await classifyOnce(input, route, options);
|
|
131
|
+
comparison.results.push({
|
|
132
|
+
...selected,
|
|
133
|
+
status: "success",
|
|
134
|
+
result,
|
|
135
|
+
durationMs: performance.now() - start,
|
|
136
|
+
});
|
|
137
|
+
} catch (error) {
|
|
138
|
+
comparison.results.push({
|
|
139
|
+
...selected,
|
|
140
|
+
status: "error",
|
|
141
|
+
error: {
|
|
142
|
+
code: error instanceof ClassifierError ? error.code : "unexpected",
|
|
143
|
+
message: userError(error),
|
|
144
|
+
},
|
|
145
|
+
durationMs: performance.now() - start,
|
|
146
|
+
});
|
|
147
|
+
if (
|
|
148
|
+
options.signal?.aborted ||
|
|
149
|
+
(error instanceof ClassifierError && error.code === "aborted")
|
|
150
|
+
) {
|
|
151
|
+
comparison.cancelled = true;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return comparison;
|
|
157
|
+
}
|