@fenlyin/pi-subscription-usage 0.0.0-stage → 2.0.1
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/LICENSE +24 -0
- package/README.md +156 -3
- package/README.zh-CN.md +156 -0
- package/THIRD_PARTY_NOTICES.md +28 -0
- package/index.ts +1 -0
- package/package.json +52 -6
- package/src/codex-reset-core.ts +249 -0
- package/src/codex-resets.ts +145 -0
- package/src/config-core.ts +43 -0
- package/src/config.ts +48 -0
- package/src/core.ts +182 -0
- package/src/display.ts +55 -0
- package/src/format.ts +225 -0
- package/src/providers/claude-bridge.ts +118 -0
- package/src/providers/codex-constants.ts +2 -0
- package/src/providers/codex.ts +227 -0
- package/src/providers/grok.ts +358 -0
- package/src/providers/kimi.ts +155 -0
- package/src/providers/openai.ts +145 -0
- package/src/providers/opencode-go.ts +88 -0
- package/src/query.ts +511 -0
- package/src/status.ts +255 -0
- package/src/types.ts +90 -0
- package/src/usage.ts +679 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// Adapted from @sumhou/pi-kimi-usage@1.0.1 (MIT).
|
|
2
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
3
|
+
import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
|
|
4
|
+
|
|
5
|
+
const MAX_PLAN_LEVEL_LENGTH = 80;
|
|
6
|
+
const KIMI_PLAN_NAMES: Readonly<Record<string, string>> = {
|
|
7
|
+
LEVEL_FREE: "Free",
|
|
8
|
+
LEVEL_BASIC: "Adagio",
|
|
9
|
+
LEVEL_STANDARD: "Moderato",
|
|
10
|
+
LEVEL_INTERMEDIATE: "Allegretto",
|
|
11
|
+
LEVEL_ADVANCED: "Allegro",
|
|
12
|
+
LEVEL_PREMIUM: "Vivace",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export function normalizeKimiUsage(
|
|
16
|
+
payload: unknown,
|
|
17
|
+
capturedAt: number,
|
|
18
|
+
): UsageReport {
|
|
19
|
+
const root = asObject(payload);
|
|
20
|
+
if (!root) throw new Error("Kimi usage response was not an object.");
|
|
21
|
+
const buckets: UsageBucket[] = [];
|
|
22
|
+
const weekly = parseQuota(root.usage);
|
|
23
|
+
if (weekly) {
|
|
24
|
+
buckets.push({
|
|
25
|
+
id: "weekly",
|
|
26
|
+
label: "Weekly window",
|
|
27
|
+
...weekly,
|
|
28
|
+
unit: "count",
|
|
29
|
+
windowMinutes: 10_080,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const limits = Array.isArray(root.limits) ? root.limits : [];
|
|
33
|
+
for (const [index, item] of limits.entries()) {
|
|
34
|
+
const entry = asObject(item);
|
|
35
|
+
const detail = parseQuota(entry?.detail ?? entry);
|
|
36
|
+
if (!detail) continue;
|
|
37
|
+
const window = asObject(entry?.window);
|
|
38
|
+
const windowInfo = parseWindow(window);
|
|
39
|
+
buckets.push({
|
|
40
|
+
id: `rolling-${index}`,
|
|
41
|
+
label: `${windowInfo.label} window`,
|
|
42
|
+
...detail,
|
|
43
|
+
unit: "count",
|
|
44
|
+
...(windowInfo.minutes === undefined
|
|
45
|
+
? {}
|
|
46
|
+
: { windowMinutes: windowInfo.minutes }),
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (buckets.length === 0) {
|
|
50
|
+
throw new Error("Kimi usage endpoint returned no displayable quota data.");
|
|
51
|
+
}
|
|
52
|
+
const metrics: UsageMetric[] = [];
|
|
53
|
+
const plan = kimiPlanName(root);
|
|
54
|
+
if (plan) metrics.push({ id: "plan", label: "Plan", value: plan });
|
|
55
|
+
return {
|
|
56
|
+
providerId: "kimi-coding",
|
|
57
|
+
providerName: "Kimi Coding",
|
|
58
|
+
capturedAt,
|
|
59
|
+
source: "kimi-coding-usage",
|
|
60
|
+
semantics: { kind: "consumer-subscription", label: "Kimi Coding plan usage" },
|
|
61
|
+
buckets,
|
|
62
|
+
metrics,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function kimiPlanName(root: Record<string, unknown>): string | undefined {
|
|
67
|
+
const membership = asObject(asObject(root.user)?.membership);
|
|
68
|
+
if (typeof membership?.level !== "string") return undefined;
|
|
69
|
+
const level = sanitizeDisplayText(membership.level, MAX_PLAN_LEVEL_LENGTH);
|
|
70
|
+
if (!level) return undefined;
|
|
71
|
+
return Object.hasOwn(KIMI_PLAN_NAMES, level) ? KIMI_PLAN_NAMES[level] : level;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseQuota(
|
|
75
|
+
value: unknown,
|
|
76
|
+
): Omit<UsageBucket, "id" | "label" | "unit"> | undefined {
|
|
77
|
+
const record = asObject(value);
|
|
78
|
+
if (!record) return undefined;
|
|
79
|
+
const limit = asFiniteNumber(record.limit);
|
|
80
|
+
let used = asFiniteNumber(record.used);
|
|
81
|
+
let remaining = asFiniteNumber(record.remaining);
|
|
82
|
+
if (limit === undefined || limit <= 0) return undefined;
|
|
83
|
+
// Missing fields can be derived; present-but-invalid data must not become zero.
|
|
84
|
+
if (
|
|
85
|
+
(record.used !== undefined && used === undefined) ||
|
|
86
|
+
(record.remaining !== undefined && remaining === undefined)
|
|
87
|
+
)
|
|
88
|
+
return undefined;
|
|
89
|
+
// Observed: used=limit=100 with remaining omitted. The cause is undocumented.
|
|
90
|
+
if (used === undefined && remaining !== undefined) {
|
|
91
|
+
used = Math.max(0, limit - remaining);
|
|
92
|
+
}
|
|
93
|
+
if (remaining === undefined && used !== undefined) {
|
|
94
|
+
remaining = Math.max(0, limit - used);
|
|
95
|
+
}
|
|
96
|
+
if (
|
|
97
|
+
used === undefined ||
|
|
98
|
+
remaining === undefined ||
|
|
99
|
+
used < 0 ||
|
|
100
|
+
remaining < 0
|
|
101
|
+
) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
const resetsAt = parseDate(record.resetTime);
|
|
105
|
+
return {
|
|
106
|
+
used,
|
|
107
|
+
remaining,
|
|
108
|
+
limit,
|
|
109
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function parseWindow(value: Record<string, unknown> | undefined): {
|
|
114
|
+
label: string;
|
|
115
|
+
minutes?: number;
|
|
116
|
+
} {
|
|
117
|
+
const duration = asFiniteNumber(value?.duration);
|
|
118
|
+
const unit = value?.timeUnit;
|
|
119
|
+
if (duration === undefined || duration <= 0 || typeof unit !== "string") {
|
|
120
|
+
return { label: "Rolling" };
|
|
121
|
+
}
|
|
122
|
+
if (unit === "TIME_UNIT_SECOND") {
|
|
123
|
+
return { label: `${duration}s`, minutes: duration / 60 };
|
|
124
|
+
}
|
|
125
|
+
if (unit === "TIME_UNIT_MINUTE") {
|
|
126
|
+
return {
|
|
127
|
+
label: duration % 60 === 0 ? `${duration / 60}h` : `${duration}m`,
|
|
128
|
+
minutes: duration,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (unit === "TIME_UNIT_HOUR")
|
|
132
|
+
return { label: `${duration}h`, minutes: duration * 60 };
|
|
133
|
+
if (unit === "TIME_UNIT_DAY")
|
|
134
|
+
return { label: `${duration}d`, minutes: duration * 1_440 };
|
|
135
|
+
return { label: "Rolling" };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
139
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
140
|
+
? (value as Record<string, unknown>)
|
|
141
|
+
: undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function asFiniteNumber(value: unknown): number | undefined {
|
|
145
|
+
if (typeof value !== "number" && typeof value !== "string") return undefined;
|
|
146
|
+
if (typeof value === "string" && !value.trim()) return undefined;
|
|
147
|
+
const parsed = Number(value);
|
|
148
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function parseDate(value: unknown): number | undefined {
|
|
152
|
+
if (typeof value !== "string" || !value.trim()) return undefined;
|
|
153
|
+
const parsed = Date.parse(value);
|
|
154
|
+
return Number.isNaN(parsed) ? undefined : Math.floor(parsed / 1000);
|
|
155
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
2
|
+
import type { UsageBucket, UsageReport } from "../types.ts";
|
|
3
|
+
import { normalizeCodexUsage } from "./codex.ts";
|
|
4
|
+
|
|
5
|
+
export const OPENAI_PROVIDER_ID = "openai";
|
|
6
|
+
|
|
7
|
+
/** Decode only routing metadata from Pi's active OAuth credential, not identity claims. */
|
|
8
|
+
export function openaiClientIdFromAuthorization(authorization: string): string {
|
|
9
|
+
try {
|
|
10
|
+
const token = /^Bearer\s+(\S+)$/iu.exec(authorization)?.[1];
|
|
11
|
+
const parts = token?.split(".");
|
|
12
|
+
if (parts?.length !== 3) throw new Error();
|
|
13
|
+
const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
14
|
+
if (
|
|
15
|
+
claims.iss !== "https://auth.openai.com" ||
|
|
16
|
+
claims.aud !== "https://api.openai.com/v1" ||
|
|
17
|
+
typeof claims.scope !== "string" ||
|
|
18
|
+
!claims.scope.split(/\s+/u).includes("chatgpt.tokens.use.direct") ||
|
|
19
|
+
typeof claims.client_id !== "string" ||
|
|
20
|
+
!/^oaiapp_[a-zA-Z0-9_-]+$/u.test(claims.client_id)
|
|
21
|
+
) throw new Error();
|
|
22
|
+
return claims.client_id;
|
|
23
|
+
} catch {
|
|
24
|
+
throw new Error("OpenAI usage requires a Sign in with ChatGPT OAuth credential with an application ID.");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The ChatGPT usage page reads app-scoped subscription windows here, separately
|
|
30
|
+
* from Codex's rate_limit. Match the active registration, never an app name or
|
|
31
|
+
* the first result: a different Codex account must not supply another quota.
|
|
32
|
+
*/
|
|
33
|
+
export function normalizeOpenAIUsage(
|
|
34
|
+
payload: unknown,
|
|
35
|
+
clientId: string,
|
|
36
|
+
capturedAt: number,
|
|
37
|
+
): UsageReport {
|
|
38
|
+
const root = asObject(payload);
|
|
39
|
+
const matches = Array.isArray(root?.items)
|
|
40
|
+
? root.items.map(asObject).filter((item) => item?.id === clientId)
|
|
41
|
+
: [];
|
|
42
|
+
if (!clientId || matches.length !== 1) {
|
|
43
|
+
throw new Error("The active OpenAI application was not uniquely found in this Codex account. Sign in to OpenAI and OpenAI Codex with the same ChatGPT account/workspace.");
|
|
44
|
+
}
|
|
45
|
+
const app = matches[0]!;
|
|
46
|
+
const windows = Array.isArray(app.windows) ? app.windows : [];
|
|
47
|
+
const buckets: UsageBucket[] = windows.map((raw, index) => {
|
|
48
|
+
const window = asObject(raw);
|
|
49
|
+
const used = number(window?.used_percent);
|
|
50
|
+
const remaining = number(window?.remaining_percent);
|
|
51
|
+
const seconds = number(window?.limit_window_seconds);
|
|
52
|
+
const reset = number(window?.reset_at);
|
|
53
|
+
if (
|
|
54
|
+
used === undefined || used < 0 || used > 100 ||
|
|
55
|
+
seconds === undefined || seconds <= 0 ||
|
|
56
|
+
(remaining !== undefined && (remaining < 0 || remaining > 100))
|
|
57
|
+
) throw new Error("OpenAI subscription returned an invalid usage window.");
|
|
58
|
+
return {
|
|
59
|
+
id: `chatpass:${index}`,
|
|
60
|
+
label: "App subscription limit",
|
|
61
|
+
used,
|
|
62
|
+
remaining: remaining ?? 100 - used,
|
|
63
|
+
limit: 100,
|
|
64
|
+
unit: "percent",
|
|
65
|
+
windowMinutes: Math.ceil(seconds / 60),
|
|
66
|
+
...(reset !== undefined && reset > 0 ? { resetsAt: reset } : {}),
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
if (buckets.length === 0) {
|
|
70
|
+
throw new Error("OpenAI subscription returned no displayable app usage windows.");
|
|
71
|
+
}
|
|
72
|
+
const name = typeof app.name === "string" ? sanitizeDisplayText(app.name, 80) : "";
|
|
73
|
+
const allowance = number(app.allowed_usage_percent);
|
|
74
|
+
return {
|
|
75
|
+
providerId: OPENAI_PROVIDER_ID,
|
|
76
|
+
providerName: "OpenAI (ChatGPT subscription)",
|
|
77
|
+
capturedAt,
|
|
78
|
+
source: "openai-chatpass-pi-auth",
|
|
79
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT app subscription limits" },
|
|
80
|
+
buckets,
|
|
81
|
+
metrics: [
|
|
82
|
+
{ id: "source", label: "Source", value: "Matched app in Pi Codex account" },
|
|
83
|
+
...(name ? [{ id: "app", label: "App", value: name }] : []),
|
|
84
|
+
...(allowance !== undefined && allowance >= 0 && allowance <= 100
|
|
85
|
+
? [{ id: "allowance", label: "Plan Allowance", value: `${allowance}%` }]
|
|
86
|
+
: []),
|
|
87
|
+
],
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The website's Plan limits and app-specific caps are separate quota domains. */
|
|
92
|
+
export function normalizeOpenAIPlanUsage(
|
|
93
|
+
appPayload: unknown,
|
|
94
|
+
planPayload: unknown,
|
|
95
|
+
clientId: string,
|
|
96
|
+
capturedAt: number,
|
|
97
|
+
): UsageReport {
|
|
98
|
+
// Require the exact app match even when account-wide plan data is available.
|
|
99
|
+
const app = normalizeOpenAIUsage(appPayload, clientId, capturedAt);
|
|
100
|
+
const root = asObject(planPayload);
|
|
101
|
+
const plan = normalizeCodexUsage({
|
|
102
|
+
rate_limit: root?.rate_limit,
|
|
103
|
+
credits: root?.credits,
|
|
104
|
+
}, capturedAt);
|
|
105
|
+
if (plan.buckets.length === 0) {
|
|
106
|
+
throw new Error("OpenAI subscription returned no displayable plan usage windows.");
|
|
107
|
+
}
|
|
108
|
+
const name = app.metrics.find((metric) => metric.id === "app")?.value ?? "Current";
|
|
109
|
+
return {
|
|
110
|
+
...app,
|
|
111
|
+
source: "openai-plan-and-app-pi-auth",
|
|
112
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan and app limits" },
|
|
113
|
+
defaultGroupId: "chatgpt-plan",
|
|
114
|
+
buckets: [
|
|
115
|
+
...plan.buckets.map((bucket) => ({
|
|
116
|
+
...bucket,
|
|
117
|
+
id: `plan:${bucket.id}`,
|
|
118
|
+
groupId: "chatgpt-plan",
|
|
119
|
+
groupLabel: "Plan limits",
|
|
120
|
+
modelKeys: undefined,
|
|
121
|
+
})),
|
|
122
|
+
...app.buckets.map((bucket) => ({
|
|
123
|
+
...bucket,
|
|
124
|
+
groupId: "chatgpt-app",
|
|
125
|
+
groupLabel: `${name} app limits`,
|
|
126
|
+
})),
|
|
127
|
+
],
|
|
128
|
+
metrics: [
|
|
129
|
+
...app.metrics.map((metric) => metric.id === "allowance"
|
|
130
|
+
? { ...metric, label: "App Allowance" } : metric),
|
|
131
|
+
...plan.metrics.filter((metric) => metric.id === "credits")
|
|
132
|
+
.map((metric) => ({ ...metric, label: "Credits Balance" })),
|
|
133
|
+
],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
138
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
139
|
+
? value as Record<string, unknown>
|
|
140
|
+
: undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function number(value: unknown): number | undefined {
|
|
144
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
145
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
3
|
+
import type { UsageBucket, UsageReport } from "../types.ts";
|
|
4
|
+
|
|
5
|
+
const WINDOWS = [
|
|
6
|
+
{ key: "rolling", label: "Rolling", windowMinutes: 300 },
|
|
7
|
+
{ key: "weekly", label: "Weekly", windowMinutes: 10_080 },
|
|
8
|
+
{ key: "monthly", label: "Monthly", windowMinutes: 43_200 },
|
|
9
|
+
] as const;
|
|
10
|
+
|
|
11
|
+
export function normalizeOpenCodeGoUsage(
|
|
12
|
+
payload: unknown,
|
|
13
|
+
capturedAt: number,
|
|
14
|
+
): UsageReport {
|
|
15
|
+
const root = asObject(payload);
|
|
16
|
+
const usage = asObject(root?.usage);
|
|
17
|
+
if (!usage) throw new Error("OpenCode Go usage response was not an object.");
|
|
18
|
+
const buckets: UsageBucket[] = [];
|
|
19
|
+
const notes: string[] = [];
|
|
20
|
+
for (const window of WINDOWS) {
|
|
21
|
+
const raw = asObject(usage[window.key]);
|
|
22
|
+
if (!raw) continue;
|
|
23
|
+
const status = asString(raw.status);
|
|
24
|
+
if (status !== "ok" && status !== "rate-limited") {
|
|
25
|
+
notes.push(
|
|
26
|
+
`${window.label} window unavailable (${status ?? "unknown status"}).`,
|
|
27
|
+
);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
const used = asNonnegativeNumber(raw.percent);
|
|
31
|
+
if (used === undefined) continue;
|
|
32
|
+
const clampedUsed = clampPercent(used);
|
|
33
|
+
const resetsAt = asEpochSeconds(raw.resetsAt);
|
|
34
|
+
buckets.push({
|
|
35
|
+
id: window.key,
|
|
36
|
+
label: `${window.label} window`,
|
|
37
|
+
used: clampedUsed,
|
|
38
|
+
remaining: 100 - clampedUsed,
|
|
39
|
+
limit: 100,
|
|
40
|
+
unit: "percent",
|
|
41
|
+
windowMinutes: window.windowMinutes,
|
|
42
|
+
...(resetsAt === undefined ? {} : { resetsAt }),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
if (buckets.length === 0) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
"OpenCode Go usage endpoint returned no displayable usage data.",
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
providerId: "opencode-go",
|
|
52
|
+
providerName: "OpenCode Go",
|
|
53
|
+
capturedAt,
|
|
54
|
+
source: "opencode-go-usage",
|
|
55
|
+
semantics: { kind: "consumer-subscription", label: "OpenCode Go plan usage" },
|
|
56
|
+
buckets,
|
|
57
|
+
metrics: [],
|
|
58
|
+
...(notes.length > 0 ? { notes } : {}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
63
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
64
|
+
? (value as Record<string, unknown>)
|
|
65
|
+
: undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function asString(value: unknown): string | undefined {
|
|
69
|
+
return typeof value === "string"
|
|
70
|
+
? sanitizeDisplayText(value, 80) || undefined
|
|
71
|
+
: undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function asNonnegativeNumber(value: unknown): number | undefined {
|
|
75
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0
|
|
76
|
+
? value
|
|
77
|
+
: undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function asEpochSeconds(value: unknown): number | undefined {
|
|
81
|
+
if (typeof value !== "string" || !value.trim()) return undefined;
|
|
82
|
+
const parsed = Date.parse(value);
|
|
83
|
+
return Number.isNaN(parsed) ? undefined : Math.floor(parsed / 1000);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function clampPercent(value: number): number {
|
|
87
|
+
return Math.min(100, Math.max(0, value));
|
|
88
|
+
}
|