@workskills/getskill 1.1.8 → 1.1.10

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.
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.cloneOrUpdateRepo = cloneOrUpdateRepo;
7
+ exports.restartOpenClawGateway = restartOpenClawGateway;
8
+ exports.downloadSkill = downloadSkill;
9
+ exports.updateSkill = updateSkill;
10
+ exports.updateAllSkills = updateAllSkills;
11
+ exports.uninstallSkill = uninstallSkill;
12
+ exports.publishSkill = publishSkill;
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const config_1 = require("./config");
16
+ const logger_1 = __importDefault(require("./logger"));
17
+ const publish_registry_1 = require("./publish-registry");
18
+ const state_1 = require("./state");
19
+ const skill_validator_1 = require("./skill-validator");
20
+ 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;
42
+ }
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);
48
+ }
49
+ else {
50
+ await (0, system_1.executeCommand)(`git clone --depth 1 "${gitUrl}" "${localSkillName}"`, cacheDir);
51
+ }
52
+ logger_1.default.info(`仓库克隆成功: ${repoPath}`);
53
+ return repoPath;
54
+ }
55
+ async function restartOpenClawGateway() {
56
+ const restartCommand = 'openclaw gateway restart';
57
+ logger_1.default.info(`尝试执行: ${restartCommand}`);
58
+ try {
59
+ await (0, system_1.executeCommand)(restartCommand);
60
+ logger_1.default.info('OpenClaw Gateway 重启成功,新技能应已生效。');
61
+ }
62
+ catch (error) {
63
+ const message = error instanceof Error ? error.message : String(error);
64
+ logger_1.default.warn('自动重启 OpenClaw Gateway 失败,请手动执行: openclaw gateway restart');
65
+ logger_1.default.warn(`失败原因: ${message}`);
66
+ }
67
+ }
68
+ async function downloadSkill(skillName, options = {}) {
69
+ logger_1.default.info(`下载技能: ${skillName}...`);
70
+ const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
71
+ const requestedVersion = options.version?.trim();
72
+ const repoPath = await cloneOrUpdateRepo(normalizedSkillName, {
73
+ version: requestedVersion
74
+ });
75
+ const copiedFiles = (0, state_1.copySkillFiles)(repoPath, normalizedSkillName);
76
+ await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'install', requestedVersion);
77
+ return {
78
+ skillName: normalizedSkillName,
79
+ repoPath,
80
+ files: copiedFiles,
81
+ requestedVersion: requestedVersion || null
82
+ };
83
+ }
84
+ async function updateSkill(skillName, options = {}) {
85
+ const normalizedSkillName = (0, state_1.normalizeCliSkillArgument)(skillName);
86
+ const requestedVersion = options.version?.trim();
87
+ 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
+ });
96
+ }
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);
100
+ }
101
+ else {
102
+ await (0, system_1.executeCommand)('git pull', repoPath);
103
+ }
104
+ logger_1.default.info('Git 仓库已更新');
105
+ const copiedFiles = (0, state_1.copySkillFiles)(repoPath, normalizedSkillName);
106
+ await (0, state_1.updateInstallState)(normalizedSkillName, repoPath, copiedFiles[0], 'update', requestedVersion);
107
+ logger_1.default.info(`技能 ${normalizedSkillName} 更新成功!`);
108
+ return {
109
+ skillName: normalizedSkillName,
110
+ repoPath,
111
+ files: copiedFiles,
112
+ requestedVersion: requestedVersion || null
113
+ };
114
+ }
115
+ async function updateAllSkills() {
116
+ const installedSkills = (0, state_1.listInstalledSkillNames)();
117
+ const results = [];
118
+ for (const skillName of installedSkills) {
119
+ try {
120
+ const result = await updateSkill(skillName);
121
+ results.push({ skillName, ok: true, result });
122
+ }
123
+ catch (error) {
124
+ const message = error instanceof Error ? error.message : String(error);
125
+ results.push({ skillName, ok: false, error: message });
126
+ }
127
+ }
128
+ return results;
129
+ }
130
+ async function uninstallSkill(skillName, options = {}) {
131
+ const result = (0, state_1.removeInstalledSkill)(skillName, options);
132
+ logger_1.default.info(`已卸载技能目录: ${result.skillDir}`);
133
+ if (result.removedCache) {
134
+ logger_1.default.info(`已移除缓存仓库: ${result.repoPath}`);
135
+ }
136
+ return result;
137
+ }
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
+ }
@@ -0,0 +1,4 @@
1
+ import type { SkillValidationResult } from './types';
2
+ export declare function sanitizeRepositoryName(input: string): string;
3
+ export declare function validateSkillMarkdownContent(content: string): SkillValidationResult;
4
+ export declare function validateSkillDirectory(skillPath: string): SkillValidationResult;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.sanitizeRepositoryName = sanitizeRepositoryName;
7
+ exports.validateSkillMarkdownContent = validateSkillMarkdownContent;
8
+ exports.validateSkillDirectory = validateSkillDirectory;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const REQUIRED_FRONTMATTER_KEYS = [
12
+ 'name',
13
+ 'description',
14
+ 'license',
15
+ 'compatibility'
16
+ ];
17
+ const REQUIRED_METADATA_KEYS = ['author', 'version', 'category'];
18
+ const REQUIRED_SECTIONS = ['## 何时使用此 Skill', '## 指令'];
19
+ function cleanYamlValue(value) {
20
+ if (!value) {
21
+ return undefined;
22
+ }
23
+ return value.trim().replace(/^['"]|['"]$/g, '');
24
+ }
25
+ function extractFrontMatter(content) {
26
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
27
+ if (!match) {
28
+ return null;
29
+ }
30
+ return {
31
+ frontMatter: match[1],
32
+ body: match[2]
33
+ };
34
+ }
35
+ function readTopLevelValue(frontMatter, key) {
36
+ const match = frontMatter.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'));
37
+ return cleanYamlValue(match?.[1]);
38
+ }
39
+ function readMetadataValue(frontMatter, key) {
40
+ const match = frontMatter.match(new RegExp(`^\\s+${key}:\\s*(.+)$`, 'm'));
41
+ return cleanYamlValue(match?.[1]);
42
+ }
43
+ function sanitizeRepositoryName(input) {
44
+ return input
45
+ .trim()
46
+ .replace(/\.git$/i, '')
47
+ .replace(/[^a-zA-Z0-9._-]+/g, '-')
48
+ .replace(/-{2,}/g, '-')
49
+ .replace(/^-+|-+$/g, '')
50
+ .toLowerCase();
51
+ }
52
+ function validateSkillMarkdownContent(content) {
53
+ const errors = [];
54
+ const metadata = {};
55
+ const parsed = extractFrontMatter(content);
56
+ if (!parsed) {
57
+ return {
58
+ valid: false,
59
+ errors: ['SKILL.md 必须包含 YAML front matter(使用 --- 包裹)'],
60
+ metadata
61
+ };
62
+ }
63
+ for (const key of REQUIRED_FRONTMATTER_KEYS) {
64
+ const value = readTopLevelValue(parsed.frontMatter, key);
65
+ if (!value) {
66
+ errors.push(`front matter 缺少必填字段: ${key}`);
67
+ continue;
68
+ }
69
+ metadata[key] = value;
70
+ }
71
+ if (!/^metadata:\s*$/m.test(parsed.frontMatter)) {
72
+ errors.push('front matter 缺少 metadata 区块');
73
+ }
74
+ for (const key of REQUIRED_METADATA_KEYS) {
75
+ const value = readMetadataValue(parsed.frontMatter, key);
76
+ if (!value) {
77
+ errors.push(`metadata 缺少必填字段: ${key}`);
78
+ continue;
79
+ }
80
+ metadata[key] = value;
81
+ }
82
+ if (!/^#\s+.+$/m.test(parsed.body)) {
83
+ errors.push('正文缺少一级标题(例如 # My Skill)');
84
+ }
85
+ for (const section of REQUIRED_SECTIONS) {
86
+ if (!parsed.body.includes(section)) {
87
+ errors.push(`正文缺少必填章节: ${section}`);
88
+ }
89
+ }
90
+ return {
91
+ valid: errors.length === 0,
92
+ errors,
93
+ metadata
94
+ };
95
+ }
96
+ function validateSkillDirectory(skillPath) {
97
+ const skillFilePath = path_1.default.join(skillPath, 'SKILL.md');
98
+ if (!fs_1.default.existsSync(skillFilePath)) {
99
+ return {
100
+ valid: false,
101
+ errors: ['publish 目录中缺少 SKILL.md'],
102
+ metadata: {}
103
+ };
104
+ }
105
+ const content = fs_1.default.readFileSync(skillFilePath, 'utf8');
106
+ return validateSkillMarkdownContent(content);
107
+ }
@@ -0,0 +1,18 @@
1
+ import type { InstallState, InstalledSkillInfo, RemoveInstalledSkillResult } from './types';
2
+ export declare function normalizeSkillName(skillName: string): string;
3
+ export declare function getRemoteSkillPath(skillName: string): string;
4
+ export declare function normalizeCliSkillArgument(rawSkillName: string): string;
5
+ export declare function collectSkillMarkdownFiles(dirPath: string, baseDir?: string, result?: string[]): string[];
6
+ export declare function readInstallState(): InstallState;
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>;
9
+ export declare function removeInstallState(skillName: string): void;
10
+ export declare function copyDirectoryRecursive(sourceDir: string, targetDir: string): void;
11
+ export declare function replaceDirectoryAtomically(sourceDir: string, targetDir: string): void;
12
+ export declare function copySkillFiles(repoPath: string, skillName: string): string[];
13
+ export declare function listLocalSkills(): string[];
14
+ export declare function listInstalledSkillNames(): string[];
15
+ export declare function getInstalledSkillInfo(skillName: string): InstalledSkillInfo;
16
+ export declare function removeInstalledSkill(skillName: string, options?: {
17
+ removeCache?: boolean;
18
+ }): RemoveInstalledSkillResult;
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.normalizeSkillName = normalizeSkillName;
7
+ exports.getRemoteSkillPath = getRemoteSkillPath;
8
+ exports.normalizeCliSkillArgument = normalizeCliSkillArgument;
9
+ exports.collectSkillMarkdownFiles = collectSkillMarkdownFiles;
10
+ exports.readInstallState = readInstallState;
11
+ exports.writeInstallState = writeInstallState;
12
+ exports.updateInstallState = updateInstallState;
13
+ exports.removeInstallState = removeInstallState;
14
+ exports.copyDirectoryRecursive = copyDirectoryRecursive;
15
+ exports.replaceDirectoryAtomically = replaceDirectoryAtomically;
16
+ exports.copySkillFiles = copySkillFiles;
17
+ exports.listLocalSkills = listLocalSkills;
18
+ exports.listInstalledSkillNames = listInstalledSkillNames;
19
+ exports.getInstalledSkillInfo = getInstalledSkillInfo;
20
+ exports.removeInstalledSkill = removeInstalledSkill;
21
+ const fs_1 = __importDefault(require("fs"));
22
+ const path_1 = __importDefault(require("path"));
23
+ const config_1 = require("./config");
24
+ const logger_1 = __importDefault(require("./logger"));
25
+ const system_1 = require("./system");
26
+ function normalizeSkillName(skillName) {
27
+ return skillName.replace(/^skills\//, '').replace(/[\\/]/g, '_');
28
+ }
29
+ function getRemoteSkillPath(skillName) {
30
+ return skillName.includes('/') ? skillName : `skills/${skillName}`;
31
+ }
32
+ function normalizeCliSkillArgument(rawSkillName) {
33
+ if (!rawSkillName || typeof rawSkillName !== 'string') {
34
+ throw new Error('请提供技能名称,例如: getskill install pdf-extract 或 getskill install skills/xejrax_pdf-extract');
35
+ }
36
+ const value = rawSkillName.trim();
37
+ if (!value) {
38
+ throw new Error('技能名称不能为空');
39
+ }
40
+ if (/^https?:\/\//i.test(value) || value.endsWith('.git')) {
41
+ throw new Error('请传入技能名称而不是 Git URL,例如: getskill install pdf-extract');
42
+ }
43
+ return value.replace(/^\/+|\/+$/g, '');
44
+ }
45
+ function collectSkillMarkdownFiles(dirPath, baseDir = dirPath, result = []) {
46
+ const entries = fs_1.default.readdirSync(dirPath, { withFileTypes: true });
47
+ entries.forEach((entry) => {
48
+ if (entry.name === '.git') {
49
+ return;
50
+ }
51
+ const fullPath = path_1.default.join(dirPath, entry.name);
52
+ const relativePath = path_1.default.relative(baseDir, fullPath);
53
+ if (entry.isDirectory()) {
54
+ collectSkillMarkdownFiles(fullPath, baseDir, result);
55
+ return;
56
+ }
57
+ if (!entry.isFile()) {
58
+ return;
59
+ }
60
+ const isMarkdown = entry.name.toLowerCase().endsWith('.md');
61
+ const isReadme = entry.name.toLowerCase().startsWith('readme');
62
+ if (isMarkdown && !isReadme) {
63
+ result.push(relativePath);
64
+ }
65
+ });
66
+ return result;
67
+ }
68
+ function readInstallState() {
69
+ const stateFilePath = (0, config_1.getStateFilePath)();
70
+ if (!fs_1.default.existsSync(stateFilePath)) {
71
+ return { skills: {} };
72
+ }
73
+ try {
74
+ const content = fs_1.default.readFileSync(stateFilePath, 'utf8');
75
+ const parsed = JSON.parse(content);
76
+ if (!parsed || typeof parsed !== 'object') {
77
+ return { skills: {} };
78
+ }
79
+ return {
80
+ skills: parsed.skills && typeof parsed.skills === 'object'
81
+ ? parsed.skills
82
+ : {}
83
+ };
84
+ }
85
+ catch {
86
+ return { skills: {} };
87
+ }
88
+ }
89
+ function writeInstallState(state) {
90
+ const stateFilePath = (0, config_1.getStateFilePath)();
91
+ (0, system_1.ensureDirectoryExists)(path_1.default.dirname(stateFilePath));
92
+ fs_1.default.writeFileSync(stateFilePath, JSON.stringify(state, null, 2), 'utf8');
93
+ }
94
+ async function updateInstallState(skillName, repoPath, installDir, action, requestedVersion) {
95
+ const localSkillName = normalizeSkillName(skillName);
96
+ const remoteSkillPath = getRemoteSkillPath(skillName);
97
+ const now = new Date().toISOString();
98
+ const commitHash = await (0, system_1.getGitCommitHash)(repoPath);
99
+ const state = readInstallState();
100
+ const previous = state.skills[localSkillName];
101
+ state.skills[localSkillName] = {
102
+ inputSkillName: skillName,
103
+ localSkillName,
104
+ remoteSkillPath,
105
+ repoPath,
106
+ installDir,
107
+ lastAction: action,
108
+ installedAt: previous?.installedAt || now,
109
+ updatedAt: now,
110
+ gitCommitHash: commitHash || previous?.gitCommitHash || null,
111
+ requestedVersion: requestedVersion ?? previous?.requestedVersion ?? null
112
+ };
113
+ writeInstallState(state);
114
+ }
115
+ function removeInstallState(skillName) {
116
+ const state = readInstallState();
117
+ const localSkillName = normalizeSkillName(skillName);
118
+ if (state.skills[localSkillName]) {
119
+ delete state.skills[localSkillName];
120
+ writeInstallState(state);
121
+ }
122
+ }
123
+ function copyDirectoryRecursive(sourceDir, targetDir) {
124
+ (0, system_1.ensureDirectoryExists)(targetDir);
125
+ const entries = fs_1.default.readdirSync(sourceDir, { withFileTypes: true });
126
+ entries.forEach((entry) => {
127
+ if (entry.name === '.git') {
128
+ return;
129
+ }
130
+ const sourcePath = path_1.default.join(sourceDir, entry.name);
131
+ const targetPath = path_1.default.join(targetDir, entry.name);
132
+ const stat = fs_1.default.lstatSync(sourcePath);
133
+ if (stat.isSymbolicLink()) {
134
+ logger_1.default.warn(`跳过符号链接: ${sourcePath}`);
135
+ return;
136
+ }
137
+ if (entry.isDirectory()) {
138
+ copyDirectoryRecursive(sourcePath, targetPath);
139
+ return;
140
+ }
141
+ if (entry.isFile()) {
142
+ if (stat.size > config_1.MAX_COPY_FILE_SIZE_BYTES) {
143
+ logger_1.default.warn(`跳过超大文件 (${config_1.MAX_COPY_FILE_SIZE_BYTES} bytes): ${sourcePath}`);
144
+ return;
145
+ }
146
+ fs_1.default.copyFileSync(sourcePath, targetPath);
147
+ }
148
+ });
149
+ }
150
+ function replaceDirectoryAtomically(sourceDir, targetDir) {
151
+ const parentDir = path_1.default.dirname(targetDir);
152
+ const dirName = path_1.default.basename(targetDir);
153
+ const tempDir = path_1.default.join(parentDir, `.${dirName}.tmp-${process.pid}-${Date.now()}`);
154
+ const backupDir = path_1.default.join(parentDir, `.${dirName}.bak-${process.pid}-${Date.now()}`);
155
+ (0, system_1.ensureDirectoryExists)(parentDir);
156
+ copyDirectoryRecursive(sourceDir, tempDir);
157
+ try {
158
+ if (fs_1.default.existsSync(targetDir)) {
159
+ fs_1.default.renameSync(targetDir, backupDir);
160
+ }
161
+ fs_1.default.renameSync(tempDir, targetDir);
162
+ if (fs_1.default.existsSync(backupDir)) {
163
+ fs_1.default.rmSync(backupDir, { recursive: true, force: true });
164
+ }
165
+ }
166
+ catch (error) {
167
+ if (fs_1.default.existsSync(tempDir)) {
168
+ fs_1.default.rmSync(tempDir, { recursive: true, force: true });
169
+ }
170
+ if (!fs_1.default.existsSync(targetDir) && fs_1.default.existsSync(backupDir)) {
171
+ fs_1.default.renameSync(backupDir, targetDir);
172
+ }
173
+ throw error;
174
+ }
175
+ }
176
+ function copySkillFiles(repoPath, skillName) {
177
+ const skillsDir = (0, config_1.getSkillsDirectory)();
178
+ (0, system_1.ensureDirectoryExists)(skillsDir);
179
+ const localSkillName = normalizeSkillName(skillName);
180
+ const sourceSkillFiles = collectSkillMarkdownFiles(repoPath);
181
+ if (sourceSkillFiles.length === 0) {
182
+ throw new Error('在仓库中未找到技能 .md 文件');
183
+ }
184
+ const targetSkillDir = path_1.default.join(skillsDir, localSkillName);
185
+ replaceDirectoryAtomically(repoPath, targetSkillDir);
186
+ const installedSkillFiles = collectSkillMarkdownFiles(targetSkillDir);
187
+ if (installedSkillFiles.length === 0) {
188
+ throw new Error('复制后技能目录校验失败:未发现技能 .md 文件');
189
+ }
190
+ logger_1.default.info(`已复制技能目录: ${repoPath} -> ${targetSkillDir}`);
191
+ return [targetSkillDir];
192
+ }
193
+ function listLocalSkills() {
194
+ const skillsDir = (0, config_1.getSkillsDirectory)();
195
+ if (!fs_1.default.existsSync(skillsDir)) {
196
+ logger_1.default.info('技能目录不存在');
197
+ return [];
198
+ }
199
+ return fs_1.default
200
+ .readdirSync(skillsDir, { withFileTypes: true })
201
+ .filter((entry) => entry.isDirectory())
202
+ .map((entry) => entry.name);
203
+ }
204
+ function listInstalledSkillNames() {
205
+ const state = readInstallState();
206
+ const stateNames = Object.values(state.skills)
207
+ .map((item) => item.inputSkillName || item.localSkillName)
208
+ .filter(Boolean);
209
+ if (stateNames.length > 0) {
210
+ return [...new Set(stateNames)];
211
+ }
212
+ return listLocalSkills();
213
+ }
214
+ function getInstalledSkillInfo(skillName) {
215
+ const normalizedSkillName = normalizeCliSkillArgument(skillName);
216
+ const localSkillName = normalizeSkillName(normalizedSkillName);
217
+ const state = readInstallState();
218
+ const record = state.skills[localSkillName] || null;
219
+ const skillDir = path_1.default.join((0, config_1.getSkillsDirectory)(), localSkillName);
220
+ const repoPath = path_1.default.join((0, config_1.getSkillsCacheDirectory)(), localSkillName);
221
+ return {
222
+ skillName: normalizedSkillName,
223
+ localSkillName,
224
+ installed: fs_1.default.existsSync(skillDir),
225
+ cached: fs_1.default.existsSync(repoPath),
226
+ skillDir,
227
+ repoPath,
228
+ state: record
229
+ };
230
+ }
231
+ function removeInstalledSkill(skillName, options = {}) {
232
+ const normalizedSkillName = normalizeCliSkillArgument(skillName);
233
+ const localSkillName = normalizeSkillName(normalizedSkillName);
234
+ const removeCache = options.removeCache !== false;
235
+ const skillDir = path_1.default.join((0, config_1.getSkillsDirectory)(), localSkillName);
236
+ const repoPath = path_1.default.join((0, config_1.getSkillsCacheDirectory)(), localSkillName);
237
+ let removedInstall = false;
238
+ let removedCache = false;
239
+ if (fs_1.default.existsSync(skillDir)) {
240
+ fs_1.default.rmSync(skillDir, { recursive: true, force: true });
241
+ removedInstall = true;
242
+ }
243
+ if (removeCache && fs_1.default.existsSync(repoPath)) {
244
+ fs_1.default.rmSync(repoPath, { recursive: true, force: true });
245
+ removedCache = true;
246
+ }
247
+ removeInstallState(normalizedSkillName);
248
+ return {
249
+ skillName: normalizedSkillName,
250
+ localSkillName,
251
+ removedInstall,
252
+ removedCache,
253
+ skillDir,
254
+ repoPath
255
+ };
256
+ }
@@ -0,0 +1,17 @@
1
+ import type { CommandOutput } from './types';
2
+ export declare function ensureDirectoryExists(dirPath: string): void;
3
+ export declare function executeCommand(command: string, cwd?: string, options?: {
4
+ env?: NodeJS.ProcessEnv;
5
+ }): Promise<CommandOutput>;
6
+ export declare function checkGitInstalled(): Promise<boolean>;
7
+ export declare function getGitDownloadUrl(): string | null;
8
+ export declare function downloadFile(url: string, destPath: string): Promise<string>;
9
+ export declare function installGit(): Promise<void>;
10
+ export declare function ensureGitInstalled(): Promise<true>;
11
+ export declare function isInteractiveTerminal(): boolean;
12
+ export declare function promptForInput(question: string, options?: {
13
+ defaultValue?: string;
14
+ required?: boolean;
15
+ secret?: boolean;
16
+ }): Promise<string>;
17
+ export declare function getGitCommitHash(repoPath: string): Promise<string | null>;