dsh-workplan 1.6.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime.ts CHANGED
@@ -13,6 +13,8 @@
13
13
  */
14
14
 
15
15
  import { randomUUID } from 'node:crypto'
16
+ import { existsSync } from 'node:fs'
17
+ import { isAbsolute, resolve } from 'node:path'
16
18
 
17
19
  import {
18
20
  MAX_CONCURRENT,
@@ -48,6 +50,10 @@ import {
48
50
  truncate,
49
51
  validatePlan,
50
52
  applyResultStatuses,
53
+ adjudicateResult,
54
+ MAX_CONVERSATION_CHARS,
55
+ parseUpdateMessage,
56
+ buildUpdateMessage,
51
57
  } from './plan.js'
52
58
  import { createProgressWatchdog, describeError } from './watchdog.js'
53
59
 
@@ -121,7 +127,7 @@ function taskTextFromMessages(messages: any) {
121
127
  * it to both the planner and every child. Plugin-generated plan/result rows are
122
128
  * excluded to avoid feeding the plan back into itself.
123
129
  */
124
- function recentConversation(session: any, maxChars = 7000) {
130
+ function recentConversation(session: any, maxChars = MAX_CONVERSATION_CHARS) {
125
131
  if (!session || typeof session.eventAt !== 'function') return ''
126
132
  const parts: string[] = []
127
133
  let seq = typeof session.seq === 'number' ? session.seq - 1 : -1
@@ -203,7 +209,7 @@ async function collectStream(stream: any) {
203
209
  }
204
210
 
205
211
  async function runPlanner(ctx: any, options: any) {
206
- const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '' } = options
212
+ const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {} } = options
207
213
  let lastErrors: string[] = []
208
214
  for (let attempt = 1; attempt <= 2; attempt += 1) {
209
215
  if (signal.aborted) throw abortError()
@@ -214,7 +220,7 @@ async function runPlanner(ctx: any, options: any) {
214
220
  controller.abort(new PlanError('规划器超时', 'PLANNER_TIMEOUT'))
215
221
  }, PLANNER_TIMEOUT_MS)
216
222
  try {
217
- let prompt = buildPlannerPrompt(taskText, cwd, conversationContext)
223
+ let prompt = buildPlannerPrompt(taskText, cwd, conversationContext, budget)
218
224
  if (lastErrors.length > 0) {
219
225
  prompt += [
220
226
  '',
@@ -362,7 +368,7 @@ export function normaliseIdleTimeout(value: any) {
362
368
  */
363
369
  function writeSubtaskStatus(record: any, subtaskId: any, patch: any, guard: SubtaskGuard) {
364
370
  if (guard.timedOut) return false
365
- record.statuses = applyStatus(record.statuses, subtaskId, patch)
371
+ record.statuses = applyStatus(record.statuses, subtaskId, { updatedBy: 'child', ...patch })
366
372
  record.updatedAt = Date.now()
367
373
  return true
368
374
  }
@@ -372,9 +378,101 @@ function recordSubtaskError(record: any, subtaskId: any, message: any, guard: Su
372
378
  record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20)
373
379
  }
374
380
 
381
+ /**
382
+ * Resolve one artifact reference against the round's working directory.
383
+ *
384
+ * Relative refs are what a child is asked to report, so they must be resolved
385
+ * the same way for every check; an empty ref is never "present".
386
+ */
387
+ function resolveArtifactPath(ref: any, cwd: any) {
388
+ const text = typeof ref === 'string' ? ref.trim() : ''
389
+ if (!text) return ''
390
+ if (isAbsolute(text)) return text
391
+ const base = typeof cwd === 'string' && cwd ? cwd : process.cwd()
392
+ return resolve(base, text)
393
+ }
394
+
395
+ /**
396
+ * [1.7.0] Check the files a child declared.
397
+ *
398
+ * Only `kind:'file'` is verifiable here. A url or a note is taken at face
399
+ * value; pretending to verify them would be worse than not checking at all.
400
+ * The verdict is recorded rather than enforced: a missing file makes the
401
+ * dependency gate fail, but it does not silently rewrite "done" to "blocked".
402
+ */
403
+ export function checkArtifacts(artifacts: any, cwd: any, artifactExists: any = existsSync) {
404
+ const list = Array.isArray(artifacts) ? artifacts : []
405
+ const missingArtifacts: string[] = []
406
+ const checked = list.map((item: any) => {
407
+ if (!isRecord(item) || item.kind !== 'file') return item
408
+ const target = resolveArtifactPath(item.ref, cwd)
409
+ let exists = false
410
+ try {
411
+ exists = target ? artifactExists(target) === true : false
412
+ } catch {
413
+ exists = false
414
+ }
415
+ if (!exists) missingArtifacts.push(String(item.ref))
416
+ return { ...item, exists }
417
+ })
418
+ return { artifacts: checked, missingArtifacts }
419
+ }
420
+
421
+ /**
422
+ * Turn one child output into a status verdict.
423
+ *
424
+ * The decision lives in `adjudicateResult` (a pure function) so the runtime and
425
+ * the session replay cannot disagree. This wrapper only adds the two things
426
+ * that need the environment: the strict/legacy switch and the file check.
427
+ */
428
+ function settleFromOutput(record: any, subtask: any, output: any, guard: SubtaskGuard, options: any) {
429
+ const verdict = adjudicateResult({ output, strict: options.strictEvidence !== false })
430
+ const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists)
431
+ writeSubtaskStatus(record, subtask.id, {
432
+ status: verdict.status,
433
+ progress: 100,
434
+ finishedAt: Date.now(),
435
+ summary: truncate(output, 3000),
436
+ error: verdict.error,
437
+ verification: verdict.verification,
438
+ acceptance: verdict.acceptance,
439
+ artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
440
+ missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
441
+ needs: verdict.needs.length > 0 ? verdict.needs : undefined,
442
+ }, guard)
443
+ if (verdict.status === 'blocked') {
444
+ recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard)
445
+ } else if (checked.missingArtifacts.length > 0) {
446
+ recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard)
447
+ }
448
+ return verdict
449
+ }
450
+
451
+ /**
452
+ * Retry policy for one child attempt.
453
+ *
454
+ * A wedged child (no event for the whole idle window) is worth one fresh
455
+ * attempt. A hard ceiling means the budget is gone, and an abort is a decision,
456
+ * so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
457
+ * more than one idle window left, otherwise the retry itself would just be
458
+ * killed by the same watchdog.
459
+ */
460
+ export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, idleTimeoutMs: any) {
461
+ if (attempt >= 2) return false
462
+ const code = error?.code
463
+ if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
464
+ if (/aborted|refusal/i.test(String(error?.message ?? ''))) return false
465
+ if (code === 'CHILD_STALLED') return true
466
+ if (code === 'CHILD_NOT_COMPLETED') {
467
+ return Number(remainingMs) > Number(idleTimeoutMs)
468
+ }
469
+ return true
470
+ }
471
+
375
472
  async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
376
473
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
377
474
  let lastError: any = null
475
+ let lastFailure: any = null
378
476
  try {
379
477
  if (!writeSubtaskStatus(record, subtask.id, {
380
478
  status: 'in_progress',
@@ -411,6 +509,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
411
509
  })),
412
510
  cwd: options.cwd,
413
511
  conversationContext,
512
+ statuses: record.statuses,
513
+ previousFailure: attempt > 1 ? lastFailure : null,
414
514
  }),
415
515
  }],
416
516
  parent: options.agent,
@@ -482,50 +582,52 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
482
582
  )
483
583
  }
484
584
  if (!output) throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT')
485
- if (/^\s*BLOCKED\s*[::]/i.test(output)) {
486
- writeSubtaskStatus(record, subtask.id, {
487
- status: 'blocked',
488
- progress: 100,
489
- finishedAt: Date.now(),
490
- summary: truncate(output, 3000),
491
- error: truncate(output.replace(/^\s*BLOCKED\s*[::]\s*/i, ''), 2000),
492
- }, guard)
493
- recordSubtaskError(record, subtask.id, output, guard)
494
- return
495
- }
496
- writeSubtaskStatus(record, subtask.id, {
497
- status: 'done',
498
- progress: 100,
499
- finishedAt: Date.now(),
500
- summary: truncate(output, 3000),
501
- error: null,
502
- }, guard)
585
+ /*
586
+ * [1.7.0] Evidence decides the verdict.
587
+ *
588
+ * The old rule was "not BLOCKED => done", so a child that reported
589
+ * unverified or failed self-checks was still counted as finished and
590
+ * the main Agent had nothing to review but prose. `adjudicateResult`
591
+ * is the single deterministic table; `settleFromOutput` adds the
592
+ * environment-dependent artifact check.
593
+ */
594
+ settleFromOutput(record, subtask, output, guard, options)
503
595
  return
504
596
  } catch (error: any) {
505
597
  lastError = error
506
598
  if (guard.timedOut) break
507
599
  const isAbort = parentSignal.aborted || child.controller.signal.aborted
600
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
601
+ const remaining = deadline - Date.now()
508
602
  /*
509
- * Two failure kinds, two different correct reactions.
603
+ * [1.7.0] The retry carries the previous failure with it.
510
604
  *
511
- * A stalled child is wedged — no event for the whole idle window — so
512
- * one fresh attempt can succeed and is worth trying. A hard ceiling
513
- * means the budget is gone, so retrying would only burn the plan's
514
- * remaining time; it goes straight to blocked.
605
+ * Retrying with an identical prompt made the child repeat the same
606
+ * dead end and produced the same error twice. The next attempt now
607
+ * receives the code, message and attempt number, so it can change
608
+ * approach — or stop honestly.
515
609
  */
516
- const stalled = error?.code === 'CHILD_STALLED'
517
- if (stalled && attempt < 2 && !isAbort) {
610
+ lastFailure = {
611
+ attempt,
612
+ code: error?.code ?? 'UNKNOWN',
613
+ message: describeError(error),
614
+ }
615
+ const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs)
616
+ if (retry) {
518
617
  record.errors = [
519
618
  ...record.errors,
520
- `${subtask.id}: 第 ${attempt} 次执行无进展,已停止并重试`,
619
+ `${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
521
620
  ].slice(-20)
522
621
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
523
622
  continue
524
623
  }
525
- if (isAbort || attempt >= 2 || error?.code === 'CHILD_NOT_COMPLETED' && /aborted|refusal/i.test(String(error?.message ?? ''))) {
526
- break
624
+ if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
625
+ record.errors = [
626
+ ...record.errors,
627
+ `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
628
+ ].slice(-20)
527
629
  }
528
- writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
630
+ break
529
631
  } finally {
530
632
  if (activation) {
531
633
  await disposeActivation(activation, record, subtask.id, guard)
@@ -652,6 +754,31 @@ async function runWithConcurrency(items: any, limit: any, worker: any) {
652
754
  * @param limits - resolved runtime limits (the resume budget comes from here).
653
755
  * @returns a user message carrying the `workplan-result` payload.
654
756
  */
757
+ /**
758
+ * The subtask rows a dispatch/status tool returns to the model.
759
+ *
760
+ * One definition, because the same plan was described in three slightly
761
+ * different shapes (dispatch tail, already-running branch, status tool) and the
762
+ * model could see three different answers in one turn.
763
+ */
764
+ export function modelStatusLines(statuses: any) {
765
+ const list = Array.isArray(statuses) ? statuses : []
766
+ return list.map((item: any) => ({
767
+ subtaskId: item.subtaskId,
768
+ title: item.title,
769
+ department: item.department,
770
+ status: item.status,
771
+ progress: item.progress,
772
+ summary: truncate(item.summary ?? item.error ?? '', 2000),
773
+ error: item.error ?? null,
774
+ verification: item.verification ?? null,
775
+ revision: Number(item.revision ?? 0),
776
+ updatedBy: item.updatedBy ?? null,
777
+ missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
778
+ needs: Array.isArray(item.needs) ? item.needs : [],
779
+ }))
780
+ }
781
+
655
782
  export function buildRoundResult(record: any, sessionId: any, limits: any) {
656
783
  const { statuses, stats } = derivePlanSnapshot(record.statuses)
657
784
  return buildResultMessage({
@@ -725,7 +852,18 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
725
852
  if (guard > 200) throw new PlanError('调度次数异常', 'DISPATCH_LOOP')
726
853
  if (parentSignal.aborted) throw abortError()
727
854
  if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
728
- const ready = readySubtasks(record.plan, record.statuses)
855
+ /*
856
+ * [1.7.0] A `done` upstream only unblocks its dependents when the files it
857
+ * declared actually exist. The check is opt-out (`artifactGate:false`) so
858
+ * an older plan or a debugging session can keep plain status semantics.
859
+ */
860
+ const gate = options.artifactGate !== false
861
+ const ready = readySubtasks(record.plan, record.statuses, gate
862
+ ? {
863
+ dependencyOk: (dependency: any) => dependency?.status === 'done'
864
+ && !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
865
+ }
866
+ : {})
729
867
  if (ready.length === 0) {
730
868
  const pending = record.statuses.filter((item: any) => item.status === 'pending')
731
869
  for (const item of pending) {
@@ -752,13 +890,27 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
752
890
  modelSelection,
753
891
  cwd,
754
892
  conversationContext,
893
+ strictEvidence: options.strictEvidence,
894
+ artifactExists: options.artifactExists,
755
895
  })
756
896
  })
757
897
  const blocked = record.statuses
758
898
  .filter((item: any) => item.status === 'blocked')
759
899
  .map((item: any) => item.subtaskId)
760
900
  for (const id of blocked) {
761
- record.statuses = markDependentsBlocked(record.plan, record.statuses, id)
901
+ /*
902
+ * Carry the actual cause downstream. The main Agent used to receive
903
+ * "上游子任务受阻: T2" with no reason and no missing artifacts, so it
904
+ * had to re-read the whole plan to guess what to repair.
905
+ */
906
+ const upstream = record.statuses.find((item: any) => item.subtaskId === id)
907
+ const cause = upstream
908
+ ? {
909
+ reason: upstream.error,
910
+ missingArtifacts: Array.isArray(upstream.missingArtifacts) ? upstream.missingArtifacts : [],
911
+ }
912
+ : null
913
+ record.statuses = markDependentsBlocked(record.plan, record.statuses, id, cause)
762
914
  }
763
915
  /*
764
916
  * No stats refresh here any more: `serialisePlan` derives the counts from
@@ -1093,6 +1245,29 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1093
1245
  resultPhase = typeof result.phase === 'string' ? result.phase : ''
1094
1246
  resultSeen = true
1095
1247
  }
1248
+ /*
1249
+ * [1.7.0] Manual re-adjudications replay in order.
1250
+ *
1251
+ * `dsh_workplan_update` used to live only in the live cache, so a refresh
1252
+ * reverted the dashboard to the child's original verdict. The durable
1253
+ * `workplan-update` message is small and append-only, so replay is just
1254
+ * "apply it when its turn comes"; a lower revision never overwrites a
1255
+ * newer one (see `applyResultStatuses`).
1256
+ */
1257
+ const update = parseUpdateMessage(event.data)
1258
+ if (update && plan && update.planId === plan.planId && typeof update.subtaskId === 'string') {
1259
+ try {
1260
+ statuses = applyStatus(statuses, update.subtaskId, {
1261
+ status: update.status,
1262
+ progress: typeof update.progress === 'number' ? update.progress : undefined,
1263
+ summary: typeof update.note === 'string' ? update.note : undefined,
1264
+ revision: Number.isInteger(update.revision) ? update.revision : undefined,
1265
+ updatedBy: 'agent',
1266
+ })
1267
+ } catch {
1268
+ // An invalid historical update is ignored; the rest still replays.
1269
+ }
1270
+ }
1096
1271
  const cancel = parseCancelMessage(event.data)
1097
1272
  if (cancel && plan && cancel.planId === plan.planId) {
1098
1273
  cancelled = true
@@ -1285,7 +1460,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1285
1460
  }
1286
1461
  if (downstream?.kind !== 'enter') return downstream
1287
1462
  try {
1288
- return await maybePlan(ctx, state, payload, downstream, options)
1463
+ return await maybePlan(ctx, state, payload, downstream, { ...options, limits })
1289
1464
  } catch (error) {
1290
1465
  try {
1291
1466
  const session = payload.agent?.session
@@ -1340,14 +1515,77 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1340
1515
  ? args.evidence.filter((item: any) => typeof item === 'string').join(';')
1341
1516
  : ''
1342
1517
  const summary = [note, evidence].filter(Boolean).join('|')
1518
+ const current = record.statuses.find((item: any) => item.subtaskId === subtaskId)
1519
+ /*
1520
+ * [1.7.0] Two write guards, both non-throwing.
1521
+ *
1522
+ * 1. A stale revision means the caller is looking at an older snapshot; the
1523
+ * write is refused instead of silently overwriting newer evidence.
1524
+ * 2. While the plan is running, the child owns the status of the subtask it
1525
+ * is executing. An agent edit would race the child's settlement (and the
1526
+ * child would overwrite it back). `force:true` is the explicit override,
1527
+ * recorded as a manual re-adjudication.
1528
+ */
1529
+ if (Number.isInteger(args?.expectedRevision) && (current?.revision ?? 0) !== args.expectedRevision) {
1530
+ return {
1531
+ ok: false,
1532
+ code: 'STALE_WRITE',
1533
+ planId: record.plan.planId,
1534
+ subtaskId,
1535
+ current: {
1536
+ status: current?.status ?? null,
1537
+ revision: current?.revision ?? 0,
1538
+ updatedBy: current?.updatedBy ?? null,
1539
+ },
1540
+ hint: `该子任务已被更新(当前 revision ${current?.revision ?? 0},你基于 ${args.expectedRevision});请重新读取状态后再改。`,
1541
+ }
1542
+ }
1543
+ const running = Boolean(record.dispatchPromise)
1544
+ const writeWhileRunning = running && !args?.force && (current?.status === 'pending' || current?.status === 'in_progress')
1545
+ if (writeWhileRunning) {
1546
+ return {
1547
+ ok: false,
1548
+ code: 'TASK_RUNNING',
1549
+ planId: record.plan.planId,
1550
+ subtaskId,
1551
+ current: {
1552
+ status: current?.status ?? null,
1553
+ revision: current?.revision ?? 0,
1554
+ updatedBy: current?.updatedBy ?? null,
1555
+ },
1556
+ hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
1557
+ }
1558
+ }
1559
+ const revision = Number(current?.revision ?? 0) + 1
1343
1560
  record.statuses = applyStatus(record.statuses, subtaskId, {
1344
1561
  status,
1345
1562
  progress: typeof args?.progress === 'number' ? args.progress : undefined,
1346
1563
  summary: summary || undefined,
1347
1564
  error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
1565
+ revision,
1566
+ updatedBy: 'agent',
1348
1567
  })
1349
1568
  if (status === 'blocked') {
1350
- record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId)
1569
+ record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' })
1570
+ }
1571
+ /*
1572
+ * [1.7.0] A re-adjudication is durable.
1573
+ *
1574
+ * `applyStatus` only touched the in-memory record, so after a refresh the
1575
+ * manual verdict vanished and the dashboard fell back to the old child
1576
+ * result. Appending one small message keeps the replay path honest.
1577
+ */
1578
+ try {
1579
+ session.append('user/message', buildUpdateMessage({
1580
+ planId: record.plan.planId,
1581
+ subtaskId,
1582
+ status,
1583
+ progress: typeof args?.progress === 'number' ? args.progress : undefined,
1584
+ note: summary || undefined,
1585
+ revision,
1586
+ }), { surfaceOp: 'append' })
1587
+ } catch (error) {
1588
+ pushRecordError(record, error)
1351
1589
  }
1352
1590
  /*
1353
1591
  * [1.5.2] 这里曾是「100% + 正在收尾」的直接入口。
@@ -1361,11 +1599,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1361
1599
  record.phase = reconcilePhase(record.phase, record.statuses)
1362
1600
  record.updatedAt = Date.now()
1363
1601
  const snapshot = derivePlanSnapshot(record.statuses)
1602
+ const written = snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)
1364
1603
  return {
1365
1604
  ok: true,
1366
1605
  planId: record.plan.planId,
1367
1606
  subtaskId,
1368
- status: snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)?.status ?? status,
1607
+ status: written?.status ?? status,
1608
+ revision: written?.revision ?? revision,
1609
+ updatedBy: written?.updatedBy ?? 'agent',
1369
1610
  stats: snapshot.stats,
1370
1611
  }
1371
1612
  }
@@ -1450,6 +1691,91 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1450
1691
  }
1451
1692
  }
1452
1693
 
1694
+ /**
1695
+ * Persist the round result and settle the phase.
1696
+ *
1697
+ * Extracted from the wait path so an async dispatch reaches exactly the same
1698
+ * end state: a durable result message plus a reconciled phase. Anything less
1699
+ * would make "start now, read later" a second, divergent code path.
1700
+ */
1701
+ function finishRound(record: any, session: any) {
1702
+ if (!record.resultWritten) {
1703
+ const resultMessage = buildRoundResult(record, session.id, limits)
1704
+ try {
1705
+ session.append('user/message', resultMessage, { surfaceOp: 'append' })
1706
+ record.resultWritten = true
1707
+ } catch (error) {
1708
+ ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
1709
+ }
1710
+ }
1711
+ /*
1712
+ * [1.5.2] 终态不再依赖「结果消息写成功」这个副作用。
1713
+ *
1714
+ * 旧代码只有 `record.resultWritten === true` 时才把 phase 升成 done,
1715
+ * 于是 session.append 抛错(或该轮根本没有派发)就会永久停在 integrating。
1716
+ * 完成语义由 statuses 决定;结果消息只负责持久化,不负责定义完成。
1717
+ */
1718
+ record.phase = reconcilePhase(record.phase, record.statuses)
1719
+ return record
1720
+ }
1721
+
1722
+ function dispatchSnapshotOf(record: any, extra: any = {}) {
1723
+ const snapshot = derivePlanSnapshot(record.statuses)
1724
+ return {
1725
+ ok: true,
1726
+ planId: record.plan.planId,
1727
+ alreadyRunning: false,
1728
+ ...extra,
1729
+ phase: record.phase,
1730
+ stats: snapshot.stats,
1731
+ statuses: modelStatusLines(snapshot.statuses),
1732
+ }
1733
+ }
1734
+
1735
+ /**
1736
+ * Read-only progress probe for the main Agent.
1737
+ *
1738
+ * With async dispatch the model no longer blocks until the round ends, so it
1739
+ * needs a supported way to answer "做成什么样了" without guessing. This is the
1740
+ * only source it should read: same `derivePlanSnapshot` as the dashboard and
1741
+ * the result message, so all three cannot disagree.
1742
+ */
1743
+ async function statusTool(agent: any, args: any) {
1744
+ const session = agent?.session
1745
+ if (!session) throw new PlanError('只能在会话内查看计划', 'NO_SESSION')
1746
+ const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined
1747
+ let record = state.records.get(session.id)
1748
+ if (!record?.plan || (requestedPlanId && record.plan.planId !== requestedPlanId)) {
1749
+ const rebuilt = reconstructFromSession(session, requestedPlanId)
1750
+ if (rebuilt?.plan) record = rebuilt
1751
+ }
1752
+ if (!record?.plan) {
1753
+ return {
1754
+ ok: false,
1755
+ code: 'NO_PLAN',
1756
+ running: false,
1757
+ error: '当前会话没有可查看的计划',
1758
+ hint: '先让本轮生成计划并调用 dsh_workplan_dispatch。',
1759
+ }
1760
+ }
1761
+ const running = Boolean(record.dispatchPromise)
1762
+ const snapshot = derivePlanSnapshot(record.statuses)
1763
+ return {
1764
+ ok: true,
1765
+ planId: record.plan.planId,
1766
+ running,
1767
+ phase: record.phase,
1768
+ elapsedMs: record.dispatchStartedAt ? Date.now() - record.dispatchStartedAt : null,
1769
+ stats: snapshot.stats,
1770
+ statuses: modelStatusLines(snapshot.statuses),
1771
+ errors: (record.errors ?? []).slice(-10),
1772
+ resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
1773
+ ...(running
1774
+ ? { hint: '计划仍在执行:先向用户报告进度,不要声称完成;等结果消息出现后再逐项核对证据。' }
1775
+ : { hint: '当前没有正在执行的派发。若仍有 pending/blocked,可再次调用 dsh_workplan_dispatch 续跑。' }),
1776
+ }
1777
+ }
1778
+
1453
1779
  async function dispatchTool(agent: any, args: any, signal: any) {
1454
1780
  const session = agent?.session
1455
1781
  if (!session) throw new PlanError('只能在会话内派发计划', 'NO_SESSION')
@@ -1491,6 +1817,35 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1491
1817
  if (args?.planId && record.plan.planId !== args.planId) {
1492
1818
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
1493
1819
  }
1820
+ /*
1821
+ * [1.7.0] Two dispatch modes.
1822
+ *
1823
+ * `wait` (default, backward compatible) blocks until the round ends.
1824
+ * `async` starts the round and returns immediately, so the main Agent can
1825
+ * answer the user and keep integrating instead of sitting blind inside a
1826
+ * tool call for twenty minutes (the top-ranked collaboration break C1).
1827
+ */
1828
+ const mode = args?.mode === 'async' ? 'async' : 'wait'
1829
+ if (mode === 'wait' && record.dispatchPromise) {
1830
+ /*
1831
+ * A wait caller that meets an in-flight round joins it instead of being
1832
+ * told "already running" — the old answer carried no results at all, so
1833
+ * a model that missed the async result message had nothing to integrate.
1834
+ * A wedged promise keeps the old stale escape hatch (see below).
1835
+ */
1836
+ const startedAt = Number(record.dispatchStartedAt ?? 0)
1837
+ const staleAfter = limits.totalTimeoutMs + 120000
1838
+ if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
1839
+ try {
1840
+ await record.dispatchPromise
1841
+ } catch (error) {
1842
+ pushRecordError(record, error)
1843
+ }
1844
+ finishRound(record, session)
1845
+ state.records.set(session.id, record)
1846
+ return dispatchSnapshotOf(record, { joined: true })
1847
+ }
1848
+ }
1494
1849
  if (record.dispatchPromise) {
1495
1850
  /*
1496
1851
  * "Already running" must not become a permanent answer.
@@ -1517,7 +1872,25 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1517
1872
  hint: '请主 Agent 直接接手完成剩余子任务,不要再次派发;并在答复中说明本次是直接执行而非派发。',
1518
1873
  }
1519
1874
  }
1520
- return { ok: true, planId: record.plan.planId, alreadyRunning: true, phase: record.phase, startedAt: startedAt || null }
1875
+ /*
1876
+ * [1.7.0] The idempotent answer now carries the progress itself.
1877
+ *
1878
+ * It used to say only `alreadyRunning: true`, so a second dispatch gave
1879
+ * the model strictly less information than doing nothing.
1880
+ */
1881
+ const live = derivePlanSnapshot(record.statuses)
1882
+ return {
1883
+ ok: true,
1884
+ planId: record.plan.planId,
1885
+ alreadyRunning: true,
1886
+ running: true,
1887
+ phase: record.phase,
1888
+ startedAt: startedAt || null,
1889
+ elapsedMs: startedAt ? Date.now() - startedAt : null,
1890
+ stats: live.stats,
1891
+ statuses: modelStatusLines(live.statuses),
1892
+ hint: '计划仍在执行:先向用户报告进度,不要声称完成;用 dsh_workplan_status 查看实时状态。',
1893
+ }
1521
1894
  }
1522
1895
  /*
1523
1896
  * Refuse with an explanation instead of silently "succeeding".
@@ -1576,46 +1949,47 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1576
1949
  record.abortDispatch = null
1577
1950
  signal?.removeEventListener?.('abort', onToolAbort)
1578
1951
  })
1579
- await record.dispatchPromise
1580
- if (!record.resultWritten) {
1581
- const resultMessage = buildRoundResult(record, session.id, limits)
1582
- try {
1583
- session.append('user/message', resultMessage, { surfaceOp: 'append' })
1584
- record.resultWritten = true
1585
- } catch (error) {
1586
- ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
1952
+ if (mode === 'async') {
1953
+ /*
1954
+ * Settlement happens in the background: the same durable result message
1955
+ * is appended when the round ends, so a page refresh (or a later turn)
1956
+ * still sees the outcome. The returned values are a *starting* snapshot,
1957
+ * never a completion claim.
1958
+ */
1959
+ const startedAt = record.dispatchStartedAt
1960
+ record.dispatchPromise
1961
+ .then(() => {
1962
+ finishRound(record, session)
1963
+ state.records.set(session.id, record)
1964
+ })
1965
+ .catch((error: any) => {
1966
+ pushRecordError(record, error)
1967
+ finishRound(record, session)
1968
+ state.records.set(session.id, record)
1969
+ })
1970
+ const live = derivePlanSnapshot(record.statuses)
1971
+ return {
1972
+ ok: true,
1973
+ planId: record.plan.planId,
1974
+ mode: 'async',
1975
+ running: true,
1976
+ alreadyRunning: false,
1977
+ phase: record.phase,
1978
+ startedAt,
1979
+ stats: live.stats,
1980
+ statuses: modelStatusLines(live.statuses),
1981
+ hint: '计划已开跑,尚未完成:先向用户说明“已派发、正在执行”,不要声称完成;'
1982
+ + '结果消息会在本轮结束时自动出现,期间可用 dsh_workplan_status 查看进度。',
1587
1983
  }
1588
1984
  }
1589
- /*
1590
- * [1.5.2] 终态不再依赖「结果消息写成功」这个副作用。
1591
- *
1592
- * 旧代码只有 `record.resultWritten === true` 时才把 phase 升成 done,
1593
- * 于是 session.append 抛错(或该轮根本没有派发)就会永久停在 integrating。
1594
- * 完成语义由 statuses 决定;结果消息只负责持久化,不负责定义完成。
1595
- */
1596
- record.phase = reconcilePhase(record.phase, record.statuses)
1985
+ await record.dispatchPromise
1986
+ finishRound(record, session)
1597
1987
  /*
1598
1988
  * The model's dispatch result reports the same snapshot the dashboard will
1599
1989
  * show. It used to send `record.stats` while the status list below was read
1600
1990
  * fresh, so one reply could say “已完成 11” next to twelve finished rows.
1601
1991
  */
1602
- const snapshot = derivePlanSnapshot(record.statuses)
1603
- return {
1604
- ok: true,
1605
- planId: record.plan.planId,
1606
- alreadyRunning: false,
1607
- phase: record.phase,
1608
- stats: snapshot.stats,
1609
- statuses: snapshot.statuses.map((item: any) => ({
1610
- subtaskId: item.subtaskId,
1611
- title: item.title,
1612
- department: item.department,
1613
- status: item.status,
1614
- progress: item.progress,
1615
- summary: truncate(item.summary ?? item.error ?? '', 2000),
1616
- error: item.error ?? null,
1617
- })),
1618
- }
1992
+ return dispatchSnapshotOf(record)
1619
1993
  }
1620
1994
 
1621
1995
  function plansPayload(sessionId: any) {
@@ -1694,6 +2068,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1694
2068
  updateStatus,
1695
2069
  cancelPlan,
1696
2070
  dispatchTool,
2071
+ statusTool,
1697
2072
  plansPayload,
1698
2073
  route,
1699
2074
  dispose,
@@ -1799,6 +2174,18 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
1799
2174
  modelSelection,
1800
2175
  signal: payload.signal,
1801
2176
  conversationContext,
2177
+ /*
2178
+ * Hand the real limits to the planner. Without them it had no idea the
2179
+ * round budget was 20 minutes and happily planned 15 heavy subtasks,
2180
+ * which then died at the budget wall. The prompt now states the budget
2181
+ * and asks for `estimateMinutes` on every subtask.
2182
+ */
2183
+ budget: {
2184
+ totalMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
2185
+ childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
2186
+ concurrency: MAX_CONCURRENT,
2187
+ maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
2188
+ },
1802
2189
  })
1803
2190
  } catch (error) {
1804
2191
  if (payload.signal.aborted) return downstream
@@ -1859,7 +2246,10 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
1859
2246
  * tool appends the durable result after the children finish, and tools.guard
1860
2247
  * stops the main Agent from doing other work before dispatching.
1861
2248
  */
1862
- const planMessage = buildPlanMessage(fullPlan)
2249
+ const planMessage = buildPlanMessage(fullPlan, {
2250
+ totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
2251
+ maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
2252
+ })
1863
2253
  if (!planMode) return enterDecision(downstream, [planMessage])
1864
2254
  /*
1865
2255
  * Plan mode is a planning-only collaboration state: the plugin must still
@@ -1909,6 +2299,44 @@ export function updateToolOutputSchema() {
1909
2299
  }
1910
2300
  }
1911
2301
 
2302
+ export function cancelToolOutputSchema() {
2303
+ return {
2304
+ type: 'object',
2305
+ properties: {
2306
+ ok: { type: 'boolean' },
2307
+ planId: { type: 'string' },
2308
+ phase: { type: 'string' },
2309
+ reason: { type: 'string' },
2310
+ },
2311
+ required: ['ok'],
2312
+ additionalProperties: true,
2313
+ }
2314
+ }
2315
+
2316
+ export function statusToolOutputSchema() {
2317
+ return {
2318
+ type: 'object',
2319
+ properties: {
2320
+ ok: { type: 'boolean' },
2321
+ planId: { type: 'string' },
2322
+ running: { type: 'boolean' },
2323
+ phase: { type: 'string' },
2324
+ // The host accepts only a single type string per node; a nullable scalar
2325
+ // is expressed with oneOf (type arrays throw JsonSchemaError at activation).
2326
+ elapsedMs: { oneOf: [{ type: 'number' }, { type: 'null' }] },
2327
+ stats: { type: 'object' },
2328
+ statuses: { type: 'array' },
2329
+ errors: { type: 'array' },
2330
+ resumeLimit: { type: 'number' },
2331
+ hint: { type: 'string' },
2332
+ error: { type: 'string' },
2333
+ code: { type: 'string' },
2334
+ },
2335
+ required: ['ok'],
2336
+ additionalProperties: true,
2337
+ }
2338
+ }
2339
+
1912
2340
  export function dispatchToolOutputSchema() {
1913
2341
  return {
1914
2342
  type: 'object',
@@ -1917,6 +2345,11 @@ export function dispatchToolOutputSchema() {
1917
2345
  planId: { type: 'string' },
1918
2346
  alreadyRunning: { type: 'boolean' },
1919
2347
  stale: { type: 'boolean' },
2348
+ running: { type: 'boolean' },
2349
+ joined: { type: 'boolean' },
2350
+ mode: { type: 'string' },
2351
+ elapsedMs: { type: 'number' },
2352
+ statuses: { type: 'array' },
1920
2353
  phase: { type: 'string' },
1921
2354
  stats: { type: 'object' },
1922
2355
  error: { type: 'string' },