@xiangyixie/dsh-superagent 0.14.6 → 0.14.8

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/long-goal.js CHANGED
@@ -24,8 +24,8 @@ export const PHASE_TERMINAL = new Set(['completed', 'failed', 'skipped', 'cancel
24
24
  /** Goal statuses that still own work. */
25
25
  export const GOAL_ACTIVE = new Set(['planning', 'running'])
26
26
 
27
- /** Goal statuses a tick may advance. */
28
- const GOAL_TICKABLE = new Set(['planning', 'running'])
27
+ /** Goal statuses a tick may advance. A goal waiting on a person still watches its runs. */
28
+ const GOAL_TICKABLE = new Set(['planning', 'running', 'needs-decision'])
29
29
 
30
30
  export const MAX_PHASES = 8
31
31
  export const DEFAULT_MAX_PARALLEL_PHASES = 2
@@ -733,22 +733,31 @@ export function createLongGoalManager({
733
733
  phase.status = 'running'
734
734
  event(goal, 'phase.resumed', `resumed run ${run.id} after interruption`, phase.id)
735
735
  } catch (error) {
736
+ const reason = oneLine(error?.message ?? error, 500)
736
737
  phase.status = 'ready'
737
738
  phase.resumeRunId = null
738
739
  phase.lastOutcome = {
739
740
  runStatus: 'interrupted',
740
- error: oneLine(error?.message ?? error, 500),
741
+ error: reason,
742
+ }
743
+ // A resume that fails after a host restart is routine, not a judgement
744
+ // call: start one more attempt of the same phase while the cap allows
745
+ // it. Completed phases are never replayed, so nothing is paid twice.
746
+ if (phase.attempts < goal.maxAttemptsPerPhase) {
747
+ phase.retryNote = interruptedNote(reason)
748
+ event(goal, 'phase.resume-fell-back', `resume failed; attempt ${phase.attempts + 1} starts fresh`, phase.id)
749
+ } else {
750
+ goal.status = 'needs-decision'
751
+ addDecision(goal, {
752
+ kind: 'resume-failed',
753
+ phaseId: phase.id,
754
+ question: `阶段 ${phase.id}「${phase.title}」的原 run ${run.id} 无法恢复,且已用尽 `
755
+ + `${goal.maxAttemptsPerPhase} 次尝试。重试会新建一次尝试(已完成阶段不会重跑);也可以跳过该阶段或停止目标。`,
756
+ options: ['retry', 'skip', 'stop'],
757
+ reason,
758
+ source: { runId: run.id },
759
+ })
741
760
  }
742
- goal.status = 'needs-decision'
743
- addDecision(goal, {
744
- kind: 'resume-failed',
745
- phaseId: phase.id,
746
- question: `阶段 ${phase.id}「${phase.title}」的原 run ${run.id} 无法恢复。`
747
- + '重试会新建一次尝试(已完成阶段不会重跑);也可以跳过该阶段或停止目标。',
748
- options: ['retry', 'skip', 'stop'],
749
- reason: phase.lastOutcome.error,
750
- source: { runId: run.id },
751
- })
752
761
  }
753
762
  return
754
763
  }
@@ -844,11 +853,25 @@ export function createLongGoalManager({
844
853
  : !retryable
845
854
  ? (phase.lastOutcome.error || 'a failure that a retry cannot fix')
846
855
  : `已用尽 ${goal.maxAttemptsPerPhase} 次尝试`
856
+ const dependents = (goal.phases ?? []).filter(item => (item.dependsOn ?? []).includes(phase.id))
857
+ if (dependents.length === 0) {
858
+ // Nothing later needs this phase, so cutting it loses no other work and
859
+ // the goal can still end as partial. The skip is recorded by name —
860
+ // status and the completion note both say what was cut, why, and how to
861
+ // redo it alone — because a silent skip would read as success.
862
+ phase.status = 'skipped'
863
+ phase.skippedBy = 'exhausted'
864
+ phase.skipReason = why
865
+ phase.lastOutcome = { runStatus: run.status, error: why }
866
+ event(goal, 'phase.auto-skipped', `${why}; no later phase depends on it`, phase.id)
867
+ return
868
+ }
847
869
  goal.status = 'needs-decision'
848
870
  addDecision(goal, {
849
871
  kind: 'phase-exhausted',
850
872
  phaseId: phase.id,
851
873
  question: `阶段 ${phase.id}「${phase.title}」失败:${why}。`
874
+ + `下游阶段 ${dependents.map(item => item.id).join('、')} 依赖它。`
852
875
  + '可以换一种做法重试、跳过该阶段,或停止整个目标。',
853
876
  options: ['retry', 'skip', 'stop'],
854
877
  reason: why,
@@ -886,6 +909,12 @@ export function createLongGoalManager({
886
909
  return lines.join('\n')
887
910
  }
888
911
 
912
+ /** Text for the attempt that replaces one the host could not resume. */
913
+ function interruptedNote(reason) {
914
+ return 'The previous attempt was interrupted when the host restarted and could not be resumed'
915
+ + ` (${reason}). Continue from what is already on disk; do not start the phase over.`
916
+ }
917
+
889
918
  async function dependencySummaries(goal, phase) {
890
919
  const lines = []
891
920
  for (const id of phase.dependsOn) {
@@ -964,13 +993,23 @@ export function createLongGoalManager({
964
993
  } catch (error) {
965
994
  const reason = oneLine(error?.message ?? error, 600)
966
995
  phase.resumeRunId = null
967
- phase.status = 'failed'
968
996
  phase.lastOutcome = { runStatus: 'interrupted', error: reason }
997
+ // Same rule as the reconcile path: a failed resume falls back to one
998
+ // fresh attempt while the cap allows it, and only then asks a person.
999
+ if (phase.attempts < goal.maxAttemptsPerPhase) {
1000
+ phase.status = 'ready'
1001
+ phase.retryNote = interruptedNote(reason)
1002
+ event(goal, 'phase.resume-fell-back', `resume failed; attempt ${phase.attempts + 1} starts fresh`, phase.id)
1003
+ await store.write(goal)
1004
+ return false
1005
+ }
1006
+ phase.status = 'failed'
969
1007
  goal.status = 'needs-decision'
970
1008
  addDecision(goal, {
971
1009
  kind: 'resume-failed',
972
1010
  phaseId: phase.id,
973
- question: `宿主重启后阶段 ${phase.id}「${phase.title}」的原 run ${runId} 无法继续:${reason}。`
1011
+ question: `宿主重启后阶段 ${phase.id}「${phase.title}」的原 run ${runId} 无法继续,且已用尽 `
1012
+ + `${goal.maxAttemptsPerPhase} 次尝试:${reason}。`
974
1013
  + '重试会从该阶段开头新建一次尝试(已完成的阶段不会重跑);也可以跳过或停止。',
975
1014
  options: ['retry', 'skip', 'stop'],
976
1015
  reason,
@@ -992,6 +1031,7 @@ export function createLongGoalManager({
992
1031
  .filter(dependency => dependency && ['failed', 'skipped', 'cancelled'].includes(dependency.status))
993
1032
  if (blocked.length === 0) continue
994
1033
  phase.status = 'skipped'
1034
+ phase.skippedBy = 'dependency'
995
1035
  phase.finishedAt = new Date(now()).toISOString()
996
1036
  phase.lastOutcome = {
997
1037
  runStatus: 'skipped',
@@ -1023,11 +1063,27 @@ export function createLongGoalManager({
1023
1063
  }
1024
1064
  await store.write(goal)
1025
1065
  const label = goal.status === 'completed' ? '完成' : goal.status === 'partial' ? '部分完成' : '失败'
1026
- announce(goal, `goal-${goal.status}`, `长期目标 ${goal.id} ${label}:${progressLine(goal)}。`
1027
- + `完整记录:superagent_goal status goal_id=${goal.id}`)
1066
+ const cutNote = cutNoteFor(goal)
1067
+ announce(goal, `goal-${goal.status}`, `长期目标 ${goal.id} ${label}:${progressLine(goal)}。${cutNote}`
1068
+ + `完整记录:superagent_goal action=status goal_id=${goal.id}`)
1028
1069
  return true
1029
1070
  }
1030
1071
 
1072
+ /**
1073
+ * Name every phase that was dropped after its attempts ran out.
1074
+ *
1075
+ * A partial goal that only says "2/3 complete" leaves the reader to guess
1076
+ * which third is missing and how to finish it, so the completion note and
1077
+ * the status view carry the id, the reason, and the retry that revives it.
1078
+ */
1079
+ function cutNoteFor(goal) {
1080
+ const cut = (goal.phases ?? []).filter(phase => phase.status === 'skipped' && phase.skippedBy === 'exhausted')
1081
+ if (cut.length === 0) return ''
1082
+ const items = cut.map(phase => `阶段 ${phase.id}「${phase.title}」没做成:${oneLine(phase.skipReason ?? '尝试已用尽', 200)}`
1083
+ + `(单独重来:superagent_goal action=retry_phase goal_id=${goal.id} phase_id=${phase.id})`)
1084
+ return `未做成 ${cut.length} 段——${items.join(';')}。`
1085
+ }
1086
+
1031
1087
  function stallReason(goal) {
1032
1088
  const phases = goal.phases ?? []
1033
1089
  const unfinished = phases.filter(phase => !PHASE_TERMINAL.has(phase.status))
@@ -1069,6 +1125,26 @@ export function createLongGoalManager({
1069
1125
  if (!goal || !GOAL_TICKABLE.has(goal.status)) return
1070
1126
  await refreshUsage(goal)
1071
1127
 
1128
+ if (goal.status === 'needs-decision') {
1129
+ // Waiting on a person must not stop watching work already in flight.
1130
+ // Phases that finish now are recorded, and a question from a second
1131
+ // phase joins the open one instead of arriving after the first answer.
1132
+ // Nothing new is dispatched until the open decisions are answered.
1133
+ const parent = await owner(goal)
1134
+ if (!parent) return
1135
+ let progressed = false
1136
+ for (const phase of goal.phases ?? []) {
1137
+ if (phase.status !== 'running') continue
1138
+ await reconcilePhase(goal, phase, parent)
1139
+ progressed = true
1140
+ }
1141
+ if (progressed) {
1142
+ goal.updatedAt = new Date(now()).toISOString()
1143
+ await store.write(goal)
1144
+ }
1145
+ return
1146
+ }
1147
+
1072
1148
  if (goal.status === 'planning') {
1073
1149
  if (!goal.decomposeRunId) {
1074
1150
  const parent = await owner(goal)
@@ -1216,7 +1292,7 @@ export function createLongGoalManager({
1216
1292
  }
1217
1293
  }
1218
1294
  const after = await store.list()
1219
- if (after.some(goal => GOAL_ACTIVE.has(goal.status))) arm()
1295
+ if (after.some(goal => GOAL_ACTIVE.has(goal.status) || watching(goal))) arm()
1220
1296
  return processed
1221
1297
  })()
1222
1298
  try {
@@ -1226,9 +1302,16 @@ export function createLongGoalManager({
1226
1302
  }
1227
1303
  }
1228
1304
 
1305
+ /** A goal with an open decision still has runs worth watching. */
1306
+ function watching(goal) {
1307
+ return goal?.status === 'needs-decision'
1308
+ && (goal.phases ?? []).some(phase => phase.status === 'running')
1309
+ }
1310
+
1229
1311
  function autoResumeFor(goal) {
1230
1312
  if (!goal?.autoResume) return false
1231
1313
  if (GOAL_ACTIVE.has(goal.status)) return true
1314
+ if (watching(goal)) return true
1232
1315
  return goal.status === 'paused' && goal.pausedReason !== 'manual'
1233
1316
  }
1234
1317
 
@@ -1246,7 +1329,7 @@ export function createLongGoalManager({
1246
1329
  changed++
1247
1330
  dirty = true
1248
1331
  }
1249
- if (!GOAL_ACTIVE.has(goal.status)) continue
1332
+ if (!GOAL_ACTIVE.has(goal.status) && !watching(goal)) continue
1250
1333
  for (const phase of goal.phases ?? []) {
1251
1334
  if (phase.status !== 'running' || !phase.currentRunId) continue
1252
1335
  const run = await readRun(phase.currentRunId)
@@ -1472,6 +1555,20 @@ export function createLongGoalManager({
1472
1555
  return goal
1473
1556
  }
1474
1557
 
1558
+ /**
1559
+ * Answering one decision does not resume the goal while another is open.
1560
+ * Folding several questions into one interruption only works if the goal
1561
+ * keeps waiting after the first of them is answered.
1562
+ */
1563
+ function settleDecisionStatus(goal) {
1564
+ if (openDecisions(goal).length > 0) {
1565
+ goal.status = 'needs-decision'
1566
+ return
1567
+ }
1568
+ goal.status = 'running'
1569
+ goal.progressAt = new Date(now()).toISOString()
1570
+ }
1571
+
1475
1572
  /**
1476
1573
  * Apply one decision.
1477
1574
  *
@@ -1503,8 +1600,7 @@ export function createLongGoalManager({
1503
1600
  phase.status = 'running'
1504
1601
  phase.currentRunId = runId
1505
1602
  }
1506
- goal.status = 'running'
1507
- goal.progressAt = new Date(now()).toISOString()
1603
+ settleDecisionStatus(goal)
1508
1604
  event(goal, 'decision.answered', `worker question answered on run ${runId}`, phase?.id ?? null)
1509
1605
  await store.write(goal)
1510
1606
  arm(200)
@@ -1526,8 +1622,7 @@ export function createLongGoalManager({
1526
1622
  acceptanceNote: note ? oneLine(note, 600) : null,
1527
1623
  }
1528
1624
  }
1529
- goal.status = 'running'
1530
- goal.progressAt = new Date(now()).toISOString()
1625
+ settleDecisionStatus(goal)
1531
1626
  goal.noProgressAttempts = 0
1532
1627
  event(goal, 'phase.accepted', note ? oneLine(note, 300) : 'the user accepted the machine result', phase?.id ?? null)
1533
1628
  announce(goal, 'phase-completed', `长期目标 ${goal.id}:阶段 ${phase?.id}「${phase?.title}」按你的判断计为完成`
@@ -1541,8 +1636,7 @@ export function createLongGoalManager({
1541
1636
  phase.retryNote = note ? oneLine(note, 1200) : phase.retryNote
1542
1637
  phase.finishedAt = null
1543
1638
  }
1544
- goal.status = 'running'
1545
- goal.progressAt = new Date(now()).toISOString()
1639
+ settleDecisionStatus(goal)
1546
1640
  goal.noProgressAttempts = 0
1547
1641
  } else {
1548
1642
  return stop(goal, 'the user chose to stop after a verification conflict')
@@ -1557,8 +1651,7 @@ export function createLongGoalManager({
1557
1651
  phase.retryNote = note ? oneLine(note, 1200) : phase.retryNote
1558
1652
  phase.finishedAt = null
1559
1653
  }
1560
- goal.status = 'running'
1561
- goal.progressAt = new Date(now()).toISOString()
1654
+ settleDecisionStatus(goal)
1562
1655
  goal.noProgressAttempts = 0
1563
1656
  } else if (choice === 'skip') {
1564
1657
  if (phase) {
@@ -1566,16 +1659,14 @@ export function createLongGoalManager({
1566
1659
  phase.finishedAt = new Date(now()).toISOString()
1567
1660
  phase.lastOutcome = { runStatus: 'skipped', error: note ? oneLine(note, 400) : 'skipped by the user' }
1568
1661
  }
1569
- goal.status = 'running'
1570
- goal.progressAt = new Date(now()).toISOString()
1662
+ settleDecisionStatus(goal)
1571
1663
  goal.noProgressAttempts = 0
1572
1664
  } else {
1573
1665
  return stop(goal, 'the user chose to stop after a phase failed')
1574
1666
  }
1575
1667
  } else if (decision.kind === 'stalled') {
1576
1668
  if (choice === 'continue') {
1577
- goal.status = 'running'
1578
- goal.progressAt = new Date(now()).toISOString()
1669
+ settleDecisionStatus(goal)
1579
1670
  goal.noProgressAttempts = 0
1580
1671
  goal.stalledAt = null
1581
1672
  if (note) goal.continueNote = oneLine(note, 600)
@@ -1591,6 +1682,68 @@ export function createLongGoalManager({
1591
1682
  return goal
1592
1683
  }
1593
1684
 
1685
+ /**
1686
+ * Reopen one phase that was skipped or failed, together with the phases that
1687
+ * were skipped only because it never completed.
1688
+ *
1689
+ * This is what the completion note points at when a goal ends partial: the
1690
+ * phases that did finish stay finished, and one call revives the missing piece.
1691
+ */
1692
+ async function retryPhase(goalId, phaseId) {
1693
+ const goal = await store.read(goalId)
1694
+ if (!goal) throw new Error(`no long-term goal ${goalId}`)
1695
+ const phase = phaseById(goal, phaseId ?? '')
1696
+ if (!phase) throw new Error(`goal ${goalId} has no phase ${JSON.stringify(phaseId)}`)
1697
+ if (goal.status === 'needs-decision') {
1698
+ throw new Error('the goal is waiting on a decision; answer it before retrying one phase')
1699
+ }
1700
+ if (!['skipped', 'failed'].includes(phase.status)) {
1701
+ throw new Error(`phase ${phase.id} is ${phase.status}; only a skipped or failed phase can be retried alone`)
1702
+ }
1703
+ const reopened = [phase]
1704
+ for (const item of goal.phases ?? []) {
1705
+ if (item === phase || item.status !== 'skipped') continue
1706
+ if (dependsOnPhase(goal, item, phase.id)) reopened.push(item)
1707
+ }
1708
+ for (const item of reopened) {
1709
+ item.status = 'pending'
1710
+ item.attempts = 0
1711
+ item.finishedAt = null
1712
+ item.currentRunId = null
1713
+ item.resumeRunId = null
1714
+ item.lastSignature = null
1715
+ item.lastOutcome = null
1716
+ item.skippedBy = null
1717
+ item.skipReason = null
1718
+ item.retryNote = item === phase
1719
+ ? 'This phase was reopened on request after it was dropped: the earlier attempts failed, so take a different approach and still meet the same acceptance conditions.'
1720
+ : `Phase ${phase.id} is being retried, so this dependent phase is back on the plan.`
1721
+ }
1722
+ goal.status = 'running'
1723
+ goal.finishedAt = null
1724
+ goal.stoppedReason = null
1725
+ goal.noProgressAttempts = 0
1726
+ goal.progressAt = new Date(now()).toISOString()
1727
+ event(goal, 'phase.reopened', `reopened on request (${reopened.map(item => item.id).join(', ')})`, phase.id)
1728
+ await store.write(goal)
1729
+ arm(0)
1730
+ return goal
1731
+ }
1732
+
1733
+ /** True when `phase` depends on `ancestorId` through any chain. */
1734
+ function dependsOnPhase(goal, phase, ancestorId) {
1735
+ const seen = new Set()
1736
+ const queue = [...(phase.dependsOn ?? [])]
1737
+ while (queue.length > 0) {
1738
+ const id = queue.pop()
1739
+ if (id === ancestorId) return true
1740
+ if (seen.has(id)) continue
1741
+ seen.add(id)
1742
+ queue.push(...(phaseById(goal, id)?.dependsOn ?? []))
1743
+ }
1744
+ return false
1745
+ }
1746
+
1594
1747
  return {
1595
1748
  init,
1596
1749
  close,
@@ -1603,6 +1756,7 @@ export function createLongGoalManager({
1603
1756
  resume,
1604
1757
  pause,
1605
1758
  cancel,
1759
+ retryPhase,
1606
1760
  store,
1607
1761
  formatStatus,
1608
1762
  }
@@ -1680,6 +1834,14 @@ export function formatStatus(goal, runs = {}) {
1680
1834
  if (phase.lastOutcome?.error) lines.push(` last: ${oneLine(phase.lastOutcome.error, 300)}`)
1681
1835
  }
1682
1836
  }
1837
+ const cut = phases.filter(phase => phase.status === 'skipped' && phase.skippedBy === 'exhausted')
1838
+ if (cut.length > 0) {
1839
+ lines.push('', 'Skipped after its attempts ran out (no later phase needed it):')
1840
+ for (const phase of cut) {
1841
+ lines.push(`- ${phase.id}「${phase.title}」— ${oneLine(phase.skipReason ?? 'attempts exhausted', 300)}`)
1842
+ lines.push(` redo this phase alone: superagent_goal action=retry_phase goal_id=${goal.id} phase_id=${phase.id}`)
1843
+ }
1844
+ }
1683
1845
  if (goal.recovery) {
1684
1846
  lines.push('', `Recovered: ${goal.recovery.reason} at ${goal.recovery.at}`
1685
1847
  + `${(goal.recovery.phases ?? []).length > 0 ? ` (phases ${goal.recovery.phases.join(', ')})` : ''}`)
@@ -1697,7 +1859,7 @@ export function formatStatus(goal, runs = {}) {
1697
1859
  lines.push('', 'Next:')
1698
1860
  if (goal.status === 'needs-decision') lines.push('- answer the open decision above; no new phase will start until then')
1699
1861
  else if (goal.status === 'completed') lines.push('- nothing; every phase met its acceptance conditions')
1700
- else if (goal.status === 'partial') lines.push('- inspect the skipped phases in the table; start a new goal for the rest')
1862
+ else if (goal.status === 'partial') lines.push('- retry one skipped phase alone with superagent_goal action=retry_phase, or start a new goal for the rest')
1701
1863
  else if (goal.status === 'failed') lines.push('- inspect the report; create a new goal with explicit phases if the framing was wrong')
1702
1864
  else if (goal.status === 'paused') lines.push('- superagent_goal action=resume when the owning session is available again')
1703
1865
  else lines.push('- poll with superagent_goal action=status; phase runs continue in the background')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiangyixie/dsh-superagent",
3
- "version": "0.14.6",
3
+ "version": "0.14.8",
4
4
  "description": "长周期自主执行插件:一个目标拆成可并行的子任务,交付一份合并报告,重启后仍可继续。",
5
5
  "author": "Admire (LittleChenLiya)",
6
6
  "type": "module",