codexmate 0.0.30 → 0.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +363 -421
  2. package/README.zh.md +371 -354
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1725 -1725
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +402 -402
  9. package/cli/config-health.js +454 -454
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/local-bridge.js +324 -324
  13. package/cli/openai-bridge.js +1653 -1653
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -65
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -43
  18. package/cli/session-usage.concurrent.js +28 -28
  19. package/cli/session-usage.js +118 -118
  20. package/cli/session-usage.models.js +176 -176
  21. package/cli/skills.js +1141 -1141
  22. package/cli/zip-commands.js +510 -510
  23. package/cli.js +15829 -15481
  24. package/lib/automation.js +404 -404
  25. package/lib/cli-file-utils.js +151 -151
  26. package/lib/cli-models-utils.js +440 -440
  27. package/lib/cli-network-utils.js +190 -190
  28. package/lib/cli-path-utils.js +85 -85
  29. package/lib/cli-session-utils.js +121 -121
  30. package/lib/cli-sessions.js +426 -417
  31. package/lib/cli-utils.js +155 -155
  32. package/lib/cli-webhook.js +126 -126
  33. package/lib/download-artifacts.js +92 -92
  34. package/lib/mcp-stdio.js +453 -453
  35. package/lib/task-orchestrator.js +869 -869
  36. package/lib/text-diff.js +303 -303
  37. package/lib/workflow-engine.js +340 -340
  38. package/package.json +76 -76
  39. package/plugins/README.md +20 -20
  40. package/plugins/README.zh-CN.md +20 -20
  41. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  42. package/plugins/prompt-templates/computed.mjs +253 -253
  43. package/plugins/prompt-templates/index.mjs +8 -8
  44. package/plugins/prompt-templates/manifest.mjs +15 -15
  45. package/plugins/prompt-templates/methods.mjs +553 -553
  46. package/plugins/prompt-templates/overview.mjs +91 -91
  47. package/plugins/prompt-templates/ownership.mjs +19 -19
  48. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  49. package/plugins/prompt-templates/storage.mjs +64 -64
  50. package/plugins/registry.mjs +16 -16
  51. package/web-ui/app.js +647 -645
  52. package/web-ui/index.html +36 -36
  53. package/web-ui/logic.agents-diff.mjs +386 -386
  54. package/web-ui/logic.claude.mjs +168 -168
  55. package/web-ui/logic.codex.mjs +69 -69
  56. package/web-ui/logic.mjs +5 -5
  57. package/web-ui/logic.runtime.mjs +128 -128
  58. package/web-ui/logic.session-convert.mjs +70 -70
  59. package/web-ui/logic.sessions.mjs +781 -765
  60. package/web-ui/modules/api.mjs +90 -90
  61. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  62. package/web-ui/modules/app.computed.index.mjs +17 -17
  63. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  64. package/web-ui/modules/app.computed.session.mjs +693 -999
  65. package/web-ui/modules/app.constants.mjs +15 -15
  66. package/web-ui/modules/app.methods.agents.mjs +651 -632
  67. package/web-ui/modules/app.methods.claude-config.mjs +200 -200
  68. package/web-ui/modules/app.methods.codex-config.mjs +861 -917
  69. package/web-ui/modules/app.methods.index.mjs +94 -94
  70. package/web-ui/modules/app.methods.install.mjs +205 -205
  71. package/web-ui/modules/app.methods.navigation.mjs +774 -774
  72. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  73. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  74. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  75. package/web-ui/modules/app.methods.providers.mjs +529 -529
  76. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  77. package/web-ui/modules/app.methods.session-actions.mjs +591 -593
  78. package/web-ui/modules/app.methods.session-browser.mjs +1012 -984
  79. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  80. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  81. package/web-ui/modules/app.methods.startup-claude.mjs +537 -534
  82. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  83. package/web-ui/modules/app.methods.webhook.mjs +79 -79
  84. package/web-ui/modules/config-mode.computed.mjs +124 -124
  85. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  86. package/web-ui/modules/i18n.dict.mjs +3177 -3146
  87. package/web-ui/modules/i18n.mjs +62 -62
  88. package/web-ui/modules/plugins.computed.mjs +3 -3
  89. package/web-ui/modules/plugins.methods.mjs +3 -3
  90. package/web-ui/modules/plugins.storage.mjs +11 -11
  91. package/web-ui/modules/provider-url-display.mjs +17 -17
  92. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  93. package/web-ui/modules/skills.computed.mjs +107 -107
  94. package/web-ui/modules/skills.methods.mjs +482 -482
  95. package/web-ui/partials/index/layout-footer.html +13 -13
  96. package/web-ui/partials/index/layout-header.html +503 -500
  97. package/web-ui/partials/index/modal-config-template-agents.html +185 -174
  98. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  99. package/web-ui/partials/index/modal-health-check.html +45 -45
  100. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  101. package/web-ui/partials/index/modal-skills.html +200 -200
  102. package/web-ui/partials/index/modals-basic.html +162 -162
  103. package/web-ui/partials/index/panel-config-claude.html +136 -194
  104. package/web-ui/partials/index/panel-config-codex.html +197 -337
  105. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  106. package/web-ui/partials/index/panel-dashboard.html +219 -219
  107. package/web-ui/partials/index/panel-docs.html +115 -147
  108. package/web-ui/partials/index/panel-market.html +177 -177
  109. package/web-ui/partials/index/panel-orchestration.html +391 -391
  110. package/web-ui/partials/index/panel-plugins.html +253 -253
  111. package/web-ui/partials/index/panel-sessions.html +313 -308
  112. package/web-ui/partials/index/panel-settings.html +190 -190
  113. package/web-ui/partials/index/panel-trash.html +83 -88
  114. package/web-ui/partials/index/panel-usage.html +138 -371
  115. package/web-ui/res/json5.min.js +1 -1
  116. package/web-ui/res/vue.global.prod.js +13 -13
  117. package/web-ui/session-helpers.mjs +591 -594
  118. package/web-ui/source-bundle.cjs +233 -233
  119. package/web-ui/styles/base-theme.css +281 -281
  120. package/web-ui/styles/bridge-pool.css +197 -0
  121. package/web-ui/styles/controls-forms.css +433 -422
  122. package/web-ui/styles/dashboard.css +406 -406
  123. package/web-ui/styles/docs-panel.css +245 -271
  124. package/web-ui/styles/feedback.css +108 -108
  125. package/web-ui/styles/health-check-dialog.css +144 -144
  126. package/web-ui/styles/layout-shell.css +638 -626
  127. package/web-ui/styles/modals-core.css +466 -466
  128. package/web-ui/styles/navigation-panels.css +391 -391
  129. package/web-ui/styles/openclaw-structured.css +266 -266
  130. package/web-ui/styles/plugins-panel.css +564 -564
  131. package/web-ui/styles/responsive.css +392 -454
  132. package/web-ui/styles/sessions-list.css +647 -417
  133. package/web-ui/styles/sessions-preview.css +407 -407
  134. package/web-ui/styles/sessions-toolbar-trash.css +518 -334
  135. package/web-ui/styles/sessions-usage.css +588 -1040
  136. package/web-ui/styles/settings-panel.css +349 -349
  137. package/web-ui/styles/skills-list.css +305 -305
  138. package/web-ui/styles/skills-market.css +429 -429
  139. package/web-ui/styles/task-orchestration.css +822 -822
  140. package/web-ui/styles/titles-cards.css +472 -472
  141. package/web-ui/styles/trash-panel.css +90 -90
  142. package/web-ui/styles/webhook.css +81 -81
  143. package/web-ui/styles.css +24 -23
  144. package/web-ui.html +17 -17
@@ -1,356 +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 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
- };
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
+ };