codexmate 0.1.30 → 0.1.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 (77) hide show
  1. package/README.md +98 -7
  2. package/README.vi.md +98 -7
  3. package/README.zh.md +99 -7
  4. package/cli/agents-files.js +18 -4
  5. package/cli/config-bootstrap.js +25 -11
  6. package/cli/plugin-config.js +64 -0
  7. package/cli/prompt-history.js +17 -4
  8. package/cli/system-prompt-files.js +7 -2
  9. package/cli.js +396 -46
  10. package/lib/cli-config-engine.js +266 -0
  11. package/lib/cli-utils.js +2 -1
  12. package/lib/cli-webhook.js +1 -1
  13. package/lib/handoff-mcp.js +282 -0
  14. package/lib/http-access-control.js +335 -0
  15. package/lib/session-context-health.js +82 -0
  16. package/lib/session-context-records.js +153 -0
  17. package/lib/thread-handoff.js +130 -0
  18. package/lib/web-startup-auth.js +53 -0
  19. package/lib/workflow-engine.js +92 -21
  20. package/lib/workflow-runner.js +261 -0
  21. package/package.json +1 -1
  22. package/plugins/prompt-templates/computed.mjs +3 -3
  23. package/plugins/prompt-templates/invocation.mjs +73 -0
  24. package/plugins/prompt-templates/methods.mjs +48 -3
  25. package/plugins/prompt-templates/overview.mjs +2 -0
  26. package/web-ui/app.js +48 -2
  27. package/web-ui/index.html +1 -0
  28. package/web-ui/logic.context-health.mjs +144 -0
  29. package/web-ui/modules/access-token.mjs +33 -0
  30. package/web-ui/modules/api.mjs +2 -1
  31. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  32. package/web-ui/modules/app.methods.agents.mjs +20 -3
  33. package/web-ui/modules/app.methods.index.mjs +6 -0
  34. package/web-ui/modules/app.methods.navigation.mjs +17 -3
  35. package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
  36. package/web-ui/modules/app.methods.providers.mjs +2 -2
  37. package/web-ui/modules/app.methods.runtime.mjs +3 -2
  38. package/web-ui/modules/app.methods.session-actions.mjs +3 -0
  39. package/web-ui/modules/app.methods.session-browser.mjs +6 -2
  40. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  41. package/web-ui/modules/app.methods.workflows.mjs +41 -0
  42. package/web-ui/modules/context-health.methods.mjs +70 -0
  43. package/web-ui/modules/i18n/locales/en.mjs +70 -2
  44. package/web-ui/modules/i18n/locales/ja.mjs +70 -2
  45. package/web-ui/modules/i18n/locales/vi.mjs +70 -2
  46. package/web-ui/modules/i18n/locales/zh-tw.mjs +70 -2
  47. package/web-ui/modules/i18n/locales/zh.mjs +70 -2
  48. package/web-ui/modules/plugins.methods.mjs +2 -0
  49. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  50. package/web-ui/modules/sessions-filters-url.mjs +3 -0
  51. package/web-ui/modules/skills.methods.mjs +6 -5
  52. package/web-ui/modules/thread-handoff.mjs +142 -0
  53. package/web-ui/partials/index/context-health.html +45 -0
  54. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  55. package/web-ui/partials/index/panel-config-claude.html +2 -0
  56. package/web-ui/partials/index/panel-config-codex.html +2 -0
  57. package/web-ui/partials/index/panel-config-kilocode.html +3 -1
  58. package/web-ui/partials/index/panel-config-openclaw.html +2 -0
  59. package/web-ui/partials/index/panel-config-opencode.html +3 -1
  60. package/web-ui/partials/index/panel-config-pi.html +2 -0
  61. package/web-ui/partials/index/panel-dashboard.html +59 -0
  62. package/web-ui/partials/index/panel-plugins.html +37 -9
  63. package/web-ui/partials/index/panel-prompts.html +46 -18
  64. package/web-ui/partials/index/panel-sessions.html +35 -44
  65. package/web-ui/partials/index/thread-handoff.html +59 -0
  66. package/web-ui/res/web-ui-render.precompiled.js +1289 -177
  67. package/web-ui/styles/context-health.css +107 -0
  68. package/web-ui/styles/controls-forms.css +9 -0
  69. package/web-ui/styles/dashboard.css +51 -0
  70. package/web-ui/styles/modals-core.css +87 -0
  71. package/web-ui/styles/navigation-panels.css +1 -1
  72. package/web-ui/styles/plugins-panel.css +62 -0
  73. package/web-ui/styles/prompts-editor.css +34 -4
  74. package/web-ui/styles/responsive.css +19 -10
  75. package/web-ui/styles/sessions-preview.css +206 -111
  76. package/web-ui/styles/sub-tabs.css +181 -0
  77. package/web-ui/styles.css +2 -0
@@ -0,0 +1,130 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const crypto = require('crypto');
5
+ const { deliver } = require('./handoff-mcp');
6
+
7
+ function threadDirectory(threadId, options = {}) {
8
+ if (typeof threadId !== 'string' || !threadId.trim()) throw new Error('缺少 threadId');
9
+ const key = crypto.createHash('sha256').update(threadId).digest('hex');
10
+ return path.join(options.root || path.join(os.homedir(), '.codexmate', 'threads'), key);
11
+ }
12
+
13
+ function appendEvent(threadId, event, options) {
14
+ const directory = threadDirectory(threadId, options);
15
+ fs.mkdirSync(directory, { recursive: true });
16
+ fs.appendFileSync(path.join(directory, 'handoffs.jsonl'), JSON.stringify({ ...event, eventAt: new Date().toISOString() }) + '\n', { mode: 0o600 });
17
+ }
18
+
19
+ function listHandoffs(threadId, options) {
20
+ const file = path.join(threadDirectory(threadId, options), 'handoffs.jsonl');
21
+ if (!fs.existsSync(file)) return [];
22
+ const records = new Map();
23
+ for (const line of fs.readFileSync(file, 'utf8').split('\n').filter(Boolean)) {
24
+ const event = JSON.parse(line);
25
+ records.set(event.id, { ...(records.get(event.id) || {}), ...event });
26
+ }
27
+ return Array.from(records.values()).reverse();
28
+ }
29
+
30
+ function requireRecord(params, options) {
31
+ const record = listHandoffs(params.threadId, options).find(item => item.id === params.handoffId);
32
+ if (!record) throw new Error('未找到交接记录');
33
+ return record;
34
+ }
35
+
36
+ function validateCard(card) {
37
+ if (!card || typeof card.goal !== 'string' || !card.goal.trim()) throw new Error('交接卡缺少 goal');
38
+ for (const field of ['completed', 'blockers', 'nextSteps', 'files']) {
39
+ if (!Array.isArray(card[field]) || card[field].some(value => typeof value !== 'string')) {
40
+ throw new Error(`交接卡 ${field} 必须为字符串数组`);
41
+ }
42
+ }
43
+ return Object.fromEntries(['goal', 'completed', 'blockers', 'nextSteps', 'files'].map(key => [key, card[key]]));
44
+ }
45
+
46
+ function resultMessage(record) {
47
+ if (record.route === 'mcp') return `已写入 MCP ${record.mcp.server};等待目标 Agent 读取确认。文件回退:${record.filePath}`;
48
+ return `已走文件级路径:${record.filePath};${record.reason || '已手动回退'}。尚未确认目标读取。`;
49
+ }
50
+
51
+ async function createHandoff(params, options = {}) {
52
+ const directory = threadDirectory(params.threadId, options);
53
+ if (typeof params.target !== 'string' || !params.target.trim()) throw new Error('缺少目标 Agent');
54
+ const card = validateCard(params.card);
55
+ const id = crypto.randomBytes(16).toString('hex');
56
+ const createdAt = new Date().toISOString();
57
+ const handoff = { id, threadId: params.threadId, target: params.target, createdAt, card,
58
+ acknowledgement: { command: `codexmate thread ack ${params.threadId} --handoff ${id} --agent ${params.target} --evidence <读取证据>`,
59
+ instruction: '目标 Agent 实际读取本卡后,使用原始 threadId、id、target 调用 thread ack;evidence 填写目标会话或检索记录标识。此确认为目标自报,非自动验证。' } };
60
+ fs.mkdirSync(directory, { recursive: true });
61
+ const filePath = path.join(directory, `${id}.json`);
62
+ fs.writeFileSync(filePath, JSON.stringify(handoff, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
63
+ let record = { id, threadId: params.threadId, target: params.target, createdAt, filePath,
64
+ route: 'file', status: 'file_ready', mcp: null, durationMs: 0, fallback: false,
65
+ reason: 'MCP 探测进行中;文件已就绪', readConfirmation: null, event: 'created' };
66
+ appendEvent(params.threadId, record, options);
67
+ const delivery = await deliver(handoff, { ...options, ...(params.cwd ? { cwd: path.resolve(params.cwd) } : {}) });
68
+ record = { ...record, route: delivery.ok ? 'mcp' : 'file',
69
+ status: delivery.ok ? 'awaiting_read' : 'file_ready', mcp: delivery.mcp,
70
+ durationMs: delivery.durationMs, writeDurationMs: delivery.writeDurationMs, discoveryWarnings: delivery.discoveryWarnings,
71
+ writeResult: delivery.ok ? 'written' : delivery.stage === 'tools/call' ? 'failed_or_unconfirmed' : 'not_attempted',
72
+ fallback: !delivery.ok, reason: delivery.reason, stage: delivery.stage, event: 'delivery' };
73
+ appendEvent(params.threadId, record, options);
74
+ return { record, message: resultMessage(record) };
75
+ }
76
+
77
+ function fallbackHandoff(params, options) {
78
+ const record = requireRecord(params, options);
79
+ const text = fs.readFileSync(record.filePath, 'utf8');
80
+ const updated = { id: record.id, route: 'file', fallback: true,
81
+ status: record.readConfirmation ? 'read_confirmed' : 'file_ready', event: 'manual_fallback',
82
+ reason: '用户选择文件级注入' };
83
+ appendEvent(params.threadId, updated, options);
84
+ return { record: { ...record, ...updated }, text, message: '已切换文件路径;请将交接卡注入目标 Agent,未据此确认读取。' };
85
+ }
86
+
87
+ function acknowledgeHandoff(params, options) {
88
+ const record = requireRecord(params, options);
89
+ if (params.agent !== record.target) throw new Error('确认 Agent 与目标不匹配');
90
+ if (typeof params.evidence !== 'string' || !params.evidence.trim()) throw new Error('读取确认需要会话或检索记录证据');
91
+ const updated = { id: record.id, status: 'read_confirmed', event: 'read_acknowledged',
92
+ readConfirmation: { agent: params.agent, evidence: params.evidence, at: new Date().toISOString(), source: 'target_reported' } };
93
+ appendEvent(params.threadId, updated, options);
94
+ return { record: { ...record, ...updated }, message: '已记录目标自报读取确认;证据已归档。' };
95
+ }
96
+
97
+ async function handleThreadAction(action, params, options) {
98
+ if (action === 'thread-handoff-list') return { records: listHandoffs(params.threadId, options) };
99
+ if (action === 'thread-handoff-create') return createHandoff(params, options);
100
+ if (action === 'thread-handoff-fallback') return fallbackHandoff(params, options);
101
+ if (action === 'thread-handoff-ack') return acknowledgeHandoff(params, options);
102
+ throw new Error('未知交接操作');
103
+ }
104
+
105
+ async function cmdThread(args) {
106
+ const [operation, threadId, ...flags] = args;
107
+ if (!operation || operation === '--help' || operation === '-h') {
108
+ console.log('用法:codexmate thread handoff <thread-id> --card <json-file> --target <agent>\n'
109
+ + ' codexmate thread list <thread-id>\n'
110
+ + ' codexmate thread fallback <thread-id> --handoff <id>\n'
111
+ + ' codexmate thread ack <thread-id> --handoff <id> --agent <agent> --evidence <读取证据>');
112
+ return;
113
+ }
114
+ const params = { threadId };
115
+ const names = { '--card': 'cardFile', '--target': 'target', '--handoff': 'handoffId', '--agent': 'agent', '--evidence': 'evidence' };
116
+ for (let i = 0; i < flags.length; i += 2) {
117
+ if (!names[flags[i]] || !flags[i + 1] || flags[i + 1].startsWith('--')) throw new Error('交接命令参数无效');
118
+ params[names[flags[i]]] = flags[i + 1];
119
+ }
120
+ const actions = { handoff: 'create', list: 'list', fallback: 'fallback', ack: 'ack' };
121
+ if (!actions[operation]) throw new Error('未知 thread 子命令');
122
+ if (operation === 'handoff') {
123
+ if (!params.cardFile) throw new Error('请用 --card 指定结构化交接卡 JSON 文件');
124
+ params.card = JSON.parse(fs.readFileSync(path.resolve(params.cardFile), 'utf8'));
125
+ }
126
+ const result = await handleThreadAction(`thread-handoff-${actions[operation]}`, params);
127
+ console.log(JSON.stringify(result, null, 2));
128
+ }
129
+
130
+ module.exports = { createHandoff, listHandoffs, fallbackHandoff, acknowledgeHandoff, handleThreadAction, cmdThread };
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+ const crypto = require('crypto');
3
+ const TOKEN_BYTES = 32;
4
+
5
+ function equalToken(actual, expected) {
6
+ const digest = value => crypto.createHash('sha256').update(value).digest();
7
+ return typeof actual === 'string' && crypto.timingSafeEqual(digest(actual), digest(expected));
8
+ }
9
+
10
+ function createStartupAuth(configuredToken = '') {
11
+ const token = configuredToken.trim() || crypto.randomBytes(TOKEN_BYTES).toString('hex');
12
+ function respond(res, status, body, headers = {}) {
13
+ res.writeHead(status, { 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer',
14
+ 'Content-Type': 'text/plain; charset=utf-8',
15
+ 'X-Content-Type-Options': 'nosniff', ...headers });
16
+ res.end(body);
17
+ }
18
+ function requestToken(req) {
19
+ const headers = req.headers || {};
20
+ const bearer = /^Bearer\s+(.+)$/i.exec(headers.authorization || '');
21
+ if (bearer) return bearer[1].trim();
22
+ try {
23
+ return new URL(req.url || '/', 'http://localhost').searchParams.get('token') || '';
24
+ } catch (_) {
25
+ return '';
26
+ }
27
+ }
28
+ function authorized(req) {
29
+ const provided = requestToken(req);
30
+ return !!provided && equalToken(provided, token);
31
+ }
32
+ function middleware(req, res, next) {
33
+ const pathname = String(req.url || '/').split('?')[0];
34
+ if (pathname.startsWith('/web-ui/') || pathname.startsWith('/res/') || pathname.startsWith('/bridge/')) { next(); return; }
35
+ const headers = req.headers || {};
36
+ // 外部浏览器跳转只允许首页顶层导航进入令牌校验,不直接放行。
37
+ const isEntryNavigation = pathname === '/' && req.method === 'GET'
38
+ && headers['sec-fetch-mode'] === 'navigate' && headers['sec-fetch-dest'] === 'document';
39
+ if (headers['sec-fetch-site'] === 'cross-site' && !isEntryNavigation) {
40
+ respond(res, 403, '跨站访问已拒绝');
41
+ return;
42
+ }
43
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && headers.origin) {
44
+ const expectedOrigin = `http://${headers.host}`;
45
+ if (headers.origin !== expectedOrigin) { respond(res, 403, '请求来源不匹配'); return; }
46
+ }
47
+ if (authorized(req)) { next(); return; }
48
+ respond(res, 401, JSON.stringify({ error: 'Unauthorized' }), {
49
+ 'Content-Type': 'application/json; charset=utf-8', 'WWW-Authenticate': 'Bearer realm="codexmate"' });
50
+ }
51
+ return { token, middleware, authorized };
52
+ }
53
+ module.exports = { createStartupAuth };
@@ -166,6 +166,29 @@ function validateWorkflowDefinition(definition, options = {}) {
166
166
  }
167
167
  }
168
168
 
169
+ const pending = steps.filter(step => step && isPlainObject(step));
170
+ const ordered = new Set();
171
+ for (const step of steps) {
172
+ if (!step || !isPlainObject(step)) continue;
173
+ if (step.dependsOn !== undefined && (!Array.isArray(step.dependsOn) || step.dependsOn.some(id => !stepIds.has(id)))) {
174
+ issues.push({ code: 'workflow-dependency-invalid', message: `invalid dependencies: ${step.id}` });
175
+ }
176
+ if (step.retry !== undefined && (!Number.isInteger(step.retry) || step.retry < 0 || step.retry > 5)) {
177
+ issues.push({ code: 'workflow-retry-invalid', message: `retry must be an integer from 0 to 5: ${step.id}` });
178
+ }
179
+ if (step.timeoutMs !== undefined && (!Number.isInteger(step.timeoutMs) || step.timeoutMs < 1)) {
180
+ issues.push({ code: 'workflow-timeout-invalid', message: `timeoutMs must be a positive integer: ${step.id}` });
181
+ }
182
+ }
183
+ while (pending.length && !issues.length) {
184
+ const index = pending.findIndex(step => (step.dependsOn || []).every(id => ordered.has(id)));
185
+ if (index < 0) {
186
+ issues.push({ code: 'workflow-cycle', message: 'workflow dependency cycle' });
187
+ break;
188
+ }
189
+ ordered.add(pending.splice(index, 1)[0].id);
190
+ }
191
+
169
192
  if (issues.length > 0) {
170
193
  return {
171
194
  ok: false,
@@ -191,10 +214,31 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
191
214
  };
192
215
  const steps = Array.isArray(definition && definition.steps) ? definition.steps : [];
193
216
  const logs = [];
217
+ const pendingSteps = [...steps];
218
+ const orderedSteps = [];
219
+ while (pendingSteps.length) {
220
+ const index = pendingSteps.findIndex(step => (step.dependsOn || []).every(id => orderedSteps.some(item => item.id === id)));
221
+ if (index < 0) throw new Error('invalid workflow dependencies');
222
+ orderedSteps.push(pendingSteps.splice(index, 1)[0]);
223
+ }
224
+ let waiting = false;
225
+ let cancelled = false;
226
+ const saveLog = async log => {
227
+ logs.push(log);
228
+ if (options.onProgress) await options.onProgress(log);
229
+ };
194
230
  let overallError = '';
195
231
  let lastOutput = null;
196
232
 
197
- for (const step of steps) {
233
+ for (const step of orderedSteps) {
234
+ if (options.shouldStop && options.shouldStop()) { cancelled = true; break; }
235
+ const saved = (options.resumeSteps || []).find(item => item.id === step.id && ['success', 'skipped'].includes(item.status));
236
+ if (saved) {
237
+ logs.push(saved);
238
+ context.steps[step.id] = saved;
239
+ if (saved.status === 'success') lastOutput = saved.output;
240
+ continue;
241
+ }
198
242
  const stepId = typeof step.id === 'string' ? step.id.trim() : '';
199
243
  const startedStepTs = Date.now();
200
244
  const baseLog = {
@@ -203,6 +247,11 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
203
247
  startedAt: toIso(startedStepTs)
204
248
  };
205
249
 
250
+ if ((step.dependsOn || []).some(id => !context.steps[id] || context.steps[id].status !== 'success')) {
251
+ overallError = `dependency did not succeed: ${stepId}`;
252
+ waiting = true;
253
+ break;
254
+ }
206
255
  const conditionPass = evaluateStepCondition(step.when, context);
207
256
  if (!conditionPass) {
208
257
  const skippedLog = {
@@ -212,7 +261,7 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
212
261
  endedAt: toIso(Date.now()),
213
262
  durationMs: Date.now() - startedStepTs
214
263
  };
215
- logs.push(skippedLog);
264
+ await saveLog(skippedLog);
216
265
  context.steps[stepId] = {
217
266
  status: 'skipped',
218
267
  output: null,
@@ -234,7 +283,7 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
234
283
  endedAt: toIso(Date.now()),
235
284
  durationMs: Date.now() - startedStepTs
236
285
  };
237
- logs.push(failedLog);
286
+ await saveLog(failedLog);
238
287
  context.steps[stepId] = {
239
288
  status: 'failed',
240
289
  output: null,
@@ -242,6 +291,7 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
242
291
  args: resolvedArgs
243
292
  };
244
293
  overallError = error;
294
+ waiting = true;
245
295
  if (!step.continueOnError) {
246
296
  break;
247
297
  }
@@ -257,7 +307,7 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
257
307
  endedAt: toIso(Date.now()),
258
308
  durationMs: Date.now() - startedStepTs
259
309
  };
260
- logs.push(dryRunLog);
310
+ await saveLog(dryRunLog);
261
311
  context.steps[stepId] = {
262
312
  status: 'skipped',
263
313
  output: null,
@@ -269,22 +319,38 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
269
319
 
270
320
  let payload;
271
321
  let stepError = '';
272
- try {
273
- payload = await invokeTool(baseLog.tool, resolvedArgs, {
274
- step,
275
- context,
276
- allowWrite,
277
- dryRun
278
- });
279
- if (isFailurePayload(payload)) {
280
- stepError = typeof payload.error === 'string' && payload.error.trim()
281
- ? payload.error.trim()
282
- : `step failed: ${stepId || baseLog.tool}`;
322
+ let attempts = 0;
323
+ const retryBudget = isWriteStep ? 0 : (step.retry || 0);
324
+ do {
325
+ attempts += 1;
326
+ if (options.onBeforeStep) await options.onBeforeStep(step);
327
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
328
+ let timedOut = false;
329
+ const timer = step.timeoutMs ? setTimeout(() => {
330
+ timedOut = true;
331
+ if (controller) controller.abort();
332
+ }, step.timeoutMs) : null;
333
+ try {
334
+ payload = await invokeTool(baseLog.tool, resolvedArgs, {
335
+ step, context, allowWrite, dryRun,
336
+ signal: controller ? controller.signal : undefined
337
+ });
338
+ stepError = isFailurePayload(payload) ? (payload.error || `step failed: ${stepId}`) : '';
339
+ } catch (error) {
340
+ stepError = error.message || String(error);
341
+ payload = { error: stepError, retryable: error.retryable === true };
342
+ } finally {
343
+ if (timer) clearTimeout(timer);
283
344
  }
284
- } catch (error) {
285
- stepError = error && error.message ? error.message : String(error || 'step execution failed');
286
- payload = { error: stepError };
287
- }
345
+ if (timedOut) {
346
+ stepError = `step exceeded timeout; execution has settled: ${stepId}`;
347
+ payload = { error: stepError, blocked: true };
348
+ }
349
+ if (!stepError || !payload.retryable || payload.blocked || attempts > retryBudget) break;
350
+ if (options.shouldStop && options.shouldStop()) break;
351
+ await new Promise(resolve => setTimeout(resolve, 100 * Math.pow(2, attempts - 1)));
352
+ } while (true);
353
+ if (payload && payload.blocked) waiting = true;
288
354
 
289
355
  const status = stepError ? 'failed' : 'success';
290
356
  const endedAtTs = Date.now();
@@ -293,14 +359,16 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
293
359
  args: resolvedArgs,
294
360
  status,
295
361
  output: payload,
362
+ attempts,
296
363
  error: stepError,
297
364
  endedAt: toIso(endedAtTs),
298
365
  durationMs: endedAtTs - startedStepTs
299
366
  };
300
- logs.push(stepLog);
367
+ await saveLog(stepLog);
301
368
  context.steps[stepId] = {
302
369
  status,
303
370
  output: payload,
371
+ attempts,
304
372
  error: stepError,
305
373
  args: resolvedArgs
306
374
  };
@@ -315,10 +383,13 @@ async function executeWorkflowDefinition(definition, input = {}, options = {}) {
315
383
  }
316
384
  }
317
385
 
386
+ if (options.shouldStop && options.shouldStop()) cancelled = true;
318
387
  const endedAtTs = Date.now();
319
388
  const hasFailed = logs.some((item) => item.status === 'failed');
320
389
  const result = {
321
- success: !hasFailed,
390
+ success: !hasFailed && !waiting && !cancelled,
391
+ waiting,
392
+ cancelled,
322
393
  startedAt: toIso(startedAtTs),
323
394
  endedAt: toIso(endedAtTs),
324
395
  durationMs: endedAtTs - startedAtTs,
@@ -0,0 +1,261 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { randomBytes } = require('crypto');
6
+ const randomUUID = () => randomBytes(16).toString('hex');
7
+ const { executeWorkflowDefinition } = require('./workflow-engine');
8
+
9
+ const TERMINAL = new Set(['completed', 'failed', 'cancelled']);
10
+ const clone = value => JSON.parse(JSON.stringify(value));
11
+ const now = () => new Date().toISOString();
12
+ const message = error => error instanceof Error ? error.message : String(error);
13
+
14
+ function createWorkflowRunner({ directory, execute = executeWorkflowDefinition, notify } = {}) {
15
+ if (!directory) throw new TypeError('directory is required');
16
+ if (typeof execute !== 'function') throw new TypeError('execute must be a function');
17
+ fs.mkdirSync(directory, { recursive: true });
18
+ const runs = new Map();
19
+ const live = new Set();
20
+ const notifying = new Set();
21
+ const adapters = new Map();
22
+
23
+ function save(run) {
24
+ run.updatedAt = now();
25
+ const destination = path.join(directory, `${run.id}.json`);
26
+ const temporary = `${destination}.${randomUUID()}.tmp`;
27
+ try {
28
+ fs.writeFileSync(temporary, JSON.stringify(run, null, 2), { flag: 'wx', mode: 0o600 });
29
+ fs.renameSync(temporary, destination);
30
+ } finally {
31
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
32
+ }
33
+ }
34
+
35
+ for (const file of fs.readdirSync(directory)) {
36
+ if (!file.endsWith('.json')) continue;
37
+ const run = JSON.parse(fs.readFileSync(path.join(directory, file), 'utf8'));
38
+ if (file !== `${run.id}.json`) throw new Error(`Invalid workflow run file: ${file}`);
39
+ runs.set(run.id, run);
40
+ }
41
+
42
+ function requireRun(id) {
43
+ const run = runs.get(id);
44
+ if (!run) throw new Error(`Unknown workflow run: ${id}`);
45
+ return run;
46
+ }
47
+
48
+ function summarize(run) {
49
+ const completed = run.steps.filter(step => step.status === 'success');
50
+ const done = new Set(run.steps.filter(step => ['success', 'skipped'].includes(step.status)).map(step => step.id));
51
+ return {
52
+ completed: clone(completed),
53
+ result: run.status === 'completed' ? clone(run.output) : null,
54
+ unfinished: (run.definition.steps || []).filter(step => !done.has(step.id)).map(step => ({
55
+ id: step.id,
56
+ reason: run.reason || run.error || run.status
57
+ }))
58
+ };
59
+ }
60
+
61
+ function notifyLater(run) {
62
+ if (typeof notify !== 'function' || notifying.has(run.id)) return;
63
+ if (!['pending', 'sending'].includes(run.notification.status)) return;
64
+ notifying.add(run.id);
65
+ Promise.resolve().then(async () => {
66
+ run.notification.status = 'sending';
67
+ run.notification.attempts += 1;
68
+ save(run);
69
+ try {
70
+ const delivery = await notify(clone(run));
71
+ if (delivery && delivery.ok === false && !delivery.skipped) throw new Error(delivery.error || 'notification failed');
72
+ run.notification.status = delivery && delivery.skipped ? 'skipped' : 'sent';
73
+ run.notification.error = '';
74
+ } catch (error) {
75
+ run.notification.status = 'failed';
76
+ run.notification.error = message(error);
77
+ }
78
+ run.notification.endedAt = now();
79
+ save(run);
80
+ }).finally(() => notifying.delete(run.id)).catch(error => {
81
+ run.notification.status = 'failed';
82
+ run.notification.error = message(error);
83
+ });
84
+ }
85
+
86
+ function finish(run, status, reason = '') {
87
+ run.status = status;
88
+ run.reason = reason;
89
+ run.activeStep = null;
90
+ run.endedAt = TERMINAL.has(status) ? now() : null;
91
+ run.summary = summarize(run);
92
+ run.notification = {
93
+ status: typeof notify === 'function' ? 'pending' : 'disabled',
94
+ attempts: 0,
95
+ error: ''
96
+ };
97
+ save(run);
98
+ notifyLater(run);
99
+ }
100
+
101
+ function record(run, log) {
102
+ const saved = clone(log);
103
+ const index = run.steps.findIndex(item => item.id === saved.id);
104
+ if (index < 0) run.steps.push(saved);
105
+ else run.steps[index] = saved;
106
+ run.logs.push(saved);
107
+ if (!run.activeStep || run.activeStep.id === saved.id) run.activeStep = null;
108
+ save(run);
109
+ }
110
+
111
+ async function advance(run) {
112
+ const options = adapters.get(run.id) || {};
113
+ if (run.status === 'cancelling') {
114
+ finish(run, 'cancelled', 'cancelled by user');
115
+ return;
116
+ }
117
+ run.status = 'running';
118
+ run.attempts += 1;
119
+ run.startedAt = run.startedAt || now();
120
+ run.endedAt = null;
121
+ save(run);
122
+ const resumeSteps = run.steps.filter(step => ['success', 'skipped'].includes(step.status));
123
+ try {
124
+ const execution = await execute(clone(run.definition), clone(run.input), {
125
+ ...options,
126
+ allowWrite: run.options.allowWrite,
127
+ dryRun: run.options.dryRun,
128
+ resumeSteps: clone(resumeSteps),
129
+ shouldStop: () => run.status === 'cancelling',
130
+ onBeforeStep: async step => {
131
+ if (run.status === 'cancelling') throw new Error('cancelled by user');
132
+ run.activeStep = clone(step);
133
+ run.stepAttempts[step.id] = (run.stepAttempts[step.id] || 0) + 1;
134
+ save(run);
135
+ if (options.onBeforeStep) await options.onBeforeStep(clone(step));
136
+ },
137
+ onProgress: async log => {
138
+ record(run, log);
139
+ if (options.onProgress) await options.onProgress(clone(log));
140
+ }
141
+ });
142
+ run.execution = clone(execution);
143
+ run.output = execution.output === undefined ? null : clone(execution.output);
144
+ for (const log of execution.steps || []) {
145
+ const previous = run.steps.find(item => item.id === log.id);
146
+ if (!previous || JSON.stringify(previous) !== JSON.stringify(log)) record(run, log);
147
+ }
148
+ run.error = execution.error || '';
149
+ if (run.status === 'cancelling' || execution.cancelled) finish(run, 'cancelled', run.error || 'cancelled by user');
150
+ else if (execution.waiting) finish(run, 'waiting', run.error || execution.reason || 'execution requires explicit resume');
151
+ else finish(run, execution.success ? 'completed' : 'failed', run.error);
152
+ } catch (error) {
153
+ run.error = message(error);
154
+ // A rejected engine may leave a side effect in flight or unacknowledged.
155
+ // Keep the active step for recovery instead of assuming it completed.
156
+ if (run.activeStep) {
157
+ const activeStep = run.activeStep;
158
+ finish(run, 'waiting', run.error);
159
+ run.activeStep = activeStep;
160
+ save(run);
161
+ } else {
162
+ finish(run, run.status === 'cancelling' ? 'cancelled' : 'failed', run.error);
163
+ }
164
+ }
165
+ }
166
+
167
+ function schedule(run) {
168
+ if (live.has(run.id)) return;
169
+ live.add(run.id);
170
+ Promise.resolve().then(() => advance(run)).finally(() => live.delete(run.id)).catch(error => {
171
+ // Persistence errors must stop execution, never trigger another attempt.
172
+ run.error = message(error);
173
+ run.status = 'waiting';
174
+ });
175
+ }
176
+
177
+ function submit(definition, input = {}, options = {}) {
178
+ const run = {
179
+ id: randomUUID(),
180
+ definition: clone(definition),
181
+ input: clone(input),
182
+ options: { allowWrite: options.allowWrite === true, dryRun: options.dryRun === true },
183
+ status: 'queued',
184
+ createdAt: now(),
185
+ updatedAt: now(),
186
+ startedAt: null,
187
+ endedAt: null,
188
+ attempts: 0,
189
+ stepAttempts: {},
190
+ steps: clone(options.resumeSteps || []),
191
+ logs: [],
192
+ activeStep: null,
193
+ execution: null,
194
+ output: null,
195
+ error: '',
196
+ reason: '',
197
+ summary: null,
198
+ notification: { status: 'idle', attempts: 0, error: '' }
199
+ };
200
+ save(run);
201
+ runs.set(run.id, run);
202
+ adapters.set(run.id, options);
203
+ schedule(run);
204
+ return clone(run);
205
+ }
206
+
207
+ function resume(id, options = {}) {
208
+ const run = requireRun(id);
209
+ if (live.has(id) || run.status !== 'waiting') throw new Error(`Run is not waiting: ${id}`);
210
+ if (Object.prototype.hasOwnProperty.call(options, 'input')) run.input = clone(options.input);
211
+ if (Object.prototype.hasOwnProperty.call(options, 'allowWrite')) run.options.allowWrite = options.allowWrite === true;
212
+ run.status = 'queued';
213
+ run.reason = '';
214
+ run.error = '';
215
+ run.activeStep = null;
216
+ save(run);
217
+ schedule(run);
218
+ return clone(run);
219
+ }
220
+
221
+ function cancel(id) {
222
+ const run = requireRun(id);
223
+ if (TERMINAL.has(run.status)) return clone(run);
224
+ if (live.has(id)) {
225
+ run.status = 'cancelling';
226
+ save(run);
227
+ } else finish(run, 'cancelled', 'cancelled by user');
228
+ return clone(run);
229
+ }
230
+
231
+ function recover() {
232
+ for (const run of runs.values()) {
233
+ if (live.has(run.id)) continue;
234
+ if (TERMINAL.has(run.status) || run.status === 'waiting') {
235
+ notifyLater(run);
236
+ continue;
237
+ }
238
+ if (run.status === 'cancelling') {
239
+ if (run.activeStep) finish(run, 'waiting', 'interrupted cancellation requires explicit resume');
240
+ else finish(run, 'cancelled', 'cancelled by user');
241
+ continue;
242
+ }
243
+ if (run.activeStep) {
244
+ const step = (run.definition.steps || []).find(item => item.id === run.activeStep.id);
245
+ // Only an explicitly read-only definition is safe to replay.
246
+ if (!step || step.write !== false) {
247
+ finish(run, 'waiting', 'interrupted write or unclassified step requires explicit resume');
248
+ continue;
249
+ }
250
+ }
251
+ schedule(run);
252
+ }
253
+ return list();
254
+ }
255
+
256
+ function list() { return Array.from(runs.values(), run => clone(run)); }
257
+ function get(id) { return runs.has(id) ? clone(runs.get(id)) : null; }
258
+ return { submit, list, get, resume, cancel, recover };
259
+ }
260
+
261
+ module.exports = { createWorkflowRunner };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codexmate",
3
- "version": "0.1.30",
3
+ "version": "0.1.32",
4
4
  "description": "Codex/Claude Code/OpenClaw 配置、会话与任务编排 CLI + Web 工具",
5
5
  "main": "cli.js",
6
6
  "bin": {
@@ -26,7 +26,7 @@ function normalizePromptTemplateEntry(item) {
26
26
 
27
27
  const TEMPLATE_PARTS_CACHE = new Map();
28
28
 
29
- function parseTemplateVariables(templateText) {
29
+ export function parseTemplateVariables(templateText) {
30
30
  const text = typeof templateText === 'string' ? templateText : '';
31
31
  const vars = new Set();
32
32
  const re = /\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g;
@@ -91,13 +91,13 @@ function formatIsoDateLabel(iso) {
91
91
  return `${y}-${m}-${d}`;
92
92
  }
93
93
 
94
- function renderTemplate(templateText, values = {}) {
94
+ export function renderTemplate(templateText, values = {}) {
95
95
  const text = typeof templateText === 'string' ? templateText : '';
96
96
  const map = values && typeof values === 'object' ? values : {};
97
97
  return text.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_whole, key) => {
98
98
  const name = String(key || '').trim();
99
99
  if (!name) return '';
100
- const value = map[name];
100
+ const value = Object.prototype.hasOwnProperty.call(map, name) ? map[name] : null;
101
101
  return value == null || String(value).trim() === '' ? _whole : String(value);
102
102
  });
103
103
  }