Heartbeat is an automation. See Automation for guidance on choosing the system-owned monitor or an independently scheduled job.

Heartbeat is a system-owned automation that runs periodic agent turns in the main session so the model can surface anything that needs attention without spamming you.

Heartbeat is a scheduled main-session turn. ACP runs, subagents, and isolated automation jobs use their own execution owners.

Under the hood, heartbeat cadence is owned by the Automations scheduler: the gateway maintains one system-owned automation job per heartbeat-enabled agent (visible in apus cron list --all as Heartbeat (agent-id)). Heartbeat config remains the desired-state input, while the persisted monitor schedule owns the actual tick and the runner's later cooldown. The gateway writes config changes through at startup and on config reload. apus doctor --fix can materialize missing or stale monitor rows before the next gateway start. Edit agents.*.heartbeat, not the automation job. If saving monitor rows fails after a config change is accepted, the Gateway keeps the accepted config and reports that recovery is required. Monitor retries use the current accepted config. Rejected changes never become retry targets.

Scheduled heartbeats require automations. When cron.enabled is false or APUS_SKIP_CRON=1, the gateway logs a startup warning and does not run scheduled heartbeats. Manual and event-driven heartbeat wakes remain available. There is no separate heartbeat fallback timer.

Setting heartbeat.every: "0m" disables only the recurring cadence. A targeted event-driven wake can still run one agent turn, such as a background exec completion. It does not create or re-enable a recurring schedule. To keep background exec without automatic completion turns or their model calls, set tools.exec.notifyOnExit: false; check agents.entries.<id>.tools.exec.notifyOnExit for per-agent overrides. Collect results with process poll. See Background exec notifications. Tool policy and sandboxing control whether agent turns may execute commands.

Heartbeat-owned event wakes retain the same per-agent rate limits when recurring cadence is disabled. Those limits are a 30-second minimum between event turns, and a flood guard after five starts within 60 seconds. Deferred work resumes when its guard expires. Config reloads preserve this accounting without enrolling the agent in recurring or broadcast heartbeats.

Transcript markers distinguish [Apus heartbeat poll] from an exec completion, cron wake, or session event. Scheduled polls use the configured heartbeat session, which is the agent's main session by default. Targeted completion events return to the session that owns the work. Event markers retain their source provenance without copying internal instructions into chat history. Silent acknowledgment pairs remain hidden.

Troubleshooting: Automations

Quick start (beginner)

Pick a cadence

Leave heartbeats enabled (default is `30m`, or `1h` when Anthropic OAuth/token auth is configured, including Claude CLI reuse) or set your own cadence.

Add monitor scratch (optional)

Store a tiny checklist in the heartbeat monitor's scratch with `apus cron scratch <jobId> --set "..."`.

Decide where heartbeat messages should go

Heartbeat alerts go to the operator's direct message by default. Set `commands.ownerAllowFrom` to an array such as `["telegram:123456789"]`, or use a concrete channel `allowFrom`. Wildcard-only allowlists do not identify an owner.

Optional tuning

- Use lightweight bootstrap context if heartbeat runs only need the monitor scratch.
- Enable isolated sessions to avoid sending full conversation history each heartbeat.
- Restrict heartbeats to active hours (local time).

Example config:

{
  commands: {
    ownerAllowFrom: ["telegram:123456789"],
  },
  agents: {
    defaults: {
      heartbeat: {
        every: "30m",
        target: "owner", // default: operator DM from ownerAllowFrom or channel allowFrom
        directPolicy: "allow", // default: allow direct/DM targets; set "block" to suppress
        lightContext: true, // optional: skip workspace bootstrap files for heartbeat runs
        isolatedSession: true, // optional: fresh session each run (no conversation history)
        // activeHours: { start: "08:00", end: "24:00" },
      },
    },
  },
}

For a configured Telegram bot, set the owner with a JSON array, even when there is only one entry. Replace 123456789 with your Telegram user ID and include any existing owners you want to keep:

apus config set commands.ownerAllowFrom '["telegram:123456789"]'

To select a recipient explicitly, set the channel and recipient separately:

apus config set agents.defaults.heartbeat.to '"123456789"'
apus config set agents.defaults.heartbeat.target telegram

Keep the inner double quotes around the numeric chat ID so to is stored as a string. heartbeat.target accepts owner, last, none, or a channel ID such as telegram; telegram:123456789 belongs in commands.ownerAllowFrom, not target.

Defaults

What the heartbeat prompt is for

The default prompt is intentionally narrow: follow the heartbeat monitor scratch context when provided, keep recurring work in automation jobs, and reply NO_REPLY when nothing needs attention. It explicitly tells the agent not to infer or repeat old tasks from prior chats, so a default install stays quiet instead of rehashing stale conversation context.

Proactive heartbeat behavior is opt-in:

Heartbeat still handles node completion events. Host exec, CLI watchdog, ACP parent relay, immediate HTTP hooks, restart continuations, and session-state notices use ordinary session execution. A completion carrying a captured delivery route returns to that account, conversation, and thread; the monitor's configured target, to, or accountId cannot redirect it. Intentional target: "none", direct-message restrictions, notification opt-outs, and disabled heartbeat controls still apply. Plugin normalization that would change the captured route fails closed. Ordinary scheduled heartbeats retain their configured destinations.

Heartbeat-owned node completions with different delivery routes run in separate turns, including different accounts or topics. Identical completion text does not suppress a different completion occurrence.

If a heartbeat-owned completion cannot enter delivery, its original-route event remains available for the existing bounded wake retry. Once the durable delivery queue owns an attempt, that queue owns transport retries; an unrelated wake must not regenerate its result. An unresolved attempt without confirmed delivery custody is withheld from model replay. Use process poll to collect an exec result, and verify whether a message arrived before manually resending an ambiguous delivery. This does not change node protocol negotiation or legacy notification behavior.

If you want a heartbeat to do something very specific (e.g. "check Gmail PubSub stats" or "verify gateway health"), set agents.defaults.heartbeat.prompt (or agents.entries.*.heartbeat.prompt) to a custom body (sent verbatim).

Immediate session events

Host background commands, CLI watchdog completions, ACP parent notifications, immediate HTTP hook wakes, restart continuations, and session-state notices enter the ordinary reply queue. They keep the originating session's history and captured delivery route, wait behind its existing work, and use its current permissions. Heartbeat cadence, active hours, model, and visibility settings do not control these events. An originating run's automatic-delivery opt-out remains in effect.

Session-state notices for the same watcher and captured delivery route collect for up to 20 seconds and enter one reconciliation turn. The turn retains every notice's permission limits and acknowledges the watched sessions only when it is adopted. If one notice is consumed before adoption, the remaining original notices keep their own reconciliation work.

Each occurrence has one execution owner. Periodic heartbeat polls and incoming user turns cannot consume an event waiting in the ordinary queue. Acceptance confirms that the owner retained the event; it does not prove execution or delivery completed. Resetting or deleting the target session cancels the retained event rather than moving it into the replacement session. A NO_REPLY result remains silent.

Response contract

Outside heartbeats, stray HEARTBEAT_OK at the start/end of a message is stripped and logged. A message that is only HEARTBEAT_OK is dropped.

Config

{
  agents: {
    defaults: {
      heartbeat: {
        every: "30m", // default: 30m (0m disables)
        model: "anthropic/claude-opus-4-6",
        lightContext: false, // default: false; true skips workspace bootstrap files for heartbeat runs
        isolatedSession: false, // default: false; true runs each heartbeat in a fresh session (no conversation history)
        target: "owner", // default | options: last | none | <channel id>
        accountId: "ops-bot", // optional multi-account channel id
        prompt: "Follow the heartbeat monitor scratch context when provided. Recurring tasks are automations; create or change their schedules with the automations tool, not heartbeat scratch. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply NO_REPLY.",
      },
    },
  },
}

Scope and precedence

Per-agent heartbeats

If any agents.entries.* entry includes a heartbeat block, only those agents run heartbeats. The per-agent block merges on top of agents.defaults.heartbeat (so you can set shared defaults once and override per agent).

Example: two agents, only the second agent runs heartbeats.

{
  agents: {
    ownership: "explicit",
    defaults: {
      systemAgent: { agentId: "main" },
      heartbeat: {
        every: "30m",
        target: "owner", // default: operator DM
      },
    },
    entries: {
      main: { workspace: "~/.apus/workspace" },
      ops: {
        heartbeat: {
          every: "1h",
          target: "whatsapp",
          to: "+15551234567",
          timeoutSeconds: 45,
          prompt: "Follow the heartbeat monitor scratch context when provided. Recurring tasks are automations; create or change their schedules with the automations tool, not heartbeat scratch. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply NO_REPLY.",
        },
      },
    },
  },
  talk: { agentId: "main" },
}

Active hours example

Restrict heartbeats to business hours in a specific timezone:

{
  agents: {
    defaults: {
      heartbeat: {
        every: "30m",
        target: "owner", // default: operator DM
        activeHours: {
          start: "09:00",
          end: "22:00",
          timezone: "America/New_York", // optional; uses your userTimezone if set, otherwise host tz
        },
      },
    },
  },
}

Outside this window (before 9am or after 10pm Eastern), heartbeats are skipped. The next scheduled tick inside the window will run normally.

24/7 setup

If you want heartbeats to run all day, use one of these patterns:

Do not set the same start and end time (for example 08:00 to 08:00). That is treated as a zero-width window, so heartbeats are always skipped.

Multi-account example

Use accountId to target a specific account on multi-account channels like Telegram:

{
  agents: {
    entries: {
      ops: {
        heartbeat: {
          every: "1h",
          target: "telegram",
          to: "12345678:topic:42", // optional: route to a specific topic/thread
          accountId: "ops-bot",
        },
      },
    },
  },
  channels: {
    telegram: {
      accounts: {
        "ops-bot": { botToken: "YOUR_TELEGRAM_BOT_TOKEN" },
      },
    },
  },
}

Field notes

every string

Heartbeat interval (duration string, default unit minutes).

model string

Optional model override for heartbeat runs (provider/model).

lightContext boolean

When true, heartbeat runs use lightweight bootstrap context and skip workspace bootstrap files. Monitor scratch is injected by the heartbeat runner either way. A conversation's own background command completion keeps the conversation's full context.

isolatedSession boolean

When true, each heartbeat runs in a fresh session with no prior conversation history. Uses the same isolation pattern as automation jobs with sessionTarget: "isolated". Dramatically reduces per-heartbeat token cost. Combine with lightContext: true for maximum savings. Delivery routing and conversation context still follow the selected conversation, including its channel, account, and topic. A background command's completion keeps its original event route if that conversation later moves. It does not borrow the new room's description or activation policy. A conversation's own background command completion is not isolated; see Session and target routing.

session string

Optional session key for heartbeat runs.

  • main (default): agent main session.
  • Explicit session key (copy from apus sessions --json or the sessions CLI).
  • Session key formats: see Sessions and Groups.
target string
  • owner (default): deliver to the first resolvable operator DM from commands.ownerAllowFrom, then channel allowFrom. This route never resolves to a group or channel.
  • last: explicitly follow the last used external conversation, including groups and channels.
  • explicit channel: any configured channel or plugin id, for example discord, matrix, telegram, or whatsapp.
  • none: run the heartbeat for internal state only. Do not deliver it externally.

For an explicit Telegram recipient, use target: "telegram" and to: "123456789". The target field does not accept a combined channel-and-recipient value such as "telegram:123456789".

directPolicy "allow" | "block"

Controls direct/DM delivery behavior. allow: allow direct/DM heartbeat delivery. block: suppress direct/DM delivery (reason=dm-blocked).

to string

Recipient for an explicit channel target (for example, E.164 for WhatsApp or a Telegram chat id). owner and an unset target ignore to. For Telegram topics/threads, use <chatId>:topic:<messageThreadId>.

accountId string

Optional account id for multi-account channels. When target: "last", the account id applies to the resolved last channel if it supports accounts. Otherwise it is ignored. If the account id does not match a configured account for the resolved channel, delivery is skipped.

prompt string

Overrides the default prompt body (not merged).

timeoutSeconds number

Maximum seconds allowed for a heartbeat agent turn before it is aborted. Leave unset to use agents.defaults.timeoutSeconds when set, otherwise the heartbeat cadence capped at 600 seconds. Exec-completion, background-task, and recovered restart continuations use the ordinary agent timeout instead, including an explicit agents.defaults.timeoutSeconds value of 0 for no timeout.

activeHours object

Restricts heartbeat runs to a time window. Object with start (HH:MM, inclusive, with 00:00 for start-of-day), end (HH:MM exclusive, with 24:00 allowed for end-of-day), and optional timezone.

  • Omitted or "user": uses your agents.defaults.userTimezone if set, otherwise falls back to the host system timezone.
  • "local": always uses the host system timezone.
  • Any IANA identifier (e.g. America/New_York): used directly. If invalid, falls back to the "user" behavior above.
  • start and end must not be equal for an active window. Equal values are treated as zero-width (always outside the window).
  • Outside the active window, heartbeats are skipped until the next tick inside the window.

Heartbeat configuration is strict: only the fields listed above are accepted. Acknowledgment suppression, reasoning visibility, system-prompt guidance, busy deferral, and tool-error warning behavior are fixed runtime policies rather than heartbeat configuration fields.

Delivery behavior

Session and target routing
- Heartbeats run in the agent's main session by default (`agent:<id>:main`), or `global` when `session.scope = "global"`. Set `session` to override to a specific channel session (Discord/WhatsApp/etc.).
- `session` only affects the run context. Delivery is controlled by `target` and `to`, except for session-owned events (see below).
- A heartbeat-owned node completion whose captured route is still its session's own conversation (for example the Telegram topic where the agent started the command) continues that conversation. It runs in that session with its full context, ignoring `isolatedSession` and `lightContext`, and the reply goes to that conversation, regardless of `target`, `to`, `directPolicy`, and channel `heartbeatVisibility`. A command started during that completion turn belongs to the same conversation. These completions do not wait for the next heartbeat interval, but event turns still start at least 30 seconds apart and at most 5 per minute. The model still stays silent when the result is not worth reporting. Apus's own notices from that turn, such as a run-failure notice, a tool-failure warning, a status line, or a truncation label, still follow the heartbeat's `target`, `isolatedSession`, and `showAlerts` settings, so `target: "none"` or `showAlerts: false` keeps them out of the chat while the model's answer is still delivered. These settings keep governing periodic polls and heartbeat-owned work. A completion without such a route, for example from an automation with `delivery: "none"`, still follows `target`/`to`. To turn off completion turns, set `tools.exec.notifyOnExit: false`.
- A heartbeat wake whose pending events are all session-owned node completions in an internal session (Control UI/WebChat, or another operator-owned session without an external route) publishes the reply into that session's transcript instead of the `target`/`to` channel. `target: "none"` still suppresses it. If the session write fails, the event stays queued for a later wake and does not fall back to the channel. Batches that also contain other events use `target`/`to` as usual.
- The default `owner` target chooses an explicitly configured owner identity. It reuses the exact account/thread only when the session's last route is a direct chat to that owner.
- A wake that carries a channel and recipient uses that named origin before owner discovery. This event destination can be a group because it is explicit, not inferred.
- To deliver to a specific channel/recipient, set a channel `target` plus `to`. `target: "last"` is an explicit opt-in to the last external conversation, including groups.
- Heartbeat deliveries allow direct/DM targets by default. Set `directPolicy: "block"` to suppress direct-target sends while still running the heartbeat turn.
- Scheduled heartbeats skip when the main queue or automation work is busy, any reply or embedded run for the same agent is active, or the resolved target session has active or queued work. Event-free plain monitor polls that have not begun preparation wait for the next persisted cadence tick. Queued events, scheduled tasks, and work already admitted or retained after execution keep their retries. Immediate and manual wakes bypass only the broad same-agent active-run precheck.
- If `owner` has no concrete, DM-capable owner or configured channel, the poll is skipped as `reason=no-route` before the agent runs. Explicit `last` also skips when the session has no external route.
- The first alert delivered by the implicit `owner` default explains periodic checks and how to choose `target: "none"`. Later alerts omit that line.
Visibility and skip behavior
- If the heartbeat turn fails before the model can reply, the failure notice names the reason whenever Apus itself refused the run. One example is a session runtime that is still busy in another runner. Raw provider or runtime errors stay behind the verbose failure-detail setting (`/verbose on` or `/verbose full`), as in normal chats.
- If `showOk`, `showAlerts`, and `useIndicator` are all disabled, the run is skipped up front as `reason=alerts-disabled`.
- If only alert delivery is disabled, Apus can still run the heartbeat, update due-task timestamps, restore the session idle timestamp, and suppress the outward alert payload.
- If the channel readiness check blocks an alert, Apus records the non-delivery. It retries the heartbeat after a one-minute grace period, without consuming its cadence slot. This retry runs the heartbeat again. It does not replay the exact earlier alert. Once a send enters the durable delivery queue, that queue owns transport retries.
- If the resolved heartbeat target supports typing, Apus shows typing while the heartbeat run is active. This uses the same target the heartbeat would send chat output to, and it is disabled by `typingMode: "never"`.
Session lifecycle and audit
- Heartbeat-only replies do **not** keep the session alive. Heartbeat metadata may update the session row, but idle expiry uses `lastInteractionAt` from the last real user/channel message, and daily expiry uses `sessionStartedAt`.
- Control UI and WebChat history hide heartbeat prompts and OK-only acknowledgments. The underlying session transcript can still contain those turns for audit/replay.
- Host background execution resumes through ordinary session execution. Heartbeat-owned node notices and deferred hooks continue to use the heartbeat queue.

Visibility controls

By default, quiet heartbeat acknowledgments are suppressed while alert content is delivered. You can adjust this per channel or per account:

{
  channels: {
    defaults: {
      heartbeatVisibility: {
        showOk: false, // Hide HEARTBEAT_OK (default)
        showAlerts: true, // Show alert messages (default)
        useIndicator: true, // Emit indicator events (default)
      },
    },
    telegram: {
      heartbeatVisibility: {
        showOk: true, // Show OK acknowledgments on Telegram
      },
    },
    whatsapp: {
      accounts: {
        work: {
          heartbeatVisibility: {
            showAlerts: false, // Suppress alert delivery for this account
          },
        },
      },
    },
  },
}

Precedence: per-account → per-channel → channel defaults → built-in defaults.

What each flag does

If all three are false, Apus skips the heartbeat run entirely (no model call).

Per-channel vs per-account examples

{
  channels: {
    defaults: {
      heartbeatVisibility: {
        showOk: false,
        showAlerts: true,
        useIndicator: true,
      },
    },
    slack: {
      heartbeatVisibility: {
        showOk: true, // all Slack accounts
      },
      accounts: {
        ops: {
          heartbeatVisibility: {
            showAlerts: false, // suppress alerts for the ops account only
          },
        },
      },
    },
    telegram: {
      heartbeatVisibility: {
        showOk: true,
      },
    },
  },
}

Common patterns

Goal Config
Default behavior (silent OKs, alerts on) (no config needed)
Fully silent (no messages, no indicator) channels.defaults.heartbeatVisibility: { showOk: false, showAlerts: false, useIndicator: false }
Indicator-only (no messages) channels.defaults.heartbeatVisibility: { showOk: false, showAlerts: false, useIndicator: true }
OKs in one channel only channels.telegram.heartbeatVisibility: { showOk: true }

Monitor scratch (optional)

Each heartbeat automation job owns a private monitor scratch stored in the shared state database. Think of it as your "heartbeat checklist": small, stable, and safe to consider every 30 minutes. When scratch exists, its content is appended to the heartbeat prompt.

Manage it with the automations CLI (the job id comes from apus cron list --all):

apus cron scratch <jobId>                 # print the current scratch
apus cron scratch <jobId> --set "..."     # replace it with exact text
apus cron scratch <jobId> --file notes.md # replace it from a file (- for stdin)
apus cron scratch <jobId> --unset         # remove it

Writes are compare-and-swap guarded: pass --expected-revision <n> to fail instead of overwriting a concurrent edit. Scratch is capped at 256 KiB and never appears in cron list/cron runs output.

The agent can also update its own scratch: during a heartbeat turn, heartbeat_respond accepts an optional scratch string that fully replaces the monitor's scratch for future heartbeats.

Migrating from HEARTBEAT.md or config-only cadence? Run apus doctor --fix. Doctor first creates or updates the system-owned monitor rows from agents.*.heartbeat. It then imports each agent's workspace HEARTBEAT.md into the monitor scratch. It converts any valid legacy tasks: entries into automation jobs. It archives the original under the state directory (backups/heartbeat-migration/) and removes the file. Runtime heartbeat instructions come from database scratch only. The runtime never reads HEARTBEAT.md.

If the workspace and state directory are on different filesystems, Doctor keeps the original file in a private HEARTBEAT.md.doctor-archived.* directory beside its former location. The state-directory backup remains an immutable snapshot. Later writes through an already-open file descriptor remain recoverable in the workspace archive.

Apus skips the heartbeat run to save API calls when scratch exists but is effectively empty. Effectively empty means only blank lines, Markdown or HTML comments, Markdown headings like # Heading, fence markers, or empty checklist stubs. That skip is reported as reason=empty-heartbeat-file. Scheduled interval monitors without due tasks resolve this skip before deferring behind busy execution queues. If no scratch exists, the heartbeat still runs and the model decides what to do.

Keep it tiny (short checklist or reminders) to avoid prompt bloat.

Example scratch:

# Heartbeat checklist

- Quick scan: anything urgent in inboxes?
- If it's daytime, do a lightweight check-in if nothing else is pending.
- If a task is blocked, write down _what is missing_ and ask Peter next time.

Schedule recurring checks with automations

Monitor scratch is prompt context, not a scheduler. Create each recurring check as an automation job so it has its own cadence, enable/disable state, and run history. Automation jobs can still target the main session when the check should use the normal conversation context.

Older scratch may contain a structured tasks: block. Run apus doctor --fix once after upgrading: Doctor converts every valid entry into an independently scheduled automation job. It preserves each entry's interval and previous last-run timing. It removes the retired block and keeps the surrounding scratch prose. Runtime heartbeat turns do not parse tasks: text as schedules.

Doctor-created heartbeat task jobs keep heartbeat active-hours, cooldown, flood, and busy guards. Jobs due together can coalesce into one heartbeat turn. An occurrence outside active hours is skipped and tried again at its next scheduled occurrence.

Can the agent update its scratch?

Yes. During a heartbeat turn, the agent can pass a scratch value to heartbeat_respond to fully replace the monitor scratch for future heartbeats. You can also ask it in a normal chat to run apus cron scratch <jobId> --set ..., or edit the scratch yourself with the same command. Manage recurring schedules with automations instead of writing scheduler syntax into scratch.

Don't put secrets (API keys, phone numbers, private tokens) into monitor scratch - it becomes part of the prompt context.

Manual wake (on-demand)

Use apus system event to enqueue a system event and optionally trigger an immediate heartbeat:

apus system event --text "Check for urgent follow-ups" --mode now
Flag Description
--text <text> System event text (required).
--mode <mode> now runs an immediate heartbeat; next-heartbeat (default) waits for the next scheduled tick.
--session-key <sessionKey> Target a specific session for the event; defaults to the agent's main session.
--json Output JSON.

If no --session-key is given and multiple agents have heartbeat configured, --mode now runs each of those agent heartbeats immediately.

Broadcast completion reports an agent failure even if another agent succeeded or was quietly skipped. Busy retries and guarded deferrals keep their existing retry behavior.

Related heartbeat controls in the same CLI group:

apus system heartbeat last     # show the last heartbeat event
apus system heartbeat enable   # enable heartbeats
apus system heartbeat disable  # disable heartbeats

Cost awareness

Heartbeats run full agent turns. Shorter intervals burn more tokens. To reduce cost:

Context overflow after heartbeat

Heartbeats preserve the shared session's existing runtime model after the run completes. A heartbeat that switched a session to a smaller local model can therefore leave that model in place for the next main-session turn. An Ollama model with a 32k window is one example. That next turn may report context overflow. If the session's last runtime model also matches configured heartbeat.model, Apus's recovery message calls out heartbeat model bleed as the likely cause. The message also suggests a fix.

To avoid this, use isolatedSession: true to run heartbeats in a fresh session. You can combine it with lightContext: true for the smallest prompt. Otherwise choose a heartbeat model with a context window large enough for the shared session.

Related