@bitget-ai/bitget-agent-skill 3.4.1 → 4.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.
@@ -1,23 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Bitget Skill Installer
3
+ * Bitget Agentic Skill Installer
4
4
  *
5
- * Usage (run explicitly — no postinstall side effects):
6
- * npx bitget-agent-skill # default: uta skill, Claude Code only
7
- * npx bitget-agent-skill --interactive # prompt to choose targets
8
- * npx bitget-agent-skill --target all # install to all supported tools
9
- * npx bitget-agent-skill --target claude # Claude Code only
10
- * npx bitget-agent-skill --target codex # Codex only
11
- * npx bitget-agent-skill --target openclaw # OpenClaw only
12
- * npx bitget-agent-skill --target claude,codex # multiple targets
13
- * npx bitget-agent-skill --skill agentic # install the Agentic (OAuth) skill instead
14
- * npx bitget-agent-skill --skill agentic-connect # first-time cloud MCP connect guide
15
- * npx bitget-agent-skill --skill uta,agentic # install both skills
16
- * npx bitget-agent-skill --skill all # install all skills
5
+ * Copies the `bitget-agentic` skill directory (SKILL.md and its references/)
6
+ * into an AI tool's skills directory. No runtime, no API keys, no network access.
7
+ *
8
+ * Usage:
9
+ * npx @bitget-ai/bitget-agent-skill # Claude Code
10
+ * npx @bitget-ai/bitget-agent-skill --target all # every supported tool
11
+ * npx @bitget-ai/bitget-agent-skill --target codex,cursor # specific tools
12
+ * npx @bitget-ai/bitget-agent-skill --interactive # prompt to choose
17
13
  */
18
14
 
19
- import { copyFileSync, mkdirSync, existsSync, readdirSync } from "node:fs";
20
- import { join, dirname } from "node:path";
15
+ import { cpSync, mkdirSync, existsSync, rmSync, readdirSync, readFileSync, statSync } from "node:fs";
16
+ import { join, dirname, relative } from "node:path";
21
17
  import { fileURLToPath } from "node:url";
22
18
  import { homedir } from "node:os";
23
19
  import { createInterface } from "node:readline";
@@ -26,37 +22,15 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
26
22
  const PKG_ROOT = join(__dirname, "..");
27
23
  const HOME = homedir();
28
24
 
29
- // Installable skills — each copies its own SKILL.md (and optional reference
30
- // files) into a per-skill subdirectory under the AI tool's skills root.
31
- const SKILLS = {
32
- uta: {
33
- label: "UTA trading (manual API key)",
34
- skillSrcDir: join(PKG_ROOT, "skills", "uta"),
35
- skillDirName: "bitget-agent-skill",
36
- refFiles: [
37
- "commands.md",
38
- "discover-guide.md",
39
- "trading-safety.md",
40
- "error-codes.md",
41
- "auth-setup.md",
42
- "demo-trading.md",
43
- ],
44
- },
45
- agentic: {
46
- label: "Agentic sub-account (OAuth)",
47
- skillSrcDir: join(PKG_ROOT, "skills", "agentic"),
48
- skillDirName: "bitget-agentic",
49
- refFiles: [],
50
- },
51
- "agentic-connect": {
52
- label: "Agentic first-time MCP connect guide",
53
- skillSrcDir: join(PKG_ROOT, "skills", "agentic-connect"),
54
- skillDirName: "bitget-agentic-connect",
55
- refFiles: [],
56
- },
57
- };
25
+ const SKILL_NAME = "bitget-agentic";
26
+ const SKILL_SRC_DIR = join(PKG_ROOT, "skills", SKILL_NAME);
27
+ const DEFAULT_TARGET = "claude";
28
+ // Where a replaced copy is kept. Outside every skills directory, so a client
29
+ // never loads the old copy as a second skill.
30
+ const BACKUP_ROOT = join(HOME, ".bitget-agent-skill", "backup");
58
31
 
59
- // Skill destinations per AI tool
32
+ // Skill destinations per AI tool. Codex reads user skills from ~/.agents/skills,
33
+ // a location Cursor and OpenClaw also read.
60
34
  const TARGETS = {
61
35
  claude: {
62
36
  label: "Claude Code",
@@ -64,7 +38,14 @@ const TARGETS = {
64
38
  },
65
39
  codex: {
66
40
  label: "Codex",
67
- skillsRoot: join(HOME, ".codex", "skills"),
41
+ skillsRoot: join(HOME, ".agents", "skills"),
42
+ // Older Codex versions read ~/.codex/skills. Refresh a copy that an earlier
43
+ // version of this installer put there, so it does not go stale.
44
+ legacySkillsRoot: join(HOME, ".codex", "skills"),
45
+ },
46
+ cursor: {
47
+ label: "Cursor",
48
+ skillsRoot: join(HOME, ".cursor", "skills"),
68
49
  },
69
50
  openclaw: {
70
51
  label: "OpenClaw",
@@ -72,34 +53,87 @@ const TARGETS = {
72
53
  },
73
54
  };
74
55
 
75
- function installTo(targetKey, skillKey) {
76
- const target = TARGETS[targetKey];
77
- const skill = SKILLS[skillKey];
78
- const skillDir = join(target.skillsRoot, skill.skillDirName);
79
- const refsDir = join(skillDir, "references");
56
+ // Skill folders installed by earlier versions that this version replaces.
57
+ // They are reported, never deleted: they live in the user's own directory.
58
+ const OBSOLETE_SKILL_DIRS = {
59
+ "bitget-agent-skill":
60
+ "the old local API-key skill (bgc). It is discontinued and can conflict with this one",
61
+ "bitget-agentic-connect":
62
+ "the old first-time connect guide. It is now part of bitget-agentic and its copy is out of date",
63
+ };
80
64
 
81
- mkdirSync(skillDir, { recursive: true });
65
+ function listFiles(dir, base = dir) {
66
+ const out = [];
67
+ for (const entry of readdirSync(dir)) {
68
+ const abs = join(dir, entry);
69
+ if (statSync(abs).isDirectory()) out.push(...listFiles(abs, base));
70
+ else out.push(relative(base, abs));
71
+ }
72
+ return out.sort();
73
+ }
82
74
 
83
- const skillSrc = join(skill.skillSrcDir, "SKILL.md");
84
- copyFileSync(skillSrc, join(skillDir, "SKILL.md"));
75
+ // True when both folders hold the same files with the same content.
76
+ function sameContent(a, b) {
77
+ const filesA = listFiles(a);
78
+ const filesB = listFiles(b);
79
+ if (filesA.length !== filesB.length || filesA.some((f, i) => f !== filesB[i])) return false;
80
+ return filesA.every((f) => readFileSync(join(a, f)).equals(readFileSync(join(b, f))));
81
+ }
85
82
 
86
- if (skill.refFiles.length > 0) {
87
- mkdirSync(refsDir, { recursive: true });
88
- for (const f of skill.refFiles) {
89
- const src = join(PKG_ROOT, "references", f);
90
- if (existsSync(src)) {
91
- copyFileSync(src, join(refsDir, f));
83
+ // Returns where the previous copy was saved, or null when there was nothing to save.
84
+ function copySkill(skillsRoot, backupName) {
85
+ const dest = join(skillsRoot, SKILL_NAME);
86
+ mkdirSync(skillsRoot, { recursive: true });
87
+ let backup = null;
88
+ if (existsSync(dest) && !sameContent(dest, SKILL_SRC_DIR)) {
89
+ // The installed copy is an older version or was edited by the user. Keep
90
+ // one copy of it per location; the next run replaces that copy.
91
+ backup = join(BACKUP_ROOT, backupName);
92
+ rmSync(backup, { recursive: true, force: true });
93
+ mkdirSync(BACKUP_ROOT, { recursive: true });
94
+ cpSync(dest, backup, { recursive: true });
95
+ }
96
+ // Replace the whole folder so files removed in a newer version do not linger.
97
+ rmSync(dest, { recursive: true, force: true });
98
+ cpSync(SKILL_SRC_DIR, dest, { recursive: true });
99
+ return { dest, backup };
100
+ }
101
+
102
+ function installTo(targetKey) {
103
+ const target = TARGETS[targetKey];
104
+ const main = copySkill(target.skillsRoot, targetKey);
105
+ console.log(` ✓ ${target.label} → ${join(main.dest, "SKILL.md")}`);
106
+ if (main.backup) console.log(` previous copy saved to ${main.backup}`);
107
+
108
+ if (target.legacySkillsRoot && existsSync(join(target.legacySkillsRoot, SKILL_NAME))) {
109
+ const legacy = copySkill(target.legacySkillsRoot, `${targetKey}-older-location`);
110
+ console.log(` ✓ ${target.label} (older location) → ${join(legacy.dest, "SKILL.md")}`);
111
+ if (legacy.backup) console.log(` previous copy saved to ${legacy.backup}`);
112
+ }
113
+ }
114
+
115
+ // Looks in every client's skills directory, not only the ones being installed
116
+ // to: an old skill left in any of them can still be picked up.
117
+ function reportObsolete() {
118
+ const roots = new Set();
119
+ for (const target of Object.values(TARGETS)) {
120
+ roots.add(target.skillsRoot);
121
+ if (target.legacySkillsRoot) roots.add(target.legacySkillsRoot);
122
+ }
123
+ for (const root of roots) {
124
+ for (const [dirName, why] of Object.entries(OBSOLETE_SKILL_DIRS)) {
125
+ const dir = join(root, dirName);
126
+ if (existsSync(dir)) {
127
+ console.log(`\nNote: ${dir} is ${why}. Remove that directory.`);
92
128
  }
93
129
  }
94
130
  }
95
-
96
- console.log(` ✓ ${target.label} (${skill.label}) → ${join(skillDir, "SKILL.md")}`);
97
131
  }
98
132
 
99
133
  async function promptTargets() {
100
134
  const rl = createInterface({ input: process.stdin, output: process.stdout });
101
135
 
102
- console.log("\nBitget Skill — choose installation targets:\n");
136
+ console.log("\nBitget Agentic skill — choose installation targets:\n");
103
137
  const keys = Object.keys(TARGETS);
104
138
  keys.forEach((k, i) => {
105
139
  console.log(` ${i + 1}. ${TARGETS[k].label} (${TARGETS[k].skillsRoot})`);
@@ -108,105 +142,109 @@ async function promptTargets() {
108
142
  console.log();
109
143
 
110
144
  return new Promise((resolve) => {
111
- rl.question(
112
- `Enter numbers separated by commas [default: 1]: `,
113
- (answer) => {
114
- rl.close();
115
- const trimmed = answer.trim();
116
- if (!trimmed || trimmed === "1") {
117
- resolve(["claude"]);
118
- return;
119
- }
120
- if (trimmed === String(keys.length + 1)) {
121
- resolve(keys);
122
- return;
123
- }
124
- const selected = trimmed
125
- .split(",")
126
- .map((s) => parseInt(s.trim(), 10) - 1)
127
- .filter((i) => i >= 0 && i < keys.length)
128
- .map((i) => keys[i]);
129
- resolve(selected.length > 0 ? selected : ["claude"]);
145
+ rl.question(`Enter numbers separated by commas [default: 1]: `, (answer) => {
146
+ rl.close();
147
+ const trimmed = answer.trim();
148
+ if (!trimmed || trimmed === "1") {
149
+ resolve([DEFAULT_TARGET]);
150
+ return;
130
151
  }
131
- );
152
+ if (trimmed === String(keys.length + 1)) {
153
+ resolve(keys);
154
+ return;
155
+ }
156
+ const selected = trimmed
157
+ .split(",")
158
+ .map((s) => parseInt(s.trim(), 10) - 1)
159
+ .filter((i) => i >= 0 && i < keys.length)
160
+ .map((i) => keys[i]);
161
+ resolve(selected.length > 0 ? selected : [DEFAULT_TARGET]);
162
+ });
132
163
  });
133
164
  }
134
165
 
135
- function parseListFlag(args, name, validKeys) {
166
+ function flagValue(args, name) {
136
167
  const arg = args.find((a) => a.startsWith(`--${name}=`) || a === `--${name}`);
137
168
  if (!arg) return null;
138
- const value =
139
- arg === `--${name}` ? args[args.indexOf(`--${name}`) + 1] : arg.split("=")[1];
169
+ return arg === `--${name}` ? args[args.indexOf(`--${name}`) + 1] || null : arg.split("=")[1] || null;
170
+ }
171
+
172
+ function parseTargets(args) {
173
+ const value = flagValue(args, "target");
140
174
  if (!value) return null;
141
- if (value === "all") return Object.keys(validKeys);
142
- const keys = value
175
+ if (value === "all") return Object.keys(TARGETS);
176
+ const names = value
143
177
  .split(",")
144
178
  .map((s) => s.trim())
145
- .filter((k) => k in validKeys);
146
- if (keys.length === 0) {
179
+ .filter(Boolean);
180
+ // Own keys only: "constructor" and the like are not targets.
181
+ const unknown = names.filter((k) => !Object.hasOwn(TARGETS, k));
182
+ if (names.length === 0 || unknown.length > 0) {
183
+ // Nothing is installed: a misspelled name would otherwise leave one client
184
+ // without the skill and no sign of it.
185
+ console.error(
186
+ `Unknown target(s): ${unknown.join(", ") || value}. ` +
187
+ `Valid: ${Object.keys(TARGETS).join(", ")}, all. Nothing was installed.`
188
+ );
189
+ process.exit(1);
190
+ }
191
+ return [...new Set(names)];
192
+ }
193
+
194
+ // --skill is no longer needed: the package ships one skill. It is still
195
+ // accepted so that commands from older guides keep working.
196
+ function handleDeprecatedSkillFlag(args) {
197
+ const value = flagValue(args, "skill");
198
+ if (!value) return;
199
+ const requested = value.split(",").map((s) => s.trim());
200
+ if (requested.includes("uta")) {
147
201
  console.warn(
148
- `Unknown ${name}(s): ${value}. Valid: ${Object.keys(validKeys).join(", ")}, all`
202
+ "The local API-key skill (uta, driven by the bgc CLI) was removed in 4.0.0 and is " +
203
+ "no longer supported. Run again without --skill to install the cloud MCP skill."
149
204
  );
150
205
  process.exit(1);
151
206
  }
152
- return keys;
207
+ console.log(`Note: --skill is no longer needed and is ignored; installing ${SKILL_NAME}.`);
153
208
  }
154
209
 
155
210
  async function main() {
156
211
  const args = process.argv.slice(2);
157
- const isInteractive = args.includes("--interactive");
158
- const targetValue = parseListFlag(args, "target", TARGETS);
159
- const skillValue = parseListFlag(args, "skill", SKILLS);
212
+ handleDeprecatedSkillFlag(args);
160
213
 
161
- let selectedTargetKeys;
162
- const selectedSkillKeys = skillValue || ["uta"];
163
-
164
- if (isInteractive) {
165
- // Interactive mode — prompt user
214
+ let targetKeys;
215
+ if (args.includes("--interactive")) {
166
216
  try {
167
- selectedTargetKeys = await promptTargets();
217
+ targetKeys = await promptTargets();
168
218
  } catch {
169
- selectedTargetKeys = ["claude"];
219
+ targetKeys = [DEFAULT_TARGET];
170
220
  }
171
- } else if (targetValue) {
172
- selectedTargetKeys = targetValue;
173
221
  } else {
174
- // Default postinstall: Claude Code, uta skill only, silent on failure
175
- try {
176
- installTo("claude", "uta");
177
- } catch (err) {
178
- console.warn("Could not auto-install skill:", err.message);
179
- }
180
- return;
222
+ targetKeys = parseTargets(args) || [DEFAULT_TARGET];
181
223
  }
182
224
 
183
- console.log("\nInstalling Bitget skill...");
225
+ console.log("\nInstalling the Bitget Agentic skill...");
184
226
  let ok = 0;
185
- const total = selectedTargetKeys.length * selectedSkillKeys.length;
186
- for (const targetKey of selectedTargetKeys) {
187
- for (const skillKey of selectedSkillKeys) {
188
- try {
189
- installTo(targetKey, skillKey);
190
- ok++;
191
- } catch (err) {
192
- console.warn(` ✗ ${TARGETS[targetKey].label} (${SKILLS[skillKey].label}): ${err.message}`);
193
- }
227
+ for (const targetKey of targetKeys) {
228
+ try {
229
+ installTo(targetKey);
230
+ ok++;
231
+ } catch (err) {
232
+ console.warn(` ✗ ${TARGETS[targetKey].label}: ${err.message}`);
194
233
  }
195
234
  }
196
- console.log(`\nDone — installed ${ok} of ${total} target/skill combinations.`);
235
+ console.log(`\nDone — installed to ${ok} of ${targetKeys.length} target(s).`);
197
236
 
198
- if (selectedTargetKeys.includes("claude")) {
199
- console.log(
200
- "\nClaude Code: restart Claude Code to pick up the skill, or run:\n" +
201
- " claude skills list"
202
- );
203
- }
204
- if (selectedTargetKeys.includes("codex")) {
205
- console.log("\nCodex: skill will be loaded automatically from ~/.codex/skills/");
206
- }
207
- if (selectedTargetKeys.includes("openclaw")) {
208
- console.log("\nOpenClaw: skill will be loaded automatically from ~/.openclaw/skills/");
237
+ reportObsolete();
238
+
239
+ if (targetKeys.includes("claude")) {
240
+ console.log("\nClaude Code: restart Claude Code to pick up the skill.");
209
241
  }
242
+ console.log(
243
+ "\nNext: ask your AI agent to read the installed SKILL.md and connect " +
244
+ "https://agent.bitget.com/mcp."
245
+ );
246
+
247
+ if (ok < targetKeys.length) process.exit(1);
210
248
  }
211
249
 
212
250
  main();
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Validates every skill under skills/ against the Agent Skills specification
4
+ * (https://agentskills.io/specification) and the authoring limits this repo
5
+ * holds itself to. Exits non-zero on any error, so it can gate build and publish.
6
+ *
7
+ * Usage: node scripts/validate-skills.mjs
8
+ *
9
+ * The frontmatter parser is deliberately small: it accepts only top-level
10
+ * `key: value`, folded `key: >` blocks, and one flat `metadata:` map of quoted
11
+ * strings. Anything else is reported, which is how the "metadata is a map of
12
+ * string keys to string values" rule is enforced.
13
+ */
14
+
15
+ import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
16
+ import { join, dirname, relative, resolve, sep } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
20
+ const SKILLS_DIR = join(ROOT, "skills");
21
+
22
+ // Fields accepted by every Agent Skills host. Host-specific fields would make
23
+ // the skill fail to load elsewhere.
24
+ const ALLOWED_KEYS = new Set([
25
+ "name",
26
+ "description",
27
+ "license",
28
+ "compatibility",
29
+ "metadata",
30
+ "allowed-tools",
31
+ ]);
32
+ const NAME_MAX = 64;
33
+ const DESCRIPTION_MAX = 1024;
34
+ const COMPATIBILITY_MAX = 500;
35
+ const BODY_MAX_LINES = 500;
36
+ // The spec recommends under 5000 tokens. Roughly 4 characters per token.
37
+ const BODY_MAX_TOKENS = 5000;
38
+ const CHARS_PER_TOKEN = 4;
39
+ // Reference files longer than this need a contents list at the top.
40
+ const REFERENCE_TOC_LINES = 100;
41
+ const RESERVED_NAME_WORDS = ["anthropic", "claude"];
42
+
43
+ function unquote(value) {
44
+ const v = value.trim();
45
+ if (v.length >= 2 && (v[0] === '"' || v[0] === "'") && v[v.length - 1] === v[0]) {
46
+ return { text: v.slice(1, -1), quoted: true };
47
+ }
48
+ return { text: v, quoted: false };
49
+ }
50
+
51
+ function parseFrontmatter(source, errors) {
52
+ if (!source.startsWith("---\n")) {
53
+ errors.push("SKILL.md must start with a `---` frontmatter line");
54
+ return null;
55
+ }
56
+ const end = source.indexOf("\n---", 4);
57
+ if (end === -1) {
58
+ errors.push("frontmatter is not closed with `---`");
59
+ return null;
60
+ }
61
+ const lines = source.slice(4, end).split("\n");
62
+ const body = source.slice(end + 4).replace(/^\n/, "");
63
+ const fields = {};
64
+
65
+ for (let i = 0; i < lines.length; i++) {
66
+ const line = lines[i];
67
+ if (!line.trim()) continue;
68
+ const top = /^([A-Za-z][\w-]*):(.*)$/.exec(line);
69
+ if (!top) {
70
+ errors.push(`frontmatter line ${i + 2} is not a top-level \`key: value\`: ${line.trim()}`);
71
+ continue;
72
+ }
73
+ const [, key, rest] = top;
74
+ const value = rest.trim();
75
+
76
+ const collectIndented = () => {
77
+ const block = [];
78
+ while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]) || !lines[i + 1].trim())) {
79
+ block.push(lines[++i]);
80
+ }
81
+ return block;
82
+ };
83
+
84
+ if (value === ">" || value === ">-" || value === "|" || value === "|-") {
85
+ const block = collectIndented().map((l) => l.trim());
86
+ fields[key] = value.startsWith(">") ? block.filter(Boolean).join(" ") : block.join("\n");
87
+ } else if (value === "") {
88
+ const map = {};
89
+ for (const entry of collectIndented()) {
90
+ if (!entry.trim()) continue;
91
+ const m = /^ {2}([A-Za-z][\w-]*):\s*(.+)$/.exec(entry);
92
+ if (!m) {
93
+ errors.push(`\`${key}\` must be a flat map of \`key: "string"\` pairs; found: ${entry.trim()}`);
94
+ continue;
95
+ }
96
+ const { text, quoted } = unquote(m[2]);
97
+ if (!quoted) {
98
+ errors.push(`\`${key}.${m[1]}\` must be a quoted string so YAML cannot read it as a number or date`);
99
+ }
100
+ map[m[1]] = text;
101
+ }
102
+ fields[key] = map;
103
+ } else {
104
+ fields[key] = unquote(value).text;
105
+ }
106
+ }
107
+ return { fields, body };
108
+ }
109
+
110
+ function validateSkill(dirName) {
111
+ const errors = [];
112
+ const skillDir = join(SKILLS_DIR, dirName);
113
+ const skillFile = join(skillDir, "SKILL.md");
114
+ if (!existsSync(skillFile)) {
115
+ return [`missing SKILL.md`];
116
+ }
117
+ const source = readFileSync(skillFile, "utf8");
118
+ const parsed = parseFrontmatter(source, errors);
119
+ if (!parsed) return errors;
120
+ const { fields, body } = parsed;
121
+
122
+ for (const key of Object.keys(fields)) {
123
+ if (!ALLOWED_KEYS.has(key)) {
124
+ errors.push(`frontmatter field \`${key}\` is not in the Agent Skills spec (${[...ALLOWED_KEYS].join(", ")})`);
125
+ }
126
+ }
127
+
128
+ // name
129
+ const name = fields.name;
130
+ if (typeof name !== "string" || !name) {
131
+ errors.push("`name` is required");
132
+ } else {
133
+ if (name.length > NAME_MAX) errors.push(`\`name\` is ${name.length} characters (max ${NAME_MAX})`);
134
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) {
135
+ errors.push("`name` may contain only lowercase letters, digits, and single hyphens, and cannot start or end with a hyphen");
136
+ }
137
+ if (name !== dirName) errors.push(`\`name\` (${name}) must match the directory name (${dirName})`);
138
+ for (const word of RESERVED_NAME_WORDS) {
139
+ if (name.includes(word)) errors.push(`\`name\` cannot contain the reserved word "${word}"`);
140
+ }
141
+ }
142
+
143
+ // description
144
+ const description = fields.description;
145
+ if (typeof description !== "string" || !description) {
146
+ errors.push("`description` is required");
147
+ } else {
148
+ if (description.length > DESCRIPTION_MAX) {
149
+ errors.push(`\`description\` is ${description.length} characters (max ${DESCRIPTION_MAX})`);
150
+ }
151
+ if (/[<>]/.test(description)) errors.push("`description` cannot contain `<` or `>`");
152
+ }
153
+
154
+ if (typeof fields.compatibility === "string" && fields.compatibility.length > COMPATIBILITY_MAX) {
155
+ errors.push(`\`compatibility\` is ${fields.compatibility.length} characters (max ${COMPATIBILITY_MAX})`);
156
+ }
157
+ if ("metadata" in fields && (typeof fields.metadata !== "object" || fields.metadata === null)) {
158
+ errors.push("`metadata` must be a map of string keys to string values");
159
+ }
160
+
161
+ // body size
162
+ const bodyLines = body.split("\n").length;
163
+ const bodyTokens = Math.ceil(body.length / CHARS_PER_TOKEN);
164
+ if (bodyLines > BODY_MAX_LINES) errors.push(`SKILL.md body is ${bodyLines} lines (max ${BODY_MAX_LINES})`);
165
+ if (bodyTokens > BODY_MAX_TOKENS) {
166
+ errors.push(`SKILL.md body is about ${bodyTokens} tokens (max ${BODY_MAX_TOKENS}); move detail into references/`);
167
+ }
168
+
169
+ // links from SKILL.md: relative, forward slashes, inside the skill, existing
170
+ const linked = new Set();
171
+ for (const m of body.matchAll(/\]\(([^)\s]+)\)/g)) {
172
+ const target = m[1].split("#")[0];
173
+ if (!target || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue; // external or anchor
174
+ if (target.includes("\\")) errors.push(`link \`${target}\` uses a backslash; use forward slashes`);
175
+ const abs = resolve(skillDir, target);
176
+ if (abs !== skillDir && !abs.startsWith(skillDir + sep)) {
177
+ errors.push(`link \`${target}\` points outside the skill directory`);
178
+ } else if (!existsSync(abs)) {
179
+ errors.push(`link \`${target}\` does not resolve to a file`);
180
+ } else {
181
+ linked.add(abs);
182
+ }
183
+ }
184
+
185
+ // every reference file is reachable from SKILL.md (one level deep)
186
+ const refsDir = join(skillDir, "references");
187
+ if (existsSync(refsDir)) {
188
+ for (const entry of readdirSync(refsDir)) {
189
+ const abs = join(refsDir, entry);
190
+ if (statSync(abs).isDirectory()) {
191
+ errors.push(`references/${entry}/ is nested; keep reference files one level deep`);
192
+ continue;
193
+ }
194
+ const rel = relative(skillDir, abs).split(sep).join("/");
195
+ if (!linked.has(abs)) errors.push(`${rel} is not linked from SKILL.md, so an agent cannot discover it`);
196
+ const text = readFileSync(abs, "utf8");
197
+ if (text.split("\n").length > REFERENCE_TOC_LINES && !/^## Contents\s*$/m.test(text)) {
198
+ errors.push(`${rel} is over ${REFERENCE_TOC_LINES} lines and needs a "## Contents" list at the top`);
199
+ }
200
+ }
201
+ }
202
+
203
+ if (!errors.length) {
204
+ console.log(
205
+ ` ✓ ${dirName}: description ${description.length}/${DESCRIPTION_MAX} chars, ` +
206
+ `body ${bodyLines} lines, about ${bodyTokens} tokens`
207
+ );
208
+ }
209
+ return errors;
210
+ }
211
+
212
+ // One version, written in four places. A release where they disagree publishes
213
+ // a package whose skill reports a different version than npm does.
214
+ function versionErrors(skillDirs) {
215
+ const errors = [];
216
+ const read = (file) => (existsSync(join(ROOT, file)) ? readFileSync(join(ROOT, file), "utf8") : null);
217
+
218
+ const versionFile = read("VERSION");
219
+ const version = versionFile === null ? null : versionFile.trim();
220
+ if (!version) return ["VERSION is missing or empty"];
221
+ if (!/^\d+\.\d+\.\d+$/.test(version)) errors.push(`VERSION is "${version}", expected x.y.z`);
222
+
223
+ const pkg = read("package.json");
224
+ if (pkg === null) {
225
+ errors.push("package.json is missing");
226
+ } else {
227
+ const pkgVersion = JSON.parse(pkg).version;
228
+ if (pkgVersion !== version) errors.push(`package.json version is ${pkgVersion}, VERSION is ${version}`);
229
+ }
230
+
231
+ for (const dir of skillDirs) {
232
+ const skill = readFileSync(join(SKILLS_DIR, dir, "SKILL.md"), "utf8");
233
+ const found = skill.match(/^\s+version:\s*"([^"]+)"\s*$/m);
234
+ if (!found) errors.push(`skills/${dir}/SKILL.md has no metadata.version`);
235
+ else if (found[1] !== version) {
236
+ errors.push(`skills/${dir}/SKILL.md metadata.version is ${found[1]}, VERSION is ${version}`);
237
+ }
238
+ }
239
+
240
+ const changelog = read("CHANGELOG.md");
241
+ if (changelog !== null) {
242
+ const newest = changelog.match(/^## \[([^\]]+)\]/m);
243
+ if (!newest) errors.push("CHANGELOG.md has no version entry");
244
+ else if (newest[1] !== version) {
245
+ errors.push(`newest CHANGELOG.md entry is ${newest[1]}, VERSION is ${version}`);
246
+ }
247
+ }
248
+ return errors;
249
+ }
250
+
251
+ function main() {
252
+ if (!existsSync(SKILLS_DIR)) {
253
+ console.error("skills/ directory not found");
254
+ process.exit(1);
255
+ }
256
+ const dirs = readdirSync(SKILLS_DIR).filter((d) => statSync(join(SKILLS_DIR, d)).isDirectory());
257
+ if (dirs.length === 0) {
258
+ console.error("no skills found under skills/");
259
+ process.exit(1);
260
+ }
261
+
262
+ console.log("Validating skills against the Agent Skills specification...");
263
+ let failed = 0;
264
+ for (const dir of dirs) {
265
+ const errors = validateSkill(dir);
266
+ if (errors.length) {
267
+ failed++;
268
+ console.error(` ✗ ${dir}`);
269
+ for (const e of errors) console.error(` - ${e}`);
270
+ }
271
+ }
272
+ if (failed) {
273
+ console.error(`\n${failed} of ${dirs.length} skill(s) failed validation.`);
274
+ process.exit(1);
275
+ }
276
+
277
+ const mismatches = versionErrors(dirs);
278
+ if (mismatches.length) {
279
+ console.error(" ✗ version");
280
+ for (const e of mismatches) console.error(` - ${e}`);
281
+ console.error("\nThe version is not the same everywhere.");
282
+ process.exit(1);
283
+ }
284
+ console.log(` ✓ version ${readFileSync(join(ROOT, "VERSION"), "utf8").trim()} in VERSION, package.json, SKILL.md, CHANGELOG.md`);
285
+
286
+ console.log(`\nAll ${dirs.length} skill(s) are valid.`);
287
+ }
288
+
289
+ main();