@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/README.md CHANGED
@@ -6,16 +6,22 @@ Define an AI-Agent as a folder of Markdown files.
6
6
  my-agent/
7
7
  ├── agent.md # the agent
8
8
  ├── env.md # the environment it runs in
9
- └── tools/ # tool files, in any folders you like
10
- ├── agent_toolset_20260401.md # the pre-built tools to enable
11
- └── get_weather.md
9
+ ├── tools/ # tool files, in any folders you like
10
+ │ ├── agent_toolset_20260401.md # the pre-built tools to enable
11
+ │ └── get_weather.md
12
+ ├── skills/ # instructions the agent loads when a task needs them
13
+ │ └── code-review/
14
+ │ └── SKILL.md
15
+ └── vaults/ # credentials for MCP servers and API keys
16
+ └── Ops/ # a vault, named after its folder
17
+ └── Slack.md # a credential, without its secrets
12
18
  ```
13
19
 
14
20
  **Status:** v0.2.1 draft. v0.2 breaks from the Claude Managed Agents schema: tools move out of `agent.md` and into `tools/`.
15
21
 
16
22
  ## Philosophy
17
23
 
18
- 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.
24
+ 1. **One folder, one agent.** A folder defines one agent, the one environment it runs in, and the shared vaults its runs use. Sessions, each user's own credentials, mounted files and repositories, and schedules are supplied by whatever runs the agent.
19
25
  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.
20
26
  3. **Inspired by Claude Managed Agents, not tied to it.** `agent.md` and `env.md` use the Claude Managed Agents fields because they're a well-documented vocabulary for agents. Tools are the exception: they're split into their own files, and agentschema compiles them into the API's format. The format itself assumes no particular infrastructure, so any runtime that can read the files can run the agent.
21
27
 
@@ -25,6 +31,8 @@ my-agent/
25
31
  npm install -g @soft-boy/agentschema
26
32
  ```
27
33
 
34
+ This installs the `agentschema` command, and `ags` as a short name for it.
35
+
28
36
  ## Specification
29
37
 
30
38
  ### Files
@@ -35,9 +43,17 @@ An instance is a folder of Markdown files. `agent.md` and `env.md` are required.
35
43
  my-agent/
36
44
  ├── agent.md # the agent
37
45
  ├── env.md # the environment (computer)
38
- └── tools/ # tool files, nested however you like
39
- ├── agent_toolset_20260401.md # the pre-built tools to enable
40
- └── get_weather.md
46
+ ├── tools/ # tool files, nested however you like
47
+ │ ├── agent_toolset_20260401.md # the pre-built tools to enable
48
+ │ └── get_weather.md
49
+ ├── skills/ # optional: one folder per skill
50
+ │ └── code-review/
51
+ │ ├── SKILL.md
52
+ │ └── checklist.md # any other files the skill needs
53
+ └── vaults/ # optional: one folder per vault
54
+ └── Ops/
55
+ ├── vault.md # optional: the vault's metadata
56
+ └── Slack.md # one file per credential
41
57
  ```
42
58
 
43
59
  ### `agent.md`
@@ -55,9 +71,9 @@ Field reference: [Environments](https://platform.claude.com/docs/en/managed-agen
55
71
 
56
72
  ### `tools/`
57
73
 
58
- Each `.md` file in `tools/` is either the pre-built toolset or one custom tool.
74
+ Each `.md` file in `tools/` is the pre-built toolset, one MCP server, or one custom tool. `agentschema tools create` writes any of them for you.
59
75
 
60
- Subfolders are only for organizing. Every `.md` file under `tools/`, at any depth, is read, and its folder is ignored when compiling: moving a file between folders changes nothing that's deployed. Because the folders are dropped, two custom tools can't share a name even in different folders. Folders and files whose names start with `.` are skipped.
76
+ Subfolders are only for organizing. Every `.md` file under `tools/`, at any depth, is read, and its folder is ignored when compiling: moving a file between folders changes nothing that's deployed. Because the folders are dropped, two custom tools, or two MCP toolsets, can't share a name even in different folders. Folders and files whose names start with `.` are skipped.
61
77
 
62
78
  **Pre-built tools** are the tools Claude Managed Agents runs in the container: `bash`, `edit`, `glob`, `grep`, `read`, `web_fetch`, `web_search` and `write`. One file lists the ones the agent gets. By convention it's `tools/agent_toolset_20260401.md`, but the file name isn't used:
63
79
 
@@ -80,6 +96,41 @@ type: agent_toolset_20260401
80
96
  - **Permission** is `always_allow`, `always_ask` or `auto`. Leave the cell blank for the API's default (`always_allow`), or leave out the column entirely.
81
97
  - There can be only one such file. Other sections are notes for people.
82
98
 
99
+ **MCP toolsets** give the agent the tools a remote MCP server offers. Declare the server in `agent.md`, with the API's fields:
100
+
101
+ ```yaml
102
+ mcp_servers:
103
+ - type: url
104
+ name: calendar
105
+ url: https://calendarmcp.googleapis.com/mcp/v1
106
+ ```
107
+
108
+ Then give it one file in `tools/`, named after the server:
109
+
110
+ ```markdown
111
+ ---
112
+ type: mcp_toolset
113
+ mcp_server_name: calendar
114
+ default_config:
115
+ enabled: false
116
+ ---
117
+
118
+ ## Tools
119
+
120
+ | Name | Enabled | Permission |
121
+ |---|---|---|
122
+ | `list_events` | `true` | `always_allow` |
123
+ | `create_event` | `true` | |
124
+ ```
125
+
126
+ - **`mcp_server_name`** is required, and must match both the file name and a server in `agent.md`. A server with no toolset file is an error too, because the API rejects it.
127
+ - **`default_config`** is optional, and applies to every tool without a row: `enabled` and `permission_policy`, as in the API. Without it, all the server's tools are on, and they ask for approval before each call (`always_ask`). `enabled: false`, as above, turns on only the tools you list.
128
+ - **`## Tools`** is optional, and configures tools by the names the server reports. The server defines its own tools, so `check` can't verify these names.
129
+ - **Sign-in:** a server that needs it gets its credentials from `vaults/`, matched by URL. `agentschema cred create` offers the servers in `agent.md`.
130
+ - **Networking:** with `limited` networking in `env.md`, set `allow_mcp_servers: true` or add the server's host to `allowed_hosts`, or the API won't start sessions. `check` warns about this.
131
+
132
+ An agent can have up to 20 MCP servers.
133
+
83
134
  **Custom tools** run on your side: when the agent calls one, `agentschema run` runs its code on your machine and sends back the result.
84
135
 
85
136
  ````markdown
@@ -108,22 +159,100 @@ module.exports = ({ city }) =>
108
159
  - **`## Code`** is required, and must be one JavaScript code block. It's a CommonJS module, and `module.exports` is the function. It's called with the call's input as an object. A string it returns (or resolves to) is sent as the result; anything else is sent as JSON. If it throws, the error message is sent as an error result. `require()` resolves from the tool's file, so packages installed in the agent folder work.
109
160
  - Other sections are notes for people.
110
161
 
111
- **Compiling.** `deploy` turns `tools/` into the agent's `tools` list, sorted by tool name: one `agent_toolset_20260401` entry with a config for each row of the `## Tools` table (its `enabled`, and its `permission_policy` if it has one), then the custom tools. A custom tool sends only its name, description and input schema; the code never leaves your machine.
162
+ **Compiling.** `deploy` turns `tools/` into the agent's `tools` list, sorted by tool name: one `agent_toolset_20260401` entry with a config for each row of the `## Tools` table (its `enabled`, and its `permission_policy` if it has one), then an `mcp_toolset` entry for each MCP toolset file, then the custom tools. A custom tool sends only its name, description and input schema; the code never leaves your machine.
163
+
164
+ ### `skills/`
165
+ Field reference: [Skills](https://platform.claude.com/docs/en/managed-agents/skills).
166
+
167
+ Skills are instructions, and optionally scripts or reference files, that the agent loads only when a task calls for them. Each folder in `skills/` is one skill, following the standard layout: a `SKILL.md`, plus any other files it needs, at any depth.
168
+
169
+ ```markdown
170
+ ---
171
+ name: code-review
172
+ description: Review code for bugs, security problems and missing tests. Use when asked to review a change.
173
+ ---
174
+
175
+ Read `checklist.md`, then go through the change one file at a time.
176
+ ```
177
+
178
+ - **`name`** is required, and must match the folder's name. It may use lowercase letters, digits and hyphens, up to 64 characters, and can't contain `anthropic` or `claude`.
179
+ - **`description`** is required, up to 1,024 characters, with no XML tags. The agent reads it to decide when to load the skill. Other frontmatter fields are left as written.
180
+ - **Files:** hidden files and `node_modules` aren't uploaded. A skill's files can add up to 30 MB.
181
+ - **Everything in the folder is uploaded to Anthropic,** so keep secrets out. `check` scans these files too.
182
+
183
+ Every skill in the folder is attached to the agent. To use Anthropic's pre-built skills, or a skill that already exists in your workspace, list it under `skills` in `agent.md`'s frontmatter, as in the API; `deploy` adds the folder's skills to that list.
184
+
185
+ ### `vaults/`
186
+ Field reference: [Vaults](https://platform.claude.com/docs/en/managed-agents/vaults).
187
+
188
+ Vaults hold the credentials the agent's MCP servers and API calls need. Each folder in `vaults/` is one vault, and the folder name is the vault's name. `run` attaches every vault to its session, in folder name order: when two vaults have a credential for the same server, the first one wins.
189
+
190
+ - **`vault.md`** is optional. Its frontmatter takes the vault's `metadata`; the body is a note for people.
191
+ - **Every other `.md` file is a credential**, and the file name is the credential's name. It's either `mcp_oauth`, for an MCP server's sign-in, or `environment_variable`, for an API key. A vault holds at most 20, one per MCP server or variable.
192
+
193
+ A credential file holds its settings, using the fields of the API's `auth` object, but never its secrets. This is an `mcp_oauth` credential:
194
+
195
+ ```markdown
196
+ ---
197
+ auth:
198
+ type: mcp_oauth
199
+ mcp_server_url: https://mcp.slack.com/mcp
200
+ refresh:
201
+ token_endpoint: https://slack.com/api/oauth.v2.user.access
202
+ client_id: "1234567890.0987654321"
203
+ scope: channels:read chat:write
204
+ token_endpoint_auth:
205
+ type: client_secret_post
206
+ ---
207
+
208
+ The ops bot's Slack token.
209
+ ```
210
+
211
+ - **No secrets.** `access_token`, `expires_at`, `refresh.refresh_token` and `token_endpoint_auth.client_secret` are errors in a file. The `cred` commands get them by signing you in, or ask you to paste them; either way they go straight to the vault, so they're never on disk and everything in `vaults/` can be committed. The vault is their source of truth from then on: Anthropic refreshes the access token, and many providers replace the refresh token each time.
212
+ - **`refresh`** is optional, but without it the credential stops working when the access token expires.
213
+ - **Some fields can't change** once the credential exists: `type`, `mcp_server_url`, whether there's a `refresh` block, and its `token_endpoint`, `client_id`, `resource` and `token_endpoint_auth.type`, or an environment variable's `secret_name`. Changing one is an error at `deploy`; delete the credential with `cred delete` and create it again. Other settings, the metadata and the note can change.
214
+
215
+ An `environment_variable` credential gives code in the agent's container an API key it never sees. The sandbox holds a placeholder, and Anthropic swaps in the real value as a request leaves:
216
+
217
+ ```markdown
218
+ ---
219
+ auth:
220
+ type: environment_variable
221
+ secret_name: STRIPE_API_KEY
222
+ networking:
223
+ type: limited
224
+ allowed_hosts:
225
+ - api.stripe.com
226
+ injection_location:
227
+ header: true
228
+ body: false
229
+ ---
230
+ ```
231
+
232
+ - **`networking`** is required, and says which hosts get the real value. It doesn't open the network: with `limited` networking in `env.md`, those hosts must be allowed there too, and `check` warns if they aren't. `unrestricted` substitutes the value on a request to any host, so a prompt-injected agent could send it anywhere; `check` warns about that as well.
233
+ - **`injection_location`** is optional, and says where in a request the value may appear. Without it, both are on; with it, a field you leave out is off.
234
+ - **It holds one fixed value,** so it suits long-lived keys, not tokens that expire. It only reaches code in the container, so custom tools can't use it, because they run on your side. It isn't supported on self-hosted environments yet.
235
+ - **Two vaults setting the same variable:** the docs don't say which wins, so `check` warns.
112
236
 
113
237
  ## Usage
114
238
 
115
239
  ```sh
116
240
  agentschema init <name> # scaffold a new agent folder
117
241
  agentschema check [dir] # validate the folder, no network
118
- agentschema deploy [dir] # create or update the agent and environment
242
+ agentschema deploy [dir] # create or update the skills, agent, environment and vaults
119
243
  agentschema run [dir] # chat with the deployed agent in the terminal
120
244
  agentschema list # list the agents in your workspace
121
245
  agentschema delete <agent_id> # archive an agent
246
+ agentschema tools create [dir] # add pre-built tools, a custom tool or an MCP server
122
247
  agentschema sessions list # list the sessions in your workspace
123
248
  agentschema sessions delete <id> # delete a session
249
+ agentschema cred create [dir] # add a credential to a vault, asking a few questions
250
+ agentschema cred deploy <file> # create a credential file's credential in Anthropic
251
+ agentschema cred login <file> # sign in to a credential's server in the browser
252
+ agentschema cred delete <file> # delete a credential
124
253
  ```
125
254
 
126
- `dir` defaults to the current directory.
255
+ `dir` defaults to the current directory. `ags` is a short name for `agentschema`. `agentschema -h` lists the commands; `tools`, `sessions` and `cred` have their own help, such as `agentschema cred -h`.
127
256
 
128
257
  **`init`** creates the folder `<name>` with an `agent.md` and an `env.md` that pass `check`. It asks for:
129
258
  - the agent's name and model
@@ -137,24 +266,29 @@ Press Enter to keep the default shown, or pass `--yes` to skip the questions. `i
137
266
  - a missing file, or a name that isn't lowercase
138
267
  - frontmatter that is missing, unclosed, or invalid YAML
139
268
  - a missing `name` or `model`, or a `system` or `tools` key in `agent.md`'s frontmatter
140
- - a pre-built tools table that names an unknown tool or permission, or a custom tool with a missing description, a malformed input table, or code that isn't JavaScript or doesn't parse
269
+ - a pre-built tools table that names an unknown tool or permission, an MCP server without both its entry in `agent.md` and its toolset file, or a custom tool with a missing description, a malformed input table, or code that isn't JavaScript or doesn't parse
270
+ - a skill with no `SKILL.md`, or a `name` or `description` the API would reject
271
+ - a credential file with a secret in it, a missing field, or two credentials for the same server
141
272
  - values over the API's limits
142
273
  - anything that looks like an API key or token
143
274
 
144
275
  Unknown fields are only warnings, because they're sent to the API as written. `check` exits with status 1 when there are errors.
145
276
 
146
- **`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.
277
+ **`deploy`** runs `check` first, then creates or updates the skills, the environment, the agent and the vaults, and records their IDs in `claude-lock.json` in the folder. Commit that file.
147
278
  - **Later runs update the same resources.** A file that hasn't changed since the last deploy is skipped. Each change to `agent.md` or `tools/` adds a new version of the agent, and sessions already running keep the version they started on.
148
279
  - **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.
149
280
  - **Changes made elsewhere aren't overwritten silently.** If the agent was changed outside the folder since the last deploy, `deploy` stops; `--force` overwrites it.
281
+ - **A changed skill gets a new version.** Any change to a skill's files uploads the whole folder as a new version. The agent is pinned to skill versions, so that also adds a new version of the agent, and sessions already running keep what they started on. Deleting a skill's folder detaches it from the agent, but the skill stays in your workspace until you delete it in the Console. Renaming the folder creates a new skill.
282
+ - **Credentials are updated, not created.** Creating a credential needs its secrets, which aren't in the files, so `deploy` lists each credential file that has no credential yet, with the `cred deploy` command to run. It updates the settings of credentials that exist.
150
283
 
151
284
  `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.
152
285
 
153
286
  **`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.
154
287
  - **Messages:** type a message and press Enter. The agent's replies stream in, with a one-line summary of each tool call.
155
288
  - **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.
156
- - **Custom tools:** `run` runs the tool's code from `tools/` and sends back the result. The code runs on your machine with your permissions, like any script in the folder. If the folder doesn't pass `check`, or the tool isn't in it (for example, when you resume a session from somewhere else), `run` shows the call's input and asks you to type the result.
289
+ - **Custom tools:** `run` runs the tool's code from `tools/` and sends back the result. The code runs on your machine with your permissions, like any script in the folder. Settings the code needs can go in a `.env` file in the agent folder, as `KEY=VALUE` lines, which `run` loads before it starts. Keep `.env` out of git. A variable already set in your shell wins, and `.env` doesn't change which Anthropic credentials `run` uses. If the folder doesn't pass `check`, or the tool isn't in it (for example, when you resume a session from somewhere else), `run` shows the call's input and asks you to type the result.
157
290
  - **Interrupting:** Ctrl+C interrupts the agent mid-turn, and a second Ctrl+C quits. Ctrl+D quits at the prompt.
291
+ - **Vaults:** the session gets every vault in `vaults/` that's been deployed, in folder name order. `run` warns about vaults that haven't been deployed and credentials that haven't been created.
158
292
  - **Resuming:** quitting leaves the session in place, and `run` prints a command to resume it: `agentschema run --resume sesn_…`.
159
293
 
160
294
  ```sh
@@ -165,6 +299,11 @@ To run the agent from your own code, create a session with the agent and environ
165
299
 
166
300
  **`list`** prints every agent in your workspace, with its ID, latest version, model and when it was last updated. It includes agents that weren't deployed with agentschema, and leaves out archived ones.
167
301
 
302
+ **`tools create`** adds a tool, asking a few questions like `init`. It only writes files; `deploy` sends them to the API.
303
+ - **Pre-built tools:** turn on all eight, or pick them one by one. It writes `tools/agent_toolset_20260401.md`, and stops if the agent already has that file.
304
+ - **Custom tool:** its name, what it does, and each input's name, type, description and whether it's required. It writes `tools/<name>.md` with a code block to fill in, which throws "isn't implemented yet" until you do.
305
+ - **MCP server:** its URL, its name and the permission for its tools. It asks the server for its tools, adds the server to `mcp_servers` in `agent.md`, keeping the rest of that file as written, and writes `tools/<name>.md` with a `## Tools` table listing them all as enabled, with that permission; edit the table to turn tools off. If `agent.md` already declares that server, it only writes the file. A server that won't list its tools without signing in gets no table, so every tool is on with that permission. A tool the server adds later isn't in the table, so it gets the API's defaults.
306
+
168
307
  **`sessions list`** prints every session in your workspace, newest first, with its status, the agent and version it runs, and its title. Pass an ID to `run --resume` to pick a session back up.
169
308
 
170
309
  **`delete`** archives an agent. The API can't delete agents outright, so this is as close as it gets. An archived agent drops out of `list`, and the API has no way to unarchive it. If the agent is in a folder's `claude-lock.json`, remove its entry so the next `deploy` creates a new one.
@@ -173,6 +312,28 @@ To run the agent from your own code, create a session with the agent and environ
173
312
 
174
313
  Both ask for confirmation first, showing the agent's name or the session's title. Pass `--yes` to skip that, for example in scripts; without a terminal to ask in, they refuse unless you pass `--yes`.
175
314
 
315
+ **`cred create`** adds a credential, asking a few questions like `init`:
316
+ 1. Which vault it goes in: one in `vaults/`, or a new one.
317
+ 2. Whether it's for an MCP server's sign-in or an environment variable.
318
+ 3. For an MCP server: which one (from `agent.md`'s `mcp_servers` where the vault has no credential for it yet, or any URL), its name, and how to get its tokens: sign in with the browser (when the server publishes an OAuth sign-in), paste them, or just write the file for later.
319
+ 4. For an environment variable: its name, the hosts it may be sent to, where in a request it can appear, the credential's name, and whether to paste the value now or just write the file. The menu only writes `limited` networking; edit the file for `unrestricted`.
320
+
321
+ It writes `vaults/<vault>/<name>.md`, asking for the OAuth client's details when the file needs them. Then it signs you in as `cred login` does, or asks for the tokens without showing what you type: the access token, when it expires, and with a `refresh` block, the refresh token and client secret. It creates the vault first if it hasn't been deployed. If you chose to just write the file, create the credential later with `cred deploy`.
322
+
323
+ **`cred deploy`** creates the credential an existing file describes in Anthropic, such as one you wrote by hand or one `deploy` lists as missing: `agentschema cred deploy my-agent/vaults/Ops/Slack.md`. It asks whether to sign in with the browser or paste the tokens; for an environment variable, it just asks for the value. A credential that already exists is an error when pasting; to replace its tokens, run `cred login`, or delete it and deploy it again.
324
+
325
+ **`cred login`** creates a credential by signing you in to its MCP server in the browser, for example `agentschema cred login my-agent/vaults/Ops/Linear.md`. The file needs only `type` and `mcp_server_url`:
326
+ 1. It finds the server's sign-in from its URL, using the OAuth metadata MCP servers publish.
327
+ 2. It needs an OAuth client. With a `refresh` block in the file, it uses that block's `client_id`, and asks for the client secret unless `token_endpoint_auth.type` is `none`. Without one, it registers agentschema as a client, which servers such as Linear and Notion allow, and writes the `refresh` block into the file.
328
+ 3. It opens your browser to sign in, and receives the result on `http://127.0.0.1:<port>/callback`. The port is any free one, or `--port`.
329
+ 4. It creates the credential with the tokens, creating the vault first if needed. If the credential already exists, it replaces its tokens instead, so signing in again is how you renew a credential whose refresh token stopped working.
330
+
331
+ It stops without creating anything if the server doesn't return a refresh token, since the credential would stop working within the hour.
332
+
333
+ Some servers, such as Google's and Slack's, don't let apps register themselves. For those, create an OAuth client with the provider first, add its details to the file's `refresh` block (`cred login` prints what to add), and allow the redirect URI `http://127.0.0.1:<port>/callback`. A client that needs an exact redirect URI needs a fixed `--port`. For Google, `cred login` also asks for offline access, which Google requires before it issues a refresh token.
334
+
335
+ **`cred delete`** permanently deletes the credential a file describes and removes it from `claude-lock.json`. The file stays, so you can create it again. It asks for confirmation unless you pass `--yes`.
336
+
176
337
  ### Authentication
177
338
 
178
339
  agentschema has no account setting of its own. Every command except `init` and `check` uses whichever Anthropic credentials are in your shell:
@@ -4,24 +4,34 @@ import { createInterface } from "node:readline/promises";
4
4
  import { parseArgs } from "node:util";
5
5
  import Anthropic from "@anthropic-ai/sdk";
6
6
  import { chat } from "../src/chat.js";
7
+ import { spawn } from "node:child_process";
8
+ import { credCreate, credDeploy } from "../src/cred-menu.js";
9
+ import { credDelete, credLogin } from "../src/cred.js";
7
10
  import { check } from "../src/check.js";
8
11
  import { DeleteError, deleteAgent, deleteSession } from "../src/delete.js";
9
12
  import { DeployError, deploy } from "../src/deploy.js";
13
+ import { loadEnvFile } from "../src/dotenv.js";
10
14
  import { InitError, init } from "../src/init.js";
11
15
  import { listAgents, listSessions } from "../src/list.js";
16
+ import { prompts } from "../src/prompts.js";
12
17
  import { SessionError, openSession } from "../src/session.js";
18
+ import { toolsCreate } from "../src/tools-menu.js";
19
+
20
+ const FOOTER = `ags is a short name for agentschema. dir defaults to the current directory. Every command
21
+ but init, check and tools create authenticates with ANTHROPIC_API_KEY, or with a profile from \`ant auth login\`.`;
13
22
 
14
23
  const USAGE = `Usage: agentschema <command> [dir] [options]
15
24
 
16
25
  Commands:
17
26
  init <name> Scaffold a new agent folder, asking a few questions
18
- check [dir] Validate agent.md and env.md, without calling the API
19
- deploy [dir] Create or update the agent and environment, and write claude-lock.json
20
- run [dir] Chat with the deployed agent in a new session
27
+ check [dir] Validate the folder's files, without calling the API
28
+ deploy [dir] Create or update the skills, agent, environment and vaults, and write claude-lock.json
29
+ run [dir] Chat with the deployed agent in a new session, loading dir/.env for your tools
21
30
  list List the agents in your workspace
22
31
  delete <agent_id> Archive an agent (agents can't be deleted outright)
23
- sessions list List the sessions in your workspace, newest first
24
- sessions delete <id> Delete a session and its history
32
+ tools <command> Add pre-built tools, custom tools and MCP servers (agentschema tools -h)
33
+ sessions <command> List and delete sessions (agentschema sessions -h)
34
+ cred <command> Create and manage the credentials in vaults/ (agentschema cred -h)
25
35
 
26
36
  Options:
27
37
  -y, --yes (init) Skip the questions and use the defaults
@@ -32,14 +42,65 @@ Options:
32
42
  -h, --help Show this help
33
43
  -v, --version Show the version
34
44
 
35
- dir defaults to the current directory. Every command but init and check authenticates with
36
- ANTHROPIC_API_KEY, or with a profile from \`ant auth login\`.`;
45
+ ${FOOTER}`;
46
+
47
+ const TOOLS_USAGE = `Usage: agentschema tools <command> [options]
48
+
49
+ Each tool is a file in tools/. The pre-built tools share one file, each custom tool has its own,
50
+ and so does each MCP server.
51
+
52
+ Commands:
53
+ create [dir] Add a tool: asks whether it's the pre-built tools, a custom tool or an
54
+ MCP server, then writes its file
55
+
56
+ Options:
57
+ -h, --help Show this help
58
+
59
+ dir defaults to the current directory.`;
60
+
61
+ const SESSIONS_USAGE = `Usage: agentschema sessions <command> [options]
62
+
63
+ Commands:
64
+ list List the sessions in your workspace, newest first
65
+ delete <id> Delete a session and its history
66
+
67
+ Options:
68
+ -y, --yes (delete) Don't ask for confirmation
69
+ -h, --help Show this help
70
+
71
+ Resume a session with agentschema run --resume <id>.`;
72
+
73
+ const CRED_USAGE = `Usage: agentschema cred <command> [options]
74
+
75
+ Each credential is a file in vaults/<vault>/<name>.md, without its secrets, which go straight
76
+ to Anthropic.
77
+
78
+ Commands:
79
+ create [dir] Add a credential: asks which vault it goes in and whether it's for an MCP
80
+ server or an environment variable, writes its file, then signs you in or
81
+ asks for its secrets, and creates it in Anthropic
82
+ deploy <file> Create the credential a file describes in Anthropic, by signing in or
83
+ pasting its secrets
84
+ login <file> Sign in to the credential's MCP server in the browser, and store the tokens,
85
+ creating the credential or replacing the tokens of the existing one
86
+ delete <file> Delete the credential a file describes from Anthropic; the file stays
87
+
88
+ Options:
89
+ --port <port> (create, deploy, login) Port for the sign-in redirect (default: any free port)
90
+ -y, --yes (delete) Don't ask for confirmation
91
+ -h, --help Show this help
92
+
93
+ dir defaults to the current directory.`;
94
+
95
+ // The commands that group subcommands, and their help.
96
+ const GROUPS = { tools: TOOLS_USAGE, sessions: SESSIONS_USAGE, cred: CRED_USAGE };
37
97
 
38
98
  const OPTIONS = {
39
99
  yes: { type: "boolean", short: "y" },
40
100
  "dry-run": { type: "boolean" },
41
101
  force: { type: "boolean" },
42
102
  resume: { type: "string" },
103
+ port: { type: "string" },
43
104
  help: { type: "boolean", short: "h" },
44
105
  version: { type: "boolean", short: "v" },
45
106
  };
@@ -51,8 +112,13 @@ const COMMANDS = {
51
112
  run: { args: [0, 1], options: ["resume"] },
52
113
  list: { args: [0, 0], options: [] },
53
114
  delete: { args: [1, 1], options: ["yes"] },
115
+ "tools create": { args: [0, 1], options: [] },
54
116
  "sessions list": { args: [0, 0], options: [] },
55
117
  "sessions delete": { args: [1, 1], options: ["yes"] },
118
+ "cred create": { args: [0, 1], options: ["port"] },
119
+ "cred deploy": { args: [1, 1], options: ["port"] },
120
+ "cred login": { args: [1, 1], options: ["port"] },
121
+ "cred delete": { args: [1, 1], options: ["yes"] },
56
122
  };
57
123
 
58
124
  async function main(argv) {
@@ -60,39 +126,45 @@ async function main(argv) {
60
126
  try {
61
127
  parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
62
128
  } catch (err) {
63
- console.error(`agentschema: ${err.message}\n\n${USAGE}`);
129
+ console.error(`agentschema: ${err.message}\n\n${GROUPS[argv[0]] ?? USAGE}`);
64
130
  return 1;
65
131
  }
66
132
  const { values, positionals } = parsed;
67
133
  let [command, ...args] = positionals;
68
- if (command === "sessions") command = `sessions ${args.shift() ?? ""}`.trim();
134
+ const group = command in GROUPS ? command : null;
135
+ if (group) command = `${group} ${args.shift() ?? ""}`.trim();
136
+ const usage = group ? GROUPS[group] : USAGE;
69
137
 
70
138
  if (values.version) {
71
139
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
72
140
  console.log(pkg.version);
73
141
  return 0;
74
142
  }
75
- if (!command || values.help) {
143
+ if (values.help) {
144
+ console.log(usage);
145
+ return 0;
146
+ }
147
+ if (!command) {
76
148
  console.log(USAGE);
77
- return command || values.help ? 0 : 1;
149
+ return 1;
78
150
  }
79
- if (command.startsWith("sessions") && !(command in COMMANDS)) {
80
- console.error(`agentschema: usage: agentschema sessions list | sessions delete <id>`);
151
+ if (group && command === group) {
152
+ console.error(usage);
81
153
  return 1;
82
154
  }
83
155
  if (!(command in COMMANDS)) {
84
- console.error(`agentschema: unknown command "${command}"\n\n${USAGE}`);
156
+ console.error(`agentschema: unknown command "${command}"\n\n${usage}`);
85
157
  return 1;
86
158
  }
87
159
  const spec = COMMANDS[command];
88
160
  const misplaced = Object.keys(values).filter((k) => !spec.options.includes(k));
89
161
  if (args.length > spec.args[1] || misplaced.length > 0) {
90
162
  const arg = args[spec.args[1]] ?? `--${misplaced[0]}`;
91
- console.error(`agentschema: unexpected argument ${arg} for ${command}\n\n${USAGE}`);
163
+ console.error(`agentschema: unexpected argument ${arg} for ${command}\n\n${usage}`);
92
164
  return 1;
93
165
  }
94
166
  if (args.length < spec.args[0]) {
95
- const example = { init: "init my-agent", delete: "delete agent_…", "sessions delete": "sessions delete sesn_…" }[command];
167
+ const example = { init: "init my-agent", delete: "delete agent_…", "sessions delete": "sessions delete sesn_…", "cred deploy": "cred deploy my-agent/vaults/Ops/Slack.md", "cred login": "cred login my-agent/vaults/Ops/Slack.md", "cred delete": "cred delete my-agent/vaults/Ops/Slack.md" }[command];
96
168
  console.error(`agentschema: ${command} needs an argument, e.g. agentschema ${example}`);
97
169
  return 1;
98
170
  }
@@ -146,8 +218,44 @@ async function main(argv) {
146
218
  return 0;
147
219
  }
148
220
 
221
+ if (command === "tools create") {
222
+ const io = prompts(process.stdin, process.stdout, { cancelled: () => new DeployError("cancelled") });
223
+ try {
224
+ await toolsCreate(args[0] ?? ".", { io, log: (line) => console.log(line) });
225
+ } finally {
226
+ io.close();
227
+ }
228
+ return 0;
229
+ }
230
+
231
+ if (["cred create", "cred deploy", "cred login"].includes(command)) {
232
+ if (values.port !== undefined && !/^\d+$/.test(values.port)) throw new DeployError(`--port must be a number, not "${values.port}"`);
233
+ const io = prompts(process.stdin, process.stdout, { cancelled: () => new DeployError("cancelled") });
234
+ const options = { client: makeClient(false), openBrowser, port: values.port ?? 0, log: (line) => console.log(line) };
235
+ try {
236
+ if (command === "cred create") await credCreate(args[0] ?? ".", { ...options, io });
237
+ else if (command === "cred deploy") await credDeploy(args[0], { ...options, io });
238
+ else await credLogin(args[0], { ...options, ask: (q, { secret }) => (secret ? io.secret(q.trim()) : io.text(q.trim())) });
239
+ } finally {
240
+ io.close();
241
+ }
242
+ return 0;
243
+ }
244
+
245
+ if (command === "cred delete") {
246
+ await credDelete(args[0], {
247
+ client: makeClient(false),
248
+ confirm: values.yes ? async () => true : confirm,
249
+ log: (line) => console.log(line),
250
+ });
251
+ return 0;
252
+ }
253
+
149
254
  if (command === "run") {
255
+ // Made first, so .env only reaches your tools: Anthropic credentials still come from the
256
+ // shell, the same as for every other command.
150
257
  const client = makeClient(false);
258
+ for (const warning of loadEnvFile(dir)) console.warn(`warning: ${warning}`);
151
259
  const { session, notes } = await openSession(dir, {
152
260
  client,
153
261
  sessionId: values.resume,
@@ -180,6 +288,18 @@ async function confirm(question) {
180
288
  }
181
289
  }
182
290
 
291
+ // Opens a URL in the default browser; the URL is also printed, in case this fails.
292
+ function openBrowser(url) {
293
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]]
294
+ : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
295
+ : ["xdg-open", [url]];
296
+ try {
297
+ spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {}).unref();
298
+ } catch {
299
+ // The URL was printed; the user can open it.
300
+ }
301
+ }
302
+
183
303
  // The folder's custom tools, by name, for run to execute. A folder that doesn't pass check
184
304
  // runs none of them; run asks you for each result instead.
185
305
  function customTools(dir) {
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@soft-boy/agentschema",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Markdown based AI agent schema",
5
5
  "type": "module",
6
6
  "bin": {
7
- "agentschema": "bin/agentschema.js"
7
+ "agentschema": "bin/agentschema.js",
8
+ "ags": "bin/agentschema.js"
8
9
  },
9
10
  "files": [
10
11
  "bin",
package/src/chat.js CHANGED
@@ -54,6 +54,54 @@ function firstLine(content = []) {
54
54
 
55
55
  const truncate = (s, n = 100) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
56
56
 
57
+ // Prints the agent's text as it streams in, chunk by chunk. Deltas are best effort (the server
58
+ // may stop sending them under load), so the complete agent.message that follows is the record:
59
+ // whatever part of it the deltas didn't cover is printed then.
60
+ export function textStream(write) {
61
+ let preview = null; // { id, text } for the agent.message being previewed
62
+ const close = () => {
63
+ if (preview?.text) write("\n");
64
+ preview = null;
65
+ };
66
+ return {
67
+ // Returns true when the event was printed here, so it shouldn't be printed again.
68
+ handle(event) {
69
+ switch (event.type) {
70
+ case "event_start":
71
+ close();
72
+ if (event.event?.type === "agent.message") preview = { id: event.event.id, text: "" };
73
+ return true;
74
+ case "event_delta": {
75
+ const content = event.delta?.content;
76
+ if (preview?.id !== event.event_id || content?.type !== "text" || !content.text) return true;
77
+ preview.text += content.text;
78
+ write(content.text);
79
+ return true;
80
+ }
81
+ case "agent.message": {
82
+ if (preview?.id !== event.id) {
83
+ close();
84
+ return false;
85
+ }
86
+ const full = formatEvent(event);
87
+ const shown = preview.text;
88
+ preview = null;
89
+ if (full.startsWith(shown)) {
90
+ if (full.length > 0) write(`${full.slice(shown.length)}\n`);
91
+ } else {
92
+ write(`\n${full}\n`);
93
+ }
94
+ return true;
95
+ }
96
+ default:
97
+ // A model request that errors or is interrupted ends without its agent.message.
98
+ close();
99
+ return false;
100
+ }
101
+ },
102
+ };
103
+ }
104
+
57
105
  // Runs a custom tool's code with the call's input. A thrown error is returned as an error
58
106
  // result, so the agent sees what went wrong.
59
107
  export async function runTool(tool, input) {
@@ -81,8 +129,10 @@ export async function chat(client, session, { agentName, tools = {}, input = pro
81
129
  return done ? null : value;
82
130
  };
83
131
 
132
+ const stream = textStream((text) => output.write(text));
84
133
  const ui = {
85
134
  event(event) {
135
+ if (stream.handle(event)) return;
86
136
  const text = formatEvent(event);
87
137
  if (text) output.write(`${text}\n`);
88
138
  },