@soft-boy/agentschema 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +11 -5
  2. package/dist/bin/agentschema.d.ts +2 -0
  3. package/dist/bin/agentschema.js +333 -0
  4. package/dist/lib/channels.d.ts +74 -0
  5. package/dist/lib/channels.js +403 -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 +4 -13
  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 +127 -0
  27. package/dist/lib/tools.js +465 -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/mcp.js DELETED
@@ -1,76 +0,0 @@
1
- import { readTools, MCP_TOOLSET, mcpToolsetFile } from "../lib/tools.js";
2
- import { readInstance } from "../lib/instance.js";
3
-
4
- // Just enough of the MCP client protocol (Streamable HTTP) to ask a server for its tools.
5
-
6
- const PROTOCOL_VERSION = "2025-06-18";
7
- const TIMEOUT_MS = 10_000;
8
-
9
- // The names of the tools an MCP server offers, sorted. Returns null when the server won't say, or
10
- // can't be reached. Many only say once you've signed in, so `token` is sent if it's given.
11
- export async function listMcpTools(url, { fetch = globalThis.fetch, token, clientName = "agentschema" } = {}) {
12
- try {
13
- let sessionId = null;
14
- const send = async (message) => {
15
- const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
16
- if (sessionId) headers["mcp-session-id"] = sessionId;
17
- if (token) headers.authorization = `Bearer ${token}`;
18
- const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(message), signal: AbortSignal.timeout(TIMEOUT_MS) });
19
- sessionId = res.headers.get("mcp-session-id") ?? sessionId;
20
- if (!res.ok) throw new Error(`status ${res.status}`);
21
- return message.id === undefined ? null : parseResponse(await res.text(), message.id);
22
- };
23
-
24
- await send({
25
- jsonrpc: "2.0",
26
- id: 1,
27
- method: "initialize",
28
- params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: clientName, version: "0" } },
29
- });
30
- await send({ jsonrpc: "2.0", method: "notifications/initialized" });
31
-
32
- const names = [];
33
- let cursor;
34
- let id = 2;
35
- do {
36
- const { result } = await send({ jsonrpc: "2.0", id: id++, method: "tools/list", params: cursor ? { cursor } : {} });
37
- names.push(...result.tools.map((t) => t.name));
38
- cursor = result.nextCursor;
39
- } while (cursor);
40
- return [...new Set(names)].sort();
41
- } catch {
42
- return null;
43
- }
44
- }
45
-
46
- // The tool file for the server at `url`, now listing its tools, once there's a way to ask. Returns
47
- // { path, text }, or null if there's nothing to change: the file has a table already, so it may hold
48
- // choices worth keeping, or the agent has no file for that server, or it won't say what it offers.
49
- export async function listedMcpToolset(files, url, options = {}) {
50
- const servers = readInstance(files).agent?.data.mcp_servers;
51
- const server = Array.isArray(servers) ? servers.find((candidate) => candidate?.url === url) : null;
52
- if (!server) return null;
53
- const tool = readTools(files).tools.find((candidate) => candidate.data.type === MCP_TOOLSET && candidate.data.mcp_server_name === server.name);
54
- if (!tool || tool.rows?.length) return null;
55
-
56
- const names = await listMcpTools(url, options);
57
- if (!names?.length) return null;
58
- return { path: tool.file, text: mcpToolsetFile({ name: server.name, tools: names, permission: tool.data.default_config?.permission_policy?.type ?? "always_ask" }) };
59
- }
60
-
61
- // A response is either plain JSON, or a stream of events with the JSON in a `data:` line.
62
- function parseResponse(text, id) {
63
- const trimmed = text.trim();
64
- if (trimmed.startsWith("{")) return checked(JSON.parse(trimmed));
65
- for (const line of trimmed.split("\n")) {
66
- if (!line.startsWith("data:")) continue;
67
- const message = JSON.parse(line.slice(5));
68
- if (message.id === id) return checked(message);
69
- }
70
- throw new Error("no response");
71
- }
72
-
73
- function checked(message) {
74
- if (message.error) throw new Error(message.error.message);
75
- return message;
76
- }
package/src/oauth.js DELETED
@@ -1,215 +0,0 @@
1
- import { createHash, randomBytes } from "node:crypto";
2
- import { createServer } from "node:http";
3
- import { DeployError } from "./deploy.js";
4
-
5
- // OAuth for MCP servers, as the MCP authorization spec describes it: find the server's
6
- // authorization server from its URL, then sign in through the browser with the authorization
7
- // code flow and PKCE, receiving the code on a local port.
8
-
9
- // A DeployError, so the CLI reports it like any other failure.
10
- export class OAuthError extends DeployError {}
11
-
12
- const GOOGLE = "accounts.google.com";
13
-
14
- // Finds the OAuth endpoints for an MCP server from its URL alone.
15
- // Returns { resource, scopesSupported, issuer, authorizationEndpoint, tokenEndpoint,
16
- // registrationEndpoint, codeChallengeMethods }.
17
- export async function discover(serverUrl, { fetch = globalThis.fetch } = {}) {
18
- const url = new URL(serverUrl);
19
- const path = url.pathname.replace(/\/$/, "");
20
-
21
- // Protected resource metadata (RFC 9728): which authorization server the MCP server trusts. The
22
- // server can say where that is when it turns away a request with no token, and some put it where
23
- // the well-known addresses below wouldn't find it, so its word comes first.
24
- const hinted = await resourceMetadataHint(serverUrl, fetch);
25
- const resourceMeta =
26
- (hinted && (await getJSON(hinted, fetch))) ||
27
- (path && (await getJSON(`${url.origin}/.well-known/oauth-protected-resource${path}`, fetch))) ||
28
- (await getJSON(`${url.origin}/.well-known/oauth-protected-resource`, fetch));
29
- const issuer = resourceMeta?.authorization_servers?.[0] ?? url.origin;
30
-
31
- // Authorization server metadata (RFC 8414), or OpenID Connect discovery, which Google uses.
32
- const as = new URL(issuer);
33
- const asPath = as.pathname.replace(/\/$/, "");
34
- const candidates = [
35
- `${as.origin}/.well-known/oauth-authorization-server${asPath}`,
36
- `${as.origin}/.well-known/openid-configuration${asPath}`,
37
- ...(asPath ? [`${as.origin}${asPath}/.well-known/openid-configuration`] : []),
38
- ];
39
- let meta = null;
40
- for (const candidate of candidates) {
41
- meta = await getJSON(candidate, fetch);
42
- if (meta?.authorization_endpoint && meta?.token_endpoint) break;
43
- meta = null;
44
- }
45
- if (!meta) {
46
- throw new OAuthError(`couldn't find the OAuth sign-in for ${serverUrl}: ${issuer} publishes no authorization server metadata`);
47
- }
48
-
49
- return {
50
- resource: resourceMeta?.resource ?? null,
51
- scopesSupported: resourceMeta?.scopes_supported ?? meta.scopes_supported ?? [],
52
- issuer: meta.issuer ?? issuer,
53
- authorizationEndpoint: meta.authorization_endpoint,
54
- tokenEndpoint: meta.token_endpoint,
55
- registrationEndpoint: meta.registration_endpoint ?? null,
56
- codeChallengeMethods: meta.code_challenge_methods_supported ?? null,
57
- };
58
- }
59
-
60
- // Where the MCP server's 401 says its protected resource metadata is: the resource_metadata
61
- // parameter of its WWW-Authenticate header. Returns null when it doesn't say.
62
- async function resourceMetadataHint(serverUrl, fetch) {
63
- try {
64
- const res = await fetch(serverUrl, {
65
- method: "POST",
66
- headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
67
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "agentschema", version: "0" } } }),
68
- signal: AbortSignal.timeout(10_000),
69
- });
70
- if (res.status !== 401) return null;
71
- const match = /\bresource_metadata\s*=\s*(?:"([^"]*)"|([^\s,]+))/i.exec(res.headers.get("www-authenticate") ?? "");
72
- const hint = match?.[1] ?? match?.[2];
73
- return hint && URL.canParse(hint) ? hint : null;
74
- } catch {
75
- return null;
76
- }
77
- }
78
-
79
- async function getJSON(url, fetch) {
80
- try {
81
- const res = await fetch(url, { headers: { accept: "application/json" } });
82
- if (!res.ok) return null;
83
- return await res.json();
84
- } catch {
85
- return null;
86
- }
87
- }
88
-
89
- // Starts the local server the browser is sent back to after signing in.
90
- // Returns { redirectUri, waitForCode(state, timeoutMs), close() }.
91
- export async function startCallbackServer(port = 0) {
92
- let deliver;
93
- const received = new Promise((resolve) => (deliver = resolve));
94
- const server = createServer((req, res) => {
95
- const url = new URL(req.url, "http://127.0.0.1");
96
- if (url.pathname !== "/callback") {
97
- res.writeHead(404).end();
98
- return;
99
- }
100
- const error = url.searchParams.get("error");
101
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
102
- res.end(
103
- `<!doctype html><title>agentschema</title><body style="font:16px system-ui;margin:4em auto;max-width:30em">` +
104
- (error ? `<h1>Sign-in failed</h1><p>${escape(error)}. Check the terminal.</p>` : "<h1>Signed in</h1><p>You can close this tab and go back to the terminal.</p>") +
105
- "</body>",
106
- );
107
- deliver(url.searchParams);
108
- });
109
- await new Promise((resolve, reject) => {
110
- server.once("error", (err) => reject(new OAuthError(`couldn't listen on 127.0.0.1:${port}: ${err.message}`)));
111
- server.listen(port, "127.0.0.1", resolve);
112
- });
113
- const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
114
-
115
- return {
116
- redirectUri,
117
- async waitForCode(state, timeoutMs = 5 * 60_000) {
118
- let timer;
119
- const timeout = new Promise((_, reject) => {
120
- timer = setTimeout(() => reject(new OAuthError("timed out waiting for the browser sign-in")), timeoutMs);
121
- });
122
- try {
123
- const params = await Promise.race([received, timeout]);
124
- const error = params.get("error");
125
- if (error) {
126
- const detail = params.get("error_description");
127
- throw new OAuthError(`sign-in failed: ${error}${detail ? ` (${detail})` : ""}`);
128
- }
129
- if (params.get("state") !== state) throw new OAuthError("sign-in failed: the response's state didn't match");
130
- const code = params.get("code");
131
- if (!code) throw new OAuthError("sign-in failed: no authorization code came back");
132
- return code;
133
- } finally {
134
- clearTimeout(timer);
135
- }
136
- },
137
- close: () => new Promise((resolve) => server.close(resolve)),
138
- };
139
- }
140
-
141
- const escape = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
142
-
143
- // Registers as an OAuth client (RFC 7591), for servers that allow it. `clientName` is what the
144
- // provider shows on its sign-in page. Returns { clientId, clientSecret, authMethod }.
145
- export async function registerClient(registrationEndpoint, redirectUri, { fetch = globalThis.fetch, clientName = "agentschema" } = {}) {
146
- const res = await fetch(registrationEndpoint, {
147
- method: "POST",
148
- headers: { "content-type": "application/json", accept: "application/json" },
149
- body: JSON.stringify({
150
- client_name: clientName,
151
- redirect_uris: [redirectUri],
152
- grant_types: ["authorization_code", "refresh_token"],
153
- response_types: ["code"],
154
- token_endpoint_auth_method: "none",
155
- }),
156
- });
157
- const body = await res.json().catch(() => ({}));
158
- if (!res.ok || !body.client_id) {
159
- throw new OAuthError(`couldn't register a client at ${registrationEndpoint} (${res.status}): ${body.error_description ?? body.error ?? "no client_id in the response"}`);
160
- }
161
- return {
162
- clientId: body.client_id,
163
- clientSecret: body.client_secret ?? null,
164
- authMethod: body.token_endpoint_auth_method ?? (body.client_secret ? "client_secret_post" : "none"),
165
- };
166
- }
167
-
168
- // The URL to send the browser to, and the PKCE verifier and state to finish with.
169
- export function authorizationRequest({ authorizationEndpoint, issuer, clientId, redirectUri, scope, resource }) {
170
- const verifier = base64url(randomBytes(32));
171
- const state = base64url(randomBytes(16));
172
- const url = new URL(authorizationEndpoint);
173
- const params = {
174
- response_type: "code",
175
- client_id: clientId,
176
- redirect_uri: redirectUri,
177
- code_challenge: base64url(createHash("sha256").update(verifier).digest()),
178
- code_challenge_method: "S256",
179
- state,
180
- };
181
- if (scope) params.scope = scope;
182
- if (resource) params.resource = resource;
183
- // Google only issues a refresh token for offline access, and only on a fresh consent.
184
- if (new URL(issuer).host === GOOGLE) Object.assign(params, { access_type: "offline", prompt: "consent" });
185
- for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
186
- return { url: url.toString(), verifier, state };
187
- }
188
-
189
- // Trades the authorization code for tokens.
190
- // Returns { accessToken, refreshToken, expiresAt, scope }.
191
- export async function exchangeCode({ tokenEndpoint, code, verifier, redirectUri, clientId, clientSecret, authMethod, resource }, { fetch = globalThis.fetch } = {}) {
192
- const form = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, code_verifier: verifier });
193
- if (resource) form.set("resource", resource);
194
- const headers = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
195
- if (authMethod === "client_secret_basic") {
196
- headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString("base64")}`;
197
- } else {
198
- form.set("client_id", clientId);
199
- if (authMethod === "client_secret_post") form.set("client_secret", clientSecret);
200
- }
201
-
202
- const res = await fetch(tokenEndpoint, { method: "POST", headers, body: form });
203
- const body = await res.json().catch(() => ({}));
204
- if (!res.ok || !body.access_token) {
205
- throw new OAuthError(`the token endpoint refused the sign-in (${res.status}): ${body.error_description ?? body.error ?? "no access token in the response"}`);
206
- }
207
- return {
208
- accessToken: body.access_token,
209
- refreshToken: body.refresh_token ?? null,
210
- expiresAt: body.expires_in ? new Date(Date.now() + Number(body.expires_in) * 1000).toISOString() : null,
211
- scope: body.scope ?? null,
212
- };
213
- }
214
-
215
- const base64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
package/src/prompts.js DELETED
@@ -1,159 +0,0 @@
1
- import { createInterface, emitKeypressEvents } from "node:readline";
2
-
3
- // Interactive questions, shared by `init` and `cred create`. In a terminal, choices are picked
4
- // with the arrow keys and secrets aren't echoed; with piped input, each answer is a line.
5
- //
6
- // text(question, fallback, { validate }) an empty reply keeps the fallback; validate returns
7
- // an error message, or nothing when the reply is fine
8
- // select(question, choices, fallback) one of `choices` (strings)
9
- // confirm(question, fallback) true or false
10
- // secret(question) a reply that isn't shown
11
- // close()
12
- //
13
- // Ctrl+C rejects with the error `cancelled()` returns.
14
- export function prompts(input, output, { cancelled = () => new Error("cancelled") } = {}) {
15
- const base = input.isTTY ? terminalPrompts(input, output, cancelled) : linePrompts(input, output, cancelled);
16
-
17
- const text = async (question, fallback = "", { validate } = {}) => {
18
- while (true) {
19
- const reply = await base.text(question, fallback);
20
- const problem = validate?.(reply);
21
- if (!problem) return reply;
22
- output.write(`${problem}\n`);
23
- if (base.ended?.()) throw cancelled();
24
- }
25
- };
26
- const confirm = async (question, fallback) => {
27
- while (true) {
28
- const reply = (await base.text(`${question} [y/n]`, fallback ? "y" : "n")).toLowerCase();
29
- if (/^(y|yes)$/.test(reply)) return true;
30
- if (/^(n|no)$/.test(reply)) return false;
31
- output.write("Answer y or n\n");
32
- }
33
- };
34
- return { ...base, text, confirm };
35
- }
36
-
37
- // Prompts for piped input: one answer per line, and choices picked by name or number.
38
- function linePrompts(input, output, cancelled) {
39
- const rl = createInterface({ input, output, terminal: false });
40
- const lines = rl[Symbol.asyncIterator]();
41
- let ended = false;
42
-
43
- const line = async () => {
44
- if (ended) return null;
45
- const { value, done } = await lines.next();
46
- if (done) {
47
- ended = true;
48
- output.write("\n");
49
- return null;
50
- }
51
- return value.trim();
52
- };
53
- const text = async (question, fallback) => {
54
- output.write(fallback ? `${question} (${fallback}) ` : `${question} `);
55
- return (await line()) || fallback;
56
- };
57
- const select = async (question, choices, fallback) => {
58
- const listed = choices.map((c, i) => `${i + 1}) ${c}`).join(" ");
59
- while (true) {
60
- const reply = await text(`${question} ${listed}`, String(choices.indexOf(fallback) + 1 || 1));
61
- const picked = choices[Number(reply) - 1] ?? choices.find((c) => c === reply);
62
- if (picked) return picked;
63
- output.write(`Pick one of: ${choices.join(", ")}\n`);
64
- if (ended) throw cancelled();
65
- }
66
- };
67
- const secret = async (question) => {
68
- output.write(`${question} `);
69
- const reply = await line();
70
- if (reply === null) throw cancelled();
71
- return reply;
72
- };
73
- return { text, select, secret, ended: () => ended, close: () => rl.close() };
74
- }
75
-
76
- const ESC = "\x1b[";
77
- const cyan = (s) => `${ESC}36m${s}${ESC}0m`;
78
- const dim = (s) => `${ESC}2m${s}${ESC}0m`;
79
-
80
- // Prompts for a terminal: choices are picked with the arrow keys and Enter.
81
- function terminalPrompts(input, output, cancelled) {
82
- // A fresh readline per question, so it doesn't fight the raw-mode select for the arrow keys.
83
- const text = (question, fallback) =>
84
- new Promise((resolve, reject) => {
85
- const rl = createInterface({ input, output, terminal: true });
86
- rl.on("SIGINT", () => {
87
- rl.close();
88
- output.write("\n");
89
- reject(cancelled());
90
- });
91
- rl.question(fallback ? `${question} ${dim(`(${fallback})`)} ` : `${question} `, (reply) => {
92
- rl.close();
93
- resolve(reply.trim() || fallback);
94
- });
95
- });
96
-
97
- const select = (question, choices, fallback) =>
98
- new Promise((resolve, reject) => {
99
- let index = Math.max(0, choices.indexOf(fallback));
100
- const render = (first) => {
101
- if (!first) output.write(`${ESC}${choices.length}A`);
102
- for (const [i, choice] of choices.entries()) {
103
- output.write(`${ESC}2K${i === index ? cyan(`❯ ${choice}`) : ` ${choice}`}\n`);
104
- }
105
- };
106
- const finish = (err) => {
107
- input.off("keypress", onKey);
108
- input.setRawMode(false);
109
- input.pause();
110
- // Collapse the list to one line with the answer.
111
- output.write(`${ESC}${choices.length + 1}A${ESC}J${ESC}?25h`);
112
- output.write(`${question} ${err ? dim("cancelled") : cyan(choices[index])}\n`);
113
- err ? reject(err) : resolve(choices[index]);
114
- };
115
- const onKey = (str, key = {}) => {
116
- if (key.ctrl && key.name === "c") return finish(cancelled());
117
- if (key.name === "return" || key.name === "enter") return finish();
118
- if (key.name === "up" || key.name === "k") index = (index - 1 + choices.length) % choices.length;
119
- else if (key.name === "down" || key.name === "j" || key.name === "tab") index = (index + 1) % choices.length;
120
- else if (/^[1-9]$/.test(str ?? "") && Number(str) <= choices.length) index = Number(str) - 1;
121
- else return;
122
- render(false);
123
- };
124
-
125
- emitKeypressEvents(input);
126
- input.setRawMode(true);
127
- input.resume();
128
- output.write(`${question} ${dim("(↑/↓, Enter)")}\n${ESC}?25l`);
129
- render(true);
130
- input.on("keypress", onKey);
131
- });
132
-
133
- // Not echoed, so the secret doesn't end up on screen or in the scrollback; pasting works.
134
- const secret = (question) =>
135
- new Promise((resolve, reject) => {
136
- output.write(`${question} ${dim("(hidden)")} `);
137
- input.setRawMode(true);
138
- input.resume();
139
- let answer = "";
140
- const finish = (err) => {
141
- input.off("data", onData);
142
- input.setRawMode(false);
143
- input.pause();
144
- output.write("\n");
145
- err ? reject(err) : resolve(answer.trim());
146
- };
147
- const onData = (chunk) => {
148
- for (const ch of chunk.toString("utf8")) {
149
- if (ch === "\r" || ch === "\n") return finish();
150
- if (ch === "\u0003") return finish(cancelled());
151
- if (ch === "\u007f" || ch === "\b") answer = answer.slice(0, -1);
152
- else if (ch >= " ") answer += ch;
153
- }
154
- };
155
- input.on("data", onData);
156
- });
157
-
158
- return { text, select, secret, close() {} };
159
- }
package/src/session.js DELETED
@@ -1,194 +0,0 @@
1
- import { join } from "node:path";
2
- import { AGENT_FILE, agentBody, envBody, environmentEntry } from "../lib/instance.js";
3
- import { SYSTEM_PROMPT_DIR } from "../lib/system-prompt.js";
4
- import { skillKey, skillRefs } from "../lib/skills.js";
5
- import { TOOLS_DIR } from "../lib/tools.js";
6
- import { credentialKey, vaultKey } from "../lib/vaults.js";
7
- import { check } from "./check.js";
8
- import { LOCK_FILE, hashBody, readLock, skillFingerprint } from "./lock.js";
9
-
10
- export class SessionError extends Error {}
11
-
12
- // Starts a session on the agent and environment recorded in claude-lock.json, or resumes `sessionId`.
13
- // Returns { session, notes }: notes are warnings worth showing, such as files changed since the last deploy.
14
- export async function openSession(dir, { client, sessionId }) {
15
- if (sessionId) {
16
- const session = await client.beta.sessions.retrieve(sessionId);
17
- if (session.status === "terminated") throw new SessionError(`session ${sessionId} has terminated`);
18
- return { session, notes: [] };
19
- }
20
-
21
- const lock = readLock(dir);
22
- const agent = lock?.resources?.[`./${AGENT_FILE}`];
23
- const env = environmentEntry(lock);
24
- if (!agent || !env) {
25
- throw new SessionError(`${dir} hasn't been deployed (no agent or environment in ${LOCK_FILE}); run agentschema deploy first`);
26
- }
27
-
28
- const notes = [];
29
- const { instance, errors } = check(dir);
30
- if (instance && errors.length === 0) {
31
- if (hashBody(agentBody(instance, skillRefs(instance.skills, lock))) !== agent.hash) {
32
- notes.push(`${AGENT_FILE}, ${SYSTEM_PROMPT_DIR}/ or ${TOOLS_DIR}/ has changed since the last deploy`);
33
- }
34
- for (const skill of instance.skills) {
35
- if (hashBody(skillFingerprint(skill)) !== lock.resources[skillKey(skill)]?.hash) notes.push(`${skill.path} has changed since the last deploy`);
36
- }
37
- if (hashBody(envBody(instance)) !== env.hash) notes.push(`${instance.env.file} has changed since the last deploy`);
38
- if (notes.length > 0) notes.push(`this session uses the deployed version; run agentschema deploy to pick up the changes`);
39
- }
40
-
41
- const name = instance?.agent.data.name;
42
- const started = await startSession({
43
- instance,
44
- lock,
45
- client,
46
- title: name ? `${name} (agentschema run)` : "agentschema run",
47
- pathOf: (file) => join(dir, file),
48
- });
49
- return { session: started.session, notes: [...notes, ...started.notes] };
50
- }
51
-
52
- // Starts a session from a lock, pinned to a deployed version, so it runs exactly what deploy sent.
53
- //
54
- // instance the checked files, for finding the vaults to attach
55
- // agentVersion the agent version to pin, instead of the lock's latest
56
- // system the system prompt for this session only, such as with a channel's instructions added
57
- // budget the API's session budget, to cap what the session can spend
58
- // pathOf how to show a file's path to the user in messages
59
- //
60
- // Returns { session, notes }.
61
- export async function startSession({ instance, lock, client, agentVersion, system, title, budget, pathOf = (file) => file }) {
62
- const agent = lock?.resources?.[`./${AGENT_FILE}`];
63
- const env = environmentEntry(lock);
64
- if (!agent || !env) throw new SessionError("this agent hasn't been deployed (no agent or environment in its lock)");
65
-
66
- const pinned = { id: agent.id, version: Number(agentVersion ?? agent.version) };
67
- const params = {
68
- // Overriding affects this session only, and doesn't change the agent or make a new version of it.
69
- agent: system === undefined ? { type: "agent", ...pinned } : { type: "agent_with_overrides", ...pinned, system },
70
- environment_id: env.id,
71
- };
72
-
73
- // Every deployed vault in vaults/, in name order: when two hold a credential for the same
74
- // server, the first one wins.
75
- const notes = [];
76
- const vaultIds = [];
77
- for (const vault of instance?.vaults ?? []) {
78
- const entry = lock.resources[vaultKey(vault)];
79
- if (!entry) {
80
- notes.push(`vault ${vault.path} hasn't been deployed, so this session doesn't have it; run agentschema deploy`);
81
- continue;
82
- }
83
- vaultIds.push(entry.id);
84
- for (const cred of vault.credentials) {
85
- const credEntry = lock.resources[credentialKey(cred)];
86
- if (!credEntry || credEntry.vault_id !== entry.id) {
87
- notes.push(`credential ${cred.file} hasn't been created; run agentschema cred deploy ${pathOf(cred.file)}`);
88
- }
89
- }
90
- }
91
- if (vaultIds.length > 0) params.vault_ids = vaultIds;
92
- if (title) params.title = title;
93
- if (budget) params.budget = budget;
94
- return { session: await client.beta.sessions.create(params), notes };
95
- }
96
-
97
- // Drives a session one turn at a time. `ui` answers what only a person can:
98
- // ui.event(event) show an event, including the stream-only event_start / event_delta previews
99
- // ui.confirm(event) -> { result: "allow" | "deny", deny_message? } for a paused tool call
100
- // ui.customToolResult(event) -> string, or { text, isError }: the result of a custom tool call
101
- export class Conversation {
102
- constructor(client, sessionId, ui) {
103
- this.client = client;
104
- this.sessionId = sessionId;
105
- this.ui = ui;
106
- this.seen = new Set();
107
- this.stream = null;
108
- }
109
-
110
- // Sends a message and handles events until the agent finishes its turn.
111
- // Returns the idle stop reason, or "terminated".
112
- async send(text) {
113
- return this.#turn([{ type: "user.message", content: [{ type: "text", text }] }]);
114
- }
115
-
116
- // Asks the agent to stop at the next safe point; the running turn then ends normally.
117
- async interrupt() {
118
- await this.client.beta.sessions.events.send(this.sessionId, { events: [{ type: "user.interrupt" }] });
119
- }
120
-
121
- async #turn(events) {
122
- // Stream first: events emitted before the stream opens would never reach us.
123
- this.stream = await this.#openStream();
124
- await this.client.beta.sessions.events.send(this.sessionId, { events });
125
-
126
- for (let attempt = 0; ; attempt++) {
127
- try {
128
- for await (const event of this.stream) {
129
- const done = await this.#handle(event);
130
- if (done) return done;
131
- }
132
- throw new Error("event stream closed");
133
- } catch (err) {
134
- if (this.closed || attempt >= 3) throw err;
135
- // The stream has no replay: reopen it, then catch up from the event history.
136
- this.stream = await this.#openStream();
137
- for await (const event of this.client.beta.sessions.events.list(this.sessionId)) {
138
- const done = await this.#handle(event);
139
- if (done) return done;
140
- }
141
- }
142
- }
143
- }
144
-
145
- // Opts in to live previews, so agent text arrives as event_start / event_delta events while
146
- // the model is still writing, ahead of the complete agent.message.
147
- #openStream() {
148
- return this.client.beta.sessions.events.stream(this.sessionId, { event_deltas: ["agent.message"] });
149
- }
150
-
151
- // Returns a value when the turn is over.
152
- async #handle(event) {
153
- // Events are deduped by ID: the history and the live stream overlap after a reconnect,
154
- // and a queued user event is echoed twice.
155
- if (event.id) {
156
- if (this.seen.has(event.id)) return null;
157
- this.seen.add(event.id);
158
- }
159
- this.ui.event(event);
160
-
161
- const send = (e) => this.client.beta.sessions.events.send(this.sessionId, { events: [e] });
162
- switch (event.type) {
163
- case "agent.tool_use":
164
- case "agent.mcp_tool_use":
165
- if (event.evaluated_permission === "ask") {
166
- const { result, deny_message } = await this.ui.confirm(event);
167
- const reply = { type: "user.tool_confirmation", tool_use_id: event.id, result };
168
- if (result === "deny" && deny_message) reply.deny_message = deny_message;
169
- await send(reply);
170
- }
171
- return null;
172
- case "agent.custom_tool_use": {
173
- const result = await this.ui.customToolResult(event);
174
- const { text, isError } = typeof result === "string" ? { text: result } : result;
175
- const reply = { type: "user.custom_tool_result", custom_tool_use_id: event.id, content: [{ type: "text", text }] };
176
- if (isError) reply.is_error = true;
177
- await send(reply);
178
- return null;
179
- }
180
- case "session.status_idle":
181
- // requires_action means the session is waiting on one of the replies above.
182
- return event.stop_reason?.type === "requires_action" ? null : (event.stop_reason?.type ?? "end_turn");
183
- case "session.status_terminated":
184
- return "terminated";
185
- default:
186
- return null;
187
- }
188
- }
189
-
190
- close() {
191
- this.closed = true;
192
- this.stream?.controller?.abort();
193
- }
194
- }