@soft-boy/agentschema 0.3.0 → 0.3.2

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/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,7 @@
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 { DeployError, deploy, deployFiles, prepareLock } from "./deploy.js";
5
+ export { readFolder, updateFrontmatter } from "./folder.js";
6
+ export { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
7
+ export { Conversation, SessionError, openSession, startSession } from "./session.js";
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
- }