dsh-workflow-canvas 0.2.1 → 0.2.2
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/client.js +82 -14
- package/docs/MECHANISM.md +4 -4
- package/docs/MECHANISM.zh.md +5 -5
- package/index.js +231 -76
- package/package.json +1 -1
- package/skills/workflow-canvas/SKILL.md +25 -7
package/client.js
CHANGED
|
@@ -180,6 +180,9 @@ window.__ModuleLoader__.load({
|
|
|
180
180
|
fxStandard: '标准',
|
|
181
181
|
fxVivid: '炫酷',
|
|
182
182
|
tipLeadReady: '上游节点已全部完成,正等待在对话里拍板继续',
|
|
183
|
+
stDeadEnd: '无出边',
|
|
184
|
+
tipDeadEnd: '该子代理节点没有下游连线:若需把产出交给后续节点或终审 Lead,请从右侧端口连出',
|
|
185
|
+
singleModelHint: '当前仅 1 个可用模型,暂无其它备用路由',
|
|
183
186
|
importNone: '剪贴板里没有可识别的画布数据',
|
|
184
187
|
importBad: '画布数据格式不对',
|
|
185
188
|
tipSync: '把当前画布同步给 Host(会在对话里留一条同步记录)',
|
|
@@ -275,6 +278,9 @@ window.__ModuleLoader__.load({
|
|
|
275
278
|
fxStandard: 'Standard',
|
|
276
279
|
fxVivid: 'Vivid',
|
|
277
280
|
tipLeadReady: 'Upstream steps are done; waiting for Lead in chat',
|
|
281
|
+
stDeadEnd: 'No out-link',
|
|
282
|
+
tipDeadEnd: 'This subagent has no outgoing link: wire it to a downstream node or Lead so its output is consumed',
|
|
283
|
+
singleModelHint: 'Only 1 model available — no alternate fallback route',
|
|
278
284
|
importNone: 'No canvas data found in the clipboard',
|
|
279
285
|
importBad: 'Canvas data is malformed',
|
|
280
286
|
tipSync: 'Publish this canvas to the host (leaves one sync record in the chat)',
|
|
@@ -474,6 +480,13 @@ window.__ModuleLoader__.load({
|
|
|
474
480
|
color: C.dim, pointerEvents: 'none', zIndex: 3, whiteSpace: 'nowrap',
|
|
475
481
|
display: 'inline-flex', alignItems: 'center', gap: '3px',
|
|
476
482
|
},
|
|
483
|
+
warnChip: {
|
|
484
|
+
position: 'absolute', left: '12px', bottom: '4px', fontSize: '9px', lineHeight: '13px',
|
|
485
|
+
padding: '1px 5px', borderRadius: '999px',
|
|
486
|
+
color: '#d29922', background: 'rgba(210,153,34,0.14)', border: '1px solid rgba(210,153,34,0.55)',
|
|
487
|
+
pointerEvents: 'auto', zIndex: 5, whiteSpace: 'nowrap',
|
|
488
|
+
display: 'inline-flex', alignItems: 'center', gap: '2px',
|
|
489
|
+
},
|
|
477
490
|
statusBtn: {
|
|
478
491
|
position: 'absolute', right: '12px', bottom: '3px', fontSize: '10px', lineHeight: '14px',
|
|
479
492
|
padding: '1px 6px', borderRadius: '999px', border: '1px solid ' + C.border,
|
|
@@ -1305,6 +1318,8 @@ window.__ModuleLoader__.load({
|
|
|
1305
1318
|
edgesRef.current = edges;
|
|
1306
1319
|
const selectedIdsRef = useRef(selectedIds);
|
|
1307
1320
|
selectedIdsRef.current = selectedIds;
|
|
1321
|
+
const skipDirtyOnce = useRef(false);
|
|
1322
|
+
const staleChildIds = useRef(new Set());
|
|
1308
1323
|
|
|
1309
1324
|
useEffect(() => {
|
|
1310
1325
|
const stamp = applyStamp.current;
|
|
@@ -1312,8 +1327,13 @@ window.__ModuleLoader__.load({
|
|
|
1312
1327
|
saveDoc(sessionId, { nodes, edges, enabled }, stamp === null ? undefined : stamp);
|
|
1313
1328
|
}, [sessionId, nodes, edges, enabled]);
|
|
1314
1329
|
|
|
1315
|
-
// Any structural edit after enabling leaves the Host copy stale
|
|
1330
|
+
// Any structural edit after enabling leaves the Host copy stale,
|
|
1331
|
+
// except when the update came directly from the Host itself.
|
|
1316
1332
|
useEffect(() => {
|
|
1333
|
+
if (skipDirtyOnce.current) {
|
|
1334
|
+
skipDirtyOnce.current = false;
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1317
1337
|
if (enabled) setDirty(true);
|
|
1318
1338
|
}, [nodes, edges]);
|
|
1319
1339
|
|
|
@@ -1372,7 +1392,7 @@ window.__ModuleLoader__.load({
|
|
|
1372
1392
|
if (ack && ack.ok) {
|
|
1373
1393
|
lastSync.current = sig;
|
|
1374
1394
|
setDirty(false);
|
|
1375
|
-
|
|
1395
|
+
snapshotStaleCatalog();
|
|
1376
1396
|
flash(t('syncedToHost'));
|
|
1377
1397
|
} else {
|
|
1378
1398
|
flash(t('syncFailed'));
|
|
@@ -1418,6 +1438,26 @@ window.__ModuleLoader__.load({
|
|
|
1418
1438
|
|
|
1419
1439
|
const NODE_MARK = /#([^\s#]+)$/;
|
|
1420
1440
|
|
|
1441
|
+
/** Mark existing historical subagent sessions as stale before a fresh run. */
|
|
1442
|
+
const snapshotStaleCatalog = () => {
|
|
1443
|
+
try {
|
|
1444
|
+
const sessions = hostCtx && hostCtx.sessions;
|
|
1445
|
+
if (sessions && sessionId) {
|
|
1446
|
+
const state = sessions.list.getSnapshot();
|
|
1447
|
+
const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
|
|
1448
|
+
const catalog = proj && proj.values && proj.values.subagentCatalog;
|
|
1449
|
+
if (Array.isArray(catalog)) {
|
|
1450
|
+
const stale = new Set();
|
|
1451
|
+
for (const entry of catalog) {
|
|
1452
|
+
if (entry && entry.id) stale.add(entry.id);
|
|
1453
|
+
}
|
|
1454
|
+
staleChildIds.current = stale;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
} catch (_e) { /* ignore */ }
|
|
1458
|
+
setStatusById({});
|
|
1459
|
+
};
|
|
1460
|
+
|
|
1421
1461
|
const readCatalog = () => {
|
|
1422
1462
|
try {
|
|
1423
1463
|
const sessions = hostCtx && hostCtx.sessions;
|
|
@@ -1437,9 +1477,6 @@ window.__ModuleLoader__.load({
|
|
|
1437
1477
|
const child = state.byId && state.byId[entry.id];
|
|
1438
1478
|
const timingProj = state.projectionsBySession && state.projectionsBySession[entry.id];
|
|
1439
1479
|
const timing = timingProj && timingProj.values && timingProj.values.subagentTiming;
|
|
1440
|
-
if (child && child.running) nextStatus[nodeId] = 'running';
|
|
1441
|
-
else if (timing && timing.lastTurnCompleted === false) nextStatus[nodeId] = 'failed';
|
|
1442
|
-
else nextStatus[nodeId] = 'done';
|
|
1443
1480
|
if (entry.id) {
|
|
1444
1481
|
const prev = nextRuns[nodeId];
|
|
1445
1482
|
nextRuns[nodeId] = {
|
|
@@ -1449,6 +1486,13 @@ window.__ModuleLoader__.load({
|
|
|
1449
1486
|
count: prev ? prev.count + 1 : 1,
|
|
1450
1487
|
};
|
|
1451
1488
|
}
|
|
1489
|
+
if (child && child.running) {
|
|
1490
|
+
if (entry.id) staleChildIds.current.delete(entry.id);
|
|
1491
|
+
nextStatus[nodeId] = 'running';
|
|
1492
|
+
} else if (!entry.id || !staleChildIds.current.has(entry.id)) {
|
|
1493
|
+
if (timing && timing.lastTurnCompleted === false) nextStatus[nodeId] = 'failed';
|
|
1494
|
+
else nextStatus[nodeId] = 'done';
|
|
1495
|
+
}
|
|
1452
1496
|
}
|
|
1453
1497
|
return { status: nextStatus, runs: nextRuns };
|
|
1454
1498
|
} catch (_e) {
|
|
@@ -1460,6 +1504,7 @@ window.__ModuleLoader__.load({
|
|
|
1460
1504
|
// catalog lists children by `label#nodeId`. Lead steps run inside the
|
|
1461
1505
|
// conversation, so the canvas cannot observe them and must not pretend to.
|
|
1462
1506
|
useEffect(() => {
|
|
1507
|
+
staleChildIds.current = new Set();
|
|
1463
1508
|
const sessions = hostCtx && hostCtx.sessions;
|
|
1464
1509
|
const face = sessionFace(sessionId);
|
|
1465
1510
|
if (!sessions || !sessionId || !face || typeof face.subscribe !== 'function') return undefined;
|
|
@@ -1477,8 +1522,6 @@ window.__ModuleLoader__.load({
|
|
|
1477
1522
|
const onSnapshot = () => {
|
|
1478
1523
|
let running = false;
|
|
1479
1524
|
try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
|
|
1480
|
-
// A new turn means a new run: drop the previous run's statuses first.
|
|
1481
|
-
if (running && !wasRunning) setStatusById({});
|
|
1482
1525
|
const finished = !running && wasRunning;
|
|
1483
1526
|
wasRunning = running;
|
|
1484
1527
|
if (running && !timer) { read(); timer = setInterval(read, 700); }
|
|
@@ -2256,13 +2299,20 @@ window.__ModuleLoader__.load({
|
|
|
2256
2299
|
};
|
|
2257
2300
|
|
|
2258
2301
|
/** Load a canvas document produced by the model. */
|
|
2259
|
-
const applyCanvasDoc = (doc, remoteAt) => {
|
|
2302
|
+
const applyCanvasDoc = (doc, remoteAt, fromRemote) => {
|
|
2260
2303
|
if (!doc || !Array.isArray(doc.nodes)) return false;
|
|
2261
2304
|
const merge = doc.mode === 'merge';
|
|
2262
2305
|
if (!merge && !doc.nodes.length) return false;
|
|
2263
2306
|
pushSnapshot();
|
|
2264
2307
|
const stamp = typeof remoteAt === 'number' ? remoteAt : (typeof doc.at === 'number' ? doc.at : null);
|
|
2265
2308
|
applyStamp.current = stamp;
|
|
2309
|
+
if (fromRemote) {
|
|
2310
|
+
skipDirtyOnce.current = true;
|
|
2311
|
+
setDirty(false);
|
|
2312
|
+
}
|
|
2313
|
+
if (typeof doc.enabled === 'boolean') {
|
|
2314
|
+
setEnabled(doc.enabled);
|
|
2315
|
+
}
|
|
2266
2316
|
const removedNodes = new Set(doc.removeNodes || []);
|
|
2267
2317
|
const rawIncomingEdges = Array.isArray(doc.edges) ? doc.edges : [];
|
|
2268
2318
|
setNodes((existing) => {
|
|
@@ -2293,7 +2343,9 @@ window.__ModuleLoader__.load({
|
|
|
2293
2343
|
});
|
|
2294
2344
|
if (!merge) return incoming;
|
|
2295
2345
|
const touched = new Set(incoming.map((n) => n.id));
|
|
2296
|
-
const kept = existing
|
|
2346
|
+
const kept = existing
|
|
2347
|
+
.filter((n) => !touched.has(n.id) && !removedNodes.has(n.id))
|
|
2348
|
+
.map((n) => (n.id === 'lead' && typeof doc.task === 'string' ? { ...n, task: doc.task } : n));
|
|
2297
2349
|
return kept.concat(incoming);
|
|
2298
2350
|
});
|
|
2299
2351
|
setEdges((existing) => {
|
|
@@ -2315,7 +2367,7 @@ window.__ModuleLoader__.load({
|
|
|
2315
2367
|
return kept.concat(added);
|
|
2316
2368
|
});
|
|
2317
2369
|
setSelectedIds([]);
|
|
2318
|
-
|
|
2370
|
+
snapshotStaleCatalog();
|
|
2319
2371
|
if (!merge) {
|
|
2320
2372
|
setRunsById({});
|
|
2321
2373
|
setTimeout(() => fitView(nodesRef.current), 0);
|
|
@@ -2377,7 +2429,7 @@ window.__ModuleLoader__.load({
|
|
|
2377
2429
|
const valid = canvas && Array.isArray(canvas.nodes)
|
|
2378
2430
|
&& (canvas.mode === 'merge' || canvas.nodes.length > 0)
|
|
2379
2431
|
&& canvas.nodes.every((n) => n && typeof n.id === 'string');
|
|
2380
|
-
if (valid && applyCanvasDoc(canvas, doc.at)) {
|
|
2432
|
+
if (valid && applyCanvasDoc(canvas, doc.at, true)) {
|
|
2381
2433
|
flash(t('generated'));
|
|
2382
2434
|
setSyncNote(t('syncApplied'));
|
|
2383
2435
|
setTimeout(() => setSyncNote(''), 4000);
|
|
@@ -2418,7 +2470,7 @@ window.__ModuleLoader__.load({
|
|
|
2418
2470
|
setNodes(preset.nodes);
|
|
2419
2471
|
setEdges(preset.edges);
|
|
2420
2472
|
setSelectedIds([]);
|
|
2421
|
-
|
|
2473
|
+
snapshotStaleCatalog();
|
|
2422
2474
|
setRunsById({});
|
|
2423
2475
|
setPresetOpen(null);
|
|
2424
2476
|
setTimeout(() => fitView(preset.nodes), 0);
|
|
@@ -2433,7 +2485,7 @@ window.__ModuleLoader__.load({
|
|
|
2433
2485
|
setNodes(clonedNodes);
|
|
2434
2486
|
setEdges(clonedEdges);
|
|
2435
2487
|
setSelectedIds([]);
|
|
2436
|
-
|
|
2488
|
+
snapshotStaleCatalog();
|
|
2437
2489
|
setRunsById({});
|
|
2438
2490
|
setPresetOpen(null);
|
|
2439
2491
|
setTimeout(() => fitView(clonedNodes), 0);
|
|
@@ -2520,6 +2572,9 @@ window.__ModuleLoader__.load({
|
|
|
2520
2572
|
onClick: () => { updateNode(node.id, { fallbackModel: m.model, fallbackProvider: m.provider }); setOpenModelFor(null); },
|
|
2521
2573
|
}, m.modelName || m.model));
|
|
2522
2574
|
}
|
|
2575
|
+
if (models.length === 1) {
|
|
2576
|
+
rows.push(h('div', { key: 'single-hint', style: S.presetEmpty }, t('singleModelHint')));
|
|
2577
|
+
}
|
|
2523
2578
|
return h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
|
|
2524
2579
|
h('button', {
|
|
2525
2580
|
style: S.selectBtn,
|
|
@@ -2632,6 +2687,11 @@ window.__ModuleLoader__.load({
|
|
|
2632
2687
|
}
|
|
2633
2688
|
const reachableIds = reachableFrom(nodes, edges);
|
|
2634
2689
|
const nodeById = new Map(nodes.map((n) => [n.id, n]));
|
|
2690
|
+
const hasDownstreamLead = nodes.some((n) => n.kind === 'lead' && n.id !== 'lead' && reachableIds.has(n.id));
|
|
2691
|
+
const hasOutNode = new Set(edges.map((e) => e.from));
|
|
2692
|
+
const deadEndIds = new Set(hasDownstreamLead
|
|
2693
|
+
? nodes.filter((n) => n.kind !== 'lead' && reachableIds.has(n.id) && !hasOutNode.has(n.id)).map((n) => n.id)
|
|
2694
|
+
: []);
|
|
2635
2695
|
|
|
2636
2696
|
// Identify intermediate/final Lead nodes whose upstream subagents are all
|
|
2637
2697
|
// finished and whose downstream has not started yet ("Ready for Lead").
|
|
@@ -3036,6 +3096,7 @@ window.__ModuleLoader__.load({
|
|
|
3036
3096
|
}),
|
|
3037
3097
|
);
|
|
3038
3098
|
const isOrphan = node.id !== 'lead' && !reachableIds.has(node.id);
|
|
3099
|
+
const isDeadEnd = deadEndIds.has(node.id);
|
|
3039
3100
|
const isSelected = selectedSet.has(node.id);
|
|
3040
3101
|
const nodeStatus = enabled ? statusById[node.id] : undefined;
|
|
3041
3102
|
const isLeadReady = leadReadyIds.has(node.id);
|
|
@@ -3053,7 +3114,9 @@ window.__ModuleLoader__.load({
|
|
|
3053
3114
|
? { border: '1.5px solid rgba(229,83,75,0.8)', boxShadow: '0 0 12px rgba(229,83,75,0.18)' }
|
|
3054
3115
|
: isDone
|
|
3055
3116
|
? { border: '1px solid rgba(63,185,80,0.55)' }
|
|
3056
|
-
:
|
|
3117
|
+
: isDeadEnd
|
|
3118
|
+
? { border: '1px solid rgba(210,153,34,0.55)' }
|
|
3119
|
+
: null;
|
|
3057
3120
|
const topBarBg = (isRunning || isLeadReady) && fxLevel === 'vivid'
|
|
3058
3121
|
? (isLeadKind
|
|
3059
3122
|
? 'linear-gradient(90deg, #2f81f7 0%, #79c0ff 50%, #2f81f7 100%)'
|
|
@@ -3083,6 +3146,11 @@ window.__ModuleLoader__.load({
|
|
|
3083
3146
|
}),
|
|
3084
3147
|
h('div', { style: S.nodeHeader }),
|
|
3085
3148
|
h('div', { style: S.bandDivider }),
|
|
3149
|
+
isDeadEnd && h('div', {
|
|
3150
|
+
style: S.warnChip,
|
|
3151
|
+
title: t('tipDeadEnd'),
|
|
3152
|
+
onMouseDown: (e) => e.stopPropagation(),
|
|
3153
|
+
}, '⚠ ', t('stDeadEnd')),
|
|
3086
3154
|
(() => {
|
|
3087
3155
|
const latestRun = !isLeadKind ? runsById[node.id] : null;
|
|
3088
3156
|
const statusColor = isLeadReady ? '#2f81f7'
|
package/docs/MECHANISM.md
CHANGED
|
@@ -62,11 +62,11 @@ When `canvas_workflow` runs, `executePlan` executes the following pipeline:
|
|
|
62
62
|
1. **Entry stripping & task override**: The entry `lead` node is stripped (`withoutEntry`) and never spawned. If `args.task` is provided, it overrides `plan.task` for this run (allowing blank-task templates to be reused straight from chat).
|
|
63
63
|
2. **Cycle validation (Kahn topological sort)**: `orderNodes` validates the DAG is acyclic (the client also blocks cycles interactively via `wouldCycle`).
|
|
64
64
|
3. **Reachability pruning**: BFS from `'lead'` filters out disconnected nodes. Unreachable nodes are drawn dashed, skipped at run time, and listed in `skipped` without burning tokens.
|
|
65
|
-
4. **
|
|
65
|
+
4. **Event-driven concurrency pool & resumable pauses**:
|
|
66
66
|
- Progress per session is tracked in `runBySession` (`{ sig, done, results, labels, failed }`).
|
|
67
|
-
-
|
|
68
|
-
-
|
|
69
|
-
-
|
|
67
|
+
- Instead of a strict per-wave barrier, the executor runs an **event-driven concurrency pool (`inFlight` + `Promise.race`, `MAX_PARALLEL = 4`)**:
|
|
68
|
+
- The instant any running subagent finishes, newly unblocked downstream subagents launch immediately — fast branches never stall waiting for slower siblings.
|
|
69
|
+
- Once no runnable subagents remain and only downstream **non-entry Lead nodes** are ready (entry Lead never pauses) without a `leadResult`, execution pauses with `status: "need-lead"`, returning collected results, any failures, and `session` child IDs.
|
|
70
70
|
- The conversation performs that Lead step and calls `canvas_workflow({ leadResult: "..." })` to resume seamlessly.
|
|
71
71
|
- Changing the graph (different plan `sig`) or passing `reset: true` discards paused progress and restarts cleanly.
|
|
72
72
|
|
package/docs/MECHANISM.zh.md
CHANGED
|
@@ -59,12 +59,12 @@ flowchart LR
|
|
|
59
59
|
1. **入口剥离与任务解析**:剥离作为总任务容器的入口节点 `lead`(永不作为子代理执行)。若调用时传入 `task` 参数,则覆盖入口 Lead 的总任务(方便直接复用空任务预设)。
|
|
60
60
|
2. **成环校验(Kahn 拓扑排序)**:用 `orderNodes` 校验 DAG 无环(客户端手动画线时也会用 `wouldCycle` 即时拦截)。
|
|
61
61
|
3. **可达性剪枝**:从入口 `lead` 做广度优先遍历,不可达的孤立节点在画布上显示为虚线,运行时被自动跳过并列入 `skipped`,不会消耗 Token。
|
|
62
|
-
4.
|
|
62
|
+
4. **事件驱动并发池与暂停续跑**:
|
|
63
63
|
- 每个会话的运行进度保存在 `runBySession`(包含计划签名 `sig`、`done`、`results`、`labels`、`failed`);
|
|
64
|
-
-
|
|
65
|
-
-
|
|
66
|
-
-
|
|
67
|
-
- 主对话完成该 Lead 步骤后,再次调用 `canvas_workflow({ leadResult: "..." })
|
|
64
|
+
- 执行器维护一个上限为 **4 并发**(`MAX_PARALLEL = 4`)的**动态并发池(`inFlight` + `Promise.race`)**,而非同步屏障:
|
|
65
|
+
- 只要有任意在跑子代理完成、空出并发槽位,**任何依赖已满足的下游子代理会立刻启动**,不再傻等同层较慢的兄弟节点;
|
|
66
|
+
- 直到当前所有可执行子代理全部跑完、仅剩 **非入口 Lead 节点**就绪且尚未收到 `leadResult` 时,执行器暂停并返回 `status: "need-lead"`(入口 Lead 仅承载总任务,不会触发暂停),把已收集结果、失败汇总以及紫线 `childId` 交回主对话;
|
|
67
|
+
- 主对话完成该 Lead 步骤后,再次调用 `canvas_workflow({ leadResult: "..." })`,执行器从断点无缝继续;
|
|
68
68
|
- 若中途修改了画布(计划签名 `sig` 变化)或显式传入 `reset: true`,则丢弃旧进度从头重跑。
|
|
69
69
|
|
|
70
70
|
```mermaid
|
package/index.js
CHANGED
|
@@ -134,7 +134,7 @@ function briefFor(plan, node, results, failedMap) {
|
|
|
134
134
|
head.push('【职责】' + (node.role || node.label));
|
|
135
135
|
if (ups.length) head.push('【上游】' + ups.map((u) => u.from.label).join('、') + ' 已交付结果给你(见下文)。');
|
|
136
136
|
head.push('【下游】' + (downs.length ? downs.join('、') + ' 会使用你的输出。' : '你是终点,结果会直接交付给用户。'));
|
|
137
|
-
head.push('
|
|
137
|
+
head.push('【要求】只完成你这一步;最终回复只输出简洁、可直接被下游或 Lead 消费的交付报告(结论、改动清单、关键接口/路径),不要包含思考独白、过程叙述或对其他并行节点的评价。若因环境或权限受限未能生成预期产物,必须在开头显式标注「【未完全交付】」并列出缺失项,不得把仅写脚本汇报为已完成。');
|
|
138
138
|
let text = head.join('\n') + '\n';
|
|
139
139
|
for (const u of ups) {
|
|
140
140
|
const value = results[u.from.id];
|
|
@@ -176,6 +176,13 @@ function failed(result) {
|
|
|
176
176
|
return reason !== undefined && reason !== 'completed';
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
+
function isEmptyOutput(result) {
|
|
180
|
+
if (result && result.structured !== undefined) return false;
|
|
181
|
+
const blocks = (result && result.output) || [];
|
|
182
|
+
const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
|
|
183
|
+
return text.trim().length === 0;
|
|
184
|
+
}
|
|
185
|
+
|
|
179
186
|
async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid, failedMap) {
|
|
180
187
|
const childKey = (id) => String(sid || '') + '::' + id;
|
|
181
188
|
const spec = {
|
|
@@ -225,7 +232,12 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
225
232
|
const message = String((error && error.message) || error);
|
|
226
233
|
return { ok: false, text: '运行失败:' + message, reason: 'run-failed' };
|
|
227
234
|
}
|
|
228
|
-
return {
|
|
235
|
+
return {
|
|
236
|
+
ok: !failed(result),
|
|
237
|
+
text: textOf(result),
|
|
238
|
+
reason: result && result.stopReason,
|
|
239
|
+
empty: isEmptyOutput(result),
|
|
240
|
+
};
|
|
229
241
|
} finally {
|
|
230
242
|
try { await activation.dispose(); } catch (_e) { /* ignore */ }
|
|
231
243
|
}
|
|
@@ -280,22 +292,22 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
280
292
|
|
|
281
293
|
if (continueFrom) {
|
|
282
294
|
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap);
|
|
283
|
-
if (continued.ok) return { ok: true, text: continued.text + '\n(已在上游会话中继续)' };
|
|
295
|
+
if (continued.ok) return { ok: true, empty: Boolean(continued.empty), text: continued.text + '\n(已在上游会话中继续)' };
|
|
284
296
|
}
|
|
285
297
|
|
|
286
298
|
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap);
|
|
287
|
-
if (first.ok) return { ok: true, text: first.text };
|
|
299
|
+
if (first.ok) return { ok: true, empty: Boolean(first.empty), text: first.text };
|
|
288
300
|
if (!node.fallbackModel && !node.fallbackProvider) {
|
|
289
301
|
const reason = first.reason || 'unknown';
|
|
290
|
-
return { ok: false, reason, text: first.text + '\n(失败原因:' + reason + ',未配置备用模型)' };
|
|
302
|
+
return { ok: false, empty: false, reason, text: first.text + '\n(失败原因:' + reason + ',未配置备用模型)' };
|
|
291
303
|
}
|
|
292
304
|
const retry = await spawnOnce(scope, plan, node, results, parent, signal, {
|
|
293
305
|
provider: node.fallbackProvider,
|
|
294
306
|
model: node.fallbackModel,
|
|
295
307
|
}, undefined, sid, failedMap);
|
|
296
|
-
if (retry.ok) return { ok: true, text: retry.text + '\n(已用备用模型重试成功)' };
|
|
308
|
+
if (retry.ok) return { ok: true, empty: Boolean(retry.empty), text: retry.text + '\n(已用备用模型重试成功)' };
|
|
297
309
|
const reason = retry.reason || 'unknown';
|
|
298
|
-
return { ok: false, reason, text: retry.text + '\n(重试仍失败:' + reason + ')' };
|
|
310
|
+
return { ok: false, empty: false, reason, text: retry.text + '\n(重试仍失败:' + reason + ')' };
|
|
299
311
|
}
|
|
300
312
|
|
|
301
313
|
/** Ids reachable from the entry Lead; every other node is skipped at run time. */
|
|
@@ -312,8 +324,39 @@ function reachableFrom(plan) {
|
|
|
312
324
|
}
|
|
313
325
|
|
|
314
326
|
/**
|
|
315
|
-
*
|
|
316
|
-
*
|
|
327
|
+
* Detect structural warnings on a canvas plan:
|
|
328
|
+
* 1. Unreachable nodes (will be skipped at run time).
|
|
329
|
+
* 2. Reachable non-Lead agent nodes with zero outgoing edges when the graph
|
|
330
|
+
* already has a downstream Lead node (likely forgot to wire into the Lead).
|
|
331
|
+
*/
|
|
332
|
+
function analyzeCanvasWarnings(nodes, edges) {
|
|
333
|
+
const list = withoutEntry(nodes);
|
|
334
|
+
const linkList = Array.isArray(edges) ? edges : [];
|
|
335
|
+
const warnings = [];
|
|
336
|
+
if (!list.length) return warnings;
|
|
337
|
+
|
|
338
|
+
const reachable = reachableFrom({ edges: linkList });
|
|
339
|
+
const orphans = list.filter((n) => !reachable.has(n.id));
|
|
340
|
+
if (orphans.length) {
|
|
341
|
+
warnings.push('以下节点未从入口 Lead 连通,运行时会被跳过:'
|
|
342
|
+
+ orphans.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const hasDownstreamLead = list.some((n) => n.kind === 'lead' && reachable.has(n.id));
|
|
346
|
+
if (hasDownstreamLead) {
|
|
347
|
+
const hasOut = new Set(linkList.map((e) => e.from));
|
|
348
|
+
const deadEnds = list.filter((n) => n.kind !== 'lead' && reachable.has(n.id) && !hasOut.has(n.id));
|
|
349
|
+
if (deadEnds.length) {
|
|
350
|
+
warnings.push('以下子代理节点没有出边,产出未显式连入下游或终审 Lead:'
|
|
351
|
+
+ deadEnds.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return warnings;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Turn a model-authored sketch into a canvas document: assign ids, ensure one
|
|
359
|
+
* connected entry Lead, and lay the graph out in columns by depth.
|
|
317
360
|
*/
|
|
318
361
|
function normalizeCanvas(args) {
|
|
319
362
|
const rawNodes = Array.isArray(args && args.nodes) ? args.nodes : [];
|
|
@@ -322,19 +365,28 @@ function normalizeCanvas(args) {
|
|
|
322
365
|
|
|
323
366
|
const nodes = [];
|
|
324
367
|
const idByRef = new Map();
|
|
368
|
+
const usedIds = new Set();
|
|
325
369
|
let counter = 0;
|
|
370
|
+
let hasExplicitLead = false;
|
|
326
371
|
for (const raw of rawNodes) {
|
|
327
372
|
if (!raw || typeof raw !== 'object') continue;
|
|
328
373
|
counter += 1;
|
|
329
374
|
const kind = raw.kind === 'lead' ? 'lead' : 'agent';
|
|
330
|
-
const wantsEntry = raw.entry === true && kind === 'lead';
|
|
331
|
-
|
|
375
|
+
const wantsEntry = !hasExplicitLead && (raw.id === 'lead' || (raw.entry === true && kind === 'lead'));
|
|
376
|
+
let id = wantsEntry
|
|
332
377
|
? 'lead'
|
|
333
378
|
: (typeof raw.id === 'string' && raw.id && raw.id !== 'lead' ? raw.id : 'n' + counter);
|
|
379
|
+
if (usedIds.has(id)) {
|
|
380
|
+
let suffix = 2;
|
|
381
|
+
while (usedIds.has(id + '_' + suffix)) suffix += 1;
|
|
382
|
+
id = id + '_' + suffix;
|
|
383
|
+
}
|
|
384
|
+
usedIds.add(id);
|
|
385
|
+
if (id === 'lead') hasExplicitLead = true;
|
|
334
386
|
const label = String(raw.label || (kind === 'lead' ? 'Lead 步骤 ' + counter : 'Node ' + counter));
|
|
335
387
|
nodes.push({
|
|
336
388
|
id,
|
|
337
|
-
kind,
|
|
389
|
+
kind: id === 'lead' ? 'lead' : kind,
|
|
338
390
|
label,
|
|
339
391
|
role: String(raw.role || ''),
|
|
340
392
|
task: String(raw.task || ''),
|
|
@@ -349,33 +401,65 @@ function normalizeCanvas(args) {
|
|
|
349
401
|
x: 0,
|
|
350
402
|
y: 0,
|
|
351
403
|
});
|
|
352
|
-
if (raw.ref) idByRef.set(String(raw.ref), id);
|
|
404
|
+
if (raw.ref && !idByRef.has(String(raw.ref))) idByRef.set(String(raw.ref), id);
|
|
405
|
+
if (raw.id && !idByRef.has(String(raw.id))) idByRef.set(String(raw.id), id);
|
|
353
406
|
idByRef.set(id, id);
|
|
354
407
|
}
|
|
355
408
|
if (!nodes.length) return { error: '节点都无效' };
|
|
356
409
|
|
|
357
|
-
const entry = nodes.find((n) => n.id === 'lead');
|
|
358
|
-
if (!entry) {
|
|
359
|
-
nodes.unshift({
|
|
360
|
-
id: 'lead', kind: 'lead', label: 'Lead(本对话)', role: '',
|
|
361
|
-
task: String(args.task || ''), provider: '', model: '', reasoning: '',
|
|
362
|
-
preset: '', structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
|
|
363
|
-
x: 0, y: 0,
|
|
364
|
-
});
|
|
365
|
-
} else if (!entry.task) {
|
|
366
|
-
entry.task = String(args.task || '');
|
|
367
|
-
}
|
|
368
|
-
|
|
369
410
|
const ids = new Set(nodes.map((n) => n.id));
|
|
370
411
|
const edges = [];
|
|
371
412
|
for (const raw of rawEdges) {
|
|
372
413
|
if (!raw || typeof raw !== 'object') continue;
|
|
373
414
|
const from = idByRef.get(String(raw.from)) || String(raw.from);
|
|
374
415
|
const to = idByRef.get(String(raw.to)) || String(raw.to);
|
|
375
|
-
if (!ids.has(from) || !ids.has(to) || from === to) continue;
|
|
416
|
+
if ((from !== 'lead' && !ids.has(from)) || !ids.has(to) || from === to || to === 'lead') continue;
|
|
376
417
|
const type = ['prompt', 'structured', 'session-ref'].includes(raw.type) ? raw.type : 'prompt';
|
|
377
418
|
edges.push({ id: 'e' + edges.length, from, to, type });
|
|
378
419
|
}
|
|
420
|
+
|
|
421
|
+
let entry = nodes.find((n) => n.id === 'lead');
|
|
422
|
+
if (!entry) {
|
|
423
|
+
// If the caller hand-authored a root Lead node (no incoming edges, has outgoing edges)
|
|
424
|
+
// and didn't wire from id='lead', promote it to entry Lead instead of duplicating it.
|
|
425
|
+
const hasLeadEdge = edges.some((e) => e.from === 'lead');
|
|
426
|
+
const inSet = new Set(edges.map((e) => e.to));
|
|
427
|
+
const outSet = new Set(edges.map((e) => e.from));
|
|
428
|
+
const rootLead = !hasLeadEdge
|
|
429
|
+
? nodes.find((n) => n.kind === 'lead' && !inSet.has(n.id) && outSet.has(n.id))
|
|
430
|
+
: null;
|
|
431
|
+
if (rootLead) {
|
|
432
|
+
const oldId = rootLead.id;
|
|
433
|
+
rootLead.id = 'lead';
|
|
434
|
+
rootLead.task = rootLead.task || String(args.task || '') || rootLead.role;
|
|
435
|
+
rootLead.role = '';
|
|
436
|
+
for (const e of edges) {
|
|
437
|
+
if (e.from === oldId) e.from = 'lead';
|
|
438
|
+
}
|
|
439
|
+
entry = rootLead;
|
|
440
|
+
} else {
|
|
441
|
+
entry = {
|
|
442
|
+
id: 'lead', kind: 'lead', label: 'Lead(本对话)', role: '',
|
|
443
|
+
task: String(args.task || ''), provider: '', model: '', reasoning: '',
|
|
444
|
+
preset: '', structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
|
|
445
|
+
x: 0, y: 0,
|
|
446
|
+
};
|
|
447
|
+
nodes.unshift(entry);
|
|
448
|
+
}
|
|
449
|
+
} else if (!entry.task) {
|
|
450
|
+
entry.task = String(args.task || '') || entry.role;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// If entry Lead still has no outgoing edges, auto-wire it to all root nodes so
|
|
454
|
+
// a freshly generated canvas is never dead/unreachable on arrival.
|
|
455
|
+
if (!edges.some((e) => e.from === 'lead')) {
|
|
456
|
+
const hasIn = new Set(edges.map((e) => e.to));
|
|
457
|
+
const roots = nodes.filter((n) => n.id !== 'lead' && !hasIn.has(n.id));
|
|
458
|
+
for (const root of roots) {
|
|
459
|
+
edges.push({ id: 'e' + edges.length, from: 'lead', to: root.id, type: 'prompt' });
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
379
463
|
const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
|
|
380
464
|
for (const node of nodes) {
|
|
381
465
|
if (structuredSources.has(node.id)) node.structured = true;
|
|
@@ -398,10 +482,15 @@ function normalizeCanvas(args) {
|
|
|
398
482
|
const row = perColumn.get(level) || 0;
|
|
399
483
|
perColumn.set(level, row + 1);
|
|
400
484
|
node.x = 60 + level * 300;
|
|
401
|
-
node.y = 80 + row *
|
|
485
|
+
node.y = 80 + row * 260;
|
|
402
486
|
}
|
|
403
487
|
|
|
404
|
-
return {
|
|
488
|
+
return {
|
|
489
|
+
nodes,
|
|
490
|
+
edges,
|
|
491
|
+
task: String(entry.task || args.task || ''),
|
|
492
|
+
warnings: analyzeCanvasWarnings(nodes, edges),
|
|
493
|
+
};
|
|
405
494
|
}
|
|
406
495
|
|
|
407
496
|
/**
|
|
@@ -464,11 +553,14 @@ function applyPatch(plan, args) {
|
|
|
464
553
|
}
|
|
465
554
|
const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
|
|
466
555
|
for (const node of keptNodes) {
|
|
467
|
-
|
|
556
|
+
node.structured = structuredSources.has(node.id);
|
|
468
557
|
}
|
|
558
|
+
const taskPatched = typeof (args && args.task) === 'string';
|
|
559
|
+
const nextTask = taskPatched ? args.task : String(plan.task || '');
|
|
469
560
|
return {
|
|
470
|
-
plan: { ...plan, nodes: keptNodes, edges },
|
|
561
|
+
plan: { ...plan, task: nextTask, nodes: keptNodes, edges },
|
|
471
562
|
touched,
|
|
563
|
+
taskPatched,
|
|
472
564
|
removed: Array.from(removed),
|
|
473
565
|
removeEdges: rawRemoveEdges
|
|
474
566
|
.filter((r) => r && typeof r.from === 'string' && typeof r.to === 'string')
|
|
@@ -514,38 +606,42 @@ function inspectPlan(sid) {
|
|
|
514
606
|
task: '',
|
|
515
607
|
nodes: [],
|
|
516
608
|
edges: [],
|
|
609
|
+
warnings: [],
|
|
517
610
|
paused: false,
|
|
518
611
|
};
|
|
519
612
|
}
|
|
520
613
|
const plan = payload.plan || {};
|
|
521
614
|
const nodes = withoutEntry(plan.nodes).map((n) => ({
|
|
522
|
-
id: n.id,
|
|
615
|
+
id: String(n.id || ''),
|
|
523
616
|
kind: n.kind === 'lead' ? 'lead' : 'agent',
|
|
524
|
-
label: n.label || n.id,
|
|
525
|
-
role: n.role || '',
|
|
526
|
-
provider: n.provider || '',
|
|
527
|
-
model: n.model || '',
|
|
528
|
-
reasoning: n.reasoning || '',
|
|
617
|
+
label: String(n.label || n.id || ''),
|
|
618
|
+
role: String(n.role || ''),
|
|
619
|
+
provider: String(n.provider || ''),
|
|
620
|
+
model: String(n.model || ''),
|
|
621
|
+
reasoning: String(n.reasoning || ''),
|
|
529
622
|
preset: n.preset === 'minimal' ? 'minimal' : 'standard',
|
|
530
623
|
keepSession: Boolean(n.keepSession),
|
|
531
624
|
structured: Boolean(n.structured),
|
|
532
|
-
fallbackModel: n.fallbackModel || '',
|
|
533
|
-
fallbackProvider: n.fallbackProvider || '',
|
|
625
|
+
fallbackModel: String(n.fallbackModel || ''),
|
|
626
|
+
fallbackProvider: String(n.fallbackProvider || ''),
|
|
534
627
|
}));
|
|
535
628
|
const edges = Array.isArray(plan.edges) ? plan.edges.map((e) => ({
|
|
536
|
-
from: e.from,
|
|
537
|
-
to: e.to,
|
|
538
|
-
type: e.type || 'prompt',
|
|
629
|
+
from: String(e.from || ''),
|
|
630
|
+
to: String(e.to || ''),
|
|
631
|
+
type: String(e.type || 'prompt'),
|
|
539
632
|
})) : [];
|
|
540
|
-
|
|
633
|
+
const out = {
|
|
541
634
|
hasCanvas: true,
|
|
542
635
|
enabled: Boolean(payload.enabled),
|
|
543
636
|
task: String(plan.task || ''),
|
|
544
637
|
nodes,
|
|
545
638
|
edges,
|
|
639
|
+
warnings: analyzeCanvasWarnings(nodes, edges),
|
|
546
640
|
paused: Boolean(sid && runBySession.has(sid)),
|
|
547
|
-
error: payload.error ? String(payload.error) : undefined,
|
|
548
641
|
};
|
|
642
|
+
// Never attach `error: undefined`: DSH's lossless JSON validator rejects keys with undefined values.
|
|
643
|
+
if (payload.error) out.error = String(payload.error);
|
|
644
|
+
return out;
|
|
549
645
|
}
|
|
550
646
|
|
|
551
647
|
/** Takes a plan directly so tests can feed any plan shape (sync, generate, patch). */
|
|
@@ -590,9 +686,10 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
590
686
|
const sig = JSON.stringify(plan);
|
|
591
687
|
let state = runBySession.get(sid);
|
|
592
688
|
if (!state || state.sig !== sig) {
|
|
593
|
-
state = { sig, done: new Set(), results: {}, labels: {}, failed: {} };
|
|
689
|
+
state = { sig, done: new Set(), results: {}, labels: {}, failed: {}, emptyOutputs: {} };
|
|
594
690
|
runBySession.set(sid, state);
|
|
595
691
|
}
|
|
692
|
+
if (!state.emptyOutputs) state.emptyOutputs = {};
|
|
596
693
|
|
|
597
694
|
const byId = new Map(runnable.map((n) => [n.id, n]));
|
|
598
695
|
const labelOf = new Map(order.map((n) => [n.id, n.label || n.id]));
|
|
@@ -603,8 +700,33 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
603
700
|
|
|
604
701
|
let leadResult = typeof opts.leadResult === 'string' ? opts.leadResult : undefined;
|
|
605
702
|
const MAX_PARALLEL = 4;
|
|
703
|
+
// Event-driven concurrency pool: as soon as any node finishes, newly unblocked
|
|
704
|
+
// downstream agents start immediately instead of waiting for slower siblings.
|
|
705
|
+
const inFlight = new Map();
|
|
706
|
+
|
|
707
|
+
const isAborted = () => Boolean(exec && exec.signal && exec.signal.aborted);
|
|
708
|
+
|
|
709
|
+
const launchReadyAgents = () => {
|
|
710
|
+
if (isAborted() || inFlight.size >= MAX_PARALLEL) return;
|
|
711
|
+
const candidates = runnable.filter((n) => n.kind !== 'lead'
|
|
712
|
+
&& !state.done.has(n.id)
|
|
713
|
+
&& !inFlight.has(n.id)
|
|
714
|
+
&& depsOf(n).every((id) => state.done.has(id)));
|
|
715
|
+
for (const node of candidates) {
|
|
716
|
+
if (isAborted() || inFlight.size >= MAX_PARALLEL) break;
|
|
717
|
+
const promise = spawnNode(scope, plan, node, state.results, agent, exec.signal, sid, state.failed)
|
|
718
|
+
.then(
|
|
719
|
+
(outcome) => ({ node, outcome }),
|
|
720
|
+
(err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
|
|
721
|
+
);
|
|
722
|
+
inFlight.set(node.id, promise);
|
|
723
|
+
}
|
|
724
|
+
};
|
|
606
725
|
|
|
607
726
|
for (;;) {
|
|
727
|
+
if (isAborted()) {
|
|
728
|
+
return { error: '工作流执行已取消。' };
|
|
729
|
+
}
|
|
608
730
|
const remaining = runnable.filter((n) => !state.done.has(n.id));
|
|
609
731
|
if (!remaining.length) {
|
|
610
732
|
runBySession.delete(sid);
|
|
@@ -614,31 +736,33 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
614
736
|
results: state.results,
|
|
615
737
|
labels: state.labels,
|
|
616
738
|
failed: Object.values(state.failed),
|
|
739
|
+
emptyOutputs: Object.values(state.emptyOutputs),
|
|
617
740
|
skipped,
|
|
618
741
|
};
|
|
619
742
|
}
|
|
620
743
|
|
|
621
|
-
|
|
622
|
-
if (!ready.length) return { error: '有节点的依赖无法满足(存在环或悬空依赖)。' };
|
|
744
|
+
launchReadyAgents();
|
|
623
745
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
state.
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
});
|
|
746
|
+
if (inFlight.size > 0) {
|
|
747
|
+
const { node, outcome } = await Promise.race(inFlight.values());
|
|
748
|
+
inFlight.delete(node.id);
|
|
749
|
+
if (isAborted()) {
|
|
750
|
+
return { error: '工作流执行已取消。' };
|
|
751
|
+
}
|
|
752
|
+
state.results[node.id] = outcome.text;
|
|
753
|
+
state.labels[node.id] = node.label;
|
|
754
|
+
if (!outcome.ok) {
|
|
755
|
+
state.failed[node.id] = { id: node.id, label: node.label, reason: outcome.reason || 'unknown' };
|
|
756
|
+
} else if (outcome.empty) {
|
|
757
|
+
state.emptyOutputs[node.id] = { id: node.id, label: node.label };
|
|
758
|
+
}
|
|
759
|
+
state.done.add(node.id);
|
|
639
760
|
continue;
|
|
640
761
|
}
|
|
641
762
|
|
|
763
|
+
const ready = remaining.filter((n) => depsOf(n).every((id) => state.done.has(id)));
|
|
764
|
+
if (!ready.length) return { error: '有节点的依赖无法满足(存在环或悬空依赖)。' };
|
|
765
|
+
|
|
642
766
|
const leadNode = ready.find((n) => n.kind === 'lead');
|
|
643
767
|
if (!leadNode) return { error: '没有可执行的节点。' };
|
|
644
768
|
if (leadResult === undefined) {
|
|
@@ -652,6 +776,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
652
776
|
results: state.results,
|
|
653
777
|
labels: state.labels,
|
|
654
778
|
failed: Object.values(state.failed),
|
|
779
|
+
emptyOutputs: Object.values(state.emptyOutputs),
|
|
655
780
|
sessions: depsOf(leadNode)
|
|
656
781
|
.filter((id) => (plan.edges || []).some((e) => e.to === leadNode.id && e.from === id && e.type === 'session-ref'))
|
|
657
782
|
.map((id) => ({
|
|
@@ -756,19 +881,20 @@ export function apply(ctx) {
|
|
|
756
881
|
try {
|
|
757
882
|
scope.effect(() => scope.tools.register({
|
|
758
883
|
name: 'canvas_generate',
|
|
759
|
-
description: 'Build a workflow canvas for this session from a node/edge sketch.
|
|
884
|
+
description: 'Build a workflow canvas for this session from a node/edge sketch. Entry Lead (id="lead") is created automatically with the top-level task — do NOT add a separate entry Lead node; wire first-wave nodes from "lead". Only downstream non-entry Lead nodes pause for need-lead. Load the `workflow-canvas` skill first for node fields and link semantics.',
|
|
760
885
|
parameters: {
|
|
761
886
|
type: 'object',
|
|
762
887
|
properties: {
|
|
763
|
-
task: { type: 'string', description: 'Overall task written into the entry Lead node.' },
|
|
888
|
+
task: { type: 'string', description: 'Overall task written into the auto-created entry Lead node (id="lead").' },
|
|
764
889
|
nodes: {
|
|
765
890
|
type: 'array',
|
|
766
|
-
description: 'Nodes in any order. Give each an id or ref so edges can point at it.',
|
|
891
|
+
description: 'Nodes in any order (do not include an entry Lead — wire from "lead" instead). Give each an id or ref so edges can point at it.',
|
|
767
892
|
items: {
|
|
768
893
|
type: 'object',
|
|
769
894
|
properties: {
|
|
770
895
|
id: { type: 'string' },
|
|
771
896
|
ref: { type: 'string', description: 'Temporary handle for edges; the tool assigns the real id.' },
|
|
897
|
+
entry: { type: 'boolean', description: 'Optional: set true only if customizing the entry Lead node itself.' },
|
|
772
898
|
kind: { type: 'string', enum: ['agent', 'lead'] },
|
|
773
899
|
label: { type: 'string' },
|
|
774
900
|
role: { type: 'string' },
|
|
@@ -805,6 +931,7 @@ export function apply(ctx) {
|
|
|
805
931
|
properties: {
|
|
806
932
|
canvas: { type: 'object' },
|
|
807
933
|
delivered: { type: 'boolean' },
|
|
934
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
808
935
|
error: { type: 'string' },
|
|
809
936
|
},
|
|
810
937
|
},
|
|
@@ -814,12 +941,16 @@ export function apply(ctx) {
|
|
|
814
941
|
const canvas = v.canvas || {};
|
|
815
942
|
const nodes = Array.isArray(canvas.nodes) ? canvas.nodes : [];
|
|
816
943
|
const edges = Array.isArray(canvas.edges) ? canvas.edges : [];
|
|
817
|
-
const lines = nodes.map((n) => '- ' + (n.kind === 'lead' ? '〔Lead〕' : '') + n.label
|
|
944
|
+
const lines = nodes.map((n) => '- [' + n.id + '] ' + (n.kind === 'lead' ? '〔Lead〕' : '') + n.label
|
|
818
945
|
+ (n.role ? ':' + n.role : ''));
|
|
946
|
+
const warnBlock = Array.isArray(v.warnings) && v.warnings.length
|
|
947
|
+
? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
|
|
948
|
+
: '';
|
|
819
949
|
return [{
|
|
820
950
|
type: 'text',
|
|
821
951
|
text: '已生成画布:' + nodes.length + ' 个节点、' + edges.length + ' 条连线\n'
|
|
822
952
|
+ lines.join('\n')
|
|
953
|
+
+ warnBlock
|
|
823
954
|
+ (v.delivered
|
|
824
955
|
? '\n\n画布已经自动同步到右侧画布,直接看即可(若没出现,点画布上的「⊡ 全览」)。'
|
|
825
956
|
: '\n\n**下一步**:点画布右上角「⋯ → ⇩ 导入」,它会把这段画布数据装进当前画布。')
|
|
@@ -832,16 +963,18 @@ export function apply(ctx) {
|
|
|
832
963
|
try {
|
|
833
964
|
const result = normalizeCanvas(args || {});
|
|
834
965
|
if (result.error) return { error: result.error };
|
|
835
|
-
const
|
|
966
|
+
const warnings = Array.isArray(result.warnings) ? result.warnings : [];
|
|
836
967
|
const agent = exec && exec.agent;
|
|
837
968
|
const sid = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
969
|
+
const previous = sid ? canvasBySession.get(sid) : undefined;
|
|
970
|
+
const nextEnabled = previous ? Boolean(previous.enabled) : true;
|
|
971
|
+
const canvas = { nodes: result.nodes, edges: result.edges, enabled: nextEnabled };
|
|
838
972
|
const delivered = sid ? publishCanvas(scope, sid, canvas) : false;
|
|
839
973
|
if (sid) {
|
|
840
|
-
const previous = canvasBySession.get(sid);
|
|
841
974
|
canvasBySession.set(sid, {
|
|
842
|
-
enabled:
|
|
975
|
+
enabled: nextEnabled,
|
|
843
976
|
plan: {
|
|
844
|
-
task: String((args && args.task) || ''),
|
|
977
|
+
task: String(result.task || (args && args.task) || ''),
|
|
845
978
|
nodes: withoutEntry(canvas.nodes),
|
|
846
979
|
edges: canvas.edges,
|
|
847
980
|
},
|
|
@@ -849,7 +982,7 @@ export function apply(ctx) {
|
|
|
849
982
|
runBySession.delete(sid);
|
|
850
983
|
saveStore();
|
|
851
984
|
}
|
|
852
|
-
return { canvas, delivered };
|
|
985
|
+
return { canvas, delivered, warnings };
|
|
853
986
|
} catch (error) {
|
|
854
987
|
return { error: String((error && error.message) || error) };
|
|
855
988
|
}
|
|
@@ -868,6 +1001,7 @@ export function apply(ctx) {
|
|
|
868
1001
|
parameters: {
|
|
869
1002
|
type: 'object',
|
|
870
1003
|
properties: {
|
|
1004
|
+
task: { type: 'string', description: 'Optional: update the overall task in the entry Lead node.' },
|
|
871
1005
|
nodes: { type: 'array', description: 'Nodes to update or add. Existing ids are merged field by field.', items: { type: 'object' } },
|
|
872
1006
|
removeNodes: { type: 'array', description: 'Node ids to delete.', items: { type: 'string' } },
|
|
873
1007
|
edges: { type: 'array', description: 'Links to add.', items: { type: 'object' } },
|
|
@@ -880,13 +1014,17 @@ export function apply(ctx) {
|
|
|
880
1014
|
properties: {
|
|
881
1015
|
delivered: { type: 'boolean' },
|
|
882
1016
|
summary: { type: 'string' },
|
|
1017
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
883
1018
|
error: { type: 'string' },
|
|
884
1019
|
},
|
|
885
1020
|
},
|
|
886
1021
|
render: (_a, value) => {
|
|
887
1022
|
const v = value || {};
|
|
888
1023
|
if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
|
|
889
|
-
|
|
1024
|
+
const warnBlock = Array.isArray(v.warnings) && v.warnings.length
|
|
1025
|
+
? '\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
|
|
1026
|
+
: '';
|
|
1027
|
+
return [{ type: 'text', text: v.summary + (v.delivered ? '(画布已就地更新)' : '(画布不可达,未应用)') + warnBlock }];
|
|
890
1028
|
},
|
|
891
1029
|
},
|
|
892
1030
|
execute: (args, exec) => {
|
|
@@ -900,15 +1038,20 @@ export function apply(ctx) {
|
|
|
900
1038
|
canvasBySession.set(sid, { enabled: payload.enabled, plan: nextPlan });
|
|
901
1039
|
runBySession.delete(sid);
|
|
902
1040
|
saveStore();
|
|
903
|
-
const
|
|
1041
|
+
const patchDoc = {
|
|
904
1042
|
mode: 'merge',
|
|
905
1043
|
nodes: nextPlan.nodes,
|
|
906
1044
|
edges: nextPlan.edges,
|
|
907
1045
|
removeNodes: patched.removed,
|
|
908
1046
|
removeEdges: patched.removeEdges,
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
|
|
1047
|
+
};
|
|
1048
|
+
if (patched.taskPatched) patchDoc.task = nextPlan.task;
|
|
1049
|
+
const delivered = publishCanvas(scope, sid, patchDoc);
|
|
1050
|
+
const warnings = analyzeCanvasWarnings(nextPlan.nodes, nextPlan.edges);
|
|
1051
|
+
const summary = '已更新 ' + patched.touched.length + ' 个节点'
|
|
1052
|
+
+ (patched.taskPatched ? '、已更新总任务' : '')
|
|
1053
|
+
+ '、删除 ' + patched.removed.length + ' 个、连线 ' + nextPlan.edges.length + ' 条';
|
|
1054
|
+
return { delivered, summary, warnings };
|
|
912
1055
|
} catch (error) {
|
|
913
1056
|
return { error: String((error && error.message) || error) };
|
|
914
1057
|
}
|
|
@@ -938,6 +1081,7 @@ export function apply(ctx) {
|
|
|
938
1081
|
task: { type: 'string' },
|
|
939
1082
|
nodes: { type: 'array' },
|
|
940
1083
|
edges: { type: 'array' },
|
|
1084
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
941
1085
|
paused: { type: 'boolean' },
|
|
942
1086
|
error: { type: 'string' },
|
|
943
1087
|
},
|
|
@@ -952,6 +1096,9 @@ export function apply(ctx) {
|
|
|
952
1096
|
'总任务:' + (v.task || '(未填写,运行时可通过 task 参数指定)'),
|
|
953
1097
|
];
|
|
954
1098
|
if (v.error) head.push('校验错误:' + v.error);
|
|
1099
|
+
const warnBlock = Array.isArray(v.warnings) && v.warnings.length
|
|
1100
|
+
? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
|
|
1101
|
+
: '';
|
|
955
1102
|
const nodeLines = (v.nodes || []).map((n) => {
|
|
956
1103
|
const flags = [];
|
|
957
1104
|
if (n.kind === 'lead') flags.push('Lead');
|
|
@@ -968,6 +1115,7 @@ export function apply(ctx) {
|
|
|
968
1115
|
return [{
|
|
969
1116
|
type: 'text',
|
|
970
1117
|
text: head.join('\n')
|
|
1118
|
+
+ warnBlock
|
|
971
1119
|
+ '\n\n节点(' + nodeLines.length + '):\n' + (nodeLines.join('\n') || '(无)')
|
|
972
1120
|
+ '\n\n连线(' + edgeLines.length + '):\n' + (edgeLines.join('\n') || '(无)'),
|
|
973
1121
|
}];
|
|
@@ -1007,6 +1155,7 @@ export function apply(ctx) {
|
|
|
1007
1155
|
results: { type: 'object' },
|
|
1008
1156
|
labels: { type: 'object' },
|
|
1009
1157
|
failed: { type: 'array' },
|
|
1158
|
+
emptyOutputs: { type: 'array' },
|
|
1010
1159
|
sessions: { type: 'array' },
|
|
1011
1160
|
skipped: { type: 'array' },
|
|
1012
1161
|
hint: { type: 'string' },
|
|
@@ -1026,6 +1175,10 @@ export function apply(ctx) {
|
|
|
1026
1175
|
const failedList = Array.isArray(v.failed) && v.failed.length
|
|
1027
1176
|
? '\n\n⚠ 失败节点:' + v.failed.map((f) => (f.label || f.id) + '(' + (f.reason || 'unknown') + ')').join('、')
|
|
1028
1177
|
: '';
|
|
1178
|
+
const emptyList = Array.isArray(v.emptyOutputs) && v.emptyOutputs.length
|
|
1179
|
+
? '\n\n⚠ 未返回交付文本的节点(请核查其实际产物,切勿直接当作已完成):'
|
|
1180
|
+
+ v.emptyOutputs.map((e) => e.label || e.id).join('、')
|
|
1181
|
+
: '';
|
|
1029
1182
|
if (v.status === 'need-lead') {
|
|
1030
1183
|
const n = v.node || {};
|
|
1031
1184
|
const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
|
|
@@ -1038,6 +1191,7 @@ export function apply(ctx) {
|
|
|
1038
1191
|
text: '需要你(Lead)完成「' + n.label + '」:' + n.role
|
|
1039
1192
|
+ '\n需要用到:' + ((n.needs && n.needs.length) ? n.needs.join('、') : '(无上游)')
|
|
1040
1193
|
+ failedList
|
|
1194
|
+
+ emptyList
|
|
1041
1195
|
+ '\n\n已完成节点的结果:\n' + body
|
|
1042
1196
|
+ handover
|
|
1043
1197
|
+ '\n\n' + (v.hint || ''),
|
|
@@ -1047,7 +1201,7 @@ export function apply(ctx) {
|
|
|
1047
1201
|
const skip = Array.isArray(v.skipped) && v.skipped.length
|
|
1048
1202
|
? '\n\n已跳过(未连线):' + v.skipped.join('、')
|
|
1049
1203
|
: '';
|
|
1050
|
-
return [{ type: 'text', text: '画布执行完成。' + failedList + '\n\n' + body + skip }];
|
|
1204
|
+
return [{ type: 'text', text: '画布执行完成。' + failedList + emptyList + '\n\n' + body + skip }];
|
|
1051
1205
|
}
|
|
1052
1206
|
return [{ type: 'text', text: JSON.stringify(v) }];
|
|
1053
1207
|
},
|
|
@@ -1069,6 +1223,7 @@ export {
|
|
|
1069
1223
|
downstreamLabels,
|
|
1070
1224
|
briefFor,
|
|
1071
1225
|
withoutEntry,
|
|
1226
|
+
analyzeCanvasWarnings,
|
|
1072
1227
|
normalizeCanvas,
|
|
1073
1228
|
applyPatch,
|
|
1074
1229
|
inspectPlan,
|
package/package.json
CHANGED
|
@@ -9,8 +9,9 @@ A canvas is a DAG of agents the user can see and edit.
|
|
|
9
9
|
|
|
10
10
|
## Node kinds
|
|
11
11
|
|
|
12
|
-
- **Lead** (blue top bar) —
|
|
13
|
-
- **
|
|
12
|
+
- **Entry Lead** (`id: "lead"`, blue top bar) — created automatically by `canvas_generate` to hold the overall `task`. **Do not author a separate entry Lead node** — wire first-wave nodes directly from `from: "lead"`. The entry Lead **never** triggers `need-lead` (it does not pause before Wave 1).
|
|
13
|
+
- **Downstream Lead** (`kind: "lead"`, blue top bar) — performed by the conversation itself, never spawned. Any added non-entry Lead node holds a `role` and pauses the run (`status: "need-lead"`) so you can decide, review, or integrate before continuing.
|
|
14
|
+
- **Subagent** (`kind: "agent"`, green top bar) — spawned as a child agent with its own model, reasoning effort, capability scope, fallback model and memory switch. Wire every subagent's output into a downstream node or final Lead so nothing becomes a dead end.
|
|
14
15
|
|
|
15
16
|
## Which tool to call
|
|
16
17
|
|
|
@@ -50,18 +51,35 @@ Links only join matching types. Nodes the entry Lead cannot reach are skipped at
|
|
|
50
51
|
|
|
51
52
|
1. The canvas must be enabled (the pill over the canvas); `canvas_workflow` refuses while it is disabled.
|
|
52
53
|
2. You may pass `task` to override the entry Lead's task (handy when reusing a preset), or `reset: true` to discard a paused run and start from scratch.
|
|
53
|
-
3. Subagent nodes run in
|
|
54
|
-
4.
|
|
55
|
-
5.
|
|
54
|
+
3. Subagent nodes run in a dynamic concurrency pool of up to four: as soon as any node finishes, newly unblocked downstream subagents start immediately without waiting for slower siblings.
|
|
55
|
+
4. The run pauses (`status: "need-lead"`) only at downstream non-entry Lead nodes (never at the entry Lead).
|
|
56
|
+
5. Do that Lead step yourself, then call `canvas_workflow` again with `leadResult` — do not spawn an agent for it.
|
|
57
|
+
6. When a `session-ref` link points into that Lead node the result lists `sessions: [{ label, childId }]`; you may message those agents directly to follow up.
|
|
58
|
+
7. Only assign image/visual inspection roles to models that declare image input support.
|
|
56
59
|
|
|
57
|
-
## Failures
|
|
60
|
+
## Failures & verification iron rule
|
|
58
61
|
|
|
59
62
|
A failing node (unknown model, provider error, a stop reason other than completed) does not abort the run. Its result carries the reason, a node with `fallbackModel` is retried once on that model, and unrecovered failures are listed in `failed: [{ id, label, reason }]` while downstream nodes are warned not to treat the error as valid output. Failed nodes show red in the canvas.
|
|
60
63
|
|
|
64
|
+
If a subagent finishes with no prose and no structured JSON (`[completed]` / `[no-output]`), it is flagged in `emptyOutputs: [{ id, label }]`. **Never claim a workflow or step succeeded while `failed`, `emptyOutputs`, or `【未完全交付】` is present** — always verify the declared files on disk or follow up with that subagent first.
|
|
65
|
+
|
|
66
|
+
## Designing a good workflow (checklist)
|
|
67
|
+
|
|
68
|
+
1. **Pre-flight before `canvas_workflow`**:
|
|
69
|
+
- Never author a duplicate entry Lead — wire first-wave nodes from `from: "lead"`.
|
|
70
|
+
- Always check `warnings` returned by `canvas_generate` / `canvas_patch` / `canvas_inspect` and fix dead-end subagents (missing out-links) or unreachable nodes before running.
|
|
71
|
+
- Give parallel subagents **strictly disjoint file/directory ownership** in their `role` so two agents never overwrite the same file.
|
|
72
|
+
2. **When to add an intermediate Lead gate**:
|
|
73
|
+
- **Add an intermediate Lead** when scope/architecture is not yet locked down (need human/Lead sign-off before coding), or when downstream steps heavily depend on foundation artifacts (e.g. verify scaffold/assets actually exist and pass checks before building levels on top).
|
|
74
|
+
- **End-only Lead is fine** when all shared contracts (file paths, signals, APIs, groups) are already frozen upfront in the entry `task` and you want uninterrupted parallel execution into a final integration/review Lead.
|
|
75
|
+
3. **When to use `session-ref` (purple links)**:
|
|
76
|
+
- **Subagent → Subagent**: when an implementer should continue a codebase scanner's warm session instead of re-reading the repo from scratch.
|
|
77
|
+
- **Subagent → final Lead**: wire key implementation nodes into the final review/integration Lead with `session-ref` so if review finds bugs, you can message the original author's warm session to fix them in place.
|
|
78
|
+
|
|
61
79
|
## Memory
|
|
62
80
|
|
|
63
81
|
`keepSession: true` reuses that node's child session — across runs, and after a restart through a persisted id (cold resume). If the Host refuses the resume the record is dropped and the node starts fresh.
|
|
64
82
|
|
|
65
83
|
## Style
|
|
66
84
|
|
|
67
|
-
Keep labels short and distinct; ids must be unique even when labels repeat. Describe each step by its outcome, not by
|
|
85
|
+
Keep labels short and distinct; ids must be unique even when labels repeat. Describe each step by its outcome and exact file ownership, not by internal tool names.
|