@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.
- package/README.md +8 -2
- package/dist/bin/agentschema.d.ts +2 -0
- package/dist/bin/agentschema.js +333 -0
- package/dist/lib/channels.d.ts +65 -0
- package/dist/lib/channels.js +339 -0
- package/dist/lib/check.d.ts +10 -0
- package/dist/lib/check.js +411 -0
- package/dist/lib/files.d.ts +7 -0
- package/{lib → dist/lib}/files.js +10 -14
- package/dist/lib/index.d.ts +24 -0
- package/{lib → dist/lib}/index.js +3 -12
- package/dist/lib/instance.d.ts +41 -0
- package/dist/lib/instance.js +74 -0
- package/dist/lib/markdown.d.ts +11 -0
- package/dist/lib/markdown.js +38 -0
- package/dist/lib/scaffold.d.ts +15 -0
- package/dist/lib/scaffold.js +46 -0
- package/dist/lib/scheduled.d.ts +56 -0
- package/dist/lib/scheduled.js +185 -0
- package/dist/lib/skills.d.ts +28 -0
- package/dist/lib/skills.js +55 -0
- package/dist/lib/stream.d.ts +30 -0
- package/dist/lib/stream.js +56 -0
- package/dist/lib/system-prompt.d.ts +16 -0
- package/{lib → dist/lib}/system-prompt.js +14 -15
- package/dist/lib/tools.d.ts +105 -0
- package/dist/lib/tools.js +353 -0
- package/dist/lib/vaults.d.ts +55 -0
- package/dist/lib/vaults.js +143 -0
- package/dist/src/chat.d.ts +15 -0
- package/dist/src/chat.js +159 -0
- package/dist/src/check.d.ts +2 -0
- package/dist/src/check.js +14 -0
- package/dist/src/cred-menu.d.ts +17 -0
- package/dist/src/cred-menu.js +193 -0
- package/dist/src/cred.d.ts +54 -0
- package/dist/src/cred.js +252 -0
- package/dist/src/custom-tools.d.ts +3 -0
- package/dist/src/custom-tools.js +18 -0
- package/dist/src/delete.d.ts +9 -0
- package/dist/src/delete.js +27 -0
- package/dist/src/deploy.d.ts +62 -0
- package/dist/src/deploy.js +442 -0
- package/dist/src/dotenv.d.ts +7 -0
- package/dist/src/dotenv.js +54 -0
- package/dist/src/folder.d.ts +5 -0
- package/{src → dist/src}/folder.js +30 -28
- package/dist/src/init.d.ts +11 -0
- package/dist/src/init.js +51 -0
- package/dist/src/list.d.ts +3 -0
- package/dist/src/list.js +46 -0
- package/dist/src/lock.d.ts +10 -0
- package/dist/src/lock.js +37 -0
- package/dist/src/mcp.d.ts +11 -0
- package/dist/src/mcp.js +79 -0
- package/dist/src/node.d.ts +14 -0
- package/dist/src/oauth.d.ts +64 -0
- package/dist/src/oauth.js +208 -0
- package/dist/src/prompts.d.ts +18 -0
- package/dist/src/prompts.js +166 -0
- package/dist/src/session.d.ts +58 -0
- package/dist/src/session.js +200 -0
- package/dist/src/tools-menu.d.ts +8 -0
- package/dist/src/tools-menu.js +173 -0
- package/package.json +21 -9
- package/bin/agentschema.js +0 -326
- package/lib/channels.js +0 -338
- package/lib/check.js +0 -387
- package/lib/instance.js +0 -75
- package/lib/markdown.js +0 -42
- package/lib/scaffold.js +0 -51
- package/lib/scheduled.js +0 -175
- package/lib/skills.js +0 -58
- package/lib/stream.js +0 -50
- package/lib/tools.js +0 -327
- package/lib/vaults.js +0 -142
- package/src/chat.js +0 -156
- package/src/check.js +0 -14
- package/src/cred-menu.js +0 -197
- package/src/cred.js +0 -263
- package/src/custom-tools.js +0 -17
- package/src/delete.js +0 -25
- package/src/deploy.js +0 -441
- package/src/dotenv.js +0 -50
- package/src/init.js +0 -54
- package/src/list.js +0 -49
- package/src/lock.js +0 -40
- package/src/mcp.js +0 -76
- package/src/oauth.js +0 -215
- package/src/prompts.js +0 -159
- package/src/session.js +0 -194
- package/src/tools-menu.js +0 -163
- /package/{src → dist/src}/node.js +0 -0
package/lib/scheduled.js
DELETED
|
@@ -1,175 +0,0 @@
|
|
|
1
|
-
import { pathsUnder, textOf } from "./files.js";
|
|
2
|
-
import { FileError, parseMarkdown } from "./markdown.js";
|
|
3
|
-
import { AGENTBOOK, MCP_TOOLSET, TOOLSET } from "./tools.js";
|
|
4
|
-
|
|
5
|
-
// A scheduled task runs the agent on a timetable, with the same message each time, like "say good
|
|
6
|
-
// morning in #gm" every weekday at 8. Each file in scheduled/ is one, named after its file, and it
|
|
7
|
-
// becomes a Managed Agents deployment: Anthropic starts each run, so nothing needs to be running here.
|
|
8
|
-
export const SCHEDULED_DIR = "scheduled";
|
|
9
|
-
|
|
10
|
-
const FIELDS = ["schedule", "timezone", "enabled", "budget", "description"];
|
|
11
|
-
const MAX_DESCRIPTION = 2048;
|
|
12
|
-
|
|
13
|
-
// Each part of a cron expression, and the numbers it takes. Day of the week is 0 to 7, where both 0
|
|
14
|
-
// and 7 are Sunday.
|
|
15
|
-
const CRON_PARTS = [
|
|
16
|
-
["minute", 0, 59],
|
|
17
|
-
["hour", 0, 23],
|
|
18
|
-
["day of the month", 1, 31],
|
|
19
|
-
["month", 1, 12],
|
|
20
|
-
["day of the week", 0, 7],
|
|
21
|
-
];
|
|
22
|
-
|
|
23
|
-
// Reads scheduled/: each .md file directly inside it is a task named after the file. No scheduled/
|
|
24
|
-
// folder means no tasks. Returns { tasks, errors }; a file that can't be parsed has an entry in errors.
|
|
25
|
-
export function readScheduled(files) {
|
|
26
|
-
if (SCHEDULED_DIR in files) return { tasks: [], errors: [`${SCHEDULED_DIR}: not a directory`] };
|
|
27
|
-
|
|
28
|
-
const tasks = [];
|
|
29
|
-
const errors = [];
|
|
30
|
-
const reportedFolders = new Set();
|
|
31
|
-
for (const file of pathsUnder(files, SCHEDULED_DIR)) {
|
|
32
|
-
const [, item, ...rest] = file.split("/");
|
|
33
|
-
if (rest.length > 0) {
|
|
34
|
-
const folder = `${SCHEDULED_DIR}/${item}`;
|
|
35
|
-
if (!reportedFolders.has(folder)) errors.push(`${folder}: ${SCHEDULED_DIR}/ holds task files, not folders`);
|
|
36
|
-
reportedFolders.add(folder);
|
|
37
|
-
} else if (item.endsWith(".md")) {
|
|
38
|
-
try {
|
|
39
|
-
tasks.push({ file, name: item.slice(0, -".md".length), ...parseMarkdown(textOf(files[file]), file) });
|
|
40
|
-
} catch (err) {
|
|
41
|
-
if (!(err instanceof FileError)) throw err;
|
|
42
|
-
errors.push(err.message);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return { tasks, errors };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// What's wrong with a cron expression, or null. Only the standard five parts are allowed, with
|
|
50
|
-
// numbers, ranges, lists, steps and *, which is what Managed Agents accepts.
|
|
51
|
-
export function cronProblem(expression) {
|
|
52
|
-
if (typeof expression !== "string") return `must be a cron expression in quotes, like "0 8 * * 1-5"`;
|
|
53
|
-
const parts = expression.trim().split(/\s+/);
|
|
54
|
-
if (parts.length !== 5) return `must have five parts, for the minute, hour, day of the month, month and day of the week, like "0 8 * * 1-5"`;
|
|
55
|
-
for (const [i, part] of parts.entries()) {
|
|
56
|
-
const [what, min, max] = CRON_PARTS[i];
|
|
57
|
-
for (const item of part.split(",")) {
|
|
58
|
-
const match = /^(?:\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(item);
|
|
59
|
-
if (!match) return `has "${part}" for the ${what}; use numbers, a range like 1-5, a list like 1,3, a step like */15, or *`;
|
|
60
|
-
const [, from, to, step] = match;
|
|
61
|
-
const numbers = [from, to].filter((n) => n !== undefined).map(Number);
|
|
62
|
-
if (numbers.some((n) => n < min || n > max)) return `has "${part}" for the ${what}, which goes from ${min} to ${max}`;
|
|
63
|
-
if (to !== undefined && Number(from) > Number(to)) return `has "${part}" for the ${what}, a range that runs backwards`;
|
|
64
|
-
if (step !== undefined && Number(step) < 1) return `has "${part}" for the ${what}, but a step must be at least 1`;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return null;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// Whether a time zone is one the IANA database knows, like America/Los_Angeles or UTC.
|
|
71
|
-
export function isTimeZone(value) {
|
|
72
|
-
if (typeof value !== "string" || value.trim() === "") return false;
|
|
73
|
-
try {
|
|
74
|
-
new Intl.DateTimeFormat("en-US", { timeZone: value });
|
|
75
|
-
return true;
|
|
76
|
-
} catch {
|
|
77
|
-
return false;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// Errors and warnings for the task files, in check's format. `tools` and `toolsets` are the agent's,
|
|
82
|
-
// to warn about tools nobody can answer during a run.
|
|
83
|
-
export function checkScheduled(tasks, { tools = [] } = {}, errors = [], warnings = []) {
|
|
84
|
-
const waiting = toolsThatWaitForSomeone(tools);
|
|
85
|
-
for (const task of tasks) {
|
|
86
|
-
const err = (msg) => errors.push(`${task.file}: ${msg}`);
|
|
87
|
-
const { data, body, name } = task;
|
|
88
|
-
|
|
89
|
-
// It's the deployment's name, and hosts use it to keep track of the task.
|
|
90
|
-
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");
|
|
91
|
-
|
|
92
|
-
if (data.schedule === undefined) err('`schedule` is required: a cron expression, like "0 8 * * 1-5" for 8 AM on weekdays');
|
|
93
|
-
else {
|
|
94
|
-
const problem = cronProblem(data.schedule);
|
|
95
|
-
if (problem) err(`\`schedule\` ${problem}`);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
if (data.timezone === undefined) err("`timezone` is required, like America/Los_Angeles or UTC");
|
|
99
|
-
else if (!isTimeZone(data.timezone)) err(`\`timezone\` must be a time zone like America/Los_Angeles or UTC, and ${JSON.stringify(data.timezone)} isn't one`);
|
|
100
|
-
|
|
101
|
-
if (data.enabled !== undefined && typeof data.enabled !== "boolean") err("`enabled` must be true or false");
|
|
102
|
-
|
|
103
|
-
if (data.budget !== undefined && budgetCents(data.budget) === null) err("`budget` must be an amount in US dollars above 0, like 0.50");
|
|
104
|
-
|
|
105
|
-
if (data.description !== undefined && data.description !== null) {
|
|
106
|
-
if (typeof data.description !== "string") err("`description` must be text");
|
|
107
|
-
else if (data.description.length > MAX_DESCRIPTION) err(`\`description\` must be at most ${MAX_DESCRIPTION.toLocaleString("en-US")} characters`);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
for (const key of Object.keys(data)) if (!FIELDS.includes(key)) err(`unknown field \`${key}\``);
|
|
111
|
-
|
|
112
|
-
if (body.trim() === "") err("the body is empty; it's the message the agent starts each run with");
|
|
113
|
-
|
|
114
|
-
if (waiting.length > 0 && data.enabled !== false) {
|
|
115
|
-
warnings.push(`${task.file}: nobody's there to answer during a scheduled run, so a run that calls one of these waits until it's stopped: ${waiting.join(", ")}`);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
return { errors, warnings };
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// Dollars as the API's minor units, or null if it isn't an amount above 0 with at most two decimals.
|
|
122
|
-
function budgetCents(value) {
|
|
123
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
|
|
124
|
-
const cents = Math.round(value * 100);
|
|
125
|
-
return Math.abs(cents - value * 100) < 1e-6 && cents > 0 ? cents : null;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// The tools that stop a run until someone answers, which nobody does during a scheduled run: ones set to
|
|
129
|
-
// ask first, and custom and agentbook tools, which run wherever the session is being watched from.
|
|
130
|
-
function toolsThatWaitForSomeone(tools) {
|
|
131
|
-
const isOn = (row) => row.enabled.toLowerCase() === "true";
|
|
132
|
-
return tools.flatMap((tool) => {
|
|
133
|
-
const type = tool.data.type;
|
|
134
|
-
if (type === TOOLSET) return (tool.rows ?? []).filter((row) => isOn(row) && row.permission === "always_ask").map((row) => row.name);
|
|
135
|
-
if (type === MCP_TOOLSET) {
|
|
136
|
-
const defaults = tool.data.default_config;
|
|
137
|
-
const fallback = defaults?.permission_policy?.type ?? "always_ask";
|
|
138
|
-
if (tool.rows?.length) return tool.rows.filter((row) => isOn(row) && (row.permission || fallback) === "always_ask").map((row) => `${tool.name}.${row.name}`);
|
|
139
|
-
return fallback === "always_ask" && defaults?.enabled !== false ? [`every tool in ${tool.name}`] : [];
|
|
140
|
-
}
|
|
141
|
-
if (type === "custom") return [tool.name];
|
|
142
|
-
if (type === AGENTBOOK) return (tool.rows ?? []).filter(isOn).map((row) => `${tool.name}.${row.name}`);
|
|
143
|
-
return [];
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
// How a task behaves, with the defaults filled in, so that every host agrees on them.
|
|
148
|
-
export function taskSettings({ name, data, body }) {
|
|
149
|
-
return {
|
|
150
|
-
name,
|
|
151
|
-
schedule: data.schedule,
|
|
152
|
-
timezone: data.timezone,
|
|
153
|
-
enabled: data.enabled ?? true,
|
|
154
|
-
budgetCents: data.budget === undefined ? null : budgetCents(data.budget),
|
|
155
|
-
description: data.description ?? null,
|
|
156
|
-
message: body,
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
// The parts of a deployment that come from the task's file. Whoever deploys it adds the agent, the
|
|
161
|
-
// environment and the vaults.
|
|
162
|
-
export function taskBody(task) {
|
|
163
|
-
const { name, schedule, timezone, budgetCents: cents, description, message } = taskSettings(task);
|
|
164
|
-
const body = {
|
|
165
|
-
name,
|
|
166
|
-
initial_events: [{ type: "user.message", content: [{ type: "text", text: message }] }],
|
|
167
|
-
schedule: { type: "cron", expression: schedule.trim(), timezone },
|
|
168
|
-
};
|
|
169
|
-
if (cents !== null) body.budget = { type: "limit", max_list_cost: { amount: String(cents), currency: "USD" } };
|
|
170
|
-
if (description) body.description = description;
|
|
171
|
-
return body;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// A task's key in the lock.
|
|
175
|
-
export const taskKey = (task) => `./${task.file}`;
|
package/lib/skills.js
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { bytesOf, isIgnoredPath, pathsUnder, textOf } from "./files.js";
|
|
2
|
-
import { FileError, parseMarkdown } from "./markdown.js";
|
|
3
|
-
|
|
4
|
-
export const SKILLS_DIR = "skills";
|
|
5
|
-
export const SKILL_FILE = "SKILL.md";
|
|
6
|
-
export const MAX_UPLOAD_BYTES = 30 * 1024 * 1024;
|
|
7
|
-
|
|
8
|
-
// Reads skills/: each folder is a skill, with a SKILL.md at its top and any other files it needs,
|
|
9
|
-
// at any depth. Hidden files and node_modules are left out. Skills are sorted by name. No skills/
|
|
10
|
-
// folder means no skills.
|
|
11
|
-
// Returns { skills, errors }; a skill that can't be read has an entry in errors.
|
|
12
|
-
export function readSkills(files) {
|
|
13
|
-
if (SKILLS_DIR in files) return { skills: [], errors: [`${SKILLS_DIR}: not a directory`] };
|
|
14
|
-
|
|
15
|
-
const folders = new Map();
|
|
16
|
-
const errors = [];
|
|
17
|
-
for (const file of pathsUnder(files, SKILLS_DIR)) {
|
|
18
|
-
const [, name, ...rest] = file.split("/");
|
|
19
|
-
if (rest.length === 0) {
|
|
20
|
-
if (name.endsWith(".md")) errors.push(`${file}: each skill is a folder, like ${SKILLS_DIR}/my-skill/${SKILL_FILE}`);
|
|
21
|
-
continue;
|
|
22
|
-
}
|
|
23
|
-
if (!folders.has(name)) folders.set(name, []);
|
|
24
|
-
folders.get(name).push({ rel: rest.join("/"), bytes: bytesOf(files[file]) });
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const skills = [];
|
|
28
|
-
for (const [name, skillFiles] of folders) {
|
|
29
|
-
const path = `${SKILLS_DIR}/${name}`;
|
|
30
|
-
// Exact names only, so a skill behaves the same on a case-sensitive file system.
|
|
31
|
-
const main = skillFiles.find((f) => f.rel === SKILL_FILE);
|
|
32
|
-
if (!main) {
|
|
33
|
-
const wrongCase = skillFiles.find((f) => f.rel.toLowerCase() === SKILL_FILE.toLowerCase());
|
|
34
|
-
errors.push(`${path}: missing ${SKILL_FILE}${wrongCase ? ` (found ${wrongCase.rel}; the name must be uppercase)` : ""}`);
|
|
35
|
-
continue;
|
|
36
|
-
}
|
|
37
|
-
try {
|
|
38
|
-
const parsed = parseMarkdown(textOf(main.bytes), `${path}/${SKILL_FILE}`);
|
|
39
|
-
skills.push({ name, path, file: `${path}/${SKILL_FILE}`, files: skillFiles, ...parsed });
|
|
40
|
-
} catch (err) {
|
|
41
|
-
if (!(err instanceof FileError)) throw err;
|
|
42
|
-
errors.push(err.message);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
return { skills, errors };
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// The lock file key for a skill.
|
|
49
|
-
export const skillKey = (skill) => `./${skill.path}`;
|
|
50
|
-
|
|
51
|
-
// The agent's references to the skills deployed from this folder, pinned to their versions, so
|
|
52
|
-
// that a session runs exactly what deploy last sent.
|
|
53
|
-
export function skillRefs(skills = [], lock) {
|
|
54
|
-
return skills
|
|
55
|
-
.map((skill) => lock?.resources?.[skillKey(skill)])
|
|
56
|
-
.filter(Boolean)
|
|
57
|
-
.map((entry) => ({ type: "custom", skill_id: entry.id, version: entry.version }));
|
|
58
|
-
}
|
package/lib/stream.js
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
// The text of a complete agent.message event.
|
|
2
|
-
export const agentMessageText = (event) => event.content.filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
3
|
-
|
|
4
|
-
// Passes the agent's text to `write` as it streams in, chunk by chunk. Deltas are best effort (the
|
|
5
|
-
// server may stop sending them under load), so the complete agent.message that follows is the
|
|
6
|
-
// record: whatever part of it the deltas didn't cover is written then.
|
|
7
|
-
export function textStream(write) {
|
|
8
|
-
let preview = null; // { id, text } for the agent.message being previewed
|
|
9
|
-
const close = () => {
|
|
10
|
-
if (preview?.text) write("\n");
|
|
11
|
-
preview = null;
|
|
12
|
-
};
|
|
13
|
-
return {
|
|
14
|
-
// Returns true when the event was written here, so it shouldn't be shown again.
|
|
15
|
-
handle(event) {
|
|
16
|
-
switch (event.type) {
|
|
17
|
-
case "event_start":
|
|
18
|
-
close();
|
|
19
|
-
if (event.event?.type === "agent.message") preview = { id: event.event.id, text: "" };
|
|
20
|
-
return true;
|
|
21
|
-
case "event_delta": {
|
|
22
|
-
const content = event.delta?.content;
|
|
23
|
-
if (preview?.id !== event.event_id || content?.type !== "text" || !content.text) return true;
|
|
24
|
-
preview.text += content.text;
|
|
25
|
-
write(content.text);
|
|
26
|
-
return true;
|
|
27
|
-
}
|
|
28
|
-
case "agent.message": {
|
|
29
|
-
if (preview?.id !== event.id) {
|
|
30
|
-
close();
|
|
31
|
-
return false;
|
|
32
|
-
}
|
|
33
|
-
const full = agentMessageText(event);
|
|
34
|
-
const shown = preview.text;
|
|
35
|
-
preview = null;
|
|
36
|
-
if (full.startsWith(shown)) {
|
|
37
|
-
if (full.length > 0) write(`${full.slice(shown.length)}\n`);
|
|
38
|
-
} else {
|
|
39
|
-
write(`\n${full}\n`);
|
|
40
|
-
}
|
|
41
|
-
return true;
|
|
42
|
-
}
|
|
43
|
-
default:
|
|
44
|
-
// A model request that errors or is interrupted ends without its agent.message.
|
|
45
|
-
close();
|
|
46
|
-
return false;
|
|
47
|
-
}
|
|
48
|
-
},
|
|
49
|
-
};
|
|
50
|
-
}
|
package/lib/tools.js
DELETED
|
@@ -1,327 +0,0 @@
|
|
|
1
|
-
import { stringify } from "yaml";
|
|
2
|
-
import { pathsUnder, textOf } from "./files.js";
|
|
3
|
-
import { FileError, parseMarkdown } from "./markdown.js";
|
|
4
|
-
|
|
5
|
-
export const TOOLS_DIR = "tools";
|
|
6
|
-
export const TOOLSET = "agent_toolset_20260401";
|
|
7
|
-
export const TOOLSET_FILE = `${TOOLSET}.md`;
|
|
8
|
-
export const MCP_TOOLSET = "mcp_toolset";
|
|
9
|
-
export const AGENTBOOK = "agentbook";
|
|
10
|
-
export const PREBUILT_TOOLS = ["bash", "edit", "glob", "grep", "read", "web_fetch", "web_search", "write"];
|
|
11
|
-
export const POLICIES = ["always_allow", "always_ask", "auto"];
|
|
12
|
-
// agentbook tools reach the API as custom tools, which have no permission policy: agentbook
|
|
13
|
-
// enforces these itself, and has nothing like the API's per-call `auto` judgement.
|
|
14
|
-
const AGENTBOOK_POLICIES = ["always_allow", "always_ask"];
|
|
15
|
-
const TYPES = ["string", "number", "integer", "boolean", "object", "array"];
|
|
16
|
-
|
|
17
|
-
// Reads every .md file under tools/, in any subfolder, sorted by name. Folders are only for
|
|
18
|
-
// organizing: a custom tool's name is its file name, and its path isn't compiled into anything.
|
|
19
|
-
// The pre-built toolset is one file (by convention tools/agent_toolset_20260401.md) that lists its tools.
|
|
20
|
-
// No tools/ folder means no tools.
|
|
21
|
-
// Returns { tools, errors }; a tool file that can't be parsed has an entry in errors.
|
|
22
|
-
export function readTools(files) {
|
|
23
|
-
if (TOOLS_DIR in files) return { tools: [], errors: [`${TOOLS_DIR}: not a directory`] };
|
|
24
|
-
|
|
25
|
-
const tools = [];
|
|
26
|
-
const errors = [];
|
|
27
|
-
for (const file of pathsUnder(files, TOOLS_DIR).filter((path) => path.endsWith(".md"))) {
|
|
28
|
-
try {
|
|
29
|
-
const parsed = parseMarkdown(textOf(files[file]), file);
|
|
30
|
-
const name = file.slice(file.lastIndexOf("/") + 1, -".md".length);
|
|
31
|
-
tools.push({ file, name, ...parsed, ...parseSections(parsed.body, file) });
|
|
32
|
-
} catch (err) {
|
|
33
|
-
if (!(err instanceof FileError)) throw err;
|
|
34
|
-
errors.push(err.message);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// Names must be unique across folders, since the folders are dropped.
|
|
39
|
-
for (const [type, what] of [["custom", "tool"], [MCP_TOOLSET, "MCP server"], [AGENTBOOK, "agentbook toolset"]]) {
|
|
40
|
-
for (const [name, same] of groupBy(tools.filter((t) => t.data.type === type), (t) => t.name)) {
|
|
41
|
-
if (same.length > 1) errors.push(`${TOOLS_DIR}: more than one ${what} is named \`${name}\` (${same.map((t) => t.file).join(", ")})`);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
const toolsets = tools.filter((t) => t.data.type === TOOLSET);
|
|
45
|
-
if (toolsets.length > 1) {
|
|
46
|
-
errors.push(`${TOOLS_DIR}: more than one \`${TOOLSET}\` file (${toolsets.map((t) => t.file).join(", ")}); list every pre-built tool in one file`);
|
|
47
|
-
}
|
|
48
|
-
return { tools: tools.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)), errors };
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function groupBy(items, key) {
|
|
52
|
-
const groups = new Map();
|
|
53
|
-
for (const item of items) groups.set(key(item), [...(groups.get(key(item)) ?? []), item]);
|
|
54
|
-
return groups;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Pulls the `## Input Schema` table, the `## Code` block and the `## Tools` table (for a toolset)
|
|
58
|
-
// out of a tool file's body.
|
|
59
|
-
function parseSections(body, file) {
|
|
60
|
-
const sections = {};
|
|
61
|
-
let current = null;
|
|
62
|
-
let fence = null;
|
|
63
|
-
for (const line of body.split("\n")) {
|
|
64
|
-
const marker = /^(```|~~~)/.exec(line)?.[1];
|
|
65
|
-
if (marker && (!fence || fence === marker)) fence = fence ? null : marker;
|
|
66
|
-
const heading = !fence && /^##\s+(.+?)\s*$/.exec(line);
|
|
67
|
-
if (heading) {
|
|
68
|
-
current = heading[1].toLowerCase();
|
|
69
|
-
sections[current] = [];
|
|
70
|
-
} else if (current) {
|
|
71
|
-
sections[current].push(line);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const result = { params: null, code: null, rows: null };
|
|
76
|
-
if (sections["input schema"]) {
|
|
77
|
-
result.params = parseTable(sections["input schema"], `${file}: the Input Schema table's columns must be Name | Type | Description | Required`,
|
|
78
|
-
["name", "type", "description", "required"]);
|
|
79
|
-
}
|
|
80
|
-
if (sections.code) result.code = parseCode(sections.code, file);
|
|
81
|
-
if (sections.tools) {
|
|
82
|
-
result.rows = parseTable(sections.tools, `${file}: the Tools table's columns must be Name | Enabled, or Name | Enabled | Permission`, ["name", "enabled"], ["permission"]);
|
|
83
|
-
}
|
|
84
|
-
return result;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// The rows of a Markdown table as objects keyed by column name. The header must start with
|
|
88
|
-
// the `required` columns, and may go on with the `optional` ones, in order.
|
|
89
|
-
function parseTable(lines, message, required, optional = []) {
|
|
90
|
-
const rows = lines.filter((l) => l.trim().startsWith("|")).map(splitRow);
|
|
91
|
-
if (rows.length === 0) return [];
|
|
92
|
-
const header = rows[0].map((c) => c.toLowerCase());
|
|
93
|
-
const allowed = [...required, ...optional];
|
|
94
|
-
if (header.length < required.length || header.length > allowed.length || header.some((c, i) => c !== allowed[i])) {
|
|
95
|
-
throw new FileError(message);
|
|
96
|
-
}
|
|
97
|
-
return rows.slice(2).map((cells) => Object.fromEntries(header.map((c, i) => [c, cells[i] ?? ""])));
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function splitRow(line) {
|
|
101
|
-
const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split(/(?<!\\)\|/);
|
|
102
|
-
return cells.map((c) => c.trim().replace(/\\\|/g, "|").replace(/^`(.*)`$/, "$1"));
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function parseCode(lines, file) {
|
|
106
|
-
const text = lines.join("\n");
|
|
107
|
-
const blocks = [...text.matchAll(/^(```|~~~)[ \t]*([\w-]*)[^\n]*\n([\s\S]*?)^\1[ \t]*$/gm)];
|
|
108
|
-
if (blocks.length !== 1) throw new FileError(`${file}: the Code section must hold exactly one fenced code block`);
|
|
109
|
-
const [, , lang, source] = blocks[0];
|
|
110
|
-
return { lang: lang.toLowerCase(), source };
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// Errors and warnings for the tool files, in check's format.
|
|
114
|
-
// `options.customTools: false` refuses custom tools, for hosts that won't run user code.
|
|
115
|
-
// `options.toolsets` is the catalog behind `type: agentbook` files; see agentbookTools.
|
|
116
|
-
export function checkTools(tools, errors, warnings = [], options = {}) {
|
|
117
|
-
const customs = tools.filter((t) => t.data.type === "custom");
|
|
118
|
-
if (customs.length + (customs.length < tools.length ? 1 : 0) > 256) errors.push(`${TOOLS_DIR}: more than 256 tools`);
|
|
119
|
-
|
|
120
|
-
// agentbook tools and custom tools all reach the API as custom tools, in one namespace.
|
|
121
|
-
if (options.toolsets) {
|
|
122
|
-
const names = new Set(customs.map((t) => t.name));
|
|
123
|
-
for (const { file, name } of agentbookTools(tools, options.toolsets)) {
|
|
124
|
-
if (names.has(name)) errors.push(`${file}: another tool is already named \`${name}\``);
|
|
125
|
-
names.add(name);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
for (const tool of tools) {
|
|
130
|
-
const err = (msg) => errors.push(`${tool.file}: ${msg}`);
|
|
131
|
-
const { type } = tool.data;
|
|
132
|
-
const extra = (allowed) => {
|
|
133
|
-
for (const key of Object.keys(tool.data)) if (!allowed.includes(key)) err(`unknown field \`${key}\``);
|
|
134
|
-
};
|
|
135
|
-
|
|
136
|
-
if (type === TOOLSET) {
|
|
137
|
-
checkToolset(tool, err);
|
|
138
|
-
extra(["type"]);
|
|
139
|
-
} else if (type === MCP_TOOLSET) {
|
|
140
|
-
checkMcpToolset(tool, err);
|
|
141
|
-
extra(["type", "mcp_server_name", "default_config", "url"]);
|
|
142
|
-
} else if (type === "custom") {
|
|
143
|
-
if (options.customTools === false) err("custom tools aren't available here, because they'd run your code on a shared server");
|
|
144
|
-
else checkCustom(tool, err);
|
|
145
|
-
extra(["type", "name", "description"]);
|
|
146
|
-
} else if (type === AGENTBOOK) {
|
|
147
|
-
checkAgentbook(tool, err, (msg) => warnings.push(`${tool.file}: ${msg}`), options);
|
|
148
|
-
extra(["type", "toolset"]);
|
|
149
|
-
} else {
|
|
150
|
-
err(`\`type\` must be \`${TOOLSET}\` (the pre-built tools), \`${MCP_TOOLSET}\` (an MCP server), \`custom\` or \`${AGENTBOOK}\``);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// The tools of an MCP server that agent.md declares: `mcp_server_name` is the server's name, and the
|
|
156
|
-
// optional `## Tools` table configures tools by the names the server reports.
|
|
157
|
-
function checkMcpToolset(tool, err) {
|
|
158
|
-
const { mcp_server_name: server, default_config: defaults } = tool.data;
|
|
159
|
-
if ("url" in tool.data) err("`url` belongs in agent.md's `mcp_servers`; refer to the server here with `mcp_server_name`");
|
|
160
|
-
if (typeof server !== "string" || server === "") err("`mcp_server_name` is required");
|
|
161
|
-
else if (server !== tool.name) err(`\`mcp_server_name\` must match the file name (${tool.name})`);
|
|
162
|
-
if (tool.name.length > 255) err("an MCP server's name (its file name) must be at most 255 characters");
|
|
163
|
-
|
|
164
|
-
if (defaults !== undefined && defaults !== null) {
|
|
165
|
-
if (typeof defaults !== "object" || Array.isArray(defaults)) err("`default_config` must be a mapping");
|
|
166
|
-
else {
|
|
167
|
-
if (defaults.enabled !== undefined && typeof defaults.enabled !== "boolean") err("`default_config.enabled` must be true or false");
|
|
168
|
-
const policy = defaults.permission_policy;
|
|
169
|
-
if (policy !== undefined && !POLICIES.includes(policy?.type)) {
|
|
170
|
-
err(`\`default_config.permission_policy.type\` must be ${POLICIES.join(", ")}`);
|
|
171
|
-
}
|
|
172
|
-
for (const key of Object.keys(defaults)) {
|
|
173
|
-
if (!["enabled", "permission_policy"].includes(key)) err(`unknown field \`default_config.${key}\``);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
checkRows(tool.rows ?? [], err, { known: null });
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// A toolset from agentbook's catalog. `## Tools` turns its tools on one by one, so a tool without
|
|
181
|
-
// a row is off: a new tool in the catalog never reaches a deployed agent by itself.
|
|
182
|
-
function checkAgentbook(tool, err, warn, { toolsets }) {
|
|
183
|
-
const { toolset } = tool.data;
|
|
184
|
-
if (typeof toolset !== "string" || toolset === "") return err("`toolset` is required");
|
|
185
|
-
if (toolset !== tool.name) err(`\`toolset\` must match the file name (${tool.name})`);
|
|
186
|
-
if (!tool.rows) err("a `## Tools` table listing the tools to enable is required");
|
|
187
|
-
|
|
188
|
-
if (!toolsets) warn("this toolset runs on agentbook, so `agentschema deploy` can't deploy it");
|
|
189
|
-
else if (!Object.hasOwn(toolsets, toolset)) err(`\`${toolset}\` isn't an agentbook toolset; use ${Object.keys(toolsets).join(", ")}`);
|
|
190
|
-
const known = toolsets && Object.hasOwn(toolsets, toolset) ? toolsets[toolset].tools.map((t) => t.name) : null;
|
|
191
|
-
checkRows(tool.rows ?? [], err, { known, what: `a tool in \`${toolset}\``, policies: AGENTBOOK_POLICIES });
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
function checkToolset(tool, err) {
|
|
195
|
-
if (!tool.rows) {
|
|
196
|
-
// 0.2.0 had one file per pre-built tool, with no table.
|
|
197
|
-
const hint = PREBUILT_TOOLS.includes(tool.name) ? `; since 0.2.1 all pre-built tools go in one file, ${TOOLS_DIR}/${TOOLSET_FILE}` : "";
|
|
198
|
-
return err(`a \`## Tools\` table listing the pre-built tools to enable is required${hint}`);
|
|
199
|
-
}
|
|
200
|
-
checkRows(tool.rows, err, { known: PREBUILT_TOOLS, what: "a pre-built tool" });
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
// The rows of a `## Tools` table. `known` is the list of valid tool names, when there is one.
|
|
204
|
-
function checkRows(rows, err, { known, what, policies = POLICIES }) {
|
|
205
|
-
const seen = new Set();
|
|
206
|
-
for (const row of rows) {
|
|
207
|
-
if (!row.name) err("a `## Tools` row has no name");
|
|
208
|
-
else if (known && !known.includes(row.name)) err(`\`${row.name}\` is not ${what}; use ${known.join(", ")}`);
|
|
209
|
-
else if (seen.has(row.name)) err(`\`${row.name}\` is listed twice`);
|
|
210
|
-
seen.add(row.name);
|
|
211
|
-
if (!["true", "false"].includes(row.enabled.toLowerCase())) err(`\`${row.name}\`: Enabled must be true or false`);
|
|
212
|
-
if (row.permission && !policies.includes(row.permission)) {
|
|
213
|
-
err(`\`${row.name}\` has permission \`${row.permission}\`; use ${policies.join(", ")}, or leave it blank`);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
function checkCustom(tool, err) {
|
|
219
|
-
const { name, description } = tool.data;
|
|
220
|
-
if (name !== tool.name) err(`\`name\` must match the file name (${tool.name})`);
|
|
221
|
-
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(tool.name)) err("the name may only use letters, digits, _ and -, up to 64 characters");
|
|
222
|
-
if (PREBUILT_TOOLS.includes(tool.name)) err(`\`${tool.name}\` is a pre-built tool's name; the API rejects custom tools that reuse one`);
|
|
223
|
-
if (/^(mcp__|ant__)/.test(tool.name)) err("custom tool names can't start with mcp__ or ant__");
|
|
224
|
-
if (typeof description !== "string" || description.trim() === "") err("`description` is required");
|
|
225
|
-
|
|
226
|
-
const seen = new Set();
|
|
227
|
-
for (const p of tool.params ?? []) {
|
|
228
|
-
if (!p.name) err("an Input Schema row has no name");
|
|
229
|
-
else if (seen.has(p.name)) err(`input \`${p.name}\` is listed twice`);
|
|
230
|
-
seen.add(p.name);
|
|
231
|
-
if (!TYPES.includes(p.type?.replace(/\[\]$/, ""))) {
|
|
232
|
-
err(`input \`${p.name}\` has type \`${p.type}\`; use ${TYPES.join(", ")}, or one of them followed by []`);
|
|
233
|
-
}
|
|
234
|
-
if (!["true", "false"].includes(p.required?.toLowerCase())) err(`input \`${p.name}\`: Required must be true or false`);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
if (!tool.code) return err("a `## Code` section with a JavaScript code block is required");
|
|
238
|
-
if (!["javascript", "js"].includes(tool.code.lang)) err("the code must be JavaScript (```javascript)");
|
|
239
|
-
else {
|
|
240
|
-
// Parses the code without running it: the function this builds is never called.
|
|
241
|
-
try {
|
|
242
|
-
new Function(wrapToolCode(tool.code.source));
|
|
243
|
-
} catch (e) {
|
|
244
|
-
// A page's content security policy can forbid this, which says nothing about the code.
|
|
245
|
-
if (e instanceof SyntaxError) err(`the code doesn't parse: ${e.message}`);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
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
|
-
|
|
265
|
-
// The agentbook tools a folder turns on, as { file, toolset, name, description, input_schema,
|
|
266
|
-
// permission }. `toolsets` is the catalog, { [toolset]: { tools: [{ name, description, input_schema }] } }.
|
|
267
|
-
// A blank permission means `always_ask`, the safe choice for a tool with no policy of its own.
|
|
268
|
-
export function agentbookTools(tools, toolsets = {}) {
|
|
269
|
-
return byName(tools.filter((t) => t.data.type === AGENTBOOK)).flatMap((tool) => {
|
|
270
|
-
const { toolset } = tool.data;
|
|
271
|
-
if (!Object.hasOwn(toolsets, toolset)) return [];
|
|
272
|
-
return toolsets[toolset].tools.flatMap((definition) => {
|
|
273
|
-
const row = tool.rows?.find((r) => r.name === definition.name);
|
|
274
|
-
if (row?.enabled.toLowerCase() !== "true") return [];
|
|
275
|
-
return [{ ...definition, file: tool.file, toolset, permission: row.permission || "always_ask" }];
|
|
276
|
-
});
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// The tools list sent to the API, each kind sorted by name: the pre-built toolset with a config
|
|
281
|
-
// for each row of its table (tools it doesn't list keep the API's defaults), then a toolset for
|
|
282
|
-
// each MCP server, then the custom tools, and last agentbook's tools, which reach the API as
|
|
283
|
-
// custom tools. Only their name, description and input schema are sent.
|
|
284
|
-
export function compileTools(tools, { toolsets } = {}) {
|
|
285
|
-
const compiled = [];
|
|
286
|
-
const toolset = tools.find((t) => t.data.type === TOOLSET);
|
|
287
|
-
if (toolset) compiled.push({ type: TOOLSET, configs: configs(toolset.rows) });
|
|
288
|
-
for (const tool of byName(tools.filter((t) => t.data.type === MCP_TOOLSET))) {
|
|
289
|
-
const entry = { type: MCP_TOOLSET, mcp_server_name: tool.name };
|
|
290
|
-
if (tool.data.default_config) entry.default_config = tool.data.default_config;
|
|
291
|
-
if (tool.rows?.length) entry.configs = configs(tool.rows);
|
|
292
|
-
compiled.push(entry);
|
|
293
|
-
}
|
|
294
|
-
for (const tool of tools.filter((t) => t.data.type === "custom").sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
295
|
-
compiled.push({ type: "custom", name: tool.name, description: tool.data.description, input_schema: inputSchema(tool.params ?? []) });
|
|
296
|
-
}
|
|
297
|
-
for (const { name, description, input_schema } of agentbookTools(tools, toolsets)) {
|
|
298
|
-
compiled.push({ type: "custom", name, description, input_schema });
|
|
299
|
-
}
|
|
300
|
-
return compiled;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
const byName = (tools) => [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
304
|
-
|
|
305
|
-
function configs(rows = []) {
|
|
306
|
-
return [...rows].sort((a, b) => (a.name < b.name ? -1 : 1)).map(({ name, enabled, permission }) => {
|
|
307
|
-
const config = { name, enabled: enabled.toLowerCase() === "true" };
|
|
308
|
-
if (permission) config.permission_policy = { type: permission };
|
|
309
|
-
return config;
|
|
310
|
-
});
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
function inputSchema(params) {
|
|
314
|
-
const properties = {};
|
|
315
|
-
for (const p of params) {
|
|
316
|
-
const list = p.type.endsWith("[]");
|
|
317
|
-
const type = p.type.replace(/\[\]$/, "");
|
|
318
|
-
const prop = list ? { type: "array", items: { type } } : { type };
|
|
319
|
-
if (p.description) prop.description = p.description;
|
|
320
|
-
properties[p.name] = prop;
|
|
321
|
-
}
|
|
322
|
-
const required = params.filter((p) => p.required.toLowerCase() === "true").map((p) => p.name);
|
|
323
|
-
return required.length > 0 ? { type: "object", properties, required } : { type: "object", properties };
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
// A custom tool's code wrapped as a CommonJS module.
|
|
327
|
-
export const wrapToolCode = (source) => `(function (exports, require, module, __filename, __dirname) {${source}\n})`;
|