@lks347/dsh-oauth 0.0.0-stage → 1.0.1
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/README.en.md +155 -0
- package/README.md +100 -2
- package/app.js +1005 -0
- package/auth.html +80 -0
- package/client.js +31 -0
- package/cordis.patch.yml +4 -0
- package/docs/CONNECTIONS.md +77 -0
- package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
- package/docs/RELEASE-1.0.1.md +38 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/index.html +43 -0
- package/package.json +64 -4
- package/providers.js +73 -0
- package/scripts/check-upstreams.mjs +27 -0
- package/scripts/link-peers.js +38 -0
- package/scripts/verify-browser.mjs +297 -0
- package/scripts/verify-host.mjs +484 -0
- package/scripts/verify-live.mjs +268 -0
- package/scripts/verify-package.mjs +168 -0
- package/scripts/verify-persistence.mjs +307 -0
- package/scripts/verify-subscriptions-ui.mjs +304 -0
- package/src/account.js +85 -0
- package/src/account.test.js +52 -0
- package/src/authorization.js +199 -0
- package/src/authorization.test.js +332 -0
- package/src/catalog.js +177 -0
- package/src/catalog.test.js +146 -0
- package/src/chat-recovery.js +110 -0
- package/src/chat-recovery.test.js +261 -0
- package/src/connection-runtime.js +126 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +103 -0
- package/src/grants.test.js +327 -0
- package/src/index.js +704 -0
- package/src/local-imports.js +145 -0
- package/src/local-imports.test.js +168 -0
- package/src/media.js +149 -0
- package/src/models.js +546 -0
- package/src/models.test.js +415 -0
- package/src/profile-store.js +51 -0
- package/src/pulls.js +100 -0
- package/src/pulls.test.js +156 -0
- package/src/qwen.js +141 -0
- package/src/qwen.test.js +35 -0
- package/src/request-errors.js +50 -0
- package/src/request-errors.test.js +131 -0
- package/src/routes.js +47 -0
- package/src/routes.test.js +136 -0
- package/src/subscription-models.test.js +139 -0
- package/src/usage/aggregators.js +292 -0
- package/src/usage/aggregators.test.js +316 -0
- package/src/usage/core.js +68 -0
- package/src/usage/index.js +93 -0
- package/src/usage/official.js +339 -0
- package/src/usage/official.test.js +273 -0
- package/src/usage/service.test.js +89 -0
- package/src/xai-browser.js +272 -0
- package/src/xai-browser.test.js +256 -0
- package/src/xai-login.js +121 -0
- package/src/xai-login.test.js +259 -0
- package/styles.css +364 -0
- package/theme.js +118 -0
- package/upstreams.json +10 -0
package/src/models.js
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model lists from a signed-in account, supplier catalog, or explicitly marked
|
|
3
|
+
* installed catalog. Catalog availability does not prove subscription coverage.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { qwenEndpoint } from "./qwen.js";
|
|
7
|
+
import { OAuthRequestError } from "./request-errors.js";
|
|
8
|
+
import { builtinModels } from '@earendil-works/pi-ai/providers/all';
|
|
9
|
+
import { getProviderDefinition } from './catalog.js';
|
|
10
|
+
|
|
11
|
+
const JSON_HEADERS = { accept: "application/json" };
|
|
12
|
+
const CODEX_CLIENT_VERSION = "0.156.1";
|
|
13
|
+
|
|
14
|
+
/** Codex model catalog requires this query; a missing client_version is HTTP 400. */
|
|
15
|
+
export function codexModelsUrl(clientVersion = CODEX_CLIENT_VERSION) {
|
|
16
|
+
const url = new URL("https://chatgpt.com/backend-api/codex/models");
|
|
17
|
+
url.searchParams.set("client_version", clientVersion);
|
|
18
|
+
return url.toString();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Chat models stay in the conversation picker. Image and video models are
|
|
23
|
+
* stored beside the pull and used by tools, so the session model does not change.
|
|
24
|
+
* Embedding, speech, and moderation rows are dropped.
|
|
25
|
+
* @param {unknown} body
|
|
26
|
+
* @param {string} [provider] OAuth provider id. Selects the policy used when a chat row declares no input.
|
|
27
|
+
* @returns {{ id: string, name: string, role: "chat" | "image" | "video", contextWindow?: number, maxTokens?: number, input?: string[], reasoningEfforts?: false | Record<string, string> }[]}
|
|
28
|
+
*/
|
|
29
|
+
export function parseModelList(body, provider) {
|
|
30
|
+
const items = [];
|
|
31
|
+
collectItems(body, items);
|
|
32
|
+
const seen = new Set();
|
|
33
|
+
const models = [];
|
|
34
|
+
for (const item of items) {
|
|
35
|
+
if (!item || typeof item !== "object") continue;
|
|
36
|
+
const info = item.info && typeof item.info === "object" ? item.info : item;
|
|
37
|
+
if (info.hidden === true || item.hidden === true ||
|
|
38
|
+
[info.visibility, item.visibility].some((visibility) => visibility === "hide" || visibility === "none")) continue;
|
|
39
|
+
const id = firstString(info.id, info.slug, info.model, item.id, item.slug, item.model);
|
|
40
|
+
if (id === undefined || seen.has(id)) continue;
|
|
41
|
+
const role = classifyModel(id, info);
|
|
42
|
+
if (role === "skip") continue;
|
|
43
|
+
seen.add(id);
|
|
44
|
+
const name = firstString(info.name, info.display_name, info.title, item.name) ?? id;
|
|
45
|
+
const model = { id, name, role };
|
|
46
|
+
const contextWindow = positiveInt(
|
|
47
|
+
info.context_window,
|
|
48
|
+
info.contextWindow,
|
|
49
|
+
info.context_length,
|
|
50
|
+
info.max_input_tokens,
|
|
51
|
+
item.context_window,
|
|
52
|
+
item.max_input_tokens,
|
|
53
|
+
info.capabilities?.limits?.max_context_window_tokens,
|
|
54
|
+
item.capabilities?.limits?.max_context_window_tokens,
|
|
55
|
+
info.max_context_window,
|
|
56
|
+
item.max_context_window,
|
|
57
|
+
);
|
|
58
|
+
if (contextWindow !== undefined) model.contextWindow = contextWindow;
|
|
59
|
+
if (role === "chat") {
|
|
60
|
+
const maxTokens = positiveInt(
|
|
61
|
+
info.max_output_tokens,
|
|
62
|
+
info.maxTokens,
|
|
63
|
+
info.top_provider?.max_completion_tokens,
|
|
64
|
+
item.max_output_tokens,
|
|
65
|
+
item.maxTokens,
|
|
66
|
+
info.capabilities?.limits?.max_output_tokens,
|
|
67
|
+
item.capabilities?.limits?.max_output_tokens,
|
|
68
|
+
);
|
|
69
|
+
if (maxTokens !== undefined) model.maxTokens = maxTokens;
|
|
70
|
+
const input = modelInput(info, item, provider);
|
|
71
|
+
if (input !== undefined) model.input = input;
|
|
72
|
+
const reasoningEfforts = reasoningEffortsFrom(info, item);
|
|
73
|
+
if (reasoningEfforts !== undefined) model.reasoningEfforts = reasoningEfforts;
|
|
74
|
+
const reasoning = [info.reasoning, info.capabilities?.reasoning, item.reasoning].find(value => typeof value === 'boolean');
|
|
75
|
+
if (reasoning !== undefined) model.reasoning = reasoning;
|
|
76
|
+
const tools = [info.capabilities?.supports?.tool_calls, info.supports_tools, info.tool_calling, info.capabilities?.tool_calling, info.capabilities?.tool_calling?.supported].find(value => typeof value === 'boolean');
|
|
77
|
+
if (tools !== undefined) model.tools = tools;
|
|
78
|
+
else if (Array.isArray(info.supported_parameters)) model.tools = info.supported_parameters.includes('tools');
|
|
79
|
+
}
|
|
80
|
+
const output = outputModalities(info) ?? outputModalities(item);
|
|
81
|
+
if (output !== undefined) model.output = output;
|
|
82
|
+
models.push(model);
|
|
83
|
+
}
|
|
84
|
+
return models;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const IMAGE_PREFERENCE = ["grok-imagine-image-2.0", "grok-imagine-image"];
|
|
88
|
+
const VIDEO_PREFERENCE = ["grok-imagine-video-1.5", "grok-imagine-video"];
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Prefer one image model and one video model from the returned catalog.
|
|
92
|
+
* A missing media role stays absent.
|
|
93
|
+
* @param {{ id: string, name: string, role: string }[]} models
|
|
94
|
+
*/
|
|
95
|
+
export function preferredMedia(models) {
|
|
96
|
+
return [
|
|
97
|
+
pickMedia(models, "image", IMAGE_PREFERENCE),
|
|
98
|
+
pickMedia(models, "video", VIDEO_PREFERENCE),
|
|
99
|
+
].filter((model) => model !== undefined);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function pickMedia(models, role, order) {
|
|
103
|
+
for (const id of order) {
|
|
104
|
+
const found = models.find((model) => model.role === role && model.id === id);
|
|
105
|
+
if (found) return found;
|
|
106
|
+
}
|
|
107
|
+
return models.find((model) => model.role === role);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function collectItems(body, items) {
|
|
111
|
+
if (Array.isArray(body)) {
|
|
112
|
+
items.push(...body);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!body || typeof body !== "object") return;
|
|
116
|
+
for (const key of ["models", "data", "items"]) {
|
|
117
|
+
if (Array.isArray(body[key])) items.push(...body[key]);
|
|
118
|
+
}
|
|
119
|
+
if (items.length > 0) return;
|
|
120
|
+
for (const value of Object.values(body)) {
|
|
121
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) continue;
|
|
122
|
+
const info = value.info && typeof value.info === "object" ? value.info : value;
|
|
123
|
+
if (typeof info.id === "string" || typeof info.model === "string") items.push(value);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function classifyModel(id, info) {
|
|
128
|
+
const type = info.capabilities?.type;
|
|
129
|
+
if (type === "embedding" || type === "embeddings" || type === "completion") return "skip";
|
|
130
|
+
// Input video and descriptions mentioning image tools do not make a chat
|
|
131
|
+
// model a media generator. Explicit output modalities take precedence.
|
|
132
|
+
const output = outputModalities(info);
|
|
133
|
+
if (output?.includes('text')) return 'chat';
|
|
134
|
+
if (output?.includes('video')) return 'video';
|
|
135
|
+
if (output?.includes('image')) return 'image';
|
|
136
|
+
if (output?.includes('audio')) return 'skip';
|
|
137
|
+
const blob = `${id} ${info.name ?? ""}`.toLowerCase();
|
|
138
|
+
if (/imagine-video|\bvideo\b|sora|veo/.test(blob)) return "video";
|
|
139
|
+
if (/imagine-image|dall-e|gpt-image|image-gen|flux|aurora/.test(blob)) return "image";
|
|
140
|
+
if (/embed|moderation|whisper|transcri|\btts\b|realtime|speech/.test(blob)) return "skip";
|
|
141
|
+
return "chat";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @param {string} provider
|
|
146
|
+
* @param {Record<string, unknown>} payload OAuth grant payload. `access` is the bearer token.
|
|
147
|
+
* @returns {Promise<ReturnType<typeof parseModelList>>}
|
|
148
|
+
*/
|
|
149
|
+
export async function fetchAccountModels(provider, payload) {
|
|
150
|
+
const access = typeof payload.access === "string" ? payload.access : "";
|
|
151
|
+
if (access.length === 0) throw new Error("这次登录里没有 access token,无法拉取模型");
|
|
152
|
+
const definition = getProviderDefinition(provider, payload);
|
|
153
|
+
if (definition?.catalogProvider && !definition.modelsURL) {
|
|
154
|
+
const registry = builtinModels({ authContext: { env: async () => undefined, fileExists: async () => false } });
|
|
155
|
+
const installed = await registry.getProvider(definition.catalogProvider)?.getModels();
|
|
156
|
+
if (!installed?.length) throw new Error('The installed provider catalog is unavailable.');
|
|
157
|
+
const source = new Map(installed.map(model => [model.id, model]));
|
|
158
|
+
return parseModelList(installed, provider).map(model => {
|
|
159
|
+
const compat = modelCompatFrom(source.get(model.id)?.compat);
|
|
160
|
+
return { ...model, ...(compat ? { compat } : {}), source: 'installed-catalog', entitlement: 'unknown' };
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
const request = modelListRequest(provider, access, payload);
|
|
164
|
+
let body = await fetchModelPage(provider, request.url, request.headers);
|
|
165
|
+
// Anthropic pages its catalog: follow has_more / last_id until the list ends.
|
|
166
|
+
if (provider === "anthropic") {
|
|
167
|
+
const rows = Array.isArray(body?.data) ? [...body.data] : [];
|
|
168
|
+
let page = body;
|
|
169
|
+
for (let guard = 0; guard < 20 && page?.has_more === true && typeof page.last_id === "string"; guard++) {
|
|
170
|
+
const next = new URL(request.url);
|
|
171
|
+
next.searchParams.set("after_id", page.last_id);
|
|
172
|
+
page = await fetchModelPage(provider, next.toString(), request.headers);
|
|
173
|
+
if (Array.isArray(page?.data)) rows.push(...page.data);
|
|
174
|
+
}
|
|
175
|
+
body = { data: rows };
|
|
176
|
+
}
|
|
177
|
+
if (provider === "github-copilot") body = copilotAccountCatalog(body, request.url);
|
|
178
|
+
let models = parseModelList(body, provider);
|
|
179
|
+
if (provider === "xai") models = await withGrokMedia(models, access);
|
|
180
|
+
if (models.length === 0) throw new Error(`${provider} 的 OAuth 账号没有返回可用模型`);
|
|
181
|
+
return models.map(model => ({ ...model, source: definition?.modelSource ?? 'account', entitlement: definition?.entitlement ?? 'account' }));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function fetchModelPage(provider, url, headers) {
|
|
185
|
+
const response = await fetch(url, {
|
|
186
|
+
headers,
|
|
187
|
+
signal: AbortSignal.timeout(20000),
|
|
188
|
+
redirect: 'error',
|
|
189
|
+
});
|
|
190
|
+
const text = await response.text();
|
|
191
|
+
if (!response.ok) {
|
|
192
|
+
throw new OAuthRequestError(provider, response.status, text);
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
return JSON.parse(text);
|
|
196
|
+
} catch {
|
|
197
|
+
throw new Error(`${provider} 模型列表不是 JSON`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function withGrokMedia(chatModels, access) {
|
|
202
|
+
const chats = chatModels.filter((model) => model.role === "chat");
|
|
203
|
+
const listed = chatModels.filter((model) => model.role === "image" || model.role === "video");
|
|
204
|
+
try {
|
|
205
|
+
const response = await fetch("https://api.x.ai/v1/models", {
|
|
206
|
+
headers: { ...JSON_HEADERS, authorization: `Bearer ${access}` },
|
|
207
|
+
signal: AbortSignal.timeout(15000),
|
|
208
|
+
redirect: 'error',
|
|
209
|
+
});
|
|
210
|
+
if (response.ok) listed.push(...parseModelList(await response.json()));
|
|
211
|
+
} catch {
|
|
212
|
+
/* Preserve only media the account's successful catalog response listed. */
|
|
213
|
+
}
|
|
214
|
+
const seen = new Set(chats.map((model) => model.id));
|
|
215
|
+
return [...chats, ...preferredMedia(listed).filter((model) => !seen.has(model.id))];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Copilot's picker and policy flags describe account availability, including its Individual-only fallback. */
|
|
219
|
+
function copilotAccountCatalog(body, requestUrl) {
|
|
220
|
+
const rows = Array.isArray(body?.data) ? body.data.filter((item) =>
|
|
221
|
+
item && typeof item === "object" && item.capabilities?.type === "chat" &&
|
|
222
|
+
item.capabilities?.supports?.tool_calls !== false) : [];
|
|
223
|
+
const picker = rows.filter((item) => item.model_picker_enabled === true && item.policy?.state !== "disabled");
|
|
224
|
+
const individual = requestUrl === "https://api.individual.githubcopilot.com/models";
|
|
225
|
+
return { data: picker.length > 0 || !individual ? picker : rows.filter((item) => item.policy?.state === "enabled") };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Grok chat accepts images, but the xAI account catalog omits modalities.
|
|
230
|
+
* Harness inherits an omitted `input` from the install catalog and otherwise
|
|
231
|
+
* uses the route default `["text"]`, so an id that is not installed yet loses
|
|
232
|
+
* vision. Other providers keep the omission: their catalogs mix text-only and
|
|
233
|
+
* vision models, and inheritance is the per-model answer.
|
|
234
|
+
*/
|
|
235
|
+
const UNDECLARED_CHAT_INPUT = {
|
|
236
|
+
xai: ["text", "image"],
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
/** Keep only input modalities the installed Harness can represent. */
|
|
240
|
+
function modelInput(info, item, provider) {
|
|
241
|
+
for (const source of [info, item]) {
|
|
242
|
+
const declared = declaredInput(source);
|
|
243
|
+
if (declared !== undefined) return declared;
|
|
244
|
+
}
|
|
245
|
+
return UNDECLARED_CHAT_INPUT[provider];
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Every account catalog is read here. Codex and Qwen use `input_modalities`.
|
|
250
|
+
* Copilot uses `capabilities.supports.vision`. Anthropic uses
|
|
251
|
+
* `capabilities.image_input.supported`. OpenRouter nests the list under
|
|
252
|
+
* `architecture`, or encodes it as `text+image->text`.
|
|
253
|
+
*/
|
|
254
|
+
function declaredInput(source) {
|
|
255
|
+
if (!source || typeof source !== "object") return undefined;
|
|
256
|
+
for (const modalities of [
|
|
257
|
+
source.input_modalities,
|
|
258
|
+
source.input,
|
|
259
|
+
source.architecture?.input_modalities,
|
|
260
|
+
source.architecture?.inputModalities,
|
|
261
|
+
]) {
|
|
262
|
+
const input = modalityList(modalities);
|
|
263
|
+
if (input !== undefined) return input;
|
|
264
|
+
}
|
|
265
|
+
const described = modalityList(modalityWords(source.architecture?.modality));
|
|
266
|
+
if (described !== undefined) return described;
|
|
267
|
+
for (const vision of [
|
|
268
|
+
source.capabilities?.supports?.vision,
|
|
269
|
+
source.capabilities?.image_input?.supported,
|
|
270
|
+
source.capabilities?.vision,
|
|
271
|
+
]) {
|
|
272
|
+
if (typeof vision === "boolean") return vision ? ["text", "image"] : ["text"];
|
|
273
|
+
}
|
|
274
|
+
return undefined;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function modalityList(modalities) {
|
|
278
|
+
if (!Array.isArray(modalities)) return undefined;
|
|
279
|
+
const seen = new Set(modalities.filter((value) => value === "text" || value === "image"));
|
|
280
|
+
if (seen.size === 0) return undefined;
|
|
281
|
+
return seen.has("image") ? ["text", "image"] : ["text"];
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function modalityWords(value) {
|
|
285
|
+
if (typeof value !== "string" || !value.includes("->")) return undefined;
|
|
286
|
+
return value.split("->")[0].split(/[+,]/).map((part) => part.trim().toLowerCase());
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function outputModalities(source) {
|
|
290
|
+
if (!source || typeof source !== 'object') return undefined;
|
|
291
|
+
const declared = source.output_modalities ?? source.output ?? source.architecture?.output_modalities;
|
|
292
|
+
if (Array.isArray(declared)) return [...new Set(declared.filter(value => ['text', 'image', 'audio', 'video'].includes(value)))];
|
|
293
|
+
const modality = source.architecture?.modality;
|
|
294
|
+
if (typeof modality !== 'string' || !modality.includes('->')) return undefined;
|
|
295
|
+
return [...new Set(modality.split('->')[1].split(/[+,]/).map(value => value.trim().toLowerCase()).filter(value => ['text', 'image', 'audio', 'video'].includes(value)))];
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function positiveInt(...values) {
|
|
299
|
+
for (const value of values) {
|
|
300
|
+
if (Number.isInteger(value) && value > 0) return value;
|
|
301
|
+
}
|
|
302
|
+
return undefined;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Vendor spellings that correspond to a harness thinking level. The stored value stays the vendor string. */
|
|
306
|
+
const THINKING_ALIASES = {
|
|
307
|
+
off: "off",
|
|
308
|
+
none: "off",
|
|
309
|
+
disabled: "off",
|
|
310
|
+
minimal: "minimal",
|
|
311
|
+
min: "minimal",
|
|
312
|
+
low: "low",
|
|
313
|
+
medium: "medium",
|
|
314
|
+
med: "medium",
|
|
315
|
+
high: "high",
|
|
316
|
+
xhigh: "xhigh",
|
|
317
|
+
"x-high": "xhigh",
|
|
318
|
+
extra_high: "xhigh",
|
|
319
|
+
"extra-high": "xhigh",
|
|
320
|
+
max: "max",
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Levels the account catalog actually advertises.
|
|
325
|
+
* Maps name only advertised levels. An explicit empty list or only off
|
|
326
|
+
* becomes false, which disables inherited reasoning in the Harness catalog.
|
|
327
|
+
* @param {object} info
|
|
328
|
+
* @param {object} item
|
|
329
|
+
*/
|
|
330
|
+
export function reasoningEffortsFrom(info, item) {
|
|
331
|
+
const efforts = {};
|
|
332
|
+
for (const source of [info, item]) {
|
|
333
|
+
if (!source || typeof source !== "object") continue;
|
|
334
|
+
collectEffortRows(source.reasoning_efforts, efforts);
|
|
335
|
+
collectEffortRows(source.reasoningEfforts, efforts);
|
|
336
|
+
collectLevelList(source.supported_reasoning_levels, efforts);
|
|
337
|
+
collectLevelList(source.supportedReasoningLevels, efforts);
|
|
338
|
+
collectLevelList(source.supported_reasoning_efforts, efforts);
|
|
339
|
+
collectLevelList(source.capabilities?.supports?.reasoning_effort, efforts);
|
|
340
|
+
collectLevelList(source.effort?.supported_levels, efforts);
|
|
341
|
+
collectThinkingMap(source.thinkingLevelMap, efforts);
|
|
342
|
+
collectCapabilityMap(source.capabilities?.effort, efforts);
|
|
343
|
+
}
|
|
344
|
+
const levels = Object.keys(efforts);
|
|
345
|
+
if (levels.length > 0) return levels.some((level) => level !== "off") ? efforts : false;
|
|
346
|
+
for (const source of [info, item]) {
|
|
347
|
+
if (!source || typeof source !== "object") continue;
|
|
348
|
+
if (source.reasoning === false || source.reasoningEfforts === false || source.capabilities?.reasoning === false || source.capabilities?.effort?.supported === false) return false;
|
|
349
|
+
for (const key of ["reasoning_efforts", "reasoningEfforts", "supported_reasoning_levels", "supportedReasoningLevels", "supported_reasoning_efforts"]) {
|
|
350
|
+
if (Array.isArray(source[key]) && source[key].length === 0) return false;
|
|
351
|
+
}
|
|
352
|
+
if (Array.isArray(source.capabilities?.supports?.reasoning_effort) && source.capabilities.supports.reasoning_effort.length === 0) return false;
|
|
353
|
+
}
|
|
354
|
+
return undefined;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function collectThinkingMap(map, efforts) {
|
|
358
|
+
if (!map || typeof map !== 'object' || Array.isArray(map)) return;
|
|
359
|
+
// pi-ai uses null to explicitly disable a level. A boolean reasoning flag
|
|
360
|
+
// alone does not advertise a set of wire-level reasoning_effort values.
|
|
361
|
+
for (const [level, wire] of Object.entries(map)) if (typeof wire === 'string') assignEffort(efforts, level, wire);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Intersection with the oldest supported Harness compatProfile. Installed
|
|
365
|
+
// provider extras must not become unknown profile fields and reject the route.
|
|
366
|
+
const COMPAT_BOOLEANS = new Set([
|
|
367
|
+
'supportsStore', 'supportsDeveloperRole', 'supportsReasoningEffort', 'supportsUsageInStreaming',
|
|
368
|
+
'supportsFinishReason', 'requiresToolResultName', 'requiresAssistantAfterToolResult', 'requiresThinkingAsText',
|
|
369
|
+
'requiresReasoningContentOnAssistantMessages', 'supportsThinkingTokenBudget', 'supportsMaxOutputTokens',
|
|
370
|
+
'supportsStrictMode', 'supportsLongCacheRetention', 'supportsEagerToolInputStreaming',
|
|
371
|
+
'supportsCacheControlOnTools', 'supportsTemperature', 'forceAdaptiveThinking', 'allowEmptySignature', 'supportsStrictTools',
|
|
372
|
+
]);
|
|
373
|
+
const COMPAT_ENUMS = {
|
|
374
|
+
maxTokensField: ['max_completion_tokens', 'max_tokens'],
|
|
375
|
+
thinkingFormat: ['openai', 'deepseek', 'openrouter', 'together', 'baseten', 'zai', 'qwen', 'chat-template', 'qwen-chat-template', 'string-thinking', 'ant-ling'],
|
|
376
|
+
thinkingTokenBudgetField: ['thinking_token_budget', 'thinking_budget', 'thinking_budget_tokens'],
|
|
377
|
+
cacheControlFormat: ['anthropic'],
|
|
378
|
+
};
|
|
379
|
+
export function modelCompatFrom(value) {
|
|
380
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
|
|
381
|
+
const out = {};
|
|
382
|
+
for (const [key, item] of Object.entries(value)) {
|
|
383
|
+
if (COMPAT_BOOLEANS.has(key) && typeof item === 'boolean') out[key] = item;
|
|
384
|
+
else if (Object.hasOwn(COMPAT_ENUMS, key) && COMPAT_ENUMS[key].includes(item)) out[key] = item;
|
|
385
|
+
else if (key === 'vllmPriority' && Number.isSafeInteger(item)) out[key] = item;
|
|
386
|
+
else if (['chatTemplateKwargs', 'chatTemplateArgs'].includes(key) && item && typeof item === 'object' && !Array.isArray(item)) {
|
|
387
|
+
const template = {};
|
|
388
|
+
for (const [name, entry] of Object.entries(item).slice(0, 100)) {
|
|
389
|
+
if (!/^[A-Za-z0-9_]{1,100}$/.test(name) || ['__proto__', 'constructor', 'prototype'].includes(name)) continue;
|
|
390
|
+
if (entry === null || typeof entry === 'boolean' || typeof entry === 'number' && Number.isFinite(entry) || typeof entry === 'string' && entry.length <= 1000) template[name] = entry;
|
|
391
|
+
else if (entry && typeof entry === 'object' && ['thinking.enabled', 'thinking.effort', 'thinking.budget'].includes(entry.$var)) {
|
|
392
|
+
template[name] = { $var: entry.$var, ...(typeof entry.omitWhenOff === 'boolean' ? { omitWhenOff: entry.omitWhenOff } : {}) };
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (Object.keys(template).length) out[key] = template;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return Object.keys(out).length ? out : undefined;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function collectEffortRows(rows, efforts) {
|
|
402
|
+
if (!Array.isArray(rows)) return;
|
|
403
|
+
for (const row of rows) {
|
|
404
|
+
if (typeof row === "string") {
|
|
405
|
+
assignEffort(efforts, row, row);
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (!row || typeof row !== "object") continue;
|
|
409
|
+
const levelName = firstString(row.id, row.effort, row.level);
|
|
410
|
+
const wire = firstString(row.value, row.wire, row.effort, row.id);
|
|
411
|
+
assignEffort(efforts, levelName, wire);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function collectLevelList(rows, efforts) {
|
|
416
|
+
if (!Array.isArray(rows)) return;
|
|
417
|
+
for (const row of rows) {
|
|
418
|
+
if (typeof row === "string") {
|
|
419
|
+
assignEffort(efforts, row, row);
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (!row || typeof row !== "object") continue;
|
|
423
|
+
const effort = firstString(row.effort, row.id, row.value);
|
|
424
|
+
assignEffort(efforts, effort, effort);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Anthropic lists effort as an object of per-level flags:
|
|
430
|
+
* capabilities.effort = { supported, low: { supported }, ..., max: { supported } }.
|
|
431
|
+
*/
|
|
432
|
+
function collectCapabilityMap(map, efforts) {
|
|
433
|
+
if (!map || typeof map !== "object" || Array.isArray(map) || map.supported === false) return;
|
|
434
|
+
for (const [key, value] of Object.entries(map)) {
|
|
435
|
+
if (key === "supported") continue;
|
|
436
|
+
if (value && typeof value === "object" && value.supported === true) assignEffort(efforts, key, key);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function assignEffort(efforts, levelName, wire) {
|
|
441
|
+
const level = thinkingLevel(levelName);
|
|
442
|
+
const spelling = firstString(wire);
|
|
443
|
+
if (level === undefined || spelling === undefined) return;
|
|
444
|
+
if (efforts[level] !== undefined) return;
|
|
445
|
+
efforts[level] = spelling;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function thinkingLevel(value) {
|
|
449
|
+
if (typeof value !== "string") return undefined;
|
|
450
|
+
const key = value.trim().toLowerCase().replaceAll(" ", "_");
|
|
451
|
+
return Object.hasOwn(THINKING_ALIASES, key) ? THINKING_ALIASES[key] : undefined;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* @param {string} provider
|
|
456
|
+
* @param {string} access
|
|
457
|
+
* @param {Record<string, unknown>} payload
|
|
458
|
+
*/
|
|
459
|
+
export function modelListRequest(provider, access, payload = {}) {
|
|
460
|
+
const authHeaders = new Headers({ ...JSON_HEADERS, authorization: `Bearer ${access}` });
|
|
461
|
+
// Existing OAuth resolvers may attach protocol-specific auth headers. New
|
|
462
|
+
// key connections use only the chosen credential and fixed catalog headers.
|
|
463
|
+
const oauthHeaders = ['openai-codex', 'anthropic', 'xai', 'kimi-coding', 'qwen', 'github-copilot'].includes(provider) ? payload.requestHeaders : undefined;
|
|
464
|
+
for (const [key, value] of Object.entries(oauthHeaders ?? {})) {
|
|
465
|
+
if (typeof value === "string") authHeaders.set(key, value);
|
|
466
|
+
}
|
|
467
|
+
const bearer = Object.fromEntries(authHeaders);
|
|
468
|
+
if (provider === "openai-codex") {
|
|
469
|
+
const headers = { ...bearer };
|
|
470
|
+
const accountId = chatgptAccountId(access) ?? (typeof payload.accountId === "string" ? payload.accountId : undefined);
|
|
471
|
+
if (accountId) headers["chatgpt-account-id"] = accountId;
|
|
472
|
+
return { url: codexModelsUrl(), headers };
|
|
473
|
+
}
|
|
474
|
+
if (provider === "anthropic") {
|
|
475
|
+
return {
|
|
476
|
+
url: "https://api.anthropic.com/v1/models?limit=1000",
|
|
477
|
+
headers: {
|
|
478
|
+
"anthropic-version": "2023-06-01",
|
|
479
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
480
|
+
...bearer,
|
|
481
|
+
},
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
if (provider === "openrouter") {
|
|
485
|
+
return { url: "https://openrouter.ai/api/v1/models/user", headers: bearer };
|
|
486
|
+
}
|
|
487
|
+
if (provider === "xai") {
|
|
488
|
+
return { url: modelsUrl(payload.apiBase, "https://cli-chat-proxy.grok.com/v1"), headers: bearer };
|
|
489
|
+
}
|
|
490
|
+
if (provider === "kimi-coding") {
|
|
491
|
+
if (payload.region === 'cn' || payload.region === 'global') {
|
|
492
|
+
return { url: `https://${payload.region === 'cn' ? 'api.kimi.com' : 'api.kimi.ai'}/coding/v1/models`, headers: { 'user-agent': 'KimiCLI/1.0', ...bearer } };
|
|
493
|
+
}
|
|
494
|
+
return {
|
|
495
|
+
url: modelsUrl(payload.apiBase, "https://api.kimi.com/coding/v1"),
|
|
496
|
+
headers: { "user-agent": "KimiCLI/1.0", ...bearer },
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
if (provider === "qwen") {
|
|
500
|
+
return { url: `${qwenEndpoint(payload.resourceUrl)}/models`, headers: bearer };
|
|
501
|
+
}
|
|
502
|
+
if (provider === "github-copilot") {
|
|
503
|
+
return {
|
|
504
|
+
url: modelsUrl(payload.apiBase, copilotApiBase(access)),
|
|
505
|
+
headers: {
|
|
506
|
+
"user-agent": "GitHubCopilotChat/0.35.0",
|
|
507
|
+
"editor-version": "vscode/1.107.0",
|
|
508
|
+
"editor-plugin-version": "copilot-chat/0.35.0",
|
|
509
|
+
"copilot-integration-id": "vscode-chat",
|
|
510
|
+
"x-github-api-version": "2026-06-01",
|
|
511
|
+
...bearer,
|
|
512
|
+
},
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
const definition = getProviderDefinition(provider, payload);
|
|
516
|
+
if (definition?.modelsURL) return { url: definition.modelsURL, headers: { ...bearer, ...definition.modelHeaders } };
|
|
517
|
+
throw new Error(`${provider} 还没有已核实的模型目录接口`);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function modelsUrl(apiBase, fallback) {
|
|
521
|
+
const base = firstString(apiBase) ?? fallback;
|
|
522
|
+
return `${base.replace(/\/+$/, "")}/models`;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function chatgptAccountId(token) {
|
|
526
|
+
try {
|
|
527
|
+
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf8"));
|
|
528
|
+
const accountId = payload?.["https://api.openai.com/auth"]?.chatgpt_account_id;
|
|
529
|
+
return typeof accountId === "string" && accountId.length > 0 ? accountId : undefined;
|
|
530
|
+
} catch {
|
|
531
|
+
return undefined;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function copilotApiBase(token) {
|
|
536
|
+
const match = token.match(/proxy-ep=([^;]+)/);
|
|
537
|
+
if (match?.[1]) return `https://${match[1].replace(/^proxy\./, "api.")}`;
|
|
538
|
+
return "https://api.individual.githubcopilot.com";
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function firstString(...values) {
|
|
542
|
+
for (const value of values) {
|
|
543
|
+
if (typeof value === "string" && value.trim().length > 0) return value.trim();
|
|
544
|
+
}
|
|
545
|
+
return undefined;
|
|
546
|
+
}
|