dsh-workplan 2.1.3 → 2.2.6

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +380 -1
  2. package/README.en.md +5 -2
  3. package/README.md +5 -2
  4. package/README.zh.md +5 -2
  5. package/client.js +143 -3
  6. package/docs/dsh-workplan_T4_runtime.patch +508 -0
  7. package/docs/release-records/_release_notes_2.1.2_20261106.md +44 -0
  8. package/docs/release-records/_t2_version_determination_20261106.md +39 -0
  9. package/docs/release-records/_t5_external_reverify_20261106.md +18 -0
  10. package/docs/release-records/release-dryrun-report-20261106.md +74 -0
  11. package/docs/release-records/release-notes-2.2.6-T3.md +128 -0
  12. package/docs/release-records/release-record-2.1.3-20261106.md +82 -0
  13. package/docs/release-records/release-steps-20261106.md +129 -0
  14. package/docs/release-records/version-freeze-20261109-T2.md +37 -0
  15. package/lib/client.js +143 -3
  16. package/lib/comm-format.js +17 -0
  17. package/lib/departments.js +19 -0
  18. package/lib/host.js +95 -17
  19. package/lib/notice-channel.js +290 -0
  20. package/lib/plan.js +541 -32
  21. package/lib/replan.js +4 -0
  22. package/lib/runtime.js +1481 -85
  23. package/lib/supersede.js +2 -2
  24. package/lib/understanding.js +8 -2
  25. package/lib/watchdog.js +52 -1
  26. package/package.json +3 -2
  27. package/scripts/repair-malformed-user-messages.mjs +312 -0
  28. package/src/client.ts +150 -2
  29. package/src/comm-format.ts +17 -0
  30. package/src/departments.ts +22 -0
  31. package/src/host.ts +90 -12
  32. package/src/notice-channel.ts +328 -0
  33. package/src/plan.ts +575 -24
  34. package/src/replan.ts +4 -0
  35. package/src/runtime.ts +1500 -86
  36. package/src/supersede.ts +2 -1
  37. package/src/understanding.ts +10 -2
  38. package/src/watchdog.ts +80 -1
package/lib/runtime.js CHANGED
@@ -14,7 +14,10 @@
14
14
  import { randomUUID } from 'node:crypto';
15
15
  import { existsSync, realpathSync, statSync } from 'node:fs';
16
16
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
17
- import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, blockCancelledDependents, buildChildPrompt, buildCancelMessage, buildClarifyMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS, parseUpdateMessage, buildUpdateMessage, normaliseHandoffs, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, findSubtask, } from './plan.js';
17
+ import { createNoticeChannel, finaliseNoticeChannel, formatNoticeChannelLog, observeRelayedNotice, readLeadAgentId, resolveLeadAgentId, validateNoticeChannel, } from './notice-channel.js';
18
+ import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, appendUserMessage, applyStatus, attachPlanMeta, blockCancelledDependents, buildChildPrompt, buildCancelMessage, buildClarifyMessage, createPlannerProgressReporter, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, DEFAULT_REASONING_EFFORT, deliveryReadiness, derivePlanSnapshot,
19
+ // [2.2.0][T4/O-3b] O-3b 消费接线:缺省协商上限由预估派生(plan.ts 纯函数,T3 已定稿)。
20
+ deriveSubtaskTimeoutMs, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, REASONING_EFFORTS, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS, parseUpdateMessage, buildUpdateMessage, normaliseHandoffs, needEntryText, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, findSubtask, } from './plan.js';
18
21
  import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js';
19
22
  import { phaseGateFromErrors, phaseSummaryLine, validatePhaseEvidence } from './three-phase.js';
20
23
  import { lessonStats, rankLessons, readLessons, recordLesson, renderLessonsBrief, resolveLessonsFile, } from './lessons.js';
@@ -96,14 +99,42 @@ function readinessOf(record, snapshot) {
96
99
  }
97
100
  export const PLANNER_TIMEOUT_MS = 300000;
98
101
  /**
99
- * Wall-clock ceiling for ONE planner attempt (a single LLM stream).
102
+ * 无进展窗口(默认 300s,DSH_WORKPLAN_PLANNER_TIMEOUT_MS,毫秒 >0)。
100
103
  *
101
- * 2.1.1 把固定 120s 提到 300s,只是推迟了超时,没解决「单次调用被固定超时
102
- * 卡死」的结构性问题。2.1.3 起改为可配置:DSH_WORKPLAN_PLANNER_TIMEOUT_MS
103
- * (毫秒,>0),未配置时回落到这里的默认值。这样复杂任务可以按需放宽,
104
- * 而不必改代码重新发布。
104
+ * 2.1.6 起它的含义从「固定墙钟」改成「**没有新内容**的时长」:从上一个
105
+ * chunk 起算,首个 chunk 之前也按它计时。模型一直在正常输出时窗口不断
106
+ * 重置,慢而稳定的长任务不再被误杀。
107
+ *
108
+ * 历史:2.1.1 把 120s 提到 300s 只是推迟超时;2.1.3 把常量改成可配置,
109
+ * 默认值仍是 300s 的固定墙钟。于是 2026-11-07 10:05:19 → 10:10:19(实测
110
+ * 300.06s)规划器仍在工作却被 abort,自动分解直接降级——提高默认值或开放
111
+ * 配置都没有解决「按墙钟掐断一个正在产出的调用」这个结构问题。
105
112
  */
106
113
  export const PLANNER_IDLE_TIMEOUT_MS = 90000;
114
+ /**
115
+ * 首个 chunk 之后的「完全静默」窗口(默认 90s,DSH_WORKPLAN_PLANNER_IDLE_
116
+ * TIMEOUT_MS,毫秒 >0):文本、推理、usage 一个 chunk 都没有这么久,判定为
117
+ * 连接卡死而不是模型还在思考。这个常量在 2.1.6 之前只声明、从未接线(死
118
+ * 代码),现在真正参与计时;设为不小于无进展窗口即等价于关闭。
119
+ */
120
+ export const PLANNER_HARD_MULTIPLIER = 3;
121
+ /**
122
+ * 绝对上限 = 无进展窗口 × 该倍数(默认 900s)。慢可以,慢到没边不行:它给
123
+ * 单次规划器尝试一个终点,保证规划失败永远是「有限时间后给出可执行建议」,
124
+ * 而不是无限占用本轮预算。
125
+ */
126
+ /**
127
+ * [2.2.0][T13b/推理等级] 规划器默认推理档 = max(用户 2026-11-08 决策 5)。
128
+ *
129
+ * 用户规则(AGENTS.md 第 12 条)只说过「子 Agent 不得继承主 Agent 的等级」,
130
+ * 规划器同样是主 Agent 派出的子调用:任务里明确授权「规划器停止继承」。规划
131
+ * 本身属于「跨多个系统梳理根因并给出方案」——按同一条三档规则属非常复杂 →
132
+ * max。`DSH_WORKPLAN_PLANNER_REASONING_EFFORT` 仍可显式覆盖(用户为降本/提速
133
+ * 主动选择低档时有效),未设或非法时才用本默认值;**绝不读取
134
+ * modelSelection.reasoningEffort**。旧行为(plannerEffort || 主 Agent 档位)会
135
+ * 让主 Agent 的 low/high 直接决定拆解质量,与「子 Agent 自决档位」同源、同错。
136
+ */
137
+ export const DEFAULT_PLANNER_REASONING_EFFORT = 'max';
107
138
  /**
108
139
  * Absolute ceiling for one child execution.
109
140
  *
@@ -113,6 +144,13 @@ export const PLANNER_IDLE_TIMEOUT_MS = 90000;
113
144
  * plan became terminal at the first slow subtask. The ceiling is now a
114
145
  * settlement guarantee, while the no-progress window below is what normally
115
146
  * ends an attempt.
147
+ *
148
+ * [2.2.0][T4/O-3b] 语义更新(柔性时长协商,方案 §1③/§2.2):这不是固定交付
149
+ * 期限,而是「协商上限+L4 安全兜底」——单次执行时限协商而来(subtask.timeoutMs
150
+ * 显式值优先,缺省 deriveSubtaskTimeoutMs(estimateMinutes)=clamp(预估分钟×
151
+ * 2.0×60000, MIN, MAX)),本常量只在无预估、无显式值时兜底(③C2 零回归)。
152
+ * 时间是协商出来的安全兜底,不是固定交付期限:到点走 L4 安全兜底结算+
153
+ * 「待裁决」标记(延期 / 重试 / 接受),不表述为「强制结束」式固定期限误杀。
116
154
  */
117
155
  export const CHILD_TIMEOUT_MS = 900000;
118
156
  /** No-progress window: the child's own session log stopped growing. */
@@ -124,7 +162,14 @@ export const CHILD_IDLE_TIMEOUT_MS = 300000;
124
162
  * minutes.
125
163
  */
126
164
  export const MIN_CHILD_TIMEOUT_MS = 1000;
127
- export const MAX_CHILD_TIMEOUT_MS = 1800000;
165
+ /*
166
+ * [2.2.0][T4/O-3b] 单次绝对上限 1800000 → 7200000(120 分钟):用户 2026-11-07
167
+ * 决断(方案 §6 未知第 4 条)。协商上限 = clamp(预估分钟 × 2.0, 全局下限,
168
+ * 单次绝对上限)(方案 §1③),2h 让「预告 60 分钟的子任务,其单次执行上限
169
+ * ≥ 60 分钟」(方案 C1)成立;tests/time-estimate-negotiation.test.ts 的
170
+ * expected 公式直接引用本常量,数值不同步会红灯。
171
+ */
172
+ export const MAX_CHILD_TIMEOUT_MS = 7200000;
128
173
  export const MIN_CHILD_IDLE_MS = 1000;
129
174
  export const MAX_CHILD_IDLE_MS = 900000;
130
175
  export const CHILD_POLL_MS = 2000;
@@ -152,7 +197,26 @@ export const INSTRUCTION_ACK_DEADLINE_MS = 180000;
152
197
  * 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
153
198
  */
154
199
  export const INSTRUCTION_POLL_MS = 5000;
155
- export const TOTAL_TIMEOUT_MS = 1200000;
200
+ // [2.2.5][RoundBudget] 轮次总预算默认关闭。
201
+ //
202
+ // 用户要求:对子任务的执行时间不做强制限制,只通过开工预告/预估/协商/延期
203
+ // 与到点预警来治理;旧版默认 20 分钟会在子任务自己的 30 分钟协商截止前
204
+ // 先切断整轮,界面上出现“本轮预算用尽”,与上述目标矛盾。
205
+ //
206
+ // 现在:
207
+ // - TOTAL_TIMEOUT_MS = 0 表示默认不设整轮硬预算;
208
+ // - 显式传正数(配置/DSH_WORKPLAN_TOTAL_TIMEOUT_MS)仍可启用安全兜底;
209
+ // - 子任务自己的 timeoutMs/deadlineAt/extendMs 不受影响。
210
+ // dispatchPlan 用 20 天哨兵值避免 Infinity 参与计时器/差值计算。
211
+ //
212
+ // [2.2.5][热修] 哨兵值不能超过 Node setTimeout 的上限:延时 > 2^31-1 毫秒
213
+ // (约 24.8 天)会被 Node 强制改成 1 毫秒并告警(TimeoutOverflowWarning)。
214
+ // 最初版本用 10 年,结果整轮定时器派发后 1ms 就触发,所有子任务瞬间被
215
+ // 「总执行超时」杀死(2026-11-08 17:36 / 18:01 两次现场实锤,38ms 与 8ms)。
216
+ // 20 天 = 1,728,000,000ms < 2^31-1,安全;且对单轮执行而言等价于“无预算”。
217
+ export const TOTAL_TIMEOUT_MS = 0;
218
+ export const NO_ROUND_BUDGET_MS = 20 * 24 * 60 * 60 * 1000;
219
+ export const ROUND_TIMER_MAX_MS = 2_000_000_000;
156
220
  export const DISPOSE_TIMEOUT_MS = 5000;
157
221
  export const STALE_PENDING_MS = 10 * 60 * 1000;
158
222
  export const MAX_HISTORY_EVENTS = 2000;
@@ -329,7 +393,7 @@ function pushRecordError(record, error) {
329
393
  const text = truncate(describeError(error), 1000);
330
394
  record.errors = [...(record.errors ?? []), text].slice(-20);
331
395
  }
332
- async function collectStream(stream) {
396
+ async function collectStream(stream, onChunk, sink) {
333
397
  let text = '';
334
398
  let textDeltaSeen = false;
335
399
  let finished = false;
@@ -337,19 +401,42 @@ async function collectStream(stream) {
337
401
  for await (const chunk of stream) {
338
402
  if (!chunk || typeof chunk !== 'object')
339
403
  continue;
404
+ /*
405
+ * [2.1.6] 任何 chunk 都是「连接还活着」的证据——包括 reasoning-delta、
406
+ * block-start、usage 这些不进正文的类型。计时器只认这里,才不会把正在
407
+ * 推理的模型当成卡死。
408
+ */
409
+ onChunk?.();
340
410
  if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
341
411
  text += chunk.text;
412
+ /*
413
+ * [2.1.7] 正文必须边流边落进 sink:定时器中止时 for-await 会直接抛错,
414
+ * 局部变量 text 连同 900 秒的产出一起蒸发,旧实现正是这样把「差一个
415
+ * 收尾 } 的完整计划」整体扔掉的。
416
+ */
417
+ if (sink)
418
+ sink.text = text;
342
419
  textDeltaSeen = true;
343
420
  }
344
421
  else if (chunk.type === 'block-end' && chunk.block?.type === 'text' && !textDeltaSeen) {
345
422
  text += chunk.block.text ?? '';
423
+ if (sink)
424
+ sink.text = text;
346
425
  }
347
426
  else if (chunk.type === 'finish') {
348
427
  finished = true;
349
428
  finishKind = chunk.reason?.kind ?? 'unknown';
350
429
  if (finishKind === 'error' || finishKind === 'aborted') {
351
430
  const failure = chunk.reason?.failure;
352
- throw new PlanError(`模型调用结束:${finishKind}${failure?.code ? ` ${failure.code}` : ''}${failure?.message ? `:${failure.message}` : ''}`, finishKind === 'aborted' ? 'ABORTED' : 'PLANNER_LLM_ERROR');
431
+ /*
432
+ * [2.2.5][T4] 底层原因透传(T3 根因 P2):failure.message 只是包装文案
433
+ * (如 "Connection error."),真因可能挂在 failure.cause 上(宿主透传后
434
+ * 自动生效,未透传时保持原文、行为不变)。failure.code 记入 details,
435
+ * 供重试分级(P1)判定,不再从文案反解。
436
+ */
437
+ const causeText = failure?.cause ? errorCauseChain(failure.cause) : '';
438
+ const failureCode = failure?.code != null ? String(failure.code) : '';
439
+ throw new PlanError(`模型调用结束:${finishKind}${failureCode ? ` ${failureCode}` : ''}${failure?.message ? `:${failure.message}` : ''}${causeText ? `(底层原因:${causeText})` : ''}`, finishKind === 'aborted' ? 'ABORTED' : 'PLANNER_LLM_ERROR', failureCode);
353
440
  }
354
441
  if (finishKind !== 'stop') {
355
442
  throw new PlanError(`规划器输出未正常结束:${finishKind}`, 'PLANNER_INCOMPLETE');
@@ -374,21 +461,239 @@ function contextGuardStrict() {
374
461
  const flag = String(process.env.DSH_WORKPLAN_CONTEXT_GUARD ?? '').trim().toLowerCase();
375
462
  return flag !== 'off' && flag !== '0' && flag !== 'false';
376
463
  }
377
- async function runPlanner(ctx, options) {
378
- const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {}, sourceMessageIds = [] } = options;
379
- const plannerTimeoutMs = Number(options.plannerTimeoutMs ?? PLANNER_TIMEOUT_MS);
464
+ /** 规划器窗口取值:只接受有限正数,否则回落默认值(0/负数/NaN 都不许把计时器打成 1ms)。 */
465
+ export function normalisePlannerWindow(value, fallback) {
466
+ const numeric = Number(value);
467
+ return Number.isFinite(numeric) && numeric > 0 ? numeric : fallback;
468
+ }
469
+ function plannerDebugEnabled() {
470
+ const flag = String(process.env.DSH_WORKPLAN_DEBUG ?? '').trim().toLowerCase();
471
+ return flag !== '' && flag !== '0' && flag !== 'false' && flag !== 'off';
472
+ }
473
+ /**
474
+ * 把规划器遥测压成一行能直接给用户看的现场说明(降级消息的 detail)。
475
+ * 没有遥测时返回空串,调用方据此跳过,不制造「0 次尝试」之类的假事实。
476
+ */
477
+ export function plannerTelemetryLine(telemetry) {
478
+ if (!telemetry || typeof telemetry !== 'object' || !telemetry.attempt)
479
+ return '';
480
+ const parts = [
481
+ telemetry.model ? `模型 ${telemetry.model}` : '',
482
+ Number(telemetry.elapsedMs) > 0 ? `耗时 ${(Number(telemetry.elapsedMs) / 1000).toFixed(1)}s` : '',
483
+ Number(telemetry.chunks) > 0 ? `收到 ${Number(telemetry.chunks)} 个输出块` : '未收到任何输出块',
484
+ Number(telemetry.promptChars) > 0 ? `提示词 ${Number(telemetry.promptChars)} 字` : '',
485
+ Number(telemetry.textChars) > 0 ? `输出 ${Number(telemetry.textChars)} 字` : '',
486
+ telemetry.outcome && telemetry.outcome !== 'ok' ? `判定 ${telemetry.outcome}` : '',
487
+ ].filter(Boolean);
488
+ return `现场:${parts.join('|')}`;
489
+ }
490
+ const PLANNER_ABORT_CODES = ['PLANNER_TIMEOUT', 'PLANNER_IDLE', 'PLANNER_TIMEOUT_HARD'];
491
+ /*
492
+ * [2.2.5][T4] 规划器重试分级与退避(T3 根因 P1:规划器链路全层零重试零退避,
493
+ * 一次 ~1s 网络连接尖峰 × 0ms 间隔 = 1.2 秒内两连败直接降级)。
494
+ * - PLANNER_RETRYABLE_LLM_CODES:宿主 classifyPiAiError 的可自愈失败类
495
+ * (偶发传输错误 / 超时 / 服务端 5xx / 限流 429),重试前做指数退避;
496
+ * - 其余失败类(AUTH / INVALID_REQUEST / 配额 / 上下文溢出 / PI_AI_ERROR /
497
+ * ABORTED)重试不会自愈,立即终止,不再烧下一次调用;
498
+ * - 退避 500ms → 1s(±20% 抖动),期间 signal 一旦取消立即让路,绝不悬挂。
499
+ */
500
+ const PLANNER_RETRYABLE_LLM_CODES = ['TRANSPORT', 'TIMEOUT', 'SERVER', 'RATE_LIMIT'];
501
+ const PLANNER_MAX_ATTEMPTS = 3;
502
+ const PLANNER_RETRY_BACKOFF_BASE_MS = 500;
503
+ /**
504
+ * [2.2.5][T4] 把 Error 的 cause 链展开成一行可读文本(T3 根因 P2 的插件侧落点)。
505
+ *
506
+ * 真实失败原因(ENOTFOUND / ECONNREFUSED / TLS alert 等)挂在 Error.cause 链上,
507
+ * 外层 message 往往只有包装文案("fetch failed"、"Connection error.")。
508
+ * 展开规则与宿主 dsh-llm 的 errorChain 一致:外层在前,每层 cause 以 ": " 追加,
509
+ * 重复文案只记一次;深度封顶 5 层防环。无 cause 时返回与 error.message 相同的
510
+ * 文本,不改变既有行为。
511
+ */
512
+ function errorCauseChain(value) {
513
+ const parts = [];
514
+ let current = value;
515
+ for (let depth = 0; depth < 5 && current != null; depth += 1) {
516
+ const text = typeof current.message === 'string' && current.message !== ''
517
+ ? current.message
518
+ : (typeof current.name === 'string' && current.name !== '' ? current.name : String(current));
519
+ if (!parts.includes(text))
520
+ parts.push(text);
521
+ current = current.cause;
522
+ }
523
+ return parts.join(': ');
524
+ }
525
+ /**
526
+ * [2.2.5][T4] 可被 signal 打断的退避等待:取消一到,Promise 立即 resolve,
527
+ * 调用方随后检查 signal.aborted 抛 ABORTED——真取消路径不吃退避延迟。
528
+ */
529
+ function sleepAbortable(signal, ms) {
530
+ return new Promise((resolve) => {
531
+ let timer = null;
532
+ const finish = () => {
533
+ if (timer !== null)
534
+ clearTimeout(timer);
535
+ timer = null;
536
+ signal?.removeEventListener?.('abort', onAbort);
537
+ resolve();
538
+ };
539
+ const onAbort = () => finish();
540
+ if (signal?.aborted) {
541
+ resolve();
542
+ return;
543
+ }
544
+ timer = setTimeout(finish, ms);
545
+ signal?.addEventListener?.('abort', onAbort, { once: true });
546
+ });
547
+ }
548
+ /**
549
+ * [2.1.7] 定时器中止后的正文抢救。
550
+ *
551
+ * 事故里模型流式输出了 900 秒、11694 个块,却因为没等到 finish 信号被整体
552
+ * 丢弃——局部变量 text 连同它一起消失。只要正文末尾已闭合(`}`),就按与正常
553
+ * 路径完全一致的三道闸(extractJson → validatePlan → validatePlanContext)
554
+ * 重新验收;任何一道不过返回 null,照旧报超时。
555
+ *
556
+ * 只认「末尾已闭合」:被拦腰截断的 JSON 即使补上括号也可能丢掉尾部阶段,
557
+ * 静默交出残缺计划比降级更危险。
558
+ */
559
+ function salvagePartialPlan(text, guardOptions) {
560
+ if (typeof text !== 'string')
561
+ return null;
562
+ const trimmed = text.trimEnd();
563
+ if (!trimmed.endsWith('}'))
564
+ return null;
565
+ try {
566
+ const raw = extractJson(trimmed);
567
+ const validated = validatePlan(raw);
568
+ if (!validated.ok)
569
+ return null;
570
+ const guard = validatePlanContext(validated.plan, guardOptions);
571
+ if (!guard.ok)
572
+ return null;
573
+ const plan = validated.plan;
574
+ plan.taskAnchor = guard.audit.anchor;
575
+ plan.understandingAudit = compactUnderstandingAudit(guard.audit);
576
+ return plan;
577
+ }
578
+ catch {
579
+ return null;
580
+ }
581
+ }
582
+ /**
583
+ * [2.1.6] 单次规划器尝试的计时策略——判据是「有没有在产出」,不是「过了多久」。
584
+ *
585
+ * 三扇窗:
586
+ * 1. 无进展窗口(plannerTimeoutMs,默认 300s):自上一个 chunk 起算,首个
587
+ * chunk 之前同样适用。模型持续产出 ⇒ 窗口不断后移,慢而稳定的长任务不再
588
+ * 被固定墙钟掐断;
589
+ * 2. 静默窗口(plannerIdleTimeoutMs,默认 90s):首个 chunk 之后完全静默,
590
+ * 判定为卡死而非还在思考;不小于无进展窗口时等于关闭;
591
+ * 3. 绝对上限(无进展窗口 × PLANNER_HARD_MULTIPLIER,默认 900s):有无产出
592
+ * 都到此为止,规划失败因此永远是「有限时间 + 可执行建议」。
593
+ *
594
+ * 每次中止都携带真实旋钮(DSH_WORKPLAN_PLANNER_TIMEOUT_MS /
595
+ * DSH_WORKPLAN_PLANNER_IDLE_TIMEOUT_MS),而不是让用户去改源码常量。
596
+ */
597
+ export async function runPlanner(ctx, options) {
598
+ const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {}, sourceMessageIds = [], telemetry, onProgress, } = options;
599
+ const timeoutMs = normalisePlannerWindow(options.plannerTimeoutMs, PLANNER_TIMEOUT_MS);
600
+ const idleMs = normalisePlannerWindow(options.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS);
601
+ const hardMs = timeoutMs * PLANNER_HARD_MULTIPLIER;
602
+ /*
603
+ * [2.1.7] 两个可选旋钮:
604
+ * - DSH_WORKPLAN_PLANNER_MAX_TOKENS:给单次生成封顶。无界生成是「流满 900 秒
605
+ * 撞绝对上限」的放大器——封顶后模型会正常 finish,截断可被抢救/回喂;
606
+ * - DSH_WORKPLAN_PLANNER_REASONING_EFFORT:规划专用推理档,只接受
607
+ * low / high / max 三档。非法值不传给模型,回落默认档(见下)。
608
+ *
609
+ * [2.2.0][T13b] 用户 2026-11-08 决策 5「规划器停止继承」:未设该旋钮时,规划器
610
+ * 不再沿用主 Agent 的推理档,而是取 DEFAULT_PLANNER_REASONING_EFFORT(max)。
611
+ * 校验白名单复用 plan.ts 的 REASONING_EFFORTS:把 "ultra"/"medium" 这类非法值
612
+ * 原样发给模型,真实宿主会以 400 拒绝整次规划——环境变量写错不应该让整个
613
+ * 任务降级,所以非法值按「未设置」处理。
614
+ */
615
+ const plannerMaxTokens = normalisePlannerWindow(process.env.DSH_WORKPLAN_PLANNER_MAX_TOKENS, 0);
616
+ // 大小写归一:"LOW" 这类写法若因大小写被当成非法值回落 max,会静默抬高
617
+ // 用户的成本预期,所以先归一化再进白名单。
618
+ const plannerEffortRaw = String(process.env.DSH_WORKPLAN_PLANNER_REASONING_EFFORT ?? '').trim().toLowerCase();
619
+ const plannerEffort = REASONING_EFFORTS.includes(plannerEffortRaw) ? plannerEffortRaw : '';
620
+ const effectivePlannerEffort = plannerEffort || DEFAULT_PLANNER_REASONING_EFFORT;
621
+ const secs = (ms) => Math.max(1, Math.round(ms / 1000));
380
622
  let lastErrors = [];
381
- for (let attempt = 1; attempt <= 2; attempt += 1) {
623
+ /*
624
+ * [2.1.6.1] 每次尝试的失败原因必须都留档:旧实现每轮 `lastErrors = ...` 整体
625
+ * 覆盖,最终报错里只剩最后一次,第一次为什么失败永远丢失——事后只能靠猜。
626
+ * [2.2.5][T4] 尝试次数由 2 提到 3(PLANNER_MAX_ATTEMPTS),可重试类失败
627
+ * (传输/超时/服务端/限流)在两次尝试之间做指数退避,吸收偶发网络抖动。
628
+ */
629
+ const attemptReports = [];
630
+ let lastText = '';
631
+ for (let attempt = 1; attempt <= PLANNER_MAX_ATTEMPTS; attempt += 1) {
382
632
  if (signal.aborted)
383
633
  throw abortError();
384
634
  const controller = new AbortController();
385
635
  const onAbort = () => controller.abort(signal.reason ?? abortError());
386
636
  signal.addEventListener('abort', onAbort, { once: true });
387
- const timeout = setTimeout(() => {
388
- controller.abort(new PlanError('规划器超时', 'PLANNER_TIMEOUT'));
389
- }, plannerTimeoutMs);
637
+ const startedAt = Date.now();
638
+ let sawChunk = false;
639
+ let lastChunkAt = startedAt;
640
+ let chunks = 0;
641
+ let promptChars = 0;
642
+ let outcome = 'ok';
643
+ /*
644
+ * [2.1.7] 流式正文的落点:collectStream 边流边写,abort/缺 finish 时也
645
+ * 能留下全文,供抢救(salvagePartialPlan)与遥测复盘使用。
646
+ */
647
+ const sink = { text: '' };
648
+ let progressTimer = null;
649
+ const clearProgress = () => {
650
+ if (progressTimer) {
651
+ clearTimeout(progressTimer);
652
+ progressTimer = null;
653
+ }
654
+ };
655
+ const idleActive = () => sawChunk && idleMs < timeoutMs;
656
+ const windowMs = () => (idleActive() ? idleMs : timeoutMs);
657
+ const stallError = () => (idleActive()
658
+ ? new PlanError(`规划器停滞:输出开始后 ${secs(idleMs)} 秒没有任何新内容,判定为卡死(不是还在思考)。可用 DSH_WORKPLAN_PLANNER_IDLE_TIMEOUT_MS 调整,设为不小于 ${secs(timeoutMs)} 秒即关闭`, 'PLANNER_IDLE')
659
+ : new PlanError(`规划器超时:${secs(timeoutMs)} 秒内没有取得任何进展(任务过长或模型过慢)。请设置 DSH_WORKPLAN_PLANNER_TIMEOUT_MS(毫秒)放宽单次调用上限,或缩短任务文本`, 'PLANNER_TIMEOUT'));
660
+ const checkProgress = () => {
661
+ progressTimer = null;
662
+ // 到点时若其实还有进展(窗口刚被收紧或时钟抖动),按剩余时间重新武装。
663
+ if (Date.now() - lastChunkAt < windowMs()) {
664
+ scheduleCheck();
665
+ return;
666
+ }
667
+ controller.abort(stallError());
668
+ };
669
+ const scheduleCheck = () => {
670
+ clearProgress();
671
+ const remaining = Math.max(1, windowMs() - (Date.now() - lastChunkAt));
672
+ progressTimer = setTimeout(checkProgress, remaining);
673
+ };
674
+ const hardTimer = setTimeout(() => {
675
+ controller.abort(new PlanError(`规划器超出绝对上限:${secs(hardMs)} 秒(= DSH_WORKPLAN_PLANNER_TIMEOUT_MS 的 ${PLANNER_HARD_MULTIPLIER} 倍)。请缩短任务文本,或提高 DSH_WORKPLAN_PLANNER_TIMEOUT_MS`, 'PLANNER_TIMEOUT_HARD'));
676
+ }, hardMs);
677
+ const onChunk = () => {
678
+ chunks += 1;
679
+ lastChunkAt = Date.now();
680
+ // 首个 chunk 到达时窗口可能由 300s 收紧为 90s,必须立刻按新窗口重排。
681
+ if (!sawChunk) {
682
+ sawChunk = true;
683
+ scheduleCheck();
684
+ }
685
+ };
686
+ scheduleCheck();
687
+ /*
688
+ * [2.2.5][T4] 本轮重试判定(catch 内赋值,finally 遥测之后执行):
689
+ * - terminalFailure:不可自愈的 LLM 失败类,本轮结束后立即跳出循环;
690
+ * - retryBackoffMs:可重试类失败的重试前退避毫秒数(0 = 不退避)。
691
+ */
692
+ let terminalFailure = false;
693
+ let retryBackoffMs = 0;
390
694
  try {
391
695
  let prompt = buildPlannerPrompt(taskText, cwd, conversationContext, budget);
696
+ promptChars = prompt.length;
392
697
  if (lastErrors.length > 0) {
393
698
  prompt += [
394
699
  '',
@@ -396,15 +701,26 @@ async function runPlanner(ctx, options) {
396
701
  ...lastErrors.slice(0, 12).map((error) => `- ${error}`),
397
702
  ].join('\n');
398
703
  }
704
+ /*
705
+ * [2.2.0][T13b/推理等级] 规划器停止继承主 Agent 的档位(用户 2026-11-08
706
+ * 决策 5,选项 A):显式传 effectivePlannerEffort(旋钮合法值,否则 max)。
707
+ *
708
+ * 旧代码 `plannerEffort || modelSelection.reasoningEffort` 的第二个操作数是
709
+ * 主 Agent 的档位,等于让主 Agent 决定规划器:主 Agent 用 low 省成本时,
710
+ * 拆解也降档,复杂任务被拆得更浅,后续部门再努力也补不回来。现在没有任何
711
+ * 路径读 modelSelection.reasoningEffort 作为规划档位。
712
+ */
399
713
  const stream = ctx.llm.stream({
400
714
  provider: modelSelection.provider,
401
715
  model: modelSelection.model,
402
- reasoningEffort: modelSelection.reasoningEffort,
716
+ reasoningEffort: effectivePlannerEffort,
717
+ ...(plannerMaxTokens > 0 ? { maxTokens: plannerMaxTokens } : {}),
403
718
  messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
404
719
  signal: controller.signal,
405
720
  sessionId,
406
721
  });
407
- const text = await collectStream(stream);
722
+ const text = await collectStream(stream, onChunk, sink);
723
+ lastText = text;
408
724
  const raw = extractJson(text);
409
725
  const validated = validatePlan(raw);
410
726
  if (validated.ok) {
@@ -426,32 +742,180 @@ async function runPlanner(ctx, options) {
426
742
  plan.understandingAudit = compactUnderstandingAudit(guard.audit);
427
743
  return plan;
428
744
  }
745
+ outcome = 'CONTEXT_GUARD';
429
746
  lastErrors = guard.errors.length > 0 ? guard.errors : guard.warnings;
430
747
  continue;
431
748
  }
749
+ outcome = 'INVALID_PLAN';
432
750
  lastErrors = validated.errors ?? [];
433
751
  }
434
752
  catch (error) {
435
- // 规划器自身的墙钟超时:LLM 层会把 abort 掩码成泛化的
436
- // "DeepSeek Messages request aborted",丢失真实原因。这里优先识别
437
- // PLANNER_TIMEOUT,抛出明确错误,避免误报成“偶发中断”。
438
- if (controller.signal.aborted && controller.signal.reason?.code === 'PLANNER_TIMEOUT') {
439
- throw new PlanError('规划器超时:任务分解未在时限内完成,请缩短任务文本或提高 PLANNER_TIMEOUT_MS', 'PLANNER_TIMEOUT');
753
+ /*
754
+ * LLM 层会把 abort 掩码成泛化的 "DeepSeek Messages request aborted",丢失
755
+ * 真实原因。这里优先读我们自己写进 controller.signal.reason 的判定码,
756
+ * 再区分「用户/宿主主动取消」,最后才当作可重试的偶发错误。
757
+ */
758
+ const reason = controller.signal.aborted ? controller.signal.reason : undefined;
759
+ if (reason && PLANNER_ABORT_CODES.includes(String(reason.code))) {
760
+ /*
761
+ * [2.1.7] 定时器中止 ≠ 产出作废。旧实现在此直接 throw,900 秒里流出来的
762
+ * 正文随局部变量一起蒸发(遥测 textChars=0 就是这么来的)。先尝试用
763
+ * 与正常路径一致的三道闸验收已产出的正文:能通过就照常返回计划;
764
+ * 通不过才按原判定中止,失败现场由 finally 的遥测留档。
765
+ */
766
+ const salvaged = salvagePartialPlan(sink.text, {
767
+ taskText,
768
+ conversationContext,
769
+ sourceMessageIds,
770
+ strict: contextGuardStrict(),
771
+ });
772
+ if (salvaged && !signal.aborted) {
773
+ outcome = 'SALVAGED';
774
+ lastText = sink.text;
775
+ return salvaged;
776
+ }
777
+ outcome = String(reason.code);
778
+ throw reason;
779
+ }
780
+ /*
781
+ * [2.1.7] 同样地:模型写完了 JSON 却没送来 finish 信号(连接抖动、
782
+ * 层序错乱)时,正文若已完整可用就不要整轮作废。
783
+ */
784
+ if (error instanceof PlanError && error.code === 'PLANNER_INCOMPLETE' && !signal.aborted) {
785
+ const salvaged = salvagePartialPlan(sink.text, {
786
+ taskText,
787
+ conversationContext,
788
+ sourceMessageIds,
789
+ strict: contextGuardStrict(),
790
+ });
791
+ if (salvaged) {
792
+ outcome = 'SALVAGED';
793
+ lastText = sink.text;
794
+ return salvaged;
795
+ }
440
796
  }
441
- if (signal.aborted || (controller.signal.aborted && controller.signal.reason?.code === 'ABORTED')) {
797
+ if (signal.aborted || (controller.signal.aborted && reason?.code === 'ABORTED')) {
798
+ outcome = 'ABORTED';
442
799
  throw abortError();
443
800
  }
444
- if (error instanceof PlanError && error.code === 'ABORTED')
801
+ if (error instanceof PlanError && error.code === 'ABORTED') {
802
+ outcome = 'ABORTED';
445
803
  throw error;
446
- lastErrors = [error instanceof Error ? error.message : String(error)];
804
+ }
805
+ outcome = (error instanceof PlanError && error.code) || 'PLANNER_ERROR';
806
+ /*
807
+ * [2.2.5][T4] 失败原因整链透传(T3 根因 P2):error.message 只是外层包装
808
+ * (如 "fetch failed"),真因(ENOTFOUND / ECONNREFUSED / TLS alert)挂在
809
+ * cause 链上。展开后写入 lastErrors → attemptReports → 最终降级文案,
810
+ * 下次失败不再只看到一句 "TRANSPORT:Connection error"。
811
+ */
812
+ const message = error instanceof Error ? errorCauseChain(error) : String(error);
813
+ lastErrors = [message];
814
+ /*
815
+ * [2.1.6.1] 只回一句「位置 6041」给模型毫无用处:它看不到自己断在哪。
816
+ * 把断点附近的原文与「截断 / 写错」的判据一并回喂,第二次尝试才有靶子;
817
+ * 同时把长度与尾部落进遥测,失败现场从此可复盘。
818
+ */
819
+ if (error instanceof PlanError && error.code === 'INVALID_JSON' && lastText) {
820
+ const trimmed = lastText.trimEnd();
821
+ const tail = trimmed.slice(-120);
822
+ const closed = trimmed.endsWith('}');
823
+ lastErrors = [
824
+ message,
825
+ `输出共 ${lastText.length} 字符,末尾原文:${JSON.stringify(tail)}`,
826
+ closed
827
+ ? '末尾已闭合 → 断点在正文中间,属语法写错(漏逗号/括号不匹配)'
828
+ : '末尾未闭合(没有结尾 })→ 疑似输出被截断,请给出更紧凑的完整 JSON',
829
+ ];
830
+ }
831
+ /*
832
+ * [2.2.5][T4] 重试分级 + 退避(T3 根因 P1):旧实现 catch 后零退避立即
833
+ * 重试——一次 ~1s 网络连接尖峰 × 0ms 间隔 = 1.2 秒内两连败直接降级。
834
+ * 现在:可重试类(TRANSPORT/TIMEOUT/SERVER/RATE_LIMIT)按 500ms→1s
835
+ * 指数退避(±20% 抖动,可被 signal 打断)给抖动尾巴留出恢复窗口;
836
+ * 其余 LLM 失败类(AUTH/INVALID_REQUEST/配额/上下文溢出等)重试不会
837
+ * 自愈,置 terminal 标志本轮结束后立即跳出,不烧下一次调用。
838
+ */
839
+ const llmCode = error instanceof PlanError && error.code === 'PLANNER_LLM_ERROR'
840
+ && typeof error.details === 'string'
841
+ ? error.details
842
+ : '';
843
+ if (llmCode !== '' && !PLANNER_RETRYABLE_LLM_CODES.includes(llmCode)) {
844
+ terminalFailure = true;
845
+ }
846
+ else if (attempt < PLANNER_MAX_ATTEMPTS && !signal.aborted) {
847
+ retryBackoffMs = Math.round(PLANNER_RETRY_BACKOFF_BASE_MS * 2 ** (attempt - 1) * (0.8 + Math.random() * 0.4));
848
+ }
447
849
  }
448
850
  finally {
449
- clearTimeout(timeout);
851
+ clearProgress();
852
+ clearTimeout(hardTimer);
450
853
  signal.removeEventListener('abort', onAbort);
854
+ /*
855
+ * [2.1.6] 规划器遥测:此前失败现场什么都不留,事后只能从会话 JSONL 反推
856
+ * 「恰好 300.06 秒」。现在每次尝试都留下模型、提示词规模、产出块数、耗时
857
+ * 与判定码,失败时随降级消息一起给到用户。
858
+ */
859
+ if (outcome !== 'ok' && lastErrors.length > 0) {
860
+ attemptReports.push(`第 ${attempt} 次[${outcome}]:${lastErrors.join(';')}`);
861
+ /*
862
+ * [2.2.5][T5] 分解期间进度透出(T1 P-6 / T3 §5):每次失败尝试在遥测
863
+ * 留档之后向调用方回调一次(attempt / outcome / 真因链 / 退避毫秒 /
864
+ * 终态)。这里只是追加观察点——terminalFailure 与 retryBackoffMs 在
865
+ * catch 里已定值,本回调不读写循环控制变量,重试判定、退避与跳出
866
+ * 语义与旧实现逐字节一致。
867
+ */
868
+ if (typeof onProgress === 'function') {
869
+ onProgress({
870
+ attempt,
871
+ outcome,
872
+ lastErrors: [...lastErrors],
873
+ retryBackoffMs,
874
+ terminal: terminalFailure,
875
+ aborted: signal.aborted,
876
+ });
877
+ }
878
+ }
879
+ if (telemetry && typeof telemetry === 'object') {
880
+ Object.assign(telemetry, {
881
+ // [2.1.7] 以 sink 为准:abort 时 lastText 恒为空,旧值让现场永远缺「输出 N 字」。
882
+ textChars: Math.max(lastText.length, sink.text.length),
883
+ provider: modelSelection.provider,
884
+ model: modelSelection.model,
885
+ // [2.2.0][T13b] 记录**实际发给模型**的档位:旧值记的是 modelSelection
886
+ // (主 Agent 档位),规划器停止继承后它不再等于生效值,照抄会让事后
887
+ // 复盘把「主 Agent=high」误读成「规划器=high」。
888
+ reasoningEffort: effectivePlannerEffort,
889
+ reasoningEffortSource: plannerEffort ? 'env' : 'default-max',
890
+ attempt,
891
+ taskChars: typeof taskText === 'string' ? taskText.length : 0,
892
+ promptChars,
893
+ chunks,
894
+ elapsedMs: Date.now() - startedAt,
895
+ outcome,
896
+ at: Date.now(),
897
+ });
898
+ if (plannerDebugEnabled()) {
899
+ console.warn('[dsh-workplan] planner attempt', JSON.stringify({ ...telemetry }));
900
+ }
901
+ }
902
+ }
903
+ /*
904
+ * [2.2.5][T4] 退避在 finally(遥测计时)之后执行,不污染单次尝试的
905
+ * elapsedMs;不可自愈失败在此直接跳出,最终报错仍走统一的聚合文案。
906
+ * 校验类重试(CONTEXT_GUARD/INVALID_PLAN 的 continue)不经过这里,
907
+ * 保持原有的零退避快重试。
908
+ */
909
+ if (terminalFailure)
910
+ break;
911
+ if (retryBackoffMs > 0) {
912
+ await sleepAbortable(signal, retryBackoffMs);
913
+ if (signal.aborted)
914
+ throw abortError();
451
915
  }
452
916
  }
453
917
  const deviation = lastErrors.some((error) => /^(?:DEVIATION|CLARIFY|CONTEXT):/.test(String(error)));
454
- throw new PlanError(`规划器两次输出均未通过校验:${lastErrors.slice(0, 5).join(';')}`, deviation ? 'DEVIATION' : 'PLANNER_FAILED', lastErrors);
918
+ throw new PlanError(`规划器 ${attemptReports.length > 0 ? `全部 ${attemptReports.length} 次尝试` : '输出'}均未通过校验:${(attemptReports.length > 0 ? attemptReports : lastErrors).slice(0, 6).join(' | ')}`, deviation ? 'DEVIATION' : 'PLANNER_FAILED', lastErrors);
455
919
  }
456
920
  function createChildController(parentSignal) {
457
921
  const controller = new AbortController();
@@ -947,6 +1411,26 @@ function settleFromOutput(record, subtask, output, guard, options) {
947
1411
  else if (checked.missingArtifacts.length > 0) {
948
1412
  recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard);
949
1413
  }
1414
+ /*
1415
+ * [2.2.0][T6/O-1a] 完成即时通知(插件兜底通道,方案 §2.3)。
1416
+ *
1417
+ * 结算成功后立刻把「子任务 ID+摘要+验收计数+用时」交给主会话,不等待
1418
+ * 整轮结束;只有真正的 done 才通知(blocked/escalated 不产生「已完成」
1419
+ * 措辞,A4)。投递与幂等标记由 `onSubtaskDone` 处理器负责:先写通知、
1420
+ * 写成功才记 report.state='sent',绝不留无证据的已回报。
1421
+ */
1422
+ if (verdict.status === 'done' && options.notifyCompletion === true
1423
+ && typeof options.onSubtaskDone === 'function') {
1424
+ try {
1425
+ options.onSubtaskDone(record, subtask, verdict);
1426
+ }
1427
+ catch {
1428
+ /*
1429
+ * 通知是辅助通道:写失败不得回滚已经成立的完成判定,也不得让执行
1430
+ * 路径报错。失败由处理器记 reportPending,交 finishRound 批量补齐。
1431
+ */
1432
+ }
1433
+ }
950
1434
  return { ...verdict, escalated };
951
1435
  }
952
1436
  /**
@@ -1009,6 +1493,97 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1009
1493
  ? options.attemptOffset
1010
1494
  : 1;
1011
1495
  let lastFailure = options.priorFailure ?? null;
1496
+ /*
1497
+ * [2.2.0][T3/O-2a] 子→主预告通道的两个动作,都在本函数内闭环:
1498
+ * recordNoticeChannel —— 派发瞬间写下「目标 / 调用方 / 时间戳」;
1499
+ * finaliseNotice —— 结算瞬间去父会话日志里核实预告到底有没有转达,
1500
+ * 没转达就写一条四项齐全的失败日志(不静默丢失)。
1501
+ *
1502
+ * 目标 id 只从注入值取;注入值缺失时才按 agent.id → session.id 再解析一次
1503
+ * (重启重建/续跑路径)。[2.2.1][T5][F4] 不再回落 plan.sessionId:计划正文
1504
+ * 可能属于另一个 root 会话,不能作为「发给谁」的依据;两级都没有就留空,
1505
+ * 让提示词走「禁止猜测」分支。
1506
+ */
1507
+ const noticeLead = (() => {
1508
+ const injected = readLeadAgentId(options.leadAgentId);
1509
+ const liveAgentId = readLeadAgentId(options.agent?.id);
1510
+ /*
1511
+ * [2.2.0][T3/O-2a][F4] 目标完整性 fail-closed。
1512
+ *
1513
+ * 注入值来自 dispatchPlan 的 agent.id 优先解析;若未来某条重建/续跑路径
1514
+ * 只拿得到 plan.sessionId 兜底值,而执行侧又有活 Agent,则两者不一致
1515
+ * 时绝不能把兜底值写进子提示词(那等于把目标指向另一个 root 会话)。
1516
+ */
1517
+ if (injected && liveAgentId && injected !== liveAgentId) {
1518
+ return { id: '', source: 'mismatch:agent.id' };
1519
+ }
1520
+ if (injected) {
1521
+ return {
1522
+ id: injected,
1523
+ source: typeof options.leadAgentIdSource === 'string' && options.leadAgentIdSource !== 'none'
1524
+ ? options.leadAgentIdSource
1525
+ : 'options.leadAgentId',
1526
+ };
1527
+ }
1528
+ return resolveLeadAgentId({ agent: options.agent, session: options.session });
1529
+ })();
1530
+ const recordNoticeChannel = (entry) => {
1531
+ try {
1532
+ writeSubtaskStatus(record, subtask.id, { noticeChannel: entry }, guard);
1533
+ }
1534
+ catch (error) {
1535
+ /*
1536
+ * 通道留痕失败不能影响子任务本身(它是观测设施,不是交付物),但也不能
1537
+ * 一点痕迹都不留——写进本轮错误列表,主 Agent 读记录时能看到。
1538
+ */
1539
+ record.errors = [...(record.errors ?? []), `${subtask.id} noticeChannel 写入失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20);
1540
+ }
1541
+ };
1542
+ const finaliseNotice = () => {
1543
+ if (guard.timedOut) {
1544
+ /*
1545
+ * [2.2.0][T3/O-2a][F3] 超时路径 writeSubtaskStatus 会被 guard 静默拒绝,
1546
+ * 不能写状态行;但通道不能停在没有结论的 awaiting。至少把四项日志写进
1547
+ * record.errors,让主 Agent 知道「是超时导致没收到结论」,而不是猜测。
1548
+ */
1549
+ const row = record.statuses.find((item) => item?.subtaskId === subtask.id);
1550
+ const current = row?.noticeChannel;
1551
+ if (current) {
1552
+ record.errors = [...(record.errors ?? []), formatNoticeChannelLog({
1553
+ subtaskId: subtask.id,
1554
+ target: current.target,
1555
+ caller: current.caller,
1556
+ at: current.at,
1557
+ reason: 'TIMEOUT',
1558
+ })].slice(-20);
1559
+ }
1560
+ return;
1561
+ }
1562
+ const row = record.statuses.find((item) => item?.subtaskId === subtask.id);
1563
+ const current = row?.noticeChannel;
1564
+ if (!current)
1565
+ return;
1566
+ const noticeSession = options.session && typeof options.session.eventAt === 'function'
1567
+ ? options.session
1568
+ : findSession(ctx, current.target);
1569
+ const observed = observeRelayedNotice(noticeSession, { childId: current.caller, sinceMs: current.at });
1570
+ const entry = finaliseNoticeChannel(current, {
1571
+ observed: Boolean(observed),
1572
+ observedAt: observed?.at ?? null,
1573
+ sessionAvailable: Boolean(noticeSession),
1574
+ now: Date.now(),
1575
+ });
1576
+ recordNoticeChannel(entry);
1577
+ if (entry.state !== 'observed') {
1578
+ record.errors = [...(record.errors ?? []), formatNoticeChannelLog({
1579
+ subtaskId: subtask.id,
1580
+ target: entry.target,
1581
+ caller: entry.caller,
1582
+ at: entry.at,
1583
+ reason: entry.reason,
1584
+ })].slice(-20);
1585
+ }
1586
+ };
1012
1587
  /*
1013
1588
  * [2.1.0] 格式退回通知必须在下一次激活送达部门人员(用户 2026-11-06 的
1014
1589
  * 强制要求:不符合要求立刻退回,通知其重新检查格式后重交)。
@@ -1054,12 +1629,26 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1054
1629
  let interruptedFlag = false;
1055
1630
  let interruptedEvidence = null;
1056
1631
  try {
1632
+ // [2.2.0][T4/O-3b] 尝试起点与协商截止同一时钟读数(C3 契约:deadlineAt −
1633
+ // startedAt 严格等于协商窗口)。deadlineAt 走 StatusEntry 未知字段保留通道
1634
+ // 直写:applyStatus(src/plan.ts,T3 领地)无路由分支,patch 会静默丢弃。
1635
+ const attemptStartMs = Date.now();
1636
+ const attemptWindowMs = Number(options.attemptTimeoutMs ?? 0);
1057
1637
  if (!writeSubtaskStatus(record, subtask.id, {
1058
1638
  status: 'in_progress',
1059
1639
  progress: 5,
1060
- startedAt: Date.now(),
1640
+ startedAt: attemptStartMs,
1061
1641
  }, guard))
1062
1642
  return;
1643
+ if (Number.isFinite(attemptWindowMs) && attemptWindowMs > 0) {
1644
+ const attemptRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
1645
+ if (attemptRow)
1646
+ attemptRow.deadlineAt = attemptStartMs + attemptWindowMs;
1647
+ if (options.attemptHandle) {
1648
+ options.attemptHandle.startedAt = attemptStartMs;
1649
+ options.attemptHandle.deadlineAt = attemptStartMs + attemptWindowMs;
1650
+ }
1651
+ }
1063
1652
  for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
1064
1653
  if (guard.timedOut)
1065
1654
  return;
@@ -1125,6 +1714,14 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1125
1714
  cwd: options.cwd,
1126
1715
  conversationContext,
1127
1716
  statuses: record.statuses,
1717
+ /*
1718
+ * [2.2.0][T3/O-2a] 子→主预告通道的目标(真实父会话 id)。
1719
+ *
1720
+ * 宿主只在非 caller 投递时注入父会话 id,本插件用 caller 投递,
1721
+ * 所以这里必须自己给值;空值走「禁止猜测」分支,绝不编造 id。
1722
+ */
1723
+ leadAgentId: noticeLead.id,
1724
+ leadAgentIdSource: noticeLead.source,
1128
1725
  /*
1129
1726
  * [2.1.0] 不再用 attempt>1 做门槛:被格式退回的行复位后第 1 次
1130
1727
  * 激活也必须带上退回通知,否则「退回」只是写了一行状态。
@@ -1135,9 +1732,27 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1135
1732
  }],
1136
1733
  parent: options.agent,
1137
1734
  cwd: typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined,
1138
- agentOptions: modelSelection?.provider && modelSelection?.model
1139
- ? { provider: modelSelection.provider, model: modelSelection.model }
1140
- : undefined,
1735
+ /*
1736
+ * [2.2.0][T13/推理等级] 子 Agent 不得继承主 Agent 的推理等级。
1737
+ *
1738
+ * 用户规则原文:「禁止子agent继承主agent的推理等级,子agent必须根据
1739
+ * 自身任务的复杂度,自己使用推理等级为low、high或者是Max,其中,轻度
1740
+ * 复杂的任务使用low,中等复杂的任务使用high,非常复杂的任务使用Max。」
1741
+ * 宿主 resolveChildAgentOptions 在请求未点名 reasoningEffort 时会继承
1742
+ * 父 Agent 的等级(dsh-subagent child-agent.d.ts:40-50),旧实现在这里
1743
+ * 只传 provider/model,于是主 Agent 的等级被原样带进每个部门子会话。
1744
+ * 现在显式覆盖为子任务自己的档位;缺失(旧计划/回放)回落 high,绝不
1745
+ * 读取 modelSelection.reasoningEffort。
1746
+ */
1747
+ agentOptions: {
1748
+ ...(modelSelection?.provider && modelSelection?.model
1749
+ ? { provider: modelSelection.provider, model: modelSelection.model }
1750
+ : {}),
1751
+ reasoningEffort: typeof subtask.reasoningEffort === 'string'
1752
+ && REASONING_EFFORTS.includes(subtask.reasoningEffort)
1753
+ ? subtask.reasoningEffort
1754
+ : DEFAULT_REASONING_EFFORT,
1755
+ },
1141
1756
  maxDepth: 1,
1142
1757
  },
1143
1758
  signal: child.controller.signal,
@@ -1177,6 +1792,19 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1177
1792
  }, guard);
1178
1793
  if (!assigned)
1179
1794
  return;
1795
+ /*
1796
+ * [2.2.0][T3/O-2a] 通道条目:此刻写下目标、调用方与时间戳。
1797
+ *
1798
+ * 这一步只记事实,不猜结果——消息有没有真的到主会话,要等结算时去父
1799
+ * 会话日志里看(observeRelayedNotice)。旧实现里预告失败在计划记录上
1800
+ * 完全不可见,主 Agent 只能看到一句 `subagent "lead" is unavailable`。
1801
+ */
1802
+ recordNoticeChannel(createNoticeChannel({
1803
+ target: noticeLead.id,
1804
+ targetSource: noticeLead.source,
1805
+ caller: activation.childId,
1806
+ at: assignedAt,
1807
+ }));
1180
1808
  const ackTimers = [];
1181
1809
  clearAckTimers = () => {
1182
1810
  while (ackTimers.length > 0) {
@@ -1229,8 +1857,58 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1229
1857
  deadlineTimer.unref?.();
1230
1858
  ackTimers.push(deadlineTimer);
1231
1859
  const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
1232
- const hardTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
1860
+ // [2.2.0][T4/O-3b][O-4d] 双计时同源(方案 §2.5):看门狗 hardMs 与本次尝试的
1861
+ // 协商执行时限同值(options.attemptTimeoutMs,缺省回落旧路径);两者必须同步
1862
+ // 推移——延期时 rearmApproachingDeadline 传「自尝试起点计的新完整窗口」。
1863
+ const hardTimeoutMs = Number.isFinite(Number(options.attemptTimeoutMs)) && Number(options.attemptTimeoutMs) > 0
1864
+ ? Math.min(MAX_CHILD_TIMEOUT_MS, Math.max(MIN_CHILD_TIMEOUT_MS, Number(options.attemptTimeoutMs)))
1865
+ : normaliseChildTimeout(options.childTimeoutMs);
1233
1866
  const watchdog = createProgressWatchdog({
1867
+ // [2.2.0][T4/O-3b][O-4b] 到点预警接线(T7 watchdog.ts 契约,原样消费):
1868
+ // 剩余 ≤ max(timeoutMs×0.2, 120000) 触发一次、同一武装周期幂等、extend 后
1869
+ // rearm 可再触发。最小处理器:时间链留档 timeWarning+本轮记录 notice+会话
1870
+ // 消息通知主 Agent(格式朴素,T6 波次统一润色)。
1871
+ subtaskId: String(subtask.id),
1872
+ onApproachingDeadline: (info) => {
1873
+ if (guard.timedOut)
1874
+ return;
1875
+ try {
1876
+ const warnRow = Array.isArray(record.statuses)
1877
+ ? record.statuses.find((item) => item?.subtaskId === subtask.id)
1878
+ : null;
1879
+ if (warnRow) {
1880
+ // timeWarning 走未知字段通道直写(applyStatus 白名单属 T3 领地)。
1881
+ warnRow.timeWarning = {
1882
+ at: Date.now(),
1883
+ remainingMs: Math.max(0, Number(info?.remainingMs ?? 0)),
1884
+ newEstimateMinutes: null,
1885
+ channel: 'watchdog',
1886
+ };
1887
+ }
1888
+ const text = `子任务 ${subtask.id} 即将到点:剩余 ${Math.max(0, Math.round(Number(info?.remainingMs ?? 0) / 1000))}s(协商上限 ${Number(info?.timeoutMs ?? 0)}ms);如需继续请尽快决定延期(extendMs),否则到点将按安全兜底结算(待裁决)`;
1889
+ record.notices = [...(record.notices ?? []), text].slice(-20);
1890
+ record.updatedAt = Date.now();
1891
+ /*
1892
+ * 会话消息只对「有决策余量」的窗口推送:窗口 < 120000ms(=触发规则
1893
+ * max(timeoutMs×0.2, 120000) 里的预警下限,生产最小派生窗口恰好
1894
+ * 120000ms)只出现在测试小窗场景,预警本身没有可执行的延期决策余量,
1895
+ * 此时只留档(record.notices+timeWarning),不推送会话消息——也不与
1896
+ * tests/workplan-stuck-recovery.test.ts「session.events 只计持久消息」
1897
+ * 的既有断言冲突。T6 波次统一润色通知渠道时再定稿推送策略。
1898
+ * [2.2.0][T6/O-1a] 渠道已定稿:与完成即时通知同走主会话
1899
+ * `user/message` 纯文本通道(方案 §2.3「即时通知消息」);决策余量
1900
+ * 门槛(timeoutMs ≥ 120000,取自触发规则预警下限)保持不变,故
1901
+ * 上述断言不受影响。
1902
+ */
1903
+ if (Number(info?.timeoutMs ?? 0) >= 120000) {
1904
+ const warnSession = options.session ?? options.agent?.session;
1905
+ appendUserMessage(warnSession, text);
1906
+ }
1907
+ }
1908
+ catch {
1909
+ // 预警只做提示不得影响执行:写档失败静默忽略(T6 波次统一润色)。
1910
+ }
1911
+ },
1234
1912
  getSeq: () => {
1235
1913
  try {
1236
1914
  const childSession = ctx.sessions?.get?.(activation.childId);
@@ -1277,6 +1955,9 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1277
1955
  ? `子任务 ${subtask.id} 无进展超时(${idleTimeoutMs}ms 内子 Agent 没有产生任何新事件)`
1278
1956
  : `子任务 ${subtask.id} 超时(${hardTimeoutMs}ms)`, reason === 'stalled' ? 'CHILD_STALLED' : 'CHILD_TIMEOUT', { subtaskId: subtask.id }),
1279
1957
  });
1958
+ // [2.2.0][T4/O-3b][O-4d] 看门狗挂到计时句柄:extendDeadline 延期成功后经
1959
+ // watchdog.rearmApproachingDeadline(传新完整窗口)同步推移两处计时。
1960
+ options.attemptHandle?.attachWatchdog?.(watchdog);
1280
1961
  let result;
1281
1962
  try {
1282
1963
  const waiter = waitForActivation(activation, child.controller.signal);
@@ -1427,6 +2108,126 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1427
2108
  }
1428
2109
  recordSubtaskError(record, subtask.id, message, guard);
1429
2110
  }
2111
+ finally {
2112
+ /*
2113
+ * [2.2.0][T3/O-2a] 结算点唯一的通道收束入口(成功/受阻/待指示/中断都走这里)。
2114
+ *
2115
+ * 放在 finally 而不是各条 return 前面,是为了让「通道结论」与「子任务结论」
2116
+ * 一定是同一次执行的产物:任何一个出口漏写,都会让预告看起来像消失了。
2117
+ * [F3] 观测设施自身不得把已结算的子任务变成本轮异常:任何异常只进
2118
+ * record.errors,绝不从 finally 外抛。
2119
+ */
2120
+ try {
2121
+ finaliseNotice();
2122
+ }
2123
+ catch (error) {
2124
+ record.errors = [...(record.errors ?? []), `${subtask.id} noticeChannel 收束失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20);
2125
+ }
2126
+ }
2127
+ }
2128
+ /*
2129
+ * [2.2.0][T4/O-3b] 本次执行时限(柔性时长协商消费序;T3b 待决点③裁决:消费侧钳位)。
2130
+ *
2131
+ * 消费序:① subtask.timeoutMs 显式协商上限(O-3c 原样透传)→ ② 缺省
2132
+ * deriveSubtaskTimeoutMs(estimateMinutes)=clamp(预估分钟×2.0×60000, 1000,
2133
+ * 7200000) 派生(方案 §1③)→ ③ 两者皆无回落 normaliseChildTimeout(全局兜底
2134
+ * CHILD_TIMEOUT_MS,方案 ③C2 零回归)。结果统一钳 [MIN_CHILD_TIMEOUT_MS,
2135
+ * MAX_CHILD_TIMEOUT_MS](方案 ③C3)。
2136
+ *
2137
+ * 显式注入的 childTimeoutMs(测试小窗 / DSH_WORKPLAN_CHILD_TIMEOUT_MS 旋钮)
2138
+ * 语义是「兜底上限」而非「固定值」(方案 §5.2「协商的默认基准/兜底上限」):
2139
+ * 它对上面三步的结果取 min。必须区分「显式注入」与「缺省」——验收合同
2140
+ * tests/no-fixed-deadline-semantics.test.ts E4 注入 1000ms 小窗必须压过
2141
+ * estimateMinutes:10 派生的 1200000ms;而 tests/time-estimate-negotiation
2142
+ * .test.ts C3(无注入)派生值必须严格生效(deadlineAt − startedAt === 派生值)。
2143
+ * 因此 dispatchPlan 三处调用点改传 options.childTimeoutMs 原始值(未配置=
2144
+ * undefined),不再传 normalise 后的 limits.childTimeoutMs(后者恒为 900000,
2145
+ * 无法区分显式与缺省)。
2146
+ */
2147
+ function resolveSubtaskTimeoutMs(subtask, configuredChildTimeoutMs) {
2148
+ const clampWindow = (value) => Math.min(MAX_CHILD_TIMEOUT_MS, Math.max(MIN_CHILD_TIMEOUT_MS, value));
2149
+ const explicit = Number(subtask?.timeoutMs);
2150
+ const derived = deriveSubtaskTimeoutMs(subtask?.estimateMinutes, MIN_CHILD_TIMEOUT_MS, MAX_CHILD_TIMEOUT_MS);
2151
+ let window;
2152
+ if (Number.isFinite(explicit) && explicit > 0)
2153
+ window = clampWindow(explicit);
2154
+ else if (derived !== undefined)
2155
+ window = clampWindow(derived);
2156
+ else
2157
+ window = normaliseChildTimeout(configuredChildTimeoutMs);
2158
+ // 显式注入=兜底上限(对协商结果取 min);未配置不封顶。
2159
+ const cap = Number(configuredChildTimeoutMs);
2160
+ if (Number.isFinite(cap) && cap > 0)
2161
+ window = Math.min(window, clampWindow(cap));
2162
+ return window;
2163
+ }
2164
+ /*
2165
+ * [2.2.0][T4/O-3b][O-4c/O-4d] 延期接口(D 项;T5 extendMs 事务的计时侧承接)。
2166
+ *
2167
+ * 调用契约(T5 按此接线):
2168
+ * extendDeadline(record, subtaskId, extendMs, { by?, reason? })
2169
+ * → 成功 { ok: true, deadlineAt, timerRearmed: true, watchdogRearmed }
2170
+ * → 拒绝 { ok: false, code: 'INVALID_EXTEND' | 'NO_ACTIVE_ATTEMPT', error, hint }
2171
+ *
2172
+ * 语义与边界:
2173
+ * - extendMs 须为正有限数(毫秒,向下取整),否则 INVALID_EXTEND。
2174
+ * - 只对「有活跃尝试」的子任务生效(runSubtaskAttempt 已注册计时句柄且未收束);
2175
+ * 已到点收束 / 已结束的尝试一律 NO_ACTIVE_ATTEMPT(不能复活已结算的行)。
2176
+ * - 累计放宽预算校验(≤初始协商上限×1,超限 EXTEND_BUDGET_EXHAUSTED→转新轮
2177
+ * 续跑或转 escalate)属 T5 事务层职责,本函数不重复校验:调用方先校验再调用。
2178
+ * - 线程/并发语义:Node 单线程;本函数「校验→改 deadlineAt→重置计时器→
2179
+ * watchdog.rearmApproachingDeadline→行内直写」在一个同步段完成,天然原子;
2180
+ * 并发调用按到达顺序串行,每次追加独立 timeJournal 条目(action:'extend')。
2181
+ * - 延期成功后 deadlineAt 同步更新(行上字段=句柄 deadlineAt),runSubtaskAttempt
2182
+ * 的一次性计时器重置为「新截止点 − now」,原截止点不再触发(O-4d:任务不被
2183
+ * 原截止点杀死)。
2184
+ * - 与 watchdog 的配合(F 项):watchdog.rearmApproachingDeadline(newTimeoutMs)
2185
+ * 传入「自尝试起点计的新完整窗口」=deadlineAt − 尝试起点(T7 watchdog.ts
2186
+ * 契约,不是剩余量);两处计时同步推移(方案 §2.5),先触发者仍会杀任务。
2187
+ * - 行字段直写原因:applyStatus(src/plan.ts,T3 领地)无 deadlineAt/timeJournal
2188
+ * 路由分支,patch 会静默丢弃;这里走 StatusEntry 未知字段保留通道直写,
2189
+ * 回放/重建白名单在 reconstructFromSession 同名直写(本文件 2931 一带)。
2190
+ */
2191
+ export function extendDeadline(record, subtaskId, extendMs, meta = {}) {
2192
+ const id = String(subtaskId ?? '');
2193
+ const amount = Number(extendMs);
2194
+ if (!Number.isFinite(amount) || amount < 1) {
2195
+ return {
2196
+ ok: false,
2197
+ code: 'INVALID_EXTEND',
2198
+ error: `extendMs 必须是正有限数(毫秒):${String(extendMs)}`,
2199
+ hint: '请传入 1 以上的毫秒数;需要更长时限请转新轮续跑或转 escalate',
2200
+ };
2201
+ }
2202
+ const delta = Math.floor(amount);
2203
+ const handle = record?.attemptHandles?.[id];
2204
+ if (!handle || handle.settled) {
2205
+ return {
2206
+ ok: false,
2207
+ code: 'NO_ACTIVE_ATTEMPT',
2208
+ error: `子任务 ${id} 当前没有可延期的执行中尝试`,
2209
+ hint: '已收束的尝试不能复活:请转新轮续跑或人工裁决(escalate)',
2210
+ };
2211
+ }
2212
+ const deadlineAt = handle.extend(delta);
2213
+ const row = Array.isArray(record?.statuses)
2214
+ ? record.statuses.find((item) => item?.subtaskId === id)
2215
+ : null;
2216
+ if (row) {
2217
+ // deadlineAt/timeJournal 走未知字段通道直写(applyStatus 白名单属 T3 领地)。
2218
+ row.deadlineAt = deadlineAt;
2219
+ const journal = Array.isArray(row.timeJournal) ? row.timeJournal : [];
2220
+ journal.push({
2221
+ at: Date.now(),
2222
+ action: 'extend',
2223
+ extendMs: delta,
2224
+ by: ['agent', 'child', 'system'].includes(meta?.by) ? meta.by : 'agent',
2225
+ reason: truncate(String(meta?.reason ?? ''), 300),
2226
+ });
2227
+ row.timeJournal = journal.slice(-20);
2228
+ }
2229
+ record.updatedAt = Date.now();
2230
+ return { ok: true, deadlineAt, timerRearmed: true, watchdogRearmed: Boolean(handle.watchdog) };
1430
2231
  }
1431
2232
  /*
1432
2233
  * One attempt under a deadline that belongs to that attempt alone.
@@ -1460,14 +2261,46 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
1460
2261
  */
1461
2262
  let ceilingFingerprint = [];
1462
2263
  const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync;
2264
+ /*
2265
+ * [2.2.0][T4/O-3b][O-4d] 可延期计时句柄(D 项延期接口的运行时锚点,方案 §2.2/§2.5)。
2266
+ * 本次尝试的协商截止只属于这次尝试:extend() 重置一次性计时器并同步 watchdog
2267
+ * (rearmApproachingDeadline 传「自尝试起点计的新完整窗口」);settled 后不得
2268
+ * 复活(extendDeadline 一律 NO_ACTIVE_ATTEMPT)。行上 deadlineAt 由 executeSubtask
2269
+ * 以同一时钟读数写入(C3 契约),句柄权威值随写同步。
2270
+ */
2271
+ const attemptStart = Date.now();
2272
+ const attemptHandle = {
2273
+ subtaskId: String(subtask.id),
2274
+ startedAt: attemptStart,
2275
+ deadlineAt: attemptStart + timeoutMs,
2276
+ settled: false,
2277
+ watchdog: null,
2278
+ arm: (_ms) => { },
2279
+ extend(ms) {
2280
+ if (this.settled)
2281
+ return this.deadlineAt;
2282
+ this.deadlineAt += ms;
2283
+ this.arm(this.deadlineAt - Date.now());
2284
+ this.watchdog?.rearmApproachingDeadline(this.deadlineAt - this.startedAt);
2285
+ return this.deadlineAt;
2286
+ },
2287
+ attachWatchdog(watchdog) {
2288
+ this.watchdog = watchdog;
2289
+ },
2290
+ };
2291
+ record.attemptHandles = { ...(record.attemptHandles ?? {}), [String(subtask.id)]: attemptHandle };
1463
2292
  const deadlinePromise = new Promise((resolve) => {
1464
- timer = setTimeout(() => {
2293
+ const fire = () => {
1465
2294
  ceilingFired = true;
1466
2295
  guard.timedOut = true;
1467
- // Reached only when the child ignored both its idle window and its
1468
- // abort signal; the message says so, otherwise the cause looks like a
1469
- // plain "too slow" and the next investigation goes down the wrong path.
1470
- const message = `子任务 ${subtask.id} 达到执行上限(${timeoutMs}ms),已强制结束`;
2296
+ attemptHandle.settled = true;
2297
+ // [2.2.0][T4/O-3b][O-4d] L4 安全兜底结算+「待裁决」标记(E4 契约):时间是
2298
+ // 协商出来的安全兜底,不是固定交付期限——到点不表述为「强制结束」式固定期限
2299
+ // 误杀,而是安全兜底结算落盘,供主 Agent 决定延期 / 重试 / 接受(或转新轮
2300
+ // 续跑、人工裁决)。Reached only when the child ignored both its idle window
2301
+ // and its abort signal; the message says so, otherwise the cause looks like
2302
+ // a plain "too slow" and the next investigation goes down the wrong path.
2303
+ const message = `子任务 ${subtask.id} 达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:请主 Agent 决定延期 / 重试 / 接受,或转新轮续跑、人工裁决)`;
1471
2304
  try {
1472
2305
  // [1.8.19] Keep the evidence of what already landed on disk.
1473
2306
  const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
@@ -1492,6 +2325,14 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
1492
2325
  record.statuses = applyStatus(record.statuses, subtask.id, patch);
1493
2326
  record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
1494
2327
  }
2328
+ /*
2329
+ * [2.2.0][T4/O-3b][C/E] 「待裁决」结构化标记(E4 契约):结算文案已含
2330
+ * 「待裁决」,这里再落机器可读标记供裁决/回放白名单透传(pendingAdjudication)。
2331
+ * 走 StatusEntry 未知字段通道直写(applyStatus 白名单属 T3 领地)。
2332
+ */
2333
+ const settleRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2334
+ if (settleRow)
2335
+ settleRow.pendingAdjudication = true;
1495
2336
  record.updatedAt = Date.now();
1496
2337
  }
1497
2338
  catch (error) {
@@ -1507,8 +2348,17 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
1507
2348
  child.disposeListener();
1508
2349
  resolve();
1509
2350
  }
1510
- }, timeoutMs);
1511
- timer.unref?.();
2351
+ };
2352
+ // [2.2.0][T4/O-3b][O-4d] 可延期计时(D 项):arm() 重置一次性计时器,extend()
2353
+ // 经 attemptHandle 调用它把截止点推移到新协商截止;原截止点不再触发。
2354
+ const arm = (ms) => {
2355
+ if (timer)
2356
+ clearTimeout(timer);
2357
+ timer = setTimeout(fire, Math.max(1, ms));
2358
+ timer.unref?.();
2359
+ };
2360
+ attemptHandle.arm = arm;
2361
+ arm(timeoutMs);
1512
2362
  });
1513
2363
  try {
1514
2364
  // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
@@ -1518,12 +2368,20 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
1518
2368
  ...options,
1519
2369
  child,
1520
2370
  guard,
2371
+ // [2.2.0][T4/O-3b] 本次尝试的协商执行时限与计时句柄(deadlineAt 写入同源、
2372
+ // 看门狗 hardMs 同值、延期接口锚点)。
2373
+ attemptTimeoutMs: timeoutMs,
2374
+ attemptHandle,
1521
2375
  }),
1522
2376
  deadlinePromise,
1523
2377
  ]);
1524
2378
  return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint };
1525
2379
  }
1526
2380
  finally {
2381
+ // [2.2.0][T4/O-3b] 收束即注销句柄:已收束的尝试不得再被 extendDeadline 复活。
2382
+ attemptHandle.settled = true;
2383
+ if (record.attemptHandles)
2384
+ delete record.attemptHandles[String(subtask.id)];
1527
2385
  if (timer) {
1528
2386
  clearTimeout(timer);
1529
2387
  timer = null;
@@ -1548,7 +2406,10 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
1548
2406
  * skipped and the row is marked `artifactConflict` instead of overwriting it.
1549
2407
  */
1550
2408
  async function runSubtask(ctx, record, stage, subtask, options) {
1551
- const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
2409
+ // [2.2.0][T4/O-3b] 本次执行时限=柔性时长协商消费序(见 resolveSubtaskTimeoutMs):
2410
+ // ① subtask.timeoutMs 显式值 → ② deriveSubtaskTimeoutMs(estimateMinutes) 派生 →
2411
+ // ③ 缺省回落 CHILD_TIMEOUT_MS;显式注入的 childTimeoutMs 作兜底上限取 min。
2412
+ const childTimeoutMs = resolveSubtaskTimeoutMs(subtask, options.childTimeoutMs);
1552
2413
  const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs);
1553
2414
  if (!first.ceilingFired)
1554
2415
  return first.outcome;
@@ -1556,7 +2417,7 @@ async function runSubtask(ctx, record, stage, subtask, options) {
1556
2417
  const now = Date.now();
1557
2418
  const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs;
1558
2419
  const remaining = deadline - now;
1559
- const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms)`;
2420
+ const message = `子任务 ${subtask.id} 达到协商执行上限(${childTimeoutMs}ms)`;
1560
2421
  /*
1561
2422
  * [1.8.6] A parent abort outranks a retry: the round is being stopped on
1562
2423
  * purpose, and a second child would only be aborted on arrival.
@@ -1610,7 +2471,7 @@ async function runSubtask(ctx, record, stage, subtask, options) {
1610
2471
  const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
1611
2472
  ...options,
1612
2473
  attemptOffset: 2,
1613
- priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已强制结束` },
2474
+ priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已按安全兜底结算(待裁决)` },
1614
2475
  }, retryTimeoutMs);
1615
2476
  return second.outcome;
1616
2477
  }
@@ -1694,6 +2555,29 @@ export function modelStatusLines(statuses) {
1694
2555
  status: handoff.status,
1695
2556
  })),
1696
2557
  reportedAt: item.reportedAt ?? null,
2558
+ /*
2559
+ * [2.2.0][T4/O-3b][O-2.4] 柔性时长协商字段进入模型可读面(纯展示):
2560
+ * 协商截止 deadlineAt、尝试起点 startedAt、剩余协商时间、预警标记 timeWarning、
2561
+ * 待裁决标记 pendingAdjudication 与时间链审计 timeJournal。验收合同
2562
+ * tests/time-estimate-negotiation.test.ts C3 直接从 statusTool 输出读
2563
+ * deadlineAt/startedAt(字段名/单位照合同原文)。
2564
+ */
2565
+ startedAt: item.startedAt ?? null,
2566
+ deadlineAt: item.deadlineAt ?? null,
2567
+ deadlineRemainingMs: Number.isFinite(Number(item.deadlineAt))
2568
+ ? Math.max(0, Number(item.deadlineAt) - Date.now())
2569
+ : null,
2570
+ timeWarning: item.timeWarning ?? null,
2571
+ timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
2572
+ pendingAdjudication: item.pendingAdjudication === true,
2573
+ /*
2574
+ * [2.2.0][T3/O-2a] 子→主预告通道的结论必须进入模型可读面。
2575
+ *
2576
+ * 这条能力的目标就是「可观测」:主 Agent 要能一眼看出该子任务的开工预告
2577
+ * 有没有真的到达(observed/not-observed)、目标是谁、什么时候、失败原因。
2578
+ * 只写状态行不让读,等于又是一个「看不见的失败」。
2579
+ */
2580
+ noticeChannel: item.noticeChannel ?? null,
1697
2581
  }));
1698
2582
  }
1699
2583
  export function buildRoundResult(record, sessionId, limits) {
@@ -1765,7 +2649,18 @@ function describePendingCause(plan, statuses, id) {
1765
2649
  }
1766
2650
  export async function dispatchPlan(ctx, record, options) {
1767
2651
  const { agent, signal, modelSelection, cwd, conversationContext = '' } = options;
1768
- const deadline = Date.now() + (options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
2652
+ const roundBudgetMs = Number(options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
2653
+ const deadline = Date.now() + (roundBudgetMs > 0 ? roundBudgetMs : NO_ROUND_BUDGET_MS);
2654
+ /*
2655
+ * [2.2.0][T3/O-2a] 本轮子→主预告通道的目标会话 id,一轮只解析一次。
2656
+ *
2657
+ * 宿主只在**非 caller** 投递时把父会话 id 追加进子提示词
2658
+ * (dsh-subagent/lib/index.js:1466),本插件用 `delivery: 'caller'` 派发,
2659
+ * 所以必须自己注入。解析优先级见 notice-channel.ts(agent.id → session.id),
2660
+ * 两级都拿不到就留空,提示词改走「禁止猜测」分支([2.2.1][T5][F4] 不再用
2661
+ * plan.sessionId 兜底:计划正文可能属于另一个 root 会话)。
2662
+ */
2663
+ const leadNotice = resolveLeadAgentId({ agent, session: options.session });
1769
2664
  /*
1770
2665
  * Resume, do not restart.
1771
2666
  *
@@ -1844,7 +2739,9 @@ export async function dispatchPlan(ctx, record, options) {
1844
2739
  parentSignal.addEventListener('abort', onAbort, { once: true });
1845
2740
  const totalTimer = setTimeout(() => {
1846
2741
  childController.abort(new PlanError('总执行超时', 'TOTAL_TIMEOUT'));
1847
- }, Math.max(1000, deadline - Date.now()));
2742
+ // [2.2.5][热修] 双重保险:即使哨兵值/配置未来被改成超限值,也把延时钳在
2743
+ // Node setTimeout 上限之内,杜绝“1ms 触发”的整轮秒杀。
2744
+ }, Math.min(Math.max(1000, deadline - Date.now()), ROUND_TIMER_MAX_MS));
1848
2745
  totalTimer.unref?.();
1849
2746
  record.dispatchedAt = Date.now();
1850
2747
  record.phase = 'executing';
@@ -1933,6 +2830,15 @@ export async function dispatchPlan(ctx, record, options) {
1933
2830
  // [1.10.6] Injectable stat for the pre-retry fingerprint check; tests
1934
2831
  // use it so the conflict branch is provable without real files.
1935
2832
  artifactStat: options.artifactStat,
2833
+ // [2.2.0][T6/O-1a] 即时通知接线:后台轮次标记、主会话与完成回调透传到结算点。
2834
+ notifyCompletion: options.notifyCompletion === true,
2835
+ session: options.session,
2836
+ // [2.2.0][T3/O-2a] 子→主预告通道:目标 id 与其来源随派发一起下传,
2837
+ // 提示词注入与结算观测必须用同一个值(否则「注入了什么」与
2838
+ // 「观测的是谁」会分叉,通道永远对不上)。
2839
+ leadAgentId: leadNotice.id,
2840
+ leadAgentIdSource: leadNotice.source,
2841
+ onSubtaskDone: options.onSubtaskDone,
1936
2842
  });
1937
2843
  // [1.8.6] Remember which failures were interrupts, so the cascade below
1938
2844
  // can leave their dependents pending instead of blaming them.
@@ -2068,12 +2974,14 @@ export async function dispatchPlan(ctx, record, options) {
2068
2974
  * 会让卡片显示「预算用完、可续跑」,而真正该做的是 instruct。
2069
2975
  */
2070
2976
  record.phase = allDoneNow ? 'done' : (blockedNow > 0 ? 'blocked' : 'paused');
2071
- const minutes = Math.max(1, Math.round((options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000));
2977
+ const roundBudgetMs = Number(options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
2978
+ const minutes = roundBudgetMs > 0 ? Math.max(1, Math.round(roundBudgetMs / 60000)) : 0;
2979
+ const roundLabel = minutes > 0 ? `本轮执行预算(${minutes} 分钟)` : '本轮无固定总预算';
2072
2980
  record.error = allDoneNow
2073
2981
  ? null
2074
2982
  : blockedNow > 0
2075
- ? `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total};${blockedNow} 项在等待指示或已受阻(续跑不会重派,请先 instruct 或改判),${pendingNow} 项保留为未完成,再次派发本计划即可继续`
2076
- : `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total},其余 ${total - done} 项保留为未完成,再次派发本计划即可续跑(已完成的不重跑)`;
2983
+ ? `${roundLabel}已到:已完成 ${done}/${total};${blockedNow} 项在等待指示或已受阻(续跑不会重派,请先 instruct 或改判),${pendingNow} 项保留为未完成,再次派发本计划即可继续`
2984
+ : `${roundLabel}已到:已完成 ${done}/${total},其余 ${total - done} 项保留为未完成,再次派发本计划即可续跑(已完成的不重跑)`;
2077
2985
  /*
2078
2986
  * Drop the failure lines the aborted children wrote on their way out.
2079
2987
  * They used to survive into the result payload as
@@ -2574,6 +3482,38 @@ export function reconstructFromSession(session, targetPlanId) {
2574
3482
  const snap = snapshots.get(result.planId);
2575
3483
  if (snap) {
2576
3484
  snap.statuses = applyResultStatuses(snap.statuses, result);
3485
+ /*
3486
+ * [2.2.0][T4/O-3b][E] 重建白名单(E 项,runtime 侧):applyResultStatuses
3487
+ * (src/plan.ts,T3 领地)逐字段重建不含柔性时长协商新字段,会把
3488
+ * deadlineAt/timeNotice/timeWarning/timeJournal/待裁决标记洗掉;结果消息
3489
+ * 整包透传行对象(字段在 entry 上),按 T3b plan.ts:2966-2971 同名修复
3490
+ * 口径补直写回放。
3491
+ */
3492
+ for (const entry of (Array.isArray(result.statuses) ? result.statuses : [])) {
3493
+ const rebuiltRow = snap.statuses.find((item) => item?.subtaskId === entry?.subtaskId);
3494
+ if (!rebuiltRow || !isRecord(entry))
3495
+ continue;
3496
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
3497
+ if (entry[field] !== undefined)
3498
+ rebuiltRow[field] = entry[field];
3499
+ }
3500
+ /*
3501
+ * [2.2.0][T3/O-2a][F1] 通道结论也必须活过进程重启。
3502
+ * applyResultStatuses 已带该字段;这里再走一次校验,防止旧日志/
3503
+ * 未来字段来源把脏值直接拷进重建行(fail-closed)。
3504
+ *
3505
+ * [2.2.1][T5][F1] 非法值必须 `delete` 而不是写 `null`:写 null 会让
3506
+ * 脏字段跨每次重启自我延续(下一次回放又把整行丢掉,done 行永远显示
3507
+ * pending)。删除等价于「该结果消息没带这个字段」,合法值不受影响。
3508
+ */
3509
+ if (entry.noticeChannel !== undefined) {
3510
+ const checked = validateNoticeChannel(entry.noticeChannel);
3511
+ if (checked.ok)
3512
+ rebuiltRow.noticeChannel = checked.value;
3513
+ else
3514
+ delete rebuiltRow.noticeChannel;
3515
+ }
3516
+ }
2577
3517
  // Resume bookkeeping must survive a page refresh, otherwise the budget
2578
3518
  // silently resets and a never-succeeding subtask can loop forever.
2579
3519
  snap.resumeCount = Number(result.resumeCount ?? snap.resumeCount) || 0;
@@ -2616,6 +3556,18 @@ export function reconstructFromSession(session, targetPlanId) {
2616
3556
  * INVALID_TRANSITION(wp-79c31abf 的 H1 就是这样被丢掉的)。
2617
3557
  */
2618
3558
  status: update.handoffs === undefined ? update.status : undefined,
3559
+ /*
3560
+ * [2.2.6][D-1] 人工改判的 closure 必须随 patch 回放。
3561
+ *
3562
+ * durable 的 workplan-update 自 1.11.0 起携带 closure
3563
+ * (buildUpdateMessage),但这里的 patch 一直没把它传给
3564
+ * applyStatus:行停在 escalated 时,status=done 的改判会因
3565
+ * 「非法闭环迁移 escalated→done / closure=escalated 必须同时
3566
+ * status=blocked」被拒,整条 update 被下面的裸 catch 吞掉,
3567
+ * 重启后「待指示」行永久卡死(2026-11-08 wp-3c8c84b2 T2 实证,
3568
+ * 见 artifacts/2.2.5-post-restart-regression.md §4 D-1)。
3569
+ */
3570
+ closure: typeof update.closure === 'string' ? update.closure : undefined,
2619
3571
  progress: typeof update.progress === 'number' ? update.progress : undefined,
2620
3572
  summary: typeof update.note === 'string' ? update.note : undefined,
2621
3573
  // [1.8.13] Evidence written through the update tool must survive replay.
@@ -2625,15 +3577,56 @@ export function reconstructFromSession(session, targetPlanId) {
2625
3577
  missingArtifacts: update.missingArtifacts,
2626
3578
  handoffs: update.handoffs,
2627
3579
  revision: Number.isInteger(update.revision) ? update.revision : undefined,
3580
+ // [2.2.0][T4/O-3b][E] 回放白名单(T3b TODO#2):O-3b/O-2c 留档字段随
3581
+ // update 记录回放;timeoutMs 有 applyStatus 分支,走 patch 即可。
3582
+ timeoutMs: update.timeoutMs,
2628
3583
  updatedBy: 'agent',
2629
3584
  });
3585
+ /*
3586
+ * [2.2.0][T4/O-3b][E] 柔性时长协商新字段回放(E 项,runtime.ts 2931 一带)。
3587
+ *
3588
+ * deadlineAt/timeNotice/timeWarning/timeJournal/待裁决标记在 applyStatus
3589
+ * (src/plan.ts,T3 领地)无路由分支,走 patch 会被静默丢弃;按 T3b
3590
+ * plan.ts:2966-2971 同名修复口径在此直写重建行。extendMs 走累加语义
3591
+ * (与线上 extendDeadline 一致:deadlineAt += extendMs 并追加 timeJournal),
3592
+ * 仅当记录未自带 timeJournal 时合成,避免同一条 journal 被回放两次。
3593
+ */
3594
+ const replayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
3595
+ if (replayRow) {
3596
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
3597
+ if (update[field] !== undefined)
3598
+ replayRow[field] = update[field];
3599
+ }
3600
+ const replayExtend = Number(update.extendMs);
3601
+ if (update.timeJournal === undefined && Number.isFinite(replayExtend) && replayExtend > 0
3602
+ && Number.isFinite(Number(replayRow.deadlineAt))) {
3603
+ replayRow.deadlineAt = Number(replayRow.deadlineAt) + Math.floor(replayExtend);
3604
+ replayRow.timeJournal = [
3605
+ ...(Array.isArray(replayRow.timeJournal) ? replayRow.timeJournal : []),
3606
+ {
3607
+ at: Date.now(),
3608
+ action: 'extend',
3609
+ extendMs: Math.floor(replayExtend),
3610
+ by: 'agent',
3611
+ reason: truncate(String(update.reason ?? ''), 300),
3612
+ },
3613
+ ].slice(-20);
3614
+ }
3615
+ }
2630
3616
  appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
2631
3617
  seq: Number(event.seq ?? 0),
2632
3618
  status: String(update.status ?? ''),
2633
3619
  });
2634
3620
  }
2635
- catch {
2636
- // An invalid historical update is ignored; the rest still replays.
3621
+ catch (error) {
3622
+ /*
3623
+ * [2.2.6][D-1] fail-closed 而非 fail-silent:历史 update 不合法时
3624
+ * 至少留一条日志,否则「改判丢失」永远无从发现(本缺陷因此潜伏
3625
+ * 自 1.7.0)。回放继续,不让单条坏记录拖垮整个重建。
3626
+ */
3627
+ console.warn('[dsh-workplan] 回放忽略一条不合法的历史改判:'
3628
+ + `${String(update?.planId ?? '')}/${String(update?.subtaskId ?? '')}:`
3629
+ + `${error instanceof Error ? error.message : String(error)}`);
2637
3630
  }
2638
3631
  }
2639
3632
  }
@@ -2969,10 +3962,20 @@ export function createWorkplanRuntime(ctx, options = {}) {
2969
3962
  };
2970
3963
  }
2971
3964
  const limits = {
3965
+ /*
3966
+ * [2.1.6] 规划器的两扇窗此前不在 limits 里:`options.limits.plannerTimeoutMs`
3967
+ * 永远是 undefined,调用处只能靠兜底常量,状态/诊断也因此读不到「当前生效
3968
+ * 的规划器时限」。补齐后配置 → limits → 单次调用是同一条链路。
3969
+ */
3970
+ plannerTimeoutMs: normalisePlannerWindow(options.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
3971
+ plannerIdleTimeoutMs: normalisePlannerWindow(options.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
2972
3972
  childTimeoutMs: normaliseChildTimeout(options.childTimeoutMs),
2973
3973
  idleTimeoutMs: normaliseIdleTimeout(options.idleTimeoutMs),
2974
- totalTimeoutMs: Number.isFinite(Number(options.totalTimeoutMs)) && Number(options.totalTimeoutMs) > 0
2975
- ? Math.max(60000, Math.floor(Number(options.totalTimeoutMs)))
3974
+ // [2.2.5] 0 = 不设整轮硬预算;正数才启用(最小 60s)。未配置按 0。
3975
+ totalTimeoutMs: Number.isFinite(Number(options.totalTimeoutMs)) && Number(options.totalTimeoutMs) >= 0
3976
+ ? (Number(options.totalTimeoutMs) === 0
3977
+ ? 0
3978
+ : Math.max(60000, Math.floor(Number(options.totalTimeoutMs))))
2976
3979
  : TOTAL_TIMEOUT_MS,
2977
3980
  maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
2978
3981
  ? Math.min(5, Math.floor(Number(options.maxResumes)))
@@ -3003,12 +4006,16 @@ export function createWorkplanRuntime(ctx, options = {}) {
3003
4006
  modelSelection: record.modelSelection,
3004
4007
  cwd: session.header?.cwd ?? options.cwd,
3005
4008
  conversationContext: record.conversationContext ?? '',
4009
+ // [2.2.0][T6/O-1a] 自动派发是后台轮次:结算成功即推送完成即时通知。
4010
+ notifyCompletion: true,
4011
+ onSubtaskDone: (recordArg, subtask, verdict) => emitSubtaskDoneNotice(recordArg, session, subtask, verdict),
3006
4012
  };
3007
4013
  record.dispatchStartedAt = Date.now();
3008
4014
  record.dispatchPromise = dispatchPlan(ctx, record, {
3009
4015
  ...roundOptions,
3010
4016
  signal: controller.signal,
3011
- childTimeoutMs: limits.childTimeoutMs,
4017
+ // [2.2.0][T4/O-3b] 传原始配置值:未配置=undefined 时协商派生生效,显式配置=兜底上限(resolveSubtaskTimeoutMs)。
4018
+ childTimeoutMs: options.childTimeoutMs,
3012
4019
  idleTimeoutMs: limits.idleTimeoutMs,
3013
4020
  totalTimeoutMs: limits.totalTimeoutMs,
3014
4021
  maxResumes: limits.maxResumes,
@@ -3117,6 +4124,84 @@ export function createWorkplanRuntime(ctx, options = {}) {
3117
4124
  state.records.set(session.id, rebuilt);
3118
4125
  return rebuilt;
3119
4126
  }
4127
+ /*
4128
+ * [2.2.0][T5/O-4c/O-4d] 延期预算(防滥用,方案 §5.4 #1/#2;数值只引方案原文)。
4129
+ *
4130
+ * 初始协商上限的解析完全复用 T4 的 resolveSubtaskTimeoutMs(显式
4131
+ * subtask.timeoutMs → deriveSubtaskTimeoutMs(estimateMinutes) → 回落
4132
+ * CHILD_TIMEOUT_MS)。方案没有给出 MAX_EXTEND_MS 的具体数值,因此**不自拟
4133
+ * 常量**:单次延期上限派生为「剩余延期预算」=初始协商上限 × 1 − 已累计延期
4134
+ * (timeJournal 中 action:'extend' 之和)。累计超限即拒绝并转「请主 Agent
4135
+ * 裁决」(EXTEND_BUDGET_EXHAUSTED),放宽永远有界。
4136
+ *
4137
+ * 为什么初始上限不传 options.childTimeoutMs:显式注入的 childTimeoutMs 是
4138
+ * 运维兜底上限(见 resolveSubtaskTimeoutMs 注释),不是本子任务的协商上限;
4139
+ * 延期预算按方案 §2.2 的口径取计划层解析值。验收合同也用同一口径(D4 用
4140
+ * 显式 timeoutMs 定 2000ms;D2 用例在 1200ms 小窗上放宽 1500ms 是合法的)。
4141
+ */
4142
+ function extendBudgetOf(record, subtaskId) {
4143
+ const entry = flattenSubtasks(record?.plan ?? { stages: [] })
4144
+ .find((candidate) => candidate?.subtask?.id === subtaskId);
4145
+ const initialMs = resolveSubtaskTimeoutMs(entry?.subtask, undefined);
4146
+ const row = Array.isArray(record?.statuses)
4147
+ ? record.statuses.find((item) => item?.subtaskId === subtaskId)
4148
+ : null;
4149
+ const usedMs = (Array.isArray(row?.timeJournal) ? row.timeJournal : [])
4150
+ .filter((item) => item?.action === 'extend')
4151
+ .reduce((sum, item) => {
4152
+ const value = Number(item?.extendMs);
4153
+ return Number.isFinite(value) && value > 0 ? sum + Math.floor(value) : sum;
4154
+ }, 0);
4155
+ // 方案 §5.4 #2:累计 extendMs ≤ 初始协商上限 × 1(最多再给一倍)。
4156
+ const capMs = initialMs;
4157
+ return { initialMs, capMs, usedMs, remainingMs: Math.max(0, capMs - usedMs) };
4158
+ }
4159
+ /*
4160
+ * [2.2.0][T5/O-4c] timeNotice 的形状校验(方案 §2.4:{declaredMinutes, reason})。
4161
+ * 只记录、不改判定;非法值返回可读错误而不是抛裸错(与 STALE_WRITE 同风格)。
4162
+ */
4163
+ function validateTimeNotice(notice) {
4164
+ const declared = Number(notice?.declaredMinutes);
4165
+ if (!Number.isFinite(declared) || declared <= 0) {
4166
+ return {
4167
+ code: 'INVALID_TIME_NOTICE',
4168
+ error: `timeNotice.declaredMinutes 必须是正数分钟:${String(notice?.declaredMinutes)}`,
4169
+ hint: '预告只做记录(仅供参考、非承诺):请传正数分钟与可选 reason。',
4170
+ };
4171
+ }
4172
+ return null;
4173
+ }
4174
+ /*
4175
+ * [2.2.0][T5/O-4c] 写入专家开工预告(O-2a):状态行 timeNotice + timeJournal
4176
+ * 的 action:'estimate' 条目。applyStatus(plan.ts,T3 领地)还没有该字段的
4177
+ * 路由分支,按 T4 直写通道写行(StatusEntry 保留未知字段;回放白名单已透传
4178
+ * timeNotice,刷新后不丢)。
4179
+ */
4180
+ function recordTimeNotice(record, subtaskId, notice) {
4181
+ const row = Array.isArray(record?.statuses)
4182
+ ? record.statuses.find((item) => item?.subtaskId === subtaskId)
4183
+ : null;
4184
+ if (!row)
4185
+ return;
4186
+ const at = Date.now();
4187
+ const reason = truncate(String(notice?.reason ?? ''), 300);
4188
+ row.timeNotice = {
4189
+ declaredMinutes: Number(notice?.declaredMinutes),
4190
+ at,
4191
+ channel: 'agent',
4192
+ reason,
4193
+ };
4194
+ const journal = Array.isArray(row.timeJournal) ? row.timeJournal : [];
4195
+ journal.push({
4196
+ at,
4197
+ action: 'estimate',
4198
+ declaredMinutes: Number(notice?.declaredMinutes),
4199
+ by: 'agent',
4200
+ reason,
4201
+ });
4202
+ row.timeJournal = journal.slice(-20);
4203
+ record.updatedAt = at;
4204
+ }
3120
4205
  async function updateStatus(agent, args) {
3121
4206
  const session = agent?.session;
3122
4207
  if (!session)
@@ -3129,21 +4214,87 @@ export function createWorkplanRuntime(ctx, options = {}) {
3129
4214
  record = adoptRequestedPlan(session, record, args?.planId);
3130
4215
  if (!record?.plan)
3131
4216
  throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
3132
- // [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
3133
- clearAutoResumeTimer(record, 'manual-update');
3134
4217
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : '';
3135
4218
  if (!subtaskId)
3136
4219
  throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK');
3137
4220
  const status = typeof args?.status === 'string' ? args.status : '';
3138
- if (!['pending', 'in_progress', 'done', 'blocked'].includes(status)) {
3139
- throw new PlanError('status 必须是 pending / in_progress / done / blocked', 'INVALID_STATUS');
4221
+ /*
4222
+ * [2.2.0][T5/O-4c] 延期事务的入口判定(D2/D3/D4,方案 §2.2):
4223
+ * extendMs / timeNotice 属于「只改时限、只做记录」的字段,不改状态判定,
4224
+ * 因此允许不带 status 单独提交;运行中也不需要 force——TASK_RUNNING 的
4225
+ * 唯一豁免来自「不改判定」这一事实,而不是特权。
4226
+ */
4227
+ const extendMsArg = args?.extendMs;
4228
+ const hasExtend = extendMsArg !== undefined && extendMsArg !== null;
4229
+ const timeNoticeArg = args?.timeNotice;
4230
+ const hasTimeNotice = timeNoticeArg !== undefined && timeNoticeArg !== null;
4231
+ const statusRequested = ['pending', 'in_progress', 'done', 'blocked'].includes(status);
4232
+ if (!statusRequested && !hasExtend && !hasTimeNotice) {
4233
+ throw new PlanError('status 必须是 pending / in_progress / done / blocked(仅协商时限时可省略 status,改传 extendMs / timeNotice)', 'INVALID_STATUS');
4234
+ }
4235
+ if (hasExtend && !(typeof extendMsArg === 'number' && Number.isInteger(extendMsArg) && extendMsArg > 0)) {
4236
+ return {
4237
+ ok: false,
4238
+ code: 'INVALID_EXTEND',
4239
+ planId: record.plan.planId,
4240
+ subtaskId,
4241
+ error: `extendMs 必须是正整数毫秒:${String(extendMsArg)}`,
4242
+ hint: '请传入 1 以上的整数毫秒;放宽永远有界(累计 ≤ 初始协商上限 × 1),超出请转新轮续跑或转 escalate 请主 Agent 裁决。',
4243
+ };
4244
+ }
4245
+ /*
4246
+ * [2.2.0][T5/O-4c] timeNotice 的校验放在入口统一做(所有路径共享):
4247
+ * 非法预告不该因为调用同时带了 status/instruction 就被静默接受。
4248
+ */
4249
+ if (hasTimeNotice) {
4250
+ const problem = validateTimeNotice(timeNoticeArg);
4251
+ if (problem) {
4252
+ return {
4253
+ ok: false,
4254
+ code: problem.code,
4255
+ planId: record.plan.planId,
4256
+ subtaskId,
4257
+ error: problem.error,
4258
+ hint: problem.hint,
4259
+ };
4260
+ }
3140
4261
  }
4262
+ /*
4263
+ * [2.2.0][T5/O-4c] 延期事务与状态改判分开提交:方案 §2.2 把 extendMs 定为
4264
+ * 「放宽时间的唯一写路径」,要求原子与可审计;一次调用既改判定又改时限会让
4265
+ * 失败路径出现半写(判定已落、时限未落,或相反)。组合调用显式拒绝,模型分
4266
+ * 两次提交即可(两者都不需要 force)。
4267
+ */
4268
+ if (hasExtend && statusRequested) {
4269
+ return {
4270
+ ok: false,
4271
+ code: 'EXTEND_REQUIRES_DEDICATED_CALL',
4272
+ planId: record.plan.planId,
4273
+ subtaskId,
4274
+ error: '延期事务必须单独提交:同一次调用不要同时传 status 与 extendMs(放宽是原子、可审计的唯一写路径)',
4275
+ hint: '先单独调用 extendMs 放宽时限,再用另一次调用改判状态。',
4276
+ };
4277
+ }
4278
+ /*
4279
+ * [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
4280
+ * [2.2.0][T5/O-4c] 纯延期/纯预告不改判定,不撤销自动续跑(否则一次失败的
4281
+ * 延期尝试会把已排期的续跑静默取消,计划停在 paused 无人推进)。
4282
+ */
4283
+ if (statusRequested)
4284
+ clearAutoResumeTimer(record, 'manual-update');
3141
4285
  const note = typeof args?.note === 'string' ? args.note : '';
3142
4286
  const evidence = Array.isArray(args?.evidence)
3143
4287
  ? args.evidence.filter((item) => typeof item === 'string').join(';')
3144
4288
  : '';
3145
4289
  const summary = [note, evidence].filter(Boolean).join('|');
3146
4290
  const current = record.statuses.find((item) => item.subtaskId === subtaskId);
4291
+ /*
4292
+ * [2.2.0][T5/O-4c] 纯时限事务(不带 status)不经过 applyStatus,必须自己
4293
+ * 拒绝未知子任务——否则一次对不存在行的 timeNotice 会得到「成功」。
4294
+ */
4295
+ if (!statusRequested && !current) {
4296
+ throw new PlanError(`未知子任务:${subtaskId}`, 'UNKNOWN_SUBTASK');
4297
+ }
3147
4298
  /*
3148
4299
  * [1.7.0] Two write guards, both non-throwing.
3149
4300
  *
@@ -3169,7 +4320,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
3169
4320
  };
3170
4321
  }
3171
4322
  const running = Boolean(record.dispatchPromise);
3172
- const writeWhileRunning = running && !args?.force && (current?.status === 'pending' || current?.status === 'in_progress');
4323
+ /*
4324
+ * [2.2.0][T5/O-4c] TASK_RUNNING 的唯一豁免:只给「不改状态判定」的时限事务。
4325
+ * 纯 extendMs / timeNotice 更新(statusRequested=false)照常放行;只要同一次
4326
+ * 调用还带 status,仍走原守卫——其余状态字段不得被顺手改掉(行为不变)。
4327
+ */
4328
+ const writeWhileRunning = running && !args?.force && statusRequested
4329
+ && (current?.status === 'pending' || current?.status === 'in_progress');
3173
4330
  if (writeWhileRunning) {
3174
4331
  return {
3175
4332
  ok: false,
@@ -3211,11 +4368,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
3211
4368
  error: '下发 instruction 时 status 必须是 in_progress(或改用 dsh_workplan_instruct)。',
3212
4369
  };
3213
4370
  }
3214
- return instructSubtask(agent, {
4371
+ const instructed = await instructSubtask(agent, {
3215
4372
  planId: args?.planId,
3216
4373
  subtaskId,
3217
4374
  instruction,
3218
4375
  }, undefined, record);
4376
+ /*
4377
+ * [2.2.0][T5/O-4c] 预告与指示同一次到达时,指示成功落行后再记预告:
4378
+ * 指示失败不该留下一笔「专家已预告」的记录。
4379
+ */
4380
+ if (hasTimeNotice && instructed?.ok !== false)
4381
+ recordTimeNotice(record, subtaskId, timeNoticeArg);
4382
+ return instructed;
3219
4383
  }
3220
4384
  if (current?.closure === 'escalated') {
3221
4385
  if (status === 'done') {
@@ -3237,6 +4401,90 @@ export function createWorkplanRuntime(ctx, options = {}) {
3237
4401
  };
3238
4402
  }
3239
4403
  }
4404
+ /*
4405
+ * [2.2.0][T5/O-4c] 延期事务(放宽时间的唯一写路径,方案 §2.2;D2/D3 效果 +
4406
+ * §5.4 防滥用):
4407
+ * 1. 预算:初始协商上限取 T4 resolveSubtaskTimeoutMs 的计划层解析值;累计
4408
+ * 放宽(timeJournal 中 action:'extend' 之和)≤ 初始上限 × 1。方案没有给
4409
+ * MAX_EXTEND_MS 数值,单次上限派生为「剩余延期预算」,不自拟常量。
4410
+ * 2. 执行:校验通过才调用 T4 extendDeadline——它负责 deadlineAt += extendMs、
4411
+ * 重置一次性计时器、同步 watchdog,并追加 timeJournal(action:'extend')。
4412
+ * 回放侧(本文件 replay 白名单)的累加语义与此一致:deadlineAt 累加 +
4413
+ * 同形 journal 条目,所以回放代码不需要改。
4414
+ * 3. 纯时限事务不改状态判定:回执只带时限结果与审计字段。
4415
+ */
4416
+ let extension = null;
4417
+ if (hasExtend) {
4418
+ const budget = extendBudgetOf(record, subtaskId);
4419
+ if (extendMsArg > budget.remainingMs) {
4420
+ return {
4421
+ ok: false,
4422
+ code: 'EXTEND_BUDGET_EXHAUSTED',
4423
+ planId: record.plan.planId,
4424
+ subtaskId,
4425
+ budget,
4426
+ error: `extendMs ${extendMsArg}ms 超出剩余延期预算 ${budget.remainingMs}ms:`
4427
+ + `累计延期 ${budget.usedMs}ms,初始协商上限 ${budget.initialMs}ms(上限 × 1 = ${budget.capMs}ms)`,
4428
+ hint: '放宽永远有界:该任务应转入新轮续跑(auto-resume)或转 escalate 请主 Agent/用户裁决。',
4429
+ };
4430
+ }
4431
+ const extended = extendDeadline(record, subtaskId, extendMsArg, {
4432
+ by: 'agent',
4433
+ reason: typeof args?.reason === 'string'
4434
+ ? args.reason
4435
+ : (typeof args?.note === 'string' ? args.note : ''),
4436
+ });
4437
+ if (!extended.ok) {
4438
+ return {
4439
+ ok: false,
4440
+ code: extended.code,
4441
+ planId: record.plan.planId,
4442
+ subtaskId,
4443
+ error: extended.error,
4444
+ hint: extended.hint,
4445
+ };
4446
+ }
4447
+ extension = extended;
4448
+ }
4449
+ if (!statusRequested) {
4450
+ if (hasTimeNotice)
4451
+ recordTimeNotice(record, subtaskId, timeNoticeArg);
4452
+ /*
4453
+ * 纯时限事务到此结束。方案 §2.2 效果 3:状态行 revision +1(延期/预告也是
4454
+ * 行变更,同样受 STALE_WRITE 乐观锁保护);状态与判定一个字段都不改。
4455
+ */
4456
+ const row = record.statuses.find((item) => item?.subtaskId === subtaskId);
4457
+ if (row) {
4458
+ row.revision = Number(current?.revision ?? 0) + 1;
4459
+ row.updatedBy = 'agent';
4460
+ }
4461
+ record.updatedAt = Date.now();
4462
+ const snapshot = derivePlanSnapshot(record.statuses);
4463
+ const written = snapshot.statuses.find((item) => item.subtaskId === subtaskId);
4464
+ const readiness = readinessOf(record, snapshot);
4465
+ return {
4466
+ ok: true,
4467
+ planId: record.plan.planId,
4468
+ subtaskId,
4469
+ status: written?.status ?? current?.status ?? null,
4470
+ revision: written?.revision ?? Number(current?.revision ?? 0),
4471
+ updatedBy: written?.updatedBy ?? 'agent',
4472
+ ...(extension
4473
+ ? {
4474
+ deadlineAt: extension.deadlineAt,
4475
+ timerRearmed: extension.timerRearmed,
4476
+ watchdogRearmed: extension.watchdogRearmed,
4477
+ }
4478
+ : {}),
4479
+ ...(hasTimeNotice ? { timeNotice: written?.timeNotice ?? null } : {}),
4480
+ timeJournal: Array.isArray(written?.timeJournal) ? written.timeJournal.slice(-10) : [],
4481
+ stats: snapshot.stats,
4482
+ deliveryReady: readiness.ready,
4483
+ deliveryBlockers: readiness.blockers.slice(0, 12),
4484
+ deliveryRemaining: readiness.remaining.slice(0, 20),
4485
+ hint: '时限协商已记录:状态与判定未改,不需要 force;放宽永远有界,超出累计上限请转新轮续跑或转 escalate 请主 Agent 裁决。',
4486
+ };
4487
+ }
3240
4488
  const revision = Number(current?.revision ?? 0) + 1;
3241
4489
  /*
3242
4490
  * [1.8.13] A manual verdict can carry structured evidence.
@@ -3273,6 +4521,12 @@ export function createWorkplanRuntime(ctx, options = {}) {
3273
4521
  revision,
3274
4522
  updatedBy: 'agent',
3275
4523
  });
4524
+ /*
4525
+ * [2.2.0][T5/O-4c] 带 status 的调用同时带 timeNotice 时,预告记录在改判落行
4526
+ * 之后写入:applyStatus 抛错(如非法 verification)时不会留下半写的预告。
4527
+ */
4528
+ if (hasTimeNotice)
4529
+ recordTimeNotice(record, subtaskId, timeNoticeArg);
3276
4530
  if (status === 'blocked') {
3277
4531
  record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' });
3278
4532
  }
@@ -3285,7 +4539,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3285
4539
  */
3286
4540
  try {
3287
4541
  const writtenRow = record.statuses.find((item) => item.subtaskId === subtaskId);
3288
- session.append('user/message', buildUpdateMessage({
4542
+ appendUserMessage(session, buildUpdateMessage({
3289
4543
  planId: record.plan.planId,
3290
4544
  subtaskId,
3291
4545
  status,
@@ -3302,7 +4556,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3302
4556
  options: writtenRow?.options,
3303
4557
  instruction: writtenRow?.instruction,
3304
4558
  instructionSeq: writtenRow?.instructionSeq,
3305
- }), { surfaceOp: 'append' });
4559
+ }));
3306
4560
  }
3307
4561
  catch (error) {
3308
4562
  pushRecordError(record, error);
@@ -3422,7 +4676,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3422
4676
  * 「内存里已经改了、刷新后又退回去」的分叉。
3423
4677
  */
3424
4678
  try {
3425
- session.append('user/message', buildReplanMessage(result.payload), { surfaceOp: 'append' });
4679
+ appendUserMessage(session, buildReplanMessage(result.payload));
3426
4680
  }
3427
4681
  catch (error) {
3428
4682
  return {
@@ -3577,7 +4831,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3577
4831
  */
3578
4832
  const appendCancelRecord = () => {
3579
4833
  try {
3580
- session.append('user/message', cancelMessage, { surfaceOp: 'append' });
4834
+ appendUserMessage(session, cancelMessage);
3581
4835
  record.cancelRecorded = true;
3582
4836
  record.cancelReason = reason;
3583
4837
  return true;
@@ -3843,8 +5097,11 @@ export function createWorkplanRuntime(ctx, options = {}) {
3843
5097
  book.doneBefore = Number(live.stats?.done ?? 0);
3844
5098
  record.dispatchPromise = dispatchPlan(ctx, record, {
3845
5099
  ...base,
5100
+ // [2.2.0][T6/O-1a] 自动续跑同样在后台执行:保持完成即时通知。
5101
+ notifyCompletion: true,
3846
5102
  signal: controller.signal,
3847
- childTimeoutMs: limits.childTimeoutMs,
5103
+ // [2.2.0][T4/O-3b] 传原始配置值:未配置=undefined 时协商派生生效,显式配置=兜底上限(resolveSubtaskTimeoutMs)。
5104
+ childTimeoutMs: options.childTimeoutMs,
3848
5105
  idleTimeoutMs: limits.idleTimeoutMs,
3849
5106
  totalTimeoutMs: limits.totalTimeoutMs,
3850
5107
  maxResumes: limits.maxResumes,
@@ -3888,12 +5145,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
3888
5145
  * `closure:'reported'` + `report{state,at,ref,turn}`,与左侧栏 chip 同源。
3889
5146
  * 返回本次新标记的条数;已是 reported 的行不重复写,避免每轮刷新 revision。
3890
5147
  */
3891
- function markReported(record, session, ref) {
5148
+ function markReported(record, session, ref, onlySubtaskId) {
3892
5149
  const at = Date.now();
3893
5150
  const rawTurn = Number(state.activeTurns?.get?.(session?.id) ?? NaN);
3894
5151
  const turn = Number.isFinite(rawTurn) ? rawTurn : null;
3895
5152
  let changed = 0;
3896
5153
  for (const item of Array.isArray(record?.statuses) ? record.statuses : []) {
5154
+ /*
5155
+ * [2.2.0][T6/O-1a] 即时通知只标记「刚结算的这一条」;finishRound 批量
5156
+ * 补齐不传 onlySubtaskId,保持原有「所有 done 未回报行」语义。
5157
+ */
5158
+ if (onlySubtaskId !== undefined && String(item?.subtaskId) !== String(onlySubtaskId))
5159
+ continue;
3897
5160
  if (item?.status !== 'done')
3898
5161
  continue;
3899
5162
  if (item?.closure === 'reported' && item?.report?.state === 'sent')
@@ -3915,6 +5178,49 @@ export function createWorkplanRuntime(ctx, options = {}) {
3915
5178
  }
3916
5179
  return changed;
3917
5180
  }
5181
+ /**
5182
+ * [2.2.0][T6/O-1a] 完成即时通知的插件兜底投递器(后台轮次专用)。
5183
+ *
5184
+ * 方案 §2.3 双通道:①协议通道由子 Agent 完成即 `send_message`;②兜底通道
5185
+ * 由这里在 `settleFromOutput` 结算成功后立刻写一条纯文本 `user/message`
5186
+ * (含子任务 ID、摘要、验收计数、用时),不等待整轮结束。消息不带任何
5187
+ * workplan 标记,回放解析器按未知消息跳过(A2:回放是纯读)。
5188
+ *
5189
+ * 幂等:同一子任务已有 `closure:'reported'` + `report.state:'sent'` 时直接
5190
+ * 跳过——重复结算、finishRound 轮级批量补齐都不得重报。先写通知、后记
5191
+ * 回报:写失败只置 reportPending,交结果消息补齐(绝不留无证据已回报)。
5192
+ */
5193
+ function emitSubtaskDoneNotice(record, session, subtask, verdict) {
5194
+ if (!record || !session || typeof session.append !== 'function')
5195
+ return;
5196
+ const row = Array.isArray(record.statuses)
5197
+ ? record.statuses.find((item) => item?.subtaskId === subtask?.id)
5198
+ : null;
5199
+ if (row?.closure === 'reported' && row?.report?.state === 'sent')
5200
+ return;
5201
+ const acceptance = Array.isArray(verdict?.acceptance) ? verdict.acceptance : [];
5202
+ const passed = acceptance.filter((item) => item?.result === 'pass').length;
5203
+ const acceptanceCount = acceptance.length > 0
5204
+ ? `验收 ${passed}/${acceptance.length} 通过`
5205
+ : '验收记录 0 条(legacy 未提供结构化验收)';
5206
+ const elapsedMs = Number.isFinite(Number(row?.startedAt))
5207
+ ? Math.max(0, Date.now() - Number(row.startedAt))
5208
+ : 0;
5209
+ const elapsed = elapsedMs < 1000 ? `${elapsedMs}ms` : `${(elapsedMs / 1000).toFixed(1)}s`;
5210
+ const summary = truncate(String(row?.summary ?? '').replace(/\s+/g, ' ').trim(), 160) || '(无摘要)';
5211
+ const text = `[dsh-workplan] 子任务 ${String(subtask?.id ?? '')} 已完成并结算:${summary};${acceptanceCount};用时 ${elapsed}`;
5212
+ try {
5213
+ appendUserMessage(session, text);
5214
+ }
5215
+ catch (error) {
5216
+ ctx.logger?.warn?.(`dsh-workplan: 完成即时通知写入失败 ${String(subtask?.id ?? '')}:`
5217
+ + `${error instanceof Error ? error.message : String(error)}`);
5218
+ record.reportPending = true;
5219
+ return;
5220
+ }
5221
+ const ref = `${record?.plan?.planId ?? 'plan'}:${record?.dispatchedAt ?? 0}`;
5222
+ markReported(record, session, ref, subtask?.id);
5223
+ }
3918
5224
  function finishRound(record, session) {
3919
5225
  const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`;
3920
5226
  if (!record.resultWritten) {
@@ -3931,7 +5237,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3931
5237
  const reported = markReported(record, session, ref);
3932
5238
  const resultMessage = buildRoundResult(record, session.id, limits);
3933
5239
  try {
3934
- session.append('user/message', resultMessage, { surfaceOp: 'append' });
5240
+ appendUserMessage(session, resultMessage);
3935
5241
  record.resultWritten = true;
3936
5242
  record.reportPending = needReport > 0 && reported < needReport;
3937
5243
  }
@@ -4066,6 +5372,15 @@ export function createWorkplanRuntime(ctx, options = {}) {
4066
5372
  version: pluginVersion,
4067
5373
  runtime: runtimeIdentity(),
4068
5374
  planId: record.plan.planId,
5375
+ /*
5376
+ * [2.2.2][D5] 规划器档位遥测进入模型可读面。
5377
+ *
5378
+ * 之前只写进内存 record / 失败降级消息;成功计划没有可复核的
5379
+ * planner reasoningEffort 证据,D5 只能 CONDITIONAL。现在 status
5380
+ * 返回 provider/model/reasoningEffort/source/outcome/at,便于在
5381
+ * 真实运行态核对“规划器未继承主 Agent”。
5382
+ */
5383
+ planner: record.planner ?? null,
4069
5384
  running,
4070
5385
  phase: record.phase,
4071
5386
  elapsedMs: record.dispatchStartedAt ? Date.now() - record.dispatchStartedAt : null,
@@ -4297,13 +5612,14 @@ export function createWorkplanRuntime(ctx, options = {}) {
4297
5612
  message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待主 Agent 指示。',
4298
5613
  };
4299
5614
  }
5615
+ // [2.2.6][T4] 同模式共犯(T1 W4):对象感知读取,消灭 String(对象) 分支。
4300
5616
  const options = (Array.isArray(args?.options) ? args.options : [])
4301
5617
  .slice(0, MAX_ESCALATION_OPTIONS)
4302
- .map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
5618
+ .map((item) => truncate(needEntryText(item), 300))
4303
5619
  .filter(Boolean);
4304
5620
  const needs = (Array.isArray(args?.needs) ? args.needs : [])
4305
5621
  .slice(0, 10)
4306
- .map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
5622
+ .map((item) => truncate(needEntryText(item), 300))
4307
5623
  .filter(Boolean);
4308
5624
  const now = Date.now();
4309
5625
  const revision = Number(row.revision ?? 0) + 1;
@@ -4327,7 +5643,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4327
5643
  try {
4328
5644
  const parent = ctx.sessions?.get?.(parentId);
4329
5645
  const written = record.statuses.find((item) => item?.subtaskId === row.subtaskId);
4330
- parent?.append?.('user/message', buildUpdateMessage({
5646
+ appendUserMessage(parent, buildUpdateMessage({
4331
5647
  planId: record.plan.planId,
4332
5648
  subtaskId: row.subtaskId,
4333
5649
  status: 'blocked',
@@ -4339,7 +5655,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4339
5655
  escalatedAt: now,
4340
5656
  escalationSeq: revision,
4341
5657
  revision,
4342
- }), { surfaceOp: 'append' });
5658
+ }));
4343
5659
  }
4344
5660
  catch (error) {
4345
5661
  pushRecordError(record, error);
@@ -4571,7 +5887,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4571
5887
  record.updatedAt = now;
4572
5888
  try {
4573
5889
  const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
4574
- session.append('user/message', buildUpdateMessage({
5890
+ appendUserMessage(session, buildUpdateMessage({
4575
5891
  planId: record.plan.planId,
4576
5892
  subtaskId,
4577
5893
  status: 'in_progress',
@@ -4579,7 +5895,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4579
5895
  instruction: written?.instruction,
4580
5896
  instructionSeq: revision,
4581
5897
  revision,
4582
- }), { surfaceOp: 'append' });
5898
+ }));
4583
5899
  }
4584
5900
  catch (error) {
4585
5901
  pushRecordError(record, error);
@@ -4697,13 +6013,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
4697
6013
  });
4698
6014
  record.updatedAt = Date.now();
4699
6015
  try {
4700
- session.append('user/message', buildUpdateMessage({
6016
+ appendUserMessage(session, buildUpdateMessage({
4701
6017
  planId: record.plan.planId,
4702
6018
  subtaskId,
4703
6019
  status: row.status,
4704
6020
  handoffs,
4705
6021
  revision,
4706
- }), { surfaceOp: 'append' });
6022
+ }));
4707
6023
  }
4708
6024
  catch (error) {
4709
6025
  pushRecordError(record, error);
@@ -4850,7 +6166,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4850
6166
  * A wedged promise keeps the old stale escape hatch (see below).
4851
6167
  */
4852
6168
  const startedAt = Number(record.dispatchStartedAt ?? 0);
4853
- const staleAfter = limits.totalTimeoutMs + 120000;
6169
+ const staleAfter = limits.totalTimeoutMs > 0 ? limits.totalTimeoutMs + 120000 : NO_ROUND_BUDGET_MS + 120000;
4854
6170
  if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
4855
6171
  try {
4856
6172
  await record.dispatchPromise;
@@ -4874,7 +6190,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4874
6190
  * stops claiming the plan is running and hands the work back instead.
4875
6191
  */
4876
6192
  const startedAt = Number(record.dispatchStartedAt ?? 0);
4877
- const staleAfter = limits.totalTimeoutMs + 120000;
6193
+ const staleAfter = limits.totalTimeoutMs > 0 ? limits.totalTimeoutMs + 120000 : NO_ROUND_BUDGET_MS + 120000;
4878
6194
  if (startedAt > 0 && Date.now() - startedAt > staleAfter) {
4879
6195
  return {
4880
6196
  ok: false,
@@ -4957,11 +6273,19 @@ export function createWorkplanRuntime(ctx, options = {}) {
4957
6273
  modelSelection: selection.provider && selection.model ? selection : record.modelSelection,
4958
6274
  cwd: session.header?.cwd ?? options.cwd,
4959
6275
  conversationContext: record.conversationContext ?? '',
6276
+ /*
6277
+ * [2.2.0][T6/O-1a] 只有后台(async)轮次推即时通知:wait 模式主 Agent
6278
+ * 在调用栈内等待,轮级结果消息就是该模式的完成通道,避免同一轮重复
6279
+ * 两条消息;既有的「每轮恰 1 条持久结果消息」断言因此保持不变。
6280
+ */
6281
+ notifyCompletion: mode === 'async',
6282
+ onSubtaskDone: (recordArg, subtask, verdict) => emitSubtaskDoneNotice(recordArg, session, subtask, verdict),
4960
6283
  };
4961
6284
  record.dispatchPromise = dispatchPlan(ctx, record, {
4962
6285
  ...roundOptions,
4963
6286
  signal: dispatchController.signal,
4964
- childTimeoutMs: limits.childTimeoutMs,
6287
+ // [2.2.0][T4/O-3b] 传原始配置值:未配置=undefined 时协商派生生效,显式配置=兜底上限(resolveSubtaskTimeoutMs)。
6288
+ childTimeoutMs: options.childTimeoutMs,
4965
6289
  idleTimeoutMs: limits.idleTimeoutMs,
4966
6290
  totalTimeoutMs: limits.totalTimeoutMs,
4967
6291
  maxResumes: limits.maxResumes,
@@ -5353,7 +6677,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
5353
6677
  ctx.logger?.warn?.(`dsh-workplan: 回合 ${turn} 连续 ${book.count} 次未通过交付就绪,按 B 方案放行但留痕:`
5354
6678
  + `${stuck.stats.done}/${stuck.stats.total},未完成 ${released.join(', ') || '无'}`);
5355
6679
  try {
5356
- session.append('user/message', makeUserMessage([
6680
+ appendUserMessage(session, makeUserMessage([
5357
6681
  `⚠️ 本轮未通过交付就绪检查,已按「放行但留痕」结束(计划 ${record.plan.planId})`,
5358
6682
  `进度 ${stuck.stats.done}/${stuck.stats.total};未完成:${released.join(', ') || '无'}`,
5359
6683
  '本回合的内容不是最终交付;产物若已在盘上,下一回合核验后仍可交付。',
@@ -5361,7 +6685,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
5361
6685
  kind: 'workplan-release',
5362
6686
  form: 'notice',
5363
6687
  summary: `未就绪放行 ${stuck.stats.done}/${stuck.stats.total}`,
5364
- }), { surfaceOp: 'append' });
6688
+ }));
5365
6689
  }
5366
6690
  catch (error) {
5367
6691
  ctx.logger?.warn?.(`dsh-workplan: 放行留痕写入失败:${error instanceof Error ? error.message : String(error)}`);
@@ -6280,6 +7604,51 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6280
7604
  return enterDecision(downstream, [message]);
6281
7605
  }
6282
7606
  let plan;
7607
+ /*
7608
+ * [2.1.6] 规划器遥测的落点:成功写进记录、失败写进降级消息,让「为什么没
7609
+ * 分解成功」不再是一句没有现场的「超时」。
7610
+ */
7611
+ const plannerTelemetry = {};
7612
+ /*
7613
+ * [2.2.5][T5] 分解期间可见性——占位卡片(T1 P-5 / T3 §2 S1、§3 C1)。
7614
+ *
7615
+ * 缺陷:runPlanner 全程(最长 3 次尝试 × 300s 窗口 + 退避)此前零写入,
7616
+ * 用户看到的是「发出去一句话后界面没有任何反应」,无法区分「正在重试」
7617
+ * 与「卡死」(T1 断点层判定=未发出,插件层)。现在进入规划前先放一张
7618
+ * phase:'planning' 的占位记录:侧栏 4 秒轮询只要记录存在就下发(serialisePlan
7619
+ * 对 plan:null 已兜底),卡片徽标走既有词汇「正在安排」(client.ts LOCALE)。
7620
+ * 后续出口不新增路径:成功/降级由下方既有 records.set 整体覆盖;用户中止
7621
+ * 路径由 serialisePlan 的终态收敛(turnEnded → phase:'ended')兜住,不会
7622
+ * 残留假「进行中」。
7623
+ */
7624
+ const planningStartedAt = Date.now();
7625
+ const planningRecord = {
7626
+ planId: null,
7627
+ plan: null,
7628
+ title: '正在生成任务分解…',
7629
+ degraded: false,
7630
+ statuses: [],
7631
+ phase: 'planning',
7632
+ errors: [],
7633
+ createdAt: planningStartedAt,
7634
+ updatedAt: planningStartedAt,
7635
+ createdTurn: payload.turn,
7636
+ };
7637
+ state.records.set(session.id, planningRecord);
7638
+ /*
7639
+ * [2.2.5][T5] 进度回调落点(T1 P-6 / T3 §3 C2/C3、§4 频率规则):
7640
+ * 通道 A = 占位卡片 errors 区追加重试摘要(≤2 行,保底通道);通道 B =
7641
+ * appendUserMessage 通知(仅「会退避重试」的失败发,≤2 条,aborted 静默)。
7642
+ * 文案组装与频率硬规则全部在 createPlannerProgressReporter / plannerProgressLines
7643
+ * (plan.ts,可独立回归);这里只注入宿主交互面。
7644
+ */
7645
+ const onPlannerProgress = createPlannerProgressReporter({
7646
+ signal: payload.signal,
7647
+ record: planningRecord,
7648
+ setRecord: (record) => state.records.set(session.id, record),
7649
+ appendNotice: (text) => appendUserMessage(session, text),
7650
+ maxAttempts: PLANNER_MAX_ATTEMPTS,
7651
+ });
6283
7652
  try {
6284
7653
  plan = await runPlanner(ctx, {
6285
7654
  taskText,
@@ -6287,7 +7656,11 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6287
7656
  sessionId: session.id,
6288
7657
  modelSelection,
6289
7658
  signal: payload.signal,
6290
- plannerTimeoutMs: Number(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs ?? PLANNER_TIMEOUT_MS),
7659
+ plannerTimeoutMs: normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
7660
+ plannerIdleTimeoutMs: normalisePlannerWindow(options?.limits?.plannerIdleTimeoutMs ?? options?.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
7661
+ telemetry: plannerTelemetry,
7662
+ // [2.2.5][T5] 分解期间进度事件(T1 P-6):只追加观察回调,不改重试语义。
7663
+ onProgress: onPlannerProgress,
6291
7664
  conversationContext,
6292
7665
  sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
6293
7666
  /*
@@ -6297,7 +7670,9 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6297
7670
  * and asks for `estimateMinutes` on every subtask.
6298
7671
  */
6299
7672
  budget: {
6300
- totalMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
7673
+ totalMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
7674
+ ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
7675
+ : 0,
6301
7676
  childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
6302
7677
  concurrency: MAX_CONCURRENT,
6303
7678
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
@@ -6305,8 +7680,17 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6305
7680
  });
6306
7681
  }
6307
7682
  catch (error) {
6308
- if (payload.signal.aborted)
7683
+ if (payload.signal.aborted) {
7684
+ /*
7685
+ * [2.2.5][T5] 用户中止:静默退出(T3 §2 中止分支,不发通知)。占位卡片
7686
+ * 若本轮前无旧记录,交给 serialisePlan 终态收敛转 'ended',不留假
7687
+ * 「进行中」;若本轮前已有旧计划记录,恢复它——中止不该把用户上一份
7688
+ * 终态进度从内存里挤掉(旧实现中止路径不写记录,此行为保持不变)。
7689
+ */
7690
+ if (existing?.plan)
7691
+ state.records.set(session.id, existing);
6309
7692
  return downstream;
7693
+ }
6310
7694
  const planId = `wp-${randomUUID()}`;
6311
7695
  const createdAt = Date.now();
6312
7696
  const message = buildDegradedMessage({
@@ -6315,6 +7699,7 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6315
7699
  createdTurn: payload.turn,
6316
7700
  createdAt,
6317
7701
  error: error instanceof Error ? error.message : String(error),
7702
+ detail: plannerTelemetryLine(plannerTelemetry),
6318
7703
  taskText,
6319
7704
  });
6320
7705
  state.records.set(session.id, {
@@ -6323,6 +7708,7 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6323
7708
  title: '自动分解降级',
6324
7709
  degraded: true,
6325
7710
  error: error instanceof Error ? error.message : String(error),
7711
+ planner: { ...plannerTelemetry, at: createdAt },
6326
7712
  statuses: [],
6327
7713
  phase: 'degraded',
6328
7714
  errors: [truncate(error instanceof Error ? error.message : String(error), 1000)],
@@ -6332,8 +7718,12 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6332
7718
  });
6333
7719
  return enterDecision(downstream, [message]);
6334
7720
  }
6335
- if (payload.signal.aborted)
7721
+ if (payload.signal.aborted) {
7722
+ // [2.2.5][T5] 计划已生成但回合被中止:同中止分支,恢复旧记录再静默退出。
7723
+ if (existing?.plan)
7724
+ state.records.set(session.id, existing);
6336
7725
  return downstream;
7726
+ }
6337
7727
  const planId = `wp-${randomUUID()}`;
6338
7728
  const createdAt = Date.now();
6339
7729
  const fullPlan = attachPlanMeta(plan, {
@@ -6348,6 +7738,9 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6348
7738
  statuses: createStatuses(fullPlan),
6349
7739
  phase: 'pending',
6350
7740
  errors: [],
7741
+ // [2.1.6] 规划这一步花了多久、用的哪个模型:成功也留痕,失败才好对比。
7742
+ // [2.1.7] 抢救成功的计划保留 SALVAGED 判定,别被 'ok' 覆盖——它是复盘的关键证据。
7743
+ planner: { ...plannerTelemetry, outcome: plannerTelemetry.outcome === 'SALVAGED' ? 'SALVAGED' : 'ok', at: createdAt },
6351
7744
  createdAt,
6352
7745
  updatedAt: createdAt,
6353
7746
  dispatchedAt: null,
@@ -6380,7 +7773,9 @@ async function maybePlan(ctx, state, payload, downstream, options) {
6380
7773
  * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
6381
7774
  */
6382
7775
  const planMessage = buildPlanMessage(fullPlan, {
6383
- totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
7776
+ totalBudgetMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
7777
+ ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
7778
+ : 0,
6384
7779
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
6385
7780
  planMode,
6386
7781
  autoDispatched,
@@ -6506,6 +7901,7 @@ export function statusToolOutputSchema() {
6506
7901
  // [1.8.14] Loaded-build identity: version alone cannot prove which bytes
6507
7902
  // the process is running after a rebuild or a profile recomposition.
6508
7903
  runtime: { type: 'object' },
7904
+ planner: { oneOf: [{ type: 'object' }, { type: 'null' }] },
6509
7905
  deliveryReady: { type: 'boolean' },
6510
7906
  deliveryBlockers: { type: 'array' },
6511
7907
  deliveryRemaining: { type: 'array' },