dsh-opendesign-corouter 0.1.14 → 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,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";
@@ -340,7 +340,9 @@ var Config = Schema.object({
340
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(),
341
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(),
342
342
  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(),
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(),
344
346
  quotaRefreshSeconds: Schema.natural().min(5).max(3600).default(60).description("\u989D\u5EA6\u81EA\u52A8\u5237\u65B0\u95F4\u9694\uFF08\u79D2\uFF09").volatile(),
345
347
  requestTimeoutMs: Schema.natural().min(1e3).max(36e5).default(18e5).description("\u63A8\u7406\u8BF7\u6C42\u603B\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile(),
346
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(),
@@ -371,7 +373,9 @@ function readConfig(config) {
371
373
  emptyTurnGuard: config.emptyTurnGuard.get(),
372
374
  requestTimeoutMs: config.requestTimeoutMs.get(),
373
375
  streamIdleTimeoutMs: config.streamIdleTimeoutMs.get(),
374
- maxRequestImageBytes: config.maxRequestImageBytes.get()
376
+ maxRequestImageBytes: config.maxRequestImageBytes.get(),
377
+ turnReviewMaxContinuations: config.turnReviewMaxContinuations.get(),
378
+ turnReviewNoProgressLimit: config.turnReviewNoProgressLimit.get()
375
379
  };
376
380
  }
377
381
 
@@ -854,7 +858,6 @@ var OPENDESIGN_EOT = "OPENDESIGN_EOT";
854
858
 
855
859
  // src/empty-turn.ts
856
860
  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
861
  var RESIDUE_PATTERNS = [
859
862
  /<\s*rea:tool_calls\s*>[\s\S]*?(?:<\s*\/\s*rea:tool_calls\s*>|$)/giu,
860
863
  /<\s*rea:tool(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*rea:tool\s*>|$)/giu,
@@ -877,20 +880,6 @@ function stripProtocolResidue(text2) {
877
880
  function isResidueOnly(text2) {
878
881
  return text2 === void 0 || stripProtocolResidue(text2) === "";
879
882
  }
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
883
  function isMarkupOnlyStop(reason, input) {
895
884
  return reason.kind === "stop" && !input.sawToolCall && isResidueOnly(input.text);
896
885
  }
@@ -959,8 +948,7 @@ var EmptyTurnTracker = class {
959
948
  sawToolCall: this.#sawToolCall,
960
949
  textLength: text2.length,
961
950
  reasoningLength: reasoning.length,
962
- markupOnly: isResidueOnly(text2),
963
- pendingAction: isPendingActionTurn(text2)
951
+ markupOnly: isResidueOnly(text2)
964
952
  };
965
953
  }
966
954
  /**
@@ -975,12 +963,11 @@ var EmptyTurnTracker = class {
975
963
  resolve(reason) {
976
964
  const text2 = this.#text();
977
965
  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) {
966
+ if (!this.#enabled || !markupOnly) {
980
967
  return reason;
981
968
  }
982
969
  this.#notify();
983
- 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 } };
984
971
  }
985
972
  /** Report one rewrite to the telemetry hook; monitoring must never break the stream. */
986
973
  #notify() {
@@ -2314,12 +2301,14 @@ function cancellableDelay(delay, signal) {
2314
2301
  });
2315
2302
  }
2316
2303
  var EotRecovery = class {
2317
- constructor(enabled, wait = cancellableDelay) {
2304
+ constructor(enabled, wait = cancellableDelay, onRetry) {
2318
2305
  this.enabled = enabled;
2319
2306
  this.wait = wait;
2307
+ this.onRetry = onRetry;
2320
2308
  }
2321
2309
  enabled;
2322
2310
  wait;
2311
+ onRetry;
2323
2312
  #lifetime = new AbortController();
2324
2313
  #states = /* @__PURE__ */ new WeakMap();
2325
2314
  #active = /* @__PURE__ */ new Set();
@@ -2341,6 +2330,10 @@ var EotRecovery = class {
2341
2330
  agent.session.append("llm/retry", { retryId: state.retryId, turn, step, provider, mode: "always", policyKey: POLICY_KEY, retry: state.retry, delayMs, failure });
2342
2331
  if (!await this.wait(delayMs, fused) || fused.aborted || !this.enabled()) return;
2343
2332
  agent.session.append("llm/retry-started", { retryId: state.retryId, turn, step, retry: state.retry });
2333
+ try {
2334
+ this.onRetry?.();
2335
+ } catch {
2336
+ }
2344
2337
  return { kind: "retry" };
2345
2338
  }
2346
2339
  async dispose() {
@@ -2348,8 +2341,8 @@ var EotRecovery = class {
2348
2341
  await Promise.allSettled([...this.#active]);
2349
2342
  }
2350
2343
  };
2351
- function installEotRecovery(ctx, enabled) {
2352
- const recovery = new EotRecovery(enabled);
2344
+ function installEotRecovery(ctx, enabled, onRetry) {
2345
+ const recovery = new EotRecovery(enabled, cancellableDelay, onRetry);
2353
2346
  const events = ctx;
2354
2347
  const remove = events.on("agent/request-error", recovery.handle, { prepend: true });
2355
2348
  ctx.effect(() => async () => {
@@ -2358,6 +2351,398 @@ function installEotRecovery(ctx, enabled) {
2358
2351
  });
2359
2352
  }
2360
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
+
2361
2746
  // src/model-discovery.ts
2362
2747
  import { attributionHeaders as attributionHeaders2 } from "@deepseek-ai/dsh-llm";
2363
2748
  var DISCOVERY_TIMEOUT_MS = 2e4;
@@ -3014,7 +3399,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
3014
3399
 
3015
3400
  // src/device-auth.ts
3016
3401
  var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
3017
- var DEVICE_AUTH_PLUGIN_VERSION = "0.1.14";
3402
+ var DEVICE_AUTH_PLUGIN_VERSION = "0.1.15";
3018
3403
  var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
3019
3404
  var DEVICE_RESPONSE_MAX_BYTES = 65536;
3020
3405
  var DEVICE_POLL_MIN_MS = 1e3;
@@ -3945,6 +4330,10 @@ async function readDesktopQuota(session, signal, runner = runVela, fetcher = fet
3945
4330
  };
3946
4331
  }
3947
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
+
3948
4337
  // src/remote.ts
3949
4338
  var MAX_REVISION = 256;
3950
4339
  var MAX_JOB_ID = 128;
@@ -4134,7 +4523,9 @@ function parseStatusConfig(value) {
4134
4523
  ...value.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: positiveInteger(value.requestTimeoutMs, "\u8BF7\u6C42\u8D85\u65F6", 36e5, 1e3) },
4135
4524
  ...value.streamIdleTimeoutMs === void 0 ? {} : { streamIdleTimeoutMs: positiveInteger(value.streamIdleTimeoutMs, "\u6D41\u7A7A\u95F2\u8D85\u65F6", 18e5, 1e3) },
4136
4525
  ...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) }
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) }
4138
4529
  };
4139
4530
  }
4140
4531
  function parseStatus(value) {
@@ -4159,12 +4550,25 @@ function parseStatus(value) {
4159
4550
  login: parseLoginState(value.login),
4160
4551
  config: parseStatusConfig(value.config),
4161
4552
  guardedTurns: count(value.guardedTurns, "\u5DF2\u62E6\u622A\u7A7A\u8F6E\u6570"),
4553
+ ...value.turnMonitor === void 0 ? {} : { turnMonitor: parseTurnMonitor(value.turnMonitor) },
4162
4554
  models: parsed,
4163
4555
  ...value.modelsSource === void 0 ? {} : { modelsSource: member(value.modelsSource, ["builtin", "openai"], "\u6A21\u578B\u76EE\u5F55\u6765\u6E90") },
4164
4556
  ...value.modelsUpdatedAt === void 0 ? {} : { modelsUpdatedAt: isoTime(value.modelsUpdatedAt, "\u6A21\u578B\u66F4\u65B0\u65F6\u95F4") },
4165
4557
  ...value.modelsError === void 0 ? {} : { modelsError: text(value.modelsError, "\u6A21\u578B\u66F4\u65B0\u63D0\u793A", MAX_MESSAGE) }
4166
4558
  };
4167
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
+ }
4168
4572
  function parseStartLoginRequest(value) {
4169
4573
  if (!record(value)) throw new Error("\u767B\u5F55\u8BF7\u6C42\u5FC5\u987B\u662F\u5BF9\u8C61");
4170
4574
  return { expectedRevision: text(value.expectedRevision, "\u914D\u7F6E\u7248\u672C", MAX_REVISION) };
@@ -4191,7 +4595,7 @@ var name = "llm-opendesign-corouter";
4191
4595
  var inject = ["llm"];
4192
4596
  var API_KEY = credentialKey2(name, "api-key");
4193
4597
  var SESSION = credentialKey2(name, "console");
4194
- var hash = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4598
+ var hash = (value) => createHash2("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4195
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" });
4196
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" });
4197
4601
  function grantOf(value) {
@@ -4220,6 +4624,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4220
4624
  __publicField(this, "_quotaPending");
4221
4625
  __publicField(this, "_quotaController");
4222
4626
  __publicField(this, "guardedTurns", 0);
4627
+ __publicField(this, "turnMonitorStatus");
4223
4628
  __publicField(this, "_models", MODELS);
4224
4629
  __publicField(this, "_modelsUpdatedAt");
4225
4630
  __publicField(this, "_modelsError");
@@ -4353,6 +4758,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4353
4758
  login: this._login.status(),
4354
4759
  config: state.config,
4355
4760
  guardedTurns: this.guardedTurns,
4761
+ ...this.turnMonitorStatus ? { turnMonitor: this.turnMonitorStatus() } : {},
4356
4762
  models: this._models.map((row) => {
4357
4763
  const { id, name: name2, group: group2, contextWindow, maxOutputTokens, inputModalities } = row;
4358
4764
  const reasoningEfforts = modelReasoningEfforts(row, state.config.apiProtocol ?? "chat-completions");
@@ -4589,11 +4995,13 @@ __decoratorMetadata(_init, OpenDesignCoRouterService);
4589
4995
  function apply(ctx, config) {
4590
4996
  const current = () => readConfig(config);
4591
4997
  current();
4592
- installEotRecovery(ctx, () => current().emptyTurnGuard);
4593
4998
  ctx.inject(["settings"], (scope) => scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)));
4594
4999
  let modelsChanged = () => {
4595
5000
  };
4596
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());
4597
5005
  const replayKeys = new ReplayKeyStore(() => ctx.get("credentials"));
4598
5006
  const adapter = new CoRouterAdapter({
4599
5007
  config: current,
@@ -4620,10 +5028,10 @@ function apply(ctx, config) {
4620
5028
  modelsChanged();
4621
5029
  });
4622
5030
  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");
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");
4624
5032
  const config2 = current();
4625
5033
  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");
5034
+ if (!key) throw new LlmError14("\u8BF7\u5148\u914D\u7F6E CoRouter API Key", "MISSING_CREDENTIAL");
4627
5035
  const models = await fetchModelCatalog(config2.baseURL, key, signal);
4628
5036
  return models.map((row) => {
4629
5037
  const effective = applyModelSettings(row, config2.modelSettings?.[row.id]);