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/lib/runtime.js CHANGED
@@ -12,12 +12,13 @@
12
12
  * in this file is allowed to escape as an unhandled rejection from a listener.
13
13
  */
14
14
  import { randomUUID } from 'node:crypto';
15
- import { existsSync } from 'node:fs';
15
+ import { existsSync, statSync } from 'node:fs';
16
16
  import { isAbsolute, resolve } from 'node:path';
17
17
  import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
18
18
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
19
19
  import { supersedePlanRecord } from './supersede.js';
20
20
  import { createProgressWatchdog, describeError } from './watchdog.js';
21
+ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js';
21
22
  /**
22
23
  * [1.8.18] How many subtasks the plan *defines*.
23
24
  *
@@ -483,6 +484,67 @@ export function probeInterruptedEvidence(output, subtask, cwd, artifactExists =
483
484
  const missingArtifacts = declared.filter((ref) => !landed.includes(ref));
484
485
  return { artifacts, missingArtifacts };
485
486
  }
487
+ /**
488
+ * [1.10.6] Fingerprint the files a timed-out attempt already wrote.
489
+ *
490
+ * T6 (G3) found that the retry decision never looked at the disk: a second
491
+ * attempt could silently overwrite a deliverable the first attempt had already
492
+ * produced, turning "the child stopped early" into "the deliverable was
493
+ * rewritten". This snapshot (path + size + mtime) is the record the retry is
494
+ * compared against.
495
+ *
496
+ * A missing file is not a conflict — it simply has no fingerprint. `stat` is
497
+ * injectable so the check can be tested without touching the real filesystem.
498
+ */
499
+ export function fingerprintArtifacts(refs, cwd, stat = statSync) {
500
+ const list = Array.isArray(refs) ? refs : [];
501
+ const out = [];
502
+ const seen = new Set();
503
+ for (const item of list) {
504
+ const ref = typeof item === 'string' ? item.trim() : '';
505
+ if (!ref || seen.has(ref))
506
+ continue;
507
+ seen.add(ref);
508
+ const target = resolveArtifactPath(ref, cwd);
509
+ if (!target)
510
+ continue;
511
+ try {
512
+ const info = stat(target);
513
+ if (!info)
514
+ continue;
515
+ out.push({ ref, size: Number(info.size), mtimeMs: Number(info.mtimeMs) });
516
+ }
517
+ catch {
518
+ // Missing or unreadable: nothing to protect, and not a conflict.
519
+ }
520
+ }
521
+ return out;
522
+ }
523
+ /**
524
+ * [1.10.6] Which landed artifacts changed since the snapshot was taken.
525
+ *
526
+ * Size or mtime differing is enough to call it a conflict: the file the first
527
+ * attempt produced is no longer the file on disk, so a retry that rewrites it
528
+ * would destroy work rather than finish it.
529
+ */
530
+ export function diffArtifactFingerprints(before, after) {
531
+ const previous = new Map();
532
+ for (const item of Array.isArray(before) ? before : []) {
533
+ if (item && typeof item.ref === 'string')
534
+ previous.set(item.ref, item);
535
+ }
536
+ const conflicts = [];
537
+ for (const item of Array.isArray(after) ? after : []) {
538
+ if (!item || typeof item.ref !== 'string')
539
+ continue;
540
+ const recorded = previous.get(item.ref);
541
+ if (!recorded)
542
+ continue;
543
+ if (recorded.size !== item.size || recorded.mtimeMs !== item.mtimeMs)
544
+ conflicts.push(item.ref);
545
+ }
546
+ return conflicts;
547
+ }
486
548
  /**
487
549
  * [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
488
550
  */
@@ -582,16 +644,38 @@ function settleFromOutput(record, subtask, output, guard, options) {
582
644
  * Retry policy for one child attempt.
583
645
  *
584
646
  * A wedged child (no event for the whole idle window) is worth one fresh
585
- * attempt. A hard ceiling means the budget is gone, and an abort is a decision,
586
- * so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
587
- * more than one idle window left, otherwise the retry itself would just be
588
- * killed by the same watchdog.
647
+ * attempt. `CHILD_NOT_COMPLETED` is retried only while there is more than one
648
+ * idle window left, otherwise the retry itself would just be killed by the same
649
+ * watchdog.
650
+ *
651
+ * [1.10.3] 单个子任务撞上 900 秒硬上限时,只要整轮预算还够再跑一轮,就自动重试
652
+ * 一次。用户 2026-11-01 的质疑是对的:此前这一支被无条件 `return false`,
653
+ * 于是「预算没花完、只是这一步慢了」也被判成阻塞,必须等主 Agent 人工改判或
654
+ * 重新派发——而 `attempt` 已经是 1、产物又都在盘上,重跑一次往往就能过。
655
+ *
656
+ * 仍然**不自动重试**的两种情况,理由不变:
657
+ * - `TOTAL_TIMEOUT`:整轮预算已经用光,重试必然再被同一把闸刀砍掉,只会空耗;
658
+ * - `ABORTED`:那是「有人决定停」而不是「跑不完」,自动重来等于违背决定。
589
659
  */
590
660
  export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
591
661
  if (attempt >= 2)
592
662
  return false;
593
663
  const code = error?.code;
594
- if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT')
664
+ if (code === 'CHILD_TIMEOUT') {
665
+ /*
666
+ * 重试要有意义,必须给它留够「至少再跑一次短任务」的时间。
667
+ *
668
+ * [1.10.6] 这里**不能**再拿空闲窗口当门槛(旧式 `max(idle, 120s)`):
669
+ * 出厂配置是 ceiling=900s / idle=300s / round=1200s,撞上限后剩下约
670
+ * 300s,而 `remaining > 300s` 恒为假——用户要的「有预算就自动重试一次」
671
+ * 会在默认配置下永远不触发,正是 T6 记录的那类「策略说会、链路不会」。
672
+ * 固定 120s 是「够跑一次短任务」的下限,同时保证不会刚重试就被砍掉。
673
+ * `tests/workplan-retry-feedback.test.ts` 的 60s 反例与 600s 正例都仍然成立。
674
+ */
675
+ const floor = 120000;
676
+ return Number(remainingMs) > floor;
677
+ }
678
+ if (code === 'ABORTED' || code === 'TOTAL_TIMEOUT')
595
679
  return false;
596
680
  if (/aborted|refusal/i.test(String(error?.message ?? '')))
597
681
  return false;
@@ -605,7 +689,17 @@ export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
605
689
  async function executeSubtask(ctx, record, stage, subtask, options) {
606
690
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
607
691
  let lastError = null;
608
- let lastFailure = null;
692
+ /*
693
+ * [1.10.6] A retry that starts after a *ceiling* timeout is a second attempt
694
+ * even though this function is entered afresh. `attemptOffset` keeps the
695
+ * numbering honest (`第 2 次尝试`) and, with the loop condition below, keeps
696
+ * the cap at two real activations instead of letting the new call spend its
697
+ * own two.
698
+ */
699
+ const firstAttempt = Number.isInteger(options.attemptOffset) && options.attemptOffset > 1
700
+ ? options.attemptOffset
701
+ : 1;
702
+ let lastFailure = options.priorFailure ?? null;
609
703
  /*
610
704
  * [1.8.6] The interrupt has to outlive the thrown error.
611
705
  *
@@ -622,7 +716,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
622
716
  startedAt: Date.now(),
623
717
  }, guard))
624
718
  return;
625
- for (let attempt = 1; attempt <= 2; attempt += 1) {
719
+ for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
626
720
  if (guard.timedOut)
627
721
  return;
628
722
  interruptedEvidence = null;
@@ -786,7 +880,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
786
880
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
787
881
  continue;
788
882
  }
789
- if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
883
+ /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
884
+ if (!isAbort && remaining <= idleTimeoutMs) {
790
885
  record.errors = [
791
886
  ...(record.errors ?? []),
792
887
  `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
@@ -839,30 +934,50 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
839
934
  }
840
935
  }
841
936
  /*
842
- * Runs one subtask under a deadline that belongs to that subtask alone.
937
+ * One attempt under a deadline that belongs to that attempt alone.
938
+ *
939
+ * [1.10.6] Split out of `runSubtask` so a ceiling timeout can be retried with a
940
+ * *fresh* timer. The old code armed a single timer for the whole subtask (shared
941
+ * by both attempts), so even once the retry decision became reachable the second
942
+ * attempt would have had no time left — a patch that changes nothing.
843
943
  *
844
- * The subtask timer is a full settlement guarantee, not just an abort hint: if
845
- * the child activation ignores its abort signal, or never settles at all, the
846
- * race below still resolves, that subtask is recorded as blocked, and the
847
- * dispatcher keeps scheduling the rest of the DAG. This function never throws
848
- * on a per-subtask timeout, so one slow child can no longer blanket-block the
849
- * whole plan — only that subtask (and its real dependents) is affected.
944
+ * The timer remains a full settlement guarantee, not just an abort hint: if the
945
+ * child activation ignores its abort signal, or never settles at all, the race
946
+ * below still resolves, the subtask is recorded as blocked, and the dispatcher
947
+ * keeps scheduling the rest of the DAG.
850
948
  */
851
- async function runSubtask(ctx, record, stage, subtask, options) {
852
- const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
949
+ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs) {
853
950
  const child = createChildController(options.parentSignal);
854
951
  const guard = { timedOut: false };
855
952
  let timer = null;
953
+ let ceilingFired = false;
954
+ // [1.10.6] What the ceiling left on disk, in the words of the same probe the
955
+ // blocked row records. The retry is compared against exactly this list.
956
+ let ceilingLanded = [];
957
+ /*
958
+ * [1.10.6] Snapshot taken *at the moment the ceiling fires*, not later.
959
+ *
960
+ * The first cut of this check fingerprinted the same refs twice, back to back,
961
+ * immediately before the retry. Two reads of the same instant can never
962
+ * differ, so the conflict branch was unreachable in production (only a test
963
+ * injecting a mutating `stat` could reach it). The record must be taken while
964
+ * the timeout is being recorded; the pre-retry read is compared against it.
965
+ */
966
+ let ceilingFingerprint = [];
967
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync;
856
968
  const deadlinePromise = new Promise((resolve) => {
857
969
  timer = setTimeout(() => {
970
+ ceilingFired = true;
858
971
  guard.timedOut = true;
859
972
  // Reached only when the child ignored both its idle window and its
860
973
  // abort signal; the message says so, otherwise the cause looks like a
861
974
  // plain "too slow" and the next investigation goes down the wrong path.
862
- const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`;
975
+ const message = `子任务 ${subtask.id} 达到执行上限(${timeoutMs}ms),已强制结束`;
863
976
  try {
864
977
  // [1.8.19] Keep the evidence of what already landed on disk.
865
- const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
978
+ const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
979
+ ceilingLanded = Array.isArray(landed) ? landed : [];
980
+ ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat);
866
981
  record.statuses = applyStatus(record.statuses, subtask.id, patch);
867
982
  record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
868
983
  record.updatedAt = Date.now();
@@ -880,13 +995,13 @@ async function runSubtask(ctx, record, stage, subtask, options) {
880
995
  child.disposeListener();
881
996
  resolve();
882
997
  }
883
- }, childTimeoutMs);
998
+ }, timeoutMs);
884
999
  timer.unref?.();
885
1000
  });
886
1001
  try {
887
1002
  // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
888
1003
  // swallowing it here is why an interrupted child looked like any failure.
889
- return await Promise.race([
1004
+ const outcome = await Promise.race([
890
1005
  executeSubtask(ctx, record, stage, subtask, {
891
1006
  ...options,
892
1007
  child,
@@ -894,6 +1009,7 @@ async function runSubtask(ctx, record, stage, subtask, options) {
894
1009
  }),
895
1010
  deadlinePromise,
896
1011
  ]);
1012
+ return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint };
897
1013
  }
898
1014
  finally {
899
1015
  if (timer) {
@@ -905,6 +1021,87 @@ async function runSubtask(ctx, record, stage, subtask, options) {
905
1021
  child.controller.abort();
906
1022
  }
907
1023
  }
1024
+ /*
1025
+ * Runs one subtask, retrying **once** when the per-subtask ceiling fired and the
1026
+ * round budget can still pay for a second attempt (T6 G1/G3/G4).
1027
+ *
1028
+ * The retry is deliberately narrow:
1029
+ * - only the ceiling (`CHILD_TIMEOUT`) qualifies; a user abort and a round
1030
+ * budget timeout stay non-retryable, because retrying them would be killed by
1031
+ * the same guillotine;
1032
+ * - at most one retry (`attemptOffset: 2` caps the inner loop at a single run);
1033
+ * - before it starts, the artifacts the first attempt landed are fingerprinted
1034
+ * (path + size + mtime) and re-checked. If any of them changed since the
1035
+ * timeout was recorded, something else owns that file now: the retry is
1036
+ * skipped and the row is marked `artifactConflict` instead of overwriting it.
1037
+ */
1038
+ async function runSubtask(ctx, record, stage, subtask, options) {
1039
+ const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
1040
+ const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs);
1041
+ if (!first.ceilingFired)
1042
+ return first.outcome;
1043
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
1044
+ const now = Date.now();
1045
+ const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs;
1046
+ const remaining = deadline - now;
1047
+ const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms)`;
1048
+ /*
1049
+ * [1.8.6] A parent abort outranks a retry: the round is being stopped on
1050
+ * purpose, and a second child would only be aborted on arrival.
1051
+ */
1052
+ if (options.parentSignal?.aborted)
1053
+ return first.outcome;
1054
+ if (!shouldRetryAttempt({ code: 'CHILD_TIMEOUT', message }, 1, remaining, idleTimeoutMs)) {
1055
+ record.errors = [
1056
+ ...(record.errors ?? []),
1057
+ `${subtask.id}: 达到执行上限,剩余预算 ${Math.max(0, Math.round(remaining / 1000))}s 不足,未重试`,
1058
+ ].slice(-20);
1059
+ return first.outcome;
1060
+ }
1061
+ /*
1062
+ * [1.10.6] T6 G3: never retry over work that already exists.
1063
+ *
1064
+ * `ceilingFingerprint` was taken the moment the ceiling fired (inside the
1065
+ * timeout callback); the same refs are re-read right before the retry starts.
1066
+ * A size or mtime difference means the file was written by somebody else in
1067
+ * between, so a retry would overwrite it rather than finish it.
1068
+ */
1069
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync;
1070
+ const current = fingerprintArtifacts(first.ceilingLanded, options.cwd, stat);
1071
+ const conflicts = diffArtifactFingerprints(first.ceilingFingerprint, current);
1072
+ const row = Array.isArray(record.statuses)
1073
+ ? record.statuses.find((item) => item.subtaskId === subtask.id)
1074
+ : null;
1075
+ if (conflicts.length > 0) {
1076
+ const note = `重试前核对发现已落盘产物在超时后被改动(${conflicts.join('、')}),为避免覆盖已跳过自动重试,请人工核对`;
1077
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1078
+ artifactConflict: conflicts,
1079
+ error: truncate(`${truncate(String(row?.error ?? message), 1500)};${note}`, 2000),
1080
+ });
1081
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${note}`].slice(-20);
1082
+ record.updatedAt = Date.now();
1083
+ return first.outcome;
1084
+ }
1085
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1086
+ status: 'in_progress',
1087
+ progress: 15,
1088
+ // Clearing `error` moves the timeout text to `lastError` (applyStatus does
1089
+ // that move), so the row no longer claims "blocked" while it is retrying.
1090
+ error: null,
1091
+ });
1092
+ record.errors = [
1093
+ ...(record.errors ?? []),
1094
+ `${subtask.id}: 第 1 次执行达到上限(CHILD_TIMEOUT),已核对产物无冲突,自动重试一次`,
1095
+ ].slice(-20);
1096
+ record.updatedAt = Date.now();
1097
+ const retryTimeoutMs = Math.max(MIN_CHILD_TIMEOUT_MS, Math.min(childTimeoutMs, remaining));
1098
+ const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
1099
+ ...options,
1100
+ attemptOffset: 2,
1101
+ priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已强制结束` },
1102
+ }, retryTimeoutMs);
1103
+ return second.outcome;
1104
+ }
908
1105
  async function runWithConcurrency(items, limit, worker) {
909
1106
  let cursor = 0;
910
1107
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
@@ -1059,7 +1256,13 @@ export async function dispatchPlan(ctx, record, options) {
1059
1256
  ].slice(-20);
1060
1257
  }
1061
1258
  else {
1062
- record.errors = (record.errors ?? []).filter((line) => !/预算|续跑/.test(String(line))).slice(-20);
1259
+ /*
1260
+ * [1.10.4] 保留自动续跑的审计行:它们必然含「续跑/预算」字样,旧过滤器
1261
+ * 会把「为什么自动续跑、停在哪个判定码」一起擦掉,正好毁掉事后取证。
1262
+ */
1263
+ record.errors = (record.errors ?? [])
1264
+ .filter((line) => !/预算|续跑/.test(String(line)) || String(line).includes('[auto-resume]'))
1265
+ .slice(-20);
1063
1266
  }
1064
1267
  }
1065
1268
  const parentSignal = signal;
@@ -1147,6 +1350,9 @@ export async function dispatchPlan(ctx, record, options) {
1147
1350
  conversationContext,
1148
1351
  strictEvidence: options.strictEvidence,
1149
1352
  artifactExists: options.artifactExists,
1353
+ // [1.10.6] Injectable stat for the pre-retry fingerprint check; tests
1354
+ // use it so the conflict branch is provable without real files.
1355
+ artifactStat: options.artifactStat,
1150
1356
  });
1151
1357
  // [1.8.6] Remember which failures were interrupts, so the cascade below
1152
1358
  // can leave their dependents pending instead of blaming them.
@@ -1406,7 +1612,16 @@ function serialisePlan(record, session) {
1406
1612
  : plan
1407
1613
  ? createStatuses(plan)
1408
1614
  : [];
1409
- const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses);
1615
+ /*
1616
+ * [1.10.0] 分母来自计划定义,并允许「明细行少于定义」时按 pending 补齐。
1617
+ * `definedSubtaskCount` 对畸形计划返回 MAX_SAFE_INTEGER,那种情况下退回
1618
+ * 「只数明细行」,避免把一个坏计划直接判成 0/天文数字。
1619
+ */
1620
+ const defined = plan ? definedSubtaskCount(plan) : 0;
1621
+ const expectedTotal = Number.isFinite(defined) && defined > 0 && defined < Number.MAX_SAFE_INTEGER
1622
+ ? defined
1623
+ : undefined;
1624
+ const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses, expectedTotal);
1410
1625
  const statuses = snapshot.statuses;
1411
1626
  const stats = snapshot.stats;
1412
1627
  /*
@@ -1468,7 +1683,18 @@ function serialisePlan(record, session) {
1468
1683
  ...(violations.length ? { violations } : {}),
1469
1684
  degraded: record.degraded === true,
1470
1685
  error: record.error ? truncate(record.error, 2000) : null,
1471
- errors: (record.errors ?? []).slice(-20),
1686
+ /*
1687
+ * [1.10.0] C-18:「已结束 / 已完成」的计划不再把上一轮的失败文本摆在首页。
1688
+ *
1689
+ * 1.9.1 把 `record.errors`("本轮执行预算已到:已完成 9/13…" 之类)无条件
1690
+ * 下发,界面又无条件渲染,于是 13/13 完成的那一帧下面还挂着一句「这件事没有
1691
+ * 做完」。现在:计划已 done 或 cancelled 时,这批文本改挂 `archivedErrors`,
1692
+ * 供折叠区/审计使用;`errors` 只在计划仍需处理时下发。
1693
+ */
1694
+ errors: phase === 'done' || phase === 'cancelled' ? [] : (record.errors ?? []).slice(-20),
1695
+ ...(phase === 'done' || phase === 'cancelled'
1696
+ ? { archivedErrors: (record.errors ?? []).slice(-20) }
1697
+ : {}),
1472
1698
  createdAt: record.createdAt ?? plan?.createdAt ?? session.header.createdAt,
1473
1699
  updatedAt: record.updatedAt ?? Date.now(),
1474
1700
  createdTurn: plan?.createdTurn ?? record.createdTurn ?? null,
@@ -2054,6 +2280,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
2054
2280
  maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
2055
2281
  ? Math.min(5, Math.floor(Number(options.maxResumes)))
2056
2282
  : MAX_PLAN_RESUMES,
2283
+ autoResume: {
2284
+ enabled: options.autoResume === true,
2285
+ maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
2286
+ },
2057
2287
  };
2058
2288
  async function onPreStep(payload, next) {
2059
2289
  let downstream;
@@ -2140,6 +2370,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
2140
2370
  record = adoptRequestedPlan(session, record, args?.planId);
2141
2371
  if (!record?.plan)
2142
2372
  throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
2373
+ // [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
2374
+ clearAutoResumeTimer(record, 'manual-update');
2143
2375
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : '';
2144
2376
  if (!subtaskId)
2145
2377
  throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK');
@@ -2336,6 +2568,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
2336
2568
  const reason = typeof args?.reason === 'string' && args.reason.trim()
2337
2569
  ? args.reason.trim()
2338
2570
  : '用户取消';
2571
+ // [1.10.4] 取消是终态:必须撤销已排期的自动续跑,否则定时器会在取消之后复活计划。
2572
+ clearAutoResumeTimer(record, 'cancelled');
2339
2573
  /*
2340
2574
  * [1.5.2] 已完成即终态:取消不再把 100% 的计划改写成「已取消」。
2341
2575
  *
@@ -2468,6 +2702,225 @@ export function createWorkplanRuntime(ctx, options = {}) {
2468
2702
  stats: derivePlanSnapshot(record.statuses).stats,
2469
2703
  };
2470
2704
  }
2705
+ /*
2706
+ * [1.10.4][auto-resume] 自动续跑的记账与排期。
2707
+ *
2708
+ * 为什么在工具层而不是 `dispatchPlan` 里:被整轮预算中止时,这一轮已经没有
2709
+ * 预算可用,轮内重试必然再被同一把闸刀砍掉(`shouldRetryAttempt` 对
2710
+ * `TOTAL_TIMEOUT` / `ABORTED` 恒为 false 是正确的)。能重试的只有「下一轮」:
2711
+ * 新预算、新截止时间,未完成项由 `resetBlockedStatuses` 放回 pending,
2712
+ * done 项永不重跑。所以调度点属于「谁结束了一轮」,也就是这里。
2713
+ *
2714
+ * 所有停止分支都由纯函数 `decideAutoResume` 判定,本层只负责:
2715
+ * - 记录 done 水位与连续无进展轮数(防止空转);
2716
+ * - 用 unref 的定时器排期,并在取消/人工派发/进程销毁时撤销;
2717
+ * - 起跑前再核对一次记录身份与阶段(定时器期间状态可能已变)。
2718
+ */
2719
+ function autoResumeBook(record) {
2720
+ if (!record.autoResume || typeof record.autoResume !== 'object') {
2721
+ record.autoResume = {
2722
+ attempt: 0,
2723
+ noProgressRounds: 0,
2724
+ doneBefore: null,
2725
+ nextAt: null,
2726
+ timer: null,
2727
+ lastDecision: null,
2728
+ history: [],
2729
+ };
2730
+ }
2731
+ return record.autoResume;
2732
+ }
2733
+ function clearAutoResumeTimer(record, reason) {
2734
+ const book = record?.autoResume;
2735
+ if (!book)
2736
+ return false;
2737
+ book.nextAt = null;
2738
+ if (!book.timer)
2739
+ return false;
2740
+ clearTimeout(book.timer);
2741
+ book.timer = null;
2742
+ book.lastStopReason = reason;
2743
+ return true;
2744
+ }
2745
+ function autoResumeView(record) {
2746
+ const book = record?.autoResume;
2747
+ return {
2748
+ enabled: limits.autoResume.enabled,
2749
+ attempt: Number(book?.attempt ?? 0),
2750
+ maxAttempts: limits.autoResume.maxAttempts,
2751
+ armed: Boolean(book?.timer),
2752
+ nextInMs: book?.nextAt ? Math.max(0, Number(book.nextAt) - Date.now()) : null,
2753
+ lastCode: book?.lastDecision?.code ?? null,
2754
+ lastReason: book?.lastDecision?.reason ?? null,
2755
+ lastStopReason: book?.lastStopReason ?? null,
2756
+ };
2757
+ }
2758
+ /**
2759
+ * 在一轮结束后决定是否再开一轮。
2760
+ *
2761
+ * @param record - 当前计划记录。
2762
+ * @param session - 根会话(结果消息与子 Agent 都归属它)。
2763
+ * @param base - 本轮派发的可复用参数(agent / modelSelection / cwd / conversationContext)。
2764
+ */
2765
+ function armAutoResume(record, session, base) {
2766
+ const book = autoResumeBook(record);
2767
+ clearAutoResumeTimer(record, 'rearmed');
2768
+ const snapshot = derivePlanSnapshot(record.statuses);
2769
+ const stats = snapshot.stats ?? {};
2770
+ const statuses = Array.isArray(record.statuses) ? record.statuses : [];
2771
+ const done = Number(stats.done ?? 0);
2772
+ const doneBefore = Number.isFinite(Number(book.doneBefore)) ? Number(book.doneBefore) : done;
2773
+ /*
2774
+ * 「有进展」只认新增的 done 行。被预算中止的子任务会把 error 从 pending
2775
+ * 一路写到重置,只有真正完成才会抬高 done;用 done 作水位既不会把
2776
+ * 「重跑一次又失败」误判成进展,也不会因错误文案变化而空转。
2777
+ */
2778
+ if (done > doneBefore)
2779
+ book.noProgressRounds = 0;
2780
+ else if (Number(book.attempt ?? 0) > 0)
2781
+ book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1;
2782
+ book.doneBefore = done;
2783
+ const pending = statuses.filter((item) => item?.status === 'pending').length;
2784
+ const blocked = statuses.filter((item) => item?.status === 'blocked').length;
2785
+ /*
2786
+ * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
2787
+ *
2788
+ * T7 实测:`armAutoResume` 在每一轮结束后都会被调用,正常完成的轮也会走到
2789
+ * `PHASE_NOT_PAUSED` 分支,于是每个顺利结束的计划都在 `record.errors` 里多一条
2790
+ * 「[auto-resume] 停止」——把真正需要看的中止信息埋掉。全部 done 且没有
2791
+ * pending/blocked 时,直接静默收尾,不写台账。
2792
+ */
2793
+ if (Number(stats.total ?? 0) > 0 && pending === 0 && blocked === 0 && done === Number(stats.total ?? 0)) {
2794
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code: 'NOTHING_PENDING', reason: '全部子任务已 done,无需自动续跑' };
2795
+ return book.lastDecision;
2796
+ }
2797
+ const decision = decideAutoResume({
2798
+ enabled: limits.autoResume.enabled,
2799
+ phase: record.phase,
2800
+ cancelled: record.cancelled === true,
2801
+ degraded: record.degraded === true,
2802
+ planMode: isPlanModeActive(ctx, session),
2803
+ running: Boolean(record.dispatchPromise),
2804
+ total: Number(stats.total ?? 0),
2805
+ done,
2806
+ pending,
2807
+ blocked,
2808
+ attempt: Number(book.attempt ?? 0),
2809
+ maxAttempts: limits.autoResume.maxAttempts,
2810
+ noProgressRounds: Number(book.noProgressRounds ?? 0),
2811
+ stallLimit: AUTO_RESUME_DEFAULTS.stallLimit,
2812
+ baseDelayMs: AUTO_RESUME_DEFAULTS.baseDelayMs,
2813
+ maxDelayMs: AUTO_RESUME_DEFAULTS.maxDelayMs,
2814
+ });
2815
+ book.lastDecision = { at: Date.now(), phase: record.phase, ...decision };
2816
+ book.history = [...(book.history ?? []), {
2817
+ at: Date.now(),
2818
+ phase: record.phase,
2819
+ done,
2820
+ pending,
2821
+ blocked,
2822
+ attempt: Number(book.attempt ?? 0),
2823
+ action: decision.action,
2824
+ code: decision.code,
2825
+ }].slice(-10);
2826
+ if (decision.action !== 'schedule') {
2827
+ /*
2828
+ * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
2829
+ * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
2830
+ */
2831
+ if (decision.code !== 'AUTO_RESUME_DISABLED') {
2832
+ record.errors = [...(record.errors ?? []),
2833
+ `[auto-resume] 停止(${decision.code}):${decision.reason}`].slice(-20);
2834
+ }
2835
+ return decision;
2836
+ }
2837
+ const attempt = Number(book.attempt ?? 0) + 1;
2838
+ book.attempt = attempt;
2839
+ book.nextAt = Date.now() + decision.delayMs;
2840
+ record.errors = [...(record.errors ?? []),
2841
+ `[auto-resume] 已排期第 ${attempt}/${limits.autoResume.maxAttempts} 次自动续跑:`
2842
+ + `${Math.round(decision.delayMs / 1000)}s 后开始(本轮预算到点,仍有 ${pending} 项 pending;done 项不重跑)`].slice(-20);
2843
+ const timer = setTimeout(() => {
2844
+ book.timer = null;
2845
+ book.nextAt = null;
2846
+ try {
2847
+ /*
2848
+ * 排期到点后逐项复核,任何一项不成立都安静退出:定时器活过了一个
2849
+ * 回合,期间用户可能已经取消、主 Agent 可能已经手动派发、页面可能
2850
+ * 已经换了一份计划记录。
2851
+ */
2852
+ /*
2853
+ * [1.10.4 / D1] 复核失败必须留下停止码。
2854
+ *
2855
+ * T5 的 I9:任何一次「本应自动续跑却没有发生」都要可解释。原先这里五个
2856
+ * 分支全是裸 `return`,计划停在 paused 而台账里没有任何痕迹,用户只能再
2857
+ * 做一次考古。现在每个分支都写 `lastStopReason`,并把原因追加到 history。
2858
+ */
2859
+ const stopTimer = (code) => {
2860
+ book.lastStopReason = code;
2861
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code, reason: '定时器复核未通过' };
2862
+ book.history = [...(book.history ?? []), {
2863
+ at: Date.now(), phase: record.phase, action: 'stop', code,
2864
+ }].slice(-10);
2865
+ return;
2866
+ };
2867
+ if (state.records.get(session.id) !== record)
2868
+ return stopTimer('SCHEDULE_REVOKED_RECORD_REPLACED');
2869
+ if (record.dispatchPromise)
2870
+ return stopTimer('SCHEDULE_REVOKED_ALREADY_RUNNING');
2871
+ if (record.cancelled === true)
2872
+ return stopTimer('CANCELLED');
2873
+ if (isTerminalPhase(record.phase))
2874
+ return stopTimer('PHASE_TERMINAL');
2875
+ if (isPlanModeActive(ctx, session))
2876
+ return stopTimer('PLAN_MODE');
2877
+ if (record.phase !== 'paused')
2878
+ return stopTimer('PHASE_NOT_PAUSED');
2879
+ const live = derivePlanSnapshot(record.statuses);
2880
+ const livePending = (record.statuses ?? []).filter((item) => item?.status === 'pending').length;
2881
+ if (Number(live.stats?.total ?? 0) === 0 || livePending === 0)
2882
+ return stopTimer('NOTHING_PENDING');
2883
+ const controller = new AbortController();
2884
+ record.abortRequested = false;
2885
+ record.abortDispatch = (reason) => {
2886
+ if (!controller.signal.aborted)
2887
+ controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'));
2888
+ };
2889
+ record.dispatchStartedAt = Date.now();
2890
+ // 新一轮必须写一条新的结果消息,否则主 Agent 永远看不到自动续跑的结局。
2891
+ record.resultWritten = false;
2892
+ book.doneBefore = Number(live.stats?.done ?? 0);
2893
+ record.dispatchPromise = dispatchPlan(ctx, record, {
2894
+ ...base,
2895
+ signal: controller.signal,
2896
+ childTimeoutMs: limits.childTimeoutMs,
2897
+ idleTimeoutMs: limits.idleTimeoutMs,
2898
+ totalTimeoutMs: limits.totalTimeoutMs,
2899
+ maxResumes: limits.maxResumes,
2900
+ })
2901
+ .then(() => finishRound(record, session))
2902
+ .catch((error) => {
2903
+ pushRecordError(record, error);
2904
+ finishRound(record, session);
2905
+ })
2906
+ .finally(() => {
2907
+ record.dispatchPromise = null;
2908
+ record.dispatchStartedAt = null;
2909
+ record.abortDispatch = null;
2910
+ armAutoResume(record, session, base);
2911
+ });
2912
+ ctx.logger?.warn?.(`dsh-workplan: 计划 ${record.plan?.planId ?? '?'} 自动续跑第 ${attempt}/${limits.autoResume.maxAttempts} 轮已开始`
2913
+ + `(remaining ${Number(live.stats?.total ?? 0) - Number(live.stats?.done ?? 0)})`);
2914
+ }
2915
+ catch (error) {
2916
+ pushRecordError(record, error);
2917
+ ctx.logger?.warn?.(`dsh-workplan: 自动续跑失败:${error instanceof Error ? error.message : String(error)}`);
2918
+ }
2919
+ }, decision.delayMs);
2920
+ timer.unref?.();
2921
+ book.timer = timer;
2922
+ return decision;
2923
+ }
2471
2924
  /**
2472
2925
  * Persist the round result and settle the phase.
2473
2926
  *
@@ -2599,6 +3052,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
2599
3052
  statuses: modelStatusLines(snapshot.statuses),
2600
3053
  errors: (record.errors ?? []).slice(-10),
2601
3054
  resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
3055
+ // [1.10.4] 自动续跑的可观测面:开关、已用轮次、是否已排期、上一次判定码。
3056
+ autoResume: autoResumeView(record),
2602
3057
  deliveryReady: readiness.ready,
2603
3058
  deliveryBlockers: readiness.blockers.slice(0, 12),
2604
3059
  deliveryRemaining: readiness.remaining.slice(0, 20),
@@ -2714,6 +3169,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
2714
3169
  }
2715
3170
  if (!record?.plan)
2716
3171
  throw new PlanError('当前会话没有可派发的计划', 'NO_PLAN');
3172
+ /*
3173
+ * [1.10.4] 人工/工具派发优先于自动续跑:撤销待触发的定时器,并把自动
3174
+ * 轮次计数归零(这一次是外部授权的新起点)。done 水位取当前值,下一轮
3175
+ * 结束后才能正确判断「有没有新增完成项」。
3176
+ */
3177
+ clearAutoResumeTimer(record, 'manual-dispatch');
3178
+ {
3179
+ const book = autoResumeBook(record);
3180
+ book.attempt = 0;
3181
+ book.noProgressRounds = 0;
3182
+ book.doneBefore = Number(derivePlanSnapshot(record.statuses).stats?.done ?? 0);
3183
+ }
2717
3184
  if (args?.planId && record.plan.planId !== args.planId) {
2718
3185
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
2719
3186
  }
@@ -2871,12 +3338,15 @@ export function createWorkplanRuntime(ctx, options = {}) {
2871
3338
  dispatchController.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'));
2872
3339
  }
2873
3340
  };
2874
- record.dispatchPromise = dispatchPlan(ctx, record, {
3341
+ const roundOptions = {
2875
3342
  agent,
2876
- signal: dispatchController.signal,
2877
3343
  modelSelection: selection.provider && selection.model ? selection : record.modelSelection,
2878
3344
  cwd: session.header?.cwd ?? options.cwd,
2879
3345
  conversationContext: record.conversationContext ?? '',
3346
+ };
3347
+ record.dispatchPromise = dispatchPlan(ctx, record, {
3348
+ ...roundOptions,
3349
+ signal: dispatchController.signal,
2880
3350
  childTimeoutMs: limits.childTimeoutMs,
2881
3351
  idleTimeoutMs: limits.idleTimeoutMs,
2882
3352
  totalTimeoutMs: limits.totalTimeoutMs,
@@ -2899,11 +3369,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
2899
3369
  .then(() => {
2900
3370
  finishRound(record, session);
2901
3371
  state.records.set(session.id, record);
3372
+ armAutoResume(record, session, roundOptions);
2902
3373
  })
2903
3374
  .catch((error) => {
2904
3375
  pushRecordError(record, error);
2905
3376
  finishRound(record, session);
2906
3377
  state.records.set(session.id, record);
3378
+ armAutoResume(record, session, roundOptions);
2907
3379
  });
2908
3380
  const live = derivePlanSnapshot(record.statuses);
2909
3381
  return {
@@ -2924,6 +3396,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2924
3396
  }
2925
3397
  await record.dispatchPromise;
2926
3398
  finishRound(record, session);
3399
+ armAutoResume(record, session, roundOptions);
2927
3400
  /*
2928
3401
  * The model's dispatch result reports the same snapshot the dashboard will
2929
3402
  * show. It used to send `record.stats` while the status list below was read
@@ -3745,6 +4218,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
3745
4218
  }
3746
4219
  }
3747
4220
  function dispose() {
4221
+ // [1.10.4] 定时器不能吊住进程,也不能在记录清空后复活一个已销毁的计划。
4222
+ for (const record of state.records.values())
4223
+ clearAutoResumeTimer(record, 'dispose');
3748
4224
  state.records.clear();
3749
4225
  }
3750
4226
  return {