dsh-opendesign-corouter 0.1.14 → 0.1.16

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,11 +48,11 @@ 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";
@@ -249,13 +249,25 @@ function inferenceEndpoint(baseURL, protocol) {
249
249
  return baseURL.trim() === "" ? suffix : `${openAiBaseURL(baseURL.trim())}${suffix}`;
250
250
  }
251
251
 
252
+ // src/context-budget.ts
253
+ var CONTEXT_WINDOW_PRESETS = [
254
+ { id: "default", label: "\u9ED8\u8BA4", tokens: 272e3 },
255
+ { id: "extended", label: "\u6269\u5C55", tokens: 5e5 },
256
+ { id: "maximum", label: "\u6700\u5927", tokens: 872e3 }
257
+ ];
258
+ function effectiveContextWindow(reference, override, tier) {
259
+ if (tier === void 0 && override !== void 0) return override;
260
+ const requested = (CONTEXT_WINDOW_PRESETS.find((preset) => preset.id === (tier ?? "default")) ?? CONTEXT_WINDOW_PRESETS[0]).tokens;
261
+ return reference === void 0 ? requested : Math.min(requested, reference);
262
+ }
263
+
252
264
  // src/model-settings.ts
253
265
  var RESERVED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
254
266
  function parseModelSettingsMap(value) {
255
267
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");
256
268
  const keys = Object.keys(value);
257
269
  if (keys.length > 512) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u6700\u591A\u5141\u8BB8 512 \u4E2A\u6A21\u578B");
258
- const fields = /* @__PURE__ */ new Set(["enabled", "imageInput", "temperature", "topP", "maxTokens", "contextWindow", "reasoningEffort"]);
270
+ const fields = /* @__PURE__ */ new Set(["enabled", "imageInput", "temperature", "topP", "maxTokens", "contextWindow", "contextTier", "reasoningEffort"]);
259
271
  const efforts = ["none", "minimal", "low", "medium", "high", "xhigh", "ultra", "max"];
260
272
  const out = {};
261
273
  for (const id of keys) {
@@ -288,6 +300,13 @@ function parseModelSettingsMap(value) {
288
300
  if (typeof item !== "number" || !Number.isSafeInteger(item) || item < 1 || item > max) throw new Error(`\u6A21\u578B\u8BBE\u7F6E\u7684 ${field} \u5FC5\u987B\u662F 1 \u5230 ${max} \u4E4B\u95F4\u7684\u6574\u6570`);
289
301
  parsed[field] = item;
290
302
  }
303
+ if (settings.contextTier !== void 0) {
304
+ if (settings.contextTier !== "default" && settings.contextTier !== "extended" && settings.contextTier !== "maximum") throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 contextTier \u4E0D\u5728\u5141\u8BB8\u7684\u53D6\u503C\u5185");
305
+ if (parsed.contextWindow !== void 0) throw new Error("\u4E0A\u4E0B\u6587\u6863\u4F4D\u4E0E\u65E7\u81EA\u5B9A\u4E49\u7A97\u53E3\u4E0D\u80FD\u540C\u65F6\u8BBE\u7F6E");
306
+ parsed.contextTier = settings.contextTier;
307
+ const window = parsed.contextTier === "default" ? 272e3 : parsed.contextTier === "extended" ? 5e5 : 872e3;
308
+ if (parsed.maxTokens !== void 0 && parsed.maxTokens >= window) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 maxTokens \u5FC5\u987B\u5C0F\u4E8E\u6863\u4F4D\u603B\u7A97\u53E3");
309
+ }
291
310
  if (settings.reasoningEffort !== void 0) {
292
311
  if (typeof settings.reasoningEffort !== "string" || !efforts.includes(settings.reasoningEffort)) throw new Error("\u6A21\u578B\u8BBE\u7F6E\u7684 reasoningEffort \u4E0D\u5728\u5141\u8BB8\u7684\u53D6\u503C\u5185");
293
312
  parsed.reasoningEffort = settings.reasoningEffort;
@@ -298,14 +317,14 @@ function parseModelSettingsMap(value) {
298
317
  return out;
299
318
  }
300
319
  function applyModelSettings(row, settings) {
301
- const { contextWindow, maxTokens, imageInput } = settings ?? {};
302
- if (contextWindow === void 0 && maxTokens === void 0 && imageInput === void 0) return { ...row };
320
+ const { contextWindow, contextTier, maxTokens, imageInput } = settings ?? {};
303
321
  if (contextWindow !== void 0) parseModelSettingsMap({ model: { contextWindow } });
322
+ if (contextTier !== void 0) parseModelSettingsMap({ model: { contextTier, ...contextWindow === void 0 ? {} : { contextWindow } } });
304
323
  if (maxTokens !== void 0) parseModelSettingsMap({ model: { maxTokens } });
305
324
  if (imageInput !== void 0) parseModelSettingsMap({ model: { imageInput } });
306
325
  return {
307
326
  ...row,
308
- ...contextWindow === void 0 ? {} : { contextWindow },
327
+ contextWindow: effectiveContextWindow(row.contextWindow, contextWindow, contextTier),
309
328
  ...maxTokens === void 0 ? {} : { maxOutputTokens: maxTokens },
310
329
  ...imageInput === void 0 ? {} : { inputModalities: imageInput ? ["text", "image"] : ["text"] }
311
330
  };
@@ -340,7 +359,10 @@ var Config = Schema.object({
340
359
  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(),
341
360
  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(),
342
361
  useDesktopCredential: Schema.boolean().default(true).description("\u4F18\u5148\u8BFB\u53D6 OpenDesign \u684C\u9762\u7AEF\u767B\u5F55\u6001\u67E5\u8BE2\u989D\u5EA6").volatile(),
343
- 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(),
362
+ emptyTurnGuard: Schema.boolean().default(true).description("\u4FDD\u62A4 DeepSeek V4.1 Flash \u5DE5\u5177\u5BF9\u8BDD\uFF1A\u6062\u590D\u7A7A\u56DE\u7B54\u4E0E\u5DF2\u77E5\u534F\u8BAE\u6B8B\u7559\u7ED3\u675F").volatile(),
363
+ turnCompletionReview: Schema.boolean().default(false).description("\u56DE\u590D\u7ED3\u675F\u540E\u8FFD\u52A0\u6709\u754C\u7684\u7ED3\u6784\u5316\u6536\u5C3E\u6838\u9A8C\uFF0C\u8981\u6C42\u6A21\u578B\u8C03\u7528\u6536\u5C3E\u5DE5\u5177\u62A5\u544A\u72B6\u6001").volatile(),
364
+ 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(),
365
+ 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(),
344
366
  quotaRefreshSeconds: Schema.natural().min(5).max(3600).default(60).description("\u989D\u5EA6\u81EA\u52A8\u5237\u65B0\u95F4\u9694\uFF08\u79D2\uFF09").volatile(),
345
367
  requestTimeoutMs: Schema.natural().min(1e3).max(36e5).default(18e5).description("\u63A8\u7406\u8BF7\u6C42\u603B\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile(),
346
368
  streamIdleTimeoutMs: Schema.natural().min(1e3).max(18e5).default(3e5).description("\u6D41\u5F0F\u54CD\u5E94\u65E0\u6570\u636E\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile(),
@@ -371,7 +393,10 @@ function readConfig(config) {
371
393
  emptyTurnGuard: config.emptyTurnGuard.get(),
372
394
  requestTimeoutMs: config.requestTimeoutMs.get(),
373
395
  streamIdleTimeoutMs: config.streamIdleTimeoutMs.get(),
374
- maxRequestImageBytes: config.maxRequestImageBytes.get()
396
+ maxRequestImageBytes: config.maxRequestImageBytes.get(),
397
+ turnCompletionReview: config.turnCompletionReview.get(),
398
+ turnReviewMaxContinuations: config.turnReviewMaxContinuations.get(),
399
+ turnReviewNoProgressLimit: config.turnReviewNoProgressLimit.get()
375
400
  };
376
401
  }
377
402
 
@@ -854,7 +879,6 @@ var OPENDESIGN_EOT = "OPENDESIGN_EOT";
854
879
 
855
880
  // src/empty-turn.ts
856
881
  var EMPTY_TURN_MESSAGE = "OpenDesign\uFF1A\u6A21\u578B\u672A\u4EA7\u751F\u53EF\u7528\u56DE\u7B54\u6216\u6709\u6548\u5DE5\u5177\u8C03\u7528";
857
- var INCOMPLETE_TURN_MESSAGE = "OpenDesign\uFF1A\u6A21\u578B\u505C\u5728\u64CD\u4F5C\u8BF4\u660E\uFF0C\u672A\u7EE7\u7EED\u53D1\u8D77\u5DE5\u5177\u8C03\u7528";
858
882
  var RESIDUE_PATTERNS = [
859
883
  /<\s*rea:tool_calls\s*>[\s\S]*?(?:<\s*\/\s*rea:tool_calls\s*>|$)/giu,
860
884
  /<\s*rea:tool(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*rea:tool\s*>|$)/giu,
@@ -877,20 +901,6 @@ function stripProtocolResidue(text2) {
877
901
  function isResidueOnly(text2) {
878
902
  return text2 === void 0 || stripProtocolResidue(text2) === "";
879
903
  }
880
- var ACTION_PREAMBLE_ZH = /^(?:(?:好的?|明白|收到)[,,。]\s*)?(?:让我|我需要|我(?:先|再|将|会|来|要|这就|马上)|先|现在|接下来(?:我)?(?:将|会)?)(?:先|再|去|来|马上)?(?:看一看|看看|看下|查看|检查|核对|核验|核查|对照|比对|确认|验证|验收|测试|读取|读|打开|搜索|查找|定位|分析|排查|审查|检索|查询|运行|执行|修改|修复|调整|更新|编写|梳理|对比|比较)(?!了|过|到|出|完)[^,,。!?!?\n;;::]{1,100}[。!!…]?$/u;
881
- 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;
882
- var FOLLOWUP_ACTION_ZH = /^(?:现在|接下来|下一步|随后|接着)(?:我)?(?:先|再|将|会|准备|重新)?(?:看一看|看看|看下|查看|检查|核对|核验|核查|对照|比对|确认|验证|验收|测试|读取|读|打开|搜索|查找|定位|分析|排查|审查|检索|查询|运行|执行|修改|修复|调整|更新|编写|梳理|对比|比较)(?!了|过|到|出|完|结果)[^。!?!?\n;;::]{1,100}[。!!…]?$/u;
883
- var COMPLETED_ACTION_ZH = /(?:发现|结果(?:是|为|显示)|显示|得出|证明|确认了|已经完成|已完成|通过|没有问题|无误|正常)/u;
884
- function isPendingActionTurn(text2) {
885
- if (text2 === void 0) return false;
886
- const content2 = stripProtocolResidue(text2);
887
- if (ACTION_PREAMBLE_ZH.test(content2) || ACTION_PREAMBLE_EN.test(content2)) return true;
888
- if (content2.length > 200 || /[\n`]/u.test(content2)) return false;
889
- const sentences = content2.split(/(?<=[。!?])\s*/u).filter(Boolean);
890
- if (sentences.length < 2 || sentences.length > 3) return false;
891
- const last = sentences.at(-1) ?? "";
892
- return FOLLOWUP_ACTION_ZH.test(last) && !COMPLETED_ACTION_ZH.test(last);
893
- }
894
904
  function isMarkupOnlyStop(reason, input) {
895
905
  return reason.kind === "stop" && !input.sawToolCall && isResidueOnly(input.text);
896
906
  }
@@ -959,8 +969,7 @@ var EmptyTurnTracker = class {
959
969
  sawToolCall: this.#sawToolCall,
960
970
  textLength: text2.length,
961
971
  reasoningLength: reasoning.length,
962
- markupOnly: isResidueOnly(text2),
963
- pendingAction: isPendingActionTurn(text2)
972
+ markupOnly: isResidueOnly(text2)
964
973
  };
965
974
  }
966
975
  /**
@@ -975,12 +984,11 @@ var EmptyTurnTracker = class {
975
984
  resolve(reason) {
976
985
  const text2 = this.#text();
977
986
  const markupOnly = isMarkupOnlyStop(reason, { sawToolCall: this.#sawToolCall, text: text2 });
978
- const pendingAction = reason.kind === "stop" && !this.#sawToolCall && isPendingActionTurn(text2);
979
- if (!this.#enabled || !markupOnly && !pendingAction) {
987
+ if (!this.#enabled || !markupOnly) {
980
988
  return reason;
981
989
  }
982
990
  this.#notify();
983
- return { kind: "error", failure: { code: OPENDESIGN_EOT, message: pendingAction ? INCOMPLETE_TURN_MESSAGE : EMPTY_TURN_MESSAGE } };
991
+ return { kind: "error", failure: { code: OPENDESIGN_EOT, message: EMPTY_TURN_MESSAGE } };
984
992
  }
985
993
  /** Report one rewrite to the telemetry hook; monitoring must never break the stream. */
986
994
  #notify() {
@@ -2021,7 +2029,7 @@ var CoRouterAdapter = class extends LlmAdapter {
2021
2029
  if (!isModelEnabled(id, config.modelSettings)) throw new LlmError11("\u8BE5\u6A21\u578B\u5DF2\u5728 CoRouter \u8BBE\u7F6E\u4E2D\u505C\u7528", "MODEL_DISABLED");
2022
2030
  const configured = applyModelSettings(row, config.modelSettings?.[id]);
2023
2031
  const output = config.modelSettings?.[id]?.maxTokens;
2024
- 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");
2032
+ if (output !== void 0 && configured.contextWindow !== void 0 && output >= configured.contextWindow) throw new LlmError11("\u6A21\u578B\u6700\u5927\u8F93\u51FA\u5FC5\u987B\u5C0F\u4E8E\u5F53\u524D\u603B\u7A97\u53E3\uFF08\u542B\u8F93\u51FA\u9884\u7559\uFF09\uFF0C\u8BF7\u8C03\u6574\u6A21\u578B\u53C2\u6570", "INVALID_REQUEST");
2025
2033
  return configured;
2026
2034
  }
2027
2035
  async listModels(provider) {
@@ -2314,12 +2322,14 @@ function cancellableDelay(delay, signal) {
2314
2322
  });
2315
2323
  }
2316
2324
  var EotRecovery = class {
2317
- constructor(enabled, wait = cancellableDelay) {
2325
+ constructor(enabled, wait = cancellableDelay, onRetry) {
2318
2326
  this.enabled = enabled;
2319
2327
  this.wait = wait;
2328
+ this.onRetry = onRetry;
2320
2329
  }
2321
2330
  enabled;
2322
2331
  wait;
2332
+ onRetry;
2323
2333
  #lifetime = new AbortController();
2324
2334
  #states = /* @__PURE__ */ new WeakMap();
2325
2335
  #active = /* @__PURE__ */ new Set();
@@ -2341,6 +2351,10 @@ var EotRecovery = class {
2341
2351
  agent.session.append("llm/retry", { retryId: state.retryId, turn, step, provider, mode: "always", policyKey: POLICY_KEY, retry: state.retry, delayMs, failure });
2342
2352
  if (!await this.wait(delayMs, fused) || fused.aborted || !this.enabled()) return;
2343
2353
  agent.session.append("llm/retry-started", { retryId: state.retryId, turn, step, retry: state.retry });
2354
+ try {
2355
+ this.onRetry?.();
2356
+ } catch {
2357
+ }
2344
2358
  return { kind: "retry" };
2345
2359
  }
2346
2360
  async dispose() {
@@ -2348,8 +2362,8 @@ var EotRecovery = class {
2348
2362
  await Promise.allSettled([...this.#active]);
2349
2363
  }
2350
2364
  };
2351
- function installEotRecovery(ctx, enabled) {
2352
- const recovery = new EotRecovery(enabled);
2365
+ function installEotRecovery(ctx, enabled, onRetry) {
2366
+ const recovery = new EotRecovery(enabled, cancellableDelay, onRetry);
2353
2367
  const events = ctx;
2354
2368
  const remove = events.on("agent/request-error", recovery.handle, { prepend: true });
2355
2369
  ctx.effect(() => async () => {
@@ -2358,6 +2372,403 @@ function installEotRecovery(ctx, enabled) {
2358
2372
  });
2359
2373
  }
2360
2374
 
2375
+ // src/turn-monitor.ts
2376
+ import { createHash } from "node:crypto";
2377
+ import { createUserMessage, LlmError as LlmError13 } from "@deepseek-ai/dsh-llm";
2378
+ var FINISH_TURN_TOOL = "opendesign_finish_turn";
2379
+ var MAX_EVIDENCE = 64;
2380
+ var MAX_SUMMARY = 1200;
2381
+ var MAX_NEXT_ACTION = 800;
2382
+ var OUTCOMES = ["completed", "waiting_user", "waiting_work", "blocked", "continue"];
2383
+ var outcomeSchema = {
2384
+ type: "object",
2385
+ additionalProperties: false,
2386
+ required: ["status", "summary", "evidence"],
2387
+ properties: {
2388
+ status: { type: "string", enum: OUTCOMES },
2389
+ summary: { type: "string", description: "\u975E\u7A7A\u6536\u5C3E\u8BF4\u660E\uFF0C\u6700\u591A1200\u5B57\u7B26\u3002" },
2390
+ evidence: { type: "array", items: { type: "integer" }, description: "\u6700\u591A16\u4E2A\u975E\u8D1F\u5DE5\u5177\u7ED3\u679C\u5E8F\u53F7\u3002" },
2391
+ nextAction: { type: "string", description: "\u7EE7\u7EED\u6267\u884C\u65F6\u5FC5\u586B\uFF0C\u6700\u591A800\u5B57\u7B26\u3002" }
2392
+ }
2393
+ };
2394
+ function parseOutcome(value) {
2395
+ 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)) {
2396
+ throw new LlmError13("\u6536\u5C3E\u72B6\u6001\u6216\u8BC1\u636E\u5F15\u7528\u65E0\u6548", "INVALID_REQUEST");
2397
+ }
2398
+ 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");
2399
+ return {
2400
+ status: value.status,
2401
+ summary: value.summary,
2402
+ evidence: [...new Set(value.evidence)],
2403
+ ...typeof value.nextAction === "string" ? { nextAction: value.nextAction } : {}
2404
+ };
2405
+ }
2406
+ function fresh(turn) {
2407
+ return {
2408
+ turn,
2409
+ assistantSeq: -1,
2410
+ checkedSeq: -1,
2411
+ finish: void 0,
2412
+ interrupted: false,
2413
+ truncated: false,
2414
+ assistantMonitored: false,
2415
+ agent: void 0,
2416
+ removeTool: void 0,
2417
+ steering: void 0,
2418
+ continuations: 0,
2419
+ stagnant: 0,
2420
+ progress: 0,
2421
+ reviewedProgress: 0,
2422
+ settled: false,
2423
+ outcome: void 0,
2424
+ nativeConcluded: false,
2425
+ calls: /* @__PURE__ */ new Map(),
2426
+ evidence: /* @__PURE__ */ new Map(),
2427
+ fingerprints: /* @__PURE__ */ new Set(),
2428
+ pending: /* @__PURE__ */ new Map(),
2429
+ nativeEndings: /* @__PURE__ */ new Set()
2430
+ };
2431
+ }
2432
+ function services(ctx) {
2433
+ return ctx;
2434
+ }
2435
+ function monitored(session) {
2436
+ const header = session.requestHeader();
2437
+ return header?.config.provider === PLAN_PROVIDER && header.config.model === "deepseek-v4.1-flash" && Boolean(header.tools?.length);
2438
+ }
2439
+ var TurnMonitor = class {
2440
+ constructor(ctx, config, now = Date.now) {
2441
+ this.ctx = ctx;
2442
+ this.config = config;
2443
+ this.now = now;
2444
+ }
2445
+ ctx;
2446
+ config;
2447
+ now;
2448
+ #states = /* @__PURE__ */ new WeakMap();
2449
+ #active = /* @__PURE__ */ new Set();
2450
+ #disposed = false;
2451
+ #checks = 0;
2452
+ #continuations = 0;
2453
+ #requestRetries = 0;
2454
+ #last;
2455
+ status() {
2456
+ return {
2457
+ available: !this.#disposed && services(this.ctx).get("tools") !== void 0,
2458
+ checks: this.#checks,
2459
+ continuations: this.#continuations,
2460
+ requestRetries: this.#requestRetries,
2461
+ ...this.#last ? { last: { ...this.#last } } : {}
2462
+ };
2463
+ }
2464
+ requestRetried() {
2465
+ if (!this.#disposed) this.#requestRetries++;
2466
+ }
2467
+ #report(decision, reason) {
2468
+ this.#last = { at: new Date(this.now()).toISOString(), decision, reason };
2469
+ }
2470
+ /** The completion handshake is opt-in; the empty-turn guard stays the outer switch. */
2471
+ #reviewing() {
2472
+ const config = this.config();
2473
+ return config.emptyTurnGuard === true && config.turnCompletionReview === true;
2474
+ }
2475
+ #release(state) {
2476
+ const remove = state.removeTool;
2477
+ state.removeTool = void 0;
2478
+ try {
2479
+ remove?.();
2480
+ } catch {
2481
+ this.#report("unverified", "service-unavailable");
2482
+ }
2483
+ if (state.steering && state.agent) {
2484
+ try {
2485
+ state.agent.inbox.remove(state.steering);
2486
+ } catch {
2487
+ this.#report("unverified", "service-unavailable");
2488
+ }
2489
+ }
2490
+ state.steering = void 0;
2491
+ state.pending.clear();
2492
+ this.#active.delete(state);
2493
+ }
2494
+ configurationChanged() {
2495
+ if (this.#reviewing()) return;
2496
+ for (const state of [...this.#active]) {
2497
+ state.settled = true;
2498
+ this.#release(state);
2499
+ }
2500
+ this.#report("skipped", "disabled");
2501
+ }
2502
+ dispose() {
2503
+ this.#disposed = true;
2504
+ for (const state of [...this.#active]) this.#release(state);
2505
+ }
2506
+ observe = (session, event) => {
2507
+ if (this.#disposed || !record(event.data)) return;
2508
+ const data = event.data;
2509
+ if (event.type === "turn/start" && Number.isSafeInteger(data.turn)) {
2510
+ const previous = this.#states.get(session);
2511
+ if (previous) this.#release(previous);
2512
+ this.#states.set(session, fresh(data.turn));
2513
+ return;
2514
+ }
2515
+ const state = this.#states.get(session);
2516
+ if (!state) return;
2517
+ if (event.type === "user/message" && record(data.source)) {
2518
+ const source = data.source;
2519
+ if (source.kind === "opendesign-review" && data.id === state.steering && source.turn === state.turn && source.checkpoint === state.checkedSeq) state.steering = void 0;
2520
+ else if (source.kind === "user" && state.continuations > 0) {
2521
+ state.settled = true;
2522
+ this.#release(state);
2523
+ this.#report("skipped", "superseded");
2524
+ }
2525
+ return;
2526
+ }
2527
+ if (data.turn !== state.turn) return;
2528
+ if (event.type === "turn/end") {
2529
+ this.#release(state);
2530
+ this.#states.delete(session);
2531
+ return;
2532
+ }
2533
+ if (!this.config().emptyTurnGuard || !monitored(session)) {
2534
+ this.#release(state);
2535
+ return;
2536
+ }
2537
+ if (event.type === "assistant/message" && record(data.message)) {
2538
+ state.assistantSeq = event.seq;
2539
+ state.interrupted = data.interrupted === true;
2540
+ const source = data.message.source;
2541
+ state.assistantMonitored = record(source) && source.provider === PLAN_PROVIDER && source.model === "deepseek-v4.1-flash";
2542
+ return;
2543
+ }
2544
+ if (event.type === "tool/call" && typeof data.callId === "string" && typeof data.name === "string") {
2545
+ if (state.calls.size >= MAX_EVIDENCE) state.calls.delete(state.calls.keys().next().value ?? "");
2546
+ state.calls.set(data.callId, { name: data.name, arguments: createHash("sha256").update(typeof data.arguments === "string" ? data.arguments : "").digest("hex") });
2547
+ return;
2548
+ }
2549
+ if (event.type !== "tool/result" || !record(data.message) || typeof data.message.toolCallId !== "string") return;
2550
+ const callId = data.message.toolCallId;
2551
+ const pending = state.pending.get(callId);
2552
+ state.pending.delete(callId);
2553
+ if (pending && data.message.isError !== true) state.outcome = pending;
2554
+ if (state.nativeEndings.delete(callId) && data.message.isError !== true) state.nativeConcluded = true;
2555
+ const call = state.calls.get(callId);
2556
+ state.calls.delete(callId);
2557
+ if (!call || call.name === FINISH_TURN_TOOL || pending) return;
2558
+ const fingerprint = createHash("sha256").update(JSON.stringify([call.name, call.arguments, data.message.content, data.message.isError === true])).digest("hex");
2559
+ const success = data.message.isError !== true;
2560
+ if (success && !state.fingerprints.has(fingerprint)) {
2561
+ state.progress++;
2562
+ if (state.fingerprints.size >= MAX_EVIDENCE) state.fingerprints.delete(state.fingerprints.values().next().value ?? "");
2563
+ state.fingerprints.add(fingerprint);
2564
+ }
2565
+ if (state.evidence.size >= MAX_EVIDENCE) state.evidence.delete(state.evidence.keys().next().value ?? -1);
2566
+ state.evidence.set(event.seq, { seq: event.seq, name: call.name, success, fingerprint });
2567
+ };
2568
+ stream = ({ agent, frame }) => {
2569
+ const state = this.#states.get(agent.session);
2570
+ if (!state || !this.config().emptyTurnGuard || !monitored(agent.session)) return;
2571
+ if (frame.type === "start") {
2572
+ state.finish = void 0;
2573
+ state.outcome = void 0;
2574
+ state.nativeConcluded = false;
2575
+ }
2576
+ if (frame.type === "chunk" && frame.chunk?.type === "finish") {
2577
+ state.finish = frame.chunk.reason?.kind;
2578
+ state.truncated ||= state.finish === "max-tokens";
2579
+ }
2580
+ };
2581
+ #goalOwns(agent) {
2582
+ const goal = services(agent.ctx).get("goals")?.get(agent);
2583
+ return goal !== void 0 && goal.phase !== "complete";
2584
+ }
2585
+ #workRunning(agent) {
2586
+ const host = services(agent.ctx);
2587
+ if (host.get("jobs")?.list(agent.session.id).some((job) => job.owner === agent.session.id && (job.status === "running" || job.status === "stopping"))) return true;
2588
+ const registry = host.get("agents");
2589
+ if (!registry) return false;
2590
+ const pending = [agent];
2591
+ const visited = /* @__PURE__ */ new Set([agent.id]);
2592
+ const agents = registry.list();
2593
+ while (pending.length) {
2594
+ const parent = pending.pop();
2595
+ if (!parent) break;
2596
+ for (const child of agents) {
2597
+ if (visited.has(child.id) || !registry.isOwnedBy(child.id, parent)) continue;
2598
+ visited.add(child.id);
2599
+ if (child.status === "running") return true;
2600
+ pending.push(child);
2601
+ }
2602
+ }
2603
+ return false;
2604
+ }
2605
+ #tool(state) {
2606
+ return {
2607
+ name: FINISH_TURN_TOOL,
2608
+ 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",
2609
+ parameters: outcomeSchema,
2610
+ output: { schema: outcomeSchema, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] },
2611
+ execute: async (args, exec) => {
2612
+ exec.signal.throwIfAborted();
2613
+ if (this.#disposed || !this.#reviewing() || state.settled || exec.agent !== state.agent || !state.removeTool || !exec.agent || this.#states.get(exec.agent.session) !== state || !monitored(exec.agent.session)) {
2614
+ throw new LlmError13("\u5F53\u524D\u6CA1\u6709\u53EF\u63D0\u4EA4\u7684\u6536\u5C3E\u6838\u9A8C", "INVALID_REQUEST");
2615
+ }
2616
+ const outcome = parseOutcome(args);
2617
+ 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");
2618
+ if (outcome.status === "completed" && state.evidence.size > 0 && outcome.evidence.length === 0) {
2619
+ 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");
2620
+ }
2621
+ const running = this.#workRunning(exec.agent);
2622
+ 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");
2623
+ 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");
2624
+ exec.signal.throwIfAborted();
2625
+ exec.concludeTurn();
2626
+ return outcome;
2627
+ }
2628
+ };
2629
+ }
2630
+ toolResult = (exec, result) => {
2631
+ if (!exec.agent || result.isError || result.concludesTurn !== true || exec.signal.aborted) return;
2632
+ const state = this.#states.get(exec.agent.session);
2633
+ if (!state || state.settled) return;
2634
+ const root = exec.rootCallId ?? exec.callId;
2635
+ if (exec.name !== FINISH_TURN_TOOL) {
2636
+ if (!state.pending.has(root)) state.nativeEndings.add(root);
2637
+ return;
2638
+ }
2639
+ if (state.agent !== exec.agent || !state.removeTool) return;
2640
+ try {
2641
+ const outcome = parseOutcome(result.value);
2642
+ if (outcome.evidence.some((seq) => state.evidence.get(seq)?.success !== true) || outcome.status === "completed" && state.evidence.size > 0 && outcome.evidence.length === 0) {
2643
+ this.#report("unverified", "invalid-evidence");
2644
+ return;
2645
+ }
2646
+ state.pending.set(root, outcome);
2647
+ } catch {
2648
+ }
2649
+ };
2650
+ stopping = ({ agent, turn, signal }) => {
2651
+ const state = this.#states.get(agent.session);
2652
+ if (!state || state.turn !== turn || state.settled || state.assistantSeq < 0 || state.checkedSeq === state.assistantSeq) return;
2653
+ if (this.#disposed || !this.#reviewing() || !monitored(agent.session) || !state.assistantMonitored) {
2654
+ this.#release(state);
2655
+ return;
2656
+ }
2657
+ state.agent = agent;
2658
+ state.checkedSeq = state.assistantSeq;
2659
+ if (signal.aborted || state.interrupted) {
2660
+ this.#release(state);
2661
+ this.#report("skipped", "cancelled");
2662
+ return;
2663
+ }
2664
+ if (state.truncated || state.finish !== "stop" && state.finish !== "tool-calls") {
2665
+ this.#release(state);
2666
+ this.#report("skipped", state.truncated ? "truncated" : "request-failed");
2667
+ return;
2668
+ }
2669
+ if (state.nativeConcluded) {
2670
+ state.settled = true;
2671
+ this.#release(state);
2672
+ this.#report("skipped", "tool-concluded");
2673
+ return;
2674
+ }
2675
+ if (agent.inbox.nextStep.length || agent.inbox.nextTurn.length) {
2676
+ this.#release(state);
2677
+ this.#report("skipped", "superseded");
2678
+ return;
2679
+ }
2680
+ this.#checks++;
2681
+ try {
2682
+ if (this.#goalOwns(agent)) {
2683
+ state.settled = true;
2684
+ this.#release(state);
2685
+ this.#report("skipped", "goal-owned");
2686
+ return;
2687
+ }
2688
+ if (this.#workRunning(agent)) {
2689
+ state.settled = true;
2690
+ this.#release(state);
2691
+ this.#report("waiting-work", "work-running");
2692
+ return;
2693
+ }
2694
+ } catch {
2695
+ state.settled = true;
2696
+ this.#release(state);
2697
+ this.#report("unverified", "service-unavailable");
2698
+ return;
2699
+ }
2700
+ const outcome = state.outcome;
2701
+ if (outcome && outcome.status !== "continue") {
2702
+ const decision = outcome.status === "completed" ? "completed" : outcome.status === "waiting_user" ? "waiting-user" : outcome.status === "waiting_work" ? "waiting-work" : "blocked";
2703
+ const reason = outcome.status === "completed" ? "reported-complete" : outcome.status === "waiting_user" ? "needs-user" : outcome.status === "waiting_work" ? "work-running" : "reported-blocked";
2704
+ state.settled = true;
2705
+ this.#release(state);
2706
+ this.#report(decision, reason);
2707
+ return;
2708
+ }
2709
+ const config = this.config();
2710
+ if (state.continuations > 0) state.stagnant = state.progress === state.reviewedProgress ? state.stagnant + 1 : 0;
2711
+ const limit = state.continuations >= (config.turnReviewMaxContinuations ?? 3) ? "continuation-limit" : state.stagnant >= (config.turnReviewNoProgressLimit ?? 2) ? "no-progress" : void 0;
2712
+ if (limit) {
2713
+ state.settled = true;
2714
+ this.#release(state);
2715
+ this.#report("limited", limit);
2716
+ return;
2717
+ }
2718
+ const tools = services(agent.ctx).get("tools");
2719
+ if (!tools) {
2720
+ state.settled = true;
2721
+ this.#report("unverified", "service-unavailable");
2722
+ return;
2723
+ }
2724
+ if (!state.removeTool) {
2725
+ try {
2726
+ state.removeTool = tools.register(this.#tool(state));
2727
+ this.#active.add(state);
2728
+ } catch {
2729
+ state.settled = true;
2730
+ this.#report("unverified", "service-unavailable");
2731
+ return;
2732
+ }
2733
+ }
2734
+ const evidence = [...state.evidence.values()].slice(-16).map((item) => ({ seq: item.seq, tool: item.name, success: item.success }));
2735
+ const nextAction = outcome?.status === "continue" ? outcome.nextAction : void 0;
2736
+ 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` : ""}
2737
+ \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
2738
+ \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` }] });
2739
+ state.steering = message.id;
2740
+ try {
2741
+ agent.steer(message);
2742
+ } catch {
2743
+ state.settled = true;
2744
+ this.#release(state);
2745
+ this.#report("unverified", "service-unavailable");
2746
+ return;
2747
+ }
2748
+ state.continuations++;
2749
+ state.reviewedProgress = state.progress;
2750
+ this.#continuations++;
2751
+ this.#report("continued", nextAction ? "pending-action" : "missing-outcome");
2752
+ };
2753
+ disposedAgent = ({ agent }) => {
2754
+ const state = this.#states.get(agent.session);
2755
+ if (state) this.#release(state);
2756
+ this.#states.delete(agent.session);
2757
+ };
2758
+ };
2759
+ function installTurnMonitor(ctx, config) {
2760
+ const monitor = new TurnMonitor(ctx, config);
2761
+ const events = ctx;
2762
+ events.on("session/event", monitor.observe);
2763
+ events.on("agent/assistant-stream", monitor.stream);
2764
+ events.on("agent/turn-stopping", monitor.stopping);
2765
+ events.on("tools/result", monitor.toolResult);
2766
+ events.on("agent/disposed", monitor.disposedAgent);
2767
+ ctx.on("loader/volatile-update", () => monitor.configurationChanged());
2768
+ ctx.effect(() => () => monitor.dispose());
2769
+ return monitor;
2770
+ }
2771
+
2361
2772
  // src/model-discovery.ts
2362
2773
  import { attributionHeaders as attributionHeaders2 } from "@deepseek-ai/dsh-llm";
2363
2774
  var DISCOVERY_TIMEOUT_MS = 2e4;
@@ -3014,7 +3425,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
3014
3425
 
3015
3426
  // src/device-auth.ts
3016
3427
  var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
3017
- var DEVICE_AUTH_PLUGIN_VERSION = "0.1.14";
3428
+ var DEVICE_AUTH_PLUGIN_VERSION = "0.1.16";
3018
3429
  var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
3019
3430
  var DEVICE_RESPONSE_MAX_BYTES = 65536;
3020
3431
  var DEVICE_POLL_MIN_MS = 1e3;
@@ -3945,6 +4356,10 @@ async function readDesktopQuota(session, signal, runner = runVela, fetcher = fet
3945
4356
  };
3946
4357
  }
3947
4358
 
4359
+ // src/turn-monitor-status.ts
4360
+ var REVIEW_DECISIONS = ["continued", "completed", "waiting-user", "waiting-work", "blocked", "limited", "skipped", "unverified"];
4361
+ 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"];
4362
+
3948
4363
  // src/remote.ts
3949
4364
  var MAX_REVISION = 256;
3950
4365
  var MAX_JOB_ID = 128;
@@ -4126,6 +4541,7 @@ function parseStatusConfig(value) {
4126
4541
  if (!ENV_REF.test(apiKeyEnv)) throw new Error("\u51ED\u636E\u5F15\u7528\u540D\u5FC5\u987B\u662F\u5408\u6CD5\u6807\u8BC6\u7B26");
4127
4542
  return {
4128
4543
  emptyTurnGuard: flag(value.emptyTurnGuard, "\u7A7A\u8F6E\u4FDD\u62A4\u5F00\u5173"),
4544
+ ...value.turnCompletionReview === void 0 ? {} : { turnCompletionReview: flag(value.turnCompletionReview, "\u7ED3\u675F\u56DE\u5408\u6838\u9A8C\u5F00\u5173") },
4129
4545
  useDesktopCredential: flag(value.useDesktopCredential, "\u684C\u9762\u767B\u5F55\u6001\u5F00\u5173"),
4130
4546
  baseURL: text(value.baseURL, "\u63A8\u7406\u5730\u5740", MAX_BASE_URL),
4131
4547
  apiKeyEnv,
@@ -4134,7 +4550,9 @@ function parseStatusConfig(value) {
4134
4550
  ...value.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: positiveInteger(value.requestTimeoutMs, "\u8BF7\u6C42\u8D85\u65F6", 36e5, 1e3) },
4135
4551
  ...value.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: positiveInteger(value.streamIdleTimeoutMs, "\u6D41\u7A7A\u95F2\u8D85\u65F6", 18e5, 1e3) },
4136
4552
  ...value.quotaRefreshSeconds === void 0 ? {} : { quotaRefreshSeconds: positiveInteger(value.quotaRefreshSeconds, "\u81EA\u52A8\u5237\u65B0\u95F4\u9694", 3600, 5) },
4137
- ...value.maxRequestImageBytes === void 0 ? {} : { maxRequestImageBytes: positiveInteger(value.maxRequestImageBytes, "\u8BF7\u6C42\u56FE\u7247\u9884\u7B97", MAX_REQUEST_IMAGE_BYTES, MIN_REQUEST_IMAGE_BYTES) }
4553
+ ...value.maxRequestImageBytes === void 0 ? {} : { maxRequestImageBytes: positiveInteger(value.maxRequestImageBytes, "\u8BF7\u6C42\u56FE\u7247\u9884\u7B97", MAX_REQUEST_IMAGE_BYTES, MIN_REQUEST_IMAGE_BYTES) },
4554
+ ...value.turnReviewMaxContinuations === void 0 ? {} : { turnReviewMaxContinuations: positiveInteger(value.turnReviewMaxContinuations, "\u6536\u5C3E\u7EED\u529E\u6B21\u6570", 10) },
4555
+ ...value.turnReviewNoProgressLimit === void 0 ? {} : { turnReviewNoProgressLimit: positiveInteger(value.turnReviewNoProgressLimit, "\u65E0\u8FDB\u5C55\u6B21\u6570", 5) }
4138
4556
  };
4139
4557
  }
4140
4558
  function parseStatus(value) {
@@ -4159,12 +4577,25 @@ function parseStatus(value) {
4159
4577
  login: parseLoginState(value.login),
4160
4578
  config: parseStatusConfig(value.config),
4161
4579
  guardedTurns: count(value.guardedTurns, "\u5DF2\u62E6\u622A\u7A7A\u8F6E\u6570"),
4580
+ ...value.turnMonitor === void 0 ? {} : { turnMonitor: parseTurnMonitor(value.turnMonitor) },
4162
4581
  models: parsed,
4163
4582
  ...value.modelsSource === void 0 ? {} : { modelsSource: member(value.modelsSource, ["builtin", "openai"], "\u6A21\u578B\u76EE\u5F55\u6765\u6E90") },
4164
4583
  ...value.modelsUpdatedAt === void 0 ? {} : { modelsUpdatedAt: isoTime(value.modelsUpdatedAt, "\u6A21\u578B\u66F4\u65B0\u65F6\u95F4") },
4165
4584
  ...value.modelsError === void 0 ? {} : { modelsError: text(value.modelsError, "\u6A21\u578B\u66F4\u65B0\u63D0\u793A", MAX_MESSAGE) }
4166
4585
  };
4167
4586
  }
4587
+ function parseTurnMonitor(value) {
4588
+ if (!record(value)) throw new Error("\u7ED3\u675F\u6838\u9A8C\u72B6\u6001\u5FC5\u987B\u662F\u5BF9\u8C61");
4589
+ const last = value.last;
4590
+ if (last !== void 0 && !record(last)) throw new Error("\u6700\u8FD1\u7ED3\u675F\u6838\u9A8C\u5FC5\u987B\u662F\u5BF9\u8C61");
4591
+ return {
4592
+ available: flag(value.available, "\u6536\u5C3E\u6838\u9A8C\u662F\u5426\u53EF\u7528"),
4593
+ checks: count(value.checks, "\u6536\u5C3E\u6838\u9A8C\u6B21\u6570"),
4594
+ continuations: count(value.continuations, "\u4EFB\u52A1\u7EED\u529E\u6B21\u6570"),
4595
+ requestRetries: count(value.requestRetries, "\u8BF7\u6C42\u91CD\u8BD5\u6B21\u6570"),
4596
+ ...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") } } : {}
4597
+ };
4598
+ }
4168
4599
  function parseStartLoginRequest(value) {
4169
4600
  if (!record(value)) throw new Error("\u767B\u5F55\u8BF7\u6C42\u5FC5\u987B\u662F\u5BF9\u8C61");
4170
4601
  return { expectedRevision: text(value.expectedRevision, "\u914D\u7F6E\u7248\u672C", MAX_REVISION) };
@@ -4191,7 +4622,7 @@ var name = "llm-opendesign-corouter";
4191
4622
  var inject = ["llm"];
4192
4623
  var API_KEY = credentialKey2(name, "api-key");
4193
4624
  var SESSION = credentialKey2(name, "console");
4194
- var hash = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4625
+ var hash = (value) => createHash2("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4195
4626
  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" });
4196
4627
  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" });
4197
4628
  function grantOf(value) {
@@ -4220,6 +4651,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4220
4651
  __publicField(this, "_quotaPending");
4221
4652
  __publicField(this, "_quotaController");
4222
4653
  __publicField(this, "guardedTurns", 0);
4654
+ __publicField(this, "turnMonitorStatus");
4223
4655
  __publicField(this, "_models", MODELS);
4224
4656
  __publicField(this, "_modelsUpdatedAt");
4225
4657
  __publicField(this, "_modelsError");
@@ -4353,6 +4785,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4353
4785
  login: this._login.status(),
4354
4786
  config: state.config,
4355
4787
  guardedTurns: this.guardedTurns,
4788
+ ...this.turnMonitorStatus ? { turnMonitor: this.turnMonitorStatus() } : {},
4356
4789
  models: this._models.map((row) => {
4357
4790
  const { id, name: name2, group: group2, contextWindow, maxOutputTokens, inputModalities } = row;
4358
4791
  const reasoningEfforts = modelReasoningEfforts(row, state.config.apiProtocol ?? "chat-completions");
@@ -4589,11 +5022,13 @@ __decoratorMetadata(_init, OpenDesignCoRouterService);
4589
5022
  function apply(ctx, config) {
4590
5023
  const current = () => readConfig(config);
4591
5024
  current();
4592
- installEotRecovery(ctx, () => current().emptyTurnGuard);
4593
5025
  ctx.inject(["settings"], (scope) => scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)));
4594
5026
  let modelsChanged = () => {
4595
5027
  };
4596
5028
  const service = new OpenDesignCoRouterService(ctx, current, { resolveSession, readQuota, readDesktopQuota, modelsChanged: () => modelsChanged() });
5029
+ const turnMonitor = installTurnMonitor(ctx, current);
5030
+ service.turnMonitorStatus = () => turnMonitor.status();
5031
+ installEotRecovery(ctx, () => current().emptyTurnGuard, () => turnMonitor.requestRetried());
4597
5032
  const replayKeys = new ReplayKeyStore(() => ctx.get("credentials"));
4598
5033
  const adapter = new CoRouterAdapter({
4599
5034
  config: current,
@@ -4620,10 +5055,10 @@ function apply(ctx, config) {
4620
5055
  modelsChanged();
4621
5056
  });
4622
5057
  ctx.llm.registerModelDiscovery(SETTINGS_NS, async (request, signal) => {
4623
- 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");
5058
+ 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");
4624
5059
  const config2 = current();
4625
5060
  const key = request.apiKey ?? await service.resolveApiKey(config2.apiKeyEnv, config2.baseURL);
4626
- if (!key) throw new LlmError13("\u8BF7\u5148\u914D\u7F6E CoRouter API Key", "MISSING_CREDENTIAL");
5061
+ if (!key) throw new LlmError14("\u8BF7\u5148\u914D\u7F6E CoRouter API Key", "MISSING_CREDENTIAL");
4627
5062
  const models = await fetchModelCatalog(config2.baseURL, key, signal);
4628
5063
  return models.map((row) => {
4629
5064
  const effective = applyModelSettings(row, config2.modelSettings?.[row.id]);