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