@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,127 @@
1
+ import { type FileMap } from "./files.ts";
2
+ import { type Frontmatter, type MarkdownFile } from "./markdown.ts";
3
+ export declare const TOOLS_DIR = "tools";
4
+ export declare const TOOLSET = "agent_toolset_20260401";
5
+ export declare const TOOLSET_FILE = "agent_toolset_20260401.md";
6
+ export declare const MCP_TOOLSET = "mcp_toolset";
7
+ export declare const AGENTBOOK = "agentbook";
8
+ export declare const TOOLSET_FOLDER_FILE = "toolset.md";
9
+ export declare const COMPUTER_TOOLS: string[];
10
+ /** @deprecated Their old name: use COMPUTER_TOOLS. */
11
+ export declare const PREBUILT_TOOLS: string[];
12
+ export declare const POLICIES: string[];
13
+ export interface ToolParam {
14
+ name: string;
15
+ type: string;
16
+ description: string;
17
+ required: string;
18
+ }
19
+ export interface ToolRow {
20
+ name: string;
21
+ enabled: string;
22
+ permission?: string;
23
+ }
24
+ export interface ToolMember extends MarkdownFile {
25
+ file: string;
26
+ name: string;
27
+ }
28
+ export interface ToolCode {
29
+ lang: string;
30
+ source: string;
31
+ }
32
+ export interface Tool extends MarkdownFile {
33
+ file: string;
34
+ name: string;
35
+ params: ToolParam[] | null;
36
+ code: ToolCode | null;
37
+ rows: ToolRow[] | null;
38
+ members?: ToolMember[];
39
+ path?: string;
40
+ }
41
+ export interface ReadToolsResult {
42
+ tools: Tool[];
43
+ errors: string[];
44
+ }
45
+ export type JsonSchema = Record<string, unknown>;
46
+ export interface AgentbookToolDefinition {
47
+ name: string;
48
+ description: string;
49
+ input_schema: JsonSchema;
50
+ liveAllowed?: boolean;
51
+ safeForAnyone?: boolean;
52
+ }
53
+ export type AgentbookCatalog = Record<string, {
54
+ tools: AgentbookToolDefinition[];
55
+ }>;
56
+ export interface AgentbookTool extends AgentbookToolDefinition {
57
+ file: string;
58
+ group: string;
59
+ toolset: string;
60
+ permission: string;
61
+ notes: string;
62
+ }
63
+ export interface CompileOptions {
64
+ toolsets?: AgentbookCatalog;
65
+ }
66
+ export interface CheckToolsOptions extends CompileOptions {
67
+ customTools?: boolean;
68
+ }
69
+ export interface PermissionPolicy {
70
+ type: string;
71
+ }
72
+ export interface ToolConfig {
73
+ name: string;
74
+ enabled: boolean;
75
+ permission_policy?: PermissionPolicy;
76
+ }
77
+ export interface SchemaProperty {
78
+ type: string;
79
+ items?: {
80
+ type: string;
81
+ };
82
+ description?: string;
83
+ }
84
+ export type InputSchema = {
85
+ type: "object";
86
+ properties: Record<string, SchemaProperty>;
87
+ required?: string[];
88
+ };
89
+ export interface CompiledToolset {
90
+ type: typeof TOOLSET;
91
+ configs: ToolConfig[];
92
+ }
93
+ export interface CompiledMcpToolset {
94
+ type: typeof MCP_TOOLSET;
95
+ mcp_server_name: string;
96
+ default_config?: Frontmatter;
97
+ configs?: ToolConfig[];
98
+ }
99
+ export interface CompiledCustomTool {
100
+ type: "custom";
101
+ name: string;
102
+ description: string;
103
+ input_schema: JsonSchema;
104
+ }
105
+ export type CompiledTool = CompiledToolset | CompiledMcpToolset | CompiledCustomTool;
106
+ export declare function readTools(files: FileMap): ReadToolsResult;
107
+ export declare function checkTools(tools: Tool[], errors: string[], warnings?: string[], options?: CheckToolsOptions): void;
108
+ export declare function mcpToolsetFile({ name, tools, permission }: {
109
+ name: string;
110
+ tools?: string[];
111
+ permission?: string;
112
+ }): string;
113
+ export declare function agentbookTools(tools: Tool[], toolsets?: AgentbookCatalog): AgentbookTool[];
114
+ export declare const OWNER_NOTES = "Notes from the agent's owner:";
115
+ export declare function agentbookToolsetFiles({ folder, toolset, note, tools }: {
116
+ folder: string;
117
+ toolset: string;
118
+ note?: string;
119
+ tools: {
120
+ name: string;
121
+ permission?: string;
122
+ enabled?: boolean;
123
+ notes?: string;
124
+ }[];
125
+ }): FileMap;
126
+ export declare function compileTools(tools: Tool[], { toolsets }?: CompileOptions): CompiledTool[];
127
+ export declare const wrapToolCode: (source: string) => string;
@@ -0,0 +1,465 @@
1
+ import { stringify } from "yaml";
2
+ import { pathsUnder, textOf } from "./files.js";
3
+ import { FileError, parseMarkdown } from "./markdown.js";
4
+ export const TOOLS_DIR = "tools";
5
+ export const TOOLSET = "agent_toolset_20260401";
6
+ export const TOOLSET_FILE = `${TOOLSET}.md`;
7
+ export const MCP_TOOLSET = "mcp_toolset";
8
+ export const AGENTBOOK = "agentbook";
9
+ // A folder of an agentbook toolset's tools has this file, saying which toolset it is.
10
+ export const TOOLSET_FOLDER_FILE = "toolset.md";
11
+ // The tools Claude runs on the agent's computer, its container, which computer.md describes.
12
+ export const COMPUTER_TOOLS = ["bash", "edit", "glob", "grep", "read", "web_fetch", "web_search", "write"];
13
+ /** @deprecated Their old name: use COMPUTER_TOOLS. */
14
+ export const PREBUILT_TOOLS = COMPUTER_TOOLS;
15
+ export const POLICIES = ["always_allow", "always_ask", "auto"];
16
+ // agentbook tools reach the API as custom tools, which have no permission policy: agentbook
17
+ // enforces these itself, and has nothing like the API's per-call `auto` judgement.
18
+ const AGENTBOOK_POLICIES = ["always_allow", "always_ask"];
19
+ const TYPES = ["string", "number", "integer", "boolean", "object", "array"];
20
+ // Reads every .md file under tools/, in any subfolder, sorted by name. Folders are only for
21
+ // organizing: a custom tool's name is its file name, and its path isn't compiled into anything.
22
+ // The computer toolset is one file (by convention tools/agent_toolset_20260401.md) that lists its tools.
23
+ // No tools/ folder means no tools.
24
+ // Returns { tools, errors }; a tool file that can't be parsed has an entry in errors.
25
+ export function readTools(files) {
26
+ if (TOOLS_DIR in files)
27
+ return { tools: [], errors: [`${TOOLS_DIR}: not a directory`] };
28
+ const tools = [];
29
+ const errors = [];
30
+ const parse = (file) => {
31
+ try {
32
+ return parseMarkdown(textOf(files[file]), file);
33
+ }
34
+ catch (err) {
35
+ if (!(err instanceof FileError))
36
+ throw err;
37
+ errors.push(err.message);
38
+ return null;
39
+ }
40
+ };
41
+ // A tool file, with its tables and code. A table that can't be read is an error too.
42
+ const asTool = (file, name, parsed, extra = {}) => {
43
+ try {
44
+ return { file, name, ...parsed, ...parseSections(parsed.body, file), ...extra };
45
+ }
46
+ catch (err) {
47
+ if (!(err instanceof FileError))
48
+ throw err;
49
+ errors.push(err.message);
50
+ return null;
51
+ }
52
+ };
53
+ const paths = pathsUnder(files, TOOLS_DIR).filter((path) => path.endsWith(".md"));
54
+ const folderOf = (path) => path.slice(0, path.lastIndexOf("/"));
55
+ const nameOf = (path) => path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/, "");
56
+ // A folder with a toolset.md of `type: agentbook` is one toolset, and every other file in it is one of
57
+ // its tools. tools/ itself can't be one, since its files are tools of every kind.
58
+ const folders = new Set();
59
+ for (const path of paths) {
60
+ if (!path.endsWith(`/${TOOLSET_FOLDER_FILE}`) || folderOf(path) === TOOLS_DIR)
61
+ continue;
62
+ const parsed = parse(path);
63
+ if (!parsed || parsed.data.type !== AGENTBOOK)
64
+ continue;
65
+ const folder = folderOf(path);
66
+ folders.add(folder);
67
+ const members = [];
68
+ for (const file of paths) {
69
+ if (file === path || !file.startsWith(`${folder}/`))
70
+ continue;
71
+ if (folderOf(file) !== folder) {
72
+ errors.push(`${file}: a toolset's folder holds its tools' files directly, without folders inside it`);
73
+ continue;
74
+ }
75
+ // A tool's file can be only notes, without properties.
76
+ const text = textOf(files[file]).replace(/^\uFEFF/, "");
77
+ const member = /^---\r?\n/.test(text) ? parse(file) : { data: {}, body: text.trim(), raw: text };
78
+ if (member)
79
+ members.push({ file, name: nameOf(file), ...member });
80
+ }
81
+ members.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
82
+ const rows = members.map(({ name, data }) => ({ name, enabled: data.enabled === false ? "false" : "true", permission: typeof data.permission === "string" ? data.permission : "" }));
83
+ const tool = asTool(path, nameOf(folder), parsed, { rows, members });
84
+ if (tool)
85
+ tools.push(tool);
86
+ }
87
+ const inFolder = (path) => [...folders].some((folder) => path.startsWith(`${folder}/`));
88
+ for (const file of paths) {
89
+ if (inFolder(file))
90
+ continue;
91
+ const parsed = parse(file);
92
+ const tool = parsed && asTool(file, nameOf(file), parsed);
93
+ if (tool)
94
+ tools.push(tool);
95
+ }
96
+ // Names must be unique across folders, since the folders are dropped.
97
+ for (const [type, what] of [["custom", "tool"], [MCP_TOOLSET, "MCP server"], [AGENTBOOK, "agentbook toolset"]]) {
98
+ for (const [name, same] of groupBy(tools.filter((t) => t.data.type === type), (t) => t.name)) {
99
+ if (same.length > 1)
100
+ errors.push(`${TOOLS_DIR}: more than one ${what} is named \`${name}\` (${same.map((t) => t.file).join(", ")})`);
101
+ }
102
+ }
103
+ for (const [toolset, same] of groupBy(tools.filter((t) => t.data.type === AGENTBOOK && typeof t.data.toolset === "string"), (t) => t.data.toolset)) {
104
+ if (same.length > 1 && new Set(same.map((t) => t.name)).size > 1) {
105
+ errors.push(`${TOOLS_DIR}: more than one file turns on the agentbook toolset \`${toolset}\` (${same.map((t) => t.file).join(", ")})`);
106
+ }
107
+ }
108
+ const toolsets = tools.filter((t) => t.data.type === TOOLSET);
109
+ if (toolsets.length > 1) {
110
+ errors.push(`${TOOLS_DIR}: more than one \`${TOOLSET}\` file (${toolsets.map((t) => t.file).join(", ")}); list every computer tool in one file`);
111
+ }
112
+ return { tools: tools.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)), errors };
113
+ }
114
+ function groupBy(items, key) {
115
+ const groups = new Map();
116
+ for (const item of items)
117
+ groups.set(key(item), [...(groups.get(key(item)) ?? []), item]);
118
+ return groups;
119
+ }
120
+ // Pulls the `## Input Schema` table, the `## Code` block and the `## Tools` table (for a toolset)
121
+ // out of a tool file's body.
122
+ function parseSections(body, file) {
123
+ const sections = {};
124
+ let current = null;
125
+ let fence = null;
126
+ for (const line of body.split("\n")) {
127
+ const marker = /^(```|~~~)/.exec(line)?.[1];
128
+ if (marker && (!fence || fence === marker))
129
+ fence = fence ? null : marker;
130
+ const heading = !fence && /^##\s+(.+?)\s*$/.exec(line);
131
+ if (heading) {
132
+ current = heading[1].toLowerCase();
133
+ sections[current] = [];
134
+ }
135
+ else if (current) {
136
+ sections[current].push(line);
137
+ }
138
+ }
139
+ const result = { params: null, code: null, rows: null };
140
+ if (sections["input schema"]) {
141
+ result.params = parseTable(sections["input schema"], `${file}: the Input Schema table's columns must be Name | Type | Description | Required`, ["name", "type", "description", "required"]);
142
+ }
143
+ if (sections.code)
144
+ result.code = parseCode(sections.code, file);
145
+ if (sections.tools) {
146
+ result.rows = parseTable(sections.tools, `${file}: the Tools table's columns must be Name | Enabled, or Name | Enabled | Permission`, ["name", "enabled"], ["permission"]);
147
+ }
148
+ return result;
149
+ }
150
+ // The rows of a Markdown table as objects keyed by column name. The header must start with
151
+ // the `required` columns, and may go on with the `optional` ones, in order.
152
+ function parseTable(lines, message, required, optional = []) {
153
+ const rows = lines.filter((l) => l.trim().startsWith("|")).map(splitRow);
154
+ if (rows.length === 0)
155
+ return [];
156
+ const header = rows[0].map((c) => c.toLowerCase());
157
+ const allowed = [...required, ...optional];
158
+ if (header.length < required.length || header.length > allowed.length || header.some((c, i) => c !== allowed[i])) {
159
+ throw new FileError(message);
160
+ }
161
+ return rows.slice(2).map((cells) => Object.fromEntries(header.map((c, i) => [c, cells[i] ?? ""])));
162
+ }
163
+ function splitRow(line) {
164
+ const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split(/(?<!\\)\|/);
165
+ return cells.map((c) => c.trim().replace(/\\\|/g, "|").replace(/^`(.*)`$/, "$1"));
166
+ }
167
+ function parseCode(lines, file) {
168
+ const text = lines.join("\n");
169
+ const blocks = [...text.matchAll(/^(```|~~~)[ \t]*([\w-]*)[^\n]*\n([\s\S]*?)^\1[ \t]*$/gm)];
170
+ if (blocks.length !== 1)
171
+ throw new FileError(`${file}: the Code section must hold exactly one fenced code block`);
172
+ const [, , lang, source] = blocks[0];
173
+ return { lang: lang.toLowerCase(), source };
174
+ }
175
+ // Errors and warnings for the tool files, in check's format.
176
+ // `options.customTools: false` refuses custom tools, for hosts that won't run user code.
177
+ // `options.toolsets` is the catalog behind `type: agentbook` files; see agentbookTools.
178
+ export function checkTools(tools, errors, warnings = [], options = {}) {
179
+ const customs = tools.filter((t) => t.data.type === "custom");
180
+ if (customs.length + (customs.length < tools.length ? 1 : 0) > 256)
181
+ errors.push(`${TOOLS_DIR}: more than 256 tools`);
182
+ // agentbook tools and custom tools all reach the API as custom tools, in one namespace.
183
+ if (options.toolsets) {
184
+ const names = new Set(customs.map((t) => t.name));
185
+ for (const { file, name } of agentbookTools(tools, options.toolsets)) {
186
+ if (names.has(name))
187
+ errors.push(`${file}: another tool is already named \`${name}\``);
188
+ names.add(name);
189
+ }
190
+ }
191
+ for (const tool of tools) {
192
+ const err = (msg) => errors.push(`${tool.file}: ${msg}`);
193
+ const { type } = tool.data;
194
+ const extra = (allowed) => {
195
+ for (const key of Object.keys(tool.data))
196
+ if (!allowed.includes(key))
197
+ err(`unknown field \`${key}\``);
198
+ };
199
+ if (type === TOOLSET) {
200
+ checkToolset(tool, err);
201
+ extra(["type"]);
202
+ }
203
+ else if (type === MCP_TOOLSET) {
204
+ checkMcpToolset(tool, err);
205
+ extra(["type", "mcp_server_name", "default_config", "url"]);
206
+ }
207
+ else if (type === "custom") {
208
+ if (options.customTools === false)
209
+ err("custom tools aren't available here, because they'd run your code on a shared server");
210
+ else
211
+ checkCustom(tool, err);
212
+ extra(["type", "name", "description"]);
213
+ }
214
+ else if (type === AGENTBOOK) {
215
+ checkAgentbook(tool, err, (msg) => warnings.push(`${tool.file}: ${msg}`), options, (file, msg) => errors.push(`${file}: ${msg}`));
216
+ extra(["type", "toolset"]);
217
+ }
218
+ else {
219
+ err(`\`type\` must be \`${TOOLSET}\` (the computer tools), \`${MCP_TOOLSET}\` (an MCP server), \`custom\` or \`${AGENTBOOK}\``);
220
+ }
221
+ }
222
+ }
223
+ // The tools of an MCP server that agent.md declares: `mcp_server_name` is the server's name, and the
224
+ // optional `## Tools` table configures tools by the names the server reports.
225
+ function checkMcpToolset(tool, err) {
226
+ const { mcp_server_name: server, default_config: defaults } = tool.data;
227
+ if ("url" in tool.data)
228
+ err("`url` belongs in agent.md's `mcp_servers`; refer to the server here with `mcp_server_name`");
229
+ if (typeof server !== "string" || server === "")
230
+ err("`mcp_server_name` is required");
231
+ else if (server !== tool.name)
232
+ err(`\`mcp_server_name\` must match the file name (${tool.name})`);
233
+ if (tool.name.length > 255)
234
+ err("an MCP server's name (its file name) must be at most 255 characters");
235
+ if (defaults !== undefined && defaults !== null) {
236
+ if (typeof defaults !== "object" || Array.isArray(defaults))
237
+ err("`default_config` must be a mapping");
238
+ else {
239
+ if (defaults.enabled !== undefined && typeof defaults.enabled !== "boolean")
240
+ err("`default_config.enabled` must be true or false");
241
+ const policy = defaults.permission_policy;
242
+ if (policy !== undefined && !POLICIES.includes(policy?.type)) {
243
+ err(`\`default_config.permission_policy.type\` must be ${POLICIES.join(", ")}`);
244
+ }
245
+ for (const key of Object.keys(defaults)) {
246
+ if (!["enabled", "permission_policy"].includes(key))
247
+ err(`unknown field \`default_config.${key}\``);
248
+ }
249
+ }
250
+ }
251
+ checkRows(tool.rows ?? [], err, { known: null });
252
+ }
253
+ // A toolset from agentbook's catalog. `## Tools` turns its tools on one by one, so a tool without
254
+ // a row is off: a new tool in the catalog never reaches a deployed agent by itself.
255
+ //
256
+ // It's either one file with a `## Tools` table, named after the toolset, or a folder: a toolset.md, and a
257
+ // file for each tool, named after it, whose body is notes for the agent. A tool without a row, or a
258
+ // file, is off.
259
+ function checkAgentbook(tool, err, warn, { toolsets }, errAt) {
260
+ const { toolset } = tool.data;
261
+ if (typeof toolset !== "string" || toolset === "")
262
+ return err("`toolset` is required");
263
+ if (tool.members) {
264
+ const hasTable = /^##\s+tools\s*$/im.test(tool.body);
265
+ if (hasTable)
266
+ err("a toolset's folder lists its tools as files beside this one, not as a `## Tools` table");
267
+ }
268
+ else {
269
+ if (toolset !== tool.name)
270
+ err(`\`toolset\` must match the file name (${tool.name})`);
271
+ if (!tool.rows)
272
+ err("a `## Tools` table listing the tools to enable is required");
273
+ }
274
+ if (!toolsets)
275
+ warn("this toolset runs on agentbook, so `agentschema deploy` can't deploy it");
276
+ else if (!Object.hasOwn(toolsets, toolset))
277
+ err(`\`${toolset}\` isn't an agentbook toolset; use ${Object.keys(toolsets).join(", ")}`);
278
+ const known = toolsets && Object.hasOwn(toolsets, toolset) ? toolsets[toolset].tools.map((t) => t.name) : null;
279
+ if (!tool.members)
280
+ return checkRows(tool.rows ?? [], err, { known, what: `a tool in \`${toolset}\``, policies: AGENTBOOK_POLICIES });
281
+ for (const member of tool.members) {
282
+ const memberErr = (msg) => errAt(member.file, msg);
283
+ if (known && !known.includes(member.name))
284
+ memberErr(`\`${member.name}\` is not a tool in \`${toolset}\`; use ${known.join(", ")}`);
285
+ const { enabled, permission } = member.data;
286
+ if (enabled !== undefined && typeof enabled !== "boolean")
287
+ memberErr("`enabled` must be true or false");
288
+ if (permission !== undefined && permission !== null && !AGENTBOOK_POLICIES.includes(permission)) {
289
+ memberErr(`\`permission\` must be ${AGENTBOOK_POLICIES.join(" or ")}, or left out`);
290
+ }
291
+ for (const key of Object.keys(member.data))
292
+ if (!["enabled", "permission"].includes(key))
293
+ memberErr(`unknown field \`${key}\``);
294
+ }
295
+ }
296
+ function checkToolset(tool, err) {
297
+ if (!tool.rows) {
298
+ // 0.2.0 had one file per computer tool, with no table.
299
+ const hint = COMPUTER_TOOLS.includes(tool.name) ? `; since 0.2.1 all computer tools go in one file, ${TOOLS_DIR}/${TOOLSET_FILE}` : "";
300
+ return err(`a \`## Tools\` table listing the computer tools to enable is required${hint}`);
301
+ }
302
+ checkRows(tool.rows, err, { known: COMPUTER_TOOLS, what: "a computer tool" });
303
+ }
304
+ // The rows of a `## Tools` table. `known` is the list of valid tool names, when there is one.
305
+ function checkRows(rows, err, { known, what, policies = POLICIES }) {
306
+ const seen = new Set();
307
+ for (const row of rows) {
308
+ if (!row.name)
309
+ err("a `## Tools` row has no name");
310
+ else if (known && !known.includes(row.name))
311
+ err(`\`${row.name}\` is not ${what}; use ${known.join(", ")}`);
312
+ else if (seen.has(row.name))
313
+ err(`\`${row.name}\` is listed twice`);
314
+ seen.add(row.name);
315
+ if (!["true", "false"].includes(row.enabled.toLowerCase()))
316
+ err(`\`${row.name}\`: Enabled must be true or false`);
317
+ if (row.permission && !policies.includes(row.permission)) {
318
+ err(`\`${row.name}\` has permission \`${row.permission}\`; use ${policies.join(", ")}, or leave it blank`);
319
+ }
320
+ }
321
+ }
322
+ function checkCustom(tool, err) {
323
+ const { name, description } = tool.data;
324
+ if (name !== tool.name)
325
+ err(`\`name\` must match the file name (${tool.name})`);
326
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(tool.name))
327
+ err("the name may only use letters, digits, _ and -, up to 64 characters");
328
+ if (COMPUTER_TOOLS.includes(tool.name))
329
+ err(`\`${tool.name}\` is a computer tool's name; the API rejects custom tools that reuse one`);
330
+ if (/^(mcp__|ant__)/.test(tool.name))
331
+ err("custom tool names can't start with mcp__ or ant__");
332
+ if (typeof description !== "string" || description.trim() === "")
333
+ err("`description` is required");
334
+ const seen = new Set();
335
+ for (const p of tool.params ?? []) {
336
+ if (!p.name)
337
+ err("an Input Schema row has no name");
338
+ else if (seen.has(p.name))
339
+ err(`input \`${p.name}\` is listed twice`);
340
+ seen.add(p.name);
341
+ if (!TYPES.includes(p.type?.replace(/\[\]$/, ""))) {
342
+ err(`input \`${p.name}\` has type \`${p.type}\`; use ${TYPES.join(", ")}, or one of them followed by []`);
343
+ }
344
+ if (!["true", "false"].includes(p.required?.toLowerCase()))
345
+ err(`input \`${p.name}\`: Required must be true or false`);
346
+ }
347
+ if (!tool.code)
348
+ return err("a `## Code` section with a JavaScript code block is required");
349
+ if (!["javascript", "js"].includes(tool.code.lang))
350
+ err("the code must be JavaScript (```javascript)");
351
+ else {
352
+ // Parses the code without running it: the function this builds is never called.
353
+ try {
354
+ new Function(wrapToolCode(tool.code.source));
355
+ }
356
+ catch (e) {
357
+ // A page's content security policy can forbid this, which says nothing about the code.
358
+ if (e instanceof SyntaxError)
359
+ err(`the code doesn't parse: ${e.message}`);
360
+ }
361
+ }
362
+ }
363
+ // An MCP server's tool file. With the server's tools, it's a table of them, all on, each with
364
+ // `permission`. A tool the server adds later isn't in the table, so it gets the API's defaults: on, and
365
+ // asking before each call. Many servers won't list their tools until you've signed in, so with no tools
366
+ // it keeps `permission` for all of them, ready for the table: see listedMcpToolset.
367
+ export function mcpToolsetFile({ name, tools = [], permission = "always_ask" }) {
368
+ const front = { type: MCP_TOOLSET, mcp_server_name: name };
369
+ if (tools.length > 0) {
370
+ const rows = tools.map((tool) => `| \`${tool}\` | \`true\` | \`${permission}\` |`);
371
+ const body = ["Set Enabled to false to turn a tool off.", "", "## Tools", "", "| Name | Enabled | Permission |", "|---|---|---|", ...rows, ""].join("\n");
372
+ return `---\n${stringify(front)}---\n\n${body}`;
373
+ }
374
+ if (permission !== "always_ask")
375
+ front.default_config = { permission_policy: { type: permission } };
376
+ 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`;
377
+ }
378
+ // The agentbook tools a folder turns on, as { file, group, toolset, name, description, input_schema,
379
+ // permission, notes }. `toolsets` is the catalog, { [toolset]: { tools: [{ name, description,
380
+ // input_schema }] } }. A blank permission means `always_ask`, the safe choice for a tool with no policy of
381
+ // its own. A tool's own file in a toolset folder can add notes, which follow the catalog's description.
382
+ export function agentbookTools(tools, toolsets = {}) {
383
+ return byName(tools.filter((t) => t.data.type === AGENTBOOK)).flatMap((tool) => {
384
+ const { toolset } = tool.data;
385
+ if (!Object.hasOwn(toolsets, toolset))
386
+ return [];
387
+ return toolsets[toolset].tools.flatMap((definition) => {
388
+ const row = tool.rows?.find((r) => r.name === definition.name);
389
+ if (row?.enabled.toLowerCase() !== "true")
390
+ return [];
391
+ const member = tool.members?.find((m) => m.name === definition.name);
392
+ const notes = member?.body.trim() ?? "";
393
+ const description = notes ? `${definition.description}\n\n${OWNER_NOTES}\n${notes}` : definition.description;
394
+ return [{ ...definition, description, file: member?.file ?? tool.file, group: tool.name, toolset, permission: row.permission || "always_ask", notes }];
395
+ });
396
+ });
397
+ }
398
+ // What comes before a tool's notes from its file, in the description the agent gets.
399
+ export const OWNER_NOTES = "Notes from the agent's owner:";
400
+ // The files of an agentbook toolset as a folder: tools/<folder>/toolset.md, saying which toolset, with
401
+ // `note` for people in its body, and a file for each tool in `tools`, with its permission and notes.
402
+ export function agentbookToolsetFiles({ folder, toolset, note = "", tools }) {
403
+ const dir = `${TOOLS_DIR}/${folder}`;
404
+ const files = { [`${dir}/${TOOLSET_FOLDER_FILE}`]: `---\n${stringify({ type: AGENTBOOK, toolset })}---\n${note ? `\n${note.trim()}\n` : ""}` };
405
+ for (const { name, permission, enabled, notes = "" } of tools) {
406
+ const front = {};
407
+ if (enabled === false)
408
+ front.enabled = false;
409
+ if (permission)
410
+ front.permission = permission;
411
+ const head = Object.keys(front).length > 0 ? `---\n${stringify(front)}---\n` : "";
412
+ files[`${dir}/${name}.md`] = `${head}${notes ? `${head ? "\n" : ""}${notes.trim()}\n` : ""}`;
413
+ }
414
+ return files;
415
+ }
416
+ // The tools list sent to the API, each kind sorted by name: the computer toolset with a config
417
+ // for each row of its table (tools it doesn't list keep the API's defaults), then a toolset for
418
+ // each MCP server, then the custom tools, and last agentbook's tools, which reach the API as
419
+ // custom tools. Only their name, description and input schema are sent.
420
+ export function compileTools(tools, { toolsets } = {}) {
421
+ const compiled = [];
422
+ const toolset = tools.find((t) => t.data.type === TOOLSET);
423
+ // check requires the computer toolset's table, so its rows are there.
424
+ if (toolset)
425
+ compiled.push({ type: TOOLSET, configs: configs(toolset.rows) });
426
+ for (const tool of byName(tools.filter((t) => t.data.type === MCP_TOOLSET))) {
427
+ const entry = { type: MCP_TOOLSET, mcp_server_name: tool.name };
428
+ if (tool.data.default_config)
429
+ entry.default_config = tool.data.default_config;
430
+ if (tool.rows?.length)
431
+ entry.configs = configs(tool.rows);
432
+ compiled.push(entry);
433
+ }
434
+ for (const tool of tools.filter((t) => t.data.type === "custom").sort((a, b) => (a.name < b.name ? -1 : 1))) {
435
+ compiled.push({ type: "custom", name: tool.name, description: tool.data.description, input_schema: inputSchema(tool.params ?? []) });
436
+ }
437
+ for (const { name, description, input_schema } of agentbookTools(tools, toolsets)) {
438
+ compiled.push({ type: "custom", name, description, input_schema });
439
+ }
440
+ return compiled;
441
+ }
442
+ const byName = (tools) => [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
443
+ function configs(rows = []) {
444
+ return [...rows].sort((a, b) => (a.name < b.name ? -1 : 1)).map(({ name, enabled, permission }) => {
445
+ const config = { name, enabled: enabled.toLowerCase() === "true" };
446
+ if (permission)
447
+ config.permission_policy = { type: permission };
448
+ return config;
449
+ });
450
+ }
451
+ function inputSchema(params) {
452
+ const properties = {};
453
+ for (const p of params) {
454
+ const list = p.type.endsWith("[]");
455
+ const type = p.type.replace(/\[\]$/, "");
456
+ const prop = list ? { type: "array", items: { type } } : { type };
457
+ if (p.description)
458
+ prop.description = p.description;
459
+ properties[p.name] = prop;
460
+ }
461
+ const required = params.filter((p) => p.required.toLowerCase() === "true").map((p) => p.name);
462
+ return required.length > 0 ? { type: "object", properties, required } : { type: "object", properties };
463
+ }
464
+ // A custom tool's code wrapped as a CommonJS module.
465
+ export const wrapToolCode = (source) => `(function (exports, require, module, __filename, __dirname) {${source}\n})`;
@@ -0,0 +1,55 @@
1
+ import { type FileMap } from "./files.ts";
2
+ import { type Frontmatter, type MarkdownFile } from "./markdown.ts";
3
+ export declare const VAULTS_DIR = "vaults";
4
+ export declare const VAULT_FILE = "vault.md";
5
+ export declare const MCP_OAUTH = "mcp_oauth";
6
+ export declare const ENV_VAR = "environment_variable";
7
+ export declare const CREDENTIAL_TYPES: string[];
8
+ export declare const TOKEN_ENDPOINT_AUTH: string[];
9
+ export type FieldPath = string[];
10
+ export interface Credential extends MarkdownFile {
11
+ file: string;
12
+ name: string;
13
+ vault: string;
14
+ }
15
+ export interface Vault {
16
+ name: string;
17
+ path: string;
18
+ file: MarkdownFile | null;
19
+ credentials: Credential[];
20
+ }
21
+ export interface ReadVaultsResult {
22
+ vaults: Vault[];
23
+ errors: string[];
24
+ }
25
+ export interface VaultBody {
26
+ display_name: string;
27
+ metadata?: Record<string, string>;
28
+ }
29
+ export interface CredentialSettings {
30
+ display_name: string;
31
+ auth: Frontmatter;
32
+ metadata?: Record<string, string>;
33
+ }
34
+ export interface CredentialSecrets {
35
+ accessToken?: string;
36
+ expiresAt?: string;
37
+ refreshToken?: string;
38
+ clientSecret?: string;
39
+ secretValue?: string;
40
+ }
41
+ export interface SecretsNeeded {
42
+ refreshToken: boolean;
43
+ clientSecret: boolean;
44
+ }
45
+ export declare const SECRET_FIELDS: Record<string, FieldPath[]>;
46
+ export declare const IMMUTABLE_FIELDS: Record<string, FieldPath[]>;
47
+ export declare function readVaults(files: FileMap): ReadVaultsResult;
48
+ export declare const vaultKey: (vault: Pick<Vault, "path">) => string;
49
+ export declare const credentialKey: (cred: Pick<Credential, "file">) => string;
50
+ export declare function vaultBody(vault: Pick<Vault, "name" | "file">): VaultBody;
51
+ export declare function credentialSettings(cred: Pick<Credential, "name" | "data">): CredentialSettings;
52
+ export declare function credentialCreateBody(cred: Pick<Credential, "name" | "data">, { accessToken, expiresAt, refreshToken, clientSecret, secretValue }: CredentialSecrets): CredentialSettings;
53
+ export declare function secretsNeeded(cred: Pick<Credential, "data">): SecretsNeeded;
54
+ export declare function changedImmutableFields(cred: Pick<Credential, "data">, remoteAuth: unknown): string[];
55
+ export declare const get: (obj: unknown, path: FieldPath) => unknown;