codexmate 0.0.41 → 0.0.43

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 (155) hide show
  1. package/README.md +168 -168
  2. package/README.zh.md +168 -168
  3. package/cli/agents-files.js +230 -230
  4. package/cli/analytics-export-args.js +68 -68
  5. package/cli/archive-helpers.js +453 -453
  6. package/cli/auth-profiles.js +375 -375
  7. package/cli/builtin-proxy.js +2144 -2144
  8. package/cli/claude-proxy.js +1022 -1022
  9. package/cli/config-bootstrap.js +407 -407
  10. package/cli/config-health.js +454 -454
  11. package/cli/doctor-core.js +903 -903
  12. package/cli/import-skills-url.js +356 -356
  13. package/cli/local-bridge.js +556 -556
  14. package/cli/openai-bridge.js +1984 -1984
  15. package/cli/openclaw-config.js +629 -629
  16. package/cli/session-convert-args.js +69 -69
  17. package/cli/session-convert-io.js +82 -82
  18. package/cli/session-convert.js +150 -150
  19. package/cli/session-usage.concurrent.js +28 -28
  20. package/cli/session-usage.js +304 -304
  21. package/cli/session-usage.models.js +176 -176
  22. package/cli/skills.js +1141 -1141
  23. package/cli/update.js +171 -171
  24. package/cli/zip-commands.js +510 -510
  25. package/cli.js +16495 -16458
  26. package/lib/automation.js +404 -404
  27. package/lib/cli-file-utils.js +151 -151
  28. package/lib/cli-models-utils.js +440 -440
  29. package/lib/cli-network-utils.js +190 -190
  30. package/lib/cli-path-utils.js +85 -85
  31. package/lib/cli-session-utils.js +121 -121
  32. package/lib/cli-sessions.js +427 -427
  33. package/lib/cli-utils.js +155 -155
  34. package/lib/cli-webhook.js +154 -154
  35. package/lib/download-artifacts.js +92 -92
  36. package/lib/mcp-stdio.js +453 -453
  37. package/lib/task-orchestrator.js +869 -869
  38. package/lib/text-diff.js +303 -303
  39. package/lib/win-tray.js +119 -119
  40. package/lib/workflow-engine.js +340 -340
  41. package/package.json +77 -77
  42. package/plugins/README.md +20 -20
  43. package/plugins/README.zh-CN.md +20 -20
  44. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  45. package/plugins/prompt-templates/computed.mjs +311 -311
  46. package/plugins/prompt-templates/index.mjs +8 -8
  47. package/plugins/prompt-templates/manifest.mjs +18 -18
  48. package/plugins/prompt-templates/methods.mjs +553 -553
  49. package/plugins/prompt-templates/overview.mjs +91 -91
  50. package/plugins/prompt-templates/ownership.mjs +19 -19
  51. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  52. package/plugins/prompt-templates/storage.mjs +64 -64
  53. package/plugins/registry.mjs +16 -16
  54. package/web-ui/app.js +705 -695
  55. package/web-ui/index.html +37 -37
  56. package/web-ui/logic.agents-diff.mjs +386 -386
  57. package/web-ui/logic.claude.mjs +172 -172
  58. package/web-ui/logic.codex.mjs +69 -69
  59. package/web-ui/logic.mjs +5 -5
  60. package/web-ui/logic.runtime.mjs +128 -128
  61. package/web-ui/logic.session-convert.mjs +70 -70
  62. package/web-ui/logic.sessions.mjs +782 -782
  63. package/web-ui/modules/api.mjs +90 -90
  64. package/web-ui/modules/app.computed.dashboard.mjs +252 -252
  65. package/web-ui/modules/app.computed.index.mjs +17 -17
  66. package/web-ui/modules/app.computed.main-tabs.mjs +214 -214
  67. package/web-ui/modules/app.computed.session.mjs +876 -876
  68. package/web-ui/modules/app.constants.mjs +15 -15
  69. package/web-ui/modules/app.methods.agents.mjs +651 -651
  70. package/web-ui/modules/app.methods.claude-config.mjs +412 -412
  71. package/web-ui/modules/app.methods.codex-config.mjs +869 -869
  72. package/web-ui/modules/app.methods.index.mjs +96 -96
  73. package/web-ui/modules/app.methods.install.mjs +205 -205
  74. package/web-ui/modules/app.methods.navigation.mjs +804 -804
  75. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  76. package/web-ui/modules/app.methods.openclaw-editing.mjs +420 -420
  77. package/web-ui/modules/app.methods.openclaw-persist.mjs +375 -375
  78. package/web-ui/modules/app.methods.providers.mjs +602 -601
  79. package/web-ui/modules/app.methods.runtime.mjs +426 -420
  80. package/web-ui/modules/app.methods.session-actions.mjs +617 -591
  81. package/web-ui/modules/app.methods.session-browser.mjs +1018 -1018
  82. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  83. package/web-ui/modules/app.methods.session-trash.mjs +468 -468
  84. package/web-ui/modules/app.methods.startup-claude.mjs +557 -554
  85. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  86. package/web-ui/modules/app.methods.tool-config-permissions.mjs +90 -87
  87. package/web-ui/modules/app.methods.webhook.mjs +87 -87
  88. package/web-ui/modules/config-mode.computed.mjs +124 -124
  89. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  90. package/web-ui/modules/i18n/locales/en.mjs +1187 -1140
  91. package/web-ui/modules/i18n/locales/ja.mjs +1178 -1130
  92. package/web-ui/modules/i18n/locales/vi.mjs +294 -239
  93. package/web-ui/modules/i18n/locales/zh.mjs +1190 -1143
  94. package/web-ui/modules/i18n.dict.mjs +14 -14
  95. package/web-ui/modules/i18n.mjs +111 -111
  96. package/web-ui/modules/plugins.computed.mjs +3 -3
  97. package/web-ui/modules/plugins.methods.mjs +3 -3
  98. package/web-ui/modules/plugins.storage.mjs +11 -11
  99. package/web-ui/modules/provider-url-display.mjs +17 -17
  100. package/web-ui/modules/sessions-filters-url.mjs +138 -138
  101. package/web-ui/modules/skills.computed.mjs +107 -107
  102. package/web-ui/modules/skills.methods.mjs +513 -513
  103. package/web-ui/partials/index/layout-footer.html +13 -13
  104. package/web-ui/partials/index/layout-header.html +478 -478
  105. package/web-ui/partials/index/modal-config-template-agents.html +185 -185
  106. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  107. package/web-ui/partials/index/modal-health-check.html +45 -45
  108. package/web-ui/partials/index/modal-openclaw-config.html +344 -344
  109. package/web-ui/partials/index/modal-skills.html +200 -200
  110. package/web-ui/partials/index/modal-webhook.html +42 -42
  111. package/web-ui/partials/index/modals-basic.html +263 -263
  112. package/web-ui/partials/index/panel-config-claude.html +187 -187
  113. package/web-ui/partials/index/panel-config-codex.html +205 -205
  114. package/web-ui/partials/index/panel-config-openclaw.html +89 -89
  115. package/web-ui/partials/index/panel-dashboard.html +171 -171
  116. package/web-ui/partials/index/panel-docs.html +114 -114
  117. package/web-ui/partials/index/panel-market.html +104 -104
  118. package/web-ui/partials/index/panel-orchestration.html +391 -391
  119. package/web-ui/partials/index/panel-plugins.html +253 -253
  120. package/web-ui/partials/index/panel-sessions.html +325 -319
  121. package/web-ui/partials/index/panel-settings.html +181 -181
  122. package/web-ui/partials/index/panel-trash.html +82 -82
  123. package/web-ui/partials/index/panel-usage.html +181 -181
  124. package/web-ui/res/json5.min.js +1 -1
  125. package/web-ui/res/vue.global.prod.js +13 -13
  126. package/web-ui/res/vue.runtime.global.prod.js +7 -7
  127. package/web-ui/res/web-ui-render.precompiled.js +7671 -7666
  128. package/web-ui/session-helpers.mjs +602 -602
  129. package/web-ui/source-bundle.cjs +305 -305
  130. package/web-ui/styles/base-theme.css +291 -291
  131. package/web-ui/styles/bridge-pool.css +266 -266
  132. package/web-ui/styles/controls-forms.css +532 -532
  133. package/web-ui/styles/dashboard.css +438 -438
  134. package/web-ui/styles/docs-panel.css +245 -245
  135. package/web-ui/styles/feedback.css +108 -108
  136. package/web-ui/styles/health-check-dialog.css +144 -144
  137. package/web-ui/styles/layout-shell.css +711 -711
  138. package/web-ui/styles/modals-core.css +499 -499
  139. package/web-ui/styles/navigation-panels.css +399 -399
  140. package/web-ui/styles/openclaw-structured.css +616 -616
  141. package/web-ui/styles/plugins-panel.css +564 -564
  142. package/web-ui/styles/responsive.css +501 -501
  143. package/web-ui/styles/sessions-list.css +683 -683
  144. package/web-ui/styles/sessions-preview.css +407 -407
  145. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  146. package/web-ui/styles/sessions-usage.css +849 -849
  147. package/web-ui/styles/settings-panel.css +419 -419
  148. package/web-ui/styles/skills-list.css +305 -305
  149. package/web-ui/styles/skills-market.css +723 -723
  150. package/web-ui/styles/task-orchestration.css +822 -822
  151. package/web-ui/styles/titles-cards.css +492 -486
  152. package/web-ui/styles/trash-panel.css +90 -90
  153. package/web-ui/styles/webhook.css +115 -115
  154. package/web-ui/styles.css +24 -24
  155. 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
+ };