dsh-opendesign-corouter 0.1.18 → 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/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 createHash2 } from "node:crypto";
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,9 +75,9 @@ 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 MODELS = [
78
+ var REFERENCE_MODELS = [
79
79
  // ── OpenAI(8) ─────────────────────────────────────────────
80
- { id: "gpt-6.1-sol", name: "GPT-6.1 Sol", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
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
  {
82
82
  id: "gpt-6.1-terra",
83
83
  name: "GPT-6.1 Terra",
@@ -85,40 +85,47 @@ var MODELS = [
85
85
  contextWindow: 105e4,
86
86
  maxOutputTokens: 128e3,
87
87
  inputModalities: TEXT_AND_IMAGE,
88
- reasoningEfforts: EFFORTS_OPENAI
88
+ reasoningEfforts: EFFORTS_OPENAI,
89
+ defaultEffort: "medium"
89
90
  },
90
- { id: "gpt-6-astra", name: "GPT-6 Astra", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
91
+ // 厂商页只列出档位、未声明默认值;low 取自 Codex CLI 模型注册表的默认 effort 与网关记录。
92
+ { id: "gpt-6-astra", name: "GPT-6 Astra", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "low" },
91
93
  {
92
94
  id: "gpt-6-luna",
93
95
  name: "GPT-6 Luna",
94
- group: "plan",
96
+ group: "paid",
95
97
  contextWindow: 105e4,
96
98
  maxOutputTokens: 128e3,
97
99
  inputModalities: TEXT_AND_IMAGE,
98
- reasoningEfforts: EFFORTS_OPENAI
100
+ reasoningEfforts: EFFORTS_OPENAI,
101
+ defaultEffort: "medium"
99
102
  },
100
- { id: "gpt-6-sol", name: "GPT-6 Sol", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
101
- { id: "gpt-5.6-luna", name: "GPT-5.6 Luna", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
102
- { id: "gpt-5.6-sol", name: "GPT-5.6 Sol", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
103
- { id: "gpt-5.6-terra", name: "GPT-5.6 Terra", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
103
+ { id: "gpt-6-sol", name: "GPT-6 Sol", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI, defaultEffort: "medium" },
104
+ { id: "gpt-5.6-luna", name: "GPT-5.6 Luna", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI, defaultEffort: "medium" },
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
+ { id: "gpt-5.6-terra", name: "GPT-5.6 Terra", group: "paid", contextWindow: 105e4, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI, defaultEffort: "medium" },
104
107
  // ── Anthropic(8) ──────────────────────────────────────────
105
- { id: "claude-fable-5.1", name: "Claude Fable 5.1", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
106
- { id: "claude-fable-5", name: "Claude Fable 5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
107
- { id: "claude-opus-5.5", name: "Claude Opus 5.5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
108
- { id: "claude-opus-5", name: "Claude Opus 5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
109
- { id: "claude-opus-4.8", name: "Claude Opus 4.8", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
110
- { id: "claude-sonnet-5.5", name: "Claude Sonnet 5.5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
111
- { id: "claude-sonnet-5", name: "Claude Sonnet 5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
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" },
109
+ { id: "claude-fable-5.1", name: "Claude Fable 5.1", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
110
+ { id: "claude-fable-5", name: "Claude Fable 5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
111
+ { id: "claude-opus-5.5", name: "Claude Opus 5.5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "medium" },
112
+ { id: "claude-opus-5", name: "Claude Opus 5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
113
+ { id: "claude-opus-4.8", name: "Claude Opus 4.8", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
114
+ { id: "claude-sonnet-5.5", name: "Claude Sonnet 5.5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
115
+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", group: "paid", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "high" },
112
116
  {
113
117
  id: "claude-haiku-5.5",
114
118
  name: "Claude Haiku 5.5",
115
- group: "plan",
119
+ group: "paid",
116
120
  contextWindow: 1e6,
117
121
  maxOutputTokens: 128e3,
118
122
  inputModalities: TEXT_AND_IMAGE,
119
- reasoningEfforts: EFFORTS_REASONING
123
+ reasoningEfforts: EFFORTS_REASONING,
124
+ defaultEffort: "medium"
120
125
  },
121
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" },
122
129
  {
123
130
  id: "deepseek-v4.1-flash",
124
131
  name: "DeepSeek V4.1 Flash",
@@ -126,7 +133,8 @@ var MODELS = [
126
133
  contextWindow: 1e6,
127
134
  maxOutputTokens: 384e3,
128
135
  inputModalities: TEXT_AND_IMAGE,
129
- reasoningEfforts: EFFORTS_LOW_HIGH
136
+ reasoningEfforts: EFFORTS_LOW_HIGH,
137
+ defaultEffort: "high"
130
138
  },
131
139
  {
132
140
  id: "deepseek-v4-pro",
@@ -134,7 +142,8 @@ var MODELS = [
134
142
  group: "plan",
135
143
  contextWindow: 1e6,
136
144
  maxOutputTokens: 384e3,
137
- reasoningEfforts: EFFORTS_LOW_HIGH
145
+ reasoningEfforts: EFFORTS_LOW_HIGH,
146
+ defaultEffort: "high"
138
147
  },
139
148
  {
140
149
  id: "deepseek-v4-flash",
@@ -143,7 +152,8 @@ var MODELS = [
143
152
  contextWindow: 1e6,
144
153
  maxOutputTokens: 384e3,
145
154
  inputModalities: TEXT_AND_IMAGE,
146
- reasoningEfforts: EFFORTS_LOW_HIGH
155
+ reasoningEfforts: EFFORTS_LOW_HIGH,
156
+ defaultEffort: "high"
147
157
  },
148
158
  {
149
159
  id: "deepseek-v4-flash-vision-exp",
@@ -152,17 +162,19 @@ var MODELS = [
152
162
  contextWindow: 1e6,
153
163
  maxOutputTokens: 384e3,
154
164
  inputModalities: TEXT_AND_IMAGE,
155
- reasoningEfforts: EFFORTS_LOW_HIGH
165
+ reasoningEfforts: EFFORTS_LOW_HIGH,
166
+ defaultEffort: "high"
156
167
  },
157
168
  // ── Z.ai(3) ───────────────────────────────────────────────
158
169
  {
159
170
  id: "glm-5.3-flashx",
160
171
  name: "GLM-5.3 Flash-X",
161
- group: "plan",
172
+ group: "paid",
162
173
  contextWindow: 1e6,
163
174
  maxOutputTokens: 128e3,
164
175
  inputModalities: TEXT_AND_IMAGE,
165
- reasoningEfforts: EFFORTS_LOW_HIGH
176
+ reasoningEfforts: EFFORTS_LOW_HIGH,
177
+ defaultEffort: "max"
166
178
  },
167
179
  {
168
180
  id: "glm-5.3-flash",
@@ -171,9 +183,10 @@ var MODELS = [
171
183
  contextWindow: 1e6,
172
184
  maxOutputTokens: 128e3,
173
185
  inputModalities: TEXT_AND_IMAGE,
174
- reasoningEfforts: EFFORTS_LOW_HIGH
186
+ reasoningEfforts: EFFORTS_LOW_HIGH,
187
+ defaultEffort: "max"
175
188
  },
176
- { id: "glm-5.2", name: "GLM-5.2", group: "paid", contextWindow: 1e6, inputModalities: TEXT_ONLY, reasoningEfforts: EFFORTS_GLM52 },
189
+ { id: "glm-5.2", name: "GLM-5.2", group: "paid", contextWindow: 1e6, inputModalities: TEXT_ONLY, reasoningEfforts: EFFORTS_GLM52, defaultEffort: "max" },
177
190
  // ── Moonshot(3) ───────────────────────────────────────────
178
191
  {
179
192
  id: "kimi-k2.7-code",
@@ -184,16 +197,17 @@ var MODELS = [
184
197
  inputModalities: TEXT_AND_IMAGE,
185
198
  reasoningEfforts: []
186
199
  },
187
- { id: "kimi-k3", name: "Kimi K3", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LOW_HIGH },
188
- { id: "kimi-k3.1-pro", name: "Kimi K3.1 Pro", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LOW_HIGH },
200
+ { id: "kimi-k3", name: "Kimi K3", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LOW_HIGH, defaultEffort: "max" },
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" },
189
202
  // ── Google(3) ─────────────────────────────────────────────
190
- { id: "gemini-4-argon", name: "Gemini 4 Argon", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
191
- { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
192
- { id: "gemini-3.7-flash", name: "Gemini 3.7 Flash", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
203
+ { id: "gemini-4-carbon", name: "Gemini 4 Carbon", group: "paid" },
204
+ { id: "gemini-4-argon", name: "Gemini 4 Argon", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS, defaultEffort: "medium" },
205
+ { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS, defaultEffort: "medium" },
206
+ { id: "gemini-3.7-flash", name: "Gemini 3.7 Flash", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS, defaultEffort: "medium" },
193
207
  // ── xAI(3) ────────────────────────────────────────────────
194
- { id: "grok-4.7", name: "Grok 4.7", group: "paid", contextWindow: 5e5, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_GROK },
195
- { id: "grok-4.6", name: "Grok 4.6", group: "paid", contextWindow: 5e5, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_GROK },
196
- { id: "grok-4.5", name: "Grok 4.5", group: "paid", contextWindow: 5e5, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
208
+ { id: "grok-4.7", name: "Grok 4.7", group: "paid", contextWindow: 5e5, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_GROK, defaultEffort: "high" },
209
+ { id: "grok-4.6", name: "Grok 4.6", group: "paid", contextWindow: 5e5, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_GROK, defaultEffort: "high" },
210
+ { id: "grok-4.5", name: "Grok 4.5", group: "paid", contextWindow: 5e5, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS, defaultEffort: "high" },
197
211
  // ── Xiaomi(2) ─────────────────────────────────────────────
198
212
  {
199
213
  id: "mimo-v2.6-pro",
@@ -214,6 +228,8 @@ var MODELS = [
214
228
  reasoningEfforts: []
215
229
  },
216
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" },
217
233
  {
218
234
  id: "hy4-preview",
219
235
  name: "Hunyuan H4 Preview",
@@ -221,15 +237,54 @@ var MODELS = [
221
237
  contextWindow: 1e6,
222
238
  maxOutputTokens: 64e3,
223
239
  inputModalities: TEXT_ONLY,
224
- reasoningEfforts: ["none", "high"]
240
+ reasoningEfforts: ["none", "high"],
241
+ defaultEffort: "high"
225
242
  },
226
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" },
227
246
  { id: "qwen3.7-max", name: "Qwen3.7 Max", group: "paid", contextWindow: 1e6, inputModalities: TEXT_ONLY, reasoningEfforts: [] },
228
247
  // Official API additions; display labels for undocumented entries are local formatting.
229
- { id: "minimax-m3.1-flash", name: "MiniMax M3.1 Flash", group: "plan", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
230
- { id: "muse-spark-1.3", name: "Muse Spark 1.3", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_MUSE },
248
+ { id: "muse-ember-1.0", name: "Muse Ember 1.0", group: "paid" },
249
+ { id: "minimax-m3.1-flash", name: "MiniMax M3.1 Flash", group: "plan", contextWindow: 1e6, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING, defaultEffort: "max" },
250
+ // 厂商只说默认“由模型决定”;high 取自 Meta 合作客户端与网关实现的默认 effort。
251
+ { id: "muse-spark-1.3", name: "Muse Spark 1.3", group: "paid", contextWindow: 1048576, inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_MUSE, defaultEffort: "high" },
231
252
  { id: "muse-wonder", name: "Muse Wonder", group: "paid", contextWindow: 1048576 }
232
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] } : {} }));
233
288
  var BY_ID = new Map(MODELS.map((model) => [model.id, model]));
234
289
  function findModel(id) {
235
290
  return BY_ID.get(id);
@@ -240,6 +295,12 @@ import Schema from "@deepseek-ai/schemastery";
240
295
 
241
296
  // src/protocol-options.ts
242
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
+ }
243
304
  function openAiBaseURL(baseURL) {
244
305
  const base = baseURL.replace(/\/+$/u, "");
245
306
  return new URL(base).pathname === "/" ? `${base}/v1` : base;
@@ -267,7 +328,7 @@ function parseModelSettingsMap(value) {
267
328
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");
268
329
  const keys = Object.keys(value);
269
330
  if (keys.length > 512) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u6700\u591A\u5141\u8BB8 512 \u4E2A\u6A21\u578B");
270
- 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"]);
271
332
  const efforts = ["none", "minimal", "low", "medium", "high", "xhigh", "ultra", "max"];
272
333
  const out = {};
273
334
  for (const id of keys) {
@@ -280,6 +341,10 @@ function parseModelSettingsMap(value) {
280
341
  if (!fields.has(field)) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u542B\u6709\u4E0D\u652F\u6301\u7684\u5B57\u6BB5");
281
342
  }
282
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
+ }
283
348
  if (settings.enabled !== void 0) {
284
349
  if (typeof settings.enabled !== "boolean") throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
285
350
  parsed.enabled = settings.enabled;
@@ -347,10 +412,11 @@ function serializableTransform(callback) {
347
412
  function parseModelCatalogSnapshot(value) {
348
413
  const MODEL_ID4 = /^[A-Za-z0-9._:/-]{1,128}$/u;
349
414
  const GROUPS = ["plan", "paid"];
350
- const KEYS = ["id", "name", "group", "contextWindow", "maxOutputTokens", "inputModalities", "reasoningEfforts"];
415
+ const KEYS = ["id", "name", "group", "contextWindow", "maxOutputTokens", "inputModalities", "reasoningEfforts", "defaultEffort", "nativeProtocol", "coverage"];
351
416
  const RESERVED = ["__proto__", "constructor", "prototype"];
352
417
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
353
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;
354
420
  if (typeof snapshot.baseURL !== "string" || snapshot.baseURL.length === 0 || snapshot.baseURL.length > 2048) return void 0;
355
421
  let base;
356
422
  try {
@@ -375,6 +441,14 @@ function parseModelCatalogSnapshot(value) {
375
441
  if (typeof name2 !== "string" || name2.trim().length === 0 || name2.length > 128) return void 0;
376
442
  if (typeof group2 !== "string" || !GROUPS.includes(group2)) return void 0;
377
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
+ }
378
452
  if (item.contextWindow !== void 0) {
379
453
  if (!Number.isSafeInteger(item.contextWindow) || item.contextWindow <= 0 || item.contextWindow > 1e8) return void 0;
380
454
  model.contextWindow = item.contextWindow;
@@ -402,10 +476,15 @@ function parseModelCatalogSnapshot(value) {
402
476
  }
403
477
  model.reasoningEfforts = efforts;
404
478
  }
479
+ if (item.defaultEffort !== void 0) {
480
+ if (typeof item.defaultEffort !== "string" || item.defaultEffort.length === 0 || item.defaultEffort.length > 32) return void 0;
481
+ if (!(model.reasoningEfforts ?? []).includes(item.defaultEffort)) return void 0;
482
+ model.defaultEffort = item.defaultEffort;
483
+ }
405
484
  seen.add(id);
406
485
  models.push(model);
407
486
  }
408
- return { baseURL, updatedAt: snapshot.updatedAt, models };
487
+ return { baseURL, updatedAt: snapshot.updatedAt, models, ...snapshot.binding === void 0 ? {} : { binding: snapshot.binding } };
409
488
  }
410
489
 
411
490
  // src/image-budget.ts
@@ -422,7 +501,7 @@ var DEFAULT_API_KEY_REF = "COROUTER_API_KEY";
422
501
  var Config = Schema.object({
423
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(),
424
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(),
425
- apiProtocol: Schema.union(API_PROTOCOL_IDS).default("chat-completions").description("\u7F51\u5173\u652F\u6301\u7684\u63A8\u7406\u534F\u8BAE\uFF1B\u6A21\u578B\u76EE\u5F55\u901A\u8FC7\u8BE5\u7F51\u5173\u7684\u517C\u5BB9\u63A5\u53E3\u8BFB\u53D6").volatile(),
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(),
426
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(),
427
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(),
428
507
  useDesktopCredential: Schema.boolean().default(true).description("\u4F18\u5148\u8BFB\u53D6 OpenDesign \u684C\u9762\u7AEF\u767B\u5F55\u6001\u67E5\u8BE2\u989D\u5EA6").volatile(),
@@ -1119,6 +1198,14 @@ function protocolAcceptsEffort(protocol, effort) {
1119
1198
  function modelReasoningEfforts(model, protocol) {
1120
1199
  return model.reasoningEfforts?.filter((effort) => protocolAcceptsEffort(protocol, effort));
1121
1200
  }
1201
+ function vendorDefaultEffort(model, protocol) {
1202
+ const available = modelReasoningEfforts(model, protocol);
1203
+ return model.defaultEffort !== void 0 && available?.includes(model.defaultEffort) === true ? model.defaultEffort : void 0;
1204
+ }
1205
+ function defaultReasoningEffort(model, protocol, configured) {
1206
+ if (configured === void 0) return vendorDefaultEffort(model, protocol);
1207
+ return modelReasoningEfforts(model, protocol)?.includes(configured) === true ? configured : void 0;
1208
+ }
1122
1209
 
1123
1210
  // src/protocols/chat-completions.ts
1124
1211
  function buildChatCompletionsRequest(ctx) {
@@ -1150,6 +1237,7 @@ var chatCompletions = {
1150
1237
  };
1151
1238
 
1152
1239
  // src/protocols/messages.ts
1240
+ import { createHash } from "node:crypto";
1153
1241
  import {
1154
1242
  LlmError as LlmError8,
1155
1243
  ToolCallId as ToolCallId2
@@ -1223,6 +1311,7 @@ import { LlmError as LlmError7 } from "@deepseek-ai/dsh-llm";
1223
1311
 
1224
1312
  // src/claude-capabilities.ts
1225
1313
  var RESTRICTED_MESSAGES_SAMPLING = /* @__PURE__ */ new Set([
1314
+ "claude-fable-5.2",
1226
1315
  "claude-fable-5.1",
1227
1316
  "claude-fable-5",
1228
1317
  "claude-opus-5.5",
@@ -1264,7 +1353,30 @@ var DATA_URL = /^data:([^;,]+);base64,(.*)$/su;
1264
1353
  var REPLAY_FORMAT = "opendesign.anthropic-messages";
1265
1354
  var MAX_REPLAY_CHARS = 8 * 1024 * 1024;
1266
1355
  var MAX_BLOCKS = 4096;
1267
- function replayBlocks(message, ctx) {
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) {
1268
1380
  if (message.role !== "assistant" || message.source.provider !== ctx.options.provider || message.source.model !== ctx.options.model) return;
1269
1381
  const envelope = message.source.replayState;
1270
1382
  if (!record(envelope) || !record(envelope.response) || !Array.isArray(envelope.blocks)) return;
@@ -1293,6 +1405,7 @@ function replayBlocks(message, ctx) {
1293
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)) {
1294
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");
1295
1407
  }
1408
+ if (ctx.model.id === PREFIX_BOUND_MODEL && (prefix === void 0 || response.requestPrefix !== prefix || response.blocksDigest !== replayDigest(entries))) return;
1296
1409
  return entries;
1297
1410
  }
1298
1411
  function messagesURL(baseURL) {
@@ -1320,20 +1433,32 @@ function buildMessagesRequest(ctx) {
1320
1433
  validateClaudeOutput(model.id, maxTokens);
1321
1434
  if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) throw new LlmError8("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
1322
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;
1323
1444
  const messages2 = [];
1445
+ const pushMessage = (message) => {
1446
+ messages2.push(message);
1447
+ binding?.append(message);
1448
+ };
1324
1449
  const lookup = ctx.images.size ? (ref) => ctx.images.get(ref.attachmentId) : void 0;
1325
1450
  let results = [];
1326
1451
  let lifted = [];
1327
1452
  const flushResults = () => {
1328
1453
  if (results.length) {
1329
- messages2.push({ role: "user", content: results });
1454
+ pushMessage({ role: "user", content: results });
1330
1455
  results = [];
1331
1456
  }
1332
1457
  };
1333
1458
  const flushLifted = () => {
1334
1459
  flushResults();
1335
1460
  if (lifted.length) {
1336
- messages2.push({
1461
+ pushMessage({
1337
1462
  role: "user",
1338
1463
  content: [{ type: "text", text: "(Image content from the preceding tool result.)" }, ...lifted.map(imagePart)]
1339
1464
  });
@@ -1346,19 +1471,18 @@ function buildMessagesRequest(ctx) {
1346
1471
  switch (message.role) {
1347
1472
  case "system":
1348
1473
  case "developer":
1349
- if (projected.text) system.push(projected.text);
1350
1474
  break;
1351
1475
  case "user": {
1352
1476
  const content2 = [
1353
1477
  ...projected.text ? [{ type: "text", text: projected.text }] : [],
1354
1478
  ...projected.images.map(imagePart)
1355
1479
  ];
1356
- if (content2.length) messages2.push({ role: "user", content: content2 });
1480
+ if (content2.length) pushMessage({ role: "user", content: content2 });
1357
1481
  break;
1358
1482
  }
1359
1483
  case "assistant": {
1360
1484
  const content2 = [];
1361
- const replay = replayBlocks(message, ctx);
1485
+ const replay = replayBlocks(message, ctx, binding?.snapshot());
1362
1486
  for (const [index, block] of message.content.entries()) {
1363
1487
  const entry = replay?.[index];
1364
1488
  if (entry?.type === "thinking") content2.push({ type: "thinking", thinking: entry.thinking, signature: entry.signature });
@@ -1370,7 +1494,7 @@ function buildMessagesRequest(ctx) {
1370
1494
  if (placeholder) content2.push({ type: "text", text: placeholder });
1371
1495
  }
1372
1496
  }
1373
- if (content2.length) messages2.push({ role: "assistant", content: content2 });
1497
+ if (content2.length) pushMessage({ role: "assistant", content: content2 });
1374
1498
  break;
1375
1499
  }
1376
1500
  case "tool": {
@@ -1385,22 +1509,28 @@ function buildMessagesRequest(ctx) {
1385
1509
  }
1386
1510
  }
1387
1511
  flushLifted();
1388
- if (options.system?.trim()) system.unshift(options.system);
1389
1512
  const body = { model: model.id, max_tokens: maxTokens, messages: messages2, stream: true };
1390
- if (system.length) body.system = system.join("\n\n");
1391
- if (options.tools?.length) body.tools = options.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters }));
1513
+ if (systemText !== void 0) body.system = systemText;
1514
+ if (tools !== void 0) body.tools = tools;
1392
1515
  if (options.temperature !== void 0) body.temperature = options.temperature;
1393
1516
  if (ctx.topP !== void 0) body.top_p = ctx.topP;
1394
1517
  if (options.stop?.length) body.stop_sequences = options.stop;
1395
1518
  if (options.reasoningEffort !== void 0) {
1396
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");
1397
1521
  if (effort === "none") body.thinking = { type: "disabled" };
1398
1522
  else if (protocolAcceptsEffort("messages", effort)) {
1399
1523
  body.thinking = { type: "adaptive" };
1400
1524
  body.output_config = { effort };
1401
1525
  } else throw new LlmError8(`Anthropic Messages \u534F\u8BAE\u4E0D\u63A5\u53D7\u601D\u8003\u6DF1\u5EA6\u300C${effort}\u300D`, "UNSUPPORTED_OPTION");
1402
1526
  }
1403
- return { url: messagesURL(ctx.baseURL), headers: streamHeaders(ctx.apiKey, { "anthropic-version": ANTHROPIC_VERSION }), body };
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
+ };
1404
1534
  }
1405
1535
  function num(value) {
1406
1536
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
@@ -1452,6 +1582,7 @@ async function* streamMessages(body, signal, idleMs, context) {
1452
1582
  }
1453
1583
  function replay() {
1454
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;
1455
1586
  const entries = [];
1456
1587
  for (const state of blocks.values()) {
1457
1588
  if (!state.started) continue;
@@ -1467,7 +1598,8 @@ async function* streamMessages(body, signal, idleMs, context) {
1467
1598
  provider: context.provider,
1468
1599
  model: context.model,
1469
1600
  origin: new URL(context.baseURL).origin,
1470
- credentialIdentity: context.credentialIdentity
1601
+ credentialIdentity: context.credentialIdentity,
1602
+ ...context.model === PREFIX_BOUND_MODEL ? { requestPrefix: context.replayPrefix, blocksDigest: replayDigest(entries) } : {}
1471
1603
  }, blocks: entries };
1472
1604
  }
1473
1605
  function reasonFromStop(stop) {
@@ -1674,6 +1806,90 @@ import {
1674
1806
  LlmError as LlmError9,
1675
1807
  ToolCallId as ToolCallId3
1676
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
1677
1893
  function userContent(text2, images) {
1678
1894
  if (!images.length) return text2;
1679
1895
  return [
@@ -1704,6 +1920,11 @@ function buildResponsesRequest(ctx) {
1704
1920
  if (projected.text || projected.images.length) input.push({ role: "user", content: userContent(projected.text, projected.images) });
1705
1921
  break;
1706
1922
  case "assistant": {
1923
+ const replay = responseReplay(message, ctx);
1924
+ if (replay) {
1925
+ input.push(...replay);
1926
+ break;
1927
+ }
1707
1928
  if (projected.text) input.push({ role: "assistant", content: projected.text });
1708
1929
  for (const block of message.content) {
1709
1930
  if (block.type === "tool-call") input.push({ type: "function_call", call_id: block.id, name: block.name, arguments: block.arguments });
@@ -1723,7 +1944,7 @@ function buildResponsesRequest(ctx) {
1723
1944
  }
1724
1945
  flushLifted();
1725
1946
  if (options.system?.trim()) instructions.unshift(options.system);
1726
- 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"] };
1727
1948
  if (instructions.length) body.instructions = instructions.join("\n\n");
1728
1949
  if (options.tools?.length) body.tools = options.tools.map((tool) => ({ type: "function", name: tool.name, description: tool.description, parameters: tool.parameters }));
1729
1950
  if (options.temperature !== void 0) body.temperature = options.temperature;
@@ -1759,7 +1980,7 @@ function responseUsage(response) {
1759
1980
  reasoning: typeof output.reasoning_tokens === "number" ? output.reasoning_tokens : void 0
1760
1981
  });
1761
1982
  }
1762
- async function* streamResponses(body, signal, idleMs) {
1983
+ async function* streamResponses(body, signal, idleMs, context) {
1763
1984
  let nextIndex = 0;
1764
1985
  let count2 = 0;
1765
1986
  let usage;
@@ -1995,10 +2216,12 @@ async function* streamResponses(body, signal, idleMs) {
1995
2216
  const reason = reasonOf(type, response);
1996
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");
1997
2218
  if (!count2) throw new LlmError9("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
1998
- out.push(...close());
2219
+ const closed = close();
2220
+ out.push(...closed);
1999
2221
  if (usage) out.push({ type: "usage", usage });
2000
2222
  finish = reason;
2001
- out.push({ type: "finish", reason });
2223
+ const replayState = responseReplayEnvelope(response.output, closed, context);
2224
+ out.push({ type: "finish", reason, ...replayState ? { replayState } : {} });
2002
2225
  break;
2003
2226
  }
2004
2227
  case "error":
@@ -2042,10 +2265,11 @@ function outputReserve(model, protocol) {
2042
2265
  }
2043
2266
  function metadata(provider, row, config) {
2044
2267
  const setting = config.modelSettings?.[row.id];
2045
- const proposedReserve = setting?.maxTokens ?? outputReserve(row, config.apiProtocol ?? "chat-completions");
2046
- const reserve = claudeOutputError(row.id, config.apiProtocol ?? "chat-completions", proposedReserve) === void 0 ? proposedReserve : void 0;
2047
- const efforts = modelReasoningEfforts(row, config.apiProtocol ?? "chat-completions");
2048
- const defaultEffort = setting?.reasoningEffort !== void 0 && efforts?.includes(setting.reasoningEffort) ? setting.reasoningEffort : void 0;
2268
+ const protocol = effectiveProtocol(row, config.apiProtocol, setting?.apiProtocol);
2269
+ const proposedReserve = setting?.maxTokens ?? outputReserve(row, protocol);
2270
+ const reserve = claudeOutputError(row.id, protocol, proposedReserve) === void 0 ? proposedReserve : void 0;
2271
+ const efforts = modelReasoningEfforts(row, protocol);
2272
+ const defaultEffort = defaultReasoningEffort(row, protocol, setting?.reasoningEffort);
2049
2273
  return {
2050
2274
  provider,
2051
2275
  id: row.id,
@@ -2071,12 +2295,12 @@ var CoRouterAdapter = class extends LlmAdapter {
2071
2295
  this.#lifetime.abort(new LlmError11("CoRouter \u63D2\u4EF6\u5DF2\u5378\u8F7D", "ABORTED"));
2072
2296
  this.#credentialSecret.fill(0);
2073
2297
  }
2074
- async #credentialIdentity(baseURL, key, model, signal) {
2298
+ async #credentialIdentity(baseURL, key, model, signal, workspace) {
2075
2299
  let secret2;
2076
2300
  let abort = () => {
2077
2301
  };
2078
2302
  try {
2079
- if (this.options.replayBindingSecret && hasRestrictedClaudeSampling(model, "messages")) {
2303
+ if (this.options.replayBindingSecret) {
2080
2304
  const operation = this.options.replayBindingSecret(signal).then((bytes) => {
2081
2305
  if (signal.aborted) {
2082
2306
  bytes.fill(0);
@@ -2093,7 +2317,9 @@ var CoRouterAdapter = class extends LlmAdapter {
2093
2317
  } else secret2 = Buffer.from(this.#credentialSecret);
2094
2318
  signal.throwIfAborted();
2095
2319
  if (secret2.length !== 32) throw new Error("invalid binding");
2096
- return createHmac("sha256", secret2).update("opendesign-claude-replay-v1\0").update(new URL(baseURL).origin).update("\0").update(key).digest("hex");
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");
2097
2323
  } catch {
2098
2324
  if (signal.aborted) throw new LlmError11("Claude \u56DE\u653E\u7ED1\u5B9A\u5DF2\u53D6\u6D88", "ABORTED");
2099
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");
@@ -2115,6 +2341,7 @@ var CoRouterAdapter = class extends LlmAdapter {
2115
2341
  return configured;
2116
2342
  }
2117
2343
  async listModels(provider) {
2344
+ await this.#ready();
2118
2345
  const config = this.options.config(), selectedGroup = group(provider);
2119
2346
  return (this.options.models?.() ?? MODELS).filter((row) => row.group === selectedGroup && isModelEnabled(row.id, config.modelSettings)).map((row) => {
2120
2347
  const effective = applyModelSettings(row, config.modelSettings?.[row.id]);
@@ -2123,38 +2350,77 @@ var CoRouterAdapter = class extends LlmAdapter {
2123
2350
  }
2124
2351
  async resolveModel(provider, model, signal) {
2125
2352
  signal?.throwIfAborted();
2353
+ await this.#ready(signal);
2126
2354
  const config = this.options.config();
2127
2355
  return metadata(provider, this.modelOf(provider, model, config), config);
2128
2356
  }
2129
2357
  async prepareCall(provider, model, signal) {
2130
2358
  signal?.throwIfAborted();
2359
+ await this.#ready(signal);
2131
2360
  const config = this.options.config(), row = this.modelOf(provider, model, config);
2132
- return { model: metadata(provider, row, config), stream: (options) => this.#stream(options, config, row) };
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) };
2133
2373
  }
2134
2374
  stream(options) {
2135
2375
  const config = this.options.config();
2136
- return this.#stream(options, config, this.modelOf(options.provider, options.model, config));
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
+ }
2137
2400
  }
2138
- async *#stream(options, config, row) {
2401
+ async *#stream(options, config, row, workspace, capturedKey, captured = false) {
2139
2402
  const signal = AbortSignal.any([combinedSignal(options.signal, config.requestTimeoutMs), this.#lifetime.signal]);
2140
2403
  signal.throwIfAborted();
2141
2404
  const setting = config.modelSettings?.[row.id] ?? {};
2142
- const protocolId = config.apiProtocol ?? "chat-completions";
2143
- const effort = options.reasoningEffort ?? (setting.reasoningEffort ? ReasoningEffortId(setting.reasoningEffort) : void 0);
2144
- if (effort !== void 0 && !modelReasoningEfforts(row, protocolId)?.includes(effort)) 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");
2405
+ const protocolId = effectiveProtocol(row, config.apiProtocol, setting.apiProtocol);
2406
+ const configured = setting.reasoningEffort;
2407
+ const explicit = options.reasoningEffort ?? (configured === void 0 ? void 0 : ReasoningEffortId(configured));
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");
2409
+ const vendorDefault = vendorDefaultEffort(row, protocolId);
2410
+ const effort = explicit ?? (vendorDefault === void 0 ? void 0 : ReasoningEffortId(vendorDefault));
2145
2411
  if (protocolId === "messages") {
2146
2412
  validateClaudeSampling(row.id, options.temperature ?? setting.temperature, setting.topP);
2147
2413
  validateClaudeOutput(row.id, options.maxTokens ?? setting.maxTokens);
2148
2414
  }
2149
2415
  const keyRef = apiKeyRef(config);
2150
- const raw = await this.options.apiKey(keyRef, config.baseURL);
2416
+ const raw = captured ? capturedKey : await this.options.apiKey(keyRef, config.baseURL);
2151
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");
2152
2418
  const key = assertUsableApiKey(raw, "dsh-opendesign-corouter", keyRef);
2153
2419
  signal.throwIfAborted();
2154
2420
  let credentialIdentity;
2155
- if (protocolId === "messages") {
2421
+ if (protocolId === "messages" || protocolId === "responses") {
2156
2422
  try {
2157
- credentialIdentity = await this.#credentialIdentity(config.baseURL, key, row.id, signal);
2423
+ credentialIdentity = await this.#credentialIdentity(config.baseURL, key, row.id, signal, workspace);
2158
2424
  } catch (error) {
2159
2425
  if (signal.aborted && !options.signal?.aborted && !this.#lifetime.signal.aborted) throw new LlmError11("CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6", "TIMEOUT");
2160
2426
  throw error;
@@ -2219,7 +2485,7 @@ var CoRouterAdapter = class extends LlmAdapter {
2219
2485
  try {
2220
2486
  response = await (this.options.fetch ?? fetch)(request.url, {
2221
2487
  method: "POST",
2222
- headers: request.headers,
2488
+ headers: { ...request.headers, ...workspace ? { "x-vela-workspace-id": workspace } : {} },
2223
2489
  body: JSON.stringify(request.body),
2224
2490
  signal,
2225
2491
  redirect: "error"
@@ -2280,7 +2546,8 @@ var CoRouterAdapter = class extends LlmAdapter {
2280
2546
  provider: options.provider,
2281
2547
  model: options.model,
2282
2548
  baseURL: config.baseURL,
2283
- ...credentialIdentity === void 0 ? {} : { credentialIdentity }
2549
+ ...credentialIdentity === void 0 ? {} : { credentialIdentity },
2550
+ ...request.replayPrefix === void 0 ? {} : { replayPrefix: request.replayPrefix }
2284
2551
  })) {
2285
2552
  signal.throwIfAborted();
2286
2553
  tracker.observe(chunk);
@@ -2456,7 +2723,7 @@ function installEotRecovery(ctx, enabled, onRetry) {
2456
2723
  }
2457
2724
 
2458
2725
  // src/turn-monitor.ts
2459
- import { createHash } from "node:crypto";
2726
+ import { createHash as createHash3 } from "node:crypto";
2460
2727
  import { createUserMessage, LlmError as LlmError13 } from "@deepseek-ai/dsh-llm";
2461
2728
  var FINISH_TURN_TOOL = "opendesign_finish_turn";
2462
2729
  var MAX_EVIDENCE = 64;
@@ -2626,7 +2893,7 @@ var TurnMonitor = class {
2626
2893
  }
2627
2894
  if (event.type === "tool/call" && typeof data.callId === "string" && typeof data.name === "string") {
2628
2895
  if (state.calls.size >= MAX_EVIDENCE) state.calls.delete(state.calls.keys().next().value ?? "");
2629
- state.calls.set(data.callId, { name: data.name, arguments: createHash("sha256").update(typeof data.arguments === "string" ? data.arguments : "").digest("hex") });
2896
+ state.calls.set(data.callId, { name: data.name, arguments: createHash3("sha256").update(typeof data.arguments === "string" ? data.arguments : "").digest("hex") });
2630
2897
  return;
2631
2898
  }
2632
2899
  if (event.type !== "tool/result" || !record(data.message) || typeof data.message.toolCallId !== "string") return;
@@ -2638,7 +2905,7 @@ var TurnMonitor = class {
2638
2905
  const call = state.calls.get(callId);
2639
2906
  state.calls.delete(callId);
2640
2907
  if (!call || call.name === FINISH_TURN_TOOL || pending) return;
2641
- const fingerprint = createHash("sha256").update(JSON.stringify([call.name, call.arguments, data.message.content, data.message.isError === true])).digest("hex");
2908
+ const fingerprint = createHash3("sha256").update(JSON.stringify([call.name, call.arguments, data.message.content, data.message.isError === true])).digest("hex");
2642
2909
  const success = data.message.isError !== true;
2643
2910
  if (success && !state.fingerprints.has(fingerprint)) {
2644
2911
  state.progress++;
@@ -2860,7 +3127,7 @@ var MAX_MODELS = 512;
2860
3127
  var MAX_MODEL_NAME_LENGTH = 128;
2861
3128
  var MAX_CONTEXT_WINDOW = 1e8;
2862
3129
  var MODEL_ID = /^[A-Za-z0-9._:/-]{1,128}$/u;
2863
- 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;
2864
3131
  var MESSAGES2 = {
2865
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",
2866
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",
@@ -2964,7 +3231,7 @@ function normalize(body) {
2964
3231
  }
2965
3232
  return rows;
2966
3233
  }
2967
- async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher) {
3234
+ async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher, workspaceId) {
2968
3235
  let base;
2969
3236
  try {
2970
3237
  base = openAiBaseURL(assertBaseURL(openAiBaseURL2));
@@ -2983,7 +3250,7 @@ async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher) {
2983
3250
  try {
2984
3251
  response = await request(`${base}/models`, {
2985
3252
  method: "GET",
2986
- 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 } : {} },
2987
3254
  signal: deadline,
2988
3255
  redirect: "error"
2989
3256
  });
@@ -2999,135 +3266,821 @@ async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher) {
2999
3266
  return normalize(await boundedJson(response, signal, deadline));
3000
3267
  }
3001
3268
 
3002
- // src/pricing.ts
3003
- var PRICING_ORIGIN = "https://corouter.open-design.ai";
3004
- var PRICING_CATALOG_PATH = "/zh/models/";
3005
- var PRICING_TIMEOUT_MS = 15e3;
3006
- var MAX_PRICING_BODY_BYTES = 4 * 1024 * 1024;
3007
- var MESSAGES3 = {
3008
- timeout: "\u5B98\u7F51\u4EF7\u683C\u8BF7\u6C42\u8D85\u8FC7\u65F6\u9650",
3009
- aborted: "\u5B98\u7F51\u4EF7\u683C\u8BF7\u6C42\u5DF2\u53D6\u6D88",
3010
- network: "\u65E0\u6CD5\u8FDE\u63A5\u5B98\u7F51",
3011
- status: "\u5B98\u7F51\u8FD4\u56DE\u4E86\u975E 200 \u72B6\u6001",
3012
- "too-large": "\u5B98\u7F51\u4EF7\u683C\u54CD\u5E94\u4F53\u8D85\u8FC7\u4E0A\u9650",
3013
- "invalid-page": "\u62FF\u5230\u7684\u9875\u9762\u4E0D\u662F\u5B98\u7F51\u6A21\u578B\u4EF7\u683C\u9875",
3014
- "invalid-model": "\u62FF\u5230\u7684\u9875\u9762\u4E0D\u662F\u5B98\u7F51\u6A21\u578B\u4EF7\u683C\u8BE6\u60C5\u9875"
3015
- };
3016
- var PricingError = class extends Error {
3017
- constructor(kind, status) {
3018
- super(MESSAGES3[kind]);
3019
- this.kind = kind;
3020
- this.status = status;
3021
- 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;
3022
3287
  }
3023
- kind;
3024
- status;
3025
- };
3026
- var ENTITIES = {
3027
- "&quot;": '"',
3028
- "&amp;": "&",
3029
- "&lt;": "<",
3030
- "&gt;": ">",
3031
- "&apos;": "'",
3032
- "&nbsp;": " ",
3033
- "&mdash;": "\u2014",
3034
- "&ndash;": "\u2013"
3035
- };
3036
- function decodeEntities(text2) {
3037
- return text2.replace(/&(?:quot|amp|lt|gt|apos|nbsp|mdash|ndash);/gu, (match) => ENTITIES[match] ?? match).replace(/&#(\d+);/gu, (_match, code) => {
3038
- const point = Number(code);
3039
- return Number.isInteger(point) && point > 0 && point <= 1114111 ? String.fromCodePoint(point) : "";
3040
- });
3041
- }
3042
- function stripTags(text2) {
3043
- return decodeEntities(text2.replace(/<[^>]*>/gu, " ")).replace(/\s+/gu, " ").trim();
3044
- }
3045
- function metricOf(label) {
3046
- if (/缓存读取|cache\s+read/iu.test(label)) return "cacheRead";
3047
- if (/缓存写入|cache\s+write/iu.test(label)) return "cacheWrite";
3048
- if (/^\s*(?:输入|input)/iu.test(label)) return "input";
3049
- if (/^\s*(?:输出|output)/iu.test(label)) return "output";
3050
- return void 0;
3051
- }
3052
- function unitOf(label) {
3053
- if (/百万\s*token|1m\s*tokens?/iu.test(label)) return "per_1m_tokens";
3054
- if (/千\s*token|1k\s*tokens?/iu.test(label)) return "per_1k_tokens";
3055
- 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;
3056
3293
  }
3057
- function currencyOf(value) {
3058
- if (value.includes("$")) return "USD";
3059
- return null;
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()}`;
3060
3300
  }
3061
- function priceOf(value) {
3062
- const text2 = value.replace(/[$\u20ac\u00a3\u00a5\u00a4,\s]/gu, "");
3063
- if (text2 === "" || /^[–—−\-]+$/u.test(text2)) return null;
3064
- const parsed = Number(text2);
3065
- 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;
3066
3304
  }
3067
- var MODEL_ID2 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
3068
- var SLUG = /^[a-z0-9][a-z0-9-]{0,127}$/u;
3069
- function slugOf(href) {
3070
- const match = /\/models\/([A-Za-z0-9._-]+)\/?(?:#.*)?$/u.exec(href);
3071
- if (!match) return null;
3072
- const slug = match[1];
3073
- 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;
3074
3311
  }
3075
- function trimPanelBody(body) {
3076
- const anchor = /<a\b[^>]*class="[^"]*\bmodel-explorer-detail-link\b[^"]*"[^>]*>/u.exec(body);
3077
- if (!anchor) return body;
3078
- const close = body.indexOf("</a>", anchor.index + anchor[0].length);
3079
- if (close < 0) return body.slice(0, anchor.index);
3080
- return body.slice(0, close + 4);
3312
+ function desktopConfigPath(env = process.env, home = osHomedir()) {
3313
+ return join(desktopConfigDir(env, home), "config.json");
3081
3314
  }
3082
- function collectPanels(html) {
3083
- const openTag = /<div\b[^>]*class="[^"]*\bmodel-explorer-panel\b[^"]*"[^>]*>/gu;
3084
- const opens = [];
3085
- for (const match of html.matchAll(openTag)) {
3086
- const id = /data-model-panel="([^"]*)"/u.exec(match[0])?.[1];
3087
- if (!id || !MODEL_ID2.test(id)) continue;
3088
- 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" };
3089
3321
  }
3090
- const panels = [];
3091
- for (let index = 0; index < opens.length; index += 1) {
3092
- const open = opens[index];
3093
- const next = opens[index + 1];
3094
- const body = html.slice(open.end, next ? next.start : html.length);
3095
- panels.push({ id: open.id, body: trimPanelBody(body) });
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" };
3096
3338
  }
3097
- return panels;
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 };
3098
3351
  }
3099
- function collectProviders(html) {
3100
- const providers = /* @__PURE__ */ new Map();
3101
- for (const match of html.matchAll(/<button\b[^>]*>/gu)) {
3102
- const tag = match[0];
3103
- const id = /data-model-tab="([^"]*)"/u.exec(tag)?.[1];
3104
- const provider = /data-provider="([^"]*)"/u.exec(tag)?.[1];
3105
- if (!id || !provider) continue;
3106
- providers.set(id, provider.trim());
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" };
3107
3363
  }
3108
- return providers;
3364
+ return parseDesktopConfigText(text2, profile);
3109
3365
  }
3110
- function collectTiers(body) {
3111
- const marker = /<div\b[^>]*class="[^"]*\bmodel-explorer-tier\b[^"]*"[^>]*>/gu;
3112
- const starts = [];
3113
- for (const match of body.matchAll(marker)) starts.push(match.index);
3114
- const tiers = [];
3115
- for (let index = 0; index < starts.length; index += 1) {
3116
- const start = starts[index];
3117
- const end = index + 1 < starts.length ? starts[index + 1] : body.length;
3118
- const chunk = body.slice(start, end);
3119
- const label = stripTags(/<h4[^>]*>([\s\S]*?)<\/h4>/u.exec(chunk)?.[1] ?? "");
3120
- const metrics = /* @__PURE__ */ new Map();
3121
- for (const metric of chunk.matchAll(/<dt[^>]*>([\s\S]*?)<\/dt>\s*<dd([^>]*)>([\s\S]*?)<\/dd>/gu)) {
3122
- const labelText = stripTags(metric[1] ?? "");
3123
- const key = metricOf(labelText);
3124
- if (!key) continue;
3125
- const value = stripTags(metric[3] ?? "");
3126
- metrics.set(key, { price: priceOf(value), currency: currencyOf(value), unit: unitOf(labelText) });
3127
- }
3128
- 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;
3129
3374
  }
3130
- return tiers;
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
+ "&quot;": '"',
3981
+ "&amp;": "&",
3982
+ "&lt;": "<",
3983
+ "&gt;": ">",
3984
+ "&apos;": "'",
3985
+ "&nbsp;": " ",
3986
+ "&mdash;": "\u2014",
3987
+ "&ndash;": "\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;
3131
4084
  }
3132
4085
  function hasCatalogMarker(html) {
3133
4086
  return /data-page-name="corouter_models"/u.test(html);
@@ -3292,215 +4245,11 @@ async function fetchPricingSnapshot(options = {}) {
3292
4245
  } catch (error) {
3293
4246
  const failure = deadline.aborted && !options.signal?.aborted ? new PricingError("timeout") : classify2(error, options.signal, deadline);
3294
4247
  const issue = { code: failure.kind, message: failure.message, url: catalogUrl };
3295
- if (failure.status !== void 0) issue.status = failure.status;
3296
- return { status: "failed", source, fetchedAt: now().toISOString(), currency: null, unit: null, models: [], issues: [issue] };
3297
- } finally {
3298
- deadline.removeEventListener("abort", onAbort);
3299
- }
3300
- }
3301
-
3302
- // src/auth.ts
3303
- import { readFile as fsReadFile } from "node:fs/promises";
3304
- import { homedir as osHomedir } from "node:os";
3305
- import { join } from "node:path";
3306
- var DEFAULT_API_URL = "https://amr-api.open-design.ai";
3307
- var API_HOST = "amr-api.open-design.ai";
3308
- var DESKTOP_PROFILES = ["prod", "test", "feature-test", "local"];
3309
- var DEFAULT_PROFILE = "prod";
3310
- var COOKIE_ENV_REFS = ["OPEN_DESIGN_COOKIE", "OPEN_DESIGN_SESSION"];
3311
- function isOfficialApiUrl(raw) {
3312
- let url;
3313
- try {
3314
- url = new URL(raw);
3315
- } catch {
3316
- return false;
3317
- }
3318
- if (url.protocol !== "https:") return false;
3319
- if (url.username || url.password) return false;
3320
- if (url.search || url.hash) return false;
3321
- if (url.pathname !== "/" && url.pathname !== "") return false;
3322
- return url.hostname.toLowerCase() === API_HOST && !url.port;
3323
- }
3324
- function normalizeApiUrl(raw) {
3325
- const value = typeof raw === "string" ? raw.trim() : "";
3326
- if (!value) return void 0;
3327
- if (!isOfficialApiUrl(value)) return void 0;
3328
- const url = new URL(value);
3329
- return `https://${url.hostname.toLowerCase()}`;
3330
- }
3331
- function resolveProfile(env = process.env) {
3332
- const raw = (env.OPEN_DESIGN_AMR_PROFILE ?? env.VELA_PROFILE ?? "").trim();
3333
- return DESKTOP_PROFILES.includes(raw) ? raw : DEFAULT_PROFILE;
3334
- }
3335
- function desktopConfigDir(env = process.env, home = osHomedir()) {
3336
- const raw = (env.AMR_HOME ?? "").trim();
3337
- if (!raw) return join(home, ".amr");
3338
- if (raw === "~") return home;
3339
- if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(home, raw.slice(2));
3340
- return raw;
3341
- }
3342
- function desktopConfigPath(env = process.env, home = osHomedir()) {
3343
- return join(desktopConfigDir(env, home), "config.json");
3344
- }
3345
- function parseDesktopConfigText(text2, profile = DEFAULT_PROFILE) {
3346
- let parsed;
3347
- try {
3348
- parsed = JSON.parse(text2);
3349
- } catch {
3350
- return { state: "invalid" };
3351
- }
3352
- if (!record(parsed)) return { state: "invalid" };
3353
- const profiles = parsed["profiles"];
3354
- if (!record(profiles)) return { state: "invalid" };
3355
- const entry = profiles[profile];
3356
- if (entry === void 0) return { state: "incomplete", profile };
3357
- if (!record(entry)) return { state: "invalid" };
3358
- const controlKey = typeof entry["controlKey"] === "string" ? entry["controlKey"].trim() : "";
3359
- const runtimeKey = typeof entry["runtimeKey"] === "string" ? entry["runtimeKey"].trim() : "";
3360
- const rawApiUrl = typeof entry["apiUrl"] === "string" ? entry["apiUrl"].trim() : "";
3361
- const user = record(entry["user"]) ? entry["user"] : void 0;
3362
- const plan = typeof user?.["plan"] === "string" ? user["plan"].trim() : "";
3363
- if (!controlKey) return { state: "incomplete", profile };
3364
- try {
3365
- safeSecret(controlKey);
3366
- } catch {
3367
- return { state: "invalid" };
3368
- }
3369
- const apiUrl = normalizeApiUrl(rawApiUrl);
3370
- if (rawApiUrl && !apiUrl) return { state: "unsafe-api-url", profile };
3371
- if (profile !== DEFAULT_PROFILE) return { state: "unsupported-profile", profile };
3372
- return {
3373
- state: "credential",
3374
- credential: {
3375
- profile,
3376
- controlKey,
3377
- ...apiUrl === void 0 ? {} : { apiUrl },
3378
- ...plan ? { plan } : {},
3379
- signedIn: runtimeKey.length > 0
3380
- }
3381
- };
3382
- }
3383
- async function readDesktopCredential(deps = {}) {
3384
- const env = deps.env ?? process.env;
3385
- const profile = deps.profile ?? resolveProfile(env);
3386
- const path = desktopConfigPath(env, deps.home ?? osHomedir());
3387
- const readFile = deps.readFile ?? ((file) => fsReadFile(file, "utf8"));
3388
- let text2;
3389
- try {
3390
- text2 = await readFile(path);
3391
- } catch (error) {
3392
- const code = record(error) && typeof error["code"] === "string" ? error["code"] : "";
3393
- return code === "ENOENT" || code === "ENOTDIR" ? { state: "missing" } : { state: "unreadable" };
3394
- }
3395
- return parseDesktopConfigText(text2, profile);
3396
- }
3397
- function deviceGrant(value) {
3398
- if (!record(value) || value.kind !== "device" || typeof value.controlKey !== "string" || typeof value.runtimeKey !== "string") return;
3399
- try {
3400
- const controlKey = safeSecret(value.controlKey), runtimeKey = safeSecret(value.runtimeKey);
3401
- if ([controlKey, runtimeKey].some((key) => key.length > 8192 || /\s/u.test(key))) return;
3402
- return { kind: "device", controlKey, runtimeKey, ...typeof value.savedAt === "string" ? { savedAt: value.savedAt } : {} };
3403
- } catch {
3404
- return void 0;
3405
- }
3406
- }
3407
- function isOfficialRuntimeUrl(raw) {
3408
- try {
3409
- const url = new URL(raw);
3410
- return url.origin === "https://amr-link.open-design.ai" && !url.username && !url.password && !url.search && !url.hash;
3411
- } catch {
3412
- return false;
3413
- }
3414
- }
3415
- function cookieHeader(raw) {
3416
- const value = raw.trim();
3417
- if (!value || !value.includes("=")) return void 0;
3418
- try {
3419
- return safeSecret(value);
3420
- } catch {
3421
- return void 0;
3422
- }
3423
- }
3424
- function desktopSession(credential, apiUrl = credential.apiUrl ?? DEFAULT_API_URL) {
3425
- const base = normalizeApiUrl(apiUrl) ?? DEFAULT_API_URL;
3426
- return {
3427
- headers: { authorization: `Bearer ${safeSecret(credential.controlKey)}` },
3428
- source: "desktop",
3429
- via: "desktop",
3430
- apiUrl: base,
3431
- profile: credential.profile,
3432
- ...credential.plan ? { plan: credential.plan } : {}
3433
- };
3434
- }
3435
- function deviceSession(tokens) {
3436
- const controlKey = typeof tokens === "string" ? tokens : tokens.controlKey;
3437
- return { headers: { authorization: `Bearer ${safeSecret(controlKey)}` }, source: "login", via: "login", apiUrl: DEFAULT_API_URL, credentialType: "device" };
3438
- }
3439
- function cookieSession(cookie, source, apiUrl = DEFAULT_API_URL) {
3440
- const header = cookieHeader(cookie);
3441
- if (!header) return void 0;
3442
- return {
3443
- headers: { cookie: header },
3444
- source,
3445
- via: source === "environment" ? "environment" : "login",
3446
- apiUrl: normalizeApiUrl(apiUrl) ?? DEFAULT_API_URL
3447
- };
3448
- }
3449
- async function resolveSession(deps = {}) {
3450
- const env = deps.env ?? process.env;
3451
- const warnings = [];
3452
- const now = deps.now ?? Date.now;
3453
- if (deps.useDesktop !== false) {
3454
- const desktop = await readDesktopCredential(deps);
3455
- if (desktop.state === "credential") {
3456
- const envApiUrl = (env.VELA_API_URL ?? "").trim();
3457
- if (envApiUrl && !normalizeApiUrl(envApiUrl)) {
3458
- warnings.push("unsafe-api-url");
3459
- } else {
3460
- return { state: "ready", session: desktopSession(desktop.credential, envApiUrl || DEFAULT_API_URL), warnings };
3461
- }
3462
- } else if (desktop.state === "unsafe-api-url") {
3463
- warnings.push("unsafe-api-url");
3464
- } else if (desktop.state === "unsupported-profile") {
3465
- warnings.push("unsupported-profile");
3466
- } else if (desktop.state === "incomplete") {
3467
- warnings.push("desktop-incomplete");
3468
- } else if (desktop.state === "unreadable" || desktop.state === "invalid") {
3469
- warnings.push("desktop-unreadable");
3470
- }
3471
- }
3472
- if (deps.readGrant) {
3473
- let grant;
3474
- try {
3475
- grant = await deps.readGrant();
3476
- } catch {
3477
- grant = void 0;
3478
- }
3479
- if (grant && "kind" in grant && grant.kind === "device") {
3480
- const device = deviceGrant(grant);
3481
- if (device) return { state: "ready", session: deviceSession(device), warnings };
3482
- } else if (grant && "cookie" in grant) {
3483
- const expiry = typeof grant.expiresAt === "number" && Number.isFinite(grant.expiresAt) ? grant.expiresAt : 0;
3484
- if (expiry === 0 || expiry > now()) {
3485
- const session = cookieSession(grant.cookie, "login");
3486
- if (session) return { state: "ready", session, warnings };
3487
- }
3488
- }
3489
- }
3490
- if (deps.resolveRef) {
3491
- for (const ref of COOKIE_ENV_REFS) {
3492
- let value;
3493
- try {
3494
- value = await deps.resolveRef(ref);
3495
- } catch {
3496
- value = void 0;
3497
- }
3498
- if (!value) continue;
3499
- const session = cookieSession(value, "environment");
3500
- if (session) return { state: "ready", session, warnings };
3501
- }
4248
+ if (failure.status !== void 0) issue.status = failure.status;
4249
+ return { status: "failed", source, fetchedAt: now().toISOString(), currency: null, unit: null, models: [], issues: [issue] };
4250
+ } finally {
4251
+ deadline.removeEventListener("abort", onAbort);
3502
4252
  }
3503
- return { state: "need-login", reason: warnings[0] ?? "no-credential", warnings };
3504
4253
  }
3505
4254
 
3506
4255
  // src/login.ts
@@ -3508,7 +4257,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
3508
4257
 
3509
4258
  // src/device-auth.ts
3510
4259
  var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
3511
- var DEVICE_AUTH_PLUGIN_VERSION = "0.1.18";
4260
+ var DEVICE_AUTH_PLUGIN_VERSION = "0.2.0";
3512
4261
  var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
3513
4262
  var DEVICE_RESPONSE_MAX_BYTES = 65536;
3514
4263
  var DEVICE_POLL_MIN_MS = 1e3;
@@ -4166,216 +4915,6 @@ async function defaultLaunch() {
4166
4915
  return playwright.chromium.launch(chromeLaunchOptions());
4167
4916
  }
4168
4917
 
4169
- // src/quota.ts
4170
- import { attributionHeaders as attributionHeaders3 } from "@deepseek-ai/dsh-llm";
4171
- var API_BASE = "https://amr-api.open-design.ai/api/v1";
4172
- var CURRENT_URL = `${API_BASE}/workspaces/current`;
4173
- var SUMMARY_URL = `${API_BASE}/billing/summary`;
4174
- var usageUrl = (workspace) => `${API_BASE}/workspaces/${encodeURIComponent(workspace)}/billing/coding-plan-usage`;
4175
- var preflightUrl = (workspace) => `${API_BASE}/workspaces/${encodeURIComponent(workspace)}/billing/preflight`;
4176
- var ConsoleError = class extends Error {
4177
- constructor(kind, status) {
4178
- 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");
4179
- this.kind = kind;
4180
- this.status = status;
4181
- }
4182
- kind;
4183
- status;
4184
- };
4185
- async function consoleJson(url, session, signal, fetcher = fetch) {
4186
- signal?.throwIfAborted();
4187
- if (session.credentialType === "device") {
4188
- let target;
4189
- try {
4190
- target = new URL(url);
4191
- } catch {
4192
- throw new ConsoleError("response");
4193
- }
4194
- if (target.origin !== "https://amr-api.open-design.ai" || target.username || target.password) throw new ConsoleError("response");
4195
- }
4196
- const requestSignal = combinedSignal(signal, 2e4);
4197
- let rejectAbort = () => void 0;
4198
- const aborted = new Promise((_resolve, reject) => {
4199
- rejectAbort = reject;
4200
- });
4201
- const onAbort = () => rejectAbort(new ConsoleError("network"));
4202
- requestSignal.addEventListener("abort", onAbort, { once: true });
4203
- const read = async () => {
4204
- const response = await fetcher(url, { headers: { ...attributionHeaders3(), accept: "application/json", ...session.headers }, signal: requestSignal, redirect: "error", credentials: "omit" });
4205
- const cancelBody = () => {
4206
- void response.body?.cancel().catch(() => void 0);
4207
- };
4208
- if (requestSignal.aborted) {
4209
- cancelBody();
4210
- throw new ConsoleError("network");
4211
- }
4212
- if (response.redirected || response.url && response.url !== url) {
4213
- cancelBody();
4214
- throw new ConsoleError("response");
4215
- }
4216
- if (response.status === 401 || response.status === 403) {
4217
- cancelBody();
4218
- throw new ConsoleError(response.status === 401 ? "auth" : "permission", response.status);
4219
- }
4220
- if (!response.ok) {
4221
- cancelBody();
4222
- throw new ConsoleError(response.status === 429 ? "rate-limit" : "network", response.status);
4223
- }
4224
- const declared = response.headers.get("content-length");
4225
- if (declared !== null && (!/^\d+$/u.test(declared) || Number(declared) > 2 * 1024 * 1024)) {
4226
- cancelBody();
4227
- throw new ConsoleError("response");
4228
- }
4229
- const reader = response.body?.getReader();
4230
- if (!reader) throw new ConsoleError("response");
4231
- const cancelReader = () => {
4232
- void reader.cancel().catch(() => void 0);
4233
- };
4234
- requestSignal.addEventListener("abort", cancelReader, { once: true });
4235
- let size = 0, raw = "";
4236
- const decoder = new TextDecoder("utf-8", { fatal: true });
4237
- try {
4238
- while (true) {
4239
- const chunk = await reader.read();
4240
- if (requestSignal.aborted) throw new ConsoleError("network");
4241
- if (chunk.done) break;
4242
- size += chunk.value.byteLength;
4243
- if (size > 2 * 1024 * 1024) throw new ConsoleError("response");
4244
- raw += decoder.decode(chunk.value, { stream: true });
4245
- }
4246
- raw += decoder.decode();
4247
- } finally {
4248
- requestSignal.removeEventListener("abort", cancelReader);
4249
- cancelReader();
4250
- reader.releaseLock();
4251
- }
4252
- let body;
4253
- try {
4254
- body = JSON.parse(raw);
4255
- } catch {
4256
- throw new ConsoleError("response");
4257
- }
4258
- if (record(body) && (body.code === 401 || body.code === "401")) throw new ConsoleError("auth", 401);
4259
- if (record(body) && (body.code === 403 || body.code === "403")) throw new ConsoleError("permission", 403);
4260
- return body;
4261
- };
4262
- try {
4263
- return await Promise.race([read(), aborted]);
4264
- } catch (error) {
4265
- signal?.throwIfAborted();
4266
- throw error instanceof ConsoleError ? error : new ConsoleError("network");
4267
- } finally {
4268
- requestSignal.removeEventListener("abort", onAbort);
4269
- }
4270
- }
4271
- function number(value, negative = false) {
4272
- const n = typeof value === "number" ? value : typeof value === "string" && /^-?\d+(\.\d+)?$/u.test(value.trim()) ? Number(value) : NaN;
4273
- return Number.isFinite(n) && (negative || n >= 0) ? n : void 0;
4274
- }
4275
- function iso(value) {
4276
- return typeof value === "string" && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : void 0;
4277
- }
4278
- function normalizeQuota(body, summary) {
4279
- if (!record(body) || !(typeof body.eligible === "boolean" || typeof body.tier === "string" || body.tier === null || Array.isArray(body.windows))) throw new ConsoleError("response");
4280
- const windows = [];
4281
- for (const row of Array.isArray(body.windows) ? body.windows : []) {
4282
- if (!record(row)) continue;
4283
- const seconds = number(row.durationSeconds), used = number(row.usedCredits), limit = number(row.limitCredits), remaining = number(row.remainingCredits);
4284
- if (seconds === void 0 || seconds <= 0 || used === void 0 || limit === void 0 || limit <= 0) continue;
4285
- const resetsAt = iso(row.resetsAt), windowStart = iso(row.windowStart);
4286
- const resetMode = typeof row.resetMode === "string" && row.resetMode.trim() ? row.resetMode.trim() : void 0;
4287
- 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 } });
4288
- }
4289
- const membershipTier = record(summary) && typeof summary.membershipTier === "string" ? summary.membershipTier.trim() : "";
4290
- const tier = typeof body.tier === "string" ? body.tier.trim() : body.tier === void 0 && body.eligible !== false ? membershipTier : "";
4291
- const eligible = typeof body.eligible === "boolean" ? body.eligible : body.tier === null ? false : void 0;
4292
- return { windows, balances: normalizeBalances(summary), ...normalizeSubscription(summary), ...tier ? { tier } : {}, ...eligible === void 0 ? {} : { eligible } };
4293
- }
4294
- function normalizeSubscription(summary) {
4295
- if (!record(summary)) return {};
4296
- const start = iso(summary.subscriptionCurrentPeriodStart), end = iso(summary.subscriptionCurrentPeriodEnd);
4297
- return { ...start === void 0 ? {} : { subscriptionPeriodStart: start }, ...end === void 0 ? {} : { subscriptionPeriodEnd: end } };
4298
- }
4299
- function normalizeBalances(summary) {
4300
- if (!record(summary)) return {};
4301
- const perUsd = number(summary.creditsPerUsd), balances = record(summary.balances) ? summary.balances : {};
4302
- const subscription = number(balances.subscriptionCredits), recharge = number(balances.rechargeCredits), total = number(balances.totalAvailableCredits, true);
4303
- const divisor = perUsd !== void 0 && perUsd > 0 ? perUsd : void 0;
4304
- const totalUsd = number(summary.balanceUsd, true) ?? number(summary.totalAvailableCreditsUsd, true) ?? (divisor !== void 0 && total !== void 0 ? total / divisor : void 0);
4305
- return { ...divisor !== void 0 && subscription !== void 0 ? { subscriptionUsd: subscription / divisor } : {}, ...divisor !== void 0 && recharge !== void 0 ? { rechargeUsd: recharge / divisor } : {}, ...totalUsd !== void 0 ? { totalUsd } : {} };
4306
- }
4307
- async function readDeviceQuota(session, signal, fetcher = fetch) {
4308
- const common = { source: session.source, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
4309
- let current;
4310
- try {
4311
- current = await consoleJson(CURRENT_URL, session, signal, fetcher);
4312
- } catch (error) {
4313
- signal?.throwIfAborted();
4314
- 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" };
4315
- throw error;
4316
- }
4317
- if (!record(current)) throw new ConsoleError("response");
4318
- const workspaceId = typeof current.activeWorkspaceId === "string" && current.activeWorkspaceId.trim() ? current.activeWorkspaceId : current.workspaceId;
4319
- if (typeof workspaceId !== "string" || !/^[A-Za-z0-9_-]{1,64}$/u.test(workspaceId)) throw new ConsoleError("response");
4320
- const personal = current.workspaceType === "personal";
4321
- const [preflight, billing] = await Promise.allSettled([
4322
- consoleJson(preflightUrl(workspaceId), session, signal, fetcher),
4323
- personal ? consoleJson(SUMMARY_URL, session, signal, fetcher) : Promise.resolve(void 0)
4324
- ]);
4325
- signal?.throwIfAborted();
4326
- for (const item of [preflight, billing]) if (item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "auth") throw item.reason;
4327
- const summary = billing.status === "fulfilled" ? billing.value : void 0;
4328
- const flight = preflight.status === "fulfilled" && record(preflight.value) ? preflight.value : void 0;
4329
- let normalized;
4330
- try {
4331
- normalized = normalizeQuota(flight?.codingPlan, personal ? summary : void 0);
4332
- } catch (error) {
4333
- if (!(error instanceof ConsoleError)) throw error;
4334
- }
4335
- const balances = personal ? normalizeBalances(summary) : {};
4336
- const total = personal ? number(flight?.balanceUsd, true) : void 0;
4337
- if (total !== void 0) balances.totalUsd = total;
4338
- const permission = [preflight, billing].some((item) => item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "permission");
4339
- if (!normalized && !Object.keys(balances).length && !permission) {
4340
- if (preflight.status === "rejected") throw preflight.reason;
4341
- throw new ConsoleError("response");
4342
- }
4343
- const windows = normalized?.windows ?? [];
4344
- const missingWindows = normalized?.eligible !== false && !windows.length;
4345
- const missingBalances = personal && Object.keys(balances).length < 3;
4346
- const partial = missingWindows || missingBalances || !personal || permission;
4347
- 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;
4348
- return { ...common, ...normalized, ...normalizeSubscription(personal ? summary : void 0), windows, balances, state: partial ? "partial" : "ok", ...note ? { note } : {} };
4349
- }
4350
- async function readQuota(session, signal, fetcher = fetch) {
4351
- if (session.credentialType === "device") return readDeviceQuota(session, signal, fetcher);
4352
- const current = await consoleJson(CURRENT_URL, session, signal, fetcher);
4353
- if (!record(current) || typeof current.workspaceId !== "string" || !/^[A-Za-z0-9_-]{1,64}$/u.test(current.workspaceId)) throw new ConsoleError("response");
4354
- const personal = current.workspaceType === "personal";
4355
- const [usage, billing] = await Promise.allSettled([
4356
- consoleJson(usageUrl(current.workspaceId), session, signal, fetcher),
4357
- personal ? consoleJson(SUMMARY_URL, session, signal, fetcher) : Promise.resolve(void 0)
4358
- ]);
4359
- for (const item of [usage, billing]) if (item.status === "rejected" && item.reason instanceof ConsoleError && item.reason.kind === "auth") throw item.reason;
4360
- const summary = billing.status === "fulfilled" ? billing.value : void 0;
4361
- const common = { source: session.source, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
4362
- let normalized;
4363
- try {
4364
- if (usage.status === "rejected") throw usage.reason;
4365
- normalized = normalizeQuota(usage.value, summary);
4366
- } catch (error) {
4367
- const balances = normalizeBalances(summary);
4368
- if (!Object.keys(balances).length) throw error;
4369
- 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" };
4370
- }
4371
- const missingWindows = normalized.eligible !== false && !normalized.windows.length;
4372
- const noSubscription = normalized.eligible === false && !normalized.windows.length;
4373
- const missingBalances = personal && Object.keys(normalized.balances).length < 3;
4374
- const partial = missingWindows || missingBalances || !personal;
4375
- 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;
4376
- return { ...common, ...normalized, state: partial ? "partial" : "ok", ...note === void 0 ? {} : { note } };
4377
- }
4378
-
4379
4918
  // src/desktop-quota.ts
4380
4919
  import { execFile } from "node:child_process";
4381
4920
  import { existsSync } from "node:fs";
@@ -4615,9 +5154,18 @@ function parseStatusModel(value) {
4615
5154
  ...value.inputModalities === void 0 ? {} : { inputModalities: parseModalities(value.inputModalities) },
4616
5155
  ...value.contextWindow === void 0 ? {} : { contextWindow: positiveInteger(value.contextWindow, "\u4E0A\u4E0B\u6587\u9884\u7B97", 1e8) },
4617
5156
  ...value.maxOutputTokens === void 0 ? {} : { maxOutputTokens: positiveInteger(value.maxOutputTokens, "\u6700\u5927\u8F93\u51FA", 1e7) },
4618
- ...value.reasoningEfforts === void 0 ? {} : { reasoningEfforts: parseEfforts(value.reasoningEfforts) }
5157
+ ...value.reasoningEfforts === void 0 ? {} : { reasoningEfforts: parseEfforts(value.reasoningEfforts) },
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") }
4619
5162
  };
4620
5163
  }
5164
+ function parseEffort(value) {
5165
+ const effort = text(value, "\u9ED8\u8BA4\u601D\u8003\u6863\u4F4D", 32);
5166
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(effort)) throw new Error("\u9ED8\u8BA4\u601D\u8003\u6863\u4F4D\u683C\u5F0F\u65E0\u6548");
5167
+ return effort;
5168
+ }
4621
5169
  function parseStatusConfig(value) {
4622
5170
  if (!record(value)) throw new Error("\u914D\u7F6E\u89C6\u56FE\u5FC5\u987B\u662F\u5BF9\u8C61");
4623
5171
  if (typeof value.apiKeyEnv !== "string" || value.apiKeyEnv.length > MAX_ENV_REF) {
@@ -4631,7 +5179,7 @@ function parseStatusConfig(value) {
4631
5179
  useDesktopCredential: flag(value.useDesktopCredential, "\u684C\u9762\u767B\u5F55\u6001\u5F00\u5173"),
4632
5180
  baseURL: text(value.baseURL, "\u63A8\u7406\u5730\u5740", MAX_BASE_URL),
4633
5181
  apiKeyEnv,
4634
- ...value.apiProtocol === void 0 ? {} : { apiProtocol: member(value.apiProtocol, API_PROTOCOL_IDS, "\u63A8\u7406\u534F\u8BAE") },
5182
+ ...value.apiProtocol === void 0 ? {} : { apiProtocol: member(value.apiProtocol, API_PROTOCOL_SELECTION_IDS, "\u63A8\u7406\u534F\u8BAE") },
4635
5183
  ...value.modelSettings === void 0 ? {} : { modelSettings: parseModelSettingsMap(value.modelSettings) },
4636
5184
  ...value.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: positiveInteger(value.requestTimeoutMs, "\u8BF7\u6C42\u8D85\u65F6", 36e5, 1e3) },
4637
5185
  ...value.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: positiveInteger(value.streamIdleTimeoutMs, "\u6D41\u7A7A\u95F2\u8D85\u65F6", 18e5, 1e3) },
@@ -4652,7 +5200,7 @@ function parseStatus(value) {
4652
5200
  ids.add(model.id);
4653
5201
  }
4654
5202
  const apiKeyConfigured = flag(value.apiKeyConfigured, "\u51ED\u636E\u662F\u5426\u5C31\u7EEA");
4655
- 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");
4656
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");
4657
5205
  return {
4658
5206
  revision: text(value.revision, "\u914D\u7F6E\u7248\u672C", MAX_REVISION),
@@ -4667,7 +5215,17 @@ function parseStatus(value) {
4667
5215
  models: parsed,
4668
5216
  ...value.modelsSource === void 0 ? {} : { modelsSource: member(value.modelsSource, ["builtin", "openai"], "\u6A21\u578B\u76EE\u5F55\u6765\u6E90") },
4669
5217
  ...value.modelsUpdatedAt === void 0 ? {} : { modelsUpdatedAt: isoTime(value.modelsUpdatedAt, "\u6A21\u578B\u66F4\u65B0\u65F6\u95F4") },
4670
- ...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") }
4671
5229
  };
4672
5230
  }
4673
5231
  function parseTurnMonitor(value) {
@@ -4710,7 +5268,7 @@ var API_KEY = credentialKey2(name, "api-key");
4710
5268
  var SESSION = credentialKey2(name, "console");
4711
5269
  var SETTINGS_CONFLICT = "SETTINGS_CONFLICT";
4712
5270
  var NATIVE_AUTH = { env: [], oauth: true };
4713
- var hash = (value) => createHash2("sha256").update(JSON.stringify(value) ?? "").digest("hex");
5271
+ var hash = (value) => createHash4("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4714
5272
  var stableConfig = (config) => {
4715
5273
  const { modelCatalog: _snapshot, ...rest } = config;
4716
5274
  return rest;
@@ -4744,19 +5302,27 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4744
5302
  __publicField(this, "_quotaController");
4745
5303
  __publicField(this, "guardedTurns", 0);
4746
5304
  __publicField(this, "turnMonitorStatus");
4747
- __publicField(this, "_models", MODELS);
4748
- __publicField(this, "_modelsUpdatedAt");
4749
- __publicField(this, "_modelsError");
5305
+ __publicField(this, "_directory");
5306
+ __publicField(this, "_catalogKeys");
4750
5307
  __publicField(this, "_modelsFingerprint", "");
4751
- __publicField(this, "_modelsEpoch", 0);
4752
- __publicField(this, "_modelsPending");
4753
- __publicField(this, "_modelsController");
4754
- __publicField(this, "_modelsWriteSerial", 0);
4755
- __publicField(this, "_modelsWrite", Promise.resolve());
4756
5308
  __publicField(this, "_prices");
4757
5309
  __publicField(this, "_pricesPending");
4758
5310
  this._config = config;
4759
- this._restoreModels();
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
+ });
4760
5326
  this._login = new ConsoleLogin({
4761
5327
  capture: async (expectedRevision) => {
4762
5328
  const state = await this._state();
@@ -4791,13 +5357,27 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4791
5357
  this._activation = new ActivationLauncher(dependencies.activationOptions);
4792
5358
  ctx.effect(() => () => {
4793
5359
  this._lifetime.abort();
5360
+ this._directory.dispose();
5361
+ this._catalogKeys.dispose();
4794
5362
  this._login.dispose();
4795
5363
  return this._activation.dispose();
4796
5364
  });
4797
5365
  }
4798
5366
  dependencies;
4799
5367
  modelCatalog() {
4800
- return this._models;
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();
4801
5381
  }
4802
5382
  _credentials() {
4803
5383
  const service = this.ctx.get("credentials");
@@ -4810,21 +5390,17 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4810
5390
  if (ambient?.trim()) return { key: ambient, source: "reference" };
4811
5391
  if (apiRecord?.kind === "api-key" && apiRecord.key?.trim()) return { key: apiRecord.key, source: "stored" };
4812
5392
  const grant = grantOf(sessionRecord);
4813
- return isOfficialRuntimeUrl(baseURL) && grant && "kind" in grant && grant.kind === "device" ? { key: grant.runtimeKey, source: "device" } : void 0;
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
+ }
4814
5398
  }
4815
5399
  async resolveApiKey(ref, baseURL = this._config().baseURL) {
4816
5400
  const credentials = this.ctx.get("credentials");
4817
5401
  const [apiRecord, sessionRecord] = await Promise.all([credentials?.readRecord(API_KEY), credentials?.readRecord(SESSION)]);
4818
5402
  return (await this._key(ref, baseURL, apiRecord, sessionRecord))?.key;
4819
5403
  }
4820
- /** Restore the persisted gateway catalog when it belongs to the active gateway. */
4821
- _restoreModels() {
4822
- const config = this._config();
4823
- const snapshot = config.modelCatalog;
4824
- if (!snapshot || snapshot.baseURL !== config.baseURL) return;
4825
- this._models = snapshot.models;
4826
- this._modelsUpdatedAt = snapshot.updatedAt;
4827
- }
4828
5404
  /**
4829
5405
  * Persist the snapshot through the Host form service.
4830
5406
  * `unsupported` means no settings service is composed (nothing to report);
@@ -4854,34 +5430,8 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4854
5430
  }
4855
5431
  return "failed";
4856
5432
  }
4857
- /** Serialize snapshot writes so the newest successful refresh is the last one persisted. */
4858
- _queueModelsWrite(snapshot, epoch) {
4859
- const serial = ++this._modelsWriteSerial;
4860
- this._modelsWrite = this._modelsWrite.then(async () => {
4861
- const result = await this._persistModels(snapshot);
4862
- if (serial !== this._modelsWriteSerial || epoch !== this._modelsEpoch) return;
4863
- 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";
4864
- 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";
4865
- }).catch(() => {
4866
- if (serial !== this._modelsWriteSerial || epoch !== this._modelsEpoch) return;
4867
- 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";
4868
- });
4869
- }
4870
5433
  _invalidateModels() {
4871
- const changed = this._modelsUpdatedAt !== void 0;
4872
- this._modelsEpoch++;
4873
- this._modelsController?.abort();
4874
- this._modelsPending = void 0;
4875
- this._models = MODELS;
4876
- this._modelsUpdatedAt = void 0;
4877
- this._modelsError = void 0;
4878
- this._restoreModels();
4879
- if (changed || this._modelsUpdatedAt !== void 0) {
4880
- try {
4881
- this.dependencies.modelsChanged?.();
4882
- } catch {
4883
- }
4884
- }
5434
+ this._directory.invalidate();
4885
5435
  }
4886
5436
  async _state() {
4887
5437
  const credentials = this.ctx.get("credentials"), config = this._config();
@@ -4889,7 +5439,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4889
5439
  const resolved = await this._key(apiKeyRef(config), config.baseURL, apiRecord, sessionRecord);
4890
5440
  const key = resolved?.key;
4891
5441
  const state = { apiRecord, sessionRecord, key, keySource: resolved?.source, config };
4892
- const modelsFingerprint = hash({ key, baseURL: config.baseURL });
5442
+ const modelsFingerprint = hash({ key, baseURL: config.baseURL, session: sessionRecord, desktop: config.useDesktopCredential });
4893
5443
  if (modelsFingerprint !== this._modelsFingerprint) {
4894
5444
  this._modelsFingerprint = modelsFingerprint;
4895
5445
  this._invalidateModels();
@@ -4917,6 +5467,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4917
5467
  }
4918
5468
  async status() {
4919
5469
  const state = await this._state();
5470
+ if (this.dependencies.modelAutoRefresh !== false) this._directory.warm();
4920
5471
  const quotaConfig = hash({ desktop: state.config.useDesktopCredential, session: state.sessionRecord, refreshSeconds: state.config.quotaRefreshSeconds });
4921
5472
  if (this._quotaConfig !== quotaConfig) {
4922
5473
  this._quotaConfig = quotaConfig;
@@ -4932,69 +5483,36 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4932
5483
  config: { ...state.config, apiKeyEnv: state.config.apiKeyEnv ?? "" },
4933
5484
  guardedTurns: this.guardedTurns,
4934
5485
  ...this.turnMonitorStatus ? { turnMonitor: this.turnMonitorStatus() } : {},
4935
- models: this._models.map((row) => {
5486
+ models: this._directory.models().map((row) => {
4936
5487
  const { id, name: name2, group: group2, contextWindow, maxOutputTokens, inputModalities } = row;
4937
- const reasoningEfforts = modelReasoningEfforts(row, state.config.apiProtocol ?? "chat-completions");
5488
+ const protocol = effectiveProtocol(row, state.config.apiProtocol, state.config.modelSettings?.[row.id]?.apiProtocol);
5489
+ const reasoningEfforts = modelReasoningEfforts(row, protocol);
5490
+ const defaultEffort = vendorDefaultEffort(row, protocol);
4938
5491
  return {
4939
5492
  id,
4940
5493
  name: name2,
4941
5494
  group: group2,
4942
5495
  enabled: isModelEnabled(id, state.config.modelSettings),
5496
+ ...row.coverage ? { coverage: row.coverage } : {},
5497
+ ...row.nativeProtocol ? { nativeProtocol: row.nativeProtocol } : {},
5498
+ effectiveProtocol: protocol,
4943
5499
  ...inputModalities === void 0 ? {} : { inputModalities },
4944
5500
  ...contextWindow === void 0 ? {} : { contextWindow },
4945
5501
  ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
4946
- ...reasoningEfforts === void 0 ? {} : { reasoningEfforts }
5502
+ ...reasoningEfforts === void 0 ? {} : { reasoningEfforts },
5503
+ ...defaultEffort === void 0 ? {} : { defaultEffort }
4947
5504
  };
4948
5505
  }),
4949
- modelsSource: this._modelsUpdatedAt ? "openai" : "builtin",
4950
- ...this._modelsUpdatedAt ? { modelsUpdatedAt: this._modelsUpdatedAt } : {},
4951
- ...this._modelsError ? { modelsError: this._modelsError } : {}
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()
4952
5510
  });
4953
5511
  }
4954
5512
  async refreshModels() {
4955
- const state = await this._state();
4956
- if (this._modelsPending) return this._modelsPending;
4957
- const key = state.key;
4958
- if (!key?.trim()) {
4959
- this._modelsError = "\u8BF7\u5148\u914D\u7F6E API Key\uFF0C\u518D\u4ECE\u5F53\u524D\u7F51\u5173\u8BFB\u53D6\u6A21\u578B\u76EE\u5F55\u3002";
4960
- return this.status();
4961
- }
4962
- const epoch = this._modelsEpoch;
4963
- const controller = new AbortController();
4964
- this._modelsController = controller;
4965
- const signal = AbortSignal.any([controller.signal, this._lifetime.signal]);
4966
- const run = (async () => {
4967
- try {
4968
- const models = await (this.dependencies.fetchModels ?? fetchModelCatalog)(state.config.baseURL, key, signal);
4969
- await this._state();
4970
- if (signal.aborted || epoch !== this._modelsEpoch) return this.status();
4971
- const previousModels = this._models;
4972
- const previousUpdatedAt = this._modelsUpdatedAt;
4973
- const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4974
- this._models = models;
4975
- this._modelsUpdatedAt = updatedAt;
4976
- this._modelsError = void 0;
4977
- let accepted = true;
4978
- try {
4979
- this.dependencies.modelsChanged?.();
4980
- } catch {
4981
- accepted = false;
4982
- this._models = previousModels;
4983
- this._modelsUpdatedAt = previousUpdatedAt;
4984
- 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";
4985
- }
4986
- if (accepted) this._queueModelsWrite({ baseURL: state.config.baseURL, updatedAt, models }, epoch);
4987
- } catch (error) {
4988
- 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";
4989
- }
4990
- return this.status();
4991
- })();
4992
- this._modelsPending = run;
4993
- try {
4994
- return await run;
4995
- } finally {
4996
- if (this._modelsPending === run) this._modelsPending = void 0;
4997
- }
5513
+ await this._state();
5514
+ await this._directory.refresh();
5515
+ return this.status();
4998
5516
  }
4999
5517
  async refreshPrices() {
5000
5518
  if (this._pricesPending) return this._pricesPending;
@@ -5183,6 +5701,8 @@ function apply(ctx, config) {
5183
5701
  const adapter = new CoRouterAdapter({
5184
5702
  config: current,
5185
5703
  models: () => service.modelCatalog(),
5704
+ readyModels: () => service.currentModelCatalog(),
5705
+ callIdentity: () => service.modelCallIdentity(),
5186
5706
  apiKey: (ref, baseURL) => service.resolveApiKey(ref, baseURL),
5187
5707
  onEmptyTurn: () => {
5188
5708
  service.guardedTurns++;