> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xenovia.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Policies

> Hard rules in Rego, attached to agents, run at the model request or response.

Decide what your agents can never do. Policies are your hard rules; [Neon](https://docs.xenovia.io/control/neon.md) catches what no rule named. Each starts in Monitor, so you see what it would block before you Enforce it.

For example, this policy blocks any request that offers the model a tool named `delete_database`:

```rego theme={null}
package xenovia

import future.keywords.if
import future.keywords.in

default decision = {"action": "allow"}

decision = {"action": "block", "rule": "no-delete-database"} if {
    some tool in input.tool_names
    tool == "delete_database"
}
```

## Create a policy

**1. Open the form**

On **Policies**, click **Create policy**. If the button reads **Create with Nova**, open its menu and choose **Create manually**.

**2. Write the rule**

Under **Start from**, choose **Blank policy** and paste the rule, or start from a template.

**3. Name it and pick its stage**

Give it a **Policy name** and set **Runs at** to **Model request** or **Model response**.

**4. Pick its agents and mode**

Under **Agents**, add your agents. **Starts in** defaults to **Monitor**, which records what the policy would do without acting on it.

**5. Create it**

Click **Create custom policy**. A policy that covers an agent is on as soon as it is created.

![Create policy form with a blank policy named No delete database, Runs at Model request, Starts in Monitor, and its Rego](https://mintcdn.com/xenovia/RO5UF1Tk8L9B7yPt/images/screens/policies-create.png?fit=max\&auto=format\&n=RO5UF1Tk8L9B7yPt\&q=85\&s=d6725867d2095ff9f986d5dba202265f)

The Create policy form

## Monitor, then Enforce

Every control in Xenovia can watch before it acts. A policy, a Neon risk family, the agent's purpose check and each guardrail has a mode:

* **Monitor** records what it would have done, on the session and in its counts, and changes nothing.
* **Enforce** acts: it blocks, redacts or escalates.

Start in Monitor, read what would have been blocked in [Sessions](https://docs.xenovia.io/observability/sessions.md), then switch to Enforce. For a policy, open its **Agents** tab and set **Mode** for each agent. When you choose to enforce, the dashboard shows, per agent, how many calls it would have blocked in the last 7 days. For Neon, use the agent's **Neon** tab. Testing a policy before you save it is covered in [Test a policy](#test-a-policy); testing a whole agent against attacks is [Simulation](https://docs.xenovia.io/simulation.md).

## How policies run

Xenovia evaluates [Open Policy Agent (OPA)](https://www.openpolicyagent.org/) Rego policies on every call to an agent. You write a policy once in the control plane and attach it to one or more agents. Each policy runs at one stage, chosen under **Runs at** when you create it:

* **Model request**: checks the prompt, the tools offered and the tool results before the model is called.
* **Model response**: checks the model's reply and the tool calls it proposes before your app gets them.

Policies run before [Neon](https://docs.xenovia.io/control/neon.md) at the same stage. A policy block stops the call before Neon sees it, and a policy redaction is applied before Neon judges the material. With the [Python SDK](https://docs.xenovia.io/sdk/quickstart.md), request-stage policies also run on `model_request` checks, and response-stage policies on `model_response` and `tool_call` checks.

Enabled policies are compiled into each agent's configuration. Each runtime instance revalidates that configuration at least every five minutes. OPA compiles with a 2-second timeout, and enforced policies get 200 milliseconds per stage to evaluate. If an enforced policy fails to evaluate (an error, a conflict or a timeout), the call is refused with `503`. Monitor policies are evaluated on their own budget and never affect the call.

## Policies, agents and modes

A policy covers every agent on its **Agents** tab. Each agent there has its own **Mode**:

* **Enforce** acts on that agent's calls.
* **Monitor** records what the policy would do and changes nothing. Its would-be decision is recorded on the trace.

So one policy can be enforced for some agents and in monitor mode for others. Use monitor mode to trial a policy against live traffic before enforcing it. When you choose to enforce, the dashboard shows, per agent, how many calls it would have blocked in the last 7 days.

A policy created in the dashboard starts in the mode you pick under **Starts in** (Monitor by default). A policy with no agents stays in your library. You can only enable a policy that covers an active agent, and removing its last agent turns it off.

| API | What it does |
| - | - |
| `POST /api/v1/policies` | Creates a policy. `enforcement_mode` defaults to `enforce`; `agent_ids` attaches it |
| `PUT /api/v1/policies/{policy_id}/agents` | Replaces the agents it covers (`{"agent_ids": [...]}`, up to 200) |
| `PUT /api/v1/policies/{policy_id}/agents/{agent_id}/mode` | Sets one agent's mode (`{"enforcement_mode": "monitor"}`). An agent without its own mode uses the policy's |
| `POST /api/v1/policies/{policy_id}/enable`, `/disable` | Turns the policy on or off |

### The policy page

| Tab | What it shows |
| - | - |
| **Overview** | Calls evaluated, blocked or would have blocked, and evaluation time (median and p95) over the last 7 days, with decisions per day and the latest decisions |
| **Rule** | The Rego and its **Rule versions**. Each save is a new version. Compare an older version with the live one, or restore it |
| **Agents** | Each agent, its decisions over the last 7 days and its mode |
| **Activity** | Every change to the policy, newest first |

Through the API, `GET /api/v1/policies/{policy_id}/versions` lists the versions, newest first. `GET /api/v1/policies/{policy_id}/stats?days=7` returns the decision counts (1 to 30 days), and `GET /api/v1/policies/{policy_id}/activity` returns the change history.

## The decision contract

A policy returns a single `decision` object. This is the only value the runtime reads. `allow`/`deny` rules and a bare `redact_fields` set are ignored.

```rego theme={null}
package xenovia

import future.keywords.if
import future.keywords.in

# Allow by default; a matching rule below overrides it.
default decision = {"action": "allow"}

decision = {"action": "block", "rule": "no-delete-tools"} if {
    some tool in input.tool_names
    tool == "delete_database"
}
```

* Write `package xenovia`. The control plane strips your `package` line and re-packages the rule under a system namespace, so the package name you choose does not matter.
* `action` says what to do. `rule` is a short identifier recorded on the trace and returned in `X-Xenovia-Reason` as `policy:<rule>`. Any other key (including `reason`) is ignored by the runtime.
* Multiple complete `decision` rules must have mutually exclusive conditions. If two can be true at once with different values, OPA reports a conflict and the call fails closed. Guard each rule with distinct conditions, for example on `input.sub_agent.name`.
* A policy whose `decision` is undefined for a call (no rule matched and there is no default) allows it.

> [!NOTE]
>
> When you save, the Rego is compiled with `opa check --strict`. A policy is also refused if it defines no `decision` rule, or if it writes an `action` the runtime doesn't know. Each of these returns `422` with the diagnostics.

## Actions

| Stage | `action` | Effect |
| - | - | - |
| Request | `allow` | Forward to the model |
| Request | `block` | Refuse the call and record the trace |
| Request | `redact` | Mask the listed fields in messages and tool definitions, then forward |
| Request | `escalate` | Refuse the call and record an escalation (see [Escalations](#escalations)) |
| Response | `allow` | Return the reply |
| Response | `block_response` | Withhold the reply and record the trace |
| Response | `redact_response` | Mask the listed fields in the reply, then return it |
| Response | `escalate` | Withhold the reply and record an escalation |

A refused call gets a `200` refusal, not an error (see [What a block looks like to your app](https://docs.xenovia.io/observability/sessions.md#what-a-block-looks-like-to-your-app)). At the response stage, `block` and `redact` are read as `block_response` and `redact_response`.

When several enabled policies run at the same stage, the strongest action wins. At the request stage, `block` beats `escalate`, which beats `redact`, which beats `allow`. At the response stage the order is `block_response`, `escalate`, `redact_response`, then `allow`. The redact fields of every redacting policy are combined.

An action outside the stage's list, such as `deny` or a response action at the request stage, fails closed. The runtime treats it as a block and records the error on the trace.

### Redaction

Return the labels to strip in `redact_fields`:

```rego theme={null}
package xenovia
import future.keywords.if
import future.keywords.in

default decision = {"action": "allow"}

decision = {
    "action": "redact",
    "rule": "mask-contact-details",
    "redact_fields": ["email", "phone"],
} if {
    some msg in input.messages
    contains(msg.content, "@")
}
```

Supported labels: `email`, `ssn`, `phone`, `creditcard` (Luhn-validated), `ip`, `url`. At the request stage, redaction applies to message text, tool descriptions and the Responses `instructions` field. At the response stage it applies to the reply text. Streamed replies are buffered and checked before any content is sent, so response redaction applies to them too.

## Test a policy

When you create a policy in the dashboard, **Test with a sample call** runs the rule as written against a sample call in JSON. Nothing is saved.

Through the API, pass up to 50 `conformance_cases` when you create or update a policy. Each case has a `name`, an `input` in the policy input shape (a subset is fine) and an `expect` with an `action` and, optionally, a `rule`. The cases run when you save, and a failing case refuses the save with `422`.

## Policy input

Both stages receive the same base fields, and each stage adds its own. `GET /api/v1/agents/{agent_id}/schema/policy-input` lists the fields for one agent, with the stage each is available at.

> [accordion] Base fields (both stages)
>
> ```json theme={null}
> {
>   "agent_id":         "string — the agent's ID",
>   "org_id":           "string — organization ID",
>   "request_type":     "chat_completion | chat_completion_stream | responses | responses_stream",
>   "provider":         "the provider's type as configured (openai, anthropic, azure, microsoft-foundry, bedrock, vertex, together, ...); see Supported providers",
>   "provider_adapter": "the API the runtime used to reach it (openai, anthropic, azure, bedrock, openai_compatible, ...)",
>   "provider_host":    "the upstream host, e.g. api.together.xyz",
>   "model_family":     "anthropic | openai | gemini | llama | mistral | ... or empty when unknown",
>   "model":            "the model the runtime will call — the provider's configured model, not the value your client sent",
>   "stream":           "boolean",
>   "messages":         "[{ role, content, tool_call_id?, tool_call_ids? }] — text only",
>   "messages_text":    "string — the text of every message, joined by newlines",
>   "tools":            "[{ name, type, family, description, parameters_schema, server_host?, allowed_tools? }]",
>   "tool_names":       "[]string — the names of the tools your app declared, exactly as sent",
>   "system_prompt":    "string — first system message, if any",
>   "http_headers":     "object — request headers, lowercase, with secret values redacted",
>   "sub_agent":        "{ id, name, kind, parent_agent_id } or null — see Sub-agents",
>   "caller_sub_agent": "{ id, name } or null — on a linked call",
>   "caller_agent_id":  "string — the calling agent, only on a linked call",
>   "agent_depth":      "int — from the x-xenovia-agent-depth header, 0 if absent",
>   "enforcement_stage": "model_request | model_response, or tool_call for an SDK check",
>   "workflow_context": "{ workflow_id, decisions: [{ agent_id, trace_id, policy_action, timestamp }] } — only with an X-Xenovia-Workflow-Id header"
> }
> ```

`input.tools` lists every declared tool. `family` is `function` or `custom` for tools your code runs. For a tool the provider runs, it is the hosted tool family, such as `web_search` or `mcp` (see [Hosted tools](https://docs.xenovia.io/control/hosted-tools.md#restrict-hosted-tools)). `input.tool_names` lists only named tools, so a hosted tool such as web search may be in `tools` but not in `tool_names`. The sub-agent fields are described in [Sub-agents](https://docs.xenovia.io/agents/sub-agents.md#policy-fields). With the SDK, `input.payload` holds the payload your code sent.

> [accordion] Request stage adds
>
> ```json theme={null}
> {
>   "request":             "object — the normalised request (parameters under request.params)",
>   "request_flat":        "object — the same request flattened to dotted keys",
>   "request_max_tokens":  "int — requested output cap, 0 if unset",
>   "tool_results":        "[{ tool_call_id, name, content }] — tool results in the request, on Chat Completions and Responses",
>   "agent_tokens_today":  "int — running token count for this agent today",
>   "session_tokens_used": "int — running token count for this session"
> }
> ```

> [accordion] Response stage adds
>
> ```json theme={null}
> {
>   "stage":  "response",
>   "output": {
>     "content":    "string — the reply text",
>     "tool_calls": "[{ id, name, arguments }]"
>   },
>   "tool_args_json": "string — the proposed call's arguments, or a JSON array of them for several calls",
>   "usage":          "{ input_tokens, output_tokens, total_tokens }"
> }
> ```

## Examples

### Block a tool

```rego theme={null}
package xenovia
import future.keywords.if
import future.keywords.in

default decision = {"action": "allow"}

decision = {"action": "block", "rule": "no-destructive-tools"} if {
    some tool in input.tool_names
    startswith(tool, "delete_")
}
```

### Allow only known-safe tools

```rego theme={null}
package xenovia
import future.keywords.if
import future.keywords.in

default decision = {"action": "allow"}

safe := {"db_read", "get_user_profile", "list_records"}

decision = {"action": "block", "rule": "tool-allowlist"} if {
    some tool in input.tool_names
    not safe[tool]
}
```

`input.tool_names` lists the names of the tools your app declared, exactly as sent; comparisons are case-sensitive. A hosted tool such as web search may be in `input.tools` without a name in `input.tool_names`, so use `tool_names` for your own tools and the [hosted tool allow-list](https://docs.xenovia.io/control/hosted-tools.md) for the provider's.

### Escalate a destructive tool for human attention

```rego theme={null}
package xenovia
import future.keywords.if
import future.keywords.in

default decision = {"action": "allow"}

decision = {"action": "escalate", "rule": "destructive-tool-review"} if {
    some tool in input.tool_names
    tool == "delete_account"
}
```

A policy escalation refuses the call and records an [escalation](#escalations) for review.

### Require the agent's model to be on an allowlist

```rego theme={null}
package xenovia
import future.keywords.if
import future.keywords.in

default decision = {"action": "allow"}

approved := {"gpt-4o", "gpt-4o-mini", "claude-sonnet-4-20250514"}

decision = {"action": "block", "rule": "model-allowlist"} if {
    not approved[input.model]
}
```

`input.model` is the model configured on the agent's provider, so this rule guards against an agent routed to an unapproved model rather than a client choosing one.

### Cap output tokens (request stage)

```rego theme={null}
package xenovia
import future.keywords.if

default decision = {"action": "allow"}

decision = {"action": "block", "rule": "output-cap"} if {
    input.request_max_tokens > 2000
}
```

### Block a refusal in the reply (response stage)

```rego theme={null}
package xenovia
import future.keywords.if

default decision = {"action": "allow"}

decision = {"action": "block_response", "rule": "no-refusal"} if {
    input.stage == "response"
    contains(input.output.content, "I cannot help")
}
```

## Templates

Instantiate a shipped template with its parameters instead of writing Rego. Several cover tool access directly, for example an approved-tool allowlist, tool-argument PII blocking, and tool-argument size caps.

Thirteen templates were removed because the runtime never produces the inputs they read, or because they always escalated: `pii-pattern-block`, `rapid-call-rate-block`, `repeat-denial-escalation`, `anomalous-tool-pattern-escalation`, `tenant-boundary-match`, `external-disclosure-consent-gate`, `block-shadow-model-fallback`, `low-confidence-escalation`, `high-risk-tool-human-approval`, `financial-threshold-escalation`, `eu-ai-act-fundamental-rights-review`, `destructive-tool-confirmation`, and `workflow-intent-aggregate-escalate`. Policies you already created from them are unchanged; review whether they can still fire.

## Neon and guardrails

Policies are deterministic rules. [Neon](https://docs.xenovia.io/control/neon.md), Xenovia's decision model, judges each stage after them. It checks its trained risks, the guardrails you write in plain language, and the agent's purpose and capabilities. Set it up on the agent's **Neon** tab. See [Neon](https://docs.xenovia.io/control/neon.md) for its stages, settings and what happens when it can't be reached.

## Escalations

`escalate` is for actions you want flagged for human attention. When a policy escalates:

1. The call is refused: a request-stage escalation refuses the request, and a response-stage escalation withholds the reply. Your app gets the refusal described above.
2. An escalation is recorded, carrying the agent and the matched rule.
3. Any alert rule with the **Policy escalation** trigger fires.

A Neon guardrail with the action **Allow and flag for review** records an escalation the same way but lets the call go on. It fires alert rules with the **Guardrail escalation** trigger.

Open escalations are listed under **Escalations** in **Sessions**, and a session with one shows **Waiting for approval**. Choose **Resolve escalation** to close it with a note. Through the API, use `GET /api/v1/escalations` (filter with `status=open` or `resolved`) and `POST /api/v1/escalations/{escalation_id}/resolve` with an optional `note`.

> [!WARNING]
>
> There is no approve/deny queue. Resolving an escalation records your note; it doesn't release or replay the call. A policy escalation has already refused the call, and a guardrail escalation has already let it through. After review, adjust the policy or guardrail.

## Recommended controls

* **Least privilege.** Blocklist high-risk tools explicitly rather than trusting a broad allowlist, and turn on **Restrict hosted tools** for agents that don't need provider-run tools.
* **Separate by environment.** Use different agents, or different policies on one agent, for `dev`, `staging`, and `prod`. Never share production credentials.
* **Flag irreversible actions.** A policy `escalate` refuses deletions, financial writes and cross-system state changes and records them for review. A Neon guardrail with **Allow and flag for review** lets them through and records them. Either way they show up in Sessions.
* **Review from evidence.** Traces show which tools are actually called. Remove rules for tools that no longer appear.

## What next?

> [card] [Neon](https://docs.xenovia.io/control/neon.md)
>
> Catch what no rule named.

> [card] [Hosted tools](https://docs.xenovia.io/control/hosted-tools.md)
>
> Limit the tools the provider runs.

> [card] [Sessions](https://docs.xenovia.io/observability/sessions.md)
>
> See what a policy blocked, or would have.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.