dsh-opendesign-corouter 0.1.19 → 0.2.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/README.md +6 -6
- package/lib/adapter.d.ts +5 -0
- package/lib/auth.d.ts +2 -0
- package/lib/catalog.d.ts +8 -16
- package/lib/client.d.ts +4 -4
- package/lib/client.js +60 -13
- package/lib/config.d.ts +4 -4
- package/lib/device-auth.d.ts +1 -1
- package/lib/generated/typert.host.js +23 -5
- package/lib/generated/typert.remote-client.js +23 -5
- package/lib/index.d.ts +13 -13
- package/lib/index.js +1164 -686
- package/lib/index.js.map +4 -4
- package/lib/model-catalog-snapshot.d.ts +2 -0
- package/lib/model-directory.d.ts +59 -0
- package/lib/model-discovery.d.ts +1 -1
- package/lib/model-entitlements.d.ts +44 -0
- package/lib/model-settings.d.ts +3 -0
- package/lib/protocol-options.d.ts +7 -1
- package/lib/protocols/messages.d.ts +1 -1
- package/lib/protocols/responses-replay.d.ts +6 -0
- package/lib/protocols/responses.d.ts +5 -5
- package/lib/protocols/types.d.ts +4 -0
- package/lib/remote.d.ts +8 -3
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -48,7 +48,7 @@ var __privateSet = (obj, member2, value, setter) => (__accessCheck(obj, member2,
|
|
|
48
48
|
var __privateMethod = (obj, member2, method) => (__accessCheck(obj, member2, "access private method"), method);
|
|
49
49
|
|
|
50
50
|
// src/index.ts
|
|
51
|
-
import { randomUUID as randomUUID3, createHash as
|
|
51
|
+
import { randomUUID as randomUUID3, createHash as createHash4 } from "node:crypto";
|
|
52
52
|
import { credentialKey as credentialKey2, credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
53
53
|
import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
|
|
54
54
|
import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
@@ -75,7 +75,7 @@ var EFFORTS_LOW_HIGH = ["low", "high", "max"];
|
|
|
75
75
|
var EFFORTS_LEVELS = ["low", "medium", "high"];
|
|
76
76
|
var EFFORTS_GROK = [...EFFORTS_LEVELS, "xhigh"];
|
|
77
77
|
var EFFORTS_MUSE = ["minimal", ...EFFORTS_REASONING];
|
|
78
|
-
var
|
|
78
|
+
var REFERENCE_MODELS = [
|
|
79
79
|
// ── OpenAI(8) ─────────────────────────────────────────────
|
|
80
80
|
{ id: "gpt-6.1-sol", name: "GPT-6.1 Sol", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "medium" },
|
|
81
81
|
{
|
|
@@ -93,7 +93,7 @@ var MODELS = [
|
|
|
93
93
|
{
|
|
94
94
|
id: "gpt-6-luna",
|
|
95
95
|
name: "GPT-6 Luna",
|
|
96
|
-
group: "
|
|
96
|
+
group: "paid",
|
|
97
97
|
contextWindow: 105e4,
|
|
98
98
|
maxOutputTokens: 128e3,
|
|
99
99
|
inputModalities: TEXT_AND_IMAGE,
|
|
@@ -105,6 +105,7 @@ var MODELS = [
|
|
|
105
105
|
{ id: "gpt-5.6-sol", name: "GPT-5.6 Sol", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI, defaultEffort: "medium" },
|
|
106
106
|
{ id: "gpt-5.6-terra", name: "GPT-5.6 Terra", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI, defaultEffort: "medium" },
|
|
107
107
|
// ── Anthropic(8) ──────────────────────────────────────────
|
|
108
|
+
{ id: "claude-fable-5.2", name: "Claude Fable 5.2", group: "paid", contextWindow: 1e6, maxOutputTokens: 128e3, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
|
|
108
109
|
{ id: "claude-fable-5.1", name: "Claude Fable 5.1", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
|
|
109
110
|
{ id: "claude-fable-5", name: "Claude Fable 5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
|
|
110
111
|
{ id: "claude-opus-5.5", name: "Claude Opus 5.5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "medium" },
|
|
@@ -115,7 +116,7 @@ var MODELS = [
|
|
|
115
116
|
{
|
|
116
117
|
id: "claude-haiku-5.5",
|
|
117
118
|
name: "Claude Haiku 5.5",
|
|
118
|
-
group: "
|
|
119
|
+
group: "paid",
|
|
119
120
|
contextWindow: 1e6,
|
|
120
121
|
maxOutputTokens: 128e3,
|
|
121
122
|
inputModalities: TEXT_AND_IMAGE,
|
|
@@ -123,6 +124,8 @@ var MODELS = [
|
|
|
123
124
|
defaultEffort: "medium"
|
|
124
125
|
},
|
|
125
126
|
// ── DeepSeek(4) ───────────────────────────────────────────
|
|
127
|
+
// Exact route confirmed by Link; Eco-specific capability evidence is not published.
|
|
128
|
+
{ id: "deepseek-v4.1-flash-eco", name: "DeepSeek V4.1 Flash Eco", group: "plan" },
|
|
126
129
|
{
|
|
127
130
|
id: "deepseek-v4.1-flash",
|
|
128
131
|
name: "DeepSeek V4.1 Flash",
|
|
@@ -166,7 +169,7 @@ var MODELS = [
|
|
|
166
169
|
{
|
|
167
170
|
id: "glm-5.3-flashx",
|
|
168
171
|
name: "GLM-5.3 Flash-X",
|
|
169
|
-
group: "
|
|
172
|
+
group: "paid",
|
|
170
173
|
contextWindow: 1e6,
|
|
171
174
|
maxOutputTokens: 128e3,
|
|
172
175
|
inputModalities: TEXT_AND_IMAGE,
|
|
@@ -197,6 +200,7 @@ var MODELS = [
|
|
|
197
200
|
{ id: "kimi-k3", name: "Kimi K3", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LOW_HIGH, defaultEffort: "max" },
|
|
198
201
|
{ id: "kimi-k3.1-pro", name: "Kimi K3.1 Pro", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LOW_HIGH, defaultEffort: "max" },
|
|
199
202
|
// ── Google(3) ─────────────────────────────────────────────
|
|
203
|
+
{ id: "gemini-4-carbon", name: "Gemini 4 Carbon", group: "paid" },
|
|
200
204
|
{ id: "gemini-4-argon", name: "Gemini 4 Argon", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS, defaultEffort: "medium" },
|
|
201
205
|
{ id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS, defaultEffort: "medium" },
|
|
202
206
|
{ id: "gemini-3.7-flash", name: "Gemini 3.7 Flash", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS, defaultEffort: "medium" },
|
|
@@ -224,6 +228,8 @@ var MODELS = [
|
|
|
224
228
|
reasoningEfforts: []
|
|
225
229
|
},
|
|
226
230
|
// ── Tencent(1) ────────────────────────────────────────────
|
|
231
|
+
{ id: "hy4", name: "Hy4", group: "paid", contextWindow: 1e6, maxOutputTokens: 64e3, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: ["high"], defaultEffort: "high" },
|
|
232
|
+
{ id: "hy4-flash", name: "Hy4 Flash", group: "paid", contextWindow: 1e6, maxOutputTokens: 64e3, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: ["high"], defaultEffort: "high" },
|
|
227
233
|
{
|
|
228
234
|
id: "hy4-preview",
|
|
229
235
|
name: "Hunyuan H4 Preview",
|
|
@@ -235,13 +241,50 @@ var MODELS = [
|
|
|
235
241
|
defaultEffort: "high"
|
|
236
242
|
},
|
|
237
243
|
// ── Alibaba(1) ────────────────────────────────────────────
|
|
244
|
+
// 131072 is the conservative output cap across both thinking modes, not their combined budget.
|
|
245
|
+
{ id: "qwen4-max", name: "Qwen4 Max", group: "paid", contextWindow: 1e6, maxOutputTokens: 131072, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: ["low", "high", "xhigh"], defaultEffort: "high" },
|
|
238
246
|
{ id: "qwen3.7-max", name: "Qwen3.7 Max", group: "paid", contextWindow: 1e6, inputModalities: TEXT_ONLY, reasoningEfforts: [] },
|
|
239
247
|
// Official API additions; display labels for undocumented entries are local formatting.
|
|
248
|
+
{ id: "muse-ember-1.0", name: "Muse Ember 1.0", group: "paid" },
|
|
240
249
|
{ id: "minimax-m3.1-flash", name: "MiniMax M3.1 Flash", group: "plan", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "max" },
|
|
241
250
|
// 厂商只说默认“由模型决定”;high 取自 Meta 合作客户端与网关实现的默认 effort。
|
|
242
251
|
{ id: "muse-spark-1.3", name: "Muse Spark 1.3", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_MUSE, defaultEffort: "high" },
|
|
243
252
|
{ id: "muse-wonder", name: "Muse Wonder", group: "paid", contextWindow: 1048576 }
|
|
244
253
|
];
|
|
254
|
+
var NATIVE_PROTOCOLS = {
|
|
255
|
+
"gpt-6.1-sol": "responses",
|
|
256
|
+
"gpt-6.1-terra": "responses",
|
|
257
|
+
"gpt-6-astra": "responses",
|
|
258
|
+
"gpt-6-luna": "responses",
|
|
259
|
+
"gpt-6-sol": "responses",
|
|
260
|
+
"gpt-5.6-luna": "responses",
|
|
261
|
+
"gpt-5.6-sol": "responses",
|
|
262
|
+
"gpt-5.6-terra": "responses",
|
|
263
|
+
"claude-fable-5.2": "messages",
|
|
264
|
+
"claude-fable-5.1": "messages",
|
|
265
|
+
"claude-fable-5": "messages",
|
|
266
|
+
"claude-opus-5.5": "messages",
|
|
267
|
+
"claude-opus-5": "messages",
|
|
268
|
+
"claude-opus-4.8": "messages",
|
|
269
|
+
"claude-sonnet-5.5": "messages",
|
|
270
|
+
"claude-sonnet-5": "messages",
|
|
271
|
+
"claude-haiku-5.5": "messages",
|
|
272
|
+
"deepseek-v4.1-flash": "responses",
|
|
273
|
+
"deepseek-v4-pro": "responses",
|
|
274
|
+
"deepseek-v4-flash": "responses",
|
|
275
|
+
"deepseek-v4-flash-vision-exp": "responses",
|
|
276
|
+
"kimi-k3.1-pro": "chat-completions",
|
|
277
|
+
"kimi-k3": "chat-completions",
|
|
278
|
+
"kimi-k2.7-code": "chat-completions",
|
|
279
|
+
"glm-5.3-flash": "chat-completions",
|
|
280
|
+
"glm-5.3-flashx": "chat-completions",
|
|
281
|
+
"glm-5.2": "chat-completions",
|
|
282
|
+
"mimo-v2.6-pro": "chat-completions",
|
|
283
|
+
"mimo-v2.6-flash": "chat-completions",
|
|
284
|
+
"qwen3.7-max": "chat-completions",
|
|
285
|
+
"hy4-preview": "chat-completions"
|
|
286
|
+
};
|
|
287
|
+
var MODELS = REFERENCE_MODELS.map((row) => ({ ...row, ...NATIVE_PROTOCOLS[row.id] ? { nativeProtocol: NATIVE_PROTOCOLS[row.id] } : {} }));
|
|
245
288
|
var BY_ID = new Map(MODELS.map((model) => [model.id, model]));
|
|
246
289
|
function findModel(id) {
|
|
247
290
|
return BY_ID.get(id);
|
|
@@ -252,6 +295,12 @@ import Schema from "@deepseek-ai/schemastery";
|
|
|
252
295
|
|
|
253
296
|
// src/protocol-options.ts
|
|
254
297
|
var API_PROTOCOL_IDS = ["chat-completions", "responses", "messages"];
|
|
298
|
+
var API_PROTOCOL_SELECTION_IDS = ["auto", ...API_PROTOCOL_IDS];
|
|
299
|
+
function effectiveProtocol(model, selection = "auto", override) {
|
|
300
|
+
if (override !== void 0 && override !== "auto") return override;
|
|
301
|
+
if (selection !== "auto") return selection;
|
|
302
|
+
return model.nativeProtocol ?? "responses";
|
|
303
|
+
}
|
|
255
304
|
function openAiBaseURL(baseURL) {
|
|
256
305
|
const base = baseURL.replace(/\/+$/u, "");
|
|
257
306
|
return new URL(base).pathname === "/" ? `${base}/v1` : base;
|
|
@@ -279,7 +328,7 @@ function parseModelSettingsMap(value) {
|
|
|
279
328
|
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");
|
|
280
329
|
const keys = Object.keys(value);
|
|
281
330
|
if (keys.length > 512) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u6700\u591A\u5141\u8BB8 512 \u4E2A\u6A21\u578B");
|
|
282
|
-
const fields = /* @__PURE__ */ new Set(["enabled", "imageInput", "temperature", "topP", "maxTokens", "contextWindow", "contextTier", "reasoningEffort"]);
|
|
331
|
+
const fields = /* @__PURE__ */ new Set(["enabled", "imageInput", "temperature", "topP", "maxTokens", "contextWindow", "contextTier", "reasoningEffort", "apiProtocol"]);
|
|
283
332
|
const efforts = ["none", "minimal", "low", "medium", "high", "xhigh", "ultra", "max"];
|
|
284
333
|
const out = {};
|
|
285
334
|
for (const id of keys) {
|
|
@@ -292,6 +341,10 @@ function parseModelSettingsMap(value) {
|
|
|
292
341
|
if (!fields.has(field)) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u542B\u6709\u4E0D\u652F\u6301\u7684\u5B57\u6BB5");
|
|
293
342
|
}
|
|
294
343
|
const parsed = {};
|
|
344
|
+
if (settings.apiProtocol !== void 0) {
|
|
345
|
+
if (!["auto", "chat-completions", "responses", "messages"].includes(String(settings.apiProtocol))) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 apiProtocol \u4E0D\u5728\u5141\u8BB8\u7684\u53D6\u503C\u5185");
|
|
346
|
+
parsed.apiProtocol = settings.apiProtocol;
|
|
347
|
+
}
|
|
295
348
|
if (settings.enabled !== void 0) {
|
|
296
349
|
if (typeof settings.enabled !== "boolean") throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
|
|
297
350
|
parsed.enabled = settings.enabled;
|
|
@@ -359,10 +412,11 @@ function serializableTransform(callback) {
|
|
|
359
412
|
function parseModelCatalogSnapshot(value) {
|
|
360
413
|
const MODEL_ID4 = /^[A-Za-z0-9._:/-]{1,128}$/u;
|
|
361
414
|
const GROUPS = ["plan", "paid"];
|
|
362
|
-
const KEYS = ["id", "name", "group", "contextWindow", "maxOutputTokens", "inputModalities", "reasoningEfforts", "defaultEffort"];
|
|
415
|
+
const KEYS = ["id", "name", "group", "contextWindow", "maxOutputTokens", "inputModalities", "reasoningEfforts", "defaultEffort", "nativeProtocol", "coverage"];
|
|
363
416
|
const RESERVED = ["__proto__", "constructor", "prototype"];
|
|
364
417
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
365
418
|
const snapshot = value;
|
|
419
|
+
if (snapshot.binding !== void 0 && (typeof snapshot.binding !== "string" || !/^[a-f0-9]{64}$/u.test(snapshot.binding))) return void 0;
|
|
366
420
|
if (typeof snapshot.baseURL !== "string" || snapshot.baseURL.length === 0 || snapshot.baseURL.length > 2048) return void 0;
|
|
367
421
|
let base;
|
|
368
422
|
try {
|
|
@@ -387,6 +441,14 @@ function parseModelCatalogSnapshot(value) {
|
|
|
387
441
|
if (typeof name2 !== "string" || name2.trim().length === 0 || name2.length > 128) return void 0;
|
|
388
442
|
if (typeof group2 !== "string" || !GROUPS.includes(group2)) return void 0;
|
|
389
443
|
const model = { id, name: name2, group: group2 };
|
|
444
|
+
if (item.nativeProtocol !== void 0) {
|
|
445
|
+
if (!["chat-completions", "responses", "messages"].includes(String(item.nativeProtocol))) return void 0;
|
|
446
|
+
model.nativeProtocol = item.nativeProtocol;
|
|
447
|
+
}
|
|
448
|
+
if (item.coverage !== void 0) {
|
|
449
|
+
if (!["included", "not-included", "unknown"].includes(String(item.coverage))) return void 0;
|
|
450
|
+
model.coverage = item.coverage;
|
|
451
|
+
}
|
|
390
452
|
if (item.contextWindow !== void 0) {
|
|
391
453
|
if (!Number.isSafeInteger(item.contextWindow) || item.contextWindow <= 0 || item.contextWindow > 1e8) return void 0;
|
|
392
454
|
model.contextWindow = item.contextWindow;
|
|
@@ -422,7 +484,7 @@ function parseModelCatalogSnapshot(value) {
|
|
|
422
484
|
seen.add(id);
|
|
423
485
|
models.push(model);
|
|
424
486
|
}
|
|
425
|
-
return { baseURL, updatedAt: snapshot.updatedAt, models };
|
|
487
|
+
return { baseURL, updatedAt: snapshot.updatedAt, models, ...snapshot.binding === void 0 ? {} : { binding: snapshot.binding } };
|
|
426
488
|
}
|
|
427
489
|
|
|
428
490
|
// src/image-budget.ts
|
|
@@ -439,7 +501,7 @@ var DEFAULT_API_KEY_REF = "COROUTER_API_KEY";
|
|
|
439
501
|
var Config = Schema.object({
|
|
440
502
|
apiKeyEnv: Schema.string().max(128).pattern(/^[A-Za-z_][A-Za-z0-9_]*$/u).description(`CoRouter API Key \u7684\u73AF\u5883\u53D8\u91CF\u6216 DSH \u51ED\u636E\u5F15\u7528\u540D\uFF1B\u4E0D\u8BBE\u7F6E\u65F6\u4F7F\u7528 ${DEFAULT_API_KEY_REF}`).volatile(),
|
|
441
503
|
baseURL: Schema.transform(Schema.string(), serializableTransform(assertBaseURL)).default(DEFAULT_BASE_URL).description("CoRouter \u7F51\u5173\u5730\u5740\uFF1B\u4E0D\u7528\u4E8E\u63A7\u5236\u53F0\u767B\u5F55\u6216\u989D\u5EA6\u67E5\u8BE2").volatile(),
|
|
442
|
-
apiProtocol: Schema.union(
|
|
504
|
+
apiProtocol: Schema.union(API_PROTOCOL_SELECTION_IDS).default("auto").description("\u9ED8\u8BA4\u6309\u7CBE\u786E\u578B\u53F7\u9009\u62E9\u539F\u751F\u8BF7\u6C42\u683C\u5F0F\uFF1B\u53EF\u663E\u5F0F\u8986\u76D6\u3002\u672A\u77E5\u8DEF\u7531\u4F7F\u7528\u517C\u5BB9\u63A5\u53E3\uFF0C\u4E0D\u4FDD\u8BC1\u7F51\u5173\u5185\u90E8\u4E0D\u8F6C\u8BD1").volatile(),
|
|
443
505
|
modelSettings: Schema.transform(Schema.dict(Schema.any()), serializableTransform(parseModelSettingsMap)).default({}).description("\u9010\u6A21\u578B\u542F\u7528\u72B6\u6001\u3001\u56FE\u7247\u8F93\u5165\u548C\u8BF7\u6C42\u53C2\u6570").volatile(),
|
|
444
506
|
modelCatalog: Schema.transform(Schema.any(), serializableTransform(parseModelCatalogSnapshot)).description("\u4E0A\u6B21\u6210\u529F\u8BFB\u53D6\u7684\u7F51\u5173\u6A21\u578B\u76EE\u5F55\u5FEB\u7167\uFF1B\u91CD\u542F\u540E\u7EE7\u7EED\u4F7F\u7528\uFF0C\u76F4\u5230\u518D\u6B21\u5237\u65B0").volatile(),
|
|
445
507
|
useDesktopCredential: Schema.boolean().default(true).description("\u4F18\u5148\u8BFB\u53D6 OpenDesign \u684C\u9762\u7AEF\u767B\u5F55\u6001\u67E5\u8BE2\u989D\u5EA6").volatile(),
|
|
@@ -1175,6 +1237,7 @@ var chatCompletions = {
|
|
|
1175
1237
|
};
|
|
1176
1238
|
|
|
1177
1239
|
// src/protocols/messages.ts
|
|
1240
|
+
import { createHash } from "node:crypto";
|
|
1178
1241
|
import {
|
|
1179
1242
|
LlmError as LlmError8,
|
|
1180
1243
|
ToolCallId as ToolCallId2
|
|
@@ -1248,6 +1311,7 @@ import { LlmError as LlmError7 } from "@deepseek-ai/dsh-llm";
|
|
|
1248
1311
|
|
|
1249
1312
|
// src/claude-capabilities.ts
|
|
1250
1313
|
var RESTRICTED_MESSAGES_SAMPLING = /* @__PURE__ */ new Set([
|
|
1314
|
+
"claude-fable-5.2",
|
|
1251
1315
|
"claude-fable-5.1",
|
|
1252
1316
|
"claude-fable-5",
|
|
1253
1317
|
"claude-opus-5.5",
|
|
@@ -1289,7 +1353,30 @@ var DATA_URL = /^data:([^;,]+);base64,(.*)$/su;
|
|
|
1289
1353
|
var REPLAY_FORMAT = "opendesign.anthropic-messages";
|
|
1290
1354
|
var MAX_REPLAY_CHARS = 8 * 1024 * 1024;
|
|
1291
1355
|
var MAX_BLOCKS = 4096;
|
|
1292
|
-
|
|
1356
|
+
var PREFIX_BOUND_MODEL = "claude-fable-5.2";
|
|
1357
|
+
var PREFIX_PATTERN = /^sha256:[a-f0-9]{64}$/u;
|
|
1358
|
+
var MAX_PREFIX_CHARS = 32 * 1024 * 1024;
|
|
1359
|
+
function prefixBinding(system, tools) {
|
|
1360
|
+
const hash2 = createHash("sha256");
|
|
1361
|
+
let size = 0;
|
|
1362
|
+
let bounded = true;
|
|
1363
|
+
const append = (value) => {
|
|
1364
|
+
if (!bounded) return;
|
|
1365
|
+
const text2 = JSON.stringify(value);
|
|
1366
|
+
size += text2.length;
|
|
1367
|
+
if (size > MAX_PREFIX_CHARS) {
|
|
1368
|
+
bounded = false;
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
hash2.update(`${text2.length}:`).update(text2);
|
|
1372
|
+
};
|
|
1373
|
+
append({ system, tools });
|
|
1374
|
+
return { append, snapshot: () => bounded ? `sha256:${hash2.copy().digest("hex")}` : void 0 };
|
|
1375
|
+
}
|
|
1376
|
+
function replayDigest(blocks) {
|
|
1377
|
+
return `sha256:${createHash("sha256").update(JSON.stringify(blocks)).digest("hex")}`;
|
|
1378
|
+
}
|
|
1379
|
+
function replayBlocks(message, ctx, prefix) {
|
|
1293
1380
|
if (message.role !== "assistant" || message.source.provider !== ctx.options.provider || message.source.model !== ctx.options.model) return;
|
|
1294
1381
|
const envelope = message.source.replayState;
|
|
1295
1382
|
if (!record(envelope) || !record(envelope.response) || !Array.isArray(envelope.blocks)) return;
|
|
@@ -1318,6 +1405,7 @@ function replayBlocks(message, ctx) {
|
|
|
1318
1405
|
if (entries.some((entry) => entry.type === "thinking" || entry.type === "redacted_thinking") && (response.origin !== new URL(ctx.baseURL).origin || typeof ctx.credentialIdentity !== "string" || ctx.credentialIdentity.length === 0 || response.credentialIdentity !== ctx.credentialIdentity)) {
|
|
1319
1406
|
throw new LlmError8("\u65E0\u6CD5\u9A8C\u8BC1\u5386\u53F2 Claude \u601D\u8003\u6570\u636E\u5C5E\u4E8E\u5F53\u524D\u51ED\u636E\u3002\u8BF7\u6062\u590D\u539F\u51ED\u636E\u53CA\u56DE\u653E\u7ED1\u5B9A\u8BB0\u5F55\u540E\u91CD\u8BD5\uFF1B\u82E5\u4EC5\u4F7F\u7528\u5185\u5B58\u7ED1\u5B9A\u4E14\u5DF2\u91CD\u542F\uFF0C\u8BF7\u65B0\u5EFA\u4F1A\u8BDD\uFF0C\u6216\u5148\u538B\u7F29\u79FB\u9664\u65E7\u601D\u8003\u53CA\u5176\u5DE5\u5177\u7EED\u63A5\u5386\u53F2\u3002", "INVALID_REQUEST");
|
|
1320
1407
|
}
|
|
1408
|
+
if (ctx.model.id === PREFIX_BOUND_MODEL && (prefix === void 0 || response.requestPrefix !== prefix || response.blocksDigest !== replayDigest(entries))) return;
|
|
1321
1409
|
return entries;
|
|
1322
1410
|
}
|
|
1323
1411
|
function messagesURL(baseURL) {
|
|
@@ -1345,20 +1433,32 @@ function buildMessagesRequest(ctx) {
|
|
|
1345
1433
|
validateClaudeOutput(model.id, maxTokens);
|
|
1346
1434
|
if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) throw new LlmError8("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
|
|
1347
1435
|
const system = [];
|
|
1436
|
+
for (const message of options.messages) if (message.role === "system" || message.role === "developer") {
|
|
1437
|
+
const text2 = projectContent(message.content).text;
|
|
1438
|
+
if (text2) system.push(text2);
|
|
1439
|
+
}
|
|
1440
|
+
if (options.system?.trim()) system.unshift(options.system);
|
|
1441
|
+
const systemText = system.length ? system.join("\n\n") : void 0;
|
|
1442
|
+
const tools = options.tools?.length ? options.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters })) : void 0;
|
|
1443
|
+
const binding = model.id === PREFIX_BOUND_MODEL ? prefixBinding(systemText, tools) : void 0;
|
|
1348
1444
|
const messages2 = [];
|
|
1445
|
+
const pushMessage = (message) => {
|
|
1446
|
+
messages2.push(message);
|
|
1447
|
+
binding?.append(message);
|
|
1448
|
+
};
|
|
1349
1449
|
const lookup = ctx.images.size ? (ref) => ctx.images.get(ref.attachmentId) : void 0;
|
|
1350
1450
|
let results = [];
|
|
1351
1451
|
let lifted = [];
|
|
1352
1452
|
const flushResults = () => {
|
|
1353
1453
|
if (results.length) {
|
|
1354
|
-
|
|
1454
|
+
pushMessage({ role: "user", content: results });
|
|
1355
1455
|
results = [];
|
|
1356
1456
|
}
|
|
1357
1457
|
};
|
|
1358
1458
|
const flushLifted = () => {
|
|
1359
1459
|
flushResults();
|
|
1360
1460
|
if (lifted.length) {
|
|
1361
|
-
|
|
1461
|
+
pushMessage({
|
|
1362
1462
|
role: "user",
|
|
1363
1463
|
content: [{ type: "text", text: "(Image content from the preceding tool result.)" }, ...lifted.map(imagePart)]
|
|
1364
1464
|
});
|
|
@@ -1371,19 +1471,18 @@ function buildMessagesRequest(ctx) {
|
|
|
1371
1471
|
switch (message.role) {
|
|
1372
1472
|
case "system":
|
|
1373
1473
|
case "developer":
|
|
1374
|
-
if (projected.text) system.push(projected.text);
|
|
1375
1474
|
break;
|
|
1376
1475
|
case "user": {
|
|
1377
1476
|
const content2 = [
|
|
1378
1477
|
...projected.text ? [{ type: "text", text: projected.text }] : [],
|
|
1379
1478
|
...projected.images.map(imagePart)
|
|
1380
1479
|
];
|
|
1381
|
-
if (content2.length)
|
|
1480
|
+
if (content2.length) pushMessage({ role: "user", content: content2 });
|
|
1382
1481
|
break;
|
|
1383
1482
|
}
|
|
1384
1483
|
case "assistant": {
|
|
1385
1484
|
const content2 = [];
|
|
1386
|
-
const replay = replayBlocks(message, ctx);
|
|
1485
|
+
const replay = replayBlocks(message, ctx, binding?.snapshot());
|
|
1387
1486
|
for (const [index, block] of message.content.entries()) {
|
|
1388
1487
|
const entry = replay?.[index];
|
|
1389
1488
|
if (entry?.type === "thinking") content2.push({ type: "thinking", thinking: entry.thinking, signature: entry.signature });
|
|
@@ -1395,7 +1494,7 @@ function buildMessagesRequest(ctx) {
|
|
|
1395
1494
|
if (placeholder) content2.push({ type: "text", text: placeholder });
|
|
1396
1495
|
}
|
|
1397
1496
|
}
|
|
1398
|
-
if (content2.length)
|
|
1497
|
+
if (content2.length) pushMessage({ role: "assistant", content: content2 });
|
|
1399
1498
|
break;
|
|
1400
1499
|
}
|
|
1401
1500
|
case "tool": {
|
|
@@ -1410,22 +1509,28 @@ function buildMessagesRequest(ctx) {
|
|
|
1410
1509
|
}
|
|
1411
1510
|
}
|
|
1412
1511
|
flushLifted();
|
|
1413
|
-
if (options.system?.trim()) system.unshift(options.system);
|
|
1414
1512
|
const body = { model: model.id, max_tokens: maxTokens, messages: messages2, stream: true };
|
|
1415
|
-
if (
|
|
1416
|
-
if (
|
|
1513
|
+
if (systemText !== void 0) body.system = systemText;
|
|
1514
|
+
if (tools !== void 0) body.tools = tools;
|
|
1417
1515
|
if (options.temperature !== void 0) body.temperature = options.temperature;
|
|
1418
1516
|
if (ctx.topP !== void 0) body.top_p = ctx.topP;
|
|
1419
1517
|
if (options.stop?.length) body.stop_sequences = options.stop;
|
|
1420
1518
|
if (options.reasoningEffort !== void 0) {
|
|
1421
1519
|
const effort = String(options.reasoningEffort);
|
|
1520
|
+
if (effort === "none" && model.id === PREFIX_BOUND_MODEL) throw new LlmError8("Claude Fable 5.2 \u4E0D\u652F\u6301\u5173\u95ED\u601D\u8003", "UNSUPPORTED_OPTION");
|
|
1422
1521
|
if (effort === "none") body.thinking = { type: "disabled" };
|
|
1423
1522
|
else if (protocolAcceptsEffort("messages", effort)) {
|
|
1424
1523
|
body.thinking = { type: "adaptive" };
|
|
1425
1524
|
body.output_config = { effort };
|
|
1426
1525
|
} else throw new LlmError8(`Anthropic Messages \u534F\u8BAE\u4E0D\u63A5\u53D7\u601D\u8003\u6DF1\u5EA6\u300C${effort}\u300D`, "UNSUPPORTED_OPTION");
|
|
1427
1526
|
}
|
|
1428
|
-
|
|
1527
|
+
const replayPrefix = binding?.snapshot();
|
|
1528
|
+
return {
|
|
1529
|
+
url: messagesURL(ctx.baseURL),
|
|
1530
|
+
headers: streamHeaders(ctx.apiKey, { "anthropic-version": ANTHROPIC_VERSION }),
|
|
1531
|
+
body,
|
|
1532
|
+
...replayPrefix === void 0 ? {} : { replayPrefix }
|
|
1533
|
+
};
|
|
1429
1534
|
}
|
|
1430
1535
|
function num(value) {
|
|
1431
1536
|
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
@@ -1477,6 +1582,7 @@ async function* streamMessages(body, signal, idleMs, context) {
|
|
|
1477
1582
|
}
|
|
1478
1583
|
function replay() {
|
|
1479
1584
|
if (!context?.credentialIdentity || ![...blocks.values()].some((state) => state.signature !== "" || state.kind === "redacted")) return;
|
|
1585
|
+
if (context.model === PREFIX_BOUND_MODEL && (context.replayPrefix === void 0 || !PREFIX_PATTERN.test(context.replayPrefix))) return;
|
|
1480
1586
|
const entries = [];
|
|
1481
1587
|
for (const state of blocks.values()) {
|
|
1482
1588
|
if (!state.started) continue;
|
|
@@ -1492,7 +1598,8 @@ async function* streamMessages(body, signal, idleMs, context) {
|
|
|
1492
1598
|
provider: context.provider,
|
|
1493
1599
|
model: context.model,
|
|
1494
1600
|
origin: new URL(context.baseURL).origin,
|
|
1495
|
-
credentialIdentity: context.credentialIdentity
|
|
1601
|
+
credentialIdentity: context.credentialIdentity,
|
|
1602
|
+
...context.model === PREFIX_BOUND_MODEL ? { requestPrefix: context.replayPrefix, blocksDigest: replayDigest(entries) } : {}
|
|
1496
1603
|
}, blocks: entries };
|
|
1497
1604
|
}
|
|
1498
1605
|
function reasonFromStop(stop) {
|
|
@@ -1699,6 +1806,90 @@ import {
|
|
|
1699
1806
|
LlmError as LlmError9,
|
|
1700
1807
|
ToolCallId as ToolCallId3
|
|
1701
1808
|
} from "@deepseek-ai/dsh-llm";
|
|
1809
|
+
|
|
1810
|
+
// src/protocols/responses-replay.ts
|
|
1811
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1812
|
+
var FORMAT = "opendesign.responses";
|
|
1813
|
+
var MAX_CHARS = 8 * 1024 * 1024;
|
|
1814
|
+
var MAX_ITEMS = 4096;
|
|
1815
|
+
var digest = (value) => createHash2("sha256").update(JSON.stringify(value)).digest("hex");
|
|
1816
|
+
function outputItems(value) {
|
|
1817
|
+
if (!Array.isArray(value) || value.length > MAX_ITEMS) return;
|
|
1818
|
+
const serialized = JSON.stringify(value);
|
|
1819
|
+
if (serialized.length > MAX_CHARS) return;
|
|
1820
|
+
const out = [];
|
|
1821
|
+
for (const item of value) {
|
|
1822
|
+
if (!record(item) || typeof item.id !== "string" || item.id.length > 512) return;
|
|
1823
|
+
if (item.type === "reasoning") {
|
|
1824
|
+
if (item.encrypted_content !== void 0 && item.encrypted_content !== null && typeof item.encrypted_content !== "string") return;
|
|
1825
|
+
if (!Array.isArray(item.summary)) return;
|
|
1826
|
+
const summary = [];
|
|
1827
|
+
for (const entry of item.summary) {
|
|
1828
|
+
if (!record(entry) || entry.type !== "summary_text" || typeof entry.text !== "string") return;
|
|
1829
|
+
summary.push({ type: "summary_text", text: entry.text });
|
|
1830
|
+
}
|
|
1831
|
+
const content2 = [];
|
|
1832
|
+
if (item.content !== void 0) {
|
|
1833
|
+
if (!Array.isArray(item.content)) return;
|
|
1834
|
+
for (const part of item.content) {
|
|
1835
|
+
if (!record(part) || part.type !== "reasoning_text" || typeof part.text !== "string") return;
|
|
1836
|
+
content2.push({ type: "reasoning_text", text: part.text });
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
if (typeof item.encrypted_content === "string" && item.encrypted_content.length > 0) out.push({ type: "reasoning", id: item.id, encrypted_content: item.encrypted_content, summary, ...item.content === void 0 ? {} : { content: content2 } });
|
|
1840
|
+
} else if (item.type === "message") {
|
|
1841
|
+
if (item.role !== "assistant" || !Array.isArray(item.content)) return;
|
|
1842
|
+
const content2 = [];
|
|
1843
|
+
for (const part of item.content) {
|
|
1844
|
+
if (!record(part)) return;
|
|
1845
|
+
if (part.type === "output_text" && typeof part.text === "string") content2.push({ type: "output_text", text: part.text, annotations: [] });
|
|
1846
|
+
else if (part.type === "refusal" && typeof part.refusal === "string") content2.push({ type: "refusal", refusal: part.refusal });
|
|
1847
|
+
else return;
|
|
1848
|
+
}
|
|
1849
|
+
if (item.phase !== void 0 && !["commentary", "final_answer"].includes(String(item.phase))) return;
|
|
1850
|
+
out.push({ type: "message", id: item.id, role: "assistant", content: content2, ...item.phase ? { phase: item.phase } : {} });
|
|
1851
|
+
} else if (item.type === "function_call") {
|
|
1852
|
+
if (typeof item.call_id !== "string" || typeof item.name !== "string" || typeof item.arguments !== "string") return;
|
|
1853
|
+
out.push({ type: "function_call", id: item.id, call_id: item.call_id, name: item.name, arguments: item.arguments });
|
|
1854
|
+
} else return;
|
|
1855
|
+
}
|
|
1856
|
+
return out;
|
|
1857
|
+
}
|
|
1858
|
+
function visibleMatches(items, blocks) {
|
|
1859
|
+
const text2 = items.filter((item) => item.type === "message").flatMap((item) => item.content).map((part) => part.text ?? part.refusal ?? "").join("");
|
|
1860
|
+
if (text2 !== blocks.filter((block) => block.type === "text").map((block) => block.text).join("")) return false;
|
|
1861
|
+
const calls = items.filter((item) => item.type === "function_call").map((item) => [item.call_id, item.name, item.arguments]);
|
|
1862
|
+
const actual = blocks.filter((block) => block.type === "tool-call").map((block) => [block.id, block.name, block.arguments]);
|
|
1863
|
+
return JSON.stringify(calls) === JSON.stringify(actual);
|
|
1864
|
+
}
|
|
1865
|
+
function responseReplay(message, ctx) {
|
|
1866
|
+
if (message.role !== "assistant" || message.source.provider !== ctx.options.provider || message.source.model !== ctx.model.id) return;
|
|
1867
|
+
const state = message.source.replayState;
|
|
1868
|
+
if (!record(state) || !record(state.response) || !Array.isArray(state.blocks) || state.blocks.length !== message.content.length) return;
|
|
1869
|
+
const response = state.response;
|
|
1870
|
+
if (response.format !== FORMAT || response.version !== 1 || response.provider !== ctx.options.provider || response.model !== ctx.model.id || response.baseURL !== ctx.baseURL || !ctx.credentialIdentity || response.credentialIdentity !== ctx.credentialIdentity || response.blocksDigest !== digest(message.content) || JSON.stringify(state.blocks) !== JSON.stringify(message.content)) return;
|
|
1871
|
+
const items = outputItems(response.output);
|
|
1872
|
+
return items && visibleMatches(items, message.content) ? items : void 0;
|
|
1873
|
+
}
|
|
1874
|
+
function responseReplayEnvelope(output, closed, context) {
|
|
1875
|
+
if (!context?.credentialIdentity) return;
|
|
1876
|
+
const items = outputItems(output);
|
|
1877
|
+
if (!items?.length || !items.some((item) => item.type === "reasoning" || item.phase !== void 0)) return;
|
|
1878
|
+
const blocks = closed.filter((chunk) => chunk.type === "block-end").map((chunk) => chunk.block);
|
|
1879
|
+
if (blocks.length > MAX_ITEMS || JSON.stringify(blocks).length > MAX_CHARS || !visibleMatches(items, blocks)) return;
|
|
1880
|
+
return { response: {
|
|
1881
|
+
format: FORMAT,
|
|
1882
|
+
version: 1,
|
|
1883
|
+
provider: context.provider,
|
|
1884
|
+
model: context.model,
|
|
1885
|
+
baseURL: context.baseURL,
|
|
1886
|
+
credentialIdentity: context.credentialIdentity,
|
|
1887
|
+
blocksDigest: digest(blocks),
|
|
1888
|
+
output: items
|
|
1889
|
+
}, blocks };
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
// src/protocols/responses.ts
|
|
1702
1893
|
function userContent(text2, images) {
|
|
1703
1894
|
if (!images.length) return text2;
|
|
1704
1895
|
return [
|
|
@@ -1729,6 +1920,11 @@ function buildResponsesRequest(ctx) {
|
|
|
1729
1920
|
if (projected.text || projected.images.length) input.push({ role: "user", content: userContent(projected.text, projected.images) });
|
|
1730
1921
|
break;
|
|
1731
1922
|
case "assistant": {
|
|
1923
|
+
const replay = responseReplay(message, ctx);
|
|
1924
|
+
if (replay) {
|
|
1925
|
+
input.push(...replay);
|
|
1926
|
+
break;
|
|
1927
|
+
}
|
|
1732
1928
|
if (projected.text) input.push({ role: "assistant", content: projected.text });
|
|
1733
1929
|
for (const block of message.content) {
|
|
1734
1930
|
if (block.type === "tool-call") input.push({ type: "function_call", call_id: block.id, name: block.name, arguments: block.arguments });
|
|
@@ -1748,7 +1944,7 @@ function buildResponsesRequest(ctx) {
|
|
|
1748
1944
|
}
|
|
1749
1945
|
flushLifted();
|
|
1750
1946
|
if (options.system?.trim()) instructions.unshift(options.system);
|
|
1751
|
-
const body = { model: model.id, input, stream: true, store: false };
|
|
1947
|
+
const body = { model: model.id, input, stream: true, store: false, include: ["reasoning.encrypted_content"] };
|
|
1752
1948
|
if (instructions.length) body.instructions = instructions.join("\n\n");
|
|
1753
1949
|
if (options.tools?.length) body.tools = options.tools.map((tool) => ({ type: "function", name: tool.name, description: tool.description, parameters: tool.parameters }));
|
|
1754
1950
|
if (options.temperature !== void 0) body.temperature = options.temperature;
|
|
@@ -1784,7 +1980,7 @@ function responseUsage(response) {
|
|
|
1784
1980
|
reasoning: typeof output.reasoning_tokens === "number" ? output.reasoning_tokens : void 0
|
|
1785
1981
|
});
|
|
1786
1982
|
}
|
|
1787
|
-
async function* streamResponses(body, signal, idleMs) {
|
|
1983
|
+
async function* streamResponses(body, signal, idleMs, context) {
|
|
1788
1984
|
let nextIndex = 0;
|
|
1789
1985
|
let count2 = 0;
|
|
1790
1986
|
let usage;
|
|
@@ -2020,10 +2216,12 @@ async function* streamResponses(body, signal, idleMs) {
|
|
|
2020
2216
|
const reason = reasonOf(type, response);
|
|
2021
2217
|
if (reason.kind === "tool-calls" && calls.size === 0) throw new LlmError9("OpenDesign\uFF1A\u54CD\u5E94\u58F0\u660E\u5DE5\u5177\u8C03\u7528\uFF0C\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5DE5\u5177\u5757", "INVALID_RESPONSE");
|
|
2022
2218
|
if (!count2) throw new LlmError9("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
|
|
2023
|
-
|
|
2219
|
+
const closed = close();
|
|
2220
|
+
out.push(...closed);
|
|
2024
2221
|
if (usage) out.push({ type: "usage", usage });
|
|
2025
2222
|
finish = reason;
|
|
2026
|
-
|
|
2223
|
+
const replayState = responseReplayEnvelope(response.output, closed, context);
|
|
2224
|
+
out.push({ type: "finish", reason, ...replayState ? { replayState } : {} });
|
|
2027
2225
|
break;
|
|
2028
2226
|
}
|
|
2029
2227
|
case "error":
|
|
@@ -2067,7 +2265,7 @@ function outputReserve(model, protocol) {
|
|
|
2067
2265
|
}
|
|
2068
2266
|
function metadata(provider, row, config) {
|
|
2069
2267
|
const setting = config.modelSettings?.[row.id];
|
|
2070
|
-
const protocol = config.apiProtocol
|
|
2268
|
+
const protocol = effectiveProtocol(row, config.apiProtocol, setting?.apiProtocol);
|
|
2071
2269
|
const proposedReserve = setting?.maxTokens ?? outputReserve(row, protocol);
|
|
2072
2270
|
const reserve = claudeOutputError(row.id, protocol, proposedReserve) === void 0 ? proposedReserve : void 0;
|
|
2073
2271
|
const efforts = modelReasoningEfforts(row, protocol);
|
|
@@ -2097,12 +2295,12 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
2097
2295
|
this.#lifetime.abort(new LlmError11("CoRouter \u63D2\u4EF6\u5DF2\u5378\u8F7D", "ABORTED"));
|
|
2098
2296
|
this.#credentialSecret.fill(0);
|
|
2099
2297
|
}
|
|
2100
|
-
async #credentialIdentity(baseURL, key, model, signal) {
|
|
2298
|
+
async #credentialIdentity(baseURL, key, model, signal, workspace) {
|
|
2101
2299
|
let secret2;
|
|
2102
2300
|
let abort = () => {
|
|
2103
2301
|
};
|
|
2104
2302
|
try {
|
|
2105
|
-
if (this.options.replayBindingSecret
|
|
2303
|
+
if (this.options.replayBindingSecret) {
|
|
2106
2304
|
const operation = this.options.replayBindingSecret(signal).then((bytes) => {
|
|
2107
2305
|
if (signal.aborted) {
|
|
2108
2306
|
bytes.fill(0);
|
|
@@ -2119,7 +2317,9 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
2119
2317
|
} else secret2 = Buffer.from(this.#credentialSecret);
|
|
2120
2318
|
signal.throwIfAborted();
|
|
2121
2319
|
if (secret2.length !== 32) throw new Error("invalid binding");
|
|
2122
|
-
|
|
2320
|
+
const identity = createHmac("sha256", secret2).update("opendesign-claude-replay-v1\0").update(new URL(baseURL).origin).update("\0").update(key);
|
|
2321
|
+
if (workspace !== void 0) identity.update("\0workspace\0").update(workspace);
|
|
2322
|
+
return identity.digest("hex");
|
|
2123
2323
|
} catch {
|
|
2124
2324
|
if (signal.aborted) throw new LlmError11("Claude \u56DE\u653E\u7ED1\u5B9A\u5DF2\u53D6\u6D88", "ABORTED");
|
|
2125
2325
|
throw new LlmError11("\u65E0\u6CD5\u8BFB\u53D6\u6216\u5B89\u5168\u4FDD\u5B58 Claude \u56DE\u653E\u7ED1\u5B9A\u5BC6\u94A5\uFF0C\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u670D\u52A1\u540E\u91CD\u8BD5\u3002", "INVALID_REQUEST");
|
|
@@ -2141,6 +2341,7 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
2141
2341
|
return configured;
|
|
2142
2342
|
}
|
|
2143
2343
|
async listModels(provider) {
|
|
2344
|
+
await this.#ready();
|
|
2144
2345
|
const config = this.options.config(), selectedGroup = group(provider);
|
|
2145
2346
|
return (this.options.models?.() ?? MODELS).filter((row) => row.group === selectedGroup && isModelEnabled(row.id, config.modelSettings)).map((row) => {
|
|
2146
2347
|
const effective = applyModelSettings(row, config.modelSettings?.[row.id]);
|
|
@@ -2149,23 +2350,59 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
2149
2350
|
}
|
|
2150
2351
|
async resolveModel(provider, model, signal) {
|
|
2151
2352
|
signal?.throwIfAborted();
|
|
2353
|
+
await this.#ready(signal);
|
|
2152
2354
|
const config = this.options.config();
|
|
2153
2355
|
return metadata(provider, this.modelOf(provider, model, config), config);
|
|
2154
2356
|
}
|
|
2155
2357
|
async prepareCall(provider, model, signal) {
|
|
2156
2358
|
signal?.throwIfAborted();
|
|
2359
|
+
await this.#ready(signal);
|
|
2157
2360
|
const config = this.options.config(), row = this.modelOf(provider, model, config);
|
|
2158
|
-
|
|
2361
|
+
const settings = config.modelSettings?.[row.id];
|
|
2362
|
+
const protocol = effectiveProtocol(row, config.apiProtocol, settings?.apiProtocol);
|
|
2363
|
+
if (settings?.reasoningEffort !== void 0 && !modelReasoningEfforts(row, protocol)?.includes(settings.reasoningEffort)) throw new LlmError11("\u6240\u9009\u601D\u8003\u6DF1\u5EA6\u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u6A21\u578B\u6216\u534F\u8BAE\uFF1B\u8BF7\u4FEE\u6539\u9ED8\u8BA4\u503C\u6216\u9009\u62E9\u5176\u4ED6\u6863\u4F4D", "UNSUPPORTED_OPTION");
|
|
2364
|
+
if (protocol === "messages") {
|
|
2365
|
+
validateClaudeSampling(row.id, settings?.temperature, settings?.topP);
|
|
2366
|
+
validateClaudeOutput(row.id, settings?.maxTokens);
|
|
2367
|
+
}
|
|
2368
|
+
const identity = this.options.callIdentity?.();
|
|
2369
|
+
if (this.options.callIdentity && !identity) throw new LlmError11("\u5F53\u524D\u8D26\u53F7\u6A21\u578B\u76EE\u5F55\u5C1A\u672A\u6838\u5B9E\uFF0C\u8BF7\u767B\u5F55\u6216\u5237\u65B0\u6A21\u578B\u76EE\u5F55\u540E\u91CD\u8BD5", "INVALID_REQUEST");
|
|
2370
|
+
const raw = identity?.key ?? await this.options.apiKey(apiKeyRef(config), config.baseURL);
|
|
2371
|
+
signal?.throwIfAborted();
|
|
2372
|
+
return { model: metadata(provider, row, config), stream: (options) => this.#stream(options, config, row, identity?.workspace, raw, true) };
|
|
2159
2373
|
}
|
|
2160
2374
|
stream(options) {
|
|
2161
2375
|
const config = this.options.config();
|
|
2162
|
-
|
|
2376
|
+
const identity = this.options.callIdentity?.();
|
|
2377
|
+
if (this.options.callIdentity && !identity) throw new LlmError11("\u5F53\u524D\u8D26\u53F7\u6A21\u578B\u76EE\u5F55\u5C1A\u672A\u6838\u5B9E\uFF0C\u8BF7\u767B\u5F55\u6216\u5237\u65B0\u6A21\u578B\u76EE\u5F55\u540E\u91CD\u8BD5", "INVALID_REQUEST");
|
|
2378
|
+
return this.#stream(options, config, this.modelOf(options.provider, options.model, config), identity?.workspace, identity?.key, identity !== void 0);
|
|
2379
|
+
}
|
|
2380
|
+
async #ready(signal) {
|
|
2381
|
+
const operation = this.options.readyModels?.();
|
|
2382
|
+
if (!operation) return;
|
|
2383
|
+
if (!signal) {
|
|
2384
|
+
await operation;
|
|
2385
|
+
return;
|
|
2386
|
+
}
|
|
2387
|
+
let cancelled2 = () => {
|
|
2388
|
+
};
|
|
2389
|
+
try {
|
|
2390
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
2391
|
+
cancelled2 = () => reject(new LlmError11("\u6A21\u578B\u76EE\u5F55\u7B49\u5F85\u5DF2\u53D6\u6D88", "ABORTED"));
|
|
2392
|
+
signal.addEventListener("abort", cancelled2, { once: true });
|
|
2393
|
+
if (signal.aborted) cancelled2();
|
|
2394
|
+
});
|
|
2395
|
+
await Promise.race([operation, aborted]);
|
|
2396
|
+
signal.throwIfAborted();
|
|
2397
|
+
} finally {
|
|
2398
|
+
signal.removeEventListener("abort", cancelled2);
|
|
2399
|
+
}
|
|
2163
2400
|
}
|
|
2164
|
-
async *#stream(options, config, row) {
|
|
2401
|
+
async *#stream(options, config, row, workspace, capturedKey, captured = false) {
|
|
2165
2402
|
const signal = AbortSignal.any([combinedSignal(options.signal, config.requestTimeoutMs), this.#lifetime.signal]);
|
|
2166
2403
|
signal.throwIfAborted();
|
|
2167
2404
|
const setting = config.modelSettings?.[row.id] ?? {};
|
|
2168
|
-
const protocolId = config.apiProtocol
|
|
2405
|
+
const protocolId = effectiveProtocol(row, config.apiProtocol, setting.apiProtocol);
|
|
2169
2406
|
const configured = setting.reasoningEffort;
|
|
2170
2407
|
const explicit = options.reasoningEffort ?? (configured === void 0 ? void 0 : ReasoningEffortId(configured));
|
|
2171
2408
|
if (explicit !== void 0 && !modelReasoningEfforts(row, protocolId)?.includes(explicit)) throw new LlmError11("\u6240\u9009\u601D\u8003\u6DF1\u5EA6\u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u6A21\u578B\u6216\u534F\u8BAE\uFF1B\u8BF7\u4FEE\u6539\u9ED8\u8BA4\u503C\u6216\u9009\u62E9\u5176\u4ED6\u6863\u4F4D", "UNSUPPORTED_OPTION");
|
|
@@ -2176,14 +2413,14 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
2176
2413
|
validateClaudeOutput(row.id, options.maxTokens ?? setting.maxTokens);
|
|
2177
2414
|
}
|
|
2178
2415
|
const keyRef = apiKeyRef(config);
|
|
2179
|
-
const raw = await this.options.apiKey(keyRef, config.baseURL);
|
|
2416
|
+
const raw = captured ? capturedKey : await this.options.apiKey(keyRef, config.baseURL);
|
|
2180
2417
|
if (!raw) throw new LlmError11("\u672A\u914D\u7F6E\u5F53\u524D\u7F51\u5173\u7684\u63A8\u7406\u51ED\u636E\uFF1B\u8BF7\u5B8C\u6210\u8BBE\u5907\u6388\u6743\u6216\u914D\u7F6E\u5BF9\u5E94 API Key", "MISSING_CREDENTIAL");
|
|
2181
2418
|
const key = assertUsableApiKey(raw, "dsh-opendesign-corouter", keyRef);
|
|
2182
2419
|
signal.throwIfAborted();
|
|
2183
2420
|
let credentialIdentity;
|
|
2184
|
-
if (protocolId === "messages") {
|
|
2421
|
+
if (protocolId === "messages" || protocolId === "responses") {
|
|
2185
2422
|
try {
|
|
2186
|
-
credentialIdentity = await this.#credentialIdentity(config.baseURL, key, row.id, signal);
|
|
2423
|
+
credentialIdentity = await this.#credentialIdentity(config.baseURL, key, row.id, signal, workspace);
|
|
2187
2424
|
} catch (error) {
|
|
2188
2425
|
if (signal.aborted && !options.signal?.aborted && !this.#lifetime.signal.aborted) throw new LlmError11("CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6", "TIMEOUT");
|
|
2189
2426
|
throw error;
|
|
@@ -2248,7 +2485,7 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
2248
2485
|
try {
|
|
2249
2486
|
response = await (this.options.fetch ?? fetch)(request.url, {
|
|
2250
2487
|
method: "POST",
|
|
2251
|
-
headers: request.headers,
|
|
2488
|
+
headers: { ...request.headers, ...workspace ? { "x-vela-workspace-id": workspace } : {} },
|
|
2252
2489
|
body: JSON.stringify(request.body),
|
|
2253
2490
|
signal,
|
|
2254
2491
|
redirect: "error"
|
|
@@ -2309,7 +2546,8 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
2309
2546
|
provider: options.provider,
|
|
2310
2547
|
model: options.model,
|
|
2311
2548
|
baseURL: config.baseURL,
|
|
2312
|
-
...credentialIdentity === void 0 ? {} : { credentialIdentity }
|
|
2549
|
+
...credentialIdentity === void 0 ? {} : { credentialIdentity },
|
|
2550
|
+
...request.replayPrefix === void 0 ? {} : { replayPrefix: request.replayPrefix }
|
|
2313
2551
|
})) {
|
|
2314
2552
|
signal.throwIfAborted();
|
|
2315
2553
|
tracker.observe(chunk);
|
|
@@ -2485,7 +2723,7 @@ function installEotRecovery(ctx, enabled, onRetry) {
|
|
|
2485
2723
|
}
|
|
2486
2724
|
|
|
2487
2725
|
// src/turn-monitor.ts
|
|
2488
|
-
import { createHash } from "node:crypto";
|
|
2726
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
2489
2727
|
import { createUserMessage, LlmError as LlmError13 } from "@deepseek-ai/dsh-llm";
|
|
2490
2728
|
var FINISH_TURN_TOOL = "opendesign_finish_turn";
|
|
2491
2729
|
var MAX_EVIDENCE = 64;
|
|
@@ -2655,7 +2893,7 @@ var TurnMonitor = class {
|
|
|
2655
2893
|
}
|
|
2656
2894
|
if (event.type === "tool/call" && typeof data.callId === "string" && typeof data.name === "string") {
|
|
2657
2895
|
if (state.calls.size >= MAX_EVIDENCE) state.calls.delete(state.calls.keys().next().value ?? "");
|
|
2658
|
-
state.calls.set(data.callId, { name: data.name, arguments:
|
|
2896
|
+
state.calls.set(data.callId, { name: data.name, arguments: createHash3("sha256").update(typeof data.arguments === "string" ? data.arguments : "").digest("hex") });
|
|
2659
2897
|
return;
|
|
2660
2898
|
}
|
|
2661
2899
|
if (event.type !== "tool/result" || !record(data.message) || typeof data.message.toolCallId !== "string") return;
|
|
@@ -2667,7 +2905,7 @@ var TurnMonitor = class {
|
|
|
2667
2905
|
const call = state.calls.get(callId);
|
|
2668
2906
|
state.calls.delete(callId);
|
|
2669
2907
|
if (!call || call.name === FINISH_TURN_TOOL || pending) return;
|
|
2670
|
-
const fingerprint =
|
|
2908
|
+
const fingerprint = createHash3("sha256").update(JSON.stringify([call.name, call.arguments, data.message.content, data.message.isError === true])).digest("hex");
|
|
2671
2909
|
const success = data.message.isError !== true;
|
|
2672
2910
|
if (success && !state.fingerprints.has(fingerprint)) {
|
|
2673
2911
|
state.progress++;
|
|
@@ -2889,7 +3127,7 @@ var MAX_MODELS = 512;
|
|
|
2889
3127
|
var MAX_MODEL_NAME_LENGTH = 128;
|
|
2890
3128
|
var MAX_CONTEXT_WINDOW = 1e8;
|
|
2891
3129
|
var MODEL_ID = /^[A-Za-z0-9._:/-]{1,128}$/u;
|
|
2892
|
-
var MEDIA_MODEL_ID = /^(?:gpt-image-|nano-banana-|seedream-|imagen-|veo-|doubao-seedance-|sora-)/u;
|
|
3130
|
+
var MEDIA_MODEL_ID = /^(?:gpt-image-|nano-banana-|seedream-|imagen-|veo-|doubao-seedance-|seedance-|sora-|wan-|elevenlabs-|byteplus-)/u;
|
|
2893
3131
|
var MESSAGES2 = {
|
|
2894
3132
|
url: "\u6A21\u578B\u53D1\u73B0\u5730\u5740\u65E0\u6548\uFF1A\u5FC5\u987B\u662F\u7EDD\u5BF9 HTTP(S) \u5730\u5740\uFF0C\u4E14\u4E0D\u542B\u51ED\u636E\u3001\u67E5\u8BE2\u4E32\u6216\u7247\u6BB5",
|
|
2895
3133
|
credential: "\u6A21\u578B\u53D1\u73B0\u51ED\u636E\u7F3A\u5931\uFF0C\u6216\u542B\u6709\u4E0D\u53EF\u7528\u4E8E HTTP \u8BF7\u6C42\u5934\u7684\u5B57\u7B26",
|
|
@@ -2993,7 +3231,7 @@ function normalize(body) {
|
|
|
2993
3231
|
}
|
|
2994
3232
|
return rows;
|
|
2995
3233
|
}
|
|
2996
|
-
async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher) {
|
|
3234
|
+
async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher, workspaceId) {
|
|
2997
3235
|
let base;
|
|
2998
3236
|
try {
|
|
2999
3237
|
base = openAiBaseURL(assertBaseURL(openAiBaseURL2));
|
|
@@ -3012,7 +3250,7 @@ async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher) {
|
|
|
3012
3250
|
try {
|
|
3013
3251
|
response = await request(`${base}/models`, {
|
|
3014
3252
|
method: "GET",
|
|
3015
|
-
headers: { ...attributionHeaders2(), authorization: `Bearer ${credential}`, accept: "application/json" },
|
|
3253
|
+
headers: { ...attributionHeaders2(), authorization: `Bearer ${credential}`, accept: "application/json", ...workspaceId && /^[A-Za-z0-9_-]{1,128}$/u.test(workspaceId) ? { "x-vela-workspace-id": workspaceId } : {} },
|
|
3016
3254
|
signal: deadline,
|
|
3017
3255
|
redirect: "error"
|
|
3018
3256
|
});
|
|
@@ -3028,138 +3266,824 @@ async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher) {
|
|
|
3028
3266
|
return normalize(await boundedJson(response, signal, deadline));
|
|
3029
3267
|
}
|
|
3030
3268
|
|
|
3031
|
-
// src/
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
this.status = status;
|
|
3050
|
-
this.name = "PricingError";
|
|
3269
|
+
// src/model-directory.ts
|
|
3270
|
+
import { createHmac as createHmac2 } from "node:crypto";
|
|
3271
|
+
|
|
3272
|
+
// src/auth.ts
|
|
3273
|
+
import { readFile as fsReadFile } from "node:fs/promises";
|
|
3274
|
+
import { homedir as osHomedir } from "node:os";
|
|
3275
|
+
import { join } from "node:path";
|
|
3276
|
+
var DEFAULT_API_URL = "https://amr-api.open-design.ai";
|
|
3277
|
+
var API_HOST = "amr-api.open-design.ai";
|
|
3278
|
+
var DESKTOP_PROFILES = ["prod", "test", "feature-test", "local"];
|
|
3279
|
+
var DEFAULT_PROFILE = "prod";
|
|
3280
|
+
var COOKIE_ENV_REFS = ["OPEN_DESIGN_COOKIE", "OPEN_DESIGN_SESSION"];
|
|
3281
|
+
function isOfficialApiUrl(raw) {
|
|
3282
|
+
let url;
|
|
3283
|
+
try {
|
|
3284
|
+
url = new URL(raw);
|
|
3285
|
+
} catch {
|
|
3286
|
+
return false;
|
|
3051
3287
|
}
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
"&": "&",
|
|
3058
|
-
"<": "<",
|
|
3059
|
-
">": ">",
|
|
3060
|
-
"'": "'",
|
|
3061
|
-
" ": " ",
|
|
3062
|
-
"—": "\u2014",
|
|
3063
|
-
"–": "\u2013"
|
|
3064
|
-
};
|
|
3065
|
-
function decodeEntities(text2) {
|
|
3066
|
-
return text2.replace(/&(?:quot|amp|lt|gt|apos|nbsp|mdash|ndash);/gu, (match) => ENTITIES[match] ?? match).replace(/&#(\d+);/gu, (_match, code) => {
|
|
3067
|
-
const point = Number(code);
|
|
3068
|
-
return Number.isInteger(point) && point > 0 && point <= 1114111 ? String.fromCodePoint(point) : "";
|
|
3069
|
-
});
|
|
3070
|
-
}
|
|
3071
|
-
function stripTags(text2) {
|
|
3072
|
-
return decodeEntities(text2.replace(/<[^>]*>/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
3073
|
-
}
|
|
3074
|
-
function metricOf(label) {
|
|
3075
|
-
if (/缓存读取|cache\s+read/iu.test(label)) return "cacheRead";
|
|
3076
|
-
if (/缓存写入|cache\s+write/iu.test(label)) return "cacheWrite";
|
|
3077
|
-
if (/^\s*(?:输入|input)/iu.test(label)) return "input";
|
|
3078
|
-
if (/^\s*(?:输出|output)/iu.test(label)) return "output";
|
|
3079
|
-
return void 0;
|
|
3080
|
-
}
|
|
3081
|
-
function unitOf(label) {
|
|
3082
|
-
if (/百万\s*token|1m\s*tokens?/iu.test(label)) return "per_1m_tokens";
|
|
3083
|
-
if (/千\s*token|1k\s*tokens?/iu.test(label)) return "per_1k_tokens";
|
|
3084
|
-
return null;
|
|
3288
|
+
if (url.protocol !== "https:") return false;
|
|
3289
|
+
if (url.username || url.password) return false;
|
|
3290
|
+
if (url.search || url.hash) return false;
|
|
3291
|
+
if (url.pathname !== "/" && url.pathname !== "") return false;
|
|
3292
|
+
return url.hostname.toLowerCase() === API_HOST && !url.port;
|
|
3085
3293
|
}
|
|
3086
|
-
function
|
|
3087
|
-
|
|
3088
|
-
return
|
|
3294
|
+
function normalizeApiUrl(raw) {
|
|
3295
|
+
const value = typeof raw === "string" ? raw.trim() : "";
|
|
3296
|
+
if (!value) return void 0;
|
|
3297
|
+
if (!isOfficialApiUrl(value)) return void 0;
|
|
3298
|
+
const url = new URL(value);
|
|
3299
|
+
return `https://${url.hostname.toLowerCase()}`;
|
|
3089
3300
|
}
|
|
3090
|
-
function
|
|
3091
|
-
const
|
|
3092
|
-
|
|
3093
|
-
const parsed = Number(text2);
|
|
3094
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
3301
|
+
function resolveProfile(env = process.env) {
|
|
3302
|
+
const raw = (env.OPEN_DESIGN_AMR_PROFILE ?? env.VELA_PROFILE ?? "").trim();
|
|
3303
|
+
return DESKTOP_PROFILES.includes(raw) ? raw : DEFAULT_PROFILE;
|
|
3095
3304
|
}
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
if (
|
|
3101
|
-
|
|
3102
|
-
return SLUG.test(slug) ? slug : null;
|
|
3305
|
+
function desktopConfigDir(env = process.env, home = osHomedir()) {
|
|
3306
|
+
const raw = (env.AMR_HOME ?? "").trim();
|
|
3307
|
+
if (!raw) return join(home, ".amr");
|
|
3308
|
+
if (raw === "~") return home;
|
|
3309
|
+
if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(home, raw.slice(2));
|
|
3310
|
+
return raw;
|
|
3103
3311
|
}
|
|
3104
|
-
function
|
|
3105
|
-
|
|
3106
|
-
if (!anchor) return body;
|
|
3107
|
-
const close = body.indexOf("</a>", anchor.index + anchor[0].length);
|
|
3108
|
-
if (close < 0) return body.slice(0, anchor.index);
|
|
3109
|
-
return body.slice(0, close + 4);
|
|
3312
|
+
function desktopConfigPath(env = process.env, home = osHomedir()) {
|
|
3313
|
+
return join(desktopConfigDir(env, home), "config.json");
|
|
3110
3314
|
}
|
|
3111
|
-
function
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
opens.push({ id, start: match.index, end: match.index + match[0].length });
|
|
3315
|
+
function parseDesktopConfigText(text2, profile = DEFAULT_PROFILE) {
|
|
3316
|
+
let parsed;
|
|
3317
|
+
try {
|
|
3318
|
+
parsed = JSON.parse(text2);
|
|
3319
|
+
} catch {
|
|
3320
|
+
return { state: "invalid" };
|
|
3118
3321
|
}
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3322
|
+
if (!record(parsed)) return { state: "invalid" };
|
|
3323
|
+
const profiles = parsed["profiles"];
|
|
3324
|
+
if (!record(profiles)) return { state: "invalid" };
|
|
3325
|
+
const entry = profiles[profile];
|
|
3326
|
+
if (entry === void 0) return { state: "incomplete", profile };
|
|
3327
|
+
if (!record(entry)) return { state: "invalid" };
|
|
3328
|
+
const controlKey = typeof entry["controlKey"] === "string" ? entry["controlKey"].trim() : "";
|
|
3329
|
+
const runtimeKey = typeof entry["runtimeKey"] === "string" ? entry["runtimeKey"].trim() : "";
|
|
3330
|
+
const rawApiUrl = typeof entry["apiUrl"] === "string" ? entry["apiUrl"].trim() : "";
|
|
3331
|
+
const user = record(entry["user"]) ? entry["user"] : void 0;
|
|
3332
|
+
const plan = typeof user?.["plan"] === "string" ? user["plan"].trim() : "";
|
|
3333
|
+
if (!controlKey) return { state: "incomplete", profile };
|
|
3334
|
+
try {
|
|
3335
|
+
safeSecret(controlKey);
|
|
3336
|
+
} catch {
|
|
3337
|
+
return { state: "invalid" };
|
|
3125
3338
|
}
|
|
3126
|
-
|
|
3339
|
+
const apiUrl = normalizeApiUrl(rawApiUrl);
|
|
3340
|
+
if (rawApiUrl && !apiUrl) return { state: "unsafe-api-url", profile };
|
|
3341
|
+
if (profile !== DEFAULT_PROFILE) return { state: "unsupported-profile", profile };
|
|
3342
|
+
const credential = {
|
|
3343
|
+
profile,
|
|
3344
|
+
controlKey,
|
|
3345
|
+
...apiUrl === void 0 ? {} : { apiUrl },
|
|
3346
|
+
...plan ? { plan } : {},
|
|
3347
|
+
signedIn: runtimeKey.length > 0
|
|
3348
|
+
};
|
|
3349
|
+
if (runtimeKey) Object.defineProperty(credential, "runtimeKey", { value: runtimeKey, enumerable: false });
|
|
3350
|
+
return { state: "credential", credential };
|
|
3127
3351
|
}
|
|
3128
|
-
function
|
|
3129
|
-
const
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3352
|
+
async function readDesktopCredential(deps = {}) {
|
|
3353
|
+
const env = deps.env ?? process.env;
|
|
3354
|
+
const profile = deps.profile ?? resolveProfile(env);
|
|
3355
|
+
const path = desktopConfigPath(env, deps.home ?? osHomedir());
|
|
3356
|
+
const readFile = deps.readFile ?? ((file) => fsReadFile(file, "utf8"));
|
|
3357
|
+
let text2;
|
|
3358
|
+
try {
|
|
3359
|
+
text2 = await readFile(path);
|
|
3360
|
+
} catch (error) {
|
|
3361
|
+
const code = record(error) && typeof error["code"] === "string" ? error["code"] : "";
|
|
3362
|
+
return code === "ENOENT" || code === "ENOTDIR" ? { state: "missing" } : { state: "unreadable" };
|
|
3136
3363
|
}
|
|
3137
|
-
return
|
|
3364
|
+
return parseDesktopConfigText(text2, profile);
|
|
3138
3365
|
}
|
|
3139
|
-
function
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
const chunk = body.slice(start, end);
|
|
3148
|
-
const label = stripTags(/<h4[^>]*>([\s\S]*?)<\/h4>/u.exec(chunk)?.[1] ?? "");
|
|
3149
|
-
const metrics = /* @__PURE__ */ new Map();
|
|
3150
|
-
for (const metric of chunk.matchAll(/<dt[^>]*>([\s\S]*?)<\/dt>\s*<dd([^>]*)>([\s\S]*?)<\/dd>/gu)) {
|
|
3151
|
-
const labelText = stripTags(metric[1] ?? "");
|
|
3152
|
-
const key = metricOf(labelText);
|
|
3153
|
-
if (!key) continue;
|
|
3154
|
-
const value = stripTags(metric[3] ?? "");
|
|
3155
|
-
metrics.set(key, { price: priceOf(value), currency: currencyOf(value), unit: unitOf(labelText) });
|
|
3156
|
-
}
|
|
3157
|
-
tiers.push({ label, metrics });
|
|
3366
|
+
function deviceGrant(value) {
|
|
3367
|
+
if (!record(value) || value.kind !== "device" || typeof value.controlKey !== "string" || typeof value.runtimeKey !== "string") return;
|
|
3368
|
+
try {
|
|
3369
|
+
const controlKey = safeSecret(value.controlKey), runtimeKey = safeSecret(value.runtimeKey);
|
|
3370
|
+
if ([controlKey, runtimeKey].some((key) => key.length > 8192 || /\s/u.test(key))) return;
|
|
3371
|
+
return { kind: "device", controlKey, runtimeKey, ...typeof value.savedAt === "string" ? { savedAt: value.savedAt } : {} };
|
|
3372
|
+
} catch {
|
|
3373
|
+
return void 0;
|
|
3158
3374
|
}
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3375
|
+
}
|
|
3376
|
+
function isOfficialRuntimeUrl(raw) {
|
|
3377
|
+
try {
|
|
3378
|
+
const url = new URL(raw);
|
|
3379
|
+
return url.origin === "https://amr-link.open-design.ai" && !url.username && !url.password && !url.search && !url.hash;
|
|
3380
|
+
} catch {
|
|
3381
|
+
return false;
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
3384
|
+
function cookieHeader(raw) {
|
|
3385
|
+
const value = raw.trim();
|
|
3386
|
+
if (!value || !value.includes("=")) return void 0;
|
|
3387
|
+
try {
|
|
3388
|
+
return safeSecret(value);
|
|
3389
|
+
} catch {
|
|
3390
|
+
return void 0;
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3393
|
+
function desktopSession(credential, apiUrl = credential.apiUrl ?? DEFAULT_API_URL) {
|
|
3394
|
+
const base = normalizeApiUrl(apiUrl) ?? DEFAULT_API_URL;
|
|
3395
|
+
return {
|
|
3396
|
+
headers: { authorization: `Bearer ${safeSecret(credential.controlKey)}` },
|
|
3397
|
+
source: "desktop",
|
|
3398
|
+
via: "desktop",
|
|
3399
|
+
apiUrl: base,
|
|
3400
|
+
profile: credential.profile,
|
|
3401
|
+
...credential.plan ? { plan: credential.plan } : {}
|
|
3402
|
+
};
|
|
3403
|
+
}
|
|
3404
|
+
function deviceSession(tokens) {
|
|
3405
|
+
const controlKey = typeof tokens === "string" ? tokens : tokens.controlKey;
|
|
3406
|
+
return { headers: { authorization: `Bearer ${safeSecret(controlKey)}` }, source: "login", via: "login", apiUrl: DEFAULT_API_URL, credentialType: "device" };
|
|
3407
|
+
}
|
|
3408
|
+
function cookieSession(cookie, source, apiUrl = DEFAULT_API_URL) {
|
|
3409
|
+
const header = cookieHeader(cookie);
|
|
3410
|
+
if (!header) return void 0;
|
|
3411
|
+
return {
|
|
3412
|
+
headers: { cookie: header },
|
|
3413
|
+
source,
|
|
3414
|
+
via: source === "environment" ? "environment" : "login",
|
|
3415
|
+
apiUrl: normalizeApiUrl(apiUrl) ?? DEFAULT_API_URL
|
|
3416
|
+
};
|
|
3417
|
+
}
|
|
3418
|
+
async function resolveSession(deps = {}) {
|
|
3419
|
+
const env = deps.env ?? process.env;
|
|
3420
|
+
const warnings = [];
|
|
3421
|
+
const now = deps.now ?? Date.now;
|
|
3422
|
+
if (deps.useDesktop !== false) {
|
|
3423
|
+
const desktop = await readDesktopCredential(deps);
|
|
3424
|
+
if (desktop.state === "credential") {
|
|
3425
|
+
const envApiUrl = (env.VELA_API_URL ?? "").trim();
|
|
3426
|
+
if (envApiUrl && !normalizeApiUrl(envApiUrl)) {
|
|
3427
|
+
warnings.push("unsafe-api-url");
|
|
3428
|
+
} else {
|
|
3429
|
+
return { state: "ready", session: desktopSession(desktop.credential, envApiUrl || DEFAULT_API_URL), warnings };
|
|
3430
|
+
}
|
|
3431
|
+
} else if (desktop.state === "unsafe-api-url") {
|
|
3432
|
+
warnings.push("unsafe-api-url");
|
|
3433
|
+
} else if (desktop.state === "unsupported-profile") {
|
|
3434
|
+
warnings.push("unsupported-profile");
|
|
3435
|
+
} else if (desktop.state === "incomplete") {
|
|
3436
|
+
warnings.push("desktop-incomplete");
|
|
3437
|
+
} else if (desktop.state === "unreadable" || desktop.state === "invalid") {
|
|
3438
|
+
warnings.push("desktop-unreadable");
|
|
3439
|
+
}
|
|
3440
|
+
}
|
|
3441
|
+
if (deps.readGrant) {
|
|
3442
|
+
let grant;
|
|
3443
|
+
try {
|
|
3444
|
+
grant = await deps.readGrant();
|
|
3445
|
+
} catch {
|
|
3446
|
+
grant = void 0;
|
|
3447
|
+
}
|
|
3448
|
+
if (grant && "kind" in grant && grant.kind === "device") {
|
|
3449
|
+
const device = deviceGrant(grant);
|
|
3450
|
+
if (device) return { state: "ready", session: deviceSession(device), warnings };
|
|
3451
|
+
} else if (grant && "cookie" in grant) {
|
|
3452
|
+
const expiry = typeof grant.expiresAt === "number" && Number.isFinite(grant.expiresAt) ? grant.expiresAt : 0;
|
|
3453
|
+
if (expiry === 0 || expiry > now()) {
|
|
3454
|
+
const session = cookieSession(grant.cookie, "login");
|
|
3455
|
+
if (session) return { state: "ready", session, warnings };
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
if (deps.resolveRef) {
|
|
3460
|
+
for (const ref of COOKIE_ENV_REFS) {
|
|
3461
|
+
let value;
|
|
3462
|
+
try {
|
|
3463
|
+
value = await deps.resolveRef(ref);
|
|
3464
|
+
} catch {
|
|
3465
|
+
value = void 0;
|
|
3466
|
+
}
|
|
3467
|
+
if (!value) continue;
|
|
3468
|
+
const session = cookieSession(value, "environment");
|
|
3469
|
+
if (session) return { state: "ready", session, warnings };
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
return { state: "need-login", reason: warnings[0] ?? "no-credential", warnings };
|
|
3473
|
+
}
|
|
3474
|
+
|
|
3475
|
+
// src/quota.ts
|
|
3476
|
+
import { attributionHeaders as attributionHeaders3 } from "@deepseek-ai/dsh-llm";
|
|
3477
|
+
var API_BASE = "https://amr-api.open-design.ai/api/v1";
|
|
3478
|
+
var CURRENT_URL = `${API_BASE}/workspaces/current`;
|
|
3479
|
+
var SUMMARY_URL = `${API_BASE}/billing/summary`;
|
|
3480
|
+
var usageUrl = (workspace) => `${API_BASE}/workspaces/${encodeURIComponent(workspace)}/billing/coding-plan-usage`;
|
|
3481
|
+
var preflightUrl = (workspace) => `${API_BASE}/workspaces/${encodeURIComponent(workspace)}/billing/preflight`;
|
|
3482
|
+
var ConsoleError = class extends Error {
|
|
3483
|
+
constructor(kind, status) {
|
|
3484
|
+
super(kind === "auth" ? "OpenDesign \u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55" : kind === "permission" ? "OpenDesign \u5F53\u524D\u767B\u5F55\u6001\u65E0\u6743\u8BFB\u53D6\u8BE5\u989D\u5EA6\u5C42" : kind === "rate-limit" ? "OpenDesign \u989D\u5EA6\u63A5\u53E3\u9650\u6D41\uFF0C\u8BF7\u7A0D\u540E\u5237\u65B0" : kind === "response" ? "OpenDesign \u989D\u5EA6\u63A5\u53E3\u8FD4\u56DE\u683C\u5F0F\u53D1\u751F\u53D8\u5316" : "OpenDesign \u989D\u5EA6\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6");
|
|
3485
|
+
this.kind = kind;
|
|
3486
|
+
this.status = status;
|
|
3487
|
+
}
|
|
3488
|
+
kind;
|
|
3489
|
+
status;
|
|
3490
|
+
};
|
|
3491
|
+
async function consoleJson(url, session, signal, fetcher = fetch) {
|
|
3492
|
+
signal?.throwIfAborted();
|
|
3493
|
+
if (session.credentialType === "device") {
|
|
3494
|
+
let target;
|
|
3495
|
+
try {
|
|
3496
|
+
target = new URL(url);
|
|
3497
|
+
} catch {
|
|
3498
|
+
throw new ConsoleError("response");
|
|
3499
|
+
}
|
|
3500
|
+
if (target.origin !== "https://amr-api.open-design.ai" || target.username || target.password) throw new ConsoleError("response");
|
|
3501
|
+
}
|
|
3502
|
+
const requestSignal = combinedSignal(signal, 2e4);
|
|
3503
|
+
let rejectAbort = () => void 0;
|
|
3504
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
3505
|
+
rejectAbort = reject;
|
|
3506
|
+
});
|
|
3507
|
+
const onAbort = () => rejectAbort(new ConsoleError("network"));
|
|
3508
|
+
requestSignal.addEventListener("abort", onAbort, { once: true });
|
|
3509
|
+
const read = async () => {
|
|
3510
|
+
const response = await fetcher(url, { headers: { ...attributionHeaders3(), accept: "application/json", ...session.headers }, signal: requestSignal, redirect: "error", credentials: "omit" });
|
|
3511
|
+
const cancelBody = () => {
|
|
3512
|
+
void response.body?.cancel().catch(() => void 0);
|
|
3513
|
+
};
|
|
3514
|
+
if (requestSignal.aborted) {
|
|
3515
|
+
cancelBody();
|
|
3516
|
+
throw new ConsoleError("network");
|
|
3517
|
+
}
|
|
3518
|
+
if (response.redirected || response.url && response.url !== url) {
|
|
3519
|
+
cancelBody();
|
|
3520
|
+
throw new ConsoleError("response");
|
|
3521
|
+
}
|
|
3522
|
+
if (response.status === 401 || response.status === 403) {
|
|
3523
|
+
cancelBody();
|
|
3524
|
+
throw new ConsoleError(response.status === 401 ? "auth" : "permission", response.status);
|
|
3525
|
+
}
|
|
3526
|
+
if (!response.ok) {
|
|
3527
|
+
cancelBody();
|
|
3528
|
+
throw new ConsoleError(response.status === 429 ? "rate-limit" : "network", response.status);
|
|
3529
|
+
}
|
|
3530
|
+
const declared = response.headers.get("content-length");
|
|
3531
|
+
if (declared !== null && (!/^\d+$/u.test(declared) || Number(declared) > 2 * 1024 * 1024)) {
|
|
3532
|
+
cancelBody();
|
|
3533
|
+
throw new ConsoleError("response");
|
|
3534
|
+
}
|
|
3535
|
+
const reader = response.body?.getReader();
|
|
3536
|
+
if (!reader) throw new ConsoleError("response");
|
|
3537
|
+
const cancelReader = () => {
|
|
3538
|
+
void reader.cancel().catch(() => void 0);
|
|
3539
|
+
};
|
|
3540
|
+
requestSignal.addEventListener("abort", cancelReader, { once: true });
|
|
3541
|
+
let size = 0, raw = "";
|
|
3542
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
3543
|
+
try {
|
|
3544
|
+
while (true) {
|
|
3545
|
+
const chunk = await reader.read();
|
|
3546
|
+
if (requestSignal.aborted) throw new ConsoleError("network");
|
|
3547
|
+
if (chunk.done) break;
|
|
3548
|
+
size += chunk.value.byteLength;
|
|
3549
|
+
if (size > 2 * 1024 * 1024) throw new ConsoleError("response");
|
|
3550
|
+
raw += decoder.decode(chunk.value, { stream: true });
|
|
3551
|
+
}
|
|
3552
|
+
raw += decoder.decode();
|
|
3553
|
+
} finally {
|
|
3554
|
+
requestSignal.removeEventListener("abort", cancelReader);
|
|
3555
|
+
cancelReader();
|
|
3556
|
+
reader.releaseLock();
|
|
3557
|
+
}
|
|
3558
|
+
let body;
|
|
3559
|
+
try {
|
|
3560
|
+
body = JSON.parse(raw);
|
|
3561
|
+
} catch {
|
|
3562
|
+
throw new ConsoleError("response");
|
|
3563
|
+
}
|
|
3564
|
+
if (record(body) && (body.code === 401 || body.code === "401")) throw new ConsoleError("auth", 401);
|
|
3565
|
+
if (record(body) && (body.code === 403 || body.code === "403")) throw new ConsoleError("permission", 403);
|
|
3566
|
+
return body;
|
|
3567
|
+
};
|
|
3568
|
+
try {
|
|
3569
|
+
return await Promise.race([read(), aborted]);
|
|
3570
|
+
} catch (error) {
|
|
3571
|
+
signal?.throwIfAborted();
|
|
3572
|
+
throw error instanceof ConsoleError ? error : new ConsoleError("network");
|
|
3573
|
+
} finally {
|
|
3574
|
+
requestSignal.removeEventListener("abort", onAbort);
|
|
3575
|
+
}
|
|
3576
|
+
}
|
|
3577
|
+
function number(value, negative = false) {
|
|
3578
|
+
const n = typeof value === "number" ? value : typeof value === "string" && /^-?\d+(\.\d+)?$/u.test(value.trim()) ? Number(value) : NaN;
|
|
3579
|
+
return Number.isFinite(n) && (negative || n >= 0) ? n : void 0;
|
|
3580
|
+
}
|
|
3581
|
+
function iso(value) {
|
|
3582
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : void 0;
|
|
3583
|
+
}
|
|
3584
|
+
function normalizeQuota(body, summary) {
|
|
3585
|
+
if (!record(body) || !(typeof body.eligible === "boolean" || typeof body.tier === "string" || body.tier === null || Array.isArray(body.windows))) throw new ConsoleError("response");
|
|
3586
|
+
const windows = [];
|
|
3587
|
+
for (const row of Array.isArray(body.windows) ? body.windows : []) {
|
|
3588
|
+
if (!record(row)) continue;
|
|
3589
|
+
const seconds = number(row.durationSeconds), used = number(row.usedCredits), limit = number(row.limitCredits), remaining = number(row.remainingCredits);
|
|
3590
|
+
if (seconds === void 0 || seconds <= 0 || used === void 0 || limit === void 0 || limit <= 0) continue;
|
|
3591
|
+
const resetsAt = iso(row.resetsAt), windowStart = iso(row.windowStart);
|
|
3592
|
+
const resetMode = typeof row.resetMode === "string" && row.resetMode.trim() ? row.resetMode.trim() : void 0;
|
|
3593
|
+
windows.push({ durationSeconds: seconds, used, limit, percent: Math.min(100, used / limit * 100), ...remaining === void 0 ? {} : { remaining }, ...resetsAt === void 0 ? {} : { resetsAt }, ...windowStart === void 0 ? {} : { windowStart }, ...resetMode === void 0 ? {} : { resetMode } });
|
|
3594
|
+
}
|
|
3595
|
+
const membershipTier = record(summary) && typeof summary.membershipTier === "string" ? summary.membershipTier.trim() : "";
|
|
3596
|
+
const tier = typeof body.tier === "string" ? body.tier.trim() : body.tier === void 0 && body.eligible !== false ? membershipTier : "";
|
|
3597
|
+
const eligible = typeof body.eligible === "boolean" ? body.eligible : body.tier === null ? false : void 0;
|
|
3598
|
+
return { windows, balances: normalizeBalances(summary), ...normalizeSubscription(summary), ...tier ? { tier } : {}, ...eligible === void 0 ? {} : { eligible } };
|
|
3599
|
+
}
|
|
3600
|
+
function normalizeSubscription(summary) {
|
|
3601
|
+
if (!record(summary)) return {};
|
|
3602
|
+
const start = iso(summary.subscriptionCurrentPeriodStart), end = iso(summary.subscriptionCurrentPeriodEnd);
|
|
3603
|
+
return { ...start === void 0 ? {} : { subscriptionPeriodStart: start }, ...end === void 0 ? {} : { subscriptionPeriodEnd: end } };
|
|
3604
|
+
}
|
|
3605
|
+
function normalizeBalances(summary) {
|
|
3606
|
+
if (!record(summary)) return {};
|
|
3607
|
+
const perUsd = number(summary.creditsPerUsd), balances = record(summary.balances) ? summary.balances : {};
|
|
3608
|
+
const subscription = number(balances.subscriptionCredits), recharge = number(balances.rechargeCredits), total = number(balances.totalAvailableCredits, true);
|
|
3609
|
+
const divisor = perUsd !== void 0 && perUsd > 0 ? perUsd : void 0;
|
|
3610
|
+
const totalUsd = number(summary.balanceUsd, true) ?? number(summary.totalAvailableCreditsUsd, true) ?? (divisor !== void 0 && total !== void 0 ? total / divisor : void 0);
|
|
3611
|
+
return { ...divisor !== void 0 && subscription !== void 0 ? { subscriptionUsd: subscription / divisor } : {}, ...divisor !== void 0 && recharge !== void 0 ? { rechargeUsd: recharge / divisor } : {}, ...totalUsd !== void 0 ? { totalUsd } : {} };
|
|
3612
|
+
}
|
|
3613
|
+
async function readDeviceQuota(session, signal, fetcher = fetch) {
|
|
3614
|
+
const common = { source: session.source, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3615
|
+
let current;
|
|
3616
|
+
try {
|
|
3617
|
+
current = await consoleJson(CURRENT_URL, session, signal, fetcher);
|
|
3618
|
+
} catch (error) {
|
|
3619
|
+
signal?.throwIfAborted();
|
|
3620
|
+
if (error instanceof ConsoleError && error.kind === "permission") return { ...common, state: "partial", windows: [], balances: {}, note: "\u5F53\u524D\u8BBE\u5907\u6388\u6743\u65E0\u6743\u8BFB\u53D6\u5DE5\u4F5C\u533A\uFF1B\u989D\u5EA6\u6682\u4E0D\u53EF\u786E\u8BA4" };
|
|
3621
|
+
throw error;
|
|
3622
|
+
}
|
|
3623
|
+
if (!record(current)) throw new ConsoleError("response");
|
|
3624
|
+
const workspaceId = typeof current.activeWorkspaceId === "string" && current.activeWorkspaceId.trim() ? current.activeWorkspaceId : current.workspaceId;
|
|
3625
|
+
if (typeof workspaceId !== "string" || !/^[A-Za-z0-9_-]{1,64}$/u.test(workspaceId)) throw new ConsoleError("response");
|
|
3626
|
+
const personal = current.workspaceType === "personal";
|
|
3627
|
+
const [preflight, billing] = await Promise.allSettled([
|
|
3628
|
+
consoleJson(preflightUrl(workspaceId), session, signal, fetcher),
|
|
3629
|
+
personal ? consoleJson(SUMMARY_URL, session, signal, fetcher) : Promise.resolve(void 0)
|
|
3630
|
+
]);
|
|
3631
|
+
signal?.throwIfAborted();
|
|
3632
|
+
for (const item of [preflight, billing]) if (item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "auth") throw item.reason;
|
|
3633
|
+
const summary = billing.status === "fulfilled" ? billing.value : void 0;
|
|
3634
|
+
const flight = preflight.status === "fulfilled" && record(preflight.value) ? preflight.value : void 0;
|
|
3635
|
+
let normalized;
|
|
3636
|
+
try {
|
|
3637
|
+
normalized = normalizeQuota(flight?.codingPlan, personal ? summary : void 0);
|
|
3638
|
+
} catch (error) {
|
|
3639
|
+
if (!(error instanceof ConsoleError)) throw error;
|
|
3640
|
+
}
|
|
3641
|
+
const balances = personal ? normalizeBalances(summary) : {};
|
|
3642
|
+
const total = personal ? number(flight?.balanceUsd, true) : void 0;
|
|
3643
|
+
if (total !== void 0) balances.totalUsd = total;
|
|
3644
|
+
const permission = [preflight, billing].some((item) => item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "permission");
|
|
3645
|
+
if (!normalized && !Object.keys(balances).length && !permission) {
|
|
3646
|
+
if (preflight.status === "rejected") throw preflight.reason;
|
|
3647
|
+
throw new ConsoleError("response");
|
|
3648
|
+
}
|
|
3649
|
+
const windows = normalized?.windows ?? [];
|
|
3650
|
+
const missingWindows = normalized?.eligible !== false && !windows.length;
|
|
3651
|
+
const missingBalances = personal && Object.keys(balances).length < 3;
|
|
3652
|
+
const partial = missingWindows || missingBalances || !personal || permission;
|
|
3653
|
+
const note = !personal ? "\u56E2\u961F\u6216\u672A\u77E5\u5DE5\u4F5C\u533A\uFF1A\u8D26\u53F7\u94B1\u5305\u53E3\u5F84\u672A\u6838\u5B9E\uFF0C\u6682\u4E0D\u663E\u793A" : missingWindows ? "\u5957\u9910\u989D\u5EA6\u7A97\u53E3\u6682\u4E0D\u53EF\u786E\u8BA4" : missingBalances ? "\u90E8\u5206\u94B1\u5305\u4F59\u989D\u6682\u4E0D\u53EF\u786E\u8BA4" : permission ? "\u90E8\u5206\u989D\u5EA6\u5C42\u65E0\u6743\u8BFB\u53D6" : normalized?.eligible === false ? "\u8BE5\u8D26\u53F7\u6CA1\u6709 Design Plan \u8BA2\u9605\uFF1B\u94B1\u5305\u4F59\u989D\u7167\u5E38\u663E\u793A" : void 0;
|
|
3654
|
+
return { ...common, ...normalized, ...normalizeSubscription(personal ? summary : void 0), windows, balances, state: partial ? "partial" : "ok", ...note ? { note } : {} };
|
|
3655
|
+
}
|
|
3656
|
+
async function readQuota(session, signal, fetcher = fetch) {
|
|
3657
|
+
if (session.credentialType === "device") return readDeviceQuota(session, signal, fetcher);
|
|
3658
|
+
const current = await consoleJson(CURRENT_URL, session, signal, fetcher);
|
|
3659
|
+
if (!record(current) || typeof current.workspaceId !== "string" || !/^[A-Za-z0-9_-]{1,64}$/u.test(current.workspaceId)) throw new ConsoleError("response");
|
|
3660
|
+
const personal = current.workspaceType === "personal";
|
|
3661
|
+
const [usage, billing] = await Promise.allSettled([
|
|
3662
|
+
consoleJson(usageUrl(current.workspaceId), session, signal, fetcher),
|
|
3663
|
+
personal ? consoleJson(SUMMARY_URL, session, signal, fetcher) : Promise.resolve(void 0)
|
|
3664
|
+
]);
|
|
3665
|
+
for (const item of [usage, billing]) if (item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "auth") throw item.reason;
|
|
3666
|
+
const summary = billing.status === "fulfilled" ? billing.value : void 0;
|
|
3667
|
+
const common = { source: session.source, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3668
|
+
let normalized;
|
|
3669
|
+
try {
|
|
3670
|
+
if (usage.status === "rejected") throw usage.reason;
|
|
3671
|
+
normalized = normalizeQuota(usage.value, summary);
|
|
3672
|
+
} catch (error) {
|
|
3673
|
+
const balances = normalizeBalances(summary);
|
|
3674
|
+
if (!Object.keys(balances).length) throw error;
|
|
3675
|
+
return { ...common, state: "partial", windows: [], balances, ...normalizeSubscription(summary), note: "\u94B1\u5305\u5DF2\u8BFB\u53D6\uFF1B\u5957\u9910\u8D60\u9001\u989D\u5EA6\u6682\u4E0D\u53EF\u786E\u8BA4" };
|
|
3676
|
+
}
|
|
3677
|
+
const missingWindows = normalized.eligible !== false && !normalized.windows.length;
|
|
3678
|
+
const noSubscription = normalized.eligible === false && !normalized.windows.length;
|
|
3679
|
+
const missingBalances = personal && Object.keys(normalized.balances).length < 3;
|
|
3680
|
+
const partial = missingWindows || missingBalances || !personal;
|
|
3681
|
+
const note = !personal ? "\u56E2\u961F\u6216\u672A\u77E5\u5DE5\u4F5C\u533A\uFF1A\u8D26\u53F7\u94B1\u5305\u53E3\u5F84\u672A\u6838\u5B9E\uFF0C\u6682\u4E0D\u663E\u793A" : missingWindows ? "\u5957\u9910\u989D\u5EA6\u7A97\u53E3\u6682\u4E0D\u53EF\u786E\u8BA4" : noSubscription ? "\u8BE5\u8D26\u53F7\u6CA1\u6709 Design Plan \u8BA2\u9605\uFF1B\u94B1\u5305\u4F59\u989D\u7167\u5E38\u663E\u793A" : missingBalances ? "\u90E8\u5206\u94B1\u5305\u4F59\u989D\u6682\u4E0D\u53EF\u786E\u8BA4" : void 0;
|
|
3682
|
+
return { ...common, ...normalized, state: partial ? "partial" : "ok", ...note === void 0 ? {} : { note } };
|
|
3683
|
+
}
|
|
3684
|
+
|
|
3685
|
+
// src/model-entitlements.ts
|
|
3686
|
+
var ID = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
3687
|
+
var ENTITLEMENT_TIMEOUT_MS = 6e4;
|
|
3688
|
+
async function resolveModelAccount(key, baseURL, grant, useDesktop) {
|
|
3689
|
+
if (!isOfficialRuntimeUrl(baseURL)) return;
|
|
3690
|
+
if (grant && "kind" in grant && grant.kind === "device" && grant.runtimeKey === key) {
|
|
3691
|
+
return { session: deviceSession(grant), source: "device" };
|
|
3692
|
+
}
|
|
3693
|
+
if (!useDesktop) return;
|
|
3694
|
+
const desktop = await readDesktopCredential();
|
|
3695
|
+
if (desktop.state === "credential" && desktop.credential.runtimeKey === key) {
|
|
3696
|
+
return { session: desktopSession(desktop.credential), source: "desktop" };
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
async function readModelScope(account, signal, fetcher = fetch) {
|
|
3700
|
+
const body = await consoleJson(CURRENT_URL, account.session, signal, fetcher);
|
|
3701
|
+
if (!record(body)) throw new Error("\u6A21\u578B\u6743\u76CA\u5DE5\u4F5C\u533A\u4E0D\u53EF\u786E\u8BA4");
|
|
3702
|
+
const workspaceId = body.activeWorkspaceId ?? body.workspaceId;
|
|
3703
|
+
if (typeof workspaceId !== "string" || !ID.test(workspaceId) || typeof body.workspaceMemberId !== "string" || !ID.test(body.workspaceMemberId) || body.workspaceId !== void 0 && body.workspaceId !== workspaceId || body.memberStatus !== void 0 && body.memberStatus !== "active") throw new Error("\u6A21\u578B\u6743\u76CA\u5DE5\u4F5C\u533A\u4E0D\u53EF\u786E\u8BA4");
|
|
3704
|
+
return { workspaceId, memberId: body.workspaceMemberId, source: account.source };
|
|
3705
|
+
}
|
|
3706
|
+
function parseModelCoverage(value, scope, modelId) {
|
|
3707
|
+
if (!record(value) || value.schemaVersion !== 1 || value.workspaceId !== scope.workspaceId || value.workspaceMemberId !== scope.memberId || value.modelId !== modelId || typeof value.generatedAt !== "string" || !Number.isFinite(Date.parse(value.generatedAt)) || !record(value.codingPlan) || value.codingPlan.workspaceId !== scope.workspaceId || typeof value.codingPlan.eligible !== "boolean" || typeof value.modelCovered !== "boolean" || !["coding_plan", "wallet", "gateway"].includes(String(value.funding))) return;
|
|
3708
|
+
const tier = typeof value.codingPlan.tier === "string" && ["go", "plus", "pro", "max"].includes(value.codingPlan.tier) ? value.codingPlan.tier : void 0;
|
|
3709
|
+
const included = value.codingPlan.eligible && value.modelCovered;
|
|
3710
|
+
if (value.funding === "coding_plan" && !included) return;
|
|
3711
|
+
return { coverage: included ? "included" : "not-included", ...tier === void 0 ? {} : { tier } };
|
|
3712
|
+
}
|
|
3713
|
+
function unverifiedModels(models) {
|
|
3714
|
+
return models.map((model) => ({ ...model, group: "paid", coverage: "unknown" }));
|
|
3715
|
+
}
|
|
3716
|
+
async function readModelEntitlements(models, options = {}) {
|
|
3717
|
+
const rows = unverifiedModels(models).map((model) => ({ ...model }));
|
|
3718
|
+
if (!options.account || !options.scope) return { models: rows, summary: { state: "unavailable" } };
|
|
3719
|
+
const { account, scope } = options;
|
|
3720
|
+
const deadline = combinedSignal(options.signal, ENTITLEMENT_TIMEOUT_MS);
|
|
3721
|
+
let next = 0, verified = 0;
|
|
3722
|
+
const tiers = /* @__PURE__ */ new Set();
|
|
3723
|
+
await Promise.all(Array.from({ length: Math.min(3, rows.length) }, async () => {
|
|
3724
|
+
while (next < rows.length && !deadline.aborted) {
|
|
3725
|
+
const index = next++, row = rows[index];
|
|
3726
|
+
try {
|
|
3727
|
+
const value = await consoleJson(`${preflightUrl(scope.workspaceId)}?modelId=${encodeURIComponent(row.id)}`, account.session, deadline, options.fetcher ?? fetch);
|
|
3728
|
+
const evidence = parseModelCoverage(value, scope, row.id);
|
|
3729
|
+
if (!evidence) continue;
|
|
3730
|
+
rows[index] = { ...row, group: evidence.coverage === "included" ? "plan" : "paid", coverage: evidence.coverage };
|
|
3731
|
+
if (evidence.tier) tiers.add(evidence.tier);
|
|
3732
|
+
verified++;
|
|
3733
|
+
} catch {
|
|
3734
|
+
if (options.signal?.aborted) options.signal.throwIfAborted();
|
|
3735
|
+
}
|
|
3736
|
+
}
|
|
3737
|
+
}));
|
|
3738
|
+
options.signal?.throwIfAborted();
|
|
3739
|
+
if (tiers.size > 1) return { models: unverifiedModels(models), summary: { state: "unavailable", source: account.source }, scope };
|
|
3740
|
+
return { models: rows, scope, summary: {
|
|
3741
|
+
state: verified === rows.length && verified > 0 ? "verified" : verified > 0 ? "partial" : "unavailable",
|
|
3742
|
+
source: account.source,
|
|
3743
|
+
...tiers.size === 1 ? { tier: [...tiers][0] } : {},
|
|
3744
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3745
|
+
} };
|
|
3746
|
+
}
|
|
3747
|
+
|
|
3748
|
+
// src/model-directory.ts
|
|
3749
|
+
var MODEL_DIRECTORY_REFRESH_MS = 10 * 6e4;
|
|
3750
|
+
var ModelDirectory = class {
|
|
3751
|
+
constructor(options) {
|
|
3752
|
+
this.options = options;
|
|
3753
|
+
this._models = this.seed();
|
|
3754
|
+
}
|
|
3755
|
+
options;
|
|
3756
|
+
lifetime = new AbortController();
|
|
3757
|
+
controller;
|
|
3758
|
+
pending;
|
|
3759
|
+
epoch = 0;
|
|
3760
|
+
lastAttempt = 0;
|
|
3761
|
+
write = Promise.resolve();
|
|
3762
|
+
writeSerial = 0;
|
|
3763
|
+
_models;
|
|
3764
|
+
_updatedAt;
|
|
3765
|
+
_error;
|
|
3766
|
+
_entitlements = { state: "unavailable" };
|
|
3767
|
+
_scope;
|
|
3768
|
+
_runtimeKey;
|
|
3769
|
+
_callBlocked = false;
|
|
3770
|
+
seed() {
|
|
3771
|
+
const config = this.options.config();
|
|
3772
|
+
const rows = MODELS;
|
|
3773
|
+
return unverifiedModels(rows.map((row) => {
|
|
3774
|
+
const known = findModel(row.id);
|
|
3775
|
+
if (!known) return row;
|
|
3776
|
+
return { ...known, ...row.contextWindow === void 0 ? {} : { contextWindow: known.contextWindow === void 0 ? row.contextWindow : Math.min(known.contextWindow, row.contextWindow) } };
|
|
3777
|
+
}));
|
|
3778
|
+
}
|
|
3779
|
+
models() {
|
|
3780
|
+
return this._models;
|
|
3781
|
+
}
|
|
3782
|
+
updatedAt() {
|
|
3783
|
+
return this._updatedAt;
|
|
3784
|
+
}
|
|
3785
|
+
error() {
|
|
3786
|
+
return this._error;
|
|
3787
|
+
}
|
|
3788
|
+
entitlements() {
|
|
3789
|
+
return this._entitlements;
|
|
3790
|
+
}
|
|
3791
|
+
workspace() {
|
|
3792
|
+
return this._scope?.workspaceId;
|
|
3793
|
+
}
|
|
3794
|
+
callIdentity() {
|
|
3795
|
+
if (this._callBlocked) throw new Error("\u5F53\u524D\u5DE5\u4F5C\u533A\u8EAB\u4EFD\u5DF2\u53D8\u5316\u6216\u4E0D\u53EF\u786E\u8BA4\uFF0C\u8BF7\u5148\u5237\u65B0\u6A21\u578B\u76EE\u5F55");
|
|
3796
|
+
return this._runtimeKey ? { key: this._runtimeKey, ...this._scope ? { workspace: this._scope.workspaceId } : {} } : void 0;
|
|
3797
|
+
}
|
|
3798
|
+
dispose() {
|
|
3799
|
+
this.lifetime.abort();
|
|
3800
|
+
this.controller?.abort();
|
|
3801
|
+
this._runtimeKey = void 0;
|
|
3802
|
+
}
|
|
3803
|
+
invalidate() {
|
|
3804
|
+
const changed = this._updatedAt !== void 0 || this._scope !== void 0;
|
|
3805
|
+
this.epoch++;
|
|
3806
|
+
this.controller?.abort();
|
|
3807
|
+
this.pending = void 0;
|
|
3808
|
+
this.lastAttempt = 0;
|
|
3809
|
+
this._models = this.seed();
|
|
3810
|
+
this._updatedAt = void 0;
|
|
3811
|
+
this._error = void 0;
|
|
3812
|
+
this._entitlements = { state: "unavailable" };
|
|
3813
|
+
this._scope = void 0;
|
|
3814
|
+
this._runtimeKey = void 0;
|
|
3815
|
+
this._callBlocked = false;
|
|
3816
|
+
if (changed) try {
|
|
3817
|
+
this.options.changed();
|
|
3818
|
+
} catch {
|
|
3819
|
+
}
|
|
3820
|
+
}
|
|
3821
|
+
/** Status/list reads start at most one background refresh per ten minutes. */
|
|
3822
|
+
warm() {
|
|
3823
|
+
if (this.pending || Date.now() - this.lastAttempt < MODEL_DIRECTORY_REFRESH_MS || this.lifetime.signal.aborted) return;
|
|
3824
|
+
void this.refresh().catch(() => void 0);
|
|
3825
|
+
}
|
|
3826
|
+
async refresh() {
|
|
3827
|
+
if (this.pending) return this.pending;
|
|
3828
|
+
const epoch = this.epoch;
|
|
3829
|
+
const controller = new AbortController();
|
|
3830
|
+
this.controller = controller;
|
|
3831
|
+
const signal = combinedSignal(AbortSignal.any([controller.signal, this.lifetime.signal]), 9e4);
|
|
3832
|
+
this.lastAttempt = Date.now();
|
|
3833
|
+
const run = this.read(epoch, signal);
|
|
3834
|
+
this.pending = run;
|
|
3835
|
+
try {
|
|
3836
|
+
await run;
|
|
3837
|
+
} finally {
|
|
3838
|
+
if (this.pending === run) this.pending = void 0;
|
|
3839
|
+
}
|
|
3840
|
+
}
|
|
3841
|
+
async binding(key, scope, signal) {
|
|
3842
|
+
const secret2 = await this.options.bindingSecret(signal);
|
|
3843
|
+
try {
|
|
3844
|
+
return createHmac2("sha256", secret2).update(JSON.stringify(["opendesign-model-directory-v2", this.options.config().baseURL, key, scope?.workspaceId ?? "", scope?.memberId ?? ""])).digest("hex");
|
|
3845
|
+
} finally {
|
|
3846
|
+
secret2.fill(0);
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3849
|
+
async read(epoch, signal) {
|
|
3850
|
+
try {
|
|
3851
|
+
const state = await this.options.state();
|
|
3852
|
+
const key = state.key;
|
|
3853
|
+
if (!key?.trim()) {
|
|
3854
|
+
this._error = "\u8BF7\u5148\u767B\u5F55\u6216\u914D\u7F6E API Key\uFF0C\u518D\u4ECE\u5F53\u524D\u7F51\u5173\u8BFB\u53D6\u6A21\u578B\u76EE\u5F55\u3002";
|
|
3855
|
+
return;
|
|
3856
|
+
}
|
|
3857
|
+
const config = this.options.config();
|
|
3858
|
+
let scope;
|
|
3859
|
+
if (state.account) {
|
|
3860
|
+
try {
|
|
3861
|
+
scope = await (this.options.readScope ?? readModelScope)(state.account, signal);
|
|
3862
|
+
} catch {
|
|
3863
|
+
this.dropCoverage(true);
|
|
3864
|
+
signal.throwIfAborted();
|
|
3865
|
+
}
|
|
3866
|
+
}
|
|
3867
|
+
if (this._scope && (!scope || scope.workspaceId !== this._scope.workspaceId || scope.memberId !== this._scope.memberId)) this.dropCoverage(true);
|
|
3868
|
+
const binding = await this.binding(key, scope, signal);
|
|
3869
|
+
const snapshot = config.modelCatalog;
|
|
3870
|
+
if (this._updatedAt === void 0 && snapshot?.baseURL === config.baseURL && snapshot.binding === binding) {
|
|
3871
|
+
this._models = unverifiedModels(snapshot.models.map((row) => {
|
|
3872
|
+
const known = findModel(row.id);
|
|
3873
|
+
return known ? { ...known, ...row.contextWindow === void 0 ? {} : { contextWindow: known.contextWindow === void 0 ? row.contextWindow : Math.min(known.contextWindow, row.contextWindow) } } : row;
|
|
3874
|
+
}));
|
|
3875
|
+
this._updatedAt = snapshot.updatedAt;
|
|
3876
|
+
this._runtimeKey = key;
|
|
3877
|
+
this._scope = scope;
|
|
3878
|
+
try {
|
|
3879
|
+
this.options.changed();
|
|
3880
|
+
} catch {
|
|
3881
|
+
this._models = this.seed();
|
|
3882
|
+
this._updatedAt = void 0;
|
|
3883
|
+
}
|
|
3884
|
+
}
|
|
3885
|
+
const models = await (this.options.fetchModels ?? fetchModelCatalog)(config.baseURL, key, signal, void 0, scope?.workspaceId);
|
|
3886
|
+
if (models.length === 0) throw new ModelDiscoveryError("response");
|
|
3887
|
+
const result = await (this.options.readEntitlements ?? readModelEntitlements)(models, { ...state.account ? { account: state.account } : {}, ...scope ? { scope } : {}, signal });
|
|
3888
|
+
if (scope && state.account) {
|
|
3889
|
+
let after;
|
|
3890
|
+
try {
|
|
3891
|
+
after = await (this.options.readScope ?? readModelScope)(state.account, signal);
|
|
3892
|
+
} catch {
|
|
3893
|
+
this.dropCoverage(true);
|
|
3894
|
+
throw new ModelDiscoveryError("response");
|
|
3895
|
+
}
|
|
3896
|
+
if (after.workspaceId !== scope.workspaceId || after.memberId !== scope.memberId) {
|
|
3897
|
+
this.dropCoverage(true);
|
|
3898
|
+
throw new ModelDiscoveryError("response");
|
|
3899
|
+
}
|
|
3900
|
+
}
|
|
3901
|
+
const latest = await this.options.state();
|
|
3902
|
+
if (signal.aborted || epoch !== this.epoch || latest.key !== key || this.options.config().baseURL !== config.baseURL) return;
|
|
3903
|
+
const previous = { models: this._models, updatedAt: this._updatedAt, entitlements: this._entitlements, scope: this._scope, key: this._runtimeKey, blocked: this._callBlocked };
|
|
3904
|
+
this._models = result.models;
|
|
3905
|
+
this._updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3906
|
+
this._entitlements = result.summary;
|
|
3907
|
+
this._scope = scope;
|
|
3908
|
+
this._runtimeKey = key;
|
|
3909
|
+
this._error = void 0;
|
|
3910
|
+
this._callBlocked = state.account !== void 0 && scope === void 0;
|
|
3911
|
+
try {
|
|
3912
|
+
this.options.changed();
|
|
3913
|
+
} catch {
|
|
3914
|
+
this._models = previous.models;
|
|
3915
|
+
this._updatedAt = previous.updatedAt;
|
|
3916
|
+
this._entitlements = previous.entitlements;
|
|
3917
|
+
this._scope = previous.scope;
|
|
3918
|
+
this._runtimeKey = previous.key;
|
|
3919
|
+
this._callBlocked = previous.blocked;
|
|
3920
|
+
this._error = "\u6A21\u578B\u76EE\u5F55\u5DF2\u8BFB\u53D6\uFF0C\u4F46\u6A21\u578B\u9009\u62E9\u5668\u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002";
|
|
3921
|
+
return;
|
|
3922
|
+
}
|
|
3923
|
+
if (snapshot?.binding !== binding || JSON.stringify(snapshot.models) !== JSON.stringify(this._models)) {
|
|
3924
|
+
this.queueWrite({ baseURL: config.baseURL, updatedAt: this._updatedAt, models: this._models, binding }, epoch);
|
|
3925
|
+
}
|
|
3926
|
+
} catch (error) {
|
|
3927
|
+
if (!signal.aborted && epoch === this.epoch) this._error = error instanceof ModelDiscoveryError ? error.message : "\u6A21\u578B\u76EE\u5F55\u6216\u8D26\u53F7\u6743\u76CA\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u7A0D\u540E\u5237\u65B0\u3002";
|
|
3928
|
+
}
|
|
3929
|
+
}
|
|
3930
|
+
dropCoverage(blockCalls) {
|
|
3931
|
+
this._models = unverifiedModels(this._models);
|
|
3932
|
+
this._entitlements = { state: "unavailable" };
|
|
3933
|
+
this._scope = void 0;
|
|
3934
|
+
this._runtimeKey = void 0;
|
|
3935
|
+
this._callBlocked = blockCalls;
|
|
3936
|
+
try {
|
|
3937
|
+
this.options.changed();
|
|
3938
|
+
} catch {
|
|
3939
|
+
}
|
|
3940
|
+
}
|
|
3941
|
+
queueWrite(snapshot, epoch) {
|
|
3942
|
+
const serial = ++this.writeSerial;
|
|
3943
|
+
this.write = this.write.then(async () => {
|
|
3944
|
+
if (this.lifetime.signal.aborted || epoch !== this.epoch) return;
|
|
3945
|
+
const result = await this.options.persist(snapshot);
|
|
3946
|
+
if (serial !== this.writeSerial || epoch !== this.epoch) return;
|
|
3947
|
+
if (result === "unavailable") this._error = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u5F53\u524D\u914D\u7F6E\u670D\u52A1\u4E0D\u53EF\u5199\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
|
|
3948
|
+
else if (result === "failed") this._error = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u4FDD\u5B58\u5931\u8D25\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
|
|
3949
|
+
}).catch(() => {
|
|
3950
|
+
if (epoch === this.epoch) this._error = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u4FDD\u5B58\u5931\u8D25\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
|
|
3951
|
+
});
|
|
3952
|
+
}
|
|
3953
|
+
};
|
|
3954
|
+
|
|
3955
|
+
// src/pricing.ts
|
|
3956
|
+
var PRICING_ORIGIN = "https://corouter.open-design.ai";
|
|
3957
|
+
var PRICING_CATALOG_PATH = "/zh/models/";
|
|
3958
|
+
var PRICING_TIMEOUT_MS = 15e3;
|
|
3959
|
+
var MAX_PRICING_BODY_BYTES = 4 * 1024 * 1024;
|
|
3960
|
+
var MESSAGES3 = {
|
|
3961
|
+
timeout: "\u5B98\u7F51\u4EF7\u683C\u8BF7\u6C42\u8D85\u8FC7\u65F6\u9650",
|
|
3962
|
+
aborted: "\u5B98\u7F51\u4EF7\u683C\u8BF7\u6C42\u5DF2\u53D6\u6D88",
|
|
3963
|
+
network: "\u65E0\u6CD5\u8FDE\u63A5\u5B98\u7F51",
|
|
3964
|
+
status: "\u5B98\u7F51\u8FD4\u56DE\u4E86\u975E 200 \u72B6\u6001",
|
|
3965
|
+
"too-large": "\u5B98\u7F51\u4EF7\u683C\u54CD\u5E94\u4F53\u8D85\u8FC7\u4E0A\u9650",
|
|
3966
|
+
"invalid-page": "\u62FF\u5230\u7684\u9875\u9762\u4E0D\u662F\u5B98\u7F51\u6A21\u578B\u4EF7\u683C\u9875",
|
|
3967
|
+
"invalid-model": "\u62FF\u5230\u7684\u9875\u9762\u4E0D\u662F\u5B98\u7F51\u6A21\u578B\u4EF7\u683C\u8BE6\u60C5\u9875"
|
|
3968
|
+
};
|
|
3969
|
+
var PricingError = class extends Error {
|
|
3970
|
+
constructor(kind, status) {
|
|
3971
|
+
super(MESSAGES3[kind]);
|
|
3972
|
+
this.kind = kind;
|
|
3973
|
+
this.status = status;
|
|
3974
|
+
this.name = "PricingError";
|
|
3975
|
+
}
|
|
3976
|
+
kind;
|
|
3977
|
+
status;
|
|
3978
|
+
};
|
|
3979
|
+
var ENTITIES = {
|
|
3980
|
+
""": '"',
|
|
3981
|
+
"&": "&",
|
|
3982
|
+
"<": "<",
|
|
3983
|
+
">": ">",
|
|
3984
|
+
"'": "'",
|
|
3985
|
+
" ": " ",
|
|
3986
|
+
"—": "\u2014",
|
|
3987
|
+
"–": "\u2013"
|
|
3988
|
+
};
|
|
3989
|
+
function decodeEntities(text2) {
|
|
3990
|
+
return text2.replace(/&(?:quot|amp|lt|gt|apos|nbsp|mdash|ndash);/gu, (match) => ENTITIES[match] ?? match).replace(/&#(\d+);/gu, (_match, code) => {
|
|
3991
|
+
const point = Number(code);
|
|
3992
|
+
return Number.isInteger(point) && point > 0 && point <= 1114111 ? String.fromCodePoint(point) : "";
|
|
3993
|
+
});
|
|
3994
|
+
}
|
|
3995
|
+
function stripTags(text2) {
|
|
3996
|
+
return decodeEntities(text2.replace(/<[^>]*>/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
3997
|
+
}
|
|
3998
|
+
function metricOf(label) {
|
|
3999
|
+
if (/缓存读取|cache\s+read/iu.test(label)) return "cacheRead";
|
|
4000
|
+
if (/缓存写入|cache\s+write/iu.test(label)) return "cacheWrite";
|
|
4001
|
+
if (/^\s*(?:输入|input)/iu.test(label)) return "input";
|
|
4002
|
+
if (/^\s*(?:输出|output)/iu.test(label)) return "output";
|
|
4003
|
+
return void 0;
|
|
4004
|
+
}
|
|
4005
|
+
function unitOf(label) {
|
|
4006
|
+
if (/百万\s*token|1m\s*tokens?/iu.test(label)) return "per_1m_tokens";
|
|
4007
|
+
if (/千\s*token|1k\s*tokens?/iu.test(label)) return "per_1k_tokens";
|
|
4008
|
+
return null;
|
|
4009
|
+
}
|
|
4010
|
+
function currencyOf(value) {
|
|
4011
|
+
if (value.includes("$")) return "USD";
|
|
4012
|
+
return null;
|
|
4013
|
+
}
|
|
4014
|
+
function priceOf(value) {
|
|
4015
|
+
const text2 = value.replace(/[$\u20ac\u00a3\u00a5\u00a4,\s]/gu, "");
|
|
4016
|
+
if (text2 === "" || /^[–—−\-]+$/u.test(text2)) return null;
|
|
4017
|
+
const parsed = Number(text2);
|
|
4018
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
4019
|
+
}
|
|
4020
|
+
var MODEL_ID2 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
4021
|
+
var SLUG = /^[a-z0-9][a-z0-9-]{0,127}$/u;
|
|
4022
|
+
function slugOf(href) {
|
|
4023
|
+
const match = /\/models\/([A-Za-z0-9._-]+)\/?(?:#.*)?$/u.exec(href);
|
|
4024
|
+
if (!match) return null;
|
|
4025
|
+
const slug = match[1];
|
|
4026
|
+
return SLUG.test(slug) ? slug : null;
|
|
4027
|
+
}
|
|
4028
|
+
function trimPanelBody(body) {
|
|
4029
|
+
const anchor = /<a\b[^>]*class="[^"]*\bmodel-explorer-detail-link\b[^"]*"[^>]*>/u.exec(body);
|
|
4030
|
+
if (!anchor) return body;
|
|
4031
|
+
const close = body.indexOf("</a>", anchor.index + anchor[0].length);
|
|
4032
|
+
if (close < 0) return body.slice(0, anchor.index);
|
|
4033
|
+
return body.slice(0, close + 4);
|
|
4034
|
+
}
|
|
4035
|
+
function collectPanels(html) {
|
|
4036
|
+
const openTag = /<div\b[^>]*class="[^"]*\bmodel-explorer-panel\b[^"]*"[^>]*>/gu;
|
|
4037
|
+
const opens = [];
|
|
4038
|
+
for (const match of html.matchAll(openTag)) {
|
|
4039
|
+
const id = /data-model-panel="([^"]*)"/u.exec(match[0])?.[1];
|
|
4040
|
+
if (!id || !MODEL_ID2.test(id)) continue;
|
|
4041
|
+
opens.push({ id, start: match.index, end: match.index + match[0].length });
|
|
4042
|
+
}
|
|
4043
|
+
const panels = [];
|
|
4044
|
+
for (let index = 0; index < opens.length; index += 1) {
|
|
4045
|
+
const open = opens[index];
|
|
4046
|
+
const next = opens[index + 1];
|
|
4047
|
+
const body = html.slice(open.end, next ? next.start : html.length);
|
|
4048
|
+
panels.push({ id: open.id, body: trimPanelBody(body) });
|
|
4049
|
+
}
|
|
4050
|
+
return panels;
|
|
4051
|
+
}
|
|
4052
|
+
function collectProviders(html) {
|
|
4053
|
+
const providers = /* @__PURE__ */ new Map();
|
|
4054
|
+
for (const match of html.matchAll(/<button\b[^>]*>/gu)) {
|
|
4055
|
+
const tag = match[0];
|
|
4056
|
+
const id = /data-model-tab="([^"]*)"/u.exec(tag)?.[1];
|
|
4057
|
+
const provider = /data-provider="([^"]*)"/u.exec(tag)?.[1];
|
|
4058
|
+
if (!id || !provider) continue;
|
|
4059
|
+
providers.set(id, provider.trim());
|
|
4060
|
+
}
|
|
4061
|
+
return providers;
|
|
4062
|
+
}
|
|
4063
|
+
function collectTiers(body) {
|
|
4064
|
+
const marker = /<div\b[^>]*class="[^"]*\bmodel-explorer-tier\b[^"]*"[^>]*>/gu;
|
|
4065
|
+
const starts = [];
|
|
4066
|
+
for (const match of body.matchAll(marker)) starts.push(match.index);
|
|
4067
|
+
const tiers = [];
|
|
4068
|
+
for (let index = 0; index < starts.length; index += 1) {
|
|
4069
|
+
const start = starts[index];
|
|
4070
|
+
const end = index + 1 < starts.length ? starts[index + 1] : body.length;
|
|
4071
|
+
const chunk = body.slice(start, end);
|
|
4072
|
+
const label = stripTags(/<h4[^>]*>([\s\S]*?)<\/h4>/u.exec(chunk)?.[1] ?? "");
|
|
4073
|
+
const metrics = /* @__PURE__ */ new Map();
|
|
4074
|
+
for (const metric of chunk.matchAll(/<dt[^>]*>([\s\S]*?)<\/dt>\s*<dd([^>]*)>([\s\S]*?)<\/dd>/gu)) {
|
|
4075
|
+
const labelText = stripTags(metric[1] ?? "");
|
|
4076
|
+
const key = metricOf(labelText);
|
|
4077
|
+
if (!key) continue;
|
|
4078
|
+
const value = stripTags(metric[3] ?? "");
|
|
4079
|
+
metrics.set(key, { price: priceOf(value), currency: currencyOf(value), unit: unitOf(labelText) });
|
|
4080
|
+
}
|
|
4081
|
+
tiers.push({ label, metrics });
|
|
4082
|
+
}
|
|
4083
|
+
return tiers;
|
|
4084
|
+
}
|
|
4085
|
+
function hasCatalogMarker(html) {
|
|
4086
|
+
return /data-page-name="corouter_models"/u.test(html);
|
|
3163
4087
|
}
|
|
3164
4088
|
function commonCurrency(values) {
|
|
3165
4089
|
const seen = new Set(values.filter((value) => value !== null));
|
|
@@ -3322,214 +4246,10 @@ async function fetchPricingSnapshot(options = {}) {
|
|
|
3322
4246
|
const failure = deadline.aborted && !options.signal?.aborted ? new PricingError("timeout") : classify2(error, options.signal, deadline);
|
|
3323
4247
|
const issue = { code: failure.kind, message: failure.message, url: catalogUrl };
|
|
3324
4248
|
if (failure.status !== void 0) issue.status = failure.status;
|
|
3325
|
-
return { status: "failed", source, fetchedAt: now().toISOString(), currency: null, unit: null, models: [], issues: [issue] };
|
|
3326
|
-
} finally {
|
|
3327
|
-
deadline.removeEventListener("abort", onAbort);
|
|
3328
|
-
}
|
|
3329
|
-
}
|
|
3330
|
-
|
|
3331
|
-
// src/auth.ts
|
|
3332
|
-
import { readFile as fsReadFile } from "node:fs/promises";
|
|
3333
|
-
import { homedir as osHomedir } from "node:os";
|
|
3334
|
-
import { join } from "node:path";
|
|
3335
|
-
var DEFAULT_API_URL = "https://amr-api.open-design.ai";
|
|
3336
|
-
var API_HOST = "amr-api.open-design.ai";
|
|
3337
|
-
var DESKTOP_PROFILES = ["prod", "test", "feature-test", "local"];
|
|
3338
|
-
var DEFAULT_PROFILE = "prod";
|
|
3339
|
-
var COOKIE_ENV_REFS = ["OPEN_DESIGN_COOKIE", "OPEN_DESIGN_SESSION"];
|
|
3340
|
-
function isOfficialApiUrl(raw) {
|
|
3341
|
-
let url;
|
|
3342
|
-
try {
|
|
3343
|
-
url = new URL(raw);
|
|
3344
|
-
} catch {
|
|
3345
|
-
return false;
|
|
3346
|
-
}
|
|
3347
|
-
if (url.protocol !== "https:") return false;
|
|
3348
|
-
if (url.username || url.password) return false;
|
|
3349
|
-
if (url.search || url.hash) return false;
|
|
3350
|
-
if (url.pathname !== "/" && url.pathname !== "") return false;
|
|
3351
|
-
return url.hostname.toLowerCase() === API_HOST && !url.port;
|
|
3352
|
-
}
|
|
3353
|
-
function normalizeApiUrl(raw) {
|
|
3354
|
-
const value = typeof raw === "string" ? raw.trim() : "";
|
|
3355
|
-
if (!value) return void 0;
|
|
3356
|
-
if (!isOfficialApiUrl(value)) return void 0;
|
|
3357
|
-
const url = new URL(value);
|
|
3358
|
-
return `https://${url.hostname.toLowerCase()}`;
|
|
3359
|
-
}
|
|
3360
|
-
function resolveProfile(env = process.env) {
|
|
3361
|
-
const raw = (env.OPEN_DESIGN_AMR_PROFILE ?? env.VELA_PROFILE ?? "").trim();
|
|
3362
|
-
return DESKTOP_PROFILES.includes(raw) ? raw : DEFAULT_PROFILE;
|
|
3363
|
-
}
|
|
3364
|
-
function desktopConfigDir(env = process.env, home = osHomedir()) {
|
|
3365
|
-
const raw = (env.AMR_HOME ?? "").trim();
|
|
3366
|
-
if (!raw) return join(home, ".amr");
|
|
3367
|
-
if (raw === "~") return home;
|
|
3368
|
-
if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(home, raw.slice(2));
|
|
3369
|
-
return raw;
|
|
3370
|
-
}
|
|
3371
|
-
function desktopConfigPath(env = process.env, home = osHomedir()) {
|
|
3372
|
-
return join(desktopConfigDir(env, home), "config.json");
|
|
3373
|
-
}
|
|
3374
|
-
function parseDesktopConfigText(text2, profile = DEFAULT_PROFILE) {
|
|
3375
|
-
let parsed;
|
|
3376
|
-
try {
|
|
3377
|
-
parsed = JSON.parse(text2);
|
|
3378
|
-
} catch {
|
|
3379
|
-
return { state: "invalid" };
|
|
3380
|
-
}
|
|
3381
|
-
if (!record(parsed)) return { state: "invalid" };
|
|
3382
|
-
const profiles = parsed["profiles"];
|
|
3383
|
-
if (!record(profiles)) return { state: "invalid" };
|
|
3384
|
-
const entry = profiles[profile];
|
|
3385
|
-
if (entry === void 0) return { state: "incomplete", profile };
|
|
3386
|
-
if (!record(entry)) return { state: "invalid" };
|
|
3387
|
-
const controlKey = typeof entry["controlKey"] === "string" ? entry["controlKey"].trim() : "";
|
|
3388
|
-
const runtimeKey = typeof entry["runtimeKey"] === "string" ? entry["runtimeKey"].trim() : "";
|
|
3389
|
-
const rawApiUrl = typeof entry["apiUrl"] === "string" ? entry["apiUrl"].trim() : "";
|
|
3390
|
-
const user = record(entry["user"]) ? entry["user"] : void 0;
|
|
3391
|
-
const plan = typeof user?.["plan"] === "string" ? user["plan"].trim() : "";
|
|
3392
|
-
if (!controlKey) return { state: "incomplete", profile };
|
|
3393
|
-
try {
|
|
3394
|
-
safeSecret(controlKey);
|
|
3395
|
-
} catch {
|
|
3396
|
-
return { state: "invalid" };
|
|
3397
|
-
}
|
|
3398
|
-
const apiUrl = normalizeApiUrl(rawApiUrl);
|
|
3399
|
-
if (rawApiUrl && !apiUrl) return { state: "unsafe-api-url", profile };
|
|
3400
|
-
if (profile !== DEFAULT_PROFILE) return { state: "unsupported-profile", profile };
|
|
3401
|
-
return {
|
|
3402
|
-
state: "credential",
|
|
3403
|
-
credential: {
|
|
3404
|
-
profile,
|
|
3405
|
-
controlKey,
|
|
3406
|
-
...apiUrl === void 0 ? {} : { apiUrl },
|
|
3407
|
-
...plan ? { plan } : {},
|
|
3408
|
-
signedIn: runtimeKey.length > 0
|
|
3409
|
-
}
|
|
3410
|
-
};
|
|
3411
|
-
}
|
|
3412
|
-
async function readDesktopCredential(deps = {}) {
|
|
3413
|
-
const env = deps.env ?? process.env;
|
|
3414
|
-
const profile = deps.profile ?? resolveProfile(env);
|
|
3415
|
-
const path = desktopConfigPath(env, deps.home ?? osHomedir());
|
|
3416
|
-
const readFile = deps.readFile ?? ((file) => fsReadFile(file, "utf8"));
|
|
3417
|
-
let text2;
|
|
3418
|
-
try {
|
|
3419
|
-
text2 = await readFile(path);
|
|
3420
|
-
} catch (error) {
|
|
3421
|
-
const code = record(error) && typeof error["code"] === "string" ? error["code"] : "";
|
|
3422
|
-
return code === "ENOENT" || code === "ENOTDIR" ? { state: "missing" } : { state: "unreadable" };
|
|
3423
|
-
}
|
|
3424
|
-
return parseDesktopConfigText(text2, profile);
|
|
3425
|
-
}
|
|
3426
|
-
function deviceGrant(value) {
|
|
3427
|
-
if (!record(value) || value.kind !== "device" || typeof value.controlKey !== "string" || typeof value.runtimeKey !== "string") return;
|
|
3428
|
-
try {
|
|
3429
|
-
const controlKey = safeSecret(value.controlKey), runtimeKey = safeSecret(value.runtimeKey);
|
|
3430
|
-
if ([controlKey, runtimeKey].some((key) => key.length > 8192 || /\s/u.test(key))) return;
|
|
3431
|
-
return { kind: "device", controlKey, runtimeKey, ...typeof value.savedAt === "string" ? { savedAt: value.savedAt } : {} };
|
|
3432
|
-
} catch {
|
|
3433
|
-
return void 0;
|
|
3434
|
-
}
|
|
3435
|
-
}
|
|
3436
|
-
function isOfficialRuntimeUrl(raw) {
|
|
3437
|
-
try {
|
|
3438
|
-
const url = new URL(raw);
|
|
3439
|
-
return url.origin === "https://amr-link.open-design.ai" && !url.username && !url.password && !url.search && !url.hash;
|
|
3440
|
-
} catch {
|
|
3441
|
-
return false;
|
|
3442
|
-
}
|
|
3443
|
-
}
|
|
3444
|
-
function cookieHeader(raw) {
|
|
3445
|
-
const value = raw.trim();
|
|
3446
|
-
if (!value || !value.includes("=")) return void 0;
|
|
3447
|
-
try {
|
|
3448
|
-
return safeSecret(value);
|
|
3449
|
-
} catch {
|
|
3450
|
-
return void 0;
|
|
3451
|
-
}
|
|
3452
|
-
}
|
|
3453
|
-
function desktopSession(credential, apiUrl = credential.apiUrl ?? DEFAULT_API_URL) {
|
|
3454
|
-
const base = normalizeApiUrl(apiUrl) ?? DEFAULT_API_URL;
|
|
3455
|
-
return {
|
|
3456
|
-
headers: { authorization: `Bearer ${safeSecret(credential.controlKey)}` },
|
|
3457
|
-
source: "desktop",
|
|
3458
|
-
via: "desktop",
|
|
3459
|
-
apiUrl: base,
|
|
3460
|
-
profile: credential.profile,
|
|
3461
|
-
...credential.plan ? { plan: credential.plan } : {}
|
|
3462
|
-
};
|
|
3463
|
-
}
|
|
3464
|
-
function deviceSession(tokens) {
|
|
3465
|
-
const controlKey = typeof tokens === "string" ? tokens : tokens.controlKey;
|
|
3466
|
-
return { headers: { authorization: `Bearer ${safeSecret(controlKey)}` }, source: "login", via: "login", apiUrl: DEFAULT_API_URL, credentialType: "device" };
|
|
3467
|
-
}
|
|
3468
|
-
function cookieSession(cookie, source, apiUrl = DEFAULT_API_URL) {
|
|
3469
|
-
const header = cookieHeader(cookie);
|
|
3470
|
-
if (!header) return void 0;
|
|
3471
|
-
return {
|
|
3472
|
-
headers: { cookie: header },
|
|
3473
|
-
source,
|
|
3474
|
-
via: source === "environment" ? "environment" : "login",
|
|
3475
|
-
apiUrl: normalizeApiUrl(apiUrl) ?? DEFAULT_API_URL
|
|
3476
|
-
};
|
|
3477
|
-
}
|
|
3478
|
-
async function resolveSession(deps = {}) {
|
|
3479
|
-
const env = deps.env ?? process.env;
|
|
3480
|
-
const warnings = [];
|
|
3481
|
-
const now = deps.now ?? Date.now;
|
|
3482
|
-
if (deps.useDesktop !== false) {
|
|
3483
|
-
const desktop = await readDesktopCredential(deps);
|
|
3484
|
-
if (desktop.state === "credential") {
|
|
3485
|
-
const envApiUrl = (env.VELA_API_URL ?? "").trim();
|
|
3486
|
-
if (envApiUrl && !normalizeApiUrl(envApiUrl)) {
|
|
3487
|
-
warnings.push("unsafe-api-url");
|
|
3488
|
-
} else {
|
|
3489
|
-
return { state: "ready", session: desktopSession(desktop.credential, envApiUrl || DEFAULT_API_URL), warnings };
|
|
3490
|
-
}
|
|
3491
|
-
} else if (desktop.state === "unsafe-api-url") {
|
|
3492
|
-
warnings.push("unsafe-api-url");
|
|
3493
|
-
} else if (desktop.state === "unsupported-profile") {
|
|
3494
|
-
warnings.push("unsupported-profile");
|
|
3495
|
-
} else if (desktop.state === "incomplete") {
|
|
3496
|
-
warnings.push("desktop-incomplete");
|
|
3497
|
-
} else if (desktop.state === "unreadable" || desktop.state === "invalid") {
|
|
3498
|
-
warnings.push("desktop-unreadable");
|
|
3499
|
-
}
|
|
3500
|
-
}
|
|
3501
|
-
if (deps.readGrant) {
|
|
3502
|
-
let grant;
|
|
3503
|
-
try {
|
|
3504
|
-
grant = await deps.readGrant();
|
|
3505
|
-
} catch {
|
|
3506
|
-
grant = void 0;
|
|
3507
|
-
}
|
|
3508
|
-
if (grant && "kind" in grant && grant.kind === "device") {
|
|
3509
|
-
const device = deviceGrant(grant);
|
|
3510
|
-
if (device) return { state: "ready", session: deviceSession(device), warnings };
|
|
3511
|
-
} else if (grant && "cookie" in grant) {
|
|
3512
|
-
const expiry = typeof grant.expiresAt === "number" && Number.isFinite(grant.expiresAt) ? grant.expiresAt : 0;
|
|
3513
|
-
if (expiry === 0 || expiry > now()) {
|
|
3514
|
-
const session = cookieSession(grant.cookie, "login");
|
|
3515
|
-
if (session) return { state: "ready", session, warnings };
|
|
3516
|
-
}
|
|
3517
|
-
}
|
|
3518
|
-
}
|
|
3519
|
-
if (deps.resolveRef) {
|
|
3520
|
-
for (const ref of COOKIE_ENV_REFS) {
|
|
3521
|
-
let value;
|
|
3522
|
-
try {
|
|
3523
|
-
value = await deps.resolveRef(ref);
|
|
3524
|
-
} catch {
|
|
3525
|
-
value = void 0;
|
|
3526
|
-
}
|
|
3527
|
-
if (!value) continue;
|
|
3528
|
-
const session = cookieSession(value, "environment");
|
|
3529
|
-
if (session) return { state: "ready", session, warnings };
|
|
3530
|
-
}
|
|
4249
|
+
return { status: "failed", source, fetchedAt: now().toISOString(), currency: null, unit: null, models: [], issues: [issue] };
|
|
4250
|
+
} finally {
|
|
4251
|
+
deadline.removeEventListener("abort", onAbort);
|
|
3531
4252
|
}
|
|
3532
|
-
return { state: "need-login", reason: warnings[0] ?? "no-credential", warnings };
|
|
3533
4253
|
}
|
|
3534
4254
|
|
|
3535
4255
|
// src/login.ts
|
|
@@ -3537,7 +4257,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
|
|
|
3537
4257
|
|
|
3538
4258
|
// src/device-auth.ts
|
|
3539
4259
|
var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
|
|
3540
|
-
var DEVICE_AUTH_PLUGIN_VERSION = "0.
|
|
4260
|
+
var DEVICE_AUTH_PLUGIN_VERSION = "0.2.0";
|
|
3541
4261
|
var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
|
|
3542
4262
|
var DEVICE_RESPONSE_MAX_BYTES = 65536;
|
|
3543
4263
|
var DEVICE_POLL_MIN_MS = 1e3;
|
|
@@ -4195,216 +4915,6 @@ async function defaultLaunch() {
|
|
|
4195
4915
|
return playwright.chromium.launch(chromeLaunchOptions());
|
|
4196
4916
|
}
|
|
4197
4917
|
|
|
4198
|
-
// src/quota.ts
|
|
4199
|
-
import { attributionHeaders as attributionHeaders3 } from "@deepseek-ai/dsh-llm";
|
|
4200
|
-
var API_BASE = "https://amr-api.open-design.ai/api/v1";
|
|
4201
|
-
var CURRENT_URL = `${API_BASE}/workspaces/current`;
|
|
4202
|
-
var SUMMARY_URL = `${API_BASE}/billing/summary`;
|
|
4203
|
-
var usageUrl = (workspace) => `${API_BASE}/workspaces/${encodeURIComponent(workspace)}/billing/coding-plan-usage`;
|
|
4204
|
-
var preflightUrl = (workspace) => `${API_BASE}/workspaces/${encodeURIComponent(workspace)}/billing/preflight`;
|
|
4205
|
-
var ConsoleError = class extends Error {
|
|
4206
|
-
constructor(kind, status) {
|
|
4207
|
-
super(kind === "auth" ? "OpenDesign \u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55" : kind === "permission" ? "OpenDesign \u5F53\u524D\u767B\u5F55\u6001\u65E0\u6743\u8BFB\u53D6\u8BE5\u989D\u5EA6\u5C42" : kind === "rate-limit" ? "OpenDesign \u989D\u5EA6\u63A5\u53E3\u9650\u6D41\uFF0C\u8BF7\u7A0D\u540E\u5237\u65B0" : kind === "response" ? "OpenDesign \u989D\u5EA6\u63A5\u53E3\u8FD4\u56DE\u683C\u5F0F\u53D1\u751F\u53D8\u5316" : "OpenDesign \u989D\u5EA6\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6");
|
|
4208
|
-
this.kind = kind;
|
|
4209
|
-
this.status = status;
|
|
4210
|
-
}
|
|
4211
|
-
kind;
|
|
4212
|
-
status;
|
|
4213
|
-
};
|
|
4214
|
-
async function consoleJson(url, session, signal, fetcher = fetch) {
|
|
4215
|
-
signal?.throwIfAborted();
|
|
4216
|
-
if (session.credentialType === "device") {
|
|
4217
|
-
let target;
|
|
4218
|
-
try {
|
|
4219
|
-
target = new URL(url);
|
|
4220
|
-
} catch {
|
|
4221
|
-
throw new ConsoleError("response");
|
|
4222
|
-
}
|
|
4223
|
-
if (target.origin !== "https://amr-api.open-design.ai" || target.username || target.password) throw new ConsoleError("response");
|
|
4224
|
-
}
|
|
4225
|
-
const requestSignal = combinedSignal(signal, 2e4);
|
|
4226
|
-
let rejectAbort = () => void 0;
|
|
4227
|
-
const aborted = new Promise((_resolve, reject) => {
|
|
4228
|
-
rejectAbort = reject;
|
|
4229
|
-
});
|
|
4230
|
-
const onAbort = () => rejectAbort(new ConsoleError("network"));
|
|
4231
|
-
requestSignal.addEventListener("abort", onAbort, { once: true });
|
|
4232
|
-
const read = async () => {
|
|
4233
|
-
const response = await fetcher(url, { headers: { ...attributionHeaders3(), accept: "application/json", ...session.headers }, signal: requestSignal, redirect: "error", credentials: "omit" });
|
|
4234
|
-
const cancelBody = () => {
|
|
4235
|
-
void response.body?.cancel().catch(() => void 0);
|
|
4236
|
-
};
|
|
4237
|
-
if (requestSignal.aborted) {
|
|
4238
|
-
cancelBody();
|
|
4239
|
-
throw new ConsoleError("network");
|
|
4240
|
-
}
|
|
4241
|
-
if (response.redirected || response.url && response.url !== url) {
|
|
4242
|
-
cancelBody();
|
|
4243
|
-
throw new ConsoleError("response");
|
|
4244
|
-
}
|
|
4245
|
-
if (response.status === 401 || response.status === 403) {
|
|
4246
|
-
cancelBody();
|
|
4247
|
-
throw new ConsoleError(response.status === 401 ? "auth" : "permission", response.status);
|
|
4248
|
-
}
|
|
4249
|
-
if (!response.ok) {
|
|
4250
|
-
cancelBody();
|
|
4251
|
-
throw new ConsoleError(response.status === 429 ? "rate-limit" : "network", response.status);
|
|
4252
|
-
}
|
|
4253
|
-
const declared = response.headers.get("content-length");
|
|
4254
|
-
if (declared !== null && (!/^\d+$/u.test(declared) || Number(declared) > 2 * 1024 * 1024)) {
|
|
4255
|
-
cancelBody();
|
|
4256
|
-
throw new ConsoleError("response");
|
|
4257
|
-
}
|
|
4258
|
-
const reader = response.body?.getReader();
|
|
4259
|
-
if (!reader) throw new ConsoleError("response");
|
|
4260
|
-
const cancelReader = () => {
|
|
4261
|
-
void reader.cancel().catch(() => void 0);
|
|
4262
|
-
};
|
|
4263
|
-
requestSignal.addEventListener("abort", cancelReader, { once: true });
|
|
4264
|
-
let size = 0, raw = "";
|
|
4265
|
-
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
4266
|
-
try {
|
|
4267
|
-
while (true) {
|
|
4268
|
-
const chunk = await reader.read();
|
|
4269
|
-
if (requestSignal.aborted) throw new ConsoleError("network");
|
|
4270
|
-
if (chunk.done) break;
|
|
4271
|
-
size += chunk.value.byteLength;
|
|
4272
|
-
if (size > 2 * 1024 * 1024) throw new ConsoleError("response");
|
|
4273
|
-
raw += decoder.decode(chunk.value, { stream: true });
|
|
4274
|
-
}
|
|
4275
|
-
raw += decoder.decode();
|
|
4276
|
-
} finally {
|
|
4277
|
-
requestSignal.removeEventListener("abort", cancelReader);
|
|
4278
|
-
cancelReader();
|
|
4279
|
-
reader.releaseLock();
|
|
4280
|
-
}
|
|
4281
|
-
let body;
|
|
4282
|
-
try {
|
|
4283
|
-
body = JSON.parse(raw);
|
|
4284
|
-
} catch {
|
|
4285
|
-
throw new ConsoleError("response");
|
|
4286
|
-
}
|
|
4287
|
-
if (record(body) && (body.code === 401 || body.code === "401")) throw new ConsoleError("auth", 401);
|
|
4288
|
-
if (record(body) && (body.code === 403 || body.code === "403")) throw new ConsoleError("permission", 403);
|
|
4289
|
-
return body;
|
|
4290
|
-
};
|
|
4291
|
-
try {
|
|
4292
|
-
return await Promise.race([read(), aborted]);
|
|
4293
|
-
} catch (error) {
|
|
4294
|
-
signal?.throwIfAborted();
|
|
4295
|
-
throw error instanceof ConsoleError ? error : new ConsoleError("network");
|
|
4296
|
-
} finally {
|
|
4297
|
-
requestSignal.removeEventListener("abort", onAbort);
|
|
4298
|
-
}
|
|
4299
|
-
}
|
|
4300
|
-
function number(value, negative = false) {
|
|
4301
|
-
const n = typeof value === "number" ? value : typeof value === "string" && /^-?\d+(\.\d+)?$/u.test(value.trim()) ? Number(value) : NaN;
|
|
4302
|
-
return Number.isFinite(n) && (negative || n >= 0) ? n : void 0;
|
|
4303
|
-
}
|
|
4304
|
-
function iso(value) {
|
|
4305
|
-
return typeof value === "string" && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : void 0;
|
|
4306
|
-
}
|
|
4307
|
-
function normalizeQuota(body, summary) {
|
|
4308
|
-
if (!record(body) || !(typeof body.eligible === "boolean" || typeof body.tier === "string" || body.tier === null || Array.isArray(body.windows))) throw new ConsoleError("response");
|
|
4309
|
-
const windows = [];
|
|
4310
|
-
for (const row of Array.isArray(body.windows) ? body.windows : []) {
|
|
4311
|
-
if (!record(row)) continue;
|
|
4312
|
-
const seconds = number(row.durationSeconds), used = number(row.usedCredits), limit = number(row.limitCredits), remaining = number(row.remainingCredits);
|
|
4313
|
-
if (seconds === void 0 || seconds <= 0 || used === void 0 || limit === void 0 || limit <= 0) continue;
|
|
4314
|
-
const resetsAt = iso(row.resetsAt), windowStart = iso(row.windowStart);
|
|
4315
|
-
const resetMode = typeof row.resetMode === "string" && row.resetMode.trim() ? row.resetMode.trim() : void 0;
|
|
4316
|
-
windows.push({ durationSeconds: seconds, used, limit, percent: Math.min(100, used / limit * 100), ...remaining === void 0 ? {} : { remaining }, ...resetsAt === void 0 ? {} : { resetsAt }, ...windowStart === void 0 ? {} : { windowStart }, ...resetMode === void 0 ? {} : { resetMode } });
|
|
4317
|
-
}
|
|
4318
|
-
const membershipTier = record(summary) && typeof summary.membershipTier === "string" ? summary.membershipTier.trim() : "";
|
|
4319
|
-
const tier = typeof body.tier === "string" ? body.tier.trim() : body.tier === void 0 && body.eligible !== false ? membershipTier : "";
|
|
4320
|
-
const eligible = typeof body.eligible === "boolean" ? body.eligible : body.tier === null ? false : void 0;
|
|
4321
|
-
return { windows, balances: normalizeBalances(summary), ...normalizeSubscription(summary), ...tier ? { tier } : {}, ...eligible === void 0 ? {} : { eligible } };
|
|
4322
|
-
}
|
|
4323
|
-
function normalizeSubscription(summary) {
|
|
4324
|
-
if (!record(summary)) return {};
|
|
4325
|
-
const start = iso(summary.subscriptionCurrentPeriodStart), end = iso(summary.subscriptionCurrentPeriodEnd);
|
|
4326
|
-
return { ...start === void 0 ? {} : { subscriptionPeriodStart: start }, ...end === void 0 ? {} : { subscriptionPeriodEnd: end } };
|
|
4327
|
-
}
|
|
4328
|
-
function normalizeBalances(summary) {
|
|
4329
|
-
if (!record(summary)) return {};
|
|
4330
|
-
const perUsd = number(summary.creditsPerUsd), balances = record(summary.balances) ? summary.balances : {};
|
|
4331
|
-
const subscription = number(balances.subscriptionCredits), recharge = number(balances.rechargeCredits), total = number(balances.totalAvailableCredits, true);
|
|
4332
|
-
const divisor = perUsd !== void 0 && perUsd > 0 ? perUsd : void 0;
|
|
4333
|
-
const totalUsd = number(summary.balanceUsd, true) ?? number(summary.totalAvailableCreditsUsd, true) ?? (divisor !== void 0 && total !== void 0 ? total / divisor : void 0);
|
|
4334
|
-
return { ...divisor !== void 0 && subscription !== void 0 ? { subscriptionUsd: subscription / divisor } : {}, ...divisor !== void 0 && recharge !== void 0 ? { rechargeUsd: recharge / divisor } : {}, ...totalUsd !== void 0 ? { totalUsd } : {} };
|
|
4335
|
-
}
|
|
4336
|
-
async function readDeviceQuota(session, signal, fetcher = fetch) {
|
|
4337
|
-
const common = { source: session.source, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
4338
|
-
let current;
|
|
4339
|
-
try {
|
|
4340
|
-
current = await consoleJson(CURRENT_URL, session, signal, fetcher);
|
|
4341
|
-
} catch (error) {
|
|
4342
|
-
signal?.throwIfAborted();
|
|
4343
|
-
if (error instanceof ConsoleError && error.kind === "permission") return { ...common, state: "partial", windows: [], balances: {}, note: "\u5F53\u524D\u8BBE\u5907\u6388\u6743\u65E0\u6743\u8BFB\u53D6\u5DE5\u4F5C\u533A\uFF1B\u989D\u5EA6\u6682\u4E0D\u53EF\u786E\u8BA4" };
|
|
4344
|
-
throw error;
|
|
4345
|
-
}
|
|
4346
|
-
if (!record(current)) throw new ConsoleError("response");
|
|
4347
|
-
const workspaceId = typeof current.activeWorkspaceId === "string" && current.activeWorkspaceId.trim() ? current.activeWorkspaceId : current.workspaceId;
|
|
4348
|
-
if (typeof workspaceId !== "string" || !/^[A-Za-z0-9_-]{1,64}$/u.test(workspaceId)) throw new ConsoleError("response");
|
|
4349
|
-
const personal = current.workspaceType === "personal";
|
|
4350
|
-
const [preflight, billing] = await Promise.allSettled([
|
|
4351
|
-
consoleJson(preflightUrl(workspaceId), session, signal, fetcher),
|
|
4352
|
-
personal ? consoleJson(SUMMARY_URL, session, signal, fetcher) : Promise.resolve(void 0)
|
|
4353
|
-
]);
|
|
4354
|
-
signal?.throwIfAborted();
|
|
4355
|
-
for (const item of [preflight, billing]) if (item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "auth") throw item.reason;
|
|
4356
|
-
const summary = billing.status === "fulfilled" ? billing.value : void 0;
|
|
4357
|
-
const flight = preflight.status === "fulfilled" && record(preflight.value) ? preflight.value : void 0;
|
|
4358
|
-
let normalized;
|
|
4359
|
-
try {
|
|
4360
|
-
normalized = normalizeQuota(flight?.codingPlan, personal ? summary : void 0);
|
|
4361
|
-
} catch (error) {
|
|
4362
|
-
if (!(error instanceof ConsoleError)) throw error;
|
|
4363
|
-
}
|
|
4364
|
-
const balances = personal ? normalizeBalances(summary) : {};
|
|
4365
|
-
const total = personal ? number(flight?.balanceUsd, true) : void 0;
|
|
4366
|
-
if (total !== void 0) balances.totalUsd = total;
|
|
4367
|
-
const permission = [preflight, billing].some((item) => item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "permission");
|
|
4368
|
-
if (!normalized && !Object.keys(balances).length && !permission) {
|
|
4369
|
-
if (preflight.status === "rejected") throw preflight.reason;
|
|
4370
|
-
throw new ConsoleError("response");
|
|
4371
|
-
}
|
|
4372
|
-
const windows = normalized?.windows ?? [];
|
|
4373
|
-
const missingWindows = normalized?.eligible !== false && !windows.length;
|
|
4374
|
-
const missingBalances = personal && Object.keys(balances).length < 3;
|
|
4375
|
-
const partial = missingWindows || missingBalances || !personal || permission;
|
|
4376
|
-
const note = !personal ? "\u56E2\u961F\u6216\u672A\u77E5\u5DE5\u4F5C\u533A\uFF1A\u8D26\u53F7\u94B1\u5305\u53E3\u5F84\u672A\u6838\u5B9E\uFF0C\u6682\u4E0D\u663E\u793A" : missingWindows ? "\u5957\u9910\u989D\u5EA6\u7A97\u53E3\u6682\u4E0D\u53EF\u786E\u8BA4" : missingBalances ? "\u90E8\u5206\u94B1\u5305\u4F59\u989D\u6682\u4E0D\u53EF\u786E\u8BA4" : permission ? "\u90E8\u5206\u989D\u5EA6\u5C42\u65E0\u6743\u8BFB\u53D6" : normalized?.eligible === false ? "\u8BE5\u8D26\u53F7\u6CA1\u6709 Design Plan \u8BA2\u9605\uFF1B\u94B1\u5305\u4F59\u989D\u7167\u5E38\u663E\u793A" : void 0;
|
|
4377
|
-
return { ...common, ...normalized, ...normalizeSubscription(personal ? summary : void 0), windows, balances, state: partial ? "partial" : "ok", ...note ? { note } : {} };
|
|
4378
|
-
}
|
|
4379
|
-
async function readQuota(session, signal, fetcher = fetch) {
|
|
4380
|
-
if (session.credentialType === "device") return readDeviceQuota(session, signal, fetcher);
|
|
4381
|
-
const current = await consoleJson(CURRENT_URL, session, signal, fetcher);
|
|
4382
|
-
if (!record(current) || typeof current.workspaceId !== "string" || !/^[A-Za-z0-9_-]{1,64}$/u.test(current.workspaceId)) throw new ConsoleError("response");
|
|
4383
|
-
const personal = current.workspaceType === "personal";
|
|
4384
|
-
const [usage, billing] = await Promise.allSettled([
|
|
4385
|
-
consoleJson(usageUrl(current.workspaceId), session, signal, fetcher),
|
|
4386
|
-
personal ? consoleJson(SUMMARY_URL, session, signal, fetcher) : Promise.resolve(void 0)
|
|
4387
|
-
]);
|
|
4388
|
-
for (const item of [usage, billing]) if (item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "auth") throw item.reason;
|
|
4389
|
-
const summary = billing.status === "fulfilled" ? billing.value : void 0;
|
|
4390
|
-
const common = { source: session.source, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
4391
|
-
let normalized;
|
|
4392
|
-
try {
|
|
4393
|
-
if (usage.status === "rejected") throw usage.reason;
|
|
4394
|
-
normalized = normalizeQuota(usage.value, summary);
|
|
4395
|
-
} catch (error) {
|
|
4396
|
-
const balances = normalizeBalances(summary);
|
|
4397
|
-
if (!Object.keys(balances).length) throw error;
|
|
4398
|
-
return { ...common, state: "partial", windows: [], balances, ...normalizeSubscription(summary), note: "\u94B1\u5305\u5DF2\u8BFB\u53D6\uFF1B\u5957\u9910\u8D60\u9001\u989D\u5EA6\u6682\u4E0D\u53EF\u786E\u8BA4" };
|
|
4399
|
-
}
|
|
4400
|
-
const missingWindows = normalized.eligible !== false && !normalized.windows.length;
|
|
4401
|
-
const noSubscription = normalized.eligible === false && !normalized.windows.length;
|
|
4402
|
-
const missingBalances = personal && Object.keys(normalized.balances).length < 3;
|
|
4403
|
-
const partial = missingWindows || missingBalances || !personal;
|
|
4404
|
-
const note = !personal ? "\u56E2\u961F\u6216\u672A\u77E5\u5DE5\u4F5C\u533A\uFF1A\u8D26\u53F7\u94B1\u5305\u53E3\u5F84\u672A\u6838\u5B9E\uFF0C\u6682\u4E0D\u663E\u793A" : missingWindows ? "\u5957\u9910\u989D\u5EA6\u7A97\u53E3\u6682\u4E0D\u53EF\u786E\u8BA4" : noSubscription ? "\u8BE5\u8D26\u53F7\u6CA1\u6709 Design Plan \u8BA2\u9605\uFF1B\u94B1\u5305\u4F59\u989D\u7167\u5E38\u663E\u793A" : missingBalances ? "\u90E8\u5206\u94B1\u5305\u4F59\u989D\u6682\u4E0D\u53EF\u786E\u8BA4" : void 0;
|
|
4405
|
-
return { ...common, ...normalized, state: partial ? "partial" : "ok", ...note === void 0 ? {} : { note } };
|
|
4406
|
-
}
|
|
4407
|
-
|
|
4408
4918
|
// src/desktop-quota.ts
|
|
4409
4919
|
import { execFile } from "node:child_process";
|
|
4410
4920
|
import { existsSync } from "node:fs";
|
|
@@ -4645,7 +5155,10 @@ function parseStatusModel(value) {
|
|
|
4645
5155
|
...value.contextWindow === void 0 ? {} : { contextWindow: positiveInteger(value.contextWindow, "\u4E0A\u4E0B\u6587\u9884\u7B97", 1e8) },
|
|
4646
5156
|
...value.maxOutputTokens === void 0 ? {} : { maxOutputTokens: positiveInteger(value.maxOutputTokens, "\u6700\u5927\u8F93\u51FA", 1e7) },
|
|
4647
5157
|
...value.reasoningEfforts === void 0 ? {} : { reasoningEfforts: parseEfforts(value.reasoningEfforts) },
|
|
4648
|
-
...value.defaultEffort === void 0 ? {} : { defaultEffort: parseEffort(value.defaultEffort) }
|
|
5158
|
+
...value.defaultEffort === void 0 ? {} : { defaultEffort: parseEffort(value.defaultEffort) },
|
|
5159
|
+
...value.nativeProtocol === void 0 ? {} : { nativeProtocol: member(value.nativeProtocol, API_PROTOCOL_IDS, "\u539F\u751F\u534F\u8BAE") },
|
|
5160
|
+
...value.effectiveProtocol === void 0 ? {} : { effectiveProtocol: member(value.effectiveProtocol, API_PROTOCOL_IDS, "\u751F\u6548\u534F\u8BAE") },
|
|
5161
|
+
...value.coverage === void 0 ? {} : { coverage: member(value.coverage, ["included", "not-included", "unknown"], "\u6A21\u578B\u8BA2\u9605\u8986\u76D6") }
|
|
4649
5162
|
};
|
|
4650
5163
|
}
|
|
4651
5164
|
function parseEffort(value) {
|
|
@@ -4666,7 +5179,7 @@ function parseStatusConfig(value) {
|
|
|
4666
5179
|
useDesktopCredential: flag(value.useDesktopCredential, "\u684C\u9762\u767B\u5F55\u6001\u5F00\u5173"),
|
|
4667
5180
|
baseURL: text(value.baseURL, "\u63A8\u7406\u5730\u5740", MAX_BASE_URL),
|
|
4668
5181
|
apiKeyEnv,
|
|
4669
|
-
...value.apiProtocol === void 0 ? {} : { apiProtocol: member(value.apiProtocol,
|
|
5182
|
+
...value.apiProtocol === void 0 ? {} : { apiProtocol: member(value.apiProtocol, API_PROTOCOL_SELECTION_IDS, "\u63A8\u7406\u534F\u8BAE") },
|
|
4670
5183
|
...value.modelSettings === void 0 ? {} : { modelSettings: parseModelSettingsMap(value.modelSettings) },
|
|
4671
5184
|
...value.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: positiveInteger(value.requestTimeoutMs, "\u8BF7\u6C42\u8D85\u65F6", 36e5, 1e3) },
|
|
4672
5185
|
...value.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: positiveInteger(value.streamIdleTimeoutMs, "\u6D41\u7A7A\u95F2\u8D85\u65F6", 18e5, 1e3) },
|
|
@@ -4687,7 +5200,7 @@ function parseStatus(value) {
|
|
|
4687
5200
|
ids.add(model.id);
|
|
4688
5201
|
}
|
|
4689
5202
|
const apiKeyConfigured = flag(value.apiKeyConfigured, "\u51ED\u636E\u662F\u5426\u5C31\u7EEA");
|
|
4690
|
-
const apiKeySource = value.apiKeySource === void 0 ? void 0 : member(value.apiKeySource, ["reference", "stored", "device"], "\u63A8\u7406\u51ED\u636E\u6765\u6E90");
|
|
5203
|
+
const apiKeySource = value.apiKeySource === void 0 ? void 0 : member(value.apiKeySource, ["reference", "stored", "device", "desktop"], "\u63A8\u7406\u51ED\u636E\u6765\u6E90");
|
|
4691
5204
|
if (!apiKeyConfigured && apiKeySource !== void 0) throw new Error("\u672A\u914D\u7F6E\u51ED\u636E\u65F6\u4E0D\u80FD\u6307\u5B9A\u63A8\u7406\u51ED\u636E\u6765\u6E90");
|
|
4692
5205
|
return {
|
|
4693
5206
|
revision: text(value.revision, "\u914D\u7F6E\u7248\u672C", MAX_REVISION),
|
|
@@ -4702,7 +5215,17 @@ function parseStatus(value) {
|
|
|
4702
5215
|
models: parsed,
|
|
4703
5216
|
...value.modelsSource === void 0 ? {} : { modelsSource: member(value.modelsSource, ["builtin", "openai"], "\u6A21\u578B\u76EE\u5F55\u6765\u6E90") },
|
|
4704
5217
|
...value.modelsUpdatedAt === void 0 ? {} : { modelsUpdatedAt: isoTime(value.modelsUpdatedAt, "\u6A21\u578B\u66F4\u65B0\u65F6\u95F4") },
|
|
4705
|
-
...value.modelsError === void 0 ? {} : { modelsError: text(value.modelsError, "\u6A21\u578B\u66F4\u65B0\u63D0\u793A", MAX_MESSAGE) }
|
|
5218
|
+
...value.modelsError === void 0 ? {} : { modelsError: text(value.modelsError, "\u6A21\u578B\u66F4\u65B0\u63D0\u793A", MAX_MESSAGE) },
|
|
5219
|
+
...value.modelEntitlements === void 0 ? {} : { modelEntitlements: parseModelEntitlements(value.modelEntitlements) }
|
|
5220
|
+
};
|
|
5221
|
+
}
|
|
5222
|
+
function parseModelEntitlements(value) {
|
|
5223
|
+
if (!record(value)) throw new Error("\u6A21\u578B\u6743\u76CA\u72B6\u6001\u65E0\u6548");
|
|
5224
|
+
return {
|
|
5225
|
+
state: member(value.state, ["verified", "partial", "unavailable"], "\u6A21\u578B\u6743\u76CA\u72B6\u6001"),
|
|
5226
|
+
...value.source === void 0 ? {} : { source: member(value.source, ["device", "desktop"], "\u6A21\u578B\u6743\u76CA\u6765\u6E90") },
|
|
5227
|
+
...value.tier === void 0 ? {} : { tier: text(value.tier, "\u6A21\u578B\u6743\u76CA\u5957\u9910", 32) },
|
|
5228
|
+
...value.updatedAt === void 0 ? {} : { updatedAt: isoTime(value.updatedAt, "\u6A21\u578B\u6743\u76CA\u66F4\u65B0\u65F6\u95F4") }
|
|
4706
5229
|
};
|
|
4707
5230
|
}
|
|
4708
5231
|
function parseTurnMonitor(value) {
|
|
@@ -4745,7 +5268,7 @@ var API_KEY = credentialKey2(name, "api-key");
|
|
|
4745
5268
|
var SESSION = credentialKey2(name, "console");
|
|
4746
5269
|
var SETTINGS_CONFLICT = "SETTINGS_CONFLICT";
|
|
4747
5270
|
var NATIVE_AUTH = { env: [], oauth: true };
|
|
4748
|
-
var hash = (value) =>
|
|
5271
|
+
var hash = (value) => createHash4("sha256").update(JSON.stringify(value) ?? "").digest("hex");
|
|
4749
5272
|
var stableConfig = (config) => {
|
|
4750
5273
|
const { modelCatalog: _snapshot, ...rest } = config;
|
|
4751
5274
|
return rest;
|
|
@@ -4779,19 +5302,27 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4779
5302
|
__publicField(this, "_quotaController");
|
|
4780
5303
|
__publicField(this, "guardedTurns", 0);
|
|
4781
5304
|
__publicField(this, "turnMonitorStatus");
|
|
4782
|
-
__publicField(this, "
|
|
4783
|
-
__publicField(this, "
|
|
4784
|
-
__publicField(this, "_modelsError");
|
|
5305
|
+
__publicField(this, "_directory");
|
|
5306
|
+
__publicField(this, "_catalogKeys");
|
|
4785
5307
|
__publicField(this, "_modelsFingerprint", "");
|
|
4786
|
-
__publicField(this, "_modelsEpoch", 0);
|
|
4787
|
-
__publicField(this, "_modelsPending");
|
|
4788
|
-
__publicField(this, "_modelsController");
|
|
4789
|
-
__publicField(this, "_modelsWriteSerial", 0);
|
|
4790
|
-
__publicField(this, "_modelsWrite", Promise.resolve());
|
|
4791
5308
|
__publicField(this, "_prices");
|
|
4792
5309
|
__publicField(this, "_pricesPending");
|
|
4793
5310
|
this._config = config;
|
|
4794
|
-
this.
|
|
5311
|
+
this._catalogKeys = new ReplayKeyStore(() => ctx.get("credentials"));
|
|
5312
|
+
this._directory = new ModelDirectory({
|
|
5313
|
+
config: this._config,
|
|
5314
|
+
state: async () => {
|
|
5315
|
+
const state = await this._state();
|
|
5316
|
+
const account = state.key ? await (dependencies.modelAccount ?? resolveModelAccount)(state.key, state.config.baseURL, grantOf(state.sessionRecord), state.config.useDesktopCredential) : void 0;
|
|
5317
|
+
return { ...state.key ? { key: state.key } : {}, ...account ? { account } : {} };
|
|
5318
|
+
},
|
|
5319
|
+
changed: () => dependencies.modelsChanged?.(),
|
|
5320
|
+
persist: (snapshot) => this._persistModels(snapshot),
|
|
5321
|
+
bindingSecret: (signal) => this._catalogKeys.get(signal),
|
|
5322
|
+
...dependencies.fetchModels ? { fetchModels: dependencies.fetchModels } : {},
|
|
5323
|
+
...dependencies.readModelScope ? { readScope: dependencies.readModelScope } : {},
|
|
5324
|
+
...dependencies.readEntitlements ? { readEntitlements: dependencies.readEntitlements } : {}
|
|
5325
|
+
});
|
|
4795
5326
|
this._login = new ConsoleLogin({
|
|
4796
5327
|
capture: async (expectedRevision) => {
|
|
4797
5328
|
const state = await this._state();
|
|
@@ -4826,13 +5357,27 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4826
5357
|
this._activation = new ActivationLauncher(dependencies.activationOptions);
|
|
4827
5358
|
ctx.effect(() => () => {
|
|
4828
5359
|
this._lifetime.abort();
|
|
5360
|
+
this._directory.dispose();
|
|
5361
|
+
this._catalogKeys.dispose();
|
|
4829
5362
|
this._login.dispose();
|
|
4830
5363
|
return this._activation.dispose();
|
|
4831
5364
|
});
|
|
4832
5365
|
}
|
|
4833
5366
|
dependencies;
|
|
4834
5367
|
modelCatalog() {
|
|
4835
|
-
return this.
|
|
5368
|
+
return this._directory.models();
|
|
5369
|
+
}
|
|
5370
|
+
modelWorkspace() {
|
|
5371
|
+
return this._directory.workspace();
|
|
5372
|
+
}
|
|
5373
|
+
modelCallIdentity() {
|
|
5374
|
+
return this._directory.callIdentity();
|
|
5375
|
+
}
|
|
5376
|
+
async currentModelCatalog() {
|
|
5377
|
+
await this._state();
|
|
5378
|
+
if (this._directory.updatedAt() === void 0) await this._directory.refresh();
|
|
5379
|
+
else if (this.dependencies.modelAutoRefresh !== false) this._directory.warm();
|
|
5380
|
+
return this._directory.models();
|
|
4836
5381
|
}
|
|
4837
5382
|
_credentials() {
|
|
4838
5383
|
const service = this.ctx.get("credentials");
|
|
@@ -4845,25 +5390,17 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4845
5390
|
if (ambient?.trim()) return { key: ambient, source: "reference" };
|
|
4846
5391
|
if (apiRecord?.kind === "api-key" && apiRecord.key?.trim()) return { key: apiRecord.key, source: "stored" };
|
|
4847
5392
|
const grant = grantOf(sessionRecord);
|
|
4848
|
-
|
|
5393
|
+
if (isOfficialRuntimeUrl(baseURL) && grant && "kind" in grant && grant.kind === "device") return { key: grant.runtimeKey, source: "device" };
|
|
5394
|
+
if (isOfficialRuntimeUrl(baseURL) && this._config().useDesktopCredential) {
|
|
5395
|
+
const desktop = await (this.dependencies.readDesktopCredential ?? readDesktopCredential)();
|
|
5396
|
+
if (desktop.state === "credential" && desktop.credential.runtimeKey) return { key: desktop.credential.runtimeKey, source: "desktop" };
|
|
5397
|
+
}
|
|
4849
5398
|
}
|
|
4850
5399
|
async resolveApiKey(ref, baseURL = this._config().baseURL) {
|
|
4851
5400
|
const credentials = this.ctx.get("credentials");
|
|
4852
5401
|
const [apiRecord, sessionRecord] = await Promise.all([credentials?.readRecord(API_KEY), credentials?.readRecord(SESSION)]);
|
|
4853
5402
|
return (await this._key(ref, baseURL, apiRecord, sessionRecord))?.key;
|
|
4854
5403
|
}
|
|
4855
|
-
/** Restore the persisted gateway catalog when it belongs to the active gateway. */
|
|
4856
|
-
_restoreModels() {
|
|
4857
|
-
const config = this._config();
|
|
4858
|
-
const snapshot = config.modelCatalog;
|
|
4859
|
-
if (!snapshot || snapshot.baseURL !== config.baseURL) return;
|
|
4860
|
-
this._models = snapshot.models.map((row) => {
|
|
4861
|
-
const known = findModel(row.id);
|
|
4862
|
-
if (known?.defaultEffort === void 0 || row.defaultEffort !== void 0) return row;
|
|
4863
|
-
return (row.reasoningEfforts ?? []).includes(known.defaultEffort) ? { ...row, defaultEffort: known.defaultEffort } : row;
|
|
4864
|
-
});
|
|
4865
|
-
this._modelsUpdatedAt = snapshot.updatedAt;
|
|
4866
|
-
}
|
|
4867
5404
|
/**
|
|
4868
5405
|
* Persist the snapshot through the Host form service.
|
|
4869
5406
|
* `unsupported` means no settings service is composed (nothing to report);
|
|
@@ -4893,34 +5430,8 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4893
5430
|
}
|
|
4894
5431
|
return "failed";
|
|
4895
5432
|
}
|
|
4896
|
-
/** Serialize snapshot writes so the newest successful refresh is the last one persisted. */
|
|
4897
|
-
_queueModelsWrite(snapshot, epoch) {
|
|
4898
|
-
const serial = ++this._modelsWriteSerial;
|
|
4899
|
-
this._modelsWrite = this._modelsWrite.then(async () => {
|
|
4900
|
-
const result = await this._persistModels(snapshot);
|
|
4901
|
-
if (serial !== this._modelsWriteSerial || epoch !== this._modelsEpoch) return;
|
|
4902
|
-
if (result === "unavailable") this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u5F53\u524D\u914D\u7F6E\u670D\u52A1\u4E0D\u53EF\u5199\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
|
|
4903
|
-
else if (result === "failed") this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u4FDD\u5B58\u5931\u8D25\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
|
|
4904
|
-
}).catch(() => {
|
|
4905
|
-
if (serial !== this._modelsWriteSerial || epoch !== this._modelsEpoch) return;
|
|
4906
|
-
this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u4FDD\u5B58\u5931\u8D25\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
|
|
4907
|
-
});
|
|
4908
|
-
}
|
|
4909
5433
|
_invalidateModels() {
|
|
4910
|
-
|
|
4911
|
-
this._modelsEpoch++;
|
|
4912
|
-
this._modelsController?.abort();
|
|
4913
|
-
this._modelsPending = void 0;
|
|
4914
|
-
this._models = MODELS;
|
|
4915
|
-
this._modelsUpdatedAt = void 0;
|
|
4916
|
-
this._modelsError = void 0;
|
|
4917
|
-
this._restoreModels();
|
|
4918
|
-
if (changed || this._modelsUpdatedAt !== void 0) {
|
|
4919
|
-
try {
|
|
4920
|
-
this.dependencies.modelsChanged?.();
|
|
4921
|
-
} catch {
|
|
4922
|
-
}
|
|
4923
|
-
}
|
|
5434
|
+
this._directory.invalidate();
|
|
4924
5435
|
}
|
|
4925
5436
|
async _state() {
|
|
4926
5437
|
const credentials = this.ctx.get("credentials"), config = this._config();
|
|
@@ -4928,7 +5439,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4928
5439
|
const resolved = await this._key(apiKeyRef(config), config.baseURL, apiRecord, sessionRecord);
|
|
4929
5440
|
const key = resolved?.key;
|
|
4930
5441
|
const state = { apiRecord, sessionRecord, key, keySource: resolved?.source, config };
|
|
4931
|
-
const modelsFingerprint = hash({ key, baseURL: config.baseURL });
|
|
5442
|
+
const modelsFingerprint = hash({ key, baseURL: config.baseURL, session: sessionRecord, desktop: config.useDesktopCredential });
|
|
4932
5443
|
if (modelsFingerprint !== this._modelsFingerprint) {
|
|
4933
5444
|
this._modelsFingerprint = modelsFingerprint;
|
|
4934
5445
|
this._invalidateModels();
|
|
@@ -4956,6 +5467,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4956
5467
|
}
|
|
4957
5468
|
async status() {
|
|
4958
5469
|
const state = await this._state();
|
|
5470
|
+
if (this.dependencies.modelAutoRefresh !== false) this._directory.warm();
|
|
4959
5471
|
const quotaConfig = hash({ desktop: state.config.useDesktopCredential, session: state.sessionRecord, refreshSeconds: state.config.quotaRefreshSeconds });
|
|
4960
5472
|
if (this._quotaConfig !== quotaConfig) {
|
|
4961
5473
|
this._quotaConfig = quotaConfig;
|
|
@@ -4971,9 +5483,9 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4971
5483
|
config: { ...state.config, apiKeyEnv: state.config.apiKeyEnv ?? "" },
|
|
4972
5484
|
guardedTurns: this.guardedTurns,
|
|
4973
5485
|
...this.turnMonitorStatus ? { turnMonitor: this.turnMonitorStatus() } : {},
|
|
4974
|
-
models: this.
|
|
5486
|
+
models: this._directory.models().map((row) => {
|
|
4975
5487
|
const { id, name: name2, group: group2, contextWindow, maxOutputTokens, inputModalities } = row;
|
|
4976
|
-
const protocol = state.config.apiProtocol
|
|
5488
|
+
const protocol = effectiveProtocol(row, state.config.apiProtocol, state.config.modelSettings?.[row.id]?.apiProtocol);
|
|
4977
5489
|
const reasoningEfforts = modelReasoningEfforts(row, protocol);
|
|
4978
5490
|
const defaultEffort = vendorDefaultEffort(row, protocol);
|
|
4979
5491
|
return {
|
|
@@ -4981,6 +5493,9 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4981
5493
|
name: name2,
|
|
4982
5494
|
group: group2,
|
|
4983
5495
|
enabled: isModelEnabled(id, state.config.modelSettings),
|
|
5496
|
+
...row.coverage ? { coverage: row.coverage } : {},
|
|
5497
|
+
...row.nativeProtocol ? { nativeProtocol: row.nativeProtocol } : {},
|
|
5498
|
+
effectiveProtocol: protocol,
|
|
4984
5499
|
...inputModalities === void 0 ? {} : { inputModalities },
|
|
4985
5500
|
...contextWindow === void 0 ? {} : { contextWindow },
|
|
4986
5501
|
...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
|
|
@@ -4988,55 +5503,16 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
4988
5503
|
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
4989
5504
|
};
|
|
4990
5505
|
}),
|
|
4991
|
-
modelsSource: this.
|
|
4992
|
-
...this.
|
|
4993
|
-
...this.
|
|
5506
|
+
modelsSource: this._directory.updatedAt() ? "openai" : "builtin",
|
|
5507
|
+
...this._directory.updatedAt() ? { modelsUpdatedAt: this._directory.updatedAt() } : {},
|
|
5508
|
+
...this._directory.error() ? { modelsError: this._directory.error() } : {},
|
|
5509
|
+
modelEntitlements: this._directory.entitlements()
|
|
4994
5510
|
});
|
|
4995
5511
|
}
|
|
4996
5512
|
async refreshModels() {
|
|
4997
|
-
|
|
4998
|
-
|
|
4999
|
-
|
|
5000
|
-
if (!key?.trim()) {
|
|
5001
|
-
this._modelsError = "\u8BF7\u5148\u914D\u7F6E API Key\uFF0C\u518D\u4ECE\u5F53\u524D\u7F51\u5173\u8BFB\u53D6\u6A21\u578B\u76EE\u5F55\u3002";
|
|
5002
|
-
return this.status();
|
|
5003
|
-
}
|
|
5004
|
-
const epoch = this._modelsEpoch;
|
|
5005
|
-
const controller = new AbortController();
|
|
5006
|
-
this._modelsController = controller;
|
|
5007
|
-
const signal = AbortSignal.any([controller.signal, this._lifetime.signal]);
|
|
5008
|
-
const run = (async () => {
|
|
5009
|
-
try {
|
|
5010
|
-
const models = await (this.dependencies.fetchModels ?? fetchModelCatalog)(state.config.baseURL, key, signal);
|
|
5011
|
-
await this._state();
|
|
5012
|
-
if (signal.aborted || epoch !== this._modelsEpoch) return this.status();
|
|
5013
|
-
const previousModels = this._models;
|
|
5014
|
-
const previousUpdatedAt = this._modelsUpdatedAt;
|
|
5015
|
-
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5016
|
-
this._models = models;
|
|
5017
|
-
this._modelsUpdatedAt = updatedAt;
|
|
5018
|
-
this._modelsError = void 0;
|
|
5019
|
-
let accepted = true;
|
|
5020
|
-
try {
|
|
5021
|
-
this.dependencies.modelsChanged?.();
|
|
5022
|
-
} catch {
|
|
5023
|
-
accepted = false;
|
|
5024
|
-
this._models = previousModels;
|
|
5025
|
-
this._modelsUpdatedAt = previousUpdatedAt;
|
|
5026
|
-
this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u8BFB\u53D6\uFF0C\u4F46\u6A21\u578B\u9009\u62E9\u5668\u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002";
|
|
5027
|
-
}
|
|
5028
|
-
if (accepted) this._queueModelsWrite({ baseURL: state.config.baseURL, updatedAt, models }, epoch);
|
|
5029
|
-
} catch (error) {
|
|
5030
|
-
if (!signal.aborted && epoch === this._modelsEpoch) this._modelsError = error instanceof ModelDiscoveryError ? error.message : "\u6A21\u578B\u5217\u8868\u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";
|
|
5031
|
-
}
|
|
5032
|
-
return this.status();
|
|
5033
|
-
})();
|
|
5034
|
-
this._modelsPending = run;
|
|
5035
|
-
try {
|
|
5036
|
-
return await run;
|
|
5037
|
-
} finally {
|
|
5038
|
-
if (this._modelsPending === run) this._modelsPending = void 0;
|
|
5039
|
-
}
|
|
5513
|
+
await this._state();
|
|
5514
|
+
await this._directory.refresh();
|
|
5515
|
+
return this.status();
|
|
5040
5516
|
}
|
|
5041
5517
|
async refreshPrices() {
|
|
5042
5518
|
if (this._pricesPending) return this._pricesPending;
|
|
@@ -5225,6 +5701,8 @@ function apply(ctx, config) {
|
|
|
5225
5701
|
const adapter = new CoRouterAdapter({
|
|
5226
5702
|
config: current,
|
|
5227
5703
|
models: () => service.modelCatalog(),
|
|
5704
|
+
readyModels: () => service.currentModelCatalog(),
|
|
5705
|
+
callIdentity: () => service.modelCallIdentity(),
|
|
5228
5706
|
apiKey: (ref, baseURL) => service.resolveApiKey(ref, baseURL),
|
|
5229
5707
|
onEmptyTurn: () => {
|
|
5230
5708
|
service.guardedTurns++;
|