@soft-boy/agentschema 0.3.1 → 0.3.3

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/deploy.js CHANGED
@@ -1,23 +1,57 @@
1
1
  import { join } from "node:path";
2
2
  import Anthropic, { toFile } from "@anthropic-ai/sdk";
3
- import { check } from "./check.js";
4
- import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
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";
3
+ import { checkFiles } from "../lib/check.js";
4
+ import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "../lib/instance.js";
5
+ import { skillKey, skillRefs } from "../lib/skills.js";
6
+ import { AGENTBOOK } from "../lib/tools.js";
7
+ import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey } from "../lib/vaults.js";
8
+ import { folderProblem, readFolder } from "./folder.js";
9
+ import { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
8
10
 
9
11
  export class DeployError extends Error {}
10
12
 
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.
14
- // Returns the plan: one { file, kind, action, id, version } entry per resource.
13
+ // Deploys an agent folder, keeping the lock in its claude-lock.json. Returns the plan: one
14
+ // { file, kind, action, id, version } entry per resource.
15
15
  export async function deploy(dir, { client, dryRun = false, force = false, log = () => {} }) {
16
- const { errors, instance } = check(dir);
16
+ const problem = folderProblem(dir);
17
+ if (problem) throw new DeployError(`check failed:\n ${problem}`);
18
+ const { plan } = await deployFiles({
19
+ files: readFolder(dir),
20
+ lock: readLock(dir),
21
+ client,
22
+ dryRun,
23
+ force,
24
+ log,
25
+ saveLock: (lock) => writeLock(dir, lock),
26
+ pathOf: (file) => join(dir, file),
27
+ });
28
+ return plan;
29
+ }
30
+
31
+ // Creates or updates the skills, environment, agent and vaults in a file map (see lib/files.js).
32
+ // Skills go first, because the agent refers to their IDs and versions. Credentials are only
33
+ // updated here: creating one needs its secrets, so that's `cred deploy`'s job.
34
+ //
35
+ // lock the IDs from the last deploy, or null for a first deploy
36
+ // saveLock called with the lock as soon as each resource exists, so a failure later
37
+ // doesn't orphan it; it may be async
38
+ // checkOptions what checkFiles takes: { customTools, toolsets }
39
+ // pathOf how to show a file's path to the user in messages
40
+ //
41
+ // Returns { plan, lock }. A dry run calls neither the API nor saveLock.
42
+ export async function deployFiles({
43
+ files, lock: previous = null, client, dryRun = false, force = false, log = () => {},
44
+ saveLock = () => {}, checkOptions = {}, pathOf = (file) => file,
45
+ }) {
46
+ const { errors, instance } = checkFiles(files, checkOptions);
17
47
  if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
18
- const lock = openLock(dir, client);
48
+ const agentbook = instance.tools.find((t) => t.data.type === AGENTBOOK);
49
+ if (agentbook && !checkOptions.toolsets) {
50
+ throw new DeployError(`${agentbook.file}: this toolset runs on agentbook, so it can only be deployed from there`);
51
+ }
52
+ const lock = prepareLock(previous, client);
19
53
 
20
- const skillSteps = await deploySkills(instance.skills, { dir, client, lock, dryRun, log });
54
+ const skillSteps = await deploySkills(instance.skills, { client, lock, dryRun, log, saveLock });
21
55
  // A dry run has no new IDs or versions yet, so a stand-in shows that the agent will change too.
22
56
  const pending = dryRun ? skillSteps.filter((s) => s.action !== "unchanged") : [];
23
57
  const refs = instance.skills.flatMap((skill) => {
@@ -28,7 +62,7 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
28
62
 
29
63
  const steps = [
30
64
  { file: ENV_FILE, kind: "environment", body: envBody(instance) },
31
- { file: AGENT_FILE, kind: "agent", body: agentBody(instance, refs) },
65
+ { file: AGENT_FILE, kind: "agent", body: agentBody(instance, refs, checkOptions) },
32
66
  ];
33
67
  for (const step of steps) {
34
68
  step.key = `./${step.file}`;
@@ -53,25 +87,29 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
53
87
  ? { kind: "agent", id: result.id, version: String(result.version), hash: step.hash }
54
88
  : { kind: "environment", id: result.id, hash: step.hash };
55
89
  // Record each resource as soon as it exists, so a failure later doesn't orphan it.
56
- writeLock(dir, lock);
90
+ await saveLock(lock);
57
91
 
58
92
  const version = step.kind === "agent" ? ` (version ${result.version})` : "";
59
93
  log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}${version}`);
60
94
  }
61
95
 
62
- const vaultSteps = await deployVaults(dir, instance.vaults, { client, lock, dryRun, log });
96
+ const vaultSteps = await deployVaults(instance.vaults, { client, lock, dryRun, log, saveLock, pathOf });
63
97
 
64
- return [...skillSteps, ...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
98
+ const plan = [...skillSteps, ...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
65
99
  file, kind, action,
66
100
  id: lock.resources[key]?.id,
67
101
  version: lock.resources[key]?.version,
68
102
  }));
103
+ return { plan, lock };
69
104
  }
70
105
 
71
- // Reads claude-lock.json, or starts a new one, and checks it was written for this API.
72
- export function openLock(dir, client) {
106
+ // Reads claude-lock.json, or starts a new lock, and checks it was written for this API.
107
+ export const openLock = (dir, client) => prepareLock(readLock(dir), client);
108
+
109
+ // The lock to deploy with: the one given, or a new one, after checking it's for this API.
110
+ export function prepareLock(previous, client) {
73
111
  const baseURL = client.baseURL;
74
- const lock = readLock(dir) ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
112
+ const lock = previous ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
75
113
  lock.resources ??= {};
76
114
  if (lock.origin?.base_url && lock.origin.base_url !== baseURL) {
77
115
  throw new DeployError(
@@ -82,7 +120,7 @@ export function openLock(dir, client) {
82
120
  }
83
121
 
84
122
  // 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 }) {
123
+ async function deploySkills(skills, { client, lock, dryRun, log, saveLock }) {
86
124
  const steps = [];
87
125
  for (const skill of skills) {
88
126
  const step = planStep(lock, { file: skill.path, key: skillKey(skill), kind: "skill", body: skillFingerprint(skill) });
@@ -105,7 +143,7 @@ async function deploySkills(skills, { dir, client, lock, dryRun, log }) {
105
143
  ({ id: version } = await call(step, () => client.skills.versions.create(id, { files })));
106
144
  }
107
145
  lock.resources[step.key] = { kind: "skill", id, version, hash: step.hash };
108
- writeLock(dir, lock);
146
+ await saveLock(lock);
109
147
  log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} skill ${id} (version ${version})`);
110
148
  }
111
149
  return steps;
@@ -113,7 +151,7 @@ async function deploySkills(skills, { dir, client, lock, dryRun, log }) {
113
151
 
114
152
  // Creates or updates each vault, then updates the settings of credentials already created.
115
153
  // 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 }) {
154
+ async function deployVaults(vaults, { client, lock, dryRun, log, saveLock, pathOf }) {
117
155
  const steps = [];
118
156
  for (const vault of vaults) {
119
157
  const step = planStep(lock, { file: vault.path, key: vaultKey(vault), kind: "vault", body: vaultBody(vault) });
@@ -138,7 +176,7 @@ async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
138
176
  if (changed.length > 0) {
139
177
  throw new DeployError(
140
178
  `${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\`.`,
179
+ `Delete it with \`agentschema cred delete ${pathOf(step.file)}\`, then create it again with \`agentschema cred deploy\`.`,
142
180
  );
143
181
  }
144
182
  step.remote = remote;
@@ -147,7 +185,7 @@ async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
147
185
 
148
186
  for (const step of steps) {
149
187
  if (step.action === "missing") {
150
- log(`missing credential ${step.file} (create it with: agentschema cred deploy ${join(dir, step.file)})`);
188
+ log(`missing credential ${step.file} (create it with: agentschema cred deploy ${pathOf(step.file)})`);
151
189
  continue;
152
190
  }
153
191
  if (dryRun || step.action === "unchanged") {
@@ -169,7 +207,7 @@ async function deployVaults(dir, vaults, { client, lock, dryRun, log }) {
169
207
  result = await call(step, () => client.beta.vaults.credentials.update(step.entry.id, credentialUpdateBody(step)));
170
208
  lock.resources[step.key] = { ...step.entry, hash: step.hash };
171
209
  }
172
- writeLock(dir, lock);
210
+ await saveLock(lock);
173
211
  log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}`);
174
212
  }
175
213
  return steps;
package/src/folder.js ADDED
@@ -0,0 +1,52 @@
1
+ import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { editFrontmatter } from "../lib/markdown.js";
4
+ import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
5
+ import { SKILLS_DIR } from "../lib/skills.js";
6
+ import { TOOLS_DIR } from "../lib/tools.js";
7
+ import { VAULTS_DIR } from "../lib/vaults.js";
8
+
9
+ const FOLDERS = [TOOLS_DIR, SKILLS_DIR, VAULTS_DIR];
10
+ const TOP_LEVEL_FILES = [AGENT_FILE, ENV_FILE];
11
+
12
+ // Why `dir` can't be read as an agent folder, or null when it can.
13
+ export function folderProblem(dir) {
14
+ try {
15
+ return statSync(dir).isDirectory() ? null : `${dir}: not a directory`;
16
+ } catch {
17
+ return `${dir}: no such directory`;
18
+ }
19
+ }
20
+
21
+ // Reads an agent folder into a file map (see lib/files.js), as bytes. Only the agent's own files
22
+ // are read, so empty folders, hidden files and node_modules aren't part of it.
23
+ export function readFolder(dir) {
24
+ const files = {};
25
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
26
+ const path = join(dir, entry.name);
27
+ if (FOLDERS.includes(entry.name)) {
28
+ if (statSync(path).isDirectory()) walk(path, entry.name, files, entry.name !== SKILLS_DIR);
29
+ else files[entry.name] = readFileSync(path);
30
+ } else if (TOP_LEVEL_FILES.includes(entry.name.toLowerCase()) && !statSync(path).isDirectory()) {
31
+ files[entry.name] = readFileSync(path);
32
+ }
33
+ }
34
+ return files;
35
+ }
36
+
37
+ // Everything in a skill's folder gets uploaded, so links there aren't followed, in case one
38
+ // points outside the agent.
39
+ function walk(folder, prefix, files, followLinks) {
40
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
41
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
42
+ const path = join(folder, entry.name);
43
+ const rel = `${prefix}/${entry.name}`;
44
+ if (entry.isDirectory()) walk(path, rel, files, followLinks);
45
+ else if (entry.isFile() || (followLinks && entry.isSymbolicLink() && statSync(path).isFile())) files[rel] = readFileSync(path);
46
+ }
47
+ }
48
+
49
+ // Edits a file's frontmatter on disk, keeping its comments and the rest of the file.
50
+ export function updateFrontmatter(file, edit) {
51
+ writeFileSync(file, editFrontmatter(readFileSync(file, "utf8"), edit));
52
+ }
package/src/init.js CHANGED
@@ -1,57 +1,14 @@
1
1
  import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, resolve } from "node:path";
3
- import { stringify } from "yaml";
4
- import { AGENT_FILE, ENV_FILE } from "./instance.js";
3
+ import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
4
+ import { MODELS, NETWORKING, defaultAnswers, scaffold } from "../lib/scaffold.js";
5
+ import { TOOLSET_FILE, TOOLS_DIR } from "../lib/tools.js";
5
6
  import { prompts } from "./prompts.js";
6
- import { TOOLSET_FILE, PREBUILT_TOOLS, TOOLSET, TOOLS_DIR } from "./tools.js";
7
7
 
8
8
  export class InitError extends Error {}
9
9
 
10
- export const MODELS = ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"];
11
- export const NETWORKING = ["limited", "unrestricted"];
12
-
13
10
  // The answers used when a question is skipped (--yes, or input ends early).
14
- export function defaults(dir) {
15
- const slug = basename(resolve(dir)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "agent";
16
- return {
17
- name: slug.split("-").map((w) => w[0].toUpperCase() + w.slice(1)).join(" "),
18
- model: MODELS[0],
19
- system: "You are a helpful assistant.",
20
- tools: true,
21
- environment: slug,
22
- networking: "limited",
23
- packageManagers: true,
24
- };
25
- }
26
-
27
- // Returns { path: text } for a set of answers: agent.md, env.md, and tools/agent_toolset_20260401.md
28
- // listing every pre-built tool when the agent gets them.
29
- export function scaffold(answers) {
30
- const agent = { name: answers.name, model: answers.model };
31
-
32
- const networking = { type: answers.networking };
33
- if (answers.networking === "limited") networking.allow_package_managers = answers.packageManagers;
34
- const env = { name: answers.environment, config: { type: "cloud", networking } };
35
-
36
- const access = answers.networking === "unrestricted"
37
- ? "unrestricted network access"
38
- : answers.packageManagers ? "limited networking and package manager access" : "limited networking";
39
- const files = {
40
- [AGENT_FILE]: `---\n${stringify(agent)}---\n\n${answers.system.trim()}\n`,
41
- [ENV_FILE]: `---\n${stringify(env)}---\nCloud container with ${access}.\n`,
42
- };
43
- if (answers.tools) {
44
- files[`${TOOLS_DIR}/${TOOLSET_FILE}`] = builtInFile(PREBUILT_TOOLS);
45
- }
46
- return files;
47
- }
48
-
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");
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`;
54
- }
11
+ export const defaults = (dir) => defaultAnswers(basename(resolve(dir)));
55
12
 
56
13
  // Asks the setup questions, then writes agent.md and env.md into a new folder `dir`.
57
14
  export async function init(dir, { yes = false, input = process.stdin, output = process.stdout } = {}) {
package/src/lock.js CHANGED
@@ -19,6 +19,12 @@ export function writeLock(dir, lock) {
19
19
  writeFileSync(join(dir, LOCK_FILE), JSON.stringify(lock, null, 2) + "\n");
20
20
  }
21
21
 
22
+ // What's hashed into the lock for a skill: each file's path and contents, so any change makes a
23
+ // new version.
24
+ export function skillFingerprint(skill) {
25
+ return { files: skill.files.map((f) => [f.rel, createHash("sha256").update(f.bytes).digest("hex")]) };
26
+ }
27
+
22
28
  // Hash of a request body with keys sorted, so key order in the YAML doesn't count as a change.
23
29
  export function hashBody(body) {
24
30
  return createHash("md5").update(canonicalJSON(body)).digest("hex");
package/src/node.js ADDED
@@ -0,0 +1,9 @@
1
+ // What agentschema does on a server: anything that needs the API client, hashing or the disk. It
2
+ // works on file maps and lock objects, so a host can keep both in a database.
3
+ export { check } from "./check.js";
4
+ export { createCredential, deleteCredential } from "./cred.js";
5
+ export { DeployError, deploy, deployFiles, prepareLock } from "./deploy.js";
6
+ export { readFolder, updateFrontmatter } from "./folder.js";
7
+ export { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
8
+ export { OAuthError, authorizationRequest, discover, exchangeCode, registerClient } from "./oauth.js";
9
+ export { Conversation, SessionError, openSession, startSession } from "./session.js";
package/src/oauth.js CHANGED
@@ -117,14 +117,14 @@ export async function startCallbackServer(port = 0) {
117
117
 
118
118
  const escape = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
119
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 } = {}) {
120
+ // Registers as an OAuth client (RFC 7591), for servers that allow it. `clientName` is what the
121
+ // provider shows on its sign-in page. Returns { clientId, clientSecret, authMethod }.
122
+ export async function registerClient(registrationEndpoint, redirectUri, { fetch = globalThis.fetch, clientName = "agentschema" } = {}) {
123
123
  const res = await fetch(registrationEndpoint, {
124
124
  method: "POST",
125
125
  headers: { "content-type": "application/json", accept: "application/json" },
126
126
  body: JSON.stringify({
127
- client_name: "agentschema",
127
+ client_name: clientName,
128
128
  redirect_uris: [redirectUri],
129
129
  grant_types: ["authorization_code", "refresh_token"],
130
130
  response_types: ["code"],
package/src/session.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { join } from "node:path";
2
+ import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "../lib/instance.js";
3
+ import { skillKey, skillRefs } from "../lib/skills.js";
4
+ import { TOOLS_DIR } from "../lib/tools.js";
5
+ import { credentialKey, vaultKey } from "../lib/vaults.js";
2
6
  import { check } from "./check.js";
3
- import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
4
- import { LOCK_FILE, hashBody, readLock } from "./lock.js";
5
- import { skillFingerprint, skillKey, skillRefs } from "./skills.js";
6
- import { TOOLS_DIR } from "./tools.js";
7
- import { credentialKey, vaultKey } from "./vaults.js";
7
+ import { LOCK_FILE, hashBody, readLock, skillFingerprint } from "./lock.js";
8
8
 
9
9
  export class SessionError extends Error {}
10
10
 
@@ -37,14 +37,38 @@ export async function openSession(dir, { client, sessionId }) {
37
37
  if (notes.length > 0) notes.push(`this session uses the deployed version; run agentschema deploy to pick up the changes`);
38
38
  }
39
39
 
40
- // Pin the deployed version, so the session runs exactly what deploy last sent.
40
+ const name = instance?.agent.data.name;
41
+ const started = await startSession({
42
+ instance,
43
+ lock,
44
+ client,
45
+ title: name ? `${name} (agentschema run)` : "agentschema run",
46
+ pathOf: (file) => join(dir, file),
47
+ });
48
+ return { session: started.session, notes: [...notes, ...started.notes] };
49
+ }
50
+
51
+ // Starts a session from a lock, pinned to a deployed version, so it runs exactly what deploy sent.
52
+ //
53
+ // instance the checked files, for finding the vaults to attach
54
+ // agentVersion the agent version to pin, instead of the lock's latest
55
+ // budget the API's session budget, to cap what the session can spend
56
+ // pathOf how to show a file's path to the user in messages
57
+ //
58
+ // Returns { session, notes }.
59
+ export async function startSession({ instance, lock, client, agentVersion, title, budget, pathOf = (file) => file }) {
60
+ const agent = lock?.resources?.[`./${AGENT_FILE}`];
61
+ const env = lock?.resources?.[`./${ENV_FILE}`];
62
+ if (!agent || !env) throw new SessionError("this agent hasn't been deployed (no agent or environment in its lock)");
63
+
41
64
  const params = {
42
- agent: { type: "agent", id: agent.id, version: Number(agent.version) },
65
+ agent: { type: "agent", id: agent.id, version: Number(agentVersion ?? agent.version) },
43
66
  environment_id: env.id,
44
67
  };
45
68
 
46
69
  // Every deployed vault in vaults/, in name order: when two hold a credential for the same
47
70
  // server, the first one wins.
71
+ const notes = [];
48
72
  const vaultIds = [];
49
73
  for (const vault of instance?.vaults ?? []) {
50
74
  const entry = lock.resources[vaultKey(vault)];
@@ -56,13 +80,13 @@ export async function openSession(dir, { client, sessionId }) {
56
80
  for (const cred of vault.credentials) {
57
81
  const credEntry = lock.resources[credentialKey(cred)];
58
82
  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)}`);
83
+ notes.push(`credential ${cred.file} hasn't been created; run agentschema cred deploy ${pathOf(cred.file)}`);
60
84
  }
61
85
  }
62
86
  }
63
87
  if (vaultIds.length > 0) params.vault_ids = vaultIds;
64
- const name = instance?.agent.data.name;
65
- params.title = name ? `${name} (agentschema run)` : "agentschema run";
88
+ if (title) params.title = title;
89
+ if (budget) params.budget = budget;
66
90
  return { session: await client.beta.sessions.create(params), notes };
67
91
  }
68
92
 
package/src/tools-menu.js CHANGED
@@ -4,11 +4,11 @@ import { stringify } from "yaml";
4
4
  import { check } from "./check.js";
5
5
  import { serviceName } from "./cred-menu.js";
6
6
  import { DeployError } from "./deploy.js";
7
- import { builtInFile } from "./init.js";
8
- import { AGENT_FILE, ENV_FILE } from "./instance.js";
9
- import { updateFrontmatter } from "./markdown.js";
7
+ import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
8
+ import { builtInFile } from "../lib/scaffold.js";
9
+ import { updateFrontmatter } from "./folder.js";
10
10
  import { listMcpTools } from "./mcp.js";
11
- import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR } from "./tools.js";
11
+ import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR } from "../lib/tools.js";
12
12
 
13
13
  const PREBUILT = "Pre-built tools (bash, files, web search)";
14
14
  const CUSTOM = "Custom tool (JavaScript that runs on your machine)";
package/src/skills.js DELETED
@@ -1,79 +0,0 @@
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
- }