dsh-workflow-canvas 1.5.0 → 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
@@ -24,6 +24,8 @@ import { fileURLToPath } from 'node:url';
24
24
  const canvasBySession = new Map();
25
25
  /** In-flight run progress per Session id. */
26
26
  const runBySession = new Map();
27
+ /** Live AbortController & active child session ids per executing Session id. */
28
+ const activeRunBySession = new Map();
27
29
  /** Snapshot of the last completed/halted run per Session id (enables partial retry). */
28
30
  const lastRunBySession = new Map();
29
31
  /**
@@ -161,8 +163,8 @@ function orderNodes(plan) {
161
163
  }
162
164
  const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
163
165
  const out = [];
164
- while (queue.length) {
165
- const id = queue.shift();
166
+ for (let i = 0; i < queue.length; i += 1) {
167
+ const id = queue[i];
166
168
  out.push(byId.get(id));
167
169
  for (const next of adj.get(id)) {
168
170
  indeg.set(next, indeg.get(next) - 1);
@@ -455,6 +457,23 @@ function briefFor(plan, node, results, failedMap, prunedSet, loopCtx) {
455
457
  return text;
456
458
  }
457
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
+
458
477
  function textOf(result) {
459
478
  // A structured node's canonical value is its parsed object, not the prose.
460
479
  if (result && result.structured !== undefined) {
@@ -466,7 +485,10 @@ function textOf(result) {
466
485
  }
467
486
  const blocks = (result && result.output) || [];
468
487
  const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
469
- 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 + ']';
470
492
  }
471
493
 
472
494
  function failed(result) {
@@ -515,39 +537,42 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
515
537
  if (model) agentOptions.model = model;
516
538
  if (node.reasoning) agentOptions.reasoningEffort = node.reasoning;
517
539
  if (Object.keys(agentOptions).length) spec.agentOptions = agentOptions;
540
+ const allowSchema = !(route && route.noSchema);
518
541
  if (isCondition) {
519
542
  const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
520
543
  spec.agentPreset = 'minimal';
521
- spec.outputSchema = isDefaultBinary
522
- ? {
523
- type: 'object',
524
- properties: {
525
- pass: { type: 'boolean', description: 'true to follow the Yes/Pass branch, false to follow the No/Fail branch.' },
526
- reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
527
- },
528
- required: ['pass', 'reason'],
529
- additionalProperties: false,
530
- }
531
- : {
532
- type: 'object',
533
- properties: {
534
- branches: {
535
- type: 'array',
536
- items: { type: 'string', enum: branches.map((b) => b.id) },
537
- description: multiMatch
538
- ? 'All matching branch ids to execute in parallel (empty array if none match).'
539
- : '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.' },
540
551
  },
541
- reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
542
- },
543
- required: ['branches', 'reason'],
544
- additionalProperties: false,
545
- };
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
+ }
546
571
  } else {
547
572
  if (node.preset) spec.agentPreset = node.preset;
548
573
  const wantsStructured = Boolean(node.structured)
549
574
  || (plan.edges || []).some((e) => e.from === node.id && e.type === 'structured');
550
- if (wantsStructured) {
575
+ if (wantsStructured && allowSchema) {
551
576
  spec.outputSchema = {
552
577
  type: 'object',
553
578
  additionalProperties: true,
@@ -557,6 +582,10 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
557
582
  }
558
583
 
559
584
  const run = async (childId, overridePrompt) => {
585
+ // Guard before every activation so an interrupted run can never spawn fresh/fallback zombies.
586
+ if (signal && signal.aborted) {
587
+ return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '' };
588
+ }
560
589
  const baseSpec = overridePrompt
561
590
  ? { ...spec, prompt: [{ type: 'text', text: overridePrompt }] }
562
591
  : spec;
@@ -566,27 +595,32 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
566
595
  activation = await scope.subagents.startActivation(withChild);
567
596
  } catch (error) {
568
597
  const message = String((error && error.message) || error);
569
- return { ok: false, text: '启动失败:' + message, reason: 'activation-failed' };
598
+ return { ok: false, text: '启动失败:' + message, reason: 'activation-failed', errorDetail: message };
570
599
  }
571
600
  try {
572
601
  if (activation && activation.childId) {
573
- liveChild.set(childKey(node.id), activation.childId);
602
+ const cid = String(activation.childId);
603
+ liveChild.set(childKey(node.id), cid);
574
604
  // Only overwrite the persisted memory slot when Memory is ON, so a
575
605
  // temporary keepSession=false experiment never destroys saved memory.
576
- if (node.keepSession) childByNode.set(childKey(node.id), activation.childId);
606
+ if (node.keepSession) childByNode.set(childKey(node.id), cid);
607
+ const activeRec = sid ? activeRunBySession.get(String(sid)) : null;
608
+ if (activeRec && activeRec.childIds) activeRec.childIds.add(cid);
577
609
  }
578
610
  let result;
579
611
  try {
580
612
  result = await activation.result;
581
613
  } catch (error) {
582
614
  const message = String((error && error.message) || error);
583
- return { ok: false, text: '运行失败:' + message, reason: 'run-failed' };
615
+ return { ok: false, text: '运行失败:' + message, reason: 'run-failed', errorDetail: message };
584
616
  }
585
617
  const outText = textOf(result);
618
+ const errDetail = extractResultError(result);
586
619
  const outcome = {
587
620
  ok: !failed(result),
588
621
  text: outText,
589
622
  reason: result && result.stopReason,
623
+ errorDetail: errDetail,
590
624
  empty: isEmptyOutput(result),
591
625
  childId: activation && activation.childId ? String(activation.childId) : '',
592
626
  };
@@ -595,6 +629,10 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
595
629
  }
596
630
  return outcome;
597
631
  } finally {
632
+ if (activation && activation.childId && sid) {
633
+ const activeRec = activeRunBySession.get(String(sid));
634
+ if (activeRec && activeRec.childIds) activeRec.childIds.delete(String(activation.childId));
635
+ }
598
636
  try { await activation.dispose(); } catch (_e) { /* ignore */ }
599
637
  }
600
638
  };
@@ -603,9 +641,10 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
603
641
  // resume its warm child session with a concise incremental correction prompt.
604
642
  if (warmPrompt && loopCtx && loopCtx.warmChildId && !forcedChild) {
605
643
  const continued = await run(loopCtx.warmChildId, warmPrompt);
644
+ if (signal && signal.aborted) return continued;
606
645
  if (continued.ok) {
607
646
  liveChild.set(childKey(node.id), continued.childId || loopCtx.warmChildId);
608
- return continued;
647
+ return { ...continued, warmReused: true };
609
648
  }
610
649
  if (continued.reason !== 'activation-failed') {
611
650
  return continued;
@@ -617,6 +656,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
617
656
  // step inside that child session instead of starting a fresh one.
618
657
  if (forcedChild) {
619
658
  const continued = await run(forcedChild);
659
+ if (signal && signal.aborted) return continued;
620
660
  if (continued.ok) {
621
661
  liveChild.set(childKey(node.id), forcedChild);
622
662
  return continued;
@@ -637,6 +677,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
637
677
  const previous = pinned || saved || inProcess;
638
678
  if (previous) {
639
679
  const resumed = await run(previous);
680
+ if (signal && signal.aborted) return resumed;
640
681
  if (resumed.ok) return resumed;
641
682
  if (resumed.reason === 'activation-failed') {
642
683
  if (previous === inProcess) liveChild.delete(childKey(node.id));
@@ -654,7 +695,18 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
654
695
  return started;
655
696
  }
656
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
+
657
705
  async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet, loopCtx) {
706
+ const primaryModel = formatModelLabel(node.provider, node.model);
707
+ if (signal && signal.aborted) {
708
+ return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '', modelUsed: primaryModel, fallbackUsed: false, sessionContinued: false };
709
+ }
658
710
  const continueFrom = forwardEdgesOf(plan.edges || [])
659
711
  .filter((e) => e.to === node.id && e.type === 'session-ref' && !(prunedSet && prunedSet.has(e.from)))
660
712
  .map((e) => liveChild.get(String(sid || '') + '::' + e.from)
@@ -663,34 +715,111 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
663
715
 
664
716
  if (continueFrom) {
665
717
  const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet, loopCtx);
718
+ if (signal && signal.aborted) return continued;
666
719
  if (continued.ok) {
667
- 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
+ };
668
729
  if (continued.decision) out.decision = continued.decision;
669
730
  return out;
670
731
  }
671
732
  }
672
733
 
673
- 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);
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
+ }
674
751
  if (first.ok) {
675
- 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
+ };
676
761
  if (first.decision) out.decision = first.decision;
677
762
  return out;
678
763
  }
679
764
  if (!node.fallbackModel && !node.fallbackProvider) {
680
765
  const reason = first.reason || 'unknown';
681
- 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
+ };
682
780
  }
683
- 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, {
684
783
  provider: node.fallbackProvider,
685
784
  model: node.fallbackModel,
686
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
+ }
687
796
  if (retry.ok) {
688
- 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
+ };
689
806
  if (retry.decision) out.decision = retry.decision;
690
807
  return out;
691
808
  }
692
809
  const reason = retry.reason || 'unknown';
693
- 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
+ };
694
823
  }
695
824
 
696
825
  /** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
@@ -902,7 +1031,7 @@ function normalizeCanvas(args) {
902
1031
  provider: String(raw.provider || ''),
903
1032
  model: String(raw.model || ''),
904
1033
  reasoning: String(raw.reasoning || ''),
905
- preset: String(raw.preset || ''),
1034
+ preset: (id === 'lead' ? '' : (kind === 'condition' ? 'minimal' : String(raw.preset || ''))),
906
1035
  structured: Boolean(raw.structured),
907
1036
  keepSession: Boolean(raw.keepSession),
908
1037
  fallbackModel: String(raw.fallbackModel || ''),
@@ -1038,6 +1167,7 @@ function applyPatch(plan, args) {
1038
1167
  if (patch[key] !== undefined) existing[key] = patch[key];
1039
1168
  }
1040
1169
  if (patch.kind !== undefined) existing.kind = normalizeKind(patch.kind);
1170
+ if (existing.kind === 'condition') existing.preset = 'minimal';
1041
1171
  if (patch.branches !== undefined) {
1042
1172
  const nb = normalizeBranches(patch.branches);
1043
1173
  if (nb) existing.branches = nb;
@@ -1064,7 +1194,7 @@ function applyPatch(plan, args) {
1064
1194
  for (const key of ALLOWED) {
1065
1195
  if (patch[key] !== undefined) created[key] = patch[key];
1066
1196
  }
1067
- created.preset = created.preset === 'minimal' ? 'minimal' : 'standard';
1197
+ created.preset = (created.kind === 'condition' || created.preset === 'minimal') ? 'minimal' : 'standard';
1068
1198
  if (created.kind === 'condition' && patch.branches !== undefined) {
1069
1199
  const nb = normalizeBranches(patch.branches);
1070
1200
  if (nb) created.branches = nb;
@@ -1157,9 +1287,18 @@ function applyPatch(plan, args) {
1157
1287
  * resolves a session's root from its header cwd, so the client reads the same
1158
1288
  * relative path back through the Remote.
1159
1289
  */
1290
+ function resolveSessionsService(scope) {
1291
+ try {
1292
+ return (scope && scope.sessions) || (scope && typeof scope.get === 'function' ? scope.get('sessions') : null);
1293
+ } catch (_e) {
1294
+ return null;
1295
+ }
1296
+ }
1297
+
1160
1298
  function publishCanvas(scope, sessionId, canvas) {
1161
1299
  try {
1162
- const live = scope && scope.sessions && scope.sessions.get(sessionId);
1300
+ const sessionsSvc = resolveSessionsService(scope);
1301
+ const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
1163
1302
  const root = live && live.header && live.header.cwd;
1164
1303
  if (!root) return false;
1165
1304
  const dir = join(root, '.dsh', 'canvas');
@@ -1171,15 +1310,139 @@ function publishCanvas(scope, sessionId, canvas) {
1171
1310
  }
1172
1311
  }
1173
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
+
1174
1435
  /**
1175
1436
  * Publish live run-state telemetry (condition decisions, pruned nodes, blocked edges,
1176
- * waitingLead) to `.dsh/canvas/<sessionId>.run.json` so the sidebar canvas can
1177
- * 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.
1178
1440
  */
1179
1441
  function publishRunState(scope, sessionId, runState) {
1180
1442
  try {
1181
1443
  if (!sessionId) return false;
1182
- const live = scope && scope.sessions && scope.sessions.get(sessionId);
1444
+ const sessionsSvc = resolveSessionsService(scope);
1445
+ const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
1183
1446
  const root = live && live.header && live.header.cwd;
1184
1447
  if (!root) return false;
1185
1448
  const dir = join(root, '.dsh', 'canvas');
@@ -1194,9 +1457,138 @@ function publishRunState(scope, sessionId, runState) {
1194
1457
  }
1195
1458
  }
1196
1459
 
1460
+ /**
1461
+ * Force-stop any running or paused (waitingLead) workflow for `sessionId`.
1462
+ * Uses DSH 0.2.2 native APIs:
1463
+ * - `scope.subagents.interrupt(childId, { kind: 'user' })` for each live child
1464
+ * - `scope.subagents.drainDescendants([rootAgent])` to tear down the full subtree
1465
+ * - `rootAgent.cancel({ kind: 'user' }, { keepInbox: true })` when a turn is active
1466
+ * Also aborts our local `AbortController`, preserves partial progress in `lastRunBySession`,
1467
+ * clears `runBySession` (`waitingLead`), and writes `halted` / `idle` to `.run.json`.
1468
+ */
1469
+ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1470
+ const sid = sessionId !== undefined && sessionId !== null ? String(sessionId) : '';
1471
+ if (!sid) return { stopped: false, wasRunning: false, wasWaiting: false };
1472
+ const allowCancelRoot = !(opts && opts.cancelRootTurn === false);
1473
+
1474
+ const active = activeRunBySession.get(sid);
1475
+ const wasRunning = Boolean(active);
1476
+ const childIds = active && active.childIds ? Array.from(active.childIds) : [];
1477
+ if (active) {
1478
+ try { active.ctrl.abort('user-stop'); } catch (_e) { /* ignore */ }
1479
+ activeRunBySession.delete(sid);
1480
+ }
1481
+
1482
+ // Interrupt every tracked live child immediately via DSH's native subagents.interrupt API.
1483
+ let subagents = null;
1484
+ try {
1485
+ subagents = (scope && scope.subagents) || (scope && typeof scope.get === 'function' ? scope.get('subagents') : null);
1486
+ } catch (_e) { subagents = null; }
1487
+ if (subagents && typeof subagents.interrupt === 'function') {
1488
+ for (const cid of childIds) {
1489
+ try { subagents.interrupt(cid, { kind: 'user' }); } catch (_e) { /* best-effort */ }
1490
+ }
1491
+ }
1492
+
1493
+ // Resolve the exact root Agent (from command invocation or `scope.agents.get(sid)`)
1494
+ // to drain the entire descendant subagent tree and cancel any active root turn.
1495
+ let targetAgent = rootAgent || null;
1496
+ if (!targetAgent) {
1497
+ let agentsSvc = null;
1498
+ try {
1499
+ agentsSvc = (scope && scope.agents) || (scope && typeof scope.get === 'function' ? scope.get('agents') : null);
1500
+ } catch (_e) { agentsSvc = null; }
1501
+ if (agentsSvc && typeof agentsSvc.get === 'function') {
1502
+ try { targetAgent = agentsSvc.get(sid) || null; } catch (_e) { targetAgent = null; }
1503
+ }
1504
+ }
1505
+ if (targetAgent) {
1506
+ if (subagents && typeof subagents.drainDescendants === 'function') {
1507
+ try {
1508
+ // Fire-and-forget teardown so `/canvas-stop` returns immediately to the UI even if a remote provider stalls.
1509
+ Promise.resolve(subagents.drainDescendants([targetAgent])).catch(() => {});
1510
+ } catch (_e) { /* best-effort */ }
1511
+ }
1512
+ if (allowCancelRoot && (wasRunning || targetAgent.running) && typeof targetAgent.cancel === 'function') {
1513
+ try { targetAgent.cancel({ kind: 'user' }, { keepInbox: true }); } catch (_e) { /* best-effort */ }
1514
+ }
1515
+ }
1516
+
1517
+ const st = runBySession.get(sid);
1518
+ const wasWaiting = Boolean(st && st.waitingLead);
1519
+ if (st) {
1520
+ const haltNow = Date.now();
1521
+ st.endedAt = haltNow;
1522
+ st.haltedReason = wasWaiting ? '用户结束了等待拍板状态' : '用户主动终止';
1523
+ if (st.done && st.done.size > 0) {
1524
+ lastRunBySession.set(sid, {
1525
+ sig: st.sig,
1526
+ done: new Set(st.done),
1527
+ results: { ...(st.results || {}) },
1528
+ labels: { ...(st.labels || {}) },
1529
+ failed: { ...(st.failed || {}) },
1530
+ emptyOutputs: { ...(st.emptyOutputs || {}) },
1531
+ blockedEdges: new Set(st.blockedEdges || []),
1532
+ pruned: new Set(st.pruned || []),
1533
+ decisions: { ...(st.decisions || {}) },
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 }])) : {},
1536
+ halted: true,
1537
+ });
1538
+ }
1539
+ const summary = buildRunSummarySnapshot(st, {
1540
+ status: 'halted',
1541
+ waitingLead: null,
1542
+ haltedReason: st.haltedReason,
1543
+ now: haltNow,
1544
+ });
1545
+ runBySession.delete(sid);
1546
+ publishRunState(scope, sid, {
1547
+ status: 'halted',
1548
+ done: Array.from(st.done || []),
1549
+ decisions: { ...(st.decisions || {}) },
1550
+ pruned: Array.from(st.pruned || []),
1551
+ blockedEdges: Array.from(st.blockedEdges || []),
1552
+ loopCounts: {},
1553
+ nodeAttempts: { ...(st.nodeAttempts || {}) },
1554
+ waitingLead: null,
1555
+ summary,
1556
+ });
1557
+ saveStore();
1558
+ } else {
1559
+ // Even if in-memory state was already gone (e.g. after restart), overwrite any stale `.run.json`
1560
+ // so a leftover `need-lead` file can never trap the sidebar UI.
1561
+ publishRunState(scope, sid, {
1562
+ status: wasRunning ? 'halted' : 'idle',
1563
+ done: [],
1564
+ decisions: {},
1565
+ pruned: [],
1566
+ blockedEdges: [],
1567
+ loopCounts: {},
1568
+ nodeAttempts: {},
1569
+ waitingLead: null,
1570
+ summary: null,
1571
+ });
1572
+ }
1573
+ return { stopped: true, wasRunning, wasWaiting };
1574
+ }
1575
+
1197
1576
  async function runPlan(scope, args, exec) {
1198
1577
  const agent = exec && exec.agent;
1199
1578
  const sid = agent && agent.id !== undefined ? String(agent.id) : '';
1579
+ if (args && args.cancel === true) {
1580
+ // Pass `cancelRootTurn: false` because this tool call runs inside the model's current turn;
1581
+ // cancelling the root turn here would cut off the model's own cancellation confirmation reply.
1582
+ const res = abortSessionRun(scope, sid, agent, { cancelRootTurn: false });
1583
+ return {
1584
+ status: 'cancelled',
1585
+ wasRunning: res.wasRunning,
1586
+ wasWaiting: res.wasWaiting,
1587
+ hint: res.wasWaiting
1588
+ ? '已终止暂停中的工作流并解除等待拍板状态。'
1589
+ : '已终止当前工作流执行。',
1590
+ };
1591
+ }
1200
1592
  const payload = sid ? canvasBySession.get(sid) : undefined;
1201
1593
  if (!payload) return { error: '当前会话还没有画布数据。请在右侧 Workflow 画布点「启用」。' };
1202
1594
  if (!payload.enabled) return { error: '画布当前是「已禁用」状态。请在画布上点「启用」后再运行。' };
@@ -1227,7 +1619,7 @@ function inspectPlan(sid) {
1227
1619
  provider: String(n.provider || ''),
1228
1620
  model: String(n.model || ''),
1229
1621
  reasoning: String(n.reasoning || ''),
1230
- preset: n.preset === 'minimal' ? 'minimal' : 'standard',
1622
+ preset: (normalizeKind(n.kind) === 'condition' || n.preset === 'minimal') ? 'minimal' : 'standard',
1231
1623
  keepSession: Boolean(n.keepSession),
1232
1624
  structured: Boolean(n.structured),
1233
1625
  fallbackModel: String(n.fallbackModel || ''),
@@ -1297,12 +1689,16 @@ function buildActiveCanvasContext(sid) {
1297
1689
  const runState = runBySession.get(String(sid));
1298
1690
  if (runState && runState.waitingLead) {
1299
1691
  const wl = runState.waitingLead;
1692
+ const loopHint = wl.loopFeedback
1693
+ ? ('(↺ 第 ' + wl.loopFeedback.retry + '/' + wl.loopFeedback.max + ' 次回环修正,打回理由:' + (wl.loopFeedback.reason || '未达预期') + ')')
1694
+ : '';
1300
1695
  return [
1301
1696
  '[Workflow Canvas Active — Paused at Lead Step]',
1302
- '当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')。',
1697
+ '当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')' + loopHint + '。',
1303
1698
  '- 若用户的当前消息是在拍板、确认、补充决策或要求继续:请整理决策结论并直接调用 `canvas_workflow({ leadResult: "..." })` 恢复下游节点运行。',
1699
+ '- 若用户要求取消、结束或终止当前工作流:直接调用 `canvas_workflow({ cancel: true })` 解除暂停状态。',
1304
1700
  '- 若用户要求放弃当前进度从头重跑:调用 `canvas_workflow({ reset: true })`。',
1305
- '- 若用户要求修改画布结构/分工:先 `canvas_inspect` 再用 `canvas_patch`。',
1701
+ '- 若用户要求修改画布结构、分工、参考清单、分支或回环:先 `canvas_inspect` 再用 `canvas_patch`。',
1306
1702
  ].join('\n');
1307
1703
  }
1308
1704
 
@@ -1311,21 +1707,29 @@ function buildActiveCanvasContext(sid) {
1311
1707
  .map((n) => (n.kind === 'lead' ? '〔Lead〕' : (n.kind === 'condition' ? '〔条件〕' : '')) + (n.label || n.id))
1312
1708
  .join(' → ') + (nodes.length > 8 ? ' …' : '');
1313
1709
  const hasTask = Boolean(String((plan && plan.task) || '').trim());
1710
+ const loopCount = (plan && Array.isArray(plan.edges)) ? plan.edges.filter((e) => isLoopEdge(e)).length : 0;
1711
+ const globalRefs = normalizeRefs(plan && plan.refs) || [];
1314
1712
  const prefix = String(sid) + '::';
1315
1713
  const hasMemory = nodes.some((n) => n.keepSession && (liveChild.has(prefix + n.id) || childByNode.has(prefix + n.id)));
1714
+ const metaParts = [
1715
+ '共 ' + nodes.length + ' 个执行节点:' + preview,
1716
+ '入口总任务:' + (hasTask ? '已填写' : '未填写'),
1717
+ ];
1718
+ if (loopCount > 0) metaParts.push('含 ' + loopCount + ' 条受控回环(引擎自动按条件带反馈重试并在超限时熔断交 Lead,无需你手动循环调用)');
1719
+ if (globalRefs.length > 0) metaParts.push('全局参考 ×' + globalRefs.length);
1316
1720
  const lines = [
1317
1721
  '[Workflow Canvas Active]',
1318
- '当前会话的右侧工作流画布处于「● 已启用」状态(共 ' + nodes.length + ' 个执行节点:' + preview + ';入口总任务:' + (hasTask ? '已填写' : '未填写') + ')。',
1722
+ '当前会话的右侧工作流画布处于「● 已启用」状态(' + metaParts.join(';') + ')。',
1319
1723
  '- 若用户发出任务请求、布置工作或说「开始 / 执行 / 跑一次」:请直接调用 `canvas_workflow` 按画布编排执行('
1320
1724
  + (hasTask ? '可直接沿用入口总任务;若用户给出了新任务则通过 task 参数传入' : '请将用户的任务内容作为 task 参数传入')
1321
1725
  + '),不要绕过画布直接自己完成。',
1322
- '- 若用户在讨论或要求修改画布结构、模型、分工或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
1726
+ '- 若用户在讨论或要求修改画布结构、模型、分工、参考清单、条件分支、回环或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
1323
1727
  '- 仅当用户明确只是闲聊、问无关问题或要求先停用画布时,才无需调用 `canvas_workflow`。',
1324
1728
  ];
1325
1729
  if (hasMemory) {
1326
1730
  lines.push('- 本会话已有开启「记忆」节点的历史子代理会话:若用户说「再跑一次 / 换个任务重跑」,请先简短询问用户是保留上次记忆继续(reset: true)还是清空记忆全新开跑(reset: true, clearMemory: true)。');
1327
1731
  }
1328
- const stdCount = nodes.filter((n) => n.kind !== 'lead' && n.preset !== 'minimal').length;
1732
+ const stdCount = nodes.filter((n) => n.kind !== 'lead' && n.kind !== 'condition' && n.preset !== 'minimal').length;
1329
1733
  if (stdCount >= 2) {
1330
1734
  lines.push('- 本画布包含 ' + stdCount + ' 个可写/命令型(standard)子代理,受主对话权限上限约束;若任务涉及改代码、写文件或跑终端命令且当前主对话权限偏严格,请先简短提醒用户放开主对话权限再调 `canvas_workflow`,避免中途报错白耗额度。');
1331
1735
  }
@@ -1358,6 +1762,17 @@ async function executePlan(scope, plan, args, exec) {
1358
1762
  const opts = args || {};
1359
1763
  const agent = exec && exec.agent;
1360
1764
  const sid = agent && agent.id !== undefined ? String(agent.id) : '';
1765
+ if (opts.cancel === true) {
1766
+ const res = abortSessionRun(scope, sid, agent, { cancelRootTurn: false });
1767
+ return {
1768
+ status: 'cancelled',
1769
+ wasRunning: res.wasRunning,
1770
+ wasWaiting: res.wasWaiting,
1771
+ hint: res.wasWaiting
1772
+ ? '已终止暂停中的工作流并解除等待拍板状态。'
1773
+ : '已终止当前工作流执行。',
1774
+ };
1775
+ }
1361
1776
  if (!plan || !Array.isArray(plan.nodes) || !plan.nodes.length) {
1362
1777
  return { error: '画布没有可执行的节点。' };
1363
1778
  }
@@ -1402,16 +1817,40 @@ async function executePlan(scope, plan, args, exec) {
1402
1817
 
1403
1818
  const byId = new Map(runnable.map((n) => [n.id, n]));
1404
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;
1405
1838
  const sig = JSON.stringify(plan);
1406
1839
  let state = runBySession.get(sid);
1407
1840
  const wantRetryFailed = opts.retryFailed === true;
1408
1841
  const rawFromNodes = Array.isArray(opts.fromNodes) ? opts.fromNodes.filter((x) => typeof x === 'string' && x.trim()) : [];
1409
1842
  const wantPartial = wantRetryFailed || rawFromNodes.length > 0;
1410
1843
  let reused = [];
1844
+ let reusedIds = [];
1411
1845
 
1412
1846
  if (wantPartial && sid) {
1413
1847
  const base = state || lastRunBySession.get(sid);
1414
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
+ }
1415
1854
  state = {
1416
1855
  sig,
1417
1856
  done: new Set(Array.from(base.done || []).filter((id) => byId.has(id))),
@@ -1431,6 +1870,15 @@ async function executePlan(scope, plan, args, exec) {
1431
1870
  loopWarmChild: {},
1432
1871
  loopExhausted: [],
1433
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: [],
1434
1882
  };
1435
1883
  // Build forward adjacency to invalidate seed nodes and all their downstream dependents.
1436
1884
  const fwd = new Map();
@@ -1467,12 +1915,35 @@ async function executePlan(scope, plan, args, exec) {
1467
1915
  delete state.failed[id];
1468
1916
  delete state.emptyOutputs[id];
1469
1917
  delete state.decisions[id];
1918
+ delete state.nodeStats[id];
1470
1919
  }
1471
1920
  for (const e of plan.edges || []) {
1472
1921
  if (e && invalid.has(e.from)) state.blockedEdges.delete(edgeKey(e));
1473
1922
  }
1474
1923
  state.fallbackLinks = state.fallbackLinks.filter((fl) => !invalid.has(fl.from) && !invalid.has(fl.to));
1475
- 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);
1476
1947
  runBySession.set(sid, state);
1477
1948
  }
1478
1949
  }
@@ -1497,6 +1968,15 @@ async function executePlan(scope, plan, args, exec) {
1497
1968
  loopWarmChild: {},
1498
1969
  loopExhausted: [],
1499
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: [],
1500
1980
  };
1501
1981
  runBySession.set(sid, state);
1502
1982
  }
@@ -1512,8 +1992,14 @@ async function executePlan(scope, plan, args, exec) {
1512
1992
  if (!state.nodeAttempts) state.nodeAttempts = {};
1513
1993
  if (!state.loopWarmChild) state.loopWarmChild = {};
1514
1994
  if (!state.loopExhausted) state.loopExhausted = [];
1515
-
1516
- 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) => {
1517
2003
  if (!sid) return;
1518
2004
  const loopCounts = {};
1519
2005
  for (const e of plan.edges || []) {
@@ -1523,6 +2009,11 @@ async function executePlan(scope, plan, args, exec) {
1523
2009
  loopCounts[k] = entry;
1524
2010
  if (e.id) loopCounts[e.id] = entry;
1525
2011
  }
2012
+ const summary = buildRunSummarySnapshot(state, {
2013
+ status,
2014
+ waitingLead,
2015
+ haltedReason: reasonOverride || state.haltedReason || '',
2016
+ });
1526
2017
  publishRunState(scope, sid, {
1527
2018
  status,
1528
2019
  done: Array.from(state.done || []),
@@ -1532,6 +2023,7 @@ async function executePlan(scope, plan, args, exec) {
1532
2023
  loopCounts,
1533
2024
  nodeAttempts: { ...state.nodeAttempts },
1534
2025
  waitingLead: waitingLead ? { id: waitingLead.id, label: waitingLead.label } : null,
2026
+ summary,
1535
2027
  });
1536
2028
  };
1537
2029
  emitRunState('running', null);
@@ -1549,6 +2041,7 @@ async function executePlan(scope, plan, args, exec) {
1549
2041
  pruned: new Set(state.pruned),
1550
2042
  decisions: { ...state.decisions },
1551
2043
  fallbackLinks: state.fallbackLinks.map((fl) => ({ ...fl })),
2044
+ nodeStats: Object.fromEntries(Object.entries(state.nodeStats || {}).map(([k, v]) => [k, { ...v }])),
1552
2045
  halted: Boolean(haltedFlag),
1553
2046
  });
1554
2047
  };
@@ -1692,15 +2185,62 @@ async function executePlan(scope, plan, args, exec) {
1692
2185
  };
1693
2186
 
1694
2187
  let leadResult = typeof opts.leadResult === 'string' ? opts.leadResult : undefined;
1695
- const rawMaxParallel = opts.maxParallel !== undefined ? opts.maxParallel : plan.maxParallel;
1696
- const MAX_PARALLEL = Number.isFinite(Number(rawMaxParallel))
1697
- ? Math.max(1, Math.min(8, Math.floor(Number(rawMaxParallel))))
1698
- : 4;
1699
2188
  // Event-driven concurrency pool: as soon as any node finishes, newly unblocked
1700
2189
  // downstream agents start immediately instead of waiting for slower siblings.
1701
2190
  const inFlight = new Map();
1702
2191
 
1703
- const isAborted = () => Boolean(exec && exec.signal && exec.signal.aborted);
2192
+ const runCtrl = new AbortController();
2193
+ const runSignal = runCtrl.signal;
2194
+ const activeRec = { ctrl: runCtrl, childIds: new Set() };
2195
+ const parentSignal = exec && exec.signal;
2196
+ const onParentAbort = () => {
2197
+ try { runCtrl.abort('parent-abort'); } catch (_e) { /* ignore */ }
2198
+ // Also interrupt every already-running child via DSH's native subagents.interrupt API,
2199
+ // since startActivation({ signal }) only aborts startup, not post-start execution.
2200
+ try {
2201
+ const subagents = (scope && scope.subagents) || (scope && typeof scope.get === 'function' ? scope.get('subagents') : null);
2202
+ if (subagents && typeof subagents.interrupt === 'function') {
2203
+ for (const cid of activeRec.childIds) {
2204
+ try { subagents.interrupt(cid, { kind: 'user' }); } catch (_e) { /* best-effort */ }
2205
+ }
2206
+ }
2207
+ } catch (_e) { /* best-effort */ }
2208
+ };
2209
+ if (parentSignal) {
2210
+ if (parentSignal.aborted) onParentAbort();
2211
+ else if (typeof parentSignal.addEventListener === 'function') {
2212
+ parentSignal.addEventListener('abort', onParentAbort, { once: true });
2213
+ }
2214
+ }
2215
+ if (sid) activeRunBySession.set(sid, activeRec);
2216
+
2217
+ const isAborted = () => Boolean(runSignal.aborted || (parentSignal && parentSignal.aborted));
2218
+ // Raced alongside `inFlight` so user cancellation unblocks immediately even if a child activation hangs.
2219
+ const abortPromise = new Promise((resolve) => {
2220
+ if (isAborted()) { resolve({ __aborted: true }); return; }
2221
+ runSignal.addEventListener('abort', () => resolve({ __aborted: true }), { once: true });
2222
+ });
2223
+ const finishAborted = () => {
2224
+ state.endedAt = Date.now();
2225
+ state.haltedReason = '工作流执行已取消';
2226
+ snapshotLastRun(true);
2227
+ emitRunState('halted', null, state.haltedReason);
2228
+ if (sid) runBySession.delete(sid);
2229
+ saveStore();
2230
+ return {
2231
+ status: 'halted',
2232
+ error: '工作流执行已取消。',
2233
+ results: state.results,
2234
+ labels: state.labels,
2235
+ failed: Object.values(state.failed),
2236
+ emptyOutputs: Object.values(state.emptyOutputs),
2237
+ decisions: Object.values(state.decisions),
2238
+ branchSkipped: branchSkippedList(),
2239
+ ...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
2240
+ reused,
2241
+ skipped,
2242
+ };
2243
+ };
1704
2244
  const permBlocked = [];
1705
2245
  let activationFailCount = 0;
1706
2246
  let haltedReason = '';
@@ -1711,33 +2251,54 @@ async function executePlan(scope, plan, args, exec) {
1711
2251
  && !state.done.has(n.id)
1712
2252
  && !inFlight.has(n.id)
1713
2253
  && depsOf(n).every((id) => state.done.has(id)));
2254
+ let launched = 0;
1714
2255
  for (const node of candidates) {
1715
2256
  if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) break;
1716
2257
  const fb = state.loopFeedback[node.id] || null;
1717
2258
  const warmChildId = (fb && state.loopWarmChild[node.id]) ? state.loopWarmChild[node.id] : '';
1718
2259
  const loopCtx = fb ? { feedback: fb, warmChildId } : undefined;
1719
2260
  if (fb) delete state.loopFeedback[node.id];
1720
- const promise = spawnNode(scope, plan, node, state.results, agent, exec.signal, sid, state.failed, state.pruned, loopCtx)
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
+ };
2278
+ const promise = spawnNode(scope, plan, node, state.results, agent, runSignal, sid, state.failed, state.pruned, loopCtx)
1721
2279
  .then(
1722
- (outcome) => ({ node, outcome }),
1723
- (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) } }),
1724
2282
  );
1725
2283
  inFlight.set(node.id, promise);
2284
+ launched += 1;
1726
2285
  }
2286
+ if (launched > 0) emitRunState('running', null);
1727
2287
  };
1728
2288
 
2289
+ try {
1729
2290
  for (;;) {
1730
2291
  if (isAborted()) {
1731
- emitRunState('halted', null);
1732
- if (sid) runBySession.delete(sid);
1733
- return { error: '工作流执行已取消。' };
2292
+ return finishAborted();
1734
2293
  }
1735
2294
  // On circuit-break halt, stop launching new downstream waves immediately,
1736
2295
  // but let already in-flight siblings settle so no orphan promises or partial
1737
2296
  // results are dropped before returning the halted report.
1738
2297
  if (haltedReason && inFlight.size === 0) {
2298
+ state.endedAt = Date.now();
2299
+ state.haltedReason = haltedReason;
1739
2300
  snapshotLastRun(true);
1740
- emitRunState('halted', null);
2301
+ emitRunState('halted', null, haltedReason);
1741
2302
  if (sid) runBySession.delete(sid);
1742
2303
  saveStore();
1743
2304
  return {
@@ -1756,6 +2317,7 @@ async function executePlan(scope, plan, args, exec) {
1756
2317
  }
1757
2318
  const remaining = runnable.filter((n) => !state.done.has(n.id));
1758
2319
  if (!remaining.length) {
2320
+ state.endedAt = Date.now();
1759
2321
  snapshotLastRun(false);
1760
2322
  emitRunState('done', null);
1761
2323
  runBySession.delete(sid);
@@ -1777,13 +2339,36 @@ async function executePlan(scope, plan, args, exec) {
1777
2339
  launchReadyAgents();
1778
2340
 
1779
2341
  if (inFlight.size > 0) {
1780
- const { node, outcome } = await Promise.race(inFlight.values());
1781
- inFlight.delete(node.id);
1782
- if (isAborted()) {
1783
- emitRunState('halted', null);
1784
- if (sid) runBySession.delete(sid);
1785
- return { error: '工作流执行已取消。' };
2342
+ const raceHit = await Promise.race([...inFlight.values(), abortPromise]);
2343
+ if ((raceHit && raceHit.__aborted) || isAborted()) {
2344
+ return finishAborted();
1786
2345
  }
2346
+ const { node, outcome, startedAt } = raceHit;
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
+ };
1787
2372
  state.labels[node.id] = node.label;
1788
2373
  if (node.kind === 'condition') {
1789
2374
  const { branches, isDefaultBinary } = conditionBranches(node);
@@ -1897,10 +2482,37 @@ async function executePlan(scope, plan, args, exec) {
1897
2482
  delete state.emptyOutputs[mid];
1898
2483
  delete state.decisions[mid];
1899
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
+ }
1900
2489
  }
1901
2490
  for (const e of plan.edges || []) {
1902
2491
  if (e && members.has(e.from)) state.blockedEdges.delete(edgeKey(e));
1903
2492
  }
2493
+ // Un-prune previously pruned downstream nodes reachable from loop members so
2494
+ // an inner condition picking a different branch on a retry round can still run them.
2495
+ if (state.pruned.size > 0) {
2496
+ const fwdAdj = new Map();
2497
+ for (const e of forwardEdgesOf(plan.edges || [])) {
2498
+ if (!e || !e.from || !e.to) continue;
2499
+ if (!fwdAdj.has(e.from)) fwdAdj.set(e.from, []);
2500
+ fwdAdj.get(e.from).push(e.to);
2501
+ }
2502
+ const reach = new Set(members);
2503
+ const rq = Array.from(members);
2504
+ for (let i = 0; i < rq.length; i += 1) {
2505
+ for (const nx of fwdAdj.get(rq[i]) || []) {
2506
+ if (!reach.has(nx)) { reach.add(nx); rq.push(nx); }
2507
+ }
2508
+ }
2509
+ for (const rid of reach) {
2510
+ if (!members.has(rid) && state.pruned.has(rid)) {
2511
+ state.pruned.delete(rid);
2512
+ state.done.delete(rid);
2513
+ }
2514
+ }
2515
+ }
1904
2516
  state.fallbackLinks = state.fallbackLinks.filter((fl) => !members.has(fl.from) && !members.has(fl.to));
1905
2517
  state.loopFeedback[le.to] = {
1906
2518
  retry: nextRetry,
@@ -1994,6 +2606,7 @@ async function executePlan(scope, plan, args, exec) {
1994
2606
  haltedReason = '连续 ' + activationFailCount + ' 个子代理启动失败,已熔断停止后续节点以防继续消耗额度。请检查模型配置或主对话权限后重试。';
1995
2607
  }
1996
2608
  state.done.add(node.id);
2609
+ emitRunState('running', null);
1997
2610
  continue;
1998
2611
  }
1999
2612
 
@@ -2035,10 +2648,29 @@ async function executePlan(scope, plan, args, exec) {
2035
2648
  fallbackParts.push('⚠ 条件节点(' + unmatchedConds.join('、') + ')所有分支均未命中,已跳过中间分支直接转交给你处理。');
2036
2649
  }
2037
2650
  const fallbackNotice = fallbackParts.join(' ');
2651
+ const mergedLeadRefs = normalizeRefs((normalizeRefs(plan && plan.refs) || []).concat(normalizeRefs(leadNode.refs) || []));
2038
2652
  const hasDownstreamWork = remaining.some((n) => n.id !== leadNode.id);
2039
2653
  if (!hasDownstreamWork && leadResult === undefined) {
2040
2654
  // Terminal Lead: zero downstream nodes remain, so complete the run directly
2041
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;
2042
2674
  state.done.add(leadNode.id);
2043
2675
  snapshotLastRun(false);
2044
2676
  emitRunState('done', null);
@@ -2050,7 +2682,7 @@ async function executePlan(scope, plan, args, exec) {
2050
2682
  label: leadNode.label,
2051
2683
  role: leadNode.role || leadNode.label,
2052
2684
  needs: depsOf(leadNode).map((id) => byId.get(id).label),
2053
- ...(normalizeRefs(leadNode.refs) ? { refs: normalizeRefs(leadNode.refs) } : {}),
2685
+ ...(mergedLeadRefs ? { refs: mergedLeadRefs } : {}),
2054
2686
  },
2055
2687
  results: state.results,
2056
2688
  labels: state.labels,
@@ -2067,10 +2699,31 @@ async function executePlan(scope, plan, args, exec) {
2067
2699
  };
2068
2700
  }
2069
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
+ };
2719
+ const leadFbSummary = leadFb
2720
+ ? { retry: leadFb.retry, max: leadFb.max, sourceLabel: leadFb.sourceLabel, reason: leadFb.reason }
2721
+ : null;
2070
2722
  state.waitingLead = {
2071
2723
  id: leadNode.id,
2072
2724
  label: leadNode.label,
2073
2725
  role: leadNode.role || leadNode.label,
2726
+ ...(leadFbSummary ? { loopFeedback: leadFbSummary } : {}),
2074
2727
  };
2075
2728
  emitRunState('need-lead', state.waitingLead);
2076
2729
  return {
@@ -2079,8 +2732,8 @@ async function executePlan(scope, plan, args, exec) {
2079
2732
  label: leadNode.label,
2080
2733
  role: leadNode.role || leadNode.label,
2081
2734
  needs: depsOf(leadNode).map((id) => byId.get(id).label),
2082
- ...(normalizeRefs(leadNode.refs) ? { refs: normalizeRefs(leadNode.refs) } : {}),
2083
- ...(leadFb ? { loopFeedback: { retry: leadFb.retry, max: leadFb.max, sourceLabel: leadFb.sourceLabel, reason: leadFb.reason } } : {}),
2735
+ ...(mergedLeadRefs ? { refs: mergedLeadRefs } : {}),
2736
+ ...(leadFbSummary ? { loopFeedback: leadFbSummary } : {}),
2084
2737
  },
2085
2738
  results: state.results,
2086
2739
  labels: state.labels,
@@ -2091,21 +2744,50 @@ async function executePlan(scope, plan, args, exec) {
2091
2744
  ...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
2092
2745
  sessions: leadSessions,
2093
2746
  hint: (fallbackNotice ? fallbackNotice + ' ' : '')
2094
- + '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需从头重跑可传 reset: true。',
2747
+ + '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需取消本次流程可传 cancel: true,若需从头重跑可传 reset: true。',
2095
2748
  };
2096
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
+ };
2097
2770
  state.waitingLead = null;
2098
2771
  delete state.loopFeedback[leadNode.id];
2099
2772
  state.results[leadNode.id] = leadResult;
2100
2773
  state.labels[leadNode.id] = leadNode.label;
2101
2774
  state.done.add(leadNode.id);
2102
2775
  leadResult = undefined;
2776
+ emitRunState('running', null);
2777
+ }
2778
+ } finally {
2779
+ if (parentSignal && typeof parentSignal.removeEventListener === 'function') {
2780
+ try { parentSignal.removeEventListener('abort', onParentAbort); } catch (_e) { /* ignore */ }
2781
+ }
2782
+ if (sid && activeRunBySession.get(sid) === activeRec) {
2783
+ activeRunBySession.delete(sid);
2784
+ }
2103
2785
  }
2104
2786
  }
2105
2787
 
2106
2788
  /** Agent-facing guide, shipped as a skill so any agent can load it on demand. */
2107
2789
  const SKILL_NAME = 'workflow-canvas';
2108
- const SKILL_DESCRIPTION = 'Workflow canvas (画布 / 工作流 / 编排): inspect, draw, edit or run a node graph of DSH subagents — add or re-role nodes, wire typed links, run in parallel waves, handle Lead steps, presets and memory. Load before using canvas_inspect, canvas_generate, canvas_patch or canvas_workflow.';
2790
+ const SKILL_DESCRIPTION = 'Workflow canvas (画布 / 工作流 / 编排 / 条件分支 / 回环重试): inspect, draw, edit, run or cancel a node graph of DSH subagents, condition judges, Lead gates, controlled retry loops, reference lists, presets and memory. Load before using canvas_inspect, canvas_generate, canvas_patch or canvas_workflow.';
2109
2791
  function skillPath() {
2110
2792
  try {
2111
2793
  return fileURLToPath(new URL('./skills/workflow-canvas/SKILL.md', import.meta.url));
@@ -2194,6 +2876,21 @@ export function apply(ctx) {
2194
2876
  }
2195
2877
  },
2196
2878
  }), 'workflow-canvas: sync command');
2879
+ scope.effect(() => scope.commands.register({
2880
+ name: 'canvas-stop',
2881
+ description: 'Stop any running or paused workflow canvas execution for this session.',
2882
+ recordInput: false,
2883
+ handler: ({ agent }) => {
2884
+ try {
2885
+ const id = agent && agent.id !== undefined ? String(agent.id) : '';
2886
+ if (!id) return { kind: 'error', text: 'no session' };
2887
+ abortSessionRun(ctx, id, agent);
2888
+ return { kind: 'success', text: 'workflow stopped' };
2889
+ } catch (error) {
2890
+ return { kind: 'error', text: String((error && error.message) || error) };
2891
+ }
2892
+ },
2893
+ }), 'workflow-canvas: stop command');
2197
2894
  } catch (_e) {
2198
2895
  /* command registry unavailable */
2199
2896
  }
@@ -2447,6 +3144,9 @@ export function apply(ctx) {
2447
3144
  '画布状态:' + (v.enabled ? '● 已启用' : '○ 已禁用') + (v.paused ? '(当前暂停在 Lead 步骤)' : ''),
2448
3145
  '总任务:' + (v.task || '(未填写,运行时可通过 task 参数指定)'),
2449
3146
  ];
3147
+ if (Array.isArray(v.refs) && v.refs.length) {
3148
+ head.push('全局参考:' + v.refs.join(';'));
3149
+ }
2450
3150
  if (v.error) head.push('校验错误:' + v.error);
2451
3151
  const warnBlock = Array.isArray(v.warnings) && v.warnings.length
2452
3152
  ? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
@@ -2471,7 +3171,9 @@ export function apply(ctx) {
2471
3171
  + (n.role ? ':' + n.role : '');
2472
3172
  });
2473
3173
  const edgeLines = (v.edges || []).map((e) => '- ' + e.from
2474
- + ' --(' + e.type + (e.branch ? ':' + e.branch : '') + ')--> ' + e.to);
3174
+ + ' --(' + e.type + (e.branch ? ':' + e.branch : '')
3175
+ + (e.loop ? ', ↺ loop ×' + normalizeMaxIterations(e.maxIterations) : '')
3176
+ + ')--> ' + e.to);
2475
3177
  return [{
2476
3178
  type: 'text',
2477
3179
  text: head.join('\n')
@@ -2492,16 +3194,17 @@ export function apply(ctx) {
2492
3194
  }
2493
3195
  });
2494
3196
 
2495
- ctx.inject(['tools', 'subagents'], (scope) => {
3197
+ ctx.inject(['tools', 'subagents', 'sessions'], (scope) => {
2496
3198
  try {
2497
3199
  scope.effect(() => scope.tools.register({
2498
3200
  name: 'canvas_workflow',
2499
- description: 'Run the workflow canvas of the current session. Executes subagent nodes in parallel waves; when a Lead node is reached it returns status "need-lead" and expects a follow-up call carrying leadResult. Supports optional `task` to override the entry Lead task and `reset: true` to restart from scratch. Load the `workflow-canvas` skill first when unsure.',
3201
+ description: 'Run, resume, or cancel the workflow canvas of the current session. Executes subagent and condition nodes in parallel waves with automatic branch pruning and controlled retry loops; pauses with status "need-lead" at intermediate Lead nodes (resume via leadResult, or abort via cancel: true). Also supports task override, reset, retryFailed, fromNodes, clearMemory, and maxParallel (1–8). Load the `workflow-canvas` skill first when unsure.',
2500
3202
  parameters: {
2501
3203
  type: 'object',
2502
3204
  properties: {
2503
3205
  leadResult: { type: 'string', description: 'Your own output for the Lead step that was just requested.' },
2504
3206
  task: { type: 'string', description: 'Optional overall task overriding the entry Lead task for this run (useful for reusing a preset).' },
3207
+ cancel: { type: 'boolean', description: 'Stop and cancel any active or paused (waitingLead) workflow run cleanly.' },
2505
3208
  reset: { type: 'boolean', description: 'Discard any paused run progress and start from the beginning.' },
2506
3209
  retryFailed: { type: 'boolean', description: 'Reuse succeeded nodes from the previous run and re-run only failed, empty, or unfinished nodes along with their downstream.' },
2507
3210
  fromNodes: { type: 'array', items: { type: 'string' }, description: 'Re-run only the specified node ids (or labels) and their downstream, reusing all other succeeded nodes from the previous run.' },
@@ -2534,6 +3237,7 @@ export function apply(ctx) {
2534
3237
  render: (_args, value) => {
2535
3238
  const v = value || {};
2536
3239
  if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
3240
+ if (v.status === 'cancelled') return [{ type: 'text', text: v.hint || '已终止当前工作流执行。' }];
2537
3241
  const results = v.results || {};
2538
3242
  const labels = v.labels || {};
2539
3243
  const blocks = Object.keys(results).map((id) => {
@@ -2573,6 +3277,9 @@ export function apply(ctx) {
2573
3277
  : '';
2574
3278
  if (v.status === 'need-lead') {
2575
3279
  const n = v.node || {};
3280
+ const refsBlock = Array.isArray(n.refs) && n.refs.length
3281
+ ? '\n参考资料 / 约束:\n' + n.refs.map((r) => '- ' + r).join('\n')
3282
+ : '';
2576
3283
  const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
2577
3284
  const handover = handed.length
2578
3285
  ? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
@@ -2582,6 +3289,7 @@ export function apply(ctx) {
2582
3289
  type: 'text',
2583
3290
  text: '需要你(Lead)完成「' + n.label + '」:' + n.role
2584
3291
  + '\n需要用到:' + ((n.needs && n.needs.length) ? n.needs.join('、') : '(无上游)')
3292
+ + refsBlock
2585
3293
  + decisionList
2586
3294
  + failedList
2587
3295
  + emptyList
@@ -2601,6 +3309,9 @@ export function apply(ctx) {
2601
3309
  : '';
2602
3310
  if (v.finalLead) {
2603
3311
  const fl = v.finalLead;
3312
+ const refsBlock = Array.isArray(fl.refs) && fl.refs.length
3313
+ ? '\n参考资料 / 约束:\n' + fl.refs.map((r) => '- ' + r).join('\n')
3314
+ : '';
2604
3315
  const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
2605
3316
  const handover = handed.length
2606
3317
  ? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
@@ -2610,6 +3321,7 @@ export function apply(ctx) {
2610
3321
  type: 'text',
2611
3322
  text: '所有子代理已完成,现在进入终审 Lead 步骤「' + fl.label + '」:' + fl.role
2612
3323
  + '\n需要用到:' + ((fl.needs && fl.needs.length) ? fl.needs.join('、') : '(无上游)')
3324
+ + refsBlock
2613
3325
  + decisionList
2614
3326
  + failedList
2615
3327
  + emptyList
@@ -2657,6 +3369,8 @@ export {
2657
3369
  sessionIdFromContext,
2658
3370
  buildActiveCanvasContext,
2659
3371
  isPermissionFailure,
3372
+ buildRunSummarySnapshot,
3373
+ abortSessionRun,
2660
3374
  runPlan,
2661
3375
  executePlan,
2662
3376
  };