# Dispatch Protocol
<!--
ref: @protocol/dispatch-protocol
version: 17
updated_at: 2026-11-18T20:12:14.561Z
-->

How a runner gets work from a protocol.supply repo: register, ask, claim, report, wait.

How a runner gets work from a protocol.supply repo: **register, ask, claim, report, wait.** Selection is pull-only: the server never hands out work, never contacts a runner, and never decides whether a runner is alive. It answers questions about its own rows, and a runner's atomic claim decides who does the work. It can ring a doorbell when an impulse you subscribed to changes (§5, *Realtime notification*), but the doorbell carries no work; asking is still how work moves.

## 1. Register (optional)

`PUT /runner/:id` with `{type, pools?, lanes?, tier?, state?, capacity?, capabilities?, note?, staleAfterSec?}`.

- `type` is required. It must be one of `engine|ephemeral|subagent|routine|openclaw|human`.
- This is a full PUT: a field you leave out goes back to its default (`capacity` 1, `staleAfterSec` 7200, lists empty). Unknown fields are a 400.
- `lanes` sets the default assignee scope for your asks (see *Assignee scope* in §2). `pools` names spend sources, which the pace gate meters (§2, *Pools*). Pools never scope which rows you see: a runner with pools and no lanes asks in the `default` scope. `capabilities` sets the default `type` allowlist — defined below.
- Every ask that carries `?runner=<id>` counts as your heartbeat. No separate call is needed. A runner that stays silent longer than `staleAfterSec` reads as `unknown`.

**Asking is enough to be on the roster.** Engines come and go without signing out, so the roster builds itself (2026-11-18; live once the backend deploy that carries V119 ships):

- An ask with `?runner=<id>` from an id with no row creates one: `type` `engine`, `lanes` = the `assignee` list the ask sent, `capacity` undeclared (never gated unless an ask sends `?capacity=`).
- On your own row, an ask fills `lanes` only while the row has none, so a one-off `?assignee=` override never rewrites a registration.
- Silence past `staleAfterSec` (default 7200) reads as `unknown`: gone, for now or for good. The row stays readable, and a lane only it served reads `known: false` in `GET /impulse/assignees`. The next ask brings it back. There is no sign-out call and none is needed.
- An id another account holds is never taken over; your ask is answered as if you had no row. A token pinned to one repo or team, or a learning token, can heartbeat an existing row but cannot create one.

Register with `PUT` when you want more than that: a non-`engine` type, pools, capabilities, a capacity, or a longer `staleAfterSec` for a runner that wakes daily. With no lanes, an ask that names no `assignee` sees only unassigned rows and rows assigned to your own bare handle (§2, *Assignee scope*).

### What `capabilities` actually is

An allowlist over the impulse `type` column, and nothing else. It is not a declaration of skills, tools or models. Matching is exact, case-sensitive string equality against `type`.

**The vocabulary is open — there is no enum.** `capabilities` is validated only as an array of strings, and an impulse's `type` is a free string too, so a value does something only if rows in that repo actually carry it. Types in live use today: `session`, `intent`, `tick-task`, `defect`, `bug`, `escalation`, `task`, `improvement`. A capability nobody files under matches nothing, and **a typo is indistinguishable from an empty backlog** — both answer 204.

**Precedence, in order:**

- `?type=` on the ask wins outright.
- `?exclude_type=` on the ask suppresses the capabilities default entirely — you get the denylist alone, never both filters.
- Otherwise a non-empty `capabilities` becomes the allowlist.
- `capabilities: []` means NO filter: every type is offered. It does not mean "I can do nothing". Registration is a wholesale PUT, so omitting the field clears it to `[]`.

**An active allowlist drops rows whose `type` is null.** The predicate requires a non-null type to match, so untyped work is invisible to any runner that registers capabilities — and untyped rows are common enough to matter (10 of the 200 most recent rows in one live repo). Ask without capabilities, or with an explicit `?exclude_type=`, to see them.

**The filter reports its own effect.** Whenever an allowlist is in force — including one you never typed, because it came from your registration — the response carries `X-Filtered-Type: <n>`, the count of otherwise-eligible rows it removed. A 204 with `X-Filtered-Type: 5` means the work exists and your capabilities hid it; a 204 without the header means there was genuinely nothing.

## 2. Ask — `GET /impulse/next`

The query string is an allowlist. Any other param is a 400.

| param | meaning |
|---|---|
| `repoId` | required; one repo per ask (id or slug) |
| `runner` | who is asking. Required by `state`, `capacity` and `claim=true` |
| `assignee` | the assignees you serve, comma-separated, matched by exact equality, e.g. `owner+runnerA,owner`. Overrides registered `lanes`. Omitted: see *Assignee scope* below |
| `type` / `exclude_type` | comma-separated allow/deny list over impulse `type`. Send at most one of the two; an empty value is a 400 |
| `state` | `idle\|busy\|asleep\|halted`. The server stores it on your roster row |
| `capacity` | how many claims you will hold at once. The server stores it too |
| `limit` | 1–100, default 10. Ignored when `claim=true` |
| `wait` | long-poll seconds, capped at 50 (see §5) |
| `claim` | `true` or `false` only |

**Assignee scope.** Assignee is a boundary the server enforces, not a filter you opt into. Every ask is scoped one of three ways, and the `X-Assignee-Scope` header (on 200 and 204 alike) says which:

- `param`: you passed `?assignee=`. Exactly those values, by equality.
- `registered`: no param, and your runner registered `lanes`. Exactly those lanes.
- `default`: neither. **Unassigned rows (null or empty) plus rows assigned to your own bare handle** (`owner`, never `owner+lane`). This is also the scope of a registered runner with no `lanes`, whatever its `pools`. Rows assigned to another person or to a lane are never in scope, so a row filed for a person cannot be offered to, or claimed by, a runner that never said it serves them.

To get lane work, name it: pass `?assignee=owner+lane` (add `,owner` to keep your own rows), or register `lanes`. An explicit scope does not add unassigned rows; list them separately if you want both. There is no way to ask for the whole repo. `evaluated` counts only the rows in scope.

**Answers**

- **200:** `{evaluated, eligible, rejected, candidates[]}`. Each candidate carries `{id, title, score, priority, cycleKey, cadence, dispatch, type, assignee}`, with no body. Candidates are sorted by score, and ties go to the oldest row.
- **204:** nothing for you. The headers still carry `X-Evaluated` and `X-Eligible`, so an empty estate can be told apart from a gated one. `X-Assignee-Scope` is always there. Other headers you may see: `X-Runner-State`, `X-Free-Capacity`, `X-Filtered-Type`, `X-Pool-Disposition`, `X-Pool-Gated`.
- A state other than `idle`, or zero free capacity, answers **204 immediately**, even when you asked for `wait`. That state stands until a later ask says otherwise.

`claim=true` claims the top candidate atomically and returns `{impulse, claim}`. If another runner wins that candidate, the server moves on to the next one. A 204 with `X-Eligible > 0` means other runners claimed every candidate first.

### Pools: report your meter, and the ask obeys it

A pool is whatever budget you spend from: a subscription window, an API key's quota. The server never reads a provider's meter. You report what you see, and `GET /impulse/next` gates what it serves you on it. There is no pool registration: a pool exists once a reading names it, and you join it by listing its id in `pools` when you register.

**Report:** `POST /pool/{id}/reading` with `{pct, window_sec, resets_at, window_pct?, read_at?, reported_by?}`.
- `pct` is how much of the current window you have used (0–100; above 100 is accepted). `window_sec` is the window's length and is required. `resets_at` is when the window closes, as ISO time.
- `window_pct` is optional usage of a second, longer window. It only feeds `hold`.
- `read_at` is when YOU observed the meter, defaulting to now. Send it when you post late, so an old reading never looks fresh.
- An unknown field is a 400 that names it. The response is the pool's state, so you need no second call before you ask.

**What the server derives** (`GET /pool/{id}` shows it): `expectedPct = 100 × elapsed / window`, and `pace = pct − expectedPct`. The disposition is:

| Disposition | When | What `/impulse/next` serves you |
|---|---|---|
| `open` | pace ≤ +10, or the pool has never had a reading | everything |
| `shy` | pace > +10, or the latest reading is over 2h old (fail-shy) | P0/P1, plus rows with a cadence |
| `hold` | `pct > 90` or `window_pct > 80` | P0/P1 only |

A runner in several pools gets the worst disposition among them. Only a registered runner with `pools` is gated. An unregistered ask, or one with no pools, is never metered.

**Reading the answer.** When you are gated, the ask carries `X-Pool-Disposition: open|shy|hold`. When it isn't `open`, it also carries `X-Pool-Gated: <n>`, the number of rows that were ready and that your pool held back. A `204` with `X-Pool-Gated: 3` means the work exists and your meter is holding it. Post a fresh reading if yours is stale, or wait for the window. A `204` without that header means there was nothing to serve. The gate is not sticky: a new reading that reads `open` serves on the next ask.

## 3. Claim

`POST /impulse/:id/claim` with `{runnerId, cycleKey?, leaseSec?}`.

- **Pass `cycleKey` exactly as the candidate gave it.** Never derive it yourself. The server allows one winner per `(impulse, cycleKey)`, so two runners that derive different keys can both win.
- `''` is the once-ever bucket. A candidate key of `once` also means that bucket, so send `''` for it. An omitted `cycleKey` claims the once-ever bucket as well. Treat an omitted key as a bug unless you mean it.
- The lease defaults to 1800s and is clamped to 30–86400s. When a lease expires, the next claimer takes it over (reaping is lazy). A claim on a `failed` or `released` bucket succeeds as well.
- **201** means you hold the claim. The claim `id` (`iclm_…`) is your fencing token. `wonFresh` is `true` for a fresh cycle and `false` when you took over a reaped or released claim, which means you are picking up someone else's unfinished work. The impulse log also carries a `(reaped prior lease)` note.
- **409 `IMPULSE_CLAIM_HELD`** means another runner holds the claim or the cycle is already done. Back off and do not retry. The 409 body includes `holder` and `expiresAt`.
- **403 `REPO_ACCESS_DENIED`** means you are not allowed to write. **A 403 does not mean another runner won.** Escalate it.

## 4. Report

- **Renew:** `POST /impulse/:id/claim/:claimId/renew` with `{leaseSec?}`. Use it for long work.
- **Complete:** `POST /impulse/:id/claim/:claimId/complete` with `{status?: "done"|"failed", cost?}`. It is idempotent: completing an already-terminal claim returns it unchanged, and the server records `cost` only once.
- **`cost` is an OBJECT, never a bare number** — a number is a 400, and it lands on the final call after the work is done. Fields, all optional, all non-negative numbers: token buckets `input`, `output`, `cache_read`, `cache_create`, `thinking`, plus `ms` (wall time, milliseconds) and `model` (free string, ≤120 chars). Unknown keys are kept on the row rather than rejected. A runner that cannot measure itself omits `cost` entirely — omission is counted, never read as zero.
- **Reading your own trail:** `GET /impulse/:id/log` returns the row's log; `GET /runner/:id` returns your registration. Use these for the reap check instead of guessing at write endpoints.
- **Release:** `DELETE /impulse/:id/claim/:claimId` returns 204. It gives the work back so another runner can claim it.
- If your lease was reaped or replaced, renew, complete and release all return **409 `IMPULSE_CLAIM_LOST`**. When that happens, stop: do not write results and do not claim again to finish.
- **Log:** `POST /impulse/:id/log` with `{action, note?, agent?, cost?, becomes?}`. `action` is a verb of at most 40 characters; prose goes in `note`. Use `becomes` (for example `{status:"completed"}`) to move the row in the same write. A terminal-sounding action that leaves a one-shot row open returns the header `X-Impulse-Log-Warning`.
- **Holder:** `GET /impulse/:id/claim?cycleKey=` returns the current holder or the terminal outcome.

Claim, complete and release each add an entry to the impulse log in the same transaction.

**One-shot work closes twice.** Claim-complete records that YOU did the work; it does not close the row. On a one-shot row (no cadence), close it too: `POST /impulse/:id/complete`, or log your result with `becomes: {status: "completed"}`. A recurring row is the opposite:

**Completing the IMPULSE is not completing your work.** On a recurring row (type `tick-task`, a `cadence`, `expires: never`, `no_auto_park`) the row IS the schedule: completing the impulse deletes the recurrence, not just your cycle. Close your claim (`done`), log your result — and leave the row open. A 2026-09-19 near-miss: an orchestrator instruction "complete the impulses if you ship it" aimed at a daily-refresh tick-task would have silently stopped the refresh forever.

**The server now refuses it** (#272). `POST /impulse/:id/complete` on a row with a live cadence or rrule returns **409 `IMPULSE_RECURRING`**, naming the claim-complete route. Prose alone did not hold: in 2026-09 a W39 pass completed the coaching mission's weekly row, three later passes ran with no work and no alarm, pipe status stayed `ok`, and it took 20 days to notice — a sweep of 974 completed rows then found 26 still carrying a cadence. This class of mistake is invisible after the fact, so the only thing that stops it is a refusal at the write.

The refusal is narrow on purpose, and the distinction is worth knowing: the once-family (`once`, `one-shot`), the sentinels (`manual`, `none`, `on-demand`) and an unparseable cadence all still complete normally, because none of them is a schedule that would fire again. To retire a real recurrence deliberately, re-send with `{"retire": true}` (or `?retire=true`); that logs a `retire-recurrence` entry, so the record says a human meant it.

A cycle counts as taken while its claim is `done` or is `held` with an unexpired lease. Once a claim has `failed`, been released, or expired, the impulse shows up in `/impulse/next` again.

## 5. Wait

- `wait=N` (at most 50) holds the request open while the answer is empty. The server re-runs the query about every 5s and releases its DB connection between passes. Timeout returns a normal 204, not an error. If a response is lost, the runner just asks again.
- Asking again is the only way work *moves*. To hear sooner that something changed, use a realtime notification (below) instead of a tighter poll.

**Realtime notification.** A host can hold one socket and be told when impulses it cares about change. Why one per host: a socket only ever receives what was addressed to it, so the server needs to know which host to address, and the host knows which local session or runner to wake.

1. Register the host once: `POST /impulse/listener {install_key, label}` returns a stable `lstn_` id (an upsert on `install_key`, so a restart keeps its subscriptions).
2. Say what it wants and for whom. A runner's standing interest: `POST /impulse/subscription {listener, lane, assignee | runner}`. One session watching one impulse: `POST /impulse/:id/subscribe {listener, session, expires_in?}` (default 7 days; it also ends when the impulse closes). `DELETE /impulse/subscription/:id` ends one, and `GET /impulse/listener/:id/subscriptions` lists them.
3. Connect socket.io to path `/realtime` with `auth: {token}` (an API token works) and emit `subscribe` with `listener:<lstn_id>`. Only the listener's owner may subscribe to it.
4. Each write arrives as one `message` per listener, `{impulseId, action, actor, agent, via, at, targets:[{lane}|{sessionId}]}`. This is a dirty flag, never the body: re-read the impulse. `agent` is the log agent of the entry the write appended, which lets a runner drop its own echo. `via` is `session` for a signed-in person and `token` for an API token, which is how you tell a person from an agent that shares their token.
5. Realtime is lossy (deploys, reconnects). On every connect, and every few minutes, walk `GET /impulse/listener/:id/events?since=<cursor>`, sending back `next` until `complete`. Advance your cursor only after you have acted on what it returned. The socket tells you sooner, and the catch-up guarantees you are told.
6. A message also carries `logIndex`: the stored 0-based index of the log entry the write appended (null when it appended none). A reaction arrives as `action: "react"`. It is a signal, not work, so never wake a runner for one.

**Reactions.** Slack-style: `POST /impulse/:id/log {action:"react", emoji, target?}` adds any one emoji, and `{action:"unreact", emoji, target?}` takes it back (an appended row, never a delete). A person may hold several emoji on one entry. `target` is the stored index of the entry you are reacting to (a message's `logIndex`); leave it out to react to the impulse itself. A reaction is a log row, so the history is kept, but the page shows it as a chip with a count. It raises no block, resolves none and wakes no runner: to block, still log `blocked` with `blocked_on`. Both actions arrive on the socket and in catch-up as `action: "react"`.

**Status reactions: a runner's live state on a note.** `{action:"react", emoji, status:true, target}` with emoji 👀 (picked up), 🔨 (still working), ✅ (replied or finished) or ⛔ (cannot proceed). There is one per agent per entry, and each replaces that agent's last. Why: the operator wants to see within seconds that his note landed, and then whether it is still moving, ended, or stuck. A status that stays on 👀 after the reply reads as "never finished". The contract:

1. **👀 at pickup.** A host that routes a person's note to a runner posts 👀 on that entry at once, as that runner, without waiting for a model turn.
2. **🔨 at 30s.** If the runner has written nothing on the impulse 30s later, the host flips it to 🔨.
3. **✅ is automatic.** Any non-reaction entry the runner writes on the impulse (its reply, a progress note, anything) closes each of its open 👀/🔨 there as ✅. The server does this in the same write, placed just before the entry, so dispatch still announces the reply. No runner has to remember it.
4. **⛔ is the runner's.** If it cannot proceed, it posts the ⛔ status on the note *and* a log note saying why. Order does not matter: a ⛔ after the auto-✅ replaces it, and a note after the ⛔ closes nothing.
5. **Ended work stays ended.** A 👀/🔨 after that agent's ✅/⛔ on the same entry is a 409 `IMPULSE_STATUS_SUPERSEDED` and writes nothing, so a late timer cannot reopen a reply. Treat that 409 as success.

`status` is only valid with those four emoji, on `react`, and is never unreacted (send the next status instead).

**A page watching one impulse** subscribes to `impulse:<ipls_id>`. Anyone who can read the impulse's repo may subscribe, and only the server publishes. Every write sends `{impulseId, action, agent, via, logIndex, at}`: refetch the row on each one.
- **Halt:** ask with `state=halted`. You get 204 immediately, and the server stops routing work to you until a later ask sends `state=idle`.
- Keep the fleet's long-polls few. Each replica has a small DB pool, so prefer one shared asker over one parked poll per runner.

**Waiting on another runner's work.** `POST /impulse/:id/wait` with `{waiter, note?}` registers you as blocked on that impulse (idempotent per waiter; `DELETE /impulse/:id/wait?waiter=` withdraws, `GET /impulse/:id/waiters` lists who waits). `GET /impulse/waiting?waiter=<you>` lists what you are still waiting on, oldest first; each item carries `openedAt`, `ageSec` and `stale` (past `?older_than=<sec>`, default 86400). `?since=<iso>` returns what landed instead, so polling it is your notification. `?stale=true` with no waiter lists every unanswered ask you can see.

**Where work came from.** When work begins as a message, create the impulse with `origin: {platform, channel, thread_id?, message_id?, url?, actor?}`. `platform` is one of `slack | peer | email | web | cli | human`; for `peer`, `channel` is the asking runner and `thread_id` its dispatch or claim id. It is immutable once set (a different origin gets a 409). It is echoed by `/impulse/next` and on completion, so the runner that finishes can answer into the thread it came from. Find it again with `GET /impulse?origin.platform=&origin.thread_id=`.

## A minimal runner loop

1. `GET /impulse/next?repoId=R&runner=runnerA&state=idle&assignee=owner+runnerA&wait=50`
2. For each candidate, `POST /impulse/:id/claim` with its `cycleKey` unchanged. A 409 means skip it; a 403 means escalate.
3. Do the work, renewing the lease if it runs long. Then complete with `done` or `failed`, or release it.
4. When halted, ask with `state=halted` and run nothing.

<!--
sources (protocol backend/src unless noted):
controller/ImpulseController.ts:408 NEXT_QUERY_PARAMS; :417-441 state/capacity need runner; :444-478 type/exclude_type; :502-514 claim=true;
  :516-522 wait cap; :1076-1250 /impulse/next handler (204 on non-idle/zero-free :1138-1145, limit :1112, claim-in-one :1234-1246);
  :320-325 ClaimBody; :1794-1871 claim/renew/complete/release routes; :1614-1686 POST :id/log; :1873-1892 GET :id/claim
service/ImpulseDispatchService.ts:44-60 DispatchCandidate; :62-73 NextResult; :103-104 MAX_WAIT_SEC=50, 5s poll; :125-140 waitForNext; :177-188 ready rows cycleKey ''; :248-256 sort
service/ImpulseClaimService.ts:14-19 lease default/clamp; :81-103 attemptClaim + log; :115-131 claimFirstAvailable; :138-159 409 HELD body; :162-237 renew/complete/release, LOST
repository/ImpulseClaimRepository.ts:52-56 CLAIM_BLOCKS_DUE_SQL; :84-101 reapable ON CONFLICT
service/RepoAccessService.ts:196-205 403 REPO_ACCESS_DENIED
controller/RunnerController.ts:24-44 PUT /runner/:id; service/RunnerService.ts:20 body keys, :103-131 defaults; model/Runner.ts:18,24 types/states
support/CycleKey.ts:45-57 once -> '' bucket
reference client scripts: claim.sh:410-433 once->"" mapping, exit codes; dispatch-pipe.sh:91-92, shell-runner.sh:186-189 ask shape
-->

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*