@soft-boy/agentschema 0.2.2 → 0.3.0

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/README.md CHANGED
@@ -9,6 +9,9 @@ my-agent/
9
9
  ├── tools/ # tool files, in any folders you like
10
10
  │ ├── agent_toolset_20260401.md # the pre-built tools to enable
11
11
  │ └── get_weather.md
12
+ ├── skills/ # instructions the agent loads when a task needs them
13
+ │ └── code-review/
14
+ │ └── SKILL.md
12
15
  └── vaults/ # credentials for MCP servers and API keys
13
16
  └── Ops/ # a vault, named after its folder
14
17
  └── Slack.md # a credential, without its secrets
@@ -43,6 +46,10 @@ my-agent/
43
46
  ├── tools/ # tool files, nested however you like
44
47
  │ ├── agent_toolset_20260401.md # the pre-built tools to enable
45
48
  │ └── get_weather.md
49
+ ├── skills/ # optional: one folder per skill
50
+ │ └── code-review/
51
+ │ ├── SKILL.md
52
+ │ └── checklist.md # any other files the skill needs
46
53
  └── vaults/ # optional: one folder per vault
47
54
  └── Ops/
48
55
  ├── vault.md # optional: the vault's metadata
@@ -154,6 +161,27 @@ module.exports = ({ city }) =>
154
161
 
155
162
  **Compiling.** `deploy` turns `tools/` into the agent's `tools` list, sorted by tool name: one `agent_toolset_20260401` entry with a config for each row of the `## Tools` table (its `enabled`, and its `permission_policy` if it has one), then an `mcp_toolset` entry for each MCP toolset file, then the custom tools. A custom tool sends only its name, description and input schema; the code never leaves your machine.
156
163
 
164
+ ### `skills/`
165
+ Field reference: [Skills](https://platform.claude.com/docs/en/managed-agents/skills).
166
+
167
+ Skills are instructions, and optionally scripts or reference files, that the agent loads only when a task calls for them. Each folder in `skills/` is one skill, following the standard layout: a `SKILL.md`, plus any other files it needs, at any depth.
168
+
169
+ ```markdown
170
+ ---
171
+ name: code-review
172
+ description: Review code for bugs, security problems and missing tests. Use when asked to review a change.
173
+ ---
174
+
175
+ Read `checklist.md`, then go through the change one file at a time.
176
+ ```
177
+
178
+ - **`name`** is required, and must match the folder's name. It may use lowercase letters, digits and hyphens, up to 64 characters, and can't contain `anthropic` or `claude`.
179
+ - **`description`** is required, up to 1,024 characters, with no XML tags. The agent reads it to decide when to load the skill. Other frontmatter fields are left as written.
180
+ - **Files:** hidden files and `node_modules` aren't uploaded. A skill's files can add up to 30 MB.
181
+ - **Everything in the folder is uploaded to Anthropic,** so keep secrets out. `check` scans these files too.
182
+
183
+ Every skill in the folder is attached to the agent. To use Anthropic's pre-built skills, or a skill that already exists in your workspace, list it under `skills` in `agent.md`'s frontmatter, as in the API; `deploy` adds the folder's skills to that list.
184
+
157
185
  ### `vaults/`
158
186
  Field reference: [Vaults](https://platform.claude.com/docs/en/managed-agents/vaults).
159
187
 
@@ -211,7 +239,7 @@ auth:
211
239
  ```sh
212
240
  agentschema init <name> # scaffold a new agent folder
213
241
  agentschema check [dir] # validate the folder, no network
214
- agentschema deploy [dir] # create or update the agent, environment and vaults
242
+ agentschema deploy [dir] # create or update the skills, agent, environment and vaults
215
243
  agentschema run [dir] # chat with the deployed agent in the terminal
216
244
  agentschema list # list the agents in your workspace
217
245
  agentschema delete <agent_id> # archive an agent
@@ -239,16 +267,18 @@ Press Enter to keep the default shown, or pass `--yes` to skip the questions. `i
239
267
  - frontmatter that is missing, unclosed, or invalid YAML
240
268
  - a missing `name` or `model`, or a `system` or `tools` key in `agent.md`'s frontmatter
241
269
  - a pre-built tools table that names an unknown tool or permission, an MCP server without both its entry in `agent.md` and its toolset file, or a custom tool with a missing description, a malformed input table, or code that isn't JavaScript or doesn't parse
270
+ - a skill with no `SKILL.md`, or a `name` or `description` the API would reject
242
271
  - a credential file with a secret in it, a missing field, or two credentials for the same server
243
272
  - values over the API's limits
244
273
  - anything that looks like an API key or token
245
274
 
246
275
  Unknown fields are only warnings, because they're sent to the API as written. `check` exits with status 1 when there are errors.
247
276
 
248
- **`deploy`** runs `check` first, then creates or updates the environment, the agent and the vaults, and records their IDs in `claude-lock.json` in the folder. Commit that file.
277
+ **`deploy`** runs `check` first, then creates or updates the skills, the environment, the agent and the vaults, and records their IDs in `claude-lock.json` in the folder. Commit that file.
249
278
  - **Later runs update the same resources.** A file that hasn't changed since the last deploy is skipped. Each change to `agent.md` or `tools/` adds a new version of the agent, and sessions already running keep the version they started on.
250
279
  - **The files are the source of truth.** A field you delete from a file is cleared on the next deploy, rather than left at its old value.
251
280
  - **Changes made elsewhere aren't overwritten silently.** If the agent was changed outside the folder since the last deploy, `deploy` stops; `--force` overwrites it.
281
+ - **A changed skill gets a new version.** Any change to a skill's files uploads the whole folder as a new version. The agent is pinned to skill versions, so that also adds a new version of the agent, and sessions already running keep what they started on. Deleting a skill's folder detaches it from the agent, but the skill stays in your workspace until you delete it in the Console. Renaming the folder creates a new skill.
252
282
  - **Credentials are updated, not created.** Creating a credential needs its secrets, which aren't in the files, so `deploy` lists each credential file that has no credential yet, with the `cred deploy` command to run. It updates the settings of credentials that exist.
253
283
 
254
284
  `claude-lock.json` uses the same layout as `ant apply`'s, so `deploy` updates resources that `ant apply` created. The two tools hash files differently, though, so the first `deploy` after an `ant apply` updates both resources even if nothing changed.
@@ -256,7 +286,7 @@ Unknown fields are only warnings, because they're sent to the API as written. `c
256
286
  **`run`** starts a session on the agent and environment in `claude-lock.json`, then opens a chat in the terminal. Deploy first; if you've edited the files since, `run` warns you and still uses the deployed version.
257
287
  - **Messages:** type a message and press Enter. The agent's replies stream in, with a one-line summary of each tool call.
258
288
  - **Approvals:** when a tool call needs approval (`always_ask`, or `auto` when the server can't decide), `run` asks you. Answer `y` to allow it, or type a reason to deny it; the agent sees the reason.
259
- - **Custom tools:** `run` runs the tool's code from `tools/` and sends back the result. The code runs on your machine with your permissions, like any script in the folder. If the folder doesn't pass `check`, or the tool isn't in it (for example, when you resume a session from somewhere else), `run` shows the call's input and asks you to type the result.
289
+ - **Custom tools:** `run` runs the tool's code from `tools/` and sends back the result. The code runs on your machine with your permissions, like any script in the folder. Settings the code needs can go in a `.env` file in the agent folder, as `KEY=VALUE` lines, which `run` loads before it starts. Keep `.env` out of git. A variable already set in your shell wins, and `.env` doesn't change which Anthropic credentials `run` uses. If the folder doesn't pass `check`, or the tool isn't in it (for example, when you resume a session from somewhere else), `run` shows the call's input and asks you to type the result.
260
290
  - **Interrupting:** Ctrl+C interrupts the agent mid-turn, and a second Ctrl+C quits. Ctrl+D quits at the prompt.
261
291
  - **Vaults:** the session gets every vault in `vaults/` that's been deployed, in folder name order. `run` warns about vaults that haven't been deployed and credentials that haven't been created.
262
292
  - **Resuming:** quitting leaves the session in place, and `run` prints a command to resume it: `agentschema run --resume sesn_…`.
@@ -10,6 +10,7 @@ import { credDelete, credLogin } from "../src/cred.js";
10
10
  import { check } from "../src/check.js";
11
11
  import { DeleteError, deleteAgent, deleteSession } from "../src/delete.js";
12
12
  import { DeployError, deploy } from "../src/deploy.js";
13
+ import { loadEnvFile } from "../src/dotenv.js";
13
14
  import { InitError, init } from "../src/init.js";
14
15
  import { listAgents, listSessions } from "../src/list.js";
15
16
  import { prompts } from "../src/prompts.js";
@@ -24,8 +25,8 @@ const USAGE = `Usage: agentschema <command> [dir] [options]
24
25
  Commands:
25
26
  init <name> Scaffold a new agent folder, asking a few questions
26
27
  check [dir] Validate the folder's files, without calling the API
27
- deploy [dir] Create or update the agent, environment and vaults, and write claude-lock.json
28
- run [dir] Chat with the deployed agent in a new session
28
+ deploy [dir] Create or update the skills, agent, environment and vaults, and write claude-lock.json
29
+ run [dir] Chat with the deployed agent in a new session, loading dir/.env for your tools
29
30
  list List the agents in your workspace
30
31
  delete <agent_id> Archive an agent (agents can't be deleted outright)
31
32
  tools <command> Add pre-built tools, custom tools and MCP servers (agentschema tools -h)
@@ -251,7 +252,10 @@ async function main(argv) {
251
252
  }
252
253
 
253
254
  if (command === "run") {
255
+ // Made first, so .env only reaches your tools: Anthropic credentials still come from the
256
+ // shell, the same as for every other command.
254
257
  const client = makeClient(false);
258
+ for (const warning of loadEnvFile(dir)) console.warn(`warning: ${warning}`);
255
259
  const { session, notes } = await openSession(dir, {
256
260
  client,
257
261
  sessionId: values.resume,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soft-boy/agentschema",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Markdown based AI agent schema",
5
5
  "type": "module",
6
6
  "bin": {
package/src/check.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AGENT_FILE, ENV_FILE, readInstance } from "./instance.js";
2
+ import { MAX_UPLOAD_BYTES, SKILLS_DIR, readSkills } from "./skills.js";
2
3
  import { MCP_TOOLSET, TOOLS_DIR, checkTools, readTools } from "./tools.js";
3
4
  import { CREDENTIAL_TYPES, ENV_VAR, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULT_FILE, get, readVaults } from "./vaults.js";
4
5
 
@@ -24,7 +25,8 @@ export function check(dir) {
24
25
  const { agent, env, errors } = readInstance(dir);
25
26
  const { tools, errors: toolErrors } = readTools(dir);
26
27
  const { vaults, errors: vaultErrors } = readVaults(dir);
27
- errors.push(...toolErrors, ...vaultErrors);
28
+ const { skills, errors: skillErrors } = readSkills(dir);
29
+ errors.push(...toolErrors, ...vaultErrors, ...skillErrors);
28
30
  const warnings = [];
29
31
 
30
32
  if (agent) checkAgent(agent, errors, warnings);
@@ -32,18 +34,22 @@ export function check(dir) {
32
34
  checkTools(tools, errors);
33
35
  if (agent) checkMcpServers(agent, tools, errors);
34
36
  if (agent && env) checkMcpNetworking(agent, env, warnings);
37
+ for (const skill of skills) checkSkill(skill, errors);
38
+ const declaredSkills = Array.isArray(agent?.data.skills) ? agent.data.skills.length : 0;
39
+ if (declaredSkills + skills.length > 500) errors.push(`${declaredSkills + skills.length} skills; the limit is 500`);
35
40
  for (const vault of vaults) checkVault(vault, errors, warnings);
36
41
  checkEnvVarCredentials(vaults, env, warnings);
37
42
 
38
43
  const vaultFiles = vaults.flatMap((v) => [...(v.file ? [[`${v.path}/${VAULT_FILE}`, v.file]] : []), ...v.credentials.map((c) => [c.file, c])]);
39
- for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t]), ...vaultFiles]) {
44
+ const skillTexts = skills.flatMap((s) => s.files.map((f) => [`${s.path}/${f.rel}`, { raw: f.bytes.toString("utf8") }]));
45
+ for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t]), ...vaultFiles, ...skillTexts]) {
40
46
  if (!parsed) continue;
41
47
  for (const [pattern, what] of SECRET_PATTERNS) {
42
48
  if (pattern.test(parsed.raw)) errors.push(`${file}: looks like it contains ${what}; keep secrets out of these files`);
43
49
  }
44
50
  }
45
51
 
46
- return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults } : null };
52
+ return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills } : null };
47
53
  }
48
54
 
49
55
  function checkAgent({ data, body }, errors, warnings) {
@@ -73,6 +79,10 @@ function checkAgent({ data, body }, errors, warnings) {
73
79
  else if (data[field].length > max) err(`\`${field}\` has ${data[field].length} entries; the limit is ${max}`);
74
80
  }
75
81
 
82
+ if (Array.isArray(data.skills)) {
83
+ for (const [index, skill] of data.skills.entries()) checkSkillRef(skill, (msg) => err(`\`skills[${index}]\`: ${msg}`));
84
+ }
85
+
76
86
  checkMetadata(data.metadata, 16, err);
77
87
 
78
88
  for (const key of Object.keys(data)) {
@@ -110,6 +120,38 @@ function checkEnv({ data }, errors, warnings) {
110
120
  }
111
121
  }
112
122
 
123
+ // An entry in agent.md's `skills` list, in the API's shape.
124
+ function checkSkillRef(skill, err) {
125
+ if (typeof skill === "string") {
126
+ return err(`write this as a mapping with \`type\` and \`skill_id\`; a skill in ${SKILLS_DIR}/ is attached without being listed`);
127
+ }
128
+ if (!isObject(skill)) return err("must be a mapping with `type` and `skill_id`");
129
+ if (!["anthropic", "custom"].includes(skill.type)) err("`type` must be `anthropic` or `custom`");
130
+ if (typeof skill.skill_id !== "string" || skill.skill_id === "") err("`skill_id` is required");
131
+ else if (skill.type === "custom" && !skill.skill_id.startsWith("skill_")) err("a custom skill's `skill_id` starts with skill_");
132
+ if (skill.version !== undefined && skill.version !== null && typeof skill.version !== "string") {
133
+ err("`version` must be a string (quote numbers)");
134
+ }
135
+ }
136
+
137
+ function checkSkill(skill, errors) {
138
+ const err = (msg) => errors.push(`${skill.file}: ${msg}`);
139
+ const { name, description } = skill.data;
140
+ if (typeof name !== "string" || name === "") err("`name` is required");
141
+ else {
142
+ if (name !== skill.name) err(`\`name\` must match the folder's name (${skill.name})`);
143
+ if (!/^[a-z0-9-]{1,64}$/.test(name)) err("`name` may only use lowercase letters, digits and hyphens, up to 64 characters");
144
+ if (/anthropic|claude/.test(name)) err("`name` can't contain the reserved words `anthropic` or `claude`");
145
+ }
146
+ if (typeof description !== "string" || description.trim() === "") err("`description` is required");
147
+ else {
148
+ if (description.length > 1024) err(`\`description\` is ${description.length} characters; the limit is 1,024`);
149
+ if (/<[^>]+>/.test(description)) err("`description` can't contain XML tags");
150
+ }
151
+ const size = skill.files.reduce((total, f) => total + f.bytes.length, 0);
152
+ if (size > MAX_UPLOAD_BYTES) errors.push(`${skill.path}: its files add up to ${Math.ceil(size / 1024 / 1024)} MB; the limit is 30 MB`);
153
+ }
154
+
113
155
  const mcpServers = (agent) => (Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers.filter(isObject) : []);
114
156
 
115
157
  // Each server agent.md declares needs a toolset file, and each toolset file a declared server;
package/src/deploy.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import { join } from "node:path";
2
- import Anthropic from "@anthropic-ai/sdk";
2
+ import Anthropic, { toFile } from "@anthropic-ai/sdk";
3
3
  import { check } from "./check.js";
4
4
  import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
5
5
  import { LOCK_FILE, hashBody, readLock, writeLock } from "./lock.js";
6
+ import { skillFingerprint, skillKey, skillRefs } from "./skills.js";
6
7
  import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey } from "./vaults.js";
7
8
 
8
9
  export class DeployError extends Error {}
9
10
 
10
- // Creates or updates the environment, agent and vaults a folder defines, recording their IDs
11
- // in claude-lock.json. Credentials are only updated here: creating one needs its secrets, so
11
+ // Creates or updates the skills, environment, agent and vaults a folder defines, recording their
12
+ // IDs in claude-lock.json. Skills go first, because the agent refers to their IDs and versions. Credentials are only updated here: creating one needs its secrets, so
12
13
  // that's `cred deploy`'s job.
13
14
  // Returns the plan: one { file, kind, action, id, version } entry per resource.
14
15
  export async function deploy(dir, { client, dryRun = false, force = false, log = () => {} }) {
@@ -16,9 +17,18 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
16
17
  if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
17
18
  const lock = openLock(dir, client);
18
19
 
20
+ const skillSteps = await deploySkills(instance.skills, { dir, client, lock, dryRun, log });
21
+ // A dry run has no new IDs or versions yet, so a stand-in shows that the agent will change too.
22
+ const pending = dryRun ? skillSteps.filter((s) => s.action !== "unchanged") : [];
23
+ const refs = instance.skills.flatMap((skill) => {
24
+ const step = pending.find((s) => s.key === skillKey(skill));
25
+ if (!step) return skillRefs([skill], lock);
26
+ return [{ type: "custom", skill_id: step.entry?.id ?? `pending:${skill.name}`, version: `pending:${step.hash}` }];
27
+ });
28
+
19
29
  const steps = [
20
30
  { file: ENV_FILE, kind: "environment", body: envBody(instance) },
21
- { file: AGENT_FILE, kind: "agent", body: agentBody(instance) },
31
+ { file: AGENT_FILE, kind: "agent", body: agentBody(instance, refs) },
22
32
  ];
23
33
  for (const step of steps) {
24
34
  step.key = `./${step.file}`;
@@ -51,7 +61,7 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
51
61
 
52
62
  const vaultSteps = await deployVaults(dir, instance.vaults, { client, lock, dryRun, log });
53
63
 
54
- return [...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
64
+ return [...skillSteps, ...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
55
65
  file, kind, action,
56
66
  id: lock.resources[key]?.id,
57
67
  version: lock.resources[key]?.version,
@@ -71,6 +81,36 @@ export function openLock(dir, client) {
71
81
  return lock;
72
82
  }
73
83
 
84
+ // Uploads each skill that's new or changed. A change uploads the whole folder as a new version.
85
+ async function deploySkills(skills, { dir, client, lock, dryRun, log }) {
86
+ const steps = [];
87
+ for (const skill of skills) {
88
+ const step = planStep(lock, { file: skill.path, key: skillKey(skill), kind: "skill", body: skillFingerprint(skill) });
89
+ steps.push(step);
90
+ if (dryRun || step.action === "unchanged") {
91
+ log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? skill.name}`);
92
+ continue;
93
+ }
94
+
95
+ // The API keeps a skill's layout from these names, so each one starts with its folder.
96
+ const files = await Promise.all(skill.files.map((f) => toFile(f.bytes, `${skill.name}/${f.rel}`)));
97
+ let id;
98
+ let version;
99
+ if (step.action === "create") {
100
+ const created = await call(step, () => client.skills.create({ files }));
101
+ ({ id, latest_version_id: version } = created);
102
+ } else {
103
+ ({ id } = step.entry);
104
+ await retrieve(step, () => client.skills.retrieve(id));
105
+ ({ id: version } = await call(step, () => client.skills.versions.create(id, { files })));
106
+ }
107
+ lock.resources[step.key] = { kind: "skill", id, version, hash: step.hash };
108
+ writeLock(dir, lock);
109
+ log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} skill ${id} (version ${version})`);
110
+ }
111
+ return steps;
112
+ }
113
+
74
114
  // Creates or updates each vault, then updates the settings of credentials already created.
75
115
  // A credential file with no credential yet is reported, not created: that needs its secrets.
76
116
  async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
package/src/dotenv.js ADDED
@@ -0,0 +1,50 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ export const ENV_FILE_NAME = ".env";
5
+
6
+ // Parses KEY=VALUE lines. Returns { values, bad }: `bad` holds the numbers of lines that aren't
7
+ // valid, so they can be reported without showing what's on them.
8
+ export function parseEnvFile(text) {
9
+ const values = {};
10
+ const bad = [];
11
+ for (const [index, raw] of text.replace(/^/, "").split(/\r?\n/).entries()) {
12
+ const line = raw.trim();
13
+ if (line === "" || line.startsWith("#")) continue;
14
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
15
+ const value = match && parseValue(match[2]);
16
+ if (value === null || !match) bad.push(index + 1);
17
+ else values[match[1]] = value;
18
+ }
19
+ return { values, bad };
20
+ }
21
+
22
+ // A quoted value, where double quotes understand \n and \", or a bare value up to a " #" comment.
23
+ // Returns null for a quote that isn't closed.
24
+ function parseValue(text) {
25
+ const quote = text[0];
26
+ if (quote === "'" || quote === '"') {
27
+ const end = quote === "'" ? text.indexOf("'", 1) : /(?<!\\)"/.exec(text.slice(1))?.index + 1;
28
+ if (end === undefined || end < 1 || Number.isNaN(end)) return null;
29
+ const inner = text.slice(1, end);
30
+ return quote === "'" ? inner : inner.replace(/\\n/g, "\n").replace(/\\"/g, '"');
31
+ }
32
+ return text.replace(/\s+#.*$/, "").trim();
33
+ }
34
+
35
+ // Loads a folder's .env into process.env, for code that runs on your side. A variable already
36
+ // set in the shell wins. A missing file is fine. Returns warnings to show.
37
+ export function loadEnvFile(dir, env = process.env) {
38
+ let text;
39
+ try {
40
+ text = readFileSync(join(dir, ENV_FILE_NAME), "utf8");
41
+ } catch (err) {
42
+ if (err.code === "ENOENT") return [];
43
+ return [`couldn't read ${ENV_FILE_NAME}: ${err.message}`];
44
+ }
45
+ const { values, bad } = parseEnvFile(text);
46
+ for (const [name, value] of Object.entries(values)) {
47
+ if (env[name] === undefined) env[name] = value;
48
+ }
49
+ return bad.map((line) => `${ENV_FILE_NAME}:${line}: not a KEY=VALUE line, so it was skipped`);
50
+ }
package/src/instance.js CHANGED
@@ -41,9 +41,11 @@ export function readInstance(dir) {
41
41
  }
42
42
 
43
43
  // The bodies sent to POST /v1/agents and POST /v1/environments.
44
- // The agent's tools come from tools/, compiled into the API's `tools` list.
45
- export function agentBody({ agent, tools }) {
44
+ // The agent's tools come from tools/, compiled into the API's `tools` list. `skills` are the
45
+ // references to the skills deployed from skills/, added to any in agent.md's frontmatter.
46
+ export function agentBody({ agent, tools }, skills = []) {
46
47
  const body = { ...agent.data, tools: compileTools(tools) };
48
+ if (skills.length > 0) body.skills = [...(agent.data.skills ?? []), ...skills];
47
49
  if (agent.body) body.system = agent.body;
48
50
  return body;
49
51
  }
package/src/session.js CHANGED
@@ -2,6 +2,7 @@ import { join } from "node:path";
2
2
  import { check } from "./check.js";
3
3
  import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
4
4
  import { LOCK_FILE, hashBody, readLock } from "./lock.js";
5
+ import { skillFingerprint, skillKey, skillRefs } from "./skills.js";
5
6
  import { TOOLS_DIR } from "./tools.js";
6
7
  import { credentialKey, vaultKey } from "./vaults.js";
7
8
 
@@ -26,7 +27,12 @@ export async function openSession(dir, { client, sessionId }) {
26
27
  const notes = [];
27
28
  const { instance, errors } = check(dir);
28
29
  if (instance && errors.length === 0) {
29
- if (hashBody(agentBody(instance)) !== agent.hash) notes.push(`${AGENT_FILE} or ${TOOLS_DIR}/ has changed since the last deploy`);
30
+ if (hashBody(agentBody(instance, skillRefs(instance.skills, lock))) !== agent.hash) {
31
+ notes.push(`${AGENT_FILE} or ${TOOLS_DIR}/ has changed since the last deploy`);
32
+ }
33
+ for (const skill of instance.skills) {
34
+ if (hashBody(skillFingerprint(skill)) !== lock.resources[skillKey(skill)]?.hash) notes.push(`${skill.path} has changed since the last deploy`);
35
+ }
30
36
  if (hashBody(envBody(instance)) !== env.hash) notes.push(`${ENV_FILE} has changed since the last deploy`);
31
37
  if (notes.length > 0) notes.push(`this session uses the deployed version; run agentschema deploy to pick up the changes`);
32
38
  }
package/src/skills.js ADDED
@@ -0,0 +1,79 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { FileError, parseMarkdown } from "./markdown.js";
5
+
6
+ export const SKILLS_DIR = "skills";
7
+ export const SKILL_FILE = "SKILL.md";
8
+ export const MAX_UPLOAD_BYTES = 30 * 1024 * 1024;
9
+
10
+ // Reads skills/: each folder is a skill, with a SKILL.md at its top and any other files it needs,
11
+ // at any depth. Hidden files and node_modules are left out. Skills are sorted by name. A missing
12
+ // skills/ folder means no skills.
13
+ // Returns { skills, errors }; a skill that can't be read has an entry in errors.
14
+ export function readSkills(dir) {
15
+ const folder = join(dir, SKILLS_DIR);
16
+ try {
17
+ if (!statSync(folder).isDirectory()) return { skills: [], errors: [`${SKILLS_DIR}: not a directory`] };
18
+ } catch {
19
+ return { skills: [], errors: [] };
20
+ }
21
+
22
+ const skills = [];
23
+ const errors = [];
24
+ for (const entry of sorted(readdirSync(folder, { withFileTypes: true }))) {
25
+ if (entry.name.startsWith(".")) continue;
26
+ const path = `${SKILLS_DIR}/${entry.name}`;
27
+ if (!entry.isDirectory()) {
28
+ if (entry.name.endsWith(".md")) errors.push(`${path}: each skill is a folder, like ${SKILLS_DIR}/my-skill/${SKILL_FILE}`);
29
+ continue;
30
+ }
31
+
32
+ const files = skillFiles(join(folder, entry.name), "");
33
+ // Compare exact names: macOS file systems would otherwise open skill.md as SKILL.md.
34
+ const main = files.find((f) => f.rel === SKILL_FILE);
35
+ if (!main) {
36
+ const wrongCase = files.find((f) => f.rel.toLowerCase() === SKILL_FILE.toLowerCase());
37
+ errors.push(`${path}: missing ${SKILL_FILE}${wrongCase ? ` (found ${wrongCase.rel}; the name must be uppercase)` : ""}`);
38
+ continue;
39
+ }
40
+ try {
41
+ const parsed = parseMarkdown(main.bytes.toString("utf8"), `${path}/${SKILL_FILE}`);
42
+ skills.push({ name: entry.name, path, file: `${path}/${SKILL_FILE}`, files, ...parsed });
43
+ } catch (err) {
44
+ if (!(err instanceof FileError)) throw err;
45
+ errors.push(err.message);
46
+ }
47
+ }
48
+ return { skills, errors };
49
+ }
50
+
51
+ function skillFiles(folder, prefix) {
52
+ const files = [];
53
+ for (const entry of sorted(readdirSync(folder, { withFileTypes: true }))) {
54
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
55
+ const rel = `${prefix}${entry.name}`;
56
+ if (entry.isDirectory()) files.push(...skillFiles(join(folder, entry.name), `${rel}/`));
57
+ else if (entry.isFile()) files.push({ rel, bytes: readFileSync(join(folder, entry.name)) });
58
+ }
59
+ return files;
60
+ }
61
+
62
+ const sorted = (entries) => entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
63
+
64
+ // The lock file key for a skill.
65
+ export const skillKey = (skill) => `./${skill.path}`;
66
+
67
+ // What's hashed into the lock: each file's path and contents, so any change makes a new version.
68
+ export function skillFingerprint(skill) {
69
+ return { files: skill.files.map((f) => [f.rel, createHash("sha256").update(f.bytes).digest("hex")]) };
70
+ }
71
+
72
+ // The agent's references to the skills deployed from this folder, pinned to their versions, so
73
+ // that a session runs exactly what deploy last sent.
74
+ export function skillRefs(skills = [], lock) {
75
+ return skills
76
+ .map((skill) => lock?.resources?.[skillKey(skill)])
77
+ .filter(Boolean)
78
+ .map((entry) => ({ type: "custom", skill_id: entry.id, version: entry.version }));
79
+ }