dsh-workflow-canvas 0.2.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -111
- package/README.zh.md +78 -75
- package/client.js +339 -190
- package/docs/DETAIL.md +13 -10
- package/docs/images/add-node-shift-a.gif +0 -0
- package/docs/images/connect-and-cut.gif +0 -0
- package/docs/images/lead-pause-resume.gif +0 -0
- package/docs/images/node-config.gif +0 -0
- package/docs/images/node-entry-en.png +0 -0
- package/docs/images/node-entry-zh.png +0 -0
- package/docs/images/node-lead-en.png +0 -0
- package/docs/images/node-lead-zh.png +0 -0
- package/docs/images/node-subagent-en.png +0 -0
- package/docs/images/node-subagent-zh.png +0 -0
- package/docs/images/parallel-and-inspect.gif +0 -0
- package/index.js +281 -53
- package/package.json +1 -1
- package/skills/workflow-canvas/SKILL.md +6 -4
package/docs/DETAIL.md
CHANGED
|
@@ -9,14 +9,16 @@ are performed by the conversation itself.
|
|
|
9
9
|
|
|
10
10
|
- **Subagent node** (green top bar): spawns a child agent with its own
|
|
11
11
|
`provider` / `model` / `reasoning effort` / capability scope (`standard` or
|
|
12
|
-
`minimal
|
|
13
|
-
**Fallback** retries once on another model.
|
|
12
|
+
`minimal`, bounded by the main chat permission mode). Optional **Memory** reuses
|
|
13
|
+
the node's child session; optional **Fallback** retries once on another model.
|
|
14
14
|
- **Lead node** (blue top bar): performed by the conversation, never spawned. The
|
|
15
|
-
entry node carries the overall task;
|
|
15
|
+
entry node carries the overall task; intermediate Lead nodes pause for your
|
|
16
|
+
decision, and a terminal Lead finishes in one shot without an extra callback.
|
|
16
17
|
- **Sockets are typed** (`prompt` / `structured` / `session`); a link only joins
|
|
17
18
|
the same type (either direction), and cycles are blocked immediately. Drag a
|
|
18
19
|
connected input away to detach.
|
|
19
|
-
-
|
|
20
|
+
- Inactive nodes (unreachable from entry, solo chained Leads with no subagent
|
|
21
|
+
upstream, or dangling dead-end subagents) are drawn dashed and skipped at run time.
|
|
20
22
|
- Wheel zooms around the cursor; middle-drag (or `Space` + drag) pans; `⊡ Fit`
|
|
21
23
|
fits all nodes into the visible viewport; the percentage button resets to 100%
|
|
22
24
|
on the Lead.
|
|
@@ -45,12 +47,13 @@ node positions survive.
|
|
|
45
47
|
|
|
46
48
|
## Running
|
|
47
49
|
|
|
48
|
-
Subagent nodes run in
|
|
49
|
-
supports `task` (override the entry task for template
|
|
50
|
-
(discard a paused run)
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
50
|
+
Subagent nodes run in an event-driven concurrency pool (up to 4) via
|
|
51
|
+
`canvas_workflow`, which supports `task` (override the entry task for template
|
|
52
|
+
reuse), `reset: true` (discard a paused run), and `clearMemory: true` (forget
|
|
53
|
+
saved `keepSession` memories). While enabled, a per-session runtime context
|
|
54
|
+
notifies the agent automatically. Intermediate Lead nodes pause with
|
|
55
|
+
`status: "need-lead"` and report `failed` / `emptyOutputs` plus `session`
|
|
56
|
+
handovers; a terminal Lead completes directly with `status: "done"` and `finalLead`.
|
|
54
57
|
|
|
55
58
|
## Memory
|
|
56
59
|
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/index.js
CHANGED
|
@@ -222,8 +222,10 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
222
222
|
}
|
|
223
223
|
try {
|
|
224
224
|
if (activation && activation.childId) {
|
|
225
|
-
childByNode.set(childKey(node.id), activation.childId);
|
|
226
225
|
liveChild.set(childKey(node.id), activation.childId);
|
|
226
|
+
// Only overwrite the persisted memory slot when Memory is ON, so a
|
|
227
|
+
// temporary keepSession=false experiment never destroys saved memory.
|
|
228
|
+
if (node.keepSession) childByNode.set(childKey(node.id), activation.childId);
|
|
227
229
|
}
|
|
228
230
|
let result;
|
|
229
231
|
try {
|
|
@@ -257,19 +259,20 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
257
259
|
/* activation refused (e.g. cold session gone): fall through to a fresh session */
|
|
258
260
|
}
|
|
259
261
|
|
|
260
|
-
// Memory: prefer
|
|
261
|
-
//
|
|
262
|
-
//
|
|
262
|
+
// Memory: prefer an explicitly pinned `memoryChildId` from the node dropdown,
|
|
263
|
+
// then the saved memory slot (`childByNode`), then this process's live child.
|
|
264
|
+
// A cold resume that the Host refuses falls through to a fresh session.
|
|
263
265
|
if (node.keepSession) {
|
|
266
|
+
const pinned = typeof node.memoryChildId === 'string' ? node.memoryChildId.trim() : '';
|
|
267
|
+
const saved = childByNode.get(childKey(node.id));
|
|
264
268
|
const inProcess = liveChild.get(childKey(node.id));
|
|
265
|
-
const
|
|
266
|
-
const previous = inProcess || fromDisk;
|
|
269
|
+
const previous = pinned || saved || inProcess;
|
|
267
270
|
if (previous) {
|
|
268
271
|
const resumed = await run(previous);
|
|
269
272
|
if (resumed.ok) return resumed;
|
|
270
273
|
if (resumed.reason === 'activation-failed') {
|
|
271
|
-
liveChild.delete(childKey(node.id));
|
|
272
|
-
childByNode.delete(childKey(node.id));
|
|
274
|
+
if (previous === inProcess) liveChild.delete(childKey(node.id));
|
|
275
|
+
if (previous === saved) childByNode.delete(childKey(node.id));
|
|
273
276
|
} else {
|
|
274
277
|
return resumed;
|
|
275
278
|
}
|
|
@@ -310,24 +313,83 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
310
313
|
return { ok: false, empty: false, reason, text: retry.text + '\n(重试仍失败:' + reason + ')' };
|
|
311
314
|
}
|
|
312
315
|
|
|
313
|
-
/** Ids reachable from the entry Lead; every other node is skipped at run time. */
|
|
316
|
+
/** Ids reachable from the entry Lead via O(V + E) BFS; every other node is skipped at run time. */
|
|
314
317
|
function reachableFrom(plan) {
|
|
318
|
+
const adj = new Map();
|
|
319
|
+
for (const e of (plan && plan.edges) || []) {
|
|
320
|
+
if (!e || !e.from || !e.to) continue;
|
|
321
|
+
if (!adj.has(e.from)) adj.set(e.from, []);
|
|
322
|
+
adj.get(e.from).push(e.to);
|
|
323
|
+
}
|
|
315
324
|
const set = new Set(['lead']);
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
for (const
|
|
320
|
-
if (
|
|
325
|
+
const queue = ['lead'];
|
|
326
|
+
for (let i = 0; i < queue.length; i += 1) {
|
|
327
|
+
const cur = queue[i];
|
|
328
|
+
for (const next of adj.get(cur) || []) {
|
|
329
|
+
if (!set.has(next)) { set.add(next); queue.push(next); }
|
|
321
330
|
}
|
|
322
331
|
}
|
|
323
332
|
return set;
|
|
324
333
|
}
|
|
325
334
|
|
|
326
335
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
*
|
|
336
|
+
* Classify inactive nodes that are rendered dashed on the canvas and skipped at run time:
|
|
337
|
+
* - unreachable orphans
|
|
338
|
+
* - solo chained Leads (zero reachable subagent upstream)
|
|
339
|
+
* - dangling dead-end subagents (zero outgoing edges while an active non-ancestor downstream Lead exists)
|
|
340
|
+
*/
|
|
341
|
+
function inactiveNodeSets(nodes, edges) {
|
|
342
|
+
const list = withoutEntry(nodes);
|
|
343
|
+
const linkList = Array.isArray(edges) ? edges : [];
|
|
344
|
+
const reachable = reachableFrom({ edges: linkList });
|
|
345
|
+
const byId = new Map(list.map((n) => [n.id, n]));
|
|
346
|
+
|
|
347
|
+
const soloLeads = new Set();
|
|
348
|
+
for (const n of list) {
|
|
349
|
+
if (n.kind !== 'lead' || !reachable.has(n.id)) continue;
|
|
350
|
+
const hasAgentUp = linkList.some((e) => {
|
|
351
|
+
if (!e || e.to !== n.id || !reachable.has(e.from) || e.from === 'lead') return false;
|
|
352
|
+
const src = byId.get(e.from);
|
|
353
|
+
return Boolean(src && src.kind !== 'lead');
|
|
354
|
+
});
|
|
355
|
+
if (!hasAgentUp) soloLeads.add(n.id);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const deadEnds = new Set();
|
|
359
|
+
const activeLeads = list.filter((n) => n.kind === 'lead' && reachable.has(n.id) && !soloLeads.has(n.id));
|
|
360
|
+
if (activeLeads.length) {
|
|
361
|
+
const hasOut = new Set(linkList.map((e) => e.from));
|
|
362
|
+
const parents = new Map();
|
|
363
|
+
for (const e of linkList) {
|
|
364
|
+
if (!parents.has(e.to)) parents.set(e.to, []);
|
|
365
|
+
parents.get(e.to).push(e.from);
|
|
366
|
+
}
|
|
367
|
+
const ancestorsOf = (id) => {
|
|
368
|
+
const seen = new Set();
|
|
369
|
+
const stack = [id];
|
|
370
|
+
while (stack.length) {
|
|
371
|
+
const cur = stack.pop();
|
|
372
|
+
for (const p of parents.get(cur) || []) {
|
|
373
|
+
if (!seen.has(p)) { seen.add(p); stack.push(p); }
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return seen;
|
|
377
|
+
};
|
|
378
|
+
for (const n of list) {
|
|
379
|
+
if (n.kind === 'lead' || !reachable.has(n.id) || hasOut.has(n.id)) continue;
|
|
380
|
+
const anc = ancestorsOf(n.id);
|
|
381
|
+
if (activeLeads.some((ln) => !anc.has(ln.id))) deadEnds.add(n.id);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return { reachable, soloLeads, deadEnds };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Detect structural warnings on a canvas plan (all three classes are rendered
|
|
389
|
+
* dashed on the canvas and skipped at run time):
|
|
390
|
+
* 1. Unreachable nodes.
|
|
391
|
+
* 2. Solo chained Lead nodes with zero subagent upstream.
|
|
392
|
+
* 3. Dangling dead-end subagent nodes with zero outgoing edges.
|
|
331
393
|
*/
|
|
332
394
|
function analyzeCanvasWarnings(nodes, edges) {
|
|
333
395
|
const list = withoutEntry(nodes);
|
|
@@ -335,21 +397,21 @@ function analyzeCanvasWarnings(nodes, edges) {
|
|
|
335
397
|
const warnings = [];
|
|
336
398
|
if (!list.length) return warnings;
|
|
337
399
|
|
|
338
|
-
const reachable =
|
|
400
|
+
const { reachable, soloLeads, deadEnds } = inactiveNodeSets(list, linkList);
|
|
339
401
|
const orphans = list.filter((n) => !reachable.has(n.id));
|
|
340
402
|
if (orphans.length) {
|
|
341
403
|
warnings.push('以下节点未从入口 Lead 连通,运行时会被跳过:'
|
|
342
404
|
+ orphans.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
343
405
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
406
|
+
const soloList = list.filter((n) => soloLeads.has(n.id));
|
|
407
|
+
if (soloList.length) {
|
|
408
|
+
warnings.push('以下 Lead 节点仅串联了其他 Lead、未连入子代理,运行时不生效:'
|
|
409
|
+
+ soloList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
410
|
+
}
|
|
411
|
+
const deadList = list.filter((n) => deadEnds.has(n.id));
|
|
412
|
+
if (deadList.length) {
|
|
413
|
+
warnings.push('以下子代理节点没有出边,产出未连入下游或终审 Lead,运行时不生效:'
|
|
414
|
+
+ deadList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
353
415
|
}
|
|
354
416
|
return warnings;
|
|
355
417
|
}
|
|
@@ -501,7 +563,7 @@ function normalizeCanvas(args) {
|
|
|
501
563
|
function applyPatch(plan, args) {
|
|
502
564
|
const nodes = withoutEntry(plan.nodes).map((n) => ({ ...n }));
|
|
503
565
|
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
504
|
-
const ALLOWED = ['label', 'role', 'provider', 'model', 'reasoning', 'preset', 'keepSession', 'structured', 'fallbackModel', 'fallbackProvider'];
|
|
566
|
+
const ALLOWED = ['label', 'role', 'provider', 'model', 'reasoning', 'preset', 'keepSession', 'memoryChildId', 'structured', 'fallbackModel', 'fallbackProvider'];
|
|
505
567
|
const touched = [];
|
|
506
568
|
for (const patch of args && Array.isArray(args.nodes) ? args.nodes : []) {
|
|
507
569
|
// 'lead' is the reserved entry node and is never edited here.
|
|
@@ -637,13 +699,82 @@ function inspectPlan(sid) {
|
|
|
637
699
|
nodes,
|
|
638
700
|
edges,
|
|
639
701
|
warnings: analyzeCanvasWarnings(nodes, edges),
|
|
640
|
-
paused: Boolean(sid && runBySession.
|
|
702
|
+
paused: Boolean(sid && runBySession.get(sid) && runBySession.get(sid).waitingLead),
|
|
641
703
|
};
|
|
642
704
|
// Never attach `error: undefined`: DSH's lossless JSON validator rejects keys with undefined values.
|
|
643
705
|
if (payload.error) out.error = String(payload.error);
|
|
644
706
|
return out;
|
|
645
707
|
}
|
|
646
708
|
|
|
709
|
+
/** Extract the active session id from a DSH `AssembleContext`. */
|
|
710
|
+
function sessionIdFromContext(assembleCtx) {
|
|
711
|
+
if (!assembleCtx || typeof assembleCtx !== 'object') return '';
|
|
712
|
+
if (assembleCtx.agent && assembleCtx.agent.id !== undefined) return String(assembleCtx.agent.id);
|
|
713
|
+
if (assembleCtx.sessionId !== undefined) return String(assembleCtx.sessionId);
|
|
714
|
+
return '';
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Per-turn runtime prompt context injected ONLY for the session whose canvas is
|
|
719
|
+
* currently enabled. Returns '' for disabled canvases, unrelated sessions, and
|
|
720
|
+
* subagent sessions (zero token overhead and no recursive triggering).
|
|
721
|
+
*/
|
|
722
|
+
function buildActiveCanvasContext(sid) {
|
|
723
|
+
if (!sid) return '';
|
|
724
|
+
const payload = canvasBySession.get(String(sid));
|
|
725
|
+
if (!payload || !payload.enabled || payload.error) return '';
|
|
726
|
+
const plan = payload.plan;
|
|
727
|
+
const nodes = withoutEntry(plan && plan.nodes);
|
|
728
|
+
if (!nodes.length) return '';
|
|
729
|
+
|
|
730
|
+
const runState = runBySession.get(String(sid));
|
|
731
|
+
if (runState && runState.waitingLead) {
|
|
732
|
+
const wl = runState.waitingLead;
|
|
733
|
+
return [
|
|
734
|
+
'[Workflow Canvas Active — Paused at Lead Step]',
|
|
735
|
+
'当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')。',
|
|
736
|
+
'- 若用户的当前消息是在拍板、确认、补充决策或要求继续:请整理决策结论并直接调用 `canvas_workflow({ leadResult: "..." })` 恢复下游节点运行。',
|
|
737
|
+
'- 若用户要求放弃当前进度从头重跑:调用 `canvas_workflow({ reset: true })`。',
|
|
738
|
+
'- 若用户要求修改画布结构/分工:先 `canvas_inspect` 再用 `canvas_patch`。',
|
|
739
|
+
].join('\n');
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
const preview = nodes
|
|
743
|
+
.slice(0, 8)
|
|
744
|
+
.map((n) => (n.kind === 'lead' ? '〔Lead〕' : '') + (n.label || n.id))
|
|
745
|
+
.join(' → ') + (nodes.length > 8 ? ' …' : '');
|
|
746
|
+
const hasTask = Boolean(String((plan && plan.task) || '').trim());
|
|
747
|
+
const prefix = String(sid) + '::';
|
|
748
|
+
const hasMemory = nodes.some((n) => n.keepSession && (liveChild.has(prefix + n.id) || childByNode.has(prefix + n.id)));
|
|
749
|
+
const lines = [
|
|
750
|
+
'[Workflow Canvas Active]',
|
|
751
|
+
'当前会话的右侧工作流画布处于「● 已启用」状态(共 ' + nodes.length + ' 个执行节点:' + preview + ';入口总任务:' + (hasTask ? '已填写' : '未填写') + ')。',
|
|
752
|
+
'- 若用户发出任务请求、布置工作或说「开始 / 执行 / 跑一次」:请直接调用 `canvas_workflow` 按画布编排执行('
|
|
753
|
+
+ (hasTask ? '可直接沿用入口总任务;若用户给出了新任务则通过 task 参数传入' : '请将用户的任务内容作为 task 参数传入')
|
|
754
|
+
+ '),不要绕过画布直接自己完成。',
|
|
755
|
+
'- 若用户在讨论或要求修改画布结构、模型、分工或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
|
|
756
|
+
'- 仅当用户明确只是闲聊、问无关问题或要求先停用画布时,才无需调用 `canvas_workflow`。',
|
|
757
|
+
];
|
|
758
|
+
if (hasMemory) {
|
|
759
|
+
lines.push('- 本会话已有开启「记忆」节点的历史子代理会话:若用户说「再跑一次 / 换个任务重跑」,请先简短询问用户是保留上次记忆继续(reset: true)还是清空记忆全新开跑(reset: true, clearMemory: true)。');
|
|
760
|
+
}
|
|
761
|
+
const stdCount = nodes.filter((n) => n.kind !== 'lead' && n.preset !== 'minimal').length;
|
|
762
|
+
if (stdCount >= 2) {
|
|
763
|
+
lines.push('- 本画布包含 ' + stdCount + ' 个可写/命令型(standard)子代理,受主对话权限上限约束;若任务涉及改代码、写文件或跑终端命令且当前主对话权限偏严格,请先简短提醒用户放开主对话权限再调 `canvas_workflow`,避免中途报错白耗额度。');
|
|
764
|
+
}
|
|
765
|
+
return lines.join('\n');
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/** Detect permission / sandbox denial outcomes so we can circuit-break before burning downstream tokens. */
|
|
769
|
+
const PERMISSION_ERR_RE = /permission denied|access is denied|sandbox-local|windows-acl|win32error|eacces|eperm|approval required|not permitted|拒绝访问|权限不足|无权执行|沙箱拒绝/i;
|
|
770
|
+
function isPermissionFailure(outcome) {
|
|
771
|
+
if (!outcome) return false;
|
|
772
|
+
const text = String(outcome.text || '');
|
|
773
|
+
if (!outcome.ok && PERMISSION_ERR_RE.test(text)) return true;
|
|
774
|
+
if (text.includes('【未完全交付】') && PERMISSION_ERR_RE.test(text)) return true;
|
|
775
|
+
return false;
|
|
776
|
+
}
|
|
777
|
+
|
|
647
778
|
/** Takes a plan directly so tests can feed any plan shape (sync, generate, patch). */
|
|
648
779
|
async function executePlan(scope, plan, args, exec) {
|
|
649
780
|
const opts = args || {};
|
|
@@ -666,19 +797,24 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
666
797
|
const order = orderNodes(plan);
|
|
667
798
|
if (!order) return { error: '存在环,无法执行有向无环图。' };
|
|
668
799
|
|
|
669
|
-
// Defense in depth: unreachable
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
800
|
+
// Defense in depth: unreachable orphans, solo chained Leads, and dangling
|
|
801
|
+
// dead-end subagents are skipped instead of wasting tokens or stalling.
|
|
802
|
+
const { reachable, soloLeads, deadEnds } = inactiveNodeSets(plan.nodes, plan.edges);
|
|
803
|
+
const isInactive = (n) => !reachable.has(n.id) || soloLeads.has(n.id) || deadEnds.has(n.id);
|
|
804
|
+
const runnable = order.filter((n) => !isInactive(n));
|
|
805
|
+
const skipped = order.filter((n) => isInactive(n)).map((n) => n.label || n.id);
|
|
806
|
+
if (!runnable.length) return { error: '没有从入口 Lead 连通的有效节点,无法执行。' };
|
|
807
|
+
|
|
808
|
+
if (opts.clearMemory === true && sid) {
|
|
809
|
+
const prefix = String(sid) + '::';
|
|
810
|
+
for (const key of Array.from(childByNode.keys())) {
|
|
811
|
+
if (key.startsWith(prefix)) childByNode.delete(key);
|
|
676
812
|
}
|
|
813
|
+
for (const key of Array.from(liveChild.keys())) {
|
|
814
|
+
if (key.startsWith(prefix)) liveChild.delete(key);
|
|
815
|
+
}
|
|
816
|
+
saveStore();
|
|
677
817
|
}
|
|
678
|
-
const runnable = order.filter((n) => reachable.has(n.id));
|
|
679
|
-
const skipped = order.filter((n) => !reachable.has(n.id)).map((n) => n.label || n.id);
|
|
680
|
-
if (!runnable.length) return { error: '没有从入口 Lead 连通的节点,无法执行。' };
|
|
681
|
-
|
|
682
818
|
if (opts.reset === true && sid) {
|
|
683
819
|
runBySession.delete(sid);
|
|
684
820
|
}
|
|
@@ -686,7 +822,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
686
822
|
const sig = JSON.stringify(plan);
|
|
687
823
|
let state = runBySession.get(sid);
|
|
688
824
|
if (!state || state.sig !== sig) {
|
|
689
|
-
state = { sig, done: new Set(), results: {}, labels: {}, failed: {}, emptyOutputs: {} };
|
|
825
|
+
state = { sig, done: new Set(), results: {}, labels: {}, failed: {}, emptyOutputs: {}, waitingLead: null };
|
|
690
826
|
runBySession.set(sid, state);
|
|
691
827
|
}
|
|
692
828
|
if (!state.emptyOutputs) state.emptyOutputs = {};
|
|
@@ -705,15 +841,18 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
705
841
|
const inFlight = new Map();
|
|
706
842
|
|
|
707
843
|
const isAborted = () => Boolean(exec && exec.signal && exec.signal.aborted);
|
|
844
|
+
const permBlocked = [];
|
|
845
|
+
let activationFailCount = 0;
|
|
846
|
+
let haltedReason = '';
|
|
708
847
|
|
|
709
848
|
const launchReadyAgents = () => {
|
|
710
|
-
if (isAborted() || inFlight.size >= MAX_PARALLEL) return;
|
|
849
|
+
if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) return;
|
|
711
850
|
const candidates = runnable.filter((n) => n.kind !== 'lead'
|
|
712
851
|
&& !state.done.has(n.id)
|
|
713
852
|
&& !inFlight.has(n.id)
|
|
714
853
|
&& depsOf(n).every((id) => state.done.has(id)));
|
|
715
854
|
for (const node of candidates) {
|
|
716
|
-
if (isAborted() || inFlight.size >= MAX_PARALLEL) break;
|
|
855
|
+
if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) break;
|
|
717
856
|
const promise = spawnNode(scope, plan, node, state.results, agent, exec.signal, sid, state.failed)
|
|
718
857
|
.then(
|
|
719
858
|
(outcome) => ({ node, outcome }),
|
|
@@ -725,8 +864,22 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
725
864
|
|
|
726
865
|
for (;;) {
|
|
727
866
|
if (isAborted()) {
|
|
867
|
+
if (sid) runBySession.delete(sid);
|
|
728
868
|
return { error: '工作流执行已取消。' };
|
|
729
869
|
}
|
|
870
|
+
if (haltedReason && inFlight.size === 0) {
|
|
871
|
+
if (sid) runBySession.delete(sid);
|
|
872
|
+
saveStore();
|
|
873
|
+
return {
|
|
874
|
+
status: 'halted',
|
|
875
|
+
error: haltedReason,
|
|
876
|
+
results: state.results,
|
|
877
|
+
labels: state.labels,
|
|
878
|
+
failed: Object.values(state.failed),
|
|
879
|
+
emptyOutputs: Object.values(state.emptyOutputs),
|
|
880
|
+
skipped,
|
|
881
|
+
};
|
|
882
|
+
}
|
|
730
883
|
const remaining = runnable.filter((n) => !state.done.has(n.id));
|
|
731
884
|
if (!remaining.length) {
|
|
732
885
|
runBySession.delete(sid);
|
|
@@ -747,15 +900,24 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
747
900
|
const { node, outcome } = await Promise.race(inFlight.values());
|
|
748
901
|
inFlight.delete(node.id);
|
|
749
902
|
if (isAborted()) {
|
|
903
|
+
if (sid) runBySession.delete(sid);
|
|
750
904
|
return { error: '工作流执行已取消。' };
|
|
751
905
|
}
|
|
752
906
|
state.results[node.id] = outcome.text;
|
|
753
907
|
state.labels[node.id] = node.label;
|
|
754
908
|
if (!outcome.ok) {
|
|
755
909
|
state.failed[node.id] = { id: node.id, label: node.label, reason: outcome.reason || 'unknown' };
|
|
910
|
+
if (outcome.reason === 'activation-failed') activationFailCount += 1;
|
|
756
911
|
} else if (outcome.empty) {
|
|
757
912
|
state.emptyOutputs[node.id] = { id: node.id, label: node.label };
|
|
758
913
|
}
|
|
914
|
+
if (isPermissionFailure(outcome)) {
|
|
915
|
+
permBlocked.push(node.label || node.id);
|
|
916
|
+
haltedReason = '检测到权限/沙箱受限导致节点失败(' + permBlocked.join('、')
|
|
917
|
+
+ '),已熔断停止启动后续节点以防继续消耗额度。请先检查主对话左下角权限模式,放开后重新运行。';
|
|
918
|
+
} else if (activationFailCount >= 2 && !haltedReason) {
|
|
919
|
+
haltedReason = '连续 ' + activationFailCount + ' 个子代理启动失败,已熔断停止后续节点以防继续消耗额度。请检查模型配置或主对话权限后重试。';
|
|
920
|
+
}
|
|
759
921
|
state.done.add(node.id);
|
|
760
922
|
continue;
|
|
761
923
|
}
|
|
@@ -765,7 +927,42 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
765
927
|
|
|
766
928
|
const leadNode = ready.find((n) => n.kind === 'lead');
|
|
767
929
|
if (!leadNode) return { error: '没有可执行的节点。' };
|
|
930
|
+
const leadSessions = depsOf(leadNode)
|
|
931
|
+
.filter((id) => (plan.edges || []).some((e) => e.to === leadNode.id && e.from === id && e.type === 'session-ref'))
|
|
932
|
+
.map((id) => ({
|
|
933
|
+
label: labelOf.get(id) || id,
|
|
934
|
+
childId: liveChild.get(String(sid || '') + '::' + id)
|
|
935
|
+
|| childByNode.get(String(sid || '') + '::' + id)
|
|
936
|
+
|| null,
|
|
937
|
+
}));
|
|
938
|
+
const hasDownstreamWork = remaining.some((n) => n.id !== leadNode.id);
|
|
939
|
+
if (!hasDownstreamWork && leadResult === undefined) {
|
|
940
|
+
// Terminal Lead: zero downstream nodes remain, so complete the run directly
|
|
941
|
+
// and hand off final review/delivery to the Lead without a redundant extra turn.
|
|
942
|
+
if (sid) runBySession.delete(sid);
|
|
943
|
+
saveStore();
|
|
944
|
+
return {
|
|
945
|
+
status: 'done',
|
|
946
|
+
finalLead: {
|
|
947
|
+
label: leadNode.label,
|
|
948
|
+
role: leadNode.role || leadNode.label,
|
|
949
|
+
needs: depsOf(leadNode).map((id) => byId.get(id).label),
|
|
950
|
+
},
|
|
951
|
+
results: state.results,
|
|
952
|
+
labels: state.labels,
|
|
953
|
+
failed: Object.values(state.failed),
|
|
954
|
+
emptyOutputs: Object.values(state.emptyOutputs),
|
|
955
|
+
sessions: leadSessions,
|
|
956
|
+
skipped,
|
|
957
|
+
hint: '所有子代理已完成。最后一步由你(Lead 本体)按要求完成终审/汇总后直接向用户交付即可,无需再次调用 canvas_workflow。',
|
|
958
|
+
};
|
|
959
|
+
}
|
|
768
960
|
if (leadResult === undefined) {
|
|
961
|
+
state.waitingLead = {
|
|
962
|
+
id: leadNode.id,
|
|
963
|
+
label: leadNode.label,
|
|
964
|
+
role: leadNode.role || leadNode.label,
|
|
965
|
+
};
|
|
769
966
|
return {
|
|
770
967
|
status: 'need-lead',
|
|
771
968
|
node: {
|
|
@@ -777,17 +974,11 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
777
974
|
labels: state.labels,
|
|
778
975
|
failed: Object.values(state.failed),
|
|
779
976
|
emptyOutputs: Object.values(state.emptyOutputs),
|
|
780
|
-
sessions:
|
|
781
|
-
.filter((id) => (plan.edges || []).some((e) => e.to === leadNode.id && e.from === id && e.type === 'session-ref'))
|
|
782
|
-
.map((id) => ({
|
|
783
|
-
label: labelOf.get(id) || id,
|
|
784
|
-
childId: liveChild.get(String(sid || '') + '::' + id)
|
|
785
|
-
|| childByNode.get(String(sid || '') + '::' + id)
|
|
786
|
-
|| null,
|
|
787
|
-
})),
|
|
977
|
+
sessions: leadSessions,
|
|
788
978
|
hint: '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需从头重跑可传 reset: true。',
|
|
789
979
|
};
|
|
790
980
|
}
|
|
981
|
+
state.waitingLead = null;
|
|
791
982
|
state.results[leadNode.id] = leadResult;
|
|
792
983
|
state.labels[leadNode.id] = leadNode.label;
|
|
793
984
|
state.done.add(leadNode.id);
|
|
@@ -823,7 +1014,20 @@ function fallbackGuide() {
|
|
|
823
1014
|
}
|
|
824
1015
|
export function apply(ctx) {
|
|
825
1016
|
loadStore();
|
|
826
|
-
|
|
1017
|
+
ctx.inject(['systemPrompt'], (promptCtx) => {
|
|
1018
|
+
try {
|
|
1019
|
+
if (promptCtx.systemPrompt && typeof promptCtx.systemPrompt.context === 'function') {
|
|
1020
|
+
promptCtx.effect(() => promptCtx.systemPrompt.context({
|
|
1021
|
+
name: 'app:workflow-canvas-active',
|
|
1022
|
+
order: 950,
|
|
1023
|
+
text: (assembleCtx) => buildActiveCanvasContext(sessionIdFromContext(assembleCtx)),
|
|
1024
|
+
}), 'workflow-canvas: active context');
|
|
1025
|
+
}
|
|
1026
|
+
} catch (_e) {
|
|
1027
|
+
/* systemPrompt service unavailable */
|
|
1028
|
+
}
|
|
1029
|
+
});
|
|
1030
|
+
ctx.inject(['skills'], (scope) => {
|
|
827
1031
|
try {
|
|
828
1032
|
scope.effect(() => scope.skills.registerProvider(() => ({
|
|
829
1033
|
name: 'dsh-workflow-canvas',
|
|
@@ -1143,6 +1347,7 @@ export function apply(ctx) {
|
|
|
1143
1347
|
leadResult: { type: 'string', description: 'Your own output for the Lead step that was just requested.' },
|
|
1144
1348
|
task: { type: 'string', description: 'Optional overall task overriding the entry Lead task for this run (useful for reusing a preset).' },
|
|
1145
1349
|
reset: { type: 'boolean', description: 'Discard any paused run progress and start from the beginning.' },
|
|
1350
|
+
clearMemory: { type: 'boolean', description: 'Forget saved subagent sessions (keepSession memory) for this session before running so every node starts fresh.' },
|
|
1146
1351
|
},
|
|
1147
1352
|
additionalProperties: false,
|
|
1148
1353
|
},
|
|
@@ -1152,6 +1357,7 @@ export function apply(ctx) {
|
|
|
1152
1357
|
properties: {
|
|
1153
1358
|
status: { type: 'string' },
|
|
1154
1359
|
node: { type: 'object' },
|
|
1360
|
+
finalLead: { type: 'object' },
|
|
1155
1361
|
results: { type: 'object' },
|
|
1156
1362
|
labels: { type: 'object' },
|
|
1157
1363
|
failed: { type: 'array' },
|
|
@@ -1201,6 +1407,25 @@ export function apply(ctx) {
|
|
|
1201
1407
|
const skip = Array.isArray(v.skipped) && v.skipped.length
|
|
1202
1408
|
? '\n\n已跳过(未连线):' + v.skipped.join('、')
|
|
1203
1409
|
: '';
|
|
1410
|
+
if (v.finalLead) {
|
|
1411
|
+
const fl = v.finalLead;
|
|
1412
|
+
const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
|
|
1413
|
+
const handover = handed.length
|
|
1414
|
+
? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
|
|
1415
|
+
+ '\n如需局部追问或返工,可直接给对应子代理发消息。'
|
|
1416
|
+
: '';
|
|
1417
|
+
return [{
|
|
1418
|
+
type: 'text',
|
|
1419
|
+
text: '所有子代理已完成,现在进入终审 Lead 步骤「' + fl.label + '」:' + fl.role
|
|
1420
|
+
+ '\n需要用到:' + ((fl.needs && fl.needs.length) ? fl.needs.join('、') : '(无上游)')
|
|
1421
|
+
+ failedList
|
|
1422
|
+
+ emptyList
|
|
1423
|
+
+ '\n\n已完成节点的结果:\n' + body
|
|
1424
|
+
+ handover
|
|
1425
|
+
+ skip
|
|
1426
|
+
+ '\n\n' + (v.hint || ''),
|
|
1427
|
+
}];
|
|
1428
|
+
}
|
|
1204
1429
|
return [{ type: 'text', text: '画布执行完成。' + failedList + emptyList + '\n\n' + body + skip }];
|
|
1205
1430
|
}
|
|
1206
1431
|
return [{ type: 'text', text: JSON.stringify(v) }];
|
|
@@ -1227,6 +1452,9 @@ export {
|
|
|
1227
1452
|
normalizeCanvas,
|
|
1228
1453
|
applyPatch,
|
|
1229
1454
|
inspectPlan,
|
|
1455
|
+
sessionIdFromContext,
|
|
1456
|
+
buildActiveCanvasContext,
|
|
1457
|
+
isPermissionFailure,
|
|
1230
1458
|
runPlan,
|
|
1231
1459
|
executePlan,
|
|
1232
1460
|
};
|
package/package.json
CHANGED
|
@@ -49,11 +49,13 @@ Links only join matching types. Nodes the entry Lead cannot reach are skipped at
|
|
|
49
49
|
|
|
50
50
|
## Running
|
|
51
51
|
|
|
52
|
-
1. The canvas must be enabled (the pill over the canvas); `canvas_workflow` refuses while it is disabled.
|
|
53
|
-
2. You may pass `task` to override the entry Lead's task (handy when reusing a preset),
|
|
52
|
+
1. The canvas must be enabled (the pill over the canvas); `canvas_workflow` refuses while it is disabled. While enabled, the host automatically injects a per-session runtime context reminder on each turn.
|
|
53
|
+
2. You may pass `task` to override the entry Lead's task (handy when reusing a preset), `reset: true` to discard a paused run and start from scratch, and `clearMemory: true` to forget saved `keepSession` child sessions so every node starts fresh.
|
|
54
|
+
3. Solo chained Lead nodes (zero subagent upstream) and dangling dead-end subagents (zero outgoing edges while an active downstream Lead exists) are rendered dashed on the canvas and skipped at run time. Wiring a Lead + Subagent together into a downstream Lead is valid and active.
|
|
55
|
+
4. Subagent capability (`preset: standard | minimal`) narrows the toolset within the main chat's permission ceiling; it cannot elevate past the parent session's sandbox/approval mode.
|
|
54
56
|
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.
|
|
56
|
-
5.
|
|
57
|
+
4. Intermediate downstream Lead nodes pause the run (`status: "need-lead"`). Complete that Lead step yourself, then call `canvas_workflow` again with `leadResult` to resume downstream nodes — do not spawn an agent for it.
|
|
58
|
+
5. A **terminal** Lead node (zero remaining downstream nodes) finishes directly with `status: "done"` and `finalLead`: complete the review/summary and reply directly to the user — no extra `canvas_workflow` callback is needed.
|
|
57
59
|
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
60
|
7. Only assign image/visual inspection roles to models that declare image input support.
|
|
59
61
|
|