dsh-workflow-canvas 1.0.2 → 1.2.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 +33 -16
- package/README.zh.md +33 -16
- package/client.js +1334 -317
- package/docs/DETAIL.md +21 -10
- package/docs/MECHANISM.md +7 -7
- package/docs/MECHANISM.zh.md +7 -7
- package/docs/images/add-node-shift-a.gif +0 -0
- package/docs/images/canvas-demo-zh.png +0 -0
- package/docs/images/canvas-demo.png +0 -0
- package/docs/images/chat-patch-canvas.gif +0 -0
- package/docs/images/condition-switch-run.gif +0 -0
- package/docs/images/connect-and-cut.gif +0 -0
- package/docs/images/node-condition-en.png +0 -0
- package/docs/images/node-condition-zh.png +0 -0
- package/docs/images/node-config.gif +0 -0
- package/docs/images/node-entry-en.png +0 -0
- package/docs/images/node-entry-zh.png +0 -0
- package/docs/images/node-lead-en.png +0 -0
- package/docs/images/node-lead-zh.png +0 -0
- package/docs/images/node-subagent-en.png +0 -0
- package/docs/images/node-subagent-zh.png +0 -0
- package/docs/images/parallel-and-inspect.gif +0 -0
- package/index.js +738 -78
- package/package.json +1 -1
- package/skills/workflow-canvas/SKILL.md +3 -2
package/index.js
CHANGED
|
@@ -132,16 +132,208 @@ function downstreamLabels(plan, node) {
|
|
|
132
132
|
.filter(Boolean);
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
-
function
|
|
136
|
-
|
|
135
|
+
function normalizeKind(rawKind) {
|
|
136
|
+
if (rawKind === 'lead') return 'lead';
|
|
137
|
+
if (rawKind === 'condition') return 'condition';
|
|
138
|
+
return 'agent';
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function normalizeBranch(rawBranch) {
|
|
142
|
+
if (rawBranch === true) return 'true';
|
|
143
|
+
if (rawBranch === false) return 'false';
|
|
144
|
+
if (typeof rawBranch !== 'string') return '';
|
|
145
|
+
return rawBranch.trim();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const DEFAULT_BINARY_BRANCHES = [
|
|
149
|
+
{ id: 'true', label: '是' },
|
|
150
|
+
{ id: 'false', label: '否' },
|
|
151
|
+
];
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Normalize a condition node's branch list (2–5 entries).
|
|
155
|
+
* Accepts either string arrays (e.g. `['通过', '小修', '重做']`) or `{ id, label }` objects.
|
|
156
|
+
* Returns `null` when the node uses the default binary `true`/`false` pair.
|
|
157
|
+
*/
|
|
158
|
+
function normalizeBranches(rawBranches) {
|
|
159
|
+
if (!Array.isArray(rawBranches) || rawBranches.length < 2) return null;
|
|
160
|
+
const out = [];
|
|
161
|
+
const used = new Set();
|
|
162
|
+
for (let i = 0; i < Math.min(16, rawBranches.length); i += 1) {
|
|
163
|
+
const item = rawBranches[i];
|
|
164
|
+
let id = '';
|
|
165
|
+
let label = '';
|
|
166
|
+
if (typeof item === 'string') {
|
|
167
|
+
label = item.trim();
|
|
168
|
+
id = label;
|
|
169
|
+
} else if (item && typeof item === 'object') {
|
|
170
|
+
id = typeof item.id === 'string' ? item.id.trim() : '';
|
|
171
|
+
label = typeof item.label === 'string' ? item.label.trim() : '';
|
|
172
|
+
if (!id) id = label;
|
|
173
|
+
if (!label) label = id;
|
|
174
|
+
}
|
|
175
|
+
if (!id) id = 'case_' + (i + 1);
|
|
176
|
+
if (!label) label = '分支 ' + (i + 1);
|
|
177
|
+
let uniq = id;
|
|
178
|
+
let suffix = 2;
|
|
179
|
+
while (used.has(uniq)) { uniq = id + '_' + suffix; suffix += 1; }
|
|
180
|
+
used.add(uniq);
|
|
181
|
+
out.push({ id: uniq, label });
|
|
182
|
+
}
|
|
183
|
+
return out.length >= 2 ? out : null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function conditionBranches(node) {
|
|
187
|
+
const custom = normalizeBranches(node && node.branches);
|
|
188
|
+
const multiMatch = Boolean(node && node.multiMatch);
|
|
189
|
+
if (custom) return { branches: custom, isDefaultBinary: false, multiMatch };
|
|
190
|
+
return { branches: DEFAULT_BINARY_BRANCHES, isDefaultBinary: !multiMatch, multiMatch };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function edgeKey(e) {
|
|
194
|
+
return String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Parse a condition node's structured or text output into
|
|
199
|
+
* `{ branches, branchLabels, branch, branchLabel, pass, reason }`.
|
|
200
|
+
* Supports:
|
|
201
|
+
* - default binary `{ pass: boolean }`
|
|
202
|
+
* - single-match `switch/case` (`{ branches: [id] }` or `{ branch: id }`, or `[]` when none match)
|
|
203
|
+
* - multi-match parallel fan-out (`multiMatch: true`, `{ branches: [id1, id2, ...] }` or `[]`)
|
|
204
|
+
*/
|
|
205
|
+
function parseConditionDecision(result, fallbackText, nodeOrBranches) {
|
|
206
|
+
const { branches, isDefaultBinary, multiMatch } = Array.isArray(nodeOrBranches)
|
|
207
|
+
? { branches: normalizeBranches(nodeOrBranches) || DEFAULT_BINARY_BRANCHES, isDefaultBinary: !normalizeBranches(nodeOrBranches), multiMatch: false }
|
|
208
|
+
: conditionBranches(nodeOrBranches);
|
|
209
|
+
|
|
210
|
+
const resolveByToken = (token) => {
|
|
211
|
+
const t = String(token || '').trim();
|
|
212
|
+
if (!t) return null;
|
|
213
|
+
const exactId = branches.find((b) => b.id === t);
|
|
214
|
+
if (exactId) return exactId;
|
|
215
|
+
const exactLabel = branches.find((b) => b.label === t);
|
|
216
|
+
if (exactLabel) return exactLabel;
|
|
217
|
+
const lower = t.toLowerCase();
|
|
218
|
+
const ci = branches.find((b) => b.id.toLowerCase() === lower || b.label.toLowerCase() === lower);
|
|
219
|
+
return ci || null;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const makeDecision = (pickedList, reason) => {
|
|
223
|
+
const seen = new Set();
|
|
224
|
+
const uniq = [];
|
|
225
|
+
for (const item of pickedList) {
|
|
226
|
+
if (!item || seen.has(item.id)) continue;
|
|
227
|
+
seen.add(item.id);
|
|
228
|
+
uniq.push(item);
|
|
229
|
+
}
|
|
230
|
+
const finalList = multiMatch ? uniq : uniq.slice(0, 1);
|
|
231
|
+
const first = finalList[0] || null;
|
|
232
|
+
return {
|
|
233
|
+
branches: finalList.map((b) => b.id),
|
|
234
|
+
branchLabels: finalList.map((b) => b.label),
|
|
235
|
+
branch: first ? first.id : '',
|
|
236
|
+
branchLabel: first ? first.label : '',
|
|
237
|
+
pass: isDefaultBinary ? Boolean(first && first.id === 'true') : finalList.length > 0,
|
|
238
|
+
reason: String(reason || ''),
|
|
239
|
+
};
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const tryObj = (obj) => {
|
|
243
|
+
if (!obj || typeof obj !== 'object') return null;
|
|
244
|
+
if (Array.isArray(obj.branches)) {
|
|
245
|
+
const hits = obj.branches.map(resolveByToken).filter(Boolean);
|
|
246
|
+
return makeDecision(hits, obj.reason);
|
|
247
|
+
}
|
|
248
|
+
if (typeof obj.branch === 'string') {
|
|
249
|
+
const trimmed = obj.branch.trim();
|
|
250
|
+
if (!trimmed || /^(none|null|无|都不满足|未命中)$/i.test(trimmed)) {
|
|
251
|
+
return makeDecision([], obj.reason);
|
|
252
|
+
}
|
|
253
|
+
const hit = resolveByToken(trimmed);
|
|
254
|
+
if (hit) return makeDecision([hit], obj.reason);
|
|
255
|
+
}
|
|
256
|
+
if (typeof obj.pass === 'boolean') {
|
|
257
|
+
const picked = obj.pass ? branches[0] : branches[branches.length - 1];
|
|
258
|
+
return makeDecision([picked], obj.reason);
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
const fromStructured = tryObj(result && result.structured);
|
|
264
|
+
if (fromStructured) return fromStructured;
|
|
265
|
+
|
|
266
|
+
const raw = String(fallbackText || '').trim();
|
|
267
|
+
const start = raw.indexOf('{');
|
|
268
|
+
const end = raw.lastIndexOf('}');
|
|
269
|
+
if (start !== -1 && end > start) {
|
|
270
|
+
try {
|
|
271
|
+
const fromJson = tryObj(JSON.parse(raw.slice(start, end + 1)));
|
|
272
|
+
if (fromJson) return fromJson;
|
|
273
|
+
} catch (_e) { /* fall through */ }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (isDefaultBinary) {
|
|
277
|
+
if (/^(true|yes|pass|通过|是)\b/i.test(raw)) return makeDecision([branches[0]], raw.slice(0, 200));
|
|
278
|
+
return makeDecision([branches[1]], raw.slice(0, 200) || '未能解析布尔判断,默认走「否」分支');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Multi-way text fallback: collect matching branch ids/labels; return empty [] if none match.
|
|
282
|
+
const lowerRaw = raw.toLowerCase();
|
|
283
|
+
const matched = [];
|
|
284
|
+
for (const b of branches) {
|
|
285
|
+
if (lowerRaw.includes(b.id.toLowerCase()) || lowerRaw.includes(b.label.toLowerCase())) {
|
|
286
|
+
matched.push(b);
|
|
287
|
+
if (!multiMatch) break;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return makeDecision(matched, raw.slice(0, 200) || (matched.length ? '' : '未命中任何分支,已跳过后续分支'));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function briefFor(plan, node, results, failedMap, prunedSet) {
|
|
294
|
+
const ups = upstreamOf(plan, node).filter((u) => !(prunedSet && prunedSet.has(u.from.id)));
|
|
137
295
|
const downs = downstreamLabels(plan, node);
|
|
138
296
|
const head = [];
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
297
|
+
if (node.kind === 'condition') {
|
|
298
|
+
const outEdges = (plan.edges || []).filter((e) => e.from === node.id);
|
|
299
|
+
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
300
|
+
const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
|
|
301
|
+
head.push('【工作流条件判断节点】你负责判断当前工作流接下来走哪条分支(「' + node.label + '」)。');
|
|
302
|
+
head.push('【总任务】' + plan.task);
|
|
303
|
+
if (isDefaultBinary) {
|
|
304
|
+
const yesTargets = outEdges.filter((e) => (normalizeBranch(e.branch) || 'true') === 'true').map((e) => (byId.get(e.to) || {}).label || e.to);
|
|
305
|
+
const noTargets = outEdges.filter((e) => normalizeBranch(e.branch) === 'false').map((e) => (byId.get(e.to) || {}).label || e.to);
|
|
306
|
+
head.push('【判断条件】' + (node.role || '判断上游步骤是否执行成功并达到预期;成功返回 true,失败或未达标返回 false。'));
|
|
307
|
+
head.push('【分支去向】pass=true(是)→ ' + (yesTargets.join('、') || '(无)') + ';pass=false(否)→ ' + (noTargets.join('、') || '(无)'));
|
|
308
|
+
head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"pass": true/false, "reason": "一句话理由"}。');
|
|
309
|
+
} else {
|
|
310
|
+
const branchLines = branches.map((b, idx) => {
|
|
311
|
+
const targets = outEdges
|
|
312
|
+
.filter((e) => {
|
|
313
|
+
const eb = normalizeBranch(e.branch);
|
|
314
|
+
return eb ? eb === b.id : idx === 0;
|
|
315
|
+
})
|
|
316
|
+
.map((e) => (byId.get(e.to) || {}).label || e.to);
|
|
317
|
+
const tag = b.label === b.id ? '"' + b.id + '"' : '"' + b.id + '"(' + b.label + ')';
|
|
318
|
+
return '- ' + tag + ' → ' + (targets.join('、') || '(无下游)');
|
|
319
|
+
});
|
|
320
|
+
head.push('【判断规则】' + (node.role || (multiMatch
|
|
321
|
+
? '根据上游结果选出所有满足条件的分支(可多选并行);若均不满足返回空数组。'
|
|
322
|
+
: '根据上游结果选出最匹配的一条分支;若均不满足返回空数组(如有「其他/兜底」分支则选它)。')));
|
|
323
|
+
head.push('【匹配模式】' + (multiMatch
|
|
324
|
+
? '多选并行(可返回 0 条、1 条或多条分支 id)'
|
|
325
|
+
: '单选分流(最多返回 1 条最匹配的分支 id;均不满足返回空数组 [])'));
|
|
326
|
+
head.push('【可选分支】\n' + branchLines.join('\n'));
|
|
327
|
+
head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"branches": ["<分支id>"], "reason": "一句话理由"};若没有任何分支满足,返回 {"branches": [], "reason": "..."}。');
|
|
328
|
+
}
|
|
329
|
+
} else {
|
|
330
|
+
head.push('【工作流节点】你在一个多步工作流里负责「' + node.label + '」这一步(子代理)。');
|
|
331
|
+
if (ups.length === 0) head.push('【总任务】' + plan.task);
|
|
332
|
+
head.push('【职责】' + (node.role || node.label));
|
|
333
|
+
if (ups.length) head.push('【上游】' + ups.map((u) => u.from.label).join('、') + ' 已交付结果给你(见下文)。');
|
|
334
|
+
head.push('【下游】' + (downs.length ? downs.join('、') + ' 会使用你的输出。' : '你是终点,结果会直接交付给用户。'));
|
|
335
|
+
head.push('【要求】只完成你这一步;最终回复只输出简洁、可直接被下游或 Lead 消费的交付报告(结论、改动清单、关键接口/路径),不要包含思考独白、过程叙述或对其他并行节点的评价。若因环境或权限受限未能生成预期产物,必须在开头显式标注「【未完全交付】」并列出缺失项,不得把仅写脚本汇报为已完成。');
|
|
336
|
+
}
|
|
145
337
|
let text = head.join('\n') + '\n';
|
|
146
338
|
for (const u of ups) {
|
|
147
339
|
const value = results[u.from.id];
|
|
@@ -190,12 +382,13 @@ function isEmptyOutput(result) {
|
|
|
190
382
|
return text.trim().length === 0;
|
|
191
383
|
}
|
|
192
384
|
|
|
193
|
-
async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid, failedMap) {
|
|
385
|
+
async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid, failedMap, prunedSet) {
|
|
194
386
|
const childKey = (id) => String(sid || '') + '::' + id;
|
|
387
|
+
const isCondition = node.kind === 'condition';
|
|
195
388
|
const spec = {
|
|
196
389
|
provider: 'spawn',
|
|
197
390
|
label: node.label + '#' + node.id,
|
|
198
|
-
prompt: [{ type: 'text', text: briefFor(plan, node, results, failedMap) }],
|
|
391
|
+
prompt: [{ type: 'text', text: briefFor(plan, node, results, failedMap, prunedSet) }],
|
|
199
392
|
parent,
|
|
200
393
|
signal,
|
|
201
394
|
delivery: 'caller',
|
|
@@ -207,15 +400,45 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
207
400
|
if (model) agentOptions.model = model;
|
|
208
401
|
if (node.reasoning) agentOptions.reasoningEffort = node.reasoning;
|
|
209
402
|
if (Object.keys(agentOptions).length) spec.agentOptions = agentOptions;
|
|
210
|
-
if (
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
403
|
+
if (isCondition) {
|
|
404
|
+
const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
|
|
405
|
+
spec.agentPreset = 'minimal';
|
|
406
|
+
spec.outputSchema = isDefaultBinary
|
|
407
|
+
? {
|
|
408
|
+
type: 'object',
|
|
409
|
+
properties: {
|
|
410
|
+
pass: { type: 'boolean', description: 'true to follow the Yes/Pass branch, false to follow the No/Fail branch.' },
|
|
411
|
+
reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
|
|
412
|
+
},
|
|
413
|
+
required: ['pass', 'reason'],
|
|
414
|
+
additionalProperties: false,
|
|
415
|
+
}
|
|
416
|
+
: {
|
|
417
|
+
type: 'object',
|
|
418
|
+
properties: {
|
|
419
|
+
branches: {
|
|
420
|
+
type: 'array',
|
|
421
|
+
items: { type: 'string', enum: branches.map((b) => b.id) },
|
|
422
|
+
description: multiMatch
|
|
423
|
+
? 'All matching branch ids to execute in parallel (empty array if none match).'
|
|
424
|
+
: 'At most one best-matching branch id (empty array if none match).',
|
|
425
|
+
},
|
|
426
|
+
reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
|
|
427
|
+
},
|
|
428
|
+
required: ['branches', 'reason'],
|
|
429
|
+
additionalProperties: false,
|
|
430
|
+
};
|
|
431
|
+
} else {
|
|
432
|
+
if (node.preset) spec.agentPreset = node.preset;
|
|
433
|
+
const wantsStructured = Boolean(node.structured)
|
|
434
|
+
|| (plan.edges || []).some((e) => e.from === node.id && e.type === 'structured');
|
|
435
|
+
if (wantsStructured) {
|
|
436
|
+
spec.outputSchema = {
|
|
437
|
+
type: 'object',
|
|
438
|
+
additionalProperties: true,
|
|
439
|
+
description: 'Return the result as a JSON object so downstream steps can consume it.',
|
|
440
|
+
};
|
|
441
|
+
}
|
|
219
442
|
}
|
|
220
443
|
|
|
221
444
|
const run = async (childId) => {
|
|
@@ -241,12 +464,17 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
241
464
|
const message = String((error && error.message) || error);
|
|
242
465
|
return { ok: false, text: '运行失败:' + message, reason: 'run-failed' };
|
|
243
466
|
}
|
|
244
|
-
|
|
467
|
+
const outText = textOf(result);
|
|
468
|
+
const outcome = {
|
|
245
469
|
ok: !failed(result),
|
|
246
|
-
text:
|
|
470
|
+
text: outText,
|
|
247
471
|
reason: result && result.stopReason,
|
|
248
472
|
empty: isEmptyOutput(result),
|
|
249
473
|
};
|
|
474
|
+
if (isCondition) {
|
|
475
|
+
outcome.decision = parseConditionDecision(result, outText, node);
|
|
476
|
+
}
|
|
477
|
+
return outcome;
|
|
250
478
|
} finally {
|
|
251
479
|
try { await activation.dispose(); } catch (_e) { /* ignore */ }
|
|
252
480
|
}
|
|
@@ -293,20 +521,28 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
293
521
|
return started;
|
|
294
522
|
}
|
|
295
523
|
|
|
296
|
-
async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap) {
|
|
524
|
+
async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet) {
|
|
297
525
|
const continueFrom = (plan.edges || [])
|
|
298
|
-
.filter((e) => e.to === node.id && e.type === 'session-ref')
|
|
526
|
+
.filter((e) => e.to === node.id && e.type === 'session-ref' && !(prunedSet && prunedSet.has(e.from)))
|
|
299
527
|
.map((e) => liveChild.get(String(sid || '') + '::' + e.from)
|
|
300
528
|
|| childByNode.get(String(sid || '') + '::' + e.from))
|
|
301
529
|
.find((id) => typeof id === 'string');
|
|
302
530
|
|
|
303
531
|
if (continueFrom) {
|
|
304
|
-
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap);
|
|
305
|
-
if (continued.ok)
|
|
532
|
+
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet);
|
|
533
|
+
if (continued.ok) {
|
|
534
|
+
const out = { ok: true, empty: Boolean(continued.empty), text: continued.text + '\n(已在上游会话中继续)' };
|
|
535
|
+
if (continued.decision) out.decision = continued.decision;
|
|
536
|
+
return out;
|
|
537
|
+
}
|
|
306
538
|
}
|
|
307
539
|
|
|
308
|
-
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap);
|
|
309
|
-
if (first.ok)
|
|
540
|
+
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet);
|
|
541
|
+
if (first.ok) {
|
|
542
|
+
const out = { ok: true, empty: Boolean(first.empty), text: first.text };
|
|
543
|
+
if (first.decision) out.decision = first.decision;
|
|
544
|
+
return out;
|
|
545
|
+
}
|
|
310
546
|
if (!node.fallbackModel && !node.fallbackProvider) {
|
|
311
547
|
const reason = first.reason || 'unknown';
|
|
312
548
|
return { ok: false, empty: false, reason, text: first.text + '\n(失败原因:' + reason + ',未配置备用模型)' };
|
|
@@ -314,8 +550,12 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
314
550
|
const retry = await spawnOnce(scope, plan, node, results, parent, signal, {
|
|
315
551
|
provider: node.fallbackProvider,
|
|
316
552
|
model: node.fallbackModel,
|
|
317
|
-
}, undefined, sid, failedMap);
|
|
318
|
-
if (retry.ok)
|
|
553
|
+
}, undefined, sid, failedMap, prunedSet);
|
|
554
|
+
if (retry.ok) {
|
|
555
|
+
const out = { ok: true, empty: Boolean(retry.empty), text: retry.text + '\n(已用备用模型重试成功)' };
|
|
556
|
+
if (retry.decision) out.decision = retry.decision;
|
|
557
|
+
return out;
|
|
558
|
+
}
|
|
319
559
|
const reason = retry.reason || 'unknown';
|
|
320
560
|
return { ok: false, empty: false, reason, text: retry.text + '\n(重试仍失败:' + reason + ')' };
|
|
321
561
|
}
|
|
@@ -440,7 +680,7 @@ function normalizeCanvas(args) {
|
|
|
440
680
|
for (const raw of rawNodes) {
|
|
441
681
|
if (!raw || typeof raw !== 'object') continue;
|
|
442
682
|
counter += 1;
|
|
443
|
-
const kind = raw.kind
|
|
683
|
+
const kind = normalizeKind(raw.kind);
|
|
444
684
|
const wantsEntry = !hasExplicitLead && (raw.id === 'lead' || (raw.entry === true && kind === 'lead'));
|
|
445
685
|
let id = wantsEntry
|
|
446
686
|
? 'lead'
|
|
@@ -452,8 +692,11 @@ function normalizeCanvas(args) {
|
|
|
452
692
|
}
|
|
453
693
|
usedIds.add(id);
|
|
454
694
|
if (id === 'lead') hasExplicitLead = true;
|
|
455
|
-
const
|
|
456
|
-
|
|
695
|
+
const defaultLabel = kind === 'lead'
|
|
696
|
+
? 'Lead 步骤 ' + counter
|
|
697
|
+
: (kind === 'condition' ? '条件判断 ' + counter : 'Node ' + counter);
|
|
698
|
+
const label = String(raw.label || defaultLabel);
|
|
699
|
+
const nodeObj = {
|
|
457
700
|
id,
|
|
458
701
|
kind: id === 'lead' ? 'lead' : kind,
|
|
459
702
|
label,
|
|
@@ -469,7 +712,13 @@ function normalizeCanvas(args) {
|
|
|
469
712
|
fallbackProvider: String(raw.fallbackProvider || ''),
|
|
470
713
|
x: 0,
|
|
471
714
|
y: 0,
|
|
472
|
-
}
|
|
715
|
+
};
|
|
716
|
+
if (nodeObj.kind === 'condition') {
|
|
717
|
+
const customBranches = normalizeBranches(raw.branches);
|
|
718
|
+
if (customBranches) nodeObj.branches = customBranches;
|
|
719
|
+
if (raw.multiMatch === true) nodeObj.multiMatch = true;
|
|
720
|
+
}
|
|
721
|
+
nodes.push(nodeObj);
|
|
473
722
|
if (raw.ref && !idByRef.has(String(raw.ref))) idByRef.set(String(raw.ref), id);
|
|
474
723
|
if (raw.id && !idByRef.has(String(raw.id))) idByRef.set(String(raw.id), id);
|
|
475
724
|
idByRef.set(id, id);
|
|
@@ -484,7 +733,10 @@ function normalizeCanvas(args) {
|
|
|
484
733
|
const to = idByRef.get(String(raw.to)) || String(raw.to);
|
|
485
734
|
if ((from !== 'lead' && !ids.has(from)) || !ids.has(to) || from === to || to === 'lead') continue;
|
|
486
735
|
const type = ['prompt', 'structured', 'session-ref'].includes(raw.type) ? raw.type : 'prompt';
|
|
487
|
-
|
|
736
|
+
const branch = normalizeBranch(raw.branch);
|
|
737
|
+
const edgeObj = { id: 'e' + edges.length, from, to, type };
|
|
738
|
+
if (branch) edgeObj.branch = branch;
|
|
739
|
+
edges.push(edgeObj);
|
|
488
740
|
}
|
|
489
741
|
|
|
490
742
|
let entry = nodes.find((n) => n.id === 'lead');
|
|
@@ -580,11 +832,21 @@ function applyPatch(plan, args) {
|
|
|
580
832
|
for (const key of ALLOWED) {
|
|
581
833
|
if (patch[key] !== undefined) existing[key] = patch[key];
|
|
582
834
|
}
|
|
835
|
+
if (patch.kind !== undefined) existing.kind = normalizeKind(patch.kind);
|
|
836
|
+
if (patch.branches !== undefined) {
|
|
837
|
+
const nb = normalizeBranches(patch.branches);
|
|
838
|
+
if (nb) existing.branches = nb;
|
|
839
|
+
else delete existing.branches;
|
|
840
|
+
}
|
|
841
|
+
if (patch.multiMatch !== undefined) {
|
|
842
|
+
if (patch.multiMatch) existing.multiMatch = true;
|
|
843
|
+
else delete existing.multiMatch;
|
|
844
|
+
}
|
|
583
845
|
touched.push(patch.id);
|
|
584
846
|
} else {
|
|
585
847
|
const created = {
|
|
586
848
|
id: patch.id,
|
|
587
|
-
kind: patch.kind
|
|
849
|
+
kind: normalizeKind(patch.kind),
|
|
588
850
|
label: patch.label || patch.id,
|
|
589
851
|
role: '', provider: '', model: '', reasoning: '', preset: 'standard',
|
|
590
852
|
structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
|
|
@@ -593,6 +855,13 @@ function applyPatch(plan, args) {
|
|
|
593
855
|
if (patch[key] !== undefined) created[key] = patch[key];
|
|
594
856
|
}
|
|
595
857
|
created.preset = created.preset === 'minimal' ? 'minimal' : 'standard';
|
|
858
|
+
if (created.kind === 'condition' && patch.branches !== undefined) {
|
|
859
|
+
const nb = normalizeBranches(patch.branches);
|
|
860
|
+
if (nb) created.branches = nb;
|
|
861
|
+
}
|
|
862
|
+
if (created.kind === 'condition' && patch.multiMatch === true) {
|
|
863
|
+
created.multiMatch = true;
|
|
864
|
+
}
|
|
596
865
|
nodes.push(created);
|
|
597
866
|
byId.set(created.id, created);
|
|
598
867
|
touched.push(created.id);
|
|
@@ -603,10 +872,13 @@ function applyPatch(plan, args) {
|
|
|
603
872
|
const keptNodes = nodes.filter((n) => !removed.has(n.id));
|
|
604
873
|
const keptIds = new Set(keptNodes.map((n) => n.id));
|
|
605
874
|
const rawRemoveEdges = Array.isArray(args && args.removeEdges) ? args.removeEdges : [];
|
|
606
|
-
const matchesRemovedEdge = (edge) => rawRemoveEdges.some((r) =>
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
875
|
+
const matchesRemovedEdge = (edge) => rawRemoveEdges.some((r) => {
|
|
876
|
+
if (!r || String(r.from) !== edge.from || String(r.to) !== edge.to) return false;
|
|
877
|
+
if (r.type && r.type !== edge.type) return false;
|
|
878
|
+
const rb = normalizeBranch(r.branch);
|
|
879
|
+
if (rb && rb !== normalizeBranch(edge.branch)) return false;
|
|
880
|
+
return true;
|
|
881
|
+
});
|
|
610
882
|
let edges = (Array.isArray(plan.edges) ? plan.edges : [])
|
|
611
883
|
.filter((e) => !matchesRemovedEdge(e) && !removed.has(e.from) && !removed.has(e.to))
|
|
612
884
|
.map((e) => ({ ...e }));
|
|
@@ -617,8 +889,11 @@ function applyPatch(plan, args) {
|
|
|
617
889
|
const validTo = keptIds.has(edge.to);
|
|
618
890
|
if (!validFrom || !validTo) continue;
|
|
619
891
|
const type = ['prompt', 'structured', 'session-ref'].includes(edge.type) ? edge.type : 'prompt';
|
|
620
|
-
|
|
621
|
-
edges.
|
|
892
|
+
const branch = normalizeBranch(edge.branch);
|
|
893
|
+
if (edges.some((e) => e.from === edge.from && e.to === edge.to && e.type === type && normalizeBranch(e.branch) === branch)) continue;
|
|
894
|
+
const nextEdge = { from: edge.from, to: edge.to, type };
|
|
895
|
+
if (branch) nextEdge.branch = branch;
|
|
896
|
+
edges.push(nextEdge);
|
|
622
897
|
}
|
|
623
898
|
const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
|
|
624
899
|
for (const node of keptNodes) {
|
|
@@ -633,7 +908,13 @@ function applyPatch(plan, args) {
|
|
|
633
908
|
removed: Array.from(removed),
|
|
634
909
|
removeEdges: rawRemoveEdges
|
|
635
910
|
.filter((r) => r && typeof r.from === 'string' && typeof r.to === 'string')
|
|
636
|
-
.map((r) =>
|
|
911
|
+
.map((r) => {
|
|
912
|
+
const item = { from: r.from, to: r.to };
|
|
913
|
+
if (r.type) item.type = r.type;
|
|
914
|
+
const rb = normalizeBranch(r.branch);
|
|
915
|
+
if (rb) item.branch = rb;
|
|
916
|
+
return item;
|
|
917
|
+
}),
|
|
637
918
|
};
|
|
638
919
|
}
|
|
639
920
|
|
|
@@ -656,6 +937,29 @@ function publishCanvas(scope, sessionId, canvas) {
|
|
|
656
937
|
}
|
|
657
938
|
}
|
|
658
939
|
|
|
940
|
+
/**
|
|
941
|
+
* Publish live run-state telemetry (condition decisions, pruned nodes, blocked edges,
|
|
942
|
+
* waitingLead) to `.dsh/canvas/<sessionId>.run.json` so the sidebar canvas can
|
|
943
|
+
* visualize branch routing and verdict reasons without touching the canvas definition file.
|
|
944
|
+
*/
|
|
945
|
+
function publishRunState(scope, sessionId, runState) {
|
|
946
|
+
try {
|
|
947
|
+
if (!sessionId) return false;
|
|
948
|
+
const live = scope && scope.sessions && scope.sessions.get(sessionId);
|
|
949
|
+
const root = live && live.header && live.header.cwd;
|
|
950
|
+
if (!root) return false;
|
|
951
|
+
const dir = join(root, '.dsh', 'canvas');
|
|
952
|
+
mkdirSync(dir, { recursive: true });
|
|
953
|
+
writeFileSync(join(dir, sessionId + '.run.json'), JSON.stringify({
|
|
954
|
+
...(runState || {}),
|
|
955
|
+
at: Date.now(),
|
|
956
|
+
}), 'utf8');
|
|
957
|
+
return true;
|
|
958
|
+
} catch (_e) {
|
|
959
|
+
return false;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
659
963
|
async function runPlan(scope, args, exec) {
|
|
660
964
|
const agent = exec && exec.agent;
|
|
661
965
|
const sid = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
@@ -680,25 +984,38 @@ function inspectPlan(sid) {
|
|
|
680
984
|
};
|
|
681
985
|
}
|
|
682
986
|
const plan = payload.plan || {};
|
|
683
|
-
const nodes = withoutEntry(plan.nodes).map((n) =>
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
987
|
+
const nodes = withoutEntry(plan.nodes).map((n) => {
|
|
988
|
+
const item = {
|
|
989
|
+
id: String(n.id || ''),
|
|
990
|
+
kind: normalizeKind(n.kind),
|
|
991
|
+
label: String(n.label || n.id || ''),
|
|
992
|
+
role: String(n.role || ''),
|
|
993
|
+
provider: String(n.provider || ''),
|
|
994
|
+
model: String(n.model || ''),
|
|
995
|
+
reasoning: String(n.reasoning || ''),
|
|
996
|
+
preset: n.preset === 'minimal' ? 'minimal' : 'standard',
|
|
997
|
+
keepSession: Boolean(n.keepSession),
|
|
998
|
+
structured: Boolean(n.structured),
|
|
999
|
+
fallbackModel: String(n.fallbackModel || ''),
|
|
1000
|
+
fallbackProvider: String(n.fallbackProvider || ''),
|
|
1001
|
+
};
|
|
1002
|
+
if (item.kind === 'condition') {
|
|
1003
|
+
const nb = normalizeBranches(n.branches);
|
|
1004
|
+
if (nb) item.branches = nb;
|
|
1005
|
+
if (n.multiMatch) item.multiMatch = true;
|
|
1006
|
+
}
|
|
1007
|
+
return item;
|
|
1008
|
+
});
|
|
1009
|
+
const edges = Array.isArray(plan.edges) ? plan.edges.map((e) => {
|
|
1010
|
+
const out = {
|
|
1011
|
+
from: String(e.from || ''),
|
|
1012
|
+
to: String(e.to || ''),
|
|
1013
|
+
type: String(e.type || 'prompt'),
|
|
1014
|
+
};
|
|
1015
|
+
const branch = normalizeBranch(e.branch);
|
|
1016
|
+
if (branch) out.branch = branch;
|
|
1017
|
+
return out;
|
|
1018
|
+
}) : [];
|
|
702
1019
|
const out = {
|
|
703
1020
|
hasCanvas: true,
|
|
704
1021
|
enabled: Boolean(payload.enabled),
|
|
@@ -749,7 +1066,7 @@ function buildActiveCanvasContext(sid) {
|
|
|
749
1066
|
|
|
750
1067
|
const preview = nodes
|
|
751
1068
|
.slice(0, 8)
|
|
752
|
-
.map((n) => (n.kind === 'lead' ? '〔Lead〕' : '') + (n.label || n.id))
|
|
1069
|
+
.map((n) => (n.kind === 'lead' ? '〔Lead〕' : (n.kind === 'condition' ? '〔条件〕' : '')) + (n.label || n.id))
|
|
753
1070
|
.join(' → ') + (nodes.length > 8 ? ' …' : '');
|
|
754
1071
|
const hasTask = Boolean(String((plan && plan.task) || '').trim());
|
|
755
1072
|
const prefix = String(sid) + '::';
|
|
@@ -858,6 +1175,10 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
858
1175
|
labels: { ...(base.labels || {}) },
|
|
859
1176
|
failed: { ...(base.failed || {}) },
|
|
860
1177
|
emptyOutputs: { ...(base.emptyOutputs || {}) },
|
|
1178
|
+
blockedEdges: new Set(Array.from(base.blockedEdges || [])),
|
|
1179
|
+
pruned: new Set(Array.from(base.pruned || []).filter((id) => byId.has(id))),
|
|
1180
|
+
decisions: { ...(base.decisions || {}) },
|
|
1181
|
+
fallbackLinks: Array.isArray(base.fallbackLinks) ? base.fallbackLinks.map((fl) => ({ ...fl })) : [],
|
|
861
1182
|
waitingLead: null,
|
|
862
1183
|
};
|
|
863
1184
|
// Build forward adjacency to invalidate seed nodes and all their downstream dependents.
|
|
@@ -889,21 +1210,55 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
889
1210
|
}
|
|
890
1211
|
for (const id of invalid) {
|
|
891
1212
|
state.done.delete(id);
|
|
1213
|
+
state.pruned.delete(id);
|
|
892
1214
|
delete state.results[id];
|
|
893
1215
|
delete state.labels[id];
|
|
894
1216
|
delete state.failed[id];
|
|
895
1217
|
delete state.emptyOutputs[id];
|
|
1218
|
+
delete state.decisions[id];
|
|
1219
|
+
}
|
|
1220
|
+
for (const e of plan.edges || []) {
|
|
1221
|
+
if (e && invalid.has(e.from)) state.blockedEdges.delete(edgeKey(e));
|
|
896
1222
|
}
|
|
897
|
-
|
|
1223
|
+
state.fallbackLinks = state.fallbackLinks.filter((fl) => !invalid.has(fl.from) && !invalid.has(fl.to));
|
|
1224
|
+
reused = Array.from(state.done).filter((id) => !state.pruned.has(id)).map((id) => labelOf.get(id) || id);
|
|
898
1225
|
runBySession.set(sid, state);
|
|
899
1226
|
}
|
|
900
1227
|
}
|
|
901
1228
|
|
|
902
1229
|
if (!state || state.sig !== sig) {
|
|
903
|
-
state = {
|
|
1230
|
+
state = {
|
|
1231
|
+
sig,
|
|
1232
|
+
done: new Set(),
|
|
1233
|
+
results: {},
|
|
1234
|
+
labels: {},
|
|
1235
|
+
failed: {},
|
|
1236
|
+
emptyOutputs: {},
|
|
1237
|
+
blockedEdges: new Set(),
|
|
1238
|
+
pruned: new Set(),
|
|
1239
|
+
decisions: {},
|
|
1240
|
+
fallbackLinks: [],
|
|
1241
|
+
waitingLead: null,
|
|
1242
|
+
};
|
|
904
1243
|
runBySession.set(sid, state);
|
|
905
1244
|
}
|
|
906
1245
|
if (!state.emptyOutputs) state.emptyOutputs = {};
|
|
1246
|
+
if (!state.blockedEdges) state.blockedEdges = new Set();
|
|
1247
|
+
if (!state.pruned) state.pruned = new Set();
|
|
1248
|
+
if (!state.decisions) state.decisions = {};
|
|
1249
|
+
if (!state.fallbackLinks) state.fallbackLinks = [];
|
|
1250
|
+
|
|
1251
|
+
const emitRunState = (status, waitingLead) => {
|
|
1252
|
+
if (!sid) return;
|
|
1253
|
+
publishRunState(scope, sid, {
|
|
1254
|
+
status,
|
|
1255
|
+
decisions: { ...state.decisions },
|
|
1256
|
+
pruned: Array.from(state.pruned || []),
|
|
1257
|
+
blockedEdges: Array.from(state.blockedEdges || []),
|
|
1258
|
+
waitingLead: waitingLead ? { id: waitingLead.id, label: waitingLead.label } : null,
|
|
1259
|
+
});
|
|
1260
|
+
};
|
|
1261
|
+
emitRunState('running', null);
|
|
907
1262
|
|
|
908
1263
|
const snapshotLastRun = (haltedFlag) => {
|
|
909
1264
|
if (!sid) return;
|
|
@@ -914,13 +1269,150 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
914
1269
|
labels: { ...state.labels },
|
|
915
1270
|
failed: { ...state.failed },
|
|
916
1271
|
emptyOutputs: { ...state.emptyOutputs },
|
|
1272
|
+
blockedEdges: new Set(state.blockedEdges),
|
|
1273
|
+
pruned: new Set(state.pruned),
|
|
1274
|
+
decisions: { ...state.decisions },
|
|
1275
|
+
fallbackLinks: state.fallbackLinks.map((fl) => ({ ...fl })),
|
|
917
1276
|
halted: Boolean(haltedFlag),
|
|
918
1277
|
});
|
|
919
1278
|
};
|
|
920
|
-
const depsOf = (node) =>
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
1279
|
+
const depsOf = (node) => {
|
|
1280
|
+
const out = new Set();
|
|
1281
|
+
for (const e of plan.edges || []) {
|
|
1282
|
+
if (e.to === node.id
|
|
1283
|
+
&& e.from !== 'lead'
|
|
1284
|
+
&& !state.blockedEdges.has(edgeKey(e))
|
|
1285
|
+
&& !state.pruned.has(e.from)
|
|
1286
|
+
&& byId.has(e.from)) {
|
|
1287
|
+
out.add(e.from);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
for (const fl of state.fallbackLinks || []) {
|
|
1291
|
+
if (fl.to === node.id && byId.has(fl.from)) out.add(fl.from);
|
|
1292
|
+
}
|
|
1293
|
+
return Array.from(out);
|
|
1294
|
+
};
|
|
1295
|
+
const nearestDownstreamLead = (startId) => {
|
|
1296
|
+
const fwd = new Map();
|
|
1297
|
+
for (const e of plan.edges || []) {
|
|
1298
|
+
if (!e || !e.from || !e.to) continue;
|
|
1299
|
+
if (!fwd.has(e.from)) fwd.set(e.from, []);
|
|
1300
|
+
fwd.get(e.from).push(e.to);
|
|
1301
|
+
}
|
|
1302
|
+
const seen = new Set([startId]);
|
|
1303
|
+
const queue = [startId];
|
|
1304
|
+
for (let i = 0; i < queue.length; i += 1) {
|
|
1305
|
+
const cur = queue[i];
|
|
1306
|
+
for (const next of fwd.get(cur) || []) {
|
|
1307
|
+
if (seen.has(next)) continue;
|
|
1308
|
+
seen.add(next);
|
|
1309
|
+
const candidate = byId.get(next);
|
|
1310
|
+
if (candidate && candidate.kind === 'lead' && !state.done.has(candidate.id)) {
|
|
1311
|
+
return candidate;
|
|
1312
|
+
}
|
|
1313
|
+
queue.push(next);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
return null;
|
|
1317
|
+
};
|
|
1318
|
+
const branchSkippedList = () => Array.from(state.pruned).map((id) => labelOf.get(id) || id);
|
|
1319
|
+
const ancestorsOf = (targetId) => {
|
|
1320
|
+
const parents = new Map();
|
|
1321
|
+
for (const e of plan.edges || []) {
|
|
1322
|
+
if (!e || !e.from || !e.to) continue;
|
|
1323
|
+
if (!parents.has(e.to)) parents.set(e.to, []);
|
|
1324
|
+
parents.get(e.to).push(e.from);
|
|
1325
|
+
}
|
|
1326
|
+
const seen = new Set();
|
|
1327
|
+
const stack = [targetId];
|
|
1328
|
+
while (stack.length) {
|
|
1329
|
+
const cur = stack.pop();
|
|
1330
|
+
for (const p of parents.get(cur) || []) {
|
|
1331
|
+
if (!seen.has(p)) { seen.add(p); stack.push(p); }
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
return seen;
|
|
1335
|
+
};
|
|
1336
|
+
const recomputeBranchPrune = () => {
|
|
1337
|
+
// Re-evaluate reachability from entry Lead over non-blocked edges so diamond
|
|
1338
|
+
// convergence nodes stay active, while side-channel edges from ancestors of a
|
|
1339
|
+
// condition node (e.g. A --session-ref--> N) cannot bypass a blocked branch gate.
|
|
1340
|
+
const condAncestors = new Map();
|
|
1341
|
+
const blockedSources = new Map();
|
|
1342
|
+
for (const e of plan.edges || []) {
|
|
1343
|
+
if (!e || !e.from || !e.to) continue;
|
|
1344
|
+
if (!state.blockedEdges.has(edgeKey(e))) continue;
|
|
1345
|
+
if (!blockedSources.has(e.to)) blockedSources.set(e.to, new Set());
|
|
1346
|
+
blockedSources.get(e.to).add(e.from);
|
|
1347
|
+
if (!condAncestors.has(e.from)) condAncestors.set(e.from, ancestorsOf(e.from));
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
const gatedBy = new Map();
|
|
1351
|
+
const addGates = (nodeId, condIds) => {
|
|
1352
|
+
if (!gatedBy.has(nodeId)) gatedBy.set(nodeId, new Set());
|
|
1353
|
+
const set = gatedBy.get(nodeId);
|
|
1354
|
+
for (const c of condIds) set.add(c);
|
|
1355
|
+
};
|
|
1356
|
+
for (const [toId, cSet] of blockedSources.entries()) addGates(toId, cSet);
|
|
1357
|
+
|
|
1358
|
+
const isBypassEdge = (e) => {
|
|
1359
|
+
const directGates = blockedSources.get(e.to);
|
|
1360
|
+
if (directGates) {
|
|
1361
|
+
for (const cId of directGates) {
|
|
1362
|
+
if ((condAncestors.get(cId) || new Set()).has(e.from)) return true;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
if (e.type === 'session-ref') {
|
|
1366
|
+
const inherited = gatedBy.get(e.to);
|
|
1367
|
+
if (inherited) {
|
|
1368
|
+
for (const cId of inherited) {
|
|
1369
|
+
if ((condAncestors.get(cId) || new Set()).has(e.from)) return true;
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
return false;
|
|
1374
|
+
};
|
|
1375
|
+
|
|
1376
|
+
for (let pass = 0; pass <= runnable.length; pass += 1) {
|
|
1377
|
+
const adj = new Map();
|
|
1378
|
+
for (const e of plan.edges || []) {
|
|
1379
|
+
if (!e || !e.from || !e.to) continue;
|
|
1380
|
+
if (state.blockedEdges.has(edgeKey(e))) continue;
|
|
1381
|
+
if (state.pruned.has(e.from)) continue;
|
|
1382
|
+
if (isBypassEdge(e)) continue;
|
|
1383
|
+
if (!adj.has(e.from)) adj.set(e.from, []);
|
|
1384
|
+
adj.get(e.from).push(e.to);
|
|
1385
|
+
}
|
|
1386
|
+
for (const fl of state.fallbackLinks || []) {
|
|
1387
|
+
if (!fl || !fl.from || !fl.to || state.pruned.has(fl.from)) continue;
|
|
1388
|
+
if (!adj.has(fl.from)) adj.set(fl.from, []);
|
|
1389
|
+
adj.get(fl.from).push(fl.to);
|
|
1390
|
+
}
|
|
1391
|
+
const active = new Set(['lead']);
|
|
1392
|
+
const queue = ['lead'];
|
|
1393
|
+
for (let i = 0; i < queue.length; i += 1) {
|
|
1394
|
+
const cur = queue[i];
|
|
1395
|
+
for (const next of adj.get(cur) || []) {
|
|
1396
|
+
if (!active.has(next)) { active.add(next); queue.push(next); }
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
let addedAny = false;
|
|
1400
|
+
for (const n of runnable) {
|
|
1401
|
+
if (!state.done.has(n.id) && !inFlight.has(n.id) && !active.has(n.id)) {
|
|
1402
|
+
state.pruned.add(n.id);
|
|
1403
|
+
state.done.add(n.id);
|
|
1404
|
+
addedAny = true;
|
|
1405
|
+
const gates = gatedBy.get(n.id);
|
|
1406
|
+
if (gates && gates.size) {
|
|
1407
|
+
for (const e of plan.edges || []) {
|
|
1408
|
+
if (e && e.from === n.id && e.to) addGates(e.to, gates);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
if (!addedAny) break;
|
|
1414
|
+
}
|
|
1415
|
+
};
|
|
924
1416
|
|
|
925
1417
|
let leadResult = typeof opts.leadResult === 'string' ? opts.leadResult : undefined;
|
|
926
1418
|
const rawMaxParallel = opts.maxParallel !== undefined ? opts.maxParallel : plan.maxParallel;
|
|
@@ -944,7 +1436,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
944
1436
|
&& depsOf(n).every((id) => state.done.has(id)));
|
|
945
1437
|
for (const node of candidates) {
|
|
946
1438
|
if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) break;
|
|
947
|
-
const promise = spawnNode(scope, plan, node, state.results, agent, exec.signal, sid, state.failed)
|
|
1439
|
+
const promise = spawnNode(scope, plan, node, state.results, agent, exec.signal, sid, state.failed, state.pruned)
|
|
948
1440
|
.then(
|
|
949
1441
|
(outcome) => ({ node, outcome }),
|
|
950
1442
|
(err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
|
|
@@ -955,6 +1447,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
955
1447
|
|
|
956
1448
|
for (;;) {
|
|
957
1449
|
if (isAborted()) {
|
|
1450
|
+
emitRunState('halted', null);
|
|
958
1451
|
if (sid) runBySession.delete(sid);
|
|
959
1452
|
return { error: '工作流执行已取消。' };
|
|
960
1453
|
}
|
|
@@ -963,6 +1456,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
963
1456
|
// results are dropped before returning the halted report.
|
|
964
1457
|
if (haltedReason && inFlight.size === 0) {
|
|
965
1458
|
snapshotLastRun(true);
|
|
1459
|
+
emitRunState('halted', null);
|
|
966
1460
|
if (sid) runBySession.delete(sid);
|
|
967
1461
|
saveStore();
|
|
968
1462
|
return {
|
|
@@ -972,6 +1466,8 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
972
1466
|
labels: state.labels,
|
|
973
1467
|
failed: Object.values(state.failed),
|
|
974
1468
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1469
|
+
decisions: Object.values(state.decisions),
|
|
1470
|
+
branchSkipped: branchSkippedList(),
|
|
975
1471
|
reused,
|
|
976
1472
|
skipped,
|
|
977
1473
|
};
|
|
@@ -979,6 +1475,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
979
1475
|
const remaining = runnable.filter((n) => !state.done.has(n.id));
|
|
980
1476
|
if (!remaining.length) {
|
|
981
1477
|
snapshotLastRun(false);
|
|
1478
|
+
emitRunState('done', null);
|
|
982
1479
|
runBySession.delete(sid);
|
|
983
1480
|
saveStore();
|
|
984
1481
|
return {
|
|
@@ -987,6 +1484,8 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
987
1484
|
labels: state.labels,
|
|
988
1485
|
failed: Object.values(state.failed),
|
|
989
1486
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1487
|
+
decisions: Object.values(state.decisions),
|
|
1488
|
+
branchSkipped: branchSkippedList(),
|
|
990
1489
|
reused,
|
|
991
1490
|
skipped,
|
|
992
1491
|
};
|
|
@@ -998,22 +1497,114 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
998
1497
|
const { node, outcome } = await Promise.race(inFlight.values());
|
|
999
1498
|
inFlight.delete(node.id);
|
|
1000
1499
|
if (isAborted()) {
|
|
1500
|
+
emitRunState('halted', null);
|
|
1001
1501
|
if (sid) runBySession.delete(sid);
|
|
1002
1502
|
return { error: '工作流执行已取消。' };
|
|
1003
1503
|
}
|
|
1004
|
-
state.results[node.id] = outcome.text;
|
|
1005
1504
|
state.labels[node.id] = node.label;
|
|
1505
|
+
if (node.kind === 'condition') {
|
|
1506
|
+
const { branches, isDefaultBinary } = conditionBranches(node);
|
|
1507
|
+
if (!outcome.ok) {
|
|
1508
|
+
const failReason = outcome.reason || 'unknown';
|
|
1509
|
+
state.failed[node.id] = { id: node.id, label: node.label, reason: failReason };
|
|
1510
|
+
state.decisions[node.id] = {
|
|
1511
|
+
id: node.id,
|
|
1512
|
+
label: node.label,
|
|
1513
|
+
branches: [],
|
|
1514
|
+
branchLabels: [],
|
|
1515
|
+
branch: '',
|
|
1516
|
+
branchLabel: '',
|
|
1517
|
+
pass: false,
|
|
1518
|
+
failed: true,
|
|
1519
|
+
reason: outcome.text || ('运行失败:' + failReason),
|
|
1520
|
+
};
|
|
1521
|
+
state.results[node.id] = '【条件节点自身执行失败:' + failReason + '】' + (outcome.text ? ' ' + outcome.text : '');
|
|
1522
|
+
state.done.add(node.id);
|
|
1523
|
+
// Never guess a branch when the judge itself crashed: block all outgoing branches.
|
|
1524
|
+
for (const e of plan.edges || []) {
|
|
1525
|
+
if (e && e.from === node.id) state.blockedEdges.add(edgeKey(e));
|
|
1526
|
+
}
|
|
1527
|
+
const fallbackLead = nearestDownstreamLead(node.id);
|
|
1528
|
+
if (fallbackLead) {
|
|
1529
|
+
state.fallbackLinks.push({ from: node.id, to: fallbackLead.id, label: node.label, failed: true, reason: failReason });
|
|
1530
|
+
state.decisions[node.id].fallbackLead = fallbackLead.label;
|
|
1531
|
+
state.results[node.id] += '(未擅自选择分支,已直接转交至最近 Lead「' + fallbackLead.label + '」)';
|
|
1532
|
+
recomputeBranchPrune();
|
|
1533
|
+
emitRunState('running', null);
|
|
1534
|
+
} else {
|
|
1535
|
+
recomputeBranchPrune();
|
|
1536
|
+
emitRunState('running', null);
|
|
1537
|
+
haltedReason = '条件节点「' + node.label + '」自身执行失败(' + failReason
|
|
1538
|
+
+ '),为避免误走分支已停止下游执行。';
|
|
1539
|
+
}
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
const fallbackBranch = branches[0];
|
|
1543
|
+
const dec = outcome.decision || {
|
|
1544
|
+
branches: [fallbackBranch.id],
|
|
1545
|
+
branchLabels: [fallbackBranch.label],
|
|
1546
|
+
branch: fallbackBranch.id,
|
|
1547
|
+
branchLabel: fallbackBranch.label,
|
|
1548
|
+
pass: isDefaultBinary ? fallbackBranch.id === 'true' : true,
|
|
1549
|
+
reason: outcome.text || '',
|
|
1550
|
+
};
|
|
1551
|
+
const matchedIds = Array.isArray(dec.branches) ? dec.branches : (dec.branch ? [dec.branch] : []);
|
|
1552
|
+
const matchedLabels = Array.isArray(dec.branchLabels) ? dec.branchLabels : (dec.branchLabel ? [dec.branchLabel] : matchedIds);
|
|
1553
|
+
const pass = Boolean(dec.pass);
|
|
1554
|
+
const reason = dec.reason || '';
|
|
1555
|
+
state.decisions[node.id] = {
|
|
1556
|
+
id: node.id,
|
|
1557
|
+
label: node.label,
|
|
1558
|
+
branches: matchedIds,
|
|
1559
|
+
branchLabels: matchedLabels,
|
|
1560
|
+
branch: matchedIds[0] || '',
|
|
1561
|
+
branchLabel: matchedLabels[0] || '',
|
|
1562
|
+
pass,
|
|
1563
|
+
reason,
|
|
1564
|
+
};
|
|
1565
|
+
state.results[node.id] = (matchedIds.length === 0
|
|
1566
|
+
? '【条件判断:未命中任何分支】'
|
|
1567
|
+
: (isDefaultBinary
|
|
1568
|
+
? (pass ? '【条件判断:是 / 通过】' : '【条件判断:否 / 未通过】')
|
|
1569
|
+
: ('【条件分支:' + matchedLabels.join('、') + '】')))
|
|
1570
|
+
+ (reason ? ' ' + reason : '');
|
|
1571
|
+
state.done.add(node.id);
|
|
1572
|
+
const matchedSet = new Set(matchedIds);
|
|
1573
|
+
for (const e of plan.edges || []) {
|
|
1574
|
+
if (!e || e.from !== node.id) continue;
|
|
1575
|
+
const edgeBranch = normalizeBranch(e.branch) || branches[0].id;
|
|
1576
|
+
if (!matchedSet.has(edgeBranch)) state.blockedEdges.add(edgeKey(e));
|
|
1577
|
+
}
|
|
1578
|
+
if (matchedIds.length === 0) {
|
|
1579
|
+
// When no condition branch matched, skip intermediate subagent branches
|
|
1580
|
+
// and jump directly to the nearest downstream Lead so the user/Lead is notified.
|
|
1581
|
+
const fallbackLead = nearestDownstreamLead(node.id);
|
|
1582
|
+
if (fallbackLead) {
|
|
1583
|
+
state.fallbackLinks.push({ from: node.id, to: fallbackLead.id, label: node.label });
|
|
1584
|
+
state.decisions[node.id].fallbackLead = fallbackLead.label;
|
|
1585
|
+
state.results[node.id] += '(已跳过中间分支,直接转交至最近 Lead「' + fallbackLead.label + '」)';
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
recomputeBranchPrune();
|
|
1589
|
+
emitRunState('running', null);
|
|
1590
|
+
continue;
|
|
1591
|
+
}
|
|
1592
|
+
state.results[node.id] = outcome.text;
|
|
1006
1593
|
if (!outcome.ok) {
|
|
1007
1594
|
state.failed[node.id] = { id: node.id, label: node.label, reason: outcome.reason || 'unknown' };
|
|
1008
1595
|
if (outcome.reason === 'activation-failed') activationFailCount += 1;
|
|
1009
1596
|
} else if (outcome.empty) {
|
|
1010
1597
|
state.emptyOutputs[node.id] = { id: node.id, label: node.label };
|
|
1011
1598
|
}
|
|
1012
|
-
|
|
1599
|
+
// If a failing node feeds a condition node, let the condition handle failure routing
|
|
1600
|
+
// instead of circuit-breaking the whole run prematurely.
|
|
1601
|
+
const routesToCondition = (plan.edges || []).some((e) => e && e.from === node.id
|
|
1602
|
+
&& byId.get(e.to) && byId.get(e.to).kind === 'condition');
|
|
1603
|
+
if (!routesToCondition && isPermissionFailure(outcome)) {
|
|
1013
1604
|
permBlocked.push(node.label || node.id);
|
|
1014
1605
|
haltedReason = '检测到权限/沙箱受限导致节点失败(' + permBlocked.join('、')
|
|
1015
1606
|
+ '),已熔断停止启动后续节点以防继续消耗额度。请先检查主对话左下角权限模式,放开后重新运行。';
|
|
1016
|
-
} else if (activationFailCount >= 2 && !haltedReason) {
|
|
1607
|
+
} else if (!routesToCondition && activationFailCount >= 2 && !haltedReason) {
|
|
1017
1608
|
haltedReason = '连续 ' + activationFailCount + ' 个子代理启动失败,已熔断停止后续节点以防继续消耗额度。请检查模型配置或主对话权限后重试。';
|
|
1018
1609
|
}
|
|
1019
1610
|
state.done.add(node.id);
|
|
@@ -1033,11 +1624,23 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1033
1624
|
|| childByNode.get(String(sid || '') + '::' + id)
|
|
1034
1625
|
|| null,
|
|
1035
1626
|
}));
|
|
1627
|
+
const jumpedEntries = (state.fallbackLinks || []).filter((fl) => fl.to === leadNode.id);
|
|
1628
|
+
const failedConds = jumpedEntries.filter((fl) => fl.failed).map((fl) => (fl.label || labelOf.get(fl.from) || fl.from) + '(' + (fl.reason || 'unknown') + ')');
|
|
1629
|
+
const unmatchedConds = jumpedEntries.filter((fl) => !fl.failed).map((fl) => fl.label || labelOf.get(fl.from) || fl.from);
|
|
1630
|
+
const fallbackParts = [];
|
|
1631
|
+
if (failedConds.length) {
|
|
1632
|
+
fallbackParts.push('⚠ 条件节点(' + failedConds.join('、') + ')自身执行失败,未擅自选择分支,已跳过中间分支直接转交给你处理;也可调用 canvas_workflow({ retryFailed: true }) 复用上游缓存并只重跑该条件节点及其下游。');
|
|
1633
|
+
}
|
|
1634
|
+
if (unmatchedConds.length) {
|
|
1635
|
+
fallbackParts.push('⚠ 条件节点(' + unmatchedConds.join('、') + ')所有分支均未命中,已跳过中间分支直接转交给你处理。');
|
|
1636
|
+
}
|
|
1637
|
+
const fallbackNotice = fallbackParts.join(' ');
|
|
1036
1638
|
const hasDownstreamWork = remaining.some((n) => n.id !== leadNode.id);
|
|
1037
1639
|
if (!hasDownstreamWork && leadResult === undefined) {
|
|
1038
1640
|
// Terminal Lead: zero downstream nodes remain, so complete the run directly
|
|
1039
1641
|
// and hand off final review/delivery to the Lead without a redundant extra turn.
|
|
1040
1642
|
snapshotLastRun(false);
|
|
1643
|
+
emitRunState('done', null);
|
|
1041
1644
|
if (sid) runBySession.delete(sid);
|
|
1042
1645
|
saveStore();
|
|
1043
1646
|
return {
|
|
@@ -1051,10 +1654,13 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1051
1654
|
labels: state.labels,
|
|
1052
1655
|
failed: Object.values(state.failed),
|
|
1053
1656
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1657
|
+
decisions: Object.values(state.decisions),
|
|
1658
|
+
branchSkipped: branchSkippedList(),
|
|
1054
1659
|
sessions: leadSessions,
|
|
1055
1660
|
reused,
|
|
1056
1661
|
skipped,
|
|
1057
|
-
hint: '
|
|
1662
|
+
hint: (fallbackNotice ? fallbackNotice + ' ' : '')
|
|
1663
|
+
+ '所有子代理已完成。最后一步由你(Lead 本体)按要求完成终审/汇总后直接向用户交付即可,无需再次调用 canvas_workflow。',
|
|
1058
1664
|
};
|
|
1059
1665
|
}
|
|
1060
1666
|
if (leadResult === undefined) {
|
|
@@ -1063,6 +1669,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1063
1669
|
label: leadNode.label,
|
|
1064
1670
|
role: leadNode.role || leadNode.label,
|
|
1065
1671
|
};
|
|
1672
|
+
emitRunState('need-lead', state.waitingLead);
|
|
1066
1673
|
return {
|
|
1067
1674
|
status: 'need-lead',
|
|
1068
1675
|
node: {
|
|
@@ -1074,8 +1681,11 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1074
1681
|
labels: state.labels,
|
|
1075
1682
|
failed: Object.values(state.failed),
|
|
1076
1683
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
1684
|
+
decisions: Object.values(state.decisions),
|
|
1685
|
+
branchSkipped: branchSkippedList(),
|
|
1077
1686
|
sessions: leadSessions,
|
|
1078
|
-
hint:
|
|
1687
|
+
hint: (fallbackNotice ? fallbackNotice + ' ' : '')
|
|
1688
|
+
+ '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需从头重跑可传 reset: true。',
|
|
1079
1689
|
};
|
|
1080
1690
|
}
|
|
1081
1691
|
state.waitingLead = null;
|
|
@@ -1169,6 +1779,7 @@ export function apply(ctx) {
|
|
|
1169
1779
|
if (!id) return { kind: 'error', text: 'no session' };
|
|
1170
1780
|
canvasBySession.set(id, parsePayload(rawInput));
|
|
1171
1781
|
runBySession.delete(id);
|
|
1782
|
+
publishRunState(ctx, id, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
|
|
1172
1783
|
saveStore();
|
|
1173
1784
|
return { kind: 'success', text: 'canvas synced' };
|
|
1174
1785
|
} catch (error) {
|
|
@@ -1199,7 +1810,7 @@ export function apply(ctx) {
|
|
|
1199
1810
|
id: { type: 'string' },
|
|
1200
1811
|
ref: { type: 'string', description: 'Temporary handle for edges; the tool assigns the real id.' },
|
|
1201
1812
|
entry: { type: 'boolean', description: 'Optional: set true only if customizing the entry Lead node itself.' },
|
|
1202
|
-
kind: { type: 'string', enum: ['agent', 'lead'] },
|
|
1813
|
+
kind: { type: 'string', enum: ['agent', 'lead', 'condition'] },
|
|
1203
1814
|
label: { type: 'string' },
|
|
1204
1815
|
role: { type: 'string' },
|
|
1205
1816
|
task: { type: 'string' },
|
|
@@ -1211,6 +1822,15 @@ export function apply(ctx) {
|
|
|
1211
1822
|
keepSession: { type: 'boolean' },
|
|
1212
1823
|
fallbackModel: { type: 'string' },
|
|
1213
1824
|
fallbackProvider: { type: 'string' },
|
|
1825
|
+
branches: {
|
|
1826
|
+
type: 'array',
|
|
1827
|
+
description: 'Optional (condition nodes only): custom switch/case branch names (strings or { id, label }, 2 or more). Omit for default true/false.',
|
|
1828
|
+
items: {},
|
|
1829
|
+
},
|
|
1830
|
+
multiMatch: {
|
|
1831
|
+
type: 'boolean',
|
|
1832
|
+
description: 'Optional (condition nodes only): true to allow matching multiple branches in parallel; false (default) picks at most 1 branch (or none if unmatched).',
|
|
1833
|
+
},
|
|
1214
1834
|
},
|
|
1215
1835
|
},
|
|
1216
1836
|
},
|
|
@@ -1222,6 +1842,7 @@ export function apply(ctx) {
|
|
|
1222
1842
|
from: { type: 'string' },
|
|
1223
1843
|
to: { type: 'string' },
|
|
1224
1844
|
type: { type: 'string', enum: ['prompt', 'structured', 'session-ref'] },
|
|
1845
|
+
branch: { type: 'string', description: 'For edges leaving a condition node: "true" / "false" (default binary) or one of the condition node branch ids.' },
|
|
1225
1846
|
},
|
|
1226
1847
|
required: ['from', 'to'],
|
|
1227
1848
|
},
|
|
@@ -1245,7 +1866,9 @@ export function apply(ctx) {
|
|
|
1245
1866
|
const canvas = v.canvas || {};
|
|
1246
1867
|
const nodes = Array.isArray(canvas.nodes) ? canvas.nodes : [];
|
|
1247
1868
|
const edges = Array.isArray(canvas.edges) ? canvas.edges : [];
|
|
1248
|
-
const lines = nodes.map((n) => '- [' + n.id + '] '
|
|
1869
|
+
const lines = nodes.map((n) => '- [' + n.id + '] '
|
|
1870
|
+
+ (n.kind === 'lead' ? '〔Lead〕' : (n.kind === 'condition' ? '〔条件〕' : ''))
|
|
1871
|
+
+ n.label
|
|
1249
1872
|
+ (n.role ? ':' + n.role : ''));
|
|
1250
1873
|
const warnBlock = Array.isArray(v.warnings) && v.warnings.length
|
|
1251
1874
|
? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
|
|
@@ -1285,6 +1908,7 @@ export function apply(ctx) {
|
|
|
1285
1908
|
});
|
|
1286
1909
|
runBySession.delete(sid);
|
|
1287
1910
|
lastRunBySession.delete(sid);
|
|
1911
|
+
publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
|
|
1288
1912
|
saveStore();
|
|
1289
1913
|
}
|
|
1290
1914
|
return { canvas, delivered, warnings };
|
|
@@ -1342,6 +1966,7 @@ export function apply(ctx) {
|
|
|
1342
1966
|
const nextPlan = patched.plan;
|
|
1343
1967
|
canvasBySession.set(sid, { enabled: payload.enabled, plan: nextPlan });
|
|
1344
1968
|
runBySession.delete(sid);
|
|
1969
|
+
publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
|
|
1345
1970
|
saveStore();
|
|
1346
1971
|
const patchDoc = {
|
|
1347
1972
|
mode: 'merge',
|
|
@@ -1407,6 +2032,12 @@ export function apply(ctx) {
|
|
|
1407
2032
|
const nodeLines = (v.nodes || []).map((n) => {
|
|
1408
2033
|
const flags = [];
|
|
1409
2034
|
if (n.kind === 'lead') flags.push('Lead');
|
|
2035
|
+
if (n.kind === 'condition') {
|
|
2036
|
+
flags.push('条件' + (Array.isArray(n.branches) && n.branches.length >= 2
|
|
2037
|
+
? ':' + n.branches.map((b) => b.label || b.id).join('/')
|
|
2038
|
+
: ''));
|
|
2039
|
+
if (n.multiMatch) flags.push('多选');
|
|
2040
|
+
}
|
|
1410
2041
|
if (n.model) flags.push(n.model);
|
|
1411
2042
|
if (n.reasoning) flags.push('reasoning=' + n.reasoning);
|
|
1412
2043
|
if (n.preset === 'minimal') flags.push('minimal');
|
|
@@ -1416,7 +2047,8 @@ export function apply(ctx) {
|
|
|
1416
2047
|
+ (flags.length ? ' (' + flags.join(', ') + ')' : '')
|
|
1417
2048
|
+ (n.role ? ':' + n.role : '');
|
|
1418
2049
|
});
|
|
1419
|
-
const edgeLines = (v.edges || []).map((e) => '- ' + e.from
|
|
2050
|
+
const edgeLines = (v.edges || []).map((e) => '- ' + e.from
|
|
2051
|
+
+ ' --(' + e.type + (e.branch ? ':' + e.branch : '') + ')--> ' + e.to);
|
|
1420
2052
|
return [{
|
|
1421
2053
|
type: 'text',
|
|
1422
2054
|
text: head.join('\n')
|
|
@@ -1466,6 +2098,8 @@ export function apply(ctx) {
|
|
|
1466
2098
|
labels: { type: 'object' },
|
|
1467
2099
|
failed: { type: 'array' },
|
|
1468
2100
|
emptyOutputs: { type: 'array' },
|
|
2101
|
+
decisions: { type: 'array' },
|
|
2102
|
+
branchSkipped: { type: 'array' },
|
|
1469
2103
|
sessions: { type: 'array' },
|
|
1470
2104
|
reused: { type: 'array' },
|
|
1471
2105
|
skipped: { type: 'array' },
|
|
@@ -1490,6 +2124,26 @@ export function apply(ctx) {
|
|
|
1490
2124
|
? '\n\n⚠ 未返回交付文本的节点(请核查其实际产物,切勿直接当作已完成):'
|
|
1491
2125
|
+ v.emptyOutputs.map((e) => e.label || e.id).join('、')
|
|
1492
2126
|
: '';
|
|
2127
|
+
const decisionList = Array.isArray(v.decisions) && v.decisions.length
|
|
2128
|
+
? '\n\n条件分支判决:' + v.decisions.map((d) => {
|
|
2129
|
+
if (d.failed) {
|
|
2130
|
+
return (d.label || d.id) + ' → ⚠ 自身执行失败' + (d.reason ? '(' + d.reason + ')' : '');
|
|
2131
|
+
}
|
|
2132
|
+
const ids = Array.isArray(d.branches) ? d.branches : (d.branch ? [d.branch] : []);
|
|
2133
|
+
const labels = Array.isArray(d.branchLabels) ? d.branchLabels : (d.branchLabel ? [d.branchLabel] : ids);
|
|
2134
|
+
if (!ids.length) {
|
|
2135
|
+
return (d.label || d.id) + ' → 未命中任何分支' + (d.reason ? '(' + d.reason + ')' : '');
|
|
2136
|
+
}
|
|
2137
|
+
const isDefault = ids.length === 1
|
|
2138
|
+
&& (ids[0] === 'true' || ids[0] === 'false')
|
|
2139
|
+
&& (!labels[0] || labels[0] === '是' || labels[0] === '否' || labels[0] === 'Yes' || labels[0] === 'No');
|
|
2140
|
+
const chosen = isDefault ? (d.pass ? '✓ 是' : '✕ 否') : labels.join(' + ');
|
|
2141
|
+
return (d.label || d.id) + ' → ' + chosen + (d.reason ? '(' + d.reason + ')' : '');
|
|
2142
|
+
}).join(';')
|
|
2143
|
+
: '';
|
|
2144
|
+
const branchSkipNote = Array.isArray(v.branchSkipped) && v.branchSkipped.length
|
|
2145
|
+
? '\n\n条件未命中已跳过:' + v.branchSkipped.join('、')
|
|
2146
|
+
: '';
|
|
1493
2147
|
if (v.status === 'need-lead') {
|
|
1494
2148
|
const n = v.node || {};
|
|
1495
2149
|
const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
|
|
@@ -1501,10 +2155,12 @@ export function apply(ctx) {
|
|
|
1501
2155
|
type: 'text',
|
|
1502
2156
|
text: '需要你(Lead)完成「' + n.label + '」:' + n.role
|
|
1503
2157
|
+ '\n需要用到:' + ((n.needs && n.needs.length) ? n.needs.join('、') : '(无上游)')
|
|
2158
|
+
+ decisionList
|
|
1504
2159
|
+ failedList
|
|
1505
2160
|
+ emptyList
|
|
1506
2161
|
+ '\n\n已完成节点的结果:\n' + body
|
|
1507
2162
|
+ handover
|
|
2163
|
+
+ branchSkipNote
|
|
1508
2164
|
+ '\n\n' + (v.hint || ''),
|
|
1509
2165
|
}];
|
|
1510
2166
|
}
|
|
@@ -1526,16 +2182,18 @@ export function apply(ctx) {
|
|
|
1526
2182
|
type: 'text',
|
|
1527
2183
|
text: '所有子代理已完成,现在进入终审 Lead 步骤「' + fl.label + '」:' + fl.role
|
|
1528
2184
|
+ '\n需要用到:' + ((fl.needs && fl.needs.length) ? fl.needs.join('、') : '(无上游)')
|
|
2185
|
+
+ decisionList
|
|
1529
2186
|
+ failedList
|
|
1530
2187
|
+ emptyList
|
|
1531
2188
|
+ '\n\n已完成节点的结果:\n' + body
|
|
1532
2189
|
+ handover
|
|
2190
|
+
+ branchSkipNote
|
|
1533
2191
|
+ reusedNote
|
|
1534
2192
|
+ skip
|
|
1535
2193
|
+ '\n\n' + (v.hint || ''),
|
|
1536
2194
|
}];
|
|
1537
2195
|
}
|
|
1538
|
-
return [{ type: 'text', text: '画布执行完成。' + failedList + emptyList + '\n\n' + body + reusedNote + skip }];
|
|
2196
|
+
return [{ type: 'text', text: '画布执行完成。' + decisionList + failedList + emptyList + '\n\n' + body + branchSkipNote + reusedNote + skip }];
|
|
1539
2197
|
}
|
|
1540
2198
|
return [{ type: 'text', text: JSON.stringify(v) }];
|
|
1541
2199
|
},
|
|
@@ -1556,6 +2214,8 @@ export {
|
|
|
1556
2214
|
upstreamOf,
|
|
1557
2215
|
downstreamLabels,
|
|
1558
2216
|
briefFor,
|
|
2217
|
+
normalizeBranches,
|
|
2218
|
+
parseConditionDecision,
|
|
1559
2219
|
withoutEntry,
|
|
1560
2220
|
analyzeCanvasWarnings,
|
|
1561
2221
|
normalizeCanvas,
|