codexmate 0.0.32 → 0.0.34

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 (148) hide show
  1. package/README.md +147 -363
  2. package/README.zh.md +147 -371
  3. package/cli/agents-files.js +230 -224
  4. package/cli/archive-helpers.js +453 -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 +556 -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/update.js +171 -0
  23. package/cli/zip-commands.js +510 -510
  24. package/cli.js +16079 -15829
  25. package/lib/automation.js +404 -404
  26. package/lib/cli-file-utils.js +151 -151
  27. package/lib/cli-models-utils.js +440 -440
  28. package/lib/cli-network-utils.js +190 -190
  29. package/lib/cli-path-utils.js +85 -85
  30. package/lib/cli-session-utils.js +121 -121
  31. package/lib/cli-sessions.js +427 -426
  32. package/lib/cli-utils.js +155 -155
  33. package/lib/cli-webhook.js +154 -126
  34. package/lib/download-artifacts.js +92 -92
  35. package/lib/mcp-stdio.js +453 -453
  36. package/lib/task-orchestrator.js +869 -869
  37. package/lib/text-diff.js +303 -303
  38. package/lib/win-tray.js +119 -0
  39. package/lib/workflow-engine.js +340 -340
  40. package/package.json +76 -76
  41. package/plugins/README.md +20 -20
  42. package/plugins/README.zh-CN.md +20 -20
  43. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  44. package/plugins/prompt-templates/computed.mjs +253 -253
  45. package/plugins/prompt-templates/index.mjs +8 -8
  46. package/plugins/prompt-templates/manifest.mjs +15 -15
  47. package/plugins/prompt-templates/methods.mjs +553 -553
  48. package/plugins/prompt-templates/overview.mjs +91 -91
  49. package/plugins/prompt-templates/ownership.mjs +19 -19
  50. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  51. package/plugins/prompt-templates/storage.mjs +64 -64
  52. package/plugins/registry.mjs +16 -16
  53. package/web-ui/app.js +654 -647
  54. package/web-ui/index.html +37 -36
  55. package/web-ui/logic.agents-diff.mjs +386 -386
  56. package/web-ui/logic.claude.mjs +172 -168
  57. package/web-ui/logic.codex.mjs +69 -69
  58. package/web-ui/logic.mjs +5 -5
  59. package/web-ui/logic.runtime.mjs +128 -128
  60. package/web-ui/logic.session-convert.mjs +70 -70
  61. package/web-ui/logic.sessions.mjs +781 -781
  62. package/web-ui/modules/api.mjs +90 -90
  63. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  64. package/web-ui/modules/app.computed.index.mjs +17 -17
  65. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  66. package/web-ui/modules/app.computed.session.mjs +735 -693
  67. package/web-ui/modules/app.constants.mjs +15 -15
  68. package/web-ui/modules/app.methods.agents.mjs +651 -651
  69. package/web-ui/modules/app.methods.claude-config.mjs +306 -200
  70. package/web-ui/modules/app.methods.codex-config.mjs +869 -861
  71. package/web-ui/modules/app.methods.index.mjs +94 -94
  72. package/web-ui/modules/app.methods.install.mjs +205 -205
  73. package/web-ui/modules/app.methods.navigation.mjs +788 -774
  74. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  75. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  76. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  77. package/web-ui/modules/app.methods.providers.mjs +575 -529
  78. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  79. package/web-ui/modules/app.methods.session-actions.mjs +591 -591
  80. package/web-ui/modules/app.methods.session-browser.mjs +1011 -1012
  81. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  82. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  83. package/web-ui/modules/app.methods.startup-claude.mjs +547 -537
  84. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  85. package/web-ui/modules/app.methods.webhook.mjs +87 -79
  86. package/web-ui/modules/config-mode.computed.mjs +124 -124
  87. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  88. package/web-ui/modules/i18n.dict.mjs +3195 -3177
  89. package/web-ui/modules/i18n.mjs +62 -62
  90. package/web-ui/modules/plugins.computed.mjs +3 -3
  91. package/web-ui/modules/plugins.methods.mjs +3 -3
  92. package/web-ui/modules/plugins.storage.mjs +11 -11
  93. package/web-ui/modules/provider-url-display.mjs +17 -17
  94. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  95. package/web-ui/modules/skills.computed.mjs +107 -107
  96. package/web-ui/modules/skills.methods.mjs +482 -482
  97. package/web-ui/partials/index/layout-footer.html +13 -13
  98. package/web-ui/partials/index/layout-header.html +499 -503
  99. package/web-ui/partials/index/modal-config-template-agents.html +185 -185
  100. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  101. package/web-ui/partials/index/modal-health-check.html +45 -45
  102. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  103. package/web-ui/partials/index/modal-skills.html +200 -200
  104. package/web-ui/partials/index/modal-webhook.html +42 -0
  105. package/web-ui/partials/index/modals-basic.html +223 -162
  106. package/web-ui/partials/index/panel-config-claude.html +155 -136
  107. package/web-ui/partials/index/panel-config-codex.html +176 -196
  108. package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
  109. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  110. package/web-ui/partials/index/panel-dashboard.html +186 -219
  111. package/web-ui/partials/index/panel-docs.html +114 -114
  112. package/web-ui/partials/index/panel-market.html +177 -177
  113. package/web-ui/partials/index/panel-orchestration.html +391 -391
  114. package/web-ui/partials/index/panel-plugins.html +253 -253
  115. package/web-ui/partials/index/panel-sessions.html +319 -313
  116. package/web-ui/partials/index/panel-settings.html +158 -190
  117. package/web-ui/partials/index/panel-trash.html +82 -82
  118. package/web-ui/partials/index/panel-usage.html +137 -137
  119. package/web-ui/res/json5.min.js +1 -1
  120. package/web-ui/res/vue.global.prod.js +13 -13
  121. package/web-ui/session-helpers.mjs +591 -591
  122. package/web-ui/source-bundle.cjs +233 -233
  123. package/web-ui/styles/base-theme.css +281 -281
  124. package/web-ui/styles/bridge-pool.css +266 -197
  125. package/web-ui/styles/controls-forms.css +433 -433
  126. package/web-ui/styles/dashboard.css +406 -406
  127. package/web-ui/styles/docs-panel.css +245 -245
  128. package/web-ui/styles/feedback.css +108 -108
  129. package/web-ui/styles/health-check-dialog.css +144 -144
  130. package/web-ui/styles/layout-shell.css +628 -638
  131. package/web-ui/styles/modals-core.css +499 -466
  132. package/web-ui/styles/navigation-panels.css +391 -391
  133. package/web-ui/styles/openclaw-structured.css +266 -266
  134. package/web-ui/styles/plugins-panel.css +564 -564
  135. package/web-ui/styles/responsive.css +392 -392
  136. package/web-ui/styles/sessions-list.css +683 -647
  137. package/web-ui/styles/sessions-preview.css +407 -407
  138. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  139. package/web-ui/styles/sessions-usage.css +588 -588
  140. package/web-ui/styles/settings-panel.css +415 -349
  141. package/web-ui/styles/skills-list.css +305 -305
  142. package/web-ui/styles/skills-market.css +429 -429
  143. package/web-ui/styles/task-orchestration.css +822 -822
  144. package/web-ui/styles/titles-cards.css +472 -472
  145. package/web-ui/styles/trash-panel.css +90 -90
  146. package/web-ui/styles/webhook.css +115 -81
  147. package/web-ui/styles.css +24 -24
  148. package/web-ui.html +17 -17
package/lib/automation.js CHANGED
@@ -1,404 +1,404 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const http = require('http');
4
- const https = require('https');
5
- const net = require('net');
6
-
7
- function isPlainObject(value) {
8
- return !!value && typeof value === 'object' && !Array.isArray(value);
9
- }
10
-
11
- function cloneJson(value, fallback) {
12
- try {
13
- return JSON.parse(JSON.stringify(value));
14
- } catch (_) {
15
- return fallback;
16
- }
17
- }
18
-
19
- function normalizeText(value, maxLength = 4000) {
20
- const text = value === undefined || value === null ? '' : String(value).trim();
21
- if (!text) return '';
22
- return text.length > maxLength ? text.slice(0, maxLength) : text;
23
- }
24
-
25
- function uniqueStringList(items = []) {
26
- const list = Array.isArray(items) ? items : [];
27
- const out = [];
28
- const seen = new Set();
29
- for (const item of list) {
30
- const text = normalizeText(item, 200);
31
- if (!text || seen.has(text)) continue;
32
- seen.add(text);
33
- out.push(text);
34
- }
35
- return out;
36
- }
37
-
38
- function expandEnvTemplate(value, env = process.env) {
39
- const text = String(value || '');
40
- if (!text) return '';
41
- return text.replace(/\$\{([A-Z0-9_]+)\}/g, (_, key) => {
42
- const envValue = env && typeof env[key] === 'string' ? env[key] : '';
43
- return envValue ? envValue : '';
44
- });
45
- }
46
-
47
- function isPrivateNetworkHost(hostname) {
48
- const host = typeof hostname === 'string' ? hostname.trim().toLowerCase() : '';
49
- if (!host) return true;
50
- if (host === 'localhost') return true;
51
- const ipVer = net.isIP(host);
52
- if (!ipVer) return false;
53
- if (ipVer === 4) {
54
- const parts = host.split('.').map((x) => parseInt(x, 10));
55
- if (parts.length !== 4 || parts.some((x) => !Number.isFinite(x))) return true;
56
- const [a, b] = parts;
57
- if (a === 10) return true;
58
- if (a === 127) return true;
59
- if (a === 169 && b === 254) return true;
60
- if (a === 192 && b === 168) return true;
61
- if (a === 172 && b >= 16 && b <= 31) return true;
62
- return false;
63
- }
64
- if (ipVer === 6) {
65
- if (host === '::1') return true;
66
- if (host.startsWith('fe80:')) return true;
67
- if (host.startsWith('fc') || host.startsWith('fd')) return true;
68
- return false;
69
- }
70
- return false;
71
- }
72
-
73
- function readAutomationConfig(configPath, options = {}) {
74
- const filePath = typeof configPath === 'string' ? configPath.trim() : '';
75
- if (!filePath) {
76
- return { ok: true, exists: false, config: createDefaultAutomationConfig() };
77
- }
78
- if (!fs.existsSync(filePath)) {
79
- return { ok: true, exists: false, config: createDefaultAutomationConfig() };
80
- }
81
- let raw = '';
82
- try {
83
- raw = fs.readFileSync(filePath, 'utf-8');
84
- } catch (error) {
85
- return { ok: false, error: error && error.message ? error.message : 'failed to read automation config', exists: true };
86
- }
87
- let parsed;
88
- try {
89
- parsed = JSON.parse(raw);
90
- } catch (error) {
91
- return { ok: false, error: error && error.message ? error.message : 'invalid automation config json', exists: true };
92
- }
93
- const normalized = normalizeAutomationConfig(parsed, options);
94
- return { ok: true, exists: true, config: normalized };
95
- }
96
-
97
- function createDefaultAutomationConfig() {
98
- return {
99
- version: 1,
100
- rules: [],
101
- schedules: [],
102
- notifiers: []
103
- };
104
- }
105
-
106
- function normalizeAutomationRule(rule = {}) {
107
- const item = isPlainObject(rule) ? rule : {};
108
- return {
109
- id: normalizeText(item.id, 120),
110
- enabled: item.enabled !== false,
111
- source: normalizeText(item.source, 40).toLowerCase(),
112
- event: normalizeText(item.event, 120).toLowerCase(),
113
- action: cloneJson(isPlainObject(item.action) ? item.action : {}, {})
114
- };
115
- }
116
-
117
- function normalizeAutomationSchedule(schedule = {}) {
118
- const item = isPlainObject(schedule) ? schedule : {};
119
- return {
120
- id: normalizeText(item.id, 120),
121
- enabled: item.enabled !== false,
122
- cron: normalizeText(item.cron, 120),
123
- action: cloneJson(isPlainObject(item.action) ? item.action : {}, {})
124
- };
125
- }
126
-
127
- function normalizeAutomationNotifier(notifier = {}, options = {}) {
128
- const item = isPlainObject(notifier) ? notifier : {};
129
- const env = options.env || process.env;
130
- const url = normalizeText(item.url, 800);
131
- const normalizedUrl = url ? expandEnvTemplate(url, env) : '';
132
- return {
133
- id: normalizeText(item.id, 120),
134
- enabled: item.enabled !== false,
135
- type: normalizeText(item.type, 40).toLowerCase(),
136
- url: normalizedUrl,
137
- events: uniqueStringList(item.events || []).map((value) => value.toLowerCase()),
138
- headers: cloneJson(isPlainObject(item.headers) ? item.headers : {}, {})
139
- };
140
- }
141
-
142
- function normalizeAutomationConfig(config = {}, options = {}) {
143
- const base = isPlainObject(config) ? config : {};
144
- const defaults = createDefaultAutomationConfig();
145
- const rawRules = Array.isArray(base.rules) ? base.rules : [];
146
- const rawSchedules = Array.isArray(base.schedules) ? base.schedules : [];
147
- const rawNotifiers = Array.isArray(base.notifiers) ? base.notifiers : [];
148
- return {
149
- version: Number.isFinite(base.version) ? base.version : defaults.version,
150
- rules: rawRules.map(normalizeAutomationRule).filter((rule) => rule.id && rule.source && rule.event),
151
- schedules: rawSchedules.map(normalizeAutomationSchedule).filter((item) => item.id && item.cron),
152
- notifiers: rawNotifiers.map((item) => normalizeAutomationNotifier(item, options)).filter((item) => item.id && item.type)
153
- };
154
- }
155
-
156
- function matchAutomationRule(config = {}, event = {}) {
157
- const cfg = isPlainObject(config) ? config : createDefaultAutomationConfig();
158
- const source = normalizeText(event.source, 40).toLowerCase();
159
- const eventKey = normalizeText(event.event, 120).toLowerCase();
160
- if (!source || !eventKey) return null;
161
- const rules = Array.isArray(cfg.rules) ? cfg.rules : [];
162
- for (const rule of rules) {
163
- if (!rule || rule.enabled === false) continue;
164
- if (rule.source !== source) continue;
165
- const pattern = rule.event;
166
- if (!pattern) continue;
167
- if (pattern.endsWith('*')) {
168
- const prefix = pattern.slice(0, -1);
169
- if (eventKey.startsWith(prefix)) return rule;
170
- continue;
171
- }
172
- if (pattern === eventKey) return rule;
173
- }
174
- return null;
175
- }
176
-
177
- function buildAutomationEventKey(source, headers = {}, payload = {}) {
178
- const src = normalizeText(source, 40).toLowerCase();
179
- const hdr = isPlainObject(headers) ? headers : {};
180
- const body = isPlainObject(payload) ? payload : {};
181
- if (!src) return '';
182
-
183
- if (src === 'github') {
184
- const eventName = normalizeText(hdr['x-github-event'] || hdr['X-GitHub-Event'], 80).toLowerCase();
185
- const action = normalizeText(body.action, 80).toLowerCase();
186
- if (!eventName) return '';
187
- return action ? `${eventName}.${action}` : eventName;
188
- }
189
-
190
- if (src === 'gitlab') {
191
- const eventName = normalizeText(hdr['x-gitlab-event'] || hdr['X-Gitlab-Event'], 120).toLowerCase();
192
- const kind = normalizeText(body.object_kind || body.event_type, 120).toLowerCase();
193
- const action = normalizeText(body.action, 80).toLowerCase();
194
- const base = kind || eventName;
195
- if (!base) return '';
196
- return action ? `${base}.${action}` : base;
197
- }
198
-
199
- const fallback = normalizeText(
200
- hdr['x-event'] || hdr['X-Event'] || hdr['x-codexmate-event'] || hdr['X-Codexmate-Event'],
201
- 120
202
- ).toLowerCase();
203
- return fallback;
204
- }
205
-
206
- function httpPostJson(url, payload, headers = {}, options = {}) {
207
- const target = normalizeText(url, 800);
208
- if (!target) {
209
- return Promise.resolve({ ok: false, error: 'url is required' });
210
- }
211
- let parsed;
212
- try {
213
- parsed = new URL(target);
214
- } catch (_) {
215
- return Promise.resolve({ ok: false, error: 'invalid url' });
216
- }
217
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
218
- return Promise.resolve({ ok: false, error: 'invalid url protocol' });
219
- }
220
- const allowPrivate = process.env.CODEXMATE_ALLOW_AUTOMATION_PRIVATE_NETWORK === '1';
221
- if (!allowPrivate && isPrivateNetworkHost(parsed.hostname || '')) {
222
- return Promise.resolve({ ok: false, error: 'refusing to post to private network url' });
223
- }
224
- const transport = parsed.protocol === 'http:' ? http : https;
225
- const data = Buffer.from(JSON.stringify(payload || {}), 'utf-8');
226
- const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(200, Math.floor(options.timeoutMs)) : 4000;
227
- const requestOptions = {
228
- method: 'POST',
229
- hostname: parsed.hostname,
230
- port: parsed.port || (parsed.protocol === 'http:' ? 80 : 443),
231
- path: `${parsed.pathname || '/'}${parsed.search || ''}`,
232
- headers: {
233
- 'Content-Type': 'application/json; charset=utf-8',
234
- 'Content-Length': data.length,
235
- ...headers
236
- }
237
- };
238
- return new Promise((resolve) => {
239
- const req = transport.request(requestOptions, (res) => {
240
- let body = '';
241
- res.setEncoding('utf-8');
242
- res.on('data', (chunk) => body += chunk);
243
- res.on('end', () => {
244
- resolve({
245
- ok: (res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300,
246
- statusCode: res.statusCode || 0,
247
- body: body.slice(0, 2000)
248
- });
249
- });
250
- });
251
- req.on('error', (error) => {
252
- resolve({ ok: false, error: error && error.message ? error.message : 'request failed' });
253
- });
254
- req.setTimeout(timeoutMs, () => {
255
- req.destroy(new Error('timeout'));
256
- });
257
- req.write(data);
258
- req.end();
259
- });
260
- }
261
-
262
- function parseCronPart(part, min, max) {
263
- const text = normalizeText(part, 120);
264
- if (!text) return null;
265
- if (text === '*') return { any: true };
266
- if (text.startsWith('*/')) {
267
- const step = Number.parseInt(text.slice(2), 10);
268
- if (!Number.isFinite(step) || step <= 0) return null;
269
- return { step };
270
- }
271
- const list = text.split(',').map((chunk) => chunk.trim()).filter(Boolean);
272
- if (list.length === 0) return null;
273
- const ranges = [];
274
- for (const item of list) {
275
- if (item.includes('-')) {
276
- const [rawStart, rawEnd] = item.split('-', 2);
277
- const start = Number.parseInt(rawStart, 10);
278
- const end = Number.parseInt(rawEnd, 10);
279
- if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
280
- ranges.push({ start, end });
281
- continue;
282
- }
283
- const value = Number.parseInt(item, 10);
284
- if (!Number.isFinite(value)) return null;
285
- ranges.push({ start: value, end: value });
286
- }
287
- return { ranges, min, max };
288
- }
289
-
290
- function cronPartMatches(spec, value) {
291
- if (!spec) return false;
292
- if (spec.any) return true;
293
- if (spec.step) {
294
- return value % spec.step === 0;
295
- }
296
- const ranges = Array.isArray(spec.ranges) ? spec.ranges : [];
297
- for (const range of ranges) {
298
- const start = Number.isFinite(range.start) ? range.start : NaN;
299
- const end = Number.isFinite(range.end) ? range.end : NaN;
300
- if (!Number.isFinite(start) || !Number.isFinite(end)) continue;
301
- const normalizedStart = Math.min(start, end);
302
- const normalizedEnd = Math.max(start, end);
303
- if (value >= normalizedStart && value <= normalizedEnd) {
304
- return true;
305
- }
306
- }
307
- return false;
308
- }
309
-
310
- function isCronMatch(expr, date = new Date()) {
311
- const text = normalizeText(expr, 120);
312
- if (!text) return false;
313
- const parts = text.split(/\s+/g).filter(Boolean);
314
- if (parts.length !== 5) return false;
315
- const [minExpr, hourExpr, domExpr, monExpr, dowExpr] = parts;
316
- const minute = date.getMinutes();
317
- const hour = date.getHours();
318
- const dom = date.getDate();
319
- const month = date.getMonth() + 1;
320
- const dow = date.getDay();
321
- const minSpec = parseCronPart(minExpr, 0, 59);
322
- const hourSpec = parseCronPart(hourExpr, 0, 23);
323
- const domSpec = parseCronPart(domExpr, 1, 31);
324
- const monSpec = parseCronPart(monExpr, 1, 12);
325
- const dowSpecRaw = parseCronPart(dowExpr, 0, 7);
326
- const dowValue = dow;
327
- if (!minSpec || !hourSpec || !domSpec || !monSpec || !dowSpecRaw) return false;
328
- const dowSpec = dowSpecRaw.step || dowSpecRaw.any ? dowSpecRaw : {
329
- ...dowSpecRaw,
330
- ranges: (dowSpecRaw.ranges || []).map((range) => ({
331
- start: range.start === 7 ? 0 : range.start,
332
- end: range.end === 7 ? 0 : range.end
333
- }))
334
- };
335
- return cronPartMatches(minSpec, minute)
336
- && cronPartMatches(hourSpec, hour)
337
- && cronPartMatches(domSpec, dom)
338
- && cronPartMatches(monSpec, month)
339
- && cronPartMatches(dowSpec, dowValue);
340
- }
341
-
342
- function formatTaskRunNotificationPayload(detail = {}) {
343
- const base = isPlainObject(detail) ? detail : {};
344
- const run = isPlainObject(base.run) ? base.run : {};
345
- const nodes = Array.isArray(run.nodes) ? run.nodes : [];
346
- return {
347
- kind: 'task-run',
348
- runId: base.runId || '',
349
- taskId: base.taskId || '',
350
- title: base.title || '',
351
- target: base.target || '',
352
- engine: base.engine || '',
353
- allowWrite: base.allowWrite === true,
354
- dryRun: base.dryRun === true,
355
- status: run.status || base.status || '',
356
- startedAt: run.startedAt || base.startedAt || '',
357
- endedAt: run.endedAt || base.endedAt || '',
358
- durationMs: run.durationMs || 0,
359
- summary: run.summary || base.summary || '',
360
- error: run.error || base.error || '',
361
- nodes: nodes.map((node) => ({
362
- id: node.id || '',
363
- kind: node.kind || '',
364
- status: node.status || '',
365
- attemptCount: node.attemptCount || 0,
366
- summary: node.summary || '',
367
- error: node.error || ''
368
- }))
369
- };
370
- }
371
-
372
- async function dispatchAutomationNotifiers(config, eventType, payload) {
373
- const cfg = isPlainObject(config) ? config : createDefaultAutomationConfig();
374
- const normalizedEvent = normalizeText(eventType, 80).toLowerCase();
375
- if (!normalizedEvent) return [];
376
- const out = [];
377
- const notifiers = Array.isArray(cfg.notifiers) ? cfg.notifiers : [];
378
- for (const notifier of notifiers) {
379
- if (!notifier || notifier.enabled === false) continue;
380
- const events = Array.isArray(notifier.events) ? notifier.events : [];
381
- if (events.length > 0 && !events.includes(normalizedEvent)) {
382
- continue;
383
- }
384
- if (notifier.type === 'webhook') {
385
- out.push({
386
- id: notifier.id,
387
- type: notifier.type,
388
- ...(await httpPostJson(notifier.url, payload, notifier.headers || {}))
389
- });
390
- }
391
- }
392
- return out;
393
- }
394
-
395
- module.exports = {
396
- createDefaultAutomationConfig,
397
- normalizeAutomationConfig,
398
- readAutomationConfig,
399
- matchAutomationRule,
400
- buildAutomationEventKey,
401
- isCronMatch,
402
- dispatchAutomationNotifiers,
403
- formatTaskRunNotificationPayload
404
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const http = require('http');
4
+ const https = require('https');
5
+ const net = require('net');
6
+
7
+ function isPlainObject(value) {
8
+ return !!value && typeof value === 'object' && !Array.isArray(value);
9
+ }
10
+
11
+ function cloneJson(value, fallback) {
12
+ try {
13
+ return JSON.parse(JSON.stringify(value));
14
+ } catch (_) {
15
+ return fallback;
16
+ }
17
+ }
18
+
19
+ function normalizeText(value, maxLength = 4000) {
20
+ const text = value === undefined || value === null ? '' : String(value).trim();
21
+ if (!text) return '';
22
+ return text.length > maxLength ? text.slice(0, maxLength) : text;
23
+ }
24
+
25
+ function uniqueStringList(items = []) {
26
+ const list = Array.isArray(items) ? items : [];
27
+ const out = [];
28
+ const seen = new Set();
29
+ for (const item of list) {
30
+ const text = normalizeText(item, 200);
31
+ if (!text || seen.has(text)) continue;
32
+ seen.add(text);
33
+ out.push(text);
34
+ }
35
+ return out;
36
+ }
37
+
38
+ function expandEnvTemplate(value, env = process.env) {
39
+ const text = String(value || '');
40
+ if (!text) return '';
41
+ return text.replace(/\$\{([A-Z0-9_]+)\}/g, (_, key) => {
42
+ const envValue = env && typeof env[key] === 'string' ? env[key] : '';
43
+ return envValue ? envValue : '';
44
+ });
45
+ }
46
+
47
+ function isPrivateNetworkHost(hostname) {
48
+ const host = typeof hostname === 'string' ? hostname.trim().toLowerCase() : '';
49
+ if (!host) return true;
50
+ if (host === 'localhost') return true;
51
+ const ipVer = net.isIP(host);
52
+ if (!ipVer) return false;
53
+ if (ipVer === 4) {
54
+ const parts = host.split('.').map((x) => parseInt(x, 10));
55
+ if (parts.length !== 4 || parts.some((x) => !Number.isFinite(x))) return true;
56
+ const [a, b] = parts;
57
+ if (a === 10) return true;
58
+ if (a === 127) return true;
59
+ if (a === 169 && b === 254) return true;
60
+ if (a === 192 && b === 168) return true;
61
+ if (a === 172 && b >= 16 && b <= 31) return true;
62
+ return false;
63
+ }
64
+ if (ipVer === 6) {
65
+ if (host === '::1') return true;
66
+ if (host.startsWith('fe80:')) return true;
67
+ if (host.startsWith('fc') || host.startsWith('fd')) return true;
68
+ return false;
69
+ }
70
+ return false;
71
+ }
72
+
73
+ function readAutomationConfig(configPath, options = {}) {
74
+ const filePath = typeof configPath === 'string' ? configPath.trim() : '';
75
+ if (!filePath) {
76
+ return { ok: true, exists: false, config: createDefaultAutomationConfig() };
77
+ }
78
+ if (!fs.existsSync(filePath)) {
79
+ return { ok: true, exists: false, config: createDefaultAutomationConfig() };
80
+ }
81
+ let raw = '';
82
+ try {
83
+ raw = fs.readFileSync(filePath, 'utf-8');
84
+ } catch (error) {
85
+ return { ok: false, error: error && error.message ? error.message : 'failed to read automation config', exists: true };
86
+ }
87
+ let parsed;
88
+ try {
89
+ parsed = JSON.parse(raw);
90
+ } catch (error) {
91
+ return { ok: false, error: error && error.message ? error.message : 'invalid automation config json', exists: true };
92
+ }
93
+ const normalized = normalizeAutomationConfig(parsed, options);
94
+ return { ok: true, exists: true, config: normalized };
95
+ }
96
+
97
+ function createDefaultAutomationConfig() {
98
+ return {
99
+ version: 1,
100
+ rules: [],
101
+ schedules: [],
102
+ notifiers: []
103
+ };
104
+ }
105
+
106
+ function normalizeAutomationRule(rule = {}) {
107
+ const item = isPlainObject(rule) ? rule : {};
108
+ return {
109
+ id: normalizeText(item.id, 120),
110
+ enabled: item.enabled !== false,
111
+ source: normalizeText(item.source, 40).toLowerCase(),
112
+ event: normalizeText(item.event, 120).toLowerCase(),
113
+ action: cloneJson(isPlainObject(item.action) ? item.action : {}, {})
114
+ };
115
+ }
116
+
117
+ function normalizeAutomationSchedule(schedule = {}) {
118
+ const item = isPlainObject(schedule) ? schedule : {};
119
+ return {
120
+ id: normalizeText(item.id, 120),
121
+ enabled: item.enabled !== false,
122
+ cron: normalizeText(item.cron, 120),
123
+ action: cloneJson(isPlainObject(item.action) ? item.action : {}, {})
124
+ };
125
+ }
126
+
127
+ function normalizeAutomationNotifier(notifier = {}, options = {}) {
128
+ const item = isPlainObject(notifier) ? notifier : {};
129
+ const env = options.env || process.env;
130
+ const url = normalizeText(item.url, 800);
131
+ const normalizedUrl = url ? expandEnvTemplate(url, env) : '';
132
+ return {
133
+ id: normalizeText(item.id, 120),
134
+ enabled: item.enabled !== false,
135
+ type: normalizeText(item.type, 40).toLowerCase(),
136
+ url: normalizedUrl,
137
+ events: uniqueStringList(item.events || []).map((value) => value.toLowerCase()),
138
+ headers: cloneJson(isPlainObject(item.headers) ? item.headers : {}, {})
139
+ };
140
+ }
141
+
142
+ function normalizeAutomationConfig(config = {}, options = {}) {
143
+ const base = isPlainObject(config) ? config : {};
144
+ const defaults = createDefaultAutomationConfig();
145
+ const rawRules = Array.isArray(base.rules) ? base.rules : [];
146
+ const rawSchedules = Array.isArray(base.schedules) ? base.schedules : [];
147
+ const rawNotifiers = Array.isArray(base.notifiers) ? base.notifiers : [];
148
+ return {
149
+ version: Number.isFinite(base.version) ? base.version : defaults.version,
150
+ rules: rawRules.map(normalizeAutomationRule).filter((rule) => rule.id && rule.source && rule.event),
151
+ schedules: rawSchedules.map(normalizeAutomationSchedule).filter((item) => item.id && item.cron),
152
+ notifiers: rawNotifiers.map((item) => normalizeAutomationNotifier(item, options)).filter((item) => item.id && item.type)
153
+ };
154
+ }
155
+
156
+ function matchAutomationRule(config = {}, event = {}) {
157
+ const cfg = isPlainObject(config) ? config : createDefaultAutomationConfig();
158
+ const source = normalizeText(event.source, 40).toLowerCase();
159
+ const eventKey = normalizeText(event.event, 120).toLowerCase();
160
+ if (!source || !eventKey) return null;
161
+ const rules = Array.isArray(cfg.rules) ? cfg.rules : [];
162
+ for (const rule of rules) {
163
+ if (!rule || rule.enabled === false) continue;
164
+ if (rule.source !== source) continue;
165
+ const pattern = rule.event;
166
+ if (!pattern) continue;
167
+ if (pattern.endsWith('*')) {
168
+ const prefix = pattern.slice(0, -1);
169
+ if (eventKey.startsWith(prefix)) return rule;
170
+ continue;
171
+ }
172
+ if (pattern === eventKey) return rule;
173
+ }
174
+ return null;
175
+ }
176
+
177
+ function buildAutomationEventKey(source, headers = {}, payload = {}) {
178
+ const src = normalizeText(source, 40).toLowerCase();
179
+ const hdr = isPlainObject(headers) ? headers : {};
180
+ const body = isPlainObject(payload) ? payload : {};
181
+ if (!src) return '';
182
+
183
+ if (src === 'github') {
184
+ const eventName = normalizeText(hdr['x-github-event'] || hdr['X-GitHub-Event'], 80).toLowerCase();
185
+ const action = normalizeText(body.action, 80).toLowerCase();
186
+ if (!eventName) return '';
187
+ return action ? `${eventName}.${action}` : eventName;
188
+ }
189
+
190
+ if (src === 'gitlab') {
191
+ const eventName = normalizeText(hdr['x-gitlab-event'] || hdr['X-Gitlab-Event'], 120).toLowerCase();
192
+ const kind = normalizeText(body.object_kind || body.event_type, 120).toLowerCase();
193
+ const action = normalizeText(body.action, 80).toLowerCase();
194
+ const base = kind || eventName;
195
+ if (!base) return '';
196
+ return action ? `${base}.${action}` : base;
197
+ }
198
+
199
+ const fallback = normalizeText(
200
+ hdr['x-event'] || hdr['X-Event'] || hdr['x-codexmate-event'] || hdr['X-Codexmate-Event'],
201
+ 120
202
+ ).toLowerCase();
203
+ return fallback;
204
+ }
205
+
206
+ function httpPostJson(url, payload, headers = {}, options = {}) {
207
+ const target = normalizeText(url, 800);
208
+ if (!target) {
209
+ return Promise.resolve({ ok: false, error: 'url is required' });
210
+ }
211
+ let parsed;
212
+ try {
213
+ parsed = new URL(target);
214
+ } catch (_) {
215
+ return Promise.resolve({ ok: false, error: 'invalid url' });
216
+ }
217
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
218
+ return Promise.resolve({ ok: false, error: 'invalid url protocol' });
219
+ }
220
+ const allowPrivate = process.env.CODEXMATE_ALLOW_AUTOMATION_PRIVATE_NETWORK === '1';
221
+ if (!allowPrivate && isPrivateNetworkHost(parsed.hostname || '')) {
222
+ return Promise.resolve({ ok: false, error: 'refusing to post to private network url' });
223
+ }
224
+ const transport = parsed.protocol === 'http:' ? http : https;
225
+ const data = Buffer.from(JSON.stringify(payload || {}), 'utf-8');
226
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(200, Math.floor(options.timeoutMs)) : 4000;
227
+ const requestOptions = {
228
+ method: 'POST',
229
+ hostname: parsed.hostname,
230
+ port: parsed.port || (parsed.protocol === 'http:' ? 80 : 443),
231
+ path: `${parsed.pathname || '/'}${parsed.search || ''}`,
232
+ headers: {
233
+ 'Content-Type': 'application/json; charset=utf-8',
234
+ 'Content-Length': data.length,
235
+ ...headers
236
+ }
237
+ };
238
+ return new Promise((resolve) => {
239
+ const req = transport.request(requestOptions, (res) => {
240
+ let body = '';
241
+ res.setEncoding('utf-8');
242
+ res.on('data', (chunk) => body += chunk);
243
+ res.on('end', () => {
244
+ resolve({
245
+ ok: (res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300,
246
+ statusCode: res.statusCode || 0,
247
+ body: body.slice(0, 2000)
248
+ });
249
+ });
250
+ });
251
+ req.on('error', (error) => {
252
+ resolve({ ok: false, error: error && error.message ? error.message : 'request failed' });
253
+ });
254
+ req.setTimeout(timeoutMs, () => {
255
+ req.destroy(new Error('timeout'));
256
+ });
257
+ req.write(data);
258
+ req.end();
259
+ });
260
+ }
261
+
262
+ function parseCronPart(part, min, max) {
263
+ const text = normalizeText(part, 120);
264
+ if (!text) return null;
265
+ if (text === '*') return { any: true };
266
+ if (text.startsWith('*/')) {
267
+ const step = Number.parseInt(text.slice(2), 10);
268
+ if (!Number.isFinite(step) || step <= 0) return null;
269
+ return { step };
270
+ }
271
+ const list = text.split(',').map((chunk) => chunk.trim()).filter(Boolean);
272
+ if (list.length === 0) return null;
273
+ const ranges = [];
274
+ for (const item of list) {
275
+ if (item.includes('-')) {
276
+ const [rawStart, rawEnd] = item.split('-', 2);
277
+ const start = Number.parseInt(rawStart, 10);
278
+ const end = Number.parseInt(rawEnd, 10);
279
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
280
+ ranges.push({ start, end });
281
+ continue;
282
+ }
283
+ const value = Number.parseInt(item, 10);
284
+ if (!Number.isFinite(value)) return null;
285
+ ranges.push({ start: value, end: value });
286
+ }
287
+ return { ranges, min, max };
288
+ }
289
+
290
+ function cronPartMatches(spec, value) {
291
+ if (!spec) return false;
292
+ if (spec.any) return true;
293
+ if (spec.step) {
294
+ return value % spec.step === 0;
295
+ }
296
+ const ranges = Array.isArray(spec.ranges) ? spec.ranges : [];
297
+ for (const range of ranges) {
298
+ const start = Number.isFinite(range.start) ? range.start : NaN;
299
+ const end = Number.isFinite(range.end) ? range.end : NaN;
300
+ if (!Number.isFinite(start) || !Number.isFinite(end)) continue;
301
+ const normalizedStart = Math.min(start, end);
302
+ const normalizedEnd = Math.max(start, end);
303
+ if (value >= normalizedStart && value <= normalizedEnd) {
304
+ return true;
305
+ }
306
+ }
307
+ return false;
308
+ }
309
+
310
+ function isCronMatch(expr, date = new Date()) {
311
+ const text = normalizeText(expr, 120);
312
+ if (!text) return false;
313
+ const parts = text.split(/\s+/g).filter(Boolean);
314
+ if (parts.length !== 5) return false;
315
+ const [minExpr, hourExpr, domExpr, monExpr, dowExpr] = parts;
316
+ const minute = date.getMinutes();
317
+ const hour = date.getHours();
318
+ const dom = date.getDate();
319
+ const month = date.getMonth() + 1;
320
+ const dow = date.getDay();
321
+ const minSpec = parseCronPart(minExpr, 0, 59);
322
+ const hourSpec = parseCronPart(hourExpr, 0, 23);
323
+ const domSpec = parseCronPart(domExpr, 1, 31);
324
+ const monSpec = parseCronPart(monExpr, 1, 12);
325
+ const dowSpecRaw = parseCronPart(dowExpr, 0, 7);
326
+ const dowValue = dow;
327
+ if (!minSpec || !hourSpec || !domSpec || !monSpec || !dowSpecRaw) return false;
328
+ const dowSpec = dowSpecRaw.step || dowSpecRaw.any ? dowSpecRaw : {
329
+ ...dowSpecRaw,
330
+ ranges: (dowSpecRaw.ranges || []).map((range) => ({
331
+ start: range.start === 7 ? 0 : range.start,
332
+ end: range.end === 7 ? 0 : range.end
333
+ }))
334
+ };
335
+ return cronPartMatches(minSpec, minute)
336
+ && cronPartMatches(hourSpec, hour)
337
+ && cronPartMatches(domSpec, dom)
338
+ && cronPartMatches(monSpec, month)
339
+ && cronPartMatches(dowSpec, dowValue);
340
+ }
341
+
342
+ function formatTaskRunNotificationPayload(detail = {}) {
343
+ const base = isPlainObject(detail) ? detail : {};
344
+ const run = isPlainObject(base.run) ? base.run : {};
345
+ const nodes = Array.isArray(run.nodes) ? run.nodes : [];
346
+ return {
347
+ kind: 'task-run',
348
+ runId: base.runId || '',
349
+ taskId: base.taskId || '',
350
+ title: base.title || '',
351
+ target: base.target || '',
352
+ engine: base.engine || '',
353
+ allowWrite: base.allowWrite === true,
354
+ dryRun: base.dryRun === true,
355
+ status: run.status || base.status || '',
356
+ startedAt: run.startedAt || base.startedAt || '',
357
+ endedAt: run.endedAt || base.endedAt || '',
358
+ durationMs: run.durationMs || 0,
359
+ summary: run.summary || base.summary || '',
360
+ error: run.error || base.error || '',
361
+ nodes: nodes.map((node) => ({
362
+ id: node.id || '',
363
+ kind: node.kind || '',
364
+ status: node.status || '',
365
+ attemptCount: node.attemptCount || 0,
366
+ summary: node.summary || '',
367
+ error: node.error || ''
368
+ }))
369
+ };
370
+ }
371
+
372
+ async function dispatchAutomationNotifiers(config, eventType, payload) {
373
+ const cfg = isPlainObject(config) ? config : createDefaultAutomationConfig();
374
+ const normalizedEvent = normalizeText(eventType, 80).toLowerCase();
375
+ if (!normalizedEvent) return [];
376
+ const out = [];
377
+ const notifiers = Array.isArray(cfg.notifiers) ? cfg.notifiers : [];
378
+ for (const notifier of notifiers) {
379
+ if (!notifier || notifier.enabled === false) continue;
380
+ const events = Array.isArray(notifier.events) ? notifier.events : [];
381
+ if (events.length > 0 && !events.includes(normalizedEvent)) {
382
+ continue;
383
+ }
384
+ if (notifier.type === 'webhook') {
385
+ out.push({
386
+ id: notifier.id,
387
+ type: notifier.type,
388
+ ...(await httpPostJson(notifier.url, payload, notifier.headers || {}))
389
+ });
390
+ }
391
+ }
392
+ return out;
393
+ }
394
+
395
+ module.exports = {
396
+ createDefaultAutomationConfig,
397
+ normalizeAutomationConfig,
398
+ readAutomationConfig,
399
+ matchAutomationRule,
400
+ buildAutomationEventKey,
401
+ isCronMatch,
402
+ dispatchAutomationNotifiers,
403
+ formatTaskRunNotificationPayload
404
+ };