@soft-boy/agentschema 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +11 -5
  2. package/dist/bin/agentschema.d.ts +2 -0
  3. package/dist/bin/agentschema.js +333 -0
  4. package/dist/lib/channels.d.ts +74 -0
  5. package/dist/lib/channels.js +403 -0
  6. package/dist/lib/check.d.ts +10 -0
  7. package/dist/lib/check.js +411 -0
  8. package/dist/lib/files.d.ts +7 -0
  9. package/{lib → dist/lib}/files.js +10 -14
  10. package/dist/lib/index.d.ts +24 -0
  11. package/{lib → dist/lib}/index.js +4 -13
  12. package/dist/lib/instance.d.ts +41 -0
  13. package/dist/lib/instance.js +74 -0
  14. package/dist/lib/markdown.d.ts +11 -0
  15. package/dist/lib/markdown.js +38 -0
  16. package/dist/lib/scaffold.d.ts +15 -0
  17. package/dist/lib/scaffold.js +46 -0
  18. package/dist/lib/scheduled.d.ts +56 -0
  19. package/dist/lib/scheduled.js +185 -0
  20. package/dist/lib/skills.d.ts +28 -0
  21. package/dist/lib/skills.js +55 -0
  22. package/dist/lib/stream.d.ts +30 -0
  23. package/dist/lib/stream.js +56 -0
  24. package/dist/lib/system-prompt.d.ts +16 -0
  25. package/{lib → dist/lib}/system-prompt.js +14 -15
  26. package/dist/lib/tools.d.ts +127 -0
  27. package/dist/lib/tools.js +465 -0
  28. package/dist/lib/vaults.d.ts +55 -0
  29. package/dist/lib/vaults.js +143 -0
  30. package/dist/src/chat.d.ts +15 -0
  31. package/dist/src/chat.js +159 -0
  32. package/dist/src/check.d.ts +2 -0
  33. package/dist/src/check.js +14 -0
  34. package/dist/src/cred-menu.d.ts +17 -0
  35. package/dist/src/cred-menu.js +193 -0
  36. package/dist/src/cred.d.ts +54 -0
  37. package/dist/src/cred.js +252 -0
  38. package/dist/src/custom-tools.d.ts +3 -0
  39. package/dist/src/custom-tools.js +18 -0
  40. package/dist/src/delete.d.ts +9 -0
  41. package/dist/src/delete.js +27 -0
  42. package/dist/src/deploy.d.ts +62 -0
  43. package/dist/src/deploy.js +442 -0
  44. package/dist/src/dotenv.d.ts +7 -0
  45. package/dist/src/dotenv.js +54 -0
  46. package/dist/src/folder.d.ts +5 -0
  47. package/{src → dist/src}/folder.js +30 -28
  48. package/dist/src/init.d.ts +11 -0
  49. package/dist/src/init.js +51 -0
  50. package/dist/src/list.d.ts +3 -0
  51. package/dist/src/list.js +46 -0
  52. package/dist/src/lock.d.ts +10 -0
  53. package/dist/src/lock.js +37 -0
  54. package/dist/src/mcp.d.ts +11 -0
  55. package/dist/src/mcp.js +79 -0
  56. package/dist/src/node.d.ts +14 -0
  57. package/dist/src/oauth.d.ts +64 -0
  58. package/dist/src/oauth.js +208 -0
  59. package/dist/src/prompts.d.ts +18 -0
  60. package/dist/src/prompts.js +166 -0
  61. package/dist/src/session.d.ts +58 -0
  62. package/dist/src/session.js +200 -0
  63. package/dist/src/tools-menu.d.ts +8 -0
  64. package/dist/src/tools-menu.js +173 -0
  65. package/package.json +21 -9
  66. package/bin/agentschema.js +0 -326
  67. package/lib/channels.js +0 -338
  68. package/lib/check.js +0 -387
  69. package/lib/instance.js +0 -75
  70. package/lib/markdown.js +0 -42
  71. package/lib/scaffold.js +0 -51
  72. package/lib/scheduled.js +0 -175
  73. package/lib/skills.js +0 -58
  74. package/lib/stream.js +0 -50
  75. package/lib/tools.js +0 -327
  76. package/lib/vaults.js +0 -142
  77. package/src/chat.js +0 -156
  78. package/src/check.js +0 -14
  79. package/src/cred-menu.js +0 -197
  80. package/src/cred.js +0 -263
  81. package/src/custom-tools.js +0 -17
  82. package/src/delete.js +0 -25
  83. package/src/deploy.js +0 -441
  84. package/src/dotenv.js +0 -50
  85. package/src/init.js +0 -54
  86. package/src/list.js +0 -49
  87. package/src/lock.js +0 -40
  88. package/src/mcp.js +0 -76
  89. package/src/oauth.js +0 -215
  90. package/src/prompts.js +0 -159
  91. package/src/session.js +0 -194
  92. package/src/tools-menu.js +0 -163
  93. /package/{src → dist/src}/node.js +0 -0
@@ -0,0 +1,411 @@
1
+ import { checkChannels, readChannels } from "./channels.js";
2
+ import { textOf } from "./files.js";
3
+ import { AGENT_FILE, readInstance } from "./instance.js";
4
+ import { checkScheduled, readScheduled } from "./scheduled.js";
5
+ import { SYSTEM_PROMPT_DIR, readSystemPrompt, systemPromptOf } from "./system-prompt.js";
6
+ import { MAX_UPLOAD_BYTES, SKILLS_DIR, readSkills } from "./skills.js";
7
+ import { MCP_TOOLSET, TOOLS_DIR, checkTools, readTools } from "./tools.js";
8
+ import { CREDENTIAL_TYPES, ENV_VAR, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULT_FILE, get, readVaults } from "./vaults.js";
9
+ const AGENT_FIELDS = new Set([
10
+ "name", "model", "description", "mcp_servers", "skills",
11
+ "multiagent", "metadata", "execution_identity",
12
+ ]);
13
+ const ENV_FIELDS = new Set(["name", "config", "description", "metadata", "scope"]);
14
+ const SECRET_PATTERNS = [
15
+ [/sk-ant-[A-Za-z0-9_-]{8,}/, "an Anthropic API key"],
16
+ [/\bghp_[A-Za-z0-9]{20,}/, "a GitHub token"],
17
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token"],
18
+ [/\bxox[bpas]-[A-Za-z0-9-]{10,}/, "a Slack token"],
19
+ [/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key"],
20
+ [/\b\d{6,12}:[A-Za-z0-9_-]{35}\b/, "a Telegram bot token"],
21
+ [/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/, "a SendGrid API key"],
22
+ [/\b(AC|SK)[0-9a-f]{32}\b/, "a Twilio SID"],
23
+ [/\b[MNO][A-Za-z0-9_-]{23,}\.[A-Za-z0-9_-]{6,7}\.[A-Za-z0-9_-]{27,}\b/, "a Discord bot token"],
24
+ ];
25
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
26
+ // Validates an agent's files without calling the API. `files` is a file map (see files.ts), and
27
+ // `options` is what checkTools takes: { customTools, toolsets }.
28
+ // Returns { errors, warnings, instance }; instance is null when the files can't be read.
29
+ export function checkFiles(files, options = {}) {
30
+ const { agent, env, errors, warnings } = readInstance(files);
31
+ const { tools, errors: toolErrors } = readTools(files);
32
+ const { vaults, errors: vaultErrors } = readVaults(files);
33
+ const { skills, errors: skillErrors } = readSkills(files);
34
+ const { channels, errors: channelErrors } = readChannels(files);
35
+ const { tasks: scheduled, errors: scheduledErrors } = readScheduled(files);
36
+ const { parts: systemPrompt, errors: systemPromptErrors } = readSystemPrompt(files);
37
+ errors.push(...toolErrors, ...vaultErrors, ...skillErrors, ...channelErrors, ...scheduledErrors, ...systemPromptErrors);
38
+ if (agent)
39
+ checkAgent(agent, errors, warnings);
40
+ if (agent)
41
+ checkSystemPromptLength({ agent, systemPrompt }, errors);
42
+ if (env)
43
+ checkEnv(env, errors, warnings);
44
+ checkTools(tools, errors, warnings, options);
45
+ if (agent)
46
+ checkMcpServers(agent, tools, errors);
47
+ if (agent && env)
48
+ checkMcpNetworking(agent, env, warnings);
49
+ for (const skill of skills)
50
+ checkSkill(skill, errors);
51
+ const declaredSkills = Array.isArray(agent?.data.skills) ? agent.data.skills.length : 0;
52
+ if (declaredSkills + skills.length > 500)
53
+ errors.push(`${declaredSkills + skills.length} skills; the limit is 500`);
54
+ for (const vault of vaults)
55
+ checkVault(vault, errors, warnings);
56
+ checkEnvVarCredentials(vaults, env, warnings);
57
+ checkChannels(channels, { agent: agent ?? undefined, systemPrompt, tools, toolsets: options.toolsets }, errors, warnings);
58
+ checkScheduled(scheduled, { tools }, errors, warnings);
59
+ const vaultFiles = vaults.flatMap((v) => [...(v.file ? [[`${v.path}/${VAULT_FILE}`, v.file]] : []), ...v.credentials.map((c) => [c.file, c])]);
60
+ const skillTexts = skills.flatMap((s) => s.files.map((f) => [`${s.path}/${f.rel}`, { raw: textOf(f.bytes) }]));
61
+ const scanned = [[AGENT_FILE, agent], [env?.file, env], ...tools.flatMap((t) => [[t.file, t], ...(t.members ?? []).map((m) => [m.file, m])]), ...vaultFiles, ...skillTexts, ...channels.map((c) => [c.file, c]), ...scheduled.map((t) => [t.file, t]), ...systemPrompt.map((p) => [p.file, { raw: p.text }])];
62
+ for (const [file, parsed] of scanned) {
63
+ if (!parsed)
64
+ continue;
65
+ for (const [pattern, what] of SECRET_PATTERNS) {
66
+ if (pattern.test(parsed.raw))
67
+ errors.push(`${file}: looks like it contains ${what}; keep secrets out of these files`);
68
+ }
69
+ }
70
+ return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills, channels, scheduled, systemPrompt } : null };
71
+ }
72
+ const MAX_SYSTEM_PROMPT = 100_000;
73
+ // The system prompt is agent.md's body and system_prompt/'s files together, and the API's limit is on
74
+ // all of it.
75
+ function checkSystemPromptLength(instance, errors) {
76
+ const { length } = systemPromptOf(instance);
77
+ if (length <= MAX_SYSTEM_PROMPT)
78
+ return;
79
+ const where = instance.systemPrompt.length > 0 ? `${AGENT_FILE} and ${SYSTEM_PROMPT_DIR}/` : AGENT_FILE;
80
+ errors.push(`${where}: the system prompt is ${length.toLocaleString("en-US")} characters; the limit is ${MAX_SYSTEM_PROMPT.toLocaleString("en-US")}`);
81
+ }
82
+ function checkAgent({ data, body }, errors, warnings) {
83
+ const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
84
+ if (typeof data.name !== "string" || data.name.trim() === "")
85
+ err("`name` is required");
86
+ else if (data.name.length > 256)
87
+ err("`name` must be at most 256 characters");
88
+ if (data.model === undefined)
89
+ err("`model` is required");
90
+ else if (isObject(data.model) ? typeof data.model.id !== "string" : typeof data.model !== "string") {
91
+ err("`model` must be a model ID, or a mapping with an `id`");
92
+ }
93
+ if ("system" in data)
94
+ err("`system` is not allowed in frontmatter; the Markdown body is the system prompt");
95
+ if (data.description !== undefined && data.description !== null) {
96
+ if (typeof data.description !== "string")
97
+ err("`description` must be a string");
98
+ else if (data.description.length > 2048)
99
+ err("`description` must be at most 2048 characters");
100
+ }
101
+ if ("tools" in data)
102
+ err(`\`tools\` is not allowed in frontmatter; define each tool as a file in ${TOOLS_DIR}/`);
103
+ for (const [field, max] of [["mcp_servers", 20], ["skills", 500]]) {
104
+ if (data[field] === undefined)
105
+ continue;
106
+ if (!Array.isArray(data[field]))
107
+ err(`\`${field}\` must be a list`);
108
+ else if (data[field].length > max)
109
+ err(`\`${field}\` has ${data[field].length} entries; the limit is ${max}`);
110
+ }
111
+ if (Array.isArray(data.skills)) {
112
+ for (const [index, skill] of data.skills.entries())
113
+ checkSkillRef(skill, (msg) => err(`\`skills[${index}]\`: ${msg}`));
114
+ }
115
+ checkMetadata(data.metadata, 16, err);
116
+ for (const key of Object.keys(data)) {
117
+ if (!AGENT_FIELDS.has(key) && key !== "system" && key !== "tools") {
118
+ warnings.push(`${AGENT_FILE}: unknown field \`${key}\` will be sent to the API as written`);
119
+ }
120
+ }
121
+ }
122
+ function checkEnv({ data, file }, errors, warnings) {
123
+ const err = (msg) => errors.push(`${file}: ${msg}`);
124
+ if (typeof data.name !== "string" || data.name.trim() === "")
125
+ err("`name` is required");
126
+ if (data.config !== undefined) {
127
+ const { config } = data;
128
+ if (!isObject(config))
129
+ err("`config` must be a mapping");
130
+ else {
131
+ if (!["cloud", "self_hosted"].includes(config.type))
132
+ err("`config.type` must be `cloud` or `self_hosted`");
133
+ const net = config.networking;
134
+ if (net !== undefined && !(isObject(net) && ["limited", "unrestricted"].includes(net.type))) {
135
+ err("`config.networking.type` must be `limited` or `unrestricted`");
136
+ }
137
+ }
138
+ }
139
+ if (data.description !== undefined && data.description !== null && typeof data.description !== "string") {
140
+ err("`description` must be a string");
141
+ }
142
+ checkMetadata(data.metadata, Infinity, err);
143
+ for (const key of Object.keys(data)) {
144
+ if (!ENV_FIELDS.has(key))
145
+ warnings.push(`${file}: unknown field \`${key}\` will be sent to the API as written`);
146
+ }
147
+ }
148
+ // An entry in agent.md's `skills` list, in the API's shape.
149
+ function checkSkillRef(skill, err) {
150
+ if (typeof skill === "string") {
151
+ return err(`write this as a mapping with \`type\` and \`skill_id\`; a skill in ${SKILLS_DIR}/ is attached without being listed`);
152
+ }
153
+ if (!isObject(skill))
154
+ return err("must be a mapping with `type` and `skill_id`");
155
+ if (!["anthropic", "custom"].includes(skill.type))
156
+ err("`type` must be `anthropic` or `custom`");
157
+ if (typeof skill.skill_id !== "string" || skill.skill_id === "")
158
+ err("`skill_id` is required");
159
+ else if (skill.type === "custom" && !skill.skill_id.startsWith("skill_"))
160
+ err("a custom skill's `skill_id` starts with skill_");
161
+ if (skill.version !== undefined && skill.version !== null && typeof skill.version !== "string") {
162
+ err("`version` must be a string (quote numbers)");
163
+ }
164
+ }
165
+ function checkSkill(skill, errors) {
166
+ const err = (msg) => errors.push(`${skill.file}: ${msg}`);
167
+ const { name, description } = skill.data;
168
+ if (typeof name !== "string" || name === "")
169
+ err("`name` is required");
170
+ else {
171
+ if (name !== skill.name)
172
+ err(`\`name\` must match the folder's name (${skill.name})`);
173
+ if (!/^[a-z0-9-]{1,64}$/.test(name))
174
+ err("`name` may only use lowercase letters, digits and hyphens, up to 64 characters");
175
+ if (/anthropic|claude/.test(name))
176
+ err("`name` can't contain the reserved words `anthropic` or `claude`");
177
+ }
178
+ if (typeof description !== "string" || description.trim() === "")
179
+ err("`description` is required");
180
+ else {
181
+ if (description.length > 1024)
182
+ err(`\`description\` is ${description.length} characters; the limit is 1,024`);
183
+ if (/<[^>]+>/.test(description))
184
+ err("`description` can't contain XML tags");
185
+ }
186
+ const size = skill.files.reduce((total, f) => total + f.bytes.length, 0);
187
+ if (size > MAX_UPLOAD_BYTES)
188
+ errors.push(`${skill.path}: its files add up to ${Math.ceil(size / 1024 / 1024)} MB; the limit is 30 MB`);
189
+ }
190
+ const mcpServers = (agent) => (Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers.filter(isObject) : []);
191
+ // Each server agent.md declares needs a toolset file, and each toolset file a declared server;
192
+ // the API rejects an agent otherwise.
193
+ function checkMcpServers(agent, tools, errors) {
194
+ const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
195
+ const names = new Set();
196
+ for (const server of mcpServers(agent)) {
197
+ const label = typeof server.name === "string" && server.name ? `\`${server.name}\`` : "an entry";
198
+ if (server.type !== "url")
199
+ err(`\`mcp_servers\`: ${label} must have \`type: url\``);
200
+ if (typeof server.name !== "string" || server.name === "" || server.name.length > 255) {
201
+ err("`mcp_servers`: each server needs a `name` of 1 to 255 characters");
202
+ }
203
+ else if (names.has(server.name)) {
204
+ err(`\`mcp_servers\`: \`${server.name}\` is declared twice`);
205
+ }
206
+ if (typeof server.url !== "string" || !/^https?:\/\/\S+$/.test(server.url) || server.url.length > 2048) {
207
+ err(`\`mcp_servers\`: ${label} needs a \`url\`, an http(s) URL of at most 2048 characters`);
208
+ }
209
+ names.add(server.name);
210
+ }
211
+ const toolsets = tools.filter((t) => t.data.type === MCP_TOOLSET);
212
+ const covered = new Set(toolsets.map((t) => t.data.mcp_server_name));
213
+ for (const name of names) {
214
+ if (typeof name === "string" && name && !covered.has(name)) {
215
+ err(`\`mcp_servers\`: \`${name}\` has no toolset; add ${TOOLS_DIR}/${name}.md with \`type: mcp_toolset\`, or the API rejects the agent`);
216
+ }
217
+ }
218
+ for (const toolset of toolsets) {
219
+ const name = toolset.data.mcp_server_name;
220
+ if (typeof name === "string" && name && !names.has(name)) {
221
+ errors.push(`${toolset.file}: \`${name}\` isn't in ${AGENT_FILE}'s \`mcp_servers\``);
222
+ }
223
+ }
224
+ }
225
+ // A limited network blocks MCP servers that aren't allowed, and the API then refuses to start sessions.
226
+ function checkMcpNetworking(agent, env, warnings) {
227
+ const net = env.data.config?.networking;
228
+ if (net?.type !== "limited" || net.allow_mcp_servers === true)
229
+ return;
230
+ const allowed = net.allowed_hosts ?? [];
231
+ for (const server of mcpServers(agent)) {
232
+ let host;
233
+ try {
234
+ host = new URL(server.url).host;
235
+ }
236
+ catch {
237
+ continue;
238
+ }
239
+ if (!allowed.includes(host)) {
240
+ warnings.push(`${env.file}: its limited networking doesn't allow MCP server \`${server.name}\` (${host}), so sessions won't start; ` +
241
+ `set config.networking.allow_mcp_servers to true, or add ${host} to allowed_hosts`);
242
+ }
243
+ }
244
+ }
245
+ function checkVault(vault, errors, warnings) {
246
+ if (vault.name.length > 255)
247
+ errors.push(`${vault.path}: a vault's name (its folder name) must be at most 255 characters`);
248
+ if (vault.file) {
249
+ const file = `${vault.path}/${VAULT_FILE}`;
250
+ const err = (msg) => errors.push(`${file}: ${msg}`);
251
+ const { data } = vault.file;
252
+ if ("display_name" in data)
253
+ err("`display_name` is not allowed; the folder name is the vault's name");
254
+ checkMetadata(data.metadata, 16, err);
255
+ for (const key of Object.keys(data)) {
256
+ if (key !== "metadata" && key !== "display_name")
257
+ warnings.push(`${file}: unknown field \`${key}\` will be sent to the API as written`);
258
+ }
259
+ }
260
+ if (vault.credentials.length > 20)
261
+ errors.push(`${vault.path}: ${vault.credentials.length} credentials; a vault holds at most 20`);
262
+ const urls = new Map();
263
+ const secretNames = new Map();
264
+ for (const cred of vault.credentials) {
265
+ checkCredential(cred, errors, warnings);
266
+ const url = cred.data.auth?.mcp_server_url;
267
+ if (typeof url === "string") {
268
+ if (urls.has(url))
269
+ errors.push(`${cred.file}: ${urls.get(url)} is already a credential for ${url}; a vault holds one per server`);
270
+ else
271
+ urls.set(url, cred.file);
272
+ }
273
+ const secretName = cred.data.auth?.secret_name;
274
+ if (typeof secretName === "string") {
275
+ if (secretNames.has(secretName))
276
+ errors.push(`${cred.file}: ${secretNames.get(secretName)} already sets ${secretName}; a vault holds one per variable`);
277
+ else
278
+ secretNames.set(secretName, cred.file);
279
+ }
280
+ }
281
+ }
282
+ // What an environment variable credential depends on outside its own file.
283
+ function checkEnvVarCredentials(vaults, env, warnings) {
284
+ const creds = vaults.flatMap((v) => v.credentials).filter((c) => c.data.auth?.type === ENV_VAR);
285
+ const net = env?.data.config?.networking;
286
+ const seen = new Map();
287
+ for (const cred of creds) {
288
+ const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
289
+ const { secret_name: name, networking } = cred.data.auth;
290
+ // Two vaults can both set a variable, but the docs don't say which one wins.
291
+ if (typeof name === "string") {
292
+ if (seen.has(name) && seen.get(name).vault !== cred.vault)
293
+ warn(`${seen.get(name).file} also sets ${name}, and the API doesn't document which vault wins`);
294
+ else
295
+ seen.set(name, cred);
296
+ }
297
+ if (env?.data.config?.type === "self_hosted")
298
+ warn("environment variable credentials aren't supported on self-hosted environments yet");
299
+ // allowed_hosts only decides where the secret is substituted; the environment decides what's reachable.
300
+ if (net?.type === "limited" && networking?.type === "limited" && Array.isArray(networking.allowed_hosts)) {
301
+ for (const host of networking.allowed_hosts) {
302
+ if (!(net.allowed_hosts ?? []).includes(host)) {
303
+ 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}`);
304
+ }
305
+ }
306
+ }
307
+ }
308
+ }
309
+ function checkCredential(cred, errors, warnings) {
310
+ const err = (msg) => errors.push(`${cred.file}: ${msg}`);
311
+ const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
312
+ const { data } = cred;
313
+ if (cred.name.length > 255)
314
+ err("a credential's name (its file name) must be at most 255 characters");
315
+ if ("display_name" in data)
316
+ err("`display_name` is not allowed; the file name is the credential's name");
317
+ checkMetadata(data.metadata, 16, err);
318
+ for (const key of Object.keys(data)) {
319
+ if (!["auth", "metadata", "display_name"].includes(key))
320
+ warn(`unknown field \`${key}\` will be sent to the API as written`);
321
+ }
322
+ const { auth } = data;
323
+ if (!isObject(auth))
324
+ return err("`auth` is required");
325
+ if (!CREDENTIAL_TYPES.includes(auth.type))
326
+ return err(`\`auth.type\` must be ${CREDENTIAL_TYPES.map((t) => `\`${t}\``).join(" or ")}; other credential types aren't supported yet`);
327
+ for (const path of SECRET_FIELDS[auth.type]) {
328
+ if (get(auth, path) !== undefined) {
329
+ err(`\`auth.${path.join(".")}\` doesn't go in the file; \`agentschema cred deploy\` asks for it and sends it straight to the vault`);
330
+ }
331
+ }
332
+ if (auth.type === ENV_VAR)
333
+ return checkEnvVarAuth(auth, err, warn);
334
+ const url = (value, field) => {
335
+ if (typeof value !== "string" || value === "")
336
+ return err(`\`${field}\` is required`);
337
+ if (!/^https?:\/\/\S+$/.test(value))
338
+ err(`\`${field}\` must be an http(s) URL`);
339
+ };
340
+ url(auth.mcp_server_url, "auth.mcp_server_url");
341
+ for (const key of Object.keys(auth)) {
342
+ if (!["type", "mcp_server_url", "refresh", "access_token", "expires_at"].includes(key)) {
343
+ warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
344
+ }
345
+ }
346
+ if (auth.refresh === undefined || auth.refresh === null)
347
+ return;
348
+ const { refresh } = auth;
349
+ if (!isObject(refresh))
350
+ return err("`auth.refresh` must be a mapping");
351
+ url(refresh.token_endpoint, "auth.refresh.token_endpoint");
352
+ if (typeof refresh.client_id !== "string" || refresh.client_id === "")
353
+ err("`auth.refresh.client_id` is required, as a string (quote it if it looks like a number)");
354
+ for (const field of ["scope", "resource"]) {
355
+ if (refresh[field] !== undefined && typeof refresh[field] !== "string")
356
+ err(`\`auth.refresh.${field}\` must be a string`);
357
+ }
358
+ if (!isObject(refresh.token_endpoint_auth) || !TOKEN_ENDPOINT_AUTH.includes(refresh.token_endpoint_auth.type)) {
359
+ err(`\`auth.refresh.token_endpoint_auth.type\` must be ${TOKEN_ENDPOINT_AUTH.map((t) => `\`${t}\``).join(", ")}`);
360
+ }
361
+ for (const key of Object.keys(refresh)) {
362
+ if (!["token_endpoint", "client_id", "scope", "resource", "token_endpoint_auth", "refresh_token"].includes(key)) {
363
+ warn(`unknown field \`auth.refresh.${key}\` will be sent to the API as written`);
364
+ }
365
+ }
366
+ }
367
+ function checkEnvVarAuth(auth, err, warn) {
368
+ if (typeof auth.secret_name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(auth.secret_name)) {
369
+ err("`auth.secret_name` is required, and must be a variable name like STRIPE_API_KEY");
370
+ }
371
+ const { networking: net, injection_location: where } = auth;
372
+ if (!isObject(net) || !["limited", "unrestricted"].includes(net.type)) {
373
+ err("`auth.networking.type` is required, and must be `limited` or `unrestricted`");
374
+ }
375
+ else if (net.type === "unrestricted") {
376
+ warn("`auth.networking` is `unrestricted`, so the secret is substituted on requests to any host; a prompt-injected agent could send it anywhere");
377
+ }
378
+ else if (!Array.isArray(net.allowed_hosts) || net.allowed_hosts.length === 0 || net.allowed_hosts.some((h) => typeof h !== "string" || h === "")) {
379
+ err("`auth.networking.allowed_hosts` must list the hosts the secret may be sent to");
380
+ }
381
+ if (where !== undefined && where !== null) {
382
+ if (!isObject(where))
383
+ err("`auth.injection_location` must be a mapping");
384
+ else {
385
+ for (const field of ["header", "body"]) {
386
+ if (where[field] !== undefined && typeof where[field] !== "boolean")
387
+ err(`\`auth.injection_location.${field}\` must be true or false`);
388
+ }
389
+ if (where.header !== true && where.body !== true)
390
+ err("`auth.injection_location` must enable `header` or `body`; a field you leave out is false");
391
+ }
392
+ }
393
+ for (const key of Object.keys(auth)) {
394
+ if (!["type", "secret_name", "secret_value", "networking", "injection_location"].includes(key)) {
395
+ warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
396
+ }
397
+ }
398
+ }
399
+ function checkMetadata(metadata, maxKeys, err) {
400
+ if (metadata === undefined)
401
+ return;
402
+ if (!isObject(metadata))
403
+ return err("`metadata` must be a mapping");
404
+ const keys = Object.keys(metadata);
405
+ if (keys.length > maxKeys)
406
+ err(`\`metadata\` has ${keys.length} keys; the limit is ${maxKeys}`);
407
+ for (const key of keys) {
408
+ if (typeof metadata[key] !== "string")
409
+ err(`\`metadata.${key}\` must be a string (quote numbers and booleans)`);
410
+ }
411
+ }
@@ -0,0 +1,7 @@
1
+ export type FileContents = string | Uint8Array;
2
+ export type FileMap = Record<string, FileContents>;
3
+ export declare const textOf: (contents: FileContents) => string;
4
+ export declare const bytesOf: (contents: FileContents) => Uint8Array;
5
+ export declare const isIgnoredPath: (path: string) => boolean;
6
+ export declare function comparePaths(a: string, b: string): number;
7
+ export declare function pathsUnder(files: FileMap, folder: string): string[];
@@ -2,29 +2,25 @@
2
2
  // Paths are relative and use forward slashes. Contents are a string, or bytes (a Uint8Array) for
3
3
  // files that may not be text. This is what a folder on disk, a browser editor and a database row
4
4
  // all have in common, so nothing else in lib/ needs to know where the files came from.
5
-
6
5
  const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
7
6
  const encoder = new TextEncoder();
8
-
9
7
  export const textOf = (contents) => (typeof contents === "string" ? contents : decoder.decode(contents));
10
8
  export const bytesOf = (contents) => (typeof contents === "string" ? encoder.encode(contents) : contents);
11
-
12
9
  // Hidden files and installed packages are never part of an agent.
13
10
  export const isIgnoredPath = (path) => path.split("/").some((part) => part.startsWith(".") || part === "node_modules");
14
-
15
11
  // The same order as walking a folder with each level sorted by name.
16
12
  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;
13
+ const x = a.split("/");
14
+ const y = b.split("/");
15
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
16
+ if (x[i] !== y[i])
17
+ return x[i] < y[i] ? -1 : 1;
18
+ }
19
+ return x.length - y.length;
23
20
  }
24
-
25
21
  // The paths under `folder`, sorted, leaving out ignored ones.
26
22
  export function pathsUnder(files, folder) {
27
- return Object.keys(files)
28
- .filter((path) => path.startsWith(`${folder}/`) && !isIgnoredPath(path))
29
- .sort(comparePaths);
23
+ return Object.keys(files)
24
+ .filter((path) => path.startsWith(`${folder}/`) && !isIgnoredPath(path))
25
+ .sort(comparePaths);
30
26
  }
@@ -0,0 +1,24 @@
1
+ export { ANYONE, CHANNELS_DIR, CHANNEL_TYPES, CONTACTS, channelSettings, channelSystem, durationMs, maySendTo, readChannels } from "./channels.ts";
2
+ export { checkFiles } from "./check.ts";
3
+ export { bytesOf, isIgnoredPath, pathsUnder, textOf } from "./files.ts";
4
+ export { AGENT_FILE, COMPUTER_FILE, ENVIRONMENT_KEY, OLD_COMPUTER_FILE, agentBody, envBody, environmentEntry, readInstance, upgradeLock, } from "./instance.ts";
5
+ export { FileError, editFrontmatter, parseMarkdown } from "./markdown.ts";
6
+ export { MODELS, NETWORKING, builtInFile, defaultAnswers, scaffold } from "./scaffold.ts";
7
+ export { SCHEDULED_DIR, cronProblem, isTimeZone, readScheduled, taskBody, taskKey, taskSettings } from "./scheduled.ts";
8
+ export { SYSTEM_PROMPT_DIR, readSystemPrompt, systemPromptOf } from "./system-prompt.ts";
9
+ export { MAX_UPLOAD_BYTES, SKILLS_DIR, SKILL_FILE, readSkills, skillKey, skillRefs } from "./skills.ts";
10
+ export { agentMessageText, textStream } from "./stream.ts";
11
+ export { AGENTBOOK, MCP_TOOLSET, OWNER_NOTES, POLICIES, COMPUTER_TOOLS, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLSET_FOLDER_FILE, TOOLS_DIR, agentbookTools, agentbookToolsetFiles, compileTools, mcpToolsetFile, readTools, } from "./tools.ts";
12
+ export { CREDENTIAL_TYPES, ENV_VAR, MCP_OAUTH, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE, changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings, readVaults, secretsNeeded, vaultBody, vaultKey, } from "./vaults.ts";
13
+ export type { Channel, ChannelSettings, ChannelSystemSource, ChannelType, CheckChannelsOptions, ReadChannelsResult, } from "./channels.ts";
14
+ export type { CheckOptions, CheckResult } from "./check.ts";
15
+ export type { FileContents, FileMap } from "./files.ts";
16
+ export type { EnvFile, Instance, Lock, LockEntry, ReadInstanceResult } from "./instance.ts";
17
+ export type { Frontmatter, MarkdownFile } from "./markdown.ts";
18
+ export type { Answers } from "./scaffold.ts";
19
+ export type { ReadScheduledResult, ScheduledTask, TaskBody, TaskSettings } from "./scheduled.ts";
20
+ export type { ReadSkillsResult, Skill, SkillFile, SkillRef } from "./skills.ts";
21
+ export type { AgentMessageEvent, ContentBlock, StreamEvent, TextStream } from "./stream.ts";
22
+ export type { ReadSystemPromptResult, SystemPromptPart } from "./system-prompt.ts";
23
+ export type { AgentbookCatalog, AgentbookTool, AgentbookToolDefinition, CheckToolsOptions, CompileOptions, CompiledTool, InputSchema, JsonSchema, ReadToolsResult, Tool, ToolCode, ToolMember, ToolParam, ToolRow, } from "./tools.ts";
24
+ export type { Credential, CredentialSecrets, CredentialSettings, ReadVaultsResult, SecretsNeeded, Vault, VaultBody, } from "./vaults.ts";
@@ -1,23 +1,14 @@
1
1
  // The browser-safe core of agentschema: no Node APIs, and `yaml` as the only dependency. It works
2
2
  // on file maps (see files.js), so it doesn't care whether an agent lives on disk or in a database.
3
- export { ANYONE, CHANNELS_DIR, CHANNEL_TYPES, channelSettings, channelSystem, durationMs, readChannels } from "./channels.js";
3
+ export { ANYONE, CHANNELS_DIR, CHANNEL_TYPES, CONTACTS, channelSettings, channelSystem, durationMs, maySendTo, readChannels } from "./channels.js";
4
4
  export { checkFiles } from "./check.js";
5
5
  export { bytesOf, isIgnoredPath, pathsUnder, textOf } from "./files.js";
6
- export {
7
- AGENT_FILE, COMPUTER_FILE, ENVIRONMENT_KEY, OLD_COMPUTER_FILE, agentBody, envBody, environmentEntry, readInstance, upgradeLock,
8
- } from "./instance.js";
6
+ export { AGENT_FILE, COMPUTER_FILE, ENVIRONMENT_KEY, OLD_COMPUTER_FILE, agentBody, envBody, environmentEntry, readInstance, upgradeLock, } from "./instance.js";
9
7
  export { FileError, editFrontmatter, parseMarkdown } from "./markdown.js";
10
8
  export { MODELS, NETWORKING, builtInFile, defaultAnswers, scaffold } from "./scaffold.js";
11
9
  export { SCHEDULED_DIR, cronProblem, isTimeZone, readScheduled, taskBody, taskKey, taskSettings } from "./scheduled.js";
12
10
  export { SYSTEM_PROMPT_DIR, readSystemPrompt, systemPromptOf } from "./system-prompt.js";
13
11
  export { MAX_UPLOAD_BYTES, SKILLS_DIR, SKILL_FILE, readSkills, skillKey, skillRefs } from "./skills.js";
14
12
  export { agentMessageText, textStream } from "./stream.js";
15
- export {
16
- AGENTBOOK, MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR,
17
- agentbookTools, compileTools, mcpToolsetFile, readTools,
18
- } from "./tools.js";
19
- export {
20
- CREDENTIAL_TYPES, ENV_VAR, MCP_OAUTH, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE,
21
- changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings, readVaults,
22
- secretsNeeded, vaultBody, vaultKey,
23
- } from "./vaults.js";
13
+ export { AGENTBOOK, MCP_TOOLSET, OWNER_NOTES, POLICIES, COMPUTER_TOOLS, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLSET_FOLDER_FILE, TOOLS_DIR, agentbookTools, agentbookToolsetFiles, compileTools, mcpToolsetFile, readTools, } from "./tools.js";
14
+ export { CREDENTIAL_TYPES, ENV_VAR, MCP_OAUTH, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE, changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings, readVaults, secretsNeeded, vaultBody, vaultKey, } from "./vaults.js";
@@ -0,0 +1,41 @@
1
+ import type { Channel } from "./channels.ts";
2
+ import { type FileMap } from "./files.ts";
3
+ import { type Frontmatter, type MarkdownFile } from "./markdown.ts";
4
+ import type { ScheduledTask } from "./scheduled.ts";
5
+ import type { Skill } from "./skills.ts";
6
+ import { type SystemPromptPart } from "./system-prompt.ts";
7
+ import { type CompileOptions, type Tool } from "./tools.ts";
8
+ import type { Vault } from "./vaults.ts";
9
+ export interface EnvFile extends MarkdownFile {
10
+ file: string;
11
+ }
12
+ export interface Instance {
13
+ agent: MarkdownFile;
14
+ env: EnvFile;
15
+ tools: Tool[];
16
+ vaults: Vault[];
17
+ skills: Skill[];
18
+ channels: Channel[];
19
+ scheduled: ScheduledTask[];
20
+ systemPrompt: SystemPromptPart[];
21
+ }
22
+ export interface Lock {
23
+ resources?: Record<string, LockEntry>;
24
+ [key: string]: unknown;
25
+ }
26
+ export type LockEntry = Record<string, any>;
27
+ export interface ReadInstanceResult {
28
+ agent: MarkdownFile | null;
29
+ env: EnvFile | null;
30
+ errors: string[];
31
+ warnings: string[];
32
+ }
33
+ export declare const AGENT_FILE = "agent.md";
34
+ export declare const COMPUTER_FILE = "computer.md";
35
+ export declare const OLD_COMPUTER_FILE = "env.md";
36
+ export declare function readInstance(files: FileMap): ReadInstanceResult;
37
+ export declare function agentBody(instance: Pick<Instance, "agent" | "tools"> & Partial<Pick<Instance, "systemPrompt">>, skills?: Frontmatter[], options?: CompileOptions): Frontmatter;
38
+ export declare function envBody({ env }: Pick<Instance, "env">): Frontmatter;
39
+ export declare const ENVIRONMENT_KEY = "./computer.md";
40
+ export declare const environmentEntry: (lock: Lock | null | undefined) => LockEntry | undefined;
41
+ export declare function upgradeLock<T extends Lock | null | undefined>(lock: T): T;
@@ -0,0 +1,74 @@
1
+ import { textOf } from "./files.js";
2
+ import { FileError, parseMarkdown } from "./markdown.js";
3
+ import { systemPromptOf } from "./system-prompt.js";
4
+ import { compileTools } from "./tools.js";
5
+ export const AGENT_FILE = "agent.md";
6
+ export const COMPUTER_FILE = "computer.md";
7
+ // computer.md's old name. A folder that still has it works, with a warning to rename it.
8
+ export const OLD_COMPUTER_FILE = "env.md";
9
+ // Reads agent.md and computer.md. Returns { agent, env, errors, warnings }; a file that can't be
10
+ // read is null and has an entry in errors. `env` is computer.md, the agent's environment, and its
11
+ // `file` says which name it was read from.
12
+ export function readInstance(files) {
13
+ const names = Object.keys(files).filter((path) => !path.includes("/"));
14
+ const errors = [];
15
+ const warnings = [];
16
+ const read = (name) => {
17
+ try {
18
+ // Exact names only, so an agent behaves the same on a case-sensitive file system.
19
+ if (!names.includes(name)) {
20
+ const wrongCase = names.find((n) => n.toLowerCase() === name);
21
+ const hint = wrongCase ? ` (found ${wrongCase}; the name must be lowercase)` : "";
22
+ throw new FileError(`${name}: missing${hint}`);
23
+ }
24
+ return parseMarkdown(textOf(files[name]), name);
25
+ }
26
+ catch (err) {
27
+ if (!(err instanceof FileError))
28
+ throw err;
29
+ errors.push(err.message);
30
+ return null;
31
+ }
32
+ };
33
+ const agent = read(AGENT_FILE);
34
+ const hasOldName = names.includes(OLD_COMPUTER_FILE);
35
+ const computerFile = hasOldName && !names.includes(COMPUTER_FILE) ? OLD_COMPUTER_FILE : COMPUTER_FILE;
36
+ if (computerFile === OLD_COMPUTER_FILE)
37
+ warnings.push(`${OLD_COMPUTER_FILE}: this is ${COMPUTER_FILE}'s old name; rename it to ${COMPUTER_FILE}`);
38
+ else if (hasOldName)
39
+ errors.push(`${OLD_COMPUTER_FILE}: this is ${COMPUTER_FILE}'s old name, and the folder has both; remove ${OLD_COMPUTER_FILE}`);
40
+ const env = read(computerFile);
41
+ return { agent, env: env && { ...env, file: computerFile }, errors, warnings };
42
+ }
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. `skills` are the
45
+ // references to the skills deployed from skills/, added to any in agent.md's frontmatter. The system
46
+ // prompt is agent.md's body, then system_prompt/'s files.
47
+ // `options.toolsets` is the catalog behind `type: agentbook` tool files.
48
+ export function agentBody(instance, skills = [], options = {}) {
49
+ const { agent, tools } = instance;
50
+ const body = { ...agent.data, tools: compileTools(tools, options) };
51
+ if (skills.length > 0)
52
+ body.skills = [...(agent.data.skills ?? []), ...skills];
53
+ const system = systemPromptOf(instance);
54
+ if (system)
55
+ body.system = system;
56
+ return body;
57
+ }
58
+ export function envBody({ env }) {
59
+ return { ...env.data };
60
+ }
61
+ // The lock's entry for the environment is under "./computer.md". A lock written before computer.md
62
+ // was renamed has it under "./env.md": environmentEntry finds it either way, and upgradeLock moves
63
+ // it, so the next deploy updates that environment rather than making another.
64
+ export const ENVIRONMENT_KEY = `./${COMPUTER_FILE}`;
65
+ const OLD_ENVIRONMENT_KEY = `./${OLD_COMPUTER_FILE}`;
66
+ export const environmentEntry = (lock) => lock?.resources?.[ENVIRONMENT_KEY] ?? lock?.resources?.[OLD_ENVIRONMENT_KEY];
67
+ export function upgradeLock(lock) {
68
+ const resources = lock?.resources;
69
+ if (resources?.[OLD_ENVIRONMENT_KEY] && !resources[ENVIRONMENT_KEY]) {
70
+ resources[ENVIRONMENT_KEY] = resources[OLD_ENVIRONMENT_KEY];
71
+ delete resources[OLD_ENVIRONMENT_KEY];
72
+ }
73
+ return lock;
74
+ }
@@ -0,0 +1,11 @@
1
+ import { type Document } from "yaml";
2
+ export type Frontmatter = Record<string, any>;
3
+ export interface MarkdownFile {
4
+ data: Frontmatter;
5
+ body: string;
6
+ raw: string;
7
+ }
8
+ export declare class FileError extends Error {
9
+ }
10
+ export declare function parseMarkdown(text: string, file: string): MarkdownFile;
11
+ export declare function editFrontmatter(text: string, edit: (doc: Document) => void): string;