pi-cliproxyapi 0.4.3 → 0.5.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/README.md +78 -7
- package/index.ts +182 -105
- package/package.json +2 -1
- package/src/aliases.ts +520 -0
- package/src/apply.ts +80 -3
- package/src/cache-namespace.ts +21 -0
- package/src/cache.ts +58 -3
- package/src/config.ts +2 -0
- package/src/fetch-models.ts +119 -15
- package/src/fetch-usage.ts +297 -11
- package/src/quota-footer.ts +255 -0
- package/src/quota-format.ts +74 -0
- package/src/status-quota.ts +188 -34
- package/src/ui-hub/hub.ts +10 -1
- package/src/ui-hub/view-usage.ts +9 -2
- package/src/ui-usage.ts +178 -34
- package/src/usage-shared-cache.ts +303 -24
package/src/aliases.ts
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
// `latest/*` alias models.
|
|
2
|
+
//
|
|
3
|
+
// The bridge resolves model families (`opus`, `gpt-sol`, ...) to their newest
|
|
4
|
+
// concrete model and publishes the result in the catalogue. Each resolution is
|
|
5
|
+
// registered as a selectable model under the `latest` provider, with the
|
|
6
|
+
// metadata of the model it resolves to.
|
|
7
|
+
//
|
|
8
|
+
// An alias is never meant to serve a session: when a session starts with, or
|
|
9
|
+
// switches to, `latest/<alias>`, it is switched to the concrete model with
|
|
10
|
+
// pi.setModel. The session file then records the concrete model, so a resumed
|
|
11
|
+
// session keeps the version it was pinned to and the prompt cache is never
|
|
12
|
+
// broken by a silent upgrade, while the next new session picks the newest.
|
|
13
|
+
|
|
14
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
15
|
+
import type {
|
|
16
|
+
ExtensionAPI,
|
|
17
|
+
ProviderConfig,
|
|
18
|
+
ProviderModelConfig,
|
|
19
|
+
} from "@earendil-works/pi-coding-agent";
|
|
20
|
+
|
|
21
|
+
import type { DiscoveryAlias } from "./fetch-models.ts";
|
|
22
|
+
import { log } from "./log.ts";
|
|
23
|
+
|
|
24
|
+
/** Pi provider the aliases are registered under: `latest/opus`. */
|
|
25
|
+
export const ALIAS_PROVIDER = "latest";
|
|
26
|
+
|
|
27
|
+
/** CLIProxyAPI provider key → the Pi built-in provider this extension registers it as. */
|
|
28
|
+
const PI_PROVIDER_FOR: Record<string, string> = {
|
|
29
|
+
claude: "anthropic",
|
|
30
|
+
codex: "openai",
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** CLIProxyAPI provider keys whose models a Pi built-in provider serves. */
|
|
34
|
+
export function upstreamForBuiltin(piProvider: string): string[] {
|
|
35
|
+
return Object.entries(PI_PROVIDER_FOR)
|
|
36
|
+
.filter(([, pi]) => pi === piProvider)
|
|
37
|
+
.map(([key]) => key);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* CLIProxyAPI provider key of a custom-pool model: CLIProxyAPI reports an
|
|
42
|
+
* OpenAI-compatible upstream's name as `owned_by` and keys its credentials by
|
|
43
|
+
* that name in lower case, which is what the catalogue's alias names.
|
|
44
|
+
*/
|
|
45
|
+
export function upstreamForCustom(ownedBy: string | undefined): string[] {
|
|
46
|
+
const key = (ownedBy ?? "").trim().toLowerCase();
|
|
47
|
+
return key ? [key] : [];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Longest family pattern accepted from the catalogue. */
|
|
51
|
+
const MAX_PATTERN_LENGTH = 256;
|
|
52
|
+
/** Most optional groups / digit runs a family pattern may have. */
|
|
53
|
+
const MAX_PATTERN_GROUPS = 4;
|
|
54
|
+
const MAX_PATTERN_DIGIT_RUNS = 6;
|
|
55
|
+
/** Model ids longer than this are never matched against a family pattern. */
|
|
56
|
+
const MAX_MATCH_ID_LENGTH = 256;
|
|
57
|
+
|
|
58
|
+
type PatternToken =
|
|
59
|
+
| { t: "lit"; c: string }
|
|
60
|
+
| { t: "num"; capture: boolean }
|
|
61
|
+
| { t: "open" }
|
|
62
|
+
| { t: "close" };
|
|
63
|
+
|
|
64
|
+
const LITERAL = /[A-Za-z0-9_\-/:@]/;
|
|
65
|
+
const ESCAPED_LITERAL = /[.\-_/:@]/;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Tokens of a family pattern if it is inside the safe grammar, else null.
|
|
69
|
+
*
|
|
70
|
+
* The bridge's patterns are Go regexps, which match in linear time; JS RegExp
|
|
71
|
+
* backtracks, and a match runs synchronously on Pi's event loop. So a pattern
|
|
72
|
+
* is used only when it is in a grammar that cannot backtrack badly: anchored
|
|
73
|
+
* `^…$`, literal characters (`\.` escaped), `\d+`, `(\d+)`, and flat optional
|
|
74
|
+
* groups `(?:…)?` that start with a non-digit literal. No alternation, no
|
|
75
|
+
* classes, no `*`/`{}`/nested quantifiers, and a digit run is never directly
|
|
76
|
+
* followed by another digit (run). Enough for `^claude-opus-(\d+)(?:-(\d+))?$`.
|
|
77
|
+
*/
|
|
78
|
+
function safePatternTokens(body: string): PatternToken[] | null {
|
|
79
|
+
if (!body.startsWith("^") || !body.endsWith("$") || body.length < 2) return null;
|
|
80
|
+
const src = body.slice(1, -1);
|
|
81
|
+
const out: PatternToken[] = [];
|
|
82
|
+
let inGroup = false;
|
|
83
|
+
let groups = 0;
|
|
84
|
+
let runs = 0;
|
|
85
|
+
let i = 0;
|
|
86
|
+
while (i < src.length) {
|
|
87
|
+
if (src.startsWith("(\\d+)", i)) {
|
|
88
|
+
out.push({ t: "num", capture: true });
|
|
89
|
+
i += 5;
|
|
90
|
+
runs++;
|
|
91
|
+
} else if (src.startsWith("\\d+", i)) {
|
|
92
|
+
out.push({ t: "num", capture: false });
|
|
93
|
+
i += 3;
|
|
94
|
+
runs++;
|
|
95
|
+
} else if (src.startsWith("(?:", i)) {
|
|
96
|
+
if (inGroup) return null;
|
|
97
|
+
inGroup = true;
|
|
98
|
+
groups++;
|
|
99
|
+
out.push({ t: "open" });
|
|
100
|
+
i += 3;
|
|
101
|
+
} else if (src.startsWith(")?", i)) {
|
|
102
|
+
if (!inGroup) return null;
|
|
103
|
+
inGroup = false;
|
|
104
|
+
out.push({ t: "close" });
|
|
105
|
+
i += 2;
|
|
106
|
+
} else if (src[i] === "\\" && ESCAPED_LITERAL.test(src[i + 1] ?? "")) {
|
|
107
|
+
out.push({ t: "lit", c: src[i + 1]! });
|
|
108
|
+
i += 2;
|
|
109
|
+
} else if (LITERAL.test(src[i]!)) {
|
|
110
|
+
out.push({ t: "lit", c: src[i]! });
|
|
111
|
+
i += 1;
|
|
112
|
+
} else {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (inGroup || groups > MAX_PATTERN_GROUPS || runs > MAX_PATTERN_DIGIT_RUNS) return null;
|
|
117
|
+
const isDigitLit = (tok: PatternToken | undefined) =>
|
|
118
|
+
tok?.t === "lit" && tok.c >= "0" && tok.c <= "9";
|
|
119
|
+
for (let k = 0; k < out.length; k++) {
|
|
120
|
+
const tok = out[k]!;
|
|
121
|
+
// A group starts with a non-digit literal and is never empty.
|
|
122
|
+
if (tok.t === "open") {
|
|
123
|
+
const first = out[k + 1];
|
|
124
|
+
if (first?.t !== "lit" || isDigitLit(first)) return null;
|
|
125
|
+
}
|
|
126
|
+
// A digit run is followed by a non-digit literal, a group, or the end.
|
|
127
|
+
if (tok.t === "num") {
|
|
128
|
+
let j = k + 1;
|
|
129
|
+
while (out[j]?.t === "close") j++;
|
|
130
|
+
const next = out[j];
|
|
131
|
+
if (next?.t === "num" || isDigitLit(next)) return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Rejected patterns already logged, so a bad catalogue warns once. */
|
|
138
|
+
const rejectedPatterns = new Set<string>();
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Compile a family pattern published by the bridge, or null when it is absent
|
|
142
|
+
* or outside the safe grammar (see safePatternTokens); then its alias family is
|
|
143
|
+
* not auto-allowed. A leading Go `(?i)` flag group becomes the JS flag.
|
|
144
|
+
*/
|
|
145
|
+
export function familyPattern(source: string | undefined): RegExp | null {
|
|
146
|
+
if (!source) return null;
|
|
147
|
+
let flags = "";
|
|
148
|
+
let body = source;
|
|
149
|
+
if (body.startsWith("(?i)")) {
|
|
150
|
+
flags = "i";
|
|
151
|
+
body = body.slice(4);
|
|
152
|
+
}
|
|
153
|
+
const safe =
|
|
154
|
+
source.length <= MAX_PATTERN_LENGTH ? safePatternTokens(body) : null;
|
|
155
|
+
if (!safe) {
|
|
156
|
+
if (!rejectedPatterns.has(source)) {
|
|
157
|
+
rejectedPatterns.add(source);
|
|
158
|
+
log.warn(
|
|
159
|
+
`alias pattern ignored, outside the supported safe grammar: ${source.slice(0, 80)}`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
return new RegExp(body, flags);
|
|
166
|
+
} catch {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Model id as the bridge matches it: without a `<upstream key>/` prefix. */
|
|
172
|
+
function matchKey(id: string, upstreamKey: string): string {
|
|
173
|
+
const slash = id.indexOf("/");
|
|
174
|
+
return slash > 0 && id.slice(0, slash).toLowerCase() === upstreamKey
|
|
175
|
+
? id.slice(slash + 1)
|
|
176
|
+
: id;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Version a family pattern captures from an id (missing group = 0), or null. */
|
|
180
|
+
function familyVersion(
|
|
181
|
+
re: RegExp,
|
|
182
|
+
id: string,
|
|
183
|
+
upstreamKey = "",
|
|
184
|
+
): number[] | null {
|
|
185
|
+
const key = matchKey(id, upstreamKey);
|
|
186
|
+
if (key.length > MAX_MATCH_ID_LENGTH) return null;
|
|
187
|
+
const m = re.exec(key);
|
|
188
|
+
if (!m) return null;
|
|
189
|
+
return m.slice(1).map((g) => (g ? Number.parseInt(g, 10) || 0 : 0));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Compare two versions component-wise, the bridge's way. */
|
|
193
|
+
function compareVersions(a: number[], b: number[]): number {
|
|
194
|
+
for (let i = 0; i < a.length || i < b.length; i++) {
|
|
195
|
+
const x = a[i] ?? 0;
|
|
196
|
+
const y = b[i] ?? 0;
|
|
197
|
+
if (x !== y) return x > y ? 1 : -1;
|
|
198
|
+
}
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Models a built-in provider serves although they are not in its whitelist:
|
|
204
|
+
* versions of a family the user already allowed, i.e. a whitelisted model
|
|
205
|
+
* matches the alias's published pattern. Every version the proxy still serves
|
|
206
|
+
* that is not older than the oldest whitelisted one is allowed, not only the
|
|
207
|
+
* current alias target: a session pinned to the previous target must stay
|
|
208
|
+
* resolvable after the alias advances (resume never moves it). Without a
|
|
209
|
+
* usable pattern (old bridge, unsafe pattern) nothing is added and only
|
|
210
|
+
* whitelisted targets are aliased.
|
|
211
|
+
*/
|
|
212
|
+
export function autoAllowedModels(
|
|
213
|
+
aliases: DiscoveryAlias[] | undefined,
|
|
214
|
+
piProvider: string,
|
|
215
|
+
whitelist: readonly string[],
|
|
216
|
+
served: readonly string[] = [],
|
|
217
|
+
): string[] {
|
|
218
|
+
const out: string[] = [];
|
|
219
|
+
for (const a of aliases ?? []) {
|
|
220
|
+
const key = a.provider.trim().toLowerCase();
|
|
221
|
+
if (PI_PROVIDER_FOR[key] !== piProvider) continue;
|
|
222
|
+
const re = familyPattern(a.pattern);
|
|
223
|
+
if (!re) continue;
|
|
224
|
+
let floor: number[] | null = null;
|
|
225
|
+
for (const id of whitelist) {
|
|
226
|
+
const v = familyVersion(re, id, key);
|
|
227
|
+
if (v && (!floor || compareVersions(v, floor) < 0)) floor = v;
|
|
228
|
+
}
|
|
229
|
+
if (!floor) continue;
|
|
230
|
+
for (const id of [a.model, ...served]) {
|
|
231
|
+
if (whitelist.includes(id) || out.includes(id)) continue;
|
|
232
|
+
const v = familyVersion(re, id, key);
|
|
233
|
+
if (v && compareVersions(v, floor) >= 0) out.push(id);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** What a Pi provider was registered with, as needed to mirror its models. */
|
|
240
|
+
export interface RegisteredProvider {
|
|
241
|
+
baseUrl: string;
|
|
242
|
+
api: string;
|
|
243
|
+
models: ProviderModelConfig[];
|
|
244
|
+
/**
|
|
245
|
+
* Model id → the CLIProxyAPI provider keys known to serve it. A model with
|
|
246
|
+
* no known provenance is never an alias target.
|
|
247
|
+
*/
|
|
248
|
+
upstream: Map<string, string[]>;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export interface ModelRef {
|
|
252
|
+
provider: string;
|
|
253
|
+
id: string;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** `opus` → `Opus`, `gpt-sol` → `GPT Sol`. */
|
|
257
|
+
function familyTitle(alias: string): string {
|
|
258
|
+
return alias
|
|
259
|
+
.split(/[-_]/)
|
|
260
|
+
.filter(Boolean)
|
|
261
|
+
.map((w) =>
|
|
262
|
+
w.toLowerCase() === "gpt" ? "GPT" : w[0]!.toUpperCase() + w.slice(1),
|
|
263
|
+
)
|
|
264
|
+
.join(" ");
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Display name that shows the current resolution. */
|
|
268
|
+
export function aliasDisplayName(alias: string, model: string): string {
|
|
269
|
+
return `${familyTitle(alias)} (latest: ${model})`;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Find where this extension registered the alias's model: the (provider,
|
|
274
|
+
* model) pair the bridge resolved, i.e. a Pi provider registering that id AND
|
|
275
|
+
* known to serve it from that CLIProxyAPI provider. A same-id model from an
|
|
276
|
+
* unrelated provider is never used. The built-in provider for the key is
|
|
277
|
+
* preferred when several match.
|
|
278
|
+
*/
|
|
279
|
+
function findTarget(
|
|
280
|
+
a: DiscoveryAlias,
|
|
281
|
+
registered: Map<string, RegisteredProvider>,
|
|
282
|
+
): { provider: string; reg: RegisteredProvider; def: ProviderModelConfig } | null {
|
|
283
|
+
const key = a.provider.trim().toLowerCase();
|
|
284
|
+
const preferred = PI_PROVIDER_FOR[key];
|
|
285
|
+
const order = [
|
|
286
|
+
...(preferred ? [preferred] : []),
|
|
287
|
+
...Array.from(registered.keys()).filter((p) => p !== preferred),
|
|
288
|
+
];
|
|
289
|
+
for (const provider of order) {
|
|
290
|
+
if (provider === ALIAS_PROVIDER) continue;
|
|
291
|
+
const reg = registered.get(provider);
|
|
292
|
+
const def = reg?.models.find((m) => m.id === a.model);
|
|
293
|
+
if (reg && def && reg.upstream.get(def.id)?.includes(key)) {
|
|
294
|
+
return { provider, reg, def };
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export interface AliasProvider {
|
|
301
|
+
/** Provider to register, or null when no alias resolves to a registered model. */
|
|
302
|
+
config: ProviderConfig | null;
|
|
303
|
+
/** Alias id → concrete model it pins to. */
|
|
304
|
+
targets: Map<string, ModelRef>;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Build the `latest` provider from catalogue aliases and what was registered.
|
|
309
|
+
* Pure: the caller registers the result.
|
|
310
|
+
*/
|
|
311
|
+
export function buildAliasProvider(
|
|
312
|
+
aliases: DiscoveryAlias[] | undefined,
|
|
313
|
+
registered: Map<string, RegisteredProvider>,
|
|
314
|
+
apiKey: string,
|
|
315
|
+
): AliasProvider {
|
|
316
|
+
const targets = new Map<string, ModelRef>();
|
|
317
|
+
const models: ProviderModelConfig[] = [];
|
|
318
|
+
let first: RegisteredProvider | null = null;
|
|
319
|
+
for (const a of aliases ?? []) {
|
|
320
|
+
const id = a.alias.toLowerCase();
|
|
321
|
+
if (targets.has(id)) continue;
|
|
322
|
+
const found = findTarget(a, registered);
|
|
323
|
+
if (!found) {
|
|
324
|
+
log.debug(
|
|
325
|
+
`alias ${a.alias} → ${a.model} skipped: model not registered by this extension`,
|
|
326
|
+
);
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
targets.set(id, { provider: found.provider, id: found.def.id });
|
|
330
|
+
first ??= found.reg;
|
|
331
|
+
models.push({
|
|
332
|
+
...found.def,
|
|
333
|
+
id,
|
|
334
|
+
name: aliasDisplayName(id, found.def.id),
|
|
335
|
+
api: found.def.api ?? found.reg.api,
|
|
336
|
+
baseUrl: found.def.baseUrl ?? found.reg.baseUrl,
|
|
337
|
+
} as ProviderModelConfig);
|
|
338
|
+
}
|
|
339
|
+
if (!first || models.length === 0) return { config: null, targets };
|
|
340
|
+
return {
|
|
341
|
+
config: {
|
|
342
|
+
name: ALIAS_PROVIDER,
|
|
343
|
+
baseUrl: first.baseUrl,
|
|
344
|
+
apiKey,
|
|
345
|
+
authHeader: true,
|
|
346
|
+
api: first.api as ProviderConfig["api"],
|
|
347
|
+
models,
|
|
348
|
+
},
|
|
349
|
+
targets,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// --------------------------------------------------------------------------- state
|
|
354
|
+
|
|
355
|
+
let currentTargets = new Map<string, ModelRef>();
|
|
356
|
+
let aliasProviderRegistered = false;
|
|
357
|
+
/** When the catalogue behind the current resolutions was fetched (epoch ms). */
|
|
358
|
+
let catalogueAt = 0;
|
|
359
|
+
|
|
360
|
+
/** Age of the catalogue the current resolutions come from; Infinity if none. */
|
|
361
|
+
export function aliasCatalogueAgeMs(now = Date.now()): number {
|
|
362
|
+
return catalogueAt > 0 ? now - catalogueAt : Number.POSITIVE_INFINITY;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Concrete model an alias currently pins to. */
|
|
366
|
+
export function aliasTarget(alias: string): ModelRef | undefined {
|
|
367
|
+
return currentTargets.get(alias.toLowerCase());
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* The name `latest` belongs to a configured provider: forget the resolutions.
|
|
372
|
+
* If that provider was registered in this pass it already replaced ours;
|
|
373
|
+
* otherwise (disabled, empty, nothing on the proxy) the alias provider this
|
|
374
|
+
* extension registered earlier is removed so its stale entries cannot be
|
|
375
|
+
* selected. A provider this extension does not own is never unregistered.
|
|
376
|
+
*/
|
|
377
|
+
export function forgetAliases(
|
|
378
|
+
pi: Pick<ExtensionAPI, "unregisterProvider">,
|
|
379
|
+
takenOverByConfigured: boolean,
|
|
380
|
+
): void {
|
|
381
|
+
currentTargets = new Map();
|
|
382
|
+
if (aliasProviderRegistered && !takenOverByConfigured) {
|
|
383
|
+
pi.unregisterProvider(ALIAS_PROVIDER);
|
|
384
|
+
}
|
|
385
|
+
aliasProviderRegistered = false;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Register (or drop) the `latest` provider and remember the resolutions. */
|
|
389
|
+
export function applyAliases(
|
|
390
|
+
pi: Pick<ExtensionAPI, "registerProvider" | "unregisterProvider">,
|
|
391
|
+
built: AliasProvider,
|
|
392
|
+
fetchedAt: number = Date.now(),
|
|
393
|
+
): number {
|
|
394
|
+
currentTargets = built.targets;
|
|
395
|
+
catalogueAt = fetchedAt;
|
|
396
|
+
if (built.config) {
|
|
397
|
+
pi.registerProvider(ALIAS_PROVIDER, built.config);
|
|
398
|
+
aliasProviderRegistered = true;
|
|
399
|
+
return built.config.models?.length ?? 0;
|
|
400
|
+
}
|
|
401
|
+
if (aliasProviderRegistered) {
|
|
402
|
+
pi.unregisterProvider(ALIAS_PROVIDER);
|
|
403
|
+
aliasProviderRegistered = false;
|
|
404
|
+
}
|
|
405
|
+
return 0;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// --------------------------------------------------------------------------- pin
|
|
409
|
+
|
|
410
|
+
export type PinDecision =
|
|
411
|
+
| { kind: "none" }
|
|
412
|
+
| { kind: "pin"; alias: string; target: ModelRef }
|
|
413
|
+
| { kind: "unresolved"; alias: string };
|
|
414
|
+
|
|
415
|
+
/** What to do with the session's model: nothing for concrete models. */
|
|
416
|
+
export function pinDecision(model: ModelRef | undefined): PinDecision {
|
|
417
|
+
if (!model || model.provider !== ALIAS_PROVIDER) return { kind: "none" };
|
|
418
|
+
const target = aliasTarget(model.id);
|
|
419
|
+
return target
|
|
420
|
+
? { kind: "pin", alias: model.id, target }
|
|
421
|
+
: { kind: "unresolved", alias: model.id };
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** session_start reasons that create a session; resume keeps its own model. */
|
|
425
|
+
const PIN_ON_START = new Set(["startup", "new", "fork"]);
|
|
426
|
+
|
|
427
|
+
/** The slice of the extension context the pin reads. */
|
|
428
|
+
export interface PinContext {
|
|
429
|
+
model?: ModelRef;
|
|
430
|
+
modelRegistry: { find(provider: string, id: string): Model<Api> | undefined };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** The slice of the extension API the pin uses; tests pass a fake. */
|
|
434
|
+
export interface PinApi {
|
|
435
|
+
on(
|
|
436
|
+
event: "session_start",
|
|
437
|
+
handler: (event: { reason?: string }, ctx: PinContext) => Promise<void>,
|
|
438
|
+
): void;
|
|
439
|
+
on(
|
|
440
|
+
event: "model_select",
|
|
441
|
+
handler: (event: { model?: ModelRef }, ctx: PinContext) => Promise<void>,
|
|
442
|
+
): void;
|
|
443
|
+
setModel(model: Model<Api>): Promise<boolean>;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
export interface PinOptions {
|
|
447
|
+
/**
|
|
448
|
+
* Runs before an alias is resolved, so a stale catalogue can be refreshed
|
|
449
|
+
* first. It must bound its own wait; failures leave the last known
|
|
450
|
+
* resolution in place.
|
|
451
|
+
*/
|
|
452
|
+
beforePin?: () => Promise<void>;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Pin `latest/*` to the concrete model on session start and model selection.
|
|
457
|
+
*
|
|
458
|
+
* pi.setModel fires model_select again with the concrete model, for which the
|
|
459
|
+
* handler is a no-op, so the recursion ends after one hop; the in-flight flag
|
|
460
|
+
* covers a host that would report the alias again mid-switch.
|
|
461
|
+
*/
|
|
462
|
+
export function registerAliasPin(pi: PinApi, opts: PinOptions = {}): void {
|
|
463
|
+
let pinning = false;
|
|
464
|
+
|
|
465
|
+
const pin = async (model: ModelRef | undefined, ctx: PinContext) => {
|
|
466
|
+
if (pinning) return;
|
|
467
|
+
if (pinDecision(model).kind === "none") return;
|
|
468
|
+
if (opts.beforePin) {
|
|
469
|
+
try {
|
|
470
|
+
await opts.beforePin();
|
|
471
|
+
} catch (err) {
|
|
472
|
+
log.debug("alias refresh before pin failed:", (err as Error).message);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
const d = pinDecision(model);
|
|
476
|
+
if (d.kind === "none") return;
|
|
477
|
+
if (d.kind === "unresolved") {
|
|
478
|
+
log.warn(
|
|
479
|
+
`${ALIAS_PROVIDER}/${d.alias} does not resolve to a model right now; keeping it as selected`,
|
|
480
|
+
);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const concrete = ctx.modelRegistry.find(d.target.provider, d.target.id);
|
|
484
|
+
if (!concrete) {
|
|
485
|
+
log.warn(
|
|
486
|
+
`${ALIAS_PROVIDER}/${d.alias} resolves to ${d.target.provider}/${d.target.id}, which is not available; keeping the alias`,
|
|
487
|
+
);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
pinning = true;
|
|
491
|
+
try {
|
|
492
|
+
const ok = await pi.setModel(concrete);
|
|
493
|
+
if (!ok) {
|
|
494
|
+
log.warn(
|
|
495
|
+
`could not switch ${ALIAS_PROVIDER}/${d.alias} to ${d.target.provider}/${d.target.id}: no credentials`,
|
|
496
|
+
);
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
log.debug(
|
|
500
|
+
`pinned ${ALIAS_PROVIDER}/${d.alias} to ${d.target.provider}/${d.target.id}`,
|
|
501
|
+
);
|
|
502
|
+
} catch (err) {
|
|
503
|
+
log.warn(
|
|
504
|
+
`could not switch ${ALIAS_PROVIDER}/${d.alias} to ${d.target.provider}/${d.target.id}:`,
|
|
505
|
+
(err as Error).message,
|
|
506
|
+
);
|
|
507
|
+
} finally {
|
|
508
|
+
pinning = false;
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
pi.on("session_start", async (event, ctx) => {
|
|
513
|
+
if (!PIN_ON_START.has(event?.reason ?? "")) return;
|
|
514
|
+
await pin(ctx.model, ctx);
|
|
515
|
+
});
|
|
516
|
+
|
|
517
|
+
pi.on("model_select", async (event, ctx) => {
|
|
518
|
+
await pin(event?.model ?? ctx.model, ctx);
|
|
519
|
+
});
|
|
520
|
+
}
|
package/src/apply.ts
CHANGED
|
@@ -9,6 +9,16 @@ import type {
|
|
|
9
9
|
ProviderModelConfig,
|
|
10
10
|
} from "@earendil-works/pi-coding-agent";
|
|
11
11
|
|
|
12
|
+
import {
|
|
13
|
+
ALIAS_PROVIDER,
|
|
14
|
+
applyAliases,
|
|
15
|
+
autoAllowedModels,
|
|
16
|
+
forgetAliases,
|
|
17
|
+
buildAliasProvider,
|
|
18
|
+
type RegisteredProvider,
|
|
19
|
+
upstreamForBuiltin,
|
|
20
|
+
upstreamForCustom,
|
|
21
|
+
} from "./aliases.ts";
|
|
12
22
|
import { ALLOWED_APIS, baseUrlFor, modelDefaults } from "./compat.ts";
|
|
13
23
|
import type { CustomProviderModelConfig, ProxyConfig } from "./config.ts";
|
|
14
24
|
import { resolveConfigValue } from "./config.ts";
|
|
@@ -25,8 +35,12 @@ export async function applyAll(
|
|
|
25
35
|
pi: ExtensionAPI,
|
|
26
36
|
cfg: ProxyConfig,
|
|
27
37
|
discovery: Discovery,
|
|
38
|
+
/** When the discovery was fetched; a cached copy passes its save time. */
|
|
39
|
+
opts: { fetchedAt?: number } = {},
|
|
28
40
|
): Promise<ApplyReport> {
|
|
29
41
|
const report: ApplyReport = { registered: [], skipped: [] };
|
|
42
|
+
/** What each provider was registered with; `latest/*` mirrors it. */
|
|
43
|
+
const registeredModels = new Map<string, RegisteredProvider>();
|
|
30
44
|
const proxyIds = discoveryToIdSet(discovery);
|
|
31
45
|
const resolvedKey = resolveConfigValue(cfg.proxy.apiKey);
|
|
32
46
|
if (!resolvedKey) {
|
|
@@ -51,6 +65,7 @@ export async function applyAll(
|
|
|
51
65
|
cacheRead: number;
|
|
52
66
|
cacheWrite: number;
|
|
53
67
|
};
|
|
68
|
+
input?: ("text" | "image")[];
|
|
54
69
|
}>
|
|
55
70
|
>();
|
|
56
71
|
for (const p of discovery.builtinProviders) {
|
|
@@ -63,6 +78,7 @@ export async function applyAll(
|
|
|
63
78
|
contextWindow: m.contextWindow,
|
|
64
79
|
maxTokens: m.maxTokens,
|
|
65
80
|
cost: m.cost,
|
|
81
|
+
input: m.input,
|
|
66
82
|
})),
|
|
67
83
|
);
|
|
68
84
|
}
|
|
@@ -109,7 +125,17 @@ export async function applyAll(
|
|
|
109
125
|
thinkingLevelMap?: any;
|
|
110
126
|
}
|
|
111
127
|
const selected: MergedModel[] = [];
|
|
112
|
-
|
|
128
|
+
// New versions of a whitelisted family, so `latest/*` can pin them.
|
|
129
|
+
const autoAllowed = autoAllowedModels(
|
|
130
|
+
discovery.aliases,
|
|
131
|
+
name,
|
|
132
|
+
p.models,
|
|
133
|
+
Array.from(proxyById.keys()),
|
|
134
|
+
);
|
|
135
|
+
if (autoAllowed.length > 0) {
|
|
136
|
+
log.info(`${name}: allowing new family versions ${autoAllowed.join(", ")}`);
|
|
137
|
+
}
|
|
138
|
+
for (const id of [...p.models, ...autoAllowed]) {
|
|
113
139
|
if (!proxyIds.has(id)) continue;
|
|
114
140
|
const c = catalogById.get(id);
|
|
115
141
|
const px = proxyById.get(id);
|
|
@@ -140,7 +166,7 @@ export async function applyAll(
|
|
|
140
166
|
contextWindow: px.contextWindow,
|
|
141
167
|
maxTokens: px.maxTokens,
|
|
142
168
|
cost: px.cost,
|
|
143
|
-
input: ["text"],
|
|
169
|
+
input: px.input ?? ["text"],
|
|
144
170
|
api,
|
|
145
171
|
});
|
|
146
172
|
}
|
|
@@ -188,6 +214,13 @@ export async function applyAll(
|
|
|
188
214
|
models: modelDefs,
|
|
189
215
|
};
|
|
190
216
|
pi.registerProvider(name, providerConfig);
|
|
217
|
+
const builtinUpstream = upstreamForBuiltin(name);
|
|
218
|
+
registeredModels.set(name, {
|
|
219
|
+
baseUrl: providerConfig.baseUrl as string,
|
|
220
|
+
api,
|
|
221
|
+
models: modelDefs,
|
|
222
|
+
upstream: new Map(modelDefs.map((m) => [m.id, builtinUpstream])),
|
|
223
|
+
});
|
|
191
224
|
report.registered.push({
|
|
192
225
|
provider: name,
|
|
193
226
|
modelCount: modelDefs.length,
|
|
@@ -232,7 +265,7 @@ export async function applyAll(
|
|
|
232
265
|
base.reasoning,
|
|
233
266
|
ov.reasoning,
|
|
234
267
|
) ?? false,
|
|
235
|
-
input: ["text"],
|
|
268
|
+
input: m.input ?? fromPool?.input ?? ["text"],
|
|
236
269
|
cost: m.cost ??
|
|
237
270
|
fromPool?.cost ??
|
|
238
271
|
base.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
@@ -261,6 +294,19 @@ export async function applyAll(
|
|
|
261
294
|
models: modelDefs,
|
|
262
295
|
};
|
|
263
296
|
pi.registerProvider(name, providerConfig);
|
|
297
|
+
registeredModels.set(name, {
|
|
298
|
+
baseUrl: providerConfig.baseUrl as string,
|
|
299
|
+
api: c.api,
|
|
300
|
+
models: modelDefs,
|
|
301
|
+
// Only models the catalogue lists in the custom pool have a known
|
|
302
|
+
// upstream; anything else is never an alias target.
|
|
303
|
+
upstream: new Map(
|
|
304
|
+
modelDefs.map((m) => [
|
|
305
|
+
m.id,
|
|
306
|
+
upstreamForCustom(proxyCustomById.get(m.id)?.ownedBy),
|
|
307
|
+
]),
|
|
308
|
+
),
|
|
309
|
+
});
|
|
264
310
|
report.registered.push({
|
|
265
311
|
provider: name,
|
|
266
312
|
modelCount: modelDefs.length,
|
|
@@ -268,6 +314,37 @@ export async function applyAll(
|
|
|
268
314
|
});
|
|
269
315
|
}
|
|
270
316
|
|
|
317
|
+
// -------- `latest/*` aliases, mirroring models registered above
|
|
318
|
+
if (
|
|
319
|
+
cfg.customProviders[ALIAS_PROVIDER] ||
|
|
320
|
+
cfg.builtinProviders[ALIAS_PROVIDER]
|
|
321
|
+
) {
|
|
322
|
+
report.skipped.push({
|
|
323
|
+
provider: ALIAS_PROVIDER,
|
|
324
|
+
reason: "name taken by a configured provider",
|
|
325
|
+
});
|
|
326
|
+
// Nothing to pin to: the name now means the configured provider.
|
|
327
|
+
forgetAliases(pi, registeredModels.has(ALIAS_PROVIDER));
|
|
328
|
+
} else {
|
|
329
|
+
const built = buildAliasProvider(
|
|
330
|
+
discovery.aliases,
|
|
331
|
+
registeredModels,
|
|
332
|
+
resolvedKey,
|
|
333
|
+
);
|
|
334
|
+
const count = applyAliases(
|
|
335
|
+
pi,
|
|
336
|
+
built,
|
|
337
|
+
discovery.aliasesFetchedAt ?? opts.fetchedAt,
|
|
338
|
+
);
|
|
339
|
+
if (built.config) {
|
|
340
|
+
report.registered.push({
|
|
341
|
+
provider: ALIAS_PROVIDER,
|
|
342
|
+
modelCount: count,
|
|
343
|
+
api: built.config.api as Api,
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
271
348
|
log.info(
|
|
272
349
|
`applyAll: registered ${report.registered.length} providers, skipped ${report.skipped.length}`,
|
|
273
350
|
);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Cache namespace: which proxy, and which client key, a cached value belongs to.
|
|
2
|
+
//
|
|
3
|
+
// Cached usage documents, session bindings and the alias/catalogue discovery
|
|
4
|
+
// describe one proxy as seen by one client key. After the endpoint or the key
|
|
5
|
+
// changes, entries written under the old pair must read as a miss, not be shown
|
|
6
|
+
// as the new pair's data. The namespace is `origin#sha256(secrets)`; the raw key
|
|
7
|
+
// never reaches disk or logs.
|
|
8
|
+
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
|
|
11
|
+
/** `origin#<sha256 hex of the secrets>`; the endpoint verbatim if not a URL. */
|
|
12
|
+
export function cacheNamespace(endpoint: string, ...secrets: string[]): string {
|
|
13
|
+
let origin: string;
|
|
14
|
+
try {
|
|
15
|
+
origin = new URL(endpoint).origin;
|
|
16
|
+
} catch {
|
|
17
|
+
origin = endpoint;
|
|
18
|
+
}
|
|
19
|
+
const digest = createHash("sha256").update(secrets.join("\u0000")).digest("hex");
|
|
20
|
+
return `${origin}#${digest}`;
|
|
21
|
+
}
|