@soft-boy/agentschema 0.2.1 → 0.2.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/README.md CHANGED
@@ -6,16 +6,19 @@ 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
+ └── vaults/ # credentials for MCP servers and API keys
13
+ └── Ops/ # a vault, named after its folder
14
+ └── Slack.md # a credential, without its secrets
12
15
  ```
13
16
 
14
17
  **Status:** v0.2.1 draft. v0.2 breaks from the Claude Managed Agents schema: tools move out of `agent.md` and into `tools/`.
15
18
 
16
19
  ## Philosophy
17
20
 
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.
21
+ 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
22
  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
23
  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
24
 
@@ -25,6 +28,8 @@ my-agent/
25
28
  npm install -g @soft-boy/agentschema
26
29
  ```
27
30
 
31
+ This installs the `agentschema` command, and `ags` as a short name for it.
32
+
28
33
  ## Specification
29
34
 
30
35
  ### Files
@@ -35,9 +40,13 @@ An instance is a folder of Markdown files. `agent.md` and `env.md` are required.
35
40
  my-agent/
36
41
  ├── agent.md # the agent
37
42
  ├── 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
43
+ ├── tools/ # tool files, nested however you like
44
+ │ ├── agent_toolset_20260401.md # the pre-built tools to enable
45
+ │ └── get_weather.md
46
+ └── vaults/ # optional: one folder per vault
47
+ └── Ops/
48
+ ├── vault.md # optional: the vault's metadata
49
+ └── Slack.md # one file per credential
41
50
  ```
42
51
 
43
52
  ### `agent.md`
@@ -55,9 +64,9 @@ Field reference: [Environments](https://platform.claude.com/docs/en/managed-agen
55
64
 
56
65
  ### `tools/`
57
66
 
58
- Each `.md` file in `tools/` is either the pre-built toolset or one custom tool.
67
+ 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
68
 
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.
69
+ 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
70
 
62
71
  **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
72
 
@@ -80,6 +89,41 @@ type: agent_toolset_20260401
80
89
  - **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
90
  - There can be only one such file. Other sections are notes for people.
82
91
 
92
+ **MCP toolsets** give the agent the tools a remote MCP server offers. Declare the server in `agent.md`, with the API's fields:
93
+
94
+ ```yaml
95
+ mcp_servers:
96
+ - type: url
97
+ name: calendar
98
+ url: https://calendarmcp.googleapis.com/mcp/v1
99
+ ```
100
+
101
+ Then give it one file in `tools/`, named after the server:
102
+
103
+ ```markdown
104
+ ---
105
+ type: mcp_toolset
106
+ mcp_server_name: calendar
107
+ default_config:
108
+ enabled: false
109
+ ---
110
+
111
+ ## Tools
112
+
113
+ | Name | Enabled | Permission |
114
+ |---|---|---|
115
+ | `list_events` | `true` | `always_allow` |
116
+ | `create_event` | `true` | |
117
+ ```
118
+
119
+ - **`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.
120
+ - **`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.
121
+ - **`## 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.
122
+ - **Sign-in:** a server that needs it gets its credentials from `vaults/`, matched by URL. `agentschema cred create` offers the servers in `agent.md`.
123
+ - **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.
124
+
125
+ An agent can have up to 20 MCP servers.
126
+
83
127
  **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
128
 
85
129
  ````markdown
@@ -108,22 +152,79 @@ module.exports = ({ city }) =>
108
152
  - **`## 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
153
  - Other sections are notes for people.
110
154
 
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.
155
+ **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.
156
+
157
+ ### `vaults/`
158
+ Field reference: [Vaults](https://platform.claude.com/docs/en/managed-agents/vaults).
159
+
160
+ 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.
161
+
162
+ - **`vault.md`** is optional. Its frontmatter takes the vault's `metadata`; the body is a note for people.
163
+ - **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.
164
+
165
+ 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:
166
+
167
+ ```markdown
168
+ ---
169
+ auth:
170
+ type: mcp_oauth
171
+ mcp_server_url: https://mcp.slack.com/mcp
172
+ refresh:
173
+ token_endpoint: https://slack.com/api/oauth.v2.user.access
174
+ client_id: "1234567890.0987654321"
175
+ scope: channels:read chat:write
176
+ token_endpoint_auth:
177
+ type: client_secret_post
178
+ ---
179
+
180
+ The ops bot's Slack token.
181
+ ```
182
+
183
+ - **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.
184
+ - **`refresh`** is optional, but without it the credential stops working when the access token expires.
185
+ - **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.
186
+
187
+ 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:
188
+
189
+ ```markdown
190
+ ---
191
+ auth:
192
+ type: environment_variable
193
+ secret_name: STRIPE_API_KEY
194
+ networking:
195
+ type: limited
196
+ allowed_hosts:
197
+ - api.stripe.com
198
+ injection_location:
199
+ header: true
200
+ body: false
201
+ ---
202
+ ```
203
+
204
+ - **`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.
205
+ - **`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.
206
+ - **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.
207
+ - **Two vaults setting the same variable:** the docs don't say which wins, so `check` warns.
112
208
 
113
209
  ## Usage
114
210
 
115
211
  ```sh
116
212
  agentschema init <name> # scaffold a new agent folder
117
213
  agentschema check [dir] # validate the folder, no network
118
- agentschema deploy [dir] # create or update the agent and environment
214
+ agentschema deploy [dir] # create or update the agent, environment and vaults
119
215
  agentschema run [dir] # chat with the deployed agent in the terminal
120
216
  agentschema list # list the agents in your workspace
121
217
  agentschema delete <agent_id> # archive an agent
218
+ agentschema tools create [dir] # add pre-built tools, a custom tool or an MCP server
122
219
  agentschema sessions list # list the sessions in your workspace
123
220
  agentschema sessions delete <id> # delete a session
221
+ agentschema cred create [dir] # add a credential to a vault, asking a few questions
222
+ agentschema cred deploy <file> # create a credential file's credential in Anthropic
223
+ agentschema cred login <file> # sign in to a credential's server in the browser
224
+ agentschema cred delete <file> # delete a credential
124
225
  ```
125
226
 
126
- `dir` defaults to the current directory.
227
+ `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
228
 
128
229
  **`init`** creates the folder `<name>` with an `agent.md` and an `env.md` that pass `check`. It asks for:
129
230
  - the agent's name and model
@@ -137,16 +238,18 @@ Press Enter to keep the default shown, or pass `--yes` to skip the questions. `i
137
238
  - a missing file, or a name that isn't lowercase
138
239
  - frontmatter that is missing, unclosed, or invalid YAML
139
240
  - 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
241
+ - 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
242
+ - a credential file with a secret in it, a missing field, or two credentials for the same server
141
243
  - values over the API's limits
142
244
  - anything that looks like an API key or token
143
245
 
144
246
  Unknown fields are only warnings, because they're sent to the API as written. `check` exits with status 1 when there are errors.
145
247
 
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.
248
+ **`deploy`** runs `check` first, then creates or updates the environment, the agent and the vaults, and records their IDs in `claude-lock.json` in the folder. Commit that file.
147
249
  - **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
250
  - **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
251
  - **Changes made elsewhere aren't overwritten silently.** If the agent was changed outside the folder since the last deploy, `deploy` stops; `--force` overwrites it.
252
+ - **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
253
 
151
254
  `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
255
 
@@ -155,6 +258,7 @@ Unknown fields are only warnings, because they're sent to the API as written. `c
155
258
  - **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
259
  - **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.
157
260
  - **Interrupting:** Ctrl+C interrupts the agent mid-turn, and a second Ctrl+C quits. Ctrl+D quits at the prompt.
261
+ - **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
262
  - **Resuming:** quitting leaves the session in place, and `run` prints a command to resume it: `agentschema run --resume sesn_…`.
159
263
 
160
264
  ```sh
@@ -165,6 +269,11 @@ To run the agent from your own code, create a session with the agent and environ
165
269
 
166
270
  **`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
271
 
272
+ **`tools create`** adds a tool, asking a few questions like `init`. It only writes files; `deploy` sends them to the API.
273
+ - **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.
274
+ - **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.
275
+ - **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.
276
+
168
277
  **`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
278
 
170
279
  **`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 +282,28 @@ To run the agent from your own code, create a session with the agent and environ
173
282
 
174
283
  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
284
 
285
+ **`cred create`** adds a credential, asking a few questions like `init`:
286
+ 1. Which vault it goes in: one in `vaults/`, or a new one.
287
+ 2. Whether it's for an MCP server's sign-in or an environment variable.
288
+ 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.
289
+ 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`.
290
+
291
+ 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`.
292
+
293
+ **`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.
294
+
295
+ **`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`:
296
+ 1. It finds the server's sign-in from its URL, using the OAuth metadata MCP servers publish.
297
+ 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.
298
+ 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`.
299
+ 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.
300
+
301
+ It stops without creating anything if the server doesn't return a refresh token, since the credential would stop working within the hour.
302
+
303
+ 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.
304
+
305
+ **`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`.
306
+
176
307
  ### Authentication
177
308
 
178
309
  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,33 @@ 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";
10
13
  import { InitError, init } from "../src/init.js";
11
14
  import { listAgents, listSessions } from "../src/list.js";
15
+ import { prompts } from "../src/prompts.js";
12
16
  import { SessionError, openSession } from "../src/session.js";
17
+ import { toolsCreate } from "../src/tools-menu.js";
18
+
19
+ const FOOTER = `ags is a short name for agentschema. dir defaults to the current directory. Every command
20
+ but init, check and tools create authenticates with ANTHROPIC_API_KEY, or with a profile from \`ant auth login\`.`;
13
21
 
14
22
  const USAGE = `Usage: agentschema <command> [dir] [options]
15
23
 
16
24
  Commands:
17
25
  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
26
+ check [dir] Validate the folder's files, without calling the API
27
+ deploy [dir] Create or update the agent, environment and vaults, and write claude-lock.json
20
28
  run [dir] Chat with the deployed agent in a new session
21
29
  list List the agents in your workspace
22
30
  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
31
+ tools <command> Add pre-built tools, custom tools and MCP servers (agentschema tools -h)
32
+ sessions <command> List and delete sessions (agentschema sessions -h)
33
+ cred <command> Create and manage the credentials in vaults/ (agentschema cred -h)
25
34
 
26
35
  Options:
27
36
  -y, --yes (init) Skip the questions and use the defaults
@@ -32,14 +41,65 @@ Options:
32
41
  -h, --help Show this help
33
42
  -v, --version Show the version
34
43
 
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\`.`;
44
+ ${FOOTER}`;
45
+
46
+ const TOOLS_USAGE = `Usage: agentschema tools <command> [options]
47
+
48
+ Each tool is a file in tools/. The pre-built tools share one file, each custom tool has its own,
49
+ and so does each MCP server.
50
+
51
+ Commands:
52
+ create [dir] Add a tool: asks whether it's the pre-built tools, a custom tool or an
53
+ MCP server, then writes its file
54
+
55
+ Options:
56
+ -h, --help Show this help
57
+
58
+ dir defaults to the current directory.`;
59
+
60
+ const SESSIONS_USAGE = `Usage: agentschema sessions <command> [options]
61
+
62
+ Commands:
63
+ list List the sessions in your workspace, newest first
64
+ delete <id> Delete a session and its history
65
+
66
+ Options:
67
+ -y, --yes (delete) Don't ask for confirmation
68
+ -h, --help Show this help
69
+
70
+ Resume a session with agentschema run --resume <id>.`;
71
+
72
+ const CRED_USAGE = `Usage: agentschema cred <command> [options]
73
+
74
+ Each credential is a file in vaults/<vault>/<name>.md, without its secrets, which go straight
75
+ to Anthropic.
76
+
77
+ Commands:
78
+ create [dir] Add a credential: asks which vault it goes in and whether it's for an MCP
79
+ server or an environment variable, writes its file, then signs you in or
80
+ asks for its secrets, and creates it in Anthropic
81
+ deploy <file> Create the credential a file describes in Anthropic, by signing in or
82
+ pasting its secrets
83
+ login <file> Sign in to the credential's MCP server in the browser, and store the tokens,
84
+ creating the credential or replacing the tokens of the existing one
85
+ delete <file> Delete the credential a file describes from Anthropic; the file stays
86
+
87
+ Options:
88
+ --port <port> (create, deploy, login) Port for the sign-in redirect (default: any free port)
89
+ -y, --yes (delete) Don't ask for confirmation
90
+ -h, --help Show this help
91
+
92
+ dir defaults to the current directory.`;
93
+
94
+ // The commands that group subcommands, and their help.
95
+ const GROUPS = { tools: TOOLS_USAGE, sessions: SESSIONS_USAGE, cred: CRED_USAGE };
37
96
 
38
97
  const OPTIONS = {
39
98
  yes: { type: "boolean", short: "y" },
40
99
  "dry-run": { type: "boolean" },
41
100
  force: { type: "boolean" },
42
101
  resume: { type: "string" },
102
+ port: { type: "string" },
43
103
  help: { type: "boolean", short: "h" },
44
104
  version: { type: "boolean", short: "v" },
45
105
  };
@@ -51,8 +111,13 @@ const COMMANDS = {
51
111
  run: { args: [0, 1], options: ["resume"] },
52
112
  list: { args: [0, 0], options: [] },
53
113
  delete: { args: [1, 1], options: ["yes"] },
114
+ "tools create": { args: [0, 1], options: [] },
54
115
  "sessions list": { args: [0, 0], options: [] },
55
116
  "sessions delete": { args: [1, 1], options: ["yes"] },
117
+ "cred create": { args: [0, 1], options: ["port"] },
118
+ "cred deploy": { args: [1, 1], options: ["port"] },
119
+ "cred login": { args: [1, 1], options: ["port"] },
120
+ "cred delete": { args: [1, 1], options: ["yes"] },
56
121
  };
57
122
 
58
123
  async function main(argv) {
@@ -60,39 +125,45 @@ async function main(argv) {
60
125
  try {
61
126
  parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
62
127
  } catch (err) {
63
- console.error(`agentschema: ${err.message}\n\n${USAGE}`);
128
+ console.error(`agentschema: ${err.message}\n\n${GROUPS[argv[0]] ?? USAGE}`);
64
129
  return 1;
65
130
  }
66
131
  const { values, positionals } = parsed;
67
132
  let [command, ...args] = positionals;
68
- if (command === "sessions") command = `sessions ${args.shift() ?? ""}`.trim();
133
+ const group = command in GROUPS ? command : null;
134
+ if (group) command = `${group} ${args.shift() ?? ""}`.trim();
135
+ const usage = group ? GROUPS[group] : USAGE;
69
136
 
70
137
  if (values.version) {
71
138
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
72
139
  console.log(pkg.version);
73
140
  return 0;
74
141
  }
75
- if (!command || values.help) {
142
+ if (values.help) {
143
+ console.log(usage);
144
+ return 0;
145
+ }
146
+ if (!command) {
76
147
  console.log(USAGE);
77
- return command || values.help ? 0 : 1;
148
+ return 1;
78
149
  }
79
- if (command.startsWith("sessions") && !(command in COMMANDS)) {
80
- console.error(`agentschema: usage: agentschema sessions list | sessions delete <id>`);
150
+ if (group && command === group) {
151
+ console.error(usage);
81
152
  return 1;
82
153
  }
83
154
  if (!(command in COMMANDS)) {
84
- console.error(`agentschema: unknown command "${command}"\n\n${USAGE}`);
155
+ console.error(`agentschema: unknown command "${command}"\n\n${usage}`);
85
156
  return 1;
86
157
  }
87
158
  const spec = COMMANDS[command];
88
159
  const misplaced = Object.keys(values).filter((k) => !spec.options.includes(k));
89
160
  if (args.length > spec.args[1] || misplaced.length > 0) {
90
161
  const arg = args[spec.args[1]] ?? `--${misplaced[0]}`;
91
- console.error(`agentschema: unexpected argument ${arg} for ${command}\n\n${USAGE}`);
162
+ console.error(`agentschema: unexpected argument ${arg} for ${command}\n\n${usage}`);
92
163
  return 1;
93
164
  }
94
165
  if (args.length < spec.args[0]) {
95
- const example = { init: "init my-agent", delete: "delete agent_…", "sessions delete": "sessions delete sesn_…" }[command];
166
+ 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
167
  console.error(`agentschema: ${command} needs an argument, e.g. agentschema ${example}`);
97
168
  return 1;
98
169
  }
@@ -146,6 +217,39 @@ async function main(argv) {
146
217
  return 0;
147
218
  }
148
219
 
220
+ if (command === "tools create") {
221
+ const io = prompts(process.stdin, process.stdout, { cancelled: () => new DeployError("cancelled") });
222
+ try {
223
+ await toolsCreate(args[0] ?? ".", { io, log: (line) => console.log(line) });
224
+ } finally {
225
+ io.close();
226
+ }
227
+ return 0;
228
+ }
229
+
230
+ if (["cred create", "cred deploy", "cred login"].includes(command)) {
231
+ if (values.port !== undefined && !/^\d+$/.test(values.port)) throw new DeployError(`--port must be a number, not "${values.port}"`);
232
+ const io = prompts(process.stdin, process.stdout, { cancelled: () => new DeployError("cancelled") });
233
+ const options = { client: makeClient(false), openBrowser, port: values.port ?? 0, log: (line) => console.log(line) };
234
+ try {
235
+ if (command === "cred create") await credCreate(args[0] ?? ".", { ...options, io });
236
+ else if (command === "cred deploy") await credDeploy(args[0], { ...options, io });
237
+ else await credLogin(args[0], { ...options, ask: (q, { secret }) => (secret ? io.secret(q.trim()) : io.text(q.trim())) });
238
+ } finally {
239
+ io.close();
240
+ }
241
+ return 0;
242
+ }
243
+
244
+ if (command === "cred delete") {
245
+ await credDelete(args[0], {
246
+ client: makeClient(false),
247
+ confirm: values.yes ? async () => true : confirm,
248
+ log: (line) => console.log(line),
249
+ });
250
+ return 0;
251
+ }
252
+
149
253
  if (command === "run") {
150
254
  const client = makeClient(false);
151
255
  const { session, notes } = await openSession(dir, {
@@ -180,6 +284,18 @@ async function confirm(question) {
180
284
  }
181
285
  }
182
286
 
287
+ // Opens a URL in the default browser; the URL is also printed, in case this fails.
288
+ function openBrowser(url) {
289
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]]
290
+ : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
291
+ : ["xdg-open", [url]];
292
+ try {
293
+ spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {}).unref();
294
+ } catch {
295
+ // The URL was printed; the user can open it.
296
+ }
297
+ }
298
+
183
299
  // The folder's custom tools, by name, for run to execute. A folder that doesn't pass check
184
300
  // runs none of them; run asks you for each result instead.
185
301
  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.2.2",
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
  },