@juvio15/pi-cliproxyapi-provider 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bjørn Aagaard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@juvio15/pi-cliproxyapi-provider",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "pi provider for CLIProxyAPI: per-family APIs, model catalog, costs, web search, usage footer",
5
+ "keywords": [
6
+ "cliproxyapi",
7
+ "pi",
8
+ "pi-package",
9
+ "provider"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "Bjørn Aagaard",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/bjoernaagaard/cliproxyapi-provider.git"
16
+ },
17
+ "files": [
18
+ "src"
19
+ ],
20
+ "type": "module",
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "scripts": {
25
+ "check": "ultracite check",
26
+ "fix": "ultracite fix",
27
+ "test": "node --test",
28
+ "typecheck": "tsc --noEmit"
29
+ },
30
+ "devDependencies": {
31
+ "@earendil-works/pi-ai": "^1.3.0",
32
+ "@earendil-works/pi-coding-agent": "^1.3.0",
33
+ "@types/node": "^22.15.21",
34
+ "oxfmt": "^0.71.0",
35
+ "oxlint": "^1.89.0",
36
+ "typebox": "1.3.27",
37
+ "typescript": "6.0.3",
38
+ "ultracite": "^8.0.2"
39
+ },
40
+ "peerDependencies": {
41
+ "@earendil-works/pi-ai": "*",
42
+ "@earendil-works/pi-coding-agent": ">=0.82.0",
43
+ "typebox": "*"
44
+ },
45
+ "engines": {
46
+ "node": ">=22.19.0"
47
+ },
48
+ "pi": {
49
+ "extensions": [
50
+ "./src/extension/index.ts"
51
+ ]
52
+ }
53
+ }
@@ -0,0 +1,400 @@
1
+ import type {
2
+ Model,
3
+ ModelPromptCache,
4
+ ThinkingLevelMap,
5
+ } from "@earendil-works/pi-ai";
6
+ import { Type } from "typebox";
7
+ import type { Static } from "typebox";
8
+ import { Value } from "typebox/value";
9
+
10
+ import { resolveEndpoints } from "./connection.ts";
11
+ import { matchModelCost, ZERO_COST } from "./costs.ts";
12
+ import type { CostCatalog } from "./costs.ts";
13
+
14
+ export type CliproxyApi =
15
+ | "anthropic-messages"
16
+ | "openai-responses"
17
+ | "openai-completions";
18
+
19
+ export type ThoughtSummary = "omitted" | "summarized";
20
+
21
+ export type ModelFamilies = Readonly<Record<string, CliproxyApi>>;
22
+
23
+ /**
24
+ * Family patterns. The wildcard is the fallback regardless of table order.
25
+ * Kimi uses Anthropic Messages. On Responses CLIProxyAPI rejects its
26
+ * prompt_cache_retention, and on Chat Completions it rejects the developer
27
+ * role pi-ai sends for system prompts. Messages takes both and caches.
28
+ */
29
+ export const MODEL_API_BY_FAMILY = {
30
+ "*": "openai-responses",
31
+ "claude-*": "anthropic-messages",
32
+ "kimi-*": "anthropic-messages",
33
+ } satisfies ModelFamilies;
34
+
35
+ const OptionalString = Type.Optional(Type.String());
36
+ const OptionalNumber = Type.Optional(Type.Number());
37
+ const EffortName = Type.String();
38
+
39
+ export const CatalogModelSchema = Type.Object({
40
+ additional_speed_tiers: Type.Optional(Type.Array(Type.String())),
41
+ context_window: OptionalNumber,
42
+ cpa_capabilities: Type.Optional(
43
+ Type.Object({
44
+ web_search: Type.Optional(Type.Boolean()),
45
+ })
46
+ ),
47
+ default_service_tier: Type.Optional(Type.Union([Type.String(), Type.Null()])),
48
+ description: OptionalString,
49
+ display_name: OptionalString,
50
+ id: OptionalString,
51
+ input_modalities: Type.Optional(Type.Array(Type.String())),
52
+ max_completion_tokens: OptionalNumber,
53
+ max_context_window: OptionalNumber,
54
+ max_output_tokens: OptionalNumber,
55
+ max_tokens: OptionalNumber,
56
+ name: OptionalString,
57
+ service_tiers: Type.Optional(
58
+ Type.Array(
59
+ Type.Union([
60
+ Type.String(),
61
+ Type.Object({
62
+ description: OptionalString,
63
+ id: OptionalString,
64
+ name: OptionalString,
65
+ }),
66
+ ])
67
+ )
68
+ ),
69
+ slug: OptionalString,
70
+ supported_reasoning_levels: Type.Optional(
71
+ Type.Array(
72
+ Type.Union([
73
+ EffortName,
74
+ Type.Object({ description: OptionalString, effort: OptionalString }),
75
+ ])
76
+ )
77
+ ),
78
+ supports_reasoning_effort_updates: Type.Optional(Type.Boolean()),
79
+ visibility: OptionalString,
80
+ });
81
+
82
+ export type CatalogModel = Static<typeof CatalogModelSchema>;
83
+
84
+ const CatalogEntries = Type.Array(CatalogModelSchema);
85
+
86
+ const CatalogEnvelope = Type.Union([
87
+ CatalogEntries,
88
+ Type.Object({ models: CatalogEntries }),
89
+ Type.Object({ data: CatalogEntries }),
90
+ ]);
91
+
92
+ export interface CliproxyModel extends Model<CliproxyApi> {
93
+ thoughtSummary: ThoughtSummary;
94
+ supportsFast: boolean;
95
+ supportsWebSearch?: boolean;
96
+ supportsReasoningEffortUpdates?: boolean;
97
+ thinkingLevelMap?: ThinkingLevelMap & { ultra?: string | null };
98
+ stale?: boolean;
99
+ lastSeenAt?: number;
100
+ staleSince?: number;
101
+ }
102
+
103
+ export interface MappingOptions {
104
+ baseUrl: string;
105
+ providerId?: string;
106
+ families?: ModelFamilies;
107
+ costs?: CostCatalog;
108
+ fast?: () => boolean;
109
+ thoughtSummaries?: Readonly<Record<string, ThoughtSummary>>;
110
+ /** Prompt cache lifetimes by model id. Core has no built-in numbers. */
111
+ promptCache?: (id: string) => ModelPromptCache | undefined;
112
+ }
113
+
114
+ export interface MappedCatalog {
115
+ models: CliproxyModel[];
116
+ fastModelIds: string[];
117
+ }
118
+
119
+ export interface CatalogFetchOptions {
120
+ baseUrl: string;
121
+ apiKey: string;
122
+ signal?: AbortSignal;
123
+ timeoutMs?: number;
124
+ fetch?: typeof globalThis.fetch;
125
+ }
126
+
127
+ export interface MergeOptions {
128
+ now?: number;
129
+ staleTtlMs?: number;
130
+ }
131
+
132
+ export const DEFAULT_MODEL_STALE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
133
+
134
+ const THINKING_LEVELS = [
135
+ "off",
136
+ "minimal",
137
+ "low",
138
+ "medium",
139
+ "high",
140
+ "xhigh",
141
+ "max",
142
+ "ultra",
143
+ ] as const;
144
+
145
+ export const selectModelApi = (
146
+ id: string,
147
+ families: ModelFamilies = MODEL_API_BY_FAMILY
148
+ ): CliproxyApi => {
149
+ const modelId = id.trim().toLowerCase();
150
+ // Prefixed aliases (<channel>/<model>, e.g. devin/claude-fable-5-1) hide
151
+ // the family at the start, so also match the segment after the last "/".
152
+ // Full-id matches win, so an explicit prefixed pattern still takes over.
153
+ const segment = modelId.slice(modelId.lastIndexOf("/") + 1);
154
+ const candidates = segment === modelId ? [modelId] : [modelId, segment];
155
+
156
+ for (const candidate of candidates) {
157
+ for (const [pattern, api] of Object.entries(families)) {
158
+ if (pattern === "*") {
159
+ continue;
160
+ }
161
+
162
+ if (
163
+ pattern.endsWith("*")
164
+ ? candidate.startsWith(pattern.slice(0, -1))
165
+ : candidate === pattern
166
+ ) {
167
+ return api;
168
+ }
169
+ }
170
+ }
171
+
172
+ return families["*"] ?? "openai-responses";
173
+ };
174
+
175
+ const thinkingMap = (efforts: string[]): CliproxyModel["thinkingLevelMap"] => {
176
+ if (efforts.length === 0) {
177
+ return undefined;
178
+ }
179
+
180
+ const map: NonNullable<CliproxyModel["thinkingLevelMap"]> = {};
181
+
182
+ for (const level of THINKING_LEVELS) {
183
+ const effort = level === "off" ? "none" : level;
184
+ map[level] = efforts.includes(effort) ? effort : null;
185
+ }
186
+
187
+ return map;
188
+ };
189
+
190
+ const positive = (...values: (number | undefined)[]): number | undefined =>
191
+ values.find(
192
+ (value) => value !== undefined && Number.isFinite(value) && value > 0
193
+ );
194
+
195
+ const capabilities = (entry: CatalogModel) => {
196
+ const efforts = (entry.supported_reasoning_levels ?? [])
197
+ .map((level) => {
198
+ const effort = Value.Check(EffortName, level)
199
+ ? level
200
+ : (level.effort ?? "");
201
+
202
+ return effort.trim().toLowerCase();
203
+ })
204
+ .filter(Boolean);
205
+
206
+ const input: ("text" | "image")[] = [];
207
+
208
+ for (const modality of entry.input_modalities ?? []) {
209
+ const value = modality.trim().toLowerCase();
210
+
211
+ if ((value === "text" || value === "image") && !input.includes(value)) {
212
+ input.push(value);
213
+ }
214
+ }
215
+
216
+ if (!input.includes("text")) {
217
+ input.unshift("text");
218
+ }
219
+
220
+ return {
221
+ contextWindow:
222
+ positive(entry.context_window, entry.max_context_window) ?? 128_000,
223
+ input,
224
+ maxTokens:
225
+ positive(
226
+ entry.max_tokens,
227
+ entry.max_output_tokens,
228
+ entry.max_completion_tokens
229
+ ) ?? 16_384,
230
+ reasoning: efforts.some((effort) => effort !== "none"),
231
+ thinkingLevelMap: thinkingMap(efforts),
232
+ };
233
+ };
234
+
235
+ const webSearchCapability = (
236
+ entry: CatalogModel
237
+ ): { supportsWebSearch?: boolean } =>
238
+ entry.cpa_capabilities?.web_search === undefined
239
+ ? {}
240
+ : { supportsWebSearch: entry.cpa_capabilities.web_search };
241
+
242
+ /** Read once per mapping, so every model in one catalog gets the same tier. */
243
+ const readFast = (options: MappingOptions): boolean =>
244
+ options.fast?.() ?? false;
245
+
246
+ const addAnthropicSettings = (
247
+ model: CliproxyModel,
248
+ options: MappingOptions
249
+ ): void => {
250
+ // pi-ai sends the session id as X-Session-Affinity only when asked.
251
+ // CLIProxyAPI's session affinity reads it to keep a session, and the
252
+ // prompt cache, on one upstream account. Responses always sends one.
253
+ model.compat = { sendSessionAffinityHeaders: true };
254
+
255
+ // pi warms the prompt cache only for models that declare its lifetimes.
256
+ const promptCache = options.promptCache?.(model.id);
257
+
258
+ if (promptCache) {
259
+ model.promptCache = promptCache;
260
+ }
261
+ };
262
+
263
+ export const mapCatalog = (
264
+ entries: readonly CatalogModel[],
265
+ options: MappingOptions
266
+ ): MappedCatalog => {
267
+ const endpoints = resolveEndpoints(options.baseUrl);
268
+ const models = new Map<string, CliproxyModel>();
269
+ const fastPricing = readFast(options);
270
+
271
+ for (const entry of entries) {
272
+ const id = (entry.slug ?? entry.id ?? "").trim();
273
+
274
+ if (!id || entry.visibility?.toLowerCase() === "hide") {
275
+ continue;
276
+ }
277
+
278
+ const api = selectModelApi(id, options.families);
279
+
280
+ const supportsFast = (entry.service_tiers?.length ?? 0) > 0;
281
+
282
+ const model: CliproxyModel = {
283
+ ...capabilities(entry),
284
+ api,
285
+ baseUrl:
286
+ api === "anthropic-messages"
287
+ ? endpoints.anthropicBaseUrl
288
+ : endpoints.openaiBaseUrl,
289
+ cost: options.costs
290
+ ? matchModelCost(
291
+ id,
292
+ options.costs,
293
+ fastPricing && supportsFast && api === "openai-responses"
294
+ )
295
+ : { ...ZERO_COST },
296
+ id,
297
+ name: (entry.display_name ?? entry.name ?? id).trim() || id,
298
+ provider: options.providerId ?? "cliproxyapi",
299
+ supportsFast,
300
+ supportsReasoningEffortUpdates:
301
+ entry.supports_reasoning_effort_updates === true,
302
+ thoughtSummary: options.thoughtSummaries?.[id] ?? "omitted",
303
+ ...webSearchCapability(entry),
304
+ };
305
+
306
+ if (api === "anthropic-messages") {
307
+ addAnthropicSettings(model, options);
308
+ }
309
+
310
+ models.set(id, model);
311
+ }
312
+
313
+ const result = [...models.values()];
314
+
315
+ return {
316
+ fastModelIds: result.flatMap((model) =>
317
+ model.supportsFast ? [model.id] : []
318
+ ),
319
+ models: result,
320
+ };
321
+ };
322
+
323
+ export class CatalogHttpError extends Error {
324
+ readonly status: number;
325
+ constructor(status: number, statusText: string) {
326
+ super(`Catalog request failed: ${status} ${statusText}`);
327
+ this.name = "CatalogHttpError";
328
+ this.status = status;
329
+ }
330
+ }
331
+
332
+ export const fetchCatalog = async (
333
+ options: CatalogFetchOptions
334
+ ): Promise<CatalogModel[]> => {
335
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 60_000);
336
+
337
+ const signal = options.signal
338
+ ? AbortSignal.any([options.signal, timeout])
339
+ : timeout;
340
+
341
+ const response = await (options.fetch ?? globalThis.fetch)(
342
+ resolveEndpoints(options.baseUrl).modelsUrl,
343
+ {
344
+ headers: {
345
+ Accept: "application/json",
346
+ Authorization: `Bearer ${options.apiKey}`,
347
+ },
348
+ signal,
349
+ }
350
+ );
351
+
352
+ if (!response.ok) {
353
+ throw new CatalogHttpError(response.status, response.statusText);
354
+ }
355
+
356
+ const payload: unknown = await response.json();
357
+
358
+ if (!Value.Check(CatalogEnvelope, payload)) {
359
+ throw new TypeError(
360
+ "Invalid model catalog: expected an array, models, or data of catalog entries"
361
+ );
362
+ }
363
+
364
+ if (Array.isArray(payload)) {
365
+ return payload;
366
+ }
367
+
368
+ return "models" in payload ? payload.models : payload.data;
369
+ };
370
+
371
+ export const mergeCatalog = (
372
+ previous: readonly CliproxyModel[],
373
+ fresh: readonly CliproxyModel[],
374
+ options: MergeOptions = {}
375
+ ): CliproxyModel[] => {
376
+ const now = options.now ?? Date.now();
377
+ const ttl = options.staleTtlMs ?? DEFAULT_MODEL_STALE_TTL_MS;
378
+ const merged = new Map<string, CliproxyModel>();
379
+
380
+ for (const model of fresh) {
381
+ const updated = { ...model, lastSeenAt: now, stale: false };
382
+ delete updated.staleSince;
383
+ merged.set(model.id, updated);
384
+ }
385
+
386
+ for (const model of previous) {
387
+ if (merged.has(model.id)) {
388
+ continue;
389
+ }
390
+
391
+ const lastSeenAt = model.lastSeenAt ?? now;
392
+ const staleSince = model.stale ? (model.staleSince ?? lastSeenAt) : now;
393
+
394
+ if (now - staleSince < ttl) {
395
+ merged.set(model.id, { ...model, lastSeenAt, stale: true, staleSince });
396
+ }
397
+ }
398
+
399
+ return [...merged.values()];
400
+ };
@@ -0,0 +1,119 @@
1
+ export interface Endpoints {
2
+ rootUrl: string;
3
+ anthropicBaseUrl: string;
4
+ openaiBaseUrl: string;
5
+ modelsUrl: string;
6
+ messagesUrl: string;
7
+ responsesUrl: string;
8
+ chatCompletionsUrl: string;
9
+ }
10
+
11
+ export interface ConnectionValues {
12
+ baseUrl?: string;
13
+ apiKey?: string;
14
+ }
15
+
16
+ export interface ResolvedConnection extends Endpoints {
17
+ baseUrl: string;
18
+ apiKey: string;
19
+ }
20
+
21
+ /** Where a connection value came from: the environment, cliproxyapi.json, pi's /login, or the built-in default. */
22
+ export type ValueSource = "env" | "cliproxyapi.json" | "login" | "default";
23
+
24
+ export interface ConnectionSources {
25
+ baseUrl: ValueSource;
26
+ /** Undefined when no API key is configured. */
27
+ apiKey?: ValueSource;
28
+ }
29
+
30
+ const HTTP_SCHEME = /^https?:\/\//iu;
31
+ const OTHER_SCHEME = /^[a-z][a-z\d+.-]*:\/\//iu;
32
+ const TRAILING_SLASHES = /\/+$/u;
33
+
34
+ const ENDPOINT_SUFFIX =
35
+ /\/(?:v1(?:\/(?:models|messages|responses|chat\/completions))?|backend-api(?:\/codex\/responses)?)$/u;
36
+
37
+ export const DEFAULT_BASE_URL = "http://127.0.0.1:8317";
38
+
39
+ export const resolveEndpoints = (baseUrl: string): Endpoints => {
40
+ const input = baseUrl.trim();
41
+
42
+ if (!input) {
43
+ throw new Error("baseUrl is empty");
44
+ }
45
+
46
+ if (OTHER_SCHEME.test(input) && !HTTP_SCHEME.test(input)) {
47
+ throw new Error("baseUrl must use HTTP or HTTPS");
48
+ }
49
+
50
+ const url = new URL(HTTP_SCHEME.test(input) ? input : `http://${input}`);
51
+
52
+ if (url.username || url.password) {
53
+ throw new Error("baseUrl must not contain credentials");
54
+ }
55
+
56
+ const path = url.pathname
57
+ .replace(TRAILING_SLASHES, "")
58
+ .replace(ENDPOINT_SUFFIX, "");
59
+
60
+ const rootUrl = `${url.origin}${path}`;
61
+
62
+ return {
63
+ anthropicBaseUrl: rootUrl,
64
+ chatCompletionsUrl: `${rootUrl}/v1/chat/completions`,
65
+ messagesUrl: `${rootUrl}/v1/messages`,
66
+ modelsUrl: `${rootUrl}/v1/models?client_version=cpa`,
67
+ openaiBaseUrl: `${rootUrl}/v1`,
68
+ responsesUrl: `${rootUrl}/v1/responses`,
69
+ rootUrl,
70
+ };
71
+ };
72
+
73
+ const firstSource = (
74
+ candidates: readonly (readonly [ValueSource, string | undefined])[]
75
+ ): ValueSource | undefined =>
76
+ candidates.find(([, value]) => value?.trim())?.[0];
77
+
78
+ /** The sources resolveConnection takes its values from, in the same priority order. Never returns the values. */
79
+ export const resolveConnectionSources = (
80
+ env: Readonly<Record<string, string | undefined>>,
81
+ file: ConnectionValues = {},
82
+ stored: ConnectionValues = {}
83
+ ): ConnectionSources => {
84
+ const baseUrl =
85
+ firstSource([
86
+ ["env", env.CLIPROXYAPI_BASE_URL],
87
+ ["cliproxyapi.json", file.baseUrl],
88
+ ["login", stored.baseUrl],
89
+ ]) ?? "default";
90
+
91
+ const apiKey = firstSource([
92
+ ["env", env.CLIPROXYAPI_API_KEY],
93
+ ["cliproxyapi.json", file.apiKey],
94
+ ["login", stored.apiKey],
95
+ ]);
96
+
97
+ return apiKey ? { apiKey, baseUrl } : { baseUrl };
98
+ };
99
+
100
+ export const resolveConnection = (
101
+ env: Readonly<Record<string, string | undefined>>,
102
+ file: ConnectionValues = {},
103
+ stored: ConnectionValues = {}
104
+ ): ResolvedConnection | null => {
105
+ const baseUrl =
106
+ [env.CLIPROXYAPI_BASE_URL, file.baseUrl, stored.baseUrl, DEFAULT_BASE_URL]
107
+ .map((value) => value?.trim())
108
+ .find(Boolean) ?? DEFAULT_BASE_URL;
109
+
110
+ const apiKey = [env.CLIPROXYAPI_API_KEY, file.apiKey, stored.apiKey]
111
+ .map((value) => value?.trim())
112
+ .find(Boolean);
113
+
114
+ if (!apiKey) {
115
+ return null;
116
+ }
117
+
118
+ return { apiKey, baseUrl, ...resolveEndpoints(baseUrl) };
119
+ };