@soft-boy/agentschema 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -1,20 +1,128 @@
1
1
  # agentschema
2
2
 
3
+ Define a Claude Managed Agent as a folder of Markdown files.
4
+
5
+ ```
6
+ my-agent/
7
+ ├── agent.md # the agent
8
+ └── env.md # the environment it runs in
9
+ ```
10
+
11
+ **Status:** v0.1 draft. `check`, `deploy` and `run` work.
12
+
13
+ ## Philosophy
14
+
15
+ 1. **One folder, one agent.** A folder defines one agent and the one environment it runs in. Sessions, credentials, mounted files and repositories, and schedules are supplied by whatever runs the agent.
16
+ 2. **Everything is a Markdown file.** An agent is plain files you can read, diff, review and version like any other code. Structured settings go in YAML frontmatter, and prose the model reads goes in the Markdown body.
17
+ 3. **Inspired by Claude Managed Agents, not tied to it.** The fields follow the Claude Managed Agents schema because it's a well-documented vocabulary for agents. The format itself assumes no particular infrastructure, so any runtime that can read the files can run the agent.
18
+
3
19
  ## Install
4
20
 
5
21
  ```sh
6
22
  npm install -g @soft-boy/agentschema
7
23
  ```
8
24
 
25
+ ## Example
26
+
27
+ [`examples/coding-agent/agent.md`](examples/coding-agent/agent.md):
28
+
29
+ ```markdown
30
+ ---
31
+ name: Coding Assistant
32
+ model: claude-opus-5-5
33
+ tools:
34
+ - type: agent_toolset_20260401
35
+ ---
36
+
37
+ You are a helpful coding assistant. Write clean, well-documented code.
38
+ ```
39
+
40
+ [`examples/coding-agent/env.md`](examples/coding-agent/env.md):
41
+
42
+ ```markdown
43
+ ---
44
+ name: quickstart
45
+ config:
46
+ type: cloud
47
+ networking:
48
+ type: limited
49
+ allow_package_managers: true
50
+ ---
51
+ Cloud container with limited networking and package manager access.
52
+ ```
53
+
54
+ ## Specification
55
+
56
+ ### Files
57
+
58
+ An instance is a folder of Markdown files.
59
+
60
+ ```
61
+ my-agent/
62
+ ├── agent.md # the agent
63
+ └── env.md # the environment it runs in
64
+ ```
65
+
66
+ ### `agent.md`
67
+ Field reference: [Agent setup](https://platform.claude.com/docs/en/managed-agents/agent-setup).
68
+
69
+ - **Frontmatter** uses the fields of a Claude Managed Agents agent (the `POST /v1/agents` request body), written as YAML. `name` and `model` are required. Every other field (`description`, `tools`, `mcp_servers`, `skills`, `multiagent`, `metadata`, …) is optional and uses the same names and shapes.
70
+ - **Body** is the agent's system prompt, sent as `system` exactly as written (leading and trailing whitespace trimmed). An empty body means no system prompt.
71
+ - Setting `system` in the frontmatter is an error, because the body is the system prompt.
72
+
73
+ ### `env.md`
74
+ Field reference: [Environments](https://platform.claude.com/docs/en/managed-agents/environments).
75
+
76
+ - **Frontmatter** uses the fields of a Claude Managed Agents environment (the `POST /v1/environments` request body), written as YAML: `name`, `config`, and any other field the schema defines.
77
+ - **Body** is a note for people reading the folder. It is not sent anywhere.
78
+
9
79
  ## Usage
10
80
 
11
81
  ```sh
12
- agentschema
82
+ agentschema check [dir] # validate the folder, no network
83
+ agentschema deploy [dir] # create or update the agent and environment
84
+ agentschema run [dir] # chat with the deployed agent in the terminal
85
+ ```
86
+
87
+ `dir` defaults to the current directory.
88
+
89
+ **`check`** reads both files and reports every problem it finds:
90
+ - a missing file, or a name that isn't lowercase
91
+ - frontmatter that is missing, unclosed, or invalid YAML
92
+ - a missing `name` or `model`, or a `system` key in `agent.md`'s frontmatter
93
+ - values over the API's limits
94
+ - anything that looks like an API key or token
95
+
96
+ Unknown fields are only warnings, because they're sent to the API as written. `check` exits with status 1 when there are errors.
97
+
98
+ **`deploy`** runs `check` first, then creates or updates the environment and the agent, and records their IDs in `claude-lock.json` in the folder. Commit that file.
99
+ - **Later runs update the same resources.** A file that hasn't changed since the last deploy is skipped. Each change to `agent.md` adds a new version of the agent, and sessions already running keep the version they started on.
100
+ - **The files are the source of truth.** A field you delete from a file is cleared on the next deploy, rather than left at its old value.
101
+ - **Changes made elsewhere aren't overwritten silently.** If the agent was changed outside the folder since the last deploy, `deploy` stops; `--force` overwrites it.
102
+
103
+ `deploy` authenticates with `ANTHROPIC_API_KEY`, or with a profile from `ant auth login`.
104
+
105
+ `claude-lock.json` uses the same layout as `ant apply`'s, so `deploy` updates resources that `ant apply` created. The two tools hash files differently, though, so the first `deploy` after an `ant apply` updates both resources even if nothing changed.
106
+
107
+ **`run`** starts a session on the agent and environment in `claude-lock.json`, then opens a chat in the terminal. Deploy first; if you've edited the files since, `run` warns you and still uses the deployed version.
108
+ - **Messages:** type a message and press Enter. The agent's replies stream in, with a one-line summary of each tool call.
109
+ - **Approvals:** when a tool call needs approval (`always_ask`, or `auto` when the server can't decide), `run` asks you. Answer `y` to allow it, or type a reason to deny it; the agent sees the reason.
110
+ - **Custom tools:** `run` shows the call's input and asks you to type the result.
111
+ - **Interrupting:** Ctrl+C interrupts the agent mid-turn, and a second Ctrl+C quits. Ctrl+D quits at the prompt.
112
+ - **Resuming:** quitting leaves the session in place, and `run` prints a command to resume it: `agentschema run --session sesn_…`.
113
+
114
+ ```sh
115
+ agentschema run [dir] --vault vlt_… # attach a vault for MCP or other credentials (repeatable)
116
+ agentschema run [dir] --title "Bug triage" # name the session
117
+ agentschema run --session sesn_… # resume an existing session
13
118
  ```
14
119
 
120
+ To run the agent from your own code, create a session with the agent and environment IDs from the lock file.
121
+
15
122
  ## Development
16
123
 
17
124
  ```sh
125
+ npm install
126
+ npm test # unit tests; deploy runs against a fake API client
18
127
  npm link # makes `agentschema` available globally from this checkout
19
- agentschema
20
128
  ```
@@ -1,3 +1,132 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import Anthropic from "@anthropic-ai/sdk";
5
+ import { chat } from "../src/chat.js";
6
+ import { check } from "../src/check.js";
7
+ import { DeployError, deploy } from "../src/deploy.js";
8
+ import { SessionError, openSession } from "../src/session.js";
2
9
 
3
- console.log("hello world");
10
+ const USAGE = `Usage: agentschema <command> [dir] [options]
11
+
12
+ Commands:
13
+ check [dir] Validate agent.md and env.md, without calling the API
14
+ deploy [dir] Create or update the agent and environment, and write claude-lock.json
15
+ run [dir] Chat with the deployed agent in a new session
16
+
17
+ Options:
18
+ --dry-run (deploy) Show what would be created or updated, change nothing
19
+ --force (deploy) Update the agent even if it was changed outside this folder
20
+ --vault <id> (run) Attach a vault (vlt_...) for MCP and other credentials; repeatable
21
+ --title <title> (run) Title for the new session
22
+ --session <id> (run) Resume an existing session (sesn_...) instead of starting one
23
+ -h, --help Show this help
24
+ -v, --version Show the version
25
+
26
+ dir defaults to the current directory. deploy and run authenticate with
27
+ ANTHROPIC_API_KEY, or with a profile from \`ant auth login\`.`;
28
+
29
+ const OPTIONS = {
30
+ "dry-run": { type: "boolean" },
31
+ force: { type: "boolean" },
32
+ vault: { type: "string", multiple: true },
33
+ title: { type: "string" },
34
+ session: { type: "string" },
35
+ help: { type: "boolean", short: "h" },
36
+ version: { type: "boolean", short: "v" },
37
+ };
38
+ const COMMAND_OPTIONS = {
39
+ check: [],
40
+ deploy: ["dry-run", "force"],
41
+ run: ["vault", "title", "session"],
42
+ };
43
+
44
+ async function main(argv) {
45
+ let parsed;
46
+ try {
47
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
48
+ } catch (err) {
49
+ console.error(`agentschema: ${err.message}\n\n${USAGE}`);
50
+ return 1;
51
+ }
52
+ const { values, positionals } = parsed;
53
+ const [command, dir = ".", ...extra] = positionals;
54
+
55
+ if (values.version) {
56
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
57
+ console.log(pkg.version);
58
+ return 0;
59
+ }
60
+ if (!command || values.help) {
61
+ console.log(USAGE);
62
+ return command || values.help ? 0 : 1;
63
+ }
64
+ if (!(command in COMMAND_OPTIONS)) {
65
+ console.error(`agentschema: unknown command "${command}"\n\n${USAGE}`);
66
+ return 1;
67
+ }
68
+ const misplaced = Object.keys(values).filter((k) => !COMMAND_OPTIONS[command].includes(k));
69
+ if (extra.length > 0 || misplaced.length > 0) {
70
+ const arg = extra[0] ?? `--${misplaced[0]}`;
71
+ console.error(`agentschema: unexpected argument ${arg} for ${command}\n\n${USAGE}`);
72
+ return 1;
73
+ }
74
+
75
+ if (command === "check") {
76
+ const { errors, warnings } = check(dir);
77
+ for (const w of warnings) console.warn(`warning: ${w}`);
78
+ for (const e of errors) console.error(`error: ${e}`);
79
+ if (errors.length > 0) return 1;
80
+ console.log(`${dir}: ok`);
81
+ return 0;
82
+ }
83
+
84
+ try {
85
+ if (command === "deploy") {
86
+ for (const w of check(dir).warnings) console.warn(`warning: ${w}`);
87
+ const dryRun = values["dry-run"] ?? false;
88
+ await deploy(dir, {
89
+ client: makeClient(dryRun),
90
+ dryRun,
91
+ force: values.force ?? false,
92
+ log: (line) => console.log(line),
93
+ });
94
+ return 0;
95
+ }
96
+
97
+ if (command === "run") {
98
+ const client = makeClient(false);
99
+ const { session, notes } = await openSession(dir, {
100
+ client,
101
+ sessionId: values.session,
102
+ vaultIds: values.vault ?? [],
103
+ title: values.title,
104
+ });
105
+ for (const note of notes) console.warn(`warning: ${note}`);
106
+ await chat(client, session, { agentName: session.agent?.name ?? "agent" });
107
+ return 0;
108
+ }
109
+ } catch (err) {
110
+ if (err instanceof Anthropic.APIError) {
111
+ console.error(`error: ${err.status ?? "network error"}: ${err.error?.error?.message ?? err.message}`);
112
+ return 1;
113
+ }
114
+ if (err instanceof DeployError || err instanceof SessionError || err instanceof Anthropic.AnthropicError) {
115
+ console.error(`error: ${err.message}`);
116
+ return 1;
117
+ }
118
+ throw err;
119
+ }
120
+ }
121
+
122
+ // A dry run makes no API calls, so it works without credentials.
123
+ function makeClient(dryRun) {
124
+ try {
125
+ return new Anthropic();
126
+ } catch (err) {
127
+ if (!dryRun) throw err;
128
+ return { baseURL: process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com" };
129
+ }
130
+ }
131
+
132
+ process.exitCode = await main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@soft-boy/agentschema",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Markdown based AI agent schema",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "agentschema": "bin/agentschema.js"
8
8
  },
9
9
  "files": [
10
- "bin"
10
+ "bin",
11
+ "src"
11
12
  ],
12
13
  "engines": {
13
14
  "node": ">=18"
@@ -15,5 +16,12 @@
15
16
  "license": "MIT",
16
17
  "publishConfig": {
17
18
  "access": "public"
19
+ },
20
+ "dependencies": {
21
+ "@anthropic-ai/sdk": "^1.4.0",
22
+ "yaml": "^2.9.1"
23
+ },
24
+ "scripts": {
25
+ "test": "node --test test/*.test.js"
18
26
  }
19
27
  }
package/src/chat.js ADDED
@@ -0,0 +1,135 @@
1
+ import { createInterface } from "node:readline";
2
+ import { Conversation } from "./session.js";
3
+
4
+ const color = (code) => (text) => (process.stdout.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text);
5
+ const dim = color(2);
6
+ const red = color(31);
7
+ const bold = color(1);
8
+
9
+ // Prints a session's events as a terminal transcript.
10
+ export function formatEvent(event) {
11
+ switch (event.type) {
12
+ case "agent.message":
13
+ return event.content.filter((b) => b.type === "text").map((b) => b.text).join("");
14
+ case "agent.tool_use":
15
+ case "agent.mcp_tool_use": {
16
+ const name = event.type === "agent.mcp_tool_use" ? `${event.mcp_server_name}.${event.name}` : event.name;
17
+ const denied = event.evaluated_permission === "deny" ? red(" (denied)") : "";
18
+ return dim(`· ${name} ${summarize(event.input)}`) + denied;
19
+ }
20
+ case "agent.custom_tool_use":
21
+ return dim(`· ${event.name} ${summarize(event.input)}`);
22
+ case "agent.tool_result":
23
+ case "agent.mcp_tool_result":
24
+ if (!event.is_error) return null;
25
+ return red(` ↳ ${firstLine(event.content)}`);
26
+ case "session.error":
27
+ return red(`error: ${event.error?.message ?? event.error?.type ?? "unknown error"}`);
28
+ case "session.status_idle": {
29
+ const reason = event.stop_reason?.type;
30
+ if (reason === "retries_exhausted") return red("The agent gave up after repeated errors.");
31
+ if (reason === "budget_reached") return red("The session reached its budget and paused.");
32
+ return null;
33
+ }
34
+ case "session.status_terminated":
35
+ return dim("The session has ended.");
36
+ default:
37
+ return null;
38
+ }
39
+ }
40
+
41
+ // One line describing a tool call's input: the command, path or query when there is one.
42
+ function summarize(input = {}) {
43
+ for (const key of ["command", "file_path", "path", "pattern", "url", "query"]) {
44
+ if (typeof input[key] === "string") return truncate(input[key]);
45
+ }
46
+ return truncate(JSON.stringify(input));
47
+ }
48
+
49
+ function firstLine(content = []) {
50
+ const text = content.find((b) => b.type === "text")?.text ?? "tool error";
51
+ return truncate(text.split("\n")[0]);
52
+ }
53
+
54
+ const truncate = (s, n = 100) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
55
+
56
+ // Runs an interactive chat in the terminal until the user quits or the session ends.
57
+ export async function chat(client, session, { agentName, input = process.stdin, output = process.stdout }) {
58
+ const rl = createInterface({ input, output, terminal: input.isTTY });
59
+ const lines = rl[Symbol.asyncIterator]();
60
+ let running = false;
61
+ let interrupted = false;
62
+ let quit = false;
63
+
64
+ const ask = async (prompt) => {
65
+ output.write(prompt);
66
+ const { value, done } = await lines.next();
67
+ if (done) quit = true;
68
+ return done ? null : value;
69
+ };
70
+
71
+ const ui = {
72
+ event(event) {
73
+ const text = formatEvent(event);
74
+ if (text) output.write(`${text}\n`);
75
+ },
76
+ async confirm(event) {
77
+ const answer = await ask(bold(`Allow ${event.name}? `) + dim("[y/N, or type why not] "));
78
+ if (answer && /^(y|yes)$/i.test(answer.trim())) return { result: "allow" };
79
+ const reason = answer?.trim();
80
+ return { result: "deny", deny_message: reason && !/^(n|no)$/i.test(reason) ? reason : undefined };
81
+ },
82
+ async customToolResult(event) {
83
+ output.write(dim(`${event.name} is a custom tool, so you supply its result.\n`));
84
+ output.write(dim(`input: ${JSON.stringify(event.input)}\n`));
85
+ return (await ask(bold("result> "))) ?? "The user didn't provide a result.";
86
+ },
87
+ };
88
+
89
+ const conversation = new Conversation(client, session.id, ui);
90
+ let ended = false;
91
+
92
+ // Ctrl+C interrupts the agent while it works; a second Ctrl+C, or one at the prompt, quits.
93
+ rl.on("SIGINT", () => {
94
+ if (running && !interrupted) {
95
+ interrupted = true;
96
+ output.write(dim("\nInterrupting… (Ctrl+C again to quit)\n"));
97
+ conversation.interrupt().catch(() => {});
98
+ return;
99
+ }
100
+ quit = true;
101
+ conversation.close();
102
+ rl.close();
103
+ });
104
+
105
+ output.write(dim(`${agentName} · session ${session.id}\nCtrl+C interrupts the agent, Ctrl+D quits.\n\n`));
106
+
107
+ try {
108
+ while (!quit) {
109
+ const text = await ask(bold("> "));
110
+ if (text === null) break;
111
+ if (text.trim() === "") continue;
112
+
113
+ running = true;
114
+ interrupted = false;
115
+ let outcome;
116
+ try {
117
+ outcome = await conversation.send(text);
118
+ } catch (err) {
119
+ if (quit) break;
120
+ throw err;
121
+ } finally {
122
+ running = false;
123
+ }
124
+ output.write("\n");
125
+ if (outcome === "terminated") {
126
+ ended = true;
127
+ break;
128
+ }
129
+ }
130
+ } finally {
131
+ conversation.close();
132
+ rl.close();
133
+ }
134
+ if (!ended) output.write(dim(`Resume this conversation with: agentschema run --session ${session.id}\n`));
135
+ }
package/src/check.js ADDED
@@ -0,0 +1,107 @@
1
+ import { AGENT_FILE, ENV_FILE, readInstance } from "./instance.js";
2
+
3
+ const AGENT_FIELDS = new Set([
4
+ "name", "model", "description", "tools", "mcp_servers", "skills",
5
+ "multiagent", "metadata", "execution_identity",
6
+ ]);
7
+ const ENV_FIELDS = new Set(["name", "config", "description", "metadata", "scope"]);
8
+
9
+ const SECRET_PATTERNS = [
10
+ [/sk-ant-[A-Za-z0-9_-]{8,}/, "an Anthropic API key"],
11
+ [/\bghp_[A-Za-z0-9]{20,}/, "a GitHub token"],
12
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token"],
13
+ [/\bxox[bpas]-[A-Za-z0-9-]{10,}/, "a Slack token"],
14
+ [/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key"],
15
+ ];
16
+
17
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18
+
19
+ // Validates an instance folder without calling the API.
20
+ // Returns { errors, warnings, instance }; instance is null when the files can't be read.
21
+ export function check(dir) {
22
+ const { agent, env, errors } = readInstance(dir);
23
+ const warnings = [];
24
+
25
+ if (agent) checkAgent(agent, errors, warnings);
26
+ if (env) checkEnv(env, errors, warnings);
27
+ for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env]]) {
28
+ if (!parsed) continue;
29
+ for (const [pattern, what] of SECRET_PATTERNS) {
30
+ if (pattern.test(parsed.raw)) errors.push(`${file}: looks like it contains ${what}; keep secrets in a vault`);
31
+ }
32
+ }
33
+
34
+ return { errors, warnings, instance: agent && env ? { agent, env } : null };
35
+ }
36
+
37
+ function checkAgent({ data, body }, errors, warnings) {
38
+ const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
39
+
40
+ if (typeof data.name !== "string" || data.name.trim() === "") err("`name` is required");
41
+ else if (data.name.length > 256) err("`name` must be at most 256 characters");
42
+
43
+ if (data.model === undefined) err("`model` is required");
44
+ else if (isObject(data.model) ? typeof data.model.id !== "string" : typeof data.model !== "string") {
45
+ err("`model` must be a model ID, or a mapping with an `id`");
46
+ }
47
+
48
+ if ("system" in data) err("`system` is not allowed in frontmatter; the Markdown body is the system prompt");
49
+ if (body.length > 100_000) err(`system prompt is ${body.length} characters; the limit is 100,000`);
50
+
51
+ if (data.description !== undefined && data.description !== null) {
52
+ if (typeof data.description !== "string") err("`description` must be a string");
53
+ else if (data.description.length > 2048) err("`description` must be at most 2048 characters");
54
+ }
55
+
56
+ for (const [field, max] of [["tools", 256], ["mcp_servers", 20], ["skills", 500]]) {
57
+ if (data[field] === undefined) continue;
58
+ if (!Array.isArray(data[field])) err(`\`${field}\` must be a list`);
59
+ else if (data[field].length > max) err(`\`${field}\` has ${data[field].length} entries; the limit is ${max}`);
60
+ }
61
+
62
+ checkMetadata(data.metadata, 16, err);
63
+
64
+ for (const key of Object.keys(data)) {
65
+ if (!AGENT_FIELDS.has(key) && key !== "system") {
66
+ warnings.push(`${AGENT_FILE}: unknown field \`${key}\` will be sent to the API as written`);
67
+ }
68
+ }
69
+ }
70
+
71
+ function checkEnv({ data }, errors, warnings) {
72
+ const err = (msg) => errors.push(`${ENV_FILE}: ${msg}`);
73
+
74
+ if (typeof data.name !== "string" || data.name.trim() === "") err("`name` is required");
75
+
76
+ if (data.config !== undefined) {
77
+ const { config } = data;
78
+ if (!isObject(config)) err("`config` must be a mapping");
79
+ else {
80
+ if (!["cloud", "self_hosted"].includes(config.type)) err("`config.type` must be `cloud` or `self_hosted`");
81
+ const net = config.networking;
82
+ if (net !== undefined && !(isObject(net) && ["limited", "unrestricted"].includes(net.type))) {
83
+ err("`config.networking.type` must be `limited` or `unrestricted`");
84
+ }
85
+ }
86
+ }
87
+
88
+ if (data.description !== undefined && data.description !== null && typeof data.description !== "string") {
89
+ err("`description` must be a string");
90
+ }
91
+
92
+ checkMetadata(data.metadata, Infinity, err);
93
+
94
+ for (const key of Object.keys(data)) {
95
+ if (!ENV_FIELDS.has(key)) warnings.push(`${ENV_FILE}: unknown field \`${key}\` will be sent to the API as written`);
96
+ }
97
+ }
98
+
99
+ function checkMetadata(metadata, maxKeys, err) {
100
+ if (metadata === undefined) return;
101
+ if (!isObject(metadata)) return err("`metadata` must be a mapping");
102
+ const keys = Object.keys(metadata);
103
+ if (keys.length > maxKeys) err(`\`metadata\` has ${keys.length} keys; the limit is ${maxKeys}`);
104
+ for (const key of keys) {
105
+ if (typeof metadata[key] !== "string") err(`\`metadata.${key}\` must be a string (quote numbers and booleans)`);
106
+ }
107
+ }
package/src/deploy.js ADDED
@@ -0,0 +1,143 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import { check } from "./check.js";
3
+ import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
4
+ import { LOCK_FILE, hashBody, readLock, writeLock } from "./lock.js";
5
+
6
+ export class DeployError extends Error {}
7
+
8
+ // Creates or updates the environment and agent a folder defines, recording their IDs in claude-lock.json.
9
+ // Returns the plan: one { file, kind, action, id, version } entry per resource.
10
+ export async function deploy(dir, { client, dryRun = false, force = false, log = () => {} }) {
11
+ const { errors, instance } = check(dir);
12
+ if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
13
+
14
+ const baseURL = client.baseURL;
15
+ const lock = readLock(dir) ?? { version: 1, origin: { base_url: baseURL }, resources: {} };
16
+ lock.resources ??= {};
17
+ if (lock.origin?.base_url && lock.origin.base_url !== baseURL) {
18
+ throw new DeployError(
19
+ `${LOCK_FILE} was written for ${lock.origin.base_url}, but this client uses ${baseURL}`,
20
+ );
21
+ }
22
+
23
+ const steps = [
24
+ { file: ENV_FILE, kind: "environment", body: envBody(instance.env) },
25
+ { file: AGENT_FILE, kind: "agent", body: agentBody(instance.agent) },
26
+ ];
27
+ for (const step of steps) {
28
+ step.key = `./${step.file}`;
29
+ step.hash = hashBody(step.body);
30
+ step.entry = lock.resources[step.key];
31
+ if (step.entry && step.entry.kind !== step.kind) {
32
+ throw new DeployError(`${LOCK_FILE}: entry for ${step.key} is a ${step.entry.kind}, expected ${step.kind}`);
33
+ }
34
+ step.action = !step.entry ? "create" : step.entry.hash === step.hash ? "unchanged" : "update";
35
+ }
36
+
37
+ for (const step of steps) {
38
+ if (dryRun || step.action === "unchanged") {
39
+ log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? ""}`.trimEnd());
40
+ continue;
41
+ }
42
+ const result = step.kind === "environment"
43
+ ? await deployEnvironment(client, step)
44
+ : await deployAgent(client, step, force);
45
+
46
+ lock.resources[step.key] = step.kind === "agent"
47
+ ? { kind: "agent", id: result.id, version: String(result.version), hash: step.hash }
48
+ : { kind: "environment", id: result.id, hash: step.hash };
49
+ // Record each resource as soon as it exists, so a failure later doesn't orphan it.
50
+ writeLock(dir, lock);
51
+
52
+ const version = step.kind === "agent" ? ` (version ${result.version})` : "";
53
+ log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}${version}`);
54
+ }
55
+
56
+ return steps.map(({ file, kind, action, key }) => ({
57
+ file, kind, action,
58
+ id: lock.resources[key]?.id,
59
+ version: lock.resources[key]?.version,
60
+ }));
61
+ }
62
+
63
+ async function deployEnvironment(client, step) {
64
+ if (step.action === "create") return call(step, () => client.beta.environments.create(step.body));
65
+
66
+ const { id } = step.entry;
67
+ const remote = await retrieve(step, () => client.beta.environments.retrieve(id));
68
+ const body = { ...step.body };
69
+ // Updates keep any field you omit, so clear what was removed from env.md.
70
+ if (!("description" in body)) body.description = null;
71
+ body.metadata = metadataWithDeletions(body.metadata, remote.metadata);
72
+ return call(step, () => client.beta.environments.update(id, body));
73
+ }
74
+
75
+ async function deployAgent(client, step, force) {
76
+ if (step.action === "create") return call(step, () => client.beta.agents.create(step.body));
77
+
78
+ const { id, version } = step.entry;
79
+ const remote = await retrieve(step, () => client.beta.agents.retrieve(id));
80
+ const body = { ...step.body };
81
+ // Updates keep any field you omit, so clear what was removed from agent.md.
82
+ if (!("system" in body)) body.system = null;
83
+ for (const field of ["description", "multiagent"]) if (!(field in body)) body[field] = null;
84
+ for (const field of ["tools", "mcp_servers", "skills"]) if (!(field in body)) body[field] = [];
85
+ body.metadata = metadataWithDeletions(body.metadata, remote.metadata);
86
+ // Sending the locked version makes the API refuse the update if someone changed the agent since.
87
+ if (!force && version !== undefined) body.version = Number(version);
88
+
89
+ try {
90
+ return await client.beta.agents.update(id, body);
91
+ } catch (err) {
92
+ if (err instanceof Anthropic.APIError && err.status === 409) {
93
+ throw new DeployError(
94
+ `agent ${id} was changed outside this folder (${LOCK_FILE} has version ${version}, ` +
95
+ `the agent is at version ${remote.version}). Re-run with --force to overwrite it.`,
96
+ );
97
+ }
98
+ throw apiError(step, err);
99
+ }
100
+ }
101
+
102
+ // Metadata updates merge, so keys removed from the file are sent as null to delete them.
103
+ function metadataWithDeletions(local = {}, remote = {}) {
104
+ const merged = { ...local };
105
+ for (const key of Object.keys(remote ?? {})) if (!(key in merged)) merged[key] = null;
106
+ return merged;
107
+ }
108
+
109
+ async function retrieve(step, fn) {
110
+ let remote;
111
+ try {
112
+ remote = await fn();
113
+ } catch (err) {
114
+ if (err instanceof Anthropic.APIError && err.status === 404) {
115
+ throw new DeployError(
116
+ `${step.kind} ${step.entry.id} in ${LOCK_FILE} no longer exists. ` +
117
+ `Remove the "${step.key}" entry from ${LOCK_FILE} to create a new one.`,
118
+ );
119
+ }
120
+ throw apiError(step, err);
121
+ }
122
+ if (remote.archived_at) {
123
+ throw new DeployError(
124
+ `${step.kind} ${step.entry.id} is archived and can't be updated. ` +
125
+ `Remove the "${step.key}" entry from ${LOCK_FILE} to create a new one.`,
126
+ );
127
+ }
128
+ return remote;
129
+ }
130
+
131
+ async function call(step, fn) {
132
+ try {
133
+ return await fn();
134
+ } catch (err) {
135
+ throw apiError(step, err);
136
+ }
137
+ }
138
+
139
+ function apiError(step, err) {
140
+ if (!(err instanceof Anthropic.APIError)) return err;
141
+ const message = err.error?.error?.message ?? err.message;
142
+ return new DeployError(`${step.file}: the API rejected the ${step.kind} (${err.status ?? "network error"}): ${message}`);
143
+ }
@@ -0,0 +1,78 @@
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { parseDocument } from "yaml";
4
+
5
+ export const AGENT_FILE = "agent.md";
6
+ export const ENV_FILE = "env.md";
7
+
8
+ export class FileError extends Error {}
9
+
10
+ // Splits a Markdown file into YAML frontmatter (between `---` fences) and body.
11
+ export function parseMarkdown(text, file) {
12
+ const normalized = text.replace(/^/, "").replace(/\r\n/g, "\n");
13
+ if (!normalized.startsWith("---\n")) {
14
+ throw new FileError(`${file}: must start with YAML frontmatter between --- lines`);
15
+ }
16
+ const closing = /^---[ \t]*$/m.exec(normalized.slice(4));
17
+ if (!closing) throw new FileError(`${file}: frontmatter is not closed with a --- line`);
18
+ const end = 4 + closing.index;
19
+ const afterFence = normalized.slice(end + closing[0].length);
20
+
21
+ const doc = parseDocument(normalized.slice(4, end));
22
+ if (doc.errors.length > 0) {
23
+ // The YAML library counts lines from the start of the frontmatter; +1 for the opening fence.
24
+ const err = doc.errors[0];
25
+ const line = err.linePos?.[0]?.line;
26
+ const where = line ? `:${line + 1}` : "";
27
+ throw new FileError(`${file}${where}: invalid YAML: ${err.message.split("\n")[0]}`);
28
+ }
29
+
30
+ const data = doc.toJS() ?? {};
31
+ if (typeof data !== "object" || Array.isArray(data)) {
32
+ throw new FileError(`${file}: frontmatter must be a YAML mapping (key: value pairs)`);
33
+ }
34
+ return { data, body: afterFence.trim(), raw: text };
35
+ }
36
+
37
+ // Reads agent.md and env.md from an instance folder.
38
+ // Returns { agent, env, errors }; a file that can't be read is null and has an entry in errors.
39
+ export function readInstance(dir) {
40
+ let stat;
41
+ try {
42
+ stat = statSync(dir);
43
+ } catch {
44
+ return { agent: null, env: null, errors: [`${dir}: no such directory`] };
45
+ }
46
+ if (!stat.isDirectory()) return { agent: null, env: null, errors: [`${dir}: not a directory`] };
47
+
48
+ // Compare exact names: macOS file systems would otherwise open AGENT.md as agent.md.
49
+ const names = readdirSync(dir);
50
+ const errors = [];
51
+ const read = (name) => {
52
+ try {
53
+ if (!names.includes(name)) {
54
+ const wrongCase = names.find((n) => n.toLowerCase() === name);
55
+ const hint = wrongCase ? ` (found ${wrongCase}; the name must be lowercase)` : "";
56
+ throw new FileError(`${name}: missing${hint}`);
57
+ }
58
+ return parseMarkdown(readFileSync(join(dir, name), "utf8"), name);
59
+ } catch (err) {
60
+ if (!(err instanceof FileError)) throw err;
61
+ errors.push(err.message);
62
+ return null;
63
+ }
64
+ };
65
+
66
+ return { agent: read(AGENT_FILE), env: read(ENV_FILE), errors };
67
+ }
68
+
69
+ // The bodies sent to POST /v1/agents and POST /v1/environments.
70
+ export function agentBody(agent) {
71
+ const body = { ...agent.data };
72
+ if (agent.body) body.system = agent.body;
73
+ return body;
74
+ }
75
+
76
+ export function envBody(env) {
77
+ return { ...env.data };
78
+ }
package/src/lock.js ADDED
@@ -0,0 +1,34 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ export const LOCK_FILE = "claude-lock.json";
6
+
7
+ // Same layout as the lock file `ant apply` writes: one entry per file, keyed by "./<file>".
8
+ export function readLock(dir) {
9
+ const path = join(dir, LOCK_FILE);
10
+ if (!existsSync(path)) return null;
11
+ try {
12
+ return JSON.parse(readFileSync(path, "utf8"));
13
+ } catch (err) {
14
+ throw new Error(`${LOCK_FILE}: not valid JSON (${err.message})`);
15
+ }
16
+ }
17
+
18
+ export function writeLock(dir, lock) {
19
+ writeFileSync(join(dir, LOCK_FILE), JSON.stringify(lock, null, 2) + "\n");
20
+ }
21
+
22
+ // Hash of a request body with keys sorted, so key order in the YAML doesn't count as a change.
23
+ export function hashBody(body) {
24
+ return createHash("md5").update(canonicalJSON(body)).digest("hex");
25
+ }
26
+
27
+ function canonicalJSON(value) {
28
+ if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(",")}]`;
29
+ if (value && typeof value === "object") {
30
+ const keys = Object.keys(value).sort();
31
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}`).join(",")}}`;
32
+ }
33
+ return JSON.stringify(value);
34
+ }
package/src/session.js ADDED
@@ -0,0 +1,130 @@
1
+ import { check } from "./check.js";
2
+ import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
3
+ import { LOCK_FILE, hashBody, readLock } from "./lock.js";
4
+
5
+ export class SessionError extends Error {}
6
+
7
+ // Starts a session on the agent and environment recorded in claude-lock.json, or resumes `sessionId`.
8
+ // Returns { session, notes }: notes are warnings worth showing, such as files changed since the last deploy.
9
+ export async function openSession(dir, { client, sessionId, vaultIds = [], title }) {
10
+ if (sessionId) {
11
+ const session = await client.beta.sessions.retrieve(sessionId);
12
+ if (session.status === "terminated") throw new SessionError(`session ${sessionId} has terminated`);
13
+ return { session, notes: [] };
14
+ }
15
+
16
+ const lock = readLock(dir);
17
+ const agent = lock?.resources?.[`./${AGENT_FILE}`];
18
+ const env = lock?.resources?.[`./${ENV_FILE}`];
19
+ if (!agent || !env) {
20
+ throw new SessionError(`${dir} hasn't been deployed (no agent or environment in ${LOCK_FILE}); run agentschema deploy first`);
21
+ }
22
+
23
+ const notes = [];
24
+ const { instance } = check(dir);
25
+ if (instance) {
26
+ if (hashBody(agentBody(instance.agent)) !== agent.hash) notes.push(`${AGENT_FILE} has changed since the last deploy`);
27
+ if (hashBody(envBody(instance.env)) !== env.hash) notes.push(`${ENV_FILE} has changed since the last deploy`);
28
+ if (notes.length > 0) notes.push(`this session uses the deployed version; run agentschema deploy to pick up the changes`);
29
+ }
30
+
31
+ // Pin the deployed version, so the session runs exactly what deploy last sent.
32
+ const params = {
33
+ agent: { type: "agent", id: agent.id, version: Number(agent.version) },
34
+ environment_id: env.id,
35
+ };
36
+ if (vaultIds.length > 0) params.vault_ids = vaultIds;
37
+ const name = instance?.agent.data.name;
38
+ params.title = title ?? (name ? `${name} (agentschema run)` : "agentschema run");
39
+ return { session: await client.beta.sessions.create(params), notes };
40
+ }
41
+
42
+ // Drives a session one turn at a time. `ui` answers what only a person can:
43
+ // ui.event(event) show an event
44
+ // ui.confirm(event) -> { result: "allow" | "deny", deny_message? } for a paused tool call
45
+ // ui.customToolResult(event) -> string, the result of a custom tool call
46
+ export class Conversation {
47
+ constructor(client, sessionId, ui) {
48
+ this.client = client;
49
+ this.sessionId = sessionId;
50
+ this.ui = ui;
51
+ this.seen = new Set();
52
+ this.stream = null;
53
+ }
54
+
55
+ // Sends a message and handles events until the agent finishes its turn.
56
+ // Returns the idle stop reason, or "terminated".
57
+ async send(text) {
58
+ return this.#turn([{ type: "user.message", content: [{ type: "text", text }] }]);
59
+ }
60
+
61
+ // Asks the agent to stop at the next safe point; the running turn then ends normally.
62
+ async interrupt() {
63
+ await this.client.beta.sessions.events.send(this.sessionId, { events: [{ type: "user.interrupt" }] });
64
+ }
65
+
66
+ async #turn(events) {
67
+ // Stream first: events emitted before the stream opens would never reach us.
68
+ this.stream = await this.client.beta.sessions.events.stream(this.sessionId);
69
+ await this.client.beta.sessions.events.send(this.sessionId, { events });
70
+
71
+ for (let attempt = 0; ; attempt++) {
72
+ try {
73
+ for await (const event of this.stream) {
74
+ const done = await this.#handle(event);
75
+ if (done) return done;
76
+ }
77
+ throw new Error("event stream closed");
78
+ } catch (err) {
79
+ if (this.closed || attempt >= 3) throw err;
80
+ // 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);
82
+ for await (const event of this.client.beta.sessions.events.list(this.sessionId)) {
83
+ const done = await this.#handle(event);
84
+ if (done) return done;
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ // Returns a value when the turn is over.
91
+ async #handle(event) {
92
+ // Events are deduped by ID: the history and the live stream overlap after a reconnect,
93
+ // and a queued user event is echoed twice.
94
+ if (event.id) {
95
+ if (this.seen.has(event.id)) return null;
96
+ this.seen.add(event.id);
97
+ }
98
+ this.ui.event(event);
99
+
100
+ const send = (e) => this.client.beta.sessions.events.send(this.sessionId, { events: [e] });
101
+ switch (event.type) {
102
+ case "agent.tool_use":
103
+ case "agent.mcp_tool_use":
104
+ if (event.evaluated_permission === "ask") {
105
+ const { result, deny_message } = await this.ui.confirm(event);
106
+ const reply = { type: "user.tool_confirmation", tool_use_id: event.id, result };
107
+ if (result === "deny" && deny_message) reply.deny_message = deny_message;
108
+ await send(reply);
109
+ }
110
+ return null;
111
+ case "agent.custom_tool_use": {
112
+ const text = await this.ui.customToolResult(event);
113
+ await send({ type: "user.custom_tool_result", custom_tool_use_id: event.id, content: [{ type: "text", text }] });
114
+ return null;
115
+ }
116
+ case "session.status_idle":
117
+ // requires_action means the session is waiting on one of the replies above.
118
+ return event.stop_reason?.type === "requires_action" ? null : (event.stop_reason?.type ?? "end_turn");
119
+ case "session.status_terminated":
120
+ return "terminated";
121
+ default:
122
+ return null;
123
+ }
124
+ }
125
+
126
+ close() {
127
+ this.closed = true;
128
+ this.stream?.controller?.abort();
129
+ }
130
+ }