@soft-boy/agentschema 0.3.0 → 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/lib/check.js ADDED
@@ -0,0 +1,365 @@
1
+ import { textOf } from "./files.js";
2
+ import { AGENT_FILE, ENV_FILE, readInstance } from "./instance.js";
3
+ import { MAX_UPLOAD_BYTES, SKILLS_DIR, readSkills } from "./skills.js";
4
+ import { MCP_TOOLSET, TOOLS_DIR, checkTools, readTools } from "./tools.js";
5
+ import { CREDENTIAL_TYPES, ENV_VAR, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULT_FILE, get, readVaults } from "./vaults.js";
6
+
7
+ const AGENT_FIELDS = new Set([
8
+ "name", "model", "description", "mcp_servers", "skills",
9
+ "multiagent", "metadata", "execution_identity",
10
+ ]);
11
+ const ENV_FIELDS = new Set(["name", "config", "description", "metadata", "scope"]);
12
+
13
+ const SECRET_PATTERNS = [
14
+ [/sk-ant-[A-Za-z0-9_-]{8,}/, "an Anthropic API key"],
15
+ [/\bghp_[A-Za-z0-9]{20,}/, "a GitHub token"],
16
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token"],
17
+ [/\bxox[bpas]-[A-Za-z0-9-]{10,}/, "a Slack token"],
18
+ [/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key"],
19
+ ];
20
+
21
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
22
+
23
+ // Validates an agent's files without calling the API. `files` is a file map (see files.js), and
24
+ // `options` is what checkTools takes: { customTools, toolsets }.
25
+ // Returns { errors, warnings, instance }; instance is null when the files can't be read.
26
+ export function checkFiles(files, options = {}) {
27
+ const { agent, env, errors } = readInstance(files);
28
+ const { tools, errors: toolErrors } = readTools(files);
29
+ const { vaults, errors: vaultErrors } = readVaults(files);
30
+ const { skills, errors: skillErrors } = readSkills(files);
31
+ errors.push(...toolErrors, ...vaultErrors, ...skillErrors);
32
+ const warnings = [];
33
+
34
+ if (agent) checkAgent(agent, errors, warnings);
35
+ if (env) checkEnv(env, errors, warnings);
36
+ checkTools(tools, errors, warnings, options);
37
+ if (agent) checkMcpServers(agent, tools, errors);
38
+ if (agent && env) checkMcpNetworking(agent, env, warnings);
39
+ for (const skill of skills) checkSkill(skill, errors);
40
+ const declaredSkills = Array.isArray(agent?.data.skills) ? agent.data.skills.length : 0;
41
+ if (declaredSkills + skills.length > 500) errors.push(`${declaredSkills + skills.length} skills; the limit is 500`);
42
+ for (const vault of vaults) checkVault(vault, errors, warnings);
43
+ checkEnvVarCredentials(vaults, env, warnings);
44
+
45
+ const vaultFiles = vaults.flatMap((v) => [...(v.file ? [[`${v.path}/${VAULT_FILE}`, v.file]] : []), ...v.credentials.map((c) => [c.file, c])]);
46
+ const skillTexts = skills.flatMap((s) => s.files.map((f) => [`${s.path}/${f.rel}`, { raw: textOf(f.bytes) }]));
47
+ for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t]), ...vaultFiles, ...skillTexts]) {
48
+ if (!parsed) continue;
49
+ for (const [pattern, what] of SECRET_PATTERNS) {
50
+ if (pattern.test(parsed.raw)) errors.push(`${file}: looks like it contains ${what}; keep secrets out of these files`);
51
+ }
52
+ }
53
+
54
+ return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills } : null };
55
+ }
56
+
57
+ function checkAgent({ data, body }, errors, warnings) {
58
+ const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
59
+
60
+ if (typeof data.name !== "string" || data.name.trim() === "") err("`name` is required");
61
+ else if (data.name.length > 256) err("`name` must be at most 256 characters");
62
+
63
+ if (data.model === undefined) err("`model` is required");
64
+ else if (isObject(data.model) ? typeof data.model.id !== "string" : typeof data.model !== "string") {
65
+ err("`model` must be a model ID, or a mapping with an `id`");
66
+ }
67
+
68
+ if ("system" in data) err("`system` is not allowed in frontmatter; the Markdown body is the system prompt");
69
+ if (body.length > 100_000) err(`system prompt is ${body.length} characters; the limit is 100,000`);
70
+
71
+ if (data.description !== undefined && data.description !== null) {
72
+ if (typeof data.description !== "string") err("`description` must be a string");
73
+ else if (data.description.length > 2048) err("`description` must be at most 2048 characters");
74
+ }
75
+
76
+ if ("tools" in data) err(`\`tools\` is not allowed in frontmatter; define each tool as a file in ${TOOLS_DIR}/`);
77
+
78
+ for (const [field, max] of [["mcp_servers", 20], ["skills", 500]]) {
79
+ if (data[field] === undefined) continue;
80
+ if (!Array.isArray(data[field])) err(`\`${field}\` must be a list`);
81
+ else if (data[field].length > max) err(`\`${field}\` has ${data[field].length} entries; the limit is ${max}`);
82
+ }
83
+
84
+ if (Array.isArray(data.skills)) {
85
+ for (const [index, skill] of data.skills.entries()) checkSkillRef(skill, (msg) => err(`\`skills[${index}]\`: ${msg}`));
86
+ }
87
+
88
+ checkMetadata(data.metadata, 16, err);
89
+
90
+ for (const key of Object.keys(data)) {
91
+ if (!AGENT_FIELDS.has(key) && key !== "system" && key !== "tools") {
92
+ warnings.push(`${AGENT_FILE}: unknown field \`${key}\` will be sent to the API as written`);
93
+ }
94
+ }
95
+ }
96
+
97
+ function checkEnv({ data }, errors, warnings) {
98
+ const err = (msg) => errors.push(`${ENV_FILE}: ${msg}`);
99
+
100
+ if (typeof data.name !== "string" || data.name.trim() === "") err("`name` is required");
101
+
102
+ if (data.config !== undefined) {
103
+ const { config } = data;
104
+ if (!isObject(config)) err("`config` must be a mapping");
105
+ else {
106
+ if (!["cloud", "self_hosted"].includes(config.type)) err("`config.type` must be `cloud` or `self_hosted`");
107
+ const net = config.networking;
108
+ if (net !== undefined && !(isObject(net) && ["limited", "unrestricted"].includes(net.type))) {
109
+ err("`config.networking.type` must be `limited` or `unrestricted`");
110
+ }
111
+ }
112
+ }
113
+
114
+ if (data.description !== undefined && data.description !== null && typeof data.description !== "string") {
115
+ err("`description` must be a string");
116
+ }
117
+
118
+ checkMetadata(data.metadata, Infinity, err);
119
+
120
+ for (const key of Object.keys(data)) {
121
+ if (!ENV_FIELDS.has(key)) warnings.push(`${ENV_FILE}: unknown field \`${key}\` will be sent to the API as written`);
122
+ }
123
+ }
124
+
125
+ // An entry in agent.md's `skills` list, in the API's shape.
126
+ function checkSkillRef(skill, err) {
127
+ if (typeof skill === "string") {
128
+ return err(`write this as a mapping with \`type\` and \`skill_id\`; a skill in ${SKILLS_DIR}/ is attached without being listed`);
129
+ }
130
+ if (!isObject(skill)) return err("must be a mapping with `type` and `skill_id`");
131
+ if (!["anthropic", "custom"].includes(skill.type)) err("`type` must be `anthropic` or `custom`");
132
+ if (typeof skill.skill_id !== "string" || skill.skill_id === "") err("`skill_id` is required");
133
+ else if (skill.type === "custom" && !skill.skill_id.startsWith("skill_")) err("a custom skill's `skill_id` starts with skill_");
134
+ if (skill.version !== undefined && skill.version !== null && typeof skill.version !== "string") {
135
+ err("`version` must be a string (quote numbers)");
136
+ }
137
+ }
138
+
139
+ function checkSkill(skill, errors) {
140
+ const err = (msg) => errors.push(`${skill.file}: ${msg}`);
141
+ const { name, description } = skill.data;
142
+ if (typeof name !== "string" || name === "") err("`name` is required");
143
+ else {
144
+ if (name !== skill.name) err(`\`name\` must match the folder's name (${skill.name})`);
145
+ if (!/^[a-z0-9-]{1,64}$/.test(name)) err("`name` may only use lowercase letters, digits and hyphens, up to 64 characters");
146
+ if (/anthropic|claude/.test(name)) err("`name` can't contain the reserved words `anthropic` or `claude`");
147
+ }
148
+ if (typeof description !== "string" || description.trim() === "") err("`description` is required");
149
+ else {
150
+ if (description.length > 1024) err(`\`description\` is ${description.length} characters; the limit is 1,024`);
151
+ if (/<[^>]+>/.test(description)) err("`description` can't contain XML tags");
152
+ }
153
+ const size = skill.files.reduce((total, f) => total + f.bytes.length, 0);
154
+ 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`);
155
+ }
156
+
157
+ const mcpServers = (agent) => (Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers.filter(isObject) : []);
158
+
159
+ // Each server agent.md declares needs a toolset file, and each toolset file a declared server;
160
+ // the API rejects an agent otherwise.
161
+ function checkMcpServers(agent, tools, errors) {
162
+ const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
163
+ const names = new Set();
164
+ for (const server of mcpServers(agent)) {
165
+ const label = typeof server.name === "string" && server.name ? `\`${server.name}\`` : "an entry";
166
+ if (server.type !== "url") err(`\`mcp_servers\`: ${label} must have \`type: url\``);
167
+ if (typeof server.name !== "string" || server.name === "" || server.name.length > 255) {
168
+ err("`mcp_servers`: each server needs a `name` of 1 to 255 characters");
169
+ } else if (names.has(server.name)) {
170
+ err(`\`mcp_servers\`: \`${server.name}\` is declared twice`);
171
+ }
172
+ if (typeof server.url !== "string" || !/^https?:\/\/\S+$/.test(server.url) || server.url.length > 2048) {
173
+ err(`\`mcp_servers\`: ${label} needs a \`url\`, an http(s) URL of at most 2048 characters`);
174
+ }
175
+ names.add(server.name);
176
+ }
177
+
178
+ const toolsets = tools.filter((t) => t.data.type === MCP_TOOLSET);
179
+ const covered = new Set(toolsets.map((t) => t.data.mcp_server_name));
180
+ for (const name of names) {
181
+ if (typeof name === "string" && name && !covered.has(name)) {
182
+ err(`\`mcp_servers\`: \`${name}\` has no toolset; add ${TOOLS_DIR}/${name}.md with \`type: mcp_toolset\`, or the API rejects the agent`);
183
+ }
184
+ }
185
+ for (const toolset of toolsets) {
186
+ const name = toolset.data.mcp_server_name;
187
+ if (typeof name === "string" && name && !names.has(name)) {
188
+ errors.push(`${toolset.file}: \`${name}\` isn't in ${AGENT_FILE}'s \`mcp_servers\``);
189
+ }
190
+ }
191
+ }
192
+
193
+ // A limited network blocks MCP servers that aren't allowed, and the API then refuses to start sessions.
194
+ function checkMcpNetworking(agent, env, warnings) {
195
+ const net = env.data.config?.networking;
196
+ if (net?.type !== "limited" || net.allow_mcp_servers === true) return;
197
+ const allowed = net.allowed_hosts ?? [];
198
+ for (const server of mcpServers(agent)) {
199
+ let host;
200
+ try {
201
+ host = new URL(server.url).host;
202
+ } catch {
203
+ continue;
204
+ }
205
+ if (!allowed.includes(host)) {
206
+ warnings.push(
207
+ `${ENV_FILE}: its limited networking doesn't allow MCP server \`${server.name}\` (${host}), so sessions won't start; ` +
208
+ `set config.networking.allow_mcp_servers to true, or add ${host} to allowed_hosts`,
209
+ );
210
+ }
211
+ }
212
+ }
213
+
214
+ function checkVault(vault, errors, warnings) {
215
+ if (vault.name.length > 255) errors.push(`${vault.path}: a vault's name (its folder name) must be at most 255 characters`);
216
+
217
+ if (vault.file) {
218
+ const file = `${vault.path}/${VAULT_FILE}`;
219
+ const err = (msg) => errors.push(`${file}: ${msg}`);
220
+ const { data } = vault.file;
221
+ if ("display_name" in data) err("`display_name` is not allowed; the folder name is the vault's name");
222
+ checkMetadata(data.metadata, 16, err);
223
+ for (const key of Object.keys(data)) {
224
+ if (key !== "metadata" && key !== "display_name") warnings.push(`${file}: unknown field \`${key}\` will be sent to the API as written`);
225
+ }
226
+ }
227
+
228
+ if (vault.credentials.length > 20) errors.push(`${vault.path}: ${vault.credentials.length} credentials; a vault holds at most 20`);
229
+ const urls = new Map();
230
+ const secretNames = new Map();
231
+ for (const cred of vault.credentials) {
232
+ checkCredential(cred, errors, warnings);
233
+ const url = cred.data.auth?.mcp_server_url;
234
+ if (typeof url === "string") {
235
+ if (urls.has(url)) errors.push(`${cred.file}: ${urls.get(url)} is already a credential for ${url}; a vault holds one per server`);
236
+ else urls.set(url, cred.file);
237
+ }
238
+ const secretName = cred.data.auth?.secret_name;
239
+ if (typeof secretName === "string") {
240
+ if (secretNames.has(secretName)) errors.push(`${cred.file}: ${secretNames.get(secretName)} already sets ${secretName}; a vault holds one per variable`);
241
+ else secretNames.set(secretName, cred.file);
242
+ }
243
+ }
244
+ }
245
+
246
+ // What an environment variable credential depends on outside its own file.
247
+ function checkEnvVarCredentials(vaults, env, warnings) {
248
+ const creds = vaults.flatMap((v) => v.credentials).filter((c) => c.data.auth?.type === ENV_VAR);
249
+ const net = env?.data.config?.networking;
250
+ const seen = new Map();
251
+ for (const cred of creds) {
252
+ const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
253
+ const { secret_name: name, networking } = cred.data.auth;
254
+
255
+ // Two vaults can both set a variable, but the docs don't say which one wins.
256
+ if (typeof name === "string") {
257
+ 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`);
258
+ else seen.set(name, cred);
259
+ }
260
+
261
+ if (env?.data.config?.type === "self_hosted") warn("environment variable credentials aren't supported on self-hosted environments yet");
262
+
263
+ // allowed_hosts only decides where the secret is substituted; the environment decides what's reachable.
264
+ if (net?.type === "limited" && networking?.type === "limited" && Array.isArray(networking.allowed_hosts)) {
265
+ for (const host of networking.allowed_hosts) {
266
+ if (!(net.allowed_hosts ?? []).includes(host)) {
267
+ 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}`);
268
+ }
269
+ }
270
+ }
271
+ }
272
+ }
273
+
274
+ function checkCredential(cred, errors, warnings) {
275
+ const err = (msg) => errors.push(`${cred.file}: ${msg}`);
276
+ const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
277
+ const { data } = cred;
278
+ if (cred.name.length > 255) err("a credential's name (its file name) must be at most 255 characters");
279
+ if ("display_name" in data) err("`display_name` is not allowed; the file name is the credential's name");
280
+ checkMetadata(data.metadata, 16, err);
281
+ for (const key of Object.keys(data)) {
282
+ if (!["auth", "metadata", "display_name"].includes(key)) warn(`unknown field \`${key}\` will be sent to the API as written`);
283
+ }
284
+
285
+ const { auth } = data;
286
+ if (!isObject(auth)) return err("`auth` is required");
287
+ 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`);
288
+
289
+ for (const path of SECRET_FIELDS[auth.type]) {
290
+ if (get(auth, path) !== undefined) {
291
+ err(`\`auth.${path.join(".")}\` doesn't go in the file; \`agentschema cred deploy\` asks for it and sends it straight to the vault`);
292
+ }
293
+ }
294
+
295
+ if (auth.type === ENV_VAR) return checkEnvVarAuth(auth, err, warn);
296
+
297
+ const url = (value, field) => {
298
+ if (typeof value !== "string" || value === "") return err(`\`${field}\` is required`);
299
+ if (!/^https?:\/\/\S+$/.test(value)) err(`\`${field}\` must be an http(s) URL`);
300
+ };
301
+ url(auth.mcp_server_url, "auth.mcp_server_url");
302
+ for (const key of Object.keys(auth)) {
303
+ if (!["type", "mcp_server_url", "refresh", "access_token", "expires_at"].includes(key)) {
304
+ warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
305
+ }
306
+ }
307
+
308
+ if (auth.refresh === undefined || auth.refresh === null) return;
309
+ const { refresh } = auth;
310
+ if (!isObject(refresh)) return err("`auth.refresh` must be a mapping");
311
+ url(refresh.token_endpoint, "auth.refresh.token_endpoint");
312
+ 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)");
313
+ for (const field of ["scope", "resource"]) {
314
+ if (refresh[field] !== undefined && typeof refresh[field] !== "string") err(`\`auth.refresh.${field}\` must be a string`);
315
+ }
316
+ if (!isObject(refresh.token_endpoint_auth) || !TOKEN_ENDPOINT_AUTH.includes(refresh.token_endpoint_auth.type)) {
317
+ err(`\`auth.refresh.token_endpoint_auth.type\` must be ${TOKEN_ENDPOINT_AUTH.map((t) => `\`${t}\``).join(", ")}`);
318
+ }
319
+ for (const key of Object.keys(refresh)) {
320
+ if (!["token_endpoint", "client_id", "scope", "resource", "token_endpoint_auth", "refresh_token"].includes(key)) {
321
+ warn(`unknown field \`auth.refresh.${key}\` will be sent to the API as written`);
322
+ }
323
+ }
324
+ }
325
+
326
+ function checkEnvVarAuth(auth, err, warn) {
327
+ if (typeof auth.secret_name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(auth.secret_name)) {
328
+ err("`auth.secret_name` is required, and must be a variable name like STRIPE_API_KEY");
329
+ }
330
+
331
+ const { networking: net, injection_location: where } = auth;
332
+ if (!isObject(net) || !["limited", "unrestricted"].includes(net.type)) {
333
+ err("`auth.networking.type` is required, and must be `limited` or `unrestricted`");
334
+ } else if (net.type === "unrestricted") {
335
+ warn("`auth.networking` is `unrestricted`, so the secret is substituted on requests to any host; a prompt-injected agent could send it anywhere");
336
+ } else if (!Array.isArray(net.allowed_hosts) || net.allowed_hosts.length === 0 || net.allowed_hosts.some((h) => typeof h !== "string" || h === "")) {
337
+ err("`auth.networking.allowed_hosts` must list the hosts the secret may be sent to");
338
+ }
339
+
340
+ if (where !== undefined && where !== null) {
341
+ if (!isObject(where)) err("`auth.injection_location` must be a mapping");
342
+ else {
343
+ for (const field of ["header", "body"]) {
344
+ if (where[field] !== undefined && typeof where[field] !== "boolean") err(`\`auth.injection_location.${field}\` must be true or false`);
345
+ }
346
+ if (where.header !== true && where.body !== true) err("`auth.injection_location` must enable `header` or `body`; a field you leave out is false");
347
+ }
348
+ }
349
+
350
+ for (const key of Object.keys(auth)) {
351
+ if (!["type", "secret_name", "secret_value", "networking", "injection_location"].includes(key)) {
352
+ warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
353
+ }
354
+ }
355
+ }
356
+
357
+ function checkMetadata(metadata, maxKeys, err) {
358
+ if (metadata === undefined) return;
359
+ if (!isObject(metadata)) return err("`metadata` must be a mapping");
360
+ const keys = Object.keys(metadata);
361
+ if (keys.length > maxKeys) err(`\`metadata\` has ${keys.length} keys; the limit is ${maxKeys}`);
362
+ for (const key of keys) {
363
+ if (typeof metadata[key] !== "string") err(`\`metadata.${key}\` must be a string (quote numbers and booleans)`);
364
+ }
365
+ }
package/lib/files.js ADDED
@@ -0,0 +1,30 @@
1
+ // An agent is passed around as a file map: { "agent.md": contents, "tools/x.md": contents, … }.
2
+ // Paths are relative and use forward slashes. Contents are a string, or bytes (a Uint8Array) for
3
+ // files that may not be text. This is what a folder on disk, a browser editor and a database row
4
+ // all have in common, so nothing else in lib/ needs to know where the files came from.
5
+
6
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
7
+ const encoder = new TextEncoder();
8
+
9
+ export const textOf = (contents) => (typeof contents === "string" ? contents : decoder.decode(contents));
10
+ export const bytesOf = (contents) => (typeof contents === "string" ? encoder.encode(contents) : contents);
11
+
12
+ // Hidden files and installed packages are never part of an agent.
13
+ export const isIgnoredPath = (path) => path.split("/").some((part) => part.startsWith(".") || part === "node_modules");
14
+
15
+ // The same order as walking a folder with each level sorted by name.
16
+ export function comparePaths(a, b) {
17
+ const x = a.split("/");
18
+ const y = b.split("/");
19
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
20
+ if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
21
+ }
22
+ return x.length - y.length;
23
+ }
24
+
25
+ // The paths under `folder`, sorted, leaving out ignored ones.
26
+ export function pathsUnder(files, folder) {
27
+ return Object.keys(files)
28
+ .filter((path) => path.startsWith(`${folder}/`) && !isIgnoredPath(path))
29
+ .sort(comparePaths);
30
+ }
package/lib/index.js ADDED
@@ -0,0 +1,18 @@
1
+ // The browser-safe core of agentschema: no Node APIs, and `yaml` as the only dependency. It works
2
+ // on file maps (see files.js), so it doesn't care whether an agent lives on disk or in a database.
3
+ export { checkFiles } from "./check.js";
4
+ export { bytesOf, isIgnoredPath, pathsUnder, textOf } from "./files.js";
5
+ export { AGENT_FILE, ENV_FILE, agentBody, envBody, readInstance } from "./instance.js";
6
+ export { FileError, editFrontmatter, parseMarkdown } from "./markdown.js";
7
+ export { MODELS, NETWORKING, builtInFile, defaultAnswers, scaffold } from "./scaffold.js";
8
+ export { MAX_UPLOAD_BYTES, SKILLS_DIR, SKILL_FILE, readSkills, skillKey, skillRefs } from "./skills.js";
9
+ export { agentMessageText, textStream } from "./stream.js";
10
+ export {
11
+ AGENTBOOK, MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR,
12
+ agentbookTools, compileTools, readTools,
13
+ } from "./tools.js";
14
+ export {
15
+ CREDENTIAL_TYPES, ENV_VAR, MCP_OAUTH, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE,
16
+ changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings, readVaults,
17
+ secretsNeeded, vaultBody, vaultKey,
18
+ } from "./vaults.js";
@@ -1,50 +1,39 @@
1
- import { readFileSync, readdirSync, statSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { textOf } from "./files.js";
3
2
  import { FileError, parseMarkdown } from "./markdown.js";
4
3
  import { compileTools } from "./tools.js";
5
4
 
6
5
  export const AGENT_FILE = "agent.md";
7
6
  export const ENV_FILE = "env.md";
8
7
 
9
- export { FileError, parseMarkdown };
10
-
11
- // Reads agent.md and env.md from an instance folder.
12
- // Returns { agent, env, errors }; a file that can't be read is null and has an entry in errors.
13
- export function readInstance(dir) {
14
- let stat;
15
- try {
16
- stat = statSync(dir);
17
- } catch {
18
- return { agent: null, env: null, errors: [`${dir}: no such directory`] };
19
- }
20
- if (!stat.isDirectory()) return { agent: null, env: null, errors: [`${dir}: not a directory`] };
21
-
22
- // Compare exact names: macOS file systems would otherwise open AGENT.md as agent.md.
23
- const names = readdirSync(dir);
8
+ // Reads agent.md and env.md. Returns { agent, env, errors }; a file that can't be read is null
9
+ // and has an entry in errors.
10
+ export function readInstance(files) {
11
+ const names = Object.keys(files).filter((path) => !path.includes("/"));
24
12
  const errors = [];
25
13
  const read = (name) => {
26
14
  try {
15
+ // Exact names only, so an agent behaves the same on a case-sensitive file system.
27
16
  if (!names.includes(name)) {
28
17
  const wrongCase = names.find((n) => n.toLowerCase() === name);
29
18
  const hint = wrongCase ? ` (found ${wrongCase}; the name must be lowercase)` : "";
30
19
  throw new FileError(`${name}: missing${hint}`);
31
20
  }
32
- return parseMarkdown(readFileSync(join(dir, name), "utf8"), name);
21
+ return parseMarkdown(textOf(files[name]), name);
33
22
  } catch (err) {
34
23
  if (!(err instanceof FileError)) throw err;
35
24
  errors.push(err.message);
36
25
  return null;
37
26
  }
38
27
  };
39
-
40
28
  return { agent: read(AGENT_FILE), env: read(ENV_FILE), errors };
41
29
  }
42
30
 
43
31
  // The bodies sent to POST /v1/agents and POST /v1/environments.
44
32
  // The agent's tools come from tools/, compiled into the API's `tools` list. `skills` are the
45
33
  // references to the skills deployed from skills/, added to any in agent.md's frontmatter.
46
- export function agentBody({ agent, tools }, skills = []) {
47
- const body = { ...agent.data, tools: compileTools(tools) };
34
+ // `options.toolsets` is the catalog behind `type: agentbook` tool files.
35
+ export function agentBody({ agent, tools }, skills = [], options = {}) {
36
+ const body = { ...agent.data, tools: compileTools(tools, options) };
48
37
  if (skills.length > 0) body.skills = [...(agent.data.skills ?? []), ...skills];
49
38
  if (agent.body) body.system = agent.body;
50
39
  return body;
@@ -1,20 +1,10 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
2
1
  import { parseDocument } from "yaml";
3
2
 
4
3
  export class FileError extends Error {}
5
4
 
6
- // Edits a file's frontmatter through `edit(doc)`, keeping its comments and the rest of the file.
7
- export function updateFrontmatter(file, edit) {
8
- const text = readFileSync(file, "utf8").replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
9
- const end = 4 + /^---[ \t]*$/m.exec(text.slice(4)).index;
10
- const doc = parseDocument(text.slice(4, end));
11
- edit(doc);
12
- writeFileSync(file, `---\n${doc.toString({ lineWidth: 0 })}${text.slice(end)}`);
13
- }
14
-
15
5
  // Splits a Markdown file into YAML frontmatter (between `---` fences) and body.
16
6
  export function parseMarkdown(text, file) {
17
- const normalized = text.replace(/^/, "").replace(/\r\n/g, "\n");
7
+ const normalized = normalize(text);
18
8
  if (!normalized.startsWith("---\n")) {
19
9
  throw new FileError(`${file}: must start with YAML frontmatter between --- lines`);
20
10
  }
@@ -38,3 +28,15 @@ export function parseMarkdown(text, file) {
38
28
  }
39
29
  return { data, body: afterFence.trim(), raw: text };
40
30
  }
31
+
32
+ // Edits a file's frontmatter through `edit(doc)`, keeping its comments and the rest of the file.
33
+ // Returns the new text.
34
+ export function editFrontmatter(text, edit) {
35
+ const normalized = normalize(text);
36
+ const end = 4 + /^---[ \t]*$/m.exec(normalized.slice(4)).index;
37
+ const doc = parseDocument(normalized.slice(4, end));
38
+ edit(doc);
39
+ return `---\n${doc.toString({ lineWidth: 0 })}${normalized.slice(end)}`;
40
+ }
41
+
42
+ const normalize = (text) => text.replace(/^/, "").replace(/\r\n/g, "\n");
@@ -0,0 +1,49 @@
1
+ import { stringify } from "yaml";
2
+ import { AGENT_FILE, ENV_FILE } from "./instance.js";
3
+ import { PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR } from "./tools.js";
4
+
5
+ export const MODELS = ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"];
6
+ export const NETWORKING = ["limited", "unrestricted"];
7
+
8
+ // The answers used for a new agent called `name`, when a question is skipped.
9
+ export function defaultAnswers(name) {
10
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "agent";
11
+ return {
12
+ name: slug.split("-").map((w) => w[0].toUpperCase() + w.slice(1)).join(" "),
13
+ model: MODELS[0],
14
+ system: "You are a helpful assistant.",
15
+ tools: true,
16
+ environment: slug,
17
+ networking: "limited",
18
+ packageManagers: true,
19
+ };
20
+ }
21
+
22
+ // Returns { path: text } for a set of answers: agent.md, env.md, and tools/agent_toolset_20260401.md
23
+ // listing every pre-built tool when the agent gets them.
24
+ export function scaffold(answers) {
25
+ const agent = { name: answers.name, model: answers.model };
26
+
27
+ const networking = { type: answers.networking };
28
+ if (answers.networking === "limited") networking.allow_package_managers = answers.packageManagers;
29
+ const env = { name: answers.environment, config: { type: "cloud", networking } };
30
+
31
+ const access = answers.networking === "unrestricted"
32
+ ? "unrestricted network access"
33
+ : answers.packageManagers ? "limited networking and package manager access" : "limited networking";
34
+ const files = {
35
+ [AGENT_FILE]: `---\n${stringify(agent)}---\n\n${answers.system.trim()}\n`,
36
+ [ENV_FILE]: `---\n${stringify(env)}---\nCloud container with ${access}.\n`,
37
+ };
38
+ if (answers.tools) {
39
+ files[`${TOOLS_DIR}/${TOOLSET_FILE}`] = builtInFile(PREBUILT_TOOLS);
40
+ }
41
+ return files;
42
+ }
43
+
44
+ // The pre-built toolset file, with a row for each of `names`: on if it's in `enabled`, with the
45
+ // API's default permission policy.
46
+ export function builtInFile(names, enabled = names) {
47
+ const rows = names.map((name) => `| \`${name}\` | \`${enabled.includes(name)}\` | |`).join("\n");
48
+ return `---\ntype: ${TOOLSET}\n---\n\nThe tools Claude runs in the agent's container. Set Enabled to false to turn a tool off.\n\n## Tools\n\n| Name | Enabled | Permission |\n|---|---|---|\n${rows}\n`;
49
+ }
package/lib/skills.js ADDED
@@ -0,0 +1,58 @@
1
+ import { bytesOf, isIgnoredPath, pathsUnder, textOf } from "./files.js";
2
+ import { FileError, parseMarkdown } from "./markdown.js";
3
+
4
+ export const SKILLS_DIR = "skills";
5
+ export const SKILL_FILE = "SKILL.md";
6
+ export const MAX_UPLOAD_BYTES = 30 * 1024 * 1024;
7
+
8
+ // Reads skills/: each folder is a skill, with a SKILL.md at its top and any other files it needs,
9
+ // at any depth. Hidden files and node_modules are left out. Skills are sorted by name. No skills/
10
+ // folder means no skills.
11
+ // Returns { skills, errors }; a skill that can't be read has an entry in errors.
12
+ export function readSkills(files) {
13
+ if (SKILLS_DIR in files) return { skills: [], errors: [`${SKILLS_DIR}: not a directory`] };
14
+
15
+ const folders = new Map();
16
+ const errors = [];
17
+ for (const file of pathsUnder(files, SKILLS_DIR)) {
18
+ const [, name, ...rest] = file.split("/");
19
+ if (rest.length === 0) {
20
+ if (name.endsWith(".md")) errors.push(`${file}: each skill is a folder, like ${SKILLS_DIR}/my-skill/${SKILL_FILE}`);
21
+ continue;
22
+ }
23
+ if (!folders.has(name)) folders.set(name, []);
24
+ folders.get(name).push({ rel: rest.join("/"), bytes: bytesOf(files[file]) });
25
+ }
26
+
27
+ const skills = [];
28
+ for (const [name, skillFiles] of folders) {
29
+ const path = `${SKILLS_DIR}/${name}`;
30
+ // Exact names only, so a skill behaves the same on a case-sensitive file system.
31
+ const main = skillFiles.find((f) => f.rel === SKILL_FILE);
32
+ if (!main) {
33
+ const wrongCase = skillFiles.find((f) => f.rel.toLowerCase() === SKILL_FILE.toLowerCase());
34
+ errors.push(`${path}: missing ${SKILL_FILE}${wrongCase ? ` (found ${wrongCase.rel}; the name must be uppercase)` : ""}`);
35
+ continue;
36
+ }
37
+ try {
38
+ const parsed = parseMarkdown(textOf(main.bytes), `${path}/${SKILL_FILE}`);
39
+ skills.push({ name, path, file: `${path}/${SKILL_FILE}`, files: skillFiles, ...parsed });
40
+ } catch (err) {
41
+ if (!(err instanceof FileError)) throw err;
42
+ errors.push(err.message);
43
+ }
44
+ }
45
+ return { skills, errors };
46
+ }
47
+
48
+ // The lock file key for a skill.
49
+ export const skillKey = (skill) => `./${skill.path}`;
50
+
51
+ // The agent's references to the skills deployed from this folder, pinned to their versions, so
52
+ // that a session runs exactly what deploy last sent.
53
+ export function skillRefs(skills = [], lock) {
54
+ return skills
55
+ .map((skill) => lock?.resources?.[skillKey(skill)])
56
+ .filter(Boolean)
57
+ .map((entry) => ({ type: "custom", skill_id: entry.id, version: entry.version }));
58
+ }