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/lib/runtime.js
CHANGED
|
@@ -14,11 +14,12 @@
|
|
|
14
14
|
import { randomUUID } from 'node:crypto';
|
|
15
15
|
import { existsSync, statSync } from 'node:fs';
|
|
16
16
|
import { isAbsolute, resolve } from 'node:path';
|
|
17
|
-
import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
|
|
17
|
+
import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, blockCancelledDependents, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS, parseUpdateMessage, buildUpdateMessage, normaliseHandoffs, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, } from './plan.js';
|
|
18
18
|
import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
|
|
19
19
|
import { supersedePlanRecord } from './supersede.js';
|
|
20
20
|
import { createProgressWatchdog, describeError } from './watchdog.js';
|
|
21
21
|
import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js';
|
|
22
|
+
import { applyReplanStatuses, buildChangeRequestMessage, buildReplanMessage, parseChangeRequestMessage, parseReplanMessage, planReplan, } from './replan.js';
|
|
22
23
|
/**
|
|
23
24
|
* [1.8.18] How many subtasks the plan *defines*.
|
|
24
25
|
*
|
|
@@ -33,14 +34,63 @@ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './
|
|
|
33
34
|
* (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
|
|
34
35
|
* `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
|
|
35
36
|
*/
|
|
37
|
+
function expectedAcceptanceOf(plan) {
|
|
38
|
+
const out = {};
|
|
39
|
+
for (const entry of flattenSubtasks(plan)) {
|
|
40
|
+
const id = String(entry?.subtask?.id ?? '');
|
|
41
|
+
if (!id)
|
|
42
|
+
continue;
|
|
43
|
+
out[id] = Array.isArray(entry.subtask.acceptance) ? entry.subtask.acceptance : [];
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
36
47
|
function definedSubtaskCount(plan) {
|
|
37
48
|
try {
|
|
38
|
-
|
|
49
|
+
/*
|
|
50
|
+
* [1.11.0] 被重规划替换/撤销的旧行不占分母。
|
|
51
|
+
*
|
|
52
|
+
* 契约 §7.2 硬规则 2:`cancel` 掉的工作如果仍然计入定义条数,计划就永远
|
|
53
|
+
* 差一项、永远无法交付。标记由 `replan.ts` 写在计划定义上(supersededAt),
|
|
54
|
+
* 与状态条目的 `closure:'replanned'` 是同一次写入的两个镜像。
|
|
55
|
+
*/
|
|
56
|
+
return flattenSubtasks(plan).filter((entry) => !entry.subtask?.supersededAt).length;
|
|
39
57
|
}
|
|
40
58
|
catch {
|
|
41
59
|
return Number.MAX_SAFE_INTEGER;
|
|
42
60
|
}
|
|
43
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* [1.11.0] 可调度/可计数的状态行:排除已被重规划替换或撤销的旧行。
|
|
64
|
+
*
|
|
65
|
+
* `closure` 仍是唯一标记。这里不复制状态的其它字段,只做视图过滤,因此
|
|
66
|
+
* 左侧栏、调度器、交付门禁读到的仍是同一个 `record.statuses` 数组。
|
|
67
|
+
*/
|
|
68
|
+
function liveStatuses(statuses) {
|
|
69
|
+
return Array.isArray(statuses)
|
|
70
|
+
? statuses.filter((item) => item?.closure !== 'replanned')
|
|
71
|
+
: [];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* [1.11.0] C-17:交付门禁的唯一读取助手——左侧栏、present、收尾闸门、dispatch
|
|
75
|
+
* 返回体都从这里拿 `deliveryReady`,不再各自决定“要不要把记录级事实算进去”。
|
|
76
|
+
*
|
|
77
|
+
* `changeRequest.pending`(执行中收到、尚未重规划的变更)与 `reportPending`
|
|
78
|
+
* (完成结果还没写进会话)只存在于 `record` 而不是 `statuses`,所以必须在
|
|
79
|
+
* 这一层显式传入;`plan.ts` 的 `deliveryReadiness` 因此仍是纯函数。
|
|
80
|
+
*/
|
|
81
|
+
function readinessOf(record, snapshot) {
|
|
82
|
+
const snap = snapshot ?? derivePlanSnapshot(record?.plan ? blockCancelledDependents(record.plan, record?.statuses) : record?.statuses, record?.plan ? definedSubtaskCount(record.plan) : undefined);
|
|
83
|
+
return deliveryReadiness(snap, {
|
|
84
|
+
phase: record?.phase,
|
|
85
|
+
changePending: record?.changeRequest?.status === 'pending',
|
|
86
|
+
reportPending: record?.reportPending === true,
|
|
87
|
+
/*
|
|
88
|
+
* 计划定义的验收标准是交付门的另一半:状态行只回答「子 Agent 说通过
|
|
89
|
+
* 了几条」,这里回答「计划要求的几条有没有被逐条回应」。
|
|
90
|
+
*/
|
|
91
|
+
expectedAcceptance: record?.plan ? expectedAcceptanceOf(record.plan) : undefined,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
44
94
|
export const PLANNER_TIMEOUT_MS = 120000;
|
|
45
95
|
/**
|
|
46
96
|
* Absolute ceiling for one child execution.
|
|
@@ -66,6 +116,30 @@ export const MAX_CHILD_TIMEOUT_MS = 1800000;
|
|
|
66
116
|
export const MIN_CHILD_IDLE_MS = 1000;
|
|
67
117
|
export const MAX_CHILD_IDLE_MS = 900000;
|
|
68
118
|
export const CHILD_POLL_MS = 2000;
|
|
119
|
+
/*
|
|
120
|
+
* [1.11.0] 派发回执的两个窗口(T4 B1/B2)。
|
|
121
|
+
*
|
|
122
|
+
* `assigned` 只是「已交给子会话」,不等于「子会话已经动了」。收不到回执时
|
|
123
|
+
* 静默等到空闲窗口(默认 300s)会把「根本没启动」和「在慢慢想」混为一谈:
|
|
124
|
+
* 90s 先标记 ackOverdue 让看板可见,180s 仍无任何新事件就按 no-ack 收束,
|
|
125
|
+
* 不再无限等待。
|
|
126
|
+
*/
|
|
127
|
+
export const ASSIGN_ACK_NOTICE_MS = 90000;
|
|
128
|
+
export const ASSIGN_ACK_DEADLINE_MS = 180000;
|
|
129
|
+
/*
|
|
130
|
+
* [1.11.0] 指示回执的两个窗口(T4 B5)。
|
|
131
|
+
*
|
|
132
|
+
* `instructed` 只表示「指示已经写进状态行并投递」,不表示子 Agent 已经照做。
|
|
133
|
+
* 60s 没有新事件先标 `instructionOverdue`(看板可见、主 Agent 可催),
|
|
134
|
+
* 180s 仍无增长就按 no-ack 收束,避免「指示已下、那边根本没跑」无限挂起。
|
|
135
|
+
*/
|
|
136
|
+
export const INSTRUCTION_ACK_NOTICE_MS = 60000;
|
|
137
|
+
export const INSTRUCTION_ACK_DEADLINE_MS = 180000;
|
|
138
|
+
/*
|
|
139
|
+
* 正向回执的观察频率。5s 足以在 60s 提醒前发现「子会话已在动」,同时把
|
|
140
|
+
* 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
|
|
141
|
+
*/
|
|
142
|
+
export const INSTRUCTION_POLL_MS = 5000;
|
|
69
143
|
export const TOTAL_TIMEOUT_MS = 1200000;
|
|
70
144
|
export const DISPOSE_TIMEOUT_MS = 5000;
|
|
71
145
|
export const STALE_PENDING_MS = 10 * 60 * 1000;
|
|
@@ -577,6 +651,8 @@ export function timeoutBlockedPatch(subtask, cwd, message, artifactExists = exis
|
|
|
577
651
|
return {
|
|
578
652
|
patch: {
|
|
579
653
|
status: 'blocked',
|
|
654
|
+
closure: 'blocked',
|
|
655
|
+
blockedKind: 'timeout',
|
|
580
656
|
progress: 100,
|
|
581
657
|
finishedAt: Date.now(),
|
|
582
658
|
error: message + artifactNote,
|
|
@@ -618,8 +694,32 @@ export function budgetResetError(item, subtask, cwd, artifactExists = existsSync
|
|
|
618
694
|
* that need the environment: the strict/legacy switch and the file check.
|
|
619
695
|
*/
|
|
620
696
|
function settleFromOutput(record, subtask, output, guard, options) {
|
|
621
|
-
|
|
697
|
+
/*
|
|
698
|
+
* [1.11.0] 已经升级的请示不能被收尾正文覆盖。
|
|
699
|
+
*
|
|
700
|
+
* `dsh_workplan_escalate` 在子会话中途就写下了 blocked + escalated。子 Agent
|
|
701
|
+
* 随后仍可能补一段结果块(甚至写 done),如果这里照常 adjudicate,就会把
|
|
702
|
+
* 「等人拍板」洗成「完成/普通失败」,提问也随之丢失。升级一旦写入,本轮
|
|
703
|
+
* 的最终判定只能保留它。
|
|
704
|
+
*/
|
|
705
|
+
const current = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
706
|
+
if (current?.closure === 'escalated')
|
|
707
|
+
return { status: 'blocked', escalated: true };
|
|
708
|
+
const verdict = adjudicateResult({
|
|
709
|
+
output,
|
|
710
|
+
strict: options.strictEvidence !== false,
|
|
711
|
+
/*
|
|
712
|
+
* [1.11.0] 计划验收进入裁决(T5 C4 / T10 D-01)。
|
|
713
|
+
*
|
|
714
|
+
* 不传这一项时,子 Agent 可以用一条自创验收项绕过整张验收表;传了之后
|
|
715
|
+
* 「5 条只回 1 条」会在收尾时直接变成 blocked/unverified,而不是等到
|
|
716
|
+
* 交付才被用户发现。
|
|
717
|
+
*/
|
|
718
|
+
expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
|
|
719
|
+
});
|
|
622
720
|
const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists);
|
|
721
|
+
const escalated = verdict.status === 'blocked'
|
|
722
|
+
&& typeof verdict.question === 'string' && verdict.question.trim() !== '';
|
|
623
723
|
writeSubtaskStatus(record, subtask.id, {
|
|
624
724
|
status: verdict.status,
|
|
625
725
|
progress: 100,
|
|
@@ -631,14 +731,41 @@ function settleFromOutput(record, subtask, output, guard, options) {
|
|
|
631
731
|
artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
|
|
632
732
|
missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
|
|
633
733
|
needs: verdict.needs.length > 0 ? verdict.needs : undefined,
|
|
734
|
+
/*
|
|
735
|
+
* [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
|
|
736
|
+
* `question` 就是同一条请示。它仍然写成 blocked 投影,但 closure 是
|
|
737
|
+
* escalated,看板与主 Agent 看到的都是「等指示」而不是普通失败。
|
|
738
|
+
*/
|
|
739
|
+
...(escalated
|
|
740
|
+
? {
|
|
741
|
+
closure: 'escalated',
|
|
742
|
+
blockedKind: 'escalated',
|
|
743
|
+
question: verdict.question,
|
|
744
|
+
options: verdict.options,
|
|
745
|
+
escalatedAt: Date.now(),
|
|
746
|
+
escalationSeq: Number(current?.revision ?? 0) + 1,
|
|
747
|
+
}
|
|
748
|
+
: verdict.status === 'done'
|
|
749
|
+
/*
|
|
750
|
+
* [1.11.0] 完成必须落到 `closure:'done'`,不是 `blocked`。
|
|
751
|
+
*
|
|
752
|
+
* T9 的 P1 探针抓到过这里:完成路径固定写 `blocked/failed`,于是
|
|
753
|
+
* `done` 在执行路径不可达,「完成未回报」门禁与 `reportPending` 全部
|
|
754
|
+
* 恒不成立,进度栏也只能显示「失败」。完成与受阻是两种语义,必须分开。
|
|
755
|
+
*/
|
|
756
|
+
? { closure: 'done', blockedKind: null }
|
|
757
|
+
: {
|
|
758
|
+
closure: 'blocked',
|
|
759
|
+
blockedKind: 'failed',
|
|
760
|
+
}),
|
|
634
761
|
}, guard);
|
|
635
762
|
if (verdict.status === 'blocked') {
|
|
636
|
-
recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard);
|
|
763
|
+
recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (verdict.error ?? '未完成'), guard);
|
|
637
764
|
}
|
|
638
765
|
else if (checked.missingArtifacts.length > 0) {
|
|
639
766
|
recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard);
|
|
640
767
|
}
|
|
641
|
-
return verdict;
|
|
768
|
+
return { ...verdict, escalated };
|
|
642
769
|
}
|
|
643
770
|
/**
|
|
644
771
|
* Retry policy for one child attempt.
|
|
@@ -725,6 +852,9 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
725
852
|
if (Date.now() >= deadline)
|
|
726
853
|
throw new PlanError('总执行超时', 'TOTAL_TIMEOUT');
|
|
727
854
|
let activation = null;
|
|
855
|
+
// Declared outside the try so the per-attempt finally can always cancel
|
|
856
|
+
// the receipt timers, even when activation itself failed.
|
|
857
|
+
let clearAckTimers = () => { };
|
|
728
858
|
try {
|
|
729
859
|
if (child.controller.signal.aborted) {
|
|
730
860
|
throw child.controller.signal.reason ?? abortError();
|
|
@@ -746,6 +876,16 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
746
876
|
title: item.title,
|
|
747
877
|
status: item.status,
|
|
748
878
|
summary: item.summary,
|
|
879
|
+
/*
|
|
880
|
+
* [1.11.0] 跨部门交接物必须能被下游直接消费(用户 m00687)。
|
|
881
|
+
*
|
|
882
|
+
* 只传状态和摘要时,下游部门知道「上游做完了」,却不知道
|
|
883
|
+
* 产物在哪,只能重做或向主 Agent 再提一次需求。这里把上游
|
|
884
|
+
* 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
|
|
885
|
+
*/
|
|
886
|
+
artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
|
|
887
|
+
.filter((artifact) => artifact?.exists === true && typeof artifact?.ref === 'string')
|
|
888
|
+
.map((artifact) => String(artifact.ref)),
|
|
749
889
|
})),
|
|
750
890
|
cwd: options.cwd,
|
|
751
891
|
conversationContext,
|
|
@@ -768,10 +908,86 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
768
908
|
if (!activation || typeof activation.result?.then !== 'function') {
|
|
769
909
|
throw new PlanError('子 Agent 没有返回可等待的结果', 'NO_ACTIVATION');
|
|
770
910
|
}
|
|
771
|
-
|
|
911
|
+
/*
|
|
912
|
+
* [1.11.0] `assigned` 是「已交给子会话」,不是「子会话已确认」。
|
|
913
|
+
*
|
|
914
|
+
* 旧代码只写 childId + 10%,从这一刻起到子 Agent 真正产出第一个事件
|
|
915
|
+
* 之间没有任何可观察状态:用户看到 10% 长时间不动,也无法区分
|
|
916
|
+
* 「没启动」「启动失败」「在跑一个很长的工具」。这里把派发序号和
|
|
917
|
+
* 回执窗口一起写进状态,后面的 onProgress/定时器才有据可依。
|
|
918
|
+
*/
|
|
919
|
+
const assignedAt = Date.now();
|
|
920
|
+
const dispatchSeq = Number(record.dispatchSeq ?? 0) + 1;
|
|
921
|
+
record.dispatchSeq = dispatchSeq;
|
|
922
|
+
const assigned = writeSubtaskStatus(record, subtask.id, {
|
|
772
923
|
childId: activation.childId,
|
|
773
924
|
progress: 10,
|
|
925
|
+
closure: 'assigned',
|
|
926
|
+
assignedAt,
|
|
927
|
+
dispatchSeq,
|
|
928
|
+
// A retry is a fresh attempt: no stale receipt or escalation survives it.
|
|
929
|
+
ackedAt: null,
|
|
930
|
+
ackEvidence: undefined,
|
|
931
|
+
ackOverdue: false,
|
|
932
|
+
escalatedAt: null,
|
|
933
|
+
escalationSeq: null,
|
|
934
|
+
question: null,
|
|
935
|
+
options: [],
|
|
936
|
+
blockedKind: null,
|
|
774
937
|
}, guard);
|
|
938
|
+
if (!assigned)
|
|
939
|
+
return;
|
|
940
|
+
const ackTimers = [];
|
|
941
|
+
clearAckTimers = () => {
|
|
942
|
+
while (ackTimers.length > 0) {
|
|
943
|
+
const timer = ackTimers.pop();
|
|
944
|
+
if (timer)
|
|
945
|
+
clearTimeout(timer);
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
const attemptRow = () => record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
949
|
+
const noticeTimer = setTimeout(() => {
|
|
950
|
+
if (guard.timedOut)
|
|
951
|
+
return;
|
|
952
|
+
const row = attemptRow();
|
|
953
|
+
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
|
|
954
|
+
return;
|
|
955
|
+
writeSubtaskStatus(record, subtask.id, { ackOverdue: true }, guard);
|
|
956
|
+
}, ASSIGN_ACK_NOTICE_MS);
|
|
957
|
+
noticeTimer.unref?.();
|
|
958
|
+
ackTimers.push(noticeTimer);
|
|
959
|
+
/*
|
|
960
|
+
* [1.11.0] 180s 仍无回执 → 明确收束为 no-ack,而不是继续静默等待。
|
|
961
|
+
*
|
|
962
|
+
* 看门狗默认空闲窗口是 300s,而「根本没启动」和「在慢慢想」在日志上
|
|
963
|
+
* 都表现为没有新事件。先把状态写成 blocked + blockedKind:'no-ack',
|
|
964
|
+
* 再中止子会话;主 Agent 因此能立刻看到原因,也能选择续跑。
|
|
965
|
+
*/
|
|
966
|
+
const deadlineTimer = setTimeout(() => {
|
|
967
|
+
if (guard.timedOut)
|
|
968
|
+
return;
|
|
969
|
+
const row = attemptRow();
|
|
970
|
+
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
|
|
971
|
+
return;
|
|
972
|
+
const seconds = Math.round(ASSIGN_ACK_DEADLINE_MS / 1000);
|
|
973
|
+
const message = `派发后 ${seconds}s 未收到子 Agent 任何新事件(no-ack)`;
|
|
974
|
+
writeSubtaskStatus(record, subtask.id, {
|
|
975
|
+
status: 'blocked',
|
|
976
|
+
closure: 'blocked',
|
|
977
|
+
blockedKind: 'no-ack',
|
|
978
|
+
progress: 100,
|
|
979
|
+
finishedAt: Date.now(),
|
|
980
|
+
ackOverdue: true,
|
|
981
|
+
error: message,
|
|
982
|
+
summary: `未完成:${message}`,
|
|
983
|
+
}, guard);
|
|
984
|
+
recordSubtaskError(record, subtask.id, message, guard);
|
|
985
|
+
if (!child.controller.signal.aborted) {
|
|
986
|
+
child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }));
|
|
987
|
+
}
|
|
988
|
+
}, ASSIGN_ACK_DEADLINE_MS);
|
|
989
|
+
deadlineTimer.unref?.();
|
|
990
|
+
ackTimers.push(deadlineTimer);
|
|
775
991
|
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
|
|
776
992
|
const hardTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
|
|
777
993
|
const watchdog = createProgressWatchdog({
|
|
@@ -790,13 +1006,32 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
790
1006
|
// Poll often enough to notice growth inside a short idle window, but
|
|
791
1007
|
// never more than four times per window.
|
|
792
1008
|
pollMs: Math.min(CHILD_POLL_MS, Math.max(20, Math.floor(idleTimeoutMs / 4))),
|
|
793
|
-
onProgress: ({ now }) => {
|
|
1009
|
+
onProgress: ({ now, seq, elapsedMs }) => {
|
|
794
1010
|
if (guard.timedOut)
|
|
795
1011
|
return;
|
|
796
1012
|
// Visible liveness: the dashboard can show that a slow subtask is
|
|
797
1013
|
// still producing events instead of looking frozen.
|
|
798
1014
|
record.heartbeatAt = now;
|
|
799
1015
|
record.updatedAt = now;
|
|
1016
|
+
/*
|
|
1017
|
+
* [1.11.0] 第一次观察到子会话日志增长 = 回执。
|
|
1018
|
+
*
|
|
1019
|
+
* 这是唯一能证明「子 Agent 已经在动」的廉价事实:不用它自己的
|
|
1020
|
+
* 汇报(可能永远等不到),只看它有没有产生新事件。回执写入后
|
|
1021
|
+
* 两个 no-ack 定时器立即撤销,正常的长任务不会被误判。
|
|
1022
|
+
*/
|
|
1023
|
+
const row = attemptRow();
|
|
1024
|
+
if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
|
|
1025
|
+
return;
|
|
1026
|
+
const acked = writeSubtaskStatus(record, subtask.id, {
|
|
1027
|
+
closure: 'acknowledged',
|
|
1028
|
+
ackedAt: now,
|
|
1029
|
+
ackEvidence: { seq, elapsedMs },
|
|
1030
|
+
ackOverdue: false,
|
|
1031
|
+
progress: Math.max(Number(row.progress ?? 10), 15),
|
|
1032
|
+
}, guard);
|
|
1033
|
+
if (acked)
|
|
1034
|
+
clearAckTimers();
|
|
800
1035
|
},
|
|
801
1036
|
makeError: (reason) => new PlanError(reason === 'stalled'
|
|
802
1037
|
? `子任务 ${subtask.id} 无进展超时(${idleTimeoutMs}ms 内子 Agent 没有产生任何新事件)`
|
|
@@ -890,15 +1125,28 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
890
1125
|
break;
|
|
891
1126
|
}
|
|
892
1127
|
finally {
|
|
1128
|
+
clearAckTimers();
|
|
893
1129
|
if (activation) {
|
|
894
1130
|
await disposeActivation(activation, record, subtask.id, guard);
|
|
895
1131
|
activation = null;
|
|
896
1132
|
}
|
|
897
1133
|
}
|
|
898
1134
|
}
|
|
1135
|
+
/*
|
|
1136
|
+
* [1.11.0] 已升级的请示不被最终的失败收束覆盖。
|
|
1137
|
+
*
|
|
1138
|
+
* 子 Agent 可能先调用 escalate,再因为中断/超时走到这里;此时问题已经
|
|
1139
|
+
* 写入状态,把它改成普通 blocked 会让主 Agent 永远看不到要回答什么。
|
|
1140
|
+
*/
|
|
1141
|
+
const finalRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
1142
|
+
if (finalRow?.closure === 'escalated') {
|
|
1143
|
+
return interruptedFlag ? { interrupted: true } : undefined;
|
|
1144
|
+
}
|
|
899
1145
|
const message = describeError(lastError ?? new Error('未知失败'));
|
|
900
1146
|
writeSubtaskStatus(record, subtask.id, {
|
|
901
1147
|
status: 'blocked',
|
|
1148
|
+
closure: 'blocked',
|
|
1149
|
+
blockedKind: 'failed',
|
|
902
1150
|
progress: 100,
|
|
903
1151
|
finishedAt: Date.now(),
|
|
904
1152
|
error: truncate(message, 2000),
|
|
@@ -919,8 +1167,15 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
919
1167
|
catch (error) {
|
|
920
1168
|
const message = describeError(error);
|
|
921
1169
|
try {
|
|
1170
|
+
const row = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
1171
|
+
if (row?.closure === 'escalated') {
|
|
1172
|
+
recordSubtaskError(record, subtask.id, `升级后发生异常,保留待指示状态:${message}`, guard);
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
922
1175
|
writeSubtaskStatus(record, subtask.id, {
|
|
923
1176
|
status: 'blocked',
|
|
1177
|
+
closure: 'blocked',
|
|
1178
|
+
blockedKind: 'failed',
|
|
924
1179
|
progress: 100,
|
|
925
1180
|
finishedAt: Date.now(),
|
|
926
1181
|
error: truncate(message, 2000),
|
|
@@ -978,8 +1233,25 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
|
|
|
978
1233
|
const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
|
|
979
1234
|
ceilingLanded = Array.isArray(landed) ? landed : [];
|
|
980
1235
|
ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat);
|
|
981
|
-
|
|
982
|
-
|
|
1236
|
+
/*
|
|
1237
|
+
* [1.11.0] An escalation outranks the ceiling.
|
|
1238
|
+
*
|
|
1239
|
+
* The child may have written `escalated` seconds before this timer fired;
|
|
1240
|
+
* turning that into a plain timeout would erase the question the main
|
|
1241
|
+
* Agent has to answer. The activation is still aborted, but the row keeps
|
|
1242
|
+
* its pending-decision state.
|
|
1243
|
+
*/
|
|
1244
|
+
const existing = record.statuses.find((item) => item?.subtaskId === subtask.id);
|
|
1245
|
+
if (existing?.closure === 'escalated') {
|
|
1246
|
+
record.errors = [
|
|
1247
|
+
...(record.errors ?? []),
|
|
1248
|
+
`${subtask.id}: 已达执行上限,但该子任务已在等待指示,保留 escalated 状态`,
|
|
1249
|
+
].slice(-20);
|
|
1250
|
+
}
|
|
1251
|
+
else {
|
|
1252
|
+
record.statuses = applyStatus(record.statuses, subtask.id, patch);
|
|
1253
|
+
record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
|
|
1254
|
+
}
|
|
983
1255
|
record.updatedAt = Date.now();
|
|
984
1256
|
}
|
|
985
1257
|
catch (error) {
|
|
@@ -1159,6 +1431,29 @@ export function modelStatusLines(statuses) {
|
|
|
1159
1431
|
updatedBy: item.updatedBy ?? null,
|
|
1160
1432
|
missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
|
|
1161
1433
|
needs: Array.isArray(item.needs) ? item.needs : [],
|
|
1434
|
+
// [1.11.0] 闭环阶段必须进入模型可读面:只暴露四值 status 时,
|
|
1435
|
+
// 「在等指示」和「做失败了」在工具输出里长得一模一样。
|
|
1436
|
+
closure: item.closure ?? null,
|
|
1437
|
+
blockedKind: item.blockedKind ?? null,
|
|
1438
|
+
question: item.question ?? null,
|
|
1439
|
+
options: Array.isArray(item.options) ? item.options : [],
|
|
1440
|
+
ackOverdue: item.ackOverdue === true,
|
|
1441
|
+
escalatedAt: item.escalatedAt ?? null,
|
|
1442
|
+
instruction: item.instruction?.text ? truncate(item.instruction.text, 500) : null,
|
|
1443
|
+
/*
|
|
1444
|
+
* [1.11.0] 跨部门需求的待处理项必须出现在模型可读面(用户 m00687)。
|
|
1445
|
+
*
|
|
1446
|
+
* 只放在结果消息里时,主 Agent 一旦错过那一轮就再也看不到「还有一条
|
|
1447
|
+
* 需求没处置」,而交付门禁却一直拦着。status 工具是与进度同源的读取口,
|
|
1448
|
+
* 这里只暴露未处置项,避免把已答复的历史反复塞进上下文。
|
|
1449
|
+
*/
|
|
1450
|
+
openHandoffs: openHandoffs(item).map((handoff) => ({
|
|
1451
|
+
id: handoff.id,
|
|
1452
|
+
request: truncate(String(handoff.request ?? ''), 300),
|
|
1453
|
+
department: handoff.department ?? null,
|
|
1454
|
+
status: handoff.status,
|
|
1455
|
+
})),
|
|
1456
|
+
reportedAt: item.reportedAt ?? null,
|
|
1162
1457
|
}));
|
|
1163
1458
|
}
|
|
1164
1459
|
export function buildRoundResult(record, sessionId, limits) {
|
|
@@ -1175,6 +1470,14 @@ export function buildRoundResult(record, sessionId, limits) {
|
|
|
1175
1470
|
phase: record.phase,
|
|
1176
1471
|
resumeCount: Number(record.resumeCount ?? 0),
|
|
1177
1472
|
resumeAvailable: canResumePlan(record, limits.maxResumes).resume,
|
|
1473
|
+
// [1.11.0] 结果消息也带上修订号,回放时才知道这份结果属于哪一版计划。
|
|
1474
|
+
planRevision: Number(record.planRevision ?? 0),
|
|
1475
|
+
/*
|
|
1476
|
+
* [1.11.0] C-17:记录级闭环事实随结果消息下发,让摘要里的判定与
|
|
1477
|
+
* `deliveryReady` 门禁读同一组输入(否则「结果说完成、present 被拒」)。
|
|
1478
|
+
*/
|
|
1479
|
+
changePending: record.changeRequest?.status === 'pending',
|
|
1480
|
+
reportPending: record.reportPending === true,
|
|
1178
1481
|
});
|
|
1179
1482
|
}
|
|
1180
1483
|
/**
|
|
@@ -1232,6 +1535,11 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
1232
1535
|
* its side effects) while giving the rest a second chance, and the resume
|
|
1233
1536
|
* budget stops a subtask that always fails from looping forever.
|
|
1234
1537
|
*/
|
|
1538
|
+
/*
|
|
1539
|
+
* [1.11.0] 重规划 cancel 留下的悬挂下游,在派发前显式收束成 blocked
|
|
1540
|
+
* (T4 D-T4-02)。否则它们永远 pending,既不报错也不进入交付阻塞。
|
|
1541
|
+
*/
|
|
1542
|
+
record.statuses = blockCancelledDependents(record.plan, record.statuses);
|
|
1235
1543
|
const resume = canResumePlan(record, options.maxResumes ?? MAX_PLAN_RESUMES);
|
|
1236
1544
|
if (resume.resume) {
|
|
1237
1545
|
/*
|
|
@@ -1305,9 +1613,19 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
1305
1613
|
* an older plan or a debugging session can keep plain status semantics.
|
|
1306
1614
|
*/
|
|
1307
1615
|
const gate = options.artifactGate !== false;
|
|
1308
|
-
const ready = readySubtasks(record.plan, record.statuses, gate
|
|
1616
|
+
const ready = readySubtasks(record.plan, liveStatuses(record.statuses), gate
|
|
1309
1617
|
? {
|
|
1618
|
+
/*
|
|
1619
|
+
* [1.11.0] 未验收的 done 不再解锁下游(T5 C5 / T8 S1-05)。
|
|
1620
|
+
*
|
|
1621
|
+
* `done` 只说明子 Agent 交了东西;`unverified`/`failed` 说明
|
|
1622
|
+
* 交付内容没有通过验收。让下游在这时开跑,等于把未验证的结论
|
|
1623
|
+
* 当上游契约使用——跨部门链条会一路放大错误。legacy(旧日志)
|
|
1624
|
+
* 与 structured 仍放行,避免历史计划整体卡死。
|
|
1625
|
+
*/
|
|
1310
1626
|
dependencyOk: (dependency) => dependency?.status === 'done'
|
|
1627
|
+
&& dependency?.verification !== 'unverified'
|
|
1628
|
+
&& dependency?.verification !== 'failed'
|
|
1311
1629
|
&& !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
|
|
1312
1630
|
}
|
|
1313
1631
|
: {});
|
|
@@ -1322,7 +1640,7 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
1322
1640
|
* status, the plan turned `blocked`, and a resume was billed against
|
|
1323
1641
|
* the failure budget. Keep them `pending`, and record the actual cause.
|
|
1324
1642
|
*/
|
|
1325
|
-
const pending = record.statuses.filter((item) => item.status === 'pending');
|
|
1643
|
+
const pending = liveStatuses(record.statuses).filter((item) => item.status === 'pending');
|
|
1326
1644
|
if (pending.length > 0) {
|
|
1327
1645
|
const reasons = pending.map((item) => `${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`);
|
|
1328
1646
|
const message = `本轮结束,仍有 ${pending.length} 项保持 pending(不是失败,也未级联成 blocked):${reasons.slice(0, 6).join(';')}`;
|
|
@@ -1404,8 +1722,8 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
1404
1722
|
* `blocked` for real failures, and report `paused` when only pending work
|
|
1405
1723
|
* is left, so a resume is not billed against the failure budget.
|
|
1406
1724
|
*/
|
|
1407
|
-
const hasBlocked = record.statuses.some((item) => item.status === 'blocked');
|
|
1408
|
-
const hasPending = record.statuses.some((item) => item.status === 'pending');
|
|
1725
|
+
const hasBlocked = liveStatuses(record.statuses).some((item) => item.status === 'blocked');
|
|
1726
|
+
const hasPending = liveStatuses(record.statuses).some((item) => item.status === 'pending');
|
|
1409
1727
|
record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses));
|
|
1410
1728
|
}
|
|
1411
1729
|
catch (error) {
|
|
@@ -1481,6 +1799,9 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
1481
1799
|
* or 100 % depending on which branch happened to write it.
|
|
1482
1800
|
*/
|
|
1483
1801
|
record.statuses = record.statuses.map((item) => {
|
|
1802
|
+
// [1.11.0] 被重规划的行不参与「失败收敛」:它们本来就是闭态旧行。
|
|
1803
|
+
if (item.closure === 'replanned')
|
|
1804
|
+
return item;
|
|
1484
1805
|
if (item.status === 'pending' || item.status === 'in_progress') {
|
|
1485
1806
|
return {
|
|
1486
1807
|
...item,
|
|
@@ -1673,7 +1994,7 @@ function serialisePlan(record, session) {
|
|
|
1673
1994
|
* 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
|
|
1674
1995
|
*/
|
|
1675
1996
|
const violations = aggregateInvariantViolations(snapshot, phase);
|
|
1676
|
-
const readiness =
|
|
1997
|
+
const readiness = readinessOf(record, snapshot);
|
|
1677
1998
|
return {
|
|
1678
1999
|
sessionId: session.id,
|
|
1679
2000
|
planId: record.planId ?? plan?.planId ?? null,
|
|
@@ -1712,6 +2033,16 @@ function serialisePlan(record, session) {
|
|
|
1712
2033
|
deliveryReady: readiness.ready,
|
|
1713
2034
|
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
1714
2035
|
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
2036
|
+
/*
|
|
2037
|
+
* [1.11.0] 重规划与回报状态随载荷下发(T7 C-15)。
|
|
2038
|
+
*
|
|
2039
|
+
* `planRevision` 让界面能显示「第 N 次修订」;`changeRequest` 是执行中
|
|
2040
|
+
* 收到、尚未重规划的用户变更;`reportPending` 表示完成结果还没成功回报。
|
|
2041
|
+
* 三者都来自 record 的同一份事实,不另建缓存。
|
|
2042
|
+
*/
|
|
2043
|
+
planRevision: Number(record.planRevision ?? 0),
|
|
2044
|
+
changeRequest: record.changeRequest ?? null,
|
|
2045
|
+
reportPending: record.reportPending === true,
|
|
1715
2046
|
/*
|
|
1716
2047
|
* Liveness and resume bookkeeping. Without these the dashboard could not
|
|
1717
2048
|
* tell a slow-but-alive child from a wedged one, and the model could not
|
|
@@ -1862,6 +2193,8 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1862
2193
|
superseded: false,
|
|
1863
2194
|
supersededBy: undefined,
|
|
1864
2195
|
errors: [],
|
|
2196
|
+
planRevision: Number(plan?.planRevision ?? 0) || 0,
|
|
2197
|
+
changeRequest: null,
|
|
1865
2198
|
};
|
|
1866
2199
|
snapshots.set(plan.planId, snap);
|
|
1867
2200
|
}
|
|
@@ -1905,6 +2238,44 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1905
2238
|
* that was the 13/14 → 5/14 replay regression. A plan never inherits
|
|
1906
2239
|
* another plan's round phase or resume counter (each snapshot owns them).
|
|
1907
2240
|
*/
|
|
2241
|
+
/*
|
|
2242
|
+
* [1.11.0] 重规划记录:采用 durable 消息里的完整修订计划,不重新推导。
|
|
2243
|
+
* 旧行在同一份 plan 里带 supersededAt,状态条目同步标 closure='replanned'。
|
|
2244
|
+
*/
|
|
2245
|
+
const replan = parseReplanMessage(event.data);
|
|
2246
|
+
if (replan && typeof replan.planId === 'string') {
|
|
2247
|
+
const snap = snapshots.get(replan.planId);
|
|
2248
|
+
if (snap) {
|
|
2249
|
+
snap.plan = replan.plan;
|
|
2250
|
+
snap.planRevision = Number(replan.revision) || snap.planRevision;
|
|
2251
|
+
snap.statuses = applyReplanStatuses(snap.statuses, replan);
|
|
2252
|
+
if (snap.changeRequest && snap.changeRequest.status !== 'replanned') {
|
|
2253
|
+
snap.changeRequest = {
|
|
2254
|
+
...snap.changeRequest,
|
|
2255
|
+
status: 'replanned',
|
|
2256
|
+
replannedAt: replan.at,
|
|
2257
|
+
planRevision: snap.planRevision,
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
/*
|
|
2263
|
+
* [1.11.0] 执行中收到的变更:恢复成 changeRequest,刷新后仍然可见、
|
|
2264
|
+
* 仍然阻止“静默收尾”。
|
|
2265
|
+
*/
|
|
2266
|
+
const change = parseChangeRequestMessage(event.data);
|
|
2267
|
+
if (change && typeof change.planId === 'string') {
|
|
2268
|
+
const snap = snapshots.get(change.planId);
|
|
2269
|
+
if (snap) {
|
|
2270
|
+
snap.changeRequest = {
|
|
2271
|
+
seq: change.seq,
|
|
2272
|
+
text: change.text,
|
|
2273
|
+
at: change.at,
|
|
2274
|
+
turn: change.turn,
|
|
2275
|
+
status: 'pending',
|
|
2276
|
+
};
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
1908
2279
|
const result = parseResultMessage(event.data);
|
|
1909
2280
|
if (result && typeof result.planId === 'string') {
|
|
1910
2281
|
const snap = snapshots.get(result.planId);
|
|
@@ -2156,6 +2527,19 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
2156
2527
|
superseded,
|
|
2157
2528
|
supersedeRecorded: superseded,
|
|
2158
2529
|
supersededBy: superseded ? chosen.supersededBy : undefined,
|
|
2530
|
+
/*
|
|
2531
|
+
* [1.11.0] 回放也恢复修订号与未处理变更。`reportPending` 由状态本身派生:
|
|
2532
|
+
* 存在 done 行却没到 reported,说明当时的结果消息没有成功写进会话。
|
|
2533
|
+
*/
|
|
2534
|
+
planRevision: chosen.planRevision,
|
|
2535
|
+
changeRequest: chosen.changeRequest,
|
|
2536
|
+
/*
|
|
2537
|
+
* [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
|
|
2538
|
+
* 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
|
|
2539
|
+
* 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
|
|
2540
|
+
* 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
|
|
2541
|
+
*/
|
|
2542
|
+
reportPending: statuses.some((item) => item?.status === 'done' && item?.closure === 'done'),
|
|
2159
2543
|
};
|
|
2160
2544
|
}
|
|
2161
2545
|
function liveSessions(ctx) {
|
|
@@ -2296,6 +2680,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2296
2680
|
if (downstream?.kind !== 'enter')
|
|
2297
2681
|
return downstream;
|
|
2298
2682
|
try {
|
|
2683
|
+
/*
|
|
2684
|
+
* [1.11.0] 回报自愈(契约 §7.3 B4):上一轮结果消息已写入,但回报标记
|
|
2685
|
+
* 写失败/进程中断时,下一步 pre-step 幂等补齐,不重复追加上下文。
|
|
2686
|
+
*/
|
|
2687
|
+
const session = payload.agent?.session;
|
|
2688
|
+
const known = session ? state.records.get(session.id) : null;
|
|
2689
|
+
if (known?.plan && known.reportPending === true && known.resultWritten === true) {
|
|
2690
|
+
const changed = markReported(known, session, `${known.plan.planId}:${known.dispatchedAt ?? 0}`);
|
|
2691
|
+
if (changed > 0) {
|
|
2692
|
+
known.reportPending = (known.statuses ?? []).some((item) => item?.status === 'done' && item?.closure === 'done');
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2299
2695
|
return await maybePlan(ctx, state, payload, downstream, { ...options, limits });
|
|
2300
2696
|
}
|
|
2301
2697
|
catch (error) {
|
|
@@ -2425,6 +2821,59 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2425
2821
|
hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
|
|
2426
2822
|
};
|
|
2427
2823
|
}
|
|
2824
|
+
/*
|
|
2825
|
+
* [1.11.0] 待指示行的两条合法出口(T4 S4→S5 / S4→S6)。
|
|
2826
|
+
*
|
|
2827
|
+
* `dsh_workplan_update` 也是 `instruct` 的等价入口:带 instruction 即恢复
|
|
2828
|
+
* 推进,不带 instruction 直接 in_progress/done 会把一条未回答的请示洗成
|
|
2829
|
+
* 「在做/做完」,所以显式拒绝,并告诉主 Agent 该用哪个字段。
|
|
2830
|
+
*/
|
|
2831
|
+
const instruction = typeof args?.instruction === 'string' ? args.instruction.trim() : '';
|
|
2832
|
+
if (instruction) {
|
|
2833
|
+
if (current?.closure !== 'escalated') {
|
|
2834
|
+
return {
|
|
2835
|
+
ok: false,
|
|
2836
|
+
code: 'NOT_ESCALATED',
|
|
2837
|
+
planId: record.plan.planId,
|
|
2838
|
+
subtaskId,
|
|
2839
|
+
error: '该子任务不在待指示状态,不需要 instruction;普通受阻请直接改判。',
|
|
2840
|
+
};
|
|
2841
|
+
}
|
|
2842
|
+
if (status !== 'in_progress') {
|
|
2843
|
+
return {
|
|
2844
|
+
ok: false,
|
|
2845
|
+
code: 'INSTRUCTION_REQUIRES_IN_PROGRESS',
|
|
2846
|
+
planId: record.plan.planId,
|
|
2847
|
+
subtaskId,
|
|
2848
|
+
error: '下发 instruction 时 status 必须是 in_progress(或改用 dsh_workplan_instruct)。',
|
|
2849
|
+
};
|
|
2850
|
+
}
|
|
2851
|
+
return instructSubtask(agent, {
|
|
2852
|
+
planId: args?.planId,
|
|
2853
|
+
subtaskId,
|
|
2854
|
+
instruction,
|
|
2855
|
+
}, undefined, record);
|
|
2856
|
+
}
|
|
2857
|
+
if (current?.closure === 'escalated') {
|
|
2858
|
+
if (status === 'done') {
|
|
2859
|
+
return {
|
|
2860
|
+
ok: false,
|
|
2861
|
+
code: 'ESCALATION_OPEN',
|
|
2862
|
+
planId: record.plan.planId,
|
|
2863
|
+
subtaskId,
|
|
2864
|
+
error: '该子任务仍在等待指示,不能直接改判 done:请先给出 instruction,或明确改判 blocked 放弃。',
|
|
2865
|
+
};
|
|
2866
|
+
}
|
|
2867
|
+
if (status === 'in_progress') {
|
|
2868
|
+
return {
|
|
2869
|
+
ok: false,
|
|
2870
|
+
code: 'INSTRUCTION_REQUIRED',
|
|
2871
|
+
planId: record.plan.planId,
|
|
2872
|
+
subtaskId,
|
|
2873
|
+
error: '该子任务正在等待指示:恢复推进必须传 instruction(或调用 dsh_workplan_instruct),不能只改 status。',
|
|
2874
|
+
};
|
|
2875
|
+
}
|
|
2876
|
+
}
|
|
2428
2877
|
const revision = Number(current?.revision ?? 0) + 1;
|
|
2429
2878
|
/*
|
|
2430
2879
|
* [1.8.13] A manual verdict can carry structured evidence.
|
|
@@ -2451,6 +2900,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2451
2900
|
summary: summary || undefined,
|
|
2452
2901
|
error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
|
|
2453
2902
|
...evidencePatch,
|
|
2903
|
+
/*
|
|
2904
|
+
* [1.11.0] 明确放弃(blocked)必须同时关掉 escalated,否则
|
|
2905
|
+
* applyStatus 会保留「等指示」投影,主 Agent 的放弃写了个寂寞。
|
|
2906
|
+
*/
|
|
2907
|
+
...(current?.closure === 'escalated' && status === 'blocked'
|
|
2908
|
+
? { closure: 'blocked', blockedKind: 'failed', question: null, options: [] }
|
|
2909
|
+
: {}),
|
|
2454
2910
|
revision,
|
|
2455
2911
|
updatedBy: 'agent',
|
|
2456
2912
|
});
|
|
@@ -2477,6 +2933,12 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2477
2933
|
acceptance: writtenRow?.acceptance,
|
|
2478
2934
|
artifacts: writtenRow?.artifacts,
|
|
2479
2935
|
missingArtifacts: writtenRow?.missingArtifacts,
|
|
2936
|
+
closure: writtenRow?.closure,
|
|
2937
|
+
blockedKind: writtenRow?.blockedKind,
|
|
2938
|
+
question: writtenRow?.question,
|
|
2939
|
+
options: writtenRow?.options,
|
|
2940
|
+
instruction: writtenRow?.instruction,
|
|
2941
|
+
instructionSeq: writtenRow?.instructionSeq,
|
|
2480
2942
|
}), { surfaceOp: 'append' });
|
|
2481
2943
|
}
|
|
2482
2944
|
catch (error) {
|
|
@@ -2495,7 +2957,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2495
2957
|
record.updatedAt = Date.now();
|
|
2496
2958
|
const snapshot = derivePlanSnapshot(record.statuses);
|
|
2497
2959
|
const written = snapshot.statuses.find((item) => item.subtaskId === subtaskId);
|
|
2498
|
-
const readiness =
|
|
2960
|
+
const readiness = readinessOf(record, snapshot);
|
|
2499
2961
|
return {
|
|
2500
2962
|
ok: true,
|
|
2501
2963
|
planId: record.plan.planId,
|
|
@@ -2516,6 +2978,126 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2516
2978
|
}),
|
|
2517
2979
|
};
|
|
2518
2980
|
}
|
|
2981
|
+
/**
|
|
2982
|
+
* [1.11.0] C-11:需求变更的唯一写入入口(dsh_workplan_replan)。
|
|
2983
|
+
*
|
|
2984
|
+
* 为什么必须单独一个工具,而不是让模型直接改计划消息:
|
|
2985
|
+
* 1. 旧行的 `supersededAt` 与状态条的 `closure:'replanned'` 必须同一次写入,
|
|
2986
|
+
* 否则调度器会继续跑「已撤销」的工作;
|
|
2987
|
+
* 2. durable `workplan-replan` 带上完整修订计划,刷新后才能得到同一份定义;
|
|
2988
|
+
* 3. 执行中收到变更时,工具返回 `REPLAN_PLAN_RUNNING` 并保留 changeRequest,
|
|
2989
|
+
* 让模型等待而不是静默丢弃或强行中断正在跑的子任务。
|
|
2990
|
+
*/
|
|
2991
|
+
async function replanPlan(agent, args) {
|
|
2992
|
+
const session = agent?.session;
|
|
2993
|
+
if (!session)
|
|
2994
|
+
throw new PlanError('只能在会话内重规划', 'NO_SESSION');
|
|
2995
|
+
if (!isRootSession(session))
|
|
2996
|
+
throw new PlanError('子 Agent 不能重规划主计划', 'NOT_ROOT');
|
|
2997
|
+
let record = state.records.get(session.id);
|
|
2998
|
+
if (!record?.plan)
|
|
2999
|
+
record = reconstructFromSession(session, args?.planId);
|
|
3000
|
+
record = adoptRequestedPlan(session, record, args?.planId);
|
|
3001
|
+
if (!record?.plan)
|
|
3002
|
+
throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
|
|
3003
|
+
const planId = record.plan.planId;
|
|
3004
|
+
const revisionNow = Number(record.planRevision ?? record.plan?.planRevision ?? 0);
|
|
3005
|
+
const base = {
|
|
3006
|
+
ok: false,
|
|
3007
|
+
planId,
|
|
3008
|
+
planRevision: revisionNow,
|
|
3009
|
+
stats: derivePlanSnapshot(record.statuses).stats,
|
|
3010
|
+
};
|
|
3011
|
+
if (record.phase === 'cancelled' || record.phase === 'superseded' || record.superseded === true) {
|
|
3012
|
+
return {
|
|
3013
|
+
...base,
|
|
3014
|
+
code: 'REPLAN_TERMINAL',
|
|
3015
|
+
error: '计划已是终态(已取消/已被取代),不能重规划',
|
|
3016
|
+
hint: '终态计划不会复活:如需继续这项工作,请让主 Agent 生成新计划。',
|
|
3017
|
+
};
|
|
3018
|
+
}
|
|
3019
|
+
if (record.dispatchPromise) {
|
|
3020
|
+
/*
|
|
3021
|
+
* 执行中拒绝改写定义,但把变更原文记下来。旧行为(maybePlan 直接
|
|
3022
|
+
* return downstream)会让用户在派发期间说的新需求彻底消失。
|
|
3023
|
+
*/
|
|
3024
|
+
const change = typeof args?.changeText === 'string' ? truncate(args.changeText.trim(), 4000) : '';
|
|
3025
|
+
if (change) {
|
|
3026
|
+
const seq = Number(record.changeRequestSeq ?? 0) + 1;
|
|
3027
|
+
record.changeRequestSeq = seq;
|
|
3028
|
+
record.changeRequest = {
|
|
3029
|
+
seq,
|
|
3030
|
+
text: change,
|
|
3031
|
+
at: Date.now(),
|
|
3032
|
+
turn: Number(state.activeTurns?.get?.(session.id) ?? NaN) || null,
|
|
3033
|
+
status: 'pending',
|
|
3034
|
+
};
|
|
3035
|
+
record.updatedAt = Date.now();
|
|
3036
|
+
}
|
|
3037
|
+
state.records.set(session.id, record);
|
|
3038
|
+
return {
|
|
3039
|
+
...base,
|
|
3040
|
+
code: 'REPLAN_PLAN_RUNNING',
|
|
3041
|
+
error: '本轮派发仍在执行:重规划不会中途改写正在跑的子任务',
|
|
3042
|
+
hint: '先轮询 dsh_workplan_status 等本轮结束(或先 cancel 并等它收敛),再提交同一组 changes;变更已记录为 changeRequest,不会丢失。',
|
|
3043
|
+
running: true,
|
|
3044
|
+
changeRequest: record.changeRequest ?? null,
|
|
3045
|
+
};
|
|
3046
|
+
}
|
|
3047
|
+
const revision = revisionNow + 1;
|
|
3048
|
+
const at = Date.now();
|
|
3049
|
+
const result = planReplan(record.plan, args?.changes, {
|
|
3050
|
+
planId,
|
|
3051
|
+
reason: args?.reason,
|
|
3052
|
+
revision,
|
|
3053
|
+
at,
|
|
3054
|
+
});
|
|
3055
|
+
if (!result.ok)
|
|
3056
|
+
return { ...base, code: result.code, error: result.error };
|
|
3057
|
+
/*
|
|
3058
|
+
* 先落 durable 记录,再改内存:写失败时计划保持原样,不会出现
|
|
3059
|
+
* 「内存里已经改了、刷新后又退回去」的分叉。
|
|
3060
|
+
*/
|
|
3061
|
+
try {
|
|
3062
|
+
session.append('user/message', buildReplanMessage(result.payload), { surfaceOp: 'append' });
|
|
3063
|
+
}
|
|
3064
|
+
catch (error) {
|
|
3065
|
+
return {
|
|
3066
|
+
...base,
|
|
3067
|
+
code: 'REPLAN_WRITE_FAILED',
|
|
3068
|
+
error: `写入重规划记录失败:${error instanceof Error ? error.message : String(error)}`,
|
|
3069
|
+
hint: '计划未被改动;修复会话写入问题后重试同一组 changes。',
|
|
3070
|
+
};
|
|
3071
|
+
}
|
|
3072
|
+
record.plan = result.payload.plan;
|
|
3073
|
+
record.planRevision = revision;
|
|
3074
|
+
record.statuses = applyReplanStatuses(record.statuses, result.payload);
|
|
3075
|
+
record.phase = planPhase(record.statuses);
|
|
3076
|
+
record.error = null;
|
|
3077
|
+
record.updatedAt = at;
|
|
3078
|
+
if (record.changeRequest && record.changeRequest.status !== 'replanned') {
|
|
3079
|
+
record.changeRequest = {
|
|
3080
|
+
...record.changeRequest,
|
|
3081
|
+
status: 'replanned',
|
|
3082
|
+
replannedAt: at,
|
|
3083
|
+
planRevision: revision,
|
|
3084
|
+
};
|
|
3085
|
+
}
|
|
3086
|
+
state.records.set(session.id, record);
|
|
3087
|
+
const snapshot = derivePlanSnapshot(record.statuses, definedSubtaskCount(record.plan));
|
|
3088
|
+
return {
|
|
3089
|
+
ok: true,
|
|
3090
|
+
planId,
|
|
3091
|
+
planRevision: revision,
|
|
3092
|
+
reason: result.payload.reason,
|
|
3093
|
+
marks: result.payload.marks,
|
|
3094
|
+
added: result.payload.added,
|
|
3095
|
+
phase: record.phase,
|
|
3096
|
+
stats: snapshot.stats,
|
|
3097
|
+
statuses: modelStatusLines(snapshot.statuses),
|
|
3098
|
+
hint: '旧行保留为 closure=replanned(可追溯、不计入剩余项、不再调度);修订后的新行是 pending,调用 dsh_workplan_dispatch 才会执行。',
|
|
3099
|
+
};
|
|
3100
|
+
}
|
|
2519
3101
|
async function cancelPlan(agent, args) {
|
|
2520
3102
|
const session = agent?.session;
|
|
2521
3103
|
if (!session)
|
|
@@ -2897,6 +3479,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2897
3479
|
idleTimeoutMs: limits.idleTimeoutMs,
|
|
2898
3480
|
totalTimeoutMs: limits.totalTimeoutMs,
|
|
2899
3481
|
maxResumes: limits.maxResumes,
|
|
3482
|
+
strictEvidence: options.strictEvidence,
|
|
2900
3483
|
})
|
|
2901
3484
|
.then(() => finishRound(record, session))
|
|
2902
3485
|
.catch((error) => {
|
|
@@ -2928,14 +3511,64 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2928
3511
|
* end state: a durable result message plus a reconciled phase. Anything less
|
|
2929
3512
|
* would make "start now, read later" a second, divergent code path.
|
|
2930
3513
|
*/
|
|
3514
|
+
/**
|
|
3515
|
+
* [1.11.0] 完成必回报的写入点(T7 C-06;契约 S7 done → S8 reported)。
|
|
3516
|
+
*
|
|
3517
|
+
* 只有在「结果消息确实写进会话」之后才调用:没有证据的“已回报”比不回报
|
|
3518
|
+
* 更危险。写入走 applyStatus(唯一写入口),读到的是同一条状态条目上的
|
|
3519
|
+
* `closure:'reported'` + `report{state,at,ref,turn}`,与左侧栏 chip 同源。
|
|
3520
|
+
* 返回本次新标记的条数;已是 reported 的行不重复写,避免每轮刷新 revision。
|
|
3521
|
+
*/
|
|
3522
|
+
function markReported(record, session, ref) {
|
|
3523
|
+
const at = Date.now();
|
|
3524
|
+
const rawTurn = Number(state.activeTurns?.get?.(session?.id) ?? NaN);
|
|
3525
|
+
const turn = Number.isFinite(rawTurn) ? rawTurn : null;
|
|
3526
|
+
let changed = 0;
|
|
3527
|
+
for (const item of Array.isArray(record?.statuses) ? record.statuses : []) {
|
|
3528
|
+
if (item?.status !== 'done')
|
|
3529
|
+
continue;
|
|
3530
|
+
if (item?.closure === 'reported' && item?.report?.state === 'sent')
|
|
3531
|
+
continue;
|
|
3532
|
+
try {
|
|
3533
|
+
record.statuses = applyStatus(record.statuses, item.subtaskId, {
|
|
3534
|
+
closure: 'reported',
|
|
3535
|
+
reportedAt: at,
|
|
3536
|
+
report: { state: 'sent', at, ref, turn },
|
|
3537
|
+
revision: Number(item.revision ?? 0) + 1,
|
|
3538
|
+
updatedBy: 'system',
|
|
3539
|
+
});
|
|
3540
|
+
changed += 1;
|
|
3541
|
+
}
|
|
3542
|
+
catch (error) {
|
|
3543
|
+
ctx.logger?.warn?.(`dsh-workplan: 回报标记失败 ${String(item?.subtaskId)}:${error instanceof Error ? error.message : String(error)}`);
|
|
3544
|
+
record.reportPending = true;
|
|
3545
|
+
}
|
|
3546
|
+
}
|
|
3547
|
+
return changed;
|
|
3548
|
+
}
|
|
2931
3549
|
function finishRound(record, session) {
|
|
3550
|
+
const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`;
|
|
2932
3551
|
if (!record.resultWritten) {
|
|
3552
|
+
/*
|
|
3553
|
+
* [1.11.0] 完成必回报的顺序:先标记 reported,再构建并落盘结果消息。
|
|
3554
|
+
*
|
|
3555
|
+
* 这样结果消息里的 statuses 就带着 `closure:'reported'`,刷新/重启后
|
|
3556
|
+
* 回放得到同一个结论;而“标记了但消息没写成功”会在 catch 里回滚,
|
|
3557
|
+
* 绝不留下没有证据的 reported。
|
|
3558
|
+
*/
|
|
3559
|
+
const before = (record.statuses ?? []).map((item) => ({ ...item }));
|
|
3560
|
+
const needReport = before.filter((item) => item?.status === 'done' && item?.closure !== 'reported').length;
|
|
3561
|
+
// ^ 本轮结算:done 且未到 reported 的行(含旧日志的 null)都算待回报。
|
|
3562
|
+
const reported = markReported(record, session, ref);
|
|
2933
3563
|
const resultMessage = buildRoundResult(record, session.id, limits);
|
|
2934
3564
|
try {
|
|
2935
3565
|
session.append('user/message', resultMessage, { surfaceOp: 'append' });
|
|
2936
3566
|
record.resultWritten = true;
|
|
3567
|
+
record.reportPending = needReport > 0 && reported < needReport;
|
|
2937
3568
|
}
|
|
2938
3569
|
catch (error) {
|
|
3570
|
+
// 消息没写成功 ⇒ 回报没有证据:把状态回滚成写之前的快照。
|
|
3571
|
+
record.statuses = before;
|
|
2939
3572
|
ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
|
|
2940
3573
|
/*
|
|
2941
3574
|
* [1.8.14] N13: a failed result write is a real, user-visible failure —
|
|
@@ -2943,6 +3576,23 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2943
3576
|
* disagree with the live phase. Log it durably, not only in the host log.
|
|
2944
3577
|
*/
|
|
2945
3578
|
pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
|
|
3579
|
+
/*
|
|
3580
|
+
* [1.11.0] 写失败时不能假装回报过。保留 reportPending,让下一次
|
|
3581
|
+
* pre-step 或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
|
|
3582
|
+
*/
|
|
3583
|
+
record.reportPending = true;
|
|
3584
|
+
}
|
|
3585
|
+
}
|
|
3586
|
+
else {
|
|
3587
|
+
/*
|
|
3588
|
+
* 旧日志 / 上一次写失败的重试:结果消息已在,但仍有 done 行没到
|
|
3589
|
+
* reported。幂等补齐,不重复追加消息。
|
|
3590
|
+
*/
|
|
3591
|
+
const pending = (record.statuses ?? []).some((item) => item?.status === 'done' && item?.closure !== 'reported');
|
|
3592
|
+
if (pending) {
|
|
3593
|
+
const changed = markReported(record, session, ref);
|
|
3594
|
+
if (changed > 0)
|
|
3595
|
+
record.reportPending = false;
|
|
2946
3596
|
}
|
|
2947
3597
|
}
|
|
2948
3598
|
/*
|
|
@@ -2963,7 +3613,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2963
3613
|
* had no field telling it the round ended early. `complete`/`remaining` make
|
|
2964
3614
|
* that state machine-readable instead of a sentence to interpret.
|
|
2965
3615
|
*/
|
|
2966
|
-
function completionFields(snapshot, phase) {
|
|
3616
|
+
function completionFields(snapshot, phase, record) {
|
|
2967
3617
|
const stats = snapshot?.stats ?? {};
|
|
2968
3618
|
const total = Number(stats.total ?? 0);
|
|
2969
3619
|
const done = Number(stats.done ?? 0);
|
|
@@ -2976,7 +3626,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2976
3626
|
* model now also sees whether the plan passed the delivery gate, plus the
|
|
2977
3627
|
* exact gaps.
|
|
2978
3628
|
*/
|
|
2979
|
-
const readiness =
|
|
3629
|
+
const readiness = record
|
|
3630
|
+
? readinessOf(record, snapshot)
|
|
3631
|
+
: deliveryReadiness(snapshot, { phase });
|
|
2980
3632
|
return {
|
|
2981
3633
|
complete: total > 0 && done >= total,
|
|
2982
3634
|
remaining: Math.max(0, total - done),
|
|
@@ -2993,7 +3645,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2993
3645
|
runtime: runtimeIdentity(),
|
|
2994
3646
|
planId: record.plan.planId,
|
|
2995
3647
|
alreadyRunning: false,
|
|
2996
|
-
...completionFields(snapshot, record.phase),
|
|
3648
|
+
...completionFields(snapshot, record.phase, record),
|
|
2997
3649
|
...extra,
|
|
2998
3650
|
phase: record.phase,
|
|
2999
3651
|
stats: snapshot.stats,
|
|
@@ -3039,7 +3691,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3039
3691
|
}
|
|
3040
3692
|
const running = Boolean(record.dispatchPromise);
|
|
3041
3693
|
const snapshot = derivePlanSnapshot(record.statuses);
|
|
3042
|
-
const readiness =
|
|
3694
|
+
const readiness = readinessOf(record, snapshot);
|
|
3043
3695
|
return {
|
|
3044
3696
|
ok: true,
|
|
3045
3697
|
version: pluginVersion,
|
|
@@ -3128,6 +3780,518 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3128
3780
|
};
|
|
3129
3781
|
}
|
|
3130
3782
|
}
|
|
3783
|
+
/**
|
|
3784
|
+
* [1.11.0] 子 → 父的唯一反向通道(T4 C-09 / T6 M5)。
|
|
3785
|
+
*
|
|
3786
|
+
* 子会话只知道自己的 `session.id` 和父会话 id。这里用父链 + `childId` 反查
|
|
3787
|
+
* 子任务,而不是相信子 Agent 自报的 subtaskId:自报值可以写错,父链不会。
|
|
3788
|
+
* 写入仍是 `applyStatus`(唯一写入口),并同步落一条 durable update,刷新后
|
|
3789
|
+
* 「有一条请示在等指示」不会退回 pending。
|
|
3790
|
+
*/
|
|
3791
|
+
async function escalateSubtask(agent, args) {
|
|
3792
|
+
const childSession = agent?.session;
|
|
3793
|
+
if (!childSession?.id) {
|
|
3794
|
+
return { ok: false, code: 'NO_SESSION', error: '只能在子会话内上报遇阻' };
|
|
3795
|
+
}
|
|
3796
|
+
const parentId = childSession.header?.parentSession;
|
|
3797
|
+
if (!parentId) {
|
|
3798
|
+
return {
|
|
3799
|
+
ok: false,
|
|
3800
|
+
code: 'NOT_CHILD_SESSION',
|
|
3801
|
+
error: '当前不是子会话,无法反查父计划;请直接在结果块写 status=blocked + question',
|
|
3802
|
+
};
|
|
3803
|
+
}
|
|
3804
|
+
let record = state.records.get(parentId);
|
|
3805
|
+
if (!record?.plan) {
|
|
3806
|
+
const parent = ctx.sessions?.get?.(parentId);
|
|
3807
|
+
if (parent) {
|
|
3808
|
+
try {
|
|
3809
|
+
record = reconstructFromSession(parent);
|
|
3810
|
+
}
|
|
3811
|
+
catch (error) {
|
|
3812
|
+
pushRecordError({ errors: [] }, error);
|
|
3813
|
+
}
|
|
3814
|
+
}
|
|
3815
|
+
}
|
|
3816
|
+
if (!record?.plan) {
|
|
3817
|
+
return {
|
|
3818
|
+
ok: false,
|
|
3819
|
+
code: 'NO_PLAN',
|
|
3820
|
+
error: '父会话没有可关联的计划;请在结果块写 status=blocked + question,由主 Agent 处理',
|
|
3821
|
+
};
|
|
3822
|
+
}
|
|
3823
|
+
const row = (record.statuses ?? []).find((item) => item?.childId === childSession.id);
|
|
3824
|
+
if (!row) {
|
|
3825
|
+
return {
|
|
3826
|
+
ok: false,
|
|
3827
|
+
code: 'NO_SUBTASK',
|
|
3828
|
+
error: '计划里找不到与本子会话关联的子任务(childId 未登记);请在结果块写 status=blocked + question',
|
|
3829
|
+
};
|
|
3830
|
+
}
|
|
3831
|
+
if (row.status === 'done') {
|
|
3832
|
+
return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, error: '该子任务已标记完成,不能再提交请示' };
|
|
3833
|
+
}
|
|
3834
|
+
const question = truncate(String(args?.question ?? '').trim(), MAX_QUESTION_CHARS);
|
|
3835
|
+
if (!question) {
|
|
3836
|
+
return { ok: false, code: 'INVALID_QUESTION', subtaskId: row.subtaskId, error: 'question 必填:写清需要主 Agent 决定的单个问题' };
|
|
3837
|
+
}
|
|
3838
|
+
if (row.closure === 'escalated') {
|
|
3839
|
+
return {
|
|
3840
|
+
ok: true,
|
|
3841
|
+
alreadyEscalated: true,
|
|
3842
|
+
planId: record.plan.planId,
|
|
3843
|
+
subtaskId: row.subtaskId,
|
|
3844
|
+
status: 'blocked',
|
|
3845
|
+
closure: 'escalated',
|
|
3846
|
+
question: row.question ?? question,
|
|
3847
|
+
message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待主 Agent 指示。',
|
|
3848
|
+
};
|
|
3849
|
+
}
|
|
3850
|
+
const options = (Array.isArray(args?.options) ? args.options : [])
|
|
3851
|
+
.slice(0, MAX_ESCALATION_OPTIONS)
|
|
3852
|
+
.map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
|
|
3853
|
+
.filter(Boolean);
|
|
3854
|
+
const needs = (Array.isArray(args?.needs) ? args.needs : [])
|
|
3855
|
+
.slice(0, 10)
|
|
3856
|
+
.map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
|
|
3857
|
+
.filter(Boolean);
|
|
3858
|
+
const now = Date.now();
|
|
3859
|
+
const revision = Number(row.revision ?? 0) + 1;
|
|
3860
|
+
record.statuses = applyStatus(record.statuses, row.subtaskId, {
|
|
3861
|
+
status: 'blocked',
|
|
3862
|
+
closure: 'escalated',
|
|
3863
|
+
blockedKind: 'escalated',
|
|
3864
|
+
question,
|
|
3865
|
+
options,
|
|
3866
|
+
needs: [...(Array.isArray(row.needs) ? row.needs : []), ...needs],
|
|
3867
|
+
progress: 100,
|
|
3868
|
+
finishedAt: now,
|
|
3869
|
+
error: question,
|
|
3870
|
+
summary: `待指示:${question}`,
|
|
3871
|
+
escalatedAt: now,
|
|
3872
|
+
escalationSeq: revision,
|
|
3873
|
+
revision,
|
|
3874
|
+
updatedBy: 'child',
|
|
3875
|
+
});
|
|
3876
|
+
record.updatedAt = now;
|
|
3877
|
+
try {
|
|
3878
|
+
const parent = ctx.sessions?.get?.(parentId);
|
|
3879
|
+
const written = record.statuses.find((item) => item?.subtaskId === row.subtaskId);
|
|
3880
|
+
parent?.append?.('user/message', buildUpdateMessage({
|
|
3881
|
+
planId: record.plan.planId,
|
|
3882
|
+
subtaskId: row.subtaskId,
|
|
3883
|
+
status: 'blocked',
|
|
3884
|
+
closure: 'escalated',
|
|
3885
|
+
blockedKind: 'escalated',
|
|
3886
|
+
question,
|
|
3887
|
+
options,
|
|
3888
|
+
needs: written?.needs,
|
|
3889
|
+
escalatedAt: now,
|
|
3890
|
+
escalationSeq: revision,
|
|
3891
|
+
revision,
|
|
3892
|
+
}), { surfaceOp: 'append' });
|
|
3893
|
+
}
|
|
3894
|
+
catch (error) {
|
|
3895
|
+
pushRecordError(record, error);
|
|
3896
|
+
}
|
|
3897
|
+
return {
|
|
3898
|
+
ok: true,
|
|
3899
|
+
planId: record.plan.planId,
|
|
3900
|
+
subtaskId: row.subtaskId,
|
|
3901
|
+
status: 'blocked',
|
|
3902
|
+
closure: 'escalated',
|
|
3903
|
+
question,
|
|
3904
|
+
revision,
|
|
3905
|
+
message: '已上报主 Agent。请立即停止推进,只允许做只读核对;等待指示期间不要开始新的写入或大改。',
|
|
3906
|
+
};
|
|
3907
|
+
}
|
|
3908
|
+
/**
|
|
3909
|
+
* [1.11.0] 指示回执(T4 B5 / M6,T10 N4)。
|
|
3910
|
+
*
|
|
3911
|
+
* 指示投递成功只证明消息进了收件箱,不证明子会话真的开始执行。三个观察点
|
|
3912
|
+
* 都以「该行仍是 instructed 且 instructionSeq 未变」为前提:
|
|
3913
|
+
* - 轮询:子会话 seq 增长 = 已开始执行 → 写 acknowledged(唯一正向回执);
|
|
3914
|
+
* - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent 可催);
|
|
3915
|
+
* - 180s:仍无增长 → 收束为 blocked/no-ack(不再无限等待)。
|
|
3916
|
+
* 主 Agent 再次改判或子会话产出结果都会让这三个观察点自然作废。
|
|
3917
|
+
*/
|
|
3918
|
+
function scheduleInstructionAck(record, subtaskId, childId, revision) {
|
|
3919
|
+
const rowOf = () => record.statuses.find((item) => item?.subtaskId === subtaskId);
|
|
3920
|
+
const readSeq = () => {
|
|
3921
|
+
try {
|
|
3922
|
+
const seq = Number(ctx.sessions?.get?.(childId)?.seq);
|
|
3923
|
+
return Number.isFinite(seq) ? seq : undefined;
|
|
3924
|
+
}
|
|
3925
|
+
catch {
|
|
3926
|
+
return undefined;
|
|
3927
|
+
}
|
|
3928
|
+
};
|
|
3929
|
+
const baseline = readSeq();
|
|
3930
|
+
let stopped = false;
|
|
3931
|
+
const timers = [];
|
|
3932
|
+
const stop = () => {
|
|
3933
|
+
if (stopped)
|
|
3934
|
+
return;
|
|
3935
|
+
stopped = true;
|
|
3936
|
+
for (const timer of timers) {
|
|
3937
|
+
clearTimeout(timer);
|
|
3938
|
+
clearInterval(timer);
|
|
3939
|
+
}
|
|
3940
|
+
};
|
|
3941
|
+
const sameAttempt = (row) => {
|
|
3942
|
+
if (stopped)
|
|
3943
|
+
return false;
|
|
3944
|
+
if (!row || row.closure !== 'instructed')
|
|
3945
|
+
return false;
|
|
3946
|
+
return Number(row.instructionSeq ?? 0) === Number(revision);
|
|
3947
|
+
};
|
|
3948
|
+
const unchanged = (row) => {
|
|
3949
|
+
if (!sameAttempt(row))
|
|
3950
|
+
return false;
|
|
3951
|
+
const seq = readSeq();
|
|
3952
|
+
if (seq === undefined || baseline === undefined)
|
|
3953
|
+
return true;
|
|
3954
|
+
return seq <= baseline;
|
|
3955
|
+
};
|
|
3956
|
+
/*
|
|
3957
|
+
* 正向回执:没有这一步时,一个正常工作但耗时较长的子会话会在 180s 被
|
|
3958
|
+
* 误判成 no-ack 并阻断,而它其实早就在产出事件了。
|
|
3959
|
+
*/
|
|
3960
|
+
const poll = setInterval(() => {
|
|
3961
|
+
const row = rowOf();
|
|
3962
|
+
if (!sameAttempt(row)) {
|
|
3963
|
+
stop();
|
|
3964
|
+
return;
|
|
3965
|
+
}
|
|
3966
|
+
const seq = readSeq();
|
|
3967
|
+
if (seq === undefined || baseline === undefined || seq <= baseline)
|
|
3968
|
+
return;
|
|
3969
|
+
try {
|
|
3970
|
+
writeSubtaskStatus(record, subtaskId, {
|
|
3971
|
+
closure: 'acknowledged',
|
|
3972
|
+
ackedAt: Date.now(),
|
|
3973
|
+
ackEvidence: { seq, elapsedMs: Date.now() - Number(row.instruction?.at ?? Date.now()) },
|
|
3974
|
+
instructionOverdue: false,
|
|
3975
|
+
progress: Math.max(Number(row.progress ?? 0), 15),
|
|
3976
|
+
}, { timedOut: false });
|
|
3977
|
+
}
|
|
3978
|
+
catch {
|
|
3979
|
+
// Row moved on between read and write; the next tick re-evaluates.
|
|
3980
|
+
return;
|
|
3981
|
+
}
|
|
3982
|
+
stop();
|
|
3983
|
+
}, INSTRUCTION_POLL_MS);
|
|
3984
|
+
poll.unref?.();
|
|
3985
|
+
timers.push(poll);
|
|
3986
|
+
const notice = setTimeout(() => {
|
|
3987
|
+
if (!unchanged(rowOf()))
|
|
3988
|
+
return;
|
|
3989
|
+
try {
|
|
3990
|
+
writeSubtaskStatus(record, subtaskId, { instructionOverdue: true }, { timedOut: false });
|
|
3991
|
+
}
|
|
3992
|
+
catch {
|
|
3993
|
+
// The row moved on between the read and the write; nothing to report.
|
|
3994
|
+
}
|
|
3995
|
+
}, INSTRUCTION_ACK_NOTICE_MS);
|
|
3996
|
+
notice.unref?.();
|
|
3997
|
+
timers.push(notice);
|
|
3998
|
+
const deadline = setTimeout(() => {
|
|
3999
|
+
if (!unchanged(rowOf())) {
|
|
4000
|
+
stop();
|
|
4001
|
+
return;
|
|
4002
|
+
}
|
|
4003
|
+
const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000);
|
|
4004
|
+
const message = `指示下发后 ${seconds}s 子会话仍无任何新事件(no-ack):指示没有被执行`;
|
|
4005
|
+
try {
|
|
4006
|
+
writeSubtaskStatus(record, subtaskId, {
|
|
4007
|
+
status: 'blocked',
|
|
4008
|
+
closure: 'blocked',
|
|
4009
|
+
blockedKind: 'no-ack',
|
|
4010
|
+
progress: 100,
|
|
4011
|
+
finishedAt: Date.now(),
|
|
4012
|
+
instructionOverdue: true,
|
|
4013
|
+
error: message,
|
|
4014
|
+
summary: `未完成:${message}`,
|
|
4015
|
+
}, { timedOut: false });
|
|
4016
|
+
recordSubtaskError(record, subtaskId, message, { timedOut: false });
|
|
4017
|
+
}
|
|
4018
|
+
catch {
|
|
4019
|
+
// Same race as above: the row already left instructed.
|
|
4020
|
+
}
|
|
4021
|
+
stop();
|
|
4022
|
+
}, INSTRUCTION_ACK_DEADLINE_MS);
|
|
4023
|
+
deadline.unref?.();
|
|
4024
|
+
timers.push(deadline);
|
|
4025
|
+
}
|
|
4026
|
+
/**
|
|
4027
|
+
* [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
|
|
4028
|
+
*
|
|
4029
|
+
* 只有根会话能调用;只接受 `closure:'escalated'` 的行;只投递给本会话直接
|
|
4030
|
+
* 子会话。投递失败时不改状态(不伪造成「已指示」),把错误原样交给主 Agent。
|
|
4031
|
+
*/
|
|
4032
|
+
async function instructSubtask(agent, args, signal, existingRecord) {
|
|
4033
|
+
const session = agent?.session;
|
|
4034
|
+
if (!session)
|
|
4035
|
+
return { ok: false, code: 'NO_SESSION', error: '只能在会话内下发指示' };
|
|
4036
|
+
if (!isRootSession(session))
|
|
4037
|
+
return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' };
|
|
4038
|
+
let record = existingRecord ?? state.records.get(session.id);
|
|
4039
|
+
if (!record?.plan)
|
|
4040
|
+
record = reconstructFromSession(session, args?.planId);
|
|
4041
|
+
record = adoptRequestedPlan(session, record, args?.planId);
|
|
4042
|
+
if (!record?.plan)
|
|
4043
|
+
return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' };
|
|
4044
|
+
clearAutoResumeTimer(record, 'manual-instruct');
|
|
4045
|
+
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : '';
|
|
4046
|
+
if (!subtaskId)
|
|
4047
|
+
return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' };
|
|
4048
|
+
const current = record.statuses.find((item) => item?.subtaskId === subtaskId);
|
|
4049
|
+
if (!current)
|
|
4050
|
+
return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` };
|
|
4051
|
+
if (current.closure !== 'escalated') {
|
|
4052
|
+
return {
|
|
4053
|
+
ok: false,
|
|
4054
|
+
code: 'NOT_ESCALATED',
|
|
4055
|
+
subtaskId,
|
|
4056
|
+
error: '该子任务不在待指示状态;普通受阻请用 dsh_workplan_update 改判',
|
|
4057
|
+
};
|
|
4058
|
+
}
|
|
4059
|
+
const instruction = truncate(String(args?.instruction ?? args?.text ?? '').trim(), MAX_INSTRUCTION_CHARS);
|
|
4060
|
+
if (!instruction)
|
|
4061
|
+
return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要子 Agent 执行的决定' };
|
|
4062
|
+
const childId = typeof current.childId === 'string' ? current.childId : '';
|
|
4063
|
+
if (!childId)
|
|
4064
|
+
return { ok: false, code: 'NO_CHILD', subtaskId, error: '该行没有关联子会话,无法投递指示' };
|
|
4065
|
+
if (!spawnedChildIds(session).has(childId)) {
|
|
4066
|
+
return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: `${childId} 不是本会话的直接子会话,拒绝投递` };
|
|
4067
|
+
}
|
|
4068
|
+
const service = ctx.subagents;
|
|
4069
|
+
if (!service || typeof service.sendMessage !== 'function') {
|
|
4070
|
+
return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId, error: '当前部署没有可用的 subagent 服务,无法投递指示' };
|
|
4071
|
+
}
|
|
4072
|
+
let messageId = '';
|
|
4073
|
+
try {
|
|
4074
|
+
messageId = String(await service.sendMessage(agent, childId, [{
|
|
4075
|
+
type: 'text',
|
|
4076
|
+
text: [
|
|
4077
|
+
'【主 Agent 指示(对应你此前提交的请示)】',
|
|
4078
|
+
instruction,
|
|
4079
|
+
'',
|
|
4080
|
+
'请按上述指示继续原任务。若仍受阻,先调用 dsh_workplan_escalate 再次上报,然后停止推进等待指示;不要自行猜测未被回答的部分。',
|
|
4081
|
+
].join('\n'),
|
|
4082
|
+
}], { signal }) ?? '');
|
|
4083
|
+
}
|
|
4084
|
+
catch (error) {
|
|
4085
|
+
return {
|
|
4086
|
+
ok: false,
|
|
4087
|
+
code: 'DELIVERY_FAILED',
|
|
4088
|
+
subtaskId,
|
|
4089
|
+
error: truncate(error instanceof Error ? error.message : String(error), 500),
|
|
4090
|
+
hint: '状态未改变,该行仍是待指示;可重试,或用 dsh_workplan_followup 直接投递同一段指示。',
|
|
4091
|
+
};
|
|
4092
|
+
}
|
|
4093
|
+
const now = Date.now();
|
|
4094
|
+
const revision = Number(current.revision ?? 0) + 1;
|
|
4095
|
+
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
4096
|
+
status: 'in_progress',
|
|
4097
|
+
closure: 'instructed',
|
|
4098
|
+
instruction: { text: instruction, at: now, by: 'agent', messageId, delivery: 'sent' },
|
|
4099
|
+
instructionSeq: revision,
|
|
4100
|
+
progress: Math.max(Number(current.progress ?? 0), 15),
|
|
4101
|
+
finishedAt: null,
|
|
4102
|
+
error: null,
|
|
4103
|
+
question: null,
|
|
4104
|
+
options: [],
|
|
4105
|
+
blockedKind: null,
|
|
4106
|
+
ackOverdue: false,
|
|
4107
|
+
ackedAt: null,
|
|
4108
|
+
ackEvidence: undefined,
|
|
4109
|
+
revision,
|
|
4110
|
+
updatedBy: 'agent',
|
|
4111
|
+
});
|
|
4112
|
+
/*
|
|
4113
|
+
* [1.11.0] 指示会解除「受阻」(T10 N3)。
|
|
4114
|
+
*
|
|
4115
|
+
* 行从 blocked/escalated 变成 in_progress/instructed 后,缓存的
|
|
4116
|
+
* `record.phase` 仍是 blocked;`reconcilePhase` 现在允许 blocked 在有
|
|
4117
|
+
* 活跃行时让位给 executing,这里必须重新对账,否则卡片继续显示
|
|
4118
|
+
* 「卡住了」,与事实相反。
|
|
4119
|
+
*/
|
|
4120
|
+
record.phase = reconcilePhase(record.phase, record.statuses);
|
|
4121
|
+
record.updatedAt = now;
|
|
4122
|
+
try {
|
|
4123
|
+
const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
|
|
4124
|
+
session.append('user/message', buildUpdateMessage({
|
|
4125
|
+
planId: record.plan.planId,
|
|
4126
|
+
subtaskId,
|
|
4127
|
+
status: 'in_progress',
|
|
4128
|
+
closure: 'instructed',
|
|
4129
|
+
instruction: written?.instruction,
|
|
4130
|
+
instructionSeq: revision,
|
|
4131
|
+
revision,
|
|
4132
|
+
}), { surfaceOp: 'append' });
|
|
4133
|
+
}
|
|
4134
|
+
catch (error) {
|
|
4135
|
+
pushRecordError(record, error);
|
|
4136
|
+
}
|
|
4137
|
+
scheduleInstructionAck(record, subtaskId, childId, revision);
|
|
4138
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
4139
|
+
const readiness = readinessOf(record, snapshot);
|
|
4140
|
+
return {
|
|
4141
|
+
ok: true,
|
|
4142
|
+
planId: record.plan.planId,
|
|
4143
|
+
subtaskId,
|
|
4144
|
+
status: 'in_progress',
|
|
4145
|
+
closure: 'instructed',
|
|
4146
|
+
revision,
|
|
4147
|
+
messageId,
|
|
4148
|
+
stats: snapshot.stats,
|
|
4149
|
+
deliveryReady: readiness.ready,
|
|
4150
|
+
hint: '指示已投递,该行已变为「已收到指示」。子 Agent 会开启新一轮;完成前仍不得交付。',
|
|
4151
|
+
};
|
|
4152
|
+
}
|
|
4153
|
+
/**
|
|
4154
|
+
* [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
|
|
4155
|
+
*
|
|
4156
|
+
* 单独一层包装而不是让 host 直接调内部函数:`escalateSubtask` 需要
|
|
4157
|
+
* `record`/`ctx` 闭包,host 侧只拿得到 runtime 的公开面;这一层也是
|
|
4158
|
+
* 唯一被 `dsh_workplan_escalate` 触发的地方,便于测试替身注入。
|
|
4159
|
+
*/
|
|
4160
|
+
async function escalateTool(agent, args) {
|
|
4161
|
+
return escalateSubtask(agent, args);
|
|
4162
|
+
}
|
|
4163
|
+
/**
|
|
4164
|
+
* [1.11.0] 工具层入口:主 Agent 下发指示(T4 C-10 / T6 M6)。
|
|
4165
|
+
*
|
|
4166
|
+
* 前置校验(根会话、escalated、直接子会话、非空 instruction)全部在
|
|
4167
|
+
* `instructSubtask` 里,这一层只转发 —— 校验留在唯一实现处,两个入口
|
|
4168
|
+
* (工具与 `dsh_workplan_update` 的 instruction 字段)才不会分叉。
|
|
4169
|
+
*/
|
|
4170
|
+
async function instructTool(agent, args, signal) {
|
|
4171
|
+
return instructSubtask(agent, args, signal);
|
|
4172
|
+
}
|
|
4173
|
+
/**
|
|
4174
|
+
* [1.11.0] 跨部门需求的唯一处置入口(用户 m00687)。
|
|
4175
|
+
*
|
|
4176
|
+
* 子 Agent 只能「提出」需求(needs → open handoff),不能宣称需求已解决;
|
|
4177
|
+
* 只有根会话的主 Agent 能把一条需求指派给部门(routed)、写入书面答复
|
|
4178
|
+
* (answered)或判定无需动作(closed)。处置结果写回同一条状态行并追加
|
|
4179
|
+
* 一条可回放的人工改判消息,刷新后仍然有效。
|
|
4180
|
+
*/
|
|
4181
|
+
async function handoffTool(agent, args, signal) {
|
|
4182
|
+
const session = agent?.session;
|
|
4183
|
+
if (!session)
|
|
4184
|
+
return { ok: false, code: 'NO_SESSION', error: '只能在会话内处置跨部门需求' };
|
|
4185
|
+
if (!isRootSession(session))
|
|
4186
|
+
return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以处置跨部门需求' };
|
|
4187
|
+
let record = state.records.get(session.id);
|
|
4188
|
+
if (!record?.plan)
|
|
4189
|
+
record = reconstructFromSession(session, args?.planId);
|
|
4190
|
+
record = adoptRequestedPlan(session, record, args?.planId);
|
|
4191
|
+
if (!record?.plan)
|
|
4192
|
+
return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' };
|
|
4193
|
+
const action = ['list', 'assign', 'resolve', 'close'].includes(args?.action) ? args.action : '';
|
|
4194
|
+
if (!action)
|
|
4195
|
+
return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 list / assign / resolve / close' };
|
|
4196
|
+
if (action === 'list') {
|
|
4197
|
+
const rows = (record.statuses ?? []).flatMap((row) => openHandoffs(row).map((handoff) => ({
|
|
4198
|
+
subtaskId: row.subtaskId,
|
|
4199
|
+
id: handoff.id,
|
|
4200
|
+
department: handoff.department,
|
|
4201
|
+
status: handoff.status,
|
|
4202
|
+
request: handoff.request,
|
|
4203
|
+
})));
|
|
4204
|
+
return { ok: true, planId: record.plan.planId, handoffs: rows, count: rows.length };
|
|
4205
|
+
}
|
|
4206
|
+
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : '';
|
|
4207
|
+
if (!subtaskId)
|
|
4208
|
+
return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' };
|
|
4209
|
+
const row = record.statuses.find((item) => item?.subtaskId === subtaskId);
|
|
4210
|
+
if (!row)
|
|
4211
|
+
return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` };
|
|
4212
|
+
const handoffs = normaliseHandoffs(row.handoffs);
|
|
4213
|
+
const wanted = typeof args?.handoffId === 'string' ? args.handoffId.trim() : '';
|
|
4214
|
+
const index = wanted
|
|
4215
|
+
? handoffs.findIndex((item) => item.id === wanted)
|
|
4216
|
+
: handoffs.findIndex((item) => item.status === 'open' || item.status === 'routed');
|
|
4217
|
+
if (index < 0) {
|
|
4218
|
+
return {
|
|
4219
|
+
ok: false,
|
|
4220
|
+
code: wanted ? 'UNKNOWN_HANDOFF' : 'NO_OPEN_HANDOFF',
|
|
4221
|
+
subtaskId,
|
|
4222
|
+
error: wanted ? `未知跨部门需求:${wanted}` : '该行没有待处理的跨部门需求',
|
|
4223
|
+
};
|
|
4224
|
+
}
|
|
4225
|
+
const handoff = handoffs[index];
|
|
4226
|
+
if (action === 'assign') {
|
|
4227
|
+
const department = typeof args?.department === 'string' ? args.department.trim() : '';
|
|
4228
|
+
if (!DEPARTMENTS[department]) {
|
|
4229
|
+
return { ok: false, code: 'INVALID_DEPARTMENT', error: `department 必须是 ${DEPARTMENT_IDS.join(' / ')} 之一` };
|
|
4230
|
+
}
|
|
4231
|
+
handoffs[index] = { ...handoff, department, status: 'routed', updatedAt: Date.now(), by: 'agent' };
|
|
4232
|
+
}
|
|
4233
|
+
else if (action === 'resolve') {
|
|
4234
|
+
const response = truncate(String(args?.response ?? '').trim(), MAX_HANDOFF_RESPONSE_CHARS);
|
|
4235
|
+
if (!response)
|
|
4236
|
+
return { ok: false, code: 'INVALID_RESPONSE', error: 'resolve 必须写清答复或已由哪项产物满足该需求' };
|
|
4237
|
+
handoffs[index] = { ...handoff, status: 'answered', response, updatedAt: Date.now(), by: 'agent' };
|
|
4238
|
+
}
|
|
4239
|
+
else {
|
|
4240
|
+
handoffs[index] = { ...handoff, status: 'closed', response: handoff.response ?? null, updatedAt: Date.now(), by: 'agent' };
|
|
4241
|
+
}
|
|
4242
|
+
const revision = Number(row.revision ?? 0) + 1;
|
|
4243
|
+
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
4244
|
+
handoffs,
|
|
4245
|
+
revision,
|
|
4246
|
+
updatedBy: 'agent',
|
|
4247
|
+
});
|
|
4248
|
+
record.updatedAt = Date.now();
|
|
4249
|
+
try {
|
|
4250
|
+
session.append('user/message', buildUpdateMessage({
|
|
4251
|
+
planId: record.plan.planId,
|
|
4252
|
+
subtaskId,
|
|
4253
|
+
status: row.status,
|
|
4254
|
+
handoffs,
|
|
4255
|
+
revision,
|
|
4256
|
+
}), { surfaceOp: 'append' });
|
|
4257
|
+
}
|
|
4258
|
+
catch (error) {
|
|
4259
|
+
pushRecordError(record, error);
|
|
4260
|
+
}
|
|
4261
|
+
/*
|
|
4262
|
+
* [1.11.0] 答复必须真的送到还在等它的子会话(用户 m00687)。
|
|
4263
|
+
*
|
|
4264
|
+
* 如果提出需求的行正处于「待指示」,它此刻停在那里等主 Agent:只把
|
|
4265
|
+
* handoff 写成 answered、不发指示,子会话永远不会继续,需求闭环只闭在
|
|
4266
|
+
* 计划表里。这里复用 instructSubtask 的唯一投递/回执链路(写 instructed、
|
|
4267
|
+
* 60s/180s 回执、下次激活注入),不另造第二条消息通道。
|
|
4268
|
+
* 投递失败不回滚 handoff:答复本身是真的,失败原因如实返回给主 Agent。
|
|
4269
|
+
*/
|
|
4270
|
+
let instruction = null;
|
|
4271
|
+
if (action === 'resolve' && row.closure === 'escalated' && handoffs[index]?.response) {
|
|
4272
|
+
const answer = handoffs[index];
|
|
4273
|
+
instruction = await instructSubtask(agent, {
|
|
4274
|
+
planId: record.plan.planId,
|
|
4275
|
+
subtaskId,
|
|
4276
|
+
instruction: `跨部门需求 ${answer.id} 已答复${answer.department ? `(${answer.department})` : ''}:${answer.response}。按此答复继续原任务。`,
|
|
4277
|
+
}, signal);
|
|
4278
|
+
}
|
|
4279
|
+
const finalReadiness = readinessOf(record, derivePlanSnapshot(record.statuses));
|
|
4280
|
+
return {
|
|
4281
|
+
ok: true,
|
|
4282
|
+
planId: record.plan.planId,
|
|
4283
|
+
subtaskId,
|
|
4284
|
+
handoff: record.statuses.find((item) => item?.subtaskId === subtaskId)?.handoffs?.[index] ?? null,
|
|
4285
|
+
deliveryReady: finalReadiness.ready,
|
|
4286
|
+
deliveryBlockers: finalReadiness.blockers,
|
|
4287
|
+
...(instruction ? { instruction } : {}),
|
|
4288
|
+
hint: action === 'assign'
|
|
4289
|
+
? '已登记责任部门。插件没有常驻部门代理:这次指派不会自动产生工作,请用 dsh_workplan_replan(action=add) 建一个该部门的子任务,或由你直接完成,再用 action=resolve 写入答复或产物引用;否则交付仍被拦住。'
|
|
4290
|
+
: instruction && instruction.ok !== true
|
|
4291
|
+
? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
|
|
4292
|
+
: '已记录处置结果;交付阻塞按最新状态重新计算。',
|
|
4293
|
+
};
|
|
4294
|
+
}
|
|
3131
4295
|
async function dispatchTool(agent, args, signal) {
|
|
3132
4296
|
const session = agent?.session;
|
|
3133
4297
|
if (!session)
|
|
@@ -3351,6 +4515,11 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3351
4515
|
idleTimeoutMs: limits.idleTimeoutMs,
|
|
3352
4516
|
totalTimeoutMs: limits.totalTimeoutMs,
|
|
3353
4517
|
maxResumes: limits.maxResumes,
|
|
4518
|
+
/*
|
|
4519
|
+
* [1.11.0] 严格完成是运行时级配置,不是每个调用点各传一份。
|
|
4520
|
+
* 漏传会让 `strictCompletion:false` 的部署读到默认 true,行为无法预期。
|
|
4521
|
+
*/
|
|
4522
|
+
strictEvidence: options.strictEvidence,
|
|
3354
4523
|
}).finally(() => {
|
|
3355
4524
|
record.dispatchPromise = null;
|
|
3356
4525
|
record.dispatchStartedAt = null;
|
|
@@ -3435,8 +4604,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3435
4604
|
*/
|
|
3436
4605
|
const STOP_STEER_LIMIT = 2;
|
|
3437
4606
|
function recordReadiness(record) {
|
|
3438
|
-
|
|
3439
|
-
return deliveryReadiness(snapshot, { phase: record.phase });
|
|
4607
|
+
return readinessOf(record);
|
|
3440
4608
|
}
|
|
3441
4609
|
function stopGateApplies(record, session, turn) {
|
|
3442
4610
|
if (!record?.plan)
|
|
@@ -3707,6 +4875,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3707
4875
|
stats: snapshot.stats,
|
|
3708
4876
|
statuses: snapshot.statuses,
|
|
3709
4877
|
attempt: book.count,
|
|
4878
|
+
changePending: record.changeRequest?.status === 'pending',
|
|
4879
|
+
reportPending: record.reportPending === true,
|
|
3710
4880
|
}), {
|
|
3711
4881
|
kind: 'workplan-continue',
|
|
3712
4882
|
form: 'notice',
|
|
@@ -3856,7 +5026,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3856
5026
|
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
|
|
3857
5027
|
+ '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。');
|
|
3858
5028
|
}
|
|
3859
|
-
const readiness =
|
|
5029
|
+
const readiness = readinessOf(successor);
|
|
3860
5030
|
if (!readiness.ready) {
|
|
3861
5031
|
const ids = readiness.remaining.slice(0, 10).join('、');
|
|
3862
5032
|
return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY, `计划 ${planId} 已被取代,承接计划 ${successorPlanId} 只完成 ${readiness.done}/${readiness.total}`
|
|
@@ -3877,8 +5047,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3877
5047
|
}
|
|
3878
5048
|
function presentDenialVerdict(agent) {
|
|
3879
5049
|
const session = agent?.session;
|
|
3880
|
-
if (!session
|
|
5050
|
+
if (!session)
|
|
3881
5051
|
return undefined;
|
|
5052
|
+
/*
|
|
5053
|
+
* [1.11.0] 子会话不得直接交付(T7 P9 / R3)。
|
|
5054
|
+
*
|
|
5055
|
+
* 1.10.6 对非根会话直接返回 undefined,等于让子 Agent 绕过根交付门禁
|
|
5056
|
+
* 调用 present:中间产物会被当成最终交付展示给用户。交付只属于根会话;
|
|
5057
|
+
* 子会话的产物应写进工作区并由主 Agent 统一 present。
|
|
5058
|
+
*/
|
|
5059
|
+
if (!isRootSession(session)) {
|
|
5060
|
+
return presentDenial(PRESENT_DENY_CODES.NOT_ROOT, '子 Agent 不能直接交付:请把产物写入工作区并在结论里给出路径,由主 Agent 统一核对后调用 present。');
|
|
5061
|
+
}
|
|
3882
5062
|
if (isPlanModeActive(ctx, session))
|
|
3883
5063
|
return undefined;
|
|
3884
5064
|
/*
|
|
@@ -3918,7 +5098,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3918
5098
|
const unresolved = gateable
|
|
3919
5099
|
.map((item) => ({
|
|
3920
5100
|
record: item,
|
|
3921
|
-
readiness:
|
|
5101
|
+
readiness: readinessOf(item),
|
|
3922
5102
|
}))
|
|
3923
5103
|
/*
|
|
3924
5104
|
* A cancelled plan is not a delivery blocker for *other* plans — the
|
|
@@ -3981,7 +5161,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
3981
5161
|
return denial;
|
|
3982
5162
|
return undefined;
|
|
3983
5163
|
}
|
|
3984
|
-
readiness =
|
|
5164
|
+
readiness = readinessOf(record);
|
|
3985
5165
|
if (readiness.ready)
|
|
3986
5166
|
return undefined;
|
|
3987
5167
|
}
|
|
@@ -4129,7 +5309,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
4129
5309
|
.map((planId) => recordForPlan(session, planId))
|
|
4130
5310
|
.filter((record) => record?.plan
|
|
4131
5311
|
&& !isTerminalPhase(record.phase)
|
|
4132
|
-
&& !
|
|
5312
|
+
&& !readinessOf(record).ready);
|
|
4133
5313
|
if (unresolved.length === 0)
|
|
4134
5314
|
return undefined;
|
|
4135
5315
|
const ids = unresolved.slice(0, 4).map((record) => record.plan.planId);
|
|
@@ -4237,6 +5417,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
4237
5417
|
dispatchTool,
|
|
4238
5418
|
statusTool,
|
|
4239
5419
|
followupTool,
|
|
5420
|
+
escalateTool,
|
|
5421
|
+
instructTool,
|
|
5422
|
+
handoffTool,
|
|
5423
|
+
replanPlan,
|
|
4240
5424
|
plansPayload,
|
|
4241
5425
|
route,
|
|
4242
5426
|
dispose,
|
|
@@ -4309,6 +5493,25 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
4309
5493
|
const existing = state.records.get(session.id);
|
|
4310
5494
|
if (existing?.plan?.createdTurn === payload.turn)
|
|
4311
5495
|
return downstream;
|
|
5496
|
+
/*
|
|
5497
|
+
* [1.11.0] 执行中记录的变更,在本轮结束后仍然没有被 replan 落实时,必须
|
|
5498
|
+
* 在下一步拦住“直接开始新一轮计划/直接收尾”:提醒模型先处理变更。每个
|
|
5499
|
+
* 变更序号只提醒一次(notifiedSeq),不会每步重复注入。
|
|
5500
|
+
*/
|
|
5501
|
+
if (existing?.plan && !existing.dispatchPromise
|
|
5502
|
+
&& existing.changeRequest?.status === 'pending'
|
|
5503
|
+
&& existing.changeRequest.notifiedSeq !== existing.changeRequest.seq) {
|
|
5504
|
+
existing.changeRequest.notifiedSeq = existing.changeRequest.seq;
|
|
5505
|
+
const change = existing.changeRequest;
|
|
5506
|
+
return enterDecision(downstream, [buildChangeRequestMessage({
|
|
5507
|
+
kind: 'workplan-change',
|
|
5508
|
+
planId: String(existing.plan.planId ?? ''),
|
|
5509
|
+
seq: Number(change.seq) || 1,
|
|
5510
|
+
at: Number(change.at) || Date.now(),
|
|
5511
|
+
turn: Number(change.turn) || null,
|
|
5512
|
+
text: String(change.text ?? ''),
|
|
5513
|
+
}, { afterRound: true })]);
|
|
5514
|
+
}
|
|
4312
5515
|
// A plan generated in plan mode is intentionally deferred: keep it intact
|
|
4313
5516
|
// until the user leaves plan mode and dispatches it. Cancelling it here
|
|
4314
5517
|
// would make the plan disappear before the main Agent can act on approval.
|
|
@@ -4332,8 +5535,46 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
4332
5535
|
existing.errors = Array.isArray(existing.errors) ? existing.errors : [];
|
|
4333
5536
|
existing.errors.push('计划已取消:上一轮未派发');
|
|
4334
5537
|
}
|
|
4335
|
-
if (existing?.dispatchPromise || existing?.phase === 'executing')
|
|
5538
|
+
if (existing?.dispatchPromise || existing?.phase === 'executing') {
|
|
5539
|
+
/*
|
|
5540
|
+
* [1.11.0] C-12:执行中收到的新需求不能静默丢弃。
|
|
5541
|
+
*
|
|
5542
|
+
* 旧代码在这里直接 `return downstream`,用户在看到「正在做」之后补充的要求
|
|
5543
|
+
* 既没写进状态、也没出现在会话里,下一轮计划更不会包含它们。现在:
|
|
5544
|
+
* - 原文落进 `record.changeRequest`(带序号/回合/时间),刷新后可恢复;
|
|
5545
|
+
* - 一条 notice 消息进入本轮上下文,明确告诉模型「先别打断、结束后用
|
|
5546
|
+
* dsh_workplan_replan 落实」;
|
|
5547
|
+
* - 同一段文本只记一次,避免每步重复注入。
|
|
5548
|
+
*/
|
|
5549
|
+
const text = truncate(taskText, 4000);
|
|
5550
|
+
const previous = typeof existing.changeRequest?.text === 'string' ? existing.changeRequest.text : '';
|
|
5551
|
+
if (previous !== text) {
|
|
5552
|
+
const seq = Number(existing.changeRequestSeq ?? 0) + 1;
|
|
5553
|
+
const at = Date.now();
|
|
5554
|
+
existing.changeRequestSeq = seq;
|
|
5555
|
+
existing.changeRequest = {
|
|
5556
|
+
seq,
|
|
5557
|
+
text,
|
|
5558
|
+
at,
|
|
5559
|
+
turn: Number(payload.turn ?? 0),
|
|
5560
|
+
status: 'pending',
|
|
5561
|
+
notifiedSeq: seq,
|
|
5562
|
+
};
|
|
5563
|
+
existing.updatedAt = at;
|
|
5564
|
+
const active = (existing.statuses ?? [])
|
|
5565
|
+
.filter((item) => item?.status === 'in_progress')
|
|
5566
|
+
.map((item) => `${String(item.subtaskId)}「${String(item.title ?? '')}」`);
|
|
5567
|
+
return enterDecision(downstream, [buildChangeRequestMessage({
|
|
5568
|
+
kind: 'workplan-change',
|
|
5569
|
+
planId: String(existing.plan?.planId ?? ''),
|
|
5570
|
+
seq,
|
|
5571
|
+
at,
|
|
5572
|
+
turn: Number(payload.turn ?? 0),
|
|
5573
|
+
text,
|
|
5574
|
+
}, { activeSubtasks: active })]);
|
|
5575
|
+
}
|
|
4336
5576
|
return downstream;
|
|
5577
|
+
}
|
|
4337
5578
|
const modelSelection = resolveModelSelection(ctx, payload);
|
|
4338
5579
|
if (!modelSelection?.provider || !modelSelection?.model) {
|
|
4339
5580
|
const message = buildDegradedMessage({
|
|
@@ -4578,6 +5819,54 @@ export function statusToolOutputSchema() {
|
|
|
4578
5819
|
additionalProperties: true,
|
|
4579
5820
|
};
|
|
4580
5821
|
}
|
|
5822
|
+
export function replanToolOutputSchema() {
|
|
5823
|
+
return {
|
|
5824
|
+
type: 'object',
|
|
5825
|
+
properties: {
|
|
5826
|
+
ok: { type: 'boolean' },
|
|
5827
|
+
planId: { type: 'string' },
|
|
5828
|
+
planRevision: { type: 'number' },
|
|
5829
|
+
reason: { type: 'string' },
|
|
5830
|
+
phase: { type: 'string' },
|
|
5831
|
+
stats: { type: 'object' },
|
|
5832
|
+
statuses: { type: 'array' },
|
|
5833
|
+
marks: {
|
|
5834
|
+
type: 'array',
|
|
5835
|
+
items: {
|
|
5836
|
+
type: 'object',
|
|
5837
|
+
properties: {
|
|
5838
|
+
subtaskId: { type: 'string' },
|
|
5839
|
+
action: { type: 'string' },
|
|
5840
|
+
replacedBy: { type: 'array', items: { type: 'string' } },
|
|
5841
|
+
reason: { type: 'string' },
|
|
5842
|
+
},
|
|
5843
|
+
additionalProperties: true,
|
|
5844
|
+
},
|
|
5845
|
+
},
|
|
5846
|
+
added: {
|
|
5847
|
+
type: 'array',
|
|
5848
|
+
items: {
|
|
5849
|
+
type: 'object',
|
|
5850
|
+
properties: {
|
|
5851
|
+
subtaskId: { type: 'string' },
|
|
5852
|
+
stageId: { type: 'string' },
|
|
5853
|
+
title: { type: 'string' },
|
|
5854
|
+
replaces: { oneOf: [{ type: 'string' }, { type: 'null' }] },
|
|
5855
|
+
},
|
|
5856
|
+
additionalProperties: true,
|
|
5857
|
+
},
|
|
5858
|
+
},
|
|
5859
|
+
// 执行中拒绝改计划时:变更已记录、本轮仍在跑(REPLAN_PLAN_RUNNING)。
|
|
5860
|
+
running: { type: 'boolean' },
|
|
5861
|
+
changeRequest: { oneOf: [{ type: 'object' }, { type: 'null' }] },
|
|
5862
|
+
code: { type: 'string' },
|
|
5863
|
+
error: { type: 'string' },
|
|
5864
|
+
hint: { type: 'string' },
|
|
5865
|
+
},
|
|
5866
|
+
required: ['ok'],
|
|
5867
|
+
additionalProperties: true,
|
|
5868
|
+
};
|
|
5869
|
+
}
|
|
4581
5870
|
export function dispatchToolOutputSchema() {
|
|
4582
5871
|
return {
|
|
4583
5872
|
type: 'object',
|