ShtukbaseStandard
package file→ .shtukbase/packages/blueprint-skilled-agent/lib/skills.ts

lib/skills.ts

99 lines, 5.5 KB.

  1. // Skills of a project and what an agent gets from them. A skill is `skills/<id>/SKILL.md` in the Agent Skills
  2. // format (name = id, description = when to use it, the body = the instruction) plus the page fields title and use.
  3. // An agent page with `skills:` (a list of ids or `all`) gets them through its instruction file
  4. // `instructions: /agents/prompts/<agent>.md`, which is built here: the page body, then every skill in full.
  5. // The active skills are also mirrored to `.claude/skills/<id>/SKILL.md` for Claude Code sessions in the project.
  6. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  7. import { join } from 'node:path';
  8. export type Skill = { id: string; name: string; description: string; body: string; active: boolean };
  9. export type Plan = { files: Map<string, string>; mirrors: string[]; problems: { at: string; what: string; fix: string }[] };
  10. export const MARK = '<!-- built by blueprint-skilled-agent; edit skills/ and the agent page, then run: shtuk run blueprint-skilled-agent build -->';
  11. function page(file: string): { fm: any; body: string } {
  12. const t = readFileSync(file, 'utf8');
  13. const m = /^---\n([\s\S]*?)\n---\n?/.exec(t);
  14. if (!m) return { fm: {}, body: t };
  15. let fm: any = {};
  16. try {
  17. fm = (Bun.YAML.parse(m[1]) as any) ?? {};
  18. } catch {
  19. fm = { __bad: true };
  20. }
  21. return { fm, body: t.slice(m[0].length) };
  22. }
  23. const text = (v: unknown): string => (v == null ? '' : String(v)).trim();
  24. export function skillsOf(root: string, problems: Plan['problems']): Skill[] {
  25. const dir = join(root, 'skills');
  26. if (!existsSync(dir)) return [];
  27. const out: Skill[] = [];
  28. for (const id of readdirSync(dir).sort()) {
  29. const f = join(dir, id, 'SKILL.md');
  30. if (!statSync(join(dir, id)).isDirectory()) continue;
  31. const at = `skills/${id}/SKILL.md`;
  32. if (!existsSync(f)) {
  33. problems.push({ at: `skills/${id}`, what: 'the skill folder has no SKILL.md', fix: 'add SKILL.md or remove the folder' });
  34. continue;
  35. }
  36. const { fm, body } = page(f);
  37. if (fm.__bad) {
  38. problems.push({ at, what: 'the head cannot be read as YAML', fix: 'fix the head' });
  39. continue;
  40. }
  41. const name = text(fm.name), description = text(fm.description);
  42. if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(id) || id.length > 64)
  43. problems.push({ at, what: `the folder name "${id}" is not a skill name`, fix: 'lowercase Latin letters, digits and a hyphen, up to 64 characters' });
  44. if (name !== id) problems.push({ at, what: `name "${name || '—'}" does not match the folder "${id}"`, fix: `set name: ${id}` });
  45. if (!description) problems.push({ at, what: 'no description — it is not said when to apply the skill', fix: 'write description: "Use when …"' });
  46. else if (description.length > 1024) problems.push({ at, what: 'description is longer than 1024 characters', fix: 'shorten it' });
  47. if (!body.trim()) problems.push({ at, what: 'no instruction — the page body is empty', fix: 'write what to do' });
  48. out.push({ id, name, description, body: body.trim(), active: text(fm.use) !== 'paused' });
  49. }
  50. return out;
  51. }
  52. const q = (s: string) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, ' ')}"`;
  53. /** What the build writes: the prompt of every agent with skills, the Claude Code mirror of the active skills. */
  54. export function plan(root: string): Plan {
  55. const problems: Plan['problems'] = [];
  56. const skills = skillsOf(root, problems);
  57. const byId = new Map(skills.map((s) => [s.id, s]));
  58. const active = skills.filter((s) => s.active);
  59. const files = new Map<string, string>();
  60. const agents = join(root, 'agents');
  61. for (const f of existsSync(agents) ? readdirSync(agents).filter((x) => x.endsWith('.md')).sort() : []) {
  62. const { fm, body } = page(join(agents, f));
  63. if (fm.skills == null) continue;
  64. const at = `agents/${f}`;
  65. const want = fm.skills === 'all' ? active : (Array.isArray(fm.skills) ? fm.skills : [fm.skills]).map((x: unknown) => {
  66. const id = text(x).replace(/^\/?skills\//, '').replace(/\/(SKILL\.md)?$/, '');
  67. const s = byId.get(id);
  68. if (!s) problems.push({ at, what: `the skill "${id}" is not in /skills`, fix: 'fix the skills of the agent or add the skill' });
  69. else if (!s.active) problems.push({ at, what: `the skill "${id}" is switched off (use: paused)`, fix: 'remove it from the skills of the agent or switch it on' });
  70. return s && s.active ? s : null;
  71. }).filter(Boolean) as Skill[];
  72. const prompt = `/agents/prompts/${f}`;
  73. if (text(fm.instructions) !== prompt) {
  74. problems.push({ at, what: `the instruction of the agent is not ${prompt}: the skills will not reach it`, fix: `set instructions: ${prompt}` });
  75. continue;
  76. }
  77. const parts = [MARK, '', body.trim()];
  78. if (want.length) {
  79. parts.push('', '## Skills', '', 'Below are your skills. Each one says when to apply it. Apply all that fit the task.');
  80. for (const s of want) parts.push('', `### Skill ${s.name}`, '', `Use when: ${s.description}`, '', s.body);
  81. }
  82. files.set(prompt.slice(1), parts.join('\n') + '\n');
  83. }
  84. for (const s of active)
  85. files.set(`.claude/skills/${s.id}/SKILL.md`, `---\nname: ${s.id}\ndescription: ${q(s.description)}\n---\n\n${MARK}\n\n${s.body}\n`);
  86. const mirrorDir = join(root, '.claude', 'skills');
  87. const mirrors = existsSync(mirrorDir) ? readdirSync(mirrorDir).filter((id) => {
  88. const f = join(mirrorDir, id, 'SKILL.md');
  89. return existsSync(f) && readFileSync(f, 'utf8').includes(MARK) && !files.has(`.claude/skills/${id}/SKILL.md`);
  90. }) : [];
  91. return { files, mirrors, problems };
  92. }