dsh-workflow-canvas 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -7
- package/README.zh.md +14 -7
- package/client.js +874 -99
- package/docs/DETAIL.md +37 -22
- package/docs/MECHANISM.md +6 -5
- package/docs/MECHANISM.zh.md +6 -5
- package/docs/images/retry-loop-en.png +0 -0
- package/docs/images/retry-loop-zh.png +0 -0
- package/index.js +400 -41
- package/package.json +20 -2
- package/skills/workflow-canvas/SKILL.md +1 -0
package/index.js
CHANGED
|
@@ -90,10 +90,66 @@ function parsePayload(rawInput) {
|
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
-
|
|
93
|
+
const MAX_LOOP_ITERATIONS = 10;
|
|
94
|
+
const DEFAULT_LOOP_ITERATIONS = 3;
|
|
95
|
+
const MAX_GLOBAL_LOOPS = 20;
|
|
96
|
+
|
|
97
|
+
function normalizeMaxIterations(val) {
|
|
98
|
+
const n = Number(val);
|
|
99
|
+
if (!Number.isFinite(n)) return DEFAULT_LOOP_ITERATIONS;
|
|
100
|
+
return Math.max(1, Math.min(MAX_LOOP_ITERATIONS, Math.floor(n)));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isLoopEdge(e) {
|
|
104
|
+
return Boolean(e && e.loop === true);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function forwardEdgesOf(edges) {
|
|
108
|
+
return (Array.isArray(edges) ? edges : []).filter((e) => e && !e.loop);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Compute the set of node ids strictly inside a controlled loop edge (from target -> ... -> source)
|
|
113
|
+
* over forward edges: `descendants(loopEdge.to) ∩ ancestors(loopEdge.from)` (inclusive).
|
|
114
|
+
* Returns an empty Set if `loopEdge.from` is not reachable from `loopEdge.to` over forward edges.
|
|
115
|
+
*/
|
|
116
|
+
function loopMemberIds(nodes, edges, loopEdge) {
|
|
117
|
+
if (!loopEdge || !loopEdge.from || !loopEdge.to || loopEdge.to === 'lead') return new Set();
|
|
118
|
+
const fwd = new Map();
|
|
119
|
+
const rev = new Map();
|
|
120
|
+
for (const e of forwardEdgesOf(edges)) {
|
|
121
|
+
if (!e.from || !e.to) continue;
|
|
122
|
+
if (!fwd.has(e.from)) fwd.set(e.from, []);
|
|
123
|
+
fwd.get(e.from).push(e.to);
|
|
124
|
+
if (!rev.has(e.to)) rev.set(e.to, []);
|
|
125
|
+
rev.get(e.to).push(e.from);
|
|
126
|
+
}
|
|
127
|
+
const desc = new Set([loopEdge.to]);
|
|
128
|
+
const q1 = [loopEdge.to];
|
|
129
|
+
for (let i = 0; i < q1.length; i += 1) {
|
|
130
|
+
for (const next of fwd.get(q1[i]) || []) {
|
|
131
|
+
if (!desc.has(next)) { desc.add(next); q1.push(next); }
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (!desc.has(loopEdge.from)) return new Set();
|
|
135
|
+
const anc = new Set([loopEdge.from]);
|
|
136
|
+
const q2 = [loopEdge.from];
|
|
137
|
+
for (let i = 0; i < q2.length; i += 1) {
|
|
138
|
+
for (const prev of rev.get(q2[i]) || []) {
|
|
139
|
+
if (!anc.has(prev)) { anc.add(prev); q2.push(prev); }
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const members = new Set();
|
|
143
|
+
for (const id of desc) {
|
|
144
|
+
if (anc.has(id)) members.add(id);
|
|
145
|
+
}
|
|
146
|
+
return members;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Kahn topological order over every plan node (ignoring controlled loop back-edges). */
|
|
94
150
|
function orderNodes(plan) {
|
|
95
151
|
const nodes = plan.nodes || [];
|
|
96
|
-
const edges = plan.edges || [];
|
|
152
|
+
const edges = forwardEdgesOf(plan.edges || []);
|
|
97
153
|
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
98
154
|
const indeg = new Map(nodes.map((n) => [n.id, 0]));
|
|
99
155
|
const adj = new Map(nodes.map((n) => [n.id, []]));
|
|
@@ -118,7 +174,7 @@ function orderNodes(plan) {
|
|
|
118
174
|
|
|
119
175
|
function upstreamOf(plan, node) {
|
|
120
176
|
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
121
|
-
return (plan.edges || [])
|
|
177
|
+
return forwardEdgesOf(plan.edges || [])
|
|
122
178
|
.filter((e) => e.to === node.id)
|
|
123
179
|
.map((e) => ({ edge: e, from: byId.get(e.from) }))
|
|
124
180
|
.filter((x) => x.from);
|
|
@@ -126,7 +182,7 @@ function upstreamOf(plan, node) {
|
|
|
126
182
|
|
|
127
183
|
function downstreamLabels(plan, node) {
|
|
128
184
|
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
129
|
-
return (plan.edges || [])
|
|
185
|
+
return forwardEdgesOf(plan.edges || [])
|
|
130
186
|
.filter((e) => e.from === node.id)
|
|
131
187
|
.map((e) => (byId.get(e.to) || {}).label)
|
|
132
188
|
.filter(Boolean);
|
|
@@ -312,7 +368,7 @@ function parseConditionDecision(result, fallbackText, nodeOrBranches) {
|
|
|
312
368
|
return makeDecision(matched, raw.slice(0, 200) || (matched.length ? '' : '未命中任何分支,已跳过后续分支'));
|
|
313
369
|
}
|
|
314
370
|
|
|
315
|
-
function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
371
|
+
function briefFor(plan, node, results, failedMap, prunedSet, loopCtx) {
|
|
316
372
|
const ups = upstreamOf(plan, node).filter((u) => !(prunedSet && prunedSet.has(u.from.id)));
|
|
317
373
|
const downs = downstreamLabels(plan, node);
|
|
318
374
|
const head = [];
|
|
@@ -320,11 +376,15 @@ function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
|
320
376
|
const outEdges = (plan.edges || []).filter((e) => e.from === node.id);
|
|
321
377
|
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
322
378
|
const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
|
|
379
|
+
const fmtTarget = (e) => {
|
|
380
|
+
const lbl = (byId.get(e.to) || {}).label || e.to;
|
|
381
|
+
return e.loop ? (lbl + '(↺ 回环重做,最多 ' + normalizeMaxIterations(e.maxIterations) + ' 次)') : lbl;
|
|
382
|
+
};
|
|
323
383
|
head.push('【工作流条件判断节点】你负责判断当前工作流接下来走哪条分支(「' + node.label + '」)。');
|
|
324
384
|
head.push('【总任务】' + plan.task);
|
|
325
385
|
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(
|
|
386
|
+
const yesTargets = outEdges.filter((e) => (normalizeBranch(e.branch) || 'true') === 'true').map(fmtTarget);
|
|
387
|
+
const noTargets = outEdges.filter((e) => normalizeBranch(e.branch) === 'false').map(fmtTarget);
|
|
328
388
|
head.push('【判断条件】' + (node.role || '判断上游步骤是否执行成功并达到预期;成功返回 true,失败或未达标返回 false。'));
|
|
329
389
|
head.push('【分支去向】pass=true(是)→ ' + (yesTargets.join('、') || '(无)') + ';pass=false(否)→ ' + (noTargets.join('、') || '(无)'));
|
|
330
390
|
head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"pass": true/false, "reason": "一句话理由"}。');
|
|
@@ -335,7 +395,7 @@ function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
|
335
395
|
const eb = normalizeBranch(e.branch);
|
|
336
396
|
return eb ? eb === b.id : idx === 0;
|
|
337
397
|
})
|
|
338
|
-
.map(
|
|
398
|
+
.map(fmtTarget);
|
|
339
399
|
const tag = b.label === b.id ? '"' + b.id + '"' : '"' + b.id + '"(' + b.label + ')';
|
|
340
400
|
return '- ' + tag + ' → ' + (targets.join('、') || '(无下游)');
|
|
341
401
|
});
|
|
@@ -364,6 +424,15 @@ function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
|
364
424
|
if (mergedRefs.length) {
|
|
365
425
|
head.push('【参考资料 / 约束】\n' + mergedRefs.map((r) => '- ' + r).join('\n'));
|
|
366
426
|
}
|
|
427
|
+
if (loopCtx && loopCtx.feedback) {
|
|
428
|
+
const fb = loopCtx.feedback;
|
|
429
|
+
const lines = [
|
|
430
|
+
'【第 ' + fb.retry + '/' + fb.max + ' 次回环修正反馈】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请针对以下问题修正后输出最新结果:',
|
|
431
|
+
'- 打回理由:' + (fb.reason || '未达预期'),
|
|
432
|
+
];
|
|
433
|
+
if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
|
|
434
|
+
head.push(lines.join('\n'));
|
|
435
|
+
}
|
|
367
436
|
let text = head.join('\n') + '\n';
|
|
368
437
|
for (const u of ups) {
|
|
369
438
|
const value = results[u.from.id];
|
|
@@ -412,13 +481,29 @@ function isEmptyOutput(result) {
|
|
|
412
481
|
return text.trim().length === 0;
|
|
413
482
|
}
|
|
414
483
|
|
|
415
|
-
|
|
484
|
+
function buildLoopWarmPrompt(node, loopCtx) {
|
|
485
|
+
const fb = loopCtx && loopCtx.feedback;
|
|
486
|
+
if (!fb) return null;
|
|
487
|
+
const lines = [
|
|
488
|
+
'【第 ' + fb.retry + '/' + fb.max + ' 次回环修正】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请结合以下反馈直接在当前会话上下文中修正并输出最新交付结果(无需重复叙述过程):',
|
|
489
|
+
'- 打回理由:' + (fb.reason || '未达预期'),
|
|
490
|
+
];
|
|
491
|
+
if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
|
|
492
|
+
if (node.role) lines.push('- 你的职责提醒:' + node.role);
|
|
493
|
+
return lines.join('\n');
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid, failedMap, prunedSet, loopCtx) {
|
|
416
497
|
const childKey = (id) => String(sid || '') + '::' + id;
|
|
417
498
|
const isCondition = node.kind === 'condition';
|
|
499
|
+
const fullBrief = briefFor(plan, node, results, failedMap, prunedSet, loopCtx);
|
|
500
|
+
const warmPrompt = (!isCondition && loopCtx && loopCtx.warmChildId && loopCtx.feedback)
|
|
501
|
+
? buildLoopWarmPrompt(node, loopCtx)
|
|
502
|
+
: null;
|
|
418
503
|
const spec = {
|
|
419
504
|
provider: 'spawn',
|
|
420
505
|
label: node.label + '#' + node.id,
|
|
421
|
-
prompt: [{ type: 'text', text:
|
|
506
|
+
prompt: [{ type: 'text', text: fullBrief }],
|
|
422
507
|
parent,
|
|
423
508
|
signal,
|
|
424
509
|
delivery: 'caller',
|
|
@@ -471,8 +556,11 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
471
556
|
}
|
|
472
557
|
}
|
|
473
558
|
|
|
474
|
-
const run = async (childId) => {
|
|
475
|
-
const
|
|
559
|
+
const run = async (childId, overridePrompt) => {
|
|
560
|
+
const baseSpec = overridePrompt
|
|
561
|
+
? { ...spec, prompt: [{ type: 'text', text: overridePrompt }] }
|
|
562
|
+
: spec;
|
|
563
|
+
const withChild = childId ? { ...baseSpec, childId } : baseSpec;
|
|
476
564
|
let activation;
|
|
477
565
|
try {
|
|
478
566
|
activation = await scope.subagents.startActivation(withChild);
|
|
@@ -511,6 +599,20 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
511
599
|
}
|
|
512
600
|
};
|
|
513
601
|
|
|
602
|
+
// On a controlled loop retry where the previous run of this node was healthy,
|
|
603
|
+
// resume its warm child session with a concise incremental correction prompt.
|
|
604
|
+
if (warmPrompt && loopCtx && loopCtx.warmChildId && !forcedChild) {
|
|
605
|
+
const continued = await run(loopCtx.warmChildId, warmPrompt);
|
|
606
|
+
if (continued.ok) {
|
|
607
|
+
liveChild.set(childKey(node.id), continued.childId || loopCtx.warmChildId);
|
|
608
|
+
return continued;
|
|
609
|
+
}
|
|
610
|
+
if (continued.reason !== 'activation-failed') {
|
|
611
|
+
return continued;
|
|
612
|
+
}
|
|
613
|
+
/* warm session refused: fall through to a fresh session with the full brief + feedback */
|
|
614
|
+
}
|
|
615
|
+
|
|
514
616
|
// A `session` edge means "continue the upstream node's conversation": run this
|
|
515
617
|
// step inside that child session instead of starting a fresh one.
|
|
516
618
|
if (forcedChild) {
|
|
@@ -552,15 +654,15 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
552
654
|
return started;
|
|
553
655
|
}
|
|
554
656
|
|
|
555
|
-
async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet) {
|
|
556
|
-
const continueFrom = (plan.edges || [])
|
|
657
|
+
async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet, loopCtx) {
|
|
658
|
+
const continueFrom = forwardEdgesOf(plan.edges || [])
|
|
557
659
|
.filter((e) => e.to === node.id && e.type === 'session-ref' && !(prunedSet && prunedSet.has(e.from)))
|
|
558
660
|
.map((e) => liveChild.get(String(sid || '') + '::' + e.from)
|
|
559
661
|
|| childByNode.get(String(sid || '') + '::' + e.from))
|
|
560
662
|
.find((id) => typeof id === 'string');
|
|
561
663
|
|
|
562
664
|
if (continueFrom) {
|
|
563
|
-
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet);
|
|
665
|
+
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet, loopCtx);
|
|
564
666
|
if (continued.ok) {
|
|
565
667
|
const out = { ok: true, empty: Boolean(continued.empty), text: continued.text + '\n(已在上游会话中继续)', childId: continued.childId || continueFrom };
|
|
566
668
|
if (continued.decision) out.decision = continued.decision;
|
|
@@ -568,7 +670,7 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
568
670
|
}
|
|
569
671
|
}
|
|
570
672
|
|
|
571
|
-
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet);
|
|
673
|
+
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
572
674
|
if (first.ok) {
|
|
573
675
|
const out = { ok: true, empty: Boolean(first.empty), text: first.text, childId: first.childId || '' };
|
|
574
676
|
if (first.decision) out.decision = first.decision;
|
|
@@ -581,7 +683,7 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
581
683
|
const retry = await spawnOnce(scope, plan, node, results, parent, signal, {
|
|
582
684
|
provider: node.fallbackProvider,
|
|
583
685
|
model: node.fallbackModel,
|
|
584
|
-
}, undefined, sid, failedMap, prunedSet);
|
|
686
|
+
}, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
585
687
|
if (retry.ok) {
|
|
586
688
|
const out = { ok: true, empty: Boolean(retry.empty), text: retry.text + '\n(已用备用模型重试成功)', childId: retry.childId || '' };
|
|
587
689
|
if (retry.decision) out.decision = retry.decision;
|
|
@@ -591,10 +693,10 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
591
693
|
return { ok: false, empty: false, reason, text: retry.text + '\n(重试仍失败:' + reason + ')', childId: retry.childId || first.childId || '' };
|
|
592
694
|
}
|
|
593
695
|
|
|
594
|
-
/** Ids reachable from the entry Lead via O(V + E) BFS; every other node is skipped at run time. */
|
|
696
|
+
/** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
|
|
595
697
|
function reachableFrom(plan) {
|
|
596
698
|
const adj = new Map();
|
|
597
|
-
for (const e of (plan && plan.edges)
|
|
699
|
+
for (const e of forwardEdgesOf(plan && plan.edges)) {
|
|
598
700
|
if (!e || !e.from || !e.to) continue;
|
|
599
701
|
if (!adj.has(e.from)) adj.set(e.from, []);
|
|
600
702
|
adj.get(e.from).push(e.to);
|
|
@@ -613,19 +715,20 @@ function reachableFrom(plan) {
|
|
|
613
715
|
/**
|
|
614
716
|
* Classify inactive nodes that are rendered dashed on the canvas and skipped at run time:
|
|
615
717
|
* - unreachable orphans
|
|
616
|
-
* - solo chained Leads (zero reachable subagent upstream)
|
|
718
|
+
* - solo chained Leads (zero reachable subagent upstream and blank role)
|
|
617
719
|
* - dangling dead-end subagents (zero outgoing edges while an active non-ancestor downstream Lead exists)
|
|
618
720
|
*/
|
|
619
721
|
function inactiveNodeSets(nodes, edges) {
|
|
620
722
|
const list = withoutEntry(nodes);
|
|
621
723
|
const linkList = Array.isArray(edges) ? edges : [];
|
|
622
|
-
const
|
|
724
|
+
const fwdLinks = forwardEdgesOf(linkList);
|
|
725
|
+
const reachable = reachableFrom({ edges: fwdLinks });
|
|
623
726
|
const byId = new Map(list.map((n) => [n.id, n]));
|
|
624
727
|
|
|
625
728
|
const soloLeads = new Set();
|
|
626
729
|
for (const n of list) {
|
|
627
730
|
if (n.kind !== 'lead' || !reachable.has(n.id)) continue;
|
|
628
|
-
const hasAgentUp =
|
|
731
|
+
const hasAgentUp = fwdLinks.some((e) => {
|
|
629
732
|
if (!e || e.to !== n.id || !reachable.has(e.from) || e.from === 'lead') return false;
|
|
630
733
|
const src = byId.get(e.from);
|
|
631
734
|
return Boolean(src && src.kind !== 'lead');
|
|
@@ -639,7 +742,7 @@ function inactiveNodeSets(nodes, edges) {
|
|
|
639
742
|
if (activeLeads.length) {
|
|
640
743
|
const hasOut = new Set(linkList.map((e) => e.from));
|
|
641
744
|
const parents = new Map();
|
|
642
|
-
for (const e of
|
|
745
|
+
for (const e of fwdLinks) {
|
|
643
746
|
if (!parents.has(e.to)) parents.set(e.to, []);
|
|
644
747
|
parents.get(e.to).push(e.from);
|
|
645
748
|
}
|
|
@@ -663,12 +766,53 @@ function inactiveNodeSets(nodes, edges) {
|
|
|
663
766
|
return { reachable, soloLeads, deadEnds };
|
|
664
767
|
}
|
|
665
768
|
|
|
769
|
+
/**
|
|
770
|
+
* Validate controlled loop edges: each loop edge must leave a condition node, target a strict
|
|
771
|
+
* forward-path ancestor (never entry Lead), and not overlap/cross another loop edge's body.
|
|
772
|
+
*/
|
|
773
|
+
function validateLoopEdges(nodes, edges) {
|
|
774
|
+
const list = withoutEntry(nodes);
|
|
775
|
+
const byId = new Map(list.map((n) => [n.id, n]));
|
|
776
|
+
const linkList = Array.isArray(edges) ? edges : [];
|
|
777
|
+
const loopEdges = linkList.filter((e) => isLoopEdge(e));
|
|
778
|
+
const errors = [];
|
|
779
|
+
const seenMembers = new Map();
|
|
780
|
+
for (const le of loopEdges) {
|
|
781
|
+
const src = byId.get(le.from);
|
|
782
|
+
const dst = byId.get(le.to);
|
|
783
|
+
if (!src || src.kind !== 'condition') {
|
|
784
|
+
errors.push('回环边起点必须是条件判断节点(' + le.from + ' → ' + le.to + ')。');
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
if (!dst || le.to === 'lead') {
|
|
788
|
+
errors.push('回环边不能指向入口 Lead 或不存在的节点(' + le.from + ' → ' + le.to + ')。');
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
const members = loopMemberIds(list, linkList, le);
|
|
792
|
+
if (!members.size) {
|
|
793
|
+
errors.push('回环边目标「' + (dst.label || dst.id) + '」不是「' + (src.label || src.id) + '」的上游祖先节点。');
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
let overlap = false;
|
|
797
|
+
for (const mid of members) {
|
|
798
|
+
if (seenMembers.has(mid)) { overlap = true; break; }
|
|
799
|
+
}
|
|
800
|
+
if (overlap) {
|
|
801
|
+
errors.push('检测到交叉或嵌套回环(涉及节点「' + (dst.label || dst.id) + '」),暂不支持交叉回环。');
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
for (const mid of members) seenMembers.set(mid, le);
|
|
805
|
+
}
|
|
806
|
+
return errors;
|
|
807
|
+
}
|
|
808
|
+
|
|
666
809
|
/**
|
|
667
810
|
* Detect structural warnings on a canvas plan (all three classes are rendered
|
|
668
811
|
* dashed on the canvas and skipped at run time):
|
|
669
812
|
* 1. Unreachable nodes.
|
|
670
|
-
* 2. Solo chained Lead nodes with zero subagent upstream.
|
|
813
|
+
* 2. Solo chained Lead nodes with zero subagent upstream and blank role.
|
|
671
814
|
* 3. Dangling dead-end subagent nodes with zero outgoing edges.
|
|
815
|
+
* 4. Invalid/crossing loop edges or loop conditions with no forward exit.
|
|
672
816
|
*/
|
|
673
817
|
function analyzeCanvasWarnings(nodes, edges) {
|
|
674
818
|
const list = withoutEntry(nodes);
|
|
@@ -692,6 +836,27 @@ function analyzeCanvasWarnings(nodes, edges) {
|
|
|
692
836
|
warnings.push('以下子代理节点没有出边,产出未连入下游或终审 Lead,运行时不生效:'
|
|
693
837
|
+ deadList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
694
838
|
}
|
|
839
|
+
for (const err of validateLoopEdges(list, linkList)) warnings.push(err);
|
|
840
|
+
// Warn if a non-exit node inside a loop has a forward edge leaking outside the loop
|
|
841
|
+
// (that outside branch starts on round 1 and will not re-run on retry rounds).
|
|
842
|
+
const fwdLinks = forwardEdgesOf(linkList);
|
|
843
|
+
const byId = new Map(list.map((n) => [n.id, n]));
|
|
844
|
+
for (const le of linkList) {
|
|
845
|
+
if (!isLoopEdge(le)) continue;
|
|
846
|
+
const members = loopMemberIds(list, linkList, le);
|
|
847
|
+
if (!members.size) continue;
|
|
848
|
+
const leaked = [];
|
|
849
|
+
for (const e of fwdLinks) {
|
|
850
|
+
if (e.from !== le.from && members.has(e.from) && !members.has(e.to)) {
|
|
851
|
+
const src = byId.get(e.from);
|
|
852
|
+
const dst = byId.get(e.to);
|
|
853
|
+
leaked.push(((src && src.label) || e.from) + ' → ' + ((dst && dst.label) || e.to));
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
if (leaked.length) {
|
|
857
|
+
warnings.push('回环内部节点存在绕过条件裁判的旁路连线(' + leaked.join('、') + '),回环重试时这些环外节点不会重跑。');
|
|
858
|
+
}
|
|
859
|
+
}
|
|
695
860
|
return warnings;
|
|
696
861
|
}
|
|
697
862
|
|
|
@@ -770,6 +935,10 @@ function normalizeCanvas(args) {
|
|
|
770
935
|
const branch = normalizeBranch(raw.branch);
|
|
771
936
|
const edgeObj = { id: 'e' + edges.length, from, to, type };
|
|
772
937
|
if (branch) edgeObj.branch = branch;
|
|
938
|
+
if (raw.loop === true) {
|
|
939
|
+
edgeObj.loop = true;
|
|
940
|
+
edgeObj.maxIterations = normalizeMaxIterations(raw.maxIterations);
|
|
941
|
+
}
|
|
773
942
|
edges.push(edgeObj);
|
|
774
943
|
}
|
|
775
944
|
|
|
@@ -822,11 +991,11 @@ function normalizeCanvas(args) {
|
|
|
822
991
|
if (structuredSources.has(node.id)) node.structured = true;
|
|
823
992
|
}
|
|
824
993
|
|
|
825
|
-
// Layout: depth of the longest path from the entry
|
|
994
|
+
// Layout: depth of the longest path from the entry (ignoring controlled loop back-edges).
|
|
826
995
|
const depth = new Map(nodes.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
|
|
827
996
|
for (let pass = 0; pass < nodes.length; pass += 1) {
|
|
828
997
|
let changed = false;
|
|
829
|
-
for (const e of edges) {
|
|
998
|
+
for (const e of forwardEdgesOf(edges)) {
|
|
830
999
|
if (e.to === 'lead') continue;
|
|
831
1000
|
const next = Math.min(nodes.length, depth.get(e.from) + 1);
|
|
832
1001
|
if (next > depth.get(e.to)) { depth.set(e.to, next); changed = true; }
|
|
@@ -935,9 +1104,23 @@ function applyPatch(plan, args) {
|
|
|
935
1104
|
if (!validFrom || !validTo) continue;
|
|
936
1105
|
const type = ['prompt', 'structured', 'session-ref'].includes(edge.type) ? edge.type : 'prompt';
|
|
937
1106
|
const branch = normalizeBranch(edge.branch);
|
|
938
|
-
|
|
1107
|
+
const existingEdge = edges.find((e) => e.from === edge.from && e.to === edge.to && e.type === type && normalizeBranch(e.branch) === branch);
|
|
1108
|
+
if (existingEdge) {
|
|
1109
|
+
if (edge.loop === true) {
|
|
1110
|
+
existingEdge.loop = true;
|
|
1111
|
+
existingEdge.maxIterations = normalizeMaxIterations(edge.maxIterations !== undefined ? edge.maxIterations : existingEdge.maxIterations);
|
|
1112
|
+
} else if (edge.loop === false) {
|
|
1113
|
+
delete existingEdge.loop;
|
|
1114
|
+
delete existingEdge.maxIterations;
|
|
1115
|
+
}
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
939
1118
|
const nextEdge = { from: edge.from, to: edge.to, type };
|
|
940
1119
|
if (branch) nextEdge.branch = branch;
|
|
1120
|
+
if (edge.loop === true) {
|
|
1121
|
+
nextEdge.loop = true;
|
|
1122
|
+
nextEdge.maxIterations = normalizeMaxIterations(edge.maxIterations);
|
|
1123
|
+
}
|
|
941
1124
|
edges.push(nextEdge);
|
|
942
1125
|
}
|
|
943
1126
|
const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
|
|
@@ -1067,6 +1250,10 @@ function inspectPlan(sid) {
|
|
|
1067
1250
|
};
|
|
1068
1251
|
const branch = normalizeBranch(e.branch);
|
|
1069
1252
|
if (branch) out.branch = branch;
|
|
1253
|
+
if (e.loop === true) {
|
|
1254
|
+
out.loop = true;
|
|
1255
|
+
out.maxIterations = normalizeMaxIterations(e.maxIterations);
|
|
1256
|
+
}
|
|
1070
1257
|
return out;
|
|
1071
1258
|
}) : [];
|
|
1072
1259
|
const planRefs = normalizeRefs(plan.refs);
|
|
@@ -1187,6 +1374,8 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1187
1374
|
|
|
1188
1375
|
const order = orderNodes(plan);
|
|
1189
1376
|
if (!order) return { error: '存在环,无法执行有向无环图。' };
|
|
1377
|
+
const loopErrors = validateLoopEdges(plan.nodes, plan.edges);
|
|
1378
|
+
if (loopErrors.length) return { error: '回环配置无效:' + loopErrors[0] };
|
|
1190
1379
|
|
|
1191
1380
|
// Defense in depth: unreachable orphans, solo chained Leads, and dangling
|
|
1192
1381
|
// dead-end subagents are skipped instead of wasting tokens or stalling.
|
|
@@ -1234,11 +1423,18 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1234
1423
|
pruned: new Set(Array.from(base.pruned || []).filter((id) => byId.has(id))),
|
|
1235
1424
|
decisions: { ...(base.decisions || {}) },
|
|
1236
1425
|
fallbackLinks: Array.isArray(base.fallbackLinks) ? base.fallbackLinks.map((fl) => ({ ...fl })) : [],
|
|
1426
|
+
loopCounts: {},
|
|
1427
|
+
totalLoops: 0,
|
|
1428
|
+
loopHistory: {},
|
|
1429
|
+
loopFeedback: {},
|
|
1430
|
+
nodeAttempts: {},
|
|
1431
|
+
loopWarmChild: {},
|
|
1432
|
+
loopExhausted: [],
|
|
1237
1433
|
waitingLead: null,
|
|
1238
1434
|
};
|
|
1239
1435
|
// Build forward adjacency to invalidate seed nodes and all their downstream dependents.
|
|
1240
1436
|
const fwd = new Map();
|
|
1241
|
-
for (const e of plan.edges || []) {
|
|
1437
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1242
1438
|
if (!e || !e.from || !e.to) continue;
|
|
1243
1439
|
if (!fwd.has(e.from)) fwd.set(e.from, []);
|
|
1244
1440
|
fwd.get(e.from).push(e.to);
|
|
@@ -1293,6 +1489,13 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1293
1489
|
pruned: new Set(),
|
|
1294
1490
|
decisions: {},
|
|
1295
1491
|
fallbackLinks: [],
|
|
1492
|
+
loopCounts: {},
|
|
1493
|
+
totalLoops: 0,
|
|
1494
|
+
loopHistory: {},
|
|
1495
|
+
loopFeedback: {},
|
|
1496
|
+
nodeAttempts: {},
|
|
1497
|
+
loopWarmChild: {},
|
|
1498
|
+
loopExhausted: [],
|
|
1296
1499
|
waitingLead: null,
|
|
1297
1500
|
};
|
|
1298
1501
|
runBySession.set(sid, state);
|
|
@@ -1302,15 +1505,32 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1302
1505
|
if (!state.pruned) state.pruned = new Set();
|
|
1303
1506
|
if (!state.decisions) state.decisions = {};
|
|
1304
1507
|
if (!state.fallbackLinks) state.fallbackLinks = [];
|
|
1508
|
+
if (!state.loopCounts) state.loopCounts = {};
|
|
1509
|
+
if (typeof state.totalLoops !== 'number') state.totalLoops = 0;
|
|
1510
|
+
if (!state.loopHistory) state.loopHistory = {};
|
|
1511
|
+
if (!state.loopFeedback) state.loopFeedback = {};
|
|
1512
|
+
if (!state.nodeAttempts) state.nodeAttempts = {};
|
|
1513
|
+
if (!state.loopWarmChild) state.loopWarmChild = {};
|
|
1514
|
+
if (!state.loopExhausted) state.loopExhausted = [];
|
|
1305
1515
|
|
|
1306
1516
|
const emitRunState = (status, waitingLead) => {
|
|
1307
1517
|
if (!sid) return;
|
|
1518
|
+
const loopCounts = {};
|
|
1519
|
+
for (const e of plan.edges || []) {
|
|
1520
|
+
if (!isLoopEdge(e)) continue;
|
|
1521
|
+
const k = edgeKey(e);
|
|
1522
|
+
const entry = { count: state.loopCounts[k] || 0, max: normalizeMaxIterations(e.maxIterations) };
|
|
1523
|
+
loopCounts[k] = entry;
|
|
1524
|
+
if (e.id) loopCounts[e.id] = entry;
|
|
1525
|
+
}
|
|
1308
1526
|
publishRunState(scope, sid, {
|
|
1309
1527
|
status,
|
|
1310
1528
|
done: Array.from(state.done || []),
|
|
1311
1529
|
decisions: { ...state.decisions },
|
|
1312
1530
|
pruned: Array.from(state.pruned || []),
|
|
1313
1531
|
blockedEdges: Array.from(state.blockedEdges || []),
|
|
1532
|
+
loopCounts,
|
|
1533
|
+
nodeAttempts: { ...state.nodeAttempts },
|
|
1314
1534
|
waitingLead: waitingLead ? { id: waitingLead.id, label: waitingLead.label } : null,
|
|
1315
1535
|
});
|
|
1316
1536
|
};
|
|
@@ -1334,7 +1554,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1334
1554
|
};
|
|
1335
1555
|
const depsOf = (node) => {
|
|
1336
1556
|
const out = new Set();
|
|
1337
|
-
for (const e of plan.edges || []) {
|
|
1557
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1338
1558
|
if (e.to === node.id
|
|
1339
1559
|
&& e.from !== 'lead'
|
|
1340
1560
|
&& !state.blockedEdges.has(edgeKey(e))
|
|
@@ -1350,7 +1570,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1350
1570
|
};
|
|
1351
1571
|
const nearestDownstreamLead = (startId) => {
|
|
1352
1572
|
const fwd = new Map();
|
|
1353
|
-
for (const e of plan.edges || []) {
|
|
1573
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1354
1574
|
if (!e || !e.from || !e.to) continue;
|
|
1355
1575
|
if (!fwd.has(e.from)) fwd.set(e.from, []);
|
|
1356
1576
|
fwd.get(e.from).push(e.to);
|
|
@@ -1374,7 +1594,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1374
1594
|
const branchSkippedList = () => Array.from(state.pruned).map((id) => labelOf.get(id) || id);
|
|
1375
1595
|
const ancestorsOf = (targetId) => {
|
|
1376
1596
|
const parents = new Map();
|
|
1377
|
-
for (const e of plan.edges || []) {
|
|
1597
|
+
for (const e of forwardEdgesOf(plan.edges || [])) {
|
|
1378
1598
|
if (!e || !e.from || !e.to) continue;
|
|
1379
1599
|
if (!parents.has(e.to)) parents.set(e.to, []);
|
|
1380
1600
|
parents.get(e.to).push(e.from);
|
|
@@ -1390,12 +1610,13 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1390
1610
|
return seen;
|
|
1391
1611
|
};
|
|
1392
1612
|
const recomputeBranchPrune = () => {
|
|
1393
|
-
// Re-evaluate reachability from entry Lead over non-blocked edges so diamond
|
|
1613
|
+
// Re-evaluate reachability from entry Lead over non-blocked forward edges so diamond
|
|
1394
1614
|
// convergence nodes stay active, while side-channel edges from ancestors of a
|
|
1395
1615
|
// condition node (e.g. A --session-ref--> N) cannot bypass a blocked branch gate.
|
|
1616
|
+
const fwdEdges = forwardEdgesOf(plan.edges || []);
|
|
1396
1617
|
const condAncestors = new Map();
|
|
1397
1618
|
const blockedSources = new Map();
|
|
1398
|
-
for (const e of
|
|
1619
|
+
for (const e of fwdEdges) {
|
|
1399
1620
|
if (!e || !e.from || !e.to) continue;
|
|
1400
1621
|
if (!state.blockedEdges.has(edgeKey(e))) continue;
|
|
1401
1622
|
if (!blockedSources.has(e.to)) blockedSources.set(e.to, new Set());
|
|
@@ -1431,7 +1652,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1431
1652
|
|
|
1432
1653
|
for (let pass = 0; pass <= runnable.length; pass += 1) {
|
|
1433
1654
|
const adj = new Map();
|
|
1434
|
-
for (const e of
|
|
1655
|
+
for (const e of fwdEdges) {
|
|
1435
1656
|
if (!e || !e.from || !e.to) continue;
|
|
1436
1657
|
if (state.blockedEdges.has(edgeKey(e))) continue;
|
|
1437
1658
|
if (state.pruned.has(e.from)) continue;
|
|
@@ -1460,7 +1681,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1460
1681
|
addedAny = true;
|
|
1461
1682
|
const gates = gatedBy.get(n.id);
|
|
1462
1683
|
if (gates && gates.size) {
|
|
1463
|
-
for (const e of
|
|
1684
|
+
for (const e of fwdEdges) {
|
|
1464
1685
|
if (e && e.from === n.id && e.to) addGates(e.to, gates);
|
|
1465
1686
|
}
|
|
1466
1687
|
}
|
|
@@ -1492,7 +1713,11 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1492
1713
|
&& depsOf(n).every((id) => state.done.has(id)));
|
|
1493
1714
|
for (const node of candidates) {
|
|
1494
1715
|
if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) break;
|
|
1495
|
-
const
|
|
1716
|
+
const fb = state.loopFeedback[node.id] || null;
|
|
1717
|
+
const warmChildId = (fb && state.loopWarmChild[node.id]) ? state.loopWarmChild[node.id] : '';
|
|
1718
|
+
const loopCtx = fb ? { feedback: fb, warmChildId } : undefined;
|
|
1719
|
+
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)
|
|
1496
1721
|
.then(
|
|
1497
1722
|
(outcome) => ({ node, outcome }),
|
|
1498
1723
|
(err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
|
|
@@ -1524,6 +1749,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1524
1749
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1525
1750
|
decisions: Object.values(state.decisions),
|
|
1526
1751
|
branchSkipped: branchSkippedList(),
|
|
1752
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1527
1753
|
reused,
|
|
1528
1754
|
skipped,
|
|
1529
1755
|
};
|
|
@@ -1542,6 +1768,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1542
1768
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1543
1769
|
decisions: Object.values(state.decisions),
|
|
1544
1770
|
branchSkipped: branchSkippedList(),
|
|
1771
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1545
1772
|
reused,
|
|
1546
1773
|
skipped,
|
|
1547
1774
|
};
|
|
@@ -1626,8 +1853,107 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1626
1853
|
+ (reason ? ' ' + reason : '');
|
|
1627
1854
|
state.done.add(node.id);
|
|
1628
1855
|
const matchedSet = new Set(matchedIds);
|
|
1629
|
-
|
|
1630
|
-
|
|
1856
|
+
const outEdges = (plan.edges || []).filter((e) => e && e.from === node.id);
|
|
1857
|
+
const matchedEdges = outEdges.filter((e) => {
|
|
1858
|
+
const edgeBranch = normalizeBranch(e.branch) || branches[0].id;
|
|
1859
|
+
return matchedSet.has(edgeBranch);
|
|
1860
|
+
});
|
|
1861
|
+
const matchedLoopEdges = matchedEdges.filter((e) => isLoopEdge(e));
|
|
1862
|
+
const matchedForwardEdges = matchedEdges.filter((e) => !isLoopEdge(e));
|
|
1863
|
+
|
|
1864
|
+
if (matchedLoopEdges.length > 0) {
|
|
1865
|
+
// Loop priority: when a condition matches a controlled loop back-edge,
|
|
1866
|
+
// execute the retry reset (if within bounds) instead of advancing forward branches.
|
|
1867
|
+
const le = matchedLoopEdges[0];
|
|
1868
|
+
const leKey = edgeKey(le);
|
|
1869
|
+
const maxIter = normalizeMaxIterations(le.maxIterations);
|
|
1870
|
+
const used = state.loopCounts[leKey] || 0;
|
|
1871
|
+
const members = loopMemberIds(runnable, plan.edges, le);
|
|
1872
|
+
if (!state.loopHistory[leKey]) state.loopHistory[leKey] = [];
|
|
1873
|
+
state.loopHistory[leKey].push({
|
|
1874
|
+
round: used + 1,
|
|
1875
|
+
reason: reason || '未达预期',
|
|
1876
|
+
sourceLabel: node.label,
|
|
1877
|
+
targetLabel: labelOf.get(le.to) || le.to,
|
|
1878
|
+
});
|
|
1879
|
+
if (used < maxIter && state.totalLoops < MAX_GLOBAL_LOOPS && members.size > 0) {
|
|
1880
|
+
const summaryLines = [];
|
|
1881
|
+
for (const mid of members) {
|
|
1882
|
+
if (mid === node.id) continue;
|
|
1883
|
+
const rawRes = state.results[mid];
|
|
1884
|
+
if (typeof rawRes === 'string' && rawRes.trim()) {
|
|
1885
|
+
const clipped = rawRes.length > 500 ? rawRes.slice(0, 500) + '…' : rawRes;
|
|
1886
|
+
summaryLines.push('[' + (labelOf.get(mid) || mid) + '] ' + clipped);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
const nextRetry = used + 1;
|
|
1890
|
+
state.loopCounts[leKey] = nextRetry;
|
|
1891
|
+
state.totalLoops += 1;
|
|
1892
|
+
for (const mid of members) {
|
|
1893
|
+
state.done.delete(mid);
|
|
1894
|
+
state.pruned.delete(mid);
|
|
1895
|
+
delete state.results[mid];
|
|
1896
|
+
delete state.failed[mid];
|
|
1897
|
+
delete state.emptyOutputs[mid];
|
|
1898
|
+
delete state.decisions[mid];
|
|
1899
|
+
state.nodeAttempts[mid] = { retry: nextRetry, max: maxIter };
|
|
1900
|
+
}
|
|
1901
|
+
for (const e of plan.edges || []) {
|
|
1902
|
+
if (e && members.has(e.from)) state.blockedEdges.delete(edgeKey(e));
|
|
1903
|
+
}
|
|
1904
|
+
state.fallbackLinks = state.fallbackLinks.filter((fl) => !members.has(fl.from) && !members.has(fl.to));
|
|
1905
|
+
state.loopFeedback[le.to] = {
|
|
1906
|
+
retry: nextRetry,
|
|
1907
|
+
max: maxIter,
|
|
1908
|
+
reason: reason || '未达预期',
|
|
1909
|
+
sourceLabel: node.label,
|
|
1910
|
+
lastSummary: summaryLines.join('\n'),
|
|
1911
|
+
};
|
|
1912
|
+
emitRunState('running', null);
|
|
1913
|
+
continue;
|
|
1914
|
+
}
|
|
1915
|
+
// Loop limit reached: stop jumping back and hand off round history to Lead or exit cleanly.
|
|
1916
|
+
const hitGlobalCap = used < maxIter && state.totalLoops >= MAX_GLOBAL_LOOPS;
|
|
1917
|
+
const hist = state.loopHistory[leKey].slice();
|
|
1918
|
+
state.loopExhausted.push({
|
|
1919
|
+
edgeKey: leKey,
|
|
1920
|
+
fromLabel: node.label,
|
|
1921
|
+
toLabel: labelOf.get(le.to) || le.to,
|
|
1922
|
+
iterations: used,
|
|
1923
|
+
maxIterations: maxIter,
|
|
1924
|
+
...(hitGlobalCap ? { globalLimit: MAX_GLOBAL_LOOPS } : {}),
|
|
1925
|
+
history: hist,
|
|
1926
|
+
});
|
|
1927
|
+
state.decisions[node.id].loopExhausted = true;
|
|
1928
|
+
state.results[node.id] += hitGlobalCap
|
|
1929
|
+
? ('(已达全局最大回环上限 ' + MAX_GLOBAL_LOOPS + ' 次,停止回跳)')
|
|
1930
|
+
: ('(已达最大回环重试次数 ' + used + '/' + maxIter + ',停止回跳)');
|
|
1931
|
+
for (const e of outEdges) {
|
|
1932
|
+
const edgeBranch = normalizeBranch(e.branch) || branches[0].id;
|
|
1933
|
+
if (isLoopEdge(e) || !matchedSet.has(edgeBranch)) state.blockedEdges.add(edgeKey(e));
|
|
1934
|
+
}
|
|
1935
|
+
if (matchedForwardEdges.length === 0) {
|
|
1936
|
+
const fallbackLead = nearestDownstreamLead(node.id);
|
|
1937
|
+
if (fallbackLead) {
|
|
1938
|
+
state.fallbackLinks.push({
|
|
1939
|
+
from: node.id,
|
|
1940
|
+
to: fallbackLead.id,
|
|
1941
|
+
label: node.label,
|
|
1942
|
+
loopExhausted: true,
|
|
1943
|
+
iterations: used,
|
|
1944
|
+
maxIterations: maxIter,
|
|
1945
|
+
history: hist,
|
|
1946
|
+
});
|
|
1947
|
+
state.decisions[node.id].fallbackLead = fallbackLead.label;
|
|
1948
|
+
state.results[node.id] += '(已汇总历次反馈转交至最近 Lead「' + fallbackLead.label + '」)';
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
recomputeBranchPrune();
|
|
1952
|
+
emitRunState('running', null);
|
|
1953
|
+
continue;
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
for (const e of outEdges) {
|
|
1631
1957
|
const edgeBranch = normalizeBranch(e.branch) || branches[0].id;
|
|
1632
1958
|
if (!matchedSet.has(edgeBranch)) state.blockedEdges.add(edgeKey(e));
|
|
1633
1959
|
}
|
|
@@ -1648,13 +1974,17 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1648
1974
|
state.results[node.id] = outcome.text;
|
|
1649
1975
|
if (!outcome.ok) {
|
|
1650
1976
|
state.failed[node.id] = { id: node.id, label: node.label, reason: outcome.reason || 'unknown' };
|
|
1977
|
+
delete state.loopWarmChild[node.id];
|
|
1651
1978
|
if (outcome.reason === 'activation-failed') activationFailCount += 1;
|
|
1652
1979
|
} else if (outcome.empty) {
|
|
1653
1980
|
state.emptyOutputs[node.id] = { id: node.id, label: node.label };
|
|
1981
|
+
delete state.loopWarmChild[node.id];
|
|
1982
|
+
} else if (outcome.childId) {
|
|
1983
|
+
state.loopWarmChild[node.id] = outcome.childId;
|
|
1654
1984
|
}
|
|
1655
1985
|
// If a failing node feeds a condition node, let the condition handle failure routing
|
|
1656
1986
|
// instead of circuit-breaking the whole run prematurely.
|
|
1657
|
-
const routesToCondition = (plan.edges || []).some((e) => e && e.from === node.id
|
|
1987
|
+
const routesToCondition = forwardEdgesOf(plan.edges || []).some((e) => e && e.from === node.id
|
|
1658
1988
|
&& byId.get(e.to) && byId.get(e.to).kind === 'condition');
|
|
1659
1989
|
if (!routesToCondition && isPermissionFailure(outcome)) {
|
|
1660
1990
|
permBlocked.push(node.label || node.id);
|
|
@@ -1682,8 +2012,22 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1682
2012
|
}));
|
|
1683
2013
|
const jumpedEntries = (state.fallbackLinks || []).filter((fl) => fl.to === leadNode.id);
|
|
1684
2014
|
const failedConds = jumpedEntries.filter((fl) => fl.failed).map((fl) => (fl.label || labelOf.get(fl.from) || fl.from) + '(' + (fl.reason || 'unknown') + ')');
|
|
1685
|
-
const
|
|
2015
|
+
const exhaustedConds = jumpedEntries.filter((fl) => fl.loopExhausted);
|
|
2016
|
+
const unmatchedConds = jumpedEntries.filter((fl) => !fl.failed && !fl.loopExhausted).map((fl) => fl.label || labelOf.get(fl.from) || fl.from);
|
|
2017
|
+
const leadFb = state.loopFeedback[leadNode.id] || null;
|
|
1686
2018
|
const fallbackParts = [];
|
|
2019
|
+
if (leadFb) {
|
|
2020
|
+
fallbackParts.push('↺ 【第 ' + leadFb.retry + '/' + leadFb.max + ' 次回环修正】下游条件节点「' + (leadFb.sourceLabel || '条件判断') + '」判定未通过,理由:' + (leadFb.reason || '未达预期') + '。请结合最新反馈修正此步骤后再继续。');
|
|
2021
|
+
}
|
|
2022
|
+
if (exhaustedConds.length) {
|
|
2023
|
+
const exLines = exhaustedConds.map((fl) => {
|
|
2024
|
+
const rounds = Array.isArray(fl.history)
|
|
2025
|
+
? fl.history.map((h) => '第' + h.round + '轮:' + h.reason).join(';')
|
|
2026
|
+
: '';
|
|
2027
|
+
return (fl.label || fl.from) + '(已重试 ' + fl.iterations + '/' + fl.maxIterations + ' 次仍未通过' + (rounds ? ' — ' + rounds : '') + ')';
|
|
2028
|
+
});
|
|
2029
|
+
fallbackParts.push('⚠ 回环达到最大次数上限已熔断:' + exLines.join(';') + '。请由你(Lead)审阅历次失败摘要后决定下一步。');
|
|
2030
|
+
}
|
|
1687
2031
|
if (failedConds.length) {
|
|
1688
2032
|
fallbackParts.push('⚠ 条件节点(' + failedConds.join('、') + ')自身执行失败,未擅自选择分支,已跳过中间分支直接转交给你处理;也可调用 canvas_workflow({ retryFailed: true }) 复用上游缓存并只重跑该条件节点及其下游。');
|
|
1689
2033
|
}
|
|
@@ -1714,6 +2058,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1714
2058
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1715
2059
|
decisions: Object.values(state.decisions),
|
|
1716
2060
|
branchSkipped: branchSkippedList(),
|
|
2061
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1717
2062
|
sessions: leadSessions,
|
|
1718
2063
|
reused,
|
|
1719
2064
|
skipped,
|
|
@@ -1735,6 +2080,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1735
2080
|
role: leadNode.role || leadNode.label,
|
|
1736
2081
|
needs: depsOf(leadNode).map((id) => byId.get(id).label),
|
|
1737
2082
|
...(normalizeRefs(leadNode.refs) ? { refs: normalizeRefs(leadNode.refs) } : {}),
|
|
2083
|
+
...(leadFb ? { loopFeedback: { retry: leadFb.retry, max: leadFb.max, sourceLabel: leadFb.sourceLabel, reason: leadFb.reason } } : {}),
|
|
1738
2084
|
},
|
|
1739
2085
|
results: state.results,
|
|
1740
2086
|
labels: state.labels,
|
|
@@ -1742,12 +2088,14 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1742
2088
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1743
2089
|
decisions: Object.values(state.decisions),
|
|
1744
2090
|
branchSkipped: branchSkippedList(),
|
|
2091
|
+
...(state.loopExhausted.length ? { loopExhausted: state.loopExhausted } : {}),
|
|
1745
2092
|
sessions: leadSessions,
|
|
1746
2093
|
hint: (fallbackNotice ? fallbackNotice + ' ' : '')
|
|
1747
2094
|
+ '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需从头重跑可传 reset: true。',
|
|
1748
2095
|
};
|
|
1749
2096
|
}
|
|
1750
2097
|
state.waitingLead = null;
|
|
2098
|
+
delete state.loopFeedback[leadNode.id];
|
|
1751
2099
|
state.results[leadNode.id] = leadResult;
|
|
1752
2100
|
state.labels[leadNode.id] = leadNode.label;
|
|
1753
2101
|
state.done.add(leadNode.id);
|
|
@@ -1908,6 +2256,8 @@ export function apply(ctx) {
|
|
|
1908
2256
|
to: { type: 'string' },
|
|
1909
2257
|
type: { type: 'string', enum: ['prompt', 'structured', 'session-ref'] },
|
|
1910
2258
|
branch: { type: 'string', description: 'For edges leaving a condition node: "true" / "false" (default binary) or one of the condition node branch ids.' },
|
|
2259
|
+
loop: { type: 'boolean', description: 'Optional (condition outgoing edge only): set true to mark a controlled retry back-edge pointing to a strict ancestor node.' },
|
|
2260
|
+
maxIterations: { type: 'integer', minimum: 1, maximum: 10, description: 'Optional (loop edges only): max retry loops before circuit-breaking (1–10, default 3).' },
|
|
1911
2261
|
},
|
|
1912
2262
|
required: ['from', 'to'],
|
|
1913
2263
|
},
|
|
@@ -2173,6 +2523,7 @@ export function apply(ctx) {
|
|
|
2173
2523
|
emptyOutputs: { type: 'array' },
|
|
2174
2524
|
decisions: { type: 'array' },
|
|
2175
2525
|
branchSkipped: { type: 'array' },
|
|
2526
|
+
loopExhausted: { type: 'array' },
|
|
2176
2527
|
sessions: { type: 'array' },
|
|
2177
2528
|
reused: { type: 'array' },
|
|
2178
2529
|
skipped: { type: 'array' },
|
|
@@ -2217,6 +2568,9 @@ export function apply(ctx) {
|
|
|
2217
2568
|
const branchSkipNote = Array.isArray(v.branchSkipped) && v.branchSkipped.length
|
|
2218
2569
|
? '\n\n条件未命中已跳过:' + v.branchSkipped.join('、')
|
|
2219
2570
|
: '';
|
|
2571
|
+
const loopExNote = Array.isArray(v.loopExhausted) && v.loopExhausted.length
|
|
2572
|
+
? '\n\n⚠ 回环达上限熔断:' + v.loopExhausted.map((lx) => (lx.fromLabel || lx.edgeKey) + ' ↺ ' + (lx.toLabel || '') + '(' + lx.iterations + '/' + lx.maxIterations + ')').join(';')
|
|
2573
|
+
: '';
|
|
2220
2574
|
if (v.status === 'need-lead') {
|
|
2221
2575
|
const n = v.node || {};
|
|
2222
2576
|
const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
|
|
@@ -2234,6 +2588,7 @@ export function apply(ctx) {
|
|
|
2234
2588
|
+ '\n\n已完成节点的结果:\n' + body
|
|
2235
2589
|
+ handover
|
|
2236
2590
|
+ branchSkipNote
|
|
2591
|
+
+ loopExNote
|
|
2237
2592
|
+ '\n\n' + (v.hint || ''),
|
|
2238
2593
|
}];
|
|
2239
2594
|
}
|
|
@@ -2261,12 +2616,13 @@ export function apply(ctx) {
|
|
|
2261
2616
|
+ '\n\n已完成节点的结果:\n' + body
|
|
2262
2617
|
+ handover
|
|
2263
2618
|
+ branchSkipNote
|
|
2619
|
+
+ loopExNote
|
|
2264
2620
|
+ reusedNote
|
|
2265
2621
|
+ skip
|
|
2266
2622
|
+ '\n\n' + (v.hint || ''),
|
|
2267
2623
|
}];
|
|
2268
2624
|
}
|
|
2269
|
-
return [{ type: 'text', text: '画布执行完成。' + decisionList + failedList + emptyList + '\n\n' + body + branchSkipNote + reusedNote + skip }];
|
|
2625
|
+
return [{ type: 'text', text: '画布执行完成。' + decisionList + failedList + emptyList + loopExNote + '\n\n' + body + branchSkipNote + reusedNote + skip }];
|
|
2270
2626
|
}
|
|
2271
2627
|
return [{ type: 'text', text: JSON.stringify(v) }];
|
|
2272
2628
|
},
|
|
@@ -2289,6 +2645,9 @@ export {
|
|
|
2289
2645
|
briefFor,
|
|
2290
2646
|
normalizeBranches,
|
|
2291
2647
|
normalizeRefs,
|
|
2648
|
+
normalizeMaxIterations,
|
|
2649
|
+
loopMemberIds,
|
|
2650
|
+
validateLoopEdges,
|
|
2292
2651
|
parseConditionDecision,
|
|
2293
2652
|
withoutEntry,
|
|
2294
2653
|
analyzeCanvasWarnings,
|