dsh-workflow-canvas 0.2.0 → 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/README.md +4 -5
- package/README.zh.md +4 -3
- package/client.js +82 -14
- package/docs/DETAIL.md +3 -1
- package/docs/MECHANISM.md +135 -0
- package/docs/MECHANISM.zh.md +132 -0
- package/index.js +231 -76
- package/package.json +1 -1
- package/skills/workflow-canvas/SKILL.md +25 -7
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://github.com/Wasabi2575/dsh-workflow-canvas)
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
|
|
7
|
-
English | [中文](README.zh.md)
|
|
7
|
+
English | [中文](README.zh.md) | [Mechanism & Architecture](docs/MECHANISM.md)
|
|
8
8
|
|
|
9
9
|
Orchestrate subagent workflows from the DSH sidebar. Draw each step as a node, wire
|
|
10
10
|
the data flow with three link types, enable it, and run it from chat — subagent nodes
|
|
@@ -152,11 +152,10 @@ When a task involves the workflow canvas or the canvas_* tools, call the `skill`
|
|
|
152
152
|
tool with name `workflow-canvas` first.
|
|
153
153
|
```
|
|
154
154
|
|
|
155
|
-
## Development
|
|
155
|
+
## Development & internals
|
|
156
156
|
|
|
157
|
-
|
|
158
|
-
changes need a restart. Run `npm test` for the test suite. See
|
|
159
|
-
[docs/DETAIL.md](docs/DETAIL.md) for the internals.
|
|
157
|
+
- For the full architecture, Client ↔ Host sync bridge, DAG wave execution, runtime link semantics, cold resume, and live status tracking, see [**Mechanism & Architecture**](docs/MECHANISM.md) ([中文](docs/MECHANISM.zh.md)).
|
|
158
|
+
- Edit `client.js` / `index.js` and reload the app; client changes hot-reload, Host changes need a restart. Run `npm test` for the test suite. See [docs/DETAIL.md](docs/DETAIL.md) for the compact plugin detail page.
|
|
160
159
|
|
|
161
160
|
## License
|
|
162
161
|
|
package/README.zh.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://github.com/Wasabi2575/dsh-workflow-canvas)
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
|
|
7
|
-
中文 | [English](README.md)
|
|
7
|
+
中文 | [English](README.md) | [工作机制与架构原理](docs/MECHANISM.zh.md)
|
|
8
8
|
|
|
9
9
|
在 DSH 侧边栏里编排子代理工作流:把每一步画成一个节点、用三种连线标出数据怎么流转,
|
|
10
10
|
启用后直接在对话里运行。子代理节点会被真实启动,Lead 节点会暂停运行、由对话本体执行。
|
|
@@ -116,9 +116,10 @@ DSH 生态里不止一个「工作流画布」。本项目在侧边栏里编排*
|
|
|
116
116
|
先调用 `skill` 工具加载 `workflow-canvas`。
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
-
##
|
|
119
|
+
## 开发与原理
|
|
120
120
|
|
|
121
|
-
|
|
121
|
+
- 底层架构、双向同步通道、波次执行、三种连线运行时行为与冷恢复机制详见 [**工作机制与架构原理**](docs/MECHANISM.zh.md)([English](docs/MECHANISM.md))。
|
|
122
|
+
- 编辑 `client.js` / `index.js` 后重载应用;客户端改动热更生效,Host 改动需要重启。运行 `npm test` 执行单测;插件详情页说明见 [docs/DETAIL.md](docs/DETAIL.md)。
|
|
122
123
|
|
|
123
124
|
## 许可
|
|
124
125
|
|
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/DETAIL.md
CHANGED
|
@@ -63,5 +63,7 @@ if the Host refuses, the record is dropped and the node starts fresh.
|
|
|
63
63
|
- Saved presets live in browser storage and do not auto-sync between the Desktop
|
|
64
64
|
app and `dsh web`, nor across machines (use `⋯ → ⇧ Copy JSON` and `⇩ Import`
|
|
65
65
|
to share or migrate them; starter templates are built in under `☰ Presets`).
|
|
66
|
-
- Lead steps have no tracked state; they show **Runs in chat
|
|
66
|
+
- Lead steps have no tracked state; they show **Runs in chat** (or **Ready** once all upstream subagents finish).
|
|
67
67
|
- Up to 4 nodes run at a time.
|
|
68
|
+
|
|
69
|
+
For architecture diagrams and runtime internals, see [MECHANISM.md](MECHANISM.md) ([中文](MECHANISM.zh.md)).
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Mechanism & Architecture
|
|
2
|
+
|
|
3
|
+
English | [中文](MECHANISM.zh.md)
|
|
4
|
+
|
|
5
|
+
This document explains how **DSH Workflow Canvas** works under the hood: how the
|
|
6
|
+
sidebar canvas (Client) and the DSH Host stay in sync, how the DAG executor runs
|
|
7
|
+
parallel waves and pauses at Lead gates, what the three link types actually do
|
|
8
|
+
at run time, and how memory cold-resume, fallbacks, and live status tracking work.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Architecture: Bidirectional Client ↔ Host Bridge
|
|
13
|
+
|
|
14
|
+
The plugin splits cleanly into two halves:
|
|
15
|
+
- **Client (`client.js`)**: Mounted as a right-sidebar `Workflow` tab (`keepMounted: true`, preserving state while collapsed). Owns visual editing, presets, shortcuts, visual effects, and live status rendering.
|
|
16
|
+
- **Host (`index.js`)**: Registers the bundled `workflow-canvas` skill, the `/canvas-sync` command, and four tools (`canvas_inspect`, `canvas_generate`, `canvas_patch`, `canvas_workflow`). Owns real subagent execution and durable state persistence.
|
|
17
|
+
|
|
18
|
+
```mermaid
|
|
19
|
+
flowchart LR
|
|
20
|
+
subgraph Client["Sidebar Canvas (client.js)"]
|
|
21
|
+
UI["Graph Editor / Presets / Status Pills"]
|
|
22
|
+
LS["localStorage\n(drafts / presets / prefs)"]
|
|
23
|
+
Poll["workspaceFiles Poll\n(every 1.5s)"]
|
|
24
|
+
Cat["subagentCatalog Observer\n(every 700ms while running)"]
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
subgraph Host["Host Plugin (index.js)"]
|
|
28
|
+
Sync["/canvas-sync command"]
|
|
29
|
+
Store["Atomic Disk Store\n.workflow-canvas-state.json"]
|
|
30
|
+
Tools["canvas_inspect / generate / patch"]
|
|
31
|
+
Exec["canvas_workflow\nDAG Wave Executor"]
|
|
32
|
+
Sub["ctx.subagents\nReal Child Sessions"]
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
UI <--> LS
|
|
36
|
+
UI -- "enable / sync / turn edge\n/canvas-sync" --> Sync
|
|
37
|
+
Sync --> Store
|
|
38
|
+
Tools -- "writes .dsh/canvas/<sid>.json" --> Poll
|
|
39
|
+
Poll -- "timestamp guard + merge layout" --> UI
|
|
40
|
+
Exec <--> Store
|
|
41
|
+
Exec -- "startActivation\nlabel#nodeId" --> Sub
|
|
42
|
+
Sub -- "live status & childId" --> Cat
|
|
43
|
+
Cat --> UI
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Sync & Conflict-Free Editing
|
|
47
|
+
1. **Canvas → Host (`pushPlan` → `/canvas-sync`)**:
|
|
48
|
+
- Triggered when pressing **● ON**, clicking `↥ Sync`, or starting a chat turn while `enabled && dirty`.
|
|
49
|
+
- The Host stores the plan per session in `canvasBySession` and persists it **atomically** (write `.tmp` → `renameSync`) to `<DSH_PROFILE_DIR>/.workflow-canvas-state.json`, so plans and node memory survive Host restarts.
|
|
50
|
+
2. **Host → Canvas (Workspace Bridge + 1.5s Polling)**:
|
|
51
|
+
- `canvas_generate` and `canvas_patch` update `canvasBySession` immediately and publish `<workspace>/.dsh/canvas/<sessionId>.json` stamped with `at`.
|
|
52
|
+
- The client polls via `remote.workspaceFiles.read` every 1.5s.
|
|
53
|
+
- **Local-wins timestamp guard**: every local edit updates `localStorage.at`; a stale bridge file with `doc.at < local.at` is ignored so manual edits are never clobbered.
|
|
54
|
+
- **In-place `merge` mode**: `canvas_patch` publishes `mode: "merge"` together with `removeNodes` and `removeEdges`, so existing node coordinates and the current viewport remain untouched while newly added nodes are placed neatly relative to their upstream parent.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 2. DAG Wave Execution & Lead Handover
|
|
59
|
+
|
|
60
|
+
When `canvas_workflow` runs, `executePlan` executes the following pipeline:
|
|
61
|
+
|
|
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
|
+
2. **Cycle validation (Kahn topological sort)**: `orderNodes` validates the DAG is acyclic (the client also blocks cycles interactively via `wouldCycle`).
|
|
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. **Event-driven concurrency pool & resumable pauses**:
|
|
66
|
+
- Progress per session is tracked in `runBySession` (`{ sig, done, results, labels, failed }`).
|
|
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
|
+
- The conversation performs that Lead step and calls `canvas_workflow({ leadResult: "..." })` to resume seamlessly.
|
|
71
|
+
- Changing the graph (different plan `sig`) or passing `reset: true` discards paused progress and restarts cleanly.
|
|
72
|
+
|
|
73
|
+
```mermaid
|
|
74
|
+
sequenceDiagram
|
|
75
|
+
participant Chat as Main Chat (Lead)
|
|
76
|
+
participant Exec as Host Executor (executePlan)
|
|
77
|
+
participant Sub1 as Subagents Wave 1 (up to 4)
|
|
78
|
+
participant Sub2 as Subagents Wave 2 (up to 4)
|
|
79
|
+
|
|
80
|
+
Chat->>Exec: canvas_workflow()
|
|
81
|
+
Exec->>Sub1: Parallel startActivation (Nodes A, B)
|
|
82
|
+
Sub1-->>Exec: Results (text or structured JSON)
|
|
83
|
+
Note over Exec: Reaches Lead node — pauses with state kept
|
|
84
|
+
Exec-->>Chat: status="need-lead" + results + sessions (purple links)
|
|
85
|
+
Note over Chat: Lead decides (can follow up with purple sessions)
|
|
86
|
+
Chat->>Exec: canvas_workflow(leadResult="approved plan")
|
|
87
|
+
Exec->>Sub2: Parallel startActivation (Nodes C, D)
|
|
88
|
+
Sub2-->>Exec: Results
|
|
89
|
+
Exec-->>Chat: status="done" + results + failed + skipped
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## 3. Runtime Semantics of the Three Link Types
|
|
95
|
+
|
|
96
|
+
The three link types are distinct runtime channels, not just visual colour coding:
|
|
97
|
+
|
|
98
|
+
| Link Type | Colour | Runtime Behaviour |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| `prompt` | grey | Appends upstream text as a labelled section inside the downstream node's `briefFor` prompt. |
|
|
101
|
+
| `structured` | blue | `spawnOnce` detects any outgoing `structured` edge and **automatically** injects a JSON `outputSchema` (`type: "object", additionalProperties: true`) into `startActivation`. `textOf` extracts `result.structured` as JSON and wraps it in a `` ```json `` block for downstream consumers. |
|
|
102
|
+
| `session` (`session-ref`) | purple | **Into a subagent**: resolves the upstream `childId` (preferring in-process `liveChild`, falling back to disk-persisted `childByNode`) and passes it to `startActivation({ ...spec, childId })`, running the downstream step **inside the upstream child's live conversation**.<br>**Into a Lead**: reports `sessions: [{ label, childId }]` in `need-lead` so the main chat can message that subagent directly for follow-ups or fixes. |
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## 4. Memory Cold-Resume, Fallback Retry & Failure Isolation
|
|
107
|
+
|
|
108
|
+
### Memory (`keepSession`) & Cold Resume
|
|
109
|
+
- The Host keeps two maps keyed by `<sessionId>::<nodeId>`: `liveChild` (current process) and `childByNode` (persisted in `.workflow-canvas-state.json`).
|
|
110
|
+
- A node with `keepSession: true` resumes `liveChild || childByNode`.
|
|
111
|
+
- After a Host restart, `childByNode` enables **cold resume**; if the Host refuses activation (`activation-failed`), the stale ID is dropped and the node starts a fresh child session automatically.
|
|
112
|
+
|
|
113
|
+
### Fallback Model & Failure Reporting
|
|
114
|
+
- If a subagent fails to start (`activation-failed`), throws (`run-failed`), or stops with `stopReason !== 'completed'`:
|
|
115
|
+
1. When `fallbackModel` / `fallbackProvider` is configured, it retries once on the fallback route.
|
|
116
|
+
2. Unrecovered failures do **not** abort unrelated branches — they are recorded in `failed: [{ id, label, reason }]`.
|
|
117
|
+
3. Downstream prompts built by `briefFor` receive an explicit upstream-failure warning so downstream agents do not hallucinate on error text, and `canvas_workflow` highlights failed nodes prominently in its rendered summary.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## 5. Live Status Pills & Click-to-Open Subagent Chats
|
|
122
|
+
|
|
123
|
+
1. **Node tagging**: `spawnOnce` tags every spawned child with `label: "<node.label>#<node.id>"`.
|
|
124
|
+
2. **Catalog projection tracking**: While a turn runs (every 700ms, plus on mount and turn completion), the client reads `subagentCatalog` and `subagentTiming` from `sessions.list`, matching `/#([^\s#]+)$/` to map each child back to its canvas node (`running` / `done` / `failed`) and latest `childId`.
|
|
125
|
+
3. **Lead `⏸ Ready` detection**: For non-entry Lead nodes, the client highlights **`⏸ Ready`** as soon as all upstream subagents are `done` and no downstream node has started yet.
|
|
126
|
+
4. **Jump to live chat**: Clicking any subagent's status pill (e.g. `Running ↗`, `Done ↗`) opens `dsh-resource://subagentchat/session/<childId>?parent=<sessionId>&mode=<mode>` via `sidebarRight.openResource(..., { kind: 'subagentchat', preferNewPane: true })`.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## 6. Skill & Tool Discovery
|
|
131
|
+
|
|
132
|
+
Because DSH loads skills on demand rather than auto-injecting every plugin guide, the plugin combines three layers for reliable agent adoption:
|
|
133
|
+
1. **Bundled skill provider**: `index.js` registers `workflow-canvas` via `ctx.skills.registerProvider` with bilingual trigger keywords (`canvas / workflow / pipeline / 画布 / 工作流 / 编排`) and all four `canvas_*` tool names, serving [skills/workflow-canvas/SKILL.md](../skills/workflow-canvas/SKILL.md).
|
|
134
|
+
2. **Tool-level pointers**: Every `canvas_*` tool description reminds the model to load the `workflow-canvas` skill first, and tool schemas are always in context.
|
|
135
|
+
3. **Optional `AGENTS.md` rule**: Adding a single line in a project's `AGENTS.md` guarantees deterministic skill loading in every session.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# 工作机制与架构原理
|
|
2
|
+
|
|
3
|
+
中文 | [English](MECHANISM.md)
|
|
4
|
+
|
|
5
|
+
本文说明 **DSH Workflow Canvas** 的底层实现机制:侧边栏画布(Client)如何与 DSH Host 双向同步、DAG 执行器如何按波次调度子代理与暂停交接、三种连线在运行时的真实差异,以及记忆冷恢复、失败降级和实时状态追踪的工作方式。
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. 整体架构:Client 与 Host 的双向通道
|
|
10
|
+
|
|
11
|
+
插件由两部分组成:
|
|
12
|
+
- **客户端(`client.js`)**:挂载在 DSH 右侧边栏的 `Workflow` 标签页(`keepMounted: true`,收起侧边栏时保留画布状态),负责图形编辑、交互、预设存储与实时状态渲染。
|
|
13
|
+
- **Host 侧(`index.js`)**:注册技能 `workflow-canvas`、同步命令 `/canvas-sync`,以及 4 个工具(`canvas_inspect`、`canvas_generate`、`canvas_patch`、`canvas_workflow`),负责真实调度子代理和持久化执行状态。
|
|
14
|
+
|
|
15
|
+
```mermaid
|
|
16
|
+
flowchart LR
|
|
17
|
+
subgraph Client["客户端画布 (client.js)"]
|
|
18
|
+
UI["画布编辑 / 预设 / 状态胶囊"]
|
|
19
|
+
LS["localStorage\n(画布草稿 / 预设 / 偏好)"]
|
|
20
|
+
Poll["workspaceFiles 轮询\n(每 1.5s)"]
|
|
21
|
+
Cat["subagentCatalog 投影监听\n(运行中每 700ms)"]
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
subgraph Host["Host 插件 (index.js)"]
|
|
25
|
+
Sync["/canvas-sync 命令"]
|
|
26
|
+
Store["原子持久化\n.workflow-canvas-state.json"]
|
|
27
|
+
Tools["canvas_inspect / generate / patch"]
|
|
28
|
+
Exec["canvas_workflow\nDAG 波次执行器"]
|
|
29
|
+
Sub["ctx.subagents\n真实子代理会话"]
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
UI <--> LS
|
|
33
|
+
UI -- "启用 / 同步 / 轮次边界\n/canvas-sync" --> Sync
|
|
34
|
+
Sync --> Store
|
|
35
|
+
Tools -- "写入 .dsh/canvas/<sid>.json" --> Poll
|
|
36
|
+
Poll -- "时间戳比对 + merge 保留排版" --> UI
|
|
37
|
+
Exec <--> Store
|
|
38
|
+
Exec -- "startActivation\nlabel#nodeId" --> Sub
|
|
39
|
+
Sub -- "状态与 childId" --> Cat
|
|
40
|
+
Cat --> UI
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### 双向同步与防覆盖机制
|
|
44
|
+
1. **画布 → Host(`pushPlan` → `/canvas-sync`)**:
|
|
45
|
+
- 用户点击 **● 已启用**、手动点击 `↥ 同步`,或在已启用且有未同步改动(`dirty`)时发送新消息触发轮次切换,客户端会把当前有效执行计划编码后通过 `/canvas-sync` 推送给 Host;
|
|
46
|
+
- Host 存入按会话隔离的 `canvasBySession`,并通过写 `.tmp` 再 `renameSync` 的方式**原子落盘**到 `<DSH_PROFILE_DIR>/.workflow-canvas-state.json`,因此重启 Host 后画布计划与节点记忆都不会丢失。
|
|
47
|
+
2. **Host → 画布(工作区桥接文件 + 1.5s 轮询)**:
|
|
48
|
+
- 当对话调用 `canvas_generate` 或 `canvas_patch` 时,Host 一方面直接更新 `canvasBySession`,另一方面把文档写入 `<workspace>/.dsh/canvas/<sessionId>.json`(携带时间戳 `at`);
|
|
49
|
+
- 客户端面板每 1.5 秒通过 `remote.workspaceFiles.read` 读取该文件;
|
|
50
|
+
- **本地优先防覆盖**:每次手动编辑都会给 `localStorage` 记上时间戳 `at`,若本地时间晚于远端文件,旧文件不会覆盖用户的最新改动;
|
|
51
|
+
- **就地合并(`merge` 模式)**:`canvas_patch` 下发 `mode: "merge"` 与 `removeNodes` / `removeEdges`,客户端按节点 ID 就地合并字段,**完整保留用户手摆坐标与当前视角**,仅给新增节点按上游位置智能排布。
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 2. DAG 波次执行与 Lead 暂停交接
|
|
56
|
+
|
|
57
|
+
调用 `canvas_workflow` 时,Host 的 `executePlan` 按以下流水线运行:
|
|
58
|
+
|
|
59
|
+
1. **入口剥离与任务解析**:剥离作为总任务容器的入口节点 `lead`(永不作为子代理执行)。若调用时传入 `task` 参数,则覆盖入口 Lead 的总任务(方便直接复用空任务预设)。
|
|
60
|
+
2. **成环校验(Kahn 拓扑排序)**:用 `orderNodes` 校验 DAG 无环(客户端手动画线时也会用 `wouldCycle` 即时拦截)。
|
|
61
|
+
3. **可达性剪枝**:从入口 `lead` 做广度优先遍历,不可达的孤立节点在画布上显示为虚线,运行时被自动跳过并列入 `skipped`,不会消耗 Token。
|
|
62
|
+
4. **事件驱动并发池与暂停续跑**:
|
|
63
|
+
- 每个会话的运行进度保存在 `runBySession`(包含计划签名 `sig`、`done`、`results`、`labels`、`failed`);
|
|
64
|
+
- 执行器维护一个上限为 **4 并发**(`MAX_PARALLEL = 4`)的**动态并发池(`inFlight` + `Promise.race`)**,而非同步屏障:
|
|
65
|
+
- 只要有任意在跑子代理完成、空出并发槽位,**任何依赖已满足的下游子代理会立刻启动**,不再傻等同层较慢的兄弟节点;
|
|
66
|
+
- 直到当前所有可执行子代理全部跑完、仅剩 **非入口 Lead 节点**就绪且尚未收到 `leadResult` 时,执行器暂停并返回 `status: "need-lead"`(入口 Lead 仅承载总任务,不会触发暂停),把已收集结果、失败汇总以及紫线 `childId` 交回主对话;
|
|
67
|
+
- 主对话完成该 Lead 步骤后,再次调用 `canvas_workflow({ leadResult: "..." })`,执行器从断点无缝继续;
|
|
68
|
+
- 若中途修改了画布(计划签名 `sig` 变化)或显式传入 `reset: true`,则丢弃旧进度从头重跑。
|
|
69
|
+
|
|
70
|
+
```mermaid
|
|
71
|
+
sequenceDiagram
|
|
72
|
+
participant Chat as 主对话 (Lead)
|
|
73
|
+
participant Exec as Host 执行器 (executePlan)
|
|
74
|
+
participant Sub1 as 子代理 Wave 1 (并行 ≤4)
|
|
75
|
+
participant Sub2 as 子代理 Wave 2 (并行 ≤4)
|
|
76
|
+
|
|
77
|
+
Chat->>Exec: canvas_workflow()
|
|
78
|
+
Exec->>Sub1: 并行 startActivation (节点 A, B)
|
|
79
|
+
Sub1-->>Exec: 返回结果 (或结构化 JSON)
|
|
80
|
+
Note over Exec: 遇到中间 Lead 节点,保留进度暂停
|
|
81
|
+
Exec-->>Chat: status="need-lead" + results + sessions(紫线)
|
|
82
|
+
Note over Chat: Lead 拍板(必要时可直接追问紫线子代理)
|
|
83
|
+
Chat->>Exec: canvas_workflow(leadResult="拍板结论")
|
|
84
|
+
Exec->>Sub2: 并行 startActivation (节点 C, D)
|
|
85
|
+
Sub2-->>Exec: 返回结果
|
|
86
|
+
Exec-->>Chat: status="done" + results + failed + skipped
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 3. 三种连线的底层语义差异
|
|
92
|
+
|
|
93
|
+
三种连线不只是视觉颜色区分,在 Host 执行器里对应完全不同的数据与会话通道:
|
|
94
|
+
|
|
95
|
+
| 连线类型 | 颜色 | 运行时底层行为 |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `prompt` | 灰 | 将上游输出文本作为独立 Markdown 章节拼入下游 `briefFor` prompt。 |
|
|
98
|
+
| `structured` | 蓝 | `spawnOnce` 检测到节点有 `structured` 出边时,**自动**在 `startActivation` 中注入 JSON `outputSchema`(`type: "object", additionalProperties: true`);执行完成后通过 `textOf` 优先提取解析后的 `result.structured` 序列化为 JSON,再以 `` ```json `` 代码块交给下游。 |
|
|
99
|
+
| `session` (`session-ref`) | 紫 | **指向子代理时**:查找上游节点的 `childId`(优先进程内 `liveChild`,重启后兜底读落盘 `childByNode`),直接作为 `childId` 传入 `startActivation`,下游**在上游的同一个子会话里继续跑**(完整保留上游上下文与工具历史,无需重新读代码库);<br>**指向 Lead 时**:在 `need-lead` 返回的 `sessions: [{ label, childId }]` 里上报该子会话 ID,主对话可直接给对应子代理发消息追问或下达补修。 |
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 4. 记忆冷恢复、备用模型与失败隔离
|
|
104
|
+
|
|
105
|
+
### 记忆(`keepSession`)与冷恢复
|
|
106
|
+
- Host 维护两层映射:`liveChild`(当前进程内活跃会话)和 `childByNode`(随 `.workflow-canvas-state.json` 落盘,按 `sessionId::nodeId` 隔离)。
|
|
107
|
+
- 节点开启记忆后,再次运行时按 `liveChild → childByNode` 顺序尝试复用旧 `childId`。
|
|
108
|
+
- **Host 重启后的冷恢复**:重启后 `liveChild` 为空,执行器会用落盘的 `childByNode` 尝试冷恢复;如果 Host 拒绝激活(`activation-failed`),插件会自动清除过期记录并无缝改开新会话,不会卡死工作流。
|
|
109
|
+
|
|
110
|
+
### 备用模型降级与失败透传
|
|
111
|
+
- 任意子代理出现启动失败(`activation-failed`)、运行异常(`run-failed`)或 `stopReason !== 'completed'` 时:
|
|
112
|
+
1. 若配置了 `fallbackModel` / `fallbackProvider`,自动用备用模型重试一次;
|
|
113
|
+
2. 若未配置备用模型或重试仍失败,**不中断整张图的其他分支**,而是把该节点记入 `failed: [{ id, label, reason }]`;
|
|
114
|
+
3. 同时在下游节点的 `briefFor` 上游段落头部插入显式警告,提示下游不要把报错文本当作正常结论继续编造,并在最终返回及 Lead 暂停输出中高亮列出所有失败节点。
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## 5. 实时状态胶囊与点击直达子会话
|
|
119
|
+
|
|
120
|
+
1. **节点反查标记**:`spawnOnce` 启动子代理时,固定把 `spec.label` 设为 `<节点名>#<nodeId>`。
|
|
121
|
+
2. **状态实时追踪**:客户端监听当前会话的运行态,在对话运行期间每 700ms(以及挂载与每轮结束时)读取 `sessions.list` 投影中的 `subagentCatalog` 与 `subagentTiming`,用末尾正则 `/#([^\s#]+)$/` 精准反查节点状态(`running` / `done` / `failed`)以及对应的 `childId`。
|
|
122
|
+
3. **Lead「待拍板」自动高亮**:对于非入口 Lead 节点,客户端检测到其所有上游子代理均为 `done` 且下游尚未启动时,自动亮起蓝色 **`⏸ 待拍板`** 提示。
|
|
123
|
+
4. **一键直达真实子对话**:点击任意子代理节点右下角状态胶囊(如 `进行中 ↗` / `已完成 ↗`),客户端调用 `sidebarRight.openResource('dsh-resource://subagentchat/session/<childId>?parent=<sessionId>&mode=<mode>', { kind: 'subagentchat', preferNewPane: true })`,直接在新侧边窗格打开该子代理的真实对话记录。
|
|
124
|
+
|
|
125
|
+
---
|
|
126
|
+
|
|
127
|
+
## 6. Skill 与工具引导机制
|
|
128
|
+
|
|
129
|
+
DSH 不会强制把所有插件文档塞进每次系统提示词,因此插件采用三层协同引导,让模型能稳定、准确地调用画布工具:
|
|
130
|
+
1. **Skill 目录注册**:`index.js` 通过 `ctx.skills.registerProvider` 注册内置技能 `workflow-canvas`,摘要中包含中英触发词(`canvas / workflow / pipeline / 画布 / 工作流 / 编排`)与 4 个 `canvas_*` 工具名;正文读取自 [skills/workflow-canvas/SKILL.md](../skills/workflow-canvas/SKILL.md)。
|
|
131
|
+
2. **工具说明互指**:`canvas_inspect`、`canvas_generate`、`canvas_patch`、`canvas_workflow` 的工具描述均提示模型按需先加载 `workflow-canvas` 技能,而工具定义始终在上下文中。
|
|
132
|
+
3. **项目级锁定(可选)**:在项目 `AGENTS.md` 中加一行显式指令,可在任意对话中实现最高触发稳定性。
|
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.
|