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/fetch-usage.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
import type { ProxyConfig } from "./config.ts";
|
|
15
15
|
import { resolveConfigValue } from "./config.ts";
|
|
16
16
|
import { PLUGIN_USER_AGENT } from "./fetch-models.ts";
|
|
17
|
+
import { cacheNamespace } from "./cache-namespace.ts";
|
|
17
18
|
import { log } from "./log.ts";
|
|
18
19
|
|
|
19
20
|
const REQUEST_TIMEOUT_MS = 15_000;
|
|
@@ -34,12 +35,60 @@ const SIDECAR_USAGE_PATH = "/api/usage";
|
|
|
34
35
|
/** Where a usage document came from. */
|
|
35
36
|
export type UsageSource = "plugin" | "sidecar";
|
|
36
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Contract v2 only: burn pace of a quota window, computed by the bridge from its
|
|
40
|
+
* own history. Absent until the bridge has enough samples, and on old bridges.
|
|
41
|
+
*/
|
|
42
|
+
export interface UsagePace {
|
|
43
|
+
/** Burn rate divided by the sustainable rate (remaining / time to reset). */
|
|
44
|
+
multiplier: number;
|
|
45
|
+
/** Fraction of the window spent per hour. */
|
|
46
|
+
burnPerHour: number;
|
|
47
|
+
/** RFC 3339 projection of exhaustion; absent when nothing is being spent. */
|
|
48
|
+
exhaustAt?: string;
|
|
49
|
+
/** Minutes of history the estimate is based on. */
|
|
50
|
+
sampleMinutes: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
37
53
|
export interface UsageGroup {
|
|
38
54
|
id: string;
|
|
39
55
|
label: string;
|
|
40
56
|
remainingFraction: number;
|
|
41
57
|
resetTime: string | null;
|
|
42
58
|
models?: string[];
|
|
59
|
+
pace?: UsagePace;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Contract v2 only: the account that served the session's last request. */
|
|
63
|
+
export interface UsageLastServed {
|
|
64
|
+
authIndex: string;
|
|
65
|
+
/** Usage-API provider key, e.g. `claude`; may be empty. */
|
|
66
|
+
provider: string;
|
|
67
|
+
/** RFC 3339 time of the request. */
|
|
68
|
+
at: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Contract v2 only: which account the bridge has bound the Pi session to. */
|
|
72
|
+
export interface UsageSession {
|
|
73
|
+
/** Absent in a session-only answer that carries just `lastServed`. */
|
|
74
|
+
status?: "bound" | "unbound" | "ambiguous" | "unsupported";
|
|
75
|
+
authIndex?: string;
|
|
76
|
+
lastServed?: UsageLastServed;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Contract v2 only: how the router spreads requests over an account tier. */
|
|
80
|
+
export type RoutingStrategy = "round-robin" | "weighted-round-robin" | "fill-first";
|
|
81
|
+
|
|
82
|
+
/** Contract v2 only: where an account stands in the router's current choice. */
|
|
83
|
+
export interface UsageAccountRouting {
|
|
84
|
+
/** The account belongs to the tier the router currently dispatches to. */
|
|
85
|
+
active: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Fraction (0..1) of the tier's requests the account receives. Absent when
|
|
88
|
+
* the bridge sent none or an invalid one, which is not the same as an
|
|
89
|
+
* explicit 0 (fill-first: in the tier, but receiving nothing).
|
|
90
|
+
*/
|
|
91
|
+
share?: number;
|
|
43
92
|
}
|
|
44
93
|
|
|
45
94
|
export interface UsageAccount {
|
|
@@ -56,6 +105,12 @@ export interface UsageAccount {
|
|
|
56
105
|
supported: boolean;
|
|
57
106
|
error?: string;
|
|
58
107
|
groups?: UsageGroup[];
|
|
108
|
+
/** Contract v2 only: routing priority, higher first (0 when unset). */
|
|
109
|
+
priority?: number;
|
|
110
|
+
/** Contract v2 only: weight within its priority tier (1 when unset). */
|
|
111
|
+
weight?: number;
|
|
112
|
+
/** Contract v2 only: the account's place in the current routing tier. */
|
|
113
|
+
routing?: UsageAccountRouting;
|
|
59
114
|
}
|
|
60
115
|
|
|
61
116
|
export interface UsageDocument {
|
|
@@ -67,6 +122,10 @@ export interface UsageDocument {
|
|
|
67
122
|
cache?: { updatedAt: string; stale: boolean; ttlMs: number };
|
|
68
123
|
/** Contract v2 only: which key the server authenticated. */
|
|
69
124
|
client?: { keyHint: string };
|
|
125
|
+
/** Contract v2 only, when the request named a session: its bound account. */
|
|
126
|
+
session?: UsageSession;
|
|
127
|
+
/** Contract v2 only: the router's strategy. */
|
|
128
|
+
routing?: { strategy: RoutingStrategy };
|
|
70
129
|
}
|
|
71
130
|
|
|
72
131
|
interface CacheEntry {
|
|
@@ -74,6 +133,43 @@ interface CacheEntry {
|
|
|
74
133
|
doc: UsageDocument;
|
|
75
134
|
source: UsageSource;
|
|
76
135
|
contract: number;
|
|
136
|
+
/** Session query the document was fetched with; its `session` field depends on it. */
|
|
137
|
+
query: string;
|
|
138
|
+
/** Proxy origin + key digest it was fetched for; another pair is a miss. */
|
|
139
|
+
namespace: string;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The Pi session asking for usage, so the bridge can report its bound account. */
|
|
143
|
+
export interface UsageSessionQuery {
|
|
144
|
+
id: string;
|
|
145
|
+
model?: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Query string carrying the session and model, or "" when there is none. */
|
|
149
|
+
export function sessionQueryString(session?: UsageSessionQuery): string {
|
|
150
|
+
if (!session?.id) return "";
|
|
151
|
+
const q = new URLSearchParams({ session: session.id });
|
|
152
|
+
if (session.model) q.set("model", session.model);
|
|
153
|
+
return `?${q.toString()}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The proxy API key; it may be a `!command` reference, so it is run. */
|
|
157
|
+
export function resolveProxyApiKey(cfg: ProxyConfig): string {
|
|
158
|
+
return cfg.proxy.apiKey ? resolveConfigValue(cfg.proxy.apiKey) : "";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The cache namespace of usage data for this configuration: the proxy origin
|
|
163
|
+
* and the digest of both client keys. `apiKey` is resolved from the config
|
|
164
|
+
* unless the caller already holds it; a caller that fetches must pass the
|
|
165
|
+
* key it sends, so the result is cached under the key that produced it.
|
|
166
|
+
*/
|
|
167
|
+
export function usageNamespace(
|
|
168
|
+
cfg: ProxyConfig,
|
|
169
|
+
resolvedUsageKey: string,
|
|
170
|
+
apiKey: string = resolveProxyApiKey(cfg),
|
|
171
|
+
): string {
|
|
172
|
+
return cacheNamespace(cfg.proxy.endpoint, apiKey, resolvedUsageKey);
|
|
77
173
|
}
|
|
78
174
|
|
|
79
175
|
let cache: CacheEntry | null = null;
|
|
@@ -116,9 +212,170 @@ async function getJSON(
|
|
|
116
212
|
}
|
|
117
213
|
|
|
118
214
|
function parseUsage(body: unknown, origin: string): UsageDocument {
|
|
119
|
-
const doc = body
|
|
120
|
-
if (!doc
|
|
121
|
-
|
|
215
|
+
const doc = sanitizeUsageDocument(body);
|
|
216
|
+
if (!doc) throw new Error(`${origin} returned unexpected payload shape`);
|
|
217
|
+
return doc;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// --------------------------------------------------------------------------- sanitizing
|
|
221
|
+
//
|
|
222
|
+
// The document reaches the footer and the Usage tab from the network and from
|
|
223
|
+
// a file other processes write. Both renderers run inside Pi event handlers,
|
|
224
|
+
// so the shape is enforced once at ingress: an invalid envelope is rejected
|
|
225
|
+
// (callers keep the last good document), invalid entries are skipped, and
|
|
226
|
+
// malformed optional fields are omitted. Non-finite numbers count as absent.
|
|
227
|
+
|
|
228
|
+
type Obj = Record<string, unknown>;
|
|
229
|
+
|
|
230
|
+
function isObj(v: unknown): v is Obj {
|
|
231
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function finite(v: unknown): number | undefined {
|
|
235
|
+
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function str(v: unknown): string | undefined {
|
|
239
|
+
return typeof v === "string" ? v : undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function sanitizePace(v: unknown): UsagePace | undefined {
|
|
243
|
+
if (!isObj(v)) return undefined;
|
|
244
|
+
const multiplier = finite(v.multiplier);
|
|
245
|
+
const burnPerHour = finite(v.burnPerHour);
|
|
246
|
+
if (multiplier === undefined || burnPerHour === undefined) return undefined;
|
|
247
|
+
const pace: UsagePace = {
|
|
248
|
+
multiplier,
|
|
249
|
+
burnPerHour,
|
|
250
|
+
sampleMinutes: finite(v.sampleMinutes) ?? 0,
|
|
251
|
+
};
|
|
252
|
+
const exhaustAt = str(v.exhaustAt);
|
|
253
|
+
if (exhaustAt && Number.isFinite(Date.parse(exhaustAt))) {
|
|
254
|
+
pace.exhaustAt = exhaustAt;
|
|
255
|
+
}
|
|
256
|
+
return pace;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function sanitizeGroup(v: unknown): UsageGroup | null {
|
|
260
|
+
if (!isObj(v)) return null;
|
|
261
|
+
const id = str(v.id);
|
|
262
|
+
const remainingFraction = finite(v.remainingFraction);
|
|
263
|
+
if (!id || remainingFraction === undefined) return null;
|
|
264
|
+
const g: UsageGroup = {
|
|
265
|
+
id,
|
|
266
|
+
label: str(v.label) ?? id,
|
|
267
|
+
remainingFraction,
|
|
268
|
+
resetTime: str(v.resetTime) ?? null,
|
|
269
|
+
};
|
|
270
|
+
if (Array.isArray(v.models)) {
|
|
271
|
+
g.models = v.models.filter((m): m is string => typeof m === "string");
|
|
272
|
+
}
|
|
273
|
+
const pace = sanitizePace(v.pace);
|
|
274
|
+
if (pace) g.pace = pace;
|
|
275
|
+
return g;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function sanitizeAccount(v: unknown): UsageAccount | null {
|
|
279
|
+
if (!isObj(v)) return null;
|
|
280
|
+
const provider = str(v.provider);
|
|
281
|
+
if (!provider) return null;
|
|
282
|
+
const account = str(v.account) ?? "";
|
|
283
|
+
const authIndex =
|
|
284
|
+
str(v.authIndex) ?? (finite(v.authIndex) !== undefined ? String(v.authIndex) : "");
|
|
285
|
+
const a: UsageAccount = {
|
|
286
|
+
provider,
|
|
287
|
+
account,
|
|
288
|
+
authIndex,
|
|
289
|
+
label: str(v.label) ?? (account || authIndex || provider),
|
|
290
|
+
status: str(v.status) ?? "",
|
|
291
|
+
disabled: v.disabled === true,
|
|
292
|
+
unavailable: v.unavailable === true,
|
|
293
|
+
success: finite(v.success) ?? 0,
|
|
294
|
+
failed: finite(v.failed) ?? 0,
|
|
295
|
+
lastRequestAt: str(v.lastRequestAt) ?? null,
|
|
296
|
+
supported: v.supported === true,
|
|
297
|
+
};
|
|
298
|
+
const error = str(v.error);
|
|
299
|
+
if (error) a.error = error;
|
|
300
|
+
if (Array.isArray(v.groups)) {
|
|
301
|
+
a.groups = v.groups
|
|
302
|
+
.map(sanitizeGroup)
|
|
303
|
+
.filter((g): g is UsageGroup => g !== null);
|
|
304
|
+
}
|
|
305
|
+
const priority = finite(v.priority);
|
|
306
|
+
if (priority !== undefined) a.priority = priority;
|
|
307
|
+
const weight = finite(v.weight);
|
|
308
|
+
if (weight !== undefined) a.weight = weight;
|
|
309
|
+
if (isObj(v.routing) && typeof v.routing.active === "boolean") {
|
|
310
|
+
const share = finite(v.routing.share);
|
|
311
|
+
a.routing = { active: v.routing.active };
|
|
312
|
+
if (share !== undefined) a.routing.share = Math.max(0, Math.min(1, share));
|
|
313
|
+
}
|
|
314
|
+
return a;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const STRATEGIES = new Set(["round-robin", "weighted-round-robin", "fill-first"]);
|
|
318
|
+
|
|
319
|
+
function sanitizeLastServed(v: unknown): UsageLastServed | undefined {
|
|
320
|
+
if (!isObj(v)) return undefined;
|
|
321
|
+
const authIndex =
|
|
322
|
+
str(v.authIndex) ?? (finite(v.authIndex) !== undefined ? String(v.authIndex) : "");
|
|
323
|
+
const at = str(v.at);
|
|
324
|
+
if (!authIndex || !at || !Number.isFinite(Date.parse(at))) return undefined;
|
|
325
|
+
return { authIndex, provider: str(v.provider) ?? "", at };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const SESSION_STATUSES = new Set(["bound", "unbound", "ambiguous", "unsupported"]);
|
|
329
|
+
|
|
330
|
+
/** A session binding, or undefined when it is not one. */
|
|
331
|
+
export function sanitizeUsageSession(v: unknown): UsageSession | undefined {
|
|
332
|
+
if (!isObj(v)) return undefined;
|
|
333
|
+
// Status and lastServed are independent: either alone is valid data.
|
|
334
|
+
const s: UsageSession = {};
|
|
335
|
+
if (SESSION_STATUSES.has(v.status as string)) {
|
|
336
|
+
s.status = v.status as UsageSession["status"];
|
|
337
|
+
}
|
|
338
|
+
const authIndex = str(v.authIndex);
|
|
339
|
+
if (authIndex && s.status) s.authIndex = authIndex;
|
|
340
|
+
const lastServed = sanitizeLastServed(v.lastServed);
|
|
341
|
+
if (lastServed) s.lastServed = lastServed;
|
|
342
|
+
return s.status || s.lastServed ? s : undefined;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* A well-formed usage document built from untrusted JSON, or null when the
|
|
347
|
+
* envelope itself is unusable (wrong schema, no account list).
|
|
348
|
+
*/
|
|
349
|
+
export function sanitizeUsageDocument(body: unknown): UsageDocument | null {
|
|
350
|
+
if (!isObj(body) || body.schemaVersion !== 1 || !Array.isArray(body.accounts)) {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
const doc: UsageDocument = {
|
|
354
|
+
schemaVersion: 1,
|
|
355
|
+
generatedAt: str(body.generatedAt) ?? "",
|
|
356
|
+
accounts: body.accounts
|
|
357
|
+
.map(sanitizeAccount)
|
|
358
|
+
.filter((a): a is UsageAccount => a !== null),
|
|
359
|
+
unsupportedProviders: Array.isArray(body.unsupportedProviders)
|
|
360
|
+
? body.unsupportedProviders.filter((p): p is string => typeof p === "string")
|
|
361
|
+
: [],
|
|
362
|
+
};
|
|
363
|
+
const c = body.cache;
|
|
364
|
+
if (
|
|
365
|
+
isObj(c) &&
|
|
366
|
+
typeof c.updatedAt === "string" &&
|
|
367
|
+
typeof c.stale === "boolean" &&
|
|
368
|
+
finite(c.ttlMs) !== undefined
|
|
369
|
+
) {
|
|
370
|
+
doc.cache = { updatedAt: c.updatedAt, stale: c.stale, ttlMs: c.ttlMs as number };
|
|
371
|
+
}
|
|
372
|
+
if (isObj(body.client) && typeof body.client.keyHint === "string") {
|
|
373
|
+
doc.client = { keyHint: body.client.keyHint };
|
|
374
|
+
}
|
|
375
|
+
const session = sanitizeUsageSession(body.session);
|
|
376
|
+
if (session) doc.session = session;
|
|
377
|
+
if (isObj(body.routing) && STRATEGIES.has(body.routing.strategy as string)) {
|
|
378
|
+
doc.routing = { strategy: body.routing.strategy as RoutingStrategy };
|
|
122
379
|
}
|
|
123
380
|
return doc;
|
|
124
381
|
}
|
|
@@ -126,11 +383,26 @@ function parseUsage(body: unknown, origin: string): UsageDocument {
|
|
|
126
383
|
export async function fetchUsage(
|
|
127
384
|
cfg: ProxyConfig,
|
|
128
385
|
resolvedUsageKey: string,
|
|
129
|
-
opts: {
|
|
386
|
+
opts: {
|
|
387
|
+
force?: boolean;
|
|
388
|
+
session?: UsageSessionQuery;
|
|
389
|
+
/**
|
|
390
|
+
* The resolved proxy key to send. A caller that caches the result
|
|
391
|
+
* passes the key its namespace was computed from; otherwise the key is
|
|
392
|
+
* resolved here.
|
|
393
|
+
*/
|
|
394
|
+
apiKey?: string;
|
|
395
|
+
} = {},
|
|
130
396
|
): Promise<UsageDocument> {
|
|
397
|
+
const query = sessionQueryString(opts.session);
|
|
398
|
+
// The key may be a `!command` reference, so it must be resolved before use.
|
|
399
|
+
const apiKey = opts.apiKey ?? resolveProxyApiKey(cfg);
|
|
400
|
+
const namespace = usageNamespace(cfg, resolvedUsageKey, apiKey);
|
|
131
401
|
if (
|
|
132
402
|
!opts.force &&
|
|
133
403
|
cache &&
|
|
404
|
+
cache.namespace === namespace &&
|
|
405
|
+
cache.query === query &&
|
|
134
406
|
Date.now() - cache.fetchedAt < cfg.usageCacheTtlMs
|
|
135
407
|
) {
|
|
136
408
|
return cache.doc;
|
|
@@ -142,14 +414,19 @@ export async function fetchUsage(
|
|
|
142
414
|
} catch {
|
|
143
415
|
throw new Error(`proxy.endpoint is not a valid URL: ${cfg.proxy.endpoint}`);
|
|
144
416
|
}
|
|
145
|
-
// The key may be a `!command` reference, so it must be resolved before use.
|
|
146
|
-
const apiKey = cfg.proxy.apiKey ? resolveConfigValue(cfg.proxy.apiKey) : "";
|
|
147
417
|
|
|
148
418
|
// Preferred path: the plugin, using the key already configured for models.
|
|
149
419
|
if (apiKey) {
|
|
150
420
|
try {
|
|
151
|
-
const { doc, contract } = await fetchFromPlugin(origin, apiKey);
|
|
152
|
-
cache = {
|
|
421
|
+
const { doc, contract } = await fetchFromPlugin(origin, apiKey, query);
|
|
422
|
+
cache = {
|
|
423
|
+
fetchedAt: Date.now(),
|
|
424
|
+
doc,
|
|
425
|
+
source: "plugin",
|
|
426
|
+
contract,
|
|
427
|
+
query,
|
|
428
|
+
namespace,
|
|
429
|
+
};
|
|
153
430
|
log.debug(
|
|
154
431
|
`usage fetched from plugin (contract v${contract}), accounts:`,
|
|
155
432
|
doc.accounts.length,
|
|
@@ -171,7 +448,14 @@ export async function fetchUsage(
|
|
|
171
448
|
|
|
172
449
|
const doc = await fetchFromSidecar(origin, resolvedUsageKey);
|
|
173
450
|
// The sidecar predates contracts and only ever served the v1 shape.
|
|
174
|
-
cache = {
|
|
451
|
+
cache = {
|
|
452
|
+
fetchedAt: Date.now(),
|
|
453
|
+
doc,
|
|
454
|
+
source: "sidecar",
|
|
455
|
+
contract: 1,
|
|
456
|
+
query,
|
|
457
|
+
namespace,
|
|
458
|
+
};
|
|
175
459
|
log.debug("usage fetched from sidecar, accounts:", doc.accounts.length);
|
|
176
460
|
return doc;
|
|
177
461
|
}
|
|
@@ -187,20 +471,22 @@ export async function fetchUsage(
|
|
|
187
471
|
async function fetchFromPlugin(
|
|
188
472
|
origin: string,
|
|
189
473
|
apiKey: string,
|
|
474
|
+
query: string,
|
|
190
475
|
): Promise<{ doc: UsageDocument; contract: number }> {
|
|
191
476
|
const headers = {
|
|
192
477
|
Authorization: `Bearer ${apiKey}`,
|
|
193
478
|
[CONTRACT_HEADER]: String(PREFERRED_CONTRACT),
|
|
194
479
|
};
|
|
195
480
|
|
|
481
|
+
// Bridges that predate session binding ignore the extra query parameters.
|
|
196
482
|
let resp = await getJSON(
|
|
197
|
-
new URL(PLUGIN_USAGE_PATH, origin).toString(),
|
|
483
|
+
new URL(PLUGIN_USAGE_PATH + query, origin).toString(),
|
|
198
484
|
headers,
|
|
199
485
|
);
|
|
200
486
|
if (resp.status === 404) {
|
|
201
487
|
// Older bridge: only the testing path exists.
|
|
202
488
|
resp = await getJSON(
|
|
203
|
-
new URL(PLUGIN_USAGE_PATH_LEGACY, origin).toString(),
|
|
489
|
+
new URL(PLUGIN_USAGE_PATH_LEGACY + query, origin).toString(),
|
|
204
490
|
headers,
|
|
205
491
|
);
|
|
206
492
|
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// Footer quota segment: when to paint it and from what.
|
|
2
|
+
//
|
|
3
|
+
// Pi awaits `model_select` (and the other event handlers), and the concrete
|
|
4
|
+
// selection that pins a `latest/*` alias runs inside one. So the footer never
|
|
5
|
+
// waits on the bridge: every update paints from the shared file cache at once
|
|
6
|
+
// and refreshes over the network in the background. A background result is
|
|
7
|
+
// applied only if it still belongs to what the footer shows — the same Pi
|
|
8
|
+
// session, model and UI — so a slow response for the previous model can never
|
|
9
|
+
// repaint the footer after a switch.
|
|
10
|
+
|
|
11
|
+
import type { ProxyConfig } from "./config.ts";
|
|
12
|
+
import type { UsageDocument, UsageSessionQuery } from "./fetch-usage.ts";
|
|
13
|
+
import { fetchUsage, resolveProxyApiKey, usageNamespace } from "./fetch-usage.ts";
|
|
14
|
+
import { log } from "./log.ts";
|
|
15
|
+
import { providerToUsageKey, renderQuotaSegment } from "./status-quota.ts";
|
|
16
|
+
import {
|
|
17
|
+
isUsageFresh,
|
|
18
|
+
readUsageCache,
|
|
19
|
+
acquireUsageLock,
|
|
20
|
+
releaseUsageLock,
|
|
21
|
+
writeUsageCache,
|
|
22
|
+
} from "./usage-shared-cache.ts";
|
|
23
|
+
|
|
24
|
+
/** Status-line key. The leading "0" makes it sort before alphabetic keys so
|
|
25
|
+
* the quota segment appears first on the footer's extension-status line. */
|
|
26
|
+
export const QUOTA_STATUS_KEY = "0quota";
|
|
27
|
+
|
|
28
|
+
type ThemeColor = "success" | "warning" | "error" | "dim";
|
|
29
|
+
|
|
30
|
+
export interface QuotaUi {
|
|
31
|
+
theme: { fg(color: ThemeColor, text: string): string };
|
|
32
|
+
setStatus(key: string, text: string | undefined): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What the footer is about: one session's model, shown in one UI. */
|
|
36
|
+
export interface QuotaTarget {
|
|
37
|
+
ui: QuotaUi;
|
|
38
|
+
model?: { provider: string; id?: string };
|
|
39
|
+
sessionId?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface QuotaSource {
|
|
43
|
+
/** The cached document for the session, without any network. */
|
|
44
|
+
cached(session?: UsageSessionQuery): UsageDocument | null;
|
|
45
|
+
/** The document after refreshing it over the network if needed. */
|
|
46
|
+
load(
|
|
47
|
+
session?: UsageSessionQuery,
|
|
48
|
+
opts?: { staleAfterMs?: number },
|
|
49
|
+
): Promise<UsageDocument | null>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Fetch usage data through the shared file cache: if the on-disk cache is
|
|
54
|
+
* fresh, return it without any network call; otherwise acquire a
|
|
55
|
+
* cross-process lock and fetch at most once. Returns the best available doc
|
|
56
|
+
* (possibly stale) or null on failure. Never rejects.
|
|
57
|
+
*/
|
|
58
|
+
export async function loadUsageCached(
|
|
59
|
+
cfg: ProxyConfig,
|
|
60
|
+
resolvedUsageKey: string,
|
|
61
|
+
opts: {
|
|
62
|
+
session?: UsageSessionQuery;
|
|
63
|
+
staleAfterMs?: number;
|
|
64
|
+
/**
|
|
65
|
+
* The resolved proxy key, when the caller already holds it (avoids
|
|
66
|
+
* re-running a `!command` key). The same key is sent with the fetch
|
|
67
|
+
* and names the cache namespace, so a key that changes between calls
|
|
68
|
+
* can never publish one key's answer under another key's namespace.
|
|
69
|
+
*/
|
|
70
|
+
apiKey?: string;
|
|
71
|
+
} = {},
|
|
72
|
+
): Promise<UsageDocument | null> {
|
|
73
|
+
const apiKey = opts.apiKey ?? resolveProxyApiKey(cfg);
|
|
74
|
+
const ns = usageNamespace(cfg, resolvedUsageKey, apiKey);
|
|
75
|
+
const cached = readUsageCache(ns, opts.session);
|
|
76
|
+
// The document is shared, but the session binding is this session's own: a
|
|
77
|
+
// fresh document fetched by another instance still needs one fetch of ours.
|
|
78
|
+
const sessionKnown = !opts.session || cached?.sessionFresh === true;
|
|
79
|
+
const fresh =
|
|
80
|
+
cached !== null &&
|
|
81
|
+
(opts.staleAfterMs === undefined
|
|
82
|
+
? isUsageFresh(cached.ageMs)
|
|
83
|
+
: cached.ageMs < opts.staleAfterMs);
|
|
84
|
+
if (cached && fresh && sessionKnown) return cached.doc;
|
|
85
|
+
// Stale or missing — try to become the fetcher.
|
|
86
|
+
const lock = acquireUsageLock();
|
|
87
|
+
if (lock.state === "busy") {
|
|
88
|
+
// Another instance is fetching; serve what is cached.
|
|
89
|
+
return cached?.doc ?? null;
|
|
90
|
+
}
|
|
91
|
+
if (lock.state === "unavailable") {
|
|
92
|
+
// The cache directory refuses files: continue without the shared
|
|
93
|
+
// cache, throttled by the in-process cache instead.
|
|
94
|
+
try {
|
|
95
|
+
return await fetchUsage(cfg, resolvedUsageKey, { session: opts.session, apiKey });
|
|
96
|
+
} catch (e) {
|
|
97
|
+
log.debug("usage fetch failed without shared cache:", (e as Error).message);
|
|
98
|
+
return cached?.doc ?? null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const token = lock.token;
|
|
102
|
+
const startedAt = Date.now();
|
|
103
|
+
try {
|
|
104
|
+
const doc = await fetchUsage(cfg, resolvedUsageKey, {
|
|
105
|
+
force: true,
|
|
106
|
+
session: opts.session,
|
|
107
|
+
apiKey,
|
|
108
|
+
});
|
|
109
|
+
await writeUsageCache(ns, doc, opts.session, startedAt);
|
|
110
|
+
// Read back: the file may hold a newer document, and the binding rules
|
|
111
|
+
// (expiry) are applied in one place.
|
|
112
|
+
return readUsageCache(ns, opts.session)?.doc ?? doc;
|
|
113
|
+
} catch (e) {
|
|
114
|
+
log.debug("usage fetch failed in shared cache:", (e as Error).message);
|
|
115
|
+
return readUsageCache(ns, opts.session)?.doc ?? null;
|
|
116
|
+
} finally {
|
|
117
|
+
releaseUsageLock(token);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The shared-file source used by the extension. */
|
|
122
|
+
export function sharedCacheSource(
|
|
123
|
+
cfg: ProxyConfig,
|
|
124
|
+
resolvedUsageKey: string,
|
|
125
|
+
): QuotaSource {
|
|
126
|
+
// Resolved once and used for every fetch, cache read and publication: the
|
|
127
|
+
// configuration is fixed for the process, and a `!command` key whose
|
|
128
|
+
// output changes takes effect on reload, as for model calls.
|
|
129
|
+
const apiKey = resolveProxyApiKey(cfg);
|
|
130
|
+
const namespace = usageNamespace(cfg, resolvedUsageKey, apiKey);
|
|
131
|
+
return {
|
|
132
|
+
cached: (session) => readUsageCache(namespace, session)?.doc ?? null,
|
|
133
|
+
load: (session, opts) =>
|
|
134
|
+
loadUsageCached(cfg, resolvedUsageKey, { session, ...opts, apiKey }),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function targetKey(t: QuotaTarget): string {
|
|
139
|
+
return `${t.sessionId ?? ""}\u0000${t.model?.provider ?? ""}\u0000${t.model?.id ?? ""}`;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export interface QuotaFooter {
|
|
143
|
+
/**
|
|
144
|
+
* Paint the footer for the target from the cache now and, with `fetch`,
|
|
145
|
+
* refresh it in the background. Returns the background work so tests can
|
|
146
|
+
* wait for it; event handlers must not await it.
|
|
147
|
+
*/
|
|
148
|
+
update(
|
|
149
|
+
target: QuotaTarget,
|
|
150
|
+
opts?: {
|
|
151
|
+
fetch?: boolean;
|
|
152
|
+
staleAfterMs?: number;
|
|
153
|
+
/** Skip the network if a refresh is already pending (timer ticks). */
|
|
154
|
+
unlessBusy?: boolean;
|
|
155
|
+
},
|
|
156
|
+
): Promise<void>;
|
|
157
|
+
/** Repaint what the footer currently shows from the cache (clock tick). */
|
|
158
|
+
repaint(): void;
|
|
159
|
+
/** The UI is going away: drop the target and any pending results. */
|
|
160
|
+
reset(): void;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function createQuotaFooter(
|
|
164
|
+
source: QuotaSource,
|
|
165
|
+
clock: () => number = () => Date.now(),
|
|
166
|
+
): QuotaFooter {
|
|
167
|
+
let current: QuotaTarget | null = null;
|
|
168
|
+
let currentKey = "";
|
|
169
|
+
/** Sequence of background loads; an older one never overwrites a newer one. */
|
|
170
|
+
let seq = 0;
|
|
171
|
+
let appliedSeq = 0;
|
|
172
|
+
let pendingLoads = 0;
|
|
173
|
+
|
|
174
|
+
const sessionOf = (t: QuotaTarget): UsageSessionQuery | undefined =>
|
|
175
|
+
t.sessionId ? { id: t.sessionId, model: t.model?.id } : undefined;
|
|
176
|
+
|
|
177
|
+
const paint = (t: QuotaTarget, doc: UsageDocument | null) => {
|
|
178
|
+
let text: string | undefined;
|
|
179
|
+
try {
|
|
180
|
+
text =
|
|
181
|
+
doc && t.model
|
|
182
|
+
? (renderQuotaSegment(doc, t.model.provider, t.ui.theme, t.model.id, clock()) ??
|
|
183
|
+
undefined)
|
|
184
|
+
: undefined;
|
|
185
|
+
} catch (err) {
|
|
186
|
+
log.debug("quota render failed:", (err as Error).message);
|
|
187
|
+
text = undefined;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
t.ui.setStatus(QUOTA_STATUS_KEY, text);
|
|
191
|
+
} catch (err) {
|
|
192
|
+
// A replaced session's UI throws; the new session repaints itself.
|
|
193
|
+
log.debug("quota status update skipped:", (err as Error).message);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const paintFromCache = (t: QuotaTarget) => {
|
|
198
|
+
let doc: UsageDocument | null = null;
|
|
199
|
+
try {
|
|
200
|
+
doc = t.model ? source.cached(sessionOf(t)) : null;
|
|
201
|
+
} catch (err) {
|
|
202
|
+
log.debug("quota cache read failed:", (err as Error).message);
|
|
203
|
+
}
|
|
204
|
+
paint(t, doc);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const isCurrent = (t: QuotaTarget, key: string) =>
|
|
208
|
+
current !== null && current.ui === t.ui && currentKey === key;
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
update(target, opts = {}) {
|
|
212
|
+
// Copy the model: ctx.model is a live getter.
|
|
213
|
+
const t: QuotaTarget = {
|
|
214
|
+
ui: target.ui,
|
|
215
|
+
sessionId: target.sessionId,
|
|
216
|
+
model: target.model
|
|
217
|
+
? { provider: target.model.provider, id: target.model.id }
|
|
218
|
+
: undefined,
|
|
219
|
+
};
|
|
220
|
+
const key = targetKey(t);
|
|
221
|
+
current = t;
|
|
222
|
+
currentKey = key;
|
|
223
|
+
paintFromCache(t);
|
|
224
|
+
// Nothing to fetch for a model without quota windows.
|
|
225
|
+
if (!opts.fetch || !t.model || !providerToUsageKey(t.model.provider)) {
|
|
226
|
+
return Promise.resolve();
|
|
227
|
+
}
|
|
228
|
+
if (opts.unlessBusy && pendingLoads > 0) return Promise.resolve();
|
|
229
|
+
const mine = ++seq;
|
|
230
|
+
pendingLoads++;
|
|
231
|
+
return source
|
|
232
|
+
.load(sessionOf(t), { staleAfterMs: opts.staleAfterMs })
|
|
233
|
+
.finally(() => {
|
|
234
|
+
pendingLoads--;
|
|
235
|
+
})
|
|
236
|
+
.then(
|
|
237
|
+
(doc) => {
|
|
238
|
+
if (!isCurrent(t, key) || mine < appliedSeq) return;
|
|
239
|
+
appliedSeq = mine;
|
|
240
|
+
paint(t, doc);
|
|
241
|
+
},
|
|
242
|
+
(err) => {
|
|
243
|
+
log.debug("quota refresh failed:", (err as Error).message);
|
|
244
|
+
},
|
|
245
|
+
);
|
|
246
|
+
},
|
|
247
|
+
repaint() {
|
|
248
|
+
if (current) paintFromCache(current);
|
|
249
|
+
},
|
|
250
|
+
reset() {
|
|
251
|
+
current = null;
|
|
252
|
+
currentKey = "";
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
}
|