codexmate 0.0.24 → 0.0.26

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 (136) hide show
  1. package/README.md +416 -391
  2. package/README.zh.md +349 -324
  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 +1079 -1044
  7. package/cli/claude-proxy.js +1022 -998
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -334
  12. package/cli/openai-bridge.js +997 -950
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -0
  15. package/cli/session-convert-io.js +82 -0
  16. package/cli/session-convert.js +43 -0
  17. package/cli/session-usage.concurrent.js +28 -28
  18. package/cli/session-usage.js +118 -112
  19. package/cli/session-usage.models.js +176 -176
  20. package/cli/skills.js +1141 -1141
  21. package/cli/zip-commands.js +510 -510
  22. package/cli.js +15218 -13310
  23. package/lib/automation.js +404 -0
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +379 -379
  26. package/lib/cli-network-utils.js +190 -190
  27. package/lib/cli-path-utils.js +85 -69
  28. package/lib/cli-session-utils.js +121 -121
  29. package/lib/cli-sessions.js +417 -386
  30. package/lib/cli-utils.js +155 -155
  31. package/lib/download-artifacts.js +92 -77
  32. package/lib/mcp-stdio.js +453 -440
  33. package/lib/task-orchestrator.js +869 -869
  34. package/lib/text-diff.js +303 -303
  35. package/lib/workflow-engine.js +340 -340
  36. package/package.json +74 -77
  37. package/plugins/README.md +20 -20
  38. package/plugins/README.zh-CN.md +20 -20
  39. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  40. package/plugins/prompt-templates/computed.mjs +253 -253
  41. package/plugins/prompt-templates/index.mjs +8 -8
  42. package/plugins/prompt-templates/manifest.mjs +15 -15
  43. package/plugins/prompt-templates/methods.mjs +619 -619
  44. package/plugins/prompt-templates/overview.mjs +90 -90
  45. package/plugins/prompt-templates/ownership.mjs +19 -19
  46. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  47. package/plugins/prompt-templates/storage.mjs +64 -64
  48. package/plugins/registry.mjs +16 -16
  49. package/web-ui/app.js +625 -609
  50. package/web-ui/index.html +35 -35
  51. package/web-ui/logic.agents-diff.mjs +386 -386
  52. package/web-ui/logic.claude.mjs +168 -168
  53. package/web-ui/logic.mjs +5 -5
  54. package/web-ui/logic.runtime.mjs +128 -128
  55. package/web-ui/logic.session-convert.mjs +70 -0
  56. package/web-ui/logic.sessions.mjs +709 -614
  57. package/web-ui/modules/api.mjs +90 -90
  58. package/web-ui/modules/app.computed.dashboard.mjs +171 -126
  59. package/web-ui/modules/app.computed.index.mjs +17 -17
  60. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  61. package/web-ui/modules/app.computed.session.mjs +946 -653
  62. package/web-ui/modules/app.constants.mjs +15 -15
  63. package/web-ui/modules/app.methods.agents.mjs +632 -632
  64. package/web-ui/modules/app.methods.claude-config.mjs +179 -174
  65. package/web-ui/modules/app.methods.codex-config.mjs +860 -784
  66. package/web-ui/modules/app.methods.index.mjs +92 -92
  67. package/web-ui/modules/app.methods.install.mjs +205 -177
  68. package/web-ui/modules/app.methods.navigation.mjs +743 -695
  69. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  70. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  71. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  72. package/web-ui/modules/app.methods.providers.mjs +404 -404
  73. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  74. package/web-ui/modules/app.methods.session-actions.mjs +596 -537
  75. package/web-ui/modules/app.methods.session-browser.mjs +985 -698
  76. package/web-ui/modules/app.methods.session-timeline.mjs +479 -448
  77. package/web-ui/modules/app.methods.session-trash.mjs +424 -422
  78. package/web-ui/modules/app.methods.startup-claude.mjs +522 -417
  79. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  80. package/web-ui/modules/config-mode.computed.mjs +124 -124
  81. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  82. package/web-ui/modules/i18n.dict.mjs +2113 -2039
  83. package/web-ui/modules/i18n.mjs +56 -56
  84. package/web-ui/modules/plugins.computed.mjs +3 -3
  85. package/web-ui/modules/plugins.methods.mjs +3 -3
  86. package/web-ui/modules/plugins.storage.mjs +11 -11
  87. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  88. package/web-ui/modules/skills.computed.mjs +107 -107
  89. package/web-ui/modules/skills.methods.mjs +481 -481
  90. package/web-ui/partials/index/layout-footer.html +13 -13
  91. package/web-ui/partials/index/layout-header.html +475 -465
  92. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  93. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  94. package/web-ui/partials/index/modal-health-check.html +45 -45
  95. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  96. package/web-ui/partials/index/modal-skills.html +200 -200
  97. package/web-ui/partials/index/modals-basic.html +165 -165
  98. package/web-ui/partials/index/panel-config-claude.html +184 -179
  99. package/web-ui/partials/index/panel-config-codex.html +283 -283
  100. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  101. package/web-ui/partials/index/panel-dashboard.html +186 -186
  102. package/web-ui/partials/index/panel-docs.html +147 -147
  103. package/web-ui/partials/index/panel-market.html +177 -177
  104. package/web-ui/partials/index/panel-orchestration.html +391 -391
  105. package/web-ui/partials/index/panel-plugins.html +279 -279
  106. package/web-ui/partials/index/panel-sessions.html +326 -301
  107. package/web-ui/partials/index/panel-settings.html +258 -258
  108. package/web-ui/partials/index/panel-usage.html +342 -354
  109. package/{res → web-ui/res}/json5.min.js +1 -1
  110. package/{res → web-ui/res}/vue.global.prod.js +13 -13
  111. package/web-ui/session-helpers.mjs +576 -573
  112. package/web-ui/source-bundle.cjs +233 -233
  113. package/web-ui/styles/base-theme.css +268 -264
  114. package/web-ui/styles/controls-forms.css +423 -376
  115. package/web-ui/styles/dashboard.css +274 -274
  116. package/web-ui/styles/docs-panel.css +247 -247
  117. package/web-ui/styles/feedback.css +108 -108
  118. package/web-ui/styles/health-check-dialog.css +144 -144
  119. package/web-ui/styles/layout-shell.css +603 -602
  120. package/web-ui/styles/modals-core.css +464 -464
  121. package/web-ui/styles/navigation-panels.css +390 -390
  122. package/web-ui/styles/openclaw-structured.css +266 -266
  123. package/web-ui/styles/plugins-panel.css +523 -523
  124. package/web-ui/styles/responsive.css +454 -456
  125. package/web-ui/styles/sessions-list.css +415 -400
  126. package/web-ui/styles/sessions-preview.css +411 -411
  127. package/web-ui/styles/sessions-toolbar-trash.css +330 -268
  128. package/web-ui/styles/sessions-usage.css +945 -888
  129. package/web-ui/styles/settings-panel.css +166 -166
  130. package/web-ui/styles/skills-list.css +303 -303
  131. package/web-ui/styles/skills-market.css +406 -406
  132. package/web-ui/styles/task-orchestration.css +822 -822
  133. package/web-ui/styles/titles-cards.css +408 -408
  134. package/web-ui/styles.css +21 -21
  135. package/web-ui.html +17 -17
  136. /package/{res → web-ui/res}/logo-pack.webp +0 -0
@@ -1,334 +1,356 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const os = require('os');
4
- const http = require('http');
5
- const https = require('https');
6
- const { isValidHttpUrl } = require('../lib/cli-utils');
7
- const { MAX_SKILLS_ZIP_UPLOAD_SIZE, importSkillsFromZipFile } = require('./skills');
8
-
9
- function decodeUrlPathPart(part) {
10
- try {
11
- return decodeURIComponent(part);
12
- } catch (_) {
13
- return part;
14
- }
15
- }
16
-
17
- function parseGithubRepoFromUrl(inputUrl) {
18
- const raw = typeof inputUrl === 'string' ? inputUrl.trim() : '';
19
- if (!raw) return null;
20
- let parsed;
21
- try {
22
- parsed = new URL(raw);
23
- } catch (_) {
24
- return null;
25
- }
26
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
27
- return null;
28
- }
29
- if (parsed.hostname !== 'github.com') {
30
- return null;
31
- }
32
- const parts = parsed.pathname.split('/').filter(Boolean).map(decodeUrlPathPart);
33
- if (parts.length < 2) return null;
34
- const owner = parts[0];
35
- const repoPart = parts[1] || '';
36
- const repo = repoPart.endsWith('.git') ? repoPart.slice(0, -4) : repoPart;
37
- if (!owner || !repo) return null;
38
- const ref = parts[2] === 'tree' && parts[3]
39
- ? parts.slice(3).join('/')
40
- : '';
41
- return { owner, repo, ref };
42
- }
43
-
44
- function buildGithubArchiveZipBase(repoInfo) {
45
- if (!repoInfo || !repoInfo.owner || !repoInfo.repo) return '';
46
- return `https://github.com/${encodeURIComponent(repoInfo.owner)}/${encodeURIComponent(repoInfo.repo)}/archive/refs`;
47
- }
48
-
49
- function encodeGithubRefPath(ref) {
50
- return String(ref || '')
51
- .split('/')
52
- .map(part => encodeURIComponent(part))
53
- .join('/');
54
- }
55
-
56
- function resolveGithubArchiveZipUrl(inputUrl) {
57
- const repoInfo = parseGithubRepoFromUrl(inputUrl);
58
- if (!repoInfo) return '';
59
- const base = buildGithubArchiveZipBase(repoInfo);
60
- const ref = repoInfo.ref || 'main';
61
- return `${base}/heads/${encodeGithubRefPath(ref)}.zip`;
62
- }
63
-
64
- function buildGithubArchiveZipCandidates(inputUrl) {
65
- const repoInfo = parseGithubRepoFromUrl(inputUrl);
66
- if (!repoInfo) return [];
67
- const base = buildGithubArchiveZipBase(repoInfo);
68
- if (repoInfo.ref) {
69
- const ref = encodeGithubRefPath(repoInfo.ref);
70
- return [
71
- `${base}/heads/${ref}.zip`,
72
- `${base}/tags/${ref}.zip`
73
- ];
74
- }
75
- return [
76
- `${base}/heads/main.zip`,
77
- `${base}/heads/master.zip`
78
- ];
79
- }
80
-
81
- function redactUrlForLog(inputUrl) {
82
- const raw = typeof inputUrl === 'string' ? inputUrl.trim() : '';
83
- if (!raw) return '';
84
- try {
85
- const parsed = new URL(raw);
86
- return `${parsed.origin}${parsed.pathname}`;
87
- } catch (_) {
88
- return raw;
89
- }
90
- }
91
-
92
- function extractHttpStatusFromError(err) {
93
- const message = err && err.message ? String(err.message) : '';
94
- const matched = message.match(/\bHTTP\s+(\d{3})\b/);
95
- if (!matched) return 0;
96
- const value = Number(matched[1]);
97
- return Number.isFinite(value) ? value : 0;
98
- }
99
-
100
- function downloadUrlToFile(targetUrl, filePath, options = {}) {
101
- const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0
102
- ? Math.floor(options.maxBytes)
103
- : MAX_SKILLS_ZIP_UPLOAD_SIZE;
104
- const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
105
- ? Math.floor(options.timeoutMs)
106
- : 30000;
107
- const maxRedirects = Number.isFinite(options.maxRedirects) && options.maxRedirects >= 0
108
- ? Math.floor(options.maxRedirects)
109
- : 5;
110
-
111
- return new Promise((resolve, reject) => {
112
- let parsed;
113
- try {
114
- parsed = new URL(targetUrl);
115
- } catch (_) {
116
- reject(new Error('Invalid URL'));
117
- return;
118
- }
119
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
120
- reject(new Error(`ERR_INVALID_PROTOCOL: Protocol "${parsed.protocol}" not supported. Expected "http:" or "https:"`));
121
- return;
122
- }
123
-
124
- const transport = parsed.protocol === 'https:' ? https : http;
125
- const requestOptions = {
126
- method: 'GET',
127
- headers: {
128
- 'User-Agent': 'codexmate-import-skills',
129
- 'Accept': 'application/octet-stream,application/zip,*/*'
130
- }
131
- };
132
-
133
- const req = transport.request(parsed, requestOptions, (res) => {
134
- const status = Number(res.statusCode) || 0;
135
- const redirectLocation = res.headers && typeof res.headers.location === 'string' ? res.headers.location : '';
136
- if (status >= 300 && status < 400 && redirectLocation) {
137
- if (maxRedirects <= 0) {
138
- reject(new Error('Too many redirects'));
139
- return;
140
- }
141
- const nextUrl = redirectLocation.startsWith('http')
142
- ? redirectLocation
143
- : `${parsed.origin}${redirectLocation}`;
144
- res.resume();
145
- downloadUrlToFile(nextUrl, filePath, { maxBytes, timeoutMs, maxRedirects: maxRedirects - 1 })
146
- .then(resolve)
147
- .catch(reject);
148
- return;
149
- }
150
- if (status < 200 || status >= 300) {
151
- res.resume();
152
- reject(new Error(`HTTP ${status}`));
153
- return;
154
- }
155
-
156
- const out = fs.createWriteStream(filePath, { flags: 'w' });
157
- let bytes = 0;
158
- let finished = false;
159
-
160
- const fail = (err) => {
161
- if (finished) return;
162
- finished = true;
163
- try {
164
- out.close();
165
- } catch (_) {}
166
- try {
167
- fs.unlinkSync(filePath);
168
- } catch (_) {}
169
- reject(err);
170
- };
171
-
172
- res.on('data', (chunk) => {
173
- if (!chunk || finished) return;
174
- bytes += chunk.length;
175
- if (bytes > maxBytes) {
176
- req.destroy(new Error('download too large'));
177
- res.destroy(new Error('download too large'));
178
- fail(new Error('Download too large'));
179
- }
180
- });
181
-
182
- res.on('error', fail);
183
- out.on('error', fail);
184
- out.on('finish', () => {
185
- if (finished) return;
186
- finished = true;
187
- resolve({ bytes });
188
- });
189
-
190
- res.pipe(out);
191
- });
192
-
193
- req.on('error', (err) => {
194
- reject(new Error(err && err.message ? err.message : 'request failed'));
195
- });
196
- req.setTimeout(timeoutMs, () => {
197
- req.destroy(new Error('timeout'));
198
- });
199
- req.end();
200
- });
201
- }
202
-
203
- function printImportSkillsUsage() {
204
- process.stdout.write('\n用法:\n');
205
- process.stdout.write(' codexmate import-skills <URL> [--target-app codex|claude] [--name <NAME>] [--timeout-ms <MS>]\n');
206
- process.stdout.write('\n示例:\n');
207
- process.stdout.write(' codexmate import-skills https://github.com/<owner>/<repo>\n');
208
- process.stdout.write(' codexmate import-skills https://github.com/<owner>/<repo>/tree/dev\n');
209
- process.stdout.write(' codexmate import-skills https://github.com/<owner>/<repo>/archive/refs/heads/main.zip\n');
210
- }
211
-
212
- function parseImportSkillsCommandArgs(argv = []) {
213
- const options = {
214
- url: '',
215
- targetApp: 'codex',
216
- name: '',
217
- timeoutMs: 30000,
218
- help: false
219
- };
220
- let cursor = 0;
221
- while (cursor < argv.length) {
222
- const token = String(argv[cursor] || '');
223
- if (token === '--help' || token === '-h') {
224
- options.help = true;
225
- cursor += 1;
226
- continue;
227
- }
228
- if (token && !token.startsWith('-') && !options.url) {
229
- options.url = token.trim();
230
- cursor += 1;
231
- continue;
232
- }
233
- if (token === '--target-app') {
234
- const value = String(argv[cursor + 1] || '').trim().toLowerCase();
235
- if (!value || value.startsWith('-')) {
236
- throw new Error('错误: --target-app 需要一个值(codex/claude)');
237
- }
238
- options.targetApp = value === 'claude' ? 'claude' : 'codex';
239
- cursor += 2;
240
- continue;
241
- }
242
- if (token === '--name') {
243
- const value = String(argv[cursor + 1] || '').trim();
244
- if (!value || value.startsWith('-')) {
245
- throw new Error('错误: --name 需要一个值');
246
- }
247
- options.name = value;
248
- cursor += 2;
249
- continue;
250
- }
251
- if (token === '--timeout-ms') {
252
- const value = Number(argv[cursor + 1]);
253
- if (!Number.isFinite(value) || value <= 0) {
254
- throw new Error('错误: --timeout-ms 需要一个正整数');
255
- }
256
- options.timeoutMs = Math.floor(value);
257
- cursor += 2;
258
- continue;
259
- }
260
- if (token.startsWith('-')) {
261
- throw new Error(`错误: 未知参数: ${token}`);
262
- }
263
- throw new Error(`错误: 多余参数: ${token}`);
264
- }
265
- return options;
266
- }
267
-
268
- async function cmdImportSkills(argv = []) {
269
- const options = parseImportSkillsCommandArgs(argv);
270
- if (options.help) {
271
- printImportSkillsUsage();
272
- return;
273
- }
274
- if (!options.url) {
275
- printImportSkillsUsage();
276
- throw new Error('错误: 缺少 URL(例如: https://github.com/<owner>/<repo>/archive/refs/heads/main.zip)');
277
- }
278
- const candidates = buildGithubArchiveZipCandidates(options.url);
279
- if (!candidates.length) {
280
- const resolvedGithubUrl = resolveGithubArchiveZipUrl(options.url);
281
- candidates.push(resolvedGithubUrl || options.url);
282
- }
283
- const uniqueCandidates = Array.from(new Set(candidates.filter(Boolean)));
284
- if (!uniqueCandidates.length || !uniqueCandidates.every(isValidHttpUrl)) {
285
- throw new Error('错误: URL 非法(仅支持 http/https)');
286
- }
287
-
288
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codexmate-skills-url-'));
289
- const zipPath = path.join(tempDir, 'skills.zip');
290
- let finalUrl = uniqueCandidates[0];
291
- try {
292
- let lastError = null;
293
- for (const candidateUrl of uniqueCandidates) {
294
- finalUrl = candidateUrl;
295
- console.log(`\n[Skills] Download: ${redactUrlForLog(candidateUrl)}`);
296
- try {
297
- await downloadUrlToFile(candidateUrl, zipPath, {
298
- maxBytes: MAX_SKILLS_ZIP_UPLOAD_SIZE,
299
- timeoutMs: options.timeoutMs,
300
- maxRedirects: 5
301
- });
302
- lastError = null;
303
- break;
304
- } catch (e) {
305
- lastError = e;
306
- if (extractHttpStatusFromError(e) === 404) {
307
- continue;
308
- }
309
- throw e;
310
- }
311
- }
312
- if (lastError) {
313
- throw lastError;
314
- }
315
- const fallbackName = options.name || path.basename(new URL(finalUrl).pathname) || 'skills.zip';
316
- const result = await importSkillsFromZipFile(zipPath, {
317
- tempDir,
318
- targetApp: options.targetApp,
319
- fallbackName
320
- });
321
- process.stdout.write(JSON.stringify(result, null, 2) + '\n');
322
- } finally {
323
- try {
324
- fs.rmSync(tempDir, { recursive: true, force: true });
325
- } catch (_) {}
326
- }
327
- }
328
-
329
- module.exports = {
330
- parseGithubRepoFromUrl,
331
- resolveGithubArchiveZipUrl,
332
- buildGithubArchiveZipCandidates,
333
- cmdImportSkills
334
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const http = require('http');
5
+ const https = require('https');
6
+ const { isValidHttpUrl } = require('../lib/cli-utils');
7
+ const { MAX_SKILLS_ZIP_UPLOAD_SIZE, importSkillsFromZipFile } = require('./skills');
8
+
9
+ function decodeUrlPathPart(part) {
10
+ try {
11
+ return decodeURIComponent(part);
12
+ } catch (_) {
13
+ return part;
14
+ }
15
+ }
16
+
17
+ function parseGithubRepoFromUrl(inputUrl) {
18
+ const raw = typeof inputUrl === 'string' ? inputUrl.trim() : '';
19
+ if (!raw) return null;
20
+ let parsed;
21
+ try {
22
+ parsed = new URL(raw);
23
+ } catch (_) {
24
+ return null;
25
+ }
26
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
27
+ return null;
28
+ }
29
+ if (parsed.hostname !== 'github.com') {
30
+ return null;
31
+ }
32
+ const parts = parsed.pathname.split('/').filter(Boolean).map(decodeUrlPathPart);
33
+ if (parts.length < 2) return null;
34
+ const owner = parts[0];
35
+ const repoPart = parts[1] || '';
36
+ const repo = repoPart.endsWith('.git') ? repoPart.slice(0, -4) : repoPart;
37
+ if (!owner || !repo) return null;
38
+ const ref = parts[2] === 'tree' && parts[3]
39
+ ? parts.slice(3).join('/')
40
+ : '';
41
+ return { owner, repo, ref };
42
+ }
43
+
44
+ function buildGithubArchiveZipBase(repoInfo) {
45
+ if (!repoInfo || !repoInfo.owner || !repoInfo.repo) return '';
46
+ return `https://github.com/${encodeURIComponent(repoInfo.owner)}/${encodeURIComponent(repoInfo.repo)}/archive/refs`;
47
+ }
48
+
49
+ function encodeGithubRefPath(ref) {
50
+ return String(ref || '')
51
+ .split('/')
52
+ .map(part => encodeURIComponent(part))
53
+ .join('/');
54
+ }
55
+
56
+ function resolveGithubArchiveZipUrl(inputUrl) {
57
+ const repoInfo = parseGithubRepoFromUrl(inputUrl);
58
+ if (!repoInfo) return '';
59
+ const base = buildGithubArchiveZipBase(repoInfo);
60
+ const ref = repoInfo.ref || 'main';
61
+ return `${base}/heads/${encodeGithubRefPath(ref)}.zip`;
62
+ }
63
+
64
+ function buildGithubArchiveZipCandidates(inputUrl) {
65
+ const repoInfo = parseGithubRepoFromUrl(inputUrl);
66
+ if (!repoInfo) return [];
67
+ const base = buildGithubArchiveZipBase(repoInfo);
68
+ if (repoInfo.ref) {
69
+ const ref = encodeGithubRefPath(repoInfo.ref);
70
+ return [
71
+ `${base}/heads/${ref}.zip`,
72
+ `${base}/tags/${ref}.zip`
73
+ ];
74
+ }
75
+ return [
76
+ `${base}/heads/main.zip`,
77
+ `${base}/heads/master.zip`
78
+ ];
79
+ }
80
+
81
+ function redactUrlForLog(inputUrl) {
82
+ const raw = typeof inputUrl === 'string' ? inputUrl.trim() : '';
83
+ if (!raw) return '';
84
+ try {
85
+ const parsed = new URL(raw);
86
+ return `${parsed.origin}${parsed.pathname}`;
87
+ } catch (_) {
88
+ return raw;
89
+ }
90
+ }
91
+
92
+ function extractHttpStatusFromError(err) {
93
+ const message = err && err.message ? String(err.message) : '';
94
+ const matched = message.match(/\bHTTP\s+(\d{3})\b/);
95
+ if (!matched) return 0;
96
+ const value = Number(matched[1]);
97
+ return Number.isFinite(value) ? value : 0;
98
+ }
99
+
100
+ function isAllowedSkillsRedirectHost(originHost, nextHost) {
101
+ const origin = typeof originHost === 'string' ? originHost.trim().toLowerCase() : '';
102
+ const next = typeof nextHost === 'string' ? nextHost.trim().toLowerCase() : '';
103
+ if (!origin || !next) return false;
104
+ if (origin === next) return true;
105
+ if (process.env.CODEXMATE_ALLOW_SKILLS_REDIRECT === '1') return true;
106
+ if (origin === 'github.com' && next === 'codeload.github.com') return true;
107
+ if (origin === 'github.com' && next.endsWith('.githubusercontent.com')) return true;
108
+ return false;
109
+ }
110
+
111
+ function downloadUrlToFile(targetUrl, filePath, options = {}) {
112
+ const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0
113
+ ? Math.floor(options.maxBytes)
114
+ : MAX_SKILLS_ZIP_UPLOAD_SIZE;
115
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
116
+ ? Math.floor(options.timeoutMs)
117
+ : 30000;
118
+ const maxRedirects = Number.isFinite(options.maxRedirects) && options.maxRedirects >= 0
119
+ ? Math.floor(options.maxRedirects)
120
+ : 5;
121
+
122
+ return new Promise((resolve, reject) => {
123
+ let parsed;
124
+ try {
125
+ parsed = new URL(targetUrl);
126
+ } catch (_) {
127
+ reject(new Error('Invalid URL'));
128
+ return;
129
+ }
130
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
131
+ reject(new Error(`ERR_INVALID_PROTOCOL: Protocol "${parsed.protocol}" not supported. Expected "http:" or "https:"`));
132
+ return;
133
+ }
134
+
135
+ const transport = parsed.protocol === 'https:' ? https : http;
136
+ const requestOptions = {
137
+ method: 'GET',
138
+ headers: {
139
+ 'User-Agent': 'codexmate-import-skills',
140
+ 'Accept': 'application/octet-stream,application/zip,*/*'
141
+ }
142
+ };
143
+
144
+ const req = transport.request(parsed, requestOptions, (res) => {
145
+ const status = Number(res.statusCode) || 0;
146
+ const redirectLocation = res.headers && typeof res.headers.location === 'string' ? res.headers.location : '';
147
+ if (status >= 300 && status < 400 && redirectLocation) {
148
+ if (maxRedirects <= 0) {
149
+ reject(new Error('Too many redirects'));
150
+ return;
151
+ }
152
+ const nextUrl = redirectLocation.startsWith('http')
153
+ ? redirectLocation
154
+ : `${parsed.origin}${redirectLocation}`;
155
+ let originHost = typeof options.originHost === 'string' && options.originHost.trim()
156
+ ? options.originHost.trim()
157
+ : parsed.host;
158
+ try {
159
+ const nextParsed = new URL(nextUrl);
160
+ if (!isAllowedSkillsRedirectHost(originHost, nextParsed.host)) {
161
+ res.resume();
162
+ reject(new Error('Cross-origin redirect is not allowed'));
163
+ return;
164
+ }
165
+ } catch (_) {}
166
+ res.resume();
167
+ downloadUrlToFile(nextUrl, filePath, { maxBytes, timeoutMs, maxRedirects: maxRedirects - 1, originHost })
168
+ .then(resolve)
169
+ .catch(reject);
170
+ return;
171
+ }
172
+ if (status < 200 || status >= 300) {
173
+ res.resume();
174
+ reject(new Error(`HTTP ${status}`));
175
+ return;
176
+ }
177
+
178
+ const out = fs.createWriteStream(filePath, { flags: 'w' });
179
+ let bytes = 0;
180
+ let finished = false;
181
+
182
+ const fail = (err) => {
183
+ if (finished) return;
184
+ finished = true;
185
+ try {
186
+ out.close();
187
+ } catch (_) {}
188
+ try {
189
+ fs.unlinkSync(filePath);
190
+ } catch (_) {}
191
+ reject(err);
192
+ };
193
+
194
+ res.on('data', (chunk) => {
195
+ if (!chunk || finished) return;
196
+ bytes += chunk.length;
197
+ if (bytes > maxBytes) {
198
+ req.destroy(new Error('download too large'));
199
+ res.destroy(new Error('download too large'));
200
+ fail(new Error('Download too large'));
201
+ }
202
+ });
203
+
204
+ res.on('error', fail);
205
+ out.on('error', fail);
206
+ out.on('finish', () => {
207
+ if (finished) return;
208
+ finished = true;
209
+ resolve({ bytes });
210
+ });
211
+
212
+ res.pipe(out);
213
+ });
214
+
215
+ req.on('error', (err) => {
216
+ reject(new Error(err && err.message ? err.message : 'request failed'));
217
+ });
218
+ req.setTimeout(timeoutMs, () => {
219
+ req.destroy(new Error('timeout'));
220
+ });
221
+ req.end();
222
+ });
223
+ }
224
+
225
+ function printImportSkillsUsage() {
226
+ process.stdout.write('\n用法:\n');
227
+ process.stdout.write(' codexmate import-skills <URL> [--target-app codex|claude] [--name <NAME>] [--timeout-ms <MS>]\n');
228
+ process.stdout.write('\n示例:\n');
229
+ process.stdout.write(' codexmate import-skills https://github.com/<owner>/<repo>\n');
230
+ process.stdout.write(' codexmate import-skills https://github.com/<owner>/<repo>/tree/dev\n');
231
+ process.stdout.write(' codexmate import-skills https://github.com/<owner>/<repo>/archive/refs/heads/main.zip\n');
232
+ }
233
+
234
+ function parseImportSkillsCommandArgs(argv = []) {
235
+ const options = {
236
+ url: '',
237
+ targetApp: 'codex',
238
+ name: '',
239
+ timeoutMs: 30000,
240
+ help: false
241
+ };
242
+ let cursor = 0;
243
+ while (cursor < argv.length) {
244
+ const token = String(argv[cursor] || '');
245
+ if (token === '--help' || token === '-h') {
246
+ options.help = true;
247
+ cursor += 1;
248
+ continue;
249
+ }
250
+ if (token && !token.startsWith('-') && !options.url) {
251
+ options.url = token.trim();
252
+ cursor += 1;
253
+ continue;
254
+ }
255
+ if (token === '--target-app') {
256
+ const value = String(argv[cursor + 1] || '').trim().toLowerCase();
257
+ if (!value || value.startsWith('-')) {
258
+ throw new Error('错误: --target-app 需要一个值(codex/claude)');
259
+ }
260
+ options.targetApp = value === 'claude' ? 'claude' : 'codex';
261
+ cursor += 2;
262
+ continue;
263
+ }
264
+ if (token === '--name') {
265
+ const value = String(argv[cursor + 1] || '').trim();
266
+ if (!value || value.startsWith('-')) {
267
+ throw new Error('错误: --name 需要一个值');
268
+ }
269
+ options.name = value;
270
+ cursor += 2;
271
+ continue;
272
+ }
273
+ if (token === '--timeout-ms') {
274
+ const value = Number(argv[cursor + 1]);
275
+ if (!Number.isFinite(value) || value <= 0) {
276
+ throw new Error('错误: --timeout-ms 需要一个正整数');
277
+ }
278
+ options.timeoutMs = Math.floor(value);
279
+ cursor += 2;
280
+ continue;
281
+ }
282
+ if (token.startsWith('-')) {
283
+ throw new Error(`错误: 未知参数: ${token}`);
284
+ }
285
+ throw new Error(`错误: 多余参数: ${token}`);
286
+ }
287
+ return options;
288
+ }
289
+
290
+ async function cmdImportSkills(argv = []) {
291
+ const options = parseImportSkillsCommandArgs(argv);
292
+ if (options.help) {
293
+ printImportSkillsUsage();
294
+ return;
295
+ }
296
+ if (!options.url) {
297
+ printImportSkillsUsage();
298
+ throw new Error('错误: 缺少 URL(例如: https://github.com/<owner>/<repo>/archive/refs/heads/main.zip)');
299
+ }
300
+ const candidates = buildGithubArchiveZipCandidates(options.url);
301
+ if (!candidates.length) {
302
+ const resolvedGithubUrl = resolveGithubArchiveZipUrl(options.url);
303
+ candidates.push(resolvedGithubUrl || options.url);
304
+ }
305
+ const uniqueCandidates = Array.from(new Set(candidates.filter(Boolean)));
306
+ if (!uniqueCandidates.length || !uniqueCandidates.every(isValidHttpUrl)) {
307
+ throw new Error('错误: URL 非法(仅支持 http/https)');
308
+ }
309
+
310
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codexmate-skills-url-'));
311
+ const zipPath = path.join(tempDir, 'skills.zip');
312
+ let finalUrl = uniqueCandidates[0];
313
+ try {
314
+ let lastError = null;
315
+ for (const candidateUrl of uniqueCandidates) {
316
+ finalUrl = candidateUrl;
317
+ console.log(`\n[Skills] Download: ${redactUrlForLog(candidateUrl)}`);
318
+ try {
319
+ await downloadUrlToFile(candidateUrl, zipPath, {
320
+ maxBytes: MAX_SKILLS_ZIP_UPLOAD_SIZE,
321
+ timeoutMs: options.timeoutMs,
322
+ maxRedirects: 5
323
+ });
324
+ lastError = null;
325
+ break;
326
+ } catch (e) {
327
+ lastError = e;
328
+ if (extractHttpStatusFromError(e) === 404) {
329
+ continue;
330
+ }
331
+ throw e;
332
+ }
333
+ }
334
+ if (lastError) {
335
+ throw lastError;
336
+ }
337
+ const fallbackName = options.name || path.basename(new URL(finalUrl).pathname) || 'skills.zip';
338
+ const result = await importSkillsFromZipFile(zipPath, {
339
+ tempDir,
340
+ targetApp: options.targetApp,
341
+ fallbackName
342
+ });
343
+ process.stdout.write(JSON.stringify(result, null, 2) + '\n');
344
+ } finally {
345
+ try {
346
+ fs.rmSync(tempDir, { recursive: true, force: true });
347
+ } catch (_) {}
348
+ }
349
+ }
350
+
351
+ module.exports = {
352
+ parseGithubRepoFromUrl,
353
+ resolveGithubArchiveZipUrl,
354
+ buildGithubArchiveZipCandidates,
355
+ cmdImportSkills
356
+ };