@narumitw/pi-usage 0.61.2 → 0.63.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 +34 -7
- package/dist/chunks/chunk-ENCC7IBP.ts +3002 -0
- package/dist/chunks/chunk-ENCC7IBP.ts.map +7 -0
- package/dist/chunks/openai-companion-auth-6VLPFVHF.ts +83 -0
- package/dist/chunks/openai-companion-auth-6VLPFVHF.ts.map +7 -0
- package/dist/chunks/openai-companion-usage-4NOBHGP7.ts +120 -0
- package/dist/chunks/openai-companion-usage-4NOBHGP7.ts.map +7 -0
- package/dist/index.ts +382 -3202
- package/dist/index.ts.map +4 -4
- package/docs/providers.md +32 -8
- package/package.json +4 -4
- package/src/format.ts +35 -1
- package/src/openai-companion-auth.ts +101 -0
- package/src/providers/openai-chatgpt.ts +21 -10
- package/src/providers/openai-companion-usage.ts +146 -0
- package/src/query.ts +5 -1
- package/src/types.ts +3 -0
- package/src/usage-settings-ui.ts +116 -114
- package/src/usage.ts +62 -4
package/docs/providers.md
CHANGED
|
@@ -25,10 +25,10 @@ The README contains the capability overview and shared security requirements.
|
|
|
25
25
|
### OpenAI native ChatGPT OAuth
|
|
26
26
|
|
|
27
27
|
- Provider ID: `openai`
|
|
28
|
-
-
|
|
29
|
-
-
|
|
30
|
-
-
|
|
31
|
-
-
|
|
28
|
+
- Source: verified native OAuth plus automatic same-account Codex companion OAuth; distinct shared plan and app windows
|
|
29
|
+
- Display: plan percentages and plan/app resets; app used/remaining percentages are hidden
|
|
30
|
+
- Missing-companion fallback: **Connected (native OAuth)**, same-account login guidance, and [ChatGPT usage settings](https://chatgpt.com/settings/usage)
|
|
31
|
+
- Fallback statusline: `chatgpt usage: web only`
|
|
32
32
|
|
|
33
33
|
Use `/login openai` in a Pi runtime that supports native Sign in with ChatGPT, then select an official `https://api.openai.com` model.
|
|
34
34
|
Authentication requires Pi's freshly resolved provider source to be `OAuth`, matching effective model and provider authorization, and a complete matching credential with `clientId` and the `chatgpt.tokens.use.direct` scope.
|
|
@@ -37,16 +37,40 @@ Stored OAuth alone and Pi's cached OAuth flag do not establish the active runtim
|
|
|
37
37
|
Runtime/API-key overrides, model-level Authorization replacements or removals, and custom/proxy origins cannot inherit native subscription status.
|
|
38
38
|
OpenAI API-key usage reporting remains unsupported.
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
Without companion credentials, the report verifies authentication, not the plan tier, allowance, remaining quota, or reset time.
|
|
41
|
+
With valid companion credentials, queries and automatic refreshes read both companion endpoints; otherwise no usage request is made.
|
|
42
42
|
The settings link is guidance, not an automatically opened browser or a promise that the browser is signed into Pi's account.
|
|
43
43
|
Native tokens are never sent to `/backend-api/wham`, and opaque native metadata is not decoded as a legacy Codex account ID.
|
|
44
|
-
Legacy Fast payload rewriting, pricing correction,
|
|
44
|
+
Legacy Fast payload rewriting, pricing correction, and earned reset redemption do not apply to native `openai`.
|
|
45
45
|
Existing `openai-codex` behavior below is unchanged.
|
|
46
46
|
|
|
47
47
|
The boundary is verified against Pi's [`openai-chatgpt.ts`](https://github.com/earendil-works/pi/blob/d86654abb8862e201933517d6f1fce9f88dd117f/packages/ai/src/auth/oauth/openai-chatgpt.ts) at `d86654abb8862e201933517d6f1fce9f88dd117f` and OpenAI's [models and inference](https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference), [token reference](https://developers.openai.com/siwc/token-sharing-open-source/token-reference), and [UI/UX guidelines](https://developers.openai.com/siwc/ui-ux-guidelines).
|
|
48
48
|
These contracts establish the public inference and authentication boundary, not a numerical usage API.
|
|
49
|
-
|
|
49
|
+
Deterministic verification uses synthetic credentials with Pi's real auth resolver. A user reported one plan weekly remaining percentage and reset time matching the web overview; browser login, app numerical agreement, and broader live coverage remain unverified.
|
|
50
|
+
|
|
51
|
+
#### Automatic companion quotas
|
|
52
|
+
|
|
53
|
+
Follow the [companion setup](../README.md#chatgpt-companion-usage): a same-account/workspace `/login openai-codex` is required.
|
|
54
|
+
The former opt-in setting and confirmation are removed; stored `openaiCompanionUsage` values, including `false`, no longer disable requests and are preserved without rewriting on reads.
|
|
55
|
+
Fresh companion OAuth must match a complete grant with its own account ID; custom origins, API-key overrides, conflicting grants, and effective Authorization overrides fail closed.
|
|
56
|
+
Only the companion bearer and matching `ChatGPT-Account-Id` reach these fixed, redirect-rejecting GET routes:
|
|
57
|
+
|
|
58
|
+
- `https://chatgpt.com/backend-api/wham/usage/chatpass/apps`
|
|
59
|
+
- `https://chatgpt.com/backend-api/wham/usage`
|
|
60
|
+
|
|
61
|
+
The app list must be complete and bounded to 128 registrations, with a readable nonempty string `id` on every entry, exactly one `id` equal to the native grant's `clientId`, and 1–32 valid windows on that matched entry.
|
|
62
|
+
Unknown envelope fields or pagination markers fail closed rather than assuming uniqueness on one page.
|
|
63
|
+
Only plan primary/secondary windows are used; Codex model-specific limits are not native app quotas.
|
|
64
|
+
Each window requires a finite 0–100 used percentage and positive whole-second duration; optional remaining percentages must agree within one percentage point, and reset timestamps must be valid nonnegative epoch seconds.
|
|
65
|
+
`allowed_usage_percent` is **App allowance**, a cap on shared plan usage, not remaining quota.
|
|
66
|
+
Plan/app windows and reset boundaries stay separate in reports and the statusline; Codex display preferences do not apply.
|
|
67
|
+
App used/remaining values are validated internally but not displayed; app reset/window information and the separately labeled allowance cap remain visible.
|
|
68
|
+
|
|
69
|
+
Missing-companion paths remain web-only without requests. Other companion failures invalidate numerical data and remain observable.
|
|
70
|
+
No native token, refresh token, app name, or account ID is rendered or persisted by this feature.
|
|
71
|
+
An exact registration match is not independent identity proof; users must choose the same account/workspace for both logins.
|
|
72
|
+
The endpoints remain an experimental, undocumented source despite automatic querying. One user-reported plan weekly comparison matched the web; app numerical agreement and broader live availability remain unverified.
|
|
73
|
+
Contract fixtures derive from [Specode's pinned implementation](https://github.com/specode/pi-subscription-usage/blob/1015f9f419dfef9ac27c9845ec2318394928fa38/src/providers/openai.ts) and [OpenAI's shared-plan/app-limit explanation](https://help.openai.com/en/articles/20001542-using-your-chatgpt-plan-in-other-apps-and-sites), not a public native quota API.
|
|
50
74
|
|
|
51
75
|
### OpenAI Codex
|
|
52
76
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-usage",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.63.0",
|
|
4
4
|
"description": "Pi extension that shows current-account usage and DeepSeek API balance for supported providers.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -57,9 +57,9 @@
|
|
|
57
57
|
"@earendil-works/pi-tui": "*"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
|
-
"@earendil-works/pi-ai": "1.0.
|
|
61
|
-
"@earendil-works/pi-coding-agent": "1.0.
|
|
62
|
-
"@earendil-works/pi-tui": "1.0.
|
|
60
|
+
"@earendil-works/pi-ai": "1.0.2",
|
|
61
|
+
"@earendil-works/pi-coding-agent": "1.0.2",
|
|
62
|
+
"@earendil-works/pi-tui": "1.0.2",
|
|
63
63
|
"@types/node": "26.6.4",
|
|
64
64
|
"esbuild": "0.28.2",
|
|
65
65
|
"typescript": "7.0.2"
|
package/src/format.ts
CHANGED
|
@@ -28,7 +28,8 @@ export function formatUsageReport(report: UsageReport, displayState: UsageDispla
|
|
|
28
28
|
if (report.accountLabel) lines.push(`Account: ${report.accountLabel}`);
|
|
29
29
|
lines.push(`Semantics: ${report.semantics.label}`, "");
|
|
30
30
|
|
|
31
|
-
if (report.
|
|
31
|
+
if (report.source === "openai-chatgpt-companion") formatOpenAICompanionReport(lines, report);
|
|
32
|
+
else if (report.providerId === "baseten") formatBasetenReport(lines, report);
|
|
32
33
|
else if (report.providerId === "openai-codex") formatCodexReport(lines, report);
|
|
33
34
|
else if (report.providerId === "deepseek") formatDeepSeekReport(lines, report);
|
|
34
35
|
else if (report.providerId === "fireworks") formatFireworksReport(lines, report);
|
|
@@ -60,6 +61,21 @@ export function formatUsageStatusline(
|
|
|
60
61
|
codexStatusPercentage: CodexStatusPercentage = "remaining",
|
|
61
62
|
): string | undefined {
|
|
62
63
|
if (report.providerId === "openai" && report.source === "openai-chatgpt-auth") return "chatgpt usage: web only";
|
|
64
|
+
if (report.source === "openai-chatgpt-companion") {
|
|
65
|
+
return `chatgpt ${["chatgpt-plan", "chatgpt-app"]
|
|
66
|
+
.map((group) => {
|
|
67
|
+
const windows = report.buckets
|
|
68
|
+
.filter((bucket) => bucket.groupId === group)
|
|
69
|
+
.map((bucket) => {
|
|
70
|
+
const reset = formatResetCountdown(bucket.resetsAt, now);
|
|
71
|
+
const window = reset ? `↻ ${reset}` : formatWindowLabel(bucket.windowMinutes, "weekly", true);
|
|
72
|
+
if (group === "chatgpt-app") return window;
|
|
73
|
+
return `${bucket.remaining === undefined ? "unavailable" : `${bucket.remaining.toFixed(0)}%`} ${window}`;
|
|
74
|
+
});
|
|
75
|
+
return `${group === "chatgpt-plan" ? "plan" : "app"} ${windows.join(" ")}`;
|
|
76
|
+
})
|
|
77
|
+
.join(" · ")}`;
|
|
78
|
+
}
|
|
63
79
|
if (report.providerId === "baseten") return formatBasetenStatusline(report);
|
|
64
80
|
if (report.providerId === "openai-codex") {
|
|
65
81
|
return formatCodexStatusline(report, model, now, showCodexResetCountdown, codexStatusPercentage);
|
|
@@ -522,6 +538,23 @@ function formatZaiReport(lines: string[], report: UsageReport): void {
|
|
|
522
538
|
}
|
|
523
539
|
}
|
|
524
540
|
|
|
541
|
+
function formatOpenAICompanionReport(lines: string[], report: UsageReport): void {
|
|
542
|
+
for (const group of ["chatgpt-plan", "chatgpt-app"]) {
|
|
543
|
+
lines.push(group === "chatgpt-plan" ? "Plan limits:" : "App limits:");
|
|
544
|
+
for (const bucket of report.buckets.filter((bucket) => bucket.groupId === group)) {
|
|
545
|
+
const value =
|
|
546
|
+
group === "chatgpt-app"
|
|
547
|
+
? bucket.resetsAt === undefined
|
|
548
|
+
? "Reset time unavailable"
|
|
549
|
+
: `resets ${formatReset(bucket.resetsAt)}`
|
|
550
|
+
: formatPercentBucket(bucket);
|
|
551
|
+
lines.push(`${formatWindowLabel(bucket.windowMinutes, "weekly", false).padEnd(VALUE_COLUMN)}${value}`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
for (const metric of report.metrics)
|
|
555
|
+
lines.push(`${`${metric.label}:`.padEnd(VALUE_COLUMN)}${formatMetricValue(metric.value, metric.unit)}`);
|
|
556
|
+
}
|
|
557
|
+
|
|
525
558
|
function formatGenericReport(lines: string[], report: UsageReport): void {
|
|
526
559
|
for (const bucket of report.buckets) {
|
|
527
560
|
lines.push(
|
|
@@ -668,6 +701,7 @@ function formatResetCountdown(resetsAt: number | undefined, now: number): string
|
|
|
668
701
|
|
|
669
702
|
function formatMetricValue(value: number | string, unit: UsageBucket["unit"] | undefined): string {
|
|
670
703
|
if (unit === "usd" && typeof value === "number") return formatUsd(value);
|
|
704
|
+
if (unit === "percent" && typeof value === "number") return `${value}%`;
|
|
671
705
|
return String(value);
|
|
672
706
|
}
|
|
673
707
|
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { fingerprintResolvedAuth } from "./core.js";
|
|
3
|
+
import { fallbackOAuthCredentialCandidates, type OAuthCredentialCandidateReader } from "./oauth-credential-source.js";
|
|
4
|
+
import { openAIAuthAccessToken } from "./providers/openai-chatgpt.js";
|
|
5
|
+
import { adapterForProvider, resolveUsageAuth } from "./query.js";
|
|
6
|
+
import type { ResolvedUsageAuth } from "./types.js";
|
|
7
|
+
|
|
8
|
+
// A native app registration is routing metadata, not cryptographic same-account proof.
|
|
9
|
+
// Keep this read-only boundary separate from legacy Codex querying and reset mutation policy.
|
|
10
|
+
export async function resolveOpenAICompanionAuth(
|
|
11
|
+
ctx: ExtensionContext,
|
|
12
|
+
native: ResolvedUsageAuth,
|
|
13
|
+
salt: Uint8Array,
|
|
14
|
+
credentialReader: (providerId: string) => unknown,
|
|
15
|
+
candidateReader?: OAuthCredentialCandidateReader,
|
|
16
|
+
): Promise<ResolvedUsageAuth> {
|
|
17
|
+
const unavailable = () => ({
|
|
18
|
+
...native,
|
|
19
|
+
fingerprint: fingerprintResolvedAuth(
|
|
20
|
+
{ apiKey: JSON.stringify([native.fingerprint, native.openaiClientId, null]) },
|
|
21
|
+
salt,
|
|
22
|
+
),
|
|
23
|
+
});
|
|
24
|
+
if (candidateReader?.waitUntilReady && !(await candidateReader.waitUntilReady(ctx, "openai-codex"))) {
|
|
25
|
+
throw new Error("Companion Codex OAuth credential readiness failed closed.");
|
|
26
|
+
}
|
|
27
|
+
const adapter = adapterForProvider("openai-codex");
|
|
28
|
+
if (!adapter) throw new Error("Companion Codex usage support is unavailable.");
|
|
29
|
+
const companion = await resolveUsageAuth(ctx, adapter, salt, credentialReader);
|
|
30
|
+
if (!companion) return unavailable();
|
|
31
|
+
if (companion.source !== "OAuth")
|
|
32
|
+
throw new Error("Companion usage requires /login openai-codex OAuth, not an API key.");
|
|
33
|
+
// Legacy querying is more permissive. Enforce explicit Authorization removals and duplicates
|
|
34
|
+
// against preserved fresh provider auth before using its normalized request headers.
|
|
35
|
+
const access = openAIAuthAccessToken(companion.auth);
|
|
36
|
+
if (ctx.model?.provider === "openai-codex") {
|
|
37
|
+
const selected = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
|
|
38
|
+
if (
|
|
39
|
+
!selected.ok ||
|
|
40
|
+
(selected.baseUrl && new URL(selected.baseUrl).origin !== "https://chatgpt.com") ||
|
|
41
|
+
openAIAuthAccessToken(selected) !== access
|
|
42
|
+
) {
|
|
43
|
+
throw new Error("Selected Codex model authorization does not match the companion OAuth credential.");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!access || access !== openAIAuthAccessToken(companion)) {
|
|
47
|
+
throw new Error("Companion Codex runtime authorization did not match its OAuth credential.");
|
|
48
|
+
}
|
|
49
|
+
const accountId = codexAccountId(access);
|
|
50
|
+
if (!accountId) throw new Error("Companion Codex token did not contain a valid account ID.");
|
|
51
|
+
const offered = candidateReader
|
|
52
|
+
? await candidateReader(ctx, "openai-codex")
|
|
53
|
+
: fallbackOAuthCredentialCandidates("openai-codex", credentialReader);
|
|
54
|
+
if (!offered.ok) throw new Error("Companion Codex OAuth credential discovery failed closed.");
|
|
55
|
+
const matches = new Set<string>();
|
|
56
|
+
for (const candidate of offered.candidates) {
|
|
57
|
+
const credential = object(candidate);
|
|
58
|
+
if (credential?.type !== "oauth" || credential.access !== access) continue;
|
|
59
|
+
if (
|
|
60
|
+
credential.accountId !== accountId ||
|
|
61
|
+
typeof credential.refresh !== "string" ||
|
|
62
|
+
!credential.refresh ||
|
|
63
|
+
typeof credential.expires !== "number" ||
|
|
64
|
+
!Number.isFinite(credential.expires)
|
|
65
|
+
) {
|
|
66
|
+
throw new Error("The matching companion Codex OAuth credential was incomplete or had a different account ID.");
|
|
67
|
+
}
|
|
68
|
+
matches.add(credential.refresh);
|
|
69
|
+
}
|
|
70
|
+
if (matches.size !== 1) throw new Error("Companion Codex OAuth must uniquely match the fresh runtime credential.");
|
|
71
|
+
const headers = { Authorization: `Bearer ${access}`, "ChatGPT-Account-Id": accountId };
|
|
72
|
+
return {
|
|
73
|
+
...native,
|
|
74
|
+
openaiCompanion: { headers },
|
|
75
|
+
fingerprint: fingerprintResolvedAuth(
|
|
76
|
+
{ apiKey: JSON.stringify([native.fingerprint, native.openaiClientId, companion.fingerprint, headers]) },
|
|
77
|
+
salt,
|
|
78
|
+
),
|
|
79
|
+
secrets: [
|
|
80
|
+
...new Set([...native.secrets, ...companion.secrets, ...matches, access, accountId, headers.Authorization]),
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function codexAccountId(access: string): string | undefined {
|
|
86
|
+
try {
|
|
87
|
+
const parts = access.split(".");
|
|
88
|
+
if (parts.length !== 3 || !parts[1]) return undefined;
|
|
89
|
+
const payload = object(JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")));
|
|
90
|
+
const account = object(payload?.["https://api.openai.com/auth"])?.chatgpt_account_id;
|
|
91
|
+
return typeof account === "string" && account.length > 0 && account.length <= 512 && /^[\x21-\x7e]+$/u.test(account)
|
|
92
|
+
? account
|
|
93
|
+
: undefined;
|
|
94
|
+
} catch {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function object(value: unknown): Record<string, unknown> | undefined {
|
|
100
|
+
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
101
|
+
}
|
|
@@ -24,7 +24,13 @@ export const OPENAI_CHATGPT_ADAPTER: UsageProviderAdapter = {
|
|
|
24
24
|
id: "openai",
|
|
25
25
|
displayName: "OpenAI",
|
|
26
26
|
semantics: { kind: "consumer-subscription", label: "ChatGPT plan authentication status" },
|
|
27
|
-
|
|
27
|
+
invalidateCacheOnFailure: true,
|
|
28
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
29
|
+
if (auth.openaiCompanion) {
|
|
30
|
+
const { queryOpenAICompanionUsage } = await import("./openai-companion-usage.js");
|
|
31
|
+
signal.throwIfAborted();
|
|
32
|
+
return queryOpenAICompanionUsage(auth, signal, timeoutMs, guard);
|
|
33
|
+
}
|
|
28
34
|
if (!guard) throw new Error("ChatGPT plan status requires runtime-auth revalidation.");
|
|
29
35
|
signal.throwIfAborted();
|
|
30
36
|
await guard();
|
|
@@ -38,8 +44,9 @@ export const OPENAI_CHATGPT_ADAPTER: UsageProviderAdapter = {
|
|
|
38
44
|
buckets: [],
|
|
39
45
|
metrics: [{ id: "plan-auth", label: "ChatGPT plan authentication", value: "Connected (native OAuth)" }],
|
|
40
46
|
notes: [
|
|
41
|
-
"Numerical usage
|
|
47
|
+
"Numerical usage requires a companion /login openai-codex with the same ChatGPT account/workspace; native inference stays on openai.",
|
|
42
48
|
`Manage usage: ${CHATGPT_USAGE_SETTINGS_URL}`,
|
|
49
|
+
"Companion usage uses undocumented ChatGPT endpoints; registration matching is not independent identity proof.",
|
|
43
50
|
"Fast mode and earned reset redemption remain legacy openai-codex features.",
|
|
44
51
|
],
|
|
45
52
|
};
|
|
@@ -56,11 +63,11 @@ export function resolveOpenAIChatGPTAuth(
|
|
|
56
63
|
// isUsingOAuth() is a cached snapshot; source alone is also insufficient when a model header
|
|
57
64
|
// overrides Authorization. Match both freshly resolved credentials and the exact native grant.
|
|
58
65
|
if (source !== "OAuth") throw new UnsupportedOpenAIUsageAuthError();
|
|
59
|
-
const access =
|
|
60
|
-
if (!access || access !==
|
|
66
|
+
const access = openAIAuthAccessToken(auth);
|
|
67
|
+
if (!access || access !== openAIAuthAccessToken(providerAuth)) {
|
|
61
68
|
throw new Error("The active OpenAI model authorization does not match its resolved OAuth credential.");
|
|
62
69
|
}
|
|
63
|
-
const matches = new Map<string, string>();
|
|
70
|
+
const matches = new Map<string, { refresh: string; clientId: string }>();
|
|
64
71
|
for (const candidate of candidates) {
|
|
65
72
|
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) continue;
|
|
66
73
|
const credential = candidate as Record<string, unknown>;
|
|
@@ -80,24 +87,28 @@ export function resolveOpenAIChatGPTAuth(
|
|
|
80
87
|
"The matching OpenAI OAuth credential is not a complete native ChatGPT grant; reconnect with /login openai.",
|
|
81
88
|
);
|
|
82
89
|
}
|
|
83
|
-
matches.set(JSON.stringify([credential.clientId, credential.refresh]),
|
|
90
|
+
matches.set(JSON.stringify([credential.clientId, credential.refresh]), {
|
|
91
|
+
refresh: credential.refresh,
|
|
92
|
+
clientId: credential.clientId,
|
|
93
|
+
});
|
|
84
94
|
}
|
|
85
95
|
if (matches.size > 1)
|
|
86
96
|
throw new Error("Conflicting native ChatGPT credentials match the active OpenAI runtime account.");
|
|
87
|
-
const
|
|
88
|
-
if (!
|
|
97
|
+
const match = matches.values().next().value;
|
|
98
|
+
if (!match)
|
|
89
99
|
throw new Error("The active OpenAI runtime account does not match an available native ChatGPT OAuth credential.");
|
|
90
100
|
const authorization = `Bearer ${access}`;
|
|
91
101
|
return {
|
|
102
|
+
openaiClientId: match.clientId,
|
|
92
103
|
apiKey: access,
|
|
93
104
|
headers: { Authorization: authorization },
|
|
94
105
|
fingerprint: "",
|
|
95
|
-
secrets: [access, refresh, authorization],
|
|
106
|
+
secrets: [access, match.refresh, authorization, match.clientId],
|
|
96
107
|
model,
|
|
97
108
|
};
|
|
98
109
|
}
|
|
99
110
|
|
|
100
|
-
function
|
|
111
|
+
export function openAIAuthAccessToken(auth: RequestAuth | undefined): string | undefined {
|
|
101
112
|
if (!auth) return undefined;
|
|
102
113
|
const authorization = Object.entries(auth.headers ?? {}).filter(([name]) => name.toLowerCase() === "authorization");
|
|
103
114
|
if (authorization.length > 1) throw new Error("OpenAI runtime authorization headers are ambiguous.");
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { fetchProviderJson } from "../query.js";
|
|
2
|
+
import type { ResolvedUsageAuth, UsageBucket, UsageReport, UsageRequestGuard } from "../types.js";
|
|
3
|
+
import { CHATGPT_USAGE_SETTINGS_URL } from "./openai-chatgpt.js";
|
|
4
|
+
|
|
5
|
+
const USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
6
|
+
const MAX_APPS = 128;
|
|
7
|
+
const MAX_WINDOWS = 32;
|
|
8
|
+
|
|
9
|
+
// Evidence: pinned Specode openai.ts at 1015f9f419dfef9ac27c9845ec2318394928fa38
|
|
10
|
+
// and OpenAI's Help Center article 20001542. Backend shapes remain undocumented.
|
|
11
|
+
// Accept only a complete list; unknown list envelope fields fail closed, including pagination.
|
|
12
|
+
export function matchingOpenAIAppBuckets(
|
|
13
|
+
payload: unknown,
|
|
14
|
+
clientId: string,
|
|
15
|
+
): { buckets: UsageBucket[]; allowance?: number } {
|
|
16
|
+
const root = object(payload);
|
|
17
|
+
if (
|
|
18
|
+
!root ||
|
|
19
|
+
!Array.isArray(root.items) ||
|
|
20
|
+
root.items.length > MAX_APPS ||
|
|
21
|
+
Object.keys(root).some((key) => !["items", "has_more", "next_cursor"].includes(key)) ||
|
|
22
|
+
(root.has_more !== undefined && root.has_more !== false) ||
|
|
23
|
+
(root.next_cursor !== undefined && root.next_cursor !== null && root.next_cursor !== "")
|
|
24
|
+
) {
|
|
25
|
+
throw new Error("ChatGPT app usage requires a complete, bounded registration list; pagination is unsupported.");
|
|
26
|
+
}
|
|
27
|
+
const apps = root.items.map(object);
|
|
28
|
+
if (apps.some((app) => !app || typeof app.id !== "string" || !app.id.trim())) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
"ChatGPT app usage returned an unreadable registration identity; uniqueness cannot be established.",
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const matches = apps.filter((app) => app?.id === clientId);
|
|
34
|
+
if (!clientId || matches.length !== 1) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
"The native registration was not uniquely found in the companion Codex account; use the same ChatGPT account/workspace for both logins.",
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
const app = matches[0];
|
|
40
|
+
if (!Array.isArray(app?.windows) || app.windows.length === 0 || app.windows.length > MAX_WINDOWS) {
|
|
41
|
+
throw new Error("ChatGPT app usage returned no bounded, displayable windows.");
|
|
42
|
+
}
|
|
43
|
+
const allowance = app.allowed_usage_percent;
|
|
44
|
+
if (allowance !== undefined && !percent(allowance)) throw new Error("ChatGPT app allowance was invalid.");
|
|
45
|
+
return {
|
|
46
|
+
buckets: app.windows.map((window, index) => normalizeWindow(window, `app:${index}`, "chatgpt-app", "App limits")),
|
|
47
|
+
...(allowance === undefined ? {} : { allowance: allowance as number }),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function queryOpenAICompanionUsage(
|
|
52
|
+
auth: ResolvedUsageAuth,
|
|
53
|
+
signal: AbortSignal,
|
|
54
|
+
timeoutMs: number,
|
|
55
|
+
guard?: UsageRequestGuard,
|
|
56
|
+
): Promise<UsageReport> {
|
|
57
|
+
if (!guard) throw new Error("Companion ChatGPT usage requires request-boundary revalidation.");
|
|
58
|
+
if (!auth.openaiCompanion || !auth.openaiClientId)
|
|
59
|
+
throw new Error("Companion ChatGPT usage authentication was incomplete.");
|
|
60
|
+
const startedAt = Date.now();
|
|
61
|
+
// Never pass native apiKey/auth/env to transport: the only request credential is the companion.
|
|
62
|
+
const backend: ResolvedUsageAuth = {
|
|
63
|
+
headers: { ...auth.openaiCompanion.headers },
|
|
64
|
+
fingerprint: auth.fingerprint,
|
|
65
|
+
secrets: auth.secrets,
|
|
66
|
+
model: auth.model,
|
|
67
|
+
};
|
|
68
|
+
const read = async (url: string, description: string) => {
|
|
69
|
+
signal.throwIfAborted();
|
|
70
|
+
await guard();
|
|
71
|
+
signal.throwIfAborted();
|
|
72
|
+
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
73
|
+
if (remaining <= 0) throw new Error("Timed out while fetching companion ChatGPT usage.");
|
|
74
|
+
const payload = await fetchProviderJson(url, backend, signal, remaining, description, { redirect: "error" });
|
|
75
|
+
await guard();
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
return payload;
|
|
78
|
+
};
|
|
79
|
+
const appPayload = await read(`${USAGE_URL}/chatpass/apps`, "ChatGPT companion app usage endpoint");
|
|
80
|
+
const app = matchingOpenAIAppBuckets(appPayload, auth.openaiClientId);
|
|
81
|
+
// Match and validate the app before reading plan data; never substitute Codex-only quotas.
|
|
82
|
+
const planPayload = await read(USAGE_URL, "ChatGPT companion plan usage endpoint");
|
|
83
|
+
const rateLimit = object(planPayload.rate_limit);
|
|
84
|
+
const planBuckets: UsageBucket[] = [];
|
|
85
|
+
for (const position of ["primary", "secondary"] as const) {
|
|
86
|
+
const window = rateLimit?.[`${position}_window`];
|
|
87
|
+
if (window !== undefined && window !== null)
|
|
88
|
+
planBuckets.push(normalizeWindow(window, `plan:${position}`, "chatgpt-plan", "Plan limits"));
|
|
89
|
+
}
|
|
90
|
+
if (planBuckets.length === 0) throw new Error("ChatGPT plan usage returned no displayable windows.");
|
|
91
|
+
return {
|
|
92
|
+
providerId: "openai",
|
|
93
|
+
providerName: "OpenAI",
|
|
94
|
+
capturedAt: Date.now(),
|
|
95
|
+
source: "openai-chatgpt-companion",
|
|
96
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan and app limits (experimental companion source)" },
|
|
97
|
+
buckets: [...planBuckets, ...app.buckets],
|
|
98
|
+
metrics:
|
|
99
|
+
app.allowance === undefined
|
|
100
|
+
? []
|
|
101
|
+
: [{ id: "app-allowance", label: "App allowance", value: app.allowance, unit: "percent" }],
|
|
102
|
+
notes: [
|
|
103
|
+
"Source: companion Codex OAuth; registration matching is not independent proof of the same user/workspace.",
|
|
104
|
+
"App allowance caps shared plan usage; it is not remaining or reserved quota.",
|
|
105
|
+
`Manage usage: ${CHATGPT_USAGE_SETTINGS_URL}`,
|
|
106
|
+
],
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function normalizeWindow(raw: unknown, id: string, groupId: string, groupLabel: string): UsageBucket {
|
|
111
|
+
const window = object(raw);
|
|
112
|
+
const used = window?.used_percent;
|
|
113
|
+
const remaining = window?.remaining_percent;
|
|
114
|
+
const seconds = window?.limit_window_seconds;
|
|
115
|
+
const resetsAt = window?.reset_at;
|
|
116
|
+
if (
|
|
117
|
+
!percent(used) ||
|
|
118
|
+
(remaining !== undefined && (!percent(remaining) || Math.abs(used + remaining - 100) > 1)) ||
|
|
119
|
+
typeof seconds !== "number" ||
|
|
120
|
+
!Number.isSafeInteger(seconds) ||
|
|
121
|
+
seconds <= 0 ||
|
|
122
|
+
(resetsAt !== undefined &&
|
|
123
|
+
(typeof resetsAt !== "number" || !Number.isSafeInteger(resetsAt) || resetsAt < 0 || resetsAt > 8_640_000_000_000))
|
|
124
|
+
) {
|
|
125
|
+
throw new Error("ChatGPT usage returned an invalid or contradictory window.");
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
id,
|
|
129
|
+
label: "Subscription limit",
|
|
130
|
+
groupId,
|
|
131
|
+
groupLabel,
|
|
132
|
+
used,
|
|
133
|
+
remaining: remaining === undefined ? 100 - used : (remaining as number),
|
|
134
|
+
limit: 100,
|
|
135
|
+
unit: "percent",
|
|
136
|
+
windowMinutes: Math.ceil(seconds / 60),
|
|
137
|
+
...(resetsAt === undefined ? {} : { resetsAt: resetsAt as number }),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function percent(value: unknown): value is number {
|
|
142
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100;
|
|
143
|
+
}
|
|
144
|
+
function object(value: unknown): Record<string, unknown> | undefined {
|
|
145
|
+
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
146
|
+
}
|
package/src/query.ts
CHANGED
|
@@ -340,6 +340,8 @@ export async function resolveUsageAuth(
|
|
|
340
340
|
salt: Uint8Array = AUTH_FINGERPRINT_SALT,
|
|
341
341
|
credentialReader: StoredCredentialReader = readStoredCredential,
|
|
342
342
|
candidateReader?: OAuthCredentialCandidateReader,
|
|
343
|
+
/** @deprecated Companion resolution is automatic; this argument is ignored. */
|
|
344
|
+
_openaiCompanionUsage?: boolean,
|
|
343
345
|
): Promise<ResolvedUsageAuth | undefined> {
|
|
344
346
|
if (ctx.model?.provider === adapter.id && !hasOfficialOrigin(ctx.model, adapter.id)) {
|
|
345
347
|
throw new Error(
|
|
@@ -437,9 +439,11 @@ export async function resolveUsageAuth(
|
|
|
437
439
|
? await candidateReader(ctx, adapter.id)
|
|
438
440
|
: fallbackOAuthCredentialCandidates(adapter.id, credentialReader);
|
|
439
441
|
if (!offered.ok) throw new Error("OpenAI OAuth credential discovery failed closed.");
|
|
440
|
-
|
|
442
|
+
const native = finalize(
|
|
441
443
|
resolveOpenAIChatGPTAuth(auth, providerResult.auth, providerResult.source, model, offered.candidates),
|
|
442
444
|
);
|
|
445
|
+
const { resolveOpenAICompanionAuth } = await import("./openai-companion-auth.js");
|
|
446
|
+
return resolveOpenAICompanionAuth(ctx, native, salt, credentialReader, candidateReader);
|
|
443
447
|
}
|
|
444
448
|
if (adapter.id === "github-copilot") {
|
|
445
449
|
const offered = candidateReader
|
package/src/types.ts
CHANGED
|
@@ -48,6 +48,9 @@ export interface UsageReport {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
export interface ResolvedUsageAuth {
|
|
51
|
+
/** Native registration metadata stays local; only companion headers reach ChatGPT. */
|
|
52
|
+
openaiClientId?: string;
|
|
53
|
+
openaiCompanion?: { headers: Record<string, string> };
|
|
51
54
|
apiKey?: string;
|
|
52
55
|
headers: Record<string, string>;
|
|
53
56
|
fingerprint: string;
|