dsh-workplan 1.9.1 → 1.10.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/src/runtime.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
 
15
15
  import { randomUUID } from 'node:crypto'
16
- import { existsSync } from 'node:fs'
16
+ import { existsSync, statSync } from 'node:fs'
17
17
  import { isAbsolute, resolve } from 'node:path'
18
18
 
19
19
  import {
@@ -65,6 +65,7 @@ import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
65
65
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
66
66
  import { supersedePlanRecord } from './supersede.js'
67
67
  import { createProgressWatchdog, describeError } from './watchdog.js'
68
+ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js'
68
69
 
69
70
  /**
70
71
  * [1.8.18] How many subtasks the plan *defines*.
@@ -519,6 +520,61 @@ export function probeInterruptedEvidence(output: any, subtask: any, cwd: any, ar
519
520
  return { artifacts, missingArtifacts }
520
521
  }
521
522
 
523
+ /**
524
+ * [1.10.6] Fingerprint the files a timed-out attempt already wrote.
525
+ *
526
+ * T6 (G3) found that the retry decision never looked at the disk: a second
527
+ * attempt could silently overwrite a deliverable the first attempt had already
528
+ * produced, turning "the child stopped early" into "the deliverable was
529
+ * rewritten". This snapshot (path + size + mtime) is the record the retry is
530
+ * compared against.
531
+ *
532
+ * A missing file is not a conflict — it simply has no fingerprint. `stat` is
533
+ * injectable so the check can be tested without touching the real filesystem.
534
+ */
535
+ export function fingerprintArtifacts(refs: any, cwd: any, stat: any = statSync) {
536
+ const list = Array.isArray(refs) ? refs : []
537
+ const out: { ref: string; size: number; mtimeMs: number }[] = []
538
+ const seen = new Set<string>()
539
+ for (const item of list) {
540
+ const ref = typeof item === 'string' ? item.trim() : ''
541
+ if (!ref || seen.has(ref)) continue
542
+ seen.add(ref)
543
+ const target = resolveArtifactPath(ref, cwd)
544
+ if (!target) continue
545
+ try {
546
+ const info = stat(target)
547
+ if (!info) continue
548
+ out.push({ ref, size: Number(info.size), mtimeMs: Number(info.mtimeMs) })
549
+ } catch {
550
+ // Missing or unreadable: nothing to protect, and not a conflict.
551
+ }
552
+ }
553
+ return out
554
+ }
555
+
556
+ /**
557
+ * [1.10.6] Which landed artifacts changed since the snapshot was taken.
558
+ *
559
+ * Size or mtime differing is enough to call it a conflict: the file the first
560
+ * attempt produced is no longer the file on disk, so a retry that rewrites it
561
+ * would destroy work rather than finish it.
562
+ */
563
+ export function diffArtifactFingerprints(before: any, after: any) {
564
+ const previous = new Map<string, any>()
565
+ for (const item of Array.isArray(before) ? before : []) {
566
+ if (item && typeof item.ref === 'string') previous.set(item.ref, item)
567
+ }
568
+ const conflicts: string[] = []
569
+ for (const item of Array.isArray(after) ? after : []) {
570
+ if (!item || typeof item.ref !== 'string') continue
571
+ const recorded = previous.get(item.ref)
572
+ if (!recorded) continue
573
+ if (recorded.size !== item.size || recorded.mtimeMs !== item.mtimeMs) conflicts.push(item.ref)
574
+ }
575
+ return conflicts
576
+ }
577
+
522
578
  /**
523
579
  * [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
524
580
  */
@@ -618,15 +674,37 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
618
674
  * Retry policy for one child attempt.
619
675
  *
620
676
  * A wedged child (no event for the whole idle window) is worth one fresh
621
- * attempt. A hard ceiling means the budget is gone, and an abort is a decision,
622
- * so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
623
- * more than one idle window left, otherwise the retry itself would just be
624
- * killed by the same watchdog.
677
+ * attempt. `CHILD_NOT_COMPLETED` is retried only while there is more than one
678
+ * idle window left, otherwise the retry itself would just be killed by the same
679
+ * watchdog.
680
+ *
681
+ * [1.10.3] 单个子任务撞上 900 秒硬上限时,只要整轮预算还够再跑一轮,就自动重试
682
+ * 一次。用户 2026-11-01 的质疑是对的:此前这一支被无条件 `return false`,
683
+ * 于是「预算没花完、只是这一步慢了」也被判成阻塞,必须等主 Agent 人工改判或
684
+ * 重新派发——而 `attempt` 已经是 1、产物又都在盘上,重跑一次往往就能过。
685
+ *
686
+ * 仍然**不自动重试**的两种情况,理由不变:
687
+ * - `TOTAL_TIMEOUT`:整轮预算已经用光,重试必然再被同一把闸刀砍掉,只会空耗;
688
+ * - `ABORTED`:那是「有人决定停」而不是「跑不完」,自动重来等于违背决定。
625
689
  */
626
690
  export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, idleTimeoutMs: any) {
627
691
  if (attempt >= 2) return false
628
692
  const code = error?.code
629
- if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
693
+ if (code === 'CHILD_TIMEOUT') {
694
+ /*
695
+ * 重试要有意义,必须给它留够「至少再跑一次短任务」的时间。
696
+ *
697
+ * [1.10.6] 这里**不能**再拿空闲窗口当门槛(旧式 `max(idle, 120s)`):
698
+ * 出厂配置是 ceiling=900s / idle=300s / round=1200s,撞上限后剩下约
699
+ * 300s,而 `remaining > 300s` 恒为假——用户要的「有预算就自动重试一次」
700
+ * 会在默认配置下永远不触发,正是 T6 记录的那类「策略说会、链路不会」。
701
+ * 固定 120s 是「够跑一次短任务」的下限,同时保证不会刚重试就被砍掉。
702
+ * `tests/workplan-retry-feedback.test.ts` 的 60s 反例与 600s 正例都仍然成立。
703
+ */
704
+ const floor = 120000
705
+ return Number(remainingMs) > floor
706
+ }
707
+ if (code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
630
708
  if (/aborted|refusal/i.test(String(error?.message ?? ''))) return false
631
709
  if (code === 'CHILD_STALLED') return true
632
710
  if (code === 'CHILD_NOT_COMPLETED') {
@@ -638,7 +716,17 @@ export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, i
638
716
  async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
639
717
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
640
718
  let lastError: any = null
641
- let lastFailure: any = null
719
+ /*
720
+ * [1.10.6] A retry that starts after a *ceiling* timeout is a second attempt
721
+ * even though this function is entered afresh. `attemptOffset` keeps the
722
+ * numbering honest (`第 2 次尝试`) and, with the loop condition below, keeps
723
+ * the cap at two real activations instead of letting the new call spend its
724
+ * own two.
725
+ */
726
+ const firstAttempt = Number.isInteger(options.attemptOffset) && options.attemptOffset > 1
727
+ ? options.attemptOffset
728
+ : 1
729
+ let lastFailure: any = options.priorFailure ?? null
642
730
  /*
643
731
  * [1.8.6] The interrupt has to outlive the thrown error.
644
732
  *
@@ -655,7 +743,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
655
743
  startedAt: Date.now(),
656
744
  }, guard)) return
657
745
 
658
- for (let attempt = 1; attempt <= 2; attempt += 1) {
746
+ for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
659
747
  if (guard.timedOut) return
660
748
  interruptedEvidence = null
661
749
  if (parentSignal.aborted) throw abortError()
@@ -819,7 +907,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
819
907
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
820
908
  continue
821
909
  }
822
- if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
910
+ /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
911
+ if (!isAbort && remaining <= idleTimeoutMs) {
823
912
  record.errors = [
824
913
  ...(record.errors ?? []),
825
914
  `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
@@ -871,30 +960,57 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
871
960
  }
872
961
 
873
962
  /*
874
- * Runs one subtask under a deadline that belongs to that subtask alone.
963
+ * One attempt under a deadline that belongs to that attempt alone.
964
+ *
965
+ * [1.10.6] Split out of `runSubtask` so a ceiling timeout can be retried with a
966
+ * *fresh* timer. The old code armed a single timer for the whole subtask (shared
967
+ * by both attempts), so even once the retry decision became reachable the second
968
+ * attempt would have had no time left — a patch that changes nothing.
875
969
  *
876
- * The subtask timer is a full settlement guarantee, not just an abort hint: if
877
- * the child activation ignores its abort signal, or never settles at all, the
878
- * race below still resolves, that subtask is recorded as blocked, and the
879
- * dispatcher keeps scheduling the rest of the DAG. This function never throws
880
- * on a per-subtask timeout, so one slow child can no longer blanket-block the
881
- * whole plan — only that subtask (and its real dependents) is affected.
970
+ * The timer remains a full settlement guarantee, not just an abort hint: if the
971
+ * child activation ignores its abort signal, or never settles at all, the race
972
+ * below still resolves, the subtask is recorded as blocked, and the dispatcher
973
+ * keeps scheduling the rest of the DAG.
882
974
  */
883
- async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
884
- const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
975
+ async function runSubtaskAttempt(
976
+ ctx: any,
977
+ record: any,
978
+ stage: any,
979
+ subtask: any,
980
+ options: any,
981
+ timeoutMs: number,
982
+ ) {
885
983
  const child = createChildController(options.parentSignal)
886
984
  const guard: SubtaskGuard = { timedOut: false }
887
985
  let timer: ReturnType<typeof setTimeout> | null = null
986
+ let ceilingFired = false
987
+ // [1.10.6] What the ceiling left on disk, in the words of the same probe the
988
+ // blocked row records. The retry is compared against exactly this list.
989
+ let ceilingLanded: string[] = []
990
+ /*
991
+ * [1.10.6] Snapshot taken *at the moment the ceiling fires*, not later.
992
+ *
993
+ * The first cut of this check fingerprinted the same refs twice, back to back,
994
+ * immediately before the retry. Two reads of the same instant can never
995
+ * differ, so the conflict branch was unreachable in production (only a test
996
+ * injecting a mutating `stat` could reach it). The record must be taken while
997
+ * the timeout is being recorded; the pre-retry read is compared against it.
998
+ */
999
+ let ceilingFingerprint: any[] = []
1000
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
888
1001
  const deadlinePromise = new Promise<void>((resolve) => {
889
1002
  timer = setTimeout(() => {
1003
+ ceilingFired = true
890
1004
  guard.timedOut = true
891
1005
  // Reached only when the child ignored both its idle window and its
892
1006
  // abort signal; the message says so, otherwise the cause looks like a
893
1007
  // plain "too slow" and the next investigation goes down the wrong path.
894
- const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`
1008
+ const message = `子任务 ${subtask.id} 达到执行上限(${timeoutMs}ms),已强制结束`
895
1009
  try {
896
1010
  // [1.8.19] Keep the evidence of what already landed on disk.
897
- const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
1011
+ const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
1012
+ ceilingLanded = Array.isArray(landed) ? landed : []
1013
+ ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat)
898
1014
  record.statuses = applyStatus(record.statuses, subtask.id, patch)
899
1015
  record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
900
1016
  record.updatedAt = Date.now()
@@ -910,13 +1026,13 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
910
1026
  child.disposeListener()
911
1027
  resolve()
912
1028
  }
913
- }, childTimeoutMs)
1029
+ }, timeoutMs)
914
1030
  timer.unref?.()
915
1031
  })
916
1032
  try {
917
1033
  // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
918
1034
  // swallowing it here is why an interrupted child looked like any failure.
919
- return await Promise.race([
1035
+ const outcome = await Promise.race([
920
1036
  executeSubtask(ctx, record, stage, subtask, {
921
1037
  ...options,
922
1038
  child,
@@ -924,6 +1040,7 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
924
1040
  }),
925
1041
  deadlinePromise,
926
1042
  ])
1043
+ return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint }
927
1044
  } finally {
928
1045
  if (timer) {
929
1046
  clearTimeout(timer)
@@ -934,6 +1051,88 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
934
1051
  }
935
1052
  }
936
1053
 
1054
+ /*
1055
+ * Runs one subtask, retrying **once** when the per-subtask ceiling fired and the
1056
+ * round budget can still pay for a second attempt (T6 G1/G3/G4).
1057
+ *
1058
+ * The retry is deliberately narrow:
1059
+ * - only the ceiling (`CHILD_TIMEOUT`) qualifies; a user abort and a round
1060
+ * budget timeout stay non-retryable, because retrying them would be killed by
1061
+ * the same guillotine;
1062
+ * - at most one retry (`attemptOffset: 2` caps the inner loop at a single run);
1063
+ * - before it starts, the artifacts the first attempt landed are fingerprinted
1064
+ * (path + size + mtime) and re-checked. If any of them changed since the
1065
+ * timeout was recorded, something else owns that file now: the retry is
1066
+ * skipped and the row is marked `artifactConflict` instead of overwriting it.
1067
+ */
1068
+ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
1069
+ const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
1070
+ const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs)
1071
+ if (!first.ceilingFired) return first.outcome
1072
+
1073
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
1074
+ const now = Date.now()
1075
+ const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs
1076
+ const remaining = deadline - now
1077
+ const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms)`
1078
+ /*
1079
+ * [1.8.6] A parent abort outranks a retry: the round is being stopped on
1080
+ * purpose, and a second child would only be aborted on arrival.
1081
+ */
1082
+ if (options.parentSignal?.aborted) return first.outcome
1083
+ if (!shouldRetryAttempt({ code: 'CHILD_TIMEOUT', message }, 1, remaining, idleTimeoutMs)) {
1084
+ record.errors = [
1085
+ ...(record.errors ?? []),
1086
+ `${subtask.id}: 达到执行上限,剩余预算 ${Math.max(0, Math.round(remaining / 1000))}s 不足,未重试`,
1087
+ ].slice(-20)
1088
+ return first.outcome
1089
+ }
1090
+ /*
1091
+ * [1.10.6] T6 G3: never retry over work that already exists.
1092
+ *
1093
+ * `ceilingFingerprint` was taken the moment the ceiling fired (inside the
1094
+ * timeout callback); the same refs are re-read right before the retry starts.
1095
+ * A size or mtime difference means the file was written by somebody else in
1096
+ * between, so a retry would overwrite it rather than finish it.
1097
+ */
1098
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
1099
+ const current = fingerprintArtifacts(first.ceilingLanded, options.cwd, stat)
1100
+ const conflicts = diffArtifactFingerprints(first.ceilingFingerprint, current)
1101
+ const row: any = Array.isArray(record.statuses)
1102
+ ? record.statuses.find((item: any) => item.subtaskId === subtask.id)
1103
+ : null
1104
+ if (conflicts.length > 0) {
1105
+ const note = `重试前核对发现已落盘产物在超时后被改动(${conflicts.join('、')}),为避免覆盖已跳过自动重试,请人工核对`
1106
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1107
+ artifactConflict: conflicts,
1108
+ error: truncate(`${truncate(String(row?.error ?? message), 1500)};${note}`, 2000),
1109
+ })
1110
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${note}`].slice(-20)
1111
+ record.updatedAt = Date.now()
1112
+ return first.outcome
1113
+ }
1114
+
1115
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1116
+ status: 'in_progress',
1117
+ progress: 15,
1118
+ // Clearing `error` moves the timeout text to `lastError` (applyStatus does
1119
+ // that move), so the row no longer claims "blocked" while it is retrying.
1120
+ error: null,
1121
+ })
1122
+ record.errors = [
1123
+ ...(record.errors ?? []),
1124
+ `${subtask.id}: 第 1 次执行达到上限(CHILD_TIMEOUT),已核对产物无冲突,自动重试一次`,
1125
+ ].slice(-20)
1126
+ record.updatedAt = Date.now()
1127
+ const retryTimeoutMs = Math.max(MIN_CHILD_TIMEOUT_MS, Math.min(childTimeoutMs, remaining))
1128
+ const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
1129
+ ...options,
1130
+ attemptOffset: 2,
1131
+ priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已强制结束` },
1132
+ }, retryTimeoutMs)
1133
+ return second.outcome
1134
+ }
1135
+
937
1136
  async function runWithConcurrency(items: any, limit: any, worker: any) {
938
1137
  let cursor = 0
939
1138
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
@@ -1081,7 +1280,13 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1081
1280
  `第 ${record.resumeCount} 次续跑:已重置 ${resume.failed} 个受阻子任务(已完成的不重跑)`,
1082
1281
  ].slice(-20)
1083
1282
  } else {
1084
- record.errors = (record.errors ?? []).filter((line: string) => !/预算|续跑/.test(String(line))).slice(-20)
1283
+ /*
1284
+ * [1.10.4] 保留自动续跑的审计行:它们必然含「续跑/预算」字样,旧过滤器
1285
+ * 会把「为什么自动续跑、停在哪个判定码」一起擦掉,正好毁掉事后取证。
1286
+ */
1287
+ record.errors = (record.errors ?? [])
1288
+ .filter((line: string) => !/预算|续跑/.test(String(line)) || String(line).includes('[auto-resume]'))
1289
+ .slice(-20)
1085
1290
  }
1086
1291
  }
1087
1292
  const parentSignal = signal
@@ -1164,6 +1369,9 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1164
1369
  conversationContext,
1165
1370
  strictEvidence: options.strictEvidence,
1166
1371
  artifactExists: options.artifactExists,
1372
+ // [1.10.6] Injectable stat for the pre-retry fingerprint check; tests
1373
+ // use it so the conflict branch is provable without real files.
1374
+ artifactStat: options.artifactStat,
1167
1375
  })
1168
1376
  // [1.8.6] Remember which failures were interrupts, so the cascade below
1169
1377
  // can leave their dependents pending instead of blaming them.
@@ -1419,7 +1627,19 @@ function serialisePlan(record: any, session: any) {
1419
1627
  : plan
1420
1628
  ? createStatuses(plan)
1421
1629
  : []
1422
- const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses)
1630
+ /*
1631
+ * [1.10.0] 分母来自计划定义,并允许「明细行少于定义」时按 pending 补齐。
1632
+ * `definedSubtaskCount` 对畸形计划返回 MAX_SAFE_INTEGER,那种情况下退回
1633
+ * 「只数明细行」,避免把一个坏计划直接判成 0/天文数字。
1634
+ */
1635
+ const defined = plan ? definedSubtaskCount(plan) : 0
1636
+ const expectedTotal = Number.isFinite(defined) && defined > 0 && defined < Number.MAX_SAFE_INTEGER
1637
+ ? defined
1638
+ : undefined
1639
+ const snapshot = derivePlanSnapshot(
1640
+ turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses,
1641
+ expectedTotal,
1642
+ )
1423
1643
  const statuses = snapshot.statuses
1424
1644
  const stats = snapshot.stats
1425
1645
  /*
@@ -1481,7 +1701,18 @@ function serialisePlan(record: any, session: any) {
1481
1701
  ...(violations.length ? { violations } : {}),
1482
1702
  degraded: record.degraded === true,
1483
1703
  error: record.error ? truncate(record.error, 2000) : null,
1484
- errors: (record.errors ?? []).slice(-20),
1704
+ /*
1705
+ * [1.10.0] C-18:「已结束 / 已完成」的计划不再把上一轮的失败文本摆在首页。
1706
+ *
1707
+ * 1.9.1 把 `record.errors`("本轮执行预算已到:已完成 9/13…" 之类)无条件
1708
+ * 下发,界面又无条件渲染,于是 13/13 完成的那一帧下面还挂着一句「这件事没有
1709
+ * 做完」。现在:计划已 done 或 cancelled 时,这批文本改挂 `archivedErrors`,
1710
+ * 供折叠区/审计使用;`errors` 只在计划仍需处理时下发。
1711
+ */
1712
+ errors: phase === 'done' || phase === 'cancelled' ? [] : (record.errors ?? []).slice(-20),
1713
+ ...(phase === 'done' || phase === 'cancelled'
1714
+ ? { archivedErrors: (record.errors ?? []).slice(-20) }
1715
+ : {}),
1485
1716
  createdAt: record.createdAt ?? plan?.createdAt ?? session.header.createdAt,
1486
1717
  updatedAt: record.updatedAt ?? Date.now(),
1487
1718
  createdTurn: plan?.createdTurn ?? record.createdTurn ?? null,
@@ -2023,6 +2254,16 @@ export type WorkplanRuntimeOptions = {
2023
2254
  totalTimeoutMs?: number
2024
2255
  /** How many times a blocked plan may be resumed. */
2025
2256
  maxResumes?: number
2257
+ /**
2258
+ * [1.10.4] 整轮预算到点后自动开始下一轮。**默认关闭**:默认值来自
2259
+ * `AUTO_RESUME_DEFAULTS.enabled=false`,必须由宿主显式打开。
2260
+ *
2261
+ * 它只续跑 `paused`(预算到点)的计划,不动 `blocked`(真实失败),
2262
+ * 也不重跑任何 `done` 项;自动续跑本身不做任何证据判定。
2263
+ */
2264
+ autoResume?: boolean
2265
+ /** 自动续跑轮次上限(0–4,默认 2)。 */
2266
+ autoResumeMaxAttempts?: number
2026
2267
  /**
2027
2268
  * [1.8.13] Package version, supplied by the host from its `meta.version`.
2028
2269
  *
@@ -2104,6 +2345,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2104
2345
  maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
2105
2346
  ? Math.min(5, Math.floor(Number(options.maxResumes)))
2106
2347
  : MAX_PLAN_RESUMES,
2348
+ autoResume: {
2349
+ enabled: options.autoResume === true,
2350
+ maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
2351
+ },
2107
2352
  }
2108
2353
 
2109
2354
  async function onPreStep(payload: any, next: any) {
@@ -2190,6 +2435,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2190
2435
  if (!record?.plan) record = reconstructFromSession(session, args?.planId)
2191
2436
  record = adoptRequestedPlan(session, record, args?.planId)
2192
2437
  if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
2438
+ // [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
2439
+ clearAutoResumeTimer(record, 'manual-update')
2193
2440
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : ''
2194
2441
  if (!subtaskId) throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK')
2195
2442
  const status = typeof args?.status === 'string' ? args.status : ''
@@ -2380,6 +2627,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2380
2627
  const reason = typeof args?.reason === 'string' && args.reason.trim()
2381
2628
  ? args.reason.trim()
2382
2629
  : '用户取消'
2630
+ // [1.10.4] 取消是终态:必须撤销已排期的自动续跑,否则定时器会在取消之后复活计划。
2631
+ clearAutoResumeTimer(record, 'cancelled')
2383
2632
  /*
2384
2633
  * [1.5.2] 已完成即终态:取消不再把 100% 的计划改写成「已取消」。
2385
2634
  *
@@ -2511,6 +2760,218 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2511
2760
  }
2512
2761
  }
2513
2762
 
2763
+ /*
2764
+ * [1.10.4][auto-resume] 自动续跑的记账与排期。
2765
+ *
2766
+ * 为什么在工具层而不是 `dispatchPlan` 里:被整轮预算中止时,这一轮已经没有
2767
+ * 预算可用,轮内重试必然再被同一把闸刀砍掉(`shouldRetryAttempt` 对
2768
+ * `TOTAL_TIMEOUT` / `ABORTED` 恒为 false 是正确的)。能重试的只有「下一轮」:
2769
+ * 新预算、新截止时间,未完成项由 `resetBlockedStatuses` 放回 pending,
2770
+ * done 项永不重跑。所以调度点属于「谁结束了一轮」,也就是这里。
2771
+ *
2772
+ * 所有停止分支都由纯函数 `decideAutoResume` 判定,本层只负责:
2773
+ * - 记录 done 水位与连续无进展轮数(防止空转);
2774
+ * - 用 unref 的定时器排期,并在取消/人工派发/进程销毁时撤销;
2775
+ * - 起跑前再核对一次记录身份与阶段(定时器期间状态可能已变)。
2776
+ */
2777
+ function autoResumeBook(record: any) {
2778
+ if (!record.autoResume || typeof record.autoResume !== 'object') {
2779
+ record.autoResume = {
2780
+ attempt: 0,
2781
+ noProgressRounds: 0,
2782
+ doneBefore: null,
2783
+ nextAt: null,
2784
+ timer: null,
2785
+ lastDecision: null,
2786
+ history: [],
2787
+ }
2788
+ }
2789
+ return record.autoResume
2790
+ }
2791
+
2792
+ function clearAutoResumeTimer(record: any, reason: string) {
2793
+ const book = record?.autoResume
2794
+ if (!book) return false
2795
+ book.nextAt = null
2796
+ if (!book.timer) return false
2797
+ clearTimeout(book.timer)
2798
+ book.timer = null
2799
+ book.lastStopReason = reason
2800
+ return true
2801
+ }
2802
+
2803
+ function autoResumeView(record: any) {
2804
+ const book = record?.autoResume
2805
+ return {
2806
+ enabled: limits.autoResume.enabled,
2807
+ attempt: Number(book?.attempt ?? 0),
2808
+ maxAttempts: limits.autoResume.maxAttempts,
2809
+ armed: Boolean(book?.timer),
2810
+ nextInMs: book?.nextAt ? Math.max(0, Number(book.nextAt) - Date.now()) : null,
2811
+ lastCode: book?.lastDecision?.code ?? null,
2812
+ lastReason: book?.lastDecision?.reason ?? null,
2813
+ lastStopReason: book?.lastStopReason ?? null,
2814
+ }
2815
+ }
2816
+
2817
+ /**
2818
+ * 在一轮结束后决定是否再开一轮。
2819
+ *
2820
+ * @param record - 当前计划记录。
2821
+ * @param session - 根会话(结果消息与子 Agent 都归属它)。
2822
+ * @param base - 本轮派发的可复用参数(agent / modelSelection / cwd / conversationContext)。
2823
+ */
2824
+ function armAutoResume(record: any, session: any, base: any) {
2825
+ const book = autoResumeBook(record)
2826
+ clearAutoResumeTimer(record, 'rearmed')
2827
+ const snapshot = derivePlanSnapshot(record.statuses)
2828
+ const stats: any = snapshot.stats ?? {}
2829
+ const statuses: any[] = Array.isArray(record.statuses) ? record.statuses : []
2830
+ const done = Number(stats.done ?? 0)
2831
+ const doneBefore = Number.isFinite(Number(book.doneBefore)) ? Number(book.doneBefore) : done
2832
+ /*
2833
+ * 「有进展」只认新增的 done 行。被预算中止的子任务会把 error 从 pending
2834
+ * 一路写到重置,只有真正完成才会抬高 done;用 done 作水位既不会把
2835
+ * 「重跑一次又失败」误判成进展,也不会因错误文案变化而空转。
2836
+ */
2837
+ if (done > doneBefore) book.noProgressRounds = 0
2838
+ else if (Number(book.attempt ?? 0) > 0) book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1
2839
+ book.doneBefore = done
2840
+ const pending = statuses.filter((item: any) => item?.status === 'pending').length
2841
+ const blocked = statuses.filter((item: any) => item?.status === 'blocked').length
2842
+ /*
2843
+ * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
2844
+ *
2845
+ * T7 实测:`armAutoResume` 在每一轮结束后都会被调用,正常完成的轮也会走到
2846
+ * `PHASE_NOT_PAUSED` 分支,于是每个顺利结束的计划都在 `record.errors` 里多一条
2847
+ * 「[auto-resume] 停止」——把真正需要看的中止信息埋掉。全部 done 且没有
2848
+ * pending/blocked 时,直接静默收尾,不写台账。
2849
+ */
2850
+ if (Number(stats.total ?? 0) > 0 && pending === 0 && blocked === 0 && done === Number(stats.total ?? 0)) {
2851
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code: 'NOTHING_PENDING', reason: '全部子任务已 done,无需自动续跑' }
2852
+ return book.lastDecision
2853
+ }
2854
+ const decision = decideAutoResume({
2855
+ enabled: limits.autoResume.enabled,
2856
+ phase: record.phase,
2857
+ cancelled: record.cancelled === true,
2858
+ degraded: record.degraded === true,
2859
+ planMode: isPlanModeActive(ctx, session),
2860
+ running: Boolean(record.dispatchPromise),
2861
+ total: Number(stats.total ?? 0),
2862
+ done,
2863
+ pending,
2864
+ blocked,
2865
+ attempt: Number(book.attempt ?? 0),
2866
+ maxAttempts: limits.autoResume.maxAttempts,
2867
+ noProgressRounds: Number(book.noProgressRounds ?? 0),
2868
+ stallLimit: AUTO_RESUME_DEFAULTS.stallLimit,
2869
+ baseDelayMs: AUTO_RESUME_DEFAULTS.baseDelayMs,
2870
+ maxDelayMs: AUTO_RESUME_DEFAULTS.maxDelayMs,
2871
+ })
2872
+ book.lastDecision = { at: Date.now(), phase: record.phase, ...decision }
2873
+ book.history = [...(book.history ?? []), {
2874
+ at: Date.now(),
2875
+ phase: record.phase,
2876
+ done,
2877
+ pending,
2878
+ blocked,
2879
+ attempt: Number(book.attempt ?? 0),
2880
+ action: decision.action,
2881
+ code: decision.code,
2882
+ }].slice(-10)
2883
+ if (decision.action !== 'schedule') {
2884
+ /*
2885
+ * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
2886
+ * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
2887
+ */
2888
+ if (decision.code !== 'AUTO_RESUME_DISABLED') {
2889
+ record.errors = [...(record.errors ?? []),
2890
+ `[auto-resume] 停止(${decision.code}):${decision.reason}`].slice(-20)
2891
+ }
2892
+ return decision
2893
+ }
2894
+ const attempt = Number(book.attempt ?? 0) + 1
2895
+ book.attempt = attempt
2896
+ book.nextAt = Date.now() + decision.delayMs
2897
+ record.errors = [...(record.errors ?? []),
2898
+ `[auto-resume] 已排期第 ${attempt}/${limits.autoResume.maxAttempts} 次自动续跑:`
2899
+ + `${Math.round(decision.delayMs / 1000)}s 后开始(本轮预算到点,仍有 ${pending} 项 pending;done 项不重跑)`].slice(-20)
2900
+ const timer = setTimeout(() => {
2901
+ book.timer = null
2902
+ book.nextAt = null
2903
+ try {
2904
+ /*
2905
+ * 排期到点后逐项复核,任何一项不成立都安静退出:定时器活过了一个
2906
+ * 回合,期间用户可能已经取消、主 Agent 可能已经手动派发、页面可能
2907
+ * 已经换了一份计划记录。
2908
+ */
2909
+ /*
2910
+ * [1.10.4 / D1] 复核失败必须留下停止码。
2911
+ *
2912
+ * T5 的 I9:任何一次「本应自动续跑却没有发生」都要可解释。原先这里五个
2913
+ * 分支全是裸 `return`,计划停在 paused 而台账里没有任何痕迹,用户只能再
2914
+ * 做一次考古。现在每个分支都写 `lastStopReason`,并把原因追加到 history。
2915
+ */
2916
+ const stopTimer = (code: string) => {
2917
+ book.lastStopReason = code
2918
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code, reason: '定时器复核未通过' }
2919
+ book.history = [...(book.history ?? []), {
2920
+ at: Date.now(), phase: record.phase, action: 'stop', code,
2921
+ }].slice(-10)
2922
+ return
2923
+ }
2924
+ if (state.records.get(session.id) !== record) return stopTimer('SCHEDULE_REVOKED_RECORD_REPLACED')
2925
+ if (record.dispatchPromise) return stopTimer('SCHEDULE_REVOKED_ALREADY_RUNNING')
2926
+ if (record.cancelled === true) return stopTimer('CANCELLED')
2927
+ if (isTerminalPhase(record.phase)) return stopTimer('PHASE_TERMINAL')
2928
+ if (isPlanModeActive(ctx, session)) return stopTimer('PLAN_MODE')
2929
+ if (record.phase !== 'paused') return stopTimer('PHASE_NOT_PAUSED')
2930
+ const live = derivePlanSnapshot(record.statuses)
2931
+ const livePending = (record.statuses ?? []).filter((item: any) => item?.status === 'pending').length
2932
+ if (Number(live.stats?.total ?? 0) === 0 || livePending === 0) return stopTimer('NOTHING_PENDING')
2933
+ const controller = new AbortController()
2934
+ record.abortRequested = false
2935
+ record.abortDispatch = (reason: string) => {
2936
+ if (!controller.signal.aborted) controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
2937
+ }
2938
+ record.dispatchStartedAt = Date.now()
2939
+ // 新一轮必须写一条新的结果消息,否则主 Agent 永远看不到自动续跑的结局。
2940
+ record.resultWritten = false
2941
+ book.doneBefore = Number(live.stats?.done ?? 0)
2942
+ record.dispatchPromise = dispatchPlan(ctx, record, {
2943
+ ...base,
2944
+ signal: controller.signal,
2945
+ childTimeoutMs: limits.childTimeoutMs,
2946
+ idleTimeoutMs: limits.idleTimeoutMs,
2947
+ totalTimeoutMs: limits.totalTimeoutMs,
2948
+ maxResumes: limits.maxResumes,
2949
+ })
2950
+ .then(() => finishRound(record, session))
2951
+ .catch((error: any) => {
2952
+ pushRecordError(record, error)
2953
+ finishRound(record, session)
2954
+ })
2955
+ .finally(() => {
2956
+ record.dispatchPromise = null
2957
+ record.dispatchStartedAt = null
2958
+ record.abortDispatch = null
2959
+ armAutoResume(record, session, base)
2960
+ })
2961
+ ctx.logger?.warn?.(
2962
+ `dsh-workplan: 计划 ${record.plan?.planId ?? '?'} 自动续跑第 ${attempt}/${limits.autoResume.maxAttempts} 轮已开始`
2963
+ + `(remaining ${Number(live.stats?.total ?? 0) - Number(live.stats?.done ?? 0)})`,
2964
+ )
2965
+ } catch (error) {
2966
+ pushRecordError(record, error)
2967
+ ctx.logger?.warn?.(`dsh-workplan: 自动续跑失败:${error instanceof Error ? error.message : String(error)}`)
2968
+ }
2969
+ }, decision.delayMs)
2970
+ timer.unref?.()
2971
+ book.timer = timer
2972
+ return decision
2973
+ }
2974
+
2514
2975
  /**
2515
2976
  * Persist the round result and settle the phase.
2516
2977
  *
@@ -2642,6 +3103,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2642
3103
  statuses: modelStatusLines(snapshot.statuses),
2643
3104
  errors: (record.errors ?? []).slice(-10),
2644
3105
  resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
3106
+ // [1.10.4] 自动续跑的可观测面:开关、已用轮次、是否已排期、上一次判定码。
3107
+ autoResume: autoResumeView(record),
2645
3108
  deliveryReady: readiness.ready,
2646
3109
  deliveryBlockers: readiness.blockers.slice(0, 12),
2647
3110
  deliveryRemaining: readiness.remaining.slice(0, 20),
@@ -2760,6 +3223,18 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2760
3223
  }
2761
3224
  }
2762
3225
  if (!record?.plan) throw new PlanError('当前会话没有可派发的计划', 'NO_PLAN')
3226
+ /*
3227
+ * [1.10.4] 人工/工具派发优先于自动续跑:撤销待触发的定时器,并把自动
3228
+ * 轮次计数归零(这一次是外部授权的新起点)。done 水位取当前值,下一轮
3229
+ * 结束后才能正确判断「有没有新增完成项」。
3230
+ */
3231
+ clearAutoResumeTimer(record, 'manual-dispatch')
3232
+ {
3233
+ const book = autoResumeBook(record)
3234
+ book.attempt = 0
3235
+ book.noProgressRounds = 0
3236
+ book.doneBefore = Number(derivePlanSnapshot(record.statuses).stats?.done ?? 0)
3237
+ }
2763
3238
  if (args?.planId && record.plan.planId !== args.planId) {
2764
3239
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
2765
3240
  }
@@ -2914,12 +3389,15 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2914
3389
  dispatchController.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
2915
3390
  }
2916
3391
  }
2917
- record.dispatchPromise = dispatchPlan(ctx, record, {
3392
+ const roundOptions = {
2918
3393
  agent,
2919
- signal: dispatchController.signal,
2920
3394
  modelSelection: selection.provider && selection.model ? selection : record.modelSelection,
2921
3395
  cwd: session.header?.cwd ?? options.cwd,
2922
3396
  conversationContext: record.conversationContext ?? '',
3397
+ }
3398
+ record.dispatchPromise = dispatchPlan(ctx, record, {
3399
+ ...roundOptions,
3400
+ signal: dispatchController.signal,
2923
3401
  childTimeoutMs: limits.childTimeoutMs,
2924
3402
  idleTimeoutMs: limits.idleTimeoutMs,
2925
3403
  totalTimeoutMs: limits.totalTimeoutMs,
@@ -2942,11 +3420,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2942
3420
  .then(() => {
2943
3421
  finishRound(record, session)
2944
3422
  state.records.set(session.id, record)
3423
+ armAutoResume(record, session, roundOptions)
2945
3424
  })
2946
3425
  .catch((error: any) => {
2947
3426
  pushRecordError(record, error)
2948
3427
  finishRound(record, session)
2949
3428
  state.records.set(session.id, record)
3429
+ armAutoResume(record, session, roundOptions)
2950
3430
  })
2951
3431
  const live = derivePlanSnapshot(record.statuses)
2952
3432
  return {
@@ -2967,6 +3447,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2967
3447
  }
2968
3448
  await record.dispatchPromise
2969
3449
  finishRound(record, session)
3450
+ armAutoResume(record, session, roundOptions)
2970
3451
  /*
2971
3452
  * The model's dispatch result reports the same snapshot the dashboard will
2972
3453
  * show. It used to send `record.stats` while the status list below was read
@@ -3747,6 +4228,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3747
4228
  }
3748
4229
 
3749
4230
  function dispose() {
4231
+ // [1.10.4] 定时器不能吊住进程,也不能在记录清空后复活一个已销毁的计划。
4232
+ for (const record of state.records.values()) clearAutoResumeTimer(record, 'dispose')
3750
4233
  state.records.clear()
3751
4234
  }
3752
4235