@workskills/getskill 1.1.10 → 1.2.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, PublishOptions, PublishResult, 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>;
@@ -3,6 +3,7 @@ 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;
@@ -14,42 +15,48 @@ const fs_1 = __importDefault(require("fs"));
14
15
  const path_1 = __importDefault(require("path"));
15
16
  const config_1 = require("./config");
16
17
  const logger_1 = __importDefault(require("./logger"));
17
- const publish_registry_1 = require("./publish-registry");
18
+ const network_1 = require("./network");
18
19
  const state_1 = require("./state");
19
20
  const skill_validator_1 = require("./skill-validator");
20
21
  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 });
22
+ const unzip_1 = require("./unzip");
23
+ function assertVersionAvailable(entry, requestedVersion) {
24
+ if (!requestedVersion) {
25
+ return;
30
26
  }
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;
27
+ if (requestedVersion !== entry.version) {
28
+ throw new Error(`技能 ${entry.id} 不提供版本 ${requestedVersion},站点当前仅提供最新版本 ${entry.version}`);
42
29
  }
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);
30
+ }
31
+ async function fetchSkillToCache(skillName, options = {}) {
32
+ const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
33
+ const entry = await (0, network_1.findSkillIndexEntry)(normalizedSkillName);
34
+ if (!entry) {
35
+ throw new Error(`技能不存在: ${normalizedSkillName},请先使用 getskill search <关键词> 查询可用技能`);
48
36
  }
49
- else {
50
- await (0, system_1.executeCommand)(`git clone --depth 1 "${gitUrl}" "${localSkillName}"`, cacheDir);
37
+ const requestedVersion = options.version?.trim();
38
+ assertVersionAvailable(entry, requestedVersion);
39
+ const cacheDir = (0, config_1.getSkillsCacheDirectory)();
40
+ (0, system_1.ensureDirectoryExists)(cacheDir);
41
+ const localSkillName = (0, state_1.normalizeSkillName)(normalizedSkillName);
42
+ const cachePath = path_1.default.join(cacheDir, localSkillName);
43
+ const zipPath = path_1.default.join(cacheDir, `${localSkillName}.zip`);
44
+ const downloadUrl = (0, network_1.getSkillPackageUrl)(entry);
45
+ logger_1.default.info(`下载技能包: ${downloadUrl}`);
46
+ const receivedBytes = await (0, network_1.downloadFile)(downloadUrl, zipPath);
47
+ logger_1.default.info(`下载完成 (${receivedBytes} bytes),正在解压...`);
48
+ if (fs_1.default.existsSync(cachePath)) {
49
+ fs_1.default.rmSync(cachePath, { recursive: true, force: true });
51
50
  }
52
- logger_1.default.info(`仓库克隆成功: ${repoPath}`);
51
+ (0, system_1.ensureDirectoryExists)(cachePath);
52
+ (0, unzip_1.extractZip)(zipPath, cachePath);
53
+ fs_1.default.rmSync(zipPath, { force: true });
54
+ const repoPath = (0, unzip_1.resolveSkillRoot)(cachePath);
55
+ logger_1.default.info(`技能包已解压: ${repoPath}`);
56
+ return { repoPath, cachePath, entry };
57
+ }
58
+ async function cloneOrUpdateRepo(skillName, options = {}) {
59
+ const { repoPath } = await fetchSkillToCache(skillName, options);
53
60
  return repoPath;
54
61
  }
55
62
  async function restartOpenClawGateway() {
@@ -69,47 +76,62 @@ async function downloadSkill(skillName, options = {}) {
69
76
  logger_1.default.info(`下载技能: ${skillName}...`);
70
77
  const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
71
78
  const requestedVersion = options.version?.trim();
72
- const repoPath = await cloneOrUpdateRepo(normalizedSkillName, {
79
+ const { repoPath, entry } = await fetchSkillToCache(normalizedSkillName, {
73
80
  version: requestedVersion
74
81
  });
75
82
  const copiedFiles = (0, state_1.copySkillFiles)(repoPath, normalizedSkillName);
76
- await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'install', requestedVersion);
83
+ await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'install', requestedVersion, entry.version);
84
+ logger_1.default.info(`技能 ${normalizedSkillName} (v${entry.version}) 安装成功!`);
77
85
  return {
78
86
  skillName: normalizedSkillName,
79
87
  repoPath,
80
88
  files: copiedFiles,
81
- requestedVersion: requestedVersion || null
89
+ requestedVersion: requestedVersion || null,
90
+ version: entry.version
82
91
  };
83
92
  }
84
93
  async function updateSkill(skillName, options = {}) {
85
94
  const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
86
95
  const requestedVersion = options.version?.trim();
87
96
  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
- });
97
+ const entry = await (0, network_1.findSkillIndexEntry)(normalizedSkillName);
98
+ if (!entry) {
99
+ throw new Error(`技能不存在: ${normalizedSkillName},无法更新`);
96
100
  }
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);
101
+ assertVersionAvailable(entry, requestedVersion);
102
+ const localSkillName = (0, state_1.normalizeSkillName)(normalizedSkillName);
103
+ const skillDir = path_1.default.join((0, config_1.getSkillsDirectory)(), localSkillName);
104
+ const cachePath = path_1.default.join((0, config_1.getSkillsCacheDirectory)(), localSkillName);
105
+ const record = (0, state_1.readInstallState)().skills[localSkillName];
106
+ if (record &&
107
+ record.version &&
108
+ record.version === entry.version &&
109
+ fs_1.default.existsSync(skillDir)) {
110
+ logger_1.default.info(`技能 ${normalizedSkillName} 已是最新版本 (${entry.version}),无需更新`);
111
+ return {
112
+ skillName: normalizedSkillName,
113
+ repoPath: record.repoPath || cachePath,
114
+ files: [skillDir],
115
+ requestedVersion: requestedVersion || null,
116
+ version: entry.version,
117
+ upToDate: true
118
+ };
100
119
  }
101
- else {
102
- await (0, system_1.executeCommand)('git pull', repoPath);
120
+ if (record) {
121
+ logger_1.default.info(`发现新版本: ${record.version || 'unknown'} -> ${entry.version}`);
103
122
  }
104
- logger_1.default.info('Git 仓库已更新');
123
+ const { repoPath } = await fetchSkillToCache(normalizedSkillName, {
124
+ version: requestedVersion
125
+ });
105
126
  const copiedFiles = (0, state_1.copySkillFiles)(repoPath, normalizedSkillName);
106
- await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'update', requestedVersion);
127
+ await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'update', requestedVersion, entry.version);
107
128
  logger_1.default.info(`技能 ${normalizedSkillName} 更新成功!`);
108
129
  return {
109
130
  skillName: normalizedSkillName,
110
131
  repoPath,
111
132
  files: copiedFiles,
112
- requestedVersion: requestedVersion || null
133
+ requestedVersion: requestedVersion || null,
134
+ version: entry.version
113
135
  };
114
136
  }
115
137
  async function updateAllSkills() {
@@ -183,19 +205,7 @@ async function publishSkill(skillPath, options = {}) {
183
205
  throw new Error(`SKILL.md 校验失败:\n- ${validation.errors.join('\n- ')}`);
184
206
  }
185
207
  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
208
  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
209
  const gitDirPath = path_1.default.join(resolvedSkillPath, '.git');
200
210
  if (!fs_1.default.existsSync(gitDirPath)) {
201
211
  logger_1.default.info('未检测到 Git 仓库,正在初始化...');
@@ -204,33 +214,22 @@ async function publishSkill(skillPath, options = {}) {
204
214
  const branch = options.branch?.trim() || 'main';
205
215
  const commitMessage = options.message?.trim() || 'chore: publish skill via getskill';
206
216
  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
217
  if (options.repoUrl?.trim()) {
216
218
  currentRemoteUrl = options.repoUrl.trim();
217
219
  }
218
- else if (!currentRemoteUrl) {
219
- if (!authSession) {
220
- throw new Error('当前未登录,无法自动创建远程仓库');
220
+ else {
221
+ try {
222
+ const { stdout } = await (0, system_1.executeCommand)('git remote get-url origin', resolvedSkillPath);
223
+ currentRemoteUrl = stdout.trim();
224
+ }
225
+ catch {
226
+ currentRemoteUrl = '';
221
227
  }
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
228
  }
232
229
  if (!currentRemoteUrl) {
233
- throw new Error('无法确定发布目标仓库地址');
230
+ throw new Error('getskill.work 已迁移为 Cloudflare 静态托管,官方技能库不再支持通过 CLI 注册/推送。\n' +
231
+ '请使用 --repo <git-url> 发布到你自己的 Git 仓库(如 GitHub),\n' +
232
+ '或将技能提交到 https://github.com/work-skills 组织下的技能仓库以收录进官方站点。');
234
233
  }
235
234
  try {
236
235
  await (0, system_1.executeCommand)(`git remote set-url origin "${quoteShellArg(currentRemoteUrl)}"`, resolvedSkillPath);
@@ -238,15 +237,8 @@ async function publishSkill(skillPath, options = {}) {
238
237
  catch {
239
238
  await (0, system_1.executeCommand)(`git remote add origin "${quoteShellArg(currentRemoteUrl)}"`, resolvedSkillPath);
240
239
  }
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
240
  await (0, system_1.executeCommand)(`git checkout -B "${quoteShellArg(branch)}"`, resolvedSkillPath);
249
- await ensureLocalGitIdentity(resolvedSkillPath, authSession?.username || options.username, authSession?.email || options.email || null);
241
+ await ensureLocalGitIdentity(resolvedSkillPath, options.username, options.email || null);
250
242
  await (0, system_1.executeCommand)('git add .', resolvedSkillPath);
251
243
  let committed = false;
252
244
  try {
@@ -264,15 +256,13 @@ async function publishSkill(skillPath, options = {}) {
264
256
  throw error;
265
257
  }
266
258
  }
267
- await (0, system_1.executeCommand)(`git push -u origin "${quoteShellArg(branch)}"`, resolvedSkillPath, pushEnv ? { env: pushEnv } : undefined);
259
+ await (0, system_1.executeCommand)(`git push -u origin "${quoteShellArg(branch)}"`, resolvedSkillPath);
268
260
  logger_1.default.info(`已发布技能目录: ${resolvedSkillPath}`);
269
261
  return {
270
262
  skillPath: resolvedSkillPath,
271
263
  remoteUrl: currentRemoteUrl,
272
264
  branch,
273
265
  committed,
274
- repositoryName: repoName,
275
- createdRemoteRepo,
276
- authMode: authSession?.mode || 'not-required'
266
+ repositoryName: repoName
277
267
  };
278
268
  }
@@ -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;
package/dist/lib/state.js CHANGED
@@ -91,11 +91,10 @@ function writeInstallState(state) {
91
91
  (0, system_1.ensureDirectoryExists)(path_1.default.dirname(stateFilePath));
92
92
  fs_1.default.writeFileSync(stateFilePath, JSON.stringify(state, null, 2), 'utf8');
93
93
  }
94
- async function updateInstallState(skillName, repoPath, installDir, action, requestedVersion) {
94
+ async function updateInstallState(skillName, repoPath, installDir, action, requestedVersion, version) {
95
95
  const localSkillName = normalizeSkillName(skillName);
96
96
  const remoteSkillPath = getRemoteSkillPath(skillName);
97
97
  const now = new Date().toISOString();
98
- const commitHash = await (0, system_1.getGitCommitHash)(repoPath);
99
98
  const state = readInstallState();
100
99
  const previous = state.skills[localSkillName];
101
100
  state.skills[localSkillName] = {
@@ -107,8 +106,9 @@ async function updateInstallState(skillName, repoPath, installDir, action, reque
107
106
  lastAction: action,
108
107
  installedAt: previous?.installedAt || now,
109
108
  updatedAt: now,
110
- gitCommitHash: commitHash || previous?.gitCommitHash || null,
111
- requestedVersion: requestedVersion ?? previous?.requestedVersion ?? null
109
+ gitCommitHash: previous?.gitCommitHash || null,
110
+ requestedVersion: requestedVersion ?? previous?.requestedVersion ?? null,
111
+ version: version ?? previous?.version ?? null
112
112
  };
113
113
  writeInstallState(state);
114
114
  }