Agent governance
The controls on this page, per-session limits, required trace ids, agent identity and the kill switch, need a Spanway enterprise license that includes the agent_governance feature. Without it, creating or updating an agent that turns one of them on answers 403 and names the control, and the kill switch and identity routes answer 403. Clearing a control never needs the feature. An agent declared in config.yaml without the feature is still registered, but its governance controls are dropped and the gateway logs an error naming them, and max_iterations in key metadata is ignored. Registering agents, their agent cards, invoking them over A2A, enabling and disabling them, their overall rpm_limit and tpm_limit and their spend stay free. Sensitive data sticky routing is not part of the feature.
An agent registered with POST /v1/agents is a first class caller. Keys can be bound to it with agent_id, JWTs can name it through agent_id_jwt_field, and the gateway applies the agent's own limits on top of the key's. The controls on this page are the ones that keep an agentic loop from running away or acting outside its mandate.
A real-world scenario
A release bot runs as an agent and calls the model in a loop until the release notes are done. One night a bad prompt sends it into an endless loop that keeps calling the model and spending money. With governance in place, the bot's sessions are capped at 25 model calls and 2.50 dollars each, so the runaway session stops on its own with a 429. The on-call engineer then presses the kill switch, which disables the agent and blocks its keys at once, and the audit log records who stopped it and why.
Step by step
-
In the Admin UI open Agents under Agentic and click Add New Agent, or open an existing agent to edit it.
-
On the Governance step, under Budgets & Rate Limits, set Max Iterations to 25 and Max Budget Per Session ($) to 2.50, switch on the trace id requirement, and finish with Create Agent. The same agent can be created with curl, as shown in Per-session limits.
-
Give the agent's key to the bot, and have the bot send a session id on every call, for example in the
x-spanway-trace-idheader. -
To stop the agent, open it on the Agents page and click Stop Agent in its danger zone, or call the kill switch:
curl -X POST "http://localhost:4000/v1/agents/$AGENT_ID/kill_switch" \-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \-d '{"key_action": "block", "reason": "runaway loop"}'
Expected result
The 26th model call in one session, or the first call after the session's spend reached 2.50 dollars, answers 429, while other sessions of the same agent keep working. A call without a trace or session id header answers 400. After the kill switch the agent shows a Disabled badge, its blocked keys answer 401 with Authentication Error, Key is blocked. Update via /key/unblock if you're an admin., the kill switch answer lists the blocked key hashes in affected_tokens, and the audit log holds a kill_switch_fired row naming the admin and the reason.
Per-session limits
Agents work in sessions. The gateway reads the session id from the x-spanway-trace-id header first, then x-spanway-session-id, then a vendor header such as x-claude-code-session-id, then Codex's session-id or thread-id. The session limits also accept metadata.session_id in the body, but the trace id requirement below checks headers only, so an agent that must send a trace id sends it as a header. Three limits are set in the agent's spanway_params and enforced per session, shared across gateway instances through Redis.
curl -X POST http://localhost:4000/v1/agents -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{
"agent_name": "release-bot",
"agent_card_params": {"name": "release-bot", "description": "Prepares release notes", "url": "https://agents.example.com/release-bot"},
"spanway_params": {
"max_iterations": 25,
"max_budget_per_session": 2.50,
"require_trace_id_on_calls_by_agent": true
},
"session_rpm_limit": 60,
"session_tpm_limit": 200000
}'
| Limit | Where | Effect |
|---|---|---|
max_iterations | spanway_params, or key metadata for older setups (the key metadata fallback also needs the feature) | Counts LLM calls per session. The call that exceeds the cap gets 429. A counter is kept for an hour after the session's last call, set with SPANWAY_MAX_ITERATIONS_TTL, so a session that goes quiet for longer starts again at zero. |
max_budget_per_session | spanway_params | Accumulates the cost of each successful response per session. Once the total reaches or exceeds the cap in dollars, further calls in that session get 429. The total is kept for an hour after the last call, set with SPANWAY_MAX_BUDGET_PER_SESSION_TTL. |
session_rpm_limit, session_tpm_limit | Top level agent fields | Requests and tokens per minute per agent session, enforced by the same rate limiter as key and team limits. rpm_limit and tpm_limit cap the agent as a whole. |
require_trace_id_on_calls_by_agent | spanway_params | On, any model or MCP call made with a key bound to the agent must carry a trace or session id header, or it answers 400, so every call can be attributed to a session. Off (the default), no header is needed. The session limits above need it on to count calls per session. |
require_trace_id_on_calls_to_agent | spanway_params | On, a call to the agent over A2A without a trace or session id header answers 400, which keeps sub-agent runs joined to the run that started them. Off (the default), callers may omit it. In the Admin UI it is the Require x-spanway-trace-id on calls TO this agent switch. |
Set general_settings.missing_session_id to generate to have the gateway stamp an id on requests that arrive without one, reject to refuse them with 400, or omit to leave the session empty in the request logs instead of falling back to the trace id. The settings reference lists the session timeouts.
Agent identity
An agent can be bound to a Microsoft Entra ID application, or to an application of any OpenID Connect provider, so that only tokens issued to that application may act as the agent. An OpenID Connect binding supports autonomous agents only, see agent identity providers.
{
"agent_name": "release-bot",
"identity": {
"provider": "microsoft_entra",
"tenant_id": "f1c2...",
"client_id": "9a7b...",
"required_roles": ["Agent.Release"],
"required_scopes": ["user_impersonation"]
},
"execution_mode": "delegated"
}
An agent in autonomous or both mode also needs service_principal_id, the Object ID from Enterprise applications in Entra (not the one under App registrations), or the create answers 400 Autonomous mode requires the Enterprise application service-principal object ID. Agent identity providers walks through it.
execution_mode is autonomous for an agent that calls with its own application token, delegated for one that calls on behalf of a signed in user, or both. The tenant's issuer must already be trusted by JWT auth, either through spanway_jwtauth.issuers or the global JWT_ISSUER and JWT_AUDIENCE, and GET /v1/agents/identity/providers returns the issuers that qualify. GET /v1/agents/{agent_id}/identity reports the binding, whether it is active, the execution mode and when the agent last authenticated. The binding is kept with a revision so that a rotated application cannot reuse an old one, and spanway_params.identity from earlier releases is rejected in favour of the top level field.
Stored credentials
An agent can hold its own API keys and tokens for MCP servers and SaaS tools, so it never borrows a person's key or one shared key. Admins rotate and revoke them, and Suspend all credentials stops all of them at once without stopping the agent's model access. Agent credentials explains it.
Kill switch
POST /v1/agents/{agent_id}/kill_switch, proxy admin only, stops an agent at the gateway. It needs a license with the agent_governance feature. In order, it
- disables the agent, so a key bound to it is rejected and the agent cannot be invoked,
- blocks every key whose
agent_idis the agent (including keys bound to a config.yaml agent's legacy id), or deletes them with"key_action": "delete", and evicts them from the auth cache on every replica, - stops the agent's workflow runner steps, and a gateway-hosted custom agent stops its running runs before their next model or tool call,
- calls the agent's
kill_switchwebhook when one is configured.
The gateway halt always happens before the webhook, so a slow or broken webhook never leaves the agent running at the gateway. The body is optional.
curl -X POST "http://localhost:4000/v1/agents/$AGENT_ID/kill_switch" \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{"key_action": "block", "reason": "leaking data"}'
{
"agent_id": "8b6c...",
"durable": true,
"key_action": "block",
"affected_tokens": ["88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b"],
"failed_tokens": [],
"halted_workflow_runs": 1,
"reason": "leaking data",
"store_error": null,
"webhook": {"agent_id": "8b6c...", "url": "https://agents.example.com/release-bot/stop", "method": "POST", "status_code": 502, "response_body": "bad gateway", "error": null}
}
The answer is 200 whenever the gateway halt succeeded, even when the webhook failed, and the webhook result is in webhook (null when none is configured). affected_tokens are the hashed keys that were blocked or deleted, already blocked keys are left out so a restore unblocks exactly what the switch blocked, and failed_tokens are keys a delete could not remove. halted_workflow_runs is null when the workflow runner could not be reached. When the agent row cannot be disabled, durable is false and the agent is held disabled on the replica that served the call. That hold is checked before the database row, survives the periodic registry reload, and lasts until that replica restarts or the agent is re-enabled through it with PATCH or PUT. Other replicas keep serving the agent. A config.yaml agent has no database row, so it is always held this way and setting enabled: false in its config makes the halt stick everywhere. When the database step fails, store_error is agent_halt_store_unavailable, no key is blocked or deleted, and the workflow steps are still stopped and the webhook is still called, so call the switch again once the database is back. When a delete stops part way, store_error is agent_key_delete_failed, the agent row is still disabled, every bound key is listed in failed_tokens and evicted from the auth cache, and some of them may already be gone. store_error only ever holds one of these two codes, and the database error itself goes to the proxy log. The halt is written to the audit log as one kill_switch_fired row on the agent with the whole result, where the key action is stored as halt_action so secret redaction leaves it readable, and one blocked or deleted row per key.
To restore the agent, set enabled back to true with PATCH /v1/agents/{agent_id}, unblock each hash in affected_tokens with /key/unblock, and release the workflow runner with POST /v1/workflows/runner/agents/{agent_id}/release. Deleted keys cannot be restored, so issue new ones.
In the Admin UI the agent's page shows the kill switch under its danger zone. The confirm dialog shows how many keys will be blocked or deleted, a stopped agent shows a Disabled badge, and Restore re-enables the agent and unblocks the keys its last kill switch blocked, read from that kill_switch_fired audit row. Restore re-enables the agent first and only unblocks the keys once that worked. For a config.yaml agent it only unblocks the keys, because the agent has no row to re-enable and stays held on the replica that stopped it until that replica restarts. When audit logs are off and the switch was not fired from the same page, Restore only re-enables the agent and the keys have to be unblocked by hand. Restore does not release the workflow runner.
enabled: false is enforced for every agent, not only identity-managed ones. A key bound to a disabled agent is rejected with 403 and invoking a disabled agent is refused with 403. Before this release an ordinary agent with enabled: false still served its keys, so check for disabled agents whose keys you expect to keep working before upgrading.
Webhook
An agent can carry a kill_switch, a webhook the operator wants called to stop the agent where it runs.
{
"kill_switch": {
"url": "https://agents.example.com/release-bot/stop",
"method": "POST",
"headers": {"x-reason": "operator"},
"query_params": {},
"body": {"action": "stop"},
"auth": {"type": "bearer", "token": "..."}
}
}
auth is bearer with a token, api_key with header_name and api_key, or basic with username and password. Secrets are stored once and echoed back redacted, and an update that sends the redaction marker keeps the stored secret. The call has a ten second timeout, and the result carries the status code and up to 2,000 characters of the response body.
Sensitive data sticky routing
A guardrail that detects sensitive data can route the conversation to another model instead of blocking it.
guardrails:
- guardrail_name: pii-to-onprem
spanway_params:
guardrail: presidio
mode: pre_call
on_sensitive_data: route
sensitive_data_route_to_model: onprem-llama
sticky_session_routing: true
When the guardrail fires, the request is rewritten to sensitive_data_route_to_model and the decision is stored against the session id and tenant for an hour, configurable with the SPANWAY_SENSITIVE_ROUTING_TTL environment variable, shared across instances through Redis. A pre-call hook then rewrites the model of every later request in that session, so once a conversation has touched personal data it stays on the on-premise model even when later turns look harmless. sticky_session_routing: false applies the override to the single request only.
Endpoints
{{ops:^/v1/agents/(identity/providers)$|^/v1/agents/{agent_id}/(identity|kill_switch)$}}
Admin UI
The Agents page under Agentic creates and edits agents, including the session limits, identity binding and kill switch, and shows per agent usage from /agent/daily/activity. Only proxy admins see the create, edit and delete actions and the danger zone, because the routes behind them answer 403 for every other role. Without the agent_governance feature the trace id switches, Max Iterations, Max Budget Per Session, the session rate limits, the identity provider and the Stop Agent button are locked, and a note on each says which license feature unlocks them. The overall TPM and RPM limits stay editable because they are free. Workflow runs and memory sit next to it.
Errors
| Status | Message | Meaning and fix |
|---|---|---|
| 403 | The 'agent_governance' feature needs a Spanway enterprise license that includes it. It covers ... | Creating or updating an agent that turns on one of these controls needs the feature. Add it, or leave the controls off. |
| 429 | A session limit message | The session passed max_iterations, max_budget_per_session, session_rpm_limit or session_tpm_limit. Start a new session, or raise the limit. |
| 400 | Requests made with this agent's key must include the x-spanway-trace-id header. | The agent requires a trace id on its calls. Send the header, metadata.session_id in the body is not enough. |
| 400 | Agent '<id>' requires x-spanway-trace-id header on all inbound requests. | The agent requires a trace id on calls to it. Send x-spanway-trace-id or x-spanway-session-id with the A2A call. |
| 401 | Authentication Error, Key is blocked. Update via /key/unblock if you're an admin. | The kill switch blocked the key of a stopped agent. Re-enable the agent and unblock or reissue its keys when it is safe. |
| 403 | Agent is disabled or Invoked agent is disabled | The agent was disabled, by the kill switch or with enabled: false, but this key was not blocked. Re-enable the agent. |
| 403 | A kill switch call from a non admin | The kill switch is proxy admin only. |
In the Admin UI, open Agents under Agentic, open the agent and use its danger zone for the kill switch. The session limits are on the agent's edit form.
Logs
| Level | Line | Meaning | Action |
|---|---|---|---|
| ERROR | Agent '<name>' in config.yaml sets <controls> ... Those controls are not enforced. | A config.yaml agent turns on governance controls the license does not cover, so the gateway registered it without them. | Add the agent_governance feature, or remove the controls from the config. |
| WARNING | MaxIterationsHandler: rejecting request, Redis could not verify the session count, or MaxBudgetPerSessionHandler: rejecting request, Redis GET could not verify the session spend | Redis did not answer, and with fail_closed_rate_limit_enforcement on the call was refused with 503. | Restore Redis. Turn the setting off only if per-instance counting is acceptable. |
| WARNING | MaxIterationsHandler: Redis failed, falling back to in-memory: ... | Redis did not answer and the session was counted on this instance only. | Restore Redis, limits are not shared across replicas meanwhile. |
| ERROR | Error adding agent to db: ... | Saving an agent failed, and the caller got Saving the agent failed. The gateway log has the cause. | Read the database error after the colon. |
Audit
Agent changes write audit rows on Spanway_AgentsTable: created, updated and deleted with the agent before and after, secrets redacted. The kill switch writes one kill_switch_fired row on the agent and one blocked or deleted row on Spanway_VerificationToken per key. Find them on the audit log:
curl "http://localhost:4000/audit?table_name=Spanway_AgentsTable&object_id=$AGENT_ID" -H "Authorization: Bearer $SPANWAY_ADMIN_KEY"
Related
- Agents page for the Admin UI.
- Agent credentials for an agent's own keys for MCP servers and SaaS tools.
- Run ledger to see what a stopped agent did.
- Agent identity providers.