@oh-my-pi/pi-ai 18.2.7 → 18.2.9

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.
Files changed (133) hide show
  1. package/CHANGELOG.md +49 -18
  2. package/dist/types/auth-gateway/dispatch.d.ts +80 -0
  3. package/dist/types/auth-gateway/http.d.ts +5 -6
  4. package/dist/types/auth-gateway/index.d.ts +1 -0
  5. package/dist/types/auth-gateway/routes/embeddings.d.ts +3 -0
  6. package/dist/types/auth-gateway/routes/images.d.ts +3 -0
  7. package/dist/types/auth-gateway/routes/rerank.d.ts +3 -0
  8. package/dist/types/auth-gateway/routes/speech.d.ts +2 -0
  9. package/dist/types/auth-gateway/routes/systemone.d.ts +2 -0
  10. package/dist/types/auth-gateway/routes/transcriptions.d.ts +3 -0
  11. package/dist/types/auth-gateway/routes/video.d.ts +7 -0
  12. package/dist/types/auth-gateway/server.d.ts +10 -16
  13. package/dist/types/auth-gateway/types.d.ts +5 -0
  14. package/dist/types/auth-storage.d.ts +35 -32
  15. package/dist/types/embeddings/index.d.ts +7 -0
  16. package/dist/types/embeddings/openai-embeddings.d.ts +15 -0
  17. package/dist/types/embeddings/types.d.ts +15 -0
  18. package/dist/types/images/google-antigravity.d.ts +9 -0
  19. package/dist/types/images/google-generative-ai.d.ts +3 -0
  20. package/dist/types/images/index.d.ts +14 -0
  21. package/dist/types/images/openai-hosted.d.ts +3 -0
  22. package/dist/types/images/openai-images.d.ts +5 -0
  23. package/dist/types/images/openrouter-images.d.ts +3 -0
  24. package/dist/types/images/shared.d.ts +34 -0
  25. package/dist/types/images/types.d.ts +31 -0
  26. package/dist/types/index.d.ts +8 -1
  27. package/dist/types/judgment/typesafe.d.ts +2 -0
  28. package/dist/types/providers/amazon-bedrock.d.ts +7 -0
  29. package/dist/types/providers/claude-code-fingerprint.d.ts +22 -3
  30. package/dist/types/providers/embeddings-server.d.ts +32 -0
  31. package/dist/types/providers/google-gemini-cli.d.ts +0 -2
  32. package/dist/types/providers/images-server.d.ts +22 -0
  33. package/dist/types/providers/openai-chat-server-schema.d.ts +2 -2
  34. package/dist/types/providers/rerank-server.d.ts +35 -0
  35. package/dist/types/providers/speech-server.d.ts +8 -0
  36. package/dist/types/providers/systemone-server.d.ts +26 -0
  37. package/dist/types/providers/transcriptions-server.d.ts +32 -0
  38. package/dist/types/providers/video-server.d.ts +39 -0
  39. package/dist/types/rerank/index.d.ts +7 -0
  40. package/dist/types/rerank/openrouter-rerank.d.ts +15 -0
  41. package/dist/types/rerank/types.d.ts +17 -0
  42. package/dist/types/speech/index.d.ts +13 -0
  43. package/dist/types/speech/openai-speech.d.ts +3 -0
  44. package/dist/types/speech/transport.d.ts +7 -0
  45. package/dist/types/speech/types.d.ts +24 -0
  46. package/dist/types/speech/xai-tts.d.ts +7 -0
  47. package/dist/types/transcription/index.d.ts +7 -0
  48. package/dist/types/transcription/openai-transcriptions.d.ts +15 -0
  49. package/dist/types/transcription/types.d.ts +41 -0
  50. package/dist/types/usage/claude-api.d.ts +22 -0
  51. package/dist/types/usage/claude-reset.d.ts +44 -0
  52. package/dist/types/usage.d.ts +111 -5
  53. package/dist/types/utils/schema/json-schema-validator.d.ts +5 -2
  54. package/dist/types/utils/tool-call-loop-guard.d.ts +1 -1
  55. package/dist/types/video/index.d.ts +11 -0
  56. package/dist/types/video/openrouter-video.d.ts +19 -0
  57. package/dist/types/video/types.d.ts +62 -0
  58. package/package.json +30 -6
  59. package/src/auth/sqlite-credential-store.ts +44 -1
  60. package/src/auth-broker/remote-store.ts +6 -6
  61. package/src/auth-broker/wire-schemas.ts +14 -0
  62. package/src/auth-gateway/dispatch.ts +273 -0
  63. package/src/auth-gateway/http.ts +6 -7
  64. package/src/auth-gateway/index.ts +1 -0
  65. package/src/auth-gateway/routes/embeddings.ts +98 -0
  66. package/src/auth-gateway/routes/images.ts +131 -0
  67. package/src/auth-gateway/routes/rerank.ts +87 -0
  68. package/src/auth-gateway/routes/speech.ts +101 -0
  69. package/src/auth-gateway/routes/systemone.ts +116 -0
  70. package/src/auth-gateway/routes/transcriptions.ts +98 -0
  71. package/src/auth-gateway/routes/video.ts +243 -0
  72. package/src/auth-gateway/server.ts +127 -260
  73. package/src/auth-gateway/types.ts +5 -0
  74. package/src/auth-storage.ts +263 -140
  75. package/src/embeddings/index.ts +17 -0
  76. package/src/embeddings/openai-embeddings.ts +141 -0
  77. package/src/embeddings/types.ts +14 -0
  78. package/src/error/flags.ts +10 -0
  79. package/src/error/rate-limit.ts +1 -1
  80. package/src/images/google-antigravity.ts +180 -0
  81. package/src/images/google-generative-ai.ts +92 -0
  82. package/src/images/index.ts +59 -0
  83. package/src/images/openai-hosted.ts +185 -0
  84. package/src/images/openai-images.ts +110 -0
  85. package/src/images/openrouter-images.ts +33 -0
  86. package/src/images/shared.ts +193 -0
  87. package/src/images/types.ts +36 -0
  88. package/src/index.ts +8 -1
  89. package/src/judgment/typesafe.ts +5 -0
  90. package/src/providers/amazon-bedrock.ts +55 -5
  91. package/src/providers/anthropic.ts +45 -11
  92. package/src/providers/aws-credentials.ts +124 -11
  93. package/src/providers/claude-code-fingerprint.ts +55 -3
  94. package/src/providers/embeddings-server.ts +151 -0
  95. package/src/providers/gitlab-duo.ts +20 -4
  96. package/src/providers/google-gemini-cli.ts +0 -8
  97. package/src/providers/google-shared.ts +1 -18
  98. package/src/providers/images-server.ts +159 -0
  99. package/src/providers/openai-chat-server-schema.ts +1 -1
  100. package/src/providers/openai-chat-server.ts +3 -1
  101. package/src/providers/openai-codex-responses.ts +27 -5
  102. package/src/providers/openai-completions.ts +122 -19
  103. package/src/providers/pi-native-server.ts +1 -0
  104. package/src/providers/rerank-server.ts +166 -0
  105. package/src/providers/speech-server.ts +53 -0
  106. package/src/providers/systemone-server.ts +73 -0
  107. package/src/providers/transcriptions-server.ts +243 -0
  108. package/src/providers/video-server.ts +286 -0
  109. package/src/registry/oauth/anthropic.ts +2 -3
  110. package/src/rerank/index.ts +13 -0
  111. package/src/rerank/openrouter-rerank.ts +136 -0
  112. package/src/rerank/types.ts +20 -0
  113. package/src/speech/index.ts +35 -0
  114. package/src/speech/openai-speech.ts +26 -0
  115. package/src/speech/transport.ts +66 -0
  116. package/src/speech/types.ts +37 -0
  117. package/src/speech/xai-tts.ts +41 -0
  118. package/src/stream.ts +13 -4
  119. package/src/transcription/index.ts +17 -0
  120. package/src/transcription/openai-transcriptions.ts +133 -0
  121. package/src/transcription/types.ts +46 -0
  122. package/src/usage/alibaba-token-plan.ts +7 -1
  123. package/src/usage/claude-api.ts +66 -0
  124. package/src/usage/claude-reset.ts +638 -0
  125. package/src/usage/claude.ts +37 -59
  126. package/src/usage/kimi.ts +32 -1
  127. package/src/usage.ts +52 -5
  128. package/src/utils/schema/json-schema-validator.ts +23 -10
  129. package/src/utils/tool-call-loop-guard.ts +2 -2
  130. package/src/utils/validation.ts +145 -50
  131. package/src/video/index.ts +34 -0
  132. package/src/video/openrouter-video.ts +210 -0
  133. package/src/video/types.ts +72 -0
@@ -0,0 +1,41 @@
1
+ import type { Api, Model } from "@oh-my-pi/pi-catalog/types";
2
+ import * as AIError from "../error";
3
+ import { postSpeechRequest } from "./transport";
4
+ import type { SpeechOptions, SpeechRequest, SpeechResult } from "./types";
5
+
6
+ export const DEFAULT_XAI_VOICE_ID = "eve";
7
+ export const DEFAULT_XAI_SAMPLE_RATE = 24_000;
8
+ export const DEFAULT_XAI_BIT_RATE = 128_000;
9
+ export const XAI_MAX_TEXT_LENGTH = 15_000;
10
+
11
+ export async function synthesizeXaiSpeech(
12
+ model: Model<Api>,
13
+ request: SpeechRequest,
14
+ options: SpeechOptions,
15
+ ): Promise<SpeechResult> {
16
+ if (request.text.length > XAI_MAX_TEXT_LENGTH) {
17
+ throw new AIError.ValidationError(`xai-tts input exceeds the ${XAI_MAX_TEXT_LENGTH}-character limit`);
18
+ }
19
+ if (request.format !== "mp3" && request.format !== "wav") {
20
+ throw new AIError.ValidationError(`xai-tts does not support ${request.format} output; use mp3 or wav`);
21
+ }
22
+ if (request.speed !== undefined) throw new AIError.ValidationError("xai-tts does not support speed");
23
+ if (request.instructions !== undefined) throw new AIError.ValidationError("xai-tts does not support instructions");
24
+
25
+ const sampleRate = request.sampleRate ?? DEFAULT_XAI_SAMPLE_RATE;
26
+ const bitRate = request.bitRate ?? DEFAULT_XAI_BIT_RATE;
27
+ const payload: Record<string, unknown> = {
28
+ text: request.text,
29
+ voice_id: request.voice ?? DEFAULT_XAI_VOICE_ID,
30
+ };
31
+ const codecOverridden = request.format !== "mp3";
32
+ const sampleRateOverridden = sampleRate !== DEFAULT_XAI_SAMPLE_RATE;
33
+ const bitRateOverridden = request.format === "mp3" && bitRate !== DEFAULT_XAI_BIT_RATE;
34
+ if (codecOverridden || sampleRateOverridden || bitRateOverridden) {
35
+ const outputFormat: Record<string, unknown> = { codec: request.format };
36
+ if (sampleRate > 0) outputFormat.sample_rate = sampleRate;
37
+ if (request.format === "mp3" && bitRate > 0) outputFormat.bit_rate = bitRate;
38
+ payload.output_format = outputFormat;
39
+ }
40
+ return postSpeechRequest(model, "/tts", payload, request.format, options);
41
+ }
package/src/stream.ts CHANGED
@@ -1841,7 +1841,7 @@ function resolveBedrockThinkingBudget(
1841
1841
  model: Model<"bedrock-converse-stream">,
1842
1842
  options?: SimpleStreamOptions,
1843
1843
  ): { budget: number; level: Effort } | null {
1844
- if (!options?.reasoning || !model.reasoning) return null;
1844
+ if (!options?.reasoning || !model.reasoning || options.disableReasoning || options.forceReasoningOff) return null;
1845
1845
  const level = requireSupportedEffort(model, options.reasoning);
1846
1846
  const budget = options.thinkingBudgets?.[level] ?? BEDROCK_CLAUDE_THINKING[level];
1847
1847
  return { budget, level };
@@ -2167,7 +2167,11 @@ function mapOptionsForApi<TApi extends Api>(
2167
2167
  case "bedrock-converse-stream": {
2168
2168
  const bedrockBase: BedrockOptions = {
2169
2169
  ...base,
2170
- reasoning: options?.reasoning,
2170
+ // Explicit reasoning-off must fold here like the anthropic-messages
2171
+ // branch: the provider gates thinking only on `reasoning`, and the
2172
+ // budget path below must not inflate a capped request for thinking
2173
+ // that was turned off.
2174
+ reasoning: options?.disableReasoning || options?.forceReasoningOff ? undefined : options?.reasoning,
2171
2175
  thinkingBudgets: options?.thinkingBudgets,
2172
2176
  toolChoice: mapAnthropicToolChoice(options?.toolChoice),
2173
2177
  thinkingDisplay: options?.hideThinkingSummary ? "omitted" : undefined,
@@ -2212,6 +2216,9 @@ function mapOptionsForApi<TApi extends Api>(
2212
2216
  openrouterVariant: options?.openrouterVariant,
2213
2217
  maxTokensExplicit: rawOptions?.maxTokens !== undefined,
2214
2218
  disableReasoning: options?.disableReasoning,
2219
+ // Forwarded, not folded: the Responses record reads both flags
2220
+ // itself (`applyResponsesCompatPolicy`).
2221
+ forceReasoningOff: options?.forceReasoningOff,
2215
2222
  textVerbosity: options?.textVerbosity,
2216
2223
  promptCache: options?.promptCache,
2217
2224
  statefulResponses: options?.statefulResponses,
@@ -2220,7 +2227,8 @@ function mapOptionsForApi<TApi extends Api>(
2220
2227
  return castApi<"openai-completions">({
2221
2228
  ...base,
2222
2229
  reasoning: resolveOpenAiReasoningEffort(model, options),
2223
- disableReasoning: options?.disableReasoning,
2230
+ // `OpenAICompletionsOptions` carries no forceReasoningOff; fold it.
2231
+ disableReasoning: options?.disableReasoning || options?.forceReasoningOff,
2224
2232
  toolChoice: mapOpenAiToolChoice(options?.toolChoice),
2225
2233
  serviceTier: options?.serviceTier,
2226
2234
  openrouterVariant: options?.openrouterVariant,
@@ -2233,7 +2241,8 @@ function mapOptionsForApi<TApi extends Api>(
2233
2241
  return castApi<"openai-completions">({
2234
2242
  ...base,
2235
2243
  reasoning: resolveOpenAiReasoningEffort(model, options),
2236
- disableReasoning: options?.disableReasoning,
2244
+ // `OpenAICompletionsOptions` carries no forceReasoningOff; fold it.
2245
+ disableReasoning: options?.disableReasoning || options?.forceReasoningOff,
2237
2246
  toolChoice: mapOpenAiToolChoice(options?.toolChoice),
2238
2247
  serviceTier: options?.serviceTier,
2239
2248
  openrouterVariant: options?.openrouterVariant,
@@ -0,0 +1,17 @@
1
+ import type { Api, Model } from "@oh-my-pi/pi-catalog/types";
2
+ import * as AIError from "../error";
3
+ import { transcribeOpenAI, type TranscriptionOptions } from "./openai-transcriptions";
4
+ import type { TranscriptionRequest, TranscriptionResult } from "./types";
5
+
6
+ export * from "./openai-transcriptions";
7
+ export * from "./types";
8
+
9
+ /** Dispatch an audio transcription through the transport selected by the catalog model. */
10
+ export function transcribeAudio(
11
+ model: Model<Api>,
12
+ request: TranscriptionRequest,
13
+ options: TranscriptionOptions,
14
+ ): Promise<TranscriptionResult> {
15
+ if (model.api === "openai-transcriptions") return transcribeOpenAI(model, request, options);
16
+ throw new AIError.ConfigurationError(`Unsupported transcription API: ${model.api}`);
17
+ }
@@ -0,0 +1,133 @@
1
+ import { calculateCost } from "@oh-my-pi/pi-catalog/models";
2
+ import type { Api, FetchImpl, Model, Usage } from "@oh-my-pi/pi-catalog/types";
3
+ import { type } from "@oh-my-pi/omptype";
4
+ import { type ApiKey, withAuth } from "../auth-retry";
5
+ import * as AIError from "../error";
6
+ import type { TranscriptionRequest, TranscriptionResult, TranscriptionSegment, TranscriptionWord } from "./types";
7
+
8
+ export interface TranscriptionOptions {
9
+ apiKey: ApiKey;
10
+ fetch?: FetchImpl;
11
+ signal?: AbortSignal;
12
+ }
13
+
14
+ /** Non-2xx response from an OpenAI-compatible transcription endpoint. */
15
+ export class TranscriptionApiError extends AIError.ProviderHttpError {
16
+ override readonly name = "TranscriptionApiError";
17
+ }
18
+
19
+ const upstreamResponseSchema = type({
20
+ text: "string",
21
+ "language?": "string",
22
+ "duration?": "number",
23
+ "segments?": "object[]",
24
+ "words?": "object[]",
25
+ "usage?": "object",
26
+ });
27
+
28
+ interface UpstreamUsage {
29
+ input_tokens?: unknown;
30
+ output_tokens?: unknown;
31
+ total_tokens?: unknown;
32
+ cost?: unknown;
33
+ seconds?: unknown;
34
+ }
35
+
36
+ function finiteNumber(value: unknown): number | undefined {
37
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
38
+ }
39
+
40
+ function decodeUsage(model: Model<Api>, raw: unknown): { usage: Usage; seconds?: number } {
41
+ const upstream = raw && typeof raw === "object" ? (raw as UpstreamUsage) : {};
42
+ const input = finiteNumber(upstream.input_tokens) ?? 0;
43
+ const output = finiteNumber(upstream.output_tokens) ?? 0;
44
+ const reportedTotal = finiteNumber(upstream.total_tokens);
45
+ const reportedCost = finiteNumber(upstream.cost);
46
+ const usage: Usage = {
47
+ input,
48
+ output,
49
+ cacheRead: 0,
50
+ cacheWrite: 0,
51
+ totalTokens: reportedTotal ?? input + output,
52
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: reportedCost ?? 0 },
53
+ };
54
+ if (reportedCost === undefined) calculateCost(model, usage);
55
+ return { usage, seconds: finiteNumber(upstream.seconds) };
56
+ }
57
+
58
+ async function responseError(response: Response, model: Model<Api>): Promise<TranscriptionApiError> {
59
+ const text = await response.text();
60
+ let detail = text;
61
+ let code: string | undefined;
62
+ try {
63
+ const parsed: unknown = JSON.parse(text);
64
+ if (parsed && typeof parsed === "object" && "error" in parsed) {
65
+ const error = parsed.error;
66
+ if (error && typeof error === "object") {
67
+ const envelope = error as { message?: unknown; code?: unknown; type?: unknown };
68
+ if (typeof envelope.message === "string") detail = envelope.message;
69
+ if (typeof envelope.code === "string") code = envelope.code;
70
+ else if (typeof envelope.type === "string") code = envelope.type;
71
+ }
72
+ }
73
+ } catch {}
74
+ return new TranscriptionApiError(
75
+ `${model.provider}/${model.id} transcription API error (${response.status}): ${detail || response.statusText}`,
76
+ response.status,
77
+ { headers: response.headers, code },
78
+ );
79
+ }
80
+
81
+ /** Call an OpenAI/OpenRouter-compatible multipart transcription endpoint. */
82
+ export async function transcribeOpenAI(
83
+ model: Model<Api>,
84
+ request: TranscriptionRequest,
85
+ options: TranscriptionOptions,
86
+ ): Promise<TranscriptionResult> {
87
+ const form = new FormData();
88
+ const fileName = request.fileName?.trim() || "audio";
89
+ form.append("file", new File([request.audio], fileName, { type: request.mimeType }));
90
+ form.append("model", model.id);
91
+ form.append("response_format", request.responseFormat);
92
+ if (request.language !== undefined) form.append("language", request.language);
93
+ if (request.prompt !== undefined) form.append("prompt", request.prompt);
94
+ if (request.temperature !== undefined) form.append("temperature", String(request.temperature));
95
+ for (const granularity of request.timestampGranularities ?? []) {
96
+ form.append("timestamp_granularities[]", granularity);
97
+ }
98
+
99
+ const fetchImpl = options.fetch ?? fetch;
100
+ const response = await withAuth(
101
+ options.apiKey,
102
+ async key => {
103
+ const attempt = await fetchImpl(`${model.baseUrl.replace(/\/+$/, "")}/audio/transcriptions`, {
104
+ method: "POST",
105
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
106
+ body: form,
107
+ signal: options.signal,
108
+ });
109
+ if (!attempt.ok) throw await responseError(attempt, model);
110
+ return attempt;
111
+ },
112
+ { signal: options.signal },
113
+ );
114
+
115
+ const body: unknown = await response.json();
116
+ const parsed = upstreamResponseSchema(body);
117
+ if (parsed instanceof type.errors) {
118
+ throw new AIError.ProviderResponseError(
119
+ `${model.provider}/${model.id} transcription response is malformed: ${parsed.summary}`,
120
+ { provider: model.provider, kind: "envelope" },
121
+ );
122
+ }
123
+ const decoded = decodeUsage(model, parsed.usage);
124
+ return {
125
+ text: parsed.text,
126
+ ...(parsed.language !== undefined && { language: parsed.language }),
127
+ ...(parsed.duration !== undefined && { duration: parsed.duration }),
128
+ ...(parsed.segments !== undefined && { segments: parsed.segments as TranscriptionSegment[] }),
129
+ ...(parsed.words !== undefined && { words: parsed.words as TranscriptionWord[] }),
130
+ ...(decoded.seconds !== undefined && { seconds: decoded.seconds }),
131
+ usage: decoded.usage,
132
+ };
133
+ }
@@ -0,0 +1,46 @@
1
+ import type { Usage } from "@oh-my-pi/pi-catalog/types";
2
+
3
+ export type TranscriptionResponseFormat = "json" | "verbose_json";
4
+ export type TranscriptionTimestampGranularity = "word" | "segment";
5
+
6
+ export interface TranscriptionRequest {
7
+ audio: Uint8Array;
8
+ mimeType: string;
9
+ fileName?: string;
10
+ language?: string;
11
+ prompt?: string;
12
+ temperature?: number;
13
+ responseFormat: TranscriptionResponseFormat;
14
+ timestampGranularities?: TranscriptionTimestampGranularity[];
15
+ }
16
+
17
+ /** Provider-specific segment fields are preserved alongside the normalized timestamps and text. */
18
+ export interface TranscriptionSegment {
19
+ id?: number | string;
20
+ start: number;
21
+ end: number;
22
+ text: string;
23
+ speaker?: number | string;
24
+ [key: string]: unknown;
25
+ }
26
+
27
+ /** Provider-specific word fields are preserved alongside the normalized timestamps and spelling. */
28
+ export interface TranscriptionWord {
29
+ word: string;
30
+ start: number;
31
+ end: number;
32
+ speaker?: number | string;
33
+ confidence?: number;
34
+ [key: string]: unknown;
35
+ }
36
+
37
+ export interface TranscriptionResult {
38
+ text: string;
39
+ language?: string;
40
+ duration?: number;
41
+ segments?: TranscriptionSegment[];
42
+ words?: TranscriptionWord[];
43
+ /** Provider-billed audio duration, which may be present without verbose output. */
44
+ seconds?: number;
45
+ usage: Usage;
46
+ }
@@ -46,7 +46,6 @@ const CHINA_CONSOLE = {
46
46
  protocol: "V2",
47
47
  console: "ONE_CONSOLE",
48
48
  productCode: "p_efm",
49
- switchAgent: 12608464,
50
49
  switchUserType: 3,
51
50
  domain: "bailian.console.aliyun.com",
52
51
  consoleSite: "BAILIAN_ALIYUN",
@@ -221,6 +220,13 @@ async function fetchAlibabaTokenPlanUsage(
221
220
  ctx.logger?.warn("Alibaba Token Plan usage response invalid", { provider: PROVIDER });
222
221
  return null;
223
222
  }
223
+ if (payload.data.success === false) {
224
+ ctx.logger?.warn("Alibaba Token Plan usage request rejected", {
225
+ provider: PROVIDER,
226
+ errorCode: typeof payload.data.errorCode === "string" ? payload.data.errorCode : "unknown",
227
+ });
228
+ return null;
229
+ }
224
230
  const responseData = unwrapGatewayData(payload.data);
225
231
  const limits = [
226
232
  buildLimit(
@@ -0,0 +1,66 @@
1
+ import { getClaudeCodeUserAgent } from "../providers/claude-code-fingerprint";
2
+
3
+ /** Canonical host for Claude's first-party account API. */
4
+ export const DEFAULT_CLAUDE_API_BASE_URL = "https://api.anthropic.com";
5
+ /** Canonical subscription usage and profile endpoint. */
6
+ export const DEFAULT_CLAUDE_OAUTH_BASE_URL = `${DEFAULT_CLAUDE_API_BASE_URL}/api/oauth`;
7
+ /** OAuth protocol beta required by Claude's account routes. */
8
+ export const CLAUDE_OAUTH_BETA = "oauth-2025-04-20";
9
+
10
+ /**
11
+ * Normalize Messages (`/v1`) and OAuth (`/api/oauth`) endpoints to the common
12
+ * API root used by both usage and reset routes. Custom path prefixes survive.
13
+ */
14
+ export function normalizeClaudeApiBaseUrl(baseUrl?: string): string {
15
+ if (!baseUrl?.trim()) return DEFAULT_CLAUDE_API_BASE_URL;
16
+ let url: URL;
17
+ try {
18
+ url = new URL(baseUrl.trim());
19
+ } catch {
20
+ return DEFAULT_CLAUDE_API_BASE_URL;
21
+ }
22
+ let path = url.pathname.replace(/\/+$/, "");
23
+ if (path === "/") path = "";
24
+ const lower = path.toLowerCase();
25
+ if (lower.endsWith("/api/oauth")) {
26
+ path = path.slice(0, -"/api/oauth".length);
27
+ } else if (lower.endsWith("/v1")) {
28
+ path = path.slice(0, -"/v1".length);
29
+ }
30
+ return `${url.origin}${path}`;
31
+ }
32
+
33
+ /** Resolve the OAuth API base while retaining a configured proxy path prefix. */
34
+ export function claudeOAuthBaseUrl(baseUrl?: string): string {
35
+ return `${normalizeClaudeApiBaseUrl(baseUrl)}/api/oauth`;
36
+ }
37
+
38
+ /** Configured OAuth endpoint followed by canonical fallback, without duplicates. */
39
+ export function claudeOAuthBaseUrls(baseUrl?: string): readonly string[] {
40
+ const configured = claudeOAuthBaseUrl(baseUrl);
41
+ return configured === DEFAULT_CLAUDE_OAUTH_BASE_URL
42
+ ? [DEFAULT_CLAUDE_OAUTH_BASE_URL]
43
+ : [configured, DEFAULT_CLAUDE_OAUTH_BASE_URL];
44
+ }
45
+
46
+ /** Resolve a first-party account route against the configured Claude API root. */
47
+ export function claudeApiUrl(baseUrl: string | undefined, path: string): string {
48
+ const suffix = path.startsWith("/") ? path : `/${path}`;
49
+ return `${normalizeClaudeApiBaseUrl(baseUrl)}${suffix}`;
50
+ }
51
+
52
+ /** Shared OAuth and CLI identity headers for Claude usage, profile, and resets. */
53
+ export function buildClaudeOAuthHeaders(
54
+ accessToken: string,
55
+ options: { beta?: string; json?: boolean } = {},
56
+ ): Record<string, string> {
57
+ return {
58
+ accept: "application/json, text/plain, */*",
59
+ "accept-encoding": "gzip, compress, deflate, br",
60
+ "anthropic-beta": options.beta ?? CLAUDE_OAUTH_BETA,
61
+ ...(options.json === false ? {} : { "content-type": "application/json" }),
62
+ connection: "keep-alive",
63
+ "user-agent": getClaudeCodeUserAgent(),
64
+ authorization: `Bearer ${accessToken}`,
65
+ };
66
+ }