From 64c71c7bc43f57140d613d7fe6efbd1c6b0b6fcf Mon Sep 17 00:00:00 2001 From: Jonathan Date: Tue, 10 Nov 2026 11:04:34 -0500 Subject: [PATCH 1/3] Pause a schedule without editing its file (0.16.0) `skillhook schedules pause|resume`, `POST /schedules//pause|resume` and the cloud commands `schedule.pause` / `schedule.resume`. The pause lives in jobs/.schedules.json, so the repository's skillhook.yaml stays the source of truth for schedules while a person can switch one off from Skillhook Cloud. Paused slots are skipped quietly and never caught up; `until` ends a pause. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + README.md | 2 +- docs/api.md | 1 + docs/cloud-protocol.md | 1 + docs/cloud.md | 3 +- docs/schedules.md | 15 ++- package.json | 2 +- plugins/skillhook/.claude-plugin/plugin.json | 2 +- plugins/skillhook/.codex-plugin/plugin.json | 2 +- plugins/skillhook/.cursor-plugin/plugin.json | 2 +- plugins/skillhook/.mcp.json | 4 +- .../skillhook/skills/skillhook-setup/SKILL.md | 2 +- src/cli.test.ts | 15 ++- src/cloud/control.ts | 24 +++- src/cloud/link.test.ts | 25 +++- src/cloud/link.ts | 4 +- src/cloud/protocol.ts | 6 + src/commands/main.ts | 2 +- src/commands/schedules.ts | 56 ++++++++- src/commands/serve.ts | 4 +- src/scheduler.test.ts | 67 +++++++++- src/scheduler.ts | 114 +++++++++++++++++- src/server.test.ts | 16 +++ src/server.ts | 26 +++- 24 files changed, 369 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c43aab..31b6c25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ All notable changes to skillhook, newest first. The format follows [Keep a Chang ## Unreleased +## 0.16.0 (2026-11-10) + +- A schedule can be paused without editing the file that declares it: `skillhook schedules pause [--reason …] [--until 2h|]` and `schedules resume `, `POST /schedules//pause` and `/resume` (admin), and the cloud commands `schedule.pause` / `schedule.resume`. While paused nothing fires (the webhook still works); slots that pass are counted as skipped and never caught up. The pause lives in `jobs/.schedules.json`, so a repository pull or a restart keeps it, and `--until` ends it by itself. `schedules list`, `GET /health` and the cloud snapshot show `paused: {at, by, reason, until}`. This lets a repository's `skillhook.yaml` stay the source of truth for schedules while a person can still switch one off from Skillhook Cloud. - The published plugin mirror (`MeterApp/skillhook-plugins`, what Anthropic's plugin directory installs) no longer carries local MCP servers, a launcher script or a lockfile: the directory refuses those from organizations that are not Verified. It now has the skills and the hosted Skillhook Cloud server, which the host signs in to with the browser. This repository's own marketplace (`/plugin marketplace add MeterApp/skillhook`) keeps both local servers, and `skillhook mcp --print-config` adds the local one to any host. - New `runners.claude.auth` (`auto`, `login`, `api_key`) chooses whether Claude Code runs and readiness checks use an API key or the subscription login, instead of whichever the environment happens to hold. `auto` (the default) behaves as before. `login` removes `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `CLAUDE_CODE_OAUTH_TOKEN` from Claude Code runs and probes, so readiness reflects the login in `CLAUDE_CONFIG_DIR` / `~/.claude`. `api_key` counts the runner as ready only with a key and keeps the key for skills with their own `claude.config_dir`. Named accounts keep their own credential either way. `skillhook health` reports by the same rule. Changing it is answered by a fresh readiness probe at once. - The test suite no longer depends on the developer's shell: runner credentials (`ANTHROPIC_*`, `OPENAI_*`, `CODEX_*`, `CLAUDE_CONFIG_DIR`, `CLAUDE_CODE_OAUTH_TOKEN`) are cleared before every test file, so `pnpm test` passes inside a Claude Code session too. diff --git a/README.md b/README.md index 5aa2f1b..c692fa0 100644 --- a/README.md +++ b/README.md @@ -385,7 +385,7 @@ Agents reading this repository should start with [`AGENTS.md`](AGENTS.md) (layou | `skillhook config show\|get \|set \|unset \|reload\|path` | Read and edit `skillhook.json`; `set`/`unset` tell the running server, which applies every key but `host` and `port` live. | | `skillhook link [dir] [--no-secret]` / `skillhook unlink ` | Serve the hooks a repository declares in its `skillhook.yaml` (default `.`); stop serving them. | | `skillhook projects [list]` / `skillhook projects init [dir] [--force]` | List linked repositories and their hooks; write a starter `skillhook.yaml` and link it. | -| `skillhook schedules [list]` · `schedules next [--count N]` · `schedules run [--wait S]` | Every skill or hook with a `schedule:`, its next and last runs; preview occurrences; fire one now. | +| `skillhook schedules [list]` · `schedules next [--count N]` · `schedules run [--wait S]` · `schedules pause [--reason T] [--until 2h]` · `schedules resume ` | Every skill or hook with a `schedule:`, its next and last runs; preview occurrences; fire one now; pause one without editing its file, and resume it. | | `skillhook update [--install]` | Check npm for a newer skillhook; `--install` upgrades with the package manager that installed it and restarts the background service when it is idle. | Global options: `--dir ` (default `$SKILLHOOK_HOME` or `~/.skillhook`), `--json` (machine-readable output for every command), `--help` (on any command or subcommand, or `skillhook help `: prints its usage and runs nothing), `--version`. Exit codes: 0 success, 1 failure, 2 usage error. Environment: `SKILLHOOK_HOME`, `SKILLHOOK_NO_UPDATE_CHECK=1` (or `CI`) to turn off the hourly update check and automatic updates, `SKILLHOOK_NPM_REGISTRY` for a mirror, `SKILLHOOK_DEBUG=1` for stack traces. HTTP API: [docs/api.md](docs/api.md). Service, logs, jobs, config and troubleshooting: [docs/operations.md](docs/operations.md). diff --git a/docs/api.md b/docs/api.md index b857822..ff880ee 100644 --- a/docs/api.md +++ b/docs/api.md @@ -27,6 +27,7 @@ Related: [security.md](security.md) (authentication), [skills.md](skills.md) (fi | `GET` | `/stats` | admin | Numbers over jobs and deliveries: by status, outcome, runner, failure kind; durations, cost, tokens; per skill (`?since=24h`, `?until=`, `?skill=`). | | `GET`, `PATCH` | `/config` | admin | The live `skillhook.json` (defaults applied) with what applies live and what needs a restart; change keys in one validated write. | | `POST` | `/config/reload` | admin | Re-read `skillhook.json` (after editing it by hand). | +| `POST` | `/schedules//pause`, `/schedules//resume` | admin | Pause a schedule (body `{reason?, until?, by?}`) or resume it; answers `{ok, schedule}`. `404` for an unknown skill, `409` for one without a schedule, `400` for an `until` that is not a future instant ([schedules.md](schedules.md#pausing-a-schedule)). | | `POST` | `/control/restart` | admin | Pause dispatch, exit only if active jobs finish within the bound; otherwise resume dispatch. `409` when not run as the service. | | `GET` | `/service` | admin | The launchd / systemd service status. | | `GET` | `/logs` | admin | The last lines of the service log (`?lines=200`). | diff --git a/docs/cloud-protocol.md b/docs/cloud-protocol.md index e9c1b64..811d34a 100644 --- a/docs/cloud-protocol.md +++ b/docs/cloud-protocol.md @@ -49,6 +49,7 @@ Errors are `SyncError` `{ok: false, error, message?, retry_after_ms?, min_protoc ## Command results worth knowing +- `schedule.pause`, `schedule.resume`: `{schedule}`, the schedule's status as `schedules.list` gives it, with `paused: {at, by?, reason?, until?}` or `null`. Machines before 0.16.0 do not know these types, and a machine refuses a whole sync response that carries a command type it does not know, so the cloud must send them only to machines that report 0.16.0 or later. - `skill.run`, `skill.test`, `delivery.replay`, `job.replay`, `schedule.run`: `{accepted: true, job_id, …}` (a replay whose filters do not match: `{accepted: false, skipped: true, reason}`); the job itself is followed through its events. - `job.answer`: `{job_id, delivered: live|resumed|recorded, answer, resume_job_id}`. - `config.patch`: `{applied, restart_required_keys, pending_restart}`. diff --git a/docs/cloud.md b/docs/cloud.md index dd493aa..4f1ea02 100644 --- a/docs/cloud.md +++ b/docs/cloud.md @@ -263,7 +263,7 @@ A skill can have a hosted webhook URL on the cloud (the dashboard creates it) in Read commands (both modes): `ping`, `health.get`, `snapshot.get`, `runners.get`, `accounts.get` (`{account?, refresh?, usage?}`, [what it answers](#accounts)), `skills.list`, `skill.get`, `delivery.list`, `delivery.get`, `job.list`, `job.get`, `job.artifact`, `job.watch`, `job.unwatch`, `job.progress.get`, `stats.get`, `config.get`, `secret.list` (names only), `service.status`, `logs.tail`, `schedules.list`, `update.check`, `expose.status`. -Control commands (`mode: control` or an allow entry): `skill.put`, `skill.delete`, `skill.run`, `skill.test`, `delivery.replay`, `job.cancel`, `job.replay`, `job.answer`, `config.patch`, `secret.generate`, `service.restart`, `schedule.run`, `update.install`. +Control commands (`mode: control` or an allow entry): `skill.put`, `skill.delete`, `skill.run`, `skill.test`, `delivery.replay`, `job.cancel`, `job.replay`, `job.answer`, `config.patch`, `secret.generate`, `service.restart`, `schedule.run`, `schedule.pause`, `schedule.resume`, `update.install`. Results are scrubbed like events. Each command runs once: its id is remembered in `jobs/.cloud/commands.json`, and a command the cloud sends again is answered from the kept result. @@ -283,6 +283,7 @@ What each control command does, and the rules it adds on top of the policy: | `config.patch` | Changes `skillhook.json` like `PATCH /config`, except for `host`, `port`, `trust_proxy`, `runners`, `env_passthrough`, `projects`, `project_refresh` and `cloud`, which the cloud may never change. | | `service.restart` | Restarts a server run by launchd / systemd once the cloud has the answer (`when: idle` pauses dispatch and lets running jobs finish up to `wait_seconds`, then resumes dispatch if jobs remain; `now` terminates them without waiting. Through version 0.10.4, even `idle` terminates jobs when the wait expires). | | `schedule.run` | Fires a scheduled skill now. | +| `schedule.pause`, `schedule.resume` | Pauses a skill's or hook's `schedule:` (`{name, reason?, until?}`) or resumes it (`{name}`), like `skillhook schedules pause` / `resume`: nothing fires while paused, the webhook keeps working, missed slots are not caught up, and the pause survives repository pulls and restarts ([schedules.md](schedules.md#pausing-a-schedule)). `by` is the requester's name. The next sync carries a snapshot with the schedule's `paused`. | | `update.install` | Installs a newer skillhook with the package manager that installed it; the server keeps running the old version until `service.restart`. | | `secret.generate` | Generates a skill's secret (or any `ENV_NAME`) and returns it only sealed to the requester's key (`recipient_key`, required); the value never travels or rests in the clear. The machine's own credentials (`SKILLHOOK_CLOUD_*`, `SKILLHOOK_ADMIN_TOKEN`) are refused, by whatever name they are asked for (`admin`, a skill's, the variable's). | | `skill.put` | Writes `skills//SKILL.md` after validating it. Never for a name that comes from a linked repository; `auth: none` needs `allow_unauthenticated`. No secret is created: `secret.generate` does that, sealed. | diff --git a/docs/schedules.md b/docs/schedules.md index 675f83b..441ee12 100644 --- a/docs/schedules.md +++ b/docs/schedules.md @@ -100,7 +100,20 @@ skillhook schedules run weekday-digest --wait 60 # fire it now with a schedul skillhook run weekday-digest --payload '{"scheduled_for":"2026-09-24T13:05:00Z"}' --dry-run # the prompt and command a scheduled run would get ``` -`skillhook skills list` shows `(schedule )` in the URL column for schedule-only hooks, `skillhook skills show ` prints the schedule and its next run, `GET /skills` carries `schedule: {cron, timezone, catch_up, overlap, next_run_at}` and `webhook`, and `GET /health` (admin) lists every schedule with `next_due`, `last_slot`, `last_fired_at`, `last_job`, `last_status` and `skipped`. The MCP tool is `list_schedules`. +## Pausing a schedule + +The schedule is declared in the skill or the repository's `skillhook.yaml`, which stays its source of truth. To stop it firing for a while without a commit (it misbehaves, a migration runs, a service it calls is down), pause it on the machine: + +```bash +skillhook schedules pause availability-sweep --reason "duplicate emails" --until 2h # or --until 2026-11-12T09:00:00Z; without --until, until resumed +skillhook schedules resume availability-sweep +``` + +A paused schedule fires nothing; its webhook, if it has one, keeps working, and `skillhook run` / `schedules run` still run it by hand. Slots that pass while it is paused are counted in `skipped` but are never caught up, whatever `catch_up` says: on resume (or when `until` passes) it fires from its next slot. The pause is kept in `jobs/.schedules.json`, not in the skill's file, so a repository pull, a change to the hook and a restart all leave it in place; removing the pause is always an explicit resume or the end of `until`. With a server running the command goes through it (`POST /schedules//pause` and `/resume`, admin); without one it writes the state file, and the server honours it when it starts. + +Skillhook Cloud pauses and resumes the same way, with the `schedule.pause` / `schedule.resume` commands ([cloud.md](cloud.md#commands-the-cloud-may-send)); the pause records who asked. + +`skillhook skills list` shows `(schedule )` in the URL column for schedule-only hooks, `skillhook skills show ` prints the schedule and its next run, `GET /skills` carries `schedule: {cron, timezone, catch_up, overlap, next_run_at}` and `webhook`, and `GET /health` (admin) lists every schedule with `next_due`, `last_slot`, `last_fired_at`, `last_job`, `last_status`, `skipped` and `paused` (`{at, by?, reason?, until?}` or `null`; `next_due` is `null` while paused until resumed). The MCP tool is `list_schedules`. `skillhook doctor` adds a `schedules` line (every schedule with its next run) and, on macOS, a `sleep` line that warns when `pmset` reports a sleep timer. diff --git a/package.json b/package.json index d0614b0..65e904d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@meterapp/skillhook", - "version": "0.15.2", + "version": "0.16.0", "mcpName": "dev.skillhook/skillhook", "description": "Make your Agent Skills reactive. A permanent, secure webhook endpoint on your own machine that runs SKILL.md files with Claude Code or Codex the moment something happens, plus version-controlled schedules for the work that has no trigger. Webhook in, agent out.", "license": "MIT", diff --git a/plugins/skillhook/.claude-plugin/plugin.json b/plugins/skillhook/.claude-plugin/plugin.json index 581d9c8..c9247b2 100644 --- a/plugins/skillhook/.claude-plugin/plugin.json +++ b/plugins/skillhook/.claude-plugin/plugin.json @@ -2,7 +2,7 @@ "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json", "name": "skillhook", "displayName": "skillhook", - "version": "0.15.2", + "version": "0.16.0", "description": "Turn this machine into a permanent, secure webhook endpoint that runs Agent Skills with Claude Code or Codex, and run your whole Skillhook Cloud organisation from the agent. Three skills teach the agent to install and expose skillhook, to write good webhook skills and to operate the fleet; two MCP servers manage this machine (skills, secrets, jobs, exposure) and, with an organisation API key, every machine as the Skillhook Cloud dashboard does (what needs a person, failures, stats, answers, replays, runs, hosted URLs).", "author": { "name": "Meter", diff --git a/plugins/skillhook/.codex-plugin/plugin.json b/plugins/skillhook/.codex-plugin/plugin.json index 01a063e..98102c2 100644 --- a/plugins/skillhook/.codex-plugin/plugin.json +++ b/plugins/skillhook/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "skillhook", - "version": "0.15.2", + "version": "0.16.0", "description": "Turn this machine into a permanent, secure webhook endpoint that runs Agent Skills with Claude Code or Codex, and run your whole Skillhook Cloud organisation from the agent. Three skills teach the agent to install and expose skillhook, to write good webhook skills and to operate the fleet; two MCP servers manage this machine (skills, secrets, jobs, exposure) and, with an organisation API key, every machine as the Skillhook Cloud dashboard does (what needs a person, failures, stats, answers, replays, runs, hosted URLs).", "author": { "name": "Meter", diff --git a/plugins/skillhook/.cursor-plugin/plugin.json b/plugins/skillhook/.cursor-plugin/plugin.json index 1cdb208..510db5e 100644 --- a/plugins/skillhook/.cursor-plugin/plugin.json +++ b/plugins/skillhook/.cursor-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "skillhook", - "version": "0.15.2", + "version": "0.16.0", "description": "Turn this machine into a permanent, secure webhook endpoint that runs Agent Skills with Claude Code or Codex, and run your whole Skillhook Cloud organisation from the agent. Three skills teach the agent to install and expose skillhook, to write good webhook skills and to operate the fleet; two MCP servers manage this machine (skills, secrets, jobs, exposure) and, with an organisation API key, every machine as the Skillhook Cloud dashboard does (what needs a person, failures, stats, answers, replays, runs, hosted URLs).", "author": { "name": "Meter", diff --git a/plugins/skillhook/.mcp.json b/plugins/skillhook/.mcp.json index c9c3781..ba85e18 100644 --- a/plugins/skillhook/.mcp.json +++ b/plugins/skillhook/.mcp.json @@ -2,11 +2,11 @@ "mcpServers": { "skillhook": { "command": "npx", - "args": ["-y", "@meterapp/skillhook@0.15.2", "mcp"] + "args": ["-y", "@meterapp/skillhook@0.16.0", "mcp"] }, "skillhook-cloud": { "command": "npx", - "args": ["-y", "@meterapp/skillhook@0.15.2", "mcp", "--cloud"] + "args": ["-y", "@meterapp/skillhook@0.16.0", "mcp", "--cloud"] } } } diff --git a/plugins/skillhook/skills/skillhook-setup/SKILL.md b/plugins/skillhook/skills/skillhook-setup/SKILL.md index 77ec30c..543ee55 100644 --- a/plugins/skillhook/skills/skillhook-setup/SKILL.md +++ b/plugins/skillhook/skills/skillhook-setup/SKILL.md @@ -115,7 +115,7 @@ skillhook secret set GITHUB_WEBHOOK_SECRET # the file names secrets; values st Hooks are live without a restart, `git pull` deploys changes, and `skillhook unlink ` stops serving them. Names in `~/.skillhook/skills` win over repositories; a duplicate is reported by `skillhook skills list` and `doctor`. MCP: `link_project` (`init: true` to scaffold), `list_projects`, `unlink_project`. Writing the file itself is covered by skillhook-authoring. -Hooks with a `schedule:` (cron + time zone) fire from the running server without a webhook; `skillhook schedules list` shows the next and last run of each, `skillhook schedules run ` fires one now. They need the server running and the machine awake (`doctor` checks both). A server older than the version that added schedules rejects a `skillhook.yaml` that uses them, so `skillhook update --install` every linked machine before merging one. +Hooks with a `schedule:` (cron + time zone) fire from the running server without a webhook; `skillhook schedules list` shows the next and last run of each, `skillhook schedules run ` fires one now, `skillhook schedules pause [--until 2h]` / `resume ` stop and restart one without touching the repository (Skillhook Cloud can do the same). They need the server running and the machine awake (`doctor` checks both). A server older than the version that added schedules rejects a `skillhook.yaml` that uses them, so `skillhook update --install` every linked machine before merging one. ## 10. Pair with Skillhook Cloud (optional) diff --git a/src/cli.test.ts b/src/cli.test.ts index 224a906..083b8f8 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -516,6 +516,19 @@ describe("cli", () => { const checks = doctor.json().checks as { name: string; status: string; detail: string }[]; expect(checks.find((c) => c.name === "skill tick")).toMatchObject({ status: "ok", detail: expect.stringContaining("schedule only") }); expect(checks.find((c) => c.name === "schedules")).toMatchObject({ status: "ok", detail: expect.stringContaining("tick (*/5 * * * *") }); + const pause = io(); + expect(await main(["schedules", "pause", "tick", ...dir, "--reason", "too noisy", "--until", "2h", "--json"], pause.cli)).toBe(0); + expect(pause.json()).toMatchObject({ via: "local", schedule: { skill: "tick", paused: { reason: "too noisy", by: "cli", until: expect.stringMatching(/Z$/) } } }); + const pausedList = io(); + expect(await main(["schedules", ...dir], pausedList.cli)).toBe(0); + expect(pausedList.out()).toContain("(paused until"); + const resume = io(); + expect(await main(["schedules", "resume", "tick", ...dir, "--json"], resume.cli)).toBe(0); + expect(resume.json()).toMatchObject({ via: "local", schedule: { paused: null } }); + const pauseNone = io(); + expect(await main(["schedules", "pause", "hello", ...dir, "--json"], pauseNone.cli)).toBe(1); + const badUntil = io(); + expect(await main(["schedules", "pause", "tick", ...dir, "--until", "soonish"], badUntil.cli)).toBe(2); const none = io(); expect(await main(["schedules", "next", "hello", ...dir, "--json"], none.cli)).toBe(1); const usage = io(); @@ -1374,7 +1387,7 @@ describe("cli", () => { link: [[], [unlinked]], unlink: [[linked]], projects: [[], ["list"], ["init", path.join(home.home, "fresh")], ["add", unlinked], ["remove", linked]], - schedules: [[], ["list"], ["next", "tick"], ["run", "tick"]], + schedules: [[], ["list"], ["next", "tick"], ["run", "tick"], ["pause", "tick"], ["resume", "tick"]], }; for (const name of Object.keys(lines)) expect(COMMANDS, name).toHaveProperty(name); diff --git a/src/cloud/control.ts b/src/cloud/control.ts index 0584b16..4ddbf34 100644 --- a/src/cloud/control.ts +++ b/src/cloud/control.ts @@ -18,7 +18,7 @@ import type { JobQueue } from "../queue.js"; import type { SkillRegistry } from "../registry.js"; import { enqueueReplay, planReplay, ReplayError } from "../replay.js"; import type { RunOverrides } from "../run.js"; -import { buildSchedulePayload } from "../scheduler.js"; +import { buildSchedulePayload, ScheduleControlError, type Scheduler } from "../scheduler.js"; import type { ServerControl } from "../server.js"; import { parseSkillDocument, SkillError } from "../skills.js"; import { applyUpdate, type ApplyUpdateResult } from "../update.js"; @@ -45,6 +45,8 @@ export interface ControlDeps { logger: Logger; /** Restart through launchd / systemd (what `POST /control/restart` uses). */ serverControl?: ServerControl; + /** The running scheduler, for `schedule.pause` / `schedule.resume`. */ + scheduler?: Pick; /** Injectable for tests. */ applyUpdate?: (options: { install: boolean }) => Promise; } @@ -166,6 +168,26 @@ export function createControlHandlers(deps: ControlDeps): Partial, command) => { + if (!deps.scheduler) throw new CommandError("unavailable", "this server runs no scheduler"); + try { + return { result: { schedule: deps.scheduler.pause(args.name, { by: requester(command), reason: args.reason, until: args.until }) } }; + } catch (error) { + if (error instanceof ScheduleControlError) throw new CommandError(error.code, error.message); + throw error; + } + }, + + "schedule.resume": (args: Args<{ name: string }>, command) => { + if (!deps.scheduler) throw new CommandError("unavailable", "this server runs no scheduler"); + try { + return { result: { schedule: deps.scheduler.resume(args.name, { by: requester(command) }) } }; + } catch (error) { + if (error instanceof ScheduleControlError) throw new CommandError(error.code, error.message); + throw error; + } + }, + "update.install": async () => { const result = await (deps.applyUpdate ?? ((o: { install: boolean }) => applyUpdate(deps.paths, { install: o.install, restartService: false })))({ install: true }); if (!result.ok) throw new CommandError("unavailable", result.error ?? "the update could not be installed"); diff --git a/src/cloud/link.test.ts b/src/cloud/link.test.ts index 4945847..cbb7df6 100644 --- a/src/cloud/link.test.ts +++ b/src/cloud/link.test.ts @@ -15,6 +15,7 @@ import type { WebhookEvent } from "../payload.js"; import { JobQueue } from "../queue.js"; import type { ReadinessCache } from "../readiness.js"; import { SkillRegistry } from "../registry.js"; +import { readScheduleStates, Scheduler } from "../scheduler.js"; import { createServer } from "../server.js"; import { FakeCloud } from "../test-support/fake-cloud.js"; import { FAKE_CLAUDE, tempHome, writeConfigFile, writeEnv, writeSkill } from "../test-support/helpers.js"; @@ -83,17 +84,19 @@ async function setup(options: SetupOptions = {}) { const restarts: { force: boolean; waitSeconds: number }[] = []; let queue: JobQueue | undefined; let control: ReturnType | undefined; + let scheduler: Scheduler | undefined; if (options.control) { queue = new JobQueue({ store, config, registry, secrets, fileSecrets: secrets, logger: silentLogger, events }); + scheduler = new Scheduler({ registry, store, queue, config, logger: silentLogger }); const configRef = new ConfigRef(paths, config, { events }); - control = createControlHandlers({ paths, config, configRef, secrets, fileSecrets, registry, store, deliveryLog, queue, events, logger: silentLogger, serverControl: { supervised: async () => true, restart: (o) => void restarts.push(o) }, applyUpdate: async ({ install }) => ({ ok: true, current: "0.4.0", latest: "0.4.1", available: true, checked_at: null, registry: "http://registry.invalid", cached: false, install: { method: "npm", command: "npm install -g @meterapp/skillhook@0.4.1" }, release_notes: null, installed: install, service_restarted: false, service_note: null }) }); + control = createControlHandlers({ paths, config, configRef, secrets, fileSecrets, registry, store, deliveryLog, queue, events, logger: silentLogger, scheduler, serverControl: { supervised: async () => true, restart: (o) => void restarts.push(o) }, applyUpdate: async ({ install }) => ({ ok: true, current: "0.4.0", latest: "0.4.1", available: true, checked_at: null, registry: "http://registry.invalid", cached: false, install: { method: "npm", command: "npm install -g @meterapp/skillhook@0.4.1" }, release_notes: null, installed: install, service_restarted: false, service_note: null }) }); const q = queue; cleanups.push(() => q.shutdown()); } const readiness = options.readiness?.(events); - const link = new CloudLink({ paths, config, secrets, fileSecrets, events, logger: silentLogger, registry, store, deliveryLog, serverState: () => undefined, localBaseUrl: options.localBaseUrl ?? (() => undefined), env: options.env ?? {}, fetchImpl: options.fetchImpl, timing: TIMING, control, queueStats: queue ? () => (queue as JobQueue).stats() : undefined, readiness, health: options.health }); + const link = new CloudLink({ paths, config, secrets, fileSecrets, events, logger: silentLogger, registry, store, deliveryLog, serverState: () => undefined, localBaseUrl: options.localBaseUrl ?? (() => undefined), env: options.env ?? {}, fetchImpl: options.fetchImpl, timing: TIMING, control, schedules: scheduler ? () => (scheduler as Scheduler).status() : undefined, queueStats: queue ? () => (queue as JobQueue).stats() : undefined, readiness, health: options.health }); cleanups.push(() => link.stop("test")); - return { fake, paths, config, events, store, deliveryLog, registry, link, secrets, queue, restarts }; + return { fake, paths, config, events, store, deliveryLog, registry, link, secrets, queue, restarts, scheduler }; } async function runCommands(fake: FakeCloud, commands: Command[]): Promise> { @@ -424,6 +427,22 @@ describe("CloudLink", () => { expect(JSON.stringify(fake.requests)).not.toContain(SECRET); }); + it("pauses and resumes a schedule from the cloud, and the next sync's snapshot says so", async () => { + const { fake, link, paths, registry } = await setup({ control: true, cloud: { mode: "control" } }); + writeSkill(paths, "ticker", "description: tick\nskillhook:\n webhook: false\n schedule: \"*/10 * * * *\""); + expect(registry.get("ticker")?.schedule).toBeDefined(); + link.start(); + await waitUntil(() => link.status().state === "connected"); + const paused = await runCommands(fake, [cmd("pause", "schedule.pause", { name: "ticker", reason: "too noisy" }), cmd("pause-plain", "schedule.pause", { name: "hello" }), cmd("pause-past", "schedule.pause", { name: "ticker", until: "2001-01-01T00:00:00.000Z" })]); + expect(paused.pause).toMatchObject({ ok: true, result: { schedule: { skill: "ticker", next_due: null, paused: { by: "ada", reason: "too noisy" } } } }); + expect(paused["pause-plain"]).toMatchObject({ ok: false, error: { code: "conflict" } }); + expect(paused["pause-past"]).toMatchObject({ ok: false, error: { code: "invalid_args" } }); + await fake.waitFor(() => fake.requests.some((r) => r.snapshot?.schedules.some((s) => s.skill === "ticker" && (s as { paused?: { reason?: string } }).paused?.reason === "too noisy"))); + const resumed = await runCommands(fake, [cmd("resume", "schedule.resume", { name: "ticker" })]); + expect(resumed.resume).toMatchObject({ ok: true, result: { schedule: { skill: "ticker", paused: null } } }); + expect(readScheduleStates(paths.jobsDir).ticker?.paused).toBeUndefined(); + }); + it("acts on the machine in control mode: runs, tests, replays, answers, patches config within bounds, restarts after the answer", async () => { const { fake, link, store, paths, config, restarts, registry } = await setup({ control: true, cloud: { mode: "control" } }); link.start(); diff --git a/src/cloud/link.ts b/src/cloud/link.ts index dd74440..f1e7c7a 100644 --- a/src/cloud/link.ts +++ b/src/cloud/link.ts @@ -107,8 +107,8 @@ export interface LinkStatusView extends LinkStatus { events_seq: number; } -/** Commands after which the snapshot differs (skills, whether their secrets are set, the configuration): one goes at once. */ -const RESNAPSHOT: ReadonlySet = new Set(["skill.put", "skill.delete", "config.patch", "secret.generate", "secret.set"]); +/** Commands after which the snapshot differs (skills, whether their secrets are set, the configuration, a paused schedule): one goes at once. */ +const RESNAPSHOT: ReadonlySet = new Set(["skill.put", "skill.delete", "config.patch", "secret.generate", "secret.set", "schedule.pause", "schedule.resume"]); /** Event types that travel; `server.*` stays local. */ const UPLOADED: Set = new Set(["delivery.received", "job.queued", "job.started", "job.updated", "job.finished", "job.cancelled", "job.progress", "job.waiting_human", "job.answered", "schedule.registered", "schedule.fired", "schedule.skipped", "skill.changed", "config.changed", "health.changed", "runners.changed", "account.changed", "account.updated"]); diff --git a/src/cloud/protocol.ts b/src/cloud/protocol.ts index a07331a..ed6f3f7 100644 --- a/src/cloud/protocol.ts +++ b/src/cloud/protocol.ts @@ -122,6 +122,8 @@ export const COMMAND_TYPES = [ "logs.tail", "schedules.list", "schedule.run", + "schedule.pause", + "schedule.resume", "update.check", "update.install", "expose.status", @@ -165,6 +167,8 @@ export const COMMAND_CLASS: Record = { "logs.tail": "read", "schedules.list": "read", "schedule.run": "control", + "schedule.pause": "control", + "schedule.resume": "control", "update.check": "read", "update.install": "control", "expose.status": "read", @@ -213,6 +217,8 @@ export const COMMAND_ARGS = { "logs.tail": z.object({ lines: z.number().int().min(1).max(2000).optional() }).strict(), "schedules.list": z.object({}).strict(), "schedule.run": z.object({ name }).strict(), + "schedule.pause": z.object({ name, reason: z.string().max(500).optional(), until: iso.optional() }).strict(), + "schedule.resume": z.object({ name }).strict(), "update.check": z.object({}).strict(), "update.install": z.object({}).strict(), "expose.status": z.object({}).strict(), diff --git a/src/commands/main.ts b/src/commands/main.ts index 2ce5e16..0a47998 100644 --- a/src/commands/main.ts +++ b/src/commands/main.ts @@ -62,7 +62,7 @@ Running run [--payload JSON|@file|-] [--header "K: v"]... [--runner R] [--model M] [--effort E] [--account A] [--cwd DIR] [--wait S] [--dry-run] run --file SKILL.md | --stdin [same options] Run a SKILL.md that is not installed (kept with the job) send [--payload …] [--wait S] [--url BASE|--public|--local] [--header "K: v"]... POST a signed test webhook - schedules list | next [--count N] | run [--wait S] Skills with a schedule: next and last runs; fire one now + schedules list | next [--count N] | run [--wait S] | pause [--until 2h] | resume Skills with a schedule: next and last runs; fire, pause or resume one jobs list [--skill S] [--account A] [--status ST] [--outcome O] [--failure K] [--trigger T] [--waiting] [--since ISO] [--after ID] [--limit N] | show [--result|--prompt|--stdout|--stderr] | logs [-f] jobs answer [""] [--option X]... [--by NAME] [--no-resume] [--wait S] Answer a job that asked (live) or ended needs_human (resumes the session) jobs cancel | replay [--skip-filters] [--wait S] | resume [--exec] | path | prune [--keep N] diff --git a/src/commands/schedules.ts b/src/commands/schedules.ts index 23c3f25..7dd71d0 100644 --- a/src/commands/schedules.ts +++ b/src/commands/schedules.ts @@ -1,13 +1,15 @@ -import { findRunningServer } from "../client.js"; +import { adminRequest, findRunningServer } from "../client.js"; import { createOps, publicJob, runSkillLocally, triggerViaServer } from "../ops.js"; import { nextRuns } from "../schedule.js"; -import { buildSchedulePayload, listSchedules, type ScheduleStatus } from "../scheduler.js"; -import { CommandError, num, relativeTime, table, UsageError, type Ctx } from "./shared.js"; +import { buildSchedulePayload, listSchedules, ScheduleControlError, setPauseOffline, type ScheduleStatus } from "../scheduler.js"; +import { CommandError, num, relativeTime, str, table, UsageError, type Ctx } from "./shared.js"; export const SCHEDULES_USAGE = `Usage: skillhook schedules list every skill or hook with a schedule: cron, zone, next and last run skillhook schedules next [--count N] the next N occurrences (default 5) - skillhook schedules run [--wait S] fire a scheduled skill now, with the payload a scheduled run gets`; + skillhook schedules run [--wait S] fire a scheduled skill now, with the payload a scheduled run gets + skillhook schedules pause [--reason TEXT] [--until 2h|ISO] stop it firing (webhooks still run) until resumed + skillhook schedules resume fire again from the next slot (paused slots are not caught up)`; export async function schedulesCommand(ctx: Ctx): Promise { const [sub = "list", name] = ctx.args; @@ -20,6 +22,11 @@ export async function schedulesCommand(ctx: Ctx): Promise { case "run": case "fire": return runCommand(ctx, requireName(name)); + case "pause": + return pauseCommand(ctx, requireName(name), true); + case "resume": + case "unpause": + return pauseCommand(ctx, requireName(name), false); default: throw new UsageError(`Unknown schedules subcommand "${sub}"`, SCHEDULES_USAGE); } @@ -44,7 +51,7 @@ async function listCommand(ctx: Ctx): Promise { if (rows.length) { lines.push( table( - rows.map((s) => [s.skill, s.enabled ? s.cron : `(disabled) ${s.cron}`, s.timezone, s.next_due ? `${s.next_due.slice(0, 16).replaceAll("T", " ")}Z` : "never", s.last_fired_at ? relativeTime(s.last_fired_at, now) : "never", s.last_status ?? "", s.catch_up + (s.skipped ? ` (${s.skipped} skipped)` : ""), s.webhook ? "yes" : "no"]), + rows.map((s) => [s.skill, !s.enabled ? `(disabled) ${s.cron}` : s.paused ? `(paused${s.paused.until ? ` until ${s.paused.until.slice(0, 16).replaceAll("T", " ")}Z` : ""}) ${s.cron}` : s.cron, s.timezone, s.next_due ? `${s.next_due.slice(0, 16).replaceAll("T", " ")}Z` : "never", s.last_fired_at ? relativeTime(s.last_fired_at, now) : "never", s.last_status ?? "", s.catch_up + (s.skipped ? ` (${s.skipped} skipped)` : ""), s.webhook ? "yes" : "no"]), ["skill", "cron", "timezone", "next (UTC)", "last run", "status", "catch_up", "webhook"], ), ); @@ -83,3 +90,42 @@ async function runCommand(ctx: Ctx, name: string): Promise { ctx.print(`Ran ${name} in-process: job ${job.id} ${job.status}${job.error ? ` (${job.error})` : ""}${job.result ? `\n\n${job.result}` : ""}`, { via: "local", job: publicJob(job), job_dir: ops.store.pathsFor(job.id).dir }); return job.status === "succeeded" || job.status === "queued" || job.status === "running" ? 0 : 1; } + +/** `--until`: an ISO-8601 instant, or a duration from now (`30m`, `2h`, `1d`, `1w`). */ +export function parseUntil(value: string | undefined, now = new Date()): string | undefined { + if (value === undefined) return undefined; + const match = /^(\d{1,5})([mhdw])$/.exec(value.trim()); + if (match) { + const unit = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[match[2] as "m" | "h" | "d" | "w"]; + return new Date(now.getTime() + Number(match[1]) * unit).toISOString(); + } + const at = Date.parse(value); + if (Number.isNaN(at)) throw new UsageError(`--until must be an ISO-8601 instant or a duration like 2h: "${value}"`, SCHEDULES_USAGE); + return new Date(at).toISOString(); +} + +async function pauseCommand(ctx: Ctx, name: string, pause: boolean): Promise { + const options = pause ? { reason: str(ctx.flags, "reason"), until: parseUntil(str(ctx.flags, "until")), by: "cli" } : { by: "cli" }; + const running = await findRunningServer(ctx.paths); + let schedule: ScheduleStatus; + let via: "server" | "local"; + if (running?.health.schedules) { + const response = await adminRequest<{ ok?: boolean; schedule?: ScheduleStatus; message?: string; error?: string }>(running.baseUrl, ctx.secrets(), `/schedules/${encodeURIComponent(name)}/${pause ? "pause" : "resume"}`, { method: "POST", body: options, timeoutMs: 5_000 }); + if (response.status === 404 && response.body.error === "not_found" && !response.body.message?.includes("no skill")) throw new CommandError("The running server predates schedule pauses; update it (`skillhook update`) or stop it and run this again."); + if (response.status >= 300 || !response.body.schedule) throw new CommandError(response.body.message ?? `the server answered ${response.status}`); + schedule = response.body.schedule; + via = "server"; + } else { + if (running) throw new CommandError("The running server predates the scheduler; restart it (`skillhook service restart`) first."); + try { + schedule = setPauseOffline({ registry: ctx.registry(), jobsDir: ctx.store().jobsDir }, name, pause ? options : null); + } catch (error) { + if (error instanceof ScheduleControlError) throw new CommandError(error.message); + throw error; + } + via = "local"; + } + const text = pause ? `Paused ${name}${schedule.paused?.until ? ` until ${schedule.paused.until}` : " until resumed"}. Webhooks still run; slots that pass are not caught up.` : `Resumed ${name}: next run ${schedule.next_due ?? "never"}.`; + ctx.print(text, { via, schedule }); + return 0; +} diff --git a/src/commands/serve.ts b/src/commands/serve.ts index c10ab62..85577c5 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -95,7 +95,7 @@ async function runDaemon(ctx: Ctx, sentry: DaemonSentry): Promise { }, restart: (options) => void stop("restart", options), }; - const server = createServer({ config, paths: ctx.paths, store, queue, registry, secrets, logger, sentry, events, deliveryLog, health, readiness, configRef, control, cloud: () => link?.status(), schedules: () => scheduler.status() }); + const server = createServer({ config, paths: ctx.paths, store, queue, registry, secrets, logger, sentry, events, deliveryLog, health, readiness, configRef, control, cloud: () => link?.status(), schedules: () => scheduler.status(), scheduleControl: scheduler }); const loaded = registry.list(); for (const error of loaded.errors) logger.error("skill failed to load", { skill: error.name, error: error.error }); @@ -126,7 +126,7 @@ async function runDaemon(ctx: Ctx, sentry: DaemonSentry): Promise { events.emit("server.started", { state }); // The cloud link idles until `skillhook cloud connect` enabled it (docs/cloud.md); it re-reads the config every few seconds. const fileSecrets = () => readEnvFile(ctx.paths.envFile); - const cloudControl = createControlHandlers({ paths: ctx.paths, config, configRef, secrets, fileSecrets, registry, store, deliveryLog, queue, events, logger, serverControl: control }); + const cloudControl = createControlHandlers({ paths: ctx.paths, config, configRef, secrets, fileSecrets, registry, store, deliveryLog, queue, events, logger, serverControl: control, scheduler }); link = new CloudLink({ paths: ctx.paths, config, secrets, fileSecrets, events, logger, registry, store, deliveryLog, schedules: () => scheduler.status(), health, readiness, serverState: () => state, localBaseUrl: () => localBaseUrl({ host, port: boundPort }), env: ctx.io.env, queueStats: () => queue.stats(), runningJobs: () => queue.stats().running_ids, control: cloudControl }); link.start(); for (const job of recovered.interrupted) events.emit("job.finished", { job }); diff --git a/src/scheduler.test.ts b/src/scheduler.test.ts index 2b90e26..1c65349 100644 --- a/src/scheduler.test.ts +++ b/src/scheduler.test.ts @@ -8,7 +8,7 @@ import { JobStore, type JobRecord } from "./jobs.js"; import { silentLogger } from "./logger.js"; import { JobQueue } from "./queue.js"; import { SkillRegistry } from "./registry.js"; -import { buildSchedulePayload, CATCH_UP_MAX_SLOTS, dueSlots, listSchedules, readScheduleStates, Scheduler, scheduleStateFile } from "./scheduler.js"; +import { buildSchedulePayload, CATCH_UP_MAX_SLOTS, dueSlots, listSchedules, readScheduleStates, ScheduleControlError, Scheduler, scheduleStateFile, setPauseOffline } from "./scheduler.js"; import { tempHome, writeConfigFile, writeSkill } from "./test-support/helpers.js"; import { readJsonFileOr, writeJsonFile } from "./util.js"; @@ -46,6 +46,71 @@ describe("dueSlots", () => { }); }); +describe("Scheduler pause", () => { + const MINUTELY = { minutely: `description: m\n${SHELL("echo p")} schedule: "* * * * *"\n`, plain: `description: p\n${SHELL("echo x")}` }; + + it("skips every slot while paused, quietly, and does not catch them up on resume", async () => { + const h = harness(MINUTELY); + const seen: SkillhookEvent[] = []; + h.events.onAny((event) => seen.push(event)); + h.scheduler.start(); + const paused = h.scheduler.pause("minutely", { by: "test", reason: "noisy" }); + expect(paused).toMatchObject({ skill: "minutely", next_due: null, paused: { by: "test", reason: "noisy", at: "2026-09-23T10:00:30.000Z" } }); + expect(readScheduleStates(h.paths.jobsDir).minutely?.paused).toMatchObject({ reason: "noisy" }); + h.setClock("2026-09-23T10:05:05Z"); + expect(h.scheduler.tick()).toEqual({ fired: [], skipped: [] }); + expect(seen.filter((e) => e.type === "schedule.skipped" || e.type === "schedule.fired")).toEqual([]); + expect(h.scheduler.status()[0]).toMatchObject({ skipped: 5, paused: { reason: "noisy" } }); + h.setClock("2026-09-23T10:07:10Z"); + const resumed = h.scheduler.resume("minutely", { by: "test" }); + expect(resumed).toMatchObject({ paused: null, next_due: "2026-09-23T10:08:00.000Z" }); + expect(h.scheduler.tick().fired).toEqual([]); // 10:06 and 10:07 passed while paused + h.setClock("2026-09-23T10:08:02Z"); + const tick = h.scheduler.tick(); + expect(tick.fired).toHaveLength(1); + await h.finished(tick.fired[0] as JobRecord); + return h.close(); + }); + + it("a pause survives a restart, and one with until ends by itself", async () => { + const h = harness(MINUTELY); + h.scheduler.start(); + expect(h.scheduler.pause("minutely", { until: "2026-09-23T10:03:00Z" }).next_due).toBe("2026-09-23T10:03:00.000Z"); + h.scheduler.stop(); + const again = new Scheduler({ registry: h.registry, store: h.store, queue: h.queue, config: h.config, logger: silentLogger, now: () => at("2026-09-23T10:02:10Z") }); + expect(again.tick().fired).toEqual([]); + expect(again.status()[0]?.paused).toMatchObject({ until: "2026-09-23T10:03:00.000Z" }); + const ended = again.tick(at("2026-09-23T10:03:05Z")); + expect(ended.fired).toEqual([]); // the pause is cleared on this tick… + expect(again.status(at("2026-09-23T10:03:05Z"))[0]?.paused).toBeNull(); + const next = again.tick(at("2026-09-23T10:03:20Z")); // …and the 10:03 slot, the pause's end, fires + expect(next.fired).toHaveLength(1); + await h.finished(next.fired[0] as JobRecord); + return h.close(); + }); + + it("refuses unknown skills, skills without a schedule and an until in the past", async () => { + const h = harness(MINUTELY); + expect(() => h.scheduler.pause("nope")).toThrow(ScheduleControlError); + expect(() => h.scheduler.pause("plain")).toThrow(/has no schedule/); + expect(() => h.scheduler.pause("minutely", { until: "2026-09-23T09:00:00Z" })).toThrow(/future/); + expect(() => h.scheduler.pause("minutely", { until: "soon" })).toThrow(/ISO-8601/); + expect(() => h.scheduler.resume("plain")).toThrow(/has no schedule/); + return h.close(); + }); + + it("setPauseOffline writes the state a server then honours", async () => { + const h = harness(MINUTELY); + expect(setPauseOffline({ registry: h.registry, jobsDir: h.paths.jobsDir }, "minutely", { reason: "offline" }, at("2026-09-23T10:00:00Z")).paused).toMatchObject({ reason: "offline" }); + expect(listSchedules({ registry: h.registry, jobsDir: h.paths.jobsDir }, at("2026-09-23T10:00:00Z"))[0]).toMatchObject({ paused: { reason: "offline" }, next_due: null }); + const server = new Scheduler({ registry: h.registry, store: h.store, queue: h.queue, config: h.config, logger: silentLogger, now: () => at("2026-09-23T10:00:30Z") }); + server.tick(); // registers the schedule + expect(server.tick(at("2026-09-23T10:04:05Z")).fired).toEqual([]); + expect(setPauseOffline({ registry: h.registry, jobsDir: h.paths.jobsDir }, "minutely", null).paused).toBeNull(); + return h.close(); + }); +}); + describe("Scheduler", () => { it("publishes schedule.registered, schedule.fired and schedule.skipped on the event bus", async () => { const h = harness({ minutely: `description: m\n${SHELL("echo ev")} schedule: "* * * * *"\n` }); diff --git a/src/scheduler.ts b/src/scheduler.ts index b42a761..3d21c2e 100644 --- a/src/scheduler.ts +++ b/src/scheduler.ts @@ -30,8 +30,17 @@ export interface ScheduleState { last_fired_at?: string; last_job?: string; last_status?: JobStatus; - /** Slots that were due but not run (still in flight, caught up, too old, or already fired by an earlier process). */ + /** Slots that were due but not run (still in flight, caught up, too old, paused, or already fired by an earlier process). */ skipped?: number; + /** Set while the schedule is paused (`skillhook schedules pause`, `POST /schedules//pause`, the cloud's `schedule.pause`). Lives here, not in the skill's file, so a repository pull or a restart keeps it. */ + paused?: SchedulePause; +} +/** Who paused a schedule, why, and until when (absent: until someone resumes it). */ +export interface SchedulePause { + at: string; + by?: string; + reason?: string; + until?: string; } export type ScheduleStates = Record; @@ -49,6 +58,8 @@ export interface ScheduleStatus { last_job: string | null; last_status: JobStatus | null; skipped: number; + /** Set while the schedule is paused; its slots pass without a job and are not caught up on resume. */ + paused: SchedulePause | null; } export type SkipReason = "in_flight" | "caught_up" | "too_old" | "duplicate"; @@ -82,10 +93,20 @@ export function buildSchedulePayload(skill: Skill, slot: Date, options: { firedA }; } +/** The pause in force at `now`: none once its `until` has passed. */ +export function activePause(state: ScheduleState | undefined, now = new Date()): SchedulePause | undefined { + const paused = state?.paused; + if (!paused) return undefined; + if (paused.until && Date.parse(paused.until) <= now.getTime()) return undefined; + return paused; +} + export function scheduleStatus(skill: Skill, state: ScheduleState | undefined, now = new Date()): ScheduleStatus | undefined { const schedule = skill.schedule; if (!schedule) return undefined; - const next = skill.enabled ? nextRun(schedule.spec, now, schedule.timezone) : undefined; + const paused = activePause(state, now); + const from = paused?.until ? new Date(Math.max(now.getTime(), Date.parse(paused.until) - 1)) : now; + const next = skill.enabled && !(paused && !paused.until) ? nextRun(schedule.spec, from, schedule.timezone) : undefined; return { skill: skill.name, cron: schedule.cron, @@ -100,9 +121,61 @@ export function scheduleStatus(skill: Skill, state: ScheduleState | undefined, n last_job: state?.last_job ?? null, last_status: state?.last_status ?? null, skipped: state?.skipped ?? 0, + paused: paused ?? null, }; } +/** Thrown by `pause` / `resume` for a skill that does not exist or has no schedule. */ +export class ScheduleControlError extends Error { + constructor( + readonly code: "not_found" | "conflict" | "invalid_args", + message: string, + ) { + super(message); + } +} + +export interface PauseOptions { + by?: string; + reason?: string; + /** An ISO-8601 instant in the future; absent pauses until someone resumes. */ + until?: string; +} + +/** Validates a pause request against the registry and builds the record; shared by the server and the offline CLI. */ +export function buildPause(registry: SkillRegistry, name: string, options: PauseOptions, now = new Date()): SchedulePause { + requireScheduled(registry, name); + let until: string | undefined; + if (options.until !== undefined) { + const at = Date.parse(options.until); + if (Number.isNaN(at)) throw new ScheduleControlError("invalid_args", "until must be an ISO-8601 instant"); + if (at <= now.getTime()) throw new ScheduleControlError("invalid_args", "until must be in the future"); + until = new Date(at).toISOString(); + } + return { at: now.toISOString(), ...(options.by ? { by: options.by.slice(0, 200) } : {}), ...(options.reason ? { reason: options.reason.slice(0, 500) } : {}), ...(until ? { until } : {}) }; +} + +function requireScheduled(registry: SkillRegistry, name: string): Skill { + const skill = registry.get(name); + if (!skill) throw new ScheduleControlError("not_found", `no skill named "${name}"`); + if (!skill.schedule) throw new ScheduleControlError("conflict", `skill "${name}" has no schedule`); + return skill; +} + +/** + * Pause or resume with no server running: the state file is written directly (a running server owns it in memory, so + * the CLI goes through `POST /schedules//pause` instead). Returns the schedule's new status. + */ +export function setPauseOffline(input: { registry: SkillRegistry; jobsDir: string }, name: string, pause: PauseOptions | null, now = new Date()): ScheduleStatus { + const skill = requireScheduled(input.registry, name); + const states = readScheduleStates(input.jobsDir); + const state = (states[name] ??= {}); + if (pause) state.paused = buildPause(input.registry, name, pause, now); + else delete state.paused; + writeJsonFile(scheduleStateFile(input.jobsDir), states); + return scheduleStatus(skill, state, now) as ScheduleStatus; +} + /** Every scheduled skill with its persisted state: what `skillhook schedules list` and the MCP tool show when no server is running. */ export function listSchedules(input: { registry: SkillRegistry; jobsDir: string }, now = new Date()): ScheduleStatus[] { const states = readScheduleStates(input.jobsDir); @@ -213,6 +286,28 @@ export class Scheduler { return out; } + /** Stops the schedule from firing (webhooks still run) until `resume`, or until `options.until`. Slots that pass while paused are not caught up. */ + pause(name: string, options: PauseOptions = {}, now = this.now()): ScheduleStatus { + const pause = buildPause(this.deps.registry, name, options, now); + const state = (this.states[name] ??= {}); + state.paused = pause; + this.save(); + this.deps.logger.warn("schedule paused", { skill: name, by: pause.by, reason: pause.reason, until: pause.until }); + return scheduleStatus(this.deps.registry.get(name) as Skill, state, now) as ScheduleStatus; + } + + resume(name: string, options: { by?: string } = {}, now = this.now()): ScheduleStatus { + const skill = requireScheduled(this.deps.registry, name); + const state = (this.states[name] ??= {}); + const was = state.paused; + delete state.paused; + // The slots that passed while paused are gone: the schedule picks up at its next slot. + if (was) state.last_slot = now.toISOString(); + this.save(); + this.deps.logger.info("schedule resumed", { skill: name, by: options.by, was_paused: Boolean(was) }); + return scheduleStatus(skill, state, now) as ScheduleStatus; + } + /** One pass over every schedule. Exported for tests; the server calls it on its timer. */ tick(now = this.now()): TickResult { const result: TickResult = { fired: [], skipped: [] }; @@ -239,9 +334,24 @@ export class Scheduler { dirty = true; continue; } + if (state.paused && !activePause(state, now)) { + // The pause ran out: slots up to its end were paused, the schedule fires from the next one. + const until = state.paused.until as string; + delete state.paused; + if (Date.parse(until) > lastSlot.getTime()) state.last_slot = new Date(Date.parse(until) - 1).toISOString(); + dirty = true; + this.deps.logger.info("schedule pause ended", { skill: skill.name, until }); + continue; + } const due = dueSlots(schedule, lastSlot, now); // newest first if (!due.length) continue; dirty = true; + if (state.paused) { + // Paused slots pass quietly: no job, no event per slot (a week of a 10-minute schedule would be a thousand). + state.skipped = (state.skipped ?? 0) + due.length; + state.last_slot = (due[0] as Date).toISOString(); + continue; + } const latest = due[0] as Date; let toFire: Date[]; if (schedule.catch_up === "all") toFire = due.slice(0, CATCH_UP_MAX_SLOTS).reverse(); diff --git a/src/server.test.ts b/src/server.test.ts index 8fad42a..bece4fc 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -153,6 +153,7 @@ beforeAll(async () => { serviceLog: (lines) => `${["one", "two", "three"].slice(-lines).join("\n")}\n`, applyUpdate: async ({ install }) => ({ ok: true, current: "0.3.0", latest: "0.3.0", available: false, checked_at: "2026-09-28T00:00:00.000Z", registry: "http://registry.invalid", cached: false, install: { method: "npm", command: "npm install -g @meterapp/skillhook@latest" }, release_notes: null, installed: install, service_restarted: false, service_note: null }), schedules: () => scheduler.status(), + scheduleControl: scheduler, }); await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); const address = server.address(); @@ -1015,6 +1016,21 @@ describe("HTTP surface", () => { expect((await fetch(`${base}/config`, { method: "DELETE", headers: auth })).status).toBe(405); }); + it("pauses and resumes a schedule through the admin API", async () => { + const auth = { authorization: `Bearer ${ADMIN}`, "content-type": "application/json" }; + const paused = await json(await fetch(`${base}/schedules/nightly/pause`, { method: "POST", headers: auth, body: JSON.stringify({ reason: "migration", until: "2026-09-24T00:00:00Z" }) })); + expect(paused).toMatchObject({ ok: true, schedule: { skill: "nightly", paused: { reason: "migration", by: "admin API", until: "2026-09-24T00:00:00.000Z" }, next_due: "2026-09-24T03:00:00.000Z" } }); + const health = await json(await fetch(`${base}/health`, { headers: auth })); + expect((health.schedules as { skill: string; paused: unknown }[]).find((s) => s.skill === "nightly")?.paused).toMatchObject({ reason: "migration" }); + expect((await fetch(`${base}/schedules/hello/pause`, { method: "POST", headers: auth })).status).toBe(409); + expect((await fetch(`${base}/schedules/nope/pause`, { method: "POST", headers: auth })).status).toBe(404); + expect((await fetch(`${base}/schedules/nightly/pause`, { method: "POST", headers: auth, body: JSON.stringify({ until: "yesterday" }) })).status).toBe(400); + expect((await fetch(`${base}/schedules/nightly/pause`, { method: "GET", headers: auth })).status).toBe(405); + expect((await fetch(`${base}/schedules/nightly/pause`, { method: "POST", headers: { "x-forwarded-for": "203.0.113.1" } })).status).toBe(401); + const resumed = await json(await fetch(`${base}/schedules/nightly/resume`, { method: "POST", headers: auth })); + expect(resumed).toMatchObject({ ok: true, schedule: { skill: "nightly", paused: null } }); + }); + it("restarts only when supervised, and serves the service status, its log and the update check", async () => { const auth = { authorization: `Bearer ${ADMIN}` }; const jsonHeaders = { ...auth, "content-type": "application/json" }; diff --git a/src/server.ts b/src/server.ts index de92361..ed48cf3 100644 --- a/src/server.ts +++ b/src/server.ts @@ -33,7 +33,7 @@ import { resolveRunSettings } from "./run.js"; import { RunnerNameSchema } from "./config.js"; import type { SkillRegistry } from "./registry.js"; import { nextRun } from "./schedule.js"; -import type { ScheduleStatus } from "./scheduler.js"; +import { ScheduleControlError, type Scheduler, type ScheduleStatus } from "./scheduler.js"; import { describeAuth, SkillError, type Skill } from "./skills.js"; import { errorMessage, getPath, isPlainObject, isValidSkillName, nowIso, writeJsonFile } from "./util.js"; import { VERSION } from "./version.js"; @@ -53,6 +53,8 @@ export interface ServerDeps { sentry?: Pick; /** Live schedule state for `/health` (admin); absent when the server runs without a scheduler. */ schedules?: () => ScheduleStatus[]; + /** `POST /schedules//pause` and `/resume` (the running scheduler; absent means 404). */ + scheduleControl?: Pick; /** The cached health report behind `GET /health/checks` and `GET /doctor` (built by `serve`; absent means 404). */ health?: HealthCache; /** Runner readiness behind `GET /runners` (the queue's pre-flight shares it). */ @@ -769,6 +771,28 @@ export function createServer(deps: ServerDeps): Server { } throw new HttpError(405, "method_not_allowed", "use GET, PATCH or POST /config/reload"); } + if (segments[0] === "schedules" && segments.length === 3 && (segments[2] === "pause" || segments[2] === "resume")) { + requireAdmin(headers, req, viaProxy, ip); + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "use POST"); + if (!deps.scheduleControl) throw new HttpError(404, "not_found", "this server runs no scheduler"); + const rawBody = await readBody(req, config.max_body_bytes); + const body = rawBody.length ? (parseBody(headers["content-type"], rawBody).payload as Record) : {}; + if (!isPlainObject(body)) throw new HttpError(400, "bad_request", "expected a JSON object body"); + const str = (key: string): string | undefined => { + const value = body[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") throw new HttpError(400, "bad_request", `${key} must be a string`); + return value; + }; + const name = segments[1] as string; + try { + const schedule = segments[2] === "pause" ? deps.scheduleControl.pause(name, { by: str("by") ?? "admin API", reason: str("reason"), until: str("until") }) : deps.scheduleControl.resume(name, { by: str("by") ?? "admin API" }); + return send(res, 200, { ok: true, schedule }); + } catch (error) { + if (error instanceof ScheduleControlError) throw new HttpError(error.code === "not_found" ? 404 : error.code === "conflict" ? 409 : 400, error.code === "invalid_args" ? "bad_request" : error.code, error.message); + throw error; + } + } if (segments[0] === "control" && segments.length === 2 && segments[1] === "restart") { requireAdmin(headers, req, viaProxy, ip); if (method !== "POST") throw new HttpError(405, "method_not_allowed", "use POST"); From f6a2ca0db497f232296e1fa34546949f2f027420 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Tue, 10 Nov 2026 13:56:57 -0500 Subject: [PATCH 2/3] Name 0.17.0 as the version that knows schedule.pause/resume Co-Authored-By: Claude Opus 5.5 --- docs/cloud-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cloud-protocol.md b/docs/cloud-protocol.md index 811d34a..d4d18fd 100644 --- a/docs/cloud-protocol.md +++ b/docs/cloud-protocol.md @@ -49,7 +49,7 @@ Errors are `SyncError` `{ok: false, error, message?, retry_after_ms?, min_protoc ## Command results worth knowing -- `schedule.pause`, `schedule.resume`: `{schedule}`, the schedule's status as `schedules.list` gives it, with `paused: {at, by?, reason?, until?}` or `null`. Machines before 0.16.0 do not know these types, and a machine refuses a whole sync response that carries a command type it does not know, so the cloud must send them only to machines that report 0.16.0 or later. +- `schedule.pause`, `schedule.resume`: `{schedule}`, the schedule's status as `schedules.list` gives it, with `paused: {at, by?, reason?, until?}` or `null`. Machines before 0.17.0 do not know these types, and a machine refuses a whole sync response that carries a command type it does not know, so the cloud must send them only to machines that report 0.17.0 or later. - `skill.run`, `skill.test`, `delivery.replay`, `job.replay`, `schedule.run`: `{accepted: true, job_id, …}` (a replay whose filters do not match: `{accepted: false, skipped: true, reason}`); the job itself is followed through its events. - `job.answer`: `{job_id, delivered: live|resumed|recorded, answer, resume_job_id}`. - `config.patch`: `{applied, restart_required_keys, pending_restart}`. From 390f6345dee6479ca3d254edaf6db27d774eeecc Mon Sep 17 00:00:00 2001 From: Jonathan Date: Wed, 11 Nov 2026 15:20:17 -0500 Subject: [PATCH 3/3] Schedule state takes only skill names as keys (CodeQL prototype-polluting assignment) Co-Authored-By: Claude Opus 5.5 --- src/scheduler.test.ts | 6 ++++++ src/scheduler.ts | 23 ++++++++++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/scheduler.test.ts b/src/scheduler.test.ts index 1c65349..e1dc323 100644 --- a/src/scheduler.test.ts +++ b/src/scheduler.test.ts @@ -96,6 +96,12 @@ describe("Scheduler pause", () => { expect(() => h.scheduler.pause("minutely", { until: "2026-09-23T09:00:00Z" })).toThrow(/future/); expect(() => h.scheduler.pause("minutely", { until: "soon" })).toThrow(/ISO-8601/); expect(() => h.scheduler.resume("plain")).toThrow(/has no schedule/); + // A name is a skill name or nothing: no key reaches Object.prototype. + for (const name of ["__proto__", "constructor", "prototype"]) { + expect(() => h.scheduler.pause(name)).toThrow(ScheduleControlError); + expect(() => setPauseOffline({ registry: h.registry, jobsDir: h.paths.jobsDir }, name, {})).toThrow(ScheduleControlError); + } + expect(({} as Record).paused).toBeUndefined(); return h.close(); }); diff --git a/src/scheduler.ts b/src/scheduler.ts index 3d21c2e..df76198 100644 --- a/src/scheduler.ts +++ b/src/scheduler.ts @@ -13,7 +13,7 @@ import type { JobQueue } from "./queue.js"; import type { SkillRegistry } from "./registry.js"; import { nextRun, previousRun, slotKey } from "./schedule.js"; import type { NormalizedSchedule, Skill } from "./skills.js"; -import { errorMessage, isPlainObject, readJsonFileOr, writeJsonFile } from "./util.js"; +import { errorMessage, isPlainObject, isValidSkillName, readJsonFileOr, writeJsonFile } from "./util.js"; /** How often the scheduler compares the wall clock with the next due slot. */ export const SCHEDULER_TICK_MS = 15_000; @@ -75,9 +75,10 @@ export function scheduleStateFile(jobsDir: string): string { export function readScheduleStates(jobsDir: string): ScheduleStates { const raw = readJsonFileOr(scheduleStateFile(jobsDir), {}); - if (!isPlainObject(raw)) return {}; - const states: ScheduleStates = {}; - for (const [name, value] of Object.entries(raw)) if (isPlainObject(value)) states[name] = value as ScheduleState; + // Keyed by skill name: a null prototype, and only valid names, so no key can reach Object.prototype. + const states: ScheduleStates = Object.create(null) as ScheduleStates; + if (!isPlainObject(raw)) return states; + for (const [name, value] of Object.entries(raw)) if (isValidSkillName(name) && isPlainObject(value)) states[name] = value as ScheduleState; return states; } @@ -155,7 +156,15 @@ export function buildPause(registry: SkillRegistry, name: string, options: Pause return { at: now.toISOString(), ...(options.by ? { by: options.by.slice(0, 200) } : {}), ...(options.reason ? { reason: options.reason.slice(0, 500) } : {}), ...(until ? { until } : {}) }; } +/** The state of one schedule, created when missing; never for a key that is not a skill name (`__proto__`, say). */ +function stateFor(states: ScheduleStates, name: string): ScheduleState { + if (!isValidSkillName(name) || name === "__proto__" || name === "constructor" || name === "prototype") throw new ScheduleControlError("not_found", `no skill named "${name}"`); + if (!Object.hasOwn(states, name)) Object.defineProperty(states, name, { value: {}, enumerable: true, writable: true, configurable: true }); + return states[name] as ScheduleState; +} + function requireScheduled(registry: SkillRegistry, name: string): Skill { + if (!isValidSkillName(name)) throw new ScheduleControlError("not_found", `no skill named "${name}"`); const skill = registry.get(name); if (!skill) throw new ScheduleControlError("not_found", `no skill named "${name}"`); if (!skill.schedule) throw new ScheduleControlError("conflict", `skill "${name}" has no schedule`); @@ -169,7 +178,7 @@ function requireScheduled(registry: SkillRegistry, name: string): Skill { export function setPauseOffline(input: { registry: SkillRegistry; jobsDir: string }, name: string, pause: PauseOptions | null, now = new Date()): ScheduleStatus { const skill = requireScheduled(input.registry, name); const states = readScheduleStates(input.jobsDir); - const state = (states[name] ??= {}); + const state = stateFor(states, name); if (pause) state.paused = buildPause(input.registry, name, pause, now); else delete state.paused; writeJsonFile(scheduleStateFile(input.jobsDir), states); @@ -289,7 +298,7 @@ export class Scheduler { /** Stops the schedule from firing (webhooks still run) until `resume`, or until `options.until`. Slots that pass while paused are not caught up. */ pause(name: string, options: PauseOptions = {}, now = this.now()): ScheduleStatus { const pause = buildPause(this.deps.registry, name, options, now); - const state = (this.states[name] ??= {}); + const state = stateFor(this.states, name); state.paused = pause; this.save(); this.deps.logger.warn("schedule paused", { skill: name, by: pause.by, reason: pause.reason, until: pause.until }); @@ -298,7 +307,7 @@ export class Scheduler { resume(name: string, options: { by?: string } = {}, now = this.now()): ScheduleStatus { const skill = requireScheduled(this.deps.registry, name); - const state = (this.states[name] ??= {}); + const state = stateFor(this.states, name); const was = state.paused; delete state.paused; // The slots that passed while paused are gone: the schedule picks up at its next slot.