dsh-opendesign-corouter 0.1.11 → 0.1.12

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
@@ -49,15 +49,16 @@ var __privateMethod = (obj, member2, method) => (__accessCheck(obj, member2, "ac
49
49
 
50
50
  // src/index.ts
51
51
  import { randomUUID as randomUUID3, createHash } from "node:crypto";
52
- import { credentialKey, credentialRef } from "@deepseek-ai/dsh-credentials";
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";
55
- import { LlmError as LlmError11 } from "@deepseek-ai/dsh-llm";
55
+ import { LlmError as LlmError13 } from "@deepseek-ai/dsh-llm";
56
56
 
57
57
  // src/adapter.ts
58
+ import { createHmac, randomBytes } from "node:crypto";
58
59
  import {
59
60
  LlmAdapter,
60
- LlmError as LlmError10,
61
+ LlmError as LlmError11,
61
62
  ReasoningEffortId,
62
63
  assertUsableApiKey
63
64
  } from "@deepseek-ai/dsh-llm";
@@ -74,7 +75,7 @@ var EFFORTS_GROK = [...EFFORTS_LEVELS, "xhigh"];
74
75
  var EFFORTS_MUSE = ["minimal", ...EFFORTS_REASONING];
75
76
  var MODELS = [
76
77
  // ── OpenAI(8) ─────────────────────────────────────────────
77
- { id: "gpt-6.1-sol", name: "GPT-6.1 Sol", group: "paid", reasoningEfforts: EFFORTS_REASONING },
78
+ { id: "gpt-6.1-sol", name: "GPT-6.1 Sol", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
78
79
  {
79
80
  id: "gpt-6.1-terra",
80
81
  name: "GPT-6.1 Terra",
@@ -84,7 +85,7 @@ var MODELS = [
84
85
  inputModalities: TEXT_AND_IMAGE,
85
86
  reasoningEfforts: EFFORTS_OPENAI
86
87
  },
87
- { id: "gpt-6-astra", name: "GPT-6 Astra", group: "paid", reasoningEfforts: EFFORTS_REASONING },
88
+ { id: "gpt-6-astra", name: "GPT-6 Astra", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
88
89
  {
89
90
  id: "gpt-6-luna",
90
91
  name: "GPT-6 Luna",
@@ -94,18 +95,18 @@ var MODELS = [
94
95
  inputModalities: TEXT_AND_IMAGE,
95
96
  reasoningEfforts: EFFORTS_OPENAI
96
97
  },
97
- { id: "gpt-6-sol", name: "GPT-6 Sol", group: "paid", reasoningEfforts: EFFORTS_OPENAI },
98
- { id: "gpt-5.6-luna", name: "GPT-5.6 Luna", group: "paid", reasoningEfforts: EFFORTS_OPENAI },
99
- { id: "gpt-5.6-sol", name: "GPT-5.6 Sol", group: "paid", reasoningEfforts: EFFORTS_OPENAI },
100
- { id: "gpt-5.6-terra", name: "GPT-5.6 Terra", group: "paid", reasoningEfforts: EFFORTS_OPENAI },
98
+ { id: "gpt-6-sol", name: "GPT-6 Sol", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
99
+ { id: "gpt-5.6-luna", name: "GPT-5.6 Luna", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
100
+ { id: "gpt-5.6-sol", name: "GPT-5.6 Sol", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
101
+ { id: "gpt-5.6-terra", name: "GPT-5.6 Terra", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_OPENAI },
101
102
  // ── Anthropic(8) ──────────────────────────────────────────
102
- { id: "claude-fable-5.1", name: "Claude Fable 5.1", group: "paid", reasoningEfforts: EFFORTS_REASONING },
103
- { id: "claude-fable-5", name: "Claude Fable 5", group: "paid", reasoningEfforts: EFFORTS_REASONING },
104
- { id: "claude-opus-5.5", name: "Claude Opus 5.5", group: "paid", reasoningEfforts: EFFORTS_REASONING },
105
- { id: "claude-opus-5", name: "Claude Opus 5", group: "paid", reasoningEfforts: EFFORTS_REASONING },
106
- { id: "claude-opus-4.8", name: "Claude Opus 4.8", group: "paid", reasoningEfforts: EFFORTS_REASONING },
107
- { id: "claude-sonnet-5.5", name: "Claude Sonnet 5.5", group: "paid", reasoningEfforts: EFFORTS_REASONING },
108
- { id: "claude-sonnet-5", name: "Claude Sonnet 5", group: "paid", reasoningEfforts: EFFORTS_REASONING },
103
+ { id: "claude-fable-5.1", name: "Claude Fable 5.1", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
104
+ { id: "claude-fable-5", name: "Claude Fable 5", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
105
+ { id: "claude-opus-5.5", name: "Claude Opus 5.5", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
106
+ { id: "claude-opus-5", name: "Claude Opus 5", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
107
+ { id: "claude-opus-4.8", name: "Claude Opus 4.8", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
108
+ { id: "claude-sonnet-5.5", name: "Claude Sonnet 5.5", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
109
+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
109
110
  {
110
111
  id: "claude-haiku-5.5",
111
112
  name: "Claude Haiku 5.5",
@@ -131,7 +132,6 @@ var MODELS = [
131
132
  group: "plan",
132
133
  contextWindow: 1e6,
133
134
  maxOutputTokens: 384e3,
134
- inputModalities: TEXT_ONLY,
135
135
  reasoningEfforts: EFFORTS_LOW_HIGH
136
136
  },
137
137
  {
@@ -171,7 +171,7 @@ var MODELS = [
171
171
  inputModalities: TEXT_AND_IMAGE,
172
172
  reasoningEfforts: EFFORTS_LOW_HIGH
173
173
  },
174
- { id: "glm-5.2", name: "GLM-5.2", group: "paid", reasoningEfforts: EFFORTS_GLM52 },
174
+ { id: "glm-5.2", name: "GLM-5.2", group: "paid", inputModalities: TEXT_ONLY, reasoningEfforts: EFFORTS_GLM52 },
175
175
  // ── Moonshot(3) ───────────────────────────────────────────
176
176
  {
177
177
  id: "kimi-k2.7-code",
@@ -182,16 +182,16 @@ var MODELS = [
182
182
  inputModalities: TEXT_AND_IMAGE,
183
183
  reasoningEfforts: []
184
184
  },
185
- { id: "kimi-k3", name: "Kimi K3", group: "paid", reasoningEfforts: EFFORTS_LOW_HIGH },
186
- { id: "kimi-k3.1-pro", name: "Kimi K3.1 Pro", group: "paid", reasoningEfforts: EFFORTS_LOW_HIGH },
185
+ { id: "kimi-k3", name: "Kimi K3", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LOW_HIGH },
186
+ { id: "kimi-k3.1-pro", name: "Kimi K3.1 Pro", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LOW_HIGH },
187
187
  // ── Google(3) ─────────────────────────────────────────────
188
- { id: "gemini-4-argon", name: "Gemini 4 Argon", group: "paid", reasoningEfforts: EFFORTS_LEVELS },
189
- { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", group: "paid", reasoningEfforts: EFFORTS_LEVELS },
190
- { id: "gemini-3.7-flash", name: "Gemini 3.7 Flash", group: "paid", reasoningEfforts: EFFORTS_LEVELS },
188
+ { id: "gemini-4-argon", name: "Gemini 4 Argon", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
189
+ { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
190
+ { id: "gemini-3.7-flash", name: "Gemini 3.7 Flash", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
191
191
  // ── xAI(3) ────────────────────────────────────────────────
192
- { id: "grok-4.7", name: "Grok 4.7", group: "paid", reasoningEfforts: EFFORTS_GROK },
193
- { id: "grok-4.6", name: "Grok 4.6", group: "paid", reasoningEfforts: EFFORTS_GROK },
194
- { id: "grok-4.5", name: "Grok 4.5", group: "paid", reasoningEfforts: EFFORTS_LEVELS },
192
+ { id: "grok-4.7", name: "Grok 4.7", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_GROK },
193
+ { id: "grok-4.6", name: "Grok 4.6", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_GROK },
194
+ { id: "grok-4.5", name: "Grok 4.5", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_LEVELS },
195
195
  // ── Xiaomi(2) ─────────────────────────────────────────────
196
196
  {
197
197
  id: "mimo-v2.6-pro",
@@ -222,10 +222,10 @@ var MODELS = [
222
222
  reasoningEfforts: ["none", "high"]
223
223
  },
224
224
  // ── Alibaba(1) ────────────────────────────────────────────
225
- { id: "qwen3.7-max", name: "Qwen3.7 Max", group: "paid", reasoningEfforts: [] },
225
+ { id: "qwen3.7-max", name: "Qwen3.7 Max", group: "paid", inputModalities: TEXT_ONLY, reasoningEfforts: [] },
226
226
  // Official API additions; display labels for undocumented entries are local formatting.
227
- { id: "minimax-m3.1-flash", name: "MiniMax M3.1 Flash", group: "plan", reasoningEfforts: EFFORTS_REASONING },
228
- { id: "muse-spark-1.3", name: "Muse Spark 1.3", group: "paid", reasoningEfforts: EFFORTS_MUSE },
227
+ { id: "minimax-m3.1-flash", name: "MiniMax M3.1 Flash", group: "plan", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_REASONING },
228
+ { id: "muse-spark-1.3", name: "Muse Spark 1.3", group: "paid", inputModalities: TEXT_AND_IMAGE, reasoningEfforts: EFFORTS_MUSE },
229
229
  { id: "muse-wonder", name: "Muse Wonder", group: "paid" }
230
230
  ];
231
231
  var BY_ID = new Map(MODELS.map((model) => [model.id, model]));
@@ -253,7 +253,7 @@ function parseModelSettingsMap(value) {
253
253
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");
254
254
  const keys = Object.keys(value);
255
255
  if (keys.length > 512) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u6700\u591A\u5141\u8BB8 512 \u4E2A\u6A21\u578B");
256
- const fields = /* @__PURE__ */ new Set(["enabled", "temperature", "topP", "maxTokens", "contextWindow", "reasoningEffort"]);
256
+ const fields = /* @__PURE__ */ new Set(["enabled", "imageInput", "temperature", "topP", "maxTokens", "contextWindow", "reasoningEffort"]);
257
257
  const efforts = ["none", "minimal", "low", "medium", "high", "xhigh", "ultra", "max"];
258
258
  const out = {};
259
259
  for (const id of keys) {
@@ -270,6 +270,10 @@ function parseModelSettingsMap(value) {
270
270
  if (typeof settings.enabled !== "boolean") throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
271
271
  parsed.enabled = settings.enabled;
272
272
  }
273
+ if (settings.imageInput !== void 0) {
274
+ if (typeof settings.imageInput !== "boolean") throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 imageInput \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
275
+ parsed.imageInput = settings.imageInput;
276
+ }
273
277
  for (const [field, max] of [["temperature", 2], ["topP", 1]]) {
274
278
  const item = settings[field];
275
279
  if (item === void 0) continue;
@@ -292,14 +296,16 @@ function parseModelSettingsMap(value) {
292
296
  return out;
293
297
  }
294
298
  function applyModelSettings(row, settings) {
295
- const { contextWindow, maxTokens } = settings ?? {};
296
- if (contextWindow === void 0 && maxTokens === void 0) return { ...row };
299
+ const { contextWindow, maxTokens, imageInput } = settings ?? {};
300
+ if (contextWindow === void 0 && maxTokens === void 0 && imageInput === void 0) return { ...row };
297
301
  if (contextWindow !== void 0) parseModelSettingsMap({ model: { contextWindow } });
298
302
  if (maxTokens !== void 0) parseModelSettingsMap({ model: { maxTokens } });
303
+ if (imageInput !== void 0) parseModelSettingsMap({ model: { imageInput } });
299
304
  return {
300
305
  ...row,
301
306
  ...contextWindow === void 0 ? {} : { contextWindow },
302
- ...maxTokens === void 0 ? {} : { maxOutputTokens: maxTokens }
307
+ ...maxTokens === void 0 ? {} : { maxOutputTokens: maxTokens },
308
+ ...imageInput === void 0 ? {} : { inputModalities: imageInput ? ["text", "image"] : ["text"] }
303
309
  };
304
310
  }
305
311
  function isModelEnabled(id, settings = {}) {
@@ -325,7 +331,7 @@ var Config = Schema.object({
325
331
  apiKeyEnv: Schema.string().max(128).pattern(/^[A-Za-z_][A-Za-z0-9_]*$/u).default("COROUTER_API_KEY").description("CoRouter API Key \u7684\u73AF\u5883\u53D8\u91CF\u6216 DSH \u51ED\u636E\u5F15\u7528\u540D").volatile(),
326
332
  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(),
327
333
  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(),
328
- modelSettings: Schema.transform(Schema.dict(Schema.any()), serializableTransform(parseModelSettingsMap)).default({}).description("\u9010\u6A21\u578B\u542F\u7528\u72B6\u6001\u548C\u8BF7\u6C42\u53C2\u6570").volatile(),
334
+ 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(),
329
335
  useDesktopCredential: Schema.boolean().default(true).description("\u4F18\u5148\u8BFB\u53D6 OpenDesign \u684C\u9762\u7AEF\u767B\u5F55\u6001\u67E5\u8BE2\u989D\u5EA6").volatile(),
330
336
  emptyTurnGuard: Schema.boolean().default(true).description("\u68C0\u6D4B DeepSeek V4.1 Flash \u5DE5\u5177\u5BF9\u8BDD\u7684\u7A7A\u56DE\u7B54\u548C\u5F02\u5E38\u7ED3\u675F\uFF1B\u6301\u7EED\u91CD\u8BD5\u76F4\u5230\u6210\u529F\u6216\u53D6\u6D88\uFF0C\u53EF\u80FD\u8BEF\u5224\u5E76\u989D\u5916\u6D88\u8017\u989D\u5EA6").volatile(),
331
337
  quotaRefreshSeconds: Schema.natural().min(5).max(3600).default(60).description("\u989D\u5EA6\u81EA\u52A8\u5237\u65B0\u95F4\u9694\uFF08\u79D2\uFF09").volatile(),
@@ -361,7 +367,7 @@ function readConfig(config) {
361
367
  }
362
368
 
363
369
  // src/conversion.ts
364
- import { LlmError, textOnlyImageText } from "@deepseek-ai/dsh-llm";
370
+ import { LlmError, offloadedImageText, textOnlyImageText } from "@deepseek-ai/dsh-llm";
365
371
  function parts(blocks, image) {
366
372
  let text2 = "";
367
373
  const images = [];
@@ -373,7 +379,7 @@ function parts(blocks, image) {
373
379
  case "image": {
374
380
  const url = block.offloaded ? void 0 : image?.(block.attachment);
375
381
  if (url) images.push(url);
376
- else text2 += `${text2 ? "\n" : ""}${textOnlyImageText(block.attachment)}`;
382
+ else text2 += `${text2 ? "\n" : ""}${block.offloaded ? offloadedImageText(block.attachment) : textOnlyImageText(block.attachment)}`;
377
383
  break;
378
384
  }
379
385
  case "file":
@@ -983,7 +989,7 @@ var EmptyTurnTracker = class {
983
989
  };
984
990
 
985
991
  // src/protocols/index.ts
986
- import { LlmError as LlmError9 } from "@deepseek-ai/dsh-llm";
992
+ import { LlmError as LlmError10 } from "@deepseek-ai/dsh-llm";
987
993
 
988
994
  // src/protocols/chat-completions.ts
989
995
  import { LlmError as LlmError5 } from "@deepseek-ai/dsh-llm";
@@ -1044,12 +1050,12 @@ var chatCompletions = {
1044
1050
 
1045
1051
  // src/protocols/messages.ts
1046
1052
  import {
1047
- LlmError as LlmError7,
1053
+ LlmError as LlmError8,
1048
1054
  ToolCallId as ToolCallId2
1049
1055
  } from "@deepseek-ai/dsh-llm";
1050
1056
 
1051
1057
  // src/protocols/parts.ts
1052
- import { LlmError as LlmError6, textOnlyImageText as textOnlyImageText2 } from "@deepseek-ai/dsh-llm";
1058
+ import { LlmError as LlmError6, offloadedImageText as offloadedImageText2, textOnlyImageText as textOnlyImageText2 } from "@deepseek-ai/dsh-llm";
1053
1059
  function projectContent(blocks, image) {
1054
1060
  let text2 = "";
1055
1061
  const images = [];
@@ -1061,7 +1067,7 @@ function projectContent(blocks, image) {
1061
1067
  case "image": {
1062
1068
  const url = block.offloaded ? void 0 : image?.(block.attachment);
1063
1069
  if (url) images.push(url);
1064
- else text2 += `${text2 ? "\n" : ""}${textOnlyImageText2(block.attachment)}`;
1070
+ else text2 += `${text2 ? "\n" : ""}${block.offloaded ? offloadedImageText2(block.attachment) : textOnlyImageText2(block.attachment)}`;
1065
1071
  break;
1066
1072
  }
1067
1073
  case "file":
@@ -1111,10 +1117,83 @@ function anthropicUsage(raw) {
1111
1117
  };
1112
1118
  }
1113
1119
 
1120
+ // src/claude-parameters.ts
1121
+ import { LlmError as LlmError7 } from "@deepseek-ai/dsh-llm";
1122
+
1123
+ // src/claude-capabilities.ts
1124
+ var RESTRICTED_MESSAGES_SAMPLING = /* @__PURE__ */ new Set([
1125
+ "claude-fable-5.1",
1126
+ "claude-fable-5",
1127
+ "claude-opus-5.5",
1128
+ "claude-opus-5",
1129
+ "claude-opus-4.8",
1130
+ "claude-sonnet-5.5",
1131
+ "claude-sonnet-5",
1132
+ "claude-haiku-5.5"
1133
+ ]);
1134
+ function hasRestrictedClaudeSampling(model, protocol) {
1135
+ return protocol === "messages" && RESTRICTED_MESSAGES_SAMPLING.has(model);
1136
+ }
1137
+ function claudeSamplingError(model, protocol, temperature, topP) {
1138
+ if (!hasRestrictedClaudeSampling(model, protocol)) return void 0;
1139
+ if (temperature !== void 0 && topP !== void 0) return "\u6B64 Claude \u6A21\u578B\u7684 Messages \u8BF7\u6C42\u4E0D\u80FD\u540C\u65F6\u8BBE\u7F6E\u6E29\u5EA6\u548C Top P\uFF0C\u8BF7\u81F3\u5C11\u6E05\u7A7A\u4E00\u9879\u3002";
1140
+ if (temperature !== void 0 && temperature !== 1) return "\u6B64 Claude \u6A21\u578B\u7684 Messages \u8BF7\u6C42\u4EC5\u63A5\u53D7\u9ED8\u8BA4\u6E29\u5EA6 1\uFF0C\u8BF7\u6E05\u7A7A\u6216\u6539\u4E3A 1\u3002";
1141
+ if (topP !== void 0 && topP !== 0.99) return "\u6B64 Claude \u6A21\u578B\u7684 Messages \u8BF7\u6C42\u4EC5\u63A5\u53D7\u9ED8\u8BA4 Top P 0.99\uFF0C\u8BF7\u6E05\u7A7A\u6216\u6539\u4E3A 0.99\u3002";
1142
+ return void 0;
1143
+ }
1144
+ var CLAUDE_MESSAGES_MAX_OUTPUT = 128e3;
1145
+ function claudeOutputError(model, protocol, maxTokens) {
1146
+ return hasRestrictedClaudeSampling(model, protocol) && maxTokens !== void 0 && maxTokens > CLAUDE_MESSAGES_MAX_OUTPUT ? "\u6B64 Claude \u6A21\u578B\u7684 Messages \u6700\u5927\u8F93\u51FA\u4E3A 128000\uFF0C\u8BF7\u51CF\u5C0F\u8F93\u51FA\u4E0A\u9650\u3002" : void 0;
1147
+ }
1148
+
1149
+ // src/claude-parameters.ts
1150
+ function validateClaudeSampling(model, temperature, topP) {
1151
+ const error = claudeSamplingError(model, "messages", temperature, topP);
1152
+ if (error !== void 0) throw new LlmError7(error, "UNSUPPORTED_OPTION");
1153
+ }
1154
+ function validateClaudeOutput(model, maxTokens) {
1155
+ const error = claudeOutputError(model, "messages", maxTokens);
1156
+ if (error !== void 0) throw new LlmError7(error, "UNSUPPORTED_OPTION");
1157
+ }
1158
+
1114
1159
  // src/protocols/messages.ts
1115
1160
  var MESSAGES_DEFAULT_MAX_TOKENS = 4096;
1116
1161
  var ANTHROPIC_VERSION = "2023-06-01";
1117
1162
  var DATA_URL = /^data:([^;,]+);base64,(.*)$/su;
1163
+ var REPLAY_FORMAT = "opendesign.anthropic-messages";
1164
+ var MAX_REPLAY_CHARS = 8 * 1024 * 1024;
1165
+ var MAX_BLOCKS = 4096;
1166
+ function replayBlocks(message, ctx) {
1167
+ if (message.role !== "assistant" || message.source.provider !== ctx.options.provider || message.source.model !== ctx.options.model) return;
1168
+ const envelope = message.source.replayState;
1169
+ if (!record(envelope) || !record(envelope.response) || !Array.isArray(envelope.blocks)) return;
1170
+ const response = envelope.response;
1171
+ if (response.format !== REPLAY_FORMAT || response.version !== 1 || response.protocol !== "messages" || response.provider !== ctx.options.provider || response.model !== ctx.options.model || envelope.blocks.length !== message.content.length) return;
1172
+ let size = 0;
1173
+ const entries = [];
1174
+ for (const [index, block] of message.content.entries()) {
1175
+ const entry = envelope.blocks[index];
1176
+ if (!record(entry)) return;
1177
+ if ((entry.type === "text" || entry.type === "reasoning") && block.type === entry.type && typeof entry.text === "string" && entry.text === block.text) {
1178
+ entries.push({ type: entry.type, text: entry.text });
1179
+ size += entry.text.length;
1180
+ } else if (entry.type === "tool-call" && block.type === "tool-call" && entry.id === block.id && entry.name === block.name && entry.arguments === block.arguments) {
1181
+ entries.push({ type: "tool-call", id: block.id, name: block.name, arguments: block.arguments });
1182
+ size += block.id.length + block.name.length + block.arguments.length;
1183
+ } else if (entry.type === "thinking" && block.type === "reasoning" && typeof entry.thinking === "string" && entry.thinking === block.text && typeof entry.signature === "string" && entry.signature.length > 0) {
1184
+ entries.push({ type: "thinking", thinking: entry.thinking, signature: entry.signature });
1185
+ size += entry.thinking.length + entry.signature.length;
1186
+ } else if (entry.type === "redacted_thinking" && block.type === "reasoning" && block.text === "" && typeof entry.data === "string" && entry.data.length > 0) {
1187
+ entries.push({ type: "redacted_thinking", data: entry.data });
1188
+ size += entry.data.length;
1189
+ } else return;
1190
+ if (size > MAX_REPLAY_CHARS || entries.length > MAX_BLOCKS) return;
1191
+ }
1192
+ 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)) {
1193
+ 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");
1194
+ }
1195
+ return entries;
1196
+ }
1118
1197
  function messagesURL(baseURL) {
1119
1198
  return inferenceEndpoint(baseURL, "messages");
1120
1199
  }
@@ -1128,15 +1207,17 @@ function toolInput(argumentsText) {
1128
1207
  try {
1129
1208
  parsed = JSON.parse(argumentsText);
1130
1209
  } catch {
1131
- throw new LlmError7("\u5386\u53F2\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u4E0D\u662F\u5408\u6CD5 JSON\uFF0C\u65E0\u6CD5\u6295\u5F71\u4E3A Anthropic tool_use.input", "INVALID_REQUEST");
1210
+ throw new LlmError8("\u5386\u53F2\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u4E0D\u662F\u5408\u6CD5 JSON\uFF0C\u65E0\u6CD5\u6295\u5F71\u4E3A Anthropic tool_use.input", "INVALID_REQUEST");
1132
1211
  }
1133
- if (!record(parsed)) throw new LlmError7("\u5386\u53F2\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u4E0D\u662F JSON \u5BF9\u8C61\uFF0C\u65E0\u6CD5\u6295\u5F71\u4E3A Anthropic tool_use.input", "INVALID_REQUEST");
1212
+ if (!record(parsed)) throw new LlmError8("\u5386\u53F2\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u4E0D\u662F JSON \u5BF9\u8C61\uFF0C\u65E0\u6CD5\u6295\u5F71\u4E3A Anthropic tool_use.input", "INVALID_REQUEST");
1134
1213
  return parsed;
1135
1214
  }
1136
1215
  function buildMessagesRequest(ctx) {
1137
1216
  const { options, model } = ctx;
1217
+ validateClaudeSampling(model.id, options.temperature, ctx.topP);
1138
1218
  const maxTokens = options.maxTokens ?? MESSAGES_DEFAULT_MAX_TOKENS;
1139
- if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) throw new LlmError7("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
1219
+ validateClaudeOutput(model.id, maxTokens);
1220
+ if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) throw new LlmError8("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
1140
1221
  const system = [];
1141
1222
  const messages2 = [];
1142
1223
  const lookup = ctx.images.size ? (ref) => ctx.images.get(ref.attachmentId) : void 0;
@@ -1176,9 +1257,17 @@ function buildMessagesRequest(ctx) {
1176
1257
  }
1177
1258
  case "assistant": {
1178
1259
  const content2 = [];
1179
- if (projected.text) content2.push({ type: "text", text: projected.text });
1180
- for (const block of message.content) {
1181
- if (block.type === "tool-call") content2.push({ type: "tool_use", id: block.id, name: block.name, input: toolInput(block.arguments) });
1260
+ const replay = replayBlocks(message, ctx);
1261
+ for (const [index, block] of message.content.entries()) {
1262
+ const entry = replay?.[index];
1263
+ if (entry?.type === "thinking") content2.push({ type: "thinking", thinking: entry.thinking, signature: entry.signature });
1264
+ else if (entry?.type === "redacted_thinking") content2.push({ type: "redacted_thinking", data: entry.data });
1265
+ else if (block.type === "text" && block.text !== "") content2.push({ type: "text", text: block.text });
1266
+ else if (block.type === "tool-call") content2.push({ type: "tool_use", id: block.id, name: block.name, input: toolInput(block.arguments) });
1267
+ else if (block.type === "image") {
1268
+ const placeholder = projectContent([block]).text;
1269
+ if (placeholder) content2.push({ type: "text", text: placeholder });
1270
+ }
1182
1271
  }
1183
1272
  if (content2.length) messages2.push({ role: "assistant", content: content2 });
1184
1273
  break;
@@ -1208,14 +1297,14 @@ function buildMessagesRequest(ctx) {
1208
1297
  else if (protocolAcceptsEffort("messages", effort)) {
1209
1298
  body.thinking = { type: "adaptive" };
1210
1299
  body.output_config = { effort };
1211
- } else throw new LlmError7(`Anthropic Messages \u534F\u8BAE\u4E0D\u63A5\u53D7\u601D\u8003\u6DF1\u5EA6\u300C${effort}\u300D`, "UNSUPPORTED_OPTION");
1300
+ } else throw new LlmError8(`Anthropic Messages \u534F\u8BAE\u4E0D\u63A5\u53D7\u601D\u8003\u6DF1\u5EA6\u300C${effort}\u300D`, "UNSUPPORTED_OPTION");
1212
1301
  }
1213
1302
  return { url: messagesURL(ctx.baseURL), headers: streamHeaders(ctx.apiKey, { "anthropic-version": ANTHROPIC_VERSION }), body };
1214
1303
  }
1215
1304
  function num(value) {
1216
1305
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1217
1306
  }
1218
- async function* streamMessages(body, signal, idleMs) {
1307
+ async function* streamMessages(body, signal, idleMs, context) {
1219
1308
  let nextIndex = 0;
1220
1309
  let count2 = 0;
1221
1310
  let finish;
@@ -1229,9 +1318,14 @@ async function* streamMessages(body, signal, idleMs) {
1229
1318
  cacheWrite: void 0
1230
1319
  };
1231
1320
  let usage;
1321
+ let replayChars = 0;
1322
+ function account(text2) {
1323
+ replayChars += text2.length;
1324
+ if (replayChars > MAX_REPLAY_CHARS) throw new LlmError8("OpenDesign\uFF1A\u54CD\u5E94\u5185\u5BB9\u8D85\u8FC7\u5927\u5C0F\u9650\u5236", "INVALID_RESPONSE");
1325
+ }
1232
1326
  function stateAt(index) {
1233
1327
  const state = typeof index === "number" ? blocks.get(index) : void 0;
1234
- if (!state) throw new LlmError7("OpenDesign\uFF1A\u6D41\u5F0F\u5185\u5BB9\u5757\u7D22\u5F15\u65E0\u6548", "INVALID_RESPONSE");
1328
+ if (!state) throw new LlmError8("OpenDesign\uFF1A\u6D41\u5F0F\u5185\u5BB9\u5757\u7D22\u5F15\u65E0\u6548", "INVALID_RESPONSE");
1235
1329
  return state;
1236
1330
  }
1237
1331
  function assign(state) {
@@ -1240,19 +1334,41 @@ async function* streamMessages(body, signal, idleMs) {
1240
1334
  count2++;
1241
1335
  }
1242
1336
  }
1243
- function close() {
1337
+ function close(only) {
1244
1338
  const out = [];
1245
1339
  for (const state of blocks.values()) {
1246
- if (!state.started) continue;
1340
+ if (!state.started || state.ended || only !== void 0 && state !== only) continue;
1341
+ state.ended = true;
1247
1342
  if (state.kind === "text") out.push({ type: "block-end", index: state.index, block: { type: "text", text: state.text } });
1248
- else if (state.kind === "reasoning") out.push({ type: "block-end", index: state.index, block: { type: "reasoning", text: state.text } });
1343
+ else if (state.kind === "reasoning" || state.kind === "redacted") out.push({ type: "block-end", index: state.index, block: { type: "reasoning", text: state.text } });
1249
1344
  else if (state.kind === "tool") {
1250
- if (!state.id || !state.name) throw new LlmError7("OpenDesign\uFF1A\u5DE5\u5177\u8C03\u7528\u7F3A\u5C11\u6807\u8BC6\u6216\u540D\u79F0", "INVALID_RESPONSE");
1251
- out.push({ type: "block-end", index: state.index, block: { type: "tool-call", id: ToolCallId2(state.id), name: state.name, arguments: state.args } });
1345
+ if (!state.id || !state.name) throw new LlmError8("OpenDesign\uFF1A\u5DE5\u5177\u8C03\u7528\u7F3A\u5C11\u6807\u8BC6\u6216\u540D\u79F0", "INVALID_RESPONSE");
1346
+ const args = state.hasArgsDelta ? state.args : state.initialInput;
1347
+ out.push({ type: "block-end", index: state.index, block: { type: "tool-call", id: ToolCallId2(state.id), name: state.name, arguments: args } });
1252
1348
  }
1253
1349
  }
1254
1350
  return out.sort((a, b) => ("index" in a ? a.index : 0) - ("index" in b ? b.index : 0));
1255
1351
  }
1352
+ function replay() {
1353
+ if (!context?.credentialIdentity || ![...blocks.values()].some((state) => state.signature !== "" || state.kind === "redacted")) return;
1354
+ const entries = [];
1355
+ for (const state of blocks.values()) {
1356
+ if (!state.started) continue;
1357
+ if (state.kind === "text") entries.push({ type: "text", text: state.text });
1358
+ else if (state.kind === "reasoning") entries.push(state.signature ? { type: "thinking", thinking: state.text, signature: state.signature } : { type: "reasoning", text: state.text });
1359
+ else if (state.kind === "redacted") entries.push({ type: "redacted_thinking", data: state.data });
1360
+ else if (state.kind === "tool") entries.push({ type: "tool-call", id: state.id, name: state.name, arguments: state.hasArgsDelta ? state.args : state.initialInput });
1361
+ }
1362
+ return { response: {
1363
+ format: REPLAY_FORMAT,
1364
+ version: 1,
1365
+ protocol: "messages",
1366
+ provider: context.provider,
1367
+ model: context.model,
1368
+ origin: new URL(context.baseURL).origin,
1369
+ credentialIdentity: context.credentialIdentity
1370
+ }, blocks: entries };
1371
+ }
1256
1372
  function reasonFromStop(stop) {
1257
1373
  switch (stop) {
1258
1374
  case "end_turn":
@@ -1264,23 +1380,24 @@ async function* streamMessages(body, signal, idleMs) {
1264
1380
  case "tool_use":
1265
1381
  return { kind: "tool-calls" };
1266
1382
  case "refusal":
1267
- throw new LlmError7("OpenDesign\uFF1A\u6A21\u578B\u62D2\u7EDD\u56DE\u7B54\uFF08refusal\uFF09", "INVALID_RESPONSE");
1383
+ throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u62D2\u7EDD\u56DE\u7B54\uFF08refusal\uFF09", "INVALID_RESPONSE");
1268
1384
  case "pause_turn":
1269
- throw new LlmError7("OpenDesign\uFF1A\u6A21\u578B\u6682\u505C\u8F6E\u6B21\uFF0C\u9700\u91CD\u65B0\u53D1\u8D77\u8BF7\u6C42", "INVALID_RESPONSE");
1385
+ throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u6682\u505C\u8F6E\u6B21\uFF0C\u9700\u91CD\u65B0\u53D1\u8D77\u8BF7\u6C42", "INVALID_RESPONSE");
1270
1386
  default:
1271
- throw new LlmError7("OpenDesign\uFF1A\u6A21\u578B\u54CD\u5E94\u88AB\u8FC7\u6EE4\u6216\u5F02\u5E38\u7EC8\u6B62", "INVALID_RESPONSE");
1387
+ throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u54CD\u5E94\u88AB\u8FC7\u6EE4\u6216\u5F02\u5E38\u7EC8\u6B62", "INVALID_RESPONSE");
1272
1388
  }
1273
1389
  }
1274
1390
  for await (const frame of sseFrames(body, signal, idleMs)) {
1391
+ signal.throwIfAborted();
1275
1392
  let value;
1276
1393
  try {
1277
1394
  value = JSON.parse(frame.data);
1278
1395
  } catch {
1279
- throw new LlmError7("OpenDesign\uFF1A\u65E0\u6548\u7684\u6D41\u5F0F JSON", "INVALID_RESPONSE");
1396
+ throw new LlmError8("OpenDesign\uFF1A\u65E0\u6548\u7684\u6D41\u5F0F JSON", "INVALID_RESPONSE");
1280
1397
  }
1281
- if (!record(value)) throw new LlmError7("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u4E0D\u662F\u5BF9\u8C61", "INVALID_RESPONSE");
1398
+ if (!record(value)) throw new LlmError8("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u4E0D\u662F\u5BF9\u8C61", "INVALID_RESPONSE");
1282
1399
  const type = typeof value.type === "string" && value.type !== "" ? value.type : frame.event;
1283
- if (!type) throw new LlmError7("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u7F3A\u5C11\u7C7B\u578B", "INVALID_RESPONSE");
1400
+ if (!type) throw new LlmError8("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u7F3A\u5C11\u7C7B\u578B", "INVALID_RESPONSE");
1284
1401
  const out = [];
1285
1402
  switch (type) {
1286
1403
  case "message_start": {
@@ -1294,39 +1411,66 @@ async function* streamMessages(body, signal, idleMs) {
1294
1411
  }
1295
1412
  case "content_block_start": {
1296
1413
  const index = value.index;
1297
- if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) throw new LlmError7("OpenDesign\uFF1A\u6D41\u5F0F\u5185\u5BB9\u5757\u7D22\u5F15\u65E0\u6548", "INVALID_RESPONSE");
1414
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) throw new LlmError8("OpenDesign\uFF1A\u6D41\u5F0F\u5185\u5BB9\u5757\u7D22\u5F15\u65E0\u6548", "INVALID_RESPONSE");
1298
1415
  const block = record(value.content_block) ? value.content_block : {};
1299
1416
  const kind = typeof block.type === "string" ? block.type : "";
1300
- const state = { index: -1, kind: "skip", text: "", id: "", name: "", args: "", started: false };
1417
+ if (blocks.has(index) || blocks.size >= MAX_BLOCKS) throw new LlmError8("OpenDesign\uFF1A\u5185\u5BB9\u5757\u91CD\u590D\u6216\u8D85\u8FC7\u6570\u91CF\u9650\u5236", "INVALID_RESPONSE");
1418
+ const state = {
1419
+ index: -1,
1420
+ kind: "skip",
1421
+ text: "",
1422
+ id: "",
1423
+ name: "",
1424
+ args: "",
1425
+ started: false,
1426
+ ended: false,
1427
+ signature: "",
1428
+ data: "",
1429
+ initialInput: "{}",
1430
+ hasArgsDelta: false
1431
+ };
1301
1432
  if (kind === "text") state.kind = "text";
1302
1433
  else if (kind === "thinking") state.kind = "reasoning";
1434
+ else if (kind === "redacted_thinking") state.kind = "redacted";
1303
1435
  else if (kind === "tool_use") state.kind = "tool";
1304
1436
  if (state.kind === "tool") {
1305
1437
  state.id = typeof block.id === "string" ? block.id : "";
1306
1438
  state.name = typeof block.name === "string" ? block.name : "";
1307
1439
  sawTool = true;
1440
+ if (block.input !== void 0) {
1441
+ if (!record(block.input)) throw new LlmError8("OpenDesign\uFF1A\u5DE5\u5177\u521D\u59CB\u53C2\u6570\u4E0D\u662F\u5BF9\u8C61", "INVALID_RESPONSE");
1442
+ state.initialInput = JSON.stringify(block.input);
1443
+ }
1308
1444
  }
1309
1445
  if (state.kind === "text" && typeof block.text === "string" && block.text !== "") state.text = block.text;
1310
1446
  if (state.kind === "reasoning" && typeof block.thinking === "string" && block.thinking !== "") state.text = block.thinking;
1447
+ if (state.kind === "reasoning" && typeof block.signature === "string") state.signature = block.signature;
1448
+ if (state.kind === "redacted") {
1449
+ if (typeof block.data !== "string" || block.data === "") throw new LlmError8("OpenDesign\uFF1A\u5BC6\u6001\u601D\u8003\u5757\u7F3A\u5C11\u6570\u636E", "INVALID_RESPONSE");
1450
+ state.data = block.data;
1451
+ }
1452
+ account(state.text + state.signature + state.data + state.id + state.name + state.initialInput);
1311
1453
  blocks.set(index, state);
1312
1454
  if (state.kind === "tool") {
1313
1455
  assign(state);
1314
1456
  state.started = true;
1315
1457
  out.push({ type: "block-start", index: state.index, blockType: "tool-call" });
1316
1458
  if (state.id) out.push({ type: "tool-call-delta", index: state.index, id: ToolCallId2(state.id), ...state.name ? { name: state.name } : {}, argumentsDelta: "" });
1317
- } else if ((state.kind === "text" || state.kind === "reasoning") && state.text !== "") {
1459
+ } else if (state.kind === "text" || state.kind === "reasoning" || state.kind === "redacted") {
1318
1460
  assign(state);
1319
1461
  state.started = true;
1320
1462
  out.push({ type: "block-start", index: state.index, blockType: state.kind === "text" ? "text" : "reasoning" });
1321
- out.push(state.kind === "text" ? { type: "text-delta", index: state.index, text: state.text } : { type: "reasoning-delta", index: state.index, text: state.text });
1463
+ if (state.text !== "") out.push(state.kind === "text" ? { type: "text-delta", index: state.index, text: state.text } : { type: "reasoning-delta", index: state.index, text: state.text });
1322
1464
  }
1323
1465
  break;
1324
1466
  }
1325
1467
  case "content_block_delta": {
1326
1468
  const state = stateAt(value.index);
1469
+ if (state.ended) throw new LlmError8("OpenDesign\uFF1A\u5185\u5BB9\u5757\u7ED3\u675F\u540E\u4ECD\u6536\u5230\u5206\u7247", "INVALID_RESPONSE");
1327
1470
  const delta = record(value.delta) ? value.delta : {};
1328
1471
  const deltaType = typeof delta.type === "string" ? delta.type : "";
1329
1472
  if (deltaType === "text_delta") {
1473
+ if (state.kind !== "text") throw new LlmError8("OpenDesign\uFF1A\u6587\u672C\u5206\u7247\u843D\u5728\u975E\u6587\u672C\u5757\u4E0A", "INVALID_RESPONSE");
1330
1474
  const text2 = typeof delta.text === "string" ? delta.text : "";
1331
1475
  if (!text2) break;
1332
1476
  assign(state);
@@ -1335,10 +1479,12 @@ async function* streamMessages(body, signal, idleMs) {
1335
1479
  out.push({ type: "block-start", index: state.index, blockType: "text" });
1336
1480
  }
1337
1481
  state.text += text2;
1482
+ account(text2);
1338
1483
  out.push({ type: "text-delta", index: state.index, text: text2 });
1339
1484
  break;
1340
1485
  }
1341
1486
  if (deltaType === "thinking_delta") {
1487
+ if (state.kind !== "reasoning") throw new LlmError8("OpenDesign\uFF1A\u601D\u8003\u5206\u7247\u843D\u5728\u975E\u601D\u8003\u5757\u4E0A", "INVALID_RESPONSE");
1342
1488
  const text2 = typeof delta.thinking === "string" ? delta.thinking : "";
1343
1489
  if (!text2) break;
1344
1490
  assign(state);
@@ -1347,16 +1493,32 @@ async function* streamMessages(body, signal, idleMs) {
1347
1493
  out.push({ type: "block-start", index: state.index, blockType: "reasoning" });
1348
1494
  }
1349
1495
  state.text += text2;
1496
+ account(text2);
1350
1497
  out.push({ type: "reasoning-delta", index: state.index, text: text2 });
1351
1498
  break;
1352
1499
  }
1353
1500
  if (deltaType === "input_json_delta") {
1354
- if (state.kind !== "tool") throw new LlmError7("OpenDesign\uFF1A\u5DE5\u5177\u53C2\u6570\u5206\u7247\u843D\u5728\u975E\u5DE5\u5177\u5757\u4E0A", "INVALID_RESPONSE");
1501
+ if (state.kind !== "tool") throw new LlmError8("OpenDesign\uFF1A\u5DE5\u5177\u53C2\u6570\u5206\u7247\u843D\u5728\u975E\u5DE5\u5177\u5757\u4E0A", "INVALID_RESPONSE");
1355
1502
  const part = typeof delta.partial_json === "string" ? delta.partial_json : "";
1503
+ if (state.initialInput !== "{}") throw new LlmError8("OpenDesign\uFF1A\u5DE5\u5177\u53C2\u6570\u540C\u65F6\u5305\u542B\u521D\u59CB\u5BF9\u8C61\u548C\u5206\u7247", "INVALID_RESPONSE");
1504
+ state.hasArgsDelta = true;
1356
1505
  state.args += part;
1506
+ account(part);
1357
1507
  if (state.id) out.push({ type: "tool-call-delta", index: state.index, id: ToolCallId2(state.id), ...state.name ? { name: state.name } : {}, argumentsDelta: part });
1358
1508
  break;
1359
1509
  }
1510
+ if (deltaType === "signature_delta") {
1511
+ if (state.kind !== "reasoning" || typeof delta.signature !== "string") throw new LlmError8("OpenDesign\uFF1A\u601D\u8003\u7B7E\u540D\u5206\u7247\u65E0\u6548", "INVALID_RESPONSE");
1512
+ state.signature += delta.signature;
1513
+ account(delta.signature);
1514
+ }
1515
+ break;
1516
+ }
1517
+ case "content_block_stop": {
1518
+ const state = stateAt(value.index);
1519
+ if (state.ended) throw new LlmError8("OpenDesign\uFF1A\u5185\u5BB9\u5757\u91CD\u590D\u7ED3\u675F", "INVALID_RESPONSE");
1520
+ out.push(...close(state));
1521
+ state.ended = true;
1360
1522
  break;
1361
1523
  }
1362
1524
  case "message_delta": {
@@ -1371,13 +1533,18 @@ async function* streamMessages(body, signal, idleMs) {
1371
1533
  }
1372
1534
  case "message_stop": {
1373
1535
  const reason = reasonFromStop(stopReason);
1374
- if (reason.kind === "tool-calls" && !sawTool) throw new LlmError7("OpenDesign\uFF1A\u54CD\u5E94\u58F0\u660E\u5DE5\u5177\u8C03\u7528\uFF0C\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5DE5\u5177\u5757", "INVALID_RESPONSE");
1375
- if (!count2) throw new LlmError7("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
1536
+ if (reason.kind === "tool-calls" && !sawTool) throw new LlmError8("OpenDesign\uFF1A\u54CD\u5E94\u58F0\u660E\u5DE5\u5177\u8C03\u7528\uFF0C\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5DE5\u5177\u5757", "INVALID_RESPONSE");
1537
+ if (reason.kind !== "max-tokens") for (const state of blocks.values()) {
1538
+ if (state.kind === "tool") toolInput(state.hasArgsDelta ? state.args : state.initialInput);
1539
+ }
1540
+ if (!count2 || ![...blocks.values()].some((state) => state.kind === "tool" || state.text !== "" || state.signature !== "" || state.data !== "")) throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
1541
+ signal.throwIfAborted();
1376
1542
  usage = anthropicUsage(raw) ?? usage;
1377
1543
  out.push(...close());
1378
1544
  if (usage) out.push({ type: "usage", usage });
1379
1545
  finish = reason;
1380
- out.push({ type: "finish", reason });
1546
+ const replayState = replay();
1547
+ out.push({ type: "finish", reason, ...replayState === void 0 ? {} : { replayState } });
1381
1548
  break;
1382
1549
  }
1383
1550
  case "error":
@@ -1386,7 +1553,10 @@ async function* streamMessages(body, signal, idleMs) {
1386
1553
  default:
1387
1554
  break;
1388
1555
  }
1389
- for (const chunk of out) yield chunk;
1556
+ for (const chunk of out) {
1557
+ signal.throwIfAborted();
1558
+ yield chunk;
1559
+ }
1390
1560
  if (finish) break;
1391
1561
  }
1392
1562
  signal.throwIfAborted();
@@ -1400,7 +1570,7 @@ var messages = {
1400
1570
 
1401
1571
  // src/protocols/responses.ts
1402
1572
  import {
1403
- LlmError as LlmError8,
1573
+ LlmError as LlmError9,
1404
1574
  ToolCallId as ToolCallId3
1405
1575
  } from "@deepseek-ai/dsh-llm";
1406
1576
  function userContent(text2, images) {
@@ -1458,15 +1628,15 @@ function buildResponsesRequest(ctx) {
1458
1628
  if (options.temperature !== void 0) body.temperature = options.temperature;
1459
1629
  if (ctx.topP !== void 0) body.top_p = ctx.topP;
1460
1630
  if (options.maxTokens !== void 0) {
1461
- if (!Number.isSafeInteger(options.maxTokens) || options.maxTokens <= 0) throw new LlmError8("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
1631
+ if (!Number.isSafeInteger(options.maxTokens) || options.maxTokens <= 0) throw new LlmError9("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
1462
1632
  body.max_output_tokens = options.maxTokens;
1463
1633
  }
1464
1634
  if (options.reasoningEffort !== void 0) {
1465
1635
  const effort = String(options.reasoningEffort);
1466
- if (!protocolAcceptsEffort("responses", effort)) throw new LlmError8(`Responses \u534F\u8BAE\u4E0D\u63A5\u53D7\u601D\u8003\u6DF1\u5EA6\u300C${effort}\u300D`, "UNSUPPORTED_OPTION");
1636
+ if (!protocolAcceptsEffort("responses", effort)) throw new LlmError9(`Responses \u534F\u8BAE\u4E0D\u63A5\u53D7\u601D\u8003\u6DF1\u5EA6\u300C${effort}\u300D`, "UNSUPPORTED_OPTION");
1467
1637
  body.reasoning = { effort, summary: "auto" };
1468
1638
  }
1469
- if (options.stop?.length) throw new LlmError8("Responses \u534F\u8BAE\u4E0D\u652F\u6301 stop \u5E8F\u5217", "UNSUPPORTED_OPTION");
1639
+ if (options.stop?.length) throw new LlmError9("Responses \u534F\u8BAE\u4E0D\u652F\u6301 stop \u5E8F\u5217", "UNSUPPORTED_OPTION");
1470
1640
  return { url: inferenceEndpoint(ctx.baseURL, "responses"), headers: streamHeaders(ctx.apiKey), body };
1471
1641
  }
1472
1642
  function str(value) {
@@ -1562,7 +1732,7 @@ async function* streamResponses(body, signal, idleMs) {
1562
1732
  let delta = "";
1563
1733
  if (args !== void 0) {
1564
1734
  if (typeof args !== "string" || !args.startsWith(call.args)) {
1565
- throw new LlmError8("OpenDesign\uFF1A\u5DE5\u5177\u8C03\u7528\u5B8C\u6574\u53C2\u6570\u4E0E\u6D41\u5F0F\u589E\u91CF\u4E0D\u4E00\u81F4", "INVALID_RESPONSE");
1735
+ throw new LlmError9("OpenDesign\uFF1A\u5DE5\u5177\u8C03\u7528\u5B8C\u6574\u53C2\u6570\u4E0E\u6D41\u5F0F\u589E\u91CF\u4E0D\u4E00\u81F4", "INVALID_RESPONSE");
1566
1736
  }
1567
1737
  delta = args.slice(call.args.length);
1568
1738
  call.args = args;
@@ -1610,7 +1780,7 @@ async function* streamResponses(body, signal, idleMs) {
1610
1780
  for (const state of texts.values()) if (state.started) out.push({ type: "block-end", index: state.index, block: { type: "text", text: state.text } });
1611
1781
  for (const state of reasonings.values()) if (state.started) out.push({ type: "block-end", index: state.index, block: { type: "reasoning", text: state.text } });
1612
1782
  for (const call of calls.values()) {
1613
- if (!call.id || !call.name) throw new LlmError8("OpenDesign\uFF1A\u5DE5\u5177\u8C03\u7528\u7F3A\u5C11\u6807\u8BC6\u6216\u540D\u79F0", "INVALID_RESPONSE");
1783
+ if (!call.id || !call.name) throw new LlmError9("OpenDesign\uFF1A\u5DE5\u5177\u8C03\u7528\u7F3A\u5C11\u6807\u8BC6\u6216\u540D\u79F0", "INVALID_RESPONSE");
1614
1784
  out.push({ type: "block-end", index: call.index, block: { type: "tool-call", id: ToolCallId3(call.id), name: call.name, arguments: call.args } });
1615
1785
  }
1616
1786
  return out.sort((a, b) => ("index" in a ? a.index : 0) - ("index" in b ? b.index : 0));
@@ -1620,8 +1790,8 @@ async function* streamResponses(body, signal, idleMs) {
1620
1790
  const details = record(response.incomplete_details) ? response.incomplete_details : {};
1621
1791
  const why = str(details.reason) ?? "";
1622
1792
  if (why === "max_tokens" || why === "max_output_tokens") return { kind: "max-tokens" };
1623
- if (why === "content_filter") throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u54CD\u5E94\u88AB\u5185\u5BB9\u8FC7\u6EE4", "INVALID_RESPONSE");
1624
- throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u54CD\u5E94\u672A\u5B8C\u6210\uFF0C\u4E0A\u6E38\u4E2D\u65AD", "SERVER");
1793
+ if (why === "content_filter") throw new LlmError9("OpenDesign\uFF1A\u6A21\u578B\u54CD\u5E94\u88AB\u5185\u5BB9\u8FC7\u6EE4", "INVALID_RESPONSE");
1794
+ throw new LlmError9("OpenDesign\uFF1A\u6A21\u578B\u54CD\u5E94\u672A\u5B8C\u6210\uFF0C\u4E0A\u6E38\u4E2D\u65AD", "SERVER");
1625
1795
  }
1626
1796
  const output = Array.isArray(response.output) ? response.output : [];
1627
1797
  return output.some((item) => record(item) && item.type === "function_call") || calls.size > 0 ? { kind: "tool-calls" } : { kind: "stop" };
@@ -1632,11 +1802,11 @@ async function* streamResponses(body, signal, idleMs) {
1632
1802
  try {
1633
1803
  value = JSON.parse(frame.data);
1634
1804
  } catch {
1635
- throw new LlmError8("OpenDesign\uFF1A\u65E0\u6548\u7684\u6D41\u5F0F JSON", "INVALID_RESPONSE");
1805
+ throw new LlmError9("OpenDesign\uFF1A\u65E0\u6548\u7684\u6D41\u5F0F JSON", "INVALID_RESPONSE");
1636
1806
  }
1637
- if (!record(value)) throw new LlmError8("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u4E0D\u662F\u5BF9\u8C61", "INVALID_RESPONSE");
1807
+ if (!record(value)) throw new LlmError9("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u4E0D\u662F\u5BF9\u8C61", "INVALID_RESPONSE");
1638
1808
  const type = str(value.type) ?? frame.event;
1639
- if (!type) throw new LlmError8("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u7F3A\u5C11\u7C7B\u578B", "INVALID_RESPONSE");
1809
+ if (!type) throw new LlmError9("OpenDesign\uFF1A\u6D41\u5F0F\u4E8B\u4EF6\u7F3A\u5C11\u7C7B\u578B", "INVALID_RESPONSE");
1640
1810
  const out = [];
1641
1811
  switch (type) {
1642
1812
  case "response.output_item.added": {
@@ -1722,8 +1892,8 @@ async function* streamResponses(body, signal, idleMs) {
1722
1892
  usage = responseUsage(response) ?? usage;
1723
1893
  hydrate(response.output, out);
1724
1894
  const reason = reasonOf(type, response);
1725
- if (reason.kind === "tool-calls" && calls.size === 0) throw new LlmError8("OpenDesign\uFF1A\u54CD\u5E94\u58F0\u660E\u5DE5\u5177\u8C03\u7528\uFF0C\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5DE5\u5177\u5757", "INVALID_RESPONSE");
1726
- if (!count2) throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
1895
+ 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");
1896
+ if (!count2) throw new LlmError9("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
1727
1897
  out.push(...close());
1728
1898
  if (usage) out.push({ type: "usage", usage });
1729
1899
  finish = reason;
@@ -1755,7 +1925,7 @@ var PROTOCOLS = {
1755
1925
  };
1756
1926
  function protocolFor(id) {
1757
1927
  const protocol = PROTOCOLS[id];
1758
- if (!protocol) throw new LlmError9(`\u672A\u77E5\u7684\u63A8\u7406\u534F\u8BAE\uFF1A${String(id)}`, "INVALID_REQUEST");
1928
+ if (!protocol) throw new LlmError10(`\u672A\u77E5\u7684\u63A8\u7406\u534F\u8BAE\uFF1A${String(id)}`, "INVALID_REQUEST");
1759
1929
  return protocol;
1760
1930
  }
1761
1931
 
@@ -1763,7 +1933,7 @@ function protocolFor(id) {
1763
1933
  function group(provider) {
1764
1934
  if (provider === PLAN_PROVIDER) return "plan";
1765
1935
  if (provider === PAID_PROVIDER) return "paid";
1766
- throw new LlmError10("\u672A\u77E5\u7684 CoRouter Provider", "INVALID_REQUEST");
1936
+ throw new LlmError11("\u672A\u77E5\u7684 CoRouter Provider", "INVALID_REQUEST");
1767
1937
  }
1768
1938
  function outputReserve(model, protocol) {
1769
1939
  const limit = model.maxOutputTokens ?? (protocol === "messages" ? 4096 : void 0);
@@ -1771,7 +1941,8 @@ function outputReserve(model, protocol) {
1771
1941
  }
1772
1942
  function metadata(provider, row, config) {
1773
1943
  const setting = config.modelSettings?.[row.id];
1774
- const reserve = setting?.maxTokens ?? outputReserve(row, config.apiProtocol ?? "chat-completions");
1944
+ const proposedReserve = setting?.maxTokens ?? outputReserve(row, config.apiProtocol ?? "chat-completions");
1945
+ const reserve = claudeOutputError(row.id, config.apiProtocol ?? "chat-completions", proposedReserve) === void 0 ? proposedReserve : void 0;
1775
1946
  const efforts = modelReasoningEfforts(row, config.apiProtocol ?? "chat-completions");
1776
1947
  const defaultEffort = setting?.reasoningEffort !== void 0 && efforts?.includes(setting.reasoningEffort) ? setting.reasoningEffort : void 0;
1777
1948
  return {
@@ -1794,24 +1965,60 @@ var CoRouterAdapter = class extends LlmAdapter {
1794
1965
  }
1795
1966
  options;
1796
1967
  #lifetime = new AbortController();
1968
+ #credentialSecret = randomBytes(32);
1797
1969
  dispose() {
1798
- this.#lifetime.abort(new LlmError10("CoRouter \u63D2\u4EF6\u5DF2\u5378\u8F7D", "ABORTED"));
1970
+ this.#lifetime.abort(new LlmError11("CoRouter \u63D2\u4EF6\u5DF2\u5378\u8F7D", "ABORTED"));
1971
+ this.#credentialSecret.fill(0);
1972
+ }
1973
+ async #credentialIdentity(baseURL, key, model, signal) {
1974
+ let secret2;
1975
+ let abort = () => {
1976
+ };
1977
+ try {
1978
+ if (this.options.replayBindingSecret && hasRestrictedClaudeSampling(model, "messages")) {
1979
+ const operation = this.options.replayBindingSecret(signal).then((bytes) => {
1980
+ if (signal.aborted) {
1981
+ bytes.fill(0);
1982
+ throw new LlmError11("Claude \u56DE\u653E\u7ED1\u5B9A\u5DF2\u53D6\u6D88", "ABORTED");
1983
+ }
1984
+ return bytes;
1985
+ });
1986
+ const aborted = new Promise((_resolve, reject) => {
1987
+ abort = () => reject(new LlmError11("Claude \u56DE\u653E\u7ED1\u5B9A\u5DF2\u53D6\u6D88", "ABORTED"));
1988
+ signal.addEventListener("abort", abort, { once: true });
1989
+ if (signal.aborted) abort();
1990
+ });
1991
+ secret2 = await Promise.race([operation, aborted]);
1992
+ } else secret2 = Buffer.from(this.#credentialSecret);
1993
+ signal.throwIfAborted();
1994
+ if (secret2.length !== 32) throw new Error("invalid binding");
1995
+ return createHmac("sha256", secret2).update("opendesign-claude-replay-v1\0").update(new URL(baseURL).origin).update("\0").update(key).digest("hex");
1996
+ } catch {
1997
+ if (signal.aborted) throw new LlmError11("Claude \u56DE\u653E\u7ED1\u5B9A\u5DF2\u53D6\u6D88", "ABORTED");
1998
+ 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");
1999
+ } finally {
2000
+ signal.removeEventListener("abort", abort);
2001
+ secret2?.fill(0);
2002
+ }
1799
2003
  }
1800
2004
  providerInfo(provider) {
1801
2005
  return { id: provider, name: group(provider) === "plan" ? "OpenDesign CoRouter \xB7 \u5957\u9910\u8D60\u9001" : "OpenDesign CoRouter \xB7 \u4ED8\u8D39\u6A21\u578B" };
1802
2006
  }
1803
2007
  modelOf(provider, id, config) {
1804
2008
  const row = (this.options.models?.() ?? MODELS).find((candidate) => candidate.id === id);
1805
- if (!row || row.group !== group(provider)) throw new LlmError10("\u8BE5\u6A21\u578B\u4E0D\u5C5E\u4E8E\u5F53\u524D CoRouter Provider\uFF1B\u8BF7\u5237\u65B0\u6A21\u578B\u5217\u8868\u5E76\u9009\u62E9\u5BF9\u5E94\u901A\u9053", "INVALID_REQUEST");
1806
- if (!isModelEnabled(id, config.modelSettings)) throw new LlmError10("\u8BE5\u6A21\u578B\u5DF2\u5728 CoRouter \u8BBE\u7F6E\u4E2D\u505C\u7528", "MODEL_DISABLED");
2009
+ if (!row || row.group !== group(provider)) throw new LlmError11("\u8BE5\u6A21\u578B\u4E0D\u5C5E\u4E8E\u5F53\u524D CoRouter Provider\uFF1B\u8BF7\u5237\u65B0\u6A21\u578B\u5217\u8868\u5E76\u9009\u62E9\u5BF9\u5E94\u901A\u9053", "INVALID_REQUEST");
2010
+ if (!isModelEnabled(id, config.modelSettings)) throw new LlmError11("\u8BE5\u6A21\u578B\u5DF2\u5728 CoRouter \u8BBE\u7F6E\u4E2D\u505C\u7528", "MODEL_DISABLED");
1807
2011
  const configured = applyModelSettings(row, config.modelSettings?.[id]);
1808
2012
  const output = config.modelSettings?.[id]?.maxTokens;
1809
- if (output !== void 0 && configured.contextWindow !== void 0 && output >= configured.contextWindow) throw new LlmError10("\u6A21\u578B\u6700\u5927\u8F93\u51FA\u5FC5\u987B\u5C0F\u4E8E\u4E0A\u4E0B\u6587\u9884\u7B97\uFF0C\u8BF7\u8C03\u6574\u6A21\u578B\u53C2\u6570", "INVALID_REQUEST");
2013
+ if (output !== void 0 && configured.contextWindow !== void 0 && output >= configured.contextWindow) throw new LlmError11("\u6A21\u578B\u6700\u5927\u8F93\u51FA\u5FC5\u987B\u5C0F\u4E8E\u4E0A\u4E0B\u6587\u9884\u7B97\uFF0C\u8BF7\u8C03\u6574\u6A21\u578B\u53C2\u6570", "INVALID_REQUEST");
1810
2014
  return configured;
1811
2015
  }
1812
2016
  async listModels(provider) {
1813
2017
  const config = this.options.config(), selectedGroup = group(provider);
1814
- return (this.options.models?.() ?? MODELS).filter((row) => row.group === selectedGroup && isModelEnabled(row.id, config.modelSettings)).map((row) => ({ provider, id: row.id, name: row.name, ...row.inputModalities ? { inputModalities: row.inputModalities } : {} }));
2018
+ return (this.options.models?.() ?? MODELS).filter((row) => row.group === selectedGroup && isModelEnabled(row.id, config.modelSettings)).map((row) => {
2019
+ const effective = applyModelSettings(row, config.modelSettings?.[row.id]);
2020
+ return { provider, id: effective.id, name: effective.name, ...effective.inputModalities ? { inputModalities: effective.inputModalities } : {} };
2021
+ });
1815
2022
  }
1816
2023
  async resolveModel(provider, model, signal) {
1817
2024
  signal?.throwIfAborted();
@@ -1833,18 +2040,32 @@ var CoRouterAdapter = class extends LlmAdapter {
1833
2040
  const setting = config.modelSettings?.[row.id] ?? {};
1834
2041
  const protocolId = config.apiProtocol ?? "chat-completions";
1835
2042
  const effort = options.reasoningEffort ?? (setting.reasoningEffort ? ReasoningEffortId(setting.reasoningEffort) : void 0);
1836
- if (effort !== void 0 && !modelReasoningEfforts(row, protocolId)?.includes(effort)) throw new LlmError10("\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");
2043
+ 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");
2044
+ if (protocolId === "messages") {
2045
+ validateClaudeSampling(row.id, options.temperature ?? setting.temperature, setting.topP);
2046
+ validateClaudeOutput(row.id, options.maxTokens ?? setting.maxTokens);
2047
+ }
1837
2048
  const raw = await this.options.apiKey(config.apiKeyEnv, config.baseURL);
1838
- if (!raw) throw new LlmError10("\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");
2049
+ 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");
1839
2050
  const key = assertUsableApiKey(raw, "dsh-opendesign-corouter", config.apiKeyEnv);
2051
+ signal.throwIfAborted();
2052
+ let credentialIdentity;
2053
+ if (protocolId === "messages") {
2054
+ try {
2055
+ credentialIdentity = await this.#credentialIdentity(config.baseURL, key, row.id, signal);
2056
+ } catch (error) {
2057
+ if (signal.aborted && !options.signal?.aborted && !this.#lifetime.signal.aborted) throw new LlmError11("CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6", "TIMEOUT");
2058
+ throw error;
2059
+ }
2060
+ }
1840
2061
  const images = /* @__PURE__ */ new Map();
1841
2062
  const attemptedImages = /* @__PURE__ */ new Set();
1842
2063
  const unreadableImages = /* @__PURE__ */ new Set();
1843
- if (row.inputModalities?.includes("image") && this.options.imageDataUrl) for (const message of options.messages.filter((item) => item.role === "user" || item.role === "tool")) for (const block of message.content) {
2064
+ if (row.inputModalities === void 0 || row.inputModalities.includes("image")) for (const message of options.messages.filter((item) => item.role === "user" || item.role === "tool")) for (const block of message.content) {
1844
2065
  if (block.type !== "image" || block.offloaded || attemptedImages.has(block.attachment.attachmentId)) continue;
1845
2066
  attemptedImages.add(block.attachment.attachmentId);
1846
2067
  try {
1847
- const url = await this.options.imageDataUrl(block.attachment, signal);
2068
+ const url = await this.options.imageDataUrl?.(block.attachment, signal);
1848
2069
  signal.throwIfAborted();
1849
2070
  if (url) images.set(block.attachment.attachmentId, url);
1850
2071
  else unreadableImages.add(block.attachment.attachmentId);
@@ -1864,10 +2085,10 @@ var CoRouterAdapter = class extends LlmAdapter {
1864
2085
  const tools = chatTools(options);
1865
2086
  let maxTokens = options.maxTokens ?? setting.maxTokens ?? outputReserve(row, protocolId);
1866
2087
  if (maxTokens !== void 0) {
1867
- if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) throw new LlmError10("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
2088
+ if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) throw new LlmError11("maxTokens \u5FC5\u987B\u662F\u6B63\u6574\u6570", "INVALID_REQUEST");
1868
2089
  const capped = Math.min(maxTokens, row.maxOutputTokens ?? maxTokens);
1869
2090
  const room = row.contextWindow === void 0 ? capped : row.contextWindow - estimateTokens({ messages: messages2, tools });
1870
- if (room < 1) throw new LlmError10("\u5F53\u524D\u8F93\u5165\u6CA1\u6709\u4E3A\u8F93\u51FA\u7559\u4E0B\u4E0A\u4E0B\u6587\u7A7A\u95F4", "CONTEXT_WINDOW_EXCEEDED");
2091
+ if (room < 1) throw new LlmError11("\u5F53\u524D\u8F93\u5165\u6CA1\u6709\u4E3A\u8F93\u51FA\u7559\u4E0B\u4E0A\u4E0B\u6587\u7A7A\u95F4", "CONTEXT_WINDOW_EXCEEDED");
1871
2092
  maxTokens = Math.min(capped, Math.floor(room));
1872
2093
  }
1873
2094
  const effective = {
@@ -1877,7 +2098,15 @@ var CoRouterAdapter = class extends LlmAdapter {
1877
2098
  ...effort === void 0 ? {} : { reasoningEffort: effort }
1878
2099
  };
1879
2100
  const protocol = protocolFor(protocolId);
1880
- const request = protocol.build({ baseURL: config.baseURL, apiKey: key, model: row, options: effective, images, ...setting.topP === void 0 ? {} : { topP: setting.topP } });
2101
+ const request = protocol.build({
2102
+ baseURL: config.baseURL,
2103
+ apiKey: key,
2104
+ model: row,
2105
+ options: effective,
2106
+ images,
2107
+ ...credentialIdentity === void 0 ? {} : { credentialIdentity },
2108
+ ...setting.topP === void 0 ? {} : { topP: setting.topP }
2109
+ });
1881
2110
  let response;
1882
2111
  try {
1883
2112
  response = await (this.options.fetch ?? fetch)(request.url, {
@@ -1889,7 +2118,7 @@ var CoRouterAdapter = class extends LlmAdapter {
1889
2118
  });
1890
2119
  } catch {
1891
2120
  if (options.signal?.aborted || this.#lifetime.signal.aborted) signal.throwIfAborted();
1892
- throw new LlmError10(signal.aborted ? "CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6" : "\u65E0\u6CD5\u8FDE\u63A5 CoRouter \u63A8\u7406\u670D\u52A1", signal.aborted ? "TIMEOUT" : "SERVER");
2121
+ throw new LlmError11(signal.aborted ? "CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6" : "\u65E0\u6CD5\u8FDE\u63A5 CoRouter \u63A8\u7406\u670D\u52A1", signal.aborted ? "TIMEOUT" : "SERVER");
1893
2122
  }
1894
2123
  if (!response.ok) {
1895
2124
  let error = {};
@@ -1926,25 +2155,114 @@ var CoRouterAdapter = class extends LlmAdapter {
1926
2155
  };
1927
2156
  if (!response.body) {
1928
2157
  if (monitor) reportEmptyTurn();
1929
- throw new LlmError10("CoRouter \u8FD4\u56DE\u7A7A\u54CD\u5E94", monitor ? OPENDESIGN_EOT : "EMPTY_RESPONSE");
2158
+ throw new LlmError11("CoRouter \u8FD4\u56DE\u7A7A\u54CD\u5E94", monitor ? OPENDESIGN_EOT : "EMPTY_RESPONSE");
1930
2159
  }
1931
2160
  const tracker = new EmptyTurnTracker({ enabled: monitor, onEmptyTurn: reportEmptyTurn });
1932
2161
  try {
1933
- for await (const chunk of protocol.stream(response.body, signal, config.streamIdleTimeoutMs)) {
2162
+ for await (const chunk of protocol.stream(response.body, signal, config.streamIdleTimeoutMs, {
2163
+ provider: options.provider,
2164
+ model: options.model,
2165
+ baseURL: config.baseURL,
2166
+ ...credentialIdentity === void 0 ? {} : { credentialIdentity }
2167
+ })) {
2168
+ signal.throwIfAborted();
1934
2169
  tracker.observe(chunk);
1935
- if (chunk.type === "finish" && monitor) yield { ...chunk, reason: tracker.resolve(chunk.reason) };
1936
- else yield chunk;
2170
+ if (chunk.type === "finish") {
2171
+ const reason = monitor ? tracker.resolve(chunk.reason) : chunk.reason;
2172
+ if (reason.kind === "error" || reason.kind === "aborted") yield { type: "finish", reason };
2173
+ else yield { ...chunk, reason };
2174
+ } else yield chunk;
1937
2175
  }
1938
2176
  } catch (error) {
1939
2177
  if (options.signal?.aborted || this.#lifetime.signal.aborted) signal.throwIfAborted();
1940
- if (signal.aborted) throw new LlmError10("CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6", "TIMEOUT");
1941
- if (monitor && !tracker.sawToolCall && error instanceof PrematureEndError) throw new LlmError10(error.message, "TRANSPORT");
1942
- if (monitor && !tracker.sawToolCall && error instanceof LlmError10 && error.code === "EMPTY_RESPONSE") {
2178
+ if (signal.aborted) throw new LlmError11("CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6", "TIMEOUT");
2179
+ if (monitor && !tracker.sawToolCall && error instanceof PrematureEndError) throw new LlmError11(error.message, "TRANSPORT");
2180
+ if (monitor && !tracker.sawToolCall && error instanceof LlmError11 && error.code === "EMPTY_RESPONSE") {
1943
2181
  reportEmptyTurn();
1944
- throw new LlmError10(error.message, OPENDESIGN_EOT);
2182
+ throw new LlmError11(error.message, OPENDESIGN_EOT);
1945
2183
  }
1946
- if (error instanceof LlmError10) throw error;
1947
- throw new LlmError10("CoRouter \u54CD\u5E94\u6D41\u8FDE\u63A5\u4E2D\u65AD", "SERVER");
2184
+ if (error instanceof LlmError11) throw error;
2185
+ throw new LlmError11("CoRouter \u54CD\u5E94\u6D41\u8FDE\u63A5\u4E2D\u65AD", "SERVER");
2186
+ }
2187
+ }
2188
+ };
2189
+
2190
+ // src/replay-key.ts
2191
+ import { randomBytes as randomBytes2 } from "node:crypto";
2192
+ import { credentialKey } from "@deepseek-ai/dsh-credentials";
2193
+ import { LlmError as LlmError12 } from "@deepseek-ai/dsh-llm";
2194
+ var REPLAY_BINDING_KEY = credentialKey("llm-opendesign-corouter", "claude-replay-binding");
2195
+ var unavailable = () => new LlmError12("\u65E0\u6CD5\u8BFB\u53D6\u6216\u5B89\u5168\u4FDD\u5B58 Claude \u56DE\u653E\u7ED1\u5B9A\u5BC6\u94A5\u3002\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u670D\u52A1\u53CA\u8BE5\u63D2\u4EF6\u7684\u56DE\u653E\u7ED1\u5B9A\u8BB0\u5F55\uFF1B\u539F\u6709\u8BB0\u5F55\u672A\u88AB\u66FF\u6362\u3002", "INVALID_REQUEST");
2196
+ var cancelled = () => new LlmError12("Claude \u56DE\u653E\u7ED1\u5B9A\u5DF2\u53D6\u6D88", "ABORTED");
2197
+ function decode(value) {
2198
+ if (value?.kind !== "grant" || !record(value.payload)) return;
2199
+ const payload = value.payload;
2200
+ if (payload.format !== "opendesign-claude-replay-key" || payload.version !== 1 || typeof payload.secret !== "string" || !/^[A-Za-z0-9+/]{43}=$/u.test(payload.secret) || Object.keys(payload).some((key) => !["format", "version", "secret"].includes(key))) return;
2201
+ const secret2 = Buffer.from(payload.secret, "base64");
2202
+ if (secret2.length !== 32 || secret2.toString("base64") !== payload.secret) {
2203
+ secret2.fill(0);
2204
+ return;
2205
+ }
2206
+ return secret2;
2207
+ }
2208
+ var ReplayKeyStore = class {
2209
+ constructor(provider) {
2210
+ this.provider = provider;
2211
+ }
2212
+ provider;
2213
+ #lifetime = new AbortController();
2214
+ #fallback;
2215
+ dispose() {
2216
+ this.#lifetime.abort();
2217
+ this.#fallback?.fill(0);
2218
+ this.#fallback = void 0;
2219
+ }
2220
+ /** Returns caller-owned bytes; callers clear them after deriving the binding. */
2221
+ async get(signal) {
2222
+ const lifetime = AbortSignal.any([signal, this.#lifetime.signal]);
2223
+ if (lifetime.aborted) throw cancelled();
2224
+ let abort = () => {
2225
+ };
2226
+ try {
2227
+ const provider = this.provider();
2228
+ if (!provider) {
2229
+ this.#fallback ??= randomBytes2(32);
2230
+ return Buffer.from(this.#fallback);
2231
+ }
2232
+ const aborted = new Promise((_resolve, reject) => {
2233
+ abort = () => reject(cancelled());
2234
+ lifetime.addEventListener("abort", abort, { once: true });
2235
+ if (lifetime.aborted) abort();
2236
+ });
2237
+ const current = await Promise.race([provider.readRecord(REPLAY_BINDING_KEY), aborted]);
2238
+ if (lifetime.aborted) throw cancelled();
2239
+ if (current !== void 0) {
2240
+ const secret3 = decode(current);
2241
+ if (!secret3) throw unavailable();
2242
+ return secret3;
2243
+ }
2244
+ const operation = provider.modifyRecord(REPLAY_BINDING_KEY, async (current2) => {
2245
+ if (lifetime.aborted) throw cancelled();
2246
+ if (current2 !== void 0) {
2247
+ const existing = decode(current2);
2248
+ if (!existing) throw unavailable();
2249
+ existing.fill(0);
2250
+ return void 0;
2251
+ }
2252
+ const bytes = randomBytes2(32);
2253
+ const secret3 = bytes.toString("base64");
2254
+ bytes.fill(0);
2255
+ return { kind: "grant", payload: { format: "opendesign-claude-replay-key", version: 1, secret: secret3 } };
2256
+ });
2257
+ const value = await Promise.race([operation, aborted]);
2258
+ if (lifetime.aborted) throw cancelled();
2259
+ const secret2 = decode(value);
2260
+ if (!secret2) throw unavailable();
2261
+ return secret2;
2262
+ } catch {
2263
+ throw lifetime.aborted ? cancelled() : unavailable();
2264
+ } finally {
2265
+ lifetime.removeEventListener("abort", abort);
1948
2266
  }
1949
2267
  }
1950
2268
  };
@@ -2651,7 +2969,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
2651
2969
 
2652
2970
  // src/device-auth.ts
2653
2971
  var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
2654
- var DEVICE_AUTH_PLUGIN_VERSION = "0.1.11";
2972
+ var DEVICE_AUTH_PLUGIN_VERSION = "0.1.12";
2655
2973
  var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
2656
2974
  var DEVICE_RESPONSE_MAX_BYTES = 65536;
2657
2975
  var DEVICE_POLL_MIN_MS = 1e3;
@@ -3631,6 +3949,12 @@ function parseEfforts(value) {
3631
3949
  if (!Array.isArray(value) || value.length > 16) throw new Error("\u6A21\u578B\u601D\u8003\u6863\u4F4D\u683C\u5F0F\u65E0\u6548");
3632
3950
  return value.map((item) => text(item, "\u601D\u8003\u6863\u4F4D", 32));
3633
3951
  }
3952
+ function parseModalities(value) {
3953
+ if (!Array.isArray(value) || value.length < 1 || value.length > 2) throw new Error("\u6A21\u578B\u8F93\u5165\u6A21\u6001\u683C\u5F0F\u65E0\u6548");
3954
+ const modes = value.map((item) => member(item, ["text", "image"], "\u6A21\u578B\u8F93\u5165\u6A21\u6001"));
3955
+ if (!modes.includes("text") || new Set(modes).size !== modes.length) throw new Error("\u6A21\u578B\u8F93\u5165\u6A21\u6001\u683C\u5F0F\u65E0\u6548");
3956
+ return modes;
3957
+ }
3634
3958
  function member(value, allowed, label) {
3635
3959
  const hit = allowed.find((candidate) => candidate === value);
3636
3960
  if (hit === void 0) throw new Error(`${label} \u4E0D\u5728\u5141\u8BB8\u7684\u53D6\u503C\u5185`);
@@ -3745,6 +4069,7 @@ function parseStatusModel(value) {
3745
4069
  name: text(value.name, "\u6A21\u578B\u540D", 128),
3746
4070
  group: member(value.group, MODEL_GROUPS, "\u6A21\u578B\u5206\u7EC4"),
3747
4071
  ...value.enabled === void 0 ? {} : { enabled: flag(value.enabled, "\u6A21\u578B\u542F\u7528\u72B6\u6001") },
4072
+ ...value.inputModalities === void 0 ? {} : { inputModalities: parseModalities(value.inputModalities) },
3748
4073
  ...value.contextWindow === void 0 ? {} : { contextWindow: positiveInteger(value.contextWindow, "\u4E0A\u4E0B\u6587\u9884\u7B97", 1e8) },
3749
4074
  ...value.maxOutputTokens === void 0 ? {} : { maxOutputTokens: positiveInteger(value.maxOutputTokens, "\u6700\u5927\u8F93\u51FA", 1e7) },
3750
4075
  ...value.reasoningEfforts === void 0 ? {} : { reasoningEfforts: parseEfforts(value.reasoningEfforts) }
@@ -3818,8 +4143,8 @@ function parseActivationOpenState(value) {
3818
4143
  // src/index.ts
3819
4144
  var name = "llm-opendesign-corouter";
3820
4145
  var inject = ["llm"];
3821
- var API_KEY = credentialKey(name, "api-key");
3822
- var SESSION = credentialKey(name, "console");
4146
+ var API_KEY = credentialKey2(name, "api-key");
4147
+ var SESSION = credentialKey2(name, "console");
3823
4148
  var hash = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
3824
4149
  var needLogin = () => ({ state: "need-login", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), windows: [], balances: {}, note: "\u8BF7\u5728\u8FDE\u63A5\u4E0E\u767B\u5F55\u9875\u5B8C\u6210\u8D26\u53F7\u6388\u6743\u540E\u8BFB\u53D6\u989D\u5EA6\u3002" });
3825
4150
  var unreadQuota = () => ({ state: "partial", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), windows: [], balances: {}, note: "\u989D\u5EA6\u5C1A\u672A\u8BFB\u53D6\uFF0C\u8BF7\u5237\u65B0\u989D\u5EA6\u3002" });
@@ -3983,13 +4308,14 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
3983
4308
  config: state.config,
3984
4309
  guardedTurns: this.guardedTurns,
3985
4310
  models: this._models.map((row) => {
3986
- const { id, name: name2, group: group2, contextWindow, maxOutputTokens } = row;
4311
+ const { id, name: name2, group: group2, contextWindow, maxOutputTokens, inputModalities } = row;
3987
4312
  const reasoningEfforts = modelReasoningEfforts(row, state.config.apiProtocol ?? "chat-completions");
3988
4313
  return {
3989
4314
  id,
3990
4315
  name: name2,
3991
4316
  group: group2,
3992
4317
  enabled: isModelEnabled(id, state.config.modelSettings),
4318
+ ...inputModalities === void 0 ? {} : { inputModalities },
3993
4319
  ...contextWindow === void 0 ? {} : { contextWindow },
3994
4320
  ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
3995
4321
  ...reasoningEfforts === void 0 ? {} : { reasoningEfforts }
@@ -4222,6 +4548,7 @@ function apply(ctx, config) {
4222
4548
  let modelsChanged = () => {
4223
4549
  };
4224
4550
  const service = new OpenDesignCoRouterService(ctx, current, { resolveSession, readQuota, readDesktopQuota, modelsChanged: () => modelsChanged() });
4551
+ const replayKeys = new ReplayKeyStore(() => ctx.get("credentials"));
4225
4552
  const adapter = new CoRouterAdapter({
4226
4553
  config: current,
4227
4554
  models: () => service.modelCatalog(),
@@ -4229,6 +4556,7 @@ function apply(ctx, config) {
4229
4556
  onEmptyTurn: () => {
4230
4557
  service.guardedTurns++;
4231
4558
  },
4559
+ replayBindingSecret: (signal) => replayKeys.get(signal),
4232
4560
  imageDataUrl: async (ref, signal) => {
4233
4561
  const attachments = ctx.get("attachments");
4234
4562
  if (!attachments) return void 0;
@@ -4246,18 +4574,24 @@ function apply(ctx, config) {
4246
4574
  modelsChanged();
4247
4575
  });
4248
4576
  ctx.llm.registerModelDiscovery(SETTINGS_NS, async (request, signal) => {
4249
- if (request.provider !== void 0 && ![PLAN_PROVIDER, PAID_PROVIDER].includes(request.provider)) throw new LlmError11("\u4E0D\u662F\u672C\u63D2\u4EF6\u7684\u6A21\u578B\u901A\u9053", "INVALID_REQUEST");
4577
+ if (request.provider !== void 0 && ![PLAN_PROVIDER, PAID_PROVIDER].includes(request.provider)) throw new LlmError13("\u4E0D\u662F\u672C\u63D2\u4EF6\u7684\u6A21\u578B\u901A\u9053", "INVALID_REQUEST");
4250
4578
  const config2 = current();
4251
4579
  const key = request.apiKey ?? await service.resolveApiKey(config2.apiKeyEnv, config2.baseURL);
4252
- if (!key) throw new LlmError11("\u8BF7\u5148\u914D\u7F6E CoRouter API Key", "MISSING_CREDENTIAL");
4580
+ if (!key) throw new LlmError13("\u8BF7\u5148\u914D\u7F6E CoRouter API Key", "MISSING_CREDENTIAL");
4253
4581
  const models = await fetchModelCatalog(config2.baseURL, key, signal);
4254
- return models.map((row) => ({ id: row.id, name: row.name, ...row.contextWindow === void 0 ? {} : { contextWindow: row.contextWindow }, ...row.maxOutputTokens === void 0 ? {} : { maxTokens: row.maxOutputTokens }, ...row.inputModalities ? { inputModalities: row.inputModalities } : {} }));
4582
+ return models.map((row) => {
4583
+ const effective = applyModelSettings(row, config2.modelSettings?.[row.id]);
4584
+ return { id: row.id, name: row.name, ...row.contextWindow === void 0 ? {} : { contextWindow: row.contextWindow }, ...row.maxOutputTokens === void 0 ? {} : { maxTokens: row.maxOutputTokens }, ...effective.inputModalities ? { inputModalities: effective.inputModalities } : {} };
4585
+ });
4255
4586
  });
4256
4587
  ctx.llm.registerConfigurableProviders([
4257
4588
  { provider: PLAN_PROVIDER, displayName: "OpenDesign CoRouter \xB7 \u5957\u9910\u8D60\u9001", settingsNs: SETTINGS_NS, settingsPath: [], defaultBaseURL: current().baseURL },
4258
4589
  { provider: PAID_PROVIDER, displayName: "OpenDesign CoRouter \xB7 \u4ED8\u8D39\u6A21\u578B", settingsNs: SETTINGS_NS, settingsPath: [], defaultBaseURL: current().baseURL }
4259
4590
  ]);
4260
- ctx.effect(() => () => adapter.dispose());
4591
+ ctx.effect(() => () => {
4592
+ adapter.dispose();
4593
+ replayKeys.dispose();
4594
+ });
4261
4595
  }
4262
4596
  export {
4263
4597
  CoRouterAdapter,