@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,27 @@
1
+ import type { PreflightAdapter } from "@hyav/pi-provider";
2
+ import { definePreflightExtension } from "@hyav/pi-provider";
3
+ import { createCatalogPreflightAdapter } from "../core/catalog-preflight.ts";
4
+
5
+ export const MISTRAL_MODELS_URL = "https://api.mistral.ai/v1/models";
6
+
7
+ export const mistralPreflightAdapter: PreflightAdapter = createCatalogPreflightAdapter(
8
+ {
9
+ id: "mistral-preflight",
10
+ providerId: "mistral",
11
+ name: "Mistral",
12
+ modelsUrl: MISTRAL_MODELS_URL,
13
+ },
14
+ 8_000,
15
+ );
16
+
17
+ export function createMistralPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
18
+ return { ...mistralPreflightAdapter, requestTimeoutMs };
19
+ }
20
+
21
+ const mistralPreflightExtension = definePreflightExtension({
22
+ id: "mistral-preflight",
23
+ providerId: "mistral",
24
+ create: ({ statusRequestTimeoutMs }) => createMistralPreflightAdapter(statusRequestTimeoutMs),
25
+ });
26
+
27
+ export default mistralPreflightExtension;
@@ -0,0 +1,27 @@
1
+ import type { PreflightAdapter } from "@hyav/pi-provider";
2
+ import { definePreflightExtension } from "@hyav/pi-provider";
3
+ import { createMoonshotPreflightAdapter, MOONSHOT_CN_MODELS_URL } from "./moonshotai.ts";
4
+
5
+ export const moonshotaiCnPreflightAdapter: PreflightAdapter = createMoonshotPreflightAdapter(
6
+ MOONSHOT_CN_MODELS_URL,
7
+ 8_000,
8
+ "moonshotai-cn-preflight",
9
+ "moonshotai-cn",
10
+ );
11
+
12
+ export function createMoonshotaiCnPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
13
+ return createMoonshotPreflightAdapter(
14
+ MOONSHOT_CN_MODELS_URL,
15
+ requestTimeoutMs,
16
+ "moonshotai-cn-preflight",
17
+ "moonshotai-cn",
18
+ );
19
+ }
20
+
21
+ const moonshotaiCnPreflightExtension = definePreflightExtension({
22
+ id: "moonshotai-cn-preflight",
23
+ providerId: "moonshotai-cn",
24
+ create: ({ statusRequestTimeoutMs }) => createMoonshotaiCnPreflightAdapter(statusRequestTimeoutMs),
25
+ });
26
+
27
+ export default moonshotaiCnPreflightExtension;
@@ -0,0 +1,37 @@
1
+ import type { PreflightAdapter } from "@hyav/pi-provider";
2
+ import { definePreflightExtension } from "@hyav/pi-provider";
3
+ import { createCatalogPreflightAdapter } from "../core/catalog-preflight.ts";
4
+
5
+ export const MOONSHOT_MODELS_URL = "https://api.moonshot.ai/v1/models";
6
+ export const MOONSHOT_CN_MODELS_URL = "https://api.moonshot.cn/v1/models";
7
+
8
+ export function createMoonshotPreflightAdapter(
9
+ modelsUrl: string,
10
+ requestTimeoutMs: number,
11
+ id: "moonshotai-preflight" | "moonshotai-cn-preflight" = "moonshotai-preflight",
12
+ providerId: "moonshotai" | "moonshotai-cn" = "moonshotai",
13
+ ): PreflightAdapter {
14
+ return createCatalogPreflightAdapter(
15
+ {
16
+ id,
17
+ providerId,
18
+ name: providerId === "moonshotai-cn" ? "Moonshot CN (Kimi)" : "Moonshot (Kimi)",
19
+ modelsUrl,
20
+ },
21
+ requestTimeoutMs,
22
+ );
23
+ }
24
+
25
+ export const moonshotaiPreflightAdapter = createMoonshotPreflightAdapter(MOONSHOT_MODELS_URL, 8_000);
26
+
27
+ export function createMoonshotaiPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
28
+ return { ...moonshotaiPreflightAdapter, requestTimeoutMs };
29
+ }
30
+
31
+ const moonshotaiPreflightExtension = definePreflightExtension({
32
+ id: "moonshotai-preflight",
33
+ providerId: "moonshotai",
34
+ create: ({ statusRequestTimeoutMs }) => createMoonshotPreflightAdapter(MOONSHOT_MODELS_URL, statusRequestTimeoutMs),
35
+ });
36
+
37
+ export default moonshotaiPreflightExtension;
@@ -0,0 +1,27 @@
1
+ import type { PreflightAdapter } from "@hyav/pi-provider";
2
+ import { definePreflightExtension } from "@hyav/pi-provider";
3
+ import { createCatalogPreflightAdapter } from "../core/catalog-preflight.ts";
4
+
5
+ export const NVIDIA_MODELS_URL = "https://integrate.api.nvidia.com/v1/models";
6
+
7
+ export const nvidiaPreflightAdapter: PreflightAdapter = createCatalogPreflightAdapter(
8
+ {
9
+ id: "nvidia-preflight",
10
+ providerId: "nvidia",
11
+ name: "NVIDIA NIM",
12
+ modelsUrl: NVIDIA_MODELS_URL,
13
+ },
14
+ 8_000,
15
+ );
16
+
17
+ export function createNvidiaPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
18
+ return { ...nvidiaPreflightAdapter, requestTimeoutMs };
19
+ }
20
+
21
+ const nvidiaPreflightExtension = definePreflightExtension({
22
+ id: "nvidia-preflight",
23
+ providerId: "nvidia",
24
+ create: ({ statusRequestTimeoutMs }) => createNvidiaPreflightAdapter(statusRequestTimeoutMs),
25
+ });
26
+
27
+ export default nvidiaPreflightExtension;
@@ -0,0 +1,27 @@
1
+ import type { PreflightAdapter } from "@hyav/pi-provider";
2
+ import { definePreflightExtension } from "@hyav/pi-provider";
3
+ import { createCatalogPreflightAdapter } from "../core/catalog-preflight.ts";
4
+
5
+ export const OPENAI_MODELS_URL = "https://api.openai.com/v1/models";
6
+
7
+ export const openAIPreflightAdapter: PreflightAdapter = createCatalogPreflightAdapter(
8
+ {
9
+ id: "openai-preflight",
10
+ providerId: "openai",
11
+ name: "OpenAI",
12
+ modelsUrl: OPENAI_MODELS_URL,
13
+ },
14
+ 8_000,
15
+ );
16
+
17
+ export function createOpenAIPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
18
+ return { ...openAIPreflightAdapter, requestTimeoutMs };
19
+ }
20
+
21
+ const openAIPreflightExtension = definePreflightExtension({
22
+ id: "openai-preflight",
23
+ providerId: "openai",
24
+ create: ({ statusRequestTimeoutMs }) => createOpenAIPreflightAdapter(statusRequestTimeoutMs),
25
+ });
26
+
27
+ export default openAIPreflightExtension;
@@ -0,0 +1,111 @@
1
+ import type { PreflightAdapter } from "@hyav/pi-provider";
2
+ import { definePreflightExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
3
+ import { OPENROUTER_KEY_URL } from "../status/openrouter.ts";
4
+
5
+ export const OPENROUTER_MODELS_URL = "https://openrouter.ai/api/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
+ async function collectModelIds(context: Parameters<PreflightAdapter["fetch"]>[0]): Promise<Set<string>> {
12
+ const response = await context.fetch(OPENROUTER_MODELS_URL, {
13
+ headers: {
14
+ Accept: "application/json",
15
+ "Accept-Encoding": "identity",
16
+ "User-Agent": "@hyav/pi-provider",
17
+ },
18
+ signal: context.signal,
19
+ });
20
+ if (!response.ok) {
21
+ throw new ProviderDataError(
22
+ `OpenRouter preflight failed: HTTP ${response.status}`,
23
+ `http${response.status}`,
24
+ parseRetryAfter(response.headers.get("retry-after"), context.now()),
25
+ response.status,
26
+ );
27
+ }
28
+ let payload: unknown;
29
+ try {
30
+ payload = await response.json();
31
+ } catch {
32
+ throw new ProviderDataError("OpenRouter preflight returned invalid JSON", "badjson");
33
+ }
34
+ if (!isRecord(payload) || !Array.isArray(payload.data)) {
35
+ throw new ProviderDataError("OpenRouter preflight returned invalid catalog data", "badjson");
36
+ }
37
+ return new Set(
38
+ payload.data
39
+ .filter(isRecord)
40
+ .map((model) => (typeof model.id === "string" ? model.id.trim() : undefined))
41
+ .filter((id): id is string => id !== undefined && id !== ""),
42
+ );
43
+ }
44
+
45
+ async function checkCredential(context: Parameters<PreflightAdapter["fetch"]>[0], apiKey: string): Promise<number> {
46
+ const response = await context.fetch(OPENROUTER_KEY_URL, {
47
+ headers: {
48
+ Accept: "application/json",
49
+ "Accept-Encoding": "identity",
50
+ Authorization: `Bearer ${apiKey}`,
51
+ "User-Agent": "@hyav/pi-provider",
52
+ },
53
+ signal: context.signal,
54
+ });
55
+ if (response.status === 404) return response.status;
56
+ if (!response.ok) {
57
+ throw new ProviderDataError(
58
+ `OpenRouter preflight failed: HTTP ${response.status}`,
59
+ `http${response.status}`,
60
+ parseRetryAfter(response.headers.get("retry-after"), context.now()),
61
+ response.status,
62
+ );
63
+ }
64
+ let payload: unknown;
65
+ try {
66
+ payload = await response.json();
67
+ } catch {
68
+ throw new ProviderDataError("OpenRouter preflight returned invalid JSON", "badjson");
69
+ }
70
+ if (!isRecord(payload) || !isRecord(payload.data) || typeof payload.data.label !== "string") {
71
+ throw new ProviderDataError("OpenRouter preflight returned an invalid key response", "badjson");
72
+ }
73
+ return response.status;
74
+ }
75
+
76
+ export const openRouterPreflightAdapter: PreflightAdapter = {
77
+ id: "openrouter-preflight",
78
+ providerId: "openrouter",
79
+ name: "OpenRouter",
80
+ cacheTtlMs: 30_000,
81
+ requestTimeoutMs: 8_000,
82
+ async fetch(context) {
83
+ const modelIds = await collectModelIds(context);
84
+ const apiKey = await context.getApiKey();
85
+ const checks: string[] = ["endpoint", "catalog"];
86
+ if (!apiKey || apiKey === "proxy-managed") {
87
+ return { passed: modelIds.has(context.model.id), checks: [...checks, "auth"], updatedAt: context.now() };
88
+ }
89
+ // Management keys use /api/v1/credits as the only key endpoint and get 404 here.
90
+ const authStatus = await checkCredential(context, apiKey);
91
+ const authPassed = authStatus !== 404;
92
+ checks.push("auth");
93
+ return {
94
+ passed: modelIds.has(context.model.id) && authPassed,
95
+ checks,
96
+ updatedAt: context.now(),
97
+ };
98
+ },
99
+ };
100
+
101
+ export function createOpenRouterPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
102
+ return { ...openRouterPreflightAdapter, requestTimeoutMs };
103
+ }
104
+
105
+ const openRouterPreflightExtension = definePreflightExtension({
106
+ id: "openrouter-preflight",
107
+ providerId: "openrouter",
108
+ create: ({ statusRequestTimeoutMs }) => createOpenRouterPreflightAdapter(statusRequestTimeoutMs),
109
+ });
110
+
111
+ export default openRouterPreflightExtension;
@@ -0,0 +1,86 @@
1
+ import type { PreflightAdapter, PreflightSnapshot } from "@hyav/pi-provider";
2
+ import { definePreflightExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
3
+ import { VERCEL_PROVIDER_ID } from "../status/vercel-ai-gateway/constants.ts";
4
+
5
+ export const VERCEL_MODELS_URL = "https://ai-gateway.vercel.sh/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
+ export function parseVercelModelIds(payload: unknown): Set<string> {
12
+ if (!isRecord(payload) || !Array.isArray(payload.data)) {
13
+ throw new ProviderDataError("Vercel AI Gateway preflight returned invalid catalog data", "badjson");
14
+ }
15
+
16
+ const modelIds = new Set<string>();
17
+ for (const value of payload.data) {
18
+ if (!isRecord(value)) continue;
19
+ // Mixed-type gateway catalogs can include non-language entries.
20
+ if (value.type !== undefined && value.type !== "language") continue;
21
+ if (typeof value.id !== "string") continue;
22
+ const id = value.id.trim();
23
+ if (id !== "") modelIds.add(id);
24
+ }
25
+
26
+ if (modelIds.size === 0) {
27
+ throw new ProviderDataError("Vercel AI Gateway preflight returned an empty catalog", "badjson");
28
+ }
29
+ return modelIds;
30
+ }
31
+
32
+ export function createVercelAIGatewayPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
33
+ return {
34
+ id: "vercel-ai-gateway-preflight",
35
+ providerId: VERCEL_PROVIDER_ID,
36
+ name: "Vercel AI Gateway",
37
+ cacheTtlMs: 30_000,
38
+ requestTimeoutMs,
39
+ async fetch(context): Promise<PreflightSnapshot> {
40
+ const key = await context.getApiKey();
41
+ if (!key || key === "proxy-managed") {
42
+ return { passed: false, checks: ["auth"], updatedAt: context.now() };
43
+ }
44
+
45
+ const response = await context.fetch(VERCEL_MODELS_URL, {
46
+ headers: {
47
+ Accept: "application/json",
48
+ "Accept-Encoding": "identity",
49
+ },
50
+ signal: context.signal,
51
+ });
52
+ if (!response.ok) {
53
+ throw new ProviderDataError(
54
+ `Vercel AI Gateway preflight failed: HTTP ${response.status}`,
55
+ `http${response.status}`,
56
+ parseRetryAfter(response.headers.get("retry-after"), context.now()),
57
+ response.status,
58
+ );
59
+ }
60
+
61
+ let payload: unknown;
62
+ try {
63
+ payload = await response.json();
64
+ } catch {
65
+ throw new ProviderDataError("Vercel AI Gateway preflight returned invalid JSON", "badjson");
66
+ }
67
+
68
+ return {
69
+ passed: parseVercelModelIds(payload).has(context.model.id),
70
+ checks: ["endpoint", "auth", "catalog"],
71
+ updatedAt: context.now(),
72
+ httpStatus: response.status,
73
+ };
74
+ },
75
+ };
76
+ }
77
+
78
+ export const vercelAIGatewayPreflightAdapter = createVercelAIGatewayPreflightAdapter(8_000);
79
+
80
+ const vercelAIGatewayPreflightExtension = definePreflightExtension({
81
+ id: "vercel-ai-gateway-preflight",
82
+ providerId: VERCEL_PROVIDER_ID,
83
+ create: ({ statusRequestTimeoutMs }) => createVercelAIGatewayPreflightAdapter(statusRequestTimeoutMs),
84
+ });
85
+
86
+ export default vercelAIGatewayPreflightExtension;
@@ -0,0 +1,70 @@
1
+ import type { PreflightAdapter } from "@hyav/pi-provider";
2
+ import { definePreflightExtension, ProviderDataError, parseRetryAfter } from "@hyav/pi-provider";
3
+ import { XAI_MODELS_URL } from "../status/xai.ts";
4
+
5
+ function isRecord(value: unknown): value is Record<string, unknown> {
6
+ return value !== null && typeof value === "object" && !Array.isArray(value);
7
+ }
8
+
9
+ export const xaiPreflightAdapter: PreflightAdapter = {
10
+ id: "xai-preflight",
11
+ providerId: "xai",
12
+ name: "xAI",
13
+ cacheTtlMs: 30_000,
14
+ requestTimeoutMs: 8_000,
15
+ async fetch(context) {
16
+ const apiKey = await context.getApiKey();
17
+ const authHeaders: Record<string, string> = {
18
+ Accept: "application/json",
19
+ "Accept-Encoding": "identity",
20
+ "User-Agent": "@hyav/pi-provider",
21
+ };
22
+ if (apiKey && apiKey !== "proxy-managed") authHeaders.Authorization = `Bearer ${apiKey}`;
23
+ const response = await context.fetch(XAI_MODELS_URL, {
24
+ headers: authHeaders,
25
+ signal: context.signal,
26
+ });
27
+ if (!response.ok) {
28
+ throw new ProviderDataError(
29
+ `xAI preflight failed: HTTP ${response.status}`,
30
+ `http${response.status}`,
31
+ parseRetryAfter(response.headers.get("retry-after"), context.now()),
32
+ response.status,
33
+ );
34
+ }
35
+ let payload: unknown;
36
+ try {
37
+ payload = await response.json();
38
+ } catch {
39
+ throw new ProviderDataError("xAI preflight returned invalid JSON", "badjson");
40
+ }
41
+ if (!isRecord(payload) || !Array.isArray(payload.data)) {
42
+ throw new ProviderDataError("xAI preflight returned invalid catalog data", "badjson");
43
+ }
44
+ const modelIds = new Set(
45
+ payload.data
46
+ .filter(isRecord)
47
+ .map((model) => (typeof model.id === "string" ? model.id.trim() : undefined))
48
+ .filter((id): id is string => id !== undefined && id !== ""),
49
+ );
50
+ const checks = apiKey && apiKey !== "proxy-managed" ? ["endpoint", "catalog", "auth"] : ["endpoint", "catalog"];
51
+ return {
52
+ passed: modelIds.has(context.model.id),
53
+ checks,
54
+ updatedAt: context.now(),
55
+ httpStatus: response.status,
56
+ };
57
+ },
58
+ };
59
+
60
+ export function createXaiPreflightAdapter(requestTimeoutMs: number): PreflightAdapter {
61
+ return { ...xaiPreflightAdapter, requestTimeoutMs };
62
+ }
63
+
64
+ const xaiPreflightExtension = definePreflightExtension({
65
+ id: "xai-preflight",
66
+ providerId: "xai",
67
+ create: ({ statusRequestTimeoutMs }) => createXaiPreflightAdapter(statusRequestTimeoutMs),
68
+ });
69
+
70
+ export default xaiPreflightExtension;
@@ -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;
@@ -21,7 +21,7 @@ export const hyperStatusAdapter: StatusAdapter = {
21
21
  id: "charm-hyper-status",
22
22
  providerId: "charm-hyper",
23
23
  name: "Charm Hyper",
24
- cacheTtlMs: 30_000,
24
+ cacheTtlMs: 60_000,
25
25
  requestTimeoutMs: 8_000,
26
26
  async fetch(context): Promise<StatusSnapshot> {
27
27
  const key = await context.getApiKey();