dsh-workflow-canvas 1.5.5 → 1.6.0

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/index.js CHANGED
@@ -457,6 +457,23 @@ function briefFor(plan, node, results, failedMap, prunedSet, loopCtx) {
457
457
  return text;
458
458
  }
459
459
 
460
+ function extractResultError(result) {
461
+ if (!result || typeof result !== 'object') return '';
462
+ const candidates = [result.error, result.errorMessage, result.message, result.failureReason];
463
+ for (const raw of candidates) {
464
+ if (typeof raw === 'string' && raw.trim()) return raw.trim();
465
+ if (raw && typeof raw === 'object') {
466
+ const msg = raw.message || raw.detail || raw.code;
467
+ if (typeof msg === 'string' && msg.trim()) return msg.trim();
468
+ try {
469
+ const s = JSON.stringify(raw);
470
+ if (s && s !== '{}') return s.slice(0, 240);
471
+ } catch (_e) { /* ignore */ }
472
+ }
473
+ }
474
+ return '';
475
+ }
476
+
460
477
  function textOf(result) {
461
478
  // A structured node's canonical value is its parsed object, not the prose.
462
479
  if (result && result.structured !== undefined) {
@@ -468,7 +485,10 @@ function textOf(result) {
468
485
  }
469
486
  const blocks = (result && result.output) || [];
470
487
  const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
471
- return text || '[' + ((result && result.stopReason) || 'no-output') + ']';
488
+ if (text) return text;
489
+ const errDetail = extractResultError(result);
490
+ const stop = (result && result.stopReason) || (errDetail ? 'error' : 'no-output');
491
+ return errDetail ? '[' + stop + '] ' + errDetail : '[' + stop + ']';
472
492
  }
473
493
 
474
494
  function failed(result) {
@@ -517,39 +537,42 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
517
537
  if (model) agentOptions.model = model;
518
538
  if (node.reasoning) agentOptions.reasoningEffort = node.reasoning;
519
539
  if (Object.keys(agentOptions).length) spec.agentOptions = agentOptions;
540
+ const allowSchema = !(route && route.noSchema);
520
541
  if (isCondition) {
521
542
  const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
522
543
  spec.agentPreset = 'minimal';
523
- spec.outputSchema = isDefaultBinary
524
- ? {
525
- type: 'object',
526
- properties: {
527
- pass: { type: 'boolean', description: 'true to follow the Yes/Pass branch, false to follow the No/Fail branch.' },
528
- reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
529
- },
530
- required: ['pass', 'reason'],
531
- additionalProperties: false,
532
- }
533
- : {
534
- type: 'object',
535
- properties: {
536
- branches: {
537
- type: 'array',
538
- items: { type: 'string', enum: branches.map((b) => b.id) },
539
- description: multiMatch
540
- ? 'All matching branch ids to execute in parallel (empty array if none match).'
541
- : 'At most one best-matching branch id (empty array if none match).',
544
+ if (allowSchema) {
545
+ spec.outputSchema = isDefaultBinary
546
+ ? {
547
+ type: 'object',
548
+ properties: {
549
+ pass: { type: 'boolean', description: 'true to follow the Yes/Pass branch, false to follow the No/Fail branch.' },
550
+ reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
542
551
  },
543
- reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
544
- },
545
- required: ['branches', 'reason'],
546
- additionalProperties: false,
547
- };
552
+ required: ['pass', 'reason'],
553
+ additionalProperties: false,
554
+ }
555
+ : {
556
+ type: 'object',
557
+ properties: {
558
+ branches: {
559
+ type: 'array',
560
+ items: { type: 'string', enum: branches.map((b) => b.id) },
561
+ description: multiMatch
562
+ ? 'All matching branch ids to execute in parallel (empty array if none match).'
563
+ : 'At most one best-matching branch id (empty array if none match).',
564
+ },
565
+ reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
566
+ },
567
+ required: ['branches', 'reason'],
568
+ additionalProperties: false,
569
+ };
570
+ }
548
571
  } else {
549
572
  if (node.preset) spec.agentPreset = node.preset;
550
573
  const wantsStructured = Boolean(node.structured)
551
574
  || (plan.edges || []).some((e) => e.from === node.id && e.type === 'structured');
552
- if (wantsStructured) {
575
+ if (wantsStructured && allowSchema) {
553
576
  spec.outputSchema = {
554
577
  type: 'object',
555
578
  additionalProperties: true,
@@ -572,7 +595,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
572
595
  activation = await scope.subagents.startActivation(withChild);
573
596
  } catch (error) {
574
597
  const message = String((error && error.message) || error);
575
- return { ok: false, text: '启动失败:' + message, reason: 'activation-failed' };
598
+ return { ok: false, text: '启动失败:' + message, reason: 'activation-failed', errorDetail: message };
576
599
  }
577
600
  try {
578
601
  if (activation && activation.childId) {
@@ -589,13 +612,15 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
589
612
  result = await activation.result;
590
613
  } catch (error) {
591
614
  const message = String((error && error.message) || error);
592
- return { ok: false, text: '运行失败:' + message, reason: 'run-failed' };
615
+ return { ok: false, text: '运行失败:' + message, reason: 'run-failed', errorDetail: message };
593
616
  }
594
617
  const outText = textOf(result);
618
+ const errDetail = extractResultError(result);
595
619
  const outcome = {
596
620
  ok: !failed(result),
597
621
  text: outText,
598
622
  reason: result && result.stopReason,
623
+ errorDetail: errDetail,
599
624
  empty: isEmptyOutput(result),
600
625
  childId: activation && activation.childId ? String(activation.childId) : '',
601
626
  };
@@ -619,7 +644,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
619
644
  if (signal && signal.aborted) return continued;
620
645
  if (continued.ok) {
621
646
  liveChild.set(childKey(node.id), continued.childId || loopCtx.warmChildId);
622
- return continued;
647
+ return { ...continued, warmReused: true };
623
648
  }
624
649
  if (continued.reason !== 'activation-failed') {
625
650
  return continued;
@@ -670,9 +695,17 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
670
695
  return started;
671
696
  }
672
697
 
698
+ function formatModelLabel(provider, model) {
699
+ const p = typeof provider === 'string' ? provider.trim() : '';
700
+ const m = typeof model === 'string' ? model.trim() : '';
701
+ if (p && m) return p + '/' + m;
702
+ return m || p || '';
703
+ }
704
+
673
705
  async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet, loopCtx) {
706
+ const primaryModel = formatModelLabel(node.provider, node.model);
674
707
  if (signal && signal.aborted) {
675
- return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '' };
708
+ return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '', modelUsed: primaryModel, fallbackUsed: false, sessionContinued: false };
676
709
  }
677
710
  const continueFrom = forwardEdgesOf(plan.edges || [])
678
711
  .filter((e) => e.to === node.id && e.type === 'session-ref' && !(prunedSet && prunedSet.has(e.from)))
@@ -684,34 +717,109 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
684
717
  const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet, loopCtx);
685
718
  if (signal && signal.aborted) return continued;
686
719
  if (continued.ok) {
687
- const out = { ok: true, empty: Boolean(continued.empty), text: continued.text + '\n(已在上游会话中继续)', childId: continued.childId || continueFrom };
720
+ const out = {
721
+ ok: true,
722
+ empty: Boolean(continued.empty),
723
+ text: continued.text + '\n(已在上游会话中继续)',
724
+ childId: continued.childId || continueFrom,
725
+ modelUsed: primaryModel,
726
+ fallbackUsed: false,
727
+ sessionContinued: true,
728
+ };
688
729
  if (continued.decision) out.decision = continued.decision;
689
730
  return out;
690
731
  }
691
732
  }
692
733
 
693
- const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
734
+ let first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
694
735
  if (signal && signal.aborted) return first;
736
+ // Many models/proxies reject strict `outputSchema` (`json_schema`) with stopReason='error'.
737
+ // For condition/structured nodes, automatically retry once on the same model without outputSchema
738
+ // so `parseConditionDecision` can parse plain-text JSON before giving up or falling back.
739
+ const usedSchema = node.kind === 'condition'
740
+ || Boolean(node.structured)
741
+ || (plan.edges || []).some((e) => e.from === node.id && e.type === 'structured');
742
+ if (!first.ok && usedSchema && first.reason !== 'activation-failed' && first.reason !== 'aborted' && !isPermissionFailure(first)) {
743
+ const plainRetry = await spawnOnce(scope, plan, node, results, parent, signal, { noSchema: true }, undefined, sid, failedMap, prunedSet, loopCtx);
744
+ if (signal && signal.aborted) return plainRetry;
745
+ if (plainRetry.ok) {
746
+ first = plainRetry;
747
+ } else if (plainRetry.errorDetail && !first.errorDetail) {
748
+ first = plainRetry;
749
+ }
750
+ }
695
751
  if (first.ok) {
696
- const out = { ok: true, empty: Boolean(first.empty), text: first.text, childId: first.childId || '' };
752
+ const out = {
753
+ ok: true,
754
+ empty: Boolean(first.empty),
755
+ text: first.text,
756
+ childId: first.childId || '',
757
+ modelUsed: primaryModel,
758
+ fallbackUsed: false,
759
+ sessionContinued: Boolean(first.warmReused),
760
+ };
697
761
  if (first.decision) out.decision = first.decision;
698
762
  return out;
699
763
  }
700
764
  if (!node.fallbackModel && !node.fallbackProvider) {
701
765
  const reason = first.reason || 'unknown';
702
- return { ok: false, empty: false, reason, text: first.text + '\n(失败原因:' + reason + ',未配置备用模型)', childId: first.childId || '' };
766
+ const detail = first.errorDetail || '';
767
+ const modelTag = primaryModel ? ('模型 ' + primaryModel) : '默认模型';
768
+ const suffix = detail ? (reason + ' — ' + detail) : reason;
769
+ return {
770
+ ok: false,
771
+ empty: false,
772
+ reason,
773
+ errorDetail: detail,
774
+ text: first.text + '\n(' + modelTag + ' 执行失败:' + suffix + ')',
775
+ childId: first.childId || '',
776
+ modelUsed: primaryModel,
777
+ fallbackUsed: false,
778
+ sessionContinued: false,
779
+ };
703
780
  }
704
- const retry = await spawnOnce(scope, plan, node, results, parent, signal, {
781
+ const fallbackLabel = formatModelLabel(node.fallbackProvider || node.provider, node.fallbackModel || node.model);
782
+ let retry = await spawnOnce(scope, plan, node, results, parent, signal, {
705
783
  provider: node.fallbackProvider,
706
784
  model: node.fallbackModel,
707
785
  }, undefined, sid, failedMap, prunedSet, loopCtx);
786
+ if (signal && signal.aborted) return retry;
787
+ if (!retry.ok && usedSchema && retry.reason !== 'activation-failed' && retry.reason !== 'aborted' && !isPermissionFailure(retry)) {
788
+ const plainFallback = await spawnOnce(scope, plan, node, results, parent, signal, {
789
+ provider: node.fallbackProvider,
790
+ model: node.fallbackModel,
791
+ noSchema: true,
792
+ }, undefined, sid, failedMap, prunedSet, loopCtx);
793
+ if (signal && signal.aborted) return plainFallback;
794
+ if (plainFallback.ok || (plainFallback.errorDetail && !retry.errorDetail)) retry = plainFallback;
795
+ }
708
796
  if (retry.ok) {
709
- const out = { ok: true, empty: Boolean(retry.empty), text: retry.text + '\n(已用备用模型重试成功)', childId: retry.childId || '' };
797
+ const out = {
798
+ ok: true,
799
+ empty: Boolean(retry.empty),
800
+ text: retry.text + '\n(已用备用模型重试成功)',
801
+ childId: retry.childId || '',
802
+ modelUsed: fallbackLabel,
803
+ fallbackUsed: true,
804
+ sessionContinued: Boolean(retry.warmReused),
805
+ };
710
806
  if (retry.decision) out.decision = retry.decision;
711
807
  return out;
712
808
  }
713
809
  const reason = retry.reason || 'unknown';
714
- return { ok: false, empty: false, reason, text: retry.text + '\n(重试仍失败:' + reason + ')', childId: retry.childId || first.childId || '' };
810
+ const retryDetail = retry.errorDetail || '';
811
+ const suffix = retryDetail ? (reason + ' — ' + retryDetail) : reason;
812
+ return {
813
+ ok: false,
814
+ empty: false,
815
+ reason,
816
+ errorDetail: retryDetail,
817
+ text: retry.text + '\n(备用模型 ' + (fallbackLabel || '默认') + ' 重试仍失败:' + suffix + ')',
818
+ childId: retry.childId || first.childId || '',
819
+ modelUsed: fallbackLabel,
820
+ fallbackUsed: true,
821
+ sessionContinued: false,
822
+ };
715
823
  }
716
824
 
717
825
  /** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
@@ -1202,10 +1310,133 @@ function publishCanvas(scope, sessionId, canvas) {
1202
1310
  }
1203
1311
  }
1204
1312
 
1313
+ /**
1314
+ * Build a zero-token structured run summary snapshot from in-memory executor state.
1315
+ * Published inside `.run.json` for the sidebar UI (never injected into model prompts).
1316
+ */
1317
+ function buildRunSummarySnapshot(st, opts) {
1318
+ if (!st || typeof st !== 'object') return null;
1319
+ const o = opts || {};
1320
+ const now = typeof o.now === 'number' ? o.now : Date.now();
1321
+ const status = typeof o.status === 'string' && o.status ? o.status : 'running';
1322
+ const waitingLead = o.waitingLead || st.waitingLead || null;
1323
+ const haltedReason = typeof o.haltedReason === 'string' && o.haltedReason
1324
+ ? o.haltedReason
1325
+ : (st.haltedReason || '');
1326
+ const isTerminal = status === 'done' || status === 'halted';
1327
+ const startedAt = typeof st.startedAt === 'number' ? st.startedAt : now;
1328
+ const endedAt = isTerminal ? (typeof st.endedAt === 'number' ? st.endedAt : now) : null;
1329
+ const nodeStatsMap = st.nodeStats && typeof st.nodeStats === 'object' ? st.nodeStats : {};
1330
+ const prunedSet = st.pruned instanceof Set ? st.pruned : new Set(Array.isArray(st.pruned) ? st.pruned : []);
1331
+ const decisions = st.decisions && typeof st.decisions === 'object' ? st.decisions : {};
1332
+ const failedMap = st.failed && typeof st.failed === 'object' ? st.failed : {};
1333
+ const emptyMap = st.emptyOutputs && typeof st.emptyOutputs === 'object' ? st.emptyOutputs : {};
1334
+ const nodeMeta = st.nodeMeta && typeof st.nodeMeta === 'object' ? st.nodeMeta : {};
1335
+ const orderIds = Array.isArray(st.orderIds) && st.orderIds.length
1336
+ ? st.orderIds
1337
+ : Object.keys(nodeStatsMap);
1338
+
1339
+ const nodes = [];
1340
+ for (const id of orderIds) {
1341
+ const meta = nodeMeta[id] || {};
1342
+ const stat = nodeStatsMap[id] || null;
1343
+ const dec = decisions[id] || null;
1344
+ const fail = failedMap[id] || null;
1345
+ const isPruned = prunedSet.has(id);
1346
+ const isWaiting = Boolean(status === 'need-lead' && waitingLead && waitingLead.id === id);
1347
+
1348
+ let entryStatus = 'pending';
1349
+ let durationMs = stat && typeof stat.durationMs === 'number' ? stat.durationMs : 0;
1350
+ let entryStartedAt = stat && typeof stat.startedAt === 'number' ? stat.startedAt : null;
1351
+ let entryEndedAt = stat && typeof stat.endedAt === 'number' ? stat.endedAt : null;
1352
+
1353
+ if (isPruned && (!stat || stat.status === 'pending' || stat.status === 'pruned')) {
1354
+ entryStatus = 'pruned';
1355
+ } else if (isWaiting) {
1356
+ entryStatus = 'waiting';
1357
+ } else if (stat && stat.status) {
1358
+ entryStatus = stat.status;
1359
+ if (status === 'halted' && (entryStatus === 'running' || entryStatus === 'waiting')) {
1360
+ entryStatus = 'halted';
1361
+ if (entryStartedAt && !entryEndedAt) {
1362
+ durationMs += Math.max(0, now - entryStartedAt);
1363
+ entryEndedAt = now;
1364
+ }
1365
+ }
1366
+ } else if (fail) {
1367
+ entryStatus = 'failed';
1368
+ } else if (emptyMap[id]) {
1369
+ entryStatus = 'empty';
1370
+ }
1371
+
1372
+ let reason = (stat && typeof stat.reason === 'string' ? stat.reason : '') || (fail && fail.reason) || '';
1373
+ if (!reason && dec) {
1374
+ const matched = Array.isArray(dec.branchLabels) && dec.branchLabels.length
1375
+ ? dec.branchLabels.join(', ')
1376
+ : (dec.branchLabel || dec.branch || '');
1377
+ const decReason = typeof dec.reason === 'string' ? dec.reason.trim() : '';
1378
+ reason = matched ? (decReason ? matched + ' — ' + decReason : matched) : decReason;
1379
+ }
1380
+ if (reason.length > 160) reason = reason.slice(0, 159) + '…';
1381
+
1382
+ nodes.push({
1383
+ id,
1384
+ label: (stat && stat.label) || meta.label || (st.labels && st.labels[id]) || id,
1385
+ kind: (stat && stat.kind) || meta.kind || 'agent',
1386
+ status: entryStatus,
1387
+ startedAt: entryStartedAt,
1388
+ endedAt: entryEndedAt,
1389
+ durationMs,
1390
+ runs: stat && typeof stat.runs === 'number' ? stat.runs : 0,
1391
+ model: (stat && stat.model) || meta.model || '',
1392
+ fallbackUsed: Boolean(stat && stat.fallbackUsed),
1393
+ sessionContinued: Boolean(stat && stat.sessionContinued),
1394
+ childId: (stat && stat.childId) || '',
1395
+ reason,
1396
+ });
1397
+ }
1398
+
1399
+ const loopMeta = Array.isArray(st.loopMeta) ? st.loopMeta : [];
1400
+ const loopCounts = st.loopCounts && typeof st.loopCounts === 'object' ? st.loopCounts : {};
1401
+ const loopHistory = st.loopHistory && typeof st.loopHistory === 'object' ? st.loopHistory : {};
1402
+ const exhaustedKeys = new Set(Array.isArray(st.loopExhausted) ? st.loopExhausted.map((x) => x && x.edgeKey).filter(Boolean) : []);
1403
+ const loops = [];
1404
+ for (const lm of loopMeta) {
1405
+ const used = Number(loopCounts[lm.key]) || 0;
1406
+ const rawRounds = Array.isArray(loopHistory[lm.key]) ? loopHistory[lm.key] : [];
1407
+ const exhausted = exhaustedKeys.has(lm.key);
1408
+ if (used === 0 && rawRounds.length === 0 && !exhausted) continue;
1409
+ loops.push({
1410
+ fromLabel: lm.fromLabel,
1411
+ toLabel: lm.toLabel,
1412
+ used,
1413
+ max: lm.max,
1414
+ exhausted,
1415
+ rounds: rawRounds.map((r) => ({
1416
+ round: r.round,
1417
+ reason: typeof r.reason === 'string' && r.reason.length > 140 ? r.reason.slice(0, 139) + '…' : (r.reason || ''),
1418
+ })),
1419
+ });
1420
+ }
1421
+
1422
+ return {
1423
+ status,
1424
+ startedAt,
1425
+ endedAt,
1426
+ haltedReason,
1427
+ maxParallel: typeof st.maxParallel === 'number' ? st.maxParallel : 4,
1428
+ totalLoops: typeof st.totalLoops === 'number' ? st.totalLoops : 0,
1429
+ reused: Array.isArray(st.reusedIds) ? st.reusedIds.slice() : [],
1430
+ nodes,
1431
+ loops,
1432
+ };
1433
+ }
1434
+
1205
1435
  /**
1206
1436
  * Publish live run-state telemetry (condition decisions, pruned nodes, blocked edges,
1207
- * waitingLead) to `.dsh/canvas/<sessionId>.run.json` so the sidebar canvas can
1208
- * visualize branch routing and verdict reasons without touching the canvas definition file.
1437
+ * waitingLead, and zero-token run summary) to `.dsh/canvas/<sessionId>.run.json` so
1438
+ * the sidebar canvas can visualize branch routing and execution metrics without touching
1439
+ * the canvas definition file or injecting anything into model prompts.
1209
1440
  */
1210
1441
  function publishRunState(scope, sessionId, runState) {
1211
1442
  try {
@@ -1286,6 +1517,9 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1286
1517
  const st = runBySession.get(sid);
1287
1518
  const wasWaiting = Boolean(st && st.waitingLead);
1288
1519
  if (st) {
1520
+ const haltNow = Date.now();
1521
+ st.endedAt = haltNow;
1522
+ st.haltedReason = wasWaiting ? '用户结束了等待拍板状态' : '用户主动终止';
1289
1523
  if (st.done && st.done.size > 0) {
1290
1524
  lastRunBySession.set(sid, {
1291
1525
  sig: st.sig,
@@ -1298,9 +1532,16 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1298
1532
  pruned: new Set(st.pruned || []),
1299
1533
  decisions: { ...(st.decisions || {}) },
1300
1534
  fallbackLinks: Array.isArray(st.fallbackLinks) ? st.fallbackLinks.map((fl) => ({ ...fl })) : [],
1535
+ nodeStats: st.nodeStats ? Object.fromEntries(Object.entries(st.nodeStats).map(([k, v]) => [k, { ...v }])) : {},
1301
1536
  halted: true,
1302
1537
  });
1303
1538
  }
1539
+ const summary = buildRunSummarySnapshot(st, {
1540
+ status: 'halted',
1541
+ waitingLead: null,
1542
+ haltedReason: st.haltedReason,
1543
+ now: haltNow,
1544
+ });
1304
1545
  runBySession.delete(sid);
1305
1546
  publishRunState(scope, sid, {
1306
1547
  status: 'halted',
@@ -1311,6 +1552,7 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1311
1552
  loopCounts: {},
1312
1553
  nodeAttempts: { ...(st.nodeAttempts || {}) },
1313
1554
  waitingLead: null,
1555
+ summary,
1314
1556
  });
1315
1557
  saveStore();
1316
1558
  } else {
@@ -1325,6 +1567,7 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1325
1567
  loopCounts: {},
1326
1568
  nodeAttempts: {},
1327
1569
  waitingLead: null,
1570
+ summary: null,
1328
1571
  });
1329
1572
  }
1330
1573
  return { stopped: true, wasRunning, wasWaiting };
@@ -1574,16 +1817,40 @@ async function executePlan(scope, plan, args, exec) {
1574
1817
 
1575
1818
  const byId = new Map(runnable.map((n) => [n.id, n]));
1576
1819
  const labelOf = new Map(order.map((n) => [n.id, n.label || n.id]));
1820
+ const orderIds = runnable.map((n) => n.id);
1821
+ const nodeMeta = Object.fromEntries(runnable.map((n) => [n.id, {
1822
+ label: n.label || n.id,
1823
+ kind: n.kind || 'agent',
1824
+ model: formatModelLabel(n.provider, n.model),
1825
+ }]));
1826
+ const loopMeta = (plan.edges || [])
1827
+ .filter((e) => isLoopEdge(e))
1828
+ .map((e) => ({
1829
+ key: edgeKey(e),
1830
+ fromLabel: labelOf.get(e.from) || e.from,
1831
+ toLabel: labelOf.get(e.to) || e.to,
1832
+ max: normalizeMaxIterations(e.maxIterations),
1833
+ }));
1834
+ const rawMaxParallel = opts.maxParallel !== undefined ? opts.maxParallel : plan.maxParallel;
1835
+ const MAX_PARALLEL = Number.isFinite(Number(rawMaxParallel))
1836
+ ? Math.max(1, Math.min(8, Math.floor(Number(rawMaxParallel))))
1837
+ : 4;
1577
1838
  const sig = JSON.stringify(plan);
1578
1839
  let state = runBySession.get(sid);
1579
1840
  const wantRetryFailed = opts.retryFailed === true;
1580
1841
  const rawFromNodes = Array.isArray(opts.fromNodes) ? opts.fromNodes.filter((x) => typeof x === 'string' && x.trim()) : [];
1581
1842
  const wantPartial = wantRetryFailed || rawFromNodes.length > 0;
1582
1843
  let reused = [];
1844
+ let reusedIds = [];
1583
1845
 
1584
1846
  if (wantPartial && sid) {
1585
1847
  const base = state || lastRunBySession.get(sid);
1586
1848
  if (base) {
1849
+ const prevStats = base.nodeStats && typeof base.nodeStats === 'object' ? base.nodeStats : {};
1850
+ const carriedStats = {};
1851
+ for (const [k, v] of Object.entries(prevStats)) {
1852
+ if (byId.has(k) && v && typeof v === 'object') carriedStats[k] = { ...v };
1853
+ }
1587
1854
  state = {
1588
1855
  sig,
1589
1856
  done: new Set(Array.from(base.done || []).filter((id) => byId.has(id))),
@@ -1603,6 +1870,15 @@ async function executePlan(scope, plan, args, exec) {
1603
1870
  loopWarmChild: {},
1604
1871
  loopExhausted: [],
1605
1872
  waitingLead: null,
1873
+ startedAt: Date.now(),
1874
+ endedAt: null,
1875
+ haltedReason: '',
1876
+ maxParallel: MAX_PARALLEL,
1877
+ orderIds,
1878
+ nodeMeta,
1879
+ loopMeta,
1880
+ nodeStats: carriedStats,
1881
+ reusedIds: [],
1606
1882
  };
1607
1883
  // Build forward adjacency to invalidate seed nodes and all their downstream dependents.
1608
1884
  const fwd = new Map();
@@ -1639,12 +1915,35 @@ async function executePlan(scope, plan, args, exec) {
1639
1915
  delete state.failed[id];
1640
1916
  delete state.emptyOutputs[id];
1641
1917
  delete state.decisions[id];
1918
+ delete state.nodeStats[id];
1642
1919
  }
1643
1920
  for (const e of plan.edges || []) {
1644
1921
  if (e && invalid.has(e.from)) state.blockedEdges.delete(edgeKey(e));
1645
1922
  }
1646
1923
  state.fallbackLinks = state.fallbackLinks.filter((fl) => !invalid.has(fl.from) && !invalid.has(fl.to));
1647
- reused = Array.from(state.done).filter((id) => !state.pruned.has(id)).map((id) => labelOf.get(id) || id);
1924
+ reusedIds = Array.from(state.done).filter((id) => !state.pruned.has(id));
1925
+ state.reusedIds = reusedIds;
1926
+ for (const id of reusedIds) {
1927
+ const meta = nodeMeta[id] || {};
1928
+ state.nodeStats[id] = {
1929
+ ...(state.nodeStats[id] || {
1930
+ id,
1931
+ label: meta.label || id,
1932
+ kind: meta.kind || 'agent',
1933
+ startedAt: null,
1934
+ endedAt: null,
1935
+ durationMs: 0,
1936
+ runs: 1,
1937
+ model: meta.model || '',
1938
+ fallbackUsed: false,
1939
+ sessionContinued: false,
1940
+ childId: '',
1941
+ reason: '',
1942
+ }),
1943
+ status: 'reused',
1944
+ };
1945
+ }
1946
+ reused = reusedIds.map((id) => labelOf.get(id) || id);
1648
1947
  runBySession.set(sid, state);
1649
1948
  }
1650
1949
  }
@@ -1669,6 +1968,15 @@ async function executePlan(scope, plan, args, exec) {
1669
1968
  loopWarmChild: {},
1670
1969
  loopExhausted: [],
1671
1970
  waitingLead: null,
1971
+ startedAt: Date.now(),
1972
+ endedAt: null,
1973
+ haltedReason: '',
1974
+ maxParallel: MAX_PARALLEL,
1975
+ orderIds,
1976
+ nodeMeta,
1977
+ loopMeta,
1978
+ nodeStats: {},
1979
+ reusedIds: [],
1672
1980
  };
1673
1981
  runBySession.set(sid, state);
1674
1982
  }
@@ -1684,8 +1992,14 @@ async function executePlan(scope, plan, args, exec) {
1684
1992
  if (!state.nodeAttempts) state.nodeAttempts = {};
1685
1993
  if (!state.loopWarmChild) state.loopWarmChild = {};
1686
1994
  if (!state.loopExhausted) state.loopExhausted = [];
1687
-
1688
- const emitRunState = (status, waitingLead) => {
1995
+ if (typeof state.startedAt !== 'number') state.startedAt = Date.now();
1996
+ if (!state.nodeStats) state.nodeStats = {};
1997
+ state.maxParallel = MAX_PARALLEL;
1998
+ state.orderIds = orderIds;
1999
+ state.nodeMeta = nodeMeta;
2000
+ state.loopMeta = loopMeta;
2001
+
2002
+ const emitRunState = (status, waitingLead, reasonOverride) => {
1689
2003
  if (!sid) return;
1690
2004
  const loopCounts = {};
1691
2005
  for (const e of plan.edges || []) {
@@ -1695,6 +2009,11 @@ async function executePlan(scope, plan, args, exec) {
1695
2009
  loopCounts[k] = entry;
1696
2010
  if (e.id) loopCounts[e.id] = entry;
1697
2011
  }
2012
+ const summary = buildRunSummarySnapshot(state, {
2013
+ status,
2014
+ waitingLead,
2015
+ haltedReason: reasonOverride || state.haltedReason || '',
2016
+ });
1698
2017
  publishRunState(scope, sid, {
1699
2018
  status,
1700
2019
  done: Array.from(state.done || []),
@@ -1704,6 +2023,7 @@ async function executePlan(scope, plan, args, exec) {
1704
2023
  loopCounts,
1705
2024
  nodeAttempts: { ...state.nodeAttempts },
1706
2025
  waitingLead: waitingLead ? { id: waitingLead.id, label: waitingLead.label } : null,
2026
+ summary,
1707
2027
  });
1708
2028
  };
1709
2029
  emitRunState('running', null);
@@ -1721,6 +2041,7 @@ async function executePlan(scope, plan, args, exec) {
1721
2041
  pruned: new Set(state.pruned),
1722
2042
  decisions: { ...state.decisions },
1723
2043
  fallbackLinks: state.fallbackLinks.map((fl) => ({ ...fl })),
2044
+ nodeStats: Object.fromEntries(Object.entries(state.nodeStats || {}).map(([k, v]) => [k, { ...v }])),
1724
2045
  halted: Boolean(haltedFlag),
1725
2046
  });
1726
2047
  };
@@ -1864,10 +2185,6 @@ async function executePlan(scope, plan, args, exec) {
1864
2185
  };
1865
2186
 
1866
2187
  let leadResult = typeof opts.leadResult === 'string' ? opts.leadResult : undefined;
1867
- const rawMaxParallel = opts.maxParallel !== undefined ? opts.maxParallel : plan.maxParallel;
1868
- const MAX_PARALLEL = Number.isFinite(Number(rawMaxParallel))
1869
- ? Math.max(1, Math.min(8, Math.floor(Number(rawMaxParallel))))
1870
- : 4;
1871
2188
  // Event-driven concurrency pool: as soon as any node finishes, newly unblocked
1872
2189
  // downstream agents start immediately instead of waiting for slower siblings.
1873
2190
  const inFlight = new Map();
@@ -1904,8 +2221,10 @@ async function executePlan(scope, plan, args, exec) {
1904
2221
  runSignal.addEventListener('abort', () => resolve({ __aborted: true }), { once: true });
1905
2222
  });
1906
2223
  const finishAborted = () => {
2224
+ state.endedAt = Date.now();
2225
+ state.haltedReason = '工作流执行已取消';
1907
2226
  snapshotLastRun(true);
1908
- emitRunState('halted', null);
2227
+ emitRunState('halted', null, state.haltedReason);
1909
2228
  if (sid) runBySession.delete(sid);
1910
2229
  saveStore();
1911
2230
  return {
@@ -1932,19 +2251,39 @@ async function executePlan(scope, plan, args, exec) {
1932
2251
  && !state.done.has(n.id)
1933
2252
  && !inFlight.has(n.id)
1934
2253
  && depsOf(n).every((id) => state.done.has(id)));
2254
+ let launched = 0;
1935
2255
  for (const node of candidates) {
1936
2256
  if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) break;
1937
2257
  const fb = state.loopFeedback[node.id] || null;
1938
2258
  const warmChildId = (fb && state.loopWarmChild[node.id]) ? state.loopWarmChild[node.id] : '';
1939
2259
  const loopCtx = fb ? { feedback: fb, warmChildId } : undefined;
1940
2260
  if (fb) delete state.loopFeedback[node.id];
2261
+ const launchAt = Date.now();
2262
+ const prevStat = state.nodeStats[node.id];
2263
+ state.nodeStats[node.id] = {
2264
+ id: node.id,
2265
+ label: node.label || node.id,
2266
+ kind: node.kind || 'agent',
2267
+ status: 'running',
2268
+ startedAt: launchAt,
2269
+ endedAt: null,
2270
+ durationMs: prevStat && typeof prevStat.durationMs === 'number' ? prevStat.durationMs : 0,
2271
+ runs: (prevStat && typeof prevStat.runs === 'number' ? prevStat.runs : 0) + 1,
2272
+ model: formatModelLabel(node.provider, node.model) || (prevStat && prevStat.model) || '',
2273
+ fallbackUsed: Boolean(prevStat && prevStat.fallbackUsed),
2274
+ sessionContinued: Boolean(prevStat && prevStat.sessionContinued),
2275
+ childId: (prevStat && prevStat.childId) || '',
2276
+ reason: '',
2277
+ };
1941
2278
  const promise = spawnNode(scope, plan, node, state.results, agent, runSignal, sid, state.failed, state.pruned, loopCtx)
1942
2279
  .then(
1943
- (outcome) => ({ node, outcome }),
1944
- (err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
2280
+ (outcome) => ({ node, outcome, startedAt: launchAt }),
2281
+ (err) => ({ node, startedAt: launchAt, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
1945
2282
  );
1946
2283
  inFlight.set(node.id, promise);
2284
+ launched += 1;
1947
2285
  }
2286
+ if (launched > 0) emitRunState('running', null);
1948
2287
  };
1949
2288
 
1950
2289
  try {
@@ -1956,8 +2295,10 @@ async function executePlan(scope, plan, args, exec) {
1956
2295
  // but let already in-flight siblings settle so no orphan promises or partial
1957
2296
  // results are dropped before returning the halted report.
1958
2297
  if (haltedReason && inFlight.size === 0) {
2298
+ state.endedAt = Date.now();
2299
+ state.haltedReason = haltedReason;
1959
2300
  snapshotLastRun(true);
1960
- emitRunState('halted', null);
2301
+ emitRunState('halted', null, haltedReason);
1961
2302
  if (sid) runBySession.delete(sid);
1962
2303
  saveStore();
1963
2304
  return {
@@ -1976,6 +2317,7 @@ async function executePlan(scope, plan, args, exec) {
1976
2317
  }
1977
2318
  const remaining = runnable.filter((n) => !state.done.has(n.id));
1978
2319
  if (!remaining.length) {
2320
+ state.endedAt = Date.now();
1979
2321
  snapshotLastRun(false);
1980
2322
  emitRunState('done', null);
1981
2323
  runBySession.delete(sid);
@@ -2001,8 +2343,32 @@ async function executePlan(scope, plan, args, exec) {
2001
2343
  if ((raceHit && raceHit.__aborted) || isAborted()) {
2002
2344
  return finishAborted();
2003
2345
  }
2004
- const { node, outcome } = raceHit;
2346
+ const { node, outcome, startedAt } = raceHit;
2005
2347
  inFlight.delete(node.id);
2348
+ const doneAt = Date.now();
2349
+ const attemptElapsed = typeof startedAt === 'number' ? Math.max(0, doneAt - startedAt) : 0;
2350
+ const prevStat = state.nodeStats[node.id] || {
2351
+ id: node.id,
2352
+ label: node.label || node.id,
2353
+ kind: node.kind || 'agent',
2354
+ durationMs: 0,
2355
+ runs: 1,
2356
+ };
2357
+ state.nodeStats[node.id] = {
2358
+ ...prevStat,
2359
+ label: node.label || node.id,
2360
+ kind: node.kind || 'agent',
2361
+ status: !outcome.ok ? 'failed' : (outcome.empty ? 'empty' : 'done'),
2362
+ endedAt: doneAt,
2363
+ durationMs: (prevStat.durationMs || 0) + attemptElapsed,
2364
+ model: outcome.modelUsed || prevStat.model || formatModelLabel(node.provider, node.model),
2365
+ fallbackUsed: Boolean(prevStat.fallbackUsed || outcome.fallbackUsed),
2366
+ sessionContinued: Boolean(prevStat.sessionContinued || outcome.sessionContinued),
2367
+ childId: outcome.childId || prevStat.childId || '',
2368
+ reason: !outcome.ok
2369
+ ? ((outcome.reason || 'unknown') + (outcome.errorDetail ? ' — ' + outcome.errorDetail : ''))
2370
+ : '',
2371
+ };
2006
2372
  state.labels[node.id] = node.label;
2007
2373
  if (node.kind === 'condition') {
2008
2374
  const { branches, isDefaultBinary } = conditionBranches(node);
@@ -2116,6 +2482,10 @@ async function executePlan(scope, plan, args, exec) {
2116
2482
  delete state.emptyOutputs[mid];
2117
2483
  delete state.decisions[mid];
2118
2484
  state.nodeAttempts[mid] = { retry: nextRetry, max: maxIter };
2485
+ // Preserve cumulative durationMs and runs across loop rounds while marking pending for the next launch.
2486
+ if (state.nodeStats[mid]) {
2487
+ state.nodeStats[mid] = { ...state.nodeStats[mid], status: 'pending', startedAt: null, endedAt: null };
2488
+ }
2119
2489
  }
2120
2490
  for (const e of plan.edges || []) {
2121
2491
  if (e && members.has(e.from)) state.blockedEdges.delete(edgeKey(e));
@@ -2236,6 +2606,7 @@ async function executePlan(scope, plan, args, exec) {
2236
2606
  haltedReason = '连续 ' + activationFailCount + ' 个子代理启动失败,已熔断停止后续节点以防继续消耗额度。请检查模型配置或主对话权限后重试。';
2237
2607
  }
2238
2608
  state.done.add(node.id);
2609
+ emitRunState('running', null);
2239
2610
  continue;
2240
2611
  }
2241
2612
 
@@ -2282,6 +2653,24 @@ async function executePlan(scope, plan, args, exec) {
2282
2653
  if (!hasDownstreamWork && leadResult === undefined) {
2283
2654
  // Terminal Lead: zero downstream nodes remain, so complete the run directly
2284
2655
  // and hand off final review/delivery to the Lead without a redundant extra turn.
2656
+ const termNow = Date.now();
2657
+ const prevLeadStat = state.nodeStats[leadNode.id];
2658
+ state.nodeStats[leadNode.id] = {
2659
+ id: leadNode.id,
2660
+ label: leadNode.label || leadNode.id,
2661
+ kind: 'lead',
2662
+ status: 'done',
2663
+ startedAt: (prevLeadStat && prevLeadStat.startedAt) || termNow,
2664
+ endedAt: termNow,
2665
+ durationMs: prevLeadStat && typeof prevLeadStat.durationMs === 'number' ? prevLeadStat.durationMs : 0,
2666
+ runs: (prevLeadStat && typeof prevLeadStat.runs === 'number' ? prevLeadStat.runs : 0) + 1,
2667
+ model: '',
2668
+ fallbackUsed: false,
2669
+ sessionContinued: false,
2670
+ childId: '',
2671
+ reason: '',
2672
+ };
2673
+ state.endedAt = termNow;
2285
2674
  state.done.add(leadNode.id);
2286
2675
  snapshotLastRun(false);
2287
2676
  emitRunState('done', null);
@@ -2310,6 +2699,23 @@ async function executePlan(scope, plan, args, exec) {
2310
2699
  };
2311
2700
  }
2312
2701
  if (leadResult === undefined) {
2702
+ const pauseNow = Date.now();
2703
+ const prevLeadStat = state.nodeStats[leadNode.id];
2704
+ state.nodeStats[leadNode.id] = {
2705
+ id: leadNode.id,
2706
+ label: leadNode.label || leadNode.id,
2707
+ kind: 'lead',
2708
+ status: 'waiting',
2709
+ startedAt: pauseNow,
2710
+ endedAt: null,
2711
+ durationMs: prevLeadStat && typeof prevLeadStat.durationMs === 'number' ? prevLeadStat.durationMs : 0,
2712
+ runs: (prevLeadStat && typeof prevLeadStat.runs === 'number' ? prevLeadStat.runs : 0) + 1,
2713
+ model: '',
2714
+ fallbackUsed: false,
2715
+ sessionContinued: false,
2716
+ childId: '',
2717
+ reason: '',
2718
+ };
2313
2719
  const leadFbSummary = leadFb
2314
2720
  ? { retry: leadFb.retry, max: leadFb.max, sourceLabel: leadFb.sourceLabel, reason: leadFb.reason }
2315
2721
  : null;
@@ -2341,12 +2747,33 @@ async function executePlan(scope, plan, args, exec) {
2341
2747
  + '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需取消本次流程可传 cancel: true,若需从头重跑可传 reset: true。',
2342
2748
  };
2343
2749
  }
2750
+ const resumeNow = Date.now();
2751
+ const prevLeadStat = state.nodeStats[leadNode.id];
2752
+ const leadWaitMs = prevLeadStat && typeof prevLeadStat.startedAt === 'number'
2753
+ ? Math.max(0, resumeNow - prevLeadStat.startedAt)
2754
+ : 0;
2755
+ state.nodeStats[leadNode.id] = {
2756
+ id: leadNode.id,
2757
+ label: leadNode.label || leadNode.id,
2758
+ kind: 'lead',
2759
+ status: 'done',
2760
+ startedAt: (prevLeadStat && prevLeadStat.startedAt) || resumeNow,
2761
+ endedAt: resumeNow,
2762
+ durationMs: (prevLeadStat && typeof prevLeadStat.durationMs === 'number' ? prevLeadStat.durationMs : 0) + leadWaitMs,
2763
+ runs: prevLeadStat && typeof prevLeadStat.runs === 'number' ? prevLeadStat.runs : 1,
2764
+ model: '',
2765
+ fallbackUsed: false,
2766
+ sessionContinued: false,
2767
+ childId: '',
2768
+ reason: '',
2769
+ };
2344
2770
  state.waitingLead = null;
2345
2771
  delete state.loopFeedback[leadNode.id];
2346
2772
  state.results[leadNode.id] = leadResult;
2347
2773
  state.labels[leadNode.id] = leadNode.label;
2348
2774
  state.done.add(leadNode.id);
2349
2775
  leadResult = undefined;
2776
+ emitRunState('running', null);
2350
2777
  }
2351
2778
  } finally {
2352
2779
  if (parentSignal && typeof parentSignal.removeEventListener === 'function') {
@@ -2942,6 +3369,7 @@ export {
2942
3369
  sessionIdFromContext,
2943
3370
  buildActiveCanvasContext,
2944
3371
  isPermissionFailure,
3372
+ buildRunSummarySnapshot,
2945
3373
  abortSessionRun,
2946
3374
  runPlan,
2947
3375
  executePlan,