@soft-boy/agentschema 0.4.0 → 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.
- package/README.md +8 -2
- package/dist/bin/agentschema.d.ts +2 -0
- package/dist/bin/agentschema.js +333 -0
- package/dist/lib/channels.d.ts +65 -0
- package/dist/lib/channels.js +339 -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 +3 -12
- 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 +105 -0
- package/dist/lib/tools.js +353 -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,442 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import Anthropic, { toFile } from "@anthropic-ai/sdk";
|
|
3
|
+
import { CHANNELS_DIR, readChannels } from "../lib/channels.js";
|
|
4
|
+
import { checkFiles } from "../lib/check.js";
|
|
5
|
+
import { AGENT_FILE, ENVIRONMENT_KEY, agentBody, envBody, environmentEntry, upgradeLock, } from "../lib/instance.js";
|
|
6
|
+
import { taskBody, taskKey, taskSettings } from "../lib/scheduled.js";
|
|
7
|
+
import { skillKey, skillRefs } from "../lib/skills.js";
|
|
8
|
+
import { AGENTBOOK } from "../lib/tools.js";
|
|
9
|
+
import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey, } from "../lib/vaults.js";
|
|
10
|
+
import { folderProblem, readFolder } from "./folder.js";
|
|
11
|
+
import { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
|
|
12
|
+
export class DeployError extends Error {
|
|
13
|
+
}
|
|
14
|
+
// Deploys an agent folder, keeping the lock in its claude-lock.json. Returns the plan: one
|
|
15
|
+
// { file, kind, action, id, version } entry per resource.
|
|
16
|
+
export async function deploy(dir, { client, dryRun = false, force = false, log = () => { } }) {
|
|
17
|
+
const problem = folderProblem(dir);
|
|
18
|
+
if (problem)
|
|
19
|
+
throw new DeployError(`check failed:\n ${problem}`);
|
|
20
|
+
const files = readFolder(dir);
|
|
21
|
+
const { plan } = await deployFiles({
|
|
22
|
+
files,
|
|
23
|
+
lock: readLock(dir),
|
|
24
|
+
client,
|
|
25
|
+
dryRun,
|
|
26
|
+
force,
|
|
27
|
+
log,
|
|
28
|
+
saveLock: (lock) => writeLock(dir, lock),
|
|
29
|
+
pathOf: (file) => join(dir, file),
|
|
30
|
+
});
|
|
31
|
+
if (readChannels(files).channels.length > 0)
|
|
32
|
+
log(`${CHANNELS_DIR}/ isn't connected by deploying from here; a channel needs a host that's always on, such as Agentbook`);
|
|
33
|
+
return plan;
|
|
34
|
+
}
|
|
35
|
+
// Creates or updates the skills, environment, agent, vaults and scheduled tasks in a file map (see
|
|
36
|
+
// lib/files.js). Skills go first, because the agent refers to their IDs and versions, and scheduled
|
|
37
|
+
// tasks go last, because they refer to everything else. Credentials are only updated here: creating
|
|
38
|
+
// one needs its secrets, so that's `cred deploy`'s job.
|
|
39
|
+
//
|
|
40
|
+
// lock the IDs from the last deploy, or null for a first deploy
|
|
41
|
+
// saveLock called with the lock as soon as each resource exists, so a failure later
|
|
42
|
+
// doesn't orphan it; it may be async
|
|
43
|
+
// checkOptions what checkFiles takes: { customTools, toolsets }
|
|
44
|
+
// pathOf how to show a file's path to the user in messages
|
|
45
|
+
// scheduled false leaves scheduled tasks alone, for a copy of the agent that's only for trying
|
|
46
|
+
// it out
|
|
47
|
+
//
|
|
48
|
+
// Returns { plan, lock }. A dry run calls neither the API nor saveLock.
|
|
49
|
+
export async function deployFiles({ files, lock: previous = null, client, dryRun = false, force = false, log = () => { }, saveLock = () => { }, checkOptions = {}, pathOf = (file) => file, scheduled = true, }) {
|
|
50
|
+
const { errors, instance: checked } = checkFiles(files, checkOptions);
|
|
51
|
+
if (errors.length > 0)
|
|
52
|
+
throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
|
|
53
|
+
// checkFiles only leaves instance null when there are errors.
|
|
54
|
+
const instance = checked;
|
|
55
|
+
const agentbook = instance.tools.find((t) => t.data.type === AGENTBOOK);
|
|
56
|
+
if (agentbook && !checkOptions.toolsets) {
|
|
57
|
+
throw new DeployError(`${agentbook.file}: this toolset runs on agentbook, so it can only be deployed from there`);
|
|
58
|
+
}
|
|
59
|
+
const lock = prepareLock(previous, client);
|
|
60
|
+
const skillSteps = await deploySkills(instance.skills, { client, lock, dryRun, log, saveLock });
|
|
61
|
+
// A dry run has no new IDs or versions yet, so a stand-in shows that the agent will change too.
|
|
62
|
+
const pending = dryRun ? skillSteps.filter((s) => s.action !== "unchanged") : [];
|
|
63
|
+
const refs = instance.skills.flatMap((skill) => {
|
|
64
|
+
const step = pending.find((s) => s.key === skillKey(skill));
|
|
65
|
+
if (!step)
|
|
66
|
+
return skillRefs([skill], lock);
|
|
67
|
+
return [{ type: "custom", skill_id: step.entry?.id ?? `pending:${skill.name}`, version: `pending:${step.hash}` }];
|
|
68
|
+
});
|
|
69
|
+
// hash, entry and action are filled in just below.
|
|
70
|
+
const steps = [
|
|
71
|
+
{ file: instance.env.file, key: ENVIRONMENT_KEY, kind: "environment", body: envBody(instance) },
|
|
72
|
+
{ file: AGENT_FILE, key: `./${AGENT_FILE}`, kind: "agent", body: agentBody(instance, refs, checkOptions) },
|
|
73
|
+
];
|
|
74
|
+
for (const step of steps) {
|
|
75
|
+
step.hash = hashBody(step.body);
|
|
76
|
+
step.entry = lock.resources[step.key];
|
|
77
|
+
if (step.entry && step.entry.kind !== step.kind) {
|
|
78
|
+
throw new DeployError(`${LOCK_FILE}: entry for ${step.key} is a ${step.entry.kind}, expected ${step.kind}`);
|
|
79
|
+
}
|
|
80
|
+
step.action = !step.entry ? "create" : step.entry.hash === step.hash ? "unchanged" : "update";
|
|
81
|
+
}
|
|
82
|
+
for (const step of steps) {
|
|
83
|
+
if (dryRun || step.action === "unchanged") {
|
|
84
|
+
log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? ""}`.trimEnd());
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const result = step.kind === "environment"
|
|
88
|
+
? await deployEnvironment(client, step)
|
|
89
|
+
: await deployAgent(client, step, force);
|
|
90
|
+
lock.resources[step.key] = step.kind === "agent"
|
|
91
|
+
? { kind: "agent", id: result.id, version: String(result.version), hash: step.hash }
|
|
92
|
+
: { kind: "environment", id: result.id, hash: step.hash };
|
|
93
|
+
// Record each resource as soon as it exists, so a failure later doesn't orphan it.
|
|
94
|
+
await saveLock(lock);
|
|
95
|
+
const version = step.kind === "agent" ? ` (version ${result.version})` : "";
|
|
96
|
+
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}${version}`);
|
|
97
|
+
}
|
|
98
|
+
const vaultSteps = await deployVaults(instance.vaults, { client, lock, dryRun, log, saveLock, pathOf });
|
|
99
|
+
// A dry run has no IDs for what it would create, or versions for what it would change.
|
|
100
|
+
const pendingAgent = dryRun && steps.some((step) => step.action !== "unchanged" && step.kind === "agent");
|
|
101
|
+
const pendingVaults = dryRun ? vaultSteps.filter((step) => step.kind === "vault" && step.action === "create").map((step) => step.key) : [];
|
|
102
|
+
const taskSteps = scheduled
|
|
103
|
+
? await deployScheduled(instance, { client, lock, dryRun, log, saveLock, pendingAgent, pendingVaults })
|
|
104
|
+
: [];
|
|
105
|
+
const plan = [...skillSteps, ...steps, ...vaultSteps, ...taskSteps].map(({ file, kind, action, key, entry }) => ({
|
|
106
|
+
file, kind, action,
|
|
107
|
+
id: lock.resources[key]?.id ?? entry?.id,
|
|
108
|
+
version: lock.resources[key]?.version,
|
|
109
|
+
}));
|
|
110
|
+
return { plan, lock };
|
|
111
|
+
}
|
|
112
|
+
// Makes a deployment for each task in scheduled/, pinned to the agent's version and with every
|
|
113
|
+
// deployed vault, then pauses or unpauses it to match `enabled`. A task whose file is gone has its
|
|
114
|
+
// deployment archived, because a schedule left behind would keep running, and costing money.
|
|
115
|
+
async function deployScheduled(instance, { client, lock, dryRun, log, saveLock, pendingAgent, pendingVaults }) {
|
|
116
|
+
const agentEntry = lock.resources[`./${AGENT_FILE}`];
|
|
117
|
+
const envEntry = environmentEntry(lock);
|
|
118
|
+
const agent = { type: "agent", id: agentEntry?.id ?? "pending", version: pendingAgent || !agentEntry ? "pending" : Number(agentEntry.version) };
|
|
119
|
+
const vaultIds = instance.vaults.map((vault) => lock.resources[vaultKey(vault)]?.id ?? (pendingVaults.includes(vaultKey(vault)) ? `pending:${vault.path}` : null)).filter(Boolean);
|
|
120
|
+
const steps = [];
|
|
121
|
+
for (const task of instance.scheduled) {
|
|
122
|
+
const body = { ...taskBody(task), agent, environment_id: envEntry?.id ?? "pending", vault_ids: vaultIds };
|
|
123
|
+
const paused = !taskSettings(task).enabled;
|
|
124
|
+
const step = planStep(lock, { file: task.file, key: taskKey(task), kind: "deployment", body });
|
|
125
|
+
step.isChanged = step.action === "update";
|
|
126
|
+
if (step.action === "unchanged" && Boolean(step.entry.paused) !== paused)
|
|
127
|
+
step.action = paused ? "pause" : "unpause";
|
|
128
|
+
steps.push(step);
|
|
129
|
+
if (dryRun || step.action === "unchanged") {
|
|
130
|
+
log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? task.name}`);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
let result = step.action === "create" ? null : await currentDeployment(client, step);
|
|
134
|
+
const isReplacing = step.action !== "create" && !result;
|
|
135
|
+
// Past a dry run, the agent and its environment are deployed, so body has no "pending" stand-ins.
|
|
136
|
+
if (!result)
|
|
137
|
+
result = await call(step, () => client.beta.deployments.create(body));
|
|
138
|
+
else if (step.isChanged) {
|
|
139
|
+
// Updates keep any field they aren't sent, so a budget or description taken out of the file is cleared.
|
|
140
|
+
result = await call(step, () => client.beta.deployments.update(result.id, { ...body, budget: body.budget ?? null, description: body.description ?? null }));
|
|
141
|
+
}
|
|
142
|
+
// result is set by now; the callbacks below just can't see it narrowed.
|
|
143
|
+
if (paused && result.status === "active")
|
|
144
|
+
result = await call(step, () => client.beta.deployments.pause(result.id));
|
|
145
|
+
else if (!paused && result.status === "paused")
|
|
146
|
+
result = await call(step, () => client.beta.deployments.unpause(result.id));
|
|
147
|
+
lock.resources[step.key] = { kind: "deployment", id: result.id, hash: step.hash, paused };
|
|
148
|
+
await saveLock(lock);
|
|
149
|
+
const nextRun = result.schedule?.upcoming_runs_at?.[0];
|
|
150
|
+
const when = paused ? (step.action === "pause" ? null : "paused") : nextRun ? `next run ${nextRun}` : null;
|
|
151
|
+
const done = isReplacing ? `replaced` : { create: "created", update: "updated", pause: "paused", unpause: "unpaused" }[step.action];
|
|
152
|
+
log(`${done.padEnd(9)} deployment ${result.id}${isReplacing ? ` (${step.entry.id} was archived)` : ""}${when ? ` (${when})` : ""}`);
|
|
153
|
+
}
|
|
154
|
+
const wanted = new Set(instance.scheduled.map(taskKey));
|
|
155
|
+
for (const [key, entry] of Object.entries(lock.resources)) {
|
|
156
|
+
if (entry.kind !== "deployment" || wanted.has(key))
|
|
157
|
+
continue;
|
|
158
|
+
const step = { file: key.slice(2), key, kind: "deployment", action: "archive", entry };
|
|
159
|
+
steps.push(step);
|
|
160
|
+
if (dryRun) {
|
|
161
|
+
log(`archive deployment ${entry.id}`);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
await stopDeployment(client, step, "archive");
|
|
165
|
+
delete lock.resources[key];
|
|
166
|
+
await saveLock(lock);
|
|
167
|
+
log(`archived deployment ${entry.id} (${step.file} is gone)`);
|
|
168
|
+
}
|
|
169
|
+
return steps;
|
|
170
|
+
}
|
|
171
|
+
// A deployment as it is now, or null if it's been deleted or archived, which makes it unusable.
|
|
172
|
+
// `step` has the deployment's lock entry.
|
|
173
|
+
async function currentDeployment(client, step) {
|
|
174
|
+
try {
|
|
175
|
+
const remote = await client.beta.deployments.retrieve(step.entry.id);
|
|
176
|
+
return remote.archived_at ? null : remote;
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
if (err instanceof Anthropic.APIError && err.status === 404)
|
|
180
|
+
return null;
|
|
181
|
+
throw apiError(step, err);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// Pauses or archives a deployment, unless it's already that way, or gone.
|
|
185
|
+
async function stopDeployment(client, step, how) {
|
|
186
|
+
const remote = await currentDeployment(client, step);
|
|
187
|
+
if (!remote || (how === "pause" && remote.status === "paused"))
|
|
188
|
+
return;
|
|
189
|
+
await call(step, () => client.beta.deployments[how](remote.id));
|
|
190
|
+
}
|
|
191
|
+
// Pauses the deployment of every scheduled task in a lock, such as when a host takes the agent
|
|
192
|
+
// offline. The next deploy unpauses the ones whose files say they're enabled.
|
|
193
|
+
// (An entry means the lock and its resources are there, hence the !s.)
|
|
194
|
+
export async function pauseScheduled({ lock, client, saveLock = () => { } }) {
|
|
195
|
+
for (const [key, entry] of Object.entries(lock?.resources ?? {})) {
|
|
196
|
+
if (entry.kind !== "deployment")
|
|
197
|
+
continue;
|
|
198
|
+
await stopDeployment(client, { file: key.slice(2), key, kind: "deployment", entry }, "pause");
|
|
199
|
+
lock.resources[key] = { ...entry, paused: true };
|
|
200
|
+
await saveLock(lock);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
// Archives the deployment of every scheduled task in a lock, for good, such as before a host deletes
|
|
204
|
+
// the agent. The next deploy makes new ones.
|
|
205
|
+
export async function archiveScheduled({ lock, client, saveLock = () => { } }) {
|
|
206
|
+
for (const [key, entry] of Object.entries(lock?.resources ?? {})) {
|
|
207
|
+
if (entry.kind !== "deployment")
|
|
208
|
+
continue;
|
|
209
|
+
await stopDeployment(client, { file: key.slice(2), key, kind: "deployment", entry }, "archive");
|
|
210
|
+
delete lock.resources[key];
|
|
211
|
+
await saveLock(lock);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Reads claude-lock.json, or starts a new lock, and checks it was written for this API.
|
|
215
|
+
export const openLock = (dir, client) => prepareLock(readLock(dir), client);
|
|
216
|
+
// The lock to deploy with: the one given, or a new one, after checking it's for this API.
|
|
217
|
+
export function prepareLock(previous, client) {
|
|
218
|
+
const baseURL = client.baseURL;
|
|
219
|
+
// resources is filled in just below if it's missing.
|
|
220
|
+
const lock = (previous ?? { version: 1, origin: { base_url: baseURL }, resources: {} });
|
|
221
|
+
lock.resources ??= {};
|
|
222
|
+
upgradeLock(lock);
|
|
223
|
+
if (lock.origin?.base_url && lock.origin.base_url !== baseURL) {
|
|
224
|
+
throw new DeployError(`${LOCK_FILE} was written for ${lock.origin.base_url}, but this client uses ${baseURL}`);
|
|
225
|
+
}
|
|
226
|
+
return lock;
|
|
227
|
+
}
|
|
228
|
+
// Uploads each skill that's new or changed. A change uploads the whole folder as a new version.
|
|
229
|
+
async function deploySkills(skills, { client, lock, dryRun, log, saveLock }) {
|
|
230
|
+
const steps = [];
|
|
231
|
+
for (const skill of skills) {
|
|
232
|
+
const step = planStep(lock, { file: skill.path, key: skillKey(skill), kind: "skill", body: skillFingerprint(skill) });
|
|
233
|
+
steps.push(step);
|
|
234
|
+
if (dryRun || step.action === "unchanged") {
|
|
235
|
+
log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? skill.name}`);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
// The API keeps a skill's layout from these names, so each one starts with its folder.
|
|
239
|
+
const files = await Promise.all(skill.files.map((f) => toFile(f.bytes, `${skill.name}/${f.rel}`)));
|
|
240
|
+
let id;
|
|
241
|
+
let version;
|
|
242
|
+
if (step.action === "create") {
|
|
243
|
+
const created = await call(step, () => client.skills.create({ files }));
|
|
244
|
+
({ id, latest_version_id: version } = created);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
({ id } = step.entry);
|
|
248
|
+
await retrieve(step, () => client.skills.retrieve(id));
|
|
249
|
+
({ id: version } = await call(step, () => client.skills.versions.create(id, { files })));
|
|
250
|
+
}
|
|
251
|
+
lock.resources[step.key] = { kind: "skill", id, version, hash: step.hash };
|
|
252
|
+
await saveLock(lock);
|
|
253
|
+
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} skill ${id} (version ${version})`);
|
|
254
|
+
}
|
|
255
|
+
return steps;
|
|
256
|
+
}
|
|
257
|
+
// Creates or updates each vault, then updates the settings of credentials already created.
|
|
258
|
+
// A credential file with no credential yet is reported, not created: that needs its secrets.
|
|
259
|
+
async function deployVaults(vaults, { client, lock, dryRun, log, saveLock, pathOf }) {
|
|
260
|
+
const steps = [];
|
|
261
|
+
for (const vault of vaults) {
|
|
262
|
+
const step = planStep(lock, { file: vault.path, key: vaultKey(vault), kind: "vault", body: vaultBody(vault) });
|
|
263
|
+
steps.push(step);
|
|
264
|
+
for (const cred of vault.credentials) {
|
|
265
|
+
// cred and vaultStep are set just below.
|
|
266
|
+
const credStep = planStep(lock, { file: cred.file, key: credentialKey(cred), kind: "credential", body: credentialSettings(cred) });
|
|
267
|
+
credStep.cred = cred;
|
|
268
|
+
credStep.vaultStep = step;
|
|
269
|
+
// A credential belongs to the vault it was created in; if that vault was replaced, it's gone.
|
|
270
|
+
if (credStep.entry && credStep.entry.vault_id !== step.entry?.id)
|
|
271
|
+
credStep.entry = undefined;
|
|
272
|
+
if (!credStep.entry)
|
|
273
|
+
credStep.action = "missing";
|
|
274
|
+
steps.push(credStep);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
// Check every credential update first, so an immutable field changed in one file stops the
|
|
278
|
+
// deploy before anything is sent.
|
|
279
|
+
if (!dryRun) {
|
|
280
|
+
for (const step of steps.filter((s) => s.kind === "credential" && s.action === "update")) {
|
|
281
|
+
const remote = await retrieve(step, () => client.beta.vaults.credentials.retrieve(step.entry.id, { vault_id: step.entry.vault_id }));
|
|
282
|
+
const changed = changedImmutableFields(step.cred, remote.auth);
|
|
283
|
+
if (changed.length > 0) {
|
|
284
|
+
throw new DeployError(`${step.file}: ${changed.map((f) => `\`auth.${f}\``).join(", ")} can't be changed on an existing credential. ` +
|
|
285
|
+
`Delete it with \`agentschema cred delete ${pathOf(step.file)}\`, then create it again with \`agentschema cred deploy\`.`);
|
|
286
|
+
}
|
|
287
|
+
step.remote = remote;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
for (const step of steps) {
|
|
291
|
+
if (step.action === "missing") {
|
|
292
|
+
log(`missing credential ${step.file} (create it with: agentschema cred deploy ${pathOf(step.file)})`);
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (dryRun || step.action === "unchanged") {
|
|
296
|
+
log(`${step.action.padEnd(9)} ${step.kind} ${step.entry?.id ?? ""}`.trimEnd());
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
// Past here, an update's step has its lock entry.
|
|
300
|
+
let result;
|
|
301
|
+
if (step.kind === "vault") {
|
|
302
|
+
if (step.action === "create") {
|
|
303
|
+
result = await call(step, () => client.beta.vaults.create(step.body));
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
const remote = await retrieve(step, () => client.beta.vaults.retrieve(step.entry.id));
|
|
307
|
+
const body = { ...step.body, metadata: metadataWithDeletions(step.body.metadata, remote.metadata) };
|
|
308
|
+
result = await call(step, () => client.beta.vaults.update(step.entry.id, body));
|
|
309
|
+
}
|
|
310
|
+
lock.resources[step.key] = { kind: "vault", id: result.id, hash: step.hash };
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
result = await call(step, () => client.beta.vaults.credentials.update(step.entry.id, credentialUpdateBody(step)));
|
|
314
|
+
lock.resources[step.key] = { ...step.entry, hash: step.hash };
|
|
315
|
+
}
|
|
316
|
+
await saveLock(lock);
|
|
317
|
+
log(`${(step.action === "create" ? "created" : "updated").padEnd(9)} ${step.kind} ${result.id}`);
|
|
318
|
+
}
|
|
319
|
+
return steps;
|
|
320
|
+
}
|
|
321
|
+
// Fills in a step's hash, lock entry and action, in place.
|
|
322
|
+
function planStep(lock, input) {
|
|
323
|
+
const step = input;
|
|
324
|
+
step.hash = hashBody(step.body);
|
|
325
|
+
step.entry = lock.resources[step.key];
|
|
326
|
+
if (step.entry && step.entry.kind !== step.kind) {
|
|
327
|
+
throw new DeployError(`${LOCK_FILE}: entry for ${step.key} is a ${step.entry.kind}, expected ${step.kind}`);
|
|
328
|
+
}
|
|
329
|
+
step.action = !step.entry ? "create" : step.entry.hash === step.hash ? "unchanged" : "update";
|
|
330
|
+
return step;
|
|
331
|
+
}
|
|
332
|
+
// Only a credential's name, metadata, refresh scope, networking and injection location can
|
|
333
|
+
// change; the immutable fields were checked to be unchanged, and the secrets stay as they are
|
|
334
|
+
// in the vault.
|
|
335
|
+
// `step` is an update, so it has its lock entry.
|
|
336
|
+
function credentialUpdateBody(step) {
|
|
337
|
+
const { display_name, auth, metadata } = step.body;
|
|
338
|
+
const body = {
|
|
339
|
+
vault_id: step.entry.vault_id,
|
|
340
|
+
display_name,
|
|
341
|
+
metadata: metadataWithDeletions(metadata, step.remote?.metadata),
|
|
342
|
+
};
|
|
343
|
+
if (auth.refresh)
|
|
344
|
+
body.auth = { type: auth.type, refresh: { scope: auth.refresh.scope ?? null } };
|
|
345
|
+
if (auth.type === ENV_VAR) {
|
|
346
|
+
// An update keeps what it isn't sent, so spell out what the file means: when created,
|
|
347
|
+
// no injection_location enables both, and a field left out of one is false.
|
|
348
|
+
const where = auth.injection_location;
|
|
349
|
+
body.auth = {
|
|
350
|
+
type: auth.type,
|
|
351
|
+
networking: auth.networking,
|
|
352
|
+
injection_location: where ? { header: where.header === true, body: where.body === true } : { header: true, body: true },
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
return body;
|
|
356
|
+
}
|
|
357
|
+
// The bodies are the files' frontmatter, which checkFiles checked has what the API requires.
|
|
358
|
+
async function deployEnvironment(client, step) {
|
|
359
|
+
if (step.action === "create")
|
|
360
|
+
return call(step, () => client.beta.environments.create(step.body));
|
|
361
|
+
const { id } = step.entry;
|
|
362
|
+
const remote = await retrieve(step, () => client.beta.environments.retrieve(id));
|
|
363
|
+
const body = { ...step.body };
|
|
364
|
+
// Updates keep any field you omit, so clear what was removed from env.md.
|
|
365
|
+
if (!("description" in body))
|
|
366
|
+
body.description = null;
|
|
367
|
+
body.metadata = metadataWithDeletions(body.metadata, remote.metadata);
|
|
368
|
+
return call(step, () => client.beta.environments.update(id, body));
|
|
369
|
+
}
|
|
370
|
+
async function deployAgent(client, step, force) {
|
|
371
|
+
if (step.action === "create")
|
|
372
|
+
return call(step, () => client.beta.agents.create(step.body));
|
|
373
|
+
const { id, version } = step.entry;
|
|
374
|
+
const remote = await retrieve(step, () => client.beta.agents.retrieve(id));
|
|
375
|
+
const body = { ...step.body };
|
|
376
|
+
// Updates keep any field you omit, so clear what was removed from agent.md.
|
|
377
|
+
if (!("system" in body))
|
|
378
|
+
body.system = null;
|
|
379
|
+
for (const field of ["description", "multiagent"])
|
|
380
|
+
if (!(field in body))
|
|
381
|
+
body[field] = null;
|
|
382
|
+
for (const field of ["tools", "mcp_servers", "skills"])
|
|
383
|
+
if (!(field in body))
|
|
384
|
+
body[field] = [];
|
|
385
|
+
body.metadata = metadataWithDeletions(body.metadata, remote.metadata);
|
|
386
|
+
// Sending the locked version makes the API refuse the update if someone changed the agent since.
|
|
387
|
+
if (!force && version !== undefined)
|
|
388
|
+
body.version = Number(version);
|
|
389
|
+
try {
|
|
390
|
+
return await client.beta.agents.update(id, body);
|
|
391
|
+
}
|
|
392
|
+
catch (err) {
|
|
393
|
+
if (err instanceof Anthropic.APIError && err.status === 409) {
|
|
394
|
+
throw new DeployError(`agent ${id} was changed outside this folder (${LOCK_FILE} has version ${version}, ` +
|
|
395
|
+
`the agent is at version ${remote.version}). Re-run with --force to overwrite it.`);
|
|
396
|
+
}
|
|
397
|
+
throw apiError(step, err);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
// Metadata updates merge, so keys removed from the file are sent as null to delete them.
|
|
401
|
+
export function metadataWithDeletions(local = {}, remote = {}) {
|
|
402
|
+
const merged = { ...local };
|
|
403
|
+
for (const key of Object.keys(remote ?? {}))
|
|
404
|
+
if (!(key in merged))
|
|
405
|
+
merged[key] = null;
|
|
406
|
+
return merged;
|
|
407
|
+
}
|
|
408
|
+
// `step` has the resource's lock key and entry.
|
|
409
|
+
export async function retrieve(step, fn) {
|
|
410
|
+
let remote;
|
|
411
|
+
try {
|
|
412
|
+
remote = await fn();
|
|
413
|
+
}
|
|
414
|
+
catch (err) {
|
|
415
|
+
if (err instanceof Anthropic.APIError && err.status === 404) {
|
|
416
|
+
throw new DeployError(`${step.kind} ${step.entry.id} in ${LOCK_FILE} no longer exists. ` +
|
|
417
|
+
`Remove the "${step.key}" entry from ${LOCK_FILE} to create a new one.`);
|
|
418
|
+
}
|
|
419
|
+
throw apiError(step, err);
|
|
420
|
+
}
|
|
421
|
+
// Not every resource can be archived (skills can't), so not every type has archived_at.
|
|
422
|
+
if (remote.archived_at) {
|
|
423
|
+
throw new DeployError(`${step.kind} ${step.entry.id} is archived and can't be updated. ` +
|
|
424
|
+
`Remove the "${step.key}" entry from ${LOCK_FILE} to create a new one.`);
|
|
425
|
+
}
|
|
426
|
+
return remote;
|
|
427
|
+
}
|
|
428
|
+
export async function call(step, fn) {
|
|
429
|
+
try {
|
|
430
|
+
return await fn();
|
|
431
|
+
}
|
|
432
|
+
catch (err) {
|
|
433
|
+
throw apiError(step, err);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function apiError(step, err) {
|
|
437
|
+
if (!(err instanceof Anthropic.APIError))
|
|
438
|
+
return err;
|
|
439
|
+
// The API's error body: { error: { type, message } }.
|
|
440
|
+
const message = err.error?.error?.message ?? err.message;
|
|
441
|
+
return new DeployError(`${step.file}: the API rejected the ${step.kind} (${err.status ?? "network error"}): ${message}`);
|
|
442
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const ENV_FILE_NAME = ".env";
|
|
2
|
+
export interface ParsedEnvFile {
|
|
3
|
+
values: Record<string, string>;
|
|
4
|
+
bad: number[];
|
|
5
|
+
}
|
|
6
|
+
export declare function parseEnvFile(text: string): ParsedEnvFile;
|
|
7
|
+
export declare function loadEnvFile(dir: string, env?: NodeJS.ProcessEnv): string[];
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
export const ENV_FILE_NAME = ".env";
|
|
4
|
+
// Parses KEY=VALUE lines. Returns { values, bad }: `bad` holds the numbers of lines that aren't
|
|
5
|
+
// valid, so they can be reported without showing what's on them.
|
|
6
|
+
export function parseEnvFile(text) {
|
|
7
|
+
const values = {};
|
|
8
|
+
const bad = [];
|
|
9
|
+
for (const [index, raw] of text.replace(/^/, "").split(/\r?\n/).entries()) {
|
|
10
|
+
const line = raw.trim();
|
|
11
|
+
if (line === "" || line.startsWith("#"))
|
|
12
|
+
continue;
|
|
13
|
+
const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
|
|
14
|
+
const value = match && parseValue(match[2]);
|
|
15
|
+
if (value === null || !match)
|
|
16
|
+
bad.push(index + 1);
|
|
17
|
+
else
|
|
18
|
+
values[match[1]] = value;
|
|
19
|
+
}
|
|
20
|
+
return { values, bad };
|
|
21
|
+
}
|
|
22
|
+
// A quoted value, where double quotes understand \n and \", or a bare value up to a " #" comment.
|
|
23
|
+
// Returns null for a quote that isn't closed.
|
|
24
|
+
function parseValue(text) {
|
|
25
|
+
const quote = text[0];
|
|
26
|
+
if (quote === "'" || quote === '"') {
|
|
27
|
+
// With no closing quote, undefined + 1 is NaN, which the check below catches.
|
|
28
|
+
const end = quote === "'" ? text.indexOf("'", 1) : /(?<!\\)"/.exec(text.slice(1))?.index + 1;
|
|
29
|
+
if (end === undefined || end < 1 || Number.isNaN(end))
|
|
30
|
+
return null;
|
|
31
|
+
const inner = text.slice(1, end);
|
|
32
|
+
return quote === "'" ? inner : inner.replace(/\\n/g, "\n").replace(/\\"/g, '"');
|
|
33
|
+
}
|
|
34
|
+
return text.replace(/\s+#.*$/, "").trim();
|
|
35
|
+
}
|
|
36
|
+
// Loads a folder's .env into process.env, for code that runs on your side. A variable already
|
|
37
|
+
// set in the shell wins. A missing file is fine. Returns warnings to show.
|
|
38
|
+
export function loadEnvFile(dir, env = process.env) {
|
|
39
|
+
let text;
|
|
40
|
+
try {
|
|
41
|
+
text = readFileSync(join(dir, ENV_FILE_NAME), "utf8");
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
if (err.code === "ENOENT")
|
|
45
|
+
return [];
|
|
46
|
+
return [`couldn't read ${ENV_FILE_NAME}: ${err.message}`];
|
|
47
|
+
}
|
|
48
|
+
const { values, bad } = parseEnvFile(text);
|
|
49
|
+
for (const [name, value] of Object.entries(values)) {
|
|
50
|
+
if (env[name] === undefined)
|
|
51
|
+
env[name] = value;
|
|
52
|
+
}
|
|
53
|
+
return bad.map((line) => `${ENV_FILE_NAME}:${line}: not a KEY=VALUE line, so it was skipped`);
|
|
54
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Document } from "yaml";
|
|
2
|
+
import type { FileMap } from "../lib/files.ts";
|
|
3
|
+
export declare function folderProblem(dir: string): string | null;
|
|
4
|
+
export declare function readFolder(dir: string): FileMap;
|
|
5
|
+
export declare function updateFrontmatter(file: string, edit: (doc: Document) => void): void;
|
|
@@ -8,48 +8,50 @@ import { SKILLS_DIR } from "../lib/skills.js";
|
|
|
8
8
|
import { SYSTEM_PROMPT_DIR } from "../lib/system-prompt.js";
|
|
9
9
|
import { TOOLS_DIR } from "../lib/tools.js";
|
|
10
10
|
import { VAULTS_DIR } from "../lib/vaults.js";
|
|
11
|
-
|
|
12
11
|
const FOLDERS = [TOOLS_DIR, SKILLS_DIR, VAULTS_DIR, CHANNELS_DIR, SCHEDULED_DIR, SYSTEM_PROMPT_DIR];
|
|
13
12
|
const TOP_LEVEL_FILES = [AGENT_FILE, COMPUTER_FILE, OLD_COMPUTER_FILE];
|
|
14
|
-
|
|
15
13
|
// Why `dir` can't be read as an agent folder, or null when it can.
|
|
16
14
|
export function folderProblem(dir) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
15
|
+
try {
|
|
16
|
+
return statSync(dir).isDirectory() ? null : `${dir}: not a directory`;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return `${dir}: no such directory`;
|
|
20
|
+
}
|
|
22
21
|
}
|
|
23
|
-
|
|
24
22
|
// Reads an agent folder into a file map (see lib/files.js), as bytes. Only the agent's own files
|
|
25
23
|
// are read, so empty folders, hidden files and node_modules aren't part of it.
|
|
26
24
|
export function readFolder(dir) {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
25
|
+
const files = {};
|
|
26
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
27
|
+
const path = join(dir, entry.name);
|
|
28
|
+
if (FOLDERS.includes(entry.name)) {
|
|
29
|
+
if (statSync(path).isDirectory())
|
|
30
|
+
walk(path, entry.name, files, entry.name !== SKILLS_DIR);
|
|
31
|
+
else
|
|
32
|
+
files[entry.name] = readFileSync(path);
|
|
33
|
+
}
|
|
34
|
+
else if (TOP_LEVEL_FILES.includes(entry.name.toLowerCase()) && !statSync(path).isDirectory()) {
|
|
35
|
+
files[entry.name] = readFileSync(path);
|
|
36
|
+
}
|
|
35
37
|
}
|
|
36
|
-
|
|
37
|
-
return files;
|
|
38
|
+
return files;
|
|
38
39
|
}
|
|
39
|
-
|
|
40
40
|
// Everything in a skill's folder gets uploaded, so links there aren't followed, in case one
|
|
41
41
|
// points outside the agent.
|
|
42
42
|
function walk(folder, prefix, files, followLinks) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
43
|
+
for (const entry of readdirSync(folder, { withFileTypes: true })) {
|
|
44
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules")
|
|
45
|
+
continue;
|
|
46
|
+
const path = join(folder, entry.name);
|
|
47
|
+
const rel = `${prefix}/${entry.name}`;
|
|
48
|
+
if (entry.isDirectory())
|
|
49
|
+
walk(path, rel, files, followLinks);
|
|
50
|
+
else if (entry.isFile() || (followLinks && entry.isSymbolicLink() && statSync(path).isFile()))
|
|
51
|
+
files[rel] = readFileSync(path);
|
|
52
|
+
}
|
|
50
53
|
}
|
|
51
|
-
|
|
52
54
|
// Edits a file's frontmatter on disk, keeping its comments and the rest of the file.
|
|
53
55
|
export function updateFrontmatter(file, edit) {
|
|
54
|
-
|
|
56
|
+
writeFileSync(file, editFrontmatter(readFileSync(file, "utf8"), edit));
|
|
55
57
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Answers } from "../lib/scaffold.ts";
|
|
2
|
+
import type { PromptInput } from "./prompts.ts";
|
|
3
|
+
export declare class InitError extends Error {
|
|
4
|
+
}
|
|
5
|
+
export declare const defaults: (dir: string) => Answers;
|
|
6
|
+
export interface InitOptions {
|
|
7
|
+
yes?: boolean;
|
|
8
|
+
input?: PromptInput;
|
|
9
|
+
output?: NodeJS.WritableStream;
|
|
10
|
+
}
|
|
11
|
+
export declare function init(dir: string, { yes, input, output }?: InitOptions): Promise<Record<string, string>>;
|
package/dist/src/init.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, resolve } from "node:path";
|
|
3
|
+
import { AGENT_FILE, COMPUTER_FILE } from "../lib/instance.js";
|
|
4
|
+
import { MODELS, NETWORKING, defaultAnswers, scaffold } from "../lib/scaffold.js";
|
|
5
|
+
import { TOOLSET_FILE, TOOLS_DIR } from "../lib/tools.js";
|
|
6
|
+
import { choosePermission } from "./tools-menu.js";
|
|
7
|
+
import { prompts } from "./prompts.js";
|
|
8
|
+
export class InitError extends Error {
|
|
9
|
+
}
|
|
10
|
+
// The answers used when a question is skipped (--yes, or input ends early).
|
|
11
|
+
export const defaults = (dir) => defaultAnswers(basename(resolve(dir)));
|
|
12
|
+
// Asks the setup questions, then writes agent.md and env.md into a new folder `dir`.
|
|
13
|
+
// Returns the files written, as { path: text }.
|
|
14
|
+
export async function init(dir, { yes = false, input = process.stdin, output = process.stdout } = {}) {
|
|
15
|
+
if (existsSync(dir) && readdirSync(dir).length > 0) {
|
|
16
|
+
throw new InitError(`${dir} already exists and isn't empty`);
|
|
17
|
+
}
|
|
18
|
+
const answers = defaults(dir);
|
|
19
|
+
if (!yes)
|
|
20
|
+
await ask(answers, input, output);
|
|
21
|
+
const files = scaffold(answers);
|
|
22
|
+
for (const [file, text] of Object.entries(files)) {
|
|
23
|
+
mkdirSync(dirname(resolve(dir, file)), { recursive: true });
|
|
24
|
+
writeFileSync(resolve(dir, file), text);
|
|
25
|
+
}
|
|
26
|
+
const tools = answers.tools ? `, and ${dir}/${TOOLS_DIR}/${TOOLSET_FILE} with the pre-built tools (set Enabled to false to turn one off)` : "";
|
|
27
|
+
output.write(`\nCreated ${dir}/${AGENT_FILE} and ${dir}/${COMPUTER_FILE}${tools}.\n\nNext:\n`);
|
|
28
|
+
output.write(` agentschema deploy ${dir}\n agentschema run ${dir}\n`);
|
|
29
|
+
return files;
|
|
30
|
+
}
|
|
31
|
+
// Fills in `answers` from the user's replies; an empty reply keeps the default shown.
|
|
32
|
+
async function ask(answers, input, output) {
|
|
33
|
+
const io = prompts(input, output, { cancelled: () => new InitError("cancelled") });
|
|
34
|
+
const { confirm } = io;
|
|
35
|
+
try {
|
|
36
|
+
answers.name = await io.text("Agent name?", answers.name);
|
|
37
|
+
answers.model = await io.select("Model?", MODELS, answers.model);
|
|
38
|
+
answers.system = await io.text("System prompt?", answers.system);
|
|
39
|
+
answers.tools = await confirm("Give it the built-in tools (bash, files, web)?", answers.tools);
|
|
40
|
+
if (answers.tools)
|
|
41
|
+
answers.permission = await choosePermission(io, answers.permission);
|
|
42
|
+
answers.environment = await io.text("Environment name?", answers.environment);
|
|
43
|
+
answers.networking = await io.select("Networking?", NETWORKING, answers.networking);
|
|
44
|
+
if (answers.networking === "limited") {
|
|
45
|
+
answers.packageManagers = await confirm("Allow package managers (npm, pip, …)?", answers.packageManagers);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
io.close();
|
|
50
|
+
}
|
|
51
|
+
}
|