@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.
- package/CHANGELOG.md +37 -0
- package/LICENSE +201 -0
- package/README.md +425 -2
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +56 -0
- package/dist/choices.d.ts +8 -0
- package/dist/choices.js +131 -0
- package/dist/classification-tree.d.ts +4 -0
- package/dist/classification-tree.js +143 -0
- package/dist/classify.d.ts +10 -0
- package/dist/classify.js +120 -0
- package/dist/config.d.ts +82 -0
- package/dist/config.js +338 -0
- package/dist/cost.d.ts +8 -0
- package/dist/cost.js +202 -0
- package/dist/extension.d.ts +249 -0
- package/dist/extension.js +380 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.js +85 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/inputs.d.ts +4 -0
- package/dist/inputs.js +184 -0
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +624 -0
- package/dist/settings-write.d.ts +10 -0
- package/dist/settings-write.js +110 -0
- package/dist/tree.d.ts +4 -0
- package/dist/tree.js +136 -0
- package/dist/types.d.ts +228 -0
- package/dist/types.js +18 -0
- package/dist/validation.d.ts +3 -0
- package/dist/validation.js +94 -0
- package/package.json +72 -4
- package/src/auth.ts +74 -0
- package/src/choices.ts +173 -0
- package/src/classification-tree.ts +181 -0
- package/src/classify.ts +167 -0
- package/src/config.ts +442 -0
- package/src/cost.ts +250 -0
- package/src/extension.ts +511 -0
- package/src/http.ts +108 -0
- package/src/index.ts +25 -0
- package/src/inputs.ts +239 -0
- package/src/providers.ts +905 -0
- package/src/settings-write.ts +145 -0
- package/src/tree.ts +157 -0
- package/src/types.ts +248 -0
- package/src/validation.ts +138 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
loadPiSettings,
|
|
6
|
+
resolveConfigDir,
|
|
7
|
+
} from "@amaster.ai/pi-shared/settings";
|
|
8
|
+
import { cloudflareAccountId } from "./auth.js";
|
|
9
|
+
import { resolvePricing } from "./cost.js";
|
|
10
|
+
import { choicePolicy } from "./choices.js";
|
|
11
|
+
import {
|
|
12
|
+
ClassifierError,
|
|
13
|
+
isRecord,
|
|
14
|
+
type ApiStyle,
|
|
15
|
+
type ClassifierSettings,
|
|
16
|
+
type ClassifierRoute,
|
|
17
|
+
type ModelDefinition,
|
|
18
|
+
type ProviderSettings,
|
|
19
|
+
type ResolvedModel,
|
|
20
|
+
} from "./types.js";
|
|
21
|
+
|
|
22
|
+
export const SETTINGS_KEY = "pi-classifier";
|
|
23
|
+
export const BUILT_INS = [
|
|
24
|
+
{
|
|
25
|
+
id: "microsoft",
|
|
26
|
+
route: "microsoft-api",
|
|
27
|
+
api: "microsoft-system-one",
|
|
28
|
+
baseUrl: "",
|
|
29
|
+
credentialProvider: "microsoft",
|
|
30
|
+
envVar: "AZURE_API_KEY",
|
|
31
|
+
models: [{ id: "Microsoft-Decision-1", input: ["text"] }],
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
id: "openai",
|
|
35
|
+
route: "openai-api",
|
|
36
|
+
api: "openai-decisions",
|
|
37
|
+
baseUrl: "https://api.openai.com/v1",
|
|
38
|
+
credentialProvider: "openai",
|
|
39
|
+
envVar: "OPENAI_API_KEY",
|
|
40
|
+
models: [{ id: "gpt-6-luna", input: ["text", "image"] }],
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: "perplexity",
|
|
44
|
+
route: "perplexity-api",
|
|
45
|
+
api: "perplexity-decisions",
|
|
46
|
+
baseUrl: "https://api.perplexity.ai/v1",
|
|
47
|
+
credentialProvider: "perplexity",
|
|
48
|
+
envVar: "PERPLEXITY_API_KEY",
|
|
49
|
+
models: [
|
|
50
|
+
{ id: "pplx-decider-v1.1-27b", input: ["text", "image"] },
|
|
51
|
+
{ id: "pplx-decider-v1-27b", input: ["text", "image"] },
|
|
52
|
+
],
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: "typesafe",
|
|
56
|
+
route: "typesafe-api",
|
|
57
|
+
api: "system-one",
|
|
58
|
+
baseUrl: "https://api.typesafe.ai/v1",
|
|
59
|
+
credentialProvider: "typesafe",
|
|
60
|
+
envVar: "TYPESAFE_API_KEY",
|
|
61
|
+
models: [
|
|
62
|
+
{ id: "jev-latest", input: ["text", "image"] },
|
|
63
|
+
{ id: "jev-1.13.0", input: ["text", "image"] },
|
|
64
|
+
{ id: "jev-preview", input: ["text", "image"], box: true },
|
|
65
|
+
{ id: "jev-1.14.0", input: ["text", "image"], box: true },
|
|
66
|
+
],
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
id: "cloudflare",
|
|
70
|
+
route: "cloudflare-api",
|
|
71
|
+
api: "cloudflare-system-one",
|
|
72
|
+
baseUrl: "",
|
|
73
|
+
credentialProvider: "cloudflare-workers-ai",
|
|
74
|
+
envVar: "CLOUDFLARE_API_KEY",
|
|
75
|
+
models: [
|
|
76
|
+
{ id: "@cf/cloudflare/clef", input: ["text", "image"] },
|
|
77
|
+
{ id: "@cf/cloudflare/clef-flash", input: ["text", "image"] },
|
|
78
|
+
{ id: "typesafe/jev" },
|
|
79
|
+
],
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
id: "openrouter",
|
|
83
|
+
route: "openrouter-api",
|
|
84
|
+
api: "system-one",
|
|
85
|
+
baseUrl: "https://openrouter.ai/api/v1",
|
|
86
|
+
credentialProvider: "openrouter",
|
|
87
|
+
envVar: "OPENROUTER_API_KEY",
|
|
88
|
+
models: [{ id: "typesafe/jev-1.13" }, { id: "~typesafe/jev-latest" }],
|
|
89
|
+
},
|
|
90
|
+
] satisfies Array<{
|
|
91
|
+
id: string;
|
|
92
|
+
route: string;
|
|
93
|
+
api: ApiStyle;
|
|
94
|
+
baseUrl: string;
|
|
95
|
+
credentialProvider: string;
|
|
96
|
+
envVar: string;
|
|
97
|
+
models: ModelDefinition[];
|
|
98
|
+
}>;
|
|
99
|
+
|
|
100
|
+
export function loadClassifierSettings(
|
|
101
|
+
cwd: string,
|
|
102
|
+
projectTrusted = false,
|
|
103
|
+
): ClassifierSettings {
|
|
104
|
+
try {
|
|
105
|
+
// The shared loader is forgiving; malformed layers must not silently select a different route.
|
|
106
|
+
const paths = new Set([
|
|
107
|
+
join(resolveConfigDir(join(homedir(), ".pi", "agent")), "settings.json"),
|
|
108
|
+
join(resolveConfigDir(), "settings.json"),
|
|
109
|
+
...(projectTrusted ? [join(cwd, ".pi", "settings.json")] : []),
|
|
110
|
+
]);
|
|
111
|
+
for (const path of paths) validateSettingsLayer(path);
|
|
112
|
+
const settings = loadPiSettings<ClassifierSettings>(SETTINGS_KEY, {
|
|
113
|
+
cwd,
|
|
114
|
+
projectTrusted,
|
|
115
|
+
strictProjectSettings: true,
|
|
116
|
+
});
|
|
117
|
+
if (!isRecord(settings)) throw new Error();
|
|
118
|
+
return settings;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (error instanceof ClassifierError) throw error;
|
|
121
|
+
throw new ClassifierError(
|
|
122
|
+
"configuration",
|
|
123
|
+
"Could not load pi-classifier settings. Check that the namespace contains a valid JSON object.",
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function validateSettingsLayer(path: string): void {
|
|
129
|
+
let text: string;
|
|
130
|
+
try {
|
|
131
|
+
text = readFileSync(path, "utf8");
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
if (text.charCodeAt(0) === 0xfeff)
|
|
137
|
+
configuration(
|
|
138
|
+
"pi-classifier settings require UTF-8 without a BOM. Remove the BOM from settings.json; no alternate configuration was used.",
|
|
139
|
+
);
|
|
140
|
+
const root: unknown = JSON.parse(text);
|
|
141
|
+
if (
|
|
142
|
+
!isRecord(root) ||
|
|
143
|
+
(Object.hasOwn(root, SETTINGS_KEY) && !isRecord(root[SETTINGS_KEY]))
|
|
144
|
+
)
|
|
145
|
+
configuration(
|
|
146
|
+
"Settings and the pi-classifier namespace must be JSON objects, not null or arrays.",
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function configuration(message: string): never {
|
|
151
|
+
throw new ClassifierError("configuration", message);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function validateBaseUrl(raw: string): string {
|
|
155
|
+
try {
|
|
156
|
+
const url = new URL(raw);
|
|
157
|
+
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
158
|
+
if (
|
|
159
|
+
(url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) ||
|
|
160
|
+
url.username ||
|
|
161
|
+
url.password ||
|
|
162
|
+
url.search ||
|
|
163
|
+
url.hash
|
|
164
|
+
)
|
|
165
|
+
throw new Error();
|
|
166
|
+
return url.toString().replace(/\/+$/, "");
|
|
167
|
+
} catch {
|
|
168
|
+
return configuration(
|
|
169
|
+
"Provider baseUrl must be HTTPS (or loopback HTTP), without credentials, query or fragment.",
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function optionalString(value: unknown, field: string): string | undefined {
|
|
175
|
+
if (value === undefined) return undefined;
|
|
176
|
+
if (typeof value !== "string" || !value.trim())
|
|
177
|
+
return configuration(field + " must be a non-empty string.");
|
|
178
|
+
return value.trim();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function headers(value: unknown): Record<string, string> {
|
|
182
|
+
if (value === undefined) return {};
|
|
183
|
+
if (
|
|
184
|
+
!isRecord(value) ||
|
|
185
|
+
Object.entries(value).some(
|
|
186
|
+
([key, entry]) =>
|
|
187
|
+
!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(key) ||
|
|
188
|
+
typeof entry !== "string" ||
|
|
189
|
+
/[\r\n]/.test(entry),
|
|
190
|
+
)
|
|
191
|
+
) {
|
|
192
|
+
return configuration(
|
|
193
|
+
"Provider headers must be a string map with valid HTTP header names and values.",
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
const protectedNames = [
|
|
197
|
+
"authorization",
|
|
198
|
+
"api-key",
|
|
199
|
+
"content-type",
|
|
200
|
+
"content-length",
|
|
201
|
+
"host",
|
|
202
|
+
"cookie",
|
|
203
|
+
"proxy-authorization",
|
|
204
|
+
"transfer-encoding",
|
|
205
|
+
"connection",
|
|
206
|
+
];
|
|
207
|
+
if (
|
|
208
|
+
Object.values(value).some(
|
|
209
|
+
(entry) => typeof entry === "string" && /\$\{?[A-Z_]/.test(entry),
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
return configuration(
|
|
213
|
+
"Resolve header environment references in global settings, not project settings.",
|
|
214
|
+
);
|
|
215
|
+
if (
|
|
216
|
+
Object.keys(value).some((key) => protectedNames.includes(key.toLowerCase()))
|
|
217
|
+
)
|
|
218
|
+
return configuration(
|
|
219
|
+
"Authentication and transport headers cannot be overridden.",
|
|
220
|
+
);
|
|
221
|
+
return value as Record<string, string>;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function configuredDefault(settings: ClassifierSettings): ClassifierRoute {
|
|
225
|
+
if (settings.default !== undefined)
|
|
226
|
+
return routePair(settings.default, "default");
|
|
227
|
+
return routePair(
|
|
228
|
+
{ provider: settings.defaultProvider, model: settings.defaultModel },
|
|
229
|
+
"defaultProvider/defaultModel",
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function routePair(value: unknown, field: string): ClassifierRoute {
|
|
234
|
+
if (!isRecord(value))
|
|
235
|
+
return configuration(field + " must be a provider/model pair.");
|
|
236
|
+
const provider = optionalString(value.provider, field + ".provider");
|
|
237
|
+
const model = optionalString(value.model, field + ".model");
|
|
238
|
+
if (!provider || !model)
|
|
239
|
+
return configuration(field + " requires provider and model.");
|
|
240
|
+
return { provider, model };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function configuredRoutes(
|
|
244
|
+
settings: ClassifierSettings,
|
|
245
|
+
field: "fallback" | "compare",
|
|
246
|
+
): ClassifierRoute[] {
|
|
247
|
+
const value = settings[field];
|
|
248
|
+
if (value === undefined) return [];
|
|
249
|
+
if (!Array.isArray(value))
|
|
250
|
+
return configuration(field + " must be an array of provider/model pairs.");
|
|
251
|
+
return value.map((entry, index) => routePair(entry, field + "[" + index + "]"));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function resolveModel(
|
|
255
|
+
settings: ClassifierSettings,
|
|
256
|
+
selected: ClassifierRoute = configuredDefault(settings),
|
|
257
|
+
): ResolvedModel {
|
|
258
|
+
choicePolicy(settings);
|
|
259
|
+
const { provider: routeId, model: modelId } = routePair(selected, "route");
|
|
260
|
+
if (
|
|
261
|
+
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(routeId) ||
|
|
262
|
+
modelId.length > 256 ||
|
|
263
|
+
/[\u0000-\u001f\u007f]/.test(modelId)
|
|
264
|
+
)
|
|
265
|
+
return configuration(
|
|
266
|
+
"Provider routes must be short identifiers and model IDs must be at most 256 characters without control characters.",
|
|
267
|
+
);
|
|
268
|
+
const builtIn = BUILT_INS.find(
|
|
269
|
+
(entry) => entry.route === routeId || entry.id === routeId,
|
|
270
|
+
);
|
|
271
|
+
if (settings.providers !== undefined && !isRecord(settings.providers))
|
|
272
|
+
return configuration("providers must be an object.");
|
|
273
|
+
if (
|
|
274
|
+
settings.customProviders !== undefined &&
|
|
275
|
+
!isRecord(settings.customProviders)
|
|
276
|
+
)
|
|
277
|
+
return configuration("customProviders must be an object.");
|
|
278
|
+
for (const name of Object.keys(settings.customProviders ?? {})) {
|
|
279
|
+
if (BUILT_INS.some((entry) => entry.route === name || entry.id === name))
|
|
280
|
+
return configuration("Custom providers cannot shadow built-in routes.");
|
|
281
|
+
}
|
|
282
|
+
const custom = builtIn ? undefined : settings.customProviders?.[routeId];
|
|
283
|
+
if (!builtIn && !custom)
|
|
284
|
+
return configuration("Unknown classifier provider route.");
|
|
285
|
+
const raw: ProviderSettings = builtIn
|
|
286
|
+
? (settings.providers?.[builtIn.id] ?? {})
|
|
287
|
+
: custom!;
|
|
288
|
+
if (!isRecord(raw))
|
|
289
|
+
return configuration("Provider settings must be an object.");
|
|
290
|
+
const api = builtIn?.api ?? custom!.api;
|
|
291
|
+
if (
|
|
292
|
+
![
|
|
293
|
+
"openai-decisions",
|
|
294
|
+
"perplexity-decisions",
|
|
295
|
+
"system-one",
|
|
296
|
+
"cloudflare-system-one",
|
|
297
|
+
"microsoft-system-one",
|
|
298
|
+
].includes(api)
|
|
299
|
+
)
|
|
300
|
+
return configuration("Unsupported classifier API protocol.");
|
|
301
|
+
const models: ModelDefinition[] = builtIn?.models ?? custom!.models;
|
|
302
|
+
if (
|
|
303
|
+
!Array.isArray(models) ||
|
|
304
|
+
models.length === 0 ||
|
|
305
|
+
models.some(
|
|
306
|
+
(m) =>
|
|
307
|
+
!isRecord(m) ||
|
|
308
|
+
typeof m.id !== "string" ||
|
|
309
|
+
!m.id.trim() ||
|
|
310
|
+
(m.input !== undefined &&
|
|
311
|
+
(!Array.isArray(m.input) ||
|
|
312
|
+
m.input.some((x) => x !== "text" && x !== "image"))) ||
|
|
313
|
+
(m.box !== undefined && typeof m.box !== "boolean"),
|
|
314
|
+
)
|
|
315
|
+
) {
|
|
316
|
+
return configuration(
|
|
317
|
+
"Provider models must declare an id and optional text/image input capabilities.",
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
const definition = models.find((entry) => entry.id === modelId);
|
|
321
|
+
// Built-in API routes allow new text model IDs without a package release. Images require known capabilities.
|
|
322
|
+
if (!definition && !builtIn)
|
|
323
|
+
return configuration(
|
|
324
|
+
"The selected model is not declared in customProviders.<id>.models.",
|
|
325
|
+
);
|
|
326
|
+
for (const flag of ["experimentalImages", "experimentalBox"] as const) {
|
|
327
|
+
if (raw[flag] !== undefined && typeof raw[flag] !== "boolean")
|
|
328
|
+
return configuration(flag + " must be a boolean.");
|
|
329
|
+
}
|
|
330
|
+
let baseUrl = optionalString(raw.baseUrl, "baseUrl") ?? builtIn?.baseUrl;
|
|
331
|
+
if (api === "cloudflare-system-one" && !baseUrl)
|
|
332
|
+
baseUrl =
|
|
333
|
+
"https://api.cloudflare.com/client/v4/accounts/" +
|
|
334
|
+
cloudflareAccountId(optionalString(raw.accountId, "accountId")) +
|
|
335
|
+
"/ai";
|
|
336
|
+
if (!baseUrl)
|
|
337
|
+
return configuration(
|
|
338
|
+
"The selected provider requires a baseUrl. Microsoft uses your Foundry resource endpoint.",
|
|
339
|
+
);
|
|
340
|
+
const timeout = settings.requestTimeoutMs ?? 30_000;
|
|
341
|
+
if (!Number.isInteger(timeout) || timeout < 100 || timeout > 300_000)
|
|
342
|
+
return configuration("requestTimeoutMs must be between 100 and 300000.");
|
|
343
|
+
if (raw.apiKey !== undefined && typeof raw.apiKey !== "string")
|
|
344
|
+
return configuration("apiKey must be a string.");
|
|
345
|
+
const configuredApiKey =
|
|
346
|
+
typeof raw.apiKey === "string" ? raw.apiKey.trim() || undefined : undefined;
|
|
347
|
+
if (configuredApiKey && /\$\{?|^!/.test(configuredApiKey))
|
|
348
|
+
return configuration(
|
|
349
|
+
"API-key references must be resolved in global settings; project settings cannot expand environment variables or execute commands.",
|
|
350
|
+
);
|
|
351
|
+
const isJevDirect = builtIn?.id === "typesafe";
|
|
352
|
+
const result: ResolvedModel = {
|
|
353
|
+
route: builtIn?.route ?? routeId,
|
|
354
|
+
provider: builtIn?.id ?? routeId,
|
|
355
|
+
model: modelId,
|
|
356
|
+
api,
|
|
357
|
+
baseUrl: validateBaseUrl(baseUrl),
|
|
358
|
+
headers: headers(raw.headers),
|
|
359
|
+
credentialProvider: builtIn?.credentialProvider ?? routeId,
|
|
360
|
+
images:
|
|
361
|
+
api === "microsoft-system-one"
|
|
362
|
+
? false
|
|
363
|
+
: api === "system-one"
|
|
364
|
+
? Boolean(
|
|
365
|
+
raw.experimentalImages && definition?.input?.includes("image"),
|
|
366
|
+
)
|
|
367
|
+
: Boolean(definition?.input?.includes("image")),
|
|
368
|
+
box: Boolean(
|
|
369
|
+
(isJevDirect || custom?.api === "system-one") &&
|
|
370
|
+
definition?.box &&
|
|
371
|
+
definition?.input?.includes("image") &&
|
|
372
|
+
raw.experimentalBox &&
|
|
373
|
+
raw.experimentalImages,
|
|
374
|
+
),
|
|
375
|
+
experimentalImages: raw.experimentalImages === true,
|
|
376
|
+
requestTimeoutMs: timeout,
|
|
377
|
+
};
|
|
378
|
+
const pricing = resolvePricing(
|
|
379
|
+
result.provider,
|
|
380
|
+
modelId,
|
|
381
|
+
result.baseUrl,
|
|
382
|
+
raw.pricing,
|
|
383
|
+
);
|
|
384
|
+
if (pricing) result.pricing = pricing;
|
|
385
|
+
if (raw.maxChoices !== undefined) {
|
|
386
|
+
if (
|
|
387
|
+
typeof raw.maxChoices !== "number" ||
|
|
388
|
+
!Number.isSafeInteger(raw.maxChoices) ||
|
|
389
|
+
raw.maxChoices < 2
|
|
390
|
+
)
|
|
391
|
+
return configuration(
|
|
392
|
+
"Provider maxChoices must be a safe integer of at least 2.",
|
|
393
|
+
);
|
|
394
|
+
result.maxChoices = raw.maxChoices;
|
|
395
|
+
} else {
|
|
396
|
+
const knownLimit = knownMaxChoices(result);
|
|
397
|
+
if (knownLimit !== undefined) result.maxChoices = knownLimit;
|
|
398
|
+
}
|
|
399
|
+
if (configuredApiKey) result.configuredApiKey = configuredApiKey;
|
|
400
|
+
if (builtIn?.envVar) result.envVar = builtIn.envVar;
|
|
401
|
+
return result;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function knownMaxChoices(route: ResolvedModel): number | undefined {
|
|
405
|
+
const directJev =
|
|
406
|
+
route.provider === "typesafe" &&
|
|
407
|
+
route.baseUrl === "https://api.typesafe.ai/v1" &&
|
|
408
|
+
["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"].includes(route.model);
|
|
409
|
+
const openai =
|
|
410
|
+
route.provider === "openai" &&
|
|
411
|
+
route.baseUrl === "https://api.openai.com/v1" &&
|
|
412
|
+
route.model === "gpt-6-luna";
|
|
413
|
+
const perplexity =
|
|
414
|
+
route.provider === "perplexity" &&
|
|
415
|
+
route.baseUrl === "https://api.perplexity.ai/v1" &&
|
|
416
|
+
[
|
|
417
|
+
"pplx-decider-v1.1-27b",
|
|
418
|
+
"pplx-decider-v1-27b",
|
|
419
|
+
"pplx-decider-v1.2",
|
|
420
|
+
"pplx-decider-latest",
|
|
421
|
+
"pplx-decider-flash-v1.2",
|
|
422
|
+
"pplx-decider-flash-latest",
|
|
423
|
+
].includes(route.model);
|
|
424
|
+
const clef =
|
|
425
|
+
route.provider === "cloudflare" &&
|
|
426
|
+
/^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(route.baseUrl) &&
|
|
427
|
+
["@cf/cloudflare/clef", "@cf/cloudflare/clef-flash"].includes(route.model);
|
|
428
|
+
return directJev || openai || perplexity || clef ? 255 : undefined;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
export function listModels(settings: ClassifierSettings): string {
|
|
432
|
+
const lines = BUILT_INS.flatMap((provider) =>
|
|
433
|
+
provider.models.map((model) => provider.route + " " + model.id),
|
|
434
|
+
);
|
|
435
|
+
for (const [id, provider] of Object.entries(settings.customProviders ?? {})) {
|
|
436
|
+
if (Array.isArray(provider?.models))
|
|
437
|
+
for (const model of provider.models)
|
|
438
|
+
if (typeof model?.id === "string")
|
|
439
|
+
lines.push(JSON.stringify(id) + " " + JSON.stringify(model.id));
|
|
440
|
+
}
|
|
441
|
+
return lines.join("\n");
|
|
442
|
+
}
|
package/src/cost.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ClassifierError,
|
|
3
|
+
isRecord,
|
|
4
|
+
type ClassifierCost,
|
|
5
|
+
type ClassifierResult,
|
|
6
|
+
type ResolvedModel,
|
|
7
|
+
type TokenPricing,
|
|
8
|
+
} from "./types.js";
|
|
9
|
+
|
|
10
|
+
// Standard public USD rates, not account-specific billing. Sources and caveats are in README.
|
|
11
|
+
// Keep exact model matches: newer IDs and other hosts must not inherit guessed prices.
|
|
12
|
+
const PRICES: Record<string, Record<string, TokenPricing>> = {
|
|
13
|
+
openai: {
|
|
14
|
+
"gpt-6-luna": {
|
|
15
|
+
inputPerMillion: 0.1,
|
|
16
|
+
outputPerMillion: 0,
|
|
17
|
+
cachedInputPerMillion: 0.01,
|
|
18
|
+
cacheWritePerMillion: 0.125,
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
typesafe: Object.fromEntries(
|
|
22
|
+
["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"].map((id) => [
|
|
23
|
+
id,
|
|
24
|
+
{ inputPerMillion: 0.042, outputPerMillion: 0 },
|
|
25
|
+
]),
|
|
26
|
+
),
|
|
27
|
+
perplexity: {
|
|
28
|
+
"pplx-decider-v1.1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
|
|
29
|
+
"pplx-decider-v1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
|
|
30
|
+
"pplx-decider-v1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
|
|
31
|
+
"pplx-decider-latest": { inputPerMillion: 0.02, outputPerMillion: 0 },
|
|
32
|
+
"pplx-decider-flash-v1.2": { inputPerMillion: 0.01, outputPerMillion: 0 },
|
|
33
|
+
"pplx-decider-flash-latest": { inputPerMillion: 0.01, outputPerMillion: 0 },
|
|
34
|
+
},
|
|
35
|
+
cloudflare: {
|
|
36
|
+
"@cf/cloudflare/clef": { inputPerMillion: 0.24, outputPerMillion: 0 },
|
|
37
|
+
"@cf/cloudflare/clef-flash": { inputPerMillion: 0.038, outputPerMillion: 0 },
|
|
38
|
+
"typesafe/jev": {
|
|
39
|
+
inputPerMillion: 0.042,
|
|
40
|
+
outputPerMillion: 0,
|
|
41
|
+
cachedInputPerMillion: 0,
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Validate overrides before a request; use public prices only for known official endpoints. */
|
|
47
|
+
export function resolvePricing(
|
|
48
|
+
provider: string,
|
|
49
|
+
model: string,
|
|
50
|
+
baseUrl: string,
|
|
51
|
+
overrides: unknown,
|
|
52
|
+
): ResolvedModel["pricing"] {
|
|
53
|
+
if (overrides !== undefined) {
|
|
54
|
+
if (!isRecord(overrides))
|
|
55
|
+
throw new ClassifierError(
|
|
56
|
+
"configuration",
|
|
57
|
+
"Provider pricing must be a model-keyed object.",
|
|
58
|
+
);
|
|
59
|
+
if (Object.hasOwn(overrides, model)) {
|
|
60
|
+
const value = overrides[model];
|
|
61
|
+
const keys = [
|
|
62
|
+
"inputPerMillion",
|
|
63
|
+
"outputPerMillion",
|
|
64
|
+
"cachedInputPerMillion",
|
|
65
|
+
"cacheWritePerMillion",
|
|
66
|
+
];
|
|
67
|
+
if (
|
|
68
|
+
!isRecord(value) ||
|
|
69
|
+
Object.keys(value).some((key) => !keys.includes(key)) ||
|
|
70
|
+
!validRate(value.inputPerMillion) ||
|
|
71
|
+
!validRate(value.outputPerMillion) ||
|
|
72
|
+
keys.slice(2).some(
|
|
73
|
+
(key) => value[key] !== undefined && !validRate(value[key]),
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
throw new ClassifierError(
|
|
77
|
+
"configuration",
|
|
78
|
+
"Model pricing requires finite, non-negative inputPerMillion and outputPerMillion USD rates, with optional cachedInputPerMillion and cacheWritePerMillion.",
|
|
79
|
+
);
|
|
80
|
+
const rates: TokenPricing = {
|
|
81
|
+
inputPerMillion: value.inputPerMillion,
|
|
82
|
+
outputPerMillion: value.outputPerMillion,
|
|
83
|
+
};
|
|
84
|
+
if (validRate(value.cachedInputPerMillion))
|
|
85
|
+
rates.cachedInputPerMillion = value.cachedInputPerMillion;
|
|
86
|
+
if (validRate(value.cacheWritePerMillion))
|
|
87
|
+
rates.cacheWritePerMillion = value.cacheWritePerMillion;
|
|
88
|
+
return { rates, source: "configured" };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const official =
|
|
92
|
+
(provider === "openai" && baseUrl === "https://api.openai.com/v1") ||
|
|
93
|
+
(provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
|
|
94
|
+
(provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
|
|
95
|
+
(provider === "cloudflare" &&
|
|
96
|
+
/^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(baseUrl));
|
|
97
|
+
const catalog = Object.hasOwn(PRICES, provider) ? PRICES[provider] : undefined;
|
|
98
|
+
const rates =
|
|
99
|
+
official && catalog && Object.hasOwn(catalog, model)
|
|
100
|
+
? catalog[model]
|
|
101
|
+
: undefined;
|
|
102
|
+
return rates ? { rates: { ...rates }, source: "builtin" } : undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function validRate(value: unknown): value is number {
|
|
106
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function tokenCount(value: unknown): number | undefined {
|
|
110
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
|
|
111
|
+
? value
|
|
112
|
+
: undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function unavailable(
|
|
116
|
+
reason: Extract<ClassifierCost, { status: "unavailable" }>["reason"],
|
|
117
|
+
): ClassifierCost {
|
|
118
|
+
return { status: "unavailable", currency: "USD", reason };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Raw usage is intentional: legacy normalized usage fills missing counters with zero. */
|
|
122
|
+
export function estimateCost(
|
|
123
|
+
route: ResolvedModel,
|
|
124
|
+
usage: unknown,
|
|
125
|
+
): ClassifierCost {
|
|
126
|
+
if (!route.pricing) return unavailable("unknown_pricing");
|
|
127
|
+
if (!isRecord(usage) || usage.input_tokens === undefined)
|
|
128
|
+
return unavailable("missing_usage");
|
|
129
|
+
const inputTokens = tokenCount(usage.input_tokens);
|
|
130
|
+
if (
|
|
131
|
+
usage.output_tokens === undefined &&
|
|
132
|
+
route.pricing.rates.outputPerMillion !== 0
|
|
133
|
+
)
|
|
134
|
+
return unavailable("missing_usage");
|
|
135
|
+
// Missing output usage is harmless only when the output rate is zero.
|
|
136
|
+
const outputTokens =
|
|
137
|
+
usage.output_tokens === undefined ? 0 : tokenCount(usage.output_tokens);
|
|
138
|
+
if (inputTokens === undefined || outputTokens === undefined)
|
|
139
|
+
return unavailable("invalid_usage");
|
|
140
|
+
const details = usage.input_tokens_details;
|
|
141
|
+
if (details !== undefined && !isRecord(details))
|
|
142
|
+
return unavailable("invalid_usage");
|
|
143
|
+
const cached =
|
|
144
|
+
isRecord(details) && details.cached_tokens !== undefined
|
|
145
|
+
? tokenCount(details.cached_tokens)
|
|
146
|
+
: 0;
|
|
147
|
+
const writes =
|
|
148
|
+
isRecord(details) && details.cache_write_tokens !== undefined
|
|
149
|
+
? tokenCount(details.cache_write_tokens)
|
|
150
|
+
: 0;
|
|
151
|
+
if (
|
|
152
|
+
cached === undefined ||
|
|
153
|
+
writes === undefined ||
|
|
154
|
+
cached > inputTokens ||
|
|
155
|
+
writes > inputTokens - cached
|
|
156
|
+
)
|
|
157
|
+
return unavailable("invalid_usage");
|
|
158
|
+
const rates = { ...route.pricing.rates };
|
|
159
|
+
// The extension uses default 30m cache writes. Do not misprice an unexpected 12h write.
|
|
160
|
+
if (isRecord(details) && details.cache_write_tokens_details !== undefined) {
|
|
161
|
+
const writeDetails = details.cache_write_tokens_details;
|
|
162
|
+
if (!isRecord(writeDetails)) return unavailable("invalid_usage");
|
|
163
|
+
const shortWrites = tokenCount(writeDetails.ttl_30m_tokens);
|
|
164
|
+
const longWrites = tokenCount(writeDetails.ttl_12h_tokens);
|
|
165
|
+
if (
|
|
166
|
+
shortWrites === undefined ||
|
|
167
|
+
longWrites === undefined ||
|
|
168
|
+
shortWrites > writes ||
|
|
169
|
+
longWrites !== writes - shortWrites
|
|
170
|
+
)
|
|
171
|
+
return unavailable("invalid_usage");
|
|
172
|
+
if (longWrites > 0) return unavailable("missing_cache_pricing");
|
|
173
|
+
}
|
|
174
|
+
if (
|
|
175
|
+
(cached > 0 && rates.cachedInputPerMillion === undefined) ||
|
|
176
|
+
(writes > 0 && rates.cacheWritePerMillion === undefined)
|
|
177
|
+
)
|
|
178
|
+
return unavailable("missing_cache_pricing");
|
|
179
|
+
// OpenAI doubles input rates for >272K context. Overrides already define effective rates.
|
|
180
|
+
if (
|
|
181
|
+
route.provider === "openai" &&
|
|
182
|
+
route.pricing.source === "builtin" &&
|
|
183
|
+
inputTokens > 272_000
|
|
184
|
+
) {
|
|
185
|
+
rates.inputPerMillion *= 2;
|
|
186
|
+
if (rates.cachedInputPerMillion !== undefined)
|
|
187
|
+
rates.cachedInputPerMillion *= 2;
|
|
188
|
+
if (rates.cacheWritePerMillion !== undefined)
|
|
189
|
+
rates.cacheWritePerMillion *= 2;
|
|
190
|
+
}
|
|
191
|
+
const input =
|
|
192
|
+
((inputTokens - cached - writes) / 1_000_000) * rates.inputPerMillion +
|
|
193
|
+
(cached / 1_000_000) * (rates.cachedInputPerMillion ?? 0) +
|
|
194
|
+
(writes / 1_000_000) * (rates.cacheWritePerMillion ?? 0);
|
|
195
|
+
const output = (outputTokens / 1_000_000) * rates.outputPerMillion;
|
|
196
|
+
const total = input + output;
|
|
197
|
+
if (![input, output, total].every(Number.isFinite))
|
|
198
|
+
return unavailable("calculation_overflow");
|
|
199
|
+
return {
|
|
200
|
+
status: "estimated",
|
|
201
|
+
currency: "USD",
|
|
202
|
+
input,
|
|
203
|
+
output,
|
|
204
|
+
total,
|
|
205
|
+
rates,
|
|
206
|
+
source: route.pricing.source,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function sumUsage(
|
|
211
|
+
left: ClassifierResult["usage"],
|
|
212
|
+
right: ClassifierResult["usage"],
|
|
213
|
+
): ClassifierResult["usage"] {
|
|
214
|
+
if (!left || !right) return undefined;
|
|
215
|
+
const result: NonNullable<ClassifierResult["usage"]> = {
|
|
216
|
+
inputTokens: left.inputTokens + right.inputTokens,
|
|
217
|
+
outputTokens: left.outputTokens + right.outputTokens,
|
|
218
|
+
totalTokens: left.totalTokens + right.totalTokens,
|
|
219
|
+
};
|
|
220
|
+
if (!Object.values(result).every(Number.isSafeInteger)) return undefined;
|
|
221
|
+
for (const field of ["cachedInputTokens", "cacheWriteTokens"] as const) {
|
|
222
|
+
if (left[field] !== undefined && right[field] !== undefined) {
|
|
223
|
+
const total = left[field] + right[field];
|
|
224
|
+
if (Number.isSafeInteger(total)) result[field] = total;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function sumCost(left: ClassifierCost, right: ClassifierCost): ClassifierCost {
|
|
231
|
+
if (left.status === "unavailable") return left;
|
|
232
|
+
if (right.status === "unavailable") return right;
|
|
233
|
+
const input = left.input + right.input;
|
|
234
|
+
const output = left.output + right.output;
|
|
235
|
+
const total = input + output;
|
|
236
|
+
if (![input, output, total].every(Number.isFinite))
|
|
237
|
+
return {
|
|
238
|
+
status: "unavailable",
|
|
239
|
+
currency: "USD",
|
|
240
|
+
reason: "calculation_overflow",
|
|
241
|
+
};
|
|
242
|
+
return {
|
|
243
|
+
status: "estimated",
|
|
244
|
+
currency: "USD",
|
|
245
|
+
source: "aggregated",
|
|
246
|
+
input,
|
|
247
|
+
output,
|
|
248
|
+
total,
|
|
249
|
+
};
|
|
250
|
+
}
|