dsh-workflow-canvas 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +112 -2
- package/README.zh.md +86 -0
- package/client.js +2192 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +53 -0
- package/docs/images/canvas-demo-zh.png +0 -0
- package/docs/images/canvas-demo.png +0 -0
- package/docs/images/node-types.svg +86 -0
- package/icon.svg +9 -0
- package/index.js +888 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +45 -4
- package/skills/workflow-canvas/SKILL.md +65 -0
package/index.js
ADDED
|
@@ -0,0 +1,888 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the workflow-canvas bundle.
|
|
3
|
+
*
|
|
4
|
+
* The browser canvas owns editing. This half executes the canvas plan:
|
|
5
|
+
* - `canvas-sync` publishes the plan for its Session (client → Host);
|
|
6
|
+
* - the `canvas_workflow` tool runs the DAG in parallel waves. Subagent nodes
|
|
7
|
+
* are spawned through `ctx.subagents` (per-node model, reasoning effort and
|
|
8
|
+
* preset all work); a Lead node pauses the run and hands control back to the
|
|
9
|
+
* conversation, which resumes it with `leadResult`.
|
|
10
|
+
*
|
|
11
|
+
* Extra behavior, all optional per node:
|
|
12
|
+
* - `keepSession` re-uses the node's previous child session (memory);
|
|
13
|
+
* - `fallbackModel` retries a failed node once on another model;
|
|
14
|
+
* - plans survive a Host restart through a JSON file in the profile.
|
|
15
|
+
*
|
|
16
|
+
* Everything is defensive: a missing service disables one piece instead of
|
|
17
|
+
* failing the plugin load.
|
|
18
|
+
*/
|
|
19
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
|
|
23
|
+
/** Latest canvas payload per Session id. */
|
|
24
|
+
const canvasBySession = new Map();
|
|
25
|
+
/** In-flight run progress per Session id. */
|
|
26
|
+
const runBySession = new Map();
|
|
27
|
+
/** node id → child session id, so `keepSession` can resume previous work. */
|
|
28
|
+
const childByNode = new Map();
|
|
29
|
+
/** node id → child id created in this process, safe to resume. */
|
|
30
|
+
const liveChild = new Map();
|
|
31
|
+
|
|
32
|
+
function storePath() {
|
|
33
|
+
const home = process.env.DSH_PROFILE_DIR;
|
|
34
|
+
if (!home) return undefined;
|
|
35
|
+
return join(home, '.workflow-canvas-state.json');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function loadStore() {
|
|
39
|
+
const path = storePath();
|
|
40
|
+
if (!path) return;
|
|
41
|
+
try {
|
|
42
|
+
const raw = readFileSync(path, 'utf8');
|
|
43
|
+
const doc = JSON.parse(raw);
|
|
44
|
+
if (doc && doc.canvas && typeof doc.canvas === 'object') {
|
|
45
|
+
for (const [sid, payload] of Object.entries(doc.canvas)) canvasBySession.set(sid, payload);
|
|
46
|
+
}
|
|
47
|
+
if (doc && doc.children && typeof doc.children === 'object') {
|
|
48
|
+
for (const [node, child] of Object.entries(doc.children)) childByNode.set(node, child);
|
|
49
|
+
}
|
|
50
|
+
} catch (_e) {
|
|
51
|
+
/* no store yet, or unreadable: start clean */
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function saveStore() {
|
|
56
|
+
const path = storePath();
|
|
57
|
+
if (!path) return;
|
|
58
|
+
try {
|
|
59
|
+
mkdirSync(join(path, '..'), { recursive: true });
|
|
60
|
+
const tmp = path + '.tmp';
|
|
61
|
+
writeFileSync(tmp, JSON.stringify({
|
|
62
|
+
canvas: Object.fromEntries(canvasBySession),
|
|
63
|
+
children: Object.fromEntries(childByNode),
|
|
64
|
+
}), 'utf8');
|
|
65
|
+
renameSync(tmp, path);
|
|
66
|
+
} catch (_e) {
|
|
67
|
+
/* persistence is best-effort */
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The entry Lead is a task container, never a runnable node. */
|
|
72
|
+
function withoutEntry(nodes) {
|
|
73
|
+
return (nodes || []).filter((n) => n.id !== 'lead');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function parsePayload(rawInput) {
|
|
77
|
+
const text = String(rawInput || '').trim();
|
|
78
|
+
if (!text) return { enabled: false };
|
|
79
|
+
try {
|
|
80
|
+
return JSON.parse(decodeURIComponent(text));
|
|
81
|
+
} catch (_e) {
|
|
82
|
+
return { enabled: false, error: '画布数据解析失败' };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Kahn topological order over every plan node. */
|
|
87
|
+
function orderNodes(plan) {
|
|
88
|
+
const nodes = plan.nodes || [];
|
|
89
|
+
const edges = plan.edges || [];
|
|
90
|
+
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
91
|
+
const indeg = new Map(nodes.map((n) => [n.id, 0]));
|
|
92
|
+
const adj = new Map(nodes.map((n) => [n.id, []]));
|
|
93
|
+
for (const e of edges) {
|
|
94
|
+
if (e.from === 'lead') continue;
|
|
95
|
+
if (!byId.has(e.from) || !byId.has(e.to)) continue;
|
|
96
|
+
indeg.set(e.to, indeg.get(e.to) + 1);
|
|
97
|
+
adj.get(e.from).push(e.to);
|
|
98
|
+
}
|
|
99
|
+
const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
|
|
100
|
+
const out = [];
|
|
101
|
+
while (queue.length) {
|
|
102
|
+
const id = queue.shift();
|
|
103
|
+
out.push(byId.get(id));
|
|
104
|
+
for (const next of adj.get(id)) {
|
|
105
|
+
indeg.set(next, indeg.get(next) - 1);
|
|
106
|
+
if (indeg.get(next) === 0) queue.push(next);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return out.length === nodes.length ? out : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function upstreamOf(plan, node) {
|
|
113
|
+
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
114
|
+
return (plan.edges || [])
|
|
115
|
+
.filter((e) => e.to === node.id)
|
|
116
|
+
.map((e) => ({ edge: e, from: byId.get(e.from) }))
|
|
117
|
+
.filter((x) => x.from);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function downstreamLabels(plan, node) {
|
|
121
|
+
const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
|
|
122
|
+
return (plan.edges || [])
|
|
123
|
+
.filter((e) => e.from === node.id)
|
|
124
|
+
.map((e) => (byId.get(e.to) || {}).label)
|
|
125
|
+
.filter(Boolean);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function briefFor(plan, node, results) {
|
|
129
|
+
const ups = upstreamOf(plan, node);
|
|
130
|
+
const downs = downstreamLabels(plan, node);
|
|
131
|
+
const head = [];
|
|
132
|
+
head.push('【工作流节点】你在一个多步工作流里负责「' + node.label + '」这一步(子代理)。');
|
|
133
|
+
if (ups.length === 0) head.push('【总任务】' + plan.task);
|
|
134
|
+
head.push('【职责】' + (node.role || node.label));
|
|
135
|
+
if (ups.length) head.push('【上游】' + ups.map((u) => u.from.label).join('、') + ' 已交付结果给你(见下文)。');
|
|
136
|
+
head.push('【下游】' + (downs.length ? downs.join('、') + ' 会使用你的输出。' : '你是终点,结果会直接交付给用户。'));
|
|
137
|
+
head.push('【要求】只完成你这一步;输出要能被下游直接使用,不要重复上游已完成的工作。');
|
|
138
|
+
let text = head.join('\n') + '\n';
|
|
139
|
+
for (const u of ups) {
|
|
140
|
+
const value = results[u.from.id];
|
|
141
|
+
const type = u.edge.type || 'prompt';
|
|
142
|
+
const body = typeof value === 'string' ? value : '(没有结果)';
|
|
143
|
+
if (type === 'structured') {
|
|
144
|
+
text += '\n## 来自【' + u.from.label + '】的数据(JSON,可直接解析)\n```json\n'
|
|
145
|
+
+ body + '\n```\n';
|
|
146
|
+
} else if (type === 'session-ref') {
|
|
147
|
+
text += '\n## 来自【' + u.from.label + '】的会话引用(当前按文本传递)\n'
|
|
148
|
+
+ body + '\n';
|
|
149
|
+
} else {
|
|
150
|
+
text += '\n## 来自【' + u.from.label + '】\n' + body + '\n';
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return text;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function textOf(result) {
|
|
157
|
+
// A structured node's canonical value is its parsed object, not the prose.
|
|
158
|
+
if (result && result.structured !== undefined) {
|
|
159
|
+
try {
|
|
160
|
+
return JSON.stringify(result.structured);
|
|
161
|
+
} catch (_e) {
|
|
162
|
+
/* fall through to prose */
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const blocks = (result && result.output) || [];
|
|
166
|
+
const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
|
|
167
|
+
return text || '[' + ((result && result.stopReason) || 'no-output') + ']';
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function failed(result) {
|
|
171
|
+
const reason = result && result.stopReason;
|
|
172
|
+
return reason !== undefined && reason !== 'completed';
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid) {
|
|
176
|
+
const childKey = (id) => String(sid || '') + '::' + id;
|
|
177
|
+
const spec = {
|
|
178
|
+
provider: 'spawn',
|
|
179
|
+
label: node.label + '#' + node.id,
|
|
180
|
+
prompt: [{ type: 'text', text: briefFor(plan, node, results) }],
|
|
181
|
+
parent,
|
|
182
|
+
signal,
|
|
183
|
+
delivery: 'caller',
|
|
184
|
+
};
|
|
185
|
+
const agentOptions = {};
|
|
186
|
+
const provider = (route && route.provider) || node.provider;
|
|
187
|
+
const model = (route && route.model) || node.model;
|
|
188
|
+
if (provider) agentOptions.provider = provider;
|
|
189
|
+
if (model) agentOptions.model = model;
|
|
190
|
+
if (node.reasoning) agentOptions.reasoningEffort = node.reasoning;
|
|
191
|
+
if (Object.keys(agentOptions).length) spec.agentOptions = agentOptions;
|
|
192
|
+
if (node.preset) spec.agentPreset = node.preset;
|
|
193
|
+
if (node.structured) {
|
|
194
|
+
spec.outputSchema = {
|
|
195
|
+
type: 'object',
|
|
196
|
+
additionalProperties: true,
|
|
197
|
+
description: 'Return the result as a JSON object so downstream steps can consume it.',
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const run = async (childId) => {
|
|
202
|
+
const withChild = childId ? { ...spec, childId } : spec;
|
|
203
|
+
let activation;
|
|
204
|
+
try {
|
|
205
|
+
activation = await scope.subagents.startActivation(withChild);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
const message = String((error && error.message) || error);
|
|
208
|
+
return { ok: false, text: '启动失败:' + message, reason: 'activation-failed' };
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
if (activation && activation.childId) {
|
|
212
|
+
childByNode.set(childKey(node.id), activation.childId);
|
|
213
|
+
liveChild.set(childKey(node.id), activation.childId);
|
|
214
|
+
}
|
|
215
|
+
let result;
|
|
216
|
+
try {
|
|
217
|
+
result = await activation.result;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
const message = String((error && error.message) || error);
|
|
220
|
+
return { ok: false, text: '运行失败:' + message, reason: 'run-failed' };
|
|
221
|
+
}
|
|
222
|
+
return { ok: !failed(result), text: textOf(result), reason: result && result.stopReason };
|
|
223
|
+
} finally {
|
|
224
|
+
try { await activation.dispose(); } catch (_e) { /* ignore */ }
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
// A `session` edge means "continue the upstream node's conversation": run this
|
|
229
|
+
// step inside that child session instead of starting a fresh one.
|
|
230
|
+
if (forcedChild && forcedChild !== liveChild.get(childKey(node.id))) {
|
|
231
|
+
try {
|
|
232
|
+
const continued = await run(forcedChild);
|
|
233
|
+
if (continued.ok) liveChild.set(childKey(node.id), forcedChild);
|
|
234
|
+
return continued;
|
|
235
|
+
} catch (_e) {
|
|
236
|
+
/* fall through to a fresh session */
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Memory: prefer the session created in this process, then the one persisted
|
|
241
|
+
// from an earlier run. A cold resume that the Host refuses is forgotten so the
|
|
242
|
+
// node simply starts fresh instead of failing.
|
|
243
|
+
if (node.keepSession) {
|
|
244
|
+
const inProcess = liveChild.get(childKey(node.id));
|
|
245
|
+
const fromDisk = childByNode.get(childKey(node.id));
|
|
246
|
+
const previous = inProcess || fromDisk;
|
|
247
|
+
if (previous) {
|
|
248
|
+
const resumed = await run(previous);
|
|
249
|
+
if (resumed.ok) return resumed;
|
|
250
|
+
if (resumed.reason === 'activation-failed') {
|
|
251
|
+
liveChild.delete(childKey(node.id));
|
|
252
|
+
childByNode.delete(childKey(node.id));
|
|
253
|
+
} else {
|
|
254
|
+
return resumed;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const started = await run(undefined);
|
|
259
|
+
if (node.keepSession && started.ok) {
|
|
260
|
+
const current = childByNode.get(childKey(node.id));
|
|
261
|
+
if (current) liveChild.set(childKey(node.id), current);
|
|
262
|
+
}
|
|
263
|
+
return started;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function spawnNode(scope, plan, node, results, parent, signal, sid) {
|
|
267
|
+
const continueFrom = (plan.edges || [])
|
|
268
|
+
.filter((e) => e.to === node.id && e.type === 'session-ref')
|
|
269
|
+
.map((e) => liveChild.get(String(sid || '') + '::' + e.from))
|
|
270
|
+
.find((id) => typeof id === 'string');
|
|
271
|
+
|
|
272
|
+
if (continueFrom) {
|
|
273
|
+
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid);
|
|
274
|
+
if (continued.ok) return continued.text + '\n(已在上游会话中继续)';
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid);
|
|
278
|
+
if (first.ok) return first.text;
|
|
279
|
+
if (!node.fallbackModel && !node.fallbackProvider) {
|
|
280
|
+
return first.text + '\n(失败原因:' + (first.reason || 'unknown') + ',未配置备用模型)';
|
|
281
|
+
}
|
|
282
|
+
const retry = await spawnOnce(scope, plan, node, results, parent, signal, {
|
|
283
|
+
provider: node.fallbackProvider,
|
|
284
|
+
model: node.fallbackModel,
|
|
285
|
+
}, undefined, sid);
|
|
286
|
+
if (retry.ok) return retry.text + '\n(已用备用模型重试成功)';
|
|
287
|
+
return retry.text + '\n(重试仍失败:' + (retry.reason || 'unknown') + ')';
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Ids reachable from the entry Lead; every other node is skipped at run time. */
|
|
291
|
+
function reachableFrom(plan) {
|
|
292
|
+
const set = new Set(['lead']);
|
|
293
|
+
let grew = true;
|
|
294
|
+
while (grew) {
|
|
295
|
+
grew = false;
|
|
296
|
+
for (const e of plan.edges || []) {
|
|
297
|
+
if (set.has(e.from) && !set.has(e.to)) { set.add(e.to); grew = true; }
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return set;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Turn a model-authored sketch into a canvas document: assign ids, add the entry
|
|
305
|
+
* Lead, and lay the graph out in columns by depth so it is readable on arrival.
|
|
306
|
+
*/
|
|
307
|
+
function normalizeCanvas(args) {
|
|
308
|
+
const rawNodes = Array.isArray(args && args.nodes) ? args.nodes : [];
|
|
309
|
+
const rawEdges = Array.isArray(args && args.edges) ? args.edges : [];
|
|
310
|
+
if (!rawNodes.length) return { error: '至少需要一个节点' };
|
|
311
|
+
|
|
312
|
+
const nodes = [];
|
|
313
|
+
const idByRef = new Map();
|
|
314
|
+
let counter = 0;
|
|
315
|
+
for (const raw of rawNodes) {
|
|
316
|
+
if (!raw || typeof raw !== 'object') continue;
|
|
317
|
+
counter += 1;
|
|
318
|
+
const kind = raw.kind === 'lead' ? 'lead' : 'agent';
|
|
319
|
+
const wantsEntry = raw.entry === true && kind === 'lead';
|
|
320
|
+
const id = wantsEntry
|
|
321
|
+
? 'lead'
|
|
322
|
+
: (typeof raw.id === 'string' && raw.id && raw.id !== 'lead' ? raw.id : 'n' + counter);
|
|
323
|
+
const label = String(raw.label || (kind === 'lead' ? 'Lead 步骤 ' + counter : 'Node ' + counter));
|
|
324
|
+
nodes.push({
|
|
325
|
+
id,
|
|
326
|
+
kind,
|
|
327
|
+
label,
|
|
328
|
+
role: String(raw.role || ''),
|
|
329
|
+
task: String(raw.task || ''),
|
|
330
|
+
provider: String(raw.provider || ''),
|
|
331
|
+
model: String(raw.model || ''),
|
|
332
|
+
reasoning: String(raw.reasoning || ''),
|
|
333
|
+
preset: String(raw.preset || ''),
|
|
334
|
+
structured: Boolean(raw.structured),
|
|
335
|
+
keepSession: Boolean(raw.keepSession),
|
|
336
|
+
fallbackModel: String(raw.fallbackModel || ''),
|
|
337
|
+
fallbackProvider: String(raw.fallbackProvider || ''),
|
|
338
|
+
x: 0,
|
|
339
|
+
y: 0,
|
|
340
|
+
});
|
|
341
|
+
if (raw.ref) idByRef.set(String(raw.ref), id);
|
|
342
|
+
idByRef.set(id, id);
|
|
343
|
+
}
|
|
344
|
+
if (!nodes.length) return { error: '节点都无效' };
|
|
345
|
+
|
|
346
|
+
const entry = nodes.find((n) => n.id === 'lead');
|
|
347
|
+
if (!entry) {
|
|
348
|
+
nodes.unshift({
|
|
349
|
+
id: 'lead', kind: 'lead', label: 'Lead(本对话)', role: '',
|
|
350
|
+
task: String(args.task || ''), provider: '', model: '', reasoning: '',
|
|
351
|
+
preset: '', structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
|
|
352
|
+
x: 0, y: 0,
|
|
353
|
+
});
|
|
354
|
+
} else if (!entry.task) {
|
|
355
|
+
entry.task = String(args.task || '');
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const ids = new Set(nodes.map((n) => n.id));
|
|
359
|
+
const edges = [];
|
|
360
|
+
for (const raw of rawEdges) {
|
|
361
|
+
if (!raw || typeof raw !== 'object') continue;
|
|
362
|
+
const from = idByRef.get(String(raw.from)) || String(raw.from);
|
|
363
|
+
const to = idByRef.get(String(raw.to)) || String(raw.to);
|
|
364
|
+
if (!ids.has(from) || !ids.has(to) || from === to) continue;
|
|
365
|
+
const type = ['prompt', 'structured', 'session-ref'].includes(raw.type) ? raw.type : 'prompt';
|
|
366
|
+
edges.push({ id: 'e' + edges.length, from, to, type });
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Layout: depth of the longest path from the entry, then stack per column.
|
|
370
|
+
const depth = new Map(nodes.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
|
|
371
|
+
for (let pass = 0; pass < nodes.length; pass += 1) {
|
|
372
|
+
let changed = false;
|
|
373
|
+
for (const e of edges) {
|
|
374
|
+
if (e.to === 'lead') continue;
|
|
375
|
+
const next = Math.min(nodes.length, depth.get(e.from) + 1);
|
|
376
|
+
if (next > depth.get(e.to)) { depth.set(e.to, next); changed = true; }
|
|
377
|
+
}
|
|
378
|
+
if (!changed) break;
|
|
379
|
+
}
|
|
380
|
+
const perColumn = new Map();
|
|
381
|
+
for (const node of nodes) {
|
|
382
|
+
const level = depth.get(node.id) || 0;
|
|
383
|
+
const row = perColumn.get(level) || 0;
|
|
384
|
+
perColumn.set(level, row + 1);
|
|
385
|
+
node.x = 60 + level * 300;
|
|
386
|
+
node.y = 80 + row * 230;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
return { nodes, edges, task: String(args.task || '') };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Drop a generated canvas where the browser can pick it up. `workspaceFiles`
|
|
394
|
+
* resolves a session's root from its header cwd, so the client reads the same
|
|
395
|
+
* relative path back through the Remote.
|
|
396
|
+
*/
|
|
397
|
+
function publishCanvas(scope, sessionId, canvas) {
|
|
398
|
+
try {
|
|
399
|
+
const live = scope && scope.sessions && scope.sessions.get(sessionId);
|
|
400
|
+
const root = live && live.header && live.header.cwd;
|
|
401
|
+
if (!root) return false;
|
|
402
|
+
const dir = join(root, '.dsh', 'canvas');
|
|
403
|
+
mkdirSync(dir, { recursive: true });
|
|
404
|
+
writeFileSync(join(dir, sessionId + '.json'), JSON.stringify({ canvas, at: Date.now() }), 'utf8');
|
|
405
|
+
return true;
|
|
406
|
+
} catch (_e) {
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async function runPlan(scope, args, exec) {
|
|
412
|
+
const agent = exec && exec.agent;
|
|
413
|
+
const sid = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
414
|
+
const payload = sid ? canvasBySession.get(sid) : undefined;
|
|
415
|
+
if (!payload) return { error: '当前会话还没有画布数据。请在右侧 Workflow 画布点「启用」。' };
|
|
416
|
+
if (!payload.enabled) return { error: '画布当前是「已禁用」状态。请在画布上点「启用」后再运行。' };
|
|
417
|
+
if (payload.error) return { error: String(payload.error) };
|
|
418
|
+
return executePlan(scope, payload.plan, args, exec);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Takes a plan directly so tests can feed any plan shape (sync, generate, patch). */
|
|
422
|
+
async function executePlan(scope, plan, args, exec) {
|
|
423
|
+
const agent = exec && exec.agent;
|
|
424
|
+
const sid = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
425
|
+
if (!plan || !Array.isArray(plan.nodes) || !plan.nodes.length) {
|
|
426
|
+
return { error: '画布没有可执行的节点。' };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Backstop: no matter how a plan arrived (sync, generate, patch, a stale store),
|
|
430
|
+
// the entry Lead is never executed.
|
|
431
|
+
plan = { ...plan, nodes: withoutEntry(plan.nodes) };
|
|
432
|
+
|
|
433
|
+
const order = orderNodes(plan);
|
|
434
|
+
if (!order) return { error: '存在环,无法执行有向无环图。' };
|
|
435
|
+
|
|
436
|
+
// Defense in depth: unreachable nodes are skipped, never spawned.
|
|
437
|
+
const reachable = new Set(['lead']);
|
|
438
|
+
let grew = true;
|
|
439
|
+
while (grew) {
|
|
440
|
+
grew = false;
|
|
441
|
+
for (const e of plan.edges || []) {
|
|
442
|
+
if (reachable.has(e.from) && !reachable.has(e.to)) { reachable.add(e.to); grew = true; }
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
const runnable = order.filter((n) => reachable.has(n.id));
|
|
446
|
+
const skipped = order.filter((n) => !reachable.has(n.id)).map((n) => n.label || n.id);
|
|
447
|
+
if (!runnable.length) return { error: '没有从入口 Lead 连通的节点,无法执行。' };
|
|
448
|
+
|
|
449
|
+
const sig = JSON.stringify(plan);
|
|
450
|
+
let state = runBySession.get(sid);
|
|
451
|
+
if (!state || state.sig !== sig) {
|
|
452
|
+
state = { sig, done: new Set(), results: {}, labels: {} };
|
|
453
|
+
runBySession.set(sid, state);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const byId = new Map(runnable.map((n) => [n.id, n]));
|
|
457
|
+
const labelOf = new Map(order.map((n) => [n.id, n.label || n.id]));
|
|
458
|
+
const depsOf = (node) => (plan.edges || [])
|
|
459
|
+
.filter((e) => e.to === node.id && e.from !== 'lead')
|
|
460
|
+
.map((e) => e.from)
|
|
461
|
+
.filter((id) => byId.has(id));
|
|
462
|
+
|
|
463
|
+
let leadResult = typeof args.leadResult === 'string' ? args.leadResult : undefined;
|
|
464
|
+
const MAX_PARALLEL = 4;
|
|
465
|
+
|
|
466
|
+
for (;;) {
|
|
467
|
+
const remaining = runnable.filter((n) => !state.done.has(n.id));
|
|
468
|
+
if (!remaining.length) {
|
|
469
|
+
runBySession.delete(sid);
|
|
470
|
+
saveStore();
|
|
471
|
+
return { status: 'done', results: state.results, labels: state.labels, skipped };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const ready = remaining.filter((n) => depsOf(n).every((id) => state.done.has(id)));
|
|
475
|
+
if (!ready.length) return { error: '有节点的依赖无法满足(存在环或悬空依赖)。' };
|
|
476
|
+
|
|
477
|
+
const agentReady = ready.filter((n) => n.kind !== 'lead');
|
|
478
|
+
if (agentReady.length) {
|
|
479
|
+
const batch = agentReady.slice(0, MAX_PARALLEL);
|
|
480
|
+
const texts = await Promise.all(
|
|
481
|
+
batch.map((node) => spawnNode(scope, plan, node, state.results, agent, exec.signal, sid)),
|
|
482
|
+
);
|
|
483
|
+
batch.forEach((node, i) => {
|
|
484
|
+
state.results[node.id] = texts[i];
|
|
485
|
+
state.labels[node.id] = node.label;
|
|
486
|
+
state.done.add(node.id);
|
|
487
|
+
});
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const leadNode = ready.find((n) => n.kind === 'lead');
|
|
492
|
+
if (!leadNode) return { error: '没有可执行的节点。' };
|
|
493
|
+
if (leadResult === undefined) {
|
|
494
|
+
return {
|
|
495
|
+
status: 'need-lead',
|
|
496
|
+
node: {
|
|
497
|
+
label: leadNode.label,
|
|
498
|
+
role: leadNode.role || leadNode.label,
|
|
499
|
+
needs: depsOf(leadNode).map((id) => byId.get(id).label),
|
|
500
|
+
},
|
|
501
|
+
results: state.results,
|
|
502
|
+
labels: state.labels,
|
|
503
|
+
sessions: depsOf(leadNode)
|
|
504
|
+
.filter((id) => (plan.edges || []).some((e) => e.to === leadNode.id && e.from === id && e.type === 'session-ref'))
|
|
505
|
+
.map((id) => ({
|
|
506
|
+
label: labelOf.get(id) || id,
|
|
507
|
+
childId: liveChild.get(String(sid || '') + '::' + id)
|
|
508
|
+
|| childByNode.get(String(sid || '') + '::' + id)
|
|
509
|
+
|| null,
|
|
510
|
+
})),
|
|
511
|
+
hint: '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续。',
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
state.results[leadNode.id] = leadResult;
|
|
515
|
+
state.labels[leadNode.id] = leadNode.label;
|
|
516
|
+
state.done.add(leadNode.id);
|
|
517
|
+
leadResult = undefined;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Agent-facing guide, shipped as a skill so any agent can load it on demand. */
|
|
522
|
+
const SKILL_NAME = 'workflow-canvas';
|
|
523
|
+
const SKILL_DESCRIPTION = 'Workflow canvas (画布 / 工作流 / 编排): draw, edit or run a node graph of DSH subagents — add or re-role nodes, wire typed links, run in parallel waves, handle Lead steps, presets and memory. Load before using canvas_generate, canvas_patch or canvas_workflow.';
|
|
524
|
+
function skillPath() {
|
|
525
|
+
try {
|
|
526
|
+
return fileURLToPath(new URL('./skills/workflow-canvas/SKILL.md', import.meta.url));
|
|
527
|
+
} catch (_e) {
|
|
528
|
+
return undefined;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function readSkillGuide() {
|
|
533
|
+
try {
|
|
534
|
+
const location = skillPath();
|
|
535
|
+
if (!location) return fallbackGuide();
|
|
536
|
+
const raw = readFileSync(location, 'utf8');
|
|
537
|
+
const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(raw);
|
|
538
|
+
return match ? raw.slice(match[0].length).trim() : raw.trim();
|
|
539
|
+
} catch (_e) {
|
|
540
|
+
return fallbackGuide();
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function fallbackGuide() {
|
|
545
|
+
return '# Workflow canvas\n\nThe bundled guide could not be read from this installation.';
|
|
546
|
+
}
|
|
547
|
+
export function apply(ctx) {
|
|
548
|
+
loadStore();
|
|
549
|
+
ctx.inject(['skills'], (scope) => {
|
|
550
|
+
try {
|
|
551
|
+
scope.effect(() => scope.skills.registerProvider(() => ({
|
|
552
|
+
name: 'dsh-workflow-canvas',
|
|
553
|
+
async list() {
|
|
554
|
+
return {
|
|
555
|
+
candidates: [{
|
|
556
|
+
name: SKILL_NAME,
|
|
557
|
+
description: SKILL_DESCRIPTION,
|
|
558
|
+
invocation: { modelInvocable: true, userInvocable: true },
|
|
559
|
+
provider: 'dsh-workflow-canvas',
|
|
560
|
+
source: 'bundled',
|
|
561
|
+
rank: 0,
|
|
562
|
+
locator: 'dsh-workflow-canvas/skills/workflow-canvas/SKILL.md',
|
|
563
|
+
}],
|
|
564
|
+
complete: true,
|
|
565
|
+
};
|
|
566
|
+
},
|
|
567
|
+
async get(candidate) {
|
|
568
|
+
const { rank, locator, ...summary } = candidate;
|
|
569
|
+
void rank;
|
|
570
|
+
void locator;
|
|
571
|
+
return { ...summary, content: readSkillGuide() };
|
|
572
|
+
},
|
|
573
|
+
})), 'workflow-canvas: skill');
|
|
574
|
+
} catch (_e) {
|
|
575
|
+
/* skill registry unavailable */
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
try {
|
|
579
|
+
ctx.inject(['commands'], (scope) => {
|
|
580
|
+
try {
|
|
581
|
+
scope.effect(() => scope.commands.register({
|
|
582
|
+
name: 'canvas-sync',
|
|
583
|
+
description: 'Publish the workflow canvas plan for this session.',
|
|
584
|
+
recordInput: false,
|
|
585
|
+
handler: ({ agent, rawInput }) => {
|
|
586
|
+
try {
|
|
587
|
+
const id = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
588
|
+
if (!id) return { kind: 'error', text: 'no session' };
|
|
589
|
+
canvasBySession.set(id, parsePayload(rawInput));
|
|
590
|
+
runBySession.delete(id);
|
|
591
|
+
saveStore();
|
|
592
|
+
return { kind: 'success', text: 'canvas synced' };
|
|
593
|
+
} catch (error) {
|
|
594
|
+
return { kind: 'error', text: String((error && error.message) || error) };
|
|
595
|
+
}
|
|
596
|
+
},
|
|
597
|
+
}), 'workflow-canvas: sync command');
|
|
598
|
+
} catch (_e) {
|
|
599
|
+
/* command registry unavailable */
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
ctx.inject(['tools', 'subagents', 'sessions'], (scope) => {
|
|
604
|
+
try {
|
|
605
|
+
scope.effect(() => scope.tools.register({
|
|
606
|
+
name: 'canvas_generate',
|
|
607
|
+
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.',
|
|
608
|
+
parameters: {
|
|
609
|
+
type: 'object',
|
|
610
|
+
properties: {
|
|
611
|
+
task: { type: 'string', description: 'Overall task written into the entry Lead node.' },
|
|
612
|
+
nodes: {
|
|
613
|
+
type: 'array',
|
|
614
|
+
description: 'Nodes in any order. Give each an id or ref so edges can point at it.',
|
|
615
|
+
items: {
|
|
616
|
+
type: 'object',
|
|
617
|
+
properties: {
|
|
618
|
+
id: { type: 'string' },
|
|
619
|
+
ref: { type: 'string', description: 'Temporary handle for edges; the tool assigns the real id.' },
|
|
620
|
+
kind: { type: 'string', enum: ['agent', 'lead'] },
|
|
621
|
+
label: { type: 'string' },
|
|
622
|
+
role: { type: 'string' },
|
|
623
|
+
task: { type: 'string' },
|
|
624
|
+
provider: { type: 'string' },
|
|
625
|
+
model: { type: 'string' },
|
|
626
|
+
reasoning: { type: 'string' },
|
|
627
|
+
preset: { type: 'string' },
|
|
628
|
+
structured: { type: 'boolean' },
|
|
629
|
+
keepSession: { type: 'boolean' },
|
|
630
|
+
fallbackModel: { type: 'string' },
|
|
631
|
+
},
|
|
632
|
+
},
|
|
633
|
+
},
|
|
634
|
+
edges: {
|
|
635
|
+
type: 'array',
|
|
636
|
+
items: {
|
|
637
|
+
type: 'object',
|
|
638
|
+
properties: {
|
|
639
|
+
from: { type: 'string' },
|
|
640
|
+
to: { type: 'string' },
|
|
641
|
+
type: { type: 'string', enum: ['prompt', 'structured', 'session-ref'] },
|
|
642
|
+
},
|
|
643
|
+
required: ['from', 'to'],
|
|
644
|
+
},
|
|
645
|
+
},
|
|
646
|
+
},
|
|
647
|
+
required: ['nodes'],
|
|
648
|
+
},
|
|
649
|
+
output: {
|
|
650
|
+
schema: {
|
|
651
|
+
type: 'object',
|
|
652
|
+
properties: {
|
|
653
|
+
canvas: { type: 'object' },
|
|
654
|
+
delivered: { type: 'boolean' },
|
|
655
|
+
error: { type: 'string' },
|
|
656
|
+
},
|
|
657
|
+
},
|
|
658
|
+
render: (_args, value) => {
|
|
659
|
+
const v = value || {};
|
|
660
|
+
if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
|
|
661
|
+
const canvas = v.canvas || {};
|
|
662
|
+
const nodes = Array.isArray(canvas.nodes) ? canvas.nodes : [];
|
|
663
|
+
const edges = Array.isArray(canvas.edges) ? canvas.edges : [];
|
|
664
|
+
const lines = nodes.map((n) => '- ' + (n.kind === 'lead' ? '〔Lead〕' : '') + n.label
|
|
665
|
+
+ (n.role ? ':' + n.role : ''));
|
|
666
|
+
return [{
|
|
667
|
+
type: 'text',
|
|
668
|
+
text: '已生成画布:' + nodes.length + ' 个节点、' + edges.length + ' 条连线\n'
|
|
669
|
+
+ lines.join('\n')
|
|
670
|
+
+ (v.delivered
|
|
671
|
+
? '\n\n画布已经自动同步到右侧画布,直接看即可(若没出现,点画布上的「◎ 定位」)。'
|
|
672
|
+
: '\n\n**下一步**:点画布工具栏的「⇩ 导入」,它会把这段画布数据装进当前画布。')
|
|
673
|
+
+ '\n```json canvas\n'
|
|
674
|
+
+ JSON.stringify(canvas) + '\n```',
|
|
675
|
+
}];
|
|
676
|
+
},
|
|
677
|
+
},
|
|
678
|
+
execute: (args, exec) => {
|
|
679
|
+
try {
|
|
680
|
+
const result = normalizeCanvas(args || {});
|
|
681
|
+
if (result.error) return { error: result.error };
|
|
682
|
+
const canvas = { nodes: result.nodes, edges: result.edges };
|
|
683
|
+
const agent = exec && exec.agent;
|
|
684
|
+
const sid = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
685
|
+
const delivered = sid ? publishCanvas(scope, sid, canvas) : false;
|
|
686
|
+
if (sid) {
|
|
687
|
+
const previous = canvasBySession.get(sid);
|
|
688
|
+
canvasBySession.set(sid, {
|
|
689
|
+
enabled: previous ? previous.enabled : true,
|
|
690
|
+
plan: {
|
|
691
|
+
task: String((args && args.task) || ''),
|
|
692
|
+
nodes: withoutEntry(canvas.nodes),
|
|
693
|
+
edges: canvas.edges,
|
|
694
|
+
},
|
|
695
|
+
});
|
|
696
|
+
runBySession.delete(sid);
|
|
697
|
+
saveStore();
|
|
698
|
+
}
|
|
699
|
+
return { canvas, delivered };
|
|
700
|
+
} catch (error) {
|
|
701
|
+
return { error: String((error && error.message) || error) };
|
|
702
|
+
}
|
|
703
|
+
},
|
|
704
|
+
}), 'workflow-canvas: generate tool');
|
|
705
|
+
} catch (_e) {
|
|
706
|
+
/* tool registry unavailable */
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
|
|
710
|
+
ctx.inject(['tools', 'subagents', 'sessions'], (scope) => {
|
|
711
|
+
try {
|
|
712
|
+
scope.effect(() => scope.tools.register({
|
|
713
|
+
name: 'canvas_patch',
|
|
714
|
+
description: 'Edit the current canvas in place: update the given nodes by id, add new ones, remove some, and add or remove links. Everything else, including node positions, is left alone. Prefer this over canvas_generate for edits; load the `workflow-canvas` skill first if unsure.',
|
|
715
|
+
parameters: {
|
|
716
|
+
type: 'object',
|
|
717
|
+
properties: {
|
|
718
|
+
nodes: { type: 'array', description: 'Nodes to update or add. Existing ids are merged field by field.', items: { type: 'object' } },
|
|
719
|
+
removeNodes: { type: 'array', description: 'Node ids to delete.', items: { type: 'string' } },
|
|
720
|
+
edges: { type: 'array', description: 'Links to add.', items: { type: 'object' } },
|
|
721
|
+
removeEdges: { type: 'array', description: 'Links to delete, matched by from/to.', items: { type: 'object' } },
|
|
722
|
+
},
|
|
723
|
+
},
|
|
724
|
+
output: {
|
|
725
|
+
schema: {
|
|
726
|
+
type: 'object',
|
|
727
|
+
properties: {
|
|
728
|
+
delivered: { type: 'boolean' },
|
|
729
|
+
summary: { type: 'string' },
|
|
730
|
+
error: { type: 'string' },
|
|
731
|
+
},
|
|
732
|
+
},
|
|
733
|
+
render: (_a, value) => {
|
|
734
|
+
const v = value || {};
|
|
735
|
+
if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
|
|
736
|
+
return [{ type: 'text', text: v.summary + (v.delivered ? '(画布已就地更新)' : '(画布不可达,未应用)') }];
|
|
737
|
+
},
|
|
738
|
+
},
|
|
739
|
+
execute: (args, exec) => {
|
|
740
|
+
try {
|
|
741
|
+
const agent = exec && exec.agent;
|
|
742
|
+
const sid = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
743
|
+
const payload = sid ? canvasBySession.get(sid) : undefined;
|
|
744
|
+
if (!payload || !payload.plan) return { error: '当前会话还没有画布数据,先用「启用」同步一次。' };
|
|
745
|
+
const plan = payload.plan;
|
|
746
|
+
const nodes = withoutEntry(plan.nodes).slice();
|
|
747
|
+
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
748
|
+
const ALLOWED = ['label', 'role', 'provider', 'model', 'reasoning', 'preset', 'keepSession', 'structured', 'fallbackModel', 'fallbackProvider'];
|
|
749
|
+
const touched = [];
|
|
750
|
+
for (const patch of args && Array.isArray(args.nodes) ? args.nodes : []) {
|
|
751
|
+
// 'lead' is the reserved entry node and is never edited here.
|
|
752
|
+
if (!patch || typeof patch.id !== 'string' || patch.id === 'lead') continue;
|
|
753
|
+
const existing = byId.get(patch.id);
|
|
754
|
+
if (existing) {
|
|
755
|
+
for (const key of ALLOWED) {
|
|
756
|
+
if (patch[key] !== undefined) existing[key] = patch[key];
|
|
757
|
+
}
|
|
758
|
+
touched.push(patch.id);
|
|
759
|
+
} else {
|
|
760
|
+
const created = {
|
|
761
|
+
id: patch.id,
|
|
762
|
+
kind: patch.kind === 'lead' ? 'lead' : 'agent',
|
|
763
|
+
label: patch.label || patch.id,
|
|
764
|
+
role: '', provider: '', model: '', reasoning: '', preset: 'standard',
|
|
765
|
+
structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
|
|
766
|
+
};
|
|
767
|
+
for (const key of ALLOWED) {
|
|
768
|
+
if (patch[key] !== undefined) created[key] = patch[key];
|
|
769
|
+
}
|
|
770
|
+
created.preset = created.preset === 'minimal' ? 'minimal' : 'standard';
|
|
771
|
+
nodes.push(created);
|
|
772
|
+
byId.set(created.id, created);
|
|
773
|
+
touched.push(created.id);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
const removed = new Set(Array.isArray(args && args.removeNodes) ? args.removeNodes : []);
|
|
777
|
+
const keptNodes = nodes.filter((n) => !removed.has(n.id));
|
|
778
|
+
let edges = Array.isArray(plan.edges) ? plan.edges.slice() : [];
|
|
779
|
+
const dropEdges = new Set((Array.isArray(args && args.removeEdges) ? args.removeEdges : [])
|
|
780
|
+
.map((e) => String(e.from) + '>' + String(e.to)));
|
|
781
|
+
edges = edges.filter((e) => !dropEdges.has(e.from + '>' + e.to)
|
|
782
|
+
&& !removed.has(e.from) && !removed.has(e.to));
|
|
783
|
+
for (const edge of Array.isArray(args && args.edges) ? args.edges : []) {
|
|
784
|
+
if (!edge || !byId.has(edge.from) || !byId.has(edge.to)) continue;
|
|
785
|
+
if (removed.has(edge.from) || removed.has(edge.to)) continue;
|
|
786
|
+
const type = ['prompt', 'structured', 'session-ref'].includes(edge.type) ? edge.type : 'prompt';
|
|
787
|
+
if (edges.some((e) => e.from === edge.from && e.to === edge.to && e.type === type)) continue;
|
|
788
|
+
edges.push({ from: edge.from, to: edge.to, type });
|
|
789
|
+
}
|
|
790
|
+
const nextPlan = { ...plan, nodes: keptNodes, edges };
|
|
791
|
+
canvasBySession.set(sid, { enabled: payload.enabled, plan: nextPlan });
|
|
792
|
+
runBySession.delete(sid);
|
|
793
|
+
saveStore();
|
|
794
|
+
const delivered = publishCanvas(scope, sid, { mode: 'merge', nodes: keptNodes, edges, removeNodes: Array.from(removed) });
|
|
795
|
+
const summary = '已更新 ' + touched.length + ' 个节点、删除 ' + removed.size + ' 个、连线 ' + edges.length + ' 条';
|
|
796
|
+
return { delivered, summary };
|
|
797
|
+
} catch (error) {
|
|
798
|
+
return { error: String((error && error.message) || error) };
|
|
799
|
+
}
|
|
800
|
+
},
|
|
801
|
+
}), 'workflow-canvas: patch tool');
|
|
802
|
+
} catch (_e) {
|
|
803
|
+
/* tool registry unavailable */
|
|
804
|
+
}
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
ctx.inject(['tools', 'subagents'], (scope) => {
|
|
808
|
+
try {
|
|
809
|
+
scope.effect(() => scope.tools.register({
|
|
810
|
+
name: 'canvas_workflow',
|
|
811
|
+
description: 'Run the workflow canvas of the current session. Executes subagent nodes in parallel waves; when a Lead node is reached it returns status "need-lead" and expects a follow-up call carrying leadResult. Load the `workflow-canvas` skill first when you are unsure how the canvas works.',
|
|
812
|
+
parameters: {
|
|
813
|
+
type: 'object',
|
|
814
|
+
properties: {
|
|
815
|
+
leadResult: { type: 'string', description: 'Your own output for the Lead step that was just requested.' },
|
|
816
|
+
},
|
|
817
|
+
additionalProperties: false,
|
|
818
|
+
},
|
|
819
|
+
output: {
|
|
820
|
+
schema: {
|
|
821
|
+
type: 'object',
|
|
822
|
+
properties: {
|
|
823
|
+
status: { type: 'string' },
|
|
824
|
+
node: { type: 'object' },
|
|
825
|
+
results: { type: 'object' },
|
|
826
|
+
labels: { type: 'object' },
|
|
827
|
+
sessions: { type: 'array' },
|
|
828
|
+
skipped: { type: 'array' },
|
|
829
|
+
hint: { type: 'string' },
|
|
830
|
+
error: { type: 'string' },
|
|
831
|
+
},
|
|
832
|
+
},
|
|
833
|
+
render: (_args, value) => {
|
|
834
|
+
const v = value || {};
|
|
835
|
+
if (typeof v.error === 'string') return [{ type: 'text', text: v.error }];
|
|
836
|
+
const results = v.results || {};
|
|
837
|
+
const labels = v.labels || {};
|
|
838
|
+
const blocks = Object.keys(results).map((id) => {
|
|
839
|
+
const text = typeof results[id] === 'string' ? results[id] : JSON.stringify(results[id]);
|
|
840
|
+
return '## ' + (labels[id] || id) + '\n' + text;
|
|
841
|
+
});
|
|
842
|
+
const body = blocks.length ? blocks.join('\n\n') : '(暂无上游结果)';
|
|
843
|
+
if (v.status === 'need-lead') {
|
|
844
|
+
const n = v.node || {};
|
|
845
|
+
const handed = Array.isArray(v.sessions) ? v.sessions.filter((s) => s && s.childId) : [];
|
|
846
|
+
const handover = handed.length
|
|
847
|
+
? '\n\n可用会话(session 连线):' + handed.map((s) => s.label + ' → ' + s.childId).join(';')
|
|
848
|
+
+ '\n需要追问时,直接给对应子代理发消息即可,它们仍在上游会话里。'
|
|
849
|
+
: '';
|
|
850
|
+
return [{
|
|
851
|
+
type: 'text',
|
|
852
|
+
text: '需要你(Lead)完成「' + n.label + '」:' + n.role
|
|
853
|
+
+ '\n需要用到:' + ((n.needs && n.needs.length) ? n.needs.join('、') : '(无上游)')
|
|
854
|
+
+ '\n\n已完成节点的结果:\n' + body
|
|
855
|
+
+ handover
|
|
856
|
+
+ '\n\n' + (v.hint || ''),
|
|
857
|
+
}];
|
|
858
|
+
}
|
|
859
|
+
if (v.status === 'done') {
|
|
860
|
+
const skip = Array.isArray(v.skipped) && v.skipped.length
|
|
861
|
+
? '\n\n已跳过(未连线):' + v.skipped.join('、')
|
|
862
|
+
: '';
|
|
863
|
+
return [{ type: 'text', text: '画布执行完成。\n\n' + body + skip }];
|
|
864
|
+
}
|
|
865
|
+
return [{ type: 'text', text: JSON.stringify(v) }];
|
|
866
|
+
},
|
|
867
|
+
},
|
|
868
|
+
execute: (args, exec) => runPlan(scope, args || {}, exec),
|
|
869
|
+
}), 'workflow-canvas: run tool');
|
|
870
|
+
} catch (_e) {
|
|
871
|
+
/* tool registry unavailable */
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
} catch (_e) {
|
|
875
|
+
/* never fail the plugin load because of the bridge */
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
export {
|
|
880
|
+
orderNodes,
|
|
881
|
+
upstreamOf,
|
|
882
|
+
downstreamLabels,
|
|
883
|
+
briefFor,
|
|
884
|
+
withoutEntry,
|
|
885
|
+
normalizeCanvas,
|
|
886
|
+
runPlan,
|
|
887
|
+
executePlan,
|
|
888
|
+
};
|