@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,145 @@
|
|
|
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
|
+
import type { ClassifierSettings } from "./types.js";
|
|
6
|
+
|
|
7
|
+
const SETTINGS_KEY = "pi-classifier";
|
|
8
|
+
|
|
9
|
+
export class SettingsWriteError extends Error {}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Merge classifier defaults into trusted project settings without
|
|
13
|
+
* replacing unrelated top-level or extension-owned keys. The final rename is
|
|
14
|
+
* atomic on the project filesystem. Calls in this extension process are
|
|
15
|
+
* serialized by settings path so simultaneous commands cannot lose updates.
|
|
16
|
+
*/
|
|
17
|
+
export function updateProjectClassifierSettings(
|
|
18
|
+
cwd: string,
|
|
19
|
+
projectTrusted: boolean,
|
|
20
|
+
update: Pick<ClassifierSettings, "default">,
|
|
21
|
+
): Promise<void> {
|
|
22
|
+
const settingsPath = resolve(cwd, ".pi", "settings.json");
|
|
23
|
+
return withFileMutationQueue(settingsPath, () =>
|
|
24
|
+
updateProjectClassifierSettingsNow(cwd, projectTrusted, update),
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function updateProjectClassifierSettingsNow(
|
|
29
|
+
cwd: string,
|
|
30
|
+
projectTrusted: boolean,
|
|
31
|
+
update: Pick<ClassifierSettings, "default">,
|
|
32
|
+
): Promise<void> {
|
|
33
|
+
if (!projectTrusted) {
|
|
34
|
+
throw new SettingsWriteError(
|
|
35
|
+
"Project settings are not trusted. Trust this project before changing .pi/settings.json.",
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const settingsDir = join(cwd, ".pi");
|
|
40
|
+
const settingsPath = join(settingsDir, "settings.json");
|
|
41
|
+
await rejectSymlink(
|
|
42
|
+
settingsDir,
|
|
43
|
+
"The project .pi directory must not be a symbolic link.",
|
|
44
|
+
);
|
|
45
|
+
await mkdir(settingsDir, { recursive: true, mode: 0o700 });
|
|
46
|
+
await rejectSymlink(
|
|
47
|
+
settingsPath,
|
|
48
|
+
"The project settings file must not be a symbolic link.",
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
let root: Record<string, unknown> = {};
|
|
52
|
+
let mode = 0o600;
|
|
53
|
+
try {
|
|
54
|
+
const [text, stat] = await Promise.all([
|
|
55
|
+
readFile(settingsPath, "utf8"),
|
|
56
|
+
lstat(settingsPath),
|
|
57
|
+
]);
|
|
58
|
+
const parsed: unknown = JSON.parse(text);
|
|
59
|
+
if (!isRecord(parsed))
|
|
60
|
+
throw new SettingsWriteError(
|
|
61
|
+
"Project settings must contain a JSON object.",
|
|
62
|
+
);
|
|
63
|
+
root = parsed;
|
|
64
|
+
mode = stat.mode & 0o777;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error instanceof SettingsWriteError) throw error;
|
|
67
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
68
|
+
if (error instanceof SyntaxError) {
|
|
69
|
+
throw new SettingsWriteError(
|
|
70
|
+
"Project settings contain invalid JSON. Fix .pi/settings.json before changing classifier settings.",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
throw new SettingsWriteError("Could not read project settings.");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const current = root[SETTINGS_KEY];
|
|
78
|
+
if (current !== undefined && !isRecord(current)) {
|
|
79
|
+
throw new SettingsWriteError(
|
|
80
|
+
"pi-classifier settings must contain a JSON object.",
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const next: Record<string, unknown> = {
|
|
84
|
+
...(current ?? {}),
|
|
85
|
+
...withoutUndefined(update),
|
|
86
|
+
};
|
|
87
|
+
delete next.defaultProvider;
|
|
88
|
+
delete next.defaultModel;
|
|
89
|
+
root[SETTINGS_KEY] = next;
|
|
90
|
+
|
|
91
|
+
const tempPath = join(
|
|
92
|
+
settingsDir,
|
|
93
|
+
`.settings.json.pi-classifier-${randomUUID()}`,
|
|
94
|
+
);
|
|
95
|
+
let handle: Awaited<ReturnType<typeof open>> | undefined;
|
|
96
|
+
let created = false;
|
|
97
|
+
try {
|
|
98
|
+
handle = await open(tempPath, "wx", mode);
|
|
99
|
+
created = true;
|
|
100
|
+
await handle.writeFile(`${JSON.stringify(root, null, 2)}\n`, "utf8");
|
|
101
|
+
await handle.close();
|
|
102
|
+
handle = undefined;
|
|
103
|
+
await rename(tempPath, settingsPath);
|
|
104
|
+
} catch {
|
|
105
|
+
if (handle) {
|
|
106
|
+
try {
|
|
107
|
+
await handle.close();
|
|
108
|
+
} catch {
|
|
109
|
+
// Best effort before unlinking the private temporary file.
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (created) {
|
|
113
|
+
try {
|
|
114
|
+
await unlink(tempPath);
|
|
115
|
+
} catch {
|
|
116
|
+
// Best-effort cleanup only; preserve the fixed, path-free error below.
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
throw new SettingsWriteError("Could not update project settings.");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function rejectSymlink(path: string, message: string): Promise<void> {
|
|
124
|
+
try {
|
|
125
|
+
if ((await lstat(path)).isSymbolicLink())
|
|
126
|
+
throw new SettingsWriteError(message);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof SettingsWriteError) throw error;
|
|
129
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
130
|
+
throw new SettingsWriteError("Could not inspect project settings.");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
136
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function withoutUndefined<T extends Record<string, unknown>>(
|
|
140
|
+
value: T,
|
|
141
|
+
): Partial<T> {
|
|
142
|
+
return Object.fromEntries(
|
|
143
|
+
Object.entries(value).filter(([, entry]) => entry !== undefined),
|
|
144
|
+
) as Partial<T>;
|
|
145
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
export type ApiStyle =
|
|
2
|
+
| "openai-decisions"
|
|
3
|
+
| "perplexity-decisions"
|
|
4
|
+
| "system-one"
|
|
5
|
+
| "cloudflare-system-one"
|
|
6
|
+
| "microsoft-system-one";
|
|
7
|
+
|
|
8
|
+
export type Question =
|
|
9
|
+
| {
|
|
10
|
+
type: "bool";
|
|
11
|
+
instructions: string;
|
|
12
|
+
criteria?: { true?: string; false?: string };
|
|
13
|
+
}
|
|
14
|
+
| { type: "choice"; instructions: string; criteria: Record<string, string> }
|
|
15
|
+
| { type: "score"; instructions: string; criteria: string[] }
|
|
16
|
+
| { type: "box"; instructions: string };
|
|
17
|
+
|
|
18
|
+
export type Answer =
|
|
19
|
+
| { type: "bool"; probability: number }
|
|
20
|
+
| {
|
|
21
|
+
type: "choice";
|
|
22
|
+
choice: string;
|
|
23
|
+
probabilities: Record<string, number>;
|
|
24
|
+
confidence: number;
|
|
25
|
+
}
|
|
26
|
+
| {
|
|
27
|
+
type: "score";
|
|
28
|
+
score: number;
|
|
29
|
+
confidence: number;
|
|
30
|
+
probabilities?: Record<string, number>;
|
|
31
|
+
}
|
|
32
|
+
| {
|
|
33
|
+
type: "box";
|
|
34
|
+
box: { top: number; bottom: number; left: number; right: number };
|
|
35
|
+
confidence: number;
|
|
36
|
+
}
|
|
37
|
+
| { type: "refusal" };
|
|
38
|
+
|
|
39
|
+
export interface ClassifyParams {
|
|
40
|
+
state: string | Record<string, unknown> | unknown[];
|
|
41
|
+
questions: Record<string, Question>;
|
|
42
|
+
/** Regular PNG/JPEG/WebP files inside cwd; attached in this order. */
|
|
43
|
+
images?: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ModelDefinition {
|
|
47
|
+
id: string;
|
|
48
|
+
name?: string;
|
|
49
|
+
input?: ("text" | "image")[];
|
|
50
|
+
box?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ProviderSettings {
|
|
54
|
+
apiKey?: string;
|
|
55
|
+
baseUrl?: string;
|
|
56
|
+
headers?: Record<string, string>;
|
|
57
|
+
accountId?: string;
|
|
58
|
+
experimentalImages?: boolean;
|
|
59
|
+
experimentalBox?: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface CustomProviderSettings extends ProviderSettings {
|
|
63
|
+
api: ApiStyle;
|
|
64
|
+
models: ModelDefinition[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type ClassifierRoute = {
|
|
68
|
+
provider: string;
|
|
69
|
+
model: string;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export interface ClassifierSettings {
|
|
73
|
+
default?: ClassifierRoute;
|
|
74
|
+
fallback?: ClassifierRoute[];
|
|
75
|
+
compare?: ClassifierRoute[];
|
|
76
|
+
defaultProvider?: string;
|
|
77
|
+
defaultModel?: string;
|
|
78
|
+
requestTimeoutMs?: number;
|
|
79
|
+
providers?: Record<string, ProviderSettings>;
|
|
80
|
+
customProviders?: Record<string, CustomProviderSettings>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface ResolvedModel {
|
|
84
|
+
route: string;
|
|
85
|
+
provider: string;
|
|
86
|
+
model: string;
|
|
87
|
+
api: ApiStyle;
|
|
88
|
+
baseUrl: string;
|
|
89
|
+
headers: Record<string, string>;
|
|
90
|
+
configuredApiKey?: string;
|
|
91
|
+
credentialProvider: string;
|
|
92
|
+
envVar?: string;
|
|
93
|
+
images: boolean;
|
|
94
|
+
box: boolean;
|
|
95
|
+
experimentalImages: boolean;
|
|
96
|
+
requestTimeoutMs: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface PreparedImage {
|
|
100
|
+
data: string;
|
|
101
|
+
mimeType: "image/png" | "image/jpeg" | "image/webp";
|
|
102
|
+
width: number;
|
|
103
|
+
height: number;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface PreparedInput {
|
|
107
|
+
state: ClassifyParams["state"];
|
|
108
|
+
questions: Record<string, Question>;
|
|
109
|
+
images: PreparedImage[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export type ClassifierResult = {
|
|
113
|
+
provider: string;
|
|
114
|
+
model: string;
|
|
115
|
+
answers: Record<string, Answer>;
|
|
116
|
+
usage?: { inputTokens: number; outputTokens: number; totalTokens: number };
|
|
117
|
+
requestId?: string;
|
|
118
|
+
attemptedRoutes?: ClassifierRoute[];
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export type ClassifierComparisonEntry = ClassifierRoute & {
|
|
122
|
+
durationMs: number;
|
|
123
|
+
} & (
|
|
124
|
+
| { status: "success"; result: ClassifierResult }
|
|
125
|
+
| { status: "error"; error: { code: string; message: string } }
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
export type ClassifierComparisonResult = {
|
|
129
|
+
results: ClassifierComparisonEntry[];
|
|
130
|
+
cancelled: boolean;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
export class ClassifierError extends Error {
|
|
134
|
+
constructor(
|
|
135
|
+
public readonly code: string,
|
|
136
|
+
message: string,
|
|
137
|
+
public readonly httpStatus?: number,
|
|
138
|
+
) {
|
|
139
|
+
super(message);
|
|
140
|
+
this.name = "ClassifierError";
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
145
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function userError(error: unknown): string {
|
|
149
|
+
return error instanceof ClassifierError
|
|
150
|
+
? error.message
|
|
151
|
+
: "Classification failed unexpectedly. Check the selected provider configuration.";
|
|
152
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ClassifierError,
|
|
3
|
+
isRecord,
|
|
4
|
+
type ClassifyParams,
|
|
5
|
+
type Question,
|
|
6
|
+
} from "./types.js";
|
|
7
|
+
|
|
8
|
+
function invalid(message: string): never {
|
|
9
|
+
throw new ClassifierError("input", message);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function validateParams(value: unknown): ClassifyParams {
|
|
13
|
+
if (
|
|
14
|
+
!isRecord(value) ||
|
|
15
|
+
Object.keys(value).some(
|
|
16
|
+
(key) => !["state", "questions", "images"].includes(key),
|
|
17
|
+
)
|
|
18
|
+
)
|
|
19
|
+
invalid(
|
|
20
|
+
"Expected state, questions and optional images; provider/model are selected in settings.",
|
|
21
|
+
);
|
|
22
|
+
if (
|
|
23
|
+
!(
|
|
24
|
+
typeof value.state === "string" ||
|
|
25
|
+
Array.isArray(value.state) ||
|
|
26
|
+
isRecord(value.state)
|
|
27
|
+
)
|
|
28
|
+
)
|
|
29
|
+
invalid("state must be text, a JSON object or an array.");
|
|
30
|
+
validateJson(value.state, 0);
|
|
31
|
+
if (!isRecord(value.questions))
|
|
32
|
+
invalid("questions must be a map keyed by question ID.");
|
|
33
|
+
const entries = Object.entries(value.questions);
|
|
34
|
+
if (entries.length < 1 || entries.length > 32)
|
|
35
|
+
invalid("Supply between 1 and 32 questions.");
|
|
36
|
+
for (const [id, question] of entries) {
|
|
37
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(id) || !isRecord(question))
|
|
38
|
+
invalid(
|
|
39
|
+
"Question IDs must be 1–64 letters, digits, underscores or hyphens.",
|
|
40
|
+
);
|
|
41
|
+
if (
|
|
42
|
+
Object.keys(question).some(
|
|
43
|
+
(key) => !["type", "instructions", "criteria"].includes(key),
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
invalid("Unknown question field.");
|
|
47
|
+
if (
|
|
48
|
+
typeof question.instructions !== "string" ||
|
|
49
|
+
!question.instructions.trim() ||
|
|
50
|
+
question.instructions.length > 16_384
|
|
51
|
+
)
|
|
52
|
+
invalid(
|
|
53
|
+
"Each question needs non-empty instructions, at most 16384 characters.",
|
|
54
|
+
);
|
|
55
|
+
if (question.type === "bool") {
|
|
56
|
+
if (
|
|
57
|
+
question.criteria !== undefined &&
|
|
58
|
+
(!isRecord(question.criteria) ||
|
|
59
|
+
Object.entries(question.criteria).some(
|
|
60
|
+
([key, entry]) =>
|
|
61
|
+
!["true", "false"].includes(key) ||
|
|
62
|
+
typeof entry !== "string" ||
|
|
63
|
+
entry.length > 4096,
|
|
64
|
+
))
|
|
65
|
+
)
|
|
66
|
+
invalid("bool criteria must contain optional true/false descriptions.");
|
|
67
|
+
} else if (question.type === "choice") {
|
|
68
|
+
if (!isRecord(question.criteria))
|
|
69
|
+
invalid("choice criteria must map labels to descriptions.");
|
|
70
|
+
const criteria = Object.entries(question.criteria);
|
|
71
|
+
if (
|
|
72
|
+
criteria.length < 1 ||
|
|
73
|
+
criteria.length > 64 ||
|
|
74
|
+
criteria.some(
|
|
75
|
+
([key, entry]) =>
|
|
76
|
+
!key.trim() ||
|
|
77
|
+
key.length > 128 ||
|
|
78
|
+
typeof entry !== "string" ||
|
|
79
|
+
entry.length > 4096,
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
invalid("choice requires 1–64 labels with string descriptions.");
|
|
83
|
+
} else if (question.type === "score") {
|
|
84
|
+
if (
|
|
85
|
+
!Array.isArray(question.criteria) ||
|
|
86
|
+
question.criteria.length < 2 ||
|
|
87
|
+
question.criteria.length > 10 ||
|
|
88
|
+
question.criteria.some(
|
|
89
|
+
(entry) =>
|
|
90
|
+
typeof entry !== "string" || !entry.trim() || entry.length > 4096,
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
invalid(
|
|
94
|
+
"score criteria must contain 2–10 non-empty ordered descriptions.",
|
|
95
|
+
);
|
|
96
|
+
} else if (question.type === "box") {
|
|
97
|
+
if (question.criteria !== undefined)
|
|
98
|
+
invalid("box does not accept criteria.");
|
|
99
|
+
} else invalid("Question type must be bool, choice, score or box.");
|
|
100
|
+
}
|
|
101
|
+
if (
|
|
102
|
+
value.images !== undefined &&
|
|
103
|
+
(!Array.isArray(value.images) ||
|
|
104
|
+
value.images.length > 5 ||
|
|
105
|
+
value.images.some(
|
|
106
|
+
(path) =>
|
|
107
|
+
typeof path !== "string" || !path.trim() || path.length > 4096,
|
|
108
|
+
))
|
|
109
|
+
)
|
|
110
|
+
invalid("images must contain at most five local file paths.");
|
|
111
|
+
const encoded = JSON.stringify(value);
|
|
112
|
+
if (Buffer.byteLength(encoded) > 2 * 1024 * 1024)
|
|
113
|
+
invalid("Classification text and questions must be at most 2 MiB.");
|
|
114
|
+
return value as unknown as ClassifyParams;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function validateJson(value: unknown, depth: number): void {
|
|
118
|
+
if (depth > 32) invalid("state must be at most 32 levels deep.");
|
|
119
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
120
|
+
return;
|
|
121
|
+
if (typeof value === "number" && Number.isFinite(value)) return;
|
|
122
|
+
if (Array.isArray(value)) {
|
|
123
|
+
for (const entry of value) validateJson(entry, depth + 1);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (
|
|
127
|
+
isRecord(value) &&
|
|
128
|
+
(Object.getPrototypeOf(value) === Object.prototype ||
|
|
129
|
+
Object.getPrototypeOf(value) === null)
|
|
130
|
+
) {
|
|
131
|
+
for (const entry of Object.values(value)) validateJson(entry, depth + 1);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
invalid("state must contain only finite JSON values.");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function hasBox(questions: Record<string, Question>): boolean {
|
|
138
|
+
return Object.values(questions).some((question) => question.type === "box");
|
|
139
|
+
}
|