codexmate 0.0.31 → 0.0.32

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.
Files changed (145) hide show
  1. package/README.md +363 -363
  2. package/README.zh.md +371 -371
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1725 -1725
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +402 -402
  9. package/cli/config-health.js +454 -454
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/local-bridge.js +324 -324
  13. package/cli/openai-bridge.js +1653 -1653
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -69
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -150
  18. package/cli/session-usage.concurrent.js +28 -28
  19. package/cli/session-usage.js +118 -118
  20. package/cli/session-usage.models.js +176 -176
  21. package/cli/skills.js +1141 -1141
  22. package/cli/zip-commands.js +510 -510
  23. package/cli.js +15829 -15778
  24. package/lib/automation.js +404 -404
  25. package/lib/cli-file-utils.js +151 -151
  26. package/lib/cli-models-utils.js +440 -440
  27. package/lib/cli-network-utils.js +190 -190
  28. package/lib/cli-path-utils.js +85 -85
  29. package/lib/cli-session-utils.js +121 -121
  30. package/lib/cli-sessions.js +426 -417
  31. package/lib/cli-utils.js +155 -155
  32. package/lib/cli-webhook.js +126 -126
  33. package/lib/download-artifacts.js +92 -92
  34. package/lib/mcp-stdio.js +453 -453
  35. package/lib/task-orchestrator.js +869 -869
  36. package/lib/text-diff.js +303 -303
  37. package/lib/workflow-engine.js +340 -340
  38. package/package.json +76 -76
  39. package/plugins/README.md +20 -20
  40. package/plugins/README.zh-CN.md +20 -20
  41. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  42. package/plugins/prompt-templates/computed.mjs +253 -253
  43. package/plugins/prompt-templates/index.mjs +8 -8
  44. package/plugins/prompt-templates/manifest.mjs +15 -15
  45. package/plugins/prompt-templates/methods.mjs +553 -553
  46. package/plugins/prompt-templates/overview.mjs +91 -91
  47. package/plugins/prompt-templates/ownership.mjs +19 -19
  48. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  49. package/plugins/prompt-templates/storage.mjs +64 -64
  50. package/plugins/registry.mjs +16 -16
  51. package/web-ui/app.js +647 -646
  52. package/web-ui/index.html +36 -36
  53. package/web-ui/logic.agents-diff.mjs +386 -386
  54. package/web-ui/logic.claude.mjs +168 -168
  55. package/web-ui/logic.codex.mjs +69 -69
  56. package/web-ui/logic.mjs +5 -5
  57. package/web-ui/logic.runtime.mjs +128 -128
  58. package/web-ui/logic.session-convert.mjs +70 -70
  59. package/web-ui/logic.sessions.mjs +781 -765
  60. package/web-ui/modules/api.mjs +90 -90
  61. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  62. package/web-ui/modules/app.computed.index.mjs +17 -17
  63. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  64. package/web-ui/modules/app.computed.session.mjs +693 -999
  65. package/web-ui/modules/app.constants.mjs +15 -15
  66. package/web-ui/modules/app.methods.agents.mjs +651 -632
  67. package/web-ui/modules/app.methods.claude-config.mjs +200 -200
  68. package/web-ui/modules/app.methods.codex-config.mjs +861 -841
  69. package/web-ui/modules/app.methods.index.mjs +94 -94
  70. package/web-ui/modules/app.methods.install.mjs +205 -205
  71. package/web-ui/modules/app.methods.navigation.mjs +774 -774
  72. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  73. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  74. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  75. package/web-ui/modules/app.methods.providers.mjs +529 -529
  76. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  77. package/web-ui/modules/app.methods.session-actions.mjs +591 -591
  78. package/web-ui/modules/app.methods.session-browser.mjs +1012 -984
  79. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  80. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  81. package/web-ui/modules/app.methods.startup-claude.mjs +537 -534
  82. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  83. package/web-ui/modules/app.methods.webhook.mjs +79 -79
  84. package/web-ui/modules/config-mode.computed.mjs +124 -124
  85. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  86. package/web-ui/modules/i18n.dict.mjs +3177 -3174
  87. package/web-ui/modules/i18n.mjs +62 -62
  88. package/web-ui/modules/plugins.computed.mjs +3 -3
  89. package/web-ui/modules/plugins.methods.mjs +3 -3
  90. package/web-ui/modules/plugins.storage.mjs +11 -11
  91. package/web-ui/modules/provider-url-display.mjs +17 -17
  92. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  93. package/web-ui/modules/skills.computed.mjs +107 -107
  94. package/web-ui/modules/skills.methods.mjs +482 -482
  95. package/web-ui/partials/index/layout-footer.html +13 -13
  96. package/web-ui/partials/index/layout-header.html +503 -500
  97. package/web-ui/partials/index/modal-config-template-agents.html +185 -174
  98. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  99. package/web-ui/partials/index/modal-health-check.html +45 -45
  100. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  101. package/web-ui/partials/index/modal-skills.html +200 -200
  102. package/web-ui/partials/index/modals-basic.html +162 -162
  103. package/web-ui/partials/index/panel-config-claude.html +136 -194
  104. package/web-ui/partials/index/panel-config-codex.html +197 -357
  105. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  106. package/web-ui/partials/index/panel-dashboard.html +219 -219
  107. package/web-ui/partials/index/panel-docs.html +115 -147
  108. package/web-ui/partials/index/panel-market.html +177 -177
  109. package/web-ui/partials/index/panel-orchestration.html +391 -391
  110. package/web-ui/partials/index/panel-plugins.html +253 -253
  111. package/web-ui/partials/index/panel-sessions.html +313 -302
  112. package/web-ui/partials/index/panel-settings.html +190 -190
  113. package/web-ui/partials/index/panel-trash.html +83 -88
  114. package/web-ui/partials/index/panel-usage.html +138 -371
  115. package/web-ui/res/json5.min.js +1 -1
  116. package/web-ui/res/vue.global.prod.js +13 -13
  117. package/web-ui/session-helpers.mjs +591 -591
  118. package/web-ui/source-bundle.cjs +233 -233
  119. package/web-ui/styles/base-theme.css +281 -281
  120. package/web-ui/styles/bridge-pool.css +197 -197
  121. package/web-ui/styles/controls-forms.css +433 -422
  122. package/web-ui/styles/dashboard.css +406 -406
  123. package/web-ui/styles/docs-panel.css +245 -271
  124. package/web-ui/styles/feedback.css +108 -108
  125. package/web-ui/styles/health-check-dialog.css +144 -144
  126. package/web-ui/styles/layout-shell.css +638 -626
  127. package/web-ui/styles/modals-core.css +466 -466
  128. package/web-ui/styles/navigation-panels.css +391 -391
  129. package/web-ui/styles/openclaw-structured.css +266 -266
  130. package/web-ui/styles/plugins-panel.css +564 -564
  131. package/web-ui/styles/responsive.css +392 -454
  132. package/web-ui/styles/sessions-list.css +647 -417
  133. package/web-ui/styles/sessions-preview.css +407 -407
  134. package/web-ui/styles/sessions-toolbar-trash.css +518 -348
  135. package/web-ui/styles/sessions-usage.css +588 -1040
  136. package/web-ui/styles/settings-panel.css +349 -349
  137. package/web-ui/styles/skills-list.css +305 -305
  138. package/web-ui/styles/skills-market.css +429 -429
  139. package/web-ui/styles/task-orchestration.css +822 -822
  140. package/web-ui/styles/titles-cards.css +472 -472
  141. package/web-ui/styles/trash-panel.css +90 -90
  142. package/web-ui/styles/webhook.css +81 -81
  143. package/web-ui/styles.css +24 -24
  144. package/web-ui.html +17 -17
  145. package/web-ui/partials/index/panel-config-codex.html.bak +0 -337
@@ -1,869 +1,869 @@
1
- function isPlainObject(value) {
2
- return !!value && typeof value === 'object' && !Array.isArray(value);
3
- }
4
-
5
- function cloneJson(value, fallback = null) {
6
- try {
7
- return JSON.parse(JSON.stringify(value));
8
- } catch (_) {
9
- return fallback;
10
- }
11
- }
12
-
13
- function normalizeText(value, maxLength = 4000) {
14
- const text = value === undefined || value === null ? '' : String(value).trim();
15
- if (!text) {
16
- return '';
17
- }
18
- return text.length > maxLength ? text.slice(0, maxLength) : text;
19
- }
20
-
21
- function normalizeId(value, fallback = '') {
22
- const text = String(value || '').trim().toLowerCase();
23
- const normalized = text
24
- .replace(/[^a-z0-9._-]+/g, '-')
25
- .replace(/-{2,}/g, '-')
26
- .replace(/^-+|-+$/g, '');
27
- return normalized || fallback;
28
- }
29
-
30
- function normalizePositiveInteger(value, fallback, min = 1, max = 8) {
31
- const numeric = Number.parseInt(String(value), 10);
32
- if (!Number.isFinite(numeric)) {
33
- return fallback;
34
- }
35
- return Math.min(max, Math.max(min, Math.floor(numeric)));
36
- }
37
-
38
- function truncateText(value, maxLength = 240) {
39
- const text = String(value || '').trim();
40
- if (!text) {
41
- return '';
42
- }
43
- if (text.length <= maxLength) {
44
- return text;
45
- }
46
- return `${text.slice(0, Math.max(0, maxLength - 1))}…`;
47
- }
48
-
49
- function uniqueStringList(input = []) {
50
- const result = [];
51
- const seen = new Set();
52
- for (const item of Array.isArray(input) ? input : []) {
53
- const text = normalizeText(item, 400);
54
- if (!text || seen.has(text)) {
55
- continue;
56
- }
57
- seen.add(text);
58
- result.push(text);
59
- }
60
- return result;
61
- }
62
-
63
- function splitTargetIntoItems(target) {
64
- const source = normalizeText(target, 12000);
65
- if (!source) {
66
- return [];
67
- }
68
- const lines = source
69
- .split(/\r?\n/g)
70
- .map((line) => line.trim())
71
- .filter(Boolean)
72
- .map((line) => line.replace(/^[-*+•]\s+/, '').replace(/^\d+[.)]\s+/, '').trim())
73
- .filter(Boolean);
74
- if (lines.length >= 2) {
75
- return uniqueStringList(lines).slice(0, 6);
76
- }
77
-
78
- const segments = source
79
- .split(/[;;。\n]+/g)
80
- .map((part) => part.trim())
81
- .filter(Boolean)
82
- .map((part) => part.replace(/^[-*+•]\s+/, '').replace(/^\d+[.)]\s+/, '').trim())
83
- .filter(Boolean);
84
- if (segments.length >= 2) {
85
- return uniqueStringList(segments).slice(0, 6);
86
- }
87
-
88
- return [truncateText(source, 220)];
89
- }
90
-
91
- function buildTaskTitle(target, explicitTitle = '') {
92
- const custom = normalizeText(explicitTitle, 160);
93
- if (custom) {
94
- return custom;
95
- }
96
- const normalizedTarget = normalizeText(target, 400);
97
- if (!normalizedTarget) {
98
- return '未命名任务';
99
- }
100
- return truncateText(normalizedTarget.replace(/\s+/g, ' '), 96);
101
- }
102
-
103
- function normalizeDependencyIds(value = []) {
104
- return uniqueStringList(value)
105
- .map((depId) => normalizeId(depId, ''))
106
- .filter(Boolean);
107
- }
108
-
109
- function computePlanWaves(nodes = []) {
110
- const list = Array.isArray(nodes) ? nodes : [];
111
- const byId = new Map();
112
- const indegree = new Map();
113
- const outgoing = new Map();
114
- for (const node of list) {
115
- const id = normalizeId(node && node.id, '');
116
- if (!id) continue;
117
- byId.set(id, node);
118
- indegree.set(id, 0);
119
- outgoing.set(id, []);
120
- }
121
- for (const node of list) {
122
- const id = normalizeId(node && node.id, '');
123
- if (!id) continue;
124
- const dependsOn = normalizeDependencyIds(node && node.dependsOn).filter((depId) => byId.has(depId));
125
- indegree.set(id, dependsOn.length);
126
- for (const depId of dependsOn) {
127
- outgoing.get(depId).push(id);
128
- }
129
- }
130
-
131
- const remaining = new Set(byId.keys());
132
- const waves = [];
133
- while (remaining.size > 0) {
134
- const ready = Array.from(remaining).filter((id) => (indegree.get(id) || 0) === 0);
135
- if (ready.length === 0) {
136
- waves.push(Array.from(remaining));
137
- break;
138
- }
139
- ready.sort();
140
- waves.push(ready);
141
- for (const id of ready) {
142
- remaining.delete(id);
143
- const nextIds = outgoing.get(id) || [];
144
- for (const nextId of nextIds) {
145
- indegree.set(nextId, Math.max(0, (indegree.get(nextId) || 0) - 1));
146
- }
147
- }
148
- }
149
-
150
- return waves.map((wave, index) => ({
151
- index,
152
- nodeIds: wave,
153
- label: `Wave ${index + 1}`
154
- }));
155
- }
156
-
157
- function detectDependencyCycle(nodes = []) {
158
- const list = Array.isArray(nodes) ? nodes : [];
159
- const graph = new Map();
160
- for (const node of list) {
161
- const id = normalizeId(node && node.id, '');
162
- if (!id) continue;
163
- graph.set(id, uniqueStringList(node && node.dependsOn).map((depId) => normalizeId(depId, '')).filter(Boolean));
164
- }
165
- const visiting = new Set();
166
- const visited = new Set();
167
- const visit = (id) => {
168
- if (visited.has(id)) {
169
- return false;
170
- }
171
- if (visiting.has(id)) {
172
- return true;
173
- }
174
- visiting.add(id);
175
- const deps = graph.get(id) || [];
176
- for (const depId of deps) {
177
- if (!graph.has(depId)) {
178
- continue;
179
- }
180
- if (visit(depId)) {
181
- return true;
182
- }
183
- }
184
- visiting.delete(id);
185
- visited.add(id);
186
- return false;
187
- };
188
- for (const id of graph.keys()) {
189
- if (visit(id)) {
190
- return true;
191
- }
192
- }
193
- return false;
194
- }
195
-
196
- function buildCodexNodePrompt(kind, context = {}) {
197
- const title = normalizeText(context.title, 160);
198
- const target = normalizeText(context.target, 4000);
199
- const item = normalizeText(context.item, 1200);
200
- const followUp = normalizeText(context.followUp, 1200);
201
- const dependencySummaries = uniqueStringList(context.dependencySummaries || []).slice(0, 6);
202
- const allowWrite = context.allowWrite === true;
203
- const dependencyBlock = dependencySummaries.length > 0
204
- ? `\n已完成前置摘要:\n${dependencySummaries.map((entry, index) => `${index + 1}. ${entry}`).join('\n')}`
205
- : '';
206
- const writeRule = allowWrite
207
- ? '允许直接修改本地工作区,但必须控制变更范围并完成最小必要验证。'
208
- : '只允许只读调查,不要修改任何文件,不要执行写入型操作。';
209
-
210
- if (kind === 'analysis') {
211
- return [
212
- `任务标题: ${title || '任务分析'}`,
213
- `任务目标:\n${target}`,
214
- writeRule,
215
- '请先调查当前仓库与上下文,给出简洁的现状判断、主要风险、建议执行顺序,以及你认为最小可行的验证方案。',
216
- '输出请保持简洁,聚焦可执行信息。'
217
- ].join('\n\n');
218
- }
219
-
220
- if (kind === 'work') {
221
- return [
222
- `任务标题: ${title || '执行子任务'}`,
223
- `总目标:\n${target}`,
224
- `当前子任务:\n${item || title || target}`,
225
- dependencyBlock,
226
- writeRule,
227
- '请只处理当前子任务范围,避免越界修改。完成后说明实际改动、验证结果与剩余风险。'
228
- ].join('\n\n');
229
- }
230
-
231
- if (kind === 'verify') {
232
- return [
233
- `任务标题: ${title || '验证与总结'}`,
234
- `总目标:\n${target}`,
235
- dependencyBlock,
236
- writeRule,
237
- '请基于当前工作区状态执行最小必要验证,检查明显回归,并输出结果摘要、未完成项和建议下一步。'
238
- ].join('\n\n');
239
- }
240
-
241
- return [
242
- `任务标题: ${title || '后续任务'}`,
243
- `总目标:\n${target}`,
244
- dependencyBlock,
245
- writeRule,
246
- `追加指令:\n${followUp || item || target}`,
247
- '请严格围绕上述后续指令继续推进,并给出结果摘要。'
248
- ].join('\n\n');
249
- }
250
-
251
- function normalizeWorkflowCatalog(workflowCatalog = []) {
252
- const map = new Map();
253
- for (const item of Array.isArray(workflowCatalog) ? workflowCatalog : []) {
254
- const id = normalizeId(item && item.id, '');
255
- if (!id) continue;
256
- map.set(id, {
257
- id,
258
- name: normalizeText(item.name || id, 160) || id,
259
- description: normalizeText(item.description, 600),
260
- readOnly: item && item.readOnly !== false
261
- });
262
- }
263
- return map;
264
- }
265
-
266
- function buildTaskPlan(request = {}, options = {}) {
267
- const workflowMap = normalizeWorkflowCatalog(options.workflowCatalog || []);
268
- const target = normalizeText(request.target, 4000);
269
- const title = buildTaskTitle(target, request.title);
270
- const engine = normalizeId(request.engine, 'codex') === 'workflow' ? 'workflow' : 'codex';
271
- const allowWrite = request.allowWrite === true;
272
- const dryRun = request.dryRun === true;
273
- const concurrency = normalizePositiveInteger(request.concurrency, 2, 1, 8);
274
- const autoFixRounds = normalizePositiveInteger(request.autoFixRounds, 1, 0, 5);
275
- const requestedWorkflowIds = uniqueStringList(request.workflowIds || [])
276
- .map((id) => normalizeId(id, ''))
277
- .filter(Boolean);
278
- const followUps = uniqueStringList(request.followUps || []);
279
- const notes = normalizeText(request.notes, 2000);
280
- const cwd = normalizeText(request.cwd || options.cwd, 1200);
281
- const nodes = [];
282
- let nodeSequence = 0;
283
- const nextNodeId = (prefix) => `${prefix}-${String(++nodeSequence).padStart(2, '0')}`;
284
- const shouldBuildWorkflowNodes = requestedWorkflowIds.length > 0 || engine === 'workflow';
285
-
286
- if (shouldBuildWorkflowNodes) {
287
- let previousId = '';
288
- for (const workflowId of requestedWorkflowIds) {
289
- const meta = workflowMap.get(workflowId);
290
- const nodeId = nextNodeId('workflow');
291
- const isLastWorkflowNode = requestedWorkflowIds.length > 0 && workflowId === requestedWorkflowIds[requestedWorkflowIds.length - 1];
292
- nodes.push({
293
- id: nodeId,
294
- title: meta ? meta.name : workflowId,
295
- kind: 'workflow',
296
- workflowId,
297
- dependsOn: previousId ? [previousId] : [],
298
- write: !!(meta && meta.readOnly === false),
299
- retryLimit: 0,
300
- autoFixRounds,
301
- input: {
302
- target,
303
- title,
304
- notes,
305
- ...(isLastWorkflowNode && followUps.length > 0 ? { followUps: followUps.slice() } : {})
306
- }
307
- });
308
- previousId = nodeId;
309
- }
310
- } else {
311
- const items = splitTargetIntoItems(target);
312
- const analysisId = nextNodeId('analysis');
313
- nodes.push({
314
- id: analysisId,
315
- title: '现状分析',
316
- kind: 'codex',
317
- prompt: buildCodexNodePrompt('analysis', {
318
- title,
319
- target,
320
- allowWrite: false
321
- }),
322
- dependsOn: [],
323
- write: false,
324
- retryLimit: 0,
325
- autoFixRounds: 0
326
- });
327
-
328
- const executionNodeIds = [];
329
- const workItems = items.length > 0 ? items : [target || title];
330
- for (const item of workItems) {
331
- const nodeId = nextNodeId('work');
332
- executionNodeIds.push(nodeId);
333
- nodes.push({
334
- id: nodeId,
335
- title: truncateText(item, 72) || `执行 ${executionNodeIds.length}`,
336
- kind: 'codex',
337
- prompt: buildCodexNodePrompt('work', {
338
- title,
339
- target,
340
- item,
341
- allowWrite
342
- }),
343
- dependsOn: [analysisId],
344
- write: allowWrite,
345
- retryLimit: 0,
346
- autoFixRounds
347
- });
348
- }
349
-
350
- const verifyId = nextNodeId('verify');
351
- nodes.push({
352
- id: verifyId,
353
- title: '验证与总结',
354
- kind: 'codex',
355
- prompt: buildCodexNodePrompt('verify', {
356
- title,
357
- target,
358
- allowWrite: false
359
- }),
360
- dependsOn: executionNodeIds.slice(),
361
- write: false,
362
- retryLimit: 0,
363
- autoFixRounds: 0
364
- });
365
- }
366
-
367
- if (engine !== 'workflow') {
368
- let followUpDependsOn = nodes.length > 0 ? [nodes[nodes.length - 1].id] : [];
369
- for (const followUp of followUps) {
370
- const nodeId = nextNodeId('follow-up');
371
- nodes.push({
372
- id: nodeId,
373
- title: truncateText(followUp, 72) || `Follow-up ${nodes.length + 1}`,
374
- kind: 'codex',
375
- prompt: buildCodexNodePrompt('follow-up', {
376
- title,
377
- target,
378
- allowWrite,
379
- followUp
380
- }),
381
- dependsOn: followUpDependsOn,
382
- write: allowWrite,
383
- retryLimit: 0,
384
- autoFixRounds
385
- });
386
- followUpDependsOn = [nodeId];
387
- }
388
- }
389
-
390
- const plan = {
391
- id: normalizeId(request.id, ''),
392
- title,
393
- target,
394
- notes,
395
- cwd,
396
- engine,
397
- allowWrite,
398
- dryRun,
399
- concurrency,
400
- autoFixRounds,
401
- workflowIds: requestedWorkflowIds,
402
- followUps,
403
- nodes,
404
- waves: computePlanWaves(nodes)
405
- };
406
- return plan;
407
- }
408
-
409
- function validateTaskPlan(plan, options = {}) {
410
- const issues = [];
411
- if (!isPlainObject(plan)) {
412
- return {
413
- ok: false,
414
- error: 'task plan must be an object',
415
- issues: [{ code: 'task-plan-invalid', message: 'task plan must be an object' }]
416
- };
417
- }
418
-
419
- const workflowMap = normalizeWorkflowCatalog(options.workflowCatalog || []);
420
- const engine = normalizeId(plan.engine, 'codex') === 'workflow' ? 'workflow' : 'codex';
421
- const workflowIds = uniqueStringList(plan.workflowIds || []).map((id) => normalizeId(id, '')).filter(Boolean);
422
- const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
423
- if (engine === 'workflow' && workflowIds.length === 0) {
424
- issues.push({ code: 'task-plan-workflow-required', message: 'workflow engine requires at least one workflowId' });
425
- }
426
- if (engine === 'workflow' && nodes.some((node) => normalizeId(node && node.kind, '') !== 'workflow')) {
427
- issues.push({ code: 'task-plan-engine-mismatch', message: 'workflow engine plan cannot contain non-workflow nodes' });
428
- }
429
- if (nodes.length === 0) {
430
- issues.push({ code: 'task-plan-nodes-required', message: 'task plan must contain at least one node' });
431
- }
432
- const nodeIds = new Set();
433
- for (const node of nodes) {
434
- if (!isPlainObject(node)) {
435
- issues.push({ code: 'task-node-invalid', message: 'task node must be an object' });
436
- continue;
437
- }
438
- const id = normalizeId(node.id, '');
439
- if (!id) {
440
- issues.push({ code: 'task-node-id-required', message: 'task node id is required' });
441
- continue;
442
- }
443
- if (nodeIds.has(id)) {
444
- issues.push({ code: 'task-node-id-duplicate', message: `duplicate task node id: ${id}` });
445
- continue;
446
- }
447
- nodeIds.add(id);
448
- const kind = normalizeId(node.kind, '');
449
- if (kind !== 'workflow' && kind !== 'codex') {
450
- issues.push({ code: 'task-node-kind-invalid', message: `task node ${id} has unsupported kind: ${node.kind || ''}` });
451
- }
452
- if (kind === 'workflow') {
453
- const workflowId = normalizeId(node.workflowId, '');
454
- if (!workflowId) {
455
- issues.push({ code: 'task-node-workflow-required', message: `task node ${id} missing workflowId` });
456
- } else if (workflowMap.size > 0 && !workflowMap.has(workflowId)) {
457
- issues.push({ code: 'task-node-workflow-unknown', message: `task node ${id} references unknown workflow: ${workflowId}` });
458
- }
459
- }
460
- if (kind === 'codex' && !normalizeText(node.prompt, 12000)) {
461
- issues.push({ code: 'task-node-prompt-required', message: `task node ${id} missing prompt` });
462
- }
463
- }
464
-
465
- if (issues.length === 0) {
466
- for (const node of nodes) {
467
- const id = normalizeId(node.id, '');
468
- const dependsOn = normalizeDependencyIds(node.dependsOn || []);
469
- for (const depId of dependsOn) {
470
- if (!nodeIds.has(depId)) {
471
- issues.push({ code: 'task-node-dependency-missing', message: `task node ${id} depends on missing node: ${depId}` });
472
- }
473
- if (depId === id) {
474
- issues.push({ code: 'task-node-dependency-self', message: `task node ${id} cannot depend on itself` });
475
- }
476
- }
477
- }
478
- }
479
-
480
- if (issues.length === 0 && detectDependencyCycle(nodes)) {
481
- issues.push({ code: 'task-plan-cycle-detected', message: 'task plan contains a dependency cycle' });
482
- }
483
-
484
- return {
485
- ok: issues.length === 0,
486
- error: issues[0] ? issues[0].message : '',
487
- issues
488
- };
489
- }
490
-
491
- function createNodeRunRecord(node, dependencyNodeIds = []) {
492
- return {
493
- id: normalizeId(node && node.id, ''),
494
- title: normalizeText(node && node.title, 160),
495
- kind: normalizeId(node && node.kind, ''),
496
- workflowId: normalizeId(node && node.workflowId, ''),
497
- dependsOn: normalizeDependencyIds(node && node.dependsOn),
498
- dependencyNodeIds: uniqueStringList(dependencyNodeIds),
499
- write: node && node.write === true,
500
- status: 'pending',
501
- attemptCount: 0,
502
- autoFixRounds: normalizePositiveInteger(node && node.autoFixRounds, 0, 0, 5),
503
- retryLimit: normalizePositiveInteger(node && node.retryLimit, 0, 0, 5),
504
- startedAt: '',
505
- endedAt: '',
506
- durationMs: 0,
507
- summary: '',
508
- error: '',
509
- output: null,
510
- logs: [],
511
- attempts: []
512
- };
513
- }
514
-
515
- function createRunLog(level, message, extra = {}) {
516
- return {
517
- at: new Date().toISOString(),
518
- level: level || 'info',
519
- message: normalizeText(message, 1000),
520
- ...cloneJson(extra, {})
521
- };
522
- }
523
-
524
- async function executeTaskPlan(plan, options = {}) {
525
- const executeNode = typeof options.executeNode === 'function'
526
- ? options.executeNode
527
- : async () => ({ success: false, error: 'executeNode is not configured' });
528
- const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
529
- const signal = options.signal || null;
530
- const startedAtTs = Date.now();
531
- const concurrency = normalizePositiveInteger(options.concurrency || plan.concurrency, 2, 1, 8);
532
- const nodeList = Array.isArray(plan && plan.nodes) ? plan.nodes : [];
533
- const run = {
534
- status: 'running',
535
- startedAt: new Date(startedAtTs).toISOString(),
536
- endedAt: '',
537
- durationMs: 0,
538
- concurrency,
539
- waves: computePlanWaves(nodeList),
540
- nodes: nodeList.map((node) => createNodeRunRecord(node)),
541
- logs: [createRunLog('info', 'task run started', { concurrency })],
542
- summary: '',
543
- error: ''
544
- };
545
-
546
- const nodeMap = new Map();
547
- for (const node of run.nodes) {
548
- nodeMap.set(node.id, node);
549
- }
550
-
551
- const emitUpdate = async () => {
552
- if (!onUpdate) {
553
- return;
554
- }
555
- await onUpdate(cloneJson(run, run));
556
- };
557
-
558
- const active = new Map();
559
- let writeLock = false;
560
-
561
- const finalizeNode = (nodeRun, payload, attemptStartedAt, attemptIndex) => {
562
- const endedAtTs = Date.now();
563
- const success = !!(payload && payload.success === true);
564
- const error = success ? '' : normalizeText(payload && payload.error, 2000) || `node failed: ${nodeRun.id}`;
565
- const preserveCancelledState = run.status === 'cancelled' || nodeRun.status === 'cancelled';
566
- nodeRun.attempts.push({
567
- index: attemptIndex,
568
- startedAt: new Date(attemptStartedAt).toISOString(),
569
- endedAt: new Date(endedAtTs).toISOString(),
570
- durationMs: endedAtTs - attemptStartedAt,
571
- success,
572
- error,
573
- summary: truncateText(payload && payload.summary, 400),
574
- output: cloneJson(payload && payload.output, null),
575
- logs: cloneJson(payload && payload.logs, [])
576
- });
577
- nodeRun.logs = cloneJson(payload && payload.logs, []);
578
- if (!preserveCancelledState) {
579
- nodeRun.output = cloneJson(payload && payload.output, null);
580
- nodeRun.summary = truncateText(payload && payload.summary, 400);
581
- nodeRun.error = error;
582
- }
583
- nodeRun.startedAt = nodeRun.startedAt || new Date(attemptStartedAt).toISOString();
584
- nodeRun.endedAt = new Date(endedAtTs).toISOString();
585
- nodeRun.durationMs = endedAtTs - new Date(nodeRun.startedAt).getTime();
586
- return {
587
- success: preserveCancelledState ? false : success,
588
- error: preserveCancelledState ? (nodeRun.error || 'cancelled while running') : error
589
- };
590
- };
591
-
592
- const executeOneNode = async (nodeRun, nodeDef, hooks = {}) => {
593
- nodeRun.status = 'running';
594
- if (!nodeRun.startedAt) {
595
- nodeRun.startedAt = new Date().toISOString();
596
- }
597
- nodeRun.attemptCount += 1;
598
- const attemptIndex = nodeRun.attemptCount;
599
- const attemptStartedAt = Date.now();
600
- const dependencyResults = (nodeRun.dependsOn || [])
601
- .map((depId) => nodeMap.get(depId))
602
- .filter(Boolean)
603
- .map((dep) => ({
604
- id: dep.id,
605
- status: dep.status,
606
- summary: dep.summary,
607
- error: dep.error,
608
- output: cloneJson(dep.output, null)
609
- }));
610
- const attemptLogs = [createRunLog('info', `starting node ${nodeRun.id}`, { attempt: attemptIndex })];
611
- let abortHandler = null;
612
- try {
613
- const payload = await executeNode(nodeDef, {
614
- attempt: attemptIndex,
615
- maxAttempts: 1 + Math.max(nodeRun.retryLimit, 0) + Math.max(nodeRun.autoFixRounds, 0),
616
- dependencyResults,
617
- signal,
618
- registerAbort(handler) {
619
- abortHandler = typeof handler === 'function' ? handler : null;
620
- if (typeof hooks.onAbortChange === 'function') {
621
- hooks.onAbortChange(abortHandler);
622
- }
623
- },
624
- previousAttempts: cloneJson(nodeRun.attempts, [])
625
- });
626
- attemptLogs.push(...(Array.isArray(payload && payload.logs) ? payload.logs : []));
627
- const finalized = finalizeNode(nodeRun, {
628
- ...payload,
629
- logs: attemptLogs
630
- }, attemptStartedAt, attemptIndex);
631
- return {
632
- success: finalized.success,
633
- error: finalized.error,
634
- abortHandler
635
- };
636
- } catch (error) {
637
- const message = error && error.message ? error.message : String(error || 'task node execution failed');
638
- const finalized = finalizeNode(nodeRun, {
639
- success: false,
640
- error: message,
641
- output: null,
642
- summary: message,
643
- logs: attemptLogs.concat(createRunLog('error', message))
644
- }, attemptStartedAt, attemptIndex);
645
- return {
646
- success: false,
647
- error: finalized.error,
648
- abortHandler
649
- };
650
- }
651
- };
652
-
653
- const getPendingNodeDefs = () => nodeList.filter((node) => {
654
- const nodeRun = nodeMap.get(normalizeId(node && node.id, ''));
655
- return !!nodeRun && nodeRun.status === 'pending';
656
- });
657
-
658
- const hasFailedDependency = (nodeRun) => (nodeRun.dependsOn || []).some((depId) => {
659
- const dep = nodeMap.get(depId);
660
- return dep && (dep.status === 'failed' || dep.status === 'blocked' || dep.status === 'cancelled');
661
- });
662
-
663
- const isReady = (nodeRun) => (nodeRun.dependsOn || []).every((depId) => {
664
- const dep = nodeMap.get(depId);
665
- return dep && (dep.status === 'success' || dep.status === 'skipped');
666
- });
667
-
668
- const markBlockedNodes = () => {
669
- for (const nodeRun of run.nodes) {
670
- if (nodeRun.status !== 'pending') continue;
671
- if (!hasFailedDependency(nodeRun)) continue;
672
- nodeRun.status = 'blocked';
673
- nodeRun.error = 'blocked by failed dependency';
674
- nodeRun.summary = '前置节点失败,已阻塞';
675
- nodeRun.startedAt = nodeRun.startedAt || new Date().toISOString();
676
- nodeRun.endedAt = new Date().toISOString();
677
- run.logs.push(createRunLog('warn', `node blocked: ${nodeRun.id}`));
678
- }
679
- };
680
-
681
- const abortActiveNodes = () => {
682
- for (const activeRun of active.values()) {
683
- if (activeRun && typeof activeRun.abort === 'function') {
684
- try {
685
- activeRun.abort();
686
- } catch (_) {}
687
- }
688
- }
689
- };
690
-
691
- try {
692
- while (true) {
693
- if (signal && signal.aborted) {
694
- abortActiveNodes();
695
- for (const nodeRun of run.nodes) {
696
- if (nodeRun.status === 'pending') {
697
- nodeRun.status = 'cancelled';
698
- nodeRun.error = 'cancelled before start';
699
- nodeRun.summary = '已取消';
700
- } else if (nodeRun.status === 'running') {
701
- nodeRun.status = 'cancelled';
702
- nodeRun.error = 'cancelled while running';
703
- nodeRun.summary = '执行中取消';
704
- }
705
- }
706
- run.logs.push(createRunLog('warn', 'task run cancelled'));
707
- run.status = 'cancelled';
708
- if (active.size > 0) {
709
- await Promise.allSettled(Array.from(active.values()).map((item) => item && item.promise).filter(Boolean));
710
- active.clear();
711
- writeLock = false;
712
- }
713
- break;
714
- }
715
-
716
- markBlockedNodes();
717
- const readyNodeDefs = getPendingNodeDefs().filter((node) => {
718
- const nodeRun = nodeMap.get(normalizeId(node && node.id, ''));
719
- return nodeRun && isReady(nodeRun);
720
- });
721
- let started = false;
722
- for (const nodeDef of readyNodeDefs) {
723
- if (active.size >= concurrency) {
724
- break;
725
- }
726
- const nodeRun = nodeMap.get(normalizeId(nodeDef && nodeDef.id, ''));
727
- if (!nodeRun) continue;
728
- const wantsWrite = nodeRun.write === true;
729
- if (writeLock && wantsWrite) {
730
- continue;
731
- }
732
- if (wantsWrite && active.size > 0) {
733
- continue;
734
- }
735
- if (!wantsWrite && writeLock) {
736
- continue;
737
- }
738
- started = true;
739
- if (wantsWrite) {
740
- writeLock = true;
741
- }
742
- const promise = (async () => {
743
- let result = null;
744
- const maxAttempts = 1 + Math.max(nodeRun.retryLimit, 0) + Math.max(nodeRun.autoFixRounds, 0);
745
- for (let attempt = nodeRun.attemptCount + 1; attempt <= maxAttempts; attempt += 1) {
746
- result = await executeOneNode(nodeRun, nodeDef, {
747
- onAbortChange(handler) {
748
- const current = active.get(nodeRun.id);
749
- if (current) {
750
- current._abort = typeof handler === 'function' ? handler : null;
751
- }
752
- }
753
- });
754
- if (result.success) {
755
- nodeRun.status = 'success';
756
- run.logs.push(createRunLog('info', `node completed: ${nodeRun.id}`));
757
- break;
758
- }
759
- if (signal && signal.aborted) {
760
- nodeRun.status = 'cancelled';
761
- nodeRun.summary = '执行中取消';
762
- break;
763
- }
764
- if (attempt < maxAttempts) {
765
- nodeRun.status = 'running';
766
- run.logs.push(createRunLog('warn', `node retry scheduled: ${nodeRun.id}`, {
767
- nextAttempt: attempt + 1,
768
- error: nodeRun.error
769
- }));
770
- continue;
771
- }
772
- nodeRun.status = 'failed';
773
- run.logs.push(createRunLog('error', `node failed: ${nodeRun.id}`, { error: nodeRun.error }));
774
- }
775
- return {
776
- nodeId: nodeRun.id,
777
- wantsWrite,
778
- abort: result && result.abortHandler ? result.abortHandler : null
779
- };
780
- })();
781
- active.set(nodeRun.id, {
782
- promise,
783
- abort() {
784
- const current = active.get(nodeRun.id);
785
- if (current && typeof current._abort === 'function') {
786
- current._abort();
787
- }
788
- },
789
- _abort: null,
790
- wantsWrite
791
- });
792
- await emitUpdate();
793
- }
794
-
795
- if (active.size === 0) {
796
- const pending = run.nodes.some((nodeRun) => nodeRun.status === 'pending');
797
- if (!pending) {
798
- break;
799
- }
800
- if (!started) {
801
- markBlockedNodes();
802
- const stillPending = run.nodes.some((nodeRun) => nodeRun.status === 'pending');
803
- if (!stillPending) {
804
- break;
805
- }
806
- run.logs.push(createRunLog('error', 'task run stalled because no nodes can be scheduled'));
807
- run.status = 'failed';
808
- run.error = 'task run stalled because no nodes can be scheduled';
809
- break;
810
- }
811
- }
812
-
813
- if (active.size > 0) {
814
- const settled = await Promise.race(Array.from(active.entries()).map(([nodeId, state]) => state.promise
815
- .then((payload) => ({ nodeId, payload }))
816
- .catch((error) => ({ nodeId, payload: { error: error && error.message ? error.message : String(error || 'task failed') } }))));
817
- const settledState = active.get(settled.nodeId);
818
- active.delete(settled.nodeId);
819
- if (settledState && settledState.wantsWrite) {
820
- writeLock = false;
821
- }
822
- await emitUpdate();
823
- }
824
- }
825
- } catch (error) {
826
- run.status = 'failed';
827
- run.error = error && error.message ? error.message : String(error || 'task run failed');
828
- run.logs.push(createRunLog('error', run.error));
829
- }
830
-
831
- const endedAtTs = Date.now();
832
- run.endedAt = new Date(endedAtTs).toISOString();
833
- run.durationMs = endedAtTs - startedAtTs;
834
- if (!run.status || run.status === 'running') {
835
- if (run.nodes.some((node) => node.status === 'failed')) {
836
- run.status = 'failed';
837
- } else if (run.nodes.some((node) => node.status === 'cancelled')) {
838
- run.status = 'cancelled';
839
- } else if (run.nodes.every((node) => node.status === 'success' || node.status === 'skipped')) {
840
- run.status = 'success';
841
- } else if (run.nodes.some((node) => node.status === 'blocked')) {
842
- run.status = 'failed';
843
- } else {
844
- run.status = 'failed';
845
- }
846
- }
847
- const lastCompletedNode = [...run.nodes].reverse().find((node) => node.summary || node.error);
848
- run.summary = truncateText(
849
- lastCompletedNode && (lastCompletedNode.summary || lastCompletedNode.error)
850
- ? (lastCompletedNode.summary || lastCompletedNode.error)
851
- : (run.status === 'success' ? '任务执行完成' : '任务执行失败'),
852
- 400
853
- );
854
- if (!run.error && run.status !== 'success') {
855
- const failedNode = run.nodes.find((node) => node.status === 'failed' || node.status === 'blocked' || node.status === 'cancelled');
856
- run.error = failedNode ? (failedNode.error || failedNode.summary) : 'task run failed';
857
- }
858
- await emitUpdate();
859
- return run;
860
- }
861
-
862
- module.exports = {
863
- truncateText,
864
- splitTargetIntoItems,
865
- computePlanWaves,
866
- buildTaskPlan,
867
- validateTaskPlan,
868
- executeTaskPlan
869
- };
1
+ function isPlainObject(value) {
2
+ return !!value && typeof value === 'object' && !Array.isArray(value);
3
+ }
4
+
5
+ function cloneJson(value, fallback = null) {
6
+ try {
7
+ return JSON.parse(JSON.stringify(value));
8
+ } catch (_) {
9
+ return fallback;
10
+ }
11
+ }
12
+
13
+ function normalizeText(value, maxLength = 4000) {
14
+ const text = value === undefined || value === null ? '' : String(value).trim();
15
+ if (!text) {
16
+ return '';
17
+ }
18
+ return text.length > maxLength ? text.slice(0, maxLength) : text;
19
+ }
20
+
21
+ function normalizeId(value, fallback = '') {
22
+ const text = String(value || '').trim().toLowerCase();
23
+ const normalized = text
24
+ .replace(/[^a-z0-9._-]+/g, '-')
25
+ .replace(/-{2,}/g, '-')
26
+ .replace(/^-+|-+$/g, '');
27
+ return normalized || fallback;
28
+ }
29
+
30
+ function normalizePositiveInteger(value, fallback, min = 1, max = 8) {
31
+ const numeric = Number.parseInt(String(value), 10);
32
+ if (!Number.isFinite(numeric)) {
33
+ return fallback;
34
+ }
35
+ return Math.min(max, Math.max(min, Math.floor(numeric)));
36
+ }
37
+
38
+ function truncateText(value, maxLength = 240) {
39
+ const text = String(value || '').trim();
40
+ if (!text) {
41
+ return '';
42
+ }
43
+ if (text.length <= maxLength) {
44
+ return text;
45
+ }
46
+ return `${text.slice(0, Math.max(0, maxLength - 1))}…`;
47
+ }
48
+
49
+ function uniqueStringList(input = []) {
50
+ const result = [];
51
+ const seen = new Set();
52
+ for (const item of Array.isArray(input) ? input : []) {
53
+ const text = normalizeText(item, 400);
54
+ if (!text || seen.has(text)) {
55
+ continue;
56
+ }
57
+ seen.add(text);
58
+ result.push(text);
59
+ }
60
+ return result;
61
+ }
62
+
63
+ function splitTargetIntoItems(target) {
64
+ const source = normalizeText(target, 12000);
65
+ if (!source) {
66
+ return [];
67
+ }
68
+ const lines = source
69
+ .split(/\r?\n/g)
70
+ .map((line) => line.trim())
71
+ .filter(Boolean)
72
+ .map((line) => line.replace(/^[-*+•]\s+/, '').replace(/^\d+[.)]\s+/, '').trim())
73
+ .filter(Boolean);
74
+ if (lines.length >= 2) {
75
+ return uniqueStringList(lines).slice(0, 6);
76
+ }
77
+
78
+ const segments = source
79
+ .split(/[;;。\n]+/g)
80
+ .map((part) => part.trim())
81
+ .filter(Boolean)
82
+ .map((part) => part.replace(/^[-*+•]\s+/, '').replace(/^\d+[.)]\s+/, '').trim())
83
+ .filter(Boolean);
84
+ if (segments.length >= 2) {
85
+ return uniqueStringList(segments).slice(0, 6);
86
+ }
87
+
88
+ return [truncateText(source, 220)];
89
+ }
90
+
91
+ function buildTaskTitle(target, explicitTitle = '') {
92
+ const custom = normalizeText(explicitTitle, 160);
93
+ if (custom) {
94
+ return custom;
95
+ }
96
+ const normalizedTarget = normalizeText(target, 400);
97
+ if (!normalizedTarget) {
98
+ return '未命名任务';
99
+ }
100
+ return truncateText(normalizedTarget.replace(/\s+/g, ' '), 96);
101
+ }
102
+
103
+ function normalizeDependencyIds(value = []) {
104
+ return uniqueStringList(value)
105
+ .map((depId) => normalizeId(depId, ''))
106
+ .filter(Boolean);
107
+ }
108
+
109
+ function computePlanWaves(nodes = []) {
110
+ const list = Array.isArray(nodes) ? nodes : [];
111
+ const byId = new Map();
112
+ const indegree = new Map();
113
+ const outgoing = new Map();
114
+ for (const node of list) {
115
+ const id = normalizeId(node && node.id, '');
116
+ if (!id) continue;
117
+ byId.set(id, node);
118
+ indegree.set(id, 0);
119
+ outgoing.set(id, []);
120
+ }
121
+ for (const node of list) {
122
+ const id = normalizeId(node && node.id, '');
123
+ if (!id) continue;
124
+ const dependsOn = normalizeDependencyIds(node && node.dependsOn).filter((depId) => byId.has(depId));
125
+ indegree.set(id, dependsOn.length);
126
+ for (const depId of dependsOn) {
127
+ outgoing.get(depId).push(id);
128
+ }
129
+ }
130
+
131
+ const remaining = new Set(byId.keys());
132
+ const waves = [];
133
+ while (remaining.size > 0) {
134
+ const ready = Array.from(remaining).filter((id) => (indegree.get(id) || 0) === 0);
135
+ if (ready.length === 0) {
136
+ waves.push(Array.from(remaining));
137
+ break;
138
+ }
139
+ ready.sort();
140
+ waves.push(ready);
141
+ for (const id of ready) {
142
+ remaining.delete(id);
143
+ const nextIds = outgoing.get(id) || [];
144
+ for (const nextId of nextIds) {
145
+ indegree.set(nextId, Math.max(0, (indegree.get(nextId) || 0) - 1));
146
+ }
147
+ }
148
+ }
149
+
150
+ return waves.map((wave, index) => ({
151
+ index,
152
+ nodeIds: wave,
153
+ label: `Wave ${index + 1}`
154
+ }));
155
+ }
156
+
157
+ function detectDependencyCycle(nodes = []) {
158
+ const list = Array.isArray(nodes) ? nodes : [];
159
+ const graph = new Map();
160
+ for (const node of list) {
161
+ const id = normalizeId(node && node.id, '');
162
+ if (!id) continue;
163
+ graph.set(id, uniqueStringList(node && node.dependsOn).map((depId) => normalizeId(depId, '')).filter(Boolean));
164
+ }
165
+ const visiting = new Set();
166
+ const visited = new Set();
167
+ const visit = (id) => {
168
+ if (visited.has(id)) {
169
+ return false;
170
+ }
171
+ if (visiting.has(id)) {
172
+ return true;
173
+ }
174
+ visiting.add(id);
175
+ const deps = graph.get(id) || [];
176
+ for (const depId of deps) {
177
+ if (!graph.has(depId)) {
178
+ continue;
179
+ }
180
+ if (visit(depId)) {
181
+ return true;
182
+ }
183
+ }
184
+ visiting.delete(id);
185
+ visited.add(id);
186
+ return false;
187
+ };
188
+ for (const id of graph.keys()) {
189
+ if (visit(id)) {
190
+ return true;
191
+ }
192
+ }
193
+ return false;
194
+ }
195
+
196
+ function buildCodexNodePrompt(kind, context = {}) {
197
+ const title = normalizeText(context.title, 160);
198
+ const target = normalizeText(context.target, 4000);
199
+ const item = normalizeText(context.item, 1200);
200
+ const followUp = normalizeText(context.followUp, 1200);
201
+ const dependencySummaries = uniqueStringList(context.dependencySummaries || []).slice(0, 6);
202
+ const allowWrite = context.allowWrite === true;
203
+ const dependencyBlock = dependencySummaries.length > 0
204
+ ? `\n已完成前置摘要:\n${dependencySummaries.map((entry, index) => `${index + 1}. ${entry}`).join('\n')}`
205
+ : '';
206
+ const writeRule = allowWrite
207
+ ? '允许直接修改本地工作区,但必须控制变更范围并完成最小必要验证。'
208
+ : '只允许只读调查,不要修改任何文件,不要执行写入型操作。';
209
+
210
+ if (kind === 'analysis') {
211
+ return [
212
+ `任务标题: ${title || '任务分析'}`,
213
+ `任务目标:\n${target}`,
214
+ writeRule,
215
+ '请先调查当前仓库与上下文,给出简洁的现状判断、主要风险、建议执行顺序,以及你认为最小可行的验证方案。',
216
+ '输出请保持简洁,聚焦可执行信息。'
217
+ ].join('\n\n');
218
+ }
219
+
220
+ if (kind === 'work') {
221
+ return [
222
+ `任务标题: ${title || '执行子任务'}`,
223
+ `总目标:\n${target}`,
224
+ `当前子任务:\n${item || title || target}`,
225
+ dependencyBlock,
226
+ writeRule,
227
+ '请只处理当前子任务范围,避免越界修改。完成后说明实际改动、验证结果与剩余风险。'
228
+ ].join('\n\n');
229
+ }
230
+
231
+ if (kind === 'verify') {
232
+ return [
233
+ `任务标题: ${title || '验证与总结'}`,
234
+ `总目标:\n${target}`,
235
+ dependencyBlock,
236
+ writeRule,
237
+ '请基于当前工作区状态执行最小必要验证,检查明显回归,并输出结果摘要、未完成项和建议下一步。'
238
+ ].join('\n\n');
239
+ }
240
+
241
+ return [
242
+ `任务标题: ${title || '后续任务'}`,
243
+ `总目标:\n${target}`,
244
+ dependencyBlock,
245
+ writeRule,
246
+ `追加指令:\n${followUp || item || target}`,
247
+ '请严格围绕上述后续指令继续推进,并给出结果摘要。'
248
+ ].join('\n\n');
249
+ }
250
+
251
+ function normalizeWorkflowCatalog(workflowCatalog = []) {
252
+ const map = new Map();
253
+ for (const item of Array.isArray(workflowCatalog) ? workflowCatalog : []) {
254
+ const id = normalizeId(item && item.id, '');
255
+ if (!id) continue;
256
+ map.set(id, {
257
+ id,
258
+ name: normalizeText(item.name || id, 160) || id,
259
+ description: normalizeText(item.description, 600),
260
+ readOnly: item && item.readOnly !== false
261
+ });
262
+ }
263
+ return map;
264
+ }
265
+
266
+ function buildTaskPlan(request = {}, options = {}) {
267
+ const workflowMap = normalizeWorkflowCatalog(options.workflowCatalog || []);
268
+ const target = normalizeText(request.target, 4000);
269
+ const title = buildTaskTitle(target, request.title);
270
+ const engine = normalizeId(request.engine, 'codex') === 'workflow' ? 'workflow' : 'codex';
271
+ const allowWrite = request.allowWrite === true;
272
+ const dryRun = request.dryRun === true;
273
+ const concurrency = normalizePositiveInteger(request.concurrency, 2, 1, 8);
274
+ const autoFixRounds = normalizePositiveInteger(request.autoFixRounds, 1, 0, 5);
275
+ const requestedWorkflowIds = uniqueStringList(request.workflowIds || [])
276
+ .map((id) => normalizeId(id, ''))
277
+ .filter(Boolean);
278
+ const followUps = uniqueStringList(request.followUps || []);
279
+ const notes = normalizeText(request.notes, 2000);
280
+ const cwd = normalizeText(request.cwd || options.cwd, 1200);
281
+ const nodes = [];
282
+ let nodeSequence = 0;
283
+ const nextNodeId = (prefix) => `${prefix}-${String(++nodeSequence).padStart(2, '0')}`;
284
+ const shouldBuildWorkflowNodes = requestedWorkflowIds.length > 0 || engine === 'workflow';
285
+
286
+ if (shouldBuildWorkflowNodes) {
287
+ let previousId = '';
288
+ for (const workflowId of requestedWorkflowIds) {
289
+ const meta = workflowMap.get(workflowId);
290
+ const nodeId = nextNodeId('workflow');
291
+ const isLastWorkflowNode = requestedWorkflowIds.length > 0 && workflowId === requestedWorkflowIds[requestedWorkflowIds.length - 1];
292
+ nodes.push({
293
+ id: nodeId,
294
+ title: meta ? meta.name : workflowId,
295
+ kind: 'workflow',
296
+ workflowId,
297
+ dependsOn: previousId ? [previousId] : [],
298
+ write: !!(meta && meta.readOnly === false),
299
+ retryLimit: 0,
300
+ autoFixRounds,
301
+ input: {
302
+ target,
303
+ title,
304
+ notes,
305
+ ...(isLastWorkflowNode && followUps.length > 0 ? { followUps: followUps.slice() } : {})
306
+ }
307
+ });
308
+ previousId = nodeId;
309
+ }
310
+ } else {
311
+ const items = splitTargetIntoItems(target);
312
+ const analysisId = nextNodeId('analysis');
313
+ nodes.push({
314
+ id: analysisId,
315
+ title: '现状分析',
316
+ kind: 'codex',
317
+ prompt: buildCodexNodePrompt('analysis', {
318
+ title,
319
+ target,
320
+ allowWrite: false
321
+ }),
322
+ dependsOn: [],
323
+ write: false,
324
+ retryLimit: 0,
325
+ autoFixRounds: 0
326
+ });
327
+
328
+ const executionNodeIds = [];
329
+ const workItems = items.length > 0 ? items : [target || title];
330
+ for (const item of workItems) {
331
+ const nodeId = nextNodeId('work');
332
+ executionNodeIds.push(nodeId);
333
+ nodes.push({
334
+ id: nodeId,
335
+ title: truncateText(item, 72) || `执行 ${executionNodeIds.length}`,
336
+ kind: 'codex',
337
+ prompt: buildCodexNodePrompt('work', {
338
+ title,
339
+ target,
340
+ item,
341
+ allowWrite
342
+ }),
343
+ dependsOn: [analysisId],
344
+ write: allowWrite,
345
+ retryLimit: 0,
346
+ autoFixRounds
347
+ });
348
+ }
349
+
350
+ const verifyId = nextNodeId('verify');
351
+ nodes.push({
352
+ id: verifyId,
353
+ title: '验证与总结',
354
+ kind: 'codex',
355
+ prompt: buildCodexNodePrompt('verify', {
356
+ title,
357
+ target,
358
+ allowWrite: false
359
+ }),
360
+ dependsOn: executionNodeIds.slice(),
361
+ write: false,
362
+ retryLimit: 0,
363
+ autoFixRounds: 0
364
+ });
365
+ }
366
+
367
+ if (engine !== 'workflow') {
368
+ let followUpDependsOn = nodes.length > 0 ? [nodes[nodes.length - 1].id] : [];
369
+ for (const followUp of followUps) {
370
+ const nodeId = nextNodeId('follow-up');
371
+ nodes.push({
372
+ id: nodeId,
373
+ title: truncateText(followUp, 72) || `Follow-up ${nodes.length + 1}`,
374
+ kind: 'codex',
375
+ prompt: buildCodexNodePrompt('follow-up', {
376
+ title,
377
+ target,
378
+ allowWrite,
379
+ followUp
380
+ }),
381
+ dependsOn: followUpDependsOn,
382
+ write: allowWrite,
383
+ retryLimit: 0,
384
+ autoFixRounds
385
+ });
386
+ followUpDependsOn = [nodeId];
387
+ }
388
+ }
389
+
390
+ const plan = {
391
+ id: normalizeId(request.id, ''),
392
+ title,
393
+ target,
394
+ notes,
395
+ cwd,
396
+ engine,
397
+ allowWrite,
398
+ dryRun,
399
+ concurrency,
400
+ autoFixRounds,
401
+ workflowIds: requestedWorkflowIds,
402
+ followUps,
403
+ nodes,
404
+ waves: computePlanWaves(nodes)
405
+ };
406
+ return plan;
407
+ }
408
+
409
+ function validateTaskPlan(plan, options = {}) {
410
+ const issues = [];
411
+ if (!isPlainObject(plan)) {
412
+ return {
413
+ ok: false,
414
+ error: 'task plan must be an object',
415
+ issues: [{ code: 'task-plan-invalid', message: 'task plan must be an object' }]
416
+ };
417
+ }
418
+
419
+ const workflowMap = normalizeWorkflowCatalog(options.workflowCatalog || []);
420
+ const engine = normalizeId(plan.engine, 'codex') === 'workflow' ? 'workflow' : 'codex';
421
+ const workflowIds = uniqueStringList(plan.workflowIds || []).map((id) => normalizeId(id, '')).filter(Boolean);
422
+ const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
423
+ if (engine === 'workflow' && workflowIds.length === 0) {
424
+ issues.push({ code: 'task-plan-workflow-required', message: 'workflow engine requires at least one workflowId' });
425
+ }
426
+ if (engine === 'workflow' && nodes.some((node) => normalizeId(node && node.kind, '') !== 'workflow')) {
427
+ issues.push({ code: 'task-plan-engine-mismatch', message: 'workflow engine plan cannot contain non-workflow nodes' });
428
+ }
429
+ if (nodes.length === 0) {
430
+ issues.push({ code: 'task-plan-nodes-required', message: 'task plan must contain at least one node' });
431
+ }
432
+ const nodeIds = new Set();
433
+ for (const node of nodes) {
434
+ if (!isPlainObject(node)) {
435
+ issues.push({ code: 'task-node-invalid', message: 'task node must be an object' });
436
+ continue;
437
+ }
438
+ const id = normalizeId(node.id, '');
439
+ if (!id) {
440
+ issues.push({ code: 'task-node-id-required', message: 'task node id is required' });
441
+ continue;
442
+ }
443
+ if (nodeIds.has(id)) {
444
+ issues.push({ code: 'task-node-id-duplicate', message: `duplicate task node id: ${id}` });
445
+ continue;
446
+ }
447
+ nodeIds.add(id);
448
+ const kind = normalizeId(node.kind, '');
449
+ if (kind !== 'workflow' && kind !== 'codex') {
450
+ issues.push({ code: 'task-node-kind-invalid', message: `task node ${id} has unsupported kind: ${node.kind || ''}` });
451
+ }
452
+ if (kind === 'workflow') {
453
+ const workflowId = normalizeId(node.workflowId, '');
454
+ if (!workflowId) {
455
+ issues.push({ code: 'task-node-workflow-required', message: `task node ${id} missing workflowId` });
456
+ } else if (workflowMap.size > 0 && !workflowMap.has(workflowId)) {
457
+ issues.push({ code: 'task-node-workflow-unknown', message: `task node ${id} references unknown workflow: ${workflowId}` });
458
+ }
459
+ }
460
+ if (kind === 'codex' && !normalizeText(node.prompt, 12000)) {
461
+ issues.push({ code: 'task-node-prompt-required', message: `task node ${id} missing prompt` });
462
+ }
463
+ }
464
+
465
+ if (issues.length === 0) {
466
+ for (const node of nodes) {
467
+ const id = normalizeId(node.id, '');
468
+ const dependsOn = normalizeDependencyIds(node.dependsOn || []);
469
+ for (const depId of dependsOn) {
470
+ if (!nodeIds.has(depId)) {
471
+ issues.push({ code: 'task-node-dependency-missing', message: `task node ${id} depends on missing node: ${depId}` });
472
+ }
473
+ if (depId === id) {
474
+ issues.push({ code: 'task-node-dependency-self', message: `task node ${id} cannot depend on itself` });
475
+ }
476
+ }
477
+ }
478
+ }
479
+
480
+ if (issues.length === 0 && detectDependencyCycle(nodes)) {
481
+ issues.push({ code: 'task-plan-cycle-detected', message: 'task plan contains a dependency cycle' });
482
+ }
483
+
484
+ return {
485
+ ok: issues.length === 0,
486
+ error: issues[0] ? issues[0].message : '',
487
+ issues
488
+ };
489
+ }
490
+
491
+ function createNodeRunRecord(node, dependencyNodeIds = []) {
492
+ return {
493
+ id: normalizeId(node && node.id, ''),
494
+ title: normalizeText(node && node.title, 160),
495
+ kind: normalizeId(node && node.kind, ''),
496
+ workflowId: normalizeId(node && node.workflowId, ''),
497
+ dependsOn: normalizeDependencyIds(node && node.dependsOn),
498
+ dependencyNodeIds: uniqueStringList(dependencyNodeIds),
499
+ write: node && node.write === true,
500
+ status: 'pending',
501
+ attemptCount: 0,
502
+ autoFixRounds: normalizePositiveInteger(node && node.autoFixRounds, 0, 0, 5),
503
+ retryLimit: normalizePositiveInteger(node && node.retryLimit, 0, 0, 5),
504
+ startedAt: '',
505
+ endedAt: '',
506
+ durationMs: 0,
507
+ summary: '',
508
+ error: '',
509
+ output: null,
510
+ logs: [],
511
+ attempts: []
512
+ };
513
+ }
514
+
515
+ function createRunLog(level, message, extra = {}) {
516
+ return {
517
+ at: new Date().toISOString(),
518
+ level: level || 'info',
519
+ message: normalizeText(message, 1000),
520
+ ...cloneJson(extra, {})
521
+ };
522
+ }
523
+
524
+ async function executeTaskPlan(plan, options = {}) {
525
+ const executeNode = typeof options.executeNode === 'function'
526
+ ? options.executeNode
527
+ : async () => ({ success: false, error: 'executeNode is not configured' });
528
+ const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
529
+ const signal = options.signal || null;
530
+ const startedAtTs = Date.now();
531
+ const concurrency = normalizePositiveInteger(options.concurrency || plan.concurrency, 2, 1, 8);
532
+ const nodeList = Array.isArray(plan && plan.nodes) ? plan.nodes : [];
533
+ const run = {
534
+ status: 'running',
535
+ startedAt: new Date(startedAtTs).toISOString(),
536
+ endedAt: '',
537
+ durationMs: 0,
538
+ concurrency,
539
+ waves: computePlanWaves(nodeList),
540
+ nodes: nodeList.map((node) => createNodeRunRecord(node)),
541
+ logs: [createRunLog('info', 'task run started', { concurrency })],
542
+ summary: '',
543
+ error: ''
544
+ };
545
+
546
+ const nodeMap = new Map();
547
+ for (const node of run.nodes) {
548
+ nodeMap.set(node.id, node);
549
+ }
550
+
551
+ const emitUpdate = async () => {
552
+ if (!onUpdate) {
553
+ return;
554
+ }
555
+ await onUpdate(cloneJson(run, run));
556
+ };
557
+
558
+ const active = new Map();
559
+ let writeLock = false;
560
+
561
+ const finalizeNode = (nodeRun, payload, attemptStartedAt, attemptIndex) => {
562
+ const endedAtTs = Date.now();
563
+ const success = !!(payload && payload.success === true);
564
+ const error = success ? '' : normalizeText(payload && payload.error, 2000) || `node failed: ${nodeRun.id}`;
565
+ const preserveCancelledState = run.status === 'cancelled' || nodeRun.status === 'cancelled';
566
+ nodeRun.attempts.push({
567
+ index: attemptIndex,
568
+ startedAt: new Date(attemptStartedAt).toISOString(),
569
+ endedAt: new Date(endedAtTs).toISOString(),
570
+ durationMs: endedAtTs - attemptStartedAt,
571
+ success,
572
+ error,
573
+ summary: truncateText(payload && payload.summary, 400),
574
+ output: cloneJson(payload && payload.output, null),
575
+ logs: cloneJson(payload && payload.logs, [])
576
+ });
577
+ nodeRun.logs = cloneJson(payload && payload.logs, []);
578
+ if (!preserveCancelledState) {
579
+ nodeRun.output = cloneJson(payload && payload.output, null);
580
+ nodeRun.summary = truncateText(payload && payload.summary, 400);
581
+ nodeRun.error = error;
582
+ }
583
+ nodeRun.startedAt = nodeRun.startedAt || new Date(attemptStartedAt).toISOString();
584
+ nodeRun.endedAt = new Date(endedAtTs).toISOString();
585
+ nodeRun.durationMs = endedAtTs - new Date(nodeRun.startedAt).getTime();
586
+ return {
587
+ success: preserveCancelledState ? false : success,
588
+ error: preserveCancelledState ? (nodeRun.error || 'cancelled while running') : error
589
+ };
590
+ };
591
+
592
+ const executeOneNode = async (nodeRun, nodeDef, hooks = {}) => {
593
+ nodeRun.status = 'running';
594
+ if (!nodeRun.startedAt) {
595
+ nodeRun.startedAt = new Date().toISOString();
596
+ }
597
+ nodeRun.attemptCount += 1;
598
+ const attemptIndex = nodeRun.attemptCount;
599
+ const attemptStartedAt = Date.now();
600
+ const dependencyResults = (nodeRun.dependsOn || [])
601
+ .map((depId) => nodeMap.get(depId))
602
+ .filter(Boolean)
603
+ .map((dep) => ({
604
+ id: dep.id,
605
+ status: dep.status,
606
+ summary: dep.summary,
607
+ error: dep.error,
608
+ output: cloneJson(dep.output, null)
609
+ }));
610
+ const attemptLogs = [createRunLog('info', `starting node ${nodeRun.id}`, { attempt: attemptIndex })];
611
+ let abortHandler = null;
612
+ try {
613
+ const payload = await executeNode(nodeDef, {
614
+ attempt: attemptIndex,
615
+ maxAttempts: 1 + Math.max(nodeRun.retryLimit, 0) + Math.max(nodeRun.autoFixRounds, 0),
616
+ dependencyResults,
617
+ signal,
618
+ registerAbort(handler) {
619
+ abortHandler = typeof handler === 'function' ? handler : null;
620
+ if (typeof hooks.onAbortChange === 'function') {
621
+ hooks.onAbortChange(abortHandler);
622
+ }
623
+ },
624
+ previousAttempts: cloneJson(nodeRun.attempts, [])
625
+ });
626
+ attemptLogs.push(...(Array.isArray(payload && payload.logs) ? payload.logs : []));
627
+ const finalized = finalizeNode(nodeRun, {
628
+ ...payload,
629
+ logs: attemptLogs
630
+ }, attemptStartedAt, attemptIndex);
631
+ return {
632
+ success: finalized.success,
633
+ error: finalized.error,
634
+ abortHandler
635
+ };
636
+ } catch (error) {
637
+ const message = error && error.message ? error.message : String(error || 'task node execution failed');
638
+ const finalized = finalizeNode(nodeRun, {
639
+ success: false,
640
+ error: message,
641
+ output: null,
642
+ summary: message,
643
+ logs: attemptLogs.concat(createRunLog('error', message))
644
+ }, attemptStartedAt, attemptIndex);
645
+ return {
646
+ success: false,
647
+ error: finalized.error,
648
+ abortHandler
649
+ };
650
+ }
651
+ };
652
+
653
+ const getPendingNodeDefs = () => nodeList.filter((node) => {
654
+ const nodeRun = nodeMap.get(normalizeId(node && node.id, ''));
655
+ return !!nodeRun && nodeRun.status === 'pending';
656
+ });
657
+
658
+ const hasFailedDependency = (nodeRun) => (nodeRun.dependsOn || []).some((depId) => {
659
+ const dep = nodeMap.get(depId);
660
+ return dep && (dep.status === 'failed' || dep.status === 'blocked' || dep.status === 'cancelled');
661
+ });
662
+
663
+ const isReady = (nodeRun) => (nodeRun.dependsOn || []).every((depId) => {
664
+ const dep = nodeMap.get(depId);
665
+ return dep && (dep.status === 'success' || dep.status === 'skipped');
666
+ });
667
+
668
+ const markBlockedNodes = () => {
669
+ for (const nodeRun of run.nodes) {
670
+ if (nodeRun.status !== 'pending') continue;
671
+ if (!hasFailedDependency(nodeRun)) continue;
672
+ nodeRun.status = 'blocked';
673
+ nodeRun.error = 'blocked by failed dependency';
674
+ nodeRun.summary = '前置节点失败,已阻塞';
675
+ nodeRun.startedAt = nodeRun.startedAt || new Date().toISOString();
676
+ nodeRun.endedAt = new Date().toISOString();
677
+ run.logs.push(createRunLog('warn', `node blocked: ${nodeRun.id}`));
678
+ }
679
+ };
680
+
681
+ const abortActiveNodes = () => {
682
+ for (const activeRun of active.values()) {
683
+ if (activeRun && typeof activeRun.abort === 'function') {
684
+ try {
685
+ activeRun.abort();
686
+ } catch (_) {}
687
+ }
688
+ }
689
+ };
690
+
691
+ try {
692
+ while (true) {
693
+ if (signal && signal.aborted) {
694
+ abortActiveNodes();
695
+ for (const nodeRun of run.nodes) {
696
+ if (nodeRun.status === 'pending') {
697
+ nodeRun.status = 'cancelled';
698
+ nodeRun.error = 'cancelled before start';
699
+ nodeRun.summary = '已取消';
700
+ } else if (nodeRun.status === 'running') {
701
+ nodeRun.status = 'cancelled';
702
+ nodeRun.error = 'cancelled while running';
703
+ nodeRun.summary = '执行中取消';
704
+ }
705
+ }
706
+ run.logs.push(createRunLog('warn', 'task run cancelled'));
707
+ run.status = 'cancelled';
708
+ if (active.size > 0) {
709
+ await Promise.allSettled(Array.from(active.values()).map((item) => item && item.promise).filter(Boolean));
710
+ active.clear();
711
+ writeLock = false;
712
+ }
713
+ break;
714
+ }
715
+
716
+ markBlockedNodes();
717
+ const readyNodeDefs = getPendingNodeDefs().filter((node) => {
718
+ const nodeRun = nodeMap.get(normalizeId(node && node.id, ''));
719
+ return nodeRun && isReady(nodeRun);
720
+ });
721
+ let started = false;
722
+ for (const nodeDef of readyNodeDefs) {
723
+ if (active.size >= concurrency) {
724
+ break;
725
+ }
726
+ const nodeRun = nodeMap.get(normalizeId(nodeDef && nodeDef.id, ''));
727
+ if (!nodeRun) continue;
728
+ const wantsWrite = nodeRun.write === true;
729
+ if (writeLock && wantsWrite) {
730
+ continue;
731
+ }
732
+ if (wantsWrite && active.size > 0) {
733
+ continue;
734
+ }
735
+ if (!wantsWrite && writeLock) {
736
+ continue;
737
+ }
738
+ started = true;
739
+ if (wantsWrite) {
740
+ writeLock = true;
741
+ }
742
+ const promise = (async () => {
743
+ let result = null;
744
+ const maxAttempts = 1 + Math.max(nodeRun.retryLimit, 0) + Math.max(nodeRun.autoFixRounds, 0);
745
+ for (let attempt = nodeRun.attemptCount + 1; attempt <= maxAttempts; attempt += 1) {
746
+ result = await executeOneNode(nodeRun, nodeDef, {
747
+ onAbortChange(handler) {
748
+ const current = active.get(nodeRun.id);
749
+ if (current) {
750
+ current._abort = typeof handler === 'function' ? handler : null;
751
+ }
752
+ }
753
+ });
754
+ if (result.success) {
755
+ nodeRun.status = 'success';
756
+ run.logs.push(createRunLog('info', `node completed: ${nodeRun.id}`));
757
+ break;
758
+ }
759
+ if (signal && signal.aborted) {
760
+ nodeRun.status = 'cancelled';
761
+ nodeRun.summary = '执行中取消';
762
+ break;
763
+ }
764
+ if (attempt < maxAttempts) {
765
+ nodeRun.status = 'running';
766
+ run.logs.push(createRunLog('warn', `node retry scheduled: ${nodeRun.id}`, {
767
+ nextAttempt: attempt + 1,
768
+ error: nodeRun.error
769
+ }));
770
+ continue;
771
+ }
772
+ nodeRun.status = 'failed';
773
+ run.logs.push(createRunLog('error', `node failed: ${nodeRun.id}`, { error: nodeRun.error }));
774
+ }
775
+ return {
776
+ nodeId: nodeRun.id,
777
+ wantsWrite,
778
+ abort: result && result.abortHandler ? result.abortHandler : null
779
+ };
780
+ })();
781
+ active.set(nodeRun.id, {
782
+ promise,
783
+ abort() {
784
+ const current = active.get(nodeRun.id);
785
+ if (current && typeof current._abort === 'function') {
786
+ current._abort();
787
+ }
788
+ },
789
+ _abort: null,
790
+ wantsWrite
791
+ });
792
+ await emitUpdate();
793
+ }
794
+
795
+ if (active.size === 0) {
796
+ const pending = run.nodes.some((nodeRun) => nodeRun.status === 'pending');
797
+ if (!pending) {
798
+ break;
799
+ }
800
+ if (!started) {
801
+ markBlockedNodes();
802
+ const stillPending = run.nodes.some((nodeRun) => nodeRun.status === 'pending');
803
+ if (!stillPending) {
804
+ break;
805
+ }
806
+ run.logs.push(createRunLog('error', 'task run stalled because no nodes can be scheduled'));
807
+ run.status = 'failed';
808
+ run.error = 'task run stalled because no nodes can be scheduled';
809
+ break;
810
+ }
811
+ }
812
+
813
+ if (active.size > 0) {
814
+ const settled = await Promise.race(Array.from(active.entries()).map(([nodeId, state]) => state.promise
815
+ .then((payload) => ({ nodeId, payload }))
816
+ .catch((error) => ({ nodeId, payload: { error: error && error.message ? error.message : String(error || 'task failed') } }))));
817
+ const settledState = active.get(settled.nodeId);
818
+ active.delete(settled.nodeId);
819
+ if (settledState && settledState.wantsWrite) {
820
+ writeLock = false;
821
+ }
822
+ await emitUpdate();
823
+ }
824
+ }
825
+ } catch (error) {
826
+ run.status = 'failed';
827
+ run.error = error && error.message ? error.message : String(error || 'task run failed');
828
+ run.logs.push(createRunLog('error', run.error));
829
+ }
830
+
831
+ const endedAtTs = Date.now();
832
+ run.endedAt = new Date(endedAtTs).toISOString();
833
+ run.durationMs = endedAtTs - startedAtTs;
834
+ if (!run.status || run.status === 'running') {
835
+ if (run.nodes.some((node) => node.status === 'failed')) {
836
+ run.status = 'failed';
837
+ } else if (run.nodes.some((node) => node.status === 'cancelled')) {
838
+ run.status = 'cancelled';
839
+ } else if (run.nodes.every((node) => node.status === 'success' || node.status === 'skipped')) {
840
+ run.status = 'success';
841
+ } else if (run.nodes.some((node) => node.status === 'blocked')) {
842
+ run.status = 'failed';
843
+ } else {
844
+ run.status = 'failed';
845
+ }
846
+ }
847
+ const lastCompletedNode = [...run.nodes].reverse().find((node) => node.summary || node.error);
848
+ run.summary = truncateText(
849
+ lastCompletedNode && (lastCompletedNode.summary || lastCompletedNode.error)
850
+ ? (lastCompletedNode.summary || lastCompletedNode.error)
851
+ : (run.status === 'success' ? '任务执行完成' : '任务执行失败'),
852
+ 400
853
+ );
854
+ if (!run.error && run.status !== 'success') {
855
+ const failedNode = run.nodes.find((node) => node.status === 'failed' || node.status === 'blocked' || node.status === 'cancelled');
856
+ run.error = failedNode ? (failedNode.error || failedNode.summary) : 'task run failed';
857
+ }
858
+ await emitUpdate();
859
+ return run;
860
+ }
861
+
862
+ module.exports = {
863
+ truncateText,
864
+ splitTargetIntoItems,
865
+ computePlanWaves,
866
+ buildTaskPlan,
867
+ validateTaskPlan,
868
+ executeTaskPlan
869
+ };