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/CHANGELOG.md +51 -0
- package/README.en.md +20 -18
- package/README.md +33 -19
- package/README.zh.md +15 -19
- package/client.js +36 -67
- package/docs/cc/ADV-FSP-FUNCTIONAL-SPEC.md +16 -3
- package/docs/cc/ADV-TDS-TOE-DESIGN.md +3 -3
- package/docs/cc/AGD-OPS-SECURE-OPERATION.md +3 -7
- package/docs/cc/AVA-VULNERABILITY-ANALYSIS.md +19 -0
- package/docs/cc/SECURITY-TARGET.md +6 -6
- package/docs/collaboration.md +17 -16
- package/lib/approval-gate.js +144 -0
- package/lib/client.js +36 -67
- package/lib/criterion.js +22 -27
- package/lib/host.js +178 -40
- package/lib/llm-rules.js +2 -2
- package/lib/plan.js +176 -85
- package/lib/runtime.js +756 -829
- package/lib/watchdog.js +3 -0
- package/package.json +3 -2
- package/src/approval-gate.ts +168 -0
- package/src/client.ts +36 -67
- package/src/criterion.ts +22 -23
- package/src/host.ts +185 -40
- package/src/llm-rules.ts +2 -2
- package/src/plan.ts +166 -83
- package/src/runtime.ts +643 -693
- package/src/watchdog.ts +7 -0
package/lib/runtime.js
CHANGED
|
@@ -41,7 +41,7 @@ parseUpdateMessages, flushPendingWorkplanUpdates, buildUpdateMessage, normaliseH
|
|
|
41
41
|
import { STATUS_ASSIGNED_TEXT, STATUS_ASSIGNING_TEXT, checkExpertReport, checkSubtaskQualityRequirements, isQualityGatePlan } from './v3-contract.js';
|
|
42
42
|
// [SCv2-T4] 判据层单一真源(用户 2026-11-13 裁决 B/B/B/B/A/A/B):生效边界 D-1、
|
|
43
43
|
// 例外批准 Q1-B、结算三选一 §3.5、单次墙钟 Q6-A、事前聚合 Q4-B。运行层常量不改。
|
|
44
|
-
import {
|
|
44
|
+
import { appendCriterionViolation, attemptWallClockMsOf, criterionExAnte, criterionV2Active, evaluateCriterion, sanitizeCriterionException, } from './criterion.js';
|
|
45
45
|
import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js';
|
|
46
46
|
// [2.3.9][T3] LLM 家族检测 + 推理等级静态约束(用户强制要求 1/2;详见 llm-rules.ts 头注释)。
|
|
47
47
|
// [2.3.9][T4b] 追加第三层派发纯逻辑核:buildLlmRulesBrief(要求 1/2 全文告知注入,
|
|
@@ -54,6 +54,14 @@ import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js
|
|
|
54
54
|
import { supersedePlanRecord } from './supersede.js';
|
|
55
55
|
import { createProgressWatchdog, describeError } from './watchdog.js';
|
|
56
56
|
import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume, liveResumeCounts } from './auto-resume.js';
|
|
57
|
+
/*
|
|
58
|
+
* [3.0.1] 认可闸门 + 死锁自愈(approval-gate.ts):
|
|
59
|
+
* detectApprovalGate —— 任务锚点里的「先经认可再执行」门槛语识别
|
|
60
|
+
* approvalGateDetectionDisabled —— DSH_WORKPLAN_APPROVAL_GATE=0 总开关
|
|
61
|
+
* isDispatchHeld —— 计划是否被按住不得派发
|
|
62
|
+
* buildChildRevivePatch —— escalated 行子会话失联时的复活补丁(纯函数)
|
|
63
|
+
*/
|
|
64
|
+
import { approvalGateDetectionDisabled, buildChildRevivePatch, detectApprovalGate, isDispatchHeld, } from './approval-gate.js';
|
|
57
65
|
import { applyReplanStatuses, buildChangeRequestMessage, buildReplanMessage, parseChangeRequestMessage, parseReplanMessage, planReplan, } from './replan.js';
|
|
58
66
|
/**
|
|
59
67
|
* [1.8.18] How many subtasks the plan *defines*.
|
|
@@ -121,6 +129,110 @@ function liveStatuses(statuses) {
|
|
|
121
129
|
* `deriveReportPending(record)`:事实只有 statuses(经 T2 单调闸的终态),
|
|
122
130
|
* 标志降级为审计镜像。blocked/pending 行不是 done,永不触发该阻塞。
|
|
123
131
|
*/
|
|
132
|
+
/*
|
|
133
|
+
* [3.0.1][P0 冲突修复] 跨版本兼容的「continuable 中断」。
|
|
134
|
+
*
|
|
135
|
+
* DSH 0.2.2-rc.3 起旧 API `subagents.interruptByParent(childId, parentId,
|
|
136
|
+
* 'continuable')` 已被 `subagents.interrupt(targetSessionId, authority)`
|
|
137
|
+
* 取代(dsh-subagent/src/manager.ts):authority = { kind:'ancestor', agent }
|
|
138
|
+
* 携带中断方的**活体 Agent 对象**(必须是目标会话祖先树内的活体 Agent,
|
|
139
|
+
* 否则宿主抛 UNAUTHORIZED)。新 API 的 local 分支语义与旧 'continuable'
|
|
140
|
+
* 完全等价:agent.cancel({ kind:'parent' }, { keepInbox:true }) —— 中断
|
|
141
|
+
* 当前回合但保留收件箱,可被后续接续重新驱动。
|
|
142
|
+
*
|
|
143
|
+
* 策略:优先新 API;宿主为旧版本时回退旧 API(保留旧测试夹具与旧宿主
|
|
144
|
+
* 可用性);两者皆无或 authority 不成立时返回 false(与修复前静默跳过
|
|
145
|
+
* 同口径,调用方均有接续兜底,绝不因中断失败阻断主链路)。
|
|
146
|
+
*/
|
|
147
|
+
export function interruptChildContinuable(subagents, childSessionId, ancestorAgent, ancestorIdFallback) {
|
|
148
|
+
if (subagents == null || typeof childSessionId !== 'string' || childSessionId.length === 0)
|
|
149
|
+
return false;
|
|
150
|
+
try {
|
|
151
|
+
if (typeof subagents.interrupt === 'function') {
|
|
152
|
+
// 新 API 要求 authority.agent 是目标会话祖先的活体 Agent 对象。
|
|
153
|
+
if (ancestorAgent == null || typeof ancestorAgent !== 'object')
|
|
154
|
+
return false;
|
|
155
|
+
subagents.interrupt(childSessionId, { kind: 'ancestor', agent: ancestorAgent });
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
// 旧版宿主(DSH < 0.2.2-rc.3)回退:interruptByParent(childId, parentId, 'continuable')。
|
|
159
|
+
// ancestorAgent 无 string id(旧测试夹具的裸 stub)时退用调用方提供的祖先会话 id。
|
|
160
|
+
if (typeof subagents.interruptByParent === 'function') {
|
|
161
|
+
const ancestorId = typeof ancestorAgent?.id === 'string' && ancestorAgent.id.length > 0
|
|
162
|
+
? ancestorAgent.id
|
|
163
|
+
: ancestorIdFallback;
|
|
164
|
+
if (typeof ancestorId !== 'string' || ancestorId.length === 0)
|
|
165
|
+
return false;
|
|
166
|
+
subagents.interruptByParent(childSessionId, ancestorId, 'continuable');
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// 中断失败不阻断接续(沿用原 try/catch 口径):接续由调用方兜底保证。
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/*
|
|
177
|
+
* [3.0.1][P1a 冲突修复] 宿主 subagent.maxDepth 设置与本插件三层体系的冲突检测。
|
|
178
|
+
*
|
|
179
|
+
* 宿主设置页「subagent.maxDepth」默认 1,但宿主 manager 的判定是
|
|
180
|
+
* resolveChildDepth(parent, spec.maxDepth):调用方(本插件)显式传了
|
|
181
|
+
* maxDepth:2 时该设置被架空——插件放行 depth 2 成员,其余 subagent 调用方
|
|
182
|
+
* 仍受设置约束。这本身可运行(插件派发按 spec 为准),但用户看到的设置
|
|
183
|
+
* 与实际行为不一致,属于配置矛盾。此处检测「宿主配置值 < 插件要求的最小
|
|
184
|
+
* 深度 2」并生成一次性告警文案(同一 scopeId 只告警一次,避免刷屏);
|
|
185
|
+
* 调用方负责把文案投递给用户可见会话。返回 null = 无冲突或已告警过。
|
|
186
|
+
*/
|
|
187
|
+
const depthOverrideWarnedScopes = new Set();
|
|
188
|
+
export function detectDepthOverrideConflict(subagents, scopeId) {
|
|
189
|
+
if (typeof scopeId !== 'string' || scopeId.length === 0)
|
|
190
|
+
return null;
|
|
191
|
+
if (depthOverrideWarnedScopes.has(scopeId))
|
|
192
|
+
return null;
|
|
193
|
+
let configured;
|
|
194
|
+
try {
|
|
195
|
+
configured = typeof subagents?.resolveMaxDepth === 'function' ? subagents.resolveMaxDepth() : undefined;
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
// 未配置 / 无限深度 / 已 ≥2:无冲突。
|
|
201
|
+
if (typeof configured !== 'number' || !Number.isFinite(configured) || configured >= 2)
|
|
202
|
+
return null;
|
|
203
|
+
depthOverrideWarnedScopes.add(scopeId);
|
|
204
|
+
return `【dsh-workplan·深度设置说明】检测到设置页「子代理最大深度」(subagent.maxDepth)当前为 ${configured}。该上限**只约束内置 subagent/subagent_fork 工具**;本插件的三层体系(你 → 部门负责人 → 专家)按派发契约固定需要第 2 层深度,宿主对该契约单独放行,不受此设置影响——这是设计使然,你的负责人派发给专家的流程在任何设置下都正常工作。若你的意图是「完全禁止子代理」,请直接停用本插件;若只是想让设置页显示与插件行为一致,可把该设置调到 2(立即生效,重启后恢复默认 1)。`;
|
|
205
|
+
}
|
|
206
|
+
// 检测并把冲突告警投递到指定会话(best-effort:任何失败不阻断派发主链路)。
|
|
207
|
+
function notifyDepthOverrideConflict(ctx, scopeId) {
|
|
208
|
+
const text = detectDepthOverrideConflict(ctx?.subagents, scopeId);
|
|
209
|
+
if (!text)
|
|
210
|
+
return;
|
|
211
|
+
try {
|
|
212
|
+
const session = ctx?.sessions?.get?.(scopeId);
|
|
213
|
+
appendUserMessage(session, text);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
/* 告警投递失败不影响派发 */
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/*
|
|
220
|
+
* [3.0.1][P1b 冲突修复] 宿主子代理并发上限错误的友好翻译。
|
|
221
|
+
*
|
|
222
|
+
* 宿主对超过 subagent.maxActiveSubagents(默认 8,按会话树共享)的派发抛
|
|
223
|
+
* SubagentError(code='ACTIVATION_LIMIT_REACHED', message="subagent limit
|
|
224
|
+
* reached (active child limit: N)")。原样透出会让用户看到英文宿主错误且
|
|
225
|
+
* 无从行动;此处翻译为可行动的中文提示(重试 / 调大设置)。非该错误时
|
|
226
|
+
* 原样返回传入错误(不吞错、不改类型),由调用方决定如何包装。
|
|
227
|
+
*/
|
|
228
|
+
export function describeSubagentActivationError(error, context) {
|
|
229
|
+
const code = String(error?.code ?? '');
|
|
230
|
+
const raw = String(error?.message ?? error ?? '');
|
|
231
|
+
if (code === 'ACTIVATION_LIMIT_REACHED' || /limit reached/i.test(raw)) {
|
|
232
|
+
return new PlanError(`${context}:子代理并发数已达宿主上限(设置项 subagent.maxActiveSubagents,整个会话树共享)。请稍后重试(让在跑的任务先完成),或在「设置 → 子代理」中调大该上限。`, 'ACTIVATION_LIMIT_REACHED');
|
|
233
|
+
}
|
|
234
|
+
return error instanceof Error ? error : new Error(raw || String(error));
|
|
235
|
+
}
|
|
124
236
|
export function deriveReportPending(record) {
|
|
125
237
|
const statuses = Array.isArray(record?.statuses) ? record.statuses : [];
|
|
126
238
|
/*
|
|
@@ -273,69 +385,36 @@ export async function resolveSupportedEfforts(llm, provider, model, signal) {
|
|
|
273
385
|
return null;
|
|
274
386
|
}
|
|
275
387
|
}
|
|
276
|
-
|
|
277
|
-
*
|
|
278
|
-
*
|
|
279
|
-
* 300 000 ms used to be the *only* limit, and because it was purely a wall
|
|
280
|
-
* clock it killed healthy work: a child that needed one more minute was
|
|
281
|
-
* recorded as blocked, `markDependentsBlocked` blocked every dependent, and the
|
|
282
|
-
* plan became terminal at the first slow subtask. The ceiling is now a
|
|
283
|
-
* settlement guarantee, while the no-progress window below is what normally
|
|
284
|
-
* ends an attempt.
|
|
285
|
-
*
|
|
286
|
-
* [2.2.0][T4/O-3b] 语义更新(柔性时长协商,方案 §1③/§2.2):这不是固定交付
|
|
287
|
-
* 期限,而是「协商上限+L4 安全兜底」——单次执行时限协商而来(subtask.timeoutMs
|
|
288
|
-
* 显式值优先,缺省 deriveSubtaskTimeoutMs(estimateMinutes)=clamp(预估分钟×
|
|
289
|
-
* 2.0×60000, MIN, MAX)),本常量只在无预估、无显式值时兜底(③C2 零回归)。
|
|
290
|
-
* 时间是协商出来的安全兜底,不是固定交付期限:到点走 L4 安全兜底结算+
|
|
291
|
-
* 「待裁决」标记(延期 / 重试 / 接受),不表述为「强制结束」式固定期限误杀。
|
|
388
|
+
/*
|
|
389
|
+
* [3.0.1] 历史时间常量,仅供旧数据回放、纯函数审计与兼容测试读取。
|
|
292
390
|
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
*
|
|
296
|
-
*
|
|
297
|
-
* 未批准),未批准时按判据层未达标处理(不 done、转接替子任务)。
|
|
391
|
+
* 生产执行不再调用 resolveSubtaskTimeoutMs,也不会用这些值创建计时器。
|
|
392
|
+
* 部门负责人和全球顶尖专家的正式执行没有墙钟、空闲、回执或整轮截止;
|
|
393
|
+
* timeoutMs / extendMs 即使出现在旧计划中也不会重新生效。保留数值是为了
|
|
394
|
+
* 让旧计划、旧日志和旧测试仍能解释当时发生的事,而不是允许重新启用限制。
|
|
298
395
|
*/
|
|
299
396
|
export const CHILD_TIMEOUT_MS = 900000;
|
|
300
|
-
/** No-progress window: the child's own session log stopped growing. */
|
|
301
397
|
export const CHILD_IDLE_TIMEOUT_MS = 300000;
|
|
302
|
-
/*
|
|
303
|
-
* Floors exist to reject zero, negative and absurdly small values, not to
|
|
304
|
-
* overrule an operator. The defaults above are what production uses; a floor of
|
|
305
|
-
* 1s keeps diagnostics and tests able to exercise the timers without waiting
|
|
306
|
-
* minutes.
|
|
307
|
-
*/
|
|
308
398
|
export const MIN_CHILD_TIMEOUT_MS = 1000;
|
|
309
|
-
/*
|
|
310
|
-
* [2.2.0][T4/O-3b] 单次绝对上限 1800000 → 7200000(120 分钟):用户 2026-11-07
|
|
311
|
-
* 决断(方案 §6 未知第 4 条)。协商上限 = clamp(预估分钟 × 2.0, 全局下限,
|
|
312
|
-
* 单次绝对上限)(方案 §1③),2h 让「预告 60 分钟的子任务,其单次执行上限
|
|
313
|
-
* ≥ 60 分钟」(方案 C1)成立;tests/time-estimate-negotiation.test.ts 的
|
|
314
|
-
* expected 公式直接引用本常量,数值不同步会红灯。
|
|
315
|
-
*
|
|
316
|
-
* [2.6.0][Q7-B] 分层声明:120 分钟是运行层安全兜底(防失控),不是时长许可;
|
|
317
|
-
* 判据层完成目标为 ≤10 分钟(Q1/Q4),两层互不取代,数值与公式零改动。
|
|
318
|
-
*/
|
|
319
399
|
export const MAX_CHILD_TIMEOUT_MS = 7200000;
|
|
320
400
|
export const MIN_CHILD_IDLE_MS = 1000;
|
|
321
401
|
export const MAX_CHILD_IDLE_MS = 900000;
|
|
322
402
|
export const CHILD_POLL_MS = 2000;
|
|
323
403
|
/*
|
|
324
|
-
* [
|
|
404
|
+
* [3.0.1] 派发回执只剩提示,没有硬截止。
|
|
325
405
|
*
|
|
326
|
-
*
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
* 不再无限等待。
|
|
406
|
+
* 90s 后仍未观察到子会话新事件时标记 ackOverdue,供看板提示和主 Agent 跟进;
|
|
407
|
+
* 该标记不会 blocked、中止、换人或拒绝 done。ASSIGN_ACK_DEADLINE_MS 仅为
|
|
408
|
+
* 旧脚本/测试保留的历史值,生产路径不再读取。
|
|
330
409
|
*/
|
|
331
410
|
export const ASSIGN_ACK_NOTICE_MS = 90000;
|
|
332
411
|
export const ASSIGN_ACK_DEADLINE_MS = 180000;
|
|
333
412
|
/*
|
|
334
|
-
* [
|
|
413
|
+
* [3.0.1] 指示回执只剩提示,没有硬截止。
|
|
335
414
|
*
|
|
336
|
-
* `instructed` 只表示「指示已经写进状态行并投递」,不表示子 Agent 已经照做。
|
|
337
415
|
* 60s 没有新事件先标 `instructionOverdue`(看板可见、主 Agent 可催),
|
|
338
|
-
*
|
|
416
|
+
* 但不因缺少回执收束、阻断或换人;真正结果、真实错误或用户取消才结束。
|
|
417
|
+
* INSTRUCTION_ACK_DEADLINE_MS 仅为旧脚本/测试保留,生产路径不再读取。
|
|
339
418
|
*/
|
|
340
419
|
export const INSTRUCTION_ACK_NOTICE_MS = 60000;
|
|
341
420
|
export const INSTRUCTION_ACK_DEADLINE_MS = 180000;
|
|
@@ -344,23 +423,12 @@ export const INSTRUCTION_ACK_DEADLINE_MS = 180000;
|
|
|
344
423
|
* 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
|
|
345
424
|
*/
|
|
346
425
|
export const INSTRUCTION_POLL_MS = 5000;
|
|
347
|
-
// [
|
|
426
|
+
// [3.0.1] 整轮预算已停用。
|
|
348
427
|
//
|
|
349
|
-
//
|
|
350
|
-
//
|
|
351
|
-
//
|
|
352
|
-
//
|
|
353
|
-
// 现在:
|
|
354
|
-
// - TOTAL_TIMEOUT_MS = 0 表示默认不设整轮硬预算;
|
|
355
|
-
// - 显式传正数(配置/DSH_WORKPLAN_TOTAL_TIMEOUT_MS)仍可启用安全兜底;
|
|
356
|
-
// - 子任务自己的 timeoutMs/deadlineAt/extendMs 不受影响。
|
|
357
|
-
// dispatchPlan 用 20 天哨兵值避免 Infinity 参与计时器/差值计算。
|
|
358
|
-
//
|
|
359
|
-
// [2.2.5][热修] 哨兵值不能超过 Node setTimeout 的上限:延时 > 2^31-1 毫秒
|
|
360
|
-
// (约 24.8 天)会被 Node 强制改成 1 毫秒并告警(TimeoutOverflowWarning)。
|
|
361
|
-
// 最初版本用 10 年,结果整轮定时器派发后 1ms 就触发,所有子任务瞬间被
|
|
362
|
-
// 「总执行超时」杀死(2026-11-08 17:36 / 18:01 两次现场实锤,38ms 与 8ms)。
|
|
363
|
-
// 20 天 = 1,728,000,000ms < 2^31-1,安全;且对单轮执行而言等价于“无预算”。
|
|
428
|
+
// dispatchPlan 的 deadline 恒为 Infinity,不再创建 totalTimer;显式配置
|
|
429
|
+
// DSH_WORKPLAN_TOTAL_TIMEOUT_MS 或旧 totalTimeoutMs 也不会中止任何负责人/
|
|
430
|
+
// 专家,或产生“预算用尽/可续跑”。TOTAL_TIMEOUT_MS/NO_ROUND_BUDGET_MS
|
|
431
|
+
// 仅保留给旧记录解释和兼容测试,不代表仍可通过配置重新开启。
|
|
364
432
|
export const TOTAL_TIMEOUT_MS = 0;
|
|
365
433
|
export const NO_ROUND_BUDGET_MS = 20 * 24 * 60 * 60 * 1000;
|
|
366
434
|
export const ROUND_TIMER_MAX_MS = 2_000_000_000;
|
|
@@ -1955,7 +2023,7 @@ function resolveLiveAgent(ctx, sessionId) {
|
|
|
1955
2023
|
}
|
|
1956
2024
|
}
|
|
1957
2025
|
async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
1958
|
-
const { parentSignal,
|
|
2026
|
+
const { parentSignal, modelSelection, conversationContext = '', child, guard } = options;
|
|
1959
2027
|
/*
|
|
1960
2028
|
* [2.2.7] 中断即报的目标会话:与 noticeChannel/finaliseNotice 同一取值链,
|
|
1961
2029
|
* 拿不到就安静跳过(通知是观测设施,不是交付物)。
|
|
@@ -2112,35 +2180,22 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2112
2180
|
let phaseZeroOutput = '';
|
|
2113
2181
|
let interruptedFlag = false;
|
|
2114
2182
|
let interruptedEvidence = null;
|
|
2183
|
+
// 仅用于真实错误后的重试策略与日志,不参与 watchdog 或执行截止。
|
|
2184
|
+
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
|
|
2115
2185
|
try {
|
|
2116
|
-
//
|
|
2117
|
-
// startedAt 严格等于协商窗口)。deadlineAt 走 StatusEntry 未知字段保留通道
|
|
2118
|
-
// 直写:applyStatus(src/plan.ts,T3 领地)无路由分支,patch 会静默丢弃。
|
|
2186
|
+
// 新尝试只记录起点;历史 deadlineAt 不再作为执行指令,也不显示为本轮截止。
|
|
2119
2187
|
const attemptStartMs = Date.now();
|
|
2120
|
-
const attemptWindowMs = Number(options.attemptTimeoutMs ?? 0);
|
|
2121
2188
|
if (!writeSubtaskStatus(record, subtask.id, {
|
|
2122
2189
|
status: 'in_progress',
|
|
2123
2190
|
progress: 5,
|
|
2124
2191
|
startedAt: attemptStartMs,
|
|
2192
|
+
deadlineAt: null,
|
|
2125
2193
|
}, guard))
|
|
2126
2194
|
return;
|
|
2127
|
-
if (Number.isFinite(attemptWindowMs) && attemptWindowMs > 0) {
|
|
2128
|
-
const attemptRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
2129
|
-
if (attemptRow)
|
|
2130
|
-
attemptRow.deadlineAt = attemptStartMs + attemptWindowMs;
|
|
2131
|
-
if (options.attemptHandle) {
|
|
2132
|
-
options.attemptHandle.startedAt = attemptStartMs;
|
|
2133
|
-
options.attemptHandle.deadlineAt = attemptStartMs + attemptWindowMs;
|
|
2134
|
-
}
|
|
2135
|
-
}
|
|
2136
2195
|
for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
|
|
2137
|
-
if (guard.timedOut)
|
|
2138
|
-
return;
|
|
2139
2196
|
interruptedEvidence = null;
|
|
2140
2197
|
if (parentSignal.aborted)
|
|
2141
2198
|
throw abortError();
|
|
2142
|
-
if (Date.now() >= deadline)
|
|
2143
|
-
throw new PlanError('总执行超时', 'TOTAL_TIMEOUT');
|
|
2144
2199
|
let activation = null;
|
|
2145
2200
|
// Declared outside the try so the per-attempt finally can always cancel
|
|
2146
2201
|
// the receipt timers, even when activation itself failed.
|
|
@@ -2244,108 +2299,122 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2244
2299
|
if (!liveAgent) {
|
|
2245
2300
|
throw new PlanError('派发失败:无法解析活体父 Agent(agent 缺失且 agents 服务兜底失败),fail-closed 不创建子会话', 'AGENT_RESOLUTION_FAILED', { subtaskId: subtask.id });
|
|
2246
2301
|
}
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2302
|
+
// [3.0.1][P1a] 宿主 subagent.maxDepth < 2 时一次性告警(不阻断派发)。
|
|
2303
|
+
notifyDepthOverrideConflict(ctx, typeof record?.plan?.sessionId === 'string' ? record.plan.sessionId : null);
|
|
2304
|
+
try {
|
|
2305
|
+
activation = await ctx.subagents.startActivation({
|
|
2306
|
+
provider: 'spawn',
|
|
2307
|
+
label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
|
|
2308
|
+
prompt: [{
|
|
2309
|
+
type: 'text',
|
|
2310
|
+
text: phaseZeroActivation ? buildPhaseZeroLeaderPrompt({
|
|
2311
|
+
subtaskId: subtask.id,
|
|
2312
|
+
title: subtask.title,
|
|
2313
|
+
objective: subtask.objective,
|
|
2314
|
+
departmentLabel: DEPARTMENTS[subtask.department]?.zh ?? String(subtask.department ?? '部门'),
|
|
2315
|
+
}) : buildChildPrompt({
|
|
2316
|
+
plan: record.plan,
|
|
2317
|
+
subtask,
|
|
2318
|
+
stage,
|
|
2319
|
+
dependencyResults: record.statuses
|
|
2320
|
+
.filter((item) => subtask.dependsOn.includes(item.subtaskId))
|
|
2321
|
+
.map((item) => ({
|
|
2322
|
+
id: item.subtaskId,
|
|
2323
|
+
title: item.title,
|
|
2324
|
+
status: item.status,
|
|
2325
|
+
summary: item.summary,
|
|
2326
|
+
/*
|
|
2327
|
+
* [1.11.0] 跨部门交接物必须能被下游直接消费(用户 m00687)。
|
|
2328
|
+
*
|
|
2329
|
+
* 只传状态和摘要时,下游部门知道「上游做完了」,却不知道
|
|
2330
|
+
* 产物在哪,只能重做或向主 Agent 再提一次需求。这里把上游
|
|
2331
|
+
* 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
|
|
2332
|
+
*/
|
|
2333
|
+
artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
|
|
2334
|
+
.filter((artifact) => artifact?.exists === true && typeof artifact?.ref === 'string')
|
|
2335
|
+
.map((artifact) => String(artifact.ref)),
|
|
2336
|
+
})),
|
|
2337
|
+
cwd: options.cwd,
|
|
2338
|
+
conversationContext,
|
|
2339
|
+
statuses: record.statuses,
|
|
2268
2340
|
/*
|
|
2269
|
-
* [
|
|
2341
|
+
* [2.2.0][T3/O-2a] 子→主预告通道的目标(真实父会话 id)。
|
|
2270
2342
|
*
|
|
2271
|
-
*
|
|
2272
|
-
*
|
|
2273
|
-
* 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
|
|
2343
|
+
* 宿主只在非 caller 投递时注入父会话 id,本插件用 caller 投递,
|
|
2344
|
+
* 所以这里必须自己给值;空值走「禁止猜测」分支,绝不编造 id。
|
|
2274
2345
|
*/
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
model: modelSelection?.model ?? null,
|
|
2307
|
-
effort: staticRuleChildEffort || null,
|
|
2308
|
-
requested: childStaticCorrection ? requestedChildEffort : null,
|
|
2309
|
-
correctionReason: childStaticCorrection?.reason ?? null,
|
|
2310
|
-
tier: 'department',
|
|
2311
|
-
taskEffort: typeof effortRow?.effortOverride === 'string' ? effortRow.effortOverride : null,
|
|
2346
|
+
leadAgentId: noticeLead.id,
|
|
2347
|
+
leadAgentIdSource: noticeLead.source,
|
|
2348
|
+
/*
|
|
2349
|
+
* [2.1.0] 不再用 attempt>1 做门槛:被格式退回的行复位后第 1 次
|
|
2350
|
+
* 激活也必须带上退回通知,否则「退回」只是写了一行状态。
|
|
2351
|
+
*/
|
|
2352
|
+
previousFailure: lastFailure ?? null,
|
|
2353
|
+
lessonsBrief,
|
|
2354
|
+
/*
|
|
2355
|
+
* [3.0.1] 死锁自愈:行上登记的复活指示(子会话失联后由
|
|
2356
|
+
* dsh_workplan_instruct 写入)必须随重建的子提示词送达,
|
|
2357
|
+
* 否则新子会话会再请示一遍同一个问题。
|
|
2358
|
+
*/
|
|
2359
|
+
reviveInstruction: (record.statuses.find((item) => item?.subtaskId === subtask.id)?.reviveInstruction) ?? null,
|
|
2360
|
+
/*
|
|
2361
|
+
* [2.3.9][T4b] 用户强制要求 3:分配任务时必须把要求 1/2 的
|
|
2362
|
+
* **全部内容**告知相关部门。注入文本由 llm-rules.ts 的
|
|
2363
|
+
* buildLlmRulesBrief 单一事实源生成(tier='department'):
|
|
2364
|
+
* 要求 1/2 原文 + 本会话模型与家族判定 + 本子任务已配置/钳制后
|
|
2365
|
+
* 的推理等级 + 部门负责人「先全面梳理、再用 dsh_workplan_delegate
|
|
2366
|
+
* 分配给顶尖专家与组员」的强制流程告知。
|
|
2367
|
+
*/
|
|
2368
|
+
phaseZeroContinuation: phaseZeroCompleted ? buildPhaseZeroContinuationHint(String(effortRow?.effortOverride ?? ''), phaseZeroOutput, effortRow?.effortOverride === 'low' && (effortRow?.consolidation?.assignments ?? []).length === 0) : '',
|
|
2369
|
+
llmRulesBrief: buildLlmRulesBrief({
|
|
2370
|
+
model: modelSelection?.model ?? null,
|
|
2371
|
+
effort: staticRuleChildEffort || null,
|
|
2372
|
+
requested: childStaticCorrection ? requestedChildEffort : null,
|
|
2373
|
+
correctionReason: childStaticCorrection?.reason ?? null,
|
|
2374
|
+
tier: 'department',
|
|
2375
|
+
taskEffort: typeof effortRow?.effortOverride === 'string' ? effortRow.effortOverride : null,
|
|
2376
|
+
}),
|
|
2312
2377
|
}),
|
|
2313
|
-
}
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
}
|
|
2378
|
+
}],
|
|
2379
|
+
parent: liveAgent,
|
|
2380
|
+
cwd: typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined,
|
|
2381
|
+
/*
|
|
2382
|
+
* [2.2.0][T13/推理等级] 子 Agent 不得继承主 Agent 的推理等级。
|
|
2383
|
+
*
|
|
2384
|
+
* 用户规则原文:「禁止子agent继承主agent的推理等级,子agent必须根据
|
|
2385
|
+
* 自身任务的复杂度,自己使用推理等级为low、high或者是Max,其中,轻度
|
|
2386
|
+
* 复杂的任务使用low,中等复杂的任务使用high,非常复杂的任务使用Max。」
|
|
2387
|
+
* 宿主 resolveChildAgentOptions 在请求未点名 reasoningEffort 时会继承
|
|
2388
|
+
* 父 Agent 的等级(dsh-subagent child-agent.d.ts:40-50),旧实现在这里
|
|
2389
|
+
* 只传 provider/model,于是主 Agent 的等级被原样带进每个部门子会话。
|
|
2390
|
+
* 现在显式覆盖为子任务自己的档位;缺失(旧计划/回放)回落 high,绝不
|
|
2391
|
+
* 读取 modelSelection.reasoningEffort。
|
|
2392
|
+
*/
|
|
2393
|
+
agentOptions: {
|
|
2394
|
+
...(modelSelection?.provider && modelSelection?.model
|
|
2395
|
+
? { provider: modelSelection.provider, model: modelSelection.model }
|
|
2396
|
+
: {}),
|
|
2397
|
+
// [2.2.7] '' = 模型无 reasoning 元数据 ⇒ 不发送,避免派发期即中断。
|
|
2398
|
+
...(childEffort ? { reasoningEffort: childEffort } : {}),
|
|
2399
|
+
},
|
|
2400
|
+
/*
|
|
2401
|
+
* [2.3.9][T4b] 三层派发深度(用户强制要求 4/5):主 Agent(0) →
|
|
2402
|
+
* 部门负责人子会话(1) → 顶尖专家/组员子会话(2)。maxDepth 是宿主
|
|
2403
|
+
* resolveChildDepth 的**绝对深度上限**(child-agent.d.ts:24-29),
|
|
2404
|
+
* 部门层放行到 2 才能让负责人经 dsh_workplan_delegate 派生第三层;
|
|
2405
|
+
* 第三层成员派生时同样传 2 ⇒ 任何第四层(深度 3)被宿主抛
|
|
2406
|
+
* SubagentDepthError 硬拒,delegateTool 服务端另有一道「只有部门
|
|
2407
|
+
* 负责人行可调用」的校验——提示词说服模型,代码守住边界。
|
|
2408
|
+
*/
|
|
2409
|
+
maxDepth: 2,
|
|
2410
|
+
signal: child.controller.signal,
|
|
2411
|
+
delivery: 'caller',
|
|
2412
|
+
});
|
|
2413
|
+
}
|
|
2414
|
+
catch (error) {
|
|
2415
|
+
// [3.0.1][P1b] 并发上限翻译为可行动提示;其余错误原样上抛(保持旧行为)。
|
|
2416
|
+
throw describeSubagentActivationError(error, `派发子任务 ${subtask.id}(${subtask.title})`);
|
|
2417
|
+
}
|
|
2349
2418
|
if (guard.timedOut)
|
|
2350
2419
|
return;
|
|
2351
2420
|
if (!activation || typeof activation.result?.then !== 'function') {
|
|
@@ -2413,94 +2482,9 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2413
2482
|
// [2.2.9][handle-policy] 卫生类(T1 报告 R7):只丢一次「已下发未响应」提示,保留 unref。
|
|
2414
2483
|
noticeTimer.unref?.();
|
|
2415
2484
|
ackTimers.push(noticeTimer);
|
|
2416
|
-
|
|
2417
|
-
* [1.11.0] 180s 仍无回执 → 明确收束为 no-ack,而不是继续静默等待。
|
|
2418
|
-
*
|
|
2419
|
-
* 看门狗默认空闲窗口是 300s,而「根本没启动」和「在慢慢想」在日志上
|
|
2420
|
-
* 都表现为没有新事件。先把状态写成 blocked + blockedKind:'no-ack',
|
|
2421
|
-
* 再中止子会话;主 Agent 因此能立刻看到原因,也能选择续跑。
|
|
2422
|
-
*/
|
|
2423
|
-
const deadlineTimer = setTimeout(() => {
|
|
2424
|
-
if (guard.timedOut)
|
|
2425
|
-
return;
|
|
2426
|
-
const row = attemptRow();
|
|
2427
|
-
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
|
|
2428
|
-
return;
|
|
2429
|
-
const seconds = Math.round(ASSIGN_ACK_DEADLINE_MS / 1000);
|
|
2430
|
-
const message = `派发后 ${seconds}s 未收到子 Agent 任何新事件(no-ack)`;
|
|
2431
|
-
writeSubtaskStatus(record, subtask.id, {
|
|
2432
|
-
status: 'blocked',
|
|
2433
|
-
closure: 'blocked',
|
|
2434
|
-
blockedKind: 'no-ack',
|
|
2435
|
-
progress: 100,
|
|
2436
|
-
finishedAt: Date.now(),
|
|
2437
|
-
ackOverdue: true,
|
|
2438
|
-
error: message,
|
|
2439
|
-
summary: `未完成:${message}`,
|
|
2440
|
-
}, guard);
|
|
2441
|
-
recordSubtaskError(record, subtask.id, message, guard);
|
|
2442
|
-
// [2.2.7] 中断即报:no-ack 是「根本没启动」,不是「做失败了」。
|
|
2443
|
-
announceSubtaskInterrupt(record, interruptSession(), subtask.id, `子任务 ${subtask.id}(${subtask.title})${message};性质:子会话疑似根本没启动,不是执行失败;处理:已中止该子会话并把本行置为受阻(blockedKind=no-ack),主会话可决定重新下发指示或放弃该行,其余子任务不受影响。`);
|
|
2444
|
-
if (!child.controller.signal.aborted) {
|
|
2445
|
-
child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }));
|
|
2446
|
-
}
|
|
2447
|
-
}, ASSIGN_ACK_DEADLINE_MS);
|
|
2448
|
-
// [2.2.9][handle-policy] 收束类(T1 报告 R2):180s no-ack 判定必须真实触发;unref 时
|
|
2449
|
-
// 裸循环在判定前排空、行悬死(CI cancelled 红叉根因族)。ack 与收束路径均有 clearAckTimers 清理。
|
|
2450
|
-
ackTimers.push(deadlineTimer);
|
|
2451
|
-
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
|
|
2452
|
-
// [2.2.0][T4/O-3b][O-4d] 双计时同源(方案 §2.5):看门狗 hardMs 与本次尝试的
|
|
2453
|
-
// 协商执行时限同值(options.attemptTimeoutMs,缺省回落旧路径);两者必须同步
|
|
2454
|
-
// 推移——延期时 rearmApproachingDeadline 传「自尝试起点计的新完整窗口」。
|
|
2455
|
-
const hardTimeoutMs = Number.isFinite(Number(options.attemptTimeoutMs)) && Number(options.attemptTimeoutMs) > 0
|
|
2456
|
-
? Math.min(MAX_CHILD_TIMEOUT_MS, Math.max(MIN_CHILD_TIMEOUT_MS, Number(options.attemptTimeoutMs)))
|
|
2457
|
-
: normaliseChildTimeout(options.childTimeoutMs);
|
|
2485
|
+
// 未收到回执只保留 ackOverdue 提示;执行等待没有硬截止,绝不因此 blocked/abort。
|
|
2458
2486
|
const watchdog = createProgressWatchdog({
|
|
2459
|
-
|
|
2460
|
-
// 剩余 ≤ max(timeoutMs×0.2, 120000) 触发一次、同一武装周期幂等、extend 后
|
|
2461
|
-
// rearm 可再触发。最小处理器:时间链留档 timeWarning+本轮记录 notice+会话
|
|
2462
|
-
// 消息通知主 Agent(格式朴素,T6 波次统一润色)。
|
|
2463
|
-
subtaskId: String(subtask.id),
|
|
2464
|
-
onApproachingDeadline: (info) => {
|
|
2465
|
-
if (guard.timedOut)
|
|
2466
|
-
return;
|
|
2467
|
-
try {
|
|
2468
|
-
const warnRow = Array.isArray(record.statuses)
|
|
2469
|
-
? record.statuses.find((item) => item?.subtaskId === subtask.id)
|
|
2470
|
-
: null;
|
|
2471
|
-
if (warnRow) {
|
|
2472
|
-
// timeWarning 走未知字段通道直写(applyStatus 白名单属 T3 领地)。
|
|
2473
|
-
warnRow.timeWarning = {
|
|
2474
|
-
at: Date.now(),
|
|
2475
|
-
remainingMs: Math.max(0, Number(info?.remainingMs ?? 0)),
|
|
2476
|
-
newEstimateMinutes: null,
|
|
2477
|
-
channel: 'watchdog',
|
|
2478
|
-
};
|
|
2479
|
-
}
|
|
2480
|
-
const text = `子任务 ${subtask.id} 即将到点:剩余 ${Math.max(0, Math.round(Number(info?.remainingMs ?? 0) / 1000))}s(协商上限 ${Number(info?.timeoutMs ?? 0)}ms);如需继续请尽快决定延期(extendMs),否则到点将按安全兜底结算(待裁决)`;
|
|
2481
|
-
record.notices = [...(record.notices ?? []), text].slice(-20);
|
|
2482
|
-
record.updatedAt = Date.now();
|
|
2483
|
-
/*
|
|
2484
|
-
* 会话消息只对「有决策余量」的窗口推送:窗口 < 120000ms(=触发规则
|
|
2485
|
-
* max(timeoutMs×0.2, 120000) 里的预警下限,生产最小派生窗口恰好
|
|
2486
|
-
* 120000ms)只出现在测试小窗场景,预警本身没有可执行的延期决策余量,
|
|
2487
|
-
* 此时只留档(record.notices+timeWarning),不推送会话消息——也不与
|
|
2488
|
-
* tests/workplan-stuck-recovery.test.ts「session.events 只计持久消息」
|
|
2489
|
-
* 的既有断言冲突。T6 波次统一润色通知渠道时再定稿推送策略。
|
|
2490
|
-
* [2.2.0][T6/O-1a] 渠道已定稿:与完成即时通知同走主会话
|
|
2491
|
-
* `user/message` 纯文本通道(方案 §2.3「即时通知消息」);决策余量
|
|
2492
|
-
* 门槛(timeoutMs ≥ 120000,取自触发规则预警下限)保持不变,故
|
|
2493
|
-
* 上述断言不受影响。
|
|
2494
|
-
*/
|
|
2495
|
-
if (Number(info?.timeoutMs ?? 0) >= 120000) {
|
|
2496
|
-
const warnSession = options.session ?? options.agent?.session;
|
|
2497
|
-
appendUserMessage(warnSession, text);
|
|
2498
|
-
}
|
|
2499
|
-
}
|
|
2500
|
-
catch {
|
|
2501
|
-
// 预警只做提示不得影响执行:写档失败静默忽略(T6 波次统一润色)。
|
|
2502
|
-
}
|
|
2503
|
-
},
|
|
2487
|
+
enforceTimeouts: false,
|
|
2504
2488
|
getSeq: () => {
|
|
2505
2489
|
try {
|
|
2506
2490
|
const childSession = ctx.sessions?.get?.(activation.childId);
|
|
@@ -2511,25 +2495,13 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2511
2495
|
return undefined;
|
|
2512
2496
|
}
|
|
2513
2497
|
},
|
|
2514
|
-
idleMs:
|
|
2515
|
-
hardMs:
|
|
2516
|
-
|
|
2517
|
-
// never more than four times per window.
|
|
2518
|
-
pollMs: Math.min(CHILD_POLL_MS, Math.max(20, Math.floor(idleTimeoutMs / 4))),
|
|
2498
|
+
idleMs: Number.POSITIVE_INFINITY,
|
|
2499
|
+
hardMs: Number.POSITIVE_INFINITY,
|
|
2500
|
+
pollMs: CHILD_POLL_MS,
|
|
2519
2501
|
onProgress: ({ now, seq, elapsedMs }) => {
|
|
2520
|
-
if (guard.timedOut)
|
|
2521
|
-
return;
|
|
2522
|
-
// Visible liveness: the dashboard can show that a slow subtask is
|
|
2523
|
-
// still producing events instead of looking frozen.
|
|
2524
2502
|
record.heartbeatAt = now;
|
|
2525
2503
|
record.updatedAt = now;
|
|
2526
|
-
|
|
2527
|
-
* [1.11.0] 第一次观察到子会话日志增长 = 回执。
|
|
2528
|
-
*
|
|
2529
|
-
* 这是唯一能证明「子 Agent 已经在动」的廉价事实:不用它自己的
|
|
2530
|
-
* 汇报(可能永远等不到),只看它有没有产生新事件。回执写入后
|
|
2531
|
-
* 两个 no-ack 定时器立即撤销,正常的长任务不会被误判。
|
|
2532
|
-
*/
|
|
2504
|
+
// 子会话日志增长是正向回执;确认后只撤销提示计时器,不设置任何新截止。
|
|
2533
2505
|
const row = attemptRow();
|
|
2534
2506
|
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
|
|
2535
2507
|
return;
|
|
@@ -2543,20 +2515,16 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2543
2515
|
if (acked)
|
|
2544
2516
|
clearAckTimers();
|
|
2545
2517
|
},
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
: `子任务 ${subtask.id} 超时(${hardTimeoutMs}ms)`, reason === 'stalled' ? 'CHILD_STALLED' : 'CHILD_TIMEOUT', { subtaskId: subtask.id }),
|
|
2518
|
+
// 纯观测模式永不调用;保留参数以兼容 watchdog 的公开工厂接口。
|
|
2519
|
+
makeError: () => new PlanError('执行时限已禁用', 'TIME_LIMITS_DISABLED', { subtaskId: subtask.id }),
|
|
2549
2520
|
});
|
|
2550
|
-
// [2.2.0][T4/O-3b][O-4d] 看门狗挂到计时句柄:extendDeadline 延期成功后经
|
|
2551
|
-
// watchdog.rearmApproachingDeadline(传新完整窗口)同步推移两处计时。
|
|
2552
|
-
options.attemptHandle?.attachWatchdog?.(watchdog);
|
|
2553
2521
|
let result;
|
|
2554
2522
|
try {
|
|
2555
2523
|
const waiter = waitForActivation(activation, child.controller.signal);
|
|
2556
2524
|
// The losing side of the race may reject after the watchdog fired;
|
|
2557
2525
|
// keep that rejection handled so Node never reports it as unhandled.
|
|
2558
2526
|
waiter.catch(() => { });
|
|
2559
|
-
result = await
|
|
2527
|
+
result = await waiter;
|
|
2560
2528
|
}
|
|
2561
2529
|
finally {
|
|
2562
2530
|
watchdog.stop();
|
|
@@ -2633,7 +2601,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2633
2601
|
+ (unparsableLanded.length > 0
|
|
2634
2602
|
? `;上一次回报声明且已核到在盘的产物:${unparsableLanded.slice(0, 6).join('、')}——请勿重做已完成的工作,只修正结果块为合法 JSON 后重新完整回报`
|
|
2635
2603
|
: ';请修正结果块为合法 JSON(引号、逗号、括号成对,标记成对出现)后重新回报'), 'EVIDENCE_UNPARSABLE', { subtaskId: subtask.id });
|
|
2636
|
-
if (shouldRetryAttempt(unparsableError, attempt,
|
|
2604
|
+
if (shouldRetryAttempt(unparsableError, attempt, Number.POSITIVE_INFINITY, idleTimeoutMs)) {
|
|
2637
2605
|
throw unparsableError;
|
|
2638
2606
|
}
|
|
2639
2607
|
settleFromOutput(record, subtask, output, guard, options, settleVerdict, probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists));
|
|
@@ -2742,7 +2710,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2742
2710
|
? `;已核到在盘产物:${missingLanded.slice(0, 6).join('、')}`
|
|
2743
2711
|
: '')
|
|
2744
2712
|
+ '——请勿重做已完成的工作,只补交完整结构化结果块(WORKPLAN_EVIDENCE 标记成对、JSON 合法)后重新回报', 'EVIDENCE_MISSING', { subtaskId: subtask.id });
|
|
2745
|
-
if (shouldRetryAttempt(missingError, attempt,
|
|
2713
|
+
if (shouldRetryAttempt(missingError, attempt, Number.POSITIVE_INFINITY, idleTimeoutMs)) {
|
|
2746
2714
|
throw missingError;
|
|
2747
2715
|
}
|
|
2748
2716
|
}
|
|
@@ -2760,11 +2728,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2760
2728
|
}
|
|
2761
2729
|
catch (error) {
|
|
2762
2730
|
lastError = error;
|
|
2763
|
-
if (guard.timedOut)
|
|
2764
|
-
break;
|
|
2765
2731
|
const isAbort = parentSignal.aborted || child.controller.signal.aborted;
|
|
2766
|
-
const
|
|
2767
|
-
const remaining = deadline - Date.now();
|
|
2732
|
+
const remaining = Number.POSITIVE_INFINITY;
|
|
2768
2733
|
/*
|
|
2769
2734
|
* [1.7.0] The retry carries the previous failure with it.
|
|
2770
2735
|
*
|
|
@@ -2789,13 +2754,6 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
2789
2754
|
announceSubtaskInterrupt(record, interruptSession(), subtask.id, `子任务 ${subtask.id}(${subtask.title})第 ${attempt} 次执行被打断(${lastFailure.code}:${truncate(lastFailure.message, 140)});处理:插件已把失败原因回喂同一子会话并自动重试(第 ${attempt + 1} 次),任务整体仍在推进,这不是最终失败。`);
|
|
2790
2755
|
continue;
|
|
2791
2756
|
}
|
|
2792
|
-
/* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
|
|
2793
|
-
if (!isAbort && remaining <= idleTimeoutMs) {
|
|
2794
|
-
record.errors = [
|
|
2795
|
-
...(record.errors ?? []),
|
|
2796
|
-
`${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
|
|
2797
|
-
].slice(-20);
|
|
2798
|
-
}
|
|
2799
2757
|
break;
|
|
2800
2758
|
}
|
|
2801
2759
|
finally {
|
|
@@ -3158,344 +3116,31 @@ async function notifyExpertOfExtension(ctx, agent, record, subtaskId, deadlineAt
|
|
|
3158
3116
|
}
|
|
3159
3117
|
}
|
|
3160
3118
|
/*
|
|
3161
|
-
*
|
|
3162
|
-
*
|
|
3163
|
-
* [1.10.6] Split out of `runSubtask` so a ceiling timeout can be retried with a
|
|
3164
|
-
* *fresh* timer. The old code armed a single timer for the whole subtask (shared
|
|
3165
|
-
* by both attempts), so even once the retry decision became reachable the second
|
|
3166
|
-
* attempt would have had no time left — a patch that changes nothing.
|
|
3167
|
-
*
|
|
3168
|
-
* The timer remains a full settlement guarantee, not just an abort hint: if the
|
|
3169
|
-
* child activation ignores its abort signal, or never settles at all, the race
|
|
3170
|
-
* below still resolves, the subtask is recorded as blocked, and the dispatcher
|
|
3171
|
-
* keeps scheduling the rest of the DAG.
|
|
3119
|
+
* 部门负责人与其全球顶尖专家的正式执行不设墙钟、空闲或回执硬截止。
|
|
3120
|
+
* 只有子会话真实收束、返回错误、证据门禁或用户显式取消才能结束等待。
|
|
3172
3121
|
*/
|
|
3173
|
-
async function runSubtaskAttempt(ctx, record, stage, subtask, options
|
|
3122
|
+
async function runSubtaskAttempt(ctx, record, stage, subtask, options) {
|
|
3174
3123
|
const child = createChildController(options.parentSignal);
|
|
3175
3124
|
const guard = { timedOut: false };
|
|
3176
|
-
let timer = null;
|
|
3177
|
-
let ceilingFired = false;
|
|
3178
|
-
// [1.10.6] What the ceiling left on disk, in the words of the same probe the
|
|
3179
|
-
// blocked row records. The retry is compared against exactly this list.
|
|
3180
|
-
let ceilingLanded = [];
|
|
3181
|
-
/*
|
|
3182
|
-
* [1.10.6] Snapshot taken *at the moment the ceiling fires*, not later.
|
|
3183
|
-
*
|
|
3184
|
-
* The first cut of this check fingerprinted the same refs twice, back to back,
|
|
3185
|
-
* immediately before the retry. Two reads of the same instant can never
|
|
3186
|
-
* differ, so the conflict branch was unreachable in production (only a test
|
|
3187
|
-
* injecting a mutating `stat` could reach it). The record must be taken while
|
|
3188
|
-
* the timeout is being recorded; the pre-retry read is compared against it.
|
|
3189
|
-
*/
|
|
3190
|
-
let ceilingFingerprint = [];
|
|
3191
|
-
const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync;
|
|
3192
|
-
/*
|
|
3193
|
-
* [2.2.0][T4/O-3b][O-4d] 可延期计时句柄(D 项延期接口的运行时锚点,方案 §2.2/§2.5)。
|
|
3194
|
-
* 本次尝试的协商截止只属于这次尝试:extend() 重置一次性计时器并同步 watchdog
|
|
3195
|
-
* (rearmApproachingDeadline 传「自尝试起点计的新完整窗口」);settled 后不得
|
|
3196
|
-
* 复活(extendDeadline 一律 NO_ACTIVE_ATTEMPT)。行上 deadlineAt 由 executeSubtask
|
|
3197
|
-
* 以同一时钟读数写入(C3 契约),句柄权威值随写同步。
|
|
3198
|
-
*/
|
|
3199
|
-
const attemptStart = Date.now();
|
|
3200
|
-
const attemptHandle = {
|
|
3201
|
-
subtaskId: String(subtask.id),
|
|
3202
|
-
startedAt: attemptStart,
|
|
3203
|
-
deadlineAt: attemptStart + timeoutMs,
|
|
3204
|
-
settled: false,
|
|
3205
|
-
watchdog: null,
|
|
3206
|
-
arm: (_ms) => { },
|
|
3207
|
-
extend(ms) {
|
|
3208
|
-
if (this.settled)
|
|
3209
|
-
return this.deadlineAt;
|
|
3210
|
-
this.deadlineAt += ms;
|
|
3211
|
-
this.arm(this.deadlineAt - Date.now());
|
|
3212
|
-
this.watchdog?.rearmApproachingDeadline(this.deadlineAt - this.startedAt);
|
|
3213
|
-
return this.deadlineAt;
|
|
3214
|
-
},
|
|
3215
|
-
attachWatchdog(watchdog) {
|
|
3216
|
-
this.watchdog = watchdog;
|
|
3217
|
-
},
|
|
3218
|
-
};
|
|
3219
|
-
record.attemptHandles = { ...(record.attemptHandles ?? {}), [String(subtask.id)]: attemptHandle };
|
|
3220
|
-
const deadlinePromise = new Promise((resolve) => {
|
|
3221
|
-
const fire = () => {
|
|
3222
|
-
ceilingFired = true;
|
|
3223
|
-
guard.timedOut = true;
|
|
3224
|
-
attemptHandle.settled = true;
|
|
3225
|
-
// [2.2.0][T4/O-3b][O-4d] L4 安全兜底结算+「待裁决」标记(E4 契约):时间是
|
|
3226
|
-
// 协商出来的安全兜底,不是固定交付期限——到点不表述为「强制结束」式固定期限
|
|
3227
|
-
// 误杀,而是安全兜底结算落盘,供主 Agent 决定延期 / 重试 / 接受(或转新轮
|
|
3228
|
-
// 续跑、人工裁决)。Reached only when the child ignored both its idle window
|
|
3229
|
-
// and its abort signal; the message says so, otherwise the cause looks like
|
|
3230
|
-
// a plain "too slow" and the next investigation goes down the wrong path.
|
|
3231
|
-
// [2.3.0][T1] 计数在组装文案前预读:第 1 次超时的文案要求「必须放宽并
|
|
3232
|
-
// 告知专家」;第 2 次及以后的文案要求「主 Agent 接手、已完成部分只读
|
|
3233
|
-
// 保护、禁止丢弃」。错误文本是结果消息/看板/续跑判定的共同来源,所以
|
|
3234
|
-
// 接手语义必须在这里就落进 message,而不是只进即时通知。
|
|
3235
|
-
const preRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
3236
|
-
const timeoutCountAtFire = Number(preRow?.timeoutCount ?? 0) + 1;
|
|
3237
|
-
const message = timeoutCountAtFire >= TAKEOVER_AFTER_TIMEOUTS
|
|
3238
|
-
? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent 直接接手完成尚未完成的部分;专家已完成并落盘的部分已登记只读保护,禁止丢弃、禁止整步重跑;接手仅发生在已批准延期的场景)`
|
|
3239
|
-
: `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按运行层安全兜底结算(待裁决:判据层 10 分钟完成目标未达成且无用户批准 → 判未完成,优先 replan(replace) 转新子任务只补缺口;或经用户批准并留痕后 extendMs 放宽;或重试 / 接受、转新轮续跑、人工裁决)`;
|
|
3240
|
-
try {
|
|
3241
|
-
// [1.8.19] Keep the evidence of what already landed on disk.
|
|
3242
|
-
const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
|
|
3243
|
-
ceilingLanded = Array.isArray(landed) ? landed : [];
|
|
3244
|
-
ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat);
|
|
3245
|
-
/*
|
|
3246
|
-
* [1.11.0] An escalation outranks the ceiling.
|
|
3247
|
-
*
|
|
3248
|
-
* The child may have written `escalated` seconds before this timer fired;
|
|
3249
|
-
* turning that into a plain timeout would erase the question the main
|
|
3250
|
-
* Agent has to answer. The activation is still aborted, but the row keeps
|
|
3251
|
-
* its pending-decision state.
|
|
3252
|
-
*/
|
|
3253
|
-
const existing = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
3254
|
-
if (existing?.closure === 'escalated') {
|
|
3255
|
-
record.errors = [
|
|
3256
|
-
...(record.errors ?? []),
|
|
3257
|
-
`${subtask.id}: 已达执行上限,但该子任务已在等待指示,保留 escalated 状态`,
|
|
3258
|
-
].slice(-20);
|
|
3259
|
-
}
|
|
3260
|
-
else {
|
|
3261
|
-
record.statuses = applyStatus(record.statuses, subtask.id, patch);
|
|
3262
|
-
record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
|
|
3263
|
-
}
|
|
3264
|
-
/*
|
|
3265
|
-
* [2.2.0][T4/O-3b][C/E] 「待裁决」结构化标记(E4 契约):结算文案已含
|
|
3266
|
-
* 「待裁决」,这里再落机器可读标记供裁决/回放白名单透传(pendingAdjudication)。
|
|
3267
|
-
* 走 StatusEntry 未知字段通道直写(applyStatus 白名单属 T3 领地)。
|
|
3268
|
-
*/
|
|
3269
|
-
const settleRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
3270
|
-
if (settleRow)
|
|
3271
|
-
settleRow.pendingAdjudication = true;
|
|
3272
|
-
/*
|
|
3273
|
-
* [SCv2-T4][Q1-B/Q3-B/Q6-A] 到点结算的判据层判定(仅生效计划):
|
|
3274
|
-
* 运行层兜底已完成(blocked+产物抢救照旧),这里追加判据结果与违规
|
|
3275
|
-
* 审计;unmet 时把「判未完成→replan(replace) 接替」写进 error/summary,
|
|
3276
|
-
* 与 C15 文案同向。pendingAdjudication 事实标记保留(C16 不改)。
|
|
3277
|
-
*/
|
|
3278
|
-
if (settleRow && criterionV2Active(record.plan?.createdAt)) {
|
|
3279
|
-
try {
|
|
3280
|
-
let leaderForCriterion = null;
|
|
3281
|
-
try {
|
|
3282
|
-
leaderForCriterion = deriveLeaderEstimate(settleRow);
|
|
3283
|
-
}
|
|
3284
|
-
catch {
|
|
3285
|
-
leaderForCriterion = null;
|
|
3286
|
-
}
|
|
3287
|
-
const exAnte = criterionExAnte(settleRow, leaderForCriterion);
|
|
3288
|
-
const wallClockMs = attemptWallClockMsOf(settleRow);
|
|
3289
|
-
const evaluation = evaluateCriterion({
|
|
3290
|
-
exAnteMinutes: exAnte.minutes,
|
|
3291
|
-
exAnteComplete: exAnte.complete,
|
|
3292
|
-
wallClockMs,
|
|
3293
|
-
exception: sanitizeCriterionException(settleRow.criterionException),
|
|
3294
|
-
settledAt: Date.now(),
|
|
3295
|
-
});
|
|
3296
|
-
settleRow.criterionResult = evaluation.criterionResult;
|
|
3297
|
-
if (evaluation.criterionResult === 'unmet') {
|
|
3298
|
-
settleRow.criterionViolations = appendCriterionViolation(settleRow.criterionViolations, {
|
|
3299
|
-
at: Date.now(),
|
|
3300
|
-
attempt: timeoutCountAtFire,
|
|
3301
|
-
wallClockMs,
|
|
3302
|
-
exAnteMinutes: exAnte.minutes,
|
|
3303
|
-
reasons: evaluation.reasons,
|
|
3304
|
-
});
|
|
3305
|
-
const criterionNote = `判据违规(criterion-overrun):${evaluation.reasons.join(';')}。`
|
|
3306
|
-
+ '未获用户批准不得以 done 收尾(Q1-B);已完成产物只读保留,优先 replan(replace) 转接替子任务只补缺口,'
|
|
3307
|
-
+ '或先向用户申请例外批准并留痕(criterionApproval)后放宽。';
|
|
3308
|
-
settleRow.error = truncate(`${settleRow.error ?? ''};${criterionNote}`, 3000);
|
|
3309
|
-
settleRow.summary = truncate(`未完成:${criterionNote}`, 3000);
|
|
3310
|
-
}
|
|
3311
|
-
}
|
|
3312
|
-
catch (error) {
|
|
3313
|
-
record.errors = [...(record.errors ?? []), `${subtask.id}: 判据层判定写入失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20);
|
|
3314
|
-
}
|
|
3315
|
-
}
|
|
3316
|
-
/*
|
|
3317
|
-
* [2.3.0][T1] 超时计数与二次超时接手(用户要求 1/2 的机读落点):
|
|
3318
|
-
* 每次到点收束给状态行 timeoutCount +1 并记入 timeJournal(action:'timeout')。
|
|
3319
|
-
* 第 1 次超时 → 即时通知主 Agent「必须放宽(extendMs)并告知专家最新时限」,
|
|
3320
|
-
* 告知专家由延期事务自动投递(notifyExpertOfExtension);
|
|
3321
|
-
* 第 2 次超时 → takeoverRequired=true + buildTakeoverBrief 登记已完成部分,
|
|
3322
|
-
* mergePreservedArtifacts 把已落盘产物并入行 artifacts(只读保护、只增不减),
|
|
3323
|
-
* 主 Agent 接手只继续 remainingOutputs 与未满足验收,禁止丢弃已完成部分。
|
|
3324
|
-
* 计数走 StatusEntry 未知字段直写通道,回放白名单同步透传。
|
|
3325
|
-
*/
|
|
3326
|
-
if (settleRow) {
|
|
3327
|
-
const timeoutCount = timeoutCountAtFire;
|
|
3328
|
-
settleRow.timeoutCount = timeoutCount;
|
|
3329
|
-
const timeoutJournal = Array.isArray(settleRow.timeJournal) ? settleRow.timeJournal : [];
|
|
3330
|
-
timeoutJournal.push({ at: Date.now(), action: 'timeout', timeoutCount, by: 'system' });
|
|
3331
|
-
settleRow.timeJournal = timeoutJournal.slice(-20);
|
|
3332
|
-
if (timeoutCount >= TAKEOVER_AFTER_TIMEOUTS) {
|
|
3333
|
-
// 禁止丢弃已完成部分:接手包 + artifacts 只增不减的并集合并。
|
|
3334
|
-
settleRow.takeoverRequired = true;
|
|
3335
|
-
settleRow.takeoverBrief = buildTakeoverBrief(subtask, settleRow, ceilingLanded, timeoutCount);
|
|
3336
|
-
settleRow.artifacts = mergePreservedArtifacts(settleRow.artifacts, settleRow.takeoverBrief.landedRefs);
|
|
3337
|
-
}
|
|
3338
|
-
try {
|
|
3339
|
-
const takeoverText = timeoutCount >= TAKEOVER_AFTER_TIMEOUTS
|
|
3340
|
-
? `子任务 ${subtask.id} 已第 ${timeoutCount} 次达到协商时限(二次超时):按 2.3.0 机制本行已置「主 Agent 接手」(takeoverRequired)。`
|
|
3341
|
-
+ `专家已完成并登记保护的部分(只读、禁止丢弃):${ceilingLanded.slice(0, 8).join('、') || '(见 takeoverBrief)'};`
|
|
3342
|
-
+ '请主 Agent 直接接手继续未完成部分,不要整步重跑、不要删除或覆盖已登记产物。'
|
|
3343
|
-
: (criterionV2Active(record.plan?.createdAt)
|
|
3344
|
-
? `子任务 ${subtask.id} 第 1 次达到协商时限:按用户 2026-11-13 裁决 Q1-B,第一次超时不再自动放宽——请先向用户申请例外批准并留痕`
|
|
3345
|
-
+ '(任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=未批准),批准后才可用 dsh_workplan_update(extendMs, criterionApproval) 放宽;'
|
|
3346
|
-
+ '未获批准不得放宽,按判据层未达标处理(不 done、replan(replace) 转接替子任务只补缺口,已完成产物只读保护)。'
|
|
3347
|
-
: `子任务 ${subtask.id} 第 1 次达到协商时限:按 2.3.0 机制请主 Agent 尽快用 dsh_workplan_update(extendMs) 放宽,`
|
|
3348
|
-
+ '延期成功后插件会自动把最新时限与「保证质量、高效率执行」要求告知专家;如判断无需再放宽,请接手继续未完成部分(已完成产物将只读保护)。');
|
|
3349
|
-
announceSubtaskInterrupt(record, options.session ?? options.agent?.session, subtask.id, takeoverText);
|
|
3350
|
-
}
|
|
3351
|
-
catch {
|
|
3352
|
-
// 通知失败不影响结算(与预警同一纪律)。
|
|
3353
|
-
}
|
|
3354
|
-
}
|
|
3355
|
-
record.updatedAt = Date.now();
|
|
3356
|
-
}
|
|
3357
|
-
catch (error) {
|
|
3358
|
-
record.errors = [
|
|
3359
|
-
...(record.errors ?? []),
|
|
3360
|
-
`${subtask.id}: 超时状态写入失败:${truncate(String(error?.message ?? error), 500)}`,
|
|
3361
|
-
].slice(-20);
|
|
3362
|
-
}
|
|
3363
|
-
finally {
|
|
3364
|
-
if (!child.controller.signal.aborted) {
|
|
3365
|
-
child.controller.abort(new PlanError(message, 'CHILD_TIMEOUT', { subtaskId: subtask.id }));
|
|
3366
|
-
}
|
|
3367
|
-
child.disposeListener();
|
|
3368
|
-
resolve();
|
|
3369
|
-
}
|
|
3370
|
-
};
|
|
3371
|
-
// [2.2.0][T4/O-3b][O-4d] 可延期计时(D 项):arm() 重置一次性计时器,extend()
|
|
3372
|
-
// 经 attemptHandle 调用它把截止点推移到新协商截止;原截止点不再触发。
|
|
3373
|
-
const arm = (ms) => {
|
|
3374
|
-
if (timer)
|
|
3375
|
-
clearTimeout(timer);
|
|
3376
|
-
timer = setTimeout(fire, Math.max(1, ms));
|
|
3377
|
-
// [2.2.8] 禁止 unref:上限计时器必须是 ref 句柄。unref 时裸事件循环进程
|
|
3378
|
-
// (node:test / CI node22)会在等待竞态期间排空退出,用例被 cancelledByParent
|
|
3379
|
-
// → node:test exit 1 → 2.2.6/2.2.7 提交 CI 红叉根因(本地 node26 因 runner
|
|
3380
|
-
// 自带句柄竞态获胜而假绿)。收束路径 finally 已 clearTimeout,不会悬挂进程。
|
|
3381
|
-
};
|
|
3382
|
-
attemptHandle.arm = arm;
|
|
3383
|
-
arm(timeoutMs);
|
|
3384
|
-
});
|
|
3385
3125
|
try {
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
// 看门狗 hardMs 同值、延期接口锚点)。
|
|
3395
|
-
attemptTimeoutMs: timeoutMs,
|
|
3396
|
-
attemptHandle,
|
|
3397
|
-
}),
|
|
3398
|
-
deadlinePromise,
|
|
3399
|
-
]);
|
|
3400
|
-
return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint };
|
|
3126
|
+
const outcome = await executeSubtask(ctx, record, stage, subtask, {
|
|
3127
|
+
...options,
|
|
3128
|
+
child,
|
|
3129
|
+
guard,
|
|
3130
|
+
attemptTimeoutMs: 0,
|
|
3131
|
+
attemptHandle: undefined,
|
|
3132
|
+
});
|
|
3133
|
+
return { outcome, ceilingFired: false, ceilingLanded: [], ceilingFingerprint: [] };
|
|
3401
3134
|
}
|
|
3402
3135
|
finally {
|
|
3403
|
-
// [2.2.0][T4/O-3b] 收束即注销句柄:已收束的尝试不得再被 extendDeadline 复活。
|
|
3404
|
-
attemptHandle.settled = true;
|
|
3405
|
-
if (record.attemptHandles)
|
|
3406
|
-
delete record.attemptHandles[String(subtask.id)];
|
|
3407
|
-
if (timer) {
|
|
3408
|
-
clearTimeout(timer);
|
|
3409
|
-
timer = null;
|
|
3410
|
-
}
|
|
3411
3136
|
child.disposeListener();
|
|
3412
3137
|
if (!child.controller.signal.aborted)
|
|
3413
3138
|
child.controller.abort();
|
|
3414
3139
|
}
|
|
3415
3140
|
}
|
|
3416
|
-
/*
|
|
3417
|
-
* Runs one subtask, retrying **once** when the per-subtask ceiling fired and the
|
|
3418
|
-
* round budget can still pay for a second attempt (T6 G1/G3/G4).
|
|
3419
|
-
*
|
|
3420
|
-
* The retry is deliberately narrow:
|
|
3421
|
-
* - only the ceiling (`CHILD_TIMEOUT`) qualifies; a user abort and a round
|
|
3422
|
-
* budget timeout stay non-retryable, because retrying them would be killed by
|
|
3423
|
-
* the same guillotine;
|
|
3424
|
-
* - at most one retry (`attemptOffset: 2` caps the inner loop at a single run);
|
|
3425
|
-
* - before it starts, the artifacts the first attempt landed are fingerprinted
|
|
3426
|
-
* (path + size + mtime) and re-checked. If any of them changed since the
|
|
3427
|
-
* timeout was recorded, something else owns that file now: the retry is
|
|
3428
|
-
* skipped and the row is marked `artifactConflict` instead of overwriting it.
|
|
3429
|
-
*/
|
|
3430
3141
|
async function runSubtask(ctx, record, stage, subtask, options) {
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
// ③ 缺省回落 CHILD_TIMEOUT_MS;显式注入的 childTimeoutMs 作兜底上限取 min。
|
|
3434
|
-
const childTimeoutMs = resolveSubtaskTimeoutMs(subtask, options.childTimeoutMs);
|
|
3435
|
-
const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs);
|
|
3436
|
-
if (!first.ceilingFired)
|
|
3437
|
-
return first.outcome;
|
|
3438
|
-
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
|
|
3439
|
-
const now = Date.now();
|
|
3440
|
-
const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs;
|
|
3441
|
-
const remaining = deadline - now;
|
|
3442
|
-
const message = `子任务 ${subtask.id} 达到协商执行上限(${childTimeoutMs}ms)`;
|
|
3443
|
-
/*
|
|
3444
|
-
* [1.8.6] A parent abort outranks a retry: the round is being stopped on
|
|
3445
|
-
* purpose, and a second child would only be aborted on arrival.
|
|
3446
|
-
*/
|
|
3447
|
-
if (options.parentSignal?.aborted)
|
|
3448
|
-
return first.outcome;
|
|
3449
|
-
if (!shouldRetryAttempt({ code: 'CHILD_TIMEOUT', message }, 1, remaining, idleTimeoutMs)) {
|
|
3450
|
-
record.errors = [
|
|
3451
|
-
...(record.errors ?? []),
|
|
3452
|
-
`${subtask.id}: 达到执行上限,剩余预算 ${Math.max(0, Math.round(remaining / 1000))}s 不足,未重试`,
|
|
3453
|
-
].slice(-20);
|
|
3454
|
-
return first.outcome;
|
|
3455
|
-
}
|
|
3456
|
-
/*
|
|
3457
|
-
* [1.10.6] T6 G3: never retry over work that already exists.
|
|
3458
|
-
*
|
|
3459
|
-
* `ceilingFingerprint` was taken the moment the ceiling fired (inside the
|
|
3460
|
-
* timeout callback); the same refs are re-read right before the retry starts.
|
|
3461
|
-
* A size or mtime difference means the file was written by somebody else in
|
|
3462
|
-
* between, so a retry would overwrite it rather than finish it.
|
|
3463
|
-
*/
|
|
3464
|
-
const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync;
|
|
3465
|
-
const current = fingerprintArtifacts(first.ceilingLanded, options.cwd, stat);
|
|
3466
|
-
const conflicts = diffArtifactFingerprints(first.ceilingFingerprint, current);
|
|
3467
|
-
const row = Array.isArray(record.statuses)
|
|
3468
|
-
? record.statuses.find((item) => item.subtaskId === subtask.id)
|
|
3469
|
-
: null;
|
|
3470
|
-
if (conflicts.length > 0) {
|
|
3471
|
-
const note = `重试前核对发现已落盘产物在超时后被改动(${conflicts.join('、')}),为避免覆盖已跳过自动重试,请人工核对`;
|
|
3472
|
-
record.statuses = applyStatus(record.statuses, subtask.id, {
|
|
3473
|
-
artifactConflict: conflicts,
|
|
3474
|
-
error: truncate(`${truncate(String(row?.error ?? message), 1500)};${note}`, 2000),
|
|
3475
|
-
});
|
|
3476
|
-
record.errors = [...(record.errors ?? []), `${subtask.id}: ${note}`].slice(-20);
|
|
3477
|
-
record.updatedAt = Date.now();
|
|
3478
|
-
return first.outcome;
|
|
3479
|
-
}
|
|
3480
|
-
record.statuses = applyStatus(record.statuses, subtask.id, {
|
|
3481
|
-
status: 'in_progress',
|
|
3482
|
-
progress: 15,
|
|
3483
|
-
// Clearing `error` moves the timeout text to `lastError` (applyStatus does
|
|
3484
|
-
// that move), so the row no longer claims "blocked" while it is retrying.
|
|
3485
|
-
error: null,
|
|
3486
|
-
});
|
|
3487
|
-
record.errors = [
|
|
3488
|
-
...(record.errors ?? []),
|
|
3489
|
-
`${subtask.id}: 第 1 次执行达到上限(CHILD_TIMEOUT),已核对产物无冲突,自动重试一次`,
|
|
3490
|
-
].slice(-20);
|
|
3491
|
-
record.updatedAt = Date.now();
|
|
3492
|
-
const retryTimeoutMs = Math.max(MIN_CHILD_TIMEOUT_MS, Math.min(childTimeoutMs, remaining));
|
|
3493
|
-
const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
|
|
3494
|
-
...options,
|
|
3495
|
-
attemptOffset: 2,
|
|
3496
|
-
priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已按安全兜底结算(待裁决)` },
|
|
3497
|
-
}, retryTimeoutMs);
|
|
3498
|
-
return second.outcome;
|
|
3142
|
+
const attempt = await runSubtaskAttempt(ctx, record, stage, subtask, options);
|
|
3143
|
+
return attempt.outcome;
|
|
3499
3144
|
}
|
|
3500
3145
|
async function runWithConcurrency(items, limit, worker) {
|
|
3501
3146
|
let cursor = 0;
|
|
@@ -3600,10 +3245,11 @@ export function modelStatusLines(statuses) {
|
|
|
3600
3245
|
* deadlineAt/startedAt(字段名/单位照合同原文)。
|
|
3601
3246
|
*/
|
|
3602
3247
|
startedAt: item.startedAt ?? null,
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
|
|
3248
|
+
executionTimeLimit: 'none',
|
|
3249
|
+
// 旧记录只读保留,绝不再解释为当前截止或剩余执行时间。
|
|
3250
|
+
deadlineAt: null,
|
|
3251
|
+
legacyDeadlineAt: item.deadlineAt ?? null,
|
|
3252
|
+
deadlineRemainingMs: null,
|
|
3607
3253
|
timeWarning: item.timeWarning ?? null,
|
|
3608
3254
|
timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
|
|
3609
3255
|
pendingAdjudication: item.pendingAdjudication === true,
|
|
@@ -3653,7 +3299,7 @@ export function modelStatusLines(statuses) {
|
|
|
3653
3299
|
criterionResult: item.criterionResult ?? null,
|
|
3654
3300
|
criterionException: item.criterionException ?? null,
|
|
3655
3301
|
criterionViolations: Array.isArray(item.criterionViolations) ? item.criterionViolations.slice(-10) : [],
|
|
3656
|
-
leaderEstimateOverCriterion:
|
|
3302
|
+
leaderEstimateOverCriterion: false,
|
|
3657
3303
|
};
|
|
3658
3304
|
});
|
|
3659
3305
|
}
|
|
@@ -3735,7 +3381,7 @@ function describePendingCause(plan, statuses, id) {
|
|
|
3735
3381
|
export async function dispatchPlan(ctx, record, options) {
|
|
3736
3382
|
const { agent, signal, modelSelection, cwd, conversationContext = '' } = options;
|
|
3737
3383
|
const roundBudgetMs = Number(options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
|
|
3738
|
-
const deadline =
|
|
3384
|
+
const deadline = Number.POSITIVE_INFINITY;
|
|
3739
3385
|
/*
|
|
3740
3386
|
* [2.2.0][T3/O-2a] 本轮子→主预告通道的目标会话 id,一轮只解析一次。
|
|
3741
3387
|
*
|
|
@@ -3822,14 +3468,7 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
3822
3468
|
onAbort();
|
|
3823
3469
|
else
|
|
3824
3470
|
parentSignal.addEventListener('abort', onAbort, { once: true });
|
|
3825
|
-
|
|
3826
|
-
childController.abort(new PlanError('总执行超时', 'TOTAL_TIMEOUT'));
|
|
3827
|
-
// [2.2.5][热修] 双重保险:即使哨兵值/配置未来被改成超限值,也把延时钳在
|
|
3828
|
-
// Node setTimeout 上限之内,杜绝“1ms 触发”的整轮秒杀。
|
|
3829
|
-
}, Math.min(Math.max(1000, deadline - Date.now()), ROUND_TIMER_MAX_MS));
|
|
3830
|
-
// [2.2.9][handle-policy] 收束类(T1 报告 R1,P0):轮次总预算计时器必须真实触发(与 2.2.8
|
|
3831
|
-
// 已修的 attempt 上限计时器同构);unref 时裸循环在 TOTAL_TIMEOUT 前排空 → node:test 判
|
|
3832
|
-
// cancelledByParent → CI 红叉。收束路径 finally 有 clearTimeout(totalTimer),不会悬挂宿主。
|
|
3471
|
+
// 不创建整轮 totalTimer:配置中的历史时间值不会再中止部门或专家执行。
|
|
3833
3472
|
record.dispatchedAt = Date.now();
|
|
3834
3473
|
record.phase = 'executing';
|
|
3835
3474
|
record.updatedAt = record.dispatchedAt;
|
|
@@ -3898,8 +3537,6 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
3898
3537
|
throw new PlanError('调度次数异常', 'DISPATCH_LOOP');
|
|
3899
3538
|
if (parentSignal.aborted)
|
|
3900
3539
|
throw abortError();
|
|
3901
|
-
if (Date.now() >= deadline)
|
|
3902
|
-
throw new PlanError('总执行超时', 'TOTAL_TIMEOUT');
|
|
3903
3540
|
/*
|
|
3904
3541
|
* [1.7.0] A `done` upstream only unblocks its dependents when the files it
|
|
3905
3542
|
* declared actually exist. The check is opt-out (`artifactGate:false`) so
|
|
@@ -4196,7 +3833,6 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
4196
3833
|
}
|
|
4197
3834
|
finally {
|
|
4198
3835
|
dispatchHeartbeat.stop();
|
|
4199
|
-
clearTimeout(totalTimer);
|
|
4200
3836
|
parentSignal.removeEventListener('abort', onAbort);
|
|
4201
3837
|
if (!childController.signal.aborted)
|
|
4202
3838
|
childController.abort();
|
|
@@ -4577,6 +4213,8 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
4577
4213
|
changeRequest: null,
|
|
4578
4214
|
mainDeepThink: null,
|
|
4579
4215
|
mainDeepThinkPlanId: null,
|
|
4216
|
+
dispatchHold: undefined,
|
|
4217
|
+
gateHistory: undefined,
|
|
4580
4218
|
};
|
|
4581
4219
|
snapshots.set(plan.planId, snap);
|
|
4582
4220
|
}
|
|
@@ -4745,6 +4383,30 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
4745
4383
|
deepThinkSnap.mainDeepThinkPlanId = typeof update.mainDeepThinkPlanId === 'string' ? update.mainDeepThinkPlanId : null;
|
|
4746
4384
|
}
|
|
4747
4385
|
}
|
|
4386
|
+
/*
|
|
4387
|
+
* [3.0.1] 认可闸门回放(计划级字段):写入侧 buildUpdateMessage 已携带
|
|
4388
|
+
* dispatchHold/gateHistory;消费侧同口径消毒抬升。dispatchHold 为 null
|
|
4389
|
+
* 表示「已 release」(快照清闸),gateHistory 只增审计随回放还原。
|
|
4390
|
+
*/
|
|
4391
|
+
if (update && typeof update.planId === 'string' && update.dispatchHold !== undefined) {
|
|
4392
|
+
const holdSnap = snapshots.get(update.planId);
|
|
4393
|
+
if (holdSnap) {
|
|
4394
|
+
const raw = update.dispatchHold;
|
|
4395
|
+
holdSnap.dispatchHold = raw && typeof raw === 'object'
|
|
4396
|
+
? {
|
|
4397
|
+
kind: raw.kind === 'manual' ? 'manual' : 'keyword',
|
|
4398
|
+
reason: truncate(String(raw.reason ?? ''), 300),
|
|
4399
|
+
at: Number(raw.at) || 0,
|
|
4400
|
+
by: raw.by === 'agent' ? 'agent' : 'system',
|
|
4401
|
+
}
|
|
4402
|
+
: null;
|
|
4403
|
+
}
|
|
4404
|
+
}
|
|
4405
|
+
if (update && typeof update.planId === 'string' && Array.isArray(update.gateHistory)) {
|
|
4406
|
+
const holdSnap = snapshots.get(update.planId);
|
|
4407
|
+
if (holdSnap)
|
|
4408
|
+
holdSnap.gateHistory = update.gateHistory.slice(-10);
|
|
4409
|
+
}
|
|
4748
4410
|
if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
|
|
4749
4411
|
const snap = snapshots.get(update.planId);
|
|
4750
4412
|
if (snap) {
|
|
@@ -4834,6 +4496,12 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
4834
4496
|
artifacts: update.artifacts,
|
|
4835
4497
|
missingArtifacts: update.missingArtifacts,
|
|
4836
4498
|
handoffs: update.handoffs,
|
|
4499
|
+
/*
|
|
4500
|
+
* [3.0.1] 死锁自愈:复活指示随 durable update 回放(applyStatus
|
|
4501
|
+
* 同口径消毒,undefined 保留旧值)——重启后重建的子会话仍能收到
|
|
4502
|
+
* 主 Agent 对升级请示的拍板指示。
|
|
4503
|
+
*/
|
|
4504
|
+
reviveInstruction: update.reviveInstruction,
|
|
4837
4505
|
revision: Number.isInteger(update.revision) ? update.revision : undefined,
|
|
4838
4506
|
// [2.2.0][T4/O-3b][E] 回放白名单(T3b TODO#2):O-3b/O-2c 留档字段随
|
|
4839
4507
|
// update 记录回放;timeoutMs 有 applyStatus 分支,走 patch 即可。
|
|
@@ -5106,6 +4774,11 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
5106
4774
|
/* [2.5.1] 主 Agent 两轮深度思考产物随回放回到记录(续跑读档放行)。 */
|
|
5107
4775
|
mainDeepThink: chosen.mainDeepThink ?? null,
|
|
5108
4776
|
mainDeepThinkPlanId: chosen.mainDeepThinkPlanId ?? null,
|
|
4777
|
+
/* [3.0.1] 认可闸门随重建记录还原:重启后 dispatch 闸门与审计留痕不失效。
|
|
4778
|
+
* 直接属性而非条件展开——条件展开会破坏返回字面量的判别收窄
|
|
4779
|
+
* (rebuilt.plan 的 null/对象判别失效,resumeLimit 访问报 union 错)。 */
|
|
4780
|
+
dispatchHold: chosen.dispatchHold ?? null,
|
|
4781
|
+
gateHistory: Array.isArray(chosen.gateHistory) ? chosen.gateHistory : [],
|
|
5109
4782
|
/*
|
|
5110
4783
|
* [1.8.17] A reconstructed record must carry every field the live dispatch
|
|
5111
4784
|
* path spreads/pushes unconditionally. `errors` was the one that was
|
|
@@ -5535,32 +5208,6 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
5535
5208
|
});
|
|
5536
5209
|
row.timeJournal = journal.slice(-20);
|
|
5537
5210
|
record.updatedAt = at;
|
|
5538
|
-
/*
|
|
5539
|
-
* [SCv2-T4][Q4-B/C22] 部门行事前预估落档后的超判据告警(仅生效计划):
|
|
5540
|
-
* 叶子预估之和(或无叶子直做时负责人自身预估)>10 ⇒ 即时告知主 Agent
|
|
5541
|
-
* 拆分或向用户申请例外批准;预估未齐只显示部分和、不得视为达标(D-3)。
|
|
5542
|
-
* 告警是观测设施:写失败只留档 errors,绝不影响记录与执行。
|
|
5543
|
-
*/
|
|
5544
|
-
try {
|
|
5545
|
-
if (criterionV2Active(record?.plan?.createdAt) && session) {
|
|
5546
|
-
let leaderForNotice = null;
|
|
5547
|
-
try {
|
|
5548
|
-
leaderForNotice = deriveLeaderEstimate(row);
|
|
5549
|
-
}
|
|
5550
|
-
catch {
|
|
5551
|
-
leaderForNotice = null;
|
|
5552
|
-
}
|
|
5553
|
-
const exAnte = criterionExAnte(row, leaderForNotice);
|
|
5554
|
-
if (exAnte.minutes !== null && exAnte.minutes > CRITERION_TARGET_MINUTES) {
|
|
5555
|
-
appendUserMessage(session, `【dsh-workplan·判据告警】子任务 ${subtaskId} 的事前预估为 ${exAnte.minutes} 分钟,`
|
|
5556
|
-
+ `超过判据层完成目标 ${CRITERION_TARGET_MINUTES} 分钟(Q4-B)。请事前拆分工作,或向用户申请例外批准并留痕(criterionApproval);`
|
|
5557
|
-
+ '预估未报齐时只显示部分和,不得视为「简单判据达标」。');
|
|
5558
|
-
}
|
|
5559
|
-
}
|
|
5560
|
-
}
|
|
5561
|
-
catch (error) {
|
|
5562
|
-
record.errors = [...(record.errors ?? []), `${subtaskId} 判据告警写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20);
|
|
5563
|
-
}
|
|
5564
5211
|
/*
|
|
5565
5212
|
* [2.3.0][T1] 预估上报 → 告知用户(用户要求 1 的前半段闭环):专家的开工
|
|
5566
5213
|
* 预告落档后,插件立即向主会话推送一条即时通知,明确「请把此预期执行
|
|
@@ -5572,8 +5219,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
5572
5219
|
appendUserMessage(session, `【dsh-workplan·专家预估上报】子任务 ${subtaskId} 的执行专家`
|
|
5573
5220
|
+ `预估执行时间 ${Number(notice?.declaredMinutes)} 分钟`
|
|
5574
5221
|
+ (reason ? `(${reason})` : '')
|
|
5575
|
-
+
|
|
5576
|
-
+ '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。', undefined, { allowBanned: true });
|
|
5222
|
+
+ ';请把此预期执行时间告知用户。预估仅供参考、非承诺,不会形成执行截止、超时接管或完成验收门槛。', undefined, { allowBanned: true });
|
|
5577
5223
|
}
|
|
5578
5224
|
catch (error) {
|
|
5579
5225
|
record.errors = [...(record.errors ?? []), `${subtaskId} 预估上报通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20);
|
|
@@ -5620,6 +5266,16 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
5620
5266
|
hint: '请传入 1 以上的整数毫秒;放宽永远有界(累计 ≤ 初始协商上限 × 1),超出请转新轮续跑或转 escalate 请主 Agent 裁决。',
|
|
5621
5267
|
};
|
|
5622
5268
|
}
|
|
5269
|
+
if (hasExtend) {
|
|
5270
|
+
return {
|
|
5271
|
+
ok: false,
|
|
5272
|
+
code: 'TIME_LIMITS_DISABLED',
|
|
5273
|
+
planId: record.plan.planId,
|
|
5274
|
+
subtaskId,
|
|
5275
|
+
error: '部门负责人与全球顶尖专家执行已取消时限,无需也不能申请延期;当前任务会继续等待真实完成、真实错误或用户取消。',
|
|
5276
|
+
hint: '请移除 extendMs,直接继续执行;如需汇报预估变化,只传 timeNotice(纯信息,不影响验收)。',
|
|
5277
|
+
};
|
|
5278
|
+
}
|
|
5623
5279
|
/*
|
|
5624
5280
|
* [SCv2-T4][Q1-B/C05/C06] extendMs 用户批准闸(判据 v2 生效计划专用):
|
|
5625
5281
|
* 第一次超时不再自动放宽——未携带合格用户批准留痕(criterionApproval)一律
|
|
@@ -7715,9 +7371,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
7715
7371
|
* 指示投递成功只证明消息进了收件箱,不证明子会话真的开始执行。三个观察点
|
|
7716
7372
|
* 都以「该行仍是 instructed 且 instructionSeq 未变」为前提:
|
|
7717
7373
|
* - 轮询:子会话 seq 增长 = 已开始执行 → 写 acknowledged(唯一正向回执);
|
|
7718
|
-
* - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent
|
|
7719
|
-
*
|
|
7720
|
-
*
|
|
7374
|
+
* - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent 可催)。
|
|
7375
|
+
* 这里没有 180s 硬截止,也不会因缺少回执收束为 blocked/no-ack;主 Agent
|
|
7376
|
+
* 再次改判、子会话产出结果或用户显式取消才会让观察自然作废。
|
|
7721
7377
|
*/
|
|
7722
7378
|
function scheduleInstructionAck(record, subtaskId, childId, revision) {
|
|
7723
7379
|
const rowOf = () => record.statuses.find((item) => item?.subtaskId === subtaskId);
|
|
@@ -7758,8 +7414,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
7758
7414
|
return seq <= baseline;
|
|
7759
7415
|
};
|
|
7760
7416
|
/*
|
|
7761
|
-
*
|
|
7762
|
-
*
|
|
7417
|
+
* 正向回执:没有这一步时,一个正常工作但耗时较长的子会话会被误判成
|
|
7418
|
+
* 无响应;它其实早就在产出事件了。现在只用于消除逾期提示,不做阻断。
|
|
7763
7419
|
*/
|
|
7764
7420
|
const poll = setInterval(() => {
|
|
7765
7421
|
const row = rowOf();
|
|
@@ -7785,7 +7441,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
7785
7441
|
}
|
|
7786
7442
|
stop();
|
|
7787
7443
|
}, INSTRUCTION_POLL_MS);
|
|
7788
|
-
// [
|
|
7444
|
+
// [3.0.1] 回执轮询只提供正向确认与逾期提示;没有 deadline 判定,保留 unref。
|
|
7789
7445
|
poll.unref?.();
|
|
7790
7446
|
timers.push(poll);
|
|
7791
7447
|
const notice = setTimeout(() => {
|
|
@@ -7801,35 +7457,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
7801
7457
|
// [2.2.9][handle-policy] 卫生类(T1 报告 R9):只丢一次「指示未回执」提示,保留 unref。
|
|
7802
7458
|
notice.unref?.();
|
|
7803
7459
|
timers.push(notice);
|
|
7804
|
-
const deadline = setTimeout(() => {
|
|
7805
|
-
if (!unchanged(rowOf())) {
|
|
7806
|
-
stop();
|
|
7807
|
-
return;
|
|
7808
|
-
}
|
|
7809
|
-
const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000);
|
|
7810
|
-
const message = `指示下发后 ${seconds}s 子会话仍无任何新事件(no-ack):指示没有被执行`;
|
|
7811
|
-
try {
|
|
7812
|
-
writeSubtaskStatus(record, subtaskId, {
|
|
7813
|
-
status: 'blocked',
|
|
7814
|
-
closure: 'blocked',
|
|
7815
|
-
blockedKind: 'no-ack',
|
|
7816
|
-
progress: 100,
|
|
7817
|
-
finishedAt: Date.now(),
|
|
7818
|
-
instructionOverdue: true,
|
|
7819
|
-
error: message,
|
|
7820
|
-
summary: `未完成:${message}`,
|
|
7821
|
-
}, { timedOut: false });
|
|
7822
|
-
recordSubtaskError(record, subtaskId, message, { timedOut: false });
|
|
7823
|
-
}
|
|
7824
|
-
catch {
|
|
7825
|
-
// Same race as above: the row already left instructed.
|
|
7826
|
-
}
|
|
7827
|
-
stop();
|
|
7828
|
-
}, INSTRUCTION_ACK_DEADLINE_MS);
|
|
7829
|
-
// [2.2.9][handle-policy] 收束类(T1 报告 R5):指示 no-ack 判定必须真实触发;触发/回执即 stop()
|
|
7830
|
-
// 清掉整组计时器,延时有界(INSTRUCTION_ACK_DEADLINE_MS),不会悬挂宿主。
|
|
7831
|
-
timers.push(deadline);
|
|
7832
7460
|
}
|
|
7461
|
+
/**
|
|
7462
|
+
* [1.11.0] 主 → 子下发指示 }
|
|
7463
|
+
|
|
7833
7464
|
/**
|
|
7834
7465
|
* [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
|
|
7835
7466
|
*
|
|
@@ -7897,10 +7528,52 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
7897
7528
|
if (!instruction)
|
|
7898
7529
|
return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要子 Agent 执行的决定' };
|
|
7899
7530
|
const childId = typeof current.childId === 'string' ? current.childId : '';
|
|
7900
|
-
|
|
7901
|
-
|
|
7902
|
-
|
|
7903
|
-
|
|
7531
|
+
const childAlive = Boolean(childId) && spawnedChildIds(session).has(childId);
|
|
7532
|
+
if (!childAlive) {
|
|
7533
|
+
/*
|
|
7534
|
+
* [3.0.1] 死锁自愈(wp-e745a477 事故治本):子会话失联时不再把 NO_CHILD /
|
|
7535
|
+
* NOT_DIRECT_CHILD 当成终点——那条路配上 ESCALATION_OPEN(不许改判)与
|
|
7536
|
+
* 「待指示行阻止续跑」会把三条出口全堵死,只剩人工取消整盘计划。
|
|
7537
|
+
* 现在:指示登记为行上 reviveInstruction(durable 回放不丢),行从
|
|
7538
|
+
* escalated 复位为 pending(TRANSITIONS 合法边),下一次 dispatch 走
|
|
7539
|
+
* 常规 executeSubtask 路径重建全新子会话,提示词由 buildChildPrompt
|
|
7540
|
+
* 带入这条指示。
|
|
7541
|
+
*/
|
|
7542
|
+
const now = Date.now();
|
|
7543
|
+
const { patch: revivePatch, revision } = buildChildRevivePatch(current, instruction, now);
|
|
7544
|
+
record.statuses = applyStatus(record.statuses, subtaskId, revivePatch);
|
|
7545
|
+
record.phase = reconcilePhase(record.phase, record.statuses);
|
|
7546
|
+
record.updatedAt = now;
|
|
7547
|
+
try {
|
|
7548
|
+
const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
|
|
7549
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
7550
|
+
planId: record.plan.planId,
|
|
7551
|
+
subtaskId,
|
|
7552
|
+
status: 'pending',
|
|
7553
|
+
closure: 'pending',
|
|
7554
|
+
reviveInstruction: written?.reviveInstruction,
|
|
7555
|
+
revision,
|
|
7556
|
+
keyProgress: true,
|
|
7557
|
+
stateLabel: '失联复活·待重派',
|
|
7558
|
+
title: typeof current.title === 'string' ? current.title : undefined,
|
|
7559
|
+
}));
|
|
7560
|
+
}
|
|
7561
|
+
catch (error) {
|
|
7562
|
+
pushRecordError(record, error);
|
|
7563
|
+
}
|
|
7564
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
7565
|
+
return {
|
|
7566
|
+
ok: true,
|
|
7567
|
+
revived: true,
|
|
7568
|
+
code: 'CHILD_REVIVED',
|
|
7569
|
+
planId: record.plan.planId,
|
|
7570
|
+
subtaskId,
|
|
7571
|
+
status: 'pending',
|
|
7572
|
+
closure: 'pending',
|
|
7573
|
+
revision,
|
|
7574
|
+
stats: snapshot.stats,
|
|
7575
|
+
hint: '死锁自愈:该行子会话已失联,指示已登记为行上 reviveInstruction、行已复位为待跑。调用 dsh_workplan_dispatch 将重建全新子会话并带入该指示;不要再对本行重复 instruct。',
|
|
7576
|
+
};
|
|
7904
7577
|
}
|
|
7905
7578
|
const service = ctx.subagents;
|
|
7906
7579
|
if (!service || typeof service.sendMessage !== 'function') {
|
|
@@ -8170,10 +7843,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
8170
7843
|
};
|
|
8171
7844
|
}
|
|
8172
7845
|
/**
|
|
8173
|
-
* [2.5.6] 叶子指示回执:与 scheduleInstructionAck
|
|
8174
|
-
* (轮询 seq 增长=acknowledged;60s 无增长=instructionOverdue
|
|
8175
|
-
*
|
|
8176
|
-
*
|
|
7846
|
+
* [2.5.6] 叶子指示回执:与 scheduleInstructionAck 同一套观察语义
|
|
7847
|
+
* (轮询 seq 增长=acknowledged;60s 无增长=instructionOverdue),只是读写
|
|
7848
|
+
* 目标从部门行换成行内 delegates 成员条目。两者都没有 180s 硬截止,不会
|
|
7849
|
+
* 因缺少回执 blocked/no-ack;独立实现以保持第一层零回归。
|
|
8177
7850
|
*/
|
|
8178
7851
|
function scheduleDelegateInstructionAck(record, subtaskId, member, childId, revision) {
|
|
8179
7852
|
const rowOf = () => record.statuses.find((item) => item?.subtaskId === subtaskId);
|
|
@@ -8261,34 +7934,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
8261
7934
|
}, INSTRUCTION_ACK_NOTICE_MS);
|
|
8262
7935
|
notice.unref?.();
|
|
8263
7936
|
timers.push(notice);
|
|
8264
|
-
const deadline = setTimeout(() => {
|
|
8265
|
-
if (!unchanged(entryOf())) {
|
|
8266
|
-
stop();
|
|
8267
|
-
return;
|
|
8268
|
-
}
|
|
8269
|
-
const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000);
|
|
8270
|
-
const message = `指示下发后 ${seconds}s 成员会话仍无任何新事件(no-ack):指示没有被执行`;
|
|
8271
|
-
try {
|
|
8272
|
-
patchEntry({
|
|
8273
|
-
status: 'blocked',
|
|
8274
|
-
closure: 'blocked',
|
|
8275
|
-
blockedKind: 'no-ack',
|
|
8276
|
-
progress: 100,
|
|
8277
|
-
error: message,
|
|
8278
|
-
summary: `未完成:${message}`,
|
|
8279
|
-
finishedAt: Date.now(),
|
|
8280
|
-
});
|
|
8281
|
-
// [2.5.6] 与第一层 scheduleInstructionAck 对齐:no-ack 收束必须写入
|
|
8282
|
-
// 错误台账(主行 recordSubtaskError 同款),不留「静默 blocked」。
|
|
8283
|
-
recordSubtaskError(record, subtaskId, message, { timedOut: false });
|
|
8284
|
-
}
|
|
8285
|
-
catch {
|
|
8286
|
-
// Entry already left instructed.
|
|
8287
|
-
}
|
|
8288
|
-
stop();
|
|
8289
|
-
}, INSTRUCTION_ACK_DEADLINE_MS);
|
|
8290
|
-
timers.push(deadline);
|
|
8291
7937
|
}
|
|
7938
|
+
/**
|
|
7939
|
+
* [1.11.0] 工具层入口:子会话的遇阻上报 }
|
|
7940
|
+
|
|
8292
7941
|
/**
|
|
8293
7942
|
* [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
|
|
8294
7943
|
*
|
|
@@ -8403,7 +8052,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
8403
8052
|
* 如果提出需求的行正处于「待指示」,它此刻停在那里等主 Agent:只把
|
|
8404
8053
|
* handoff 写成 answered、不发指示,子会话永远不会继续,需求闭环只闭在
|
|
8405
8054
|
* 计划表里。这里复用 instructSubtask 的唯一投递/回执链路(写 instructed、
|
|
8406
|
-
* 60s
|
|
8055
|
+
* 60s 逾期提示、下次激活注入),不另造第二条消息通道。
|
|
8407
8056
|
* 投递失败不回滚 handoff:答复本身是真的,失败原因如实返回给主 Agent。
|
|
8408
8057
|
*/
|
|
8409
8058
|
let instruction = null;
|
|
@@ -8732,13 +8381,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
8732
8381
|
persistSelf({ delegates: failedList });
|
|
8733
8382
|
return { ok: false, code: 'SELF_EFFORT_CONTINUATION_FAILED', subtaskId, member: member.member, selfEffort, error: message };
|
|
8734
8383
|
}
|
|
8735
|
-
// 接续:中断 phase-0(
|
|
8736
|
-
|
|
8737
|
-
|
|
8738
|
-
|
|
8739
|
-
}
|
|
8740
|
-
}
|
|
8741
|
-
catch { /* 中断失败不阻断接续 */ }
|
|
8384
|
+
// 接续:中断 phase-0(ancestor authority, continuable),尽力而为。
|
|
8385
|
+
// [3.0.1] 优先新版 interrupt()(authority=负责人活体 Agent);旧版宿主回退
|
|
8386
|
+
// interruptByParent。ancestorAgent 缺失时返回 false(与修复前静默跳过同口径)。
|
|
8387
|
+
interruptChildContinuable(ctx.subagents, childSession.id, leaderAgent, leaderId);
|
|
8742
8388
|
const departmentLabel = DEPARTMENTS[row.department]?.zh ?? String(row.department ?? '部门');
|
|
8743
8389
|
const assignment = (Array.isArray(row.consolidation?.assignments) ? row.consolidation.assignments : [])
|
|
8744
8390
|
.find((a) => a?.member === member.member);
|
|
@@ -8762,6 +8408,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
8762
8408
|
leadSessionId: leaderId,
|
|
8763
8409
|
extraContext: `【phase-0→phase-1 接续——继续勿重做】你已在 phase-0 完成复杂度评估并自配推理等级 \`${selfEffort}\`(依据:${truncate(rationale, 300)}${correction.adjusted ? `;请求档 ${raw} 越界已被平台钳制为 ${selfEffort}` : ''}),并登记了执行前两轮深度思考产物。平台已按你的自配档接续:直接执行正式任务,不要重新评估复杂度,不要重做 phase-0 已完成的工作。正式执行必须严格按你第二轮理清的方法、流程、步骤进行(你的第二轮产物:${leafDeepThink.approach.join(';').slice(0, 300)}…),全程少走弯路:先查历史教训、先验证再动手、不重复试错。`,
|
|
8764
8410
|
});
|
|
8411
|
+
// [3.0.1][P1a] 宿主 subagent.maxDepth < 2 时一次性告警(scope=计划根会话)。
|
|
8412
|
+
notifyDepthOverrideConflict(ctx, typeof rootId === 'string' ? rootId : null);
|
|
8765
8413
|
let activation = null;
|
|
8766
8414
|
let lastError = null;
|
|
8767
8415
|
for (let i = 0; i < 2; i += 1) {
|
|
@@ -8794,6 +8442,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
8794
8442
|
}
|
|
8795
8443
|
}
|
|
8796
8444
|
if (!activation) {
|
|
8445
|
+
// [3.0.1][P1b] 宿主并发上限单独翻译为可行动提示;其余错误走下方统一 PlanError。
|
|
8446
|
+
if (String(lastError?.code ?? '') === 'ACTIVATION_LIMIT_REACHED' || /limit reached/i.test(String(lastError?.message ?? ''))) {
|
|
8447
|
+
throw describeSubagentActivationError(lastError, `自配档接续(成员 ${member.member})`);
|
|
8448
|
+
}
|
|
8797
8449
|
const message = `自配档已登记但接续失败(已重试 1 次):${String(lastError?.message ?? lastError)}——禁止静默降档;该成员记为 failed,负责人可重派(自配档保留,重派直接以自配档接续)`;
|
|
8798
8450
|
const failedList = (currentRow()?.delegates ?? [])
|
|
8799
8451
|
.map((d) => (d?.childId === childSession.id ? { ...d, status: 'failed', error: truncate(message, 300), finishedAt: Date.now() } : d));
|
|
@@ -9050,12 +8702,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9050
8702
|
});
|
|
9051
8703
|
// 中断镜像 review 的 stall-fix 口径:仅「本次登记前尚无 effortOverride」
|
|
9052
8704
|
// (真正的 phase-0→登记转变)才中断;phase-1 重新 direct 只更新产物。
|
|
9053
|
-
|
|
9054
|
-
|
|
9055
|
-
|
|
9056
|
-
}
|
|
9057
|
-
}
|
|
9058
|
-
catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
|
|
8705
|
+
// [3.0.1] 优先新版 interrupt()(ancestor=执行本工具的活体负责人 agent)。
|
|
8706
|
+
if (!hadEffortOverride)
|
|
8707
|
+
interruptChildContinuable(ctx.subagents, childSession.id, agent, parentId);
|
|
9059
8708
|
return {
|
|
9060
8709
|
ok: true,
|
|
9061
8710
|
planId: record.plan.planId,
|
|
@@ -9130,12 +8779,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9130
8779
|
* 登记 effortOverride」(真正的 phase-0→登记 转变)才中断;phase-1 的
|
|
9131
8780
|
* 重新 review 只更新梳理产物,绝不中断正在执行的回合。
|
|
9132
8781
|
*/
|
|
9133
|
-
|
|
9134
|
-
|
|
9135
|
-
|
|
9136
|
-
}
|
|
9137
|
-
}
|
|
9138
|
-
catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
|
|
8782
|
+
// [3.0.1] 优先新版 interrupt()(ancestor=执行本工具的活体负责人 agent)。
|
|
8783
|
+
if (preview.taskEffort && !hadEffortOverride)
|
|
8784
|
+
interruptChildContinuable(ctx.subagents, childSession.id, agent, parentId);
|
|
9139
8785
|
return {
|
|
9140
8786
|
ok: true,
|
|
9141
8787
|
planId: record.plan.planId,
|
|
@@ -9254,6 +8900,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9254
8900
|
let memberStatus = 'running';
|
|
9255
8901
|
let memberError = null;
|
|
9256
8902
|
try {
|
|
8903
|
+
// [3.0.1][P1a] 宿主 subagent.maxDepth < 2 时一次性告警(scope=计划根会话)。
|
|
8904
|
+
notifyDepthOverrideConflict(ctx, typeof parentSession?.header?.parentSession === 'string' ? parentSession.header.parentSession : (typeof parentId === 'string' ? parentId : null));
|
|
9257
8905
|
// [2.5.5][治本] 同 executeSubtask:spec 顶层契约(prompt/parent/cwd/agentOptions/maxDepth)。
|
|
9258
8906
|
const activation = await ctx.subagents.startActivation({
|
|
9259
8907
|
provider: 'spawn',
|
|
@@ -9326,7 +8974,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9326
8974
|
}
|
|
9327
8975
|
catch (error) {
|
|
9328
8976
|
memberStatus = 'rejected';
|
|
9329
|
-
|
|
8977
|
+
// [3.0.1][P1b] 宿主并发上限翻译为可行动中文提示(其余错误原样透出)。
|
|
8978
|
+
const friendlyActivationError = describeSubagentActivationError(error, `派发成员 ${assignment.member}`);
|
|
8979
|
+
memberError = truncate(String(friendlyActivationError?.message ?? friendlyActivationError), 300);
|
|
9330
8980
|
}
|
|
9331
8981
|
delegates.push({
|
|
9332
8982
|
member: assignment.member,
|
|
@@ -9453,6 +9103,28 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9453
9103
|
: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
|
|
9454
9104
|
};
|
|
9455
9105
|
}
|
|
9106
|
+
/*
|
|
9107
|
+
* [3.0.1] 认可闸门硬门禁:被按住(keyword/manual)且未派发的计划,派发一律
|
|
9108
|
+
* 拒绝——这是「未经用户认可不得开跑」的执行侧;唯一的合法出口是
|
|
9109
|
+
* dsh_workplan_release(它登记用户认可留痕后解除闸门并派发)。
|
|
9110
|
+
* 落点在终态闸门之后、deepThink 门禁之前:拒绝不产生副作用。
|
|
9111
|
+
*/
|
|
9112
|
+
if (isDispatchHeld(record)) {
|
|
9113
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
9114
|
+
return {
|
|
9115
|
+
ok: false,
|
|
9116
|
+
planId: record.plan.planId,
|
|
9117
|
+
phase: record.phase,
|
|
9118
|
+
running: false,
|
|
9119
|
+
alreadyRunning: false,
|
|
9120
|
+
complete: false,
|
|
9121
|
+
remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
|
|
9122
|
+
stats: snapshot.stats,
|
|
9123
|
+
code: 'DISPATCH_HELD',
|
|
9124
|
+
error: `计划处于认可闸门之下(${truncate(String(record.dispatchHold?.reason ?? '未注明原因'), 200)}):任务要求先经用户认可再执行,在用户明确认可前不得派发。`,
|
|
9125
|
+
hint: '请先征得用户明确认可,然后调用 dsh_workplan_release(可附 note 留痕、附 deepThink 直接开跑);不要用 dsh_workplan_dispatch 绕过闸门。',
|
|
9126
|
+
};
|
|
9127
|
+
}
|
|
9456
9128
|
/*
|
|
9457
9129
|
* [2.5.1] 主 Agent 两轮深度思考协议硬门禁(用户 2026-11-11 补充要求)。
|
|
9458
9130
|
*
|
|
@@ -9524,19 +9196,15 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9524
9196
|
* a model that missed the async result message had nothing to integrate.
|
|
9525
9197
|
* A wedged promise keeps the old stale escape hatch (see below).
|
|
9526
9198
|
*/
|
|
9527
|
-
|
|
9528
|
-
|
|
9529
|
-
if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
|
|
9530
|
-
try {
|
|
9531
|
-
await record.dispatchPromise;
|
|
9532
|
-
}
|
|
9533
|
-
catch (error) {
|
|
9534
|
-
pushRecordError(record, error);
|
|
9535
|
-
}
|
|
9536
|
-
finishRound(record, session);
|
|
9537
|
-
state.records.set(session.id, record);
|
|
9538
|
-
return dispatchSnapshotOf(record, { joined: true });
|
|
9199
|
+
try {
|
|
9200
|
+
await record.dispatchPromise;
|
|
9539
9201
|
}
|
|
9202
|
+
catch (error) {
|
|
9203
|
+
pushRecordError(record, error);
|
|
9204
|
+
}
|
|
9205
|
+
finishRound(record, session);
|
|
9206
|
+
state.records.set(session.id, record);
|
|
9207
|
+
return dispatchSnapshotOf(record, { joined: true });
|
|
9540
9208
|
}
|
|
9541
9209
|
if (record.dispatchPromise) {
|
|
9542
9210
|
/*
|
|
@@ -9549,21 +9217,6 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9549
9217
|
* stops claiming the plan is running and hands the work back instead.
|
|
9550
9218
|
*/
|
|
9551
9219
|
const startedAt = Number(record.dispatchStartedAt ?? 0);
|
|
9552
|
-
const staleAfter = limits.totalTimeoutMs > 0 ? limits.totalTimeoutMs + 120000 : NO_ROUND_BUDGET_MS + 120000;
|
|
9553
|
-
if (startedAt > 0 && Date.now() - startedAt > staleAfter) {
|
|
9554
|
-
return {
|
|
9555
|
-
ok: false,
|
|
9556
|
-
planId: record.plan.planId,
|
|
9557
|
-
alreadyRunning: true,
|
|
9558
|
-
stale: true,
|
|
9559
|
-
startedAt,
|
|
9560
|
-
elapsedMs: Date.now() - startedAt,
|
|
9561
|
-
phase: record.phase,
|
|
9562
|
-
stats: derivePlanSnapshot(record.statuses).stats,
|
|
9563
|
-
error: `上一次派发已持续 ${Math.round((Date.now() - startedAt) / 1000)}s 仍未返回,判定为已卡住`,
|
|
9564
|
-
hint: '请主 Agent 直接接手完成剩余子任务,不要再次派发;并在答复中说明本次是直接执行而非派发。',
|
|
9565
|
-
};
|
|
9566
|
-
}
|
|
9567
9220
|
/*
|
|
9568
9221
|
* [1.7.0] The idempotent answer now carries the progress itself.
|
|
9569
9222
|
*
|
|
@@ -9741,11 +9394,122 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9741
9394
|
function recordReadiness(record) {
|
|
9742
9395
|
return readinessOf(record);
|
|
9743
9396
|
}
|
|
9397
|
+
/**
|
|
9398
|
+
* [3.0.1] 显式认可闸门(双保险中不依赖关键词识别的那一半):主 Agent 在
|
|
9399
|
+
* 派发前把计划按住,用户明确认可后由 dsh_workplan_release 解除并开跑。
|
|
9400
|
+
* 只能设在尚未派发的计划上;已开跑的计划不设闸门(那是取消/重规划语义)。
|
|
9401
|
+
*/
|
|
9402
|
+
async function holdTool(agent, args) {
|
|
9403
|
+
const session = agent?.session;
|
|
9404
|
+
if (!session)
|
|
9405
|
+
throw new PlanError('只能在会话内操作计划闸门', 'NO_SESSION');
|
|
9406
|
+
if (!isRootSession(session))
|
|
9407
|
+
throw new PlanError('子 Agent 不能操作主计划闸门', 'NOT_ROOT');
|
|
9408
|
+
const record = state.records.get(session.id);
|
|
9409
|
+
const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined;
|
|
9410
|
+
if (requestedPlanId && record?.plan && record.plan.planId !== requestedPlanId) {
|
|
9411
|
+
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
|
|
9412
|
+
}
|
|
9413
|
+
if (!record?.plan)
|
|
9414
|
+
throw new PlanError('当前会话没有可操作闸门的计划', 'NO_PLAN');
|
|
9415
|
+
if (isTerminalPhase(record.phase) || record.cancelled === true) {
|
|
9416
|
+
throw new PlanError('计划已是终态,不再设闸门', 'PLAN_TERMINAL');
|
|
9417
|
+
}
|
|
9418
|
+
if (record.dispatchedAt || record.dispatchPromise) {
|
|
9419
|
+
return {
|
|
9420
|
+
ok: false,
|
|
9421
|
+
code: 'ALREADY_RUNNING',
|
|
9422
|
+
planId: record.plan.planId,
|
|
9423
|
+
error: '计划已开跑,闸门只能设在尚未派发的计划上;如需停止执行请取消后重新规划。',
|
|
9424
|
+
};
|
|
9425
|
+
}
|
|
9426
|
+
if (isDispatchHeld(record)) {
|
|
9427
|
+
return { ok: true, alreadyHeld: true, planId: record.plan.planId, hold: record.dispatchHold };
|
|
9428
|
+
}
|
|
9429
|
+
const reason = truncate(String(args?.reason ?? '').trim() || '主 Agent 显式闸门:等待用户认可', 300);
|
|
9430
|
+
record.dispatchHold = { kind: 'manual', reason, at: Date.now(), by: 'agent' };
|
|
9431
|
+
record.updatedAt = record.dispatchHold.at;
|
|
9432
|
+
try {
|
|
9433
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
9434
|
+
planId: record.plan.planId,
|
|
9435
|
+
subtaskId: null,
|
|
9436
|
+
status: record.phase,
|
|
9437
|
+
dispatchHold: record.dispatchHold,
|
|
9438
|
+
}));
|
|
9439
|
+
}
|
|
9440
|
+
catch (error) {
|
|
9441
|
+
pushRecordError(record, error);
|
|
9442
|
+
}
|
|
9443
|
+
return { ok: true, planId: record.plan.planId, hold: record.dispatchHold };
|
|
9444
|
+
}
|
|
9445
|
+
/**
|
|
9446
|
+
* [3.0.1] 解除认可闸门并立即派发。release 是「用户已明确认可」的唯一合法
|
|
9447
|
+
* 出口:它把按住事实追加进 gateHistory(只增审计,durable 回放),清空
|
|
9448
|
+
* dispatchHold,然后走 dispatchTool 的同一套闸门(终态/deepThink 等照常生效)。
|
|
9449
|
+
* 若 dispatch 因 deepThink 等门禁被拒,闸门保持已解除——认可事实是用户给的,
|
|
9450
|
+
* 不让它人质化;补齐 deepThink 后直接重发 dispatch 即可。
|
|
9451
|
+
*/
|
|
9452
|
+
async function releaseTool(agent, args, signal) {
|
|
9453
|
+
const session = agent?.session;
|
|
9454
|
+
if (!session)
|
|
9455
|
+
throw new PlanError('只能在会话内操作计划闸门', 'NO_SESSION');
|
|
9456
|
+
if (!isRootSession(session))
|
|
9457
|
+
throw new PlanError('子 Agent 不能操作主计划闸门', 'NOT_ROOT');
|
|
9458
|
+
const record = state.records.get(session.id);
|
|
9459
|
+
const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined;
|
|
9460
|
+
if (requestedPlanId && record?.plan && record.plan.planId !== requestedPlanId) {
|
|
9461
|
+
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
|
|
9462
|
+
}
|
|
9463
|
+
if (!record?.plan)
|
|
9464
|
+
throw new PlanError('当前会话没有可操作闸门的计划', 'NO_PLAN');
|
|
9465
|
+
if (!isDispatchHeld(record)) {
|
|
9466
|
+
return {
|
|
9467
|
+
ok: false,
|
|
9468
|
+
code: 'NOT_HELD',
|
|
9469
|
+
planId: record.plan.planId,
|
|
9470
|
+
error: '计划不在认可闸门之下:无需解除。要开跑请直接调用 dsh_workplan_dispatch。',
|
|
9471
|
+
};
|
|
9472
|
+
}
|
|
9473
|
+
const hold = record.dispatchHold;
|
|
9474
|
+
const note = truncate(String(args?.note ?? '').trim(), 300);
|
|
9475
|
+
const releasedAt = Date.now();
|
|
9476
|
+
record.dispatchHold = null;
|
|
9477
|
+
record.gateHistory = [
|
|
9478
|
+
...(Array.isArray(record.gateHistory) ? record.gateHistory : []),
|
|
9479
|
+
{ hold, releasedAt, note, by: 'agent' },
|
|
9480
|
+
].slice(-10);
|
|
9481
|
+
record.updatedAt = releasedAt;
|
|
9482
|
+
try {
|
|
9483
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
9484
|
+
planId: record.plan.planId,
|
|
9485
|
+
subtaskId: null,
|
|
9486
|
+
status: record.phase,
|
|
9487
|
+
dispatchHold: null,
|
|
9488
|
+
gateHistory: record.gateHistory,
|
|
9489
|
+
}));
|
|
9490
|
+
}
|
|
9491
|
+
catch (error) {
|
|
9492
|
+
pushRecordError(record, error);
|
|
9493
|
+
}
|
|
9494
|
+
const dispatched = await dispatchTool(agent, {
|
|
9495
|
+
planId: record.plan.planId,
|
|
9496
|
+
deepThink: args?.deepThink,
|
|
9497
|
+
mode: args?.mode,
|
|
9498
|
+
}, signal);
|
|
9499
|
+
return { ok: dispatched?.ok !== false, gateReleased: true, hold, note, dispatch: dispatched };
|
|
9500
|
+
}
|
|
9744
9501
|
function stopGateApplies(record, session, turn) {
|
|
9745
9502
|
if (!record?.plan)
|
|
9746
9503
|
return false;
|
|
9747
9504
|
if (record.degraded)
|
|
9748
9505
|
return false;
|
|
9506
|
+
/*
|
|
9507
|
+
* [3.0.1] 认可闸门:被按住且未派发的计划是在**等用户拍板**,不是在偷懒。
|
|
9508
|
+
* 此时既不 steer「请派发」(模型只会撞 DISPATCH_HELD 拒绝墙),headless
|
|
9509
|
+
* 也不许按「未完成」硬失败——用户还没认可,谈不上未完成。
|
|
9510
|
+
*/
|
|
9511
|
+
if (isDispatchHeld(record) && !record.dispatchedAt)
|
|
9512
|
+
return false;
|
|
9749
9513
|
/*
|
|
9750
9514
|
* [1.9.0] 终态不再触发收尾 steer —— 这正是死锁的第二个出口(T8 I7)。
|
|
9751
9515
|
* cancelled 只有在本回合被结构化点名时才提醒一次(present 仍会硬拦);
|
|
@@ -9957,6 +9721,32 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9957
9721
|
}
|
|
9958
9722
|
return false;
|
|
9959
9723
|
}
|
|
9724
|
+
/*
|
|
9725
|
+
* [3.0.1] followup/queue 到达时立即取代旧后台规划。
|
|
9726
|
+
*
|
|
9727
|
+
* turn-stopping 正在 await 旧 planning.promise 时,新消息可能尚未进入下一次
|
|
9728
|
+
* pre-step;若只在那里 supersede,旧规划仍会跑完并迟到交付。官方
|
|
9729
|
+
* `agent/inbox/inserted` 在消息进入 live inbox 时即发本事件,因此这里先中止。
|
|
9730
|
+
* 内部 workplan 通知、社交/状态/空泛续跑均不取消;同任务重复投递保持幂等。
|
|
9731
|
+
*/
|
|
9732
|
+
function onInboxInserted(payload) {
|
|
9733
|
+
const session = payload?.agent?.session;
|
|
9734
|
+
if (!session || !isRootSession(session))
|
|
9735
|
+
return;
|
|
9736
|
+
const planning = state.planningInFlight?.get(session.id);
|
|
9737
|
+
if (!planning)
|
|
9738
|
+
return;
|
|
9739
|
+
const message = payload?.message;
|
|
9740
|
+
if (humanMessages([message]).length === 0)
|
|
9741
|
+
return;
|
|
9742
|
+
const taskText = taskTextFromMessages([message]);
|
|
9743
|
+
if (!taskText || isSocialMessage(taskText) || isVagueContinuation(taskText) || isStatusQuestion(taskText))
|
|
9744
|
+
return;
|
|
9745
|
+
if (planning.taskText === taskText)
|
|
9746
|
+
return;
|
|
9747
|
+
planning.superseded = true;
|
|
9748
|
+
planning.controller.abort();
|
|
9749
|
+
}
|
|
9960
9750
|
async function onTurnStopping(payload) {
|
|
9961
9751
|
try {
|
|
9962
9752
|
const agent = payload?.agent;
|
|
@@ -9974,15 +9764,50 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
9974
9764
|
*/
|
|
9975
9765
|
if (state.activeTurns?.get?.(session.id) !== turn && !turnCarriesPlanWork(session, turn, known))
|
|
9976
9766
|
return;
|
|
9977
|
-
|
|
9978
|
-
|
|
9979
|
-
|
|
9980
|
-
|
|
9767
|
+
/*
|
|
9768
|
+
* [3.0.1] 后台规划必须和本回合闭环,不能只靠“请勿提前收尾”的软提示。
|
|
9769
|
+
* 规划期间 record.plan 为空,旧 stopGateApplies 会直接放行;先等当前规划
|
|
9770
|
+
* 承诺结算,再读取最新 record,避免主 Agent 在计划出现前答复并停止回合。
|
|
9771
|
+
*/
|
|
9772
|
+
let record = state.records.get(session.id) ?? known;
|
|
9773
|
+
const planning = state.planningInFlight?.get(session.id);
|
|
9774
|
+
if (planning?.promise) {
|
|
9775
|
+
try {
|
|
9776
|
+
await planning.promise;
|
|
9777
|
+
}
|
|
9778
|
+
catch { /* 后台规划自身已记录降级/错误 */ }
|
|
9779
|
+
/*
|
|
9780
|
+
* 等待期间若同回合后续 step 已用新任务取代旧规划,本次旧收尾必须退出;
|
|
9781
|
+
* 新规划的收尾会自行等待并交回,绝不能在这里消费旧结果或误 steer。
|
|
9782
|
+
*/
|
|
9783
|
+
const latestPlanning = state.planningInFlight?.get(session.id);
|
|
9784
|
+
if (latestPlanning && latestPlanning !== planning)
|
|
9785
|
+
return;
|
|
9786
|
+
record = state.records.get(session.id) ?? reconstructFromSession(session) ?? record;
|
|
9787
|
+
}
|
|
9788
|
+
if (!record?.plan && record?.planningCompletionPending !== true) {
|
|
9981
9789
|
// [1.8.14] N5:优先按本回合结算消息里点名的计划重建,而不是最后生成的计划。
|
|
9982
|
-
|
|
9790
|
+
// 后台降级/澄清虽然没有 plan,也必须先交回主 Agent,不能被旧回放覆盖。
|
|
9791
|
+
record = reconstructFromSession(session, planIdFromTurn(session, turn)) ?? record;
|
|
9983
9792
|
if (record?.plan)
|
|
9984
9793
|
state.records.set(session.id, record);
|
|
9985
9794
|
}
|
|
9795
|
+
/*
|
|
9796
|
+
* 即使规划在 turn-stopping 前已完成,也必须把结果交回主 Agent 消费一次。
|
|
9797
|
+
* 标记只挂在后台规划的终态 record 上;held 计划下一步仍等待用户认可,
|
|
9798
|
+
* 不会落入普通“未完成计划”循环。plan mode 也要先完成这次交回。
|
|
9799
|
+
*/
|
|
9800
|
+
if (Number(record?.createdTurn ?? record?.plan?.createdTurn) === turn && record?.planningCompletionPending === true) {
|
|
9801
|
+
record.planningCompletionPending = false;
|
|
9802
|
+
agent.steer(makeUserMessage([
|
|
9803
|
+
'【后台规划结果待处理】任务分解已经结束,结果已写入本会话。',
|
|
9804
|
+
'请立即读取最新结果并据此继续:若计划已生成,先向用户展示计划并遵守其中的认可闸门或派发要求;若处于认可闸门,只能针对这份已生成的计划请求认可,不得再说“计划尚未生成”;若规划降级或需要澄清,如实说明原因并提出下一步。',
|
|
9805
|
+
'不得把本回合停留在“计划仍在生成”的旧状态。',
|
|
9806
|
+
].join('\n'), { kind: 'workplan-planning-complete', form: 'notice' }));
|
|
9807
|
+
return;
|
|
9808
|
+
}
|
|
9809
|
+
if (isPlanModeActive(ctx, session))
|
|
9810
|
+
return;
|
|
9986
9811
|
if (!stopGateApplies(record, session, turn))
|
|
9987
9812
|
return;
|
|
9988
9813
|
if (record.dispatchPromise) {
|
|
@@ -10723,6 +10548,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
10723
10548
|
state,
|
|
10724
10549
|
limits,
|
|
10725
10550
|
onPreStep,
|
|
10551
|
+
onInboxInserted,
|
|
10726
10552
|
onTurnStopping,
|
|
10727
10553
|
presentDenialReason,
|
|
10728
10554
|
presentDenialVerdict,
|
|
@@ -10732,6 +10558,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
10732
10558
|
updateStatus,
|
|
10733
10559
|
cancelPlan,
|
|
10734
10560
|
dispatchTool,
|
|
10561
|
+
holdTool,
|
|
10562
|
+
releaseTool,
|
|
10735
10563
|
statusTool,
|
|
10736
10564
|
followupTool,
|
|
10737
10565
|
escalateTool,
|
|
@@ -10804,7 +10632,13 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
10804
10632
|
}
|
|
10805
10633
|
if (!isRootSession(session))
|
|
10806
10634
|
return downstream;
|
|
10807
|
-
|
|
10635
|
+
/*
|
|
10636
|
+
* 后续 step 通常是工具续跑,不能重复规划;但后台规划未结算时,DSH 会把
|
|
10637
|
+
* steering/followup 的新人类任务作为同回合下一 step 送达(官方生命周期:
|
|
10638
|
+
* next-step input → pre-step)。此时必须进入下方分类与 supersede,否则新任务
|
|
10639
|
+
* 被静默跳过、旧计划随后迟到覆盖。相同 taskText 仍会在下方去重返回。
|
|
10640
|
+
*/
|
|
10641
|
+
if (payload.step !== 1 && !state.planningInFlight?.get(session.id))
|
|
10808
10642
|
return downstream;
|
|
10809
10643
|
// [2.5.5][T3] pre-step 窗口标记:规划/自动派发的头前通知一律暂存(治本)。
|
|
10810
10644
|
enterPreHeadWindow(session);
|
|
@@ -10839,6 +10673,17 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
10839
10673
|
if (!state.activeTurns)
|
|
10840
10674
|
state.activeTurns = new Map();
|
|
10841
10675
|
state.activeTurns.set(session.id, Number(payload.turn ?? 0));
|
|
10676
|
+
/*
|
|
10677
|
+
* 新的真实任务到达时,旧任务的后台规划不得再迟到覆盖新任务。
|
|
10678
|
+
* 社交/状态消息在上方已提前返回,不会误取消;同一任务的重复 pre-step 只去重。
|
|
10679
|
+
*/
|
|
10680
|
+
const priorPlanning = state.planningInFlight?.get(session.id);
|
|
10681
|
+
if (priorPlanning) {
|
|
10682
|
+
if (priorPlanning.taskText === taskText)
|
|
10683
|
+
return downstream;
|
|
10684
|
+
priorPlanning.superseded = true;
|
|
10685
|
+
priorPlanning.controller.abort();
|
|
10686
|
+
}
|
|
10842
10687
|
const conversationContext = recentConversation(session);
|
|
10843
10688
|
if (existing?.plan?.createdTurn === payload.turn)
|
|
10844
10689
|
return downstream;
|
|
@@ -10866,6 +10711,13 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
10866
10711
|
// would make the plan disappear before the main Agent can act on approval.
|
|
10867
10712
|
if (existing?.plan && existing.planMode && !existing.dispatchedAt)
|
|
10868
10713
|
return downstream;
|
|
10714
|
+
/*
|
|
10715
|
+
* [3.0.1] 认可闸门同理:被按住等用户认可的计划不得被下一条用户消息自动
|
|
10716
|
+
* 取消(wp-e745a477 事故:主 Agent 正在等用户回复,计划已被自动派发出去;
|
|
10717
|
+
* 修复后若计划被闸门按住,保护它活到用户答复、release 放行)。
|
|
10718
|
+
*/
|
|
10719
|
+
if (existing?.plan && isDispatchHeld(existing) && !existing.dispatchedAt)
|
|
10720
|
+
return downstream;
|
|
10869
10721
|
// A plan committed but not yet dispatched must not be overwritten in the
|
|
10870
10722
|
// same turn; a later turn may supersede it, otherwise one abandoned plan
|
|
10871
10723
|
// would lock planning forever.
|
|
@@ -10957,6 +10809,16 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
10957
10809
|
})]);
|
|
10958
10810
|
}
|
|
10959
10811
|
}
|
|
10812
|
+
/*
|
|
10813
|
+
* [3.0.1] 认可闸门:任务锚点要求「先经用户认可再执行」时,计划照出、按住不派。
|
|
10814
|
+
* 识别结果随本函数流入计划创建尾(approvalGateVerdict):创建时写入
|
|
10815
|
+
* record.dispatchHold、跳过 autoDispatch,直到用户明确认可、主 Agent 调用
|
|
10816
|
+
* dsh_workplan_release。DSH_WORKPLAN_APPROVAL_GATE=0 时识别关闭(显式
|
|
10817
|
+
* 闸门 dsh_workplan_hold 不受影响)。
|
|
10818
|
+
*/
|
|
10819
|
+
const approvalGateVerdict = approvalGateDetectionDisabled()
|
|
10820
|
+
? { held: false, matched: [], reason: '' }
|
|
10821
|
+
: detectApprovalGate(taskText);
|
|
10960
10822
|
const modelSelection = resolveModelSelection(ctx, payload);
|
|
10961
10823
|
if (!modelSelection?.provider || !modelSelection?.model) {
|
|
10962
10824
|
const message = buildDegradedMessage({
|
|
@@ -11073,13 +10935,26 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11073
10935
|
};
|
|
11074
10936
|
if (!state.planningInFlight)
|
|
11075
10937
|
state.planningInFlight = new Map();
|
|
11076
|
-
|
|
11077
|
-
|
|
11078
|
-
|
|
10938
|
+
const planningController = new AbortController();
|
|
10939
|
+
const forwardPayloadAbort = () => planningController.abort();
|
|
10940
|
+
if (payload.signal.aborted)
|
|
10941
|
+
planningController.abort();
|
|
10942
|
+
else
|
|
10943
|
+
payload.signal.addEventListener('abort', forwardPayloadAbort, { once: true });
|
|
10944
|
+
const planningSignal = planningController.signal;
|
|
10945
|
+
const planningEntry = {
|
|
10946
|
+
startedAt: planningStartedAt,
|
|
10947
|
+
turn: payload.turn,
|
|
10948
|
+
taskText,
|
|
10949
|
+
controller: planningController,
|
|
10950
|
+
superseded: false,
|
|
10951
|
+
promise: null,
|
|
10952
|
+
};
|
|
10953
|
+
state.planningInFlight.set(session.id, planningEntry);
|
|
11079
10954
|
const runPlanningInBackground = async () => {
|
|
11080
10955
|
let plannerAttempt = 1;
|
|
11081
10956
|
const onPlannerProgress = createPlannerProgressReporter({
|
|
11082
|
-
signal:
|
|
10957
|
+
signal: planningSignal,
|
|
11083
10958
|
record: planningRecord,
|
|
11084
10959
|
setRecord: (record) => state.records.set(session.id, record),
|
|
11085
10960
|
appendNotice: (text) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
|
|
@@ -11095,7 +10970,7 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11095
10970
|
* 不触碰 system/message,不会引入会话日志损坏;finally 里 stop,绝不残留。
|
|
11096
10971
|
*/
|
|
11097
10972
|
const planningHeartbeat = createPlanningHeartbeat({
|
|
11098
|
-
signal:
|
|
10973
|
+
signal: planningSignal,
|
|
11099
10974
|
appendNotice: (text) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
|
|
11100
10975
|
intervalMs: planningHeartbeatIntervalMs(process.env.DSH_WORKPLAN_PLANNING_HEARTBEAT_MS ?? PLANNING_HEARTBEAT_MS),
|
|
11101
10976
|
startedAt: planningStartedAt,
|
|
@@ -11109,7 +10984,7 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11109
10984
|
cwd: session.header?.cwd ?? options.cwd,
|
|
11110
10985
|
sessionId: session.id,
|
|
11111
10986
|
modelSelection,
|
|
11112
|
-
signal:
|
|
10987
|
+
signal: planningSignal,
|
|
11113
10988
|
plannerTimeoutMs: normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
|
|
11114
10989
|
plannerIdleTimeoutMs: normalisePlannerWindow(options?.limits?.plannerIdleTimeoutMs ?? options?.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
|
|
11115
10990
|
telemetry: plannerTelemetry,
|
|
@@ -11125,31 +11000,22 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11125
11000
|
},
|
|
11126
11001
|
conversationContext,
|
|
11127
11002
|
sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
|
|
11128
|
-
|
|
11129
|
-
* Hand the real limits to the planner. Without them it had no idea the
|
|
11130
|
-
* round budget was 20 minutes and happily planned 15 heavy subtasks,
|
|
11131
|
-
* which then died at the budget wall. The prompt now states the budget
|
|
11132
|
-
* and asks for `estimateMinutes` on every subtask.
|
|
11133
|
-
*/
|
|
11003
|
+
// 旧 totalTimeoutMs/childTimeoutMs 配置不再注入规划器;只保留非时间资源约束。
|
|
11134
11004
|
budget: {
|
|
11135
|
-
totalMinutes:
|
|
11136
|
-
|
|
11137
|
-
: 0,
|
|
11138
|
-
childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
|
|
11005
|
+
totalMinutes: 0,
|
|
11006
|
+
childMinutes: 0,
|
|
11139
11007
|
concurrency: MAX_CONCURRENT,
|
|
11140
11008
|
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
11141
11009
|
},
|
|
11142
11010
|
});
|
|
11143
11011
|
}
|
|
11144
11012
|
catch (error) {
|
|
11145
|
-
if (
|
|
11013
|
+
if (planningSignal.aborted) {
|
|
11146
11014
|
/*
|
|
11147
|
-
*
|
|
11148
|
-
*
|
|
11149
|
-
* 「进行中」;若本轮前已有旧计划记录,恢复它——中止不该把用户上一份
|
|
11150
|
-
* 终态进度从内存里挤掉(旧实现中止路径不写记录,此行为保持不变)。
|
|
11015
|
+
* 用户中止或被新任务取代都静默退出;后者尤其不得恢复旧计划、写降级通知,
|
|
11016
|
+
* 否则已取消的旧规划会迟到覆盖新任务的占位记录。
|
|
11151
11017
|
*/
|
|
11152
|
-
if (existing?.plan)
|
|
11018
|
+
if (!planningEntry.superseded && existing?.plan)
|
|
11153
11019
|
state.records.set(session.id, existing);
|
|
11154
11020
|
return;
|
|
11155
11021
|
}
|
|
@@ -11174,12 +11040,14 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11174
11040
|
createdAt,
|
|
11175
11041
|
updatedAt: createdAt,
|
|
11176
11042
|
createdTurn: payload.turn,
|
|
11043
|
+
planningCompletionPending: true,
|
|
11177
11044
|
});
|
|
11178
|
-
|
|
11045
|
+
deliver([buildClarifyMessage({
|
|
11179
11046
|
rule: 'AUDIT',
|
|
11180
11047
|
reason: error.message,
|
|
11181
11048
|
question: typeof error.details === 'string' && error.details.trim() !== '' ? error.details : '',
|
|
11182
11049
|
})]);
|
|
11050
|
+
return;
|
|
11183
11051
|
}
|
|
11184
11052
|
const planId = `wp-${randomUUID()}`;
|
|
11185
11053
|
const createdAt = Date.now();
|
|
@@ -11205,6 +11073,7 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11205
11073
|
createdAt,
|
|
11206
11074
|
updatedAt: createdAt,
|
|
11207
11075
|
createdTurn: payload.turn,
|
|
11076
|
+
planningCompletionPending: true,
|
|
11208
11077
|
});
|
|
11209
11078
|
return deliver([message]);
|
|
11210
11079
|
}
|
|
@@ -11212,14 +11081,20 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11212
11081
|
// [2.5.2] 无论成功/降级/中止,规划结束即停心跳,绝不残留定时器。
|
|
11213
11082
|
planningHeartbeat.stop();
|
|
11214
11083
|
}
|
|
11215
|
-
if (
|
|
11216
|
-
//
|
|
11217
|
-
if (existing?.plan)
|
|
11084
|
+
if (planningSignal.aborted) {
|
|
11085
|
+
// 用户中止或新任务取代:旧规划结果不得再落入会话。
|
|
11086
|
+
if (!planningEntry.superseded && existing?.plan)
|
|
11218
11087
|
state.records.set(session.id, existing);
|
|
11219
11088
|
return;
|
|
11220
11089
|
}
|
|
11221
11090
|
const planId = `wp-${randomUUID()}`;
|
|
11222
11091
|
const createdAt = Date.now();
|
|
11092
|
+
/*
|
|
11093
|
+
* [3.0.1] 认可闸门:任务锚点命中「先经用户认可再执行」门槛语时,计划照出、
|
|
11094
|
+
* 按住不派(dispatchHold 落档),直到用户明确认可、主 Agent 调用
|
|
11095
|
+
* dsh_workplan_release。必须在 record 字面量之前声明——字面量引用了它。
|
|
11096
|
+
*/
|
|
11097
|
+
const approvalHeld = !planMode && approvalGateVerdict.held;
|
|
11223
11098
|
const fullPlan = attachPlanMeta(plan, {
|
|
11224
11099
|
planId,
|
|
11225
11100
|
sessionId: session.id,
|
|
@@ -11242,14 +11117,33 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11242
11117
|
modelSelection,
|
|
11243
11118
|
conversationContext,
|
|
11244
11119
|
planMode,
|
|
11120
|
+
planningCompletionPending: true,
|
|
11121
|
+
/*
|
|
11122
|
+
* [3.0.1] 认可闸门落档:keyword=任务锚点命中门槛语;manual=dsh_workplan_hold
|
|
11123
|
+
* 显式按住。release 置 null(事实本身追加进 gateHistory 审计)。
|
|
11124
|
+
*/
|
|
11125
|
+
...(approvalHeld
|
|
11126
|
+
? {
|
|
11127
|
+
dispatchHold: {
|
|
11128
|
+
kind: 'keyword',
|
|
11129
|
+
reason: approvalGateVerdict.reason,
|
|
11130
|
+
at: createdAt,
|
|
11131
|
+
by: 'system',
|
|
11132
|
+
},
|
|
11133
|
+
}
|
|
11134
|
+
: {}),
|
|
11245
11135
|
};
|
|
11246
11136
|
state.records.set(session.id, record);
|
|
11247
11137
|
/*
|
|
11248
11138
|
* [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
|
|
11249
11139
|
* async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
|
|
11250
11140
|
* plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
|
|
11141
|
+
*
|
|
11142
|
+
* [3.0.1] 认可闸门(approvalHeld,声明见 record 字面量之前):任务锚点命中
|
|
11143
|
+
* 「先经用户认可再执行」门槛语时同样不自动派发——用户明确认可、主 Agent
|
|
11144
|
+
* 调用 dsh_workplan_release 之前,计划只展示、任何派发都被拒。
|
|
11251
11145
|
*/
|
|
11252
|
-
const autoDispatched = !planMode && options?.autoDispatch !== false;
|
|
11146
|
+
const autoDispatched = !planMode && !approvalHeld && options?.autoDispatch !== false;
|
|
11253
11147
|
/*
|
|
11254
11148
|
* Plan-first: commit the plan with this step and let the main Agent call
|
|
11255
11149
|
* dsh_workplan_dispatch. Dispatching here would hide the plan until every
|
|
@@ -11263,12 +11157,11 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11263
11157
|
* cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
|
|
11264
11158
|
*/
|
|
11265
11159
|
const planMessage = buildPlanMessage(fullPlan, {
|
|
11266
|
-
totalBudgetMinutes:
|
|
11267
|
-
? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
|
|
11268
|
-
: 0,
|
|
11160
|
+
totalBudgetMinutes: 0,
|
|
11269
11161
|
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
11270
11162
|
planMode,
|
|
11271
11163
|
autoDispatched,
|
|
11164
|
+
approvalHeld,
|
|
11272
11165
|
});
|
|
11273
11166
|
/*
|
|
11274
11167
|
* [3.0.0][顺序] 必须先让计划可见,再开跑、再发「分配完成」:
|
|
@@ -11277,6 +11170,33 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11277
11170
|
* 先 deliver 计划消息,再启动自动派发。
|
|
11278
11171
|
*/
|
|
11279
11172
|
if (!planMode) {
|
|
11173
|
+
if (approvalHeld) {
|
|
11174
|
+
/*
|
|
11175
|
+
* [3.0.1] 认可闸门:durable 落档(与 mainDeepThink 同一写入口径,
|
|
11176
|
+
* subtaskId=null 计划级)——刷新/重启后回放读档,闸门不丢;
|
|
11177
|
+
* 随后发用户可见通知,计划保持 phase=pending、不派发。
|
|
11178
|
+
*/
|
|
11179
|
+
try {
|
|
11180
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
11181
|
+
planId: fullPlan.planId,
|
|
11182
|
+
subtaskId: null,
|
|
11183
|
+
status: record.phase,
|
|
11184
|
+
dispatchHold: record.dispatchHold,
|
|
11185
|
+
}));
|
|
11186
|
+
}
|
|
11187
|
+
catch (error) {
|
|
11188
|
+
pushRecordError(record, error);
|
|
11189
|
+
}
|
|
11190
|
+
deliver([
|
|
11191
|
+
planMessage,
|
|
11192
|
+
makeUserMessage([
|
|
11193
|
+
'🔒 认可闸门已生效:您的任务要求「先经用户认可再执行」,本计划已生成但暂不分派任务。',
|
|
11194
|
+
`命中依据:${approvalGateVerdict.reason}`,
|
|
11195
|
+
'在您明确回复认可之前,任何派发(自动或手动)都会被拒绝;您认可后,请告知主 Agent 调用 dsh_workplan_release 开跑。',
|
|
11196
|
+
].join('\n'), { kind: 'workplan-hold', form: 'notice', summary: '认可闸门已生效:等待用户认可后再派发' }),
|
|
11197
|
+
]);
|
|
11198
|
+
return;
|
|
11199
|
+
}
|
|
11280
11200
|
deliver([planMessage]);
|
|
11281
11201
|
if (autoDispatched) {
|
|
11282
11202
|
record.dispatchedAt = Date.now();
|
|
@@ -11304,17 +11224,24 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
11304
11224
|
};
|
|
11305
11225
|
return deliver([planMessage, note]);
|
|
11306
11226
|
};
|
|
11307
|
-
|
|
11227
|
+
const planningPromise = (async () => {
|
|
11308
11228
|
try {
|
|
11309
11229
|
await runPlanningInBackground();
|
|
11310
11230
|
}
|
|
11311
11231
|
catch (error) {
|
|
11312
|
-
|
|
11232
|
+
if (!planningEntry.superseded)
|
|
11233
|
+
pushRecordError(planningRecord, error);
|
|
11313
11234
|
}
|
|
11314
11235
|
finally {
|
|
11315
|
-
|
|
11236
|
+
payload.signal.removeEventListener('abort', forwardPayloadAbort);
|
|
11237
|
+
// 旧任务被取代后,只能清理自己的登记,不能删掉新任务的 in-flight。
|
|
11238
|
+
if (state.planningInFlight.get(session.id) === planningEntry) {
|
|
11239
|
+
state.planningInFlight.delete(session.id);
|
|
11240
|
+
}
|
|
11316
11241
|
}
|
|
11317
11242
|
})();
|
|
11243
|
+
planningEntry.promise = planningPromise;
|
|
11244
|
+
void planningPromise;
|
|
11318
11245
|
/*
|
|
11319
11246
|
* 同步注入给本步模型的说明:先等计划,不要自己动手做用户的活。文案复用
|
|
11320
11247
|
* 用户逐字冻结的 STATUS_ASSIGNING_TEXT,不另造第二份固定文案。
|