@soft-boy/agentschema 0.2.1 → 0.3.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 +176 -15
- package/bin/agentschema.js +136 -16
- package/package.json +3 -2
- package/src/chat.js +50 -0
- package/src/check.js +254 -4
- package/src/cred-menu.js +197 -0
- package/src/cred.js +243 -0
- package/src/deploy.js +164 -15
- package/src/dotenv.js +50 -0
- package/src/init.js +7 -104
- package/src/instance.js +4 -2
- 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 +37 -4
- package/src/skills.js +79 -0
- 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,28 +1,34 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import Anthropic, { toFile } 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 { skillFingerprint, skillKey, skillRefs } from "./skills.js";
|
|
7
|
+
import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey } from "./vaults.js";
|
|
5
8
|
|
|
6
9
|
export class DeployError extends Error {}
|
|
7
10
|
|
|
8
|
-
// Creates or updates the environment and
|
|
11
|
+
// Creates or updates the skills, environment, agent and vaults a folder defines, recording their
|
|
12
|
+
// IDs in claude-lock.json. Skills go first, because the agent refers to their IDs and versions. Credentials are only updated here: creating one needs its secrets, so
|
|
13
|
+
// that's `cred deploy`'s job.
|
|
9
14
|
// Returns the plan: one { file, kind, action, id, version } entry per resource.
|
|
10
15
|
export async function deploy(dir, { client, dryRun = false, force = false, log = () => {} }) {
|
|
11
16
|
const { errors, instance } = check(dir);
|
|
12
17
|
if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
|
|
18
|
+
const lock = openLock(dir, client);
|
|
13
19
|
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
20
|
+
const skillSteps = await deploySkills(instance.skills, { dir, client, lock, dryRun, log });
|
|
21
|
+
// A dry run has no new IDs or versions yet, so a stand-in shows that the agent will change too.
|
|
22
|
+
const pending = dryRun ? skillSteps.filter((s) => s.action !== "unchanged") : [];
|
|
23
|
+
const refs = instance.skills.flatMap((skill) => {
|
|
24
|
+
const step = pending.find((s) => s.key === skillKey(skill));
|
|
25
|
+
if (!step) return skillRefs([skill], lock);
|
|
26
|
+
return [{ type: "custom", skill_id: step.entry?.id ?? `pending:${skill.name}`, version: `pending:${step.hash}` }];
|
|
27
|
+
});
|
|
22
28
|
|
|
23
29
|
const steps = [
|
|
24
30
|
{ file: ENV_FILE, kind: "environment", body: envBody(instance) },
|
|
25
|
-
{ file: AGENT_FILE, kind: "agent", body: agentBody(instance) },
|
|
31
|
+
{ file: AGENT_FILE, kind: "agent", body: agentBody(instance, refs) },
|
|
26
32
|
];
|
|
27
33
|
for (const step of steps) {
|
|
28
34
|
step.key = `./${step.file}`;
|
|
@@ -53,13 +59,156 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
|
|
|
53
59
|
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}${version}`);
|
|
54
60
|
}
|
|
55
61
|
|
|
56
|
-
|
|
62
|
+
const vaultSteps = await deployVaults(dir, instance.vaults, { client, lock, dryRun, log });
|
|
63
|
+
|
|
64
|
+
return [...skillSteps, ...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
|
|
57
65
|
file, kind, action,
|
|
58
66
|
id: lock.resources[key]?.id,
|
|
59
67
|
version: lock.resources[key]?.version,
|
|
60
68
|
}));
|
|
61
69
|
}
|
|
62
70
|
|
|
71
|
+
// Reads claude-lock.json, or starts a new one, and checks it was written for this API.
|
|
72
|
+
export function openLock(dir, client) {
|
|
73
|
+
const baseURL = client.baseURL;
|
|
74
|
+
const lock = readLock(dir) ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
|
|
75
|
+
lock.resources ??= {};
|
|
76
|
+
if (lock.origin?.base_url && lock.origin.base_url !== baseURL) {
|
|
77
|
+
throw new DeployError(
|
|
78
|
+
`${LOCK_FILE} was written for ${lock.origin.base_url}, but this client uses ${baseURL}`,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
return lock;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Uploads each skill that's new or changed. A change uploads the whole folder as a new version.
|
|
85
|
+
async function deploySkills(skills, { dir, client, lock, dryRun, log }) {
|
|
86
|
+
const steps = [];
|
|
87
|
+
for (const skill of skills) {
|
|
88
|
+
const step = planStep(lock, { file: skill.path, key: skillKey(skill), kind: "skill", body: skillFingerprint(skill) });
|
|
89
|
+
steps.push(step);
|
|
90
|
+
if (dryRun || step.action === "unchanged") {
|
|
91
|
+
log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? skill.name}`);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The API keeps a skill's layout from these names, so each one starts with its folder.
|
|
96
|
+
const files = await Promise.all(skill.files.map((f) => toFile(f.bytes, `${skill.name}/${f.rel}`)));
|
|
97
|
+
let id;
|
|
98
|
+
let version;
|
|
99
|
+
if (step.action === "create") {
|
|
100
|
+
const created = await call(step, () => client.skills.create({ files }));
|
|
101
|
+
({ id, latest_version_id: version } = created);
|
|
102
|
+
} else {
|
|
103
|
+
({ id } = step.entry);
|
|
104
|
+
await retrieve(step, () => client.skills.retrieve(id));
|
|
105
|
+
({ id: version } = await call(step, () => client.skills.versions.create(id, { files })));
|
|
106
|
+
}
|
|
107
|
+
lock.resources[step.key] = { kind: "skill", id, version, hash: step.hash };
|
|
108
|
+
writeLock(dir, lock);
|
|
109
|
+
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} skill ${id} (version ${version})`);
|
|
110
|
+
}
|
|
111
|
+
return steps;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Creates or updates each vault, then updates the settings of credentials already created.
|
|
115
|
+
// A credential file with no credential yet is reported, not created: that needs its secrets.
|
|
116
|
+
async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
|
|
117
|
+
const steps = [];
|
|
118
|
+
for (const vault of vaults) {
|
|
119
|
+
const step = planStep(lock, { file: vault.path, key: vaultKey(vault), kind: "vault", body: vaultBody(vault) });
|
|
120
|
+
steps.push(step);
|
|
121
|
+
for (const cred of vault.credentials) {
|
|
122
|
+
const credStep = planStep(lock, { file: cred.file, key: credentialKey(cred), kind: "credential", body: credentialSettings(cred) });
|
|
123
|
+
credStep.cred = cred;
|
|
124
|
+
credStep.vaultStep = step;
|
|
125
|
+
// A credential belongs to the vault it was created in; if that vault was replaced, it's gone.
|
|
126
|
+
if (credStep.entry && credStep.entry.vault_id !== step.entry?.id) credStep.entry = undefined;
|
|
127
|
+
if (!credStep.entry) credStep.action = "missing";
|
|
128
|
+
steps.push(credStep);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Check every credential update first, so an immutable field changed in one file stops the
|
|
133
|
+
// deploy before anything is sent.
|
|
134
|
+
if (!dryRun) {
|
|
135
|
+
for (const step of steps.filter((s) => s.kind === "credential" && s.action === "update")) {
|
|
136
|
+
const remote = await retrieve(step, () => client.beta.vaults.credentials.retrieve(step.entry.id, { vault_id: step.entry.vault_id }));
|
|
137
|
+
const changed = changedImmutableFields(step.cred, remote.auth);
|
|
138
|
+
if (changed.length > 0) {
|
|
139
|
+
throw new DeployError(
|
|
140
|
+
`${step.file}: ${changed.map((f) => `\`auth.${f}\``).join(", ")} can't be changed on an existing credential. ` +
|
|
141
|
+
`Delete it with \`agentschema cred delete ${join(dir, step.file)}\`, then create it again with \`agentschema cred deploy\`.`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
step.remote = remote;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
for (const step of steps) {
|
|
149
|
+
if (step.action === "missing") {
|
|
150
|
+
log(`missing credential ${step.file} (create it with: agentschema cred deploy ${join(dir, step.file)})`);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (dryRun || step.action === "unchanged") {
|
|
154
|
+
log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? ""}`.trimEnd());
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let result;
|
|
159
|
+
if (step.kind === "vault") {
|
|
160
|
+
if (step.action === "create") {
|
|
161
|
+
result = await call(step, () => client.beta.vaults.create(step.body));
|
|
162
|
+
} else {
|
|
163
|
+
const remote = await retrieve(step, () => client.beta.vaults.retrieve(step.entry.id));
|
|
164
|
+
const body = { ...step.body, metadata: metadataWithDeletions(step.body.metadata, remote.metadata) };
|
|
165
|
+
result = await call(step, () => client.beta.vaults.update(step.entry.id, body));
|
|
166
|
+
}
|
|
167
|
+
lock.resources[step.key] = { kind: "vault", id: result.id, hash: step.hash };
|
|
168
|
+
} else {
|
|
169
|
+
result = await call(step, () => client.beta.vaults.credentials.update(step.entry.id, credentialUpdateBody(step)));
|
|
170
|
+
lock.resources[step.key] = { ...step.entry, hash: step.hash };
|
|
171
|
+
}
|
|
172
|
+
writeLock(dir, lock);
|
|
173
|
+
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}`);
|
|
174
|
+
}
|
|
175
|
+
return steps;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function planStep(lock, step) {
|
|
179
|
+
step.hash = hashBody(step.body);
|
|
180
|
+
step.entry = lock.resources[step.key];
|
|
181
|
+
if (step.entry && step.entry.kind !== step.kind) {
|
|
182
|
+
throw new DeployError(`${LOCK_FILE}: entry for ${step.key} is a ${step.entry.kind}, expected ${step.kind}`);
|
|
183
|
+
}
|
|
184
|
+
step.action = !step.entry ? "create" : step.entry.hash === step.hash ? "unchanged" : "update";
|
|
185
|
+
return step;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Only a credential's name, metadata, refresh scope, networking and injection location can
|
|
189
|
+
// change; the immutable fields were checked to be unchanged, and the secrets stay as they are
|
|
190
|
+
// in the vault.
|
|
191
|
+
function credentialUpdateBody(step) {
|
|
192
|
+
const { display_name, auth, metadata } = step.body;
|
|
193
|
+
const body = {
|
|
194
|
+
vault_id: step.entry.vault_id,
|
|
195
|
+
display_name,
|
|
196
|
+
metadata: metadataWithDeletions(metadata, step.remote?.metadata),
|
|
197
|
+
};
|
|
198
|
+
if (auth.refresh) body.auth = { type: auth.type, refresh: { scope: auth.refresh.scope ?? null } };
|
|
199
|
+
if (auth.type === ENV_VAR) {
|
|
200
|
+
// An update keeps what it isn't sent, so spell out what the file means: when created,
|
|
201
|
+
// no injection_location enables both, and a field left out of one is false.
|
|
202
|
+
const where = auth.injection_location;
|
|
203
|
+
body.auth = {
|
|
204
|
+
type: auth.type,
|
|
205
|
+
networking: auth.networking,
|
|
206
|
+
injection_location: where ? { header: where.header === true, body: where.body === true } : { header: true, body: true },
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return body;
|
|
210
|
+
}
|
|
211
|
+
|
|
63
212
|
async function deployEnvironment(client, step) {
|
|
64
213
|
if (step.action === "create") return call(step, () => client.beta.environments.create(step.body));
|
|
65
214
|
|
|
@@ -100,13 +249,13 @@ async function deployAgent(client, step, force) {
|
|
|
100
249
|
}
|
|
101
250
|
|
|
102
251
|
// Metadata updates merge, so keys removed from the file are sent as null to delete them.
|
|
103
|
-
function metadataWithDeletions(local = {}, remote = {}) {
|
|
252
|
+
export function metadataWithDeletions(local = {}, remote = {}) {
|
|
104
253
|
const merged = { ...local };
|
|
105
254
|
for (const key of Object.keys(remote ?? {})) if (!(key in merged)) merged[key] = null;
|
|
106
255
|
return merged;
|
|
107
256
|
}
|
|
108
257
|
|
|
109
|
-
async function retrieve(step, fn) {
|
|
258
|
+
export async function retrieve(step, fn) {
|
|
110
259
|
let remote;
|
|
111
260
|
try {
|
|
112
261
|
remote = await fn();
|
|
@@ -128,7 +277,7 @@ async function retrieve(step, fn) {
|
|
|
128
277
|
return remote;
|
|
129
278
|
}
|
|
130
279
|
|
|
131
|
-
async function call(step, fn) {
|
|
280
|
+
export async function call(step, fn) {
|
|
132
281
|
try {
|
|
133
282
|
return await fn();
|
|
134
283
|
} catch (err) {
|
package/src/dotenv.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
export const ENV_FILE_NAME = ".env";
|
|
5
|
+
|
|
6
|
+
// Parses KEY=VALUE lines. Returns { values, bad }: `bad` holds the numbers of lines that aren't
|
|
7
|
+
// valid, so they can be reported without showing what's on them.
|
|
8
|
+
export function parseEnvFile(text) {
|
|
9
|
+
const values = {};
|
|
10
|
+
const bad = [];
|
|
11
|
+
for (const [index, raw] of text.replace(/^/, "").split(/\r?\n/).entries()) {
|
|
12
|
+
const line = raw.trim();
|
|
13
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
14
|
+
const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
|
|
15
|
+
const value = match && parseValue(match[2]);
|
|
16
|
+
if (value === null || !match) bad.push(index + 1);
|
|
17
|
+
else values[match[1]] = value;
|
|
18
|
+
}
|
|
19
|
+
return { values, bad };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// A quoted value, where double quotes understand \n and \", or a bare value up to a " #" comment.
|
|
23
|
+
// Returns null for a quote that isn't closed.
|
|
24
|
+
function parseValue(text) {
|
|
25
|
+
const quote = text[0];
|
|
26
|
+
if (quote === "'" || quote === '"') {
|
|
27
|
+
const end = quote === "'" ? text.indexOf("'", 1) : /(?<!\\)"/.exec(text.slice(1))?.index + 1;
|
|
28
|
+
if (end === undefined || end < 1 || Number.isNaN(end)) return null;
|
|
29
|
+
const inner = text.slice(1, end);
|
|
30
|
+
return quote === "'" ? inner : inner.replace(/\\n/g, "\n").replace(/\\"/g, '"');
|
|
31
|
+
}
|
|
32
|
+
return text.replace(/\s+#.*$/, "").trim();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Loads a folder's .env into process.env, for code that runs on your side. A variable already
|
|
36
|
+
// set in the shell wins. A missing file is fine. Returns warnings to show.
|
|
37
|
+
export function loadEnvFile(dir, env = process.env) {
|
|
38
|
+
let text;
|
|
39
|
+
try {
|
|
40
|
+
text = readFileSync(join(dir, ENV_FILE_NAME), "utf8");
|
|
41
|
+
} catch (err) {
|
|
42
|
+
if (err.code === "ENOENT") return [];
|
|
43
|
+
return [`couldn't read ${ENV_FILE_NAME}: ${err.message}`];
|
|
44
|
+
}
|
|
45
|
+
const { values, bad } = parseEnvFile(text);
|
|
46
|
+
for (const [name, value] of Object.entries(values)) {
|
|
47
|
+
if (env[name] === undefined) env[name] = value;
|
|
48
|
+
}
|
|
49
|
+
return bad.map((line) => `${ENV_FILE_NAME}:${line}: not a KEY=VALUE line, so it was skipped`);
|
|
50
|
+
}
|
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/instance.js
CHANGED
|
@@ -41,9 +41,11 @@ export function readInstance(dir) {
|
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
// The bodies sent to POST /v1/agents and POST /v1/environments.
|
|
44
|
-
// The agent's tools come from tools/, compiled into the API's `tools` list.
|
|
45
|
-
|
|
44
|
+
// The agent's tools come from tools/, compiled into the API's `tools` list. `skills` are the
|
|
45
|
+
// references to the skills deployed from skills/, added to any in agent.md's frontmatter.
|
|
46
|
+
export function agentBody({ agent, tools }, skills = []) {
|
|
46
47
|
const body = { ...agent.data, tools: compileTools(tools) };
|
|
48
|
+
if (skills.length > 0) body.skills = [...(agent.data.skills ?? []), ...skills];
|
|
47
49
|
if (agent.body) body.system = agent.body;
|
|
48
50
|
return body;
|
|
49
51
|
}
|