dsh-workflow-canvas 1.5.5 → 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/README.md +2 -1
- package/README.zh.md +2 -1
- package/client.js +1199 -158
- package/docs/DETAIL.md +7 -3
- package/docs/MECHANISM.md +4 -4
- package/docs/MECHANISM.zh.md +4 -4
- package/index.js +568 -1000
- package/lib/graph.js +1068 -0
- package/lib/telemetry.js +250 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +5 -3
- package/skills/workflow-canvas/SKILL.md +1 -0
- package/docs/images/add-node-shift-a.gif +0 -0
- package/docs/images/canvas-demo-zh.png +0 -0
- package/docs/images/canvas-demo.png +0 -0
- package/docs/images/chat-patch-canvas.gif +0 -0
- package/docs/images/condition-switch-run.gif +0 -0
- package/docs/images/connect-and-cut.gif +0 -0
- package/docs/images/lead-pause-resume.gif +0 -0
- package/docs/images/node-condition-en.png +0 -0
- package/docs/images/node-condition-zh.png +0 -0
- package/docs/images/node-config.gif +0 -0
- package/docs/images/node-entry-en.png +0 -0
- package/docs/images/node-entry-zh.png +0 -0
- package/docs/images/node-lead-en.png +0 -0
- package/docs/images/node-lead-zh.png +0 -0
- package/docs/images/node-subagent-en.png +0 -0
- package/docs/images/node-subagent-zh.png +0 -0
- package/docs/images/parallel-and-inspect.gif +0 -0
- package/docs/images/retry-loop-en.png +0 -0
- package/docs/images/retry-loop-zh.png +0 -0
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 {
|
|
19
|
+
import { readFileSync } from 'node:fs';
|
|
20
20
|
import { join } from 'node:path';
|
|
21
21
|
import { fileURLToPath } from 'node:url';
|
|
22
|
-
|
|
23
|
-
|
|
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';
|
|
71
|
+
|
|
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))
|
|
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))
|
|
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,434 +132,41 @@ function saveStore() {
|
|
|
65
132
|
const path = storePath();
|
|
66
133
|
if (!path) return;
|
|
67
134
|
try {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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
|
-
})
|
|
74
|
-
|
|
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
|
-
/**
|
|
81
|
-
function
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
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
|
-
|
|
386
|
-
|
|
387
|
-
|
|
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
|
-
}
|
|
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 textOf(result) {
|
|
461
|
-
// A structured node's canonical value is its parsed object, not the prose.
|
|
462
|
-
if (result && result.structured !== undefined) {
|
|
463
|
-
try {
|
|
464
|
-
return JSON.stringify(result.structured);
|
|
465
|
-
} catch (_e) {
|
|
466
|
-
/* fall through to prose */
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
const blocks = (result && result.output) || [];
|
|
470
|
-
const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
|
|
471
|
-
return text || '[' + ((result && result.stopReason) || 'no-output') + ']';
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
function failed(result) {
|
|
475
|
-
const reason = result && result.stopReason;
|
|
476
|
-
return reason !== undefined && reason !== 'completed';
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
function isEmptyOutput(result) {
|
|
480
|
-
if (result && result.structured !== undefined) return false;
|
|
481
|
-
const blocks = (result && result.output) || [];
|
|
482
|
-
const text = blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('');
|
|
483
|
-
return text.trim().length === 0;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
function buildLoopWarmPrompt(node, loopCtx) {
|
|
487
|
-
const fb = loopCtx && loopCtx.feedback;
|
|
488
|
-
if (!fb) return null;
|
|
489
|
-
const lines = [
|
|
490
|
-
'【第 ' + fb.retry + '/' + fb.max + ' 次回环修正】下游条件节点「' + (fb.sourceLabel || '条件判断') + '」判定上一轮未通过,请结合以下反馈直接在当前会话上下文中修正并输出最新交付结果(无需重复叙述过程):',
|
|
491
|
-
'- 打回理由:' + (fb.reason || '未达预期'),
|
|
492
|
-
];
|
|
493
|
-
if (fb.lastSummary) lines.push('- 上一轮环内参考摘要:\n' + fb.lastSummary);
|
|
494
|
-
if (node.role) lines.push('- 你的职责提醒:' + node.role);
|
|
495
|
-
return lines.join('\n');
|
|
169
|
+
});
|
|
496
170
|
}
|
|
497
171
|
|
|
498
172
|
async function spawnOnce(scope, plan, node, results, parent, signal, route, forcedChild, sid, failedMap, prunedSet, loopCtx) {
|
|
@@ -517,39 +191,42 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
517
191
|
if (model) agentOptions.model = model;
|
|
518
192
|
if (node.reasoning) agentOptions.reasoningEffort = node.reasoning;
|
|
519
193
|
if (Object.keys(agentOptions).length) spec.agentOptions = agentOptions;
|
|
194
|
+
const allowSchema = !(route && route.noSchema);
|
|
520
195
|
if (isCondition) {
|
|
521
196
|
const { branches, isDefaultBinary, multiMatch } = conditionBranches(node);
|
|
522
197
|
spec.agentPreset = 'minimal';
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
required: ['pass', 'reason'],
|
|
531
|
-
additionalProperties: false,
|
|
532
|
-
}
|
|
533
|
-
: {
|
|
534
|
-
type: 'object',
|
|
535
|
-
properties: {
|
|
536
|
-
branches: {
|
|
537
|
-
type: 'array',
|
|
538
|
-
items: { type: 'string', enum: branches.map((b) => b.id) },
|
|
539
|
-
description: multiMatch
|
|
540
|
-
? 'All matching branch ids to execute in parallel (empty array if none match).'
|
|
541
|
-
: 'At most one best-matching branch id (empty array if none match).',
|
|
198
|
+
if (allowSchema) {
|
|
199
|
+
spec.outputSchema = isDefaultBinary
|
|
200
|
+
? {
|
|
201
|
+
type: 'object',
|
|
202
|
+
properties: {
|
|
203
|
+
pass: { type: 'boolean', description: 'true to follow the Yes/Pass branch, false to follow the No/Fail branch.' },
|
|
204
|
+
reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
|
|
542
205
|
},
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
206
|
+
required: ['pass', 'reason'],
|
|
207
|
+
additionalProperties: false,
|
|
208
|
+
}
|
|
209
|
+
: {
|
|
210
|
+
type: 'object',
|
|
211
|
+
properties: {
|
|
212
|
+
branches: {
|
|
213
|
+
type: 'array',
|
|
214
|
+
items: { type: 'string', enum: branches.map((b) => b.id) },
|
|
215
|
+
description: multiMatch
|
|
216
|
+
? 'All matching branch ids to execute in parallel (empty array if none match).'
|
|
217
|
+
: 'At most one best-matching branch id (empty array if none match).',
|
|
218
|
+
},
|
|
219
|
+
reason: { type: 'string', description: 'Concise one-sentence explanation for this routing decision.' },
|
|
220
|
+
},
|
|
221
|
+
required: ['branches', 'reason'],
|
|
222
|
+
additionalProperties: false,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
548
225
|
} else {
|
|
549
226
|
if (node.preset) spec.agentPreset = node.preset;
|
|
550
227
|
const wantsStructured = Boolean(node.structured)
|
|
551
228
|
|| (plan.edges || []).some((e) => e.from === node.id && e.type === 'structured');
|
|
552
|
-
if (wantsStructured) {
|
|
229
|
+
if (wantsStructured && allowSchema) {
|
|
553
230
|
spec.outputSchema = {
|
|
554
231
|
type: 'object',
|
|
555
232
|
additionalProperties: true,
|
|
@@ -572,15 +249,15 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
572
249
|
activation = await scope.subagents.startActivation(withChild);
|
|
573
250
|
} catch (error) {
|
|
574
251
|
const message = String((error && error.message) || error);
|
|
575
|
-
return { ok: false, text: '启动失败:' + message, reason: 'activation-failed' };
|
|
252
|
+
return { ok: false, text: '启动失败:' + message, reason: 'activation-failed', errorDetail: message };
|
|
576
253
|
}
|
|
577
254
|
try {
|
|
578
255
|
if (activation && activation.childId) {
|
|
579
256
|
const cid = String(activation.childId);
|
|
580
|
-
liveChild
|
|
257
|
+
touchMapLRU(liveChild, childKey(node.id), cid, MAX_CHILD_SLOTS);
|
|
581
258
|
// Only overwrite the persisted memory slot when Memory is ON, so a
|
|
582
259
|
// temporary keepSession=false experiment never destroys saved memory.
|
|
583
|
-
if (node.keepSession) childByNode
|
|
260
|
+
if (node.keepSession) touchMapLRU(childByNode, childKey(node.id), cid, MAX_CHILD_SLOTS);
|
|
584
261
|
const activeRec = sid ? activeRunBySession.get(String(sid)) : null;
|
|
585
262
|
if (activeRec && activeRec.childIds) activeRec.childIds.add(cid);
|
|
586
263
|
}
|
|
@@ -589,18 +266,31 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
589
266
|
result = await activation.result;
|
|
590
267
|
} catch (error) {
|
|
591
268
|
const message = String((error && error.message) || error);
|
|
592
|
-
return { ok: false, text: '运行失败:' + message, reason: 'run-failed' };
|
|
269
|
+
return { ok: false, text: '运行失败:' + message, reason: 'run-failed', errorDetail: message };
|
|
593
270
|
}
|
|
594
271
|
const outText = textOf(result);
|
|
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;
|
|
595
284
|
const outcome = {
|
|
596
|
-
ok: !failed(result),
|
|
285
|
+
ok: rescuedDecision ? true : !failed(result),
|
|
597
286
|
text: outText,
|
|
598
|
-
reason: result && result.stopReason,
|
|
599
|
-
|
|
287
|
+
reason: rescuedDecision ? 'completed' : (result && result.stopReason),
|
|
288
|
+
errorDetail: errDetail,
|
|
289
|
+
empty: rescuedDecision ? false : isEmptyOutput(result),
|
|
600
290
|
childId: activation && activation.childId ? String(activation.childId) : '',
|
|
601
291
|
};
|
|
602
292
|
if (isCondition) {
|
|
603
|
-
outcome.decision = parseConditionDecision(result, outText, node);
|
|
293
|
+
outcome.decision = rescuedDecision || parseConditionDecision(result, outText, node);
|
|
604
294
|
}
|
|
605
295
|
return outcome;
|
|
606
296
|
} finally {
|
|
@@ -618,8 +308,8 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
618
308
|
const continued = await run(loopCtx.warmChildId, warmPrompt);
|
|
619
309
|
if (signal && signal.aborted) return continued;
|
|
620
310
|
if (continued.ok) {
|
|
621
|
-
liveChild
|
|
622
|
-
return continued;
|
|
311
|
+
touchMapLRU(liveChild, childKey(node.id), continued.childId || loopCtx.warmChildId, MAX_CHILD_SLOTS);
|
|
312
|
+
return { ...continued, warmReused: true };
|
|
623
313
|
}
|
|
624
314
|
if (continued.reason !== 'activation-failed') {
|
|
625
315
|
return continued;
|
|
@@ -633,7 +323,7 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
633
323
|
const continued = await run(forcedChild);
|
|
634
324
|
if (signal && signal.aborted) return continued;
|
|
635
325
|
if (continued.ok) {
|
|
636
|
-
liveChild
|
|
326
|
+
touchMapLRU(liveChild, childKey(node.id), forcedChild, MAX_CHILD_SLOTS);
|
|
637
327
|
return continued;
|
|
638
328
|
}
|
|
639
329
|
if (continued.reason !== 'activation-failed') {
|
|
@@ -665,14 +355,15 @@ async function spawnOnce(scope, plan, node, results, parent, signal, route, forc
|
|
|
665
355
|
const started = await run(undefined);
|
|
666
356
|
if (node.keepSession && started.ok) {
|
|
667
357
|
const current = childByNode.get(childKey(node.id));
|
|
668
|
-
if (current) liveChild
|
|
358
|
+
if (current) touchMapLRU(liveChild, childKey(node.id), current, MAX_CHILD_SLOTS);
|
|
669
359
|
}
|
|
670
360
|
return started;
|
|
671
361
|
}
|
|
672
362
|
|
|
673
363
|
async function spawnNode(scope, plan, node, results, parent, signal, sid, failedMap, prunedSet, loopCtx) {
|
|
364
|
+
const primaryModel = formatModelLabel(node.provider, node.model);
|
|
674
365
|
if (signal && signal.aborted) {
|
|
675
|
-
return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '' };
|
|
366
|
+
return { ok: false, empty: false, reason: 'aborted', text: '已取消', childId: '', modelUsed: primaryModel, fallbackUsed: false, sessionContinued: false };
|
|
676
367
|
}
|
|
677
368
|
const continueFrom = forwardEdgesOf(plan.edges || [])
|
|
678
369
|
.filter((e) => e.to === node.id && e.type === 'session-ref' && !(prunedSet && prunedSet.has(e.from)))
|
|
@@ -684,493 +375,126 @@ async function spawnNode(scope, plan, node, results, parent, signal, sid, failed
|
|
|
684
375
|
const continued = await spawnOnce(scope, plan, node, results, parent, signal, undefined, continueFrom, sid, failedMap, prunedSet, loopCtx);
|
|
685
376
|
if (signal && signal.aborted) return continued;
|
|
686
377
|
if (continued.ok) {
|
|
687
|
-
const out = {
|
|
378
|
+
const out = {
|
|
379
|
+
ok: true,
|
|
380
|
+
empty: Boolean(continued.empty),
|
|
381
|
+
text: continued.text + '\n(已在上游会话中继续)',
|
|
382
|
+
childId: continued.childId || continueFrom,
|
|
383
|
+
modelUsed: primaryModel,
|
|
384
|
+
fallbackUsed: false,
|
|
385
|
+
sessionContinued: true,
|
|
386
|
+
};
|
|
688
387
|
if (continued.decision) out.decision = continued.decision;
|
|
689
388
|
return out;
|
|
690
389
|
}
|
|
691
390
|
}
|
|
692
391
|
|
|
693
|
-
|
|
392
|
+
let first = await spawnOnce(scope, plan, node, results, parent, signal, undefined, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
694
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
|
+
}
|
|
412
|
+
// Many models/proxies reject strict `outputSchema` (`json_schema`) with stopReason='error'.
|
|
413
|
+
// For condition/structured nodes, automatically retry once on the same model without outputSchema
|
|
414
|
+
// so `parseConditionDecision` can parse plain-text JSON before giving up or falling back.
|
|
415
|
+
const usedSchema = node.kind === 'condition'
|
|
416
|
+
|| Boolean(node.structured)
|
|
417
|
+
|| (plan.edges || []).some((e) => e.from === node.id && e.type === 'structured');
|
|
418
|
+
if (!first.ok && !transientRetried && usedSchema && first.reason !== 'activation-failed' && first.reason !== 'aborted' && !isPermissionFailure(first)) {
|
|
419
|
+
const plainRetry = await spawnOnce(scope, plan, node, results, parent, signal, { noSchema: true }, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
420
|
+
if (signal && signal.aborted) return plainRetry;
|
|
421
|
+
if (plainRetry.ok) {
|
|
422
|
+
first = plainRetry;
|
|
423
|
+
} else if (plainRetry.errorDetail && !first.errorDetail) {
|
|
424
|
+
first = plainRetry;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
695
427
|
if (first.ok) {
|
|
696
|
-
const out = {
|
|
428
|
+
const out = {
|
|
429
|
+
ok: true,
|
|
430
|
+
empty: Boolean(first.empty),
|
|
431
|
+
text: first.text,
|
|
432
|
+
childId: first.childId || '',
|
|
433
|
+
modelUsed: primaryModel,
|
|
434
|
+
fallbackUsed: false,
|
|
435
|
+
sessionContinued: Boolean(first.warmReused),
|
|
436
|
+
};
|
|
697
437
|
if (first.decision) out.decision = first.decision;
|
|
698
438
|
return out;
|
|
699
439
|
}
|
|
700
440
|
if (!node.fallbackModel && !node.fallbackProvider) {
|
|
701
441
|
const reason = first.reason || 'unknown';
|
|
702
|
-
|
|
442
|
+
const detail = first.errorDetail || '';
|
|
443
|
+
const modelTag = primaryModel ? ('模型 ' + primaryModel) : '默认模型';
|
|
444
|
+
const suffix = detail ? (reason + ' — ' + detail) : reason;
|
|
445
|
+
return {
|
|
446
|
+
ok: false,
|
|
447
|
+
empty: false,
|
|
448
|
+
reason,
|
|
449
|
+
errorDetail: detail,
|
|
450
|
+
text: first.text + '\n(' + modelTag + ' 执行失败:' + suffix + ')',
|
|
451
|
+
childId: first.childId || '',
|
|
452
|
+
modelUsed: primaryModel,
|
|
453
|
+
fallbackUsed: false,
|
|
454
|
+
sessionContinued: false,
|
|
455
|
+
};
|
|
703
456
|
}
|
|
704
|
-
const
|
|
457
|
+
const fallbackLabel = formatModelLabel(node.fallbackProvider || node.provider, node.fallbackModel || node.model);
|
|
458
|
+
let retry = await spawnOnce(scope, plan, node, results, parent, signal, {
|
|
705
459
|
provider: node.fallbackProvider,
|
|
706
460
|
model: node.fallbackModel,
|
|
707
461
|
}, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
462
|
+
if (signal && signal.aborted) return retry;
|
|
463
|
+
if (!retry.ok && usedSchema && retry.reason !== 'activation-failed' && retry.reason !== 'aborted' && !isPermissionFailure(retry)) {
|
|
464
|
+
const plainFallback = await spawnOnce(scope, plan, node, results, parent, signal, {
|
|
465
|
+
provider: node.fallbackProvider,
|
|
466
|
+
model: node.fallbackModel,
|
|
467
|
+
noSchema: true,
|
|
468
|
+
}, undefined, sid, failedMap, prunedSet, loopCtx);
|
|
469
|
+
if (signal && signal.aborted) return plainFallback;
|
|
470
|
+
if (plainFallback.ok || (plainFallback.errorDetail && !retry.errorDetail)) retry = plainFallback;
|
|
471
|
+
}
|
|
708
472
|
if (retry.ok) {
|
|
709
|
-
const out = {
|
|
473
|
+
const out = {
|
|
474
|
+
ok: true,
|
|
475
|
+
empty: Boolean(retry.empty),
|
|
476
|
+
text: retry.text + '\n(已用备用模型重试成功)',
|
|
477
|
+
childId: retry.childId || '',
|
|
478
|
+
modelUsed: fallbackLabel,
|
|
479
|
+
fallbackUsed: true,
|
|
480
|
+
sessionContinued: Boolean(retry.warmReused),
|
|
481
|
+
};
|
|
710
482
|
if (retry.decision) out.decision = retry.decision;
|
|
711
483
|
return out;
|
|
712
484
|
}
|
|
713
485
|
const reason = retry.reason || 'unknown';
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
/** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
|
|
718
|
-
function reachableFrom(plan) {
|
|
719
|
-
const adj = new Map();
|
|
720
|
-
for (const e of forwardEdgesOf(plan && plan.edges)) {
|
|
721
|
-
if (!e || !e.from || !e.to) continue;
|
|
722
|
-
if (!adj.has(e.from)) adj.set(e.from, []);
|
|
723
|
-
adj.get(e.from).push(e.to);
|
|
724
|
-
}
|
|
725
|
-
const set = new Set(['lead']);
|
|
726
|
-
const queue = ['lead'];
|
|
727
|
-
for (let i = 0; i < queue.length; i += 1) {
|
|
728
|
-
const cur = queue[i];
|
|
729
|
-
for (const next of adj.get(cur) || []) {
|
|
730
|
-
if (!set.has(next)) { set.add(next); queue.push(next); }
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
return set;
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
/**
|
|
737
|
-
* Classify inactive nodes that are rendered dashed on the canvas and skipped at run time:
|
|
738
|
-
* - unreachable orphans
|
|
739
|
-
* - solo chained Leads (zero reachable subagent upstream and blank role)
|
|
740
|
-
* - dangling dead-end subagents (zero outgoing edges while an active non-ancestor downstream Lead exists)
|
|
741
|
-
*/
|
|
742
|
-
function inactiveNodeSets(nodes, edges) {
|
|
743
|
-
const list = withoutEntry(nodes);
|
|
744
|
-
const linkList = Array.isArray(edges) ? edges : [];
|
|
745
|
-
const fwdLinks = forwardEdgesOf(linkList);
|
|
746
|
-
const reachable = reachableFrom({ edges: fwdLinks });
|
|
747
|
-
const byId = new Map(list.map((n) => [n.id, n]));
|
|
748
|
-
|
|
749
|
-
const soloLeads = new Set();
|
|
750
|
-
for (const n of list) {
|
|
751
|
-
if (n.kind !== 'lead' || !reachable.has(n.id)) continue;
|
|
752
|
-
const hasAgentUp = fwdLinks.some((e) => {
|
|
753
|
-
if (!e || e.to !== n.id || !reachable.has(e.from) || e.from === 'lead') return false;
|
|
754
|
-
const src = byId.get(e.from);
|
|
755
|
-
return Boolean(src && src.kind !== 'lead');
|
|
756
|
-
});
|
|
757
|
-
const hasRole = Boolean(String(n.role || '').trim());
|
|
758
|
-
if (!hasAgentUp && !hasRole) soloLeads.add(n.id);
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
const deadEnds = new Set();
|
|
762
|
-
const activeLeads = list.filter((n) => n.kind === 'lead' && reachable.has(n.id) && !soloLeads.has(n.id));
|
|
763
|
-
if (activeLeads.length) {
|
|
764
|
-
const hasOut = new Set(linkList.map((e) => e.from));
|
|
765
|
-
const parents = new Map();
|
|
766
|
-
for (const e of fwdLinks) {
|
|
767
|
-
if (!parents.has(e.to)) parents.set(e.to, []);
|
|
768
|
-
parents.get(e.to).push(e.from);
|
|
769
|
-
}
|
|
770
|
-
const ancestorsOf = (id) => {
|
|
771
|
-
const seen = new Set();
|
|
772
|
-
const stack = [id];
|
|
773
|
-
while (stack.length) {
|
|
774
|
-
const cur = stack.pop();
|
|
775
|
-
for (const p of parents.get(cur) || []) {
|
|
776
|
-
if (!seen.has(p)) { seen.add(p); stack.push(p); }
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
return seen;
|
|
780
|
-
};
|
|
781
|
-
for (const n of list) {
|
|
782
|
-
if (n.kind === 'lead' || !reachable.has(n.id) || hasOut.has(n.id)) continue;
|
|
783
|
-
const anc = ancestorsOf(n.id);
|
|
784
|
-
if (activeLeads.some((ln) => !anc.has(ln.id))) deadEnds.add(n.id);
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
return { reachable, soloLeads, deadEnds };
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
/**
|
|
791
|
-
* Validate controlled loop edges: each loop edge must leave a condition node, target a strict
|
|
792
|
-
* forward-path ancestor (never entry Lead), and not overlap/cross another loop edge's body.
|
|
793
|
-
*/
|
|
794
|
-
function validateLoopEdges(nodes, edges) {
|
|
795
|
-
const list = withoutEntry(nodes);
|
|
796
|
-
const byId = new Map(list.map((n) => [n.id, n]));
|
|
797
|
-
const linkList = Array.isArray(edges) ? edges : [];
|
|
798
|
-
const loopEdges = linkList.filter((e) => isLoopEdge(e));
|
|
799
|
-
const errors = [];
|
|
800
|
-
const seenMembers = new Map();
|
|
801
|
-
for (const le of loopEdges) {
|
|
802
|
-
const src = byId.get(le.from);
|
|
803
|
-
const dst = byId.get(le.to);
|
|
804
|
-
if (!src || src.kind !== 'condition') {
|
|
805
|
-
errors.push('回环边起点必须是条件判断节点(' + le.from + ' → ' + le.to + ')。');
|
|
806
|
-
continue;
|
|
807
|
-
}
|
|
808
|
-
if (!dst || le.to === 'lead') {
|
|
809
|
-
errors.push('回环边不能指向入口 Lead 或不存在的节点(' + le.from + ' → ' + le.to + ')。');
|
|
810
|
-
continue;
|
|
811
|
-
}
|
|
812
|
-
const members = loopMemberIds(list, linkList, le);
|
|
813
|
-
if (!members.size) {
|
|
814
|
-
errors.push('回环边目标「' + (dst.label || dst.id) + '」不是「' + (src.label || src.id) + '」的上游祖先节点。');
|
|
815
|
-
continue;
|
|
816
|
-
}
|
|
817
|
-
let overlap = false;
|
|
818
|
-
for (const mid of members) {
|
|
819
|
-
if (seenMembers.has(mid)) { overlap = true; break; }
|
|
820
|
-
}
|
|
821
|
-
if (overlap) {
|
|
822
|
-
errors.push('检测到交叉或嵌套回环(涉及节点「' + (dst.label || dst.id) + '」),暂不支持交叉回环。');
|
|
823
|
-
continue;
|
|
824
|
-
}
|
|
825
|
-
for (const mid of members) seenMembers.set(mid, le);
|
|
826
|
-
}
|
|
827
|
-
return errors;
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
/**
|
|
831
|
-
* Detect structural warnings on a canvas plan (all three classes are rendered
|
|
832
|
-
* dashed on the canvas and skipped at run time):
|
|
833
|
-
* 1. Unreachable nodes.
|
|
834
|
-
* 2. Solo chained Lead nodes with zero subagent upstream and blank role.
|
|
835
|
-
* 3. Dangling dead-end subagent nodes with zero outgoing edges.
|
|
836
|
-
* 4. Invalid/crossing loop edges or loop conditions with no forward exit.
|
|
837
|
-
*/
|
|
838
|
-
function analyzeCanvasWarnings(nodes, edges) {
|
|
839
|
-
const list = withoutEntry(nodes);
|
|
840
|
-
const linkList = Array.isArray(edges) ? edges : [];
|
|
841
|
-
const warnings = [];
|
|
842
|
-
if (!list.length) return warnings;
|
|
843
|
-
|
|
844
|
-
const { reachable, soloLeads, deadEnds } = inactiveNodeSets(list, linkList);
|
|
845
|
-
const orphans = list.filter((n) => !reachable.has(n.id));
|
|
846
|
-
if (orphans.length) {
|
|
847
|
-
warnings.push('以下节点未从入口 Lead 连通,运行时会被跳过:'
|
|
848
|
-
+ orphans.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
849
|
-
}
|
|
850
|
-
const soloList = list.filter((n) => soloLeads.has(n.id));
|
|
851
|
-
if (soloList.length) {
|
|
852
|
-
warnings.push('以下 Lead 节点未连入子代理且未填写分工(role),运行时不生效:'
|
|
853
|
-
+ soloList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
854
|
-
}
|
|
855
|
-
const deadList = list.filter((n) => deadEnds.has(n.id));
|
|
856
|
-
if (deadList.length) {
|
|
857
|
-
warnings.push('以下子代理节点没有出边,产出未连入下游或终审 Lead,运行时不生效:'
|
|
858
|
-
+ deadList.map((n) => (n.label || n.id) + '(' + n.id + ')').join('、'));
|
|
859
|
-
}
|
|
860
|
-
for (const err of validateLoopEdges(list, linkList)) warnings.push(err);
|
|
861
|
-
// Warn if a non-exit node inside a loop has a forward edge leaking outside the loop
|
|
862
|
-
// (that outside branch starts on round 1 and will not re-run on retry rounds).
|
|
863
|
-
const fwdLinks = forwardEdgesOf(linkList);
|
|
864
|
-
const byId = new Map(list.map((n) => [n.id, n]));
|
|
865
|
-
for (const le of linkList) {
|
|
866
|
-
if (!isLoopEdge(le)) continue;
|
|
867
|
-
const members = loopMemberIds(list, linkList, le);
|
|
868
|
-
if (!members.size) continue;
|
|
869
|
-
const leaked = [];
|
|
870
|
-
for (const e of fwdLinks) {
|
|
871
|
-
if (e.from !== le.from && members.has(e.from) && !members.has(e.to)) {
|
|
872
|
-
const src = byId.get(e.from);
|
|
873
|
-
const dst = byId.get(e.to);
|
|
874
|
-
leaked.push(((src && src.label) || e.from) + ' → ' + ((dst && dst.label) || e.to));
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
if (leaked.length) {
|
|
878
|
-
warnings.push('回环内部节点存在绕过条件裁判的旁路连线(' + leaked.join('、') + '),回环重试时这些环外节点不会重跑。');
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
return warnings;
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
/**
|
|
885
|
-
* Turn a model-authored sketch into a canvas document: assign ids, ensure one
|
|
886
|
-
* connected entry Lead, and lay the graph out in columns by depth.
|
|
887
|
-
*/
|
|
888
|
-
function normalizeCanvas(args) {
|
|
889
|
-
const rawNodes = Array.isArray(args && args.nodes) ? args.nodes : [];
|
|
890
|
-
const rawEdges = Array.isArray(args && args.edges) ? args.edges : [];
|
|
891
|
-
if (!rawNodes.length) return { error: '至少需要一个节点' };
|
|
892
|
-
|
|
893
|
-
const nodes = [];
|
|
894
|
-
const idByRef = new Map();
|
|
895
|
-
const usedIds = new Set();
|
|
896
|
-
let counter = 0;
|
|
897
|
-
let hasExplicitLead = false;
|
|
898
|
-
for (const raw of rawNodes) {
|
|
899
|
-
if (!raw || typeof raw !== 'object') continue;
|
|
900
|
-
counter += 1;
|
|
901
|
-
const kind = normalizeKind(raw.kind);
|
|
902
|
-
const wantsEntry = !hasExplicitLead && (raw.id === 'lead' || (raw.entry === true && kind === 'lead'));
|
|
903
|
-
let id = wantsEntry
|
|
904
|
-
? 'lead'
|
|
905
|
-
: (typeof raw.id === 'string' && raw.id && raw.id !== 'lead' ? raw.id : 'n' + counter);
|
|
906
|
-
if (usedIds.has(id)) {
|
|
907
|
-
let suffix = 2;
|
|
908
|
-
while (usedIds.has(id + '_' + suffix)) suffix += 1;
|
|
909
|
-
id = id + '_' + suffix;
|
|
910
|
-
}
|
|
911
|
-
usedIds.add(id);
|
|
912
|
-
if (id === 'lead') hasExplicitLead = true;
|
|
913
|
-
const defaultLabel = kind === 'lead'
|
|
914
|
-
? 'Lead 步骤 ' + counter
|
|
915
|
-
: (kind === 'condition' ? '条件判断 ' + counter : 'Node ' + counter);
|
|
916
|
-
const label = String(raw.label || defaultLabel);
|
|
917
|
-
const nodeObj = {
|
|
918
|
-
id,
|
|
919
|
-
kind: id === 'lead' ? 'lead' : kind,
|
|
920
|
-
label,
|
|
921
|
-
role: String(raw.role || ''),
|
|
922
|
-
task: String(raw.task || ''),
|
|
923
|
-
provider: String(raw.provider || ''),
|
|
924
|
-
model: String(raw.model || ''),
|
|
925
|
-
reasoning: String(raw.reasoning || ''),
|
|
926
|
-
preset: (id === 'lead' ? '' : (kind === 'condition' ? 'minimal' : String(raw.preset || ''))),
|
|
927
|
-
structured: Boolean(raw.structured),
|
|
928
|
-
keepSession: Boolean(raw.keepSession),
|
|
929
|
-
fallbackModel: String(raw.fallbackModel || ''),
|
|
930
|
-
fallbackProvider: String(raw.fallbackProvider || ''),
|
|
931
|
-
x: 0,
|
|
932
|
-
y: 0,
|
|
933
|
-
};
|
|
934
|
-
const normRefs = normalizeRefs(raw.refs);
|
|
935
|
-
if (normRefs) nodeObj.refs = normRefs;
|
|
936
|
-
if (nodeObj.kind === 'condition') {
|
|
937
|
-
const customBranches = normalizeBranches(raw.branches);
|
|
938
|
-
if (customBranches) nodeObj.branches = customBranches;
|
|
939
|
-
if (raw.multiMatch === true) nodeObj.multiMatch = true;
|
|
940
|
-
}
|
|
941
|
-
nodes.push(nodeObj);
|
|
942
|
-
if (raw.ref && !idByRef.has(String(raw.ref))) idByRef.set(String(raw.ref), id);
|
|
943
|
-
if (raw.id && !idByRef.has(String(raw.id))) idByRef.set(String(raw.id), id);
|
|
944
|
-
idByRef.set(id, id);
|
|
945
|
-
}
|
|
946
|
-
if (!nodes.length) return { error: '节点都无效' };
|
|
947
|
-
|
|
948
|
-
const ids = new Set(nodes.map((n) => n.id));
|
|
949
|
-
const edges = [];
|
|
950
|
-
for (const raw of rawEdges) {
|
|
951
|
-
if (!raw || typeof raw !== 'object') continue;
|
|
952
|
-
const from = idByRef.get(String(raw.from)) || String(raw.from);
|
|
953
|
-
const to = idByRef.get(String(raw.to)) || String(raw.to);
|
|
954
|
-
if ((from !== 'lead' && !ids.has(from)) || !ids.has(to) || from === to || to === 'lead') continue;
|
|
955
|
-
const type = ['prompt', 'structured', 'session-ref'].includes(raw.type) ? raw.type : 'prompt';
|
|
956
|
-
const branch = normalizeBranch(raw.branch);
|
|
957
|
-
const edgeObj = { id: 'e' + edges.length, from, to, type };
|
|
958
|
-
if (branch) edgeObj.branch = branch;
|
|
959
|
-
if (raw.loop === true) {
|
|
960
|
-
edgeObj.loop = true;
|
|
961
|
-
edgeObj.maxIterations = normalizeMaxIterations(raw.maxIterations);
|
|
962
|
-
}
|
|
963
|
-
edges.push(edgeObj);
|
|
964
|
-
}
|
|
965
|
-
|
|
966
|
-
let entry = nodes.find((n) => n.id === 'lead');
|
|
967
|
-
if (!entry) {
|
|
968
|
-
// If the caller hand-authored a root Lead node (no incoming edges, has outgoing edges)
|
|
969
|
-
// and didn't wire from id='lead', promote it to entry Lead instead of duplicating it.
|
|
970
|
-
const hasLeadEdge = edges.some((e) => e.from === 'lead');
|
|
971
|
-
const inSet = new Set(edges.map((e) => e.to));
|
|
972
|
-
const outSet = new Set(edges.map((e) => e.from));
|
|
973
|
-
const rootLead = !hasLeadEdge
|
|
974
|
-
? nodes.find((n) => n.kind === 'lead' && !inSet.has(n.id) && outSet.has(n.id))
|
|
975
|
-
: null;
|
|
976
|
-
if (rootLead) {
|
|
977
|
-
const oldId = rootLead.id;
|
|
978
|
-
rootLead.id = 'lead';
|
|
979
|
-
rootLead.task = rootLead.task || String(args.task || '') || rootLead.role;
|
|
980
|
-
rootLead.role = '';
|
|
981
|
-
for (const e of edges) {
|
|
982
|
-
if (e.from === oldId) e.from = 'lead';
|
|
983
|
-
}
|
|
984
|
-
entry = rootLead;
|
|
985
|
-
} else {
|
|
986
|
-
entry = {
|
|
987
|
-
id: 'lead', kind: 'lead', label: 'Lead(本对话)', role: '',
|
|
988
|
-
task: String(args.task || ''), provider: '', model: '', reasoning: '',
|
|
989
|
-
preset: '', structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
|
|
990
|
-
x: 0, y: 0,
|
|
991
|
-
};
|
|
992
|
-
nodes.unshift(entry);
|
|
993
|
-
}
|
|
994
|
-
} else if (!entry.task) {
|
|
995
|
-
entry.task = String(args.task || '') || entry.role;
|
|
996
|
-
}
|
|
997
|
-
const topRefs = normalizeRefs(args && args.refs);
|
|
998
|
-
if (topRefs && !entry.refs) entry.refs = topRefs;
|
|
999
|
-
|
|
1000
|
-
// If entry Lead still has no outgoing edges, auto-wire it to all root nodes so
|
|
1001
|
-
// a freshly generated canvas is never dead/unreachable on arrival.
|
|
1002
|
-
if (!edges.some((e) => e.from === 'lead')) {
|
|
1003
|
-
const hasIn = new Set(edges.map((e) => e.to));
|
|
1004
|
-
const roots = nodes.filter((n) => n.id !== 'lead' && !hasIn.has(n.id));
|
|
1005
|
-
for (const root of roots) {
|
|
1006
|
-
edges.push({ id: 'e' + edges.length, from: 'lead', to: root.id, type: 'prompt' });
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
|
|
1011
|
-
for (const node of nodes) {
|
|
1012
|
-
if (structuredSources.has(node.id)) node.structured = true;
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
// Layout: depth of the longest path from the entry (ignoring controlled loop back-edges).
|
|
1016
|
-
const depth = new Map(nodes.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
|
|
1017
|
-
for (let pass = 0; pass < nodes.length; pass += 1) {
|
|
1018
|
-
let changed = false;
|
|
1019
|
-
for (const e of forwardEdgesOf(edges)) {
|
|
1020
|
-
if (e.to === 'lead') continue;
|
|
1021
|
-
const next = Math.min(nodes.length, depth.get(e.from) + 1);
|
|
1022
|
-
if (next > depth.get(e.to)) { depth.set(e.to, next); changed = true; }
|
|
1023
|
-
}
|
|
1024
|
-
if (!changed) break;
|
|
1025
|
-
}
|
|
1026
|
-
const perColumn = new Map();
|
|
1027
|
-
for (const node of nodes) {
|
|
1028
|
-
const level = depth.get(node.id) || 0;
|
|
1029
|
-
const row = perColumn.get(level) || 0;
|
|
1030
|
-
perColumn.set(level, row + 1);
|
|
1031
|
-
node.x = 60 + level * 300;
|
|
1032
|
-
node.y = 80 + row * 260;
|
|
1033
|
-
}
|
|
1034
|
-
|
|
486
|
+
const retryDetail = retry.errorDetail || '';
|
|
487
|
+
const suffix = retryDetail ? (reason + ' — ' + retryDetail) : reason;
|
|
1035
488
|
return {
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
* edges without losing untouched nodes. Preserves `'lead'` as a valid edge
|
|
1046
|
-
* source so newly added branches can wire directly from the entry Lead.
|
|
1047
|
-
*/
|
|
1048
|
-
function applyPatch(plan, args) {
|
|
1049
|
-
const nodes = withoutEntry(plan.nodes).map((n) => ({ ...n }));
|
|
1050
|
-
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
1051
|
-
const ALLOWED = ['label', 'role', 'provider', 'model', 'reasoning', 'preset', 'keepSession', 'memoryChildId', 'structured', 'fallbackModel', 'fallbackProvider'];
|
|
1052
|
-
const touched = [];
|
|
1053
|
-
for (const patch of args && Array.isArray(args.nodes) ? args.nodes : []) {
|
|
1054
|
-
// 'lead' is the reserved entry node and is never edited here.
|
|
1055
|
-
if (!patch || typeof patch.id !== 'string' || patch.id === 'lead') continue;
|
|
1056
|
-
const existing = byId.get(patch.id);
|
|
1057
|
-
if (existing) {
|
|
1058
|
-
for (const key of ALLOWED) {
|
|
1059
|
-
if (patch[key] !== undefined) existing[key] = patch[key];
|
|
1060
|
-
}
|
|
1061
|
-
if (patch.kind !== undefined) existing.kind = normalizeKind(patch.kind);
|
|
1062
|
-
if (existing.kind === 'condition') existing.preset = 'minimal';
|
|
1063
|
-
if (patch.branches !== undefined) {
|
|
1064
|
-
const nb = normalizeBranches(patch.branches);
|
|
1065
|
-
if (nb) existing.branches = nb;
|
|
1066
|
-
else delete existing.branches;
|
|
1067
|
-
}
|
|
1068
|
-
if (patch.multiMatch !== undefined) {
|
|
1069
|
-
if (patch.multiMatch) existing.multiMatch = true;
|
|
1070
|
-
else delete existing.multiMatch;
|
|
1071
|
-
}
|
|
1072
|
-
if (patch.refs !== undefined) {
|
|
1073
|
-
const nr = normalizeRefs(patch.refs);
|
|
1074
|
-
if (nr) existing.refs = nr;
|
|
1075
|
-
else delete existing.refs;
|
|
1076
|
-
}
|
|
1077
|
-
touched.push(patch.id);
|
|
1078
|
-
} else {
|
|
1079
|
-
const created = {
|
|
1080
|
-
id: patch.id,
|
|
1081
|
-
kind: normalizeKind(patch.kind),
|
|
1082
|
-
label: patch.label || patch.id,
|
|
1083
|
-
role: '', provider: '', model: '', reasoning: '', preset: 'standard',
|
|
1084
|
-
structured: false, keepSession: false, fallbackModel: '', fallbackProvider: '',
|
|
1085
|
-
};
|
|
1086
|
-
for (const key of ALLOWED) {
|
|
1087
|
-
if (patch[key] !== undefined) created[key] = patch[key];
|
|
1088
|
-
}
|
|
1089
|
-
created.preset = (created.kind === 'condition' || created.preset === 'minimal') ? 'minimal' : 'standard';
|
|
1090
|
-
if (created.kind === 'condition' && patch.branches !== undefined) {
|
|
1091
|
-
const nb = normalizeBranches(patch.branches);
|
|
1092
|
-
if (nb) created.branches = nb;
|
|
1093
|
-
}
|
|
1094
|
-
if (created.kind === 'condition' && patch.multiMatch === true) {
|
|
1095
|
-
created.multiMatch = true;
|
|
1096
|
-
}
|
|
1097
|
-
if (patch.refs !== undefined) {
|
|
1098
|
-
const nr = normalizeRefs(patch.refs);
|
|
1099
|
-
if (nr) created.refs = nr;
|
|
1100
|
-
}
|
|
1101
|
-
nodes.push(created);
|
|
1102
|
-
byId.set(created.id, created);
|
|
1103
|
-
touched.push(created.id);
|
|
1104
|
-
}
|
|
1105
|
-
}
|
|
1106
|
-
const removed = new Set(Array.isArray(args && args.removeNodes) ? args.removeNodes : []);
|
|
1107
|
-
removed.delete('lead');
|
|
1108
|
-
const keptNodes = nodes.filter((n) => !removed.has(n.id));
|
|
1109
|
-
const keptIds = new Set(keptNodes.map((n) => n.id));
|
|
1110
|
-
const rawRemoveEdges = Array.isArray(args && args.removeEdges) ? args.removeEdges : [];
|
|
1111
|
-
const matchesRemovedEdge = (edge) => rawRemoveEdges.some((r) => {
|
|
1112
|
-
if (!r || String(r.from) !== edge.from || String(r.to) !== edge.to) return false;
|
|
1113
|
-
if (r.type && r.type !== edge.type) return false;
|
|
1114
|
-
const rb = normalizeBranch(r.branch);
|
|
1115
|
-
if (rb && rb !== normalizeBranch(edge.branch)) return false;
|
|
1116
|
-
return true;
|
|
1117
|
-
});
|
|
1118
|
-
let edges = (Array.isArray(plan.edges) ? plan.edges : [])
|
|
1119
|
-
.filter((e) => !matchesRemovedEdge(e) && !removed.has(e.from) && !removed.has(e.to))
|
|
1120
|
-
.map((e) => ({ ...e }));
|
|
1121
|
-
for (const edge of Array.isArray(args && args.edges) ? args.edges : []) {
|
|
1122
|
-
if (!edge || typeof edge.from !== 'string' || typeof edge.to !== 'string') continue;
|
|
1123
|
-
if (edge.from === edge.to || edge.to === 'lead') continue;
|
|
1124
|
-
const validFrom = edge.from === 'lead' || keptIds.has(edge.from);
|
|
1125
|
-
const validTo = keptIds.has(edge.to);
|
|
1126
|
-
if (!validFrom || !validTo) continue;
|
|
1127
|
-
const type = ['prompt', 'structured', 'session-ref'].includes(edge.type) ? edge.type : 'prompt';
|
|
1128
|
-
const branch = normalizeBranch(edge.branch);
|
|
1129
|
-
const existingEdge = edges.find((e) => e.from === edge.from && e.to === edge.to && e.type === type && normalizeBranch(e.branch) === branch);
|
|
1130
|
-
if (existingEdge) {
|
|
1131
|
-
if (edge.loop === true) {
|
|
1132
|
-
existingEdge.loop = true;
|
|
1133
|
-
existingEdge.maxIterations = normalizeMaxIterations(edge.maxIterations !== undefined ? edge.maxIterations : existingEdge.maxIterations);
|
|
1134
|
-
} else if (edge.loop === false) {
|
|
1135
|
-
delete existingEdge.loop;
|
|
1136
|
-
delete existingEdge.maxIterations;
|
|
1137
|
-
}
|
|
1138
|
-
continue;
|
|
1139
|
-
}
|
|
1140
|
-
const nextEdge = { from: edge.from, to: edge.to, type };
|
|
1141
|
-
if (branch) nextEdge.branch = branch;
|
|
1142
|
-
if (edge.loop === true) {
|
|
1143
|
-
nextEdge.loop = true;
|
|
1144
|
-
nextEdge.maxIterations = normalizeMaxIterations(edge.maxIterations);
|
|
1145
|
-
}
|
|
1146
|
-
edges.push(nextEdge);
|
|
1147
|
-
}
|
|
1148
|
-
const structuredSources = new Set(edges.filter((e) => e.type === 'structured').map((e) => e.from));
|
|
1149
|
-
for (const node of keptNodes) {
|
|
1150
|
-
node.structured = structuredSources.has(node.id);
|
|
1151
|
-
}
|
|
1152
|
-
const taskPatched = typeof (args && args.task) === 'string';
|
|
1153
|
-
const nextTask = taskPatched ? args.task : String(plan.task || '');
|
|
1154
|
-
const refsPatched = args && args.refs !== undefined;
|
|
1155
|
-
const nextRefs = refsPatched ? normalizeRefs(args.refs) : normalizeRefs(plan.refs);
|
|
1156
|
-
const nextPlan = { ...plan, task: nextTask, nodes: keptNodes, edges };
|
|
1157
|
-
if (nextRefs) nextPlan.refs = nextRefs;
|
|
1158
|
-
else delete nextPlan.refs;
|
|
1159
|
-
return {
|
|
1160
|
-
plan: nextPlan,
|
|
1161
|
-
touched,
|
|
1162
|
-
taskPatched,
|
|
1163
|
-
refsPatched,
|
|
1164
|
-
removed: Array.from(removed),
|
|
1165
|
-
removeEdges: rawRemoveEdges
|
|
1166
|
-
.filter((r) => r && typeof r.from === 'string' && typeof r.to === 'string')
|
|
1167
|
-
.map((r) => {
|
|
1168
|
-
const item = { from: r.from, to: r.to };
|
|
1169
|
-
if (r.type) item.type = r.type;
|
|
1170
|
-
const rb = normalizeBranch(r.branch);
|
|
1171
|
-
if (rb) item.branch = rb;
|
|
1172
|
-
return item;
|
|
1173
|
-
}),
|
|
489
|
+
ok: false,
|
|
490
|
+
empty: false,
|
|
491
|
+
reason,
|
|
492
|
+
errorDetail: retryDetail,
|
|
493
|
+
text: retry.text + '\n(备用模型 ' + (fallbackLabel || '默认') + ' 重试仍失败:' + suffix + ')',
|
|
494
|
+
childId: retry.childId || first.childId || '',
|
|
495
|
+
modelUsed: fallbackLabel,
|
|
496
|
+
fallbackUsed: true,
|
|
497
|
+
sessionContinued: false,
|
|
1174
498
|
};
|
|
1175
499
|
}
|
|
1176
500
|
|
|
@@ -1187,39 +511,67 @@ function resolveSessionsService(scope) {
|
|
|
1187
511
|
}
|
|
1188
512
|
}
|
|
1189
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
|
+
|
|
1190
525
|
function publishCanvas(scope, sessionId, canvas) {
|
|
1191
526
|
try {
|
|
527
|
+
const safeId = safeSessionFileBase(sessionId);
|
|
528
|
+
if (!safeId) return false;
|
|
1192
529
|
const sessionsSvc = resolveSessionsService(scope);
|
|
1193
530
|
const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
|
|
1194
531
|
const root = live && live.header && live.header.cwd;
|
|
1195
532
|
if (!root) return false;
|
|
1196
533
|
const dir = join(root, '.dsh', 'canvas');
|
|
1197
|
-
|
|
1198
|
-
|
|
534
|
+
writeFileAtomic(join(dir, safeId + '.json'), JSON.stringify({ canvas, at: Date.now() }));
|
|
535
|
+
cleanupStaleCanvasFiles(dir, { activeIds: activeCanvasIds(sessionId) });
|
|
1199
536
|
return true;
|
|
1200
537
|
} catch (_e) {
|
|
1201
538
|
return false;
|
|
1202
539
|
}
|
|
1203
540
|
}
|
|
1204
541
|
|
|
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 };
|
|
552
|
+
}
|
|
553
|
+
return out;
|
|
554
|
+
}
|
|
555
|
+
|
|
1205
556
|
/**
|
|
1206
557
|
* Publish live run-state telemetry (condition decisions, pruned nodes, blocked edges,
|
|
1207
|
-
* waitingLead) to `.dsh/canvas/<sessionId>.run.json` so
|
|
1208
|
-
* visualize branch routing and
|
|
558
|
+
* waitingLead, and zero-token run summary) to `.dsh/canvas/<sessionId>.run.json` so
|
|
559
|
+
* the sidebar canvas can visualize branch routing and execution metrics without touching
|
|
560
|
+
* the canvas definition file or injecting anything into model prompts.
|
|
1209
561
|
*/
|
|
1210
562
|
function publishRunState(scope, sessionId, runState) {
|
|
1211
563
|
try {
|
|
1212
|
-
|
|
564
|
+
const safeId = safeSessionFileBase(sessionId);
|
|
565
|
+
if (!safeId) return false;
|
|
1213
566
|
const sessionsSvc = resolveSessionsService(scope);
|
|
1214
567
|
const live = sessionsSvc && typeof sessionsSvc.get === 'function' ? sessionsSvc.get(sessionId) : null;
|
|
1215
568
|
const root = live && live.header && live.header.cwd;
|
|
1216
569
|
if (!root) return false;
|
|
1217
570
|
const dir = join(root, '.dsh', 'canvas');
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
}), '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) });
|
|
1223
575
|
return true;
|
|
1224
576
|
} catch (_e) {
|
|
1225
577
|
return false;
|
|
@@ -1286,8 +638,11 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
|
|
|
1286
638
|
const st = runBySession.get(sid);
|
|
1287
639
|
const wasWaiting = Boolean(st && st.waitingLead);
|
|
1288
640
|
if (st) {
|
|
641
|
+
const haltNow = Date.now();
|
|
642
|
+
st.endedAt = haltNow;
|
|
643
|
+
st.haltedReason = wasWaiting ? '用户结束了等待拍板状态' : '用户主动终止';
|
|
1289
644
|
if (st.done && st.done.size > 0) {
|
|
1290
|
-
lastRunBySession
|
|
645
|
+
touchMapLRU(lastRunBySession, sid, {
|
|
1291
646
|
sig: st.sig,
|
|
1292
647
|
done: new Set(st.done),
|
|
1293
648
|
results: { ...(st.results || {}) },
|
|
@@ -1298,9 +653,16 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
|
|
|
1298
653
|
pruned: new Set(st.pruned || []),
|
|
1299
654
|
decisions: { ...(st.decisions || {}) },
|
|
1300
655
|
fallbackLinks: Array.isArray(st.fallbackLinks) ? st.fallbackLinks.map((fl) => ({ ...fl })) : [],
|
|
656
|
+
nodeStats: st.nodeStats ? Object.fromEntries(Object.entries(st.nodeStats).map(([k, v]) => [k, { ...v }])) : {},
|
|
1301
657
|
halted: true,
|
|
1302
|
-
});
|
|
658
|
+
}, MAX_LAST_RUNS);
|
|
1303
659
|
}
|
|
660
|
+
const summary = buildRunSummarySnapshot(st, {
|
|
661
|
+
status: 'halted',
|
|
662
|
+
waitingLead: null,
|
|
663
|
+
haltedReason: st.haltedReason,
|
|
664
|
+
now: haltNow,
|
|
665
|
+
});
|
|
1304
666
|
runBySession.delete(sid);
|
|
1305
667
|
publishRunState(scope, sid, {
|
|
1306
668
|
status: 'halted',
|
|
@@ -1311,6 +673,7 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
|
|
|
1311
673
|
loopCounts: {},
|
|
1312
674
|
nodeAttempts: { ...(st.nodeAttempts || {}) },
|
|
1313
675
|
waitingLead: null,
|
|
676
|
+
summary,
|
|
1314
677
|
});
|
|
1315
678
|
saveStore();
|
|
1316
679
|
} else {
|
|
@@ -1325,6 +688,7 @@ function abortSessionRun(scope, sessionId, rootAgent, opts) {
|
|
|
1325
688
|
loopCounts: {},
|
|
1326
689
|
nodeAttempts: {},
|
|
1327
690
|
waitingLead: null,
|
|
691
|
+
summary: null,
|
|
1328
692
|
});
|
|
1329
693
|
}
|
|
1330
694
|
return { stopped: true, wasRunning, wasWaiting };
|
|
@@ -1346,7 +710,7 @@ async function runPlan(scope, args, exec) {
|
|
|
1346
710
|
: '已终止当前工作流执行。',
|
|
1347
711
|
};
|
|
1348
712
|
}
|
|
1349
|
-
const payload =
|
|
713
|
+
const payload = getCanvasLRU(sid);
|
|
1350
714
|
if (!payload) return { error: '当前会话还没有画布数据。请在右侧 Workflow 画布点「启用」。' };
|
|
1351
715
|
if (!payload.enabled) return { error: '画布当前是「已禁用」状态。请在画布上点「启用」后再运行。' };
|
|
1352
716
|
if (payload.error) return { error: String(payload.error) };
|
|
@@ -1354,7 +718,7 @@ async function runPlan(scope, args, exec) {
|
|
|
1354
718
|
}
|
|
1355
719
|
|
|
1356
720
|
function inspectPlan(sid) {
|
|
1357
|
-
const payload =
|
|
721
|
+
const payload = getCanvasLRU(sid);
|
|
1358
722
|
if (!payload) {
|
|
1359
723
|
return {
|
|
1360
724
|
hasCanvas: false,
|
|
@@ -1447,15 +811,14 @@ function buildActiveCanvasContext(sid) {
|
|
|
1447
811
|
if (runState && runState.waitingLead) {
|
|
1448
812
|
const wl = runState.waitingLead;
|
|
1449
813
|
const loopHint = wl.loopFeedback
|
|
1450
|
-
? ('(↺
|
|
814
|
+
? ('(↺ ' + wl.loopFeedback.retry + '/' + wl.loopFeedback.max + ':' + (wl.loopFeedback.reason || '未达预期') + ')')
|
|
1451
815
|
: '';
|
|
1452
816
|
return [
|
|
1453
817
|
'[Workflow Canvas Active — Paused at Lead Step]',
|
|
1454
|
-
'
|
|
1455
|
-
'-
|
|
1456
|
-
'-
|
|
1457
|
-
'-
|
|
1458
|
-
'- 若用户要求修改画布结构、分工、参考清单、分支或回环:先 `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`。',
|
|
1459
822
|
].join('\n');
|
|
1460
823
|
}
|
|
1461
824
|
|
|
@@ -1469,26 +832,26 @@ function buildActiveCanvasContext(sid) {
|
|
|
1469
832
|
const prefix = String(sid) + '::';
|
|
1470
833
|
const hasMemory = nodes.some((n) => n.keepSession && (liveChild.has(prefix + n.id) || childByNode.has(prefix + n.id)));
|
|
1471
834
|
const metaParts = [
|
|
1472
|
-
|
|
1473
|
-
'
|
|
835
|
+
nodes.length + ' 节点:' + preview,
|
|
836
|
+
'总任务' + (hasTask ? '已填' : '未填'),
|
|
1474
837
|
];
|
|
1475
|
-
if (loopCount > 0) metaParts.push(
|
|
838
|
+
if (loopCount > 0) metaParts.push(loopCount + ' 条受控回环(自动按条件重试与超限熔断)');
|
|
1476
839
|
if (globalRefs.length > 0) metaParts.push('全局参考 ×' + globalRefs.length);
|
|
1477
840
|
const lines = [
|
|
1478
841
|
'[Workflow Canvas Active]',
|
|
1479
|
-
'
|
|
1480
|
-
'-
|
|
1481
|
-
+ (hasTask ? '
|
|
1482
|
-
+ '
|
|
1483
|
-
'-
|
|
1484
|
-
'-
|
|
842
|
+
'右侧画布「● 已启用」(' + metaParts.join(';') + ')。',
|
|
843
|
+
'- 用户布置任务或说「开始/执行/跑一次」:直接调 `canvas_workflow`('
|
|
844
|
+
+ (hasTask ? '沿用入口任务,有新任务则传 task' : '传入 task 参数')
|
|
845
|
+
+ '),勿绕过画布直接手做。',
|
|
846
|
+
'- 修改画布结构/模型/分工/参考清单、条件分支、回环或连线:先 `canvas_inspect` 再 `canvas_patch`,勿直接运行。',
|
|
847
|
+
'- 仅闲聊、无关问题或要求停用画布时不调 `canvas_workflow`。',
|
|
1485
848
|
];
|
|
1486
849
|
if (hasMemory) {
|
|
1487
|
-
lines.push('-
|
|
850
|
+
lines.push('- 已有开启「记忆」的子代理会话:若用户要求重跑,先问保留记忆(`reset: true`)或清空记忆(`reset: true, clearMemory: true`)。');
|
|
1488
851
|
}
|
|
1489
852
|
const stdCount = nodes.filter((n) => n.kind !== 'lead' && n.kind !== 'condition' && n.preset !== 'minimal').length;
|
|
1490
853
|
if (stdCount >= 2) {
|
|
1491
|
-
lines.push('-
|
|
854
|
+
lines.push('- 含 ' + stdCount + ' 个可写/命令型(standard)子代理,受主对话权限上限约束;若涉及改文件/跑命令且权限偏严,先简短提醒用户放开权限再跑。');
|
|
1492
855
|
}
|
|
1493
856
|
const prevRun = lastRunBySession.get(String(sid));
|
|
1494
857
|
if (prevRun) {
|
|
@@ -1497,23 +860,13 @@ function buildActiveCanvasContext(sid) {
|
|
|
1497
860
|
...Object.values(prevRun.emptyOutputs || {}).map((e) => e.label || e.id),
|
|
1498
861
|
].filter((v, i, arr) => v && arr.indexOf(v) === i);
|
|
1499
862
|
if (prevRun.halted || badNames.length) {
|
|
1500
|
-
lines.push('-
|
|
1501
|
-
+ '
|
|
863
|
+
lines.push('- 上次有失败/熔断节点(' + (badNames.join('、') || '部分未完成')
|
|
864
|
+
+ '):局部续跑调 `canvas_workflow({ retryFailed: true })`(复用成功缓存)或指定 `fromNodes`。');
|
|
1502
865
|
}
|
|
1503
866
|
}
|
|
1504
867
|
return lines.join('\n');
|
|
1505
868
|
}
|
|
1506
869
|
|
|
1507
|
-
/** Detect permission / sandbox denial outcomes so we can circuit-break before burning downstream tokens. */
|
|
1508
|
-
const PERMISSION_ERR_RE = /permission denied|access is denied|sandbox-local|windows-acl|win32error|eacces|eperm|approval required|not permitted|拒绝访问|权限不足|无权执行|沙箱拒绝/i;
|
|
1509
|
-
function isPermissionFailure(outcome) {
|
|
1510
|
-
if (!outcome) return false;
|
|
1511
|
-
const text = String(outcome.text || '');
|
|
1512
|
-
if (!outcome.ok && PERMISSION_ERR_RE.test(text)) return true;
|
|
1513
|
-
if (text.includes('【未完全交付】') && PERMISSION_ERR_RE.test(text)) return true;
|
|
1514
|
-
return false;
|
|
1515
|
-
}
|
|
1516
|
-
|
|
1517
870
|
/** Takes a plan directly so tests can feed any plan shape (sync, generate, patch). */
|
|
1518
871
|
async function executePlan(scope, plan, args, exec) {
|
|
1519
872
|
const opts = args || {};
|
|
@@ -1530,6 +883,9 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1530
883
|
: '已终止当前工作流执行。',
|
|
1531
884
|
};
|
|
1532
885
|
}
|
|
886
|
+
if (sid && activeRunBySession.has(sid)) {
|
|
887
|
+
return { error: '当前会话已有工作流正在执行中,请等待完成,或先调用 canvas_workflow({ cancel: true }) / 点击「⏹ 终止」。' };
|
|
888
|
+
}
|
|
1533
889
|
if (!plan || !Array.isArray(plan.nodes) || !plan.nodes.length) {
|
|
1534
890
|
return { error: '画布没有可执行的节点。' };
|
|
1535
891
|
}
|
|
@@ -1574,16 +930,60 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1574
930
|
|
|
1575
931
|
const byId = new Map(runnable.map((n) => [n.id, n]));
|
|
1576
932
|
const labelOf = new Map(order.map((n) => [n.id, n.label || n.id]));
|
|
933
|
+
const orderIds = runnable.map((n) => n.id);
|
|
934
|
+
const nodeMeta = Object.fromEntries(runnable.map((n) => [n.id, {
|
|
935
|
+
label: n.label || n.id,
|
|
936
|
+
kind: n.kind || 'agent',
|
|
937
|
+
model: formatModelLabel(n.provider, n.model),
|
|
938
|
+
}]));
|
|
939
|
+
const loopMeta = (plan.edges || [])
|
|
940
|
+
.filter((e) => isLoopEdge(e))
|
|
941
|
+
.map((e) => ({
|
|
942
|
+
key: edgeKey(e),
|
|
943
|
+
fromLabel: labelOf.get(e.from) || e.from,
|
|
944
|
+
toLabel: labelOf.get(e.to) || e.to,
|
|
945
|
+
max: normalizeMaxIterations(e.maxIterations),
|
|
946
|
+
}));
|
|
947
|
+
const rawMaxParallel = opts.maxParallel !== undefined ? opts.maxParallel : plan.maxParallel;
|
|
948
|
+
const MAX_PARALLEL = Number.isFinite(Number(rawMaxParallel))
|
|
949
|
+
? Math.max(1, Math.min(8, Math.floor(Number(rawMaxParallel))))
|
|
950
|
+
: 4;
|
|
1577
951
|
const sig = JSON.stringify(plan);
|
|
1578
952
|
let state = runBySession.get(sid);
|
|
1579
953
|
const wantRetryFailed = opts.retryFailed === true;
|
|
954
|
+
if (opts.fromNodes !== undefined && !Array.isArray(opts.fromNodes)) {
|
|
955
|
+
return { error: '参数 fromNodes 必须是节点 ID 或名称的字符串数组,例如 ["n1"]。' };
|
|
956
|
+
}
|
|
1580
957
|
const rawFromNodes = Array.isArray(opts.fromNodes) ? opts.fromNodes.filter((x) => typeof x === 'string' && x.trim()) : [];
|
|
1581
|
-
const
|
|
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;
|
|
1582
976
|
let reused = [];
|
|
977
|
+
let reusedIds = [];
|
|
1583
978
|
|
|
1584
979
|
if (wantPartial && sid) {
|
|
1585
980
|
const base = state || lastRunBySession.get(sid);
|
|
1586
981
|
if (base) {
|
|
982
|
+
const prevStats = base.nodeStats && typeof base.nodeStats === 'object' ? base.nodeStats : {};
|
|
983
|
+
const carriedStats = {};
|
|
984
|
+
for (const [k, v] of Object.entries(prevStats)) {
|
|
985
|
+
if (byId.has(k) && v && typeof v === 'object') carriedStats[k] = { ...v };
|
|
986
|
+
}
|
|
1587
987
|
state = {
|
|
1588
988
|
sig,
|
|
1589
989
|
done: new Set(Array.from(base.done || []).filter((id) => byId.has(id))),
|
|
@@ -1603,6 +1003,15 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1603
1003
|
loopWarmChild: {},
|
|
1604
1004
|
loopExhausted: [],
|
|
1605
1005
|
waitingLead: null,
|
|
1006
|
+
startedAt: Date.now(),
|
|
1007
|
+
endedAt: null,
|
|
1008
|
+
haltedReason: '',
|
|
1009
|
+
maxParallel: MAX_PARALLEL,
|
|
1010
|
+
orderIds,
|
|
1011
|
+
nodeMeta,
|
|
1012
|
+
loopMeta,
|
|
1013
|
+
nodeStats: carriedStats,
|
|
1014
|
+
reusedIds: [],
|
|
1606
1015
|
};
|
|
1607
1016
|
// Build forward adjacency to invalidate seed nodes and all their downstream dependents.
|
|
1608
1017
|
const fwd = new Map();
|
|
@@ -1616,14 +1025,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1616
1025
|
for (const id of Object.keys(state.failed)) seeds.add(id);
|
|
1617
1026
|
for (const id of Object.keys(state.emptyOutputs)) seeds.add(id);
|
|
1618
1027
|
}
|
|
1619
|
-
for (const
|
|
1620
|
-
const trimmed = ref.trim();
|
|
1621
|
-
if (byId.has(trimmed)) seeds.add(trimmed);
|
|
1622
|
-
else {
|
|
1623
|
-
const match = runnable.find((n) => n.label === trimmed);
|
|
1624
|
-
if (match) seeds.add(match.id);
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1028
|
+
for (const id of resolvedFromIds) seeds.add(id);
|
|
1627
1029
|
const invalid = new Set(seeds);
|
|
1628
1030
|
const q = Array.from(seeds);
|
|
1629
1031
|
for (let i = 0; i < q.length; i += 1) {
|
|
@@ -1639,12 +1041,35 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1639
1041
|
delete state.failed[id];
|
|
1640
1042
|
delete state.emptyOutputs[id];
|
|
1641
1043
|
delete state.decisions[id];
|
|
1044
|
+
delete state.nodeStats[id];
|
|
1642
1045
|
}
|
|
1643
1046
|
for (const e of plan.edges || []) {
|
|
1644
1047
|
if (e && invalid.has(e.from)) state.blockedEdges.delete(edgeKey(e));
|
|
1645
1048
|
}
|
|
1646
1049
|
state.fallbackLinks = state.fallbackLinks.filter((fl) => !invalid.has(fl.from) && !invalid.has(fl.to));
|
|
1647
|
-
|
|
1050
|
+
reusedIds = Array.from(state.done).filter((id) => !state.pruned.has(id));
|
|
1051
|
+
state.reusedIds = reusedIds;
|
|
1052
|
+
for (const id of reusedIds) {
|
|
1053
|
+
const meta = nodeMeta[id] || {};
|
|
1054
|
+
state.nodeStats[id] = {
|
|
1055
|
+
...(state.nodeStats[id] || {
|
|
1056
|
+
id,
|
|
1057
|
+
label: meta.label || id,
|
|
1058
|
+
kind: meta.kind || 'agent',
|
|
1059
|
+
startedAt: null,
|
|
1060
|
+
endedAt: null,
|
|
1061
|
+
durationMs: 0,
|
|
1062
|
+
runs: 1,
|
|
1063
|
+
model: meta.model || '',
|
|
1064
|
+
fallbackUsed: false,
|
|
1065
|
+
sessionContinued: false,
|
|
1066
|
+
childId: '',
|
|
1067
|
+
reason: '',
|
|
1068
|
+
}),
|
|
1069
|
+
status: 'reused',
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
reused = reusedIds.map((id) => labelOf.get(id) || id);
|
|
1648
1073
|
runBySession.set(sid, state);
|
|
1649
1074
|
}
|
|
1650
1075
|
}
|
|
@@ -1669,6 +1094,15 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1669
1094
|
loopWarmChild: {},
|
|
1670
1095
|
loopExhausted: [],
|
|
1671
1096
|
waitingLead: null,
|
|
1097
|
+
startedAt: Date.now(),
|
|
1098
|
+
endedAt: null,
|
|
1099
|
+
haltedReason: '',
|
|
1100
|
+
maxParallel: MAX_PARALLEL,
|
|
1101
|
+
orderIds,
|
|
1102
|
+
nodeMeta,
|
|
1103
|
+
loopMeta,
|
|
1104
|
+
nodeStats: {},
|
|
1105
|
+
reusedIds: [],
|
|
1672
1106
|
};
|
|
1673
1107
|
runBySession.set(sid, state);
|
|
1674
1108
|
}
|
|
@@ -1684,8 +1118,14 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1684
1118
|
if (!state.nodeAttempts) state.nodeAttempts = {};
|
|
1685
1119
|
if (!state.loopWarmChild) state.loopWarmChild = {};
|
|
1686
1120
|
if (!state.loopExhausted) state.loopExhausted = [];
|
|
1687
|
-
|
|
1688
|
-
|
|
1121
|
+
if (typeof state.startedAt !== 'number') state.startedAt = Date.now();
|
|
1122
|
+
if (!state.nodeStats) state.nodeStats = {};
|
|
1123
|
+
state.maxParallel = MAX_PARALLEL;
|
|
1124
|
+
state.orderIds = orderIds;
|
|
1125
|
+
state.nodeMeta = nodeMeta;
|
|
1126
|
+
state.loopMeta = loopMeta;
|
|
1127
|
+
|
|
1128
|
+
const emitRunState = (status, waitingLead, reasonOverride) => {
|
|
1689
1129
|
if (!sid) return;
|
|
1690
1130
|
const loopCounts = {};
|
|
1691
1131
|
for (const e of plan.edges || []) {
|
|
@@ -1695,6 +1135,11 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1695
1135
|
loopCounts[k] = entry;
|
|
1696
1136
|
if (e.id) loopCounts[e.id] = entry;
|
|
1697
1137
|
}
|
|
1138
|
+
const summary = buildRunSummarySnapshot(state, {
|
|
1139
|
+
status,
|
|
1140
|
+
waitingLead,
|
|
1141
|
+
haltedReason: reasonOverride || state.haltedReason || '',
|
|
1142
|
+
});
|
|
1698
1143
|
publishRunState(scope, sid, {
|
|
1699
1144
|
status,
|
|
1700
1145
|
done: Array.from(state.done || []),
|
|
@@ -1704,13 +1149,14 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1704
1149
|
loopCounts,
|
|
1705
1150
|
nodeAttempts: { ...state.nodeAttempts },
|
|
1706
1151
|
waitingLead: waitingLead ? { id: waitingLead.id, label: waitingLead.label } : null,
|
|
1152
|
+
summary,
|
|
1707
1153
|
});
|
|
1708
1154
|
};
|
|
1709
1155
|
emitRunState('running', null);
|
|
1710
1156
|
|
|
1711
1157
|
const snapshotLastRun = (haltedFlag) => {
|
|
1712
1158
|
if (!sid) return;
|
|
1713
|
-
lastRunBySession
|
|
1159
|
+
touchMapLRU(lastRunBySession, sid, {
|
|
1714
1160
|
sig: state.sig,
|
|
1715
1161
|
done: new Set(state.done),
|
|
1716
1162
|
results: { ...state.results },
|
|
@@ -1721,8 +1167,9 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1721
1167
|
pruned: new Set(state.pruned),
|
|
1722
1168
|
decisions: { ...state.decisions },
|
|
1723
1169
|
fallbackLinks: state.fallbackLinks.map((fl) => ({ ...fl })),
|
|
1170
|
+
nodeStats: Object.fromEntries(Object.entries(state.nodeStats || {}).map(([k, v]) => [k, { ...v }])),
|
|
1724
1171
|
halted: Boolean(haltedFlag),
|
|
1725
|
-
});
|
|
1172
|
+
}, MAX_LAST_RUNS);
|
|
1726
1173
|
};
|
|
1727
1174
|
const depsOf = (node) => {
|
|
1728
1175
|
const out = new Set();
|
|
@@ -1864,10 +1311,6 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1864
1311
|
};
|
|
1865
1312
|
|
|
1866
1313
|
let leadResult = typeof opts.leadResult === 'string' ? opts.leadResult : undefined;
|
|
1867
|
-
const rawMaxParallel = opts.maxParallel !== undefined ? opts.maxParallel : plan.maxParallel;
|
|
1868
|
-
const MAX_PARALLEL = Number.isFinite(Number(rawMaxParallel))
|
|
1869
|
-
? Math.max(1, Math.min(8, Math.floor(Number(rawMaxParallel))))
|
|
1870
|
-
: 4;
|
|
1871
1314
|
// Event-driven concurrency pool: as soon as any node finishes, newly unblocked
|
|
1872
1315
|
// downstream agents start immediately instead of waiting for slower siblings.
|
|
1873
1316
|
const inFlight = new Map();
|
|
@@ -1904,8 +1347,10 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1904
1347
|
runSignal.addEventListener('abort', () => resolve({ __aborted: true }), { once: true });
|
|
1905
1348
|
});
|
|
1906
1349
|
const finishAborted = () => {
|
|
1350
|
+
state.endedAt = Date.now();
|
|
1351
|
+
state.haltedReason = '工作流执行已取消';
|
|
1907
1352
|
snapshotLastRun(true);
|
|
1908
|
-
emitRunState('halted', null);
|
|
1353
|
+
emitRunState('halted', null, state.haltedReason);
|
|
1909
1354
|
if (sid) runBySession.delete(sid);
|
|
1910
1355
|
saveStore();
|
|
1911
1356
|
return {
|
|
@@ -1932,19 +1377,39 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1932
1377
|
&& !state.done.has(n.id)
|
|
1933
1378
|
&& !inFlight.has(n.id)
|
|
1934
1379
|
&& depsOf(n).every((id) => state.done.has(id)));
|
|
1380
|
+
let launched = 0;
|
|
1935
1381
|
for (const node of candidates) {
|
|
1936
1382
|
if (isAborted() || haltedReason || inFlight.size >= MAX_PARALLEL) break;
|
|
1937
1383
|
const fb = state.loopFeedback[node.id] || null;
|
|
1938
1384
|
const warmChildId = (fb && state.loopWarmChild[node.id]) ? state.loopWarmChild[node.id] : '';
|
|
1939
1385
|
const loopCtx = fb ? { feedback: fb, warmChildId } : undefined;
|
|
1940
1386
|
if (fb) delete state.loopFeedback[node.id];
|
|
1387
|
+
const launchAt = Date.now();
|
|
1388
|
+
const prevStat = state.nodeStats[node.id];
|
|
1389
|
+
state.nodeStats[node.id] = {
|
|
1390
|
+
id: node.id,
|
|
1391
|
+
label: node.label || node.id,
|
|
1392
|
+
kind: node.kind || 'agent',
|
|
1393
|
+
status: 'running',
|
|
1394
|
+
startedAt: launchAt,
|
|
1395
|
+
endedAt: null,
|
|
1396
|
+
durationMs: prevStat && typeof prevStat.durationMs === 'number' ? prevStat.durationMs : 0,
|
|
1397
|
+
runs: (prevStat && typeof prevStat.runs === 'number' ? prevStat.runs : 0) + 1,
|
|
1398
|
+
model: formatModelLabel(node.provider, node.model) || (prevStat && prevStat.model) || '',
|
|
1399
|
+
fallbackUsed: Boolean(prevStat && prevStat.fallbackUsed),
|
|
1400
|
+
sessionContinued: Boolean(prevStat && prevStat.sessionContinued),
|
|
1401
|
+
childId: (prevStat && prevStat.childId) || '',
|
|
1402
|
+
reason: '',
|
|
1403
|
+
};
|
|
1941
1404
|
const promise = spawnNode(scope, plan, node, state.results, agent, runSignal, sid, state.failed, state.pruned, loopCtx)
|
|
1942
1405
|
.then(
|
|
1943
|
-
(outcome) => ({ node, outcome }),
|
|
1944
|
-
(err) => ({ node, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
|
|
1406
|
+
(outcome) => ({ node, outcome, startedAt: launchAt }),
|
|
1407
|
+
(err) => ({ node, startedAt: launchAt, outcome: { ok: false, reason: 'run-failed', text: '运行失败:' + String((err && err.message) || err) } }),
|
|
1945
1408
|
);
|
|
1946
1409
|
inFlight.set(node.id, promise);
|
|
1410
|
+
launched += 1;
|
|
1947
1411
|
}
|
|
1412
|
+
if (launched > 0) emitRunState('running', null);
|
|
1948
1413
|
};
|
|
1949
1414
|
|
|
1950
1415
|
try {
|
|
@@ -1956,8 +1421,10 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1956
1421
|
// but let already in-flight siblings settle so no orphan promises or partial
|
|
1957
1422
|
// results are dropped before returning the halted report.
|
|
1958
1423
|
if (haltedReason && inFlight.size === 0) {
|
|
1424
|
+
state.endedAt = Date.now();
|
|
1425
|
+
state.haltedReason = haltedReason;
|
|
1959
1426
|
snapshotLastRun(true);
|
|
1960
|
-
emitRunState('halted', null);
|
|
1427
|
+
emitRunState('halted', null, haltedReason);
|
|
1961
1428
|
if (sid) runBySession.delete(sid);
|
|
1962
1429
|
saveStore();
|
|
1963
1430
|
return {
|
|
@@ -1976,6 +1443,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
1976
1443
|
}
|
|
1977
1444
|
const remaining = runnable.filter((n) => !state.done.has(n.id));
|
|
1978
1445
|
if (!remaining.length) {
|
|
1446
|
+
state.endedAt = Date.now();
|
|
1979
1447
|
snapshotLastRun(false);
|
|
1980
1448
|
emitRunState('done', null);
|
|
1981
1449
|
runBySession.delete(sid);
|
|
@@ -2001,8 +1469,32 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
2001
1469
|
if ((raceHit && raceHit.__aborted) || isAborted()) {
|
|
2002
1470
|
return finishAborted();
|
|
2003
1471
|
}
|
|
2004
|
-
const { node, outcome } = raceHit;
|
|
1472
|
+
const { node, outcome, startedAt } = raceHit;
|
|
2005
1473
|
inFlight.delete(node.id);
|
|
1474
|
+
const doneAt = Date.now();
|
|
1475
|
+
const attemptElapsed = typeof startedAt === 'number' ? Math.max(0, doneAt - startedAt) : 0;
|
|
1476
|
+
const prevStat = state.nodeStats[node.id] || {
|
|
1477
|
+
id: node.id,
|
|
1478
|
+
label: node.label || node.id,
|
|
1479
|
+
kind: node.kind || 'agent',
|
|
1480
|
+
durationMs: 0,
|
|
1481
|
+
runs: 1,
|
|
1482
|
+
};
|
|
1483
|
+
state.nodeStats[node.id] = {
|
|
1484
|
+
...prevStat,
|
|
1485
|
+
label: node.label || node.id,
|
|
1486
|
+
kind: node.kind || 'agent',
|
|
1487
|
+
status: !outcome.ok ? 'failed' : (outcome.empty ? 'empty' : 'done'),
|
|
1488
|
+
endedAt: doneAt,
|
|
1489
|
+
durationMs: (prevStat.durationMs || 0) + attemptElapsed,
|
|
1490
|
+
model: outcome.modelUsed || prevStat.model || formatModelLabel(node.provider, node.model),
|
|
1491
|
+
fallbackUsed: Boolean(prevStat.fallbackUsed || outcome.fallbackUsed),
|
|
1492
|
+
sessionContinued: Boolean(prevStat.sessionContinued || outcome.sessionContinued),
|
|
1493
|
+
childId: outcome.childId || prevStat.childId || '',
|
|
1494
|
+
reason: !outcome.ok
|
|
1495
|
+
? ((outcome.reason || 'unknown') + (outcome.errorDetail ? ' — ' + outcome.errorDetail : ''))
|
|
1496
|
+
: '',
|
|
1497
|
+
};
|
|
2006
1498
|
state.labels[node.id] = node.label;
|
|
2007
1499
|
if (node.kind === 'condition') {
|
|
2008
1500
|
const { branches, isDefaultBinary } = conditionBranches(node);
|
|
@@ -2116,6 +1608,10 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
2116
1608
|
delete state.emptyOutputs[mid];
|
|
2117
1609
|
delete state.decisions[mid];
|
|
2118
1610
|
state.nodeAttempts[mid] = { retry: nextRetry, max: maxIter };
|
|
1611
|
+
// Preserve cumulative durationMs and runs across loop rounds while marking pending for the next launch.
|
|
1612
|
+
if (state.nodeStats[mid]) {
|
|
1613
|
+
state.nodeStats[mid] = { ...state.nodeStats[mid], status: 'pending', startedAt: null, endedAt: null };
|
|
1614
|
+
}
|
|
2119
1615
|
}
|
|
2120
1616
|
for (const e of plan.edges || []) {
|
|
2121
1617
|
if (e && members.has(e.from)) state.blockedEdges.delete(edgeKey(e));
|
|
@@ -2236,6 +1732,7 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
2236
1732
|
haltedReason = '连续 ' + activationFailCount + ' 个子代理启动失败,已熔断停止后续节点以防继续消耗额度。请检查模型配置或主对话权限后重试。';
|
|
2237
1733
|
}
|
|
2238
1734
|
state.done.add(node.id);
|
|
1735
|
+
emitRunState('running', null);
|
|
2239
1736
|
continue;
|
|
2240
1737
|
}
|
|
2241
1738
|
|
|
@@ -2282,6 +1779,24 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
2282
1779
|
if (!hasDownstreamWork && leadResult === undefined) {
|
|
2283
1780
|
// Terminal Lead: zero downstream nodes remain, so complete the run directly
|
|
2284
1781
|
// and hand off final review/delivery to the Lead without a redundant extra turn.
|
|
1782
|
+
const termNow = Date.now();
|
|
1783
|
+
const prevLeadStat = state.nodeStats[leadNode.id];
|
|
1784
|
+
state.nodeStats[leadNode.id] = {
|
|
1785
|
+
id: leadNode.id,
|
|
1786
|
+
label: leadNode.label || leadNode.id,
|
|
1787
|
+
kind: 'lead',
|
|
1788
|
+
status: 'done',
|
|
1789
|
+
startedAt: (prevLeadStat && prevLeadStat.startedAt) || termNow,
|
|
1790
|
+
endedAt: termNow,
|
|
1791
|
+
durationMs: prevLeadStat && typeof prevLeadStat.durationMs === 'number' ? prevLeadStat.durationMs : 0,
|
|
1792
|
+
runs: (prevLeadStat && typeof prevLeadStat.runs === 'number' ? prevLeadStat.runs : 0) + 1,
|
|
1793
|
+
model: '',
|
|
1794
|
+
fallbackUsed: false,
|
|
1795
|
+
sessionContinued: false,
|
|
1796
|
+
childId: '',
|
|
1797
|
+
reason: '',
|
|
1798
|
+
};
|
|
1799
|
+
state.endedAt = termNow;
|
|
2285
1800
|
state.done.add(leadNode.id);
|
|
2286
1801
|
snapshotLastRun(false);
|
|
2287
1802
|
emitRunState('done', null);
|
|
@@ -2310,6 +1825,23 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
2310
1825
|
};
|
|
2311
1826
|
}
|
|
2312
1827
|
if (leadResult === undefined) {
|
|
1828
|
+
const pauseNow = Date.now();
|
|
1829
|
+
const prevLeadStat = state.nodeStats[leadNode.id];
|
|
1830
|
+
state.nodeStats[leadNode.id] = {
|
|
1831
|
+
id: leadNode.id,
|
|
1832
|
+
label: leadNode.label || leadNode.id,
|
|
1833
|
+
kind: 'lead',
|
|
1834
|
+
status: 'waiting',
|
|
1835
|
+
startedAt: pauseNow,
|
|
1836
|
+
endedAt: null,
|
|
1837
|
+
durationMs: prevLeadStat && typeof prevLeadStat.durationMs === 'number' ? prevLeadStat.durationMs : 0,
|
|
1838
|
+
runs: (prevLeadStat && typeof prevLeadStat.runs === 'number' ? prevLeadStat.runs : 0) + 1,
|
|
1839
|
+
model: '',
|
|
1840
|
+
fallbackUsed: false,
|
|
1841
|
+
sessionContinued: false,
|
|
1842
|
+
childId: '',
|
|
1843
|
+
reason: '',
|
|
1844
|
+
};
|
|
2313
1845
|
const leadFbSummary = leadFb
|
|
2314
1846
|
? { retry: leadFb.retry, max: leadFb.max, sourceLabel: leadFb.sourceLabel, reason: leadFb.reason }
|
|
2315
1847
|
: null;
|
|
@@ -2341,12 +1873,33 @@ async function executePlan(scope, plan, args, exec) {
|
|
|
2341
1873
|
+ '这一步由你(Lead 本体)完成。完成后再次调用本工具,把结果放进 leadResult 继续;若需取消本次流程可传 cancel: true,若需从头重跑可传 reset: true。',
|
|
2342
1874
|
};
|
|
2343
1875
|
}
|
|
1876
|
+
const resumeNow = Date.now();
|
|
1877
|
+
const prevLeadStat = state.nodeStats[leadNode.id];
|
|
1878
|
+
const leadWaitMs = prevLeadStat && typeof prevLeadStat.startedAt === 'number'
|
|
1879
|
+
? Math.max(0, resumeNow - prevLeadStat.startedAt)
|
|
1880
|
+
: 0;
|
|
1881
|
+
state.nodeStats[leadNode.id] = {
|
|
1882
|
+
id: leadNode.id,
|
|
1883
|
+
label: leadNode.label || leadNode.id,
|
|
1884
|
+
kind: 'lead',
|
|
1885
|
+
status: 'done',
|
|
1886
|
+
startedAt: (prevLeadStat && prevLeadStat.startedAt) || resumeNow,
|
|
1887
|
+
endedAt: resumeNow,
|
|
1888
|
+
durationMs: (prevLeadStat && typeof prevLeadStat.durationMs === 'number' ? prevLeadStat.durationMs : 0) + leadWaitMs,
|
|
1889
|
+
runs: prevLeadStat && typeof prevLeadStat.runs === 'number' ? prevLeadStat.runs : 1,
|
|
1890
|
+
model: '',
|
|
1891
|
+
fallbackUsed: false,
|
|
1892
|
+
sessionContinued: false,
|
|
1893
|
+
childId: '',
|
|
1894
|
+
reason: '',
|
|
1895
|
+
};
|
|
2344
1896
|
state.waitingLead = null;
|
|
2345
1897
|
delete state.loopFeedback[leadNode.id];
|
|
2346
1898
|
state.results[leadNode.id] = leadResult;
|
|
2347
1899
|
state.labels[leadNode.id] = leadNode.label;
|
|
2348
1900
|
state.done.add(leadNode.id);
|
|
2349
1901
|
leadResult = undefined;
|
|
1902
|
+
emitRunState('running', null);
|
|
2350
1903
|
}
|
|
2351
1904
|
} finally {
|
|
2352
1905
|
if (parentSignal && typeof parentSignal.removeEventListener === 'function') {
|
|
@@ -2439,9 +1992,11 @@ export function apply(ctx) {
|
|
|
2439
1992
|
try {
|
|
2440
1993
|
const id = agent && agent.id !== undefined ? String(agent.id) : '';
|
|
2441
1994
|
if (!id) return { kind: 'error', text: 'no session' };
|
|
2442
|
-
canvasBySession
|
|
2443
|
-
|
|
2444
|
-
|
|
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
|
+
}
|
|
2445
2000
|
saveStore();
|
|
2446
2001
|
return { kind: 'success', text: 'canvas synced' };
|
|
2447
2002
|
} catch (error) {
|
|
@@ -2591,10 +2146,10 @@ export function apply(ctx) {
|
|
|
2591
2146
|
};
|
|
2592
2147
|
const entryRefs = normalizeRefs(entryNode && entryNode.refs);
|
|
2593
2148
|
if (entryRefs) planObj.refs = entryRefs;
|
|
2594
|
-
canvasBySession
|
|
2149
|
+
touchMapLRU(canvasBySession, sid, {
|
|
2595
2150
|
enabled: nextEnabled,
|
|
2596
2151
|
plan: planObj,
|
|
2597
|
-
});
|
|
2152
|
+
}, MAX_STORED_SESSIONS);
|
|
2598
2153
|
runBySession.delete(sid);
|
|
2599
2154
|
lastRunBySession.delete(sid);
|
|
2600
2155
|
publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
|
|
@@ -2654,7 +2209,7 @@ export function apply(ctx) {
|
|
|
2654
2209
|
if (!payload || !payload.plan) return { error: '当前会话还没有画布数据,先用「启用」同步一次。' };
|
|
2655
2210
|
const patched = applyPatch(payload.plan, args);
|
|
2656
2211
|
const nextPlan = patched.plan;
|
|
2657
|
-
canvasBySession
|
|
2212
|
+
touchMapLRU(canvasBySession, sid, { enabled: payload.enabled, plan: nextPlan }, MAX_STORED_SESSIONS);
|
|
2658
2213
|
runBySession.delete(sid);
|
|
2659
2214
|
publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
|
|
2660
2215
|
saveStore();
|
|
@@ -2668,7 +2223,10 @@ export function apply(ctx) {
|
|
|
2668
2223
|
if (patched.taskPatched) patchDoc.task = nextPlan.task;
|
|
2669
2224
|
if (patched.refsPatched) patchDoc.refs = nextPlan.refs || [];
|
|
2670
2225
|
const delivered = publishCanvas(scope, sid, patchDoc);
|
|
2671
|
-
const warnings =
|
|
2226
|
+
const warnings = [
|
|
2227
|
+
...(Array.isArray(patched.warnings) ? patched.warnings : []),
|
|
2228
|
+
...analyzeCanvasWarnings(nextPlan.nodes, nextPlan.edges),
|
|
2229
|
+
];
|
|
2672
2230
|
const summary = '已更新 ' + patched.touched.length + ' 个节点'
|
|
2673
2231
|
+ (patched.taskPatched ? '、已更新总任务' : '')
|
|
2674
2232
|
+ '、删除 ' + patched.removed.length + ' 个、连线 ' + nextPlan.edges.length + ' 条';
|
|
@@ -2927,12 +2485,15 @@ export {
|
|
|
2927
2485
|
orderNodes,
|
|
2928
2486
|
upstreamOf,
|
|
2929
2487
|
downstreamLabels,
|
|
2488
|
+
parsePayload,
|
|
2489
|
+
clipUpstreamOutput,
|
|
2930
2490
|
briefFor,
|
|
2931
2491
|
normalizeBranches,
|
|
2932
2492
|
normalizeRefs,
|
|
2933
2493
|
normalizeMaxIterations,
|
|
2934
2494
|
loopMemberIds,
|
|
2935
2495
|
validateLoopEdges,
|
|
2496
|
+
parseStrictConditionJson,
|
|
2936
2497
|
parseConditionDecision,
|
|
2937
2498
|
withoutEntry,
|
|
2938
2499
|
analyzeCanvasWarnings,
|
|
@@ -2942,6 +2503,13 @@ export {
|
|
|
2942
2503
|
sessionIdFromContext,
|
|
2943
2504
|
buildActiveCanvasContext,
|
|
2944
2505
|
isPermissionFailure,
|
|
2506
|
+
isTransientFailure,
|
|
2507
|
+
safeSessionFileBase,
|
|
2508
|
+
writeFileAtomic,
|
|
2509
|
+
pruneMapLRU,
|
|
2510
|
+
touchMapLRU,
|
|
2511
|
+
cleanupStaleCanvasFiles,
|
|
2512
|
+
buildRunSummarySnapshot,
|
|
2945
2513
|
abortSessionRun,
|
|
2946
2514
|
runPlan,
|
|
2947
2515
|
executePlan,
|