@soft-boy/agentschema 0.3.8 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,8 +15,10 @@ my-agent/
15
15
  ├── vaults/
16
16
  │ └── secrets/
17
17
  │ └── creds.md # a credential, without its secrets
18
- └── channels/
19
- └── telegram.md # a place people can talk to it
18
+ ├── channels/
19
+ │ └── telegram.md # a place people can talk to it
20
+ └── scheduled/
21
+ └── good-morning.md # a task it runs on a timetable
20
22
  ```
21
23
 
22
24
  **Status:** v0.2 draft. v0.2 breaks from the Claude Managed Agents schema: tools move out of `agent.md` and into `tools/`.
@@ -154,12 +156,25 @@ allow: "*"
154
156
  You're chatting on Telegram. Keep replies short.
155
157
  ```
156
158
 
159
+ ### `scheduled/`
160
+
161
+ Each `.md` file is a task the agent runs on a timetable, named after the file. The frontmatter says when, as a cron expression and a time zone, and the body is the message each run starts with. `deploy` turns each one into a Managed Agents deployment, so Anthropic starts the runs, and removing the file stops them. See [Scheduled tasks](docs/scheduled.md):
162
+
163
+ ```markdown
164
+ ---
165
+ schedule: "0 8 * * 1-5"
166
+ timezone: America/Los_Angeles
167
+ ---
168
+
169
+ Say good morning in #gm.
170
+ ```
171
+
157
172
  ## Usage
158
173
 
159
174
  ```sh
160
175
  agentschema init <name> # scaffold a new agent folder
161
176
  agentschema check [dir] # validate the folder, no network
162
- agentschema deploy [dir] # create or update the skills, agent, environment and vaults
177
+ agentschema deploy [dir] # create or update the agent and everything it needs, including scheduled tasks
163
178
  agentschema run [dir] # chat with the deployed agent in the terminal
164
179
  agentschema list # list the agents in your workspace
165
180
  agentschema delete <agent_id> # archive an agent
@@ -25,7 +25,7 @@ const USAGE = `Usage: agentschema <command> [dir] [options]
25
25
  Commands:
26
26
  init <name> Scaffold a new agent folder, asking a few questions
27
27
  check [dir] Validate the folder's files, without calling the API
28
- deploy [dir] Create or update the skills, agent, environment and vaults, and write claude-lock.json
28
+ deploy [dir] Create or update the skills, agent, environment, vaults and scheduled tasks, and write claude-lock.json
29
29
  run [dir] Chat with the deployed agent in a new session, loading dir/.env for your tools
30
30
  list List the agents in your workspace
31
31
  delete <agent_id> Archive an agent (agents can't be deleted outright)
package/lib/check.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { checkChannels, readChannels } from "./channels.js";
2
2
  import { textOf } from "./files.js";
3
3
  import { AGENT_FILE, ENV_FILE, readInstance } from "./instance.js";
4
+ import { checkScheduled, readScheduled } from "./scheduled.js";
4
5
  import { MAX_UPLOAD_BYTES, SKILLS_DIR, readSkills } from "./skills.js";
5
6
  import { MCP_TOOLSET, TOOLS_DIR, checkTools, readTools } from "./tools.js";
6
7
  import { CREDENTIAL_TYPES, ENV_VAR, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULT_FILE, get, readVaults } from "./vaults.js";
@@ -34,7 +35,8 @@ export function checkFiles(files, options = {}) {
34
35
  const { vaults, errors: vaultErrors } = readVaults(files);
35
36
  const { skills, errors: skillErrors } = readSkills(files);
36
37
  const { channels, errors: channelErrors } = readChannels(files);
37
- errors.push(...toolErrors, ...vaultErrors, ...skillErrors, ...channelErrors);
38
+ const { tasks: scheduled, errors: scheduledErrors } = readScheduled(files);
39
+ errors.push(...toolErrors, ...vaultErrors, ...skillErrors, ...channelErrors, ...scheduledErrors);
38
40
  const warnings = [];
39
41
 
40
42
  if (agent) checkAgent(agent, errors, warnings);
@@ -48,17 +50,18 @@ export function checkFiles(files, options = {}) {
48
50
  for (const vault of vaults) checkVault(vault, errors, warnings);
49
51
  checkEnvVarCredentials(vaults, env, warnings);
50
52
  checkChannels(channels, { agent: agent ?? undefined, tools, toolsets: options.toolsets }, errors, warnings);
53
+ checkScheduled(scheduled, { tools }, errors, warnings);
51
54
 
52
55
  const vaultFiles = vaults.flatMap((v) => [...(v.file ? [[`${v.path}/${VAULT_FILE}`, v.file]] : []), ...v.credentials.map((c) => [c.file, c])]);
53
56
  const skillTexts = skills.flatMap((s) => s.files.map((f) => [`${s.path}/${f.rel}`, { raw: textOf(f.bytes) }]));
54
- for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t]), ...vaultFiles, ...skillTexts, ...channels.map((c) => [c.file, c])]) {
57
+ for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t]), ...vaultFiles, ...skillTexts, ...channels.map((c) => [c.file, c]), ...scheduled.map((t) => [t.file, t])]) {
55
58
  if (!parsed) continue;
56
59
  for (const [pattern, what] of SECRET_PATTERNS) {
57
60
  if (pattern.test(parsed.raw)) errors.push(`${file}: looks like it contains ${what}; keep secrets out of these files`);
58
61
  }
59
62
  }
60
63
 
61
- return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills, channels } : null };
64
+ return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills, channels, scheduled } : null };
62
65
  }
63
66
 
64
67
  function checkAgent({ data, body }, errors, warnings) {
package/lib/index.js CHANGED
@@ -6,6 +6,7 @@ export { bytesOf, isIgnoredPath, pathsUnder, textOf } from "./files.js";
6
6
  export { AGENT_FILE, ENV_FILE, agentBody, envBody, readInstance } from "./instance.js";
7
7
  export { FileError, editFrontmatter, parseMarkdown } from "./markdown.js";
8
8
  export { MODELS, NETWORKING, builtInFile, defaultAnswers, scaffold } from "./scaffold.js";
9
+ export { SCHEDULED_DIR, cronProblem, isTimeZone, readScheduled, taskBody, taskKey, taskSettings } from "./scheduled.js";
9
10
  export { MAX_UPLOAD_BYTES, SKILLS_DIR, SKILL_FILE, readSkills, skillKey, skillRefs } from "./skills.js";
10
11
  export { agentMessageText, textStream } from "./stream.js";
11
12
  export {
@@ -0,0 +1,175 @@
1
+ import { pathsUnder, textOf } from "./files.js";
2
+ import { FileError, parseMarkdown } from "./markdown.js";
3
+ import { AGENTBOOK, MCP_TOOLSET, TOOLSET } from "./tools.js";
4
+
5
+ // A scheduled task runs the agent on a timetable, with the same message each time, like "say good
6
+ // morning in #gm" every weekday at 8. Each file in scheduled/ is one, named after its file, and it
7
+ // becomes a Managed Agents deployment: Anthropic starts each run, so nothing needs to be running here.
8
+ export const SCHEDULED_DIR = "scheduled";
9
+
10
+ const FIELDS = ["schedule", "timezone", "enabled", "budget", "description"];
11
+ const MAX_DESCRIPTION = 2048;
12
+
13
+ // Each part of a cron expression, and the numbers it takes. Day of the week is 0 to 7, where both 0
14
+ // and 7 are Sunday.
15
+ const CRON_PARTS = [
16
+ ["minute", 0, 59],
17
+ ["hour", 0, 23],
18
+ ["day of the month", 1, 31],
19
+ ["month", 1, 12],
20
+ ["day of the week", 0, 7],
21
+ ];
22
+
23
+ // Reads scheduled/: each .md file directly inside it is a task named after the file. No scheduled/
24
+ // folder means no tasks. Returns { tasks, errors }; a file that can't be parsed has an entry in errors.
25
+ export function readScheduled(files) {
26
+ if (SCHEDULED_DIR in files) return { tasks: [], errors: [`${SCHEDULED_DIR}: not a directory`] };
27
+
28
+ const tasks = [];
29
+ const errors = [];
30
+ const reportedFolders = new Set();
31
+ for (const file of pathsUnder(files, SCHEDULED_DIR)) {
32
+ const [, item, ...rest] = file.split("/");
33
+ if (rest.length > 0) {
34
+ const folder = `${SCHEDULED_DIR}/${item}`;
35
+ if (!reportedFolders.has(folder)) errors.push(`${folder}: ${SCHEDULED_DIR}/ holds task files, not folders`);
36
+ reportedFolders.add(folder);
37
+ } else if (item.endsWith(".md")) {
38
+ try {
39
+ tasks.push({ file, name: item.slice(0, -".md".length), ...parseMarkdown(textOf(files[file]), file) });
40
+ } catch (err) {
41
+ if (!(err instanceof FileError)) throw err;
42
+ errors.push(err.message);
43
+ }
44
+ }
45
+ }
46
+ return { tasks, errors };
47
+ }
48
+
49
+ // What's wrong with a cron expression, or null. Only the standard five parts are allowed, with
50
+ // numbers, ranges, lists, steps and *, which is what Managed Agents accepts.
51
+ export function cronProblem(expression) {
52
+ if (typeof expression !== "string") return `must be a cron expression in quotes, like "0 8 * * 1-5"`;
53
+ const parts = expression.trim().split(/\s+/);
54
+ if (parts.length !== 5) return `must have five parts, for the minute, hour, day of the month, month and day of the week, like "0 8 * * 1-5"`;
55
+ for (const [i, part] of parts.entries()) {
56
+ const [what, min, max] = CRON_PARTS[i];
57
+ for (const item of part.split(",")) {
58
+ const match = /^(?:\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(item);
59
+ if (!match) return `has "${part}" for the ${what}; use numbers, a range like 1-5, a list like 1,3, a step like */15, or *`;
60
+ const [, from, to, step] = match;
61
+ const numbers = [from, to].filter((n) => n !== undefined).map(Number);
62
+ if (numbers.some((n) => n < min || n > max)) return `has "${part}" for the ${what}, which goes from ${min} to ${max}`;
63
+ if (to !== undefined && Number(from) > Number(to)) return `has "${part}" for the ${what}, a range that runs backwards`;
64
+ if (step !== undefined && Number(step) < 1) return `has "${part}" for the ${what}, but a step must be at least 1`;
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+
70
+ // Whether a time zone is one the IANA database knows, like America/Los_Angeles or UTC.
71
+ export function isTimeZone(value) {
72
+ if (typeof value !== "string" || value.trim() === "") return false;
73
+ try {
74
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
75
+ return true;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ // Errors and warnings for the task files, in check's format. `tools` and `toolsets` are the agent's,
82
+ // to warn about tools nobody can answer during a run.
83
+ export function checkScheduled(tasks, { tools = [] } = {}, errors = [], warnings = []) {
84
+ const waiting = toolsThatWaitForSomeone(tools);
85
+ for (const task of tasks) {
86
+ const err = (msg) => errors.push(`${task.file}: ${msg}`);
87
+ const { data, body, name } = task;
88
+
89
+ // It's the deployment's name, and hosts use it to keep track of the task.
90
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name)) err("the name may only use lowercase letters, digits, _ and -, up to 64 characters");
91
+
92
+ if (data.schedule === undefined) err('`schedule` is required: a cron expression, like "0 8 * * 1-5" for 8 AM on weekdays');
93
+ else {
94
+ const problem = cronProblem(data.schedule);
95
+ if (problem) err(`\`schedule\` ${problem}`);
96
+ }
97
+
98
+ if (data.timezone === undefined) err("`timezone` is required, like America/Los_Angeles or UTC");
99
+ else if (!isTimeZone(data.timezone)) err(`\`timezone\` must be a time zone like America/Los_Angeles or UTC, and ${JSON.stringify(data.timezone)} isn't one`);
100
+
101
+ if (data.enabled !== undefined && typeof data.enabled !== "boolean") err("`enabled` must be true or false");
102
+
103
+ if (data.budget !== undefined && budgetCents(data.budget) === null) err("`budget` must be an amount in US dollars above 0, like 0.50");
104
+
105
+ if (data.description !== undefined && data.description !== null) {
106
+ if (typeof data.description !== "string") err("`description` must be text");
107
+ else if (data.description.length > MAX_DESCRIPTION) err(`\`description\` must be at most ${MAX_DESCRIPTION.toLocaleString("en-US")} characters`);
108
+ }
109
+
110
+ for (const key of Object.keys(data)) if (!FIELDS.includes(key)) err(`unknown field \`${key}\``);
111
+
112
+ if (body.trim() === "") err("the body is empty; it's the message the agent starts each run with");
113
+
114
+ if (waiting.length > 0 && data.enabled !== false) {
115
+ warnings.push(`${task.file}: nobody's there to answer during a scheduled run, so a run that calls one of these waits until it's stopped: ${waiting.join(", ")}`);
116
+ }
117
+ }
118
+ return { errors, warnings };
119
+ }
120
+
121
+ // Dollars as the API's minor units, or null if it isn't an amount above 0 with at most two decimals.
122
+ function budgetCents(value) {
123
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
124
+ const cents = Math.round(value * 100);
125
+ return Math.abs(cents - value * 100) < 1e-6 && cents > 0 ? cents : null;
126
+ }
127
+
128
+ // The tools that stop a run until someone answers, which nobody does during a scheduled run: ones set to
129
+ // ask first, and custom and agentbook tools, which run wherever the session is being watched from.
130
+ function toolsThatWaitForSomeone(tools) {
131
+ const isOn = (row) => row.enabled.toLowerCase() === "true";
132
+ return tools.flatMap((tool) => {
133
+ const type = tool.data.type;
134
+ if (type === TOOLSET) return (tool.rows ?? []).filter((row) => isOn(row) && row.permission === "always_ask").map((row) => row.name);
135
+ if (type === MCP_TOOLSET) {
136
+ const defaults = tool.data.default_config;
137
+ const fallback = defaults?.permission_policy?.type ?? "always_ask";
138
+ if (tool.rows?.length) return tool.rows.filter((row) => isOn(row) && (row.permission || fallback) === "always_ask").map((row) => `${tool.name}.${row.name}`);
139
+ return fallback === "always_ask" && defaults?.enabled !== false ? [`every tool in ${tool.name}`] : [];
140
+ }
141
+ if (type === "custom") return [tool.name];
142
+ if (type === AGENTBOOK) return (tool.rows ?? []).filter(isOn).map((row) => `${tool.name}.${row.name}`);
143
+ return [];
144
+ });
145
+ }
146
+
147
+ // How a task behaves, with the defaults filled in, so that every host agrees on them.
148
+ export function taskSettings({ name, data, body }) {
149
+ return {
150
+ name,
151
+ schedule: data.schedule,
152
+ timezone: data.timezone,
153
+ enabled: data.enabled ?? true,
154
+ budgetCents: data.budget === undefined ? null : budgetCents(data.budget),
155
+ description: data.description ?? null,
156
+ message: body,
157
+ };
158
+ }
159
+
160
+ // The parts of a deployment that come from the task's file. Whoever deploys it adds the agent, the
161
+ // environment and the vaults.
162
+ export function taskBody(task) {
163
+ const { name, schedule, timezone, budgetCents: cents, description, message } = taskSettings(task);
164
+ const body = {
165
+ name,
166
+ initial_events: [{ type: "user.message", content: [{ type: "text", text: message }] }],
167
+ schedule: { type: "cron", expression: schedule.trim(), timezone },
168
+ };
169
+ if (cents !== null) body.budget = { type: "limit", max_list_cost: { amount: String(cents), currency: "USD" } };
170
+ if (description) body.description = description;
171
+ return body;
172
+ }
173
+
174
+ // A task's key in the lock.
175
+ export const taskKey = (task) => `./${task.file}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soft-boy/agentschema",
3
- "version": "0.3.8",
3
+ "version": "0.3.9",
4
4
  "description": "Markdown based AI agent schema",
5
5
  "type": "module",
6
6
  "bin": {
package/src/deploy.js CHANGED
@@ -3,6 +3,7 @@ import Anthropic, { toFile } from "@anthropic-ai/sdk";
3
3
  import { CHANNELS_DIR, readChannels } from "../lib/channels.js";
4
4
  import { checkFiles } from "../lib/check.js";
5
5
  import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "../lib/instance.js";
6
+ import { taskBody, taskKey, taskSettings } from "../lib/scheduled.js";
6
7
  import { skillKey, skillRefs } from "../lib/skills.js";
7
8
  import { AGENTBOOK } from "../lib/tools.js";
8
9
  import { ENV_VAR, changedImmutableFields, credentialKey, credentialSettings, vaultBody, vaultKey } from "../lib/vaults.js";
@@ -31,20 +32,23 @@ export async function deploy(dir, { client, dryRun = false, force = false, log =
31
32
  return plan;
32
33
  }
33
34
 
34
- // Creates or updates the skills, environment, agent and vaults in a file map (see lib/files.js).
35
- // Skills go first, because the agent refers to their IDs and versions. Credentials are only
36
- // updated here: creating one needs its secrets, so that's `cred deploy`'s job.
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.
37
39
  //
38
40
  // lock the IDs from the last deploy, or null for a first deploy
39
41
  // saveLock called with the lock as soon as each resource exists, so a failure later
40
42
  // doesn't orphan it; it may be async
41
43
  // checkOptions what checkFiles takes: { customTools, toolsets }
42
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
43
47
  //
44
48
  // Returns { plan, lock }. A dry run calls neither the API nor saveLock.
45
49
  export async function deployFiles({
46
50
  files, lock: previous = null, client, dryRun = false, force = false, log = () => {},
47
- saveLock = () => {}, checkOptions = {}, pathOf = (file) => file,
51
+ saveLock = () => {}, checkOptions = {}, pathOf = (file) => file, scheduled = true,
48
52
  }) {
49
53
  const { errors, instance } = checkFiles(files, checkOptions);
50
54
  if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
@@ -98,14 +102,118 @@ export async function deployFiles({
98
102
 
99
103
  const vaultSteps = await deployVaults(instance.vaults, { client, lock, dryRun, log, saveLock, pathOf });
100
104
 
101
- const plan = [...skillSteps, ...steps, ...vaultSteps].map(({ file, kind, action, key }) => ({
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 }) => ({
102
113
  file, kind, action,
103
- id: lock.resources[key]?.id,
114
+ id: lock.resources[key]?.id ?? entry?.id,
104
115
  version: lock.resources[key]?.version,
105
116
  }));
106
117
  return { plan, lock };
107
118
  }
108
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
+
109
217
  // Reads claude-lock.json, or starts a new lock, and checks it was written for this API.
110
218
  export const openLock = (dir, client) => prepareLock(readLock(dir), client);
111
219
 
package/src/folder.js CHANGED
@@ -3,11 +3,12 @@ import { join } from "node:path";
3
3
  import { CHANNELS_DIR } from "../lib/channels.js";
4
4
  import { editFrontmatter } from "../lib/markdown.js";
5
5
  import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
6
+ import { SCHEDULED_DIR } from "../lib/scheduled.js";
6
7
  import { SKILLS_DIR } from "../lib/skills.js";
7
8
  import { TOOLS_DIR } from "../lib/tools.js";
8
9
  import { VAULTS_DIR } from "../lib/vaults.js";
9
10
 
10
- const FOLDERS = [TOOLS_DIR, SKILLS_DIR, VAULTS_DIR, CHANNELS_DIR];
11
+ const FOLDERS = [TOOLS_DIR, SKILLS_DIR, VAULTS_DIR, CHANNELS_DIR, SCHEDULED_DIR];
11
12
  const TOP_LEVEL_FILES = [AGENT_FILE, ENV_FILE];
12
13
 
13
14
  // Why `dir` can't be read as an agent folder, or null when it can.
package/src/node.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // works on file maps and lock objects, so a host can keep both in a database.
3
3
  export { check } from "./check.js";
4
4
  export { createCredential, deleteCredential } from "./cred.js";
5
- export { DeployError, deploy, deployFiles, prepareLock } from "./deploy.js";
5
+ export { DeployError, archiveScheduled, deploy, deployFiles, pauseScheduled, prepareLock } from "./deploy.js";
6
6
  export { readFolder, updateFrontmatter } from "./folder.js";
7
7
  export { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
8
8
  export { listMcpTools, listedMcpToolset } from "./mcp.js";