dsh-opendesign-corouter 0.1.10 → 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
@@ -48,16 +48,17 @@ 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 randomUUID2, createHash } from "node:crypto";
52
- import { credentialKey, credentialRef } from "@deepseek-ai/dsh-credentials";
51
+ import { randomUUID as randomUUID3, createHash } from "node:crypto";
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,9 +331,9 @@ 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
- emptyTurnGuard: Schema.boolean().default(true).description("\u68C0\u6D4B DeepSeek V4.1 Flash \u5DE5\u5177\u5BF9\u8BDD\u7684\u7A7A\u56DE\u7B54\uFF1B\u7531\u5BBF\u4E3B\u91CD\u8BD5\u7B56\u7565\u5904\u7406\uFF0C\u53EF\u80FD\u989D\u5916\u6D88\u8017\u989D\u5EA6").volatile(),
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(),
332
338
  requestTimeoutMs: Schema.natural().min(1e3).max(36e5).default(18e5).description("\u63A8\u7406\u8BF7\u6C42\u603B\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile(),
333
339
  streamIdleTimeoutMs: Schema.natural().min(1e3).max(18e5).default(3e5).description("\u6D41\u5F0F\u54CD\u5E94\u65E0\u6570\u636E\u8D85\u65F6\uFF08\u6BEB\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":
@@ -495,6 +501,11 @@ import {
495
501
  isContextWindowExceededError,
496
502
  isQuotaExceededError
497
503
  } from "@deepseek-ai/dsh-llm";
504
+ var PrematureEndError = class extends LlmError2 {
505
+ constructor(message) {
506
+ super(message, "INVALID_RESPONSE");
507
+ }
508
+ };
498
509
  var MESSAGES = {
499
510
  [CONTEXT_WINDOW_EXCEEDED_CODE]: "OpenDesign\uFF1A\u8BF7\u6C42\u8D85\u51FA\u6A21\u578B\u4E0A\u4E0B\u6587\u957F\u5EA6\uFF0C\u8BF7\u7F29\u77ED\u8F93\u5165\u540E\u91CD\u8BD5",
500
511
  [ACCOUNT_QUOTA_EXCEEDED_CODE]: "OpenDesign\uFF1A\u5957\u9910\u6216\u8D26\u6237\u989D\u5EA6\u4E0D\u8DB3\uFF0C\u8BF7\u68C0\u67E5\u5957\u9910\u989D\u5EA6\u540E\u91CD\u8BD5",
@@ -817,7 +828,7 @@ async function* consumeSse(body, signal, idleMs) {
817
828
  if (done) break;
818
829
  }
819
830
  signal.throwIfAborted();
820
- if (!finish) throw new LlmError4("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u539F\u56E0", "INVALID_RESPONSE");
831
+ if (!finish) throw new PrematureEndError("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u539F\u56E0");
821
832
  if (!count2) throw new LlmError4("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
822
833
  if (finish.kind === "tool-calls" && !sawTool) throw new LlmError4("OpenDesign\uFF1A\u54CD\u5E94\u58F0\u660E\u5DE5\u5177\u8C03\u7528\uFF0C\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5DE5\u5177\u5757", "INVALID_RESPONSE");
823
834
  if (usage) yield { type: "usage", usage };
@@ -825,11 +836,22 @@ async function* consumeSse(body, signal, idleMs) {
825
836
  }
826
837
 
827
838
  // src/empty-turn.ts
828
- import { EMPTY_RESPONSE_CODE } from "@deepseek-ai/dsh-llm";
829
- var EMPTY_TURN_MESSAGE = "OpenDesign\uFF1A\u6A21\u578B\u56DE\u590D\u53EA\u5269\u534F\u8BAE\u6807\u8BB0\uFF0C\u672A\u4EA7\u751F\u53EF\u7528\u5185\u5BB9";
839
+ import "@deepseek-ai/dsh-llm";
840
+
841
+ // src/eot-code.ts
842
+ var OPENDESIGN_EOT = "OPENDESIGN_EOT";
843
+
844
+ // src/empty-turn.ts
845
+ var EMPTY_TURN_MESSAGE = "OpenDesign\uFF1A\u6A21\u578B\u672A\u4EA7\u751F\u53EF\u7528\u56DE\u7B54\u6216\u6709\u6548\u5DE5\u5177\u8C03\u7528";
846
+ var INCOMPLETE_TURN_MESSAGE = "OpenDesign\uFF1A\u6A21\u578B\u505C\u5728\u64CD\u4F5C\u8BF4\u660E\uFF0C\u672A\u7EE7\u7EED\u53D1\u8D77\u5DE5\u5177\u8C03\u7528";
830
847
  var RESIDUE_PATTERNS = [
848
+ /<\s*rea:tool_calls\s*>[\s\S]*?(?:<\s*\/\s*rea:tool_calls\s*>|$)/giu,
849
+ /<\s*rea:tool(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*rea:tool\s*>|$)/giu,
850
+ /<\s*rea:parameter(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*rea:parameter\s*>|$)/giu,
851
+ /<\s*||DSML||\s*calls(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*||DSML||\s*calls\s*>|$)/gu,
831
852
  /<\s*\/?\s*||DSML||[^>]*>/gu,
832
- /||DSML||[^\n<>]*>?/gu,
853
+ /||DSML||\s*(?:calls|invoke|parameter)(?:\s+[^>\n]*)?>/giu,
854
+ /||DSML||(?:\s*(?:calls|invoke|parameter))?\s*$/giu,
833
855
  /<\s*\/?\s*thinking\s*>/giu,
834
856
  /<\s*\/?\s*rea:tool_calls\s*>/giu,
835
857
  /<\s*\/?\s*返璞归真\s*>/gu
@@ -844,6 +866,20 @@ function stripProtocolResidue(text2) {
844
866
  function isResidueOnly(text2) {
845
867
  return text2 === void 0 || stripProtocolResidue(text2) === "";
846
868
  }
869
+ var ACTION_PREAMBLE_ZH = /^(?:(?:好的?|明白|收到)[,,。]\s*)?(?:让我|我需要|我(?:先|再|将|会|来|要|这就|马上)|先|现在|接下来(?:我)?(?:将|会)?)(?:先|再|去|来|马上)?(?:看一看|看看|看下|查看|检查|核对|核验|核查|对照|比对|确认|验证|验收|测试|读取|读|打开|搜索|查找|定位|分析|排查|审查|检索|查询|运行|执行|修改|修复|调整|更新|编写|梳理|对比|比较)(?!了|过|到|出|完)[^,,。!?!?\n;;::]{1,100}[。!!…]?$/u;
870
+ var ACTION_PREAMBLE_EN = /^(?:(?:okay|sure|now)[,.]?\s+)?(?:let me|i(?:'ll| will)|i(?:'m| am) going to)\s+(?:check|inspect|review|verify|read|open|search|find|locate|analy[sz]e|test|run|execute|edit|fix|update|compare)\s+[^.!?,;:\n]{1,100}(?:\.{1,3}|!|…)?$/iu;
871
+ var FOLLOWUP_ACTION_ZH = /^(?:现在|接下来|下一步|随后|接着)(?:我)?(?:先|再|将|会|准备|重新)?(?:看一看|看看|看下|查看|检查|核对|核验|核查|对照|比对|确认|验证|验收|测试|读取|读|打开|搜索|查找|定位|分析|排查|审查|检索|查询|运行|执行|修改|修复|调整|更新|编写|梳理|对比|比较)(?!了|过|到|出|完|结果)[^。!?!?\n;;::]{1,100}[。!!…]?$/u;
872
+ var COMPLETED_ACTION_ZH = /(?:发现|结果(?:是|为|显示)|显示|得出|证明|确认了|已经完成|已完成|通过|没有问题|无误|正常)/u;
873
+ function isPendingActionTurn(text2) {
874
+ if (text2 === void 0) return false;
875
+ const content2 = stripProtocolResidue(text2);
876
+ if (ACTION_PREAMBLE_ZH.test(content2) || ACTION_PREAMBLE_EN.test(content2)) return true;
877
+ if (content2.length > 200 || /[\n`]/u.test(content2)) return false;
878
+ const sentences = content2.split(/(?<=[。!?])\s*/u).filter(Boolean);
879
+ if (sentences.length < 2 || sentences.length > 3) return false;
880
+ const last = sentences.at(-1) ?? "";
881
+ return FOLLOWUP_ACTION_ZH.test(last) && !COMPLETED_ACTION_ZH.test(last);
882
+ }
847
883
  function isMarkupOnlyStop(reason, input) {
848
884
  return reason.kind === "stop" && !input.sawToolCall && isResidueOnly(input.text);
849
885
  }
@@ -912,24 +948,28 @@ var EmptyTurnTracker = class {
912
948
  sawToolCall: this.#sawToolCall,
913
949
  textLength: text2.length,
914
950
  reasoningLength: reasoning.length,
915
- markupOnly: isResidueOnly(text2)
951
+ markupOnly: isResidueOnly(text2),
952
+ pendingAction: isPendingActionTurn(text2)
916
953
  };
917
954
  }
918
955
  /**
919
- * Rewrite an eligible finish into the provider-neutral empty-response failure.
956
+ * Rewrite an eligible finish into the scoped EOT failure.
920
957
  *
921
958
  * The reason object is returned unchanged (same reference) whenever the monitor is off, the
922
- * finish is not `stop`, a tool call was observed, or the visible text carries usable content.
923
- * This method only decides and rewrites: the retry itself belongs to the host's provider policy.
959
+ * finish is not `stop`, a tool call was observed, or the visible text is a substantive answer.
960
+ * This method only decides and rewrites; scoped recovery runs at the host's request-error boundary.
924
961
  * @param reason - the finish reason the adapter is about to yield.
925
962
  * @returns a retryable `error` reason, or the given reason untouched.
926
963
  */
927
964
  resolve(reason) {
928
- if (!this.#enabled || !isMarkupOnlyStop(reason, { sawToolCall: this.#sawToolCall, text: this.#text() })) {
965
+ const text2 = this.#text();
966
+ const markupOnly = isMarkupOnlyStop(reason, { sawToolCall: this.#sawToolCall, text: text2 });
967
+ const pendingAction = reason.kind === "stop" && !this.#sawToolCall && isPendingActionTurn(text2);
968
+ if (!this.#enabled || !markupOnly && !pendingAction) {
929
969
  return reason;
930
970
  }
931
971
  this.#notify();
932
- return { kind: "error", failure: { code: EMPTY_RESPONSE_CODE, message: EMPTY_TURN_MESSAGE } };
972
+ return { kind: "error", failure: { code: OPENDESIGN_EOT, message: pendingAction ? INCOMPLETE_TURN_MESSAGE : EMPTY_TURN_MESSAGE } };
933
973
  }
934
974
  /** Report one rewrite to the telemetry hook; monitoring must never break the stream. */
935
975
  #notify() {
@@ -949,7 +989,7 @@ var EmptyTurnTracker = class {
949
989
  };
950
990
 
951
991
  // src/protocols/index.ts
952
- import { LlmError as LlmError9 } from "@deepseek-ai/dsh-llm";
992
+ import { LlmError as LlmError10 } from "@deepseek-ai/dsh-llm";
953
993
 
954
994
  // src/protocols/chat-completions.ts
955
995
  import { LlmError as LlmError5 } from "@deepseek-ai/dsh-llm";
@@ -1010,12 +1050,12 @@ var chatCompletions = {
1010
1050
 
1011
1051
  // src/protocols/messages.ts
1012
1052
  import {
1013
- LlmError as LlmError7,
1053
+ LlmError as LlmError8,
1014
1054
  ToolCallId as ToolCallId2
1015
1055
  } from "@deepseek-ai/dsh-llm";
1016
1056
 
1017
1057
  // src/protocols/parts.ts
1018
- 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";
1019
1059
  function projectContent(blocks, image) {
1020
1060
  let text2 = "";
1021
1061
  const images = [];
@@ -1027,7 +1067,7 @@ function projectContent(blocks, image) {
1027
1067
  case "image": {
1028
1068
  const url = block.offloaded ? void 0 : image?.(block.attachment);
1029
1069
  if (url) images.push(url);
1030
- else text2 += `${text2 ? "\n" : ""}${textOnlyImageText2(block.attachment)}`;
1070
+ else text2 += `${text2 ? "\n" : ""}${block.offloaded ? offloadedImageText2(block.attachment) : textOnlyImageText2(block.attachment)}`;
1031
1071
  break;
1032
1072
  }
1033
1073
  case "file":
@@ -1077,10 +1117,83 @@ function anthropicUsage(raw) {
1077
1117
  };
1078
1118
  }
1079
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
+
1080
1159
  // src/protocols/messages.ts
1081
1160
  var MESSAGES_DEFAULT_MAX_TOKENS = 4096;
1082
1161
  var ANTHROPIC_VERSION = "2023-06-01";
1083
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
+ }
1084
1197
  function messagesURL(baseURL) {
1085
1198
  return inferenceEndpoint(baseURL, "messages");
1086
1199
  }
@@ -1094,15 +1207,17 @@ function toolInput(argumentsText) {
1094
1207
  try {
1095
1208
  parsed = JSON.parse(argumentsText);
1096
1209
  } catch {
1097
- 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");
1098
1211
  }
1099
- 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");
1100
1213
  return parsed;
1101
1214
  }
1102
1215
  function buildMessagesRequest(ctx) {
1103
1216
  const { options, model } = ctx;
1217
+ validateClaudeSampling(model.id, options.temperature, ctx.topP);
1104
1218
  const maxTokens = options.maxTokens ?? MESSAGES_DEFAULT_MAX_TOKENS;
1105
- 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");
1106
1221
  const system = [];
1107
1222
  const messages2 = [];
1108
1223
  const lookup = ctx.images.size ? (ref) => ctx.images.get(ref.attachmentId) : void 0;
@@ -1142,9 +1257,17 @@ function buildMessagesRequest(ctx) {
1142
1257
  }
1143
1258
  case "assistant": {
1144
1259
  const content2 = [];
1145
- if (projected.text) content2.push({ type: "text", text: projected.text });
1146
- for (const block of message.content) {
1147
- 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
+ }
1148
1271
  }
1149
1272
  if (content2.length) messages2.push({ role: "assistant", content: content2 });
1150
1273
  break;
@@ -1174,14 +1297,14 @@ function buildMessagesRequest(ctx) {
1174
1297
  else if (protocolAcceptsEffort("messages", effort)) {
1175
1298
  body.thinking = { type: "adaptive" };
1176
1299
  body.output_config = { effort };
1177
- } 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");
1178
1301
  }
1179
1302
  return { url: messagesURL(ctx.baseURL), headers: streamHeaders(ctx.apiKey, { "anthropic-version": ANTHROPIC_VERSION }), body };
1180
1303
  }
1181
1304
  function num(value) {
1182
1305
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1183
1306
  }
1184
- async function* streamMessages(body, signal, idleMs) {
1307
+ async function* streamMessages(body, signal, idleMs, context) {
1185
1308
  let nextIndex = 0;
1186
1309
  let count2 = 0;
1187
1310
  let finish;
@@ -1195,9 +1318,14 @@ async function* streamMessages(body, signal, idleMs) {
1195
1318
  cacheWrite: void 0
1196
1319
  };
1197
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
+ }
1198
1326
  function stateAt(index) {
1199
1327
  const state = typeof index === "number" ? blocks.get(index) : void 0;
1200
- 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");
1201
1329
  return state;
1202
1330
  }
1203
1331
  function assign(state) {
@@ -1206,19 +1334,41 @@ async function* streamMessages(body, signal, idleMs) {
1206
1334
  count2++;
1207
1335
  }
1208
1336
  }
1209
- function close() {
1337
+ function close(only) {
1210
1338
  const out = [];
1211
1339
  for (const state of blocks.values()) {
1212
- if (!state.started) continue;
1340
+ if (!state.started || state.ended || only !== void 0 && state !== only) continue;
1341
+ state.ended = true;
1213
1342
  if (state.kind === "text") out.push({ type: "block-end", index: state.index, block: { type: "text", text: state.text } });
1214
- 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 } });
1215
1344
  else if (state.kind === "tool") {
1216
- if (!state.id || !state.name) throw new LlmError7("OpenDesign\uFF1A\u5DE5\u5177\u8C03\u7528\u7F3A\u5C11\u6807\u8BC6\u6216\u540D\u79F0", "INVALID_RESPONSE");
1217
- 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 } });
1218
1348
  }
1219
1349
  }
1220
1350
  return out.sort((a, b) => ("index" in a ? a.index : 0) - ("index" in b ? b.index : 0));
1221
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
+ }
1222
1372
  function reasonFromStop(stop) {
1223
1373
  switch (stop) {
1224
1374
  case "end_turn":
@@ -1230,23 +1380,24 @@ async function* streamMessages(body, signal, idleMs) {
1230
1380
  case "tool_use":
1231
1381
  return { kind: "tool-calls" };
1232
1382
  case "refusal":
1233
- 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");
1234
1384
  case "pause_turn":
1235
- 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");
1236
1386
  default:
1237
- 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");
1238
1388
  }
1239
1389
  }
1240
1390
  for await (const frame of sseFrames(body, signal, idleMs)) {
1391
+ signal.throwIfAborted();
1241
1392
  let value;
1242
1393
  try {
1243
1394
  value = JSON.parse(frame.data);
1244
1395
  } catch {
1245
- 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");
1246
1397
  }
1247
- 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");
1248
1399
  const type = typeof value.type === "string" && value.type !== "" ? value.type : frame.event;
1249
- 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");
1250
1401
  const out = [];
1251
1402
  switch (type) {
1252
1403
  case "message_start": {
@@ -1260,39 +1411,66 @@ async function* streamMessages(body, signal, idleMs) {
1260
1411
  }
1261
1412
  case "content_block_start": {
1262
1413
  const index = value.index;
1263
- 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");
1264
1415
  const block = record(value.content_block) ? value.content_block : {};
1265
1416
  const kind = typeof block.type === "string" ? block.type : "";
1266
- 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
+ };
1267
1432
  if (kind === "text") state.kind = "text";
1268
1433
  else if (kind === "thinking") state.kind = "reasoning";
1434
+ else if (kind === "redacted_thinking") state.kind = "redacted";
1269
1435
  else if (kind === "tool_use") state.kind = "tool";
1270
1436
  if (state.kind === "tool") {
1271
1437
  state.id = typeof block.id === "string" ? block.id : "";
1272
1438
  state.name = typeof block.name === "string" ? block.name : "";
1273
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
+ }
1274
1444
  }
1275
1445
  if (state.kind === "text" && typeof block.text === "string" && block.text !== "") state.text = block.text;
1276
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);
1277
1453
  blocks.set(index, state);
1278
1454
  if (state.kind === "tool") {
1279
1455
  assign(state);
1280
1456
  state.started = true;
1281
1457
  out.push({ type: "block-start", index: state.index, blockType: "tool-call" });
1282
1458
  if (state.id) out.push({ type: "tool-call-delta", index: state.index, id: ToolCallId2(state.id), ...state.name ? { name: state.name } : {}, argumentsDelta: "" });
1283
- } else if ((state.kind === "text" || state.kind === "reasoning") && state.text !== "") {
1459
+ } else if (state.kind === "text" || state.kind === "reasoning" || state.kind === "redacted") {
1284
1460
  assign(state);
1285
1461
  state.started = true;
1286
1462
  out.push({ type: "block-start", index: state.index, blockType: state.kind === "text" ? "text" : "reasoning" });
1287
- 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 });
1288
1464
  }
1289
1465
  break;
1290
1466
  }
1291
1467
  case "content_block_delta": {
1292
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");
1293
1470
  const delta = record(value.delta) ? value.delta : {};
1294
1471
  const deltaType = typeof delta.type === "string" ? delta.type : "";
1295
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");
1296
1474
  const text2 = typeof delta.text === "string" ? delta.text : "";
1297
1475
  if (!text2) break;
1298
1476
  assign(state);
@@ -1301,10 +1479,12 @@ async function* streamMessages(body, signal, idleMs) {
1301
1479
  out.push({ type: "block-start", index: state.index, blockType: "text" });
1302
1480
  }
1303
1481
  state.text += text2;
1482
+ account(text2);
1304
1483
  out.push({ type: "text-delta", index: state.index, text: text2 });
1305
1484
  break;
1306
1485
  }
1307
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");
1308
1488
  const text2 = typeof delta.thinking === "string" ? delta.thinking : "";
1309
1489
  if (!text2) break;
1310
1490
  assign(state);
@@ -1313,16 +1493,32 @@ async function* streamMessages(body, signal, idleMs) {
1313
1493
  out.push({ type: "block-start", index: state.index, blockType: "reasoning" });
1314
1494
  }
1315
1495
  state.text += text2;
1496
+ account(text2);
1316
1497
  out.push({ type: "reasoning-delta", index: state.index, text: text2 });
1317
1498
  break;
1318
1499
  }
1319
1500
  if (deltaType === "input_json_delta") {
1320
- 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");
1321
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;
1322
1505
  state.args += part;
1506
+ account(part);
1323
1507
  if (state.id) out.push({ type: "tool-call-delta", index: state.index, id: ToolCallId2(state.id), ...state.name ? { name: state.name } : {}, argumentsDelta: part });
1324
1508
  break;
1325
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;
1326
1522
  break;
1327
1523
  }
1328
1524
  case "message_delta": {
@@ -1337,13 +1533,18 @@ async function* streamMessages(body, signal, idleMs) {
1337
1533
  }
1338
1534
  case "message_stop": {
1339
1535
  const reason = reasonFromStop(stopReason);
1340
- 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");
1341
- 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();
1342
1542
  usage = anthropicUsage(raw) ?? usage;
1343
1543
  out.push(...close());
1344
1544
  if (usage) out.push({ type: "usage", usage });
1345
1545
  finish = reason;
1346
- out.push({ type: "finish", reason });
1546
+ const replayState = replay();
1547
+ out.push({ type: "finish", reason, ...replayState === void 0 ? {} : { replayState } });
1347
1548
  break;
1348
1549
  }
1349
1550
  case "error":
@@ -1352,11 +1553,14 @@ async function* streamMessages(body, signal, idleMs) {
1352
1553
  default:
1353
1554
  break;
1354
1555
  }
1355
- for (const chunk of out) yield chunk;
1556
+ for (const chunk of out) {
1557
+ signal.throwIfAborted();
1558
+ yield chunk;
1559
+ }
1356
1560
  if (finish) break;
1357
1561
  }
1358
1562
  signal.throwIfAborted();
1359
- if (!finish) throw new LlmError7("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u4E8B\u4EF6", "INVALID_RESPONSE");
1563
+ if (!finish) throw new PrematureEndError("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u4E8B\u4EF6");
1360
1564
  }
1361
1565
  var messages = {
1362
1566
  id: "messages",
@@ -1366,7 +1570,7 @@ var messages = {
1366
1570
 
1367
1571
  // src/protocols/responses.ts
1368
1572
  import {
1369
- LlmError as LlmError8,
1573
+ LlmError as LlmError9,
1370
1574
  ToolCallId as ToolCallId3
1371
1575
  } from "@deepseek-ai/dsh-llm";
1372
1576
  function userContent(text2, images) {
@@ -1424,15 +1628,15 @@ function buildResponsesRequest(ctx) {
1424
1628
  if (options.temperature !== void 0) body.temperature = options.temperature;
1425
1629
  if (ctx.topP !== void 0) body.top_p = ctx.topP;
1426
1630
  if (options.maxTokens !== void 0) {
1427
- 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");
1428
1632
  body.max_output_tokens = options.maxTokens;
1429
1633
  }
1430
1634
  if (options.reasoningEffort !== void 0) {
1431
1635
  const effort = String(options.reasoningEffort);
1432
- 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");
1433
1637
  body.reasoning = { effort, summary: "auto" };
1434
1638
  }
1435
- 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");
1436
1640
  return { url: inferenceEndpoint(ctx.baseURL, "responses"), headers: streamHeaders(ctx.apiKey), body };
1437
1641
  }
1438
1642
  function str(value) {
@@ -1528,7 +1732,7 @@ async function* streamResponses(body, signal, idleMs) {
1528
1732
  let delta = "";
1529
1733
  if (args !== void 0) {
1530
1734
  if (typeof args !== "string" || !args.startsWith(call.args)) {
1531
- 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");
1532
1736
  }
1533
1737
  delta = args.slice(call.args.length);
1534
1738
  call.args = args;
@@ -1576,7 +1780,7 @@ async function* streamResponses(body, signal, idleMs) {
1576
1780
  for (const state of texts.values()) if (state.started) out.push({ type: "block-end", index: state.index, block: { type: "text", text: state.text } });
1577
1781
  for (const state of reasonings.values()) if (state.started) out.push({ type: "block-end", index: state.index, block: { type: "reasoning", text: state.text } });
1578
1782
  for (const call of calls.values()) {
1579
- 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");
1580
1784
  out.push({ type: "block-end", index: call.index, block: { type: "tool-call", id: ToolCallId3(call.id), name: call.name, arguments: call.args } });
1581
1785
  }
1582
1786
  return out.sort((a, b) => ("index" in a ? a.index : 0) - ("index" in b ? b.index : 0));
@@ -1586,8 +1790,8 @@ async function* streamResponses(body, signal, idleMs) {
1586
1790
  const details = record(response.incomplete_details) ? response.incomplete_details : {};
1587
1791
  const why = str(details.reason) ?? "";
1588
1792
  if (why === "max_tokens" || why === "max_output_tokens") return { kind: "max-tokens" };
1589
- if (why === "content_filter") throw new LlmError8("OpenDesign\uFF1A\u6A21\u578B\u54CD\u5E94\u88AB\u5185\u5BB9\u8FC7\u6EE4", "INVALID_RESPONSE");
1590
- 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");
1591
1795
  }
1592
1796
  const output = Array.isArray(response.output) ? response.output : [];
1593
1797
  return output.some((item) => record(item) && item.type === "function_call") || calls.size > 0 ? { kind: "tool-calls" } : { kind: "stop" };
@@ -1598,11 +1802,11 @@ async function* streamResponses(body, signal, idleMs) {
1598
1802
  try {
1599
1803
  value = JSON.parse(frame.data);
1600
1804
  } catch {
1601
- 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");
1602
1806
  }
1603
- 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");
1604
1808
  const type = str(value.type) ?? frame.event;
1605
- 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");
1606
1810
  const out = [];
1607
1811
  switch (type) {
1608
1812
  case "response.output_item.added": {
@@ -1688,8 +1892,8 @@ async function* streamResponses(body, signal, idleMs) {
1688
1892
  usage = responseUsage(response) ?? usage;
1689
1893
  hydrate(response.output, out);
1690
1894
  const reason = reasonOf(type, response);
1691
- 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");
1692
- 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");
1693
1897
  out.push(...close());
1694
1898
  if (usage) out.push({ type: "usage", usage });
1695
1899
  finish = reason;
@@ -1705,7 +1909,7 @@ async function* streamResponses(body, signal, idleMs) {
1705
1909
  if (finish) break;
1706
1910
  }
1707
1911
  signal.throwIfAborted();
1708
- if (!finish) throw new LlmError8("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u4E8B\u4EF6", "INVALID_RESPONSE");
1912
+ if (!finish) throw new PrematureEndError("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u4E8B\u4EF6");
1709
1913
  }
1710
1914
  var responses = {
1711
1915
  id: "responses",
@@ -1721,7 +1925,7 @@ var PROTOCOLS = {
1721
1925
  };
1722
1926
  function protocolFor(id) {
1723
1927
  const protocol = PROTOCOLS[id];
1724
- 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");
1725
1929
  return protocol;
1726
1930
  }
1727
1931
 
@@ -1729,7 +1933,7 @@ function protocolFor(id) {
1729
1933
  function group(provider) {
1730
1934
  if (provider === PLAN_PROVIDER) return "plan";
1731
1935
  if (provider === PAID_PROVIDER) return "paid";
1732
- throw new LlmError10("\u672A\u77E5\u7684 CoRouter Provider", "INVALID_REQUEST");
1936
+ throw new LlmError11("\u672A\u77E5\u7684 CoRouter Provider", "INVALID_REQUEST");
1733
1937
  }
1734
1938
  function outputReserve(model, protocol) {
1735
1939
  const limit = model.maxOutputTokens ?? (protocol === "messages" ? 4096 : void 0);
@@ -1737,7 +1941,8 @@ function outputReserve(model, protocol) {
1737
1941
  }
1738
1942
  function metadata(provider, row, config) {
1739
1943
  const setting = config.modelSettings?.[row.id];
1740
- 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;
1741
1946
  const efforts = modelReasoningEfforts(row, config.apiProtocol ?? "chat-completions");
1742
1947
  const defaultEffort = setting?.reasoningEffort !== void 0 && efforts?.includes(setting.reasoningEffort) ? setting.reasoningEffort : void 0;
1743
1948
  return {
@@ -1760,24 +1965,60 @@ var CoRouterAdapter = class extends LlmAdapter {
1760
1965
  }
1761
1966
  options;
1762
1967
  #lifetime = new AbortController();
1968
+ #credentialSecret = randomBytes(32);
1763
1969
  dispose() {
1764
- 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
+ }
1765
2003
  }
1766
2004
  providerInfo(provider) {
1767
2005
  return { id: provider, name: group(provider) === "plan" ? "OpenDesign CoRouter \xB7 \u5957\u9910\u8D60\u9001" : "OpenDesign CoRouter \xB7 \u4ED8\u8D39\u6A21\u578B" };
1768
2006
  }
1769
2007
  modelOf(provider, id, config) {
1770
2008
  const row = (this.options.models?.() ?? MODELS).find((candidate) => candidate.id === id);
1771
- 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");
1772
- 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");
1773
2011
  const configured = applyModelSettings(row, config.modelSettings?.[id]);
1774
2012
  const output = config.modelSettings?.[id]?.maxTokens;
1775
- 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");
1776
2014
  return configured;
1777
2015
  }
1778
2016
  async listModels(provider) {
1779
2017
  const config = this.options.config(), selectedGroup = group(provider);
1780
- 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
+ });
1781
2022
  }
1782
2023
  async resolveModel(provider, model, signal) {
1783
2024
  signal?.throwIfAborted();
@@ -1799,18 +2040,32 @@ var CoRouterAdapter = class extends LlmAdapter {
1799
2040
  const setting = config.modelSettings?.[row.id] ?? {};
1800
2041
  const protocolId = config.apiProtocol ?? "chat-completions";
1801
2042
  const effort = options.reasoningEffort ?? (setting.reasoningEffort ? ReasoningEffortId(setting.reasoningEffort) : void 0);
1802
- 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
+ }
1803
2048
  const raw = await this.options.apiKey(config.apiKeyEnv, config.baseURL);
1804
- 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");
1805
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
+ }
1806
2061
  const images = /* @__PURE__ */ new Map();
1807
2062
  const attemptedImages = /* @__PURE__ */ new Set();
1808
2063
  const unreadableImages = /* @__PURE__ */ new Set();
1809
- 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) {
1810
2065
  if (block.type !== "image" || block.offloaded || attemptedImages.has(block.attachment.attachmentId)) continue;
1811
2066
  attemptedImages.add(block.attachment.attachmentId);
1812
2067
  try {
1813
- const url = await this.options.imageDataUrl(block.attachment, signal);
2068
+ const url = await this.options.imageDataUrl?.(block.attachment, signal);
1814
2069
  signal.throwIfAborted();
1815
2070
  if (url) images.set(block.attachment.attachmentId, url);
1816
2071
  else unreadableImages.add(block.attachment.attachmentId);
@@ -1830,10 +2085,10 @@ var CoRouterAdapter = class extends LlmAdapter {
1830
2085
  const tools = chatTools(options);
1831
2086
  let maxTokens = options.maxTokens ?? setting.maxTokens ?? outputReserve(row, protocolId);
1832
2087
  if (maxTokens !== void 0) {
1833
- 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");
1834
2089
  const capped = Math.min(maxTokens, row.maxOutputTokens ?? maxTokens);
1835
2090
  const room = row.contextWindow === void 0 ? capped : row.contextWindow - estimateTokens({ messages: messages2, tools });
1836
- 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");
1837
2092
  maxTokens = Math.min(capped, Math.floor(room));
1838
2093
  }
1839
2094
  const effective = {
@@ -1843,7 +2098,15 @@ var CoRouterAdapter = class extends LlmAdapter {
1843
2098
  ...effort === void 0 ? {} : { reasoningEffort: effort }
1844
2099
  };
1845
2100
  const protocol = protocolFor(protocolId);
1846
- 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
+ });
1847
2110
  let response;
1848
2111
  try {
1849
2112
  response = await (this.options.fetch ?? fetch)(request.url, {
@@ -1855,7 +2118,7 @@ var CoRouterAdapter = class extends LlmAdapter {
1855
2118
  });
1856
2119
  } catch {
1857
2120
  if (options.signal?.aborted || this.#lifetime.signal.aborted) signal.throwIfAborted();
1858
- 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");
1859
2122
  }
1860
2123
  if (!response.ok) {
1861
2124
  let error = {};
@@ -1883,24 +2146,191 @@ var CoRouterAdapter = class extends LlmAdapter {
1883
2146
  }
1884
2147
  throw gatewayError(response.status, error);
1885
2148
  }
1886
- if (!response.body) throw new LlmError10("CoRouter \u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
1887
2149
  const monitor = row.group === "plan" && row.id === "deepseek-v4.1-flash" && config.emptyTurnGuard && Boolean(options.tools?.length);
1888
- const tracker = new EmptyTurnTracker({ enabled: monitor, onEmptyTurn: () => this.options.onEmptyTurn?.() });
2150
+ const reportEmptyTurn = () => {
2151
+ try {
2152
+ this.options.onEmptyTurn?.();
2153
+ } catch {
2154
+ }
2155
+ };
2156
+ if (!response.body) {
2157
+ if (monitor) reportEmptyTurn();
2158
+ throw new LlmError11("CoRouter \u8FD4\u56DE\u7A7A\u54CD\u5E94", monitor ? OPENDESIGN_EOT : "EMPTY_RESPONSE");
2159
+ }
2160
+ const tracker = new EmptyTurnTracker({ enabled: monitor, onEmptyTurn: reportEmptyTurn });
1889
2161
  try {
1890
- 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();
1891
2169
  tracker.observe(chunk);
1892
- if (chunk.type === "finish" && monitor) yield { ...chunk, reason: tracker.resolve(chunk.reason) };
1893
- 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;
1894
2175
  }
1895
2176
  } catch (error) {
1896
2177
  if (options.signal?.aborted || this.#lifetime.signal.aborted) signal.throwIfAborted();
1897
- if (signal.aborted) throw new LlmError10("CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6", "TIMEOUT");
1898
- if (error instanceof LlmError10) throw error;
1899
- throw new LlmError10("CoRouter \u54CD\u5E94\u6D41\u8FDE\u63A5\u4E2D\u65AD", "SERVER");
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") {
2181
+ reportEmptyTurn();
2182
+ throw new LlmError11(error.message, OPENDESIGN_EOT);
2183
+ }
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);
1900
2266
  }
1901
2267
  }
1902
2268
  };
1903
2269
 
2270
+ // src/eot-recovery.ts
2271
+ import { randomUUID } from "node:crypto";
2272
+ var POLICY_KEY = "opendesign-eot-unbounded-v1";
2273
+ var INITIAL_DELAY_MS = 500;
2274
+ var MAX_DELAY_MS = 1e4;
2275
+ function cancellableDelay(delay, signal) {
2276
+ if (signal.aborted) return Promise.resolve(false);
2277
+ return new Promise((resolve) => {
2278
+ const timer = setTimeout(() => {
2279
+ signal.removeEventListener("abort", onAbort);
2280
+ resolve(true);
2281
+ }, delay);
2282
+ const onAbort = () => {
2283
+ clearTimeout(timer);
2284
+ resolve(false);
2285
+ };
2286
+ signal.addEventListener("abort", onAbort, { once: true });
2287
+ });
2288
+ }
2289
+ var EotRecovery = class {
2290
+ constructor(enabled, wait = cancellableDelay) {
2291
+ this.enabled = enabled;
2292
+ this.wait = wait;
2293
+ }
2294
+ enabled;
2295
+ wait;
2296
+ #lifetime = new AbortController();
2297
+ #states = /* @__PURE__ */ new WeakMap();
2298
+ #active = /* @__PURE__ */ new Set();
2299
+ handle = (payload, next) => {
2300
+ if (payload.provider !== PLAN_PROVIDER || payload.failure.code !== OPENDESIGN_EOT || !this.enabled()) return next();
2301
+ if (payload.signal.aborted || this.#lifetime.signal.aborted) return Promise.resolve(void 0);
2302
+ const operation = this.#recover(payload);
2303
+ const tracked = operation.finally(() => this.#active.delete(tracked));
2304
+ this.#active.add(tracked);
2305
+ return tracked;
2306
+ };
2307
+ async #recover({ agent, turn, step, provider, failure, signal }) {
2308
+ const fused = AbortSignal.any([signal, this.#lifetime.signal]);
2309
+ if (fused.aborted) return;
2310
+ const previous = this.#states.get(agent);
2311
+ const state = previous?.turn === turn && previous.step === step ? { ...previous, retry: previous.retry + 1 } : { turn, step, retryId: randomUUID(), retry: 1 };
2312
+ this.#states.set(agent, state);
2313
+ const delayMs = Math.min(INITIAL_DELAY_MS * 2 ** Math.min(state.retry - 1, 8), MAX_DELAY_MS);
2314
+ agent.session.append("llm/retry", { retryId: state.retryId, turn, step, provider, mode: "always", policyKey: POLICY_KEY, retry: state.retry, delayMs, failure });
2315
+ if (!await this.wait(delayMs, fused) || fused.aborted || !this.enabled()) return;
2316
+ agent.session.append("llm/retry-started", { retryId: state.retryId, turn, step, retry: state.retry });
2317
+ return { kind: "retry" };
2318
+ }
2319
+ async dispose() {
2320
+ this.#lifetime.abort(new Error("EOT recovery disposed"));
2321
+ await Promise.allSettled([...this.#active]);
2322
+ }
2323
+ };
2324
+ function installEotRecovery(ctx, enabled) {
2325
+ const recovery = new EotRecovery(enabled);
2326
+ const events = ctx;
2327
+ const remove = events.on("agent/request-error", recovery.handle, { prepend: true });
2328
+ ctx.effect(() => async () => {
2329
+ remove();
2330
+ await recovery.dispose();
2331
+ });
2332
+ }
2333
+
1904
2334
  // src/model-discovery.ts
1905
2335
  import { attributionHeaders as attributionHeaders2 } from "@deepseek-ai/dsh-llm";
1906
2336
  var DISCOVERY_TIMEOUT_MS = 2e4;
@@ -2535,11 +2965,11 @@ async function resolveSession(deps = {}) {
2535
2965
  }
2536
2966
 
2537
2967
  // src/login.ts
2538
- import { randomUUID } from "node:crypto";
2968
+ import { randomUUID as randomUUID2 } from "node:crypto";
2539
2969
 
2540
2970
  // src/device-auth.ts
2541
2971
  var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
2542
- var DEVICE_AUTH_PLUGIN_VERSION = "0.1.10";
2972
+ var DEVICE_AUTH_PLUGIN_VERSION = "0.1.12";
2543
2973
  var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
2544
2974
  var DEVICE_RESPONSE_MAX_BYTES = 65536;
2545
2975
  var DEVICE_POLL_MIN_MS = 1e3;
@@ -2773,7 +3203,7 @@ var ConsoleLogin = class {
2773
3203
  const requested = this.options.timeoutMs;
2774
3204
  const timeoutMs = typeof requested === "number" && Number.isFinite(requested) && requested > 0 ? Math.min(MAX_TIMEOUT_MS, requested) : MAX_TIMEOUT_MS;
2775
3205
  const job = {
2776
- id: randomUUID(),
3206
+ id: randomUUID2(),
2777
3207
  controller: new AbortController(),
2778
3208
  deadline: started + timeoutMs,
2779
3209
  status: { jobId: null, state: "launching", startedAt: new Date(started).toISOString(), message: "\u6B63\u5728\u7533\u8BF7\u5B98\u65B9\u8BBE\u5907\u6388\u6743\u7801" },
@@ -3519,6 +3949,12 @@ function parseEfforts(value) {
3519
3949
  if (!Array.isArray(value) || value.length > 16) throw new Error("\u6A21\u578B\u601D\u8003\u6863\u4F4D\u683C\u5F0F\u65E0\u6548");
3520
3950
  return value.map((item) => text(item, "\u601D\u8003\u6863\u4F4D", 32));
3521
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
+ }
3522
3958
  function member(value, allowed, label) {
3523
3959
  const hit = allowed.find((candidate) => candidate === value);
3524
3960
  if (hit === void 0) throw new Error(`${label} \u4E0D\u5728\u5141\u8BB8\u7684\u53D6\u503C\u5185`);
@@ -3633,6 +4069,7 @@ function parseStatusModel(value) {
3633
4069
  name: text(value.name, "\u6A21\u578B\u540D", 128),
3634
4070
  group: member(value.group, MODEL_GROUPS, "\u6A21\u578B\u5206\u7EC4"),
3635
4071
  ...value.enabled === void 0 ? {} : { enabled: flag(value.enabled, "\u6A21\u578B\u542F\u7528\u72B6\u6001") },
4072
+ ...value.inputModalities === void 0 ? {} : { inputModalities: parseModalities(value.inputModalities) },
3636
4073
  ...value.contextWindow === void 0 ? {} : { contextWindow: positiveInteger(value.contextWindow, "\u4E0A\u4E0B\u6587\u9884\u7B97", 1e8) },
3637
4074
  ...value.maxOutputTokens === void 0 ? {} : { maxOutputTokens: positiveInteger(value.maxOutputTokens, "\u6700\u5927\u8F93\u51FA", 1e7) },
3638
4075
  ...value.reasoningEfforts === void 0 ? {} : { reasoningEfforts: parseEfforts(value.reasoningEfforts) }
@@ -3706,8 +4143,8 @@ function parseActivationOpenState(value) {
3706
4143
  // src/index.ts
3707
4144
  var name = "llm-opendesign-corouter";
3708
4145
  var inject = ["llm"];
3709
- var API_KEY = credentialKey(name, "api-key");
3710
- var SESSION = credentialKey(name, "console");
4146
+ var API_KEY = credentialKey2(name, "api-key");
4147
+ var SESSION = credentialKey2(name, "console");
3711
4148
  var hash = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
3712
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" });
3713
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" });
@@ -3727,7 +4164,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
3727
4164
  __publicField(this, "_login");
3728
4165
  __publicField(this, "_activation");
3729
4166
  __publicField(this, "_lifetime", new AbortController());
3730
- __publicField(this, "_revision", randomUUID2());
4167
+ __publicField(this, "_revision", randomUUID3());
3731
4168
  __publicField(this, "_fingerprint", "");
3732
4169
  __publicField(this, "_quota", unreadQuota());
3733
4170
  __publicField(this, "_quotaAt", 0);
@@ -3836,7 +4273,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
3836
4273
  const fingerprint = hash(state);
3837
4274
  if (fingerprint !== this._fingerprint) {
3838
4275
  this._fingerprint = fingerprint;
3839
- this._revision = randomUUID2();
4276
+ this._revision = randomUUID3();
3840
4277
  }
3841
4278
  return state;
3842
4279
  }
@@ -3871,13 +4308,14 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
3871
4308
  config: state.config,
3872
4309
  guardedTurns: this.guardedTurns,
3873
4310
  models: this._models.map((row) => {
3874
- const { id, name: name2, group: group2, contextWindow, maxOutputTokens } = row;
4311
+ const { id, name: name2, group: group2, contextWindow, maxOutputTokens, inputModalities } = row;
3875
4312
  const reasoningEfforts = modelReasoningEfforts(row, state.config.apiProtocol ?? "chat-completions");
3876
4313
  return {
3877
4314
  id,
3878
4315
  name: name2,
3879
4316
  group: group2,
3880
4317
  enabled: isModelEnabled(id, state.config.modelSettings),
4318
+ ...inputModalities === void 0 ? {} : { inputModalities },
3881
4319
  ...contextWindow === void 0 ? {} : { contextWindow },
3882
4320
  ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
3883
4321
  ...reasoningEfforts === void 0 ? {} : { reasoningEfforts }
@@ -4105,10 +4543,12 @@ __decoratorMetadata(_init, OpenDesignCoRouterService);
4105
4543
  function apply(ctx, config) {
4106
4544
  const current = () => readConfig(config);
4107
4545
  current();
4546
+ installEotRecovery(ctx, () => current().emptyTurnGuard);
4108
4547
  ctx.inject(["settings"], (scope) => scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)));
4109
4548
  let modelsChanged = () => {
4110
4549
  };
4111
4550
  const service = new OpenDesignCoRouterService(ctx, current, { resolveSession, readQuota, readDesktopQuota, modelsChanged: () => modelsChanged() });
4551
+ const replayKeys = new ReplayKeyStore(() => ctx.get("credentials"));
4112
4552
  const adapter = new CoRouterAdapter({
4113
4553
  config: current,
4114
4554
  models: () => service.modelCatalog(),
@@ -4116,6 +4556,7 @@ function apply(ctx, config) {
4116
4556
  onEmptyTurn: () => {
4117
4557
  service.guardedTurns++;
4118
4558
  },
4559
+ replayBindingSecret: (signal) => replayKeys.get(signal),
4119
4560
  imageDataUrl: async (ref, signal) => {
4120
4561
  const attachments = ctx.get("attachments");
4121
4562
  if (!attachments) return void 0;
@@ -4133,18 +4574,24 @@ function apply(ctx, config) {
4133
4574
  modelsChanged();
4134
4575
  });
4135
4576
  ctx.llm.registerModelDiscovery(SETTINGS_NS, async (request, signal) => {
4136
- 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");
4137
4578
  const config2 = current();
4138
4579
  const key = request.apiKey ?? await service.resolveApiKey(config2.apiKeyEnv, config2.baseURL);
4139
- 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");
4140
4581
  const models = await fetchModelCatalog(config2.baseURL, key, signal);
4141
- 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
+ });
4142
4586
  });
4143
4587
  ctx.llm.registerConfigurableProviders([
4144
4588
  { provider: PLAN_PROVIDER, displayName: "OpenDesign CoRouter \xB7 \u5957\u9910\u8D60\u9001", settingsNs: SETTINGS_NS, settingsPath: [], defaultBaseURL: current().baseURL },
4145
4589
  { provider: PAID_PROVIDER, displayName: "OpenDesign CoRouter \xB7 \u4ED8\u8D39\u6A21\u578B", settingsNs: SETTINGS_NS, settingsPath: [], defaultBaseURL: current().baseURL }
4146
4590
  ]);
4147
- ctx.effect(() => () => adapter.dispose());
4591
+ ctx.effect(() => () => {
4592
+ adapter.dispose();
4593
+ replayKeys.dispose();
4594
+ });
4148
4595
  }
4149
4596
  export {
4150
4597
  CoRouterAdapter,