
# AI Agents

An agent is an autonomous AI actor that operates **as a virtual user** inside your app. Each agent binds to an auth role, is restricted to an explicit allowlist of tables and actions, and can be gated by human approval, run on a schedule, and bounded by operational limits. Agents are declared under the top-level `app.agents[]` array.

Agents require `app.auth` to be configured (they are stored as auth users) and `AI_PROVIDER` to be set.

```yaml
agents:
  - name: support-agent
    role: support
    systemPrompt: You are a courteous support assistant. Resolve tickets accurately.
    tools:
      tables: [tickets, customers]
      actions: [record.read, record.update, email.send]
    approval:
      mode: selective
      required: [email.send]
    limits:
      maxActionsPerMinute: 20
      maxTokensPerDay: 100000
```

## Agent-as-User Model

Each agent is materialized at runtime as an `auth.user` record with `type: 'agent'` and a synthetic email (`{name}@agents.sovrium.local`). This is the foundation of agent security:

- The agent **inherits every table and field permission of its assigned role**, exactly like a human user.
- Agents **cannot authenticate** via any login endpoint (email/password, magic link, OTP).
- Agent actions appear in the activity log with `actor.type = 'agent'`.
- Agent users are excluded from the user list by default, and included only when `?includeAgents=true` is passed.

Agent user records are managed automatically: created on first startup, updated when the role changes, and soft-deleted when the agent is removed from config.

## Definition Properties

The core identity fields are inlined at the top level of each agent entry.

| Property       | Description                                                                                     |
| -------------- | ----------------------------------------------------------------------------------------------- |
| `name`         | Unique kebab-case identifier (e.g. `support-agent`). Lowercase letters, digits, single hyphens. |
| `role`         | Auth role the agent operates as. Must reference a role in `auth.roles`.                         |
| `systemPrompt` | System prompt defining the agent's personality, role, and rules.                                |
| `instructions` | Optional array of behavioral instructions, appended as numbered rules to the system prompt.     |
| `model`        | LLM model override (defaults to `AI_MODEL`).                                                    |
| `temperature`  | Temperature override, `0`–`1` inclusive (defaults to `AI_TEMPERATURE`).                         |
| `maxTokens`    | Max output tokens override (defaults to `AI_MAX_TOKENS`).                                       |
| `enabled`      | Whether the agent can execute. Defaults to `true`. Disabled agents skip scheduled runs.         |

## Tools & Double-Gate Security

The `tools` block is the agent's capability allowlist. Sovrium enforces a **double-gate** security model — both gates must pass:

1. **RBAC gate** — does the agent's role have permission for this table/action?
2. **Allowlist gate** — is this table/action listed in the agent's `tools`?

An agent with no `tools` has **no access** (secure by default).

| Property        | Description                                                              |
| --------------- | ------------------------------------------------------------------------ |
| `tools.tables`  | Table names the agent can access (at least one; must exist in `tables`). |
| `tools.actions` | Action types the agent can perform (at least one; see below).            |

### Available Actions

Actions follow the `type.operator` pattern used by the automation engine.

| Category   | Actions                                                                                  |
| ---------- | ---------------------------------------------------------------------------------------- |
| **Record** | `record.read`, `record.create`, `record.update`, `record.delete`                         |
| **State**  | `state.get`, `state.set`, `state.increment`, `state.delete`, `state.list` (cross-run KV) |
| **HTTP**   | `http.request`                                                                           |
| **AI**     | `ai.generate`, `ai.classify`, `ai.extract` (chain LLM sub-tasks)                         |
| **Code**   | `code.runTypescript` (sandboxed)                                                         |
| **Email**  | `email.send`                                                                             |
| **Auth**   | `auth.createUser`, `auth.assignRole`, `auth.banUser`, `auth.unbanUser`                   |
| **File**   | `file.upload`, `file.download`, `file.delete`, `file.list`, `file.getMetadata`           |

## Permissions: Who Can Invoke the Agent

The optional `permissions` block describes the agent's RBAC integration and who may trigger it.

| Property                  | Description                                                                                |
| ------------------------- | ------------------------------------------------------------------------------------------ |
| `permissions.type`        | User-type discriminator — always `agent`.                                                  |
| `permissions.trigger`     | Who may invoke this agent: `all`, `authenticated`, or a role array like `[admin, member]`. |
| `permissions.emailDomain` | Domain for the synthetic agent email (defaults to `agents.sovrium.local`).                 |

## Human-in-the-Loop Approval

The `approval` block gates agent actions behind human review.

| Property              | Description                                                                                |
| --------------------- | ------------------------------------------------------------------------------------------ |
| `approval.mode`       | `none` (execute immediately), `all` (every action needs approval), or `selective`.         |
| `approval.required`   | Actions requiring approval (a subset of `tools.actions`). Required when `mode: selective`. |
| `approval.timeout`    | Seconds before a pending approval expires (default `3600`).                                |
| `approval.escalation` | Escalation when an approval stays pending — `{ after: <seconds>, to: <role> }`.            |

```yaml
approval:
  mode: selective
  required: [record.delete, email.send]
  timeout: 1800
  escalation:
    after: 600
    to: admin
```

:::callout
**Escalation `after` must be less than `timeout`.** An approval that is not actioned within `after` seconds escalates to the `to` role; if still unactioned by `timeout`, it expires.
:::

## Scheduled Execution

The `schedule` block makes an agent run automatically at a cron interval. The `taskPrompt` is sent to the LLM as the user message on each run.

| Property              | Description                                                            |
| --------------------- | ---------------------------------------------------------------------- |
| `schedule.cron`       | Standard 5-field cron expression (e.g. `*/15 * * * *`, `0 9 * * MON`). |
| `schedule.timezone`   | IANA timezone identifier (defaults to `UTC`).                          |
| `schedule.taskPrompt` | Prompt sent to the LLM on each scheduled execution.                    |

```yaml
schedule:
  cron: '0 9 * * MON'
  timezone: Europe/Paris
  taskPrompt: Summarize last week's new tickets and post the digest.
```

Scheduled runs respect `enabled` (disabled agents skip them) and `approval` (e.g. `mode: all` pauses the scheduled run for human sign-off).

## Operational Limits

The `limits` block caps resource consumption to prevent runaway agents. All fields are optional and fall back to system defaults.

| Property                     | Default  | Description                                         |
| ---------------------------- | -------- | --------------------------------------------------- |
| `limits.maxActionsPerMinute` | `30`     | Maximum DB/email actions per minute.                |
| `limits.maxTokensPerDay`     | `200000` | Maximum LLM tokens per 24h. Resets at midnight UTC. |
| `limits.maxConcurrentTasks`  | `5`      | Maximum simultaneous task executions.               |

## Memory, Knowledge, and MCP

Agents compose with three further capabilities, each documented in its own page:

| Block       | Purpose                                                                      | Docs                                        |
| ----------- | ---------------------------------------------------------------------------- | ------------------------------------------- |
| `memory`    | Conversation history, RAG knowledge retrieval, and persistent learned facts. | [AI Memory](/en/docs/ai-memory)             |
| `knowledge` | Tables and documents to embed as the agent's RAG knowledge base.             | [AI RAG](/en/docs/ai-rag)                   |
| `mcp`       | Allowlist of external MCP tools the agent may invoke.                        | [MCP Integration](/en/docs/mcp-integration) |

## Multi-Agent & Invocation

Agents can be invoked from the AI chat interface (a named `ai-chat` component), via API, on a schedule, and from automations through the [`ai:agent` action](/en/docs/automation-ai-actions). Because each agent is a distinct virtual user with its own role and tool allowlist, multiple agents can coexist with different privilege boundaries — a read-only analyst agent and a write-capable triage agent, for example.

## Full Example

```yaml
agents:
  - name: data-analyst
    role: analyst
    systemPrompt: You are an expert data analyst. Be precise and cite the records you used.
    instructions:
      - Never expose customer PII in summaries.
      - Prefer aggregates over row-level dumps.
    tools:
      tables: [orders, customers]
      actions: [record.read]
    approval:
      mode: none
    limits:
      maxActionsPerMinute: 20
      maxTokensPerDay: 150000
    schedule:
      cron: '0 7 * * *'
      timezone: UTC
      taskPrompt: Produce the daily orders summary.
```

## Related Pages

- [AI Overview](/en/docs/ai-overview) — the full AI ecosystem.
- [AI Providers](/en/docs/ai-providers) — model, temperature, and token defaults agents inherit.
- [AI Chat](/en/docs/ai-chat) — embed an agent as a conversational panel.
- [AI Memory](/en/docs/ai-memory) — agent conversation, knowledge, and facts.
- [AI RAG](/en/docs/ai-rag) — knowledge sources agents embed.
- [MCP Integration](/en/docs/mcp-integration) — agents as MCP clients.
- [AI Actions](/en/docs/automation-ai-actions) — the `ai:agent` automation action and AI action vocabulary.
- [Roles & RBAC](/en/docs/auth-roles-rbac) — the role permissions agents inherit.
