@sundial-ai/cli 0.0.1

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 (108) hide show
  1. package/DEV.md +58 -0
  2. package/README.md +30 -0
  3. package/dist/commands/add.d.ts +13 -0
  4. package/dist/commands/add.d.ts.map +1 -0
  5. package/dist/commands/add.js +111 -0
  6. package/dist/commands/add.js.map +1 -0
  7. package/dist/commands/config.d.ts +5 -0
  8. package/dist/commands/config.d.ts.map +1 -0
  9. package/dist/commands/config.js +40 -0
  10. package/dist/commands/config.js.map +1 -0
  11. package/dist/commands/list.d.ts +5 -0
  12. package/dist/commands/list.d.ts.map +1 -0
  13. package/dist/commands/list.js +53 -0
  14. package/dist/commands/list.js.map +1 -0
  15. package/dist/commands/remove.d.ts +13 -0
  16. package/dist/commands/remove.d.ts.map +1 -0
  17. package/dist/commands/remove.js +129 -0
  18. package/dist/commands/remove.js.map +1 -0
  19. package/dist/commands/show-dev.d.ts +20 -0
  20. package/dist/commands/show-dev.d.ts.map +1 -0
  21. package/dist/commands/show-dev.js +195 -0
  22. package/dist/commands/show-dev.js.map +1 -0
  23. package/dist/commands/show.d.ts +11 -0
  24. package/dist/commands/show.d.ts.map +1 -0
  25. package/dist/commands/show.js +175 -0
  26. package/dist/commands/show.js.map +1 -0
  27. package/dist/core/agent-detect.d.ts +22 -0
  28. package/dist/core/agent-detect.d.ts.map +1 -0
  29. package/dist/core/agent-detect.js +107 -0
  30. package/dist/core/agent-detect.js.map +1 -0
  31. package/dist/core/agents.d.ts +8 -0
  32. package/dist/core/agents.d.ts.map +1 -0
  33. package/dist/core/agents.js +34 -0
  34. package/dist/core/agents.js.map +1 -0
  35. package/dist/core/config-manager.d.ts +9 -0
  36. package/dist/core/config-manager.d.ts.map +1 -0
  37. package/dist/core/config-manager.js +47 -0
  38. package/dist/core/config-manager.js.map +1 -0
  39. package/dist/core/skill-hash.d.ts +12 -0
  40. package/dist/core/skill-hash.d.ts.map +1 -0
  41. package/dist/core/skill-hash.js +53 -0
  42. package/dist/core/skill-hash.js.map +1 -0
  43. package/dist/core/skill-info.d.ts +34 -0
  44. package/dist/core/skill-info.d.ts.map +1 -0
  45. package/dist/core/skill-info.js +213 -0
  46. package/dist/core/skill-info.js.map +1 -0
  47. package/dist/core/skill-install.d.ts +24 -0
  48. package/dist/core/skill-install.d.ts.map +1 -0
  49. package/dist/core/skill-install.js +123 -0
  50. package/dist/core/skill-install.js.map +1 -0
  51. package/dist/core/skill-source.d.ts +29 -0
  52. package/dist/core/skill-source.d.ts.map +1 -0
  53. package/dist/core/skill-source.js +111 -0
  54. package/dist/core/skill-source.js.map +1 -0
  55. package/dist/index.d.ts +3 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +104 -0
  58. package/dist/index.js.map +1 -0
  59. package/dist/types/index.d.ts +57 -0
  60. package/dist/types/index.d.ts.map +1 -0
  61. package/dist/types/index.js +2 -0
  62. package/dist/types/index.js.map +1 -0
  63. package/dist/utils/fuzzy-match.d.ts +16 -0
  64. package/dist/utils/fuzzy-match.d.ts.map +1 -0
  65. package/dist/utils/fuzzy-match.js +37 -0
  66. package/dist/utils/fuzzy-match.js.map +1 -0
  67. package/dist/utils/prompts.d.ts +16 -0
  68. package/dist/utils/prompts.d.ts.map +1 -0
  69. package/dist/utils/prompts.js +46 -0
  70. package/dist/utils/prompts.js.map +1 -0
  71. package/dist/utils/registry.d.ts +6 -0
  72. package/dist/utils/registry.d.ts.map +1 -0
  73. package/dist/utils/registry.js +14 -0
  74. package/dist/utils/registry.js.map +1 -0
  75. package/package.json +42 -0
  76. package/src/commands/add.ts +136 -0
  77. package/src/commands/config.ts +47 -0
  78. package/src/commands/list.ts +68 -0
  79. package/src/commands/remove.ts +154 -0
  80. package/src/commands/show-dev.ts +223 -0
  81. package/src/commands/show.ts +203 -0
  82. package/src/core/agent-detect.ts +125 -0
  83. package/src/core/agents.ts +40 -0
  84. package/src/core/config-manager.ts +55 -0
  85. package/src/core/skill-hash.ts +61 -0
  86. package/src/core/skill-info.ts +248 -0
  87. package/src/core/skill-install.ts +165 -0
  88. package/src/core/skill-source.ts +125 -0
  89. package/src/index.ts +116 -0
  90. package/src/types/index.ts +64 -0
  91. package/src/utils/fuzzy-match.ts +48 -0
  92. package/src/utils/prompts.ts +54 -0
  93. package/src/utils/registry.ts +16 -0
  94. package/test/README.md +123 -0
  95. package/test/fixtures/multi-skills/skill-one/SKILL.md +8 -0
  96. package/test/fixtures/multi-skills/skill-two/SKILL.md +8 -0
  97. package/test/fixtures/sample-skill/SKILL.md +8 -0
  98. package/test/logs/add-remove.log +108 -0
  99. package/test/logs/config.log +72 -0
  100. package/test/logs/fuzzy-match.log +64 -0
  101. package/test/logs/show.log +110 -0
  102. package/test/run-all.sh +83 -0
  103. package/test/test-add-remove.sh +245 -0
  104. package/test/test-config.sh +208 -0
  105. package/test/test-fuzzy-match.sh +166 -0
  106. package/test/test-show.sh +179 -0
  107. package/tsconfig.json +20 -0
  108. package/vitest.config.ts +15 -0
@@ -0,0 +1,125 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { exec } from 'child_process';
5
+ import { promisify } from 'util';
6
+ import { SUPPORTED_AGENTS } from './agents.js';
7
+ import type { DetectedAgent, AgentConfig } from '../types/index.js';
8
+
9
+ const execAsync = promisify(exec);
10
+
11
+ // Agent folder names to search for
12
+ const AGENT_FOLDER_NAMES = new Set(SUPPORTED_AGENTS.map(a => a.folderName));
13
+
14
+ export async function detectAgentsInDirectory(directory: string, isGlobal: boolean): Promise<DetectedAgent[]> {
15
+ const detected: DetectedAgent[] = [];
16
+
17
+ for (const agent of SUPPORTED_AGENTS) {
18
+ const agentPath = path.join(directory, agent.folderName);
19
+ if (await fs.pathExists(agentPath)) {
20
+ detected.push({
21
+ agent,
22
+ path: agentPath,
23
+ isGlobal
24
+ });
25
+ }
26
+ }
27
+
28
+ return detected;
29
+ }
30
+
31
+ export async function detectLocalAgents(): Promise<DetectedAgent[]> {
32
+ return detectAgentsInDirectory(process.cwd(), false);
33
+ }
34
+
35
+ export async function detectGlobalAgents(): Promise<DetectedAgent[]> {
36
+ return detectAgentsInDirectory(os.homedir(), true);
37
+ }
38
+
39
+ /**
40
+ * Search the entire file system for all agent folders.
41
+ * Uses `find -type d -name` for efficiency.
42
+ */
43
+ export async function detectAllAgentFolders(): Promise<DetectedAgent[]> {
44
+ const results: DetectedAgent[] = [];
45
+ const homeDir = os.homedir();
46
+
47
+ // Build find command: find ~ -type d \( -name ".claude" -o -name ".codex" -o -name ".gemini" \)
48
+ const namePatterns = SUPPORTED_AGENTS.map(a => `-name "${a.folderName}"`).join(' -o ');
49
+ const findCmd = `find "${homeDir}" -type d \\( ${namePatterns} \\) 2>/dev/null`;
50
+
51
+ try {
52
+ const { stdout } = await execAsync(findCmd, { maxBuffer: 10 * 1024 * 1024 });
53
+ const agentPaths = stdout.trim().split('\n').filter(Boolean);
54
+
55
+ for (const agentPath of agentPaths) {
56
+ const folderName = path.basename(agentPath);
57
+ const agent = SUPPORTED_AGENTS.find(a => a.folderName === folderName);
58
+ if (!agent) continue;
59
+
60
+ const isGlobal = path.dirname(agentPath) === homeDir;
61
+ results.push({
62
+ agent,
63
+ path: agentPath,
64
+ isGlobal
65
+ });
66
+ }
67
+ } catch {
68
+ // find command failed - fall back to simple detection
69
+ const [local, global] = await Promise.all([
70
+ detectLocalAgents(),
71
+ detectGlobalAgents()
72
+ ]);
73
+ return [...local, ...global];
74
+ }
75
+
76
+ return results;
77
+ }
78
+
79
+ /**
80
+ * Search the entire file system for agent folders that contain skills.
81
+ * Uses `find` to locate skills directories with content.
82
+ */
83
+ export async function detectAllSkillsFolders(): Promise<DetectedAgent[]> {
84
+ const allAgents = await detectAllAgentFolders();
85
+
86
+ // Filter to only those with skills installed
87
+ const withSkills: DetectedAgent[] = [];
88
+ for (const detected of allAgents) {
89
+ const skillsDir = path.join(detected.path, 'skills');
90
+ if (await fs.pathExists(skillsDir)) {
91
+ const entries = await fs.readdir(skillsDir);
92
+ if (entries.length > 0) {
93
+ withSkills.push(detected);
94
+ }
95
+ }
96
+ }
97
+
98
+ return withSkills;
99
+ }
100
+
101
+ /**
102
+ * Detect agents in local and global directories only (fast).
103
+ */
104
+ export async function detectAllAgents(): Promise<DetectedAgent[]> {
105
+ const [local, global] = await Promise.all([
106
+ detectLocalAgents(),
107
+ detectGlobalAgents()
108
+ ]);
109
+ return [...local, ...global];
110
+ }
111
+
112
+ export function getAgentPath(agent: AgentConfig, isGlobal: boolean): string {
113
+ const baseDir = isGlobal ? os.homedir() : process.cwd();
114
+ return path.join(baseDir, agent.folderName);
115
+ }
116
+
117
+ export function getSkillsPath(agent: AgentConfig, isGlobal: boolean): string {
118
+ return path.join(getAgentPath(agent, isGlobal), 'skills');
119
+ }
120
+
121
+ export async function ensureSkillsDirectory(agent: AgentConfig, isGlobal: boolean): Promise<string> {
122
+ const skillsPath = getSkillsPath(agent, isGlobal);
123
+ await fs.ensureDir(skillsPath);
124
+ return skillsPath;
125
+ }
@@ -0,0 +1,40 @@
1
+ import type { AgentConfig, AgentType } from '../types/index.js';
2
+
3
+ export const SUPPORTED_AGENTS: AgentConfig[] = [
4
+ {
5
+ name: 'Claude Code',
6
+ flag: 'claude',
7
+ folderName: '.claude'
8
+ },
9
+ {
10
+ name: 'Codex',
11
+ flag: 'codex',
12
+ folderName: '.codex'
13
+ },
14
+ {
15
+ name: 'Gemini',
16
+ flag: 'gemini',
17
+ folderName: '.gemini'
18
+ }
19
+ ];
20
+
21
+ export function getAgentByFlag(flag: string): AgentConfig | undefined {
22
+ return SUPPORTED_AGENTS.find(agent => agent.flag === flag);
23
+ }
24
+
25
+ export function getAgentByFolder(folderName: string): AgentConfig | undefined {
26
+ return SUPPORTED_AGENTS.find(agent => agent.folderName === folderName);
27
+ }
28
+
29
+ export function getSupportedAgentsMessage(): string {
30
+ const agentNames = SUPPORTED_AGENTS.map(a => a.name).join(', ');
31
+ return `Currently supported agents: ${agentNames}`;
32
+ }
33
+
34
+ export function isValidAgentType(flag: string): flag is AgentType {
35
+ return SUPPORTED_AGENTS.some(agent => agent.flag === flag);
36
+ }
37
+
38
+ export function getAgentFlags(): string[] {
39
+ return SUPPORTED_AGENTS.map(a => a.flag);
40
+ }
@@ -0,0 +1,55 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import type { SunConfig, AgentType } from '../types/index.js';
5
+
6
+ const CONFIG_DIR = path.join(os.homedir(), '.sun');
7
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
8
+
9
+ const DEFAULT_CONFIG: SunConfig = {
10
+ defaultAgents: [],
11
+ firstRunComplete: false
12
+ };
13
+
14
+ export async function ensureConfigDir(): Promise<void> {
15
+ await fs.ensureDir(CONFIG_DIR);
16
+ }
17
+
18
+ export async function loadConfig(): Promise<SunConfig> {
19
+ try {
20
+ await ensureConfigDir();
21
+ if (await fs.pathExists(CONFIG_FILE)) {
22
+ const content = await fs.readFile(CONFIG_FILE, 'utf-8');
23
+ return { ...DEFAULT_CONFIG, ...JSON.parse(content) };
24
+ }
25
+ } catch {
26
+ // Config doesn't exist or is invalid, return default
27
+ }
28
+ return { ...DEFAULT_CONFIG };
29
+ }
30
+
31
+ export async function saveConfig(config: SunConfig): Promise<void> {
32
+ await ensureConfigDir();
33
+ await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
34
+ }
35
+
36
+ export async function isFirstRun(): Promise<boolean> {
37
+ const config = await loadConfig();
38
+ return !config.firstRunComplete;
39
+ }
40
+
41
+ export async function getDefaultAgents(): Promise<AgentType[]> {
42
+ const config = await loadConfig();
43
+ return config.defaultAgents;
44
+ }
45
+
46
+ export async function setDefaultAgents(agents: AgentType[]): Promise<void> {
47
+ const config = await loadConfig();
48
+ config.defaultAgents = agents;
49
+ config.firstRunComplete = true;
50
+ await saveConfig(config);
51
+ }
52
+
53
+ export function getConfigPath(): string {
54
+ return CONFIG_FILE;
55
+ }
@@ -0,0 +1,61 @@
1
+ import crypto from 'crypto';
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+
5
+ /**
6
+ * Get all files in a directory recursively, sorted for consistency.
7
+ */
8
+ async function getAllFiles(dir: string): Promise<string[]> {
9
+ const files: string[] = [];
10
+
11
+ async function walk(currentDir: string): Promise<void> {
12
+ const entries = await fs.readdir(currentDir, { withFileTypes: true });
13
+
14
+ for (const entry of entries) {
15
+ const fullPath = path.join(currentDir, entry.name);
16
+ if (entry.isDirectory()) {
17
+ await walk(fullPath);
18
+ } else if (entry.isFile()) {
19
+ files.push(fullPath);
20
+ }
21
+ }
22
+ }
23
+
24
+ await walk(dir);
25
+ // Sort for consistent ordering across platforms
26
+ return files.sort();
27
+ }
28
+
29
+ /**
30
+ * Compute a SHA-256 hash of all files in a skill folder.
31
+ * This allows detecting if two skills with the same name have different content.
32
+ *
33
+ * The hash is computed by:
34
+ * 1. Getting all files recursively
35
+ * 2. Sorting them by path for consistency
36
+ * 3. Hashing each file's relative path + content
37
+ * 4. Combining into a final hash
38
+ */
39
+ export async function computeContentHash(skillPath: string): Promise<string> {
40
+ const files = await getAllFiles(skillPath);
41
+
42
+ if (files.length === 0) {
43
+ // Empty folder - return hash of empty string
44
+ return crypto.createHash('sha256').update('').digest('hex').slice(0, 12);
45
+ }
46
+
47
+ const hash = crypto.createHash('sha256');
48
+
49
+ for (const file of files) {
50
+ // Include relative path in hash (so moving files changes the hash)
51
+ const relativePath = path.relative(skillPath, file);
52
+ hash.update(relativePath);
53
+
54
+ // Include file content
55
+ const content = await fs.readFile(file);
56
+ hash.update(content);
57
+ }
58
+
59
+ // Return first 12 chars for readability
60
+ return hash.digest('hex').slice(0, 12);
61
+ }
@@ -0,0 +1,248 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { SUPPORTED_AGENTS } from './agents.js';
5
+ import { computeContentHash } from './skill-hash.js';
6
+ import type { SkillMetadata, SkillInstallation, AgentType } from '../types/index.js';
7
+
8
+ /**
9
+ * Parse YAML-like frontmatter from SKILL.md content.
10
+ * Frontmatter is delimited by --- at start and end.
11
+ * Handles nested metadata field as key-value pairs.
12
+ */
13
+ function parseFrontmatter(content: string): SkillMetadata | null {
14
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
15
+ if (!frontmatterMatch) {
16
+ return null;
17
+ }
18
+
19
+ const lines = frontmatterMatch[1].split('\n');
20
+ let name = '';
21
+ let description = '';
22
+ let license: string | undefined;
23
+ let compatibility: string | undefined;
24
+ let allowedTools: string | undefined;
25
+ const metadata: Record<string, string> = {};
26
+
27
+ let inMetadata = false;
28
+
29
+ for (const line of lines) {
30
+ // Check if we're entering metadata block (indented or explicit)
31
+ if (line.match(/^metadata:\s*$/)) {
32
+ inMetadata = true;
33
+ continue;
34
+ }
35
+
36
+ // If line starts with non-whitespace, we're out of metadata block
37
+ if (inMetadata && line.match(/^\S/)) {
38
+ inMetadata = false;
39
+ }
40
+
41
+ const colonIndex = line.indexOf(':');
42
+ if (colonIndex > 0) {
43
+ const key = line.slice(0, colonIndex).trim();
44
+ let value = line.slice(colonIndex + 1).trim();
45
+
46
+ // Remove surrounding quotes if present
47
+ if ((value.startsWith('"') && value.endsWith('"')) ||
48
+ (value.startsWith("'") && value.endsWith("'"))) {
49
+ value = value.slice(1, -1);
50
+ }
51
+
52
+ if (inMetadata) {
53
+ // Nested under metadata
54
+ metadata[key] = value;
55
+ } else {
56
+ // Top-level fields
57
+ switch (key) {
58
+ case 'name':
59
+ name = value;
60
+ break;
61
+ case 'description':
62
+ description = value;
63
+ break;
64
+ case 'license':
65
+ license = value;
66
+ break;
67
+ case 'compatibility':
68
+ compatibility = value;
69
+ break;
70
+ case 'allowed-tools':
71
+ allowedTools = value;
72
+ break;
73
+ }
74
+ }
75
+ }
76
+ }
77
+
78
+ // name and description are required
79
+ if (!name || !description) {
80
+ return null;
81
+ }
82
+
83
+ return {
84
+ name,
85
+ description,
86
+ license,
87
+ compatibility,
88
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
89
+ allowedTools
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Check if a directory is a valid skill.
95
+ * A valid skill must contain a SKILL.md with required frontmatter (name, description).
96
+ */
97
+ export async function isValidSkillDirectory(dirPath: string): Promise<boolean> {
98
+ const skillMdPath = path.join(dirPath, 'SKILL.md');
99
+
100
+ if (!await fs.pathExists(skillMdPath)) {
101
+ return false;
102
+ }
103
+
104
+ try {
105
+ const content = await fs.readFile(skillMdPath, 'utf-8');
106
+ const metadata = parseFrontmatter(content);
107
+ return metadata !== null;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Find skill directories within a given path by searching recursively for SKILL.md files.
115
+ * A skill is any directory containing a valid SKILL.md file (with name + description).
116
+ */
117
+ export async function findSkillDirectories(searchPath: string): Promise<string[]> {
118
+ const skills: string[] = [];
119
+
120
+ // Recursively find all SKILL.md files
121
+ async function searchRecursively(dir: string): Promise<void> {
122
+ try {
123
+ const entries = await fs.readdir(dir, { withFileTypes: true });
124
+
125
+ for (const entry of entries) {
126
+ const fullPath = path.join(dir, entry.name);
127
+
128
+ if (entry.isFile() && entry.name === 'SKILL.md') {
129
+ // Found a SKILL.md - check if it's valid
130
+ if (await isValidSkillDirectory(dir)) {
131
+ skills.push(dir);
132
+ }
133
+ } else if (entry.isDirectory() && !entry.name.startsWith('.git')) {
134
+ // Skip .git directories but recurse into others
135
+ await searchRecursively(fullPath);
136
+ }
137
+ }
138
+ } catch {
139
+ // Permission denied or other error, skip this directory
140
+ }
141
+ }
142
+
143
+ await searchRecursively(searchPath);
144
+ return skills;
145
+ }
146
+
147
+ /**
148
+ * Read skill metadata from SKILL.md frontmatter.
149
+ * The canonical skill name comes from the frontmatter, not the folder name.
150
+ */
151
+ export async function readSkillMetadata(skillPath: string): Promise<SkillMetadata | null> {
152
+ const skillMdPath = path.join(skillPath, 'SKILL.md');
153
+
154
+ try {
155
+ const content = await fs.readFile(skillMdPath, 'utf-8');
156
+ return parseFrontmatter(content);
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Get the canonical skill name from SKILL.md frontmatter.
164
+ * Returns null if not a valid skill.
165
+ */
166
+ export async function getSkillName(skillPath: string): Promise<string | null> {
167
+ const metadata = await readSkillMetadata(skillPath);
168
+ return metadata?.name || null;
169
+ }
170
+
171
+ /**
172
+ * Find all installations of a skill by name across all agents.
173
+ */
174
+ export async function findSkillInstallations(skillName: string): Promise<SkillInstallation[]> {
175
+ const installations: SkillInstallation[] = [];
176
+
177
+ // Check both local and global for each agent
178
+ const locations = [
179
+ { base: process.cwd(), isGlobal: false },
180
+ { base: os.homedir(), isGlobal: true }
181
+ ];
182
+
183
+ for (const { base, isGlobal } of locations) {
184
+ for (const agent of SUPPORTED_AGENTS) {
185
+ const skillPath = path.join(base, agent.folderName, 'skills', skillName);
186
+
187
+ if (await fs.pathExists(skillPath)) {
188
+ const metadata = await readSkillMetadata(skillPath);
189
+ if (metadata) {
190
+ const contentHash = await computeContentHash(skillPath);
191
+
192
+ installations.push({
193
+ agent: agent.flag as AgentType,
194
+ path: skillPath,
195
+ isGlobal,
196
+ metadata,
197
+ contentHash
198
+ });
199
+ }
200
+ }
201
+ }
202
+ }
203
+
204
+ return installations;
205
+ }
206
+
207
+ /**
208
+ * List all installed skills for a specific agent.
209
+ */
210
+ export async function listSkillsForAgent(
211
+ agentFolderName: string,
212
+ isGlobal: boolean
213
+ ): Promise<string[]> {
214
+ const base = isGlobal ? os.homedir() : process.cwd();
215
+ const skillsDir = path.join(base, agentFolderName, 'skills');
216
+
217
+ if (!await fs.pathExists(skillsDir)) {
218
+ return [];
219
+ }
220
+
221
+ const entries = await fs.readdir(skillsDir, { withFileTypes: true });
222
+ const skills: string[] = [];
223
+
224
+ for (const entry of entries) {
225
+ if (entry.isDirectory()) {
226
+ const skillPath = path.join(skillsDir, entry.name);
227
+ const skillName = await getSkillName(skillPath);
228
+ if (skillName) {
229
+ skills.push(skillName);
230
+ }
231
+ }
232
+ }
233
+
234
+ return skills;
235
+ }
236
+
237
+ /**
238
+ * Check if a skill exists in an agent's folder.
239
+ */
240
+ export async function skillExists(
241
+ skillName: string,
242
+ agentFolderName: string,
243
+ isGlobal: boolean
244
+ ): Promise<boolean> {
245
+ const base = isGlobal ? os.homedir() : process.cwd();
246
+ const skillPath = path.join(base, agentFolderName, 'skills', skillName);
247
+ return (await fs.pathExists(skillPath)) && (await isValidSkillDirectory(skillPath));
248
+ }
@@ -0,0 +1,165 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { execSync } from 'child_process';
5
+ import { getAgentByFlag } from './agents.js';
6
+ import { resolveSkillSource } from './skill-source.js';
7
+ import { findSkillDirectories, readSkillMetadata } from './skill-info.js';
8
+ import type { AgentType, SkillSource } from '../types/index.js';
9
+
10
+ /**
11
+ * Get the destination path for installing a skill.
12
+ * Skill name comes from SKILL.md frontmatter.
13
+ */
14
+ function getSkillDestination(skillName: string, agentFlag: AgentType, isGlobal: boolean): string {
15
+ const agent = getAgentByFlag(agentFlag);
16
+ if (!agent) {
17
+ throw new Error(`Unknown agent: ${agentFlag}`);
18
+ }
19
+
20
+ const base = isGlobal ? os.homedir() : process.cwd();
21
+ return path.join(base, agent.folderName, 'skills', skillName);
22
+ }
23
+
24
+ /**
25
+ * Install a single skill directory to an agent.
26
+ * The skill name is taken from SKILL.md frontmatter (not the folder name).
27
+ * The destination folder will be named after the frontmatter name.
28
+ */
29
+ async function installSkillDirectory(
30
+ skillDir: string,
31
+ agentFlag: AgentType,
32
+ isGlobal: boolean
33
+ ): Promise<string> {
34
+ // Get metadata from SKILL.md frontmatter (name and description are required)
35
+ const metadata = await readSkillMetadata(skillDir);
36
+ if (!metadata) {
37
+ throw new Error(`Invalid skill at "${skillDir}": SKILL.md must have name and description in frontmatter`);
38
+ }
39
+
40
+ const dest = getSkillDestination(metadata.name, agentFlag, isGlobal);
41
+
42
+ // Ensure parent directory exists
43
+ await fs.ensureDir(path.dirname(dest));
44
+
45
+ // Copy the skill folder (folder will be renamed to match frontmatter name)
46
+ await fs.copy(skillDir, dest, { overwrite: true });
47
+
48
+ return metadata.name;
49
+ }
50
+
51
+ /**
52
+ * Install skill(s) from a local path.
53
+ * Checks if path is a skill, otherwise checks direct children for SKILL.md.
54
+ */
55
+ export async function installFromLocal(
56
+ source: SkillSource,
57
+ agentFlag: AgentType,
58
+ isGlobal: boolean
59
+ ): Promise<string[]> {
60
+ const skillDirs = await findSkillDirectories(source.location);
61
+
62
+ if (skillDirs.length === 0) {
63
+ throw new Error(`No skills found in "${source.location}". A skill must contain a SKILL.md file.`);
64
+ }
65
+
66
+ const installedSkills: string[] = [];
67
+ for (const skillDir of skillDirs) {
68
+ const skillName = await installSkillDirectory(skillDir, agentFlag, isGlobal);
69
+ installedSkills.push(skillName);
70
+ }
71
+
72
+ return installedSkills;
73
+ }
74
+
75
+ /**
76
+ * Install skill(s) from GitHub using degit.
77
+ * After downloading, checks if it's a skill or searches direct children for SKILL.md.
78
+ */
79
+ export async function installFromGithub(
80
+ source: SkillSource,
81
+ agentFlag: AgentType,
82
+ isGlobal: boolean
83
+ ): Promise<string[]> {
84
+ // Create a temp directory to download to
85
+ const tempDir = path.join(os.tmpdir(), `sun-install-${Date.now()}`);
86
+
87
+ try {
88
+ // Download using degit
89
+ await fs.ensureDir(tempDir);
90
+ try {
91
+ execSync(`npx degit ${source.location} "${tempDir}"`, {
92
+ stdio: 'pipe'
93
+ });
94
+ } catch (error) {
95
+ const err = error as Error & { stderr?: Buffer };
96
+ const stderr = err.stderr?.toString() || err.message;
97
+ throw new Error(`Failed to download from GitHub: ${stderr}`);
98
+ }
99
+
100
+ // Find skills in downloaded content (checks itself and direct children)
101
+ const skillDirs = await findSkillDirectories(tempDir);
102
+
103
+ if (skillDirs.length === 0) {
104
+ throw new Error(`No skills found in "${source.originalInput}". A skill must contain a SKILL.md file.`);
105
+ }
106
+
107
+ // Install each skill found (name comes from SKILL.md frontmatter)
108
+ const installedSkills: string[] = [];
109
+ for (const skillDir of skillDirs) {
110
+ const skillName = await installSkillDirectory(skillDir, agentFlag, isGlobal);
111
+ installedSkills.push(skillName);
112
+ }
113
+
114
+ return installedSkills;
115
+ } finally {
116
+ // Clean up temp directory
117
+ await fs.remove(tempDir).catch(() => {});
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Install skill(s) from any source to an agent.
123
+ * Returns list of installed skill names.
124
+ */
125
+ export async function installSkill(
126
+ skillInput: string,
127
+ agentFlag: AgentType,
128
+ isGlobal: boolean
129
+ ): Promise<{ skillNames: string[]; source: SkillSource }> {
130
+ const source = resolveSkillSource(skillInput);
131
+
132
+ let skillNames: string[];
133
+
134
+ switch (source.type) {
135
+ case 'local':
136
+ skillNames = await installFromLocal(source, agentFlag, isGlobal);
137
+ break;
138
+ case 'github':
139
+ case 'shortcut':
140
+ skillNames = await installFromGithub(source, agentFlag, isGlobal);
141
+ break;
142
+ default:
143
+ throw new Error(`Unknown source type: ${(source as SkillSource).type}`);
144
+ }
145
+
146
+ return { skillNames, source };
147
+ }
148
+
149
+ /**
150
+ * Remove a skill from an agent.
151
+ */
152
+ export async function removeSkill(
153
+ skillName: string,
154
+ agentFlag: AgentType,
155
+ isGlobal: boolean
156
+ ): Promise<boolean> {
157
+ const dest = getSkillDestination(skillName, agentFlag, isGlobal);
158
+
159
+ if (await fs.pathExists(dest)) {
160
+ await fs.remove(dest);
161
+ return true;
162
+ }
163
+
164
+ return false;
165
+ }