dsh-workplan 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime.ts CHANGED
@@ -124,7 +124,6 @@ import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
124
124
  // [SCv2-T4] 判据层单一真源(用户 2026-11-13 裁决 B/B/B/B/A/A/B):生效边界 D-1、
125
125
  // 例外批准 Q1-B、结算三选一 §3.5、单次墙钟 Q6-A、事前聚合 Q4-B。运行层常量不改。
126
126
  import {
127
- CRITERION_TARGET_MINUTES,
128
127
  appendCriterionViolation,
129
128
  attemptWallClockMsOf,
130
129
  criterionExAnte,
@@ -161,6 +160,19 @@ import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js
161
160
  import { supersedePlanRecord } from './supersede.js'
162
161
  import { createProgressWatchdog, describeError } from './watchdog.js'
163
162
  import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume, liveResumeCounts } from './auto-resume.js'
163
+ /*
164
+ * [3.0.1] 认可闸门 + 死锁自愈(approval-gate.ts):
165
+ * detectApprovalGate —— 任务锚点里的「先经认可再执行」门槛语识别
166
+ * approvalGateDetectionDisabled —— DSH_WORKPLAN_APPROVAL_GATE=0 总开关
167
+ * isDispatchHeld —— 计划是否被按住不得派发
168
+ * buildChildRevivePatch —— escalated 行子会话失联时的复活补丁(纯函数)
169
+ */
170
+ import {
171
+ approvalGateDetectionDisabled,
172
+ buildChildRevivePatch,
173
+ detectApprovalGate,
174
+ isDispatchHeld,
175
+ } from './approval-gate.js'
164
176
  import {
165
177
  applyReplanStatuses,
166
178
  buildChangeRequestMessage,
@@ -237,6 +249,112 @@ function liveStatuses(statuses: any) {
237
249
  * `deriveReportPending(record)`:事实只有 statuses(经 T2 单调闸的终态),
238
250
  * 标志降级为审计镜像。blocked/pending 行不是 done,永不触发该阻塞。
239
251
  */
252
+ /*
253
+ * [3.0.1][P0 冲突修复] 跨版本兼容的「continuable 中断」。
254
+ *
255
+ * DSH 0.2.2-rc.3 起旧 API `subagents.interruptByParent(childId, parentId,
256
+ * 'continuable')` 已被 `subagents.interrupt(targetSessionId, authority)`
257
+ * 取代(dsh-subagent/src/manager.ts):authority = { kind:'ancestor', agent }
258
+ * 携带中断方的**活体 Agent 对象**(必须是目标会话祖先树内的活体 Agent,
259
+ * 否则宿主抛 UNAUTHORIZED)。新 API 的 local 分支语义与旧 'continuable'
260
+ * 完全等价:agent.cancel({ kind:'parent' }, { keepInbox:true }) —— 中断
261
+ * 当前回合但保留收件箱,可被后续接续重新驱动。
262
+ *
263
+ * 策略:优先新 API;宿主为旧版本时回退旧 API(保留旧测试夹具与旧宿主
264
+ * 可用性);两者皆无或 authority 不成立时返回 false(与修复前静默跳过
265
+ * 同口径,调用方均有接续兜底,绝不因中断失败阻断主链路)。
266
+ */
267
+ export function interruptChildContinuable(
268
+ subagents: any,
269
+ childSessionId: string,
270
+ ancestorAgent: any,
271
+ ancestorIdFallback?: string,
272
+ ): boolean {
273
+ if (subagents == null || typeof childSessionId !== 'string' || childSessionId.length === 0) return false
274
+ try {
275
+ if (typeof subagents.interrupt === 'function') {
276
+ // 新 API 要求 authority.agent 是目标会话祖先的活体 Agent 对象。
277
+ if (ancestorAgent == null || typeof ancestorAgent !== 'object') return false
278
+ subagents.interrupt(childSessionId, { kind: 'ancestor', agent: ancestorAgent })
279
+ return true
280
+ }
281
+ // 旧版宿主(DSH < 0.2.2-rc.3)回退:interruptByParent(childId, parentId, 'continuable')。
282
+ // ancestorAgent 无 string id(旧测试夹具的裸 stub)时退用调用方提供的祖先会话 id。
283
+ if (typeof subagents.interruptByParent === 'function') {
284
+ const ancestorId = typeof ancestorAgent?.id === 'string' && ancestorAgent.id.length > 0
285
+ ? ancestorAgent.id
286
+ : ancestorIdFallback
287
+ if (typeof ancestorId !== 'string' || ancestorId.length === 0) return false
288
+ subagents.interruptByParent(childSessionId, ancestorId, 'continuable')
289
+ return true
290
+ }
291
+ return false
292
+ } catch {
293
+ // 中断失败不阻断接续(沿用原 try/catch 口径):接续由调用方兜底保证。
294
+ return false
295
+ }
296
+ }
297
+
298
+ /*
299
+ * [3.0.1][P1a 冲突修复] 宿主 subagent.maxDepth 设置与本插件三层体系的冲突检测。
300
+ *
301
+ * 宿主设置页「subagent.maxDepth」默认 1,但宿主 manager 的判定是
302
+ * resolveChildDepth(parent, spec.maxDepth):调用方(本插件)显式传了
303
+ * maxDepth:2 时该设置被架空——插件放行 depth 2 成员,其余 subagent 调用方
304
+ * 仍受设置约束。这本身可运行(插件派发按 spec 为准),但用户看到的设置
305
+ * 与实际行为不一致,属于配置矛盾。此处检测「宿主配置值 < 插件要求的最小
306
+ * 深度 2」并生成一次性告警文案(同一 scopeId 只告警一次,避免刷屏);
307
+ * 调用方负责把文案投递给用户可见会话。返回 null = 无冲突或已告警过。
308
+ */
309
+ const depthOverrideWarnedScopes = new Set<string>()
310
+ export function detectDepthOverrideConflict(subagents: any, scopeId: string | null | undefined): string | null {
311
+ if (typeof scopeId !== 'string' || scopeId.length === 0) return null
312
+ if (depthOverrideWarnedScopes.has(scopeId)) return null
313
+ let configured: unknown
314
+ try {
315
+ configured = typeof subagents?.resolveMaxDepth === 'function' ? subagents.resolveMaxDepth() : undefined
316
+ } catch {
317
+ return null
318
+ }
319
+ // 未配置 / 无限深度 / 已 ≥2:无冲突。
320
+ if (typeof configured !== 'number' || !Number.isFinite(configured) || configured >= 2) return null
321
+ depthOverrideWarnedScopes.add(scopeId)
322
+ return `【dsh-workplan·深度设置说明】检测到设置页「子代理最大深度」(subagent.maxDepth)当前为 ${configured}。该上限**只约束内置 subagent/subagent_fork 工具**;本插件的三层体系(你 → 部门负责人 → 专家)按派发契约固定需要第 2 层深度,宿主对该契约单独放行,不受此设置影响——这是设计使然,你的负责人派发给专家的流程在任何设置下都正常工作。若你的意图是「完全禁止子代理」,请直接停用本插件;若只是想让设置页显示与插件行为一致,可把该设置调到 2(立即生效,重启后恢复默认 1)。`
323
+ }
324
+
325
+ // 检测并把冲突告警投递到指定会话(best-effort:任何失败不阻断派发主链路)。
326
+ function notifyDepthOverrideConflict(ctx: any, scopeId: string | null | undefined): void {
327
+ const text = detectDepthOverrideConflict((ctx as any)?.subagents, scopeId)
328
+ if (!text) return
329
+ try {
330
+ const session = (ctx as any)?.sessions?.get?.(scopeId)
331
+ appendUserMessage(session, text)
332
+ } catch {
333
+ /* 告警投递失败不影响派发 */
334
+ }
335
+ }
336
+
337
+ /*
338
+ * [3.0.1][P1b 冲突修复] 宿主子代理并发上限错误的友好翻译。
339
+ *
340
+ * 宿主对超过 subagent.maxActiveSubagents(默认 8,按会话树共享)的派发抛
341
+ * SubagentError(code='ACTIVATION_LIMIT_REACHED', message="subagent limit
342
+ * reached (active child limit: N)")。原样透出会让用户看到英文宿主错误且
343
+ * 无从行动;此处翻译为可行动的中文提示(重试 / 调大设置)。非该错误时
344
+ * 原样返回传入错误(不吞错、不改类型),由调用方决定如何包装。
345
+ */
346
+ export function describeSubagentActivationError(error: any, context: string): Error {
347
+ const code = String(error?.code ?? '')
348
+ const raw = String(error?.message ?? error ?? '')
349
+ if (code === 'ACTIVATION_LIMIT_REACHED' || /limit reached/i.test(raw)) {
350
+ return new PlanError(
351
+ `${context}:子代理并发数已达宿主上限(设置项 subagent.maxActiveSubagents,整个会话树共享)。请稍后重试(让在跑的任务先完成),或在「设置 → 子代理」中调大该上限。`,
352
+ 'ACTIVATION_LIMIT_REACHED',
353
+ )
354
+ }
355
+ return error instanceof Error ? error : new Error(raw || String(error))
356
+ }
357
+
240
358
  export function deriveReportPending(record: any): boolean {
241
359
  const statuses = Array.isArray(record?.statuses) ? record.statuses : []
242
360
  /*
@@ -392,69 +510,36 @@ export async function resolveSupportedEfforts(
392
510
  return null
393
511
  }
394
512
  }
395
- /**
396
- * Absolute ceiling for one child execution.
397
- *
398
- * 300 000 ms used to be the *only* limit, and because it was purely a wall
399
- * clock it killed healthy work: a child that needed one more minute was
400
- * recorded as blocked, `markDependentsBlocked` blocked every dependent, and the
401
- * plan became terminal at the first slow subtask. The ceiling is now a
402
- * settlement guarantee, while the no-progress window below is what normally
403
- * ends an attempt.
404
- *
405
- * [2.2.0][T4/O-3b] 语义更新(柔性时长协商,方案 §1③/§2.2):这不是固定交付
406
- * 期限,而是「协商上限+L4 安全兜底」——单次执行时限协商而来(subtask.timeoutMs
407
- * 显式值优先,缺省 deriveSubtaskTimeoutMs(estimateMinutes)=clamp(预估分钟×
408
- * 2.0×60000, MIN, MAX)),本常量只在无预估、无显式值时兜底(③C2 零回归)。
409
- * 时间是协商出来的安全兜底,不是固定交付期限:到点走 L4 安全兜底结算+
410
- * 「待裁决」标记(延期 / 重试 / 接受),不表述为「强制结束」式固定期限误杀。
513
+ /*
514
+ * [3.0.1] 历史时间常量,仅供旧数据回放、纯函数审计与兼容测试读取。
411
515
  *
412
- * [2.6.0][Q1-B/Q7-B] 分层:判据层完成目标 ≤10 分钟(默认必须达成,超出须用户
413
- * 明确批准并留痕);本条协商上限属运行层安全兜底,数值与公式一律不变,且不构成
414
- * 「允许慢」的许可。「延期(extendMs)」不再是主 Agent 单方可为——须先取得用户
415
- * 批准留痕(任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=
416
- * 未批准),未批准时按判据层未达标处理(不 done、转接替子任务)。
516
+ * 生产执行不再调用 resolveSubtaskTimeoutMs,也不会用这些值创建计时器。
517
+ * 部门负责人和全球顶尖专家的正式执行没有墙钟、空闲、回执或整轮截止;
518
+ * timeoutMs / extendMs 即使出现在旧计划中也不会重新生效。保留数值是为了
519
+ * 让旧计划、旧日志和旧测试仍能解释当时发生的事,而不是允许重新启用限制。
417
520
  */
418
521
  export const CHILD_TIMEOUT_MS = 900000
419
- /** No-progress window: the child's own session log stopped growing. */
420
522
  export const CHILD_IDLE_TIMEOUT_MS = 300000
421
- /*
422
- * Floors exist to reject zero, negative and absurdly small values, not to
423
- * overrule an operator. The defaults above are what production uses; a floor of
424
- * 1s keeps diagnostics and tests able to exercise the timers without waiting
425
- * minutes.
426
- */
427
523
  export const MIN_CHILD_TIMEOUT_MS = 1000
428
- /*
429
- * [2.2.0][T4/O-3b] 单次绝对上限 1800000 → 7200000(120 分钟):用户 2026-11-07
430
- * 决断(方案 §6 未知第 4 条)。协商上限 = clamp(预估分钟 × 2.0, 全局下限,
431
- * 单次绝对上限)(方案 §1③),2h 让「预告 60 分钟的子任务,其单次执行上限
432
- * ≥ 60 分钟」(方案 C1)成立;tests/time-estimate-negotiation.test.ts 的
433
- * expected 公式直接引用本常量,数值不同步会红灯。
434
- *
435
- * [2.6.0][Q7-B] 分层声明:120 分钟是运行层安全兜底(防失控),不是时长许可;
436
- * 判据层完成目标为 ≤10 分钟(Q1/Q4),两层互不取代,数值与公式零改动。
437
- */
438
524
  export const MAX_CHILD_TIMEOUT_MS = 7200000
439
525
  export const MIN_CHILD_IDLE_MS = 1000
440
526
  export const MAX_CHILD_IDLE_MS = 900000
441
527
  export const CHILD_POLL_MS = 2000
442
528
  /*
443
- * [1.11.0] 派发回执的两个窗口(T4 B1/B2)。
529
+ * [3.0.1] 派发回执只剩提示,没有硬截止。
444
530
  *
445
- * `assigned` 只是「已交给子会话」,不等于「子会话已经动了」。收不到回执时
446
- * 静默等到空闲窗口(默认 300s)会把「根本没启动」和「在慢慢想」混为一谈:
447
- * 90s 先标记 ackOverdue 让看板可见,180s 仍无任何新事件就按 no-ack 收束,
448
- * 不再无限等待。
531
+ * 90s 后仍未观察到子会话新事件时标记 ackOverdue,供看板提示和主 Agent 跟进;
532
+ * 该标记不会 blocked、中止、换人或拒绝 done。ASSIGN_ACK_DEADLINE_MS 仅为
533
+ * 旧脚本/测试保留的历史值,生产路径不再读取。
449
534
  */
450
535
  export const ASSIGN_ACK_NOTICE_MS = 90000
451
536
  export const ASSIGN_ACK_DEADLINE_MS = 180000
452
537
  /*
453
- * [1.11.0] 指示回执的两个窗口(T4 B5)。
538
+ * [3.0.1] 指示回执只剩提示,没有硬截止。
454
539
  *
455
- * `instructed` 只表示「指示已经写进状态行并投递」,不表示子 Agent 已经照做。
456
540
  * 60s 没有新事件先标 `instructionOverdue`(看板可见、主 Agent 可催),
457
- * 180s 仍无增长就按 no-ack 收束,避免「指示已下、那边根本没跑」无限挂起。
541
+ * 但不因缺少回执收束、阻断或换人;真正结果、真实错误或用户取消才结束。
542
+ * INSTRUCTION_ACK_DEADLINE_MS 仅为旧脚本/测试保留,生产路径不再读取。
458
543
  */
459
544
  export const INSTRUCTION_ACK_NOTICE_MS = 60000
460
545
  export const INSTRUCTION_ACK_DEADLINE_MS = 180000
@@ -463,23 +548,12 @@ export const INSTRUCTION_ACK_DEADLINE_MS = 180000
463
548
  * 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
464
549
  */
465
550
  export const INSTRUCTION_POLL_MS = 5000
466
- // [2.2.5][RoundBudget] 轮次总预算默认关闭。
467
- //
468
- // 用户要求:对子任务的执行时间不做强制限制,只通过开工预告/预估/协商/延期
469
- // 与到点预警来治理;旧版默认 20 分钟会在子任务自己的 30 分钟协商截止前
470
- // 先切断整轮,界面上出现“本轮预算用尽”,与上述目标矛盾。
471
- //
472
- // 现在:
473
- // - TOTAL_TIMEOUT_MS = 0 表示默认不设整轮硬预算;
474
- // - 显式传正数(配置/DSH_WORKPLAN_TOTAL_TIMEOUT_MS)仍可启用安全兜底;
475
- // - 子任务自己的 timeoutMs/deadlineAt/extendMs 不受影响。
476
- // dispatchPlan 用 20 天哨兵值避免 Infinity 参与计时器/差值计算。
551
+ // [3.0.1] 整轮预算已停用。
477
552
  //
478
- // [2.2.5][热修] 哨兵值不能超过 Node setTimeout 的上限:延时 > 2^31-1 毫秒
479
- // (约 24.8 天)会被 Node 强制改成 1 毫秒并告警(TimeoutOverflowWarning)。
480
- // 最初版本用 10 年,结果整轮定时器派发后 1ms 就触发,所有子任务瞬间被
481
- // 「总执行超时」杀死(2026-11-08 17:36 / 18:01 两次现场实锤,38ms 与 8ms)。
482
- // 20 天 = 1,728,000,000ms < 2^31-1,安全;且对单轮执行而言等价于“无预算”。
553
+ // dispatchPlan 的 deadline 恒为 Infinity,不再创建 totalTimer;显式配置
554
+ // DSH_WORKPLAN_TOTAL_TIMEOUT_MS 或旧 totalTimeoutMs 也不会中止任何负责人/
555
+ // 专家,或产生“预算用尽/可续跑”。TOTAL_TIMEOUT_MS/NO_ROUND_BUDGET_MS
556
+ // 仅保留给旧记录解释和兼容测试,不代表仍可通过配置重新开启。
483
557
  export const TOTAL_TIMEOUT_MS = 0
484
558
  export const NO_ROUND_BUDGET_MS = 20 * 24 * 60 * 60 * 1000
485
559
  export const ROUND_TIMER_MAX_MS = 2_000_000_000
@@ -2064,7 +2138,7 @@ function resolveLiveAgent(ctx: any, sessionId: any): any {
2064
2138
  }
2065
2139
 
2066
2140
  async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
2067
- const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
2141
+ const { parentSignal, modelSelection, conversationContext = '', child, guard } = options
2068
2142
  /*
2069
2143
  * [2.2.7] 中断即报的目标会话:与 noticeChannel/finaliseNotice 同一取值链,
2070
2144
  * 拿不到就安静跳过(通知是观测设施,不是交付物)。
@@ -2218,31 +2292,21 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2218
2292
  let phaseZeroOutput = ''
2219
2293
  let interruptedFlag = false
2220
2294
  let interruptedEvidence: { artifacts: any[]; missingArtifacts: string[] } | null = null
2295
+ // 仅用于真实错误后的重试策略与日志,不参与 watchdog 或执行截止。
2296
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
2221
2297
  try {
2222
- // [2.2.0][T4/O-3b] 尝试起点与协商截止同一时钟读数(C3 契约:deadlineAt −
2223
- // startedAt 严格等于协商窗口)。deadlineAt 走 StatusEntry 未知字段保留通道
2224
- // 直写:applyStatus(src/plan.ts,T3 领地)无路由分支,patch 会静默丢弃。
2298
+ // 新尝试只记录起点;历史 deadlineAt 不再作为执行指令,也不显示为本轮截止。
2225
2299
  const attemptStartMs = Date.now()
2226
- const attemptWindowMs = Number(options.attemptTimeoutMs ?? 0)
2227
2300
  if (!writeSubtaskStatus(record, subtask.id, {
2228
2301
  status: 'in_progress',
2229
2302
  progress: 5,
2230
2303
  startedAt: attemptStartMs,
2304
+ deadlineAt: null,
2231
2305
  }, guard)) return
2232
- if (Number.isFinite(attemptWindowMs) && attemptWindowMs > 0) {
2233
- const attemptRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
2234
- if (attemptRow) attemptRow.deadlineAt = attemptStartMs + attemptWindowMs
2235
- if (options.attemptHandle) {
2236
- options.attemptHandle.startedAt = attemptStartMs
2237
- options.attemptHandle.deadlineAt = attemptStartMs + attemptWindowMs
2238
- }
2239
- }
2240
2306
 
2241
2307
  for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
2242
- if (guard.timedOut) return
2243
2308
  interruptedEvidence = null
2244
2309
  if (parentSignal.aborted) throw abortError()
2245
- if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
2246
2310
  let activation: any = null
2247
2311
  // Declared outside the try so the per-attempt finally can always cancel
2248
2312
  // the receipt timers, even when activation itself failed.
@@ -2347,7 +2411,10 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2347
2411
  if (!liveAgent) {
2348
2412
  throw new PlanError('派发失败:无法解析活体父 Agent(agent 缺失且 agents 服务兜底失败),fail-closed 不创建子会话', 'AGENT_RESOLUTION_FAILED', { subtaskId: subtask.id })
2349
2413
  }
2350
- activation = await ctx.subagents.startActivation({
2414
+ // [3.0.1][P1a] 宿主 subagent.maxDepth < 2 时一次性告警(不阻断派发)。
2415
+ notifyDepthOverrideConflict(ctx, typeof record?.plan?.sessionId === 'string' ? record.plan.sessionId : null)
2416
+ try {
2417
+ activation = await ctx.subagents.startActivation({
2351
2418
  provider: 'spawn',
2352
2419
  label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
2353
2420
  prompt: [{
@@ -2396,6 +2463,12 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2396
2463
  */
2397
2464
  previousFailure: lastFailure ?? null,
2398
2465
  lessonsBrief,
2466
+ /*
2467
+ * [3.0.1] 死锁自愈:行上登记的复活指示(子会话失联后由
2468
+ * dsh_workplan_instruct 写入)必须随重建的子提示词送达,
2469
+ * 否则新子会话会再请示一遍同一个问题。
2470
+ */
2471
+ reviveInstruction: (record.statuses.find((item: any) => item?.subtaskId === subtask.id)?.reviveInstruction) ?? null,
2399
2472
  /*
2400
2473
  * [2.3.9][T4b] 用户强制要求 3:分配任务时必须把要求 1/2 的
2401
2474
  * **全部内容**告知相关部门。注入文本由 llm-rules.ts 的
@@ -2448,7 +2521,11 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2448
2521
  maxDepth: 2,
2449
2522
  signal: child.controller.signal,
2450
2523
  delivery: 'caller',
2451
- })
2524
+ })
2525
+ } catch (error) {
2526
+ // [3.0.1][P1b] 并发上限翻译为可行动提示;其余错误原样上抛(保持旧行为)。
2527
+ throw describeSubagentActivationError(error, `派发子任务 ${subtask.id}(${subtask.title})`)
2528
+ }
2452
2529
  if (guard.timedOut) return
2453
2530
  if (!activation || typeof activation.result?.then !== 'function') {
2454
2531
  throw new PlanError('子 Agent 没有返回可等待的结果', 'NO_ACTIVATION')
@@ -2511,91 +2588,9 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2511
2588
  // [2.2.9][handle-policy] 卫生类(T1 报告 R7):只丢一次「已下发未响应」提示,保留 unref。
2512
2589
  noticeTimer.unref?.()
2513
2590
  ackTimers.push(noticeTimer)
2514
- /*
2515
- * [1.11.0] 180s 仍无回执 → 明确收束为 no-ack,而不是继续静默等待。
2516
- *
2517
- * 看门狗默认空闲窗口是 300s,而「根本没启动」和「在慢慢想」在日志上
2518
- * 都表现为没有新事件。先把状态写成 blocked + blockedKind:'no-ack',
2519
- * 再中止子会话;主 Agent 因此能立刻看到原因,也能选择续跑。
2520
- */
2521
- const deadlineTimer = setTimeout(() => {
2522
- if (guard.timedOut) return
2523
- const row = attemptRow()
2524
- if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
2525
- const seconds = Math.round(ASSIGN_ACK_DEADLINE_MS / 1000)
2526
- const message = `派发后 ${seconds}s 未收到子 Agent 任何新事件(no-ack)`
2527
- writeSubtaskStatus(record, subtask.id, {
2528
- status: 'blocked',
2529
- closure: 'blocked',
2530
- blockedKind: 'no-ack',
2531
- progress: 100,
2532
- finishedAt: Date.now(),
2533
- ackOverdue: true,
2534
- error: message,
2535
- summary: `未完成:${message}`,
2536
- }, guard)
2537
- recordSubtaskError(record, subtask.id, message, guard)
2538
- // [2.2.7] 中断即报:no-ack 是「根本没启动」,不是「做失败了」。
2539
- announceSubtaskInterrupt(record, interruptSession(), subtask.id,
2540
- `子任务 ${subtask.id}(${subtask.title})${message};性质:子会话疑似根本没启动,不是执行失败;处理:已中止该子会话并把本行置为受阻(blockedKind=no-ack),主会话可决定重新下发指示或放弃该行,其余子任务不受影响。`)
2541
- if (!child.controller.signal.aborted) {
2542
- child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }))
2543
- }
2544
- }, ASSIGN_ACK_DEADLINE_MS)
2545
- // [2.2.9][handle-policy] 收束类(T1 报告 R2):180s no-ack 判定必须真实触发;unref 时
2546
- // 裸循环在判定前排空、行悬死(CI cancelled 红叉根因族)。ack 与收束路径均有 clearAckTimers 清理。
2547
- ackTimers.push(deadlineTimer)
2548
- const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
2549
- // [2.2.0][T4/O-3b][O-4d] 双计时同源(方案 §2.5):看门狗 hardMs 与本次尝试的
2550
- // 协商执行时限同值(options.attemptTimeoutMs,缺省回落旧路径);两者必须同步
2551
- // 推移——延期时 rearmApproachingDeadline 传「自尝试起点计的新完整窗口」。
2552
- const hardTimeoutMs = Number.isFinite(Number(options.attemptTimeoutMs)) && Number(options.attemptTimeoutMs) > 0
2553
- ? Math.min(MAX_CHILD_TIMEOUT_MS, Math.max(MIN_CHILD_TIMEOUT_MS, Number(options.attemptTimeoutMs)))
2554
- : normaliseChildTimeout(options.childTimeoutMs)
2591
+ // 未收到回执只保留 ackOverdue 提示;执行等待没有硬截止,绝不因此 blocked/abort。
2555
2592
  const watchdog = createProgressWatchdog({
2556
- // [2.2.0][T4/O-3b][O-4b] 到点预警接线(T7 watchdog.ts 契约,原样消费):
2557
- // 剩余 ≤ max(timeoutMs×0.2, 120000) 触发一次、同一武装周期幂等、extend 后
2558
- // rearm 可再触发。最小处理器:时间链留档 timeWarning+本轮记录 notice+会话
2559
- // 消息通知主 Agent(格式朴素,T6 波次统一润色)。
2560
- subtaskId: String(subtask.id),
2561
- onApproachingDeadline: (info: any) => {
2562
- if (guard.timedOut) return
2563
- try {
2564
- const warnRow = Array.isArray(record.statuses)
2565
- ? record.statuses.find((item: any) => item?.subtaskId === subtask.id)
2566
- : null
2567
- if (warnRow) {
2568
- // timeWarning 走未知字段通道直写(applyStatus 白名单属 T3 领地)。
2569
- warnRow.timeWarning = {
2570
- at: Date.now(),
2571
- remainingMs: Math.max(0, Number(info?.remainingMs ?? 0)),
2572
- newEstimateMinutes: null,
2573
- channel: 'watchdog',
2574
- }
2575
- }
2576
- const text = `子任务 ${subtask.id} 即将到点:剩余 ${Math.max(0, Math.round(Number(info?.remainingMs ?? 0) / 1000))}s(协商上限 ${Number(info?.timeoutMs ?? 0)}ms);如需继续请尽快决定延期(extendMs),否则到点将按安全兜底结算(待裁决)`
2577
- record.notices = [...(record.notices ?? []), text].slice(-20)
2578
- record.updatedAt = Date.now()
2579
- /*
2580
- * 会话消息只对「有决策余量」的窗口推送:窗口 < 120000ms(=触发规则
2581
- * max(timeoutMs×0.2, 120000) 里的预警下限,生产最小派生窗口恰好
2582
- * 120000ms)只出现在测试小窗场景,预警本身没有可执行的延期决策余量,
2583
- * 此时只留档(record.notices+timeWarning),不推送会话消息——也不与
2584
- * tests/workplan-stuck-recovery.test.ts「session.events 只计持久消息」
2585
- * 的既有断言冲突。T6 波次统一润色通知渠道时再定稿推送策略。
2586
- * [2.2.0][T6/O-1a] 渠道已定稿:与完成即时通知同走主会话
2587
- * `user/message` 纯文本通道(方案 §2.3「即时通知消息」);决策余量
2588
- * 门槛(timeoutMs ≥ 120000,取自触发规则预警下限)保持不变,故
2589
- * 上述断言不受影响。
2590
- */
2591
- if (Number(info?.timeoutMs ?? 0) >= 120000) {
2592
- const warnSession = options.session ?? options.agent?.session
2593
- appendUserMessage(warnSession, text)
2594
- }
2595
- } catch {
2596
- // 预警只做提示不得影响执行:写档失败静默忽略(T6 波次统一润色)。
2597
- }
2598
- },
2593
+ enforceTimeouts: false,
2599
2594
  getSeq: () => {
2600
2595
  try {
2601
2596
  const childSession = ctx.sessions?.get?.(activation.childId)
@@ -2605,24 +2600,13 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2605
2600
  return undefined
2606
2601
  }
2607
2602
  },
2608
- idleMs: idleTimeoutMs,
2609
- hardMs: Math.max(1000, Math.min(hardTimeoutMs, deadline - Date.now())),
2610
- // Poll often enough to notice growth inside a short idle window, but
2611
- // never more than four times per window.
2612
- pollMs: Math.min(CHILD_POLL_MS, Math.max(20, Math.floor(idleTimeoutMs / 4))),
2603
+ idleMs: Number.POSITIVE_INFINITY,
2604
+ hardMs: Number.POSITIVE_INFINITY,
2605
+ pollMs: CHILD_POLL_MS,
2613
2606
  onProgress: ({ now, seq, elapsedMs }: any) => {
2614
- if (guard.timedOut) return
2615
- // Visible liveness: the dashboard can show that a slow subtask is
2616
- // still producing events instead of looking frozen.
2617
2607
  record.heartbeatAt = now
2618
2608
  record.updatedAt = now
2619
- /*
2620
- * [1.11.0] 第一次观察到子会话日志增长 = 回执。
2621
- *
2622
- * 这是唯一能证明「子 Agent 已经在动」的廉价事实:不用它自己的
2623
- * 汇报(可能永远等不到),只看它有没有产生新事件。回执写入后
2624
- * 两个 no-ack 定时器立即撤销,正常的长任务不会被误判。
2625
- */
2609
+ // 子会话日志增长是正向回执;确认后只撤销提示计时器,不设置任何新截止。
2626
2610
  const row = attemptRow()
2627
2611
  if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
2628
2612
  const acked = writeSubtaskStatus(record, subtask.id, {
@@ -2634,24 +2618,16 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2634
2618
  }, guard)
2635
2619
  if (acked) clearAckTimers()
2636
2620
  },
2637
- makeError: (reason: any) => new PlanError(
2638
- reason === 'stalled'
2639
- ? `子任务 ${subtask.id} 无进展超时(${idleTimeoutMs}ms 内子 Agent 没有产生任何新事件)`
2640
- : `子任务 ${subtask.id} 超时(${hardTimeoutMs}ms)`,
2641
- reason === 'stalled' ? 'CHILD_STALLED' : 'CHILD_TIMEOUT',
2642
- { subtaskId: subtask.id },
2643
- ),
2621
+ // 纯观测模式永不调用;保留参数以兼容 watchdog 的公开工厂接口。
2622
+ makeError: () => new PlanError('执行时限已禁用', 'TIME_LIMITS_DISABLED', { subtaskId: subtask.id }),
2644
2623
  })
2645
- // [2.2.0][T4/O-3b][O-4d] 看门狗挂到计时句柄:extendDeadline 延期成功后经
2646
- // watchdog.rearmApproachingDeadline(传新完整窗口)同步推移两处计时。
2647
- options.attemptHandle?.attachWatchdog?.(watchdog)
2648
2624
  let result: any
2649
2625
  try {
2650
2626
  const waiter = waitForActivation(activation, child.controller.signal)
2651
2627
  // The losing side of the race may reject after the watchdog fired;
2652
2628
  // keep that rejection handled so Node never reports it as unhandled.
2653
2629
  waiter.catch(() => {})
2654
- result = await Promise.race([waiter, watchdog.fired])
2630
+ result = await waiter
2655
2631
  } finally {
2656
2632
  watchdog.stop()
2657
2633
  }
@@ -2740,7 +2716,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2740
2716
  'EVIDENCE_UNPARSABLE',
2741
2717
  { subtaskId: subtask.id },
2742
2718
  )
2743
- if (shouldRetryAttempt(unparsableError, attempt, deadline - Date.now(), idleTimeoutMs)) {
2719
+ if (shouldRetryAttempt(unparsableError, attempt, Number.POSITIVE_INFINITY, idleTimeoutMs)) {
2744
2720
  throw unparsableError
2745
2721
  }
2746
2722
  settleFromOutput(record, subtask, output, guard, options, settleVerdict,
@@ -2844,7 +2820,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2844
2820
  'EVIDENCE_MISSING',
2845
2821
  { subtaskId: subtask.id },
2846
2822
  )
2847
- if (shouldRetryAttempt(missingError, attempt, deadline - Date.now(), idleTimeoutMs)) {
2823
+ if (shouldRetryAttempt(missingError, attempt, Number.POSITIVE_INFINITY, idleTimeoutMs)) {
2848
2824
  throw missingError
2849
2825
  }
2850
2826
  }
@@ -2861,10 +2837,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2861
2837
  return
2862
2838
  } catch (error: any) {
2863
2839
  lastError = error
2864
- if (guard.timedOut) break
2865
2840
  const isAbort = parentSignal.aborted || child.controller.signal.aborted
2866
- const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
2867
- const remaining = deadline - Date.now()
2841
+ const remaining = Number.POSITIVE_INFINITY
2868
2842
  /*
2869
2843
  * [1.7.0] The retry carries the previous failure with it.
2870
2844
  *
@@ -2890,13 +2864,6 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2890
2864
  `子任务 ${subtask.id}(${subtask.title})第 ${attempt} 次执行被打断(${lastFailure.code}:${truncate(lastFailure.message, 140)});处理:插件已把失败原因回喂同一子会话并自动重试(第 ${attempt + 1} 次),任务整体仍在推进,这不是最终失败。`)
2891
2865
  continue
2892
2866
  }
2893
- /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
2894
- if (!isAbort && remaining <= idleTimeoutMs) {
2895
- record.errors = [
2896
- ...(record.errors ?? []),
2897
- `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
2898
- ].slice(-20)
2899
- }
2900
2867
  break
2901
2868
  } finally {
2902
2869
  clearAckTimers()
@@ -3258,17 +3225,8 @@ async function notifyExpertOfExtension(ctx: any, agent: any, record: any, subtas
3258
3225
  }
3259
3226
 
3260
3227
  /*
3261
- * One attempt under a deadline that belongs to that attempt alone.
3262
- *
3263
- * [1.10.6] Split out of `runSubtask` so a ceiling timeout can be retried with a
3264
- * *fresh* timer. The old code armed a single timer for the whole subtask (shared
3265
- * by both attempts), so even once the retry decision became reachable the second
3266
- * attempt would have had no time left — a patch that changes nothing.
3267
- *
3268
- * The timer remains a full settlement guarantee, not just an abort hint: if the
3269
- * child activation ignores its abort signal, or never settles at all, the race
3270
- * below still resolves, the subtask is recorded as blocked, and the dispatcher
3271
- * keeps scheduling the rest of the DAG.
3228
+ * 部门负责人与其全球顶尖专家的正式执行不设墙钟、空闲或回执硬截止。
3229
+ * 只有子会话真实收束、返回错误、证据门禁或用户显式取消才能结束等待。
3272
3230
  */
3273
3231
  async function runSubtaskAttempt(
3274
3232
  ctx: any,
@@ -3276,318 +3234,27 @@ async function runSubtaskAttempt(
3276
3234
  stage: any,
3277
3235
  subtask: any,
3278
3236
  options: any,
3279
- timeoutMs: number,
3280
3237
  ) {
3281
3238
  const child = createChildController(options.parentSignal)
3282
3239
  const guard: SubtaskGuard = { timedOut: false }
3283
- let timer: ReturnType<typeof setTimeout> | null = null
3284
- let ceilingFired = false
3285
- // [1.10.6] What the ceiling left on disk, in the words of the same probe the
3286
- // blocked row records. The retry is compared against exactly this list.
3287
- let ceilingLanded: string[] = []
3288
- /*
3289
- * [1.10.6] Snapshot taken *at the moment the ceiling fires*, not later.
3290
- *
3291
- * The first cut of this check fingerprinted the same refs twice, back to back,
3292
- * immediately before the retry. Two reads of the same instant can never
3293
- * differ, so the conflict branch was unreachable in production (only a test
3294
- * injecting a mutating `stat` could reach it). The record must be taken while
3295
- * the timeout is being recorded; the pre-retry read is compared against it.
3296
- */
3297
- let ceilingFingerprint: any[] = []
3298
- const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
3299
- /*
3300
- * [2.2.0][T4/O-3b][O-4d] 可延期计时句柄(D 项延期接口的运行时锚点,方案 §2.2/§2.5)。
3301
- * 本次尝试的协商截止只属于这次尝试:extend() 重置一次性计时器并同步 watchdog
3302
- * (rearmApproachingDeadline 传「自尝试起点计的新完整窗口」);settled 后不得
3303
- * 复活(extendDeadline 一律 NO_ACTIVE_ATTEMPT)。行上 deadlineAt 由 executeSubtask
3304
- * 以同一时钟读数写入(C3 契约),句柄权威值随写同步。
3305
- */
3306
- const attemptStart = Date.now()
3307
- const attemptHandle = {
3308
- subtaskId: String(subtask.id),
3309
- startedAt: attemptStart,
3310
- deadlineAt: attemptStart + timeoutMs,
3311
- settled: false,
3312
- watchdog: null as any,
3313
- arm: (_ms: number) => {},
3314
- extend(ms: number) {
3315
- if (this.settled) return this.deadlineAt
3316
- this.deadlineAt += ms
3317
- this.arm(this.deadlineAt - Date.now())
3318
- this.watchdog?.rearmApproachingDeadline(this.deadlineAt - this.startedAt)
3319
- return this.deadlineAt
3320
- },
3321
- attachWatchdog(watchdog: any) {
3322
- this.watchdog = watchdog
3323
- },
3324
- }
3325
- record.attemptHandles = { ...(record.attemptHandles ?? {}), [String(subtask.id)]: attemptHandle }
3326
- const deadlinePromise = new Promise<void>((resolve) => {
3327
- const fire = () => {
3328
- ceilingFired = true
3329
- guard.timedOut = true
3330
- attemptHandle.settled = true
3331
- // [2.2.0][T4/O-3b][O-4d] L4 安全兜底结算+「待裁决」标记(E4 契约):时间是
3332
- // 协商出来的安全兜底,不是固定交付期限——到点不表述为「强制结束」式固定期限
3333
- // 误杀,而是安全兜底结算落盘,供主 Agent 决定延期 / 重试 / 接受(或转新轮
3334
- // 续跑、人工裁决)。Reached only when the child ignored both its idle window
3335
- // and its abort signal; the message says so, otherwise the cause looks like
3336
- // a plain "too slow" and the next investigation goes down the wrong path.
3337
- // [2.3.0][T1] 计数在组装文案前预读:第 1 次超时的文案要求「必须放宽并
3338
- // 告知专家」;第 2 次及以后的文案要求「主 Agent 接手、已完成部分只读
3339
- // 保护、禁止丢弃」。错误文本是结果消息/看板/续跑判定的共同来源,所以
3340
- // 接手语义必须在这里就落进 message,而不是只进即时通知。
3341
- const preRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
3342
- const timeoutCountAtFire = Number(preRow?.timeoutCount ?? 0) + 1
3343
- const message = timeoutCountAtFire >= TAKEOVER_AFTER_TIMEOUTS
3344
- ? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent 直接接手完成尚未完成的部分;专家已完成并落盘的部分已登记只读保护,禁止丢弃、禁止整步重跑;接手仅发生在已批准延期的场景)`
3345
- : `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按运行层安全兜底结算(待裁决:判据层 10 分钟完成目标未达成且无用户批准 → 判未完成,优先 replan(replace) 转新子任务只补缺口;或经用户批准并留痕后 extendMs 放宽;或重试 / 接受、转新轮续跑、人工裁决)`
3346
- try {
3347
- // [1.8.19] Keep the evidence of what already landed on disk.
3348
- const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
3349
- ceilingLanded = Array.isArray(landed) ? landed : []
3350
- ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat)
3351
- /*
3352
- * [1.11.0] An escalation outranks the ceiling.
3353
- *
3354
- * The child may have written `escalated` seconds before this timer fired;
3355
- * turning that into a plain timeout would erase the question the main
3356
- * Agent has to answer. The activation is still aborted, but the row keeps
3357
- * its pending-decision state.
3358
- */
3359
- const existing = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
3360
- if (existing?.closure === 'escalated') {
3361
- record.errors = [
3362
- ...(record.errors ?? []),
3363
- `${subtask.id}: 已达执行上限,但该子任务已在等待指示,保留 escalated 状态`,
3364
- ].slice(-20)
3365
- } else {
3366
- record.statuses = applyStatus(record.statuses, subtask.id, patch)
3367
- record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
3368
- }
3369
- /*
3370
- * [2.2.0][T4/O-3b][C/E] 「待裁决」结构化标记(E4 契约):结算文案已含
3371
- * 「待裁决」,这里再落机器可读标记供裁决/回放白名单透传(pendingAdjudication)。
3372
- * 走 StatusEntry 未知字段通道直写(applyStatus 白名单属 T3 领地)。
3373
- */
3374
- const settleRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
3375
- if (settleRow) settleRow.pendingAdjudication = true
3376
- /*
3377
- * [SCv2-T4][Q1-B/Q3-B/Q6-A] 到点结算的判据层判定(仅生效计划):
3378
- * 运行层兜底已完成(blocked+产物抢救照旧),这里追加判据结果与违规
3379
- * 审计;unmet 时把「判未完成→replan(replace) 接替」写进 error/summary,
3380
- * 与 C15 文案同向。pendingAdjudication 事实标记保留(C16 不改)。
3381
- */
3382
- if (settleRow && criterionV2Active(record.plan?.createdAt)) {
3383
- try {
3384
- let leaderForCriterion: any = null
3385
- try { leaderForCriterion = deriveLeaderEstimate(settleRow) } catch { leaderForCriterion = null }
3386
- const exAnte = criterionExAnte(settleRow, leaderForCriterion)
3387
- const wallClockMs = attemptWallClockMsOf(settleRow)
3388
- const evaluation = evaluateCriterion({
3389
- exAnteMinutes: exAnte.minutes,
3390
- exAnteComplete: exAnte.complete,
3391
- wallClockMs,
3392
- exception: sanitizeCriterionException(settleRow.criterionException),
3393
- settledAt: Date.now(),
3394
- })
3395
- settleRow.criterionResult = evaluation.criterionResult
3396
- if (evaluation.criterionResult === 'unmet') {
3397
- settleRow.criterionViolations = appendCriterionViolation(settleRow.criterionViolations, {
3398
- at: Date.now(),
3399
- attempt: timeoutCountAtFire,
3400
- wallClockMs,
3401
- exAnteMinutes: exAnte.minutes,
3402
- reasons: evaluation.reasons,
3403
- })
3404
- const criterionNote = `判据违规(criterion-overrun):${evaluation.reasons.join(';')}。`
3405
- + '未获用户批准不得以 done 收尾(Q1-B);已完成产物只读保留,优先 replan(replace) 转接替子任务只补缺口,'
3406
- + '或先向用户申请例外批准并留痕(criterionApproval)后放宽。'
3407
- settleRow.error = truncate(`${settleRow.error ?? ''};${criterionNote}`, 3000)
3408
- settleRow.summary = truncate(`未完成:${criterionNote}`, 3000)
3409
- }
3410
- } catch (error: any) {
3411
- record.errors = [...(record.errors ?? []), `${subtask.id}: 判据层判定写入失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20)
3412
- }
3413
- }
3414
- /*
3415
- * [2.3.0][T1] 超时计数与二次超时接手(用户要求 1/2 的机读落点):
3416
- * 每次到点收束给状态行 timeoutCount +1 并记入 timeJournal(action:'timeout')。
3417
- * 第 1 次超时 → 即时通知主 Agent「必须放宽(extendMs)并告知专家最新时限」,
3418
- * 告知专家由延期事务自动投递(notifyExpertOfExtension);
3419
- * 第 2 次超时 → takeoverRequired=true + buildTakeoverBrief 登记已完成部分,
3420
- * mergePreservedArtifacts 把已落盘产物并入行 artifacts(只读保护、只增不减),
3421
- * 主 Agent 接手只继续 remainingOutputs 与未满足验收,禁止丢弃已完成部分。
3422
- * 计数走 StatusEntry 未知字段直写通道,回放白名单同步透传。
3423
- */
3424
- if (settleRow) {
3425
- const timeoutCount = timeoutCountAtFire
3426
- settleRow.timeoutCount = timeoutCount
3427
- const timeoutJournal = Array.isArray(settleRow.timeJournal) ? settleRow.timeJournal : []
3428
- timeoutJournal.push({ at: Date.now(), action: 'timeout', timeoutCount, by: 'system' })
3429
- settleRow.timeJournal = timeoutJournal.slice(-20)
3430
- if (timeoutCount >= TAKEOVER_AFTER_TIMEOUTS) {
3431
- // 禁止丢弃已完成部分:接手包 + artifacts 只增不减的并集合并。
3432
- settleRow.takeoverRequired = true
3433
- settleRow.takeoverBrief = buildTakeoverBrief(subtask, settleRow, ceilingLanded, timeoutCount)
3434
- settleRow.artifacts = mergePreservedArtifacts(settleRow.artifacts, settleRow.takeoverBrief.landedRefs)
3435
- }
3436
- try {
3437
- const takeoverText = timeoutCount >= TAKEOVER_AFTER_TIMEOUTS
3438
- ? `子任务 ${subtask.id} 已第 ${timeoutCount} 次达到协商时限(二次超时):按 2.3.0 机制本行已置「主 Agent 接手」(takeoverRequired)。`
3439
- + `专家已完成并登记保护的部分(只读、禁止丢弃):${(ceilingLanded as string[]).slice(0, 8).join('、') || '(见 takeoverBrief)'};`
3440
- + '请主 Agent 直接接手继续未完成部分,不要整步重跑、不要删除或覆盖已登记产物。'
3441
- : (criterionV2Active(record.plan?.createdAt)
3442
- ? `子任务 ${subtask.id} 第 1 次达到协商时限:按用户 2026-11-13 裁决 Q1-B,第一次超时不再自动放宽——请先向用户申请例外批准并留痕`
3443
- + '(任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=未批准),批准后才可用 dsh_workplan_update(extendMs, criterionApproval) 放宽;'
3444
- + '未获批准不得放宽,按判据层未达标处理(不 done、replan(replace) 转接替子任务只补缺口,已完成产物只读保护)。'
3445
- : `子任务 ${subtask.id} 第 1 次达到协商时限:按 2.3.0 机制请主 Agent 尽快用 dsh_workplan_update(extendMs) 放宽,`
3446
- + '延期成功后插件会自动把最新时限与「保证质量、高效率执行」要求告知专家;如判断无需再放宽,请接手继续未完成部分(已完成产物将只读保护)。')
3447
- announceSubtaskInterrupt(record, options.session ?? options.agent?.session, subtask.id, takeoverText)
3448
- } catch {
3449
- // 通知失败不影响结算(与预警同一纪律)。
3450
- }
3451
- }
3452
- record.updatedAt = Date.now()
3453
- } catch (error: any) {
3454
- record.errors = [
3455
- ...(record.errors ?? []),
3456
- `${subtask.id}: 超时状态写入失败:${truncate(String(error?.message ?? error), 500)}`,
3457
- ].slice(-20)
3458
- } finally {
3459
- if (!child.controller.signal.aborted) {
3460
- child.controller.abort(new PlanError(message, 'CHILD_TIMEOUT', { subtaskId: subtask.id }))
3461
- }
3462
- child.disposeListener()
3463
- resolve()
3464
- }
3465
- }
3466
- // [2.2.0][T4/O-3b][O-4d] 可延期计时(D 项):arm() 重置一次性计时器,extend()
3467
- // 经 attemptHandle 调用它把截止点推移到新协商截止;原截止点不再触发。
3468
- const arm = (ms: number) => {
3469
- if (timer) clearTimeout(timer)
3470
- timer = setTimeout(fire, Math.max(1, ms))
3471
- // [2.2.8] 禁止 unref:上限计时器必须是 ref 句柄。unref 时裸事件循环进程
3472
- // (node:test / CI node22)会在等待竞态期间排空退出,用例被 cancelledByParent
3473
- // → node:test exit 1 → 2.2.6/2.2.7 提交 CI 红叉根因(本地 node26 因 runner
3474
- // 自带句柄竞态获胜而假绿)。收束路径 finally 已 clearTimeout,不会悬挂进程。
3475
- }
3476
- attemptHandle.arm = arm
3477
- arm(timeoutMs)
3478
- })
3479
3240
  try {
3480
- // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
3481
- // swallowing it here is why an interrupted child looked like any failure.
3482
- const outcome = await Promise.race([
3483
- executeSubtask(ctx, record, stage, subtask, {
3484
- ...options,
3485
- child,
3486
- guard,
3487
- // [2.2.0][T4/O-3b] 本次尝试的协商执行时限与计时句柄(deadlineAt 写入同源、
3488
- // 看门狗 hardMs 同值、延期接口锚点)。
3489
- attemptTimeoutMs: timeoutMs,
3490
- attemptHandle,
3491
- }),
3492
- deadlinePromise,
3493
- ])
3494
- return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint }
3241
+ const outcome = await executeSubtask(ctx, record, stage, subtask, {
3242
+ ...options,
3243
+ child,
3244
+ guard,
3245
+ attemptTimeoutMs: 0,
3246
+ attemptHandle: undefined,
3247
+ })
3248
+ return { outcome, ceilingFired: false, ceilingLanded: [], ceilingFingerprint: [] }
3495
3249
  } finally {
3496
- // [2.2.0][T4/O-3b] 收束即注销句柄:已收束的尝试不得再被 extendDeadline 复活。
3497
- attemptHandle.settled = true
3498
- if (record.attemptHandles) delete record.attemptHandles[String(subtask.id)]
3499
- if (timer) {
3500
- clearTimeout(timer)
3501
- timer = null
3502
- }
3503
3250
  child.disposeListener()
3504
3251
  if (!child.controller.signal.aborted) child.controller.abort()
3505
3252
  }
3506
3253
  }
3507
3254
 
3508
- /*
3509
- * Runs one subtask, retrying **once** when the per-subtask ceiling fired and the
3510
- * round budget can still pay for a second attempt (T6 G1/G3/G4).
3511
- *
3512
- * The retry is deliberately narrow:
3513
- * - only the ceiling (`CHILD_TIMEOUT`) qualifies; a user abort and a round
3514
- * budget timeout stay non-retryable, because retrying them would be killed by
3515
- * the same guillotine;
3516
- * - at most one retry (`attemptOffset: 2` caps the inner loop at a single run);
3517
- * - before it starts, the artifacts the first attempt landed are fingerprinted
3518
- * (path + size + mtime) and re-checked. If any of them changed since the
3519
- * timeout was recorded, something else owns that file now: the retry is
3520
- * skipped and the row is marked `artifactConflict` instead of overwriting it.
3521
- */
3522
3255
  async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
3523
- // [2.2.0][T4/O-3b] 本次执行时限=柔性时长协商消费序(见 resolveSubtaskTimeoutMs):
3524
- // ① subtask.timeoutMs 显式值 → ② deriveSubtaskTimeoutMs(estimateMinutes) 派生 →
3525
- // ③ 缺省回落 CHILD_TIMEOUT_MS;显式注入的 childTimeoutMs 作兜底上限取 min。
3526
- const childTimeoutMs = resolveSubtaskTimeoutMs(subtask, options.childTimeoutMs)
3527
- const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs)
3528
- if (!first.ceilingFired) return first.outcome
3529
-
3530
- const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
3531
- const now = Date.now()
3532
- const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs
3533
- const remaining = deadline - now
3534
- const message = `子任务 ${subtask.id} 达到协商执行上限(${childTimeoutMs}ms)`
3535
- /*
3536
- * [1.8.6] A parent abort outranks a retry: the round is being stopped on
3537
- * purpose, and a second child would only be aborted on arrival.
3538
- */
3539
- if (options.parentSignal?.aborted) return first.outcome
3540
- if (!shouldRetryAttempt({ code: 'CHILD_TIMEOUT', message }, 1, remaining, idleTimeoutMs)) {
3541
- record.errors = [
3542
- ...(record.errors ?? []),
3543
- `${subtask.id}: 达到执行上限,剩余预算 ${Math.max(0, Math.round(remaining / 1000))}s 不足,未重试`,
3544
- ].slice(-20)
3545
- return first.outcome
3546
- }
3547
- /*
3548
- * [1.10.6] T6 G3: never retry over work that already exists.
3549
- *
3550
- * `ceilingFingerprint` was taken the moment the ceiling fired (inside the
3551
- * timeout callback); the same refs are re-read right before the retry starts.
3552
- * A size or mtime difference means the file was written by somebody else in
3553
- * between, so a retry would overwrite it rather than finish it.
3554
- */
3555
- const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
3556
- const current = fingerprintArtifacts(first.ceilingLanded, options.cwd, stat)
3557
- const conflicts = diffArtifactFingerprints(first.ceilingFingerprint, current)
3558
- const row: any = Array.isArray(record.statuses)
3559
- ? record.statuses.find((item: any) => item.subtaskId === subtask.id)
3560
- : null
3561
- if (conflicts.length > 0) {
3562
- const note = `重试前核对发现已落盘产物在超时后被改动(${conflicts.join('、')}),为避免覆盖已跳过自动重试,请人工核对`
3563
- record.statuses = applyStatus(record.statuses, subtask.id, {
3564
- artifactConflict: conflicts,
3565
- error: truncate(`${truncate(String(row?.error ?? message), 1500)};${note}`, 2000),
3566
- })
3567
- record.errors = [...(record.errors ?? []), `${subtask.id}: ${note}`].slice(-20)
3568
- record.updatedAt = Date.now()
3569
- return first.outcome
3570
- }
3571
-
3572
- record.statuses = applyStatus(record.statuses, subtask.id, {
3573
- status: 'in_progress',
3574
- progress: 15,
3575
- // Clearing `error` moves the timeout text to `lastError` (applyStatus does
3576
- // that move), so the row no longer claims "blocked" while it is retrying.
3577
- error: null,
3578
- })
3579
- record.errors = [
3580
- ...(record.errors ?? []),
3581
- `${subtask.id}: 第 1 次执行达到上限(CHILD_TIMEOUT),已核对产物无冲突,自动重试一次`,
3582
- ].slice(-20)
3583
- record.updatedAt = Date.now()
3584
- const retryTimeoutMs = Math.max(MIN_CHILD_TIMEOUT_MS, Math.min(childTimeoutMs, remaining))
3585
- const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
3586
- ...options,
3587
- attemptOffset: 2,
3588
- priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已按安全兜底结算(待裁决)` },
3589
- }, retryTimeoutMs)
3590
- return second.outcome
3256
+ const attempt = await runSubtaskAttempt(ctx, record, stage, subtask, options)
3257
+ return attempt.outcome
3591
3258
  }
3592
3259
 
3593
3260
  async function runWithConcurrency(items: any, limit: any, worker: any) {
@@ -3693,10 +3360,11 @@ export function modelStatusLines(statuses: any) {
3693
3360
  * deadlineAt/startedAt(字段名/单位照合同原文)。
3694
3361
  */
3695
3362
  startedAt: item.startedAt ?? null,
3696
- deadlineAt: item.deadlineAt ?? null,
3697
- deadlineRemainingMs: Number.isFinite(Number(item.deadlineAt))
3698
- ? Math.max(0, Number(item.deadlineAt) - Date.now())
3699
- : null,
3363
+ executionTimeLimit: 'none',
3364
+ // 旧记录只读保留,绝不再解释为当前截止或剩余执行时间。
3365
+ deadlineAt: null,
3366
+ legacyDeadlineAt: item.deadlineAt ?? null,
3367
+ deadlineRemainingMs: null,
3700
3368
  timeWarning: item.timeWarning ?? null,
3701
3369
  timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
3702
3370
  pendingAdjudication: item.pendingAdjudication === true,
@@ -3746,7 +3414,7 @@ export function modelStatusLines(statuses: any) {
3746
3414
  criterionResult: item.criterionResult ?? null,
3747
3415
  criterionException: item.criterionException ?? null,
3748
3416
  criterionViolations: Array.isArray(item.criterionViolations) ? item.criterionViolations.slice(-10) : [],
3749
- leaderEstimateOverCriterion: exAnteView.minutes !== null && exAnteView.minutes > CRITERION_TARGET_MINUTES,
3417
+ leaderEstimateOverCriterion: false,
3750
3418
  }
3751
3419
  })
3752
3420
  }
@@ -3823,7 +3491,7 @@ function describePendingCause(plan: any, statuses: any[], id: string): string {
3823
3491
  export async function dispatchPlan(ctx: any, record: any, options: any) {
3824
3492
  const { agent, signal, modelSelection, cwd, conversationContext = '' } = options
3825
3493
  const roundBudgetMs = Number(options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS)
3826
- const deadline = Date.now() + (roundBudgetMs > 0 ? roundBudgetMs : NO_ROUND_BUDGET_MS)
3494
+ const deadline = Number.POSITIVE_INFINITY
3827
3495
  /*
3828
3496
  * [2.2.0][T3/O-2a] 本轮子→主预告通道的目标会话 id,一轮只解析一次。
3829
3497
  *
@@ -3906,14 +3574,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
3906
3574
  const onAbort = () => childController.abort(parentSignal.reason ?? abortError())
3907
3575
  if (parentSignal.aborted) onAbort()
3908
3576
  else parentSignal.addEventListener('abort', onAbort, { once: true })
3909
- const totalTimer = setTimeout(() => {
3910
- childController.abort(new PlanError('总执行超时', 'TOTAL_TIMEOUT'))
3911
- // [2.2.5][热修] 双重保险:即使哨兵值/配置未来被改成超限值,也把延时钳在
3912
- // Node setTimeout 上限之内,杜绝“1ms 触发”的整轮秒杀。
3913
- }, Math.min(Math.max(1000, deadline - Date.now()), ROUND_TIMER_MAX_MS))
3914
- // [2.2.9][handle-policy] 收束类(T1 报告 R1,P0):轮次总预算计时器必须真实触发(与 2.2.8
3915
- // 已修的 attempt 上限计时器同构);unref 时裸循环在 TOTAL_TIMEOUT 前排空 → node:test 判
3916
- // cancelledByParent → CI 红叉。收束路径 finally 有 clearTimeout(totalTimer),不会悬挂宿主。
3577
+ // 不创建整轮 totalTimer:配置中的历史时间值不会再中止部门或专家执行。
3917
3578
  record.dispatchedAt = Date.now()
3918
3579
  record.phase = 'executing'
3919
3580
  record.updatedAt = record.dispatchedAt
@@ -3979,7 +3640,6 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
3979
3640
  guard += 1
3980
3641
  if (guard > 200) throw new PlanError('调度次数异常', 'DISPATCH_LOOP')
3981
3642
  if (parentSignal.aborted) throw abortError()
3982
- if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
3983
3643
  /*
3984
3644
  * [1.7.0] A `done` upstream only unblocks its dependents when the files it
3985
3645
  * declared actually exist. The check is opt-out (`artifactGate:false`) so
@@ -4265,7 +3925,6 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
4265
3925
  }
4266
3926
  } finally {
4267
3927
  dispatchHeartbeat.stop()
4268
- clearTimeout(totalTimer)
4269
3928
  parentSignal.removeEventListener('abort', onAbort)
4270
3929
  if (!childController.signal.aborted) childController.abort()
4271
3930
  record.updatedAt = Date.now()
@@ -4641,6 +4300,9 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
4641
4300
  /* [2.5.1] 主 Agent 两轮深度思考产物(计划级),随 durable workplan-update 回放。 */
4642
4301
  mainDeepThink: any
4643
4302
  mainDeepThinkPlanId: string | null
4303
+ /* [3.0.1] 认可闸门(计划级)随回放快照透传:刷新/重启后 dispatch 闸门读档生效。 */
4304
+ dispatchHold?: any
4305
+ gateHistory?: any[]
4644
4306
  /* [2.5.7] 续跑上限随回放快照透传(durable 消息未携带时为 undefined,回落 MAX_PLAN_RESUMES)。 */
4645
4307
  resumeLimit?: number
4646
4308
  }
@@ -4673,6 +4335,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
4673
4335
  changeRequest: null,
4674
4336
  mainDeepThink: null,
4675
4337
  mainDeepThinkPlanId: null,
4338
+ dispatchHold: undefined,
4339
+ gateHistory: undefined,
4676
4340
  }
4677
4341
  snapshots.set(plan.planId, snap)
4678
4342
  }
@@ -4833,6 +4497,29 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
4833
4497
  deepThinkSnap.mainDeepThinkPlanId = typeof update.mainDeepThinkPlanId === 'string' ? update.mainDeepThinkPlanId : null
4834
4498
  }
4835
4499
  }
4500
+ /*
4501
+ * [3.0.1] 认可闸门回放(计划级字段):写入侧 buildUpdateMessage 已携带
4502
+ * dispatchHold/gateHistory;消费侧同口径消毒抬升。dispatchHold 为 null
4503
+ * 表示「已 release」(快照清闸),gateHistory 只增审计随回放还原。
4504
+ */
4505
+ if (update && typeof update.planId === 'string' && update.dispatchHold !== undefined) {
4506
+ const holdSnap = snapshots.get(update.planId)
4507
+ if (holdSnap) {
4508
+ const raw = update.dispatchHold
4509
+ holdSnap.dispatchHold = raw && typeof raw === 'object'
4510
+ ? {
4511
+ kind: raw.kind === 'manual' ? 'manual' : 'keyword',
4512
+ reason: truncate(String(raw.reason ?? ''), 300),
4513
+ at: Number(raw.at) || 0,
4514
+ by: raw.by === 'agent' ? 'agent' : 'system',
4515
+ }
4516
+ : null
4517
+ }
4518
+ }
4519
+ if (update && typeof update.planId === 'string' && Array.isArray(update.gateHistory)) {
4520
+ const holdSnap = snapshots.get(update.planId)
4521
+ if (holdSnap) holdSnap.gateHistory = update.gateHistory.slice(-10)
4522
+ }
4836
4523
  if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
4837
4524
  const snap = snapshots.get(update.planId)
4838
4525
  if (snap) {
@@ -4923,6 +4610,12 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
4923
4610
  artifacts: update.artifacts,
4924
4611
  missingArtifacts: update.missingArtifacts,
4925
4612
  handoffs: update.handoffs,
4613
+ /*
4614
+ * [3.0.1] 死锁自愈:复活指示随 durable update 回放(applyStatus
4615
+ * 同口径消毒,undefined 保留旧值)——重启后重建的子会话仍能收到
4616
+ * 主 Agent 对升级请示的拍板指示。
4617
+ */
4618
+ reviveInstruction: update.reviveInstruction,
4926
4619
  revision: Number.isInteger(update.revision) ? update.revision : undefined,
4927
4620
  // [2.2.0][T4/O-3b][E] 回放白名单(T3b TODO#2):O-3b/O-2c 留档字段随
4928
4621
  // update 记录回放;timeoutMs 有 applyStatus 分支,走 patch 即可。
@@ -5182,6 +4875,11 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
5182
4875
  /* [2.5.1] 主 Agent 两轮深度思考产物随回放回到记录(续跑读档放行)。 */
5183
4876
  mainDeepThink: chosen.mainDeepThink ?? null,
5184
4877
  mainDeepThinkPlanId: chosen.mainDeepThinkPlanId ?? null,
4878
+ /* [3.0.1] 认可闸门随重建记录还原:重启后 dispatch 闸门与审计留痕不失效。
4879
+ * 直接属性而非条件展开——条件展开会破坏返回字面量的判别收窄
4880
+ * (rebuilt.plan 的 null/对象判别失效,resumeLimit 访问报 union 错)。 */
4881
+ dispatchHold: (chosen as any).dispatchHold ?? null,
4882
+ gateHistory: Array.isArray((chosen as any).gateHistory) ? (chosen as any).gateHistory : [],
5185
4883
  /*
5186
4884
  * [1.8.17] A reconstructed record must carry every field the live dispatch
5187
4885
  * path spreads/pushes unconditionally. `errors` was the one that was
@@ -5719,26 +5417,6 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5719
5417
  })
5720
5418
  row.timeJournal = journal.slice(-20)
5721
5419
  record.updatedAt = at
5722
- /*
5723
- * [SCv2-T4][Q4-B/C22] 部门行事前预估落档后的超判据告警(仅生效计划):
5724
- * 叶子预估之和(或无叶子直做时负责人自身预估)>10 ⇒ 即时告知主 Agent
5725
- * 拆分或向用户申请例外批准;预估未齐只显示部分和、不得视为达标(D-3)。
5726
- * 告警是观测设施:写失败只留档 errors,绝不影响记录与执行。
5727
- */
5728
- try {
5729
- if (criterionV2Active(record?.plan?.createdAt) && session) {
5730
- let leaderForNotice: any = null
5731
- try { leaderForNotice = deriveLeaderEstimate(row) } catch { leaderForNotice = null }
5732
- const exAnte = criterionExAnte(row, leaderForNotice)
5733
- if (exAnte.minutes !== null && exAnte.minutes > CRITERION_TARGET_MINUTES) {
5734
- appendUserMessage(session, `【dsh-workplan·判据告警】子任务 ${subtaskId} 的事前预估为 ${exAnte.minutes} 分钟,`
5735
- + `超过判据层完成目标 ${CRITERION_TARGET_MINUTES} 分钟(Q4-B)。请事前拆分工作,或向用户申请例外批准并留痕(criterionApproval);`
5736
- + '预估未报齐时只显示部分和,不得视为「简单判据达标」。')
5737
- }
5738
- }
5739
- } catch (error: any) {
5740
- record.errors = [...(record.errors ?? []), `${subtaskId} 判据告警写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20)
5741
- }
5742
5420
  /*
5743
5421
  * [2.3.0][T1] 预估上报 → 告知用户(用户要求 1 的前半段闭环):专家的开工
5744
5422
  * 预告落档后,插件立即向主会话推送一条即时通知,明确「请把此预期执行
@@ -5750,8 +5428,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5750
5428
  appendUserMessage(session, `【dsh-workplan·专家预估上报】子任务 ${subtaskId} 的执行专家`
5751
5429
  + `预估执行时间 ${Number(notice?.declaredMinutes)} 分钟`
5752
5430
  + (reason ? `(${reason})` : '')
5753
- + `;请把此预期执行时间告知用户。若执行中超时,请主 Agent 放宽(extendMs)`
5754
- + '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。',
5431
+ + ';请把此预期执行时间告知用户。预估仅供参考、非承诺,不会形成执行截止、超时接管或完成验收门槛。',
5755
5432
  undefined, { allowBanned: true })
5756
5433
  } catch (error: any) {
5757
5434
  record.errors = [...(record.errors ?? []), `${subtaskId} 预估上报通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20)
@@ -5797,6 +5474,16 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5797
5474
  hint: '请传入 1 以上的整数毫秒;放宽永远有界(累计 ≤ 初始协商上限 × 1),超出请转新轮续跑或转 escalate 请主 Agent 裁决。',
5798
5475
  }
5799
5476
  }
5477
+ if (hasExtend) {
5478
+ return {
5479
+ ok: false,
5480
+ code: 'TIME_LIMITS_DISABLED',
5481
+ planId: record.plan.planId,
5482
+ subtaskId,
5483
+ error: '部门负责人与全球顶尖专家执行已取消时限,无需也不能申请延期;当前任务会继续等待真实完成、真实错误或用户取消。',
5484
+ hint: '请移除 extendMs,直接继续执行;如需汇报预估变化,只传 timeNotice(纯信息,不影响验收)。',
5485
+ }
5486
+ }
5800
5487
  /*
5801
5488
  * [SCv2-T4][Q1-B/C05/C06] extendMs 用户批准闸(判据 v2 生效计划专用):
5802
5489
  * 第一次超时不再自动放宽——未携带合格用户批准留痕(criterionApproval)一律
@@ -7859,9 +7546,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
7859
7546
  * 指示投递成功只证明消息进了收件箱,不证明子会话真的开始执行。三个观察点
7860
7547
  * 都以「该行仍是 instructed 且 instructionSeq 未变」为前提:
7861
7548
  * - 轮询:子会话 seq 增长 = 已开始执行 → 写 acknowledged(唯一正向回执);
7862
- * - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent 可催);
7863
- * - 180s:仍无增长 → 收束为 blocked/no-ack(不再无限等待)。
7864
- * 主 Agent 再次改判或子会话产出结果都会让这三个观察点自然作废。
7549
+ * - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent 可催)。
7550
+ * 这里没有 180s 硬截止,也不会因缺少回执收束为 blocked/no-ack;主 Agent
7551
+ * 再次改判、子会话产出结果或用户显式取消才会让观察自然作废。
7865
7552
  */
7866
7553
  function scheduleInstructionAck(record: any, subtaskId: string, childId: string, revision: number) {
7867
7554
  const rowOf = () => record.statuses.find((item: any) => item?.subtaskId === subtaskId)
@@ -7896,8 +7583,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
7896
7583
  return seq <= baseline
7897
7584
  }
7898
7585
  /*
7899
- * 正向回执:没有这一步时,一个正常工作但耗时较长的子会话会在 180s 被
7900
- * 误判成 no-ack 并阻断,而它其实早就在产出事件了。
7586
+ * 正向回执:没有这一步时,一个正常工作但耗时较长的子会话会被误判成
7587
+ * 无响应;它其实早就在产出事件了。现在只用于消除逾期提示,不做阻断。
7901
7588
  */
7902
7589
  const poll = setInterval(() => {
7903
7590
  const row = rowOf()
@@ -7918,7 +7605,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
7918
7605
  }
7919
7606
  stop()
7920
7607
  }, INSTRUCTION_POLL_MS)
7921
- // [2.2.9][handle-policy] 卫生类(T1 报告 R8):回执轮询只提供提前确认,deadline 判定兜底,保留 unref。
7608
+ // [3.0.1] 回执轮询只提供正向确认与逾期提示;没有 deadline 判定,保留 unref。
7922
7609
  poll.unref?.()
7923
7610
  timers.push(poll)
7924
7611
  const notice = setTimeout(() => {
@@ -7932,32 +7619,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
7932
7619
  // [2.2.9][handle-policy] 卫生类(T1 报告 R9):只丢一次「指示未回执」提示,保留 unref。
7933
7620
  notice.unref?.()
7934
7621
  timers.push(notice)
7935
- const deadline = setTimeout(() => {
7936
- if (!unchanged(rowOf())) { stop(); return }
7937
- const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000)
7938
- const message = `指示下发后 ${seconds}s 子会话仍无任何新事件(no-ack):指示没有被执行`
7939
- try {
7940
- writeSubtaskStatus(record, subtaskId, {
7941
- status: 'blocked',
7942
- closure: 'blocked',
7943
- blockedKind: 'no-ack',
7944
- progress: 100,
7945
- finishedAt: Date.now(),
7946
- instructionOverdue: true,
7947
- error: message,
7948
- summary: `未完成:${message}`,
7949
- }, { timedOut: false })
7950
- recordSubtaskError(record, subtaskId, message, { timedOut: false })
7951
- } catch {
7952
- // Same race as above: the row already left instructed.
7953
- }
7954
- stop()
7955
- }, INSTRUCTION_ACK_DEADLINE_MS)
7956
- // [2.2.9][handle-policy] 收束类(T1 报告 R5):指示 no-ack 判定必须真实触发;触发/回执即 stop()
7957
- // 清掉整组计时器,延时有界(INSTRUCTION_ACK_DEADLINE_MS),不会悬挂宿主。
7958
- timers.push(deadline)
7959
7622
  }
7960
7623
 
7624
+ /**
7625
+ * [1.11.0] 主 → 子下发指示 }
7626
+
7961
7627
  /**
7962
7628
  * [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
7963
7629
  *
@@ -8016,9 +7682,51 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
8016
7682
  const instruction = truncate(String(args?.instruction ?? args?.text ?? '').trim(), MAX_INSTRUCTION_CHARS)
8017
7683
  if (!instruction) return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要子 Agent 执行的决定' }
8018
7684
  const childId = typeof current.childId === 'string' ? current.childId : ''
8019
- if (!childId) return { ok: false, code: 'NO_CHILD', subtaskId, error: '该行没有关联子会话,无法投递指示' }
8020
- if (!spawnedChildIds(session).has(childId)) {
8021
- return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: `${childId} 不是本会话的直接子会话,拒绝投递` }
7685
+ const childAlive = Boolean(childId) && spawnedChildIds(session).has(childId)
7686
+ if (!childAlive) {
7687
+ /*
7688
+ * [3.0.1] 死锁自愈(wp-e745a477 事故治本):子会话失联时不再把 NO_CHILD /
7689
+ * NOT_DIRECT_CHILD 当成终点——那条路配上 ESCALATION_OPEN(不许改判)与
7690
+ * 「待指示行阻止续跑」会把三条出口全堵死,只剩人工取消整盘计划。
7691
+ * 现在:指示登记为行上 reviveInstruction(durable 回放不丢),行从
7692
+ * escalated 复位为 pending(TRANSITIONS 合法边),下一次 dispatch 走
7693
+ * 常规 executeSubtask 路径重建全新子会话,提示词由 buildChildPrompt
7694
+ * 带入这条指示。
7695
+ */
7696
+ const now = Date.now()
7697
+ const { patch: revivePatch, revision } = buildChildRevivePatch(current, instruction, now)
7698
+ record.statuses = applyStatus(record.statuses, subtaskId, revivePatch)
7699
+ record.phase = reconcilePhase(record.phase, record.statuses)
7700
+ record.updatedAt = now
7701
+ try {
7702
+ const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
7703
+ appendUserMessage(session, buildUpdateMessage({
7704
+ planId: record.plan.planId,
7705
+ subtaskId,
7706
+ status: 'pending',
7707
+ closure: 'pending',
7708
+ reviveInstruction: written?.reviveInstruction,
7709
+ revision,
7710
+ keyProgress: true,
7711
+ stateLabel: '失联复活·待重派',
7712
+ title: typeof current.title === 'string' ? current.title : undefined,
7713
+ }))
7714
+ } catch (error) {
7715
+ pushRecordError(record, error)
7716
+ }
7717
+ const snapshot = derivePlanSnapshot(record.statuses)
7718
+ return {
7719
+ ok: true,
7720
+ revived: true,
7721
+ code: 'CHILD_REVIVED',
7722
+ planId: record.plan.planId,
7723
+ subtaskId,
7724
+ status: 'pending',
7725
+ closure: 'pending',
7726
+ revision,
7727
+ stats: snapshot.stats,
7728
+ hint: '死锁自愈:该行子会话已失联,指示已登记为行上 reviveInstruction、行已复位为待跑。调用 dsh_workplan_dispatch 将重建全新子会话并带入该指示;不要再对本行重复 instruct。',
7729
+ }
8022
7730
  }
8023
7731
  const service: any = (ctx as any).subagents
8024
7732
  if (!service || typeof service.sendMessage !== 'function') {
@@ -8283,10 +7991,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
8283
7991
  }
8284
7992
 
8285
7993
  /**
8286
- * [2.5.6] 叶子指示回执:与 scheduleInstructionAck 同一套三观察点语义
8287
- * (轮询 seq 增长=acknowledged;60s 无增长=instructionOverdue;180s 无
8288
- * 增长=blocked/no-ack),只是读写目标从部门行换成行内 delegates 成员条目。
8289
- * 独立实现而不改动根会话共用的 scheduleInstructionAck,保证第一层零回归。
7994
+ * [2.5.6] 叶子指示回执:与 scheduleInstructionAck 同一套观察语义
7995
+ * (轮询 seq 增长=acknowledged;60s 无增长=instructionOverdue),只是读写
7996
+ * 目标从部门行换成行内 delegates 成员条目。两者都没有 180s 硬截止,不会
7997
+ * 因缺少回执 blocked/no-ack;独立实现以保持第一层零回归。
8290
7998
  */
8291
7999
  function scheduleDelegateInstructionAck(record: any, subtaskId: string, member: string, childId: string, revision: number) {
8292
8000
  const rowOf = () => record.statuses.find((item: any) => item?.subtaskId === subtaskId)
@@ -8358,31 +8066,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
8358
8066
  }, INSTRUCTION_ACK_NOTICE_MS)
8359
8067
  notice.unref?.()
8360
8068
  timers.push(notice)
8361
- const deadline = setTimeout(() => {
8362
- if (!unchanged(entryOf())) { stop(); return }
8363
- const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000)
8364
- const message = `指示下发后 ${seconds}s 成员会话仍无任何新事件(no-ack):指示没有被执行`
8365
- try {
8366
- patchEntry({
8367
- status: 'blocked',
8368
- closure: 'blocked',
8369
- blockedKind: 'no-ack',
8370
- progress: 100,
8371
- error: message,
8372
- summary: `未完成:${message}`,
8373
- finishedAt: Date.now(),
8374
- })
8375
- // [2.5.6] 与第一层 scheduleInstructionAck 对齐:no-ack 收束必须写入
8376
- // 错误台账(主行 recordSubtaskError 同款),不留「静默 blocked」。
8377
- recordSubtaskError(record, subtaskId, message, { timedOut: false })
8378
- } catch {
8379
- // Entry already left instructed.
8380
- }
8381
- stop()
8382
- }, INSTRUCTION_ACK_DEADLINE_MS)
8383
- timers.push(deadline)
8384
8069
  }
8385
8070
 
8071
+ /**
8072
+ * [1.11.0] 工具层入口:子会话的遇阻上报 }
8073
+
8386
8074
  /**
8387
8075
  * [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
8388
8076
  *
@@ -8489,7 +8177,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
8489
8177
  * 如果提出需求的行正处于「待指示」,它此刻停在那里等主 Agent:只把
8490
8178
  * handoff 写成 answered、不发指示,子会话永远不会继续,需求闭环只闭在
8491
8179
  * 计划表里。这里复用 instructSubtask 的唯一投递/回执链路(写 instructed、
8492
- * 60s/180s 回执、下次激活注入),不另造第二条消息通道。
8180
+ * 60s 逾期提示、下次激活注入),不另造第二条消息通道。
8493
8181
  * 投递失败不回滚 handoff:答复本身是真的,失败原因如实返回给主 Agent。
8494
8182
  */
8495
8183
  let instruction: any = null
@@ -8798,12 +8486,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
8798
8486
  persistSelf({ delegates: failedList })
8799
8487
  return { ok: false, code: 'SELF_EFFORT_CONTINUATION_FAILED', subtaskId, member: member.member, selfEffort, error: message }
8800
8488
  }
8801
- // 接续:中断 phase-0(parent authority, continuable),尽力而为。
8802
- try {
8803
- if (typeof (ctx as any).subagents?.interruptByParent === 'function') {
8804
- (ctx as any).subagents.interruptByParent(childSession.id, leaderId, 'continuable')
8805
- }
8806
- } catch { /* 中断失败不阻断接续 */ }
8489
+ // 接续:中断 phase-0(ancestor authority, continuable),尽力而为。
8490
+ // [3.0.1] 优先新版 interrupt()(authority=负责人活体 Agent);旧版宿主回退
8491
+ // interruptByParent。ancestorAgent 缺失时返回 false(与修复前静默跳过同口径)。
8492
+ interruptChildContinuable((ctx as any).subagents, childSession.id, leaderAgent, leaderId)
8807
8493
  const departmentLabel = DEPARTMENTS[row.department as keyof typeof DEPARTMENTS]?.zh ?? String(row.department ?? '部门')
8808
8494
  const assignment = (Array.isArray(row.consolidation?.assignments) ? row.consolidation.assignments : [])
8809
8495
  .find((a: any) => a?.member === member.member)
@@ -8827,6 +8513,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
8827
8513
  leadSessionId: leaderId,
8828
8514
  extraContext: `【phase-0→phase-1 接续——继续勿重做】你已在 phase-0 完成复杂度评估并自配推理等级 \`${selfEffort}\`(依据:${truncate(rationale, 300)}${correction.adjusted ? `;请求档 ${raw} 越界已被平台钳制为 ${selfEffort}` : ''}),并登记了执行前两轮深度思考产物。平台已按你的自配档接续:直接执行正式任务,不要重新评估复杂度,不要重做 phase-0 已完成的工作。正式执行必须严格按你第二轮理清的方法、流程、步骤进行(你的第二轮产物:${leafDeepThink.approach.join(';').slice(0, 300)}…),全程少走弯路:先查历史教训、先验证再动手、不重复试错。`,
8829
8515
  })
8516
+ // [3.0.1][P1a] 宿主 subagent.maxDepth < 2 时一次性告警(scope=计划根会话)。
8517
+ notifyDepthOverrideConflict(ctx, typeof rootId === 'string' ? rootId : null)
8830
8518
  let activation: any = null
8831
8519
  let lastError: any = null
8832
8520
  for (let i = 0; i < 2; i += 1) {
@@ -8856,6 +8544,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
8856
8544
  } catch (error) { lastError = error }
8857
8545
  }
8858
8546
  if (!activation) {
8547
+ // [3.0.1][P1b] 宿主并发上限单独翻译为可行动提示;其余错误走下方统一 PlanError。
8548
+ if (String(lastError?.code ?? '') === 'ACTIVATION_LIMIT_REACHED' || /limit reached/i.test(String(lastError?.message ?? ''))) {
8549
+ throw describeSubagentActivationError(lastError, `自配档接续(成员 ${member.member})`)
8550
+ }
8859
8551
  const message = `自配档已登记但接续失败(已重试 1 次):${String(lastError?.message ?? lastError)}——禁止静默降档;该成员记为 failed,负责人可重派(自配档保留,重派直接以自配档接续)`
8860
8552
  const failedList = (currentRow()?.delegates ?? [])
8861
8553
  .map((d: any) => (d?.childId === childSession.id ? { ...d, status: 'failed', error: truncate(message, 300), finishedAt: Date.now() } : d))
@@ -9111,11 +8803,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9111
8803
  })
9112
8804
  // 中断镜像 review 的 stall-fix 口径:仅「本次登记前尚无 effortOverride」
9113
8805
  // (真正的 phase-0→登记转变)才中断;phase-1 重新 direct 只更新产物。
9114
- try {
9115
- if (!hadEffortOverride && typeof (ctx as any).subagents?.interruptByParent === 'function') {
9116
- (ctx as any).subagents.interruptByParent(childSession.id, parentId, 'continuable')
9117
- }
9118
- } catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
8806
+ // [3.0.1] 优先新版 interrupt()(ancestor=执行本工具的活体负责人 agent)。
8807
+ if (!hadEffortOverride) interruptChildContinuable((ctx as any).subagents, childSession.id, agent, parentId)
9119
8808
  return {
9120
8809
  ok: true,
9121
8810
  planId: record.plan.planId,
@@ -9191,11 +8880,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9191
8880
  * 登记 effortOverride」(真正的 phase-0→登记 转变)才中断;phase-1 的
9192
8881
  * 重新 review 只更新梳理产物,绝不中断正在执行的回合。
9193
8882
  */
9194
- try {
9195
- if (preview.taskEffort && !hadEffortOverride && typeof (ctx as any).subagents?.interruptByParent === 'function') {
9196
- (ctx as any).subagents.interruptByParent(childSession.id, parentId, 'continuable')
9197
- }
9198
- } catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
8883
+ // [3.0.1] 优先新版 interrupt()(ancestor=执行本工具的活体负责人 agent)。
8884
+ if (preview.taskEffort && !hadEffortOverride) interruptChildContinuable((ctx as any).subagents, childSession.id, agent, parentId)
9199
8885
  return {
9200
8886
  ok: true,
9201
8887
  planId: record.plan.planId,
@@ -9315,6 +9001,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9315
9001
  let memberStatus = 'running'
9316
9002
  let memberError: string | null = null
9317
9003
  try {
9004
+ // [3.0.1][P1a] 宿主 subagent.maxDepth < 2 时一次性告警(scope=计划根会话)。
9005
+ notifyDepthOverrideConflict(ctx, typeof parentSession?.header?.parentSession === 'string' ? parentSession.header.parentSession : (typeof parentId === 'string' ? parentId : null))
9318
9006
  // [2.5.5][治本] 同 executeSubtask:spec 顶层契约(prompt/parent/cwd/agentOptions/maxDepth)。
9319
9007
  const activation = await ctx.subagents.startActivation({
9320
9008
  provider: 'spawn',
@@ -9385,7 +9073,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9385
9073
  }
9386
9074
  } catch (error: any) {
9387
9075
  memberStatus = 'rejected'
9388
- memberError = truncate(String(error?.message ?? error), 300)
9076
+ // [3.0.1][P1b] 宿主并发上限翻译为可行动中文提示(其余错误原样透出)。
9077
+ const friendlyActivationError = describeSubagentActivationError(error, `派发成员 ${assignment.member}`)
9078
+ memberError = truncate(String(friendlyActivationError?.message ?? friendlyActivationError), 300)
9389
9079
  }
9390
9080
  delegates.push({
9391
9081
  member: assignment.member,
@@ -9510,6 +9200,28 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9510
9200
  : '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
9511
9201
  }
9512
9202
  }
9203
+ /*
9204
+ * [3.0.1] 认可闸门硬门禁:被按住(keyword/manual)且未派发的计划,派发一律
9205
+ * 拒绝——这是「未经用户认可不得开跑」的执行侧;唯一的合法出口是
9206
+ * dsh_workplan_release(它登记用户认可留痕后解除闸门并派发)。
9207
+ * 落点在终态闸门之后、deepThink 门禁之前:拒绝不产生副作用。
9208
+ */
9209
+ if (isDispatchHeld(record)) {
9210
+ const snapshot = derivePlanSnapshot(record.statuses)
9211
+ return {
9212
+ ok: false,
9213
+ planId: record.plan.planId,
9214
+ phase: record.phase,
9215
+ running: false,
9216
+ alreadyRunning: false,
9217
+ complete: false,
9218
+ remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
9219
+ stats: snapshot.stats,
9220
+ code: 'DISPATCH_HELD',
9221
+ error: `计划处于认可闸门之下(${truncate(String(record.dispatchHold?.reason ?? '未注明原因'), 200)}):任务要求先经用户认可再执行,在用户明确认可前不得派发。`,
9222
+ hint: '请先征得用户明确认可,然后调用 dsh_workplan_release(可附 note 留痕、附 deepThink 直接开跑);不要用 dsh_workplan_dispatch 绕过闸门。',
9223
+ }
9224
+ }
9513
9225
  /*
9514
9226
  * [2.5.1] 主 Agent 两轮深度思考协议硬门禁(用户 2026-11-11 补充要求)。
9515
9227
  *
@@ -9580,18 +9292,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9580
9292
  * a model that missed the async result message had nothing to integrate.
9581
9293
  * A wedged promise keeps the old stale escape hatch (see below).
9582
9294
  */
9583
- const startedAt = Number(record.dispatchStartedAt ?? 0)
9584
- const staleAfter = limits.totalTimeoutMs > 0 ? limits.totalTimeoutMs + 120000 : NO_ROUND_BUDGET_MS + 120000
9585
- if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
9586
- try {
9587
- await record.dispatchPromise
9588
- } catch (error) {
9589
- pushRecordError(record, error)
9590
- }
9591
- finishRound(record, session)
9592
- state.records.set(session.id, record)
9593
- return dispatchSnapshotOf(record, { joined: true })
9295
+ try {
9296
+ await record.dispatchPromise
9297
+ } catch (error) {
9298
+ pushRecordError(record, error)
9594
9299
  }
9300
+ finishRound(record, session)
9301
+ state.records.set(session.id, record)
9302
+ return dispatchSnapshotOf(record, { joined: true })
9595
9303
  }
9596
9304
  if (record.dispatchPromise) {
9597
9305
  /*
@@ -9604,21 +9312,6 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9604
9312
  * stops claiming the plan is running and hands the work back instead.
9605
9313
  */
9606
9314
  const startedAt = Number(record.dispatchStartedAt ?? 0)
9607
- const staleAfter = limits.totalTimeoutMs > 0 ? limits.totalTimeoutMs + 120000 : NO_ROUND_BUDGET_MS + 120000
9608
- if (startedAt > 0 && Date.now() - startedAt > staleAfter) {
9609
- return {
9610
- ok: false,
9611
- planId: record.plan.planId,
9612
- alreadyRunning: true,
9613
- stale: true,
9614
- startedAt,
9615
- elapsedMs: Date.now() - startedAt,
9616
- phase: record.phase,
9617
- stats: derivePlanSnapshot(record.statuses).stats,
9618
- error: `上一次派发已持续 ${Math.round((Date.now() - startedAt) / 1000)}s 仍未返回,判定为已卡住`,
9619
- hint: '请主 Agent 直接接手完成剩余子任务,不要再次派发;并在答复中说明本次是直接执行而非派发。',
9620
- }
9621
- }
9622
9315
  /*
9623
9316
  * [1.7.0] The idempotent answer now carries the progress itself.
9624
9317
  *
@@ -9798,9 +9491,113 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9798
9491
  return readinessOf(record)
9799
9492
  }
9800
9493
 
9494
+ /**
9495
+ * [3.0.1] 显式认可闸门(双保险中不依赖关键词识别的那一半):主 Agent 在
9496
+ * 派发前把计划按住,用户明确认可后由 dsh_workplan_release 解除并开跑。
9497
+ * 只能设在尚未派发的计划上;已开跑的计划不设闸门(那是取消/重规划语义)。
9498
+ */
9499
+ async function holdTool(agent: any, args: any) {
9500
+ const session = agent?.session
9501
+ if (!session) throw new PlanError('只能在会话内操作计划闸门', 'NO_SESSION')
9502
+ if (!isRootSession(session)) throw new PlanError('子 Agent 不能操作主计划闸门', 'NOT_ROOT')
9503
+ const record = state.records.get(session.id)
9504
+ const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined
9505
+ if (requestedPlanId && record?.plan && record.plan.planId !== requestedPlanId) {
9506
+ throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
9507
+ }
9508
+ if (!record?.plan) throw new PlanError('当前会话没有可操作闸门的计划', 'NO_PLAN')
9509
+ if (isTerminalPhase(record.phase) || record.cancelled === true) {
9510
+ throw new PlanError('计划已是终态,不再设闸门', 'PLAN_TERMINAL')
9511
+ }
9512
+ if (record.dispatchedAt || record.dispatchPromise) {
9513
+ return {
9514
+ ok: false,
9515
+ code: 'ALREADY_RUNNING',
9516
+ planId: record.plan.planId,
9517
+ error: '计划已开跑,闸门只能设在尚未派发的计划上;如需停止执行请取消后重新规划。',
9518
+ }
9519
+ }
9520
+ if (isDispatchHeld(record)) {
9521
+ return { ok: true, alreadyHeld: true, planId: record.plan.planId, hold: record.dispatchHold }
9522
+ }
9523
+ const reason = truncate(String(args?.reason ?? '').trim() || '主 Agent 显式闸门:等待用户认可', 300)
9524
+ record.dispatchHold = { kind: 'manual', reason, at: Date.now(), by: 'agent' }
9525
+ record.updatedAt = record.dispatchHold.at
9526
+ try {
9527
+ appendUserMessage(session, buildUpdateMessage({
9528
+ planId: record.plan.planId,
9529
+ subtaskId: null,
9530
+ status: record.phase,
9531
+ dispatchHold: record.dispatchHold,
9532
+ }))
9533
+ } catch (error) {
9534
+ pushRecordError(record, error)
9535
+ }
9536
+ return { ok: true, planId: record.plan.planId, hold: record.dispatchHold }
9537
+ }
9538
+
9539
+ /**
9540
+ * [3.0.1] 解除认可闸门并立即派发。release 是「用户已明确认可」的唯一合法
9541
+ * 出口:它把按住事实追加进 gateHistory(只增审计,durable 回放),清空
9542
+ * dispatchHold,然后走 dispatchTool 的同一套闸门(终态/deepThink 等照常生效)。
9543
+ * 若 dispatch 因 deepThink 等门禁被拒,闸门保持已解除——认可事实是用户给的,
9544
+ * 不让它人质化;补齐 deepThink 后直接重发 dispatch 即可。
9545
+ */
9546
+ async function releaseTool(agent: any, args: any, signal: any) {
9547
+ const session = agent?.session
9548
+ if (!session) throw new PlanError('只能在会话内操作计划闸门', 'NO_SESSION')
9549
+ if (!isRootSession(session)) throw new PlanError('子 Agent 不能操作主计划闸门', 'NOT_ROOT')
9550
+ const record = state.records.get(session.id)
9551
+ const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined
9552
+ if (requestedPlanId && record?.plan && record.plan.planId !== requestedPlanId) {
9553
+ throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
9554
+ }
9555
+ if (!record?.plan) throw new PlanError('当前会话没有可操作闸门的计划', 'NO_PLAN')
9556
+ if (!isDispatchHeld(record)) {
9557
+ return {
9558
+ ok: false,
9559
+ code: 'NOT_HELD',
9560
+ planId: record.plan.planId,
9561
+ error: '计划不在认可闸门之下:无需解除。要开跑请直接调用 dsh_workplan_dispatch。',
9562
+ }
9563
+ }
9564
+ const hold = record.dispatchHold
9565
+ const note = truncate(String(args?.note ?? '').trim(), 300)
9566
+ const releasedAt = Date.now()
9567
+ record.dispatchHold = null
9568
+ record.gateHistory = [
9569
+ ...(Array.isArray(record.gateHistory) ? record.gateHistory : []),
9570
+ { hold, releasedAt, note, by: 'agent' },
9571
+ ].slice(-10)
9572
+ record.updatedAt = releasedAt
9573
+ try {
9574
+ appendUserMessage(session, buildUpdateMessage({
9575
+ planId: record.plan.planId,
9576
+ subtaskId: null,
9577
+ status: record.phase,
9578
+ dispatchHold: null,
9579
+ gateHistory: record.gateHistory,
9580
+ }))
9581
+ } catch (error) {
9582
+ pushRecordError(record, error)
9583
+ }
9584
+ const dispatched = await dispatchTool(agent, {
9585
+ planId: record.plan.planId,
9586
+ deepThink: args?.deepThink,
9587
+ mode: args?.mode,
9588
+ }, signal)
9589
+ return { ok: dispatched?.ok !== false, gateReleased: true, hold, note, dispatch: dispatched }
9590
+ }
9591
+
9801
9592
  function stopGateApplies(record: any, session?: any, turn?: number) {
9802
9593
  if (!record?.plan) return false
9803
9594
  if (record.degraded) return false
9595
+ /*
9596
+ * [3.0.1] 认可闸门:被按住且未派发的计划是在**等用户拍板**,不是在偷懒。
9597
+ * 此时既不 steer「请派发」(模型只会撞 DISPATCH_HELD 拒绝墙),headless
9598
+ * 也不许按「未完成」硬失败——用户还没认可,谈不上未完成。
9599
+ */
9600
+ if (isDispatchHeld(record) && !record.dispatchedAt) return false
9804
9601
  /*
9805
9602
  * [1.9.0] 终态不再触发收尾 steer —— 这正是死锁的第二个出口(T8 I7)。
9806
9603
  * cancelled 只有在本回合被结构化点名时才提醒一次(present 仍会硬拦);
@@ -9993,6 +9790,28 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
9993
9790
  return false
9994
9791
  }
9995
9792
 
9793
+ /*
9794
+ * [3.0.1] followup/queue 到达时立即取代旧后台规划。
9795
+ *
9796
+ * turn-stopping 正在 await 旧 planning.promise 时,新消息可能尚未进入下一次
9797
+ * pre-step;若只在那里 supersede,旧规划仍会跑完并迟到交付。官方
9798
+ * `agent/inbox/inserted` 在消息进入 live inbox 时即发本事件,因此这里先中止。
9799
+ * 内部 workplan 通知、社交/状态/空泛续跑均不取消;同任务重复投递保持幂等。
9800
+ */
9801
+ function onInboxInserted(payload: any) {
9802
+ const session = payload?.agent?.session
9803
+ if (!session || !isRootSession(session)) return
9804
+ const planning = state.planningInFlight?.get(session.id)
9805
+ if (!planning) return
9806
+ const message = payload?.message
9807
+ if (humanMessages([message]).length === 0) return
9808
+ const taskText = taskTextFromMessages([message])
9809
+ if (!taskText || isSocialMessage(taskText) || isVagueContinuation(taskText) || isStatusQuestion(taskText)) return
9810
+ if (planning.taskText === taskText) return
9811
+ planning.superseded = true
9812
+ planning.controller.abort()
9813
+ }
9814
+
9996
9815
  async function onTurnStopping(payload: any) {
9997
9816
  try {
9998
9817
  const agent = payload?.agent
@@ -10007,13 +9826,44 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
10007
9826
  * 了本计划的续跑输入,必须受同一道收尾闸门约束。
10008
9827
  */
10009
9828
  if (state.activeTurns?.get?.(session.id) !== turn && !turnCarriesPlanWork(session, turn, known)) return
10010
- if (isPlanModeActive(ctx, session)) return
10011
- let record = known
10012
- if (!record?.plan) {
9829
+ /*
9830
+ * [3.0.1] 后台规划必须和本回合闭环,不能只靠“请勿提前收尾”的软提示。
9831
+ * 规划期间 record.plan 为空,旧 stopGateApplies 会直接放行;先等当前规划
9832
+ * 承诺结算,再读取最新 record,避免主 Agent 在计划出现前答复并停止回合。
9833
+ */
9834
+ let record = state.records.get(session.id) ?? known
9835
+ const planning = state.planningInFlight?.get(session.id)
9836
+ if (planning?.promise) {
9837
+ try { await planning.promise } catch { /* 后台规划自身已记录降级/错误 */ }
9838
+ /*
9839
+ * 等待期间若同回合后续 step 已用新任务取代旧规划,本次旧收尾必须退出;
9840
+ * 新规划的收尾会自行等待并交回,绝不能在这里消费旧结果或误 steer。
9841
+ */
9842
+ const latestPlanning = state.planningInFlight?.get(session.id)
9843
+ if (latestPlanning && latestPlanning !== planning) return
9844
+ record = state.records.get(session.id) ?? reconstructFromSession(session) ?? record
9845
+ }
9846
+ if (!record?.plan && record?.planningCompletionPending !== true) {
10013
9847
  // [1.8.14] N5:优先按本回合结算消息里点名的计划重建,而不是最后生成的计划。
10014
- record = reconstructFromSession(session, planIdFromTurn(session, turn))
9848
+ // 后台降级/澄清虽然没有 plan,也必须先交回主 Agent,不能被旧回放覆盖。
9849
+ record = reconstructFromSession(session, planIdFromTurn(session, turn)) ?? record
10015
9850
  if (record?.plan) state.records.set(session.id, record)
10016
9851
  }
9852
+ /*
9853
+ * 即使规划在 turn-stopping 前已完成,也必须把结果交回主 Agent 消费一次。
9854
+ * 标记只挂在后台规划的终态 record 上;held 计划下一步仍等待用户认可,
9855
+ * 不会落入普通“未完成计划”循环。plan mode 也要先完成这次交回。
9856
+ */
9857
+ if (Number(record?.createdTurn ?? record?.plan?.createdTurn) === turn && record?.planningCompletionPending === true) {
9858
+ record.planningCompletionPending = false
9859
+ agent.steer(makeUserMessage([
9860
+ '【后台规划结果待处理】任务分解已经结束,结果已写入本会话。',
9861
+ '请立即读取最新结果并据此继续:若计划已生成,先向用户展示计划并遵守其中的认可闸门或派发要求;若处于认可闸门,只能针对这份已生成的计划请求认可,不得再说“计划尚未生成”;若规划降级或需要澄清,如实说明原因并提出下一步。',
9862
+ '不得把本回合停留在“计划仍在生成”的旧状态。',
9863
+ ].join('\n'), { kind: 'workplan-planning-complete', form: 'notice' }))
9864
+ return
9865
+ }
9866
+ if (isPlanModeActive(ctx, session)) return
10017
9867
  if (!stopGateApplies(record, session, turn)) return
10018
9868
  if (record.dispatchPromise) {
10019
9869
  try {
@@ -10745,6 +10595,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
10745
10595
  state,
10746
10596
  limits,
10747
10597
  onPreStep,
10598
+ onInboxInserted,
10748
10599
  onTurnStopping,
10749
10600
  presentDenialReason,
10750
10601
  presentDenialVerdict,
@@ -10754,6 +10605,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
10754
10605
  updateStatus,
10755
10606
  cancelPlan,
10756
10607
  dispatchTool,
10608
+ holdTool,
10609
+ releaseTool,
10757
10610
  statusTool,
10758
10611
  followupTool,
10759
10612
  escalateTool,
@@ -10825,7 +10678,13 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
10825
10678
  /* 合并失败不拦规划:下一次落盘/结算再试。 */
10826
10679
  }
10827
10680
  if (!isRootSession(session)) return downstream
10828
- if (payload.step !== 1) return downstream
10681
+ /*
10682
+ * 后续 step 通常是工具续跑,不能重复规划;但后台规划未结算时,DSH 会把
10683
+ * steering/followup 的新人类任务作为同回合下一 step 送达(官方生命周期:
10684
+ * next-step input → pre-step)。此时必须进入下方分类与 supersede,否则新任务
10685
+ * 被静默跳过、旧计划随后迟到覆盖。相同 taskText 仍会在下方去重返回。
10686
+ */
10687
+ if (payload.step !== 1 && !state.planningInFlight?.get(session.id)) return downstream
10829
10688
  // [2.5.5][T3] pre-step 窗口标记:规划/自动派发的头前通知一律暂存(治本)。
10830
10689
  enterPreHeadWindow(session)
10831
10690
  const planMode = isPlanModeActive(ctx, session)
@@ -10853,6 +10712,16 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
10853
10712
  */
10854
10713
  if (!state.activeTurns) state.activeTurns = new Map()
10855
10714
  state.activeTurns.set(session.id, Number(payload.turn ?? 0))
10715
+ /*
10716
+ * 新的真实任务到达时,旧任务的后台规划不得再迟到覆盖新任务。
10717
+ * 社交/状态消息在上方已提前返回,不会误取消;同一任务的重复 pre-step 只去重。
10718
+ */
10719
+ const priorPlanning = state.planningInFlight?.get(session.id)
10720
+ if (priorPlanning) {
10721
+ if (priorPlanning.taskText === taskText) return downstream
10722
+ priorPlanning.superseded = true
10723
+ priorPlanning.controller.abort()
10724
+ }
10856
10725
  const conversationContext = recentConversation(session)
10857
10726
  if (existing?.plan?.createdTurn === payload.turn) return downstream
10858
10727
  /*
@@ -10878,6 +10747,12 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
10878
10747
  // until the user leaves plan mode and dispatches it. Cancelling it here
10879
10748
  // would make the plan disappear before the main Agent can act on approval.
10880
10749
  if (existing?.plan && existing.planMode && !existing.dispatchedAt) return downstream
10750
+ /*
10751
+ * [3.0.1] 认可闸门同理:被按住等用户认可的计划不得被下一条用户消息自动
10752
+ * 取消(wp-e745a477 事故:主 Agent 正在等用户回复,计划已被自动派发出去;
10753
+ * 修复后若计划被闸门按住,保护它活到用户答复、release 放行)。
10754
+ */
10755
+ if (existing?.plan && isDispatchHeld(existing) && !existing.dispatchedAt) return downstream
10881
10756
  // A plan committed but not yet dispatched must not be overwritten in the
10882
10757
  // same turn; a later turn may supersede it, otherwise one abandoned plan
10883
10758
  // would lock planning forever.
@@ -10968,6 +10843,16 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
10968
10843
  })])
10969
10844
  }
10970
10845
  }
10846
+ /*
10847
+ * [3.0.1] 认可闸门:任务锚点要求「先经用户认可再执行」时,计划照出、按住不派。
10848
+ * 识别结果随本函数流入计划创建尾(approvalGateVerdict):创建时写入
10849
+ * record.dispatchHold、跳过 autoDispatch,直到用户明确认可、主 Agent 调用
10850
+ * dsh_workplan_release。DSH_WORKPLAN_APPROVAL_GATE=0 时识别关闭(显式
10851
+ * 闸门 dsh_workplan_hold 不受影响)。
10852
+ */
10853
+ const approvalGateVerdict = approvalGateDetectionDisabled()
10854
+ ? { held: false as const, matched: [] as any[], reason: '' }
10855
+ : detectApprovalGate(taskText)
10971
10856
  const modelSelection = resolveModelSelection(ctx, payload)
10972
10857
  if (!modelSelection?.provider || !modelSelection?.model) {
10973
10858
  const message = buildDegradedMessage({
@@ -11086,12 +10971,24 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11086
10971
  }
11087
10972
  }
11088
10973
  if (!state.planningInFlight) state.planningInFlight = new Map()
11089
- if (state.planningInFlight.has(session.id)) return downstream
11090
- state.planningInFlight.set(session.id, planningStartedAt)
10974
+ const planningController = new AbortController()
10975
+ const forwardPayloadAbort = () => planningController.abort()
10976
+ if (payload.signal.aborted) planningController.abort()
10977
+ else payload.signal.addEventListener('abort', forwardPayloadAbort, { once: true })
10978
+ const planningSignal = planningController.signal
10979
+ const planningEntry: any = {
10980
+ startedAt: planningStartedAt,
10981
+ turn: payload.turn,
10982
+ taskText,
10983
+ controller: planningController,
10984
+ superseded: false,
10985
+ promise: null,
10986
+ }
10987
+ state.planningInFlight.set(session.id, planningEntry)
11091
10988
  const runPlanningInBackground = async (): Promise<void> => {
11092
10989
  let plannerAttempt = 1
11093
10990
  const onPlannerProgress = createPlannerProgressReporter({
11094
- signal: payload.signal,
10991
+ signal: planningSignal,
11095
10992
  record: planningRecord,
11096
10993
  setRecord: (record: any) => state.records.set(session.id, record),
11097
10994
  appendNotice: (text: string) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
@@ -11107,7 +11004,7 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11107
11004
  * 不触碰 system/message,不会引入会话日志损坏;finally 里 stop,绝不残留。
11108
11005
  */
11109
11006
  const planningHeartbeat = createPlanningHeartbeat({
11110
- signal: payload.signal,
11007
+ signal: planningSignal,
11111
11008
  appendNotice: (text: string) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
11112
11009
  intervalMs: planningHeartbeatIntervalMs(process.env.DSH_WORKPLAN_PLANNING_HEARTBEAT_MS ?? PLANNING_HEARTBEAT_MS),
11113
11010
  startedAt: planningStartedAt,
@@ -11121,7 +11018,7 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11121
11018
  cwd: session.header?.cwd ?? options.cwd,
11122
11019
  sessionId: session.id,
11123
11020
  modelSelection,
11124
- signal: payload.signal,
11021
+ signal: planningSignal,
11125
11022
  plannerTimeoutMs: normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
11126
11023
  plannerIdleTimeoutMs: normalisePlannerWindow(options?.limits?.plannerIdleTimeoutMs ?? options?.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
11127
11024
  telemetry: plannerTelemetry,
@@ -11137,30 +11034,21 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11137
11034
  },
11138
11035
  conversationContext,
11139
11036
  sourceMessageIds: human.map((message: any) => message.id).filter((id: any) => typeof id === 'string'),
11140
- /*
11141
- * Hand the real limits to the planner. Without them it had no idea the
11142
- * round budget was 20 minutes and happily planned 15 heavy subtasks,
11143
- * which then died at the budget wall. The prompt now states the budget
11144
- * and asks for `estimateMinutes` on every subtask.
11145
- */
11037
+ // 旧 totalTimeoutMs/childTimeoutMs 配置不再注入规划器;只保留非时间资源约束。
11146
11038
  budget: {
11147
- totalMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
11148
- ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
11149
- : 0,
11150
- childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
11039
+ totalMinutes: 0,
11040
+ childMinutes: 0,
11151
11041
  concurrency: MAX_CONCURRENT,
11152
11042
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
11153
11043
  },
11154
11044
  })
11155
11045
  } catch (error) {
11156
- if (payload.signal.aborted) {
11046
+ if (planningSignal.aborted) {
11157
11047
  /*
11158
- * [2.2.5][T5] 用户中止:静默退出(T3 §2 中止分支,不发通知)。占位卡片
11159
- * 若本轮前无旧记录,交给 serialisePlan 终态收敛转 'ended',不留假
11160
- * 「进行中」;若本轮前已有旧计划记录,恢复它——中止不该把用户上一份
11161
- * 终态进度从内存里挤掉(旧实现中止路径不写记录,此行为保持不变)。
11048
+ * 用户中止或被新任务取代都静默退出;后者尤其不得恢复旧计划、写降级通知,
11049
+ * 否则已取消的旧规划会迟到覆盖新任务的占位记录。
11162
11050
  */
11163
- if (existing?.plan) state.records.set(session.id, existing)
11051
+ if (!planningEntry.superseded && existing?.plan) state.records.set(session.id, existing)
11164
11052
  return
11165
11053
  }
11166
11054
  /*
@@ -11184,12 +11072,14 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11184
11072
  createdAt,
11185
11073
  updatedAt: createdAt,
11186
11074
  createdTurn: payload.turn,
11075
+ planningCompletionPending: true,
11187
11076
  })
11188
- return enterDecision(downstream, [buildClarifyMessage({
11077
+ deliver([buildClarifyMessage({
11189
11078
  rule: 'AUDIT',
11190
11079
  reason: error.message,
11191
11080
  question: typeof error.details === 'string' && error.details.trim() !== '' ? error.details : '',
11192
11081
  })])
11082
+ return
11193
11083
  }
11194
11084
  const planId = `wp-${randomUUID()}`
11195
11085
  const createdAt = Date.now()
@@ -11215,6 +11105,7 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11215
11105
  createdAt,
11216
11106
  updatedAt: createdAt,
11217
11107
  createdTurn: payload.turn,
11108
+ planningCompletionPending: true,
11218
11109
  })
11219
11110
  return deliver([message])
11220
11111
  } finally {
@@ -11222,13 +11113,19 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11222
11113
  planningHeartbeat.stop()
11223
11114
  }
11224
11115
 
11225
- if (payload.signal.aborted) {
11226
- // [2.2.5][T5] 计划已生成但回合被中止:同中止分支,恢复旧记录再静默退出。
11227
- if (existing?.plan) state.records.set(session.id, existing)
11116
+ if (planningSignal.aborted) {
11117
+ // 用户中止或新任务取代:旧规划结果不得再落入会话。
11118
+ if (!planningEntry.superseded && existing?.plan) state.records.set(session.id, existing)
11228
11119
  return
11229
11120
  }
11230
11121
  const planId = `wp-${randomUUID()}`
11231
11122
  const createdAt = Date.now()
11123
+ /*
11124
+ * [3.0.1] 认可闸门:任务锚点命中「先经用户认可再执行」门槛语时,计划照出、
11125
+ * 按住不派(dispatchHold 落档),直到用户明确认可、主 Agent 调用
11126
+ * dsh_workplan_release。必须在 record 字面量之前声明——字面量引用了它。
11127
+ */
11128
+ const approvalHeld = !planMode && approvalGateVerdict.held
11232
11129
  const fullPlan = attachPlanMeta(plan, {
11233
11130
  planId,
11234
11131
  sessionId: session.id,
@@ -11251,14 +11148,33 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11251
11148
  modelSelection,
11252
11149
  conversationContext,
11253
11150
  planMode,
11151
+ planningCompletionPending: true,
11152
+ /*
11153
+ * [3.0.1] 认可闸门落档:keyword=任务锚点命中门槛语;manual=dsh_workplan_hold
11154
+ * 显式按住。release 置 null(事实本身追加进 gateHistory 审计)。
11155
+ */
11156
+ ...(approvalHeld
11157
+ ? {
11158
+ dispatchHold: {
11159
+ kind: 'keyword',
11160
+ reason: approvalGateVerdict.reason,
11161
+ at: createdAt,
11162
+ by: 'system',
11163
+ },
11164
+ }
11165
+ : {}),
11254
11166
  }
11255
11167
  state.records.set(session.id, record)
11256
11168
  /*
11257
11169
  * [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
11258
11170
  * async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
11259
11171
  * plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
11172
+ *
11173
+ * [3.0.1] 认可闸门(approvalHeld,声明见 record 字面量之前):任务锚点命中
11174
+ * 「先经用户认可再执行」门槛语时同样不自动派发——用户明确认可、主 Agent
11175
+ * 调用 dsh_workplan_release 之前,计划只展示、任何派发都被拒。
11260
11176
  */
11261
- const autoDispatched = !planMode && options?.autoDispatch !== false
11177
+ const autoDispatched = !planMode && !approvalHeld && options?.autoDispatch !== false
11262
11178
  /*
11263
11179
  * Plan-first: commit the plan with this step and let the main Agent call
11264
11180
  * dsh_workplan_dispatch. Dispatching here would hide the plan until every
@@ -11272,12 +11188,11 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11272
11188
  * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
11273
11189
  */
11274
11190
  const planMessage = buildPlanMessage(fullPlan, {
11275
- totalBudgetMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
11276
- ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
11277
- : 0,
11191
+ totalBudgetMinutes: 0,
11278
11192
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
11279
11193
  planMode,
11280
11194
  autoDispatched,
11195
+ approvalHeld,
11281
11196
  })
11282
11197
  /*
11283
11198
  * [3.0.0][顺序] 必须先让计划可见,再开跑、再发「分配完成」:
@@ -11286,6 +11201,35 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11286
11201
  * 先 deliver 计划消息,再启动自动派发。
11287
11202
  */
11288
11203
  if (!planMode) {
11204
+ if (approvalHeld) {
11205
+ /*
11206
+ * [3.0.1] 认可闸门:durable 落档(与 mainDeepThink 同一写入口径,
11207
+ * subtaskId=null 计划级)——刷新/重启后回放读档,闸门不丢;
11208
+ * 随后发用户可见通知,计划保持 phase=pending、不派发。
11209
+ */
11210
+ try {
11211
+ appendUserMessage(session, buildUpdateMessage({
11212
+ planId: fullPlan.planId,
11213
+ subtaskId: null,
11214
+ status: record.phase,
11215
+ dispatchHold: record.dispatchHold,
11216
+ }))
11217
+ } catch (error) {
11218
+ pushRecordError(record, error)
11219
+ }
11220
+ deliver([
11221
+ planMessage,
11222
+ makeUserMessage(
11223
+ [
11224
+ '🔒 认可闸门已生效:您的任务要求「先经用户认可再执行」,本计划已生成但暂不分派任务。',
11225
+ `命中依据:${approvalGateVerdict.reason}`,
11226
+ '在您明确回复认可之前,任何派发(自动或手动)都会被拒绝;您认可后,请告知主 Agent 调用 dsh_workplan_release 开跑。',
11227
+ ].join('\n'),
11228
+ { kind: 'workplan-hold', form: 'notice', summary: '认可闸门已生效:等待用户认可后再派发' },
11229
+ ),
11230
+ ])
11231
+ return
11232
+ }
11289
11233
  deliver([planMessage])
11290
11234
  if (autoDispatched) {
11291
11235
  record.dispatchedAt = Date.now()
@@ -11313,15 +11257,21 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
11313
11257
  }
11314
11258
  return deliver([planMessage, note])
11315
11259
  }
11316
- void (async () => {
11260
+ const planningPromise = (async () => {
11317
11261
  try {
11318
11262
  await runPlanningInBackground()
11319
11263
  } catch (error) {
11320
- pushRecordError(planningRecord, error)
11264
+ if (!planningEntry.superseded) pushRecordError(planningRecord, error)
11321
11265
  } finally {
11322
- state.planningInFlight.delete(session.id)
11266
+ payload.signal.removeEventListener('abort', forwardPayloadAbort)
11267
+ // 旧任务被取代后,只能清理自己的登记,不能删掉新任务的 in-flight。
11268
+ if (state.planningInFlight.get(session.id) === planningEntry) {
11269
+ state.planningInFlight.delete(session.id)
11270
+ }
11323
11271
  }
11324
11272
  })()
11273
+ planningEntry.promise = planningPromise
11274
+ void planningPromise
11325
11275
  /*
11326
11276
  * 同步注入给本步模型的说明:先等计划,不要自己动手做用户的活。文案复用
11327
11277
  * 用户逐字冻结的 STATUS_ASSIGNING_TEXT,不另造第二份固定文案。