# Scheduled Tasks

**Scheduled tasks** are per-instance jobs that fire on a schedule (or on demand) and run a prompt through the supervisor as if a user had sent a message. Use them for recurring digests, polling integrations that don't push webhooks, periodic clean-up prompts, or one-shot reminders.

> **No top-level sidebar entry.** Scheduled tasks are *not* exposed at `/scheduled-tasks` or anywhere in the global sidebar. They live **only** inside an agent's own page, as the **Scheduled** row of its *Automations* group (`?tab=scheduled`). To see every scheduled task across the installation you have to open each agent in turn.

The UI is the **Scheduled** section, a row of the agent's *Automations* group next to **Hooks**, **Webhooks** and **Room** - there is no wrapping "Triggers" section. Each row of the section is one task, sorted by name, with its schedule, channel, status, next and last run, and an **Active** switch. Clicking a row opens the task in a side drawer, which edits it and holds **Run now** and **Delete**. Run history lives in the agent's **Monitor** section, under *Activity*, as **Scheduled** rows.

## What a task looks like

A task carries enough state to run autonomously and report back. The fields below mirror `scheduled_tasks` in `packages/engine/src/scheduled-tasks/schema.ts`.

| Field             | Type                                                | Notes                                                                 |
|-------------------|-----------------------------------------------------|-----------------------------------------------------------------------|
| `name`            | string                                              | Operator-facing label.                                                |
| `description`     | string (optional)                                   | Free-text reminder of what the task does.                             |
| `prompt`          | string                                              | The user-message text sent to the supervisor when the task fires.     |
| `schedule`        | discriminated union (`cron` / `interval` / `one-shot`) | See below.                                                         |
| `enabled`         | boolean                                             | Master switch. Disabled tasks never tick.                             |
| `outboundChannel` | enum (optional)                                     | `slack`, `telegram`, `whatsapp`, or unset. Where the answer is sent.  |
| `outboundTarget`  | string (optional)                                   | Channel id or user id within `outboundChannel`.                       |
| `keepHistory`     | boolean                                             | If false, each run uses a fresh conversation id (no memory carry-over).|
| `deleteAfterRun`  | boolean                                             | One-shot tasks delete themselves after success.                       |
| `maxRetries`      | int (default 3)                                     | Retries with backoff after a failed run before waiting for the next scheduled run. |

### Schedule shape

```ts
type ScheduleConfig =
  | { type: "cron";     expression: string; timezone?: string }
  | { type: "interval"; everyMs: number; anchorAt?: string }
  | { type: "one-shot"; runAt: string };
```

- **Cron** uses standard 5-field POSIX cron, optionally timezone-anchored.
- **Interval** ticks every `everyMs` from `anchorAt` (or task creation time).
- **One-shot** fires once at the given ISO timestamp. Combine with `deleteAfterRun: true` for fire-and-forget reminders.

The same rule holds wherever a schedule is written, through the API or the `scheduleTask` tool: an interval's `everyMs` is an integer of at least 60000, an anchor or a run time is a date, and fields the type does not have are dropped. Anything else answers `400` naming the field (for example `schedule.everyMs`). A bundle import keeps the tasks an earlier export carried and refuses only an interval that never advances (zero, negative or not finite). A task saved earlier with an interval of zero or less is disabled on its next run.

## Lifecycle

1. The **scheduler service** ticks every 30 s (`TICK_INTERVAL_MS = 30_000`, `packages/engine/src/scheduled-tasks/scheduler.service.ts:26`).
2. On each tick it claims up to `MAX_CONCURRENT = 3` tasks whose `nextRunAt` is in the past, the longest overdue first, in one statement, and runs them in parallel. Replicas ticking together share the due tasks rather than running one twice.
3. Each fire emits a `cron` event on the [activity bus](https://docs.polyant.ai/concepts/activity-stream) **before** the supervisor runs - useful as a heartbeat: the run appears in the [Monitor](https://docs.polyant.ai/admin-panel/activity) as a live **Scheduled** row, **Running**, until its stored row replaces it.
4. The supervisor processes the prompt exactly as if it were a user message. The conversation id is either reused (`keepHistory: true`) or freshly minted (`keepHistory: false`).
5. The reply, if any, is delivered to `outboundChannel`/`outboundTarget` when configured. Otherwise it stays in the conversation for browsing.
6. The run is recorded in `scheduled_task_runs` (`run_id`, `started_at`, `completed_at`, `duration_ms`, `status`, `output`, `error`, `tool_calls`, `token_usage`).
7. On error, `consecutive_errors` increments. The run is retried with backoff up to `maxRetries` times, then the task waits for its next scheduled run. After 5 consecutive errors the task is auto-disabled and its status in the UI reads **Auto-disabled**.

### A run whose process never came back

A run used to be able to disappear without a trace. `markRunning` set the row's status to `running`, nothing ever cleared it, and the query that picks up due tasks skips a row in that state - so a process killed mid-run by a deploy, an OOM or a crash left the task **silent, with no error anywhere**.

Two mechanisms close that, and they are deliberately not the same one:

- **A running task holds a lease** that its process renews. When the process dies, the lease expires after the orphaned-run grace (15 minutes by default, never less than a minute), and the next tick of any replica clears the run, closes it in the run log as interrupted and counts no failure, so the task runs again. A run whose process is alive keeps renewing its lease and is never touched, so a rolling deploy does not steal a live run. The boot itself no longer recovers, runs or reschedules anything: the tick serves overdue tasks.
- **On every tick**, a reaper fails any run past its deadline - the task's own `max_run_ms`, or the default run deadline (30 minutes) when it declares none. The default is deliberately generous, because reaping a run that is still alive is the worse of the two failures: the row is re-armed while the old execution keeps going.

Both windows are [Installation policies](https://docs.polyant.ai/admin-panel/installation-policies) a platform admin edits in the panel; the `SCHEDULER_ORPHAN_GRACE_MS` and `SCHEDULER_DEFAULT_MAX_RUN_MS` environment variables are no longer read.

One bad audit entry no longer kills the batch either - a run that fails to record stops itself, not its neighbours.

### Watching the loop from outside

`GET /health/scheduler` is public and answers in numbers rather than a status word, because the failure mode is silence: nothing throws, every task stays enabled, and a plain health check keeps saying `ok` while nothing runs.

| Field | What a bad value means |
|---|---|
| `freeSlots` | concurrency slots not held by a run. **Zero across consecutive scrapes** means the loop is wedged - concurrency is process-wide, so runs that never finish stop every agent's tasks |
| `stuckRunning` | rows marked `running` past the default deadline. **Non-zero for more than a tick or two** is the signature this endpoint exists to expose |

Counts only: no agent names, no task names, nothing an unauthenticated caller could use to enumerate tenants.

## API

All endpoints are scoped to an instance - replace `:slug` with the instance slug.

| Method | Path                                                        | Description                                              |
|--------|-------------------------------------------------------------|----------------------------------------------------------|
| GET    | `/api/instances/:slug/scheduled-tasks`                      | List tasks for the instance.                             |
| POST   | `/api/instances/:slug/scheduled-tasks`                      | Create a task.                                           |
| GET    | `/api/instances/:slug/scheduled-tasks/:id`                  | Get one task (full state).                               |
| PATCH  | `/api/instances/:slug/scheduled-tasks/:id`                  | Update fields (name, prompt, schedule, enabled, ...).    |
| DELETE | `/api/instances/:slug/scheduled-tasks/:id`                  | Remove the task and cascade-delete its runs.             |
| POST   | `/api/instances/:slug/scheduled-tasks/:id/run`              | Trigger an immediate execution (`triggerType: manual`).  |
| GET    | `/api/instances/:slug/scheduled-tasks/:id/runs`             | Paginated run log for a single task (most recent first). |
| GET    | `/api/instances/:slug/scheduled-tasks/runs`                 | Cross-task global run log for the instance (no `:id`).   |

## Worked example: daily digest at 09:00 Europe/Rome

1. Open the agent → **Automations → Scheduled** → **Add**.
2. Name: *Morning digest*.
3. Schedule: `cron`, expression `0 9 * * *`, timezone `Europe/Rome`.
4. Prompt: *"Search the last 24 hours of memories and summarise the three most important events. Be terse."*
5. Outbound channel: `slack`, target: `C012345678`.
6. Click **Add**. A new task starts active.

The next morning at 09:00 Rome time the agent's [Monitor](https://docs.polyant.ai/admin-panel/activity) shows one **Scheduled** row for the run, whose drawer lists the `searchMemory` call under **Tools used**, and one **Tools** row for the call itself; the reply goes out on Slack.

## Caveats

- **Tick granularity is 30 s.** Don't expect sub-minute accuracy.
- **Max concurrency is 3.** A burst of due tasks queues; the rest wait for the next tick.
- **Auto-disable is per-task, not global.** A flaky task won't take down its neighbours.
- **A run that outlasts its deadline can run twice.** The reaper frees its claim and another replica can start the task while the first run is still going. Give each task a run deadline it does not reach.
- **Shutdown waits for runs already started**, within the same grace period as acknowledged channel turns.
- **A manual run is audited before it fires**, not after - the run is fire-and-forget, so recording it afterwards would mean recording nothing when it does not come back.

See also: [Monitor](https://docs.polyant.ai/admin-panel/activity) for run history and live visibility into firings, [Activity Stream (concept)](https://docs.polyant.ai/concepts/activity-stream) for the underlying bus.
