dsh-workplan 2.3.2 → 3.0.0
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 +123 -0
- package/README.en.md +2 -2
- package/README.md +2 -2
- package/README.zh.md +2 -2
- package/client.js +103 -3
- package/docs/cc/ADV-FSP-FUNCTIONAL-SPEC.md +3 -2
- package/docs/cc/AVA-VULNERABILITY-ANALYSIS.md +12 -2
- package/docs/cc/SECURITY-TARGET.md +1 -0
- package/docs/release-record-2.3.2-20261110.md +25 -0
- package/lib/client.js +103 -3
- package/lib/comm-format.js +58 -6
- package/lib/criterion.js +215 -0
- package/lib/dept-journal.js +319 -0
- package/lib/host.js +279 -15
- package/lib/llm-rules.js +478 -0
- package/lib/plan.js +1537 -136
- package/lib/replan.js +66 -44
- package/lib/runtime.js +3458 -628
- package/lib/three-phase.js +106 -20
- package/lib/understanding.js +18 -3
- package/lib/v3-contract.js +431 -0
- package/lib/watchdog.js +6 -1
- package/package.json +2 -2
- package/src/client.ts +110 -3
- package/src/comm-format.ts +63 -5
- package/src/criterion.ts +262 -0
- package/src/dept-journal.ts +373 -0
- package/src/host.ts +288 -16
- package/src/llm-rules.ts +667 -0
- package/src/plan.ts +1560 -130
- package/src/replan.ts +64 -42
- package/src/runtime.ts +2958 -200
- package/src/three-phase.ts +147 -20
- package/src/understanding.ts +20 -3
- package/src/v3-contract.ts +470 -0
- package/src/watchdog.ts +6 -1
package/src/runtime.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { randomUUID } from 'node:crypto'
|
|
16
|
-
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
16
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
|
|
17
17
|
import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
|
|
18
18
|
|
|
19
19
|
import {
|
|
@@ -25,11 +25,14 @@ import {
|
|
|
25
25
|
resolveLeadAgentId,
|
|
26
26
|
validateNoticeChannel,
|
|
27
27
|
} from './notice-channel.js'
|
|
28
|
+
// [T5-channel][契约v1 §2] 部门消息留痕:冻结 API,只 import 不改(journal-member 实现)。
|
|
29
|
+
import { appendDeptMessage, makeDeptMessageId, readDeptMessages } from './dept-journal.js'
|
|
28
30
|
import {
|
|
29
31
|
MAX_CONCURRENT,
|
|
30
32
|
PlanError,
|
|
31
33
|
aggregateInvariantViolations,
|
|
32
34
|
appendUserMessage,
|
|
35
|
+
enterPreHeadWindow,
|
|
33
36
|
applyStatus,
|
|
34
37
|
attachPlanMeta,
|
|
35
38
|
blockCancelledDependents,
|
|
@@ -37,19 +40,36 @@ import {
|
|
|
37
40
|
buildCancelMessage,
|
|
38
41
|
buildClarifyMessage,
|
|
39
42
|
createPlannerProgressReporter,
|
|
43
|
+
// [2.5.2] 规划期间心跳(治整段静默以为死机):plan.ts 纯函数 + 注入工厂。
|
|
44
|
+
createPlanningHeartbeat,
|
|
45
|
+
planningHeartbeatIntervalMs,
|
|
46
|
+
// [2.5.2][stall-fix] 派发执行期进度心跳文案(同一工厂,buildMessage 注入)。
|
|
47
|
+
buildDispatchHeartbeat,
|
|
40
48
|
buildDegradedMessage,
|
|
41
49
|
buildPlanMessage,
|
|
50
|
+
// [2.3.10][T2] 用户要求1:规划前/派发前会话内耗时预告文案(plan.ts 纯函数)。
|
|
51
|
+
buildPhaseZeroLeaderPrompt,
|
|
52
|
+
buildPhaseZeroContinuationHint,
|
|
53
|
+
buildPlanningPreAnnouncement,
|
|
54
|
+
buildDispatchPreAnnouncement,
|
|
42
55
|
buildPlannerPrompt,
|
|
43
56
|
buildResultMessage,
|
|
44
57
|
buildStopSteerText,
|
|
45
58
|
createStatuses,
|
|
46
59
|
DEFAULT_REASONING_EFFORT,
|
|
47
60
|
deliveryReadiness,
|
|
61
|
+
// [T7][lead-decisions J2/G2] 负责人时长聚合纯函数:模型可读面与 delegate status
|
|
62
|
+
// 挂同一函数(看板载荷经 plan.ts normaliseStatusEntry 同源),读时派生不持久化。
|
|
63
|
+
deriveLeaderEstimate,
|
|
64
|
+
leaderEstimateRoster,
|
|
48
65
|
derivePlanSnapshot,
|
|
49
66
|
// [2.2.0][T4/O-3b] O-3b 消费接线:缺省协商上限由预估派生(plan.ts 纯函数,T3 已定稿)。
|
|
50
67
|
deriveSubtaskTimeoutMs,
|
|
51
68
|
extractJson,
|
|
52
69
|
flattenSubtasks,
|
|
70
|
+
// [T7] 关键进度收敛:单条 500 上限裁剪器+轮预算重置(C3)。
|
|
71
|
+
capKeyProgressText,
|
|
72
|
+
resetRoundInjectionBudget,
|
|
53
73
|
isRecord,
|
|
54
74
|
isSocialMessage,
|
|
55
75
|
isTerminalPhase,
|
|
@@ -73,12 +93,20 @@ import {
|
|
|
73
93
|
validatePlan,
|
|
74
94
|
applyResultStatuses,
|
|
75
95
|
adjudicateResult,
|
|
96
|
+
// [3.0.0] F10 专家汇报核验(adjudicateExpertReport)复用同一解析器。
|
|
97
|
+
parseEvidenceBlock,
|
|
98
|
+
// [2.5.2][T4b][D2] 备份归属校验需要从标记块内提取 JSON(裸 JSON 之外的第二入口)。
|
|
99
|
+
EVIDENCE_MARKER_BEGIN,
|
|
100
|
+
EVIDENCE_MARKER_END,
|
|
76
101
|
activeDenyCode,
|
|
77
102
|
MAX_CONVERSATION_CHARS,
|
|
78
103
|
MAX_ESCALATION_OPTIONS,
|
|
79
104
|
MAX_INSTRUCTION_CHARS,
|
|
80
105
|
MAX_QUESTION_CHARS,
|
|
81
106
|
parseUpdateMessage,
|
|
107
|
+
// [2.5.5][T10] 合并闸:回放按批展开,结算前把缓冲台账合并落盘。
|
|
108
|
+
parseUpdateMessages,
|
|
109
|
+
flushPendingWorkplanUpdates,
|
|
82
110
|
buildUpdateMessage,
|
|
83
111
|
normaliseHandoffs,
|
|
84
112
|
mergeHandoffEntriesByUpdatedAt,
|
|
@@ -88,10 +116,39 @@ import {
|
|
|
88
116
|
DEPARTMENT_IDS,
|
|
89
117
|
MAX_HANDOFF_RESPONSE_CHARS,
|
|
90
118
|
findSubtask,
|
|
119
|
+
EFFORT_STRENGTH_ORDER,
|
|
91
120
|
} from './plan.js'
|
|
121
|
+
// [3.0.0] 用户 2026-11-14 第 2、4 条:两条逐字冻结的会话固定文案。
|
|
122
|
+
import { STATUS_ASSIGNED_TEXT, STATUS_ASSIGNING_TEXT, checkExpertReport, checkSubtaskQualityRequirements, isQualityGatePlan } from './v3-contract.js'
|
|
92
123
|
import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
|
|
124
|
+
// [SCv2-T4] 判据层单一真源(用户 2026-11-13 裁决 B/B/B/B/A/A/B):生效边界 D-1、
|
|
125
|
+
// 例外批准 Q1-B、结算三选一 §3.5、单次墙钟 Q6-A、事前聚合 Q4-B。运行层常量不改。
|
|
126
|
+
import {
|
|
127
|
+
CRITERION_TARGET_MINUTES,
|
|
128
|
+
appendCriterionViolation,
|
|
129
|
+
attemptWallClockMsOf,
|
|
130
|
+
criterionExAnte,
|
|
131
|
+
criterionV2Active,
|
|
132
|
+
evaluateCriterion,
|
|
133
|
+
sanitizeCriterionException,
|
|
134
|
+
} from './criterion.js'
|
|
93
135
|
import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js'
|
|
94
|
-
|
|
136
|
+
// [2.3.9][T3] LLM 家族检测 + 推理等级静态约束(用户强制要求 1/2;详见 llm-rules.ts 头注释)。
|
|
137
|
+
// [2.3.9][T4b] 追加第三层派发纯逻辑核:buildLlmRulesBrief(要求 1/2 全文告知注入,
|
|
138
|
+
// 部门层与专家/组员层共用同一事实源)、planDelegations(负责人「先全面梳理再分配」
|
|
139
|
+
// 硬门禁 + 分工表校验 + 等级钳制)、buildDelegateePrompt(第三层任务书)。
|
|
140
|
+
import {
|
|
141
|
+
allowedEffortsForModel,
|
|
142
|
+
buildDelegateePrompt,
|
|
143
|
+
buildLlmRulesBrief,
|
|
144
|
+
classifyModelFamily,
|
|
145
|
+
correctEffortForModel,
|
|
146
|
+
highestEffortOf,
|
|
147
|
+
planDelegations,
|
|
148
|
+
buildPhaseZeroDelegateePrompt,
|
|
149
|
+
resolveTaskEffort,
|
|
150
|
+
} from './llm-rules.js'
|
|
151
|
+
import { phaseGateFromErrors, phaseSummaryLine, sanitizeMainDeepThink, validateMainDeepThink, validatePhaseEvidence } from './three-phase.js'
|
|
95
152
|
import {
|
|
96
153
|
lessonStats,
|
|
97
154
|
rankLessons,
|
|
@@ -208,7 +265,13 @@ function readinessOf(record: any, snapshot?: any) {
|
|
|
208
265
|
})
|
|
209
266
|
}
|
|
210
267
|
|
|
211
|
-
|
|
268
|
+
/**
|
|
269
|
+
* [2.5.2] 规划期间心跳间隔(默认 45s,DSH_WORKPLAN_PLANNING_HEARTBEAT_MS,
|
|
270
|
+
* 毫秒 ≥5000):runPlanner 仍在跑时按此间隔在会话里发一条可见进度通知,
|
|
271
|
+
* 治「持续流式但很慢的尝试整段静默、用户以为死机」(本会话 turn 1 实测
|
|
272
|
+
* 12.5 分钟零输出)。与失败重试通知正交,不改重试/超时语义。
|
|
273
|
+
*/
|
|
274
|
+
export const PLANNING_HEARTBEAT_MS = 45000
|
|
212
275
|
/**
|
|
213
276
|
* 无进展窗口(默认 300s,DSH_WORKPLAN_PLANNER_TIMEOUT_MS,毫秒 >0)。
|
|
214
277
|
*
|
|
@@ -221,19 +284,20 @@ export const PLANNER_TIMEOUT_MS = 300000
|
|
|
221
284
|
* 300.06s)规划器仍在工作却被 abort,自动分解直接降级——提高默认值或开放
|
|
222
285
|
* 配置都没有解决「按墙钟掐断一个正在产出的调用」这个结构问题。
|
|
223
286
|
*/
|
|
224
|
-
export const
|
|
287
|
+
export const PLANNER_TIMEOUT_MS = 300000
|
|
225
288
|
/**
|
|
226
289
|
* 首个 chunk 之后的「完全静默」窗口(默认 90s,DSH_WORKPLAN_PLANNER_IDLE_
|
|
227
290
|
* TIMEOUT_MS,毫秒 >0):文本、推理、usage 一个 chunk 都没有这么久,判定为
|
|
228
291
|
* 连接卡死而不是模型还在思考。这个常量在 2.1.6 之前只声明、从未接线(死
|
|
229
292
|
* 代码),现在真正参与计时;设为不小于无进展窗口即等价于关闭。
|
|
230
293
|
*/
|
|
231
|
-
export const
|
|
294
|
+
export const PLANNER_IDLE_TIMEOUT_MS = 90000
|
|
232
295
|
/**
|
|
233
296
|
* 绝对上限 = 无进展窗口 × 该倍数(默认 900s)。慢可以,慢到没边不行:它给
|
|
234
297
|
* 单次规划器尝试一个终点,保证规划失败永远是「有限时间后给出可执行建议」,
|
|
235
298
|
* 而不是无限占用本轮预算。
|
|
236
299
|
*/
|
|
300
|
+
export const PLANNER_HARD_MULTIPLIER = 3
|
|
237
301
|
/**
|
|
238
302
|
* [2.2.0][T13b/推理等级] 规划器默认推理档 = max(用户 2026-11-08 决策 5)。
|
|
239
303
|
*
|
|
@@ -276,9 +340,7 @@ export const DEFAULT_PLANNER_REASONING_EFFORT = 'max'
|
|
|
276
340
|
* 与宿主 resolveCallWithInfo 的「reasoning===undefined 时任何档位都抛错」对齐;
|
|
277
341
|
* - 能力查询不可用(宿主不暴露 / 查询抛错)⇒ 保持旧行为,绝不因钳制引入新故障。
|
|
278
342
|
*/
|
|
279
|
-
|
|
280
|
-
['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
|
|
281
|
-
)
|
|
343
|
+
// [3.0.0] 去副本:强度序单一真源为 plan.ts 导出的 EFFORT_STRENGTH_ORDER(上方已导入,本文件直接引用)。
|
|
282
344
|
|
|
283
345
|
/** 请求档位 → 模型支持清单内的等效钳制档;空清单返回 undefined(= 不发送该字段)。 */
|
|
284
346
|
export function clampEffortToSupported(effort: string, supported: readonly string[] | null | undefined): string | undefined {
|
|
@@ -346,6 +408,12 @@ export async function resolveSupportedEfforts(
|
|
|
346
408
|
* 2.0×60000, MIN, MAX)),本常量只在无预估、无显式值时兜底(③C2 零回归)。
|
|
347
409
|
* 时间是协商出来的安全兜底,不是固定交付期限:到点走 L4 安全兜底结算+
|
|
348
410
|
* 「待裁决」标记(延期 / 重试 / 接受),不表述为「强制结束」式固定期限误杀。
|
|
411
|
+
*
|
|
412
|
+
* [2.6.0][Q1-B/Q7-B] 分层:判据层完成目标 ≤10 分钟(默认必须达成,超出须用户
|
|
413
|
+
* 明确批准并留痕);本条协商上限属运行层安全兜底,数值与公式一律不变,且不构成
|
|
414
|
+
* 「允许慢」的许可。「延期(extendMs)」不再是主 Agent 单方可为——须先取得用户
|
|
415
|
+
* 批准留痕(任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=
|
|
416
|
+
* 未批准),未批准时按判据层未达标处理(不 done、转接替子任务)。
|
|
349
417
|
*/
|
|
350
418
|
export const CHILD_TIMEOUT_MS = 900000
|
|
351
419
|
/** No-progress window: the child's own session log stopped growing. */
|
|
@@ -363,6 +431,9 @@ export const MIN_CHILD_TIMEOUT_MS = 1000
|
|
|
363
431
|
* 单次绝对上限)(方案 §1③),2h 让「预告 60 分钟的子任务,其单次执行上限
|
|
364
432
|
* ≥ 60 分钟」(方案 C1)成立;tests/time-estimate-negotiation.test.ts 的
|
|
365
433
|
* expected 公式直接引用本常量,数值不同步会红灯。
|
|
434
|
+
*
|
|
435
|
+
* [2.6.0][Q7-B] 分层声明:120 分钟是运行层安全兜底(防失控),不是时长许可;
|
|
436
|
+
* 判据层完成目标为 ≤10 分钟(Q1/Q4),两层互不取代,数值与公式零改动。
|
|
366
437
|
*/
|
|
367
438
|
export const MAX_CHILD_TIMEOUT_MS = 7200000
|
|
368
439
|
export const MIN_CHILD_IDLE_MS = 1000
|
|
@@ -488,14 +559,15 @@ export function goalRoundPlanningTask(ctx: any, payload: any, existing: any) {
|
|
|
488
559
|
/**
|
|
489
560
|
* Whether an existing plan record still owns work in this session.
|
|
490
561
|
*
|
|
491
|
-
* `isTerminalPhase()`
|
|
492
|
-
*
|
|
493
|
-
*
|
|
562
|
+
* 终态(cancelled/superseded)判定复用 plan.ts 的同一真源 `isTerminalPhase()`
|
|
563
|
+
* (TERMINAL_PHASES),不再本地硬编码;goal 轮次入口在终态之外,done/ended/
|
|
564
|
+
* degraded/clarify 同样是「这一轮可以开始新计划」的历史记录,不能把 `/goal`
|
|
565
|
+
* 任务永久挡在自动分解之外。
|
|
494
566
|
*/
|
|
495
567
|
function planRecordIsLive(existing: any) {
|
|
496
568
|
if (!existing?.plan) return false
|
|
497
569
|
const phase = String(existing.phase ?? '')
|
|
498
|
-
return !['done', 'ended', '
|
|
570
|
+
return !isTerminalPhase(phase) && !['done', 'ended', 'clarify', 'degraded'].includes(phase)
|
|
499
571
|
}
|
|
500
572
|
|
|
501
573
|
/** Read the structured objective of the current goal view, when the service exists. */
|
|
@@ -804,11 +876,50 @@ export async function runPlanner(ctx: any, options: any) {
|
|
|
804
876
|
// 用户的成本预期,所以先归一化再进白名单。
|
|
805
877
|
const plannerEffortRaw = String(process.env.DSH_WORKPLAN_PLANNER_REASONING_EFFORT ?? '').trim().toLowerCase()
|
|
806
878
|
const plannerEffort = REASONING_EFFORTS.includes(plannerEffortRaw) ? plannerEffortRaw : ''
|
|
807
|
-
|
|
879
|
+
/*
|
|
880
|
+
* [2.3.9][T3/llm-rules] 用户强制要求 1/2(分配前先检测模型家族):qwen 开头
|
|
881
|
+
* 模型只允许 low / medium / xhigh,其余模型只允许 low / high / max。
|
|
882
|
+
* env 显式覆盖仍优先,覆盖值同样过静态收窄。静态约束先于宿主能力钳制执行
|
|
883
|
+
* (两道闸:静态表权威,能力面在其上继续交集钳制,均留痕,与 U7 裁决一致)。
|
|
884
|
+
* 模型名缺失⇒不施加静态约束并用原默认档,保持 [2.2.7]「无从判定⇒不阻断」旧行为。
|
|
885
|
+
*
|
|
886
|
+
* [2.5.2][stall-fix] 根因修复(用户报告「提交任务后长时间无反应/以为死机」):
|
|
887
|
+
* 旧默认档取家族最高档(qwen⇒xhigh、非 qwen⇒max),规划器要在最高推理档
|
|
888
|
+
* 生成整份大 JSON,实测单次规划 12-13 分钟——预告之后长时间只有心跳、没有
|
|
889
|
+
* 结果,用户体验即「死机」。规划是结构化分解(中等复杂度),默认档改为
|
|
890
|
+
* 家族中等档(qwen⇒medium、非 qwen⇒high),显著缩短首屏等待;需要最高档
|
|
891
|
+
* 的会话仍可用 DSH_WORKPLAN_PLANNER_REASONING_EFFORT 显式覆盖。中等档不在
|
|
892
|
+
* 合法集时回落最高档(不改变家族白名单语义)。
|
|
893
|
+
*/
|
|
894
|
+
const plannerStaticAllowed = allowedEffortsForModel(modelSelection?.model)
|
|
895
|
+
const plannerModerateDefault = classifyModelFamily(modelSelection?.model) === 'qwen' ? 'medium' : 'high'
|
|
896
|
+
const plannerFamilyDefault = (plannerStaticAllowed && plannerStaticAllowed.includes(plannerModerateDefault)
|
|
897
|
+
? plannerModerateDefault
|
|
898
|
+
: highestEffortOf(plannerStaticAllowed)) ?? DEFAULT_PLANNER_REASONING_EFFORT
|
|
899
|
+
const requestedPlannerEffort = plannerEffort || plannerFamilyDefault
|
|
900
|
+
const plannerEffortOriginLabel = plannerEffort ? 'env' : `default-${plannerFamilyDefault}`
|
|
901
|
+
const plannerStaticCorrection = plannerStaticAllowed && !plannerStaticAllowed.includes(requestedPlannerEffort)
|
|
902
|
+
? correctEffortForModel(requestedPlannerEffort, modelSelection?.model)
|
|
903
|
+
: null
|
|
904
|
+
const staticRulePlannerEffort = plannerStaticCorrection ? plannerStaticCorrection.effort : requestedPlannerEffort
|
|
905
|
+
const plannerStaticTrace = plannerStaticCorrection
|
|
906
|
+
? `→${classifyModelFamily(modelSelection?.model) === 'qwen' ? 'qwen-rule' : 'non-qwen-rule'}:${plannerStaticCorrection.requested}→${plannerStaticCorrection.effort}`
|
|
907
|
+
: ''
|
|
908
|
+
if (plannerStaticCorrection) {
|
|
909
|
+
console.warn('[dsh-workplan] planner reasoning effort corrected by LLM family rules:', JSON.stringify({
|
|
910
|
+
provider: modelSelection?.provider,
|
|
911
|
+
model: modelSelection?.model,
|
|
912
|
+
family: classifyModelFamily(modelSelection?.model),
|
|
913
|
+
requested: requestedPlannerEffort,
|
|
914
|
+
corrected: plannerStaticCorrection.effort,
|
|
915
|
+
allowed: plannerStaticAllowed,
|
|
916
|
+
reason: plannerStaticCorrection.reason,
|
|
917
|
+
}))
|
|
918
|
+
}
|
|
808
919
|
/*
|
|
809
920
|
* [2.2.7] 发送前按模型能力钳制档位:宿主对不支持的档位会在网络调用前直接
|
|
810
921
|
* 抛 UNSUPPORTED_REASONING_EFFORT,重试不自愈(终态),整次规划因此降级。
|
|
811
|
-
*
|
|
922
|
+
* 查询不可用时保持旧行为;查询成功后请求档钳制到清单内等效档,空清单
|
|
812
923
|
* (模型无 reasoning 元数据)则不发送档位字段。'' 在这里表示「不发送」。
|
|
813
924
|
*/
|
|
814
925
|
const plannerEffortSupport = await resolveSupportedEfforts(
|
|
@@ -818,13 +929,13 @@ export async function runPlanner(ctx: any, options: any) {
|
|
|
818
929
|
signal,
|
|
819
930
|
)
|
|
820
931
|
const effectivePlannerEffort = plannerEffortSupport === null
|
|
821
|
-
?
|
|
822
|
-
: (clampEffortToSupported(
|
|
823
|
-
if (plannerEffortSupport !== null && effectivePlannerEffort !==
|
|
932
|
+
? staticRulePlannerEffort
|
|
933
|
+
: (clampEffortToSupported(staticRulePlannerEffort, plannerEffortSupport) ?? '')
|
|
934
|
+
if (plannerEffortSupport !== null && effectivePlannerEffort !== staticRulePlannerEffort) {
|
|
824
935
|
console.warn('[dsh-workplan] planner reasoning effort clamped for model compatibility:', JSON.stringify({
|
|
825
936
|
provider: modelSelection?.provider,
|
|
826
937
|
model: modelSelection?.model,
|
|
827
|
-
requested:
|
|
938
|
+
requested: staticRulePlannerEffort,
|
|
828
939
|
effective: effectivePlannerEffort || '(omitted)',
|
|
829
940
|
supported: plannerEffortSupport,
|
|
830
941
|
}))
|
|
@@ -943,7 +1054,9 @@ export async function runPlanner(ctx: any, options: any) {
|
|
|
943
1054
|
const text = await collectStream(stream, onChunk, sink)
|
|
944
1055
|
lastText = text
|
|
945
1056
|
const raw = extractJson(text)
|
|
946
|
-
|
|
1057
|
+
// [2.3.9][T3] 事前约束:规划器显式写出集合外档位 → validatePlan 拒绝并点名,
|
|
1058
|
+
// 经重试回路回喂自纠(用户要求 1/2;模型名缺失⇒null⇒不施加)。
|
|
1059
|
+
const validated = validatePlan(raw, { allowedEfforts: allowedEffortsForModel(modelSelection.model) })
|
|
947
1060
|
if (validated.ok) {
|
|
948
1061
|
/*
|
|
949
1062
|
* [1.12.0] Structure alone is not understanding. Run the three-stage
|
|
@@ -961,10 +1074,33 @@ export async function runPlanner(ctx: any, options: any) {
|
|
|
961
1074
|
const plan: any = validated.plan
|
|
962
1075
|
plan.taskAnchor = guard.audit.anchor
|
|
963
1076
|
plan.understandingAudit = compactUnderstandingAudit(guard.audit)
|
|
1077
|
+
// [2.5.5] 归一化留痕随计划持久化,status/回放可见(治本不静默)。
|
|
1078
|
+
if (Array.isArray((validated as any).notes) && (validated as any).notes.length > 0) {
|
|
1079
|
+
plan.normalizations = (validated as any).notes
|
|
1080
|
+
}
|
|
964
1081
|
return plan
|
|
965
1082
|
}
|
|
966
1083
|
outcome = 'CONTEXT_GUARD'
|
|
967
1084
|
lastErrors = guard.errors.length > 0 ? guard.errors : guard.warnings
|
|
1085
|
+
/*
|
|
1086
|
+
* [3.0.1][治本] 只有用户本人能答复的校验错误(CLARIFY=要求自相矛盾、
|
|
1087
|
+
* CONTEXT=指代找不到先行词)禁止交回规划器重试:重试的所谓「修复」只能是
|
|
1088
|
+
* 模型替用户瞎猜,猜过守卫后计划照常自动派发——用户还没来得及答复,
|
|
1089
|
+
* 部门 Agent 已经对着猜出来的目标开工(本次用户报告的正是这一行为)。
|
|
1090
|
+
* 这类错误立即中止规划,由入口转成「先澄清」卡片等用户明确答复;
|
|
1091
|
+
* 只有 DEVIATION 这类规划器自己能改写的才继续重试。
|
|
1092
|
+
*/
|
|
1093
|
+
const askUser = lastErrors.filter((entry: any) => /^(?:CLARIFY|CONTEXT):/.test(String(entry)))
|
|
1094
|
+
if (askUser.length > 0) {
|
|
1095
|
+
const reason = askUser.map((entry: any) => String(entry).replace(/^(?:CLARIFY|CONTEXT):\s*/, '')).join(';')
|
|
1096
|
+
const hasClarify = askUser.some((entry: any) => String(entry).startsWith('CLARIFY'))
|
|
1097
|
+
const hasContext = askUser.some((entry: any) => String(entry).startsWith('CONTEXT'))
|
|
1098
|
+
const question = [
|
|
1099
|
+
hasClarify ? '上述互相矛盾/缺失的信息以哪个为准?请用户明确取舍' : '',
|
|
1100
|
+
hasContext ? '任务里的指代具体指哪个对象?请用户给出名称、路径或原内容' : '',
|
|
1101
|
+
].filter(Boolean).join(';')
|
|
1102
|
+
throw new PlanError(reason, 'CLARIFY_NEEDED', question)
|
|
1103
|
+
}
|
|
968
1104
|
continue
|
|
969
1105
|
}
|
|
970
1106
|
outcome = 'INVALID_PLAN'
|
|
@@ -975,6 +1111,14 @@ export async function runPlanner(ctx: any, options: any) {
|
|
|
975
1111
|
* 真实原因。这里优先读我们自己写进 controller.signal.reason 的判定码,
|
|
976
1112
|
* 再区分「用户/宿主主动取消」,最后才当作可重试的偶发错误。
|
|
977
1113
|
*/
|
|
1114
|
+
/*
|
|
1115
|
+
* [3.0.1] CLARIFY_NEEDED 是终态,不是可重试错误:原样上抛给入口转澄清卡片。
|
|
1116
|
+
* 必须最先判定——否则会被下面的泛化处理标成 outcome 并进入下一次重试。
|
|
1117
|
+
*/
|
|
1118
|
+
if (error instanceof PlanError && error.code === 'CLARIFY_NEEDED') {
|
|
1119
|
+
outcome = 'CLARIFY_NEEDED'
|
|
1120
|
+
throw error
|
|
1121
|
+
}
|
|
978
1122
|
const reason: any = controller.signal.aborted ? controller.signal.reason : undefined
|
|
979
1123
|
if (reason && PLANNER_ABORT_CODES.includes(String(reason.code))) {
|
|
980
1124
|
/*
|
|
@@ -1109,9 +1253,10 @@ export async function runPlanner(ctx: any, options: any) {
|
|
|
1109
1253
|
// 复盘把「主 Agent=high」误读成「规划器=high」。
|
|
1110
1254
|
// [2.2.7] 钳制发生时同样记录实际发出值('' = 未发送)。
|
|
1111
1255
|
reasoningEffort: effectivePlannerEffort,
|
|
1112
|
-
reasoningEffortSource:
|
|
1113
|
-
+
|
|
1114
|
-
|
|
1256
|
+
reasoningEffortSource: plannerEffortOriginLabel
|
|
1257
|
+
+ plannerStaticTrace
|
|
1258
|
+
+ (plannerEffortSupport !== null && effectivePlannerEffort !== staticRulePlannerEffort
|
|
1259
|
+
? `→clamped(${staticRulePlannerEffort})` : ''),
|
|
1115
1260
|
attempt,
|
|
1116
1261
|
taskChars: typeof taskText === 'string' ? taskText.length : 0,
|
|
1117
1262
|
promptChars,
|
|
@@ -1193,6 +1338,35 @@ function resultText(result: any) {
|
|
|
1193
1338
|
return text
|
|
1194
1339
|
}
|
|
1195
1340
|
|
|
1341
|
+
/*
|
|
1342
|
+
* [3.0.0] F10 专家汇报门禁接线(用户 2026-11-14 要求 7;契约同一事实源
|
|
1343
|
+
* src/comm-format.ts 的 F10 条目 / src/v3-contract.ts 的 checkExpertReport)。
|
|
1344
|
+
*
|
|
1345
|
+
* 第三层叶子(专家)的产出有两处结算回调消费(delegateTool dispatch /
|
|
1346
|
+
* selfEffort 接续),此前只看 stopReason:专家即使不写精简 report 对象也会被
|
|
1347
|
+
* 记成 done,F10 形同虚设。现在在两处回调的汇报入口统一过这道核验:
|
|
1348
|
+
* 只对「子会话正常结束且结果块声明 done」的汇报校验 report 对象
|
|
1349
|
+
* (keyResults/keyInfo/importantInfo/leadRequirements 四字段齐全、非空、
|
|
1350
|
+
* 不重复);缺失或重复即退回(该成员记 failed 并附 F10 拒因),绝不记 done。
|
|
1351
|
+
*
|
|
1352
|
+
* 最小侵入、只拦 done 路径:结果块无法解析 / 声明 blocked/partial 时维持原
|
|
1353
|
+
* 语义(受阻诊断归 escalate/instruct 通道),F1–F9 与三阶段既有判定不在此
|
|
1354
|
+
* 重复;replay/读档路径不经这两个回调,行为零变化。
|
|
1355
|
+
*/
|
|
1356
|
+
function adjudicateExpertReport(outcome: any): { ok: true } | { ok: false; rejection: string } {
|
|
1357
|
+
const text = resultText(outcome)
|
|
1358
|
+
const parsed = parseEvidenceBlock(text)
|
|
1359
|
+
const payload = parsed && typeof parsed === 'object' ? parsed.payload : null
|
|
1360
|
+
if (!payload || typeof payload !== 'object') return { ok: true }
|
|
1361
|
+
if (String(payload.status ?? '') !== 'done') return { ok: true }
|
|
1362
|
+
const report = checkExpertReport((payload as any).report)
|
|
1363
|
+
if (!Array.isArray(report.violations) || report.violations.length === 0) return { ok: true }
|
|
1364
|
+
return {
|
|
1365
|
+
ok: false,
|
|
1366
|
+
rejection: `专家汇报未通过 F10 精简汇报契约核验,结果退回重交:${report.violations.slice(0, 4).join(';')}`,
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1196
1370
|
async function disposeActivation(activation: any, record: any, subtaskId: string, guard?: SubtaskGuard) {
|
|
1197
1371
|
let timer: ReturnType<typeof setTimeout> | null = null
|
|
1198
1372
|
try {
|
|
@@ -1478,7 +1652,8 @@ export function timeoutBlockedPatch(subtask: any, cwd: any, message: string, art
|
|
|
1478
1652
|
/**
|
|
1479
1653
|
* [1.8.19] The round budget reset used to erase every trace of the attempt.
|
|
1480
1654
|
*
|
|
1481
|
-
* The
|
|
1655
|
+
* The `TOTAL_TIMEOUT` branch(整轮预算到点;现行默认 TOTAL_TIMEOUT_MS=0 即不设
|
|
1656
|
+
* 整轮硬预算,仅显式配置正数时启用)resets unfinished rows to `pending`, and
|
|
1482
1657
|
* `applyStatus` (by design) clears `childId / startedAt / finishedAt`. In the
|
|
1483
1658
|
* 2026-10-31 incident T10 had run for ~19 minutes and had already written its
|
|
1484
1659
|
* coverage report at 23:06:26 when the budget fired at 23:07:25; the card then
|
|
@@ -1559,6 +1734,23 @@ function settleFromOutput(
|
|
|
1559
1734
|
* 交付才被用户发现。
|
|
1560
1735
|
*/
|
|
1561
1736
|
expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
|
|
1737
|
+
/*
|
|
1738
|
+
* [3.0.0][用户要求 7/10/11] 格式层级:计划行=部门负责人,结果必须带
|
|
1739
|
+
* departmentSummary(F11);专家结果必须带 report(F10)。结算时按行上
|
|
1740
|
+
* 已派发的专家名单做覆盖度核对。缺省(无层级/旧回放)不查新条目。
|
|
1741
|
+
*/
|
|
1742
|
+
formatTier: (Array.isArray(record?.statuses)
|
|
1743
|
+
? record.statuses
|
|
1744
|
+
.find((item: any) => item?.subtaskId === subtask?.id)?.delegates
|
|
1745
|
+
?.map((item: any) => String(item?.member ?? ''))
|
|
1746
|
+
.filter((name: string) => name !== '') ?? []
|
|
1747
|
+
: []).length > 0 ? 'leader' : undefined,
|
|
1748
|
+
expectedExperts: Array.isArray(record?.statuses)
|
|
1749
|
+
? record.statuses
|
|
1750
|
+
.find((item: any) => item?.subtaskId === subtask?.id)?.delegates
|
|
1751
|
+
?.map((item: any) => String(item?.member ?? ''))
|
|
1752
|
+
.filter((name: string) => name !== '') ?? []
|
|
1753
|
+
: [],
|
|
1562
1754
|
})
|
|
1563
1755
|
const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists)
|
|
1564
1756
|
const escalated = verdict.status === 'blocked'
|
|
@@ -1611,12 +1803,60 @@ function settleFromOutput(
|
|
|
1611
1803
|
lessonNote = `复盘记忆写入失败:${truncate(error instanceof Error ? error.message : String(error), 120)}`
|
|
1612
1804
|
}
|
|
1613
1805
|
}
|
|
1806
|
+
/*
|
|
1807
|
+
* [SCv2-T4][Q1-B/S-Q1-3/Q3-B/Q6-A] 判据层结算闸(spec §3.5 第 4 步):
|
|
1808
|
+
* 仅对判据 v2 已生效的计划(D-1 三重门后新创建)判定;未生效计划行为逐字不变。
|
|
1809
|
+
* 运行层先安全结算(不丢成果,L4/产物探测照旧),再判判据层:done 且
|
|
1810
|
+
* 事前预估之和 ≤10 且事后单次墙钟 ≤10 ⇒ met;有用户批准留痕 ⇒ exception-approved;
|
|
1811
|
+
* 否则 unmet ⇒ 不得 done,改判 blocked(criterion-overrun)、记违规(append-only)、
|
|
1812
|
+
* 文案指向 replan(replace) 接替行只补缺口。判定顺序=运行层→判据层(S-Q7-5)。
|
|
1813
|
+
*/
|
|
1814
|
+
let effectiveStatus = verdict.status
|
|
1815
|
+
let effectiveError = settleError
|
|
1816
|
+
let criterionResultValue: string | null = null
|
|
1817
|
+
let criterionDirectWrite: any = null
|
|
1818
|
+
if (verdict.status === 'done' && criterionV2Active(record.plan?.createdAt)) {
|
|
1819
|
+
const criterionRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1820
|
+
const settledAt = Date.now()
|
|
1821
|
+
let leaderForCriterion: any = null
|
|
1822
|
+
try { leaderForCriterion = deriveLeaderEstimate(criterionRow) } catch { leaderForCriterion = null }
|
|
1823
|
+
const exAnte = criterionExAnte(criterionRow, leaderForCriterion)
|
|
1824
|
+
const wallClockMs = attemptWallClockMsOf({ startedAt: criterionRow?.startedAt, finishedAt: settledAt })
|
|
1825
|
+
const evaluation = evaluateCriterion({
|
|
1826
|
+
exAnteMinutes: exAnte.minutes,
|
|
1827
|
+
exAnteComplete: exAnte.complete,
|
|
1828
|
+
wallClockMs,
|
|
1829
|
+
exception: sanitizeCriterionException(criterionRow?.criterionException),
|
|
1830
|
+
settledAt,
|
|
1831
|
+
})
|
|
1832
|
+
criterionResultValue = evaluation.criterionResult
|
|
1833
|
+
criterionDirectWrite = { criterionResult: evaluation.criterionResult }
|
|
1834
|
+
if (evaluation.criterionResult === 'unmet') {
|
|
1835
|
+
effectiveStatus = 'blocked'
|
|
1836
|
+
criterionDirectWrite = {
|
|
1837
|
+
criterionResult: 'unmet',
|
|
1838
|
+
closure: 'blocked',
|
|
1839
|
+
blockedKind: 'criterion-overrun',
|
|
1840
|
+
criterionViolations: appendCriterionViolation(criterionRow?.criterionViolations, {
|
|
1841
|
+
at: settledAt,
|
|
1842
|
+
attempt: Number(criterionRow?.timeoutCount ?? 0) + 1,
|
|
1843
|
+
wallClockMs,
|
|
1844
|
+
exAnteMinutes: exAnte.minutes,
|
|
1845
|
+
reasons: evaluation.reasons,
|
|
1846
|
+
}),
|
|
1847
|
+
}
|
|
1848
|
+
effectiveError = `${typeof settleError === 'string' && settleError !== '' ? `${settleError};` : ''}`
|
|
1849
|
+
+ `判据违规(criterion-overrun):${evaluation.reasons.join(';')}。`
|
|
1850
|
+
+ '未获用户批准不得以 done 收尾(Q1-B);已完成产物只读保留,请用 dsh_workplan_replan(replace) 生成接替子任务只补缺口,'
|
|
1851
|
+
+ '或先向用户申请例外批准并留痕(criterionApproval)后复核改判。'
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1614
1854
|
writeSubtaskStatus(record, subtask.id, {
|
|
1615
|
-
status:
|
|
1855
|
+
status: effectiveStatus,
|
|
1616
1856
|
progress: 100,
|
|
1617
1857
|
finishedAt: Date.now(),
|
|
1618
1858
|
summary: truncate(lessonNote ? `${output}\n[自我学习] ${lessonNote}` : output, 3000),
|
|
1619
|
-
error:
|
|
1859
|
+
error: effectiveError,
|
|
1620
1860
|
verification: verdict.verification,
|
|
1621
1861
|
acceptance: verdict.acceptance,
|
|
1622
1862
|
artifacts: checked.artifacts.length > 0
|
|
@@ -1626,6 +1866,13 @@ function settleFromOutput(
|
|
|
1626
1866
|
? checked.missingArtifacts
|
|
1627
1867
|
: (extraEvidence && extraEvidence.missingArtifacts.length > 0 ? extraEvidence.missingArtifacts : undefined),
|
|
1628
1868
|
needs: verdict.needs.length > 0 ? verdict.needs : undefined,
|
|
1869
|
+
/*
|
|
1870
|
+
* [3.0.0][用户要求 7/8/10/11] 两级精简 JSON 落行:专家汇报 report 与
|
|
1871
|
+
* 部门汇总 departmentSummary。它们已通过 F10/F11 格式门禁,这里原样
|
|
1872
|
+
* 持久化,供完成通知与看板按需读取(不裁剪内容)。
|
|
1873
|
+
*/
|
|
1874
|
+
...(verdict.departmentSummary ? { departmentSummary: verdict.departmentSummary } : {}),
|
|
1875
|
+
...(verdict.report ? { report: verdict.report } : {}),
|
|
1629
1876
|
/*
|
|
1630
1877
|
* [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
|
|
1631
1878
|
* `question` 就是同一条请示。它仍然写成 blocked 投影,但 closure 是
|
|
@@ -1640,7 +1887,7 @@ function settleFromOutput(
|
|
|
1640
1887
|
escalatedAt: Date.now(),
|
|
1641
1888
|
escalationSeq: Number(current?.revision ?? 0) + 1,
|
|
1642
1889
|
}
|
|
1643
|
-
:
|
|
1890
|
+
: effectiveStatus === 'done'
|
|
1644
1891
|
/*
|
|
1645
1892
|
* [1.11.0] 完成必须落到 `closure:'done'`,不是 `blocked`。
|
|
1646
1893
|
*
|
|
@@ -1660,8 +1907,17 @@ function settleFromOutput(
|
|
|
1660
1907
|
blockedKind: verdict.blockedKind === 'comm-format' ? 'comm-format' : 'failed',
|
|
1661
1908
|
}),
|
|
1662
1909
|
}, guard)
|
|
1663
|
-
|
|
1664
|
-
|
|
1910
|
+
/*
|
|
1911
|
+
* [SCv2-T4][C08] 判据字段走 StatusEntry 未知字段直写通道(applyStatus 白名单
|
|
1912
|
+
* 不路由新字段,与 pendingAdjudication/timeoutCount 同一纪律);回放白名单
|
|
1913
|
+
* 已追加 criterionResult/criterionException/criterionViolations,刷新不丢。
|
|
1914
|
+
*/
|
|
1915
|
+
if (criterionDirectWrite) {
|
|
1916
|
+
const criterionRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1917
|
+
if (criterionRow) Object.assign(criterionRow, criterionDirectWrite)
|
|
1918
|
+
}
|
|
1919
|
+
if (effectiveStatus === 'blocked') {
|
|
1920
|
+
recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (effectiveError ?? '未完成'), guard)
|
|
1665
1921
|
} else if (checked.missingArtifacts.length > 0) {
|
|
1666
1922
|
recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard)
|
|
1667
1923
|
}
|
|
@@ -1673,7 +1929,7 @@ function settleFromOutput(
|
|
|
1673
1929
|
* 措辞,A4)。投递与幂等标记由 `onSubtaskDone` 处理器负责:先写通知、
|
|
1674
1930
|
* 写成功才记 report.state='sent',绝不留无证据的已回报。
|
|
1675
1931
|
*/
|
|
1676
|
-
if (
|
|
1932
|
+
if (effectiveStatus === 'done' && options.notifyCompletion === true
|
|
1677
1933
|
&& typeof options.onSubtaskDone === 'function') {
|
|
1678
1934
|
try {
|
|
1679
1935
|
options.onSubtaskDone(record, subtask, verdict)
|
|
@@ -1684,7 +1940,7 @@ function settleFromOutput(
|
|
|
1684
1940
|
*/
|
|
1685
1941
|
}
|
|
1686
1942
|
}
|
|
1687
|
-
return { ...verdict, escalated }
|
|
1943
|
+
return { ...verdict, status: effectiveStatus, escalated, ...(criterionResultValue ? { criterionResult: criterionResultValue } : {}) }
|
|
1688
1944
|
}
|
|
1689
1945
|
|
|
1690
1946
|
/**
|
|
@@ -1712,7 +1968,8 @@ export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, i
|
|
|
1712
1968
|
* 重试要有意义,必须给它留够「至少再跑一次短任务」的时间。
|
|
1713
1969
|
*
|
|
1714
1970
|
* [1.10.6] 这里**不能**再拿空闲窗口当门槛(旧式 `max(idle, 120s)`):
|
|
1715
|
-
*
|
|
1971
|
+
* 现行默认是 ceiling=CHILD_TIMEOUT_MS(900s) / idle=CHILD_IDLE_TIMEOUT_MS
|
|
1972
|
+
* (300s) / round=TOTAL_TIMEOUT_MS(0=不设整轮硬预算),撞上限后剩下约
|
|
1716
1973
|
* 300s,而 `remaining > 300s` 恒为假——用户要的「有预算就自动重试一次」
|
|
1717
1974
|
* 会在默认配置下永远不触发,正是 T6 记录的那类「策略说会、链路不会」。
|
|
1718
1975
|
* 固定 120s 是「够跑一次短任务」的下限,同时保证不会刚重试就被砍掉。
|
|
@@ -1788,6 +2045,24 @@ export function announceSubtaskInterrupt(
|
|
|
1788
2045
|
return true
|
|
1789
2046
|
}
|
|
1790
2047
|
|
|
2048
|
+
/*
|
|
2049
|
+
* [2.5.5][T6] 活体 agent 解析兜底:工具路径(exec.agent)与自动派发路径
|
|
2050
|
+
* (payload.agent)都可能因宿主契约差异拿不到 agent,旧实现把 undefined 直传
|
|
2051
|
+
* 宿主 startActivation,在 spec.parent.id 处毫秒级抛 TypeError(session-1513
|
|
2052
|
+
* 与当前会话实测,childId=null)。这里用宿主同款安全访问器按 session.id 解析;
|
|
2053
|
+
* 解析不到由调用方 fail-closed,绝不裸抛 TypeError。
|
|
2054
|
+
*/
|
|
2055
|
+
function resolveLiveAgent(ctx: any, sessionId: any): any {
|
|
2056
|
+
const id = typeof sessionId === 'string' && sessionId.trim() !== '' ? sessionId.trim() : ''
|
|
2057
|
+
if (!id) return null
|
|
2058
|
+
try {
|
|
2059
|
+
const agentsService = typeof ctx?.get === 'function' ? ctx.get('agents') : ctx?.agents
|
|
2060
|
+
return agentsService?.get?.(id) ?? null
|
|
2061
|
+
} catch {
|
|
2062
|
+
return null
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
|
|
1791
2066
|
async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
|
|
1792
2067
|
const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
|
|
1793
2068
|
/*
|
|
@@ -1938,6 +2213,9 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1938
2213
|
* task's dependents); `interruptedEvidence` is what gets written into the
|
|
1939
2214
|
* blocked status so the main Agent can re-adjudicate on facts.
|
|
1940
2215
|
*/
|
|
2216
|
+
// [2.5.0][自配档] phase-0→phase-1 接续状态(本次尝试链内)。
|
|
2217
|
+
let phaseZeroCompleted = false
|
|
2218
|
+
let phaseZeroOutput = ''
|
|
1941
2219
|
let interruptedFlag = false
|
|
1942
2220
|
let interruptedEvidence: { artifacts: any[]; missingArtifacts: string[] } | null = null
|
|
1943
2221
|
try {
|
|
@@ -1999,10 +2277,48 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1999
2277
|
* 在请求前抛 UNSUPPORTED_REASONING_EFFORT——派发期即中断。查询不可用
|
|
2000
2278
|
* 时保持旧行为;查询成功后钳制到等效档,空清单则不发送该字段。
|
|
2001
2279
|
*/
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2280
|
+
/*
|
|
2281
|
+
* [2.5.0] 用户要求 2「全程应用」的执行点:每次激活(首发/重试/续跑)
|
|
2282
|
+
* 都经 resolveTaskEffort 单一判据读档——负责人通过 delegate review
|
|
2283
|
+
* 配置的整体等级(状态行 effortOverride,durable 回放不丢)优先于
|
|
2284
|
+
* 规划器写死的 subtask.reasoningEffort;两者缺失才回落默认档。
|
|
2285
|
+
*/
|
|
2286
|
+
const effortRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
2287
|
+
/*
|
|
2288
|
+
* [2.5.0][自配档] 先配置后开工(平台强制):未登记自配整体档 ⇒ phase-0
|
|
2289
|
+
* 以 low 启动(唯一职责=评估复杂度+经 review 提交自配);已登记(含
|
|
2290
|
+
* 重试/续跑/回放读回)⇒ phase-1 经 resolveTaskEffort 单一判据全程用自配档。
|
|
2291
|
+
*/
|
|
2292
|
+
const selfEffortConfigured = typeof effortRow?.effortOverride === 'string' && effortRow.effortOverride.length > 0
|
|
2293
|
+
const phaseZeroActivation = !phaseZeroCompleted && !selfEffortConfigured
|
|
2294
|
+
const requestedChildEffort = phaseZeroActivation ? 'low' : resolveTaskEffort({
|
|
2295
|
+
override: effortRow?.effortOverride,
|
|
2296
|
+
planned: subtask.reasoningEffort,
|
|
2297
|
+
})
|
|
2298
|
+
/*
|
|
2299
|
+
* [2.3.9][T3/llm-rules] 用户强制要求 1/2 的执行点:派发前对每个子任务的
|
|
2300
|
+
* reasoningEffort 做模型家族等级集合校验。越界档不中断派发(A3 修正轨),
|
|
2301
|
+
* 按强度序自动降级并 console.warn 留痕;随后 [2.2.7] 宿主能力钳制作为
|
|
2302
|
+
* 第二道闸继续生效(静态表权威 + 能力面交集)。模型名缺失⇒不施加静态
|
|
2303
|
+
* 约束,保持旧行为。
|
|
2304
|
+
*/
|
|
2305
|
+
const childStaticAllowed = allowedEffortsForModel(modelSelection?.model)
|
|
2306
|
+
const childStaticCorrection = childStaticAllowed && !childStaticAllowed.includes(requestedChildEffort)
|
|
2307
|
+
? correctEffortForModel(requestedChildEffort, modelSelection?.model)
|
|
2308
|
+
: null
|
|
2309
|
+
const staticRuleChildEffort = childStaticCorrection ? childStaticCorrection.effort : requestedChildEffort
|
|
2310
|
+
if (childStaticCorrection) {
|
|
2311
|
+
console.warn('[dsh-workplan] child reasoning effort corrected by LLM family rules:', JSON.stringify({
|
|
2312
|
+
subtaskId: subtask.id,
|
|
2313
|
+
provider: modelSelection?.provider,
|
|
2314
|
+
model: modelSelection?.model,
|
|
2315
|
+
family: classifyModelFamily(modelSelection?.model),
|
|
2316
|
+
requested: requestedChildEffort,
|
|
2317
|
+
corrected: childStaticCorrection.effort,
|
|
2318
|
+
allowed: childStaticAllowed,
|
|
2319
|
+
reason: childStaticCorrection.reason,
|
|
2320
|
+
}))
|
|
2321
|
+
}
|
|
2006
2322
|
/*
|
|
2007
2323
|
* [2.2.7] 能力不可查询时保持同步路径:派发链上任何多余的 await 微任务都会
|
|
2008
2324
|
* 把 awaiting 通道写入推晚一个 tick(notice-channel 运行时集成用例即因此
|
|
@@ -2016,15 +2332,32 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
2016
2332
|
? await resolveSupportedEfforts(ctx.llm, modelSelection.provider, modelSelection.model, parentSignal)
|
|
2017
2333
|
: null
|
|
2018
2334
|
const childEffort = childEffortSupport === null
|
|
2019
|
-
?
|
|
2020
|
-
: (clampEffortToSupported(
|
|
2335
|
+
? staticRuleChildEffort
|
|
2336
|
+
: (clampEffortToSupported(staticRuleChildEffort, childEffortSupport) ?? '')
|
|
2337
|
+
/*
|
|
2338
|
+
* [2.5.5][治本] 宿主 SubagentActivationSpec 契约:prompt/parent/cwd/
|
|
2339
|
+
* agentOptions/maxDepth 必须在 spec **顶层**(dsh-subagent types.d.ts
|
|
2340
|
+
* SubagentStartRequest)。旧实现把它们嵌套在 request:{} 里(旧宿主形状),
|
|
2341
|
+
* 现宿主读 spec.parent 得 undefined → 派发期即抛
|
|
2342
|
+
* 「Cannot read properties of undefined (reading 'id')」,全部子任务
|
|
2343
|
+
* 级联受阻(本会话重启后 0/6 现场)。单点拍平,两处 spawn 同口径。
|
|
2344
|
+
*/
|
|
2345
|
+
// [2.5.5][T6] agent 兜底 + fail-closed(见 resolveLiveAgent 注释)。
|
|
2346
|
+
const liveAgent = options.agent ?? resolveLiveAgent(ctx, options.session?.id ?? record?.plan?.sessionId)
|
|
2347
|
+
if (!liveAgent) {
|
|
2348
|
+
throw new PlanError('派发失败:无法解析活体父 Agent(agent 缺失且 agents 服务兜底失败),fail-closed 不创建子会话', 'AGENT_RESOLUTION_FAILED', { subtaskId: subtask.id })
|
|
2349
|
+
}
|
|
2021
2350
|
activation = await ctx.subagents.startActivation({
|
|
2022
2351
|
provider: 'spawn',
|
|
2023
2352
|
label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
|
|
2024
|
-
|
|
2025
|
-
prompt: [{
|
|
2353
|
+
prompt: [{
|
|
2026
2354
|
type: 'text',
|
|
2027
|
-
text:
|
|
2355
|
+
text: phaseZeroActivation ? buildPhaseZeroLeaderPrompt({
|
|
2356
|
+
subtaskId: subtask.id,
|
|
2357
|
+
title: subtask.title,
|
|
2358
|
+
objective: subtask.objective,
|
|
2359
|
+
departmentLabel: DEPARTMENTS[subtask.department as keyof typeof DEPARTMENTS]?.zh ?? String(subtask.department ?? '部门'),
|
|
2360
|
+
}) : buildChildPrompt({
|
|
2028
2361
|
plan: record.plan,
|
|
2029
2362
|
subtask,
|
|
2030
2363
|
stage,
|
|
@@ -2063,9 +2396,26 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
2063
2396
|
*/
|
|
2064
2397
|
previousFailure: lastFailure ?? null,
|
|
2065
2398
|
lessonsBrief,
|
|
2399
|
+
/*
|
|
2400
|
+
* [2.3.9][T4b] 用户强制要求 3:分配任务时必须把要求 1/2 的
|
|
2401
|
+
* **全部内容**告知相关部门。注入文本由 llm-rules.ts 的
|
|
2402
|
+
* buildLlmRulesBrief 单一事实源生成(tier='department'):
|
|
2403
|
+
* 要求 1/2 原文 + 本会话模型与家族判定 + 本子任务已配置/钳制后
|
|
2404
|
+
* 的推理等级 + 部门负责人「先全面梳理、再用 dsh_workplan_delegate
|
|
2405
|
+
* 分配给顶尖专家与组员」的强制流程告知。
|
|
2406
|
+
*/
|
|
2407
|
+
phaseZeroContinuation: phaseZeroCompleted ? buildPhaseZeroContinuationHint(String(effortRow?.effortOverride ?? ''), phaseZeroOutput, effortRow?.effortOverride === 'low' && (effortRow?.consolidation?.assignments ?? []).length === 0) : '',
|
|
2408
|
+
llmRulesBrief: buildLlmRulesBrief({
|
|
2409
|
+
model: modelSelection?.model ?? null,
|
|
2410
|
+
effort: staticRuleChildEffort || null,
|
|
2411
|
+
requested: childStaticCorrection ? requestedChildEffort : null,
|
|
2412
|
+
correctionReason: childStaticCorrection?.reason ?? null,
|
|
2413
|
+
tier: 'department',
|
|
2414
|
+
taskEffort: typeof effortRow?.effortOverride === 'string' ? effortRow.effortOverride : null,
|
|
2415
|
+
}),
|
|
2066
2416
|
}),
|
|
2067
2417
|
}],
|
|
2068
|
-
parent:
|
|
2418
|
+
parent: liveAgent,
|
|
2069
2419
|
cwd: typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined,
|
|
2070
2420
|
/*
|
|
2071
2421
|
* [2.2.0][T13/推理等级] 子 Agent 不得继承主 Agent 的推理等级。
|
|
@@ -2086,8 +2436,16 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
2086
2436
|
// [2.2.7] '' = 模型无 reasoning 元数据 ⇒ 不发送,避免派发期即中断。
|
|
2087
2437
|
...(childEffort ? { reasoningEffort: childEffort } : {}),
|
|
2088
2438
|
},
|
|
2089
|
-
|
|
2090
|
-
|
|
2439
|
+
/*
|
|
2440
|
+
* [2.3.9][T4b] 三层派发深度(用户强制要求 4/5):主 Agent(0) →
|
|
2441
|
+
* 部门负责人子会话(1) → 顶尖专家/组员子会话(2)。maxDepth 是宿主
|
|
2442
|
+
* resolveChildDepth 的**绝对深度上限**(child-agent.d.ts:24-29),
|
|
2443
|
+
* 部门层放行到 2 才能让负责人经 dsh_workplan_delegate 派生第三层;
|
|
2444
|
+
* 第三层成员派生时同样传 2 ⇒ 任何第四层(深度 3)被宿主抛
|
|
2445
|
+
* SubagentDepthError 硬拒,delegateTool 服务端另有一道「只有部门
|
|
2446
|
+
* 负责人行可调用」的校验——提示词说服模型,代码守住边界。
|
|
2447
|
+
*/
|
|
2448
|
+
maxDepth: 2,
|
|
2091
2449
|
signal: child.controller.signal,
|
|
2092
2450
|
delivery: 'caller',
|
|
2093
2451
|
})
|
|
@@ -2298,6 +2656,26 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
2298
2656
|
watchdog.stop()
|
|
2299
2657
|
}
|
|
2300
2658
|
if (guard.timedOut) return
|
|
2659
|
+
/*
|
|
2660
|
+
* [2.5.0][自配档] phase-0 结算分支:已登记自配 ⇒ 平台立即以自配档接续
|
|
2661
|
+
* phase-1(不计失败、不耗重试预算);未登记 ⇒ 明确 SELF_EFFORT_MISSING
|
|
2662
|
+
* 回喂(有界重试),禁止静默以 low 档继续正式任务。
|
|
2663
|
+
*/
|
|
2664
|
+
if (phaseZeroActivation) {
|
|
2665
|
+
const configuredRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
2666
|
+
const configured = typeof configuredRow?.effortOverride === 'string' && configuredRow.effortOverride.length > 0
|
|
2667
|
+
if (configured) {
|
|
2668
|
+
phaseZeroCompleted = true
|
|
2669
|
+
phaseZeroOutput = resultText(result)
|
|
2670
|
+
attempt -= 1 // phase-0→phase-1 是接续不是重试:不消耗 attempt 预算
|
|
2671
|
+
continue
|
|
2672
|
+
}
|
|
2673
|
+
throw new PlanError(
|
|
2674
|
+
'phase-0 结束但未提交自配推理等级:先配置后开工是平台硬规则——请评估任务复杂度并经 dsh_workplan_delegate(action="review") 配置 consolidation.taskReasoningEffort,平台将以自配档接续;low(轻度)任务请改经 action="direct" 登记两轮思考产物(负责人亲自执行,禁止下派)',
|
|
2675
|
+
'SELF_EFFORT_MISSING',
|
|
2676
|
+
{ subtaskId: subtask.id },
|
|
2677
|
+
)
|
|
2678
|
+
}
|
|
2301
2679
|
const output = resultText(result)
|
|
2302
2680
|
if (result.stopReason !== 'completed') {
|
|
2303
2681
|
/*
|
|
@@ -2388,17 +2766,65 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
2388
2766
|
const settleBackup = join(options.cwd ?? process.cwd(), 'reports', `wp-settlement-${subtask.id}.json`)
|
|
2389
2767
|
let backupVerdict: any = null
|
|
2390
2768
|
let backupText = ''
|
|
2769
|
+
/*
|
|
2770
|
+
* [2.5.2][T4b][D2] 备份采纳前的新鲜度+归属闸。根因
|
|
2771
|
+
* (reports/D1-D2-root-cause-diagnosis.md §2):固定文件名跨计划跨会话
|
|
2772
|
+
* 复用,旧实现读到合法 JSON 即采纳、不做任何校验——本次误采纳 T1 的
|
|
2773
|
+
* 陈旧截图任务结算(假完成)与 T2 的陈旧基金基线结算(误 blocked),
|
|
2774
|
+
* 级联冻结 T3/T4/T5。现在:
|
|
2775
|
+
* ① 新鲜度:备份 mtime 必须 >= 本次尝试 startedAt(只认本次尝试内
|
|
2776
|
+
* 新写的备份;提示词同步要求覆盖旧文件)。
|
|
2777
|
+
* ② 归属:备份 JSON 顶层含 planId/subtaskId 则必须与本计划/本子任务
|
|
2778
|
+
* 一致(裸 JSON 或标记块内 JSON 两个入口都查;无这些字段的旧格式
|
|
2779
|
+
* 备份仍受新鲜度闸约束,adjudicateResult 对额外顶层字段容忍)。
|
|
2780
|
+
* ③ 任一不满足 ⇒ 不采纳,写 record.errors 审计行(含文件 mtime 与
|
|
2781
|
+
* startedAt),落回下方既有 EVIDENCE_MISSING 有界回喂路径。
|
|
2782
|
+
* 结算严格性不变:缺失永不计 done。
|
|
2783
|
+
*/
|
|
2784
|
+
let backupRejectReason = ''
|
|
2785
|
+
let backupMtimeMs: number | null = null
|
|
2786
|
+
const backupAttemptStartedAt = Number(attemptRow()?.startedAt ?? 0)
|
|
2391
2787
|
try {
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2788
|
+
const backupStat = statSync(settleBackup)
|
|
2789
|
+
backupMtimeMs = backupStat.mtimeMs
|
|
2790
|
+
if (backupStat.mtimeMs < backupAttemptStartedAt) {
|
|
2791
|
+
backupRejectReason = '陈旧备份(mtime 早于本次尝试 startedAt,非本次执行新写)'
|
|
2792
|
+
} else {
|
|
2793
|
+
backupText = readFileSync(settleBackup, 'utf8')
|
|
2794
|
+
let backupMeta: any = null
|
|
2795
|
+
try {
|
|
2796
|
+
backupMeta = JSON.parse(backupText)
|
|
2797
|
+
} catch {
|
|
2798
|
+
const beginAt = backupText.lastIndexOf(EVIDENCE_MARKER_BEGIN)
|
|
2799
|
+
const endAt = backupText.indexOf(EVIDENCE_MARKER_END, beginAt + EVIDENCE_MARKER_BEGIN.length)
|
|
2800
|
+
if (beginAt >= 0 && endAt > beginAt) {
|
|
2801
|
+
try { backupMeta = JSON.parse(backupText.slice(beginAt + EVIDENCE_MARKER_BEGIN.length, endAt).trim()) } catch { backupMeta = null }
|
|
2802
|
+
}
|
|
2803
|
+
}
|
|
2804
|
+
const metaPlanId = typeof backupMeta?.planId === 'string' && backupMeta.planId ? backupMeta.planId : null
|
|
2805
|
+
const metaSubtaskId = typeof backupMeta?.subtaskId === 'string' && backupMeta.subtaskId ? backupMeta.subtaskId : null
|
|
2806
|
+
if (metaPlanId && metaPlanId !== record.plan.planId) {
|
|
2807
|
+
backupRejectReason = `归属不匹配(备份 planId=${metaPlanId} ≠ 本计划 ${record.plan.planId})`
|
|
2808
|
+
} else if (metaSubtaskId && metaSubtaskId !== subtask.id) {
|
|
2809
|
+
backupRejectReason = `归属不匹配(备份 subtaskId=${metaSubtaskId} ≠ 本子任务 ${subtask.id})`
|
|
2810
|
+
} else {
|
|
2811
|
+
backupVerdict = adjudicateResult({
|
|
2812
|
+
output: backupText,
|
|
2813
|
+
strict: true,
|
|
2814
|
+
expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
|
|
2815
|
+
})
|
|
2816
|
+
if (!backupVerdict || /结果块缺失|无法解析/.test(String(backupVerdict.error ?? ''))) backupVerdict = null
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2399
2819
|
} catch {
|
|
2400
2820
|
backupVerdict = null
|
|
2401
2821
|
}
|
|
2822
|
+
if (backupRejectReason) {
|
|
2823
|
+
record.errors = [
|
|
2824
|
+
...(record.errors ?? []),
|
|
2825
|
+
`${subtask.id}: 拒绝采纳盘上结算备份 ${settleBackup}——${backupRejectReason}(文件 mtime=${backupMtimeMs === null ? '未知' : new Date(backupMtimeMs).toISOString()},本次尝试 startedAt=${new Date(backupAttemptStartedAt).toISOString()};[2.5.2][T4b][D2] 新鲜度/归属闸),落回 EVIDENCE_MISSING 回喂`,
|
|
2826
|
+
].slice(-20)
|
|
2827
|
+
}
|
|
2402
2828
|
if (backupVerdict) {
|
|
2403
2829
|
settleFromOutput(record, subtask, backupText, guard, options, backupVerdict,
|
|
2404
2830
|
probeInterruptedEvidence(backupText, subtask, options.cwd, options.artifactExists))
|
|
@@ -2731,6 +3157,71 @@ export function mergePreservedArtifacts(artifacts: any, preservedRefs: any) {
|
|
|
2731
3157
|
return list.slice(-40)
|
|
2732
3158
|
}
|
|
2733
3159
|
|
|
3160
|
+
/**
|
|
3161
|
+
* [2.5.0][R4] 第三层叶子「已完成产物在盘」探测:delegate 下级重派(重试/续跑)
|
|
3162
|
+
* 前先核盘它上次按任务书约定写下的结算备份(buildDelegateePrompt:
|
|
3163
|
+
* reports/wp-member-<成员名>-<任务代号>.json),随重试任务书附给新叶子。
|
|
3164
|
+
* 只读目录、不改任何判定;目录不存在/读取失败返回空清单(绝不编造产物)。
|
|
3165
|
+
* listDir 可注入,纯逻辑可脱离真实文件系统回归。
|
|
3166
|
+
*/
|
|
3167
|
+
export function probeDelegateLandedArtifacts(cwd: any, member: any, listDir: any = readdirSync) {
|
|
3168
|
+
const name = String(member ?? '').trim()
|
|
3169
|
+
if (!name || typeof cwd !== 'string' || !cwd) return []
|
|
3170
|
+
const prefix = `wp-member-${name}-`
|
|
3171
|
+
let entries: any[] = []
|
|
3172
|
+
try {
|
|
3173
|
+
entries = listDir(join(cwd, 'reports'))
|
|
3174
|
+
} catch {
|
|
3175
|
+
return []
|
|
3176
|
+
}
|
|
3177
|
+
return (Array.isArray(entries) ? entries : [])
|
|
3178
|
+
.map((entry: any) => String(entry ?? ''))
|
|
3179
|
+
.filter((file: string) => file.startsWith(prefix) && file.endsWith('.json'))
|
|
3180
|
+
.slice(0, 6)
|
|
3181
|
+
.map((file: string) => `reports/${file}`)
|
|
3182
|
+
}
|
|
3183
|
+
|
|
3184
|
+
/**
|
|
3185
|
+
* [2.5.0][R4] 第三层叶子重试/续跑简报(根因修复):旧实现 delegate 重派时给
|
|
3186
|
+
* 叶子一张全新任务书——上一次尝试的状态、失败原因、已回报结论与在盘产物
|
|
3187
|
+
* 全部丢失,叶子只能整步重跑(违反用户要求 4「禁止丢弃已完成部分」,与
|
|
3188
|
+
* 第二层 buildTakeoverBrief/结果块回喂同一语义在第三层的落点)。现在重派
|
|
3189
|
+
* 时把本简报经 buildDelegateePrompt.extraContext 附进任务书:上次尝试状态/
|
|
3190
|
+
* 错误/摘要 + 已核实在盘产物清单 + 负责人梳理思路 + 「请勿重做已完成的工作」
|
|
3191
|
+
* 硬约束。纯函数,可脱离宿主回归。prior 为空(首发)返回 ''。
|
|
3192
|
+
*/
|
|
3193
|
+
export function buildDelegateRetryBrief(prior: any, landedRefs: any, approach?: any) {
|
|
3194
|
+
if (!prior || typeof prior !== 'object') return ''
|
|
3195
|
+
const refs = (Array.isArray(landedRefs) ? landedRefs : [])
|
|
3196
|
+
.map((item: any) => String(item ?? '').trim())
|
|
3197
|
+
.filter(Boolean)
|
|
3198
|
+
.slice(0, 6)
|
|
3199
|
+
const status = String(prior.status ?? '')
|
|
3200
|
+
const lines = [
|
|
3201
|
+
`【重试/续跑简报——禁止丢弃已完成部分】这不是你的首次尝试:上一次尝试的状态为 ${status || '未知'}。`,
|
|
3202
|
+
]
|
|
3203
|
+
if (typeof prior.error === 'string' && prior.error.trim()) {
|
|
3204
|
+
lines.push(`- 上次失败原因:${truncate(prior.error.trim(), 300)}`)
|
|
3205
|
+
}
|
|
3206
|
+
if (typeof prior.summary === 'string' && prior.summary.trim()) {
|
|
3207
|
+
lines.push(`- 上次已回报的结论(含已完成工作):${truncate(prior.summary.trim(), 300)}`)
|
|
3208
|
+
}
|
|
3209
|
+
if (refs.length > 0) {
|
|
3210
|
+
lines.push(`- 已核实在盘的已完成产物:${refs.join('、')}`)
|
|
3211
|
+
}
|
|
3212
|
+
const approachLines = (Array.isArray(approach) ? approach : [])
|
|
3213
|
+
.map((item: any) => String(item ?? '').trim())
|
|
3214
|
+
.filter(Boolean)
|
|
3215
|
+
.slice(0, 6)
|
|
3216
|
+
if (approachLines.length > 0) {
|
|
3217
|
+
lines.push(`- 部门负责人的梳理思路(供参考):${approachLines.join(';')}`)
|
|
3218
|
+
}
|
|
3219
|
+
lines.push(status === 'done'
|
|
3220
|
+
? '- 硬约束:上次尝试已完成——先核对上述产物与结论,只补缺口;请勿重做已完成的工作,禁止删除或覆盖既有产物。'
|
|
3221
|
+
: '- 硬约束:请勿重做已完成的工作——以上述在盘产物与结论为基础,只继续补齐未完成部分;禁止删除或覆盖既有产物、禁止整步重跑。')
|
|
3222
|
+
return lines.join('\n')
|
|
3223
|
+
}
|
|
3224
|
+
|
|
2734
3225
|
/**
|
|
2735
3226
|
* [2.3.0][T1] 放宽成功后告知执行中的专家最新时限(A2 的「告知」半边)。
|
|
2736
3227
|
* 走 ctx.subagents.sendMessage 与 follow-up 同一投递通道:运行中的子会话在下一
|
|
@@ -2754,7 +3245,7 @@ async function notifyExpertOfExtension(ctx: any, agent: any, record: any, subtas
|
|
|
2754
3245
|
+ '你必须在保证工作质量的前提下高效率执行:优先推进高价值步骤,已完成内容及时落盘,'
|
|
2755
3246
|
+ '并在回报中明确区分「已完成 / 未完成」。收到本通知后请继续当前工作,不要重新开始。'
|
|
2756
3247
|
try {
|
|
2757
|
-
await service.sendMessage(agent, childId, [{ type: 'text', text }], {})
|
|
3248
|
+
await service.sendMessage(agent, childId, [{ type: 'text', text }], { signal: new AbortController().signal }) // [T11] 缺陷②:延期告知携带有效 signal,消除 throwIfAborted
|
|
2758
3249
|
if (row) {
|
|
2759
3250
|
const journal = Array.isArray(row.timeJournal) ? row.timeJournal : []
|
|
2760
3251
|
journal.push({ at: Date.now(), action: 'notify-expert', deadlineAt: Number(deadlineAt), by: 'system' })
|
|
@@ -2850,8 +3341,8 @@ async function runSubtaskAttempt(
|
|
|
2850
3341
|
const preRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
2851
3342
|
const timeoutCountAtFire = Number(preRow?.timeoutCount ?? 0) + 1
|
|
2852
3343
|
const message = timeoutCountAtFire >= TAKEOVER_AFTER_TIMEOUTS
|
|
2853
|
-
? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent
|
|
2854
|
-
: `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms
|
|
3344
|
+
? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent 直接接手完成尚未完成的部分;专家已完成并落盘的部分已登记只读保护,禁止丢弃、禁止整步重跑;接手仅发生在已批准延期的场景)`
|
|
3345
|
+
: `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按运行层安全兜底结算(待裁决:判据层 10 分钟完成目标未达成且无用户批准 → 判未完成,优先 replan(replace) 转新子任务只补缺口;或经用户批准并留痕后 extendMs 放宽;或重试 / 接受、转新轮续跑、人工裁决)`
|
|
2855
3346
|
try {
|
|
2856
3347
|
// [1.8.19] Keep the evidence of what already landed on disk.
|
|
2857
3348
|
const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
|
|
@@ -2882,6 +3373,44 @@ async function runSubtaskAttempt(
|
|
|
2882
3373
|
*/
|
|
2883
3374
|
const settleRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
2884
3375
|
if (settleRow) settleRow.pendingAdjudication = true
|
|
3376
|
+
/*
|
|
3377
|
+
* [SCv2-T4][Q1-B/Q3-B/Q6-A] 到点结算的判据层判定(仅生效计划):
|
|
3378
|
+
* 运行层兜底已完成(blocked+产物抢救照旧),这里追加判据结果与违规
|
|
3379
|
+
* 审计;unmet 时把「判未完成→replan(replace) 接替」写进 error/summary,
|
|
3380
|
+
* 与 C15 文案同向。pendingAdjudication 事实标记保留(C16 不改)。
|
|
3381
|
+
*/
|
|
3382
|
+
if (settleRow && criterionV2Active(record.plan?.createdAt)) {
|
|
3383
|
+
try {
|
|
3384
|
+
let leaderForCriterion: any = null
|
|
3385
|
+
try { leaderForCriterion = deriveLeaderEstimate(settleRow) } catch { leaderForCriterion = null }
|
|
3386
|
+
const exAnte = criterionExAnte(settleRow, leaderForCriterion)
|
|
3387
|
+
const wallClockMs = attemptWallClockMsOf(settleRow)
|
|
3388
|
+
const evaluation = evaluateCriterion({
|
|
3389
|
+
exAnteMinutes: exAnte.minutes,
|
|
3390
|
+
exAnteComplete: exAnte.complete,
|
|
3391
|
+
wallClockMs,
|
|
3392
|
+
exception: sanitizeCriterionException(settleRow.criterionException),
|
|
3393
|
+
settledAt: Date.now(),
|
|
3394
|
+
})
|
|
3395
|
+
settleRow.criterionResult = evaluation.criterionResult
|
|
3396
|
+
if (evaluation.criterionResult === 'unmet') {
|
|
3397
|
+
settleRow.criterionViolations = appendCriterionViolation(settleRow.criterionViolations, {
|
|
3398
|
+
at: Date.now(),
|
|
3399
|
+
attempt: timeoutCountAtFire,
|
|
3400
|
+
wallClockMs,
|
|
3401
|
+
exAnteMinutes: exAnte.minutes,
|
|
3402
|
+
reasons: evaluation.reasons,
|
|
3403
|
+
})
|
|
3404
|
+
const criterionNote = `判据违规(criterion-overrun):${evaluation.reasons.join(';')}。`
|
|
3405
|
+
+ '未获用户批准不得以 done 收尾(Q1-B);已完成产物只读保留,优先 replan(replace) 转接替子任务只补缺口,'
|
|
3406
|
+
+ '或先向用户申请例外批准并留痕(criterionApproval)后放宽。'
|
|
3407
|
+
settleRow.error = truncate(`${settleRow.error ?? ''};${criterionNote}`, 3000)
|
|
3408
|
+
settleRow.summary = truncate(`未完成:${criterionNote}`, 3000)
|
|
3409
|
+
}
|
|
3410
|
+
} catch (error: any) {
|
|
3411
|
+
record.errors = [...(record.errors ?? []), `${subtask.id}: 判据层判定写入失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20)
|
|
3412
|
+
}
|
|
3413
|
+
}
|
|
2885
3414
|
/*
|
|
2886
3415
|
* [2.3.0][T1] 超时计数与二次超时接手(用户要求 1/2 的机读落点):
|
|
2887
3416
|
* 每次到点收束给状态行 timeoutCount +1 并记入 timeJournal(action:'timeout')。
|
|
@@ -2909,8 +3438,12 @@ async function runSubtaskAttempt(
|
|
|
2909
3438
|
? `子任务 ${subtask.id} 已第 ${timeoutCount} 次达到协商时限(二次超时):按 2.3.0 机制本行已置「主 Agent 接手」(takeoverRequired)。`
|
|
2910
3439
|
+ `专家已完成并登记保护的部分(只读、禁止丢弃):${(ceilingLanded as string[]).slice(0, 8).join('、') || '(见 takeoverBrief)'};`
|
|
2911
3440
|
+ '请主 Agent 直接接手继续未完成部分,不要整步重跑、不要删除或覆盖已登记产物。'
|
|
2912
|
-
:
|
|
2913
|
-
|
|
3441
|
+
: (criterionV2Active(record.plan?.createdAt)
|
|
3442
|
+
? `子任务 ${subtask.id} 第 1 次达到协商时限:按用户 2026-11-13 裁决 Q1-B,第一次超时不再自动放宽——请先向用户申请例外批准并留痕`
|
|
3443
|
+
+ '(任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=未批准),批准后才可用 dsh_workplan_update(extendMs, criterionApproval) 放宽;'
|
|
3444
|
+
+ '未获批准不得放宽,按判据层未达标处理(不 done、replan(replace) 转接替子任务只补缺口,已完成产物只读保护)。'
|
|
3445
|
+
: `子任务 ${subtask.id} 第 1 次达到协商时限:按 2.3.0 机制请主 Agent 尽快用 dsh_workplan_update(extendMs) 放宽,`
|
|
3446
|
+
+ '延期成功后插件会自动把最新时限与「保证质量、高效率执行」要求告知专家;如判断无需再放宽,请接手继续未完成部分(已完成产物将只读保护)。')
|
|
2914
3447
|
announceSubtaskInterrupt(record, options.session ?? options.agent?.session, subtask.id, takeoverText)
|
|
2915
3448
|
} catch {
|
|
2916
3449
|
// 通知失败不影响结算(与预警同一纪律)。
|
|
@@ -3092,7 +3625,22 @@ async function runWithConcurrency(items: any, limit: any, worker: any) {
|
|
|
3092
3625
|
*/
|
|
3093
3626
|
export function modelStatusLines(statuses: any) {
|
|
3094
3627
|
const list = Array.isArray(statuses) ? statuses : []
|
|
3095
|
-
return list.map((item: any) =>
|
|
3628
|
+
return list.map((item: any) => {
|
|
3629
|
+
/*
|
|
3630
|
+
* [T7][lead-decisions J2/G2] 负责人时长聚合:与看板载荷(plan.ts
|
|
3631
|
+
* normaliseStatusEntry)挂同一读时派生纯函数,模型可读面不是第二套计算。
|
|
3632
|
+
* null=空 roster(无下属分工)/replanned 旧行/越界 fail-closed;
|
|
3633
|
+
* roster 非空且非 replanned 却为 null ⇒ 总和越界异常,显式标注拒绝展示(J8)。
|
|
3634
|
+
*/
|
|
3635
|
+
const leaderEstimate = deriveLeaderEstimate(item)
|
|
3636
|
+
const leaderEstimateAnomaly = leaderEstimate === null
|
|
3637
|
+
&& item?.closure !== 'replanned'
|
|
3638
|
+
&& leaderEstimateRoster(item).length > 0
|
|
3639
|
+
? '下属开工预估聚合异常(总和超出安全整数范围),拒绝展示数值;请核对 delegateEstimates 台账'
|
|
3640
|
+
: null
|
|
3641
|
+
// [SCv2-T4][Q4-B/C22] 事前预估口径(有叶子=和;直做=负责人自身预估,D-2)。
|
|
3642
|
+
const exAnteView = criterionExAnte(item, leaderEstimate)
|
|
3643
|
+
return {
|
|
3096
3644
|
subtaskId: item.subtaskId,
|
|
3097
3645
|
title: item.title,
|
|
3098
3646
|
department: item.department,
|
|
@@ -3177,7 +3725,30 @@ export function modelStatusLines(statuses: any) {
|
|
|
3177
3725
|
* 只写状态行不让读,等于又是一个「看不见的失败」。
|
|
3178
3726
|
*/
|
|
3179
3727
|
noticeChannel: item.noticeChannel ?? null,
|
|
3180
|
-
|
|
3728
|
+
/*
|
|
3729
|
+
* [T6][契约v1 §3] 第三层开工预估进入模型可读面:delegates 行透出 estimate
|
|
3730
|
+
* (declaredMinutes/delivery 等,照录不改写),任务级 delegateEstimates 台账
|
|
3731
|
+
* 一并透传——主 Agent/负责人据此核对「谁预估了多少分钟、是否已送达」。
|
|
3732
|
+
*/
|
|
3733
|
+
delegates: (Array.isArray(item.delegates) ? item.delegates : [])
|
|
3734
|
+
.filter((entry: any) => entry && typeof entry === 'object')
|
|
3735
|
+
.map((entry: any) => ({ ...entry })),
|
|
3736
|
+
delegateEstimates: item.delegateEstimates ?? null,
|
|
3737
|
+
// [T7][J1 冻结结构] {totalMinutes, reported, expected, missing[], failed[]} | null。
|
|
3738
|
+
leaderEstimate,
|
|
3739
|
+
...(leaderEstimateAnomaly ? { leaderEstimateAnomaly } : {}),
|
|
3740
|
+
/*
|
|
3741
|
+
* [SCv2-T4] 判据层字段进入模型可读面(与看板载荷 normaliseStatusEntry 同源):
|
|
3742
|
+
* 单次尝试墙钟(缺失=null 未验证,绝不按 0)、结算三选一、用户批准留痕、
|
|
3743
|
+
* 违规审计(append-only)、事前预估超判据布尔(服务端算术,客户端不计算)。
|
|
3744
|
+
*/
|
|
3745
|
+
attemptWallClockMs: attemptWallClockMsOf(item),
|
|
3746
|
+
criterionResult: item.criterionResult ?? null,
|
|
3747
|
+
criterionException: item.criterionException ?? null,
|
|
3748
|
+
criterionViolations: Array.isArray(item.criterionViolations) ? item.criterionViolations.slice(-10) : [],
|
|
3749
|
+
leaderEstimateOverCriterion: exAnteView.minutes !== null && exAnteView.minutes > CRITERION_TARGET_MINUTES,
|
|
3750
|
+
}
|
|
3751
|
+
})
|
|
3181
3752
|
}
|
|
3182
3753
|
|
|
3183
3754
|
export function buildRoundResult(record: any, sessionId: any, limits: any) {
|
|
@@ -3346,6 +3917,52 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
3346
3917
|
record.dispatchedAt = Date.now()
|
|
3347
3918
|
record.phase = 'executing'
|
|
3348
3919
|
record.updatedAt = record.dispatchedAt
|
|
3920
|
+
/*
|
|
3921
|
+
* [3.0.0][用户要求 4] 分配完成后,会话内必须输出固定文案
|
|
3922
|
+
* 「任务已经完成分配,正在执行中......」。放在本轮真正开跑(phase=executing、
|
|
3923
|
+
* 子 Agent 即将启动)之后、任何子任务结算之前,自动派发与手工派发同一路径,
|
|
3924
|
+
* 因此只输出一次、不会漏也不会重复。逐字冻结,不得改写。
|
|
3925
|
+
*/
|
|
3926
|
+
{
|
|
3927
|
+
const assignSession = options.session ?? agent?.session
|
|
3928
|
+
/*
|
|
3929
|
+
* [3.0.0][幂等键] 同一份计划只发一次:续跑/重派/durable 回放都会再次走到
|
|
3930
|
+
* 这里,若不加键就会重复刷屏。键=planId,随 record 持久化(record 本身
|
|
3931
|
+
* 走 durable 快照),刷新后仍然生效。
|
|
3932
|
+
*/
|
|
3933
|
+
const noticeKey = String(record.plan?.planId ?? record.planId ?? '')
|
|
3934
|
+
if (assignSession && noticeKey && record.assignedNoticeKey !== noticeKey) {
|
|
3935
|
+
record.assignedNoticeKey = noticeKey
|
|
3936
|
+
appendUserMessage(assignSession, STATUS_ASSIGNED_TEXT)
|
|
3937
|
+
}
|
|
3938
|
+
}
|
|
3939
|
+
/*
|
|
3940
|
+
* [2.5.2][stall-fix] 执行期进度心跳(用户报告「提交任务后长时间无反应/以为
|
|
3941
|
+
* 死机」):规划心跳只覆盖 runPlanner,派发后的执行轮次(可能十几分钟)
|
|
3942
|
+
* 旧实现期间零会话输出。现在只要本轮还在跑,就按固定间隔(默认 45s,
|
|
3943
|
+
* DSH_WORKPLAN_DISPATCH_HEARTBEAT_MS 可调,≥5000ms)经唯一合规写入器发
|
|
3944
|
+
* 「已用时+完成进度+不是卡死」的可见通知。与规划心跳同一收束纪律:
|
|
3945
|
+
* finally 里 stop(成功/超时/中止都收束),maxNotices 保险丝防失控,
|
|
3946
|
+
* 不新增事件类型、不触碰 system/message。
|
|
3947
|
+
*/
|
|
3948
|
+
const dispatchHbSession = options.session ?? agent?.session
|
|
3949
|
+
// [T7] C3 整轮预算:新一轮开跑即重置注入预算(roundKey=planId:dispatchedAt,与 finishRound 同键;
|
|
3950
|
+
// 会话取 dispatchHbSession,与本轮 appendUserMessage 同一对象,WeakMap 键一致)。
|
|
3951
|
+
if (dispatchHbSession) resetRoundInjectionBudget(dispatchHbSession, `${record.plan.planId}:${record.dispatchedAt}`)
|
|
3952
|
+
const dispatchHeartbeat = dispatchHbSession ? createPlanningHeartbeat({
|
|
3953
|
+
signal: childController.signal,
|
|
3954
|
+
appendNotice: (text: string) => appendUserMessage(dispatchHbSession, text),
|
|
3955
|
+
// 默认值引用 PLANNING_HEARTBEAT_MS 单一真源(同为 45s 心跳间隔);
|
|
3956
|
+
// 环境变量名 DSH_WORKPLAN_DISPATCH_HEARTBEAT_MS 保持不变。
|
|
3957
|
+
intervalMs: planningHeartbeatIntervalMs(process.env.DSH_WORKPLAN_DISPATCH_HEARTBEAT_MS ?? PLANNING_HEARTBEAT_MS),
|
|
3958
|
+
startedAt: record.dispatchedAt,
|
|
3959
|
+
maxAttempts: 1,
|
|
3960
|
+
buildMessage: (elapsedMs: number) => {
|
|
3961
|
+
const snap = derivePlanSnapshot(record.statuses)
|
|
3962
|
+
return buildDispatchHeartbeat(elapsedMs, snap.stats?.done, snap.stats?.total, snap.stats?.inProgress)
|
|
3963
|
+
},
|
|
3964
|
+
}) : { start: () => {}, stop: () => {} }
|
|
3965
|
+
dispatchHeartbeat.start()
|
|
3349
3966
|
try {
|
|
3350
3967
|
let guard = 0
|
|
3351
3968
|
/*
|
|
@@ -3385,7 +4002,47 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
3385
4002
|
&& !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
|
|
3386
4003
|
}
|
|
3387
4004
|
: {})
|
|
3388
|
-
|
|
4005
|
+
/*
|
|
4006
|
+
* [3.0.0+] 派发质量闸(2026-11-15 用户裁决):主 Agent 派给部门负责人的
|
|
4007
|
+
* 每个子任务必须携带 qualityRequirements(质量要求)。缺失的子任务本轮
|
|
4008
|
+
* 直接拒发(不启动部门 Agent),落 blocked + closure:'escalated'——等主
|
|
4009
|
+
* Agent replan 补齐后重派:该形态不参与自动续跑(canResumePlan 排除
|
|
4010
|
+
* escalated)、不会被 readySubtasks 重复选中,天然防重试空转;其余合格
|
|
4011
|
+
* 子任务照常并发执行,互不影响。旧计划(createdAt 早于
|
|
4012
|
+
* QUALITY_GATE_ACTIVATED_AT)豁免,零回归。
|
|
4013
|
+
*/
|
|
4014
|
+
let runnable = ready
|
|
4015
|
+
if (isQualityGatePlan(record.plan)) {
|
|
4016
|
+
const rejected: string[] = []
|
|
4017
|
+
runnable = []
|
|
4018
|
+
for (const item of ready) {
|
|
4019
|
+
const check = checkSubtaskQualityRequirements(item)
|
|
4020
|
+
if (check.ok) { runnable.push(item); continue }
|
|
4021
|
+
rejected.push(`${item.id}(${String(item.title ?? '无标题')}):${check.error}`)
|
|
4022
|
+
record.statuses = applyStatus(record.statuses, item.id, {
|
|
4023
|
+
status: 'blocked',
|
|
4024
|
+
closure: 'escalated',
|
|
4025
|
+
blockedKind: 'escalated',
|
|
4026
|
+
question: `${check.error} ${check.hint}`,
|
|
4027
|
+
error: check.error,
|
|
4028
|
+
escalatedAt: Date.now(),
|
|
4029
|
+
})
|
|
4030
|
+
record.errors = [...(record.errors ?? []), `${item.id}: ${check.code} ${check.error}`].slice(-20)
|
|
4031
|
+
}
|
|
4032
|
+
if (rejected.length > 0) {
|
|
4033
|
+
const noticeSession = options.session ?? agent?.session
|
|
4034
|
+
if (noticeSession) {
|
|
4035
|
+
appendUserMessage(noticeSession, [
|
|
4036
|
+
`【派发拒发 · 质量要求缺失】${rejected.length} 个子任务未携带质量要求(qualityRequirements),`
|
|
4037
|
+
+ '已被系统直接拒发(DISPATCH_QUALITY_REQUIREMENTS_MISSING),未启动任何部门 Agent:',
|
|
4038
|
+
...rejected.map((line, index) => ` ${index + 1}. ${line}`),
|
|
4039
|
+
'请立刻用 dsh_workplan_replan 为这些子任务补写质量要求(至少 1 条可检查:什么算合格、什么算不合格),'
|
|
4040
|
+
+ '然后重新派发;本次其余合格子任务正常执行、不受影响。',
|
|
4041
|
+
].join('\n'))
|
|
4042
|
+
}
|
|
4043
|
+
}
|
|
4044
|
+
}
|
|
4045
|
+
if (runnable.length === 0) {
|
|
3389
4046
|
/*
|
|
3390
4047
|
* [1.8.6] "Nothing is ready" is not the same thing as "everything
|
|
3391
4048
|
* failed".
|
|
@@ -3406,7 +4063,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
3406
4063
|
}
|
|
3407
4064
|
break
|
|
3408
4065
|
}
|
|
3409
|
-
await runWithConcurrency(
|
|
4066
|
+
await runWithConcurrency(runnable, MAX_CONCURRENT, async (item: any) => {
|
|
3410
4067
|
// readySubtasks() returns subtask objects (they carry `id`, not
|
|
3411
4068
|
// `subtaskId`); using the status key here silently skipped every task
|
|
3412
4069
|
// and spun the dispatcher until DISPATCH_LOOP marked all blocked.
|
|
@@ -3607,6 +4264,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
3607
4264
|
record.phase = parentSignal.aborted ? 'cancelled' : 'blocked'
|
|
3608
4265
|
}
|
|
3609
4266
|
} finally {
|
|
4267
|
+
dispatchHeartbeat.stop()
|
|
3610
4268
|
clearTimeout(totalTimer)
|
|
3611
4269
|
parentSignal.removeEventListener('abort', onAbort)
|
|
3612
4270
|
if (!childController.signal.aborted) childController.abort()
|
|
@@ -3980,6 +4638,11 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
3980
4638
|
/* [1.11.0] 重规划修订号与未处理的变更请求,随 durable 消息回放。 */
|
|
3981
4639
|
planRevision: number
|
|
3982
4640
|
changeRequest: any
|
|
4641
|
+
/* [2.5.1] 主 Agent 两轮深度思考产物(计划级),随 durable workplan-update 回放。 */
|
|
4642
|
+
mainDeepThink: any
|
|
4643
|
+
mainDeepThinkPlanId: string | null
|
|
4644
|
+
/* [2.5.7] 续跑上限随回放快照透传(durable 消息未携带时为 undefined,回落 MAX_PLAN_RESUMES)。 */
|
|
4645
|
+
resumeLimit?: number
|
|
3983
4646
|
}
|
|
3984
4647
|
/*
|
|
3985
4648
|
* [1.8.9] 回放按 planId 分账,不按会话「最后一个计划」分账。
|
|
@@ -4008,6 +4671,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4008
4671
|
errors: [],
|
|
4009
4672
|
planRevision: Number(plan?.planRevision ?? 0) || 0,
|
|
4010
4673
|
changeRequest: null,
|
|
4674
|
+
mainDeepThink: null,
|
|
4675
|
+
mainDeepThinkPlanId: null,
|
|
4011
4676
|
}
|
|
4012
4677
|
snapshots.set(plan.planId, snap)
|
|
4013
4678
|
}
|
|
@@ -4101,7 +4766,7 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4101
4766
|
for (const entry of (Array.isArray(result.statuses) ? result.statuses : [])) {
|
|
4102
4767
|
const rebuiltRow = snap.statuses.find((item: any) => item?.subtaskId === entry?.subtaskId)
|
|
4103
4768
|
if (!rebuiltRow || !isRecord(entry)) continue
|
|
4104
|
-
for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
|
|
4769
|
+
for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief', 'criterionResult', 'criterionException', 'criterionViolations']) {
|
|
4105
4770
|
if (entry[field] !== undefined) rebuiltRow[field] = entry[field]
|
|
4106
4771
|
}
|
|
4107
4772
|
/*
|
|
@@ -4152,7 +4817,22 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4152
4817
|
* a strictly-lower revision never overwrites; equal revision passes
|
|
4153
4818
|
* (dedup for the same write lives in `appliedUpdates`).
|
|
4154
4819
|
*/
|
|
4155
|
-
|
|
4820
|
+
/* [2.5.5][T10] 合并汇总消息按序展开成多条 update,逐条应用(与逐条落盘等价)。 */
|
|
4821
|
+
for (const update of parseUpdateMessages(event.data)) {
|
|
4822
|
+
/*
|
|
4823
|
+
* [2.5.1] 主 Agent 两轮深度思考产物回放(计划级字段):写入侧
|
|
4824
|
+
* (dispatchTool 门禁登记)把 mainDeepThink/mainDeepThinkPlanId 随
|
|
4825
|
+
* durable workplan-update 落盘(subtaskId=null,不挂任何子任务行);
|
|
4826
|
+
* 消费侧同一判据消毒(sanitizeMainDeepThink)后抬进计划快照——刷新/
|
|
4827
|
+
* 重启后续跑读档放行,不必重新提交;旧日志无该字段零迁移不报错。
|
|
4828
|
+
*/
|
|
4829
|
+
if (update && typeof update.planId === 'string' && update.mainDeepThink !== undefined) {
|
|
4830
|
+
const deepThinkSnap = snapshots.get(update.planId)
|
|
4831
|
+
if (deepThinkSnap) {
|
|
4832
|
+
deepThinkSnap.mainDeepThink = sanitizeMainDeepThink(update.mainDeepThink)
|
|
4833
|
+
deepThinkSnap.mainDeepThinkPlanId = typeof update.mainDeepThinkPlanId === 'string' ? update.mainDeepThinkPlanId : null
|
|
4834
|
+
}
|
|
4835
|
+
}
|
|
4156
4836
|
if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
|
|
4157
4837
|
const snap = snapshots.get(update.planId)
|
|
4158
4838
|
if (snap) {
|
|
@@ -4247,6 +4927,26 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4247
4927
|
// [2.2.0][T4/O-3b][E] 回放白名单(T3b TODO#2):O-3b/O-2c 留档字段随
|
|
4248
4928
|
// update 记录回放;timeoutMs 有 applyStatus 分支,走 patch 即可。
|
|
4249
4929
|
timeoutMs: update.timeoutMs,
|
|
4930
|
+
/*
|
|
4931
|
+
* [2.5.0][G1] 整体任务等级与第三层梳理/台账必须随 durable
|
|
4932
|
+
* workplan-update 回放:写入侧(plan.ts buildUpdateMessage)已携带
|
|
4933
|
+
* effortOverride/consolidation/delegates,消费端 patch 此前漏传,
|
|
4934
|
+
* 刷新/重启后整体等级丢失(resolveTaskEffort 回落旧档)、梳理登记
|
|
4935
|
+
* 与第三层台账同丢。三字段在 applyStatus 均有路由分支,undefined
|
|
4936
|
+
* 保留旧值——旧日志零迁移,与 live 侧同一口径。
|
|
4937
|
+
*/
|
|
4938
|
+
effortOverride: update.effortOverride,
|
|
4939
|
+
consolidation: update.consolidation,
|
|
4940
|
+
delegates: update.delegates,
|
|
4941
|
+
delegateSelfEfforts: update.delegateSelfEfforts,
|
|
4942
|
+
// [2.5.2] 叶子执行前两轮思考台账回放(applyStatus 同口径消毒)。
|
|
4943
|
+
delegateDeepThinks: update.delegateDeepThinks,
|
|
4944
|
+
// [T6][契约v1 §3] 第三层开工预估台账回放(applyStatus 同口径消毒,
|
|
4945
|
+
// undefined 保留旧值):刷新/重启后预估不丢,重派读档门禁据此判定。
|
|
4946
|
+
delegateEstimates: update.delegateEstimates,
|
|
4947
|
+
// [2.5.4][T3R1] 分派前深度梳理门禁审计回放(A3:刷新/重启后
|
|
4948
|
+
// 拒绝/放行记录仍可复核;applyStatus 同口径消毒,undefined 保留旧值)。
|
|
4949
|
+
gateAudit: update.gateAudit,
|
|
4250
4950
|
updatedBy: 'agent',
|
|
4251
4951
|
})
|
|
4252
4952
|
/*
|
|
@@ -4285,7 +4985,7 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4285
4985
|
*/
|
|
4286
4986
|
const replayRow = snap.statuses.find((item: any) => item?.subtaskId === update.subtaskId)
|
|
4287
4987
|
if (replayRow) {
|
|
4288
|
-
for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
|
|
4988
|
+
for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief', 'criterionResult', 'criterionException', 'criterionViolations']) {
|
|
4289
4989
|
if (update[field] !== undefined) replayRow[field] = update[field]
|
|
4290
4990
|
}
|
|
4291
4991
|
const replayExtend = Number(update.extendMs)
|
|
@@ -4328,6 +5028,7 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4328
5028
|
}
|
|
4329
5029
|
}
|
|
4330
5030
|
}
|
|
5031
|
+
}
|
|
4331
5032
|
const cancel = parseCancelMessage(event.data)
|
|
4332
5033
|
if (cancel && typeof cancel.planId === 'string') {
|
|
4333
5034
|
const snap = snapshots.get(cancel.planId)
|
|
@@ -4478,6 +5179,9 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4478
5179
|
updatedAt: Date.now(),
|
|
4479
5180
|
createdTurn: plan.createdTurn,
|
|
4480
5181
|
resumeCount,
|
|
5182
|
+
/* [2.5.1] 主 Agent 两轮深度思考产物随回放回到记录(续跑读档放行)。 */
|
|
5183
|
+
mainDeepThink: chosen.mainDeepThink ?? null,
|
|
5184
|
+
mainDeepThinkPlanId: chosen.mainDeepThinkPlanId ?? null,
|
|
4481
5185
|
/*
|
|
4482
5186
|
* [1.8.17] A reconstructed record must carry every field the live dispatch
|
|
4483
5187
|
* path spreads/pushes unconditionally. `errors` was the one that was
|
|
@@ -4485,8 +5189,10 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
4485
5189
|
* abort that marked the rest of the plan blocked.
|
|
4486
5190
|
*/
|
|
4487
5191
|
errors: (chosen.errors ?? []).slice(-20),
|
|
4488
|
-
resumeLimit
|
|
4489
|
-
|
|
5192
|
+
// [2.5.7] 与 serialisePlan/status 输出同口径:优先读档内 resumeLimit,
|
|
5193
|
+
// 缺失才回落 MAX_PLAN_RESUMES(三源统一,消除第四套口径)。
|
|
5194
|
+
resumeLimit: Number(chosen?.resumeLimit ?? MAX_PLAN_RESUMES),
|
|
5195
|
+
resumeAvailable: canResumePlan({ phase, statuses, resumeCount }, Number(chosen?.resumeLimit ?? MAX_PLAN_RESUMES)).resume,
|
|
4490
5196
|
stale: stalePending,
|
|
4491
5197
|
/*
|
|
4492
5198
|
* [1.8.14] Two facts, one from the log: whether the plan is cancelled and
|
|
@@ -4773,8 +5479,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4773
5479
|
maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
|
|
4774
5480
|
? Math.min(5, Math.floor(Number(options.maxResumes)))
|
|
4775
5481
|
: MAX_PLAN_RESUMES,
|
|
5482
|
+
// [1.12.0] 默认开启:仅显式 `autoResume:false`(或
|
|
5483
|
+
// `DSH_WORKPLAN_AUTO_RESUME=0`)才关闭,与 `AUTO_RESUME_DEFAULTS.enabled=true` 一致。
|
|
4776
5484
|
autoResume: {
|
|
4777
|
-
enabled: options.autoResume
|
|
5485
|
+
enabled: options.autoResume !== false,
|
|
4778
5486
|
maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
|
|
4779
5487
|
},
|
|
4780
5488
|
}
|
|
@@ -4789,6 +5497,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4789
5497
|
* - 失败只记录错误,不把「派发失败」伪装成「计划生成失败」。
|
|
4790
5498
|
*/
|
|
4791
5499
|
function startAutoDispatch(record: any, session: any, agent: any) {
|
|
5500
|
+
// [2.5.5][T6] payload.agent 缺失时按 session.id 兜底解析活体 agent,
|
|
5501
|
+
// 避免宿主 spec.parent.id 毫秒级崩溃(自动派发与工具路径同病实测)。
|
|
5502
|
+
agent = agent ?? resolveLiveAgent(ctx, session?.id)
|
|
4792
5503
|
const controller = new AbortController()
|
|
4793
5504
|
record.abortDispatch = (reason: string) => {
|
|
4794
5505
|
if (!controller.signal.aborted) {
|
|
@@ -5008,6 +5719,26 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5008
5719
|
})
|
|
5009
5720
|
row.timeJournal = journal.slice(-20)
|
|
5010
5721
|
record.updatedAt = at
|
|
5722
|
+
/*
|
|
5723
|
+
* [SCv2-T4][Q4-B/C22] 部门行事前预估落档后的超判据告警(仅生效计划):
|
|
5724
|
+
* 叶子预估之和(或无叶子直做时负责人自身预估)>10 ⇒ 即时告知主 Agent
|
|
5725
|
+
* 拆分或向用户申请例外批准;预估未齐只显示部分和、不得视为达标(D-3)。
|
|
5726
|
+
* 告警是观测设施:写失败只留档 errors,绝不影响记录与执行。
|
|
5727
|
+
*/
|
|
5728
|
+
try {
|
|
5729
|
+
if (criterionV2Active(record?.plan?.createdAt) && session) {
|
|
5730
|
+
let leaderForNotice: any = null
|
|
5731
|
+
try { leaderForNotice = deriveLeaderEstimate(row) } catch { leaderForNotice = null }
|
|
5732
|
+
const exAnte = criterionExAnte(row, leaderForNotice)
|
|
5733
|
+
if (exAnte.minutes !== null && exAnte.minutes > CRITERION_TARGET_MINUTES) {
|
|
5734
|
+
appendUserMessage(session, `【dsh-workplan·判据告警】子任务 ${subtaskId} 的事前预估为 ${exAnte.minutes} 分钟,`
|
|
5735
|
+
+ `超过判据层完成目标 ${CRITERION_TARGET_MINUTES} 分钟(Q4-B)。请事前拆分工作,或向用户申请例外批准并留痕(criterionApproval);`
|
|
5736
|
+
+ '预估未报齐时只显示部分和,不得视为「简单判据达标」。')
|
|
5737
|
+
}
|
|
5738
|
+
}
|
|
5739
|
+
} catch (error: any) {
|
|
5740
|
+
record.errors = [...(record.errors ?? []), `${subtaskId} 判据告警写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20)
|
|
5741
|
+
}
|
|
5011
5742
|
/*
|
|
5012
5743
|
* [2.3.0][T1] 预估上报 → 告知用户(用户要求 1 的前半段闭环):专家的开工
|
|
5013
5744
|
* 预告落档后,插件立即向主会话推送一条即时通知,明确「请把此预期执行
|
|
@@ -5020,7 +5751,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5020
5751
|
+ `预估执行时间 ${Number(notice?.declaredMinutes)} 分钟`
|
|
5021
5752
|
+ (reason ? `(${reason})` : '')
|
|
5022
5753
|
+ `;请把此预期执行时间告知用户。若执行中超时,请主 Agent 放宽(extendMs)`
|
|
5023
|
-
+ '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。'
|
|
5754
|
+
+ '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。',
|
|
5755
|
+
undefined, { allowBanned: true })
|
|
5024
5756
|
} catch (error: any) {
|
|
5025
5757
|
record.errors = [...(record.errors ?? []), `${subtaskId} 预估上报通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20)
|
|
5026
5758
|
}
|
|
@@ -5065,6 +5797,40 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5065
5797
|
hint: '请传入 1 以上的整数毫秒;放宽永远有界(累计 ≤ 初始协商上限 × 1),超出请转新轮续跑或转 escalate 请主 Agent 裁决。',
|
|
5066
5798
|
}
|
|
5067
5799
|
}
|
|
5800
|
+
/*
|
|
5801
|
+
* [SCv2-T4][Q1-B/C05/C06] extendMs 用户批准闸(判据 v2 生效计划专用):
|
|
5802
|
+
* 第一次超时不再自动放宽——未携带合格用户批准留痕(criterionApproval)一律
|
|
5803
|
+
* 拒绝(EXTEND_NEEDS_USER_APPROVAL),批准时间晚于当前时刻 likewise 拒绝
|
|
5804
|
+
* (C-4 推荐 A:批准仅在本次尝试结算前有效,事后追认无效)。
|
|
5805
|
+
* 未生效计划(历史/在途,Q5-A/D-1)保持 2.3.0 旧行为,既有回归零改动。
|
|
5806
|
+
* 留痕 5 项:任务 ID(subtaskId)、批准原文/来源(reason/source)、批准时间
|
|
5807
|
+
* (at)、放宽后分钟数(extendedMinutes,事务内回填)、适用范围(scope)。
|
|
5808
|
+
*/
|
|
5809
|
+
const criterionActive = criterionV2Active(record.plan?.createdAt)
|
|
5810
|
+
let criterionApproval: ReturnType<typeof sanitizeCriterionException> = null
|
|
5811
|
+
if (hasExtend && criterionActive) {
|
|
5812
|
+
criterionApproval = sanitizeCriterionException(args?.criterionApproval)
|
|
5813
|
+
if (!criterionApproval) {
|
|
5814
|
+
return {
|
|
5815
|
+
ok: false,
|
|
5816
|
+
code: 'EXTEND_NEEDS_USER_APPROVAL',
|
|
5817
|
+
planId: record.plan.planId,
|
|
5818
|
+
subtaskId,
|
|
5819
|
+
error: '判据 v2 已对该计划生效:extendMs 放宽必须先取得用户明确批准并留痕(Q1-B),本次调用未携带合格的 criterionApproval。',
|
|
5820
|
+
hint: '请先向用户申请例外批准,再随 extendMs 传 criterionApproval={ approvedBy:"user", at:<批准时间 epoch 毫秒>, reason:<批准原文/来源>, scope:"task"|"plan" }(5 项留痕:任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=未批准)。未获批准时不得放宽:按判据层未达标处理,用 dsh_workplan_replan(replace) 转接替子任务只补缺口。',
|
|
5821
|
+
}
|
|
5822
|
+
}
|
|
5823
|
+
if (criterionApproval.at > Date.now()) {
|
|
5824
|
+
return {
|
|
5825
|
+
ok: false,
|
|
5826
|
+
code: 'EXTEND_APPROVAL_INVALID_TIME',
|
|
5827
|
+
planId: record.plan.planId,
|
|
5828
|
+
subtaskId,
|
|
5829
|
+
error: `criterionApproval.at(${criterionApproval.at})晚于当前时刻:批准必须在本次尝试结算前取得,事后追认无效(C-4 推荐 A)。`,
|
|
5830
|
+
hint: '请使用用户实际批准的时间(epoch 毫秒,Asia/Shanghai 展示);结算后只能批准接替行,不能追改本次判定。',
|
|
5831
|
+
}
|
|
5832
|
+
}
|
|
5833
|
+
}
|
|
5068
5834
|
/*
|
|
5069
5835
|
* [2.2.0][T5/O-4c] timeNotice 的校验放在入口统一做(所有路径共享):
|
|
5070
5836
|
* 非法预告不该因为调用同时带了 status/instruction 就被静默接受。
|
|
@@ -5266,6 +6032,31 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5266
6032
|
}
|
|
5267
6033
|
}
|
|
5268
6034
|
extension = extended
|
|
6035
|
+
/*
|
|
6036
|
+
* [SCv2-T4][Q1-B/C08] 批准留痕落行(criterionException,最终定名):
|
|
6037
|
+
* 放宽后分钟数由本次 extendMs 回填;timeJournal 追加 action:'criterion-exception'
|
|
6038
|
+
* 审计条目。回放白名单已追加 criterionException,刷新/重启不丢批准记录。
|
|
6039
|
+
*/
|
|
6040
|
+
if (criterionActive && criterionApproval) {
|
|
6041
|
+
const extendRow = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
6042
|
+
if (extendRow) {
|
|
6043
|
+
extendRow.criterionException = {
|
|
6044
|
+
...criterionApproval,
|
|
6045
|
+
extendedMs: extendMsArg,
|
|
6046
|
+
extendedMinutes: Math.round((extendMsArg / 60000) * 100) / 100,
|
|
6047
|
+
}
|
|
6048
|
+
const approvalJournal = Array.isArray(extendRow.timeJournal) ? extendRow.timeJournal : []
|
|
6049
|
+
approvalJournal.push({
|
|
6050
|
+
at: Date.now(),
|
|
6051
|
+
action: 'criterion-exception',
|
|
6052
|
+
by: 'user',
|
|
6053
|
+
extendMs: extendMsArg,
|
|
6054
|
+
scope: criterionApproval.scope,
|
|
6055
|
+
reason: truncate(criterionApproval.reason, 300),
|
|
6056
|
+
})
|
|
6057
|
+
extendRow.timeJournal = approvalJournal.slice(-20)
|
|
6058
|
+
}
|
|
6059
|
+
}
|
|
5269
6060
|
/*
|
|
5270
6061
|
* [2.3.0][T1] 用户要求 1 后半段:放宽成功后必须把「最新执行时间」告知
|
|
5271
6062
|
* 专家,同时附「必须在保证工作质量的前提下高效率执行」硬要求,让专家
|
|
@@ -5306,6 +6097,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5306
6097
|
}
|
|
5307
6098
|
: {}),
|
|
5308
6099
|
...(hasTimeNotice ? { timeNotice: written?.timeNotice ?? null } : {}),
|
|
6100
|
+
// [SCv2-T4] 批准留痕随纯时限事务回执下发(仅生效计划且本次携带批准时)。
|
|
6101
|
+
...(criterionActive && criterionApproval ? { criterionException: written?.criterionException ?? null } : {}),
|
|
5309
6102
|
timeJournal: Array.isArray(written?.timeJournal) ? written.timeJournal.slice(-10) : [],
|
|
5310
6103
|
stats: snapshot.stats,
|
|
5311
6104
|
deliveryReady: readiness.ready,
|
|
@@ -5325,6 +6118,44 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5325
6118
|
* sanitised by `applyStatus`, persisted in the durable update message and
|
|
5326
6119
|
* replayed. Omitted fields keep their previous values.
|
|
5327
6120
|
*/
|
|
6121
|
+
/*
|
|
6122
|
+
* [SCv2-T4][Q1-B/S-Q1-3] 人工改判 done 的判据闸(仅生效计划):
|
|
6123
|
+
* 未达标且无用户批准 ⇒ CRITERION_UNMET 拒绝(不得以 done 收尾);
|
|
6124
|
+
* 随调用携带 criterionApproval 或行上已有有效批准 ⇒ 记例外后放行。
|
|
6125
|
+
* 这是「复核改判」恢复路径的判据边界:恢复也必须经用户批准留痕。
|
|
6126
|
+
*/
|
|
6127
|
+
let manualCriterionFields: any = null
|
|
6128
|
+
if (status === 'done' && criterionActive) {
|
|
6129
|
+
const settledAt = Date.now()
|
|
6130
|
+
let leaderForCriterion: any = null
|
|
6131
|
+
try { leaderForCriterion = deriveLeaderEstimate(current) } catch { leaderForCriterion = null }
|
|
6132
|
+
const exAnte = criterionExAnte(current, leaderForCriterion)
|
|
6133
|
+
const approval = sanitizeCriterionException(args?.criterionApproval)
|
|
6134
|
+
?? sanitizeCriterionException(current?.criterionException)
|
|
6135
|
+
const evaluation = evaluateCriterion({
|
|
6136
|
+
exAnteMinutes: exAnte.minutes,
|
|
6137
|
+
exAnteComplete: exAnte.complete,
|
|
6138
|
+
wallClockMs: attemptWallClockMsOf({ startedAt: current?.startedAt, finishedAt: current?.finishedAt ?? settledAt }),
|
|
6139
|
+
exception: approval,
|
|
6140
|
+
settledAt,
|
|
6141
|
+
})
|
|
6142
|
+
if (!evaluation.canBeDone) {
|
|
6143
|
+
return {
|
|
6144
|
+
ok: false,
|
|
6145
|
+
code: 'CRITERION_UNMET',
|
|
6146
|
+
planId: record.plan.planId,
|
|
6147
|
+
subtaskId,
|
|
6148
|
+
criterionResult: evaluation.criterionResult,
|
|
6149
|
+
reasons: evaluation.reasons,
|
|
6150
|
+
error: `判据层未达标(criterion-overrun),不得以 done 收尾:${evaluation.reasons.join(';')}`,
|
|
6151
|
+
hint: '唯一例外=用户明确批准并留痕:向用户申请后随本次调用传 criterionApproval={ approvedBy:"user", at, reason, scope };或改用 dsh_workplan_replan(replace) 生成接替子任务只补缺口(已完成产物只读保护)。',
|
|
6152
|
+
}
|
|
6153
|
+
}
|
|
6154
|
+
manualCriterionFields = {
|
|
6155
|
+
criterionResult: evaluation.criterionResult,
|
|
6156
|
+
...(approval && evaluation.exceptionRecorded ? { criterionException: approval } : {}),
|
|
6157
|
+
}
|
|
6158
|
+
}
|
|
5328
6159
|
const evidencePatch: any = {}
|
|
5329
6160
|
if (args?.verification !== undefined) evidencePatch.verification = args.verification
|
|
5330
6161
|
if (args?.acceptance !== undefined) evidencePatch.acceptance = args.acceptance
|
|
@@ -5393,6 +6224,12 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5393
6224
|
options: writtenRow?.options,
|
|
5394
6225
|
instruction: writtenRow?.instruction,
|
|
5395
6226
|
instructionSeq: writtenRow?.instructionSeq,
|
|
6227
|
+
// [T7] C1 白名单:仅四态(开始/完成/受阻/待指示)注入一行关键进度;
|
|
6228
|
+
// instructed(指示已下发恢复执行)等过程改判文本置空。标题取自计划
|
|
6229
|
+
// 定义(渲染输入,不进 durable 载荷)。
|
|
6230
|
+
keyProgress: writtenRow?.closure === 'escalated'
|
|
6231
|
+
|| (['in_progress', 'done', 'blocked'].includes(String(status)) && writtenRow?.closure !== 'instructed'),
|
|
6232
|
+
title: flattenSubtasks(record.plan).find((entry: any) => entry.subtask?.id === subtaskId)?.subtask?.title,
|
|
5396
6233
|
}))
|
|
5397
6234
|
/*
|
|
5398
6235
|
* [2.2.9][T3][M4] 人工改判的这条 durable update 消息本身就是「完成已
|
|
@@ -6014,7 +6851,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6014
6851
|
}
|
|
6015
6852
|
|
|
6016
6853
|
/**
|
|
6017
|
-
* [2.2.0][T6/O-1a]
|
|
6854
|
+
* [2.2.0][T6/O-1a] 完成即时通知的插件兜底投递器。
|
|
6855
|
+
* [T9][用户要求6] 起 wait/async 两模式均启用:部门负责人完成即独立汇报主 Agent。
|
|
6018
6856
|
*
|
|
6019
6857
|
* 方案 §2.3 双通道:①协议通道由子 Agent 完成即 `send_message`;②兜底通道
|
|
6020
6858
|
* 由这里在 `settleFromOutput` 结算成功后立刻写一条纯文本 `user/message`
|
|
@@ -6034,76 +6872,355 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6034
6872
|
const acceptance = Array.isArray(verdict?.acceptance) ? verdict.acceptance : []
|
|
6035
6873
|
const passed = acceptance.filter((item: any) => item?.result === 'pass').length
|
|
6036
6874
|
const acceptanceCount = acceptance.length > 0
|
|
6037
|
-
?
|
|
6038
|
-
: '
|
|
6875
|
+
? `验收结论:${passed}/${acceptance.length} 通过`
|
|
6876
|
+
: '验收结论:0 条验收记录(legacy 未提供结构化验收)'
|
|
6039
6877
|
const elapsedMs = Number.isFinite(Number(row?.startedAt))
|
|
6040
6878
|
? Math.max(0, Date.now() - Number(row.startedAt))
|
|
6041
6879
|
: 0
|
|
6042
6880
|
const elapsed = elapsedMs < 1000 ? `${elapsedMs}ms` : `${(elapsedMs / 1000).toFixed(1)}s`
|
|
6043
6881
|
const summary = truncate(String(row?.summary ?? '').replace(/\s+/g, ' ').trim(), 160) || '(无摘要)'
|
|
6044
|
-
|
|
6882
|
+
/*
|
|
6883
|
+
* [T9][用户要求6/D7] 部门负责人完成 → 主 Agent 即时汇报的文本增强。
|
|
6884
|
+
* 行级「完美完成」判据与 deliveryReadiness 的行级口径同源(plan.ts):
|
|
6885
|
+
* verification==='structured' + acceptance 非空 + 每项 result==='pass'
|
|
6886
|
+
* + 无 missingArtifacts。达到才允许声称「完美完成」;未达到仍保留结算
|
|
6887
|
+
* 通知,但必须显式写明缺口,绝不声称完美(D7)。
|
|
6888
|
+
*/
|
|
6889
|
+
const rowAcceptance = Array.isArray(row?.acceptance) ? row.acceptance : acceptance
|
|
6890
|
+
const missingArtifacts = Array.isArray(row?.missingArtifacts) ? row.missingArtifacts : []
|
|
6891
|
+
const d7Reasons: string[] = []
|
|
6892
|
+
if (row?.verification !== 'structured') d7Reasons.push(`证据等级为 ${String(row?.verification ?? '缺失')}(需 structured)`)
|
|
6893
|
+
if (rowAcceptance.length === 0) d7Reasons.push('未提供验收项(acceptance 为空)')
|
|
6894
|
+
else if (rowAcceptance.some((item: any) => item?.result !== 'pass')) d7Reasons.push('验收未全部 pass')
|
|
6895
|
+
if (missingArtifacts.length > 0) {
|
|
6896
|
+
d7Reasons.push(`缺少声明产物:${missingArtifacts.slice(0, 5).map((ref: any) => truncate(String(ref ?? ''), 80)).join('、')}`)
|
|
6897
|
+
}
|
|
6898
|
+
const conclusion = d7Reasons.length === 0
|
|
6899
|
+
? `完美完成(验收 ${rowAcceptance.length}/${rowAcceptance.length} 全部 pass,structured)`
|
|
6900
|
+
: `未达完美完成判据:${d7Reasons.join(';')}`
|
|
6901
|
+
const acceptanceLines = rowAcceptance.map((item: any) =>
|
|
6902
|
+
` - ${truncate(String(item?.criterion ?? '未命名验收项').replace(/\s+/g, ' ').trim(), 80)} → ${String(item?.result ?? '缺失')}`)
|
|
6903
|
+
const needs = Array.isArray(row?.needs) ? row.needs : []
|
|
6904
|
+
const todoLines = [
|
|
6905
|
+
'待主 Agent 执行事项:',
|
|
6906
|
+
' - 核验本行证据与验收结论,处置 needs/待指示(如有)',
|
|
6907
|
+
...needs.map((item: any) => ` - 跨部门需求:${truncate(needEntryText(item), 300)}`),
|
|
6908
|
+
...missingArtifacts.map((ref: any) => ` - 缺失产物待补:${truncate(String(ref ?? ''), 200)}`),
|
|
6909
|
+
' - 生效建议:插件源码改动需用户手动重启 dsh web 生效,无需安装;Agent 不得自行重启或安装(D8)',
|
|
6910
|
+
]
|
|
6911
|
+
/*
|
|
6912
|
+
* [3.0.0][用户要求 11] 部门负责人的汇总报告完成后必须直接交给主 Agent:
|
|
6913
|
+
* 完成通知里原样带上 departmentSummary 的 JSON(不经二次概括、不裁剪),
|
|
6914
|
+
* 主 Agent 收到即可直接汇总最终成果(用户要求 12)。
|
|
6915
|
+
*/
|
|
6916
|
+
const departmentSummaryBlock = row?.departmentSummary && typeof row.departmentSummary === 'object'
|
|
6917
|
+
? ['部门汇总报告(JSON,直接交给主 Agent):', JSON.stringify(row.departmentSummary)]
|
|
6918
|
+
: []
|
|
6919
|
+
const text = truncate([
|
|
6920
|
+
`[dsh-workplan] 子任务 ${String(subtask?.id ?? '')} 已完成并结算:${summary};${acceptanceCount};用时 ${elapsed}`,
|
|
6921
|
+
conclusion,
|
|
6922
|
+
...(acceptanceLines.length > 0 ? ['逐条验收结论:', ...acceptanceLines] : []),
|
|
6923
|
+
...departmentSummaryBlock,
|
|
6924
|
+
...todoLines,
|
|
6925
|
+
].join('\n'), 4000)
|
|
6926
|
+
const ref = `${record?.plan?.planId ?? 'plan'}:${record?.dispatchedAt ?? 0}`
|
|
6927
|
+
/*
|
|
6928
|
+
* [T9][T5 冻结契约 §1/§4/§5] head→root 完成留痕 kind='completion'(复用
|
|
6929
|
+
* channelJournal 统一入口,不另造通道)。留痕结果与投递结果分开报、绝不
|
|
6930
|
+
* 互相掩盖:留痕写失败只 warn+pushRecordError,不阻塞通知投递与回报标记。
|
|
6931
|
+
*/
|
|
6932
|
+
const journalCompletion = (delivery: any) => {
|
|
6933
|
+
try {
|
|
6934
|
+
const artifacts = (Array.isArray(row?.artifacts) ? row.artifacts : [])
|
|
6935
|
+
.map((artifact: any) => truncate(String(artifact?.ref ?? ''), 200))
|
|
6936
|
+
.filter(Boolean)
|
|
6937
|
+
.slice(0, 20)
|
|
6938
|
+
const written = channelJournal({
|
|
6939
|
+
planId: String(record?.plan?.planId ?? ''),
|
|
6940
|
+
subtaskId: String(subtask?.id ?? ''),
|
|
6941
|
+
kind: 'completion',
|
|
6942
|
+
from: { sessionId: String(row?.childId || session.id), role: 'head' },
|
|
6943
|
+
to: { sessionId: String(session.id), role: 'root' },
|
|
6944
|
+
body: text,
|
|
6945
|
+
data: { status: 'done', acceptanceCount: passed, artifacts },
|
|
6946
|
+
delivery,
|
|
6947
|
+
})
|
|
6948
|
+
if (!written.result?.ok) {
|
|
6949
|
+
ctx.logger?.warn?.(`dsh-workplan: 完成汇报留痕写入失败 ${String(subtask?.id ?? '')}:${String(written.result?.error ?? 'JOURNAL_WRITE_FAILED')}`)
|
|
6950
|
+
pushRecordError(record, `完成汇报留痕写入失败(通知投递结果=${String(delivery?.status ?? 'unknown')}):${String(written.result?.error ?? 'JOURNAL_WRITE_FAILED')}`)
|
|
6951
|
+
}
|
|
6952
|
+
} catch (error) {
|
|
6953
|
+
ctx.logger?.warn?.(`dsh-workplan: 完成汇报留痕写入失败 ${String(subtask?.id ?? '')}:${error instanceof Error ? error.message : String(error)}`)
|
|
6954
|
+
pushRecordError(record, `完成汇报留痕写入失败(通知投递结果=${String(delivery?.status ?? 'unknown')}):${error instanceof Error ? error.message : String(error)}`)
|
|
6955
|
+
}
|
|
6956
|
+
}
|
|
6957
|
+
/*
|
|
6958
|
+
* [T7] C1/C2/C3:注入正文裁剪为一行关键进度(ID+完成状态+验收计数+
|
|
6959
|
+
* 用时+D7 结论+摘要+needs/缺失产物计数+下一步);逐条验收全文与待办
|
|
6960
|
+
* 清单只保留在 channelJournal completion 留痕(按需通道:journal/reports
|
|
6961
|
+
* 产物/dsh_workplan_status),不再默认注入模型上下文。
|
|
6962
|
+
*/
|
|
6963
|
+
/*
|
|
6964
|
+
* [T9][F1/F2] C1 必含字段补齐「子任务标题」;C2 禁止注入回报正文——summary
|
|
6965
|
+
* 只保留在 channelJournal completion 留痕与既有全量 text 里,不再拼进模型
|
|
6966
|
+
* 可见通知;回报正文里的 <!-- WORKPLAN_EVIDENCE... --> 证据块因此不会进入
|
|
6967
|
+
* 上下文(此前 summary 截 160 字仍可能把证据 JSON 头部带进模型可见面)。
|
|
6968
|
+
*/
|
|
6969
|
+
const titleText = truncate(String(subtask?.title ?? '').replace(/\s+/g, ' ').trim(), 60)
|
|
6970
|
+
const keyText = capKeyProgressText([
|
|
6971
|
+
`【关键进度】${String(subtask?.id ?? '')} 完成`,
|
|
6972
|
+
...(titleText ? [`标题:${titleText}`] : []),
|
|
6973
|
+
acceptanceCount,
|
|
6974
|
+
`用时 ${elapsed}`,
|
|
6975
|
+
truncate(conclusion, 160),
|
|
6976
|
+
...(needs.length > 0 ? [`跨部门需求 ${needs.length} 条待处置(dsh_workplan_handoff list)`] : []),
|
|
6977
|
+
...(missingArtifacts.length > 0 ? [`缺失产物 ${missingArtifacts.length} 项待补`] : []),
|
|
6978
|
+
'下一步:主 Agent 核验证据与验收后整合(按需:dsh_workplan_status/结算文件)',
|
|
6979
|
+
].join('|'))
|
|
6045
6980
|
try {
|
|
6046
|
-
appendUserMessage(session,
|
|
6981
|
+
appendUserMessage(session, keyText)
|
|
6047
6982
|
} catch (error) {
|
|
6048
6983
|
ctx.logger?.warn?.(
|
|
6049
6984
|
`dsh-workplan: 完成即时通知写入失败 ${String(subtask?.id ?? '')}:`
|
|
6050
6985
|
+ `${error instanceof Error ? error.message : String(error)}`,
|
|
6051
6986
|
)
|
|
6987
|
+
/* [T9][D6] 投递失败显式留 failed 痕(可重试、不静默),维持 reportPending
|
|
6988
|
+
* 交 finishRound 补齐——「先写通知后记回报、绝不留无证据已回报」不变。 */
|
|
6989
|
+
journalCompletion({ status: 'failed', error: truncate(String(error instanceof Error ? error.message : error), 300) })
|
|
6052
6990
|
record.reportPending = true
|
|
6053
6991
|
return
|
|
6054
6992
|
}
|
|
6055
|
-
|
|
6993
|
+
journalCompletion({ status: 'sent' })
|
|
6056
6994
|
markReported(record, session, ref, subtask?.id)
|
|
6057
6995
|
}
|
|
6058
6996
|
|
|
6059
|
-
|
|
6060
|
-
|
|
6061
|
-
|
|
6062
|
-
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
6076
|
-
|
|
6077
|
-
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
6086
|
-
|
|
6087
|
-
|
|
6088
|
-
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
|
|
6092
|
-
|
|
6093
|
-
|
|
6094
|
-
|
|
6095
|
-
|
|
6096
|
-
|
|
6097
|
-
|
|
6997
|
+
/**
|
|
6998
|
+
* [T8] 第三层叶子完成即时通知:收件方 = 原分派部门负责人会话。
|
|
6999
|
+
*
|
|
7000
|
+
* 改动前验证结论(2026-11-12):两处叶子结算回调(delegateTool dispatch /
|
|
7001
|
+
* selfEffortTool 自配档接续)此前只把 durable workplan-update 写到根会话;
|
|
7002
|
+
* 负责人会话只能靠宿主 delivery=caller 转达子会话原文,没有插件侧「已结算
|
|
7003
|
+
* 为 done」的即时完成汇报,delegates 条目也没有回报幂等标记。负责人会话
|
|
7004
|
+
* id 的反查判据:根计划部门行 row.childId(executeSubtask 派发时登记,
|
|
7005
|
+
* delegateTool 按 statuses[].childId===负责人会话 id 定位行),与
|
|
7006
|
+
* escalateDelegateLeaf 的 headChildId 同一判据。
|
|
7007
|
+
*
|
|
7008
|
+
* 复用 T5 冻结契约(_t5_channel_20261112/00-contract-v1.md §1/§5):
|
|
7009
|
+
* - 投递:ctx.subagents.sendMessage(根 agent → row.childId 负责人会话,
|
|
7010
|
+
* 宿主 lineage 校验与 instructDelegate/followup 同范式);辅助
|
|
7011
|
+
* user/message 纯文本通知(appendUserMessage 唯一合规写入器,尽力而为,
|
|
7012
|
+
* 不改变投递判定);
|
|
7013
|
+
* - 留痕:channelJournal kind='completion',data={status:'done'},
|
|
7014
|
+
* from 叶子 → to head;
|
|
7015
|
+
* - done-only:只对 delegates[].status==='done' 通知(failed/待指示不产生
|
|
7016
|
+
* 「已完成」措辞);
|
|
7017
|
+
* - 幂等:只有 report.state==='sent' 拦重报(T5 教训:failed 必须可重试);
|
|
7018
|
+
* 先投递、成功才记 sent;
|
|
7019
|
+
* - 兜底:投递失败显式 DELIVERY_FAILED + report.state='failed' +
|
|
7020
|
+
* record.errors 留痕,下一次结算(含其他成员结算)自动补发所有 done
|
|
7021
|
+
* 未 sent 条目——与 reportPending「绝不留无证据的已回报」同一纪律;
|
|
7022
|
+
* 不触碰主行 closure/deriveReportPending,通知失败绝不回滚或阻塞完成判定。
|
|
7023
|
+
* 主计划子任务通知仍 → 根会话(emitSubtaskDoneNotice 不变,T9 范围)。
|
|
7024
|
+
*/
|
|
7025
|
+
/*
|
|
7026
|
+
* [T8][race-fix] 并发结算竞态治本(负责人独立审读发现,2026-11-12):
|
|
7027
|
+
* 旧实现在 pending 过滤与 report 标记写回之间隔着 await sendMessage——
|
|
7028
|
+
* 8 名下属同一 tick 完成时,回调 A 在 await 处让出事件循环,回调 B 随即
|
|
7029
|
+
* 把 m1(尚未写 sent 标记)也视为 pending → 重复投递,击穿「8 人=恰 8 条」;
|
|
7030
|
+
* 且各回调用入口捕获的 delegates 快照写回,会互相覆盖对方的结算与标记
|
|
7031
|
+
* (lost update)。治本 = 等价串行化:每 record 一条 promise 链(闭包级
|
|
7032
|
+
* WeakMap,随 record 生命周期回收,无定时器/认领泄漏),入队在同步段完成
|
|
7033
|
+
* (任何 await 之前);链节内「读最新台账 → 投递 → 写标记」整段互斥,
|
|
7034
|
+
* 上一节完全结束才跑下一节;异常在节内捕获,链永不断裂。failed 天然可重试
|
|
7035
|
+
* (无认领,state!=='sent' 即补发)。
|
|
7036
|
+
*/
|
|
7037
|
+
const delegateNoticeChains = new WeakMap<object, Promise<void>>()
|
|
7038
|
+
const delegateNoticeKey = (item: any) => `${String(item?.childId ?? '')}|${String(item?.member ?? '')}`
|
|
7039
|
+
function emitDelegateDoneNotices(record: any, leaderSession: any, rootSession: any, subtaskId: string): Promise<void> {
|
|
7040
|
+
if (!record || !leaderSession) return Promise.resolve()
|
|
7041
|
+
const prior = delegateNoticeChains.get(record) ?? Promise.resolve()
|
|
7042
|
+
const task = prior
|
|
7043
|
+
.then(() => deliverDelegateDoneNotices(record, leaderSession, rootSession, subtaskId))
|
|
7044
|
+
.catch((error) => {
|
|
7045
|
+
// 意外异常只留痕:链不得断裂,也不得影响结算判定。
|
|
7046
|
+
try {
|
|
7047
|
+
ctx.logger?.warn?.(`dsh-workplan: 第三层完成通知链节异常 ${subtaskId}:${error instanceof Error ? error.message : String(error)}`)
|
|
7048
|
+
record.errors = [...(record.errors ?? []), `${subtaskId} 完成通知链节异常:${truncate(String(error instanceof Error ? error.message : error), 200)}`].slice(-20)
|
|
7049
|
+
} catch { /* 留痕失败不影响主链路 */ }
|
|
7050
|
+
})
|
|
7051
|
+
delegateNoticeChains.set(record, task)
|
|
7052
|
+
return task
|
|
7053
|
+
}
|
|
7054
|
+
|
|
7055
|
+
async function deliverDelegateDoneNotices(record: any, leaderSession: any, rootSession: any, subtaskId: string) {
|
|
7056
|
+
if (!record || !leaderSession) return
|
|
7057
|
+
const row = Array.isArray(record.statuses)
|
|
7058
|
+
? record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
7059
|
+
: null
|
|
7060
|
+
const delegates = Array.isArray(row?.delegates) ? row.delegates : []
|
|
7061
|
+
const pending = delegates.filter((item: any) => item?.status === 'done' && item?.report?.state !== 'sent')
|
|
7062
|
+
if (pending.length === 0) return
|
|
7063
|
+
const headChildId = typeof row?.childId === 'string' && row.childId ? row.childId : String(leaderSession?.id ?? '')
|
|
7064
|
+
const service: any = (ctx as any).subagents
|
|
7065
|
+
/*
|
|
7066
|
+
* 发送者必须是根会话 agent:负责人会话是根会话的直接子会话,宿主 lineage
|
|
7067
|
+
* 校验只允许父→子投递(instructDelegate 同范式)。结算回调闭包里的 agent
|
|
7068
|
+
* 是负责人自己(delegateTool 调用者),不能作发送者。解析失败 fail-closed
|
|
7069
|
+
* 记 failed,绝不静默跳过。
|
|
7070
|
+
*/
|
|
7071
|
+
const rootAgent = resolveLiveAgent(ctx, rootSession?.id)
|
|
7072
|
+
const rawTurn = Number(state.activeTurns?.get?.(leaderSession?.id) ?? NaN)
|
|
7073
|
+
const turn = Number.isFinite(rawTurn) ? rawTurn : null
|
|
7074
|
+
const ref = `${record?.plan?.planId ?? 'plan'}:${record?.dispatchedAt ?? 0}`
|
|
7075
|
+
const marks = new Map<string, any>()
|
|
7076
|
+
for (const member of pending) {
|
|
7077
|
+
const startedAt = Number(member?.startedAt)
|
|
7078
|
+
const finishedAt = Number(member?.finishedAt)
|
|
7079
|
+
const elapsedMs = Number.isFinite(startedAt) && Number.isFinite(finishedAt) ? Math.max(0, finishedAt - startedAt) : 0
|
|
7080
|
+
const elapsed = elapsedMs < 1000 ? `${elapsedMs}ms` : `${(elapsedMs / 1000).toFixed(1)}s`
|
|
7081
|
+
const summary = truncate(String(member?.summary ?? '').replace(/\s+/g, ' ').trim(), 300) || '(无摘要)'
|
|
7082
|
+
const body = truncate([
|
|
7083
|
+
`【第三层完成汇报|${String(member?.member ?? '')} → 部门负责人】`,
|
|
7084
|
+
`子任务 ${subtaskId} 的第三层成员 ${String(member?.member ?? '')} 已完成并结算(status=done)。`,
|
|
7085
|
+
`摘要:${summary}`,
|
|
7086
|
+
`用时:${elapsed}`,
|
|
7087
|
+
'请核验并汇总该成员产物;收齐后写最终结果块。',
|
|
7088
|
+
].join('\n'), 4000)
|
|
7089
|
+
const deliveryStartedAt = Date.now()
|
|
7090
|
+
let messageId = ''
|
|
7091
|
+
let deliveryError = ''
|
|
7092
|
+
if (!headChildId) deliveryError = '部门行没有登记负责人会话(childId 缺失),无法投递完成汇报'
|
|
7093
|
+
else if (!service || typeof service.sendMessage !== 'function') deliveryError = '当前部署没有可用的 subagent 服务(NO_SUBAGENT_SERVICE),无法投递完成汇报'
|
|
7094
|
+
else if (!rootAgent) deliveryError = '根会话 agent 解析失败,无法向负责人会话投递完成汇报'
|
|
7095
|
+
else {
|
|
7096
|
+
try {
|
|
7097
|
+
messageId = String(await service.sendMessage(rootAgent, headChildId, [{ type: 'text', text: body }], { signal: new AbortController().signal }) ?? '') // [T11] 缺陷②:完成汇报携带有效 signal,消除 throwIfAborted
|
|
7098
|
+
} catch (error: any) {
|
|
7099
|
+
deliveryError = truncate(error instanceof Error ? error.message : String(error), 500)
|
|
7100
|
+
}
|
|
7101
|
+
}
|
|
7102
|
+
const delivery = deliveryError ? 'failed' : 'sent'
|
|
7103
|
+
const journal = channelJournal({
|
|
7104
|
+
planId: String(record?.plan?.planId ?? ''),
|
|
7105
|
+
subtaskId,
|
|
7106
|
+
kind: 'completion',
|
|
7107
|
+
from: { sessionId: String(member?.childId ?? ''), role: 'expert', member: String(member?.member ?? '') },
|
|
7108
|
+
to: { sessionId: headChildId, role: 'head' },
|
|
7109
|
+
body,
|
|
7110
|
+
data: { status: 'done' },
|
|
7111
|
+
delivery: { status: delivery, ...(messageId ? { messageId } : {}), latencyMs: Date.now() - deliveryStartedAt, ...(deliveryError ? { code: 'DELIVERY_FAILED', error: deliveryError } : {}) },
|
|
7112
|
+
})
|
|
7113
|
+
// 契约 §4:留痕写失败本身也要显式报 JOURNAL_WRITE_FAILED,且不得掩盖投递结果。
|
|
7114
|
+
if (!journal.result.ok) {
|
|
7115
|
+
record.errors = [...(record.errors ?? []), `${subtaskId}/${String(member?.member ?? '')} 完成留痕写入失败 JOURNAL_WRITE_FAILED:${truncate(String(journal.result.error ?? ''), 200)}`].slice(-20)
|
|
7116
|
+
}
|
|
7117
|
+
// 辅助用户可见纯文本通知(user/message 通道,尽力而为):不替代 sendMessage 投递,不改变投递判定。
|
|
7118
|
+
if (typeof leaderSession.append === 'function') {
|
|
7119
|
+
try {
|
|
7120
|
+
appendUserMessage(leaderSession, `[dsh-workplan] 第三层成员 ${String(member?.member ?? '')}(子任务 ${subtaskId})已完成并结算:${truncate(summary, 160)};用时 ${elapsed}。请核验并汇总该成员产物。`)
|
|
7121
|
+
} catch (error) {
|
|
7122
|
+
ctx.logger?.warn?.(`dsh-workplan: 第三层完成纯文本通知写入失败 ${subtaskId}/${String(member?.member ?? '')}:${error instanceof Error ? error.message : String(error)}`)
|
|
7123
|
+
}
|
|
7124
|
+
}
|
|
7125
|
+
if (deliveryError) {
|
|
7126
|
+
ctx.logger?.warn?.(`dsh-workplan: 第三层完成即时通知投递失败 ${subtaskId}/${String(member?.member ?? '')}:DELIVERY_FAILED ${deliveryError}`)
|
|
7127
|
+
record.errors = [...(record.errors ?? []), `${subtaskId}/${String(member?.member ?? '')} 完成即时通知投递失败 DELIVERY_FAILED(report.state=failed,待兜底补发):${truncate(deliveryError, 200)}`].slice(-20)
|
|
7128
|
+
}
|
|
7129
|
+
marks.set(delegateNoticeKey(member), { state: delivery, at: Date.now(), ref, turn })
|
|
7130
|
+
}
|
|
7131
|
+
/*
|
|
7132
|
+
* 幂等标记写回台账(applyStatus 唯一写入口 + delegates.report 消毒)并
|
|
7133
|
+
* durable 回放到根会话:刷新/重启后「已通知」不丢、重复结算不重报。
|
|
7134
|
+
* 标记写失败只留痕:下次结算按 state!=='sent' 补发,不影响结算判定。
|
|
7135
|
+
*/
|
|
7136
|
+
try {
|
|
7137
|
+
// [T8][race-fix] 写时重读当前行+按键贴标记:不用入口快照,对
|
|
7138
|
+
// escalate/instruct 等非结算路径的并发写也免疫(不覆盖请示/指示子对象)。
|
|
7139
|
+
const currentRow = Array.isArray(record.statuses)
|
|
7140
|
+
? record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
7141
|
+
: null
|
|
7142
|
+
const currentDelegates = Array.isArray(currentRow?.delegates) ? currentRow.delegates : delegates
|
|
7143
|
+
const list = currentDelegates.map((item: any) => {
|
|
7144
|
+
const mark = marks.get(delegateNoticeKey(item))
|
|
7145
|
+
return mark ? { ...item, report: mark } : item
|
|
7146
|
+
})
|
|
7147
|
+
const revision = Number(currentRow?.revision ?? row?.revision ?? 0) + 1
|
|
7148
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision, updatedBy: 'system' })
|
|
7149
|
+
record.updatedAt = Date.now()
|
|
7150
|
+
const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
7151
|
+
appendUserMessage(rootSession, buildUpdateMessage({
|
|
7152
|
+
planId: record?.plan?.planId,
|
|
7153
|
+
subtaskId,
|
|
7154
|
+
status: written?.status ?? row?.status,
|
|
7155
|
+
delegates: written?.delegates ?? list,
|
|
7156
|
+
revision,
|
|
7157
|
+
note: '第三层成员完成即时通知已回报原分派负责人会话(delegates[].report)',
|
|
7158
|
+
}))
|
|
7159
|
+
} catch (error) {
|
|
7160
|
+
record.errors = [...(record.errors ?? []), `${subtaskId} delegates[].report 标记写入失败:${truncate(String(error instanceof Error ? error.message : error), 200)}`].slice(-20)
|
|
7161
|
+
}
|
|
7162
|
+
}
|
|
7163
|
+
|
|
7164
|
+
function finishRound(record: any, session: any) {
|
|
7165
|
+
/*
|
|
7166
|
+
* [2.5.5][T10] 结算前先合并落盘缓冲的台账事件:本轮最后一批非关键更新
|
|
7167
|
+
* 不能因为「后面没有别的消息」而滞留内存(刷新/重启即丢)。
|
|
7168
|
+
*/
|
|
7169
|
+
try {
|
|
7170
|
+
flushPendingWorkplanUpdates(session)
|
|
7171
|
+
} catch (error) {
|
|
7172
|
+
ctx.logger?.warn?.(`dsh-workplan: 合并台账落盘失败:${error instanceof Error ? error.message : String(error)}`)
|
|
7173
|
+
}
|
|
7174
|
+
const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`
|
|
7175
|
+
if (!record.resultWritten) {
|
|
7176
|
+
/*
|
|
7177
|
+
* [1.11.0] 完成必回报的顺序:先标记 reported,再构建并落盘结果消息。
|
|
7178
|
+
*
|
|
7179
|
+
* 这样结果消息里的 statuses 就带着 `closure:'reported'`,刷新/重启后
|
|
7180
|
+
* 回放得到同一个结论;而“标记了但消息没写成功”会在 catch 里回滚,
|
|
7181
|
+
* 绝不留下没有证据的 reported。
|
|
7182
|
+
*/
|
|
7183
|
+
const before = (record.statuses ?? []).map((item: any) => ({ ...item }))
|
|
7184
|
+
markReported(record, session, ref)
|
|
7185
|
+
const resultMessage = buildRoundResult(record, session.id, limits)
|
|
7186
|
+
try {
|
|
7187
|
+
appendUserMessage(session, resultMessage)
|
|
7188
|
+
record.resultWritten = true
|
|
7189
|
+
/*
|
|
7190
|
+
* [2.2.9][T3][M4] 标志自此只是审计镜像,一律按派生函数回填。
|
|
7191
|
+
* 旧公式 `needReport > 0 && reported < needReport` 自带第三套口径
|
|
7192
|
+
* (把旧日志 closure=null 的行也算待回报),与门禁/重建/自愈使用的
|
|
7193
|
+
* 严格 `closure==='done'` 判据并存——多套判据互不一致正是震荡的
|
|
7194
|
+
* 温床。收敛后镜像与 statuses 事实恒等,任何读取方都对得上。
|
|
7195
|
+
*/
|
|
7196
|
+
record.reportPending = deriveReportPending(record)
|
|
7197
|
+
} catch (error) {
|
|
7198
|
+
// 消息没写成功 ⇒ 回报没有证据:把状态回滚成写之前的快照。
|
|
7199
|
+
record.statuses = before
|
|
7200
|
+
ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
|
|
7201
|
+
/*
|
|
7202
|
+
* [1.8.14] N13: a failed result write is a real, user-visible failure —
|
|
7203
|
+
* the round summary is absent from the transcript and a restart can
|
|
7204
|
+
* disagree with the live phase. Log it durably, not only in the host log.
|
|
7205
|
+
*/
|
|
7206
|
+
pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
|
|
7207
|
+
/*
|
|
7208
|
+
* [1.11.0] 写失败时不能假装回报过。回滚后镜像同步为回滚事实
|
|
7209
|
+
* (done 行回到 closure:'done' ⇒ 派生 true),交下一次 pre-step
|
|
7210
|
+
* 自愈或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
|
|
7211
|
+
*/
|
|
6098
7212
|
record.reportPending = deriveReportPending(record)
|
|
6099
7213
|
}
|
|
6100
7214
|
} else {
|
|
6101
7215
|
/*
|
|
6102
|
-
* 旧日志 / 上一次写失败的重试:结果消息已在,但仍有
|
|
6103
|
-
*
|
|
7216
|
+
* [2.2.9][T3][M4] 旧日志 / 上一次写失败的重试:结果消息已在,但仍有
|
|
7217
|
+
* 本轮完成、未回报的 done 行(closure==='done')。幂等补齐,不重复追加
|
|
7218
|
+
* 消息。判据与 deriveReportPending(runtime.ts:245 严格口径
|
|
7219
|
+
* `status==='done' && closure==='done'`)收敛为同一套:旧日志
|
|
7220
|
+
* closure=null 的历史 done 行本来就已回报过,不在此补标。
|
|
6104
7221
|
*/
|
|
6105
7222
|
const pending = (record.statuses ?? []).some((item: any) =>
|
|
6106
|
-
item?.status === 'done' && item?.closure
|
|
7223
|
+
item?.status === 'done' && item?.closure === 'done')
|
|
6107
7224
|
if (pending) {
|
|
6108
7225
|
markReported(record, session, ref)
|
|
6109
7226
|
// [2.2.9][T3][M4] 镜像按派生回填:部分标记失败时不谎报「已回报」。
|
|
@@ -6392,6 +7509,209 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6392
7509
|
}
|
|
6393
7510
|
}
|
|
6394
7511
|
|
|
7512
|
+
/**
|
|
7513
|
+
* [2.5.6] 第三层叶子归属反查(叶子↔负责人双向请示/指示通道的读侧)。
|
|
7514
|
+
*
|
|
7515
|
+
* 叶子会话的父链是「叶子 → 部门负责人 → 根会话」,计划只挂在根会话上。
|
|
7516
|
+
* 沿父链向上(≤3 跳,防环)找到第一个有计划记录的祖先,再按 delegate
|
|
7517
|
+
* 登记(行 delegates[].childId)定位叶子所属的部门行与成员条目——与
|
|
7518
|
+
* selfEffortTool 同一判据,不信任自报 subtaskId。找不到计划或 childId
|
|
7519
|
+
* 未登记时返回 null,由调用方维持原错误语义。
|
|
7520
|
+
*/
|
|
7521
|
+
function findDelegateLeafContext(childSession: any) {
|
|
7522
|
+
let ancestorId = childSession?.header?.parentSession
|
|
7523
|
+
for (let hop = 0; hop < 3 && typeof ancestorId === 'string' && ancestorId; hop += 1) {
|
|
7524
|
+
let rec = state.records.get(ancestorId)
|
|
7525
|
+
if (!rec?.plan) {
|
|
7526
|
+
const sess = (ctx as any).sessions?.get?.(ancestorId)
|
|
7527
|
+
if (sess) {
|
|
7528
|
+
try { rec = reconstructFromSession(sess) } catch (error) { pushRecordError({ errors: [] } as any, error) }
|
|
7529
|
+
}
|
|
7530
|
+
}
|
|
7531
|
+
if (rec?.plan) {
|
|
7532
|
+
const deptRow = (rec.statuses ?? []).find((item: any) => Array.isArray(item?.delegates)
|
|
7533
|
+
&& item.delegates.some((d: any) => d?.childId === childSession.id))
|
|
7534
|
+
if (!deptRow) return null
|
|
7535
|
+
const member = deptRow.delegates.find((d: any) => d?.childId === childSession.id)
|
|
7536
|
+
return { record: rec, row: deptRow, member, ownerId: ancestorId }
|
|
7537
|
+
}
|
|
7538
|
+
const sess = (ctx as any).sessions?.get?.(ancestorId)
|
|
7539
|
+
ancestorId = sess?.header?.parentSession
|
|
7540
|
+
}
|
|
7541
|
+
return null
|
|
7542
|
+
}
|
|
7543
|
+
|
|
7544
|
+
/**
|
|
7545
|
+
* [T5-channel][契约v1 §1/§2] 通道留痕统一入口:补齐 v/id/ts 后交
|
|
7546
|
+
* appendDeptMessage(fail-closed 校验+显式 JOURNAL_WRITE_FAILED)。返回
|
|
7547
|
+
* 消息 id 与写盘结果,供调用方把「投递结果」与「留痕结果」两者都报,
|
|
7548
|
+
* 绝不互相掩盖(契约 §4)。
|
|
7549
|
+
*/
|
|
7550
|
+
function channelJournal(fields: {
|
|
7551
|
+
planId: string
|
|
7552
|
+
subtaskId: string
|
|
7553
|
+
// [T8] completion 复用同一留痕入口(T5 冻结契约 §5:叶子→head 完成汇报)。
|
|
7554
|
+
// [T6] estimate 复用同一留痕入口(T6 冻结契约 §4:叶子→head 开工预估)。
|
|
7555
|
+
kind: 'escalation' | 'instruction' | 'completion' | 'estimate'
|
|
7556
|
+
from: any
|
|
7557
|
+
to: any
|
|
7558
|
+
body: string
|
|
7559
|
+
data?: Record<string, unknown>
|
|
7560
|
+
delivery: any
|
|
7561
|
+
}) {
|
|
7562
|
+
const message = { v: 1, id: makeDeptMessageId(), ts: Date.now(), ...fields }
|
|
7563
|
+
const written = appendDeptMessage(message)
|
|
7564
|
+
return { id: message.id, result: written }
|
|
7565
|
+
}
|
|
7566
|
+
|
|
7567
|
+
/*
|
|
7568
|
+
* [T6][契约v1 §3/§5] 叶子开工预估的读侧消毒(与 plan.ts sanitizeDelegateEstimate
|
|
7569
|
+
* 同一判据,G1 双侧接线):declaredMinutes 正整数分钟(Number.isInteger 且
|
|
7570
|
+
* 1..10080,不做字符串强转)、at 正数、delivery 枚举 sent/failed;reason ≤300、
|
|
7571
|
+
* messageId ≤200 均可选。任一必填非法 ⇒ 整个 estimate 视为未登记(null)。
|
|
7572
|
+
* 重派读档门禁与 self_effort 幂等判据据此判定「预估已登记」。
|
|
7573
|
+
*/
|
|
7574
|
+
function sanitizeLeafEstimate(value: any): { declaredMinutes: number; reason?: string; at: number; messageId?: string; delivery: 'sent' | 'failed' } | null {
|
|
7575
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
|
7576
|
+
const minutes = value.declaredMinutes
|
|
7577
|
+
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 10080) return null
|
|
7578
|
+
const at = Number(value.at)
|
|
7579
|
+
if (!Number.isFinite(at) || at <= 0) return null
|
|
7580
|
+
if (value.delivery !== 'sent' && value.delivery !== 'failed') return null
|
|
7581
|
+
return {
|
|
7582
|
+
declaredMinutes: minutes,
|
|
7583
|
+
...(typeof value.reason === 'string' && value.reason.trim() ? { reason: truncate(value.reason.trim(), 300) } : {}),
|
|
7584
|
+
at,
|
|
7585
|
+
...(typeof value.messageId === 'string' && value.messageId ? { messageId: truncate(value.messageId, 200) } : {}),
|
|
7586
|
+
delivery: value.delivery,
|
|
7587
|
+
}
|
|
7588
|
+
}
|
|
7589
|
+
|
|
7590
|
+
/**
|
|
7591
|
+
* [T5-channel][契约v1 §3a] 第三层叶子的请示落档(写侧):question/options/
|
|
7592
|
+
* needs 经 ctx.subagents.sendMessage 投给部门负责人会话(row.childId),写
|
|
7593
|
+
* kind='escalation' 留痕,经 applyStatus 把 delegates[i].escalation 子对象
|
|
7594
|
+
* 持久化并发 durable update 到根会话。部门行本身的 status/closure 不变——
|
|
7595
|
+
* 问题等负责人答,不是等主 Agent。announceSubtaskInterrupt 仅作辅助用户
|
|
7596
|
+
* 可见通知,不替代给负责人的 sendMessage 投递。
|
|
7597
|
+
*/
|
|
7598
|
+
async function escalateDelegateLeaf(agent: any, leaf: any, args: any) {
|
|
7599
|
+
const { record, row, member, ownerId } = leaf
|
|
7600
|
+
if (member.status === 'done') {
|
|
7601
|
+
return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, member: member.member, error: '该成员已结算,不能再提交请示' }
|
|
7602
|
+
}
|
|
7603
|
+
const question = truncate(String(args?.question ?? '').trim(), MAX_QUESTION_CHARS)
|
|
7604
|
+
if (!question) {
|
|
7605
|
+
return { ok: false, code: 'INVALID_QUESTION', subtaskId: row.subtaskId, member: member.member, error: 'question 必填:写清需要部门负责人决定的单个问题' }
|
|
7606
|
+
}
|
|
7607
|
+
// [T5-channel][D6] 投递失败的请示允许重试:delivery='failed' 不走幂等分支,
|
|
7608
|
+
// 重新投递并覆盖留档;只有已成功送达(sent)的请示才拦截重复提交。
|
|
7609
|
+
if (member.escalation && member.escalation.delivery !== 'failed') {
|
|
7610
|
+
return {
|
|
7611
|
+
ok: true,
|
|
7612
|
+
alreadyEscalated: true,
|
|
7613
|
+
routedTo: 'head',
|
|
7614
|
+
planId: record.plan.planId,
|
|
7615
|
+
subtaskId: row.subtaskId,
|
|
7616
|
+
member: member.member,
|
|
7617
|
+
question: member.escalation.question ?? question,
|
|
7618
|
+
message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待部门负责人指示。',
|
|
7619
|
+
}
|
|
7620
|
+
}
|
|
7621
|
+
const options = (Array.isArray(args?.options) ? args.options : [])
|
|
7622
|
+
.slice(0, MAX_ESCALATION_OPTIONS)
|
|
7623
|
+
.map((item: any) => truncate(needEntryText(item), 300))
|
|
7624
|
+
.filter(Boolean)
|
|
7625
|
+
const needs = (Array.isArray(args?.needs) ? args.needs : [])
|
|
7626
|
+
.slice(0, 10)
|
|
7627
|
+
.map((item: any) => truncate(needEntryText(item), 300))
|
|
7628
|
+
.filter(Boolean)
|
|
7629
|
+
const headChildId = typeof row.childId === 'string' ? row.childId : ''
|
|
7630
|
+
if (!headChildId) {
|
|
7631
|
+
return { ok: false, code: 'NO_SUBTASK', subtaskId: row.subtaskId, member: member.member, error: '部门行没有登记负责人会话(childId 缺失),无法投递请示' }
|
|
7632
|
+
}
|
|
7633
|
+
const service: any = (ctx as any).subagents
|
|
7634
|
+
if (!service || typeof service.sendMessage !== 'function') {
|
|
7635
|
+
return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId: row.subtaskId, member: member.member, error: '当前部署没有可用的 subagent 服务,无法投递请示' }
|
|
7636
|
+
}
|
|
7637
|
+
const now = Date.now()
|
|
7638
|
+
const body = truncate([
|
|
7639
|
+
`【第三层请示|${member.member} → 部门负责人】`,
|
|
7640
|
+
`子任务 ${row.subtaskId} 的第三层成员 ${member.member} 执行中请求指示:`,
|
|
7641
|
+
question,
|
|
7642
|
+
options.length ? `可选方向:${options.join(';')}` : '',
|
|
7643
|
+
needs.length ? `跨部门需求:${needs.join(';')}` : '',
|
|
7644
|
+
`请答复:dsh_workplan_instruct(subtaskId=${row.subtaskId},member=${member.member},instruction=你的决定)。答复前该成员停止推进、只做只读核对。`,
|
|
7645
|
+
].filter(Boolean).join('\n'), 4000)
|
|
7646
|
+
const startedAt = Date.now()
|
|
7647
|
+
let messageId = ''
|
|
7648
|
+
let deliveryError = ''
|
|
7649
|
+
try {
|
|
7650
|
+
messageId = String(await service.sendMessage(agent, headChildId, [{ type: 'text', text: body }], { signal: new AbortController().signal }) ?? '') // [T11] 缺陷②:请示上报携带有效 signal,消除 throwIfAborted
|
|
7651
|
+
} catch (error: any) {
|
|
7652
|
+
deliveryError = truncate(error instanceof Error ? error.message : String(error), 500)
|
|
7653
|
+
}
|
|
7654
|
+
const latencyMs = Date.now() - startedAt
|
|
7655
|
+
const delivery = deliveryError ? 'failed' : 'sent'
|
|
7656
|
+
const journal = channelJournal({
|
|
7657
|
+
planId: record.plan.planId,
|
|
7658
|
+
subtaskId: row.subtaskId,
|
|
7659
|
+
kind: 'escalation',
|
|
7660
|
+
from: { sessionId: String(agent?.session?.id ?? ''), role: 'expert', member: member.member },
|
|
7661
|
+
to: { sessionId: headChildId, role: 'head' },
|
|
7662
|
+
body,
|
|
7663
|
+
data: { options, needs },
|
|
7664
|
+
delivery: { status: delivery, ...(messageId ? { messageId } : {}), latencyMs, ...(deliveryError ? { code: 'DELIVERY_FAILED', error: deliveryError } : {}) },
|
|
7665
|
+
})
|
|
7666
|
+
const journalInfo = journal.result.ok ? {} : { journal: { ok: false, code: journal.result.code, error: journal.result.error } }
|
|
7667
|
+
const revision = Number(row.revision ?? 0) + 1
|
|
7668
|
+
const delegates = (Array.isArray(row.delegates) ? row.delegates : []).map((item: any) => (item?.childId === member.childId
|
|
7669
|
+
? { ...item, escalation: { question, options, needs, at: now, ...(messageId ? { messageId } : {}), delivery } }
|
|
7670
|
+
: item))
|
|
7671
|
+
record.statuses = applyStatus(record.statuses, row.subtaskId, { delegates, revision, updatedBy: 'child' })
|
|
7672
|
+
record.updatedAt = now
|
|
7673
|
+
try {
|
|
7674
|
+
const written = record.statuses.find((item: any) => item?.subtaskId === row.subtaskId)
|
|
7675
|
+
const ownerSession = (ctx as any).sessions?.get?.(ownerId)
|
|
7676
|
+
// durable 回放挂在计划所有者(根会话)上:刷新/重启后请示不丢。
|
|
7677
|
+
appendUserMessage(ownerSession, buildUpdateMessage({
|
|
7678
|
+
planId: record.plan.planId,
|
|
7679
|
+
subtaskId: row.subtaskId,
|
|
7680
|
+
status: written?.status ?? row.status,
|
|
7681
|
+
delegates: written?.delegates ?? delegates,
|
|
7682
|
+
revision,
|
|
7683
|
+
note: `第三层成员 ${member.member} 提交请示(待指示)`,
|
|
7684
|
+
// [T7] C1 白名单:第三层请示=待指示事件,注入一行关键进度(含阻塞原因)。
|
|
7685
|
+
keyProgress: true,
|
|
7686
|
+
stateLabel: '待指示(第三层)',
|
|
7687
|
+
question,
|
|
7688
|
+
title: flattenSubtasks(record.plan).find((entry: any) => entry.subtask?.id === row.subtaskId)?.subtask?.title,
|
|
7689
|
+
}))
|
|
7690
|
+
// 辅助用户可见通知(不替代 sendMessage 投递):负责人当下看到谁在等谁。
|
|
7691
|
+
const leader = (ctx as any).sessions?.get?.(headChildId)
|
|
7692
|
+
announceSubtaskInterrupt(record, leader, row.subtaskId,
|
|
7693
|
+
`第三层成员 ${member.member} 请求指示:${truncate(question, 160)};性质:等待部门负责人拍板,不是执行失败;处理:负责人用 dsh_workplan_instruct(subtaskId=${row.subtaskId},member=${member.member})答复后,该成员恢复执行。`)
|
|
7694
|
+
} catch (error) {
|
|
7695
|
+
pushRecordError(record, error)
|
|
7696
|
+
}
|
|
7697
|
+
if (deliveryError) {
|
|
7698
|
+
return { ok: false, code: 'DELIVERY_FAILED', subtaskId: row.subtaskId, member: member.member, error: deliveryError, ...journalInfo }
|
|
7699
|
+
}
|
|
7700
|
+
return {
|
|
7701
|
+
ok: true,
|
|
7702
|
+
routedTo: 'head',
|
|
7703
|
+
planId: record.plan.planId,
|
|
7704
|
+
subtaskId: row.subtaskId,
|
|
7705
|
+
member: member.member,
|
|
7706
|
+
messageId,
|
|
7707
|
+
latencyMs,
|
|
7708
|
+
question,
|
|
7709
|
+
revision,
|
|
7710
|
+
...journalInfo,
|
|
7711
|
+
message: '已上报部门负责人。请立即停止推进,只允许做只读核对;等待指示期间不要开始新的写入或大改。',
|
|
7712
|
+
}
|
|
7713
|
+
}
|
|
7714
|
+
|
|
6395
7715
|
/**
|
|
6396
7716
|
* [1.11.0] 子 → 父的唯一反向通道(T4 C-09 / T6 M5)。
|
|
6397
7717
|
*
|
|
@@ -6424,15 +7744,24 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6424
7744
|
}
|
|
6425
7745
|
}
|
|
6426
7746
|
}
|
|
6427
|
-
|
|
6428
|
-
|
|
6429
|
-
|
|
6430
|
-
|
|
6431
|
-
|
|
7747
|
+
const row = (record?.statuses ?? []).find((item: any) => item?.childId === childSession.id)
|
|
7748
|
+
/*
|
|
7749
|
+
* [2.5.6] 第三层叶子兜底(治本):叶子的直接父会话是部门负责人,负责人
|
|
7750
|
+
* 自己没有计划记录——旧实现在这里直接 NO_PLAN,叶子永远无法请示。现在
|
|
7751
|
+
* 经 delegate 登记(根计划行 delegates[].childId)反查所属部门行,把
|
|
7752
|
+
* 「待指示」落在该行的第三层台账上,并通知负责人。第一层(父会话即计划
|
|
7753
|
+
* 所有者)路径逐字节不变。
|
|
7754
|
+
*/
|
|
7755
|
+
if (!record?.plan || !row) {
|
|
7756
|
+
const leaf = findDelegateLeafContext(childSession)
|
|
7757
|
+
if (leaf) return await escalateDelegateLeaf(agent, leaf, args)
|
|
7758
|
+
if (!record?.plan) {
|
|
7759
|
+
return {
|
|
7760
|
+
ok: false,
|
|
7761
|
+
code: 'NO_PLAN',
|
|
7762
|
+
error: '父会话没有可关联的计划;请在结果块写 status=blocked + question,由主 Agent 处理',
|
|
7763
|
+
}
|
|
6432
7764
|
}
|
|
6433
|
-
}
|
|
6434
|
-
const row = (record.statuses ?? []).find((item: any) => item?.childId === childSession.id)
|
|
6435
|
-
if (!row) {
|
|
6436
7765
|
return {
|
|
6437
7766
|
ok: false,
|
|
6438
7767
|
code: 'NO_SUBTASK',
|
|
@@ -6501,6 +7830,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6501
7830
|
escalatedAt: now,
|
|
6502
7831
|
escalationSeq: revision,
|
|
6503
7832
|
revision,
|
|
7833
|
+
// [T7] C1 白名单:第一层请示=待指示事件,注入一行关键进度。
|
|
7834
|
+
keyProgress: true,
|
|
7835
|
+
title: flattenSubtasks(record.plan).find((entry: any) => entry.subtask?.id === row.subtaskId)?.subtask?.title,
|
|
6504
7836
|
}))
|
|
6505
7837
|
// [2.2.7] 中断即报:请示同样要让用户当下看到「有人卡在哪、等什么决定」,
|
|
6506
7838
|
// 结构化 update 消息是给回放/主 Agent 的,这条纯文本是给用户的。
|
|
@@ -6629,17 +7961,45 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6629
7961
|
/**
|
|
6630
7962
|
* [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
|
|
6631
7963
|
*
|
|
6632
|
-
*
|
|
6633
|
-
*
|
|
7964
|
+
* [T5-channel][契约v1 §3b] 放权为「目标子会话的直接父会话」可调用:根会话
|
|
7965
|
+
* 答复第一层部门行(行为逐字节不变);部门负责人答复自己派出的第三层叶子
|
|
7966
|
+
* (严格 lineage:调用者必须是该部门行的 childId,目标必须登记在本行
|
|
7967
|
+
* delegates 且在调用者的直接子会话 catalog 里)。非直系(跨行、跨层、无关
|
|
7968
|
+
* 会话)一律拒绝。根路径只接受 `closure:'escalated'` 的行;负责人路径按
|
|
7969
|
+
* member/sessionId 指定目标。投递失败时不改状态(不伪造成「已指示」),
|
|
7970
|
+
* 把错误原样交给调用方。
|
|
6634
7971
|
*/
|
|
6635
7972
|
async function instructSubtask(agent: any, args: any, signal?: any, existingRecord?: any) {
|
|
6636
7973
|
const session = agent?.session
|
|
6637
7974
|
if (!session) return { ok: false, code: 'NO_SESSION', error: '只能在会话内下发指示' }
|
|
6638
|
-
|
|
6639
|
-
let record
|
|
6640
|
-
if (
|
|
6641
|
-
|
|
6642
|
-
|
|
7975
|
+
const callerIsRoot = isRootSession(session)
|
|
7976
|
+
let record: any
|
|
7977
|
+
if (callerIsRoot) {
|
|
7978
|
+
record = existingRecord ?? state.records.get(session.id)
|
|
7979
|
+
if (!record?.plan) record = reconstructFromSession(session, args?.planId)
|
|
7980
|
+
record = adoptRequestedPlan(session, record, args?.planId)
|
|
7981
|
+
if (!record?.plan) return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' }
|
|
7982
|
+
} else {
|
|
7983
|
+
/*
|
|
7984
|
+
* [T5-channel][契约v1 §3b] 负责人答复自己的叶子:先沿父链反查根计划,
|
|
7985
|
+
* 再判负责人身份(根记录中 statuses[].childId === session.id 的行)。
|
|
7986
|
+
* 既非根也非登记负责人 ⇒ 维持 NOT_ROOT;subtaskId 可省略(默认自己的
|
|
7987
|
+
* 行),给了必须等于自己的行,否则 UNKNOWN_SUBTASK。目标登记/catalog/
|
|
7988
|
+
* 父链的严格 lineage 在 instructDelegateLeaf 内硬校验。
|
|
7989
|
+
*/
|
|
7990
|
+
record = findAncestorPlanRecord(session)
|
|
7991
|
+
if (!record?.plan) return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' }
|
|
7992
|
+
if (typeof args?.planId === 'string' && args.planId && record.plan.planId !== args.planId) {
|
|
7993
|
+
return { ok: false, code: 'NO_PLAN', error: `指定计划 ${args.planId} 与当前会话关联的计划不一致` }
|
|
7994
|
+
}
|
|
7995
|
+
const headRow = (record.statuses ?? []).find((item: any) => item?.childId === session.id)
|
|
7996
|
+
if (!headRow) return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' }
|
|
7997
|
+
const requested = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : ''
|
|
7998
|
+
if (requested && requested !== String(headRow.subtaskId)) {
|
|
7999
|
+
return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId: requested, error: `未知子任务:${requested}(负责人只能答复自己的部门行 ${String(headRow.subtaskId)})` }
|
|
8000
|
+
}
|
|
8001
|
+
return instructDelegateLeaf(agent, args, signal, record, headRow)
|
|
8002
|
+
}
|
|
6643
8003
|
clearAutoResumeTimer(record, 'manual-instruct')
|
|
6644
8004
|
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : ''
|
|
6645
8005
|
if (!subtaskId) return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' }
|
|
@@ -6749,6 +8109,280 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6749
8109
|
}
|
|
6750
8110
|
}
|
|
6751
8111
|
|
|
8112
|
+
/**
|
|
8113
|
+
* [2.5.6] 沿父链向上(≤3 跳,防环)找到第一个有计划记录的祖先会话。
|
|
8114
|
+
* 负责人 instruct 与叶子 escalate 共用同一父链判据;不信任自报 planId。
|
|
8115
|
+
*/
|
|
8116
|
+
function findAncestorPlanRecord(session: any) {
|
|
8117
|
+
let ancestorId = session?.header?.parentSession
|
|
8118
|
+
for (let hop = 0; hop < 3 && typeof ancestorId === 'string' && ancestorId; hop += 1) {
|
|
8119
|
+
let rec = state.records.get(ancestorId)
|
|
8120
|
+
if (!rec?.plan) {
|
|
8121
|
+
const sess = (ctx as any).sessions?.get?.(ancestorId)
|
|
8122
|
+
if (sess) {
|
|
8123
|
+
try { rec = reconstructFromSession(sess) } catch (error) { pushRecordError({ errors: [] } as any, error) }
|
|
8124
|
+
}
|
|
8125
|
+
}
|
|
8126
|
+
if (rec?.plan) return rec
|
|
8127
|
+
const sess = (ctx as any).sessions?.get?.(ancestorId)
|
|
8128
|
+
ancestorId = sess?.header?.parentSession
|
|
8129
|
+
}
|
|
8130
|
+
return null
|
|
8131
|
+
}
|
|
8132
|
+
|
|
8133
|
+
/**
|
|
8134
|
+
* [T5-channel][契约v1 §3b] 负责人 → 第三层叶子的指示投递(instruct 的叶子分支)。
|
|
8135
|
+
*
|
|
8136
|
+
* 负责人身份与行级 lineage 已在 instructSubtask 校验(调用者 == 部门行
|
|
8137
|
+
* childId);这里按 member/sessionId(至少其一)定位本行 delegates 登记的
|
|
8138
|
+
* 目标,再校验 spawnedChildIds 直接子会话证据+父链双保险。投递复用
|
|
8139
|
+
* ctx.subagents.sendMessage 既有通道(与 follow-up/延期告知同一条),不新建
|
|
8140
|
+
* 队列;写 kind='instruction' 留痕(data.inReplyTo 指向被答复的请示);
|
|
8141
|
+
* 持久化 delegates[i].lastInstruction 并清 escalation;负责人行 closure
|
|
8142
|
+
* 不变。投递失败不改状态(不伪造成「已指示」)。
|
|
8143
|
+
*/
|
|
8144
|
+
async function instructDelegateLeaf(agent: any, args: any, signal: any, record: any, current: any) {
|
|
8145
|
+
const session = agent.session
|
|
8146
|
+
const subtaskId = String(current.subtaskId)
|
|
8147
|
+
const memberName = typeof args?.member === 'string' ? args.member.trim() : ''
|
|
8148
|
+
const targetSessionId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : ''
|
|
8149
|
+
if (!memberName && !targetSessionId) {
|
|
8150
|
+
return { ok: false, code: 'MISSING_TARGET', subtaskId, error: 'member 与 sessionId 至少提供其一:指定要答复的第三层成员' }
|
|
8151
|
+
}
|
|
8152
|
+
const delegates = Array.isArray(current.delegates) ? current.delegates : []
|
|
8153
|
+
const target = memberName
|
|
8154
|
+
? delegates.find((item: any) => item?.member === memberName)
|
|
8155
|
+
: delegates.find((item: any) => item?.childId === targetSessionId)
|
|
8156
|
+
if (!target) {
|
|
8157
|
+
return memberName
|
|
8158
|
+
? { ok: false, code: 'UNKNOWN_MEMBER', subtaskId, member: memberName, error: `成员 ${memberName} 未登记在本行 delegates[]` }
|
|
8159
|
+
: { ok: false, code: 'NOT_DELEGATE', subtaskId, sessionId: targetSessionId, error: `${targetSessionId} 不是本行登记的第三层成员(跨部门/未登记目标一律拒绝)` }
|
|
8160
|
+
}
|
|
8161
|
+
if (memberName && targetSessionId && target.childId !== targetSessionId) {
|
|
8162
|
+
return { ok: false, code: 'NOT_DELEGATE', subtaskId, error: 'member 与 sessionId 指向不同成员,拒绝投递' }
|
|
8163
|
+
}
|
|
8164
|
+
const childId = typeof target.childId === 'string' ? target.childId : ''
|
|
8165
|
+
if (!childId) {
|
|
8166
|
+
return { ok: false, code: 'NOT_DELEGATE', subtaskId, member: target.member, error: '该成员没有登记子会话 childId,无法投递指示' }
|
|
8167
|
+
}
|
|
8168
|
+
if (!spawnedChildIds(session).has(childId)) {
|
|
8169
|
+
return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: `${childId} 不是本会话的直接子会话(父会话 catalog 未登记),拒绝投递` }
|
|
8170
|
+
}
|
|
8171
|
+
const targetSession = (ctx as any).sessions?.get?.(childId)
|
|
8172
|
+
if (targetSession?.header?.parentSession && targetSession.header.parentSession !== session.id) {
|
|
8173
|
+
return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: '严格血缘校验失败:目标子会话的直接父会话不是调用者,拒绝投递' }
|
|
8174
|
+
}
|
|
8175
|
+
const instruction = truncate(String(args?.instruction ?? args?.text ?? '').trim(), MAX_INSTRUCTION_CHARS)
|
|
8176
|
+
if (!instruction) return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要成员执行的决定' }
|
|
8177
|
+
const service: any = (ctx as any).subagents
|
|
8178
|
+
if (!service || typeof service.sendMessage !== 'function') {
|
|
8179
|
+
return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId, error: '当前部署没有可用的 subagent 服务,无法投递指示' }
|
|
8180
|
+
}
|
|
8181
|
+
// inReplyTo(可选):从留痕回放找该成员最近一条请示消息 id;读失败不阻断投递。
|
|
8182
|
+
let inReplyTo = ''
|
|
8183
|
+
try {
|
|
8184
|
+
const prior = readDeptMessages(record.plan.planId, { kind: 'escalation' })
|
|
8185
|
+
if (prior.ok) {
|
|
8186
|
+
const match = [...prior.messages].reverse().find((m: any) => m.from?.sessionId === childId && m.subtaskId === subtaskId)
|
|
8187
|
+
inReplyTo = match?.id ?? ''
|
|
8188
|
+
}
|
|
8189
|
+
} catch { /* 留痕读失败不阻断投递;inReplyTo 可选 */ }
|
|
8190
|
+
const body = truncate([
|
|
8191
|
+
'【部门负责人指示(对应你此前提交的请示)】',
|
|
8192
|
+
instruction,
|
|
8193
|
+
'',
|
|
8194
|
+
'请按上述指示继续原任务。若仍受阻,先调用 dsh_workplan_escalate 再次上报,然后停止推进等待指示;不要自行猜测未被回答的部分。',
|
|
8195
|
+
].join('\n'), 4000)
|
|
8196
|
+
const startedAt = Date.now()
|
|
8197
|
+
let messageId = ''
|
|
8198
|
+
try {
|
|
8199
|
+
messageId = String(await service.sendMessage(agent, childId, [{ type: 'text', text: body }], { signal }) ?? '')
|
|
8200
|
+
} catch (error: any) {
|
|
8201
|
+
const errorText = truncate(error instanceof Error ? error.message : String(error), 500)
|
|
8202
|
+
const failedJournal = channelJournal({
|
|
8203
|
+
planId: record.plan.planId,
|
|
8204
|
+
subtaskId,
|
|
8205
|
+
kind: 'instruction',
|
|
8206
|
+
from: { sessionId: session.id, role: 'head' },
|
|
8207
|
+
to: { sessionId: childId, role: 'expert', member: target.member },
|
|
8208
|
+
body,
|
|
8209
|
+
...(inReplyTo ? { data: { inReplyTo } } : {}),
|
|
8210
|
+
delivery: { status: 'failed', code: 'DELIVERY_FAILED', error: errorText, latencyMs: Date.now() - startedAt },
|
|
8211
|
+
})
|
|
8212
|
+
return {
|
|
8213
|
+
ok: false,
|
|
8214
|
+
code: 'DELIVERY_FAILED',
|
|
8215
|
+
subtaskId,
|
|
8216
|
+
member: target.member,
|
|
8217
|
+
sessionId: childId,
|
|
8218
|
+
error: errorText,
|
|
8219
|
+
hint: '状态未改变,该成员仍是待指示;可重试投递。',
|
|
8220
|
+
...(failedJournal.result.ok ? {} : { journal: { ok: false, code: failedJournal.result.code, error: failedJournal.result.error } }),
|
|
8221
|
+
}
|
|
8222
|
+
}
|
|
8223
|
+
const latencyMs = Date.now() - startedAt
|
|
8224
|
+
const now = Date.now()
|
|
8225
|
+
const journal = channelJournal({
|
|
8226
|
+
planId: record.plan.planId,
|
|
8227
|
+
subtaskId,
|
|
8228
|
+
kind: 'instruction',
|
|
8229
|
+
from: { sessionId: session.id, role: 'head' },
|
|
8230
|
+
to: { sessionId: childId, role: 'expert', member: target.member },
|
|
8231
|
+
body,
|
|
8232
|
+
...(inReplyTo ? { data: { inReplyTo } } : {}),
|
|
8233
|
+
delivery: { status: 'sent', ...(messageId ? { messageId } : {}), latencyMs },
|
|
8234
|
+
})
|
|
8235
|
+
const revision = Number(current.revision ?? 0) + 1
|
|
8236
|
+
const delegatesList = (Array.isArray(current.delegates) ? current.delegates : []).map((item: any) => (item?.childId === childId
|
|
8237
|
+
? {
|
|
8238
|
+
...item,
|
|
8239
|
+
status: 'running',
|
|
8240
|
+
closure: 'instructed',
|
|
8241
|
+
lastInstruction: { text: instruction, at: now, ...(messageId ? { messageId } : {}), delivery: 'sent' },
|
|
8242
|
+
escalation: undefined,
|
|
8243
|
+
instructionSeq: revision,
|
|
8244
|
+
instructionOverdue: false,
|
|
8245
|
+
ackedAt: null,
|
|
8246
|
+
blockedKind: null,
|
|
8247
|
+
error: null,
|
|
8248
|
+
finishedAt: null,
|
|
8249
|
+
}
|
|
8250
|
+
: item))
|
|
8251
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { delegates: delegatesList, revision, updatedBy: 'agent' })
|
|
8252
|
+
record.updatedAt = now
|
|
8253
|
+
try {
|
|
8254
|
+
const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
8255
|
+
const update = buildUpdateMessage({
|
|
8256
|
+
planId: record.plan.planId,
|
|
8257
|
+
subtaskId,
|
|
8258
|
+
status: written?.status ?? current.status,
|
|
8259
|
+
delegates: written?.delegates ?? delegatesList,
|
|
8260
|
+
revision,
|
|
8261
|
+
note: `负责人已向第三层成员 ${target.member} 下发指示`,
|
|
8262
|
+
})
|
|
8263
|
+
// durable 回放挂在计划所有者(根会话)上;负责人会话留一份供其回放核对。
|
|
8264
|
+
const ownerSession = (ctx as any).sessions?.get?.(record.plan.sessionId)
|
|
8265
|
+
appendUserMessage(ownerSession, update)
|
|
8266
|
+
if (ownerSession !== session) appendUserMessage(session, update)
|
|
8267
|
+
} catch (error) {
|
|
8268
|
+
pushRecordError(record, error)
|
|
8269
|
+
}
|
|
8270
|
+
scheduleDelegateInstructionAck(record, subtaskId, target.member, childId, revision)
|
|
8271
|
+
return {
|
|
8272
|
+
ok: true,
|
|
8273
|
+
planId: record.plan.planId,
|
|
8274
|
+
subtaskId,
|
|
8275
|
+
member: target.member,
|
|
8276
|
+
sessionId: childId,
|
|
8277
|
+
messageId,
|
|
8278
|
+
latencyMs,
|
|
8279
|
+
revision,
|
|
8280
|
+
...(journal.result.ok ? {} : { journal: { ok: false, code: journal.result.code, error: journal.result.error } }),
|
|
8281
|
+
hint: '指示已投递给第三层成员,该成员已变为「已收到指示」。它会开启新一轮;收齐结论前仍不得写最终结果块。',
|
|
8282
|
+
}
|
|
8283
|
+
}
|
|
8284
|
+
|
|
8285
|
+
/**
|
|
8286
|
+
* [2.5.6] 叶子指示回执:与 scheduleInstructionAck 同一套三观察点语义
|
|
8287
|
+
* (轮询 seq 增长=acknowledged;60s 无增长=instructionOverdue;180s 无
|
|
8288
|
+
* 增长=blocked/no-ack),只是读写目标从部门行换成行内 delegates 成员条目。
|
|
8289
|
+
* 独立实现而不改动根会话共用的 scheduleInstructionAck,保证第一层零回归。
|
|
8290
|
+
*/
|
|
8291
|
+
function scheduleDelegateInstructionAck(record: any, subtaskId: string, member: string, childId: string, revision: number) {
|
|
8292
|
+
const rowOf = () => record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
8293
|
+
const entryOf = () => {
|
|
8294
|
+
const row = rowOf()
|
|
8295
|
+
return (Array.isArray(row?.delegates) ? row.delegates : []).find((item: any) => item?.member === member) ?? null
|
|
8296
|
+
}
|
|
8297
|
+
const patchEntry = (patch: any) => {
|
|
8298
|
+
const row = rowOf()
|
|
8299
|
+
if (!row) return null
|
|
8300
|
+
const list = (Array.isArray(row.delegates) ? row.delegates : [])
|
|
8301
|
+
.map((item: any) => (item?.member === member ? { ...item, ...patch } : item))
|
|
8302
|
+
const nextRevision = Number(row.revision ?? 0) + 1
|
|
8303
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision: nextRevision, updatedBy: 'system' })
|
|
8304
|
+
record.updatedAt = Date.now()
|
|
8305
|
+
return entryOf()
|
|
8306
|
+
}
|
|
8307
|
+
const readSeq = () => {
|
|
8308
|
+
try {
|
|
8309
|
+
const seq = Number((ctx as any).sessions?.get?.(childId)?.seq)
|
|
8310
|
+
return Number.isFinite(seq) ? seq : undefined
|
|
8311
|
+
} catch {
|
|
8312
|
+
return undefined
|
|
8313
|
+
}
|
|
8314
|
+
}
|
|
8315
|
+
const baseline = readSeq()
|
|
8316
|
+
let stopped = false
|
|
8317
|
+
const timers: Array<ReturnType<typeof setTimeout> | ReturnType<typeof setInterval>> = []
|
|
8318
|
+
const stop = () => {
|
|
8319
|
+
if (stopped) return
|
|
8320
|
+
stopped = true
|
|
8321
|
+
for (const timer of timers) {
|
|
8322
|
+
clearTimeout(timer as any)
|
|
8323
|
+
clearInterval(timer as any)
|
|
8324
|
+
}
|
|
8325
|
+
}
|
|
8326
|
+
const sameAttempt = (entry: any) => {
|
|
8327
|
+
if (stopped) return false
|
|
8328
|
+
if (!entry || entry.closure !== 'instructed') return false
|
|
8329
|
+
return Number(entry.instructionSeq ?? 0) === Number(revision)
|
|
8330
|
+
}
|
|
8331
|
+
const unchanged = (entry: any) => {
|
|
8332
|
+
if (!sameAttempt(entry)) return false
|
|
8333
|
+
const seq = readSeq()
|
|
8334
|
+
if (seq === undefined || baseline === undefined) return true
|
|
8335
|
+
return seq <= baseline
|
|
8336
|
+
}
|
|
8337
|
+
const poll = setInterval(() => {
|
|
8338
|
+
const entry = entryOf()
|
|
8339
|
+
if (!sameAttempt(entry)) { stop(); return }
|
|
8340
|
+
const seq = readSeq()
|
|
8341
|
+
if (seq === undefined || baseline === undefined || seq <= baseline) return
|
|
8342
|
+
try {
|
|
8343
|
+
patchEntry({
|
|
8344
|
+
closure: 'acknowledged',
|
|
8345
|
+
ackedAt: Date.now(),
|
|
8346
|
+
instructionOverdue: false,
|
|
8347
|
+
})
|
|
8348
|
+
} catch {
|
|
8349
|
+
return
|
|
8350
|
+
}
|
|
8351
|
+
stop()
|
|
8352
|
+
}, INSTRUCTION_POLL_MS)
|
|
8353
|
+
poll.unref?.()
|
|
8354
|
+
timers.push(poll)
|
|
8355
|
+
const notice = setTimeout(() => {
|
|
8356
|
+
if (!unchanged(entryOf())) return
|
|
8357
|
+
try { patchEntry({ instructionOverdue: true }) } catch { /* entry moved on */ }
|
|
8358
|
+
}, INSTRUCTION_ACK_NOTICE_MS)
|
|
8359
|
+
notice.unref?.()
|
|
8360
|
+
timers.push(notice)
|
|
8361
|
+
const deadline = setTimeout(() => {
|
|
8362
|
+
if (!unchanged(entryOf())) { stop(); return }
|
|
8363
|
+
const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000)
|
|
8364
|
+
const message = `指示下发后 ${seconds}s 成员会话仍无任何新事件(no-ack):指示没有被执行`
|
|
8365
|
+
try {
|
|
8366
|
+
patchEntry({
|
|
8367
|
+
status: 'blocked',
|
|
8368
|
+
closure: 'blocked',
|
|
8369
|
+
blockedKind: 'no-ack',
|
|
8370
|
+
progress: 100,
|
|
8371
|
+
error: message,
|
|
8372
|
+
summary: `未完成:${message}`,
|
|
8373
|
+
finishedAt: Date.now(),
|
|
8374
|
+
})
|
|
8375
|
+
// [2.5.6] 与第一层 scheduleInstructionAck 对齐:no-ack 收束必须写入
|
|
8376
|
+
// 错误台账(主行 recordSubtaskError 同款),不留「静默 blocked」。
|
|
8377
|
+
recordSubtaskError(record, subtaskId, message, { timedOut: false })
|
|
8378
|
+
} catch {
|
|
8379
|
+
// Entry already left instructed.
|
|
8380
|
+
}
|
|
8381
|
+
stop()
|
|
8382
|
+
}, INSTRUCTION_ACK_DEADLINE_MS)
|
|
8383
|
+
timers.push(deadline)
|
|
8384
|
+
}
|
|
8385
|
+
|
|
6752
8386
|
/**
|
|
6753
8387
|
* [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
|
|
6754
8388
|
*
|
|
@@ -6812,75 +8446,979 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6812
8446
|
if (index < 0) {
|
|
6813
8447
|
return {
|
|
6814
8448
|
ok: false,
|
|
6815
|
-
code: wanted ? 'UNKNOWN_HANDOFF' : 'NO_OPEN_HANDOFF',
|
|
6816
|
-
subtaskId,
|
|
6817
|
-
error: wanted ? `未知跨部门需求:${wanted}` : '该行没有待处理的跨部门需求',
|
|
8449
|
+
code: wanted ? 'UNKNOWN_HANDOFF' : 'NO_OPEN_HANDOFF',
|
|
8450
|
+
subtaskId,
|
|
8451
|
+
error: wanted ? `未知跨部门需求:${wanted}` : '该行没有待处理的跨部门需求',
|
|
8452
|
+
}
|
|
8453
|
+
}
|
|
8454
|
+
const handoff = handoffs[index]
|
|
8455
|
+
if (action === 'assign') {
|
|
8456
|
+
const department = typeof args?.department === 'string' ? args.department.trim() : ''
|
|
8457
|
+
if (!DEPARTMENTS[department as keyof typeof DEPARTMENTS]) {
|
|
8458
|
+
return { ok: false, code: 'INVALID_DEPARTMENT', error: `department 必须是 ${DEPARTMENT_IDS.join(' / ')} 之一` }
|
|
8459
|
+
}
|
|
8460
|
+
handoffs[index] = { ...handoff, department, status: 'routed', updatedAt: Date.now(), by: 'agent' }
|
|
8461
|
+
} else if (action === 'resolve') {
|
|
8462
|
+
const response = truncate(String(args?.response ?? '').trim(), MAX_HANDOFF_RESPONSE_CHARS)
|
|
8463
|
+
if (!response) return { ok: false, code: 'INVALID_RESPONSE', error: 'resolve 必须写清答复或已由哪项产物满足该需求' }
|
|
8464
|
+
handoffs[index] = { ...handoff, status: 'answered', response, updatedAt: Date.now(), by: 'agent' }
|
|
8465
|
+
} else {
|
|
8466
|
+
handoffs[index] = { ...handoff, status: 'closed', response: handoff.response ?? null, updatedAt: Date.now(), by: 'agent' }
|
|
8467
|
+
}
|
|
8468
|
+
const revision = Number(row.revision ?? 0) + 1
|
|
8469
|
+
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
8470
|
+
handoffs,
|
|
8471
|
+
revision,
|
|
8472
|
+
updatedBy: 'agent',
|
|
8473
|
+
})
|
|
8474
|
+
record.updatedAt = Date.now()
|
|
8475
|
+
try {
|
|
8476
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
8477
|
+
planId: record.plan.planId,
|
|
8478
|
+
subtaskId,
|
|
8479
|
+
status: row.status,
|
|
8480
|
+
handoffs,
|
|
8481
|
+
revision,
|
|
8482
|
+
}))
|
|
8483
|
+
} catch (error) {
|
|
8484
|
+
pushRecordError(record, error)
|
|
8485
|
+
}
|
|
8486
|
+
/*
|
|
8487
|
+
* [1.11.0] 答复必须真的送到还在等它的子会话(用户 m00687)。
|
|
8488
|
+
*
|
|
8489
|
+
* 如果提出需求的行正处于「待指示」,它此刻停在那里等主 Agent:只把
|
|
8490
|
+
* handoff 写成 answered、不发指示,子会话永远不会继续,需求闭环只闭在
|
|
8491
|
+
* 计划表里。这里复用 instructSubtask 的唯一投递/回执链路(写 instructed、
|
|
8492
|
+
* 60s/180s 回执、下次激活注入),不另造第二条消息通道。
|
|
8493
|
+
* 投递失败不回滚 handoff:答复本身是真的,失败原因如实返回给主 Agent。
|
|
8494
|
+
*/
|
|
8495
|
+
let instruction: any = null
|
|
8496
|
+
if (action === 'resolve' && row.closure === 'escalated' && handoffs[index]?.response) {
|
|
8497
|
+
const answer = handoffs[index]
|
|
8498
|
+
instruction = await instructSubtask(agent, {
|
|
8499
|
+
planId: record.plan.planId,
|
|
8500
|
+
subtaskId,
|
|
8501
|
+
instruction: `跨部门需求 ${answer.id} 已答复${answer.department ? `(${answer.department})` : ''}:${answer.response}。按此答复继续原任务。`,
|
|
8502
|
+
}, signal)
|
|
8503
|
+
}
|
|
8504
|
+
const finalReadiness = readinessOf(record, derivePlanSnapshot(record.statuses))
|
|
8505
|
+
return {
|
|
8506
|
+
ok: true,
|
|
8507
|
+
planId: record.plan.planId,
|
|
8508
|
+
subtaskId,
|
|
8509
|
+
handoff: record.statuses.find((item: any) => item?.subtaskId === subtaskId)?.handoffs?.[index] ?? null,
|
|
8510
|
+
deliveryReady: finalReadiness.ready,
|
|
8511
|
+
deliveryBlockers: finalReadiness.blockers,
|
|
8512
|
+
...(instruction ? { instruction } : {}),
|
|
8513
|
+
hint: action === 'assign'
|
|
8514
|
+
? '已登记责任部门。插件没有常驻部门代理:这次指派不会自动产生工作,请用 dsh_workplan_replan(action=add) 建一个该部门的子任务,或由你直接完成,再用 action=resolve 写入答复或产物引用;否则交付仍被拦住。'
|
|
8515
|
+
: instruction && instruction.ok !== true
|
|
8516
|
+
? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
|
|
8517
|
+
: '已记录处置结果;交付阻塞按最新状态重新计算。',
|
|
8518
|
+
}
|
|
8519
|
+
}
|
|
8520
|
+
|
|
8521
|
+
/**
|
|
8522
|
+
* [2.3.9][T4b] 第三层派发(用户强制要求 4/5):部门负责人专用工具。
|
|
8523
|
+
*
|
|
8524
|
+
* 层级模型:主 Agent(根会话, depth 0) → 部门负责人子会话(depth 1) →
|
|
8525
|
+
* 顶尖专家/组员子会话(depth 2, 叶子层)。三道硬边界:
|
|
8526
|
+
* 1. 调用者必须是计划内某行的部门负责人子会话(childId 反查行);
|
|
8527
|
+
* 根会话被拒(用 dsh_workplan_dispatch),第三层成员也被拒——
|
|
8528
|
+
* 其父会话是部门会话、没有计划记录,NO_PLAN/NO_SUBTASK 即叶子层禁令;
|
|
8529
|
+
* 2. 梳理门禁:dispatch 前必须先 review 提交「全面梳理产物 + 分工表」
|
|
8530
|
+
* (planDelegations 唯一判据,durable 回放后依然生效);
|
|
8531
|
+
* 3. 深度:成员 spawn 传 maxDepth:2,第四层(depth 3)由宿主
|
|
8532
|
+
* SubagentDepthError 硬拒(resolveChildDepth 绝对上限)。
|
|
8533
|
+
*
|
|
8534
|
+
* 每位下级的推理等级按其任务复杂度由负责人配置,经 planDelegations 按
|
|
8535
|
+
* 当前模型家族合法集合(qwen→low/medium/xhigh;非qwen→low/high/max)
|
|
8536
|
+
* 钳制并留痕(delegates[].requested/effort 对),随 spawn 的 agentOptions
|
|
8537
|
+
* 下发且全生命周期生效(要求 5)。
|
|
8538
|
+
*/
|
|
8539
|
+
/**
|
|
8540
|
+
* [2.5.0][自配档] 叶子自配推理等级(用户要求 2 新口径):第三层专家/组员专用。
|
|
8541
|
+
* 先配置后开工——phase-0 以 low 启动,叶子评估自己任务复杂度后经此提交自配档;
|
|
8542
|
+
* 平台登记(五档白名单 + 家族钳制留痕 + delegates[].selfEffort + delegateSelfEfforts
|
|
8543
|
+
* 持久化回放)后立即中断 phase-0 回合,并以自配档接续 phase-1。宿主契约:
|
|
8544
|
+
* reasoningEffort 在子会话创建时解析(resolveChildAgentOptions),同会话换档不可行
|
|
8545
|
+
* ⇒ 接续 = interruptByParent(continuable) + 新激活携带 phase-0 产物与完整任务书,
|
|
8546
|
+
* childId 台账更新,旧结算回调按旧 childId 自动失配。接续失败重试 1 次仍败 ⇒
|
|
8547
|
+
* 明确 SELF_EFFORT_CONTINUATION_FAILED,禁止静默降档。
|
|
8548
|
+
*/
|
|
8549
|
+
async function selfEffortTool(agent: any, args: any, signal?: any) {
|
|
8550
|
+
const childSession = agent?.session
|
|
8551
|
+
if (!childSession?.id) return { ok: false, code: 'NO_SESSION', error: 'self_effort 只能在会话内使用' }
|
|
8552
|
+
const leaderId = childSession.header?.parentSession
|
|
8553
|
+
const leaderSession = leaderId ? (ctx as any).sessions?.get?.(leaderId) : null
|
|
8554
|
+
const rootId = leaderSession?.header?.parentSession
|
|
8555
|
+
let record = rootId ? state.records.get(rootId) : undefined
|
|
8556
|
+
if (!record?.plan && rootId) {
|
|
8557
|
+
const rootSession = (ctx as any).sessions?.get?.(rootId)
|
|
8558
|
+
if (rootSession) {
|
|
8559
|
+
try { record = reconstructFromSession(rootSession) } catch (error) { pushRecordError({ errors: [] } as any, error) }
|
|
8560
|
+
}
|
|
8561
|
+
}
|
|
8562
|
+
let row = (record?.statuses ?? []).find((item: any) => Array.isArray(item?.delegates) && item.delegates.some((d: any) => d?.childId === childSession.id))
|
|
8563
|
+
/*
|
|
8564
|
+
* [T11] 血缘懒加载回退(治本,缺陷①):重启早期负责人会话可能尚未载入
|
|
8565
|
+
* ctx.sessions,rootId 取不到会在旧逻辑里被误报 SELF_EFFORT_NOT_LEAF。
|
|
8566
|
+
* 此处不直接拒绝,改按 childId 扫描既有台账定位归属计划(与 rootId 路径
|
|
8567
|
+
* reconstructFromSession 回退同范式)。只有真正未被任何部门行登记为叶子的
|
|
8568
|
+
* 会话(根会话/负责人自调用)才命中下方 NOT_LEAF 拒绝——安全边界不变。
|
|
8569
|
+
*/
|
|
8570
|
+
if (!record?.plan || !row) {
|
|
8571
|
+
for (const candidate of state.records.values()) {
|
|
8572
|
+
const candidateRow = (candidate?.statuses ?? []).find((item: any) => Array.isArray(item?.delegates) && item.delegates.some((d: any) => d?.childId === childSession.id))
|
|
8573
|
+
if (candidate?.plan && candidateRow) { record = candidate; row = candidateRow; break }
|
|
8574
|
+
}
|
|
8575
|
+
}
|
|
8576
|
+
if (!record?.plan || !row) {
|
|
8577
|
+
return { ok: false, code: 'SELF_EFFORT_NOT_LEAF', error: '找不到与本子会话关联的第三层台账(childId 未登记):self_effort 仅限部门负责人派出的全球顶尖专家叶子会话调用。' }
|
|
8578
|
+
}
|
|
8579
|
+
const member = row.delegates.find((d: any) => d?.childId === childSession.id)
|
|
8580
|
+
if (member.status === 'done') return { ok: false, code: 'ALREADY_DONE', error: '该成员已结算,不能再自配等级。' }
|
|
8581
|
+
const FIVE = ['low', 'medium', 'high', 'xhigh', 'max']
|
|
8582
|
+
const raw = args?.reasoningEffort
|
|
8583
|
+
if (typeof raw !== 'string' || !FIVE.includes(raw)) {
|
|
8584
|
+
return { ok: false, code: 'SELF_EFFORT_INVALID', error: `reasoningEffort "${String(raw)}" 非法:必须是 low / medium / high / xhigh / max 之一(按你自己任务复杂度自配:轻度=low;qwen 中等=medium、非 qwen 中等=high;qwen 非常复杂=xhigh、非 qwen 非常复杂=max)。` }
|
|
8585
|
+
}
|
|
8586
|
+
const rationale = String(args?.complexityRationale ?? '').trim()
|
|
8587
|
+
if (!rationale) return { ok: false, code: 'SELF_EFFORT_RATIONALE_MISSING', error: 'complexityRationale 必填:写清你分到的单项任务为何是该复杂度档(事实/依赖/验证难度)。' }
|
|
8588
|
+
/*
|
|
8589
|
+
* [2.5.2] 叶子执行前两轮深度思考硬门禁(用户 2026-11-12 要求:四角色在
|
|
8590
|
+
* 开始具体执行前都被机制强制先思考后执行,且全程少走弯路)。
|
|
8591
|
+
*
|
|
8592
|
+
* 此前专家/组员只有任务书注入 + 结算时 validatePhaseEvidence——思考产物
|
|
8593
|
+
* 在「执行后」才被迫补齐,不满足「先思考后执行」。现在把 phase-0 提交
|
|
8594
|
+
* 升级为原子对:self_effort 必须同时携带合格 deepThink(与主 Agent/负责人
|
|
8595
|
+
* 同一 validateMainDeepThink 判据、同一 40/40/20 字口径),缺交/不合格
|
|
8596
|
+
* 硬拒(DEEP_THINK_MISSING / DEEP_THINK_INCOMPLETE),不登记、不接续;
|
|
8597
|
+
* 两者齐全才登记并以自配档接续 phase-1——正式执行只能发生在两轮思考
|
|
8598
|
+
* 登记之后,且必须按第二轮理清的方法、流程、步骤执行(少走弯路)。
|
|
8599
|
+
* 已登记自配档的旧叶子重派直接 phase-1(零迁移),其结算门禁仍验产物。
|
|
8600
|
+
*/
|
|
8601
|
+
const leafDeepThinkCheck = validateMainDeepThink(args?.deepThink)
|
|
8602
|
+
if (!leafDeepThinkCheck.ok) {
|
|
8603
|
+
const missing = leafDeepThinkCheck.code === 'MAIN_DEEP_THINK_MISSING'
|
|
8604
|
+
return {
|
|
8605
|
+
ok: false,
|
|
8606
|
+
code: missing ? 'DEEP_THINK_MISSING' : 'DEEP_THINK_INCOMPLETE',
|
|
8607
|
+
subtaskId: String(row.subtaskId),
|
|
8608
|
+
member: member.member,
|
|
8609
|
+
error: `执行前两轮深度思考产物${missing ? '缺失' : '不合格'}:全球顶尖专家开始执行自己的任务前,必须先全面、全盘、深入梳理、研究、思考自己的任务(第一轮),再基于第一轮完成好的所有结果再全面、全盘、深入地开展梳理、研究和思考,理清具体如何一步步以最高效率、少走弯路、完美完成自己任务的方法、流程和步骤(第二轮),最后才按此执行。请在 self_effort 一并携带 deepThink={ problemAnalysis[], approach[], approachBasis[] }。${leafDeepThinkCheck.error ?? ''}`,
|
|
8610
|
+
}
|
|
8611
|
+
}
|
|
8612
|
+
const leafDeepThink = leafDeepThinkCheck.deepThink!
|
|
8613
|
+
/*
|
|
8614
|
+
* [T6][D9] 开工前预估硬门禁(T6 冻结契约 §2,校验顺序最后一项:
|
|
8615
|
+
* reasoningEffort→complexityRationale→deepThink→timeNotice)。timeNotice=
|
|
8616
|
+
* { declaredMinutes: 正整数分钟(1..10080), reason?: ≤300 }。缺交=ESTIMATE_MISSING;
|
|
8617
|
+
* 非对象/非整数/越界=ESTIMATE_INVALID;error 必须含 D9 原话+形状说明。拒绝一律
|
|
8618
|
+
* 不登记、不投递、不接续(A1)。预估登记后经 T5 通道送达部门负责人(§4)才准
|
|
8619
|
+
* 接续 phase-1——「没有告知部门负责人预估时间,先拦截」。
|
|
8620
|
+
*/
|
|
8621
|
+
const D9_ESTIMATE = '你必须自己预估时间,汇报给对应负责人后,才可以重试或继续执行'
|
|
8622
|
+
const rawTimeNotice = args?.timeNotice
|
|
8623
|
+
if (rawTimeNotice === undefined) {
|
|
8624
|
+
return {
|
|
8625
|
+
ok: false,
|
|
8626
|
+
code: 'ESTIMATE_MISSING',
|
|
8627
|
+
subtaskId: String(row.subtaskId),
|
|
8628
|
+
member: member.member,
|
|
8629
|
+
error: `开工前预估缺失:${D9_ESTIMATE}。请在 self_effort 一并携带 timeNotice={ declaredMinutes: 正整数分钟(1..10080), reason?: 可选理由(≤300 字符) }。`,
|
|
8630
|
+
}
|
|
8631
|
+
}
|
|
8632
|
+
if (!rawTimeNotice || typeof rawTimeNotice !== 'object' || Array.isArray(rawTimeNotice)) {
|
|
8633
|
+
return {
|
|
8634
|
+
ok: false,
|
|
8635
|
+
code: 'ESTIMATE_INVALID',
|
|
8636
|
+
subtaskId: String(row.subtaskId),
|
|
8637
|
+
member: member.member,
|
|
8638
|
+
error: `开工前预估形状非法:timeNotice 必须是对象 { declaredMinutes: 正整数分钟(1..10080), reason? },现值 ${JSON.stringify(rawTimeNotice) ?? String(rawTimeNotice)}。${D9_ESTIMATE}。`,
|
|
8639
|
+
}
|
|
8640
|
+
}
|
|
8641
|
+
const rawMinutes = (rawTimeNotice as any).declaredMinutes
|
|
8642
|
+
if (!Number.isInteger(rawMinutes) || rawMinutes < 1 || rawMinutes > 10080) {
|
|
8643
|
+
return {
|
|
8644
|
+
ok: false,
|
|
8645
|
+
code: 'ESTIMATE_INVALID',
|
|
8646
|
+
subtaskId: String(row.subtaskId),
|
|
8647
|
+
member: member.member,
|
|
8648
|
+
error: `开工前预估非法:declaredMinutes 必须是正整数分钟(Number.isInteger 且 1..10080),现值 ${JSON.stringify(rawMinutes) ?? String(rawMinutes)}。${D9_ESTIMATE}。`,
|
|
8649
|
+
}
|
|
8650
|
+
}
|
|
8651
|
+
const rawEstimateReason = (rawTimeNotice as any).reason
|
|
8652
|
+
if (rawEstimateReason !== undefined && typeof rawEstimateReason !== 'string') {
|
|
8653
|
+
return {
|
|
8654
|
+
ok: false,
|
|
8655
|
+
code: 'ESTIMATE_INVALID',
|
|
8656
|
+
subtaskId: String(row.subtaskId),
|
|
8657
|
+
member: member.member,
|
|
8658
|
+
error: `开工前预估非法:reason 可选但必须是字符串(trim 后 ≤300 字符),现值类型 ${typeof rawEstimateReason}。${D9_ESTIMATE}。`,
|
|
8659
|
+
}
|
|
8660
|
+
}
|
|
8661
|
+
const estimateReason = typeof rawEstimateReason === 'string' && rawEstimateReason.trim() ? truncate(rawEstimateReason.trim(), 300) : ''
|
|
8662
|
+
const modelSelection = resolveModelSelection(ctx, { agent })
|
|
8663
|
+
const model = typeof modelSelection?.model === 'string' && modelSelection.model.trim() ? modelSelection.model.trim() : null
|
|
8664
|
+
const correction = correctEffortForModel(raw, model)
|
|
8665
|
+
const selfEffort = correction.effort
|
|
8666
|
+
if (correction.adjusted) {
|
|
8667
|
+
console.warn('[dsh-workplan] delegate self-effort corrected by LLM family rules:', JSON.stringify({ member: member.member, model, requested: raw, corrected: selfEffort, reason: correction.reason }))
|
|
8668
|
+
}
|
|
8669
|
+
const subtaskId = String(row.subtaskId)
|
|
8670
|
+
const rootSession = (ctx as any).sessions?.get?.(rootId)
|
|
8671
|
+
const persistSelf = (patch: any) => {
|
|
8672
|
+
const current = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
8673
|
+
const revision = Number(current?.revision ?? 0) + 1
|
|
8674
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { ...patch, revision, updatedBy: 'child' })
|
|
8675
|
+
record.updatedAt = Date.now()
|
|
8676
|
+
const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
8677
|
+
try {
|
|
8678
|
+
appendUserMessage(rootSession, buildUpdateMessage({
|
|
8679
|
+
planId: record.plan.planId,
|
|
8680
|
+
subtaskId,
|
|
8681
|
+
status: written?.status ?? row.status,
|
|
8682
|
+
...(patch.delegates === undefined ? {} : { delegates: written?.delegates }),
|
|
8683
|
+
...(patch.delegateSelfEfforts === undefined ? {} : { delegateSelfEfforts: written?.delegateSelfEfforts }),
|
|
8684
|
+
...(patch.delegateDeepThinks === undefined ? {} : { delegateDeepThinks: written?.delegateDeepThinks }),
|
|
8685
|
+
// [T6][契约v1 §3] 预估台账随 durable workplan-update 回放(重启不丢)。
|
|
8686
|
+
...(patch.delegateEstimates === undefined ? {} : { delegateEstimates: written?.delegateEstimates }),
|
|
8687
|
+
revision: written?.revision ?? revision,
|
|
8688
|
+
}))
|
|
8689
|
+
} catch (error) { pushRecordError(record, error) }
|
|
8690
|
+
return written
|
|
8691
|
+
}
|
|
8692
|
+
const currentRow = () => record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
8693
|
+
// [T6][契约v1 §4] 预估读档(幂等判据):已 sent ⇒ 不重复投递;failed/缺失 ⇒
|
|
8694
|
+
// 本次投递。读侧消毒与 plan.ts sanitizeDelegateEstimate 同口径(正整数分钟才算已登记)。
|
|
8695
|
+
const priorEstimate = sanitizeLeafEstimate((currentRow()?.delegateEstimates as any)?.[member.member])
|
|
8696
|
+
?? sanitizeLeafEstimate((currentRow()?.delegates ?? []).find((d: any) => d?.childId === childSession.id)?.estimate)
|
|
8697
|
+
const estimateAlreadySent = priorEstimate?.delivery === 'sent'
|
|
8698
|
+
const estimateDraft: { declaredMinutes: number; reason?: string; at: number; messageId?: string; delivery: 'sent' | 'failed' } = estimateAlreadySent
|
|
8699
|
+
? priorEstimate!
|
|
8700
|
+
: { declaredMinutes: rawMinutes, ...(estimateReason ? { reason: estimateReason } : {}), at: Date.now(), delivery: 'failed' }
|
|
8701
|
+
const registerList = (currentRow()?.delegates ?? row.delegates)
|
|
8702
|
+
.map((d: any) => (d?.childId === childSession.id
|
|
8703
|
+
? { ...d, selfEffort, ...(correction.adjusted ? { selfEffortRequested: raw } : {}), complexityRationale: truncate(rationale, 300), deepThink: leafDeepThink, estimate: estimateDraft, status: 'running', error: null }
|
|
8704
|
+
: d))
|
|
8705
|
+
const stash = { ...(currentRow()?.delegateSelfEfforts ?? {}), [member.member]: selfEffort }
|
|
8706
|
+
// [2.5.2] 两轮思考产物与自配档同为任务级配置:delegates[].deepThink +
|
|
8707
|
+
// delegateDeepThinks 双通道落档,重置保留、durable 回放(G1 双侧接线)。
|
|
8708
|
+
const deepThinkStash = { ...(currentRow()?.delegateDeepThinks ?? {}), [member.member]: leafDeepThink }
|
|
8709
|
+
// [T6][契约v1 §3] 预估双通道:delegates[].estimate + delegateEstimates(任务级
|
|
8710
|
+
// 配置,重置保留、durable 回放),与 selfEffort/deepThink 同范式。
|
|
8711
|
+
const estimateStash = { ...(currentRow()?.delegateEstimates ?? {}), [member.member]: estimateDraft }
|
|
8712
|
+
persistSelf({ delegates: registerList, delegateSelfEfforts: stash, delegateDeepThinks: deepThinkStash, delegateEstimates: estimateStash })
|
|
8713
|
+
/*
|
|
8714
|
+
* [T6][D9][契约v1 §4] 预估送达部门负责人:登记之后、interrupt/接续之前。
|
|
8715
|
+
* 路由 row.childId(部门行负责人会话),缺失回退 leaderId;两者皆缺 ⇒
|
|
8716
|
+
* ESTIMATE_DELIVERY_FAILED(显式,不静默)。投递失败 ⇒ delivery:'failed' 已落档
|
|
8717
|
+
* +显式报错,不接续 phase-1;重试只重投 failed(sent 幂等跳过,不重复投递)。
|
|
8718
|
+
* 留痕 kind='estimate' 走 channelJournal 统一入口;journal 写失败不掩盖投递结果
|
|
8719
|
+
* (ok:true 附 journal:{ok:false,...},同 escalateDelegateLeaf journalInfo 口径)。
|
|
8720
|
+
*/
|
|
8721
|
+
let estimateFinal = estimateDraft
|
|
8722
|
+
let estimateJournalInfo: any = {}
|
|
8723
|
+
if (!estimateAlreadySent) {
|
|
8724
|
+
const headChildId = typeof row.childId === 'string' && row.childId ? row.childId : (typeof leaderId === 'string' ? leaderId : '')
|
|
8725
|
+
const estimateBody = `【第三层开工预估|${member.member} → 部门负责人】子任务 ${subtaskId} 成员 ${member.member} 开工前预估:执行本人任务约需 ${rawMinutes} 分钟(整数分钟)。理由:${estimateReason || '无'}。该预估已登记,平台即将以自配档接续其正式执行。`
|
|
8726
|
+
const estimateStartedAt = Date.now()
|
|
8727
|
+
let estimateMessageId = ''
|
|
8728
|
+
let estimateDeliveryError = ''
|
|
8729
|
+
if (!headChildId) {
|
|
8730
|
+
estimateDeliveryError = '部门行未登记负责人会话(childId 缺失)且父会话 leaderId 缺失,无法投递预估'
|
|
8731
|
+
} else {
|
|
8732
|
+
const estimateService: any = (ctx as any).subagents
|
|
8733
|
+
if (!estimateService || typeof estimateService.sendMessage !== 'function') {
|
|
8734
|
+
estimateDeliveryError = '当前部署没有可用的 subagent 服务,无法投递预估'
|
|
8735
|
+
} else {
|
|
8736
|
+
try {
|
|
8737
|
+
estimateMessageId = String(await estimateService.sendMessage(agent, headChildId, [{ type: 'text', text: estimateBody }], { signal: new AbortController().signal }) ?? '') // [T11] 缺陷②:预估投递携带有效 signal,消除 throwIfAborted
|
|
8738
|
+
} catch (error: any) {
|
|
8739
|
+
estimateDeliveryError = truncate(error instanceof Error ? error.message : String(error), 500)
|
|
8740
|
+
}
|
|
8741
|
+
}
|
|
8742
|
+
}
|
|
8743
|
+
const estimateLatencyMs = Date.now() - estimateStartedAt
|
|
8744
|
+
const estimateDelivery: 'sent' | 'failed' = estimateDeliveryError ? 'failed' : 'sent'
|
|
8745
|
+
estimateFinal = { ...estimateDraft, delivery: estimateDelivery, ...(estimateMessageId ? { messageId: estimateMessageId } : {}) }
|
|
8746
|
+
const estimateList = (currentRow()?.delegates ?? [])
|
|
8747
|
+
.map((d: any) => (d?.childId === childSession.id ? { ...d, estimate: estimateFinal } : d))
|
|
8748
|
+
const estimateMap = { ...(currentRow()?.delegateEstimates ?? {}), [member.member]: estimateFinal }
|
|
8749
|
+
persistSelf({ delegates: estimateList, delegateEstimates: estimateMap })
|
|
8750
|
+
const estimateJournal = channelJournal({
|
|
8751
|
+
planId: record.plan.planId,
|
|
8752
|
+
subtaskId,
|
|
8753
|
+
kind: 'estimate',
|
|
8754
|
+
from: { sessionId: String(childSession.id), role: 'expert', member: member.member },
|
|
8755
|
+
to: { sessionId: headChildId, role: 'head' },
|
|
8756
|
+
body: estimateBody,
|
|
8757
|
+
data: { declaredMinutes: rawMinutes, ...(estimateReason ? { reason: estimateReason } : {}) },
|
|
8758
|
+
delivery: { status: estimateDelivery, ...(estimateMessageId ? { messageId: estimateMessageId } : {}), latencyMs: estimateLatencyMs, ...(estimateDeliveryError ? { code: 'DELIVERY_FAILED', error: estimateDeliveryError } : {}) },
|
|
8759
|
+
})
|
|
8760
|
+
estimateJournalInfo = estimateJournal.result.ok ? {} : { journal: { ok: false, code: estimateJournal.result.code, error: estimateJournal.result.error } }
|
|
8761
|
+
if (estimateDeliveryError) {
|
|
8762
|
+
return {
|
|
8763
|
+
ok: false,
|
|
8764
|
+
code: 'ESTIMATE_DELIVERY_FAILED',
|
|
8765
|
+
subtaskId,
|
|
8766
|
+
member: member.member,
|
|
8767
|
+
error: `预估投递失败(预估已以 delivery:'failed' 落档,未接续执行):${estimateDeliveryError}。请重试 self_effort(携带完整原子对:reasoningEffort+complexityRationale+deepThink+timeNotice),重试将重新投递。`,
|
|
8768
|
+
...estimateJournalInfo,
|
|
8769
|
+
}
|
|
8770
|
+
}
|
|
8771
|
+
}
|
|
8772
|
+
/*
|
|
8773
|
+
* [2.5.2][T4b][D1] 负责人 agent 解析必须先于 interrupt,且用宿主同款安全
|
|
8774
|
+
* 访问器。根因(reports/D1-D2-root-cause-diagnosis.md §1):旧实现在
|
|
8775
|
+
* interrupt 之后用属性访问 `(ctx as any).agents?.get?.(leaderId)`,而插件
|
|
8776
|
+
* inject 清单(host.ts)不含 'agents'——Cordis 上下文代理对未注入服务的
|
|
8777
|
+
* 属性访问直接抛 `cannot get property "agents" without inject`(可选链挡
|
|
8778
|
+
* 不住代理 getter 抛错)。异常发生在 interrupt 之后、startActivation 之前、
|
|
8779
|
+
* 且不在任何 try/catch 内 ⇒ 接续会话从未创建、失败台账路径不可达,四个
|
|
8780
|
+
* 叶子永久死亡。现在:
|
|
8781
|
+
* ① 解析移到 interrupt 之前:ctx.get('agents') 安全访问器(宿主
|
|
8782
|
+
* dsh-subagent / dsh-tool-jobs 同款范式),整体 try/catch;无 get 方法
|
|
8783
|
+
* 的上下文(旧测试夹具)回退属性访问,同样在 try/catch 内。
|
|
8784
|
+
* ② 解析失败 ⇒ 不中断 phase-0;自配档与两轮思考产物已登记保留
|
|
8785
|
+
* (delegateSelfEfforts / delegateDeepThinks 已 durable 落档,负责人
|
|
8786
|
+
* 重派该成员时读档直连 phase-1),显式返回
|
|
8787
|
+
* SELF_EFFORT_CONTINUATION_FAILED,绝不静默。
|
|
8788
|
+
*/
|
|
8789
|
+
let leaderAgent: any = null
|
|
8790
|
+
try {
|
|
8791
|
+
const agentsService = typeof (ctx as any).get === 'function' ? (ctx as any).get('agents') : (ctx as any).agents
|
|
8792
|
+
leaderAgent = agentsService?.get?.(leaderId) ?? null
|
|
8793
|
+
} catch { leaderAgent = null }
|
|
8794
|
+
if (!leaderAgent) {
|
|
8795
|
+
const message = '自配档与两轮思考产物已登记,但负责人 agent 解析失败(agents 服务不可用):phase-0 未被中断,登记保留——负责人可重派该成员,重派将读档直接以自配档接续 phase-1(禁止静默降档)'
|
|
8796
|
+
const failedList = (currentRow()?.delegates ?? [])
|
|
8797
|
+
.map((d: any) => (d?.childId === childSession.id ? { ...d, status: 'failed', error: truncate(message, 300), finishedAt: Date.now() } : d))
|
|
8798
|
+
persistSelf({ delegates: failedList })
|
|
8799
|
+
return { ok: false, code: 'SELF_EFFORT_CONTINUATION_FAILED', subtaskId, member: member.member, selfEffort, error: message }
|
|
8800
|
+
}
|
|
8801
|
+
// 接续:中断 phase-0(parent authority, continuable),尽力而为。
|
|
8802
|
+
try {
|
|
8803
|
+
if (typeof (ctx as any).subagents?.interruptByParent === 'function') {
|
|
8804
|
+
(ctx as any).subagents.interruptByParent(childSession.id, leaderId, 'continuable')
|
|
8805
|
+
}
|
|
8806
|
+
} catch { /* 中断失败不阻断接续 */ }
|
|
8807
|
+
const departmentLabel = DEPARTMENTS[row.department as keyof typeof DEPARTMENTS]?.zh ?? String(row.department ?? '部门')
|
|
8808
|
+
const assignment = (Array.isArray(row.consolidation?.assignments) ? row.consolidation.assignments : [])
|
|
8809
|
+
.find((a: any) => a?.member === member.member)
|
|
8810
|
+
const fullTask = assignment?.task ?? member.task
|
|
8811
|
+
/*
|
|
8812
|
+
* [3.0.0][用户要求 6] 质量要求随 phase-1 任务书一起交给专家:优先取 review
|
|
8813
|
+
* 登记的分工表原文(含质量要求),缺省时取成员记录,再缺省为空数组
|
|
8814
|
+
* (由提示词侧 renderQualityRequirementsBlock 如实显示「未交代」)。
|
|
8815
|
+
*/
|
|
8816
|
+
const qualityRequirements = Array.isArray(assignment?.qualityRequirements) && assignment.qualityRequirements.length > 0
|
|
8817
|
+
? assignment.qualityRequirements
|
|
8818
|
+
: (Array.isArray((member as any)?.qualityRequirements) ? (member as any).qualityRequirements : [])
|
|
8819
|
+
const rulesBrief = buildLlmRulesBrief({ model, effort: selfEffort, requested: correction.adjusted ? raw : null, correctionReason: correction.reason ?? null, tier: 'delegate', memberName: member.member, memberRole: member.role })
|
|
8820
|
+
const promptText = buildDelegateePrompt({
|
|
8821
|
+
departmentLabel,
|
|
8822
|
+
leaderSubtaskId: subtaskId,
|
|
8823
|
+
leaderSubtaskTitle: String(row.title ?? ''),
|
|
8824
|
+
member: { member: member.member, role: 'expert', task: fullTask, qualityRequirements, effort: selfEffort },
|
|
8825
|
+
rulesBrief,
|
|
8826
|
+
cwd: typeof childSession.header?.cwd === 'string' ? childSession.header.cwd : '',
|
|
8827
|
+
leadSessionId: leaderId,
|
|
8828
|
+
extraContext: `【phase-0→phase-1 接续——继续勿重做】你已在 phase-0 完成复杂度评估并自配推理等级 \`${selfEffort}\`(依据:${truncate(rationale, 300)}${correction.adjusted ? `;请求档 ${raw} 越界已被平台钳制为 ${selfEffort}` : ''}),并登记了执行前两轮深度思考产物。平台已按你的自配档接续:直接执行正式任务,不要重新评估复杂度,不要重做 phase-0 已完成的工作。正式执行必须严格按你第二轮理清的方法、流程、步骤进行(你的第二轮产物:${leafDeepThink.approach.join(';').slice(0, 300)}…),全程少走弯路:先查历史教训、先验证再动手、不重复试错。`,
|
|
8829
|
+
})
|
|
8830
|
+
let activation: any = null
|
|
8831
|
+
let lastError: any = null
|
|
8832
|
+
for (let i = 0; i < 2; i += 1) {
|
|
8833
|
+
try {
|
|
8834
|
+
// [2.5.5][治本] 第三处 spawn 同口径:spec 顶层契约(prompt/parent/cwd/agentOptions/maxDepth)。
|
|
8835
|
+
activation = await ctx.subagents.startActivation({
|
|
8836
|
+
provider: 'spawn',
|
|
8837
|
+
label: `${row.department}:${subtaskId}→${member.member}(self:${selfEffort})`.slice(0, 120),
|
|
8838
|
+
prompt: [{ type: 'text', text: promptText }],
|
|
8839
|
+
parent: leaderAgent ?? agent,
|
|
8840
|
+
cwd: typeof childSession.header?.cwd === 'string' && childSession.header.cwd ? childSession.header.cwd : undefined,
|
|
8841
|
+
agentOptions: {
|
|
8842
|
+
...(modelSelection?.provider && modelSelection?.model ? { provider: modelSelection.provider, model: modelSelection.model } : {}),
|
|
8843
|
+
reasoningEffort: selfEffort,
|
|
8844
|
+
},
|
|
8845
|
+
maxDepth: 2,
|
|
8846
|
+
/*
|
|
8847
|
+
* [2.5.2][T4b][D1] 接续是平台驱动的重激活:signal 不得复用调用方
|
|
8848
|
+
* (phase-0 回合)的 signal——phase-0 即将被 interrupt,复用会让接续
|
|
8849
|
+
* 在 publication 前被连带取消。宿主契约 spec.signal 必填、语义只管
|
|
8850
|
+
* publication 前取消 ⇒ 用独立不中止的控制器。
|
|
8851
|
+
*/
|
|
8852
|
+
signal: new AbortController().signal,
|
|
8853
|
+
delivery: 'caller',
|
|
8854
|
+
})
|
|
8855
|
+
break
|
|
8856
|
+
} catch (error) { lastError = error }
|
|
8857
|
+
}
|
|
8858
|
+
if (!activation) {
|
|
8859
|
+
const message = `自配档已登记但接续失败(已重试 1 次):${String(lastError?.message ?? lastError)}——禁止静默降档;该成员记为 failed,负责人可重派(自配档保留,重派直接以自配档接续)`
|
|
8860
|
+
const failedList = (currentRow()?.delegates ?? [])
|
|
8861
|
+
.map((d: any) => (d?.childId === childSession.id ? { ...d, status: 'failed', error: truncate(message, 300), finishedAt: Date.now() } : d))
|
|
8862
|
+
persistSelf({ delegates: failedList })
|
|
8863
|
+
return { ok: false, code: 'SELF_EFFORT_CONTINUATION_FAILED', subtaskId, member: member.member, selfEffort, error: message }
|
|
8864
|
+
}
|
|
8865
|
+
const newChildId = typeof activation.childId === 'string' ? activation.childId : null
|
|
8866
|
+
const continuedList = (currentRow()?.delegates ?? [])
|
|
8867
|
+
.map((d: any) => (d?.childId === childSession.id ? { ...d, childId: newChildId, status: 'running', startedAt: Date.now(), finishedAt: null, error: null } : d))
|
|
8868
|
+
const written = persistSelf({ delegates: continuedList })
|
|
8869
|
+
if (activation && typeof activation.result?.then === 'function') {
|
|
8870
|
+
// [T8] 结算回调异步化:完成即时通知经 sendMessage 定向投递(T5 契约)。
|
|
8871
|
+
activation.result.then(async (outcome: any) => {
|
|
8872
|
+
try {
|
|
8873
|
+
const completed = outcome?.stopReason === 'completed'
|
|
8874
|
+
// [3.0.0] F10:专家汇报入口强制核验(adjudicateExpertReport),
|
|
8875
|
+
// 未过即退回(failed + F10 拒因),绝不记 done。
|
|
8876
|
+
const f10 = completed ? adjudicateExpertReport(outcome) : { ok: true as const }
|
|
8877
|
+
const settledDone = completed && f10.ok
|
|
8878
|
+
const current = (record.statuses ?? []).find((item: any) => item?.subtaskId === subtaskId)
|
|
8879
|
+
const list = (Array.isArray(current?.delegates) ? current.delegates : [])
|
|
8880
|
+
.map((item: any) => (item?.childId === newChildId
|
|
8881
|
+
// [T5-channel] 与 delegateTool 结算同款:待指示优先于结算——escalation
|
|
8882
|
+
// 子对象存在即请示未答复,不得覆盖成 done/failed(契约v1 权威形状)。
|
|
8883
|
+
? (item?.escalation
|
|
8884
|
+
? item
|
|
8885
|
+
: { ...item, status: settledDone ? 'done' : 'failed', closure: null, summary: truncate(resultText(outcome), 300), error: settledDone ? null : truncate(f10.ok ? String(outcome?.diagnostic ?? `子会话结束状态 ${outcome?.stopReason}`) : f10.rejection, 300), finishedAt: Date.now() })
|
|
8886
|
+
: item))
|
|
8887
|
+
const revision = Number(current?.revision ?? 0) + 1
|
|
8888
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision, updatedBy: 'child' })
|
|
8889
|
+
record.updatedAt = Date.now()
|
|
8890
|
+
appendUserMessage(rootSession, buildUpdateMessage({ planId: record.plan.planId, subtaskId, status: current?.status ?? row.status, delegates: list, revision }))
|
|
8891
|
+
// [T8] 与 delegateTool 结算同款:完成即时通知 → 原分派负责人会话(leaderId)。
|
|
8892
|
+
await emitDelegateDoneNotices(record, (ctx as any).sessions?.get?.(String(leaderId ?? '')) ?? leaderSession, rootSession, subtaskId)
|
|
8893
|
+
} catch { /* 结算留痕失败不影响主链路 */ }
|
|
8894
|
+
}).catch(() => {})
|
|
8895
|
+
}
|
|
8896
|
+
return {
|
|
8897
|
+
ok: true,
|
|
8898
|
+
planId: record.plan.planId,
|
|
8899
|
+
subtaskId,
|
|
8900
|
+
action: 'self_effort',
|
|
8901
|
+
member: member.member,
|
|
8902
|
+
selfEffort,
|
|
8903
|
+
requested: raw,
|
|
8904
|
+
...(correction.adjusted ? { clamped: { requested: raw, corrected: selfEffort, reason: correction.reason } } : {}),
|
|
8905
|
+
childId: newChildId,
|
|
8906
|
+
delegates: written?.delegates ?? continuedList,
|
|
8907
|
+
// [T6][契约v1 §2/§4] 成功回执附预估(declaredMinutes/reason?/delivery);
|
|
8908
|
+
// 留痕写失败不掩盖投递结果(journal:{ok:false,...},同 escalateDelegateLeaf 口径)。
|
|
8909
|
+
estimate: { declaredMinutes: estimateFinal.declaredMinutes, ...(estimateFinal.reason ? { reason: estimateFinal.reason } : {}), delivery: estimateFinal.delivery },
|
|
8910
|
+
...estimateJournalInfo,
|
|
8911
|
+
hint: `自配档 \`${selfEffort}\` 已登记并以该档接续 phase-1(继续勿重做)。请执行正式任务,完成后把结论回报部门负责人会话。`,
|
|
8912
|
+
}
|
|
8913
|
+
}
|
|
8914
|
+
async function delegateTool(agent: any, args: any, signal?: any) {
|
|
8915
|
+
const childSession = agent?.session
|
|
8916
|
+
if (!childSession?.id) {
|
|
8917
|
+
return { ok: false, code: 'NO_SESSION', error: '只能在会话内使用第三层派发' }
|
|
8918
|
+
}
|
|
8919
|
+
// [2.5.0][自配档] self_effort 是叶子专属动作:先于负责人校验路由。
|
|
8920
|
+
if (args?.action === 'self_effort') return selfEffortTool(agent, args, signal)
|
|
8921
|
+
const parentId = childSession.header?.parentSession
|
|
8922
|
+
if (!parentId) {
|
|
8923
|
+
return {
|
|
8924
|
+
ok: false,
|
|
8925
|
+
code: 'NOT_LEADER_SESSION',
|
|
8926
|
+
error: '只有「部门负责人子会话」可以使用 dsh_workplan_delegate:根会话请用 dsh_workplan_dispatch 派发主计划;第三层全球顶尖专家是叶子层,不得再派发(用户要求 4:只有一层下级)。',
|
|
8927
|
+
}
|
|
8928
|
+
}
|
|
8929
|
+
let record = state.records.get(parentId)
|
|
8930
|
+
if (!record?.plan) {
|
|
8931
|
+
const parent = (ctx as any).sessions?.get?.(parentId)
|
|
8932
|
+
if (parent) {
|
|
8933
|
+
try {
|
|
8934
|
+
record = reconstructFromSession(parent)
|
|
8935
|
+
} catch (error) {
|
|
8936
|
+
pushRecordError({ errors: [] } as any, error)
|
|
8937
|
+
}
|
|
8938
|
+
}
|
|
8939
|
+
}
|
|
8940
|
+
if (!record?.plan) {
|
|
8941
|
+
return {
|
|
8942
|
+
ok: false,
|
|
8943
|
+
code: 'NO_PLAN',
|
|
8944
|
+
error: '父会话没有可关联的计划。若你是第三层全球顶尖专家(叶子层):不得再派发,完成自身任务后把结论回报部门负责人即可。',
|
|
6818
8945
|
}
|
|
6819
8946
|
}
|
|
6820
|
-
const
|
|
6821
|
-
if (
|
|
6822
|
-
|
|
6823
|
-
|
|
6824
|
-
|
|
8947
|
+
const row = (record.statuses ?? []).find((item: any) => item?.childId === childSession.id)
|
|
8948
|
+
if (!row) {
|
|
8949
|
+
return {
|
|
8950
|
+
ok: false,
|
|
8951
|
+
code: 'NO_SUBTASK',
|
|
8952
|
+
error: '计划里找不到与本子会话关联的子任务行(childId 未登记);第三层派发只能由计划内的部门负责人子会话发起。',
|
|
6825
8953
|
}
|
|
6826
|
-
handoffs[index] = { ...handoff, department, status: 'routed', updatedAt: Date.now(), by: 'agent' }
|
|
6827
|
-
} else if (action === 'resolve') {
|
|
6828
|
-
const response = truncate(String(args?.response ?? '').trim(), MAX_HANDOFF_RESPONSE_CHARS)
|
|
6829
|
-
if (!response) return { ok: false, code: 'INVALID_RESPONSE', error: 'resolve 必须写清答复或已由哪项产物满足该需求' }
|
|
6830
|
-
handoffs[index] = { ...handoff, status: 'answered', response, updatedAt: Date.now(), by: 'agent' }
|
|
6831
|
-
} else {
|
|
6832
|
-
handoffs[index] = { ...handoff, status: 'closed', response: handoff.response ?? null, updatedAt: Date.now(), by: 'agent' }
|
|
6833
8954
|
}
|
|
6834
|
-
|
|
6835
|
-
|
|
6836
|
-
|
|
6837
|
-
|
|
6838
|
-
|
|
6839
|
-
|
|
6840
|
-
|
|
6841
|
-
|
|
6842
|
-
|
|
8955
|
+
if (row.status === 'done') {
|
|
8956
|
+
return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, error: '该子任务已完成,不能再派发第三层。' }
|
|
8957
|
+
}
|
|
8958
|
+
const action = ['review', 'dispatch', 'direct', 'status'].includes(args?.action) ? String(args.action) : ''
|
|
8959
|
+
if (!action) {
|
|
8960
|
+
return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 review(提交全面梳理产物)/ dispatch(派发给本部门全球顶尖专家)/ direct(low 任务负责人亲自执行登记)/ status(查看梳理与下级进度)' }
|
|
8961
|
+
}
|
|
8962
|
+
const subtaskId = String(row.subtaskId)
|
|
8963
|
+
// [2.5.5][T3] D1 兜底:任务行记录等级。计划形状=stages[].subtasks[](不存在
|
|
8964
|
+
// record.plan.subtasks 平铺数组),复用 findSubtaskById(本文件 :1547)。
|
|
8965
|
+
// 五档消毒:非法/缺失一律 undefined(视同未配置),不把脏值传进判定链。
|
|
8966
|
+
const plannedRow = findSubtaskById(record.plan, subtaskId)
|
|
8967
|
+
const taskRowEffort = typeof plannedRow?.reasoningEffort === 'string'
|
|
8968
|
+
&& REASONING_EFFORTS.includes(plannedRow.reasoningEffort)
|
|
8969
|
+
? plannedRow.reasoningEffort
|
|
8970
|
+
: undefined
|
|
8971
|
+
const modelSelection = resolveModelSelection(ctx, { agent })
|
|
8972
|
+
const model = typeof modelSelection?.model === 'string' && modelSelection.model.trim() ? modelSelection.model.trim() : null
|
|
8973
|
+
const parentSession = (ctx as any).sessions?.get?.(parentId)
|
|
8974
|
+
const persist = (patch: any) => {
|
|
8975
|
+
const revision = Number(row.revision ?? 0) + 1
|
|
8976
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { ...patch, revision, updatedBy: 'child' })
|
|
8977
|
+
record.updatedAt = Date.now()
|
|
8978
|
+
try {
|
|
8979
|
+
const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
8980
|
+
appendUserMessage(parentSession, buildUpdateMessage({
|
|
8981
|
+
planId: record.plan.planId,
|
|
8982
|
+
subtaskId,
|
|
8983
|
+
status: written?.status ?? row.status,
|
|
8984
|
+
...(patch.consolidation === undefined ? {} : { consolidation: written?.consolidation }),
|
|
8985
|
+
...(patch.delegates === undefined ? {} : { delegates: written?.delegates }),
|
|
8986
|
+
// [2.5.4][T3R1] 门禁审计随 durable workplan-update 落盘(A3 可复核)。
|
|
8987
|
+
...(patch.gateAudit === undefined ? {} : { gateAudit: written?.gateAudit }),
|
|
8988
|
+
// [2.5.0] 整体任务等级随 durable workplan-update 回放,重启不丢。
|
|
8989
|
+
...(patch.effortOverride === undefined ? {} : { effortOverride: written?.effortOverride }),
|
|
8990
|
+
revision: written?.revision ?? revision,
|
|
8991
|
+
}))
|
|
8992
|
+
} catch (error) {
|
|
8993
|
+
pushRecordError(record, error)
|
|
8994
|
+
}
|
|
8995
|
+
return record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
8996
|
+
}
|
|
8997
|
+
|
|
8998
|
+
/*
|
|
8999
|
+
* [2.5.4][T3R1] 门禁审计记录器(T3 A3):review/dispatch 的每次拒绝都经
|
|
9000
|
+
* persist 留痕(durable workplan-update + applyStatus 消毒,有界 20 条)。
|
|
9001
|
+
* 放行记录并入各自动作既有的 persist 补丁(review 登记/dispatch 台账),
|
|
9002
|
+
* 避免同一动作二次 persist 造成 revision 竞争。
|
|
9003
|
+
*/
|
|
9004
|
+
const recordGate = (gateAction: 'review' | 'dispatch' | 'direct', ok: boolean, code?: string | null) => {
|
|
9005
|
+
const prior = Array.isArray(row.gateAudit) ? row.gateAudit : []
|
|
9006
|
+
const entry = { at: Date.now(), action: gateAction, ok, code: ok ? null : String(code ?? 'UNKNOWN') }
|
|
9007
|
+
return persist({ gateAudit: [...prior, entry].slice(-20) })
|
|
9008
|
+
}
|
|
9009
|
+
|
|
9010
|
+
if (action === 'status') {
|
|
9011
|
+
const delegates = Array.isArray(row.delegates) ? row.delegates : []
|
|
9012
|
+
return {
|
|
9013
|
+
ok: true,
|
|
6843
9014
|
planId: record.plan.planId,
|
|
6844
9015
|
subtaskId,
|
|
6845
|
-
|
|
6846
|
-
|
|
6847
|
-
|
|
6848
|
-
|
|
6849
|
-
|
|
6850
|
-
|
|
9016
|
+
action,
|
|
9017
|
+
consolidation: row.consolidation ?? null,
|
|
9018
|
+
effortOverride: row.effortOverride ?? null,
|
|
9019
|
+
// [2.5.4][T3R1] 门禁审计对负责人可见(A3:拒绝/放行记录可复核)。
|
|
9020
|
+
gateAudit: Array.isArray(row.gateAudit) ? row.gateAudit : [],
|
|
9021
|
+
delegates,
|
|
9022
|
+
// [T7][lead-decisions J2] 负责人时长聚合:与看板/模型面同一读时派生纯函数
|
|
9023
|
+
// (J1 冻结结构;null=无下属分工/replanned 旧行/越界 fail-closed,J8/R8)。
|
|
9024
|
+
leaderEstimate: deriveLeaderEstimate(row),
|
|
9025
|
+
// [2.5.5][T3] low 直执分支(派生判据,不新增持久化标记):effortOverride='low'
|
|
9026
|
+
// 且分工表为空/缺失 ⇒ low 直执;复杂任务被钳制到 low 的行(assignments 非空)
|
|
9027
|
+
// 不命中,避免误导(规格 §5.6)。
|
|
9028
|
+
hint: row.effortOverride === 'low' && (!Array.isArray((row.consolidation as any)?.assignments) || (row.consolidation as any).assignments.length === 0)
|
|
9029
|
+
? 'low 任务(含视同 low):禁止第三层下派,负责人亲自执行;两轮思考产物经 action="direct" 登记(已登记则直接执行)。'
|
|
9030
|
+
: !row.consolidation
|
|
9031
|
+
? '尚未提交梳理产物:先调用 action="review"(用户要求 4 的硬门禁)。'
|
|
9032
|
+
: delegates.length === 0
|
|
9033
|
+
? '梳理产物已登记,可调用 action="dispatch" 正式派发给本部门全球顶尖专家。'
|
|
9034
|
+
: '第三层已派发;各下级结论会送回本会话,收齐后汇总核验,再写最终结果块。若有成员 closure=escalated(待指示),必须当轮用 dsh_workplan_instruct(subtaskId=本部门行 ID,多个成员同时请示时加 member)答复,不要沉默略过。',
|
|
9035
|
+
}
|
|
6851
9036
|
}
|
|
9037
|
+
|
|
6852
9038
|
/*
|
|
6853
|
-
* [
|
|
6854
|
-
*
|
|
6855
|
-
*
|
|
6856
|
-
*
|
|
6857
|
-
*
|
|
6858
|
-
*
|
|
6859
|
-
*
|
|
9039
|
+
* [2.5.5][T3] 用户裁决 D2/D4:low 任务负责人亲自执行登记(direct)。
|
|
9040
|
+
* low(含视同 low)任务禁止第三层下派——planDelegations 禁派闸对 review/dispatch
|
|
9041
|
+
* 一律硬拒(DELEGATE_LOW_TASK_FORBIDDEN);负责人亲自执行,两轮深度思考产物经
|
|
9042
|
+
* 本动作登记(复用 validateMainDeepThink,与主 Agent/叶子/review 同一 40/40/20
|
|
9043
|
+
* 判据)。登记 effortOverride='low' ⇒ phase-0 结算闸(runSubtaskAttempt 内
|
|
9044
|
+
* SELF_EFFORT_MISSING 分支)只查 effortOverride 非空,逻辑零改动即可接续。
|
|
9045
|
+
* 防旁路(规格 §5.8):不收 consolidation/分工表;只接受 reasoningEffort='low'
|
|
9046
|
+
* (缺省默认 low);已有复杂分工表的行不得降级;下级 running 中不得改走;
|
|
9047
|
+
* 叶子调用在上方调用者边界命中 NOT_LEADER_SESSION/NO_PLAN。无任何例外通道(D5)。
|
|
6860
9048
|
*/
|
|
6861
|
-
|
|
6862
|
-
|
|
6863
|
-
|
|
6864
|
-
|
|
9049
|
+
if (action === 'direct') {
|
|
9050
|
+
if (Array.isArray(row.delegates) && row.delegates.some((item: any) => item?.status === 'running')) {
|
|
9051
|
+
recordGate('direct', false, 'DELEGATE_ALREADY_RUNNING')
|
|
9052
|
+
return {
|
|
9053
|
+
ok: false,
|
|
9054
|
+
code: 'DELEGATE_ALREADY_RUNNING',
|
|
9055
|
+
subtaskId,
|
|
9056
|
+
error: '第三层仍在派发中(有下级 running):不能改走 low 直执。先等当前下级结算(action="status" 查看进度)。',
|
|
9057
|
+
}
|
|
9058
|
+
}
|
|
9059
|
+
const priorAssignments = Array.isArray((row.consolidation as any)?.assignments) ? (row.consolidation as any).assignments : []
|
|
9060
|
+
if (priorAssignments.length > 0) {
|
|
9061
|
+
recordGate('direct', false, 'DELEGATE_DIRECT_CONFLICT')
|
|
9062
|
+
return {
|
|
9063
|
+
ok: false,
|
|
9064
|
+
code: 'DELEGATE_DIRECT_CONFLICT',
|
|
9065
|
+
subtaskId,
|
|
9066
|
+
error: '本行已登记非空分工表(复杂流程已启动):不得降级改走 low 直执。复杂任务请继续 review/dispatch;low 禁派闸只拦 low/视同 low 任务。',
|
|
9067
|
+
}
|
|
9068
|
+
}
|
|
9069
|
+
if (args?.consolidation !== undefined && args?.consolidation !== null) {
|
|
9070
|
+
recordGate('direct', false, 'DELEGATE_DIRECT_ASSIGNMENTS_FORBIDDEN')
|
|
9071
|
+
return {
|
|
9072
|
+
ok: false,
|
|
9073
|
+
code: 'DELEGATE_DIRECT_ASSIGNMENTS_FORBIDDEN',
|
|
9074
|
+
subtaskId,
|
|
9075
|
+
error: 'direct 不接受 consolidation/分工表(low 任务禁止下派,用户裁决 D2):只提交 deepThink={problemAnalysis[],approach[],approachBasis[]}(40/40/20 字判据)与可选 reasoningEffort="low"。',
|
|
9076
|
+
}
|
|
9077
|
+
}
|
|
9078
|
+
const think = validateMainDeepThink(args?.deepThink)
|
|
9079
|
+
if (!think.ok || !think.deepThink) {
|
|
9080
|
+
const code = think.code === 'MAIN_DEEP_THINK_MISSING' ? 'DELEGATE_DIRECT_THINK_MISSING' : 'DELEGATE_DIRECT_THINK_INCOMPLETE'
|
|
9081
|
+
recordGate('direct', false, code)
|
|
9082
|
+
return {
|
|
9083
|
+
ok: false,
|
|
9084
|
+
code,
|
|
9085
|
+
subtaskId,
|
|
9086
|
+
error: `${think.error ?? '两轮深度思考产物缺失或不合格。'}(direct 登记与主 Agent/叶子同一判据:problemAnalysis 合计 ≥40 字、approach 合计 ≥40 字、approachBasis 合计 ≥20 字。)`,
|
|
9087
|
+
}
|
|
9088
|
+
}
|
|
9089
|
+
const directEffortRaw = args?.reasoningEffort
|
|
9090
|
+
if (directEffortRaw !== undefined && directEffortRaw !== null && directEffortRaw !== 'low') {
|
|
9091
|
+
recordGate('direct', false, 'DELEGATE_DIRECT_EFFORT_INVALID')
|
|
9092
|
+
return {
|
|
9093
|
+
ok: false,
|
|
9094
|
+
code: 'DELEGATE_DIRECT_EFFORT_INVALID',
|
|
9095
|
+
subtaskId,
|
|
9096
|
+
error: `direct 只接受 reasoningEffort="low"(缺失默认 low);"${String(directEffortRaw)}" 不被接受。复杂任务(medium/high/xhigh/max)请走 review+dispatch(≥8 人闸),direct 不是复杂任务通道。`,
|
|
9097
|
+
}
|
|
9098
|
+
}
|
|
9099
|
+
const hadEffortOverride = typeof row.effortOverride === 'string' && row.effortOverride.length > 0
|
|
9100
|
+
const written = persist({
|
|
9101
|
+
consolidation: {
|
|
9102
|
+
problemAnalysis: think.deepThink.problemAnalysis,
|
|
9103
|
+
approach: think.deepThink.approach,
|
|
9104
|
+
approachBasis: think.deepThink.approachBasis,
|
|
9105
|
+
assignments: [], // 空分工表=直执标记(派生判据,规格 §5.6)
|
|
9106
|
+
taskReasoningEffort: 'low',
|
|
9107
|
+
submittedAt: Date.now(),
|
|
9108
|
+
},
|
|
9109
|
+
effortOverride: 'low',
|
|
9110
|
+
gateAudit: [...(Array.isArray(row.gateAudit) ? row.gateAudit : []), { at: Date.now(), action: 'direct', ok: true, code: null }].slice(-20),
|
|
9111
|
+
})
|
|
9112
|
+
// 中断镜像 review 的 stall-fix 口径:仅「本次登记前尚无 effortOverride」
|
|
9113
|
+
// (真正的 phase-0→登记转变)才中断;phase-1 重新 direct 只更新产物。
|
|
9114
|
+
try {
|
|
9115
|
+
if (!hadEffortOverride && typeof (ctx as any).subagents?.interruptByParent === 'function') {
|
|
9116
|
+
(ctx as any).subagents.interruptByParent(childSession.id, parentId, 'continuable')
|
|
9117
|
+
}
|
|
9118
|
+
} catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
|
|
9119
|
+
return {
|
|
9120
|
+
ok: true,
|
|
6865
9121
|
planId: record.plan.planId,
|
|
6866
9122
|
subtaskId,
|
|
6867
|
-
|
|
6868
|
-
|
|
9123
|
+
action: 'direct',
|
|
9124
|
+
effortOverride: 'low',
|
|
9125
|
+
consolidation: written?.consolidation ?? null,
|
|
9126
|
+
hint: 'low 直执已登记(durable,刷新后门禁依然生效):平台将以 low 档接续本会话进入 phase-1。负责人亲自执行本任务,禁止再调用 review/dispatch(low 禁派闸会硬拒);完成后按三阶段契约提交证据与结论。',
|
|
9127
|
+
}
|
|
6869
9128
|
}
|
|
6870
|
-
|
|
9129
|
+
|
|
9130
|
+
if (action === 'review') {
|
|
9131
|
+
const input = isRecord(args?.consolidation) ? args.consolidation : null
|
|
9132
|
+
if (!input) {
|
|
9133
|
+
return {
|
|
9134
|
+
ok: false,
|
|
9135
|
+
code: 'MISSING_CONSOLIDATION',
|
|
9136
|
+
subtaskId,
|
|
9137
|
+
error: 'review 必须携带 consolidation:{ problemAnalysis[], constraints[]?, unknowns[]?, approach[], approachBasis[], assignments[{member, role:"expert", task, qualityRequirements[], reasoningEffort}] }——两轮深度思考产物(第一轮全面、全盘、深入梳理研究思考自己的任务=problemAnalysis;第二轮基于第一轮全部结果理清方法、流程、步骤=approach,依据对应=approachBasis)+ 分工表(至少 1 名、最多 12 名本部门全球顶尖专家;组员角色已取消;每项任务必须极简并附质量要求)。',
|
|
9138
|
+
}
|
|
9139
|
+
}
|
|
9140
|
+
// [2.5.0][R2×R4] 重新 review 未再配整体等级时,继承行上已持久化的
|
|
9141
|
+
// effortOverride(重置不清除的任务级配置),全程贯穿不丢。
|
|
9142
|
+
// [2.5.5][T3] 防注入:钳制前声明记忆只由平台写入,review 新输入不得携带
|
|
9143
|
+
// (否则 {taskReasoningEffort:'low', taskReasoningEffortDeclared:'max'} 可绕过禁派闸)。
|
|
9144
|
+
const { taskReasoningEffortDeclared: _stripped, ...reviewInput } = input
|
|
9145
|
+
const preview = planDelegations({ consolidation: reviewInput, model, taskEffortFallback: row.effortOverride, taskRowEffort })
|
|
9146
|
+
if (!preview.ok) {
|
|
9147
|
+
// [2.5.4][T3R1] 门禁拒绝留痕(A3):薄产物/缺产物都记入 gateAudit。
|
|
9148
|
+
recordGate('review', false, preview.code ?? 'DELEGATE_CONSOLIDATION_INVALID')
|
|
9149
|
+
return {
|
|
9150
|
+
ok: false,
|
|
9151
|
+
code: preview.code ?? 'DELEGATE_CONSOLIDATION_INVALID',
|
|
9152
|
+
subtaskId,
|
|
9153
|
+
error: preview.error,
|
|
9154
|
+
hint: '修正梳理产物后重新 action="review";未登记前 action="dispatch" 会持续被硬门禁拒绝。',
|
|
9155
|
+
}
|
|
9156
|
+
}
|
|
9157
|
+
// [2.5.2][stall-fix] 中断判据快照:本次 review 之前是否已登记整体档。
|
|
9158
|
+
const hadEffortOverride = typeof row.effortOverride === 'string' && row.effortOverride.length > 0
|
|
9159
|
+
const written = persist({
|
|
9160
|
+
consolidation: {
|
|
9161
|
+
problemAnalysis: input.problemAnalysis,
|
|
9162
|
+
constraints: input.constraints,
|
|
9163
|
+
unknowns: input.unknowns,
|
|
9164
|
+
approach: input.approach,
|
|
9165
|
+
// [2.5.1] 两轮深度思考协议:第二轮依据随梳理产物留档,dispatch 读回同口径。
|
|
9166
|
+
approachBasis: input.approachBasis,
|
|
9167
|
+
assignments: input.assignments,
|
|
9168
|
+
// [2.5.0] 整体任务等级随梳理产物留档,dispatch 读回时同口径消费。
|
|
9169
|
+
...(preview.taskEffort ? { taskReasoningEffort: preview.taskEffort } : {}),
|
|
9170
|
+
// [2.5.5][T3] 钳制前声明记忆随梳理产物留档:dispatch 读回时防
|
|
9171
|
+
// 「非 qwen medium 钳制后 low」误杀复杂声明(规格 §3.4)。
|
|
9172
|
+
...(preview.taskEffortDeclared ? { taskReasoningEffortDeclared: preview.taskEffortDeclared } : {}),
|
|
9173
|
+
submittedAt: Date.now(),
|
|
9174
|
+
},
|
|
9175
|
+
// [2.5.0] 用户要求 2:负责人配置的整体等级写入状态行,本任务每次
|
|
9176
|
+
// 派发/重试/续跑优先读它(resolveTaskEffort),全程生效、durable 回放。
|
|
9177
|
+
...(preview.taskEffort ? { effortOverride: preview.taskEffort } : {}),
|
|
9178
|
+
// [2.5.4][T3R1] 门禁放行留痕(A3):合格梳理登记成功记入 gateAudit。
|
|
9179
|
+
gateAudit: [...(Array.isArray(row.gateAudit) ? row.gateAudit : []), { at: Date.now(), action: 'review', ok: true, code: null }].slice(-20),
|
|
9180
|
+
})
|
|
9181
|
+
/*
|
|
9182
|
+
* [2.5.0][自配档] 登记后立即中断 phase-0 回合(parent authority, continuable);
|
|
9183
|
+
* runSubtaskAttempt 检测到 effortOverride 即以自配档接续 phase-1。尽力而为:
|
|
9184
|
+
* interrupt 不可用时 phase-0 自然结束,平台接续仍然成立。
|
|
9185
|
+
*
|
|
9186
|
+
* [2.5.2][stall-fix] 根因修复(用户报告「提交任务后长时间无反应」):
|
|
9187
|
+
* 旧实现只要 preview.taskEffort 非空就中断——负责人已在 phase-1 时重新
|
|
9188
|
+
* review(哪怕等级不变)也会触发中断,而接续逻辑只存在于 phase-0 结算
|
|
9189
|
+
* 分支:phase-1 回合被中断后无人接续,子会话 aborted、产物丢失、台账
|
|
9190
|
+
* blocked,用户看到的就是长时间停滞。现在仅当「本次 review 之前尚未
|
|
9191
|
+
* 登记 effortOverride」(真正的 phase-0→登记 转变)才中断;phase-1 的
|
|
9192
|
+
* 重新 review 只更新梳理产物,绝不中断正在执行的回合。
|
|
9193
|
+
*/
|
|
9194
|
+
try {
|
|
9195
|
+
if (preview.taskEffort && !hadEffortOverride && typeof (ctx as any).subagents?.interruptByParent === 'function') {
|
|
9196
|
+
(ctx as any).subagents.interruptByParent(childSession.id, parentId, 'continuable')
|
|
9197
|
+
}
|
|
9198
|
+
} catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
|
|
9199
|
+
return {
|
|
9200
|
+
ok: true,
|
|
9201
|
+
planId: record.plan.planId,
|
|
9202
|
+
subtaskId,
|
|
9203
|
+
action,
|
|
9204
|
+
consolidation: written?.consolidation ?? null,
|
|
9205
|
+
members: preview.members,
|
|
9206
|
+
clamped: preview.clamped,
|
|
9207
|
+
taskEffort: preview.taskEffort,
|
|
9208
|
+
...(preview.taskEffortClamped ? { taskEffortClamped: preview.taskEffortClamped } : {}),
|
|
9209
|
+
model: model ?? '(未知,未施加静态等级约束)',
|
|
9210
|
+
hint: '梳理产物已登记(durable,刷新后门禁依然生效)。现在可调用 action="dispatch" 正式派发;每位下级的推理等级已按当前模型家族合法集合钳制(clamped 列出越界修正与原因,留痕可审计)。'
|
|
9211
|
+
+ (preview.taskEffort ? `整体任务等级已配置为 ${preview.taskEffort}(负责人自配档),本任务重试/续跑全程沿用;下级以 self_effort 自配为权威。` : '未配置整体任务等级:负责人须按先配置后开工经 review 自配(consolidation.taskReasoningEffort);下级经 self_effort 自配。'),
|
|
9212
|
+
}
|
|
9213
|
+
}
|
|
9214
|
+
|
|
9215
|
+
// action === 'dispatch'
|
|
9216
|
+
const consolidation = isRecord(row.consolidation) ? row.consolidation : null
|
|
9217
|
+
// [2.5.0][R2×R4] dispatch 读回梳理产物时,整体等级缺失同样回落行上
|
|
9218
|
+
// effortOverride(durable 回放/重置后依然全程贯穿)。
|
|
9219
|
+
const delegationPlan = planDelegations({ consolidation, model, taskEffortFallback: row.effortOverride, taskRowEffort })
|
|
9220
|
+
if (!delegationPlan.ok) {
|
|
9221
|
+
// [2.5.4][T3R1] 分派门禁拒绝留痕(A3):未梳理/薄产物一律记录拒因。
|
|
9222
|
+
recordGate('dispatch', false, delegationPlan.code ?? 'DELEGATE_CONSOLIDATION_MISSING')
|
|
9223
|
+
return {
|
|
9224
|
+
ok: false,
|
|
9225
|
+
code: delegationPlan.code ?? 'DELEGATE_CONSOLIDATION_MISSING',
|
|
9226
|
+
subtaskId,
|
|
9227
|
+
error: delegationPlan.error,
|
|
9228
|
+
}
|
|
9229
|
+
}
|
|
9230
|
+
if (Array.isArray(row.delegates) && row.delegates.some((item: any) => item?.status === 'running')) {
|
|
9231
|
+
return {
|
|
9232
|
+
ok: false,
|
|
9233
|
+
code: 'DELEGATE_ALREADY_RUNNING',
|
|
9234
|
+
subtaskId,
|
|
9235
|
+
error: '第三层已在派发中(仍有下级 running):不要重复派发。用 action="status" 查看进度;如需补派新成员,先等当前下级结算。',
|
|
9236
|
+
delegates: row.delegates,
|
|
9237
|
+
}
|
|
9238
|
+
}
|
|
9239
|
+
const departmentLabel = DEPARTMENTS[row.department as keyof typeof DEPARTMENTS]?.zh ?? String(row.department ?? '部门')
|
|
9240
|
+
// cwd 与 dispatchTool 同源(session.header.cwd,7465 行同款):优先负责人
|
|
9241
|
+
// 子会话自己的工作目录,缺失回退根会话;都没有则交给宿主按 parent 推导。
|
|
9242
|
+
const cwd = typeof childSession.header?.cwd === 'string' && childSession.header.cwd
|
|
9243
|
+
? childSession.header.cwd
|
|
9244
|
+
: (typeof parentSession?.header?.cwd === 'string' && parentSession.header.cwd
|
|
9245
|
+
? parentSession.header.cwd
|
|
9246
|
+
: undefined)
|
|
9247
|
+
const delegates: any[] = []
|
|
9248
|
+
/*
|
|
9249
|
+
* [2.5.0][R4] 重试/续跑不丢已完成部分(第三层落点):重派时 row.delegates
|
|
9250
|
+
* 仍是上一次尝试的台账——为每位下级附上次状态/失败原因/已回报结论与已核实
|
|
9251
|
+
* 在盘产物(buildDelegateRetryBrief),经 extraContext 写进新任务书。
|
|
9252
|
+
* 旧实现这里直接发全新任务书,叶子失败后重派只能整步重跑。
|
|
9253
|
+
*/
|
|
9254
|
+
const priorDelegates = Array.isArray(row.delegates) ? row.delegates : []
|
|
9255
|
+
const consolidationApproach = Array.isArray((row.consolidation as any)?.approach) ? (row.consolidation as any).approach : []
|
|
9256
|
+
for (const assignment of delegationPlan.members) {
|
|
9257
|
+
const rulesBrief = buildLlmRulesBrief({
|
|
9258
|
+
model,
|
|
9259
|
+
effort: assignment.effort,
|
|
9260
|
+
requested: assignment.requested ?? null,
|
|
9261
|
+
correctionReason: assignment.correctionReason ?? null,
|
|
9262
|
+
tier: 'delegate',
|
|
9263
|
+
memberName: assignment.member,
|
|
9264
|
+
memberRole: assignment.role,
|
|
9265
|
+
})
|
|
9266
|
+
const prior = priorDelegates.find((item: any) => item?.member === assignment.member) ?? null
|
|
9267
|
+
const retryBrief = prior
|
|
9268
|
+
? buildDelegateRetryBrief(prior, probeDelegateLandedArtifacts(cwd, assignment.member), consolidationApproach)
|
|
9269
|
+
: ''
|
|
9270
|
+
// [2.5.0][自配档] 先配置后开工:未登记自配档 ⇒ phase-0 以 low 启动(唯一
|
|
9271
|
+
// 职责=self_effort);已有自配档(含重置保留的 delegateSelfEfforts)⇒ 直接
|
|
9272
|
+
// 以自配档接续 phase-1。分工表 effort 降为建议(台账保留供看板对照)。
|
|
9273
|
+
const stashedSelf = (row.delegateSelfEfforts as any)?.[assignment.member]
|
|
9274
|
+
const priorSelf = typeof stashedSelf === 'string' && stashedSelf ? stashedSelf
|
|
9275
|
+
: (typeof prior?.selfEffort === 'string' && prior.selfEffort ? prior.selfEffort : '')
|
|
9276
|
+
/*
|
|
9277
|
+
* [2.5.2] 执行前两轮思考读档:已登记思考产物(delegateDeepThinks 或
|
|
9278
|
+
* delegates[].deepThink)⇒ 随接续提示词下发执行蓝图,直接 phase-1;
|
|
9279
|
+
* 未登记(含旧计划遗留叶子)⇒ 仍走 phase-0 补齐思考+自配后才准执行。
|
|
9280
|
+
*/
|
|
9281
|
+
const stashedThink = sanitizeMainDeepThink((row.delegateDeepThinks as any)?.[assignment.member])
|
|
9282
|
+
?? sanitizeMainDeepThink(prior?.deepThink)
|
|
9283
|
+
/*
|
|
9284
|
+
* [T6][D9][契约v1 §5] 预估读档门禁:已登记且已送达(delivery='sent')的预估
|
|
9285
|
+
* 才算门禁通过。未预估、或预估投递失败(failed)⇒ 回 phase-0 补交完整原子对
|
|
9286
|
+
* (self_effort 重试只重投 failed,sent 幂等不重投)。D9 唯一权威:「汇报给对应
|
|
9287
|
+
* 负责人后,才可以重试或继续执行」——failed 若放行 phase-1 将永远无人补投,
|
|
9288
|
+
* 故门禁以 sent 为准(正整数 declaredMinutes 才算已登记,消毒同 plan.ts 口径)。
|
|
9289
|
+
*/
|
|
9290
|
+
const stashedEstimate = sanitizeLeafEstimate((row.delegateEstimates as any)?.[assignment.member])
|
|
9291
|
+
?? sanitizeLeafEstimate(prior?.estimate)
|
|
9292
|
+
const registeredEstimate = stashedEstimate?.delivery === 'sent' ? stashedEstimate : null
|
|
9293
|
+
const leafPhaseZero = !priorSelf || !stashedThink || !registeredEstimate
|
|
9294
|
+
const selfContinuation = priorSelf && stashedThink && registeredEstimate
|
|
9295
|
+
? `【自配档接续·两轮思考读档】你的自配推理等级 \`${priorSelf}\` 与执行前两轮深度思考产物均已登记生效(成员自配为权威)。继续勿重做:直接执行正式任务,不要重新评估复杂度、不要重复提交思考产物。正式执行必须严格按你第二轮理清的方法、流程、步骤进行(你的第一轮产物:${stashedThink.problemAnalysis.join(';').slice(0, 200)}…;你的第二轮产物:${stashedThink.approach.join(';').slice(0, 300)}…),全程少走弯路:先查历史教训、先验证再动手、不重复试错。你的开工预估已登记并送达部门负责人(约 ${registeredEstimate.declaredMinutes} 分钟,整数分钟),无需重复上报。`
|
|
9296
|
+
: (priorSelf
|
|
9297
|
+
? `【自配档接续】你的自配推理等级 \`${priorSelf}\` 已登记生效(成员自配为权威)。继续勿重做:直接执行正式任务,不要重新评估复杂度。`
|
|
9298
|
+
: '')
|
|
9299
|
+
const promptText = leafPhaseZero ? buildPhaseZeroDelegateePrompt({
|
|
9300
|
+
departmentLabel,
|
|
9301
|
+
member: assignment,
|
|
9302
|
+
cwd: cwd ?? '',
|
|
9303
|
+
...(retryBrief ? { extraContext: retryBrief } : {}),
|
|
9304
|
+
}) : buildDelegateePrompt({
|
|
9305
|
+
departmentLabel,
|
|
9306
|
+
leaderSubtaskId: subtaskId,
|
|
9307
|
+
leaderSubtaskTitle: String(row.title ?? ''),
|
|
9308
|
+
member: assignment,
|
|
9309
|
+
rulesBrief,
|
|
9310
|
+
cwd: cwd ?? '',
|
|
9311
|
+
leadSessionId: childSession.id,
|
|
9312
|
+
...(retryBrief || selfContinuation ? { extraContext: [selfContinuation, retryBrief].filter(Boolean).join('\n') } : {}),
|
|
9313
|
+
})
|
|
9314
|
+
let childId: string | null = null
|
|
9315
|
+
let memberStatus = 'running'
|
|
9316
|
+
let memberError: string | null = null
|
|
9317
|
+
try {
|
|
9318
|
+
// [2.5.5][治本] 同 executeSubtask:spec 顶层契约(prompt/parent/cwd/agentOptions/maxDepth)。
|
|
9319
|
+
const activation = await ctx.subagents.startActivation({
|
|
9320
|
+
provider: 'spawn',
|
|
9321
|
+
label: `${row.department}:${subtaskId}→${assignment.member}`.slice(0, 120),
|
|
9322
|
+
prompt: [{ type: 'text', text: promptText }],
|
|
9323
|
+
parent: agent,
|
|
9324
|
+
cwd,
|
|
9325
|
+
agentOptions: {
|
|
9326
|
+
...(modelSelection?.provider && modelSelection?.model
|
|
9327
|
+
? { provider: modelSelection.provider, model: modelSelection.model }
|
|
9328
|
+
: {}),
|
|
9329
|
+
// [2.5.0][自配档] phase-0 强制 low;phase-1 用成员自配档(权威)。
|
|
9330
|
+
reasoningEffort: leafPhaseZero ? 'low' : priorSelf,
|
|
9331
|
+
},
|
|
9332
|
+
// 成员在 depth 2;任何第四层(depth 3)被宿主绝对深度上限硬拒。
|
|
9333
|
+
maxDepth: 2,
|
|
9334
|
+
signal,
|
|
9335
|
+
delivery: 'caller',
|
|
9336
|
+
})
|
|
9337
|
+
childId = typeof activation?.childId === 'string' ? activation.childId : null
|
|
9338
|
+
if (activation && typeof activation.result?.then === 'function') {
|
|
9339
|
+
const settledChildId = childId
|
|
9340
|
+
// [T8] 结算回调异步化:完成即时通知经 sendMessage 定向投递(T5 契约)。
|
|
9341
|
+
activation.result.then(async (outcome: any) => {
|
|
9342
|
+
try {
|
|
9343
|
+
const completed = outcome?.stopReason === 'completed'
|
|
9344
|
+
// [3.0.0] F10:专家汇报入口强制核验(adjudicateExpertReport),
|
|
9345
|
+
// 未过即退回(failed + F10 拒因),绝不记 done。
|
|
9346
|
+
const f10 = completed ? adjudicateExpertReport(outcome) : { ok: true as const }
|
|
9347
|
+
const settledDone = completed && f10.ok
|
|
9348
|
+
const current = (record.statuses ?? []).find((item: any) => item?.subtaskId === subtaskId)
|
|
9349
|
+
const list = (Array.isArray(current?.delegates) ? current.delegates : [])
|
|
9350
|
+
.map((item: any) => (item?.childId === settledChildId
|
|
9351
|
+
/*
|
|
9352
|
+
* [2.5.6] 待指示优先于结算:叶子请示后结束回合(stopReason
|
|
9353
|
+
* 可能是 completed),但请示还没被负责人答复——结算不得把
|
|
9354
|
+
* escalated 覆盖成 done/failed,否则「待指示」凭空消失。
|
|
9355
|
+
* 负责人 instruct 投递后叶子恢复执行,正常结算再收敛。
|
|
9356
|
+
*/
|
|
9357
|
+
? (item?.escalation
|
|
9358
|
+
? item
|
|
9359
|
+
: {
|
|
9360
|
+
...item,
|
|
9361
|
+
status: settledDone ? 'done' : 'failed',
|
|
9362
|
+
closure: null,
|
|
9363
|
+
summary: truncate(resultText(outcome), 300),
|
|
9364
|
+
error: settledDone ? null : truncate(f10.ok ? String(outcome?.diagnostic ?? `子会话结束状态 ${outcome?.stopReason}`) : f10.rejection, 300),
|
|
9365
|
+
finishedAt: Date.now(),
|
|
9366
|
+
})
|
|
9367
|
+
: item))
|
|
9368
|
+
const revision = Number(current?.revision ?? 0) + 1
|
|
9369
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision, updatedBy: 'child' })
|
|
9370
|
+
record.updatedAt = Date.now()
|
|
9371
|
+
appendUserMessage(parentSession, buildUpdateMessage({
|
|
9372
|
+
planId: record.plan.planId,
|
|
9373
|
+
subtaskId,
|
|
9374
|
+
status: current?.status ?? row.status,
|
|
9375
|
+
delegates: list,
|
|
9376
|
+
revision,
|
|
9377
|
+
}))
|
|
9378
|
+
// [T8] 完成即时通知 → 原分派负责人会话(row.childId):done-only、
|
|
9379
|
+
// report.state='sent' 幂等、投递失败留 failed 待兜底补发,绝不回滚结算。
|
|
9380
|
+
await emitDelegateDoneNotices(record, (ctx as any).sessions?.get?.(String(row.childId ?? '')) ?? childSession, parentSession, subtaskId)
|
|
9381
|
+
} catch {
|
|
9382
|
+
// 结算留痕失败不影响主链路:看板下次刷新按内存行渲染。
|
|
9383
|
+
}
|
|
9384
|
+
}).catch(() => {})
|
|
9385
|
+
}
|
|
9386
|
+
} catch (error: any) {
|
|
9387
|
+
memberStatus = 'rejected'
|
|
9388
|
+
memberError = truncate(String(error?.message ?? error), 300)
|
|
9389
|
+
}
|
|
9390
|
+
delegates.push({
|
|
9391
|
+
member: assignment.member,
|
|
9392
|
+
role: assignment.role,
|
|
9393
|
+
task: assignment.task,
|
|
9394
|
+
effort: assignment.effort,
|
|
9395
|
+
...(assignment.requested && assignment.requested !== assignment.effort ? { requested: assignment.requested } : {}),
|
|
9396
|
+
childId,
|
|
9397
|
+
status: memberStatus,
|
|
9398
|
+
summary: '',
|
|
9399
|
+
error: memberError,
|
|
9400
|
+
startedAt: Date.now(),
|
|
9401
|
+
finishedAt: null,
|
|
9402
|
+
})
|
|
9403
|
+
}
|
|
9404
|
+
// [2.5.4][T3R1] 分派门禁放行留痕(A3):并入台账 persist,同一动作不二次
|
|
9405
|
+
// persist(避免 revision 竞争);gateAudit 经 applyStatus 消毒 + durable 回放。
|
|
9406
|
+
const written = persist({
|
|
9407
|
+
delegates,
|
|
9408
|
+
gateAudit: [...(Array.isArray(row.gateAudit) ? row.gateAudit : []), { at: Date.now(), action: 'dispatch', ok: true, code: null }].slice(-20),
|
|
9409
|
+
})
|
|
9410
|
+
const rejected = delegates.filter((item) => item.status === 'rejected')
|
|
6871
9411
|
return {
|
|
6872
|
-
ok:
|
|
9412
|
+
ok: rejected.length < delegates.length,
|
|
6873
9413
|
planId: record.plan.planId,
|
|
6874
9414
|
subtaskId,
|
|
6875
|
-
|
|
6876
|
-
|
|
6877
|
-
|
|
6878
|
-
|
|
6879
|
-
|
|
6880
|
-
|
|
6881
|
-
|
|
6882
|
-
? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
|
|
6883
|
-
: '已记录处置结果;交付阻塞按最新状态重新计算。',
|
|
9415
|
+
action,
|
|
9416
|
+
delegates: written?.delegates ?? delegates,
|
|
9417
|
+
clamped: delegationPlan.clamped,
|
|
9418
|
+
taskEffort: delegationPlan.taskEffort,
|
|
9419
|
+
effortOverride: written?.effortOverride ?? row.effortOverride ?? null,
|
|
9420
|
+
...(rejected.length ? { rejected: rejected.map((item) => ({ member: item.member, error: item.error })) } : {}),
|
|
9421
|
+
hint: '第三层已派发(一层下级、叶子层,第四层会被硬拒)。每位全球顶尖专家的完成结论会送回本会话(delivery=caller);收齐后由你汇总核验,再写最终结果块。用 action="status" 查看进度。成员遇阻会经 dsh_workplan_escalate 在你这里落「待指示」(delegates[].closure=escalated):必须当轮用 dsh_workplan_instruct(subtaskId=本部门行 ID,多个成员同时请示时加 member)答复,投递成功后该成员恢复执行。',
|
|
6884
9422
|
}
|
|
6885
9423
|
}
|
|
6886
9424
|
|
|
@@ -6972,6 +9510,60 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
6972
9510
|
: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
|
|
6973
9511
|
}
|
|
6974
9512
|
}
|
|
9513
|
+
/*
|
|
9514
|
+
* [2.5.1] 主 Agent 两轮深度思考协议硬门禁(用户 2026-11-11 补充要求)。
|
|
9515
|
+
*
|
|
9516
|
+
* 主 Agent 执行自己的任务同样必须:先全面、全盘、深入梳理、研究、思考
|
|
9517
|
+
* 自己的任务(第一轮),再基于第一轮完成好的所有结果再全面、全盘、深入
|
|
9518
|
+
* 地开展梳理、研究和思考,理清方法、流程和步骤(第二轮),最后才基于
|
|
9519
|
+
* 第二轮的方法、流程、步骤开始具体执行——派发就是主 Agent 执行的起点,
|
|
9520
|
+
* 因此首次派发必须随附 deepThink 产物,未交/不合格硬拒,提示词绕不过。
|
|
9521
|
+
*
|
|
9522
|
+
* 落点=已通过 NO_PLAN / PLAN_ID_MISMATCH / 终态闸门之后、派发预告与任何
|
|
9523
|
+
* 子 Agent 启动之前:拒绝不产生副作用,也不刷派发预告。登记后持久化
|
|
9524
|
+
* (record + durable workplan-update),续跑/重试/join/重启回放读档放行;
|
|
9525
|
+
* 产物按 planId 记账——重规划换新计划是新任务,必须重新两轮思考。
|
|
9526
|
+
*/
|
|
9527
|
+
if (!record.mainDeepThink || record.mainDeepThinkPlanId !== record.plan.planId) {
|
|
9528
|
+
const deepThinkCheck = validateMainDeepThink(args?.deepThink)
|
|
9529
|
+
if (!deepThinkCheck.ok) {
|
|
9530
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
9531
|
+
return {
|
|
9532
|
+
ok: false,
|
|
9533
|
+
planId: record.plan.planId,
|
|
9534
|
+
phase: record.phase,
|
|
9535
|
+
running: false,
|
|
9536
|
+
alreadyRunning: false,
|
|
9537
|
+
complete: false,
|
|
9538
|
+
remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
|
|
9539
|
+
stats: snapshot.stats,
|
|
9540
|
+
code: deepThinkCheck.code,
|
|
9541
|
+
error: deepThinkCheck.error,
|
|
9542
|
+
hint: '先完成两轮深度思考再派发:第一轮全面、全盘、深入梳理研究思考自己的任务,第二轮基于第一轮全部结果理清方法、流程、步骤(含依据 approachBasis),随 dsh_workplan_dispatch 的 deepThink 参数提交;登记后续跑/重启自动读档,无需重复提交。',
|
|
9543
|
+
}
|
|
9544
|
+
}
|
|
9545
|
+
record.mainDeepThink = deepThinkCheck.deepThink
|
|
9546
|
+
record.mainDeepThinkPlanId = record.plan.planId
|
|
9547
|
+
// durable 持久化(计划级字段,subtaskId=null 不落任何子任务行);回放消费端同口径消毒。
|
|
9548
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
9549
|
+
planId: record.plan.planId,
|
|
9550
|
+
subtaskId: null,
|
|
9551
|
+
mainDeepThink: deepThinkCheck.deepThink,
|
|
9552
|
+
mainDeepThinkPlanId: record.plan.planId,
|
|
9553
|
+
}))
|
|
9554
|
+
}
|
|
9555
|
+
/*
|
|
9556
|
+
* [2.3.10][T2] 用户要求1(P2):派发前会话内预告执行耗时。落点=已通过
|
|
9557
|
+
* 全部拒绝闸门(NO_PLAN / PLAN_ID_MISMATCH / 终态)、尚未启动任何子 Agent。
|
|
9558
|
+
* 幂等守卫:同一 planId 只预告一次——dispatch 工具契约是重复调用幂等,
|
|
9559
|
+
* 续跑/重复派发/join 在途回合都不得重复刷屏;重规划换新 planId 时自然
|
|
9560
|
+
* 重新预告。只追加 notice,不改派发语义与任何返回体。
|
|
9561
|
+
*/
|
|
9562
|
+
if (record.preAnnouncedPlanId !== record.plan.planId) {
|
|
9563
|
+
record.preAnnouncedPlanId = record.plan.planId
|
|
9564
|
+
const preAnnouncement = buildDispatchPreAnnouncement(record.plan)
|
|
9565
|
+
if (preAnnouncement) appendUserMessage(session, preAnnouncement)
|
|
9566
|
+
}
|
|
6975
9567
|
/*
|
|
6976
9568
|
* [1.7.0] Two dispatch modes.
|
|
6977
9569
|
*
|
|
@@ -7094,11 +9686,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
7094
9686
|
cwd: session.header?.cwd ?? options.cwd,
|
|
7095
9687
|
conversationContext: record.conversationContext ?? '',
|
|
7096
9688
|
/*
|
|
7097
|
-
* [
|
|
7098
|
-
*
|
|
7099
|
-
*
|
|
9689
|
+
* [T9][用户要求6] 两种模式都推完成即时汇报:各部门负责人任务完成必须
|
|
9690
|
+
* 立刻、独立地向主 Agent 汇报,不分 wait/async(2.2.0「wait 不推」语义
|
|
9691
|
+
* 由 T9 取代)。即时通知是纯文本 user/message、不带 workplan 标记,
|
|
9692
|
+
* 不是轮级结果消息——「每轮恰 1 条持久结果消息」断言不受影响。
|
|
9693
|
+
* 结算备份采纳路径(settleFromOutput 同一 options)因此同样覆盖。
|
|
7100
9694
|
*/
|
|
7101
|
-
notifyCompletion:
|
|
9695
|
+
notifyCompletion: true,
|
|
7102
9696
|
onSubtaskDone: (recordArg: any, subtask: any, verdict: any) =>
|
|
7103
9697
|
emitSubtaskDoneNotice(recordArg, session, subtask, verdict),
|
|
7104
9698
|
}
|
|
@@ -8163,6 +10757,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
8163
10757
|
statusTool,
|
|
8164
10758
|
followupTool,
|
|
8165
10759
|
escalateTool,
|
|
10760
|
+
// [2.3.9][T4b] 第三层派发(部门负责人专用):review 梳理门禁 → dispatch 全球顶尖专家。
|
|
10761
|
+
delegateTool,
|
|
8166
10762
|
verifyTool: verifySubtask,
|
|
8167
10763
|
lessonsTool,
|
|
8168
10764
|
instructTool,
|
|
@@ -8218,8 +10814,20 @@ function resolveModelSelection(ctx: any, payload: any) {
|
|
|
8218
10814
|
|
|
8219
10815
|
async function maybePlan(ctx: any, state: any, payload: any, downstream: any, options: any) {
|
|
8220
10816
|
const session = payload.agent?.session
|
|
8221
|
-
if (!session
|
|
10817
|
+
if (!session) return downstream
|
|
10818
|
+
/*
|
|
10819
|
+
* [2.5.5][T10] 每个 pre-step 先把该会话缓冲的台账合并落盘:合并闸把有界延迟
|
|
10820
|
+
* 从「整轮」缩短到一个 step,进程崩溃最多丢当前 step 未落盘的台账。
|
|
10821
|
+
*/
|
|
10822
|
+
try {
|
|
10823
|
+
flushPendingWorkplanUpdates(session)
|
|
10824
|
+
} catch {
|
|
10825
|
+
/* 合并失败不拦规划:下一次落盘/结算再试。 */
|
|
10826
|
+
}
|
|
10827
|
+
if (!isRootSession(session)) return downstream
|
|
8222
10828
|
if (payload.step !== 1) return downstream
|
|
10829
|
+
// [2.5.5][T3] pre-step 窗口标记:规划/自动派发的头前通知一律暂存(治本)。
|
|
10830
|
+
enterPreHeadWindow(session)
|
|
8223
10831
|
const planMode = isPlanModeActive(ctx, session)
|
|
8224
10832
|
const human = humanMessages(payload.messages)
|
|
8225
10833
|
const existing = state.records.get(session.id)
|
|
@@ -8239,7 +10847,8 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8239
10847
|
*
|
|
8240
10848
|
* `agent/turn-stopping` must only object on turns whose plan belongs to the
|
|
8241
10849
|
* user's actual request. A plan left paused in an earlier turn must not turn
|
|
8242
|
-
* every later "谢谢/进度如何" turn into a forced
|
|
10850
|
+
* every later "谢谢/进度如何" turn into a forced dispatch(现行轮次预算默认
|
|
10851
|
+
* 关闭,TOTAL_TIMEOUT_MS=0;此处只拦「带真实任务文本的轮次」),so the
|
|
8243
10852
|
* stop gate reads this marker and stays silent on social or status turns.
|
|
8244
10853
|
*/
|
|
8245
10854
|
if (!state.activeTurns) state.activeTurns = new Map()
|
|
@@ -8417,6 +11026,24 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8417
11026
|
createdTurn: payload.turn,
|
|
8418
11027
|
}
|
|
8419
11028
|
state.records.set(session.id, planningRecord)
|
|
11029
|
+
/*
|
|
11030
|
+
* [2.3.10][T2] 用户要求1(P1):规划前会话内预告规划耗时。此前该时点只有
|
|
11031
|
+
* 侧栏占位卡、无会话输出(T1 E6);现在在 runPlanner 之前经唯一合规写入器
|
|
11032
|
+
* appendUserMessage 发一条【规划预告】。预估与 runPlanner 同源:同一个
|
|
11033
|
+
* normalisePlannerWindow 解析出的实际窗口(含配置/环境变量覆盖)。
|
|
11034
|
+
*/
|
|
11035
|
+
/*
|
|
11036
|
+
* [3.0.0][用户要求 2] 从接收到用户任何任务开始,会话内必须输出固定文案
|
|
11037
|
+
* 「任务正在分配中,请稍等一下......」。逐字冻结文案来自 v3-contract,
|
|
11038
|
+
* 与用户原文逐字一致(6 个半角点),不得拼接、不得改写。
|
|
11039
|
+
* 位置:任何规划动作之前(含规划预告之前),保证用户先看到「正在分配」。
|
|
11040
|
+
* deferUntilHead:受保护系统头未落地前暂存,落地后按序补发(2.5.5 治本)。
|
|
11041
|
+
*/
|
|
11042
|
+
appendUserMessage(session, STATUS_ASSIGNING_TEXT, undefined, { deferUntilHead: true })
|
|
11043
|
+
appendUserMessage(session, buildPlanningPreAnnouncement(
|
|
11044
|
+
normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
|
|
11045
|
+
PLANNER_MAX_ATTEMPTS,
|
|
11046
|
+
), undefined, { deferUntilHead: true })
|
|
8420
11047
|
/*
|
|
8421
11048
|
* [2.2.5][T5] 进度回调落点(T1 P-6 / T3 §3 C2/C3、§4 频率规则):
|
|
8422
11049
|
* 通道 A = 占位卡片 errors 区追加重试摘要(≤2 行,保底通道);通道 B =
|
|
@@ -8424,13 +11051,70 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8424
11051
|
* 文案组装与频率硬规则全部在 createPlannerProgressReporter / plannerProgressLines
|
|
8425
11052
|
* (plan.ts,可独立回归);这里只注入宿主交互面。
|
|
8426
11053
|
*/
|
|
11054
|
+
/*
|
|
11055
|
+
* [3.0.0][用户要求 1 / 2 治本 —— 依据 T4 根因报告(reports/T4b-会话内容丢失根因报告-20261114.md)]
|
|
11056
|
+
*
|
|
11057
|
+
* 缺陷实证(T4,3497 个会话 / 4034 轮对照):宿主在 pre-step 之前就认领
|
|
11058
|
+
* 用户消息,人类 user/message 只在首个 model step 内部落盘;而本插件在
|
|
11059
|
+
* pre-step 里 `await runPlanner`,把这一步推迟到分钟级(含规划轮的轮次
|
|
11060
|
+
* p50=58.4s、p90=250s,不含的 p50=0.04s)。这段时间里会话日志没有任何
|
|
11061
|
+
* 可渲染的任务正文,屏幕上唯一副本是客户端回声,而客户端在收到回执后
|
|
11062
|
+
* 无条件退休该回声——于是「切走会话再切回」就看不到用户刚输入的任务。
|
|
11063
|
+
*
|
|
11064
|
+
* 治本:pre-step 不再等待规划。先同步放行本步(模型立即看到「正在分配」
|
|
11065
|
+
* 的注入说明,不会自己去执行用户任务),规划转后台继续:计划一成即经唯一
|
|
11066
|
+
* 合规写入器 appendUserMessage 写入会话并按既有路径自动派发。这样首 step
|
|
11067
|
+
* 在秒级启动 → 宿主立即落盘人类消息、暂存的通知按序补发,任务正文与固定
|
|
11068
|
+
* 文案都在切会话前后稳定可见。
|
|
11069
|
+
*
|
|
11070
|
+
* 中止语义不变:仍沿用本步的 payload.signal(宿主只在 cancel/中断时 abort
|
|
11071
|
+
* 该信号,正常收尾不 abort),用户中断时后台规划与以前一样静默退出。
|
|
11072
|
+
* 幂等:同一会话已有规划在跑时直接放行本步,不会重复规划。
|
|
11073
|
+
*/
|
|
11074
|
+
const deliver = (messages: any[]) => {
|
|
11075
|
+
for (const message of messages) {
|
|
11076
|
+
try {
|
|
11077
|
+
/*
|
|
11078
|
+
* 后台路径没有 pre-step 的返回值可用,只能写进会话(append-only)。
|
|
11079
|
+
* deferUntilHead 由 appendUserMessage 自身按「受保护系统头是否已落地」
|
|
11080
|
+
* 判定,与本步的窗口标记无关,因此不会写出头前 surface。
|
|
11081
|
+
*/
|
|
11082
|
+
appendUserMessage(session, message)
|
|
11083
|
+
} catch (error) {
|
|
11084
|
+
pushRecordError(planningRecord, error)
|
|
11085
|
+
}
|
|
11086
|
+
}
|
|
11087
|
+
}
|
|
11088
|
+
if (!state.planningInFlight) state.planningInFlight = new Map()
|
|
11089
|
+
if (state.planningInFlight.has(session.id)) return downstream
|
|
11090
|
+
state.planningInFlight.set(session.id, planningStartedAt)
|
|
11091
|
+
const runPlanningInBackground = async (): Promise<void> => {
|
|
11092
|
+
let plannerAttempt = 1
|
|
8427
11093
|
const onPlannerProgress = createPlannerProgressReporter({
|
|
8428
11094
|
signal: payload.signal,
|
|
8429
11095
|
record: planningRecord,
|
|
8430
11096
|
setRecord: (record: any) => state.records.set(session.id, record),
|
|
8431
|
-
appendNotice: (text: string) => appendUserMessage(session, text),
|
|
11097
|
+
appendNotice: (text: string) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
|
|
11098
|
+
maxAttempts: PLANNER_MAX_ATTEMPTS,
|
|
11099
|
+
})
|
|
11100
|
+
/*
|
|
11101
|
+
* [2.5.2] 规划期间心跳(治本:用户 2026-11-11 报告本会话 turn 1 规划 12.5
|
|
11102
|
+
* 分钟全程零会话输出、以为死机并手动中断)。失败重试回报器只在「失败且
|
|
11103
|
+
* 退避重试」时发通知;一次持续流式但很慢的尝试不失败也不触发 idle,于是
|
|
11104
|
+
* 预告之后整段静默。心跳与重试正交:只要 runPlanner 还在跑,就按固定间隔
|
|
11105
|
+
* 经唯一合规写入器发一条「仍在生成、已用时多久、不是卡死」的可见通知。
|
|
11106
|
+
* 写入仍是 user/message(surfaceOp:'append'、形状校验),不新增事件类型、
|
|
11107
|
+
* 不触碰 system/message,不会引入会话日志损坏;finally 里 stop,绝不残留。
|
|
11108
|
+
*/
|
|
11109
|
+
const planningHeartbeat = createPlanningHeartbeat({
|
|
11110
|
+
signal: payload.signal,
|
|
11111
|
+
appendNotice: (text: string) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
|
|
11112
|
+
intervalMs: planningHeartbeatIntervalMs(process.env.DSH_WORKPLAN_PLANNING_HEARTBEAT_MS ?? PLANNING_HEARTBEAT_MS),
|
|
11113
|
+
startedAt: planningStartedAt,
|
|
11114
|
+
getAttempt: () => plannerAttempt,
|
|
8432
11115
|
maxAttempts: PLANNER_MAX_ATTEMPTS,
|
|
8433
11116
|
})
|
|
11117
|
+
planningHeartbeat.start()
|
|
8434
11118
|
try {
|
|
8435
11119
|
plan = await runPlanner(ctx, {
|
|
8436
11120
|
taskText,
|
|
@@ -8442,7 +11126,15 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8442
11126
|
plannerIdleTimeoutMs: normalisePlannerWindow(options?.limits?.plannerIdleTimeoutMs ?? options?.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
|
|
8443
11127
|
telemetry: plannerTelemetry,
|
|
8444
11128
|
// [2.2.5][T5] 分解期间进度事件(T1 P-6):只追加观察回调,不改重试语义。
|
|
8445
|
-
onProgress:
|
|
11129
|
+
onProgress: (report: any) => {
|
|
11130
|
+
// [2.5.2] 顺带记录当前尝试序号,供心跳文案显示「第 N/M 次尝试」。
|
|
11131
|
+
const failedAttempt = Number(report?.attempt) || 0
|
|
11132
|
+
if (failedAttempt > 0) {
|
|
11133
|
+
const willRetry = Number(report?.retryBackoffMs) > 0 && failedAttempt < PLANNER_MAX_ATTEMPTS
|
|
11134
|
+
plannerAttempt = Math.min(PLANNER_MAX_ATTEMPTS, willRetry ? failedAttempt + 1 : failedAttempt)
|
|
11135
|
+
}
|
|
11136
|
+
onPlannerProgress(report)
|
|
11137
|
+
},
|
|
8446
11138
|
conversationContext,
|
|
8447
11139
|
sourceMessageIds: human.map((message: any) => message.id).filter((id: any) => typeof id === 'string'),
|
|
8448
11140
|
/*
|
|
@@ -8469,7 +11161,35 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8469
11161
|
* 终态进度从内存里挤掉(旧实现中止路径不写记录,此行为保持不变)。
|
|
8470
11162
|
*/
|
|
8471
11163
|
if (existing?.plan) state.records.set(session.id, existing)
|
|
8472
|
-
return
|
|
11164
|
+
return
|
|
11165
|
+
}
|
|
11166
|
+
/*
|
|
11167
|
+
* [3.0.1] 规划守卫判定「只有用户能答复」(CLARIFY_NEEDED):与规划前的
|
|
11168
|
+
* C1–C4 澄清闸同一条出口——写 clarify 记录、把问题原样转给用户、本轮回合
|
|
11169
|
+
* 直接结束。不降级、不生成计划、不派发;用户的下一条答复会带着答案重新
|
|
11170
|
+
* 进入规划。在降级路径之前拦截,否则这里会把「等用户」误报成「分解失败」。
|
|
11171
|
+
*/
|
|
11172
|
+
if (error instanceof PlanError && error.code === 'CLARIFY_NEEDED') {
|
|
11173
|
+
const createdAt = Date.now()
|
|
11174
|
+
state.records.set(session.id, {
|
|
11175
|
+
planId: null,
|
|
11176
|
+
plan: null,
|
|
11177
|
+
title: '任务信息不足(先澄清)',
|
|
11178
|
+
degraded: false,
|
|
11179
|
+
clarify: true,
|
|
11180
|
+
error: error.message,
|
|
11181
|
+
statuses: [],
|
|
11182
|
+
phase: 'clarify',
|
|
11183
|
+
errors: [truncate(error.message, 1000)],
|
|
11184
|
+
createdAt,
|
|
11185
|
+
updatedAt: createdAt,
|
|
11186
|
+
createdTurn: payload.turn,
|
|
11187
|
+
})
|
|
11188
|
+
return enterDecision(downstream, [buildClarifyMessage({
|
|
11189
|
+
rule: 'AUDIT',
|
|
11190
|
+
reason: error.message,
|
|
11191
|
+
question: typeof error.details === 'string' && error.details.trim() !== '' ? error.details : '',
|
|
11192
|
+
})])
|
|
8473
11193
|
}
|
|
8474
11194
|
const planId = `wp-${randomUUID()}`
|
|
8475
11195
|
const createdAt = Date.now()
|
|
@@ -8496,13 +11216,16 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8496
11216
|
updatedAt: createdAt,
|
|
8497
11217
|
createdTurn: payload.turn,
|
|
8498
11218
|
})
|
|
8499
|
-
return
|
|
11219
|
+
return deliver([message])
|
|
11220
|
+
} finally {
|
|
11221
|
+
// [2.5.2] 无论成功/降级/中止,规划结束即停心跳,绝不残留定时器。
|
|
11222
|
+
planningHeartbeat.stop()
|
|
8500
11223
|
}
|
|
8501
11224
|
|
|
8502
11225
|
if (payload.signal.aborted) {
|
|
8503
11226
|
// [2.2.5][T5] 计划已生成但回合被中止:同中止分支,恢复旧记录再静默退出。
|
|
8504
11227
|
if (existing?.plan) state.records.set(session.id, existing)
|
|
8505
|
-
return
|
|
11228
|
+
return
|
|
8506
11229
|
}
|
|
8507
11230
|
const planId = `wp-${randomUUID()}`
|
|
8508
11231
|
const createdAt = Date.now()
|
|
@@ -8536,10 +11259,6 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8536
11259
|
* plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
|
|
8537
11260
|
*/
|
|
8538
11261
|
const autoDispatched = !planMode && options?.autoDispatch !== false
|
|
8539
|
-
if (autoDispatched) {
|
|
8540
|
-
record.dispatchedAt = Date.now()
|
|
8541
|
-
state.startAutoDispatch?.(record, session, payload.agent)
|
|
8542
|
-
}
|
|
8543
11262
|
/*
|
|
8544
11263
|
* Plan-first: commit the plan with this step and let the main Agent call
|
|
8545
11264
|
* dsh_workplan_dispatch. Dispatching here would hide the plan until every
|
|
@@ -8560,7 +11279,22 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8560
11279
|
planMode,
|
|
8561
11280
|
autoDispatched,
|
|
8562
11281
|
})
|
|
8563
|
-
|
|
11282
|
+
/*
|
|
11283
|
+
* [3.0.0][顺序] 必须先让计划可见,再开跑、再发「分配完成」:
|
|
11284
|
+
* 用户要求 4 的文案由 dispatchPlan 在真正开跑时写入,若自动派发抢在计划
|
|
11285
|
+
* 消息之前,用户会先看到「分配完成」再看到计划(T6 设计复核 D2)。因此这里
|
|
11286
|
+
* 先 deliver 计划消息,再启动自动派发。
|
|
11287
|
+
*/
|
|
11288
|
+
if (!planMode) {
|
|
11289
|
+
deliver([planMessage])
|
|
11290
|
+
if (autoDispatched) {
|
|
11291
|
+
record.dispatchedAt = Date.now()
|
|
11292
|
+
// [T7] C3 整轮预算:自动派发同样重置(与显式派发同口径)。
|
|
11293
|
+
resetRoundInjectionBudget(session, `${record.plan.planId}:${record.dispatchedAt}`)
|
|
11294
|
+
state.startAutoDispatch?.(record, session, payload.agent)
|
|
11295
|
+
}
|
|
11296
|
+
return
|
|
11297
|
+
}
|
|
8564
11298
|
/*
|
|
8565
11299
|
* Plan mode is a planning-only collaboration state: the plugin must still
|
|
8566
11300
|
* decompose the task and show the plan, but it must not start department
|
|
@@ -8577,9 +11311,33 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
8577
11311
|
}],
|
|
8578
11312
|
source: { kind: 'workplan', form: 'notice', summary: 'plan 模式:计划已生成,等待用户审阅后派发' },
|
|
8579
11313
|
}
|
|
8580
|
-
|
|
11314
|
+
return deliver([planMessage, note])
|
|
11315
|
+
}
|
|
11316
|
+
void (async () => {
|
|
11317
|
+
try {
|
|
11318
|
+
await runPlanningInBackground()
|
|
11319
|
+
} catch (error) {
|
|
11320
|
+
pushRecordError(planningRecord, error)
|
|
11321
|
+
} finally {
|
|
11322
|
+
state.planningInFlight.delete(session.id)
|
|
11323
|
+
}
|
|
11324
|
+
})()
|
|
11325
|
+
/*
|
|
11326
|
+
* 同步注入给本步模型的说明:先等计划,不要自己动手做用户的活。文案复用
|
|
11327
|
+
* 用户逐字冻结的 STATUS_ASSIGNING_TEXT,不另造第二份固定文案。
|
|
11328
|
+
*/
|
|
11329
|
+
return enterDecision(downstream, [makeUserMessage(
|
|
11330
|
+
/*
|
|
11331
|
+
* [3.0.0][不重复] 固定文案已由上面的 appendUserMessage(STATUS_ASSIGNING_TEXT)
|
|
11332
|
+
* 写入会话,这里只给本步模型一条行为说明——绝不第二次复述同一句固定文案,
|
|
11333
|
+
* 否则用户会看到两条一模一样的「任务正在分配中」。
|
|
11334
|
+
*/
|
|
11335
|
+
'(dsh-workplan:任务分解已在后台生成中,计划一生成就立即显示在本会话并自动派发;现在请不要自己动手执行用户任务,也不要提前收尾,先简短告知用户正在分配。)',
|
|
11336
|
+
{ kind: 'workplan', form: 'notice', summary: '任务分解已转为后台生成' },
|
|
11337
|
+
)])
|
|
8581
11338
|
}
|
|
8582
11339
|
|
|
11340
|
+
|
|
8583
11341
|
export function plannerOutputSchema() {
|
|
8584
11342
|
return {
|
|
8585
11343
|
type: 'object',
|