@myrialabs/clopen 0.4.4 → 0.4.6
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.
- package/backend/auth/permissions.ts +15 -1
- package/backend/database/migrations/044_create_skills_table.ts +29 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/skill-queries.ts +105 -0
- package/backend/engine/adapters/claude/stream.ts +5 -0
- package/backend/engine/adapters/codex/credential.ts +120 -13
- package/backend/engine/adapters/codex/stream.ts +34 -8
- package/backend/engine/adapters/copilot/stream.ts +4 -0
- package/backend/engine/adapters/opencode/stream.ts +4 -0
- package/backend/engine/adapters/qwen/stream.ts +3 -0
- package/backend/engine/docs/lessons-learned.md +54 -50
- package/backend/git/git-service.ts +40 -0
- package/backend/index.ts +10 -1
- package/backend/mcp/README.md +77 -24
- package/backend/mcp/external/config.ts +82 -101
- package/backend/mcp/external/parse.test.ts +190 -0
- package/backend/mcp/external/parse.ts +293 -0
- package/backend/mcp/external/proxy.ts +202 -0
- package/backend/mcp/index.ts +6 -3
- package/backend/mcp/internal/remote-server.ts +103 -55
- package/backend/skills/index.ts +21 -0
- package/backend/skills/marketplace.ts +172 -0
- package/backend/skills/service.ts +245 -0
- package/backend/skills/spec.ts +214 -0
- package/backend/skills/store.ts +99 -0
- package/backend/skills/sync.ts +187 -0
- package/backend/snapshot/gitignore.ts +230 -7
- package/backend/snapshot/helpers.ts +34 -10
- package/backend/ws/files/read.ts +10 -1
- package/backend/ws/git/branch-name.ts +20 -4
- package/backend/ws/git/branch.ts +66 -11
- package/backend/ws/git/commit-message.ts +18 -3
- package/backend/ws/git/commit.ts +50 -16
- package/backend/ws/git/conflict.ts +47 -5
- package/backend/ws/git/diff.ts +38 -4
- package/backend/ws/git/log.ts +22 -2
- package/backend/ws/git/remote.ts +82 -33
- package/backend/ws/git/staging.ts +39 -9
- package/backend/ws/git/status.ts +52 -0
- package/backend/ws/index.ts +5 -1
- package/backend/ws/mcp/crud.ts +30 -1
- package/backend/ws/skills/catalog.ts +79 -0
- package/backend/ws/skills/crud.ts +123 -0
- package/backend/ws/skills/index.ts +15 -0
- package/backend/ws/snapshot/timeline.ts +1 -1
- package/dist/assets/main-BkMrek4_.css +1 -0
- package/dist/assets/{main-AqTMkV9D.js → main-TYNK6Orl.js} +332 -295
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/git.ts +20 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-DJf71Zum.css +0 -1
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill service — orchestrates the DB metadata table and the on-disk canonical
|
|
3
|
+
* store for the Settings → Skills CRUD surface. The WS layer calls these; they
|
|
4
|
+
* keep the `skills` table and `{clopenDir}/skills/<slug>/` in lockstep.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { skillQueries, type SkillRow, type SkillSource } from '$backend/database/queries';
|
|
8
|
+
import { debug } from '$shared/utils/logger';
|
|
9
|
+
import {
|
|
10
|
+
parseSkillMd,
|
|
11
|
+
serializeSkillMd,
|
|
12
|
+
validateFrontmatter,
|
|
13
|
+
slugifySkillName,
|
|
14
|
+
type ParsedSkill
|
|
15
|
+
} from './spec';
|
|
16
|
+
import {
|
|
17
|
+
writeSkillMd,
|
|
18
|
+
writeSkillResource,
|
|
19
|
+
readSkillMd,
|
|
20
|
+
deleteSkillDir,
|
|
21
|
+
skillDirExists
|
|
22
|
+
} from './store';
|
|
23
|
+
import { fetchMarketplaceSkill } from './marketplace';
|
|
24
|
+
|
|
25
|
+
/** A skill as surfaced to the Settings UI (DB metadata + on-disk presence). */
|
|
26
|
+
export interface SkillDTO {
|
|
27
|
+
id: number;
|
|
28
|
+
slug: string;
|
|
29
|
+
name: string;
|
|
30
|
+
description: string;
|
|
31
|
+
source: SkillSource;
|
|
32
|
+
marketplaceRef: string | null;
|
|
33
|
+
version: string | null;
|
|
34
|
+
license: string | null;
|
|
35
|
+
enabled: boolean;
|
|
36
|
+
/** False when the DB row exists but its SKILL.md is missing on disk. */
|
|
37
|
+
present: boolean;
|
|
38
|
+
createdAt: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A previewed skill parsed from pasted/imported SKILL.md text. */
|
|
42
|
+
export interface ParsedSkillPreview {
|
|
43
|
+
name: string;
|
|
44
|
+
description: string;
|
|
45
|
+
license: string | null;
|
|
46
|
+
body: string;
|
|
47
|
+
warnings: string[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function toDTO(row: SkillRow, present: boolean): SkillDTO {
|
|
51
|
+
return {
|
|
52
|
+
id: row.id,
|
|
53
|
+
slug: row.slug,
|
|
54
|
+
name: row.name,
|
|
55
|
+
description: row.description,
|
|
56
|
+
source: row.source,
|
|
57
|
+
marketplaceRef: row.marketplace_ref,
|
|
58
|
+
version: row.version,
|
|
59
|
+
license: row.license,
|
|
60
|
+
enabled: row.is_enabled === 1,
|
|
61
|
+
present,
|
|
62
|
+
createdAt: row.created_at
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Derive a slug that doesn't collide with an existing skill. */
|
|
67
|
+
function uniqueSlug(base: string): string {
|
|
68
|
+
const root = slugifySkillName(base);
|
|
69
|
+
if (!skillQueries.getBySlug(root)) return root;
|
|
70
|
+
for (let i = 2; i < 1000; i++) {
|
|
71
|
+
const candidate = `${root}-${i}`.slice(0, 64).replace(/-+$/g, '');
|
|
72
|
+
if (!skillQueries.getBySlug(candidate)) return candidate;
|
|
73
|
+
}
|
|
74
|
+
return slugifySkillName(`${root}-${Date.now()}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Throw a single combined error if frontmatter validation fails. */
|
|
78
|
+
function assertValid(skill: ParsedSkill, expectedName: string): void {
|
|
79
|
+
const result = validateFrontmatter(skill.frontmatter, expectedName);
|
|
80
|
+
if (!result.valid) throw new Error(result.errors.join(' '));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const skillService = {
|
|
84
|
+
async list(): Promise<SkillDTO[]> {
|
|
85
|
+
const rows = skillQueries.getAll();
|
|
86
|
+
const presence = await Promise.all(rows.map(r => skillDirExists(r.slug)));
|
|
87
|
+
return rows.map((row, i) => toDTO(row, presence[i]));
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
async get(id: number): Promise<{ skill: SkillDTO; body: string } | null> {
|
|
91
|
+
const row = skillQueries.getById(id);
|
|
92
|
+
if (!row) return null;
|
|
93
|
+
const raw = await readSkillMd(row.slug);
|
|
94
|
+
const body = raw ? parseSkillMd(raw).body : '';
|
|
95
|
+
return { skill: toDTO(row, raw !== null), body };
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
/** Create a skill from in-app editor fields (name + description + markdown body). */
|
|
99
|
+
async create(input: { name: string; description: string; body: string; license?: string | null }): Promise<SkillDTO> {
|
|
100
|
+
const slug = uniqueSlug(input.name);
|
|
101
|
+
const skill: ParsedSkill = {
|
|
102
|
+
frontmatter: {
|
|
103
|
+
name: slug,
|
|
104
|
+
description: input.description.trim(),
|
|
105
|
+
license: input.license?.trim() || undefined,
|
|
106
|
+
extra: {}
|
|
107
|
+
},
|
|
108
|
+
body: input.body
|
|
109
|
+
};
|
|
110
|
+
assertValid(skill, slug);
|
|
111
|
+
await writeSkillMd(slug, serializeSkillMd(skill));
|
|
112
|
+
const row = skillQueries.insert({
|
|
113
|
+
slug,
|
|
114
|
+
name: input.name.trim(),
|
|
115
|
+
description: input.description.trim(),
|
|
116
|
+
source: 'custom',
|
|
117
|
+
license: input.license?.trim() || null
|
|
118
|
+
});
|
|
119
|
+
debug.log('skills', `📦 Created skill: ${slug}`);
|
|
120
|
+
return toDTO(row, true);
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
/** Update an existing skill's editable fields and rewrite its SKILL.md. */
|
|
124
|
+
async update(id: number, input: { name: string; description: string; body: string; license?: string | null }): Promise<SkillDTO> {
|
|
125
|
+
const row = skillQueries.getById(id);
|
|
126
|
+
if (!row) throw new Error('Skill not found');
|
|
127
|
+
// `name` (frontmatter) must keep matching the folder slug — only the
|
|
128
|
+
// display name, description, license and body are editable here.
|
|
129
|
+
const skill: ParsedSkill = {
|
|
130
|
+
frontmatter: {
|
|
131
|
+
name: row.slug,
|
|
132
|
+
description: input.description.trim(),
|
|
133
|
+
license: input.license?.trim() || undefined,
|
|
134
|
+
extra: {}
|
|
135
|
+
},
|
|
136
|
+
body: input.body
|
|
137
|
+
};
|
|
138
|
+
assertValid(skill, row.slug);
|
|
139
|
+
await writeSkillMd(row.slug, serializeSkillMd(skill));
|
|
140
|
+
skillQueries.updateMeta(id, input.name.trim(), input.description.trim(), input.license?.trim() || null);
|
|
141
|
+
debug.log('skills', `🔧 Updated skill: ${row.slug}`);
|
|
142
|
+
return toDTO(skillQueries.getById(id)!, true);
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Parse pasted/uploaded SKILL.md text into a reviewable preview. Nothing is
|
|
147
|
+
* persisted — the UI shows the result, then calls `import` to commit it.
|
|
148
|
+
*/
|
|
149
|
+
parsePreview(raw: string): ParsedSkillPreview {
|
|
150
|
+
const parsed = parseSkillMd(raw);
|
|
151
|
+
const warnings: string[] = [];
|
|
152
|
+
const result = validateFrontmatter(parsed.frontmatter, undefined);
|
|
153
|
+
if (!result.valid) warnings.push(...result.errors);
|
|
154
|
+
return {
|
|
155
|
+
name: parsed.frontmatter.name,
|
|
156
|
+
description: parsed.frontmatter.description,
|
|
157
|
+
license: parsed.frontmatter.license ?? null,
|
|
158
|
+
body: parsed.body,
|
|
159
|
+
warnings
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
/** Persist a skill from pasted/uploaded SKILL.md text. */
|
|
164
|
+
async import(raw: string): Promise<SkillDTO> {
|
|
165
|
+
const parsed = parseSkillMd(raw);
|
|
166
|
+
const displayName = parsed.frontmatter.name || 'Imported skill';
|
|
167
|
+
const slug = uniqueSlug(parsed.frontmatter.name || displayName);
|
|
168
|
+
// Re-key the frontmatter `name` to the de-duped slug so it matches the folder.
|
|
169
|
+
parsed.frontmatter.name = slug;
|
|
170
|
+
assertValid(parsed, slug);
|
|
171
|
+
await writeSkillMd(slug, serializeSkillMd(parsed));
|
|
172
|
+
const row = skillQueries.insert({
|
|
173
|
+
slug,
|
|
174
|
+
name: displayName,
|
|
175
|
+
description: parsed.frontmatter.description,
|
|
176
|
+
source: 'imported',
|
|
177
|
+
license: parsed.frontmatter.license ?? null
|
|
178
|
+
});
|
|
179
|
+
debug.log('skills', `📥 Imported skill: ${slug}`);
|
|
180
|
+
return toDTO(row, true);
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Fetch and parse a marketplace skill for review before install — nothing is
|
|
185
|
+
* persisted. Powers the install modal's prefilled detail form.
|
|
186
|
+
*/
|
|
187
|
+
async previewInstall(ref: string): Promise<{ name: string; description: string; license: string | null; body: string }> {
|
|
188
|
+
const fetched = await fetchMarketplaceSkill(ref);
|
|
189
|
+
const parsed = parseSkillMd(fetched.skillMd);
|
|
190
|
+
return {
|
|
191
|
+
name: parsed.frontmatter.name || ref.split(/[:/]/).pop() || 'Skill',
|
|
192
|
+
description: parsed.frontmatter.description,
|
|
193
|
+
license: parsed.frontmatter.license ?? null,
|
|
194
|
+
body: parsed.body
|
|
195
|
+
};
|
|
196
|
+
},
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Install a skill from a marketplace provider: download its SKILL.md (+ any
|
|
200
|
+
* bundled resources), validate against the spec, and persist it under a
|
|
201
|
+
* de-duped slug with `source: 'marketplace'`. Optional `override` fields (from
|
|
202
|
+
* the install modal) replace the fetched name/description/license/body.
|
|
203
|
+
*/
|
|
204
|
+
async install(ref: string, override?: { name?: string; description?: string; license?: string | null; body?: string }): Promise<SkillDTO> {
|
|
205
|
+
const fetched = await fetchMarketplaceSkill(ref);
|
|
206
|
+
const parsed = parseSkillMd(fetched.skillMd);
|
|
207
|
+
if (override?.description !== undefined) parsed.frontmatter.description = override.description.trim();
|
|
208
|
+
if (override?.license !== undefined) parsed.frontmatter.license = override.license?.trim() || undefined;
|
|
209
|
+
if (override?.body !== undefined) parsed.body = override.body;
|
|
210
|
+
const displayName = override?.name?.trim() || parsed.frontmatter.name || ref.split(/[:/]/).pop() || 'Skill';
|
|
211
|
+
const slug = uniqueSlug(parsed.frontmatter.name || displayName);
|
|
212
|
+
parsed.frontmatter.name = slug;
|
|
213
|
+
assertValid(parsed, slug);
|
|
214
|
+
await writeSkillMd(slug, serializeSkillMd(parsed));
|
|
215
|
+
for (const resource of fetched.resources) {
|
|
216
|
+
await writeSkillResource(slug, resource.path, resource.content);
|
|
217
|
+
}
|
|
218
|
+
const row = skillQueries.insert({
|
|
219
|
+
slug,
|
|
220
|
+
name: displayName,
|
|
221
|
+
description: parsed.frontmatter.description,
|
|
222
|
+
source: 'marketplace',
|
|
223
|
+
marketplaceRef: ref,
|
|
224
|
+
version: parsed.frontmatter.metadata?.version ?? null,
|
|
225
|
+
license: parsed.frontmatter.license ?? null
|
|
226
|
+
});
|
|
227
|
+
debug.log('skills', `📥 Installed marketplace skill: ${slug} (${ref})`);
|
|
228
|
+
return toDTO(row, true);
|
|
229
|
+
},
|
|
230
|
+
|
|
231
|
+
toggle(id: number, enabled: boolean): SkillDTO {
|
|
232
|
+
const row = skillQueries.getById(id);
|
|
233
|
+
if (!row) throw new Error('Skill not found');
|
|
234
|
+
skillQueries.setEnabled(id, enabled);
|
|
235
|
+
return toDTO(skillQueries.getById(id)!, true);
|
|
236
|
+
},
|
|
237
|
+
|
|
238
|
+
async remove(id: number): Promise<void> {
|
|
239
|
+
const row = skillQueries.getById(id);
|
|
240
|
+
if (!row) throw new Error('Skill not found');
|
|
241
|
+
await deleteSkillDir(row.slug);
|
|
242
|
+
skillQueries.remove(id);
|
|
243
|
+
debug.log('skills', `🗑️ Deleted skill: ${row.slug}`);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SKILL.md format — parse, serialize, validate.
|
|
3
|
+
*
|
|
4
|
+
* Implements the open Agent Skills spec (https://agentskills.io/specification):
|
|
5
|
+
* a skill is a folder whose `SKILL.md` carries YAML frontmatter (`name`,
|
|
6
|
+
* `description`, optional `license`/`compatibility`/`metadata`/`allowed-tools`)
|
|
7
|
+
* followed by a Markdown instruction body.
|
|
8
|
+
*
|
|
9
|
+
* We deliberately hand-roll a tiny frontmatter parser rather than pull in a YAML
|
|
10
|
+
* dependency: the spec's frontmatter surface is small and flat (one nested
|
|
11
|
+
* `metadata` map), and skills we author in-app are written back in this exact
|
|
12
|
+
* shape. Unknown keys are preserved verbatim so a round-trip of an imported
|
|
13
|
+
* skill never drops fields the spec tells runtimes to ignore.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface SkillFrontmatter {
|
|
17
|
+
name: string;
|
|
18
|
+
description: string;
|
|
19
|
+
license?: string;
|
|
20
|
+
compatibility?: string;
|
|
21
|
+
allowedTools?: string;
|
|
22
|
+
metadata?: Record<string, string>;
|
|
23
|
+
/** Frontmatter keys we don't model, kept verbatim for lossless round-trips. */
|
|
24
|
+
extra: Record<string, string>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ParsedSkill {
|
|
28
|
+
frontmatter: SkillFrontmatter;
|
|
29
|
+
/** The Markdown instruction body after the frontmatter fence. */
|
|
30
|
+
body: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
34
|
+
|
|
35
|
+
/** Strip matching single/double quotes from a scalar value. */
|
|
36
|
+
function unquote(value: string): string {
|
|
37
|
+
const v = value.trim();
|
|
38
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
|
|
39
|
+
return v.slice(1, -1);
|
|
40
|
+
}
|
|
41
|
+
return v;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Quote a scalar for YAML output only when it could otherwise be misparsed. */
|
|
45
|
+
function quoteIfNeeded(value: string): string {
|
|
46
|
+
if (value === '') return '""';
|
|
47
|
+
// Quote when the value contains characters that change YAML meaning, or has
|
|
48
|
+
// leading/trailing whitespace that would be trimmed on re-parse.
|
|
49
|
+
if (/[:#"'\n]|^[\s]|[\s]$|^[[{>|&*!%@`]/.test(value)) {
|
|
50
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Split a SKILL.md into its frontmatter block and body. Returns null when the
|
|
57
|
+
* leading `---` fence is missing or unterminated.
|
|
58
|
+
*/
|
|
59
|
+
function splitFrontmatter(raw: string): { fm: string; body: string } | null {
|
|
60
|
+
const text = raw.replace(/^\uFEFF/, "");
|
|
61
|
+
const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/.exec(text);
|
|
62
|
+
if (!match) return null;
|
|
63
|
+
return { fm: match[1], body: (match[2] ?? '').replace(/^\r?\n/, '') };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Parse a SKILL.md document. Throws with a readable message on malformed input. */
|
|
67
|
+
export function parseSkillMd(raw: string): ParsedSkill {
|
|
68
|
+
const split = splitFrontmatter(raw);
|
|
69
|
+
if (!split) {
|
|
70
|
+
throw new Error('SKILL.md must start with a YAML frontmatter block fenced by --- lines.');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const fm: SkillFrontmatter = { name: '', description: '', extra: {}, metadata: undefined };
|
|
74
|
+
const metadata: Record<string, string> = {};
|
|
75
|
+
|
|
76
|
+
const lines = split.fm.split(/\r?\n/);
|
|
77
|
+
let i = 0;
|
|
78
|
+
while (i < lines.length) {
|
|
79
|
+
const line = lines[i];
|
|
80
|
+
if (line.trim() === '' || line.trim().startsWith('#')) { i++; continue; }
|
|
81
|
+
|
|
82
|
+
// Nested `metadata:` block — indented `key: value` entries.
|
|
83
|
+
if (/^metadata:\s*$/.test(line)) {
|
|
84
|
+
i++;
|
|
85
|
+
while (i < lines.length && /^\s+\S/.test(lines[i])) {
|
|
86
|
+
const m = /^\s+([A-Za-z0-9_-]+):\s*(.*)$/.exec(lines[i]);
|
|
87
|
+
if (m) metadata[m[1]] = unquote(m[2]);
|
|
88
|
+
i++;
|
|
89
|
+
}
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
|
|
94
|
+
if (!m) { i++; continue; }
|
|
95
|
+
const key = m[1];
|
|
96
|
+
let value: string;
|
|
97
|
+
|
|
98
|
+
// Block scalar (`|` literal / `>` folded, with optional chomping). The value
|
|
99
|
+
// lives on the following more-indented lines; both styles are folded to a
|
|
100
|
+
// single line so the value stays one canonical, serialize-safe string.
|
|
101
|
+
if (/^[|>][+-]?\s*$/.test(m[2].trim())) {
|
|
102
|
+
i++;
|
|
103
|
+
let baseIndent: number | null = null;
|
|
104
|
+
const collected: string[] = [];
|
|
105
|
+
while (i < lines.length) {
|
|
106
|
+
const l = lines[i];
|
|
107
|
+
if (l.trim() === '') { collected.push(''); i++; continue; }
|
|
108
|
+
const indent = l.length - l.replace(/^\s+/, '').length;
|
|
109
|
+
if (indent === 0) break; // dedented back to a top-level key
|
|
110
|
+
if (baseIndent === null) baseIndent = indent;
|
|
111
|
+
collected.push(l.slice(baseIndent));
|
|
112
|
+
i++;
|
|
113
|
+
}
|
|
114
|
+
value = collected.join(' ').replace(/\s+/g, ' ').trim();
|
|
115
|
+
} else {
|
|
116
|
+
value = unquote(m[2]);
|
|
117
|
+
i++;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
switch (key) {
|
|
121
|
+
case 'name': fm.name = value; break;
|
|
122
|
+
case 'description': fm.description = value; break;
|
|
123
|
+
case 'license': fm.license = value; break;
|
|
124
|
+
case 'compatibility': fm.compatibility = value; break;
|
|
125
|
+
case 'allowed-tools': fm.allowedTools = value; break;
|
|
126
|
+
default: fm.extra[key] = value;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (Object.keys(metadata).length > 0) fm.metadata = metadata;
|
|
131
|
+
return { frontmatter: fm, body: split.body };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Serialize a parsed skill back into a canonical SKILL.md document. */
|
|
135
|
+
export function serializeSkillMd(skill: ParsedSkill): string {
|
|
136
|
+
const { frontmatter: fm, body } = skill;
|
|
137
|
+
const lines: string[] = ['---'];
|
|
138
|
+
lines.push(`name: ${quoteIfNeeded(fm.name)}`);
|
|
139
|
+
lines.push(`description: ${quoteIfNeeded(fm.description)}`);
|
|
140
|
+
if (fm.license) lines.push(`license: ${quoteIfNeeded(fm.license)}`);
|
|
141
|
+
if (fm.compatibility) lines.push(`compatibility: ${quoteIfNeeded(fm.compatibility)}`);
|
|
142
|
+
if (fm.allowedTools) lines.push(`allowed-tools: ${quoteIfNeeded(fm.allowedTools)}`);
|
|
143
|
+
for (const [k, v] of Object.entries(fm.extra)) lines.push(`${k}: ${quoteIfNeeded(v)}`);
|
|
144
|
+
if (fm.metadata && Object.keys(fm.metadata).length > 0) {
|
|
145
|
+
lines.push('metadata:');
|
|
146
|
+
for (const [k, v] of Object.entries(fm.metadata)) lines.push(` ${k}: ${quoteIfNeeded(v)}`);
|
|
147
|
+
}
|
|
148
|
+
lines.push('---');
|
|
149
|
+
const trimmedBody = body.replace(/^\s+/, '').replace(/\s+$/, '');
|
|
150
|
+
return `${lines.join('\n')}\n\n${trimmedBody}\n`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface SkillValidationResult {
|
|
154
|
+
valid: boolean;
|
|
155
|
+
errors: string[];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Validate frontmatter against the spec. `expectedName` (when given) enforces
|
|
160
|
+
* the spec rule that `name` must match the parent folder — we pass the slug.
|
|
161
|
+
*/
|
|
162
|
+
export function validateFrontmatter(fm: SkillFrontmatter, expectedName?: string): SkillValidationResult {
|
|
163
|
+
const errors: string[] = [];
|
|
164
|
+
|
|
165
|
+
if (!fm.name) {
|
|
166
|
+
errors.push('`name` is required.');
|
|
167
|
+
} else {
|
|
168
|
+
if (fm.name.length > 64) errors.push('`name` must be at most 64 characters.');
|
|
169
|
+
if (!NAME_RE.test(fm.name)) {
|
|
170
|
+
errors.push('`name` may only contain lowercase letters, numbers, and single hyphens (no leading, trailing, or consecutive hyphens).');
|
|
171
|
+
}
|
|
172
|
+
if (expectedName && fm.name !== expectedName) {
|
|
173
|
+
errors.push(`\`name\` (${fm.name}) must match the skill folder name (${expectedName}).`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!fm.description || !fm.description.trim()) {
|
|
178
|
+
errors.push('`description` is required and must describe what the skill does and when to use it.');
|
|
179
|
+
} else if (fm.description.length > 1024) {
|
|
180
|
+
errors.push('`description` must be at most 1024 characters.');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (fm.compatibility && fm.compatibility.length > 500) {
|
|
184
|
+
errors.push('`compatibility` must be at most 500 characters.');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Angle brackets in frontmatter can inject unintended system-prompt content.
|
|
188
|
+
for (const [label, value] of [
|
|
189
|
+
['name', fm.name],
|
|
190
|
+
['description', fm.description],
|
|
191
|
+
['license', fm.license],
|
|
192
|
+
['compatibility', fm.compatibility]
|
|
193
|
+
] as const) {
|
|
194
|
+
if (value && /[<>]/.test(value)) errors.push(`\`${label}\` must not contain angle brackets (< or >).`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return { valid: errors.length === 0, errors };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Normalise an arbitrary string into a spec-valid skill slug: lowercase, ASCII
|
|
202
|
+
* alphanumerics and single hyphens, no leading/trailing hyphen, capped at 64.
|
|
203
|
+
*/
|
|
204
|
+
export function slugifySkillName(input: string): string {
|
|
205
|
+
const slug = input
|
|
206
|
+
.toLowerCase()
|
|
207
|
+
.normalize('NFKD')
|
|
208
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
209
|
+
.replace(/^-+|-+$/g, '')
|
|
210
|
+
.replace(/-{2,}/g, '-')
|
|
211
|
+
.slice(0, 64)
|
|
212
|
+
.replace(/-+$/g, '');
|
|
213
|
+
return slug || 'skill';
|
|
214
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical skill store — the single source of truth on disk.
|
|
3
|
+
*
|
|
4
|
+
* Every managed skill lives in its own folder under `{clopenDir}/skills/<slug>/`
|
|
5
|
+
* with a `SKILL.md` (and optionally bundled `scripts/`, `references/`,
|
|
6
|
+
* `assets/`). This is engine-agnostic: the `syncSkills` layer mirrors enabled
|
|
7
|
+
* skills from here into each engine's native location (or injects a synthetic
|
|
8
|
+
* preamble) at stream start. The DB (`skills` table) only tracks metadata and
|
|
9
|
+
* the enable/disable toggle.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { join } from 'path';
|
|
13
|
+
import { mkdir, readdir, rm, stat, writeFile, readFile, cp } from 'node:fs/promises';
|
|
14
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
15
|
+
import { debug } from '$shared/utils/logger';
|
|
16
|
+
|
|
17
|
+
/** Root of the canonical store: `{clopenDir}/skills`. */
|
|
18
|
+
export function getSkillsRootDir(): string {
|
|
19
|
+
return join(getClopenDir(), 'skills');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Absolute path to a single skill's folder. */
|
|
23
|
+
export function getSkillDir(slug: string): string {
|
|
24
|
+
return join(getSkillsRootDir(), slug);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Absolute path to a skill's SKILL.md. */
|
|
28
|
+
export function getSkillMdPath(slug: string): string {
|
|
29
|
+
return join(getSkillDir(slug), 'SKILL.md');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function pathExists(path: string): Promise<boolean> {
|
|
33
|
+
try {
|
|
34
|
+
await stat(path);
|
|
35
|
+
return true;
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Whether a skill folder exists on disk. */
|
|
42
|
+
export function skillDirExists(slug: string): Promise<boolean> {
|
|
43
|
+
return pathExists(getSkillDir(slug));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Read a skill's SKILL.md content, or null when the file is absent. */
|
|
47
|
+
export async function readSkillMd(slug: string): Promise<string | null> {
|
|
48
|
+
const path = getSkillMdPath(slug);
|
|
49
|
+
if (!(await pathExists(path))) return null;
|
|
50
|
+
return readFile(path, 'utf8');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Create or overwrite a skill's SKILL.md (creating the folder as needed). */
|
|
54
|
+
export async function writeSkillMd(slug: string, content: string): Promise<void> {
|
|
55
|
+
const dir = getSkillDir(slug);
|
|
56
|
+
await mkdir(dir, { recursive: true });
|
|
57
|
+
await writeFile(getSkillMdPath(slug), content, 'utf8');
|
|
58
|
+
debug.log('skills', `💾 Wrote SKILL.md for ${slug}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Write an additional bundled file (e.g. `scripts/run.py`) relative to the
|
|
63
|
+
* skill folder. The relative path is sanitised to stay inside the folder.
|
|
64
|
+
*/
|
|
65
|
+
export async function writeSkillResource(slug: string, relativePath: string, content: string | Uint8Array): Promise<void> {
|
|
66
|
+
const safeRel = relativePath.replace(/\\/g, '/').replace(/(^|\/)\.\.(\/|$)/g, '/').replace(/^\/+/, '');
|
|
67
|
+
if (!safeRel || safeRel === 'SKILL.md') return;
|
|
68
|
+
const dest = join(getSkillDir(slug), safeRel);
|
|
69
|
+
await mkdir(join(dest, '..'), { recursive: true });
|
|
70
|
+
await writeFile(dest, content);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Permanently delete a skill folder and everything in it. */
|
|
74
|
+
export async function deleteSkillDir(slug: string): Promise<void> {
|
|
75
|
+
await rm(getSkillDir(slug), { recursive: true, force: true });
|
|
76
|
+
debug.log('skills', `🗑️ Removed skill folder ${slug}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** List skill folder names that physically exist in the canonical store. */
|
|
80
|
+
export async function listSkillSlugsOnDisk(): Promise<string[]> {
|
|
81
|
+
const root = getSkillsRootDir();
|
|
82
|
+
if (!(await pathExists(root))) return [];
|
|
83
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
84
|
+
return entries.filter(e => e.isDirectory() && !e.name.startsWith('.')).map(e => e.name);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Copy a skill folder from the canonical store into a destination skills
|
|
89
|
+
* directory (used by the native-engine sync). Removes any stale copy first so
|
|
90
|
+
* renames/edits never leave orphaned files behind.
|
|
91
|
+
*/
|
|
92
|
+
export async function copySkillInto(slug: string, destSkillsDir: string): Promise<void> {
|
|
93
|
+
const src = getSkillDir(slug);
|
|
94
|
+
if (!(await pathExists(src))) return;
|
|
95
|
+
const dest = join(destSkillsDir, slug);
|
|
96
|
+
await rm(dest, { recursive: true, force: true });
|
|
97
|
+
await mkdir(destSkillsDir, { recursive: true });
|
|
98
|
+
await cp(src, dest, { recursive: true });
|
|
99
|
+
}
|