# Spend cap

> **Managed services.** Spend caps are available with Polyant managed services.

**Spend cap** is a section of the agent's *Governance* group, at `?tab=budget`, between Retention and GDPR opt-out. It holds the amounts, in USD, at which the agent stops calling the model, and the message it sends when it stops. The workspace and the organization each have a **Spend cap** page too, in their sidebar's *Governance* group (`…/workspaces/{ws}/settings/budget`, `/organizations/{org}/budget`): there you set the default cap every agent below follows, and a total for all of those agents together (see [Organization and workspace caps](#organization-and-workspace-caps)).

It sits under Governance rather than beside [Analytics](https://docs.polyant.ai/admin-panel/analytics) because Analytics reports what was spent, while a cap is a rule that stops the agent. Like [Retention](https://docs.polyant.ai/admin-panel/retention), it is a limit with its own form and its own Save.

Anyone who can read the agent (`agent:read`) can open the section and see the caps and what the open windows have cost so far: knowing the cap is part of knowing why an agent went quiet. Changing a cap or the stop message requires `agent.governance:write`, held by Admin and above. Without it the fields are shown read-only. Raising a cap spends the customer's money and lowering one can silence the agent, which is why the write sits on the governance permission rather than on `agent:write`.

## The caps

Every field is optional. **An empty field means no cap** for that window. An agent with every field empty follows the default cap of its workspace or organization, and has no limit at all when neither sets one, which is how every agent starts. A value must be an amount greater than zero: `0`, a negative number or text is refused with the field marked, rather than read as "no cap", because the save replaces the whole budget and a dropped figure would remove a limit the operator believed they had set.

### Caps per window

One field per calendar window: **Per hour**, **Per day**, **Per week**, **Per month**, **Per quarter**, **Per four months** and **Per semester**. These caps are agent-wide: every model call made for the agent counts toward them. Beside each field the panel shows what has been spent in the window open right now.

The windows are **fixed calendar buckets**, not sliding ones, because "the agent resumes when the next window opens" only means something if the window has an opening. They are anchored to the calendar year and read in the **agent's time zone**, the one set under Advanced → Behaviour overrides (the deployment's `TZ` when the agent sets none), so a daily cap follows the customer's day:

| Window | Opens |
|---|---|
| Hour | at the start of each local hour |
| Day | at local midnight |
| Week | Monday at local midnight (ISO weeks) |
| Month | on the 1st of each month |
| Quarter | January, April, July, October |
| Four months | January, May, September (January to April, May to August, September to December) |
| Semester | January and July |

Daylight-saving changes are handled in the agent's zone, including the hour that repeats when clocks go back.

### Caps per contact

The same seven windows, applied **separately to every contact**. Use it when one customer must not be able to spend what is meant for everyone.

The engine has no identity for a person across channels, so a contact here is one chat on one channel: the conversation key `<agent>:<channel>:<chat>`. A person who keeps writing from the same Telegram or WhatsApp chat keeps one counter, and that counter survives across days and windows. The same person reaching the agent from another channel, or a Web or API client that sends a new `chat_id`, starts a separate counter, and the members of a group chat share one. The cap therefore limits what one chat can spend; it cannot stop a caller who is free to open new chats, which on the HTTP and OpenAI-compatible endpoints is any caller holding the agent's key. Pair it with a window cap on the whole agent when that matters.

### Cap per conversation

One amount for the **whole conversation**, with no window. It is the defence against a single conversation that spins, such as a tool loop that keeps restarting. A conversation that reaches it stays stopped until the cap is raised or removed, since there is no next window to wait for.

### Stop message

What the agent says when a cap stops it, up to 2,000 characters. Write it in the language the agent speaks. Left empty, the agent uses the message of its workspace or organization, and otherwise the default, shown as the placeholder: *"I have reached the usage limit set for me. I will resume when it resets."*

## Organization and workspace caps

The organization's and the workspace's **Spend cap** pages hold two different things.

**Default cap for each agent.** The same windows, contact caps, conversation cap and stop message as an agent's. Agents without a cap of their own follow it: the workspace's default over the organization's, an agent's own caps over both. Nothing is copied into the agents, so changing the default changes every agent that follows it at once. The caps are taken as one set: an agent that sets any cap of its own replaces the inherited set whole, it does not add to it. An agent cannot override an inherited default with "no cap"; to loosen it, it sets a higher figure. The stop message is inherited on its own, so an agent that sets caps but no message uses the message of the level above.

The default has a lock: **Allow a different value in workspaces and agents** on the organization, **Allow a different value for individual agents** on the workspace. It is on by default. Turned off, a lower level cannot change its caps or its message: the API answers `409` with `code: "setting_locked"`, and the panel shows **Locked by the organization** (or **by the workspace**) with the value in force. A value a lower level saved before the lock stays stored but is not applied; removing it is always allowed. On an agent that follows a level above, the panel shows one line with the inherited value and an **Override** link; once the agent holds its own caps, **Back to the inherited value** removes them.

**Total.** A cap **Per day**, **Per week** or **Per month** on the spend of all the agents of the organization (**Total for the whole organization**) or of the workspace (**Total for this workspace**), added together. Every model call of those agents counts toward it. When a total is reached, none of those agents calls the model until the window reopens, even if its own cap has not been reached. A total is not inherited and not covered by the lock: the organization's total and a workspace's total both apply, and a workspace may set its own total under an organization lock. Totals are counted on **UTC** calendar days, ISO weeks and months, because one total adds up agents that may each have a different time zone. A total set partway through a window starts from what its agents have already spent in that window.

The agent's own section lists, under **Totals that count for this agent**, each total above it with what it has cost so far. The organization's home shows the spend against the organization total to a caller who reaches every workspace; one bound to only some workspaces sees the cap without the spend, which would reveal what the other workspaces cost.

| Level | Read | Write (save, remove) |
|---|---|---|
| Organization | `org.governance:read` (every role) | `org.governance:write` (Admin and Owner) |
| Workspace | `agent:read` | `agent.governance:write` |

The workspace's **Spend cap** tab is listed to callers who hold `agent.governance:write` there. **Remove the cap** on either page removes both the default and the total of that level.

## When a cap is reached

Before each model call the engine compares committed spend with every cap that applies to that call: the agent's caps in force (its own or inherited) and the totals of its workspace and organization. When one of them is reached, the call is refused, and the agent answers with the stop message in force for it, whichever cap stopped it:

- **Before the turn's first call**, the stop message is the whole reply. The message is still examined by the agent's input governance first, at no cost, because the cap refuses the semantic classifier calls too while the deterministic gates run as usual. A message the gates allow is saved in the conversation with the stop message, like any other answer, so both are still there after a reload; a message the gates block, or one a classifier could not examine, is not stored.
- **In the middle of a turn**, inside the tool loop, the loop stops and the stop message is appended after whatever the agent had already said. On a streaming channel the reader sees the partial answer and then the stop message.

Each stop is stored as a governance event from the `spend-limit` gate, with the cap that was reached (its window, and its level when it is a contact, workspace or organization cap) and the amounts. It survives a restart and is listed in the [Monitor](https://docs.polyant.ai/admin-panel/activity) of the workspace and the organization as a spend-limit stop. A client that keeps retrying a stopped agent records one stop per agent and conversation per minute.

A window cap applies to the agent's background work too (memory extraction, titles, summaries, event matching, embeddings), so an agent at its daily cap stops all model calls until the day turns. Output and tool classifier calls inside a turn that was already admitted are charged but never refused, so reaching a cap cannot switch those governance gates off.

Speech-to-text is admitted the same way, before it runs: once a cap is reached the voice note is not transcribed and the sender gets the stop message.

### When the agent resumes

- **At the next window.** A window cap lifts on its own when the next window opens.
- **At once, if you raise the cap.** Saving a higher figure (or clearing the field) takes effect on the next call, on the agent or on the workspace or organization above it. On a deployment with several engine replicas, the replica that handled the save applies it immediately and the others within about 15 seconds; a lowered cap takes the same few seconds to bite.

A cap set partway through a window starts from what the agent has **already spent in that window**, so setting a monthly cap on the 20th does not hand the agent the full amount a second time.

## Soft caps

Spend caps are **soft caps**, and there is **no guaranteed bound on the overshoot**:

- They are checked against **committed spend**, the cost of calls that have already finished and been counted. A call is admitted when committed spend is below the cap, and is not stopped for what other calls are spending at the same moment.
- **Calls already in flight finish.** Several calls admitted together can each read the same headroom and all complete, and the next call is the one refused.
- **Counting can lag.** Completed calls are reconciled in batches on later admissions, so while a backlog catches up a few more calls can be admitted than the cap would allow.

The panel's own help text describes the overshoot as bounded by the cost of the calls in progress. Treat that as the usual case, not a guarantee: set the cap below the amount that must never be exceeded.

A **failed or aborted** model call is charged for the steps it completed. A multi-step call that dies at the provider on step five has already been billed for four, and a turn cancelled and restarted because the user sent a follow-up has been billed for what it did before the restart. Both count toward the caps.

If the engine cannot read the counters at all (a database error), it lets the call through uncounted rather than silencing the agent, and reports the fact as a `spend-limit` warning on the live activity feed (not stored, so it is not a Monitor row) and an error in the engine log. While that lasts, the agent has no spend protection.

## Which calls count

| Call | Window caps | Contact caps | Conversation cap |
|---|---|---|---|
| A turn in a real conversation, including its tools and sub-agents | yes | yes | yes |
| A background (service) call for a real conversation: memory extraction, title, summary | yes | no | yes |
| A [Room](https://docs.polyant.ai/admin-panel/room) cycle, a [scheduled task](https://docs.polyant.ai/admin-panel/scheduled-tasks), an agent-to-agent call, a webhook turn | yes | no | no |
| A voice-note transcription (speech-to-text) | yes | no | yes |
| An embedding call (knowledge ingestion, memory, retrieval) | yes | no | no |

Every call in the table also counts toward the totals of the agent's workspace and organization. Service calls count agent-wide and never per contact. Room, scheduler, agent-to-agent and webhook conversations are never treated as a contact, and the conversation cap applies only inside a real conversation. A transcription is billed on the audio's duration, and every one the provider processed counts, including one that comes back empty.

The figures can differ from [Analytics](https://docs.polyant.ai/admin-panel/analytics#cost-counts-every-billed-call): both sum what failed and pre-empted calls had already cost, but a cap's day or month follows the agent's time zone while Analytics renders in your browser's.

### Phone calls

A [phone call](https://docs.polyant.ai/admin-panel/channels#voice-phone-calls) is only partly under the caps. The agent's turns and the call's text model count like any other conversation. The speech and transcription by ElevenLabs, the turn detection by Deepgram and the Typesafe judges are billed by those providers outside the caps and are not logged. A call stays connected after a cap is reached, and the engine limits neither the number of concurrent calls nor their length. Set usage limits at those providers, and a concurrency limit on the Twilio number, before publishing it.

## Status checks

The agent's [Status](https://docs.polyant.ai/admin-panel/instances#status) section raises these checks, each pointing back to this section:

| Check | Severity | Fires when |
|---|---|---|
| **Spend cap reached ({period})** | Broken | committed spend in an agent-wide window has reached its cap. New calls are blocked until the next window opens or the cap is raised |
| **Near the spend cap ({period})** | Warning | committed spend in an agent-wide window is at 80% of its cap or more |
| **No spend cap** | Note | no cap applies to the agent at all (its own, an inherited default, or a workspace or organization total) and it made model calls in the last seven days |

Only the agent-wide window caps in force raise the first two checks, inherited ones included; a workspace or organization total does not. A contact or a conversation that reaches its own cap is an ordinary event rather than a state of the agent, and one check per conversation would bury the page.

## REST API

| Method | Path | Permission |
|---|---|---|
| `GET` | `/api/instances/{slug}/budget` | `agent:read` |
| `PUT` | `/api/instances/{slug}/budget` | `agent.governance:write` |
| `DELETE` | `/api/instances/{slug}/budget` | `agent.governance:write` |
| `GET` | `/api/organizations/{org}/workspaces/{ws}/budget` | `agent:read` |
| `PUT`, `DELETE` | `/api/organizations/{org}/workspaces/{ws}/budget` | `agent.governance:write` |
| `GET` | `/api/organizations/{org}/budget` | `org.governance:read` |
| `PUT`, `DELETE` | `/api/organizations/{org}/budget` | `org.governance:write` |

On an agent, `GET` returns the agent's own caps, the stop message the agent will actually use, the open agent-wide windows of the caps in force with what each has cost, the totals above the agent, and in `effective` the caps in force with the level they come from:

```json
{
  "limits": {},
  "ownStopMessage": null,
  "stopMessage": "I have reached the usage limit set for me. I will resume when it resets.",
  "stopMessageIsDefault": true,
  "windows": [
    { "period": "day", "limitUsd": 50, "spentUsd": 12.4 }
  ],
  "totals": [
    { "level": "organization", "period": "month", "limitUsd": 5000, "spentUsd": 1830.2 }
  ],
  "effective": {
    "limits": { "periods": { "day": 50 }, "conversationUsd": 2 },
    "source": "workspace",
    "lockedBy": null,
    "ownInactive": false,
    "inherited": { "source": "workspace", "limits": { "periods": { "day": 50 }, "conversationUsd": 2 }, "stopMessage": null }
  }
}
```

`source` is `organization`, `workspace`, `agent` or `null` (no cap in force). `lockedBy` names the level whose lock applies, and `ownInactive` is true when the agent stored caps or a message that a lock keeps from applying.

`PUT` takes `{ "limits": {...}, "stopMessage": "..." }` and **replaces the agent's whole budget**: a window left out has no cap of the agent's own afterwards. The period keys are `hour`, `day`, `week`, `month`, `quarter`, `four_month` and `semester`. Amounts must be positive numbers, an unknown key inside `limits` is refused with `400`, and an empty or missing `stopMessage` leaves the agent without a message of its own. Under a lock it answers `409` with `code: "setting_locked"`. `DELETE` removes the agent's own caps and message, so it follows the level above again.

On an organization or a workspace, `PUT` takes `{ "limits": {...}, "stopMessage": "...", "allowOverride": true, "totalLimits": { "day": 100, "month": 2000 } }`. `allowOverride` is required (`false` is the lock), and `totalLimits` accepts only `day`, `week` and `month`. A workspace write that changes the default under an organization lock is refused with `409`; a change to its total alone is accepted. The workspace `GET` also returns the organization's cap above it and `lockedBy`. Each write at every level is recorded in the [management audit log](https://docs.polyant.ai/admin-panel/audit-logs) with the new figures.

## See also

- [Analytics](https://docs.polyant.ai/admin-panel/analytics) - what the agent spent, by period.
- [AI Gateway](https://docs.polyant.ai/concepts/ai-gateway) - how each call is priced and logged.
- [Retention](https://docs.polyant.ai/admin-panel/retention) - the other limit in the Governance group.
