@soft-boy/agentschema 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +8 -2
  2. package/dist/bin/agentschema.d.ts +2 -0
  3. package/dist/bin/agentschema.js +333 -0
  4. package/dist/lib/channels.d.ts +65 -0
  5. package/dist/lib/channels.js +339 -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 +3 -12
  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 +105 -0
  27. package/dist/lib/tools.js +353 -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
@@ -1,326 +0,0 @@
1
- #!/usr/bin/env node
2
- import { readFileSync } from "node:fs";
3
- import { createInterface } from "node:readline/promises";
4
- import { parseArgs } from "node:util";
5
- import Anthropic from "@anthropic-ai/sdk";
6
- import { chat } from "../src/chat.js";
7
- import { spawn } from "node:child_process";
8
- import { credCreate, credDeploy } from "../src/cred-menu.js";
9
- import { credDelete, credLogin } from "../src/cred.js";
10
- import { check } from "../src/check.js";
11
- import { DeleteError, deleteAgent, deleteSession } from "../src/delete.js";
12
- import { DeployError, deploy } from "../src/deploy.js";
13
- import { loadEnvFile } from "../src/dotenv.js";
14
- import { InitError, init } from "../src/init.js";
15
- import { listAgents, listSessions } from "../src/list.js";
16
- import { prompts } from "../src/prompts.js";
17
- import { SessionError, openSession } from "../src/session.js";
18
- import { toolsCreate } from "../src/tools-menu.js";
19
-
20
- const FOOTER = `ags is a short name for agentschema. dir defaults to the current directory. Every command
21
- but init, check and tools create authenticates with ANTHROPIC_API_KEY, or with a profile from \`ant auth login\`.`;
22
-
23
- const USAGE = `Usage: agentschema <command> [dir] [options]
24
-
25
- Commands:
26
- init <name> Scaffold a new agent folder, asking a few questions
27
- check [dir] Validate the folder's files, without calling the API
28
- deploy [dir] Create or update the skills, agent, environment, vaults and scheduled tasks, and write claude-lock.json
29
- run [dir] Chat with the deployed agent in a new session, loading dir/.env for your tools
30
- list List the agents in your workspace
31
- delete <agent_id> Archive an agent (agents can't be deleted outright)
32
- tools <command> Add pre-built tools, custom tools and MCP servers (agentschema tools -h)
33
- sessions <command> List and delete sessions (agentschema sessions -h)
34
- cred <command> Create and manage the credentials in vaults/ (agentschema cred -h)
35
-
36
- Options:
37
- -y, --yes (init) Skip the questions and use the defaults
38
- (delete) Don't ask for confirmation
39
- --dry-run (deploy) Show what would be created or updated, change nothing
40
- --force (deploy) Update the agent even if it was changed outside this folder
41
- --resume <id> (run) Resume an existing session (sesn_...) instead of starting one
42
- -h, --help Show this help
43
- -v, --version Show the version
44
-
45
- ${FOOTER}`;
46
-
47
- const TOOLS_USAGE = `Usage: agentschema tools <command> [options]
48
-
49
- Each tool is a file in tools/. The pre-built tools share one file, each custom tool has its own,
50
- and so does each MCP server.
51
-
52
- Commands:
53
- create [dir] Add a tool: asks whether it's the pre-built tools, a custom tool or an
54
- MCP server, then writes its file
55
-
56
- Options:
57
- -h, --help Show this help
58
-
59
- dir defaults to the current directory.`;
60
-
61
- const SESSIONS_USAGE = `Usage: agentschema sessions <command> [options]
62
-
63
- Commands:
64
- list List the sessions in your workspace, newest first
65
- delete <id> Delete a session and its history
66
-
67
- Options:
68
- -y, --yes (delete) Don't ask for confirmation
69
- -h, --help Show this help
70
-
71
- Resume a session with agentschema run --resume <id>.`;
72
-
73
- const CRED_USAGE = `Usage: agentschema cred <command> [options]
74
-
75
- Each credential is a file in vaults/<vault>/<name>.md, without its secrets, which go straight
76
- to Anthropic.
77
-
78
- Commands:
79
- create [dir] Add a credential: asks which vault it goes in and whether it's for an MCP
80
- server or an environment variable, writes its file, then signs you in or
81
- asks for its secrets, and creates it in Anthropic
82
- deploy <file> Create the credential a file describes in Anthropic, by signing in or
83
- pasting its secrets
84
- login <file> Sign in to the credential's MCP server in the browser, and store the tokens,
85
- creating the credential or replacing the tokens of the existing one
86
- delete <file> Delete the credential a file describes from Anthropic; the file stays
87
-
88
- Options:
89
- --port <port> (create, deploy, login) Port for the sign-in redirect (default: any free port)
90
- -y, --yes (delete) Don't ask for confirmation
91
- -h, --help Show this help
92
-
93
- dir defaults to the current directory.`;
94
-
95
- // The commands that group subcommands, and their help.
96
- const GROUPS = { tools: TOOLS_USAGE, sessions: SESSIONS_USAGE, cred: CRED_USAGE };
97
-
98
- const OPTIONS = {
99
- yes: { type: "boolean", short: "y" },
100
- "dry-run": { type: "boolean" },
101
- force: { type: "boolean" },
102
- resume: { type: "string" },
103
- port: { type: "string" },
104
- help: { type: "boolean", short: "h" },
105
- version: { type: "boolean", short: "v" },
106
- };
107
- // For each command: how many positional arguments it takes, and which options.
108
- const COMMANDS = {
109
- init: { args: [1, 1], options: ["yes"] },
110
- check: { args: [0, 1], options: [] },
111
- deploy: { args: [0, 1], options: ["dry-run", "force"] },
112
- run: { args: [0, 1], options: ["resume"] },
113
- list: { args: [0, 0], options: [] },
114
- delete: { args: [1, 1], options: ["yes"] },
115
- "tools create": { args: [0, 1], options: [] },
116
- "sessions list": { args: [0, 0], options: [] },
117
- "sessions delete": { args: [1, 1], options: ["yes"] },
118
- "cred create": { args: [0, 1], options: ["port"] },
119
- "cred deploy": { args: [1, 1], options: ["port"] },
120
- "cred login": { args: [1, 1], options: ["port"] },
121
- "cred delete": { args: [1, 1], options: ["yes"] },
122
- };
123
-
124
- async function main(argv) {
125
- let parsed;
126
- try {
127
- parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
128
- } catch (err) {
129
- console.error(`agentschema: ${err.message}\n\n${GROUPS[argv[0]] ?? USAGE}`);
130
- return 1;
131
- }
132
- const { values, positionals } = parsed;
133
- let [command, ...args] = positionals;
134
- const group = command in GROUPS ? command : null;
135
- if (group) command = `${group} ${args.shift() ?? ""}`.trim();
136
- const usage = group ? GROUPS[group] : USAGE;
137
-
138
- if (values.version) {
139
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
140
- console.log(pkg.version);
141
- return 0;
142
- }
143
- if (values.help) {
144
- console.log(usage);
145
- return 0;
146
- }
147
- if (!command) {
148
- console.log(USAGE);
149
- return 1;
150
- }
151
- if (group && command === group) {
152
- console.error(usage);
153
- return 1;
154
- }
155
- if (!(command in COMMANDS)) {
156
- console.error(`agentschema: unknown command "${command}"\n\n${usage}`);
157
- return 1;
158
- }
159
- const spec = COMMANDS[command];
160
- const misplaced = Object.keys(values).filter((k) => !spec.options.includes(k));
161
- if (args.length > spec.args[1] || misplaced.length > 0) {
162
- const arg = args[spec.args[1]] ?? `--${misplaced[0]}`;
163
- console.error(`agentschema: unexpected argument ${arg} for ${command}\n\n${usage}`);
164
- return 1;
165
- }
166
- if (args.length < spec.args[0]) {
167
- const example = { init: "init my-agent", delete: "delete agent_…", "sessions delete": "sessions delete sesn_…", "cred deploy": "cred deploy my-agent/vaults/Ops/Slack.md", "cred login": "cred login my-agent/vaults/Ops/Slack.md", "cred delete": "cred delete my-agent/vaults/Ops/Slack.md" }[command];
168
- console.error(`agentschema: ${command} needs an argument, e.g. agentschema ${example}`);
169
- return 1;
170
- }
171
- const dir = args[0] ?? ".";
172
-
173
- if (command === "init") {
174
- try {
175
- await init(dir, { yes: values.yes ?? false });
176
- return 0;
177
- } catch (err) {
178
- if (!(err instanceof InitError)) throw err;
179
- console.error(`error: ${err.message}`);
180
- return 1;
181
- }
182
- }
183
-
184
- if (command === "check") {
185
- const { errors, warnings } = check(dir);
186
- for (const w of warnings) console.warn(`warning: ${w}`);
187
- for (const e of errors) console.error(`error: ${e}`);
188
- if (errors.length > 0) return 1;
189
- console.log(`${dir}: ok`);
190
- return 0;
191
- }
192
-
193
- try {
194
- if (command === "deploy") {
195
- for (const w of check(dir).warnings) console.warn(`warning: ${w}`);
196
- const dryRun = values["dry-run"] ?? false;
197
- await deploy(dir, {
198
- client: makeClient(dryRun),
199
- dryRun,
200
- force: values.force ?? false,
201
- log: (line) => console.log(line),
202
- });
203
- return 0;
204
- }
205
-
206
- if (command === "list" || command === "sessions list") {
207
- const lines = command === "list" ? await listAgents(makeClient(false)) : await listSessions(makeClient(false));
208
- for (const line of lines) console.log(line);
209
- return 0;
210
- }
211
-
212
- if (command === "delete" || command === "sessions delete") {
213
- const remove = command === "delete" ? deleteAgent : deleteSession;
214
- await remove(makeClient(false), args[0], {
215
- confirm: values.yes ? async () => true : confirm,
216
- log: (line) => console.log(line),
217
- });
218
- return 0;
219
- }
220
-
221
- if (command === "tools create") {
222
- const io = prompts(process.stdin, process.stdout, { cancelled: () => new DeployError("cancelled") });
223
- try {
224
- await toolsCreate(args[0] ?? ".", { io, log: (line) => console.log(line) });
225
- } finally {
226
- io.close();
227
- }
228
- return 0;
229
- }
230
-
231
- if (["cred create", "cred deploy", "cred login"].includes(command)) {
232
- if (values.port !== undefined && !/^\d+$/.test(values.port)) throw new DeployError(`--port must be a number, not "${values.port}"`);
233
- const io = prompts(process.stdin, process.stdout, { cancelled: () => new DeployError("cancelled") });
234
- const options = { client: makeClient(false), openBrowser, port: values.port ?? 0, log: (line) => console.log(line) };
235
- try {
236
- if (command === "cred create") await credCreate(args[0] ?? ".", { ...options, io });
237
- else if (command === "cred deploy") await credDeploy(args[0], { ...options, io });
238
- else await credLogin(args[0], { ...options, ask: (q, { secret }) => (secret ? io.secret(q.trim()) : io.text(q.trim())) });
239
- } finally {
240
- io.close();
241
- }
242
- return 0;
243
- }
244
-
245
- if (command === "cred delete") {
246
- await credDelete(args[0], {
247
- client: makeClient(false),
248
- confirm: values.yes ? async () => true : confirm,
249
- log: (line) => console.log(line),
250
- });
251
- return 0;
252
- }
253
-
254
- if (command === "run") {
255
- // Made first, so .env only reaches your tools: Anthropic credentials still come from the
256
- // shell, the same as for every other command.
257
- const client = makeClient(false);
258
- for (const warning of loadEnvFile(dir)) console.warn(`warning: ${warning}`);
259
- const { session, notes } = await openSession(dir, {
260
- client,
261
- sessionId: values.resume,
262
- });
263
- for (const note of notes) console.warn(`warning: ${note}`);
264
- await chat(client, session, { agentName: session.agent?.name ?? "agent", tools: customTools(dir) });
265
- return 0;
266
- }
267
- } catch (err) {
268
- if (err instanceof Anthropic.APIError) {
269
- console.error(`error: ${err.status ?? "network error"}: ${err.error?.error?.message ?? err.message}`);
270
- return 1;
271
- }
272
- if (err instanceof DeployError || err instanceof DeleteError || err instanceof SessionError || err instanceof Anthropic.AnthropicError) {
273
- console.error(`error: ${err.message}`);
274
- return 1;
275
- }
276
- throw err;
277
- }
278
- }
279
-
280
- // Asks a yes/no question in the terminal; without one, there's no one to ask.
281
- async function confirm(question) {
282
- if (!process.stdin.isTTY) throw new DeleteError("not a terminal, so can't ask for confirmation; pass --yes");
283
- const rl = createInterface({ input: process.stdin, output: process.stdout });
284
- try {
285
- return /^(y|yes)$/i.test((await rl.question(`${question} [y/N] `)).trim());
286
- } finally {
287
- rl.close();
288
- }
289
- }
290
-
291
- // Opens a URL in the default browser; the URL is also printed, in case this fails.
292
- function openBrowser(url) {
293
- const [cmd, args] = process.platform === "darwin" ? ["open", [url]]
294
- : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
295
- : ["xdg-open", [url]];
296
- try {
297
- spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {}).unref();
298
- } catch {
299
- // The URL was printed; the user can open it.
300
- }
301
- }
302
-
303
- // The folder's custom tools, by name, for run to execute. A folder that doesn't pass check
304
- // runs none of them; run asks you for each result instead.
305
- function customTools(dir) {
306
- const { instance, errors } = check(dir);
307
- const customs = instance?.tools.filter((t) => t.data.type === "custom") ?? [];
308
- if (customs.length === 0) return {};
309
- if (errors.length > 0) {
310
- console.warn(`warning: ${dir} doesn't pass check, so its custom tools won't run; you'll be asked for each result`);
311
- return {};
312
- }
313
- return Object.fromEntries(customs.map((t) => [t.name, t]));
314
- }
315
-
316
- // A dry run makes no API calls, so it works without credentials.
317
- function makeClient(dryRun) {
318
- try {
319
- return new Anthropic();
320
- } catch (err) {
321
- if (!dryRun) throw err;
322
- return { baseURL: process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com" };
323
- }
324
- }
325
-
326
- process.exitCode = await main(process.argv.slice(2));
package/lib/channels.js DELETED
@@ -1,338 +0,0 @@
1
- import { pathsUnder, textOf } from "./files.js";
2
- import { AGENT_FILE } from "./instance.js";
3
- import { systemPromptOf } from "./system-prompt.js";
4
- import { FileError, parseMarkdown } from "./markdown.js";
5
- import { AGENTBOOK, MCP_TOOLSET } from "./tools.js";
6
-
7
- // A channel is a place people can talk to an agent, like Telegram or SMS. Its file says how the channel
8
- // should behave, and a host that's always on (Agentbook, say) does the connecting, because Anthropic
9
- // doesn't receive these messages and `run` shouldn't either. So nothing here is sent to the API.
10
- export const CHANNELS_DIR = "channels";
11
- export const ANYONE = "*";
12
-
13
- const DEFAULT_RESPOND_TO = ["direct", "mention"];
14
- const DEFAULT_EXPIRES_AFTER = "24h";
15
- // An email thread can go quiet for days and still be one conversation.
16
- const EMAIL_EXPIRES_AFTER = "7d";
17
- const RESPOND_TO = ["direct", "mention", "reply", "all"];
18
- const LIMITS = ["messages_per_sender_per_hour", "messages_per_day", "messages_sent_per_hour"];
19
- const SHARED_FIELDS = ["type", "enabled", "allow", "respond_to", "scope", "expires_after", "approvals", "limits", "greeting"];
20
- const MAX_GREETING = 1000;
21
- const MAX_SYSTEM_PROMPT = 100_000;
22
-
23
- const code = (value) => `\`${value}\``;
24
- const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
25
-
26
- // Phone numbers and long IDs read as numbers in YAML if they aren't quoted, which loses the +.
27
- const matches = (pattern, what) => (value) => {
28
- if (typeof value === "string" && pattern.test(value)) return null;
29
- return `must be ${what}${typeof value === "number" ? " (put it in quotes, or YAML reads it as a number)" : ""}`;
30
- };
31
- const oneOf = (...values) => (value) => (values.includes(value) ? null : `must be ${values.map(code).join(" or ")}`);
32
- const text = (value) => (typeof value === "string" && value.trim() !== "" ? null : "must be text");
33
- const listOf = (check) => (value) => {
34
- if (!Array.isArray(value)) return "must be a list";
35
- return value.map(check).find(Boolean) ?? null;
36
- };
37
-
38
- const PHONE = /^\+[1-9]\d{6,14}$/;
39
- const DISCORD_ID = /^\d{17,20}$/;
40
- const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
41
-
42
- const EMAIL_ALLOW = matches(/^(\*|[^\s@]+)@[^\s@]+\.[^\s@]+$/, "an email address, or *@ and a domain");
43
-
44
- // What differs between channels. Each `secrets` entry is something the host asks for and keeps: never
45
- // the file, and never a vault, because a vault's secrets can't be read back to send a reply. The first
46
- // of `scopes` is the default. `identity` is what two files in one agent can't share, where that's known.
47
- // `expiresAfter` is the default for `expires_after`, where it isn't the usual one.
48
- export const CHANNEL_TYPES = {
49
- telegram: {
50
- secrets: ["bot_token"],
51
- scopes: ["sender", "room"],
52
- approvals: ["deny", "sender"],
53
- hasGroups: true,
54
- allow: matches(/^(\d+|@[A-Za-z0-9_]{5,32})$/, "a numeric user ID or an @username"),
55
- fields: {},
56
- },
57
- twilio: {
58
- secrets: ["account_sid", "auth_token"],
59
- scopes: ["sender"],
60
- approvals: ["deny", "sender"],
61
- hasGroups: false,
62
- allow: matches(PHONE, "a phone number like +14155550123"),
63
- fields: {
64
- transport: { required: true, check: oneOf("sms", "whatsapp") },
65
- from: { required: true, check: matches(PHONE, "a phone number like +14155550123") },
66
- },
67
- identity: ({ transport, from }) => `${transport} ${from}`,
68
- },
69
- sendgrid: {
70
- secrets: ["api_key"],
71
- scopes: ["thread", "sender"],
72
- // An email has no buttons, and its sender can be forged.
73
- approvals: ["deny"],
74
- hasGroups: false,
75
- expiresAfter: EMAIL_EXPIRES_AFTER,
76
- allow: EMAIL_ALLOW,
77
- fields: {
78
- address: { required: true, check: matches(EMAIL, "an email address") },
79
- from_name: { check: text },
80
- },
81
- identity: ({ address }) => address,
82
- },
83
- // Email at an address the host gives the agent, such as Agentbook's, so the host sends and receives it
84
- // and there's nothing to connect. `address` can be left out, for the host to fill in.
85
- email: {
86
- secrets: [],
87
- scopes: ["thread", "sender"],
88
- approvals: ["deny"],
89
- hasGroups: false,
90
- expiresAfter: EMAIL_EXPIRES_AFTER,
91
- allow: EMAIL_ALLOW,
92
- fields: {
93
- address: { check: matches(EMAIL, "an email address") },
94
- from_name: { check: text },
95
- },
96
- identity: ({ address }) => address ?? null,
97
- },
98
- slack: {
99
- secrets: ["bot_token", "signing_secret"],
100
- scopes: ["thread", "sender", "room"],
101
- approvals: ["deny", "sender"],
102
- hasGroups: true,
103
- allow: matches(/^[UW][A-Z0-9]{2,}$/, "a member ID like U012AB3CD"),
104
- fields: {
105
- channels: { check: listOf(matches(/^[CG][A-Z0-9]{2,}$/, "a channel ID like C012AB3CD")) },
106
- },
107
- },
108
- discord: {
109
- secrets: ["bot_token"],
110
- scopes: ["sender", "room"],
111
- approvals: ["deny", "sender"],
112
- hasGroups: true,
113
- allow: matches(DISCORD_ID, "a numeric user ID"),
114
- fields: {
115
- application_id: { required: true, check: matches(DISCORD_ID, "a numeric application ID") },
116
- public_key: { required: true, check: matches(/^[0-9a-f]{64}$/, "the 64-character public key") },
117
- guilds: { check: listOf(matches(DISCORD_ID, "a numeric server ID")) },
118
- channels: { check: listOf(matches(DISCORD_ID, "a numeric channel ID")) },
119
- dedicated_channels: { check: listOf(matches(DISCORD_ID, "a numeric channel ID")) },
120
- send_to: { check: listOf(matches(DISCORD_ID, "a numeric channel ID")) },
121
- command: { check: matches(/^[a-z0-9_-]{1,32}$/, "a slash command's name, like ask") },
122
- },
123
- identity: ({ application_id: id }) => id,
124
- },
125
- };
126
-
127
- // Reads channels/: each .md file directly inside it is a channel named after the file, so an agent can
128
- // have two Telegram bots. No channels/ folder means no channels.
129
- // Returns { channels, errors }; a file that can't be parsed has an entry in errors.
130
- export function readChannels(files) {
131
- if (CHANNELS_DIR in files) return { channels: [], errors: [`${CHANNELS_DIR}: not a directory`] };
132
-
133
- const channels = [];
134
- const errors = [];
135
- const reportedFolders = new Set();
136
- for (const file of pathsUnder(files, CHANNELS_DIR)) {
137
- const [, item, ...rest] = file.split("/");
138
- if (rest.length > 0) {
139
- const folder = `${CHANNELS_DIR}/${item}`;
140
- if (!reportedFolders.has(folder)) errors.push(`${folder}: ${CHANNELS_DIR}/ holds channel files, not folders`);
141
- reportedFolders.add(folder);
142
- } else if (item.endsWith(".md")) {
143
- try {
144
- channels.push({ file, name: item.slice(0, -".md".length), ...parseMarkdown(textOf(files[file]), file) });
145
- } catch (err) {
146
- if (!(err instanceof FileError)) throw err;
147
- errors.push(err.message);
148
- }
149
- }
150
- }
151
- return { channels, errors };
152
- }
153
-
154
- // Errors and warnings for the channel files, in check's format. `agent` and `tools` are what the channel
155
- // is attached to, and `toolsets` is the catalog behind `type: agentbook` files.
156
- export function checkChannels(channels, { agent = { body: "" }, systemPrompt = [], tools = [], toolsets } = {}, errors = [], warnings = []) {
157
- const unasked = toolsThatRunUnasked(tools, toolsets);
158
- const identities = new Map();
159
- // Where each place in a `send_to` came from: only one bot can post there, so it's clear which one does.
160
- const postedTo = new Map();
161
-
162
- for (const channel of channels) {
163
- const err = (msg) => errors.push(`${channel.file}: ${msg}`);
164
- const warn = (msg) => warnings.push(`${channel.file}: ${msg}`);
165
- const { data, name } = channel;
166
-
167
- // Hosts use the name in webhook addresses and to store the channel's secrets.
168
- 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");
169
-
170
- const type = Object.hasOwn(CHANNEL_TYPES, data.type) ? CHANNEL_TYPES[data.type] : null;
171
- if (!type) {
172
- err(`\`type\` must be ${Object.keys(CHANNEL_TYPES).map(code).join(", ")}`);
173
- continue;
174
- }
175
-
176
- checkAllow(data, type, err, warn);
177
- checkShared(data, type, err, warn);
178
- for (const [field, { required, check }] of Object.entries(type.fields)) {
179
- if (data[field] === undefined) {
180
- if (required) err(`\`${field}\` is required`);
181
- continue;
182
- }
183
- const problem = check(data[field]);
184
- if (problem) err(`\`${field}\` ${problem}`);
185
- }
186
-
187
- for (const key of Object.keys(data)) {
188
- if (type.secrets.includes(key)) err(`\`${key}\` doesn't go in the file; whatever hosts the channel asks for it and keeps it`);
189
- else if (!SHARED_FIELDS.includes(key) && !Object.hasOwn(type.fields, key)) err(`unknown field \`${key}\``);
190
- }
191
-
192
- if (channelSystem({ agent, systemPrompt }, channel).length > MAX_SYSTEM_PROMPT) {
193
- 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`);
194
- }
195
-
196
- const hasRequiredFields = Object.entries(type.fields).every(([field, { required }]) => !required || data[field] !== undefined);
197
- const own = type.identity && hasRequiredFields ? type.identity(data) : null;
198
- if (own !== null) {
199
- const identity = `${data.type} ${own}`;
200
- if (identities.has(identity)) err(`${identities.get(identity)} already uses this`);
201
- else identities.set(identity, channel.file);
202
- }
203
-
204
- if (Array.isArray(data.send_to)) {
205
- for (const place of data.send_to) {
206
- if (typeof place !== "string") continue;
207
- if (postedTo.has(place)) err(`\`send_to\`: ${place} is already in ${postedTo.get(place)}, and only one bot can post there`);
208
- else postedTo.set(place, channel.file);
209
- }
210
- }
211
-
212
- if (data.allow === ANYONE && data.enabled !== false && unasked.length > 0) {
213
- warn(`anyone can message this channel, and these tools can run without asking, through your sign-ins and connections: ${unasked.join(", ")}`);
214
- }
215
- }
216
- return { errors, warnings };
217
- }
218
-
219
- function checkAllow({ allow, approvals }, type, err, warn) {
220
- if (allow === undefined || allow === null) return err(`\`allow\` is required: "${ANYONE}" for anyone, or a list of who can use it`);
221
- if (allow === ANYONE) {
222
- if (approvals === "sender") err(`\`approvals: sender\` would let anyone approve tools, so it needs \`allow\` to be a list`);
223
- return;
224
- }
225
- if (!Array.isArray(allow)) return err(`\`allow\` must be "${ANYONE}", or a list of who can use it`);
226
- if (allow.length === 0) return err("`allow` has nobody in it; list who can use it, or set `enabled: false`");
227
- for (const entry of allow) {
228
- if (entry === ANYONE) return err(`write \`allow: "${ANYONE}"\` on its own, not in a list`);
229
- const problem = type.allow(entry);
230
- if (problem) err(`\`allow\`: ${JSON.stringify(entry)} ${problem}`);
231
- 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`);
232
- }
233
- }
234
-
235
- function checkShared(data, type, err, warn) {
236
- if (data.enabled !== undefined && typeof data.enabled !== "boolean") err("`enabled` must be true or false");
237
-
238
- // An agent can answer only in channels it has to itself, and nowhere else.
239
- const onlyDedicated = Array.isArray(data.respond_to) && data.respond_to.length === 0 && data.dedicated_channels?.length > 0;
240
- if (data.respond_to !== undefined && !onlyDedicated) {
241
- const list = data.respond_to;
242
- if (!Array.isArray(list) || list.length === 0 || list.some((v) => !RESPOND_TO.includes(v))) {
243
- err(`\`respond_to\` must be a list of ${RESPOND_TO.map(code).join(", ")}`);
244
- } else if (list.includes("all") && list.length > 1) {
245
- err("`respond_to`: `all` already covers the others, so list it on its own");
246
- } else if (!type.hasGroups) {
247
- warn(`\`respond_to\` has no effect on ${data.type}`);
248
- } else if (list.includes("all") && Object.hasOwn(type.fields, "channels") && data.channels === undefined) {
249
- warn("`respond_to: [all]` answers every message in every channel it can see, and each one costs you a turn; list the ones you mean under `channels`");
250
- }
251
- }
252
-
253
- if (data.scope !== undefined && !type.scopes.includes(data.scope)) err(`\`scope\` must be ${type.scopes.map(code).join(" or ")} on ${data.type}`);
254
-
255
- if (data.expires_after !== undefined && durationMs(data.expires_after) === null) {
256
- err("`expires_after` must be a length of time like 30m, 24h or 7d");
257
- }
258
-
259
- if (data.approvals !== undefined && !type.approvals.includes(data.approvals)) {
260
- err(`\`approvals\` must be ${type.approvals.map(code).join(" or ")} on ${data.type}`);
261
- }
262
-
263
- if (data.limits !== undefined) {
264
- if (!isObject(data.limits)) err("`limits` must be a mapping");
265
- else {
266
- for (const [key, value] of Object.entries(data.limits)) {
267
- if (!LIMITS.includes(key)) err(`unknown field \`limits.${key}\`; use ${LIMITS.map(code).join(" or ")}`);
268
- else if (!Number.isInteger(value) || value < 1) err(`\`limits.${key}\` must be a whole number above 0`);
269
- }
270
- if (data.limits.messages_sent_per_hour !== undefined && data.send_to === undefined) {
271
- warn("`limits.messages_sent_per_hour` has no effect without `send_to`");
272
- }
273
- }
274
- }
275
-
276
- if (data.greeting !== undefined) {
277
- if (text(data.greeting)) err("`greeting` must be text");
278
- else if (data.greeting.length > MAX_GREETING) err(`\`greeting\` is ${data.greeting.length} characters; the limit is ${MAX_GREETING.toLocaleString("en-US")}`);
279
- }
280
- }
281
-
282
- // The tools that act through the owner's sign-ins and connections without anyone approving each call.
283
- // Pre-built tools aren't here, since they run in the session's own container. In a toolset's table, a
284
- // blank permission means the file's default, which for an MCP server is the API's default of asking.
285
- function toolsThatRunUnasked(tools, toolsets) {
286
- const isOn = (row) => row.enabled.toLowerCase() === "true";
287
- return tools.flatMap((tool) => {
288
- if (tool.data.type === MCP_TOOLSET) {
289
- const defaults = tool.data.default_config;
290
- const fallback = defaults?.permission_policy?.type ?? "always_ask";
291
- if (tool.rows?.length) {
292
- return tool.rows.filter((row) => isOn(row) && (row.permission || fallback) !== "always_ask").map((row) => `${tool.name}.${row.name}`);
293
- }
294
- return fallback !== "always_ask" && defaults?.enabled !== false ? [`every tool in ${tool.name}`] : [];
295
- }
296
- if (tool.data.type === AGENTBOOK) {
297
- const catalog = toolsets?.[tool.data.toolset]?.tools;
298
- const definition = (row) => catalog?.find((t) => t.name === row.name);
299
- // A tool that never runs on a live agent can't run here, and one that's safe for anyone needn't be mentioned.
300
- const isOfNoConcern = (row) => definition(row)?.liveAllowed === false || definition(row)?.safeForAnyone === true;
301
- return (tool.rows ?? []).filter((row) => isOn(row) && row.permission === "always_allow" && !isOfNoConcern(row)).map((row) => `${tool.name}.${row.name}`);
302
- }
303
- return [];
304
- });
305
- }
306
-
307
- const UNIT_MS = { m: 60_000, h: 3_600_000, d: 86_400_000 };
308
-
309
- // A length of time like 30m, 24h or 7d, in milliseconds, or null if it isn't one.
310
- export function durationMs(value) {
311
- const match = typeof value === "string" ? /^([1-9]\d*)([mhd])$/.exec(value) : null;
312
- return match ? Number(match[1]) * UNIT_MS[match[2]] : null;
313
- }
314
-
315
- // How a channel behaves, with the defaults filled in, so that every host agrees on them.
316
- export function channelSettings({ data }) {
317
- const type = CHANNEL_TYPES[data.type];
318
- return {
319
- type: data.type,
320
- enabled: data.enabled ?? true,
321
- allow: data.allow,
322
- respondTo: data.respond_to ?? DEFAULT_RESPOND_TO,
323
- dedicatedChannels: data.dedicated_channels ?? [],
324
- sendTo: data.send_to ?? [],
325
- scope: data.scope ?? type.scopes[0],
326
- expiresAfterMs: durationMs(data.expires_after ?? type.expiresAfter ?? DEFAULT_EXPIRES_AFTER),
327
- approvals: data.approvals ?? "deny",
328
- limits: data.limits ?? {},
329
- greeting: data.greeting ?? null,
330
- };
331
- }
332
-
333
- // The system prompt for a conversation on this channel: the agent's, then the channel's own instructions.
334
- // A session can override `system` for itself, so a channel doesn't need its own copy of the agent.
335
- // `instance` is what checkFiles returns, so the agent's prompt includes system_prompt/. An agent alone,
336
- // as before, still works, with only agent.md's body.
337
- export const channelSystem = (instance, channel) =>
338
- [instance.agent ? systemPromptOf(instance) : instance.body, channel.body].filter(Boolean).join("\n\n");