@soft-boy/agentschema 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,9 +12,11 @@ my-agent/
12
12
  ├── skills/
13
13
  │ └── code-review/
14
14
  │ └── SKILL.md # instructions the agent loads when needed
15
- └── vaults/
16
- └── secrets/
17
- └── creds.md # a credential, without its secrets
15
+ ├── vaults/
16
+ │ └── secrets/
17
+ │ └── creds.md # a credential, without its secrets
18
+ └── channels/
19
+ └── telegram.md # a place people can talk to it
18
20
  ```
19
21
 
20
22
  **Status:** v0.2 draft. v0.2 breaks from the Claude Managed Agents schema: tools move out of `agent.md` and into `tools/`.
@@ -53,7 +55,7 @@ agentschema run my-agent
53
55
 
54
56
  ## Specification
55
57
 
56
- `agent.md` and `env.md` are required; everything else is optional. `agentschema check` validates a folder without calling the API.
58
+ `agent.md` and `env.md` are required; everything else is optional. `agentschema check` validates a folder without calling the API. This is the short version, and the full specification is in [docs/](docs/README.md).
57
59
 
58
60
  ### `agent.md`
59
61
 
@@ -139,6 +141,19 @@ auth:
139
141
  ---
140
142
  ```
141
143
 
144
+ ### `channels/`
145
+
146
+ Each `.md` file is a place people can talk to the agent: `telegram`, `twilio`, `sendgrid`, `slack` or `discord`. The frontmatter says who can use it and how it behaves, and the body is added to the system prompt there. `check` validates these files, but `deploy` and `run` don't connect them, because that takes a host that's always on. See [Channels](docs/channels.md):
147
+
148
+ ```markdown
149
+ ---
150
+ type: telegram
151
+ allow: "*"
152
+ ---
153
+
154
+ You're chatting on Telegram. Keep replies short.
155
+ ```
156
+
142
157
  ## Usage
143
158
 
144
159
  ```sh
@@ -0,0 +1,289 @@
1
+ import { pathsUnder, textOf } from "./files.js";
2
+ import { AGENT_FILE } from "./instance.js";
3
+ import { FileError, parseMarkdown } from "./markdown.js";
4
+ import { AGENTBOOK, MCP_TOOLSET } from "./tools.js";
5
+
6
+ // A channel is a place people can talk to an agent, like Telegram or SMS. Its file says how the channel
7
+ // should behave, and a host that's always on (Agentbook, say) does the connecting, because Anthropic
8
+ // doesn't receive these messages and `run` shouldn't either. So nothing here is sent to the API.
9
+ export const CHANNELS_DIR = "channels";
10
+ export const ANYONE = "*";
11
+
12
+ const DEFAULT_RESPOND_TO = ["direct", "mention"];
13
+ const DEFAULT_EXPIRES_AFTER = "24h";
14
+ const RESPOND_TO = ["direct", "mention", "reply", "all"];
15
+ const LIMITS = ["messages_per_sender_per_hour", "messages_per_day"];
16
+ const SHARED_FIELDS = ["type", "enabled", "allow", "respond_to", "scope", "expires_after", "approvals", "limits", "greeting"];
17
+ const MAX_GREETING = 1000;
18
+ const MAX_SYSTEM_PROMPT = 100_000;
19
+
20
+ const code = (value) => `\`${value}\``;
21
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
22
+
23
+ // Phone numbers and long IDs read as numbers in YAML if they aren't quoted, which loses the +.
24
+ const matches = (pattern, what) => (value) => {
25
+ if (typeof value === "string" && pattern.test(value)) return null;
26
+ return `must be ${what}${typeof value === "number" ? " (put it in quotes, or YAML reads it as a number)" : ""}`;
27
+ };
28
+ const oneOf = (...values) => (value) => (values.includes(value) ? null : `must be ${values.map(code).join(" or ")}`);
29
+ const text = (value) => (typeof value === "string" && value.trim() !== "" ? null : "must be text");
30
+ const listOf = (check) => (value) => {
31
+ if (!Array.isArray(value)) return "must be a list";
32
+ return value.map(check).find(Boolean) ?? null;
33
+ };
34
+
35
+ const PHONE = /^\+[1-9]\d{6,14}$/;
36
+ const DISCORD_ID = /^\d{17,20}$/;
37
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
38
+
39
+ // What differs between channels. Each `secrets` entry is something the host asks for and keeps: never
40
+ // the file, and never a vault, because a vault's secrets can't be read back to send a reply. The first
41
+ // of `scopes` is the default. `identity` is what two files in one agent can't share, where that's known.
42
+ export const CHANNEL_TYPES = {
43
+ telegram: {
44
+ secrets: ["bot_token"],
45
+ scopes: ["sender", "room"],
46
+ approvals: ["deny", "sender"],
47
+ hasGroups: true,
48
+ allow: matches(/^(\d+|@[A-Za-z0-9_]{5,32})$/, "a numeric user ID or an @username"),
49
+ fields: {},
50
+ },
51
+ twilio: {
52
+ secrets: ["account_sid", "auth_token"],
53
+ scopes: ["sender"],
54
+ approvals: ["deny", "sender"],
55
+ hasGroups: false,
56
+ allow: matches(PHONE, "a phone number like +14155550123"),
57
+ fields: {
58
+ transport: { required: true, check: oneOf("sms", "whatsapp") },
59
+ from: { required: true, check: matches(PHONE, "a phone number like +14155550123") },
60
+ },
61
+ identity: ({ transport, from }) => `${transport} ${from}`,
62
+ },
63
+ sendgrid: {
64
+ secrets: ["api_key"],
65
+ scopes: ["thread", "sender"],
66
+ // An email has no buttons, and its sender can be forged.
67
+ approvals: ["deny"],
68
+ hasGroups: false,
69
+ allow: matches(/^(\*|[^\s@]+)@[^\s@]+\.[^\s@]+$/, "an email address, or *@ and a domain"),
70
+ fields: {
71
+ address: { required: true, check: matches(EMAIL, "an email address") },
72
+ from_name: { check: text },
73
+ },
74
+ identity: ({ address }) => address,
75
+ },
76
+ slack: {
77
+ secrets: ["bot_token", "signing_secret"],
78
+ scopes: ["thread", "sender", "room"],
79
+ approvals: ["deny", "sender"],
80
+ hasGroups: true,
81
+ allow: matches(/^[UW][A-Z0-9]{2,}$/, "a member ID like U012AB3CD"),
82
+ fields: {
83
+ channels: { check: listOf(matches(/^[CG][A-Z0-9]{2,}$/, "a channel ID like C012AB3CD")) },
84
+ },
85
+ },
86
+ discord: {
87
+ secrets: ["bot_token"],
88
+ scopes: ["sender", "room"],
89
+ approvals: ["deny", "sender"],
90
+ // Reading ordinary messages takes an always-on connection, so people talk to it with a slash command.
91
+ hasGroups: false,
92
+ allow: matches(DISCORD_ID, "a numeric user ID"),
93
+ fields: {
94
+ application_id: { required: true, check: matches(DISCORD_ID, "a numeric application ID") },
95
+ public_key: { required: true, check: matches(/^[0-9a-f]{64}$/, "the 64-character public key") },
96
+ guilds: { check: listOf(matches(DISCORD_ID, "a numeric server ID")) },
97
+ command: { check: matches(/^[a-z0-9_-]{1,32}$/, "a slash command's name, like ask") },
98
+ },
99
+ identity: ({ application_id: id }) => id,
100
+ },
101
+ };
102
+
103
+ // Reads channels/: each .md file directly inside it is a channel named after the file, so an agent can
104
+ // have two Telegram bots. No channels/ folder means no channels.
105
+ // Returns { channels, errors }; a file that can't be parsed has an entry in errors.
106
+ export function readChannels(files) {
107
+ if (CHANNELS_DIR in files) return { channels: [], errors: [`${CHANNELS_DIR}: not a directory`] };
108
+
109
+ const channels = [];
110
+ const errors = [];
111
+ const reportedFolders = new Set();
112
+ for (const file of pathsUnder(files, CHANNELS_DIR)) {
113
+ const [, item, ...rest] = file.split("/");
114
+ if (rest.length > 0) {
115
+ const folder = `${CHANNELS_DIR}/${item}`;
116
+ if (!reportedFolders.has(folder)) errors.push(`${folder}: ${CHANNELS_DIR}/ holds channel files, not folders`);
117
+ reportedFolders.add(folder);
118
+ } else if (item.endsWith(".md")) {
119
+ try {
120
+ channels.push({ file, name: item.slice(0, -".md".length), ...parseMarkdown(textOf(files[file]), file) });
121
+ } catch (err) {
122
+ if (!(err instanceof FileError)) throw err;
123
+ errors.push(err.message);
124
+ }
125
+ }
126
+ }
127
+ return { channels, errors };
128
+ }
129
+
130
+ // Errors and warnings for the channel files, in check's format. `agent` and `tools` are what the channel
131
+ // is attached to, and `toolsets` is the catalog behind `type: agentbook` files.
132
+ export function checkChannels(channels, { agent = { body: "" }, tools = [], toolsets } = {}, errors = [], warnings = []) {
133
+ const unasked = toolsThatRunUnasked(tools, toolsets);
134
+ const identities = new Map();
135
+
136
+ for (const channel of channels) {
137
+ const err = (msg) => errors.push(`${channel.file}: ${msg}`);
138
+ const warn = (msg) => warnings.push(`${channel.file}: ${msg}`);
139
+ const { data, name } = channel;
140
+
141
+ // Hosts use the name in webhook addresses and to store the channel's secrets.
142
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name)) err("the name may only use lowercase letters, digits, _ and -, up to 64 characters");
143
+
144
+ const type = Object.hasOwn(CHANNEL_TYPES, data.type) ? CHANNEL_TYPES[data.type] : null;
145
+ if (!type) {
146
+ err(`\`type\` must be ${Object.keys(CHANNEL_TYPES).map(code).join(", ")}`);
147
+ continue;
148
+ }
149
+
150
+ checkAllow(data, type, err, warn);
151
+ checkShared(data, type, err, warn);
152
+ for (const [field, { required, check }] of Object.entries(type.fields)) {
153
+ if (data[field] === undefined) {
154
+ if (required) err(`\`${field}\` is required`);
155
+ continue;
156
+ }
157
+ const problem = check(data[field]);
158
+ if (problem) err(`\`${field}\` ${problem}`);
159
+ }
160
+
161
+ for (const key of Object.keys(data)) {
162
+ if (type.secrets.includes(key)) err(`\`${key}\` doesn't go in the file; whatever hosts the channel asks for it and keeps it`);
163
+ else if (!SHARED_FIELDS.includes(key) && !Object.hasOwn(type.fields, key)) err(`unknown field \`${key}\``);
164
+ }
165
+
166
+ if (channelSystem(agent, channel).length > MAX_SYSTEM_PROMPT) {
167
+ err(`with ${AGENT_FILE}'s system prompt, this comes to more than ${MAX_SYSTEM_PROMPT.toLocaleString("en-US")} characters; the limit is the API's`);
168
+ }
169
+
170
+ const hasRequiredFields = Object.entries(type.fields).every(([field, { required }]) => !required || data[field] !== undefined);
171
+ if (type.identity && hasRequiredFields) {
172
+ const identity = `${data.type} ${type.identity(data)}`;
173
+ if (identities.has(identity)) err(`${identities.get(identity)} already uses this`);
174
+ else identities.set(identity, channel.file);
175
+ }
176
+
177
+ if (data.allow === ANYONE && data.enabled !== false && unasked.length > 0) {
178
+ warn(`anyone can message this channel, and these tools can run without asking, through your sign-ins and connections: ${unasked.join(", ")}`);
179
+ }
180
+ }
181
+ return { errors, warnings };
182
+ }
183
+
184
+ function checkAllow({ allow, approvals }, type, err, warn) {
185
+ if (allow === undefined || allow === null) return err(`\`allow\` is required: "${ANYONE}" for anyone, or a list of who can use it`);
186
+ if (allow === ANYONE) {
187
+ if (approvals === "sender") err(`\`approvals: sender\` would let anyone approve tools, so it needs \`allow\` to be a list`);
188
+ return;
189
+ }
190
+ if (!Array.isArray(allow)) return err(`\`allow\` must be "${ANYONE}", or a list of who can use it`);
191
+ if (allow.length === 0) return err("`allow` has nobody in it; list who can use it, or set `enabled: false`");
192
+ for (const entry of allow) {
193
+ if (entry === ANYONE) return err(`write \`allow: "${ANYONE}"\` on its own, not in a list`);
194
+ const problem = type.allow(entry);
195
+ if (problem) err(`\`allow\`: ${JSON.stringify(entry)} ${problem}`);
196
+ else if (typeof entry === "string" && entry.startsWith("@")) warn(`\`allow\`: ${entry} can change hands, because Telegram usernames can be given up and reclaimed; a numeric user ID is safer`);
197
+ }
198
+ }
199
+
200
+ function checkShared(data, type, err, warn) {
201
+ if (data.enabled !== undefined && typeof data.enabled !== "boolean") err("`enabled` must be true or false");
202
+
203
+ if (data.respond_to !== undefined) {
204
+ const list = data.respond_to;
205
+ if (!Array.isArray(list) || list.length === 0 || list.some((v) => !RESPOND_TO.includes(v))) {
206
+ err(`\`respond_to\` must be a list of ${RESPOND_TO.map(code).join(", ")}`);
207
+ } else if (list.includes("all") && list.length > 1) {
208
+ err("`respond_to`: `all` already covers the others, so list it on its own");
209
+ } else if (!type.hasGroups) {
210
+ warn(`\`respond_to\` has no effect on ${data.type}`);
211
+ }
212
+ }
213
+
214
+ if (data.scope !== undefined && !type.scopes.includes(data.scope)) err(`\`scope\` must be ${type.scopes.map(code).join(" or ")} on ${data.type}`);
215
+
216
+ if (data.expires_after !== undefined && durationMs(data.expires_after) === null) {
217
+ err("`expires_after` must be a length of time like 30m, 24h or 7d");
218
+ }
219
+
220
+ if (data.approvals !== undefined && !type.approvals.includes(data.approvals)) {
221
+ err(`\`approvals\` must be ${type.approvals.map(code).join(" or ")} on ${data.type}`);
222
+ }
223
+
224
+ if (data.limits !== undefined) {
225
+ if (!isObject(data.limits)) err("`limits` must be a mapping");
226
+ else {
227
+ for (const [key, value] of Object.entries(data.limits)) {
228
+ if (!LIMITS.includes(key)) err(`unknown field \`limits.${key}\`; use ${LIMITS.map(code).join(" or ")}`);
229
+ else if (!Number.isInteger(value) || value < 1) err(`\`limits.${key}\` must be a whole number above 0`);
230
+ }
231
+ }
232
+ }
233
+
234
+ if (data.greeting !== undefined) {
235
+ if (text(data.greeting)) err("`greeting` must be text");
236
+ else if (data.greeting.length > MAX_GREETING) err(`\`greeting\` is ${data.greeting.length} characters; the limit is ${MAX_GREETING.toLocaleString("en-US")}`);
237
+ }
238
+ }
239
+
240
+ // The tools that act through the owner's sign-ins and connections without anyone approving each call.
241
+ // Pre-built tools aren't here, since they run in the session's own container. In a toolset's table, a
242
+ // blank permission means the file's default, which for an MCP server is the API's default of asking.
243
+ function toolsThatRunUnasked(tools, toolsets) {
244
+ const isOn = (row) => row.enabled.toLowerCase() === "true";
245
+ return tools.flatMap((tool) => {
246
+ if (tool.data.type === MCP_TOOLSET) {
247
+ const defaults = tool.data.default_config;
248
+ const fallback = defaults?.permission_policy?.type ?? "always_ask";
249
+ if (tool.rows?.length) {
250
+ return tool.rows.filter((row) => isOn(row) && (row.permission || fallback) !== "always_ask").map((row) => `${tool.name}.${row.name}`);
251
+ }
252
+ return fallback !== "always_ask" && defaults?.enabled !== false ? [`every tool in ${tool.name}`] : [];
253
+ }
254
+ if (tool.data.type === AGENTBOOK) {
255
+ const catalog = toolsets?.[tool.data.toolset]?.tools;
256
+ const neverRunsLive = (row) => catalog?.find((t) => t.name === row.name)?.liveAllowed === false;
257
+ return (tool.rows ?? []).filter((row) => isOn(row) && row.permission === "always_allow" && !neverRunsLive(row)).map((row) => `${tool.name}.${row.name}`);
258
+ }
259
+ return [];
260
+ });
261
+ }
262
+
263
+ const UNIT_MS = { m: 60_000, h: 3_600_000, d: 86_400_000 };
264
+
265
+ // A length of time like 30m, 24h or 7d, in milliseconds, or null if it isn't one.
266
+ export function durationMs(value) {
267
+ const match = typeof value === "string" ? /^([1-9]\d*)([mhd])$/.exec(value) : null;
268
+ return match ? Number(match[1]) * UNIT_MS[match[2]] : null;
269
+ }
270
+
271
+ // How a channel behaves, with the defaults filled in, so that every host agrees on them.
272
+ export function channelSettings({ data }) {
273
+ const type = CHANNEL_TYPES[data.type];
274
+ return {
275
+ type: data.type,
276
+ enabled: data.enabled ?? true,
277
+ allow: data.allow,
278
+ respondTo: data.respond_to ?? DEFAULT_RESPOND_TO,
279
+ scope: data.scope ?? type.scopes[0],
280
+ expiresAfterMs: durationMs(data.expires_after ?? DEFAULT_EXPIRES_AFTER),
281
+ approvals: data.approvals ?? "deny",
282
+ limits: data.limits ?? {},
283
+ greeting: data.greeting ?? null,
284
+ };
285
+ }
286
+
287
+ // The system prompt for a conversation on this channel: the agent's, then the channel's own instructions.
288
+ // A session can override `system` for itself, so a channel doesn't need its own copy of the agent.
289
+ export const channelSystem = (agent, channel) => [agent.body, channel.body].filter(Boolean).join("\n\n");
package/lib/check.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { checkChannels, readChannels } from "./channels.js";
1
2
  import { textOf } from "./files.js";
2
3
  import { AGENT_FILE, ENV_FILE, readInstance } from "./instance.js";
3
4
  import { MAX_UPLOAD_BYTES, SKILLS_DIR, readSkills } from "./skills.js";
@@ -16,6 +17,10 @@ const SECRET_PATTERNS = [
16
17
  [/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token"],
17
18
  [/\bxox[bpas]-[A-Za-z0-9-]{10,}/, "a Slack token"],
18
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"],
19
24
  ];
20
25
 
21
26
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -28,7 +33,8 @@ export function checkFiles(files, options = {}) {
28
33
  const { tools, errors: toolErrors } = readTools(files);
29
34
  const { vaults, errors: vaultErrors } = readVaults(files);
30
35
  const { skills, errors: skillErrors } = readSkills(files);
31
- errors.push(...toolErrors, ...vaultErrors, ...skillErrors);
36
+ const { channels, errors: channelErrors } = readChannels(files);
37
+ errors.push(...toolErrors, ...vaultErrors, ...skillErrors, ...channelErrors);
32
38
  const warnings = [];
33
39
 
34
40
  if (agent) checkAgent(agent, errors, warnings);
@@ -41,17 +47,18 @@ export function checkFiles(files, options = {}) {
41
47
  if (declaredSkills + skills.length > 500) errors.push(`${declaredSkills + skills.length} skills; the limit is 500`);
42
48
  for (const vault of vaults) checkVault(vault, errors, warnings);
43
49
  checkEnvVarCredentials(vaults, env, warnings);
50
+ checkChannels(channels, { agent: agent ?? undefined, tools, toolsets: options.toolsets }, errors, warnings);
44
51
 
45
52
  const vaultFiles = vaults.flatMap((v) => [...(v.file ? [[`${v.path}/${VAULT_FILE}`, v.file]] : []), ...v.credentials.map((c) => [c.file, c])]);
46
53
  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]) {
54
+ for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t]), ...vaultFiles, ...skillTexts, ...channels.map((c) => [c.file, c])]) {
48
55
  if (!parsed) continue;
49
56
  for (const [pattern, what] of SECRET_PATTERNS) {
50
57
  if (pattern.test(parsed.raw)) errors.push(`${file}: looks like it contains ${what}; keep secrets out of these files`);
51
58
  }
52
59
  }
53
60
 
54
- return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills } : null };
61
+ return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills, channels } : null };
55
62
  }
56
63
 
57
64
  function checkAgent({ data, body }, errors, warnings) {
package/lib/index.js CHANGED
@@ -1,5 +1,6 @@
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
4
  export { checkFiles } from "./check.js";
4
5
  export { bytesOf, isIgnoredPath, pathsUnder, textOf } from "./files.js";
5
6
  export { AGENT_FILE, ENV_FILE, agentBody, envBody, readInstance } from "./instance.js";
@@ -9,7 +10,7 @@ export { MAX_UPLOAD_BYTES, SKILLS_DIR, SKILL_FILE, readSkills, skillKey, skillRe
9
10
  export { agentMessageText, textStream } from "./stream.js";
10
11
  export {
11
12
  AGENTBOOK, MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR,
12
- agentbookTools, compileTools, readTools,
13
+ agentbookTools, compileTools, mcpToolsetFile, readTools,
13
14
  } from "./tools.js";
14
15
  export {
15
16
  CREDENTIAL_TYPES, ENV_VAR, MCP_OAUTH, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE,
package/lib/scaffold.js CHANGED
@@ -13,6 +13,7 @@ export function defaultAnswers(name) {
13
13
  model: MODELS[0],
14
14
  system: "You are a helpful assistant.",
15
15
  tools: true,
16
+ permission: "auto",
16
17
  environment: slug,
17
18
  networking: "limited",
18
19
  packageManagers: true,
@@ -36,14 +37,15 @@ export function scaffold(answers) {
36
37
  [ENV_FILE]: `---\n${stringify(env)}---\nCloud container with ${access}.\n`,
37
38
  };
38
39
  if (answers.tools) {
39
- files[`${TOOLS_DIR}/${TOOLSET_FILE}`] = builtInFile(PREBUILT_TOOLS);
40
+ files[`${TOOLS_DIR}/${TOOLSET_FILE}`] = builtInFile(PREBUILT_TOOLS, PREBUILT_TOOLS, answers.permission);
40
41
  }
41
42
  return files;
42
43
  }
43
44
 
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");
45
+ // The pre-built toolset file, with a row for each of `names`: on if it's in `enabled`, each with
46
+ // `permission`, so what's chosen is there to read and change. `auto` is what the API recommends for
47
+ // these tools: Anthropic judges each call, and asks when it can't tell.
48
+ export function builtInFile(names, enabled = names, permission = "auto") {
49
+ const rows = names.map((name) => `| \`${name}\` | \`${enabled.includes(name)}\` | \`${permission}\` |`).join("\n");
48
50
  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
51
  }
package/lib/tools.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { stringify } from "yaml";
1
2
  import { pathsUnder, textOf } from "./files.js";
2
3
  import { FileError, parseMarkdown } from "./markdown.js";
3
4
 
@@ -246,6 +247,21 @@ function checkCustom(tool, err) {
246
247
  }
247
248
  }
248
249
 
250
+ // An MCP server's tool file. With the server's tools, it's a table of them, all on, each with
251
+ // `permission`. A tool the server adds later isn't in the table, so it gets the API's defaults: on, and
252
+ // asking before each call. Many servers won't list their tools until you've signed in, so with no tools
253
+ // it keeps `permission` for all of them, ready for the table: see listedMcpToolset.
254
+ export function mcpToolsetFile({ name, tools = [], permission = "always_ask" }) {
255
+ const front = { type: MCP_TOOLSET, mcp_server_name: name };
256
+ if (tools.length > 0) {
257
+ const rows = tools.map((tool) => `| \`${tool}\` | \`true\` | \`${permission}\` |`);
258
+ const body = ["Set Enabled to false to turn a tool off.", "", "## Tools", "", "| Name | Enabled | Permission |", "|---|---|---|", ...rows, ""].join("\n");
259
+ return `---\n${stringify(front)}---\n\n${body}`;
260
+ }
261
+ if (permission !== "always_ask") front.default_config = { permission_policy: { type: permission } };
262
+ return `---\n${stringify(front)}---\n\nEvery tool the server offers is on. Its tools get listed here once it's been signed in to.\n`;
263
+ }
264
+
249
265
  // The agentbook tools a folder turns on, as { file, toolset, name, description, input_schema,
250
266
  // permission }. `toolsets` is the catalog, { [toolset]: { tools: [{ name, description, input_schema }] } }.
251
267
  // A blank permission means `always_ask`, the safe choice for a tool with no policy of its own.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soft-boy/agentschema",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Markdown based AI agent schema",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cred.js CHANGED
@@ -1,9 +1,11 @@
1
- import { basename, dirname, relative, resolve, sep } from "node:path";
1
+ import { writeFileSync } from "node:fs";
2
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
2
3
  import Anthropic from "@anthropic-ai/sdk";
3
4
  import { check } from "./check.js";
4
5
  import { DeployError, call, openLock, retrieve } from "./deploy.js";
5
6
  import { LOCK_FILE, hashBody, writeLock } from "./lock.js";
6
- import { updateFrontmatter } from "./folder.js";
7
+ import { readFolder, updateFrontmatter } from "./folder.js";
8
+ import { listedMcpToolset } from "./mcp.js";
7
9
  import { authorizationRequest, discover, exchangeCode, registerClient, startCallbackServer } from "./oauth.js";
8
10
  import {
9
11
  ENV_VAR, VAULTS_DIR, VAULT_FILE, changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings,
@@ -168,6 +170,7 @@ export async function credLogin(path, { client, ask, openBrowser, port = 0, fetc
168
170
 
169
171
  const secrets = { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, refreshToken: tokens.refreshToken, clientSecret };
170
172
  const { dir, vault, cred } = located;
173
+ await listToolsInFile(dir, auth.mcp_server_url, tokens.accessToken, { fetch, log });
171
174
  const lock = openLock(dir, client);
172
175
  const existing = lock.resources[credentialKey(cred)];
173
176
  if (existing && existing.vault_id === lock.resources[vaultKey(vault)]?.id) {
@@ -179,6 +182,14 @@ export async function credLogin(path, { client, ask, openBrowser, port = 0, fetc
179
182
  }
180
183
  }
181
184
 
185
+ // Now that the server will say what it offers, lists its tools in their file.
186
+ async function listToolsInFile(dir, url, token, { fetch, log }) {
187
+ const listed = await listedMcpToolset(readFolder(dir), url, { fetch, token });
188
+ if (!listed) return;
189
+ writeFileSync(join(dir, listed.path), listed.text);
190
+ log(`Listed the server's tools in ${listed.path}.`);
191
+ }
192
+
182
193
  async function required(ask, question) {
183
194
  const answer = (await ask(question, { secret: true })).trim();
184
195
  if (!answer) throw new DeployError(`${question.replace(/:\s*$/, "")} is required`);
package/src/deploy.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { join } from "node:path";
2
2
  import Anthropic, { toFile } from "@anthropic-ai/sdk";
3
+ import { CHANNELS_DIR, readChannels } from "../lib/channels.js";
3
4
  import { checkFiles } from "../lib/check.js";
4
5
  import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "../lib/instance.js";
5
6
  import { skillKey, skillRefs } from "../lib/skills.js";
@@ -15,8 +16,9 @@ export class DeployError extends Error {}
15
16
  export async function deploy(dir, { client, dryRun = false, force = false, log = () => {} }) {
16
17
  const problem = folderProblem(dir);
17
18
  if (problem) throw new DeployError(`check failed:\n ${problem}`);
19
+ const files = readFolder(dir);
18
20
  const { plan } = await deployFiles({
19
- files: readFolder(dir),
21
+ files,
20
22
  lock: readLock(dir),
21
23
  client,
22
24
  dryRun,
@@ -25,6 +27,7 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
25
27
  saveLock: (lock) => writeLock(dir, lock),
26
28
  pathOf: (file) => join(dir, file),
27
29
  });
30
+ if (readChannels(files).channels.length > 0) log(`${CHANNELS_DIR}/ isn't connected by deploying from here; a channel needs a host that's always on, such as Agentbook`);
28
31
  return plan;
29
32
  }
30
33
 
package/src/folder.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { CHANNELS_DIR } from "../lib/channels.js";
3
4
  import { editFrontmatter } from "../lib/markdown.js";
4
5
  import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
5
6
  import { SKILLS_DIR } from "../lib/skills.js";
6
7
  import { TOOLS_DIR } from "../lib/tools.js";
7
8
  import { VAULTS_DIR } from "../lib/vaults.js";
8
9
 
9
- const FOLDERS = [TOOLS_DIR, SKILLS_DIR, VAULTS_DIR];
10
+ const FOLDERS = [TOOLS_DIR, SKILLS_DIR, VAULTS_DIR, CHANNELS_DIR];
10
11
  const TOP_LEVEL_FILES = [AGENT_FILE, ENV_FILE];
11
12
 
12
13
  // Why `dir` can't be read as an agent folder, or null when it can.
package/src/init.js CHANGED
@@ -3,6 +3,7 @@ import { basename, dirname, resolve } from "node:path";
3
3
  import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
4
4
  import { MODELS, NETWORKING, defaultAnswers, scaffold } from "../lib/scaffold.js";
5
5
  import { TOOLSET_FILE, TOOLS_DIR } from "../lib/tools.js";
6
+ import { choosePermission } from "./tools-menu.js";
6
7
  import { prompts } from "./prompts.js";
7
8
 
8
9
  export class InitError extends Error {}
@@ -41,6 +42,7 @@ async function ask(answers, input, output) {
41
42
  answers.model = await io.select("Model?", MODELS, answers.model);
42
43
  answers.system = await io.text("System prompt?", answers.system);
43
44
  answers.tools = await confirm("Give it the built-in tools (bash, files, web)?", answers.tools);
45
+ if (answers.tools) answers.permission = await choosePermission(io, answers.permission);
44
46
  answers.environment = await io.text("Environment name?", answers.environment);
45
47
  answers.networking = await io.select("Networking?", NETWORKING, answers.networking);
46
48
  if (answers.networking === "limited") {
package/src/mcp.js CHANGED
@@ -1,16 +1,20 @@
1
+ import { readTools, MCP_TOOLSET, mcpToolsetFile } from "../lib/tools.js";
2
+ import { readInstance } from "../lib/instance.js";
3
+
1
4
  // Just enough of the MCP client protocol (Streamable HTTP) to ask a server for its tools.
2
5
 
3
6
  const PROTOCOL_VERSION = "2025-06-18";
4
7
  const TIMEOUT_MS = 10_000;
5
8
 
6
- // The names of the tools an MCP server offers, sorted. Returns null when the server won't say
7
- // without signing in, or can't be reached. Sends no credentials.
8
- export async function listMcpTools(url, { fetch = globalThis.fetch } = {}) {
9
+ // The names of the tools an MCP server offers, sorted. Returns null when the server won't say, or
10
+ // can't be reached. Many only say once you've signed in, so `token` is sent if it's given.
11
+ export async function listMcpTools(url, { fetch = globalThis.fetch, token, clientName = "agentschema" } = {}) {
9
12
  try {
10
13
  let sessionId = null;
11
14
  const send = async (message) => {
12
15
  const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
13
16
  if (sessionId) headers["mcp-session-id"] = sessionId;
17
+ if (token) headers.authorization = `Bearer ${token}`;
14
18
  const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(message), signal: AbortSignal.timeout(TIMEOUT_MS) });
15
19
  sessionId = res.headers.get("mcp-session-id") ?? sessionId;
16
20
  if (!res.ok) throw new Error(`status ${res.status}`);
@@ -21,7 +25,7 @@ export async function listMcpTools(url, { fetch = globalThis.fetch } = {}) {
21
25
  jsonrpc: "2.0",
22
26
  id: 1,
23
27
  method: "initialize",
24
- params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "agentschema", version: "0" } },
28
+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: clientName, version: "0" } },
25
29
  });
26
30
  await send({ jsonrpc: "2.0", method: "notifications/initialized" });
27
31
 
@@ -39,6 +43,21 @@ export async function listMcpTools(url, { fetch = globalThis.fetch } = {}) {
39
43
  }
40
44
  }
41
45
 
46
+ // The tool file for the server at `url`, now listing its tools, once there's a way to ask. Returns
47
+ // { path, text }, or null if there's nothing to change: the file has a table already, so it may hold
48
+ // choices worth keeping, or the agent has no file for that server, or it won't say what it offers.
49
+ export async function listedMcpToolset(files, url, options = {}) {
50
+ const servers = readInstance(files).agent?.data.mcp_servers;
51
+ const server = Array.isArray(servers) ? servers.find((candidate) => candidate?.url === url) : null;
52
+ if (!server) return null;
53
+ const tool = readTools(files).tools.find((candidate) => candidate.data.type === MCP_TOOLSET && candidate.data.mcp_server_name === server.name);
54
+ if (!tool || tool.rows?.length) return null;
55
+
56
+ const names = await listMcpTools(url, options);
57
+ if (!names?.length) return null;
58
+ return { path: tool.file, text: mcpToolsetFile({ name: server.name, tools: names, permission: tool.data.default_config?.permission_policy?.type ?? "always_ask" }) };
59
+ }
60
+
42
61
  // A response is either plain JSON, or a stream of events with the JSON in a `data:` line.
43
62
  function parseResponse(text, id) {
44
63
  const trimmed = text.trim();
package/src/node.js CHANGED
@@ -5,5 +5,6 @@ export { createCredential, deleteCredential } from "./cred.js";
5
5
  export { DeployError, deploy, deployFiles, prepareLock } from "./deploy.js";
6
6
  export { readFolder, updateFrontmatter } from "./folder.js";
7
7
  export { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
8
+ export { listMcpTools, listedMcpToolset } from "./mcp.js";
8
9
  export { OAuthError, authorizationRequest, discover, exchangeCode, registerClient } from "./oauth.js";
9
10
  export { Conversation, SessionError, openSession, startSession } from "./session.js";
package/src/session.js CHANGED
@@ -52,17 +52,20 @@ export async function openSession(dir, { client, sessionId }) {
52
52
  //
53
53
  // instance the checked files, for finding the vaults to attach
54
54
  // agentVersion the agent version to pin, instead of the lock's latest
55
+ // system the system prompt for this session only, such as with a channel's instructions added
55
56
  // budget the API's session budget, to cap what the session can spend
56
57
  // pathOf how to show a file's path to the user in messages
57
58
  //
58
59
  // Returns { session, notes }.
59
- export async function startSession({ instance, lock, client, agentVersion, title, budget, pathOf = (file) => file }) {
60
+ export async function startSession({ instance, lock, client, agentVersion, system, title, budget, pathOf = (file) => file }) {
60
61
  const agent = lock?.resources?.[`./${AGENT_FILE}`];
61
62
  const env = lock?.resources?.[`./${ENV_FILE}`];
62
63
  if (!agent || !env) throw new SessionError("this agent hasn't been deployed (no agent or environment in its lock)");
63
64
 
65
+ const pinned = { id: agent.id, version: Number(agentVersion ?? agent.version) };
64
66
  const params = {
65
- agent: { type: "agent", id: agent.id, version: Number(agentVersion ?? agent.version) },
67
+ // Overriding affects this session only, and doesn't change the agent or make a new version of it.
68
+ agent: system === undefined ? { type: "agent", ...pinned } : { type: "agent_with_overrides", ...pinned, system },
66
69
  environment_id: env.id,
67
70
  };
68
71
 
package/src/tools-menu.js CHANGED
@@ -8,7 +8,7 @@ import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
8
8
  import { builtInFile } from "../lib/scaffold.js";
9
9
  import { updateFrontmatter } from "./folder.js";
10
10
  import { listMcpTools } from "./mcp.js";
11
- import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR } from "../lib/tools.js";
11
+ import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR, mcpToolsetFile } from "../lib/tools.js";
12
12
 
13
13
  const PREBUILT = "Pre-built tools (bash, files, web search)";
14
14
  const CUSTOM = "Custom tool (JavaScript that runs on your machine)";
@@ -57,7 +57,7 @@ async function prebuilt(dir, { tools }, io) {
57
57
  enabled = [];
58
58
  for (const name of PREBUILT_TOOLS) if (await io.confirm(` ${name}?`, true)) enabled.push(name);
59
59
  }
60
- return { path: `${TOOLS_DIR}/${TOOLSET_FILE}`, text: builtInFile(PREBUILT_TOOLS, enabled) };
60
+ return { path: `${TOOLS_DIR}/${TOOLSET_FILE}`, text: builtInFile(PREBUILT_TOOLS, enabled, await choosePermission(io, "auto")) };
61
61
  }
62
62
 
63
63
  // A custom tool: its name, description and inputs, with a code block to fill in.
@@ -138,28 +138,20 @@ async function mcp(dir, instance, io, { fetch, log }) {
138
138
  });
139
139
  const addServer = existing ? null : { type: "url", name, url };
140
140
 
141
- const policies = ["always_ask", ...POLICIES.filter((p) => p !== "always_ask")];
142
- const policy = await io.select("Ask you before each call? (permission for its tools)", policies.map(describePolicy), describePolicy("always_ask"));
143
- const permission = policies.find((p) => describePolicy(p) === policy);
141
+ const permission = await choosePermission(io, "always_ask");
144
142
 
145
- // A table of the server's tools, all on, to edit. A tool the server adds later isn't in the
146
- // table, so it gets the API's defaults: on, and asking before each call.
147
143
  log(`Asking ${url} for its tools…`);
148
144
  const names = await listMcpTools(url, { fetch });
149
- const front = { type: MCP_TOOLSET, mcp_server_name: name };
150
- if (names) {
151
- log(`It has ${names.length} tool${names.length === 1 ? "" : "s"}.`);
152
- const rows = names.map((t) => `| \`${t}\` | \`true\` | \`${permission}\` |`);
153
- const body = ["Set Enabled to false to turn a tool off.", "", "## Tools", "", "| Name | Enabled | Permission |", "|---|---|---|", ...rows, ""].join("\n");
154
- return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${stringify(front)}---\n\n${body}`, addServer };
155
- }
145
+ if (names) log(`It has ${names.length} tool${names.length === 1 ? "" : "s"}.`);
146
+ else log("It won't list its tools without signing in, so they'll be listed once you have; until then, every tool is on.");
147
+ return { path: `${TOOLS_DIR}/${name}.md`, text: mcpToolsetFile({ name, tools: names ?? [], permission }), addServer };
148
+ }
156
149
 
157
- // It won't list them without signing in: every tool is on, with the permission chosen.
158
- log("It won't list its tools without signing in, so the file has no table; every tool is on.");
159
- if (permission !== "always_ask") front.default_config = { permission_policy: { type: permission } };
160
- const body = "Every tool the server offers is on. To turn one off, or give it its own permission, add a table:\n\n" +
161
- " ## Tools\n\n | Name | Enabled | Permission |\n |---|---|---|\n | `delete_event` | `false` | |\n";
162
- return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${stringify(front)}---\n\n${body}`, addServer };
150
+ // Asks how a set of tools should be approved, offering `recommended` first.
151
+ export async function choosePermission(io, recommended) {
152
+ const policies = [recommended, ...POLICIES.filter((p) => p !== recommended)];
153
+ const answer = await io.select("Ask you before each call? (permission for its tools)", policies.map(describePolicy), describePolicy(recommended));
154
+ return policies.find((p) => describePolicy(p) === answer);
163
155
  }
164
156
 
165
157
  function describePolicy(policy) {