@hyav/pi-provider 0.1.3 → 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.
@@ -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;
@@ -0,0 +1,150 @@
1
+ import type { StatusAdapter, StatusEntry, StatusSnapshot } from "@hyav/pi-provider";
2
+ import { defineStatusExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
3
+
4
+ /**
5
+ * Moonshot (Kimi) balance checks. International and China platforms keep
6
+ * fully independent API keys; the same response shape is shared by both
7
+ * endpoints, so the adapter body is factored once.
8
+ */
9
+ export const MOONSHOT_BALANCE_URL = "https://api.moonshot.ai/v1/users/me/balance";
10
+ export const MOONSHOT_CN_BALANCE_URL = "https://api.moonshot.cn/v1/users/me/balance";
11
+
12
+ function isRecord(value: unknown): value is Record<string, unknown> {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+
16
+ function finiteNumber(value: unknown): number | undefined {
17
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
18
+ }
19
+
20
+ export interface MoonshotBalance {
21
+ available: number;
22
+ voucher?: number;
23
+ cash?: number;
24
+ }
25
+
26
+ export function parseMoonshotBalance(payload: unknown): MoonshotBalance {
27
+ if (!isRecord(payload) || !isRecord(payload.data)) {
28
+ throw new ProviderDataError("Moonshot status returned an invalid balance response", "badjson");
29
+ }
30
+ const code = payload.code;
31
+ if (code !== 0 && code !== undefined) {
32
+ throw new ProviderDataError("Moonshot status returned an unsuccessful balance response", "provider");
33
+ }
34
+ const available = finiteNumber(payload.data.available_balance);
35
+ if (available === undefined) {
36
+ throw new ProviderDataError("Moonshot status returned an invalid balance response", "badjson");
37
+ }
38
+ const voucher = finiteNumber(payload.data.voucher_balance);
39
+ const cash = finiteNumber(payload.data.cash_balance);
40
+ // Voucher balances are documented as non-negative; cash may be negative.
41
+ if (voucher !== undefined && voucher < 0) {
42
+ throw new ProviderDataError("Moonshot status returned an invalid balance response", "badjson");
43
+ }
44
+ return {
45
+ available,
46
+ ...(voucher !== undefined ? { voucher } : {}),
47
+ ...(cash !== undefined ? { cash } : {}),
48
+ };
49
+ }
50
+
51
+ export interface MoonshotStatusConfig {
52
+ id: string;
53
+ providerId: string;
54
+ name: string;
55
+ balanceUrl: string;
56
+ /** Official docs: international balances are USD; China balances are CNY. */
57
+ unit: string;
58
+ }
59
+
60
+ export function createMoonshotStatusAdapter(config: MoonshotStatusConfig, requestTimeoutMs: number): StatusAdapter {
61
+ const unit = config.unit;
62
+ return {
63
+ id: config.id,
64
+ providerId: config.providerId,
65
+ name: config.name,
66
+ cacheTtlMs: 60_000,
67
+ requestTimeoutMs,
68
+ async fetch(context): Promise<StatusSnapshot> {
69
+ const key = await context.getApiKey();
70
+ if (!key || key === "proxy-managed") {
71
+ throw new ProviderDataError(`${config.name} status requires an API key`, "auth");
72
+ }
73
+ const response = await context.fetch(config.balanceUrl, {
74
+ headers: {
75
+ Accept: "application/json",
76
+ "Accept-Encoding": "identity",
77
+ Authorization: `Bearer ${key}`,
78
+ "User-Agent": "@hyav/pi-provider",
79
+ },
80
+ signal: context.signal,
81
+ });
82
+ if (!response.ok) {
83
+ throw new ProviderDataError(
84
+ `${config.name} status failed: HTTP ${response.status}`,
85
+ `http${response.status}`,
86
+ parseRetryAfter(response.headers.get("retry-after"), context.now()),
87
+ response.status,
88
+ );
89
+ }
90
+ let payload: unknown;
91
+ try {
92
+ payload = await response.json();
93
+ } catch {
94
+ throw new ProviderDataError(`${config.name} status returned invalid JSON`, "badjson");
95
+ }
96
+ const balance = parseMoonshotBalance(payload);
97
+ const entries: StatusEntry[] = [
98
+ {
99
+ kind: "amount",
100
+ id: "available-balance",
101
+ label: "Available balance",
102
+ value: balance.available,
103
+ unit,
104
+ },
105
+ ];
106
+ if (balance.voucher !== undefined) {
107
+ entries.push({
108
+ kind: "amount",
109
+ id: "voucher-balance",
110
+ label: "Voucher balance",
111
+ value: balance.voucher,
112
+ unit,
113
+ });
114
+ }
115
+ if (balance.cash !== undefined) {
116
+ entries.push({
117
+ kind: "amount",
118
+ id: "cash-balance",
119
+ label: "Cash balance",
120
+ value: balance.cash,
121
+ unit,
122
+ });
123
+ }
124
+ return { entries, updatedAt: context.now() };
125
+ },
126
+ };
127
+ }
128
+
129
+ export const moonshotaiStatusAdapter = createMoonshotStatusAdapter(
130
+ {
131
+ id: "moonshotai-status",
132
+ providerId: "moonshotai",
133
+ name: "Moonshot (Kimi)",
134
+ balanceUrl: MOONSHOT_BALANCE_URL,
135
+ unit: "USD",
136
+ },
137
+ 8_000,
138
+ );
139
+
140
+ export function createMoonshotaiStatusAdapter(requestTimeoutMs: number): StatusAdapter {
141
+ return { ...moonshotaiStatusAdapter, requestTimeoutMs };
142
+ }
143
+
144
+ const moonshotaiStatusExtension = defineStatusExtension({
145
+ id: "moonshotai-status",
146
+ providerId: "moonshotai",
147
+ create: ({ statusRequestTimeoutMs }) => createMoonshotaiStatusAdapter(statusRequestTimeoutMs),
148
+ });
149
+
150
+ export default moonshotaiStatusExtension;