dsh-workplan 1.10.6 → 1.11.1
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 +130 -0
- package/README.en.md +8 -3
- package/README.md +9 -4
- package/client.js +142 -5
- package/docs/collaboration.md +16 -5
- package/docs/departments.md +2 -2
- package/docs/release-record-1.10.6-20261101.md +78 -0
- package/docs/release-record-1.11.0-20261102.md +63 -0
- package/lib/client.js +142 -5
- package/lib/host.js +422 -4
- package/lib/plan.js +869 -37
- package/lib/replan.js +678 -0
- package/lib/runtime.js +1316 -27
- package/package.json +1 -1
- package/src/client.ts +154 -4
- package/src/host.ts +453 -3
- package/src/plan.ts +827 -32
- package/src/replan.ts +708 -0
- package/src/runtime.ts +1305 -26
package/src/runtime.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
aggregateInvariantViolations,
|
|
23
23
|
applyStatus,
|
|
24
24
|
attachPlanMeta,
|
|
25
|
+
blockCancelledDependents,
|
|
25
26
|
buildChildPrompt,
|
|
26
27
|
buildCancelMessage,
|
|
27
28
|
buildDegradedMessage,
|
|
@@ -58,14 +59,30 @@ import {
|
|
|
58
59
|
adjudicateResult,
|
|
59
60
|
activeDenyCode,
|
|
60
61
|
MAX_CONVERSATION_CHARS,
|
|
62
|
+
MAX_ESCALATION_OPTIONS,
|
|
63
|
+
MAX_INSTRUCTION_CHARS,
|
|
64
|
+
MAX_QUESTION_CHARS,
|
|
61
65
|
parseUpdateMessage,
|
|
62
66
|
buildUpdateMessage,
|
|
67
|
+
normaliseHandoffs,
|
|
68
|
+
openHandoffs,
|
|
69
|
+
DEPARTMENTS,
|
|
70
|
+
DEPARTMENT_IDS,
|
|
71
|
+
MAX_HANDOFF_RESPONSE_CHARS,
|
|
63
72
|
} from './plan.js'
|
|
64
73
|
import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
|
|
65
74
|
import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
|
|
66
75
|
import { supersedePlanRecord } from './supersede.js'
|
|
67
76
|
import { createProgressWatchdog, describeError } from './watchdog.js'
|
|
68
77
|
import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js'
|
|
78
|
+
import {
|
|
79
|
+
applyReplanStatuses,
|
|
80
|
+
buildChangeRequestMessage,
|
|
81
|
+
buildReplanMessage,
|
|
82
|
+
parseChangeRequestMessage,
|
|
83
|
+
parseReplanMessage,
|
|
84
|
+
planReplan,
|
|
85
|
+
} from './replan.js'
|
|
69
86
|
|
|
70
87
|
/**
|
|
71
88
|
* [1.8.18] How many subtasks the plan *defines*.
|
|
@@ -81,14 +98,68 @@ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './
|
|
|
81
98
|
* (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
|
|
82
99
|
* `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
|
|
83
100
|
*/
|
|
101
|
+
function expectedAcceptanceOf(plan: any): Record<string, any[]> {
|
|
102
|
+
const out: Record<string, any[]> = {}
|
|
103
|
+
for (const entry of flattenSubtasks(plan)) {
|
|
104
|
+
const id = String(entry?.subtask?.id ?? '')
|
|
105
|
+
if (!id) continue
|
|
106
|
+
out[id] = Array.isArray(entry.subtask.acceptance) ? entry.subtask.acceptance : []
|
|
107
|
+
}
|
|
108
|
+
return out
|
|
109
|
+
}
|
|
110
|
+
|
|
84
111
|
function definedSubtaskCount(plan: any): number {
|
|
85
112
|
try {
|
|
86
|
-
|
|
113
|
+
/*
|
|
114
|
+
* [1.11.0] 被重规划替换/撤销的旧行不占分母。
|
|
115
|
+
*
|
|
116
|
+
* 契约 §7.2 硬规则 2:`cancel` 掉的工作如果仍然计入定义条数,计划就永远
|
|
117
|
+
* 差一项、永远无法交付。标记由 `replan.ts` 写在计划定义上(supersededAt),
|
|
118
|
+
* 与状态条目的 `closure:'replanned'` 是同一次写入的两个镜像。
|
|
119
|
+
*/
|
|
120
|
+
return flattenSubtasks(plan).filter((entry: any) => !entry.subtask?.supersededAt).length
|
|
87
121
|
} catch {
|
|
88
122
|
return Number.MAX_SAFE_INTEGER
|
|
89
123
|
}
|
|
90
124
|
}
|
|
91
125
|
|
|
126
|
+
/**
|
|
127
|
+
* [1.11.0] 可调度/可计数的状态行:排除已被重规划替换或撤销的旧行。
|
|
128
|
+
*
|
|
129
|
+
* `closure` 仍是唯一标记。这里不复制状态的其它字段,只做视图过滤,因此
|
|
130
|
+
* 左侧栏、调度器、交付门禁读到的仍是同一个 `record.statuses` 数组。
|
|
131
|
+
*/
|
|
132
|
+
function liveStatuses(statuses: any) {
|
|
133
|
+
return Array.isArray(statuses)
|
|
134
|
+
? statuses.filter((item: any) => item?.closure !== 'replanned')
|
|
135
|
+
: []
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* [1.11.0] C-17:交付门禁的唯一读取助手——左侧栏、present、收尾闸门、dispatch
|
|
140
|
+
* 返回体都从这里拿 `deliveryReady`,不再各自决定“要不要把记录级事实算进去”。
|
|
141
|
+
*
|
|
142
|
+
* `changeRequest.pending`(执行中收到、尚未重规划的变更)与 `reportPending`
|
|
143
|
+
* (完成结果还没写进会话)只存在于 `record` 而不是 `statuses`,所以必须在
|
|
144
|
+
* 这一层显式传入;`plan.ts` 的 `deliveryReadiness` 因此仍是纯函数。
|
|
145
|
+
*/
|
|
146
|
+
function readinessOf(record: any, snapshot?: any) {
|
|
147
|
+
const snap = snapshot ?? derivePlanSnapshot(
|
|
148
|
+
record?.plan ? blockCancelledDependents(record.plan, record?.statuses) : record?.statuses,
|
|
149
|
+
record?.plan ? definedSubtaskCount(record.plan) : undefined,
|
|
150
|
+
)
|
|
151
|
+
return deliveryReadiness(snap, {
|
|
152
|
+
phase: record?.phase,
|
|
153
|
+
changePending: record?.changeRequest?.status === 'pending',
|
|
154
|
+
reportPending: record?.reportPending === true,
|
|
155
|
+
/*
|
|
156
|
+
* 计划定义的验收标准是交付门的另一半:状态行只回答「子 Agent 说通过
|
|
157
|
+
* 了几条」,这里回答「计划要求的几条有没有被逐条回应」。
|
|
158
|
+
*/
|
|
159
|
+
expectedAcceptance: record?.plan ? expectedAcceptanceOf(record.plan) : undefined,
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
92
163
|
export const PLANNER_TIMEOUT_MS = 120000
|
|
93
164
|
/**
|
|
94
165
|
* Absolute ceiling for one child execution.
|
|
@@ -114,6 +185,30 @@ export const MAX_CHILD_TIMEOUT_MS = 1800000
|
|
|
114
185
|
export const MIN_CHILD_IDLE_MS = 1000
|
|
115
186
|
export const MAX_CHILD_IDLE_MS = 900000
|
|
116
187
|
export const CHILD_POLL_MS = 2000
|
|
188
|
+
/*
|
|
189
|
+
* [1.11.0] 派发回执的两个窗口(T4 B1/B2)。
|
|
190
|
+
*
|
|
191
|
+
* `assigned` 只是「已交给子会话」,不等于「子会话已经动了」。收不到回执时
|
|
192
|
+
* 静默等到空闲窗口(默认 300s)会把「根本没启动」和「在慢慢想」混为一谈:
|
|
193
|
+
* 90s 先标记 ackOverdue 让看板可见,180s 仍无任何新事件就按 no-ack 收束,
|
|
194
|
+
* 不再无限等待。
|
|
195
|
+
*/
|
|
196
|
+
export const ASSIGN_ACK_NOTICE_MS = 90000
|
|
197
|
+
export const ASSIGN_ACK_DEADLINE_MS = 180000
|
|
198
|
+
/*
|
|
199
|
+
* [1.11.0] 指示回执的两个窗口(T4 B5)。
|
|
200
|
+
*
|
|
201
|
+
* `instructed` 只表示「指示已经写进状态行并投递」,不表示子 Agent 已经照做。
|
|
202
|
+
* 60s 没有新事件先标 `instructionOverdue`(看板可见、主 Agent 可催),
|
|
203
|
+
* 180s 仍无增长就按 no-ack 收束,避免「指示已下、那边根本没跑」无限挂起。
|
|
204
|
+
*/
|
|
205
|
+
export const INSTRUCTION_ACK_NOTICE_MS = 60000
|
|
206
|
+
export const INSTRUCTION_ACK_DEADLINE_MS = 180000
|
|
207
|
+
/*
|
|
208
|
+
* 正向回执的观察频率。5s 足以在 60s 提醒前发现「子会话已在动」,同时把
|
|
209
|
+
* 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
|
|
210
|
+
*/
|
|
211
|
+
export const INSTRUCTION_POLL_MS = 5000
|
|
117
212
|
export const TOTAL_TIMEOUT_MS = 1200000
|
|
118
213
|
export const DISPOSE_TIMEOUT_MS = 5000
|
|
119
214
|
export const STALE_PENDING_MS = 10 * 60 * 1000
|
|
@@ -607,6 +702,8 @@ export function timeoutBlockedPatch(subtask: any, cwd: any, message: string, art
|
|
|
607
702
|
return {
|
|
608
703
|
patch: {
|
|
609
704
|
status: 'blocked',
|
|
705
|
+
closure: 'blocked',
|
|
706
|
+
blockedKind: 'timeout',
|
|
610
707
|
progress: 100,
|
|
611
708
|
finishedAt: Date.now(),
|
|
612
709
|
error: message + artifactNote,
|
|
@@ -648,8 +745,31 @@ export function budgetResetError(item: any, subtask: any, cwd: any, artifactExis
|
|
|
648
745
|
* that need the environment: the strict/legacy switch and the file check.
|
|
649
746
|
*/
|
|
650
747
|
function settleFromOutput(record: any, subtask: any, output: any, guard: SubtaskGuard, options: any) {
|
|
651
|
-
|
|
748
|
+
/*
|
|
749
|
+
* [1.11.0] 已经升级的请示不能被收尾正文覆盖。
|
|
750
|
+
*
|
|
751
|
+
* `dsh_workplan_escalate` 在子会话中途就写下了 blocked + escalated。子 Agent
|
|
752
|
+
* 随后仍可能补一段结果块(甚至写 done),如果这里照常 adjudicate,就会把
|
|
753
|
+
* 「等人拍板」洗成「完成/普通失败」,提问也随之丢失。升级一旦写入,本轮
|
|
754
|
+
* 的最终判定只能保留它。
|
|
755
|
+
*/
|
|
756
|
+
const current = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
757
|
+
if (current?.closure === 'escalated') return { status: 'blocked', escalated: true }
|
|
758
|
+
const verdict = adjudicateResult({
|
|
759
|
+
output,
|
|
760
|
+
strict: options.strictEvidence !== false,
|
|
761
|
+
/*
|
|
762
|
+
* [1.11.0] 计划验收进入裁决(T5 C4 / T10 D-01)。
|
|
763
|
+
*
|
|
764
|
+
* 不传这一项时,子 Agent 可以用一条自创验收项绕过整张验收表;传了之后
|
|
765
|
+
* 「5 条只回 1 条」会在收尾时直接变成 blocked/unverified,而不是等到
|
|
766
|
+
* 交付才被用户发现。
|
|
767
|
+
*/
|
|
768
|
+
expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
|
|
769
|
+
})
|
|
652
770
|
const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists)
|
|
771
|
+
const escalated = verdict.status === 'blocked'
|
|
772
|
+
&& typeof verdict.question === 'string' && verdict.question.trim() !== ''
|
|
653
773
|
writeSubtaskStatus(record, subtask.id, {
|
|
654
774
|
status: verdict.status,
|
|
655
775
|
progress: 100,
|
|
@@ -661,13 +781,40 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
|
|
|
661
781
|
artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
|
|
662
782
|
missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
|
|
663
783
|
needs: verdict.needs.length > 0 ? verdict.needs : undefined,
|
|
784
|
+
/*
|
|
785
|
+
* [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
|
|
786
|
+
* `question` 就是同一条请示。它仍然写成 blocked 投影,但 closure 是
|
|
787
|
+
* escalated,看板与主 Agent 看到的都是「等指示」而不是普通失败。
|
|
788
|
+
*/
|
|
789
|
+
...(escalated
|
|
790
|
+
? {
|
|
791
|
+
closure: 'escalated',
|
|
792
|
+
blockedKind: 'escalated',
|
|
793
|
+
question: verdict.question,
|
|
794
|
+
options: verdict.options,
|
|
795
|
+
escalatedAt: Date.now(),
|
|
796
|
+
escalationSeq: Number(current?.revision ?? 0) + 1,
|
|
797
|
+
}
|
|
798
|
+
: verdict.status === 'done'
|
|
799
|
+
/*
|
|
800
|
+
* [1.11.0] 完成必须落到 `closure:'done'`,不是 `blocked`。
|
|
801
|
+
*
|
|
802
|
+
* T9 的 P1 探针抓到过这里:完成路径固定写 `blocked/failed`,于是
|
|
803
|
+
* `done` 在执行路径不可达,「完成未回报」门禁与 `reportPending` 全部
|
|
804
|
+
* 恒不成立,进度栏也只能显示「失败」。完成与受阻是两种语义,必须分开。
|
|
805
|
+
*/
|
|
806
|
+
? { closure: 'done', blockedKind: null }
|
|
807
|
+
: {
|
|
808
|
+
closure: 'blocked',
|
|
809
|
+
blockedKind: 'failed',
|
|
810
|
+
}),
|
|
664
811
|
}, guard)
|
|
665
812
|
if (verdict.status === 'blocked') {
|
|
666
|
-
recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard)
|
|
813
|
+
recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (verdict.error ?? '未完成'), guard)
|
|
667
814
|
} else if (checked.missingArtifacts.length > 0) {
|
|
668
815
|
recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard)
|
|
669
816
|
}
|
|
670
|
-
return verdict
|
|
817
|
+
return { ...verdict, escalated }
|
|
671
818
|
}
|
|
672
819
|
|
|
673
820
|
/**
|
|
@@ -749,6 +896,9 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
749
896
|
if (parentSignal.aborted) throw abortError()
|
|
750
897
|
if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
|
|
751
898
|
let activation: any = null
|
|
899
|
+
// Declared outside the try so the per-attempt finally can always cancel
|
|
900
|
+
// the receipt timers, even when activation itself failed.
|
|
901
|
+
let clearAckTimers: () => void = () => {}
|
|
752
902
|
try {
|
|
753
903
|
if (child.controller.signal.aborted) {
|
|
754
904
|
throw child.controller.signal.reason ?? abortError()
|
|
@@ -770,6 +920,16 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
770
920
|
title: item.title,
|
|
771
921
|
status: item.status,
|
|
772
922
|
summary: item.summary,
|
|
923
|
+
/*
|
|
924
|
+
* [1.11.0] 跨部门交接物必须能被下游直接消费(用户 m00687)。
|
|
925
|
+
*
|
|
926
|
+
* 只传状态和摘要时,下游部门知道「上游做完了」,却不知道
|
|
927
|
+
* 产物在哪,只能重做或向主 Agent 再提一次需求。这里把上游
|
|
928
|
+
* 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
|
|
929
|
+
*/
|
|
930
|
+
artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
|
|
931
|
+
.filter((artifact: any) => artifact?.exists === true && typeof artifact?.ref === 'string')
|
|
932
|
+
.map((artifact: any) => String(artifact.ref)),
|
|
773
933
|
})),
|
|
774
934
|
cwd: options.cwd,
|
|
775
935
|
conversationContext,
|
|
@@ -791,10 +951,80 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
791
951
|
if (!activation || typeof activation.result?.then !== 'function') {
|
|
792
952
|
throw new PlanError('子 Agent 没有返回可等待的结果', 'NO_ACTIVATION')
|
|
793
953
|
}
|
|
794
|
-
|
|
954
|
+
/*
|
|
955
|
+
* [1.11.0] `assigned` 是「已交给子会话」,不是「子会话已确认」。
|
|
956
|
+
*
|
|
957
|
+
* 旧代码只写 childId + 10%,从这一刻起到子 Agent 真正产出第一个事件
|
|
958
|
+
* 之间没有任何可观察状态:用户看到 10% 长时间不动,也无法区分
|
|
959
|
+
* 「没启动」「启动失败」「在跑一个很长的工具」。这里把派发序号和
|
|
960
|
+
* 回执窗口一起写进状态,后面的 onProgress/定时器才有据可依。
|
|
961
|
+
*/
|
|
962
|
+
const assignedAt = Date.now()
|
|
963
|
+
const dispatchSeq = Number(record.dispatchSeq ?? 0) + 1
|
|
964
|
+
record.dispatchSeq = dispatchSeq
|
|
965
|
+
const assigned = writeSubtaskStatus(record, subtask.id, {
|
|
795
966
|
childId: activation.childId,
|
|
796
967
|
progress: 10,
|
|
968
|
+
closure: 'assigned',
|
|
969
|
+
assignedAt,
|
|
970
|
+
dispatchSeq,
|
|
971
|
+
// A retry is a fresh attempt: no stale receipt or escalation survives it.
|
|
972
|
+
ackedAt: null,
|
|
973
|
+
ackEvidence: undefined,
|
|
974
|
+
ackOverdue: false,
|
|
975
|
+
escalatedAt: null,
|
|
976
|
+
escalationSeq: null,
|
|
977
|
+
question: null,
|
|
978
|
+
options: [],
|
|
979
|
+
blockedKind: null,
|
|
797
980
|
}, guard)
|
|
981
|
+
if (!assigned) return
|
|
982
|
+
const ackTimers: Array<ReturnType<typeof setTimeout>> = []
|
|
983
|
+
clearAckTimers = () => {
|
|
984
|
+
while (ackTimers.length > 0) {
|
|
985
|
+
const timer = ackTimers.pop()
|
|
986
|
+
if (timer) clearTimeout(timer)
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
const attemptRow = () => record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
990
|
+
const noticeTimer = setTimeout(() => {
|
|
991
|
+
if (guard.timedOut) return
|
|
992
|
+
const row = attemptRow()
|
|
993
|
+
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
|
|
994
|
+
writeSubtaskStatus(record, subtask.id, { ackOverdue: true }, guard)
|
|
995
|
+
}, ASSIGN_ACK_NOTICE_MS)
|
|
996
|
+
noticeTimer.unref?.()
|
|
997
|
+
ackTimers.push(noticeTimer)
|
|
998
|
+
/*
|
|
999
|
+
* [1.11.0] 180s 仍无回执 → 明确收束为 no-ack,而不是继续静默等待。
|
|
1000
|
+
*
|
|
1001
|
+
* 看门狗默认空闲窗口是 300s,而「根本没启动」和「在慢慢想」在日志上
|
|
1002
|
+
* 都表现为没有新事件。先把状态写成 blocked + blockedKind:'no-ack',
|
|
1003
|
+
* 再中止子会话;主 Agent 因此能立刻看到原因,也能选择续跑。
|
|
1004
|
+
*/
|
|
1005
|
+
const deadlineTimer = setTimeout(() => {
|
|
1006
|
+
if (guard.timedOut) return
|
|
1007
|
+
const row = attemptRow()
|
|
1008
|
+
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
|
|
1009
|
+
const seconds = Math.round(ASSIGN_ACK_DEADLINE_MS / 1000)
|
|
1010
|
+
const message = `派发后 ${seconds}s 未收到子 Agent 任何新事件(no-ack)`
|
|
1011
|
+
writeSubtaskStatus(record, subtask.id, {
|
|
1012
|
+
status: 'blocked',
|
|
1013
|
+
closure: 'blocked',
|
|
1014
|
+
blockedKind: 'no-ack',
|
|
1015
|
+
progress: 100,
|
|
1016
|
+
finishedAt: Date.now(),
|
|
1017
|
+
ackOverdue: true,
|
|
1018
|
+
error: message,
|
|
1019
|
+
summary: `未完成:${message}`,
|
|
1020
|
+
}, guard)
|
|
1021
|
+
recordSubtaskError(record, subtask.id, message, guard)
|
|
1022
|
+
if (!child.controller.signal.aborted) {
|
|
1023
|
+
child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }))
|
|
1024
|
+
}
|
|
1025
|
+
}, ASSIGN_ACK_DEADLINE_MS)
|
|
1026
|
+
deadlineTimer.unref?.()
|
|
1027
|
+
ackTimers.push(deadlineTimer)
|
|
798
1028
|
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
|
|
799
1029
|
const hardTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
|
|
800
1030
|
const watchdog = createProgressWatchdog({
|
|
@@ -812,12 +1042,29 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
812
1042
|
// Poll often enough to notice growth inside a short idle window, but
|
|
813
1043
|
// never more than four times per window.
|
|
814
1044
|
pollMs: Math.min(CHILD_POLL_MS, Math.max(20, Math.floor(idleTimeoutMs / 4))),
|
|
815
|
-
onProgress: ({ now }: any) => {
|
|
1045
|
+
onProgress: ({ now, seq, elapsedMs }: any) => {
|
|
816
1046
|
if (guard.timedOut) return
|
|
817
1047
|
// Visible liveness: the dashboard can show that a slow subtask is
|
|
818
1048
|
// still producing events instead of looking frozen.
|
|
819
1049
|
record.heartbeatAt = now
|
|
820
1050
|
record.updatedAt = now
|
|
1051
|
+
/*
|
|
1052
|
+
* [1.11.0] 第一次观察到子会话日志增长 = 回执。
|
|
1053
|
+
*
|
|
1054
|
+
* 这是唯一能证明「子 Agent 已经在动」的廉价事实:不用它自己的
|
|
1055
|
+
* 汇报(可能永远等不到),只看它有没有产生新事件。回执写入后
|
|
1056
|
+
* 两个 no-ack 定时器立即撤销,正常的长任务不会被误判。
|
|
1057
|
+
*/
|
|
1058
|
+
const row = attemptRow()
|
|
1059
|
+
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
|
|
1060
|
+
const acked = writeSubtaskStatus(record, subtask.id, {
|
|
1061
|
+
closure: 'acknowledged',
|
|
1062
|
+
ackedAt: now,
|
|
1063
|
+
ackEvidence: { seq, elapsedMs },
|
|
1064
|
+
ackOverdue: false,
|
|
1065
|
+
progress: Math.max(Number(row.progress ?? 10), 15),
|
|
1066
|
+
}, guard)
|
|
1067
|
+
if (acked) clearAckTimers()
|
|
821
1068
|
},
|
|
822
1069
|
makeError: (reason: any) => new PlanError(
|
|
823
1070
|
reason === 'stalled'
|
|
@@ -916,6 +1163,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
916
1163
|
}
|
|
917
1164
|
break
|
|
918
1165
|
} finally {
|
|
1166
|
+
clearAckTimers()
|
|
919
1167
|
if (activation) {
|
|
920
1168
|
await disposeActivation(activation, record, subtask.id, guard)
|
|
921
1169
|
activation = null
|
|
@@ -923,9 +1171,21 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
923
1171
|
}
|
|
924
1172
|
}
|
|
925
1173
|
|
|
1174
|
+
/*
|
|
1175
|
+
* [1.11.0] 已升级的请示不被最终的失败收束覆盖。
|
|
1176
|
+
*
|
|
1177
|
+
* 子 Agent 可能先调用 escalate,再因为中断/超时走到这里;此时问题已经
|
|
1178
|
+
* 写入状态,把它改成普通 blocked 会让主 Agent 永远看不到要回答什么。
|
|
1179
|
+
*/
|
|
1180
|
+
const finalRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1181
|
+
if (finalRow?.closure === 'escalated') {
|
|
1182
|
+
return interruptedFlag ? { interrupted: true } : undefined
|
|
1183
|
+
}
|
|
926
1184
|
const message = describeError(lastError ?? new Error('未知失败'))
|
|
927
1185
|
writeSubtaskStatus(record, subtask.id, {
|
|
928
1186
|
status: 'blocked',
|
|
1187
|
+
closure: 'blocked',
|
|
1188
|
+
blockedKind: 'failed',
|
|
929
1189
|
progress: 100,
|
|
930
1190
|
finishedAt: Date.now(),
|
|
931
1191
|
error: truncate(message, 2000),
|
|
@@ -945,8 +1205,15 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
945
1205
|
} catch (error) {
|
|
946
1206
|
const message = describeError(error)
|
|
947
1207
|
try {
|
|
1208
|
+
const row = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1209
|
+
if (row?.closure === 'escalated') {
|
|
1210
|
+
recordSubtaskError(record, subtask.id, `升级后发生异常,保留待指示状态:${message}`, guard)
|
|
1211
|
+
return
|
|
1212
|
+
}
|
|
948
1213
|
writeSubtaskStatus(record, subtask.id, {
|
|
949
1214
|
status: 'blocked',
|
|
1215
|
+
closure: 'blocked',
|
|
1216
|
+
blockedKind: 'failed',
|
|
950
1217
|
progress: 100,
|
|
951
1218
|
finishedAt: Date.now(),
|
|
952
1219
|
error: truncate(message, 2000),
|
|
@@ -1011,8 +1278,24 @@ async function runSubtaskAttempt(
|
|
|
1011
1278
|
const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
|
|
1012
1279
|
ceilingLanded = Array.isArray(landed) ? landed : []
|
|
1013
1280
|
ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat)
|
|
1014
|
-
|
|
1015
|
-
|
|
1281
|
+
/*
|
|
1282
|
+
* [1.11.0] An escalation outranks the ceiling.
|
|
1283
|
+
*
|
|
1284
|
+
* The child may have written `escalated` seconds before this timer fired;
|
|
1285
|
+
* turning that into a plain timeout would erase the question the main
|
|
1286
|
+
* Agent has to answer. The activation is still aborted, but the row keeps
|
|
1287
|
+
* its pending-decision state.
|
|
1288
|
+
*/
|
|
1289
|
+
const existing = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1290
|
+
if (existing?.closure === 'escalated') {
|
|
1291
|
+
record.errors = [
|
|
1292
|
+
...(record.errors ?? []),
|
|
1293
|
+
`${subtask.id}: 已达执行上限,但该子任务已在等待指示,保留 escalated 状态`,
|
|
1294
|
+
].slice(-20)
|
|
1295
|
+
} else {
|
|
1296
|
+
record.statuses = applyStatus(record.statuses, subtask.id, patch)
|
|
1297
|
+
record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
|
|
1298
|
+
}
|
|
1016
1299
|
record.updatedAt = Date.now()
|
|
1017
1300
|
} catch (error: any) {
|
|
1018
1301
|
record.errors = [
|
|
@@ -1190,6 +1473,29 @@ export function modelStatusLines(statuses: any) {
|
|
|
1190
1473
|
updatedBy: item.updatedBy ?? null,
|
|
1191
1474
|
missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
|
|
1192
1475
|
needs: Array.isArray(item.needs) ? item.needs : [],
|
|
1476
|
+
// [1.11.0] 闭环阶段必须进入模型可读面:只暴露四值 status 时,
|
|
1477
|
+
// 「在等指示」和「做失败了」在工具输出里长得一模一样。
|
|
1478
|
+
closure: item.closure ?? null,
|
|
1479
|
+
blockedKind: item.blockedKind ?? null,
|
|
1480
|
+
question: item.question ?? null,
|
|
1481
|
+
options: Array.isArray(item.options) ? item.options : [],
|
|
1482
|
+
ackOverdue: item.ackOverdue === true,
|
|
1483
|
+
escalatedAt: item.escalatedAt ?? null,
|
|
1484
|
+
instruction: item.instruction?.text ? truncate(item.instruction.text, 500) : null,
|
|
1485
|
+
/*
|
|
1486
|
+
* [1.11.0] 跨部门需求的待处理项必须出现在模型可读面(用户 m00687)。
|
|
1487
|
+
*
|
|
1488
|
+
* 只放在结果消息里时,主 Agent 一旦错过那一轮就再也看不到「还有一条
|
|
1489
|
+
* 需求没处置」,而交付门禁却一直拦着。status 工具是与进度同源的读取口,
|
|
1490
|
+
* 这里只暴露未处置项,避免把已答复的历史反复塞进上下文。
|
|
1491
|
+
*/
|
|
1492
|
+
openHandoffs: openHandoffs(item).map((handoff: any) => ({
|
|
1493
|
+
id: handoff.id,
|
|
1494
|
+
request: truncate(String(handoff.request ?? ''), 300),
|
|
1495
|
+
department: handoff.department ?? null,
|
|
1496
|
+
status: handoff.status,
|
|
1497
|
+
})),
|
|
1498
|
+
reportedAt: item.reportedAt ?? null,
|
|
1193
1499
|
}))
|
|
1194
1500
|
}
|
|
1195
1501
|
|
|
@@ -1207,6 +1513,14 @@ export function buildRoundResult(record: any, sessionId: any, limits: any) {
|
|
|
1207
1513
|
phase: record.phase,
|
|
1208
1514
|
resumeCount: Number(record.resumeCount ?? 0),
|
|
1209
1515
|
resumeAvailable: canResumePlan(record, limits.maxResumes).resume,
|
|
1516
|
+
// [1.11.0] 结果消息也带上修订号,回放时才知道这份结果属于哪一版计划。
|
|
1517
|
+
planRevision: Number(record.planRevision ?? 0),
|
|
1518
|
+
/*
|
|
1519
|
+
* [1.11.0] C-17:记录级闭环事实随结果消息下发,让摘要里的判定与
|
|
1520
|
+
* `deliveryReady` 门禁读同一组输入(否则「结果说完成、present 被拒」)。
|
|
1521
|
+
*/
|
|
1522
|
+
changePending: record.changeRequest?.status === 'pending',
|
|
1523
|
+
reportPending: record.reportPending === true,
|
|
1210
1524
|
})
|
|
1211
1525
|
}
|
|
1212
1526
|
|
|
@@ -1258,6 +1572,11 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
1258
1572
|
* its side effects) while giving the rest a second chance, and the resume
|
|
1259
1573
|
* budget stops a subtask that always fails from looping forever.
|
|
1260
1574
|
*/
|
|
1575
|
+
/*
|
|
1576
|
+
* [1.11.0] 重规划 cancel 留下的悬挂下游,在派发前显式收束成 blocked
|
|
1577
|
+
* (T4 D-T4-02)。否则它们永远 pending,既不报错也不进入交付阻塞。
|
|
1578
|
+
*/
|
|
1579
|
+
record.statuses = blockCancelledDependents(record.plan, record.statuses)
|
|
1261
1580
|
const resume = canResumePlan(record, options.maxResumes ?? MAX_PLAN_RESUMES)
|
|
1262
1581
|
if (resume.resume) {
|
|
1263
1582
|
/*
|
|
@@ -1324,9 +1643,19 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
1324
1643
|
* an older plan or a debugging session can keep plain status semantics.
|
|
1325
1644
|
*/
|
|
1326
1645
|
const gate = options.artifactGate !== false
|
|
1327
|
-
const ready = readySubtasks(record.plan, record.statuses, gate
|
|
1646
|
+
const ready = readySubtasks(record.plan, liveStatuses(record.statuses), gate
|
|
1328
1647
|
? {
|
|
1648
|
+
/*
|
|
1649
|
+
* [1.11.0] 未验收的 done 不再解锁下游(T5 C5 / T8 S1-05)。
|
|
1650
|
+
*
|
|
1651
|
+
* `done` 只说明子 Agent 交了东西;`unverified`/`failed` 说明
|
|
1652
|
+
* 交付内容没有通过验收。让下游在这时开跑,等于把未验证的结论
|
|
1653
|
+
* 当上游契约使用——跨部门链条会一路放大错误。legacy(旧日志)
|
|
1654
|
+
* 与 structured 仍放行,避免历史计划整体卡死。
|
|
1655
|
+
*/
|
|
1329
1656
|
dependencyOk: (dependency: any) => dependency?.status === 'done'
|
|
1657
|
+
&& dependency?.verification !== 'unverified'
|
|
1658
|
+
&& dependency?.verification !== 'failed'
|
|
1330
1659
|
&& !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
|
|
1331
1660
|
}
|
|
1332
1661
|
: {})
|
|
@@ -1341,7 +1670,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
1341
1670
|
* status, the plan turned `blocked`, and a resume was billed against
|
|
1342
1671
|
* the failure budget. Keep them `pending`, and record the actual cause.
|
|
1343
1672
|
*/
|
|
1344
|
-
const pending = record.statuses.filter((item: any) => item.status === 'pending')
|
|
1673
|
+
const pending = liveStatuses(record.statuses).filter((item: any) => item.status === 'pending')
|
|
1345
1674
|
if (pending.length > 0) {
|
|
1346
1675
|
const reasons = pending.map((item: any) =>
|
|
1347
1676
|
`${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`)
|
|
@@ -1422,8 +1751,8 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
1422
1751
|
* `blocked` for real failures, and report `paused` when only pending work
|
|
1423
1752
|
* is left, so a resume is not billed against the failure budget.
|
|
1424
1753
|
*/
|
|
1425
|
-
const hasBlocked = record.statuses.some((item: any) => item.status === 'blocked')
|
|
1426
|
-
const hasPending = record.statuses.some((item: any) => item.status === 'pending')
|
|
1754
|
+
const hasBlocked = liveStatuses(record.statuses).some((item: any) => item.status === 'blocked')
|
|
1755
|
+
const hasPending = liveStatuses(record.statuses).some((item: any) => item.status === 'pending')
|
|
1427
1756
|
record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses))
|
|
1428
1757
|
} catch (error) {
|
|
1429
1758
|
const message = describeError(error)
|
|
@@ -1495,6 +1824,8 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
1495
1824
|
* or 100 % depending on which branch happened to write it.
|
|
1496
1825
|
*/
|
|
1497
1826
|
record.statuses = record.statuses.map((item: any) => {
|
|
1827
|
+
// [1.11.0] 被重规划的行不参与「失败收敛」:它们本来就是闭态旧行。
|
|
1828
|
+
if (item.closure === 'replanned') return item
|
|
1498
1829
|
if (item.status === 'pending' || item.status === 'in_progress') {
|
|
1499
1830
|
return {
|
|
1500
1831
|
...item,
|
|
@@ -1691,7 +2022,7 @@ function serialisePlan(record: any, session: any) {
|
|
|
1691
2022
|
* 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
|
|
1692
2023
|
*/
|
|
1693
2024
|
const violations = aggregateInvariantViolations(snapshot, phase)
|
|
1694
|
-
const readiness =
|
|
2025
|
+
const readiness = readinessOf(record, snapshot)
|
|
1695
2026
|
return {
|
|
1696
2027
|
sessionId: session.id,
|
|
1697
2028
|
planId: record.planId ?? plan?.planId ?? null,
|
|
@@ -1730,6 +2061,16 @@ function serialisePlan(record: any, session: any) {
|
|
|
1730
2061
|
deliveryReady: readiness.ready,
|
|
1731
2062
|
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
1732
2063
|
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
2064
|
+
/*
|
|
2065
|
+
* [1.11.0] 重规划与回报状态随载荷下发(T7 C-15)。
|
|
2066
|
+
*
|
|
2067
|
+
* `planRevision` 让界面能显示「第 N 次修订」;`changeRequest` 是执行中
|
|
2068
|
+
* 收到、尚未重规划的用户变更;`reportPending` 表示完成结果还没成功回报。
|
|
2069
|
+
* 三者都来自 record 的同一份事实,不另建缓存。
|
|
2070
|
+
*/
|
|
2071
|
+
planRevision: Number(record.planRevision ?? 0),
|
|
2072
|
+
changeRequest: record.changeRequest ?? null,
|
|
2073
|
+
reportPending: record.reportPending === true,
|
|
1733
2074
|
/*
|
|
1734
2075
|
* Liveness and resume bookkeeping. Without these the dashboard could not
|
|
1735
2076
|
* tell a slow-but-alive child from a wedged one, and the model could not
|
|
@@ -1868,6 +2209,9 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1868
2209
|
* subtask at the budget boundary (wp-40ce5eee, 17:51:37).
|
|
1869
2210
|
*/
|
|
1870
2211
|
errors: string[]
|
|
2212
|
+
/* [1.11.0] 重规划修订号与未处理的变更请求,随 durable 消息回放。 */
|
|
2213
|
+
planRevision: number
|
|
2214
|
+
changeRequest: any
|
|
1871
2215
|
}
|
|
1872
2216
|
/*
|
|
1873
2217
|
* [1.8.9] 回放按 planId 分账,不按会话「最后一个计划」分账。
|
|
@@ -1894,6 +2238,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1894
2238
|
superseded: false,
|
|
1895
2239
|
supersededBy: undefined,
|
|
1896
2240
|
errors: [],
|
|
2241
|
+
planRevision: Number(plan?.planRevision ?? 0) || 0,
|
|
2242
|
+
changeRequest: null,
|
|
1897
2243
|
}
|
|
1898
2244
|
snapshots.set(plan.planId, snap)
|
|
1899
2245
|
}
|
|
@@ -1934,6 +2280,44 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1934
2280
|
* that was the 13/14 → 5/14 replay regression. A plan never inherits
|
|
1935
2281
|
* another plan's round phase or resume counter (each snapshot owns them).
|
|
1936
2282
|
*/
|
|
2283
|
+
/*
|
|
2284
|
+
* [1.11.0] 重规划记录:采用 durable 消息里的完整修订计划,不重新推导。
|
|
2285
|
+
* 旧行在同一份 plan 里带 supersededAt,状态条目同步标 closure='replanned'。
|
|
2286
|
+
*/
|
|
2287
|
+
const replan = parseReplanMessage(event.data)
|
|
2288
|
+
if (replan && typeof replan.planId === 'string') {
|
|
2289
|
+
const snap = snapshots.get(replan.planId)
|
|
2290
|
+
if (snap) {
|
|
2291
|
+
snap.plan = replan.plan
|
|
2292
|
+
snap.planRevision = Number(replan.revision) || snap.planRevision
|
|
2293
|
+
snap.statuses = applyReplanStatuses(snap.statuses, replan)
|
|
2294
|
+
if (snap.changeRequest && snap.changeRequest.status !== 'replanned') {
|
|
2295
|
+
snap.changeRequest = {
|
|
2296
|
+
...snap.changeRequest,
|
|
2297
|
+
status: 'replanned',
|
|
2298
|
+
replannedAt: replan.at,
|
|
2299
|
+
planRevision: snap.planRevision,
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
/*
|
|
2305
|
+
* [1.11.0] 执行中收到的变更:恢复成 changeRequest,刷新后仍然可见、
|
|
2306
|
+
* 仍然阻止“静默收尾”。
|
|
2307
|
+
*/
|
|
2308
|
+
const change = parseChangeRequestMessage(event.data)
|
|
2309
|
+
if (change && typeof change.planId === 'string') {
|
|
2310
|
+
const snap = snapshots.get(change.planId)
|
|
2311
|
+
if (snap) {
|
|
2312
|
+
snap.changeRequest = {
|
|
2313
|
+
seq: change.seq,
|
|
2314
|
+
text: change.text,
|
|
2315
|
+
at: change.at,
|
|
2316
|
+
turn: change.turn,
|
|
2317
|
+
status: 'pending',
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
1937
2321
|
const result = parseResultMessage(event.data)
|
|
1938
2322
|
if (result && typeof result.planId === 'string') {
|
|
1939
2323
|
const snap = snapshots.get(result.planId)
|
|
@@ -2170,6 +2554,20 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
2170
2554
|
superseded,
|
|
2171
2555
|
supersedeRecorded: superseded,
|
|
2172
2556
|
supersededBy: superseded ? chosen.supersededBy : undefined,
|
|
2557
|
+
/*
|
|
2558
|
+
* [1.11.0] 回放也恢复修订号与未处理变更。`reportPending` 由状态本身派生:
|
|
2559
|
+
* 存在 done 行却没到 reported,说明当时的结果消息没有成功写进会话。
|
|
2560
|
+
*/
|
|
2561
|
+
planRevision: chosen.planRevision,
|
|
2562
|
+
changeRequest: chosen.changeRequest,
|
|
2563
|
+
/*
|
|
2564
|
+
* [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
|
|
2565
|
+
* 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
|
|
2566
|
+
* 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
|
|
2567
|
+
* 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
|
|
2568
|
+
*/
|
|
2569
|
+
reportPending: statuses.some((item: any) =>
|
|
2570
|
+
item?.status === 'done' && item?.closure === 'done'),
|
|
2173
2571
|
}
|
|
2174
2572
|
}
|
|
2175
2573
|
|
|
@@ -2264,6 +2662,14 @@ export type WorkplanRuntimeOptions = {
|
|
|
2264
2662
|
autoResume?: boolean
|
|
2265
2663
|
/** 自动续跑轮次上限(0–4,默认 2)。 */
|
|
2266
2664
|
autoResumeMaxAttempts?: number
|
|
2665
|
+
/**
|
|
2666
|
+
* [1.11.0] 完成必回报开关(C-05 / M3)。
|
|
2667
|
+
*
|
|
2668
|
+
* `undefined`/`true` = 严格:子任务没有结构化证据块时判 `blocked/unverified`;
|
|
2669
|
+
* `false` = 兼容 1.10.6 的 `done/legacy`。宿主从 `WorkplanConfig.strictCompletion`
|
|
2670
|
+
* 或 `DSH_WORKPLAN_STRICT_COMPLETION` 解析后传入。
|
|
2671
|
+
*/
|
|
2672
|
+
strictEvidence?: boolean
|
|
2267
2673
|
/**
|
|
2268
2674
|
* [1.8.13] Package version, supplied by the host from its `meta.version`.
|
|
2269
2675
|
*
|
|
@@ -2360,6 +2766,19 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2360
2766
|
}
|
|
2361
2767
|
if (downstream?.kind !== 'enter') return downstream
|
|
2362
2768
|
try {
|
|
2769
|
+
/*
|
|
2770
|
+
* [1.11.0] 回报自愈(契约 §7.3 B4):上一轮结果消息已写入,但回报标记
|
|
2771
|
+
* 写失败/进程中断时,下一步 pre-step 幂等补齐,不重复追加上下文。
|
|
2772
|
+
*/
|
|
2773
|
+
const session = payload.agent?.session
|
|
2774
|
+
const known = session ? state.records.get(session.id) : null
|
|
2775
|
+
if (known?.plan && known.reportPending === true && known.resultWritten === true) {
|
|
2776
|
+
const changed = markReported(known, session, `${known.plan.planId}:${known.dispatchedAt ?? 0}`)
|
|
2777
|
+
if (changed > 0) {
|
|
2778
|
+
known.reportPending = (known.statuses ?? []).some((item: any) =>
|
|
2779
|
+
item?.status === 'done' && item?.closure === 'done')
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2363
2782
|
return await maybePlan(ctx, state, payload, downstream, { ...options, limits })
|
|
2364
2783
|
} catch (error) {
|
|
2365
2784
|
try {
|
|
@@ -2489,6 +2908,59 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2489
2908
|
hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
|
|
2490
2909
|
}
|
|
2491
2910
|
}
|
|
2911
|
+
/*
|
|
2912
|
+
* [1.11.0] 待指示行的两条合法出口(T4 S4→S5 / S4→S6)。
|
|
2913
|
+
*
|
|
2914
|
+
* `dsh_workplan_update` 也是 `instruct` 的等价入口:带 instruction 即恢复
|
|
2915
|
+
* 推进,不带 instruction 直接 in_progress/done 会把一条未回答的请示洗成
|
|
2916
|
+
* 「在做/做完」,所以显式拒绝,并告诉主 Agent 该用哪个字段。
|
|
2917
|
+
*/
|
|
2918
|
+
const instruction = typeof args?.instruction === 'string' ? args.instruction.trim() : ''
|
|
2919
|
+
if (instruction) {
|
|
2920
|
+
if (current?.closure !== 'escalated') {
|
|
2921
|
+
return {
|
|
2922
|
+
ok: false,
|
|
2923
|
+
code: 'NOT_ESCALATED',
|
|
2924
|
+
planId: record.plan.planId,
|
|
2925
|
+
subtaskId,
|
|
2926
|
+
error: '该子任务不在待指示状态,不需要 instruction;普通受阻请直接改判。',
|
|
2927
|
+
}
|
|
2928
|
+
}
|
|
2929
|
+
if (status !== 'in_progress') {
|
|
2930
|
+
return {
|
|
2931
|
+
ok: false,
|
|
2932
|
+
code: 'INSTRUCTION_REQUIRES_IN_PROGRESS',
|
|
2933
|
+
planId: record.plan.planId,
|
|
2934
|
+
subtaskId,
|
|
2935
|
+
error: '下发 instruction 时 status 必须是 in_progress(或改用 dsh_workplan_instruct)。',
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
return instructSubtask(agent, {
|
|
2939
|
+
planId: args?.planId,
|
|
2940
|
+
subtaskId,
|
|
2941
|
+
instruction,
|
|
2942
|
+
}, undefined, record)
|
|
2943
|
+
}
|
|
2944
|
+
if (current?.closure === 'escalated') {
|
|
2945
|
+
if (status === 'done') {
|
|
2946
|
+
return {
|
|
2947
|
+
ok: false,
|
|
2948
|
+
code: 'ESCALATION_OPEN',
|
|
2949
|
+
planId: record.plan.planId,
|
|
2950
|
+
subtaskId,
|
|
2951
|
+
error: '该子任务仍在等待指示,不能直接改判 done:请先给出 instruction,或明确改判 blocked 放弃。',
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
if (status === 'in_progress') {
|
|
2955
|
+
return {
|
|
2956
|
+
ok: false,
|
|
2957
|
+
code: 'INSTRUCTION_REQUIRED',
|
|
2958
|
+
planId: record.plan.planId,
|
|
2959
|
+
subtaskId,
|
|
2960
|
+
error: '该子任务正在等待指示:恢复推进必须传 instruction(或调用 dsh_workplan_instruct),不能只改 status。',
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2492
2964
|
const revision = Number(current?.revision ?? 0) + 1
|
|
2493
2965
|
/*
|
|
2494
2966
|
* [1.8.13] A manual verdict can carry structured evidence.
|
|
@@ -2511,6 +2983,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2511
2983
|
summary: summary || undefined,
|
|
2512
2984
|
error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
|
|
2513
2985
|
...evidencePatch,
|
|
2986
|
+
/*
|
|
2987
|
+
* [1.11.0] 明确放弃(blocked)必须同时关掉 escalated,否则
|
|
2988
|
+
* applyStatus 会保留「等指示」投影,主 Agent 的放弃写了个寂寞。
|
|
2989
|
+
*/
|
|
2990
|
+
...(current?.closure === 'escalated' && status === 'blocked'
|
|
2991
|
+
? { closure: 'blocked', blockedKind: 'failed', question: null, options: [] }
|
|
2992
|
+
: {}),
|
|
2514
2993
|
revision,
|
|
2515
2994
|
updatedBy: 'agent',
|
|
2516
2995
|
})
|
|
@@ -2537,6 +3016,12 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2537
3016
|
acceptance: writtenRow?.acceptance,
|
|
2538
3017
|
artifacts: writtenRow?.artifacts,
|
|
2539
3018
|
missingArtifacts: writtenRow?.missingArtifacts,
|
|
3019
|
+
closure: writtenRow?.closure,
|
|
3020
|
+
blockedKind: writtenRow?.blockedKind,
|
|
3021
|
+
question: writtenRow?.question,
|
|
3022
|
+
options: writtenRow?.options,
|
|
3023
|
+
instruction: writtenRow?.instruction,
|
|
3024
|
+
instructionSeq: writtenRow?.instructionSeq,
|
|
2540
3025
|
}), { surfaceOp: 'append' })
|
|
2541
3026
|
} catch (error) {
|
|
2542
3027
|
pushRecordError(record, error)
|
|
@@ -2554,7 +3039,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2554
3039
|
record.updatedAt = Date.now()
|
|
2555
3040
|
const snapshot = derivePlanSnapshot(record.statuses)
|
|
2556
3041
|
const written = snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
2557
|
-
const readiness =
|
|
3042
|
+
const readiness = readinessOf(record, snapshot)
|
|
2558
3043
|
return {
|
|
2559
3044
|
ok: true,
|
|
2560
3045
|
planId: record.plan.planId,
|
|
@@ -2576,6 +3061,121 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2576
3061
|
}
|
|
2577
3062
|
}
|
|
2578
3063
|
|
|
3064
|
+
/**
|
|
3065
|
+
* [1.11.0] C-11:需求变更的唯一写入入口(dsh_workplan_replan)。
|
|
3066
|
+
*
|
|
3067
|
+
* 为什么必须单独一个工具,而不是让模型直接改计划消息:
|
|
3068
|
+
* 1. 旧行的 `supersededAt` 与状态条的 `closure:'replanned'` 必须同一次写入,
|
|
3069
|
+
* 否则调度器会继续跑「已撤销」的工作;
|
|
3070
|
+
* 2. durable `workplan-replan` 带上完整修订计划,刷新后才能得到同一份定义;
|
|
3071
|
+
* 3. 执行中收到变更时,工具返回 `REPLAN_PLAN_RUNNING` 并保留 changeRequest,
|
|
3072
|
+
* 让模型等待而不是静默丢弃或强行中断正在跑的子任务。
|
|
3073
|
+
*/
|
|
3074
|
+
async function replanPlan(agent: any, args: any) {
|
|
3075
|
+
const session = agent?.session
|
|
3076
|
+
if (!session) throw new PlanError('只能在会话内重规划', 'NO_SESSION')
|
|
3077
|
+
if (!isRootSession(session)) throw new PlanError('子 Agent 不能重规划主计划', 'NOT_ROOT')
|
|
3078
|
+
let record = state.records.get(session.id)
|
|
3079
|
+
if (!record?.plan) record = reconstructFromSession(session, args?.planId)
|
|
3080
|
+
record = adoptRequestedPlan(session, record, args?.planId)
|
|
3081
|
+
if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
|
|
3082
|
+
const planId = record.plan.planId
|
|
3083
|
+
const revisionNow = Number(record.planRevision ?? record.plan?.planRevision ?? 0)
|
|
3084
|
+
const base = {
|
|
3085
|
+
ok: false,
|
|
3086
|
+
planId,
|
|
3087
|
+
planRevision: revisionNow,
|
|
3088
|
+
stats: derivePlanSnapshot(record.statuses).stats,
|
|
3089
|
+
}
|
|
3090
|
+
if (record.phase === 'cancelled' || record.phase === 'superseded' || record.superseded === true) {
|
|
3091
|
+
return {
|
|
3092
|
+
...base,
|
|
3093
|
+
code: 'REPLAN_TERMINAL',
|
|
3094
|
+
error: '计划已是终态(已取消/已被取代),不能重规划',
|
|
3095
|
+
hint: '终态计划不会复活:如需继续这项工作,请让主 Agent 生成新计划。',
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
if (record.dispatchPromise) {
|
|
3099
|
+
/*
|
|
3100
|
+
* 执行中拒绝改写定义,但把变更原文记下来。旧行为(maybePlan 直接
|
|
3101
|
+
* return downstream)会让用户在派发期间说的新需求彻底消失。
|
|
3102
|
+
*/
|
|
3103
|
+
const change = typeof args?.changeText === 'string' ? truncate(args.changeText.trim(), 4000) : ''
|
|
3104
|
+
if (change) {
|
|
3105
|
+
const seq = Number(record.changeRequestSeq ?? 0) + 1
|
|
3106
|
+
record.changeRequestSeq = seq
|
|
3107
|
+
record.changeRequest = {
|
|
3108
|
+
seq,
|
|
3109
|
+
text: change,
|
|
3110
|
+
at: Date.now(),
|
|
3111
|
+
turn: Number(state.activeTurns?.get?.(session.id) ?? NaN) || null,
|
|
3112
|
+
status: 'pending',
|
|
3113
|
+
}
|
|
3114
|
+
record.updatedAt = Date.now()
|
|
3115
|
+
}
|
|
3116
|
+
state.records.set(session.id, record)
|
|
3117
|
+
return {
|
|
3118
|
+
...base,
|
|
3119
|
+
code: 'REPLAN_PLAN_RUNNING',
|
|
3120
|
+
error: '本轮派发仍在执行:重规划不会中途改写正在跑的子任务',
|
|
3121
|
+
hint: '先轮询 dsh_workplan_status 等本轮结束(或先 cancel 并等它收敛),再提交同一组 changes;变更已记录为 changeRequest,不会丢失。',
|
|
3122
|
+
running: true,
|
|
3123
|
+
changeRequest: record.changeRequest ?? null,
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
const revision = revisionNow + 1
|
|
3127
|
+
const at = Date.now()
|
|
3128
|
+
const result = planReplan(record.plan, args?.changes, {
|
|
3129
|
+
planId,
|
|
3130
|
+
reason: args?.reason,
|
|
3131
|
+
revision,
|
|
3132
|
+
at,
|
|
3133
|
+
})
|
|
3134
|
+
if (!result.ok) return { ...base, code: result.code, error: result.error }
|
|
3135
|
+
/*
|
|
3136
|
+
* 先落 durable 记录,再改内存:写失败时计划保持原样,不会出现
|
|
3137
|
+
* 「内存里已经改了、刷新后又退回去」的分叉。
|
|
3138
|
+
*/
|
|
3139
|
+
try {
|
|
3140
|
+
session.append('user/message', buildReplanMessage(result.payload), { surfaceOp: 'append' })
|
|
3141
|
+
} catch (error) {
|
|
3142
|
+
return {
|
|
3143
|
+
...base,
|
|
3144
|
+
code: 'REPLAN_WRITE_FAILED',
|
|
3145
|
+
error: `写入重规划记录失败:${error instanceof Error ? error.message : String(error)}`,
|
|
3146
|
+
hint: '计划未被改动;修复会话写入问题后重试同一组 changes。',
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
record.plan = result.payload.plan
|
|
3150
|
+
record.planRevision = revision
|
|
3151
|
+
record.statuses = applyReplanStatuses(record.statuses, result.payload)
|
|
3152
|
+
record.phase = planPhase(record.statuses)
|
|
3153
|
+
record.error = null
|
|
3154
|
+
record.updatedAt = at
|
|
3155
|
+
if (record.changeRequest && record.changeRequest.status !== 'replanned') {
|
|
3156
|
+
record.changeRequest = {
|
|
3157
|
+
...record.changeRequest,
|
|
3158
|
+
status: 'replanned',
|
|
3159
|
+
replannedAt: at,
|
|
3160
|
+
planRevision: revision,
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
state.records.set(session.id, record)
|
|
3164
|
+
const snapshot = derivePlanSnapshot(record.statuses, definedSubtaskCount(record.plan))
|
|
3165
|
+
return {
|
|
3166
|
+
ok: true,
|
|
3167
|
+
planId,
|
|
3168
|
+
planRevision: revision,
|
|
3169
|
+
reason: result.payload.reason,
|
|
3170
|
+
marks: result.payload.marks,
|
|
3171
|
+
added: result.payload.added,
|
|
3172
|
+
phase: record.phase,
|
|
3173
|
+
stats: snapshot.stats,
|
|
3174
|
+
statuses: modelStatusLines(snapshot.statuses),
|
|
3175
|
+
hint: '旧行保留为 closure=replanned(可追溯、不计入剩余项、不再调度);修订后的新行是 pending,调用 dsh_workplan_dispatch 才会执行。',
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
|
|
2579
3179
|
async function cancelPlan(agent: any, args: any) {
|
|
2580
3180
|
const session = agent?.session
|
|
2581
3181
|
if (!session) throw new PlanError('只能在会话内取消计划', 'NO_SESSION')
|
|
@@ -2946,6 +3546,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2946
3546
|
idleTimeoutMs: limits.idleTimeoutMs,
|
|
2947
3547
|
totalTimeoutMs: limits.totalTimeoutMs,
|
|
2948
3548
|
maxResumes: limits.maxResumes,
|
|
3549
|
+
strictEvidence: options.strictEvidence,
|
|
2949
3550
|
})
|
|
2950
3551
|
.then(() => finishRound(record, session))
|
|
2951
3552
|
.catch((error: any) => {
|
|
@@ -2979,13 +3580,61 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2979
3580
|
* end state: a durable result message plus a reconciled phase. Anything less
|
|
2980
3581
|
* would make "start now, read later" a second, divergent code path.
|
|
2981
3582
|
*/
|
|
3583
|
+
/**
|
|
3584
|
+
* [1.11.0] 完成必回报的写入点(T7 C-06;契约 S7 done → S8 reported)。
|
|
3585
|
+
*
|
|
3586
|
+
* 只有在「结果消息确实写进会话」之后才调用:没有证据的“已回报”比不回报
|
|
3587
|
+
* 更危险。写入走 applyStatus(唯一写入口),读到的是同一条状态条目上的
|
|
3588
|
+
* `closure:'reported'` + `report{state,at,ref,turn}`,与左侧栏 chip 同源。
|
|
3589
|
+
* 返回本次新标记的条数;已是 reported 的行不重复写,避免每轮刷新 revision。
|
|
3590
|
+
*/
|
|
3591
|
+
function markReported(record: any, session: any, ref: string) {
|
|
3592
|
+
const at = Date.now()
|
|
3593
|
+
const rawTurn = Number(state.activeTurns?.get?.(session?.id) ?? NaN)
|
|
3594
|
+
const turn = Number.isFinite(rawTurn) ? rawTurn : null
|
|
3595
|
+
let changed = 0
|
|
3596
|
+
for (const item of Array.isArray(record?.statuses) ? record.statuses : []) {
|
|
3597
|
+
if (item?.status !== 'done') continue
|
|
3598
|
+
if (item?.closure === 'reported' && item?.report?.state === 'sent') continue
|
|
3599
|
+
try {
|
|
3600
|
+
record.statuses = applyStatus(record.statuses, item.subtaskId, {
|
|
3601
|
+
closure: 'reported',
|
|
3602
|
+
reportedAt: at,
|
|
3603
|
+
report: { state: 'sent', at, ref, turn },
|
|
3604
|
+
revision: Number(item.revision ?? 0) + 1,
|
|
3605
|
+
updatedBy: 'system',
|
|
3606
|
+
})
|
|
3607
|
+
changed += 1
|
|
3608
|
+
} catch (error) {
|
|
3609
|
+
ctx.logger?.warn?.(`dsh-workplan: 回报标记失败 ${String(item?.subtaskId)}:${error instanceof Error ? error.message : String(error)}`)
|
|
3610
|
+
record.reportPending = true
|
|
3611
|
+
}
|
|
3612
|
+
}
|
|
3613
|
+
return changed
|
|
3614
|
+
}
|
|
3615
|
+
|
|
2982
3616
|
function finishRound(record: any, session: any) {
|
|
3617
|
+
const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`
|
|
2983
3618
|
if (!record.resultWritten) {
|
|
3619
|
+
/*
|
|
3620
|
+
* [1.11.0] 完成必回报的顺序:先标记 reported,再构建并落盘结果消息。
|
|
3621
|
+
*
|
|
3622
|
+
* 这样结果消息里的 statuses 就带着 `closure:'reported'`,刷新/重启后
|
|
3623
|
+
* 回放得到同一个结论;而“标记了但消息没写成功”会在 catch 里回滚,
|
|
3624
|
+
* 绝不留下没有证据的 reported。
|
|
3625
|
+
*/
|
|
3626
|
+
const before = (record.statuses ?? []).map((item: any) => ({ ...item }))
|
|
3627
|
+
const needReport = before.filter((item: any) => item?.status === 'done' && item?.closure !== 'reported').length
|
|
3628
|
+
// ^ 本轮结算:done 且未到 reported 的行(含旧日志的 null)都算待回报。
|
|
3629
|
+
const reported = markReported(record, session, ref)
|
|
2984
3630
|
const resultMessage = buildRoundResult(record, session.id, limits)
|
|
2985
3631
|
try {
|
|
2986
3632
|
session.append('user/message', resultMessage, { surfaceOp: 'append' })
|
|
2987
3633
|
record.resultWritten = true
|
|
3634
|
+
record.reportPending = needReport > 0 && reported < needReport
|
|
2988
3635
|
} catch (error) {
|
|
3636
|
+
// 消息没写成功 ⇒ 回报没有证据:把状态回滚成写之前的快照。
|
|
3637
|
+
record.statuses = before
|
|
2989
3638
|
ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
|
|
2990
3639
|
/*
|
|
2991
3640
|
* [1.8.14] N13: a failed result write is a real, user-visible failure —
|
|
@@ -2993,6 +3642,22 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2993
3642
|
* disagree with the live phase. Log it durably, not only in the host log.
|
|
2994
3643
|
*/
|
|
2995
3644
|
pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
|
|
3645
|
+
/*
|
|
3646
|
+
* [1.11.0] 写失败时不能假装回报过。保留 reportPending,让下一次
|
|
3647
|
+
* pre-step 或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
|
|
3648
|
+
*/
|
|
3649
|
+
record.reportPending = true
|
|
3650
|
+
}
|
|
3651
|
+
} else {
|
|
3652
|
+
/*
|
|
3653
|
+
* 旧日志 / 上一次写失败的重试:结果消息已在,但仍有 done 行没到
|
|
3654
|
+
* reported。幂等补齐,不重复追加消息。
|
|
3655
|
+
*/
|
|
3656
|
+
const pending = (record.statuses ?? []).some((item: any) =>
|
|
3657
|
+
item?.status === 'done' && item?.closure !== 'reported')
|
|
3658
|
+
if (pending) {
|
|
3659
|
+
const changed = markReported(record, session, ref)
|
|
3660
|
+
if (changed > 0) record.reportPending = false
|
|
2996
3661
|
}
|
|
2997
3662
|
}
|
|
2998
3663
|
/*
|
|
@@ -3014,7 +3679,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3014
3679
|
* had no field telling it the round ended early. `complete`/`remaining` make
|
|
3015
3680
|
* that state machine-readable instead of a sentence to interpret.
|
|
3016
3681
|
*/
|
|
3017
|
-
function completionFields(snapshot: any, phase: any) {
|
|
3682
|
+
function completionFields(snapshot: any, phase: any, record?: any) {
|
|
3018
3683
|
const stats = snapshot?.stats ?? {}
|
|
3019
3684
|
const total = Number(stats.total ?? 0)
|
|
3020
3685
|
const done = Number(stats.done ?? 0)
|
|
@@ -3027,7 +3692,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3027
3692
|
* model now also sees whether the plan passed the delivery gate, plus the
|
|
3028
3693
|
* exact gaps.
|
|
3029
3694
|
*/
|
|
3030
|
-
const readiness =
|
|
3695
|
+
const readiness = record
|
|
3696
|
+
? readinessOf(record, snapshot)
|
|
3697
|
+
: deliveryReadiness(snapshot, { phase })
|
|
3031
3698
|
return {
|
|
3032
3699
|
complete: total > 0 && done >= total,
|
|
3033
3700
|
remaining: Math.max(0, total - done),
|
|
@@ -3045,7 +3712,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3045
3712
|
runtime: runtimeIdentity(),
|
|
3046
3713
|
planId: record.plan.planId,
|
|
3047
3714
|
alreadyRunning: false,
|
|
3048
|
-
...completionFields(snapshot, record.phase),
|
|
3715
|
+
...completionFields(snapshot, record.phase, record),
|
|
3049
3716
|
...extra,
|
|
3050
3717
|
phase: record.phase,
|
|
3051
3718
|
stats: snapshot.stats,
|
|
@@ -3090,7 +3757,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3090
3757
|
}
|
|
3091
3758
|
const running = Boolean(record.dispatchPromise)
|
|
3092
3759
|
const snapshot = derivePlanSnapshot(record.statuses)
|
|
3093
|
-
const readiness =
|
|
3760
|
+
const readiness = readinessOf(record, snapshot)
|
|
3094
3761
|
return {
|
|
3095
3762
|
ok: true,
|
|
3096
3763
|
version: pluginVersion,
|
|
@@ -3185,6 +3852,490 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3185
3852
|
}
|
|
3186
3853
|
}
|
|
3187
3854
|
|
|
3855
|
+
/**
|
|
3856
|
+
* [1.11.0] 子 → 父的唯一反向通道(T4 C-09 / T6 M5)。
|
|
3857
|
+
*
|
|
3858
|
+
* 子会话只知道自己的 `session.id` 和父会话 id。这里用父链 + `childId` 反查
|
|
3859
|
+
* 子任务,而不是相信子 Agent 自报的 subtaskId:自报值可以写错,父链不会。
|
|
3860
|
+
* 写入仍是 `applyStatus`(唯一写入口),并同步落一条 durable update,刷新后
|
|
3861
|
+
* 「有一条请示在等指示」不会退回 pending。
|
|
3862
|
+
*/
|
|
3863
|
+
async function escalateSubtask(agent: any, args: any) {
|
|
3864
|
+
const childSession = agent?.session
|
|
3865
|
+
if (!childSession?.id) {
|
|
3866
|
+
return { ok: false, code: 'NO_SESSION', error: '只能在子会话内上报遇阻' }
|
|
3867
|
+
}
|
|
3868
|
+
const parentId = childSession.header?.parentSession
|
|
3869
|
+
if (!parentId) {
|
|
3870
|
+
return {
|
|
3871
|
+
ok: false,
|
|
3872
|
+
code: 'NOT_CHILD_SESSION',
|
|
3873
|
+
error: '当前不是子会话,无法反查父计划;请直接在结果块写 status=blocked + question',
|
|
3874
|
+
}
|
|
3875
|
+
}
|
|
3876
|
+
let record = state.records.get(parentId)
|
|
3877
|
+
if (!record?.plan) {
|
|
3878
|
+
const parent = (ctx as any).sessions?.get?.(parentId)
|
|
3879
|
+
if (parent) {
|
|
3880
|
+
try {
|
|
3881
|
+
record = reconstructFromSession(parent)
|
|
3882
|
+
} catch (error) {
|
|
3883
|
+
pushRecordError({ errors: [] } as any, error)
|
|
3884
|
+
}
|
|
3885
|
+
}
|
|
3886
|
+
}
|
|
3887
|
+
if (!record?.plan) {
|
|
3888
|
+
return {
|
|
3889
|
+
ok: false,
|
|
3890
|
+
code: 'NO_PLAN',
|
|
3891
|
+
error: '父会话没有可关联的计划;请在结果块写 status=blocked + question,由主 Agent 处理',
|
|
3892
|
+
}
|
|
3893
|
+
}
|
|
3894
|
+
const row = (record.statuses ?? []).find((item: any) => item?.childId === childSession.id)
|
|
3895
|
+
if (!row) {
|
|
3896
|
+
return {
|
|
3897
|
+
ok: false,
|
|
3898
|
+
code: 'NO_SUBTASK',
|
|
3899
|
+
error: '计划里找不到与本子会话关联的子任务(childId 未登记);请在结果块写 status=blocked + question',
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
if (row.status === 'done') {
|
|
3903
|
+
return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, error: '该子任务已标记完成,不能再提交请示' }
|
|
3904
|
+
}
|
|
3905
|
+
const question = truncate(String(args?.question ?? '').trim(), MAX_QUESTION_CHARS)
|
|
3906
|
+
if (!question) {
|
|
3907
|
+
return { ok: false, code: 'INVALID_QUESTION', subtaskId: row.subtaskId, error: 'question 必填:写清需要主 Agent 决定的单个问题' }
|
|
3908
|
+
}
|
|
3909
|
+
if (row.closure === 'escalated') {
|
|
3910
|
+
return {
|
|
3911
|
+
ok: true,
|
|
3912
|
+
alreadyEscalated: true,
|
|
3913
|
+
planId: record.plan.planId,
|
|
3914
|
+
subtaskId: row.subtaskId,
|
|
3915
|
+
status: 'blocked',
|
|
3916
|
+
closure: 'escalated',
|
|
3917
|
+
question: row.question ?? question,
|
|
3918
|
+
message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待主 Agent 指示。',
|
|
3919
|
+
}
|
|
3920
|
+
}
|
|
3921
|
+
const options = (Array.isArray(args?.options) ? args.options : [])
|
|
3922
|
+
.slice(0, MAX_ESCALATION_OPTIONS)
|
|
3923
|
+
.map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
|
|
3924
|
+
.filter(Boolean)
|
|
3925
|
+
const needs = (Array.isArray(args?.needs) ? args.needs : [])
|
|
3926
|
+
.slice(0, 10)
|
|
3927
|
+
.map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
|
|
3928
|
+
.filter(Boolean)
|
|
3929
|
+
const now = Date.now()
|
|
3930
|
+
const revision = Number(row.revision ?? 0) + 1
|
|
3931
|
+
record.statuses = applyStatus(record.statuses, row.subtaskId, {
|
|
3932
|
+
status: 'blocked',
|
|
3933
|
+
closure: 'escalated',
|
|
3934
|
+
blockedKind: 'escalated',
|
|
3935
|
+
question,
|
|
3936
|
+
options,
|
|
3937
|
+
needs: [...(Array.isArray(row.needs) ? row.needs : []), ...needs],
|
|
3938
|
+
progress: 100,
|
|
3939
|
+
finishedAt: now,
|
|
3940
|
+
error: question,
|
|
3941
|
+
summary: `待指示:${question}`,
|
|
3942
|
+
escalatedAt: now,
|
|
3943
|
+
escalationSeq: revision,
|
|
3944
|
+
revision,
|
|
3945
|
+
updatedBy: 'child',
|
|
3946
|
+
})
|
|
3947
|
+
record.updatedAt = now
|
|
3948
|
+
try {
|
|
3949
|
+
const parent = (ctx as any).sessions?.get?.(parentId)
|
|
3950
|
+
const written = record.statuses.find((item: any) => item?.subtaskId === row.subtaskId)
|
|
3951
|
+
parent?.append?.('user/message', buildUpdateMessage({
|
|
3952
|
+
planId: record.plan.planId,
|
|
3953
|
+
subtaskId: row.subtaskId,
|
|
3954
|
+
status: 'blocked',
|
|
3955
|
+
closure: 'escalated',
|
|
3956
|
+
blockedKind: 'escalated',
|
|
3957
|
+
question,
|
|
3958
|
+
options,
|
|
3959
|
+
needs: written?.needs,
|
|
3960
|
+
escalatedAt: now,
|
|
3961
|
+
escalationSeq: revision,
|
|
3962
|
+
revision,
|
|
3963
|
+
}), { surfaceOp: 'append' })
|
|
3964
|
+
} catch (error) {
|
|
3965
|
+
pushRecordError(record, error)
|
|
3966
|
+
}
|
|
3967
|
+
return {
|
|
3968
|
+
ok: true,
|
|
3969
|
+
planId: record.plan.planId,
|
|
3970
|
+
subtaskId: row.subtaskId,
|
|
3971
|
+
status: 'blocked',
|
|
3972
|
+
closure: 'escalated',
|
|
3973
|
+
question,
|
|
3974
|
+
revision,
|
|
3975
|
+
message: '已上报主 Agent。请立即停止推进,只允许做只读核对;等待指示期间不要开始新的写入或大改。',
|
|
3976
|
+
}
|
|
3977
|
+
}
|
|
3978
|
+
|
|
3979
|
+
/**
|
|
3980
|
+
* [1.11.0] 指示回执(T4 B5 / M6,T10 N4)。
|
|
3981
|
+
*
|
|
3982
|
+
* 指示投递成功只证明消息进了收件箱,不证明子会话真的开始执行。三个观察点
|
|
3983
|
+
* 都以「该行仍是 instructed 且 instructionSeq 未变」为前提:
|
|
3984
|
+
* - 轮询:子会话 seq 增长 = 已开始执行 → 写 acknowledged(唯一正向回执);
|
|
3985
|
+
* - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent 可催);
|
|
3986
|
+
* - 180s:仍无增长 → 收束为 blocked/no-ack(不再无限等待)。
|
|
3987
|
+
* 主 Agent 再次改判或子会话产出结果都会让这三个观察点自然作废。
|
|
3988
|
+
*/
|
|
3989
|
+
function scheduleInstructionAck(record: any, subtaskId: string, childId: string, revision: number) {
|
|
3990
|
+
const rowOf = () => record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
3991
|
+
const readSeq = () => {
|
|
3992
|
+
try {
|
|
3993
|
+
const seq = Number((ctx as any).sessions?.get?.(childId)?.seq)
|
|
3994
|
+
return Number.isFinite(seq) ? seq : undefined
|
|
3995
|
+
} catch {
|
|
3996
|
+
return undefined
|
|
3997
|
+
}
|
|
3998
|
+
}
|
|
3999
|
+
const baseline = readSeq()
|
|
4000
|
+
let stopped = false
|
|
4001
|
+
const timers: Array<ReturnType<typeof setTimeout> | ReturnType<typeof setInterval>> = []
|
|
4002
|
+
const stop = () => {
|
|
4003
|
+
if (stopped) return
|
|
4004
|
+
stopped = true
|
|
4005
|
+
for (const timer of timers) {
|
|
4006
|
+
clearTimeout(timer as any)
|
|
4007
|
+
clearInterval(timer as any)
|
|
4008
|
+
}
|
|
4009
|
+
}
|
|
4010
|
+
const sameAttempt = (row: any) => {
|
|
4011
|
+
if (stopped) return false
|
|
4012
|
+
if (!row || row.closure !== 'instructed') return false
|
|
4013
|
+
return Number(row.instructionSeq ?? 0) === Number(revision)
|
|
4014
|
+
}
|
|
4015
|
+
const unchanged = (row: any) => {
|
|
4016
|
+
if (!sameAttempt(row)) return false
|
|
4017
|
+
const seq = readSeq()
|
|
4018
|
+
if (seq === undefined || baseline === undefined) return true
|
|
4019
|
+
return seq <= baseline
|
|
4020
|
+
}
|
|
4021
|
+
/*
|
|
4022
|
+
* 正向回执:没有这一步时,一个正常工作但耗时较长的子会话会在 180s 被
|
|
4023
|
+
* 误判成 no-ack 并阻断,而它其实早就在产出事件了。
|
|
4024
|
+
*/
|
|
4025
|
+
const poll = setInterval(() => {
|
|
4026
|
+
const row = rowOf()
|
|
4027
|
+
if (!sameAttempt(row)) { stop(); return }
|
|
4028
|
+
const seq = readSeq()
|
|
4029
|
+
if (seq === undefined || baseline === undefined || seq <= baseline) return
|
|
4030
|
+
try {
|
|
4031
|
+
writeSubtaskStatus(record, subtaskId, {
|
|
4032
|
+
closure: 'acknowledged',
|
|
4033
|
+
ackedAt: Date.now(),
|
|
4034
|
+
ackEvidence: { seq, elapsedMs: Date.now() - Number(row.instruction?.at ?? Date.now()) },
|
|
4035
|
+
instructionOverdue: false,
|
|
4036
|
+
progress: Math.max(Number(row.progress ?? 0), 15),
|
|
4037
|
+
}, { timedOut: false })
|
|
4038
|
+
} catch {
|
|
4039
|
+
// Row moved on between read and write; the next tick re-evaluates.
|
|
4040
|
+
return
|
|
4041
|
+
}
|
|
4042
|
+
stop()
|
|
4043
|
+
}, INSTRUCTION_POLL_MS)
|
|
4044
|
+
poll.unref?.()
|
|
4045
|
+
timers.push(poll)
|
|
4046
|
+
const notice = setTimeout(() => {
|
|
4047
|
+
if (!unchanged(rowOf())) return
|
|
4048
|
+
try {
|
|
4049
|
+
writeSubtaskStatus(record, subtaskId, { instructionOverdue: true }, { timedOut: false })
|
|
4050
|
+
} catch {
|
|
4051
|
+
// The row moved on between the read and the write; nothing to report.
|
|
4052
|
+
}
|
|
4053
|
+
}, INSTRUCTION_ACK_NOTICE_MS)
|
|
4054
|
+
notice.unref?.()
|
|
4055
|
+
timers.push(notice)
|
|
4056
|
+
const deadline = setTimeout(() => {
|
|
4057
|
+
if (!unchanged(rowOf())) { stop(); return }
|
|
4058
|
+
const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000)
|
|
4059
|
+
const message = `指示下发后 ${seconds}s 子会话仍无任何新事件(no-ack):指示没有被执行`
|
|
4060
|
+
try {
|
|
4061
|
+
writeSubtaskStatus(record, subtaskId, {
|
|
4062
|
+
status: 'blocked',
|
|
4063
|
+
closure: 'blocked',
|
|
4064
|
+
blockedKind: 'no-ack',
|
|
4065
|
+
progress: 100,
|
|
4066
|
+
finishedAt: Date.now(),
|
|
4067
|
+
instructionOverdue: true,
|
|
4068
|
+
error: message,
|
|
4069
|
+
summary: `未完成:${message}`,
|
|
4070
|
+
}, { timedOut: false })
|
|
4071
|
+
recordSubtaskError(record, subtaskId, message, { timedOut: false })
|
|
4072
|
+
} catch {
|
|
4073
|
+
// Same race as above: the row already left instructed.
|
|
4074
|
+
}
|
|
4075
|
+
stop()
|
|
4076
|
+
}, INSTRUCTION_ACK_DEADLINE_MS)
|
|
4077
|
+
deadline.unref?.()
|
|
4078
|
+
timers.push(deadline)
|
|
4079
|
+
}
|
|
4080
|
+
|
|
4081
|
+
/**
|
|
4082
|
+
* [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
|
|
4083
|
+
*
|
|
4084
|
+
* 只有根会话能调用;只接受 `closure:'escalated'` 的行;只投递给本会话直接
|
|
4085
|
+
* 子会话。投递失败时不改状态(不伪造成「已指示」),把错误原样交给主 Agent。
|
|
4086
|
+
*/
|
|
4087
|
+
async function instructSubtask(agent: any, args: any, signal?: any, existingRecord?: any) {
|
|
4088
|
+
const session = agent?.session
|
|
4089
|
+
if (!session) return { ok: false, code: 'NO_SESSION', error: '只能在会话内下发指示' }
|
|
4090
|
+
if (!isRootSession(session)) return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' }
|
|
4091
|
+
let record = existingRecord ?? state.records.get(session.id)
|
|
4092
|
+
if (!record?.plan) record = reconstructFromSession(session, args?.planId)
|
|
4093
|
+
record = adoptRequestedPlan(session, record, args?.planId)
|
|
4094
|
+
if (!record?.plan) return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' }
|
|
4095
|
+
clearAutoResumeTimer(record, 'manual-instruct')
|
|
4096
|
+
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : ''
|
|
4097
|
+
if (!subtaskId) return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' }
|
|
4098
|
+
const current = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
4099
|
+
if (!current) return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` }
|
|
4100
|
+
if (current.closure !== 'escalated') {
|
|
4101
|
+
return {
|
|
4102
|
+
ok: false,
|
|
4103
|
+
code: 'NOT_ESCALATED',
|
|
4104
|
+
subtaskId,
|
|
4105
|
+
error: '该子任务不在待指示状态;普通受阻请用 dsh_workplan_update 改判',
|
|
4106
|
+
}
|
|
4107
|
+
}
|
|
4108
|
+
const instruction = truncate(String(args?.instruction ?? args?.text ?? '').trim(), MAX_INSTRUCTION_CHARS)
|
|
4109
|
+
if (!instruction) return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要子 Agent 执行的决定' }
|
|
4110
|
+
const childId = typeof current.childId === 'string' ? current.childId : ''
|
|
4111
|
+
if (!childId) return { ok: false, code: 'NO_CHILD', subtaskId, error: '该行没有关联子会话,无法投递指示' }
|
|
4112
|
+
if (!spawnedChildIds(session).has(childId)) {
|
|
4113
|
+
return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: `${childId} 不是本会话的直接子会话,拒绝投递` }
|
|
4114
|
+
}
|
|
4115
|
+
const service: any = (ctx as any).subagents
|
|
4116
|
+
if (!service || typeof service.sendMessage !== 'function') {
|
|
4117
|
+
return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId, error: '当前部署没有可用的 subagent 服务,无法投递指示' }
|
|
4118
|
+
}
|
|
4119
|
+
let messageId = ''
|
|
4120
|
+
try {
|
|
4121
|
+
messageId = String(await service.sendMessage(
|
|
4122
|
+
agent,
|
|
4123
|
+
childId,
|
|
4124
|
+
[{
|
|
4125
|
+
type: 'text',
|
|
4126
|
+
text: [
|
|
4127
|
+
'【主 Agent 指示(对应你此前提交的请示)】',
|
|
4128
|
+
instruction,
|
|
4129
|
+
'',
|
|
4130
|
+
'请按上述指示继续原任务。若仍受阻,先调用 dsh_workplan_escalate 再次上报,然后停止推进等待指示;不要自行猜测未被回答的部分。',
|
|
4131
|
+
].join('\n'),
|
|
4132
|
+
}],
|
|
4133
|
+
{ signal },
|
|
4134
|
+
) ?? '')
|
|
4135
|
+
} catch (error: any) {
|
|
4136
|
+
return {
|
|
4137
|
+
ok: false,
|
|
4138
|
+
code: 'DELIVERY_FAILED',
|
|
4139
|
+
subtaskId,
|
|
4140
|
+
error: truncate(error instanceof Error ? error.message : String(error), 500),
|
|
4141
|
+
hint: '状态未改变,该行仍是待指示;可重试,或用 dsh_workplan_followup 直接投递同一段指示。',
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
const now = Date.now()
|
|
4145
|
+
const revision = Number(current.revision ?? 0) + 1
|
|
4146
|
+
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
4147
|
+
status: 'in_progress',
|
|
4148
|
+
closure: 'instructed',
|
|
4149
|
+
instruction: { text: instruction, at: now, by: 'agent', messageId, delivery: 'sent' },
|
|
4150
|
+
instructionSeq: revision,
|
|
4151
|
+
progress: Math.max(Number(current.progress ?? 0), 15),
|
|
4152
|
+
finishedAt: null,
|
|
4153
|
+
error: null,
|
|
4154
|
+
question: null,
|
|
4155
|
+
options: [],
|
|
4156
|
+
blockedKind: null,
|
|
4157
|
+
ackOverdue: false,
|
|
4158
|
+
ackedAt: null,
|
|
4159
|
+
ackEvidence: undefined,
|
|
4160
|
+
revision,
|
|
4161
|
+
updatedBy: 'agent',
|
|
4162
|
+
})
|
|
4163
|
+
/*
|
|
4164
|
+
* [1.11.0] 指示会解除「受阻」(T10 N3)。
|
|
4165
|
+
*
|
|
4166
|
+
* 行从 blocked/escalated 变成 in_progress/instructed 后,缓存的
|
|
4167
|
+
* `record.phase` 仍是 blocked;`reconcilePhase` 现在允许 blocked 在有
|
|
4168
|
+
* 活跃行时让位给 executing,这里必须重新对账,否则卡片继续显示
|
|
4169
|
+
* 「卡住了」,与事实相反。
|
|
4170
|
+
*/
|
|
4171
|
+
record.phase = reconcilePhase(record.phase, record.statuses)
|
|
4172
|
+
record.updatedAt = now
|
|
4173
|
+
try {
|
|
4174
|
+
const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
4175
|
+
session.append('user/message', buildUpdateMessage({
|
|
4176
|
+
planId: record.plan.planId,
|
|
4177
|
+
subtaskId,
|
|
4178
|
+
status: 'in_progress',
|
|
4179
|
+
closure: 'instructed',
|
|
4180
|
+
instruction: written?.instruction,
|
|
4181
|
+
instructionSeq: revision,
|
|
4182
|
+
revision,
|
|
4183
|
+
}), { surfaceOp: 'append' })
|
|
4184
|
+
} catch (error) {
|
|
4185
|
+
pushRecordError(record, error)
|
|
4186
|
+
}
|
|
4187
|
+
scheduleInstructionAck(record, subtaskId, childId, revision)
|
|
4188
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
4189
|
+
const readiness = readinessOf(record, snapshot)
|
|
4190
|
+
return {
|
|
4191
|
+
ok: true,
|
|
4192
|
+
planId: record.plan.planId,
|
|
4193
|
+
subtaskId,
|
|
4194
|
+
status: 'in_progress',
|
|
4195
|
+
closure: 'instructed',
|
|
4196
|
+
revision,
|
|
4197
|
+
messageId,
|
|
4198
|
+
stats: snapshot.stats,
|
|
4199
|
+
deliveryReady: readiness.ready,
|
|
4200
|
+
hint: '指示已投递,该行已变为「已收到指示」。子 Agent 会开启新一轮;完成前仍不得交付。',
|
|
4201
|
+
}
|
|
4202
|
+
}
|
|
4203
|
+
|
|
4204
|
+
/**
|
|
4205
|
+
* [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
|
|
4206
|
+
*
|
|
4207
|
+
* 单独一层包装而不是让 host 直接调内部函数:`escalateSubtask` 需要
|
|
4208
|
+
* `record`/`ctx` 闭包,host 侧只拿得到 runtime 的公开面;这一层也是
|
|
4209
|
+
* 唯一被 `dsh_workplan_escalate` 触发的地方,便于测试替身注入。
|
|
4210
|
+
*/
|
|
4211
|
+
async function escalateTool(agent: any, args: any) {
|
|
4212
|
+
return escalateSubtask(agent, args)
|
|
4213
|
+
}
|
|
4214
|
+
|
|
4215
|
+
/**
|
|
4216
|
+
* [1.11.0] 工具层入口:主 Agent 下发指示(T4 C-10 / T6 M6)。
|
|
4217
|
+
*
|
|
4218
|
+
* 前置校验(根会话、escalated、直接子会话、非空 instruction)全部在
|
|
4219
|
+
* `instructSubtask` 里,这一层只转发 —— 校验留在唯一实现处,两个入口
|
|
4220
|
+
* (工具与 `dsh_workplan_update` 的 instruction 字段)才不会分叉。
|
|
4221
|
+
*/
|
|
4222
|
+
async function instructTool(agent: any, args: any, signal?: any) {
|
|
4223
|
+
return instructSubtask(agent, args, signal)
|
|
4224
|
+
}
|
|
4225
|
+
|
|
4226
|
+
/**
|
|
4227
|
+
* [1.11.0] 跨部门需求的唯一处置入口(用户 m00687)。
|
|
4228
|
+
*
|
|
4229
|
+
* 子 Agent 只能「提出」需求(needs → open handoff),不能宣称需求已解决;
|
|
4230
|
+
* 只有根会话的主 Agent 能把一条需求指派给部门(routed)、写入书面答复
|
|
4231
|
+
* (answered)或判定无需动作(closed)。处置结果写回同一条状态行并追加
|
|
4232
|
+
* 一条可回放的人工改判消息,刷新后仍然有效。
|
|
4233
|
+
*/
|
|
4234
|
+
async function handoffTool(agent: any, args: any, signal?: any) {
|
|
4235
|
+
const session = agent?.session
|
|
4236
|
+
if (!session) return { ok: false, code: 'NO_SESSION', error: '只能在会话内处置跨部门需求' }
|
|
4237
|
+
if (!isRootSession(session)) return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以处置跨部门需求' }
|
|
4238
|
+
let record = state.records.get(session.id)
|
|
4239
|
+
if (!record?.plan) record = reconstructFromSession(session, args?.planId)
|
|
4240
|
+
record = adoptRequestedPlan(session, record, args?.planId)
|
|
4241
|
+
if (!record?.plan) return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' }
|
|
4242
|
+
const action = ['list', 'assign', 'resolve', 'close'].includes(args?.action) ? args.action : ''
|
|
4243
|
+
if (!action) return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 list / assign / resolve / close' }
|
|
4244
|
+
if (action === 'list') {
|
|
4245
|
+
const rows = (record.statuses ?? []).flatMap((row: any) =>
|
|
4246
|
+
openHandoffs(row).map((handoff: any) => ({
|
|
4247
|
+
subtaskId: row.subtaskId,
|
|
4248
|
+
id: handoff.id,
|
|
4249
|
+
department: handoff.department,
|
|
4250
|
+
status: handoff.status,
|
|
4251
|
+
request: handoff.request,
|
|
4252
|
+
})))
|
|
4253
|
+
return { ok: true, planId: record.plan.planId, handoffs: rows, count: rows.length }
|
|
4254
|
+
}
|
|
4255
|
+
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : ''
|
|
4256
|
+
if (!subtaskId) return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' }
|
|
4257
|
+
const row = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
4258
|
+
if (!row) return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` }
|
|
4259
|
+
const handoffs = normaliseHandoffs(row.handoffs)
|
|
4260
|
+
const wanted = typeof args?.handoffId === 'string' ? args.handoffId.trim() : ''
|
|
4261
|
+
const index = wanted
|
|
4262
|
+
? handoffs.findIndex((item: any) => item.id === wanted)
|
|
4263
|
+
: handoffs.findIndex((item: any) => item.status === 'open' || item.status === 'routed')
|
|
4264
|
+
if (index < 0) {
|
|
4265
|
+
return {
|
|
4266
|
+
ok: false,
|
|
4267
|
+
code: wanted ? 'UNKNOWN_HANDOFF' : 'NO_OPEN_HANDOFF',
|
|
4268
|
+
subtaskId,
|
|
4269
|
+
error: wanted ? `未知跨部门需求:${wanted}` : '该行没有待处理的跨部门需求',
|
|
4270
|
+
}
|
|
4271
|
+
}
|
|
4272
|
+
const handoff = handoffs[index]
|
|
4273
|
+
if (action === 'assign') {
|
|
4274
|
+
const department = typeof args?.department === 'string' ? args.department.trim() : ''
|
|
4275
|
+
if (!DEPARTMENTS[department as keyof typeof DEPARTMENTS]) {
|
|
4276
|
+
return { ok: false, code: 'INVALID_DEPARTMENT', error: `department 必须是 ${DEPARTMENT_IDS.join(' / ')} 之一` }
|
|
4277
|
+
}
|
|
4278
|
+
handoffs[index] = { ...handoff, department, status: 'routed', updatedAt: Date.now(), by: 'agent' }
|
|
4279
|
+
} else if (action === 'resolve') {
|
|
4280
|
+
const response = truncate(String(args?.response ?? '').trim(), MAX_HANDOFF_RESPONSE_CHARS)
|
|
4281
|
+
if (!response) return { ok: false, code: 'INVALID_RESPONSE', error: 'resolve 必须写清答复或已由哪项产物满足该需求' }
|
|
4282
|
+
handoffs[index] = { ...handoff, status: 'answered', response, updatedAt: Date.now(), by: 'agent' }
|
|
4283
|
+
} else {
|
|
4284
|
+
handoffs[index] = { ...handoff, status: 'closed', response: handoff.response ?? null, updatedAt: Date.now(), by: 'agent' }
|
|
4285
|
+
}
|
|
4286
|
+
const revision = Number(row.revision ?? 0) + 1
|
|
4287
|
+
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
4288
|
+
handoffs,
|
|
4289
|
+
revision,
|
|
4290
|
+
updatedBy: 'agent',
|
|
4291
|
+
})
|
|
4292
|
+
record.updatedAt = Date.now()
|
|
4293
|
+
try {
|
|
4294
|
+
session.append('user/message', buildUpdateMessage({
|
|
4295
|
+
planId: record.plan.planId,
|
|
4296
|
+
subtaskId,
|
|
4297
|
+
status: row.status,
|
|
4298
|
+
handoffs,
|
|
4299
|
+
revision,
|
|
4300
|
+
}), { surfaceOp: 'append' })
|
|
4301
|
+
} catch (error) {
|
|
4302
|
+
pushRecordError(record, error)
|
|
4303
|
+
}
|
|
4304
|
+
/*
|
|
4305
|
+
* [1.11.0] 答复必须真的送到还在等它的子会话(用户 m00687)。
|
|
4306
|
+
*
|
|
4307
|
+
* 如果提出需求的行正处于「待指示」,它此刻停在那里等主 Agent:只把
|
|
4308
|
+
* handoff 写成 answered、不发指示,子会话永远不会继续,需求闭环只闭在
|
|
4309
|
+
* 计划表里。这里复用 instructSubtask 的唯一投递/回执链路(写 instructed、
|
|
4310
|
+
* 60s/180s 回执、下次激活注入),不另造第二条消息通道。
|
|
4311
|
+
* 投递失败不回滚 handoff:答复本身是真的,失败原因如实返回给主 Agent。
|
|
4312
|
+
*/
|
|
4313
|
+
let instruction: any = null
|
|
4314
|
+
if (action === 'resolve' && row.closure === 'escalated' && handoffs[index]?.response) {
|
|
4315
|
+
const answer = handoffs[index]
|
|
4316
|
+
instruction = await instructSubtask(agent, {
|
|
4317
|
+
planId: record.plan.planId,
|
|
4318
|
+
subtaskId,
|
|
4319
|
+
instruction: `跨部门需求 ${answer.id} 已答复${answer.department ? `(${answer.department})` : ''}:${answer.response}。按此答复继续原任务。`,
|
|
4320
|
+
}, signal)
|
|
4321
|
+
}
|
|
4322
|
+
const finalReadiness = readinessOf(record, derivePlanSnapshot(record.statuses))
|
|
4323
|
+
return {
|
|
4324
|
+
ok: true,
|
|
4325
|
+
planId: record.plan.planId,
|
|
4326
|
+
subtaskId,
|
|
4327
|
+
handoff: record.statuses.find((item: any) => item?.subtaskId === subtaskId)?.handoffs?.[index] ?? null,
|
|
4328
|
+
deliveryReady: finalReadiness.ready,
|
|
4329
|
+
deliveryBlockers: finalReadiness.blockers,
|
|
4330
|
+
...(instruction ? { instruction } : {}),
|
|
4331
|
+
hint: action === 'assign'
|
|
4332
|
+
? '已登记责任部门。插件没有常驻部门代理:这次指派不会自动产生工作,请用 dsh_workplan_replan(action=add) 建一个该部门的子任务,或由你直接完成,再用 action=resolve 写入答复或产物引用;否则交付仍被拦住。'
|
|
4333
|
+
: instruction && instruction.ok !== true
|
|
4334
|
+
? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
|
|
4335
|
+
: '已记录处置结果;交付阻塞按最新状态重新计算。',
|
|
4336
|
+
}
|
|
4337
|
+
}
|
|
4338
|
+
|
|
3188
4339
|
async function dispatchTool(agent: any, args: any, signal: any) {
|
|
3189
4340
|
const session = agent?.session
|
|
3190
4341
|
if (!session) throw new PlanError('只能在会话内派发计划', 'NO_SESSION')
|
|
@@ -3402,6 +4553,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3402
4553
|
idleTimeoutMs: limits.idleTimeoutMs,
|
|
3403
4554
|
totalTimeoutMs: limits.totalTimeoutMs,
|
|
3404
4555
|
maxResumes: limits.maxResumes,
|
|
4556
|
+
/*
|
|
4557
|
+
* [1.11.0] 严格完成是运行时级配置,不是每个调用点各传一份。
|
|
4558
|
+
* 漏传会让 `strictCompletion:false` 的部署读到默认 true,行为无法预期。
|
|
4559
|
+
*/
|
|
4560
|
+
strictEvidence: options.strictEvidence,
|
|
3405
4561
|
}).finally(() => {
|
|
3406
4562
|
record.dispatchPromise = null
|
|
3407
4563
|
record.dispatchStartedAt = null
|
|
@@ -3488,8 +4644,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3488
4644
|
const STOP_STEER_LIMIT = 2
|
|
3489
4645
|
|
|
3490
4646
|
function recordReadiness(record: any) {
|
|
3491
|
-
|
|
3492
|
-
return deliveryReadiness(snapshot, { phase: record.phase })
|
|
4647
|
+
return readinessOf(record)
|
|
3493
4648
|
}
|
|
3494
4649
|
|
|
3495
4650
|
function stopGateApplies(record: any, session?: any, turn?: number) {
|
|
@@ -3732,6 +4887,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3732
4887
|
stats: snapshot.stats,
|
|
3733
4888
|
statuses: snapshot.statuses,
|
|
3734
4889
|
attempt: book.count,
|
|
4890
|
+
changePending: record.changeRequest?.status === 'pending',
|
|
4891
|
+
reportPending: record.reportPending === true,
|
|
3735
4892
|
}),
|
|
3736
4893
|
{
|
|
3737
4894
|
kind: 'workplan-continue',
|
|
@@ -3880,7 +5037,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3880
5037
|
`计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
|
|
3881
5038
|
+ '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。')
|
|
3882
5039
|
}
|
|
3883
|
-
const readiness =
|
|
5040
|
+
const readiness = readinessOf(successor)
|
|
3884
5041
|
if (!readiness.ready) {
|
|
3885
5042
|
const ids = readiness.remaining.slice(0, 10).join('、')
|
|
3886
5043
|
return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
|
|
@@ -3904,7 +5061,18 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3904
5061
|
|
|
3905
5062
|
function presentDenialVerdict(agent: any): PresentDenialVerdict | undefined {
|
|
3906
5063
|
const session = agent?.session
|
|
3907
|
-
if (!session
|
|
5064
|
+
if (!session) return undefined
|
|
5065
|
+
/*
|
|
5066
|
+
* [1.11.0] 子会话不得直接交付(T7 P9 / R3)。
|
|
5067
|
+
*
|
|
5068
|
+
* 1.10.6 对非根会话直接返回 undefined,等于让子 Agent 绕过根交付门禁
|
|
5069
|
+
* 调用 present:中间产物会被当成最终交付展示给用户。交付只属于根会话;
|
|
5070
|
+
* 子会话的产物应写进工作区并由主 Agent 统一 present。
|
|
5071
|
+
*/
|
|
5072
|
+
if (!isRootSession(session)) {
|
|
5073
|
+
return presentDenial(PRESENT_DENY_CODES.NOT_ROOT,
|
|
5074
|
+
'子 Agent 不能直接交付:请把产物写入工作区并在结论里给出路径,由主 Agent 统一核对后调用 present。')
|
|
5075
|
+
}
|
|
3908
5076
|
if (isPlanModeActive(ctx, session)) return undefined
|
|
3909
5077
|
/*
|
|
3910
5078
|
* [1.8.16] Every plan in the session matters, not just the turn's plan.
|
|
@@ -3939,7 +5107,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3939
5107
|
const unresolved = gateable
|
|
3940
5108
|
.map((item: any) => ({
|
|
3941
5109
|
record: item,
|
|
3942
|
-
readiness:
|
|
5110
|
+
readiness: readinessOf(item),
|
|
3943
5111
|
}))
|
|
3944
5112
|
/*
|
|
3945
5113
|
* A cancelled plan is not a delivery blocker for *other* plans — the
|
|
@@ -3996,7 +5164,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3996
5164
|
if (denial) return denial
|
|
3997
5165
|
return undefined
|
|
3998
5166
|
}
|
|
3999
|
-
readiness =
|
|
5167
|
+
readiness = readinessOf(record)
|
|
4000
5168
|
if (readiness.ready) return undefined
|
|
4001
5169
|
}
|
|
4002
5170
|
if (record?.plan && !isTerminalPhase(record.phase)) state.records.set(session.id, record)
|
|
@@ -4140,7 +5308,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4140
5308
|
.map((planId) => recordForPlan(session, planId))
|
|
4141
5309
|
.filter((record: any) => record?.plan
|
|
4142
5310
|
&& !isTerminalPhase(record.phase)
|
|
4143
|
-
&& !
|
|
5311
|
+
&& !readinessOf(record).ready)
|
|
4144
5312
|
if (unresolved.length === 0) return undefined
|
|
4145
5313
|
const ids = unresolved.slice(0, 4).map((record: any) => record.plan.planId)
|
|
4146
5314
|
return `文件 ${requested} 已通过 present 交付给用户,而交付时点已存在的计划`
|
|
@@ -4247,6 +5415,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4247
5415
|
dispatchTool,
|
|
4248
5416
|
statusTool,
|
|
4249
5417
|
followupTool,
|
|
5418
|
+
escalateTool,
|
|
5419
|
+
instructTool,
|
|
5420
|
+
handoffTool,
|
|
5421
|
+
replanPlan,
|
|
4250
5422
|
plansPayload,
|
|
4251
5423
|
route,
|
|
4252
5424
|
dispose,
|
|
@@ -4311,6 +5483,25 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
4311
5483
|
const conversationContext = recentConversation(session)
|
|
4312
5484
|
const existing = state.records.get(session.id)
|
|
4313
5485
|
if (existing?.plan?.createdTurn === payload.turn) return downstream
|
|
5486
|
+
/*
|
|
5487
|
+
* [1.11.0] 执行中记录的变更,在本轮结束后仍然没有被 replan 落实时,必须
|
|
5488
|
+
* 在下一步拦住“直接开始新一轮计划/直接收尾”:提醒模型先处理变更。每个
|
|
5489
|
+
* 变更序号只提醒一次(notifiedSeq),不会每步重复注入。
|
|
5490
|
+
*/
|
|
5491
|
+
if (existing?.plan && !existing.dispatchPromise
|
|
5492
|
+
&& existing.changeRequest?.status === 'pending'
|
|
5493
|
+
&& existing.changeRequest.notifiedSeq !== existing.changeRequest.seq) {
|
|
5494
|
+
existing.changeRequest.notifiedSeq = existing.changeRequest.seq
|
|
5495
|
+
const change = existing.changeRequest
|
|
5496
|
+
return enterDecision(downstream, [buildChangeRequestMessage({
|
|
5497
|
+
kind: 'workplan-change',
|
|
5498
|
+
planId: String(existing.plan.planId ?? ''),
|
|
5499
|
+
seq: Number(change.seq) || 1,
|
|
5500
|
+
at: Number(change.at) || Date.now(),
|
|
5501
|
+
turn: Number(change.turn) || null,
|
|
5502
|
+
text: String(change.text ?? ''),
|
|
5503
|
+
}, { afterRound: true })])
|
|
5504
|
+
}
|
|
4314
5505
|
// A plan generated in plan mode is intentionally deferred: keep it intact
|
|
4315
5506
|
// until the user leaves plan mode and dispatches it. Cancelling it here
|
|
4316
5507
|
// would make the plan disappear before the main Agent can act on approval.
|
|
@@ -4332,7 +5523,46 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
4332
5523
|
existing.errors = Array.isArray(existing.errors) ? existing.errors : []
|
|
4333
5524
|
existing.errors.push('计划已取消:上一轮未派发')
|
|
4334
5525
|
}
|
|
4335
|
-
if (existing?.dispatchPromise || existing?.phase === 'executing')
|
|
5526
|
+
if (existing?.dispatchPromise || existing?.phase === 'executing') {
|
|
5527
|
+
/*
|
|
5528
|
+
* [1.11.0] C-12:执行中收到的新需求不能静默丢弃。
|
|
5529
|
+
*
|
|
5530
|
+
* 旧代码在这里直接 `return downstream`,用户在看到「正在做」之后补充的要求
|
|
5531
|
+
* 既没写进状态、也没出现在会话里,下一轮计划更不会包含它们。现在:
|
|
5532
|
+
* - 原文落进 `record.changeRequest`(带序号/回合/时间),刷新后可恢复;
|
|
5533
|
+
* - 一条 notice 消息进入本轮上下文,明确告诉模型「先别打断、结束后用
|
|
5534
|
+
* dsh_workplan_replan 落实」;
|
|
5535
|
+
* - 同一段文本只记一次,避免每步重复注入。
|
|
5536
|
+
*/
|
|
5537
|
+
const text = truncate(taskText, 4000)
|
|
5538
|
+
const previous = typeof existing.changeRequest?.text === 'string' ? existing.changeRequest.text : ''
|
|
5539
|
+
if (previous !== text) {
|
|
5540
|
+
const seq = Number(existing.changeRequestSeq ?? 0) + 1
|
|
5541
|
+
const at = Date.now()
|
|
5542
|
+
existing.changeRequestSeq = seq
|
|
5543
|
+
existing.changeRequest = {
|
|
5544
|
+
seq,
|
|
5545
|
+
text,
|
|
5546
|
+
at,
|
|
5547
|
+
turn: Number(payload.turn ?? 0),
|
|
5548
|
+
status: 'pending',
|
|
5549
|
+
notifiedSeq: seq,
|
|
5550
|
+
}
|
|
5551
|
+
existing.updatedAt = at
|
|
5552
|
+
const active = (existing.statuses ?? [])
|
|
5553
|
+
.filter((item: any) => item?.status === 'in_progress')
|
|
5554
|
+
.map((item: any) => `${String(item.subtaskId)}「${String(item.title ?? '')}」`)
|
|
5555
|
+
return enterDecision(downstream, [buildChangeRequestMessage({
|
|
5556
|
+
kind: 'workplan-change',
|
|
5557
|
+
planId: String(existing.plan?.planId ?? ''),
|
|
5558
|
+
seq,
|
|
5559
|
+
at,
|
|
5560
|
+
turn: Number(payload.turn ?? 0),
|
|
5561
|
+
text,
|
|
5562
|
+
}, { activeSubtasks: active })])
|
|
5563
|
+
}
|
|
5564
|
+
return downstream
|
|
5565
|
+
}
|
|
4336
5566
|
const modelSelection = resolveModelSelection(ctx, payload)
|
|
4337
5567
|
if (!modelSelection?.provider || !modelSelection?.model) {
|
|
4338
5568
|
const message = buildDegradedMessage({
|
|
@@ -4580,6 +5810,55 @@ export function statusToolOutputSchema() {
|
|
|
4580
5810
|
}
|
|
4581
5811
|
}
|
|
4582
5812
|
|
|
5813
|
+
export function replanToolOutputSchema() {
|
|
5814
|
+
return {
|
|
5815
|
+
type: 'object',
|
|
5816
|
+
properties: {
|
|
5817
|
+
ok: { type: 'boolean' },
|
|
5818
|
+
planId: { type: 'string' },
|
|
5819
|
+
planRevision: { type: 'number' },
|
|
5820
|
+
reason: { type: 'string' },
|
|
5821
|
+
phase: { type: 'string' },
|
|
5822
|
+
stats: { type: 'object' },
|
|
5823
|
+
statuses: { type: 'array' },
|
|
5824
|
+
marks: {
|
|
5825
|
+
type: 'array',
|
|
5826
|
+
items: {
|
|
5827
|
+
type: 'object',
|
|
5828
|
+
properties: {
|
|
5829
|
+
subtaskId: { type: 'string' },
|
|
5830
|
+
action: { type: 'string' },
|
|
5831
|
+
replacedBy: { type: 'array', items: { type: 'string' } },
|
|
5832
|
+
reason: { type: 'string' },
|
|
5833
|
+
},
|
|
5834
|
+
additionalProperties: true,
|
|
5835
|
+
},
|
|
5836
|
+
},
|
|
5837
|
+
added: {
|
|
5838
|
+
type: 'array',
|
|
5839
|
+
items: {
|
|
5840
|
+
type: 'object',
|
|
5841
|
+
properties: {
|
|
5842
|
+
subtaskId: { type: 'string' },
|
|
5843
|
+
stageId: { type: 'string' },
|
|
5844
|
+
title: { type: 'string' },
|
|
5845
|
+
replaces: { oneOf: [{ type: 'string' }, { type: 'null' }] },
|
|
5846
|
+
},
|
|
5847
|
+
additionalProperties: true,
|
|
5848
|
+
},
|
|
5849
|
+
},
|
|
5850
|
+
// 执行中拒绝改计划时:变更已记录、本轮仍在跑(REPLAN_PLAN_RUNNING)。
|
|
5851
|
+
running: { type: 'boolean' },
|
|
5852
|
+
changeRequest: { oneOf: [{ type: 'object' }, { type: 'null' }] },
|
|
5853
|
+
code: { type: 'string' },
|
|
5854
|
+
error: { type: 'string' },
|
|
5855
|
+
hint: { type: 'string' },
|
|
5856
|
+
},
|
|
5857
|
+
required: ['ok'],
|
|
5858
|
+
additionalProperties: true,
|
|
5859
|
+
}
|
|
5860
|
+
}
|
|
5861
|
+
|
|
4583
5862
|
export function dispatchToolOutputSchema() {
|
|
4584
5863
|
return {
|
|
4585
5864
|
type: 'object',
|