dsh-workflow-canvas 1.5.0 → 1.5.5

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);
@@ -557,6 +559,10 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
557
559
  }
558
560
 
559
561
  const run = async (childId, overridePrompt) => {
562
+ // Guard before every activation so an interrupted run can never spawn fresh/fallback zombies.
563
+ if (signal && signal.aborted) {
564
+ return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '' };
565
+ }
560
566
  const baseSpec = overridePrompt
561
567
  ? { ...spec, prompt: [{ type: 'text', text: overridePrompt }] }
562
568
  : spec;
@@ -570,10 +576,13 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
570
576
  }
571
577
  try {
572
578
  if (activation && activation.childId) {
573
- liveChild.set(childKey(node.id), activation.childId);
579
+ const cid = String(activation.childId);
580
+ liveChild.set(childKey(node.id), cid);
574
581
  // Only overwrite the persisted memory slot when Memory is ON, so a
575
582
  // temporary keepSession=false experiment never destroys saved memory.
576
- if (node.keepSession) childByNode.set(childKey(node.id), activation.childId);
583
+ if (node.keepSession) childByNode.set(childKey(node.id), cid);
584
+ const activeRec = sid ? activeRunBySession.get(String(sid)) : null;
585
+ if (activeRec && activeRec.childIds) activeRec.childIds.add(cid);
577
586
  }
578
587
  let result;
579
588
  try {
@@ -595,6 +604,10 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
595
604
  }
596
605
  return outcome;
597
606
  } finally {
607
+ if (activation && activation.childId && sid) {
608
+ const activeRec = activeRunBySession.get(String(sid));
609
+ if (activeRec && activeRec.childIds) activeRec.childIds.delete(String(activation.childId));
610
+ }
598
611
  try { await activation.dispose(); } catch (_e) { /* ignore */ }
599
612
  }
600
613
  };
@@ -603,6 +616,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
603
616
  // resume its warm child session with a concise incremental correction prompt.
604
617
  if (warmPrompt && loopCtx && loopCtx.warmChildId && !forcedChild) {
605
618
  const continued = await run(loopCtx.warmChildId, warmPrompt);
619
+ if (signal && signal.aborted) return continued;
606
620
  if (continued.ok) {
607
621
  liveChild.set(childKey(node.id), continued.childId || loopCtx.warmChildId);
608
622
  return continued;
@@ -617,6 +631,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
617
631
  // step inside that child session instead of starting a fresh one.
618
632
  if (forcedChild) {
619
633
  const continued = await run(forcedChild);
634
+ if (signal && signal.aborted) return continued;
620
635
  if (continued.ok) {
621
636
  liveChild.set(childKey(node.id), forcedChild);
622
637
  return continued;
@@ -637,6 +652,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
637
652
  const previous = pinned || saved || inProcess;
638
653
  if (previous) {
639
654
  const resumed = await run(previous);
655
+ if (signal && signal.aborted) return resumed;
640
656
  if (resumed.ok) return resumed;
641
657
  if (resumed.reason === 'activation-failed') {
642
658
  if (previous === inProcess) liveChild.delete(childKey(node.id));
@@ -655,6 +671,9 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
655
671
  }
656
672
 
657
673
  async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet, loopCtx) {
674
+ if (signal && signal.aborted) {
675
+ return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '' };
676
+ }
658
677
  const continueFrom = forwardEdgesOf(plan.edges || [])
659
678
  .filter((e) => e.to === node.id && e.type === 'session-ref' && !(prunedSet && prunedSet.has(e.from)))
660
679
  .map((e) => liveChild.get(String(sid || '') + '::' + e.from)
@@ -663,6 +682,7 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
663
682
 
664
683
  if (continueFrom) {
665
684
  const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet, loopCtx);
685
+ if (signal && signal.aborted) return continued;
666
686
  if (continued.ok) {
667
687
  const out = { ok: true, empty: Boolean(continued.empty), text: continued.text + '\n(已在上游会话中继续)', childId: continued.childId || continueFrom };
668
688
  if (continued.decision) out.decision = continued.decision;
@@ -671,6 +691,7 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
671
691
  }
672
692
 
673
693
  const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
694
+ if (signal && signal.aborted) return first;
674
695
  if (first.ok) {
675
696
  const out = { ok: true, empty: Boolean(first.empty), text: first.text, childId: first.childId || '' };
676
697
  if (first.decision) out.decision = first.decision;
@@ -902,7 +923,7 @@ function normalizeCanvas(args) {
902
923
  provider: String(raw.provider || ''),
903
924
  model: String(raw.model || ''),
904
925
  reasoning: String(raw.reasoning || ''),
905
- preset: String(raw.preset || ''),
926
+ preset: (id === 'lead' ? '' : (kind === 'condition' ? 'minimal' : String(raw.preset || ''))),
906
927
  structured: Boolean(raw.structured),
907
928
  keepSession: Boolean(raw.keepSession),
908
929
  fallbackModel: String(raw.fallbackModel || ''),
@@ -1038,6 +1059,7 @@ function applyPatch(plan, args) {
1038
1059
  if (patch[key] !== undefined) existing[key] = patch[key];
1039
1060
  }
1040
1061
  if (patch.kind !== undefined) existing.kind = normalizeKind(patch.kind);
1062
+ if (existing.kind === 'condition') existing.preset = 'minimal';
1041
1063
  if (patch.branches !== undefined) {
1042
1064
  const nb = normalizeBranches(patch.branches);
1043
1065
  if (nb) existing.branches = nb;
@@ -1064,7 +1086,7 @@ function applyPatch(plan, args) {
1064
1086
  for (const key of ALLOWED) {
1065
1087
  if (patch[key] !== undefined) created[key] = patch[key];
1066
1088
  }
1067
- created.preset = created.preset === 'minimal' ? 'minimal' : 'standard';
1089
+ created.preset = (created.kind === 'condition' || created.preset === 'minimal') ? 'minimal' : 'standard';
1068
1090
  if (created.kind === 'condition' && patch.branches !== undefined) {
1069
1091
  const nb = normalizeBranches(patch.branches);
1070
1092
  if (nb) created.branches = nb;
@@ -1157,9 +1179,18 @@ function applyPatch(plan, args) {
1157
1179
  * resolves a session's root from its header cwd, so the client reads the same
1158
1180
  * relative path back through the Remote.
1159
1181
  */
1182
+ function resolveSessionsService(scope) {
1183
+ try {
1184
+ return (scope && scope.sessions) || (scope && typeof scope.get === 'function' ? scope.get('sessions') : null);
1185
+ } catch (_e) {
1186
+ return null;
1187
+ }
1188
+ }
1189
+
1160
1190
  function publishCanvas(scope, sessionId, canvas) {
1161
1191
  try {
1162
- const live = scope && scope.sessions && scope.sessions.get(sessionId);
1192
+ const sessionsSvc = resolveSessionsService(scope);
1193
+ const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
1163
1194
  const root = live && live.header && live.header.cwd;
1164
1195
  if (!root) return false;
1165
1196
  const dir = join(root, '.dsh', 'canvas');
@@ -1179,7 +1210,8 @@ function publishCanvas(scope, sessionId, canvas) {
1179
1210
  function publishRunState(scope, sessionId, runState) {
1180
1211
  try {
1181
1212
  if (!sessionId) return false;
1182
- const live = scope && scope.sessions && scope.sessions.get(sessionId);
1213
+ const sessionsSvc = resolveSessionsService(scope);
1214
+ const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
1183
1215
  const root = live && live.header && live.header.cwd;
1184
1216
  if (!root) return false;
1185
1217
  const dir = join(root, '.dsh', 'canvas');
@@ -1194,9 +1226,126 @@ function publishRunState(scope, sessionId, runState) {
1194
1226
  }
1195
1227
  }
1196
1228
 
1229
+ /**
1230
+ * Force-stop any running or paused (waitingLead) workflow for `sessionId`.
1231
+ * Uses DSH 0.2.2 native APIs:
1232
+ * - `scope.subagents.interrupt(childId, { kind: 'user' })` for each live child
1233
+ * - `scope.subagents.drainDescendants([rootAgent])` to tear down the full subtree
1234
+ * - `rootAgent.cancel({ kind: 'user' }, { keepInbox: true })` when a turn is active
1235
+ * Also aborts our local `AbortController`, preserves partial progress in `lastRunBySession`,
1236
+ * clears `runBySession` (`waitingLead`), and writes `halted` / `idle` to `.run.json`.
1237
+ */
1238
+ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1239
+ const sid = sessionId !== undefined && sessionId !== null ? String(sessionId) : '';
1240
+ if (!sid) return { stopped: false, wasRunning: false, wasWaiting: false };
1241
+ const allowCancelRoot = !(opts && opts.cancelRootTurn === false);
1242
+
1243
+ const active = activeRunBySession.get(sid);
1244
+ const wasRunning = Boolean(active);
1245
+ const childIds = active && active.childIds ? Array.from(active.childIds) : [];
1246
+ if (active) {
1247
+ try { active.ctrl.abort('user-stop'); } catch (_e) { /* ignore */ }
1248
+ activeRunBySession.delete(sid);
1249
+ }
1250
+
1251
+ // Interrupt every tracked live child immediately via DSH's native subagents.interrupt API.
1252
+ let subagents = null;
1253
+ try {
1254
+ subagents = (scope && scope.subagents) || (scope && typeof scope.get === 'function' ? scope.get('subagents') : null);
1255
+ } catch (_e) { subagents = null; }
1256
+ if (subagents && typeof subagents.interrupt === 'function') {
1257
+ for (const cid of childIds) {
1258
+ try { subagents.interrupt(cid, { kind: 'user' }); } catch (_e) { /* best-effort */ }
1259
+ }
1260
+ }
1261
+
1262
+ // Resolve the exact root Agent (from command invocation or `scope.agents.get(sid)`)
1263
+ // to drain the entire descendant subagent tree and cancel any active root turn.
1264
+ let targetAgent = rootAgent || null;
1265
+ if (!targetAgent) {
1266
+ let agentsSvc = null;
1267
+ try {
1268
+ agentsSvc = (scope && scope.agents) || (scope && typeof scope.get === 'function' ? scope.get('agents') : null);
1269
+ } catch (_e) { agentsSvc = null; }
1270
+ if (agentsSvc && typeof agentsSvc.get === 'function') {
1271
+ try { targetAgent = agentsSvc.get(sid) || null; } catch (_e) { targetAgent = null; }
1272
+ }
1273
+ }
1274
+ if (targetAgent) {
1275
+ if (subagents && typeof subagents.drainDescendants === 'function') {
1276
+ try {
1277
+ // Fire-and-forget teardown so `/canvas-stop` returns immediately to the UI even if a remote provider stalls.
1278
+ Promise.resolve(subagents.drainDescendants([targetAgent])).catch(() => {});
1279
+ } catch (_e) { /* best-effort */ }
1280
+ }
1281
+ if (allowCancelRoot && (wasRunning || targetAgent.running) && typeof targetAgent.cancel === 'function') {
1282
+ try { targetAgent.cancel({ kind: 'user' }, { keepInbox: true }); } catch (_e) { /* best-effort */ }
1283
+ }
1284
+ }
1285
+
1286
+ const st = runBySession.get(sid);
1287
+ const wasWaiting = Boolean(st && st.waitingLead);
1288
+ if (st) {
1289
+ if (st.done && st.done.size > 0) {
1290
+ lastRunBySession.set(sid, {
1291
+ sig: st.sig,
1292
+ done: new Set(st.done),
1293
+ results: { ...(st.results || {}) },
1294
+ labels: { ...(st.labels || {}) },
1295
+ failed: { ...(st.failed || {}) },
1296
+ emptyOutputs: { ...(st.emptyOutputs || {}) },
1297
+ blockedEdges: new Set(st.blockedEdges || []),
1298
+ pruned: new Set(st.pruned || []),
1299
+ decisions: { ...(st.decisions || {}) },
1300
+ fallbackLinks: Array.isArray(st.fallbackLinks) ? st.fallbackLinks.map((fl) => ({ ...fl })) : [],
1301
+ halted: true,
1302
+ });
1303
+ }
1304
+ runBySession.delete(sid);
1305
+ publishRunState(scope, sid, {
1306
+ status: 'halted',
1307
+ done: Array.from(st.done || []),
1308
+ decisions: { ...(st.decisions || {}) },
1309
+ pruned: Array.from(st.pruned || []),
1310
+ blockedEdges: Array.from(st.blockedEdges || []),
1311
+ loopCounts: {},
1312
+ nodeAttempts: { ...(st.nodeAttempts || {}) },
1313
+ waitingLead: null,
1314
+ });
1315
+ saveStore();
1316
+ } else {
1317
+ // Even if in-memory state was already gone (e.g. after restart), overwrite any stale `.run.json`
1318
+ // so a leftover `need-lead` file can never trap the sidebar UI.
1319
+ publishRunState(scope, sid, {
1320
+ status: wasRunning ? 'halted' : 'idle',
1321
+ done: [],
1322
+ decisions: {},
1323
+ pruned: [],
1324
+ blockedEdges: [],
1325
+ loopCounts: {},
1326
+ nodeAttempts: {},
1327
+ waitingLead: null,
1328
+ });
1329
+ }
1330
+ return { stopped: true, wasRunning, wasWaiting };
1331
+ }
1332
+
1197
1333
  async function runPlan(scope, args, exec) {
1198
1334
  const agent = exec && exec.agent;
1199
1335
  const sid = agent && agent.id !== undefined ? String(agent.id) : '';
1336
+ if (args && args.cancel === true) {
1337
+ // Pass `cancelRootTurn: false` because this tool call runs inside the model's current turn;
1338
+ // cancelling the root turn here would cut off the model's own cancellation confirmation reply.
1339
+ const res = abortSessionRun(scope, sid, agent, { cancelRootTurn: false });
1340
+ return {
1341
+ status: 'cancelled',
1342
+ wasRunning: res.wasRunning,
1343
+ wasWaiting: res.wasWaiting,
1344
+ hint: res.wasWaiting
1345
+ ? '已终止暂停中的工作流并解除等待拍板状态。'
1346
+ : '已终止当前工作流执行。',
1347
+ };
1348
+ }
1200
1349
  const payload = sid ? canvasBySession.get(sid) : undefined;
1201
1350
  if (!payload) return { error: '当前会话还没有画布数据。请在右侧 Workflow 画布点「启用」。' };
1202
1351
  if (!payload.enabled) return { error: '画布当前是「已禁用」状态。请在画布上点「启用」后再运行。' };
@@ -1227,7 +1376,7 @@ function inspectPlan(sid) {
1227
1376
  provider: String(n.provider || ''),
1228
1377
  model: String(n.model || ''),
1229
1378
  reasoning: String(n.reasoning || ''),
1230
- preset: n.preset === 'minimal' ? 'minimal' : 'standard',
1379
+ preset: (normalizeKind(n.kind) === 'condition' || n.preset === 'minimal') ? 'minimal' : 'standard',
1231
1380
  keepSession: Boolean(n.keepSession),
1232
1381
  structured: Boolean(n.structured),
1233
1382
  fallbackModel: String(n.fallbackModel || ''),
@@ -1297,12 +1446,16 @@ function buildActiveCanvasContext(sid) {
1297
1446
  const runState = runBySession.get(String(sid));
1298
1447
  if (runState && runState.waitingLead) {
1299
1448
  const wl = runState.waitingLead;
1449
+ const loopHint = wl.loopFeedback
1450
+ ? ('(↺ 第 ' + wl.loopFeedback.retry + '/' + wl.loopFeedback.max + ' 次回环修正,打回理由:' + (wl.loopFeedback.reason || '未达预期') + ')')
1451
+ : '';
1300
1452
  return [
1301
1453
  '[Workflow Canvas Active — Paused at Lead Step]',
1302
- '当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')。',
1454
+ '当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')' + loopHint + '。',
1303
1455
  '- 若用户的当前消息是在拍板、确认、补充决策或要求继续:请整理决策结论并直接调用 `canvas_workflow({ leadResult: "..." })` 恢复下游节点运行。',
1456
+ '- 若用户要求取消、结束或终止当前工作流:直接调用 `canvas_workflow({ cancel: true })` 解除暂停状态。',
1304
1457
  '- 若用户要求放弃当前进度从头重跑:调用 `canvas_workflow({ reset: true })`。',
1305
- '- 若用户要求修改画布结构/分工:先 `canvas_inspect` 再用 `canvas_patch`。',
1458
+ '- 若用户要求修改画布结构、分工、参考清单、分支或回环:先 `canvas_inspect` 再用 `canvas_patch`。',
1306
1459
  ].join('\n');
1307
1460
  }
1308
1461
 
@@ -1311,21 +1464,29 @@ function buildActiveCanvasContext(sid) {
1311
1464
  .map((n) => (n.kind === 'lead' ? '〔Lead〕' : (n.kind === 'condition' ? '〔条件〕' : '')) + (n.label || n.id))
1312
1465
  .join(' → ') + (nodes.length > 8 ? ' …' : '');
1313
1466
  const hasTask = Boolean(String((plan && plan.task) || '').trim());
1467
+ const loopCount = (plan && Array.isArray(plan.edges)) ? plan.edges.filter((e) => isLoopEdge(e)).length : 0;
1468
+ const globalRefs = normalizeRefs(plan && plan.refs) || [];
1314
1469
  const prefix = String(sid) + '::';
1315
1470
  const hasMemory = nodes.some((n) => n.keepSession && (liveChild.has(prefix + n.id) || childByNode.has(prefix + n.id)));
1471
+ const metaParts = [
1472
+ '共 ' + nodes.length + ' 个执行节点:' + preview,
1473
+ '入口总任务:' + (hasTask ? '已填写' : '未填写'),
1474
+ ];
1475
+ if (loopCount > 0) metaParts.push('含 ' + loopCount + ' 条受控回环(引擎自动按条件带反馈重试并在超限时熔断交 Lead,无需你手动循环调用)');
1476
+ if (globalRefs.length > 0) metaParts.push('全局参考 ×' + globalRefs.length);
1316
1477
  const lines = [
1317
1478
  '[Workflow Canvas Active]',
1318
- '当前会话的右侧工作流画布处于「● 已启用」状态(共 ' + nodes.length + ' 个执行节点:' + preview + ';入口总任务:' + (hasTask ? '已填写' : '未填写') + ')。',
1479
+ '当前会话的右侧工作流画布处于「● 已启用」状态(' + metaParts.join(';') + ')。',
1319
1480
  '- 若用户发出任务请求、布置工作或说「开始 / 执行 / 跑一次」:请直接调用 `canvas_workflow` 按画布编排执行('
1320
1481
  + (hasTask ? '可直接沿用入口总任务;若用户给出了新任务则通过 task 参数传入' : '请将用户的任务内容作为 task 参数传入')
1321
1482
  + '),不要绕过画布直接自己完成。',
1322
- '- 若用户在讨论或要求修改画布结构、模型、分工或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
1483
+ '- 若用户在讨论或要求修改画布结构、模型、分工、参考清单、条件分支、回环或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
1323
1484
  '- 仅当用户明确只是闲聊、问无关问题或要求先停用画布时,才无需调用 `canvas_workflow`。',
1324
1485
  ];
1325
1486
  if (hasMemory) {
1326
1487
  lines.push('- 本会话已有开启「记忆」节点的历史子代理会话:若用户说「再跑一次 / 换个任务重跑」,请先简短询问用户是保留上次记忆继续(reset: true)还是清空记忆全新开跑(reset: true, clearMemory: true)。');
1327
1488
  }
1328
- const stdCount = nodes.filter((n) => n.kind !== 'lead' && n.preset !== 'minimal').length;
1489
+ const stdCount = nodes.filter((n) => n.kind !== 'lead' && n.kind !== 'condition' && n.preset !== 'minimal').length;
1329
1490
  if (stdCount >= 2) {
1330
1491
  lines.push('- 本画布包含 ' + stdCount + ' 个可写/命令型(standard)子代理,受主对话权限上限约束;若任务涉及改代码、写文件或跑终端命令且当前主对话权限偏严格,请先简短提醒用户放开主对话权限再调 `canvas_workflow`,避免中途报错白耗额度。');
1331
1492
  }
@@ -1358,6 +1519,17 @@ async function executePlan(scope, plan, args, exec) {
1358
1519
  const opts = args || {};
1359
1520
  const agent = exec && exec.agent;
1360
1521
  const sid = agent && agent.id !== undefined ? String(agent.id) : '';
1522
+ if (opts.cancel === true) {
1523
+ const res = abortSessionRun(scope, sid, agent, { cancelRootTurn: false });
1524
+ return {
1525
+ status: 'cancelled',
1526
+ wasRunning: res.wasRunning,
1527
+ wasWaiting: res.wasWaiting,
1528
+ hint: res.wasWaiting
1529
+ ? '已终止暂停中的工作流并解除等待拍板状态。'
1530
+ : '已终止当前工作流执行。',
1531
+ };
1532
+ }
1361
1533
  if (!plan || !Array.isArray(plan.nodes) || !plan.nodes.length) {
1362
1534
  return { error: '画布没有可执行的节点。' };
1363
1535
  }
@@ -1700,7 +1872,56 @@ async function executePlan(scope, plan, args, exec) {
1700
1872
  // downstream agents start immediately instead of waiting for slower siblings.
1701
1873
  const inFlight = new Map();
1702
1874
 
1703
- const isAborted = () => Boolean(exec && exec.signal && exec.signal.aborted);
1875
+ const runCtrl = new AbortController();
1876
+ const runSignal = runCtrl.signal;
1877
+ const activeRec = { ctrl: runCtrl, childIds: new Set() };
1878
+ const parentSignal = exec && exec.signal;
1879
+ const onParentAbort = () => {
1880
+ try { runCtrl.abort('parent-abort'); } catch (_e) { /* ignore */ }
1881
+ // Also interrupt every already-running child via DSH's native subagents.interrupt API,
1882
+ // since startActivation({ signal }) only aborts startup, not post-start execution.
1883
+ try {
1884
+ const subagents = (scope && scope.subagents) || (scope && typeof scope.get === 'function' ? scope.get('subagents') : null);
1885
+ if (subagents && typeof subagents.interrupt === 'function') {
1886
+ for (const cid of activeRec.childIds) {
1887
+ try { subagents.interrupt(cid, { kind: 'user' }); } catch (_e) { /* best-effort */ }
1888
+ }
1889
+ }
1890
+ } catch (_e) { /* best-effort */ }
1891
+ };
1892
+ if (parentSignal) {
1893
+ if (parentSignal.aborted) onParentAbort();
1894
+ else if (typeof parentSignal.addEventListener === 'function') {
1895
+ parentSignal.addEventListener('abort', onParentAbort, { once: true });
1896
+ }
1897
+ }
1898
+ if (sid) activeRunBySession.set(sid, activeRec);
1899
+
1900
+ const isAborted = () => Boolean(runSignal.aborted || (parentSignal && parentSignal.aborted));
1901
+ // Raced alongside `inFlight` so user cancellation unblocks immediately even if a child activation hangs.
1902
+ const abortPromise = new Promise((resolve) => {
1903
+ if (isAborted()) { resolve({ __aborted: true }); return; }
1904
+ runSignal.addEventListener('abort', () => resolve({ __aborted: true }), { once: true });
1905
+ });
1906
+ const finishAborted = () => {
1907
+ snapshotLastRun(true);
1908
+ emitRunState('halted', null);
1909
+ if (sid) runBySession.delete(sid);
1910
+ saveStore();
1911
+ return {
1912
+ status: 'halted',
1913
+ error: '工作流执行已取消。',
1914
+ results: state.results,
1915
+ labels: state.labels,
1916
+ failed: Object.values(state.failed),
1917
+ emptyOutputs: Object.values(state.emptyOutputs),
1918
+ decisions: Object.values(state.decisions),
1919
+ branchSkipped: branchSkippedList(),
1920
+ ...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
1921
+ reused,
1922
+ skipped,
1923
+ };
1924
+ };
1704
1925
  const permBlocked = [];
1705
1926
  let activationFailCount = 0;
1706
1927
  let haltedReason = '';
@@ -1717,7 +1938,7 @@ async function executePlan(scope, plan, args, exec) {
1717
1938
  const warmChildId = (fb && state.loopWarmChild[node.id]) ? state.loopWarmChild[node.id] : '';
1718
1939
  const loopCtx = fb ? { feedback: fb, warmChildId } : undefined;
1719
1940
  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)
1941
+ const promise = spawnNode(scope, plan, node, state.results, agent, runSignal, sid, state.failed, state.pruned, loopCtx)
1721
1942
  .then(
1722
1943
  (outcome) => ({ node, outcome }),
1723
1944
  (err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
@@ -1726,11 +1947,10 @@ async function executePlan(scope, plan, args, exec) {
1726
1947
  }
1727
1948
  };
1728
1949
 
1950
+ try {
1729
1951
  for (;;) {
1730
1952
  if (isAborted()) {
1731
- emitRunState('halted', null);
1732
- if (sid) runBySession.delete(sid);
1733
- return { error: '工作流执行已取消。' };
1953
+ return finishAborted();
1734
1954
  }
1735
1955
  // On circuit-break halt, stop launching new downstream waves immediately,
1736
1956
  // but let already in-flight siblings settle so no orphan promises or partial
@@ -1777,13 +1997,12 @@ async function executePlan(scope, plan, args, exec) {
1777
1997
  launchReadyAgents();
1778
1998
 
1779
1999
  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: '工作流执行已取消。' };
2000
+ const raceHit = await Promise.race([...inFlight.values(), abortPromise]);
2001
+ if ((raceHit && raceHit.__aborted) || isAborted()) {
2002
+ return finishAborted();
1786
2003
  }
2004
+ const { node, outcome } = raceHit;
2005
+ inFlight.delete(node.id);
1787
2006
  state.labels[node.id] = node.label;
1788
2007
  if (node.kind === 'condition') {
1789
2008
  const { branches, isDefaultBinary } = conditionBranches(node);
@@ -1901,6 +2120,29 @@ async function executePlan(scope, plan, args, exec) {
1901
2120
  for (const e of plan.edges || []) {
1902
2121
  if (e && members.has(e.from)) state.blockedEdges.delete(edgeKey(e));
1903
2122
  }
2123
+ // Un-prune previously pruned downstream nodes reachable from loop members so
2124
+ // an inner condition picking a different branch on a retry round can still run them.
2125
+ if (state.pruned.size > 0) {
2126
+ const fwdAdj = new Map();
2127
+ for (const e of forwardEdgesOf(plan.edges || [])) {
2128
+ if (!e || !e.from || !e.to) continue;
2129
+ if (!fwdAdj.has(e.from)) fwdAdj.set(e.from, []);
2130
+ fwdAdj.get(e.from).push(e.to);
2131
+ }
2132
+ const reach = new Set(members);
2133
+ const rq = Array.from(members);
2134
+ for (let i = 0; i < rq.length; i += 1) {
2135
+ for (const nx of fwdAdj.get(rq[i]) || []) {
2136
+ if (!reach.has(nx)) { reach.add(nx); rq.push(nx); }
2137
+ }
2138
+ }
2139
+ for (const rid of reach) {
2140
+ if (!members.has(rid) && state.pruned.has(rid)) {
2141
+ state.pruned.delete(rid);
2142
+ state.done.delete(rid);
2143
+ }
2144
+ }
2145
+ }
1904
2146
  state.fallbackLinks = state.fallbackLinks.filter((fl) => !members.has(fl.from) && !members.has(fl.to));
1905
2147
  state.loopFeedback[le.to] = {
1906
2148
  retry: nextRetry,
@@ -2035,6 +2277,7 @@ async function executePlan(scope, plan, args, exec) {
2035
2277
  fallbackParts.push('⚠ 条件节点(' + unmatchedConds.join('、') + ')所有分支均未命中,已跳过中间分支直接转交给你处理。');
2036
2278
  }
2037
2279
  const fallbackNotice = fallbackParts.join(' ');
2280
+ const mergedLeadRefs = normalizeRefs((normalizeRefs(plan && plan.refs) || []).concat(normalizeRefs(leadNode.refs) || []));
2038
2281
  const hasDownstreamWork = remaining.some((n) => n.id !== leadNode.id);
2039
2282
  if (!hasDownstreamWork && leadResult === undefined) {
2040
2283
  // Terminal Lead: zero downstream nodes remain, so complete the run directly
@@ -2050,7 +2293,7 @@ async function executePlan(scope, plan, args, exec) {
2050
2293
  label: leadNode.label,
2051
2294
  role: leadNode.role || leadNode.label,
2052
2295
  needs: depsOf(leadNode).map((id) => byId.get(id).label),
2053
- ...(normalizeRefs(leadNode.refs) ? { refs: normalizeRefs(leadNode.refs) } : {}),
2296
+ ...(mergedLeadRefs ? { refs: mergedLeadRefs } : {}),
2054
2297
  },
2055
2298
  results: state.results,
2056
2299
  labels: state.labels,
@@ -2067,10 +2310,14 @@ async function executePlan(scope, plan, args, exec) {
2067
2310
  };
2068
2311
  }
2069
2312
  if (leadResult === undefined) {
2313
+ const leadFbSummary = leadFb
2314
+ ? { retry: leadFb.retry, max: leadFb.max, sourceLabel: leadFb.sourceLabel, reason: leadFb.reason }
2315
+ : null;
2070
2316
  state.waitingLead = {
2071
2317
  id: leadNode.id,
2072
2318
  label: leadNode.label,
2073
2319
  role: leadNode.role || leadNode.label,
2320
+ ...(leadFbSummary ? { loopFeedback: leadFbSummary } : {}),
2074
2321
  };
2075
2322
  emitRunState('need-lead', state.waitingLead);
2076
2323
  return {
@@ -2079,8 +2326,8 @@ async function executePlan(scope, plan, args, exec) {
2079
2326
  label: leadNode.label,
2080
2327
  role: leadNode.role || leadNode.label,
2081
2328
  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 } } : {}),
2329
+ ...(mergedLeadRefs ? { refs: mergedLeadRefs } : {}),
2330
+ ...(leadFbSummary ? { loopFeedback: leadFbSummary } : {}),
2084
2331
  },
2085
2332
  results: state.results,
2086
2333
  labels: state.labels,
@@ -2091,7 +2338,7 @@ async function executePlan(scope, plan, args, exec) {
2091
2338
  ...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
2092
2339
  sessions: leadSessions,
2093
2340
  hint: (fallbackNotice ? fallbackNotice + ' ' : '')
2094
- + '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需从头重跑可传 reset: true。',
2341
+ + '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需取消本次流程可传 cancel: true,若需从头重跑可传 reset: true。',
2095
2342
  };
2096
2343
  }
2097
2344
  state.waitingLead = null;
@@ -2101,11 +2348,19 @@ async function executePlan(scope, plan, args, exec) {
2101
2348
  state.done.add(leadNode.id);
2102
2349
  leadResult = undefined;
2103
2350
  }
2351
+ } finally {
2352
+ if (parentSignal && typeof parentSignal.removeEventListener === 'function') {
2353
+ try { parentSignal.removeEventListener('abort', onParentAbort); } catch (_e) { /* ignore */ }
2354
+ }
2355
+ if (sid && activeRunBySession.get(sid) === activeRec) {
2356
+ activeRunBySession.delete(sid);
2357
+ }
2358
+ }
2104
2359
  }
2105
2360
 
2106
2361
  /** Agent-facing guide, shipped as a skill so any agent can load it on demand. */
2107
2362
  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.';
2363
+ 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
2364
  function skillPath() {
2110
2365
  try {
2111
2366
  return fileURLToPath(new URL('./skills/workflow-canvas/SKILL.md', import.meta.url));
@@ -2194,6 +2449,21 @@ export function apply(ctx) {
2194
2449
  }
2195
2450
  },
2196
2451
  }), 'workflow-canvas: sync command');
2452
+ scope.effect(() => scope.commands.register({
2453
+ name: 'canvas-stop',
2454
+ description: 'Stop any running or paused workflow canvas execution for this session.',
2455
+ recordInput: false,
2456
+ handler: ({ agent }) => {
2457
+ try {
2458
+ const id = agent && agent.id !== undefined ? String(agent.id) : '';
2459
+ if (!id) return { kind: 'error', text: 'no session' };
2460
+ abortSessionRun(ctx, id, agent);
2461
+ return { kind: 'success', text: 'workflow stopped' };
2462
+ } catch (error) {
2463
+ return { kind: 'error', text: String((error && error.message) || error) };
2464
+ }
2465
+ },
2466
+ }), 'workflow-canvas: stop command');
2197
2467
  } catch (_e) {
2198
2468
  /* command registry unavailable */
2199
2469
  }
@@ -2447,6 +2717,9 @@ export function apply(ctx) {
2447
2717
  '画布状态:' + (v.enabled ? '● 已启用' : '○ 已禁用') + (v.paused ? '(当前暂停在 Lead 步骤)' : ''),
2448
2718
  '总任务:' + (v.task || '(未填写,运行时可通过 task 参数指定)'),
2449
2719
  ];
2720
+ if (Array.isArray(v.refs) && v.refs.length) {
2721
+ head.push('全局参考:' + v.refs.join(';'));
2722
+ }
2450
2723
  if (v.error) head.push('校验错误:' + v.error);
2451
2724
  const warnBlock = Array.isArray(v.warnings) && v.warnings.length
2452
2725
  ? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
@@ -2471,7 +2744,9 @@ export function apply(ctx) {
2471
2744
  + (n.role ? ':' + n.role : '');
2472
2745
  });
2473
2746
  const edgeLines = (v.edges || []).map((e) => '- ' + e.from
2474
- + ' --(' + e.type + (e.branch ? ':' + e.branch : '') + ')--> ' + e.to);
2747
+ + ' --(' + e.type + (e.branch ? ':' + e.branch : '')
2748
+ + (e.loop ? ', ↺ loop ×' + normalizeMaxIterations(e.maxIterations) : '')
2749
+ + ')--> ' + e.to);
2475
2750
  return [{
2476
2751
  type: 'text',
2477
2752
  text: head.join('\n')
@@ -2492,16 +2767,17 @@ export function apply(ctx) {
2492
2767
  }
2493
2768
  });
2494
2769
 
2495
- ctx.inject(['tools', 'subagents'], (scope) => {
2770
+ ctx.inject(['tools', 'subagents', 'sessions'], (scope) => {
2496
2771
  try {
2497
2772
  scope.effect(() => scope.tools.register({
2498
2773
  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.',
2774
+ 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
2775
  parameters: {
2501
2776
  type: 'object',
2502
2777
  properties: {
2503
2778
  leadResult: { type: 'string', description: 'Your own output for the Lead step that was just requested.' },
2504
2779
  task: { type: 'string', description: 'Optional overall task overriding the entry Lead task for this run (useful for reusing a preset).' },
2780
+ cancel: { type: 'boolean', description: 'Stop and cancel any active or paused (waitingLead) workflow run cleanly.' },
2505
2781
  reset: { type: 'boolean', description: 'Discard any paused run progress and start from the beginning.' },
2506
2782
  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
2783
  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 +2810,7 @@ export function apply(ctx) {
2534
2810
  render: (_args, value) => {
2535
2811
  const v = value || {};
2536
2812
  if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
2813
+ if (v.status === 'cancelled') return [{ type: 'text', text: v.hint || '已终止当前工作流执行。' }];
2537
2814
  const results = v.results || {};
2538
2815
  const labels = v.labels || {};
2539
2816
  const blocks = Object.keys(results).map((id) => {
@@ -2573,6 +2850,9 @@ export function apply(ctx) {
2573
2850
  : '';
2574
2851
  if (v.status === 'need-lead') {
2575
2852
  const n = v.node || {};
2853
+ const refsBlock = Array.isArray(n.refs) && n.refs.length
2854
+ ? '\n参考资料 / 约束:\n' + n.refs.map((r) => '- ' + r).join('\n')
2855
+ : '';
2576
2856
  const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
2577
2857
  const handover = handed.length
2578
2858
  ? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
@@ -2582,6 +2862,7 @@ export function apply(ctx) {
2582
2862
  type: 'text',
2583
2863
  text: '需要你(Lead)完成「' + n.label + '」:' + n.role
2584
2864
  + '\n需要用到:' + ((n.needs && n.needs.length) ? n.needs.join('、') : '(无上游)')
2865
+ + refsBlock
2585
2866
  + decisionList
2586
2867
  + failedList
2587
2868
  + emptyList
@@ -2601,6 +2882,9 @@ export function apply(ctx) {
2601
2882
  : '';
2602
2883
  if (v.finalLead) {
2603
2884
  const fl = v.finalLead;
2885
+ const refsBlock = Array.isArray(fl.refs) && fl.refs.length
2886
+ ? '\n参考资料 / 约束:\n' + fl.refs.map((r) => '- ' + r).join('\n')
2887
+ : '';
2604
2888
  const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
2605
2889
  const handover = handed.length
2606
2890
  ? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
@@ -2610,6 +2894,7 @@ export function apply(ctx) {
2610
2894
  type: 'text',
2611
2895
  text: '所有子代理已完成,现在进入终审 Lead 步骤「' + fl.label + '」:' + fl.role
2612
2896
  + '\n需要用到:' + ((fl.needs && fl.needs.length) ? fl.needs.join('、') : '(无上游)')
2897
+ + refsBlock
2613
2898
  + decisionList
2614
2899
  + failedList
2615
2900
  + emptyList
@@ -2657,6 +2942,7 @@ export {
2657
2942
  sessionIdFromContext,
2658
2943
  buildActiveCanvasContext,
2659
2944
  isPermissionFailure,
2945
+ abortSessionRun,
2660
2946
  runPlan,
2661
2947
  executePlan,
2662
2948
  };