# Data models: agents and system

Agent tokens, identity and audit, the Agent Bridge, and system configuration. Part of the [data model reference](./index.md).

## AgentToken, Agent, AgentAudit

**File:** `agent.py` · **Tables:** `agent_tokens`, `agent_token_vaults`,
`agents`, `agent_audit` · **Migration:** `c4e9a7f2b1d3` · **Exposure:**
REST `/api/v1/connections/...`, user only; never through MCP

Agent identity of Phase A ([Agent authentication](../../agents/authentication.md),
[Agent permissions](../../agents/permissions.md)).

`AgentToken`: a local personal access token. Tokens are revoked, never
deleted.

| Field | Type | Notes |
|---|---|---|
| `name`, `description` | String(120), Text | User's labels |
| `lookup` | String(12) | Unique, indexed; the `phm_pat_<lookup>` part |
| `digest` | String(64) | `HMAC-SHA256(pepper, secret)` hex; the secret is never stored |
| `grants` | JSON | `{resource: [action, ...]}`, validated by `GrantSet.parse` |
| `all_vaults` | Boolean | Default false; otherwise `agent_token_vaults` lists the vaults |
| `expires_at` | DateTime (tz) | Null: never expires |
| `last_used_at`, `last_used_ip` | DateTime (tz), String(64) | Recorded at most every 15 s per address |
| `revoked_at`, `revoked_reason` | DateTime (tz), String(32) | `user` or `rotated` |
| `rotated_from_id` | FK `agent_tokens.id` | `SET NULL` |

`agent_token_vaults`: (`token_id`, `vault_id`) primary key, both `CASCADE`
(deleting a vault removes it from every token).

`Agent`: one client using one token, unique per (`token_id`,
`client_key`); `client_key` is the `clientInfo.name` of `initialize`, empty
when the client sent none.

| Field | Type | Notes |
|---|---|---|
| `public_id` | String(24) | Unique, `agt_<16 base32>`; the id the API uses |
| `token_id` | FK `agent_tokens.id` | `CASCADE`; moves to the new token on rotation |
| `display_name` | String(120) | From `clientInfo.title` / name at first sight; user may rename |
| `implementation`, `implementation_version` | String(160), String(64) | Declared by the client |
| `connection_type` | String(16) | `mcp` (Bridge, provider, remote later) |
| `protocol_version` | String(32) | Declared in `initialize` |
| `declared_capabilities` | JSON | Client capabilities as declared (bounded to 4 KB) |
| `status` | String(16) | Last recorded state (`connecting`, `connected`, `disconnected`); the shown status is computed (`services/agents/status.py`) |
| `first_seen_at`, `last_seen_at`, `last_ip`, `disconnected_at` | DateTime (tz), String(64) | Activity |
| `consecutive_failures` | Integer | Failed or refused operations in a row; 3+ shows `degraded` |

`AgentAudit`: one audited operation. `vault_id` is a plain integer (no
foreign key) so the trail survives a deleted vault; `agent_id` and
`token_id` are `SET NULL`.

| Field | Type | Notes |
|---|---|---|
| `actor` | String(8) | `agent`, `dev` or `user` |
| `transport` | String(16) | `mcp`, `rest`, `in-process` |
| `operation` | String(64) | Tool name, resource URI template, `initialize`, `authenticate`, `token.create`… |
| `resource`, `action` | String(24), String(16) | The grant checked |
| `outcome`, `error_code` | String(8), String(48) | `ok`, `denied`, `error` and the error code |
| `object_refs` | JSON | `*_id` / `*_ids` arguments only; never other arguments or content |

Indexes: `(created_at, id)`, `(agent_id, id)`, `(vault_id, id)`. Bounded to
the newest 20 000 rows and 90 days.

---

## Agent Bridge models

**Files:** `bridge.py`, `bridge_work.py`, `bridge_events.py` · **Migration:**
`d8f2a6c4e1b9` (additive) · **Exposure:** REST `/api/v1/bridge/...`, MCP
inbox tools ([Agent Bridge protocol](../../agents/bridge-protocol.md))

`AgentConversation` (`agent_conversations`): `vault_id` (`CASCADE`),
`title` (200), `agent_id` (FK `agents`, `SET NULL`) or `provider_id`
(String 64, Phase D), `pinned`, `archived_at`, `share_context` (default
true; false for agent-opened), `created_by_kind` / `created_by_agent_id`,
`last_seq` (incremented with each message), `last_event_id`,
`last_message_at`. Indexes `(vault_id, archived_at, last_message_at)`,
`(agent_id, vault_id)`.

`AgentMessage` (`agent_messages`): `conversation_id` (`CASCADE`),
`vault_id`, `seq`, `sender_kind` (`user`, `agent`, `provider`,
`system`), `sender_agent_id`, `sender_key` (`user`, `agent:<id>`,
`provider:<id>`), `type`, `content` (Text, 64 000 characters), `refs`
(JSON references), `task_id` (`SET NULL`), `delivery` (`queued`,
`delivered`, `failed`), `failed_reason`, `delivered_at`, `failed_at`,
`attempts`, `streaming`, `completed_at`, `idempotency_key` (128).
Unique `(conversation_id, seq)` and `(conversation_id, sender_key,
idempotency_key)`; index `(delivery, conversation_id)`.

`AgentTask` (`agent_tasks`): `vault_id`, `conversation_id` (`SET NULL`),
`requested_by_kind` / `requested_by_agent_id`, `assigned_agent_id`,
`action` (200), `instructions` (20 000), `context_refs`, `state`
(`app/core/bridge/tasks.py`), `state_reason`, `progress` (`{percent,
text}`), `result_text`, `result_refs`, `error` (`{code, message}`),
`attempts`, `max_attempts`, `lease_id` (32 hex), `lease_expires_at`,
`deadline_at`, `sensitive`, `started_at`, `completed_at`,
`cancel_requested_at`. Indexes `(vault_id, state)`, `(assigned_agent_id,
state)`, `(state, lease_expires_at)`.

`AgentApproval` (`agent_approvals`): `vault_id`, `conversation_id` and
`task_id` (`CASCADE`), `message_id` (the request message, `SET NULL`),
`requested_by_agent_id`, `operation`, `resources`, `grant`, `reason`,
`state` (`pending`, `approved`, `denied`, `expired`), `expires_at`,
`decided_at`, `decided_by` (`user`), `note`.

`AgentEvent` (`agent_events`): `id` (AUTOINCREMENT: the resume cursor,
never reused), `vault_id`, `conversation_id`, `agent_id` (plain ids, no
foreign keys), `type`, `payload` (ids and small fields), `created_at`.
Written in the transaction of each change; the newest 50 000 rows and 30
days are kept. Indexes `(agent_id, id)`, `(created_at)`.

`WorkspaceContextRecord` (`workspace_contexts`): the last workspace context
of a vault (`vault_id` unique, `CASCADE`), `window`, `version`,
`context` (references and light summaries), `published_at`.

---

## AiProvider, AiUsage

**File:** `ai_provider.py` · **Tables:** `ai_providers`, `ai_usage` ·
**Migration:** `e2a7c9f4b6d1` · **Exposure:** REST
`/api/v1/connections/providers` (user only; [Model providers](../../agents/model-providers.md))

`AiProvider`: `kind` (`openai`, `anthropic`, `deepseek`, `gemini`,
`openai_compatible`, `ollama`, `lmstudio`), `display_name`, `base_url`,
`mode` (`remote` | `local`), `local_host` / `local_port` (the authorised
destination of a local provider), `model`, `context_limit`,
`max_output_tokens` (2048), `timeout_seconds` (60),
`price_input_per_mtok` / `price_output_per_mtok` (nullable),
`budget_conversation_tokens` / `budget_daily_tokens` (nullable),
`enabled`, `secret_hint` (last four characters, never the credential),
`agent_id` (FK `agents`, `SET NULL`), `token_id` (FK `agent_tokens`,
`SET NULL`), `last_test_at` / `last_test_ok` / `last_test_code` /
`last_test_error`.

`AiUsage`: `provider_id`, `conversation_id`, `vault_id` (plain ids, so
usage survives deletion), `model`, `input_tokens`, `output_tokens` (as
reported), `estimated_cost` (from the pricing at the time; null without
pricing). Indexes `(provider_id, created_at)`, `(conversation_id)`.

Phase D also added `agent_tokens.purpose` (`pat` | `provider`, default
`pat`) and `auto_approve` (JSON list of `resource.action`),
`agent_conversations.model`, `sharing_confirmed_at`, `allowed_tools`, and
`agent_messages.share_sensitive`. The downgrade revokes provider tokens
before dropping `purpose`.

---

## SystemConfig

**File:** `system_config.py` · **Table:** `system_configs` · **Migration:**
`e2a7c9f4b6d1` · **Exposure:** none (no route, tool or resource reads it)

A key/value configuration store with optional Fernet encryption, used for
model provider credentials (`ai_provider.<id>.credential`, group
`ai_provider_credential`, always encrypted with the configuration key by
`app/services/providers/secrets.py`). Other settings the workstation
persists use [AppSetting](traffic.md#appsetting).

| Field | Type | Notes |
|---|---|---|
| `key` | String(255) | Not null, unique, indexed |
| `value` | Text | Not null, encrypted when `is_encrypted` |
| `description` | String(500) | Nullable |
| `is_encrypted` | Boolean | Default `False` |
| `group` | String(100) | Default `'general'` |
| `created_at` | DateTime (tz) | Overrides the base column: not null, `server_default=now()` |
| `updated_at` | DateTime (tz) | Overrides the base column: not null, `server_default=now()`, `onupdate=now()` |

**Methods:** `set_value(raw_value, encrypt=False)`, `get_value()`.

The Fernet key comes from `PHANTOM_CONFIG_KEY` (a Fernet key in the
environment) or, without it, from the key file `CONFIG_KEY_FILE`
(`~/.phantom/config.key` by default), created once with mode 0600 on first
use (`app/core/config_key.py`). It is resolved lazily, never at import. A
key that is present but invalid raises `ConfigKeyError` instead of being
replaced, so values encrypted in one process still decrypt after a restart.
Back up the key file (or keep the variable) together with the database.
