@workskills/getskill 1.1.10 → 2.0.0

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.
@@ -4,9 +4,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.request = request;
7
+ exports.downloadFile = downloadFile;
8
+ exports.getSkillsIndexUrl = getSkillsIndexUrl;
9
+ exports.getSkillPackageUrl = getSkillPackageUrl;
10
+ exports.fetchSkillsIndex = fetchSkillsIndex;
11
+ exports.normalizeSkillIndexKey = normalizeSkillIndexKey;
12
+ exports.filterIndexByKeyword = filterIndexByKeyword;
13
+ exports.mapIndexEntryToSearchSkill = mapIndexEntryToSearchSkill;
14
+ exports.findSkillIndexEntry = findSkillIndexEntry;
7
15
  exports.repositoryHasSkillFile = repositoryHasSkillFile;
8
- exports.transformSearchResults = transformSearchResults;
9
16
  exports.searchSkills = searchSkills;
17
+ const fs_1 = __importDefault(require("fs"));
10
18
  const http_1 = __importDefault(require("http"));
11
19
  const https_1 = __importDefault(require("https"));
12
20
  const config_1 = require("./config");
@@ -105,25 +113,213 @@ function request(url, options = {}, redirectCount = 0) {
105
113
  req.end();
106
114
  });
107
115
  }
108
- function mapRepositoryCandidate(item) {
109
- if ('repository' in item && item.repository) {
110
- return item.repository;
116
+ function downloadFile(url, destPath, redirectCount = 0) {
117
+ const MAX_REDIRECTS = 5;
118
+ return new Promise((resolve, reject) => {
119
+ if (redirectCount >= MAX_REDIRECTS) {
120
+ reject(new Error(`Too many redirects (${MAX_REDIRECTS})`));
121
+ return;
122
+ }
123
+ let urlObj;
124
+ try {
125
+ urlObj = new URL(url);
126
+ }
127
+ catch {
128
+ reject(new Error(`Invalid URL: ${url}`));
129
+ return;
130
+ }
131
+ const protocol = urlObj.protocol === 'https:' ? https_1.default : http_1.default;
132
+ const reqOptions = {
133
+ hostname: urlObj.hostname,
134
+ port: urlObj.port,
135
+ path: urlObj.pathname + urlObj.search,
136
+ method: 'GET',
137
+ timeout: config_1.REQUEST_TIMEOUT_MS
138
+ };
139
+ const req = protocol.request(reqOptions, (res) => {
140
+ const statusCode = res.statusCode ?? 0;
141
+ if ([301, 302, 303, 307, 308].includes(statusCode)) {
142
+ const locationHeader = res.headers.location;
143
+ const redirectUrl = Array.isArray(locationHeader)
144
+ ? locationHeader[0]
145
+ : locationHeader;
146
+ res.resume();
147
+ if (!redirectUrl) {
148
+ reject(new Error(`Redirect location header missing (${statusCode})`));
149
+ return;
150
+ }
151
+ let newUrl;
152
+ try {
153
+ newUrl = new URL(redirectUrl, url).toString();
154
+ }
155
+ catch {
156
+ reject(new Error(`Invalid redirect URL: ${redirectUrl}`));
157
+ return;
158
+ }
159
+ downloadFile(newUrl, destPath, redirectCount + 1)
160
+ .then(resolve)
161
+ .catch(reject);
162
+ return;
163
+ }
164
+ if (statusCode < 200 || statusCode >= 300) {
165
+ res.resume();
166
+ reject(new Error(`Request failed with status code ${statusCode}: ${url}`));
167
+ return;
168
+ }
169
+ let receivedBytes = 0;
170
+ const fileStream = fs_1.default.createWriteStream(destPath);
171
+ res.on('data', (chunk) => {
172
+ receivedBytes += chunk.length;
173
+ });
174
+ res.on('error', (error) => {
175
+ fileStream.destroy();
176
+ fs_1.default.rmSync(destPath, { force: true });
177
+ reject(new Error(`Response error: ${error.message}`));
178
+ });
179
+ fileStream.on('error', (error) => {
180
+ res.destroy();
181
+ fs_1.default.rmSync(destPath, { force: true });
182
+ reject(new Error(`Write file error: ${error.message}`));
183
+ });
184
+ fileStream.on('finish', () => {
185
+ fileStream.close(() => resolve(receivedBytes));
186
+ });
187
+ res.pipe(fileStream);
188
+ });
189
+ req.on('error', (error) => {
190
+ fs_1.default.rmSync(destPath, { force: true });
191
+ if (error.code === 'ECONNREFUSED') {
192
+ reject(new Error(`Connection refused: ${urlObj.hostname}`));
193
+ }
194
+ else if (error.code === 'ENOTFOUND') {
195
+ reject(new Error(`Host not found: ${urlObj.hostname}`));
196
+ }
197
+ else if (error.code === 'ETIMEDOUT' ||
198
+ error.code === 'ESOCKETTIMEDOUT') {
199
+ reject(new Error(`Request timeout: ${url}`));
200
+ }
201
+ else {
202
+ reject(new Error(`Network error: ${error.message}`));
203
+ }
204
+ });
205
+ req.on('timeout', () => {
206
+ req.destroy();
207
+ fs_1.default.rmSync(destPath, { force: true });
208
+ reject(new Error(`Request timeout after ${config_1.REQUEST_TIMEOUT_MS}ms: ${url}`));
209
+ });
210
+ req.end();
211
+ });
212
+ }
213
+ function getSkillsIndexUrl() {
214
+ return `${(0, config_1.getBaseUrl)()}/data/skills.json`;
215
+ }
216
+ function getSkillPackageUrl(entry) {
217
+ const file = (entry.file || '').trim();
218
+ if (!file) {
219
+ return `${(0, config_1.getBaseUrl)()}/skills/${encodeURIComponent(entry.id)}.zip`;
220
+ }
221
+ if (/^https?:\/\//i.test(file)) {
222
+ return file;
111
223
  }
112
- return item;
224
+ return `${(0, config_1.getBaseUrl)()}/${file.replace(/^\/+/, '')}`;
113
225
  }
114
- async function repositoryHasSkillFile(repoFullName) {
115
- if (!repoFullName ||
116
- typeof repoFullName !== 'string' ||
117
- !repoFullName.includes('/')) {
226
+ async function fetchSkillsIndex() {
227
+ const url = getSkillsIndexUrl();
228
+ const response = await request(url, { timeout: config_1.REQUEST_TIMEOUT_MS });
229
+ if (!response.body || response.body.trim() === '') {
230
+ throw new Error('技能索引为空: 服务器返回空响应');
231
+ }
232
+ let parsed;
233
+ try {
234
+ parsed = JSON.parse(response.body);
235
+ }
236
+ catch (error) {
237
+ const message = error instanceof Error ? error.message : String(error);
238
+ throw new Error(`技能索引 JSON 解析失败: ${message}`);
239
+ }
240
+ if (!parsed || !Array.isArray(parsed.skills)) {
241
+ throw new Error('技能索引格式无效: 缺少 skills 数组');
242
+ }
243
+ return parsed.skills.filter((entry) => entry &&
244
+ typeof entry.id === 'string' &&
245
+ entry.id.trim() !== '' &&
246
+ typeof entry.file === 'string' &&
247
+ entry.file.trim() !== '');
248
+ }
249
+ function normalizeSkillIndexKey(skillName) {
250
+ return skillName
251
+ .trim()
252
+ .replace(/^skills\//, '')
253
+ .replace(/[\\/_\s]+/g, '-')
254
+ .replace(/-{2,}/g, '-')
255
+ .replace(/^-+|-+$/g, '')
256
+ .toLowerCase();
257
+ }
258
+ function filterIndexByKeyword(entries, keyword, limit = 20, page = 1) {
259
+ if (!Array.isArray(entries) || entries.length === 0) {
260
+ return [];
261
+ }
262
+ const normalizedKeyword = (keyword || '').trim().toLowerCase();
263
+ if (!normalizedKeyword) {
264
+ return [];
265
+ }
266
+ const matched = entries.filter((entry) => {
267
+ const haystacks = [
268
+ entry.id,
269
+ entry.name,
270
+ entry.description,
271
+ entry.category || '',
272
+ entry.author || '',
273
+ ...(Array.isArray(entry.tags) ? entry.tags : [])
274
+ ];
275
+ return haystacks.some((value) => typeof value === 'string' &&
276
+ value.toLowerCase().includes(normalizedKeyword));
277
+ });
278
+ const safeLimit = Number.isFinite(limit) && limit > 0 ? limit : 20;
279
+ const safePage = Number.isFinite(page) && page > 0 ? page : 1;
280
+ const start = (safePage - 1) * safeLimit;
281
+ return matched.slice(start, start + safeLimit);
282
+ }
283
+ function mapIndexEntryToSearchSkill(entry) {
284
+ const downloadUrl = getSkillPackageUrl(entry);
285
+ return {
286
+ name: entry.name || entry.id,
287
+ full_name: entry.id,
288
+ description: entry.description || '',
289
+ html_url: `${(0, config_1.getBaseUrl)()}/skill.html?id=${encodeURIComponent(entry.id)}`,
290
+ git_url: downloadUrl,
291
+ clone_url: downloadUrl,
292
+ download_url: downloadUrl,
293
+ version: entry.version || 'unknown',
294
+ category: entry.category || '',
295
+ author: entry.author || '',
296
+ size: typeof entry.size === 'number' ? entry.size : 0
297
+ };
298
+ }
299
+ async function findSkillIndexEntry(skillName) {
300
+ if (!skillName || typeof skillName !== 'string') {
301
+ return null;
302
+ }
303
+ const normalized = normalizeSkillIndexKey(skillName);
304
+ if (!normalized) {
305
+ return null;
306
+ }
307
+ const entries = await fetchSkillsIndex();
308
+ return (entries.find((entry) => normalizeSkillIndexKey(entry.id) === normalized ||
309
+ normalizeSkillIndexKey(entry.name || '') === normalized) || null);
310
+ }
311
+ async function repositoryHasSkillFile(skillName) {
312
+ if (!skillName || typeof skillName !== 'string') {
118
313
  return false;
119
314
  }
120
- const segments = repoFullName.split('/');
121
- const owner = segments.shift();
122
- const repo = segments.join('/');
123
- if (!owner || !repo) {
315
+ const normalized = skillName
316
+ .trim()
317
+ .replace(/^skills\//, '')
318
+ .replace(/[\\/]/g, '_');
319
+ if (!normalized) {
124
320
  return false;
125
321
  }
126
- const url = `${(0, config_1.getBaseUrl)()}/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/SKILL.md`;
322
+ const url = `${(0, config_1.getBaseUrl)()}/skills/${encodeURIComponent(normalized)}/SKILL.md`;
127
323
  try {
128
324
  await request(url, { timeout: Math.min(config_1.REQUEST_TIMEOUT_MS, 15000) });
129
325
  return true;
@@ -132,66 +328,16 @@ async function repositoryHasSkillFile(repoFullName) {
132
328
  return false;
133
329
  }
134
330
  }
135
- async function transformSearchResults(result, hasSkillFile = repositoryHasSkillFile) {
136
- if (!result || result.ok === false || !Array.isArray(result.data)) {
137
- return [];
138
- }
139
- const filteredCandidates = result.data
140
- .map(mapRepositoryCandidate)
141
- .filter((item) => Boolean(item && (item.full_name || item.name)))
142
- .filter((item) => !item.private &&
143
- !item.empty &&
144
- !item.archived &&
145
- !item.template &&
146
- !item.fork);
147
- const skillChecks = await Promise.all(filteredCandidates.map(async (item) => {
148
- const repoFullName = item.full_name || item.name || '';
149
- const hasSkill = await hasSkillFile(repoFullName);
150
- if (!hasSkill) {
151
- return null;
152
- }
153
- return {
154
- name: item.full_name || item.name || '',
155
- full_name: item.full_name || '',
156
- description: item.description || '',
157
- html_url: item.html_url || '',
158
- git_url: item.clone_url ||
159
- (item.html_url ? `${item.html_url}.git` : ''),
160
- clone_url: item.clone_url || ''
161
- };
162
- }));
163
- return skillChecks.filter((item) => Boolean(item));
164
- }
165
331
  async function searchSkills(keyword, options = {}) {
166
332
  if (!keyword || typeof keyword !== 'string') {
167
333
  logger_1.default.error('搜索失败: 关键词无效');
168
334
  return [];
169
335
  }
170
- const { sort = 'updated', order = 'desc', page = 1, limit = 20 } = options;
171
- const fixedSearchParams = [
172
- 'private=false',
173
- 'is_private=false',
174
- 'archived=false',
175
- 'template=false'
176
- ].join('&');
177
- const url = `${(0, config_1.getBaseUrl)()}/api/v1/repos/search?q=${encodeURIComponent(keyword)}&${fixedSearchParams}&sort=${sort}&order=${order}&page=${page}&limit=${limit}`;
336
+ const { page = 1, limit = 20 } = options;
178
337
  try {
179
- const response = await request(url, { timeout: config_1.REQUEST_TIMEOUT_MS });
180
- if (!response.body || response.body.trim() === '') {
181
- logger_1.default.warn('搜索警告: 服务器返回空响应');
182
- return [];
183
- }
184
- let parsed;
185
- try {
186
- parsed = JSON.parse(response.body);
187
- }
188
- catch (error) {
189
- const message = error instanceof Error ? error.message : String(error);
190
- logger_1.default.error('搜索失败: JSON 解析错误', message);
191
- logger_1.default.debug('响应内容:', response.body.substring(0, 200));
192
- return [];
193
- }
194
- return transformSearchResults(parsed);
338
+ const entries = await fetchSkillsIndex();
339
+ const matched = filterIndexByKeyword(entries, keyword, limit, page);
340
+ return matched.map(mapIndexEntryToSearchSkill);
195
341
  }
196
342
  catch (error) {
197
343
  const message = error instanceof Error ? error.message : String(error);
@@ -1,4 +1,10 @@
1
- import type { DownloadOptions, DownloadResult, PublishOptions, PublishResult, RemoveInstalledSkillResult, UpdateAllResult } from './types';
1
+ import type { DownloadOptions, DownloadResult, RemoveInstalledSkillResult, SkillIndexEntry, UpdateAllResult } from './types';
2
+ export interface FetchSkillToCacheResult {
3
+ repoPath: string;
4
+ cachePath: string;
5
+ entry: SkillIndexEntry;
6
+ }
7
+ export declare function fetchSkillToCache(skillName: string, options?: DownloadOptions): Promise<FetchSkillToCacheResult>;
2
8
  export declare function cloneOrUpdateRepo(skillName: string, options?: DownloadOptions): Promise<string>;
3
9
  export declare function restartOpenClawGateway(): Promise<void>;
4
10
  export declare function downloadSkill(skillName: string, options?: DownloadOptions): Promise<DownloadResult>;
@@ -7,4 +13,3 @@ export declare function updateAllSkills(): Promise<UpdateAllResult[]>;
7
13
  export declare function uninstallSkill(skillName: string, options?: {
8
14
  removeCache?: boolean;
9
15
  }): Promise<RemoveInstalledSkillResult>;
10
- export declare function publishSkill(skillPath: string, options?: PublishOptions): Promise<PublishResult>;
@@ -3,53 +3,58 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.fetchSkillToCache = fetchSkillToCache;
6
7
  exports.cloneOrUpdateRepo = cloneOrUpdateRepo;
7
8
  exports.restartOpenClawGateway = restartOpenClawGateway;
8
9
  exports.downloadSkill = downloadSkill;
9
10
  exports.updateSkill = updateSkill;
10
11
  exports.updateAllSkills = updateAllSkills;
11
12
  exports.uninstallSkill = uninstallSkill;
12
- exports.publishSkill = publishSkill;
13
13
  const fs_1 = __importDefault(require("fs"));
14
14
  const path_1 = __importDefault(require("path"));
15
15
  const config_1 = require("./config");
16
16
  const logger_1 = __importDefault(require("./logger"));
17
- const publish_registry_1 = require("./publish-registry");
17
+ const network_1 = require("./network");
18
18
  const state_1 = require("./state");
19
- const skill_validator_1 = require("./skill-validator");
20
19
  const system_1 = require("./system");
21
- async function cloneOrUpdateRepo(skillName, options = {}) {
22
- await (0, system_1.ensureGitInstalled)();
23
- const cacheDir = (0, config_1.getSkillsCacheDirectory)();
24
- const localSkillName = (0, state_1.normalizeSkillName)(skillName);
25
- const remoteSkillPath = (0, state_1.getRemoteSkillPath)(skillName);
26
- const repoPath = path_1.default.join(cacheDir, localSkillName);
27
- const requestedVersion = options.version?.trim();
28
- if (!fs_1.default.existsSync(cacheDir)) {
29
- fs_1.default.mkdirSync(cacheDir, { recursive: true });
30
- }
31
- if (fs_1.default.existsSync(repoPath)) {
32
- logger_1.default.info(`更新仓库: ${skillName}...`);
33
- if (requestedVersion) {
34
- await (0, system_1.executeCommand)('git fetch --all --tags --prune', repoPath);
35
- await (0, system_1.executeCommand)(`git checkout "${requestedVersion}"`, repoPath);
36
- }
37
- else {
38
- await (0, system_1.executeCommand)('git pull', repoPath);
39
- }
40
- logger_1.default.info(`仓库更新成功: ${repoPath}`);
41
- return repoPath;
20
+ const unzip_1 = require("./unzip");
21
+ function assertVersionAvailable(entry, requestedVersion) {
22
+ if (!requestedVersion) {
23
+ return;
42
24
  }
43
- const gitUrl = `${(0, config_1.getBaseUrl)()}/${remoteSkillPath}.git`;
44
- logger_1.default.info(`克隆仓库: ${gitUrl}...`);
45
- if (requestedVersion) {
46
- await (0, system_1.executeCommand)(`git clone "${gitUrl}" "${localSkillName}"`, cacheDir);
47
- await (0, system_1.executeCommand)(`git checkout "${requestedVersion}"`, repoPath);
25
+ if (requestedVersion !== entry.version) {
26
+ throw new Error(`技能 ${entry.id} 不提供版本 ${requestedVersion},站点当前仅提供最新版本 ${entry.version}`);
48
27
  }
49
- else {
50
- await (0, system_1.executeCommand)(`git clone --depth 1 "${gitUrl}" "${localSkillName}"`, cacheDir);
28
+ }
29
+ async function fetchSkillToCache(skillName, options = {}) {
30
+ const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
31
+ const entry = await (0, network_1.findSkillIndexEntry)(normalizedSkillName);
32
+ if (!entry) {
33
+ throw new Error(`技能不存在: ${normalizedSkillName},请先使用 getskill search <关键词> 查询可用技能`);
51
34
  }
52
- logger_1.default.info(`仓库克隆成功: ${repoPath}`);
35
+ const requestedVersion = options.version?.trim();
36
+ assertVersionAvailable(entry, requestedVersion);
37
+ const cacheDir = (0, config_1.getSkillsCacheDirectory)();
38
+ (0, system_1.ensureDirectoryExists)(cacheDir);
39
+ const localSkillName = (0, state_1.normalizeSkillName)(normalizedSkillName);
40
+ const cachePath = path_1.default.join(cacheDir, localSkillName);
41
+ const zipPath = path_1.default.join(cacheDir, `${localSkillName}.zip`);
42
+ const downloadUrl = (0, network_1.getSkillPackageUrl)(entry);
43
+ logger_1.default.info(`下载技能包: ${downloadUrl}`);
44
+ const receivedBytes = await (0, network_1.downloadFile)(downloadUrl, zipPath);
45
+ logger_1.default.info(`下载完成 (${receivedBytes} bytes),正在解压...`);
46
+ if (fs_1.default.existsSync(cachePath)) {
47
+ fs_1.default.rmSync(cachePath, { recursive: true, force: true });
48
+ }
49
+ (0, system_1.ensureDirectoryExists)(cachePath);
50
+ (0, unzip_1.extractZip)(zipPath, cachePath);
51
+ fs_1.default.rmSync(zipPath, { force: true });
52
+ const repoPath = (0, unzip_1.resolveSkillRoot)(cachePath);
53
+ logger_1.default.info(`技能包已解压: ${repoPath}`);
54
+ return { repoPath, cachePath, entry };
55
+ }
56
+ async function cloneOrUpdateRepo(skillName, options = {}) {
57
+ const { repoPath } = await fetchSkillToCache(skillName, options);
53
58
  return repoPath;
54
59
  }
55
60
  async function restartOpenClawGateway() {
@@ -69,47 +74,62 @@ async function downloadSkill(skillName, options = {}) {
69
74
  logger_1.default.info(`下载技能: ${skillName}...`);
70
75
  const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
71
76
  const requestedVersion = options.version?.trim();
72
- const repoPath = await cloneOrUpdateRepo(normalizedSkillName, {
77
+ const { repoPath, entry } = await fetchSkillToCache(normalizedSkillName, {
73
78
  version: requestedVersion
74
79
  });
75
80
  const copiedFiles = (0, state_1.copySkillFiles)(repoPath, normalizedSkillName);
76
- await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'install', requestedVersion);
81
+ await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'install', requestedVersion, entry.version);
82
+ logger_1.default.info(`技能 ${normalizedSkillName} (v${entry.version}) 安装成功!`);
77
83
  return {
78
84
  skillName: normalizedSkillName,
79
85
  repoPath,
80
86
  files: copiedFiles,
81
- requestedVersion: requestedVersion || null
87
+ requestedVersion: requestedVersion || null,
88
+ version: entry.version
82
89
  };
83
90
  }
84
91
  async function updateSkill(skillName, options = {}) {
85
92
  const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
86
93
  const requestedVersion = options.version?.trim();
87
94
  logger_1.default.info(`正在更新技能: ${normalizedSkillName}...`);
88
- const cacheDir = (0, config_1.getSkillsCacheDirectory)();
89
- const localSkillName = (0, state_1.normalizeSkillName)(normalizedSkillName);
90
- const repoPath = path_1.default.join(cacheDir, localSkillName);
91
- if (!fs_1.default.existsSync(repoPath)) {
92
- logger_1.default.info('技能仓库不存在,将重新下载...');
93
- return downloadSkill(normalizedSkillName, {
94
- version: requestedVersion
95
- });
95
+ const entry = await (0, network_1.findSkillIndexEntry)(normalizedSkillName);
96
+ if (!entry) {
97
+ throw new Error(`技能不存在: ${normalizedSkillName},无法更新`);
96
98
  }
97
- if (requestedVersion) {
98
- await (0, system_1.executeCommand)('git fetch --all --tags --prune', repoPath);
99
- await (0, system_1.executeCommand)(`git checkout "${requestedVersion}"`, repoPath);
99
+ assertVersionAvailable(entry, requestedVersion);
100
+ const localSkillName = (0, state_1.normalizeSkillName)(normalizedSkillName);
101
+ const skillDir = path_1.default.join((0, config_1.getSkillsDirectory)(), localSkillName);
102
+ const cachePath = path_1.default.join((0, config_1.getSkillsCacheDirectory)(), localSkillName);
103
+ const record = (0, state_1.readInstallState)().skills[localSkillName];
104
+ if (record &&
105
+ record.version &&
106
+ record.version === entry.version &&
107
+ fs_1.default.existsSync(skillDir)) {
108
+ logger_1.default.info(`技能 ${normalizedSkillName} 已是最新版本 (${entry.version}),无需更新`);
109
+ return {
110
+ skillName: normalizedSkillName,
111
+ repoPath: record.repoPath || cachePath,
112
+ files: [skillDir],
113
+ requestedVersion: requestedVersion || null,
114
+ version: entry.version,
115
+ upToDate: true
116
+ };
100
117
  }
101
- else {
102
- await (0, system_1.executeCommand)('git pull', repoPath);
118
+ if (record) {
119
+ logger_1.default.info(`发现新版本: ${record.version || 'unknown'} -> ${entry.version}`);
103
120
  }
104
- logger_1.default.info('Git 仓库已更新');
121
+ const { repoPath } = await fetchSkillToCache(normalizedSkillName, {
122
+ version: requestedVersion
123
+ });
105
124
  const copiedFiles = (0, state_1.copySkillFiles)(repoPath, normalizedSkillName);
106
- await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'update', requestedVersion);
125
+ await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'update', requestedVersion, entry.version);
107
126
  logger_1.default.info(`技能 ${normalizedSkillName} 更新成功!`);
108
127
  return {
109
128
  skillName: normalizedSkillName,
110
129
  repoPath,
111
130
  files: copiedFiles,
112
- requestedVersion: requestedVersion || null
131
+ requestedVersion: requestedVersion || null,
132
+ version: entry.version
113
133
  };
114
134
  }
115
135
  async function updateAllSkills() {
@@ -135,144 +155,3 @@ async function uninstallSkill(skillName, options = {}) {
135
155
  }
136
156
  return result;
137
157
  }
138
- function quoteShellArg(value) {
139
- return value.replace(/"/g, '\\"');
140
- }
141
- async function ensureLocalGitIdentity(repoPath, username, email) {
142
- if (username) {
143
- try {
144
- const { stdout } = await (0, system_1.executeCommand)('git config user.name', repoPath);
145
- if (!stdout.trim()) {
146
- throw new Error('missing user.name');
147
- }
148
- }
149
- catch {
150
- await (0, system_1.executeCommand)(`git config user.name "${quoteShellArg(username)}"`, repoPath);
151
- }
152
- }
153
- if (email) {
154
- try {
155
- const { stdout } = await (0, system_1.executeCommand)('git config user.email', repoPath);
156
- if (!stdout.trim()) {
157
- throw new Error('missing user.email');
158
- }
159
- }
160
- catch {
161
- await (0, system_1.executeCommand)(`git config user.email "${quoteShellArg(email)}"`, repoPath);
162
- }
163
- }
164
- }
165
- function resolvePublishRepoName(skillPath, options, skillNameFromManifest) {
166
- const candidate = options.repoName?.trim() ||
167
- skillNameFromManifest ||
168
- path_1.default.basename(skillPath);
169
- const repoName = (0, skill_validator_1.sanitizeRepositoryName)(candidate);
170
- if (!repoName) {
171
- throw new Error('无法确定仓库名称,请通过 --name 指定有效仓库名');
172
- }
173
- return repoName;
174
- }
175
- async function publishSkill(skillPath, options = {}) {
176
- await (0, system_1.ensureGitInstalled)();
177
- const resolvedSkillPath = path_1.default.resolve(skillPath);
178
- if (!fs_1.default.existsSync(resolvedSkillPath)) {
179
- throw new Error(`技能目录不存在: ${resolvedSkillPath}`);
180
- }
181
- const validation = (0, skill_validator_1.validateSkillDirectory)(resolvedSkillPath);
182
- if (!validation.valid) {
183
- throw new Error(`SKILL.md 校验失败:\n- ${validation.errors.join('\n- ')}`);
184
- }
185
- logger_1.default.info('SKILL.md 校验通过,允许继续发布。');
186
- const managesRegistryAuth = !options.repoUrl || (0, publish_registry_1.isRegistryRepoUrl)(options.repoUrl);
187
- const authSession = managesRegistryAuth
188
- ? await (0, publish_registry_1.ensureRegistryAuth)(options)
189
- : null;
190
- const repoName = resolvePublishRepoName(resolvedSkillPath, options, validation.metadata.name);
191
- if (authSession) {
192
- const labelByMode = {
193
- 'stored-token': '使用已保存登录态',
194
- login: '已自动登录',
195
- register: '已自动注册并登录'
196
- };
197
- logger_1.default.info(`${labelByMode[authSession.mode]}: ${authSession.username}`);
198
- }
199
- const gitDirPath = path_1.default.join(resolvedSkillPath, '.git');
200
- if (!fs_1.default.existsSync(gitDirPath)) {
201
- logger_1.default.info('未检测到 Git 仓库,正在初始化...');
202
- await (0, system_1.executeCommand)('git init', resolvedSkillPath);
203
- }
204
- const branch = options.branch?.trim() || 'main';
205
- const commitMessage = options.message?.trim() || 'chore: publish skill via getskill';
206
- let currentRemoteUrl = '';
207
- try {
208
- const { stdout } = await (0, system_1.executeCommand)('git remote get-url origin', resolvedSkillPath);
209
- currentRemoteUrl = stdout.trim();
210
- }
211
- catch {
212
- currentRemoteUrl = '';
213
- }
214
- let createdRemoteRepo = false;
215
- if (options.repoUrl?.trim()) {
216
- currentRemoteUrl = options.repoUrl.trim();
217
- }
218
- else if (!currentRemoteUrl) {
219
- if (!authSession) {
220
- throw new Error('当前未登录,无法自动创建远程仓库');
221
- }
222
- const repository = await (0, publish_registry_1.ensureRemoteRepository)(authSession, repoName, {
223
- description: validation.metadata.description,
224
- visibility: options.visibility
225
- });
226
- currentRemoteUrl = repository.cloneUrl;
227
- createdRemoteRepo = !repository.existed;
228
- logger_1.default.info(repository.existed
229
- ? `已检测到远程仓库: ${currentRemoteUrl}`
230
- : `已自动创建远程仓库: ${currentRemoteUrl}`);
231
- }
232
- if (!currentRemoteUrl) {
233
- throw new Error('无法确定发布目标仓库地址');
234
- }
235
- try {
236
- await (0, system_1.executeCommand)(`git remote set-url origin "${quoteShellArg(currentRemoteUrl)}"`, resolvedSkillPath);
237
- }
238
- catch {
239
- await (0, system_1.executeCommand)(`git remote add origin "${quoteShellArg(currentRemoteUrl)}"`, resolvedSkillPath);
240
- }
241
- const pushEnv = authSession && (0, publish_registry_1.isRegistryRepoUrl)(currentRemoteUrl)
242
- ? {
243
- GIT_CONFIG_COUNT: '1',
244
- GIT_CONFIG_KEY_0: 'http.extraHeader',
245
- GIT_CONFIG_VALUE_0: (0, publish_registry_1.buildGitHttpExtraHeader)(authSession)
246
- }
247
- : undefined;
248
- await (0, system_1.executeCommand)(`git checkout -B "${quoteShellArg(branch)}"`, resolvedSkillPath);
249
- await ensureLocalGitIdentity(resolvedSkillPath, authSession?.username || options.username, authSession?.email || options.email || null);
250
- await (0, system_1.executeCommand)('git add .', resolvedSkillPath);
251
- let committed = false;
252
- try {
253
- await (0, system_1.executeCommand)(`git commit -m "${quoteShellArg(commitMessage)}"`, resolvedSkillPath);
254
- committed = true;
255
- }
256
- catch (error) {
257
- const message = error instanceof Error ? error.message : String(error);
258
- const normalizedMessage = message.toLowerCase();
259
- if (normalizedMessage.includes('nothing to commit') ||
260
- normalizedMessage.includes('nothing added to commit')) {
261
- committed = false;
262
- }
263
- else {
264
- throw error;
265
- }
266
- }
267
- await (0, system_1.executeCommand)(`git push -u origin "${quoteShellArg(branch)}"`, resolvedSkillPath, pushEnv ? { env: pushEnv } : undefined);
268
- logger_1.default.info(`已发布技能目录: ${resolvedSkillPath}`);
269
- return {
270
- skillPath: resolvedSkillPath,
271
- remoteUrl: currentRemoteUrl,
272
- branch,
273
- committed,
274
- repositoryName: repoName,
275
- createdRemoteRepo,
276
- authMode: authSession?.mode || 'not-required'
277
- };
278
- }
@@ -5,7 +5,7 @@ export declare function normalizeCliSkillArgument(rawSkillName: string): string;
5
5
  export declare function collectSkillMarkdownFiles(dirPath: string, baseDir?: string, result?: string[]): string[];
6
6
  export declare function readInstallState(): InstallState;
7
7
  export declare function writeInstallState(state: InstallState): void;
8
- export declare function updateInstallState(skillName: string, repoPath: string, installDir: string, action: 'install' | 'update', requestedVersion?: string): Promise<void>;
8
+ export declare function updateInstallState(skillName: string, repoPath: string, installDir: string, action: 'install' | 'update', requestedVersion?: string, version?: string): Promise<void>;
9
9
  export declare function removeInstallState(skillName: string): void;
10
10
  export declare function copyDirectoryRecursive(sourceDir: string, targetDir: string): void;
11
11
  export declare function replaceDirectoryAtomically(sourceDir: string, targetDir: string): void;