dsh-workplan 2.1.3 → 2.2.6
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 +380 -1
- package/README.en.md +5 -2
- package/README.md +5 -2
- package/README.zh.md +5 -2
- package/client.js +143 -3
- package/docs/dsh-workplan_T4_runtime.patch +508 -0
- package/docs/release-records/_release_notes_2.1.2_20261106.md +44 -0
- package/docs/release-records/_t2_version_determination_20261106.md +39 -0
- package/docs/release-records/_t5_external_reverify_20261106.md +18 -0
- package/docs/release-records/release-dryrun-report-20261106.md +74 -0
- package/docs/release-records/release-notes-2.2.6-T3.md +128 -0
- package/docs/release-records/release-record-2.1.3-20261106.md +82 -0
- package/docs/release-records/release-steps-20261106.md +129 -0
- package/docs/release-records/version-freeze-20261109-T2.md +37 -0
- package/lib/client.js +143 -3
- package/lib/comm-format.js +17 -0
- package/lib/departments.js +19 -0
- package/lib/host.js +95 -17
- package/lib/notice-channel.js +290 -0
- package/lib/plan.js +541 -32
- package/lib/replan.js +4 -0
- package/lib/runtime.js +1481 -85
- package/lib/supersede.js +2 -2
- package/lib/understanding.js +8 -2
- package/lib/watchdog.js +52 -1
- package/package.json +3 -2
- package/scripts/repair-malformed-user-messages.mjs +312 -0
- package/src/client.ts +150 -2
- package/src/comm-format.ts +17 -0
- package/src/departments.ts +22 -0
- package/src/host.ts +90 -12
- package/src/notice-channel.ts +328 -0
- package/src/plan.ts +575 -24
- package/src/replan.ts +4 -0
- package/src/runtime.ts +1500 -86
- package/src/supersede.ts +2 -1
- package/src/understanding.ts +10 -2
- package/src/watchdog.ts +80 -1
package/src/runtime.ts
CHANGED
|
@@ -16,24 +16,38 @@ import { randomUUID } from 'node:crypto'
|
|
|
16
16
|
import { existsSync, realpathSync, statSync } from 'node:fs'
|
|
17
17
|
import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
|
|
18
18
|
|
|
19
|
+
import {
|
|
20
|
+
createNoticeChannel,
|
|
21
|
+
finaliseNoticeChannel,
|
|
22
|
+
formatNoticeChannelLog,
|
|
23
|
+
observeRelayedNotice,
|
|
24
|
+
readLeadAgentId,
|
|
25
|
+
resolveLeadAgentId,
|
|
26
|
+
validateNoticeChannel,
|
|
27
|
+
} from './notice-channel.js'
|
|
19
28
|
import {
|
|
20
29
|
MAX_CONCURRENT,
|
|
21
30
|
PlanError,
|
|
22
31
|
aggregateInvariantViolations,
|
|
32
|
+
appendUserMessage,
|
|
23
33
|
applyStatus,
|
|
24
34
|
attachPlanMeta,
|
|
25
35
|
blockCancelledDependents,
|
|
26
36
|
buildChildPrompt,
|
|
27
37
|
buildCancelMessage,
|
|
28
38
|
buildClarifyMessage,
|
|
39
|
+
createPlannerProgressReporter,
|
|
29
40
|
buildDegradedMessage,
|
|
30
41
|
buildPlanMessage,
|
|
31
42
|
buildPlannerPrompt,
|
|
32
43
|
buildResultMessage,
|
|
33
44
|
buildStopSteerText,
|
|
34
45
|
createStatuses,
|
|
46
|
+
DEFAULT_REASONING_EFFORT,
|
|
35
47
|
deliveryReadiness,
|
|
36
48
|
derivePlanSnapshot,
|
|
49
|
+
// [2.2.0][T4/O-3b] O-3b 消费接线:缺省协商上限由预估派生(plan.ts 纯函数,T3 已定稿)。
|
|
50
|
+
deriveSubtaskTimeoutMs,
|
|
37
51
|
extractJson,
|
|
38
52
|
flattenSubtasks,
|
|
39
53
|
isRecord,
|
|
@@ -54,6 +68,7 @@ import {
|
|
|
54
68
|
parseWorkplanMessage,
|
|
55
69
|
planPhase,
|
|
56
70
|
reconcilePhase,
|
|
71
|
+
REASONING_EFFORTS,
|
|
57
72
|
truncate,
|
|
58
73
|
validatePlan,
|
|
59
74
|
applyResultStatuses,
|
|
@@ -66,6 +81,7 @@ import {
|
|
|
66
81
|
parseUpdateMessage,
|
|
67
82
|
buildUpdateMessage,
|
|
68
83
|
normaliseHandoffs,
|
|
84
|
+
needEntryText,
|
|
69
85
|
openHandoffs,
|
|
70
86
|
DEPARTMENTS,
|
|
71
87
|
DEPARTMENT_IDS,
|
|
@@ -174,14 +190,42 @@ function readinessOf(record: any, snapshot?: any) {
|
|
|
174
190
|
|
|
175
191
|
export const PLANNER_TIMEOUT_MS = 300000
|
|
176
192
|
/**
|
|
177
|
-
*
|
|
193
|
+
* 无进展窗口(默认 300s,DSH_WORKPLAN_PLANNER_TIMEOUT_MS,毫秒 >0)。
|
|
194
|
+
*
|
|
195
|
+
* 2.1.6 起它的含义从「固定墙钟」改成「**没有新内容**的时长」:从上一个
|
|
196
|
+
* chunk 起算,首个 chunk 之前也按它计时。模型一直在正常输出时窗口不断
|
|
197
|
+
* 重置,慢而稳定的长任务不再被误杀。
|
|
178
198
|
*
|
|
179
|
-
* 2.1.1
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
199
|
+
* 历史:2.1.1 把 120s 提到 300s 只是推迟超时;2.1.3 把常量改成可配置,
|
|
200
|
+
* 默认值仍是 300s 的固定墙钟。于是 2026-11-07 10:05:19 → 10:10:19(实测
|
|
201
|
+
* 300.06s)规划器仍在工作却被 abort,自动分解直接降级——提高默认值或开放
|
|
202
|
+
* 配置都没有解决「按墙钟掐断一个正在产出的调用」这个结构问题。
|
|
183
203
|
*/
|
|
184
204
|
export const PLANNER_IDLE_TIMEOUT_MS = 90000
|
|
205
|
+
/**
|
|
206
|
+
* 首个 chunk 之后的「完全静默」窗口(默认 90s,DSH_WORKPLAN_PLANNER_IDLE_
|
|
207
|
+
* TIMEOUT_MS,毫秒 >0):文本、推理、usage 一个 chunk 都没有这么久,判定为
|
|
208
|
+
* 连接卡死而不是模型还在思考。这个常量在 2.1.6 之前只声明、从未接线(死
|
|
209
|
+
* 代码),现在真正参与计时;设为不小于无进展窗口即等价于关闭。
|
|
210
|
+
*/
|
|
211
|
+
export const PLANNER_HARD_MULTIPLIER = 3
|
|
212
|
+
/**
|
|
213
|
+
* 绝对上限 = 无进展窗口 × 该倍数(默认 900s)。慢可以,慢到没边不行:它给
|
|
214
|
+
* 单次规划器尝试一个终点,保证规划失败永远是「有限时间后给出可执行建议」,
|
|
215
|
+
* 而不是无限占用本轮预算。
|
|
216
|
+
*/
|
|
217
|
+
/**
|
|
218
|
+
* [2.2.0][T13b/推理等级] 规划器默认推理档 = max(用户 2026-11-08 决策 5)。
|
|
219
|
+
*
|
|
220
|
+
* 用户规则(AGENTS.md 第 12 条)只说过「子 Agent 不得继承主 Agent 的等级」,
|
|
221
|
+
* 规划器同样是主 Agent 派出的子调用:任务里明确授权「规划器停止继承」。规划
|
|
222
|
+
* 本身属于「跨多个系统梳理根因并给出方案」——按同一条三档规则属非常复杂 →
|
|
223
|
+
* max。`DSH_WORKPLAN_PLANNER_REASONING_EFFORT` 仍可显式覆盖(用户为降本/提速
|
|
224
|
+
* 主动选择低档时有效),未设或非法时才用本默认值;**绝不读取
|
|
225
|
+
* modelSelection.reasoningEffort**。旧行为(plannerEffort || 主 Agent 档位)会
|
|
226
|
+
* 让主 Agent 的 low/high 直接决定拆解质量,与「子 Agent 自决档位」同源、同错。
|
|
227
|
+
*/
|
|
228
|
+
export const DEFAULT_PLANNER_REASONING_EFFORT = 'max'
|
|
185
229
|
/**
|
|
186
230
|
* Absolute ceiling for one child execution.
|
|
187
231
|
*
|
|
@@ -191,6 +235,13 @@ export const PLANNER_IDLE_TIMEOUT_MS = 90000
|
|
|
191
235
|
* plan became terminal at the first slow subtask. The ceiling is now a
|
|
192
236
|
* settlement guarantee, while the no-progress window below is what normally
|
|
193
237
|
* ends an attempt.
|
|
238
|
+
*
|
|
239
|
+
* [2.2.0][T4/O-3b] 语义更新(柔性时长协商,方案 §1③/§2.2):这不是固定交付
|
|
240
|
+
* 期限,而是「协商上限+L4 安全兜底」——单次执行时限协商而来(subtask.timeoutMs
|
|
241
|
+
* 显式值优先,缺省 deriveSubtaskTimeoutMs(estimateMinutes)=clamp(预估分钟×
|
|
242
|
+
* 2.0×60000, MIN, MAX)),本常量只在无预估、无显式值时兜底(③C2 零回归)。
|
|
243
|
+
* 时间是协商出来的安全兜底,不是固定交付期限:到点走 L4 安全兜底结算+
|
|
244
|
+
* 「待裁决」标记(延期 / 重试 / 接受),不表述为「强制结束」式固定期限误杀。
|
|
194
245
|
*/
|
|
195
246
|
export const CHILD_TIMEOUT_MS = 900000
|
|
196
247
|
/** No-progress window: the child's own session log stopped growing. */
|
|
@@ -202,7 +253,14 @@ export const CHILD_IDLE_TIMEOUT_MS = 300000
|
|
|
202
253
|
* minutes.
|
|
203
254
|
*/
|
|
204
255
|
export const MIN_CHILD_TIMEOUT_MS = 1000
|
|
205
|
-
|
|
256
|
+
/*
|
|
257
|
+
* [2.2.0][T4/O-3b] 单次绝对上限 1800000 → 7200000(120 分钟):用户 2026-11-07
|
|
258
|
+
* 决断(方案 §6 未知第 4 条)。协商上限 = clamp(预估分钟 × 2.0, 全局下限,
|
|
259
|
+
* 单次绝对上限)(方案 §1③),2h 让「预告 60 分钟的子任务,其单次执行上限
|
|
260
|
+
* ≥ 60 分钟」(方案 C1)成立;tests/time-estimate-negotiation.test.ts 的
|
|
261
|
+
* expected 公式直接引用本常量,数值不同步会红灯。
|
|
262
|
+
*/
|
|
263
|
+
export const MAX_CHILD_TIMEOUT_MS = 7200000
|
|
206
264
|
export const MIN_CHILD_IDLE_MS = 1000
|
|
207
265
|
export const MAX_CHILD_IDLE_MS = 900000
|
|
208
266
|
export const CHILD_POLL_MS = 2000
|
|
@@ -230,7 +288,26 @@ export const INSTRUCTION_ACK_DEADLINE_MS = 180000
|
|
|
230
288
|
* 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
|
|
231
289
|
*/
|
|
232
290
|
export const INSTRUCTION_POLL_MS = 5000
|
|
233
|
-
|
|
291
|
+
// [2.2.5][RoundBudget] 轮次总预算默认关闭。
|
|
292
|
+
//
|
|
293
|
+
// 用户要求:对子任务的执行时间不做强制限制,只通过开工预告/预估/协商/延期
|
|
294
|
+
// 与到点预警来治理;旧版默认 20 分钟会在子任务自己的 30 分钟协商截止前
|
|
295
|
+
// 先切断整轮,界面上出现“本轮预算用尽”,与上述目标矛盾。
|
|
296
|
+
//
|
|
297
|
+
// 现在:
|
|
298
|
+
// - TOTAL_TIMEOUT_MS = 0 表示默认不设整轮硬预算;
|
|
299
|
+
// - 显式传正数(配置/DSH_WORKPLAN_TOTAL_TIMEOUT_MS)仍可启用安全兜底;
|
|
300
|
+
// - 子任务自己的 timeoutMs/deadlineAt/extendMs 不受影响。
|
|
301
|
+
// dispatchPlan 用 20 天哨兵值避免 Infinity 参与计时器/差值计算。
|
|
302
|
+
//
|
|
303
|
+
// [2.2.5][热修] 哨兵值不能超过 Node setTimeout 的上限:延时 > 2^31-1 毫秒
|
|
304
|
+
// (约 24.8 天)会被 Node 强制改成 1 毫秒并告警(TimeoutOverflowWarning)。
|
|
305
|
+
// 最初版本用 10 年,结果整轮定时器派发后 1ms 就触发,所有子任务瞬间被
|
|
306
|
+
// 「总执行超时」杀死(2026-11-08 17:36 / 18:01 两次现场实锤,38ms 与 8ms)。
|
|
307
|
+
// 20 天 = 1,728,000,000ms < 2^31-1,安全;且对单轮执行而言等价于“无预算”。
|
|
308
|
+
export const TOTAL_TIMEOUT_MS = 0
|
|
309
|
+
export const NO_ROUND_BUDGET_MS = 20 * 24 * 60 * 60 * 1000
|
|
310
|
+
export const ROUND_TIMER_MAX_MS = 2_000_000_000
|
|
234
311
|
export const DISPOSE_TIMEOUT_MS = 5000
|
|
235
312
|
export const STALE_PENDING_MS = 10 * 60 * 1000
|
|
236
313
|
export const MAX_HISTORY_EVENTS = 2000
|
|
@@ -395,26 +472,48 @@ function pushRecordError(record: any, error: any) {
|
|
|
395
472
|
record.errors = [...(record.errors ?? []), text].slice(-20)
|
|
396
473
|
}
|
|
397
474
|
|
|
398
|
-
async function collectStream(stream: any) {
|
|
475
|
+
async function collectStream(stream: any, onChunk?: () => void, sink?: { text: string }) {
|
|
399
476
|
let text = ''
|
|
400
477
|
let textDeltaSeen = false
|
|
401
478
|
let finished = false
|
|
402
479
|
let finishKind = null
|
|
403
480
|
for await (const chunk of stream) {
|
|
404
481
|
if (!chunk || typeof chunk !== 'object') continue
|
|
482
|
+
/*
|
|
483
|
+
* [2.1.6] 任何 chunk 都是「连接还活着」的证据——包括 reasoning-delta、
|
|
484
|
+
* block-start、usage 这些不进正文的类型。计时器只认这里,才不会把正在
|
|
485
|
+
* 推理的模型当成卡死。
|
|
486
|
+
*/
|
|
487
|
+
onChunk?.()
|
|
405
488
|
if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
|
|
406
489
|
text += chunk.text
|
|
490
|
+
/*
|
|
491
|
+
* [2.1.7] 正文必须边流边落进 sink:定时器中止时 for-await 会直接抛错,
|
|
492
|
+
* 局部变量 text 连同 900 秒的产出一起蒸发,旧实现正是这样把「差一个
|
|
493
|
+
* 收尾 } 的完整计划」整体扔掉的。
|
|
494
|
+
*/
|
|
495
|
+
if (sink) sink.text = text
|
|
407
496
|
textDeltaSeen = true
|
|
408
497
|
} else if (chunk.type === 'block-end' && chunk.block?.type === 'text' && !textDeltaSeen) {
|
|
409
498
|
text += chunk.block.text ?? ''
|
|
499
|
+
if (sink) sink.text = text
|
|
410
500
|
} else if (chunk.type === 'finish') {
|
|
411
501
|
finished = true
|
|
412
502
|
finishKind = chunk.reason?.kind ?? 'unknown'
|
|
413
503
|
if (finishKind === 'error' || finishKind === 'aborted') {
|
|
414
504
|
const failure = chunk.reason?.failure
|
|
505
|
+
/*
|
|
506
|
+
* [2.2.5][T4] 底层原因透传(T3 根因 P2):failure.message 只是包装文案
|
|
507
|
+
* (如 "Connection error."),真因可能挂在 failure.cause 上(宿主透传后
|
|
508
|
+
* 自动生效,未透传时保持原文、行为不变)。failure.code 记入 details,
|
|
509
|
+
* 供重试分级(P1)判定,不再从文案反解。
|
|
510
|
+
*/
|
|
511
|
+
const causeText = failure?.cause ? errorCauseChain(failure.cause) : ''
|
|
512
|
+
const failureCode = failure?.code != null ? String(failure.code) : ''
|
|
415
513
|
throw new PlanError(
|
|
416
|
-
`模型调用结束:${finishKind}${
|
|
514
|
+
`模型调用结束:${finishKind}${failureCode ? ` ${failureCode}` : ''}${failure?.message ? `:${failure.message}` : ''}${causeText ? `(底层原因:${causeText})` : ''}`,
|
|
417
515
|
finishKind === 'aborted' ? 'ABORTED' : 'PLANNER_LLM_ERROR',
|
|
516
|
+
failureCode,
|
|
418
517
|
)
|
|
419
518
|
}
|
|
420
519
|
if (finishKind !== 'stop') {
|
|
@@ -440,20 +539,251 @@ function contextGuardStrict() {
|
|
|
440
539
|
return flag !== 'off' && flag !== '0' && flag !== 'false'
|
|
441
540
|
}
|
|
442
541
|
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
const
|
|
542
|
+
/** 规划器窗口取值:只接受有限正数,否则回落默认值(0/负数/NaN 都不许把计时器打成 1ms)。 */
|
|
543
|
+
export function normalisePlannerWindow(value: any, fallback: number) {
|
|
544
|
+
const numeric = Number(value)
|
|
545
|
+
return Number.isFinite(numeric) && numeric > 0 ? numeric : fallback
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function plannerDebugEnabled() {
|
|
549
|
+
const flag = String(process.env.DSH_WORKPLAN_DEBUG ?? '').trim().toLowerCase()
|
|
550
|
+
return flag !== '' && flag !== '0' && flag !== 'false' && flag !== 'off'
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* 把规划器遥测压成一行能直接给用户看的现场说明(降级消息的 detail)。
|
|
555
|
+
* 没有遥测时返回空串,调用方据此跳过,不制造「0 次尝试」之类的假事实。
|
|
556
|
+
*/
|
|
557
|
+
export function plannerTelemetryLine(telemetry: any) {
|
|
558
|
+
if (!telemetry || typeof telemetry !== 'object' || !telemetry.attempt) return ''
|
|
559
|
+
const parts = [
|
|
560
|
+
telemetry.model ? `模型 ${telemetry.model}` : '',
|
|
561
|
+
Number(telemetry.elapsedMs) > 0 ? `耗时 ${(Number(telemetry.elapsedMs) / 1000).toFixed(1)}s` : '',
|
|
562
|
+
Number(telemetry.chunks) > 0 ? `收到 ${Number(telemetry.chunks)} 个输出块` : '未收到任何输出块',
|
|
563
|
+
Number(telemetry.promptChars) > 0 ? `提示词 ${Number(telemetry.promptChars)} 字` : '',
|
|
564
|
+
Number(telemetry.textChars) > 0 ? `输出 ${Number(telemetry.textChars)} 字` : '',
|
|
565
|
+
telemetry.outcome && telemetry.outcome !== 'ok' ? `判定 ${telemetry.outcome}` : '',
|
|
566
|
+
].filter(Boolean)
|
|
567
|
+
return `现场:${parts.join('|')}`
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const PLANNER_ABORT_CODES = ['PLANNER_TIMEOUT', 'PLANNER_IDLE', 'PLANNER_TIMEOUT_HARD']
|
|
571
|
+
|
|
572
|
+
/*
|
|
573
|
+
* [2.2.5][T4] 规划器重试分级与退避(T3 根因 P1:规划器链路全层零重试零退避,
|
|
574
|
+
* 一次 ~1s 网络连接尖峰 × 0ms 间隔 = 1.2 秒内两连败直接降级)。
|
|
575
|
+
* - PLANNER_RETRYABLE_LLM_CODES:宿主 classifyPiAiError 的可自愈失败类
|
|
576
|
+
* (偶发传输错误 / 超时 / 服务端 5xx / 限流 429),重试前做指数退避;
|
|
577
|
+
* - 其余失败类(AUTH / INVALID_REQUEST / 配额 / 上下文溢出 / PI_AI_ERROR /
|
|
578
|
+
* ABORTED)重试不会自愈,立即终止,不再烧下一次调用;
|
|
579
|
+
* - 退避 500ms → 1s(±20% 抖动),期间 signal 一旦取消立即让路,绝不悬挂。
|
|
580
|
+
*/
|
|
581
|
+
const PLANNER_RETRYABLE_LLM_CODES = ['TRANSPORT', 'TIMEOUT', 'SERVER', 'RATE_LIMIT']
|
|
582
|
+
const PLANNER_MAX_ATTEMPTS = 3
|
|
583
|
+
const PLANNER_RETRY_BACKOFF_BASE_MS = 500
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* [2.2.5][T4] 把 Error 的 cause 链展开成一行可读文本(T3 根因 P2 的插件侧落点)。
|
|
587
|
+
*
|
|
588
|
+
* 真实失败原因(ENOTFOUND / ECONNREFUSED / TLS alert 等)挂在 Error.cause 链上,
|
|
589
|
+
* 外层 message 往往只有包装文案("fetch failed"、"Connection error.")。
|
|
590
|
+
* 展开规则与宿主 dsh-llm 的 errorChain 一致:外层在前,每层 cause 以 ": " 追加,
|
|
591
|
+
* 重复文案只记一次;深度封顶 5 层防环。无 cause 时返回与 error.message 相同的
|
|
592
|
+
* 文本,不改变既有行为。
|
|
593
|
+
*/
|
|
594
|
+
function errorCauseChain(value: any) {
|
|
595
|
+
const parts: string[] = []
|
|
596
|
+
let current: any = value
|
|
597
|
+
for (let depth = 0; depth < 5 && current != null; depth += 1) {
|
|
598
|
+
const text = typeof current.message === 'string' && current.message !== ''
|
|
599
|
+
? current.message
|
|
600
|
+
: (typeof current.name === 'string' && current.name !== '' ? current.name : String(current))
|
|
601
|
+
if (!parts.includes(text)) parts.push(text)
|
|
602
|
+
current = current.cause
|
|
603
|
+
}
|
|
604
|
+
return parts.join(': ')
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* [2.2.5][T4] 可被 signal 打断的退避等待:取消一到,Promise 立即 resolve,
|
|
609
|
+
* 调用方随后检查 signal.aborted 抛 ABORTED——真取消路径不吃退避延迟。
|
|
610
|
+
*/
|
|
611
|
+
function sleepAbortable(signal: any, ms: number) {
|
|
612
|
+
return new Promise<void>((resolve) => {
|
|
613
|
+
let timer: any = null
|
|
614
|
+
const finish = () => {
|
|
615
|
+
if (timer !== null) clearTimeout(timer)
|
|
616
|
+
timer = null
|
|
617
|
+
signal?.removeEventListener?.('abort', onAbort)
|
|
618
|
+
resolve()
|
|
619
|
+
}
|
|
620
|
+
const onAbort = () => finish()
|
|
621
|
+
if (signal?.aborted) {
|
|
622
|
+
resolve()
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
timer = setTimeout(finish, ms)
|
|
626
|
+
signal?.addEventListener?.('abort', onAbort, { once: true })
|
|
627
|
+
})
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* [2.1.7] 定时器中止后的正文抢救。
|
|
632
|
+
*
|
|
633
|
+
* 事故里模型流式输出了 900 秒、11694 个块,却因为没等到 finish 信号被整体
|
|
634
|
+
* 丢弃——局部变量 text 连同它一起消失。只要正文末尾已闭合(`}`),就按与正常
|
|
635
|
+
* 路径完全一致的三道闸(extractJson → validatePlan → validatePlanContext)
|
|
636
|
+
* 重新验收;任何一道不过返回 null,照旧报超时。
|
|
637
|
+
*
|
|
638
|
+
* 只认「末尾已闭合」:被拦腰截断的 JSON 即使补上括号也可能丢掉尾部阶段,
|
|
639
|
+
* 静默交出残缺计划比降级更危险。
|
|
640
|
+
*/
|
|
641
|
+
function salvagePartialPlan(text: any, guardOptions: any) {
|
|
642
|
+
if (typeof text !== 'string') return null
|
|
643
|
+
const trimmed = text.trimEnd()
|
|
644
|
+
if (!trimmed.endsWith('}')) return null
|
|
645
|
+
try {
|
|
646
|
+
const raw = extractJson(trimmed)
|
|
647
|
+
const validated = validatePlan(raw)
|
|
648
|
+
if (!validated.ok) return null
|
|
649
|
+
const guard = validatePlanContext(validated.plan, guardOptions)
|
|
650
|
+
if (!guard.ok) return null
|
|
651
|
+
const plan: any = validated.plan
|
|
652
|
+
plan.taskAnchor = guard.audit.anchor
|
|
653
|
+
plan.understandingAudit = compactUnderstandingAudit(guard.audit)
|
|
654
|
+
return plan
|
|
655
|
+
} catch {
|
|
656
|
+
return null
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* [2.1.6] 单次规划器尝试的计时策略——判据是「有没有在产出」,不是「过了多久」。
|
|
662
|
+
*
|
|
663
|
+
* 三扇窗:
|
|
664
|
+
* 1. 无进展窗口(plannerTimeoutMs,默认 300s):自上一个 chunk 起算,首个
|
|
665
|
+
* chunk 之前同样适用。模型持续产出 ⇒ 窗口不断后移,慢而稳定的长任务不再
|
|
666
|
+
* 被固定墙钟掐断;
|
|
667
|
+
* 2. 静默窗口(plannerIdleTimeoutMs,默认 90s):首个 chunk 之后完全静默,
|
|
668
|
+
* 判定为卡死而非还在思考;不小于无进展窗口时等于关闭;
|
|
669
|
+
* 3. 绝对上限(无进展窗口 × PLANNER_HARD_MULTIPLIER,默认 900s):有无产出
|
|
670
|
+
* 都到此为止,规划失败因此永远是「有限时间 + 可执行建议」。
|
|
671
|
+
*
|
|
672
|
+
* 每次中止都携带真实旋钮(DSH_WORKPLAN_PLANNER_TIMEOUT_MS /
|
|
673
|
+
* DSH_WORKPLAN_PLANNER_IDLE_TIMEOUT_MS),而不是让用户去改源码常量。
|
|
674
|
+
*/
|
|
675
|
+
export async function runPlanner(ctx: any, options: any) {
|
|
676
|
+
const {
|
|
677
|
+
taskText, cwd, sessionId, modelSelection, signal,
|
|
678
|
+
conversationContext = '', budget = {}, sourceMessageIds = [], telemetry, onProgress,
|
|
679
|
+
} = options
|
|
680
|
+
const timeoutMs = normalisePlannerWindow(options.plannerTimeoutMs, PLANNER_TIMEOUT_MS)
|
|
681
|
+
const idleMs = normalisePlannerWindow(options.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS)
|
|
682
|
+
const hardMs = timeoutMs * PLANNER_HARD_MULTIPLIER
|
|
683
|
+
/*
|
|
684
|
+
* [2.1.7] 两个可选旋钮:
|
|
685
|
+
* - DSH_WORKPLAN_PLANNER_MAX_TOKENS:给单次生成封顶。无界生成是「流满 900 秒
|
|
686
|
+
* 撞绝对上限」的放大器——封顶后模型会正常 finish,截断可被抢救/回喂;
|
|
687
|
+
* - DSH_WORKPLAN_PLANNER_REASONING_EFFORT:规划专用推理档,只接受
|
|
688
|
+
* low / high / max 三档。非法值不传给模型,回落默认档(见下)。
|
|
689
|
+
*
|
|
690
|
+
* [2.2.0][T13b] 用户 2026-11-08 决策 5「规划器停止继承」:未设该旋钮时,规划器
|
|
691
|
+
* 不再沿用主 Agent 的推理档,而是取 DEFAULT_PLANNER_REASONING_EFFORT(max)。
|
|
692
|
+
* 校验白名单复用 plan.ts 的 REASONING_EFFORTS:把 "ultra"/"medium" 这类非法值
|
|
693
|
+
* 原样发给模型,真实宿主会以 400 拒绝整次规划——环境变量写错不应该让整个
|
|
694
|
+
* 任务降级,所以非法值按「未设置」处理。
|
|
695
|
+
*/
|
|
696
|
+
const plannerMaxTokens = normalisePlannerWindow(process.env.DSH_WORKPLAN_PLANNER_MAX_TOKENS, 0)
|
|
697
|
+
// 大小写归一:"LOW" 这类写法若因大小写被当成非法值回落 max,会静默抬高
|
|
698
|
+
// 用户的成本预期,所以先归一化再进白名单。
|
|
699
|
+
const plannerEffortRaw = String(process.env.DSH_WORKPLAN_PLANNER_REASONING_EFFORT ?? '').trim().toLowerCase()
|
|
700
|
+
const plannerEffort = REASONING_EFFORTS.includes(plannerEffortRaw) ? plannerEffortRaw : ''
|
|
701
|
+
const effectivePlannerEffort = plannerEffort || DEFAULT_PLANNER_REASONING_EFFORT
|
|
702
|
+
const secs = (ms: number) => Math.max(1, Math.round(ms / 1000))
|
|
446
703
|
let lastErrors: string[] = []
|
|
447
|
-
|
|
704
|
+
/*
|
|
705
|
+
* [2.1.6.1] 每次尝试的失败原因必须都留档:旧实现每轮 `lastErrors = ...` 整体
|
|
706
|
+
* 覆盖,最终报错里只剩最后一次,第一次为什么失败永远丢失——事后只能靠猜。
|
|
707
|
+
* [2.2.5][T4] 尝试次数由 2 提到 3(PLANNER_MAX_ATTEMPTS),可重试类失败
|
|
708
|
+
* (传输/超时/服务端/限流)在两次尝试之间做指数退避,吸收偶发网络抖动。
|
|
709
|
+
*/
|
|
710
|
+
const attemptReports: string[] = []
|
|
711
|
+
let lastText = ''
|
|
712
|
+
for (let attempt = 1; attempt <= PLANNER_MAX_ATTEMPTS; attempt += 1) {
|
|
448
713
|
if (signal.aborted) throw abortError()
|
|
449
714
|
const controller = new AbortController()
|
|
450
715
|
const onAbort = () => controller.abort(signal.reason ?? abortError())
|
|
451
716
|
signal.addEventListener('abort', onAbort, { once: true })
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
717
|
+
|
|
718
|
+
const startedAt = Date.now()
|
|
719
|
+
let sawChunk = false
|
|
720
|
+
let lastChunkAt = startedAt
|
|
721
|
+
let chunks = 0
|
|
722
|
+
let promptChars = 0
|
|
723
|
+
let outcome = 'ok'
|
|
724
|
+
/*
|
|
725
|
+
* [2.1.7] 流式正文的落点:collectStream 边流边写,abort/缺 finish 时也
|
|
726
|
+
* 能留下全文,供抢救(salvagePartialPlan)与遥测复盘使用。
|
|
727
|
+
*/
|
|
728
|
+
const sink = { text: '' }
|
|
729
|
+
let progressTimer: any = null
|
|
730
|
+
const clearProgress = () => {
|
|
731
|
+
if (progressTimer) {
|
|
732
|
+
clearTimeout(progressTimer)
|
|
733
|
+
progressTimer = null
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const idleActive = () => sawChunk && idleMs < timeoutMs
|
|
737
|
+
const windowMs = () => (idleActive() ? idleMs : timeoutMs)
|
|
738
|
+
const stallError = () => (idleActive()
|
|
739
|
+
? new PlanError(
|
|
740
|
+
`规划器停滞:输出开始后 ${secs(idleMs)} 秒没有任何新内容,判定为卡死(不是还在思考)。可用 DSH_WORKPLAN_PLANNER_IDLE_TIMEOUT_MS 调整,设为不小于 ${secs(timeoutMs)} 秒即关闭`,
|
|
741
|
+
'PLANNER_IDLE',
|
|
742
|
+
)
|
|
743
|
+
: new PlanError(
|
|
744
|
+
`规划器超时:${secs(timeoutMs)} 秒内没有取得任何进展(任务过长或模型过慢)。请设置 DSH_WORKPLAN_PLANNER_TIMEOUT_MS(毫秒)放宽单次调用上限,或缩短任务文本`,
|
|
745
|
+
'PLANNER_TIMEOUT',
|
|
746
|
+
))
|
|
747
|
+
const checkProgress = () => {
|
|
748
|
+
progressTimer = null
|
|
749
|
+
// 到点时若其实还有进展(窗口刚被收紧或时钟抖动),按剩余时间重新武装。
|
|
750
|
+
if (Date.now() - lastChunkAt < windowMs()) {
|
|
751
|
+
scheduleCheck()
|
|
752
|
+
return
|
|
753
|
+
}
|
|
754
|
+
controller.abort(stallError())
|
|
755
|
+
}
|
|
756
|
+
const scheduleCheck = () => {
|
|
757
|
+
clearProgress()
|
|
758
|
+
const remaining = Math.max(1, windowMs() - (Date.now() - lastChunkAt))
|
|
759
|
+
progressTimer = setTimeout(checkProgress, remaining)
|
|
760
|
+
}
|
|
761
|
+
const hardTimer = setTimeout(() => {
|
|
762
|
+
controller.abort(new PlanError(
|
|
763
|
+
`规划器超出绝对上限:${secs(hardMs)} 秒(= DSH_WORKPLAN_PLANNER_TIMEOUT_MS 的 ${PLANNER_HARD_MULTIPLIER} 倍)。请缩短任务文本,或提高 DSH_WORKPLAN_PLANNER_TIMEOUT_MS`,
|
|
764
|
+
'PLANNER_TIMEOUT_HARD',
|
|
765
|
+
))
|
|
766
|
+
}, hardMs)
|
|
767
|
+
const onChunk = () => {
|
|
768
|
+
chunks += 1
|
|
769
|
+
lastChunkAt = Date.now()
|
|
770
|
+
// 首个 chunk 到达时窗口可能由 300s 收紧为 90s,必须立刻按新窗口重排。
|
|
771
|
+
if (!sawChunk) {
|
|
772
|
+
sawChunk = true
|
|
773
|
+
scheduleCheck()
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
scheduleCheck()
|
|
777
|
+
/*
|
|
778
|
+
* [2.2.5][T4] 本轮重试判定(catch 内赋值,finally 遥测之后执行):
|
|
779
|
+
* - terminalFailure:不可自愈的 LLM 失败类,本轮结束后立即跳出循环;
|
|
780
|
+
* - retryBackoffMs:可重试类失败的重试前退避毫秒数(0 = 不退避)。
|
|
781
|
+
*/
|
|
782
|
+
let terminalFailure = false
|
|
783
|
+
let retryBackoffMs = 0
|
|
455
784
|
try {
|
|
456
785
|
let prompt = buildPlannerPrompt(taskText, cwd, conversationContext, budget)
|
|
786
|
+
promptChars = prompt.length
|
|
457
787
|
if (lastErrors.length > 0) {
|
|
458
788
|
prompt += [
|
|
459
789
|
'',
|
|
@@ -461,15 +791,26 @@ async function runPlanner(ctx: any, options: any) {
|
|
|
461
791
|
...lastErrors.slice(0, 12).map((error: any) => `- ${error}`),
|
|
462
792
|
].join('\n')
|
|
463
793
|
}
|
|
794
|
+
/*
|
|
795
|
+
* [2.2.0][T13b/推理等级] 规划器停止继承主 Agent 的档位(用户 2026-11-08
|
|
796
|
+
* 决策 5,选项 A):显式传 effectivePlannerEffort(旋钮合法值,否则 max)。
|
|
797
|
+
*
|
|
798
|
+
* 旧代码 `plannerEffort || modelSelection.reasoningEffort` 的第二个操作数是
|
|
799
|
+
* 主 Agent 的档位,等于让主 Agent 决定规划器:主 Agent 用 low 省成本时,
|
|
800
|
+
* 拆解也降档,复杂任务被拆得更浅,后续部门再努力也补不回来。现在没有任何
|
|
801
|
+
* 路径读 modelSelection.reasoningEffort 作为规划档位。
|
|
802
|
+
*/
|
|
464
803
|
const stream = ctx.llm.stream({
|
|
465
804
|
provider: modelSelection.provider,
|
|
466
805
|
model: modelSelection.model,
|
|
467
|
-
reasoningEffort:
|
|
806
|
+
reasoningEffort: effectivePlannerEffort,
|
|
807
|
+
...(plannerMaxTokens > 0 ? { maxTokens: plannerMaxTokens } : {}),
|
|
468
808
|
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
469
809
|
signal: controller.signal,
|
|
470
810
|
sessionId,
|
|
471
811
|
})
|
|
472
|
-
const text = await collectStream(stream)
|
|
812
|
+
const text = await collectStream(stream, onChunk, sink)
|
|
813
|
+
lastText = text
|
|
473
814
|
const raw = extractJson(text)
|
|
474
815
|
const validated = validatePlan(raw)
|
|
475
816
|
if (validated.ok) {
|
|
@@ -491,30 +832,178 @@ async function runPlanner(ctx: any, options: any) {
|
|
|
491
832
|
plan.understandingAudit = compactUnderstandingAudit(guard.audit)
|
|
492
833
|
return plan
|
|
493
834
|
}
|
|
835
|
+
outcome = 'CONTEXT_GUARD'
|
|
494
836
|
lastErrors = guard.errors.length > 0 ? guard.errors : guard.warnings
|
|
495
837
|
continue
|
|
496
838
|
}
|
|
839
|
+
outcome = 'INVALID_PLAN'
|
|
497
840
|
lastErrors = validated.errors ?? []
|
|
498
841
|
} catch (error) {
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
842
|
+
/*
|
|
843
|
+
* LLM 层会把 abort 掩码成泛化的 "DeepSeek Messages request aborted",丢失
|
|
844
|
+
* 真实原因。这里优先读我们自己写进 controller.signal.reason 的判定码,
|
|
845
|
+
* 再区分「用户/宿主主动取消」,最后才当作可重试的偶发错误。
|
|
846
|
+
*/
|
|
847
|
+
const reason: any = controller.signal.aborted ? controller.signal.reason : undefined
|
|
848
|
+
if (reason && PLANNER_ABORT_CODES.includes(String(reason.code))) {
|
|
849
|
+
/*
|
|
850
|
+
* [2.1.7] 定时器中止 ≠ 产出作废。旧实现在此直接 throw,900 秒里流出来的
|
|
851
|
+
* 正文随局部变量一起蒸发(遥测 textChars=0 就是这么来的)。先尝试用
|
|
852
|
+
* 与正常路径一致的三道闸验收已产出的正文:能通过就照常返回计划;
|
|
853
|
+
* 通不过才按原判定中止,失败现场由 finally 的遥测留档。
|
|
854
|
+
*/
|
|
855
|
+
const salvaged = salvagePartialPlan(sink.text, {
|
|
856
|
+
taskText,
|
|
857
|
+
conversationContext,
|
|
858
|
+
sourceMessageIds,
|
|
859
|
+
strict: contextGuardStrict(),
|
|
860
|
+
})
|
|
861
|
+
if (salvaged && !signal.aborted) {
|
|
862
|
+
outcome = 'SALVAGED'
|
|
863
|
+
lastText = sink.text
|
|
864
|
+
return salvaged
|
|
865
|
+
}
|
|
866
|
+
outcome = String(reason.code)
|
|
867
|
+
throw reason
|
|
504
868
|
}
|
|
505
|
-
|
|
869
|
+
/*
|
|
870
|
+
* [2.1.7] 同样地:模型写完了 JSON 却没送来 finish 信号(连接抖动、
|
|
871
|
+
* 层序错乱)时,正文若已完整可用就不要整轮作废。
|
|
872
|
+
*/
|
|
873
|
+
if (error instanceof PlanError && error.code === 'PLANNER_INCOMPLETE' && !signal.aborted) {
|
|
874
|
+
const salvaged = salvagePartialPlan(sink.text, {
|
|
875
|
+
taskText,
|
|
876
|
+
conversationContext,
|
|
877
|
+
sourceMessageIds,
|
|
878
|
+
strict: contextGuardStrict(),
|
|
879
|
+
})
|
|
880
|
+
if (salvaged) {
|
|
881
|
+
outcome = 'SALVAGED'
|
|
882
|
+
lastText = sink.text
|
|
883
|
+
return salvaged
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
if (signal.aborted || (controller.signal.aborted && reason?.code === 'ABORTED')) {
|
|
887
|
+
outcome = 'ABORTED'
|
|
506
888
|
throw abortError()
|
|
507
889
|
}
|
|
508
|
-
if (error instanceof PlanError && error.code === 'ABORTED')
|
|
509
|
-
|
|
890
|
+
if (error instanceof PlanError && error.code === 'ABORTED') {
|
|
891
|
+
outcome = 'ABORTED'
|
|
892
|
+
throw error
|
|
893
|
+
}
|
|
894
|
+
outcome = (error instanceof PlanError && error.code) || 'PLANNER_ERROR'
|
|
895
|
+
/*
|
|
896
|
+
* [2.2.5][T4] 失败原因整链透传(T3 根因 P2):error.message 只是外层包装
|
|
897
|
+
* (如 "fetch failed"),真因(ENOTFOUND / ECONNREFUSED / TLS alert)挂在
|
|
898
|
+
* cause 链上。展开后写入 lastErrors → attemptReports → 最终降级文案,
|
|
899
|
+
* 下次失败不再只看到一句 "TRANSPORT:Connection error"。
|
|
900
|
+
*/
|
|
901
|
+
const message = error instanceof Error ? errorCauseChain(error) : String(error)
|
|
902
|
+
lastErrors = [message]
|
|
903
|
+
/*
|
|
904
|
+
* [2.1.6.1] 只回一句「位置 6041」给模型毫无用处:它看不到自己断在哪。
|
|
905
|
+
* 把断点附近的原文与「截断 / 写错」的判据一并回喂,第二次尝试才有靶子;
|
|
906
|
+
* 同时把长度与尾部落进遥测,失败现场从此可复盘。
|
|
907
|
+
*/
|
|
908
|
+
if (error instanceof PlanError && error.code === 'INVALID_JSON' && lastText) {
|
|
909
|
+
const trimmed = lastText.trimEnd()
|
|
910
|
+
const tail = trimmed.slice(-120)
|
|
911
|
+
const closed = trimmed.endsWith('}')
|
|
912
|
+
lastErrors = [
|
|
913
|
+
message,
|
|
914
|
+
`输出共 ${lastText.length} 字符,末尾原文:${JSON.stringify(tail)}`,
|
|
915
|
+
closed
|
|
916
|
+
? '末尾已闭合 → 断点在正文中间,属语法写错(漏逗号/括号不匹配)'
|
|
917
|
+
: '末尾未闭合(没有结尾 })→ 疑似输出被截断,请给出更紧凑的完整 JSON',
|
|
918
|
+
]
|
|
919
|
+
}
|
|
920
|
+
/*
|
|
921
|
+
* [2.2.5][T4] 重试分级 + 退避(T3 根因 P1):旧实现 catch 后零退避立即
|
|
922
|
+
* 重试——一次 ~1s 网络连接尖峰 × 0ms 间隔 = 1.2 秒内两连败直接降级。
|
|
923
|
+
* 现在:可重试类(TRANSPORT/TIMEOUT/SERVER/RATE_LIMIT)按 500ms→1s
|
|
924
|
+
* 指数退避(±20% 抖动,可被 signal 打断)给抖动尾巴留出恢复窗口;
|
|
925
|
+
* 其余 LLM 失败类(AUTH/INVALID_REQUEST/配额/上下文溢出等)重试不会
|
|
926
|
+
* 自愈,置 terminal 标志本轮结束后立即跳出,不烧下一次调用。
|
|
927
|
+
*/
|
|
928
|
+
const llmCode = error instanceof PlanError && error.code === 'PLANNER_LLM_ERROR'
|
|
929
|
+
&& typeof error.details === 'string'
|
|
930
|
+
? error.details
|
|
931
|
+
: ''
|
|
932
|
+
if (llmCode !== '' && !PLANNER_RETRYABLE_LLM_CODES.includes(llmCode)) {
|
|
933
|
+
terminalFailure = true
|
|
934
|
+
} else if (attempt < PLANNER_MAX_ATTEMPTS && !signal.aborted) {
|
|
935
|
+
retryBackoffMs = Math.round(
|
|
936
|
+
PLANNER_RETRY_BACKOFF_BASE_MS * 2 ** (attempt - 1) * (0.8 + Math.random() * 0.4),
|
|
937
|
+
)
|
|
938
|
+
}
|
|
510
939
|
} finally {
|
|
511
|
-
|
|
940
|
+
clearProgress()
|
|
941
|
+
clearTimeout(hardTimer)
|
|
512
942
|
signal.removeEventListener('abort', onAbort)
|
|
943
|
+
/*
|
|
944
|
+
* [2.1.6] 规划器遥测:此前失败现场什么都不留,事后只能从会话 JSONL 反推
|
|
945
|
+
* 「恰好 300.06 秒」。现在每次尝试都留下模型、提示词规模、产出块数、耗时
|
|
946
|
+
* 与判定码,失败时随降级消息一起给到用户。
|
|
947
|
+
*/
|
|
948
|
+
if (outcome !== 'ok' && lastErrors.length > 0) {
|
|
949
|
+
attemptReports.push(`第 ${attempt} 次[${outcome}]:${lastErrors.join(';')}`)
|
|
950
|
+
/*
|
|
951
|
+
* [2.2.5][T5] 分解期间进度透出(T1 P-6 / T3 §5):每次失败尝试在遥测
|
|
952
|
+
* 留档之后向调用方回调一次(attempt / outcome / 真因链 / 退避毫秒 /
|
|
953
|
+
* 终态)。这里只是追加观察点——terminalFailure 与 retryBackoffMs 在
|
|
954
|
+
* catch 里已定值,本回调不读写循环控制变量,重试判定、退避与跳出
|
|
955
|
+
* 语义与旧实现逐字节一致。
|
|
956
|
+
*/
|
|
957
|
+
if (typeof onProgress === 'function') {
|
|
958
|
+
onProgress({
|
|
959
|
+
attempt,
|
|
960
|
+
outcome,
|
|
961
|
+
lastErrors: [...lastErrors],
|
|
962
|
+
retryBackoffMs,
|
|
963
|
+
terminal: terminalFailure,
|
|
964
|
+
aborted: signal.aborted,
|
|
965
|
+
})
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
if (telemetry && typeof telemetry === 'object') {
|
|
969
|
+
Object.assign(telemetry, {
|
|
970
|
+
// [2.1.7] 以 sink 为准:abort 时 lastText 恒为空,旧值让现场永远缺「输出 N 字」。
|
|
971
|
+
textChars: Math.max(lastText.length, sink.text.length),
|
|
972
|
+
provider: modelSelection.provider,
|
|
973
|
+
model: modelSelection.model,
|
|
974
|
+
// [2.2.0][T13b] 记录**实际发给模型**的档位:旧值记的是 modelSelection
|
|
975
|
+
// (主 Agent 档位),规划器停止继承后它不再等于生效值,照抄会让事后
|
|
976
|
+
// 复盘把「主 Agent=high」误读成「规划器=high」。
|
|
977
|
+
reasoningEffort: effectivePlannerEffort,
|
|
978
|
+
reasoningEffortSource: plannerEffort ? 'env' : 'default-max',
|
|
979
|
+
attempt,
|
|
980
|
+
taskChars: typeof taskText === 'string' ? taskText.length : 0,
|
|
981
|
+
promptChars,
|
|
982
|
+
chunks,
|
|
983
|
+
elapsedMs: Date.now() - startedAt,
|
|
984
|
+
outcome,
|
|
985
|
+
at: Date.now(),
|
|
986
|
+
})
|
|
987
|
+
if (plannerDebugEnabled()) {
|
|
988
|
+
console.warn('[dsh-workplan] planner attempt', JSON.stringify({ ...telemetry }))
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
/*
|
|
993
|
+
* [2.2.5][T4] 退避在 finally(遥测计时)之后执行,不污染单次尝试的
|
|
994
|
+
* elapsedMs;不可自愈失败在此直接跳出,最终报错仍走统一的聚合文案。
|
|
995
|
+
* 校验类重试(CONTEXT_GUARD/INVALID_PLAN 的 continue)不经过这里,
|
|
996
|
+
* 保持原有的零退避快重试。
|
|
997
|
+
*/
|
|
998
|
+
if (terminalFailure) break
|
|
999
|
+
if (retryBackoffMs > 0) {
|
|
1000
|
+
await sleepAbortable(signal, retryBackoffMs)
|
|
1001
|
+
if (signal.aborted) throw abortError()
|
|
513
1002
|
}
|
|
514
1003
|
}
|
|
515
1004
|
const deviation = lastErrors.some((error: any) => /^(?:DEVIATION|CLARIFY|CONTEXT):/.test(String(error)))
|
|
516
1005
|
throw new PlanError(
|
|
517
|
-
|
|
1006
|
+
`规划器 ${attemptReports.length > 0 ? `全部 ${attemptReports.length} 次尝试` : '输出'}均未通过校验:${(attemptReports.length > 0 ? attemptReports : lastErrors).slice(0, 6).join(' | ')}`,
|
|
518
1007
|
deviation ? 'DEVIATION' : 'PLANNER_FAILED',
|
|
519
1008
|
lastErrors,
|
|
520
1009
|
)
|
|
@@ -1001,6 +1490,25 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
|
|
|
1001
1490
|
} else if (checked.missingArtifacts.length > 0) {
|
|
1002
1491
|
recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard)
|
|
1003
1492
|
}
|
|
1493
|
+
/*
|
|
1494
|
+
* [2.2.0][T6/O-1a] 完成即时通知(插件兜底通道,方案 §2.3)。
|
|
1495
|
+
*
|
|
1496
|
+
* 结算成功后立刻把「子任务 ID+摘要+验收计数+用时」交给主会话,不等待
|
|
1497
|
+
* 整轮结束;只有真正的 done 才通知(blocked/escalated 不产生「已完成」
|
|
1498
|
+
* 措辞,A4)。投递与幂等标记由 `onSubtaskDone` 处理器负责:先写通知、
|
|
1499
|
+
* 写成功才记 report.state='sent',绝不留无证据的已回报。
|
|
1500
|
+
*/
|
|
1501
|
+
if (verdict.status === 'done' && options.notifyCompletion === true
|
|
1502
|
+
&& typeof options.onSubtaskDone === 'function') {
|
|
1503
|
+
try {
|
|
1504
|
+
options.onSubtaskDone(record, subtask, verdict)
|
|
1505
|
+
} catch {
|
|
1506
|
+
/*
|
|
1507
|
+
* 通知是辅助通道:写失败不得回滚已经成立的完成判定,也不得让执行
|
|
1508
|
+
* 路径报错。失败由处理器记 reportPending,交 finishRound 批量补齐。
|
|
1509
|
+
*/
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1004
1512
|
return { ...verdict, escalated }
|
|
1005
1513
|
}
|
|
1006
1514
|
|
|
@@ -1061,6 +1569,95 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1061
1569
|
? options.attemptOffset
|
|
1062
1570
|
: 1
|
|
1063
1571
|
let lastFailure: any = options.priorFailure ?? null
|
|
1572
|
+
/*
|
|
1573
|
+
* [2.2.0][T3/O-2a] 子→主预告通道的两个动作,都在本函数内闭环:
|
|
1574
|
+
* recordNoticeChannel —— 派发瞬间写下「目标 / 调用方 / 时间戳」;
|
|
1575
|
+
* finaliseNotice —— 结算瞬间去父会话日志里核实预告到底有没有转达,
|
|
1576
|
+
* 没转达就写一条四项齐全的失败日志(不静默丢失)。
|
|
1577
|
+
*
|
|
1578
|
+
* 目标 id 只从注入值取;注入值缺失时才按 agent.id → session.id 再解析一次
|
|
1579
|
+
* (重启重建/续跑路径)。[2.2.1][T5][F4] 不再回落 plan.sessionId:计划正文
|
|
1580
|
+
* 可能属于另一个 root 会话,不能作为「发给谁」的依据;两级都没有就留空,
|
|
1581
|
+
* 让提示词走「禁止猜测」分支。
|
|
1582
|
+
*/
|
|
1583
|
+
const noticeLead = (() => {
|
|
1584
|
+
const injected = readLeadAgentId(options.leadAgentId)
|
|
1585
|
+
const liveAgentId = readLeadAgentId(options.agent?.id)
|
|
1586
|
+
/*
|
|
1587
|
+
* [2.2.0][T3/O-2a][F4] 目标完整性 fail-closed。
|
|
1588
|
+
*
|
|
1589
|
+
* 注入值来自 dispatchPlan 的 agent.id 优先解析;若未来某条重建/续跑路径
|
|
1590
|
+
* 只拿得到 plan.sessionId 兜底值,而执行侧又有活 Agent,则两者不一致
|
|
1591
|
+
* 时绝不能把兜底值写进子提示词(那等于把目标指向另一个 root 会话)。
|
|
1592
|
+
*/
|
|
1593
|
+
if (injected && liveAgentId && injected !== liveAgentId) {
|
|
1594
|
+
return { id: '', source: 'mismatch:agent.id' }
|
|
1595
|
+
}
|
|
1596
|
+
if (injected) {
|
|
1597
|
+
return {
|
|
1598
|
+
id: injected,
|
|
1599
|
+
source: typeof options.leadAgentIdSource === 'string' && options.leadAgentIdSource !== 'none'
|
|
1600
|
+
? options.leadAgentIdSource
|
|
1601
|
+
: 'options.leadAgentId',
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
return resolveLeadAgentId({ agent: options.agent, session: options.session })
|
|
1605
|
+
})()
|
|
1606
|
+
const recordNoticeChannel = (entry: any) => {
|
|
1607
|
+
try {
|
|
1608
|
+
writeSubtaskStatus(record, subtask.id, { noticeChannel: entry }, guard)
|
|
1609
|
+
} catch (error: any) {
|
|
1610
|
+
/*
|
|
1611
|
+
* 通道留痕失败不能影响子任务本身(它是观测设施,不是交付物),但也不能
|
|
1612
|
+
* 一点痕迹都不留——写进本轮错误列表,主 Agent 读记录时能看到。
|
|
1613
|
+
*/
|
|
1614
|
+
record.errors = [...(record.errors ?? []), `${subtask.id} noticeChannel 写入失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20)
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
const finaliseNotice = () => {
|
|
1618
|
+
if (guard.timedOut) {
|
|
1619
|
+
/*
|
|
1620
|
+
* [2.2.0][T3/O-2a][F3] 超时路径 writeSubtaskStatus 会被 guard 静默拒绝,
|
|
1621
|
+
* 不能写状态行;但通道不能停在没有结论的 awaiting。至少把四项日志写进
|
|
1622
|
+
* record.errors,让主 Agent 知道「是超时导致没收到结论」,而不是猜测。
|
|
1623
|
+
*/
|
|
1624
|
+
const row = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1625
|
+
const current = row?.noticeChannel
|
|
1626
|
+
if (current) {
|
|
1627
|
+
record.errors = [...(record.errors ?? []), formatNoticeChannelLog({
|
|
1628
|
+
subtaskId: subtask.id,
|
|
1629
|
+
target: current.target,
|
|
1630
|
+
caller: current.caller,
|
|
1631
|
+
at: current.at,
|
|
1632
|
+
reason: 'TIMEOUT',
|
|
1633
|
+
})].slice(-20)
|
|
1634
|
+
}
|
|
1635
|
+
return
|
|
1636
|
+
}
|
|
1637
|
+
const row = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1638
|
+
const current = row?.noticeChannel
|
|
1639
|
+
if (!current) return
|
|
1640
|
+
const noticeSession = options.session && typeof options.session.eventAt === 'function'
|
|
1641
|
+
? options.session
|
|
1642
|
+
: findSession(ctx, current.target)
|
|
1643
|
+
const observed = observeRelayedNotice(noticeSession, { childId: current.caller, sinceMs: current.at })
|
|
1644
|
+
const entry = finaliseNoticeChannel(current, {
|
|
1645
|
+
observed: Boolean(observed),
|
|
1646
|
+
observedAt: observed?.at ?? null,
|
|
1647
|
+
sessionAvailable: Boolean(noticeSession),
|
|
1648
|
+
now: Date.now(),
|
|
1649
|
+
})
|
|
1650
|
+
recordNoticeChannel(entry)
|
|
1651
|
+
if (entry.state !== 'observed') {
|
|
1652
|
+
record.errors = [...(record.errors ?? []), formatNoticeChannelLog({
|
|
1653
|
+
subtaskId: subtask.id,
|
|
1654
|
+
target: entry.target,
|
|
1655
|
+
caller: entry.caller,
|
|
1656
|
+
at: entry.at,
|
|
1657
|
+
reason: entry.reason,
|
|
1658
|
+
})].slice(-20)
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1064
1661
|
/*
|
|
1065
1662
|
* [2.1.0] 格式退回通知必须在下一次激活送达部门人员(用户 2026-11-06 的
|
|
1066
1663
|
* 强制要求:不符合要求立刻退回,通知其重新检查格式后重交)。
|
|
@@ -1105,11 +1702,24 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1105
1702
|
let interruptedFlag = false
|
|
1106
1703
|
let interruptedEvidence: { artifacts: any[]; missingArtifacts: string[] } | null = null
|
|
1107
1704
|
try {
|
|
1705
|
+
// [2.2.0][T4/O-3b] 尝试起点与协商截止同一时钟读数(C3 契约:deadlineAt −
|
|
1706
|
+
// startedAt 严格等于协商窗口)。deadlineAt 走 StatusEntry 未知字段保留通道
|
|
1707
|
+
// 直写:applyStatus(src/plan.ts,T3 领地)无路由分支,patch 会静默丢弃。
|
|
1708
|
+
const attemptStartMs = Date.now()
|
|
1709
|
+
const attemptWindowMs = Number(options.attemptTimeoutMs ?? 0)
|
|
1108
1710
|
if (!writeSubtaskStatus(record, subtask.id, {
|
|
1109
1711
|
status: 'in_progress',
|
|
1110
1712
|
progress: 5,
|
|
1111
|
-
startedAt:
|
|
1713
|
+
startedAt: attemptStartMs,
|
|
1112
1714
|
}, guard)) return
|
|
1715
|
+
if (Number.isFinite(attemptWindowMs) && attemptWindowMs > 0) {
|
|
1716
|
+
const attemptRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1717
|
+
if (attemptRow) attemptRow.deadlineAt = attemptStartMs + attemptWindowMs
|
|
1718
|
+
if (options.attemptHandle) {
|
|
1719
|
+
options.attemptHandle.startedAt = attemptStartMs
|
|
1720
|
+
options.attemptHandle.deadlineAt = attemptStartMs + attemptWindowMs
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1113
1723
|
|
|
1114
1724
|
for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
|
|
1115
1725
|
if (guard.timedOut) return
|
|
@@ -1172,6 +1782,14 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1172
1782
|
cwd: options.cwd,
|
|
1173
1783
|
conversationContext,
|
|
1174
1784
|
statuses: record.statuses,
|
|
1785
|
+
/*
|
|
1786
|
+
* [2.2.0][T3/O-2a] 子→主预告通道的目标(真实父会话 id)。
|
|
1787
|
+
*
|
|
1788
|
+
* 宿主只在非 caller 投递时注入父会话 id,本插件用 caller 投递,
|
|
1789
|
+
* 所以这里必须自己给值;空值走「禁止猜测」分支,绝不编造 id。
|
|
1790
|
+
*/
|
|
1791
|
+
leadAgentId: noticeLead.id,
|
|
1792
|
+
leadAgentIdSource: noticeLead.source,
|
|
1175
1793
|
/*
|
|
1176
1794
|
* [2.1.0] 不再用 attempt>1 做门槛:被格式退回的行复位后第 1 次
|
|
1177
1795
|
* 激活也必须带上退回通知,否则「退回」只是写了一行状态。
|
|
@@ -1182,9 +1800,27 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1182
1800
|
}],
|
|
1183
1801
|
parent: options.agent,
|
|
1184
1802
|
cwd: typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined,
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1803
|
+
/*
|
|
1804
|
+
* [2.2.0][T13/推理等级] 子 Agent 不得继承主 Agent 的推理等级。
|
|
1805
|
+
*
|
|
1806
|
+
* 用户规则原文:「禁止子agent继承主agent的推理等级,子agent必须根据
|
|
1807
|
+
* 自身任务的复杂度,自己使用推理等级为low、high或者是Max,其中,轻度
|
|
1808
|
+
* 复杂的任务使用low,中等复杂的任务使用high,非常复杂的任务使用Max。」
|
|
1809
|
+
* 宿主 resolveChildAgentOptions 在请求未点名 reasoningEffort 时会继承
|
|
1810
|
+
* 父 Agent 的等级(dsh-subagent child-agent.d.ts:40-50),旧实现在这里
|
|
1811
|
+
* 只传 provider/model,于是主 Agent 的等级被原样带进每个部门子会话。
|
|
1812
|
+
* 现在显式覆盖为子任务自己的档位;缺失(旧计划/回放)回落 high,绝不
|
|
1813
|
+
* 读取 modelSelection.reasoningEffort。
|
|
1814
|
+
*/
|
|
1815
|
+
agentOptions: {
|
|
1816
|
+
...(modelSelection?.provider && modelSelection?.model
|
|
1817
|
+
? { provider: modelSelection.provider, model: modelSelection.model }
|
|
1818
|
+
: {}),
|
|
1819
|
+
reasoningEffort: typeof subtask.reasoningEffort === 'string'
|
|
1820
|
+
&& REASONING_EFFORTS.includes(subtask.reasoningEffort)
|
|
1821
|
+
? subtask.reasoningEffort
|
|
1822
|
+
: DEFAULT_REASONING_EFFORT,
|
|
1823
|
+
},
|
|
1188
1824
|
maxDepth: 1,
|
|
1189
1825
|
},
|
|
1190
1826
|
signal: child.controller.signal,
|
|
@@ -1222,6 +1858,19 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1222
1858
|
blockedKind: null,
|
|
1223
1859
|
}, guard)
|
|
1224
1860
|
if (!assigned) return
|
|
1861
|
+
/*
|
|
1862
|
+
* [2.2.0][T3/O-2a] 通道条目:此刻写下目标、调用方与时间戳。
|
|
1863
|
+
*
|
|
1864
|
+
* 这一步只记事实,不猜结果——消息有没有真的到主会话,要等结算时去父
|
|
1865
|
+
* 会话日志里看(observeRelayedNotice)。旧实现里预告失败在计划记录上
|
|
1866
|
+
* 完全不可见,主 Agent 只能看到一句 `subagent "lead" is unavailable`。
|
|
1867
|
+
*/
|
|
1868
|
+
recordNoticeChannel(createNoticeChannel({
|
|
1869
|
+
target: noticeLead.id,
|
|
1870
|
+
targetSource: noticeLead.source,
|
|
1871
|
+
caller: activation.childId,
|
|
1872
|
+
at: assignedAt,
|
|
1873
|
+
}))
|
|
1225
1874
|
const ackTimers: Array<ReturnType<typeof setTimeout>> = []
|
|
1226
1875
|
clearAckTimers = () => {
|
|
1227
1876
|
while (ackTimers.length > 0) {
|
|
@@ -1269,8 +1918,56 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1269
1918
|
deadlineTimer.unref?.()
|
|
1270
1919
|
ackTimers.push(deadlineTimer)
|
|
1271
1920
|
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
|
|
1272
|
-
|
|
1921
|
+
// [2.2.0][T4/O-3b][O-4d] 双计时同源(方案 §2.5):看门狗 hardMs 与本次尝试的
|
|
1922
|
+
// 协商执行时限同值(options.attemptTimeoutMs,缺省回落旧路径);两者必须同步
|
|
1923
|
+
// 推移——延期时 rearmApproachingDeadline 传「自尝试起点计的新完整窗口」。
|
|
1924
|
+
const hardTimeoutMs = Number.isFinite(Number(options.attemptTimeoutMs)) && Number(options.attemptTimeoutMs) > 0
|
|
1925
|
+
? Math.min(MAX_CHILD_TIMEOUT_MS, Math.max(MIN_CHILD_TIMEOUT_MS, Number(options.attemptTimeoutMs)))
|
|
1926
|
+
: normaliseChildTimeout(options.childTimeoutMs)
|
|
1273
1927
|
const watchdog = createProgressWatchdog({
|
|
1928
|
+
// [2.2.0][T4/O-3b][O-4b] 到点预警接线(T7 watchdog.ts 契约,原样消费):
|
|
1929
|
+
// 剩余 ≤ max(timeoutMs×0.2, 120000) 触发一次、同一武装周期幂等、extend 后
|
|
1930
|
+
// rearm 可再触发。最小处理器:时间链留档 timeWarning+本轮记录 notice+会话
|
|
1931
|
+
// 消息通知主 Agent(格式朴素,T6 波次统一润色)。
|
|
1932
|
+
subtaskId: String(subtask.id),
|
|
1933
|
+
onApproachingDeadline: (info: any) => {
|
|
1934
|
+
if (guard.timedOut) return
|
|
1935
|
+
try {
|
|
1936
|
+
const warnRow = Array.isArray(record.statuses)
|
|
1937
|
+
? record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
1938
|
+
: null
|
|
1939
|
+
if (warnRow) {
|
|
1940
|
+
// timeWarning 走未知字段通道直写(applyStatus 白名单属 T3 领地)。
|
|
1941
|
+
warnRow.timeWarning = {
|
|
1942
|
+
at: Date.now(),
|
|
1943
|
+
remainingMs: Math.max(0, Number(info?.remainingMs ?? 0)),
|
|
1944
|
+
newEstimateMinutes: null,
|
|
1945
|
+
channel: 'watchdog',
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
const text = `子任务 ${subtask.id} 即将到点:剩余 ${Math.max(0, Math.round(Number(info?.remainingMs ?? 0) / 1000))}s(协商上限 ${Number(info?.timeoutMs ?? 0)}ms);如需继续请尽快决定延期(extendMs),否则到点将按安全兜底结算(待裁决)`
|
|
1949
|
+
record.notices = [...(record.notices ?? []), text].slice(-20)
|
|
1950
|
+
record.updatedAt = Date.now()
|
|
1951
|
+
/*
|
|
1952
|
+
* 会话消息只对「有决策余量」的窗口推送:窗口 < 120000ms(=触发规则
|
|
1953
|
+
* max(timeoutMs×0.2, 120000) 里的预警下限,生产最小派生窗口恰好
|
|
1954
|
+
* 120000ms)只出现在测试小窗场景,预警本身没有可执行的延期决策余量,
|
|
1955
|
+
* 此时只留档(record.notices+timeWarning),不推送会话消息——也不与
|
|
1956
|
+
* tests/workplan-stuck-recovery.test.ts「session.events 只计持久消息」
|
|
1957
|
+
* 的既有断言冲突。T6 波次统一润色通知渠道时再定稿推送策略。
|
|
1958
|
+
* [2.2.0][T6/O-1a] 渠道已定稿:与完成即时通知同走主会话
|
|
1959
|
+
* `user/message` 纯文本通道(方案 §2.3「即时通知消息」);决策余量
|
|
1960
|
+
* 门槛(timeoutMs ≥ 120000,取自触发规则预警下限)保持不变,故
|
|
1961
|
+
* 上述断言不受影响。
|
|
1962
|
+
*/
|
|
1963
|
+
if (Number(info?.timeoutMs ?? 0) >= 120000) {
|
|
1964
|
+
const warnSession = options.session ?? options.agent?.session
|
|
1965
|
+
appendUserMessage(warnSession, text)
|
|
1966
|
+
}
|
|
1967
|
+
} catch {
|
|
1968
|
+
// 预警只做提示不得影响执行:写档失败静默忽略(T6 波次统一润色)。
|
|
1969
|
+
}
|
|
1970
|
+
},
|
|
1274
1971
|
getSeq: () => {
|
|
1275
1972
|
try {
|
|
1276
1973
|
const childSession = ctx.sessions?.get?.(activation.childId)
|
|
@@ -1317,6 +2014,9 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1317
2014
|
{ subtaskId: subtask.id },
|
|
1318
2015
|
),
|
|
1319
2016
|
})
|
|
2017
|
+
// [2.2.0][T4/O-3b][O-4d] 看门狗挂到计时句柄:extendDeadline 延期成功后经
|
|
2018
|
+
// watchdog.rearmApproachingDeadline(传新完整窗口)同步推移两处计时。
|
|
2019
|
+
options.attemptHandle?.attachWatchdog?.(watchdog)
|
|
1320
2020
|
let result: any
|
|
1321
2021
|
try {
|
|
1322
2022
|
const waiter = waitForActivation(activation, child.controller.signal)
|
|
@@ -1466,7 +2166,124 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
1466
2166
|
// The status list itself is unusable; the outer dispatcher records the error.
|
|
1467
2167
|
}
|
|
1468
2168
|
recordSubtaskError(record, subtask.id, message, guard)
|
|
2169
|
+
} finally {
|
|
2170
|
+
/*
|
|
2171
|
+
* [2.2.0][T3/O-2a] 结算点唯一的通道收束入口(成功/受阻/待指示/中断都走这里)。
|
|
2172
|
+
*
|
|
2173
|
+
* 放在 finally 而不是各条 return 前面,是为了让「通道结论」与「子任务结论」
|
|
2174
|
+
* 一定是同一次执行的产物:任何一个出口漏写,都会让预告看起来像消失了。
|
|
2175
|
+
* [F3] 观测设施自身不得把已结算的子任务变成本轮异常:任何异常只进
|
|
2176
|
+
* record.errors,绝不从 finally 外抛。
|
|
2177
|
+
*/
|
|
2178
|
+
try {
|
|
2179
|
+
finaliseNotice()
|
|
2180
|
+
} catch (error: any) {
|
|
2181
|
+
record.errors = [...(record.errors ?? []), `${subtask.id} noticeChannel 收束失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20)
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
/*
|
|
2187
|
+
* [2.2.0][T4/O-3b] 本次执行时限(柔性时长协商消费序;T3b 待决点③裁决:消费侧钳位)。
|
|
2188
|
+
*
|
|
2189
|
+
* 消费序:① subtask.timeoutMs 显式协商上限(O-3c 原样透传)→ ② 缺省
|
|
2190
|
+
* deriveSubtaskTimeoutMs(estimateMinutes)=clamp(预估分钟×2.0×60000, 1000,
|
|
2191
|
+
* 7200000) 派生(方案 §1③)→ ③ 两者皆无回落 normaliseChildTimeout(全局兜底
|
|
2192
|
+
* CHILD_TIMEOUT_MS,方案 ③C2 零回归)。结果统一钳 [MIN_CHILD_TIMEOUT_MS,
|
|
2193
|
+
* MAX_CHILD_TIMEOUT_MS](方案 ③C3)。
|
|
2194
|
+
*
|
|
2195
|
+
* 显式注入的 childTimeoutMs(测试小窗 / DSH_WORKPLAN_CHILD_TIMEOUT_MS 旋钮)
|
|
2196
|
+
* 语义是「兜底上限」而非「固定值」(方案 §5.2「协商的默认基准/兜底上限」):
|
|
2197
|
+
* 它对上面三步的结果取 min。必须区分「显式注入」与「缺省」——验收合同
|
|
2198
|
+
* tests/no-fixed-deadline-semantics.test.ts E4 注入 1000ms 小窗必须压过
|
|
2199
|
+
* estimateMinutes:10 派生的 1200000ms;而 tests/time-estimate-negotiation
|
|
2200
|
+
* .test.ts C3(无注入)派生值必须严格生效(deadlineAt − startedAt === 派生值)。
|
|
2201
|
+
* 因此 dispatchPlan 三处调用点改传 options.childTimeoutMs 原始值(未配置=
|
|
2202
|
+
* undefined),不再传 normalise 后的 limits.childTimeoutMs(后者恒为 900000,
|
|
2203
|
+
* 无法区分显式与缺省)。
|
|
2204
|
+
*/
|
|
2205
|
+
function resolveSubtaskTimeoutMs(subtask: any, configuredChildTimeoutMs: any) {
|
|
2206
|
+
const clampWindow = (value: number) =>
|
|
2207
|
+
Math.min(MAX_CHILD_TIMEOUT_MS, Math.max(MIN_CHILD_TIMEOUT_MS, value))
|
|
2208
|
+
const explicit = Number(subtask?.timeoutMs)
|
|
2209
|
+
const derived = deriveSubtaskTimeoutMs(subtask?.estimateMinutes, MIN_CHILD_TIMEOUT_MS, MAX_CHILD_TIMEOUT_MS)
|
|
2210
|
+
let window: number
|
|
2211
|
+
if (Number.isFinite(explicit) && explicit > 0) window = clampWindow(explicit)
|
|
2212
|
+
else if (derived !== undefined) window = clampWindow(derived)
|
|
2213
|
+
else window = normaliseChildTimeout(configuredChildTimeoutMs)
|
|
2214
|
+
// 显式注入=兜底上限(对协商结果取 min);未配置不封顶。
|
|
2215
|
+
const cap = Number(configuredChildTimeoutMs)
|
|
2216
|
+
if (Number.isFinite(cap) && cap > 0) window = Math.min(window, clampWindow(cap))
|
|
2217
|
+
return window
|
|
2218
|
+
}
|
|
2219
|
+
|
|
2220
|
+
/*
|
|
2221
|
+
* [2.2.0][T4/O-3b][O-4c/O-4d] 延期接口(D 项;T5 extendMs 事务的计时侧承接)。
|
|
2222
|
+
*
|
|
2223
|
+
* 调用契约(T5 按此接线):
|
|
2224
|
+
* extendDeadline(record, subtaskId, extendMs, { by?, reason? })
|
|
2225
|
+
* → 成功 { ok: true, deadlineAt, timerRearmed: true, watchdogRearmed }
|
|
2226
|
+
* → 拒绝 { ok: false, code: 'INVALID_EXTEND' | 'NO_ACTIVE_ATTEMPT', error, hint }
|
|
2227
|
+
*
|
|
2228
|
+
* 语义与边界:
|
|
2229
|
+
* - extendMs 须为正有限数(毫秒,向下取整),否则 INVALID_EXTEND。
|
|
2230
|
+
* - 只对「有活跃尝试」的子任务生效(runSubtaskAttempt 已注册计时句柄且未收束);
|
|
2231
|
+
* 已到点收束 / 已结束的尝试一律 NO_ACTIVE_ATTEMPT(不能复活已结算的行)。
|
|
2232
|
+
* - 累计放宽预算校验(≤初始协商上限×1,超限 EXTEND_BUDGET_EXHAUSTED→转新轮
|
|
2233
|
+
* 续跑或转 escalate)属 T5 事务层职责,本函数不重复校验:调用方先校验再调用。
|
|
2234
|
+
* - 线程/并发语义:Node 单线程;本函数「校验→改 deadlineAt→重置计时器→
|
|
2235
|
+
* watchdog.rearmApproachingDeadline→行内直写」在一个同步段完成,天然原子;
|
|
2236
|
+
* 并发调用按到达顺序串行,每次追加独立 timeJournal 条目(action:'extend')。
|
|
2237
|
+
* - 延期成功后 deadlineAt 同步更新(行上字段=句柄 deadlineAt),runSubtaskAttempt
|
|
2238
|
+
* 的一次性计时器重置为「新截止点 − now」,原截止点不再触发(O-4d:任务不被
|
|
2239
|
+
* 原截止点杀死)。
|
|
2240
|
+
* - 与 watchdog 的配合(F 项):watchdog.rearmApproachingDeadline(newTimeoutMs)
|
|
2241
|
+
* 传入「自尝试起点计的新完整窗口」=deadlineAt − 尝试起点(T7 watchdog.ts
|
|
2242
|
+
* 契约,不是剩余量);两处计时同步推移(方案 §2.5),先触发者仍会杀任务。
|
|
2243
|
+
* - 行字段直写原因:applyStatus(src/plan.ts,T3 领地)无 deadlineAt/timeJournal
|
|
2244
|
+
* 路由分支,patch 会静默丢弃;这里走 StatusEntry 未知字段保留通道直写,
|
|
2245
|
+
* 回放/重建白名单在 reconstructFromSession 同名直写(本文件 2931 一带)。
|
|
2246
|
+
*/
|
|
2247
|
+
export function extendDeadline(record: any, subtaskId: any, extendMs: any, meta: any = {}) {
|
|
2248
|
+
const id = String(subtaskId ?? '')
|
|
2249
|
+
const amount = Number(extendMs)
|
|
2250
|
+
if (!Number.isFinite(amount) || amount < 1) {
|
|
2251
|
+
return {
|
|
2252
|
+
ok: false,
|
|
2253
|
+
code: 'INVALID_EXTEND',
|
|
2254
|
+
error: `extendMs 必须是正有限数(毫秒):${String(extendMs)}`,
|
|
2255
|
+
hint: '请传入 1 以上的毫秒数;需要更长时限请转新轮续跑或转 escalate',
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
const delta = Math.floor(amount)
|
|
2259
|
+
const handle = record?.attemptHandles?.[id]
|
|
2260
|
+
if (!handle || handle.settled) {
|
|
2261
|
+
return {
|
|
2262
|
+
ok: false,
|
|
2263
|
+
code: 'NO_ACTIVE_ATTEMPT',
|
|
2264
|
+
error: `子任务 ${id} 当前没有可延期的执行中尝试`,
|
|
2265
|
+
hint: '已收束的尝试不能复活:请转新轮续跑或人工裁决(escalate)',
|
|
2266
|
+
}
|
|
1469
2267
|
}
|
|
2268
|
+
const deadlineAt = handle.extend(delta)
|
|
2269
|
+
const row = Array.isArray(record?.statuses)
|
|
2270
|
+
? record.statuses.find((item: any) => item?.subtaskId === id)
|
|
2271
|
+
: null
|
|
2272
|
+
if (row) {
|
|
2273
|
+
// deadlineAt/timeJournal 走未知字段通道直写(applyStatus 白名单属 T3 领地)。
|
|
2274
|
+
row.deadlineAt = deadlineAt
|
|
2275
|
+
const journal = Array.isArray(row.timeJournal) ? row.timeJournal : []
|
|
2276
|
+
journal.push({
|
|
2277
|
+
at: Date.now(),
|
|
2278
|
+
action: 'extend',
|
|
2279
|
+
extendMs: delta,
|
|
2280
|
+
by: ['agent', 'child', 'system'].includes(meta?.by) ? meta.by : 'agent',
|
|
2281
|
+
reason: truncate(String(meta?.reason ?? ''), 300),
|
|
2282
|
+
})
|
|
2283
|
+
row.timeJournal = journal.slice(-20)
|
|
2284
|
+
}
|
|
2285
|
+
record.updatedAt = Date.now()
|
|
2286
|
+
return { ok: true, deadlineAt, timerRearmed: true, watchdogRearmed: Boolean(handle.watchdog) }
|
|
1470
2287
|
}
|
|
1471
2288
|
|
|
1472
2289
|
/*
|
|
@@ -1508,14 +2325,45 @@ async function runSubtaskAttempt(
|
|
|
1508
2325
|
*/
|
|
1509
2326
|
let ceilingFingerprint: any[] = []
|
|
1510
2327
|
const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
|
|
2328
|
+
/*
|
|
2329
|
+
* [2.2.0][T4/O-3b][O-4d] 可延期计时句柄(D 项延期接口的运行时锚点,方案 §2.2/§2.5)。
|
|
2330
|
+
* 本次尝试的协商截止只属于这次尝试:extend() 重置一次性计时器并同步 watchdog
|
|
2331
|
+
* (rearmApproachingDeadline 传「自尝试起点计的新完整窗口」);settled 后不得
|
|
2332
|
+
* 复活(extendDeadline 一律 NO_ACTIVE_ATTEMPT)。行上 deadlineAt 由 executeSubtask
|
|
2333
|
+
* 以同一时钟读数写入(C3 契约),句柄权威值随写同步。
|
|
2334
|
+
*/
|
|
2335
|
+
const attemptStart = Date.now()
|
|
2336
|
+
const attemptHandle = {
|
|
2337
|
+
subtaskId: String(subtask.id),
|
|
2338
|
+
startedAt: attemptStart,
|
|
2339
|
+
deadlineAt: attemptStart + timeoutMs,
|
|
2340
|
+
settled: false,
|
|
2341
|
+
watchdog: null as any,
|
|
2342
|
+
arm: (_ms: number) => {},
|
|
2343
|
+
extend(ms: number) {
|
|
2344
|
+
if (this.settled) return this.deadlineAt
|
|
2345
|
+
this.deadlineAt += ms
|
|
2346
|
+
this.arm(this.deadlineAt - Date.now())
|
|
2347
|
+
this.watchdog?.rearmApproachingDeadline(this.deadlineAt - this.startedAt)
|
|
2348
|
+
return this.deadlineAt
|
|
2349
|
+
},
|
|
2350
|
+
attachWatchdog(watchdog: any) {
|
|
2351
|
+
this.watchdog = watchdog
|
|
2352
|
+
},
|
|
2353
|
+
}
|
|
2354
|
+
record.attemptHandles = { ...(record.attemptHandles ?? {}), [String(subtask.id)]: attemptHandle }
|
|
1511
2355
|
const deadlinePromise = new Promise<void>((resolve) => {
|
|
1512
|
-
|
|
2356
|
+
const fire = () => {
|
|
1513
2357
|
ceilingFired = true
|
|
1514
2358
|
guard.timedOut = true
|
|
1515
|
-
|
|
1516
|
-
//
|
|
1517
|
-
//
|
|
1518
|
-
|
|
2359
|
+
attemptHandle.settled = true
|
|
2360
|
+
// [2.2.0][T4/O-3b][O-4d] L4 安全兜底结算+「待裁决」标记(E4 契约):时间是
|
|
2361
|
+
// 协商出来的安全兜底,不是固定交付期限——到点不表述为「强制结束」式固定期限
|
|
2362
|
+
// 误杀,而是安全兜底结算落盘,供主 Agent 决定延期 / 重试 / 接受(或转新轮
|
|
2363
|
+
// 续跑、人工裁决)。Reached only when the child ignored both its idle window
|
|
2364
|
+
// and its abort signal; the message says so, otherwise the cause looks like
|
|
2365
|
+
// a plain "too slow" and the next investigation goes down the wrong path.
|
|
2366
|
+
const message = `子任务 ${subtask.id} 达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:请主 Agent 决定延期 / 重试 / 接受,或转新轮续跑、人工裁决)`
|
|
1519
2367
|
try {
|
|
1520
2368
|
// [1.8.19] Keep the evidence of what already landed on disk.
|
|
1521
2369
|
const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
|
|
@@ -1539,6 +2387,13 @@ async function runSubtaskAttempt(
|
|
|
1539
2387
|
record.statuses = applyStatus(record.statuses, subtask.id, patch)
|
|
1540
2388
|
record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
|
|
1541
2389
|
}
|
|
2390
|
+
/*
|
|
2391
|
+
* [2.2.0][T4/O-3b][C/E] 「待裁决」结构化标记(E4 契约):结算文案已含
|
|
2392
|
+
* 「待裁决」,这里再落机器可读标记供裁决/回放白名单透传(pendingAdjudication)。
|
|
2393
|
+
* 走 StatusEntry 未知字段通道直写(applyStatus 白名单属 T3 领地)。
|
|
2394
|
+
*/
|
|
2395
|
+
const settleRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
|
|
2396
|
+
if (settleRow) settleRow.pendingAdjudication = true
|
|
1542
2397
|
record.updatedAt = Date.now()
|
|
1543
2398
|
} catch (error: any) {
|
|
1544
2399
|
record.errors = [
|
|
@@ -1552,8 +2407,16 @@ async function runSubtaskAttempt(
|
|
|
1552
2407
|
child.disposeListener()
|
|
1553
2408
|
resolve()
|
|
1554
2409
|
}
|
|
1555
|
-
}
|
|
1556
|
-
|
|
2410
|
+
}
|
|
2411
|
+
// [2.2.0][T4/O-3b][O-4d] 可延期计时(D 项):arm() 重置一次性计时器,extend()
|
|
2412
|
+
// 经 attemptHandle 调用它把截止点推移到新协商截止;原截止点不再触发。
|
|
2413
|
+
const arm = (ms: number) => {
|
|
2414
|
+
if (timer) clearTimeout(timer)
|
|
2415
|
+
timer = setTimeout(fire, Math.max(1, ms))
|
|
2416
|
+
timer.unref?.()
|
|
2417
|
+
}
|
|
2418
|
+
attemptHandle.arm = arm
|
|
2419
|
+
arm(timeoutMs)
|
|
1557
2420
|
})
|
|
1558
2421
|
try {
|
|
1559
2422
|
// [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
|
|
@@ -1563,11 +2426,18 @@ async function runSubtaskAttempt(
|
|
|
1563
2426
|
...options,
|
|
1564
2427
|
child,
|
|
1565
2428
|
guard,
|
|
2429
|
+
// [2.2.0][T4/O-3b] 本次尝试的协商执行时限与计时句柄(deadlineAt 写入同源、
|
|
2430
|
+
// 看门狗 hardMs 同值、延期接口锚点)。
|
|
2431
|
+
attemptTimeoutMs: timeoutMs,
|
|
2432
|
+
attemptHandle,
|
|
1566
2433
|
}),
|
|
1567
2434
|
deadlinePromise,
|
|
1568
2435
|
])
|
|
1569
2436
|
return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint }
|
|
1570
2437
|
} finally {
|
|
2438
|
+
// [2.2.0][T4/O-3b] 收束即注销句柄:已收束的尝试不得再被 extendDeadline 复活。
|
|
2439
|
+
attemptHandle.settled = true
|
|
2440
|
+
if (record.attemptHandles) delete record.attemptHandles[String(subtask.id)]
|
|
1571
2441
|
if (timer) {
|
|
1572
2442
|
clearTimeout(timer)
|
|
1573
2443
|
timer = null
|
|
@@ -1592,7 +2462,10 @@ async function runSubtaskAttempt(
|
|
|
1592
2462
|
* skipped and the row is marked `artifactConflict` instead of overwriting it.
|
|
1593
2463
|
*/
|
|
1594
2464
|
async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
|
|
1595
|
-
|
|
2465
|
+
// [2.2.0][T4/O-3b] 本次执行时限=柔性时长协商消费序(见 resolveSubtaskTimeoutMs):
|
|
2466
|
+
// ① subtask.timeoutMs 显式值 → ② deriveSubtaskTimeoutMs(estimateMinutes) 派生 →
|
|
2467
|
+
// ③ 缺省回落 CHILD_TIMEOUT_MS;显式注入的 childTimeoutMs 作兜底上限取 min。
|
|
2468
|
+
const childTimeoutMs = resolveSubtaskTimeoutMs(subtask, options.childTimeoutMs)
|
|
1596
2469
|
const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs)
|
|
1597
2470
|
if (!first.ceilingFired) return first.outcome
|
|
1598
2471
|
|
|
@@ -1600,7 +2473,7 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
|
|
|
1600
2473
|
const now = Date.now()
|
|
1601
2474
|
const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs
|
|
1602
2475
|
const remaining = deadline - now
|
|
1603
|
-
const message = `子任务 ${subtask.id}
|
|
2476
|
+
const message = `子任务 ${subtask.id} 达到协商执行上限(${childTimeoutMs}ms)`
|
|
1604
2477
|
/*
|
|
1605
2478
|
* [1.8.6] A parent abort outranks a retry: the round is being stopped on
|
|
1606
2479
|
* purpose, and a second child would only be aborted on arrival.
|
|
@@ -1654,7 +2527,7 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
|
|
|
1654
2527
|
const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
|
|
1655
2528
|
...options,
|
|
1656
2529
|
attemptOffset: 2,
|
|
1657
|
-
priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message}
|
|
2530
|
+
priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已按安全兜底结算(待裁决)` },
|
|
1658
2531
|
}, retryTimeoutMs)
|
|
1659
2532
|
return second.outcome
|
|
1660
2533
|
}
|
|
@@ -1739,6 +2612,29 @@ export function modelStatusLines(statuses: any) {
|
|
|
1739
2612
|
status: handoff.status,
|
|
1740
2613
|
})),
|
|
1741
2614
|
reportedAt: item.reportedAt ?? null,
|
|
2615
|
+
/*
|
|
2616
|
+
* [2.2.0][T4/O-3b][O-2.4] 柔性时长协商字段进入模型可读面(纯展示):
|
|
2617
|
+
* 协商截止 deadlineAt、尝试起点 startedAt、剩余协商时间、预警标记 timeWarning、
|
|
2618
|
+
* 待裁决标记 pendingAdjudication 与时间链审计 timeJournal。验收合同
|
|
2619
|
+
* tests/time-estimate-negotiation.test.ts C3 直接从 statusTool 输出读
|
|
2620
|
+
* deadlineAt/startedAt(字段名/单位照合同原文)。
|
|
2621
|
+
*/
|
|
2622
|
+
startedAt: item.startedAt ?? null,
|
|
2623
|
+
deadlineAt: item.deadlineAt ?? null,
|
|
2624
|
+
deadlineRemainingMs: Number.isFinite(Number(item.deadlineAt))
|
|
2625
|
+
? Math.max(0, Number(item.deadlineAt) - Date.now())
|
|
2626
|
+
: null,
|
|
2627
|
+
timeWarning: item.timeWarning ?? null,
|
|
2628
|
+
timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
|
|
2629
|
+
pendingAdjudication: item.pendingAdjudication === true,
|
|
2630
|
+
/*
|
|
2631
|
+
* [2.2.0][T3/O-2a] 子→主预告通道的结论必须进入模型可读面。
|
|
2632
|
+
*
|
|
2633
|
+
* 这条能力的目标就是「可观测」:主 Agent 要能一眼看出该子任务的开工预告
|
|
2634
|
+
* 有没有真的到达(observed/not-observed)、目标是谁、什么时候、失败原因。
|
|
2635
|
+
* 只写状态行不让读,等于又是一个「看不见的失败」。
|
|
2636
|
+
*/
|
|
2637
|
+
noticeChannel: item.noticeChannel ?? null,
|
|
1742
2638
|
}))
|
|
1743
2639
|
}
|
|
1744
2640
|
|
|
@@ -1805,7 +2701,18 @@ function describePendingCause(plan: any, statuses: any[], id: string): string {
|
|
|
1805
2701
|
|
|
1806
2702
|
export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
1807
2703
|
const { agent, signal, modelSelection, cwd, conversationContext = '' } = options
|
|
1808
|
-
const
|
|
2704
|
+
const roundBudgetMs = Number(options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS)
|
|
2705
|
+
const deadline = Date.now() + (roundBudgetMs > 0 ? roundBudgetMs : NO_ROUND_BUDGET_MS)
|
|
2706
|
+
/*
|
|
2707
|
+
* [2.2.0][T3/O-2a] 本轮子→主预告通道的目标会话 id,一轮只解析一次。
|
|
2708
|
+
*
|
|
2709
|
+
* 宿主只在**非 caller** 投递时把父会话 id 追加进子提示词
|
|
2710
|
+
* (dsh-subagent/lib/index.js:1466),本插件用 `delivery: 'caller'` 派发,
|
|
2711
|
+
* 所以必须自己注入。解析优先级见 notice-channel.ts(agent.id → session.id),
|
|
2712
|
+
* 两级都拿不到就留空,提示词改走「禁止猜测」分支([2.2.1][T5][F4] 不再用
|
|
2713
|
+
* plan.sessionId 兜底:计划正文可能属于另一个 root 会话)。
|
|
2714
|
+
*/
|
|
2715
|
+
const leadNotice = resolveLeadAgentId({ agent, session: options.session })
|
|
1809
2716
|
/*
|
|
1810
2717
|
* Resume, do not restart.
|
|
1811
2718
|
*
|
|
@@ -1880,7 +2787,9 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
1880
2787
|
else parentSignal.addEventListener('abort', onAbort, { once: true })
|
|
1881
2788
|
const totalTimer = setTimeout(() => {
|
|
1882
2789
|
childController.abort(new PlanError('总执行超时', 'TOTAL_TIMEOUT'))
|
|
1883
|
-
|
|
2790
|
+
// [2.2.5][热修] 双重保险:即使哨兵值/配置未来被改成超限值,也把延时钳在
|
|
2791
|
+
// Node setTimeout 上限之内,杜绝“1ms 触发”的整轮秒杀。
|
|
2792
|
+
}, Math.min(Math.max(1000, deadline - Date.now()), ROUND_TIMER_MAX_MS))
|
|
1884
2793
|
totalTimer.unref?.()
|
|
1885
2794
|
record.dispatchedAt = Date.now()
|
|
1886
2795
|
record.phase = 'executing'
|
|
@@ -1966,6 +2875,15 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
1966
2875
|
// [1.10.6] Injectable stat for the pre-retry fingerprint check; tests
|
|
1967
2876
|
// use it so the conflict branch is provable without real files.
|
|
1968
2877
|
artifactStat: options.artifactStat,
|
|
2878
|
+
// [2.2.0][T6/O-1a] 即时通知接线:后台轮次标记、主会话与完成回调透传到结算点。
|
|
2879
|
+
notifyCompletion: options.notifyCompletion === true,
|
|
2880
|
+
session: options.session,
|
|
2881
|
+
// [2.2.0][T3/O-2a] 子→主预告通道:目标 id 与其来源随派发一起下传,
|
|
2882
|
+
// 提示词注入与结算观测必须用同一个值(否则「注入了什么」与
|
|
2883
|
+
// 「观测的是谁」会分叉,通道永远对不上)。
|
|
2884
|
+
leadAgentId: leadNotice.id,
|
|
2885
|
+
leadAgentIdSource: leadNotice.source,
|
|
2886
|
+
onSubtaskDone: options.onSubtaskDone,
|
|
1969
2887
|
})
|
|
1970
2888
|
// [1.8.6] Remember which failures were interrupts, so the cascade below
|
|
1971
2889
|
// can leave their dependents pending instead of blaming them.
|
|
@@ -2097,12 +3015,14 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
2097
3015
|
* 会让卡片显示「预算用完、可续跑」,而真正该做的是 instruct。
|
|
2098
3016
|
*/
|
|
2099
3017
|
record.phase = allDoneNow ? 'done' : (blockedNow > 0 ? 'blocked' : 'paused')
|
|
2100
|
-
const
|
|
3018
|
+
const roundBudgetMs = Number(options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS)
|
|
3019
|
+
const minutes = roundBudgetMs > 0 ? Math.max(1, Math.round(roundBudgetMs / 60000)) : 0
|
|
3020
|
+
const roundLabel = minutes > 0 ? `本轮执行预算(${minutes} 分钟)` : '本轮无固定总预算'
|
|
2101
3021
|
record.error = allDoneNow
|
|
2102
3022
|
? null
|
|
2103
3023
|
: blockedNow > 0
|
|
2104
|
-
?
|
|
2105
|
-
:
|
|
3024
|
+
? `${roundLabel}已到:已完成 ${done}/${total};${blockedNow} 项在等待指示或已受阻(续跑不会重派,请先 instruct 或改判),${pendingNow} 项保留为未完成,再次派发本计划即可继续`
|
|
3025
|
+
: `${roundLabel}已到:已完成 ${done}/${total},其余 ${total - done} 项保留为未完成,再次派发本计划即可续跑(已完成的不重跑)`
|
|
2106
3026
|
/*
|
|
2107
3027
|
* Drop the failure lines the aborted children wrote on their way out.
|
|
2108
3028
|
* They used to survive into the result payload as
|
|
@@ -2618,6 +3538,34 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
2618
3538
|
const snap = snapshots.get(result.planId)
|
|
2619
3539
|
if (snap) {
|
|
2620
3540
|
snap.statuses = applyResultStatuses(snap.statuses, result)
|
|
3541
|
+
/*
|
|
3542
|
+
* [2.2.0][T4/O-3b][E] 重建白名单(E 项,runtime 侧):applyResultStatuses
|
|
3543
|
+
* (src/plan.ts,T3 领地)逐字段重建不含柔性时长协商新字段,会把
|
|
3544
|
+
* deadlineAt/timeNotice/timeWarning/timeJournal/待裁决标记洗掉;结果消息
|
|
3545
|
+
* 整包透传行对象(字段在 entry 上),按 T3b plan.ts:2966-2971 同名修复
|
|
3546
|
+
* 口径补直写回放。
|
|
3547
|
+
*/
|
|
3548
|
+
for (const entry of (Array.isArray(result.statuses) ? result.statuses : [])) {
|
|
3549
|
+
const rebuiltRow = snap.statuses.find((item: any) => item?.subtaskId === entry?.subtaskId)
|
|
3550
|
+
if (!rebuiltRow || !isRecord(entry)) continue
|
|
3551
|
+
for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
|
|
3552
|
+
if (entry[field] !== undefined) rebuiltRow[field] = entry[field]
|
|
3553
|
+
}
|
|
3554
|
+
/*
|
|
3555
|
+
* [2.2.0][T3/O-2a][F1] 通道结论也必须活过进程重启。
|
|
3556
|
+
* applyResultStatuses 已带该字段;这里再走一次校验,防止旧日志/
|
|
3557
|
+
* 未来字段来源把脏值直接拷进重建行(fail-closed)。
|
|
3558
|
+
*
|
|
3559
|
+
* [2.2.1][T5][F1] 非法值必须 `delete` 而不是写 `null`:写 null 会让
|
|
3560
|
+
* 脏字段跨每次重启自我延续(下一次回放又把整行丢掉,done 行永远显示
|
|
3561
|
+
* pending)。删除等价于「该结果消息没带这个字段」,合法值不受影响。
|
|
3562
|
+
*/
|
|
3563
|
+
if (entry.noticeChannel !== undefined) {
|
|
3564
|
+
const checked = validateNoticeChannel(entry.noticeChannel)
|
|
3565
|
+
if (checked.ok) rebuiltRow.noticeChannel = checked.value
|
|
3566
|
+
else delete rebuiltRow.noticeChannel
|
|
3567
|
+
}
|
|
3568
|
+
}
|
|
2621
3569
|
// Resume bookkeeping must survive a page refresh, otherwise the budget
|
|
2622
3570
|
// silently resets and a never-succeeding subtask can loop forever.
|
|
2623
3571
|
snap.resumeCount = Number(result.resumeCount ?? snap.resumeCount) || 0
|
|
@@ -2659,6 +3607,18 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
2659
3607
|
* INVALID_TRANSITION(wp-79c31abf 的 H1 就是这样被丢掉的)。
|
|
2660
3608
|
*/
|
|
2661
3609
|
status: update.handoffs === undefined ? update.status : undefined,
|
|
3610
|
+
/*
|
|
3611
|
+
* [2.2.6][D-1] 人工改判的 closure 必须随 patch 回放。
|
|
3612
|
+
*
|
|
3613
|
+
* durable 的 workplan-update 自 1.11.0 起携带 closure
|
|
3614
|
+
* (buildUpdateMessage),但这里的 patch 一直没把它传给
|
|
3615
|
+
* applyStatus:行停在 escalated 时,status=done 的改判会因
|
|
3616
|
+
* 「非法闭环迁移 escalated→done / closure=escalated 必须同时
|
|
3617
|
+
* status=blocked」被拒,整条 update 被下面的裸 catch 吞掉,
|
|
3618
|
+
* 重启后「待指示」行永久卡死(2026-11-08 wp-3c8c84b2 T2 实证,
|
|
3619
|
+
* 见 artifacts/2.2.5-post-restart-regression.md §4 D-1)。
|
|
3620
|
+
*/
|
|
3621
|
+
closure: typeof update.closure === 'string' ? update.closure : undefined,
|
|
2662
3622
|
progress: typeof update.progress === 'number' ? update.progress : undefined,
|
|
2663
3623
|
summary: typeof update.note === 'string' ? update.note : undefined,
|
|
2664
3624
|
// [1.8.13] Evidence written through the update tool must survive replay.
|
|
@@ -2668,14 +3628,56 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
2668
3628
|
missingArtifacts: update.missingArtifacts,
|
|
2669
3629
|
handoffs: update.handoffs,
|
|
2670
3630
|
revision: Number.isInteger(update.revision) ? update.revision : undefined,
|
|
3631
|
+
// [2.2.0][T4/O-3b][E] 回放白名单(T3b TODO#2):O-3b/O-2c 留档字段随
|
|
3632
|
+
// update 记录回放;timeoutMs 有 applyStatus 分支,走 patch 即可。
|
|
3633
|
+
timeoutMs: update.timeoutMs,
|
|
2671
3634
|
updatedBy: 'agent',
|
|
2672
3635
|
})
|
|
3636
|
+
/*
|
|
3637
|
+
* [2.2.0][T4/O-3b][E] 柔性时长协商新字段回放(E 项,runtime.ts 2931 一带)。
|
|
3638
|
+
*
|
|
3639
|
+
* deadlineAt/timeNotice/timeWarning/timeJournal/待裁决标记在 applyStatus
|
|
3640
|
+
* (src/plan.ts,T3 领地)无路由分支,走 patch 会被静默丢弃;按 T3b
|
|
3641
|
+
* plan.ts:2966-2971 同名修复口径在此直写重建行。extendMs 走累加语义
|
|
3642
|
+
* (与线上 extendDeadline 一致:deadlineAt += extendMs 并追加 timeJournal),
|
|
3643
|
+
* 仅当记录未自带 timeJournal 时合成,避免同一条 journal 被回放两次。
|
|
3644
|
+
*/
|
|
3645
|
+
const replayRow = snap.statuses.find((item: any) => item?.subtaskId === update.subtaskId)
|
|
3646
|
+
if (replayRow) {
|
|
3647
|
+
for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
|
|
3648
|
+
if (update[field] !== undefined) replayRow[field] = update[field]
|
|
3649
|
+
}
|
|
3650
|
+
const replayExtend = Number(update.extendMs)
|
|
3651
|
+
if (update.timeJournal === undefined && Number.isFinite(replayExtend) && replayExtend > 0
|
|
3652
|
+
&& Number.isFinite(Number(replayRow.deadlineAt))) {
|
|
3653
|
+
replayRow.deadlineAt = Number(replayRow.deadlineAt) + Math.floor(replayExtend)
|
|
3654
|
+
replayRow.timeJournal = [
|
|
3655
|
+
...(Array.isArray(replayRow.timeJournal) ? replayRow.timeJournal : []),
|
|
3656
|
+
{
|
|
3657
|
+
at: Date.now(),
|
|
3658
|
+
action: 'extend',
|
|
3659
|
+
extendMs: Math.floor(replayExtend),
|
|
3660
|
+
by: 'agent',
|
|
3661
|
+
reason: truncate(String(update.reason ?? ''), 300),
|
|
3662
|
+
},
|
|
3663
|
+
].slice(-20)
|
|
3664
|
+
}
|
|
3665
|
+
}
|
|
2673
3666
|
appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
|
|
2674
3667
|
seq: Number(event.seq ?? 0),
|
|
2675
3668
|
status: String(update.status ?? ''),
|
|
2676
3669
|
})
|
|
2677
|
-
} catch {
|
|
2678
|
-
|
|
3670
|
+
} catch (error) {
|
|
3671
|
+
/*
|
|
3672
|
+
* [2.2.6][D-1] fail-closed 而非 fail-silent:历史 update 不合法时
|
|
3673
|
+
* 至少留一条日志,否则「改判丢失」永远无从发现(本缺陷因此潜伏
|
|
3674
|
+
* 自 1.7.0)。回放继续,不让单条坏记录拖垮整个重建。
|
|
3675
|
+
*/
|
|
3676
|
+
console.warn(
|
|
3677
|
+
'[dsh-workplan] 回放忽略一条不合法的历史改判:'
|
|
3678
|
+
+ `${String(update?.planId ?? '')}/${String(update?.subtaskId ?? '')}:`
|
|
3679
|
+
+ `${error instanceof Error ? error.message : String(error)}`,
|
|
3680
|
+
)
|
|
2679
3681
|
}
|
|
2680
3682
|
}
|
|
2681
3683
|
}
|
|
@@ -2946,11 +3948,18 @@ function respondJson(res: any, status: any, payload: any) {
|
|
|
2946
3948
|
export type WorkplanRuntimeOptions = {
|
|
2947
3949
|
cwd?: string
|
|
2948
3950
|
/**
|
|
2949
|
-
* [2.1.3]
|
|
3951
|
+
* [2.1.3][2.1.6] 单次规划器调用的**无进展**窗口(毫秒)。来自
|
|
2950
3952
|
* `DSH_WORKPLAN_PLANNER_TIMEOUT_MS` 或显式配置;缺省回落到
|
|
2951
|
-
* `PLANNER_TIMEOUT_MS
|
|
3953
|
+
* `PLANNER_TIMEOUT_MS`。2.1.6 起它从固定墙钟改为「自上一个输出块起算」,
|
|
3954
|
+
* 持续产出的调用不会在第 300 秒被掐断。
|
|
2952
3955
|
*/
|
|
2953
3956
|
plannerTimeoutMs?: number
|
|
3957
|
+
/**
|
|
3958
|
+
* [2.1.6] 首个输出块之后的完全静默窗口(毫秒),来自
|
|
3959
|
+
* `DSH_WORKPLAN_PLANNER_IDLE_TIMEOUT_MS`;缺省 `PLANNER_IDLE_TIMEOUT_MS`。
|
|
3960
|
+
* 不小于 `plannerTimeoutMs` 时等于关闭。
|
|
3961
|
+
*/
|
|
3962
|
+
plannerIdleTimeoutMs?: number
|
|
2954
3963
|
/** Absolute ceiling per child execution, clamped by `normaliseChildTimeout`. */
|
|
2955
3964
|
childTimeoutMs?: number
|
|
2956
3965
|
/** No-progress window per child execution, clamped by `normaliseIdleTimeout`. */
|
|
@@ -3093,10 +4102,20 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3093
4102
|
}
|
|
3094
4103
|
}
|
|
3095
4104
|
const limits = {
|
|
4105
|
+
/*
|
|
4106
|
+
* [2.1.6] 规划器的两扇窗此前不在 limits 里:`options.limits.plannerTimeoutMs`
|
|
4107
|
+
* 永远是 undefined,调用处只能靠兜底常量,状态/诊断也因此读不到「当前生效
|
|
4108
|
+
* 的规划器时限」。补齐后配置 → limits → 单次调用是同一条链路。
|
|
4109
|
+
*/
|
|
4110
|
+
plannerTimeoutMs: normalisePlannerWindow(options.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
|
|
4111
|
+
plannerIdleTimeoutMs: normalisePlannerWindow(options.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
|
|
3096
4112
|
childTimeoutMs: normaliseChildTimeout(options.childTimeoutMs),
|
|
3097
4113
|
idleTimeoutMs: normaliseIdleTimeout(options.idleTimeoutMs),
|
|
3098
|
-
|
|
3099
|
-
|
|
4114
|
+
// [2.2.5] 0 = 不设整轮硬预算;正数才启用(最小 60s)。未配置按 0。
|
|
4115
|
+
totalTimeoutMs: Number.isFinite(Number(options.totalTimeoutMs)) && Number(options.totalTimeoutMs) >= 0
|
|
4116
|
+
? (Number(options.totalTimeoutMs) === 0
|
|
4117
|
+
? 0
|
|
4118
|
+
: Math.max(60000, Math.floor(Number(options.totalTimeoutMs))))
|
|
3100
4119
|
: TOTAL_TIMEOUT_MS,
|
|
3101
4120
|
maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
|
|
3102
4121
|
? Math.min(5, Math.floor(Number(options.maxResumes)))
|
|
@@ -3128,12 +4147,17 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3128
4147
|
modelSelection: record.modelSelection,
|
|
3129
4148
|
cwd: session.header?.cwd ?? options.cwd,
|
|
3130
4149
|
conversationContext: record.conversationContext ?? '',
|
|
4150
|
+
// [2.2.0][T6/O-1a] 自动派发是后台轮次:结算成功即推送完成即时通知。
|
|
4151
|
+
notifyCompletion: true,
|
|
4152
|
+
onSubtaskDone: (recordArg: any, subtask: any, verdict: any) =>
|
|
4153
|
+
emitSubtaskDoneNotice(recordArg, session, subtask, verdict),
|
|
3131
4154
|
}
|
|
3132
4155
|
record.dispatchStartedAt = Date.now()
|
|
3133
4156
|
record.dispatchPromise = dispatchPlan(ctx, record, {
|
|
3134
4157
|
...roundOptions,
|
|
3135
4158
|
signal: controller.signal,
|
|
3136
|
-
|
|
4159
|
+
// [2.2.0][T4/O-3b] 传原始配置值:未配置=undefined 时协商派生生效,显式配置=兜底上限(resolveSubtaskTimeoutMs)。
|
|
4160
|
+
childTimeoutMs: options.childTimeoutMs,
|
|
3137
4161
|
idleTimeoutMs: limits.idleTimeoutMs,
|
|
3138
4162
|
totalTimeoutMs: limits.totalTimeoutMs,
|
|
3139
4163
|
maxResumes: limits.maxResumes,
|
|
@@ -3247,6 +4271,86 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3247
4271
|
return rebuilt
|
|
3248
4272
|
}
|
|
3249
4273
|
|
|
4274
|
+
/*
|
|
4275
|
+
* [2.2.0][T5/O-4c/O-4d] 延期预算(防滥用,方案 §5.4 #1/#2;数值只引方案原文)。
|
|
4276
|
+
*
|
|
4277
|
+
* 初始协商上限的解析完全复用 T4 的 resolveSubtaskTimeoutMs(显式
|
|
4278
|
+
* subtask.timeoutMs → deriveSubtaskTimeoutMs(estimateMinutes) → 回落
|
|
4279
|
+
* CHILD_TIMEOUT_MS)。方案没有给出 MAX_EXTEND_MS 的具体数值,因此**不自拟
|
|
4280
|
+
* 常量**:单次延期上限派生为「剩余延期预算」=初始协商上限 × 1 − 已累计延期
|
|
4281
|
+
* (timeJournal 中 action:'extend' 之和)。累计超限即拒绝并转「请主 Agent
|
|
4282
|
+
* 裁决」(EXTEND_BUDGET_EXHAUSTED),放宽永远有界。
|
|
4283
|
+
*
|
|
4284
|
+
* 为什么初始上限不传 options.childTimeoutMs:显式注入的 childTimeoutMs 是
|
|
4285
|
+
* 运维兜底上限(见 resolveSubtaskTimeoutMs 注释),不是本子任务的协商上限;
|
|
4286
|
+
* 延期预算按方案 §2.2 的口径取计划层解析值。验收合同也用同一口径(D4 用
|
|
4287
|
+
* 显式 timeoutMs 定 2000ms;D2 用例在 1200ms 小窗上放宽 1500ms 是合法的)。
|
|
4288
|
+
*/
|
|
4289
|
+
function extendBudgetOf(record: any, subtaskId: string) {
|
|
4290
|
+
const entry = flattenSubtasks(record?.plan ?? { stages: [] })
|
|
4291
|
+
.find((candidate: any) => candidate?.subtask?.id === subtaskId)
|
|
4292
|
+
const initialMs = resolveSubtaskTimeoutMs(entry?.subtask, undefined)
|
|
4293
|
+
const row = Array.isArray(record?.statuses)
|
|
4294
|
+
? record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
4295
|
+
: null
|
|
4296
|
+
const usedMs = (Array.isArray(row?.timeJournal) ? row.timeJournal : [])
|
|
4297
|
+
.filter((item: any) => item?.action === 'extend')
|
|
4298
|
+
.reduce((sum: number, item: any) => {
|
|
4299
|
+
const value = Number(item?.extendMs)
|
|
4300
|
+
return Number.isFinite(value) && value > 0 ? sum + Math.floor(value) : sum
|
|
4301
|
+
}, 0)
|
|
4302
|
+
// 方案 §5.4 #2:累计 extendMs ≤ 初始协商上限 × 1(最多再给一倍)。
|
|
4303
|
+
const capMs = initialMs
|
|
4304
|
+
return { initialMs, capMs, usedMs, remainingMs: Math.max(0, capMs - usedMs) }
|
|
4305
|
+
}
|
|
4306
|
+
|
|
4307
|
+
/*
|
|
4308
|
+
* [2.2.0][T5/O-4c] timeNotice 的形状校验(方案 §2.4:{declaredMinutes, reason})。
|
|
4309
|
+
* 只记录、不改判定;非法值返回可读错误而不是抛裸错(与 STALE_WRITE 同风格)。
|
|
4310
|
+
*/
|
|
4311
|
+
function validateTimeNotice(notice: any) {
|
|
4312
|
+
const declared = Number(notice?.declaredMinutes)
|
|
4313
|
+
if (!Number.isFinite(declared) || declared <= 0) {
|
|
4314
|
+
return {
|
|
4315
|
+
code: 'INVALID_TIME_NOTICE',
|
|
4316
|
+
error: `timeNotice.declaredMinutes 必须是正数分钟:${String(notice?.declaredMinutes)}`,
|
|
4317
|
+
hint: '预告只做记录(仅供参考、非承诺):请传正数分钟与可选 reason。',
|
|
4318
|
+
}
|
|
4319
|
+
}
|
|
4320
|
+
return null
|
|
4321
|
+
}
|
|
4322
|
+
|
|
4323
|
+
/*
|
|
4324
|
+
* [2.2.0][T5/O-4c] 写入专家开工预告(O-2a):状态行 timeNotice + timeJournal
|
|
4325
|
+
* 的 action:'estimate' 条目。applyStatus(plan.ts,T3 领地)还没有该字段的
|
|
4326
|
+
* 路由分支,按 T4 直写通道写行(StatusEntry 保留未知字段;回放白名单已透传
|
|
4327
|
+
* timeNotice,刷新后不丢)。
|
|
4328
|
+
*/
|
|
4329
|
+
function recordTimeNotice(record: any, subtaskId: string, notice: any) {
|
|
4330
|
+
const row = Array.isArray(record?.statuses)
|
|
4331
|
+
? record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
4332
|
+
: null
|
|
4333
|
+
if (!row) return
|
|
4334
|
+
const at = Date.now()
|
|
4335
|
+
const reason = truncate(String(notice?.reason ?? ''), 300)
|
|
4336
|
+
row.timeNotice = {
|
|
4337
|
+
declaredMinutes: Number(notice?.declaredMinutes),
|
|
4338
|
+
at,
|
|
4339
|
+
channel: 'agent',
|
|
4340
|
+
reason,
|
|
4341
|
+
}
|
|
4342
|
+
const journal = Array.isArray(row.timeJournal) ? row.timeJournal : []
|
|
4343
|
+
journal.push({
|
|
4344
|
+
at,
|
|
4345
|
+
action: 'estimate',
|
|
4346
|
+
declaredMinutes: Number(notice?.declaredMinutes),
|
|
4347
|
+
by: 'agent',
|
|
4348
|
+
reason,
|
|
4349
|
+
})
|
|
4350
|
+
row.timeJournal = journal.slice(-20)
|
|
4351
|
+
record.updatedAt = at
|
|
4352
|
+
}
|
|
4353
|
+
|
|
3250
4354
|
async function updateStatus(agent: any, args: any): Promise<any> {
|
|
3251
4355
|
const session = agent?.session
|
|
3252
4356
|
if (!session) throw new PlanError('只能在会话内更新计划', 'NO_SESSION')
|
|
@@ -3255,20 +4359,88 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3255
4359
|
if (!record?.plan) record = reconstructFromSession(session, args?.planId)
|
|
3256
4360
|
record = adoptRequestedPlan(session, record, args?.planId)
|
|
3257
4361
|
if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
|
|
3258
|
-
// [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
|
|
3259
|
-
clearAutoResumeTimer(record, 'manual-update')
|
|
3260
4362
|
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : ''
|
|
3261
4363
|
if (!subtaskId) throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK')
|
|
3262
4364
|
const status = typeof args?.status === 'string' ? args.status : ''
|
|
3263
|
-
|
|
3264
|
-
|
|
4365
|
+
/*
|
|
4366
|
+
* [2.2.0][T5/O-4c] 延期事务的入口判定(D2/D3/D4,方案 §2.2):
|
|
4367
|
+
* extendMs / timeNotice 属于「只改时限、只做记录」的字段,不改状态判定,
|
|
4368
|
+
* 因此允许不带 status 单独提交;运行中也不需要 force——TASK_RUNNING 的
|
|
4369
|
+
* 唯一豁免来自「不改判定」这一事实,而不是特权。
|
|
4370
|
+
*/
|
|
4371
|
+
const extendMsArg = args?.extendMs
|
|
4372
|
+
const hasExtend = extendMsArg !== undefined && extendMsArg !== null
|
|
4373
|
+
const timeNoticeArg = args?.timeNotice
|
|
4374
|
+
const hasTimeNotice = timeNoticeArg !== undefined && timeNoticeArg !== null
|
|
4375
|
+
const statusRequested = ['pending', 'in_progress', 'done', 'blocked'].includes(status)
|
|
4376
|
+
if (!statusRequested && !hasExtend && !hasTimeNotice) {
|
|
4377
|
+
throw new PlanError(
|
|
4378
|
+
'status 必须是 pending / in_progress / done / blocked(仅协商时限时可省略 status,改传 extendMs / timeNotice)',
|
|
4379
|
+
'INVALID_STATUS',
|
|
4380
|
+
)
|
|
4381
|
+
}
|
|
4382
|
+
if (hasExtend && !(typeof extendMsArg === 'number' && Number.isInteger(extendMsArg) && extendMsArg > 0)) {
|
|
4383
|
+
return {
|
|
4384
|
+
ok: false,
|
|
4385
|
+
code: 'INVALID_EXTEND',
|
|
4386
|
+
planId: record.plan.planId,
|
|
4387
|
+
subtaskId,
|
|
4388
|
+
error: `extendMs 必须是正整数毫秒:${String(extendMsArg)}`,
|
|
4389
|
+
hint: '请传入 1 以上的整数毫秒;放宽永远有界(累计 ≤ 初始协商上限 × 1),超出请转新轮续跑或转 escalate 请主 Agent 裁决。',
|
|
4390
|
+
}
|
|
3265
4391
|
}
|
|
4392
|
+
/*
|
|
4393
|
+
* [2.2.0][T5/O-4c] timeNotice 的校验放在入口统一做(所有路径共享):
|
|
4394
|
+
* 非法预告不该因为调用同时带了 status/instruction 就被静默接受。
|
|
4395
|
+
*/
|
|
4396
|
+
if (hasTimeNotice) {
|
|
4397
|
+
const problem = validateTimeNotice(timeNoticeArg)
|
|
4398
|
+
if (problem) {
|
|
4399
|
+
return {
|
|
4400
|
+
ok: false,
|
|
4401
|
+
code: problem.code,
|
|
4402
|
+
planId: record.plan.planId,
|
|
4403
|
+
subtaskId,
|
|
4404
|
+
error: problem.error,
|
|
4405
|
+
hint: problem.hint,
|
|
4406
|
+
}
|
|
4407
|
+
}
|
|
4408
|
+
}
|
|
4409
|
+
/*
|
|
4410
|
+
* [2.2.0][T5/O-4c] 延期事务与状态改判分开提交:方案 §2.2 把 extendMs 定为
|
|
4411
|
+
* 「放宽时间的唯一写路径」,要求原子与可审计;一次调用既改判定又改时限会让
|
|
4412
|
+
* 失败路径出现半写(判定已落、时限未落,或相反)。组合调用显式拒绝,模型分
|
|
4413
|
+
* 两次提交即可(两者都不需要 force)。
|
|
4414
|
+
*/
|
|
4415
|
+
if (hasExtend && statusRequested) {
|
|
4416
|
+
return {
|
|
4417
|
+
ok: false,
|
|
4418
|
+
code: 'EXTEND_REQUIRES_DEDICATED_CALL',
|
|
4419
|
+
planId: record.plan.planId,
|
|
4420
|
+
subtaskId,
|
|
4421
|
+
error: '延期事务必须单独提交:同一次调用不要同时传 status 与 extendMs(放宽是原子、可审计的唯一写路径)',
|
|
4422
|
+
hint: '先单独调用 extendMs 放宽时限,再用另一次调用改判状态。',
|
|
4423
|
+
}
|
|
4424
|
+
}
|
|
4425
|
+
/*
|
|
4426
|
+
* [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
|
|
4427
|
+
* [2.2.0][T5/O-4c] 纯延期/纯预告不改判定,不撤销自动续跑(否则一次失败的
|
|
4428
|
+
* 延期尝试会把已排期的续跑静默取消,计划停在 paused 无人推进)。
|
|
4429
|
+
*/
|
|
4430
|
+
if (statusRequested) clearAutoResumeTimer(record, 'manual-update')
|
|
3266
4431
|
const note = typeof args?.note === 'string' ? args.note : ''
|
|
3267
4432
|
const evidence = Array.isArray(args?.evidence)
|
|
3268
4433
|
? args.evidence.filter((item: any) => typeof item === 'string').join(';')
|
|
3269
4434
|
: ''
|
|
3270
4435
|
const summary = [note, evidence].filter(Boolean).join('|')
|
|
3271
4436
|
const current = record.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
4437
|
+
/*
|
|
4438
|
+
* [2.2.0][T5/O-4c] 纯时限事务(不带 status)不经过 applyStatus,必须自己
|
|
4439
|
+
* 拒绝未知子任务——否则一次对不存在行的 timeNotice 会得到「成功」。
|
|
4440
|
+
*/
|
|
4441
|
+
if (!statusRequested && !current) {
|
|
4442
|
+
throw new PlanError(`未知子任务:${subtaskId}`, 'UNKNOWN_SUBTASK')
|
|
4443
|
+
}
|
|
3272
4444
|
/*
|
|
3273
4445
|
* [1.7.0] Two write guards, both non-throwing.
|
|
3274
4446
|
*
|
|
@@ -3294,7 +4466,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3294
4466
|
}
|
|
3295
4467
|
}
|
|
3296
4468
|
const running = Boolean(record.dispatchPromise)
|
|
3297
|
-
|
|
4469
|
+
/*
|
|
4470
|
+
* [2.2.0][T5/O-4c] TASK_RUNNING 的唯一豁免:只给「不改状态判定」的时限事务。
|
|
4471
|
+
* 纯 extendMs / timeNotice 更新(statusRequested=false)照常放行;只要同一次
|
|
4472
|
+
* 调用还带 status,仍走原守卫——其余状态字段不得被顺手改掉(行为不变)。
|
|
4473
|
+
*/
|
|
4474
|
+
const writeWhileRunning = running && !args?.force && statusRequested
|
|
4475
|
+
&& (current?.status === 'pending' || current?.status === 'in_progress')
|
|
3298
4476
|
if (writeWhileRunning) {
|
|
3299
4477
|
return {
|
|
3300
4478
|
ok: false,
|
|
@@ -3336,11 +4514,17 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3336
4514
|
error: '下发 instruction 时 status 必须是 in_progress(或改用 dsh_workplan_instruct)。',
|
|
3337
4515
|
}
|
|
3338
4516
|
}
|
|
3339
|
-
|
|
4517
|
+
const instructed = await instructSubtask(agent, {
|
|
3340
4518
|
planId: args?.planId,
|
|
3341
4519
|
subtaskId,
|
|
3342
4520
|
instruction,
|
|
3343
4521
|
}, undefined, record)
|
|
4522
|
+
/*
|
|
4523
|
+
* [2.2.0][T5/O-4c] 预告与指示同一次到达时,指示成功落行后再记预告:
|
|
4524
|
+
* 指示失败不该留下一笔「专家已预告」的记录。
|
|
4525
|
+
*/
|
|
4526
|
+
if (hasTimeNotice && instructed?.ok !== false) recordTimeNotice(record, subtaskId, timeNoticeArg)
|
|
4527
|
+
return instructed
|
|
3344
4528
|
}
|
|
3345
4529
|
if (current?.closure === 'escalated') {
|
|
3346
4530
|
if (status === 'done') {
|
|
@@ -3362,6 +4546,89 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3362
4546
|
}
|
|
3363
4547
|
}
|
|
3364
4548
|
}
|
|
4549
|
+
/*
|
|
4550
|
+
* [2.2.0][T5/O-4c] 延期事务(放宽时间的唯一写路径,方案 §2.2;D2/D3 效果 +
|
|
4551
|
+
* §5.4 防滥用):
|
|
4552
|
+
* 1. 预算:初始协商上限取 T4 resolveSubtaskTimeoutMs 的计划层解析值;累计
|
|
4553
|
+
* 放宽(timeJournal 中 action:'extend' 之和)≤ 初始上限 × 1。方案没有给
|
|
4554
|
+
* MAX_EXTEND_MS 数值,单次上限派生为「剩余延期预算」,不自拟常量。
|
|
4555
|
+
* 2. 执行:校验通过才调用 T4 extendDeadline——它负责 deadlineAt += extendMs、
|
|
4556
|
+
* 重置一次性计时器、同步 watchdog,并追加 timeJournal(action:'extend')。
|
|
4557
|
+
* 回放侧(本文件 replay 白名单)的累加语义与此一致:deadlineAt 累加 +
|
|
4558
|
+
* 同形 journal 条目,所以回放代码不需要改。
|
|
4559
|
+
* 3. 纯时限事务不改状态判定:回执只带时限结果与审计字段。
|
|
4560
|
+
*/
|
|
4561
|
+
let extension: any = null
|
|
4562
|
+
if (hasExtend) {
|
|
4563
|
+
const budget = extendBudgetOf(record, subtaskId)
|
|
4564
|
+
if (extendMsArg > budget.remainingMs) {
|
|
4565
|
+
return {
|
|
4566
|
+
ok: false,
|
|
4567
|
+
code: 'EXTEND_BUDGET_EXHAUSTED',
|
|
4568
|
+
planId: record.plan.planId,
|
|
4569
|
+
subtaskId,
|
|
4570
|
+
budget,
|
|
4571
|
+
error: `extendMs ${extendMsArg}ms 超出剩余延期预算 ${budget.remainingMs}ms:`
|
|
4572
|
+
+ `累计延期 ${budget.usedMs}ms,初始协商上限 ${budget.initialMs}ms(上限 × 1 = ${budget.capMs}ms)`,
|
|
4573
|
+
hint: '放宽永远有界:该任务应转入新轮续跑(auto-resume)或转 escalate 请主 Agent/用户裁决。',
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
4576
|
+
const extended = extendDeadline(record, subtaskId, extendMsArg, {
|
|
4577
|
+
by: 'agent',
|
|
4578
|
+
reason: typeof args?.reason === 'string'
|
|
4579
|
+
? args.reason
|
|
4580
|
+
: (typeof args?.note === 'string' ? args.note : ''),
|
|
4581
|
+
})
|
|
4582
|
+
if (!extended.ok) {
|
|
4583
|
+
return {
|
|
4584
|
+
ok: false,
|
|
4585
|
+
code: extended.code,
|
|
4586
|
+
planId: record.plan.planId,
|
|
4587
|
+
subtaskId,
|
|
4588
|
+
error: extended.error,
|
|
4589
|
+
hint: extended.hint,
|
|
4590
|
+
}
|
|
4591
|
+
}
|
|
4592
|
+
extension = extended
|
|
4593
|
+
}
|
|
4594
|
+
if (!statusRequested) {
|
|
4595
|
+
if (hasTimeNotice) recordTimeNotice(record, subtaskId, timeNoticeArg)
|
|
4596
|
+
/*
|
|
4597
|
+
* 纯时限事务到此结束。方案 §2.2 效果 3:状态行 revision +1(延期/预告也是
|
|
4598
|
+
* 行变更,同样受 STALE_WRITE 乐观锁保护);状态与判定一个字段都不改。
|
|
4599
|
+
*/
|
|
4600
|
+
const row = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
4601
|
+
if (row) {
|
|
4602
|
+
row.revision = Number(current?.revision ?? 0) + 1
|
|
4603
|
+
row.updatedBy = 'agent'
|
|
4604
|
+
}
|
|
4605
|
+
record.updatedAt = Date.now()
|
|
4606
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
4607
|
+
const written = snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
4608
|
+
const readiness = readinessOf(record, snapshot)
|
|
4609
|
+
return {
|
|
4610
|
+
ok: true,
|
|
4611
|
+
planId: record.plan.planId,
|
|
4612
|
+
subtaskId,
|
|
4613
|
+
status: written?.status ?? current?.status ?? null,
|
|
4614
|
+
revision: written?.revision ?? Number(current?.revision ?? 0),
|
|
4615
|
+
updatedBy: written?.updatedBy ?? 'agent',
|
|
4616
|
+
...(extension
|
|
4617
|
+
? {
|
|
4618
|
+
deadlineAt: extension.deadlineAt,
|
|
4619
|
+
timerRearmed: extension.timerRearmed,
|
|
4620
|
+
watchdogRearmed: extension.watchdogRearmed,
|
|
4621
|
+
}
|
|
4622
|
+
: {}),
|
|
4623
|
+
...(hasTimeNotice ? { timeNotice: written?.timeNotice ?? null } : {}),
|
|
4624
|
+
timeJournal: Array.isArray(written?.timeJournal) ? written.timeJournal.slice(-10) : [],
|
|
4625
|
+
stats: snapshot.stats,
|
|
4626
|
+
deliveryReady: readiness.ready,
|
|
4627
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
4628
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
4629
|
+
hint: '时限协商已记录:状态与判定未改,不需要 force;放宽永远有界,超出累计上限请转新轮续跑或转 escalate 请主 Agent 裁决。',
|
|
4630
|
+
}
|
|
4631
|
+
}
|
|
3365
4632
|
const revision = Number(current?.revision ?? 0) + 1
|
|
3366
4633
|
/*
|
|
3367
4634
|
* [1.8.13] A manual verdict can carry structured evidence.
|
|
@@ -3394,6 +4661,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3394
4661
|
revision,
|
|
3395
4662
|
updatedBy: 'agent',
|
|
3396
4663
|
})
|
|
4664
|
+
/*
|
|
4665
|
+
* [2.2.0][T5/O-4c] 带 status 的调用同时带 timeNotice 时,预告记录在改判落行
|
|
4666
|
+
* 之后写入:applyStatus 抛错(如非法 verification)时不会留下半写的预告。
|
|
4667
|
+
*/
|
|
4668
|
+
if (hasTimeNotice) recordTimeNotice(record, subtaskId, timeNoticeArg)
|
|
3397
4669
|
if (status === 'blocked') {
|
|
3398
4670
|
record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' })
|
|
3399
4671
|
}
|
|
@@ -3406,7 +4678,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3406
4678
|
*/
|
|
3407
4679
|
try {
|
|
3408
4680
|
const writtenRow = record.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
3409
|
-
session
|
|
4681
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
3410
4682
|
planId: record.plan.planId,
|
|
3411
4683
|
subtaskId,
|
|
3412
4684
|
status,
|
|
@@ -3423,7 +4695,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3423
4695
|
options: writtenRow?.options,
|
|
3424
4696
|
instruction: writtenRow?.instruction,
|
|
3425
4697
|
instructionSeq: writtenRow?.instructionSeq,
|
|
3426
|
-
})
|
|
4698
|
+
}))
|
|
3427
4699
|
} catch (error) {
|
|
3428
4700
|
pushRecordError(record, error)
|
|
3429
4701
|
}
|
|
@@ -3538,7 +4810,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3538
4810
|
* 「内存里已经改了、刷新后又退回去」的分叉。
|
|
3539
4811
|
*/
|
|
3540
4812
|
try {
|
|
3541
|
-
session
|
|
4813
|
+
appendUserMessage(session, buildReplanMessage(result.payload))
|
|
3542
4814
|
} catch (error) {
|
|
3543
4815
|
return {
|
|
3544
4816
|
...base,
|
|
@@ -3692,7 +4964,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3692
4964
|
*/
|
|
3693
4965
|
const appendCancelRecord = () => {
|
|
3694
4966
|
try {
|
|
3695
|
-
session
|
|
4967
|
+
appendUserMessage(session, cancelMessage)
|
|
3696
4968
|
record.cancelRecorded = true
|
|
3697
4969
|
record.cancelReason = reason
|
|
3698
4970
|
return true
|
|
@@ -3948,8 +5220,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3948
5220
|
book.doneBefore = Number(live.stats?.done ?? 0)
|
|
3949
5221
|
record.dispatchPromise = dispatchPlan(ctx, record, {
|
|
3950
5222
|
...base,
|
|
5223
|
+
// [2.2.0][T6/O-1a] 自动续跑同样在后台执行:保持完成即时通知。
|
|
5224
|
+
notifyCompletion: true,
|
|
3951
5225
|
signal: controller.signal,
|
|
3952
|
-
|
|
5226
|
+
// [2.2.0][T4/O-3b] 传原始配置值:未配置=undefined 时协商派生生效,显式配置=兜底上限(resolveSubtaskTimeoutMs)。
|
|
5227
|
+
childTimeoutMs: options.childTimeoutMs,
|
|
3953
5228
|
idleTimeoutMs: limits.idleTimeoutMs,
|
|
3954
5229
|
totalTimeoutMs: limits.totalTimeoutMs,
|
|
3955
5230
|
maxResumes: limits.maxResumes,
|
|
@@ -3995,12 +5270,17 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
3995
5270
|
* `closure:'reported'` + `report{state,at,ref,turn}`,与左侧栏 chip 同源。
|
|
3996
5271
|
* 返回本次新标记的条数;已是 reported 的行不重复写,避免每轮刷新 revision。
|
|
3997
5272
|
*/
|
|
3998
|
-
function markReported(record: any, session: any, ref: string) {
|
|
5273
|
+
function markReported(record: any, session: any, ref: string, onlySubtaskId?: string) {
|
|
3999
5274
|
const at = Date.now()
|
|
4000
5275
|
const rawTurn = Number(state.activeTurns?.get?.(session?.id) ?? NaN)
|
|
4001
5276
|
const turn = Number.isFinite(rawTurn) ? rawTurn : null
|
|
4002
5277
|
let changed = 0
|
|
4003
5278
|
for (const item of Array.isArray(record?.statuses) ? record.statuses : []) {
|
|
5279
|
+
/*
|
|
5280
|
+
* [2.2.0][T6/O-1a] 即时通知只标记「刚结算的这一条」;finishRound 批量
|
|
5281
|
+
* 补齐不传 onlySubtaskId,保持原有「所有 done 未回报行」语义。
|
|
5282
|
+
*/
|
|
5283
|
+
if (onlySubtaskId !== undefined && String(item?.subtaskId) !== String(onlySubtaskId)) continue
|
|
4004
5284
|
if (item?.status !== 'done') continue
|
|
4005
5285
|
if (item?.closure === 'reported' && item?.report?.state === 'sent') continue
|
|
4006
5286
|
try {
|
|
@@ -4020,6 +5300,49 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4020
5300
|
return changed
|
|
4021
5301
|
}
|
|
4022
5302
|
|
|
5303
|
+
/**
|
|
5304
|
+
* [2.2.0][T6/O-1a] 完成即时通知的插件兜底投递器(后台轮次专用)。
|
|
5305
|
+
*
|
|
5306
|
+
* 方案 §2.3 双通道:①协议通道由子 Agent 完成即 `send_message`;②兜底通道
|
|
5307
|
+
* 由这里在 `settleFromOutput` 结算成功后立刻写一条纯文本 `user/message`
|
|
5308
|
+
* (含子任务 ID、摘要、验收计数、用时),不等待整轮结束。消息不带任何
|
|
5309
|
+
* workplan 标记,回放解析器按未知消息跳过(A2:回放是纯读)。
|
|
5310
|
+
*
|
|
5311
|
+
* 幂等:同一子任务已有 `closure:'reported'` + `report.state:'sent'` 时直接
|
|
5312
|
+
* 跳过——重复结算、finishRound 轮级批量补齐都不得重报。先写通知、后记
|
|
5313
|
+
* 回报:写失败只置 reportPending,交结果消息补齐(绝不留无证据已回报)。
|
|
5314
|
+
*/
|
|
5315
|
+
function emitSubtaskDoneNotice(record: any, session: any, subtask: any, verdict: any) {
|
|
5316
|
+
if (!record || !session || typeof session.append !== 'function') return
|
|
5317
|
+
const row = Array.isArray(record.statuses)
|
|
5318
|
+
? record.statuses.find((item: any) => item?.subtaskId === subtask?.id)
|
|
5319
|
+
: null
|
|
5320
|
+
if (row?.closure === 'reported' && row?.report?.state === 'sent') return
|
|
5321
|
+
const acceptance = Array.isArray(verdict?.acceptance) ? verdict.acceptance : []
|
|
5322
|
+
const passed = acceptance.filter((item: any) => item?.result === 'pass').length
|
|
5323
|
+
const acceptanceCount = acceptance.length > 0
|
|
5324
|
+
? `验收 ${passed}/${acceptance.length} 通过`
|
|
5325
|
+
: '验收记录 0 条(legacy 未提供结构化验收)'
|
|
5326
|
+
const elapsedMs = Number.isFinite(Number(row?.startedAt))
|
|
5327
|
+
? Math.max(0, Date.now() - Number(row.startedAt))
|
|
5328
|
+
: 0
|
|
5329
|
+
const elapsed = elapsedMs < 1000 ? `${elapsedMs}ms` : `${(elapsedMs / 1000).toFixed(1)}s`
|
|
5330
|
+
const summary = truncate(String(row?.summary ?? '').replace(/\s+/g, ' ').trim(), 160) || '(无摘要)'
|
|
5331
|
+
const text = `[dsh-workplan] 子任务 ${String(subtask?.id ?? '')} 已完成并结算:${summary};${acceptanceCount};用时 ${elapsed}`
|
|
5332
|
+
try {
|
|
5333
|
+
appendUserMessage(session, text)
|
|
5334
|
+
} catch (error) {
|
|
5335
|
+
ctx.logger?.warn?.(
|
|
5336
|
+
`dsh-workplan: 完成即时通知写入失败 ${String(subtask?.id ?? '')}:`
|
|
5337
|
+
+ `${error instanceof Error ? error.message : String(error)}`,
|
|
5338
|
+
)
|
|
5339
|
+
record.reportPending = true
|
|
5340
|
+
return
|
|
5341
|
+
}
|
|
5342
|
+
const ref = `${record?.plan?.planId ?? 'plan'}:${record?.dispatchedAt ?? 0}`
|
|
5343
|
+
markReported(record, session, ref, subtask?.id)
|
|
5344
|
+
}
|
|
5345
|
+
|
|
4023
5346
|
function finishRound(record: any, session: any) {
|
|
4024
5347
|
const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`
|
|
4025
5348
|
if (!record.resultWritten) {
|
|
@@ -4036,7 +5359,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4036
5359
|
const reported = markReported(record, session, ref)
|
|
4037
5360
|
const resultMessage = buildRoundResult(record, session.id, limits)
|
|
4038
5361
|
try {
|
|
4039
|
-
session
|
|
5362
|
+
appendUserMessage(session, resultMessage)
|
|
4040
5363
|
record.resultWritten = true
|
|
4041
5364
|
record.reportPending = needReport > 0 && reported < needReport
|
|
4042
5365
|
} catch (error) {
|
|
@@ -4170,6 +5493,15 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4170
5493
|
version: pluginVersion,
|
|
4171
5494
|
runtime: runtimeIdentity(),
|
|
4172
5495
|
planId: record.plan.planId,
|
|
5496
|
+
/*
|
|
5497
|
+
* [2.2.2][D5] 规划器档位遥测进入模型可读面。
|
|
5498
|
+
*
|
|
5499
|
+
* 之前只写进内存 record / 失败降级消息;成功计划没有可复核的
|
|
5500
|
+
* planner reasoningEffort 证据,D5 只能 CONDITIONAL。现在 status
|
|
5501
|
+
* 返回 provider/model/reasoningEffort/source/outcome/at,便于在
|
|
5502
|
+
* 真实运行态核对“规划器未继承主 Agent”。
|
|
5503
|
+
*/
|
|
5504
|
+
planner: record.planner ?? null,
|
|
4173
5505
|
running,
|
|
4174
5506
|
phase: record.phase,
|
|
4175
5507
|
elapsedMs: record.dispatchStartedAt ? Date.now() - record.dispatchStartedAt : null,
|
|
@@ -4406,13 +5738,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4406
5738
|
message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待主 Agent 指示。',
|
|
4407
5739
|
}
|
|
4408
5740
|
}
|
|
5741
|
+
// [2.2.6][T4] 同模式共犯(T1 W4):对象感知读取,消灭 String(对象) 分支。
|
|
4409
5742
|
const options = (Array.isArray(args?.options) ? args.options : [])
|
|
4410
5743
|
.slice(0, MAX_ESCALATION_OPTIONS)
|
|
4411
|
-
.map((item: any) => truncate(
|
|
5744
|
+
.map((item: any) => truncate(needEntryText(item), 300))
|
|
4412
5745
|
.filter(Boolean)
|
|
4413
5746
|
const needs = (Array.isArray(args?.needs) ? args.needs : [])
|
|
4414
5747
|
.slice(0, 10)
|
|
4415
|
-
.map((item: any) => truncate(
|
|
5748
|
+
.map((item: any) => truncate(needEntryText(item), 300))
|
|
4416
5749
|
.filter(Boolean)
|
|
4417
5750
|
const now = Date.now()
|
|
4418
5751
|
const revision = Number(row.revision ?? 0) + 1
|
|
@@ -4436,7 +5769,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4436
5769
|
try {
|
|
4437
5770
|
const parent = (ctx as any).sessions?.get?.(parentId)
|
|
4438
5771
|
const written = record.statuses.find((item: any) => item?.subtaskId === row.subtaskId)
|
|
4439
|
-
parent
|
|
5772
|
+
appendUserMessage(parent, buildUpdateMessage({
|
|
4440
5773
|
planId: record.plan.planId,
|
|
4441
5774
|
subtaskId: row.subtaskId,
|
|
4442
5775
|
status: 'blocked',
|
|
@@ -4448,7 +5781,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4448
5781
|
escalatedAt: now,
|
|
4449
5782
|
escalationSeq: revision,
|
|
4450
5783
|
revision,
|
|
4451
|
-
})
|
|
5784
|
+
}))
|
|
4452
5785
|
} catch (error) {
|
|
4453
5786
|
pushRecordError(record, error)
|
|
4454
5787
|
}
|
|
@@ -4660,7 +5993,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4660
5993
|
record.updatedAt = now
|
|
4661
5994
|
try {
|
|
4662
5995
|
const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
|
|
4663
|
-
session
|
|
5996
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
4664
5997
|
planId: record.plan.planId,
|
|
4665
5998
|
subtaskId,
|
|
4666
5999
|
status: 'in_progress',
|
|
@@ -4668,7 +6001,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4668
6001
|
instruction: written?.instruction,
|
|
4669
6002
|
instructionSeq: revision,
|
|
4670
6003
|
revision,
|
|
4671
|
-
})
|
|
6004
|
+
}))
|
|
4672
6005
|
} catch (error) {
|
|
4673
6006
|
pushRecordError(record, error)
|
|
4674
6007
|
}
|
|
@@ -4779,13 +6112,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4779
6112
|
})
|
|
4780
6113
|
record.updatedAt = Date.now()
|
|
4781
6114
|
try {
|
|
4782
|
-
session
|
|
6115
|
+
appendUserMessage(session, buildUpdateMessage({
|
|
4783
6116
|
planId: record.plan.planId,
|
|
4784
6117
|
subtaskId,
|
|
4785
6118
|
status: row.status,
|
|
4786
6119
|
handoffs,
|
|
4787
6120
|
revision,
|
|
4788
|
-
})
|
|
6121
|
+
}))
|
|
4789
6122
|
} catch (error) {
|
|
4790
6123
|
pushRecordError(record, error)
|
|
4791
6124
|
}
|
|
@@ -4929,7 +6262,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4929
6262
|
* A wedged promise keeps the old stale escape hatch (see below).
|
|
4930
6263
|
*/
|
|
4931
6264
|
const startedAt = Number(record.dispatchStartedAt ?? 0)
|
|
4932
|
-
const staleAfter = limits.totalTimeoutMs + 120000
|
|
6265
|
+
const staleAfter = limits.totalTimeoutMs > 0 ? limits.totalTimeoutMs + 120000 : NO_ROUND_BUDGET_MS + 120000
|
|
4933
6266
|
if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
|
|
4934
6267
|
try {
|
|
4935
6268
|
await record.dispatchPromise
|
|
@@ -4952,7 +6285,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
4952
6285
|
* stops claiming the plan is running and hands the work back instead.
|
|
4953
6286
|
*/
|
|
4954
6287
|
const startedAt = Number(record.dispatchStartedAt ?? 0)
|
|
4955
|
-
const staleAfter = limits.totalTimeoutMs + 120000
|
|
6288
|
+
const staleAfter = limits.totalTimeoutMs > 0 ? limits.totalTimeoutMs + 120000 : NO_ROUND_BUDGET_MS + 120000
|
|
4956
6289
|
if (startedAt > 0 && Date.now() - startedAt > staleAfter) {
|
|
4957
6290
|
return {
|
|
4958
6291
|
ok: false,
|
|
@@ -5033,11 +6366,20 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5033
6366
|
modelSelection: selection.provider && selection.model ? selection : record.modelSelection,
|
|
5034
6367
|
cwd: session.header?.cwd ?? options.cwd,
|
|
5035
6368
|
conversationContext: record.conversationContext ?? '',
|
|
6369
|
+
/*
|
|
6370
|
+
* [2.2.0][T6/O-1a] 只有后台(async)轮次推即时通知:wait 模式主 Agent
|
|
6371
|
+
* 在调用栈内等待,轮级结果消息就是该模式的完成通道,避免同一轮重复
|
|
6372
|
+
* 两条消息;既有的「每轮恰 1 条持久结果消息」断言因此保持不变。
|
|
6373
|
+
*/
|
|
6374
|
+
notifyCompletion: mode === 'async',
|
|
6375
|
+
onSubtaskDone: (recordArg: any, subtask: any, verdict: any) =>
|
|
6376
|
+
emitSubtaskDoneNotice(recordArg, session, subtask, verdict),
|
|
5036
6377
|
}
|
|
5037
6378
|
record.dispatchPromise = dispatchPlan(ctx, record, {
|
|
5038
6379
|
...roundOptions,
|
|
5039
6380
|
signal: dispatchController.signal,
|
|
5040
|
-
|
|
6381
|
+
// [2.2.0][T4/O-3b] 传原始配置值:未配置=undefined 时协商派生生效,显式配置=兜底上限(resolveSubtaskTimeoutMs)。
|
|
6382
|
+
childTimeoutMs: options.childTimeoutMs,
|
|
5041
6383
|
idleTimeoutMs: limits.idleTimeoutMs,
|
|
5042
6384
|
totalTimeoutMs: limits.totalTimeoutMs,
|
|
5043
6385
|
maxResumes: limits.maxResumes,
|
|
@@ -5405,7 +6747,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5405
6747
|
+ `${stuck.stats.done}/${stuck.stats.total},未完成 ${released.join(', ') || '无'}`,
|
|
5406
6748
|
)
|
|
5407
6749
|
try {
|
|
5408
|
-
session
|
|
6750
|
+
appendUserMessage(session, makeUserMessage(
|
|
5409
6751
|
[
|
|
5410
6752
|
`⚠️ 本轮未通过交付就绪检查,已按「放行但留痕」结束(计划 ${record.plan.planId})`,
|
|
5411
6753
|
`进度 ${stuck.stats.done}/${stuck.stats.total};未完成:${released.join(', ') || '无'}`,
|
|
@@ -5416,7 +6758,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
5416
6758
|
form: 'notice',
|
|
5417
6759
|
summary: `未就绪放行 ${stuck.stats.done}/${stuck.stats.total}`,
|
|
5418
6760
|
},
|
|
5419
|
-
)
|
|
6761
|
+
))
|
|
5420
6762
|
} catch (error) {
|
|
5421
6763
|
ctx.logger?.warn?.(
|
|
5422
6764
|
`dsh-workplan: 放行留痕写入失败:${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -6316,6 +7658,51 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6316
7658
|
}
|
|
6317
7659
|
|
|
6318
7660
|
let plan
|
|
7661
|
+
/*
|
|
7662
|
+
* [2.1.6] 规划器遥测的落点:成功写进记录、失败写进降级消息,让「为什么没
|
|
7663
|
+
* 分解成功」不再是一句没有现场的「超时」。
|
|
7664
|
+
*/
|
|
7665
|
+
const plannerTelemetry: any = {}
|
|
7666
|
+
/*
|
|
7667
|
+
* [2.2.5][T5] 分解期间可见性——占位卡片(T1 P-5 / T3 §2 S1、§3 C1)。
|
|
7668
|
+
*
|
|
7669
|
+
* 缺陷:runPlanner 全程(最长 3 次尝试 × 300s 窗口 + 退避)此前零写入,
|
|
7670
|
+
* 用户看到的是「发出去一句话后界面没有任何反应」,无法区分「正在重试」
|
|
7671
|
+
* 与「卡死」(T1 断点层判定=未发出,插件层)。现在进入规划前先放一张
|
|
7672
|
+
* phase:'planning' 的占位记录:侧栏 4 秒轮询只要记录存在就下发(serialisePlan
|
|
7673
|
+
* 对 plan:null 已兜底),卡片徽标走既有词汇「正在安排」(client.ts LOCALE)。
|
|
7674
|
+
* 后续出口不新增路径:成功/降级由下方既有 records.set 整体覆盖;用户中止
|
|
7675
|
+
* 路径由 serialisePlan 的终态收敛(turnEnded → phase:'ended')兜住,不会
|
|
7676
|
+
* 残留假「进行中」。
|
|
7677
|
+
*/
|
|
7678
|
+
const planningStartedAt = Date.now()
|
|
7679
|
+
const planningRecord: any = {
|
|
7680
|
+
planId: null,
|
|
7681
|
+
plan: null,
|
|
7682
|
+
title: '正在生成任务分解…',
|
|
7683
|
+
degraded: false,
|
|
7684
|
+
statuses: [],
|
|
7685
|
+
phase: 'planning',
|
|
7686
|
+
errors: [],
|
|
7687
|
+
createdAt: planningStartedAt,
|
|
7688
|
+
updatedAt: planningStartedAt,
|
|
7689
|
+
createdTurn: payload.turn,
|
|
7690
|
+
}
|
|
7691
|
+
state.records.set(session.id, planningRecord)
|
|
7692
|
+
/*
|
|
7693
|
+
* [2.2.5][T5] 进度回调落点(T1 P-6 / T3 §3 C2/C3、§4 频率规则):
|
|
7694
|
+
* 通道 A = 占位卡片 errors 区追加重试摘要(≤2 行,保底通道);通道 B =
|
|
7695
|
+
* appendUserMessage 通知(仅「会退避重试」的失败发,≤2 条,aborted 静默)。
|
|
7696
|
+
* 文案组装与频率硬规则全部在 createPlannerProgressReporter / plannerProgressLines
|
|
7697
|
+
* (plan.ts,可独立回归);这里只注入宿主交互面。
|
|
7698
|
+
*/
|
|
7699
|
+
const onPlannerProgress = createPlannerProgressReporter({
|
|
7700
|
+
signal: payload.signal,
|
|
7701
|
+
record: planningRecord,
|
|
7702
|
+
setRecord: (record: any) => state.records.set(session.id, record),
|
|
7703
|
+
appendNotice: (text: string) => appendUserMessage(session, text),
|
|
7704
|
+
maxAttempts: PLANNER_MAX_ATTEMPTS,
|
|
7705
|
+
})
|
|
6319
7706
|
try {
|
|
6320
7707
|
plan = await runPlanner(ctx, {
|
|
6321
7708
|
taskText,
|
|
@@ -6323,7 +7710,11 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6323
7710
|
sessionId: session.id,
|
|
6324
7711
|
modelSelection,
|
|
6325
7712
|
signal: payload.signal,
|
|
6326
|
-
plannerTimeoutMs:
|
|
7713
|
+
plannerTimeoutMs: normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
|
|
7714
|
+
plannerIdleTimeoutMs: normalisePlannerWindow(options?.limits?.plannerIdleTimeoutMs ?? options?.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
|
|
7715
|
+
telemetry: plannerTelemetry,
|
|
7716
|
+
// [2.2.5][T5] 分解期间进度事件(T1 P-6):只追加观察回调,不改重试语义。
|
|
7717
|
+
onProgress: onPlannerProgress,
|
|
6327
7718
|
conversationContext,
|
|
6328
7719
|
sourceMessageIds: human.map((message: any) => message.id).filter((id: any) => typeof id === 'string'),
|
|
6329
7720
|
/*
|
|
@@ -6333,14 +7724,25 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6333
7724
|
* and asks for `estimateMinutes` on every subtask.
|
|
6334
7725
|
*/
|
|
6335
7726
|
budget: {
|
|
6336
|
-
totalMinutes:
|
|
7727
|
+
totalMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
|
|
7728
|
+
? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
|
|
7729
|
+
: 0,
|
|
6337
7730
|
childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
|
|
6338
7731
|
concurrency: MAX_CONCURRENT,
|
|
6339
7732
|
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
6340
7733
|
},
|
|
6341
7734
|
})
|
|
6342
7735
|
} catch (error) {
|
|
6343
|
-
if (payload.signal.aborted)
|
|
7736
|
+
if (payload.signal.aborted) {
|
|
7737
|
+
/*
|
|
7738
|
+
* [2.2.5][T5] 用户中止:静默退出(T3 §2 中止分支,不发通知)。占位卡片
|
|
7739
|
+
* 若本轮前无旧记录,交给 serialisePlan 终态收敛转 'ended',不留假
|
|
7740
|
+
* 「进行中」;若本轮前已有旧计划记录,恢复它——中止不该把用户上一份
|
|
7741
|
+
* 终态进度从内存里挤掉(旧实现中止路径不写记录,此行为保持不变)。
|
|
7742
|
+
*/
|
|
7743
|
+
if (existing?.plan) state.records.set(session.id, existing)
|
|
7744
|
+
return downstream
|
|
7745
|
+
}
|
|
6344
7746
|
const planId = `wp-${randomUUID()}`
|
|
6345
7747
|
const createdAt = Date.now()
|
|
6346
7748
|
const message = buildDegradedMessage({
|
|
@@ -6349,6 +7751,7 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6349
7751
|
createdTurn: payload.turn,
|
|
6350
7752
|
createdAt,
|
|
6351
7753
|
error: error instanceof Error ? error.message : String(error),
|
|
7754
|
+
detail: plannerTelemetryLine(plannerTelemetry),
|
|
6352
7755
|
taskText,
|
|
6353
7756
|
})
|
|
6354
7757
|
state.records.set(session.id, {
|
|
@@ -6357,6 +7760,7 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6357
7760
|
title: '自动分解降级',
|
|
6358
7761
|
degraded: true,
|
|
6359
7762
|
error: error instanceof Error ? error.message : String(error),
|
|
7763
|
+
planner: { ...plannerTelemetry, at: createdAt },
|
|
6360
7764
|
statuses: [],
|
|
6361
7765
|
phase: 'degraded',
|
|
6362
7766
|
errors: [truncate(error instanceof Error ? error.message : String(error), 1000)],
|
|
@@ -6367,7 +7771,11 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6367
7771
|
return enterDecision(downstream, [message])
|
|
6368
7772
|
}
|
|
6369
7773
|
|
|
6370
|
-
if (payload.signal.aborted)
|
|
7774
|
+
if (payload.signal.aborted) {
|
|
7775
|
+
// [2.2.5][T5] 计划已生成但回合被中止:同中止分支,恢复旧记录再静默退出。
|
|
7776
|
+
if (existing?.plan) state.records.set(session.id, existing)
|
|
7777
|
+
return downstream
|
|
7778
|
+
}
|
|
6371
7779
|
const planId = `wp-${randomUUID()}`
|
|
6372
7780
|
const createdAt = Date.now()
|
|
6373
7781
|
const fullPlan = attachPlanMeta(plan, {
|
|
@@ -6382,6 +7790,9 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6382
7790
|
statuses: createStatuses(fullPlan),
|
|
6383
7791
|
phase: 'pending',
|
|
6384
7792
|
errors: [],
|
|
7793
|
+
// [2.1.6] 规划这一步花了多久、用的哪个模型:成功也留痕,失败才好对比。
|
|
7794
|
+
// [2.1.7] 抢救成功的计划保留 SALVAGED 判定,别被 'ok' 覆盖——它是复盘的关键证据。
|
|
7795
|
+
planner: { ...plannerTelemetry, outcome: plannerTelemetry.outcome === 'SALVAGED' ? 'SALVAGED' : 'ok', at: createdAt },
|
|
6385
7796
|
createdAt,
|
|
6386
7797
|
updatedAt: createdAt,
|
|
6387
7798
|
dispatchedAt: null,
|
|
@@ -6414,7 +7825,9 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
6414
7825
|
* cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
|
|
6415
7826
|
*/
|
|
6416
7827
|
const planMessage = buildPlanMessage(fullPlan, {
|
|
6417
|
-
totalBudgetMinutes:
|
|
7828
|
+
totalBudgetMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
|
|
7829
|
+
? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
|
|
7830
|
+
: 0,
|
|
6418
7831
|
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
6419
7832
|
planMode,
|
|
6420
7833
|
autoDispatched,
|
|
@@ -6543,6 +7956,7 @@ export function statusToolOutputSchema() {
|
|
|
6543
7956
|
// [1.8.14] Loaded-build identity: version alone cannot prove which bytes
|
|
6544
7957
|
// the process is running after a rebuild or a profile recomposition.
|
|
6545
7958
|
runtime: { type: 'object' },
|
|
7959
|
+
planner: { oneOf: [{ type: 'object' }, { type: 'null' }] },
|
|
6546
7960
|
deliveryReady: { type: 'boolean' },
|
|
6547
7961
|
deliveryBlockers: { type: 'array' },
|
|
6548
7962
|
deliveryRemaining: { type: 'array' },
|