dsh-opendesign-corouter 0.1.13 → 0.1.15

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,19 +48,21 @@ var __privateSet = (obj, member2, value, setter) => (__accessCheck(obj, member2,
48
48
  var __privateMethod = (obj, member2, method) => (__accessCheck(obj, member2, "access private method"), method);
49
49
 
50
50
  // src/index.ts
51
- import { randomUUID as randomUUID3, createHash } from "node:crypto";
51
+ import { randomUUID as randomUUID3, createHash as createHash2 } from "node:crypto";
52
52
  import { credentialKey as credentialKey2, credentialRef } from "@deepseek-ai/dsh-credentials";
53
53
  import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
54
54
  import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
55
- import { LlmError as LlmError13 } from "@deepseek-ai/dsh-llm";
55
+ import { LlmError as LlmError14 } from "@deepseek-ai/dsh-llm";
56
56
 
57
57
  // src/adapter.ts
58
58
  import { createHmac, randomBytes } from "node:crypto";
59
59
  import {
60
+ IMAGE_OFFLOAD_REQUIRED_CODE,
60
61
  LlmAdapter,
61
62
  LlmError as LlmError11,
62
63
  ReasoningEffortId,
63
- assertUsableApiKey
64
+ assertUsableApiKey,
65
+ requiredImageOffload
64
66
  } from "@deepseek-ai/dsh-llm";
65
67
 
66
68
  // src/catalog.ts
@@ -322,6 +324,11 @@ function serializableTransform(callback) {
322
324
  });
323
325
  }
324
326
 
327
+ // src/image-budget.ts
328
+ var MIN_REQUEST_IMAGE_BYTES = 1024 * 1024;
329
+ var DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
330
+ var MAX_REQUEST_IMAGE_BYTES = 100 * 1024 * 1024;
331
+
325
332
  // src/config.ts
326
333
  var SETTINGS_NS = "llm-opendesign-corouter";
327
334
  var PLAN_PROVIDER = "opendesign-corouter-plan";
@@ -333,10 +340,13 @@ var Config = Schema.object({
333
340
  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(),
334
341
  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(),
335
342
  useDesktopCredential: Schema.boolean().default(true).description("\u4F18\u5148\u8BFB\u53D6 OpenDesign \u684C\u9762\u7AEF\u767B\u5F55\u6001\u67E5\u8BE2\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(),
343
+ emptyTurnGuard: Schema.boolean().default(true).description("\u4FDD\u62A4 DeepSeek V4.1 Flash \u5DE5\u5177\u5BF9\u8BDD\uFF1A\u6062\u590D\u7A7A\u56DE\u7B54\uFF0C\u5E76\u5728\u7ED3\u675F\u524D\u8FDB\u884C\u6709\u754C\u7684\u7ED3\u6784\u5316\u6536\u5C3E\u6838\u9A8C").volatile(),
344
+ turnReviewMaxContinuations: Schema.natural().min(1).max(10).default(3).description("\u6BCF\u8F6E\u4EFB\u52A1\u7684\u6536\u5C3E\u6838\u9A8C\u6700\u591A\u7EED\u529E\u6B21\u6570").volatile(),
345
+ turnReviewNoProgressLimit: Schema.natural().min(1).max(5).default(2).description("\u8FDE\u7EED\u7F3A\u5C11\u65B0\u6210\u529F\u5DE5\u5177\u7ED3\u679C\u65F6\u505C\u6B62\u6536\u5C3E\u7EED\u529E\u7684\u6B21\u6570").volatile(),
337
346
  quotaRefreshSeconds: Schema.natural().min(5).max(3600).default(60).description("\u989D\u5EA6\u81EA\u52A8\u5237\u65B0\u95F4\u9694\uFF08\u79D2\uFF09").volatile(),
338
347
  requestTimeoutMs: Schema.natural().min(1e3).max(36e5).default(18e5).description("\u63A8\u7406\u8BF7\u6C42\u603B\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile(),
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()
348
+ streamIdleTimeoutMs: Schema.natural().min(1e3).max(18e5).default(3e5).description("\u6D41\u5F0F\u54CD\u5E94\u65E0\u6570\u636E\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile(),
349
+ maxRequestImageBytes: Schema.natural().min(MIN_REQUEST_IMAGE_BYTES).max(MAX_REQUEST_IMAGE_BYTES).default(DEFAULT_MAX_REQUEST_IMAGE_BYTES).description("\u5355\u6B21\u8BF7\u6C42\u7684\u5185\u8054\u56FE\u7247\u9884\u7B97\uFF08\u5B57\u8282\uFF09").volatile()
340
350
  });
341
351
  function assertBaseURL(raw) {
342
352
  if (raw.length > 2048) throw new Error("\u63A8\u7406 Base URL \u6700\u591A\u5141\u8BB8 2048 \u5B57\u7B26");
@@ -362,7 +372,10 @@ function readConfig(config) {
362
372
  useDesktopCredential: config.useDesktopCredential.get(),
363
373
  emptyTurnGuard: config.emptyTurnGuard.get(),
364
374
  requestTimeoutMs: config.requestTimeoutMs.get(),
365
- streamIdleTimeoutMs: config.streamIdleTimeoutMs.get()
375
+ streamIdleTimeoutMs: config.streamIdleTimeoutMs.get(),
376
+ maxRequestImageBytes: config.maxRequestImageBytes.get(),
377
+ turnReviewMaxContinuations: config.turnReviewMaxContinuations.get(),
378
+ turnReviewNoProgressLimit: config.turnReviewNoProgressLimit.get()
366
379
  };
367
380
  }
368
381
 
@@ -516,6 +529,7 @@ var MESSAGES = {
516
529
  RATE_LIMIT: "OpenDesign\uFF1A\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",
517
530
  TIMEOUT: "OpenDesign\uFF1A\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",
518
531
  SERVER: "OpenDesign\uFF1A\u4E0A\u6E38\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",
532
+ REQUEST_TOO_LARGE: "OpenDesign\uFF1A\u8BF7\u6C42\u5185\u5BB9\u8D85\u8FC7\u4E0A\u6E38\u5927\u5C0F\u9650\u5236\uFF0C\u8BF7\u538B\u7F29\u5386\u53F2\u3001\u51CF\u5C11\u56FE\u7247\u6216\u7F29\u5C0F\u8F93\u5165\u540E\u91CD\u8BD5",
519
533
  INVALID_REQUEST: "OpenDesign\uFF1A\u8BF7\u6C42\u88AB\u4E0A\u6E38\u62D2\u7EDD",
520
534
  INVALID_RESPONSE: "OpenDesign\uFF1A\u4E0A\u6E38\u54CD\u5E94\u683C\u5F0F\u65E0\u6548"
521
535
  };
@@ -586,6 +600,7 @@ function classifyStatus(status) {
586
600
  if (status === 401) return "AUTH";
587
601
  if (status === 403) return "PERMISSION";
588
602
  if (status === 402) return QUOTA_EXCEEDED_CODE;
603
+ if (status === 413) return "REQUEST_TOO_LARGE";
589
604
  if (status === 429) return "RATE_LIMIT";
590
605
  if (status === 408 || status === 504) return "TIMEOUT";
591
606
  if (status >= 500) return "SERVER";
@@ -843,7 +858,6 @@ var OPENDESIGN_EOT = "OPENDESIGN_EOT";
843
858
 
844
859
  // src/empty-turn.ts
845
860
  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";
847
861
  var RESIDUE_PATTERNS = [
848
862
  /<\s*rea:tool_calls\s*>[\s\S]*?(?:<\s*\/\s*rea:tool_calls\s*>|$)/giu,
849
863
  /<\s*rea:tool(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*rea:tool\s*>|$)/giu,
@@ -866,20 +880,6 @@ function stripProtocolResidue(text2) {
866
880
  function isResidueOnly(text2) {
867
881
  return text2 === void 0 || stripProtocolResidue(text2) === "";
868
882
  }
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
- }
883
883
  function isMarkupOnlyStop(reason, input) {
884
884
  return reason.kind === "stop" && !input.sawToolCall && isResidueOnly(input.text);
885
885
  }
@@ -948,8 +948,7 @@ var EmptyTurnTracker = class {
948
948
  sawToolCall: this.#sawToolCall,
949
949
  textLength: text2.length,
950
950
  reasoningLength: reasoning.length,
951
- markupOnly: isResidueOnly(text2),
952
- pendingAction: isPendingActionTurn(text2)
951
+ markupOnly: isResidueOnly(text2)
953
952
  };
954
953
  }
955
954
  /**
@@ -964,12 +963,11 @@ var EmptyTurnTracker = class {
964
963
  resolve(reason) {
965
964
  const text2 = this.#text();
966
965
  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) {
966
+ if (!this.#enabled || !markupOnly) {
969
967
  return reason;
970
968
  }
971
969
  this.#notify();
972
- return { kind: "error", failure: { code: OPENDESIGN_EOT, message: pendingAction ? INCOMPLETE_TURN_MESSAGE : EMPTY_TURN_MESSAGE } };
970
+ return { kind: "error", failure: { code: OPENDESIGN_EOT, message: EMPTY_TURN_MESSAGE } };
973
971
  }
974
972
  /** Report one rewrite to the telemetry hook; monitoring must never break the stream. */
975
973
  #notify() {
@@ -2074,6 +2072,12 @@ var CoRouterAdapter = class extends LlmAdapter {
2074
2072
  unreadableImages.add(block.attachment.attachmentId);
2075
2073
  }
2076
2074
  }
2075
+ signal.throwIfAborted();
2076
+ const imageMessages = options.messages.filter((message) => message.role === "user" || message.role === "tool");
2077
+ const imageBytes = (block) => Buffer.byteLength(images.get(block.attachment.attachmentId) ?? "", "utf8");
2078
+ const offloadCount = (maxBytes) => requiredImageOffload(imageMessages, { representation: "raw", maxBytes }, imageBytes);
2079
+ const overBudget = offloadCount(config.maxRequestImageBytes ?? DEFAULT_MAX_REQUEST_IMAGE_BYTES);
2080
+ if (overBudget > 0) throw new LlmError11("OpenDesign\uFF1A\u56FE\u7247\u8BF7\u6C42\u8D85\u51FA\u5B57\u8282\u9884\u7B97\uFF0C\u9700\u8981\u9000\u8F7D\u8F83\u65E9\u56FE\u7247\u540E\u91CD\u8BD5", IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages: overBudget });
2077
2081
  const projectedOptions = unreadableImages.size === 0 ? options : {
2078
2082
  ...options,
2079
2083
  messages: options.messages.map((message) => message.role !== "user" && message.role !== "tool" ? message : {
@@ -2144,7 +2148,16 @@ var CoRouterAdapter = class extends LlmAdapter {
2144
2148
  reader.releaseLock();
2145
2149
  }
2146
2150
  }
2147
- throw gatewayError(response.status, error);
2151
+ signal.throwIfAborted();
2152
+ const failure = gatewayError(response.status, error);
2153
+ if (response.status === 413 && failure.code === "REQUEST_TOO_LARGE") {
2154
+ const totalImageBytes = imageMessages.reduce((total, message) => total + message.content.reduce((sum, block) => sum + (block.type === "image" && !block.offloaded ? imageBytes(block) : 0), 0), 0);
2155
+ if (totalImageBytes > 0) {
2156
+ const offloadImages = offloadCount(Math.max(0, totalImageBytes - 4 * 1024 * 1024));
2157
+ if (offloadImages > 0) throw new LlmError11("OpenDesign\uFF1A\u8BF7\u6C42\u4F53\u8FC7\u5927\uFF0C\u9700\u8981\u9000\u8F7D\u8F83\u65E9\u56FE\u7247\u540E\u91CD\u8BD5", IMAGE_OFFLOAD_REQUIRED_CODE, { status: 413, offloadImages });
2158
+ }
2159
+ }
2160
+ throw failure;
2148
2161
  }
2149
2162
  const monitor = row.group === "plan" && row.id === "deepseek-v4.1-flash" && config.emptyTurnGuard && Boolean(options.tools?.length);
2150
2163
  const reportEmptyTurn = () => {
@@ -2288,12 +2301,14 @@ function cancellableDelay(delay, signal) {
2288
2301
  });
2289
2302
  }
2290
2303
  var EotRecovery = class {
2291
- constructor(enabled, wait = cancellableDelay) {
2304
+ constructor(enabled, wait = cancellableDelay, onRetry) {
2292
2305
  this.enabled = enabled;
2293
2306
  this.wait = wait;
2307
+ this.onRetry = onRetry;
2294
2308
  }
2295
2309
  enabled;
2296
2310
  wait;
2311
+ onRetry;
2297
2312
  #lifetime = new AbortController();
2298
2313
  #states = /* @__PURE__ */ new WeakMap();
2299
2314
  #active = /* @__PURE__ */ new Set();
@@ -2315,6 +2330,10 @@ var EotRecovery = class {
2315
2330
  agent.session.append("llm/retry", { retryId: state.retryId, turn, step, provider, mode: "always", policyKey: POLICY_KEY, retry: state.retry, delayMs, failure });
2316
2331
  if (!await this.wait(delayMs, fused) || fused.aborted || !this.enabled()) return;
2317
2332
  agent.session.append("llm/retry-started", { retryId: state.retryId, turn, step, retry: state.retry });
2333
+ try {
2334
+ this.onRetry?.();
2335
+ } catch {
2336
+ }
2318
2337
  return { kind: "retry" };
2319
2338
  }
2320
2339
  async dispose() {
@@ -2322,8 +2341,8 @@ var EotRecovery = class {
2322
2341
  await Promise.allSettled([...this.#active]);
2323
2342
  }
2324
2343
  };
2325
- function installEotRecovery(ctx, enabled) {
2326
- const recovery = new EotRecovery(enabled);
2344
+ function installEotRecovery(ctx, enabled, onRetry) {
2345
+ const recovery = new EotRecovery(enabled, cancellableDelay, onRetry);
2327
2346
  const events = ctx;
2328
2347
  const remove = events.on("agent/request-error", recovery.handle, { prepend: true });
2329
2348
  ctx.effect(() => async () => {
@@ -2332,12 +2351,405 @@ function installEotRecovery(ctx, enabled) {
2332
2351
  });
2333
2352
  }
2334
2353
 
2354
+ // src/turn-monitor.ts
2355
+ import { createHash } from "node:crypto";
2356
+ import { createUserMessage, LlmError as LlmError13 } from "@deepseek-ai/dsh-llm";
2357
+ var FINISH_TURN_TOOL = "opendesign_finish_turn";
2358
+ var MAX_EVIDENCE = 64;
2359
+ var MAX_SUMMARY = 1200;
2360
+ var MAX_NEXT_ACTION = 800;
2361
+ var OUTCOMES = ["completed", "waiting_user", "waiting_work", "blocked", "continue"];
2362
+ var outcomeSchema = {
2363
+ type: "object",
2364
+ additionalProperties: false,
2365
+ required: ["status", "summary", "evidence"],
2366
+ properties: {
2367
+ status: { type: "string", enum: OUTCOMES },
2368
+ summary: { type: "string", description: "\u975E\u7A7A\u6536\u5C3E\u8BF4\u660E\uFF0C\u6700\u591A1200\u5B57\u7B26\u3002" },
2369
+ evidence: { type: "array", items: { type: "integer" }, description: "\u6700\u591A16\u4E2A\u975E\u8D1F\u5DE5\u5177\u7ED3\u679C\u5E8F\u53F7\u3002" },
2370
+ nextAction: { type: "string", description: "\u7EE7\u7EED\u6267\u884C\u65F6\u5FC5\u586B\uFF0C\u6700\u591A800\u5B57\u7B26\u3002" }
2371
+ }
2372
+ };
2373
+ function parseOutcome(value) {
2374
+ if (!record(value) || Object.keys(value).some((key) => !["status", "summary", "evidence", "nextAction"].includes(key)) || !OUTCOMES.includes(value.status) || typeof value.summary !== "string" || value.summary.trim().length === 0 || value.summary.length > MAX_SUMMARY || !Array.isArray(value.evidence) || value.evidence.length > 16 || value.evidence.some((item) => !Number.isSafeInteger(item) || item < 0) || value.nextAction !== void 0 && (typeof value.nextAction !== "string" || value.nextAction.trim().length === 0 || value.nextAction.length > MAX_NEXT_ACTION)) {
2375
+ throw new LlmError13("\u6536\u5C3E\u72B6\u6001\u6216\u8BC1\u636E\u5F15\u7528\u65E0\u6548", "INVALID_REQUEST");
2376
+ }
2377
+ if (value.status === "continue" && value.nextAction === void 0) throw new LlmError13("\u7EE7\u7EED\u6267\u884C\u65F6\u9700\u8981\u8BF4\u660E\u5C1A\u672A\u5B8C\u6210\u7684\u52A8\u4F5C", "INVALID_REQUEST");
2378
+ return {
2379
+ status: value.status,
2380
+ summary: value.summary,
2381
+ evidence: [...new Set(value.evidence)],
2382
+ ...typeof value.nextAction === "string" ? { nextAction: value.nextAction } : {}
2383
+ };
2384
+ }
2385
+ function fresh(turn) {
2386
+ return {
2387
+ turn,
2388
+ assistantSeq: -1,
2389
+ checkedSeq: -1,
2390
+ finish: void 0,
2391
+ interrupted: false,
2392
+ truncated: false,
2393
+ assistantMonitored: false,
2394
+ agent: void 0,
2395
+ removeTool: void 0,
2396
+ steering: void 0,
2397
+ continuations: 0,
2398
+ stagnant: 0,
2399
+ progress: 0,
2400
+ reviewedProgress: 0,
2401
+ settled: false,
2402
+ outcome: void 0,
2403
+ nativeConcluded: false,
2404
+ calls: /* @__PURE__ */ new Map(),
2405
+ evidence: /* @__PURE__ */ new Map(),
2406
+ fingerprints: /* @__PURE__ */ new Set(),
2407
+ pending: /* @__PURE__ */ new Map(),
2408
+ nativeEndings: /* @__PURE__ */ new Set()
2409
+ };
2410
+ }
2411
+ function services(ctx) {
2412
+ return ctx;
2413
+ }
2414
+ function monitored(session) {
2415
+ const header = session.requestHeader();
2416
+ return header?.config.provider === PLAN_PROVIDER && header.config.model === "deepseek-v4.1-flash" && Boolean(header.tools?.length);
2417
+ }
2418
+ var TurnMonitor = class {
2419
+ constructor(ctx, config, now = Date.now) {
2420
+ this.ctx = ctx;
2421
+ this.config = config;
2422
+ this.now = now;
2423
+ }
2424
+ ctx;
2425
+ config;
2426
+ now;
2427
+ #states = /* @__PURE__ */ new WeakMap();
2428
+ #active = /* @__PURE__ */ new Set();
2429
+ #disposed = false;
2430
+ #checks = 0;
2431
+ #continuations = 0;
2432
+ #requestRetries = 0;
2433
+ #last;
2434
+ status() {
2435
+ return {
2436
+ available: !this.#disposed && services(this.ctx).get("tools") !== void 0,
2437
+ checks: this.#checks,
2438
+ continuations: this.#continuations,
2439
+ requestRetries: this.#requestRetries,
2440
+ ...this.#last ? { last: { ...this.#last } } : {}
2441
+ };
2442
+ }
2443
+ requestRetried() {
2444
+ if (!this.#disposed) this.#requestRetries++;
2445
+ }
2446
+ #report(decision, reason) {
2447
+ this.#last = { at: new Date(this.now()).toISOString(), decision, reason };
2448
+ }
2449
+ #release(state) {
2450
+ const remove = state.removeTool;
2451
+ state.removeTool = void 0;
2452
+ try {
2453
+ remove?.();
2454
+ } catch {
2455
+ this.#report("unverified", "service-unavailable");
2456
+ }
2457
+ if (state.steering && state.agent) {
2458
+ try {
2459
+ state.agent.inbox.remove(state.steering);
2460
+ } catch {
2461
+ this.#report("unverified", "service-unavailable");
2462
+ }
2463
+ }
2464
+ state.steering = void 0;
2465
+ state.pending.clear();
2466
+ this.#active.delete(state);
2467
+ }
2468
+ configurationChanged() {
2469
+ if (this.config().emptyTurnGuard) return;
2470
+ for (const state of [...this.#active]) {
2471
+ state.settled = true;
2472
+ this.#release(state);
2473
+ }
2474
+ this.#report("skipped", "disabled");
2475
+ }
2476
+ dispose() {
2477
+ this.#disposed = true;
2478
+ for (const state of [...this.#active]) this.#release(state);
2479
+ }
2480
+ observe = (session, event) => {
2481
+ if (this.#disposed || !record(event.data)) return;
2482
+ const data = event.data;
2483
+ if (event.type === "turn/start" && Number.isSafeInteger(data.turn)) {
2484
+ const previous = this.#states.get(session);
2485
+ if (previous) this.#release(previous);
2486
+ this.#states.set(session, fresh(data.turn));
2487
+ return;
2488
+ }
2489
+ const state = this.#states.get(session);
2490
+ if (!state) return;
2491
+ if (event.type === "user/message" && record(data.source)) {
2492
+ const source = data.source;
2493
+ if (source.kind === "opendesign-review" && data.id === state.steering && source.turn === state.turn && source.checkpoint === state.checkedSeq) state.steering = void 0;
2494
+ else if (source.kind === "user" && state.continuations > 0) {
2495
+ state.settled = true;
2496
+ this.#release(state);
2497
+ this.#report("skipped", "superseded");
2498
+ }
2499
+ return;
2500
+ }
2501
+ if (data.turn !== state.turn) return;
2502
+ if (event.type === "turn/end") {
2503
+ this.#release(state);
2504
+ this.#states.delete(session);
2505
+ return;
2506
+ }
2507
+ if (!this.config().emptyTurnGuard || !monitored(session)) {
2508
+ this.#release(state);
2509
+ return;
2510
+ }
2511
+ if (event.type === "assistant/message" && record(data.message)) {
2512
+ state.assistantSeq = event.seq;
2513
+ state.interrupted = data.interrupted === true;
2514
+ const source = data.message.source;
2515
+ state.assistantMonitored = record(source) && source.provider === PLAN_PROVIDER && source.model === "deepseek-v4.1-flash";
2516
+ return;
2517
+ }
2518
+ if (event.type === "tool/call" && typeof data.callId === "string" && typeof data.name === "string") {
2519
+ if (state.calls.size >= MAX_EVIDENCE) state.calls.delete(state.calls.keys().next().value ?? "");
2520
+ state.calls.set(data.callId, { name: data.name, arguments: createHash("sha256").update(typeof data.arguments === "string" ? data.arguments : "").digest("hex") });
2521
+ return;
2522
+ }
2523
+ if (event.type !== "tool/result" || !record(data.message) || typeof data.message.toolCallId !== "string") return;
2524
+ const callId = data.message.toolCallId;
2525
+ const pending = state.pending.get(callId);
2526
+ state.pending.delete(callId);
2527
+ if (pending && data.message.isError !== true) state.outcome = pending;
2528
+ if (state.nativeEndings.delete(callId) && data.message.isError !== true) state.nativeConcluded = true;
2529
+ const call = state.calls.get(callId);
2530
+ state.calls.delete(callId);
2531
+ if (!call || call.name === FINISH_TURN_TOOL || pending) return;
2532
+ const fingerprint = createHash("sha256").update(JSON.stringify([call.name, call.arguments, data.message.content, data.message.isError === true])).digest("hex");
2533
+ const success = data.message.isError !== true;
2534
+ if (success && !state.fingerprints.has(fingerprint)) {
2535
+ state.progress++;
2536
+ if (state.fingerprints.size >= MAX_EVIDENCE) state.fingerprints.delete(state.fingerprints.values().next().value ?? "");
2537
+ state.fingerprints.add(fingerprint);
2538
+ }
2539
+ if (state.evidence.size >= MAX_EVIDENCE) state.evidence.delete(state.evidence.keys().next().value ?? -1);
2540
+ state.evidence.set(event.seq, { seq: event.seq, name: call.name, success, fingerprint });
2541
+ };
2542
+ stream = ({ agent, frame }) => {
2543
+ const state = this.#states.get(agent.session);
2544
+ if (!state || !this.config().emptyTurnGuard || !monitored(agent.session)) return;
2545
+ if (frame.type === "start") {
2546
+ state.finish = void 0;
2547
+ state.outcome = void 0;
2548
+ state.nativeConcluded = false;
2549
+ }
2550
+ if (frame.type === "chunk" && frame.chunk?.type === "finish") {
2551
+ state.finish = frame.chunk.reason?.kind;
2552
+ state.truncated ||= state.finish === "max-tokens";
2553
+ }
2554
+ };
2555
+ #goalOwns(agent) {
2556
+ const goal = services(agent.ctx).get("goals")?.get(agent);
2557
+ return goal !== void 0 && goal.phase !== "complete";
2558
+ }
2559
+ #workRunning(agent) {
2560
+ const host = services(agent.ctx);
2561
+ if (host.get("jobs")?.list(agent.session.id).some((job) => job.owner === agent.session.id && (job.status === "running" || job.status === "stopping"))) return true;
2562
+ const registry = host.get("agents");
2563
+ if (!registry) return false;
2564
+ const pending = [agent];
2565
+ const visited = /* @__PURE__ */ new Set([agent.id]);
2566
+ const agents = registry.list();
2567
+ while (pending.length) {
2568
+ const parent = pending.pop();
2569
+ if (!parent) break;
2570
+ for (const child of agents) {
2571
+ if (visited.has(child.id) || !registry.isOwnedBy(child.id, parent)) continue;
2572
+ visited.add(child.id);
2573
+ if (child.status === "running") return true;
2574
+ pending.push(child);
2575
+ }
2576
+ }
2577
+ return false;
2578
+ }
2579
+ #tool(state) {
2580
+ return {
2581
+ name: FINISH_TURN_TOOL,
2582
+ description: "\u62A5\u544A\u5F53\u524D\u4EFB\u52A1\u7684\u6536\u5C3E\u72B6\u6001\uFF1A\u5B8C\u6210\u3001\u7B49\u5F85\u7528\u6237\u3001\u7B49\u5F85\u540E\u53F0\u5DE5\u4F5C\u3001\u963B\u585E\u6216\u4ECD\u9700\u6267\u884C\u3002\u5B8C\u6210\u65F6\u5F15\u7528\u6536\u5C3E\u6838\u9A8C\u4E2D\u5217\u51FA\u7684\u6210\u529F\u5DE5\u5177\u7ED3\u679C\u5E8F\u53F7\uFF1B\u8FD9\u4E0D\u662F\u6267\u884C\u5DE5\u4F5C\u6216\u9A8C\u6536\u547D\u4EE4\u7684\u5DE5\u5177\u3002",
2583
+ parameters: outcomeSchema,
2584
+ output: { schema: outcomeSchema, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] },
2585
+ execute: async (args, exec) => {
2586
+ exec.signal.throwIfAborted();
2587
+ if (this.#disposed || !this.config().emptyTurnGuard || state.settled || exec.agent !== state.agent || !state.removeTool || !exec.agent || this.#states.get(exec.agent.session) !== state || !monitored(exec.agent.session)) {
2588
+ throw new LlmError13("\u5F53\u524D\u6CA1\u6709\u53EF\u63D0\u4EA4\u7684\u6536\u5C3E\u6838\u9A8C", "INVALID_REQUEST");
2589
+ }
2590
+ const outcome = parseOutcome(args);
2591
+ if (outcome.evidence.some((seq) => state.evidence.get(seq)?.success !== true)) throw new LlmError13("\u8BC1\u636E\u5FC5\u987B\u5F15\u7528\u672C\u8F6E\u5DF2\u6210\u529F\u7684\u5DE5\u5177\u7ED3\u679C\u5E8F\u53F7", "INVALID_REQUEST");
2592
+ if (outcome.status === "completed" && state.evidence.size > 0 && outcome.evidence.length === 0) {
2593
+ throw new LlmError13("\u672C\u8F6E\u5305\u542B\u5DE5\u5177\u6267\u884C\uFF1B\u5B8C\u6210\u58F0\u660E\u9700\u8981\u5F15\u7528\u5BF9\u5E94\u7684\u6210\u529F\u7ED3\u679C\uFF0C\u65E0\u6CD5\u6838\u5B9E\u65F6\u8BF7\u62A5\u544A\u963B\u585E", "INVALID_REQUEST");
2594
+ }
2595
+ const running = this.#workRunning(exec.agent);
2596
+ if (outcome.status === "completed" && running) throw new LlmError13("\u4ECD\u6709\u540E\u53F0\u5DE5\u4F5C\u5728\u8FD0\u884C\uFF0C\u8BF7\u62A5\u544A\u7B49\u5F85\u540E\u53F0\u5DE5\u4F5C", "INVALID_REQUEST");
2597
+ if (outcome.status === "waiting_work" && !running) throw new LlmError13("\u672A\u627E\u5230\u672C\u4F1A\u8BDD\u4ECD\u5728\u8FD0\u884C\u7684\u540E\u53F0\u5DE5\u4F5C\uFF0C\u8BF7\u91CD\u65B0\u6838\u5BF9\u72B6\u6001", "INVALID_REQUEST");
2598
+ exec.signal.throwIfAborted();
2599
+ exec.concludeTurn();
2600
+ return outcome;
2601
+ }
2602
+ };
2603
+ }
2604
+ toolResult = (exec, result) => {
2605
+ if (!exec.agent || result.isError || result.concludesTurn !== true || exec.signal.aborted) return;
2606
+ const state = this.#states.get(exec.agent.session);
2607
+ if (!state || state.settled) return;
2608
+ const root = exec.rootCallId ?? exec.callId;
2609
+ if (exec.name !== FINISH_TURN_TOOL) {
2610
+ if (!state.pending.has(root)) state.nativeEndings.add(root);
2611
+ return;
2612
+ }
2613
+ if (state.agent !== exec.agent || !state.removeTool) return;
2614
+ try {
2615
+ const outcome = parseOutcome(result.value);
2616
+ if (outcome.evidence.some((seq) => state.evidence.get(seq)?.success !== true) || outcome.status === "completed" && state.evidence.size > 0 && outcome.evidence.length === 0) {
2617
+ this.#report("unverified", "invalid-evidence");
2618
+ return;
2619
+ }
2620
+ state.pending.set(root, outcome);
2621
+ } catch {
2622
+ }
2623
+ };
2624
+ stopping = ({ agent, turn, signal }) => {
2625
+ const state = this.#states.get(agent.session);
2626
+ if (!state || state.turn !== turn || state.settled || state.assistantSeq < 0 || state.checkedSeq === state.assistantSeq) return;
2627
+ if (this.#disposed || !this.config().emptyTurnGuard || !monitored(agent.session) || !state.assistantMonitored) {
2628
+ this.#release(state);
2629
+ return;
2630
+ }
2631
+ state.agent = agent;
2632
+ state.checkedSeq = state.assistantSeq;
2633
+ if (signal.aborted || state.interrupted) {
2634
+ this.#release(state);
2635
+ this.#report("skipped", "cancelled");
2636
+ return;
2637
+ }
2638
+ if (state.truncated || state.finish !== "stop" && state.finish !== "tool-calls") {
2639
+ this.#release(state);
2640
+ this.#report("skipped", state.truncated ? "truncated" : "request-failed");
2641
+ return;
2642
+ }
2643
+ if (state.nativeConcluded) {
2644
+ state.settled = true;
2645
+ this.#release(state);
2646
+ this.#report("skipped", "tool-concluded");
2647
+ return;
2648
+ }
2649
+ if (agent.inbox.nextStep.length || agent.inbox.nextTurn.length) {
2650
+ this.#release(state);
2651
+ this.#report("skipped", "superseded");
2652
+ return;
2653
+ }
2654
+ this.#checks++;
2655
+ try {
2656
+ if (this.#goalOwns(agent)) {
2657
+ state.settled = true;
2658
+ this.#release(state);
2659
+ this.#report("skipped", "goal-owned");
2660
+ return;
2661
+ }
2662
+ if (this.#workRunning(agent)) {
2663
+ state.settled = true;
2664
+ this.#release(state);
2665
+ this.#report("waiting-work", "work-running");
2666
+ return;
2667
+ }
2668
+ } catch {
2669
+ state.settled = true;
2670
+ this.#release(state);
2671
+ this.#report("unverified", "service-unavailable");
2672
+ return;
2673
+ }
2674
+ const outcome = state.outcome;
2675
+ if (outcome && outcome.status !== "continue") {
2676
+ const decision = outcome.status === "completed" ? "completed" : outcome.status === "waiting_user" ? "waiting-user" : outcome.status === "waiting_work" ? "waiting-work" : "blocked";
2677
+ const reason = outcome.status === "completed" ? "reported-complete" : outcome.status === "waiting_user" ? "needs-user" : outcome.status === "waiting_work" ? "work-running" : "reported-blocked";
2678
+ state.settled = true;
2679
+ this.#release(state);
2680
+ this.#report(decision, reason);
2681
+ return;
2682
+ }
2683
+ const config = this.config();
2684
+ if (state.continuations > 0) state.stagnant = state.progress === state.reviewedProgress ? state.stagnant + 1 : 0;
2685
+ const limit = state.continuations >= (config.turnReviewMaxContinuations ?? 3) ? "continuation-limit" : state.stagnant >= (config.turnReviewNoProgressLimit ?? 2) ? "no-progress" : void 0;
2686
+ if (limit) {
2687
+ state.settled = true;
2688
+ this.#release(state);
2689
+ this.#report("limited", limit);
2690
+ return;
2691
+ }
2692
+ const tools = services(agent.ctx).get("tools");
2693
+ if (!tools) {
2694
+ state.settled = true;
2695
+ this.#report("unverified", "service-unavailable");
2696
+ return;
2697
+ }
2698
+ if (!state.removeTool) {
2699
+ try {
2700
+ state.removeTool = tools.register(this.#tool(state));
2701
+ this.#active.add(state);
2702
+ } catch {
2703
+ state.settled = true;
2704
+ this.#report("unverified", "service-unavailable");
2705
+ return;
2706
+ }
2707
+ }
2708
+ const evidence = [...state.evidence.values()].slice(-16).map((item) => ({ seq: item.seq, tool: item.name, success: item.success }));
2709
+ const nextAction = outcome?.status === "continue" ? outcome.nextAction : void 0;
2710
+ const message = createUserMessage({ source: { kind: "opendesign-review", turn, checkpoint: state.assistantSeq }, content: [{ type: "text", text: `\u6838\u5BF9\u5F53\u524D\u4EFB\u52A1\u7684\u6536\u5C3E\u72B6\u6001\u3002\u521A\u624D\u7684\u56DE\u590D\u548C\u5DF2\u6267\u884C\u5DE5\u5177\u5747\u4FDD\u7559\u5728\u5386\u53F2\u4E2D\uFF0C\u4E0D\u8981\u91CD\u590D\u5DF2\u7ECF\u6210\u529F\u7684\u52A8\u4F5C\u3002${nextAction ? `\u5C1A\u672A\u5B8C\u6210\u7684\u52A8\u4F5C\uFF1A${JSON.stringify(nextAction)}\u3002` : ""}
2711
+ \u82E5\u4ECD\u6709\u5DF2\u786E\u5B9A\u7684\u5DE5\u4F5C\uFF0C\u8BF7\u7EE7\u7EED\u5B9E\u9645\u6267\u884C\uFF1B\u82E5\u5DF2\u7ECF\u5B8C\u6210\u3001\u9700\u8981\u7528\u6237\u51B3\u5B9A\u3001\u7B49\u5F85\u540E\u53F0\u5DE5\u4F5C\u6216\u9047\u5230\u963B\u585E\uFF0C\u8BF7\u8C03\u7528 ${FINISH_TURN_TOOL} \u62A5\u544A\u5BF9\u5E94\u72B6\u6001\u3002\u5B8C\u6210\u65F6\u5F15\u7528\u76F8\u5173\u6210\u529F\u7ED3\u679C\uFF0C\u4E0D\u628A\u8BA1\u5212\u6216\u5F85\u68C0\u67E5\u4E8B\u9879\u5F53\u6210\u5DF2\u6267\u884C\u3002\u666E\u901A\u6587\u5B57\u56DE\u7B54\u53EF\u76F4\u63A5\u62A5\u544A\u5B8C\u6210\uFF1B\u9700\u8981\u7528\u6237\u8865\u5145\u65F6\u62A5\u544A waiting_user\u3002
2712
+ \u672C\u8F6E\u6700\u8FD1\u7684\u5DE5\u5177\u7ED3\u679C\u5F15\u7528\uFF1A${JSON.stringify(evidence)}\u3002\u5DE5\u5177\u7ED3\u679C\u6B63\u6587\u5DF2\u5728\u5386\u53F2\u4E2D\uFF0C\u5F15\u7528\u53EA\u8BF4\u660E\u7ED3\u679C\u786E\u5B9E\u5B58\u5728\uFF0C\u4E0D\u66FF\u4EE3\u5BF9\u4EFB\u52A1\u8981\u6C42\u7684\u6838\u5BF9\u3002` }] });
2713
+ state.steering = message.id;
2714
+ try {
2715
+ agent.steer(message);
2716
+ } catch {
2717
+ state.settled = true;
2718
+ this.#release(state);
2719
+ this.#report("unverified", "service-unavailable");
2720
+ return;
2721
+ }
2722
+ state.continuations++;
2723
+ state.reviewedProgress = state.progress;
2724
+ this.#continuations++;
2725
+ this.#report("continued", nextAction ? "pending-action" : "missing-outcome");
2726
+ };
2727
+ disposedAgent = ({ agent }) => {
2728
+ const state = this.#states.get(agent.session);
2729
+ if (state) this.#release(state);
2730
+ this.#states.delete(agent.session);
2731
+ };
2732
+ };
2733
+ function installTurnMonitor(ctx, config) {
2734
+ const monitor = new TurnMonitor(ctx, config);
2735
+ const events = ctx;
2736
+ events.on("session/event", monitor.observe);
2737
+ events.on("agent/assistant-stream", monitor.stream);
2738
+ events.on("agent/turn-stopping", monitor.stopping);
2739
+ events.on("tools/result", monitor.toolResult);
2740
+ events.on("agent/disposed", monitor.disposedAgent);
2741
+ ctx.on("loader/volatile-update", () => monitor.configurationChanged());
2742
+ ctx.effect(() => () => monitor.dispose());
2743
+ return monitor;
2744
+ }
2745
+
2335
2746
  // src/model-discovery.ts
2336
2747
  import { attributionHeaders as attributionHeaders2 } from "@deepseek-ai/dsh-llm";
2337
2748
  var DISCOVERY_TIMEOUT_MS = 2e4;
2338
2749
  var MAX_DISCOVERY_BODY_BYTES = 2 * 1024 * 1024;
2339
2750
  var MAX_MODELS = 512;
2340
2751
  var MAX_MODEL_NAME_LENGTH = 128;
2752
+ var MAX_CONTEXT_WINDOW = 1e8;
2341
2753
  var MODEL_ID = /^[A-Za-z0-9._:/-]{1,128}$/u;
2342
2754
  var MEDIA_MODEL_ID = /^(?:gpt-image-|nano-banana-|seedream-|imagen-|veo-|doubao-seedance-|sora-)/u;
2343
2755
  var MESSAGES2 = {
@@ -2406,6 +2818,21 @@ async function boundedJson(response, signal, deadline) {
2406
2818
  throw new ModelDiscoveryError("response");
2407
2819
  }
2408
2820
  }
2821
+ function gatewayContext(value) {
2822
+ const metadata2 = record(value.metadata) ? value.metadata : {};
2823
+ const candidates = [
2824
+ metadata2.context_limit,
2825
+ metadata2.contextWindowTokens,
2826
+ metadata2.context_window_tokens,
2827
+ value.contextWindowTokens,
2828
+ value.context_window_tokens,
2829
+ value.contextLength,
2830
+ value.context_length,
2831
+ value.contextWindow,
2832
+ value.context_window
2833
+ ].filter((item) => typeof item === "number" && Number.isSafeInteger(item) && item > 0 && item <= MAX_CONTEXT_WINDOW);
2834
+ return candidates.length === 0 ? void 0 : Math.min(...candidates);
2835
+ }
2409
2836
  function normalize(body) {
2410
2837
  if (!record(body) || !Array.isArray(body.data)) throw new ModelDiscoveryError("response");
2411
2838
  if (body.data.length > MAX_MODELS) throw new ModelDiscoveryError("response");
@@ -2416,13 +2843,15 @@ function normalize(body) {
2416
2843
  if (MEDIA_MODEL_ID.test(value.id) || seen.has(value.id)) continue;
2417
2844
  seen.add(value.id);
2418
2845
  const known = findModel(value.id);
2846
+ const offeredContext = gatewayContext(value);
2419
2847
  if (known) {
2420
- rows.push({ ...known });
2848
+ const contextWindow = offeredContext === void 0 ? known.contextWindow : known.contextWindow === void 0 ? offeredContext : Math.min(known.contextWindow, offeredContext);
2849
+ rows.push({ ...known, ...contextWindow === void 0 ? {} : { contextWindow } });
2421
2850
  continue;
2422
2851
  }
2423
2852
  const offered = typeof value.name === "string" ? value.name.trim() : "";
2424
2853
  const name2 = offered !== "" && offered.length <= MAX_MODEL_NAME_LENGTH ? offered : value.id;
2425
- rows.push({ id: value.id, name: name2, group: "paid" });
2854
+ rows.push({ id: value.id, name: name2, group: "paid", ...offeredContext === void 0 ? {} : { contextWindow: offeredContext } });
2426
2855
  }
2427
2856
  return rows;
2428
2857
  }
@@ -2970,7 +3399,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
2970
3399
 
2971
3400
  // src/device-auth.ts
2972
3401
  var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
2973
- var DEVICE_AUTH_PLUGIN_VERSION = "0.1.13";
3402
+ var DEVICE_AUTH_PLUGIN_VERSION = "0.1.15";
2974
3403
  var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
2975
3404
  var DEVICE_RESPONSE_MAX_BYTES = 65536;
2976
3405
  var DEVICE_POLL_MIN_MS = 1e3;
@@ -3901,6 +4330,10 @@ async function readDesktopQuota(session, signal, runner = runVela, fetcher = fet
3901
4330
  };
3902
4331
  }
3903
4332
 
4333
+ // src/turn-monitor-status.ts
4334
+ var REVIEW_DECISIONS = ["continued", "completed", "waiting-user", "waiting-work", "blocked", "limited", "skipped", "unverified"];
4335
+ var REVIEW_REASONS = ["missing-outcome", "pending-action", "reported-complete", "needs-user", "work-running", "reported-blocked", "continuation-limit", "no-progress", "goal-owned", "service-unavailable", "cancelled", "truncated", "request-failed", "disabled", "superseded", "invalid-evidence", "tool-concluded"];
4336
+
3904
4337
  // src/remote.ts
3905
4338
  var MAX_REVISION = 256;
3906
4339
  var MAX_JOB_ID = 128;
@@ -4089,7 +4522,10 @@ function parseStatusConfig(value) {
4089
4522
  ...value.modelSettings === void 0 ? {} : { modelSettings: parseModelSettingsMap(value.modelSettings) },
4090
4523
  ...value.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: positiveInteger(value.requestTimeoutMs, "\u8BF7\u6C42\u8D85\u65F6", 36e5, 1e3) },
4091
4524
  ...value.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: positiveInteger(value.streamIdleTimeoutMs, "\u6D41\u7A7A\u95F2\u8D85\u65F6", 18e5, 1e3) },
4092
- ...value.quotaRefreshSeconds === void 0 ? {} : { quotaRefreshSeconds: positiveInteger(value.quotaRefreshSeconds, "\u81EA\u52A8\u5237\u65B0\u95F4\u9694", 3600, 5) }
4525
+ ...value.quotaRefreshSeconds === void 0 ? {} : { quotaRefreshSeconds: positiveInteger(value.quotaRefreshSeconds, "\u81EA\u52A8\u5237\u65B0\u95F4\u9694", 3600, 5) },
4526
+ ...value.maxRequestImageBytes === void 0 ? {} : { maxRequestImageBytes: positiveInteger(value.maxRequestImageBytes, "\u8BF7\u6C42\u56FE\u7247\u9884\u7B97", MAX_REQUEST_IMAGE_BYTES, MIN_REQUEST_IMAGE_BYTES) },
4527
+ ...value.turnReviewMaxContinuations === void 0 ? {} : { turnReviewMaxContinuations: positiveInteger(value.turnReviewMaxContinuations, "\u6536\u5C3E\u7EED\u529E\u6B21\u6570", 10) },
4528
+ ...value.turnReviewNoProgressLimit === void 0 ? {} : { turnReviewNoProgressLimit: positiveInteger(value.turnReviewNoProgressLimit, "\u65E0\u8FDB\u5C55\u6B21\u6570", 5) }
4093
4529
  };
4094
4530
  }
4095
4531
  function parseStatus(value) {
@@ -4114,12 +4550,25 @@ function parseStatus(value) {
4114
4550
  login: parseLoginState(value.login),
4115
4551
  config: parseStatusConfig(value.config),
4116
4552
  guardedTurns: count(value.guardedTurns, "\u5DF2\u62E6\u622A\u7A7A\u8F6E\u6570"),
4553
+ ...value.turnMonitor === void 0 ? {} : { turnMonitor: parseTurnMonitor(value.turnMonitor) },
4117
4554
  models: parsed,
4118
4555
  ...value.modelsSource === void 0 ? {} : { modelsSource: member(value.modelsSource, ["builtin", "openai"], "\u6A21\u578B\u76EE\u5F55\u6765\u6E90") },
4119
4556
  ...value.modelsUpdatedAt === void 0 ? {} : { modelsUpdatedAt: isoTime(value.modelsUpdatedAt, "\u6A21\u578B\u66F4\u65B0\u65F6\u95F4") },
4120
4557
  ...value.modelsError === void 0 ? {} : { modelsError: text(value.modelsError, "\u6A21\u578B\u66F4\u65B0\u63D0\u793A", MAX_MESSAGE) }
4121
4558
  };
4122
4559
  }
4560
+ function parseTurnMonitor(value) {
4561
+ if (!record(value)) throw new Error("\u7ED3\u675F\u6838\u9A8C\u72B6\u6001\u5FC5\u987B\u662F\u5BF9\u8C61");
4562
+ const last = value.last;
4563
+ if (last !== void 0 && !record(last)) throw new Error("\u6700\u8FD1\u7ED3\u675F\u6838\u9A8C\u5FC5\u987B\u662F\u5BF9\u8C61");
4564
+ return {
4565
+ available: flag(value.available, "\u6536\u5C3E\u6838\u9A8C\u662F\u5426\u53EF\u7528"),
4566
+ checks: count(value.checks, "\u6536\u5C3E\u6838\u9A8C\u6B21\u6570"),
4567
+ continuations: count(value.continuations, "\u4EFB\u52A1\u7EED\u529E\u6B21\u6570"),
4568
+ requestRetries: count(value.requestRetries, "\u8BF7\u6C42\u91CD\u8BD5\u6B21\u6570"),
4569
+ ...record(last) ? { last: { at: isoTime(last.at, "\u6536\u5C3E\u6838\u9A8C\u65F6\u95F4"), decision: member(last.decision, REVIEW_DECISIONS, "\u6536\u5C3E\u6838\u9A8C\u51B3\u5B9A"), reason: member(last.reason, REVIEW_REASONS, "\u6536\u5C3E\u6838\u9A8C\u539F\u56E0") } } : {}
4570
+ };
4571
+ }
4123
4572
  function parseStartLoginRequest(value) {
4124
4573
  if (!record(value)) throw new Error("\u767B\u5F55\u8BF7\u6C42\u5FC5\u987B\u662F\u5BF9\u8C61");
4125
4574
  return { expectedRevision: text(value.expectedRevision, "\u914D\u7F6E\u7248\u672C", MAX_REVISION) };
@@ -4146,7 +4595,7 @@ var name = "llm-opendesign-corouter";
4146
4595
  var inject = ["llm"];
4147
4596
  var API_KEY = credentialKey2(name, "api-key");
4148
4597
  var SESSION = credentialKey2(name, "console");
4149
- var hash = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4598
+ var hash = (value) => createHash2("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4150
4599
  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" });
4151
4600
  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" });
4152
4601
  function grantOf(value) {
@@ -4175,6 +4624,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4175
4624
  __publicField(this, "_quotaPending");
4176
4625
  __publicField(this, "_quotaController");
4177
4626
  __publicField(this, "guardedTurns", 0);
4627
+ __publicField(this, "turnMonitorStatus");
4178
4628
  __publicField(this, "_models", MODELS);
4179
4629
  __publicField(this, "_modelsUpdatedAt");
4180
4630
  __publicField(this, "_modelsError");
@@ -4308,6 +4758,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4308
4758
  login: this._login.status(),
4309
4759
  config: state.config,
4310
4760
  guardedTurns: this.guardedTurns,
4761
+ ...this.turnMonitorStatus ? { turnMonitor: this.turnMonitorStatus() } : {},
4311
4762
  models: this._models.map((row) => {
4312
4763
  const { id, name: name2, group: group2, contextWindow, maxOutputTokens, inputModalities } = row;
4313
4764
  const reasoningEfforts = modelReasoningEfforts(row, state.config.apiProtocol ?? "chat-completions");
@@ -4544,11 +4995,13 @@ __decoratorMetadata(_init, OpenDesignCoRouterService);
4544
4995
  function apply(ctx, config) {
4545
4996
  const current = () => readConfig(config);
4546
4997
  current();
4547
- installEotRecovery(ctx, () => current().emptyTurnGuard);
4548
4998
  ctx.inject(["settings"], (scope) => scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)));
4549
4999
  let modelsChanged = () => {
4550
5000
  };
4551
5001
  const service = new OpenDesignCoRouterService(ctx, current, { resolveSession, readQuota, readDesktopQuota, modelsChanged: () => modelsChanged() });
5002
+ const turnMonitor = installTurnMonitor(ctx, current);
5003
+ service.turnMonitorStatus = () => turnMonitor.status();
5004
+ installEotRecovery(ctx, () => current().emptyTurnGuard, () => turnMonitor.requestRetried());
4552
5005
  const replayKeys = new ReplayKeyStore(() => ctx.get("credentials"));
4553
5006
  const adapter = new CoRouterAdapter({
4554
5007
  config: current,
@@ -4575,10 +5028,10 @@ function apply(ctx, config) {
4575
5028
  modelsChanged();
4576
5029
  });
4577
5030
  ctx.llm.registerModelDiscovery(SETTINGS_NS, async (request, signal) => {
4578
- 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");
5031
+ if (request.provider !== void 0 && ![PLAN_PROVIDER, PAID_PROVIDER].includes(request.provider)) throw new LlmError14("\u4E0D\u662F\u672C\u63D2\u4EF6\u7684\u6A21\u578B\u901A\u9053", "INVALID_REQUEST");
4579
5032
  const config2 = current();
4580
5033
  const key = request.apiKey ?? await service.resolveApiKey(config2.apiKeyEnv, config2.baseURL);
4581
- if (!key) throw new LlmError13("\u8BF7\u5148\u914D\u7F6E CoRouter API Key", "MISSING_CREDENTIAL");
5034
+ if (!key) throw new LlmError14("\u8BF7\u5148\u914D\u7F6E CoRouter API Key", "MISSING_CREDENTIAL");
4582
5035
  const models = await fetchModelCatalog(config2.baseURL, key, signal);
4583
5036
  return models.map((row) => {
4584
5037
  const effective = applyModelSettings(row, config2.modelSettings?.[row.id]);