@soft-boy/agentschema 0.2.1 → 0.2.2
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 +145 -14
- package/bin/agentschema.js +131 -15
- package/package.json +3 -2
- package/src/chat.js +50 -0
- package/src/check.js +212 -4
- package/src/cred-menu.js +197 -0
- package/src/cred.js +243 -0
- package/src/deploy.js +123 -14
- package/src/init.js +7 -104
- package/src/markdown.js +10 -0
- package/src/mcp.js +57 -0
- package/src/oauth.js +192 -0
- package/src/prompts.js +159 -0
- package/src/session.js +30 -3
- package/src/tools-menu.js +171 -0
- package/src/tools.js +61 -17
- package/src/vaults.js +148 -0
package/src/cred.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { basename, dirname, relative, resolve, sep } from "node:path";
|
|
2
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
3
|
+
import { check } from "./check.js";
|
|
4
|
+
import { DeployError, call, openLock, retrieve } from "./deploy.js";
|
|
5
|
+
import { LOCK_FILE, hashBody, writeLock } from "./lock.js";
|
|
6
|
+
import { updateFrontmatter } from "./markdown.js";
|
|
7
|
+
import { authorizationRequest, discover, exchangeCode, registerClient, startCallbackServer } from "./oauth.js";
|
|
8
|
+
import {
|
|
9
|
+
ENV_VAR, VAULTS_DIR, VAULT_FILE, changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings,
|
|
10
|
+
secretsNeeded, vaultBody, vaultKey,
|
|
11
|
+
} from "./vaults.js";
|
|
12
|
+
|
|
13
|
+
// Finds the agent folder and the credential a path like my-agent/vaults/Ops/slack.md names.
|
|
14
|
+
export function locate(path) {
|
|
15
|
+
const file = resolve(path);
|
|
16
|
+
const vaultDir = dirname(file);
|
|
17
|
+
const dir = dirname(dirname(vaultDir));
|
|
18
|
+
if (basename(dirname(vaultDir)) !== VAULTS_DIR || !file.endsWith(".md") || basename(file) === VAULT_FILE) {
|
|
19
|
+
throw new DeployError(`${path}: not a credential file; expected a path like my-agent/${VAULTS_DIR}/<vault>/<credential>.md`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const { errors, instance } = check(dir);
|
|
23
|
+
if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
|
|
24
|
+
const rel = relative(dir, file).split(sep).join("/");
|
|
25
|
+
const vault = instance.vaults.find((v) => v.name === basename(vaultDir));
|
|
26
|
+
const cred = vault?.credentials.find((c) => c.file === rel);
|
|
27
|
+
if (!cred) throw new DeployError(`${path}: no such credential file`);
|
|
28
|
+
return { dir, vault, cred };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Creates the credential a file describes from the secrets you paste, asking for them with
|
|
32
|
+
// `ask(question, { secret })`. The secrets go straight to the vault and are never written to
|
|
33
|
+
// disk. Creates the vault first if it hasn't been deployed.
|
|
34
|
+
export async function credPaste(path, { client, ask, log = () => {} }) {
|
|
35
|
+
const { dir, vault, cred } = locate(path);
|
|
36
|
+
const lock = openLock(dir, client);
|
|
37
|
+
const vaultEntry = lock.resources[vaultKey(vault)];
|
|
38
|
+
const existing = lock.resources[credentialKey(cred)];
|
|
39
|
+
if (existing && existing.vault_id === vaultEntry?.id) {
|
|
40
|
+
throw new DeployError(
|
|
41
|
+
`${cred.file} was already created (${existing.id}). To replace its secrets, delete it with ` +
|
|
42
|
+
`\`agentschema cred delete ${path}\` and create it again.`,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const needs = secretsNeeded(cred);
|
|
47
|
+
const required = async (question) => {
|
|
48
|
+
const answer = (await ask(question, { secret: true })).trim();
|
|
49
|
+
if (!answer) throw new DeployError(`${question.replace(/:\s*$/, "")} is required`);
|
|
50
|
+
return answer;
|
|
51
|
+
};
|
|
52
|
+
if (cred.data.auth.type === ENV_VAR) {
|
|
53
|
+
const secretValue = await required(`Value of ${cred.data.auth.secret_name}: `);
|
|
54
|
+
return createCredential({ dir, lock, vault, cred }, { secretValue }, { client, log });
|
|
55
|
+
}
|
|
56
|
+
const secrets = { accessToken: await required("Access token: ") };
|
|
57
|
+
const expiresAt = (await ask("Access token expires at (ISO 8601, e.g. 2026-12-31T23:59:59Z; blank if unknown): ", { secret: false })).trim();
|
|
58
|
+
if (expiresAt) {
|
|
59
|
+
if (Number.isNaN(Date.parse(expiresAt))) throw new DeployError(`"${expiresAt}" isn't a date and time`);
|
|
60
|
+
secrets.expiresAt = new Date(expiresAt).toISOString();
|
|
61
|
+
}
|
|
62
|
+
if (needs.refreshToken) secrets.refreshToken = await required("Refresh token: ");
|
|
63
|
+
if (needs.clientSecret) secrets.clientSecret = await required("Client secret: ");
|
|
64
|
+
|
|
65
|
+
return createCredential({ dir, lock, vault, cred }, secrets, { client, log });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Creates a credential with its secrets, creating its vault first if needed, records it in the
|
|
69
|
+
// lock, and asks the API to try it.
|
|
70
|
+
async function createCredential({ dir, lock, vault, cred }, secrets, { client, log }) {
|
|
71
|
+
let vaultId = lock.resources[vaultKey(vault)]?.id;
|
|
72
|
+
if (!vaultId) {
|
|
73
|
+
const body = vaultBody(vault);
|
|
74
|
+
const created = await call({ file: vault.path, kind: "vault" }, () => client.beta.vaults.create(body));
|
|
75
|
+
vaultId = created.id;
|
|
76
|
+
lock.resources[vaultKey(vault)] = { kind: "vault", id: vaultId, hash: hashBody(body) };
|
|
77
|
+
writeLock(dir, lock);
|
|
78
|
+
log(`created vault ${vaultId}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const created = await call({ file: cred.file, kind: "credential" }, () =>
|
|
82
|
+
client.beta.vaults.credentials.create(vaultId, credentialCreateBody(cred, secrets)),
|
|
83
|
+
);
|
|
84
|
+
lock.resources[credentialKey(cred)] = { kind: "credential", id: created.id, vault_id: vaultId, hash: hashBody(credentialSettings(cred)) };
|
|
85
|
+
writeLock(dir, lock);
|
|
86
|
+
log(`created credential ${created.id}`);
|
|
87
|
+
|
|
88
|
+
if (cred.data.auth.type === ENV_VAR) return created;
|
|
89
|
+
|
|
90
|
+
// Best effort: ask the API to try the credential against the MCP server.
|
|
91
|
+
try {
|
|
92
|
+
const validation = await client.beta.vaults.credentials.mcpOAuthValidate(created.id, { vault_id: vaultId });
|
|
93
|
+
if (validation.status === "valid") log("checked the MCP server accepted the credential");
|
|
94
|
+
else log(`warning: the API couldn't confirm the credential works (${validation.status}); check the tokens`);
|
|
95
|
+
} catch {
|
|
96
|
+
// Validation is only a convenience; the credential exists either way.
|
|
97
|
+
}
|
|
98
|
+
return created;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Signs in to the credential's MCP server in the browser, then creates the credential with the
|
|
102
|
+
// tokens, or replaces the tokens of the one that exists. Endpoints come from the server's OAuth
|
|
103
|
+
// metadata. The OAuth client is the file's `auth.refresh.client_id`; without a refresh block,
|
|
104
|
+
// agentschema registers itself as a client, if the server allows it, and writes the refresh
|
|
105
|
+
// block into the file. Tokens go straight to the vault and are never written to disk.
|
|
106
|
+
export async function credLogin(path, { client, ask, openBrowser, port = 0, fetch = globalThis.fetch, log = () => {} }) {
|
|
107
|
+
let located = locate(path);
|
|
108
|
+
const { auth } = located.cred.data;
|
|
109
|
+
if (auth.type === ENV_VAR) {
|
|
110
|
+
throw new DeployError(`${located.cred.file} is an environment variable, so there's nothing to sign in to; set its value with agentschema cred deploy ${path}`);
|
|
111
|
+
}
|
|
112
|
+
let refresh = auth.refresh ?? null;
|
|
113
|
+
|
|
114
|
+
log(`Looking up the sign-in for ${auth.mcp_server_url}…`);
|
|
115
|
+
const server = await discover(auth.mcp_server_url, { fetch });
|
|
116
|
+
if (server.codeChallengeMethods && !server.codeChallengeMethods.includes("S256")) {
|
|
117
|
+
throw new DeployError(`${server.issuer} doesn't support PKCE with S256, which agentschema needs to sign in`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const callback = await startCallbackServer(Number(port));
|
|
121
|
+
try {
|
|
122
|
+
let clientId, clientSecret = null, authMethod, tokenEndpoint;
|
|
123
|
+
if (refresh) {
|
|
124
|
+
({ client_id: clientId, token_endpoint: tokenEndpoint } = refresh);
|
|
125
|
+
authMethod = refresh.token_endpoint_auth.type;
|
|
126
|
+
if (authMethod !== "none") clientSecret = await required(ask, "Client secret: ");
|
|
127
|
+
} else if (server.registrationEndpoint) {
|
|
128
|
+
({ clientId, clientSecret, authMethod } = await registerClient(server.registrationEndpoint, callback.redirectUri, { fetch }));
|
|
129
|
+
tokenEndpoint = server.tokenEndpoint;
|
|
130
|
+
log(`Registered agentschema as an OAuth client (${clientId}).`);
|
|
131
|
+
} else {
|
|
132
|
+
throw new DeployError(noClientMessage(located.cred, server, callback.redirectUri));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const resource = refresh ? (refresh.resource ?? null) : (server.resource ?? auth.mcp_server_url);
|
|
136
|
+
const request = authorizationRequest({
|
|
137
|
+
authorizationEndpoint: server.authorizationEndpoint,
|
|
138
|
+
issuer: server.issuer,
|
|
139
|
+
clientId,
|
|
140
|
+
redirectUri: callback.redirectUri,
|
|
141
|
+
scope: refresh?.scope,
|
|
142
|
+
resource,
|
|
143
|
+
});
|
|
144
|
+
log(`Opening your browser to sign in. If it doesn't open, go to:\n ${request.url}`);
|
|
145
|
+
openBrowser(request.url);
|
|
146
|
+
const code = await callback.waitForCode(request.state);
|
|
147
|
+
const tokens = await exchangeCode(
|
|
148
|
+
{ tokenEndpoint, code, verifier: request.verifier, redirectUri: callback.redirectUri, clientId, clientSecret, authMethod, resource },
|
|
149
|
+
{ fetch },
|
|
150
|
+
);
|
|
151
|
+
if (!tokens.refreshToken) {
|
|
152
|
+
throw new DeployError(
|
|
153
|
+
"the server didn't return a refresh token, so the credential would stop working when the access token expires. Nothing was created.",
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// A client agentschema registered: record it in the file, since it's part of the credential.
|
|
158
|
+
if (!refresh) {
|
|
159
|
+
refresh = { token_endpoint: tokenEndpoint, client_id: clientId };
|
|
160
|
+
if (tokens.scope) refresh.scope = tokens.scope;
|
|
161
|
+
if (resource) refresh.resource = resource;
|
|
162
|
+
refresh.token_endpoint_auth = { type: authMethod };
|
|
163
|
+
updateFrontmatter(resolve(path), (doc) => doc.setIn(["auth", "refresh"], doc.createNode(refresh)));
|
|
164
|
+
log(`Added auth.refresh to ${located.cred.file}.`);
|
|
165
|
+
located = locate(path);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const secrets = { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, refreshToken: tokens.refreshToken, clientSecret };
|
|
169
|
+
const { dir, vault, cred } = located;
|
|
170
|
+
const lock = openLock(dir, client);
|
|
171
|
+
const existing = lock.resources[credentialKey(cred)];
|
|
172
|
+
if (existing && existing.vault_id === lock.resources[vaultKey(vault)]?.id) {
|
|
173
|
+
return replaceTokens({ dir, lock, cred, entry: existing }, secrets, { client, log });
|
|
174
|
+
}
|
|
175
|
+
return createCredential({ dir, lock, vault, cred }, secrets, { client, log });
|
|
176
|
+
} finally {
|
|
177
|
+
await callback.close();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function required(ask, question) {
|
|
182
|
+
const answer = (await ask(question, { secret: true })).trim();
|
|
183
|
+
if (!answer) throw new DeployError(`${question.replace(/:\s*$/, "")} is required`);
|
|
184
|
+
return answer;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Puts the tokens from a new sign-in into an existing credential.
|
|
188
|
+
async function replaceTokens({ cred, entry }, secrets, { client, log }) {
|
|
189
|
+
const step = { file: cred.file, kind: "credential", key: credentialKey(cred), entry };
|
|
190
|
+
const remote = await retrieve(step, () => client.beta.vaults.credentials.retrieve(entry.id, { vault_id: entry.vault_id }));
|
|
191
|
+
const changed = changedImmutableFields(cred, remote.auth);
|
|
192
|
+
if (changed.length > 0) {
|
|
193
|
+
throw new DeployError(
|
|
194
|
+
`${cred.file}: ${changed.map((f) => `\`auth.${f}\``).join(", ")} changed since the credential was created. ` +
|
|
195
|
+
"Delete it with `agentschema cred delete`, then sign in again.",
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
const { auth } = cred.data;
|
|
199
|
+
const body = {
|
|
200
|
+
vault_id: entry.vault_id,
|
|
201
|
+
auth: { type: auth.type, access_token: secrets.accessToken, expires_at: secrets.expiresAt, refresh: { refresh_token: secrets.refreshToken } },
|
|
202
|
+
};
|
|
203
|
+
const method = auth.refresh.token_endpoint_auth.type;
|
|
204
|
+
if (method !== "none") body.auth.refresh.token_endpoint_auth = { type: method, client_secret: secrets.clientSecret };
|
|
205
|
+
const updated = await call(step, () => client.beta.vaults.credentials.update(entry.id, body));
|
|
206
|
+
log(`updated credential ${updated.id} with the new tokens`);
|
|
207
|
+
return updated;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// What to do when the server won't register agentschema: bring your own OAuth client.
|
|
211
|
+
function noClientMessage(cred, server, redirectUri) {
|
|
212
|
+
const scopes = server.scopesSupported.length > 0 ? `\n scope: ${server.scopesSupported[0]} # supported: ${server.scopesSupported.join(" ")}` : "";
|
|
213
|
+
return (
|
|
214
|
+
`${server.issuer} doesn't let apps register themselves, so sign-in needs your own OAuth client. ` +
|
|
215
|
+
`Create one with the provider, allowing the redirect URI ${redirectUri.replace(/:\d+\//, ":<port>/")} ` +
|
|
216
|
+
`(pass the same --port to cred login), then add this to ${cred.file}:\n\n` +
|
|
217
|
+
` refresh:\n token_endpoint: ${server.tokenEndpoint}\n client_id: "…"${scopes}\n token_endpoint_auth:\n type: client_secret_post`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Permanently deletes the credential a file describes and removes it from claude-lock.json.
|
|
222
|
+
// The file itself stays, so `cred deploy` can create it again.
|
|
223
|
+
export async function credDelete(path, { client, confirm, log = () => {} }) {
|
|
224
|
+
const { dir, cred } = locate(path);
|
|
225
|
+
const lock = openLock(dir, client);
|
|
226
|
+
const entry = lock.resources[credentialKey(cred)];
|
|
227
|
+
if (!entry) throw new DeployError(`${cred.file} has no credential in ${LOCK_FILE}; there's nothing to delete`);
|
|
228
|
+
|
|
229
|
+
if (!(await confirm(`Delete credential "${cred.name}" (${entry.id})? Its tokens are gone for good.`))) {
|
|
230
|
+
log("Cancelled.");
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
await client.beta.vaults.credentials.delete(entry.id, { vault_id: entry.vault_id });
|
|
235
|
+
} catch (err) {
|
|
236
|
+
if (!(err instanceof Anthropic.APIError && err.status === 404)) {
|
|
237
|
+
throw new DeployError(`couldn't delete ${entry.id} (${err.status ?? "network error"}): ${err.error?.error?.message ?? err.message}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
delete lock.resources[credentialKey(cred)];
|
|
241
|
+
writeLock(dir, lock);
|
|
242
|
+
log(`deleted credential ${entry.id}`);
|
|
243
|
+
}
|
package/src/deploy.js
CHANGED
|
@@ -1,24 +1,20 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
1
2
|
import Anthropic from "@anthropic-ai/sdk";
|
|
2
3
|
import { check } from "./check.js";
|
|
3
4
|
import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
|
|
4
5
|
import { LOCK_FILE, hashBody, readLock, writeLock } from "./lock.js";
|
|
6
|
+
import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey } from "./vaults.js";
|
|
5
7
|
|
|
6
8
|
export class DeployError extends Error {}
|
|
7
9
|
|
|
8
|
-
// Creates or updates the environment and
|
|
10
|
+
// Creates or updates the environment, agent and vaults a folder defines, recording their IDs
|
|
11
|
+
// in claude-lock.json. Credentials are only updated here: creating one needs its secrets, so
|
|
12
|
+
// that's `cred deploy`'s job.
|
|
9
13
|
// Returns the plan: one { file, kind, action, id, version } entry per resource.
|
|
10
14
|
export async function deploy(dir, { client, dryRun = false, force = false, log = () => {} }) {
|
|
11
15
|
const { errors, instance } = check(dir);
|
|
12
16
|
if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
|
|
13
|
-
|
|
14
|
-
const baseURL = client.baseURL;
|
|
15
|
-
const lock = readLock(dir) ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
|
|
16
|
-
lock.resources ??= {};
|
|
17
|
-
if (lock.origin?.base_url && lock.origin.base_url !== baseURL) {
|
|
18
|
-
throw new DeployError(
|
|
19
|
-
`${LOCK_FILE} was written for ${lock.origin.base_url}, but this client uses ${baseURL}`,
|
|
20
|
-
);
|
|
21
|
-
}
|
|
17
|
+
const lock = openLock(dir, client);
|
|
22
18
|
|
|
23
19
|
const steps = [
|
|
24
20
|
{ file: ENV_FILE, kind: "environment", body: envBody(instance) },
|
|
@@ -53,13 +49,126 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
|
|
|
53
49
|
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}${version}`);
|
|
54
50
|
}
|
|
55
51
|
|
|
56
|
-
|
|
52
|
+
const vaultSteps = await deployVaults(dir, instance.vaults, { client, lock, dryRun, log });
|
|
53
|
+
|
|
54
|
+
return [...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
|
|
57
55
|
file, kind, action,
|
|
58
56
|
id: lock.resources[key]?.id,
|
|
59
57
|
version: lock.resources[key]?.version,
|
|
60
58
|
}));
|
|
61
59
|
}
|
|
62
60
|
|
|
61
|
+
// Reads claude-lock.json, or starts a new one, and checks it was written for this API.
|
|
62
|
+
export function openLock(dir, client) {
|
|
63
|
+
const baseURL = client.baseURL;
|
|
64
|
+
const lock = readLock(dir) ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
|
|
65
|
+
lock.resources ??= {};
|
|
66
|
+
if (lock.origin?.base_url && lock.origin.base_url !== baseURL) {
|
|
67
|
+
throw new DeployError(
|
|
68
|
+
`${LOCK_FILE} was written for ${lock.origin.base_url}, but this client uses ${baseURL}`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return lock;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Creates or updates each vault, then updates the settings of credentials already created.
|
|
75
|
+
// A credential file with no credential yet is reported, not created: that needs its secrets.
|
|
76
|
+
async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
|
|
77
|
+
const steps = [];
|
|
78
|
+
for (const vault of vaults) {
|
|
79
|
+
const step = planStep(lock, { file: vault.path, key: vaultKey(vault), kind: "vault", body: vaultBody(vault) });
|
|
80
|
+
steps.push(step);
|
|
81
|
+
for (const cred of vault.credentials) {
|
|
82
|
+
const credStep = planStep(lock, { file: cred.file, key: credentialKey(cred), kind: "credential", body: credentialSettings(cred) });
|
|
83
|
+
credStep.cred = cred;
|
|
84
|
+
credStep.vaultStep = step;
|
|
85
|
+
// A credential belongs to the vault it was created in; if that vault was replaced, it's gone.
|
|
86
|
+
if (credStep.entry && credStep.entry.vault_id !== step.entry?.id) credStep.entry = undefined;
|
|
87
|
+
if (!credStep.entry) credStep.action = "missing";
|
|
88
|
+
steps.push(credStep);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Check every credential update first, so an immutable field changed in one file stops the
|
|
93
|
+
// deploy before anything is sent.
|
|
94
|
+
if (!dryRun) {
|
|
95
|
+
for (const step of steps.filter((s) => s.kind === "credential" && s.action === "update")) {
|
|
96
|
+
const remote = await retrieve(step, () => client.beta.vaults.credentials.retrieve(step.entry.id, { vault_id: step.entry.vault_id }));
|
|
97
|
+
const changed = changedImmutableFields(step.cred, remote.auth);
|
|
98
|
+
if (changed.length > 0) {
|
|
99
|
+
throw new DeployError(
|
|
100
|
+
`${step.file}: ${changed.map((f) => `\`auth.${f}\``).join(", ")} can't be changed on an existing credential. ` +
|
|
101
|
+
`Delete it with \`agentschema cred delete ${join(dir, step.file)}\`, then create it again with \`agentschema cred deploy\`.`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
step.remote = remote;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
for (const step of steps) {
|
|
109
|
+
if (step.action === "missing") {
|
|
110
|
+
log(`missing credential ${step.file} (create it with: agentschema cred deploy ${join(dir, step.file)})`);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (dryRun || step.action === "unchanged") {
|
|
114
|
+
log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? ""}`.trimEnd());
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
let result;
|
|
119
|
+
if (step.kind === "vault") {
|
|
120
|
+
if (step.action === "create") {
|
|
121
|
+
result = await call(step, () => client.beta.vaults.create(step.body));
|
|
122
|
+
} else {
|
|
123
|
+
const remote = await retrieve(step, () => client.beta.vaults.retrieve(step.entry.id));
|
|
124
|
+
const body = { ...step.body, metadata: metadataWithDeletions(step.body.metadata, remote.metadata) };
|
|
125
|
+
result = await call(step, () => client.beta.vaults.update(step.entry.id, body));
|
|
126
|
+
}
|
|
127
|
+
lock.resources[step.key] = { kind: "vault", id: result.id, hash: step.hash };
|
|
128
|
+
} else {
|
|
129
|
+
result = await call(step, () => client.beta.vaults.credentials.update(step.entry.id, credentialUpdateBody(step)));
|
|
130
|
+
lock.resources[step.key] = { ...step.entry, hash: step.hash };
|
|
131
|
+
}
|
|
132
|
+
writeLock(dir, lock);
|
|
133
|
+
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}`);
|
|
134
|
+
}
|
|
135
|
+
return steps;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function planStep(lock, step) {
|
|
139
|
+
step.hash = hashBody(step.body);
|
|
140
|
+
step.entry = lock.resources[step.key];
|
|
141
|
+
if (step.entry && step.entry.kind !== step.kind) {
|
|
142
|
+
throw new DeployError(`${LOCK_FILE}: entry for ${step.key} is a ${step.entry.kind}, expected ${step.kind}`);
|
|
143
|
+
}
|
|
144
|
+
step.action = !step.entry ? "create" : step.entry.hash === step.hash ? "unchanged" : "update";
|
|
145
|
+
return step;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Only a credential's name, metadata, refresh scope, networking and injection location can
|
|
149
|
+
// change; the immutable fields were checked to be unchanged, and the secrets stay as they are
|
|
150
|
+
// in the vault.
|
|
151
|
+
function credentialUpdateBody(step) {
|
|
152
|
+
const { display_name, auth, metadata } = step.body;
|
|
153
|
+
const body = {
|
|
154
|
+
vault_id: step.entry.vault_id,
|
|
155
|
+
display_name,
|
|
156
|
+
metadata: metadataWithDeletions(metadata, step.remote?.metadata),
|
|
157
|
+
};
|
|
158
|
+
if (auth.refresh) body.auth = { type: auth.type, refresh: { scope: auth.refresh.scope ?? null } };
|
|
159
|
+
if (auth.type === ENV_VAR) {
|
|
160
|
+
// An update keeps what it isn't sent, so spell out what the file means: when created,
|
|
161
|
+
// no injection_location enables both, and a field left out of one is false.
|
|
162
|
+
const where = auth.injection_location;
|
|
163
|
+
body.auth = {
|
|
164
|
+
type: auth.type,
|
|
165
|
+
networking: auth.networking,
|
|
166
|
+
injection_location: where ? { header: where.header === true, body: where.body === true } : { header: true, body: true },
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
return body;
|
|
170
|
+
}
|
|
171
|
+
|
|
63
172
|
async function deployEnvironment(client, step) {
|
|
64
173
|
if (step.action === "create") return call(step, () => client.beta.environments.create(step.body));
|
|
65
174
|
|
|
@@ -100,13 +209,13 @@ async function deployAgent(client, step, force) {
|
|
|
100
209
|
}
|
|
101
210
|
|
|
102
211
|
// Metadata updates merge, so keys removed from the file are sent as null to delete them.
|
|
103
|
-
function metadataWithDeletions(local = {}, remote = {}) {
|
|
212
|
+
export function metadataWithDeletions(local = {}, remote = {}) {
|
|
104
213
|
const merged = { ...local };
|
|
105
214
|
for (const key of Object.keys(remote ?? {})) if (!(key in merged)) merged[key] = null;
|
|
106
215
|
return merged;
|
|
107
216
|
}
|
|
108
217
|
|
|
109
|
-
async function retrieve(step, fn) {
|
|
218
|
+
export async function retrieve(step, fn) {
|
|
110
219
|
let remote;
|
|
111
220
|
try {
|
|
112
221
|
remote = await fn();
|
|
@@ -128,7 +237,7 @@ async function retrieve(step, fn) {
|
|
|
128
237
|
return remote;
|
|
129
238
|
}
|
|
130
239
|
|
|
131
|
-
async function call(step, fn) {
|
|
240
|
+
export async function call(step, fn) {
|
|
132
241
|
try {
|
|
133
242
|
return await fn();
|
|
134
243
|
} catch (err) {
|
package/src/init.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { basename, dirname, resolve } from "node:path";
|
|
3
|
-
import { createInterface, emitKeypressEvents } from "node:readline";
|
|
4
3
|
import { stringify } from "yaml";
|
|
5
4
|
import { AGENT_FILE, ENV_FILE } from "./instance.js";
|
|
5
|
+
import { prompts } from "./prompts.js";
|
|
6
6
|
import { TOOLSET_FILE, PREBUILT_TOOLS, TOOLSET, TOOLS_DIR } from "./tools.js";
|
|
7
7
|
|
|
8
8
|
export class InitError extends Error {}
|
|
@@ -46,9 +46,10 @@ export function scaffold(answers) {
|
|
|
46
46
|
return files;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
// The pre-built toolset file,
|
|
50
|
-
|
|
51
|
-
|
|
49
|
+
// The pre-built toolset file, with a row for each of `names`: on if it's in `enabled`, with the
|
|
50
|
+
// API's default permission policy.
|
|
51
|
+
export function builtInFile(names, enabled = names) {
|
|
52
|
+
const rows = names.map((name) => `| \`${name}\` | \`${enabled.includes(name)}\` | |`).join("\n");
|
|
52
53
|
return `---\ntype: ${TOOLSET}\n---\n\nThe tools Claude runs in the agent's container. Set Enabled to false to turn a tool off.\n\n## Tools\n\n| Name | Enabled | Permission |\n|---|---|---|\n${rows}\n`;
|
|
53
54
|
}
|
|
54
55
|
|
|
@@ -75,15 +76,8 @@ export async function init(dir, { yes = false, input = process.stdin, output = p
|
|
|
75
76
|
|
|
76
77
|
// Fills in `answers` from the user's replies; an empty reply keeps the default shown.
|
|
77
78
|
async function ask(answers, input, output) {
|
|
78
|
-
const io =
|
|
79
|
-
const confirm =
|
|
80
|
-
while (true) {
|
|
81
|
-
const reply = (await io.text(`${question} [y/n]`, fallback ? "y" : "n")).toLowerCase();
|
|
82
|
-
if (/^(y|yes)$/.test(reply)) return true;
|
|
83
|
-
if (/^(n|no)$/.test(reply)) return false;
|
|
84
|
-
output.write("Answer y or n\n");
|
|
85
|
-
}
|
|
86
|
-
};
|
|
79
|
+
const io = prompts(input, output, { cancelled: () => new InitError("cancelled") });
|
|
80
|
+
const { confirm } = io;
|
|
87
81
|
|
|
88
82
|
try {
|
|
89
83
|
answers.name = await io.text("Agent name?", answers.name);
|
|
@@ -99,94 +93,3 @@ async function ask(answers, input, output) {
|
|
|
99
93
|
io.close();
|
|
100
94
|
}
|
|
101
95
|
}
|
|
102
|
-
|
|
103
|
-
// Prompts for piped input: one answer per line, and choices picked by name or number.
|
|
104
|
-
function linePrompts(input, output) {
|
|
105
|
-
const rl = createInterface({ input, output, terminal: false });
|
|
106
|
-
const lines = rl[Symbol.asyncIterator]();
|
|
107
|
-
let ended = false;
|
|
108
|
-
|
|
109
|
-
const text = async (question, fallback) => {
|
|
110
|
-
if (ended) return fallback;
|
|
111
|
-
output.write(`${question} (${fallback}) `);
|
|
112
|
-
const { value, done } = await lines.next();
|
|
113
|
-
if (done) {
|
|
114
|
-
ended = true;
|
|
115
|
-
output.write("\n");
|
|
116
|
-
return fallback;
|
|
117
|
-
}
|
|
118
|
-
return value.trim() || fallback;
|
|
119
|
-
};
|
|
120
|
-
const select = async (question, choices, fallback) => {
|
|
121
|
-
const listed = choices.map((c, i) => `${i + 1}) ${c}`).join(" ");
|
|
122
|
-
while (true) {
|
|
123
|
-
const reply = await text(`${question} ${listed}`, String(choices.indexOf(fallback) + 1));
|
|
124
|
-
const picked = choices[Number(reply) - 1] ?? choices.find((c) => c === reply);
|
|
125
|
-
if (picked) return picked;
|
|
126
|
-
output.write(`Pick one of: ${choices.join(", ")}\n`);
|
|
127
|
-
}
|
|
128
|
-
};
|
|
129
|
-
return { text, select, close: () => rl.close() };
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const ESC = "\x1b[";
|
|
133
|
-
const cyan = (s) => `${ESC}36m${s}${ESC}0m`;
|
|
134
|
-
const dim = (s) => `${ESC}2m${s}${ESC}0m`;
|
|
135
|
-
|
|
136
|
-
// Prompts for a terminal: choices are picked with the arrow keys and Enter.
|
|
137
|
-
function terminalPrompts(input, output) {
|
|
138
|
-
const cancelled = () => new InitError("cancelled");
|
|
139
|
-
|
|
140
|
-
// A fresh readline per question, so it doesn't fight the raw-mode select for the arrow keys.
|
|
141
|
-
const text = (question, fallback) =>
|
|
142
|
-
new Promise((resolve, reject) => {
|
|
143
|
-
const rl = createInterface({ input, output, terminal: true });
|
|
144
|
-
rl.on("SIGINT", () => {
|
|
145
|
-
rl.close();
|
|
146
|
-
output.write("\n");
|
|
147
|
-
reject(cancelled());
|
|
148
|
-
});
|
|
149
|
-
rl.question(`${question} ${dim(`(${fallback})`)} `, (reply) => {
|
|
150
|
-
rl.close();
|
|
151
|
-
resolve(reply.trim() || fallback);
|
|
152
|
-
});
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
const select = (question, choices, fallback) =>
|
|
156
|
-
new Promise((resolve, reject) => {
|
|
157
|
-
let index = Math.max(0, choices.indexOf(fallback));
|
|
158
|
-
const render = (first) => {
|
|
159
|
-
if (!first) output.write(`${ESC}${choices.length}A`);
|
|
160
|
-
for (const [i, choice] of choices.entries()) {
|
|
161
|
-
output.write(`${ESC}2K${i === index ? cyan(`❯ ${choice}`) : ` ${choice}`}\n`);
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
const finish = (err) => {
|
|
165
|
-
input.off("keypress", onKey);
|
|
166
|
-
input.setRawMode(false);
|
|
167
|
-
input.pause();
|
|
168
|
-
// Collapse the list to one line with the answer.
|
|
169
|
-
output.write(`${ESC}${choices.length + 1}A${ESC}J${ESC}?25h`);
|
|
170
|
-
output.write(`${question} ${err ? dim("cancelled") : cyan(choices[index])}\n`);
|
|
171
|
-
err ? reject(err) : resolve(choices[index]);
|
|
172
|
-
};
|
|
173
|
-
const onKey = (str, key = {}) => {
|
|
174
|
-
if (key.ctrl && key.name === "c") return finish(cancelled());
|
|
175
|
-
if (key.name === "return" || key.name === "enter") return finish();
|
|
176
|
-
if (key.name === "up" || key.name === "k") index = (index - 1 + choices.length) % choices.length;
|
|
177
|
-
else if (key.name === "down" || key.name === "j" || key.name === "tab") index = (index + 1) % choices.length;
|
|
178
|
-
else if (/^[1-9]$/.test(str ?? "") && Number(str) <= choices.length) index = Number(str) - 1;
|
|
179
|
-
else return;
|
|
180
|
-
render(false);
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
emitKeypressEvents(input);
|
|
184
|
-
input.setRawMode(true);
|
|
185
|
-
input.resume();
|
|
186
|
-
output.write(`${question} ${dim("(↑/↓, Enter)")}\n${ESC}?25l`);
|
|
187
|
-
render(true);
|
|
188
|
-
input.on("keypress", onKey);
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
return { text, select, close() {} };
|
|
192
|
-
}
|
package/src/markdown.js
CHANGED
|
@@ -1,7 +1,17 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
1
2
|
import { parseDocument } from "yaml";
|
|
2
3
|
|
|
3
4
|
export class FileError extends Error {}
|
|
4
5
|
|
|
6
|
+
// Edits a file's frontmatter through `edit(doc)`, keeping its comments and the rest of the file.
|
|
7
|
+
export function updateFrontmatter(file, edit) {
|
|
8
|
+
const text = readFileSync(file, "utf8").replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
|
|
9
|
+
const end = 4 + /^---[ \t]*$/m.exec(text.slice(4)).index;
|
|
10
|
+
const doc = parseDocument(text.slice(4, end));
|
|
11
|
+
edit(doc);
|
|
12
|
+
writeFileSync(file, `---\n${doc.toString({ lineWidth: 0 })}${text.slice(end)}`);
|
|
13
|
+
}
|
|
14
|
+
|
|
5
15
|
// Splits a Markdown file into YAML frontmatter (between `---` fences) and body.
|
|
6
16
|
export function parseMarkdown(text, file) {
|
|
7
17
|
const normalized = text.replace(/^/, "").replace(/\r\n/g, "\n");
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Just enough of the MCP client protocol (Streamable HTTP) to ask a server for its tools.
|
|
2
|
+
|
|
3
|
+
const PROTOCOL_VERSION = "2025-06-18";
|
|
4
|
+
const TIMEOUT_MS = 10_000;
|
|
5
|
+
|
|
6
|
+
// The names of the tools an MCP server offers, sorted. Returns null when the server won't say
|
|
7
|
+
// without signing in, or can't be reached. Sends no credentials.
|
|
8
|
+
export async function listMcpTools(url, { fetch = globalThis.fetch } = {}) {
|
|
9
|
+
try {
|
|
10
|
+
let sessionId = null;
|
|
11
|
+
const send = async (message) => {
|
|
12
|
+
const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
|
|
13
|
+
if (sessionId) headers["mcp-session-id"] = sessionId;
|
|
14
|
+
const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(message), signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
15
|
+
sessionId = res.headers.get("mcp-session-id") ?? sessionId;
|
|
16
|
+
if (!res.ok) throw new Error(`status ${res.status}`);
|
|
17
|
+
return message.id === undefined ? null : parseResponse(await res.text(), message.id);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
await send({
|
|
21
|
+
jsonrpc: "2.0",
|
|
22
|
+
id: 1,
|
|
23
|
+
method: "initialize",
|
|
24
|
+
params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "agentschema", version: "0" } },
|
|
25
|
+
});
|
|
26
|
+
await send({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
27
|
+
|
|
28
|
+
const names = [];
|
|
29
|
+
let cursor;
|
|
30
|
+
let id = 2;
|
|
31
|
+
do {
|
|
32
|
+
const { result } = await send({ jsonrpc: "2.0", id: id++, method: "tools/list", params: cursor ? { cursor } : {} });
|
|
33
|
+
names.push(...result.tools.map((t) => t.name));
|
|
34
|
+
cursor = result.nextCursor;
|
|
35
|
+
} while (cursor);
|
|
36
|
+
return [...new Set(names)].sort();
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// A response is either plain JSON, or a stream of events with the JSON in a `data:` line.
|
|
43
|
+
function parseResponse(text, id) {
|
|
44
|
+
const trimmed = text.trim();
|
|
45
|
+
if (trimmed.startsWith("{")) return checked(JSON.parse(trimmed));
|
|
46
|
+
for (const line of trimmed.split("\n")) {
|
|
47
|
+
if (!line.startsWith("data:")) continue;
|
|
48
|
+
const message = JSON.parse(line.slice(5));
|
|
49
|
+
if (message.id === id) return checked(message);
|
|
50
|
+
}
|
|
51
|
+
throw new Error("no response");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function checked(message) {
|
|
55
|
+
if (message.error) throw new Error(message.error.message);
|
|
56
|
+
return message;
|
|
57
|
+
}
|