@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.
- package/README.md +11 -5
- package/dist/bin/agentschema.d.ts +2 -0
- package/dist/bin/agentschema.js +333 -0
- package/dist/lib/channels.d.ts +74 -0
- package/dist/lib/channels.js +403 -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 +4 -13
- 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 +127 -0
- package/dist/lib/tools.js +465 -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
|
@@ -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>;
|
package/dist/src/chat.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
import { agentMessageText, textStream } from "../lib/stream.js";
|
|
3
|
+
import { loadTool } from "./custom-tools.js";
|
|
4
|
+
import { Conversation } from "./session.js";
|
|
5
|
+
const color = (code) => (text) => (process.stdout.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text);
|
|
6
|
+
const dim = color(2);
|
|
7
|
+
const red = color(31);
|
|
8
|
+
const bold = color(1);
|
|
9
|
+
// Prints a session's events as a terminal transcript.
|
|
10
|
+
export function formatEvent(event) {
|
|
11
|
+
switch (event.type) {
|
|
12
|
+
case "agent.message":
|
|
13
|
+
return agentMessageText(event);
|
|
14
|
+
case "agent.tool_use":
|
|
15
|
+
case "agent.mcp_tool_use": {
|
|
16
|
+
const name = event.type === "agent.mcp_tool_use" ? `${event.mcp_server_name}.${event.name}` : event.name;
|
|
17
|
+
const denied = event.evaluated_permission === "deny" ? red(" (denied)") : "";
|
|
18
|
+
return dim(`· ${name} ${summarize(event.input)}`) + denied;
|
|
19
|
+
}
|
|
20
|
+
case "agent.custom_tool_use":
|
|
21
|
+
return dim(`· ${event.name} ${summarize(event.input)}`);
|
|
22
|
+
case "agent.tool_result":
|
|
23
|
+
case "agent.mcp_tool_result":
|
|
24
|
+
if (!event.is_error)
|
|
25
|
+
return null;
|
|
26
|
+
return red(` ↳ ${firstLine(event.content)}`);
|
|
27
|
+
case "session.error":
|
|
28
|
+
return red(`error: ${event.error?.message ?? event.error?.type ?? "unknown error"}`);
|
|
29
|
+
case "session.status_idle": {
|
|
30
|
+
const reason = event.stop_reason?.type;
|
|
31
|
+
if (reason === "retries_exhausted")
|
|
32
|
+
return red("The agent gave up after repeated errors.");
|
|
33
|
+
if (reason === "budget_reached")
|
|
34
|
+
return red("The session reached its budget and paused.");
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
case "session.status_terminated":
|
|
38
|
+
return dim("The session has ended.");
|
|
39
|
+
default:
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// One line describing a tool call's input: the command, path or query when there is one.
|
|
44
|
+
function summarize(input = {}) {
|
|
45
|
+
for (const key of ["command", "file_path", "path", "pattern", "url", "query"]) {
|
|
46
|
+
if (typeof input[key] === "string")
|
|
47
|
+
return truncate(input[key]);
|
|
48
|
+
}
|
|
49
|
+
return truncate(JSON.stringify(input));
|
|
50
|
+
}
|
|
51
|
+
function firstLine(content = []) {
|
|
52
|
+
const text = content.find((b) => b.type === "text")?.text ?? "tool error";
|
|
53
|
+
return truncate(text.split("\n")[0]);
|
|
54
|
+
}
|
|
55
|
+
const truncate = (s, n = 100) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
56
|
+
// Runs a custom tool's code with the call's input. A thrown error is returned as an error
|
|
57
|
+
// result, so the agent sees what went wrong.
|
|
58
|
+
export async function runTool(tool, input) {
|
|
59
|
+
try {
|
|
60
|
+
const value = await loadTool(tool)(input);
|
|
61
|
+
return { text: typeof value === "string" ? value : (JSON.stringify(value) ?? "") };
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
return { text: `Error: ${err?.message ?? err}`, isError: true };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
// Runs an interactive chat in the terminal until the user quits or the session ends.
|
|
68
|
+
// `tools` maps custom tool names to their tools/ files; their code runs here when called.
|
|
69
|
+
export async function chat(client, session, { agentName, tools = {}, input = process.stdin, output = process.stdout }) {
|
|
70
|
+
const rl = createInterface({ input, output, terminal: input.isTTY });
|
|
71
|
+
const lines = rl[Symbol.asyncIterator]();
|
|
72
|
+
let running = false;
|
|
73
|
+
let interrupted = false;
|
|
74
|
+
let quit = false;
|
|
75
|
+
const ask = async (prompt) => {
|
|
76
|
+
output.write(prompt);
|
|
77
|
+
const { value, done } = await lines.next();
|
|
78
|
+
if (done)
|
|
79
|
+
quit = true;
|
|
80
|
+
return done ? null : value;
|
|
81
|
+
};
|
|
82
|
+
const stream = textStream((text) => output.write(text));
|
|
83
|
+
const ui = {
|
|
84
|
+
event(event) {
|
|
85
|
+
if (stream.handle(event))
|
|
86
|
+
return;
|
|
87
|
+
const text = formatEvent(event);
|
|
88
|
+
if (text)
|
|
89
|
+
output.write(`${text}\n`);
|
|
90
|
+
},
|
|
91
|
+
async confirm(event) {
|
|
92
|
+
const answer = await ask(bold(`Allow ${event.name}? `) + dim("[y/N, or type why not] "));
|
|
93
|
+
if (answer && /^(y|yes)$/i.test(answer.trim()))
|
|
94
|
+
return { result: "allow" };
|
|
95
|
+
const reason = answer?.trim();
|
|
96
|
+
return { result: "deny", deny_message: reason && !/^(n|no)$/i.test(reason) ? reason : undefined };
|
|
97
|
+
},
|
|
98
|
+
async customToolResult(event) {
|
|
99
|
+
if (tools[event.name]) {
|
|
100
|
+
const result = await runTool(tools[event.name], event.input);
|
|
101
|
+
if (result.isError)
|
|
102
|
+
output.write(`${red(` ↳ ${truncate(result.text.split("\n")[0])}`)}\n`);
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
output.write(dim(`${event.name} is a custom tool, so you supply its result.\n`));
|
|
106
|
+
output.write(dim(`input: ${JSON.stringify(event.input)}\n`));
|
|
107
|
+
return (await ask(bold("result> "))) ?? "The user didn't provide a result.";
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
const conversation = new Conversation(client, session.id, ui);
|
|
111
|
+
let ended = false;
|
|
112
|
+
// Ctrl+C interrupts the agent while it works; a second Ctrl+C, or one at the prompt, quits.
|
|
113
|
+
rl.on("SIGINT", () => {
|
|
114
|
+
if (running && !interrupted) {
|
|
115
|
+
interrupted = true;
|
|
116
|
+
output.write(dim("\nInterrupting… (Ctrl+C again to quit)\n"));
|
|
117
|
+
conversation.interrupt().catch(() => { });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
quit = true;
|
|
121
|
+
conversation.close();
|
|
122
|
+
rl.close();
|
|
123
|
+
});
|
|
124
|
+
output.write(dim(`${agentName} · session ${session.id}\nCtrl+C interrupts the agent, Ctrl+D quits.\n\n`));
|
|
125
|
+
try {
|
|
126
|
+
while (!quit) {
|
|
127
|
+
const text = await ask(bold("> "));
|
|
128
|
+
if (text === null)
|
|
129
|
+
break;
|
|
130
|
+
if (text.trim() === "")
|
|
131
|
+
continue;
|
|
132
|
+
running = true;
|
|
133
|
+
interrupted = false;
|
|
134
|
+
let outcome;
|
|
135
|
+
try {
|
|
136
|
+
outcome = await conversation.send(text);
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
if (quit)
|
|
140
|
+
break;
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
running = false;
|
|
145
|
+
}
|
|
146
|
+
output.write("\n");
|
|
147
|
+
if (outcome === "terminated") {
|
|
148
|
+
ended = true;
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
conversation.close();
|
|
155
|
+
rl.close();
|
|
156
|
+
}
|
|
157
|
+
if (!ended)
|
|
158
|
+
output.write(dim(`Resume this conversation with: agentschema run --resume ${session.id}\n`));
|
|
159
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { checkFiles } from "../lib/check.js";
|
|
3
|
+
import { folderProblem, readFolder } from "./folder.js";
|
|
4
|
+
// Validates an agent folder without calling the API. See checkFiles for what it returns.
|
|
5
|
+
export function check(dir, options) {
|
|
6
|
+
const problem = folderProblem(dir);
|
|
7
|
+
if (problem)
|
|
8
|
+
return { errors: [problem], warnings: [], instance: null };
|
|
9
|
+
const result = checkFiles(readFolder(dir), options);
|
|
10
|
+
// Where each tool's code lives, so its require() calls can resolve from there.
|
|
11
|
+
for (const tool of result.instance?.tools ?? [])
|
|
12
|
+
tool.path = resolve(dir, tool.file);
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type Anthropic from "@anthropic-ai/sdk";
|
|
2
|
+
import type { BetaManagedAgentsCredential } from "@anthropic-ai/sdk/resources/beta/vaults/credentials";
|
|
3
|
+
import { type Log } from "./deploy.ts";
|
|
4
|
+
import type { Prompts } from "./prompts.ts";
|
|
5
|
+
type Fetch = typeof globalThis.fetch;
|
|
6
|
+
export interface CredMenuOptions {
|
|
7
|
+
io: Prompts;
|
|
8
|
+
client: Anthropic;
|
|
9
|
+
openBrowser: (url: string) => void;
|
|
10
|
+
port?: number | string;
|
|
11
|
+
fetch?: Fetch;
|
|
12
|
+
log?: Log;
|
|
13
|
+
}
|
|
14
|
+
export declare function credCreate(dir: string | undefined, options: CredMenuOptions): Promise<BetaManagedAgentsCredential | null>;
|
|
15
|
+
export declare function credDeploy(file: string, options: CredMenuOptions): Promise<BetaManagedAgentsCredential>;
|
|
16
|
+
export declare function serviceName(url: string): string;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { stringify } from "yaml";
|
|
4
|
+
import { check } from "./check.js";
|
|
5
|
+
import { credLogin, credPaste, locate } from "./cred.js";
|
|
6
|
+
import { DeployError } from "./deploy.js";
|
|
7
|
+
import { discover } from "./oauth.js";
|
|
8
|
+
import { ENV_VAR, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE } from "../lib/vaults.js";
|
|
9
|
+
const SIGN_IN = "Sign in with the browser";
|
|
10
|
+
const PASTE = "Paste the tokens";
|
|
11
|
+
const PASTE_VALUE = "Paste the value";
|
|
12
|
+
const LATER = "Just write the file";
|
|
13
|
+
const NEW_VAULT = "New vault…";
|
|
14
|
+
const OTHER_URL = "Another URL…";
|
|
15
|
+
const FOR_MCP = "An MCP server's sign-in (OAuth)";
|
|
16
|
+
const FOR_ENV_VAR = "An environment variable (an API key, say)";
|
|
17
|
+
const HEADERS_ONLY = "Request headers only";
|
|
18
|
+
const HEADERS_AND_BODY = "Headers and body";
|
|
19
|
+
// `cred create`: asks which vault the credential goes in and what it's for, writes its file,
|
|
20
|
+
// then gets its secrets and creates it, unless you'd rather do that later with `cred deploy`.
|
|
21
|
+
export async function credCreate(dir = ".", options) {
|
|
22
|
+
const { io, fetch = globalThis.fetch, log = () => { } } = options;
|
|
23
|
+
if (dir.endsWith(".md")) {
|
|
24
|
+
throw new DeployError(`cred create takes the agent folder; to create the credential ${dir} describes, run agentschema cred deploy ${dir}`);
|
|
25
|
+
}
|
|
26
|
+
const { file, method } = await writeCredentialFile(dir, { io, fetch, log });
|
|
27
|
+
if (method === LATER) {
|
|
28
|
+
log(`\nCreate the credential in Anthropic when you're ready with:\n agentschema cred deploy ${file}`);
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
return getTokens(file, method, options);
|
|
32
|
+
}
|
|
33
|
+
// `cred deploy`: creates the credential a file describes in Anthropic, asking whether to sign
|
|
34
|
+
// in for its tokens or paste them.
|
|
35
|
+
export async function credDeploy(file, options) {
|
|
36
|
+
if (!existsSync(file))
|
|
37
|
+
throw new DeployError(`${file}: no such file; to write a new credential file, run agentschema cred create`);
|
|
38
|
+
const { cred } = locate(file);
|
|
39
|
+
// An environment variable has no sign-in, so there's only its value to ask for.
|
|
40
|
+
const method = cred.data.auth.type === ENV_VAR ? PASTE : await options.io.select("How do you want to get its tokens?", [SIGN_IN, PASTE], SIGN_IN);
|
|
41
|
+
return getTokens(file, method, options);
|
|
42
|
+
}
|
|
43
|
+
// Tokens come from signing in (`cred login`) or from pasting them (`credPaste`).
|
|
44
|
+
function getTokens(file, method, { client, io, openBrowser, port = 0, fetch = globalThis.fetch, log = () => { } }) {
|
|
45
|
+
const ask = (question, { secret }) => (secret ? io.secret(question.trim()) : io.text(question.trim()));
|
|
46
|
+
return method === SIGN_IN
|
|
47
|
+
? credLogin(file, { client, ask, openBrowser, port, fetch, log })
|
|
48
|
+
: credPaste(file, { client, ask, log });
|
|
49
|
+
}
|
|
50
|
+
// Asks about the credential, and writes vaults/<vault>/<name>.md. Returns { file, method }.
|
|
51
|
+
async function writeCredentialFile(dir, { io, fetch, log }) {
|
|
52
|
+
const { errors, instance } = check(dir);
|
|
53
|
+
if (!instance)
|
|
54
|
+
throw new DeployError(`${dir} isn't an agent folder:\n ${errors.join("\n ")}`);
|
|
55
|
+
if (errors.length > 0)
|
|
56
|
+
throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
|
|
57
|
+
// The vault: an existing one, or a new folder.
|
|
58
|
+
const names = instance.vaults.map((v) => v.name);
|
|
59
|
+
let vaultName = names.length > 0 ? await io.select("Which vault?", [...names, NEW_VAULT], names[0]) : NEW_VAULT;
|
|
60
|
+
if (vaultName === NEW_VAULT) {
|
|
61
|
+
vaultName = await io.text("New vault's name?", names.includes("Shared") ? "" : "Shared", {
|
|
62
|
+
validate: (name) => fileName(name, "vault") ?? (names.includes(name) ? `There's already a vault called ${name}` : null),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const vault = instance.vaults.find((v) => v.name === vaultName);
|
|
66
|
+
const vaultDir = join(dir, VAULTS_DIR, vaultName);
|
|
67
|
+
const kind = await io.select("What is it for?", [FOR_MCP, FOR_ENV_VAR], FOR_MCP);
|
|
68
|
+
const { name, auth, method } = kind === FOR_ENV_VAR
|
|
69
|
+
? await envVarCredential({ io, vault, vaultName, vaultDir })
|
|
70
|
+
: await mcpCredential({ io, instance, vault, vaultName, vaultDir, fetch, log });
|
|
71
|
+
mkdirSync(vaultDir, { recursive: true });
|
|
72
|
+
const file = join(vaultDir, `${name}.md`);
|
|
73
|
+
writeFileSync(file, `---\n${stringify({ auth })}---\n`);
|
|
74
|
+
log(`Wrote ${file}`);
|
|
75
|
+
const rel = `${VAULTS_DIR}/${vaultName}/${name}.md`;
|
|
76
|
+
for (const warning of check(dir).warnings.filter((w) => w.startsWith(rel)))
|
|
77
|
+
log(`warning: ${warning}`);
|
|
78
|
+
return { file, method };
|
|
79
|
+
}
|
|
80
|
+
// An environment variable: its name, the hosts that may receive it, and where it can appear.
|
|
81
|
+
async function envVarCredential({ io, vault, vaultName, vaultDir }) {
|
|
82
|
+
const taken = new Set(vault?.credentials.map((c) => c.data.auth?.secret_name) ?? []);
|
|
83
|
+
const secretName = await io.text("Variable name? (like STRIPE_API_KEY)", "", {
|
|
84
|
+
validate: (n) => {
|
|
85
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))
|
|
86
|
+
return "Use letters, digits and _, not starting with a digit";
|
|
87
|
+
return taken.has(n) ? `${vaultName} already sets ${n}` : null;
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
const hosts = await io.text("Which hosts may it be sent to? (like api.stripe.com; separate several with spaces)", "", {
|
|
91
|
+
validate: (h) => {
|
|
92
|
+
const list = h.split(/[\s,]+/).filter(Boolean);
|
|
93
|
+
if (list.length === 0)
|
|
94
|
+
return "List at least one host";
|
|
95
|
+
return list.some((x) => x.includes("/")) ? "Enter host names, without https:// or a path" : null;
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
const where = await io.select("Where in a request can it appear?", [HEADERS_ONLY, HEADERS_AND_BODY], HEADERS_ONLY);
|
|
99
|
+
const name = await io.text("Credential name?", secretName, {
|
|
100
|
+
validate: (n) => fileName(n, "credential") ?? (existsSync(join(vaultDir, `${n}.md`)) ? `${vaultName}/${n}.md already exists` : null),
|
|
101
|
+
});
|
|
102
|
+
const method = await io.select("How do you want to set its value?", [PASTE_VALUE, LATER], PASTE_VALUE);
|
|
103
|
+
return {
|
|
104
|
+
name,
|
|
105
|
+
method: method === PASTE_VALUE ? PASTE : LATER,
|
|
106
|
+
auth: {
|
|
107
|
+
type: ENV_VAR,
|
|
108
|
+
secret_name: secretName,
|
|
109
|
+
networking: { type: "limited", allowed_hosts: hosts.split(/[\s,]+/).filter(Boolean) },
|
|
110
|
+
injection_location: { header: true, body: where === HEADERS_AND_BODY },
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
// An MCP server's sign-in: the server, a name, and how its tokens will be fetched.
|
|
115
|
+
async function mcpCredential({ io, instance, vault, vaultName, vaultDir, fetch, log, }) {
|
|
116
|
+
const taken = new Set(vault?.credentials.map((c) => c.data.auth?.mcp_server_url) ?? []);
|
|
117
|
+
// The MCP server: one agent.md declares, or any URL.
|
|
118
|
+
const declared = instance.agent.data.mcp_servers ?? [];
|
|
119
|
+
const servers = declared.filter((s) => typeof s?.url === "string" && !taken.has(s.url));
|
|
120
|
+
const label = (s) => `${s.name ?? s.url} (${s.url})`;
|
|
121
|
+
let url = OTHER_URL;
|
|
122
|
+
if (servers.length > 0) {
|
|
123
|
+
const picked = await io.select("Which MCP server is it for?", [...servers.map(label), OTHER_URL], label(servers[0]));
|
|
124
|
+
url = servers.find((s) => label(s) === picked)?.url ?? OTHER_URL;
|
|
125
|
+
}
|
|
126
|
+
if (url === OTHER_URL) {
|
|
127
|
+
url = await io.text("MCP server URL?", "", {
|
|
128
|
+
validate: (u) => (!/^https?:\/\/\S+$/.test(u) ? "Enter an http(s) URL" : taken.has(u) ? `${vaultName} already has a credential for ${u}` : null),
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const suggested = servers.find((s) => s.url === url)?.name ?? serviceName(url);
|
|
132
|
+
const name = await io.text("Credential name?", suggested, {
|
|
133
|
+
validate: (n) => fileName(n, "credential") ?? (existsSync(join(vaultDir, `${n}.md`)) ? `${vaultName}/${n}.md already exists` : null),
|
|
134
|
+
});
|
|
135
|
+
// How its tokens will be fetched decides what the file needs.
|
|
136
|
+
log(`Looking up the sign-in for ${url}…`);
|
|
137
|
+
const server = await discover(url, { fetch }).catch(() => null);
|
|
138
|
+
if (!server)
|
|
139
|
+
log("It doesn't publish an OAuth sign-in, so you'll paste its tokens.");
|
|
140
|
+
const method = await io.select("How do you want to get its tokens?", server ? [SIGN_IN, PASTE, LATER] : [PASTE, LATER], server ? SIGN_IN : PASTE);
|
|
141
|
+
const auth = { type: "mcp_oauth", mcp_server_url: url };
|
|
142
|
+
if (server && method !== PASTE) {
|
|
143
|
+
// Signing in registers agentschema as a client where the server allows it; elsewhere, it
|
|
144
|
+
// needs your own OAuth client.
|
|
145
|
+
if (!server.registrationEndpoint) {
|
|
146
|
+
log(`${server.issuer} doesn't let apps register themselves, so sign-in needs your own OAuth client.`);
|
|
147
|
+
log("Create one with the provider, allowing the redirect URI http://127.0.0.1:<port>/callback.");
|
|
148
|
+
auth.refresh = await refreshBlock(io, server, { tokenEndpoint: server.tokenEndpoint });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
else if (method === PASTE && (await io.confirm("Can the access token be refreshed? (needs a refresh token and the OAuth client's details)", Boolean(server)))) {
|
|
152
|
+
auth.refresh = await refreshBlock(io, server, {});
|
|
153
|
+
}
|
|
154
|
+
return { name, auth, method };
|
|
155
|
+
}
|
|
156
|
+
// The client details for the file's auth.refresh block.
|
|
157
|
+
async function refreshBlock(io, server, { tokenEndpoint }) {
|
|
158
|
+
const refresh = {}; // filled in below, in the order the file lists them
|
|
159
|
+
refresh.token_endpoint = tokenEndpoint ?? (await io.text("Token endpoint?", server?.tokenEndpoint ?? "", {
|
|
160
|
+
validate: (u) => (/^https?:\/\/\S+$/.test(u) ? null : "Enter an http(s) URL"),
|
|
161
|
+
}));
|
|
162
|
+
refresh.client_id = await io.text("OAuth client ID?", "", { validate: (id) => (id ? null : "The client ID is required") });
|
|
163
|
+
const supported = server?.scopesSupported ?? [];
|
|
164
|
+
const hint = supported.length > 0 ? ` (supported: ${supported.slice(0, 6).join(" ")}${supported.length > 6 ? " …" : ""})` : "";
|
|
165
|
+
const scope = await io.text(`Scopes, separated by spaces${hint}?`, "");
|
|
166
|
+
if (scope)
|
|
167
|
+
refresh.scope = scope;
|
|
168
|
+
const type = await io.select("How does the client authenticate to the token endpoint?", TOKEN_ENDPOINT_AUTH, "client_secret_post");
|
|
169
|
+
refresh.token_endpoint_auth = { type };
|
|
170
|
+
return refresh;
|
|
171
|
+
}
|
|
172
|
+
// Why a vault or credential name can't be a file name, or nothing when it can.
|
|
173
|
+
function fileName(name, what) {
|
|
174
|
+
if (!name)
|
|
175
|
+
return `The ${what} needs a name`;
|
|
176
|
+
if (/[/\\]/.test(name) || name.startsWith("."))
|
|
177
|
+
return `A ${what} name can't contain / or start with .`;
|
|
178
|
+
if (what === "credential" && `${name}.md` === VAULT_FILE)
|
|
179
|
+
return "vault is reserved for vault.md";
|
|
180
|
+
if (name.length > 255)
|
|
181
|
+
return `A ${what} name can be at most 255 characters`;
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
// "Linear" for https://mcp.linear.app/mcp: the host's main label, capitalized.
|
|
185
|
+
export function serviceName(url) {
|
|
186
|
+
const labels = new URL(url).hostname.split(".").filter((l) => !["mcp", "api", "www"].includes(l));
|
|
187
|
+
let main = labels.length >= 2 ? labels[labels.length - 2] : (labels[0] ?? "credential");
|
|
188
|
+
// A cloud's shared domain names the cloud, not the service: calendarmcp.googleapis.com.
|
|
189
|
+
if (["googleapis", "amazonaws", "azure", "azurewebsites", "cloudflare", "workers"].includes(main) && labels.length > 2) {
|
|
190
|
+
main = labels[0].replace(/-?mcp$/, "") || main;
|
|
191
|
+
}
|
|
192
|
+
return main.replace(/^./, (c) => c.toUpperCase());
|
|
193
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
2
|
+
import type { BetaManagedAgentsCredential } from "@anthropic-ai/sdk/resources/beta/vaults/credentials";
|
|
3
|
+
import { type Log, type PreparedLock, type SaveLock } from "./deploy.ts";
|
|
4
|
+
import { type Credential, type CredentialSecrets, type Vault } from "../lib/vaults.ts";
|
|
5
|
+
export type Ask = (question: string, options: {
|
|
6
|
+
secret: boolean;
|
|
7
|
+
}) => Promise<string>;
|
|
8
|
+
export type Secrets = {
|
|
9
|
+
[K in keyof CredentialSecrets]?: CredentialSecrets[K] | null;
|
|
10
|
+
};
|
|
11
|
+
export interface Located {
|
|
12
|
+
dir: string;
|
|
13
|
+
vault: Vault;
|
|
14
|
+
cred: Credential;
|
|
15
|
+
}
|
|
16
|
+
export interface CredPasteOptions {
|
|
17
|
+
client: Anthropic;
|
|
18
|
+
ask: Ask;
|
|
19
|
+
log?: Log;
|
|
20
|
+
}
|
|
21
|
+
export interface CreateCredentialOptions {
|
|
22
|
+
lock: PreparedLock;
|
|
23
|
+
vault: Pick<Vault, "name" | "path" | "file">;
|
|
24
|
+
cred: Credential;
|
|
25
|
+
secrets: Secrets;
|
|
26
|
+
client: Anthropic;
|
|
27
|
+
saveLock?: SaveLock;
|
|
28
|
+
log?: Log;
|
|
29
|
+
}
|
|
30
|
+
export interface CredLoginOptions {
|
|
31
|
+
client: Anthropic;
|
|
32
|
+
ask: Ask;
|
|
33
|
+
openBrowser: (url: string) => void;
|
|
34
|
+
port?: number | string;
|
|
35
|
+
fetch?: typeof globalThis.fetch;
|
|
36
|
+
log?: Log;
|
|
37
|
+
}
|
|
38
|
+
export interface CredDeleteOptions {
|
|
39
|
+
client: Anthropic;
|
|
40
|
+
confirm: (question: string) => Promise<boolean>;
|
|
41
|
+
log?: Log;
|
|
42
|
+
}
|
|
43
|
+
export interface DeleteCredentialOptions {
|
|
44
|
+
lock: PreparedLock;
|
|
45
|
+
cred: Pick<Credential, "file">;
|
|
46
|
+
client: Anthropic;
|
|
47
|
+
saveLock?: SaveLock;
|
|
48
|
+
}
|
|
49
|
+
export declare function locate(path: string): Located;
|
|
50
|
+
export declare function credPaste(path: string, { client, ask, log }: CredPasteOptions): Promise<BetaManagedAgentsCredential>;
|
|
51
|
+
export declare function createCredential({ lock, vault, cred, secrets, client, saveLock, log, }: CreateCredentialOptions): Promise<BetaManagedAgentsCredential>;
|
|
52
|
+
export declare function credLogin(path: string, { client, ask, openBrowser, port, fetch, log }: CredLoginOptions): Promise<BetaManagedAgentsCredential>;
|
|
53
|
+
export declare function credDelete(path: string, { client, confirm, log }: CredDeleteOptions): Promise<void>;
|
|
54
|
+
export declare function deleteCredential({ lock, cred, client, saveLock }: DeleteCredentialOptions): Promise<void>;
|