dsh-workflow-canvas 1.4.1 → 1.5.5

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/docs/DETAIL.md CHANGED
@@ -10,34 +10,52 @@ are performed by the conversation itself.
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
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.
13
+ the node's child session (Latest or pinned past run); optional **Fallback**
14
+ retries once on another model.
14
15
  - **Lead node** (blue top bar): performed by the conversation, never spawned. The
15
16
  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.
17
+ decision; `Lead → Lead` stage chains are supported with zero subagent spawns
18
+ when `role` is filled; a terminal Lead finishes in one shot without an extra
19
+ callback.
17
20
  - **Condition node** (amber top bar): lightweight read-only (`minimal`) branch
18
21
  judge supporting inline-editable binary `if/else` (`Yes` / `No`), multi-way
19
22
  `switch/case` (`+ Case`), and `Single` / `Multi` match modes (including clean
20
23
  zero-match full skip when no branch applies). Unchosen paths are pruned
21
24
  automatically without spawning, and branches can converge back into a shared
22
25
  downstream node or terminal Lead.
23
- - **Typed outputs, universal input**: right-side output sockets pick the channel
26
+ - **Controlled retry loops (`↺`)**: wire a condition branch back to a strict
27
+ ancestor (or select connected nodes and right-click **`↺ Create loop`**,
28
+ auto-inserting a condition gate if the tail is a subagent). Loop members get a
29
+ color-coded outer dashed outline and outer bypass rail with a clickable `↺ ×N`
30
+ pill (`1–10` retries), resetting only loop members on retry, injecting failure
31
+ feedback with healthy warm-session reuse, and circuit-breaking to the nearest
32
+ Lead when exhausted.
33
+ - **Global & per-node `+ Refs`**: every node's top-right title bar supports up to
34
+ 16 reference paths, URLs, or rules automatically deduplicated and injected at
35
+ run time.
36
+ - **Typed outputs, universal input**: output sockets pick the channel
24
37
  (`prompt` / `structured` / `session` / condition branch); every non-entry node
25
- exposes a single universal left input (`in`) that accepts any wire and inherits
26
- the source colour. Cycles are blocked immediately; drag a connected input away
27
- to detach its latest wire.
28
- - Inactive nodes (unreachable from entry, solo chained Leads with no subagent
29
- upstream, or dangling dead-end subagents) are drawn dashed and skipped at run time.
30
- - Wheel zooms around the cursor; middle-drag (or `Space` + drag) pans; `⊡ Fit`
31
- fits all nodes into the visible viewport; the percentage button resets to 100%
32
- on the Lead.
33
- - Marquee selection: drag on empty canvas to select multiple nodes; dragging any
34
- selected node moves the whole selection.
35
- - Right-drag across links cuts them on release; the swept path and links about to
36
- be cut highlight in red (toggle under `⋯`).
37
- - Shortcuts: `Shift+A` opens the Add Node menu at the cursor,
38
- `Ctrl+D` duplicates selected nodes, `Delete` removes selected nodes, `Ctrl+Z`
39
- undoes, and `Esc` closes popups. `⋯` also provides `⊞ Auto layout`,
40
- `⇧ Copy JSON`, and `Visual effects` (`Minimal` / `Standard` / `Vivid`).
38
+ exposes a single universal input (`in`) that accepts any wire and inherits the
39
+ source colour. Arbitrary cycles are blocked immediately; drag a connected input
40
+ away to detach its latest forward wire.
41
+ - Inactive nodes (unreachable from entry, blank-role solo chained Leads with no
42
+ subagent upstream, or dangling dead-end subagents) are drawn dashed and skipped
43
+ at run time.
44
+ - **Horizontal / vertical layout & slim narrow-sidebar UI**: toggle `⇄ Horiz` /
45
+ `⇅ Vert` (remembered globally for new sessions, saved with custom presets and
46
+ exported JSON, and undoable; top-in / bottom-out curves + condition `Out R / Out L`);
47
+ toolbar provides compact `↶` / `↷` Undo/Redo buttons; right-click any node,
48
+ edge, or blank canvas for context actions (insert on wire, create loop,
49
+ duplicate/delete, layout, undo/redo) without conflicting with right-drag wire
50
+ cutting (`>= 6px`). Bottom-right floating `⊡ | 100%` pill handles fit and
51
+ scrub zoom, and simultaneous pan + wheel zoom stays anchored without drift.
52
+ - **Multi-select & customizable shortcuts**: marquee drag or `Shift`/`Ctrl`+click
53
+ to multi-select; `Shift+A` adds at cursor, `Shift+D` duplicates selected nodes
54
+ together with internal wires, `Delete` removes selected, `Ctrl+Z` /
55
+ `Ctrl+Shift+Z` (`Ctrl+Y`) undo/redo (including node drags and layout flips),
56
+ and `Esc` closes popups. Customize bindings under `⋯ → ⌨ Shortcuts`.
57
+ - **Live preset sync**: custom presets sync automatically across already-open
58
+ sessions (with a manual `↻` refresh button and `H`/`V` direction tags).
41
59
  - Click any subagent node's status pill (e.g. `Done ↗`) to jump straight to its
42
60
  live subagent chat pane.
43
61
 
@@ -58,13 +76,17 @@ node positions survive.
58
76
  Subagent nodes run in an event-driven concurrency pool (default 4, configurable
59
77
  1–8 via `⋯` or `maxParallel`) via `canvas_workflow`, which supports `task`
60
78
  (override the entry task for template reuse), `reset: true` (discard a paused
61
- run), `retryFailed: true` / `fromNodes` (reuse succeeded nodes and re-run only
79
+ run), `cancel: true` (cleanly stop an active or paused `need-lead` run),
80
+ `retryFailed: true` / `fromNodes` (reuse succeeded nodes and re-run only
62
81
  failed/target segments plus downstream), and `clearMemory: true` (forget saved
63
82
  `keepSession` memories). While enabled, a per-session runtime context notifies
64
- the agent automatically. Intermediate Lead nodes pause with `status: "need-lead"`
65
- and report `decisions` / `branchSkipped` / `failed` / `emptyOutputs` plus
66
- `session` handovers; a terminal Lead completes directly with `status: "done"`
67
- and `finalLead`.
83
+ the agent automatically. While running or paused at an intermediate Lead node,
84
+ a unified red **`⏹ Stop`** button appears beside `● ON` and on the Entry Lead
85
+ card to interrupt all running subagents, cancel the root turn, and clear any
86
+ Lead pause via `/canvas-stop`. Intermediate Lead nodes pause with
87
+ `status: "need-lead"` and report `decisions` / `branchSkipped` / `failed` /
88
+ `emptyOutputs` plus `session` handovers and merged `refs`; a terminal Lead
89
+ completes directly with `status: "done"` and `finalLead`.
68
90
 
69
91
  ## Memory
70
92
 
@@ -76,8 +98,9 @@ if the Host refuses, the record is dropped and the node starts fresh.
76
98
 
77
99
  - Saved presets live in browser storage and do not auto-sync between the Desktop
78
100
  app and `dsh web`, nor across machines (use `⋯ → ⇧ Copy JSON` and `⇩ Import`
79
- to share or migrate them; starter templates are built in under `☰ Presets`).
80
- - Lead steps have no tracked state; they show **Runs in chat** (or **Ready** once all upstream subagents finish).
81
- - Up to 4 nodes run at a time.
101
+ to share or migrate them; 5 starter templates including conditional branching &
102
+ retry loop are built in under `☰ Presets`).
103
+ - Lead steps have no child session; they show **Runs in chat** (or **Ready** once upstream finishes).
104
+ - Concurrency defaults to 4 (configurable 1–8 under `⋯`); controlled loops allow up to 1–10 retries per loop (20 global safety cap).
82
105
 
83
106
  For architecture diagrams and runtime internals, see [MECHANISM.md](MECHANISM.md) ([中文](MECHANISM.zh.md)).
package/docs/MECHANISM.md CHANGED
@@ -12,20 +12,20 @@ at run time, and how memory cold-resume, fallbacks, and live status tracking wor
12
12
  ## 1. Architecture: Bidirectional Client ↔ Host Bridge
13
13
 
14
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.
15
+ - **Client (`client.js`)**: Mounted as a right-sidebar `Workflow` tab (`keepMounted: true`, keyed by `sessionId` for isolation, preserving state while collapsed). Owns visual editing, live cross-tab preset sync, global layout preferences, shortcuts, visual effects, and live status rendering.
16
+ - **Host (`index.js`)**: Registers the bundled `workflow-canvas` skill, per-session `systemPrompt.context`, two commands (`/canvas-sync` and `/canvas-stop`), and four tools (`canvas_inspect`, `canvas_generate`, `canvas_patch`, `canvas_workflow`). Owns real subagent execution, unified cancellation, and durable state persistence.
17
17
 
18
18
  ```mermaid
19
19
  flowchart LR
20
20
  subgraph Client["Sidebar Canvas (client.js)"]
21
- UI["Graph Editor / Presets / Status Pills"]
21
+ UI["Graph Editor / Presets / Pills / Stop"]
22
22
  LS["localStorage\n(drafts / presets / prefs)"]
23
23
  Poll["workspaceFiles Poll\n(every 1.5s)"]
24
24
  Cat["subagentCatalog Observer\n(every 700ms while running)"]
25
25
  end
26
26
 
27
27
  subgraph Host["Host Plugin (index.js)"]
28
- Sync["/canvas-sync command"]
28
+ Sync["/canvas-sync & /canvas-stop"]
29
29
  Store["Atomic Disk Store\n.workflow-canvas-state.json"]
30
30
  Tools["canvas_inspect / generate / patch"]
31
31
  Exec["canvas_workflow\nDAG Wave Executor"]
@@ -33,12 +33,12 @@ flowchart LR
33
33
  end
34
34
 
35
35
  UI <--> LS
36
- UI -- "enable / sync / turn edge\n/canvas-sync" --> Sync
36
+ UI -- "enable / sync / stop\n/canvas-sync & /canvas-stop" --> Sync
37
37
  Sync --> Store
38
38
  Tools -- "writes .dsh/canvas/<sid>.json" --> Poll
39
39
  Poll -- "timestamp guard + merge layout" --> UI
40
40
  Exec <--> Store
41
- Exec -- "startActivation\nlabel#nodeId" --> Sub
41
+ Exec -- "startActivation / interrupt" --> Sub
42
42
  Sub -- "live status & childId" --> Cat
43
43
  Cat --> UI
44
44
  ```
@@ -60,15 +60,16 @@ flowchart LR
60
60
  When `canvas_workflow` runs, `executePlan` executes the following pipeline:
61
61
 
62
62
  1. **Entry stripping & task override**: The entry `lead` node is stripped (`withoutEntry`) and never spawned. If `args.task` is provided, it overrides `plan.task` for this run (allowing blank-task templates to be reused straight from chat).
63
- 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, conditional pruning & partial resume**:
63
+ 2. **DAG & controlled-loop validation**: `orderNodes` validates forward edges (`!e.loop`) via Kahn topological sort; `validateLoopEdges` separately verifies controlled retry edges (`e.loop === true`) leave a condition node, target a strict forward ancestor (never entry Lead), and do not overlap/cross.
64
+ 3. **Reachability & inactive pruning**: BFS from `'lead'` over forward edges filters out disconnected nodes, blank-role solo chained Leads without subagent upstream, and dangling dead-end subagents; all render dashed and are listed in `skipped` without burning tokens.
65
+ 4. **Event-driven concurrency pool, conditional pruning, retry loops & partial resume**:
66
66
  - In-progress state lives in `runBySession`, and each completed or halted run is snapshotted into `lastRunBySession`.
67
67
  - Instead of a strict per-wave barrier, the executor runs an **event-driven concurrency pool (`inFlight` + `Promise.race`, default 4, configurable 1–8)**:
68
68
  - The instant any running subagent finishes, newly unblocked downstream subagents launch immediately — fast branches never stall waiting for slower siblings.
69
69
  - **Condition nodes (`kind: "condition"`)** run as lightweight read-only (`minimal`) judges with a strict structured `outputSchema` (supporting binary `if/else`, multi-way `switch/case`, and `multiMatch` parallel fan-out). Unmatched outgoing edges are blocked and unchosen branches are pruned via ancestor-aware BFS (so an upstream `session-ref` side wire cannot bypass a vetoed branch). If zero branches match or the condition node itself fails, it never guesses a branch — it skips intermediate branches and hands off to the nearest downstream Lead (or halts cleanly if none exists).
70
- - Intermediate **non-entry Lead nodes** pause with `status: "need-lead"`; a **terminal Lead** (zero remaining downstream work) finishes in one shot with `status: "done"` and `finalLead`.
71
- - **`retryFailed: true`** and **`fromNodes: [...]`** reuse succeeded outputs from `lastRunBySession` and re-run only failed/target nodes plus their downstream; `reset: true` discards progress and starts from scratch.
70
+ - **Controlled retry loops (`loop: true, maxIterations: 1–10`)**: when a condition matches a loop back-edge (taking priority over forward branches under `multiMatch`), if within per-loop and global safety limits (`20`), the executor resets strictly `descendants(target) ∩ ancestors(source)` (bypass nodes outside the loop never re-run), injects the rejection reason into the entry node (supporting both subagents and Lead nodes), and reuses its healthy warm session with an incremental correction prompt (or starts fresh if the prior round crashed/returned empty). At the limit, it circuit-breaks and hands off `1..N` round summaries to the nearest downstream Lead.
71
+ - Intermediate **non-entry Lead nodes** (including `Lead → Lead` stage chains) pause with `status: "need-lead"`; a **terminal Lead** (zero remaining downstream work) finishes in one shot with `status: "done"` and `finalLead`.
72
+ - **`retryFailed: true`** and **`fromNodes: [...]`** reuse succeeded outputs from `lastRunBySession` and re-run only failed/target nodes plus their downstream; `reset: true` discards progress and starts from scratch; **`cancel: true`** or clicking **`⏹ Stop`** via concurrent `/canvas-stop` (as well as DSH's native chat Stop button) immediately calls `subagents.interrupt(cid, { kind: 'user' })`, `drainDescendants([rootAgent])`, and `rootAgent.cancel({ kind: 'user' }, { keepInbox: true })`, races `abortPromise` out of the pool without spawning fallback retries, preserves completed-node cache, and clears `waitingLead` / `.run.json`.
72
73
 
73
74
  ```mermaid
74
75
  sequenceDiagram
@@ -121,15 +122,16 @@ The three link types are distinct runtime channels, not just visual colour codin
121
122
  ## 5. Live Status Pills & Click-to-Open Subagent Chats
122
123
 
123
124
  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.
125
+ 2. **Catalog & run-state telemetry 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` takes strict priority over historical rounds) and latest `childId`, while also polling `<workspace>/.dsh/canvas/<sid>.run.json` for condition `decisions`, `pruned` nodes, `blockedEdges`, live retry counts (`loopCounts` / `nodeAttempts`), and `waitingLead`.
126
+ 3. **Authoritative Lead `⏸ Ready` state & unified Stop**: Authoritative `.run.json` status takes precedence (`need-lead` highlights **`⏸ Ready`**; `halted` / `done` / `idle` never re-lock from historical subagent statuses), falling back to forward-edge heuristics only when `.run.json` is absent. Both running and awaiting-Lead states expose the unified **`⏹ Stop`** button.
126
127
  4. **Jump to live chat**: Clicking any subagent's bottom-left 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
 
128
129
  ---
129
130
 
130
- ## 6. Skill & Tool Discovery
131
+ ## 6. Per-Session Context, Skill & Tool Discovery
131
132
 
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.
133
+ To keep the agent aligned with an enabled canvas without leaking instructions into disabled chats or subagents, the plugin combines four layers:
134
+ 1. **Per-session `systemPrompt.context` injection**: Strictly scoped by `sessionId` (never injected into subagents), injecting a live canvas summary on each turn (node overview, controlled retry loop count, global refs count, memory/permission/partial-resume hints; or when paused at a Lead step, the pending Lead role, `leadResult` / `cancel: true` / `reset: true`, and any loop rejection feedback).
135
+ 2. **Bundled skill provider**: `index.js` registers `workflow-canvas` via `ctx.skills.registerProvider` with bilingual trigger keywords (`canvas / workflow / condition / retry loop / 画布 / 工作流 / 编排`) and all four `canvas_*` tool names, serving [skills/workflow-canvas/SKILL.md](../skills/workflow-canvas/SKILL.md).
136
+ 3. **Tool-level pointers**: Every `canvas_*` tool description reminds the model to load the `workflow-canvas` skill first, and tool schemas are always in context.
137
+ 4. **Optional `AGENTS.md` rule**: Adding a single line in a project's `AGENTS.md` guarantees deterministic skill loading in every session.
@@ -9,20 +9,20 @@
9
9
  ## 1. 整体架构:Client 与 Host 的双向通道
10
10
 
11
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`),负责真实调度子代理和持久化执行状态。
12
+ - **客户端(`client.js`)**:挂载在 DSH 右侧边栏的 `Workflow` 标签页(`keepMounted: true` 且按 `sessionId` 设 `key` 隔离,收起侧边栏时保留画布状态),负责图形编辑、跨会话实时预设同步、全局布局偏好与实时状态渲染。
13
+ - **Host 侧(`index.js`)**:注册技能 `workflow-canvas`、会话级强上下文注入 `systemPrompt.context`、两条命令(`/canvas-sync` 与 `/canvas-stop`),以及 4 个工具(`canvas_inspect`、`canvas_generate`、`canvas_patch`、`canvas_workflow`),负责真实调度子代理、统一中止与持久化执行状态。
14
14
 
15
15
  ```mermaid
16
16
  flowchart LR
17
17
  subgraph Client["客户端画布 (client.js)"]
18
- UI["画布编辑 / 预设 / 状态胶囊"]
18
+ UI["画布编辑 / 预设 / 状态胶囊 / 终止"]
19
19
  LS["localStorage\n(画布草稿 / 预设 / 偏好)"]
20
20
  Poll["workspaceFiles 轮询\n(每 1.5s)"]
21
21
  Cat["subagentCatalog 投影监听\n(运行中每 700ms)"]
22
22
  end
23
23
 
24
24
  subgraph Host["Host 插件 (index.js)"]
25
- Sync["/canvas-sync 命令"]
25
+ Sync["/canvas-sync & /canvas-stop"]
26
26
  Store["原子持久化\n.workflow-canvas-state.json"]
27
27
  Tools["canvas_inspect / generate / patch"]
28
28
  Exec["canvas_workflow\nDAG 波次执行器"]
@@ -30,12 +30,12 @@ flowchart LR
30
30
  end
31
31
 
32
32
  UI <--> LS
33
- UI -- "启用 / 同步 / 轮次边界\n/canvas-sync" --> Sync
33
+ UI -- "启用 / 同步 / 终止\n/canvas-sync & /canvas-stop" --> Sync
34
34
  Sync --> Store
35
35
  Tools -- "写入 .dsh/canvas/<sid>.json" --> Poll
36
36
  Poll -- "时间戳比对 + merge 保留排版" --> UI
37
37
  Exec <--> Store
38
- Exec -- "startActivation\nlabel#nodeId" --> Sub
38
+ Exec -- "startActivation / interrupt" --> Sub
39
39
  Sub -- "状态与 childId" --> Cat
40
40
  Cat --> UI
41
41
  ```
@@ -57,15 +57,16 @@ flowchart LR
57
57
  调用 `canvas_workflow` 时,Host 的 `executePlan` 按以下流水线运行:
58
58
 
59
59
  1. **入口剥离与任务解析**:剥离作为总任务容器的入口节点 `lead`(永不作为子代理执行)。若调用时传入 `task` 参数,则覆盖入口 Lead 的总任务(方便直接复用空任务预设)。
60
- 2. **成环校验(Kahn 拓扑排序)**:用 `orderNodes` 校验 DAG 无环(客户端手动画线时也会用 `wouldCycle` 即时拦截)。
61
- 3. **可达性剪枝**:从入口 `lead` 做广度优先遍历,不可达的孤立节点在画布上显示为虚线,运行时被自动跳过并列入 `skipped`,不会消耗 Token。
62
- 4. **事件驱动并发池、条件剪枝与断点续跑**:
60
+ 2. **成环校验与受控回环校验**:`orderNodes` 在**前向边(`!e.loop`)**上用 Kahn 拓扑排序保证主图无环;`validateLoopEdges` 单独校验受控回环边(`e.loop === true`),要求起点必为条件节点、目标必为严格前向祖先(非入口 Lead)且回环互不交叉。
61
+ 3. **可达性剪枝**:从入口 `lead` 沿前向边做广度优先遍历,不可达的孤立节点、空分工且无子代理上游的 Lead、以及悬空无出边的子代理在画布上显示为虚线,运行时自动跳过并列入 `skipped`,不会消耗 Token。
62
+ 4. **事件驱动并发池、条件剪枝、受控回环与断点续跑**:
63
63
  - 每个会话的运行进度保存在 `runBySession`,每次结束/熔断还会将快照存入 `lastRunBySession`;
64
64
  - 执行器维护一个**可调并发上限**(默认 4,可在 `⋯` 菜单或参数中调为 `1–8`)的**动态并发池(`inFlight` + `Promise.race`)**:
65
65
  - 只要有任意在跑子代理完成、空出并发槽位,**任何依赖已满足的下游子代理会立刻启动**,不再傻等同层较慢的兄弟节点;
66
66
  - 遇到**条件节点(`kind: "condition"`)**时,以轻量只读模式(`minimal`)+ 严格结构化 `outputSchema` 判断命中分支(支持默认 `if/else`、任意多路 `switch/case` 单选与 `multiMatch` 多选并行),随即阻断未命中出边并用祖先感知 BFS 剪枝未命中分支(包括防止上游 `session-ref` 侧线绕过条件);若所有分支均未命中或条件节点自身失败,则绝不瞎猜分支,直接跳过中间分支转交最近下游 Lead(无下游 Lead 时熔断暂停);
67
- - 遇到**中间 Lead 节点**时暂停并返回 `status: "need-lead"`;遇到**末尾终审 Lead**(无剩余下游)时直接一步返回 `status: "done"` 与 `finalLead`,无需多余回调轮次;
68
- - 支持 **`retryFailed: true`** 或 **`fromNodes: [...]`** 局部重跑:自动复用上次已成功节点的缓存结果,仅重跑失败/目标节点及其下游;传 `reset: true` 则从头重跑。
67
+ - 遇到命中的**受控回环边(`loop: true, maxIterations: 1–10`)**时(`multiMatch` 下回环优先):若未超单环上限与全局安全上限(`20` 次),精准重置 `descendants(入口) ∩ ancestors(条件)` 环内节点的运行状态(环外旁路不受影响),把打回理由注入回环入口(同时支持子代理与 `Lead` 节点),并在入口上一轮执行健康时自动复用其热子会话发送增量修正提示词(崩溃/空输出则丢弃旧会话重开);若达到上限则熔断停止回跳,汇总 `1..N` 轮失败理由转交最近下游 Lead 拍板;
68
+ - 遇到**中间 Lead 节点**(支持 `Lead → Lead` 阶段串联)时暂停并返回 `status: "need-lead"`;遇到**末尾终审 Lead**(无剩余下游)时直接一步返回 `status: "done"` 与 `finalLead`,无需多余回调轮次;
69
+ - 支持 **`retryFailed: true`** 或 **`fromNodes: [...]`** 局部重跑:自动复用上次已成功节点的缓存结果,仅重跑失败/目标节点及其下游;传 `reset: true` 则从头重跑;传 **`cancel: true`** 或通过画布 **`⏹ 终止`** 触发并发命令 **`/canvas-stop`**(亦对齐 DSH 原生聊天停止按钮)时,立即调用 `subagents.interrupt(cid, { kind: 'user' })`、`drainDescendants([rootAgent])` 与 `rootAgent.cancel({ kind: 'user' }, { keepInbox: true })`,以 `abortPromise` 秒级跳出并发池、阻止拉起备用模型重试,同时保留已完成节点缓存并清空 `waitingLead` / `.run.json`。
69
70
 
70
71
  ```mermaid
71
72
  sequenceDiagram
@@ -118,15 +119,16 @@ sequenceDiagram
118
119
  ## 5. 实时状态胶囊与点击直达子会话
119
120
 
120
121
  1. **节点反查标记**:`spawnOnce` 启动子代理时,固定把 `spec.label` 设为 `<节点名>#<nodeId>`。
121
- 2. **状态实时追踪**:客户端监听当前会话的运行态,在对话运行期间每 700ms(以及挂载与每轮结束时)读取 `sessions.list` 投影中的 `subagentCatalog` 与 `subagentTiming`,用末尾正则 `/#([^\s#]+)$/` 精准反查节点状态(`running` / `done` / `failed`)以及对应的 `childId`。
122
- 3. **Lead「待拍板」自动高亮**:对于非入口 Lead 节点,客户端检测到其所有上游子代理均为 `done` 且下游尚未启动时,自动亮起蓝色 **`⏸ 待拍板`** 提示。
122
+ 2. **状态与遥测实时追踪**:客户端在对话运行期间每 700ms(以及挂载与每轮结束时)读取 `sessions.list` 投影中的 `subagentCatalog` 与 `subagentTiming`,用末尾正则 `/#([^\s#]+)$/` 精准反查子代理状态(`running` 具最高优先级,避免多轮重试被历史记录覆盖)与 `childId`;同时轮询 Host 写入的 `<workspace>/.dsh/canvas/<sid>.run.json` 获取条件判决(`decisions`)、剪枝集(`pruned`)、阻断边(`blockedEdges`)、回环实时轮次(`loopCounts` / `nodeAttempts`)与待拍板状态(`waitingLead`)。
123
+ 3. **Lead「待拍板」权威状态与统一终止**:优先以 `.run.json` 报告的权威状态为准(`need-lead` 高亮 **`⏸ 待拍板`**,`halted` / `done` / `idle` 绝不误回弹锁死),仅在缺失 `.run.json` 时回退到前向边启发式推导;运行中或待拍板时均显示 **`⏹ 终止`** 按钮。
123
124
  4. **一键直达真实子对话**:点击任意子代理节点左下角状态胶囊(如 `进行中 ↗` / `已完成 ↗`),客户端调用 `sidebarRight.openResource('dsh-resource://subagentchat/session/<childId>?parent=<sessionId>&mode=<mode>', { kind: 'subagentchat', preferNewPane: true })`,直接在新侧边窗格打开该子代理的真实对话记录。
124
125
 
125
126
  ---
126
127
 
127
- ## 6. Skill 与工具引导机制
128
+ ## 6. 会话级强上下文、Skill 与工具引导机制
128
129
 
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` 中加一行显式指令,可在任意对话中实现最高触发稳定性。
130
+ 为了让模型在开启画布后稳定、准确地遵循编排而又不污染其它会话或子代理,插件采用四层协同引导:
131
+ 1. **会话级 `systemPrompt.context` 强注入**:仅对画布处于「`● 已启用`」的当前主会话(按 `sessionId` 严格匹配,绝不泄漏到子代理)每轮自动注入画布摘要(节点概览、受控回环条数、全局参考数、记忆/权限/断点续跑提示;若暂停在中间 Lead 则注入待拍板说明、`leadResult` / `cancel: true` / `reset: true` 与回环打回理由)。
132
+ 2. **Skill 目录注册**:`index.js` 通过 `ctx.skills.registerProvider` 注册内置技能 `workflow-canvas`,摘要中包含中英触发词(`canvas / workflow / 条件分支 / 回环重试 / 画布 / 工作流 / 编排`)与 4 个 `canvas_*` 工具名;正文读取自 [skills/workflow-canvas/SKILL.md](../skills/workflow-canvas/SKILL.md)。
133
+ 3. **工具说明互指**:`canvas_inspect`、`canvas_generate`、`canvas_patch`、`canvas_workflow` 的工具描述均提示模型按需先加载 `workflow-canvas` 技能,而工具定义始终在上下文中。
134
+ 4. **项目级锁定(可选)**:在项目 `AGENTS.md` 中加一行显式指令,可在任意对话中实现最高触发稳定性。
Binary file
Binary file