opencode-anyrouter-auth 0.0.0-stage → 0.1.0

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/generic.mjs ADDED
@@ -0,0 +1,156 @@
1
+ import { cleanResponsesRequest, createFilteredFetch, defaultRetryDelay, fetchWithFilter,
2
+ historyErrorCode, retryErrorClass } from "./lib/responses-filter.mjs";
3
+ import { resolveModelMetadata } from "./lib/model-metadata.mjs";
4
+ import { createModelRegistry } from "./lib/model-registry.mjs";
5
+ import { readBoundedText } from "./lib/site-client.mjs";
6
+
7
+ const DEFAULT_PROVIDER_ID = "auto-codex-filter";
8
+ const DEFAULT_BASE_URL = "https://api.openai.com/v1";
9
+ function normalizeBaseURL(value) {
10
+ const url = new URL(value);
11
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
12
+ throw new Error("baseURL must use http: or https:");
13
+ }
14
+ return url.href.replace(/\/+$/, "");
15
+ }
16
+
17
+ function normalizeModels(models) {
18
+ const source = Array.isArray(models)
19
+ ? Object.fromEntries(models.map(id => [String(id), { id: String(id) }]))
20
+ : models && typeof models === "object" ? models : null;
21
+ if (!source) return {};
22
+
23
+ const result = {};
24
+ for (const [key, value] of Object.entries(source)) {
25
+ const model = typeof value === "string" ? { id: value } : { ...value };
26
+ result[key] = {
27
+ ...model,
28
+ id: model.id ?? key,
29
+ name: model.name ?? model.id ?? key
30
+ };
31
+ }
32
+ return result;
33
+ }
34
+
35
+ async function plugin(input = {}, options = {}) {
36
+ const providerId = options.providerId || DEFAULT_PROVIDER_ID;
37
+ const models = normalizeModels(options.models);
38
+ let explicit = { models };
39
+ const loadRegistry = createModelRegistry(options.modelsRegistryPath ? { paths: [options.modelsRegistryPath] } : {});
40
+ const configuredBaseURL = options.baseURL ? normalizeBaseURL(options.baseURL) : undefined;
41
+ const accountBaseURL = auth => normalizeBaseURL(auth?.metadata?.baseURL || explicit.api || configuredBaseURL || DEFAULT_BASE_URL);
42
+ const prompts = configuredBaseURL ? [] : [{
43
+ type: "text",
44
+ key: "baseURL",
45
+ message: "Responses API base URL",
46
+ placeholder: "https://api.example.com/v1",
47
+ validate(value) {
48
+ try {
49
+ normalizeBaseURL(value);
50
+ return undefined;
51
+ } catch {
52
+ return "Enter an http: or https: URL";
53
+ }
54
+ }
55
+ }];
56
+
57
+ return {
58
+ config: async cfg => {
59
+ cfg.provider ??= {};
60
+ explicit = structuredClone(cfg.provider[providerId] ?? { models });
61
+ cfg.provider[providerId] ??= {
62
+ name: options.providerName || "Auto Codex Filter",
63
+ npm: "@ai-sdk/openai",
64
+ api: configuredBaseURL || DEFAULT_BASE_URL,
65
+ models
66
+ };
67
+ },
68
+ auth: {
69
+ provider: providerId,
70
+ maxConcurrency: options.maxConcurrency ?? 4,
71
+ methods: [{
72
+ type: "api",
73
+ label: "Responses 上游 API key",
74
+ placeholder: "sk-…(无鉴权的本地端点也请填一个非空占位符)",
75
+ prompts
76
+ }],
77
+ async loader(getAuth) {
78
+ const auth = await getAuth();
79
+ const baseURL = accountBaseURL(auth);
80
+ const headers = new Headers();
81
+ if (auth?.key) headers.set("authorization", `Bearer ${auth.key}`);
82
+ const filtered = createFilteredFetch((request, init) => {
83
+ const merged = new Headers(request instanceof Request ? request.headers : undefined);
84
+ new Headers(init?.headers).forEach((value, name) => merged.set(name, value));
85
+ headers.forEach((value, name) => merged.set(name, value));
86
+ return fetch(request, { ...init, headers: merged });
87
+ }, options.filter ?? {});
88
+ return {
89
+ baseURL,
90
+ apiKey: auth?.key,
91
+ fetch: filtered
92
+ };
93
+ }
94
+ },
95
+ provider: {
96
+ id: providerId,
97
+ async models(provider, { auth } = {}) {
98
+ const fallback = () => {
99
+ const result = Object.fromEntries(Object.entries(provider.models ?? {}).filter(([name]) => explicit.models?.[name] && !explicit.models[name].disabled)
100
+ .map(([name, base]) => {
101
+ const user = explicit.models[name];
102
+ return [name, { ...base, ...resolveModelMetadata({ id: user.id || name, providerId, user, base }) }];
103
+ }));
104
+ result[Symbol.for("magpie.fellBack")] = true;
105
+ return result;
106
+ };
107
+ try {
108
+ const baseURL = accountBaseURL(auth);
109
+ const headers = new Headers();
110
+ if (auth?.key) headers.set("authorization", `Bearer ${auth.key}`);
111
+ const response = await fetch(baseURL + "/models", { headers, redirect: "error", signal: AbortSignal.timeout(25000) });
112
+ if (!response.ok) { await response.body?.cancel(); return fallback(); }
113
+ const catalog = JSON.parse(await readBoundedText(response));
114
+ if (!Array.isArray(catalog?.data)) return fallback();
115
+ const registry = await loadRegistry();
116
+ const rows = catalog.data.filter(model => typeof model?.id === "string" && model.id);
117
+ for (const [name, user] of Object.entries(explicit.models ?? {})) {
118
+ const id = user.id || name;
119
+ if (!user.disabled && !rows.some(row => row.id === id)) rows.push({ id });
120
+ }
121
+ const result = {};
122
+ for (const row of rows) {
123
+ const aliases = Object.entries(explicit.models ?? {}).filter(([name, user]) => (user.id || name) === row.id);
124
+ for (const [name, user] of aliases.length ? aliases : [[row.id, {}]]) {
125
+ if (user.disabled) continue;
126
+ const base = provider.models?.[name] ?? provider.models?.[row.id] ?? {};
127
+ result[name] = {
128
+ ...base, id: name, name: user.name || row.name || base.name || name,
129
+ api: { ...base.api, id: row.id, url: user.provider?.api || baseURL, npm: user.provider?.npm || explicit.npm || "@ai-sdk/openai" },
130
+ ...resolveModelMetadata({ id: row.id, providerId, registry, row, user, base }),
131
+ options: { ...base.options, ...user.options }, headers: { ...base.headers, ...user.headers }
132
+ };
133
+ }
134
+ }
135
+ return result;
136
+ } catch {
137
+ return fallback();
138
+ }
139
+ }
140
+ }
141
+ };
142
+ }
143
+
144
+ export default {
145
+ id: "auto-codex-filter",
146
+ server: plugin
147
+ };
148
+
149
+ export const _internal = {
150
+ cleanResponsesRequest,
151
+ defaultRetryDelay,
152
+ fetchWithFilter,
153
+ historyErrorCode,
154
+ normalizeModels,
155
+ retryErrorClass
156
+ };
package/icon.png ADDED
Binary file
package/index.mjs ADDED
@@ -0,0 +1,52 @@
1
+ import { createProvider } from "./lib/provider.mjs";
2
+ import { PROVIDER } from "./lib/accounts.mjs";
3
+ import { createFilteredFetch, normalizeFilterOptions, _internal as filter } from "./lib/responses-filter.mjs";
4
+
5
+ async function plugin(input = {}, options = {}) {
6
+ const settings = normalizeFilterOptions({
7
+ retryProfile: "anyrouter",
8
+ ...(options.filter ?? {})
9
+ });
10
+ const hooks = await createProvider(input, options);
11
+ const originalLoader = hooks.auth.loader;
12
+
13
+ const onEvent = (event, data) => {
14
+ const result = input.client?.app?.log?.({ body: {
15
+ service: "anyrouter-auto-filter",
16
+ level: event.endsWith("error") || event === "cleanup-refused" ? "warn" : "info",
17
+ message: event,
18
+ extra: data
19
+ } });
20
+ result?.catch?.(() => {});
21
+ };
22
+
23
+ hooks.auth.options = [...(hooks.auth.options ?? []), {
24
+ key: "conditional-history-filter",
25
+ label: "安全重试加密历史错误",
26
+ description: "先保留完整历史,只对明确的可移植历史错误做清理;支持的推理 SSE 先缓冲再交付。",
27
+ default: true
28
+ }];
29
+ hooks.auth.loader = async (getAuth, provider) => {
30
+ const loaded = await originalLoader(getAuth, provider);
31
+ if (!loaded.fetch) return loaded;
32
+ const filtered = createFilteredFetch(loaded.fetch.bind(loaded), { ...settings, onEvent });
33
+ return {
34
+ ...loaded,
35
+ fetch(request, init) {
36
+ const enabled = settings.enabled && input.magpie?.option?.(
37
+ PROVIDER, "conditional-history-filter"
38
+ ) !== false;
39
+ if (!enabled) return loaded.fetch(request, init);
40
+ if (!(request instanceof Request)) return filtered(request, init);
41
+ const headers = new Headers(request.headers);
42
+ new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
43
+ return filtered(request, { ...init, headers });
44
+ }
45
+ };
46
+ };
47
+
48
+ return hooks;
49
+ }
50
+
51
+ export default { id: "opencode-anyrouter-auth", server: plugin };
52
+ export const _internal = { ...filter };
@@ -0,0 +1,200 @@
1
+ export const PROVIDER = "anyrouter";
2
+
3
+ export const SITES = Object.freeze({
4
+ top: "https://anyrouter.top"
5
+ });
6
+
7
+ export const API_ENDPOINTS = Object.freeze({
8
+ top: "https://anyrouter.top",
9
+ fcapp: "https://a-ocnfniawgw.cn-shanghai.fcapp.run"
10
+ });
11
+
12
+ const MODES = new Set([
13
+ "api-key",
14
+ "access-token",
15
+ "password",
16
+ "github",
17
+ "linuxdo",
18
+ "session",
19
+ "legacy-session"
20
+ ]);
21
+ const CHECKIN_MODES = new Set(["password", "github", "linuxdo", "session", "legacy-session"]);
22
+ const text = value => typeof value === "string" || typeof value === "number" ? String(value).trim() : "";
23
+ const emailText = value => /^[^\s@]+@[^\s@]+$/.test(text(value)) ? text(value) : "";
24
+ const optedIn = value => value === true || value === "true" || value === "yes";
25
+
26
+ export function normalizeBase(value) {
27
+ const url = new URL(value);
28
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
29
+ throw new Error("端点必须是不含凭据、查询或片段的 http(s) 基础地址。");
30
+ }
31
+ return url.href.replace(/\/+$/, "");
32
+ }
33
+
34
+ export function siteChoice(value = "top") {
35
+ if (!Object.hasOwn(SITES, value)) {
36
+ throw new Error("只支持 AnyRouter 官方站点 anyrouter.top。");
37
+ }
38
+ return value;
39
+ }
40
+
41
+ export function apiEndpointChoice(value = "top") {
42
+ if (!Object.hasOwn(API_ENDPOINTS, value)) {
43
+ throw new Error("模型 API 端点只能选择 anyrouter.top 或 a-ocnfniawgw.cn-shanghai.fcapp.run。");
44
+ }
45
+ return value;
46
+ }
47
+
48
+ export function protocolBase(base, protocol = "responses") {
49
+ const normalized = normalizeBase(base);
50
+ const version = protocol === "gemini" ? "v1beta" : "v1";
51
+ if (/\/(?:v1|v1beta)$/.test(normalized)) {
52
+ return normalized.replace(/\/(?:v1|v1beta)$/, `/${version}`);
53
+ }
54
+ return normalized + "/" + version;
55
+ }
56
+
57
+ export function normalizeApiBase(value) {
58
+ const normalized = normalizeBase(value);
59
+ const url = new URL(normalized);
60
+ const path = url.pathname.replace(/\/+$/, "");
61
+ if (!Object.values(API_ENDPOINTS).includes(url.origin) || !["", "/", "/v1", "/v1beta"].includes(path)) {
62
+ throw new Error("模型 API 端点只能是 anyrouter.top 或 a-ocnfniawgw.cn-shanghai.fcapp.run。");
63
+ }
64
+ return protocolBase(normalized);
65
+ }
66
+
67
+ function legacyValue(auth, key) {
68
+ return auth?.[key] ?? auth?.metadata?.[key];
69
+ }
70
+
71
+ export function readAccount(auth, provider = {}) {
72
+ if (!auth) return null;
73
+ let saved;
74
+ if (auth.type === "oauth") {
75
+ try {
76
+ saved = JSON.parse(auth.refresh);
77
+ } catch {}
78
+ if (saved?.provider !== PROVIDER || saved?.schema !== 2 || !MODES.has(saved.mode)) {
79
+ throw new Error("无法识别的 AnyRouter 账号格式,请重新连接该账号。");
80
+ }
81
+ }
82
+
83
+ const get = key => saved ? saved[key] : legacyValue(auth, key);
84
+ const username = text(get("username"));
85
+ const password = typeof get("password") === "string" ? get("password") : "";
86
+ const session = text(get("session") || get("cookie"));
87
+ const accessToken = text(get("accessToken"));
88
+ const mode = saved?.mode ?? (username && password ? "password" : accessToken ? "access-token" : session ? "legacy-session" : "api-key");
89
+ const site = siteChoice(text(get("site") || provider.site) || "top");
90
+ const siteURL = normalizeBase(text(get("siteURL") || provider.siteURL) || SITES[site]);
91
+ if (siteURL !== SITES.top) {
92
+ throw new Error("AnyRouter 登录和站点接口只支持 anyrouter.top,请重新连接该账号。");
93
+ }
94
+ const legacyEndpoint = text(get("endpoint") || provider.endpoint);
95
+ const explicitBase = text(get("apiBase"));
96
+ const endpointChoice = text(get("apiEndpoint"));
97
+ const apiBase = explicitBase || legacyEndpoint
98
+ ? normalizeApiBase(explicitBase || legacyEndpoint)
99
+ : endpointChoice ? protocolBase(API_ENDPOINTS[apiEndpointChoice(endpointChoice)]) : "";
100
+ const userId = text(get("userId"));
101
+ const email = emailText(get("email"));
102
+ const checkinEnabled = CHECKIN_MODES.has(mode) && optedIn(get("checkinEnabled"));
103
+
104
+ return {
105
+ schema: 2,
106
+ provider: PROVIDER,
107
+ mode,
108
+ site,
109
+ siteURL,
110
+ apiBase,
111
+ key: text(saved ? auth.access : auth.key),
112
+ keyId: text(get("keyId")),
113
+ userId,
114
+ username,
115
+ email,
116
+ label: text(get("label")) || (!saved && !email ? text(get("email")) : ""),
117
+ session: mode === "api-key" ? "" : session,
118
+ accessToken: mode === "api-key" ? "" : accessToken,
119
+ headers: get("headers") ?? "",
120
+ siteHeaders: get("siteHeaders") ?? "",
121
+ checkinEnabled,
122
+ password: mode === "password" && checkinEnabled ? password : "",
123
+ lastCheckinDay: text(get("lastCheckinDay")),
124
+ lastCheckin: get("lastCheckin") ?? null
125
+ };
126
+ }
127
+
128
+ export function accountCapabilities(account) {
129
+ const mode = account?.mode;
130
+ const siteCredential = mode === "password"
131
+ ? Boolean(account?.username && account?.password)
132
+ : Boolean(account?.session);
133
+ return {
134
+ inference: Boolean(account?.key),
135
+ usage: Boolean(account && mode !== "api-key" && account.userId && (account.session || account.accessToken)),
136
+ checkin: Boolean(account?.checkinEnabled && CHECKIN_MODES.has(mode) && account.userId && siteCredential)
137
+ };
138
+ }
139
+
140
+ export function saveAccount(account, previous = {}) {
141
+ if (!MODES.has(account.mode) || !account.key) {
142
+ throw new Error("已连接的账号必须有推理 key。");
143
+ }
144
+ if (account.mode !== "api-key" && !account.userId) {
145
+ throw new Error("站点没有提供账号 ID。");
146
+ }
147
+
148
+ const { key, ...state } = account;
149
+ state.schema = 2;
150
+ state.provider = PROVIDER;
151
+ state.checkinEnabled = CHECKIN_MODES.has(account.mode) && account.checkinEnabled === true;
152
+ if (!state.checkinEnabled || account.mode !== "password") {
153
+ delete state.password;
154
+ }
155
+ if (account.mode === "api-key") {
156
+ delete state.session;
157
+ delete state.accessToken;
158
+ delete state.password;
159
+ }
160
+
161
+ return {
162
+ type: "oauth",
163
+ access: key,
164
+ refresh: JSON.stringify(state),
165
+ expires: 0,
166
+ accountId: text(previous.accountId ?? previous.metadata?.email ?? previous.email) ||
167
+ emailText(account.email) || text(account.username) || `AnyRouter ${text(account.userId)}`.trim(),
168
+ ...(account.userId ? { uid: `${PROVIDER}:${account.userId}` } : {})
169
+ };
170
+ }
171
+
172
+ export function withSiteIdentity(account, user) {
173
+ const userId = assertSameUser(account, user);
174
+ return {
175
+ ...account,
176
+ userId,
177
+ username: text(user.username ?? account.username),
178
+ email: emailText(user.email ?? account.email)
179
+ };
180
+ }
181
+
182
+ export function assertSameUser(account, user) {
183
+ const id = text(user?.id);
184
+ if (!id || (account?.userId && id !== account.userId)) {
185
+ throw new Error("站点返回的用户 ID 不一致或缺失,未替换账号凭据。");
186
+ }
187
+ return id;
188
+ }
189
+
190
+ export function beijingDay(now = Date.now()) {
191
+ return new Date(now + 8 * 60 * 60 * 1000).toISOString().slice(0, 10);
192
+ }
193
+
194
+ export function isKnownSite(value) {
195
+ try {
196
+ return Object.values(SITES).includes(new URL(value).origin);
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
@@ -0,0 +1,138 @@
1
+ import { API_ENDPOINTS, SITES, protocolBase } from "./accounts.mjs";
2
+ import { inferenceHeaders } from "./headers.mjs";
3
+ import { readBoundedText } from "./site-client.mjs";
4
+ import { resolveModelMetadata } from "./model-metadata.mjs";
5
+ import { createModelRegistry } from "./model-registry.mjs";
6
+ export { protocolOfURL } from "./protocols.mjs";
7
+
8
+ export const NPMS = Object.freeze({ responses: "@ai-sdk/openai", chat: "@ai-sdk/openai-compatible", anthropic: "@ai-sdk/anthropic", gemini: "@ai-sdk/google" });
9
+
10
+ function fromNpm(npm) {
11
+ if (/anthropic/.test(npm ?? "")) return "anthropic";
12
+ if (npm === "@ai-sdk/google") return "gemini";
13
+ if (["@ai-sdk/openai", "@ai-sdk/azure"].includes(npm)) return "responses";
14
+ return "chat";
15
+ }
16
+
17
+ export function protocolForModel(id) {
18
+ const value = String(id || "").toLowerCase();
19
+ if (value.startsWith("claude-") || value.endsWith("-cc-format")) return "anthropic";
20
+ if (value.startsWith("gemini-")) return "gemini";
21
+ return "responses";
22
+ }
23
+
24
+ function chooseProtocol(row, user, providerConfig) {
25
+ const npm = user?.provider?.npm;
26
+ if (npm) return fromNpm(npm);
27
+ // The host's generated AnyRouter provider defaults to @ai-sdk/openai.
28
+ // That is a Responses default, not a declaration that Claude/Gemini models
29
+ // have changed protocol. Other provider-level SDKs remain explicit overrides.
30
+ const providerNpm = providerConfig?.npm;
31
+ if (providerNpm && providerNpm !== NPMS.responses) return fromNpm(providerNpm);
32
+ const types = Array.isArray(row.supported_endpoint_types) ? row.supported_endpoint_types : [];
33
+ if (types.includes("anthropic")) return "anthropic";
34
+ if (types.includes("gemini") || types.includes("google")) return "gemini";
35
+ if (types.some(value => ["responses", "openai-response", "openai-responses"].includes(value))) return "responses";
36
+ if (types.some(value => ["chat", "chat-completions", "openai-compatible"].includes(value))) return "chat";
37
+ // AnyRouter exposes Claude and Gemini families through their native routes
38
+ // and the remaining catalog through the Responses-compatible route.
39
+ return protocolForModel(row.id);
40
+ }
41
+
42
+ function isOfficialBase(value) {
43
+ try {
44
+ const url = new URL(value);
45
+ const path = url.pathname.replace(/\/+$/, "");
46
+ return [...Object.values(SITES), ...Object.values(API_ENDPOINTS)].includes(url.origin) &&
47
+ ["", "/", "/v1", "/v1beta"].includes(path);
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ function modelBase(value, account, protocol) {
54
+ if (!value) return account.apiBase ? protocolBase(account.apiBase, protocol) : protocolBase(account.siteURL, protocol);
55
+ if (isOfficialBase(value)) return protocolBase(value, protocol);
56
+ return value;
57
+ }
58
+
59
+ export function buildCatalog(rows, provider, account, explicit = {}, pricing = [], registry = {}) {
60
+ const meta = new Map(pricing.filter(row => row && typeof row.model_name === "string").map(row => [row.model_name, row]));
61
+ const out = Object.create(null);
62
+ const discovered = new Set(rows.map(row => row?.id));
63
+ const manual = Object.entries(explicit.models ?? {}).filter(([name, model]) => !model.disabled && !discovered.has(model.id || name))
64
+ .map(([name, model]) => ({ id: model.id || name }));
65
+ // A user declaration is an explicit override; a public price-list entry is
66
+ // not. Never silently remove a manually configured model on catalog refresh.
67
+ for (const row of [...rows, ...manual]) {
68
+ if (typeof row?.id !== "string" || !row.id) continue;
69
+ const aliases = Object.entries(explicit.models ?? {}).filter(([name, model]) => (model.id || name) === row.id);
70
+ const names = aliases.length ? aliases : [[row.id, {}]];
71
+ for (const [name, user] of names) {
72
+ if (user.disabled) continue;
73
+ const base = provider.models?.[name] ?? provider.models?.[row.id] ?? {};
74
+ const metadata = { ...meta.get(row.id), ...row };
75
+ const protocol = chooseProtocol(metadata, user, explicit);
76
+ const explicitModelBase = user.provider?.api || account.apiBase;
77
+ const url = explicitModelBase
78
+ ? modelBase(explicitModelBase, account, protocol)
79
+ : modelBase(explicit.api, account, protocol);
80
+ const npm = user.provider?.npm ||
81
+ (explicit.npm && explicit.npm !== NPMS.responses ? explicit.npm : NPMS[protocol]);
82
+ out[name] = {
83
+ ...base, id: name, name: user.name || row.name || row.display_name || base.name || name,
84
+ api: { id: row.id, url, npm },
85
+ ...resolveModelMetadata({ id: row.id, providerId: provider.id || "anyrouter", registry, user, row, pricing: meta.get(row.id), base }),
86
+ headers: { ...base.headers, ...user.headers },
87
+ options: { ...base.options, ...user.options },
88
+ ...(Array.isArray(metadata.supported_endpoint_types) ? { endpoints: metadata.supported_endpoint_types } : {})
89
+ };
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+
95
+ export function createCatalog({ site, explicit, compatibility, fetchImpl = (...args) => fetch(...args), loadRegistry = createModelRegistry({ fetchImpl }) }) {
96
+ const fallback = (provider, failed = false) => {
97
+ const models = Object.fromEntries(Object.keys(explicit().models ?? {}).filter(id => !explicit().models[id].disabled)
98
+ .filter(id => provider.models?.[id]).map(id => {
99
+ const user = explicit().models[id], base = provider.models[id];
100
+ return [id, { ...base, ...resolveModelMetadata({ id: user.id || id, providerId: provider.id || "anyrouter", user, base }) }];
101
+ }));
102
+ if (failed) models[Symbol.for("magpie.fellBack")] = true;
103
+ return models;
104
+ };
105
+ return async (provider, account) => {
106
+ if (!account?.key) return fallback(provider);
107
+ const settings = explicit();
108
+ try {
109
+ const generatedSiteDefault = settings.api && isOfficialBase(settings.api);
110
+ const base = account.apiBase || (generatedSiteDefault ? protocolBase(settings.api) : settings.api) ||
111
+ protocolBase(account.siteURL);
112
+ const headers = inferenceHeaders(account, settings.headers, "responses", compatibility());
113
+ const response = await fetchImpl(base + "/models", { headers, redirect: "error", signal: AbortSignal.timeout(25000) });
114
+ const text = await readBoundedText(response);
115
+ let value;
116
+ try { value = JSON.parse(text); } catch {}
117
+ if (response.status === 401) {
118
+ const clientRejected = /unauthorized client detected/i.test(value?.error?.message || value?.message || "") && value?.error?.code !== "invalid_api_key";
119
+ throw Object.assign(new Error(clientRejected ? "The gateway rejected the client headers, not necessarily the API key." : "The model API rejected the inference key. Reconnect this account."), { signIn: clientRejected ? "kept" : "expired" });
120
+ }
121
+ if (!response.ok) return fallback(provider, true);
122
+ if (!Array.isArray(value?.data)) return fallback(provider, true);
123
+ const publicMetadata = (async () => {
124
+ if (!value.data.length) return [];
125
+ try {
126
+ const result = await site.request(account, "/api/pricing", { anonymous: true, signal: AbortSignal.timeout(5000), operation: "public model metadata read" });
127
+ if (Array.isArray(result.data)) return result.data;
128
+ } catch {}
129
+ return [];
130
+ })();
131
+ const [pricing, registry] = await Promise.all([publicMetadata, loadRegistry()]);
132
+ return buildCatalog(value.data, provider, account, settings, pricing, registry);
133
+ } catch (error) {
134
+ if (error.signIn) throw error;
135
+ return fallback(provider, true);
136
+ }
137
+ };
138
+ }
@@ -0,0 +1,65 @@
1
+ export const MODEL_HINT_HEADER = "x-anyrouter-account-model";
2
+
3
+ const CODEX_UA = "codex_cli_rs/0.101.0";
4
+ const CODEX_UA_RE = /^codex_cli_rs\//i;
5
+
6
+ export const BROWSER_HEADERS = Object.freeze({
7
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
8
+ "accept": "application/json, text/plain, */*",
9
+ "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
10
+ "sec-ch-ua": "\"Chromium\";v=\"143\", \"Google Chrome\";v=\"143\", \"Not A(Brand\";v=\"24\"",
11
+ "sec-ch-ua-mobile": "?0",
12
+ "sec-ch-ua-platform": "\"macOS\"",
13
+ "sec-fetch-dest": "empty",
14
+ "sec-fetch-mode": "cors",
15
+ "sec-fetch-site": "same-origin",
16
+ "priority": "u=1, i"
17
+ });
18
+
19
+ export function browserHeaders() {
20
+ return new Headers(BROWSER_HEADERS);
21
+ }
22
+
23
+ const RESERVED = new Set([
24
+ "authorization", "proxy-authorization", "cookie", "set-cookie", "new-api-user",
25
+ "x-api-key", "x-goog-api-key", "host", "content-length", "transfer-encoding", "connection", MODEL_HINT_HEADER
26
+ ]);
27
+
28
+ export function customHeaders(value) {
29
+ const result = new Headers();
30
+ if (!value) return result;
31
+ if (typeof value === "string") {
32
+ for (const raw of value.split(/\r?\n/)) {
33
+ const line = raw.trim();
34
+ if (!line || line.startsWith("#")) continue;
35
+ const at = line.indexOf(":");
36
+ if (at < 1) throw new Error("自定义请求头必须每行一条 Name: value。");
37
+ result.set(line.slice(0, at).trim(), line.slice(at + 1).trim());
38
+ }
39
+ } else {
40
+ new Headers(value).forEach((v, k) => result.set(k, v));
41
+ }
42
+ for (const name of result.keys()) {
43
+ if (RESERVED.has(name)) throw new Error(`请求头 ${name} 由所选账号或传输层管理,不能自定义。`);
44
+ }
45
+ return result;
46
+ }
47
+
48
+ export function inferenceHeaders(account, incoming, protocol, compatibility = true) {
49
+ // Model requests pass the gateway's native headers through; compatibility
50
+ // only restores the codex client identity on Responses calls. Account
51
+ // custom headers stay the final override for everything not managed here.
52
+ const headers = new Headers(incoming);
53
+ if (compatibility && protocol === "responses") {
54
+ if (!CODEX_UA_RE.test(headers.get("user-agent") ?? "")) headers.set("user-agent", CODEX_UA);
55
+ if (!headers.has("originator")) headers.set("originator", "codex_cli_rs");
56
+ }
57
+ customHeaders(account.headers).forEach((value, name) => headers.set(name, value));
58
+ for (const name of ["authorization", "proxy-authorization", "cookie", "set-cookie", "new-api-user", "x-api-key", "x-goog-api-key", MODEL_HINT_HEADER]) {
59
+ headers.delete(name);
60
+ }
61
+ if (protocol === "anthropic") headers.set("x-api-key", account.key);
62
+ else if (protocol === "gemini") headers.set("x-goog-api-key", account.key);
63
+ else headers.set("authorization", `Bearer ${account.key}`);
64
+ return headers;
65
+ }