@soft-boy/agentschema 0.3.1 → 0.3.2

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/src/check.js CHANGED
@@ -1,363 +1,14 @@
1
- import { AGENT_FILE, ENV_FILE, readInstance } from "./instance.js";
2
- import { MAX_UPLOAD_BYTES, SKILLS_DIR, readSkills } from "./skills.js";
3
- import { MCP_TOOLSET, TOOLS_DIR, checkTools, readTools } from "./tools.js";
4
- import { CREDENTIAL_TYPES, ENV_VAR, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULT_FILE, get, readVaults } from "./vaults.js";
5
-
6
- const AGENT_FIELDS = new Set([
7
- "name", "model", "description", "mcp_servers", "skills",
8
- "multiagent", "metadata", "execution_identity",
9
- ]);
10
- const ENV_FIELDS = new Set(["name", "config", "description", "metadata", "scope"]);
11
-
12
- const SECRET_PATTERNS = [
13
- [/sk-ant-[A-Za-z0-9_-]{8,}/, "an Anthropic API key"],
14
- [/\bghp_[A-Za-z0-9]{20,}/, "a GitHub token"],
15
- [/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token"],
16
- [/\bxox[bpas]-[A-Za-z0-9-]{10,}/, "a Slack token"],
17
- [/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key"],
18
- ];
19
-
20
- const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
21
-
22
- // Validates an instance folder without calling the API.
23
- // Returns { errors, warnings, instance }; instance is null when the files can't be read.
24
- export function check(dir) {
25
- const { agent, env, errors } = readInstance(dir);
26
- const { tools, errors: toolErrors } = readTools(dir);
27
- const { vaults, errors: vaultErrors } = readVaults(dir);
28
- const { skills, errors: skillErrors } = readSkills(dir);
29
- errors.push(...toolErrors, ...vaultErrors, ...skillErrors);
30
- const warnings = [];
31
-
32
- if (agent) checkAgent(agent, errors, warnings);
33
- if (env) checkEnv(env, errors, warnings);
34
- checkTools(tools, errors);
35
- if (agent) checkMcpServers(agent, tools, errors);
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`);
40
- for (const vault of vaults) checkVault(vault, errors, warnings);
41
- checkEnvVarCredentials(vaults, env, warnings);
42
-
43
- const vaultFiles = vaults.flatMap((v) => [...(v.file ? [[`${v.path}/${VAULT_FILE}`, v.file]] : []), ...v.credentials.map((c) => [c.file, c])]);
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]) {
46
- if (!parsed) continue;
47
- for (const [pattern, what] of SECRET_PATTERNS) {
48
- if (pattern.test(parsed.raw)) errors.push(`${file}: looks like it contains ${what}; keep secrets out of these files`);
49
- }
50
- }
51
-
52
- return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills } : null };
53
- }
54
-
55
- function checkAgent({ data, body }, errors, warnings) {
56
- const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
57
-
58
- if (typeof data.name !== "string" || data.name.trim() === "") err("`name` is required");
59
- else if (data.name.length > 256) err("`name` must be at most 256 characters");
60
-
61
- if (data.model === undefined) err("`model` is required");
62
- else if (isObject(data.model) ? typeof data.model.id !== "string" : typeof data.model !== "string") {
63
- err("`model` must be a model ID, or a mapping with an `id`");
64
- }
65
-
66
- if ("system" in data) err("`system` is not allowed in frontmatter; the Markdown body is the system prompt");
67
- if (body.length > 100_000) err(`system prompt is ${body.length} characters; the limit is 100,000`);
68
-
69
- if (data.description !== undefined && data.description !== null) {
70
- if (typeof data.description !== "string") err("`description` must be a string");
71
- else if (data.description.length > 2048) err("`description` must be at most 2048 characters");
72
- }
73
-
74
- if ("tools" in data) err(`\`tools\` is not allowed in frontmatter; define each tool as a file in ${TOOLS_DIR}/`);
75
-
76
- for (const [field, max] of [["mcp_servers", 20], ["skills", 500]]) {
77
- if (data[field] === undefined) continue;
78
- if (!Array.isArray(data[field])) err(`\`${field}\` must be a list`);
79
- else if (data[field].length > max) err(`\`${field}\` has ${data[field].length} entries; the limit is ${max}`);
80
- }
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
-
86
- checkMetadata(data.metadata, 16, err);
87
-
88
- for (const key of Object.keys(data)) {
89
- if (!AGENT_FIELDS.has(key) && key !== "system" && key !== "tools") {
90
- warnings.push(`${AGENT_FILE}: unknown field \`${key}\` will be sent to the API as written`);
91
- }
92
- }
93
- }
94
-
95
- function checkEnv({ data }, errors, warnings) {
96
- const err = (msg) => errors.push(`${ENV_FILE}: ${msg}`);
97
-
98
- if (typeof data.name !== "string" || data.name.trim() === "") err("`name` is required");
99
-
100
- if (data.config !== undefined) {
101
- const { config } = data;
102
- if (!isObject(config)) err("`config` must be a mapping");
103
- else {
104
- if (!["cloud", "self_hosted"].includes(config.type)) err("`config.type` must be `cloud` or `self_hosted`");
105
- const net = config.networking;
106
- if (net !== undefined && !(isObject(net) && ["limited", "unrestricted"].includes(net.type))) {
107
- err("`config.networking.type` must be `limited` or `unrestricted`");
108
- }
109
- }
110
- }
111
-
112
- if (data.description !== undefined && data.description !== null && typeof data.description !== "string") {
113
- err("`description` must be a string");
114
- }
115
-
116
- checkMetadata(data.metadata, Infinity, err);
117
-
118
- for (const key of Object.keys(data)) {
119
- if (!ENV_FIELDS.has(key)) warnings.push(`${ENV_FILE}: unknown field \`${key}\` will be sent to the API as written`);
120
- }
121
- }
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
-
155
- const mcpServers = (agent) => (Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers.filter(isObject) : []);
156
-
157
- // Each server agent.md declares needs a toolset file, and each toolset file a declared server;
158
- // the API rejects an agent otherwise.
159
- function checkMcpServers(agent, tools, errors) {
160
- const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
161
- const names = new Set();
162
- for (const server of mcpServers(agent)) {
163
- const label = typeof server.name === "string" && server.name ? `\`${server.name}\`` : "an entry";
164
- if (server.type !== "url") err(`\`mcp_servers\`: ${label} must have \`type: url\``);
165
- if (typeof server.name !== "string" || server.name === "" || server.name.length > 255) {
166
- err("`mcp_servers`: each server needs a `name` of 1 to 255 characters");
167
- } else if (names.has(server.name)) {
168
- err(`\`mcp_servers\`: \`${server.name}\` is declared twice`);
169
- }
170
- if (typeof server.url !== "string" || !/^https?:\/\/\S+$/.test(server.url) || server.url.length > 2048) {
171
- err(`\`mcp_servers\`: ${label} needs a \`url\`, an http(s) URL of at most 2048 characters`);
172
- }
173
- names.add(server.name);
174
- }
175
-
176
- const toolsets = tools.filter((t) => t.data.type === MCP_TOOLSET);
177
- const covered = new Set(toolsets.map((t) => t.data.mcp_server_name));
178
- for (const name of names) {
179
- if (typeof name === "string" && name && !covered.has(name)) {
180
- err(`\`mcp_servers\`: \`${name}\` has no toolset; add ${TOOLS_DIR}/${name}.md with \`type: mcp_toolset\`, or the API rejects the agent`);
181
- }
182
- }
183
- for (const toolset of toolsets) {
184
- const name = toolset.data.mcp_server_name;
185
- if (typeof name === "string" && name && !names.has(name)) {
186
- errors.push(`${toolset.file}: \`${name}\` isn't in ${AGENT_FILE}'s \`mcp_servers\``);
187
- }
188
- }
189
- }
190
-
191
- // A limited network blocks MCP servers that aren't allowed, and the API then refuses to start sessions.
192
- function checkMcpNetworking(agent, env, warnings) {
193
- const net = env.data.config?.networking;
194
- if (net?.type !== "limited" || net.allow_mcp_servers === true) return;
195
- const allowed = net.allowed_hosts ?? [];
196
- for (const server of mcpServers(agent)) {
197
- let host;
198
- try {
199
- host = new URL(server.url).host;
200
- } catch {
201
- continue;
202
- }
203
- if (!allowed.includes(host)) {
204
- warnings.push(
205
- `${ENV_FILE}: its limited networking doesn't allow MCP server \`${server.name}\` (${host}), so sessions won't start; ` +
206
- `set config.networking.allow_mcp_servers to true, or add ${host} to allowed_hosts`,
207
- );
208
- }
209
- }
210
- }
211
-
212
- function checkVault(vault, errors, warnings) {
213
- if (vault.name.length > 255) errors.push(`${vault.path}: a vault's name (its folder name) must be at most 255 characters`);
214
-
215
- if (vault.file) {
216
- const file = `${vault.path}/${VAULT_FILE}`;
217
- const err = (msg) => errors.push(`${file}: ${msg}`);
218
- const { data } = vault.file;
219
- if ("display_name" in data) err("`display_name` is not allowed; the folder name is the vault's name");
220
- checkMetadata(data.metadata, 16, err);
221
- for (const key of Object.keys(data)) {
222
- if (key !== "metadata" && key !== "display_name") warnings.push(`${file}: unknown field \`${key}\` will be sent to the API as written`);
223
- }
224
- }
225
-
226
- if (vault.credentials.length > 20) errors.push(`${vault.path}: ${vault.credentials.length} credentials; a vault holds at most 20`);
227
- const urls = new Map();
228
- const secretNames = new Map();
229
- for (const cred of vault.credentials) {
230
- checkCredential(cred, errors, warnings);
231
- const url = cred.data.auth?.mcp_server_url;
232
- if (typeof url === "string") {
233
- if (urls.has(url)) errors.push(`${cred.file}: ${urls.get(url)} is already a credential for ${url}; a vault holds one per server`);
234
- else urls.set(url, cred.file);
235
- }
236
- const secretName = cred.data.auth?.secret_name;
237
- if (typeof secretName === "string") {
238
- if (secretNames.has(secretName)) errors.push(`${cred.file}: ${secretNames.get(secretName)} already sets ${secretName}; a vault holds one per variable`);
239
- else secretNames.set(secretName, cred.file);
240
- }
241
- }
242
- }
243
-
244
- // What an environment variable credential depends on outside its own file.
245
- function checkEnvVarCredentials(vaults, env, warnings) {
246
- const creds = vaults.flatMap((v) => v.credentials).filter((c) => c.data.auth?.type === ENV_VAR);
247
- const net = env?.data.config?.networking;
248
- const seen = new Map();
249
- for (const cred of creds) {
250
- const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
251
- const { secret_name: name, networking } = cred.data.auth;
252
-
253
- // Two vaults can both set a variable, but the docs don't say which one wins.
254
- if (typeof name === "string") {
255
- if (seen.has(name) && seen.get(name).vault !== cred.vault) warn(`${seen.get(name).file} also sets ${name}, and the API doesn't document which vault wins`);
256
- else seen.set(name, cred);
257
- }
258
-
259
- if (env?.data.config?.type === "self_hosted") warn("environment variable credentials aren't supported on self-hosted environments yet");
260
-
261
- // allowed_hosts only decides where the secret is substituted; the environment decides what's reachable.
262
- if (net?.type === "limited" && networking?.type === "limited" && Array.isArray(networking.allowed_hosts)) {
263
- for (const host of networking.allowed_hosts) {
264
- if (!(net.allowed_hosts ?? []).includes(host)) {
265
- warn(`${ENV_FILE}'s limited networking doesn't allow ${host}, so requests to it will be blocked; add it to allowed_hosts in ${ENV_FILE}`);
266
- }
267
- }
268
- }
269
- }
270
- }
271
-
272
- function checkCredential(cred, errors, warnings) {
273
- const err = (msg) => errors.push(`${cred.file}: ${msg}`);
274
- const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
275
- const { data } = cred;
276
- if (cred.name.length > 255) err("a credential's name (its file name) must be at most 255 characters");
277
- if ("display_name" in data) err("`display_name` is not allowed; the file name is the credential's name");
278
- checkMetadata(data.metadata, 16, err);
279
- for (const key of Object.keys(data)) {
280
- if (!["auth", "metadata", "display_name"].includes(key)) warn(`unknown field \`${key}\` will be sent to the API as written`);
281
- }
282
-
283
- const { auth } = data;
284
- if (!isObject(auth)) return err("`auth` is required");
285
- if (!CREDENTIAL_TYPES.includes(auth.type)) return err(`\`auth.type\` must be ${CREDENTIAL_TYPES.map((t) => `\`${t}\``).join(" or ")}; other credential types aren't supported yet`);
286
-
287
- for (const path of SECRET_FIELDS[auth.type]) {
288
- if (get(auth, path) !== undefined) {
289
- err(`\`auth.${path.join(".")}\` doesn't go in the file; \`agentschema cred deploy\` asks for it and sends it straight to the vault`);
290
- }
291
- }
292
-
293
- if (auth.type === ENV_VAR) return checkEnvVarAuth(auth, err, warn);
294
-
295
- const url = (value, field) => {
296
- if (typeof value !== "string" || value === "") return err(`\`${field}\` is required`);
297
- if (!/^https?:\/\/\S+$/.test(value)) err(`\`${field}\` must be an http(s) URL`);
298
- };
299
- url(auth.mcp_server_url, "auth.mcp_server_url");
300
- for (const key of Object.keys(auth)) {
301
- if (!["type", "mcp_server_url", "refresh", "access_token", "expires_at"].includes(key)) {
302
- warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
303
- }
304
- }
305
-
306
- if (auth.refresh === undefined || auth.refresh === null) return;
307
- const { refresh } = auth;
308
- if (!isObject(refresh)) return err("`auth.refresh` must be a mapping");
309
- url(refresh.token_endpoint, "auth.refresh.token_endpoint");
310
- if (typeof refresh.client_id !== "string" || refresh.client_id === "") err("`auth.refresh.client_id` is required, as a string (quote it if it looks like a number)");
311
- for (const field of ["scope", "resource"]) {
312
- if (refresh[field] !== undefined && typeof refresh[field] !== "string") err(`\`auth.refresh.${field}\` must be a string`);
313
- }
314
- if (!isObject(refresh.token_endpoint_auth) || !TOKEN_ENDPOINT_AUTH.includes(refresh.token_endpoint_auth.type)) {
315
- err(`\`auth.refresh.token_endpoint_auth.type\` must be ${TOKEN_ENDPOINT_AUTH.map((t) => `\`${t}\``).join(", ")}`);
316
- }
317
- for (const key of Object.keys(refresh)) {
318
- if (!["token_endpoint", "client_id", "scope", "resource", "token_endpoint_auth", "refresh_token"].includes(key)) {
319
- warn(`unknown field \`auth.refresh.${key}\` will be sent to the API as written`);
320
- }
321
- }
322
- }
323
-
324
- function checkEnvVarAuth(auth, err, warn) {
325
- if (typeof auth.secret_name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(auth.secret_name)) {
326
- err("`auth.secret_name` is required, and must be a variable name like STRIPE_API_KEY");
327
- }
328
-
329
- const { networking: net, injection_location: where } = auth;
330
- if (!isObject(net) || !["limited", "unrestricted"].includes(net.type)) {
331
- err("`auth.networking.type` is required, and must be `limited` or `unrestricted`");
332
- } else if (net.type === "unrestricted") {
333
- warn("`auth.networking` is `unrestricted`, so the secret is substituted on requests to any host; a prompt-injected agent could send it anywhere");
334
- } else if (!Array.isArray(net.allowed_hosts) || net.allowed_hosts.length === 0 || net.allowed_hosts.some((h) => typeof h !== "string" || h === "")) {
335
- err("`auth.networking.allowed_hosts` must list the hosts the secret may be sent to");
336
- }
337
-
338
- if (where !== undefined && where !== null) {
339
- if (!isObject(where)) err("`auth.injection_location` must be a mapping");
340
- else {
341
- for (const field of ["header", "body"]) {
342
- if (where[field] !== undefined && typeof where[field] !== "boolean") err(`\`auth.injection_location.${field}\` must be true or false`);
343
- }
344
- if (where.header !== true && where.body !== true) err("`auth.injection_location` must enable `header` or `body`; a field you leave out is false");
345
- }
346
- }
347
-
348
- for (const key of Object.keys(auth)) {
349
- if (!["type", "secret_name", "secret_value", "networking", "injection_location"].includes(key)) {
350
- warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
351
- }
352
- }
353
- }
354
-
355
- function checkMetadata(metadata, maxKeys, err) {
356
- if (metadata === undefined) return;
357
- if (!isObject(metadata)) return err("`metadata` must be a mapping");
358
- const keys = Object.keys(metadata);
359
- if (keys.length > maxKeys) err(`\`metadata\` has ${keys.length} keys; the limit is ${maxKeys}`);
360
- for (const key of keys) {
361
- if (typeof metadata[key] !== "string") err(`\`metadata.${key}\` must be a string (quote numbers and booleans)`);
362
- }
1
+ import { resolve } from "node:path";
2
+ import { checkFiles } from "../lib/check.js";
3
+ import { folderProblem, readFolder } from "./folder.js";
4
+
5
+ // Validates an agent folder without calling the API. See checkFiles for what it returns.
6
+ export function check(dir, options) {
7
+ const problem = folderProblem(dir);
8
+ if (problem) return { errors: [problem], warnings: [], instance: null };
9
+
10
+ const result = checkFiles(readFolder(dir), options);
11
+ // Where each tool's code lives, so its require() calls can resolve from there.
12
+ for (const tool of result.instance?.tools ?? []) tool.path = resolve(dir, tool.file);
13
+ return result;
363
14
  }
package/src/cred-menu.js CHANGED
@@ -5,7 +5,7 @@ import { check } from "./check.js";
5
5
  import { credLogin, credPaste, locate } from "./cred.js";
6
6
  import { DeployError } from "./deploy.js";
7
7
  import { discover } from "./oauth.js";
8
- import { ENV_VAR, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE } from "./vaults.js";
8
+ import { ENV_VAR, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE } from "../lib/vaults.js";
9
9
 
10
10
  const SIGN_IN = "Sign in with the browser";
11
11
  const PASTE = "Paste the tokens";
package/src/cred.js CHANGED
@@ -3,12 +3,12 @@ import Anthropic from "@anthropic-ai/sdk";
3
3
  import { check } from "./check.js";
4
4
  import { DeployError, call, openLock, retrieve } from "./deploy.js";
5
5
  import { LOCK_FILE, hashBody, writeLock } from "./lock.js";
6
- import { updateFrontmatter } from "./markdown.js";
6
+ import { updateFrontmatter } from "./folder.js";
7
7
  import { authorizationRequest, discover, exchangeCode, registerClient, startCallbackServer } from "./oauth.js";
8
8
  import {
9
9
  ENV_VAR, VAULTS_DIR, VAULT_FILE, changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings,
10
10
  secretsNeeded, vaultBody, vaultKey,
11
- } from "./vaults.js";
11
+ } from "../lib/vaults.js";
12
12
 
13
13
  // Finds the agent folder and the credential a path like my-agent/vaults/Ops/slack.md names.
14
14
  export function locate(path) {
@@ -0,0 +1,17 @@
1
+ import { createRequire } from "node:module";
2
+ import { resolve } from "node:path";
3
+ import { runInThisContext } from "node:vm";
4
+ import { wrapToolCode } from "../lib/tools.js";
5
+
6
+ // Loads a custom tool's code as a CommonJS module whose module.exports is the function.
7
+ // require() resolves relative to the tool's file, so the agent folder's node_modules work.
8
+ // The code runs with this process's full access, so only use this on your own machine.
9
+ export function loadTool(tool) {
10
+ const module = { exports: {} };
11
+ const fn = runInThisContext(wrapToolCode(tool.code.source), { filename: tool.path });
12
+ fn(module.exports, createRequire(tool.path), module, tool.path, resolve(tool.path, ".."));
13
+ if (typeof module.exports !== "function") {
14
+ throw new Error(`${tool.file}: module.exports must be a function`);
15
+ }
16
+ return module.exports;
17
+ }
package/src/deploy.js CHANGED
@@ -1,23 +1,57 @@
1
1
  import { join } from "node:path";
2
2
  import Anthropic, { toFile } from "@anthropic-ai/sdk";
3
- import { check } from "./check.js";
4
- import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
5
- import { LOCK_FILE, hashBody, readLock, writeLock } from "./lock.js";
6
- import { skillFingerprint, skillKey, skillRefs } from "./skills.js";
7
- import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey } from "./vaults.js";
3
+ import { checkFiles } from "../lib/check.js";
4
+ import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "../lib/instance.js";
5
+ import { skillKey, skillRefs } from "../lib/skills.js";
6
+ import { AGENTBOOK } from "../lib/tools.js";
7
+ import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey } from "../lib/vaults.js";
8
+ import { folderProblem, readFolder } from "./folder.js";
9
+ import { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
8
10
 
9
11
  export class DeployError extends Error {}
10
12
 
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
13
- // that's `cred deploy`'s job.
14
- // Returns the plan: one { file, kind, action, id, version } entry per resource.
13
+ // Deploys an agent folder, keeping the lock in its claude-lock.json. Returns the plan: one
14
+ // { file, kind, action, id, version } entry per resource.
15
15
  export async function deploy(dir, { client, dryRun = false, force = false, log = () => {} }) {
16
- const { errors, instance } = check(dir);
16
+ const problem = folderProblem(dir);
17
+ if (problem) throw new DeployError(`check failed:\n ${problem}`);
18
+ const { plan } = await deployFiles({
19
+ files: readFolder(dir),
20
+ lock: readLock(dir),
21
+ client,
22
+ dryRun,
23
+ force,
24
+ log,
25
+ saveLock: (lock) => writeLock(dir, lock),
26
+ pathOf: (file) => join(dir, file),
27
+ });
28
+ return plan;
29
+ }
30
+
31
+ // Creates or updates the skills, environment, agent and vaults in a file map (see lib/files.js).
32
+ // Skills go first, because the agent refers to their IDs and versions. Credentials are only
33
+ // updated here: creating one needs its secrets, so that's `cred deploy`'s job.
34
+ //
35
+ // lock the IDs from the last deploy, or null for a first deploy
36
+ // saveLock called with the lock as soon as each resource exists, so a failure later
37
+ // doesn't orphan it; it may be async
38
+ // checkOptions what checkFiles takes: { customTools, toolsets }
39
+ // pathOf how to show a file's path to the user in messages
40
+ //
41
+ // Returns { plan, lock }. A dry run calls neither the API nor saveLock.
42
+ export async function deployFiles({
43
+ files, lock: previous = null, client, dryRun = false, force = false, log = () => {},
44
+ saveLock = () => {}, checkOptions = {}, pathOf = (file) => file,
45
+ }) {
46
+ const { errors, instance } = checkFiles(files, checkOptions);
17
47
  if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
18
- const lock = openLock(dir, client);
48
+ const agentbook = instance.tools.find((t) => t.data.type === AGENTBOOK);
49
+ if (agentbook && !checkOptions.toolsets) {
50
+ throw new DeployError(`${agentbook.file}: this toolset runs on agentbook, so it can only be deployed from there`);
51
+ }
52
+ const lock = prepareLock(previous, client);
19
53
 
20
- const skillSteps = await deploySkills(instance.skills, { dir, client, lock, dryRun, log });
54
+ const skillSteps = await deploySkills(instance.skills, { client, lock, dryRun, log, saveLock });
21
55
  // A dry run has no new IDs or versions yet, so a stand-in shows that the agent will change too.
22
56
  const pending = dryRun ? skillSteps.filter((s) => s.action !== "unchanged") : [];
23
57
  const refs = instance.skills.flatMap((skill) => {
@@ -28,7 +62,7 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
28
62
 
29
63
  const steps = [
30
64
  { file: ENV_FILE, kind: "environment", body: envBody(instance) },
31
- { file: AGENT_FILE, kind: "agent", body: agentBody(instance, refs) },
65
+ { file: AGENT_FILE, kind: "agent", body: agentBody(instance, refs, checkOptions) },
32
66
  ];
33
67
  for (const step of steps) {
34
68
  step.key = `./${step.file}`;
@@ -53,25 +87,29 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
53
87
  ? { kind: "agent", id: result.id, version: String(result.version), hash: step.hash }
54
88
  : { kind: "environment", id: result.id, hash: step.hash };
55
89
  // Record each resource as soon as it exists, so a failure later doesn't orphan it.
56
- writeLock(dir, lock);
90
+ await saveLock(lock);
57
91
 
58
92
  const version = step.kind === "agent" ? ` (version ${result.version})` : "";
59
93
  log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}${version}`);
60
94
  }
61
95
 
62
- const vaultSteps = await deployVaults(dir, instance.vaults, { client, lock, dryRun, log });
96
+ const vaultSteps = await deployVaults(instance.vaults, { client, lock, dryRun, log, saveLock, pathOf });
63
97
 
64
- return [...skillSteps, ...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
98
+ const plan = [...skillSteps, ...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
65
99
  file, kind, action,
66
100
  id: lock.resources[key]?.id,
67
101
  version: lock.resources[key]?.version,
68
102
  }));
103
+ return { plan, lock };
69
104
  }
70
105
 
71
- // Reads claude-lock.json, or starts a new one, and checks it was written for this API.
72
- export function openLock(dir, client) {
106
+ // Reads claude-lock.json, or starts a new lock, and checks it was written for this API.
107
+ export const openLock = (dir, client) => prepareLock(readLock(dir), client);
108
+
109
+ // The lock to deploy with: the one given, or a new one, after checking it's for this API.
110
+ export function prepareLock(previous, client) {
73
111
  const baseURL = client.baseURL;
74
- const lock = readLock(dir) ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
112
+ const lock = previous ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
75
113
  lock.resources ??= {};
76
114
  if (lock.origin?.base_url && lock.origin.base_url !== baseURL) {
77
115
  throw new DeployError(
@@ -82,7 +120,7 @@ export function openLock(dir, client) {
82
120
  }
83
121
 
84
122
  // 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 }) {
123
+ async function deploySkills(skills, { client, lock, dryRun, log, saveLock }) {
86
124
  const steps = [];
87
125
  for (const skill of skills) {
88
126
  const step = planStep(lock, { file: skill.path, key: skillKey(skill), kind: "skill", body: skillFingerprint(skill) });
@@ -105,7 +143,7 @@ async function deploySkills(skills, { dir, client, lock, dryRun, log }) {
105
143
  ({ id: version } = await call(step, () => client.skills.versions.create(id, { files })));
106
144
  }
107
145
  lock.resources[step.key] = { kind: "skill", id, version, hash: step.hash };
108
- writeLock(dir, lock);
146
+ await saveLock(lock);
109
147
  log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} skill ${id} (version ${version})`);
110
148
  }
111
149
  return steps;
@@ -113,7 +151,7 @@ async function deploySkills(skills, { dir, client, lock, dryRun, log }) {
113
151
 
114
152
  // Creates or updates each vault, then updates the settings of credentials already created.
115
153
  // A credential file with no credential yet is reported, not created: that needs its secrets.
116
- async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
154
+ async function deployVaults(vaults, { client, lock, dryRun, log, saveLock, pathOf }) {
117
155
  const steps = [];
118
156
  for (const vault of vaults) {
119
157
  const step = planStep(lock, { file: vault.path, key: vaultKey(vault), kind: "vault", body: vaultBody(vault) });
@@ -138,7 +176,7 @@ async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
138
176
  if (changed.length > 0) {
139
177
  throw new DeployError(
140
178
  `${step.file}: ${changed.map((f) => `\`auth.${f}\``).join(", ")} can't be changed on an existing credential. ` +
141
- `Delete it with \`agentschema cred delete ${join(dir, step.file)}\`, then create it again with \`agentschema cred deploy\`.`,
179
+ `Delete it with \`agentschema cred delete ${pathOf(step.file)}\`, then create it again with \`agentschema cred deploy\`.`,
142
180
  );
143
181
  }
144
182
  step.remote = remote;
@@ -147,7 +185,7 @@ async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
147
185
 
148
186
  for (const step of steps) {
149
187
  if (step.action === "missing") {
150
- log(`missing credential ${step.file} (create it with: agentschema cred deploy ${join(dir, step.file)})`);
188
+ log(`missing credential ${step.file} (create it with: agentschema cred deploy ${pathOf(step.file)})`);
151
189
  continue;
152
190
  }
153
191
  if (dryRun || step.action === "unchanged") {
@@ -169,7 +207,7 @@ async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
169
207
  result = await call(step, () => client.beta.vaults.credentials.update(step.entry.id, credentialUpdateBody(step)));
170
208
  lock.resources[step.key] = { ...step.entry, hash: step.hash };
171
209
  }
172
- writeLock(dir, lock);
210
+ await saveLock(lock);
173
211
  log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}`);
174
212
  }
175
213
  return steps;
package/src/folder.js ADDED
@@ -0,0 +1,52 @@
1
+ import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { editFrontmatter } from "../lib/markdown.js";
4
+ import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
5
+ import { SKILLS_DIR } from "../lib/skills.js";
6
+ import { TOOLS_DIR } from "../lib/tools.js";
7
+ import { VAULTS_DIR } from "../lib/vaults.js";
8
+
9
+ const FOLDERS = [TOOLS_DIR, SKILLS_DIR, VAULTS_DIR];
10
+ const TOP_LEVEL_FILES = [AGENT_FILE, ENV_FILE];
11
+
12
+ // Why `dir` can't be read as an agent folder, or null when it can.
13
+ export function folderProblem(dir) {
14
+ try {
15
+ return statSync(dir).isDirectory() ? null : `${dir}: not a directory`;
16
+ } catch {
17
+ return `${dir}: no such directory`;
18
+ }
19
+ }
20
+
21
+ // Reads an agent folder into a file map (see lib/files.js), as bytes. Only the agent's own files
22
+ // are read, so empty folders, hidden files and node_modules aren't part of it.
23
+ export function readFolder(dir) {
24
+ const files = {};
25
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
26
+ const path = join(dir, entry.name);
27
+ if (FOLDERS.includes(entry.name)) {
28
+ if (statSync(path).isDirectory()) walk(path, entry.name, files, entry.name !== SKILLS_DIR);
29
+ else files[entry.name] = readFileSync(path);
30
+ } else if (TOP_LEVEL_FILES.includes(entry.name.toLowerCase()) && !statSync(path).isDirectory()) {
31
+ files[entry.name] = readFileSync(path);
32
+ }
33
+ }
34
+ return files;
35
+ }
36
+
37
+ // Everything in a skill's folder gets uploaded, so links there aren't followed, in case one
38
+ // points outside the agent.
39
+ function walk(folder, prefix, files, followLinks) {
40
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
41
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
42
+ const path = join(folder, entry.name);
43
+ const rel = `${prefix}/${entry.name}`;
44
+ if (entry.isDirectory()) walk(path, rel, files, followLinks);
45
+ else if (entry.isFile() || (followLinks && entry.isSymbolicLink() && statSync(path).isFile())) files[rel] = readFileSync(path);
46
+ }
47
+ }
48
+
49
+ // Edits a file's frontmatter on disk, keeping its comments and the rest of the file.
50
+ export function updateFrontmatter(file, edit) {
51
+ writeFileSync(file, editFrontmatter(readFileSync(file, "utf8"), edit));
52
+ }