dsh-workflow-canvas 0.2.1 → 0.2.4

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/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 { ok: !failed(result), text: textOf(result), reason: result && result.stopReason };
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,59 @@ function reachableFrom(plan) {
312
324
  }
313
325
 
314
326
  /**
315
- * Turn a model-authored sketch into a canvas document: assign ids, add the entry
316
- * Lead, and lay the graph out in columns by depth so it is readable on arrival.
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 downstreamLeads = list.filter((n) => n.kind === 'lead' && reachable.has(n.id));
346
+ if (downstreamLeads.length) {
347
+ const hasOut = new Set(linkList.map((e) => e.from));
348
+ const parents = new Map();
349
+ for (const e of linkList) {
350
+ if (!parents.has(e.to)) parents.set(e.to, []);
351
+ parents.get(e.to).push(e.from);
352
+ }
353
+ const ancestorsOf = (id) => {
354
+ const seen = new Set();
355
+ const stack = [id];
356
+ while (stack.length) {
357
+ const cur = stack.pop();
358
+ for (const p of parents.get(cur) || []) {
359
+ if (!seen.has(p)) { seen.add(p); stack.push(p); }
360
+ }
361
+ }
362
+ return seen;
363
+ };
364
+ const deadEnds = list.filter((n) => {
365
+ if (n.kind === 'lead' || !reachable.has(n.id) || hasOut.has(n.id)) return false;
366
+ const anc = ancestorsOf(n.id);
367
+ return downstreamLeads.some((ln) => !anc.has(ln.id));
368
+ });
369
+ if (deadEnds.length) {
370
+ warnings.push('以下子代理节点没有出边,产出未显式连入下游或终审 Lead:'
371
+ + deadEnds.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
372
+ }
373
+ }
374
+ return warnings;
375
+ }
376
+
377
+ /**
378
+ * Turn a model-authored sketch into a canvas document: assign ids, ensure one
379
+ * connected entry Lead, and lay the graph out in columns by depth.
317
380
  */
318
381
  function normalizeCanvas(args) {
319
382
  const rawNodes = Array.isArray(args && args.nodes) ? args.nodes : [];
@@ -322,19 +385,28 @@ function normalizeCanvas(args) {
322
385
 
323
386
  const nodes = [];
324
387
  const idByRef = new Map();
388
+ const usedIds = new Set();
325
389
  let counter = 0;
390
+ let hasExplicitLead = false;
326
391
  for (const raw of rawNodes) {
327
392
  if (!raw || typeof raw !== 'object') continue;
328
393
  counter += 1;
329
394
  const kind = raw.kind === 'lead' ? 'lead' : 'agent';
330
- const wantsEntry = raw.entry === true && kind === 'lead';
331
- const id = wantsEntry
395
+ const wantsEntry = !hasExplicitLead && (raw.id === 'lead' || (raw.entry === true && kind === 'lead'));
396
+ let id = wantsEntry
332
397
  ? 'lead'
333
398
  : (typeof raw.id === 'string' && raw.id && raw.id !== 'lead' ? raw.id : 'n' + counter);
399
+ if (usedIds.has(id)) {
400
+ let suffix = 2;
401
+ while (usedIds.has(id + '_' + suffix)) suffix += 1;
402
+ id = id + '_' + suffix;
403
+ }
404
+ usedIds.add(id);
405
+ if (id === 'lead') hasExplicitLead = true;
334
406
  const label = String(raw.label || (kind === 'lead' ? 'Lead 步骤 ' + counter : 'Node ' + counter));
335
407
  nodes.push({
336
408
  id,
337
- kind,
409
+ kind: id === 'lead' ? 'lead' : kind,
338
410
  label,
339
411
  role: String(raw.role || ''),
340
412
  task: String(raw.task || ''),
@@ -349,33 +421,65 @@ function normalizeCanvas(args) {
349
421
  x: 0,
350
422
  y: 0,
351
423
  });
352
- if (raw.ref) idByRef.set(String(raw.ref), id);
424
+ if (raw.ref && !idByRef.has(String(raw.ref))) idByRef.set(String(raw.ref), id);
425
+ if (raw.id && !idByRef.has(String(raw.id))) idByRef.set(String(raw.id), id);
353
426
  idByRef.set(id, id);
354
427
  }
355
428
  if (!nodes.length) return { error: '节点都无效' };
356
429
 
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
430
  const ids = new Set(nodes.map((n) => n.id));
370
431
  const edges = [];
371
432
  for (const raw of rawEdges) {
372
433
  if (!raw || typeof raw !== 'object') continue;
373
434
  const from = idByRef.get(String(raw.from)) || String(raw.from);
374
435
  const to = idByRef.get(String(raw.to)) || String(raw.to);
375
- if (!ids.has(from) || !ids.has(to) || from === to) continue;
436
+ if ((from !== 'lead' && !ids.has(from)) || !ids.has(to) || from === to || to === 'lead') continue;
376
437
  const type = ['prompt', 'structured', 'session-ref'].includes(raw.type) ? raw.type : 'prompt';
377
438
  edges.push({ id: 'e' + edges.length, from, to, type });
378
439
  }
440
+
441
+ let entry = nodes.find((n) => n.id === 'lead');
442
+ if (!entry) {
443
+ // If the caller hand-authored a root Lead node (no incoming edges, has outgoing edges)
444
+ // and didn't wire from id='lead', promote it to entry Lead instead of duplicating it.
445
+ const hasLeadEdge = edges.some((e) => e.from === 'lead');
446
+ const inSet = new Set(edges.map((e) => e.to));
447
+ const outSet = new Set(edges.map((e) => e.from));
448
+ const rootLead = !hasLeadEdge
449
+ ? nodes.find((n) => n.kind === 'lead' && !inSet.has(n.id) && outSet.has(n.id))
450
+ : null;
451
+ if (rootLead) {
452
+ const oldId = rootLead.id;
453
+ rootLead.id = 'lead';
454
+ rootLead.task = rootLead.task || String(args.task || '') || rootLead.role;
455
+ rootLead.role = '';
456
+ for (const e of edges) {
457
+ if (e.from === oldId) e.from = 'lead';
458
+ }
459
+ entry = rootLead;
460
+ } else {
461
+ entry = {
462
+ id: 'lead', kind: 'lead', label: 'Lead(本对话)', role: '',
463
+ task: String(args.task || ''), provider: '', model: '', reasoning: '',
464
+ preset: '', structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
465
+ x: 0, y: 0,
466
+ };
467
+ nodes.unshift(entry);
468
+ }
469
+ } else if (!entry.task) {
470
+ entry.task = String(args.task || '') || entry.role;
471
+ }
472
+
473
+ // If entry Lead still has no outgoing edges, auto-wire it to all root nodes so
474
+ // a freshly generated canvas is never dead/unreachable on arrival.
475
+ if (!edges.some((e) => e.from === 'lead')) {
476
+ const hasIn = new Set(edges.map((e) => e.to));
477
+ const roots = nodes.filter((n) => n.id !== 'lead' && !hasIn.has(n.id));
478
+ for (const root of roots) {
479
+ edges.push({ id: 'e' + edges.length, from: 'lead', to: root.id, type: 'prompt' });
480
+ }
481
+ }
482
+
379
483
  const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
380
484
  for (const node of nodes) {
381
485
  if (structuredSources.has(node.id)) node.structured = true;
@@ -398,10 +502,15 @@ function normalizeCanvas(args) {
398
502
  const row = perColumn.get(level) || 0;
399
503
  perColumn.set(level, row + 1);
400
504
  node.x = 60 + level * 300;
401
- node.y = 80 + row * 230;
505
+ node.y = 80 + row * 260;
402
506
  }
403
507
 
404
- return { nodes, edges, task: String(args.task || '') };
508
+ return {
509
+ nodes,
510
+ edges,
511
+ task: String(entry.task || args.task || ''),
512
+ warnings: analyzeCanvasWarnings(nodes, edges),
513
+ };
405
514
  }
406
515
 
407
516
  /**
@@ -464,11 +573,14 @@ function applyPatch(plan, args) {
464
573
  }
465
574
  const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
466
575
  for (const node of keptNodes) {
467
- if (structuredSources.has(node.id)) node.structured = true;
576
+ node.structured = structuredSources.has(node.id);
468
577
  }
578
+ const taskPatched = typeof (args && args.task) === 'string';
579
+ const nextTask = taskPatched ? args.task : String(plan.task || '');
469
580
  return {
470
- plan: { ...plan, nodes: keptNodes, edges },
581
+ plan: { ...plan, task: nextTask, nodes: keptNodes, edges },
471
582
  touched,
583
+ taskPatched,
472
584
  removed: Array.from(removed),
473
585
  removeEdges: rawRemoveEdges
474
586
  .filter((r) => r && typeof r.from === 'string' && typeof r.to === 'string')
@@ -514,38 +626,91 @@ function inspectPlan(sid) {
514
626
  task: '',
515
627
  nodes: [],
516
628
  edges: [],
629
+ warnings: [],
517
630
  paused: false,
518
631
  };
519
632
  }
520
633
  const plan = payload.plan || {};
521
634
  const nodes = withoutEntry(plan.nodes).map((n) => ({
522
- id: n.id,
635
+ id: String(n.id || ''),
523
636
  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 || '',
637
+ label: String(n.label || n.id || ''),
638
+ role: String(n.role || ''),
639
+ provider: String(n.provider || ''),
640
+ model: String(n.model || ''),
641
+ reasoning: String(n.reasoning || ''),
529
642
  preset: n.preset === 'minimal' ? 'minimal' : 'standard',
530
643
  keepSession: Boolean(n.keepSession),
531
644
  structured: Boolean(n.structured),
532
- fallbackModel: n.fallbackModel || '',
533
- fallbackProvider: n.fallbackProvider || '',
645
+ fallbackModel: String(n.fallbackModel || ''),
646
+ fallbackProvider: String(n.fallbackProvider || ''),
534
647
  }));
535
648
  const edges = Array.isArray(plan.edges) ? plan.edges.map((e) => ({
536
- from: e.from,
537
- to: e.to,
538
- type: e.type || 'prompt',
649
+ from: String(e.from || ''),
650
+ to: String(e.to || ''),
651
+ type: String(e.type || 'prompt'),
539
652
  })) : [];
540
- return {
653
+ const out = {
541
654
  hasCanvas: true,
542
655
  enabled: Boolean(payload.enabled),
543
656
  task: String(plan.task || ''),
544
657
  nodes,
545
658
  edges,
546
- paused: Boolean(sid && runBySession.has(sid)),
547
- error: payload.error ? String(payload.error) : undefined,
659
+ warnings: analyzeCanvasWarnings(nodes, edges),
660
+ paused: Boolean(sid && runBySession.get(sid) && runBySession.get(sid).waitingLead),
548
661
  };
662
+ // Never attach `error: undefined`: DSH's lossless JSON validator rejects keys with undefined values.
663
+ if (payload.error) out.error = String(payload.error);
664
+ return out;
665
+ }
666
+
667
+ /** Extract the active session id from a DSH `AssembleContext`. */
668
+ function sessionIdFromContext(assembleCtx) {
669
+ if (!assembleCtx || typeof assembleCtx !== 'object') return '';
670
+ if (assembleCtx.agent && assembleCtx.agent.id !== undefined) return String(assembleCtx.agent.id);
671
+ if (assembleCtx.sessionId !== undefined) return String(assembleCtx.sessionId);
672
+ return '';
673
+ }
674
+
675
+ /**
676
+ * Per-turn runtime prompt context injected ONLY for the session whose canvas is
677
+ * currently enabled. Returns '' for disabled canvases, unrelated sessions, and
678
+ * subagent sessions (zero token overhead and no recursive triggering).
679
+ */
680
+ function buildActiveCanvasContext(sid) {
681
+ if (!sid) return '';
682
+ const payload = canvasBySession.get(String(sid));
683
+ if (!payload || !payload.enabled || payload.error) return '';
684
+ const plan = payload.plan;
685
+ const nodes = withoutEntry(plan && plan.nodes);
686
+ if (!nodes.length) return '';
687
+
688
+ const runState = runBySession.get(String(sid));
689
+ if (runState && runState.waitingLead) {
690
+ const wl = runState.waitingLead;
691
+ return [
692
+ '[Workflow Canvas Active — Paused at Lead Step]',
693
+ '当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')。',
694
+ '- 若用户的当前消息是在拍板、确认、补充决策或要求继续:请整理决策结论并直接调用 `canvas_workflow({ leadResult: "..." })` 恢复下游节点运行。',
695
+ '- 若用户要求放弃当前进度从头重跑:调用 `canvas_workflow({ reset: true })`。',
696
+ '- 若用户要求修改画布结构/分工:先 `canvas_inspect` 再用 `canvas_patch`。',
697
+ ].join('\n');
698
+ }
699
+
700
+ const preview = nodes
701
+ .slice(0, 8)
702
+ .map((n) => (n.kind === 'lead' ? '〔Lead〕' : '') + (n.label || n.id))
703
+ .join(' → ') + (nodes.length > 8 ? ' …' : '');
704
+ const hasTask = Boolean(String((plan && plan.task) || '').trim());
705
+ return [
706
+ '[Workflow Canvas Active]',
707
+ '当前会话的右侧工作流画布处于「● 已启用」状态(共 ' + nodes.length + ' 个执行节点:' + preview + ';入口总任务:' + (hasTask ? '已填写' : '未填写') + ')。',
708
+ '- 若用户发出任务请求、布置工作或说「开始 / 执行 / 跑一次」:请直接调用 `canvas_workflow` 按画布编排执行('
709
+ + (hasTask ? '可直接沿用入口总任务;若用户给出了新任务则通过 task 参数传入' : '请将用户的任务内容作为 task 参数传入')
710
+ + '),不要绕过画布直接自己完成。',
711
+ '- 若用户在讨论或要求修改画布结构、模型、分工或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
712
+ '- 仅当用户明确只是闲聊、问无关问题或要求先停用画布时,才无需调用 `canvas_workflow`。',
713
+ ].join('\n');
549
714
  }
550
715
 
551
716
  /** Takes a plan directly so tests can feed any plan shape (sync, generate, patch). */
@@ -590,9 +755,10 @@ async function executePlan(scope, plan, args, exec) {
590
755
  const sig = JSON.stringify(plan);
591
756
  let state = runBySession.get(sid);
592
757
  if (!state || state.sig !== sig) {
593
- state = { sig, done: new Set(), results: {}, labels: {}, failed: {} };
758
+ state = { sig, done: new Set(), results: {}, labels: {}, failed: {}, emptyOutputs: {}, waitingLead: null };
594
759
  runBySession.set(sid, state);
595
760
  }
761
+ if (!state.emptyOutputs) state.emptyOutputs = {};
596
762
 
597
763
  const byId = new Map(runnable.map((n) => [n.id, n]));
598
764
  const labelOf = new Map(order.map((n) => [n.id, n.label || n.id]));
@@ -603,8 +769,34 @@ async function executePlan(scope, plan, args, exec) {
603
769
 
604
770
  let leadResult = typeof opts.leadResult === 'string' ? opts.leadResult : undefined;
605
771
  const MAX_PARALLEL = 4;
772
+ // Event-driven concurrency pool: as soon as any node finishes, newly unblocked
773
+ // downstream agents start immediately instead of waiting for slower siblings.
774
+ const inFlight = new Map();
775
+
776
+ const isAborted = () => Boolean(exec && exec.signal && exec.signal.aborted);
777
+
778
+ const launchReadyAgents = () => {
779
+ if (isAborted() || inFlight.size >= MAX_PARALLEL) return;
780
+ const candidates = runnable.filter((n) => n.kind !== 'lead'
781
+ && !state.done.has(n.id)
782
+ && !inFlight.has(n.id)
783
+ && depsOf(n).every((id) => state.done.has(id)));
784
+ for (const node of candidates) {
785
+ if (isAborted() || inFlight.size >= MAX_PARALLEL) break;
786
+ const promise = spawnNode(scope, plan, node, state.results, agent, exec.signal, sid, state.failed)
787
+ .then(
788
+ (outcome) => ({ node, outcome }),
789
+ (err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
790
+ );
791
+ inFlight.set(node.id, promise);
792
+ }
793
+ };
606
794
 
607
795
  for (;;) {
796
+ if (isAborted()) {
797
+ if (sid) runBySession.delete(sid);
798
+ return { error: '工作流执行已取消。' };
799
+ }
608
800
  const remaining = runnable.filter((n) => !state.done.has(n.id));
609
801
  if (!remaining.length) {
610
802
  runBySession.delete(sid);
@@ -614,34 +806,72 @@ async function executePlan(scope, plan, args, exec) {
614
806
  results: state.results,
615
807
  labels: state.labels,
616
808
  failed: Object.values(state.failed),
809
+ emptyOutputs: Object.values(state.emptyOutputs),
617
810
  skipped,
618
811
  };
619
812
  }
620
813
 
621
- const ready = remaining.filter((n) => depsOf(n).every((id) => state.done.has(id)));
622
- if (!ready.length) return { error: '有节点的依赖无法满足(存在环或悬空依赖)。' };
814
+ launchReadyAgents();
623
815
 
624
- const agentReady = ready.filter((n) => n.kind !== 'lead');
625
- if (agentReady.length) {
626
- const batch = agentReady.slice(0, MAX_PARALLEL);
627
- const outcomes = await Promise.all(
628
- batch.map((node) => spawnNode(scope, plan, node, state.results, agent, exec.signal, sid, state.failed)),
629
- );
630
- batch.forEach((node, i) => {
631
- const outcome = outcomes[i];
632
- state.results[node.id] = outcome.text;
633
- state.labels[node.id] = node.label;
634
- if (!outcome.ok) {
635
- state.failed[node.id] = { id: node.id, label: node.label, reason: outcome.reason || 'unknown' };
636
- }
637
- state.done.add(node.id);
638
- });
816
+ if (inFlight.size > 0) {
817
+ const { node, outcome } = await Promise.race(inFlight.values());
818
+ inFlight.delete(node.id);
819
+ if (isAborted()) {
820
+ if (sid) runBySession.delete(sid);
821
+ return { error: '工作流执行已取消。' };
822
+ }
823
+ state.results[node.id] = outcome.text;
824
+ state.labels[node.id] = node.label;
825
+ if (!outcome.ok) {
826
+ state.failed[node.id] = { id: node.id, label: node.label, reason: outcome.reason || 'unknown' };
827
+ } else if (outcome.empty) {
828
+ state.emptyOutputs[node.id] = { id: node.id, label: node.label };
829
+ }
830
+ state.done.add(node.id);
639
831
  continue;
640
832
  }
641
833
 
834
+ const ready = remaining.filter((n) => depsOf(n).every((id) => state.done.has(id)));
835
+ if (!ready.length) return { error: '有节点的依赖无法满足(存在环或悬空依赖)。' };
836
+
642
837
  const leadNode = ready.find((n) => n.kind === 'lead');
643
838
  if (!leadNode) return { error: '没有可执行的节点。' };
839
+ const leadSessions = depsOf(leadNode)
840
+ .filter((id) => (plan.edges || []).some((e) => e.to === leadNode.id && e.from === id && e.type === 'session-ref'))
841
+ .map((id) => ({
842
+ label: labelOf.get(id) || id,
843
+ childId: liveChild.get(String(sid || '') + '::' + id)
844
+ || childByNode.get(String(sid || '') + '::' + id)
845
+ || null,
846
+ }));
847
+ const hasDownstreamWork = remaining.some((n) => n.id !== leadNode.id);
848
+ if (!hasDownstreamWork && leadResult === undefined) {
849
+ // Terminal Lead: zero downstream nodes remain, so complete the run directly
850
+ // and hand off final review/delivery to the Lead without a redundant extra turn.
851
+ if (sid) runBySession.delete(sid);
852
+ saveStore();
853
+ return {
854
+ status: 'done',
855
+ finalLead: {
856
+ label: leadNode.label,
857
+ role: leadNode.role || leadNode.label,
858
+ needs: depsOf(leadNode).map((id) => byId.get(id).label),
859
+ },
860
+ results: state.results,
861
+ labels: state.labels,
862
+ failed: Object.values(state.failed),
863
+ emptyOutputs: Object.values(state.emptyOutputs),
864
+ sessions: leadSessions,
865
+ skipped,
866
+ hint: '所有子代理已完成。最后一步由你(Lead 本体)按要求完成终审/汇总后直接向用户交付即可,无需再次调用 canvas_workflow。',
867
+ };
868
+ }
644
869
  if (leadResult === undefined) {
870
+ state.waitingLead = {
871
+ id: leadNode.id,
872
+ label: leadNode.label,
873
+ role: leadNode.role || leadNode.label,
874
+ };
645
875
  return {
646
876
  status: 'need-lead',
647
877
  node: {
@@ -652,17 +882,12 @@ async function executePlan(scope, plan, args, exec) {
652
882
  results: state.results,
653
883
  labels: state.labels,
654
884
  failed: Object.values(state.failed),
655
- sessions: depsOf(leadNode)
656
- .filter((id) => (plan.edges || []).some((e) => e.to === leadNode.id && e.from === id && e.type === 'session-ref'))
657
- .map((id) => ({
658
- label: labelOf.get(id) || id,
659
- childId: liveChild.get(String(sid || '') + '::' + id)
660
- || childByNode.get(String(sid || '') + '::' + id)
661
- || null,
662
- })),
885
+ emptyOutputs: Object.values(state.emptyOutputs),
886
+ sessions: leadSessions,
663
887
  hint: '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需从头重跑可传 reset: true。',
664
888
  };
665
889
  }
890
+ state.waitingLead = null;
666
891
  state.results[leadNode.id] = leadResult;
667
892
  state.labels[leadNode.id] = leadNode.label;
668
893
  state.done.add(leadNode.id);
@@ -698,7 +923,20 @@ function fallbackGuide() {
698
923
  }
699
924
  export function apply(ctx) {
700
925
  loadStore();
701
- ctx.inject(['skills'], (scope) => {
926
+ ctx.inject(['systemPrompt'], (promptCtx) => {
927
+ try {
928
+ if (promptCtx.systemPrompt && typeof promptCtx.systemPrompt.context === 'function') {
929
+ promptCtx.effect(() => promptCtx.systemPrompt.context({
930
+ name: 'app:workflow-canvas-active',
931
+ order: 950,
932
+ text: (assembleCtx) => buildActiveCanvasContext(sessionIdFromContext(assembleCtx)),
933
+ }), 'workflow-canvas: active context');
934
+ }
935
+ } catch (_e) {
936
+ /* systemPrompt service unavailable */
937
+ }
938
+ });
939
+ ctx.inject(['skills'], (scope) => {
702
940
  try {
703
941
  scope.effect(() => scope.skills.registerProvider(() => ({
704
942
  name: 'dsh-workflow-canvas',
@@ -756,19 +994,20 @@ export function apply(ctx) {
756
994
  try {
757
995
  scope.effect(() => scope.tools.register({
758
996
  name: 'canvas_generate',
759
- description: 'Build a workflow canvas for this session from a node/edge sketch. It is written to the workspace and the open canvas picks it up. Load the `workflow-canvas` skill first for node fields and link semantics.',
997
+ 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
998
  parameters: {
761
999
  type: 'object',
762
1000
  properties: {
763
- task: { type: 'string', description: 'Overall task written into the entry Lead node.' },
1001
+ task: { type: 'string', description: 'Overall task written into the auto-created entry Lead node (id="lead").' },
764
1002
  nodes: {
765
1003
  type: 'array',
766
- description: 'Nodes in any order. Give each an id or ref so edges can point at it.',
1004
+ 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
1005
  items: {
768
1006
  type: 'object',
769
1007
  properties: {
770
1008
  id: { type: 'string' },
771
1009
  ref: { type: 'string', description: 'Temporary handle for edges; the tool assigns the real id.' },
1010
+ entry: { type: 'boolean', description: 'Optional: set true only if customizing the entry Lead node itself.' },
772
1011
  kind: { type: 'string', enum: ['agent', 'lead'] },
773
1012
  label: { type: 'string' },
774
1013
  role: { type: 'string' },
@@ -805,6 +1044,7 @@ export function apply(ctx) {
805
1044
  properties: {
806
1045
  canvas: { type: 'object' },
807
1046
  delivered: { type: 'boolean' },
1047
+ warnings: { type: 'array', items: { type: 'string' } },
808
1048
  error: { type: 'string' },
809
1049
  },
810
1050
  },
@@ -814,12 +1054,16 @@ export function apply(ctx) {
814
1054
  const canvas = v.canvas || {};
815
1055
  const nodes = Array.isArray(canvas.nodes) ? canvas.nodes : [];
816
1056
  const edges = Array.isArray(canvas.edges) ? canvas.edges : [];
817
- const lines = nodes.map((n) => '- ' + (n.kind === 'lead' ? '〔Lead〕' : '') + n.label
1057
+ const lines = nodes.map((n) => '- [' + n.id + '] ' + (n.kind === 'lead' ? '〔Lead〕' : '') + n.label
818
1058
  + (n.role ? ':' + n.role : ''));
1059
+ const warnBlock = Array.isArray(v.warnings) && v.warnings.length
1060
+ ? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
1061
+ : '';
819
1062
  return [{
820
1063
  type: 'text',
821
1064
  text: '已生成画布:' + nodes.length + ' 个节点、' + edges.length + ' 条连线\n'
822
1065
  + lines.join('\n')
1066
+ + warnBlock
823
1067
  + (v.delivered
824
1068
  ? '\n\n画布已经自动同步到右侧画布,直接看即可(若没出现,点画布上的「⊡ 全览」)。'
825
1069
  : '\n\n**下一步**:点画布右上角「⋯ → ⇩ 导入」,它会把这段画布数据装进当前画布。')
@@ -832,16 +1076,18 @@ export function apply(ctx) {
832
1076
  try {
833
1077
  const result = normalizeCanvas(args || {});
834
1078
  if (result.error) return { error: result.error };
835
- const canvas = { nodes: result.nodes, edges: result.edges };
1079
+ const warnings = Array.isArray(result.warnings) ? result.warnings : [];
836
1080
  const agent = exec && exec.agent;
837
1081
  const sid = agent && agent.id !== undefined ? String(agent.id) : '';
1082
+ const previous = sid ? canvasBySession.get(sid) : undefined;
1083
+ const nextEnabled = previous ? Boolean(previous.enabled) : true;
1084
+ const canvas = { nodes: result.nodes, edges: result.edges, enabled: nextEnabled };
838
1085
  const delivered = sid ? publishCanvas(scope, sid, canvas) : false;
839
1086
  if (sid) {
840
- const previous = canvasBySession.get(sid);
841
1087
  canvasBySession.set(sid, {
842
- enabled: previous ? previous.enabled : true,
1088
+ enabled: nextEnabled,
843
1089
  plan: {
844
- task: String((args && args.task) || ''),
1090
+ task: String(result.task || (args && args.task) || ''),
845
1091
  nodes: withoutEntry(canvas.nodes),
846
1092
  edges: canvas.edges,
847
1093
  },
@@ -849,7 +1095,7 @@ export function apply(ctx) {
849
1095
  runBySession.delete(sid);
850
1096
  saveStore();
851
1097
  }
852
- return { canvas, delivered };
1098
+ return { canvas, delivered, warnings };
853
1099
  } catch (error) {
854
1100
  return { error: String((error && error.message) || error) };
855
1101
  }
@@ -868,6 +1114,7 @@ export function apply(ctx) {
868
1114
  parameters: {
869
1115
  type: 'object',
870
1116
  properties: {
1117
+ task: { type: 'string', description: 'Optional: update the overall task in the entry Lead node.' },
871
1118
  nodes: { type: 'array', description: 'Nodes to update or add. Existing ids are merged field by field.', items: { type: 'object' } },
872
1119
  removeNodes: { type: 'array', description: 'Node ids to delete.', items: { type: 'string' } },
873
1120
  edges: { type: 'array', description: 'Links to add.', items: { type: 'object' } },
@@ -880,13 +1127,17 @@ export function apply(ctx) {
880
1127
  properties: {
881
1128
  delivered: { type: 'boolean' },
882
1129
  summary: { type: 'string' },
1130
+ warnings: { type: 'array', items: { type: 'string' } },
883
1131
  error: { type: 'string' },
884
1132
  },
885
1133
  },
886
1134
  render: (_a, value) => {
887
1135
  const v = value || {};
888
1136
  if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
889
- return [{ type: 'text', text: v.summary + (v.delivered ? '(画布已就地更新)' : '(画布不可达,未应用)') }];
1137
+ const warnBlock = Array.isArray(v.warnings) && v.warnings.length
1138
+ ? '\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
1139
+ : '';
1140
+ return [{ type: 'text', text: v.summary + (v.delivered ? '(画布已就地更新)' : '(画布不可达,未应用)') + warnBlock }];
890
1141
  },
891
1142
  },
892
1143
  execute: (args, exec) => {
@@ -900,15 +1151,20 @@ export function apply(ctx) {
900
1151
  canvasBySession.set(sid, { enabled: payload.enabled, plan: nextPlan });
901
1152
  runBySession.delete(sid);
902
1153
  saveStore();
903
- const delivered = publishCanvas(scope, sid, {
1154
+ const patchDoc = {
904
1155
  mode: 'merge',
905
1156
  nodes: nextPlan.nodes,
906
1157
  edges: nextPlan.edges,
907
1158
  removeNodes: patched.removed,
908
1159
  removeEdges: patched.removeEdges,
909
- });
910
- const summary = '已更新 ' + patched.touched.length + ' 个节点、删除 ' + patched.removed.length + ' 个、连线 ' + nextPlan.edges.length + ' 条';
911
- return { delivered, summary };
1160
+ };
1161
+ if (patched.taskPatched) patchDoc.task = nextPlan.task;
1162
+ const delivered = publishCanvas(scope, sid, patchDoc);
1163
+ const warnings = analyzeCanvasWarnings(nextPlan.nodes, nextPlan.edges);
1164
+ const summary = '已更新 ' + patched.touched.length + ' 个节点'
1165
+ + (patched.taskPatched ? '、已更新总任务' : '')
1166
+ + '、删除 ' + patched.removed.length + ' 个、连线 ' + nextPlan.edges.length + ' 条';
1167
+ return { delivered, summary, warnings };
912
1168
  } catch (error) {
913
1169
  return { error: String((error && error.message) || error) };
914
1170
  }
@@ -938,6 +1194,7 @@ export function apply(ctx) {
938
1194
  task: { type: 'string' },
939
1195
  nodes: { type: 'array' },
940
1196
  edges: { type: 'array' },
1197
+ warnings: { type: 'array', items: { type: 'string' } },
941
1198
  paused: { type: 'boolean' },
942
1199
  error: { type: 'string' },
943
1200
  },
@@ -952,6 +1209,9 @@ export function apply(ctx) {
952
1209
  '总任务:' + (v.task || '(未填写,运行时可通过 task 参数指定)'),
953
1210
  ];
954
1211
  if (v.error) head.push('校验错误:' + v.error);
1212
+ const warnBlock = Array.isArray(v.warnings) && v.warnings.length
1213
+ ? '\n\n⚠ 结构提示:\n' + v.warnings.map((w) => '- ' + w).join('\n')
1214
+ : '';
955
1215
  const nodeLines = (v.nodes || []).map((n) => {
956
1216
  const flags = [];
957
1217
  if (n.kind === 'lead') flags.push('Lead');
@@ -968,6 +1228,7 @@ export function apply(ctx) {
968
1228
  return [{
969
1229
  type: 'text',
970
1230
  text: head.join('\n')
1231
+ + warnBlock
971
1232
  + '\n\n节点(' + nodeLines.length + '):\n' + (nodeLines.join('\n') || '(无)')
972
1233
  + '\n\n连线(' + edgeLines.length + '):\n' + (edgeLines.join('\n') || '(无)'),
973
1234
  }];
@@ -1004,9 +1265,11 @@ export function apply(ctx) {
1004
1265
  properties: {
1005
1266
  status: { type: 'string' },
1006
1267
  node: { type: 'object' },
1268
+ finalLead: { type: 'object' },
1007
1269
  results: { type: 'object' },
1008
1270
  labels: { type: 'object' },
1009
1271
  failed: { type: 'array' },
1272
+ emptyOutputs: { type: 'array' },
1010
1273
  sessions: { type: 'array' },
1011
1274
  skipped: { type: 'array' },
1012
1275
  hint: { type: 'string' },
@@ -1026,6 +1289,10 @@ export function apply(ctx) {
1026
1289
  const failedList = Array.isArray(v.failed) && v.failed.length
1027
1290
  ? '\n\n⚠ 失败节点:' + v.failed.map((f) => (f.label || f.id) + '(' + (f.reason || 'unknown') + ')').join('、')
1028
1291
  : '';
1292
+ const emptyList = Array.isArray(v.emptyOutputs) && v.emptyOutputs.length
1293
+ ? '\n\n⚠ 未返回交付文本的节点(请核查其实际产物,切勿直接当作已完成):'
1294
+ + v.emptyOutputs.map((e) => e.label || e.id).join('、')
1295
+ : '';
1029
1296
  if (v.status === 'need-lead') {
1030
1297
  const n = v.node || {};
1031
1298
  const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
@@ -1038,6 +1305,7 @@ export function apply(ctx) {
1038
1305
  text: '需要你(Lead)完成「' + n.label + '」:' + n.role
1039
1306
  + '\n需要用到:' + ((n.needs && n.needs.length) ? n.needs.join('、') : '(无上游)')
1040
1307
  + failedList
1308
+ + emptyList
1041
1309
  + '\n\n已完成节点的结果:\n' + body
1042
1310
  + handover
1043
1311
  + '\n\n' + (v.hint || ''),
@@ -1047,7 +1315,26 @@ export function apply(ctx) {
1047
1315
  const skip = Array.isArray(v.skipped) && v.skipped.length
1048
1316
  ? '\n\n已跳过(未连线):' + v.skipped.join('、')
1049
1317
  : '';
1050
- return [{ type: 'text', text: '画布执行完成。' + failedList + '\n\n' + body + skip }];
1318
+ if (v.finalLead) {
1319
+ const fl = v.finalLead;
1320
+ const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
1321
+ const handover = handed.length
1322
+ ? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
1323
+ + '\n如需局部追问或返工,可直接给对应子代理发消息。'
1324
+ : '';
1325
+ return [{
1326
+ type: 'text',
1327
+ text: '所有子代理已完成,现在进入终审 Lead 步骤「' + fl.label + '」:' + fl.role
1328
+ + '\n需要用到:' + ((fl.needs && fl.needs.length) ? fl.needs.join('、') : '(无上游)')
1329
+ + failedList
1330
+ + emptyList
1331
+ + '\n\n已完成节点的结果:\n' + body
1332
+ + handover
1333
+ + skip
1334
+ + '\n\n' + (v.hint || ''),
1335
+ }];
1336
+ }
1337
+ return [{ type: 'text', text: '画布执行完成。' + failedList + emptyList + '\n\n' + body + skip }];
1051
1338
  }
1052
1339
  return [{ type: 'text', text: JSON.stringify(v) }];
1053
1340
  },
@@ -1069,9 +1356,12 @@ export {
1069
1356
  downstreamLabels,
1070
1357
  briefFor,
1071
1358
  withoutEntry,
1359
+ analyzeCanvasWarnings,
1072
1360
  normalizeCanvas,
1073
1361
  applyPatch,
1074
1362
  inspectPlan,
1363
+ sessionIdFromContext,
1364
+ buildActiveCanvasContext,
1075
1365
  runPlan,
1076
1366
  executePlan,
1077
1367
  };