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