@specode/pi-subscription-usage 1.3.1 → 1.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 +114 -84
- package/README.zh-CN.md +114 -84
- package/package.json +5 -3
- package/src/format.ts +1 -0
- package/src/providers/antigravity.ts +372 -0
- package/src/providers/claude-bridge.ts +118 -0
- package/src/query.ts +167 -6
- package/src/types.ts +3 -1
- package/src/usage.ts +61 -6
package/src/query.ts
CHANGED
|
@@ -7,8 +7,21 @@ import {
|
|
|
7
7
|
fingerprintResolvedAuth,
|
|
8
8
|
isAbortError,
|
|
9
9
|
redactUsageError,
|
|
10
|
+
sanitizeDisplayText,
|
|
10
11
|
} from "./core.ts";
|
|
11
12
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
13
|
+
import {
|
|
14
|
+
ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
|
|
15
|
+
ANTIGRAVITY_OFFICIAL_ORIGINS,
|
|
16
|
+
ANTIGRAVITY_PROVIDER_ID,
|
|
17
|
+
antigravityQueryOrigins,
|
|
18
|
+
antigravityRequestHeaders,
|
|
19
|
+
emailFromAntigravityCredential,
|
|
20
|
+
extractAntigravityAuth,
|
|
21
|
+
isAntigravitySubscriptionRequired,
|
|
22
|
+
isRetryableAntigravityError,
|
|
23
|
+
normalizeAntigravityUsage,
|
|
24
|
+
} from "./providers/antigravity.ts";
|
|
12
25
|
import {
|
|
13
26
|
codexAccountIdFromAccessToken,
|
|
14
27
|
normalizeCodexResetCreditsPayload,
|
|
@@ -206,8 +219,112 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
206
219
|
return normalizeGrokBilling(credits, capturedAt, monthly);
|
|
207
220
|
},
|
|
208
221
|
},
|
|
222
|
+
{
|
|
223
|
+
id: ANTIGRAVITY_PROVIDER_ID,
|
|
224
|
+
displayName: "Antigravity",
|
|
225
|
+
providerIds: [ANTIGRAVITY_PROVIDER_ID],
|
|
226
|
+
officialOrigins: ANTIGRAVITY_OFFICIAL_ORIGINS,
|
|
227
|
+
semantics: {
|
|
228
|
+
kind: "consumer-subscription",
|
|
229
|
+
label: "Antigravity subscription limits",
|
|
230
|
+
},
|
|
231
|
+
async query(auth, signal, timeoutMs) {
|
|
232
|
+
const origins = antigravityQueryOrigins(auth.model?.baseUrl);
|
|
233
|
+
// Plan metadata is optional; attach the handler now so a quota failure
|
|
234
|
+
// cannot leave this request as an unhandled rejection.
|
|
235
|
+
const plan = fetchAntigravityJson(
|
|
236
|
+
origins,
|
|
237
|
+
"/v1internal:loadCodeAssist",
|
|
238
|
+
auth,
|
|
239
|
+
signal,
|
|
240
|
+
timeoutMs,
|
|
241
|
+
"Antigravity code assist endpoint",
|
|
242
|
+
ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
|
|
243
|
+
).then(
|
|
244
|
+
(result) => result.payload,
|
|
245
|
+
() => undefined,
|
|
246
|
+
);
|
|
247
|
+
const quota = await fetchAntigravityJson(
|
|
248
|
+
origins,
|
|
249
|
+
"/v1internal:retrieveUserQuotaSummary",
|
|
250
|
+
auth,
|
|
251
|
+
signal,
|
|
252
|
+
timeoutMs,
|
|
253
|
+
"Antigravity quota endpoint",
|
|
254
|
+
{},
|
|
255
|
+
);
|
|
256
|
+
const planPayload = await plan;
|
|
257
|
+
if (signal.aborted) {
|
|
258
|
+
throw Object.assign(new Error("Usage query aborted."), {
|
|
259
|
+
name: "AbortError",
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return normalizeAntigravityUsage(
|
|
264
|
+
quota.payload,
|
|
265
|
+
Date.now(),
|
|
266
|
+
planPayload,
|
|
267
|
+
auth.accountEmail,
|
|
268
|
+
);
|
|
269
|
+
},
|
|
270
|
+
},
|
|
209
271
|
];
|
|
210
272
|
|
|
273
|
+
async function readAntigravityStoredCredential(): Promise<unknown> {
|
|
274
|
+
try {
|
|
275
|
+
const { readStoredCredential } = await import(
|
|
276
|
+
"@earendil-works/pi-coding-agent",
|
|
277
|
+
);
|
|
278
|
+
return readStoredCredential(ANTIGRAVITY_PROVIDER_ID);
|
|
279
|
+
} catch {
|
|
280
|
+
return undefined;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function fetchAntigravityJson(
|
|
285
|
+
origins: readonly string[],
|
|
286
|
+
path: string,
|
|
287
|
+
auth: ResolvedUsageAuth,
|
|
288
|
+
signal: AbortSignal,
|
|
289
|
+
timeoutMs: number,
|
|
290
|
+
description: string,
|
|
291
|
+
body: Record<string, unknown>,
|
|
292
|
+
): Promise<{ origin: string; payload: Record<string, unknown> }> {
|
|
293
|
+
let lastError: unknown;
|
|
294
|
+
for (const origin of origins) {
|
|
295
|
+
try {
|
|
296
|
+
return {
|
|
297
|
+
origin,
|
|
298
|
+
payload: await fetchProviderJson(
|
|
299
|
+
`${origin}${path}`,
|
|
300
|
+
auth,
|
|
301
|
+
signal,
|
|
302
|
+
timeoutMs,
|
|
303
|
+
description,
|
|
304
|
+
{
|
|
305
|
+
method: "POST",
|
|
306
|
+
body,
|
|
307
|
+
headers: antigravityRequestHeaders(),
|
|
308
|
+
},
|
|
309
|
+
),
|
|
310
|
+
};
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (isAbortError(error) || signal.aborted) throw error;
|
|
313
|
+
// Free-tier accounts get this on every origin; it is not a fault.
|
|
314
|
+
if (isAntigravitySubscriptionRequired(error)) {
|
|
315
|
+
throw new UsageUnsupportedError(
|
|
316
|
+
"Antigravity quota summary requires a paid Google AI subscription.",
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
lastError = error;
|
|
320
|
+
if (!isRetryableAntigravityError(error)) throw error;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
throw lastError instanceof Error
|
|
324
|
+
? lastError
|
|
325
|
+
: new Error(`${description} failed.`);
|
|
326
|
+
}
|
|
327
|
+
|
|
211
328
|
export function adapterForProvider(
|
|
212
329
|
providerId: string | undefined,
|
|
213
330
|
): UsageProviderAdapter | undefined {
|
|
@@ -230,6 +347,18 @@ export async function resolveUsageAuth(
|
|
|
230
347
|
const UnsupportedModeError = adapter.id === OPENAI_PROVIDER_ID
|
|
231
348
|
? UsageUnsupportedError
|
|
232
349
|
: Error;
|
|
350
|
+
// Packages that reuse a provider id over another transport (for example
|
|
351
|
+
// pi-antigravity-bridge's agy-bridge://) are not a proxy to refuse loudly.
|
|
352
|
+
if (
|
|
353
|
+
current &&
|
|
354
|
+
adapter.providerIds.includes(current.provider) &&
|
|
355
|
+
current.baseUrl &&
|
|
356
|
+
!isHttpUrl(current.baseUrl)
|
|
357
|
+
) {
|
|
358
|
+
throw new UsageUnsupportedError(
|
|
359
|
+
`${adapter.displayName} usage is unavailable for models served over ${sanitizeDisplayText(current.baseUrl, 60)}; only the provider's own HTTPS API reports quota.`,
|
|
360
|
+
);
|
|
361
|
+
}
|
|
233
362
|
if (
|
|
234
363
|
current &&
|
|
235
364
|
adapter.providerIds.includes(current.provider) &&
|
|
@@ -265,13 +394,28 @@ export async function resolveUsageAuth(
|
|
|
265
394
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
266
395
|
);
|
|
267
396
|
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
397
|
+
let authorization = headerValue(result.auth.headers, "Authorization");
|
|
398
|
+
let extractedToken: string | undefined;
|
|
399
|
+
let accountEmail: string | undefined;
|
|
400
|
+
|
|
401
|
+
if (adapter.id === ANTIGRAVITY_PROVIDER_ID) {
|
|
402
|
+
const extracted = extractAntigravityAuth(result.auth.apiKey, authorization);
|
|
403
|
+
authorization = extracted.authorization;
|
|
404
|
+
extractedToken = extracted.token;
|
|
405
|
+
accountEmail =
|
|
406
|
+
extracted.email ??
|
|
407
|
+
emailFromAntigravityCredential(
|
|
408
|
+
await readAntigravityStoredCredential(),
|
|
409
|
+
);
|
|
410
|
+
} else if (!authorization && result.auth.apiKey) {
|
|
411
|
+
authorization = `Bearer ${result.auth.apiKey}`;
|
|
412
|
+
}
|
|
413
|
+
|
|
271
414
|
if (!authorization) return undefined;
|
|
272
415
|
const headers = { Authorization: authorization };
|
|
273
416
|
const secrets = [
|
|
274
417
|
result.auth.apiKey,
|
|
418
|
+
extractedToken && extractedToken !== result.auth.apiKey ? extractedToken : undefined,
|
|
275
419
|
headerValue(result.auth.headers, "Authorization"),
|
|
276
420
|
authorization,
|
|
277
421
|
].filter((value): value is string => Boolean(value));
|
|
@@ -287,6 +431,7 @@ export async function resolveUsageAuth(
|
|
|
287
431
|
actualProviderId: model.provider,
|
|
288
432
|
model,
|
|
289
433
|
openaiClientId: clientId,
|
|
434
|
+
accountEmail,
|
|
290
435
|
// Only the backend credential is sent to ChatGPT. The active API token
|
|
291
436
|
// is used locally for registration matching and cache invalidation.
|
|
292
437
|
headers: companion.headers,
|
|
@@ -296,6 +441,7 @@ export async function resolveUsageAuth(
|
|
|
296
441
|
}
|
|
297
442
|
return {
|
|
298
443
|
actualProviderId: model.provider,
|
|
444
|
+
accountEmail,
|
|
299
445
|
apiKey: result.auth.apiKey,
|
|
300
446
|
headers,
|
|
301
447
|
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
@@ -345,7 +491,10 @@ export async function queryProviderUsage(
|
|
|
345
491
|
return await adapter.query(auth, signal, timeoutMs);
|
|
346
492
|
} catch (error) {
|
|
347
493
|
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
348
|
-
|
|
494
|
+
const message = redactUsageError(errorMessage(error), auth.secrets);
|
|
495
|
+
throw error instanceof UsageUnsupportedError
|
|
496
|
+
? new UsageUnsupportedError(message)
|
|
497
|
+
: new Error(message);
|
|
349
498
|
}
|
|
350
499
|
}
|
|
351
500
|
|
|
@@ -392,8 +541,11 @@ export async function fetchProviderJson(
|
|
|
392
541
|
description,
|
|
393
542
|
);
|
|
394
543
|
if (!response.ok) {
|
|
395
|
-
throw
|
|
396
|
-
|
|
544
|
+
throw Object.assign(
|
|
545
|
+
new Error(
|
|
546
|
+
`${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
|
|
547
|
+
),
|
|
548
|
+
{ status: response.status },
|
|
397
549
|
);
|
|
398
550
|
}
|
|
399
551
|
let parsed: unknown;
|
|
@@ -487,6 +639,15 @@ function candidateModels(
|
|
|
487
639
|
return candidates;
|
|
488
640
|
}
|
|
489
641
|
|
|
642
|
+
function isHttpUrl(value: string): boolean {
|
|
643
|
+
try {
|
|
644
|
+
const { protocol } = new URL(value);
|
|
645
|
+
return protocol === "https:" || protocol === "http:";
|
|
646
|
+
} catch {
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
490
651
|
function hasOfficialOrigin(
|
|
491
652
|
value: string | undefined,
|
|
492
653
|
adapter: UsageProviderAdapter,
|
package/src/types.ts
CHANGED
|
@@ -53,6 +53,7 @@ export interface ResolvedUsageAuth {
|
|
|
53
53
|
openaiClientId?: string;
|
|
54
54
|
/** Original usage identity, retained when reset auth adds account headers. */
|
|
55
55
|
usageFingerprint?: string;
|
|
56
|
+
accountEmail?: string;
|
|
56
57
|
apiKey?: string;
|
|
57
58
|
headers: Record<string, string>;
|
|
58
59
|
fingerprint: string;
|
|
@@ -84,6 +85,7 @@ export type ProviderUsageState =
|
|
|
84
85
|
| {
|
|
85
86
|
providerId: string;
|
|
86
87
|
providerName: string;
|
|
87
|
-
|
|
88
|
+
/** `pending`: an observed provider has not reported usage yet. */
|
|
89
|
+
status: "unsupported" | "auth-unavailable" | "query-failed" | "pending";
|
|
88
90
|
message: string;
|
|
89
91
|
};
|
package/src/usage.ts
CHANGED
|
@@ -30,6 +30,11 @@ import {
|
|
|
30
30
|
resolveCodexResetAuth,
|
|
31
31
|
} from "./codex-resets.ts";
|
|
32
32
|
import { formatProviderState } from "./format.ts";
|
|
33
|
+
import {
|
|
34
|
+
CLAUDE_BRIDGE_PROVIDER_ID,
|
|
35
|
+
normalizeClaudeRateLimitHeaders,
|
|
36
|
+
settleClaudeReport,
|
|
37
|
+
} from "./providers/claude-bridge.ts";
|
|
33
38
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
34
39
|
import { OPENAI_PROVIDER_ID } from "./providers/openai.ts";
|
|
35
40
|
import {
|
|
@@ -50,6 +55,7 @@ import type {
|
|
|
50
55
|
ResolvedUsageAuth,
|
|
51
56
|
UsageModel,
|
|
52
57
|
UsageProviderAdapter,
|
|
58
|
+
UsageReport,
|
|
53
59
|
} from "./types.ts";
|
|
54
60
|
|
|
55
61
|
const CACHE_TTL_MS = 5 * 60 * 1_000;
|
|
@@ -69,13 +75,18 @@ type StableCurrent = {
|
|
|
69
75
|
|
|
70
76
|
export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
71
77
|
const cache = new UsageCache(CACHE_TTL_MS);
|
|
72
|
-
const failureBackoff = new Map<
|
|
78
|
+
const failureBackoff = new Map<
|
|
79
|
+
string,
|
|
80
|
+
{ until: number; message: string; status: "unsupported" | "query-failed" }
|
|
81
|
+
>();
|
|
73
82
|
const activeControllers = new Set<AbortController>();
|
|
74
83
|
let sessionActive = false;
|
|
75
84
|
let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE;
|
|
76
85
|
let statusGeneration = 0;
|
|
77
86
|
let statusController: AbortController | undefined;
|
|
78
87
|
let statusTimer: ReturnType<typeof setTimeout> | undefined;
|
|
88
|
+
// Holds no credential, so session_shutdown leaves it; nothing reads it after.
|
|
89
|
+
let claudeObservation: UsageReport | undefined;
|
|
79
90
|
|
|
80
91
|
function emitUsageStatus(event: UsageStatusEvent): void {
|
|
81
92
|
pi.events.emit(USAGE_STATUS_EVENT, event);
|
|
@@ -132,7 +143,10 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
132
143
|
model: UsageModel,
|
|
133
144
|
schedule: boolean,
|
|
134
145
|
): void {
|
|
135
|
-
if (
|
|
146
|
+
if (
|
|
147
|
+
outcome.state.status === "unsupported" ||
|
|
148
|
+
outcome.state.status === "pending"
|
|
149
|
+
) {
|
|
136
150
|
clearStatusTimer();
|
|
137
151
|
safeSetStatus(ctx, undefined);
|
|
138
152
|
emitUnavailableUsage();
|
|
@@ -224,7 +238,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
224
238
|
state: {
|
|
225
239
|
providerId: adapter.id,
|
|
226
240
|
providerName: adapter.displayName,
|
|
227
|
-
status:
|
|
241
|
+
status: failure.status,
|
|
228
242
|
message: failure.message,
|
|
229
243
|
},
|
|
230
244
|
fingerprint: auth.fingerprint,
|
|
@@ -251,15 +265,19 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
251
265
|
} catch (error) {
|
|
252
266
|
if (isAbortError(error) || !sessionActive) throw error;
|
|
253
267
|
const message = errorMessage(error);
|
|
268
|
+
const status = error instanceof UsageUnsupportedError
|
|
269
|
+
? "unsupported"
|
|
270
|
+
: "query-failed";
|
|
254
271
|
failureBackoff.set(failureKey, {
|
|
255
272
|
until: Date.now() + FAILURE_BACKOFF_MS,
|
|
256
273
|
message,
|
|
274
|
+
status,
|
|
257
275
|
});
|
|
258
276
|
return {
|
|
259
277
|
state: {
|
|
260
278
|
providerId: adapter.id,
|
|
261
279
|
providerName: adapter.displayName,
|
|
262
|
-
status
|
|
280
|
+
status,
|
|
263
281
|
message,
|
|
264
282
|
},
|
|
265
283
|
fingerprint: auth.fingerprint,
|
|
@@ -273,6 +291,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
273
291
|
force: boolean,
|
|
274
292
|
signal: AbortSignal,
|
|
275
293
|
): Promise<QueryOutcome> {
|
|
294
|
+
if (isObservedProvider(model)) return observedClaudeOutcome();
|
|
276
295
|
const adapter = adapterForProvider(model?.provider);
|
|
277
296
|
if (!adapter) {
|
|
278
297
|
return {
|
|
@@ -289,6 +308,29 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
289
308
|
return queryAdapterState(ctx, adapter, force, signal);
|
|
290
309
|
}
|
|
291
310
|
|
|
311
|
+
/** Claude has no query to force; /usage and refreshes reread the last observation. */
|
|
312
|
+
function observedClaudeOutcome(): QueryOutcome {
|
|
313
|
+
const providerName = "Claude (Claude Code)";
|
|
314
|
+
if (!claudeObservation) {
|
|
315
|
+
return {
|
|
316
|
+
state: {
|
|
317
|
+
providerId: CLAUDE_BRIDGE_PROVIDER_ID,
|
|
318
|
+
providerName,
|
|
319
|
+
status: "pending",
|
|
320
|
+
message: "Claude Code has not reported usage in this session yet. It reports usage with its responses, which requires pi-claude-bridge 0.9.3 or later.",
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
state: {
|
|
326
|
+
providerId: CLAUDE_BRIDGE_PROVIDER_ID,
|
|
327
|
+
providerName,
|
|
328
|
+
status: "ready",
|
|
329
|
+
report: settleClaudeReport(claudeObservation, Date.now()),
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
292
334
|
async function outcomeStillCurrent(
|
|
293
335
|
ctx: ExtensionContext,
|
|
294
336
|
model: UsageModel | undefined,
|
|
@@ -337,7 +379,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
337
379
|
model: UsageModel | undefined,
|
|
338
380
|
force: boolean,
|
|
339
381
|
): Promise<void> {
|
|
340
|
-
|
|
382
|
+
const observed = isObservedProvider(model);
|
|
383
|
+
if ((!observed && !adapterForProvider(model?.provider)) || !model) {
|
|
341
384
|
clearStatus(ctx);
|
|
342
385
|
return;
|
|
343
386
|
}
|
|
@@ -353,7 +396,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
353
396
|
!controller.signal.aborted &&
|
|
354
397
|
modelIdentity(ctx.model) === modelIdentity(model);
|
|
355
398
|
try {
|
|
356
|
-
|
|
399
|
+
// An observed provider answers immediately; a placeholder would only flicker.
|
|
400
|
+
if (!observed) safeSetStatus(ctx, "usage …");
|
|
357
401
|
const outcome = await queryCurrentState(
|
|
358
402
|
ctx,
|
|
359
403
|
model,
|
|
@@ -616,6 +660,13 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
616
660
|
pi.on("agent_settled", (_event, ctx) => {
|
|
617
661
|
if (ctx.hasUI) startStatusRefresh(ctx, ctx.model, false);
|
|
618
662
|
});
|
|
663
|
+
pi.on("after_provider_response", (event, ctx) => {
|
|
664
|
+
if (!isObservedProvider(ctx.model)) return;
|
|
665
|
+
const report = normalizeClaudeRateLimitHeaders(event.headers, Date.now());
|
|
666
|
+
if (!report) return;
|
|
667
|
+
claudeObservation = report;
|
|
668
|
+
if (ctx.hasUI && sessionActive) startStatusRefresh(ctx, ctx.model, false);
|
|
669
|
+
});
|
|
619
670
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
620
671
|
sessionActive = false;
|
|
621
672
|
statusGeneration += 1;
|
|
@@ -629,3 +680,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
629
680
|
emitUnavailableUsage();
|
|
630
681
|
});
|
|
631
682
|
}
|
|
683
|
+
|
|
684
|
+
function isObservedProvider(model: UsageModel | undefined): boolean {
|
|
685
|
+
return model?.provider === CLAUDE_BRIDGE_PROVIDER_ID;
|
|
686
|
+
}
|