@hyav/pi-provider 0.1.2 → 0.1.4
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/CHANGELOG.md +23 -0
- package/README.md +30 -4
- package/README.zh-CN.md +30 -4
- package/core/adapter-loader.ts +58 -12
- package/core/catalog-preflight.ts +130 -0
- package/core/credential-type.ts +13 -0
- package/core/host.ts +4 -3
- package/core/official-pricing.ts +2 -3
- package/core/preflight-manager.ts +13 -0
- package/core/public-adapters.ts +47 -0
- package/core/ratelimit-headers.ts +72 -0
- package/core/runtime-config.ts +92 -8
- package/core/runtime-entry.ts +26 -0
- package/core/runtime.ts +23 -10
- package/core/status-manager.ts +7 -1
- package/core/types.ts +12 -0
- package/index.ts +30 -6
- package/package.json +1 -1
- package/preflight/anthropic.ts +42 -0
- package/preflight/cerebras.ts +27 -0
- package/preflight/charm-hyper.ts +2 -4
- package/preflight/deepseek.ts +2 -4
- package/preflight/github-copilot.ts +74 -0
- package/preflight/google.ts +2 -4
- package/preflight/groq.ts +72 -0
- package/preflight/huggingface.ts +27 -0
- package/preflight/mistral.ts +27 -0
- package/preflight/moonshotai-cn.ts +27 -0
- package/preflight/moonshotai.ts +37 -0
- package/preflight/nvidia.ts +27 -0
- package/preflight/openai-codex.ts +2 -4
- package/preflight/openai.ts +27 -0
- package/preflight/opencode-go.ts +2 -3
- package/preflight/opencode.ts +2 -3
- package/preflight/openrouter.ts +111 -0
- package/preflight/vercel-ai-gateway.ts +86 -0
- package/preflight/xai.ts +70 -0
- package/providers/charm-hyper.ts +8 -5
- package/status/anthropic.ts +258 -0
- package/status/charm-hyper.ts +3 -5
- package/status/deepseek.ts +2 -4
- package/status/github-copilot.ts +176 -0
- package/status/groq.ts +88 -0
- package/status/huggingface.ts +94 -0
- package/status/moonshotai-cn.ts +26 -0
- package/status/moonshotai.ts +150 -0
- package/status/openai-codex.ts +2 -4
- package/status/opencode-go.ts +2 -4
- package/status/openrouter.ts +172 -0
- package/status/vercel-ai-gateway/constants.ts +3 -0
- package/status/vercel-ai-gateway.ts +94 -0
- package/status/xai.ts +73 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import type { StatusAdapter, StatusEntry, StatusSnapshot } from "@hyav/pi-provider";
|
|
2
|
+
import { defineStatusExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Anthropic usage endpoint for subscription quotas (Claude Pro/Max) and extra
|
|
6
|
+
* usage credit. Not part of the public platform API contract, so the URL is
|
|
7
|
+
* overridable: ANTHROPIC_USAGE_URL, or set it to an empty string to disable.
|
|
8
|
+
*/
|
|
9
|
+
export const DEFAULT_ANTHROPIC_USAGE_URL = "https://claude.ai/api/usage";
|
|
10
|
+
export const ANTHROPIC_USAGE_URL =
|
|
11
|
+
typeof process !== "undefined" && process.env.ANTHROPIC_USAGE_URL !== undefined
|
|
12
|
+
? process.env.ANTHROPIC_USAGE_URL
|
|
13
|
+
: DEFAULT_ANTHROPIC_USAGE_URL;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Anthropic API keys are `sk-ant-api...`; subscription OAuth access tokens
|
|
17
|
+
* (used by Claude web / Claude Code) contain `sk-ant-oat...`. Only subscription
|
|
18
|
+
* tokens may be sent to the Claude web usage endpoint. This keeps API keys
|
|
19
|
+
* resolved from environment variables, models.json, or a runtime from ever
|
|
20
|
+
* reaching it.
|
|
21
|
+
*/
|
|
22
|
+
export function isAnthropicOAuthToken(key: string): boolean {
|
|
23
|
+
return key.includes("sk-ant-oat");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function isAnthropicApiKey(key: string): boolean {
|
|
27
|
+
return (key.startsWith("sk-ant-api") || key.startsWith("sk-ant-")) && !isAnthropicOAuthToken(key);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
31
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
35
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const MAX_LABEL_LENGTH = 64;
|
|
39
|
+
|
|
40
|
+
function safeLabel(value: unknown): string | undefined {
|
|
41
|
+
if (typeof value !== "string") return undefined;
|
|
42
|
+
const trimmed = value.trim();
|
|
43
|
+
if (trimmed === "" || trimmed.length > MAX_LABEL_LENGTH || /[\u0000-\u001f\u007f]/.test(trimmed)) return undefined;
|
|
44
|
+
return trimmed;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface AnthropicUsageWindow {
|
|
48
|
+
id: string;
|
|
49
|
+
label: string;
|
|
50
|
+
used: number;
|
|
51
|
+
limit: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function parseAnthropicUsage(payload: unknown): {
|
|
55
|
+
plan?: string;
|
|
56
|
+
resetAt?: number;
|
|
57
|
+
windows: AnthropicUsageWindow[];
|
|
58
|
+
extraUsageBalanceUsd?: number;
|
|
59
|
+
} {
|
|
60
|
+
if (!isRecord(payload)) {
|
|
61
|
+
throw new ProviderDataError("Anthropic status returned an invalid usage response", "badjson");
|
|
62
|
+
}
|
|
63
|
+
const subscribed = isRecord(payload.subscribedUsage) ? payload.subscribedUsage : payload;
|
|
64
|
+
|
|
65
|
+
/** History arrays use their latest entry as the current value. */
|
|
66
|
+
const read = (field: string): number | undefined => {
|
|
67
|
+
const value = subscribed[field];
|
|
68
|
+
if (Array.isArray(value)) {
|
|
69
|
+
const latest = value[value.length - 1];
|
|
70
|
+
return typeof latest === "number" && Number.isFinite(latest) ? latest : undefined;
|
|
71
|
+
}
|
|
72
|
+
return finiteNumber(value);
|
|
73
|
+
};
|
|
74
|
+
const readLimit = (field: string): number | undefined => {
|
|
75
|
+
const limitValue = finiteNumber(subscribed[`${field}Limit`]);
|
|
76
|
+
if (limitValue !== undefined && limitValue > 0) return limitValue;
|
|
77
|
+
const entriesValue = subscribed[field];
|
|
78
|
+
if (isRecord(entriesValue)) {
|
|
79
|
+
const nested = finiteNumber(entriesValue.limit);
|
|
80
|
+
if (nested !== undefined && nested > 0) return nested;
|
|
81
|
+
}
|
|
82
|
+
return undefined;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const windows: AnthropicUsageWindow[] = [];
|
|
86
|
+
for (const [field, id, label] of [
|
|
87
|
+
["session", "session-usage", "Session"],
|
|
88
|
+
["daily", "daily-usage", "Daily"],
|
|
89
|
+
["weekly", "weekly-usage", "Weekly"],
|
|
90
|
+
["monthly", "monthly-usage", "Monthly"],
|
|
91
|
+
] as const) {
|
|
92
|
+
const used = read(field);
|
|
93
|
+
const limit = readLimit(field);
|
|
94
|
+
if (used !== undefined && limit !== undefined) {
|
|
95
|
+
windows.push({ id, label, used, limit });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const resetAtValue = finiteNumber(payload.weeklyResetAt) ?? finiteNumber(subscribed.weeklyResetAt);
|
|
100
|
+
const resetAt = resetAtValue !== undefined && resetAtValue > 0 ? resetAtValue * 1_000 : undefined;
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
plan: safeLabel(payload.plan) ?? safeLabel(payload.subscriptionPlan),
|
|
104
|
+
...(resetAt !== undefined ? { resetAt } : {}),
|
|
105
|
+
windows,
|
|
106
|
+
extraUsageBalanceUsd: finiteNumber(payload.extraUsageBalanceUsd) ?? finiteNumber(subscribed.extraUsageBalanceUsd),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function windowEntry(id: string, label: string, used: number, limit: number, resetAt: number | undefined): StatusEntry {
|
|
111
|
+
const percent = (used / limit) * 100;
|
|
112
|
+
return {
|
|
113
|
+
kind: "window",
|
|
114
|
+
id,
|
|
115
|
+
label,
|
|
116
|
+
remainingPercent: Math.max(0, Math.min(100, 100 - percent)),
|
|
117
|
+
...(resetAt !== undefined ? { resetAt } : {}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function usageEntries(payload: unknown): StatusEntry[] {
|
|
122
|
+
const parsed = parseAnthropicUsage(payload);
|
|
123
|
+
const entries: StatusEntry[] = [{ kind: "text", id: "plan", label: "Plan", value: parsed.plan ?? "Unknown" }];
|
|
124
|
+
for (const window of parsed.windows) {
|
|
125
|
+
entries.push(windowEntry(window.id, window.label, window.used, window.limit, parsed.resetAt));
|
|
126
|
+
}
|
|
127
|
+
if (parsed.extraUsageBalanceUsd !== undefined) {
|
|
128
|
+
entries.push({
|
|
129
|
+
kind: "amount",
|
|
130
|
+
id: "extra-usage-balance",
|
|
131
|
+
label: "Extra usage balance",
|
|
132
|
+
value: parsed.extraUsageBalanceUsd,
|
|
133
|
+
unit: "USD",
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (entries.length === 1) {
|
|
137
|
+
entries.push({ kind: "text", id: "limits", label: "Limits", value: "not available" });
|
|
138
|
+
}
|
|
139
|
+
return entries;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function credentialType(context: Parameters<StatusAdapter["fetch"]>[0]): Promise<string | undefined> {
|
|
143
|
+
try {
|
|
144
|
+
return await context.getCredentialType?.();
|
|
145
|
+
} catch {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function apiKeyEntries(): StatusEntry[] {
|
|
151
|
+
return [
|
|
152
|
+
{ kind: "text", id: "auth", label: "Auth", value: "API key" },
|
|
153
|
+
{ kind: "text", id: "usage", label: "Usage", value: "not available from the subscription endpoint" },
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface AnthropicStatusOptions {
|
|
158
|
+
/** Usage endpoint override; defaults to ANTHROPIC_USAGE_URL. */
|
|
159
|
+
usageUrl?: string;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function createAnthropicStatusAdapter(
|
|
163
|
+
requestTimeoutMs: number,
|
|
164
|
+
options: AnthropicStatusOptions = {},
|
|
165
|
+
): StatusAdapter {
|
|
166
|
+
const usageUrl = (options.usageUrl ?? ANTHROPIC_USAGE_URL).trim();
|
|
167
|
+
return {
|
|
168
|
+
id: "anthropic-status",
|
|
169
|
+
providerId: "anthropic",
|
|
170
|
+
name: "Anthropic",
|
|
171
|
+
cacheTtlMs: 60_000,
|
|
172
|
+
requestTimeoutMs,
|
|
173
|
+
async fetch(context): Promise<StatusSnapshot> {
|
|
174
|
+
const key = await context.getApiKey();
|
|
175
|
+
if (!key || key === "proxy-managed") {
|
|
176
|
+
throw new ProviderDataError("Anthropic status requires authentication", "auth");
|
|
177
|
+
}
|
|
178
|
+
const credential = await credentialType(context);
|
|
179
|
+
const isOAuth = credential === "oauth" ? !isAnthropicApiKey(key) : isAnthropicOAuthToken(key);
|
|
180
|
+
if (usageUrl === "") {
|
|
181
|
+
return {
|
|
182
|
+
entries: [{ kind: "text", id: "usage", label: "Usage", value: "disabled" }],
|
|
183
|
+
updatedAt: context.now(),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (!isOAuth) {
|
|
188
|
+
if (usageUrl === DEFAULT_ANTHROPIC_USAGE_URL) {
|
|
189
|
+
// The default endpoint is subscription-only. Never send an
|
|
190
|
+
// API key there; the user can configure a custom endpoint
|
|
191
|
+
// via ANTHROPIC_USAGE_URL if they run their own queries.
|
|
192
|
+
return { entries: apiKeyEntries(), updatedAt: context.now() };
|
|
193
|
+
}
|
|
194
|
+
// Explicitly configured custom endpoint: send as x-api-key only.
|
|
195
|
+
const response = await context.fetch(usageUrl, {
|
|
196
|
+
headers: {
|
|
197
|
+
Accept: "application/json",
|
|
198
|
+
"Accept-Encoding": "identity",
|
|
199
|
+
"x-api-key": key,
|
|
200
|
+
"User-Agent": "@hyav/pi-provider",
|
|
201
|
+
},
|
|
202
|
+
signal: context.signal,
|
|
203
|
+
});
|
|
204
|
+
if (!response.ok) {
|
|
205
|
+
throw new ProviderDataError(
|
|
206
|
+
`Anthropic status failed: HTTP ${response.status}`,
|
|
207
|
+
`http${response.status}`,
|
|
208
|
+
parseRetryAfter(response.headers.get("retry-after"), context.now()),
|
|
209
|
+
response.status,
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
let payload: unknown;
|
|
213
|
+
try {
|
|
214
|
+
payload = await response.json();
|
|
215
|
+
} catch {
|
|
216
|
+
throw new ProviderDataError("Anthropic status returned invalid JSON", "badjson");
|
|
217
|
+
}
|
|
218
|
+
return { entries: usageEntries(payload), updatedAt: context.now() };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// OAuth (Claude Pro/Max) uses the usage endpoint with the subscription Bearer token.
|
|
222
|
+
const response = await context.fetch(usageUrl, {
|
|
223
|
+
headers: {
|
|
224
|
+
Accept: "application/json",
|
|
225
|
+
"Accept-Encoding": "identity",
|
|
226
|
+
Authorization: `Bearer ${key}`,
|
|
227
|
+
"User-Agent": "@hyav/pi-provider",
|
|
228
|
+
},
|
|
229
|
+
signal: context.signal,
|
|
230
|
+
});
|
|
231
|
+
if (!response.ok) {
|
|
232
|
+
throw new ProviderDataError(
|
|
233
|
+
`Anthropic status failed: HTTP ${response.status}`,
|
|
234
|
+
`http${response.status}`,
|
|
235
|
+
parseRetryAfter(response.headers.get("retry-after"), context.now()),
|
|
236
|
+
response.status,
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
let payload: unknown;
|
|
240
|
+
try {
|
|
241
|
+
payload = await response.json();
|
|
242
|
+
} catch {
|
|
243
|
+
throw new ProviderDataError("Anthropic status returned invalid JSON", "badjson");
|
|
244
|
+
}
|
|
245
|
+
return { entries: usageEntries(payload), updatedAt: context.now() };
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export const anthropicStatusAdapter = createAnthropicStatusAdapter(8_000);
|
|
251
|
+
|
|
252
|
+
const anthropicStatusExtension = defineStatusExtension({
|
|
253
|
+
id: "anthropic-status",
|
|
254
|
+
providerId: "anthropic",
|
|
255
|
+
create: ({ statusRequestTimeoutMs }) => createAnthropicStatusAdapter(statusRequestTimeoutMs),
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
export default anthropicStatusExtension;
|
package/status/charm-hyper.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ProviderDataError } from "
|
|
3
|
-
import { parseRetryAfter } from "../core/retry-after.ts";
|
|
4
|
-
import type { StatusAdapter, StatusSnapshot } from "../core/types.ts";
|
|
1
|
+
import type { StatusAdapter, StatusSnapshot } from "@hyav/pi-provider";
|
|
2
|
+
import { defineStatusExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
|
|
5
3
|
import { hyperJsonHeaders } from "../providers/charm-hyper/constants.ts";
|
|
6
4
|
|
|
7
5
|
const CREDITS_URL = "https://hyper.charm.land/v1/credits";
|
|
@@ -23,7 +21,7 @@ export const hyperStatusAdapter: StatusAdapter = {
|
|
|
23
21
|
id: "charm-hyper-status",
|
|
24
22
|
providerId: "charm-hyper",
|
|
25
23
|
name: "Charm Hyper",
|
|
26
|
-
cacheTtlMs:
|
|
24
|
+
cacheTtlMs: 60_000,
|
|
27
25
|
requestTimeoutMs: 8_000,
|
|
28
26
|
async fetch(context): Promise<StatusSnapshot> {
|
|
29
27
|
const key = await context.getApiKey();
|
package/status/deepseek.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ProviderDataError } from "
|
|
3
|
-
import { parseRetryAfter } from "../core/retry-after.ts";
|
|
4
|
-
import type { StatusAdapter, StatusSnapshot } from "../core/types.ts";
|
|
1
|
+
import type { StatusAdapter, StatusSnapshot } from "@hyav/pi-provider";
|
|
2
|
+
import { defineStatusExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
|
|
5
3
|
|
|
6
4
|
export const DEEPSEEK_BALANCE_URL = "https://api.deepseek.com/user/balance";
|
|
7
5
|
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type { StatusAdapter, StatusEntry, StatusSnapshot } from "@hyav/pi-provider";
|
|
2
|
+
import { defineStatusExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* GitHub Copilot Individual usage. These endpoints are not part of public
|
|
6
|
+
* GitHub documentation, so payload shapes are parsed defensively and a 404
|
|
7
|
+
* degrades to a single explanatory entry instead of an error state.
|
|
8
|
+
*/
|
|
9
|
+
export const COPILOT_USAGE_URL = "https://api.individual.githubcopilot.com/usage";
|
|
10
|
+
|
|
11
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
12
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
16
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const MAX_LABEL_LENGTH = 64;
|
|
20
|
+
|
|
21
|
+
function safeText(value: unknown): string | undefined {
|
|
22
|
+
if (typeof value !== "string") return undefined;
|
|
23
|
+
const trimmed = value.trim();
|
|
24
|
+
if (trimmed === "" || trimmed.length > MAX_LABEL_LENGTH || /[\u0000-\u001f\u007f]/.test(trimmed)) return undefined;
|
|
25
|
+
return trimmed;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface CopilotQuota {
|
|
29
|
+
id: string;
|
|
30
|
+
name?: string;
|
|
31
|
+
used: number;
|
|
32
|
+
limit: number;
|
|
33
|
+
resetAt?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function labelValue(value: unknown): string | undefined {
|
|
37
|
+
if (typeof value === "string") return safeText(value);
|
|
38
|
+
if (isRecord(value)) return safeText(value.value) ?? safeText(value.label);
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function planName(value: unknown): string | undefined {
|
|
43
|
+
return labelValue(isRecord(value) ? value.planName : undefined);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Preferred shape: `modelCatalog.usage.modelQuotas`. */
|
|
47
|
+
function parseModelCatalog(catalog: unknown): CopilotQuota[] {
|
|
48
|
+
if (!isRecord(catalog) || !isRecord(catalog.usage) || !isRecord(catalog.usage.modelQuotas)) return [];
|
|
49
|
+
const quotas: CopilotQuota[] = [];
|
|
50
|
+
for (const [key, value] of Object.entries(catalog.usage.modelQuotas)) {
|
|
51
|
+
if (!isRecord(value)) continue;
|
|
52
|
+
const used =
|
|
53
|
+
finiteNumber(value.usedRequestsQuantity) ?? finiteNumber(value.usedRequests) ?? finiteNumber(value.used);
|
|
54
|
+
const limit = finiteNumber(value.allowedRequestsQuantity);
|
|
55
|
+
if (used === undefined || limit === undefined || limit <= 0) continue;
|
|
56
|
+
const resetAt = finiteNumber(value.resetAt);
|
|
57
|
+
quotas.push({
|
|
58
|
+
id: key,
|
|
59
|
+
name: safeText(value.modelCopilotName),
|
|
60
|
+
used,
|
|
61
|
+
limit,
|
|
62
|
+
...(resetAt !== undefined ? { resetAt: resetAt * 1_000 } : {}),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return quotas;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Fallback shape: `modelQuotaByFeature[]` with nested payload. */
|
|
69
|
+
function parseQuotaByFeature(payload: unknown): CopilotQuota[] {
|
|
70
|
+
if (!isRecord(payload) || !Array.isArray(payload.modelQuotaByFeature)) return [];
|
|
71
|
+
const quotas: CopilotQuota[] = [];
|
|
72
|
+
for (const [index, entry] of payload.modelQuotaByFeature.entries()) {
|
|
73
|
+
if (!isRecord(entry)) continue;
|
|
74
|
+
const quota =
|
|
75
|
+
(isRecord(entry.modelQuotaPayload) && entry.modelQuotaPayload) ||
|
|
76
|
+
(isRecord(entry.modelQuotaForFeature) && entry.modelQuotaForFeature);
|
|
77
|
+
if (!quota) continue;
|
|
78
|
+
const used = finiteNumber(quota.usedRequestsQuantity) ?? finiteNumber(quota.usedRequests);
|
|
79
|
+
const limit = finiteNumber(quota.allowedRequestsQuantity);
|
|
80
|
+
if (used === undefined || limit === undefined) continue;
|
|
81
|
+
const resetAt = finiteNumber(quota.resetAt);
|
|
82
|
+
const name = safeText(quota.modelCopilotName);
|
|
83
|
+
quotas.push({
|
|
84
|
+
id: typeof quota.quotaId === "string" && quota.quotaId.trim() !== "" ? quota.quotaId.trim() : `quota-${index}`,
|
|
85
|
+
...(name !== undefined ? { name } : {}),
|
|
86
|
+
used,
|
|
87
|
+
limit,
|
|
88
|
+
...(resetAt !== undefined ? { resetAt: resetAt * 1_000 } : {}),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return quotas;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function windowEntry(quota: CopilotQuota): StatusEntry {
|
|
95
|
+
const percent = (quota.used / quota.limit) * 100;
|
|
96
|
+
return {
|
|
97
|
+
kind: "window",
|
|
98
|
+
id: `quota-${quota.id}`,
|
|
99
|
+
label: quota.name ?? quota.id,
|
|
100
|
+
remainingPercent: Math.max(0, Math.min(100, 100 - percent)),
|
|
101
|
+
...(quota.resetAt !== undefined ? { resetAt: quota.resetAt } : {}),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export const githubCopilotStatusAdapter: StatusAdapter = {
|
|
106
|
+
id: "github-copilot-status",
|
|
107
|
+
providerId: "github-copilot",
|
|
108
|
+
name: "GitHub Copilot",
|
|
109
|
+
cacheTtlMs: 60_000,
|
|
110
|
+
requestTimeoutMs: 8_000,
|
|
111
|
+
async fetch(context): Promise<StatusSnapshot> {
|
|
112
|
+
const key = await context.getApiKey();
|
|
113
|
+
if (!key || key === "proxy-managed") {
|
|
114
|
+
throw new ProviderDataError("GitHub Copilot status requires Copilot OAuth", "auth");
|
|
115
|
+
}
|
|
116
|
+
const response = await context.fetch(COPILOT_USAGE_URL, {
|
|
117
|
+
headers: {
|
|
118
|
+
Accept: "application/json",
|
|
119
|
+
"Accept-Encoding": "identity",
|
|
120
|
+
Authorization: `Bearer ${key}`,
|
|
121
|
+
"User-Agent": "@hyav/pi-provider",
|
|
122
|
+
},
|
|
123
|
+
signal: context.signal,
|
|
124
|
+
});
|
|
125
|
+
if (response.status === 404) {
|
|
126
|
+
return {
|
|
127
|
+
entries: [{ kind: "text", id: "usage", label: "Usage", value: "unavailable for this plan" }],
|
|
128
|
+
updatedAt: context.now(),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (!response.ok) {
|
|
132
|
+
throw new ProviderDataError(
|
|
133
|
+
`GitHub Copilot status failed: HTTP ${response.status}`,
|
|
134
|
+
`http${response.status}`,
|
|
135
|
+
parseRetryAfter(response.headers.get("retry-after"), context.now()),
|
|
136
|
+
response.status,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
let payload: unknown;
|
|
140
|
+
try {
|
|
141
|
+
payload = await response.json();
|
|
142
|
+
} catch {
|
|
143
|
+
throw new ProviderDataError("GitHub Copilot status returned invalid JSON", "badjson");
|
|
144
|
+
}
|
|
145
|
+
if (!isRecord(payload)) {
|
|
146
|
+
throw new ProviderDataError("GitHub Copilot status returned an invalid usage response", "badjson");
|
|
147
|
+
}
|
|
148
|
+
const quotas = parseModelCatalog(isRecord(payload.modelCatalog) ? payload.modelCatalog : payload);
|
|
149
|
+
const modelQuotas = quotas.length > 0 ? quotas : parseQuotaByFeature(payload);
|
|
150
|
+
const entries: StatusEntry[] = [
|
|
151
|
+
{
|
|
152
|
+
kind: "text",
|
|
153
|
+
id: "plan",
|
|
154
|
+
label: "Plan",
|
|
155
|
+
value: isRecord(payload.modelCatalog) ? (planName(payload.modelCatalog) ?? "Unknown") : "Unknown",
|
|
156
|
+
},
|
|
157
|
+
];
|
|
158
|
+
for (const quota of modelQuotas) entries.push(windowEntry(quota));
|
|
159
|
+
if (entries.length === 1) {
|
|
160
|
+
entries.push({ kind: "text", id: "limits", label: "Limits", value: "not available" });
|
|
161
|
+
}
|
|
162
|
+
return { entries, updatedAt: context.now() };
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
export function createGithubCopilotStatusAdapter(requestTimeoutMs: number): StatusAdapter {
|
|
167
|
+
return { ...githubCopilotStatusAdapter, requestTimeoutMs };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const githubCopilotStatusExtension = defineStatusExtension({
|
|
171
|
+
id: "github-copilot-status",
|
|
172
|
+
providerId: "github-copilot",
|
|
173
|
+
create: ({ statusRequestTimeoutMs }) => createGithubCopilotStatusAdapter(statusRequestTimeoutMs),
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
export default githubCopilotStatusExtension;
|
package/status/groq.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { StatusAdapter, StatusEntry, StatusSnapshot } from "@hyav/pi-provider";
|
|
2
|
+
import { defineStatusExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
|
|
3
|
+
import { parseRateLimitWindows } from "../core/ratelimit-headers.ts";
|
|
4
|
+
|
|
5
|
+
export const GROQ_MODELS_URL = "https://api.groq.com/openai/v1/models";
|
|
6
|
+
|
|
7
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
8
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function windowEntry(
|
|
12
|
+
id: string,
|
|
13
|
+
label: string,
|
|
14
|
+
window: { limit: number; remaining: number; resetAt?: number },
|
|
15
|
+
): StatusEntry {
|
|
16
|
+
const percent = (window.remaining / window.limit) * 100;
|
|
17
|
+
return {
|
|
18
|
+
kind: "window",
|
|
19
|
+
id,
|
|
20
|
+
label,
|
|
21
|
+
remainingPercent: Math.max(0, Math.min(100, percent)),
|
|
22
|
+
...(window.resetAt !== undefined ? { resetAt: window.resetAt } : {}),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const groqStatusAdapter: StatusAdapter = {
|
|
27
|
+
id: "groq-status",
|
|
28
|
+
providerId: "groq",
|
|
29
|
+
name: "Groq",
|
|
30
|
+
cacheTtlMs: 60_000,
|
|
31
|
+
requestTimeoutMs: 8_000,
|
|
32
|
+
async fetch(context): Promise<StatusSnapshot> {
|
|
33
|
+
const key = await context.getApiKey();
|
|
34
|
+
if (!key || key === "proxy-managed") {
|
|
35
|
+
throw new ProviderDataError("Groq status requires an API key", "auth");
|
|
36
|
+
}
|
|
37
|
+
const response = await context.fetch(GROQ_MODELS_URL, {
|
|
38
|
+
headers: {
|
|
39
|
+
Accept: "application/json",
|
|
40
|
+
"Accept-Encoding": "identity",
|
|
41
|
+
Authorization: `Bearer ${key}`,
|
|
42
|
+
"User-Agent": "@hyav/pi-provider",
|
|
43
|
+
},
|
|
44
|
+
signal: context.signal,
|
|
45
|
+
});
|
|
46
|
+
if (!response.ok) {
|
|
47
|
+
throw new ProviderDataError(
|
|
48
|
+
`Groq status failed: HTTP ${response.status}`,
|
|
49
|
+
`http${response.status}`,
|
|
50
|
+
parseRetryAfter(response.headers.get("retry-after"), context.now()),
|
|
51
|
+
response.status,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
let modelCount: string | undefined;
|
|
55
|
+
try {
|
|
56
|
+
const payload: unknown = await response.json();
|
|
57
|
+
modelCount = isRecord(payload) && Array.isArray(payload.data) ? `${payload.data.length} available` : undefined;
|
|
58
|
+
} catch {
|
|
59
|
+
modelCount = undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const now = context.now();
|
|
63
|
+
const { requests, tokens } = parseRateLimitWindows(response.headers, now);
|
|
64
|
+
const entries: StatusEntry[] = [
|
|
65
|
+
modelCount === undefined
|
|
66
|
+
? { kind: "text", id: "models", label: "Models", value: "unavailable" }
|
|
67
|
+
: { kind: "text", id: "models", label: "Models", value: modelCount },
|
|
68
|
+
];
|
|
69
|
+
if (requests) entries.push(windowEntry("requests-per-day", "Requests per day", requests));
|
|
70
|
+
if (tokens) entries.push(windowEntry("tokens-per-minute", "Tokens per minute", tokens));
|
|
71
|
+
if (entries.length === 1) {
|
|
72
|
+
entries.push({ kind: "text", id: "limits", label: "Limits", value: "not available" });
|
|
73
|
+
}
|
|
74
|
+
return { entries, updatedAt: now };
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export function createGroqStatusAdapter(requestTimeoutMs: number): StatusAdapter {
|
|
79
|
+
return { ...groqStatusAdapter, requestTimeoutMs };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const groqStatusExtension = defineStatusExtension({
|
|
83
|
+
id: "groq-status",
|
|
84
|
+
providerId: "groq",
|
|
85
|
+
create: ({ statusRequestTimeoutMs }) => createGroqStatusAdapter(statusRequestTimeoutMs),
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
export default groqStatusExtension;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { StatusAdapter, StatusEntry, StatusSnapshot } from "@hyav/pi-provider";
|
|
2
|
+
import { defineStatusExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
|
|
3
|
+
|
|
4
|
+
export const HF_WHOAMI_URL = "https://huggingface.co/api/whoami-v2";
|
|
5
|
+
|
|
6
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
7
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
11
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const MAX_LABEL_LENGTH = 64;
|
|
15
|
+
|
|
16
|
+
function safeText(value: unknown): string | undefined {
|
|
17
|
+
if (typeof value !== "string") return undefined;
|
|
18
|
+
const trimmed = value.trim();
|
|
19
|
+
if (trimmed === "" || trimmed.length > MAX_LABEL_LENGTH || /[\u0000-\u001f\u007f]/.test(trimmed)) return undefined;
|
|
20
|
+
return trimmed;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface HuggingFaceAccount {
|
|
24
|
+
plan?: string;
|
|
25
|
+
credits?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function parseHuggingFaceAccount(payload: unknown): HuggingFaceAccount {
|
|
29
|
+
if (!isRecord(payload)) {
|
|
30
|
+
throw new ProviderDataError("Hugging Face status returned an invalid account response", "badjson");
|
|
31
|
+
}
|
|
32
|
+
// Response envelope: { type, id, name, emailVerified, canPay, isPro, plan, periodEnd, credits, ... }
|
|
33
|
+
const plan = safeText(payload.plan);
|
|
34
|
+
// Older token generations omit the envelope fields entirely.
|
|
35
|
+
return {
|
|
36
|
+
...(plan !== undefined ? { plan } : {}),
|
|
37
|
+
...(finiteNumber(payload.credits) !== undefined ? { credits: finiteNumber(payload.credits) } : {}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const huggingFaceStatusAdapter: StatusAdapter = {
|
|
42
|
+
id: "huggingface-status",
|
|
43
|
+
providerId: "huggingface",
|
|
44
|
+
name: "Hugging Face",
|
|
45
|
+
cacheTtlMs: 60_000,
|
|
46
|
+
requestTimeoutMs: 8_000,
|
|
47
|
+
async fetch(context): Promise<StatusSnapshot> {
|
|
48
|
+
const key = await context.getApiKey();
|
|
49
|
+
if (!key || key === "proxy-managed") {
|
|
50
|
+
throw new ProviderDataError("Hugging Face status requires a token", "auth");
|
|
51
|
+
}
|
|
52
|
+
const response = await context.fetch(HF_WHOAMI_URL, {
|
|
53
|
+
headers: {
|
|
54
|
+
Accept: "application/json",
|
|
55
|
+
"Accept-Encoding": "identity",
|
|
56
|
+
Authorization: `Bearer ${key}`,
|
|
57
|
+
"User-Agent": "@hyav/pi-provider",
|
|
58
|
+
},
|
|
59
|
+
signal: context.signal,
|
|
60
|
+
});
|
|
61
|
+
if (!response.ok) {
|
|
62
|
+
throw new ProviderDataError(
|
|
63
|
+
`Hugging Face status failed: HTTP ${response.status}`,
|
|
64
|
+
`http${response.status}`,
|
|
65
|
+
parseRetryAfter(response.headers.get("retry-after"), context.now()),
|
|
66
|
+
response.status,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
let payload: unknown;
|
|
70
|
+
try {
|
|
71
|
+
payload = await response.json();
|
|
72
|
+
} catch {
|
|
73
|
+
throw new ProviderDataError("Hugging Face status returned invalid JSON", "badjson");
|
|
74
|
+
}
|
|
75
|
+
const account = parseHuggingFaceAccount(payload);
|
|
76
|
+
const entries: StatusEntry[] = [{ kind: "text", id: "plan", label: "Plan", value: account.plan ?? "Unknown" }];
|
|
77
|
+
if (account.credits !== undefined) {
|
|
78
|
+
entries.push({ kind: "amount", id: "credits", label: "Credits", value: account.credits, unit: "USD" });
|
|
79
|
+
}
|
|
80
|
+
return { entries, updatedAt: context.now() };
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export function createHuggingFaceStatusAdapter(requestTimeoutMs: number): StatusAdapter {
|
|
85
|
+
return { ...huggingFaceStatusAdapter, requestTimeoutMs };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const huggingFaceStatusExtension = defineStatusExtension({
|
|
89
|
+
id: "huggingface-status",
|
|
90
|
+
providerId: "huggingface",
|
|
91
|
+
create: ({ statusRequestTimeoutMs }) => createHuggingFaceStatusAdapter(statusRequestTimeoutMs),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
export default huggingFaceStatusExtension;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { StatusAdapter } from "@hyav/pi-provider";
|
|
2
|
+
import { defineStatusExtension } from "@hyav/pi-provider";
|
|
3
|
+
import { createMoonshotStatusAdapter, MOONSHOT_CN_BALANCE_URL } from "./moonshotai.ts";
|
|
4
|
+
|
|
5
|
+
export const moonshotaiCnStatusAdapter: StatusAdapter = createMoonshotStatusAdapter(
|
|
6
|
+
{
|
|
7
|
+
id: "moonshotai-cn-status",
|
|
8
|
+
providerId: "moonshotai-cn",
|
|
9
|
+
name: "Moonshot CN (Kimi)",
|
|
10
|
+
balanceUrl: MOONSHOT_CN_BALANCE_URL,
|
|
11
|
+
unit: "CNY",
|
|
12
|
+
},
|
|
13
|
+
8_000,
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
export function createMoonshotaiCnStatusAdapter(requestTimeoutMs: number): StatusAdapter {
|
|
17
|
+
return { ...moonshotaiCnStatusAdapter, requestTimeoutMs };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const moonshotaiCnStatusExtension = defineStatusExtension({
|
|
21
|
+
id: "moonshotai-cn-status",
|
|
22
|
+
providerId: "moonshotai-cn",
|
|
23
|
+
create: ({ statusRequestTimeoutMs }) => createMoonshotaiCnStatusAdapter(statusRequestTimeoutMs),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export default moonshotaiCnStatusExtension;
|