Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(host): run routines from a public webhook URL

leepokaic0c965b00cd5
diff --git a/CLAUDE.md b/CLAUDE.md
index eafc898b..b3378309 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -26,7 +26,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- **Chat shows only**: user messages, the *final* agent message of each turn (`data.final`), permission cards, notices. Narration, thoughts, tool calls, plans are trace entries (Full conversation sheet).
- **Sync**: every mutation stamps a global `rev`. Clients call `GET /events?since=<rev>` (catch-up in rev order, then live). Emission happens under `Hub::emit_lock` so events leave in rev order. Clients upsert by id; never skip undecodable events (the iOS app rewinds to rev 0).
- API: `POST /api/<method>` + SSE with the bearer token (`~/.codync/token`) is **loopback only** (Mac app, SSH tunnel, local helpers). Phones and other remote clients use the E2E channel (`/channel` direct, or the Cloudflare relay). Default port **19222**.
-- Remote access (Cloudflare relay primary, direct LAN/Tailscale alternative, accounts, SSH): [docs/reference/remote-relay.md](docs/reference/remote-relay.md).
+- Remote access (Cloudflare relay primary, direct LAN/Tailscale alternative, accounts, SSH, public routine webhooks queued in the relay §7.8): [docs/reference/remote-relay.md](docs/reference/remote-relay.md).
- Remote screen (`host/src/screen.rs` is the reference): phones view/control the computer over WebRTC (hardware H.264, non-trickle SDP relayed by `screenOffer`, input on data channels `input` / `input-fast`); bots get the built-in `computer` MCP server (`codync-host mcp computer`, `host/src/mcp.rs`) when their `computer` flag is on. Capture/input live in a helper on `~/.codync/screen.sock`: `apps/screen-macos` (macOS, launchd agent via `SMAppService`, owns the TCC grants) or `apps/screen-linux` (`codync-screen`: portals + GStreamer, started by the host). Off by default; `setScreenEnabled` is accepted only from loopback. An interactive phone takes over (bots may only look).
- Multiple computers per account are future work, not a current priority: the product targets one computer. The multi-computer structure (`AccountStore`, `BotReference`) stays because relay/accounts/SSH build on it; don't extend or polish multi-computer features unless asked.
- Environments: **dev** (`dev-api.codync.dev`, Clerk development instance, Debug builds) and **main** (`api.codync.dev`, Clerk production, Release builds); `apps/shared/Config/<env>.plist` becomes `AccountConfig.plist`. Details: [spec §14.0](docs/reference/remote-relay.md).
diff --git a/docs/features/routines.md b/docs/features/routines.md
index 1c47b221..7a2a0571 100644
--- a/docs/features/routines.md
+++ b/docs/features/routines.md
@@ -1,25 +1,30 @@
# Routines
-Routines belong to an agent bot and are created by talking to it ("I want a
-routine that…"). Every agent receives the built-in `routines` MCP server. The Mac
+Routines belong to an agent bot and are usually created by talking to it ("I want
+a routine that…"). Every agent receives the built-in `routines` MCP server. The Mac
conversation details panel and the iPhone's **More → Routines** show a compact list
-(name, schedule, on/off switch); **+** puts "I want a routine that " in the chat
-composer. A row opens details: instruction, triggers, pause/resume, edit (form that
-preserves existing triggers by default), edit with bot, delete, test run and run
-history. Linux (boxed list with switches) and the TUI (`n` asks the bot) match.
-Webhook credentials are not shown in clients: the endpoint is host-loopback only,
-so the bot hands them out through `routine_webhook` when a local sender needs them.
-Creation/update notices open the routine.
+(name, schedule, on/off switch). The header's chat button puts "I want a routine
+that " in the composer; **+** opens the form for doing it by hand. A row opens
+the same form filled in, with delete and test run beside Save; the row's switch
+pauses and resumes. Run results appear in the chat. The form is name, instruction, a **When to run** type (Schedule or Webhook, the two
+Claude Code routines also offer besides GitHub events) and a run timeout; cron is
+written directly as five fields plus an IANA time zone, and the host checks it and
+shows the summary and next run. One-off times, intervals, events and multiple
+triggers are left to the bot: editing such a routine shows its current triggers as
+the selected type and keeps them until Schedule or Webhook replaces them. Linux (boxed list with switches,
+same form) and the TUI (`n` form with a typed When, `c` asks the bot) match.
+A saved webhook routine's form shows its public URL and key (copy, reveal, replace
+with confirmation; Linux the same, TUI `w` copies a curl command and `W` replaces the
+key). Creation/update notices open the routine.
## Apple setup interface
-The editor keeps task fields first, followed by trigger choices and their settings.
-Trigger choices use adaptive columns, selected checkmarks and short descriptions.
+The editor keeps task fields first, then a When to run type menu and its settings.
Inputs use the shared palette with a visible filled surface. New recurring schedules
-default to cron; the frequency controls send form values to the host, which returns a five-field
-expression and an explicit IANA time zone. Run timeout is under an animated Run settings
+default to a typed cron expression and an explicit IANA time zone; the host
+describes it and shows the next run. Run timeout is under an animated Run settings
expansion. A fixed footer keeps Create routine / Save changes and inline errors
-visible while the form scrolls; it explains the local execution requirement.
+visible while the form scrolls.
The layout uses the same light/dark tokens, type family and custom controls as the
rest of Codync, with Reduce Motion support.
@@ -98,22 +103,40 @@ before stopping actors.
## Webhook delivery
-`routineWebhook` returns a per-routine URL and secret. The ordinary listing never
-returns the secret. Send JSON to `/hooks/routines/<id>` using
-`Authorization: Bearer <key>`. `X-Delivery-Id` deduplicates retries against retained
-run records. Bodies are limited to 64 KB. The routine must be enabled. Event
-routines additionally require a matching normalized payload, for example:
+Every webhook routine has a key and two addresses (`routineWebhook`): the public
+`{cloud}/v1/hooks/{computerId}/{routineId}` through the Codync cloud (null while the
+cloud is off) and the local `http://127.0.0.1:<port>/hooks/routines/<id>`. Both run
+the same checks (`host/src/routines/hooks.rs`); the protocol is
+[spec §7.8](../reference/remote-relay.md).
+
+- **Authentication**: `Authorization: Bearer <key>`, or `X-Hub-Signature-256` (an
+ HMAC-SHA256 of the body with the key). For GitHub: payload URL = the public URL,
+ content type `application/json`, secret = the key. `routineWebhook` with
+ `rotate: true` replaces the key; the old one stops working at once, including in
+ the cloud.
+- **Events**: a JSON object is the event as-is; a GitHub delivery becomes
+ `{source:"github", event:"<event>.<action>", repo, sender, text, url, payload}`
+ (GitHub `ping` succeeds without running); other bodies become `{text}`. Event
+ triggers filter on these fields, for example:
```json
{"source":"github","event":"pull_request.opened","repo":"owner/repo","text":"A PR opened"}
```
-The displayed URL uses host loopback. An external sender needs a deliberately
-configured forwarding service and must normalize its provider's event into this
-format. This implementation does **not** provision SaaS subscriptions, use Grok
-Bot's private cloud, register provider webhooks, or provision an inbound email
-address. Do not describe an event routine as connected before verifying delivery.
-The local endpoint is not automatically published through Codync's E2E relay.
+- **Delivery**: `X-Delivery-Id`, `X-GitHub-Delivery` or `Idempotency-Key`
+ deduplicates retries against retained run records. Bodies are limited to 64 KB.
+ A paused routine refuses (`409`); a non-matching event is accepted and ignored.
+ While the routine is running, the local endpoint answers `409` and the cloud
+ queue retries later (30 s doubling to 15 min).
+- **Offline**: the cloud keeps public deliveries for up to 72 hours and hands them
+ over one at a time once the host is back; the host acknowledges each.
+- **Trust**: deliveries are not end-to-end encrypted. The cloud terminates HTTPS,
+ sees the content and stores the key to check signatures. The host checks the key
+ again before anything runs.
+
+Codync does not create provider subscriptions: the user (or the bot, with the user)
+pastes the URL and key into the sending service. Do not describe an event routine as
+connected before a real delivery has arrived.
## API
@@ -127,7 +150,7 @@ All normal methods use the existing authenticated host API / authorized E2E chan
| `setRoutineEnabled` | `botId`, `id`, `enabled` |
| `deleteRoutine` | `botId`, `id` |
| `runRoutine` | `botId`, `id` |
-| `routineWebhook` | `botId`, `id` |
+| `routineWebhook` | `botId`, `id`, optional `rotate`; returns `url` (public or null), `localUrl`, `key`, `connected` |
The local-only `routineCall` backs the MCP tools. Each MCP instance is scoped to
its bot. Phone and Mac panels refresh while visible; definitions do not currently
@@ -148,7 +171,8 @@ completion reporting. Most automation modules it imports are absent. Its rendere
and private cloud are not source-complete references.
Remaining differences from the reference: provider subscription provisioning,
-cloud execution/delivery while the host is offline, inactivity auto-pause, and a Linux routine panel (the TUI edits routines with a typed schedule: cron, `every 2h`, a date, or `webhook`). The Apple UI
+cloud execution while the host is offline (deliveries wait in the cloud instead), and
+inactivity auto-pause. The Apple UI
uses Codync's shared native controls. This is not a verified complete one-to-one
reconstruction of every Grok Bot routine behavior.
@@ -158,34 +182,24 @@ reconstruction of every Grok Bot routine behavior.
checks real scheduled execution, webhook credentials, delivery deduplication,
pause/delete/edit while queued, crash recovery in the same session, unsupported
session recovery, hung-agent timeout, recurring work after failure, single-host
-ownership, silent completion, and the advertised routine MCP server. Unit tests
-cover timezone calculation, invalid schedules, event filters, persistence,
-pause/resume and bot ownership. Swift tests cover the wire model and transcript links.
+ownership, silent completion, and the advertised routine MCP server (including key
+rotation). Unit tests cover timezone calculation, invalid schedules, event filters,
+persistence, pause/resume, bot ownership, bearer/HMAC checks, GitHub event mapping and
+the relay's hook registration, acks and retries. `cloud/test/hooks.test.ts` covers the
+edge checks, queue limits, deduplication, ordering, retry and expiry; the cloud e2e
+(`npm run e2e`, step 5b) delivers through a real Worker and host, including a signed
+GitHub delivery queued while the host was down. Swift tests cover the wire model and
+transcript links.
## Public webhook ingress without a fixed IP
-Research checked on 2026-09-26:
-
-- [OpenClaw Gmail webhook setup](https://docs.openclaw.ai/cli/webhooks)
- supports Tailscale Funnel for a public push endpoint. Serve is private to the
- tailnet; it is not a replacement for a public URL used by an arbitrary SaaS.
-- [Hermes webhook adapter](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/messaging/webhooks.md)
- provides an HTTP listener, route secrets/signature validation, filtering and
- event-triggered cron jobs. Its documented setup still requires a reachable
- server URL; enabling the adapter alone does not solve NAT traversal.
-
-For Codync, a fixed IP on the user's computer is unnecessary. Two possible
-approaches are a configured outbound tunnel, or a Codync cloud ingress with a
-persistent event queue and delivery over the host's outbound connection. The
-latter fits offline delivery but is **proposed, not implemented** here.
-
-The existing relay accepts authorized devices' encrypted frames. A third-party
-HTTP sender cannot produce those frames or act as a paired device. Public ingress
-therefore needs its own per-routine authorization, provider signature checking,
-rate/body limits, delivery IDs, expiry, acknowledgements and revocation. Cloud
-HTTPS termination sees the incoming provider payload; it must not be presented as
-the same end-to-end encryption boundary as device messages. Local execution waits
-until the host reconnects and is awake.
+Research checked on 2026-09-26: [OpenClaw](https://docs.openclaw.ai/cli/webhooks)
+uses Tailscale Funnel and the [Hermes webhook adapter](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/messaging/webhooks.md)
+needs a reachable server URL. Codync instead reuses the host's outbound relay socket
+(above): no fixed IP, open port or per-user tunnel, and deliveries survive the
+computer being off. A user's own Cloudflare Tunnel to the local endpoint also works
+but needs their own account, domain and `cloudflared`, and drops deliveries while the
+computer is off.
## Usability comparison (2026-09-27)
@@ -197,35 +211,21 @@ the routine by name. No reference routine was run, paused or deleted during this
comparison.
Codync retains that compact sidebar and the chat-based setup path, while providing
-a direct editor. Calendar schedules offer minute frequencies, hourly, daily, weekdays, weekly,
-selected weekdays, monthly and custom cron. The clock uses separate hour/minute
-controls with every minute available and quick 09:00 / 12:00 / 18:00 choices.
-Selected weekdays support multiple days. The summary shows the clock time and
-zone, with the generated expression available on expansion. Switching to Custom
-starts from that expression. Monthly days 29–31 explain that shorter months are
-skipped. Existing duration intervals keep their cadence until explicitly replaced. Editing hydrates the original schedule, timezone and interval exactly;
-compound and provider-event triggers retain a lossless Keep existing triggers
-fallback. Expired one-shot timestamps are preserved when editing other fields.
+a direct editor where cron is typed as written (the earlier frequency/clock pickers
+were removed as too heavy). Existing duration intervals keep their cadence until
+explicitly replaced. Editing hydrates the original expression, timezone and interval
+exactly; compound and provider-event triggers retain a lossless Keep existing
+triggers fallback. Expired one-shot timestamps are preserved when editing other fields.
Saved definitions appear immediately. Paused schedules omit next-run deadlines.
List rows and details expose queued/running/recovery/failure states.
Edit with bot includes the routine ID in a draft without sending it.
-Verification: shared Swift tests passed (46 tests; an unrelated offline-mailbox
-assertion failed on the first run, then passed both the targeted and full rerun).
-macOS Debug and iOS Simulator builds passed. On the installed Mac build, an
-isolated fixture bot was used to create a Sunday 09:00 Asia/Taipei routine, reopen
-its populated editor, change it to weekdays, and pause it. API inspection
-confirmed one updated routine with `0 9 * * 1-5` and `enabled: false`. Edit with
-bot populated an unsent draft with the routine ID. The test bot and working
-directory were removed. Screenshots are in `build/routine-usability-calendar.jpeg`
-and `build/routine-usability-details.jpeg`.
-
## Cron scheduling contract
-All newly configured recurring schedules in the Apple editor use `cron` and run
-through the host's existing Croner scheduler. Minute presets divide an hour evenly
-(1, 5, 10, 15, 20, 30); hourly schedules choose an exact minute. Cron generation, parsing, validation, timezone checks, descriptions and next-run
+All newly configured recurring schedules in the editors use `cron` (sent as
+`calendarStyle: custom` with the typed expression) and run through the host's
+existing Croner scheduler. The host keeps preset compilation for its API. Cron generation, parsing, validation, timezone checks, descriptions and next-run
calculation all live in `host/src/routines/editor.rs` and `schedule.rs`. The Swift
draft is only a Codable form DTO. The editor debounces preview requests, discards
stale responses, shows host errors and disables Save until the current draft is
@@ -247,32 +247,3 @@ interval and expired one-shot preservation, and next occurrences across month
boundaries. An isolated HTTP integration test previews, saves and reloads the same
form and verifies direct saves reject invalid drafts. Swift tests cover wire DTO
decoding and millisecond date binding; there is no Swift cron implementation.
-
-
-### macOS selection checks
-
-The calendar editor uses shared choice menus. Nested menus become the active
-accessibility surface above the editor; Escape dismisses the top overlay through
-its own close binding. This keeps menu interaction separate from closing the
-routine editor. Schedule rules remain on the host; these are presentation rules.
-
-
-Verified on the installed Mac build through Computer Use on 2026-09-27:
-
-- Opened a saved Monday/Wednesday/Friday schedule at 14:47 in Asia/Taipei.
-- Switched to Custom and observed the host-generated `47 14 * * 1,3,5`.
-- Entered minute 61; the server error appeared and Save was disabled.
-- Selected minute 23 through the scrollable menu, saved, and reopened. Both the
- UI and API retained `23 14 * * 1,3,5` and the paused state.
-- Selected monthly day 31; the warning and October 31 next occurrence appeared.
-- Selected every 15 minutes and hourly at minute 23; both displayed host previews.
-- Verified Escape closes the top menu and preserves the editor and form values.
-- Verified the minute menu opens scrolled to the current selection. Its selection
- stays visible instead of starting at 00.
-
-The temporary bot and paused routine were removed after checking. Screenshots:
-`build/cron-verification/calendar-fields.png` and `minute-selection.png`.
-Validation: 52 Swift tests, 12 Rust routine unit tests, the isolated HTTP editor
-integration test, Rust Clippy with warnings denied, and signed macOS/iOS Debug
-builds passed. iPhone received the updated build; its final relaunch was blocked
-by the device lock. This GUI acceptance used macOS.
diff --git a/host/Cargo.lock b/host/Cargo.lock
index 3c5c3d22..838b5c54 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -587,6 +587,7 @@ dependencies = [
"gethostname",
"getrandom 0.4.3",
"hkdf 0.13.0",
+ "hmac 0.13.0",
"if-addrs",
"keyring",
"pty-process",
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 1d9d1f4b..a51c6af7 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -36,6 +36,7 @@ semver = "1.0.28"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["preserve_order"] }
sha2 = "0.11.0"
+hmac = "0.13.0"
shlex = "2.0.1"
tar = "0.4.46"
tokio = { version = "1.53.1", features = ["full"] }
diff --git a/host/src/api/mod.rs b/host/src/api/mod.rs
index e703be35..5fd995de 100644
--- a/host/src/api/mod.rs
+++ b/host/src/api/mod.rs
@@ -380,7 +380,12 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -
None,
true,
)?,
- "routineWebhook" => hub.routines.credentials(hub, str_arg(&b, "botId")?, str_arg(&b, "id")?)?,
+ "routineWebhook" => hub.routines.credentials(
+ hub,
+ str_arg(&b, "botId")?,
+ str_arg(&b, "id")?,
+ b["rotate"].as_bool().unwrap_or(false),
+ )?,
"routineCall" => crate::routines::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"])?,
"memoryCall" => {
crate::chat::memory::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?
@@ -1064,30 +1069,28 @@ async fn claim_sign(hub: &Arc<Hub>, b: &Value) -> Result<Value> {
}
/// A scoped webhook credential authorizes only firing its own routine.
+/// `POST /hooks/routines/:id`: a webhook delivery made on this computer (the public one
+/// arrives through the relay, `remote::relay`). Same checks and answers either way.
async fn routine_hook(
State(hub): State<Arc<Hub>>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Result<Json<Value>, ApiError> {
- if body.len() > 64_000 {
+ use crate::routines::hooks::{MAX_BODY, Refused};
+ if body.len() > MAX_BODY {
return Err(ApiError(StatusCode::PAYLOAD_TOO_LARGE, "event too large".into()));
}
- let key = headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .and_then(|v| v.strip_prefix("Bearer "))
- .unwrap_or_default();
- let delivery = headers.get("x-delivery-id").and_then(|v| v.to_str().ok()).map(str::to_owned);
- if delivery.as_ref().is_some_and(|v| v.len() > 200) {
- return Err(ApiError(StatusCode::BAD_REQUEST, "delivery id too long".into()));
- }
- let event =
- serde_json::from_slice(&body).map_err(|_| ApiError(StatusCode::BAD_REQUEST, "invalid event JSON".into()))?;
- hub.routines
- .webhook(&hub, &id, key, event, delivery)
- .map(Json)
- .map_err(|e| ApiError(StatusCode::BAD_REQUEST, e.to_string()))
+ let headers =
+ headers.iter().filter_map(|(k, v)| Some((k.as_str().to_owned(), v.to_str().ok()?.to_owned()))).collect();
+ hub.routines.receive(&hub, &id, &headers, &body).map(Json).map_err(|e| {
+ let status = match e {
+ Refused::Unauthorized => StatusCode::UNAUTHORIZED,
+ Refused::Paused | Refused::Busy => StatusCode::CONFLICT,
+ Refused::Invalid(_) => StatusCode::BAD_REQUEST,
+ };
+ ApiError(status, e.to_string())
+ })
}
#[cfg(test)]
diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rs
index 467648fe..d67975ef 100644
--- a/host/src/remote/relay.rs
+++ b/host/src/remote/relay.rs
@@ -4,8 +4,9 @@
//! `Codync-Sig` → pull the cloud state (≤ 10 s; account devices wait for it) → publish the
//! signed ACL → `acl.ok` → `ready`. Then device links are multiplexed onto `channel::run`
//! (the relay only ever sees ciphertext), queued mailbox sends are delivered in order and
-//! acknowledged, and every change to the device table republishes the ACL. A reconnect
-//! drops all link state.
+//! acknowledged, and every change to the device table republishes the ACL. Once ready, the
+//! routine webhooks are registered (and again whenever they change) and public webhook
+//! deliveries arrive one at a time for an ack (§7.8). A reconnect drops all link state.
use crate::LockExt;
use crate::api;
@@ -198,6 +199,8 @@ async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {
}
let mut auth = hub.auth.subscribe();
auth.mark_unchanged();
+ let mut hooks = hub.routines.subscribe_hooks();
+ hooks.mark_unchanged();
s.publish_acl().await?;
let mut ping = tokio::time::interval(PING_EVERY);
ping.reset();
@@ -225,6 +228,14 @@ async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {
}
s.publish_acl().await?;
}
+ changed = hooks.changed() => {
+ if changed.is_err() {
+ return Ok(None);
+ }
+ if s.ready {
+ s.publish_hooks().await?;
+ }
+ }
_ = ping.tick() => {
if heard.elapsed() > SILENT {
bail!("the relay stopped answering");
@@ -298,6 +309,12 @@ impl Session {
self.send(&msg).await
}
+ /// The whole webhook set; the relay replaces what it had.
+ async fn publish_hooks(&mut self) -> Result<()> {
+ let hooks = self.hub.routines.hooks();
+ self.send(&json!({"t": "hooks", "hooks": hooks})).await
+ }
+
async fn link_out(&mut self, link: String, out: Out) -> Result<()> {
let msg = match out {
Out::Msg(m) => json!({"t": "data", "link": link, "m": m}),
@@ -369,17 +386,25 @@ impl Session {
let ack = mailbox_item(&self.hub, &v).await;
self.send(&ack).await?;
}
+ "hook.item" => {
+ let ack = hook_item(&self.hub, &v);
+ self.send(&ack).await?;
+ }
"cloud.changed" => self.pull(),
"acl.ok" => {
self.retried = false;
if !self.ready {
self.ready = true;
self.send(&json!({"t": "ready"})).await?;
+ self.publish_hooks().await?;
tracing::info!(computer_id = self.hub.identity.computer_id(), "relay ready");
}
}
"error" => {
let code = v["code"].as_str().unwrap_or_default();
+ if code == "badHooks" {
+ tracing::error!("the relay refused this computer's webhook list");
+ }
if !matches!(code, "staleVersion" | "badAcl") {
return Ok(());
}
@@ -423,6 +448,29 @@ fn signed_acl(hub: &Hub) -> Result<Value> {
Ok(json!({"t": "acl", "d": b64(acl.as_bytes()), "sig": b64(&hub.identity.sign(acl.as_bytes()))}))
}
+// MARK: routine webhooks (§7.8)
+
+/// Runs one public webhook delivery and says how it went:
+/// `{"t":"hook.ack","seq","ok"}`, plus `retry` (try again later) and `code` when refused.
+fn hook_item(hub: &Arc<Hub>, item: &Value) -> Value {
+ let seq = item["seq"].clone();
+ let hook = item["hook"].as_str().unwrap_or_default();
+ let headers = item["headers"]
+ .as_object()
+ .map(|h| h.iter().filter_map(|(k, v)| Some((k.to_ascii_lowercase(), v.as_str()?.to_owned()))).collect())
+ .unwrap_or_default();
+ let Some(body) = item["body"].as_str().and_then(|b| crypto::unb64(b).ok()) else {
+ return json!({"t": "hook.ack", "seq": seq, "ok": false, "code": "invalid"});
+ };
+ match hub.routines.receive(hub, hook, &headers, &body) {
+ Ok(_) => json!({"t": "hook.ack", "seq": seq, "ok": true}),
+ Err(e) => {
+ tracing::info!(hook, code = e.code(), reason = %e, "refused a webhook delivery");
+ json!({"t": "hook.ack", "seq": seq, "ok": false, "retry": e.retry(), "code": e.code()})
+ }
+ }
+}
+
// MARK: mailbox (§6.4, §7.7)
/// Why a queued send was refused (`mbox.ack.code`).
@@ -693,6 +741,70 @@ mod tests {
assert!(hub.cloud.status().connected);
}
+ #[tokio::test]
+ async fn registers_webhooks_and_runs_public_deliveries_once() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ let cwd = std::env::temp_dir().to_string_lossy().into_owned();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
+ .unwrap();
+ let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
+ let saved = hub
+ .routines
+ .save(
+ &hub,
+ &bot_id,
+ &json!({"name": "Hook", "instruction": "Report it", "triggers": [{"type": "webhook"}]}),
+ )
+ .unwrap();
+ let id = saved["routine"]["id"].as_str().unwrap().to_owned();
+ let key = hub.routines.hooks()[0].key.clone();
+ let body = b64(br#"{"text":"deploy failed"}"#);
+ let item = |seq: i64, auth: &str, delivery: &str| {
+ json!({"t": "hook.item", "seq": seq, "hook": id, "delivery": delivery,
+ "headers": {"Authorization": format!("Bearer {auth}"), "X-Delivery-Id": delivery}, "body": body, "at": now_ms()})
+ };
+ *fake.script.lock().unwrap() =
+ vec![item(1, &key, "d1"), item(2, &key, "d1"), item(3, "wrong", "d2"), item(4, &key, "d3")];
+
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("cloud_url", &base).unwrap();
+ tokio::spawn(run(hub.clone()));
+
+ wait_for(&fake, |m| m.iter().filter(|v| v["t"] == "hook.ack").count() == 4).await;
+ let sent = fake.from_host.lock().unwrap().clone();
+ let hooks = sent.iter().find(|v| v["t"] == "hooks").unwrap();
+ assert_eq!(hooks["hooks"], json!([{"id": id, "key": key, "enabled": true}]), "registered right after ready");
+ let acks: Vec<(Option<bool>, Option<bool>, Option<&str>)> = sent
+ .iter()
+ .filter(|v| v["t"] == "hook.ack")
+ .map(|v| (v["ok"].as_bool(), v["retry"].as_bool(), v["code"].as_str()))
+ .collect();
+ assert_eq!(
+ acks,
+ [
+ (Some(true), None, None),
+ (Some(true), None, None),
+ (Some(false), Some(false), Some("unauthorized")),
+ (Some(false), Some(true), Some("busy")),
+ ],
+ "a redelivery reuses its run; a wrong key is dropped; a busy routine is retried later"
+ );
+ let runs = hub.routines.list(&bot_id)["runs"].as_array().unwrap().clone();
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0]["event"], json!({"text": "deploy failed"}));
+ assert_eq!(runs[0]["deliveryId"], "d1");
+
+ // Pausing changes what the relay should refuse: the set goes out again.
+ hub.routines.set_enabled(&hub.store, &bot_id, &id, false).unwrap();
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "hooks" && v["hooks"][0]["enabled"] == false)).await;
+ let creds = hub.routines.credentials(&hub, &bot_id, &id, true).unwrap();
+ assert_ne!(creds["key"], key, "rotate replaces the key");
+ assert_eq!(creds["url"], format!("{base}/v1/hooks/{}/{id}", hub.identity.computer_id()));
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "hooks" && v["hooks"][0]["key"] == creds["key"])).await;
+ }
+
#[tokio::test]
async fn account_mail_waits_for_a_state_pull_instead_of_failing() {
let hub = temp_hub();
diff --git a/host/src/routines/hooks.rs b/host/src/routines/hooks.rs
new file mode 100644
index 00000000..00d31d2b
--- /dev/null
+++ b/host/src/routines/hooks.rs
@@ -0,0 +1,234 @@
+//! Webhook deliveries, from the local endpoint or the cloud's public one (spec §7.8): who may
+//! send one (the routine's bearer key, or a GitHub-style HMAC of the body), and the event the
+//! routine's triggers match and its run sees.
+//!
+//! The cloud checks the same proof before it queues a delivery; the host checks again because
+//! it alone decides what runs.
+
+use hmac::{KeyInit as _, Mac as _};
+use serde_json::{Value, json};
+use std::collections::BTreeMap;
+
+pub const MAX_BODY: usize = 64 * 1024;
+const MAX_DELIVERY_ID: usize = 200;
+
+/// Request headers by lowercase name.
+pub type Headers = BTreeMap<String, String>;
+
+/// Why a delivery didn't start a run.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Refused {
+ /// Unknown routine or wrong key: told apart nowhere, so ids can't be probed.
+ Unauthorized,
+ Paused,
+ /// The routine is already running; the sender (or the cloud queue) tries again later.
+ Busy,
+ Invalid(String),
+}
+
+impl Refused {
+ pub fn code(&self) -> &'static str {
+ match self {
+ Self::Unauthorized => "unauthorized",
+ Self::Paused => "paused",
+ Self::Busy => "busy",
+ Self::Invalid(_) => "invalid",
+ }
+ }
+
+ pub fn retry(&self) -> bool {
+ matches!(self, Self::Busy)
+ }
+}
+
+impl std::fmt::Display for Refused {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Unauthorized => f.write_str("invalid webhook key or signature"),
+ Self::Paused => f.write_str("routine is paused"),
+ Self::Busy => f.write_str("routine already has an active run"),
+ Self::Invalid(why) => f.write_str(why),
+ }
+ }
+}
+
+impl std::error::Error for Refused {}
+
+/// `Authorization: Bearer <key>`, or `X-Hub-Signature-256: sha256=<hex HMAC-SHA256(key, body)>`.
+pub fn authorized(key: &str, headers: &Headers, body: &[u8]) -> bool {
+ if key.is_empty() {
+ return false;
+ }
+ if let Some(given) = headers.get("authorization").and_then(|v| v.strip_prefix("Bearer "))
+ && crate::remote::crypto::ct_eq(given.as_bytes(), key.as_bytes())
+ {
+ return true;
+ }
+ let Some(sig) = headers.get("x-hub-signature-256").and_then(|v| v.strip_prefix("sha256=")).and_then(hex) else {
+ return false;
+ };
+ let Ok(mut mac) = hmac::Hmac::<sha2::Sha256>::new_from_slice(key.as_bytes()) else { return false };
+ mac.update(body);
+ mac.verify_slice(&sig).is_ok()
+}
+
+fn hex(s: &str) -> Option<Vec<u8>> {
+ if s.len() != 64 {
+ return None;
+ }
+ (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
+}
+
+/// The sender's id for this delivery, so a retry never runs twice.
+pub fn delivery_id(headers: &Headers) -> Result<Option<String>, Refused> {
+ let id = ["x-delivery-id", "x-github-delivery", "idempotency-key"].iter().find_map(|h| headers.get(*h));
+ match id {
+ None => Ok(None),
+ Some(id) if !id.is_empty() && id.len() <= MAX_DELIVERY_ID && id.bytes().all(|b| b.is_ascii_graphic()) => {
+ Ok(Some(id.clone()))
+ }
+ Some(_) => Err(Refused::Invalid("invalid delivery id".into())),
+ }
+}
+
+/// What a routine sees and its event triggers match; `None` for a GitHub `ping`, which only
+/// checks the connection.
+///
+/// A JSON object is the event as-is; GitHub deliveries become `{source:"github", event:
+/// "<event>.<action>", repo, sender, text, url, payload}`; anything else is `{text}`.
+pub fn event(headers: &Headers, body: &[u8]) -> Result<Option<Value>, Refused> {
+ if body.len() > MAX_BODY {
+ return Err(Refused::Invalid("event too large".into()));
+ }
+ let parsed: Option<Value> =
+ if body.iter().all(u8::is_ascii_whitespace) { Some(json!({})) } else { serde_json::from_slice(body).ok() };
+ if let Some(name) = headers.get("x-github-event") {
+ if name == "ping" {
+ return Ok(None);
+ }
+ let payload = parsed.ok_or_else(|| Refused::Invalid("GitHub deliveries must use application/json".into()))?;
+ return Ok(Some(github(name, &payload)));
+ }
+ Ok(Some(match parsed {
+ Some(v @ Value::Object(_)) => v,
+ Some(other) => json!({ "payload": other }),
+ None => json!({ "text": String::from_utf8_lossy(body) }),
+ }))
+}
+
+fn github(name: &str, payload: &Value) -> Value {
+ let event = payload["action"].as_str().map_or_else(|| name.to_owned(), |action| format!("{name}.{action}"));
+ let first = |paths: &[&[&str]]| {
+ paths.iter().find_map(|path| {
+ let v = path.iter().fold(payload, |v, k| &v[*k]);
+ v.as_str().filter(|s| !s.is_empty()).map(str::to_owned)
+ })
+ };
+ let text = first(&[
+ &["pull_request", "title"],
+ &["issue", "title"],
+ &["discussion", "title"],
+ &["release", "name"],
+ &["release", "tag_name"],
+ &["comment", "body"],
+ &["review", "body"],
+ &["head_commit", "message"],
+ &["workflow_run", "name"],
+ ]);
+ let url = first(&[
+ &["comment", "html_url"],
+ &["review", "html_url"],
+ &["pull_request", "html_url"],
+ &["issue", "html_url"],
+ &["discussion", "html_url"],
+ &["release", "html_url"],
+ &["workflow_run", "html_url"],
+ &["compare"],
+ ]);
+ json!({
+ "source": "github",
+ "event": event,
+ "repo": payload["repository"]["full_name"],
+ "sender": payload["sender"]["login"],
+ "text": text,
+ "url": url,
+ "payload": payload,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+ use super::*;
+
+ const KEY: &str = "0123456789abcdef0123456789abcdef";
+
+ fn headers(pairs: &[(&str, &str)]) -> Headers {
+ pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
+ }
+
+ fn signature(key: &str, body: &[u8]) -> String {
+ let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(key.as_bytes()).unwrap();
+ mac.update(body);
+ let bytes = mac.finalize().into_bytes();
+ bytes.iter().fold(String::from("sha256="), |mut s, b| {
+ use std::fmt::Write as _;
+ let _ = write!(s, "{b:02x}");
+ s
+ })
+ }
+
+ #[test]
+ fn bearer_key_or_signature_of_the_exact_body() {
+ let body = br#"{"action":"opened"}"#;
+ assert!(authorized(KEY, &headers(&[("authorization", &format!("Bearer {KEY}"))]), body));
+ assert!(!authorized(KEY, &headers(&[("authorization", "Bearer nope")]), body));
+ assert!(!authorized(KEY, &headers(&[]), body));
+ let sig = signature(KEY, body);
+ assert!(authorized(KEY, &headers(&[("x-hub-signature-256", &sig)]), body));
+ assert!(!authorized(KEY, &headers(&[("x-hub-signature-256", &sig)]), b"{}"));
+ assert!(!authorized(KEY, &headers(&[("x-hub-signature-256", &signature("other", body))]), body));
+ assert!(!authorized(KEY, &headers(&[("x-hub-signature-256", "sha256=zz")]), body));
+ assert!(!authorized("", &headers(&[("authorization", "Bearer ")]), body), "a cleared key never matches");
+ }
+
+ #[test]
+ fn github_deliveries_become_events_triggers_can_match() {
+ let body = br#"{"action":"opened","pull_request":{"title":"Fix login","html_url":"https://github.com/o/r/pull/1"},"repository":{"full_name":"o/r"},"sender":{"login":"kai"}}"#;
+ let e = event(&headers(&[("x-github-event", "pull_request")]), body).unwrap().unwrap();
+ assert_eq!(e["source"], "github");
+ assert_eq!(e["event"], "pull_request.opened");
+ assert_eq!(e["repo"], "o/r");
+ assert_eq!(e["text"], "Fix login");
+ assert_eq!(e["url"], "https://github.com/o/r/pull/1");
+ assert_eq!(e["payload"]["sender"]["login"], "kai");
+ let push = event(&headers(&[("x-github-event", "push")]), br#"{"head_commit":{"message":"m"},"compare":"c"}"#)
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ (push["event"].as_str(), push["text"].as_str(), push["url"].as_str()),
+ (Some("push"), Some("m"), Some("c"))
+ );
+ assert_eq!(event(&headers(&[("x-github-event", "ping")]), b"{}").unwrap(), None);
+ assert!(event(&headers(&[("x-github-event", "push")]), b"payload=%7B%7D").is_err());
+ }
+
+ #[test]
+ fn other_bodies_keep_their_content() {
+ let none = headers(&[]);
+ assert_eq!(event(&none, br#"{"a":1}"#).unwrap(), Some(json!({"a":1})));
+ assert_eq!(event(&none, b"[1]").unwrap(), Some(json!({"payload":[1]})));
+ assert_eq!(event(&none, b"disk full").unwrap(), Some(json!({"text":"disk full"})));
+ assert_eq!(event(&none, b" ").unwrap(), Some(json!({})));
+ assert!(event(&none, &vec![b'x'; MAX_BODY + 1]).is_err());
+ }
+
+ #[test]
+ fn delivery_ids_come_from_the_usual_headers() {
+ assert_eq!(delivery_id(&headers(&[])), Ok(None));
+ assert_eq!(delivery_id(&headers(&[("x-github-delivery", "g-1")])), Ok(Some("g-1".into())));
+ assert_eq!(delivery_id(&headers(&[("x-delivery-id", "a"), ("idempotency-key", "b")])), Ok(Some("a".into())));
+ assert!(delivery_id(&headers(&[("x-delivery-id", "has space")])).is_err());
+ assert!(delivery_id(&headers(&[("x-delivery-id", &"x".repeat(201))])).is_err());
+ }
+}
diff --git a/host/src/routines/mod.rs b/host/src/routines/mod.rs
index 40910d35..f3524217 100644
--- a/host/src/routines/mod.rs
+++ b/host/src/routines/mod.rs
@@ -1,6 +1,8 @@
//! Durable bot routines, shared by API clients and the built-in MCP server.
mod editor;
pub use editor::preview as schedule_preview;
+pub mod hooks;
+use hooks::Refused;
mod runner;
mod schedule;
pub use runner::start;
@@ -91,12 +93,46 @@ struct State {
runs: Vec<Run>,
}
-#[derive(Default)]
pub struct Routines {
state: Mutex<State>,
active: Mutex<HashSet<String>>,
scheduler: Mutex<Option<tokio::task::JoinHandle<()>>>,
stopping: std::sync::atomic::AtomicBool,
+ /// Bumped whenever the webhook set the relay registers (`hooks()`) changes.
+ hooks_rev: tokio::sync::watch::Sender<u64>,
+}
+
+impl Default for Routines {
+ fn default() -> Self {
+ Self {
+ state: Mutex::default(),
+ active: Mutex::default(),
+ scheduler: Mutex::default(),
+ stopping: std::sync::atomic::AtomicBool::default(),
+ hooks_rev: tokio::sync::watch::channel(0).0,
+ }
+ }
+}
+
+/// One routine's public webhook as the cloud stores it.
+#[derive(Clone, PartialEq, Eq, Serialize)]
+pub struct Hook {
+ pub id: String,
+ pub key: String,
+ pub enabled: bool,
+}
+
+fn hook_set(state: &State) -> Vec<Hook> {
+ state
+ .routines
+ .iter()
+ .filter(|r| !r.deleted && r.triggers.iter().any(|t| matches!(t, Trigger::Webhook | Trigger::Event { .. })))
+ .map(|r| Hook { id: r.id.clone(), key: r.webhook_key.clone(), enabled: r.enabled })
+ .collect()
+}
+
+fn webhook_key() -> String {
+ format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple())
}
impl Routines {
@@ -120,9 +156,19 @@ impl Routines {
}
store.kv_set(STATE_KEY, &serde_json::to_string(&state)?)?;
*self.state.locked() = state;
+ self.hooks_rev.send_modify(|v| *v += 1);
Ok(())
}
+ /// The webhook routines the relay registers with the cloud.
+ pub fn hooks(&self) -> Vec<Hook> {
+ hook_set(&self.state.locked())
+ }
+
+ pub fn subscribe_hooks(&self) -> tokio::sync::watch::Receiver<u64> {
+ self.hooks_rev.subscribe()
+ }
+
fn change<T>(&self, store: &Store, update: impl FnOnce(&mut State) -> Result<T>) -> Result<T> {
let mut guard = self.state.locked();
let mut next = guard.clone();
@@ -140,7 +186,12 @@ impl Routines {
next.routines
.retain(|r| !r.deleted || next.runs.iter().any(|run| run.routine_id == r.id && run.status.active()));
store.kv_set(STATE_KEY, &serde_json::to_string(&next)?)?;
+ let hooks_changed = hook_set(&guard) != hook_set(&next);
*guard = next;
+ drop(guard);
+ if hooks_changed {
+ self.hooks_rev.send_modify(|v| *v += 1);
+ }
Ok(result)
}
@@ -214,10 +265,7 @@ impl Routines {
triggers.iter().map(|t| t.next(now)).collect::<Result<_>>()?
},
triggers,
- webhook_key: old.as_ref().map_or_else(
- || format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple()),
- |r| r.webhook_key.clone(),
- ),
+ webhook_key: old.as_ref().map_or_else(webhook_key, |r| r.webhook_key.clone()),
deleted: false,
timeout_seconds: timeout
.unwrap_or_else(|| old.as_ref().map_or_else(default_timeout, |r| r.timeout_seconds)),
@@ -293,7 +341,7 @@ impl Routines {
let r =
s.routines.iter().find(|r| r.id == id && r.bot_id == bot && !r.deleted).context("routine not found")?;
if !r.enabled && !test {
- bail!("routine is paused");
+ bail!(Refused::Paused);
}
if let Some(key) = &delivery
&& let Some(run) =
@@ -302,7 +350,7 @@ impl Routines {
return Ok(json!({"run":run}));
}
if s.runs.iter().any(|run| run.routine_id == id && run.status.active()) {
- bail!("routine already has an active run");
+ bail!(Refused::Busy);
}
let run = new_run(r, event, delivery);
let result = json!({"run":run});
@@ -311,28 +359,62 @@ impl Routines {
})
}
- pub fn credentials(&self, hub: &Hub, bot: &str, id: &str) -> Result<Value> {
- let s = self.state.locked();
- let r = s.routines.iter().find(|r| r.id == id && r.bot_id == bot && !r.deleted).context("routine not found")?;
- Ok(json!({"url":format!("http://127.0.0.1:{}/hooks/routines/{id}",hub.port),"key":r.webhook_key}))
+ /// The routine's webhook: the public URL through the Codync cloud (when it's on), the
+ /// local one, and the key. `rotate` replaces the key first, cutting off the old one.
+ pub fn credentials(&self, hub: &Hub, bot: &str, id: &str, rotate: bool) -> Result<Value> {
+ if rotate {
+ self.change(&hub.store, |s| {
+ let r = s
+ .routines
+ .iter_mut()
+ .find(|r| r.id == id && r.bot_id == bot && !r.deleted)
+ .context("routine not found")?;
+ r.webhook_key = webhook_key();
+ r.updated_at = now_ms();
+ Ok(())
+ })?;
+ }
+ let key = {
+ let s = self.state.locked();
+ s.routines
+ .iter()
+ .find(|r| r.id == id && r.bot_id == bot && !r.deleted)
+ .context("routine not found")?
+ .webhook_key
+ .clone()
+ };
+ let cloud = hub.cloud.status();
+ let url = crate::remote::cloud::url(&hub.store)
+ .map(|base| format!("{}/v1/hooks/{}/{id}", base.trim_end_matches('/'), hub.identity.computer_id()));
+ Ok(json!({
+ "url": url,
+ "localUrl": format!("http://127.0.0.1:{}/hooks/routines/{id}", hub.port),
+ "key": key,
+ "connected": url.is_some() && cloud.connected,
+ }))
}
- pub fn webhook(&self, hub: &Hub, id: &str, key: &str, event: Value, delivery: Option<String>) -> Result<Value> {
- let r = self
- .state
- .locked()
- .routines
- .iter()
- .find(|r| r.id == id && !r.deleted)
- .cloned()
- .context("unknown webhook")?;
- if !crate::remote::crypto::ct_eq(r.webhook_key.as_bytes(), key.as_bytes()) {
- bail!("invalid webhook key");
+ /// One delivery from the local endpoint or the cloud: checks the key or signature, then
+ /// queues a run when the event matches. Retries of a delivery id return its first run.
+ pub fn receive(&self, hub: &Hub, id: &str, headers: &hooks::Headers, body: &[u8]) -> Result<Value, Refused> {
+ let r = self.state.locked().routines.iter().find(|r| r.id == id && !r.deleted).cloned();
+ let Some(r) = r.filter(|r| hooks::authorized(&r.webhook_key, headers, body)) else {
+ return Err(Refused::Unauthorized);
+ };
+ let delivery = hooks::delivery_id(headers)?;
+ let Some(event) = hooks::event(headers, body)? else {
+ return Ok(json!({"ping": true}));
+ };
+ if !r.enabled {
+ return Err(Refused::Paused);
}
if !r.triggers.iter().any(|t| matches!(t, Trigger::Webhook) || t.matches(&event)) {
- bail!("event does not match this routine");
+ return Ok(json!({"ignored": "event does not match this routine"}));
}
- self.enqueue(&hub.store, &r.bot_id, id, event, delivery, false)
+ self.enqueue(&hub.store, &r.bot_id, id, event, delivery, false).map_err(|e| match e.downcast::<Refused>() {
+ Ok(refused) => refused,
+ Err(e) => Refused::Invalid(format!("{e:#}")),
+ })
}
}
@@ -389,12 +471,14 @@ pub fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result<Value
"run_routine" => {
hub.routines.enqueue(&hub.store, bot, required(args, "id")?, json!({"source":"test"}), None, true)
}
- "routine_webhook" => hub.routines.credentials(hub, bot, required(args, "id")?),
+ "routine_webhook" => {
+ hub.routines.credentials(hub, bot, required(args, "id")?, args["rotate"].as_bool().unwrap_or(false))
+ }
_ => bail!("unknown routine tool"),
}
}
-pub const INSTRUCTIONS: &str = "Create and manage persistent Codync routines when the user asks for scheduled or event-driven work. Use the built-in routines tools (save_routine, list_routines, set_routine_enabled, delete_routine, run_routine, routine_webhook), not operating-system cron or an improvised background process. For recurring clock schedules, always use a five-field cron trigger with an explicit IANA timezone, including minute/hour frequencies; do not create interval triggers for those requests. Preserve existing intervals when editing unrelated fields. Cron steps reset within their field: */7 minutes is not an exact seven-minute duration across hours. Use once for a single dated execution; never approximate a one-time task with an annually repeating cron expression. Before saving, resolve the task, trigger and intended timezone for calendar/one-time schedules from the conversation; ask only for missing or ambiguous details. If the request is already clear, create it without another confirmation. Check that tools, connector sign-ins and files needed by the task are available; describe any missing setup rather than promising the task will work. Use list_routines before creating or editing to avoid duplicates; preserve unrelated triggers, enabled state and instructions. Save returns the actual routine ID, trigger descriptions and nextRunAt: use these to report what was really saved, including timezone, next occurrence and enabled/paused state. Do not claim success if the tool failed. run_routine executes the real task immediately, including its side effects; use it when the user requested a test or immediate execution, not merely to validate a schedule. A routine runs locally in its own conversation; the host must be running and awake, results appear in the main chat, and (pass) stays silent. Webhooks use a per-routine bearer key; the returned URL is local to the host and does not configure a public tunnel or provider subscription. Establish the event source, reachable ingress and authentication separately. Never claim a third-party integration is connected until a real delivery has been verified; report a saved webhook as awaiting connection when that setup is missing. Keep secrets out of routine instructions and ordinary status summaries.";
+pub const INSTRUCTIONS: &str = "Create and manage persistent Codync routines when the user asks for scheduled or event-driven work. Use the built-in routines tools (save_routine, list_routines, set_routine_enabled, delete_routine, run_routine, routine_webhook), not operating-system cron or an improvised background process. For recurring clock schedules, always use a five-field cron trigger with an explicit IANA timezone, including minute/hour frequencies; do not create interval triggers for those requests. Preserve existing intervals when editing unrelated fields. Cron steps reset within their field: */7 minutes is not an exact seven-minute duration across hours. Use once for a single dated execution; never approximate a one-time task with an annually repeating cron expression. Before saving, resolve the task, trigger and intended timezone for calendar/one-time schedules from the conversation; ask only for missing or ambiguous details. If the request is already clear, create it without another confirmation. Check that tools, connector sign-ins and files needed by the task are available; describe any missing setup rather than promising the task will work. Use list_routines before creating or editing to avoid duplicates; preserve unrelated triggers, enabled state and instructions. Save returns the actual routine ID, trigger descriptions and nextRunAt: use these to report what was really saved, including timezone, next occurrence and enabled/paused state. Do not claim success if the tool failed. run_routine executes the real task immediately, including its side effects; use it when the user requested a test or immediate execution, not merely to validate a schedule. A routine runs locally in its own conversation; the host must be running and awake, results appear in the main chat, and (pass) stays silent. Webhooks use a per-routine key: senders POST to the returned public url (through the Codync cloud; null when the cloud is off, then only localUrl on this computer works) with Authorization: Bearer <key>, or, for GitHub, set the webhook's content type to application/json and its secret to the key (deliveries are verified by their X-Hub-Signature-256). GitHub deliveries become events {source:github, event:<event>.<action>, repo, sender, text, url, payload} that event triggers can filter. Deliveries made while the computer is offline wait up to 72 hours in the cloud. The cloud sees delivery contents (they are not end-to-end encrypted). routine_webhook with rotate:true replaces the key; the old one stops working at once. This does not register a provider subscription: set that up with the user. Never claim a third-party integration is connected until a real delivery has been verified; report a saved webhook as awaiting connection when that setup is missing. Keep secrets out of routine instructions and ordinary status summaries.";
pub fn tools() -> Value {
let id = json!({"type":"string"});
@@ -406,10 +490,19 @@ pub fn tools() -> Value {
("set_routine_enabled", "Pause or resume a routine; enabled boolean is required."),
("delete_routine", "Delete a routine and cancel pending runs."),
("run_routine", "Start a test run, including for a paused routine."),
- ("routine_webhook", "Get the local webhook URL and secret bearer key."),
+ (
+ "routine_webhook",
+ "Get the routine's public webhook URL (null when the Codync cloud is off), its local URL and secret key. rotate:true replaces the key.",
+ ),
] {
let required = if name == "set_routine_enabled" { vec!["id", "enabled"] } else { vec!["id"] };
- tools.push(json!({"name":name,"description":description,"inputSchema":{"type":"object","properties":{"id":id,"enabled":{"type":"boolean"}},"required":required}}));
+ let mut properties = json!({"id": id});
+ match name {
+ "set_routine_enabled" => properties["enabled"] = json!({"type":"boolean"}),
+ "routine_webhook" => properties["rotate"] = json!({"type":"boolean"}),
+ _ => {}
+ }
+ tools.push(json!({"name":name,"description":description,"inputSchema":{"type":"object","properties":properties,"required":required}}));
}
json!(tools)
}
diff --git a/host/tests/fixtures/routine_agent.py b/host/tests/fixtures/routine_agent.py
index 909ecba6..08dd919c 100644
--- a/host/tests/fixtures/routine_agent.py
+++ b/host/tests/fixtures/routine_agent.py
@@ -103,8 +103,11 @@ def verify_routine_tools():
assert routine["enabled"] is False
assert "webhookKey" not in routine
credentials = call("routine_webhook", {"id": identifier_value})
- assert credentials["url"].endswith("/hooks/routines/" + identifier_value)
+ assert credentials["url"] is None # the test host runs with the cloud off
+ assert credentials["localUrl"].endswith("/hooks/routines/" + identifier_value)
assert len(credentials["key"]) >= 32
+ rotated = call("routine_webhook", {"id": identifier_value, "rotate": True})
+ assert rotated["key"] != credentials["key"] and len(rotated["key"]) >= 32
body.update({"id": identifier_value, "name": "Edited through MCP"})
call("save_routine", body)
call("set_routine_enabled", {"id": identifier_value, "enabled": True})
diff --git a/host/tests/routines_e2e.rs b/host/tests/routines_e2e.rs
index 506330d3..d245cfbf 100644
--- a/host/tests/routines_e2e.rs
+++ b/host/tests/routines_e2e.rs
@@ -176,7 +176,8 @@ async fn routines_execute_pause_deduplicate_and_reject_wrong_webhook_keys() {
let id = result["routine"]["id"].as_str().unwrap();
assert!(result["routine"].get("webhookKey").is_none());
let credentials = host.call("routineWebhook", json!({"botId":bot,"id":id})).await;
- let url = credentials["url"].as_str().unwrap();
+ assert!(credentials["url"].is_null(), "no public URL while the cloud is off");
+ let url = credentials["localUrl"].as_str().unwrap();
let client = reqwest::Client::new();
assert!(!client.post(url).bearer_auth("wrong").json(&json!({})).send().await.unwrap().status().is_success());
let first: Value = client