@soft-boy/agentschema 0.3.12 → 0.5.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.
Files changed (94) hide show
  1. package/README.md +13 -9
  2. package/dist/bin/agentschema.d.ts +2 -0
  3. package/dist/bin/agentschema.js +333 -0
  4. package/dist/lib/channels.d.ts +65 -0
  5. package/dist/lib/channels.js +339 -0
  6. package/dist/lib/check.d.ts +10 -0
  7. package/dist/lib/check.js +411 -0
  8. package/dist/lib/files.d.ts +7 -0
  9. package/{lib → dist/lib}/files.js +10 -14
  10. package/dist/lib/index.d.ts +24 -0
  11. package/{lib → dist/lib}/index.js +3 -10
  12. package/dist/lib/instance.d.ts +41 -0
  13. package/dist/lib/instance.js +74 -0
  14. package/dist/lib/markdown.d.ts +11 -0
  15. package/dist/lib/markdown.js +38 -0
  16. package/dist/lib/scaffold.d.ts +15 -0
  17. package/dist/lib/scaffold.js +46 -0
  18. package/dist/lib/scheduled.d.ts +56 -0
  19. package/dist/lib/scheduled.js +185 -0
  20. package/dist/lib/skills.d.ts +28 -0
  21. package/dist/lib/skills.js +55 -0
  22. package/dist/lib/stream.d.ts +30 -0
  23. package/dist/lib/stream.js +56 -0
  24. package/dist/lib/system-prompt.d.ts +16 -0
  25. package/{lib → dist/lib}/system-prompt.js +14 -15
  26. package/dist/lib/tools.d.ts +105 -0
  27. package/dist/lib/tools.js +353 -0
  28. package/dist/lib/vaults.d.ts +55 -0
  29. package/dist/lib/vaults.js +143 -0
  30. package/dist/src/chat.d.ts +15 -0
  31. package/dist/src/chat.js +159 -0
  32. package/dist/src/check.d.ts +2 -0
  33. package/dist/src/check.js +14 -0
  34. package/dist/src/cred-menu.d.ts +17 -0
  35. package/dist/src/cred-menu.js +193 -0
  36. package/dist/src/cred.d.ts +54 -0
  37. package/dist/src/cred.js +252 -0
  38. package/dist/src/custom-tools.d.ts +3 -0
  39. package/dist/src/custom-tools.js +18 -0
  40. package/dist/src/delete.d.ts +9 -0
  41. package/dist/src/delete.js +27 -0
  42. package/dist/src/deploy.d.ts +62 -0
  43. package/dist/src/deploy.js +442 -0
  44. package/dist/src/dotenv.d.ts +7 -0
  45. package/dist/src/dotenv.js +54 -0
  46. package/dist/src/folder.d.ts +5 -0
  47. package/dist/src/folder.js +57 -0
  48. package/dist/src/init.d.ts +11 -0
  49. package/dist/src/init.js +51 -0
  50. package/dist/src/list.d.ts +3 -0
  51. package/dist/src/list.js +46 -0
  52. package/dist/src/lock.d.ts +10 -0
  53. package/dist/src/lock.js +37 -0
  54. package/dist/src/mcp.d.ts +11 -0
  55. package/dist/src/mcp.js +79 -0
  56. package/dist/src/node.d.ts +14 -0
  57. package/dist/src/oauth.d.ts +64 -0
  58. package/dist/src/oauth.js +208 -0
  59. package/dist/src/prompts.d.ts +18 -0
  60. package/dist/src/prompts.js +166 -0
  61. package/dist/src/session.d.ts +58 -0
  62. package/dist/src/session.js +200 -0
  63. package/dist/src/tools-menu.d.ts +8 -0
  64. package/dist/src/tools-menu.js +173 -0
  65. package/package.json +21 -9
  66. package/bin/agentschema.js +0 -326
  67. package/lib/channels.js +0 -338
  68. package/lib/check.js +0 -388
  69. package/lib/instance.js +0 -48
  70. package/lib/markdown.js +0 -42
  71. package/lib/scaffold.js +0 -51
  72. package/lib/scheduled.js +0 -175
  73. package/lib/skills.js +0 -58
  74. package/lib/stream.js +0 -50
  75. package/lib/tools.js +0 -327
  76. package/lib/vaults.js +0 -142
  77. package/src/chat.js +0 -156
  78. package/src/check.js +0 -14
  79. package/src/cred-menu.js +0 -197
  80. package/src/cred.js +0 -263
  81. package/src/custom-tools.js +0 -17
  82. package/src/delete.js +0 -25
  83. package/src/deploy.js +0 -441
  84. package/src/dotenv.js +0 -50
  85. package/src/folder.js +0 -55
  86. package/src/init.js +0 -54
  87. package/src/list.js +0 -49
  88. package/src/lock.js +0 -40
  89. package/src/mcp.js +0 -76
  90. package/src/oauth.js +0 -215
  91. package/src/prompts.js +0 -159
  92. package/src/session.js +0 -194
  93. package/src/tools-menu.js +0 -163
  94. /package/{src → dist/src}/node.js +0 -0
package/src/session.js DELETED
@@ -1,194 +0,0 @@
1
- import { join } from "node:path";
2
- import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "../lib/instance.js";
3
- import { SYSTEM_PROMPT_DIR } from "../lib/system-prompt.js";
4
- import { skillKey, skillRefs } from "../lib/skills.js";
5
- import { TOOLS_DIR } from "../lib/tools.js";
6
- import { credentialKey, vaultKey } from "../lib/vaults.js";
7
- import { check } from "./check.js";
8
- import { LOCK_FILE, hashBody, readLock, skillFingerprint } from "./lock.js";
9
-
10
- export class SessionError extends Error {}
11
-
12
- // Starts a session on the agent and environment recorded in claude-lock.json, or resumes `sessionId`.
13
- // Returns { session, notes }: notes are warnings worth showing, such as files changed since the last deploy.
14
- export async function openSession(dir, { client, sessionId }) {
15
- if (sessionId) {
16
- const session = await client.beta.sessions.retrieve(sessionId);
17
- if (session.status === "terminated") throw new SessionError(`session ${sessionId} has terminated`);
18
- return { session, notes: [] };
19
- }
20
-
21
- const lock = readLock(dir);
22
- const agent = lock?.resources?.[`./${AGENT_FILE}`];
23
- const env = lock?.resources?.[`./${ENV_FILE}`];
24
- if (!agent || !env) {
25
- throw new SessionError(`${dir} hasn't been deployed (no agent or environment in ${LOCK_FILE}); run agentschema deploy first`);
26
- }
27
-
28
- const notes = [];
29
- const { instance, errors } = check(dir);
30
- if (instance && errors.length === 0) {
31
- if (hashBody(agentBody(instance, skillRefs(instance.skills, lock))) !== agent.hash) {
32
- notes.push(`${AGENT_FILE}, ${SYSTEM_PROMPT_DIR}/ or ${TOOLS_DIR}/ has changed since the last deploy`);
33
- }
34
- for (const skill of instance.skills) {
35
- if (hashBody(skillFingerprint(skill)) !== lock.resources[skillKey(skill)]?.hash) notes.push(`${skill.path} has changed since the last deploy`);
36
- }
37
- if (hashBody(envBody(instance)) !== env.hash) notes.push(`${ENV_FILE} has changed since the last deploy`);
38
- if (notes.length > 0) notes.push(`this session uses the deployed version; run agentschema deploy to pick up the changes`);
39
- }
40
-
41
- const name = instance?.agent.data.name;
42
- const started = await startSession({
43
- instance,
44
- lock,
45
- client,
46
- title: name ? `${name} (agentschema run)` : "agentschema run",
47
- pathOf: (file) => join(dir, file),
48
- });
49
- return { session: started.session, notes: [...notes, ...started.notes] };
50
- }
51
-
52
- // Starts a session from a lock, pinned to a deployed version, so it runs exactly what deploy sent.
53
- //
54
- // instance the checked files, for finding the vaults to attach
55
- // agentVersion the agent version to pin, instead of the lock's latest
56
- // system the system prompt for this session only, such as with a channel's instructions added
57
- // budget the API's session budget, to cap what the session can spend
58
- // pathOf how to show a file's path to the user in messages
59
- //
60
- // Returns { session, notes }.
61
- export async function startSession({ instance, lock, client, agentVersion, system, title, budget, pathOf = (file) => file }) {
62
- const agent = lock?.resources?.[`./${AGENT_FILE}`];
63
- const env = lock?.resources?.[`./${ENV_FILE}`];
64
- if (!agent || !env) throw new SessionError("this agent hasn't been deployed (no agent or environment in its lock)");
65
-
66
- const pinned = { id: agent.id, version: Number(agentVersion ?? agent.version) };
67
- const params = {
68
- // Overriding affects this session only, and doesn't change the agent or make a new version of it.
69
- agent: system === undefined ? { type: "agent", ...pinned } : { type: "agent_with_overrides", ...pinned, system },
70
- environment_id: env.id,
71
- };
72
-
73
- // Every deployed vault in vaults/, in name order: when two hold a credential for the same
74
- // server, the first one wins.
75
- const notes = [];
76
- const vaultIds = [];
77
- for (const vault of instance?.vaults ?? []) {
78
- const entry = lock.resources[vaultKey(vault)];
79
- if (!entry) {
80
- notes.push(`vault ${vault.path} hasn't been deployed, so this session doesn't have it; run agentschema deploy`);
81
- continue;
82
- }
83
- vaultIds.push(entry.id);
84
- for (const cred of vault.credentials) {
85
- const credEntry = lock.resources[credentialKey(cred)];
86
- if (!credEntry || credEntry.vault_id !== entry.id) {
87
- notes.push(`credential ${cred.file} hasn't been created; run agentschema cred deploy ${pathOf(cred.file)}`);
88
- }
89
- }
90
- }
91
- if (vaultIds.length > 0) params.vault_ids = vaultIds;
92
- if (title) params.title = title;
93
- if (budget) params.budget = budget;
94
- return { session: await client.beta.sessions.create(params), notes };
95
- }
96
-
97
- // Drives a session one turn at a time. `ui` answers what only a person can:
98
- // ui.event(event) show an event, including the stream-only event_start / event_delta previews
99
- // ui.confirm(event) -> { result: "allow" | "deny", deny_message? } for a paused tool call
100
- // ui.customToolResult(event) -> string, or { text, isError }: the result of a custom tool call
101
- export class Conversation {
102
- constructor(client, sessionId, ui) {
103
- this.client = client;
104
- this.sessionId = sessionId;
105
- this.ui = ui;
106
- this.seen = new Set();
107
- this.stream = null;
108
- }
109
-
110
- // Sends a message and handles events until the agent finishes its turn.
111
- // Returns the idle stop reason, or "terminated".
112
- async send(text) {
113
- return this.#turn([{ type: "user.message", content: [{ type: "text", text }] }]);
114
- }
115
-
116
- // Asks the agent to stop at the next safe point; the running turn then ends normally.
117
- async interrupt() {
118
- await this.client.beta.sessions.events.send(this.sessionId, { events: [{ type: "user.interrupt" }] });
119
- }
120
-
121
- async #turn(events) {
122
- // Stream first: events emitted before the stream opens would never reach us.
123
- this.stream = await this.#openStream();
124
- await this.client.beta.sessions.events.send(this.sessionId, { events });
125
-
126
- for (let attempt = 0; ; attempt++) {
127
- try {
128
- for await (const event of this.stream) {
129
- const done = await this.#handle(event);
130
- if (done) return done;
131
- }
132
- throw new Error("event stream closed");
133
- } catch (err) {
134
- if (this.closed || attempt >= 3) throw err;
135
- // The stream has no replay: reopen it, then catch up from the event history.
136
- this.stream = await this.#openStream();
137
- for await (const event of this.client.beta.sessions.events.list(this.sessionId)) {
138
- const done = await this.#handle(event);
139
- if (done) return done;
140
- }
141
- }
142
- }
143
- }
144
-
145
- // Opts in to live previews, so agent text arrives as event_start / event_delta events while
146
- // the model is still writing, ahead of the complete agent.message.
147
- #openStream() {
148
- return this.client.beta.sessions.events.stream(this.sessionId, { event_deltas: ["agent.message"] });
149
- }
150
-
151
- // Returns a value when the turn is over.
152
- async #handle(event) {
153
- // Events are deduped by ID: the history and the live stream overlap after a reconnect,
154
- // and a queued user event is echoed twice.
155
- if (event.id) {
156
- if (this.seen.has(event.id)) return null;
157
- this.seen.add(event.id);
158
- }
159
- this.ui.event(event);
160
-
161
- const send = (e) => this.client.beta.sessions.events.send(this.sessionId, { events: [e] });
162
- switch (event.type) {
163
- case "agent.tool_use":
164
- case "agent.mcp_tool_use":
165
- if (event.evaluated_permission === "ask") {
166
- const { result, deny_message } = await this.ui.confirm(event);
167
- const reply = { type: "user.tool_confirmation", tool_use_id: event.id, result };
168
- if (result === "deny" && deny_message) reply.deny_message = deny_message;
169
- await send(reply);
170
- }
171
- return null;
172
- case "agent.custom_tool_use": {
173
- const result = await this.ui.customToolResult(event);
174
- const { text, isError } = typeof result === "string" ? { text: result } : result;
175
- const reply = { type: "user.custom_tool_result", custom_tool_use_id: event.id, content: [{ type: "text", text }] };
176
- if (isError) reply.is_error = true;
177
- await send(reply);
178
- return null;
179
- }
180
- case "session.status_idle":
181
- // requires_action means the session is waiting on one of the replies above.
182
- return event.stop_reason?.type === "requires_action" ? null : (event.stop_reason?.type ?? "end_turn");
183
- case "session.status_terminated":
184
- return "terminated";
185
- default:
186
- return null;
187
- }
188
- }
189
-
190
- close() {
191
- this.closed = true;
192
- this.stream?.controller?.abort();
193
- }
194
- }
package/src/tools-menu.js DELETED
@@ -1,163 +0,0 @@
1
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
- import { dirname, join } from "node:path";
3
- import { stringify } from "yaml";
4
- import { check } from "./check.js";
5
- import { serviceName } from "./cred-menu.js";
6
- import { DeployError } from "./deploy.js";
7
- import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
8
- import { builtInFile } from "../lib/scaffold.js";
9
- import { updateFrontmatter } from "./folder.js";
10
- import { listMcpTools } from "./mcp.js";
11
- import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR, mcpToolsetFile } from "../lib/tools.js";
12
-
13
- const PREBUILT = "Pre-built tools (bash, files, web search)";
14
- const CUSTOM = "Custom tool (JavaScript that runs on your machine)";
15
- const MCP = "MCP server";
16
- const INPUT_TYPES = ["string", "number", "integer", "boolean", "object", "string[]", "number[]", "integer[]", "boolean[]", "object[]"];
17
-
18
- // `tools create`: asks what kind of tool to add, then writes its file in tools/.
19
- // Returns the path of the file written.
20
- export async function toolsCreate(dir = ".", { io, fetch = globalThis.fetch, log = () => {} }) {
21
- const { errors, instance } = check(dir);
22
- if (!instance) throw new DeployError(`${dir} isn't an agent folder:\n ${errors.join("\n ")}`);
23
-
24
- const kind = await io.select("What kind of tool?", [PREBUILT, CUSTOM, MCP], PREBUILT);
25
- const write = kind === PREBUILT ? prebuilt : kind === CUSTOM ? custom : mcp;
26
- const { path, text, addServer } = await write(dir, instance, io, { fetch, log });
27
-
28
- const file = join(dir, path);
29
- mkdirSync(dirname(file), { recursive: true });
30
- writeFileSync(file, text);
31
- log(`Wrote ${file}`);
32
- if (addServer) {
33
- updateFrontmatter(join(dir, AGENT_FILE), (doc) => {
34
- if (doc.hasIn(["mcp_servers"])) doc.addIn(["mcp_servers"], doc.createNode(addServer));
35
- else doc.setIn(["mcp_servers"], doc.createNode([addServer]));
36
- });
37
- log(`Added ${addServer.name} to mcp_servers in ${join(dir, AGENT_FILE)}`);
38
- }
39
-
40
- const after = check(dir);
41
- const related = (m) => m.startsWith(path) || (kind === MCP && (m.startsWith(AGENT_FILE) || m.startsWith(ENV_FILE)));
42
- for (const w of after.warnings.filter(related)) log(`warning: ${w}`);
43
- for (const e of after.errors.filter(related)) log(`error: ${e}`);
44
- if (kind === CUSTOM) log(`\nWrite the tool's code in its ## Code block, then deploy with:\n agentschema deploy ${dir}`);
45
- else if (kind === MCP) log(`\nIf the server needs you to sign in, add a credential for it:\n agentschema cred create ${dir}\nThen deploy with:\n agentschema deploy ${dir}`);
46
- else log(`\nDeploy with:\n agentschema deploy ${dir}`);
47
- return file;
48
- }
49
-
50
- // The pre-built toolset: one file, with a row for each tool.
51
- async function prebuilt(dir, { tools }, io) {
52
- const existing = tools.find((t) => t.data.type === TOOLSET);
53
- if (existing) throw new DeployError(`the agent already has its pre-built tools in ${existing.file}; edit that file's table to turn tools on or off`);
54
-
55
- let enabled = PREBUILT_TOOLS;
56
- if (!(await io.confirm(`Turn on all eight (${PREBUILT_TOOLS.join(", ")})?`, true))) {
57
- enabled = [];
58
- for (const name of PREBUILT_TOOLS) if (await io.confirm(` ${name}?`, true)) enabled.push(name);
59
- }
60
- return { path: `${TOOLS_DIR}/${TOOLSET_FILE}`, text: builtInFile(PREBUILT_TOOLS, enabled, await choosePermission(io, "auto")) };
61
- }
62
-
63
- // A custom tool: its name, description and inputs, with a code block to fill in.
64
- async function custom(dir, { tools }, io) {
65
- const taken = new Set(tools.filter((t) => t.data.type === "custom").map((t) => t.name));
66
- const name = await io.text("Tool name? (letters, digits, _ and -)", "", {
67
- validate: (n) => {
68
- if (!/^[a-zA-Z0-9_-]{1,64}$/.test(n)) return "Use letters, digits, _ and -, up to 64 characters";
69
- if (PREBUILT_TOOLS.includes(n)) return `${n} is a pre-built tool's name`;
70
- if (/^(mcp__|ant__)/.test(n)) return "A custom tool's name can't start with mcp__ or ant__";
71
- if (taken.has(n) || existsSync(join(dir, TOOLS_DIR, `${n}.md`))) return `There's already a tool called ${n}`;
72
- return null;
73
- },
74
- });
75
- const description = await io.text("What does it do? (Claude reads this to decide when to call it)", "", {
76
- validate: (d) => (d ? null : "The description is required"),
77
- });
78
-
79
- const inputs = [];
80
- while (true) {
81
- const input = await io.text(inputs.length === 0 ? "First input's name? (Enter for none)" : "Next input's name? (Enter when done)", "", {
82
- validate: (n) => {
83
- if (n && !/^[a-zA-Z_$][\w$]*$/.test(n)) return "Use a name like city or max_results";
84
- if (inputs.some((i) => i.name === n)) return `${n} is already an input`;
85
- return null;
86
- },
87
- });
88
- if (!input) break;
89
- const type = await io.select(` ${input}'s type?`, INPUT_TYPES, "string");
90
- const about = await io.text(` ${input}'s description?`, "");
91
- const required = await io.confirm(` Is ${input} required?`, true);
92
- inputs.push({ name: input, type, about, required });
93
- }
94
-
95
- const cell = (s) => s.replace(/\|/g, "\\|");
96
- const table = inputs.length === 0 ? "" : [
97
- "## Input Schema", "",
98
- "| Name | Type | Description | Required |",
99
- "|---|---|---|---|",
100
- ...inputs.map((i) => `| \`${i.name}\` | \`${i.type}\` | ${cell(i.about)} | \`${i.required}\` |`),
101
- "", "",
102
- ].join("\n");
103
- const args = inputs.length === 0 ? "()" : `({ ${inputs.map((i) => i.name).join(", ")} })`;
104
- const code = [
105
- "## Code", "",
106
- "```javascript",
107
- `module.exports = async ${args} => {`,
108
- ` throw new Error("${name} isn't implemented yet");`,
109
- "};",
110
- "```", "",
111
- ].join("\n");
112
-
113
- const front = stringify({ type: "custom", name, description });
114
- return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${front}---\n\n${table}${code}` };
115
- }
116
-
117
- // An MCP server: its URL and name, how its tools are approved, and a table of those tools.
118
- // The server itself is declared in agent.md; a server already declared there only needs its file.
119
- async function mcp(dir, instance, io, { fetch, log }) {
120
- const { tools, agent } = instance;
121
- const declared = Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers : [];
122
- const toolsets = new Set(tools.filter((t) => t.data.type === MCP_TOOLSET).map((t) => t.data.mcp_server_name));
123
- const url = await io.text("MCP server URL?", "", {
124
- validate: (u) => {
125
- if (!/^https?:\/\/\S+$/.test(u)) return "Enter an http(s) URL";
126
- const same = declared.find((s) => s?.url === u);
127
- return same && toolsets.has(same.name) ? `${AGENT_FILE} already declares that server, as ${same.name}` : null;
128
- },
129
- });
130
- const existing = declared.find((s) => s?.url === url);
131
- const name = existing?.name ?? await io.text("Name for it?", serviceName(url).toLowerCase(), {
132
- validate: (n) => {
133
- if (!n || /[/\\]/.test(n) || n.startsWith(".")) return "Use a name without / that doesn't start with .";
134
- if (declared.some((s) => s?.name === n)) return `${AGENT_FILE} already declares a server called ${n}`;
135
- if (existsSync(join(dir, TOOLS_DIR, `${n}.md`))) return `There's already a tool file called ${n}.md`;
136
- return null;
137
- },
138
- });
139
- const addServer = existing ? null : { type: "url", name, url };
140
-
141
- const permission = await choosePermission(io, "always_ask");
142
-
143
- log(`Asking ${url} for its tools…`);
144
- const names = await listMcpTools(url, { fetch });
145
- if (names) log(`It has ${names.length} tool${names.length === 1 ? "" : "s"}.`);
146
- else log("It won't list its tools without signing in, so they'll be listed once you have; until then, every tool is on.");
147
- return { path: `${TOOLS_DIR}/${name}.md`, text: mcpToolsetFile({ name, tools: names ?? [], permission }), addServer };
148
- }
149
-
150
- // Asks how a set of tools should be approved, offering `recommended` first.
151
- export async function choosePermission(io, recommended) {
152
- const policies = [recommended, ...POLICIES.filter((p) => p !== recommended)];
153
- const answer = await io.select("Ask you before each call? (permission for its tools)", policies.map(describePolicy), describePolicy(recommended));
154
- return policies.find((p) => describePolicy(p) === answer);
155
- }
156
-
157
- function describePolicy(policy) {
158
- return {
159
- always_ask: "always_ask: ask before every call (the API's default for MCP tools)",
160
- always_allow: "always_allow: never ask",
161
- auto: "auto: Anthropic decides per call, and asks when it can't",
162
- }[policy];
163
- }
File without changes