@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/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
+ }
package/src/oauth.js ADDED
@@ -0,0 +1,192 @@
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.
22
+ const resourceMeta =
23
+ (path && (await getJSON(`${url.origin}/.well-known/oauth-protected-resource${path}`, fetch))) ||
24
+ (await getJSON(`${url.origin}/.well-known/oauth-protected-resource`, fetch));
25
+ const issuer = resourceMeta?.authorization_servers?.[0] ?? url.origin;
26
+
27
+ // Authorization server metadata (RFC 8414), or OpenID Connect discovery, which Google uses.
28
+ const as = new URL(issuer);
29
+ const asPath = as.pathname.replace(/\/$/, "");
30
+ const candidates = [
31
+ `${as.origin}/.well-known/oauth-authorization-server${asPath}`,
32
+ `${as.origin}/.well-known/openid-configuration${asPath}`,
33
+ ...(asPath ? [`${as.origin}${asPath}/.well-known/openid-configuration`] : []),
34
+ ];
35
+ let meta = null;
36
+ for (const candidate of candidates) {
37
+ meta = await getJSON(candidate, fetch);
38
+ if (meta?.authorization_endpoint && meta?.token_endpoint) break;
39
+ meta = null;
40
+ }
41
+ if (!meta) {
42
+ throw new OAuthError(`couldn't find the OAuth sign-in for ${serverUrl}: ${issuer} publishes no authorization server metadata`);
43
+ }
44
+
45
+ return {
46
+ resource: resourceMeta?.resource ?? null,
47
+ scopesSupported: resourceMeta?.scopes_supported ?? meta.scopes_supported ?? [],
48
+ issuer: meta.issuer ?? issuer,
49
+ authorizationEndpoint: meta.authorization_endpoint,
50
+ tokenEndpoint: meta.token_endpoint,
51
+ registrationEndpoint: meta.registration_endpoint ?? null,
52
+ codeChallengeMethods: meta.code_challenge_methods_supported ?? null,
53
+ };
54
+ }
55
+
56
+ async function getJSON(url, fetch) {
57
+ try {
58
+ const res = await fetch(url, { headers: { accept: "application/json" } });
59
+ if (!res.ok) return null;
60
+ return await res.json();
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ // Starts the local server the browser is sent back to after signing in.
67
+ // Returns { redirectUri, waitForCode(state, timeoutMs), close() }.
68
+ export async function startCallbackServer(port = 0) {
69
+ let deliver;
70
+ const received = new Promise((resolve) => (deliver = resolve));
71
+ const server = createServer((req, res) => {
72
+ const url = new URL(req.url, "http://127.0.0.1");
73
+ if (url.pathname !== "/callback") {
74
+ res.writeHead(404).end();
75
+ return;
76
+ }
77
+ const error = url.searchParams.get("error");
78
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
79
+ res.end(
80
+ `<!doctype html><title>agentschema</title><body style="font:16px system-ui;margin:4em auto;max-width:30em">` +
81
+ (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>") +
82
+ "</body>",
83
+ );
84
+ deliver(url.searchParams);
85
+ });
86
+ await new Promise((resolve, reject) => {
87
+ server.once("error", (err) => reject(new OAuthError(`couldn't listen on 127.0.0.1:${port}: ${err.message}`)));
88
+ server.listen(port, "127.0.0.1", resolve);
89
+ });
90
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
91
+
92
+ return {
93
+ redirectUri,
94
+ async waitForCode(state, timeoutMs = 5 * 60_000) {
95
+ let timer;
96
+ const timeout = new Promise((_, reject) => {
97
+ timer = setTimeout(() => reject(new OAuthError("timed out waiting for the browser sign-in")), timeoutMs);
98
+ });
99
+ try {
100
+ const params = await Promise.race([received, timeout]);
101
+ const error = params.get("error");
102
+ if (error) {
103
+ const detail = params.get("error_description");
104
+ throw new OAuthError(`sign-in failed: ${error}${detail ? ` (${detail})` : ""}`);
105
+ }
106
+ if (params.get("state") !== state) throw new OAuthError("sign-in failed: the response's state didn't match");
107
+ const code = params.get("code");
108
+ if (!code) throw new OAuthError("sign-in failed: no authorization code came back");
109
+ return code;
110
+ } finally {
111
+ clearTimeout(timer);
112
+ }
113
+ },
114
+ close: () => new Promise((resolve) => server.close(resolve)),
115
+ };
116
+ }
117
+
118
+ const escape = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
119
+
120
+ // Registers agentschema as an OAuth client (RFC 7591), for servers that allow it.
121
+ // Returns { clientId, clientSecret, authMethod }.
122
+ export async function registerClient(registrationEndpoint, redirectUri, { fetch = globalThis.fetch } = {}) {
123
+ const res = await fetch(registrationEndpoint, {
124
+ method: "POST",
125
+ headers: { "content-type": "application/json", accept: "application/json" },
126
+ body: JSON.stringify({
127
+ client_name: "agentschema",
128
+ redirect_uris: [redirectUri],
129
+ grant_types: ["authorization_code", "refresh_token"],
130
+ response_types: ["code"],
131
+ token_endpoint_auth_method: "none",
132
+ }),
133
+ });
134
+ const body = await res.json().catch(() => ({}));
135
+ if (!res.ok || !body.client_id) {
136
+ throw new OAuthError(`couldn't register a client at ${registrationEndpoint} (${res.status}): ${body.error_description ?? body.error ?? "no client_id in the response"}`);
137
+ }
138
+ return {
139
+ clientId: body.client_id,
140
+ clientSecret: body.client_secret ?? null,
141
+ authMethod: body.token_endpoint_auth_method ?? (body.client_secret ? "client_secret_post" : "none"),
142
+ };
143
+ }
144
+
145
+ // The URL to send the browser to, and the PKCE verifier and state to finish with.
146
+ export function authorizationRequest({ authorizationEndpoint, issuer, clientId, redirectUri, scope, resource }) {
147
+ const verifier = base64url(randomBytes(32));
148
+ const state = base64url(randomBytes(16));
149
+ const url = new URL(authorizationEndpoint);
150
+ const params = {
151
+ response_type: "code",
152
+ client_id: clientId,
153
+ redirect_uri: redirectUri,
154
+ code_challenge: base64url(createHash("sha256").update(verifier).digest()),
155
+ code_challenge_method: "S256",
156
+ state,
157
+ };
158
+ if (scope) params.scope = scope;
159
+ if (resource) params.resource = resource;
160
+ // Google only issues a refresh token for offline access, and only on a fresh consent.
161
+ if (new URL(issuer).host === GOOGLE) Object.assign(params, { access_type: "offline", prompt: "consent" });
162
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
163
+ return { url: url.toString(), verifier, state };
164
+ }
165
+
166
+ // Trades the authorization code for tokens.
167
+ // Returns { accessToken, refreshToken, expiresAt, scope }.
168
+ export async function exchangeCode({ tokenEndpoint, code, verifier, redirectUri, clientId, clientSecret, authMethod, resource }, { fetch = globalThis.fetch } = {}) {
169
+ const form = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, code_verifier: verifier });
170
+ if (resource) form.set("resource", resource);
171
+ const headers = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
172
+ if (authMethod === "client_secret_basic") {
173
+ headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString("base64")}`;
174
+ } else {
175
+ form.set("client_id", clientId);
176
+ if (authMethod === "client_secret_post") form.set("client_secret", clientSecret);
177
+ }
178
+
179
+ const res = await fetch(tokenEndpoint, { method: "POST", headers, body: form });
180
+ const body = await res.json().catch(() => ({}));
181
+ if (!res.ok || !body.access_token) {
182
+ throw new OAuthError(`the token endpoint refused the sign-in (${res.status}): ${body.error_description ?? body.error ?? "no access token in the response"}`);
183
+ }
184
+ return {
185
+ accessToken: body.access_token,
186
+ refreshToken: body.refresh_token ?? null,
187
+ expiresAt: body.expires_in ? new Date(Date.now() + Number(body.expires_in) * 1000).toISOString() : null,
188
+ scope: body.scope ?? null,
189
+ };
190
+ }
191
+
192
+ const base64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
package/src/prompts.js ADDED
@@ -0,0 +1,159 @@
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 CHANGED
@@ -1,7 +1,10 @@
1
+ import { join } from "node:path";
1
2
  import { check } from "./check.js";
2
3
  import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
3
4
  import { LOCK_FILE, hashBody, readLock } from "./lock.js";
5
+ import { skillFingerprint, skillKey, skillRefs } from "./skills.js";
4
6
  import { TOOLS_DIR } from "./tools.js";
7
+ import { credentialKey, vaultKey } from "./vaults.js";
5
8
 
6
9
  export class SessionError extends Error {}
7
10
 
@@ -24,7 +27,12 @@ export async function openSession(dir, { client, sessionId }) {
24
27
  const notes = [];
25
28
  const { instance, errors } = check(dir);
26
29
  if (instance && errors.length === 0) {
27
- if (hashBody(agentBody(instance)) !== agent.hash) notes.push(`${AGENT_FILE} or ${TOOLS_DIR}/ has changed since the last deploy`);
30
+ if (hashBody(agentBody(instance, skillRefs(instance.skills, lock))) !== agent.hash) {
31
+ notes.push(`${AGENT_FILE} or ${TOOLS_DIR}/ has changed since the last deploy`);
32
+ }
33
+ for (const skill of instance.skills) {
34
+ if (hashBody(skillFingerprint(skill)) !== lock.resources[skillKey(skill)]?.hash) notes.push(`${skill.path} has changed since the last deploy`);
35
+ }
28
36
  if (hashBody(envBody(instance)) !== env.hash) notes.push(`${ENV_FILE} has changed since the last deploy`);
29
37
  if (notes.length > 0) notes.push(`this session uses the deployed version; run agentschema deploy to pick up the changes`);
30
38
  }
@@ -34,13 +42,32 @@ export async function openSession(dir, { client, sessionId }) {
34
42
  agent: { type: "agent", id: agent.id, version: Number(agent.version) },
35
43
  environment_id: env.id,
36
44
  };
45
+
46
+ // Every deployed vault in vaults/, in name order: when two hold a credential for the same
47
+ // server, the first one wins.
48
+ const vaultIds = [];
49
+ for (const vault of instance?.vaults ?? []) {
50
+ const entry = lock.resources[vaultKey(vault)];
51
+ if (!entry) {
52
+ notes.push(`vault ${vault.path} hasn't been deployed, so this session doesn't have it; run agentschema deploy`);
53
+ continue;
54
+ }
55
+ vaultIds.push(entry.id);
56
+ for (const cred of vault.credentials) {
57
+ const credEntry = lock.resources[credentialKey(cred)];
58
+ if (!credEntry || credEntry.vault_id !== entry.id) {
59
+ notes.push(`credential ${cred.file} hasn't been created; run agentschema cred deploy ${join(dir, cred.file)}`);
60
+ }
61
+ }
62
+ }
63
+ if (vaultIds.length > 0) params.vault_ids = vaultIds;
37
64
  const name = instance?.agent.data.name;
38
65
  params.title = name ? `${name} (agentschema run)` : "agentschema run";
39
66
  return { session: await client.beta.sessions.create(params), notes };
40
67
  }
41
68
 
42
69
  // Drives a session one turn at a time. `ui` answers what only a person can:
43
- // ui.event(event) show an event
70
+ // ui.event(event) show an event, including the stream-only event_start / event_delta previews
44
71
  // ui.confirm(event) -> { result: "allow" | "deny", deny_message? } for a paused tool call
45
72
  // ui.customToolResult(event) -> string, or { text, isError }: the result of a custom tool call
46
73
  export class Conversation {
@@ -65,7 +92,7 @@ export class Conversation {
65
92
 
66
93
  async #turn(events) {
67
94
  // Stream first: events emitted before the stream opens would never reach us.
68
- this.stream = await this.client.beta.sessions.events.stream(this.sessionId);
95
+ this.stream = await this.#openStream();
69
96
  await this.client.beta.sessions.events.send(this.sessionId, { events });
70
97
 
71
98
  for (let attempt = 0; ; attempt++) {
@@ -78,7 +105,7 @@ export class Conversation {
78
105
  } catch (err) {
79
106
  if (this.closed || attempt >= 3) throw err;
80
107
  // The stream has no replay: reopen it, then catch up from the event history.
81
- this.stream = await this.client.beta.sessions.events.stream(this.sessionId);
108
+ this.stream = await this.#openStream();
82
109
  for await (const event of this.client.beta.sessions.events.list(this.sessionId)) {
83
110
  const done = await this.#handle(event);
84
111
  if (done) return done;
@@ -87,6 +114,12 @@ export class Conversation {
87
114
  }
88
115
  }
89
116
 
117
+ // Opts in to live previews, so agent text arrives as event_start / event_delta events while
118
+ // the model is still writing, ahead of the complete agent.message.
119
+ #openStream() {
120
+ return this.client.beta.sessions.events.stream(this.sessionId, { event_deltas: ["agent.message"] });
121
+ }
122
+
90
123
  // Returns a value when the turn is over.
91
124
  async #handle(event) {
92
125
  // Events are deduped by ID: the history and the live stream overlap after a reconnect,
package/src/skills.js ADDED
@@ -0,0 +1,79 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { FileError, parseMarkdown } from "./markdown.js";
5
+
6
+ export const SKILLS_DIR = "skills";
7
+ export const SKILL_FILE = "SKILL.md";
8
+ export const MAX_UPLOAD_BYTES = 30 * 1024 * 1024;
9
+
10
+ // Reads skills/: each folder is a skill, with a SKILL.md at its top and any other files it needs,
11
+ // at any depth. Hidden files and node_modules are left out. Skills are sorted by name. A missing
12
+ // skills/ folder means no skills.
13
+ // Returns { skills, errors }; a skill that can't be read has an entry in errors.
14
+ export function readSkills(dir) {
15
+ const folder = join(dir, SKILLS_DIR);
16
+ try {
17
+ if (!statSync(folder).isDirectory()) return { skills: [], errors: [`${SKILLS_DIR}: not a directory`] };
18
+ } catch {
19
+ return { skills: [], errors: [] };
20
+ }
21
+
22
+ const skills = [];
23
+ const errors = [];
24
+ for (const entry of sorted(readdirSync(folder, { withFileTypes: true }))) {
25
+ if (entry.name.startsWith(".")) continue;
26
+ const path = `${SKILLS_DIR}/${entry.name}`;
27
+ if (!entry.isDirectory()) {
28
+ if (entry.name.endsWith(".md")) errors.push(`${path}: each skill is a folder, like ${SKILLS_DIR}/my-skill/${SKILL_FILE}`);
29
+ continue;
30
+ }
31
+
32
+ const files = skillFiles(join(folder, entry.name), "");
33
+ // Compare exact names: macOS file systems would otherwise open skill.md as SKILL.md.
34
+ const main = files.find((f) => f.rel === SKILL_FILE);
35
+ if (!main) {
36
+ const wrongCase = files.find((f) => f.rel.toLowerCase() === SKILL_FILE.toLowerCase());
37
+ errors.push(`${path}: missing ${SKILL_FILE}${wrongCase ? ` (found ${wrongCase.rel}; the name must be uppercase)` : ""}`);
38
+ continue;
39
+ }
40
+ try {
41
+ const parsed = parseMarkdown(main.bytes.toString("utf8"), `${path}/${SKILL_FILE}`);
42
+ skills.push({ name: entry.name, path, file: `${path}/${SKILL_FILE}`, files, ...parsed });
43
+ } catch (err) {
44
+ if (!(err instanceof FileError)) throw err;
45
+ errors.push(err.message);
46
+ }
47
+ }
48
+ return { skills, errors };
49
+ }
50
+
51
+ function skillFiles(folder, prefix) {
52
+ const files = [];
53
+ for (const entry of sorted(readdirSync(folder, { withFileTypes: true }))) {
54
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
55
+ const rel = `${prefix}${entry.name}`;
56
+ if (entry.isDirectory()) files.push(...skillFiles(join(folder, entry.name), `${rel}/`));
57
+ else if (entry.isFile()) files.push({ rel, bytes: readFileSync(join(folder, entry.name)) });
58
+ }
59
+ return files;
60
+ }
61
+
62
+ const sorted = (entries) => entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
63
+
64
+ // The lock file key for a skill.
65
+ export const skillKey = (skill) => `./${skill.path}`;
66
+
67
+ // What's hashed into the lock: each file's path and contents, so any change makes a new version.
68
+ export function skillFingerprint(skill) {
69
+ return { files: skill.files.map((f) => [f.rel, createHash("sha256").update(f.bytes).digest("hex")]) };
70
+ }
71
+
72
+ // The agent's references to the skills deployed from this folder, pinned to their versions, so
73
+ // that a session runs exactly what deploy last sent.
74
+ export function skillRefs(skills = [], lock) {
75
+ return skills
76
+ .map((skill) => lock?.resources?.[skillKey(skill)])
77
+ .filter(Boolean)
78
+ .map((entry) => ({ type: "custom", skill_id: entry.id, version: entry.version }));
79
+ }