pi-cliproxyapi 0.4.2 → 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/src/cache.ts CHANGED
@@ -9,13 +9,17 @@
9
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
10
  import { dirname, join } from "node:path";
11
11
 
12
+ import { cacheNamespace } from "./cache-namespace.ts";
12
13
  import { CONFIG_DIR } from "./config.ts";
14
+ import type { ProxyConfig } from "./config.ts";
13
15
  import type { Discovery } from "./fetch-models.ts";
14
16
  import { log } from "./log.ts";
15
17
 
16
18
  export const DISCOVERY_CACHE_PATH = join(CONFIG_DIR, "discovery-cache.json");
17
19
 
18
20
  interface CacheEnvelope {
21
+ /** Proxy origin + key digest the discovery was fetched for. */
22
+ namespace: string;
19
23
  savedAt: number;
20
24
  discovery: Discovery;
21
25
  }
@@ -25,7 +29,52 @@ export interface CachedDiscovery {
25
29
  ageMs: number;
26
30
  }
27
31
 
28
- export function readDiscoveryCache(): CachedDiscovery | null {
32
+ /** Namespace of the discovery cache for this proxy endpoint and resolved key. */
33
+ export function discoveryNamespace(cfg: ProxyConfig, resolvedKey: string): string {
34
+ return cacheNamespace(cfg.proxy.endpoint, resolvedKey);
35
+ }
36
+
37
+ /** The last alias resolutions known for one namespace, and when they were fetched. */
38
+ export interface AliasSnapshot {
39
+ aliases: NonNullable<Discovery["aliases"]>;
40
+ fetchedAt: number;
41
+ }
42
+
43
+ /**
44
+ * Alias resolutions this process has seen, per namespace. The file holds one
45
+ * namespace at a time, so another credential's write would otherwise erase
46
+ * resolutions this instance already loaded and still needs during an outage.
47
+ */
48
+ const aliasSnapshots = new Map<string, AliasSnapshot>();
49
+ /** Namespaces are one per proxy/key pair; a handful per process at most. */
50
+ const MAX_ALIAS_SNAPSHOTS = 16;
51
+
52
+ function rememberAliases(namespace: string, discovery: Discovery, savedAt: number): void {
53
+ aliasSnapshots.delete(namespace);
54
+ // No aliases (or an authoritative empty list) clears what was known.
55
+ if (!discovery.aliases || discovery.aliases.length === 0) return;
56
+ aliasSnapshots.set(namespace, {
57
+ aliases: discovery.aliases,
58
+ fetchedAt:
59
+ typeof discovery.aliasesFetchedAt === "number" ? discovery.aliasesFetchedAt : savedAt,
60
+ });
61
+ while (aliasSnapshots.size > MAX_ALIAS_SNAPSHOTS) {
62
+ aliasSnapshots.delete(aliasSnapshots.keys().next().value as string);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * The last known aliases for the namespace: from the file when it still
68
+ * belongs to the namespace, otherwise from what this process loaded or wrote
69
+ * for it earlier. Null when none are known.
70
+ */
71
+ export function lastKnownAliases(namespace: string): AliasSnapshot | null {
72
+ readDiscoveryCache(namespace); // refreshes the snapshot from a same-namespace file
73
+ return aliasSnapshots.get(namespace) ?? null;
74
+ }
75
+
76
+ /** A cache written for another endpoint/key, or a legacy one, reads as a miss. */
77
+ export function readDiscoveryCache(namespace: string): CachedDiscovery | null {
29
78
  if (!existsSync(DISCOVERY_CACHE_PATH)) return null;
30
79
  try {
31
80
  const env = JSON.parse(
@@ -33,6 +82,7 @@ export function readDiscoveryCache(): CachedDiscovery | null {
33
82
  ) as CacheEnvelope;
34
83
  if (
35
84
  !env ||
85
+ env.namespace !== namespace ||
36
86
  typeof env.savedAt !== "number" ||
37
87
  !env.discovery ||
38
88
  !Array.isArray(env.discovery.builtinProviders) ||
@@ -40,6 +90,7 @@ export function readDiscoveryCache(): CachedDiscovery | null {
40
90
  ) {
41
91
  return null;
42
92
  }
93
+ rememberAliases(namespace, env.discovery, env.savedAt);
43
94
  return { discovery: env.discovery, ageMs: Date.now() - env.savedAt };
44
95
  } catch (err) {
45
96
  log.warn("failed to read discovery cache:", (err as Error).message);
@@ -47,10 +98,14 @@ export function readDiscoveryCache(): CachedDiscovery | null {
47
98
  }
48
99
  }
49
100
 
50
- export function writeDiscoveryCache(discovery: Discovery): void {
101
+ export function writeDiscoveryCache(namespace: string, discovery: Discovery): void {
102
+ const savedAt = Date.now();
103
+ // Kept in memory first, so a failed or later-overwritten write still
104
+ // leaves this process its own last known aliases.
105
+ rememberAliases(namespace, discovery, savedAt);
51
106
  try {
52
107
  mkdirSync(dirname(DISCOVERY_CACHE_PATH), { recursive: true });
53
- const env: CacheEnvelope = { savedAt: Date.now(), discovery };
108
+ const env: CacheEnvelope = { namespace, savedAt, discovery };
54
109
  writeFileSync(DISCOVERY_CACHE_PATH, JSON.stringify(env), "utf8");
55
110
  } catch (err) {
56
111
  log.warn("failed to write discovery cache:", (err as Error).message);
package/src/config.ts CHANGED
@@ -101,6 +101,8 @@ export interface BuiltinProviderConfig {
101
101
  export interface CustomProviderModelConfig {
102
102
  id: string;
103
103
  name?: string;
104
+ /** Input modalities the model accepts, e.g. ["text","image"]. Defaults to ["text"]. */
105
+ input?: ("text" | "image")[];
104
106
  contextWindow?: number;
105
107
  maxTokens?: number;
106
108
  reasoning?: boolean;
@@ -19,9 +19,12 @@ import {
19
19
  } from "./compat.ts";
20
20
  import { readFileSync } from "node:fs";
21
21
 
22
- import { writeDiscoveryCache } from "./cache.ts";
22
+ import {
23
+ discoveryNamespace,
24
+ lastKnownAliases,
25
+ writeDiscoveryCache,
26
+ } from "./cache.ts";
23
27
  import type { ProxyConfig } from "./config.ts";
24
- import { resolveConfigValue } from "./config.ts";
25
28
  import { CONTRACT_HEADER, PREFERRED_CONTRACT } from "./fetch-usage.ts";
26
29
  import { log } from "./log.ts";
27
30
 
@@ -50,6 +53,8 @@ export interface DiscoveryModelEntry {
50
53
  cacheRead: number;
51
54
  cacheWrite: number;
52
55
  };
56
+ /** Input modalities the model accepts, e.g. ["text","image"]. Absent = text-only default. */
57
+ input?: ("text" | "image")[];
53
58
  }
54
59
 
55
60
  export interface DiscoveryBuiltinProvider {
@@ -68,6 +73,22 @@ export interface DiscoveryCustomEntry extends DiscoveryModelEntry {
68
73
  ownedBy: string;
69
74
  }
70
75
 
76
+ /**
77
+ * Contract v2 only: a model family alias the bridge resolved to its newest
78
+ * concrete model, e.g. `opus` -> `claude-opus-5-5` on provider `claude`.
79
+ */
80
+ export interface DiscoveryAlias {
81
+ alias: string;
82
+ model: string;
83
+ /** CLIProxyAPI provider key (`claude`, `codex`, ...), not a Pi provider. */
84
+ provider: string;
85
+ /**
86
+ * Anchored regexp source matching every model of the family, e.g.
87
+ * `^claude-opus-\d+(-\d+)*$`. Absent on bridges that predate it.
88
+ */
89
+ pattern?: string;
90
+ }
91
+
71
92
  export interface Discovery {
72
93
  source: "well-known" | "v1-models";
73
94
  upstreamVersion: string | null;
@@ -76,6 +97,45 @@ export interface Discovery {
76
97
  serverDiscoveryExcludes: string[];
77
98
  /** Total ids seen before any filtering. */
78
99
  upstreamTotal: number;
100
+ /** Resolved family aliases; absent on old bridges and the /v1/models path. */
101
+ aliases?: DiscoveryAlias[];
102
+ /**
103
+ * Set when `aliases` were carried over from an earlier catalogue because
104
+ * the bridge could not be reached and only /v1/models answered: when that
105
+ * catalogue was fetched (epoch ms). Absent when the aliases are current.
106
+ */
107
+ aliasesFetchedAt?: number;
108
+ }
109
+
110
+ /** First argument that is a string, or null. */
111
+ function firstString(...vals: unknown[]): string | null {
112
+ for (const v of vals) if (typeof v === "string") return v;
113
+ return null;
114
+ }
115
+
116
+ /** Keep only well-formed alias entries from a catalogue body. */
117
+ export function parseAliases(raw: unknown): DiscoveryAlias[] | undefined {
118
+ if (!Array.isArray(raw)) return undefined;
119
+ const out: DiscoveryAlias[] = [];
120
+ for (const a of raw) {
121
+ if (
122
+ a &&
123
+ typeof a.alias === "string" &&
124
+ a.alias &&
125
+ typeof a.model === "string" &&
126
+ a.model &&
127
+ typeof a.provider === "string"
128
+ ) {
129
+ const entry: DiscoveryAlias = {
130
+ alias: a.alias,
131
+ model: a.model,
132
+ provider: a.provider,
133
+ };
134
+ if (typeof a.pattern === "string" && a.pattern) entry.pattern = a.pattern;
135
+ out.push(entry);
136
+ }
137
+ }
138
+ return out;
79
139
  }
80
140
 
81
141
  interface RawUpstreamModel {
@@ -83,6 +143,23 @@ interface RawUpstreamModel {
83
143
  owned_by: string;
84
144
  }
85
145
 
146
+ /**
147
+ * Extract input modalities from a well-known contract model entry.
148
+ *
149
+ * Accepts both the flat `input` array and the models.dev-style
150
+ * `modalities: { inputs: [...] }` shape. Unknown values are dropped;
151
+ * returns undefined when nothing usable is present (caller keeps its
152
+ * text-only default).
153
+ */
154
+ function parseInputModalities(m: any): ("text" | "image")[] | undefined {
155
+ const raw = m?.input ?? m?.modalities?.inputs ?? m?.modalities?.input;
156
+ if (!Array.isArray(raw)) return undefined;
157
+ const out = raw.filter(
158
+ (v: unknown): v is "text" | "image" => v === "text" || v === "image",
159
+ );
160
+ return out.length > 0 ? out : undefined;
161
+ }
162
+
86
163
  // --------------------------------------------------------------------------- HTTP
87
164
 
88
165
  async function fetchWithTimeout(
@@ -131,14 +208,16 @@ const PLUGIN_DISCOVERY_PATH_LEGACY =
131
208
  * still running the standalone sidecar has no such route, so the legacy
132
209
  * unauthenticated path remains as a fallback.
133
210
  */
134
- async function tryWellKnown(cfg: ProxyConfig): Promise<Discovery | null> {
211
+ async function tryWellKnown(
212
+ cfg: ProxyConfig,
213
+ apiKey: string,
214
+ ): Promise<Discovery | null> {
135
215
  const origin = endpointOrigin(cfg.proxy.endpoint);
136
216
  if (!origin) {
137
217
  log.warn(`proxy.endpoint is not a valid URL: ${cfg.proxy.endpoint}`);
138
218
  return null;
139
219
  }
140
220
 
141
- const apiKey = cfg.proxy.apiKey ? resolveConfigValue(cfg.proxy.apiKey) : "";
142
221
  if (apiKey) {
143
222
  const headers = {
144
223
  Authorization: `Bearer ${apiKey}`,
@@ -195,7 +274,10 @@ async function tryDiscoverySource(
195
274
  }
196
275
 
197
276
  const builtin: DiscoveryBuiltinProvider[] = [];
198
- const builtinProviders = (body.builtinProviders ?? {}) as Record<string, any>;
277
+ const builtinProviders = (body.builtinProviders ?? {}) as Record<
278
+ string,
279
+ { api?: unknown; models?: unknown } | null | undefined
280
+ >;
199
281
  for (const [name, p] of Object.entries(builtinProviders)) {
200
282
  if (!p || !Array.isArray(p.models)) continue;
201
283
  const models: DiscoveryModelEntry[] = p.models.map(
@@ -207,6 +289,7 @@ async function tryDiscoverySource(
207
289
  typeof m.contextWindow === "number" ? m.contextWindow : 200_000,
208
290
  maxTokens: typeof m.maxTokens === "number" ? m.maxTokens : 16_000,
209
291
  cost: m.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
292
+ input: parseInputModalities(m),
210
293
  }),
211
294
  );
212
295
  builtin.push({ name, api: (p.api as Api) ?? "openai-responses", models });
@@ -223,6 +306,7 @@ async function tryDiscoverySource(
223
306
  typeof m.contextWindow === "number" ? m.contextWindow : 128_000,
224
307
  maxTokens: typeof m.maxTokens === "number" ? m.maxTokens : 16_000,
225
308
  cost: m.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
309
+ input: parseInputModalities(m),
226
310
  api: (m.api as Api) ?? "openai-completions",
227
311
  suggestedProvider: normalizeSuggestedProvider(
228
312
  typeof m.suggestedProviderName === "string"
@@ -238,12 +322,10 @@ async function tryDiscoverySource(
238
322
  source: "well-known",
239
323
  // The sidecar only ever filled lproxy.upstreamVersion, and with null at
240
324
  // that; the bridge reports the real proxy version under upstream.
241
- upstreamVersion:
242
- typeof body?.upstream?.upstreamVersion === "string"
243
- ? body.upstream.upstreamVersion
244
- : typeof body?.lproxy?.upstreamVersion === "string"
245
- ? body.lproxy.upstreamVersion
246
- : null,
325
+ upstreamVersion: firstString(
326
+ body?.upstream?.upstreamVersion,
327
+ body?.lproxy?.upstreamVersion,
328
+ ),
247
329
  builtinProviders: builtin,
248
330
  customPool,
249
331
  serverDiscoveryExcludes: Array.isArray(body.discoveryExcludes)
@@ -255,6 +337,7 @@ async function tryDiscoverySource(
255
337
  typeof body?.counts?.upstreamTotal === "number"
256
338
  ? body.counts.upstreamTotal
257
339
  : 0,
340
+ aliases: parseAliases(body.aliases),
258
341
  };
259
342
  }
260
343
 
@@ -379,12 +462,15 @@ export async function fetchDiscovery(
379
462
  cfg: ProxyConfig,
380
463
  resolvedKey: string,
381
464
  ): Promise<Discovery> {
382
- const wk = await tryWellKnown(cfg);
465
+ // The key the caller resolved is the one sent and the one the cache
466
+ // namespace names: re-running a `!command` key here could fetch with
467
+ // another credential and publish its catalogue under this one.
468
+ const wk = await tryWellKnown(cfg, resolvedKey);
383
469
  if (wk) {
384
470
  log.info(
385
471
  `discovery via /.well-known/pi: ${wk.builtinProviders.length} builtin, ${wk.customPool.length} custom`,
386
472
  );
387
- writeDiscoveryCache(wk);
473
+ writeDiscoveryCache(discoveryNamespace(cfg, resolvedKey), wk);
388
474
  return wk;
389
475
  }
390
476
  if (!resolvedKey) {
@@ -393,14 +479,32 @@ export async function fetchDiscovery(
393
479
  );
394
480
  }
395
481
  const raw = await fetchRawModels(cfg, resolvedKey);
396
- const d = classifyLocally(raw, cfg);
482
+ const d = keepLastKnownAliases(classifyLocally(raw, cfg), discoveryNamespace(cfg, resolvedKey));
397
483
  log.info(
398
484
  `discovery via /v1/models: ${d.builtinProviders.length} builtin, ${d.customPool.length} custom`,
399
485
  );
400
- writeDiscoveryCache(d);
486
+ writeDiscoveryCache(discoveryNamespace(cfg, resolvedKey), d);
401
487
  return d;
402
488
  }
403
489
 
490
+ /**
491
+ * /v1/models lists models but cannot say what an alias resolves to, so it is
492
+ * not an authoritative answer about aliases (an empty `aliases` from the
493
+ * bridge is). Keep the last known resolutions, with their age, so a stale
494
+ * pin still works during a bridge outage instead of leaving the alias unpinned.
495
+ */
496
+ function keepLastKnownAliases(d: Discovery, namespace: string): Discovery {
497
+ // The file, or this process's own snapshot when another credential has
498
+ // since overwritten the shared file.
499
+ const prev = lastKnownAliases(namespace);
500
+ if (!prev) return d;
501
+ const at = prev.fetchedAt;
502
+ log.warn(
503
+ `alias catalogue unavailable; keeping the last known aliases (age ${Math.round((Date.now() - at) / 60_000)} min)`,
504
+ );
505
+ return { ...d, aliases: prev.aliases, aliasesFetchedAt: at };
506
+ }
507
+
404
508
  /** Convenience: flat set of all upstream ids (after server-applied excludes). */
405
509
  export function discoveryToIdSet(d: Discovery): Set<string> {
406
510
  const out = new Set<string>();