@soft-boy/agentschema 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +8 -2
  2. package/dist/bin/agentschema.d.ts +2 -0
  3. package/dist/bin/agentschema.js +333 -0
  4. package/dist/lib/channels.d.ts +65 -0
  5. package/dist/lib/channels.js +339 -0
  6. package/dist/lib/check.d.ts +10 -0
  7. package/dist/lib/check.js +411 -0
  8. package/dist/lib/files.d.ts +7 -0
  9. package/{lib → dist/lib}/files.js +10 -14
  10. package/dist/lib/index.d.ts +24 -0
  11. package/{lib → dist/lib}/index.js +3 -12
  12. package/dist/lib/instance.d.ts +41 -0
  13. package/dist/lib/instance.js +74 -0
  14. package/dist/lib/markdown.d.ts +11 -0
  15. package/dist/lib/markdown.js +38 -0
  16. package/dist/lib/scaffold.d.ts +15 -0
  17. package/dist/lib/scaffold.js +46 -0
  18. package/dist/lib/scheduled.d.ts +56 -0
  19. package/dist/lib/scheduled.js +185 -0
  20. package/dist/lib/skills.d.ts +28 -0
  21. package/dist/lib/skills.js +55 -0
  22. package/dist/lib/stream.d.ts +30 -0
  23. package/dist/lib/stream.js +56 -0
  24. package/dist/lib/system-prompt.d.ts +16 -0
  25. package/{lib → dist/lib}/system-prompt.js +14 -15
  26. package/dist/lib/tools.d.ts +105 -0
  27. package/dist/lib/tools.js +353 -0
  28. package/dist/lib/vaults.d.ts +55 -0
  29. package/dist/lib/vaults.js +143 -0
  30. package/dist/src/chat.d.ts +15 -0
  31. package/dist/src/chat.js +159 -0
  32. package/dist/src/check.d.ts +2 -0
  33. package/dist/src/check.js +14 -0
  34. package/dist/src/cred-menu.d.ts +17 -0
  35. package/dist/src/cred-menu.js +193 -0
  36. package/dist/src/cred.d.ts +54 -0
  37. package/dist/src/cred.js +252 -0
  38. package/dist/src/custom-tools.d.ts +3 -0
  39. package/dist/src/custom-tools.js +18 -0
  40. package/dist/src/delete.d.ts +9 -0
  41. package/dist/src/delete.js +27 -0
  42. package/dist/src/deploy.d.ts +62 -0
  43. package/dist/src/deploy.js +442 -0
  44. package/dist/src/dotenv.d.ts +7 -0
  45. package/dist/src/dotenv.js +54 -0
  46. package/dist/src/folder.d.ts +5 -0
  47. package/{src → dist/src}/folder.js +30 -28
  48. package/dist/src/init.d.ts +11 -0
  49. package/dist/src/init.js +51 -0
  50. package/dist/src/list.d.ts +3 -0
  51. package/dist/src/list.js +46 -0
  52. package/dist/src/lock.d.ts +10 -0
  53. package/dist/src/lock.js +37 -0
  54. package/dist/src/mcp.d.ts +11 -0
  55. package/dist/src/mcp.js +79 -0
  56. package/dist/src/node.d.ts +14 -0
  57. package/dist/src/oauth.d.ts +64 -0
  58. package/dist/src/oauth.js +208 -0
  59. package/dist/src/prompts.d.ts +18 -0
  60. package/dist/src/prompts.js +166 -0
  61. package/dist/src/session.d.ts +58 -0
  62. package/dist/src/session.js +200 -0
  63. package/dist/src/tools-menu.d.ts +8 -0
  64. package/dist/src/tools-menu.js +173 -0
  65. package/package.json +21 -9
  66. package/bin/agentschema.js +0 -326
  67. package/lib/channels.js +0 -338
  68. package/lib/check.js +0 -387
  69. package/lib/instance.js +0 -75
  70. package/lib/markdown.js +0 -42
  71. package/lib/scaffold.js +0 -51
  72. package/lib/scheduled.js +0 -175
  73. package/lib/skills.js +0 -58
  74. package/lib/stream.js +0 -50
  75. package/lib/tools.js +0 -327
  76. package/lib/vaults.js +0 -142
  77. package/src/chat.js +0 -156
  78. package/src/check.js +0 -14
  79. package/src/cred-menu.js +0 -197
  80. package/src/cred.js +0 -263
  81. package/src/custom-tools.js +0 -17
  82. package/src/delete.js +0 -25
  83. package/src/deploy.js +0 -441
  84. package/src/dotenv.js +0 -50
  85. package/src/init.js +0 -54
  86. package/src/list.js +0 -49
  87. package/src/lock.js +0 -40
  88. package/src/mcp.js +0 -76
  89. package/src/oauth.js +0 -215
  90. package/src/prompts.js +0 -159
  91. package/src/session.js +0 -194
  92. package/src/tools-menu.js +0 -163
  93. /package/{src → dist/src}/node.js +0 -0
package/src/cred.js DELETED
@@ -1,263 +0,0 @@
1
- import { writeFileSync } from "node:fs";
2
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
3
- import Anthropic from "@anthropic-ai/sdk";
4
- import { check } from "./check.js";
5
- import { DeployError, call, openLock, retrieve } from "./deploy.js";
6
- import { LOCK_FILE, hashBody, writeLock } from "./lock.js";
7
- import { readFolder, updateFrontmatter } from "./folder.js";
8
- import { listedMcpToolset } from "./mcp.js";
9
- import { authorizationRequest, discover, exchangeCode, registerClient, startCallbackServer } from "./oauth.js";
10
- import {
11
- ENV_VAR, VAULTS_DIR, VAULT_FILE, changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings,
12
- secretsNeeded, vaultBody, vaultKey,
13
- } from "../lib/vaults.js";
14
-
15
- // Finds the agent folder and the credential a path like my-agent/vaults/Ops/slack.md names.
16
- export function locate(path) {
17
- const file = resolve(path);
18
- const vaultDir = dirname(file);
19
- const dir = dirname(dirname(vaultDir));
20
- if (basename(dirname(vaultDir)) !== VAULTS_DIR || !file.endsWith(".md") || basename(file) === VAULT_FILE) {
21
- throw new DeployError(`${path}: not a credential file; expected a path like my-agent/${VAULTS_DIR}/<vault>/<credential>.md`);
22
- }
23
-
24
- const { errors, instance } = check(dir);
25
- if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
26
- const rel = relative(dir, file).split(sep).join("/");
27
- const vault = instance.vaults.find((v) => v.name === basename(vaultDir));
28
- const cred = vault?.credentials.find((c) => c.file === rel);
29
- if (!cred) throw new DeployError(`${path}: no such credential file`);
30
- return { dir, vault, cred };
31
- }
32
-
33
- // Creates the credential a file describes from the secrets you paste, asking for them with
34
- // `ask(question, { secret })`. The secrets go straight to the vault and are never written to
35
- // disk. Creates the vault first if it hasn't been deployed.
36
- export async function credPaste(path, { client, ask, log = () => {} }) {
37
- const { dir, vault, cred } = locate(path);
38
- const lock = openLock(dir, client);
39
- const vaultEntry = lock.resources[vaultKey(vault)];
40
- const existing = lock.resources[credentialKey(cred)];
41
- if (existing && existing.vault_id === vaultEntry?.id) {
42
- throw new DeployError(
43
- `${cred.file} was already created (${existing.id}). To replace its secrets, delete it with ` +
44
- `\`agentschema cred delete ${path}\` and create it again.`,
45
- );
46
- }
47
-
48
- const needs = secretsNeeded(cred);
49
- const required = async (question) => {
50
- const answer = (await ask(question, { secret: true })).trim();
51
- if (!answer) throw new DeployError(`${question.replace(/:\s*$/, "")} is required`);
52
- return answer;
53
- };
54
- if (cred.data.auth.type === ENV_VAR) {
55
- const secretValue = await required(`Value of ${cred.data.auth.secret_name}: `);
56
- return createCredential({ lock, vault, cred, secrets: { secretValue }, client, saveLock: (next) => writeLock(dir, next), log });
57
- }
58
- const secrets = { accessToken: await required("Access token: ") };
59
- const expiresAt = (await ask("Access token expires at (ISO 8601, e.g. 2026-12-31T23:59:59Z; blank if unknown): ", { secret: false })).trim();
60
- if (expiresAt) {
61
- if (Number.isNaN(Date.parse(expiresAt))) throw new DeployError(`"${expiresAt}" isn't a date and time`);
62
- secrets.expiresAt = new Date(expiresAt).toISOString();
63
- }
64
- if (needs.refreshToken) secrets.refreshToken = await required("Refresh token: ");
65
- if (needs.clientSecret) secrets.clientSecret = await required("Client secret: ");
66
-
67
- return createCredential({ lock, vault, cred, secrets, client, saveLock: (next) => writeLock(dir, next), log });
68
- }
69
-
70
- // Creates a credential with its secrets, creating its vault first if needed, records it in the
71
- // lock, and asks the API to try it. `secrets` are what credentialCreateBody takes. Works on a lock
72
- // object, so a host can keep it wherever it likes, and `saveLock` may be async.
73
- export async function createCredential({ lock, vault, cred, secrets, client, saveLock = () => {}, log = () => {} }) {
74
- let vaultId = lock.resources[vaultKey(vault)]?.id;
75
- if (!vaultId) {
76
- const body = vaultBody(vault);
77
- const created = await call({ file: vault.path, kind: "vault" }, () => client.beta.vaults.create(body));
78
- vaultId = created.id;
79
- lock.resources[vaultKey(vault)] = { kind: "vault", id: vaultId, hash: hashBody(body) };
80
- await saveLock(lock);
81
- log(`created vault ${vaultId}`);
82
- }
83
-
84
- const created = await call({ file: cred.file, kind: "credential" }, () =>
85
- client.beta.vaults.credentials.create(vaultId, credentialCreateBody(cred, secrets)),
86
- );
87
- lock.resources[credentialKey(cred)] = { kind: "credential", id: created.id, vault_id: vaultId, hash: hashBody(credentialSettings(cred)) };
88
- await saveLock(lock);
89
- log(`created credential ${created.id}`);
90
-
91
- if (cred.data.auth.type === ENV_VAR) return created;
92
-
93
- // Best effort: ask the API to try the credential against the MCP server.
94
- try {
95
- const validation = await client.beta.vaults.credentials.mcpOAuthValidate(created.id, { vault_id: vaultId });
96
- if (validation.status === "valid") log("checked the MCP server accepted the credential");
97
- else log(`warning: the API couldn't confirm the credential works (${validation.status}); check the tokens`);
98
- } catch {
99
- // Validation is only a convenience; the credential exists either way.
100
- }
101
- return created;
102
- }
103
-
104
- // Signs in to the credential's MCP server in the browser, then creates the credential with the
105
- // tokens, or replaces the tokens of the one that exists. Endpoints come from the server's OAuth
106
- // metadata. The OAuth client is the file's `auth.refresh.client_id`; without a refresh block,
107
- // agentschema registers itself as a client, if the server allows it, and writes the refresh
108
- // block into the file. Tokens go straight to the vault and are never written to disk.
109
- export async function credLogin(path, { client, ask, openBrowser, port = 0, fetch = globalThis.fetch, log = () => {} }) {
110
- let located = locate(path);
111
- const { auth } = located.cred.data;
112
- if (auth.type === ENV_VAR) {
113
- 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}`);
114
- }
115
- let refresh = auth.refresh ?? null;
116
-
117
- log(`Looking up the sign-in for ${auth.mcp_server_url}…`);
118
- const server = await discover(auth.mcp_server_url, { fetch });
119
- if (server.codeChallengeMethods && !server.codeChallengeMethods.includes("S256")) {
120
- throw new DeployError(`${server.issuer} doesn't support PKCE with S256, which agentschema needs to sign in`);
121
- }
122
-
123
- const callback = await startCallbackServer(Number(port));
124
- try {
125
- let clientId, clientSecret = null, authMethod, tokenEndpoint;
126
- if (refresh) {
127
- ({ client_id: clientId, token_endpoint: tokenEndpoint } = refresh);
128
- authMethod = refresh.token_endpoint_auth.type;
129
- if (authMethod !== "none") clientSecret = await required(ask, "Client secret: ");
130
- } else if (server.registrationEndpoint) {
131
- ({ clientId, clientSecret, authMethod } = await registerClient(server.registrationEndpoint, callback.redirectUri, { fetch }));
132
- tokenEndpoint = server.tokenEndpoint;
133
- log(`Registered agentschema as an OAuth client (${clientId}).`);
134
- } else {
135
- throw new DeployError(noClientMessage(located.cred, server, callback.redirectUri));
136
- }
137
-
138
- const resource = refresh ? (refresh.resource ?? null) : (server.resource ?? auth.mcp_server_url);
139
- const request = authorizationRequest({
140
- authorizationEndpoint: server.authorizationEndpoint,
141
- issuer: server.issuer,
142
- clientId,
143
- redirectUri: callback.redirectUri,
144
- scope: refresh?.scope,
145
- resource,
146
- });
147
- log(`Opening your browser to sign in. If it doesn't open, go to:\n ${request.url}`);
148
- openBrowser(request.url);
149
- const code = await callback.waitForCode(request.state);
150
- const tokens = await exchangeCode(
151
- { tokenEndpoint, code, verifier: request.verifier, redirectUri: callback.redirectUri, clientId, clientSecret, authMethod, resource },
152
- { fetch },
153
- );
154
- if (!tokens.refreshToken) {
155
- throw new DeployError(
156
- "the server didn't return a refresh token, so the credential would stop working when the access token expires. Nothing was created.",
157
- );
158
- }
159
-
160
- // A client agentschema registered: record it in the file, since it's part of the credential.
161
- if (!refresh) {
162
- refresh = { token_endpoint: tokenEndpoint, client_id: clientId };
163
- if (tokens.scope) refresh.scope = tokens.scope;
164
- if (resource) refresh.resource = resource;
165
- refresh.token_endpoint_auth = { type: authMethod };
166
- updateFrontmatter(resolve(path), (doc) => doc.setIn(["auth", "refresh"], doc.createNode(refresh)));
167
- log(`Added auth.refresh to ${located.cred.file}.`);
168
- located = locate(path);
169
- }
170
-
171
- const secrets = { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, refreshToken: tokens.refreshToken, clientSecret };
172
- const { dir, vault, cred } = located;
173
- await listToolsInFile(dir, auth.mcp_server_url, tokens.accessToken, { fetch, log });
174
- const lock = openLock(dir, client);
175
- const existing = lock.resources[credentialKey(cred)];
176
- if (existing && existing.vault_id === lock.resources[vaultKey(vault)]?.id) {
177
- return replaceTokens({ dir, lock, cred, entry: existing }, secrets, { client, log });
178
- }
179
- return createCredential({ lock, vault, cred, secrets, client, saveLock: (next) => writeLock(dir, next), log });
180
- } finally {
181
- await callback.close();
182
- }
183
- }
184
-
185
- // Now that the server will say what it offers, lists its tools in their file.
186
- async function listToolsInFile(dir, url, token, { fetch, log }) {
187
- const listed = await listedMcpToolset(readFolder(dir), url, { fetch, token });
188
- if (!listed) return;
189
- writeFileSync(join(dir, listed.path), listed.text);
190
- log(`Listed the server's tools in ${listed.path}.`);
191
- }
192
-
193
- async function required(ask, question) {
194
- const answer = (await ask(question, { secret: true })).trim();
195
- if (!answer) throw new DeployError(`${question.replace(/:\s*$/, "")} is required`);
196
- return answer;
197
- }
198
-
199
- // Puts the tokens from a new sign-in into an existing credential.
200
- async function replaceTokens({ cred, entry }, secrets, { client, log }) {
201
- const step = { file: cred.file, kind: "credential", key: credentialKey(cred), entry };
202
- const remote = await retrieve(step, () => client.beta.vaults.credentials.retrieve(entry.id, { vault_id: entry.vault_id }));
203
- const changed = changedImmutableFields(cred, remote.auth);
204
- if (changed.length > 0) {
205
- throw new DeployError(
206
- `${cred.file}: ${changed.map((f) => `\`auth.${f}\``).join(", ")} changed since the credential was created. ` +
207
- "Delete it with `agentschema cred delete`, then sign in again.",
208
- );
209
- }
210
- const { auth } = cred.data;
211
- const body = {
212
- vault_id: entry.vault_id,
213
- auth: { type: auth.type, access_token: secrets.accessToken, expires_at: secrets.expiresAt, refresh: { refresh_token: secrets.refreshToken } },
214
- };
215
- const method = auth.refresh.token_endpoint_auth.type;
216
- if (method !== "none") body.auth.refresh.token_endpoint_auth = { type: method, client_secret: secrets.clientSecret };
217
- const updated = await call(step, () => client.beta.vaults.credentials.update(entry.id, body));
218
- log(`updated credential ${updated.id} with the new tokens`);
219
- return updated;
220
- }
221
-
222
- // What to do when the server won't register agentschema: bring your own OAuth client.
223
- function noClientMessage(cred, server, redirectUri) {
224
- const scopes = server.scopesSupported.length > 0 ? `\n scope: ${server.scopesSupported[0]} # supported: ${server.scopesSupported.join(" ")}` : "";
225
- return (
226
- `${server.issuer} doesn't let apps register themselves, so sign-in needs your own OAuth client. ` +
227
- `Create one with the provider, allowing the redirect URI ${redirectUri.replace(/:\d+\//, ":<port>/")} ` +
228
- `(pass the same --port to cred login), then add this to ${cred.file}:\n\n` +
229
- ` refresh:\n token_endpoint: ${server.tokenEndpoint}\n client_id: "…"${scopes}\n token_endpoint_auth:\n type: client_secret_post`
230
- );
231
- }
232
-
233
- // Permanently deletes the credential a file describes and removes it from claude-lock.json.
234
- // The file itself stays, so `cred deploy` can create it again.
235
- export async function credDelete(path, { client, confirm, log = () => {} }) {
236
- const { dir, cred } = locate(path);
237
- const lock = openLock(dir, client);
238
- const entry = lock.resources[credentialKey(cred)];
239
- if (!entry) throw new DeployError(`${cred.file} has no credential in ${LOCK_FILE}; there's nothing to delete`);
240
-
241
- if (!(await confirm(`Delete credential "${cred.name}" (${entry.id})? Its tokens are gone for good.`))) {
242
- log("Cancelled.");
243
- return;
244
- }
245
- await deleteCredential({ lock, cred, client, saveLock: (next) => writeLock(dir, next) });
246
- log(`deleted credential ${entry.id}`);
247
- }
248
-
249
- // Permanently deletes a credential, if it has one, and removes it from the lock. One that's already
250
- // gone counts as deleted. Works on a lock object, like createCredential.
251
- export async function deleteCredential({ lock, cred, client, saveLock = () => {} }) {
252
- const entry = lock.resources[credentialKey(cred)];
253
- if (!entry) return;
254
- try {
255
- await client.beta.vaults.credentials.delete(entry.id, { vault_id: entry.vault_id });
256
- } catch (err) {
257
- if (!(err instanceof Anthropic.APIError && err.status === 404)) {
258
- throw new DeployError(`couldn't delete ${entry.id} (${err.status ?? "network error"}): ${err.error?.error?.message ?? err.message}`);
259
- }
260
- }
261
- delete lock.resources[credentialKey(cred)];
262
- await saveLock(lock);
263
- }
@@ -1,17 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import { resolve } from "node:path";
3
- import { runInThisContext } from "node:vm";
4
- import { wrapToolCode } from "../lib/tools.js";
5
-
6
- // Loads a custom tool's code as a CommonJS module whose module.exports is the function.
7
- // require() resolves relative to the tool's file, so the agent folder's node_modules work.
8
- // The code runs with this process's full access, so only use this on your own machine.
9
- export function loadTool(tool) {
10
- const module = { exports: {} };
11
- const fn = runInThisContext(wrapToolCode(tool.code.source), { filename: tool.path });
12
- fn(module.exports, createRequire(tool.path), module, tool.path, resolve(tool.path, ".."));
13
- if (typeof module.exports !== "function") {
14
- throw new Error(`${tool.file}: module.exports must be a function`);
15
- }
16
- return module.exports;
17
- }
package/src/delete.js DELETED
@@ -1,25 +0,0 @@
1
- export class DeleteError extends Error {}
2
-
3
- // Agents can't be deleted, only archived: an archived agent drops out of `list`, and
4
- // there's no unarchive. `confirm(question)` resolves to true to go ahead.
5
- export async function deleteAgent(client, agentId, { confirm, log }) {
6
- const agent = await client.beta.agents.retrieve(agentId);
7
- if (agent.archived_at) throw new DeleteError(`${agentId} is already archived`);
8
- const ok = await confirm(`Archive agent "${agent.name}" (${agentId})? It can't be undone.`);
9
- if (!ok) return log("Nothing changed.");
10
- await client.beta.agents.archive(agentId);
11
- log(`Archived ${agentId}.`);
12
- }
13
-
14
- // Deletes a session and its event history for good.
15
- export async function deleteSession(client, sessionId, { confirm, log }) {
16
- const session = await client.beta.sessions.retrieve(sessionId);
17
- if (session.status === "running") {
18
- throw new DeleteError(`${sessionId} is running; wait for it to go idle, or interrupt it, then try again`);
19
- }
20
- const label = session.title ? `"${session.title}" (${sessionId})` : sessionId;
21
- const ok = await confirm(`Delete session ${label} and its history? It can't be undone.`);
22
- if (!ok) return log("Nothing changed.");
23
- await client.beta.sessions.delete(sessionId);
24
- log(`Deleted ${sessionId}.`);
25
- }