dsh-workflow-canvas 1.6.0 → 1.6.1

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
@@ -16,17 +16,76 @@
16
16
  * Everything is defensive: a missing service disables one piece instead of
17
17
  * failing the plugin load.
18
18
  */
19
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
19
+ import { readFileSync } from 'node:fs';
20
20
  import { join } from 'node:path';
21
21
  import { fileURLToPath } from 'node:url';
22
+ import {
23
+ MAX_LOOP_ITERATIONS,
24
+ DEFAULT_LOOP_ITERATIONS,
25
+ MAX_GLOBAL_LOOPS,
26
+ withoutEntry,
27
+ parsePayload,
28
+ normalizeMaxIterations,
29
+ isLoopEdge,
30
+ forwardEdgesOf,
31
+ loopMemberIds,
32
+ orderNodes,
33
+ upstreamOf,
34
+ downstreamLabels,
35
+ normalizeKind,
36
+ normalizeRefs,
37
+ normalizeBranch,
38
+ normalizeBranches,
39
+ conditionBranches,
40
+ edgeKey,
41
+ parseStrictConditionJson,
42
+ parseConditionDecision,
43
+ clipUpstreamOutput,
44
+ briefFor,
45
+ extractResultError,
46
+ textOf,
47
+ failed,
48
+ isEmptyOutput,
49
+ buildLoopWarmPrompt,
50
+ formatModelLabel,
51
+ isPermissionFailure,
52
+ isTransientFailure,
53
+ reachableFrom,
54
+ inactiveNodeSets,
55
+ validateLoopEdges,
56
+ analyzeCanvasWarnings,
57
+ normalizeCanvas,
58
+ applyPatch,
59
+ } from './lib/graph.js';
60
+ import {
61
+ MAX_STORED_SESSIONS,
62
+ MAX_LAST_RUNS,
63
+ MAX_CHILD_SLOTS,
64
+ safeSessionFileBase,
65
+ writeFileAtomic,
66
+ pruneMapLRU,
67
+ touchMapLRU,
68
+ cleanupStaleCanvasFiles,
69
+ buildRunSummarySnapshot,
70
+ } from './lib/telemetry.js';
22
71
 
23
- /** Latest canvas payload per Session id. */
72
+ /** Latest canvas payload per Session id (LRU-bounded). */
24
73
  const canvasBySession = new Map();
74
+ /** Read a session canvas and refresh its LRU recency so active old sessions are never evicted. */
75
+ function getCanvasLRU(sid) {
76
+ if (!sid) return undefined;
77
+ const key = String(sid);
78
+ if (!canvasBySession.has(key)) return undefined;
79
+ const val = canvasBySession.get(key);
80
+ canvasBySession.delete(key);
81
+ canvasBySession.set(key, val);
82
+ return val;
83
+ }
25
84
  /** In-flight run progress per Session id. */
26
85
  const runBySession = new Map();
27
86
  /** Live AbortController & active child session ids per executing Session id. */
28
87
  const activeRunBySession = new Map();
29
- /** Snapshot of the last completed/halted run per Session id (enables partial retry). */
88
+ /** Snapshot of the last completed/halted run per Session id (LRU-bounded; enables partial retry). */
30
89
  const lastRunBySession = new Map();
31
90
  /**
32
91
  * Two separate maps by design:
@@ -37,6 +96,8 @@ const lastRunBySession = new Map();
37
96
  */
38
97
  const childByNode = new Map();
39
98
  const liveChild = new Map();
99
+ let lastSavedStorePath = '';
100
+ let lastSavedStoreJson = '';
40
101
 
41
102
  function storePath() {
42
103
  const home = process.env.DSH_PROFILE_DIR;
@@ -51,11 +112,17 @@ function loadStore() {
51
112
  const raw = readFileSync(path, 'utf8');
52
113
  const doc = JSON.parse(raw);
53
114
  if (doc && doc.canvas && typeof doc.canvas === 'object') {
54
- for (const [sid, payload] of Object.entries(doc.canvas)) canvasBySession.set(sid, payload);
115
+ for (const [sid, payload] of Object.entries(doc.canvas)) {
116
+ touchMapLRU(canvasBySession, sid, payload, MAX_STORED_SESSIONS);
117
+ }
55
118
  }
56
119
  if (doc && doc.children && typeof doc.children === 'object') {
57
- for (const [node, child] of Object.entries(doc.children)) childByNode.set(node, child);
120
+ for (const [node, child] of Object.entries(doc.children)) {
121
+ touchMapLRU(childByNode, node, child, MAX_CHILD_SLOTS);
122
+ }
58
123
  }
124
+ lastSavedStorePath = path;
125
+ lastSavedStoreJson = raw;
59
126
  } catch (_e) {
60
127
  /* no store yet, or unreadable: start clean */
61
128
  }
@@ -65,454 +132,41 @@ function saveStore() {
65
132
  const path = storePath();
66
133
  if (!path) return;
67
134
  try {
68
- mkdirSync(join(path, '..'), { recursive: true });
69
- const tmp = path + '.tmp';
70
- writeFileSync(tmp, JSON.stringify({
135
+ pruneMapLRU(canvasBySession, MAX_STORED_SESSIONS);
136
+ pruneMapLRU(childByNode, MAX_CHILD_SLOTS);
137
+ const json = JSON.stringify({
71
138
  canvas: Object.fromEntries(canvasBySession),
72
139
  children: Object.fromEntries(childByNode),
73
- }), 'utf8');
74
- renameSync(tmp, path);
140
+ });
141
+ if (path === lastSavedStorePath && json === lastSavedStoreJson) return;
142
+ writeFileAtomic(path, json);
143
+ lastSavedStorePath = path;
144
+ lastSavedStoreJson = json;
75
145
  } catch (_e) {
76
146
  /* persistence is best-effort */
77
147
  }
78
148
  }
79
149
 
80
- /** The entry Lead is a task container, never a runnable node. */
81
- function withoutEntry(nodes) {
82
- return (nodes || []).filter((n) => n.id !== 'lead');
83
- }
84
-
85
- function parsePayload(rawInput) {
86
- const text = String(rawInput || '').trim();
87
- if (!text) return { enabled: false };
88
- try {
89
- return JSON.parse(decodeURIComponent(text));
90
- } catch (_e) {
91
- return { enabled: false, error: '画布数据解析失败' };
92
- }
93
- }
94
-
95
- const MAX_LOOP_ITERATIONS = 10;
96
- const DEFAULT_LOOP_ITERATIONS = 3;
97
- const MAX_GLOBAL_LOOPS = 20;
98
-
99
- function normalizeMaxIterations(val) {
100
- const n = Number(val);
101
- if (!Number.isFinite(n)) return DEFAULT_LOOP_ITERATIONS;
102
- return Math.max(1, Math.min(MAX_LOOP_ITERATIONS, Math.floor(n)));
103
- }
104
-
105
- function isLoopEdge(e) {
106
- return Boolean(e && e.loop === true);
107
- }
108
-
109
- function forwardEdgesOf(edges) {
110
- return (Array.isArray(edges) ? edges : []).filter((e) => e && !e.loop);
111
- }
112
-
113
- /**
114
- * Compute the set of node ids strictly inside a controlled loop edge (from target -> ... -> source)
115
- * over forward edges: `descendants(loopEdge.to) ∩ ancestors(loopEdge.from)` (inclusive).
116
- * Returns an empty Set if `loopEdge.from` is not reachable from `loopEdge.to` over forward edges.
117
- */
118
- function loopMemberIds(nodes, edges, loopEdge) {
119
- if (!loopEdge || !loopEdge.from || !loopEdge.to || loopEdge.to === 'lead') return new Set();
120
- const fwd = new Map();
121
- const rev = new Map();
122
- for (const e of forwardEdgesOf(edges)) {
123
- if (!e.from || !e.to) continue;
124
- if (!fwd.has(e.from)) fwd.set(e.from, []);
125
- fwd.get(e.from).push(e.to);
126
- if (!rev.has(e.to)) rev.set(e.to, []);
127
- rev.get(e.to).push(e.from);
128
- }
129
- const desc = new Set([loopEdge.to]);
130
- const q1 = [loopEdge.to];
131
- for (let i = 0; i < q1.length; i += 1) {
132
- for (const next of fwd.get(q1[i]) || []) {
133
- if (!desc.has(next)) { desc.add(next); q1.push(next); }
134
- }
135
- }
136
- if (!desc.has(loopEdge.from)) return new Set();
137
- const anc = new Set([loopEdge.from]);
138
- const q2 = [loopEdge.from];
139
- for (let i = 0; i < q2.length; i += 1) {
140
- for (const prev of rev.get(q2[i]) || []) {
141
- if (!anc.has(prev)) { anc.add(prev); q2.push(prev); }
142
- }
143
- }
144
- const members = new Set();
145
- for (const id of desc) {
146
- if (anc.has(id)) members.add(id);
147
- }
148
- return members;
149
- }
150
-
151
- /** Kahn topological order over every plan node (ignoring controlled loop back-edges). */
152
- function orderNodes(plan) {
153
- const nodes = plan.nodes || [];
154
- const edges = forwardEdgesOf(plan.edges || []);
155
- const byId = new Map(nodes.map((n) => [n.id, n]));
156
- const indeg = new Map(nodes.map((n) => [n.id, 0]));
157
- const adj = new Map(nodes.map((n) => [n.id, []]));
158
- for (const e of edges) {
159
- if (e.from === 'lead') continue;
160
- if (!byId.has(e.from) || !byId.has(e.to)) continue;
161
- indeg.set(e.to, indeg.get(e.to) + 1);
162
- adj.get(e.from).push(e.to);
163
- }
164
- const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
165
- const out = [];
166
- for (let i = 0; i < queue.length; i += 1) {
167
- const id = queue[i];
168
- out.push(byId.get(id));
169
- for (const next of adj.get(id)) {
170
- indeg.set(next, indeg.get(next) - 1);
171
- if (indeg.get(next) === 0) queue.push(next);
172
- }
173
- }
174
- return out.length === nodes.length ? out : null;
175
- }
176
-
177
- function upstreamOf(plan, node) {
178
- const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
179
- return forwardEdgesOf(plan.edges || [])
180
- .filter((e) => e.to === node.id)
181
- .map((e) => ({ edge: e, from: byId.get(e.from) }))
182
- .filter((x) => x.from);
183
- }
184
-
185
- function downstreamLabels(plan, node) {
186
- const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
187
- return forwardEdgesOf(plan.edges || [])
188
- .filter((e) => e.from === node.id)
189
- .map((e) => (byId.get(e.to) || {}).label)
190
- .filter(Boolean);
191
- }
192
-
193
- function normalizeKind(rawKind) {
194
- if (rawKind === 'lead') return 'lead';
195
- if (rawKind === 'condition') return 'condition';
196
- return 'agent';
197
- }
198
-
199
- /**
200
- * Normalize a reference list (paths, URLs, or rules attached to a node or entry Lead).
201
- * Accepts string arrays or `{ text | path }` objects; capped at 16 unique non-empty items.
202
- */
203
- function normalizeRefs(rawRefs) {
204
- if (!Array.isArray(rawRefs) || !rawRefs.length) return null;
205
- const out = [];
206
- const seen = new Set();
207
- for (const raw of rawRefs) {
208
- if (out.length >= 16) break;
209
- let s = '';
210
- if (typeof raw === 'string') s = raw.trim();
211
- else if (raw && typeof raw === 'object') {
212
- s = String(raw.text !== undefined ? raw.text : (raw.path !== undefined ? raw.path : '')).trim();
213
- }
214
- if (!s || seen.has(s)) continue;
215
- seen.add(s);
216
- out.push(s);
217
- }
218
- return out.length ? out : null;
219
- }
220
-
221
- function normalizeBranch(rawBranch) {
222
- if (rawBranch === true) return 'true';
223
- if (rawBranch === false) return 'false';
224
- if (typeof rawBranch !== 'string') return '';
225
- return rawBranch.trim();
226
- }
227
-
228
- const DEFAULT_BINARY_BRANCHES = [
229
- { id: 'true', label: '是' },
230
- { id: 'false', label: '否' },
231
- ];
232
-
233
- /**
234
- * Normalize a condition node's branch list (2–5 entries).
235
- * Accepts either string arrays (e.g. `['通过', '小修', '重做']`) or `{ id, label }` objects.
236
- * Returns `null` when the node uses the default binary `true`/`false` pair.
237
- */
238
- function normalizeBranches(rawBranches) {
239
- if (!Array.isArray(rawBranches) || rawBranches.length < 2) return null;
240
- const out = [];
241
- const used = new Set();
242
- for (let i = 0; i < Math.min(16, rawBranches.length); i += 1) {
243
- const item = rawBranches[i];
244
- let id = '';
245
- let label = '';
246
- if (typeof item === 'string') {
247
- label = item.trim();
248
- id = label;
249
- } else if (item && typeof item === 'object') {
250
- id = typeof item.id === 'string' ? item.id.trim() : '';
251
- label = typeof item.label === 'string' ? item.label.trim() : '';
252
- if (!id) id = label;
253
- if (!label) label = id;
254
- }
255
- if (!id) id = 'case_' + (i + 1);
256
- if (!label) label = '分支 ' + (i + 1);
257
- let uniq = id;
258
- let suffix = 2;
259
- while (used.has(uniq)) { uniq = id + '_' + suffix; suffix += 1; }
260
- used.add(uniq);
261
- out.push({ id: uniq, label });
262
- }
263
- return out.length >= 2 ? out : null;
264
- }
265
-
266
- function conditionBranches(node) {
267
- const custom = normalizeBranches(node && node.branches);
268
- const multiMatch = Boolean(node && node.multiMatch);
269
- if (custom) return { branches: custom, isDefaultBinary: false, multiMatch };
270
- return { branches: DEFAULT_BINARY_BRANCHES, isDefaultBinary: !multiMatch, multiMatch };
271
- }
272
-
273
- function edgeKey(e) {
274
- return String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
275
- }
276
-
277
- /**
278
- * Parse a condition node's structured or text output into
279
- * `{ branches, branchLabels, branch, branchLabel, pass, reason }`.
280
- * Supports:
281
- * - default binary `{ pass: boolean }`
282
- * - single-match `switch/case` (`{ branches: [id] }` or `{ branch: id }`, or `[]` when none match)
283
- * - multi-match parallel fan-out (`multiMatch: true`, `{ branches: [id1, id2, ...] }` or `[]`)
284
- */
285
- function parseConditionDecision(result, fallbackText, nodeOrBranches) {
286
- const { branches, isDefaultBinary, multiMatch } = Array.isArray(nodeOrBranches)
287
- ? { branches: normalizeBranches(nodeOrBranches) || DEFAULT_BINARY_BRANCHES, isDefaultBinary: !normalizeBranches(nodeOrBranches), multiMatch: false }
288
- : conditionBranches(nodeOrBranches);
289
-
290
- const resolveByToken = (token) => {
291
- const t = String(token || '').trim();
292
- if (!t) return null;
293
- const exactId = branches.find((b) => b.id === t);
294
- if (exactId) return exactId;
295
- const exactLabel = branches.find((b) => b.label === t);
296
- if (exactLabel) return exactLabel;
297
- const lower = t.toLowerCase();
298
- const ci = branches.find((b) => b.id.toLowerCase() === lower || b.label.toLowerCase() === lower);
299
- return ci || null;
300
- };
301
-
302
- const makeDecision = (pickedList, reason) => {
303
- const seen = new Set();
304
- const uniq = [];
305
- for (const item of pickedList) {
306
- if (!item || seen.has(item.id)) continue;
307
- seen.add(item.id);
308
- uniq.push(item);
309
- }
310
- const finalList = multiMatch ? uniq : uniq.slice(0, 1);
311
- const first = finalList[0] || null;
312
- return {
313
- branches: finalList.map((b) => b.id),
314
- branchLabels: finalList.map((b) => b.label),
315
- branch: first ? first.id : '',
316
- branchLabel: first ? first.label : '',
317
- pass: isDefaultBinary ? Boolean(first && first.id === 'true') : finalList.length > 0,
318
- reason: String(reason || ''),
319
- };
320
- };
321
-
322
- const tryObj = (obj) => {
323
- if (!obj || typeof obj !== 'object') return null;
324
- if (Array.isArray(obj.branches)) {
325
- const hits = obj.branches.map(resolveByToken).filter(Boolean);
326
- return makeDecision(hits, obj.reason);
327
- }
328
- if (typeof obj.branch === 'string') {
329
- const trimmed = obj.branch.trim();
330
- if (!trimmed || /^(none|null|无|都不满足|未命中)$/i.test(trimmed)) {
331
- return makeDecision([], obj.reason);
150
+ /** Abort-aware backoff delay for safe read-only transient retries. */
151
+ function delayWithSignal(ms, signal) {
152
+ const wait = Number.isFinite(ms) ? Math.max(0, ms) : 0;
153
+ if (wait <= 0 || (signal && signal.aborted)) return Promise.resolve();
154
+ return new Promise((resolve) => {
155
+ let done = false;
156
+ const finish = () => {
157
+ if (done) return;
158
+ done = true;
159
+ clearTimeout(timer);
160
+ if (signal && typeof signal.removeEventListener === 'function') {
161
+ try { signal.removeEventListener('abort', finish); } catch (_e) { /* ignore */ }
332
162
  }
333
- const hit = resolveByToken(trimmed);
334
- if (hit) return makeDecision([hit], obj.reason);
335
- }
336
- if (typeof obj.pass === 'boolean') {
337
- const picked = obj.pass ? branches[0] : branches[branches.length - 1];
338
- return makeDecision([picked], obj.reason);
339
- }
340
- return null;
341
- };
342
-
343
- const fromStructured = tryObj(result && result.structured);
344
- if (fromStructured) return fromStructured;
345
-
346
- const raw = String(fallbackText || '').trim();
347
- const start = raw.indexOf('{');
348
- const end = raw.lastIndexOf('}');
349
- if (start !== -1 && end > start) {
350
- try {
351
- const fromJson = tryObj(JSON.parse(raw.slice(start, end + 1)));
352
- if (fromJson) return fromJson;
353
- } catch (_e) { /* fall through */ }
354
- }
355
-
356
- if (isDefaultBinary) {
357
- if (/^(true|yes|pass|通过|是)\b/i.test(raw)) return makeDecision([branches[0]], raw.slice(0, 200));
358
- return makeDecision([branches[1]], raw.slice(0, 200) || '未能解析布尔判断,默认走「否」分支');
359
- }
360
-
361
- // Multi-way text fallback: collect matching branch ids/labels; return empty [] if none match.
362
- const lowerRaw = raw.toLowerCase();
363
- const matched = [];
364
- for (const b of branches) {
365
- if (lowerRaw.includes(b.id.toLowerCase()) || lowerRaw.includes(b.label.toLowerCase())) {
366
- matched.push(b);
367
- if (!multiMatch) break;
368
- }
369
- }
370
- return makeDecision(matched, raw.slice(0, 200) || (matched.length ? '' : '未命中任何分支,已跳过后续分支'));
371
- }
372
-
373
- function briefFor(plan, node, results, failedMap, prunedSet, loopCtx) {
374
- const ups = upstreamOf(plan, node).filter((u) => !(prunedSet && prunedSet.has(u.from.id)));
375
- const downs = downstreamLabels(plan, node);
376
- const head = [];
377
- if (node.kind === 'condition') {
378
- const outEdges = (plan.edges || []).filter((e) => e.from === node.id);
379
- const byId = new Map((plan.nodes || []).map((n) => [n.id, n]));
380
- const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
381
- const fmtTarget = (e) => {
382
- const lbl = (byId.get(e.to) || {}).label || e.to;
383
- return e.loop ? (lbl + '(↺ 回环重做,最多 ' + normalizeMaxIterations(e.maxIterations) + ' 次)') : lbl;
163
+ resolve();
384
164
  };
385
- head.push('【工作流条件判断节点】你负责判断当前工作流接下来走哪条分支(「' + node.label + '」)。');
386
- head.push('【总任务】' + plan.task);
387
- if (isDefaultBinary) {
388
- const yesTargets = outEdges.filter((e) => (normalizeBranch(e.branch) || 'true') === 'true').map(fmtTarget);
389
- const noTargets = outEdges.filter((e) => normalizeBranch(e.branch) === 'false').map(fmtTarget);
390
- head.push('【判断条件】' + (node.role || '判断上游步骤是否执行成功并达到预期;成功返回 true,失败或未达标返回 false。'));
391
- head.push('【分支去向】pass=true(是)→ ' + (yesTargets.join('、') || '(无)') + ';pass=false(否)→ ' + (noTargets.join('、') || '(无)'));
392
- head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"pass": true/false, "reason": "一句话理由"}。');
393
- } else {
394
- const branchLines = branches.map((b, idx) => {
395
- const targets = outEdges
396
- .filter((e) => {
397
- const eb = normalizeBranch(e.branch);
398
- return eb ? eb === b.id : idx === 0;
399
- })
400
- .map(fmtTarget);
401
- const tag = b.label === b.id ? '"' + b.id + '"' : '"' + b.id + '"(' + b.label + ')';
402
- return '- ' + tag + ' → ' + (targets.join('、') || '(无下游)');
403
- });
404
- head.push('【判断规则】' + (node.role || (multiMatch
405
- ? '根据上游结果选出所有满足条件的分支(可多选并行);若均不满足返回空数组。'
406
- : '根据上游结果选出最匹配的一条分支;若均不满足返回空数组(如有「其他/兜底」分支则选它)。')));
407
- head.push('【匹配模式】' + (multiMatch
408
- ? '多选并行(可返回 0 条、1 条或多条分支 id)'
409
- : '单选分流(最多返回 1 条最匹配的分支 id;均不满足返回空数组 [])'));
410
- head.push('【可选分支】\n' + branchLines.join('\n'));
411
- head.push('【要求】严格依据上游实际输出(含成功/失败状态与【未完全交付】标记)做出客观判断,只返回 JSON 对象 {"branches": ["<分支id>"], "reason": "一句话理由"};若没有任何分支满足,返回 {"branches": [], "reason": "..."}。');
165
+ const timer = setTimeout(finish, wait);
166
+ if (signal && typeof signal.addEventListener === 'function') {
167
+ signal.addEventListener('abort', finish, { once: true });
412
168
  }
413
- } else {
414
- head.push('【工作流节点】你在一个多步工作流里负责「' + node.label + '」这一步(子代理)。');
415
- if (ups.length === 0) head.push('【总任务】' + plan.task);
416
- head.push('【职责】' + (node.role || node.label));
417
- if (ups.length) head.push('【上游】' + ups.map((u) => u.from.label).join('、') + ' 已交付结果给你(见下文)。');
418
- head.push('【下游】' + (downs.length ? downs.join('、') + ' 会使用你的输出。' : '你是终点,结果会直接交付给用户。'));
419
- head.push('【要求】只完成你这一步;最终回复只输出简洁、可直接被下游或 Lead 消费的交付报告(结论、改动清单、关键接口/路径),不要包含思考独白、过程叙述或对其他并行节点的评价。若因环境或权限受限未能生成预期产物,必须在开头显式标注「【未完全交付】」并列出缺失项,不得把仅写脚本汇报为已完成。');
420
- }
421
- const mergedRefs = [];
422
- const seenRefs = new Set();
423
- for (const r of (normalizeRefs(plan && plan.refs) || []).concat(normalizeRefs(node && node.refs) || [])) {
424
- if (!seenRefs.has(r)) { seenRefs.add(r); mergedRefs.push(r); }
425
- }
426
- if (mergedRefs.length) {
427
- head.push('【参考资料 / 约束】\n' + mergedRefs.map((r) => '- ' + r).join('\n'));
428
- }
429
- if (loopCtx && loopCtx.feedback) {
430
- const fb = loopCtx.feedback;
431
- const lines = [
432
- '【第 ' + fb.retry + '/' + fb.max + ' 次回环修正反馈】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请针对以下问题修正后输出最新结果:',
433
- '- 打回理由:' + (fb.reason || '未达预期'),
434
- ];
435
- if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
436
- head.push(lines.join('\n'));
437
- }
438
- let text = head.join('\n') + '\n';
439
- for (const u of ups) {
440
- const value = results[u.from.id];
441
- const type = u.edge.type || 'prompt';
442
- const body = typeof value === 'string' ? value : '(没有结果)';
443
- const failInfo = failedMap && failedMap[u.from.id];
444
- const warn = failInfo
445
- ? '【警告:该上游节点执行失败(' + (failInfo.reason || 'unknown') + '),请勿将其报错当作正常结论,必要时说明受阻情况】\n'
446
- : '';
447
- if (type === 'structured') {
448
- text += '\n## 来自【' + u.from.label + '】的数据(JSON,可直接解析)\n' + warn + '```json\n'
449
- + body + '\n```\n';
450
- } else if (type === 'session-ref') {
451
- text += '\n## 来自【' + u.from.label + '】的会话引用(当前按文本传递)\n' + warn
452
- + body + '\n';
453
- } else {
454
- text += '\n## 来自【' + u.from.label + '】\n' + warn + body + '\n';
455
- }
456
- }
457
- return text;
458
- }
459
-
460
- function extractResultError(result) {
461
- if (!result || typeof result !== 'object') return '';
462
- const candidates = [result.error, result.errorMessage, result.message, result.failureReason];
463
- for (const raw of candidates) {
464
- if (typeof raw === 'string' && raw.trim()) return raw.trim();
465
- if (raw && typeof raw === 'object') {
466
- const msg = raw.message || raw.detail || raw.code;
467
- if (typeof msg === 'string' && msg.trim()) return msg.trim();
468
- try {
469
- const s = JSON.stringify(raw);
470
- if (s && s !== '{}') return s.slice(0, 240);
471
- } catch (_e) { /* ignore */ }
472
- }
473
- }
474
- return '';
475
- }
476
-
477
- function textOf(result) {
478
- // A structured node's canonical value is its parsed object, not the prose.
479
- if (result && result.structured !== undefined) {
480
- try {
481
- return JSON.stringify(result.structured);
482
- } catch (_e) {
483
- /* fall through to prose */
484
- }
485
- }
486
- const blocks = (result && result.output) || [];
487
- const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
488
- if (text) return text;
489
- const errDetail = extractResultError(result);
490
- const stop = (result && result.stopReason) || (errDetail ? 'error' : 'no-output');
491
- return errDetail ? '[' + stop + '] ' + errDetail : '[' + stop + ']';
492
- }
493
-
494
- function failed(result) {
495
- const reason = result && result.stopReason;
496
- return reason !== undefined && reason !== 'completed';
497
- }
498
-
499
- function isEmptyOutput(result) {
500
- if (result && result.structured !== undefined) return false;
501
- const blocks = (result && result.output) || [];
502
- const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
503
- return text.trim().length === 0;
504
- }
505
-
506
- function buildLoopWarmPrompt(node, loopCtx) {
507
- const fb = loopCtx && loopCtx.feedback;
508
- if (!fb) return null;
509
- const lines = [
510
- '【第 ' + fb.retry + '/' + fb.max + ' 次回环修正】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请结合以下反馈直接在当前会话上下文中修正并输出最新交付结果(无需重复叙述过程):',
511
- '- 打回理由:' + (fb.reason || '未达预期'),
512
- ];
513
- if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
514
- if (node.role) lines.push('- 你的职责提醒:' + node.role);
515
- return lines.join('\n');
169
+ });
516
170
  }
517
171
 
518
172
  async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid, failedMap, prunedSet, loopCtx) {
@@ -600,10 +254,10 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
600
254
  try {
601
255
  if (activation && activation.childId) {
602
256
  const cid = String(activation.childId);
603
- liveChild.set(childKey(node.id), cid);
257
+ touchMapLRU(liveChild, childKey(node.id), cid, MAX_CHILD_SLOTS);
604
258
  // Only overwrite the persisted memory slot when Memory is ON, so a
605
259
  // temporary keepSession=false experiment never destroys saved memory.
606
- if (node.keepSession) childByNode.set(childKey(node.id), cid);
260
+ if (node.keepSession) touchMapLRU(childByNode, childKey(node.id), cid, MAX_CHILD_SLOTS);
607
261
  const activeRec = sid ? activeRunBySession.get(String(sid)) : null;
608
262
  if (activeRec && activeRec.childIds) activeRec.childIds.add(cid);
609
263
  }
@@ -616,16 +270,27 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
616
270
  }
617
271
  const outText = textOf(result);
618
272
  const errDetail = extractResultError(result);
273
+ // DSH 0.2.2 implements `outputSchema` via a `structured_output` tool; if a minimal
274
+ // condition judge completes with valid JSON text without calling the tool, DSH
275
+ // rewrites `completed -> error` with no `diagnostic`. Rescue strict JSON verdicts
276
+ // directly on attempt #1 instead of burning a second LLM roundtrip.
277
+ const rescuedDecision = (isCondition
278
+ && result
279
+ && result.stopReason === 'error'
280
+ && !errDetail
281
+ && result.structured === undefined)
282
+ ? parseStrictConditionJson(outText, node)
283
+ : null;
619
284
  const outcome = {
620
- ok: !failed(result),
285
+ ok: rescuedDecision ? true : !failed(result),
621
286
  text: outText,
622
- reason: result && result.stopReason,
287
+ reason: rescuedDecision ? 'completed' : (result && result.stopReason),
623
288
  errorDetail: errDetail,
624
- empty: isEmptyOutput(result),
289
+ empty: rescuedDecision ? false : isEmptyOutput(result),
625
290
  childId: activation && activation.childId ? String(activation.childId) : '',
626
291
  };
627
292
  if (isCondition) {
628
- outcome.decision = parseConditionDecision(result, outText, node);
293
+ outcome.decision = rescuedDecision || parseConditionDecision(result, outText, node);
629
294
  }
630
295
  return outcome;
631
296
  } finally {
@@ -643,7 +308,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
643
308
  const continued = await run(loopCtx.warmChildId, warmPrompt);
644
309
  if (signal && signal.aborted) return continued;
645
310
  if (continued.ok) {
646
- liveChild.set(childKey(node.id), continued.childId || loopCtx.warmChildId);
311
+ touchMapLRU(liveChild, childKey(node.id), continued.childId || loopCtx.warmChildId, MAX_CHILD_SLOTS);
647
312
  return { ...continued, warmReused: true };
648
313
  }
649
314
  if (continued.reason !== 'activation-failed') {
@@ -658,7 +323,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
658
323
  const continued = await run(forcedChild);
659
324
  if (signal && signal.aborted) return continued;
660
325
  if (continued.ok) {
661
- liveChild.set(childKey(node.id), forcedChild);
326
+ touchMapLRU(liveChild, childKey(node.id), forcedChild, MAX_CHILD_SLOTS);
662
327
  return continued;
663
328
  }
664
329
  if (continued.reason !== 'activation-failed') {
@@ -690,18 +355,11 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
690
355
  const started = await run(undefined);
691
356
  if (node.keepSession && started.ok) {
692
357
  const current = childByNode.get(childKey(node.id));
693
- if (current) liveChild.set(childKey(node.id), current);
358
+ if (current) touchMapLRU(liveChild, childKey(node.id), current, MAX_CHILD_SLOTS);
694
359
  }
695
360
  return started;
696
361
  }
697
362
 
698
- function formatModelLabel(provider, model) {
699
- const p = typeof provider === 'string' ? provider.trim() : '';
700
- const m = typeof model === 'string' ? model.trim() : '';
701
- if (p && m) return p + '/' + m;
702
- return m || p || '';
703
- }
704
-
705
363
  async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet, loopCtx) {
706
364
  const primaryModel = formatModelLabel(node.provider, node.model);
707
365
  if (signal && signal.aborted) {
@@ -733,13 +391,31 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
733
391
 
734
392
  let first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
735
393
  if (signal && signal.aborted) return first;
394
+ // Safe single transient-error backoff retry strictly for read-only nodes (`minimal` / `condition`)
395
+ // on post-start transient failures (429/502/503/504/timeout). Never auto-retry writable standard
396
+ // agents (which may have side effects) or `activation-failed` (which feeds the circuit breaker).
397
+ const isReadOnly = node.kind === 'condition' || node.preset === 'minimal';
398
+ let transientRetried = false;
399
+ if (!first.ok && isReadOnly && first.reason !== 'activation-failed' && first.reason !== 'aborted' && isTransientFailure(first)) {
400
+ transientRetried = true;
401
+ const retryDelayMs = typeof plan.__transientDelayMs === 'number' ? plan.__transientDelayMs : 600;
402
+ await delayWithSignal(retryDelayMs, signal);
403
+ if (signal && signal.aborted) {
404
+ return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: first.childId || '', modelUsed: primaryModel, fallbackUsed: false, sessionContinued: false };
405
+ }
406
+ const transientRetry = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
407
+ if (signal && signal.aborted) return transientRetry;
408
+ if (transientRetry.ok || transientRetry.errorDetail || !first.errorDetail) {
409
+ first = transientRetry;
410
+ }
411
+ }
736
412
  // Many models/proxies reject strict `outputSchema` (`json_schema`) with stopReason='error'.
737
413
  // For condition/structured nodes, automatically retry once on the same model without outputSchema
738
414
  // so `parseConditionDecision` can parse plain-text JSON before giving up or falling back.
739
415
  const usedSchema = node.kind === 'condition'
740
416
  || Boolean(node.structured)
741
417
  || (plan.edges || []).some((e) => e.from === node.id && e.type === 'structured');
742
- if (!first.ok && usedSchema && first.reason !== 'activation-failed' && first.reason !== 'aborted' && !isPermissionFailure(first)) {
418
+ if (!first.ok && !transientRetried && usedSchema && first.reason !== 'activation-failed' && first.reason !== 'aborted' && !isPermissionFailure(first)) {
743
419
  const plainRetry = await spawnOnce(scope, plan, node, results, parent, signal, { noSchema: true }, undefined, sid, failedMap, prunedSet, loopCtx);
744
420
  if (signal && signal.aborted) return plainRetry;
745
421
  if (plainRetry.ok) {
@@ -822,466 +498,6 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
822
498
  };
823
499
  }
824
500
 
825
- /** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
826
- function reachableFrom(plan) {
827
- const adj = new Map();
828
- for (const e of forwardEdgesOf(plan && plan.edges)) {
829
- if (!e || !e.from || !e.to) continue;
830
- if (!adj.has(e.from)) adj.set(e.from, []);
831
- adj.get(e.from).push(e.to);
832
- }
833
- const set = new Set(['lead']);
834
- const queue = ['lead'];
835
- for (let i = 0; i < queue.length; i += 1) {
836
- const cur = queue[i];
837
- for (const next of adj.get(cur) || []) {
838
- if (!set.has(next)) { set.add(next); queue.push(next); }
839
- }
840
- }
841
- return set;
842
- }
843
-
844
- /**
845
- * Classify inactive nodes that are rendered dashed on the canvas and skipped at run time:
846
- * - unreachable orphans
847
- * - solo chained Leads (zero reachable subagent upstream and blank role)
848
- * - dangling dead-end subagents (zero outgoing edges while an active non-ancestor downstream Lead exists)
849
- */
850
- function inactiveNodeSets(nodes, edges) {
851
- const list = withoutEntry(nodes);
852
- const linkList = Array.isArray(edges) ? edges : [];
853
- const fwdLinks = forwardEdgesOf(linkList);
854
- const reachable = reachableFrom({ edges: fwdLinks });
855
- const byId = new Map(list.map((n) => [n.id, n]));
856
-
857
- const soloLeads = new Set();
858
- for (const n of list) {
859
- if (n.kind !== 'lead' || !reachable.has(n.id)) continue;
860
- const hasAgentUp = fwdLinks.some((e) => {
861
- if (!e || e.to !== n.id || !reachable.has(e.from) || e.from === 'lead') return false;
862
- const src = byId.get(e.from);
863
- return Boolean(src && src.kind !== 'lead');
864
- });
865
- const hasRole = Boolean(String(n.role || '').trim());
866
- if (!hasAgentUp && !hasRole) soloLeads.add(n.id);
867
- }
868
-
869
- const deadEnds = new Set();
870
- const activeLeads = list.filter((n) => n.kind === 'lead' && reachable.has(n.id) && !soloLeads.has(n.id));
871
- if (activeLeads.length) {
872
- const hasOut = new Set(linkList.map((e) => e.from));
873
- const parents = new Map();
874
- for (const e of fwdLinks) {
875
- if (!parents.has(e.to)) parents.set(e.to, []);
876
- parents.get(e.to).push(e.from);
877
- }
878
- const ancestorsOf = (id) => {
879
- const seen = new Set();
880
- const stack = [id];
881
- while (stack.length) {
882
- const cur = stack.pop();
883
- for (const p of parents.get(cur) || []) {
884
- if (!seen.has(p)) { seen.add(p); stack.push(p); }
885
- }
886
- }
887
- return seen;
888
- };
889
- for (const n of list) {
890
- if (n.kind === 'lead' || !reachable.has(n.id) || hasOut.has(n.id)) continue;
891
- const anc = ancestorsOf(n.id);
892
- if (activeLeads.some((ln) => !anc.has(ln.id))) deadEnds.add(n.id);
893
- }
894
- }
895
- return { reachable, soloLeads, deadEnds };
896
- }
897
-
898
- /**
899
- * Validate controlled loop edges: each loop edge must leave a condition node, target a strict
900
- * forward-path ancestor (never entry Lead), and not overlap/cross another loop edge's body.
901
- */
902
- function validateLoopEdges(nodes, edges) {
903
- const list = withoutEntry(nodes);
904
- const byId = new Map(list.map((n) => [n.id, n]));
905
- const linkList = Array.isArray(edges) ? edges : [];
906
- const loopEdges = linkList.filter((e) => isLoopEdge(e));
907
- const errors = [];
908
- const seenMembers = new Map();
909
- for (const le of loopEdges) {
910
- const src = byId.get(le.from);
911
- const dst = byId.get(le.to);
912
- if (!src || src.kind !== 'condition') {
913
- errors.push('回环边起点必须是条件判断节点(' + le.from + ' → ' + le.to + ')。');
914
- continue;
915
- }
916
- if (!dst || le.to === 'lead') {
917
- errors.push('回环边不能指向入口 Lead 或不存在的节点(' + le.from + ' → ' + le.to + ')。');
918
- continue;
919
- }
920
- const members = loopMemberIds(list, linkList, le);
921
- if (!members.size) {
922
- errors.push('回环边目标「' + (dst.label || dst.id) + '」不是「' + (src.label || src.id) + '」的上游祖先节点。');
923
- continue;
924
- }
925
- let overlap = false;
926
- for (const mid of members) {
927
- if (seenMembers.has(mid)) { overlap = true; break; }
928
- }
929
- if (overlap) {
930
- errors.push('检测到交叉或嵌套回环(涉及节点「' + (dst.label || dst.id) + '」),暂不支持交叉回环。');
931
- continue;
932
- }
933
- for (const mid of members) seenMembers.set(mid, le);
934
- }
935
- return errors;
936
- }
937
-
938
- /**
939
- * Detect structural warnings on a canvas plan (all three classes are rendered
940
- * dashed on the canvas and skipped at run time):
941
- * 1. Unreachable nodes.
942
- * 2. Solo chained Lead nodes with zero subagent upstream and blank role.
943
- * 3. Dangling dead-end subagent nodes with zero outgoing edges.
944
- * 4. Invalid/crossing loop edges or loop conditions with no forward exit.
945
- */
946
- function analyzeCanvasWarnings(nodes, edges) {
947
- const list = withoutEntry(nodes);
948
- const linkList = Array.isArray(edges) ? edges : [];
949
- const warnings = [];
950
- if (!list.length) return warnings;
951
-
952
- const { reachable, soloLeads, deadEnds } = inactiveNodeSets(list, linkList);
953
- const orphans = list.filter((n) => !reachable.has(n.id));
954
- if (orphans.length) {
955
- warnings.push('以下节点未从入口 Lead 连通,运行时会被跳过:'
956
- + orphans.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
957
- }
958
- const soloList = list.filter((n) => soloLeads.has(n.id));
959
- if (soloList.length) {
960
- warnings.push('以下 Lead 节点未连入子代理且未填写分工(role),运行时不生效:'
961
- + soloList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
962
- }
963
- const deadList = list.filter((n) => deadEnds.has(n.id));
964
- if (deadList.length) {
965
- warnings.push('以下子代理节点没有出边,产出未连入下游或终审 Lead,运行时不生效:'
966
- + deadList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
967
- }
968
- for (const err of validateLoopEdges(list, linkList)) warnings.push(err);
969
- // Warn if a non-exit node inside a loop has a forward edge leaking outside the loop
970
- // (that outside branch starts on round 1 and will not re-run on retry rounds).
971
- const fwdLinks = forwardEdgesOf(linkList);
972
- const byId = new Map(list.map((n) => [n.id, n]));
973
- for (const le of linkList) {
974
- if (!isLoopEdge(le)) continue;
975
- const members = loopMemberIds(list, linkList, le);
976
- if (!members.size) continue;
977
- const leaked = [];
978
- for (const e of fwdLinks) {
979
- if (e.from !== le.from && members.has(e.from) && !members.has(e.to)) {
980
- const src = byId.get(e.from);
981
- const dst = byId.get(e.to);
982
- leaked.push(((src && src.label) || e.from) + ' → ' + ((dst && dst.label) || e.to));
983
- }
984
- }
985
- if (leaked.length) {
986
- warnings.push('回环内部节点存在绕过条件裁判的旁路连线(' + leaked.join('、') + '),回环重试时这些环外节点不会重跑。');
987
- }
988
- }
989
- return warnings;
990
- }
991
-
992
- /**
993
- * Turn a model-authored sketch into a canvas document: assign ids, ensure one
994
- * connected entry Lead, and lay the graph out in columns by depth.
995
- */
996
- function normalizeCanvas(args) {
997
- const rawNodes = Array.isArray(args && args.nodes) ? args.nodes : [];
998
- const rawEdges = Array.isArray(args && args.edges) ? args.edges : [];
999
- if (!rawNodes.length) return { error: '至少需要一个节点' };
1000
-
1001
- const nodes = [];
1002
- const idByRef = new Map();
1003
- const usedIds = new Set();
1004
- let counter = 0;
1005
- let hasExplicitLead = false;
1006
- for (const raw of rawNodes) {
1007
- if (!raw || typeof raw !== 'object') continue;
1008
- counter += 1;
1009
- const kind = normalizeKind(raw.kind);
1010
- const wantsEntry = !hasExplicitLead && (raw.id === 'lead' || (raw.entry === true && kind === 'lead'));
1011
- let id = wantsEntry
1012
- ? 'lead'
1013
- : (typeof raw.id === 'string' && raw.id && raw.id !== 'lead' ? raw.id : 'n' + counter);
1014
- if (usedIds.has(id)) {
1015
- let suffix = 2;
1016
- while (usedIds.has(id + '_' + suffix)) suffix += 1;
1017
- id = id + '_' + suffix;
1018
- }
1019
- usedIds.add(id);
1020
- if (id === 'lead') hasExplicitLead = true;
1021
- const defaultLabel = kind === 'lead'
1022
- ? 'Lead 步骤 ' + counter
1023
- : (kind === 'condition' ? '条件判断 ' + counter : 'Node ' + counter);
1024
- const label = String(raw.label || defaultLabel);
1025
- const nodeObj = {
1026
- id,
1027
- kind: id === 'lead' ? 'lead' : kind,
1028
- label,
1029
- role: String(raw.role || ''),
1030
- task: String(raw.task || ''),
1031
- provider: String(raw.provider || ''),
1032
- model: String(raw.model || ''),
1033
- reasoning: String(raw.reasoning || ''),
1034
- preset: (id === 'lead' ? '' : (kind === 'condition' ? 'minimal' : String(raw.preset || ''))),
1035
- structured: Boolean(raw.structured),
1036
- keepSession: Boolean(raw.keepSession),
1037
- fallbackModel: String(raw.fallbackModel || ''),
1038
- fallbackProvider: String(raw.fallbackProvider || ''),
1039
- x: 0,
1040
- y: 0,
1041
- };
1042
- const normRefs = normalizeRefs(raw.refs);
1043
- if (normRefs) nodeObj.refs = normRefs;
1044
- if (nodeObj.kind === 'condition') {
1045
- const customBranches = normalizeBranches(raw.branches);
1046
- if (customBranches) nodeObj.branches = customBranches;
1047
- if (raw.multiMatch === true) nodeObj.multiMatch = true;
1048
- }
1049
- nodes.push(nodeObj);
1050
- if (raw.ref && !idByRef.has(String(raw.ref))) idByRef.set(String(raw.ref), id);
1051
- if (raw.id && !idByRef.has(String(raw.id))) idByRef.set(String(raw.id), id);
1052
- idByRef.set(id, id);
1053
- }
1054
- if (!nodes.length) return { error: '节点都无效' };
1055
-
1056
- const ids = new Set(nodes.map((n) => n.id));
1057
- const edges = [];
1058
- for (const raw of rawEdges) {
1059
- if (!raw || typeof raw !== 'object') continue;
1060
- const from = idByRef.get(String(raw.from)) || String(raw.from);
1061
- const to = idByRef.get(String(raw.to)) || String(raw.to);
1062
- if ((from !== 'lead' && !ids.has(from)) || !ids.has(to) || from === to || to === 'lead') continue;
1063
- const type = ['prompt', 'structured', 'session-ref'].includes(raw.type) ? raw.type : 'prompt';
1064
- const branch = normalizeBranch(raw.branch);
1065
- const edgeObj = { id: 'e' + edges.length, from, to, type };
1066
- if (branch) edgeObj.branch = branch;
1067
- if (raw.loop === true) {
1068
- edgeObj.loop = true;
1069
- edgeObj.maxIterations = normalizeMaxIterations(raw.maxIterations);
1070
- }
1071
- edges.push(edgeObj);
1072
- }
1073
-
1074
- let entry = nodes.find((n) => n.id === 'lead');
1075
- if (!entry) {
1076
- // If the caller hand-authored a root Lead node (no incoming edges, has outgoing edges)
1077
- // and didn't wire from id='lead', promote it to entry Lead instead of duplicating it.
1078
- const hasLeadEdge = edges.some((e) => e.from === 'lead');
1079
- const inSet = new Set(edges.map((e) => e.to));
1080
- const outSet = new Set(edges.map((e) => e.from));
1081
- const rootLead = !hasLeadEdge
1082
- ? nodes.find((n) => n.kind === 'lead' && !inSet.has(n.id) && outSet.has(n.id))
1083
- : null;
1084
- if (rootLead) {
1085
- const oldId = rootLead.id;
1086
- rootLead.id = 'lead';
1087
- rootLead.task = rootLead.task || String(args.task || '') || rootLead.role;
1088
- rootLead.role = '';
1089
- for (const e of edges) {
1090
- if (e.from === oldId) e.from = 'lead';
1091
- }
1092
- entry = rootLead;
1093
- } else {
1094
- entry = {
1095
- id: 'lead', kind: 'lead', label: 'Lead(本对话)', role: '',
1096
- task: String(args.task || ''), provider: '', model: '', reasoning: '',
1097
- preset: '', structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
1098
- x: 0, y: 0,
1099
- };
1100
- nodes.unshift(entry);
1101
- }
1102
- } else if (!entry.task) {
1103
- entry.task = String(args.task || '') || entry.role;
1104
- }
1105
- const topRefs = normalizeRefs(args && args.refs);
1106
- if (topRefs && !entry.refs) entry.refs = topRefs;
1107
-
1108
- // If entry Lead still has no outgoing edges, auto-wire it to all root nodes so
1109
- // a freshly generated canvas is never dead/unreachable on arrival.
1110
- if (!edges.some((e) => e.from === 'lead')) {
1111
- const hasIn = new Set(edges.map((e) => e.to));
1112
- const roots = nodes.filter((n) => n.id !== 'lead' && !hasIn.has(n.id));
1113
- for (const root of roots) {
1114
- edges.push({ id: 'e' + edges.length, from: 'lead', to: root.id, type: 'prompt' });
1115
- }
1116
- }
1117
-
1118
- const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
1119
- for (const node of nodes) {
1120
- if (structuredSources.has(node.id)) node.structured = true;
1121
- }
1122
-
1123
- // Layout: depth of the longest path from the entry (ignoring controlled loop back-edges).
1124
- const depth = new Map(nodes.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
1125
- for (let pass = 0; pass < nodes.length; pass += 1) {
1126
- let changed = false;
1127
- for (const e of forwardEdgesOf(edges)) {
1128
- if (e.to === 'lead') continue;
1129
- const next = Math.min(nodes.length, depth.get(e.from) + 1);
1130
- if (next > depth.get(e.to)) { depth.set(e.to, next); changed = true; }
1131
- }
1132
- if (!changed) break;
1133
- }
1134
- const perColumn = new Map();
1135
- for (const node of nodes) {
1136
- const level = depth.get(node.id) || 0;
1137
- const row = perColumn.get(level) || 0;
1138
- perColumn.set(level, row + 1);
1139
- node.x = 60 + level * 300;
1140
- node.y = 80 + row * 260;
1141
- }
1142
-
1143
- return {
1144
- nodes,
1145
- edges,
1146
- task: String(entry.task || args.task || ''),
1147
- warnings: analyzeCanvasWarnings(nodes, edges),
1148
- };
1149
- }
1150
-
1151
- /**
1152
- * Apply an in-place patch to an existing plan: update/add/remove nodes and
1153
- * edges without losing untouched nodes. Preserves `'lead'` as a valid edge
1154
- * source so newly added branches can wire directly from the entry Lead.
1155
- */
1156
- function applyPatch(plan, args) {
1157
- const nodes = withoutEntry(plan.nodes).map((n) => ({ ...n }));
1158
- const byId = new Map(nodes.map((n) => [n.id, n]));
1159
- const ALLOWED = ['label', 'role', 'provider', 'model', 'reasoning', 'preset', 'keepSession', 'memoryChildId', 'structured', 'fallbackModel', 'fallbackProvider'];
1160
- const touched = [];
1161
- for (const patch of args && Array.isArray(args.nodes) ? args.nodes : []) {
1162
- // 'lead' is the reserved entry node and is never edited here.
1163
- if (!patch || typeof patch.id !== 'string' || patch.id === 'lead') continue;
1164
- const existing = byId.get(patch.id);
1165
- if (existing) {
1166
- for (const key of ALLOWED) {
1167
- if (patch[key] !== undefined) existing[key] = patch[key];
1168
- }
1169
- if (patch.kind !== undefined) existing.kind = normalizeKind(patch.kind);
1170
- if (existing.kind === 'condition') existing.preset = 'minimal';
1171
- if (patch.branches !== undefined) {
1172
- const nb = normalizeBranches(patch.branches);
1173
- if (nb) existing.branches = nb;
1174
- else delete existing.branches;
1175
- }
1176
- if (patch.multiMatch !== undefined) {
1177
- if (patch.multiMatch) existing.multiMatch = true;
1178
- else delete existing.multiMatch;
1179
- }
1180
- if (patch.refs !== undefined) {
1181
- const nr = normalizeRefs(patch.refs);
1182
- if (nr) existing.refs = nr;
1183
- else delete existing.refs;
1184
- }
1185
- touched.push(patch.id);
1186
- } else {
1187
- const created = {
1188
- id: patch.id,
1189
- kind: normalizeKind(patch.kind),
1190
- label: patch.label || patch.id,
1191
- role: '', provider: '', model: '', reasoning: '', preset: 'standard',
1192
- structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
1193
- };
1194
- for (const key of ALLOWED) {
1195
- if (patch[key] !== undefined) created[key] = patch[key];
1196
- }
1197
- created.preset = (created.kind === 'condition' || created.preset === 'minimal') ? 'minimal' : 'standard';
1198
- if (created.kind === 'condition' && patch.branches !== undefined) {
1199
- const nb = normalizeBranches(patch.branches);
1200
- if (nb) created.branches = nb;
1201
- }
1202
- if (created.kind === 'condition' && patch.multiMatch === true) {
1203
- created.multiMatch = true;
1204
- }
1205
- if (patch.refs !== undefined) {
1206
- const nr = normalizeRefs(patch.refs);
1207
- if (nr) created.refs = nr;
1208
- }
1209
- nodes.push(created);
1210
- byId.set(created.id, created);
1211
- touched.push(created.id);
1212
- }
1213
- }
1214
- const removed = new Set(Array.isArray(args && args.removeNodes) ? args.removeNodes : []);
1215
- removed.delete('lead');
1216
- const keptNodes = nodes.filter((n) => !removed.has(n.id));
1217
- const keptIds = new Set(keptNodes.map((n) => n.id));
1218
- const rawRemoveEdges = Array.isArray(args && args.removeEdges) ? args.removeEdges : [];
1219
- const matchesRemovedEdge = (edge) => rawRemoveEdges.some((r) => {
1220
- if (!r || String(r.from) !== edge.from || String(r.to) !== edge.to) return false;
1221
- if (r.type && r.type !== edge.type) return false;
1222
- const rb = normalizeBranch(r.branch);
1223
- if (rb && rb !== normalizeBranch(edge.branch)) return false;
1224
- return true;
1225
- });
1226
- let edges = (Array.isArray(plan.edges) ? plan.edges : [])
1227
- .filter((e) => !matchesRemovedEdge(e) && !removed.has(e.from) && !removed.has(e.to))
1228
- .map((e) => ({ ...e }));
1229
- for (const edge of Array.isArray(args && args.edges) ? args.edges : []) {
1230
- if (!edge || typeof edge.from !== 'string' || typeof edge.to !== 'string') continue;
1231
- if (edge.from === edge.to || edge.to === 'lead') continue;
1232
- const validFrom = edge.from === 'lead' || keptIds.has(edge.from);
1233
- const validTo = keptIds.has(edge.to);
1234
- if (!validFrom || !validTo) continue;
1235
- const type = ['prompt', 'structured', 'session-ref'].includes(edge.type) ? edge.type : 'prompt';
1236
- const branch = normalizeBranch(edge.branch);
1237
- const existingEdge = edges.find((e) => e.from === edge.from && e.to === edge.to && e.type === type && normalizeBranch(e.branch) === branch);
1238
- if (existingEdge) {
1239
- if (edge.loop === true) {
1240
- existingEdge.loop = true;
1241
- existingEdge.maxIterations = normalizeMaxIterations(edge.maxIterations !== undefined ? edge.maxIterations : existingEdge.maxIterations);
1242
- } else if (edge.loop === false) {
1243
- delete existingEdge.loop;
1244
- delete existingEdge.maxIterations;
1245
- }
1246
- continue;
1247
- }
1248
- const nextEdge = { from: edge.from, to: edge.to, type };
1249
- if (branch) nextEdge.branch = branch;
1250
- if (edge.loop === true) {
1251
- nextEdge.loop = true;
1252
- nextEdge.maxIterations = normalizeMaxIterations(edge.maxIterations);
1253
- }
1254
- edges.push(nextEdge);
1255
- }
1256
- const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
1257
- for (const node of keptNodes) {
1258
- node.structured = structuredSources.has(node.id);
1259
- }
1260
- const taskPatched = typeof (args && args.task) === 'string';
1261
- const nextTask = taskPatched ? args.task : String(plan.task || '');
1262
- const refsPatched = args && args.refs !== undefined;
1263
- const nextRefs = refsPatched ? normalizeRefs(args.refs) : normalizeRefs(plan.refs);
1264
- const nextPlan = { ...plan, task: nextTask, nodes: keptNodes, edges };
1265
- if (nextRefs) nextPlan.refs = nextRefs;
1266
- else delete nextPlan.refs;
1267
- return {
1268
- plan: nextPlan,
1269
- touched,
1270
- taskPatched,
1271
- refsPatched,
1272
- removed: Array.from(removed),
1273
- removeEdges: rawRemoveEdges
1274
- .filter((r) => r && typeof r.from === 'string' && typeof r.to === 'string')
1275
- .map((r) => {
1276
- const item = { from: r.from, to: r.to };
1277
- if (r.type) item.type = r.type;
1278
- const rb = normalizeBranch(r.branch);
1279
- if (rb) item.branch = rb;
1280
- return item;
1281
- }),
1282
- };
1283
- }
1284
-
1285
501
  /**
1286
502
  * Drop a generated canvas where the browser can pick it up. `workspaceFiles`
1287
503
  * resolves a session's root from its header cwd, so the client reads the same
@@ -1295,141 +511,46 @@ function resolveSessionsService(scope) {
1295
511
  }
1296
512
  }
1297
513
 
514
+ function activeCanvasIds(extraId) {
515
+ const ids = new Set();
516
+ for (const k of runBySession.keys()) {
517
+ const safe = safeSessionFileBase(k);
518
+ if (safe) ids.add(safe);
519
+ }
520
+ const extraSafe = safeSessionFileBase(extraId);
521
+ if (extraSafe) ids.add(extraSafe);
522
+ return ids;
523
+ }
524
+
1298
525
  function publishCanvas(scope, sessionId, canvas) {
1299
526
  try {
527
+ const safeId = safeSessionFileBase(sessionId);
528
+ if (!safeId) return false;
1300
529
  const sessionsSvc = resolveSessionsService(scope);
1301
530
  const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
1302
531
  const root = live && live.header && live.header.cwd;
1303
532
  if (!root) return false;
1304
533
  const dir = join(root, '.dsh', 'canvas');
1305
- mkdirSync(dir, { recursive: true });
1306
- writeFileSync(join(dir, sessionId + '.json'), JSON.stringify({ canvas, at: Date.now() }), 'utf8');
534
+ writeFileAtomic(join(dir, safeId + '.json'), JSON.stringify({ canvas, at: Date.now() }));
535
+ cleanupStaleCanvasFiles(dir, { activeIds: activeCanvasIds(sessionId) });
1307
536
  return true;
1308
537
  } catch (_e) {
1309
538
  return false;
1310
539
  }
1311
540
  }
1312
541
 
1313
- /**
1314
- * Build a zero-token structured run summary snapshot from in-memory executor state.
1315
- * Published inside `.run.json` for the sidebar UI (never injected into model prompts).
1316
- */
1317
- function buildRunSummarySnapshot(st, opts) {
1318
- if (!st || typeof st !== 'object') return null;
1319
- const o = opts || {};
1320
- const now = typeof o.now === 'number' ? o.now : Date.now();
1321
- const status = typeof o.status === 'string' && o.status ? o.status : 'running';
1322
- const waitingLead = o.waitingLead || st.waitingLead || null;
1323
- const haltedReason = typeof o.haltedReason === 'string' && o.haltedReason
1324
- ? o.haltedReason
1325
- : (st.haltedReason || '');
1326
- const isTerminal = status === 'done' || status === 'halted';
1327
- const startedAt = typeof st.startedAt === 'number' ? st.startedAt : now;
1328
- const endedAt = isTerminal ? (typeof st.endedAt === 'number' ? st.endedAt : now) : null;
1329
- const nodeStatsMap = st.nodeStats && typeof st.nodeStats === 'object' ? st.nodeStats : {};
1330
- const prunedSet = st.pruned instanceof Set ? st.pruned : new Set(Array.isArray(st.pruned) ? st.pruned : []);
1331
- const decisions = st.decisions && typeof st.decisions === 'object' ? st.decisions : {};
1332
- const failedMap = st.failed && typeof st.failed === 'object' ? st.failed : {};
1333
- const emptyMap = st.emptyOutputs && typeof st.emptyOutputs === 'object' ? st.emptyOutputs : {};
1334
- const nodeMeta = st.nodeMeta && typeof st.nodeMeta === 'object' ? st.nodeMeta : {};
1335
- const orderIds = Array.isArray(st.orderIds) && st.orderIds.length
1336
- ? st.orderIds
1337
- : Object.keys(nodeStatsMap);
1338
-
1339
- const nodes = [];
1340
- for (const id of orderIds) {
1341
- const meta = nodeMeta[id] || {};
1342
- const stat = nodeStatsMap[id] || null;
1343
- const dec = decisions[id] || null;
1344
- const fail = failedMap[id] || null;
1345
- const isPruned = prunedSet.has(id);
1346
- const isWaiting = Boolean(status === 'need-lead' && waitingLead && waitingLead.id === id);
1347
-
1348
- let entryStatus = 'pending';
1349
- let durationMs = stat && typeof stat.durationMs === 'number' ? stat.durationMs : 0;
1350
- let entryStartedAt = stat && typeof stat.startedAt === 'number' ? stat.startedAt : null;
1351
- let entryEndedAt = stat && typeof stat.endedAt === 'number' ? stat.endedAt : null;
1352
-
1353
- if (isPruned && (!stat || stat.status === 'pending' || stat.status === 'pruned')) {
1354
- entryStatus = 'pruned';
1355
- } else if (isWaiting) {
1356
- entryStatus = 'waiting';
1357
- } else if (stat && stat.status) {
1358
- entryStatus = stat.status;
1359
- if (status === 'halted' && (entryStatus === 'running' || entryStatus === 'waiting')) {
1360
- entryStatus = 'halted';
1361
- if (entryStartedAt && !entryEndedAt) {
1362
- durationMs += Math.max(0, now - entryStartedAt);
1363
- entryEndedAt = now;
1364
- }
1365
- }
1366
- } else if (fail) {
1367
- entryStatus = 'failed';
1368
- } else if (emptyMap[id]) {
1369
- entryStatus = 'empty';
1370
- }
1371
-
1372
- let reason = (stat && typeof stat.reason === 'string' ? stat.reason : '') || (fail && fail.reason) || '';
1373
- if (!reason && dec) {
1374
- const matched = Array.isArray(dec.branchLabels) && dec.branchLabels.length
1375
- ? dec.branchLabels.join(', ')
1376
- : (dec.branchLabel || dec.branch || '');
1377
- const decReason = typeof dec.reason === 'string' ? dec.reason.trim() : '';
1378
- reason = matched ? (decReason ? matched + ' — ' + decReason : matched) : decReason;
1379
- }
1380
- if (reason.length > 160) reason = reason.slice(0, 159) + '…';
1381
-
1382
- nodes.push({
1383
- id,
1384
- label: (stat && stat.label) || meta.label || (st.labels && st.labels[id]) || id,
1385
- kind: (stat && stat.kind) || meta.kind || 'agent',
1386
- status: entryStatus,
1387
- startedAt: entryStartedAt,
1388
- endedAt: entryEndedAt,
1389
- durationMs,
1390
- runs: stat && typeof stat.runs === 'number' ? stat.runs : 0,
1391
- model: (stat && stat.model) || meta.model || '',
1392
- fallbackUsed: Boolean(stat && stat.fallbackUsed),
1393
- sessionContinued: Boolean(stat && stat.sessionContinued),
1394
- childId: (stat && stat.childId) || '',
1395
- reason,
1396
- });
542
+ /** Bound per-decision reason text inside `.run.json` so huge error dumps never bloat telemetry writes. */
543
+ function compactDecisionsForTelemetry(decisions) {
544
+ if (!decisions || typeof decisions !== 'object') return {};
545
+ const out = {};
546
+ for (const [k, v] of Object.entries(decisions)) {
547
+ if (!v || typeof v !== 'object') { out[k] = v; continue; }
548
+ const reason = typeof v.reason === 'string' && v.reason.length > 1000
549
+ ? v.reason.slice(0, 999) + '…'
550
+ : v.reason;
551
+ out[k] = reason === v.reason ? v : { ...v, reason };
1397
552
  }
1398
-
1399
- const loopMeta = Array.isArray(st.loopMeta) ? st.loopMeta : [];
1400
- const loopCounts = st.loopCounts && typeof st.loopCounts === 'object' ? st.loopCounts : {};
1401
- const loopHistory = st.loopHistory && typeof st.loopHistory === 'object' ? st.loopHistory : {};
1402
- const exhaustedKeys = new Set(Array.isArray(st.loopExhausted) ? st.loopExhausted.map((x) => x && x.edgeKey).filter(Boolean) : []);
1403
- const loops = [];
1404
- for (const lm of loopMeta) {
1405
- const used = Number(loopCounts[lm.key]) || 0;
1406
- const rawRounds = Array.isArray(loopHistory[lm.key]) ? loopHistory[lm.key] : [];
1407
- const exhausted = exhaustedKeys.has(lm.key);
1408
- if (used === 0 && rawRounds.length === 0 && !exhausted) continue;
1409
- loops.push({
1410
- fromLabel: lm.fromLabel,
1411
- toLabel: lm.toLabel,
1412
- used,
1413
- max: lm.max,
1414
- exhausted,
1415
- rounds: rawRounds.map((r) => ({
1416
- round: r.round,
1417
- reason: typeof r.reason === 'string' && r.reason.length > 140 ? r.reason.slice(0, 139) + '…' : (r.reason || ''),
1418
- })),
1419
- });
1420
- }
1421
-
1422
- return {
1423
- status,
1424
- startedAt,
1425
- endedAt,
1426
- haltedReason,
1427
- maxParallel: typeof st.maxParallel === 'number' ? st.maxParallel : 4,
1428
- totalLoops: typeof st.totalLoops === 'number' ? st.totalLoops : 0,
1429
- reused: Array.isArray(st.reusedIds) ? st.reusedIds.slice() : [],
1430
- nodes,
1431
- loops,
1432
- };
553
+ return out;
1433
554
  }
1434
555
 
1435
556
  /**
@@ -1440,17 +561,17 @@ function buildRunSummarySnapshot(st, opts) {
1440
561
  */
1441
562
  function publishRunState(scope, sessionId, runState) {
1442
563
  try {
1443
- if (!sessionId) return false;
564
+ const safeId = safeSessionFileBase(sessionId);
565
+ if (!safeId) return false;
1444
566
  const sessionsSvc = resolveSessionsService(scope);
1445
567
  const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
1446
568
  const root = live && live.header && live.header.cwd;
1447
569
  if (!root) return false;
1448
570
  const dir = join(root, '.dsh', 'canvas');
1449
- mkdirSync(dir, { recursive: true });
1450
- writeFileSync(join(dir, sessionId + '.run.json'), JSON.stringify({
1451
- ...(runState || {}),
1452
- at: Date.now(),
1453
- }), 'utf8');
571
+ const payload = { ...(runState || {}), at: Date.now() };
572
+ if (payload.decisions) payload.decisions = compactDecisionsForTelemetry(payload.decisions);
573
+ writeFileAtomic(join(dir, safeId + '.run.json'), JSON.stringify(payload));
574
+ cleanupStaleCanvasFiles(dir, { activeIds: activeCanvasIds(sessionId) });
1454
575
  return true;
1455
576
  } catch (_e) {
1456
577
  return false;
@@ -1521,7 +642,7 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1521
642
  st.endedAt = haltNow;
1522
643
  st.haltedReason = wasWaiting ? '用户结束了等待拍板状态' : '用户主动终止';
1523
644
  if (st.done && st.done.size > 0) {
1524
- lastRunBySession.set(sid, {
645
+ touchMapLRU(lastRunBySession, sid, {
1525
646
  sig: st.sig,
1526
647
  done: new Set(st.done),
1527
648
  results: { ...(st.results || {}) },
@@ -1534,7 +655,7 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
1534
655
  fallbackLinks: Array.isArray(st.fallbackLinks) ? st.fallbackLinks.map((fl) => ({ ...fl })) : [],
1535
656
  nodeStats: st.nodeStats ? Object.fromEntries(Object.entries(st.nodeStats).map(([k, v]) => [k, { ...v }])) : {},
1536
657
  halted: true,
1537
- });
658
+ }, MAX_LAST_RUNS);
1538
659
  }
1539
660
  const summary = buildRunSummarySnapshot(st, {
1540
661
  status: 'halted',
@@ -1589,7 +710,7 @@ async function runPlan(scope, args, exec) {
1589
710
  : '已终止当前工作流执行。',
1590
711
  };
1591
712
  }
1592
- const payload = sid ? canvasBySession.get(sid) : undefined;
713
+ const payload = getCanvasLRU(sid);
1593
714
  if (!payload) return { error: '当前会话还没有画布数据。请在右侧 Workflow 画布点「启用」。' };
1594
715
  if (!payload.enabled) return { error: '画布当前是「已禁用」状态。请在画布上点「启用」后再运行。' };
1595
716
  if (payload.error) return { error: String(payload.error) };
@@ -1597,7 +718,7 @@ async function runPlan(scope, args, exec) {
1597
718
  }
1598
719
 
1599
720
  function inspectPlan(sid) {
1600
- const payload = sid ? canvasBySession.get(sid) : undefined;
721
+ const payload = getCanvasLRU(sid);
1601
722
  if (!payload) {
1602
723
  return {
1603
724
  hasCanvas: false,
@@ -1690,15 +811,14 @@ function buildActiveCanvasContext(sid) {
1690
811
  if (runState && runState.waitingLead) {
1691
812
  const wl = runState.waitingLead;
1692
813
  const loopHint = wl.loopFeedback
1693
- ? ('(↺ 第 ' + wl.loopFeedback.retry + '/' + wl.loopFeedback.max + ' 次回环修正,打回理由:' + (wl.loopFeedback.reason || '未达预期') + ')')
814
+ ? ('(↺ ' + wl.loopFeedback.retry + '/' + wl.loopFeedback.max + ':' + (wl.loopFeedback.reason || '未达预期') + ')')
1694
815
  : '';
1695
816
  return [
1696
817
  '[Workflow Canvas Active — Paused at Lead Step]',
1697
- '当前会话的工作流画布正暂停在中间 Lead 节点「' + wl.label + '」(分工:' + (wl.role || wl.label) + ')' + loopHint + '。',
1698
- '- 若用户的当前消息是在拍板、确认、补充决策或要求继续:请整理决策结论并直接调用 `canvas_workflow({ leadResult: "..." })` 恢复下游节点运行。',
1699
- '- 若用户要求取消、结束或终止当前工作流:直接调用 `canvas_workflow({ cancel: true })` 解除暂停状态。',
1700
- '- 若用户要求放弃当前进度从头重跑:调用 `canvas_workflow({ reset: true })`。',
1701
- '- 若用户要求修改画布结构、分工、参考清单、分支或回环:先 `canvas_inspect` 再用 `canvas_patch`。',
818
+ '画布暂停在中间 Lead「' + wl.label + '」(' + (wl.role || wl.label) + ')' + loopHint + ':',
819
+ '- 拍板/继续:整理结论调用 `canvas_workflow({ leadResult: "..." })`。',
820
+ '- 取消:`canvas_workflow({ cancel: true })`;重跑:`canvas_workflow({ reset: true })`。',
821
+ '- 改画布:先 `canvas_inspect` 再 `canvas_patch`。',
1702
822
  ].join('\n');
1703
823
  }
1704
824
 
@@ -1712,26 +832,26 @@ function buildActiveCanvasContext(sid) {
1712
832
  const prefix = String(sid) + '::';
1713
833
  const hasMemory = nodes.some((n) => n.keepSession && (liveChild.has(prefix + n.id) || childByNode.has(prefix + n.id)));
1714
834
  const metaParts = [
1715
- '共 ' + nodes.length + ' 个执行节点:' + preview,
1716
- '入口总任务:' + (hasTask ? '已填写' : '未填写'),
835
+ nodes.length + ' 节点:' + preview,
836
+ '总任务' + (hasTask ? '已填' : '未填'),
1717
837
  ];
1718
- if (loopCount > 0) metaParts.push('含 ' + loopCount + ' 条受控回环(引擎自动按条件带反馈重试并在超限时熔断交 Lead,无需你手动循环调用)');
838
+ if (loopCount > 0) metaParts.push(loopCount + ' 条受控回环(自动按条件重试与超限熔断)');
1719
839
  if (globalRefs.length > 0) metaParts.push('全局参考 ×' + globalRefs.length);
1720
840
  const lines = [
1721
841
  '[Workflow Canvas Active]',
1722
- '当前会话的右侧工作流画布处于「● 已启用」状态(' + metaParts.join(';') + ')。',
1723
- '- 若用户发出任务请求、布置工作或说「开始 / 执行 / 跑一次」:请直接调用 `canvas_workflow` 按画布编排执行('
1724
- + (hasTask ? '可直接沿用入口总任务;若用户给出了新任务则通过 task 参数传入' : '请将用户的任务内容作为 task 参数传入')
1725
- + '),不要绕过画布直接自己完成。',
1726
- '- 若用户在讨论或要求修改画布结构、模型、分工、参考清单、条件分支、回环或连线:请先 `canvas_inspect` 再用 `canvas_patch` 就地修改,不要直接运行。',
1727
- '- 仅当用户明确只是闲聊、问无关问题或要求先停用画布时,才无需调用 `canvas_workflow`。',
842
+ '右侧画布「● 已启用」(' + metaParts.join(';') + ')。',
843
+ '- 用户布置任务或说「开始/执行/跑一次」:直接调 `canvas_workflow`('
844
+ + (hasTask ? '沿用入口任务,有新任务则传 task' : '传入 task 参数')
845
+ + '),勿绕过画布直接手做。',
846
+ '- 修改画布结构/模型/分工/参考清单、条件分支、回环或连线:先 `canvas_inspect` 再 `canvas_patch`,勿直接运行。',
847
+ '- 仅闲聊、无关问题或要求停用画布时不调 `canvas_workflow`。',
1728
848
  ];
1729
849
  if (hasMemory) {
1730
- lines.push('- 本会话已有开启「记忆」节点的历史子代理会话:若用户说「再跑一次 / 换个任务重跑」,请先简短询问用户是保留上次记忆继续(reset: true)还是清空记忆全新开跑(reset: true, clearMemory: true)。');
850
+ lines.push('- 已有开启「记忆」的子代理会话:若用户要求重跑,先问保留记忆(`reset: true`)或清空记忆(`reset: true, clearMemory: true`)。');
1731
851
  }
1732
852
  const stdCount = nodes.filter((n) => n.kind !== 'lead' && n.kind !== 'condition' && n.preset !== 'minimal').length;
1733
853
  if (stdCount >= 2) {
1734
- lines.push('- 本画布包含 ' + stdCount + ' 个可写/命令型(standard)子代理,受主对话权限上限约束;若任务涉及改代码、写文件或跑终端命令且当前主对话权限偏严格,请先简短提醒用户放开主对话权限再调 `canvas_workflow`,避免中途报错白耗额度。');
854
+ lines.push('- 含 ' + stdCount + ' 个可写/命令型(standard)子代理,受主对话权限上限约束;若涉及改文件/跑命令且权限偏严,先简短提醒用户放开权限再跑。');
1735
855
  }
1736
856
  const prevRun = lastRunBySession.get(String(sid));
1737
857
  if (prevRun) {
@@ -1740,23 +860,13 @@ function buildActiveCanvasContext(sid) {
1740
860
  ...Object.values(prevRun.emptyOutputs || {}).map((e) => e.label || e.id),
1741
861
  ].filter((v, i, arr) => v && arr.indexOf(v) === i);
1742
862
  if (prevRun.halted || badNames.length) {
1743
- lines.push('- 上次运行存在失败/熔断节点(' + (badNames.join('、') || '部分未完成')
1744
- + '):若用户要求只重跑失败部分或继续未完成段,请调用 `canvas_workflow({ retryFailed: true })` 局部续跑(自动复用已成功节点缓存,零重复消耗);也可传 `fromNodes: ["节点id"]` 指定从某个节点开始重跑。');
863
+ lines.push('- 上次有失败/熔断节点(' + (badNames.join('、') || '部分未完成')
864
+ + '):局部续跑调 `canvas_workflow({ retryFailed: true })`(复用成功缓存)或指定 `fromNodes`。');
1745
865
  }
1746
866
  }
1747
867
  return lines.join('\n');
1748
868
  }
1749
869
 
1750
- /** Detect permission / sandbox denial outcomes so we can circuit-break before burning downstream tokens. */
1751
- const PERMISSION_ERR_RE = /permission denied|access is denied|sandbox-local|windows-acl|win32error|eacces|eperm|approval required|not permitted|拒绝访问|权限不足|无权执行|沙箱拒绝/i;
1752
- function isPermissionFailure(outcome) {
1753
- if (!outcome) return false;
1754
- const text = String(outcome.text || '');
1755
- if (!outcome.ok && PERMISSION_ERR_RE.test(text)) return true;
1756
- if (text.includes('【未完全交付】') && PERMISSION_ERR_RE.test(text)) return true;
1757
- return false;
1758
- }
1759
-
1760
870
  /** Takes a plan directly so tests can feed any plan shape (sync, generate, patch). */
1761
871
  async function executePlan(scope, plan, args, exec) {
1762
872
  const opts = args || {};
@@ -1773,6 +883,9 @@ async function executePlan(scope, plan, args, exec) {
1773
883
  : '已终止当前工作流执行。',
1774
884
  };
1775
885
  }
886
+ if (sid && activeRunBySession.has(sid)) {
887
+ return { error: '当前会话已有工作流正在执行中,请等待完成,或先调用 canvas_workflow({ cancel: true }) / 点击「⏹ 终止」。' };
888
+ }
1776
889
  if (!plan || !Array.isArray(plan.nodes) || !plan.nodes.length) {
1777
890
  return { error: '画布没有可执行的节点。' };
1778
891
  }
@@ -1838,8 +951,28 @@ async function executePlan(scope, plan, args, exec) {
1838
951
  const sig = JSON.stringify(plan);
1839
952
  let state = runBySession.get(sid);
1840
953
  const wantRetryFailed = opts.retryFailed === true;
954
+ if (opts.fromNodes !== undefined && !Array.isArray(opts.fromNodes)) {
955
+ return { error: '参数 fromNodes 必须是节点 ID 或名称的字符串数组,例如 ["n1"]。' };
956
+ }
1841
957
  const rawFromNodes = Array.isArray(opts.fromNodes) ? opts.fromNodes.filter((x) => typeof x === 'string' && x.trim()) : [];
1842
- const wantPartial = wantRetryFailed || rawFromNodes.length > 0;
958
+ const resolvedFromIds = [];
959
+ if (rawFromNodes.length > 0) {
960
+ const unmatched = [];
961
+ for (const ref of rawFromNodes) {
962
+ const trimmed = ref.trim();
963
+ if (byId.has(trimmed)) resolvedFromIds.push(trimmed);
964
+ else {
965
+ const match = runnable.find((n) => n.label === trimmed);
966
+ if (match) resolvedFromIds.push(match.id);
967
+ else unmatched.push(trimmed);
968
+ }
969
+ }
970
+ if (unmatched.length) {
971
+ const validList = runnable.map((n) => n.id + (n.label && n.label !== n.id ? '(' + n.label + ')' : '')).join('、');
972
+ return { error: 'fromNodes 中以下节点不存在或不可达:' + unmatched.join('、') + '。当前可执行节点:' + validList };
973
+ }
974
+ }
975
+ const wantPartial = wantRetryFailed || resolvedFromIds.length > 0;
1843
976
  let reused = [];
1844
977
  let reusedIds = [];
1845
978
 
@@ -1892,14 +1025,7 @@ async function executePlan(scope, plan, args, exec) {
1892
1025
  for (const id of Object.keys(state.failed)) seeds.add(id);
1893
1026
  for (const id of Object.keys(state.emptyOutputs)) seeds.add(id);
1894
1027
  }
1895
- for (const ref of rawFromNodes) {
1896
- const trimmed = ref.trim();
1897
- if (byId.has(trimmed)) seeds.add(trimmed);
1898
- else {
1899
- const match = runnable.find((n) => n.label === trimmed);
1900
- if (match) seeds.add(match.id);
1901
- }
1902
- }
1028
+ for (const id of resolvedFromIds) seeds.add(id);
1903
1029
  const invalid = new Set(seeds);
1904
1030
  const q = Array.from(seeds);
1905
1031
  for (let i = 0; i < q.length; i += 1) {
@@ -2030,7 +1156,7 @@ async function executePlan(scope, plan, args, exec) {
2030
1156
 
2031
1157
  const snapshotLastRun = (haltedFlag) => {
2032
1158
  if (!sid) return;
2033
- lastRunBySession.set(sid, {
1159
+ touchMapLRU(lastRunBySession, sid, {
2034
1160
  sig: state.sig,
2035
1161
  done: new Set(state.done),
2036
1162
  results: { ...state.results },
@@ -2043,7 +1169,7 @@ async function executePlan(scope, plan, args, exec) {
2043
1169
  fallbackLinks: state.fallbackLinks.map((fl) => ({ ...fl })),
2044
1170
  nodeStats: Object.fromEntries(Object.entries(state.nodeStats || {}).map(([k, v]) => [k, { ...v }])),
2045
1171
  halted: Boolean(haltedFlag),
2046
- });
1172
+ }, MAX_LAST_RUNS);
2047
1173
  };
2048
1174
  const depsOf = (node) => {
2049
1175
  const out = new Set();
@@ -2866,9 +1992,11 @@ export function apply(ctx) {
2866
1992
  try {
2867
1993
  const id = agent && agent.id !== undefined ? String(agent.id) : '';
2868
1994
  if (!id) return { kind: 'error', text: 'no session' };
2869
- canvasBySession.set(id, parsePayload(rawInput));
2870
- runBySession.delete(id);
2871
- publishRunState(ctx, id, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
1995
+ touchMapLRU(canvasBySession, id, parsePayload(rawInput), MAX_STORED_SESSIONS);
1996
+ if (!activeRunBySession.has(id)) {
1997
+ runBySession.delete(id);
1998
+ publishRunState(ctx, id, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
1999
+ }
2872
2000
  saveStore();
2873
2001
  return { kind: 'success', text: 'canvas synced' };
2874
2002
  } catch (error) {
@@ -3018,10 +2146,10 @@ export function apply(ctx) {
3018
2146
  };
3019
2147
  const entryRefs = normalizeRefs(entryNode && entryNode.refs);
3020
2148
  if (entryRefs) planObj.refs = entryRefs;
3021
- canvasBySession.set(sid, {
2149
+ touchMapLRU(canvasBySession, sid, {
3022
2150
  enabled: nextEnabled,
3023
2151
  plan: planObj,
3024
- });
2152
+ }, MAX_STORED_SESSIONS);
3025
2153
  runBySession.delete(sid);
3026
2154
  lastRunBySession.delete(sid);
3027
2155
  publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
@@ -3081,7 +2209,7 @@ export function apply(ctx) {
3081
2209
  if (!payload || !payload.plan) return { error: '当前会话还没有画布数据,先用「启用」同步一次。' };
3082
2210
  const patched = applyPatch(payload.plan, args);
3083
2211
  const nextPlan = patched.plan;
3084
- canvasBySession.set(sid, { enabled: payload.enabled, plan: nextPlan });
2212
+ touchMapLRU(canvasBySession, sid, { enabled: payload.enabled, plan: nextPlan }, MAX_STORED_SESSIONS);
3085
2213
  runBySession.delete(sid);
3086
2214
  publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
3087
2215
  saveStore();
@@ -3095,7 +2223,10 @@ export function apply(ctx) {
3095
2223
  if (patched.taskPatched) patchDoc.task = nextPlan.task;
3096
2224
  if (patched.refsPatched) patchDoc.refs = nextPlan.refs || [];
3097
2225
  const delivered = publishCanvas(scope, sid, patchDoc);
3098
- const warnings = analyzeCanvasWarnings(nextPlan.nodes, nextPlan.edges);
2226
+ const warnings = [
2227
+ ...(Array.isArray(patched.warnings) ? patched.warnings : []),
2228
+ ...analyzeCanvasWarnings(nextPlan.nodes, nextPlan.edges),
2229
+ ];
3099
2230
  const summary = '已更新 ' + patched.touched.length + ' 个节点'
3100
2231
  + (patched.taskPatched ? '、已更新总任务' : '')
3101
2232
  + '、删除 ' + patched.removed.length + ' 个、连线 ' + nextPlan.edges.length + ' 条';
@@ -3354,12 +2485,15 @@ export {
3354
2485
  orderNodes,
3355
2486
  upstreamOf,
3356
2487
  downstreamLabels,
2488
+ parsePayload,
2489
+ clipUpstreamOutput,
3357
2490
  briefFor,
3358
2491
  normalizeBranches,
3359
2492
  normalizeRefs,
3360
2493
  normalizeMaxIterations,
3361
2494
  loopMemberIds,
3362
2495
  validateLoopEdges,
2496
+ parseStrictConditionJson,
3363
2497
  parseConditionDecision,
3364
2498
  withoutEntry,
3365
2499
  analyzeCanvasWarnings,
@@ -3369,6 +2503,12 @@ export {
3369
2503
  sessionIdFromContext,
3370
2504
  buildActiveCanvasContext,
3371
2505
  isPermissionFailure,
2506
+ isTransientFailure,
2507
+ safeSessionFileBase,
2508
+ writeFileAtomic,
2509
+ pruneMapLRU,
2510
+ touchMapLRU,
2511
+ cleanupStaleCanvasFiles,
3372
2512
  buildRunSummarySnapshot,
3373
2513
  abortSessionRun,
3374
2514
  runPlan,