@soft-boy/agentschema 0.3.12 → 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 +13 -9
- 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 -10
- 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/dist/src/folder.js +57 -0
- 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 -388
- package/lib/instance.js +0 -48
- 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/folder.js +0 -55
- 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
|
@@ -0,0 +1,105 @@
|
|
|
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 PREBUILT_TOOLS: string[];
|
|
9
|
+
export declare const POLICIES: string[];
|
|
10
|
+
export interface ToolParam {
|
|
11
|
+
name: string;
|
|
12
|
+
type: string;
|
|
13
|
+
description: string;
|
|
14
|
+
required: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ToolRow {
|
|
17
|
+
name: string;
|
|
18
|
+
enabled: string;
|
|
19
|
+
permission?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface ToolCode {
|
|
22
|
+
lang: string;
|
|
23
|
+
source: string;
|
|
24
|
+
}
|
|
25
|
+
export interface Tool extends MarkdownFile {
|
|
26
|
+
file: string;
|
|
27
|
+
name: string;
|
|
28
|
+
params: ToolParam[] | null;
|
|
29
|
+
code: ToolCode | null;
|
|
30
|
+
rows: ToolRow[] | null;
|
|
31
|
+
path?: string;
|
|
32
|
+
}
|
|
33
|
+
export interface ReadToolsResult {
|
|
34
|
+
tools: Tool[];
|
|
35
|
+
errors: string[];
|
|
36
|
+
}
|
|
37
|
+
export type JsonSchema = Record<string, unknown>;
|
|
38
|
+
export interface AgentbookToolDefinition {
|
|
39
|
+
name: string;
|
|
40
|
+
description: string;
|
|
41
|
+
input_schema: JsonSchema;
|
|
42
|
+
liveAllowed?: boolean;
|
|
43
|
+
safeForAnyone?: boolean;
|
|
44
|
+
}
|
|
45
|
+
export type AgentbookCatalog = Record<string, {
|
|
46
|
+
tools: AgentbookToolDefinition[];
|
|
47
|
+
}>;
|
|
48
|
+
export interface AgentbookTool extends AgentbookToolDefinition {
|
|
49
|
+
file: string;
|
|
50
|
+
toolset: string;
|
|
51
|
+
permission: string;
|
|
52
|
+
}
|
|
53
|
+
export interface CompileOptions {
|
|
54
|
+
toolsets?: AgentbookCatalog;
|
|
55
|
+
}
|
|
56
|
+
export interface CheckToolsOptions extends CompileOptions {
|
|
57
|
+
customTools?: boolean;
|
|
58
|
+
}
|
|
59
|
+
export interface PermissionPolicy {
|
|
60
|
+
type: string;
|
|
61
|
+
}
|
|
62
|
+
export interface ToolConfig {
|
|
63
|
+
name: string;
|
|
64
|
+
enabled: boolean;
|
|
65
|
+
permission_policy?: PermissionPolicy;
|
|
66
|
+
}
|
|
67
|
+
export interface SchemaProperty {
|
|
68
|
+
type: string;
|
|
69
|
+
items?: {
|
|
70
|
+
type: string;
|
|
71
|
+
};
|
|
72
|
+
description?: string;
|
|
73
|
+
}
|
|
74
|
+
export type InputSchema = {
|
|
75
|
+
type: "object";
|
|
76
|
+
properties: Record<string, SchemaProperty>;
|
|
77
|
+
required?: string[];
|
|
78
|
+
};
|
|
79
|
+
export interface CompiledToolset {
|
|
80
|
+
type: typeof TOOLSET;
|
|
81
|
+
configs: ToolConfig[];
|
|
82
|
+
}
|
|
83
|
+
export interface CompiledMcpToolset {
|
|
84
|
+
type: typeof MCP_TOOLSET;
|
|
85
|
+
mcp_server_name: string;
|
|
86
|
+
default_config?: Frontmatter;
|
|
87
|
+
configs?: ToolConfig[];
|
|
88
|
+
}
|
|
89
|
+
export interface CompiledCustomTool {
|
|
90
|
+
type: "custom";
|
|
91
|
+
name: string;
|
|
92
|
+
description: string;
|
|
93
|
+
input_schema: JsonSchema;
|
|
94
|
+
}
|
|
95
|
+
export type CompiledTool = CompiledToolset | CompiledMcpToolset | CompiledCustomTool;
|
|
96
|
+
export declare function readTools(files: FileMap): ReadToolsResult;
|
|
97
|
+
export declare function checkTools(tools: Tool[], errors: string[], warnings?: string[], options?: CheckToolsOptions): void;
|
|
98
|
+
export declare function mcpToolsetFile({ name, tools, permission }: {
|
|
99
|
+
name: string;
|
|
100
|
+
tools?: string[];
|
|
101
|
+
permission?: string;
|
|
102
|
+
}): string;
|
|
103
|
+
export declare function agentbookTools(tools: Tool[], toolsets?: AgentbookCatalog): AgentbookTool[];
|
|
104
|
+
export declare function compileTools(tools: Tool[], { toolsets }?: CompileOptions): CompiledTool[];
|
|
105
|
+
export declare const wrapToolCode: (source: string) => string;
|
|
@@ -0,0 +1,353 @@
|
|
|
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
|
+
export const PREBUILT_TOOLS = ["bash", "edit", "glob", "grep", "read", "web_fetch", "web_search", "write"];
|
|
10
|
+
export const POLICIES = ["always_allow", "always_ask", "auto"];
|
|
11
|
+
// agentbook tools reach the API as custom tools, which have no permission policy: agentbook
|
|
12
|
+
// enforces these itself, and has nothing like the API's per-call `auto` judgement.
|
|
13
|
+
const AGENTBOOK_POLICIES = ["always_allow", "always_ask"];
|
|
14
|
+
const TYPES = ["string", "number", "integer", "boolean", "object", "array"];
|
|
15
|
+
// Reads every .md file under tools/, in any subfolder, sorted by name. Folders are only for
|
|
16
|
+
// organizing: a custom tool's name is its file name, and its path isn't compiled into anything.
|
|
17
|
+
// The pre-built toolset is one file (by convention tools/agent_toolset_20260401.md) that lists its tools.
|
|
18
|
+
// No tools/ folder means no tools.
|
|
19
|
+
// Returns { tools, errors }; a tool file that can't be parsed has an entry in errors.
|
|
20
|
+
export function readTools(files) {
|
|
21
|
+
if (TOOLS_DIR in files)
|
|
22
|
+
return { tools: [], errors: [`${TOOLS_DIR}: not a directory`] };
|
|
23
|
+
const tools = [];
|
|
24
|
+
const errors = [];
|
|
25
|
+
for (const file of pathsUnder(files, TOOLS_DIR).filter((path) => path.endsWith(".md"))) {
|
|
26
|
+
try {
|
|
27
|
+
const parsed = parseMarkdown(textOf(files[file]), file);
|
|
28
|
+
const name = file.slice(file.lastIndexOf("/") + 1, -".md".length);
|
|
29
|
+
tools.push({ file, name, ...parsed, ...parseSections(parsed.body, file) });
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
if (!(err instanceof FileError))
|
|
33
|
+
throw err;
|
|
34
|
+
errors.push(err.message);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
// Names must be unique across folders, since the folders are dropped.
|
|
38
|
+
for (const [type, what] of [["custom", "tool"], [MCP_TOOLSET, "MCP server"], [AGENTBOOK, "agentbook toolset"]]) {
|
|
39
|
+
for (const [name, same] of groupBy(tools.filter((t) => t.data.type === type), (t) => t.name)) {
|
|
40
|
+
if (same.length > 1)
|
|
41
|
+
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
|
+
function groupBy(items, key) {
|
|
51
|
+
const groups = new Map();
|
|
52
|
+
for (const item of items)
|
|
53
|
+
groups.set(key(item), [...(groups.get(key(item)) ?? []), item]);
|
|
54
|
+
return groups;
|
|
55
|
+
}
|
|
56
|
+
// Pulls the `## Input Schema` table, the `## Code` block and the `## Tools` table (for a toolset)
|
|
57
|
+
// out of a tool file's body.
|
|
58
|
+
function parseSections(body, file) {
|
|
59
|
+
const sections = {};
|
|
60
|
+
let current = null;
|
|
61
|
+
let fence = null;
|
|
62
|
+
for (const line of body.split("\n")) {
|
|
63
|
+
const marker = /^(```|~~~)/.exec(line)?.[1];
|
|
64
|
+
if (marker && (!fence || fence === marker))
|
|
65
|
+
fence = fence ? null : marker;
|
|
66
|
+
const heading = !fence && /^##\s+(.+?)\s*$/.exec(line);
|
|
67
|
+
if (heading) {
|
|
68
|
+
current = heading[1].toLowerCase();
|
|
69
|
+
sections[current] = [];
|
|
70
|
+
}
|
|
71
|
+
else if (current) {
|
|
72
|
+
sections[current].push(line);
|
|
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`, ["name", "type", "description", "required"]);
|
|
78
|
+
}
|
|
79
|
+
if (sections.code)
|
|
80
|
+
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
|
+
// The rows of a Markdown table as objects keyed by column name. The header must start with
|
|
87
|
+
// the `required` columns, and may go on with the `optional` ones, in order.
|
|
88
|
+
function parseTable(lines, message, required, optional = []) {
|
|
89
|
+
const rows = lines.filter((l) => l.trim().startsWith("|")).map(splitRow);
|
|
90
|
+
if (rows.length === 0)
|
|
91
|
+
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
|
+
function splitRow(line) {
|
|
100
|
+
const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split(/(?<!\\)\|/);
|
|
101
|
+
return cells.map((c) => c.trim().replace(/\\\|/g, "|").replace(/^`(.*)`$/, "$1"));
|
|
102
|
+
}
|
|
103
|
+
function parseCode(lines, file) {
|
|
104
|
+
const text = lines.join("\n");
|
|
105
|
+
const blocks = [...text.matchAll(/^(```|~~~)[ \t]*([\w-]*)[^\n]*\n([\s\S]*?)^\1[ \t]*$/gm)];
|
|
106
|
+
if (blocks.length !== 1)
|
|
107
|
+
throw new FileError(`${file}: the Code section must hold exactly one fenced code block`);
|
|
108
|
+
const [, , lang, source] = blocks[0];
|
|
109
|
+
return { lang: lang.toLowerCase(), source };
|
|
110
|
+
}
|
|
111
|
+
// Errors and warnings for the tool files, in check's format.
|
|
112
|
+
// `options.customTools: false` refuses custom tools, for hosts that won't run user code.
|
|
113
|
+
// `options.toolsets` is the catalog behind `type: agentbook` files; see agentbookTools.
|
|
114
|
+
export function checkTools(tools, errors, warnings = [], options = {}) {
|
|
115
|
+
const customs = tools.filter((t) => t.data.type === "custom");
|
|
116
|
+
if (customs.length + (customs.length < tools.length ? 1 : 0) > 256)
|
|
117
|
+
errors.push(`${TOOLS_DIR}: more than 256 tools`);
|
|
118
|
+
// agentbook tools and custom tools all reach the API as custom tools, in one namespace.
|
|
119
|
+
if (options.toolsets) {
|
|
120
|
+
const names = new Set(customs.map((t) => t.name));
|
|
121
|
+
for (const { file, name } of agentbookTools(tools, options.toolsets)) {
|
|
122
|
+
if (names.has(name))
|
|
123
|
+
errors.push(`${file}: another tool is already named \`${name}\``);
|
|
124
|
+
names.add(name);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
for (const tool of tools) {
|
|
128
|
+
const err = (msg) => errors.push(`${tool.file}: ${msg}`);
|
|
129
|
+
const { type } = tool.data;
|
|
130
|
+
const extra = (allowed) => {
|
|
131
|
+
for (const key of Object.keys(tool.data))
|
|
132
|
+
if (!allowed.includes(key))
|
|
133
|
+
err(`unknown field \`${key}\``);
|
|
134
|
+
};
|
|
135
|
+
if (type === TOOLSET) {
|
|
136
|
+
checkToolset(tool, err);
|
|
137
|
+
extra(["type"]);
|
|
138
|
+
}
|
|
139
|
+
else if (type === MCP_TOOLSET) {
|
|
140
|
+
checkMcpToolset(tool, err);
|
|
141
|
+
extra(["type", "mcp_server_name", "default_config", "url"]);
|
|
142
|
+
}
|
|
143
|
+
else if (type === "custom") {
|
|
144
|
+
if (options.customTools === false)
|
|
145
|
+
err("custom tools aren't available here, because they'd run your code on a shared server");
|
|
146
|
+
else
|
|
147
|
+
checkCustom(tool, err);
|
|
148
|
+
extra(["type", "name", "description"]);
|
|
149
|
+
}
|
|
150
|
+
else if (type === AGENTBOOK) {
|
|
151
|
+
checkAgentbook(tool, err, (msg) => warnings.push(`${tool.file}: ${msg}`), options);
|
|
152
|
+
extra(["type", "toolset"]);
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
err(`\`type\` must be \`${TOOLSET}\` (the pre-built tools), \`${MCP_TOOLSET}\` (an MCP server), \`custom\` or \`${AGENTBOOK}\``);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
// The tools of an MCP server that agent.md declares: `mcp_server_name` is the server's name, and the
|
|
160
|
+
// optional `## Tools` table configures tools by the names the server reports.
|
|
161
|
+
function checkMcpToolset(tool, err) {
|
|
162
|
+
const { mcp_server_name: server, default_config: defaults } = tool.data;
|
|
163
|
+
if ("url" in tool.data)
|
|
164
|
+
err("`url` belongs in agent.md's `mcp_servers`; refer to the server here with `mcp_server_name`");
|
|
165
|
+
if (typeof server !== "string" || server === "")
|
|
166
|
+
err("`mcp_server_name` is required");
|
|
167
|
+
else if (server !== tool.name)
|
|
168
|
+
err(`\`mcp_server_name\` must match the file name (${tool.name})`);
|
|
169
|
+
if (tool.name.length > 255)
|
|
170
|
+
err("an MCP server's name (its file name) must be at most 255 characters");
|
|
171
|
+
if (defaults !== undefined && defaults !== null) {
|
|
172
|
+
if (typeof defaults !== "object" || Array.isArray(defaults))
|
|
173
|
+
err("`default_config` must be a mapping");
|
|
174
|
+
else {
|
|
175
|
+
if (defaults.enabled !== undefined && typeof defaults.enabled !== "boolean")
|
|
176
|
+
err("`default_config.enabled` must be true or false");
|
|
177
|
+
const policy = defaults.permission_policy;
|
|
178
|
+
if (policy !== undefined && !POLICIES.includes(policy?.type)) {
|
|
179
|
+
err(`\`default_config.permission_policy.type\` must be ${POLICIES.join(", ")}`);
|
|
180
|
+
}
|
|
181
|
+
for (const key of Object.keys(defaults)) {
|
|
182
|
+
if (!["enabled", "permission_policy"].includes(key))
|
|
183
|
+
err(`unknown field \`default_config.${key}\``);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
checkRows(tool.rows ?? [], err, { known: null });
|
|
188
|
+
}
|
|
189
|
+
// A toolset from agentbook's catalog. `## Tools` turns its tools on one by one, so a tool without
|
|
190
|
+
// a row is off: a new tool in the catalog never reaches a deployed agent by itself.
|
|
191
|
+
function checkAgentbook(tool, err, warn, { toolsets }) {
|
|
192
|
+
const { toolset } = tool.data;
|
|
193
|
+
if (typeof toolset !== "string" || toolset === "")
|
|
194
|
+
return err("`toolset` is required");
|
|
195
|
+
if (toolset !== tool.name)
|
|
196
|
+
err(`\`toolset\` must match the file name (${tool.name})`);
|
|
197
|
+
if (!tool.rows)
|
|
198
|
+
err("a `## Tools` table listing the tools to enable is required");
|
|
199
|
+
if (!toolsets)
|
|
200
|
+
warn("this toolset runs on agentbook, so `agentschema deploy` can't deploy it");
|
|
201
|
+
else if (!Object.hasOwn(toolsets, toolset))
|
|
202
|
+
err(`\`${toolset}\` isn't an agentbook toolset; use ${Object.keys(toolsets).join(", ")}`);
|
|
203
|
+
const known = toolsets && Object.hasOwn(toolsets, toolset) ? toolsets[toolset].tools.map((t) => t.name) : null;
|
|
204
|
+
checkRows(tool.rows ?? [], err, { known, what: `a tool in \`${toolset}\``, policies: AGENTBOOK_POLICIES });
|
|
205
|
+
}
|
|
206
|
+
function checkToolset(tool, err) {
|
|
207
|
+
if (!tool.rows) {
|
|
208
|
+
// 0.2.0 had one file per pre-built tool, with no table.
|
|
209
|
+
const hint = PREBUILT_TOOLS.includes(tool.name) ? `; since 0.2.1 all pre-built tools go in one file, ${TOOLS_DIR}/${TOOLSET_FILE}` : "";
|
|
210
|
+
return err(`a \`## Tools\` table listing the pre-built tools to enable is required${hint}`);
|
|
211
|
+
}
|
|
212
|
+
checkRows(tool.rows, err, { known: PREBUILT_TOOLS, what: "a pre-built tool" });
|
|
213
|
+
}
|
|
214
|
+
// The rows of a `## Tools` table. `known` is the list of valid tool names, when there is one.
|
|
215
|
+
function checkRows(rows, err, { known, what, policies = POLICIES }) {
|
|
216
|
+
const seen = new Set();
|
|
217
|
+
for (const row of rows) {
|
|
218
|
+
if (!row.name)
|
|
219
|
+
err("a `## Tools` row has no name");
|
|
220
|
+
else if (known && !known.includes(row.name))
|
|
221
|
+
err(`\`${row.name}\` is not ${what}; use ${known.join(", ")}`);
|
|
222
|
+
else if (seen.has(row.name))
|
|
223
|
+
err(`\`${row.name}\` is listed twice`);
|
|
224
|
+
seen.add(row.name);
|
|
225
|
+
if (!["true", "false"].includes(row.enabled.toLowerCase()))
|
|
226
|
+
err(`\`${row.name}\`: Enabled must be true or false`);
|
|
227
|
+
if (row.permission && !policies.includes(row.permission)) {
|
|
228
|
+
err(`\`${row.name}\` has permission \`${row.permission}\`; use ${policies.join(", ")}, or leave it blank`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function checkCustom(tool, err) {
|
|
233
|
+
const { name, description } = tool.data;
|
|
234
|
+
if (name !== tool.name)
|
|
235
|
+
err(`\`name\` must match the file name (${tool.name})`);
|
|
236
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(tool.name))
|
|
237
|
+
err("the name may only use letters, digits, _ and -, up to 64 characters");
|
|
238
|
+
if (PREBUILT_TOOLS.includes(tool.name))
|
|
239
|
+
err(`\`${tool.name}\` is a pre-built tool's name; the API rejects custom tools that reuse one`);
|
|
240
|
+
if (/^(mcp__|ant__)/.test(tool.name))
|
|
241
|
+
err("custom tool names can't start with mcp__ or ant__");
|
|
242
|
+
if (typeof description !== "string" || description.trim() === "")
|
|
243
|
+
err("`description` is required");
|
|
244
|
+
const seen = new Set();
|
|
245
|
+
for (const p of tool.params ?? []) {
|
|
246
|
+
if (!p.name)
|
|
247
|
+
err("an Input Schema row has no name");
|
|
248
|
+
else if (seen.has(p.name))
|
|
249
|
+
err(`input \`${p.name}\` is listed twice`);
|
|
250
|
+
seen.add(p.name);
|
|
251
|
+
if (!TYPES.includes(p.type?.replace(/\[\]$/, ""))) {
|
|
252
|
+
err(`input \`${p.name}\` has type \`${p.type}\`; use ${TYPES.join(", ")}, or one of them followed by []`);
|
|
253
|
+
}
|
|
254
|
+
if (!["true", "false"].includes(p.required?.toLowerCase()))
|
|
255
|
+
err(`input \`${p.name}\`: Required must be true or false`);
|
|
256
|
+
}
|
|
257
|
+
if (!tool.code)
|
|
258
|
+
return err("a `## Code` section with a JavaScript code block is required");
|
|
259
|
+
if (!["javascript", "js"].includes(tool.code.lang))
|
|
260
|
+
err("the code must be JavaScript (```javascript)");
|
|
261
|
+
else {
|
|
262
|
+
// Parses the code without running it: the function this builds is never called.
|
|
263
|
+
try {
|
|
264
|
+
new Function(wrapToolCode(tool.code.source));
|
|
265
|
+
}
|
|
266
|
+
catch (e) {
|
|
267
|
+
// A page's content security policy can forbid this, which says nothing about the code.
|
|
268
|
+
if (e instanceof SyntaxError)
|
|
269
|
+
err(`the code doesn't parse: ${e.message}`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
// An MCP server's tool file. With the server's tools, it's a table of them, all on, each with
|
|
274
|
+
// `permission`. A tool the server adds later isn't in the table, so it gets the API's defaults: on, and
|
|
275
|
+
// asking before each call. Many servers won't list their tools until you've signed in, so with no tools
|
|
276
|
+
// it keeps `permission` for all of them, ready for the table: see listedMcpToolset.
|
|
277
|
+
export function mcpToolsetFile({ name, tools = [], permission = "always_ask" }) {
|
|
278
|
+
const front = { type: MCP_TOOLSET, mcp_server_name: name };
|
|
279
|
+
if (tools.length > 0) {
|
|
280
|
+
const rows = tools.map((tool) => `| \`${tool}\` | \`true\` | \`${permission}\` |`);
|
|
281
|
+
const body = ["Set Enabled to false to turn a tool off.", "", "## Tools", "", "| Name | Enabled | Permission |", "|---|---|---|", ...rows, ""].join("\n");
|
|
282
|
+
return `---\n${stringify(front)}---\n\n${body}`;
|
|
283
|
+
}
|
|
284
|
+
if (permission !== "always_ask")
|
|
285
|
+
front.default_config = { permission_policy: { type: permission } };
|
|
286
|
+
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`;
|
|
287
|
+
}
|
|
288
|
+
// The agentbook tools a folder turns on, as { file, toolset, name, description, input_schema,
|
|
289
|
+
// permission }. `toolsets` is the catalog, { [toolset]: { tools: [{ name, description, input_schema }] } }.
|
|
290
|
+
// A blank permission means `always_ask`, the safe choice for a tool with no policy of its own.
|
|
291
|
+
export function agentbookTools(tools, toolsets = {}) {
|
|
292
|
+
return byName(tools.filter((t) => t.data.type === AGENTBOOK)).flatMap((tool) => {
|
|
293
|
+
const { toolset } = tool.data;
|
|
294
|
+
if (!Object.hasOwn(toolsets, toolset))
|
|
295
|
+
return [];
|
|
296
|
+
return toolsets[toolset].tools.flatMap((definition) => {
|
|
297
|
+
const row = tool.rows?.find((r) => r.name === definition.name);
|
|
298
|
+
if (row?.enabled.toLowerCase() !== "true")
|
|
299
|
+
return [];
|
|
300
|
+
return [{ ...definition, file: tool.file, toolset, permission: row.permission || "always_ask" }];
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
// The tools list sent to the API, each kind sorted by name: the pre-built toolset with a config
|
|
305
|
+
// for each row of its table (tools it doesn't list keep the API's defaults), then a toolset for
|
|
306
|
+
// each MCP server, then the custom tools, and last agentbook's tools, which reach the API as
|
|
307
|
+
// custom tools. Only their name, description and input schema are sent.
|
|
308
|
+
export function compileTools(tools, { toolsets } = {}) {
|
|
309
|
+
const compiled = [];
|
|
310
|
+
const toolset = tools.find((t) => t.data.type === TOOLSET);
|
|
311
|
+
// check requires the pre-built toolset's table, so its rows are there.
|
|
312
|
+
if (toolset)
|
|
313
|
+
compiled.push({ type: TOOLSET, configs: configs(toolset.rows) });
|
|
314
|
+
for (const tool of byName(tools.filter((t) => t.data.type === MCP_TOOLSET))) {
|
|
315
|
+
const entry = { type: MCP_TOOLSET, mcp_server_name: tool.name };
|
|
316
|
+
if (tool.data.default_config)
|
|
317
|
+
entry.default_config = tool.data.default_config;
|
|
318
|
+
if (tool.rows?.length)
|
|
319
|
+
entry.configs = configs(tool.rows);
|
|
320
|
+
compiled.push(entry);
|
|
321
|
+
}
|
|
322
|
+
for (const tool of tools.filter((t) => t.data.type === "custom").sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
323
|
+
compiled.push({ type: "custom", name: tool.name, description: tool.data.description, input_schema: inputSchema(tool.params ?? []) });
|
|
324
|
+
}
|
|
325
|
+
for (const { name, description, input_schema } of agentbookTools(tools, toolsets)) {
|
|
326
|
+
compiled.push({ type: "custom", name, description, input_schema });
|
|
327
|
+
}
|
|
328
|
+
return compiled;
|
|
329
|
+
}
|
|
330
|
+
const byName = (tools) => [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
331
|
+
function configs(rows = []) {
|
|
332
|
+
return [...rows].sort((a, b) => (a.name < b.name ? -1 : 1)).map(({ name, enabled, permission }) => {
|
|
333
|
+
const config = { name, enabled: enabled.toLowerCase() === "true" };
|
|
334
|
+
if (permission)
|
|
335
|
+
config.permission_policy = { type: permission };
|
|
336
|
+
return config;
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
function inputSchema(params) {
|
|
340
|
+
const properties = {};
|
|
341
|
+
for (const p of params) {
|
|
342
|
+
const list = p.type.endsWith("[]");
|
|
343
|
+
const type = p.type.replace(/\[\]$/, "");
|
|
344
|
+
const prop = list ? { type: "array", items: { type } } : { type };
|
|
345
|
+
if (p.description)
|
|
346
|
+
prop.description = p.description;
|
|
347
|
+
properties[p.name] = prop;
|
|
348
|
+
}
|
|
349
|
+
const required = params.filter((p) => p.required.toLowerCase() === "true").map((p) => p.name);
|
|
350
|
+
return required.length > 0 ? { type: "object", properties, required } : { type: "object", properties };
|
|
351
|
+
}
|
|
352
|
+
// A custom tool's code wrapped as a CommonJS module.
|
|
353
|
+
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;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { comparePaths, isIgnoredPath, textOf } from "./files.js";
|
|
2
|
+
import { FileError, parseMarkdown } from "./markdown.js";
|
|
3
|
+
export const VAULTS_DIR = "vaults";
|
|
4
|
+
export const VAULT_FILE = "vault.md";
|
|
5
|
+
export const MCP_OAUTH = "mcp_oauth";
|
|
6
|
+
export const ENV_VAR = "environment_variable";
|
|
7
|
+
export const CREDENTIAL_TYPES = [MCP_OAUTH, ENV_VAR];
|
|
8
|
+
export const TOKEN_ENDPOINT_AUTH = ["none", "client_secret_basic", "client_secret_post"];
|
|
9
|
+
// Fields that hold secrets or short-lived values. They never go in a file: `cred deploy`
|
|
10
|
+
// asks for them and sends them straight to the vault.
|
|
11
|
+
export const SECRET_FIELDS = {
|
|
12
|
+
[MCP_OAUTH]: [
|
|
13
|
+
["access_token"],
|
|
14
|
+
["expires_at"],
|
|
15
|
+
["refresh", "refresh_token"],
|
|
16
|
+
["refresh", "token_endpoint_auth", "client_secret"],
|
|
17
|
+
],
|
|
18
|
+
[ENV_VAR]: [["secret_value"]],
|
|
19
|
+
};
|
|
20
|
+
// Fields the API won't change on an existing credential. Changing one in a file is an error;
|
|
21
|
+
// delete the credential and create it again.
|
|
22
|
+
export const IMMUTABLE_FIELDS = {
|
|
23
|
+
[MCP_OAUTH]: [
|
|
24
|
+
["type"],
|
|
25
|
+
["mcp_server_url"],
|
|
26
|
+
["refresh"], // adding or removing the refresh block
|
|
27
|
+
["refresh", "token_endpoint"],
|
|
28
|
+
["refresh", "client_id"],
|
|
29
|
+
["refresh", "resource"],
|
|
30
|
+
["refresh", "token_endpoint_auth", "type"],
|
|
31
|
+
],
|
|
32
|
+
[ENV_VAR]: [["type"], ["secret_name"]],
|
|
33
|
+
};
|
|
34
|
+
// Reads vaults/: each folder is a vault named after the folder, holding an optional vault.md
|
|
35
|
+
// and one .md file per credential, named after the file. Vaults are sorted by name, which is
|
|
36
|
+
// the order `run` attaches them in. No vaults/ folder means no vaults.
|
|
37
|
+
// Returns { vaults, errors }; a file that can't be parsed has an entry in errors.
|
|
38
|
+
export function readVaults(files) {
|
|
39
|
+
if (VAULTS_DIR in files)
|
|
40
|
+
return { vaults: [], errors: [`${VAULTS_DIR}: not a directory`] };
|
|
41
|
+
const vaults = new Map();
|
|
42
|
+
const errors = [];
|
|
43
|
+
const parse = (file) => {
|
|
44
|
+
try {
|
|
45
|
+
return parseMarkdown(textOf(files[file]), file);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
if (!(err instanceof FileError))
|
|
49
|
+
throw err;
|
|
50
|
+
errors.push(err.message);
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const reportedFolders = new Set();
|
|
55
|
+
const paths = Object.keys(files)
|
|
56
|
+
.filter((path) => path.startsWith(`${VAULTS_DIR}/`) && !isIgnoredPath(path))
|
|
57
|
+
.sort(comparePaths);
|
|
58
|
+
for (const file of paths) {
|
|
59
|
+
const [, vaultName, itemName, ...rest] = file.split("/");
|
|
60
|
+
if (itemName === undefined) {
|
|
61
|
+
if (vaultName.endsWith(".md"))
|
|
62
|
+
errors.push(`${file}: each vault is a folder; put credential files inside one`);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const path = `${VAULTS_DIR}/${vaultName}`;
|
|
66
|
+
if (!vaults.has(vaultName))
|
|
67
|
+
vaults.set(vaultName, { name: vaultName, path, file: null, credentials: [] });
|
|
68
|
+
const vault = vaults.get(vaultName);
|
|
69
|
+
if (rest.length > 0) {
|
|
70
|
+
const folder = `${path}/${itemName}`;
|
|
71
|
+
if (!reportedFolders.has(folder))
|
|
72
|
+
errors.push(`${folder}: a vault holds credential files, not folders`);
|
|
73
|
+
reportedFolders.add(folder);
|
|
74
|
+
}
|
|
75
|
+
else if (itemName === VAULT_FILE) {
|
|
76
|
+
vault.file = parse(file);
|
|
77
|
+
}
|
|
78
|
+
else if (itemName.endsWith(".md")) {
|
|
79
|
+
const parsed = parse(file);
|
|
80
|
+
if (parsed)
|
|
81
|
+
vault.credentials.push({ file, name: itemName.slice(0, -".md".length), vault: vaultName, ...parsed });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { vaults: [...vaults.values()], errors };
|
|
85
|
+
}
|
|
86
|
+
// The lock file keys for a vault and a credential.
|
|
87
|
+
export const vaultKey = (vault) => `./${vault.path}`;
|
|
88
|
+
export const credentialKey = (cred) => `./${cred.file}`;
|
|
89
|
+
// The body sent to POST /v1/vaults: the folder name and vault.md's metadata.
|
|
90
|
+
export function vaultBody(vault) {
|
|
91
|
+
const body = { display_name: vault.name };
|
|
92
|
+
if (vault.file?.data.metadata !== undefined)
|
|
93
|
+
body.metadata = vault.file.data.metadata;
|
|
94
|
+
return body;
|
|
95
|
+
}
|
|
96
|
+
// A credential's settings from its file: everything but the secrets. This is what's hashed
|
|
97
|
+
// into the lock, and what deploy keeps in sync.
|
|
98
|
+
export function credentialSettings(cred) {
|
|
99
|
+
const body = { display_name: cred.name, auth: structuredClone(cred.data.auth) };
|
|
100
|
+
if (cred.data.metadata !== undefined)
|
|
101
|
+
body.metadata = cred.data.metadata;
|
|
102
|
+
return body;
|
|
103
|
+
}
|
|
104
|
+
// The body sent to create a credential: its settings plus the secrets `cred deploy` asked for.
|
|
105
|
+
export function credentialCreateBody(cred, { accessToken, expiresAt, refreshToken, clientSecret, secretValue }) {
|
|
106
|
+
const body = credentialSettings(cred);
|
|
107
|
+
if (body.auth.type === ENV_VAR) {
|
|
108
|
+
body.auth.secret_value = secretValue;
|
|
109
|
+
return body;
|
|
110
|
+
}
|
|
111
|
+
body.auth.access_token = accessToken;
|
|
112
|
+
if (expiresAt)
|
|
113
|
+
body.auth.expires_at = expiresAt;
|
|
114
|
+
if (body.auth.refresh) {
|
|
115
|
+
body.auth.refresh.refresh_token = refreshToken;
|
|
116
|
+
if (body.auth.refresh.token_endpoint_auth?.type !== "none")
|
|
117
|
+
body.auth.refresh.token_endpoint_auth.client_secret = clientSecret;
|
|
118
|
+
}
|
|
119
|
+
return body;
|
|
120
|
+
}
|
|
121
|
+
// Which secrets a credential file needs when it's created.
|
|
122
|
+
export function secretsNeeded(cred) {
|
|
123
|
+
const refresh = cred.data.auth?.refresh;
|
|
124
|
+
return {
|
|
125
|
+
refreshToken: Boolean(refresh),
|
|
126
|
+
clientSecret: Boolean(refresh) && refresh.token_endpoint_auth?.type !== "none",
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
// The immutable fields whose value in the file differs from the deployed credential's.
|
|
130
|
+
export function changedImmutableFields(cred, remoteAuth) {
|
|
131
|
+
const local = cred.data.auth ?? {};
|
|
132
|
+
const changed = [];
|
|
133
|
+
for (const path of IMMUTABLE_FIELDS[local.type] ?? []) {
|
|
134
|
+
const a = get(local, path);
|
|
135
|
+
const b = get(remoteAuth ?? {}, path);
|
|
136
|
+
const differs = path.length === 1 && path[0] === "refresh" ? Boolean(a) !== Boolean(b) : (a ?? null) !== (b ?? null);
|
|
137
|
+
if (differs)
|
|
138
|
+
changed.push(path.join("."));
|
|
139
|
+
}
|
|
140
|
+
return changed;
|
|
141
|
+
}
|
|
142
|
+
// The value at `path` inside `obj`, or undefined if anything on the way isn't an object.
|
|
143
|
+
export const get = (obj, path) => path.reduce((o, k) => (o && typeof o === "object" ? o[k] : undefined), obj);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Readable, Writable } from "node:stream";
|
|
2
|
+
import type Anthropic from "@anthropic-ai/sdk";
|
|
3
|
+
import type { Tool } from "../lib/tools.ts";
|
|
4
|
+
import { type CustomToolResult, type Session, type SessionEvent } from "./session.ts";
|
|
5
|
+
export interface ChatOptions {
|
|
6
|
+
agentName: string;
|
|
7
|
+
tools?: Record<string, Tool>;
|
|
8
|
+
input?: Readable & {
|
|
9
|
+
isTTY?: boolean;
|
|
10
|
+
};
|
|
11
|
+
output?: Writable;
|
|
12
|
+
}
|
|
13
|
+
export declare function formatEvent(event: SessionEvent): string | null;
|
|
14
|
+
export declare function runTool(tool: Tool, input: unknown): Promise<CustomToolResult>;
|
|
15
|
+
export declare function chat(client: Anthropic, session: Pick<Session, "id">, { agentName, tools, input, output }: ChatOptions): Promise<void>;
|