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/lib/runtime.js CHANGED
@@ -12,7 +12,9 @@
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 { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, createStatuses, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isStatusQuestion, isVagueContinuation, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, } from './plan.js';
15
+ import { existsSync } from 'node:fs';
16
+ import { isAbsolute, resolve } from 'node:path';
17
+ import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, createStatuses, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isStatusQuestion, isVagueContinuation, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
16
18
  import { createProgressWatchdog, describeError } from './watchdog.js';
17
19
  export const PLANNER_TIMEOUT_MS = 120000;
18
20
  /**
@@ -87,7 +89,7 @@ function taskTextFromMessages(messages) {
87
89
  * it to both the planner and every child. Plugin-generated plan/result rows are
88
90
  * excluded to avoid feeding the plan back into itself.
89
91
  */
90
- function recentConversation(session, maxChars = 7000) {
92
+ function recentConversation(session, maxChars = MAX_CONVERSATION_CHARS) {
91
93
  if (!session || typeof session.eventAt !== 'function')
92
94
  return '';
93
95
  const parts = [];
@@ -174,7 +176,7 @@ async function collectStream(stream) {
174
176
  return text;
175
177
  }
176
178
  async function runPlanner(ctx, options) {
177
- const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '' } = options;
179
+ const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {} } = options;
178
180
  let lastErrors = [];
179
181
  for (let attempt = 1; attempt <= 2; attempt += 1) {
180
182
  if (signal.aborted)
@@ -186,7 +188,7 @@ async function runPlanner(ctx, options) {
186
188
  controller.abort(new PlanError('规划器超时', 'PLANNER_TIMEOUT'));
187
189
  }, PLANNER_TIMEOUT_MS);
188
190
  try {
189
- let prompt = buildPlannerPrompt(taskText, cwd, conversationContext);
191
+ let prompt = buildPlannerPrompt(taskText, cwd, conversationContext, budget);
190
192
  if (lastErrors.length > 0) {
191
193
  prompt += [
192
194
  '',
@@ -329,7 +331,7 @@ export function normaliseIdleTimeout(value) {
329
331
  function writeSubtaskStatus(record, subtaskId, patch, guard) {
330
332
  if (guard.timedOut)
331
333
  return false;
332
- record.statuses = applyStatus(record.statuses, subtaskId, patch);
334
+ record.statuses = applyStatus(record.statuses, subtaskId, { updatedBy: 'child', ...patch });
333
335
  record.updatedAt = Date.now();
334
336
  return true;
335
337
  }
@@ -338,9 +340,107 @@ function recordSubtaskError(record, subtaskId, message, guard) {
338
340
  return;
339
341
  record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20);
340
342
  }
343
+ /**
344
+ * Resolve one artifact reference against the round's working directory.
345
+ *
346
+ * Relative refs are what a child is asked to report, so they must be resolved
347
+ * the same way for every check; an empty ref is never "present".
348
+ */
349
+ function resolveArtifactPath(ref, cwd) {
350
+ const text = typeof ref === 'string' ? ref.trim() : '';
351
+ if (!text)
352
+ return '';
353
+ if (isAbsolute(text))
354
+ return text;
355
+ const base = typeof cwd === 'string' && cwd ? cwd : process.cwd();
356
+ return resolve(base, text);
357
+ }
358
+ /**
359
+ * [1.7.0] Check the files a child declared.
360
+ *
361
+ * Only `kind:'file'` is verifiable here. A url or a note is taken at face
362
+ * value; pretending to verify them would be worse than not checking at all.
363
+ * The verdict is recorded rather than enforced: a missing file makes the
364
+ * dependency gate fail, but it does not silently rewrite "done" to "blocked".
365
+ */
366
+ export function checkArtifacts(artifacts, cwd, artifactExists = existsSync) {
367
+ const list = Array.isArray(artifacts) ? artifacts : [];
368
+ const missingArtifacts = [];
369
+ const checked = list.map((item) => {
370
+ if (!isRecord(item) || item.kind !== 'file')
371
+ return item;
372
+ const target = resolveArtifactPath(item.ref, cwd);
373
+ let exists = false;
374
+ try {
375
+ exists = target ? artifactExists(target) === true : false;
376
+ }
377
+ catch {
378
+ exists = false;
379
+ }
380
+ if (!exists)
381
+ missingArtifacts.push(String(item.ref));
382
+ return { ...item, exists };
383
+ });
384
+ return { artifacts: checked, missingArtifacts };
385
+ }
386
+ /**
387
+ * Turn one child output into a status verdict.
388
+ *
389
+ * The decision lives in `adjudicateResult` (a pure function) so the runtime and
390
+ * the session replay cannot disagree. This wrapper only adds the two things
391
+ * that need the environment: the strict/legacy switch and the file check.
392
+ */
393
+ function settleFromOutput(record, subtask, output, guard, options) {
394
+ const verdict = adjudicateResult({ output, strict: options.strictEvidence !== false });
395
+ const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists);
396
+ writeSubtaskStatus(record, subtask.id, {
397
+ status: verdict.status,
398
+ progress: 100,
399
+ finishedAt: Date.now(),
400
+ summary: truncate(output, 3000),
401
+ error: verdict.error,
402
+ verification: verdict.verification,
403
+ acceptance: verdict.acceptance,
404
+ artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
405
+ missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
406
+ needs: verdict.needs.length > 0 ? verdict.needs : undefined,
407
+ }, guard);
408
+ if (verdict.status === 'blocked') {
409
+ recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard);
410
+ }
411
+ else if (checked.missingArtifacts.length > 0) {
412
+ recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard);
413
+ }
414
+ return verdict;
415
+ }
416
+ /**
417
+ * Retry policy for one child attempt.
418
+ *
419
+ * A wedged child (no event for the whole idle window) is worth one fresh
420
+ * attempt. A hard ceiling means the budget is gone, and an abort is a decision,
421
+ * so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
422
+ * more than one idle window left, otherwise the retry itself would just be
423
+ * killed by the same watchdog.
424
+ */
425
+ export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
426
+ if (attempt >= 2)
427
+ return false;
428
+ const code = error?.code;
429
+ if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT')
430
+ return false;
431
+ if (/aborted|refusal/i.test(String(error?.message ?? '')))
432
+ return false;
433
+ if (code === 'CHILD_STALLED')
434
+ return true;
435
+ if (code === 'CHILD_NOT_COMPLETED') {
436
+ return Number(remainingMs) > Number(idleTimeoutMs);
437
+ }
438
+ return true;
439
+ }
341
440
  async function executeSubtask(ctx, record, stage, subtask, options) {
342
441
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
343
442
  let lastError = null;
443
+ let lastFailure = null;
344
444
  try {
345
445
  if (!writeSubtaskStatus(record, subtask.id, {
346
446
  status: 'in_progress',
@@ -380,6 +480,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
380
480
  })),
381
481
  cwd: options.cwd,
382
482
  conversationContext,
483
+ statuses: record.statuses,
484
+ previousFailure: attempt > 1 ? lastFailure : null,
383
485
  }),
384
486
  }],
385
487
  parent: options.agent,
@@ -450,24 +552,16 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
450
552
  }
451
553
  if (!output)
452
554
  throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT');
453
- if (/^\s*BLOCKED\s*[::]/i.test(output)) {
454
- writeSubtaskStatus(record, subtask.id, {
455
- status: 'blocked',
456
- progress: 100,
457
- finishedAt: Date.now(),
458
- summary: truncate(output, 3000),
459
- error: truncate(output.replace(/^\s*BLOCKED\s*[::]\s*/i, ''), 2000),
460
- }, guard);
461
- recordSubtaskError(record, subtask.id, output, guard);
462
- return;
463
- }
464
- writeSubtaskStatus(record, subtask.id, {
465
- status: 'done',
466
- progress: 100,
467
- finishedAt: Date.now(),
468
- summary: truncate(output, 3000),
469
- error: null,
470
- }, guard);
555
+ /*
556
+ * [1.7.0] Evidence decides the verdict.
557
+ *
558
+ * The old rule was "not BLOCKED => done", so a child that reported
559
+ * unverified or failed self-checks was still counted as finished and
560
+ * the main Agent had nothing to review but prose. `adjudicateResult`
561
+ * is the single deterministic table; `settleFromOutput` adds the
562
+ * environment-dependent artifact check.
563
+ */
564
+ settleFromOutput(record, subtask, output, guard, options);
471
565
  return;
472
566
  }
473
567
  catch (error) {
@@ -475,27 +569,37 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
475
569
  if (guard.timedOut)
476
570
  break;
477
571
  const isAbort = parentSignal.aborted || child.controller.signal.aborted;
572
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
573
+ const remaining = deadline - Date.now();
478
574
  /*
479
- * Two failure kinds, two different correct reactions.
575
+ * [1.7.0] The retry carries the previous failure with it.
480
576
  *
481
- * A stalled child is wedged — no event for the whole idle window — so
482
- * one fresh attempt can succeed and is worth trying. A hard ceiling
483
- * means the budget is gone, so retrying would only burn the plan's
484
- * remaining time; it goes straight to blocked.
577
+ * Retrying with an identical prompt made the child repeat the same
578
+ * dead end and produced the same error twice. The next attempt now
579
+ * receives the code, message and attempt number, so it can change
580
+ * approach — or stop honestly.
485
581
  */
486
- const stalled = error?.code === 'CHILD_STALLED';
487
- if (stalled && attempt < 2 && !isAbort) {
582
+ lastFailure = {
583
+ attempt,
584
+ code: error?.code ?? 'UNKNOWN',
585
+ message: describeError(error),
586
+ };
587
+ const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs);
588
+ if (retry) {
488
589
  record.errors = [
489
590
  ...record.errors,
490
- `${subtask.id}: 第 ${attempt} 次执行无进展,已停止并重试`,
591
+ `${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
491
592
  ].slice(-20);
492
593
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
493
594
  continue;
494
595
  }
495
- if (isAbort || attempt >= 2 || error?.code === 'CHILD_NOT_COMPLETED' && /aborted|refusal/i.test(String(error?.message ?? ''))) {
496
- break;
596
+ if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
597
+ record.errors = [
598
+ ...record.errors,
599
+ `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
600
+ ].slice(-20);
497
601
  }
498
- writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
602
+ break;
499
603
  }
500
604
  finally {
501
605
  if (activation) {
@@ -626,6 +730,30 @@ async function runWithConcurrency(items, limit, worker) {
626
730
  * @param limits - resolved runtime limits (the resume budget comes from here).
627
731
  * @returns a user message carrying the `workplan-result` payload.
628
732
  */
733
+ /**
734
+ * The subtask rows a dispatch/status tool returns to the model.
735
+ *
736
+ * One definition, because the same plan was described in three slightly
737
+ * different shapes (dispatch tail, already-running branch, status tool) and the
738
+ * model could see three different answers in one turn.
739
+ */
740
+ export function modelStatusLines(statuses) {
741
+ const list = Array.isArray(statuses) ? statuses : [];
742
+ return list.map((item) => ({
743
+ subtaskId: item.subtaskId,
744
+ title: item.title,
745
+ department: item.department,
746
+ status: item.status,
747
+ progress: item.progress,
748
+ summary: truncate(item.summary ?? item.error ?? '', 2000),
749
+ error: item.error ?? null,
750
+ verification: item.verification ?? null,
751
+ revision: Number(item.revision ?? 0),
752
+ updatedBy: item.updatedBy ?? null,
753
+ missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
754
+ needs: Array.isArray(item.needs) ? item.needs : [],
755
+ }));
756
+ }
629
757
  export function buildRoundResult(record, sessionId, limits) {
630
758
  const { statuses, stats } = derivePlanSnapshot(record.statuses);
631
759
  return buildResultMessage({
@@ -705,7 +833,18 @@ export async function dispatchPlan(ctx, record, options) {
705
833
  throw abortError();
706
834
  if (Date.now() >= deadline)
707
835
  throw new PlanError('总执行超时', 'TOTAL_TIMEOUT');
708
- const ready = readySubtasks(record.plan, record.statuses);
836
+ /*
837
+ * [1.7.0] A `done` upstream only unblocks its dependents when the files it
838
+ * declared actually exist. The check is opt-out (`artifactGate:false`) so
839
+ * an older plan or a debugging session can keep plain status semantics.
840
+ */
841
+ const gate = options.artifactGate !== false;
842
+ const ready = readySubtasks(record.plan, record.statuses, gate
843
+ ? {
844
+ dependencyOk: (dependency) => dependency?.status === 'done'
845
+ && !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
846
+ }
847
+ : {});
709
848
  if (ready.length === 0) {
710
849
  const pending = record.statuses.filter((item) => item.status === 'pending');
711
850
  for (const item of pending) {
@@ -733,13 +872,27 @@ export async function dispatchPlan(ctx, record, options) {
733
872
  modelSelection,
734
873
  cwd,
735
874
  conversationContext,
875
+ strictEvidence: options.strictEvidence,
876
+ artifactExists: options.artifactExists,
736
877
  });
737
878
  });
738
879
  const blocked = record.statuses
739
880
  .filter((item) => item.status === 'blocked')
740
881
  .map((item) => item.subtaskId);
741
882
  for (const id of blocked) {
742
- record.statuses = markDependentsBlocked(record.plan, record.statuses, id);
883
+ /*
884
+ * Carry the actual cause downstream. The main Agent used to receive
885
+ * "上游子任务受阻: T2" with no reason and no missing artifacts, so it
886
+ * had to re-read the whole plan to guess what to repair.
887
+ */
888
+ const upstream = record.statuses.find((item) => item.subtaskId === id);
889
+ const cause = upstream
890
+ ? {
891
+ reason: upstream.error,
892
+ missingArtifacts: Array.isArray(upstream.missingArtifacts) ? upstream.missingArtifacts : [],
893
+ }
894
+ : null;
895
+ record.statuses = markDependentsBlocked(record.plan, record.statuses, id, cause);
743
896
  }
744
897
  /*
745
898
  * No stats refresh here any more: `serialisePlan` derives the counts from
@@ -1082,6 +1235,30 @@ export function reconstructFromSession(session, targetPlanId) {
1082
1235
  resultPhase = typeof result.phase === 'string' ? result.phase : '';
1083
1236
  resultSeen = true;
1084
1237
  }
1238
+ /*
1239
+ * [1.7.0] Manual re-adjudications replay in order.
1240
+ *
1241
+ * `dsh_workplan_update` used to live only in the live cache, so a refresh
1242
+ * reverted the dashboard to the child's original verdict. The durable
1243
+ * `workplan-update` message is small and append-only, so replay is just
1244
+ * "apply it when its turn comes"; a lower revision never overwrites a
1245
+ * newer one (see `applyResultStatuses`).
1246
+ */
1247
+ const update = parseUpdateMessage(event.data);
1248
+ if (update && plan && update.planId === plan.planId && typeof update.subtaskId === 'string') {
1249
+ try {
1250
+ statuses = applyStatus(statuses, update.subtaskId, {
1251
+ status: update.status,
1252
+ progress: typeof update.progress === 'number' ? update.progress : undefined,
1253
+ summary: typeof update.note === 'string' ? update.note : undefined,
1254
+ revision: Number.isInteger(update.revision) ? update.revision : undefined,
1255
+ updatedBy: 'agent',
1256
+ });
1257
+ }
1258
+ catch {
1259
+ // An invalid historical update is ignored; the rest still replays.
1260
+ }
1261
+ }
1085
1262
  const cancel = parseCancelMessage(event.data);
1086
1263
  if (cancel && plan && cancel.planId === plan.planId) {
1087
1264
  cancelled = true;
@@ -1273,7 +1450,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
1273
1450
  if (downstream?.kind !== 'enter')
1274
1451
  return downstream;
1275
1452
  try {
1276
- return await maybePlan(ctx, state, payload, downstream, options);
1453
+ return await maybePlan(ctx, state, payload, downstream, { ...options, limits });
1277
1454
  }
1278
1455
  catch (error) {
1279
1456
  try {
@@ -1333,14 +1510,78 @@ export function createWorkplanRuntime(ctx, options = {}) {
1333
1510
  ? args.evidence.filter((item) => typeof item === 'string').join(';')
1334
1511
  : '';
1335
1512
  const summary = [note, evidence].filter(Boolean).join('|');
1513
+ const current = record.statuses.find((item) => item.subtaskId === subtaskId);
1514
+ /*
1515
+ * [1.7.0] Two write guards, both non-throwing.
1516
+ *
1517
+ * 1. A stale revision means the caller is looking at an older snapshot; the
1518
+ * write is refused instead of silently overwriting newer evidence.
1519
+ * 2. While the plan is running, the child owns the status of the subtask it
1520
+ * is executing. An agent edit would race the child's settlement (and the
1521
+ * child would overwrite it back). `force:true` is the explicit override,
1522
+ * recorded as a manual re-adjudication.
1523
+ */
1524
+ if (Number.isInteger(args?.expectedRevision) && (current?.revision ?? 0) !== args.expectedRevision) {
1525
+ return {
1526
+ ok: false,
1527
+ code: 'STALE_WRITE',
1528
+ planId: record.plan.planId,
1529
+ subtaskId,
1530
+ current: {
1531
+ status: current?.status ?? null,
1532
+ revision: current?.revision ?? 0,
1533
+ updatedBy: current?.updatedBy ?? null,
1534
+ },
1535
+ hint: `该子任务已被更新(当前 revision ${current?.revision ?? 0},你基于 ${args.expectedRevision});请重新读取状态后再改。`,
1536
+ };
1537
+ }
1538
+ const running = Boolean(record.dispatchPromise);
1539
+ const writeWhileRunning = running && !args?.force && (current?.status === 'pending' || current?.status === 'in_progress');
1540
+ if (writeWhileRunning) {
1541
+ return {
1542
+ ok: false,
1543
+ code: 'TASK_RUNNING',
1544
+ planId: record.plan.planId,
1545
+ subtaskId,
1546
+ current: {
1547
+ status: current?.status ?? null,
1548
+ revision: current?.revision ?? 0,
1549
+ updatedBy: current?.updatedBy ?? null,
1550
+ },
1551
+ hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
1552
+ };
1553
+ }
1554
+ const revision = Number(current?.revision ?? 0) + 1;
1336
1555
  record.statuses = applyStatus(record.statuses, subtaskId, {
1337
1556
  status,
1338
1557
  progress: typeof args?.progress === 'number' ? args.progress : undefined,
1339
1558
  summary: summary || undefined,
1340
1559
  error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
1560
+ revision,
1561
+ updatedBy: 'agent',
1341
1562
  });
1342
1563
  if (status === 'blocked') {
1343
- record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId);
1564
+ record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' });
1565
+ }
1566
+ /*
1567
+ * [1.7.0] A re-adjudication is durable.
1568
+ *
1569
+ * `applyStatus` only touched the in-memory record, so after a refresh the
1570
+ * manual verdict vanished and the dashboard fell back to the old child
1571
+ * result. Appending one small message keeps the replay path honest.
1572
+ */
1573
+ try {
1574
+ session.append('user/message', buildUpdateMessage({
1575
+ planId: record.plan.planId,
1576
+ subtaskId,
1577
+ status,
1578
+ progress: typeof args?.progress === 'number' ? args.progress : undefined,
1579
+ note: summary || undefined,
1580
+ revision,
1581
+ }), { surfaceOp: 'append' });
1582
+ }
1583
+ catch (error) {
1584
+ pushRecordError(record, error);
1344
1585
  }
1345
1586
  /*
1346
1587
  * [1.5.2] 这里曾是「100% + 正在收尾」的直接入口。
@@ -1354,11 +1595,14 @@ export function createWorkplanRuntime(ctx, options = {}) {
1354
1595
  record.phase = reconcilePhase(record.phase, record.statuses);
1355
1596
  record.updatedAt = Date.now();
1356
1597
  const snapshot = derivePlanSnapshot(record.statuses);
1598
+ const written = snapshot.statuses.find((item) => item.subtaskId === subtaskId);
1357
1599
  return {
1358
1600
  ok: true,
1359
1601
  planId: record.plan.planId,
1360
1602
  subtaskId,
1361
- status: snapshot.statuses.find((item) => item.subtaskId === subtaskId)?.status ?? status,
1603
+ status: written?.status ?? status,
1604
+ revision: written?.revision ?? revision,
1605
+ updatedBy: written?.updatedBy ?? 'agent',
1362
1606
  stats: snapshot.stats,
1363
1607
  };
1364
1608
  }
@@ -1446,6 +1690,91 @@ export function createWorkplanRuntime(ctx, options = {}) {
1446
1690
  stats: derivePlanSnapshot(record.statuses).stats,
1447
1691
  };
1448
1692
  }
1693
+ /**
1694
+ * Persist the round result and settle the phase.
1695
+ *
1696
+ * Extracted from the wait path so an async dispatch reaches exactly the same
1697
+ * end state: a durable result message plus a reconciled phase. Anything less
1698
+ * would make "start now, read later" a second, divergent code path.
1699
+ */
1700
+ function finishRound(record, session) {
1701
+ if (!record.resultWritten) {
1702
+ const resultMessage = buildRoundResult(record, session.id, limits);
1703
+ try {
1704
+ session.append('user/message', resultMessage, { surfaceOp: 'append' });
1705
+ record.resultWritten = true;
1706
+ }
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
+ function dispatchSnapshotOf(record, extra = {}) {
1722
+ const snapshot = derivePlanSnapshot(record.statuses);
1723
+ return {
1724
+ ok: true,
1725
+ planId: record.plan.planId,
1726
+ alreadyRunning: false,
1727
+ ...extra,
1728
+ phase: record.phase,
1729
+ stats: snapshot.stats,
1730
+ statuses: modelStatusLines(snapshot.statuses),
1731
+ };
1732
+ }
1733
+ /**
1734
+ * Read-only progress probe for the main Agent.
1735
+ *
1736
+ * With async dispatch the model no longer blocks until the round ends, so it
1737
+ * needs a supported way to answer "做成什么样了" without guessing. This is the
1738
+ * only source it should read: same `derivePlanSnapshot` as the dashboard and
1739
+ * the result message, so all three cannot disagree.
1740
+ */
1741
+ async function statusTool(agent, args) {
1742
+ const session = agent?.session;
1743
+ if (!session)
1744
+ throw new PlanError('只能在会话内查看计划', 'NO_SESSION');
1745
+ const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined;
1746
+ let record = state.records.get(session.id);
1747
+ if (!record?.plan || (requestedPlanId && record.plan.planId !== requestedPlanId)) {
1748
+ const rebuilt = reconstructFromSession(session, requestedPlanId);
1749
+ if (rebuilt?.plan)
1750
+ 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
+ }
1449
1778
  async function dispatchTool(agent, args, signal) {
1450
1779
  const session = agent?.session;
1451
1780
  if (!session)
@@ -1490,6 +1819,36 @@ export function createWorkplanRuntime(ctx, options = {}) {
1490
1819
  if (args?.planId && record.plan.planId !== args.planId) {
1491
1820
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
1492
1821
  }
1822
+ /*
1823
+ * [1.7.0] Two dispatch modes.
1824
+ *
1825
+ * `wait` (default, backward compatible) blocks until the round ends.
1826
+ * `async` starts the round and returns immediately, so the main Agent can
1827
+ * answer the user and keep integrating instead of sitting blind inside a
1828
+ * tool call for twenty minutes (the top-ranked collaboration break C1).
1829
+ */
1830
+ const mode = args?.mode === 'async' ? 'async' : 'wait';
1831
+ if (mode === 'wait' && record.dispatchPromise) {
1832
+ /*
1833
+ * A wait caller that meets an in-flight round joins it instead of being
1834
+ * told "already running" — the old answer carried no results at all, so
1835
+ * a model that missed the async result message had nothing to integrate.
1836
+ * A wedged promise keeps the old stale escape hatch (see below).
1837
+ */
1838
+ const startedAt = Number(record.dispatchStartedAt ?? 0);
1839
+ const staleAfter = limits.totalTimeoutMs + 120000;
1840
+ if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
1841
+ try {
1842
+ await record.dispatchPromise;
1843
+ }
1844
+ catch (error) {
1845
+ pushRecordError(record, error);
1846
+ }
1847
+ finishRound(record, session);
1848
+ state.records.set(session.id, record);
1849
+ return dispatchSnapshotOf(record, { joined: true });
1850
+ }
1851
+ }
1493
1852
  if (record.dispatchPromise) {
1494
1853
  /*
1495
1854
  * "Already running" must not become a permanent answer.
@@ -1516,7 +1875,25 @@ export function createWorkplanRuntime(ctx, options = {}) {
1516
1875
  hint: '请主 Agent 直接接手完成剩余子任务,不要再次派发;并在答复中说明本次是直接执行而非派发。',
1517
1876
  };
1518
1877
  }
1519
- return { ok: true, planId: record.plan.planId, alreadyRunning: true, phase: record.phase, startedAt: startedAt || null };
1878
+ /*
1879
+ * [1.7.0] The idempotent answer now carries the progress itself.
1880
+ *
1881
+ * It used to say only `alreadyRunning: true`, so a second dispatch gave
1882
+ * the model strictly less information than doing nothing.
1883
+ */
1884
+ const live = derivePlanSnapshot(record.statuses);
1885
+ return {
1886
+ ok: true,
1887
+ planId: record.plan.planId,
1888
+ alreadyRunning: true,
1889
+ running: true,
1890
+ phase: record.phase,
1891
+ startedAt: startedAt || null,
1892
+ elapsedMs: startedAt ? Date.now() - startedAt : null,
1893
+ stats: live.stats,
1894
+ statuses: modelStatusLines(live.statuses),
1895
+ hint: '计划仍在执行:先向用户报告进度,不要声称完成;用 dsh_workplan_status 查看实时状态。',
1896
+ };
1520
1897
  }
1521
1898
  /*
1522
1899
  * Refuse with an explanation instead of silently "succeeding".
@@ -1577,47 +1954,47 @@ export function createWorkplanRuntime(ctx, options = {}) {
1577
1954
  record.abortDispatch = null;
1578
1955
  signal?.removeEventListener?.('abort', onToolAbort);
1579
1956
  });
1580
- await record.dispatchPromise;
1581
- if (!record.resultWritten) {
1582
- const resultMessage = buildRoundResult(record, session.id, limits);
1583
- try {
1584
- session.append('user/message', resultMessage, { surfaceOp: 'append' });
1585
- record.resultWritten = true;
1586
- }
1587
- catch (error) {
1588
- ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
1589
- }
1957
+ if (mode === 'async') {
1958
+ /*
1959
+ * Settlement happens in the background: the same durable result message
1960
+ * is appended when the round ends, so a page refresh (or a later turn)
1961
+ * still sees the outcome. The returned values are a *starting* snapshot,
1962
+ * never a completion claim.
1963
+ */
1964
+ const startedAt = record.dispatchStartedAt;
1965
+ record.dispatchPromise
1966
+ .then(() => {
1967
+ finishRound(record, session);
1968
+ state.records.set(session.id, record);
1969
+ })
1970
+ .catch((error) => {
1971
+ pushRecordError(record, error);
1972
+ finishRound(record, session);
1973
+ state.records.set(session.id, record);
1974
+ });
1975
+ const live = derivePlanSnapshot(record.statuses);
1976
+ return {
1977
+ ok: true,
1978
+ planId: record.plan.planId,
1979
+ mode: 'async',
1980
+ running: true,
1981
+ alreadyRunning: false,
1982
+ phase: record.phase,
1983
+ startedAt,
1984
+ stats: live.stats,
1985
+ statuses: modelStatusLines(live.statuses),
1986
+ hint: '计划已开跑,尚未完成:先向用户说明“已派发、正在执行”,不要声称完成;'
1987
+ + '结果消息会在本轮结束时自动出现,期间可用 dsh_workplan_status 查看进度。',
1988
+ };
1590
1989
  }
1591
- /*
1592
- * [1.5.2] 终态不再依赖「结果消息写成功」这个副作用。
1593
- *
1594
- * 旧代码只有 `record.resultWritten === true` 时才把 phase 升成 done,
1595
- * 于是 session.append 抛错(或该轮根本没有派发)就会永久停在 integrating。
1596
- * 完成语义由 statuses 决定;结果消息只负责持久化,不负责定义完成。
1597
- */
1598
- record.phase = reconcilePhase(record.phase, record.statuses);
1990
+ await record.dispatchPromise;
1991
+ finishRound(record, session);
1599
1992
  /*
1600
1993
  * The model's dispatch result reports the same snapshot the dashboard will
1601
1994
  * show. It used to send `record.stats` while the status list below was read
1602
1995
  * fresh, so one reply could say “已完成 11” next to twelve finished rows.
1603
1996
  */
1604
- const snapshot = derivePlanSnapshot(record.statuses);
1605
- return {
1606
- ok: true,
1607
- planId: record.plan.planId,
1608
- alreadyRunning: false,
1609
- phase: record.phase,
1610
- stats: snapshot.stats,
1611
- statuses: snapshot.statuses.map((item) => ({
1612
- subtaskId: item.subtaskId,
1613
- title: item.title,
1614
- department: item.department,
1615
- status: item.status,
1616
- progress: item.progress,
1617
- summary: truncate(item.summary ?? item.error ?? '', 2000),
1618
- error: item.error ?? null,
1619
- })),
1620
- };
1997
+ return dispatchSnapshotOf(record);
1621
1998
  }
1622
1999
  function plansPayload(sessionId) {
1623
2000
  return buildPlansPayload(ctx, state, sessionId);
@@ -1695,6 +2072,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
1695
2072
  updateStatus,
1696
2073
  cancelPlan,
1697
2074
  dispatchTool,
2075
+ statusTool,
1698
2076
  plansPayload,
1699
2077
  route,
1700
2078
  dispose,
@@ -1809,6 +2187,18 @@ async function maybePlan(ctx, state, payload, downstream, options) {
1809
2187
  modelSelection,
1810
2188
  signal: payload.signal,
1811
2189
  conversationContext,
2190
+ /*
2191
+ * Hand the real limits to the planner. Without them it had no idea the
2192
+ * round budget was 20 minutes and happily planned 15 heavy subtasks,
2193
+ * which then died at the budget wall. The prompt now states the budget
2194
+ * and asks for `estimateMinutes` on every subtask.
2195
+ */
2196
+ budget: {
2197
+ totalMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
2198
+ childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
2199
+ concurrency: MAX_CONCURRENT,
2200
+ maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
2201
+ },
1812
2202
  });
1813
2203
  }
1814
2204
  catch (error) {
@@ -1871,7 +2261,10 @@ async function maybePlan(ctx, state, payload, downstream, options) {
1871
2261
  * tool appends the durable result after the children finish, and tools.guard
1872
2262
  * stops the main Agent from doing other work before dispatching.
1873
2263
  */
1874
- const planMessage = buildPlanMessage(fullPlan);
2264
+ const planMessage = buildPlanMessage(fullPlan, {
2265
+ totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
2266
+ maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
2267
+ });
1875
2268
  if (!planMode)
1876
2269
  return enterDecision(downstream, [planMessage]);
1877
2270
  /*
@@ -1919,6 +2312,42 @@ export function updateToolOutputSchema() {
1919
2312
  additionalProperties: true,
1920
2313
  };
1921
2314
  }
2315
+ export function cancelToolOutputSchema() {
2316
+ return {
2317
+ type: 'object',
2318
+ properties: {
2319
+ ok: { type: 'boolean' },
2320
+ planId: { type: 'string' },
2321
+ phase: { type: 'string' },
2322
+ reason: { type: 'string' },
2323
+ },
2324
+ required: ['ok'],
2325
+ additionalProperties: true,
2326
+ };
2327
+ }
2328
+ export function statusToolOutputSchema() {
2329
+ return {
2330
+ type: 'object',
2331
+ properties: {
2332
+ ok: { type: 'boolean' },
2333
+ planId: { type: 'string' },
2334
+ running: { type: 'boolean' },
2335
+ phase: { type: 'string' },
2336
+ // The host accepts only a single type string per node; a nullable scalar
2337
+ // is expressed with oneOf (type arrays throw JsonSchemaError at activation).
2338
+ elapsedMs: { oneOf: [{ type: 'number' }, { type: 'null' }] },
2339
+ stats: { type: 'object' },
2340
+ statuses: { type: 'array' },
2341
+ errors: { type: 'array' },
2342
+ resumeLimit: { type: 'number' },
2343
+ hint: { type: 'string' },
2344
+ error: { type: 'string' },
2345
+ code: { type: 'string' },
2346
+ },
2347
+ required: ['ok'],
2348
+ additionalProperties: true,
2349
+ };
2350
+ }
1922
2351
  export function dispatchToolOutputSchema() {
1923
2352
  return {
1924
2353
  type: 'object',
@@ -1927,6 +2356,11 @@ export function dispatchToolOutputSchema() {
1927
2356
  planId: { type: 'string' },
1928
2357
  alreadyRunning: { type: 'boolean' },
1929
2358
  stale: { type: 'boolean' },
2359
+ running: { type: 'boolean' },
2360
+ joined: { type: 'boolean' },
2361
+ mode: { type: 'string' },
2362
+ elapsedMs: { type: 'number' },
2363
+ statuses: { type: 'array' },
1930
2364
  phase: { type: 'string' },
1931
2365
  stats: { type: 'object' },
1932
2366
  error: { type: 'string' },