dsh-workflow-canvas 1.4.1 → 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/README.md +15 -8
- package/README.zh.md +15 -8
- package/client.js +1479 -330
- package/docs/DETAIL.md +50 -27
- package/docs/MECHANISM.md +20 -18
- package/docs/MECHANISM.zh.md +20 -18
- package/docs/images/retry-loop-en.png +0 -0
- package/docs/images/retry-loop-zh.png +0 -0
- package/index.js +717 -72
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
- package/skills/workflow-canvas/SKILL.md +8 -7
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
|
/**
|
|
@@ -90,10 +92,66 @@ function parsePayload(rawInput) {
|
|
|
90
92
|
}
|
|
91
93
|
}
|
|
92
94
|
|
|
93
|
-
|
|
95
|
+
const MAX_LOOP_ITERATIONS = 10;
|
|
96
|
+
const DEFAULT_LOOP_ITERATIONS = 3;
|
|
97
|
+
const MAX_GLOBAL_LOOPS = 20;
|
|
98
|
+
|
|
99
|
+
function normalizeMaxIterations(val) {
|
|
100
|
+
const n = Number(val);
|
|
101
|
+
if (!Number.isFinite(n)) return DEFAULT_LOOP_ITERATIONS;
|
|
102
|
+
return Math.max(1, Math.min(MAX_LOOP_ITERATIONS, Math.floor(n)));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function isLoopEdge(e) {
|
|
106
|
+
return Boolean(e && e.loop === true);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function forwardEdgesOf(edges) {
|
|
110
|
+
return (Array.isArray(edges) ? edges : []).filter((e) => e && !e.loop);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Compute the set of node ids strictly inside a controlled loop edge (from target -> ... -> source)
|
|
115
|
+
* over forward edges: `descendants(loopEdge.to) ∩ ancestors(loopEdge.from)` (inclusive).
|
|
116
|
+
* Returns an empty Set if `loopEdge.from` is not reachable from `loopEdge.to` over forward edges.
|
|
117
|
+
*/
|
|
118
|
+
function loopMemberIds(nodes, edges, loopEdge) {
|
|
119
|
+
if (!loopEdge || !loopEdge.from || !loopEdge.to || loopEdge.to === 'lead') return new Set();
|
|
120
|
+
const fwd = new Map();
|
|
121
|
+
const rev = new Map();
|
|
122
|
+
for (const e of forwardEdgesOf(edges)) {
|
|
123
|
+
if (!e.from || !e.to) continue;
|
|
124
|
+
if (!fwd.has(e.from)) fwd.set(e.from, []);
|
|
125
|
+
fwd.get(e.from).push(e.to);
|
|
126
|
+
if (!rev.has(e.to)) rev.set(e.to, []);
|
|
127
|
+
rev.get(e.to).push(e.from);
|
|
128
|
+
}
|
|
129
|
+
const desc = new Set([loopEdge.to]);
|
|
130
|
+
const q1 = [loopEdge.to];
|
|
131
|
+
for (let i = 0; i < q1.length; i += 1) {
|
|
132
|
+
for (const next of fwd.get(q1[i]) || []) {
|
|
133
|
+
if (!desc.has(next)) { desc.add(next); q1.push(next); }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!desc.has(loopEdge.from)) return new Set();
|
|
137
|
+
const anc = new Set([loopEdge.from]);
|
|
138
|
+
const q2 = [loopEdge.from];
|
|
139
|
+
for (let i = 0; i < q2.length; i += 1) {
|
|
140
|
+
for (const prev of rev.get(q2[i]) || []) {
|
|
141
|
+
if (!anc.has(prev)) { anc.add(prev); q2.push(prev); }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const members = new Set();
|
|
145
|
+
for (const id of desc) {
|
|
146
|
+
if (anc.has(id)) members.add(id);
|
|
147
|
+
}
|
|
148
|
+
return members;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Kahn topological order over every plan node (ignoring controlled loop back-edges). */
|
|
94
152
|
function orderNodes(plan) {
|
|
95
153
|
const nodes = plan.nodes || [];
|
|
96
|
-
const edges = plan.edges || [];
|
|
154
|
+
const edges = forwardEdgesOf(plan.edges || []);
|
|
97
155
|
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
98
156
|
const indeg = new Map(nodes.map((n) => [n.id, 0]));
|
|
99
157
|
const adj = new Map(nodes.map((n) => [n.id, []]));
|
|
@@ -105,8 +163,8 @@ function orderNodes(plan) {
|
|
|
105
163
|
}
|
|
106
164
|
const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
|
|
107
165
|
const out = [];
|
|
108
|
-
|
|
109
|
-
const id = queue
|
|
166
|
+
for (let i = 0; i < queue.length; i += 1) {
|
|
167
|
+
const id = queue[i];
|
|
110
168
|
out.push(byId.get(id));
|
|
111
169
|
for (const next of adj.get(id)) {
|
|
112
170
|
indeg.set(next, indeg.get(next) - 1);
|
|
@@ -118,7 +176,7 @@ function orderNodes(plan) {
|
|
|
118
176
|
|
|
119
177
|
function upstreamOf(plan, node) {
|
|
120
178
|
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
121
|
-
return (plan.edges || [])
|
|
179
|
+
return forwardEdgesOf(plan.edges || [])
|
|
122
180
|
.filter((e) => e.to === node.id)
|
|
123
181
|
.map((e) => ({ edge: e, from: byId.get(e.from) }))
|
|
124
182
|
.filter((x) => x.from);
|
|
@@ -126,7 +184,7 @@ function upstreamOf(plan, node) {
|
|
|
126
184
|
|
|
127
185
|
function downstreamLabels(plan, node) {
|
|
128
186
|
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
129
|
-
return (plan.edges || [])
|
|
187
|
+
return forwardEdgesOf(plan.edges || [])
|
|
130
188
|
.filter((e) => e.from === node.id)
|
|
131
189
|
.map((e) => (byId.get(e.to) || {}).label)
|
|
132
190
|
.filter(Boolean);
|
|
@@ -312,7 +370,7 @@ function parseConditionDecision(result, fallbackText, nodeOrBranches) {
|
|
|
312
370
|
return makeDecision(matched, raw.slice(0, 200) || (matched.length ? '' : '未命中任何分支,已跳过后续分支'));
|
|
313
371
|
}
|
|
314
372
|
|
|
315
|
-
function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
373
|
+
function briefFor(plan, node, results, failedMap, prunedSet, loopCtx) {
|
|
316
374
|
const ups = upstreamOf(plan, node).filter((u) => !(prunedSet && prunedSet.has(u.from.id)));
|
|
317
375
|
const downs = downstreamLabels(plan, node);
|
|
318
376
|
const head = [];
|
|
@@ -320,11 +378,15 @@ function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
|
320
378
|
const outEdges = (plan.edges || []).filter((e) => e.from === node.id);
|
|
321
379
|
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
322
380
|
const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
|
|
381
|
+
const fmtTarget = (e) => {
|
|
382
|
+
const lbl = (byId.get(e.to) || {}).label || e.to;
|
|
383
|
+
return e.loop ? (lbl + '(↺ 回环重做,最多 ' + normalizeMaxIterations(e.maxIterations) + ' 次)') : lbl;
|
|
384
|
+
};
|
|
323
385
|
head.push('【工作流条件判断节点】你负责判断当前工作流接下来走哪条分支(「' + node.label + '」)。');
|
|
324
386
|
head.push('【总任务】' + plan.task);
|
|
325
387
|
if (isDefaultBinary) {
|
|
326
|
-
const yesTargets = outEdges.filter((e) => (normalizeBranch(e.branch) || 'true') === 'true').map(
|
|
327
|
-
const noTargets = outEdges.filter((e) => normalizeBranch(e.branch) === 'false').map(
|
|
388
|
+
const yesTargets = outEdges.filter((e) => (normalizeBranch(e.branch) || 'true') === 'true').map(fmtTarget);
|
|
389
|
+
const noTargets = outEdges.filter((e) => normalizeBranch(e.branch) === 'false').map(fmtTarget);
|
|
328
390
|
head.push('【判断条件】' + (node.role || '判断上游步骤是否执行成功并达到预期;成功返回 true,失败或未达标返回 false。'));
|
|
329
391
|
head.push('【分支去向】pass=true(是)→ ' + (yesTargets.join('、') || '(无)') + ';pass=false(否)→ ' + (noTargets.join('、') || '(无)'));
|
|
330
392
|
head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"pass": true/false, "reason": "一句话理由"}。');
|
|
@@ -335,7 +397,7 @@ function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
|
335
397
|
const eb = normalizeBranch(e.branch);
|
|
336
398
|
return eb ? eb === b.id : idx === 0;
|
|
337
399
|
})
|
|
338
|
-
.map(
|
|
400
|
+
.map(fmtTarget);
|
|
339
401
|
const tag = b.label === b.id ? '"' + b.id + '"' : '"' + b.id + '"(' + b.label + ')';
|
|
340
402
|
return '- ' + tag + ' → ' + (targets.join('、') || '(无下游)');
|
|
341
403
|
});
|
|
@@ -364,6 +426,15 @@ function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
|
364
426
|
if (mergedRefs.length) {
|
|
365
427
|
head.push('【参考资料 / 约束】\n' + mergedRefs.map((r) => '- ' + r).join('\n'));
|
|
366
428
|
}
|
|
429
|
+
if (loopCtx && loopCtx.feedback) {
|
|
430
|
+
const fb = loopCtx.feedback;
|
|
431
|
+
const lines = [
|
|
432
|
+
'【第 ' + fb.retry + '/' + fb.max + ' 次回环修正反馈】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请针对以下问题修正后输出最新结果:',
|
|
433
|
+
'- 打回理由:' + (fb.reason || '未达预期'),
|
|
434
|
+
];
|
|
435
|
+
if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
|
|
436
|
+
head.push(lines.join('\n'));
|
|
437
|
+
}
|
|
367
438
|
let text = head.join('\n') + '\n';
|
|
368
439
|
for (const u of ups) {
|
|
369
440
|
const value = results[u.from.id];
|
|
@@ -412,13 +483,29 @@ function isEmptyOutput(result) {
|
|
|
412
483
|
return text.trim().length === 0;
|
|
413
484
|
}
|
|
414
485
|
|
|
415
|
-
|
|
486
|
+
function buildLoopWarmPrompt(node, loopCtx) {
|
|
487
|
+
const fb = loopCtx && loopCtx.feedback;
|
|
488
|
+
if (!fb) return null;
|
|
489
|
+
const lines = [
|
|
490
|
+
'【第 ' + fb.retry + '/' + fb.max + ' 次回环修正】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请结合以下反馈直接在当前会话上下文中修正并输出最新交付结果(无需重复叙述过程):',
|
|
491
|
+
'- 打回理由:' + (fb.reason || '未达预期'),
|
|
492
|
+
];
|
|
493
|
+
if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
|
|
494
|
+
if (node.role) lines.push('- 你的职责提醒:' + node.role);
|
|
495
|
+
return lines.join('\n');
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid, failedMap, prunedSet, loopCtx) {
|
|
416
499
|
const childKey = (id) => String(sid || '') + '::' + id;
|
|
417
500
|
const isCondition = node.kind === 'condition';
|
|
501
|
+
const fullBrief = briefFor(plan, node, results, failedMap, prunedSet, loopCtx);
|
|
502
|
+
const warmPrompt = (!isCondition && loopCtx && loopCtx.warmChildId && loopCtx.feedback)
|
|
503
|
+
? buildLoopWarmPrompt(node, loopCtx)
|
|
504
|
+
: null;
|
|
418
505
|
const spec = {
|
|
419
506
|
provider: 'spawn',
|
|
420
507
|
label: node.label + '#' + node.id,
|
|
421
|
-
prompt: [{ type: 'text', text:
|
|
508
|
+
prompt: [{ type: 'text', text: fullBrief }],
|
|
422
509
|
parent,
|
|
423
510
|
signal,
|
|
424
511
|
delivery: 'caller',
|
|
@@ -471,8 +558,15 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
471
558
|
}
|
|
472
559
|
}
|
|
473
560
|
|
|
474
|
-
const run = async (childId) => {
|
|
475
|
-
|
|
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
|
+
}
|
|
566
|
+
const baseSpec = overridePrompt
|
|
567
|
+
? { ...spec, prompt: [{ type: 'text', text: overridePrompt }] }
|
|
568
|
+
: spec;
|
|
569
|
+
const withChild = childId ? { ...baseSpec, childId } : baseSpec;
|
|
476
570
|
let activation;
|
|
477
571
|
try {
|
|
478
572
|
activation = await scope.subagents.startActivation(withChild);
|
|
@@ -482,10 +576,13 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
482
576
|
}
|
|
483
577
|
try {
|
|
484
578
|
if (activation && activation.childId) {
|
|
485
|
-
|
|
579
|
+
const cid = String(activation.childId);
|
|
580
|
+
liveChild.set(childKey(node.id), cid);
|
|
486
581
|
// Only overwrite the persisted memory slot when Memory is ON, so a
|
|
487
582
|
// temporary keepSession=false experiment never destroys saved memory.
|
|
488
|
-
if (node.keepSession) childByNode.set(childKey(node.id),
|
|
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);
|
|
489
586
|
}
|
|
490
587
|
let result;
|
|
491
588
|
try {
|
|
@@ -507,14 +604,34 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
507
604
|
}
|
|
508
605
|
return outcome;
|
|
509
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
|
+
}
|
|
510
611
|
try { await activation.dispose(); } catch (_e) { /* ignore */ }
|
|
511
612
|
}
|
|
512
613
|
};
|
|
513
614
|
|
|
615
|
+
// On a controlled loop retry where the previous run of this node was healthy,
|
|
616
|
+
// resume its warm child session with a concise incremental correction prompt.
|
|
617
|
+
if (warmPrompt && loopCtx && loopCtx.warmChildId && !forcedChild) {
|
|
618
|
+
const continued = await run(loopCtx.warmChildId, warmPrompt);
|
|
619
|
+
if (signal && signal.aborted) return continued;
|
|
620
|
+
if (continued.ok) {
|
|
621
|
+
liveChild.set(childKey(node.id), continued.childId || loopCtx.warmChildId);
|
|
622
|
+
return continued;
|
|
623
|
+
}
|
|
624
|
+
if (continued.reason !== 'activation-failed') {
|
|
625
|
+
return continued;
|
|
626
|
+
}
|
|
627
|
+
/* warm session refused: fall through to a fresh session with the full brief + feedback */
|
|
628
|
+
}
|
|
629
|
+
|
|
514
630
|
// A `session` edge means "continue the upstream node's conversation": run this
|
|
515
631
|
// step inside that child session instead of starting a fresh one.
|
|
516
632
|
if (forcedChild) {
|
|
517
633
|
const continued = await run(forcedChild);
|
|
634
|
+
if (signal && signal.aborted) return continued;
|
|
518
635
|
if (continued.ok) {
|
|
519
636
|
liveChild.set(childKey(node.id), forcedChild);
|
|
520
637
|
return continued;
|
|
@@ -535,6 +652,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
535
652
|
const previous = pinned || saved || inProcess;
|
|
536
653
|
if (previous) {
|
|
537
654
|
const resumed = await run(previous);
|
|
655
|
+
if (signal && signal.aborted) return resumed;
|
|
538
656
|
if (resumed.ok) return resumed;
|
|
539
657
|
if (resumed.reason === 'activation-failed') {
|
|
540
658
|
if (previous === inProcess) liveChild.delete(childKey(node.id));
|
|
@@ -552,15 +670,19 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
552
670
|
return started;
|
|
553
671
|
}
|
|
554
672
|
|
|
555
|
-
async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet) {
|
|
556
|
-
|
|
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
|
+
}
|
|
677
|
+
const continueFrom = forwardEdgesOf(plan.edges || [])
|
|
557
678
|
.filter((e) => e.to === node.id && e.type === 'session-ref' && !(prunedSet && prunedSet.has(e.from)))
|
|
558
679
|
.map((e) => liveChild.get(String(sid || '') + '::' + e.from)
|
|
559
680
|
|| childByNode.get(String(sid || '') + '::' + e.from))
|
|
560
681
|
.find((id) => typeof id === 'string');
|
|
561
682
|
|
|
562
683
|
if (continueFrom) {
|
|
563
|
-
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet);
|
|
684
|
+
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet, loopCtx);
|
|
685
|
+
if (signal && signal.aborted) return continued;
|
|
564
686
|
if (continued.ok) {
|
|
565
687
|
const out = { ok: true, empty: Boolean(continued.empty), text: continued.text + '\n(已在上游会话中继续)', childId: continued.childId || continueFrom };
|
|
566
688
|
if (continued.decision) out.decision = continued.decision;
|
|
@@ -568,7 +690,8 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
568
690
|
}
|
|
569
691
|
}
|
|
570
692
|
|
|
571
|
-
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet);
|
|
693
|
+
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
694
|
+
if (signal && signal.aborted) return first;
|
|
572
695
|
if (first.ok) {
|
|
573
696
|
const out = { ok: true, empty: Boolean(first.empty), text: first.text, childId: first.childId || '' };
|
|
574
697
|
if (first.decision) out.decision = first.decision;
|
|
@@ -581,7 +704,7 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
581
704
|
const retry = await spawnOnce(scope, plan, node, results, parent, signal, {
|
|
582
705
|
provider: node.fallbackProvider,
|
|
583
706
|
model: node.fallbackModel,
|
|
584
|
-
}, undefined, sid, failedMap, prunedSet);
|
|
707
|
+
}, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
585
708
|
if (retry.ok) {
|
|
586
709
|
const out = { ok: true, empty: Boolean(retry.empty), text: retry.text + '\n(已用备用模型重试成功)', childId: retry.childId || '' };
|
|
587
710
|
if (retry.decision) out.decision = retry.decision;
|
|
@@ -591,10 +714,10 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
591
714
|
return { ok: false, empty: false, reason, text: retry.text + '\n(重试仍失败:' + reason + ')', childId: retry.childId || first.childId || '' };
|
|
592
715
|
}
|
|
593
716
|
|
|
594
|
-
/** Ids reachable from the entry Lead via O(V + E) BFS; every other node is skipped at run time. */
|
|
717
|
+
/** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
|
|
595
718
|
function reachableFrom(plan) {
|
|
596
719
|
const adj = new Map();
|
|
597
|
-
for (const e of (plan && plan.edges)
|
|
720
|
+
for (const e of forwardEdgesOf(plan && plan.edges)) {
|
|
598
721
|
if (!e || !e.from || !e.to) continue;
|
|
599
722
|
if (!adj.has(e.from)) adj.set(e.from, []);
|
|
600
723
|
adj.get(e.from).push(e.to);
|
|
@@ -613,19 +736,20 @@ function reachableFrom(plan) {
|
|
|
613
736
|
/**
|
|
614
737
|
* Classify inactive nodes that are rendered dashed on the canvas and skipped at run time:
|
|
615
738
|
* - unreachable orphans
|
|
616
|
-
* - solo chained Leads (zero reachable subagent upstream)
|
|
739
|
+
* - solo chained Leads (zero reachable subagent upstream and blank role)
|
|
617
740
|
* - dangling dead-end subagents (zero outgoing edges while an active non-ancestor downstream Lead exists)
|
|
618
741
|
*/
|
|
619
742
|
function inactiveNodeSets(nodes, edges) {
|
|
620
743
|
const list = withoutEntry(nodes);
|
|
621
744
|
const linkList = Array.isArray(edges) ? edges : [];
|
|
622
|
-
const
|
|
745
|
+
const fwdLinks = forwardEdgesOf(linkList);
|
|
746
|
+
const reachable = reachableFrom({ edges: fwdLinks });
|
|
623
747
|
const byId = new Map(list.map((n) => [n.id, n]));
|
|
624
748
|
|
|
625
749
|
const soloLeads = new Set();
|
|
626
750
|
for (const n of list) {
|
|
627
751
|
if (n.kind !== 'lead' || !reachable.has(n.id)) continue;
|
|
628
|
-
const hasAgentUp =
|
|
752
|
+
const hasAgentUp = fwdLinks.some((e) => {
|
|
629
753
|
if (!e || e.to !== n.id || !reachable.has(e.from) || e.from === 'lead') return false;
|
|
630
754
|
const src = byId.get(e.from);
|
|
631
755
|
return Boolean(src && src.kind !== 'lead');
|
|
@@ -639,7 +763,7 @@ function inactiveNodeSets(nodes, edges) {
|
|
|
639
763
|
if (activeLeads.length) {
|
|
640
764
|
const hasOut = new Set(linkList.map((e) => e.from));
|
|
641
765
|
const parents = new Map();
|
|
642
|
-
for (const e of
|
|
766
|
+
for (const e of fwdLinks) {
|
|
643
767
|
if (!parents.has(e.to)) parents.set(e.to, []);
|
|
644
768
|
parents.get(e.to).push(e.from);
|
|
645
769
|
}
|
|
@@ -663,12 +787,53 @@ function inactiveNodeSets(nodes, edges) {
|
|
|
663
787
|
return { reachable, soloLeads, deadEnds };
|
|
664
788
|
}
|
|
665
789
|
|
|
790
|
+
/**
|
|
791
|
+
* Validate controlled loop edges: each loop edge must leave a condition node, target a strict
|
|
792
|
+
* forward-path ancestor (never entry Lead), and not overlap/cross another loop edge's body.
|
|
793
|
+
*/
|
|
794
|
+
function validateLoopEdges(nodes, edges) {
|
|
795
|
+
const list = withoutEntry(nodes);
|
|
796
|
+
const byId = new Map(list.map((n) => [n.id, n]));
|
|
797
|
+
const linkList = Array.isArray(edges) ? edges : [];
|
|
798
|
+
const loopEdges = linkList.filter((e) => isLoopEdge(e));
|
|
799
|
+
const errors = [];
|
|
800
|
+
const seenMembers = new Map();
|
|
801
|
+
for (const le of loopEdges) {
|
|
802
|
+
const src = byId.get(le.from);
|
|
803
|
+
const dst = byId.get(le.to);
|
|
804
|
+
if (!src || src.kind !== 'condition') {
|
|
805
|
+
errors.push('回环边起点必须是条件判断节点(' + le.from + ' → ' + le.to + ')。');
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
if (!dst || le.to === 'lead') {
|
|
809
|
+
errors.push('回环边不能指向入口 Lead 或不存在的节点(' + le.from + ' → ' + le.to + ')。');
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
const members = loopMemberIds(list, linkList, le);
|
|
813
|
+
if (!members.size) {
|
|
814
|
+
errors.push('回环边目标「' + (dst.label || dst.id) + '」不是「' + (src.label || src.id) + '」的上游祖先节点。');
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
let overlap = false;
|
|
818
|
+
for (const mid of members) {
|
|
819
|
+
if (seenMembers.has(mid)) { overlap = true; break; }
|
|
820
|
+
}
|
|
821
|
+
if (overlap) {
|
|
822
|
+
errors.push('检测到交叉或嵌套回环(涉及节点「' + (dst.label || dst.id) + '」),暂不支持交叉回环。');
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
for (const mid of members) seenMembers.set(mid, le);
|
|
826
|
+
}
|
|
827
|
+
return errors;
|
|
828
|
+
}
|
|
829
|
+
|
|
666
830
|
/**
|
|
667
831
|
* Detect structural warnings on a canvas plan (all three classes are rendered
|
|
668
832
|
* dashed on the canvas and skipped at run time):
|
|
669
833
|
* 1. Unreachable nodes.
|
|
670
|
-
* 2. Solo chained Lead nodes with zero subagent upstream.
|
|
834
|
+
* 2. Solo chained Lead nodes with zero subagent upstream and blank role.
|
|
671
835
|
* 3. Dangling dead-end subagent nodes with zero outgoing edges.
|
|
836
|
+
* 4. Invalid/crossing loop edges or loop conditions with no forward exit.
|
|
672
837
|
*/
|
|
673
838
|
function analyzeCanvasWarnings(nodes, edges) {
|
|
674
839
|
const list = withoutEntry(nodes);
|
|
@@ -692,6 +857,27 @@ function analyzeCanvasWarnings(nodes, edges) {
|
|
|
692
857
|
warnings.push('以下子代理节点没有出边,产出未连入下游或终审 Lead,运行时不生效:'
|
|
693
858
|
+ deadList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
694
859
|
}
|
|
860
|
+
for (const err of validateLoopEdges(list, linkList)) warnings.push(err);
|
|
861
|
+
// Warn if a non-exit node inside a loop has a forward edge leaking outside the loop
|
|
862
|
+
// (that outside branch starts on round 1 and will not re-run on retry rounds).
|
|
863
|
+
const fwdLinks = forwardEdgesOf(linkList);
|
|
864
|
+
const byId = new Map(list.map((n) => [n.id, n]));
|
|
865
|
+
for (const le of linkList) {
|
|
866
|
+
if (!isLoopEdge(le)) continue;
|
|
867
|
+
const members = loopMemberIds(list, linkList, le);
|
|
868
|
+
if (!members.size) continue;
|
|
869
|
+
const leaked = [];
|
|
870
|
+
for (const e of fwdLinks) {
|
|
871
|
+
if (e.from !== le.from && members.has(e.from) && !members.has(e.to)) {
|
|
872
|
+
const src = byId.get(e.from);
|
|
873
|
+
const dst = byId.get(e.to);
|
|
874
|
+
leaked.push(((src && src.label) || e.from) + ' → ' + ((dst && dst.label) || e.to));
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
if (leaked.length) {
|
|
878
|
+
warnings.push('回环内部节点存在绕过条件裁判的旁路连线(' + leaked.join('、') + '),回环重试时这些环外节点不会重跑。');
|
|
879
|
+
}
|
|
880
|
+
}
|
|
695
881
|
return warnings;
|
|
696
882
|
}
|
|
697
883
|
|
|
@@ -737,7 +923,7 @@ function normalizeCanvas(args) {
|
|
|
737
923
|
provider: String(raw.provider || ''),
|
|
738
924
|
model: String(raw.model || ''),
|
|
739
925
|
reasoning: String(raw.reasoning || ''),
|
|
740
|
-
preset: String(raw.preset || ''),
|
|
926
|
+
preset: (id === 'lead' ? '' : (kind === 'condition' ? 'minimal' : String(raw.preset || ''))),
|
|
741
927
|
structured: Boolean(raw.structured),
|
|
742
928
|
keepSession: Boolean(raw.keepSession),
|
|
743
929
|
fallbackModel: String(raw.fallbackModel || ''),
|
|
@@ -770,6 +956,10 @@ function normalizeCanvas(args) {
|
|
|
770
956
|
const branch = normalizeBranch(raw.branch);
|
|
771
957
|
const edgeObj = { id: 'e' + edges.length, from, to, type };
|
|
772
958
|
if (branch) edgeObj.branch = branch;
|
|
959
|
+
if (raw.loop === true) {
|
|
960
|
+
edgeObj.loop = true;
|
|
961
|
+
edgeObj.maxIterations = normalizeMaxIterations(raw.maxIterations);
|
|
962
|
+
}
|
|
773
963
|
edges.push(edgeObj);
|
|
774
964
|
}
|
|
775
965
|
|
|
@@ -822,11 +1012,11 @@ function normalizeCanvas(args) {
|
|
|
822
1012
|
if (structuredSources.has(node.id)) node.structured = true;
|
|
823
1013
|
}
|
|
824
1014
|
|
|
825
|
-
// Layout: depth of the longest path from the entry
|
|
1015
|
+
// Layout: depth of the longest path from the entry (ignoring controlled loop back-edges).
|
|
826
1016
|
const depth = new Map(nodes.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
|
|
827
1017
|
for (let pass = 0; pass < nodes.length; pass += 1) {
|
|
828
1018
|
let changed = false;
|
|
829
|
-
for (const e of edges) {
|
|
1019
|
+
for (const e of forwardEdgesOf(edges)) {
|
|
830
1020
|
if (e.to === 'lead') continue;
|
|
831
1021
|
const next = Math.min(nodes.length, depth.get(e.from) + 1);
|
|
832
1022
|
if (next > depth.get(e.to)) { depth.set(e.to, next); changed = true; }
|
|
@@ -869,6 +1059,7 @@ function applyPatch(plan, args) {
|
|
|
869
1059
|
if (patch[key] !== undefined) existing[key] = patch[key];
|
|
870
1060
|
}
|
|
871
1061
|
if (patch.kind !== undefined) existing.kind = normalizeKind(patch.kind);
|
|
1062
|
+
if (existing.kind === 'condition') existing.preset = 'minimal';
|
|
872
1063
|
if (patch.branches !== undefined) {
|
|
873
1064
|
const nb = normalizeBranches(patch.branches);
|
|
874
1065
|
if (nb) existing.branches = nb;
|
|
@@ -895,7 +1086,7 @@ function applyPatch(plan, args) {
|
|
|
895
1086
|
for (const key of ALLOWED) {
|
|
896
1087
|
if (patch[key] !== undefined) created[key] = patch[key];
|
|
897
1088
|
}
|
|
898
|
-
created.preset = created.preset === 'minimal' ? 'minimal' : 'standard';
|
|
1089
|
+
created.preset = (created.kind === 'condition' || created.preset === 'minimal') ? 'minimal' : 'standard';
|
|
899
1090
|
if (created.kind === 'condition' && patch.branches !== undefined) {
|
|
900
1091
|
const nb = normalizeBranches(patch.branches);
|
|
901
1092
|
if (nb) created.branches = nb;
|
|
@@ -935,9 +1126,23 @@ function applyPatch(plan, args) {
|
|
|
935
1126
|
if (!validFrom || !validTo) continue;
|
|
936
1127
|
const type = ['prompt', 'structured', 'session-ref'].includes(edge.type) ? edge.type : 'prompt';
|
|
937
1128
|
const branch = normalizeBranch(edge.branch);
|
|
938
|
-
|
|
1129
|
+
const existingEdge = edges.find((e) => e.from === edge.from && e.to === edge.to && e.type === type && normalizeBranch(e.branch) === branch);
|
|
1130
|
+
if (existingEdge) {
|
|
1131
|
+
if (edge.loop === true) {
|
|
1132
|
+
existingEdge.loop = true;
|
|
1133
|
+
existingEdge.maxIterations = normalizeMaxIterations(edge.maxIterations !== undefined ? edge.maxIterations : existingEdge.maxIterations);
|
|
1134
|
+
} else if (edge.loop === false) {
|
|
1135
|
+
delete existingEdge.loop;
|
|
1136
|
+
delete existingEdge.maxIterations;
|
|
1137
|
+
}
|
|
1138
|
+
continue;
|
|
1139
|
+
}
|
|
939
1140
|
const nextEdge = { from: edge.from, to: edge.to, type };
|
|
940
1141
|
if (branch) nextEdge.branch = branch;
|
|
1142
|
+
if (edge.loop === true) {
|
|
1143
|
+
nextEdge.loop = true;
|
|
1144
|
+
nextEdge.maxIterations = normalizeMaxIterations(edge.maxIterations);
|
|
1145
|
+
}
|
|
941
1146
|
edges.push(nextEdge);
|
|
942
1147
|
}
|
|
943
1148
|
const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
|
|
@@ -974,9 +1179,18 @@ function applyPatch(plan, args) {
|
|
|
974
1179
|
* resolves a session's root from its header cwd, so the client reads the same
|
|
975
1180
|
* relative path back through the Remote.
|
|
976
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
|
+
|
|
977
1190
|
function publishCanvas(scope, sessionId, canvas) {
|
|
978
1191
|
try {
|
|
979
|
-
const
|
|
1192
|
+
const sessionsSvc = resolveSessionsService(scope);
|
|
1193
|
+
const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
|
|
980
1194
|
const root = live && live.header && live.header.cwd;
|
|
981
1195
|
if (!root) return false;
|
|
982
1196
|
const dir = join(root, '.dsh', 'canvas');
|
|
@@ -996,7 +1210,8 @@ function publishCanvas(scope, sessionId, canvas) {
|
|
|
996
1210
|
function publishRunState(scope, sessionId, runState) {
|
|
997
1211
|
try {
|
|
998
1212
|
if (!sessionId) return false;
|
|
999
|
-
const
|
|
1213
|
+
const sessionsSvc = resolveSessionsService(scope);
|
|
1214
|
+
const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
|
|
1000
1215
|
const root = live && live.header && live.header.cwd;
|
|
1001
1216
|
if (!root) return false;
|
|
1002
1217
|
const dir = join(root, '.dsh', 'canvas');
|
|
@@ -1011,9 +1226,126 @@ function publishRunState(scope, sessionId, runState) {
|
|
|
1011
1226
|
}
|
|
1012
1227
|
}
|
|
1013
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
|
+
|
|
1014
1333
|
async function runPlan(scope, args, exec) {
|
|
1015
1334
|
const agent = exec && exec.agent;
|
|
1016
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
|
+
}
|
|
1017
1349
|
const payload = sid ? canvasBySession.get(sid) : undefined;
|
|
1018
1350
|
if (!payload) return { error: '当前会话还没有画布数据。请在右侧 Workflow 画布点「启用」。' };
|
|
1019
1351
|
if (!payload.enabled) return { error: '画布当前是「已禁用」状态。请在画布上点「启用」后再运行。' };
|
|
@@ -1044,7 +1376,7 @@ function inspectPlan(sid) {
|
|
|
1044
1376
|
provider: String(n.provider || ''),
|
|
1045
1377
|
model: String(n.model || ''),
|
|
1046
1378
|
reasoning: String(n.reasoning || ''),
|
|
1047
|
-
preset: n.preset === 'minimal' ? 'minimal' : 'standard',
|
|
1379
|
+
preset: (normalizeKind(n.kind) === 'condition' || n.preset === 'minimal') ? 'minimal' : 'standard',
|
|
1048
1380
|
keepSession: Boolean(n.keepSession),
|
|
1049
1381
|
structured: Boolean(n.structured),
|
|
1050
1382
|
fallbackModel: String(n.fallbackModel || ''),
|
|
@@ -1067,6 +1399,10 @@ function inspectPlan(sid) {
|
|
|
1067
1399
|
};
|
|
1068
1400
|
const branch = normalizeBranch(e.branch);
|
|
1069
1401
|
if (branch) out.branch = branch;
|
|
1402
|
+
if (e.loop === true) {
|
|
1403
|
+
out.loop = true;
|
|
1404
|
+
out.maxIterations = normalizeMaxIterations(e.maxIterations);
|
|
1405
|
+
}
|
|
1070
1406
|
return out;
|
|
1071
1407
|
}) : [];
|
|
1072
1408
|
const planRefs = normalizeRefs(plan.refs);
|
|
@@ -1110,12 +1446,16 @@ function buildActiveCanvasContext(sid) {
|
|
|
1110
1446
|
const runState = runBySession.get(String(sid));
|
|
1111
1447
|
if (runState && runState.waitingLead) {
|
|
1112
1448
|
const wl = runState.waitingLead;
|
|
1449
|
+
const loopHint = wl.loopFeedback
|
|
1450
|
+
? ('(↺ 第 ' + wl.loopFeedback.retry + '/' + wl.loopFeedback.max + ' 次回环修正,打回理由:' + (wl.loopFeedback.reason || '未达预期') + ')')
|
|
1451
|
+
: '';
|
|
1113
1452
|
return [
|
|
1114
1453
|
'[Workflow Canvas Active — Paused at Lead Step]',
|
|
1115
|
-
'当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + '
|
|
1454
|
+
'当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')' + loopHint + '。',
|
|
1116
1455
|
'- 若用户的当前消息是在拍板、确认、补充决策或要求继续:请整理决策结论并直接调用 `canvas_workflow({ leadResult: "..." })` 恢复下游节点运行。',
|
|
1456
|
+
'- 若用户要求取消、结束或终止当前工作流:直接调用 `canvas_workflow({ cancel: true })` 解除暂停状态。',
|
|
1117
1457
|
'- 若用户要求放弃当前进度从头重跑:调用 `canvas_workflow({ reset: true })`。',
|
|
1118
|
-
'-
|
|
1458
|
+
'- 若用户要求修改画布结构、分工、参考清单、分支或回环:先 `canvas_inspect` 再用 `canvas_patch`。',
|
|
1119
1459
|
].join('\n');
|
|
1120
1460
|
}
|
|
1121
1461
|
|
|
@@ -1124,21 +1464,29 @@ function buildActiveCanvasContext(sid) {
|
|
|
1124
1464
|
.map((n) => (n.kind === 'lead' ? '〔Lead〕' : (n.kind === 'condition' ? '〔条件〕' : '')) + (n.label || n.id))
|
|
1125
1465
|
.join(' → ') + (nodes.length > 8 ? ' …' : '');
|
|
1126
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) || [];
|
|
1127
1469
|
const prefix = String(sid) + '::';
|
|
1128
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);
|
|
1129
1477
|
const lines = [
|
|
1130
1478
|
'[Workflow Canvas Active]',
|
|
1131
|
-
'当前会话的右侧工作流画布处于「●
|
|
1479
|
+
'当前会话的右侧工作流画布处于「● 已启用」状态(' + metaParts.join(';') + ')。',
|
|
1132
1480
|
'- 若用户发出任务请求、布置工作或说「开始 / 执行 / 跑一次」:请直接调用 `canvas_workflow` 按画布编排执行('
|
|
1133
1481
|
+ (hasTask ? '可直接沿用入口总任务;若用户给出了新任务则通过 task 参数传入' : '请将用户的任务内容作为 task 参数传入')
|
|
1134
1482
|
+ '),不要绕过画布直接自己完成。',
|
|
1135
|
-
'-
|
|
1483
|
+
'- 若用户在讨论或要求修改画布结构、模型、分工、参考清单、条件分支、回环或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
|
|
1136
1484
|
'- 仅当用户明确只是闲聊、问无关问题或要求先停用画布时,才无需调用 `canvas_workflow`。',
|
|
1137
1485
|
];
|
|
1138
1486
|
if (hasMemory) {
|
|
1139
1487
|
lines.push('- 本会话已有开启「记忆」节点的历史子代理会话:若用户说「再跑一次 / 换个任务重跑」,请先简短询问用户是保留上次记忆继续(reset: true)还是清空记忆全新开跑(reset: true, clearMemory: true)。');
|
|
1140
1488
|
}
|
|
1141
|
-
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;
|
|
1142
1490
|
if (stdCount >= 2) {
|
|
1143
1491
|
lines.push('- 本画布包含 ' + stdCount + ' 个可写/命令型(standard)子代理,受主对话权限上限约束;若任务涉及改代码、写文件或跑终端命令且当前主对话权限偏严格,请先简短提醒用户放开主对话权限再调 `canvas_workflow`,避免中途报错白耗额度。');
|
|
1144
1492
|
}
|
|
@@ -1171,6 +1519,17 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1171
1519
|
const opts = args || {};
|
|
1172
1520
|
const agent = exec && exec.agent;
|
|
1173
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
|
+
}
|
|
1174
1533
|
if (!plan || !Array.isArray(plan.nodes) || !plan.nodes.length) {
|
|
1175
1534
|
return { error: '画布没有可执行的节点。' };
|
|
1176
1535
|
}
|
|
@@ -1187,6 +1546,8 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1187
1546
|
|
|
1188
1547
|
const order = orderNodes(plan);
|
|
1189
1548
|
if (!order) return { error: '存在环,无法执行有向无环图。' };
|
|
1549
|
+
const loopErrors = validateLoopEdges(plan.nodes, plan.edges);
|
|
1550
|
+
if (loopErrors.length) return { error: '回环配置无效:' + loopErrors[0] };
|
|
1190
1551
|
|
|
1191
1552
|
// Defense in depth: unreachable orphans, solo chained Leads, and dangling
|
|
1192
1553
|
// dead-end subagents are skipped instead of wasting tokens or stalling.
|
|
@@ -1234,11 +1595,18 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1234
1595
|
pruned: new Set(Array.from(base.pruned || []).filter((id) => byId.has(id))),
|
|
1235
1596
|
decisions: { ...(base.decisions || {}) },
|
|
1236
1597
|
fallbackLinks: Array.isArray(base.fallbackLinks) ? base.fallbackLinks.map((fl) => ({ ...fl })) : [],
|
|
1598
|
+
loopCounts: {},
|
|
1599
|
+
totalLoops: 0,
|
|
1600
|
+
loopHistory: {},
|
|
1601
|
+
loopFeedback: {},
|
|
1602
|
+
nodeAttempts: {},
|
|
1603
|
+
loopWarmChild: {},
|
|
1604
|
+
loopExhausted: [],
|
|
1237
1605
|
waitingLead: null,
|
|
1238
1606
|
};
|
|
1239
1607
|
// Build forward adjacency to invalidate seed nodes and all their downstream dependents.
|
|
1240
1608
|
const fwd = new Map();
|
|
1241
|
-
for (const e of plan.edges || []) {
|
|
1609
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1242
1610
|
if (!e || !e.from || !e.to) continue;
|
|
1243
1611
|
if (!fwd.has(e.from)) fwd.set(e.from, []);
|
|
1244
1612
|
fwd.get(e.from).push(e.to);
|
|
@@ -1293,6 +1661,13 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1293
1661
|
pruned: new Set(),
|
|
1294
1662
|
decisions: {},
|
|
1295
1663
|
fallbackLinks: [],
|
|
1664
|
+
loopCounts: {},
|
|
1665
|
+
totalLoops: 0,
|
|
1666
|
+
loopHistory: {},
|
|
1667
|
+
loopFeedback: {},
|
|
1668
|
+
nodeAttempts: {},
|
|
1669
|
+
loopWarmChild: {},
|
|
1670
|
+
loopExhausted: [],
|
|
1296
1671
|
waitingLead: null,
|
|
1297
1672
|
};
|
|
1298
1673
|
runBySession.set(sid, state);
|
|
@@ -1302,15 +1677,32 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1302
1677
|
if (!state.pruned) state.pruned = new Set();
|
|
1303
1678
|
if (!state.decisions) state.decisions = {};
|
|
1304
1679
|
if (!state.fallbackLinks) state.fallbackLinks = [];
|
|
1680
|
+
if (!state.loopCounts) state.loopCounts = {};
|
|
1681
|
+
if (typeof state.totalLoops !== 'number') state.totalLoops = 0;
|
|
1682
|
+
if (!state.loopHistory) state.loopHistory = {};
|
|
1683
|
+
if (!state.loopFeedback) state.loopFeedback = {};
|
|
1684
|
+
if (!state.nodeAttempts) state.nodeAttempts = {};
|
|
1685
|
+
if (!state.loopWarmChild) state.loopWarmChild = {};
|
|
1686
|
+
if (!state.loopExhausted) state.loopExhausted = [];
|
|
1305
1687
|
|
|
1306
1688
|
const emitRunState = (status, waitingLead) => {
|
|
1307
1689
|
if (!sid) return;
|
|
1690
|
+
const loopCounts = {};
|
|
1691
|
+
for (const e of plan.edges || []) {
|
|
1692
|
+
if (!isLoopEdge(e)) continue;
|
|
1693
|
+
const k = edgeKey(e);
|
|
1694
|
+
const entry = { count: state.loopCounts[k] || 0, max: normalizeMaxIterations(e.maxIterations) };
|
|
1695
|
+
loopCounts[k] = entry;
|
|
1696
|
+
if (e.id) loopCounts[e.id] = entry;
|
|
1697
|
+
}
|
|
1308
1698
|
publishRunState(scope, sid, {
|
|
1309
1699
|
status,
|
|
1310
1700
|
done: Array.from(state.done || []),
|
|
1311
1701
|
decisions: { ...state.decisions },
|
|
1312
1702
|
pruned: Array.from(state.pruned || []),
|
|
1313
1703
|
blockedEdges: Array.from(state.blockedEdges || []),
|
|
1704
|
+
loopCounts,
|
|
1705
|
+
nodeAttempts: { ...state.nodeAttempts },
|
|
1314
1706
|
waitingLead: waitingLead ? { id: waitingLead.id, label: waitingLead.label } : null,
|
|
1315
1707
|
});
|
|
1316
1708
|
};
|
|
@@ -1334,7 +1726,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1334
1726
|
};
|
|
1335
1727
|
const depsOf = (node) => {
|
|
1336
1728
|
const out = new Set();
|
|
1337
|
-
for (const e of plan.edges || []) {
|
|
1729
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1338
1730
|
if (e.to === node.id
|
|
1339
1731
|
&& e.from !== 'lead'
|
|
1340
1732
|
&& !state.blockedEdges.has(edgeKey(e))
|
|
@@ -1350,7 +1742,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1350
1742
|
};
|
|
1351
1743
|
const nearestDownstreamLead = (startId) => {
|
|
1352
1744
|
const fwd = new Map();
|
|
1353
|
-
for (const e of plan.edges || []) {
|
|
1745
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1354
1746
|
if (!e || !e.from || !e.to) continue;
|
|
1355
1747
|
if (!fwd.has(e.from)) fwd.set(e.from, []);
|
|
1356
1748
|
fwd.get(e.from).push(e.to);
|
|
@@ -1374,7 +1766,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1374
1766
|
const branchSkippedList = () => Array.from(state.pruned).map((id) => labelOf.get(id) || id);
|
|
1375
1767
|
const ancestorsOf = (targetId) => {
|
|
1376
1768
|
const parents = new Map();
|
|
1377
|
-
for (const e of plan.edges || []) {
|
|
1769
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1378
1770
|
if (!e || !e.from || !e.to) continue;
|
|
1379
1771
|
if (!parents.has(e.to)) parents.set(e.to, []);
|
|
1380
1772
|
parents.get(e.to).push(e.from);
|
|
@@ -1390,12 +1782,13 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1390
1782
|
return seen;
|
|
1391
1783
|
};
|
|
1392
1784
|
const recomputeBranchPrune = () => {
|
|
1393
|
-
// Re-evaluate reachability from entry Lead over non-blocked edges so diamond
|
|
1785
|
+
// Re-evaluate reachability from entry Lead over non-blocked forward edges so diamond
|
|
1394
1786
|
// convergence nodes stay active, while side-channel edges from ancestors of a
|
|
1395
1787
|
// condition node (e.g. A --session-ref--> N) cannot bypass a blocked branch gate.
|
|
1788
|
+
const fwdEdges = forwardEdgesOf(plan.edges || []);
|
|
1396
1789
|
const condAncestors = new Map();
|
|
1397
1790
|
const blockedSources = new Map();
|
|
1398
|
-
for (const e of
|
|
1791
|
+
for (const e of fwdEdges) {
|
|
1399
1792
|
if (!e || !e.from || !e.to) continue;
|
|
1400
1793
|
if (!state.blockedEdges.has(edgeKey(e))) continue;
|
|
1401
1794
|
if (!blockedSources.has(e.to)) blockedSources.set(e.to, new Set());
|
|
@@ -1431,7 +1824,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1431
1824
|
|
|
1432
1825
|
for (let pass = 0; pass <= runnable.length; pass += 1) {
|
|
1433
1826
|
const adj = new Map();
|
|
1434
|
-
for (const e of
|
|
1827
|
+
for (const e of fwdEdges) {
|
|
1435
1828
|
if (!e || !e.from || !e.to) continue;
|
|
1436
1829
|
if (state.blockedEdges.has(edgeKey(e))) continue;
|
|
1437
1830
|
if (state.pruned.has(e.from)) continue;
|
|
@@ -1460,7 +1853,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1460
1853
|
addedAny = true;
|
|
1461
1854
|
const gates = gatedBy.get(n.id);
|
|
1462
1855
|
if (gates && gates.size) {
|
|
1463
|
-
for (const e of
|
|
1856
|
+
for (const e of fwdEdges) {
|
|
1464
1857
|
if (e && e.from === n.id && e.to) addGates(e.to, gates);
|
|
1465
1858
|
}
|
|
1466
1859
|
}
|
|
@@ -1479,7 +1872,56 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1479
1872
|
// downstream agents start immediately instead of waiting for slower siblings.
|
|
1480
1873
|
const inFlight = new Map();
|
|
1481
1874
|
|
|
1482
|
-
const
|
|
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
|
+
};
|
|
1483
1925
|
const permBlocked = [];
|
|
1484
1926
|
let activationFailCount = 0;
|
|
1485
1927
|
let haltedReason = '';
|
|
@@ -1492,7 +1934,11 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1492
1934
|
&& depsOf(n).every((id) => state.done.has(id)));
|
|
1493
1935
|
for (const node of candidates) {
|
|
1494
1936
|
if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) break;
|
|
1495
|
-
const
|
|
1937
|
+
const fb = state.loopFeedback[node.id] || null;
|
|
1938
|
+
const warmChildId = (fb && state.loopWarmChild[node.id]) ? state.loopWarmChild[node.id] : '';
|
|
1939
|
+
const loopCtx = fb ? { feedback: fb, warmChildId } : undefined;
|
|
1940
|
+
if (fb) delete state.loopFeedback[node.id];
|
|
1941
|
+
const promise = spawnNode(scope, plan, node, state.results, agent, runSignal, sid, state.failed, state.pruned, loopCtx)
|
|
1496
1942
|
.then(
|
|
1497
1943
|
(outcome) => ({ node, outcome }),
|
|
1498
1944
|
(err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
|
|
@@ -1501,11 +1947,10 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1501
1947
|
}
|
|
1502
1948
|
};
|
|
1503
1949
|
|
|
1950
|
+
try {
|
|
1504
1951
|
for (;;) {
|
|
1505
1952
|
if (isAborted()) {
|
|
1506
|
-
|
|
1507
|
-
if (sid) runBySession.delete(sid);
|
|
1508
|
-
return { error: '工作流执行已取消。' };
|
|
1953
|
+
return finishAborted();
|
|
1509
1954
|
}
|
|
1510
1955
|
// On circuit-break halt, stop launching new downstream waves immediately,
|
|
1511
1956
|
// but let already in-flight siblings settle so no orphan promises or partial
|
|
@@ -1524,6 +1969,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1524
1969
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1525
1970
|
decisions: Object.values(state.decisions),
|
|
1526
1971
|
branchSkipped: branchSkippedList(),
|
|
1972
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1527
1973
|
reused,
|
|
1528
1974
|
skipped,
|
|
1529
1975
|
};
|
|
@@ -1542,6 +1988,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1542
1988
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1543
1989
|
decisions: Object.values(state.decisions),
|
|
1544
1990
|
branchSkipped: branchSkippedList(),
|
|
1991
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1545
1992
|
reused,
|
|
1546
1993
|
skipped,
|
|
1547
1994
|
};
|
|
@@ -1550,13 +1997,12 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1550
1997
|
launchReadyAgents();
|
|
1551
1998
|
|
|
1552
1999
|
if (inFlight.size > 0) {
|
|
1553
|
-
const
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
emitRunState('halted', null);
|
|
1557
|
-
if (sid) runBySession.delete(sid);
|
|
1558
|
-
return { error: '工作流执行已取消。' };
|
|
2000
|
+
const raceHit = await Promise.race([...inFlight.values(), abortPromise]);
|
|
2001
|
+
if ((raceHit && raceHit.__aborted) || isAborted()) {
|
|
2002
|
+
return finishAborted();
|
|
1559
2003
|
}
|
|
2004
|
+
const { node, outcome } = raceHit;
|
|
2005
|
+
inFlight.delete(node.id);
|
|
1560
2006
|
state.labels[node.id] = node.label;
|
|
1561
2007
|
if (node.kind === 'condition') {
|
|
1562
2008
|
const { branches, isDefaultBinary } = conditionBranches(node);
|
|
@@ -1626,8 +2072,130 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1626
2072
|
+ (reason ? ' ' + reason : '');
|
|
1627
2073
|
state.done.add(node.id);
|
|
1628
2074
|
const matchedSet = new Set(matchedIds);
|
|
1629
|
-
|
|
1630
|
-
|
|
2075
|
+
const outEdges = (plan.edges || []).filter((e) => e && e.from === node.id);
|
|
2076
|
+
const matchedEdges = outEdges.filter((e) => {
|
|
2077
|
+
const edgeBranch = normalizeBranch(e.branch) || branches[0].id;
|
|
2078
|
+
return matchedSet.has(edgeBranch);
|
|
2079
|
+
});
|
|
2080
|
+
const matchedLoopEdges = matchedEdges.filter((e) => isLoopEdge(e));
|
|
2081
|
+
const matchedForwardEdges = matchedEdges.filter((e) => !isLoopEdge(e));
|
|
2082
|
+
|
|
2083
|
+
if (matchedLoopEdges.length > 0) {
|
|
2084
|
+
// Loop priority: when a condition matches a controlled loop back-edge,
|
|
2085
|
+
// execute the retry reset (if within bounds) instead of advancing forward branches.
|
|
2086
|
+
const le = matchedLoopEdges[0];
|
|
2087
|
+
const leKey = edgeKey(le);
|
|
2088
|
+
const maxIter = normalizeMaxIterations(le.maxIterations);
|
|
2089
|
+
const used = state.loopCounts[leKey] || 0;
|
|
2090
|
+
const members = loopMemberIds(runnable, plan.edges, le);
|
|
2091
|
+
if (!state.loopHistory[leKey]) state.loopHistory[leKey] = [];
|
|
2092
|
+
state.loopHistory[leKey].push({
|
|
2093
|
+
round: used + 1,
|
|
2094
|
+
reason: reason || '未达预期',
|
|
2095
|
+
sourceLabel: node.label,
|
|
2096
|
+
targetLabel: labelOf.get(le.to) || le.to,
|
|
2097
|
+
});
|
|
2098
|
+
if (used < maxIter && state.totalLoops < MAX_GLOBAL_LOOPS && members.size > 0) {
|
|
2099
|
+
const summaryLines = [];
|
|
2100
|
+
for (const mid of members) {
|
|
2101
|
+
if (mid === node.id) continue;
|
|
2102
|
+
const rawRes = state.results[mid];
|
|
2103
|
+
if (typeof rawRes === 'string' && rawRes.trim()) {
|
|
2104
|
+
const clipped = rawRes.length > 500 ? rawRes.slice(0, 500) + '…' : rawRes;
|
|
2105
|
+
summaryLines.push('[' + (labelOf.get(mid) || mid) + '] ' + clipped);
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
const nextRetry = used + 1;
|
|
2109
|
+
state.loopCounts[leKey] = nextRetry;
|
|
2110
|
+
state.totalLoops += 1;
|
|
2111
|
+
for (const mid of members) {
|
|
2112
|
+
state.done.delete(mid);
|
|
2113
|
+
state.pruned.delete(mid);
|
|
2114
|
+
delete state.results[mid];
|
|
2115
|
+
delete state.failed[mid];
|
|
2116
|
+
delete state.emptyOutputs[mid];
|
|
2117
|
+
delete state.decisions[mid];
|
|
2118
|
+
state.nodeAttempts[mid] = { retry: nextRetry, max: maxIter };
|
|
2119
|
+
}
|
|
2120
|
+
for (const e of plan.edges || []) {
|
|
2121
|
+
if (e && members.has(e.from)) state.blockedEdges.delete(edgeKey(e));
|
|
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
|
+
}
|
|
2146
|
+
state.fallbackLinks = state.fallbackLinks.filter((fl) => !members.has(fl.from) && !members.has(fl.to));
|
|
2147
|
+
state.loopFeedback[le.to] = {
|
|
2148
|
+
retry: nextRetry,
|
|
2149
|
+
max: maxIter,
|
|
2150
|
+
reason: reason || '未达预期',
|
|
2151
|
+
sourceLabel: node.label,
|
|
2152
|
+
lastSummary: summaryLines.join('\n'),
|
|
2153
|
+
};
|
|
2154
|
+
emitRunState('running', null);
|
|
2155
|
+
continue;
|
|
2156
|
+
}
|
|
2157
|
+
// Loop limit reached: stop jumping back and hand off round history to Lead or exit cleanly.
|
|
2158
|
+
const hitGlobalCap = used < maxIter && state.totalLoops >= MAX_GLOBAL_LOOPS;
|
|
2159
|
+
const hist = state.loopHistory[leKey].slice();
|
|
2160
|
+
state.loopExhausted.push({
|
|
2161
|
+
edgeKey: leKey,
|
|
2162
|
+
fromLabel: node.label,
|
|
2163
|
+
toLabel: labelOf.get(le.to) || le.to,
|
|
2164
|
+
iterations: used,
|
|
2165
|
+
maxIterations: maxIter,
|
|
2166
|
+
...(hitGlobalCap ? { globalLimit: MAX_GLOBAL_LOOPS } : {}),
|
|
2167
|
+
history: hist,
|
|
2168
|
+
});
|
|
2169
|
+
state.decisions[node.id].loopExhausted = true;
|
|
2170
|
+
state.results[node.id] += hitGlobalCap
|
|
2171
|
+
? ('(已达全局最大回环上限 ' + MAX_GLOBAL_LOOPS + ' 次,停止回跳)')
|
|
2172
|
+
: ('(已达最大回环重试次数 ' + used + '/' + maxIter + ',停止回跳)');
|
|
2173
|
+
for (const e of outEdges) {
|
|
2174
|
+
const edgeBranch = normalizeBranch(e.branch) || branches[0].id;
|
|
2175
|
+
if (isLoopEdge(e) || !matchedSet.has(edgeBranch)) state.blockedEdges.add(edgeKey(e));
|
|
2176
|
+
}
|
|
2177
|
+
if (matchedForwardEdges.length === 0) {
|
|
2178
|
+
const fallbackLead = nearestDownstreamLead(node.id);
|
|
2179
|
+
if (fallbackLead) {
|
|
2180
|
+
state.fallbackLinks.push({
|
|
2181
|
+
from: node.id,
|
|
2182
|
+
to: fallbackLead.id,
|
|
2183
|
+
label: node.label,
|
|
2184
|
+
loopExhausted: true,
|
|
2185
|
+
iterations: used,
|
|
2186
|
+
maxIterations: maxIter,
|
|
2187
|
+
history: hist,
|
|
2188
|
+
});
|
|
2189
|
+
state.decisions[node.id].fallbackLead = fallbackLead.label;
|
|
2190
|
+
state.results[node.id] += '(已汇总历次反馈转交至最近 Lead「' + fallbackLead.label + '」)';
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
recomputeBranchPrune();
|
|
2194
|
+
emitRunState('running', null);
|
|
2195
|
+
continue;
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
for (const e of outEdges) {
|
|
1631
2199
|
const edgeBranch = normalizeBranch(e.branch) || branches[0].id;
|
|
1632
2200
|
if (!matchedSet.has(edgeBranch)) state.blockedEdges.add(edgeKey(e));
|
|
1633
2201
|
}
|
|
@@ -1648,13 +2216,17 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1648
2216
|
state.results[node.id] = outcome.text;
|
|
1649
2217
|
if (!outcome.ok) {
|
|
1650
2218
|
state.failed[node.id] = { id: node.id, label: node.label, reason: outcome.reason || 'unknown' };
|
|
2219
|
+
delete state.loopWarmChild[node.id];
|
|
1651
2220
|
if (outcome.reason === 'activation-failed') activationFailCount += 1;
|
|
1652
2221
|
} else if (outcome.empty) {
|
|
1653
2222
|
state.emptyOutputs[node.id] = { id: node.id, label: node.label };
|
|
2223
|
+
delete state.loopWarmChild[node.id];
|
|
2224
|
+
} else if (outcome.childId) {
|
|
2225
|
+
state.loopWarmChild[node.id] = outcome.childId;
|
|
1654
2226
|
}
|
|
1655
2227
|
// If a failing node feeds a condition node, let the condition handle failure routing
|
|
1656
2228
|
// instead of circuit-breaking the whole run prematurely.
|
|
1657
|
-
const routesToCondition = (plan.edges || []).some((e) => e && e.from === node.id
|
|
2229
|
+
const routesToCondition = forwardEdgesOf(plan.edges || []).some((e) => e && e.from === node.id
|
|
1658
2230
|
&& byId.get(e.to) && byId.get(e.to).kind === 'condition');
|
|
1659
2231
|
if (!routesToCondition && isPermissionFailure(outcome)) {
|
|
1660
2232
|
permBlocked.push(node.label || node.id);
|
|
@@ -1682,8 +2254,22 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1682
2254
|
}));
|
|
1683
2255
|
const jumpedEntries = (state.fallbackLinks || []).filter((fl) => fl.to === leadNode.id);
|
|
1684
2256
|
const failedConds = jumpedEntries.filter((fl) => fl.failed).map((fl) => (fl.label || labelOf.get(fl.from) || fl.from) + '(' + (fl.reason || 'unknown') + ')');
|
|
1685
|
-
const
|
|
2257
|
+
const exhaustedConds = jumpedEntries.filter((fl) => fl.loopExhausted);
|
|
2258
|
+
const unmatchedConds = jumpedEntries.filter((fl) => !fl.failed && !fl.loopExhausted).map((fl) => fl.label || labelOf.get(fl.from) || fl.from);
|
|
2259
|
+
const leadFb = state.loopFeedback[leadNode.id] || null;
|
|
1686
2260
|
const fallbackParts = [];
|
|
2261
|
+
if (leadFb) {
|
|
2262
|
+
fallbackParts.push('↺ 【第 ' + leadFb.retry + '/' + leadFb.max + ' 次回环修正】下游条件节点「' + (leadFb.sourceLabel || '条件判断') + '」判定未通过,理由:' + (leadFb.reason || '未达预期') + '。请结合最新反馈修正此步骤后再继续。');
|
|
2263
|
+
}
|
|
2264
|
+
if (exhaustedConds.length) {
|
|
2265
|
+
const exLines = exhaustedConds.map((fl) => {
|
|
2266
|
+
const rounds = Array.isArray(fl.history)
|
|
2267
|
+
? fl.history.map((h) => '第' + h.round + '轮:' + h.reason).join(';')
|
|
2268
|
+
: '';
|
|
2269
|
+
return (fl.label || fl.from) + '(已重试 ' + fl.iterations + '/' + fl.maxIterations + ' 次仍未通过' + (rounds ? ' — ' + rounds : '') + ')';
|
|
2270
|
+
});
|
|
2271
|
+
fallbackParts.push('⚠ 回环达到最大次数上限已熔断:' + exLines.join(';') + '。请由你(Lead)审阅历次失败摘要后决定下一步。');
|
|
2272
|
+
}
|
|
1687
2273
|
if (failedConds.length) {
|
|
1688
2274
|
fallbackParts.push('⚠ 条件节点(' + failedConds.join('、') + ')自身执行失败,未擅自选择分支,已跳过中间分支直接转交给你处理;也可调用 canvas_workflow({ retryFailed: true }) 复用上游缓存并只重跑该条件节点及其下游。');
|
|
1689
2275
|
}
|
|
@@ -1691,6 +2277,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1691
2277
|
fallbackParts.push('⚠ 条件节点(' + unmatchedConds.join('、') + ')所有分支均未命中,已跳过中间分支直接转交给你处理。');
|
|
1692
2278
|
}
|
|
1693
2279
|
const fallbackNotice = fallbackParts.join(' ');
|
|
2280
|
+
const mergedLeadRefs = normalizeRefs((normalizeRefs(plan && plan.refs) || []).concat(normalizeRefs(leadNode.refs) || []));
|
|
1694
2281
|
const hasDownstreamWork = remaining.some((n) => n.id !== leadNode.id);
|
|
1695
2282
|
if (!hasDownstreamWork && leadResult === undefined) {
|
|
1696
2283
|
// Terminal Lead: zero downstream nodes remain, so complete the run directly
|
|
@@ -1706,7 +2293,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1706
2293
|
label: leadNode.label,
|
|
1707
2294
|
role: leadNode.role || leadNode.label,
|
|
1708
2295
|
needs: depsOf(leadNode).map((id) => byId.get(id).label),
|
|
1709
|
-
...(
|
|
2296
|
+
...(mergedLeadRefs ? { refs: mergedLeadRefs } : {}),
|
|
1710
2297
|
},
|
|
1711
2298
|
results: state.results,
|
|
1712
2299
|
labels: state.labels,
|
|
@@ -1714,6 +2301,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1714
2301
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1715
2302
|
decisions: Object.values(state.decisions),
|
|
1716
2303
|
branchSkipped: branchSkippedList(),
|
|
2304
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1717
2305
|
sessions: leadSessions,
|
|
1718
2306
|
reused,
|
|
1719
2307
|
skipped,
|
|
@@ -1722,10 +2310,14 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1722
2310
|
};
|
|
1723
2311
|
}
|
|
1724
2312
|
if (leadResult === undefined) {
|
|
2313
|
+
const leadFbSummary = leadFb
|
|
2314
|
+
? { retry: leadFb.retry, max: leadFb.max, sourceLabel: leadFb.sourceLabel, reason: leadFb.reason }
|
|
2315
|
+
: null;
|
|
1725
2316
|
state.waitingLead = {
|
|
1726
2317
|
id: leadNode.id,
|
|
1727
2318
|
label: leadNode.label,
|
|
1728
2319
|
role: leadNode.role || leadNode.label,
|
|
2320
|
+
...(leadFbSummary ? { loopFeedback: leadFbSummary } : {}),
|
|
1729
2321
|
};
|
|
1730
2322
|
emitRunState('need-lead', state.waitingLead);
|
|
1731
2323
|
return {
|
|
@@ -1734,7 +2326,8 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1734
2326
|
label: leadNode.label,
|
|
1735
2327
|
role: leadNode.role || leadNode.label,
|
|
1736
2328
|
needs: depsOf(leadNode).map((id) => byId.get(id).label),
|
|
1737
|
-
...(
|
|
2329
|
+
...(mergedLeadRefs ? { refs: mergedLeadRefs } : {}),
|
|
2330
|
+
...(leadFbSummary ? { loopFeedback: leadFbSummary } : {}),
|
|
1738
2331
|
},
|
|
1739
2332
|
results: state.results,
|
|
1740
2333
|
labels: state.labels,
|
|
@@ -1742,22 +2335,32 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1742
2335
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1743
2336
|
decisions: Object.values(state.decisions),
|
|
1744
2337
|
branchSkipped: branchSkippedList(),
|
|
2338
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1745
2339
|
sessions: leadSessions,
|
|
1746
2340
|
hint: (fallbackNotice ? fallbackNotice + ' ' : '')
|
|
1747
|
-
+ '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult
|
|
2341
|
+
+ '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需取消本次流程可传 cancel: true,若需从头重跑可传 reset: true。',
|
|
1748
2342
|
};
|
|
1749
2343
|
}
|
|
1750
2344
|
state.waitingLead = null;
|
|
2345
|
+
delete state.loopFeedback[leadNode.id];
|
|
1751
2346
|
state.results[leadNode.id] = leadResult;
|
|
1752
2347
|
state.labels[leadNode.id] = leadNode.label;
|
|
1753
2348
|
state.done.add(leadNode.id);
|
|
1754
2349
|
leadResult = undefined;
|
|
1755
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
|
+
}
|
|
1756
2359
|
}
|
|
1757
2360
|
|
|
1758
2361
|
/** Agent-facing guide, shipped as a skill so any agent can load it on demand. */
|
|
1759
2362
|
const SKILL_NAME = 'workflow-canvas';
|
|
1760
|
-
const SKILL_DESCRIPTION = 'Workflow canvas (画布 / 工作流 / 编排): inspect, draw, edit or
|
|
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.';
|
|
1761
2364
|
function skillPath() {
|
|
1762
2365
|
try {
|
|
1763
2366
|
return fileURLToPath(new URL('./skills/workflow-canvas/SKILL.md', import.meta.url));
|
|
@@ -1846,6 +2449,21 @@ export function apply(ctx) {
|
|
|
1846
2449
|
}
|
|
1847
2450
|
},
|
|
1848
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');
|
|
1849
2467
|
} catch (_e) {
|
|
1850
2468
|
/* command registry unavailable */
|
|
1851
2469
|
}
|
|
@@ -1908,6 +2526,8 @@ export function apply(ctx) {
|
|
|
1908
2526
|
to: { type: 'string' },
|
|
1909
2527
|
type: { type: 'string', enum: ['prompt', 'structured', 'session-ref'] },
|
|
1910
2528
|
branch: { type: 'string', description: 'For edges leaving a condition node: "true" / "false" (default binary) or one of the condition node branch ids.' },
|
|
2529
|
+
loop: { type: 'boolean', description: 'Optional (condition outgoing edge only): set true to mark a controlled retry back-edge pointing to a strict ancestor node.' },
|
|
2530
|
+
maxIterations: { type: 'integer', minimum: 1, maximum: 10, description: 'Optional (loop edges only): max retry loops before circuit-breaking (1–10, default 3).' },
|
|
1911
2531
|
},
|
|
1912
2532
|
required: ['from', 'to'],
|
|
1913
2533
|
},
|
|
@@ -2097,6 +2717,9 @@ export function apply(ctx) {
|
|
|
2097
2717
|
'画布状态:' + (v.enabled ? '● 已启用' : '○ 已禁用') + (v.paused ? '(当前暂停在 Lead 步骤)' : ''),
|
|
2098
2718
|
'总任务:' + (v.task || '(未填写,运行时可通过 task 参数指定)'),
|
|
2099
2719
|
];
|
|
2720
|
+
if (Array.isArray(v.refs) && v.refs.length) {
|
|
2721
|
+
head.push('全局参考:' + v.refs.join(';'));
|
|
2722
|
+
}
|
|
2100
2723
|
if (v.error) head.push('校验错误:' + v.error);
|
|
2101
2724
|
const warnBlock = Array.isArray(v.warnings) && v.warnings.length
|
|
2102
2725
|
? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
|
|
@@ -2121,7 +2744,9 @@ export function apply(ctx) {
|
|
|
2121
2744
|
+ (n.role ? ':' + n.role : '');
|
|
2122
2745
|
});
|
|
2123
2746
|
const edgeLines = (v.edges || []).map((e) => '- ' + e.from
|
|
2124
|
-
+ ' --(' + e.type + (e.branch ? ':' + e.branch : '')
|
|
2747
|
+
+ ' --(' + e.type + (e.branch ? ':' + e.branch : '')
|
|
2748
|
+
+ (e.loop ? ', ↺ loop ×' + normalizeMaxIterations(e.maxIterations) : '')
|
|
2749
|
+
+ ')--> ' + e.to);
|
|
2125
2750
|
return [{
|
|
2126
2751
|
type: 'text',
|
|
2127
2752
|
text: head.join('\n')
|
|
@@ -2142,16 +2767,17 @@ export function apply(ctx) {
|
|
|
2142
2767
|
}
|
|
2143
2768
|
});
|
|
2144
2769
|
|
|
2145
|
-
ctx.inject(['tools', 'subagents'], (scope) => {
|
|
2770
|
+
ctx.inject(['tools', 'subagents', 'sessions'], (scope) => {
|
|
2146
2771
|
try {
|
|
2147
2772
|
scope.effect(() => scope.tools.register({
|
|
2148
2773
|
name: 'canvas_workflow',
|
|
2149
|
-
description: 'Run the workflow canvas of the current session. Executes subagent nodes in parallel waves
|
|
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.',
|
|
2150
2775
|
parameters: {
|
|
2151
2776
|
type: 'object',
|
|
2152
2777
|
properties: {
|
|
2153
2778
|
leadResult: { type: 'string', description: 'Your own output for the Lead step that was just requested.' },
|
|
2154
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.' },
|
|
2155
2781
|
reset: { type: 'boolean', description: 'Discard any paused run progress and start from the beginning.' },
|
|
2156
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.' },
|
|
2157
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.' },
|
|
@@ -2173,6 +2799,7 @@ export function apply(ctx) {
|
|
|
2173
2799
|
emptyOutputs: { type: 'array' },
|
|
2174
2800
|
decisions: { type: 'array' },
|
|
2175
2801
|
branchSkipped: { type: 'array' },
|
|
2802
|
+
loopExhausted: { type: 'array' },
|
|
2176
2803
|
sessions: { type: 'array' },
|
|
2177
2804
|
reused: { type: 'array' },
|
|
2178
2805
|
skipped: { type: 'array' },
|
|
@@ -2183,6 +2810,7 @@ export function apply(ctx) {
|
|
|
2183
2810
|
render: (_args, value) => {
|
|
2184
2811
|
const v = value || {};
|
|
2185
2812
|
if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
|
|
2813
|
+
if (v.status === 'cancelled') return [{ type: 'text', text: v.hint || '已终止当前工作流执行。' }];
|
|
2186
2814
|
const results = v.results || {};
|
|
2187
2815
|
const labels = v.labels || {};
|
|
2188
2816
|
const blocks = Object.keys(results).map((id) => {
|
|
@@ -2217,8 +2845,14 @@ export function apply(ctx) {
|
|
|
2217
2845
|
const branchSkipNote = Array.isArray(v.branchSkipped) && v.branchSkipped.length
|
|
2218
2846
|
? '\n\n条件未命中已跳过:' + v.branchSkipped.join('、')
|
|
2219
2847
|
: '';
|
|
2848
|
+
const loopExNote = Array.isArray(v.loopExhausted) && v.loopExhausted.length
|
|
2849
|
+
? '\n\n⚠ 回环达上限熔断:' + v.loopExhausted.map((lx) => (lx.fromLabel || lx.edgeKey) + ' ↺ ' + (lx.toLabel || '') + '(' + lx.iterations + '/' + lx.maxIterations + ')').join(';')
|
|
2850
|
+
: '';
|
|
2220
2851
|
if (v.status === 'need-lead') {
|
|
2221
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
|
+
: '';
|
|
2222
2856
|
const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
|
|
2223
2857
|
const handover = handed.length
|
|
2224
2858
|
? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
|
|
@@ -2228,12 +2862,14 @@ export function apply(ctx) {
|
|
|
2228
2862
|
type: 'text',
|
|
2229
2863
|
text: '需要你(Lead)完成「' + n.label + '」:' + n.role
|
|
2230
2864
|
+ '\n需要用到:' + ((n.needs && n.needs.length) ? n.needs.join('、') : '(无上游)')
|
|
2865
|
+
+ refsBlock
|
|
2231
2866
|
+ decisionList
|
|
2232
2867
|
+ failedList
|
|
2233
2868
|
+ emptyList
|
|
2234
2869
|
+ '\n\n已完成节点的结果:\n' + body
|
|
2235
2870
|
+ handover
|
|
2236
2871
|
+ branchSkipNote
|
|
2872
|
+
+ loopExNote
|
|
2237
2873
|
+ '\n\n' + (v.hint || ''),
|
|
2238
2874
|
}];
|
|
2239
2875
|
}
|
|
@@ -2246,6 +2882,9 @@ export function apply(ctx) {
|
|
|
2246
2882
|
: '';
|
|
2247
2883
|
if (v.finalLead) {
|
|
2248
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
|
+
: '';
|
|
2249
2888
|
const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
|
|
2250
2889
|
const handover = handed.length
|
|
2251
2890
|
? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
|
|
@@ -2255,18 +2894,20 @@ export function apply(ctx) {
|
|
|
2255
2894
|
type: 'text',
|
|
2256
2895
|
text: '所有子代理已完成,现在进入终审 Lead 步骤「' + fl.label + '」:' + fl.role
|
|
2257
2896
|
+ '\n需要用到:' + ((fl.needs && fl.needs.length) ? fl.needs.join('、') : '(无上游)')
|
|
2897
|
+
+ refsBlock
|
|
2258
2898
|
+ decisionList
|
|
2259
2899
|
+ failedList
|
|
2260
2900
|
+ emptyList
|
|
2261
2901
|
+ '\n\n已完成节点的结果:\n' + body
|
|
2262
2902
|
+ handover
|
|
2263
2903
|
+ branchSkipNote
|
|
2904
|
+
+ loopExNote
|
|
2264
2905
|
+ reusedNote
|
|
2265
2906
|
+ skip
|
|
2266
2907
|
+ '\n\n' + (v.hint || ''),
|
|
2267
2908
|
}];
|
|
2268
2909
|
}
|
|
2269
|
-
return [{ type: 'text', text: '画布执行完成。' + decisionList + failedList + emptyList + '\n\n' + body + branchSkipNote + reusedNote + skip }];
|
|
2910
|
+
return [{ type: 'text', text: '画布执行完成。' + decisionList + failedList + emptyList + loopExNote + '\n\n' + body + branchSkipNote + reusedNote + skip }];
|
|
2270
2911
|
}
|
|
2271
2912
|
return [{ type: 'text', text: JSON.stringify(v) }];
|
|
2272
2913
|
},
|
|
@@ -2289,6 +2930,9 @@ export {
|
|
|
2289
2930
|
briefFor,
|
|
2290
2931
|
normalizeBranches,
|
|
2291
2932
|
normalizeRefs,
|
|
2933
|
+
normalizeMaxIterations,
|
|
2934
|
+
loopMemberIds,
|
|
2935
|
+
validateLoopEdges,
|
|
2292
2936
|
parseConditionDecision,
|
|
2293
2937
|
withoutEntry,
|
|
2294
2938
|
analyzeCanvasWarnings,
|
|
@@ -2298,6 +2942,7 @@ export {
|
|
|
2298
2942
|
sessionIdFromContext,
|
|
2299
2943
|
buildActiveCanvasContext,
|
|
2300
2944
|
isPermissionFailure,
|
|
2945
|
+
abortSessionRun,
|
|
2301
2946
|
runPlan,
|
|
2302
2947
|
executePlan,
|
|
2303
2948
|
};
|