dsh-workflow-canvas 1.5.5 → 1.6.1

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/lib/graph.js ADDED
@@ -0,0 +1,1068 @@
1
+ /**
2
+ * Pure graph, prompt, condition-routing, loop-validation, and schema helpers
3
+ * for dsh-workflow-canvas. Zero filesystem or host-runtime dependencies.
4
+ */
5
+
6
+ export const MAX_LOOP_ITERATIONS = 10;
7
+ export const DEFAULT_LOOP_ITERATIONS = 3;
8
+ export const MAX_GLOBAL_LOOPS = 20;
9
+ export const MAX_UPSTREAM_CHARS = 16000;
10
+ export const MAX_UPSTREAM_JSON_CHARS = 24000;
11
+
12
+ /** The entry Lead is a task container, never a runnable node. */
13
+ export function withoutEntry(nodes) {
14
+ return (nodes || []).filter((n) => n.id !== 'lead');
15
+ }
16
+
17
+ export function parsePayload(rawInput) {
18
+ const text = String(rawInput || '').trim();
19
+ if (!text) return { enabled: false };
20
+ try {
21
+ const parsed = JSON.parse(decodeURIComponent(text));
22
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
23
+ return { enabled: false, error: '画布数据格式无效:顶层必须是 JSON 对象' };
24
+ }
25
+ return parsed;
26
+ } catch (err) {
27
+ const detail = err && err.message ? ':' + String(err.message).slice(0, 120) : '';
28
+ return { enabled: false, error: '画布数据解析失败' + detail };
29
+ }
30
+ }
31
+
32
+ export function normalizeMaxIterations(val) {
33
+ const n = Number(val);
34
+ if (!Number.isFinite(n)) return DEFAULT_LOOP_ITERATIONS;
35
+ return Math.max(1, Math.min(MAX_LOOP_ITERATIONS, Math.floor(n)));
36
+ }
37
+
38
+ export function isLoopEdge(e) {
39
+ return Boolean(e && e.loop === true);
40
+ }
41
+
42
+ export function forwardEdgesOf(edges) {
43
+ return (Array.isArray(edges) ? edges : []).filter((e) => e && !e.loop);
44
+ }
45
+
46
+ /**
47
+ * Compute the set of node ids strictly inside a controlled loop edge (from target -> ... -> source)
48
+ * over forward edges: `descendants(loopEdge.to) ∩ ancestors(loopEdge.from)` (inclusive).
49
+ * Returns an empty Set if `loopEdge.from` is not reachable from `loopEdge.to` over forward edges.
50
+ */
51
+ export function loopMemberIds(nodes, edges, loopEdge) {
52
+ if (!loopEdge || !loopEdge.from || !loopEdge.to || loopEdge.to === 'lead') return new Set();
53
+ const fwd = new Map();
54
+ const rev = new Map();
55
+ for (const e of forwardEdgesOf(edges)) {
56
+ if (!e.from || !e.to) continue;
57
+ if (!fwd.has(e.from)) fwd.set(e.from, []);
58
+ fwd.get(e.from).push(e.to);
59
+ if (!rev.has(e.to)) rev.set(e.to, []);
60
+ rev.get(e.to).push(e.from);
61
+ }
62
+ const desc = new Set([loopEdge.to]);
63
+ const q1 = [loopEdge.to];
64
+ for (let i = 0; i < q1.length; i += 1) {
65
+ for (const next of fwd.get(q1[i]) || []) {
66
+ if (!desc.has(next)) { desc.add(next); q1.push(next); }
67
+ }
68
+ }
69
+ if (!desc.has(loopEdge.from)) return new Set();
70
+ const anc = new Set([loopEdge.from]);
71
+ const q2 = [loopEdge.from];
72
+ for (let i = 0; i < q2.length; i += 1) {
73
+ for (const prev of rev.get(q2[i]) || []) {
74
+ if (!anc.has(prev)) { anc.add(prev); q2.push(prev); }
75
+ }
76
+ }
77
+ const members = new Set();
78
+ for (const id of desc) {
79
+ if (anc.has(id)) members.add(id);
80
+ }
81
+ return members;
82
+ }
83
+
84
+ /** Kahn topological order over every plan node (ignoring controlled loop back-edges). */
85
+ export function orderNodes(plan) {
86
+ const nodes = plan.nodes || [];
87
+ const edges = forwardEdgesOf(plan.edges || []);
88
+ const byId = new Map(nodes.map((n) => [n.id, n]));
89
+ const indeg = new Map(nodes.map((n) => [n.id, 0]));
90
+ const adj = new Map(nodes.map((n) => [n.id, []]));
91
+ for (const e of edges) {
92
+ if (e.from === 'lead') continue;
93
+ if (!byId.has(e.from) || !byId.has(e.to)) continue;
94
+ indeg.set(e.to, indeg.get(e.to) + 1);
95
+ adj.get(e.from).push(e.to);
96
+ }
97
+ const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
98
+ const out = [];
99
+ for (let i = 0; i < queue.length; i += 1) {
100
+ const id = queue[i];
101
+ out.push(byId.get(id));
102
+ for (const next of adj.get(id)) {
103
+ indeg.set(next, indeg.get(next) - 1);
104
+ if (indeg.get(next) === 0) queue.push(next);
105
+ }
106
+ }
107
+ return out.length === nodes.length ? out : null;
108
+ }
109
+
110
+ export function upstreamOf(plan, node) {
111
+ const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
112
+ return forwardEdgesOf(plan.edges || [])
113
+ .filter((e) => e.to === node.id)
114
+ .map((e) => ({ edge: e, from: byId.get(e.from) }))
115
+ .filter((x) => x.from);
116
+ }
117
+
118
+ export function downstreamLabels(plan, node) {
119
+ const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
120
+ return forwardEdgesOf(plan.edges || [])
121
+ .filter((e) => e.from === node.id)
122
+ .map((e) => (byId.get(e.to) || {}).label)
123
+ .filter(Boolean);
124
+ }
125
+
126
+ export function normalizeKind(rawKind) {
127
+ if (rawKind === 'lead') return 'lead';
128
+ if (rawKind === 'condition') return 'condition';
129
+ return 'agent';
130
+ }
131
+
132
+ /**
133
+ * Normalize a reference list (paths, URLs, or rules attached to a node or entry Lead).
134
+ * Accepts string arrays or `{ text | path }` objects; capped at 16 unique non-empty items.
135
+ */
136
+ export function normalizeRefs(rawRefs) {
137
+ if (!Array.isArray(rawRefs) || !rawRefs.length) return null;
138
+ const out = [];
139
+ const seen = new Set();
140
+ for (const raw of rawRefs) {
141
+ if (out.length >= 16) break;
142
+ let s = '';
143
+ if (typeof raw === 'string') s = raw.trim();
144
+ else if (raw && typeof raw === 'object') {
145
+ s = String(raw.text !== undefined ? raw.text : (raw.path !== undefined ? raw.path : '')).trim();
146
+ }
147
+ if (!s || seen.has(s)) continue;
148
+ seen.add(s);
149
+ out.push(s);
150
+ }
151
+ return out.length ? out : null;
152
+ }
153
+
154
+ export function normalizeBranch(rawBranch) {
155
+ if (rawBranch === true) return 'true';
156
+ if (rawBranch === false) return 'false';
157
+ if (typeof rawBranch !== 'string') return '';
158
+ return rawBranch.trim();
159
+ }
160
+
161
+ const DEFAULT_BINARY_BRANCHES = [
162
+ { id: 'true', label: '是' },
163
+ { id: 'false', label: '否' },
164
+ ];
165
+
166
+ /**
167
+ * Normalize a condition node's branch list (2–16 entries).
168
+ * Accepts either string arrays (e.g. `['通过', '小修', '重做']`) or `{ id, label }` objects.
169
+ * Returns `null` when the node uses the default binary `true`/`false` pair.
170
+ */
171
+ export function normalizeBranches(rawBranches) {
172
+ if (!Array.isArray(rawBranches) || rawBranches.length < 2) return null;
173
+ const out = [];
174
+ const used = new Set();
175
+ for (let i = 0; i < Math.min(16, rawBranches.length); i += 1) {
176
+ const item = rawBranches[i];
177
+ let id = '';
178
+ let label = '';
179
+ if (typeof item === 'string') {
180
+ label = item.trim();
181
+ id = label;
182
+ } else if (item && typeof item === 'object') {
183
+ id = typeof item.id === 'string' ? item.id.trim() : '';
184
+ label = typeof item.label === 'string' ? item.label.trim() : '';
185
+ if (!id) id = label;
186
+ if (!label) label = id;
187
+ }
188
+ if (!id) id = 'case_' + (i + 1);
189
+ if (!label) label = '分支 ' + (i + 1);
190
+ let uniq = id;
191
+ let suffix = 2;
192
+ while (used.has(uniq)) { uniq = id + '_' + suffix; suffix += 1; }
193
+ used.add(uniq);
194
+ out.push({ id: uniq, label });
195
+ }
196
+ return out.length >= 2 ? out : null;
197
+ }
198
+
199
+ export function conditionBranches(node) {
200
+ const custom = normalizeBranches(node && node.branches);
201
+ const multiMatch = Boolean(node && node.multiMatch);
202
+ if (custom) return { branches: custom, isDefaultBinary: false, multiMatch };
203
+ return { branches: DEFAULT_BINARY_BRANCHES, isDefaultBinary: !multiMatch, multiMatch };
204
+ }
205
+
206
+ export function edgeKey(e) {
207
+ return String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
208
+ }
209
+
210
+ /**
211
+ * Parse ONLY an explicit JSON verdict (`{ pass }`, `{ branches }`, or `{ branch }`) from text.
212
+ * Returns `null` if no strict JSON verdict object is found (no loose natural-language fallback).
213
+ * Used to rescue DSH 0.2.2 `activation.ts` `completed -> error` rewrites when a minimal judge
214
+ * answered with valid JSON text directly instead of calling the `structured_output` tool.
215
+ */
216
+ export function parseStrictConditionJson(text, nodeOrBranches) {
217
+ const { branches, isDefaultBinary, multiMatch } = Array.isArray(nodeOrBranches)
218
+ ? { branches: normalizeBranches(nodeOrBranches) || DEFAULT_BINARY_BRANCHES, isDefaultBinary: !normalizeBranches(nodeOrBranches), multiMatch: false }
219
+ : conditionBranches(nodeOrBranches);
220
+
221
+ const resolveByToken = (token) => {
222
+ const t = String(token || '').trim();
223
+ if (!t) return null;
224
+ const exactId = branches.find((b) => b.id === t);
225
+ if (exactId) return exactId;
226
+ const exactLabel = branches.find((b) => b.label === t);
227
+ if (exactLabel) return exactLabel;
228
+ const lower = t.toLowerCase();
229
+ return branches.find((b) => b.id.toLowerCase() === lower || b.label.toLowerCase() === lower) || null;
230
+ };
231
+
232
+ const makeDecision = (pickedList, reason) => {
233
+ const seen = new Set();
234
+ const uniq = [];
235
+ for (const item of pickedList) {
236
+ if (!item || seen.has(item.id)) continue;
237
+ seen.add(item.id);
238
+ uniq.push(item);
239
+ }
240
+ const finalList = multiMatch ? uniq : uniq.slice(0, 1);
241
+ const first = finalList[0] || null;
242
+ return {
243
+ branches: finalList.map((b) => b.id),
244
+ branchLabels: finalList.map((b) => b.label),
245
+ branch: first ? first.id : '',
246
+ branchLabel: first ? first.label : '',
247
+ pass: isDefaultBinary ? Boolean(first && first.id === 'true') : finalList.length > 0,
248
+ reason: String(reason || ''),
249
+ };
250
+ };
251
+
252
+ const raw = String(text || '').trim();
253
+ const start = raw.indexOf('{');
254
+ const end = raw.lastIndexOf('}');
255
+ if (start === -1 || end <= start) return null;
256
+ let obj;
257
+ try {
258
+ obj = JSON.parse(raw.slice(start, end + 1));
259
+ } catch (_e) {
260
+ return null;
261
+ }
262
+ if (!obj || typeof obj !== 'object') return null;
263
+ if (Array.isArray(obj.branches)) {
264
+ return makeDecision(obj.branches.map(resolveByToken).filter(Boolean), obj.reason);
265
+ }
266
+ if (typeof obj.branch === 'string') {
267
+ const trimmed = obj.branch.trim();
268
+ if (!trimmed || /^(none|null|无|都不满足|未命中)$/i.test(trimmed)) {
269
+ return makeDecision([], obj.reason);
270
+ }
271
+ const hit = resolveByToken(trimmed);
272
+ if (hit) return makeDecision([hit], obj.reason);
273
+ }
274
+ if (typeof obj.pass === 'boolean') {
275
+ const picked = obj.pass ? branches[0] : branches[branches.length - 1];
276
+ return makeDecision([picked], obj.reason);
277
+ }
278
+ return null;
279
+ }
280
+
281
+ /**
282
+ * Parse a condition node's structured or text output into
283
+ * `{ branches, branchLabels, branch, branchLabel, pass, reason }`.
284
+ */
285
+ export function parseConditionDecision(result, fallbackText, nodeOrBranches) {
286
+ const { branches, isDefaultBinary, multiMatch } = Array.isArray(nodeOrBranches)
287
+ ? { branches: normalizeBranches(nodeOrBranches) || DEFAULT_BINARY_BRANCHES, isDefaultBinary: !normalizeBranches(nodeOrBranches), multiMatch: false }
288
+ : conditionBranches(nodeOrBranches);
289
+
290
+ const resolveByToken = (token) => {
291
+ const t = String(token || '').trim();
292
+ if (!t) return null;
293
+ const exactId = branches.find((b) => b.id === t);
294
+ if (exactId) return exactId;
295
+ const exactLabel = branches.find((b) => b.label === t);
296
+ if (exactLabel) return exactLabel;
297
+ const lower = t.toLowerCase();
298
+ const ci = branches.find((b) => b.id.toLowerCase() === lower || b.label.toLowerCase() === lower);
299
+ return ci || null;
300
+ };
301
+
302
+ const makeDecision = (pickedList, reason) => {
303
+ const seen = new Set();
304
+ const uniq = [];
305
+ for (const item of pickedList) {
306
+ if (!item || seen.has(item.id)) continue;
307
+ seen.add(item.id);
308
+ uniq.push(item);
309
+ }
310
+ const finalList = multiMatch ? uniq : uniq.slice(0, 1);
311
+ const first = finalList[0] || null;
312
+ return {
313
+ branches: finalList.map((b) => b.id),
314
+ branchLabels: finalList.map((b) => b.label),
315
+ branch: first ? first.id : '',
316
+ branchLabel: first ? first.label : '',
317
+ pass: isDefaultBinary ? Boolean(first && first.id === 'true') : finalList.length > 0,
318
+ reason: String(reason || ''),
319
+ };
320
+ };
321
+
322
+ const tryObj = (obj) => {
323
+ if (!obj || typeof obj !== 'object') return null;
324
+ if (Array.isArray(obj.branches)) {
325
+ const hits = obj.branches.map(resolveByToken).filter(Boolean);
326
+ return makeDecision(hits, obj.reason);
327
+ }
328
+ if (typeof obj.branch === 'string') {
329
+ const trimmed = obj.branch.trim();
330
+ if (!trimmed || /^(none|null|无|都不满足|未命中)$/i.test(trimmed)) {
331
+ return makeDecision([], obj.reason);
332
+ }
333
+ const hit = resolveByToken(trimmed);
334
+ if (hit) return makeDecision([hit], obj.reason);
335
+ }
336
+ if (typeof obj.pass === 'boolean') {
337
+ const picked = obj.pass ? branches[0] : branches[branches.length - 1];
338
+ return makeDecision([picked], obj.reason);
339
+ }
340
+ return null;
341
+ };
342
+
343
+ const fromStructured = tryObj(result && result.structured);
344
+ if (fromStructured) return fromStructured;
345
+
346
+ const raw = String(fallbackText || '').trim();
347
+ const start = raw.indexOf('{');
348
+ const end = raw.lastIndexOf('}');
349
+ if (start !== -1 && end > start) {
350
+ try {
351
+ const fromJson = tryObj(JSON.parse(raw.slice(start, end + 1)));
352
+ if (fromJson) return fromJson;
353
+ } catch (_e) { /* fall through */ }
354
+ }
355
+
356
+ if (isDefaultBinary) {
357
+ if (/^(true|yes|pass|通过|是)\b/i.test(raw)) return makeDecision([branches[0]], raw.slice(0, 200));
358
+ return makeDecision([branches[1]], raw.slice(0, 200) || '未能解析布尔判断,默认走「否」分支');
359
+ }
360
+
361
+ // Multi-way text fallback: collect matching branch ids/labels; return empty [] if none match.
362
+ const lowerRaw = raw.toLowerCase();
363
+ const matched = [];
364
+ for (const b of branches) {
365
+ if (lowerRaw.includes(b.id.toLowerCase()) || lowerRaw.includes(b.label.toLowerCase())) {
366
+ matched.push(b);
367
+ if (!multiMatch) break;
368
+ }
369
+ }
370
+ return makeDecision(matched, raw.slice(0, 200) || (matched.length ? '' : '未命中任何分支,已跳过后续分支'));
371
+ }
372
+
373
+ /**
374
+ * Guard downstream context budgets against verbose upstream logs by preserving both
375
+ * the head (conclusions/summary) and tail (final errors/results) when exceeding maxChars.
376
+ */
377
+ export function clipUpstreamOutput(body, maxChars = MAX_UPSTREAM_CHARS) {
378
+ const text = typeof body === 'string' ? body : '';
379
+ if (!Number.isFinite(maxChars) || maxChars <= 0 || text.length <= maxChars) return text;
380
+ let headEnd = Math.floor(maxChars * 0.68);
381
+ let tailStart = text.length - Math.floor(maxChars * 0.25);
382
+ // Never slice through a UTF-16 surrogate pair (emoji / CJK Ext-B); strict UTF-8 gateways reject lone surrogates.
383
+ if (headEnd > 0 && headEnd < text.length) {
384
+ const hi = text.charCodeAt(headEnd - 1);
385
+ if (hi >= 0xd800 && hi <= 0xdbff) headEnd -= 1;
386
+ }
387
+ if (tailStart > 0 && tailStart < text.length) {
388
+ const lo = text.charCodeAt(tailStart);
389
+ if (lo >= 0xdc00 && lo <= 0xdfff) tailStart += 1;
390
+ }
391
+ const omitted = tailStart - headEnd;
392
+ if (omitted <= 200) return text;
393
+ return text.slice(0, headEnd)
394
+ + '\n\n…[已折叠中间 ' + omitted + ' 字以节省 Token,完整内容可查看上游子代理会话]…\n\n'
395
+ + text.slice(tailStart);
396
+ }
397
+
398
+ export function briefFor(plan, node, results, failedMap, prunedSet, loopCtx) {
399
+ const ups = upstreamOf(plan, node).filter((u) => !(prunedSet && prunedSet.has(u.from.id)));
400
+ const downs = downstreamLabels(plan, node);
401
+ const head = [];
402
+ if (node.kind === 'condition') {
403
+ const outEdges = (plan.edges || []).filter((e) => e.from === node.id);
404
+ const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
405
+ const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
406
+ const fmtTarget = (e) => {
407
+ const lbl = (byId.get(e.to) || {}).label || e.to;
408
+ return e.loop ? (lbl + '(↺ 回环重做,最多 ' + normalizeMaxIterations(e.maxIterations) + ' 次)') : lbl;
409
+ };
410
+ head.push('【工作流条件判断节点】你负责判断当前工作流接下来走哪条分支(「' + node.label + '」)。');
411
+ head.push('【总任务】' + plan.task);
412
+ if (isDefaultBinary) {
413
+ const yesTargets = outEdges.filter((e) => (normalizeBranch(e.branch) || 'true') === 'true').map(fmtTarget);
414
+ const noTargets = outEdges.filter((e) => normalizeBranch(e.branch) === 'false').map(fmtTarget);
415
+ head.push('【判断条件】' + (node.role || '判断上游步骤是否执行成功并达到预期;成功返回 true,失败或未达标返回 false。'));
416
+ head.push('【分支去向】pass=true(是)→ ' + (yesTargets.join('、') || '(无)') + ';pass=false(否)→ ' + (noTargets.join('、') || '(无)'));
417
+ head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"pass": true/false, "reason": "一句话理由"}。');
418
+ } else {
419
+ const branchLines = branches.map((b, idx) => {
420
+ const targets = outEdges
421
+ .filter((e) => {
422
+ const eb = normalizeBranch(e.branch);
423
+ return eb ? eb === b.id : idx === 0;
424
+ })
425
+ .map(fmtTarget);
426
+ const tag = b.label === b.id ? '"' + b.id + '"' : '"' + b.id + '"(' + b.label + ')';
427
+ return '- ' + tag + ' → ' + (targets.join('、') || '(无下游)');
428
+ });
429
+ head.push('【判断规则】' + (node.role || (multiMatch
430
+ ? '根据上游结果选出所有满足条件的分支(可多选并行);若均不满足返回空数组。'
431
+ : '根据上游结果选出最匹配的一条分支;若均不满足返回空数组(如有「其他/兜底」分支则选它)。')));
432
+ head.push('【匹配模式】' + (multiMatch
433
+ ? '多选并行(可返回 0 条、1 条或多条分支 id)'
434
+ : '单选分流(最多返回 1 条最匹配的分支 id;均不满足返回空数组 [])'));
435
+ head.push('【可选分支】\n' + branchLines.join('\n'));
436
+ head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"branches": ["<分支id>"], "reason": "一句话理由"};若没有任何分支满足,返回 {"branches": [], "reason": "..."}。');
437
+ }
438
+ } else {
439
+ head.push('【工作流节点】你在一个多步工作流里负责「' + node.label + '」这一步(子代理)。');
440
+ if (ups.length === 0) head.push('【总任务】' + plan.task);
441
+ head.push('【职责】' + (node.role || node.label));
442
+ if (ups.length) head.push('【上游】' + ups.map((u) => u.from.label).join('、') + ' 已交付结果给你(见下文)。');
443
+ head.push('【下游】' + (downs.length ? downs.join('、') + ' 会使用你的输出。' : '你是终点,结果会直接交付给用户。'));
444
+ head.push('【要求】只完成你这一步;最终回复只输出简洁、可直接被下游或 Lead 消费的交付报告(结论、改动清单、关键接口/路径),不要包含思考独白、过程叙述或对其他并行节点的评价。若因环境或权限受限未能生成预期产物,必须在开头显式标注「【未完全交付】」并列出缺失项,不得把仅写脚本汇报为已完成。');
445
+ }
446
+ const mergedRefs = [];
447
+ const seenRefs = new Set();
448
+ for (const r of (normalizeRefs(plan && plan.refs) || []).concat(normalizeRefs(node && node.refs) || [])) {
449
+ if (!seenRefs.has(r)) { seenRefs.add(r); mergedRefs.push(r); }
450
+ }
451
+ if (mergedRefs.length) {
452
+ head.push('【参考资料 / 约束】\n' + mergedRefs.map((r) => '- ' + r).join('\n'));
453
+ }
454
+ if (loopCtx && loopCtx.feedback) {
455
+ const fb = loopCtx.feedback;
456
+ const lines = [
457
+ '【第 ' + fb.retry + '/' + fb.max + ' 次回环修正反馈】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请针对以下问题修正后输出最新结果:',
458
+ '- 打回理由:' + (fb.reason || '未达预期'),
459
+ ];
460
+ if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
461
+ head.push(lines.join('\n'));
462
+ }
463
+ let text = head.join('\n') + '\n';
464
+ for (const u of ups) {
465
+ const value = results[u.from.id];
466
+ const type = u.edge.type || 'prompt';
467
+ const rawBody = typeof value === 'string' ? value : '(没有结果)';
468
+ const body = clipUpstreamOutput(rawBody, type === 'structured' ? MAX_UPSTREAM_JSON_CHARS : MAX_UPSTREAM_CHARS);
469
+ const failInfo = failedMap && failedMap[u.from.id];
470
+ const warn = failInfo
471
+ ? '【警告:该上游节点执行失败(' + (failInfo.reason || 'unknown') + '),请勿将其报错当作正常结论,必要时说明受阻情况】\n'
472
+ : '';
473
+ if (type === 'structured') {
474
+ const jsonNote = body !== rawBody
475
+ ? '(JSON,超长已头尾折叠,完整数据见上游会话)'
476
+ : '(JSON,可直接解析)';
477
+ text += '\n## 来自【' + u.from.label + '】的数据' + jsonNote + '\n' + warn + '```json\n'
478
+ + body + '\n```\n';
479
+ } else if (type === 'session-ref') {
480
+ text += '\n## 来自【' + u.from.label + '】的会话引用(当前按文本传递)\n' + warn
481
+ + body + '\n';
482
+ } else {
483
+ text += '\n## 来自【' + u.from.label + '】\n' + warn + body + '\n';
484
+ }
485
+ }
486
+ return text;
487
+ }
488
+
489
+ export function extractResultError(result) {
490
+ if (!result || typeof result !== 'object') return '';
491
+ // DSH 0.2.2 SubagentResult stores failure details in `diagnostic` (<=4096 UTF-8 bytes);
492
+ // keep legacy/custom candidates as fallback for third-party providers or tests.
493
+ const candidates = [result.diagnostic, result.error, result.errorMessage, result.message, result.failureReason];
494
+ for (const raw of candidates) {
495
+ if (typeof raw === 'string' && raw.trim()) return raw.trim();
496
+ if (raw && typeof raw === 'object') {
497
+ const msg = raw.message || raw.detail || raw.code;
498
+ if (typeof msg === 'string' && msg.trim()) return msg.trim();
499
+ try {
500
+ const s = JSON.stringify(raw);
501
+ if (s && s !== '{}') return s.slice(0, 240);
502
+ } catch (_e) { /* ignore */ }
503
+ }
504
+ }
505
+ return '';
506
+ }
507
+
508
+ export function textOf(result) {
509
+ // A structured node's canonical value is its parsed object, not the prose.
510
+ if (result && result.structured !== undefined) {
511
+ try {
512
+ return JSON.stringify(result.structured);
513
+ } catch (_e) {
514
+ /* fall through to prose */
515
+ }
516
+ }
517
+ const blocks = (result && result.output) || [];
518
+ const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
519
+ if (text) return text;
520
+ const errDetail = extractResultError(result);
521
+ const stop = (result && result.stopReason) || (errDetail ? 'error' : 'no-output');
522
+ return errDetail ? '[' + stop + '] ' + errDetail : '[' + stop + ']';
523
+ }
524
+
525
+ export function failed(result) {
526
+ const reason = result && result.stopReason;
527
+ return reason !== undefined && reason !== 'completed';
528
+ }
529
+
530
+ export function isEmptyOutput(result) {
531
+ if (result && result.structured !== undefined) return false;
532
+ const blocks = (result && result.output) || [];
533
+ const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
534
+ return text.trim().length === 0;
535
+ }
536
+
537
+ export function buildLoopWarmPrompt(node, loopCtx) {
538
+ const fb = loopCtx && loopCtx.feedback;
539
+ if (!fb) return null;
540
+ const lines = [
541
+ '【第 ' + fb.retry + '/' + fb.max + ' 次回环修正】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请结合以下反馈直接在当前会话上下文中修正并输出最新交付结果(无需重复叙述过程):',
542
+ '- 打回理由:' + (fb.reason || '未达预期'),
543
+ ];
544
+ if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
545
+ if (node.role) lines.push('- 你的职责提醒:' + node.role);
546
+ return lines.join('\n');
547
+ }
548
+
549
+ export function formatModelLabel(provider, model) {
550
+ const p = typeof provider === 'string' ? provider.trim() : '';
551
+ const m = typeof model === 'string' ? model.trim() : '';
552
+ if (p && m) return p + '/' + m;
553
+ return m || p || '';
554
+ }
555
+
556
+ /** Detect permission / sandbox denial outcomes so we can circuit-break before burning downstream tokens. */
557
+ const PERMISSION_ERR_RE = /permission denied|access is denied|sandbox-local|windows-acl|win32error|eacces|eperm|approval required|not permitted|拒绝访问|权限不足|无权执行|沙箱拒绝/i;
558
+ export function isPermissionFailure(outcome) {
559
+ if (!outcome) return false;
560
+ const text = String(outcome.text || '');
561
+ if (!outcome.ok && PERMISSION_ERR_RE.test(text)) return true;
562
+ if (text.includes('【未完全交付】') && PERMISSION_ERR_RE.test(text)) return true;
563
+ return false;
564
+ }
565
+
566
+ /**
567
+ * Detect clearly transient network / upstream gateway / rate-limit errors suitable
568
+ * for a single short backoff retry on strictly read-only (`minimal` / `condition`) nodes.
569
+ * Restricts matching to error/timeout/run-failed stopReasons and short error texts so
570
+ * truncated model prose (`max_tokens`) mentioning "502"/"timeout" never false-triggers.
571
+ */
572
+ const TRANSIENT_ERR_RE = /\b(429|502|503|504)\b|rate[\s_-]?limit|too many requests|timed?\s*out|econnreset|etimedout|econnrefused|socket hang up|overloaded|temporarily unavailable|bad gateway|service unavailable|network error|请求过于频繁|限流|超时|网关错误/i;
573
+ const TRANSIENT_ELIGIBLE_REASONS = new Set(['', 'error', 'run-failed', 'timeout']);
574
+ export function isTransientFailure(outcome) {
575
+ if (!outcome || outcome.ok) return false;
576
+ const reason = typeof outcome.reason === 'string' ? outcome.reason.trim().toLowerCase() : '';
577
+ if (!TRANSIENT_ELIGIBLE_REASONS.has(reason) || isPermissionFailure(outcome)) return false;
578
+ const detail = typeof outcome.errorDetail === 'string' ? outcome.errorDetail.trim() : '';
579
+ if (detail) return TRANSIENT_ERR_RE.test(detail);
580
+ const text = typeof outcome.text === 'string' ? outcome.text.trim() : '';
581
+ if (!text || text.length > 500) return false;
582
+ return TRANSIENT_ERR_RE.test(text);
583
+ }
584
+
585
+ /** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
586
+ export function reachableFrom(plan) {
587
+ const adj = new Map();
588
+ for (const e of forwardEdgesOf(plan && plan.edges)) {
589
+ if (!e || !e.from || !e.to) continue;
590
+ if (!adj.has(e.from)) adj.set(e.from, []);
591
+ adj.get(e.from).push(e.to);
592
+ }
593
+ const set = new Set(['lead']);
594
+ const queue = ['lead'];
595
+ for (let i = 0; i < queue.length; i += 1) {
596
+ const cur = queue[i];
597
+ for (const next of adj.get(cur) || []) {
598
+ if (!set.has(next)) { set.add(next); queue.push(next); }
599
+ }
600
+ }
601
+ return set;
602
+ }
603
+
604
+ /**
605
+ * Classify inactive nodes that are rendered dashed on the canvas and skipped at run time:
606
+ * - unreachable orphans
607
+ * - solo chained Leads (zero reachable subagent upstream and blank role)
608
+ * - dangling dead-end subagents (zero outgoing edges while an active non-ancestor downstream Lead exists)
609
+ */
610
+ export function inactiveNodeSets(nodes, edges) {
611
+ const list = withoutEntry(nodes);
612
+ const linkList = Array.isArray(edges) ? edges : [];
613
+ const fwdLinks = forwardEdgesOf(linkList);
614
+ const reachable = reachableFrom({ edges: fwdLinks });
615
+ const byId = new Map(list.map((n) => [n.id, n]));
616
+
617
+ const soloLeads = new Set();
618
+ for (const n of list) {
619
+ if (n.kind !== 'lead' || !reachable.has(n.id)) continue;
620
+ const hasAgentUp = fwdLinks.some((e) => {
621
+ if (!e || e.to !== n.id || !reachable.has(e.from) || e.from === 'lead') return false;
622
+ const src = byId.get(e.from);
623
+ return Boolean(src && src.kind !== 'lead');
624
+ });
625
+ const hasRole = Boolean(String(n.role || '').trim());
626
+ if (!hasAgentUp && !hasRole) soloLeads.add(n.id);
627
+ }
628
+
629
+ const deadEnds = new Set();
630
+ const activeLeads = list.filter((n) => n.kind === 'lead' && reachable.has(n.id) && !soloLeads.has(n.id));
631
+ if (activeLeads.length) {
632
+ const hasOut = new Set(linkList.map((e) => e.from));
633
+ const parents = new Map();
634
+ for (const e of fwdLinks) {
635
+ if (!parents.has(e.to)) parents.set(e.to, []);
636
+ parents.get(e.to).push(e.from);
637
+ }
638
+ const ancestorsOf = (id) => {
639
+ const seen = new Set();
640
+ const stack = [id];
641
+ while (stack.length) {
642
+ const cur = stack.pop();
643
+ for (const p of parents.get(cur) || []) {
644
+ if (!seen.has(p)) { seen.add(p); stack.push(p); }
645
+ }
646
+ }
647
+ return seen;
648
+ };
649
+ for (const n of list) {
650
+ if (n.kind === 'lead' || !reachable.has(n.id) || hasOut.has(n.id)) continue;
651
+ const anc = ancestorsOf(n.id);
652
+ if (activeLeads.some((ln) => !anc.has(ln.id))) deadEnds.add(n.id);
653
+ }
654
+ }
655
+ return { reachable, soloLeads, deadEnds };
656
+ }
657
+
658
+ /**
659
+ * Validate controlled loop edges: each loop edge must leave a condition node, target a strict
660
+ * forward-path ancestor (never entry Lead), and not overlap/cross another loop edge's body.
661
+ */
662
+ export function validateLoopEdges(nodes, edges) {
663
+ const list = withoutEntry(nodes);
664
+ const byId = new Map(list.map((n) => [n.id, n]));
665
+ const linkList = Array.isArray(edges) ? edges : [];
666
+ const loopEdges = linkList.filter((e) => isLoopEdge(e));
667
+ const errors = [];
668
+ const seenMembers = new Map();
669
+ for (const le of loopEdges) {
670
+ const src = byId.get(le.from);
671
+ const dst = byId.get(le.to);
672
+ if (!src || src.kind !== 'condition') {
673
+ errors.push('回环边起点必须是条件判断节点(' + le.from + ' → ' + le.to + ')。');
674
+ continue;
675
+ }
676
+ if (!dst || le.to === 'lead') {
677
+ errors.push('回环边不能指向入口 Lead 或不存在的节点(' + le.from + ' → ' + le.to + ')。');
678
+ continue;
679
+ }
680
+ const members = loopMemberIds(list, linkList, le);
681
+ if (!members.size) {
682
+ errors.push('回环边目标「' + (dst.label || dst.id) + '」不是「' + (src.label || src.id) + '」的上游祖先节点。');
683
+ continue;
684
+ }
685
+ let overlap = false;
686
+ for (const mid of members) {
687
+ if (seenMembers.has(mid)) { overlap = true; break; }
688
+ }
689
+ if (overlap) {
690
+ errors.push('检测到交叉或嵌套回环(涉及节点「' + (dst.label || dst.id) + '」),暂不支持交叉回环。');
691
+ continue;
692
+ }
693
+ for (const mid of members) seenMembers.set(mid, le);
694
+ }
695
+ return errors;
696
+ }
697
+
698
+ /**
699
+ * Detect structural warnings on a canvas plan (all classes are rendered
700
+ * dashed on the canvas and skipped at run time).
701
+ */
702
+ export function analyzeCanvasWarnings(nodes, edges) {
703
+ const list = withoutEntry(nodes);
704
+ const linkList = Array.isArray(edges) ? edges : [];
705
+ const warnings = [];
706
+ if (!list.length) return warnings;
707
+
708
+ const { reachable, soloLeads, deadEnds } = inactiveNodeSets(list, linkList);
709
+ const orphans = list.filter((n) => !reachable.has(n.id));
710
+ if (orphans.length) {
711
+ warnings.push('以下节点未从入口 Lead 连通,运行时会被跳过:'
712
+ + orphans.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
713
+ }
714
+ const soloList = list.filter((n) => soloLeads.has(n.id));
715
+ if (soloList.length) {
716
+ warnings.push('以下 Lead 节点未连入子代理且未填写分工(role),运行时不生效:'
717
+ + soloList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
718
+ }
719
+ const deadList = list.filter((n) => deadEnds.has(n.id));
720
+ if (deadList.length) {
721
+ warnings.push('以下子代理节点没有出边,产出未连入下游或终审 Lead,运行时不生效:'
722
+ + deadList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
723
+ }
724
+ if (orderNodes({ nodes: list, edges: linkList }) === null) {
725
+ warnings.push('检测到前向连线存在环路,运行时会拒绝执行;如需条件打回重试,请在条件出边设置 loop: true。');
726
+ }
727
+ for (const err of validateLoopEdges(list, linkList)) warnings.push(err);
728
+ // Warn if a non-exit node inside a loop has a forward edge leaking outside the loop
729
+ // (that outside branch starts on round 1 and will not re-run on retry rounds).
730
+ const fwdLinks = forwardEdgesOf(linkList);
731
+ const byId = new Map(list.map((n) => [n.id, n]));
732
+ for (const le of linkList) {
733
+ if (!isLoopEdge(le)) continue;
734
+ const members = loopMemberIds(list, linkList, le);
735
+ if (!members.size) continue;
736
+ const leaked = [];
737
+ for (const e of fwdLinks) {
738
+ if (e.from !== le.from && members.has(e.from) && !members.has(e.to)) {
739
+ const src = byId.get(e.from);
740
+ const dst = byId.get(e.to);
741
+ leaked.push(((src && src.label) || e.from) + ' → ' + ((dst && dst.label) || e.to));
742
+ }
743
+ }
744
+ if (leaked.length) {
745
+ warnings.push('回环内部节点存在绕过条件裁判的旁路连线(' + leaked.join('、') + '),回环重试时这些环外节点不会重跑。');
746
+ }
747
+ }
748
+ return warnings;
749
+ }
750
+
751
+ /**
752
+ * Turn a model-authored sketch into a canvas document: assign ids, ensure one
753
+ * connected entry Lead, and lay the graph out in columns by depth.
754
+ */
755
+ export function normalizeCanvas(args) {
756
+ if (!args || !Array.isArray(args.nodes) || !args.nodes.length) {
757
+ return { error: 'nodes 必须是包含至少一个节点的数组。' };
758
+ }
759
+ const rawNodes = args.nodes;
760
+ const rawEdges = Array.isArray(args.edges) ? args.edges : [];
761
+
762
+ const nodes = [];
763
+ const idByRef = new Map();
764
+ const usedIds = new Set();
765
+ let counter = 0;
766
+ let hasExplicitLead = false;
767
+ for (const raw of rawNodes) {
768
+ if (!raw || typeof raw !== 'object') continue;
769
+ counter += 1;
770
+ const kind = normalizeKind(raw.kind);
771
+ const wantsEntry = !hasExplicitLead && (raw.id === 'lead' || (raw.entry === true && kind === 'lead'));
772
+ let id = wantsEntry
773
+ ? 'lead'
774
+ : (typeof raw.id === 'string' && raw.id && raw.id !== 'lead' ? raw.id : 'n' + counter);
775
+ if (usedIds.has(id)) {
776
+ let suffix = 2;
777
+ while (usedIds.has(id + '_' + suffix)) suffix += 1;
778
+ id = id + '_' + suffix;
779
+ }
780
+ usedIds.add(id);
781
+ if (id === 'lead') hasExplicitLead = true;
782
+ const defaultLabel = kind === 'lead'
783
+ ? 'Lead 步骤 ' + counter
784
+ : (kind === 'condition' ? '条件判断 ' + counter : 'Node ' + counter);
785
+ const label = String(raw.label || defaultLabel);
786
+ const nodeObj = {
787
+ id,
788
+ kind: id === 'lead' ? 'lead' : kind,
789
+ label,
790
+ role: String(raw.role || ''),
791
+ task: String(raw.task || ''),
792
+ provider: String(raw.provider || ''),
793
+ model: String(raw.model || ''),
794
+ reasoning: String(raw.reasoning || ''),
795
+ preset: (id === 'lead' ? '' : (kind === 'condition' ? 'minimal' : String(raw.preset || ''))),
796
+ structured: Boolean(raw.structured),
797
+ keepSession: Boolean(raw.keepSession),
798
+ fallbackModel: String(raw.fallbackModel || ''),
799
+ fallbackProvider: String(raw.fallbackProvider || ''),
800
+ x: 0,
801
+ y: 0,
802
+ };
803
+ const normRefs = normalizeRefs(raw.refs);
804
+ if (normRefs) nodeObj.refs = normRefs;
805
+ if (nodeObj.kind === 'condition') {
806
+ const customBranches = normalizeBranches(raw.branches);
807
+ if (customBranches) nodeObj.branches = customBranches;
808
+ if (raw.multiMatch === true) nodeObj.multiMatch = true;
809
+ }
810
+ nodes.push(nodeObj);
811
+ if (raw.ref && !idByRef.has(String(raw.ref))) idByRef.set(String(raw.ref), id);
812
+ if (raw.id && !idByRef.has(String(raw.id))) idByRef.set(String(raw.id), id);
813
+ idByRef.set(id, id);
814
+ }
815
+ if (!nodes.length) return { error: '节点都无效' };
816
+
817
+ const ids = new Set(nodes.map((n) => n.id));
818
+ const edges = [];
819
+ const droppedEdges = [];
820
+ for (const raw of rawEdges) {
821
+ if (!raw || typeof raw !== 'object') continue;
822
+ const from = idByRef.get(String(raw.from)) || String(raw.from);
823
+ const to = idByRef.get(String(raw.to)) || String(raw.to);
824
+ if ((from !== 'lead' && !ids.has(from)) || !ids.has(to) || from === to || to === 'lead') {
825
+ droppedEdges.push(String(raw.from || '?') + ' → ' + String(raw.to || '?'));
826
+ continue;
827
+ }
828
+ const type = ['prompt', 'structured', 'session-ref'].includes(raw.type) ? raw.type : 'prompt';
829
+ const branch = normalizeBranch(raw.branch);
830
+ const edgeObj = { id: 'e' + edges.length, from, to, type };
831
+ if (branch) edgeObj.branch = branch;
832
+ if (raw.loop === true) {
833
+ edgeObj.loop = true;
834
+ edgeObj.maxIterations = normalizeMaxIterations(raw.maxIterations);
835
+ }
836
+ edges.push(edgeObj);
837
+ }
838
+
839
+ let entry = nodes.find((n) => n.id === 'lead');
840
+ if (!entry) {
841
+ // If the caller hand-authored a root Lead node (no incoming edges, has outgoing edges)
842
+ // and didn't wire from id='lead', promote it to entry Lead instead of duplicating it.
843
+ const hasLeadEdge = edges.some((e) => e.from === 'lead');
844
+ const inSet = new Set(edges.map((e) => e.to));
845
+ const outSet = new Set(edges.map((e) => e.from));
846
+ const rootLead = !hasLeadEdge
847
+ ? nodes.find((n) => n.kind === 'lead' && !inSet.has(n.id) && outSet.has(n.id))
848
+ : null;
849
+ if (rootLead) {
850
+ const oldId = rootLead.id;
851
+ rootLead.id = 'lead';
852
+ rootLead.task = rootLead.task || String(args.task || '') || rootLead.role;
853
+ rootLead.role = '';
854
+ for (const e of edges) {
855
+ if (e.from === oldId) e.from = 'lead';
856
+ }
857
+ entry = rootLead;
858
+ } else {
859
+ entry = {
860
+ id: 'lead', kind: 'lead', label: 'Lead(本对话)', role: '',
861
+ task: String(args.task || ''), provider: '', model: '', reasoning: '',
862
+ preset: '', structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
863
+ x: 0, y: 0,
864
+ };
865
+ nodes.unshift(entry);
866
+ }
867
+ } else if (!entry.task) {
868
+ entry.task = String(args.task || '') || entry.role;
869
+ }
870
+ const topRefs = normalizeRefs(args && args.refs);
871
+ if (topRefs && !entry.refs) entry.refs = topRefs;
872
+
873
+ // If entry Lead still has no outgoing edges, auto-wire it to all root nodes so
874
+ // a freshly generated canvas is never dead/unreachable on arrival.
875
+ if (!edges.some((e) => e.from === 'lead')) {
876
+ const hasIn = new Set(edges.map((e) => e.to));
877
+ const roots = nodes.filter((n) => n.id !== 'lead' && !hasIn.has(n.id));
878
+ for (const root of roots) {
879
+ edges.push({ id: 'e' + edges.length, from: 'lead', to: root.id, type: 'prompt' });
880
+ }
881
+ }
882
+
883
+ const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
884
+ for (const node of nodes) {
885
+ if (structuredSources.has(node.id)) node.structured = true;
886
+ }
887
+
888
+ // Layout: depth of the longest path from the entry (ignoring controlled loop back-edges).
889
+ const depth = new Map(nodes.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
890
+ for (let pass = 0; pass < nodes.length; pass += 1) {
891
+ let changed = false;
892
+ for (const e of forwardEdgesOf(edges)) {
893
+ if (e.to === 'lead') continue;
894
+ const next = Math.min(nodes.length, depth.get(e.from) + 1);
895
+ if (next > depth.get(e.to)) { depth.set(e.to, next); changed = true; }
896
+ }
897
+ if (!changed) break;
898
+ }
899
+ const perColumn = new Map();
900
+ for (const node of nodes) {
901
+ const level = depth.get(node.id) || 0;
902
+ const row = perColumn.get(level) || 0;
903
+ perColumn.set(level, row + 1);
904
+ node.x = 60 + level * 300;
905
+ node.y = 80 + row * 260;
906
+ }
907
+
908
+ const warnings = analyzeCanvasWarnings(nodes, edges);
909
+ if (droppedEdges.length) {
910
+ warnings.push('以下连线因节点 ID 不存在、自环或指向入口 Lead 已被忽略:' + droppedEdges.join('、'));
911
+ }
912
+
913
+ return {
914
+ nodes,
915
+ edges,
916
+ task: String(entry.task || args.task || ''),
917
+ warnings,
918
+ };
919
+ }
920
+
921
+ /**
922
+ * Apply an in-place patch to an existing plan: update/add/remove nodes and
923
+ * edges without losing untouched nodes. Preserves `'lead'` as a valid edge
924
+ * source so newly added branches can wire directly from the entry Lead.
925
+ */
926
+ export function applyPatch(plan, args) {
927
+ const nodes = withoutEntry(plan.nodes).map((n) => ({ ...n }));
928
+ const byId = new Map(nodes.map((n) => [n.id, n]));
929
+ const ALLOWED = ['label', 'role', 'provider', 'model', 'reasoning', 'preset', 'keepSession', 'memoryChildId', 'structured', 'fallbackModel', 'fallbackProvider'];
930
+ const touched = [];
931
+ const patchWarnings = [];
932
+ for (const patch of args && Array.isArray(args.nodes) ? args.nodes : []) {
933
+ if (!patch || typeof patch.id !== 'string') continue;
934
+ // 'lead' is the reserved entry node and is never edited here.
935
+ if (patch.id === 'lead') {
936
+ patchWarnings.push('入口节点 lead 不可通过 nodes[] 修改,请改用顶层 task / refs 参数。');
937
+ continue;
938
+ }
939
+ const existing = byId.get(patch.id);
940
+ if (existing) {
941
+ for (const key of ALLOWED) {
942
+ if (patch[key] !== undefined) existing[key] = patch[key];
943
+ }
944
+ if (patch.kind !== undefined) existing.kind = normalizeKind(patch.kind);
945
+ if (existing.kind === 'condition') existing.preset = 'minimal';
946
+ if (patch.branches !== undefined) {
947
+ const nb = normalizeBranches(patch.branches);
948
+ if (nb) existing.branches = nb;
949
+ else delete existing.branches;
950
+ }
951
+ if (patch.multiMatch !== undefined) {
952
+ if (patch.multiMatch) existing.multiMatch = true;
953
+ else delete existing.multiMatch;
954
+ }
955
+ if (patch.refs !== undefined) {
956
+ const nr = normalizeRefs(patch.refs);
957
+ if (nr) existing.refs = nr;
958
+ else delete existing.refs;
959
+ }
960
+ touched.push(patch.id);
961
+ } else {
962
+ const created = {
963
+ id: patch.id,
964
+ kind: normalizeKind(patch.kind),
965
+ label: patch.label || patch.id,
966
+ role: '', provider: '', model: '', reasoning: '', preset: 'standard',
967
+ structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
968
+ };
969
+ for (const key of ALLOWED) {
970
+ if (patch[key] !== undefined) created[key] = patch[key];
971
+ }
972
+ created.preset = (created.kind === 'condition' || created.preset === 'minimal') ? 'minimal' : 'standard';
973
+ if (created.kind === 'condition' && patch.branches !== undefined) {
974
+ const nb = normalizeBranches(patch.branches);
975
+ if (nb) created.branches = nb;
976
+ }
977
+ if (created.kind === 'condition' && patch.multiMatch === true) {
978
+ created.multiMatch = true;
979
+ }
980
+ if (patch.refs !== undefined) {
981
+ const nr = normalizeRefs(patch.refs);
982
+ if (nr) created.refs = nr;
983
+ }
984
+ nodes.push(created);
985
+ byId.set(created.id, created);
986
+ touched.push(created.id);
987
+ }
988
+ }
989
+ const removed = new Set(Array.isArray(args && args.removeNodes) ? args.removeNodes : []);
990
+ if (removed.has('lead')) {
991
+ patchWarnings.push('入口节点 lead 不能删除,已自动忽略。');
992
+ removed.delete('lead');
993
+ }
994
+ const keptNodes = nodes.filter((n) => !removed.has(n.id));
995
+ const keptIds = new Set(keptNodes.map((n) => n.id));
996
+ const rawRemoveEdges = Array.isArray(args && args.removeEdges) ? args.removeEdges : [];
997
+ const matchesRemovedEdge = (edge) => rawRemoveEdges.some((r) => {
998
+ if (!r || String(r.from) !== edge.from || String(r.to) !== edge.to) return false;
999
+ if (r.type && r.type !== edge.type) return false;
1000
+ const rb = normalizeBranch(r.branch);
1001
+ if (rb && rb !== normalizeBranch(edge.branch)) return false;
1002
+ return true;
1003
+ });
1004
+ let edges = (Array.isArray(plan.edges) ? plan.edges : [])
1005
+ .filter((e) => !matchesRemovedEdge(e) && !removed.has(e.from) && !removed.has(e.to))
1006
+ .map((e) => ({ ...e }));
1007
+ const droppedEdges = [];
1008
+ for (const edge of Array.isArray(args && args.edges) ? args.edges : []) {
1009
+ if (!edge || typeof edge.from !== 'string' || typeof edge.to !== 'string') continue;
1010
+ const validFrom = edge.from === 'lead' || keptIds.has(edge.from);
1011
+ const validTo = keptIds.has(edge.to);
1012
+ if (edge.from === edge.to || edge.to === 'lead' || !validFrom || !validTo) {
1013
+ droppedEdges.push(edge.from + ' → ' + edge.to);
1014
+ continue;
1015
+ }
1016
+ const type = ['prompt', 'structured', 'session-ref'].includes(edge.type) ? edge.type : 'prompt';
1017
+ const branch = normalizeBranch(edge.branch);
1018
+ const existingEdge = edges.find((e) => e.from === edge.from && e.to === edge.to && e.type === type && normalizeBranch(e.branch) === branch);
1019
+ if (existingEdge) {
1020
+ if (edge.loop === true) {
1021
+ existingEdge.loop = true;
1022
+ existingEdge.maxIterations = normalizeMaxIterations(edge.maxIterations !== undefined ? edge.maxIterations : existingEdge.maxIterations);
1023
+ } else if (edge.loop === false) {
1024
+ delete existingEdge.loop;
1025
+ delete existingEdge.maxIterations;
1026
+ }
1027
+ continue;
1028
+ }
1029
+ const nextEdge = { from: edge.from, to: edge.to, type };
1030
+ if (branch) nextEdge.branch = branch;
1031
+ if (edge.loop === true) {
1032
+ nextEdge.loop = true;
1033
+ nextEdge.maxIterations = normalizeMaxIterations(edge.maxIterations);
1034
+ }
1035
+ edges.push(nextEdge);
1036
+ }
1037
+ if (droppedEdges.length) {
1038
+ patchWarnings.push('以下新增连线因节点 ID 不存在、自环或指向入口 Lead 已被忽略:' + droppedEdges.join('、'));
1039
+ }
1040
+ const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
1041
+ for (const node of keptNodes) {
1042
+ node.structured = structuredSources.has(node.id);
1043
+ }
1044
+ const taskPatched = typeof (args && args.task) === 'string';
1045
+ const nextTask = taskPatched ? args.task : String(plan.task || '');
1046
+ const refsPatched = args && args.refs !== undefined;
1047
+ const nextRefs = refsPatched ? normalizeRefs(args.refs) : normalizeRefs(plan.refs);
1048
+ const nextPlan = { ...plan, task: nextTask, nodes: keptNodes, edges };
1049
+ if (nextRefs) nextPlan.refs = nextRefs;
1050
+ else delete nextPlan.refs;
1051
+ return {
1052
+ plan: nextPlan,
1053
+ touched,
1054
+ taskPatched,
1055
+ refsPatched,
1056
+ warnings: patchWarnings,
1057
+ removed: Array.from(removed),
1058
+ removeEdges: rawRemoveEdges
1059
+ .filter((r) => r && typeof r.from === 'string' && typeof r.to === 'string')
1060
+ .map((r) => {
1061
+ const item = { from: r.from, to: r.to };
1062
+ if (r.type) item.type = r.type;
1063
+ const rb = normalizeBranch(r.branch);
1064
+ if (rb) item.branch = rb;
1065
+ return item;
1066
+ }),
1067
+ };
1068
+ }