# database

> Talk to PostgreSQL, MySQL, and SQLite from iii — query, execute, transactions, prepared statements, and database::on-row-changed for observing committed writes.

| field | value |
|-------|-------|
| version | 0.6.6 |
| type | binary |
| license | Apache-2.0 |
| repo | https://github.com/iii-hq/workers |
| supported_targets | x86_64-apple-darwin, aarch64-apple-darwin, x86_64-pc-windows-msvc, aarch64-pc-windows-msvc, x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-unknown-linux-musl, armv7-unknown-linux-gnueabihf |
| author | iii |

## installation

```sh
iii call compose::add worker=database@0.6.6
```

## dependencies

- `configuration` @ `latest`
- `secrets` @ `latest`
- `state` @ `latest`

## readme

# database

> Connect to PostgreSQL, MySQL, and SQLite. Run queries, prepared statements, transactions, and observe row-level changes.

| field | value |
|-------|-------|
| type | binary |
| supported_targets | x86_64-apple-darwin, aarch64-apple-darwin, x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu |
| author | iii |

## Install

```sh
iii call compose::add worker=database
```

## Skills

Install the `database` agent skill for Claude Code, Cursor, and 30+ other agents:

```bash
npx skills add iii-hq/workers --skill database
```

Browse or install every worker skill at once:

```bash
npx skills add iii-hq/workers --list
npx skills add iii-hq/workers --all
```

## Configure

Runtime settings live in the **`configuration` worker** under id **`database`**. The worker registers its JSON Schema at startup, reads the live value via `configuration::get`, and hot-reloads connection pools when the value changes.

Persisted values default to `./data/configuration/database.yaml` (fs adapter). Edit that file directly or call `configuration::set` — both propagate without a worker restart.

### Zero-config default

With no seed file and no stored configuration value, the worker uses a built-in default:

```yaml
databases:
  primary:
    url: sqlite:./data/iii.db
    pool:
      max: 10
      idle_timeout_ms: 30000
      acquire_timeout_ms: 5000
```

This is seeded into the `configuration` worker on first register and used as a runtime fallback when the stored value is `null`.

### Optional seed file

Pass `--config <path>` to supply a YAML seed file. When present, the whole value is passed as `initial_value` on `configuration::register` (overriding the built-in default for first-time registration). See [`config.yaml.example`](config.yaml.example).

Engine-managed deployments can inline config under the worker entry; the engine delivers it via `--config` as before.

### Value shape

SQLite is the recommended starting point — no server, just a file:

```yaml
databases:
  primary:
    url: sqlite:./data/iii.db
    pool:
      max: 10
      idle_timeout_ms: 30000
      acquire_timeout_ms: 5000
  analytics:
    url: ${ANALYTICS_URL:postgres://localhost/analytics}
    tls: { mode: disable }    # a local server without TLS; see "TLS" below
    pool: { max: 5 }
# history_max_entries: 200 # query history is off unless set above 0
history_max_bytes: 262144 # per-database size cap, default shown
```

`history_max_entries` / `history_max_bytes` cap the per-database query history stored on the [`state`](../state) worker — whichever cap hits first, oldest entries are dropped. History is **off by default** (`history_max_entries: 0`), so a query makes no `state` call; set `history_max_entries` above `0` to record. Applied live.

**Upgrading:** installs registered up to 0.6.5 stored `history_max_entries: 200` in their configuration and keep recording after the upgrade; set `history_max_entries: 0` to stop. From this version a default value is no longer stored, so a value equal to the default is not stored and follows later default changes.

Env placeholders use **`${VAR:default}`** syntax. The configuration worker expands them on every `configuration::get` call, so env changes propagate without a restart.

The configuration id is `database`, or the name a supervisor passes in `III_CONFIG_NAME` (under compose: `<namespace>-<container>`, e.g. `default-database`). `database::listDatabases` reports it as `config_id`.

### Connection entries

Each entry under `databases` is **either** a connection `url` (its scheme picks the driver: `sqlite:`, `postgres://`, `postgresql://`, `mysql://`) **or** the structured form below — never both (`CONFIG_ERROR` names the offending field). The structured form is what connection editors (the console, the iii app) write:

```yaml
databases:
  shop:
    driver: postgres              # postgres | mysql | sqlite
    host: db.example.com          # postgres/mysql
    port: 5432                    # default 5432 / 3306
    user: app
    password: secret://DATABASE_SHOP_PASSWORD   # literal | secret://NAME | env://NAME
    database: shop                # sqlite: the file path on the engine host (or :memory:)
    tls:
      mode: verify-full
      ca_cert: secret://SHOP_CA   # path | inline PEM | secret://NAME | env://NAME
    display: { icon: database, color: "#22C55E" }   # how clients draw it (Lucide icon, #RRGGBB)
    folder: /home/me/shop/queries                   # absolute path of its .sql query files
    pool: { max: 10 }
    capture: statements
```

- `display` and `folder` are metadata for clients; the worker validates and stores them, never reads the folder. `folder` must be absolute; neither `folder` nor a sqlite `database` path may contain `..` segments.
- `pool.max` is 1–500, `pool.idle_timeout_ms` at most 24 h, `pool.acquire_timeout_ms` 1 ms–10 min (the schema and `saveConnection` refuse anything else).
- Connection names written through `database::saveConnection` are 1–64 letters, digits, `_`, `-` or `.`, starting with a letter, digit or `_`.
- A `url` names its server in the authority, once: postgres urls may not carry `host`, `hostaddr`, `port`, `service` or `password` parameters or list several hosts, mysql urls may not carry `socket` or `password` (`CONFIG_ERROR`). Put the password in `password` (or the request's `credentials`); for several hosts or a socket, use one entry per server.
- `saveConnection` and `testConnection` refuse keys an entry does not define (`pasword`, `tls.clientkey` — `CONFIG_ERROR` naming each path), so a mistyped credential is neither stored nor sent where its value would be traced. An entry already stored with unknown keys still loads; the worker logs a warning naming the paths (never their values).
- A connection that cannot be built (an unresolvable secret, an SSH failure, an unreadable certificate — or a hand-edited entry that does not parse or validate) does **not** fail the configuration: it gets no pool, `database::listDatabases` reports its `error` and `error_stage`, and its calls fail with `CONFIG_ERROR` naming the cause. Every other connection keeps working, and the worker retries it every 15 s.

### Secrets

`password`, `tls.ca_cert`, `tls.client_cert`, `tls.client_key`, `ssh.password`, `ssh.private_key` and `ssh.passphrase` accept a **reference** instead of a literal:

- `secret://NAME` — a value in the [`secrets`](../secrets) worker's encrypted vault;
- `env://NAME` — an environment variable the secrets worker reads (the project's `.env`, else its own environment).

Only a well-formed reference, or a `${NAME}` engine template **without** a default (`${NAME}` / `${NAME:}`), names a value. Anything else in a sensitive field is a literal credential: a malformed `secret://…`, and a template with a default (`${DB_PASSWORD:hunter2}` carries the password itself). `getConnection` returns those as `"__redacted__"` and the rules below refuse them inside `connection`. A url's password counts whether it is in the userinfo (percent-encoding decoded first) or a `?password=` parameter.

The worker resolves them through `secrets::resolve` as consumer **`database`**, so each secret must list `database` in its consumers (`secrets::set` / `secrets::access`). Resolved values are cached (re-read every 5 minutes, failures after 10 s), wiped from memory when replaced, and never logged, returned or written to the configuration. When a secret is rotated, deleted or re-shared, the worker's observer of `secrets::on-changed` makes it re-read it and rebuild **only** the connections whose resolved values changed (a secret no stored connection uses is simply dropped from the cache). `database::testConnection` never uses the cache — it resolves its references at that moment, so a corrected or re-created secret is what the next Test sees — and `database::saveConnection` re-reads the saved entry's references before building its pool. The worker depends on the `secrets` worker (`iii.worker.yaml`).

**Literal credentials and traces.** A worker's trace spans record each call's payload, redacting keys that look sensitive (`password`, `private_key`, `secret`, `credential`, …) but not `passphrase`, `client_key` or a password inside `url`. So `database::testConnection` and `database::saveConnection` **refuse** a literal credential inside `connection` (a password, an inline key, a passphrase, a url password — `CONFIG_ERROR` naming the field): send it as a `secret://` / `env://` reference (safe anywhere), or in the request's **`credentials`** object — the same shape as the entry, sensitive fields only (`password`, `url`, `tls.client_key`, `ssh.password`, `ssh.private_key`, `ssh.passphrase`), merged over `connection` by the worker — which traces redact whole. Key file paths, `${VAR}` templates and `"__redacted__"` stay in `connection`. Responses never carry a credential (`getConnection` returns literals as `"__redacted__"`), no client can observe these three functions, and the configuration-change observer receives no configuration value (it re-reads it). What traces can still show: a literal that sits in the stored configuration itself (written by hand or by `configuration::set`) whenever another path ships the stored value — and a refused call's own payload: refusing happens inside the worker, after the engine traced the request, so a literal sent in `connection` by mistake is in that trace (redacted only when its key is on the SDK's list). Change that credential. A key file path stays in `connection` only while it looks like one (one line, at most 4096 bytes, not a pasted base64 key that happens to start with `/`). The lasting fix is upstream: the SDK's trace redaction (`iii-helpers`) should add `passphrase` and `client_key` to its key list and scrub url credentials.

**Where a credential may go.** `database::testConnection` (denied to agents) sends credentials only where they belong: a `"__redacted__"` value taken from the stored entry `name`, or a `secret://` / `env://` reference that a stored connection already uses, is accepted only when the candidate targets that connection's server — the same driver, every host, address and port the driver would try (read from the driver's own parse of the entry, not the url's text), the same SSH server and user, and an effective TLS mode (see the url `sslmode` note under TLS) no weaker than the stored one (for `ssh.*` fields: the same SSH server and user). Anything else is refused with `stage: "config"` before a connection is made; enter the value itself to test against a different server. References no stored connection uses (a new connection's fresh secret) are free.

An unresolvable reference fails only its connection, with a message that names the reference and what to do (`secret://X did not resolve: database is not allowed to read secret X; add database to the secret's consumers`), never a value.

### Hot reload

The worker observes `configuration::on-updated` for its entry (filters on `input.id` and `input.event_type`, delivering only the caller, never the value). When configuration changes (`configuration::set`, `database::saveConnection`, or an external edit to `./data/configuration/database.yaml`), the worker re-reads the entry and rebuilds only the connections whose entry or resolved secrets changed; the others keep their pools, tunnels and open connections. Invalid configs are rejected and the previous pools are kept. In-flight prepared-statement handles and open transactions continue on their original pool until they expire.

### TLS (postgres + mysql)

Postgres and mysql connections default to **`tls.mode: require`** — TLS handshake required, certificate chain validated against the system trust store, hostname verification skipped (matches libpq's `sslmode=require`). Override per-database:

```yaml
databases:
  primary:
    url: postgres://app@db.example.com:5432/app
    tls:
      mode: verify-full           # disable | prefer | require | verify-ca | verify-full   (default: require)
      ca_cert: /etc/ssl/internal-ca.pem    # optional; extends the system trust store
      trust_native: true                   # default true; set false to trust only ca_cert
  local:
    url: postgres://dev@localhost:5432/dev
    tls:
      mode: disable               # plaintext, local development only
```

| Mode | Encrypted | Chain checked | Host name checked | Server without TLS |
|---|---|---|---|---|
| `disable` | no | — | — | connects |
| `prefer` | when offered | yes | no | connects in plaintext (a failed certificate check is still an error) |
| `require` (default) | yes | yes | no | error |
| `verify-ca` | yes | yes | no | error |
| `verify-full` | yes | yes | yes | error |

> **Upgrading from 0.5.21 or earlier.** On postgres, `require` (the default when an entry has no `tls` block) used to fall back to plaintext when the server offered no TLS: tokio-postgres connected with `sslmode=prefer` underneath. It now refuses, as the mode always claimed — that fallback is exactly what a man in the middle exploits. An entry that never set `tls` and talks to a server without TLS (typically a local or docker postgres) now fails with `pool connection failed (tls)`; add `tls: { mode: disable }` (trusted network) or `tls: { mode: prefer }` (the old behaviour), or write `?sslmode=disable` into the url. MySQL already refused plaintext under `require`. SQLite and the built-in default (`sqlite:./data/iii.db`) are unaffected.

`require` and `verify-ca` perform the same checks (libpq names them apart because libpq's `require` skips the chain; this worker never does). On postgres, a `sslmode` written into the url (`disable`, `prefer` or `require`) decides **whether** TLS is used, over `tls.mode`; `tls.mode` still decides the certificate checks whenever TLS is used (`sslmode=require` under `tls.mode: verify-full` checks the host name; `sslmode=disable` under any `tls.mode` is plaintext). Without a url `sslmode`, `tls.mode` decides both, and `require` really requires TLS (tokio-postgres alone would fall back to plaintext). `testConnection`'s credential binding compares this effective mode. `verify-full` is the production default for managed services (RDS, Neon, Supabase).

`ca_cert` lets you point at a CA bundle for self-hosted databases or managed providers whose root isn't in the OS trust store. **Additive by default**: the supplied certs extend the system trust store rather than replacing it. Set `tls.trust_native: false` to trust only the `ca_cert` certs. Postgres only — `mysql_async`'s rustls path always bundles `webpki_roots` and offers no upstream knob to suppress it.

**Mutual TLS.** `tls.client_cert` (the client certificate chain) and `tls.client_key` (its key) present a client certificate; both are required together. Each is a path on the engine host, the PEM itself, or a `secret://` / `env://` reference (a referenced value must be PEM text). Postgres takes PKCS#8, PKCS#1 and SEC1 keys; MySQL takes RSA keys only (PKCS#8 or PKCS#1) — `mysql_async` cannot present EC or Ed25519 client keys.

#### Connecting to managed providers

**Supabase.** Every Supabase endpoint (direct, transaction pooler, session pooler) presents certificates signed by *Supabase Intermediate 2021 CA*, which is not in the OS trust store. By default `tls.mode: require` fails with `pool connection failed (tls)`. Download the CA from your project dashboard (or `https://supabase.com/downloads/prod-ca-2021.crt`) and point `tls.ca_cert` at it:

```yaml
databases:
  primary:
    url: postgresql://postgres.<project>:<password>@aws-0-<region>.pooler.supabase.com:6543/postgres
    tls:
      mode: verify-full
      ca_cert: /etc/ssl/supabase-prod-ca-2021.crt
```

`ca_cert` is additive — your existing CA pinning for other databases keeps working alongside this entry.

**Neon.** Drop `?sslmode=` and `?channel_binding=` from URLs copied out of the Neon dashboard, and configure TLS via the `tls` YAML block instead:

```yaml
databases:
  primary:
    url: postgres://user:pass@ep-xxx-pooler.<region>.aws.neon.tech/neondb
    tls:
      mode: require    # or verify-full
```

Neon's default `?channel_binding=require` cannot work through the pooler endpoint: TLS terminates at the pooler, so SCRAM-SHA-256-PLUS isn't advertised by the inner server, and `tokio-postgres` refuses to fall back. Leaving the URL param in surfaces as `pool connection failed (auth)`.

SQLite ignores the `tls` block (local-file driver).

### SSH tunnel (postgres + mysql)

```yaml
databases:
  private:
    driver: postgres
    host: pg-private             # as the SSH server resolves it
    port: 5432
    user: shop
    password: secret://PRIVATE_PG_PASSWORD
    tls: { mode: verify-full, ca_cert: /etc/ssl/internal-ca.pem }
    ssh:
      host: bastion.example.com
      port: 22                   # default
      user: tunnel
      private_key: secret://BASTION_KEY     # OpenSSH or PEM (RSA, ECDSA, Ed25519): inline, a path, or a reference
      passphrase: secret://BASTION_KEY_PASSPHRASE
      password: secret://BASTION_PASSWORD   # optional; tried after the key
      host_key: "SHA256:0rGFgr3lbFUjBJmay4CvRxX16hnJLF7mvototEUXoW0"
```

The worker opens one SSH session per connection (pure Rust, no OpenSSL), listens on an ephemeral `127.0.0.1` port and forwards each pool connection through a `direct-tcpip` channel to `host:port` as the SSH server sees it; a dropped session is reopened on the next connection. TLS still runs end to end and verifies the **database** host name (`pg-private` above), not `127.0.0.1`. Works with the url form too (the url's host is the forwarding target).

- **Host key.** With `ssh.host_key` (the OpenSSH SHA-256 fingerprint, as `ssh-keygen -lf` prints it) any other key is refused, and the error names both fingerprints. Without it any key is accepted (trust on first use) and `database::testConnection` returns `ssh_host_key: {algorithm, fingerprint}` so a client can pin it.
- **Authentication.** `private_key` (with `passphrase` when encrypted) is tried first, then `password`. Errors name the SSH server and user, never a credential.
- The local listener accepts connections only on loopback; any process on the engine host could use it while the pool is up, as with `ssh -L`.

## Quick start (SQLite)

```ts
import { registerWorker } from 'iii-sdk'

const iii = registerWorker(process.env.III_URL ?? 'ws://127.0.0.1:49134')

await iii.call({
  function_id: 'database::execute',
  payload: {
    db: 'primary',
    sql: 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT)',
  },
})

await iii.call({
  function_id: 'database::execute',
  payload: {
    db: 'primary',
    sql: 'INSERT INTO users (email) VALUES (?), (?)',
    params: ['a@x', 'b@x'],
  },
})

const { rows } = await iii.call({
  function_id: 'database::query',
  payload: {
    db: 'primary',
    sql: 'SELECT id, email FROM users ORDER BY id',
  },
})
```

## Functions

| Function | Purpose |
|---|---|
| `database::query` | Read SQL (in a read-only transaction). Returns `{ rows, row_count, columns, truncated, elapsed_ms }`. **`max_rows`** caps the rows returned: the worker stops reading after `max_rows + 1` (a postgres portal fetch, mysql's `sql_select_limit`, sqlite's lazy stepping — the SQL is never rewritten) and `truncated` says whether more existed. `elapsed_ms` is the time the statement took, pool acquisition excluded. One statement per call: a sqlite read with a second statement after `;` is refused (`MULTI_STATEMENT`). |
| `database::execute` | Write SQL. Returns `{ affected_rows, last_insert_id, returned_rows, elapsed_ms }`.<br>**`returned_rows`** come from a `RETURNING` clause written into the SQL (SQLite, Postgres — MySQL has none): `INSERT INTO t (n) VALUES (?) RETURNING id`. The `returning: [...]` option never adds the clause; SQLite rejects it without one, Postgres and MySQL ignore it.<br>**`last_insert_id` semantics:** SQLite/MySQL surface the engine's `last_insert_rowid()` / `LAST_INSERT_ID()` (only populated for INSERT). Postgres has no equivalent — `last_insert_id` is set from the **first column of the first RETURNING row** of an INSERT, so put your PK first: `RETURNING id, name`, not `RETURNING name, id`. |
| `database::executeBatch` | Convenience form of `transaction`: statements may be bare SQL strings or `{ sql, params }` objects (use `params` for dynamic values instead of inlining them). Same envelope and semantics as `transaction` — atomic, rolls back on first failure, reports `failed_index`, supports `isolation`. |
| `database::prepareStatement` | Pin a connection and return `{ handle: { id, expires_at } }`. |
| `database::runStatement` | Run a prepared SQL statement by handle. (No `timeout_ms` — uses the pinned connection's session lifetime; configure via `ttl_seconds` on `prepareStatement`.) |
| `database::transaction` | Atomic batch sequence; rolls back on first failure. One-shot — pass all statements together. Rejects bare transaction-control SQL (`BEGIN`/`COMMIT`/`ROLLBACK`/…) and empty statements with `INVALID_PARAM`. |
| `database::beginTransaction` | Open an interactive transaction. Returns `{ transaction: { id, expires_at } }`. Configurable `timeout_ms` (default 30 000, max 300 000) auto-rolls back if the deadline elapses. |
| `database::transactionQuery` | Read SQL inside an interactive transaction. Same envelope as `query`. |
| `database::transactionExecute` | Write SQL inside an interactive transaction. Same envelope as `execute`. Rejects bare `BEGIN`/`COMMIT`/`ROLLBACK`/`SAVEPOINT`/`SET TRANSACTION` with `INVALID_PARAM` — finalize via the dedicated handlers below. |
| `database::commitTransaction` | Commit an open SQL transaction, making its writes permanent. Subsequent calls against the same id return `TRANSACTION_NOT_FOUND`. |
| `database::rollbackTransaction` | Roll back an open SQL transaction, discarding its uncommitted writes. Subsequent calls against the same id return `TRANSACTION_NOT_FOUND`. |

### Connections

| Function | Description |
|---|---|
| `database::listDatabases` | Configured connections: `{ databases, count, config_id }`. Each entry: `name`, `driver`, credential-redacted `url`, `host`, `port`, `user`, `database`, `display`, `folder`, `ssh` (`host`, `port`, `user`, `host_key_pinned`), `pool`, `tls` (`mode`, `ca_cert_present`, `client_cert_present`, `trust_native`), `uses_secrets`, and `error` / `error_stage` when the connection could not be built. Config only — no secrets, no health checks. |
| `database::getConnection` | `{ name }` → `{ name, connection }`: the entry as stored, `${VAR}` templates and `secret://` references intact; a literal password, passphrase, inline private/client key or url password comes back as `"__redacted__"`. |
| `database::saveConnection` | `{ name, previous_name?, connection, credentials? }` → `{ name, saved, error?, error_stage? }`. Creates (`previous_name` absent; a taken name is refused), updates (`previous_name` = `name`) or renames (`previous_name` = the old name). A field still holding `"__redacted__"` keeps its stored value. Read-modify-write of the whole configuration through `configuration::set` (raw, so other entries' templates survive); returns after the pools reloaded, with the saved connection's build error, if any (it is saved either way). |
| `database::deleteConnection` | `{ name }` → `{ deleted }`. The last connection cannot be removed. |
| `database::testConnection` | Probe a candidate entry before saving (people only — agents are denied it): `{ connection, credentials?, name?, timeout_ms? }` (legacy `{ url, tls }` still works, a url password going in `credentials.url`; `name` resolves `"__redacted__"` from the stored entry, for the same server only — see "Where a credential may go"). One throwaway connection (and tunnel); secrets resolve like a saved connection's. Returns `{ ok, driver, latency_ms, server_version?, message?, stage?, ssh_host_key? }` — `stage` is where it failed: `config`, `secrets`, `ssh`, `tcp`, `tls`, `auth` or `database`. Failures are data, not errors. |

### Reading the schema

| Function | Description |
|---|---|
| `database::listTables` | Every table and view, with its kind, (postgres) its schema, and `row_count_estimate` where the catalog keeps one cheaply — postgres `reltuples` (tables and materialized views, once analyzed), mysql `TABLE_ROWS`; absent on sqlite and for views. An estimate, not a count. |
| `database::describeTable` | One table: columns with type, nullability, default, primary-key membership, foreign-key target, **`auto_increment`** (the database fills it in: postgres identity or a `nextval(…)` default such as `serial`, mysql `AUTO_INCREMENT`, a sqlite `INTEGER PRIMARY KEY` — the rowid — outside `WITHOUT ROWID` tables) and **`generated`** (computed, cannot be written: postgres `GENERATED ALWAYS AS … STORED`, mysql virtual/stored generated columns — not `DEFAULT CURRENT_TIMESTAMP` — and sqlite generated columns); plus indexes and a planner row estimate. Foreign keys are structured `{ schema, table, column }`, not a joined string. An unqualified postgres name is the table the search_path finds (`orders` is `public.orders` even when `analytics.orders` exists). |
| `database::describeSchema` | The same shape for every table at once. One catalog query per aspect across the whole database rather than one call per table, so a 200-table schema costs a handful of queries. `include_indexes` is off by default. |
| `database::schemaDiagram` | Positioned table nodes and routed foreign-key edges, plus each table's hub `degree`, the `isolated` tables, and remaining edge `crossings`. Layout runs server-side, so a renderer only draws. |

### Reading data

| Function | Description |
|---|---|
| `database::browseTable` | Paged, sorted, filtered table read — no SQL from the caller. Filters are structured (`{ column, op, value }`) and compile to a parameterised `WHERE` for the driver in hand; `total` honours the same filters. Values compare as the column's type: on postgres each value (`value`, `value2`, every `values` entry) is bound as text and cast to the column's catalog type (`$n::text::<type>`), so `total gt 100` on a `numeric`, a date, a timestamptz, a uuid, an inet, a boolean, an enum or an int8 means what it says, numbers may be strings, and a value the type cannot read is an error (never a match-everything); a filter on a column the table does not have is `INVALID_PARAM`. Pattern operators (`contains`, `starts_with`, …) on a non-text column compare its text form. mysql and sqlite compare by their own coercion rules (numeric for number columns). Sorts accept a `mode` (`natural`, `length`, `absolute_value`, `random`) applied across the whole table, not just the page. To follow a foreign key, filter on equality with `page_size: 1`. A filter may instead be **`{ raw: "<SQL boolean expression>" }`**, ANDed in its own parentheses (`column`/`op` ignored). A raw filter can never write: it is refused when it could leave its parentheses (a `;`, a comment, an unbalanced `)`, a placeholder, or a backslash whose meaning depends on server settings — quotes, dollar quotes, backticks and sqlite brackets are lexed like the server lexes them), and it runs in a read-only transaction (postgres, mysql) or under `PRAGMA query_only` (sqlite) through the single-statement protocol. Returns `elapsed_ms` too. |
| `database::distinctValues` | `{ table, schema?, column, search?, limit? }` → `{ values: [{ value, count }], truncated, elapsed_ms }`: a column's distinct values, most frequent first (`limit` 1–500, default 50; 0 is refused). `search` keeps values whose text form contains it, case-insensitively and literally. For filter pickers. |
| `database::formatSql` | `{ sql, db?, driver?, uppercase?, indent? }` → `{ sql }`: pretty-printed for the driver's dialect — one of `db` or `driver` is required (literal and identifier quoting differ per dialect) (keywords uppercased by default, 2-space indent); statements and comments preserved — a block comment's interior byte for byte, a line comment after a statement's `;` on that line — and literal bytes (strings, quoted identifiers, dollar-quoted bodies, sqlite `[identifiers]`) never change. Refused: NUL bytes, parentheses nested more than 100 deep, and input that could format to more than 8 MB. Nothing runs. |
| `database::explain` | The query plan as a tree with per-node cost, row estimates and warnings, instead of the driver's raw text. `analyze` collects real timings by **running** the statement, so it defaults to `false` and is refused for anything that is not a single read. |
| `database::columnStats` | Profile a table's columns. Reads the planner's own statistics by default — free and approximate, labelled `source: planner`. `exact: true` runs real aggregates and scans the table; it is refused above a row-count ceiling. To profile rows you already hold, pipe a `browseTable` result through the `fp` worker instead. |

### Writing rows

| Function | Description |
|---|---|
| `database::insertRow` | `{ table, schema?, values: { column: value } }` → `{ row, affected_rows, elapsed_ms }`. Columns left out take their default. Each value is converted to its column's catalog type: postgres binds text and casts it (`$n::text::<type>`), so numbers as strings, booleans, uuids, dates, json and arrays (from a JSON array) all parse; bytea/blob/binary columns take base64; mysql/sqlite booleans become 1/0. On integer and decimal columns a JSON number at or above 2^53 in magnitude is refused (it may already have lost digits in the client — send it as a string), and an integer column takes only decimal digit strings (`"0x10"`, `"1e3"` are refused). `row` is the inserted row (`RETURNING *` on postgres/sqlite; on mysql a re-select by the auto-increment id or the supplied primary key, else null). Reported on `database::on-row-changed` like `execute`. |

### Operations

| Function | Description |
|---|---|
| `database::health` | Check live pool occupancy plus active queries, table sizes, blocking locks and cache hit ratio. Each section reports separately as `available`, `unsupported` or `denied`, so a driver gap or a restricted role never reads as an empty result. |
| `database::terminateQuery` | Terminate a backend session, or cancel just its statement with `cancel_only`. Takes an id from `health`. Separate from `health` because it is a write. |

### Saved queries and history

The web console's snippet list, stored in the [`state`](https://github.com/iii-hq/workers/tree/main/state) worker, scoped per database, so they survive restarts and any agent can read them. These are **not files**: a connection's queries as the apps show them are the `.sql` files in its `folder`, which agents write with the file tools (the mention summary and the skill say so).

| Function | Description |
|---|---|
| `database::saveQuery` | Save a named snippet to the console's list (not a file). Saving under an existing name replaces it. |
| `database::listSavedQueries` | Saved queries for a database, sorted by name. |
| `database::deleteSavedQuery` | Delete by id or by name. |
| `database::history` | Recent queries, newest first. Best effort — recording never blocks or fails a query, so this is a convenience rather than an audit log. For an audit trail observe `database::on-row-changed`. Stored history is capped per database (`history_max_entries` / `history_max_bytes`, default 0 entries = off, 256KB — set `history_max_entries` above `0` to record; oldest dropped first) and holds metadata only: SQL text (truncated to 4000 chars), verb, timing, row count — never result rows. An oversized or unreadable stored value is replaced wholesale on the next write. |

### Chat mentions

The worker is a [mention provider](../crates/mention-contract) named `database`: `@database(id="<connection>")` in a chat renders as a pill reading `@<connection>` (the item's `hint` is the connection name; `description` is `<driver> · host:port/db`) with a preview card (driver, server, SSH, folder, status) and reaches the agent as a summary saying which `db` to pass (`database::query {db: "<connection>", sql}`, `database::listTables {db: "<connection>"}`) and where queries go: a `.sql` file in the connection's queries folder, written with the file tools (or that it has no folder) — `database::saveQuery` being only the console's snippet list. `database::mention::search` / `database::mention::get` are internal; agents read the connection through `database::listTables` (the provider's `details`).

## Cell values

Every driver returns rows as JSON objects. Values are encoded by column type, so a client parses each type one way:

| Column type | JSON |
|---|---|
| integers (`int2`, `int4`, `smallint`, `int`, `mediumint`, `year`, sqlite `INTEGER`), mysql `bigint` | number |
| postgres `int8`/`bigint`, `numeric`/`decimal` (all drivers but sqlite), `money`, mysql `bigint unsigned` | string (exact) |
| `real`, `double`, `float` | number; postgres `NaN`/`Infinity` as strings |
| `boolean` | boolean on postgres; `0`/`1` on mysql (`tinyint(1)`) and sqlite |
| text types, mysql `enum`/`set` (`"a,b"`), postgres enums, `uuid`, `xml`, `inet`, `cidr`, `macaddr`, `point`, `tsvector`, ranges | string (postgres `char(n)` keeps its padding) |
| `json`, `jsonb` (sqlite: columns declared `JSON`) | the JSON value |
| `bytea`, `blob`, `binary`, `varbinary`, `geometry` | base64 string |
| `date` | `"YYYY-MM-DD"` |
| `time` | `"HH:MM:SS[.ffffff]"` (mysql durations past 24 h or negative as mysql prints them); postgres `timetz` adds the offset (`"12:30:00+03"`) |
| `timestamp`, `timestamptz`, `datetime` | RFC 3339 with `Z`, fraction when non-zero (a zone-less value is read as UTC); postgres `infinity` as a string |
| `interval` | postgres text form (`"1 year 2 mons 3 days 04:05:06"`) |
| `bit(n)` | string of `0`/`1` |
| postgres arrays | JSON arrays of the element encoding (nested for several dimensions) |
| postgres composites / domains | JSON object by field name / the base type's encoding |
| anything else (extension types) | its bytes as text when printable, else `"\\x…"` hex |

Parameters (`params`, `insertRow` values) take the same forms back. Integers beyond 2^53 are exact when sent as JSON numbers that fit 64 bits **or as numeric strings** — send them as strings from JavaScript, whose numbers lose precision past 2^53. On postgres a JSON array bound to an array parameter (`$1::int[]`) is that array (nested arrays are dimensions).

sqlite returns what each value is stored as (its affinity): `NUMERIC` columns may hold integers or reals, and dates are whatever text was stored. A cell that cannot be decoded never fails the query.

## Row changes

### `database::on-row-changed`

One event per committed write statement. The worker calls this private
function after each committed write, and its handler returns the event, so
observers observe the event. Observe it with args that say which database,
table and operations, and filters on what changed or who changed it. Two
capture modes, chosen per database in the worker config (`capture:`):

- **`statements`** (default) — reports mutations made *through this worker*
  (`execute`, `executeBatch`, `transaction`, `insertRow`, and the interactive
  transaction surface) by classifying the SQL. A write applied by psql,
  another worker, or a database-side trigger is invisible to it. No database
  setup; identical on SQLite, Postgres and MySQL. The worker calls the
  function from the invocation that made the write, so events carry `caller`:
  the function that made the write, and its `parent`, the one that called it.
- **`native`** — reports committed writes from *any* client. Postgres: per-table
  database triggers + LISTEN/NOTIFY (the role needs TRIGGER on the table).
  File-backed SQLite: database triggers feeding a changelog table, drained on
  filesystem wake-up.
  MySQL: the binlog replication stream (`REPLICATION SLAVE, REPLICATION CLIENT`
  grants, `binlog_row_metadata=FULL` for row identity). Observers must name a
  `table`. Events have no `caller.parent`: nothing in iii made the write.

"Which worker changed `orders`?"

```ts
iii.registerFunction('audit::orders-changed', ({ input, caller }: Observed<RowChangedEvent>) =>
  audit.record({ op: input.op, keys: input.returning, by: caller?.parent?.worker_name ?? 'external' }))

iii.observe({
  function_id: 'database::on-row-changed',
  args: { db: 'primary', table: 'orders' },
  capture: ['input', 'caller'],
}, 'audit::orders-changed')
```

"Paid invoices only" (statements capture, the writer's SQL ends in
`RETURNING id, status`), once:

```ts
iii.observe({
  function_id: 'database::on-row-changed',
  args: { db: 'primary', table: 'invoices', ops: ['update'] },
  filters: { 'input.returning': { $any: { '@.status': { $eq: 'paid' } } } },
  capture: ['input'], // the target reads the event at payload.input
}, 'billing::on-invoice-paid', { max_fires: 1 })
```

"Everything except my own writes", for a projector that writes back:

```rust
iii.observe(
    Source::function("database::on-row-changed")
        .args(json!({ "db": "primary" }))
        .filters(json!({ "caller.parent.worker_name": { "$ne": "order-projector" } }))
        .capture([Capture::Input]),
    "orders::project",
);
```

**Args** (`args_format`, checked by the engine). `db` (required, a configured
connection), `table` (optional on `statements`, required on `native`) and
`ops` (optional; `insert` / `update` / `delete` / `other`). `table` is
canonical: the bare name, unquoted and lowercase (`orders`, not
`public.Orders`); the schema is in the event. An observer the worker cannot
serve is refused when it is created, and its `ready()` says why:

| Code | Why |
|---|---|
| `INVALID_ARGS` | A missing `db`, or an unknown arg (`tabel`). |
| `NON_CANONICAL_TABLE` | `table` is not canonical; the message names the canonical value. |
| `UNKNOWN_DB` | No such connection. |
| `NATIVE_CAPTURE_REQUIRES_TABLE` | A `native` database and no `table`. |
| `CAPTURE_INSTALL_FAILED` | Native capture could not be installed (privileges, a table that does not exist under that name, a MySQL server without a ROW binlog). |

A configuration reload serves each observer as the new configuration says.
When its database becomes `native`, or a `native` database's connection
changes, the worker installs capture for its table through the new
connection; when its database becomes `statements`, the statements path
serves it. An observer the new configuration cannot serve is rejected with
the code for the reason: its database was removed (`UNKNOWN_DB`), its
database became `native` and it names no table
(`NATIVE_CAPTURE_REQUIRES_TABLE`), or capture cannot be installed through
the new connection (`CAPTURE_INSTALL_FAILED`). A `native` database whose
connection cannot be built keeps its observers, and the worker installs
their capture once the connection builds.

**Event** (`input`, and `output`: the handler returns it): `{ db, schema,
table, op, affected_rows, returning?, truncated?, at }`. `schema` is
lowercase, `null` when neither the SQL nor the driver named one; `table` is
canonical. Filter paths are checked against this shape (`input.tabel` is
`INVALID_FILTER_PATH`). Every observer receives the `Observed`
envelope; with `capture: ['input']` or `capture: ['output']` the event is its
`input` or `output`.

**Delivery.** iii delivers each call to the observers whose args match it:
the worker files each observer under its `db`, its `table` (or every table)
and each of its `ops` (or every operation), and looks each event up under its
db, its table and every table, its op and every op. The observer's filters
then apply as usual. The worker calls the function from the task that
announces the write and waits for the call, which does not wait for the
observers' targets. iii runs each delivery as a call of the target of its
own, so a target can receive row events in any order, the statements of one
transaction included. An observer with `max_in_flight: 1` receives them one
at a time, in the order the worker called the function: commit order for one
transaction's statements and for one native database's changes.

**Only the database worker calls it.** The function is private: the engine
refuses a call from any other connection (`FORBIDDEN`) and refuses it as an
observer's target, so no worker can hand observers an event of its own
making. What an event says is still what the database told the worker:

- on `statements` it describes the statement as its writer wrote it
  (`returning` is the writer's projection), and `caller` says which function
  made it — filter on `caller` when it matters who wrote;
- on `native` it is as trustworthy as access to the database: any session
  that can run SQL there can raise a capture notification (Postgres
  `pg_notify`, allowed even in a read-only transaction, so through
  `database::query` too) or write the SQLite changelog, and the event
  carries no caller.

With nobody observing the function, no event is built: the worker
classifies no SQL (except an interactive transaction's statements, held
until its commit for an observer added before it), parses or decodes
nothing a `native` database sends, does not call the function, and puts
nothing on the wire. A `native` database still sends what it captures (a
Postgres notification, the MySQL binlog stream, rows in the SQLite
changelog, which the worker deletes), and the worker drops it without
decoding it. With observers of other tables only, the event is built and
costs a hash lookup per key; it is not serialized.

**Which rows changed — `returning`.** The event never invents row data:

- On `statements` it is the writer's own `RETURNING` projection, verbatim. A
  listener that needs to know *which* row changed depends on the writer having
  written `RETURNING <primary key>` into its SQL — the `returning` option on
  `execute` does not add the clause. Without it the event carries only
  `affected_rows`. `UPDATE` reports the new values, `DELETE` the removed row.
  MySQL has no `RETURNING`, so statements-mode events there never carry rows.
- On `native` it is the primary-key columns of each changed row (every column
  of a composite key; `UPDATE` reports the new key), so a listener gets row
  identity without the writer's cooperation. Capped at 100 rows per event —
  `truncated: true` says the rest were dropped, `affected_rows` stays exact.
  Absent for a table without a primary key. Values are encoded as
  `database::query` returns the same column (Postgres `bigint` as a string,
  for example).
- When not to observe: if the writer is you and already holds the new values
  in `execute`'s `returned_rows`, there is nothing to wait for.

Worth knowing:

- **Announced on commit, never before.** Statements inside an interactive
  transaction are buffered until `commitTransaction`; a rollback — including
  the timeout watcher's — drops the buffer. Atomic batches announce their
  statements only after the whole batch commits. Native capture is
  commit-gated by the database itself. **Delivery** above says in what order
  a target receives them.
- **Delivery is best-effort.** The call happens after commit and is not durable
  or atomic with the database write. There is no replay, retry, or exactly-once
  guarantee; a crash between commit and the call can lose an event. A target's
  failure never fails the write. A harness wake notification
  renders the event as JSON within ~8,000 characters; an over-long `returning`
  keeps its leading rows and ends with one marker string, `"…N more entries
  omitted (array shortened for this notification; JSON is complete)"` (N is
  what the wake dropped, on top of any `truncated` cap above), so the text
  still parses and `affected_rows` stays exact. Only an event whose
  non-array fields alone exceed the budget is cut as plain text with an
  `…(truncated)` tail. Re-read the table on wake when an observer can see wide
  or many-row writes. A filter that misses sends nothing: observers' filters
  run in the database worker, before anything goes on the wire.
- **`table` can be null on `statements`.** The table is read off the SQL. A
  CTE-wrapped write (`WITH … INSERT`) still fires, with `table: null`, rather
  than being dropped; an observer that named a table simply does not match
  it. Omit `table` to match every write, including these. The classifier reads
  keywords rather than parsing, so any `WITH` statement whose text contains
  `INSERT`/`UPDATE`/`DELETE`/`MERGE` — even inside a string literal — fires
  the same way.
- **`runStatement` does not fire on `statements`.** The prepared-run path
  returns rows, not an affected-row count, and an event that invented one would
  be lying. Use `execute` when you need the change announced. On a `native`
  database the database itself reports the write, whichever path it took.
- **Native capture stays installed.** The database triggers native capture
  installs on a table stay when the table's last observer leaves, and when
  the database leaves the configuration, leaves `capture: native` or moves
  to another server: every worker and connection that captures the table
  shares them, and the worker cannot tell whether another one still relies
  on them. While they stay, each write
  statement on the table raises a notification (Postgres) or appends
  changelog rows (SQLite); a worker deletes the changelog rows only while it
  has the database configured `capture: native`. To remove capture from a
  table, drop them: on Postgres the triggers `iii_row_changed_ins`,
  `iii_row_changed_upd` and `iii_row_changed_del` on the table (the
  `iii_row_changed_notify()` function serves every captured table); on
  SQLite the triggers `iii_row_changed_ins_<table>`,
  `iii_row_changed_upd_<table>` and `iii_row_changed_del_<table>`, and the
  `_iii_row_changes` table once no table is captured. MySQL capture installs
  nothing.
- **Native caveats.** Postgres additionally trims keys to fit NOTIFY's
  8000-byte payload. SQLite's triggers call `json_object`, so every process
  writing the file needs libsqlite ≥ 3.38 (JSON built in) — an older client
  fails its own INSERT with `no such function`. MySQL carries keys only under
  `binlog_row_metadata=FULL`; on the `MINIMAL` default the events are
  count-only and the worker warns when an observer is added.
- **Canonical args cannot name a schema or a case-sensitive table.**
  `args.table` is a bare lowercase name. On `statements` it matches every
  spelling of the table (filter on `input.schema` to tell schemas apart). On
  a `native` Postgres database the capture installs on that name, so a table
  outside the connection's `search_path`, or a quoted mixed-case one
  (`"Orders"`), fails with `CAPTURE_INSTALL_FAILED` and a hint.

## Isolation between callers

- **Postgres** pooled connections are reset when they come back to the pool (`RESET ALL`, `UNLISTEN *`, `pg_advisory_unlock_all()`, temporary tables and sequences, open cursors), so one call's `set_config(…, false)` or advisory lock never reaches the next caller. Reads run in read-only transactions.
- **Postgres prepared statements.** Session-level `PREPARE` / `EXECUTE` / `DEALLOCATE` are refused in every statement a call carries — `query`, `execute`, `transaction` / `executeBatch`, the interactive transaction calls and `prepareStatement` (`INVALID_PARAM`): a named statement would outlive the call on the pooled session (the reset cannot `DEALLOCATE ALL`: the driver's own cached statements live there too), where the next caller could run it. Use `prepareStatement` / `runStatement`, which pin a connection.
- **SQLite** connections refuse `ATTACH` (and so `VACUUM`, which attaches underneath): a call can only ever see and write its own database file. They also refuse setting `writable_schema`, `schema_version`, `ignore_check_constraints`, `trusted_schema`, `legacy_alter_table`, `temp_store_directory` and `data_store_directory` (reading them is fine), and run with double-quoted string literals off, so `"name"` is always an identifier — a misspelt column is an error, not the string `'name'`.
- **`saveConnection` is not bound to a server.** `testConnection` sends a stored credential only to that connection's own server, but `saveConnection` writes whatever entry it is given: a client allowed to call it can save an entry that points a `secret://` reference the `database` consumer can read at a server of its choosing, and the next connection attempt delivers it. That is the function's purpose (connection editors save new servers), so it is gated by permission instead: agents are denied `saveConnection`, `deleteConnection`, `getConnection` and `testConnection` (`iii-permissions.yaml`); grant them through RBAC only to clients you would let manage your connections, and share secrets with the `database` consumer only when every such client may use them.
- **Observers.** `database::query`, `execute`, `browseTable`, `insertRow` and the other data functions are ordinary observable functions: an observer capturing `input` / `output` sees other clients' SQL and rows — the same reach as calling `database::query` itself, so grant `observe` on them as you would grant the call. `testConnection`, `saveConnection` and `getConnection` are registered with `observable: false`: observing them fails with `NOT_OBSERVABLE`.

## Errors

Returned `IIIError::Handler` bodies carry a stable `code` field:

| Code | Meaning |
|---|---|
| `POOL_TIMEOUT` | Pool acquire exceeded `acquire_timeout_ms`. |
| `QUERY_TIMEOUT` | Query exceeded `timeout_ms`. |
| `STATEMENT_NOT_FOUND` | Handle expired or unknown — re-prepare. |
| `TRANSACTION_NOT_FOUND` | Transaction id unknown, already committed/rolled back, or timed out (auto-rolled-back by the watcher). |
| `UNKNOWN_DB` | `db` parameter doesn't match any configured database. |
| `INVALID_PARAM` | JSON value couldn't be coerced for the target driver, transaction-control SQL was sent to `transactionExecute` (use `commitTransaction` / `rollbackTransaction`), or a `transaction`/`executeBatch` batch contained transaction-control SQL or an empty statement. |
| `DRIVER_ERROR` | Wraps underlying driver error with `driver` and `inner_code` (nullable). `inner_code` format is per-driver: Postgres = SQLSTATE 5-char string (e.g. `42P01`), MySQL = server error number as string, SQLite = `rusqlite::ErrorCode` debug name. Pool-acquire failures use the message form `pool connection failed (<class>)` where `<class>` is one of `tls`, `auth`, `network`, `ssh`, `server-policy`, or `unknown` — a redacted hint so untrusted callers can self-triage without seeing host/userinfo/db fragments. The full driver error is in the worker's stderr via `tracing::warn!`. |
| `CONFIG_ERROR` | Config parse or pool init failure; a connection that is configured but unavailable (`connection \`x\` is unavailable (secrets): secret://X did not resolve: …`); a `saveConnection` / `deleteConnection` the worker refused (validation, duplicate name, `"__redacted__"` with nothing stored). Messages name fields and references, never values. |

## Driver compatibility

A few operations are no-ops on certain drivers. They emit a `tracing::warn!` rather than an error:

| Operation | SQLite | Postgres | MySQL |
|---|---|---|---|
| `execute` / `transactionExecute` with a `RETURNING` clause in the SQL | ✓ rows returned | ✓ rows returned | no RETURNING in MySQL |
| `execute` `returning: [...]` option (never adds the clause) | rejected without a clause (`RETURNING_MISMATCH`) | accepted, no effect (warn) | accepted, no effect (warn) |
| `transaction` `isolation: read_committed` / `repeatable_read` | warn + use serializable | ✓ | ✓ |
| `transaction` `isolation: serializable` | ✓ (`BEGIN IMMEDIATE`) | ✓ | ✓ |


## Troubleshooting

- **Pool exhausted (`POOL_TIMEOUT`)**: bump `pool.max` or shorten the longest-running query. Live `prepareStatement` handles each pin one connection from the pool until they expire.
- **`STATEMENT_NOT_FOUND` from a long-lived handle**: handles are bounded to `ttl_seconds` (default 3600, max 86400). Re-prepare and retry.
- **`DRIVER_ERROR` "pool connection failed (...)"**: the parenthesized class tells you where to look.
    - `(tls)` — handshake or cert-chain failure. For managed providers (Supabase, self-signed corporate CAs), supply `tls.ca_cert`; see "Connecting to managed providers" above.
    - `(auth)` — credential or pg_hba/SCRAM rejection. Includes Neon's `?channel_binding=require` failing through the pooler endpoint (drop the URL param, use `tls.mode` in YAML).
    - `(network)` — TCP refuse, DNS, route, or peer reset. Check host/port reachability and any firewalls. Through an SSH tunnel: the SSH server could not reach the database host.
    - `(ssh)` — the connection's SSH tunnel failed (server unreachable, authentication, host key). The worker log names the reason; `database::testConnection` reports it with `stage: "ssh"`.
    - `(server-policy)` — server reachable and TLS+auth OK, but the server actively refused (e.g. `max_connections` exceeded, admin shutdown). Look at the worker stderr for the underlying driver message.

## License

Apache 2.0 — see [LICENSE](https://github.com/iii-hq/workers/blob/main/LICENSE).

## skills

This version ships 1 skill file for agents, also browsable on the worker page:

- [`SKILL.md`](https://iii.dev/registry/workers/database?tab=skills&skill=SKILL.md&version=0.6.6)

### SKILL.md

# database

The database worker connects to PostgreSQL, MySQL, and SQLite through a
managed per-database connection pool. Every callable surface lives under
the `database::*` namespace. The driver is chosen from each database URL
scheme (`sqlite:`, `postgres://`, `postgresql://`, `mysql://`).

Runtime settings live in the `configuration` worker under id `database` (or
the `config_id` that `database::listDatabases` reports); pools hot-reload when
the value changes. SQLite is the recommended starting point. Placeholder
syntax: `?` for SQLite and MySQL, `$1`/`$2`/… for Postgres.

## Querying a connection

Each configured connection has a name; pass it as `db` on every call.

1. `database::listDatabases` — the connections: `name`, `driver`, `host`,
   `database`, `folder` (where its saved `.sql` files live, if any) and
   `error` when it is unavailable (unresolvable secret, SSH failure). An
   unavailable connection fails its calls with `CONFIG_ERROR` saying why;
   tell the person rather than retrying.
2. `database::listTables {db}` / `database::describeTable {db, table}` — the
   schema, one shape on every driver.
3. `database::query {db, sql, params?, max_rows?}` — reads. Pass `max_rows`
   (e.g. 100) for exploratory queries: the result says `truncated: true` when
   more rows existed, and the SQL is never rewritten. `elapsed_ms` is the
   statement's time.
4. `database::execute {db, sql, params?}` — writes.

A chat may mention a connection as `@database(id="shop")`: that is the
connection named `shop`; use `db: "shop"`.

### Saving a query

"Save a query" means a `.sql` file in the connection's queries folder — the
`folder` from `database::listDatabases` (or the mention's summary). Write the
file there with the file tools (format it first with `database::formatSql`);
that folder is what the apps list as the connection's queries. A connection
without a `folder` has nowhere to save one: say so. `database::saveQuery` is
something else — a console-only snippet list in the `state` worker, not a
file — so never answer "saved as t3_status.sql" after calling it.

Connections are managed by people (the console, the iii app): agents cannot
read a stored entry (`getConnection`), save, delete or test one. Never ask for or
handle database passwords; connections reference them as `secret://NAME`.

## When to Use

- You need to read rows from a configured database (`database::query`).
- You need to insert, update, delete, or run DDL and read affected-row
  counts or autoincrement ids (`database::execute`).
- Several statements must commit or roll back together as one unit
  (`database::transaction`, `database::executeBatch`, or the interactive
  transaction surface).
- The same parameterized SQL will run many times and you want to skip
  per-call parse/plan cost (`database::prepareStatement` +
  `database::runStatement`).
- You need read-your-writes across round-trips with logic between steps
  (`database::beginTransaction` … `commitTransaction` / `rollbackTransaction`).

## Boundaries

- Not a migration tool, ORM, or schema designer — pass raw SQL only.
- Not a general pub/sub bus. `database::on-row-changed` reports what THIS
  worker wrote, on commit (`capture: statements`, the default) or, on a
  `capture: native` database, any client's committed writes.
- `database::query` is read-oriented; use `database::execute` for writes.
  Keep reads on `query`: it runs them read-only, `execute` does not.
- Prepared handles pin a pool connection until TTL expiry — not transactions.
  Batch `database::transaction` / `database::executeBatch` need every
  statement up front; use the interactive surface when code must branch
  between steps.
- Rows come back from a `RETURNING` clause written into the SQL (SQLite,
  Postgres; MySQL has none). The `returning` option never adds the clause:
  SQLite rejects it without one, Postgres and MySQL ignore it. SQLite
  degrades `read_committed` / `repeatable_read` isolation to serializable.
- For filesystem or shell operations, use the `shell` worker instead.

## Functions

- `database::query` — run read-only SQL and return rows, row count, and
  column metadata.
- `database::execute` — run write SQL (INSERT/UPDATE/DELETE/DDL) and
  return affected rows, optional last insert id, and the rows of a
  `RETURNING` clause in the SQL.
- `database::executeBatch` — convenience form of `transaction`: statements
  may be bare SQL strings or `{sql, params}` objects (prefer `params` for
  dynamic values). Same atomic semantics, envelope, and `failed_index`
  reporting as `transaction`.
- `database::prepareStatement` — parse and plan SQL once; return a handle
  that pins a pool connection until TTL expiry.
- `database::runStatement` — re-execute a prepared handle with new bind
  params; response shape matches `query`.
- `database::transaction` — run an ordered batch of statements atomically;
  rolls back on first failure and reports `failed_index`.
- `database::beginTransaction` — open an interactive transaction and
  return an id plus expiry deadline.
- `database::transactionQuery` — read SQL inside an open interactive
  transaction; same envelope as `query`.
- `database::transactionExecute` — write SQL inside an open interactive
  transaction; same envelope as `execute`. Rejects bare transaction-control
  SQL — finalize via `commitTransaction` or `rollbackTransaction`.
- `database::commitTransaction` — commit and finalize an interactive
  transaction.
- `database::rollbackTransaction` — roll back and finalize an interactive
  transaction.
- `database::listDatabases` — every configured connection with its driver,
  host, database, folder, credential-redacted URL, pool settings, TLS mode and
  `error` when unavailable. Config only; use `database::health` for live state.
- `database::testConnection` — probe a candidate connection entry without
  saving it (people only: agents are denied it, like the connection editor
  functions).

Interactive transactions auto-roll back when `timeout_ms` elapses (default
30 s, max 5 min). Prepared handles default to a 1 h TTL (max 24 h) with no
explicit release call — let them expire or stop using them when done.

### Reading the schema

One shape across all three drivers — prefer these over hand-writing
`sqlite_master` / `information_schema` / `PRAGMA`.

- `database::listTables` — tables and views, with kind, (postgres) schema and
  a `row_count_estimate` where the catalog has one (postgres, mysql).
- `database::describeTable` — columns with type, nullability, default, primary
  key, a structured `foreign_key` of `{ schema, table, column }`,
  `auto_increment` (identity / serial / AUTO_INCREMENT / sqlite rowid — leave it
  out of `insertRow`) and `generated` (computed, never written); plus indexes
  and a planner row estimate.
- `database::describeSchema` — the same for every table in one pass. Use this
  rather than looping `describeTable`.
- `database::schemaDiagram` — positioned nodes, routed foreign-key edges, hub
  `degree` and `isolated` tables. For reasoning about a schema's shape, not
  only for drawing it.

### Reading data

- `database::browseTable` — paged, sorted, filtered reads with no SQL. Filters
  are `{ column, op, value }` and `total` honours them; values compare as the
  column's type (on postgres `{column: "total", op: "gt", value: "100"}` is a
  numeric comparison; dates, uuids, enums and int8 as strings work too). Follow a foreign key
  with an equality filter at `page_size: 1`. A filter may be
  `{ raw: "price > 10 AND name LIKE 'a%'" }` — one boolean expression (no `;`,
  comments or placeholders), run read-only.
- `database::distinctValues` — a column's values by frequency (`search` to
  narrow), e.g. to learn the statuses a table actually uses.
- `database::explain` — the plan as a tree with costs and warnings. `analyze`
  **runs** the statement, so it defaults to false and is refused for anything
  that is not a single read.
- `database::columnStats` — planner statistics by default (approximate,
  labelled `source: planner`); `exact: true` scans. To profile rows you already
  hold, use the `fp` worker on a `browseTable` result instead.

### Writing rows and formatting SQL

- `database::insertRow {db, table, values}` — insert one row from a
  `{column: value}` map; values are cast to each column's type (numbers and
  dates may be strings, bytea/blob take base64) and the inserted row comes
  back. Prefer it over hand-built INSERTs when you have a record in hand.
- `database::formatSql {sql, db}` (or `driver`) — pretty-print SQL for the connection's
  dialect, comments kept. Use it before writing a `.sql` file into a
  connection's `folder`.

### Values

Rows are JSON objects. Postgres `bigint`/`numeric` and every `decimal` come
back as strings (exact), `json` columns as JSON values, binary columns as
base64, dates as `YYYY-MM-DD`, timestamps as RFC 3339 with `Z`, postgres
arrays as JSON arrays. When writing them back, pass the same forms.

### Operations and reuse

- `database::health` — pool occupancy, active queries, table sizes, locks,
  cache ratio. Each section is `available`, `unsupported` or `denied`, so a
  driver gap is never mistaken for an empty result.
- `database::terminateQuery` — end a session, or cancel its statement with
  `cancel_only`. Takes an id from `database::health`.
- `database::saveQuery`, `database::listSavedQueries`,
  `database::deleteSavedQuery` — the web console's snippet list per database,
  kept in the `state` worker: console-only, not files. To save a query for
  the person, write a `.sql` file into the connection's `folder` (see
  "Saving a query").
- `database::history` — recent queries, newest first. Best effort: records only while
  `history_max_entries` is above `0` (off by default); earlier entries stay
  readable; not an audit log; observe `database::on-row-changed` for that.

## Reacting to writes

`database::on-row-changed` announces each committed write statement, so
nothing polls. Observe it with args naming the database, and optionally the
table and operations, plus filters on what changed:

```json
{
  "function_id": "database::on-row-changed",
  "args": { "db": "primary", "table": "orders", "ops": ["update"] },
  "filters": { "input.returning": { "$any": { "@.status": { "$eq": "paid" } } } }
}
```

In a session, pass the same `function_id`, `args` and `filters` to
`harness::observe`.

`table` is the bare lowercase name (`orders`, not `public.Orders`); anything
else is refused with the name to use. The event is
`{ db, schema, table, op, affected_rows, returning?, truncated?, at }`, and
`caller.parent` names the function that made the write. The function is
private: only the database worker calls it, so nobody else can raise an
event.

It fires on commit — an interactive transaction's writes are
announced by `commitTransaction`, and a rollback announces nothing.
`returning` says which rows: on a `capture: statements` database it is the
writer's own `RETURNING` projection, so write `RETURNING <primary key>` into
the SQL when a listener needs row identity; on a `capture: native` database
(which also hears other clients' writes, and needs a `table`) it is the
changed rows' primary keys, capped at 100 with `truncated: true` past that.
`table` is null when the statement's table cannot be read off the SQL (a
CTE-wrapped write), and `runStatement` does not fire on the statements path
because it has no affected-row count to report. Delivery is best-effort: it
is not durable with the commit and has no replay or exactly-once guarantee,
and a target can receive events in any order (an observer with
`max_in_flight: 1` receives them one at a time, a transaction's statements
in commit order).

## api reference

```json
{
  "functions": [
    {
      "description": "Open an interactive transaction; returns a handle to use with transactionQuery/transactionExecute/commitTransaction/rollbackTransaction.",
      "metadata": {},
      "name": "database::beginTransaction",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "description": "Logical database name. Optional — omitting it targets the sole configured database, or `primary` when several are configured.",
            "type": [
              "string",
              "null"
            ]
          },
          "isolation": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "timeout_ms": {
            "default": null,
            "format": "uint64",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          }
        },
        "title": "BeginTxReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "TxHandleResponse": {
            "description": "JSON wire envelope returned by `beginTransaction`.",
            "properties": {
              "expires_at": {
                "format": "date-time",
                "type": "string"
              },
              "id": {
                "type": "string"
              }
            },
            "required": [
              "expires_at",
              "id"
            ],
            "type": "object"
          }
        },
        "properties": {
          "transaction": {
            "$ref": "#/definitions/TxHandleResponse"
          }
        },
        "required": [
          "transaction"
        ],
        "title": "BeginTxResp",
        "type": "object"
      }
    },
    {
      "description": "Read a table page by page with typed filters and sorts, without writing SQL. Filters are structured (column, op, value) and compile to a parameterised WHERE for the driver in hand; the total honours the same filters. Use an equality filter at page_size 1 to follow a foreign key.",
      "metadata": {},
      "name": "database::browseTable",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "Direction": {
            "enum": [
              "asc",
              "desc"
            ],
            "type": "string"
          },
          "FilterOp": {
            "oneOf": [
              {
                "enum": [
                  "contains",
                  "not_contains",
                  "equals",
                  "not_equals",
                  "starts_with",
                  "ends_with",
                  "gt",
                  "gte",
                  "lt",
                  "lte",
                  "is_true",
                  "is_false",
                  "is_null",
                  "is_not_null",
                  "not_in"
                ],
                "type": "string"
              },
              {
                "description": "Inclusive range; needs both `value` and `value2`.",
                "enum": [
                  "between"
                ],
                "type": "string"
              },
              {
                "description": "NULL or the empty string. Distinct from `is_null` on purpose.",
                "enum": [
                  "is_empty"
                ],
                "type": "string"
              },
              {
                "description": "Set membership, over `values`.",
                "enum": [
                  "in"
                ],
                "type": "string"
              }
            ]
          },
          "FilterSpec": {
            "properties": {
              "case_sensitive": {
                "default": null,
                "description": "Postgres only. Rejected elsewhere rather than silently ignored.",
                "type": [
                  "boolean",
                  "null"
                ]
              },
              "column": {
                "default": "",
                "description": "The column (ignored with `raw`).",
                "type": "string"
              },
              "disabled": {
                "default": false,
                "description": "Kept in the list but not applied.",
                "type": "boolean"
              },
              "op": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/FilterOp"
                  },
                  {
                    "type": "null"
                  }
                ],
                "default": null,
                "description": "The operator (ignored with `raw`; required otherwise)."
              },
              "raw": {
                "default": null,
                "description": "A SQL boolean expression in the driver's dialect (`price > 10 AND name ILIKE 'a%'`), ANDed with the other filters inside its own parentheses. One expression only: no `;`, no comments, no unbalanced parentheses, no placeholders — and it runs in a read-only transaction (sqlite: `query_only`), so it can never write.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "value": {
                "default": null
              },
              "value2": {
                "default": null,
                "description": "Upper bound for `between`."
              },
              "values": {
                "default": [],
                "description": "Operands for `in` / `not_in`.",
                "items": true,
                "type": "array"
              }
            },
            "type": "object"
          },
          "NullsPosition": {
            "enum": [
              "first",
              "last"
            ],
            "type": "string"
          },
          "SortMode": {
            "description": "Type-aware sort modes, applied server-side over the whole table.",
            "oneOf": [
              {
                "enum": [
                  "default",
                  "length",
                  "absolute_value",
                  "random"
                ],
                "type": "string"
              },
              {
                "description": "`item2` before `item10`. The mode users actually notice.",
                "enum": [
                  "natural"
                ],
                "type": "string"
              }
            ]
          },
          "SortSpec": {
            "properties": {
              "column": {
                "type": "string"
              },
              "direction": {
                "allOf": [
                  {
                    "$ref": "#/definitions/Direction"
                  }
                ],
                "default": "asc"
              },
              "mode": {
                "allOf": [
                  {
                    "$ref": "#/definitions/SortMode"
                  }
                ],
                "default": "default"
              },
              "nulls": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/NullsPosition"
                  },
                  {
                    "type": "null"
                  }
                ],
                "default": null
              }
            },
            "required": [
              "column"
            ],
            "type": "object"
          }
        },
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "filters": {
            "description": "Combined with AND. A filter with `raw` is a SQL boolean expression (see `FilterSpec::raw`), ANDed in its own parentheses.",
            "items": {
              "$ref": "#/definitions/FilterSpec"
            },
            "type": "array"
          },
          "include_total": {
            "default": true,
            "description": "A filtered `COUNT(*)` is a second query and can be expensive on a large table. Turn it off while the caller is still typing.",
            "type": "boolean"
          },
          "page": {
            "default": 0,
            "description": "Zero-based.",
            "format": "uint32",
            "minimum": 0,
            "type": "integer"
          },
          "page_size": {
            "default": 50,
            "format": "uint32",
            "minimum": 0,
            "type": "integer"
          },
          "schema": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "sort": {
            "description": "Applied in order; sort priority is position in the list.",
            "items": {
              "$ref": "#/definitions/SortSpec"
            },
            "type": "array"
          },
          "table": {
            "type": "string"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "table"
        ],
        "title": "BrowseTableReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ColumnMeta": {
            "properties": {
              "name": {
                "type": "string"
              },
              "type": {
                "type": "string"
              }
            },
            "required": [
              "name",
              "type"
            ],
            "type": "object"
          }
        },
        "properties": {
          "columns": {
            "items": {
              "$ref": "#/definitions/ColumnMeta"
            },
            "type": "array"
          },
          "elapsed_ms": {
            "description": "Time the database spent on the page (and the count, when asked), in milliseconds.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "has_more": {
            "description": "Derived from a sentinel row, so it is correct without a count.",
            "type": "boolean"
          },
          "page": {
            "format": "uint32",
            "minimum": 0,
            "type": "integer"
          },
          "page_size": {
            "format": "uint32",
            "minimum": 0,
            "type": "integer"
          },
          "rows": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          },
          "total": {
            "description": "Total matching the same filters. Absent when not requested.",
            "format": "int64",
            "type": [
              "integer",
              "null"
            ]
          }
        },
        "required": [
          "columns",
          "elapsed_ms",
          "has_more",
          "page",
          "page_size",
          "rows"
        ],
        "title": "BrowseTableResp",
        "type": "object"
      }
    },
    {
      "description": "Profile a table's columns. Reads the planner's own statistics by default, which is free and approximate; `exact` runs real aggregates and scans the table. To profile rows you already hold, pipe a browseTable result through the fp worker instead.",
      "metadata": {},
      "name": "database::columnStats",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "columns": {
            "default": null,
            "description": "Omit to profile every column.",
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "exact": {
            "default": false,
            "description": "Run real aggregates instead of reading planner statistics. This scans the table.",
            "type": "boolean"
          },
          "schema": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "type": "string"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "top_n": {
            "default": 10,
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "table"
        ],
        "title": "ColumnStatsReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ColumnStat": {
            "properties": {
              "distinct_count": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "max": true,
              "mean": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "min": true,
              "name": {
                "type": "string"
              },
              "null_count": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "null_fraction": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "row_count": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "source": {
                "$ref": "#/definitions/StatSource"
              },
              "top_values": {
                "description": "Only populated in `exact` mode; the planner's own most-common-value lists are not portable enough to report faithfully.",
                "items": {
                  "$ref": "#/definitions/TopValue"
                },
                "type": "array"
              }
            },
            "required": [
              "name",
              "source",
              "top_values"
            ],
            "type": "object"
          },
          "StatSource": {
            "oneOf": [
              {
                "description": "Read from the planner's own statistics. Approximate, and free.",
                "enum": [
                  "planner"
                ],
                "type": "string"
              },
              {
                "description": "Counted by running aggregates over the table.",
                "enum": [
                  "computed"
                ],
                "type": "string"
              }
            ]
          },
          "TopValue": {
            "properties": {
              "count": {
                "format": "int64",
                "type": "integer"
              },
              "value": true
            },
            "required": [
              "count",
              "value"
            ],
            "type": "object"
          }
        },
        "properties": {
          "approximate": {
            "description": "True when the numbers came from the planner rather than a count.",
            "type": "boolean"
          },
          "columns": {
            "items": {
              "$ref": "#/definitions/ColumnStat"
            },
            "type": "array"
          },
          "schema": {
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "type": "string"
          }
        },
        "required": [
          "approximate",
          "columns",
          "table"
        ],
        "title": "ColumnStatsResp",
        "type": "object"
      }
    },
    {
      "description": "Commit an open SQL transaction, making its writes permanent.",
      "metadata": {},
      "name": "database::commitTransaction",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "transaction_id": {
            "type": "string"
          }
        },
        "required": [
          "transaction_id"
        ],
        "title": "CommitTxReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "committed": {
            "type": "boolean"
          }
        },
        "required": [
          "committed"
        ],
        "title": "CommitTxResp",
        "type": "object"
      }
    },
    {
      "description": "Remove a connection from the database configuration and close its pool. The last connection cannot be removed.",
      "metadata": {},
      "name": "database::deleteConnection",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "name": {
            "type": "string"
          }
        },
        "required": [
          "name"
        ],
        "title": "DeleteConnectionReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "deleted": {
            "type": "boolean"
          }
        },
        "required": [
          "deleted"
        ],
        "title": "DeleteConnectionResp",
        "type": "object"
      }
    },
    {
      "description": "Delete a saved query by id or by name.",
      "metadata": {},
      "name": "database::deleteSavedQuery",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "id": {
            "description": "Either the id returned by `saveQuery`, or the name it was saved under.",
            "type": "string"
          }
        },
        "required": [
          "id"
        ],
        "title": "DeleteSavedReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "deleted": {
            "type": "boolean"
          }
        },
        "required": [
          "deleted"
        ],
        "title": "DeleteSavedResp",
        "type": "object"
      }
    },
    {
      "description": "Describe every table at once — the same shape as describeTable, but one catalog query per aspect across the whole database instead of one call per table. Use this to reason about relationships; set include_indexes only when you need them.",
      "metadata": {},
      "name": "database::describeSchema",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "include_indexes": {
            "default": false,
            "description": "Indexes cost one extra catalog query. Off by default because the common caller (a relationship diagram) only needs columns and keys.",
            "type": "boolean"
          },
          "max_tables": {
            "default": 500,
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "tables": {
            "default": null,
            "description": "Restrict to these tables. Omit for every table in the database.",
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "title": "DescribeSchemaReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ColumnDesc": {
            "properties": {
              "auto_increment": {
                "description": "The database fills it in: postgres identity or `nextval` default, mysql `AUTO_INCREMENT`, sqlite `INTEGER PRIMARY KEY` (the rowid).",
                "type": "boolean"
              },
              "default_value": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "foreign_key": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/ForeignKeyRef"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "generated": {
                "description": "Computed from other columns (`GENERATED ALWAYS AS …`); cannot be written.",
                "type": "boolean"
              },
              "name": {
                "type": "string"
              },
              "nullable": {
                "type": "boolean"
              },
              "position": {
                "description": "1-based ordinal, as the driver reports it.",
                "format": "int32",
                "type": "integer"
              },
              "primary_key": {
                "type": "boolean"
              },
              "type": {
                "description": "Driver-reported type text (`TEXT`, `integer`, `varchar(255)`).",
                "type": "string"
              }
            },
            "required": [
              "auto_increment",
              "generated",
              "name",
              "nullable",
              "position",
              "primary_key",
              "type"
            ],
            "type": "object"
          },
          "ForeignKeyRef": {
            "description": "Where a foreign key points. Structured rather than a `\"table.column\"` string so a schema-qualified target stays unambiguous.",
            "properties": {
              "column": {
                "type": "string"
              },
              "schema": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "table": {
                "type": "string"
              }
            },
            "required": [
              "column",
              "table"
            ],
            "type": "object"
          },
          "IndexDesc": {
            "properties": {
              "columns": {
                "description": "Indexed columns in ordinal order. Empty when the index is on an expression rather than plain columns.",
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "name": {
                "type": "string"
              },
              "primary": {
                "type": "boolean"
              },
              "unique": {
                "type": "boolean"
              }
            },
            "required": [
              "columns",
              "name",
              "primary",
              "unique"
            ],
            "type": "object"
          },
          "TableDescription": {
            "properties": {
              "columns": {
                "items": {
                  "$ref": "#/definitions/ColumnDesc"
                },
                "type": "array"
              },
              "indexes": {
                "items": {
                  "$ref": "#/definitions/IndexDesc"
                },
                "type": "array"
              },
              "kind": {
                "$ref": "#/definitions/TableKind"
              },
              "row_count_estimate": {
                "description": "Planner estimate, never a `COUNT(*)`. Absent when the driver has no cheap estimate (sqlite) or has not analyzed the table yet.",
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "schema": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "table": {
                "type": "string"
              }
            },
            "required": [
              "columns",
              "indexes",
              "kind",
              "table"
            ],
            "type": "object"
          },
          "TableKind": {
            "enum": [
              "table",
              "view"
            ],
            "type": "string"
          }
        },
        "properties": {
          "count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "tables": {
            "items": {
              "$ref": "#/definitions/TableDescription"
            },
            "type": "array"
          },
          "truncated": {
            "description": "True when `max_tables` cut the result short. Never silently truncate.",
            "type": "boolean"
          }
        },
        "required": [
          "count",
          "tables",
          "truncated"
        ],
        "title": "DescribeSchemaResp",
        "type": "object"
      }
    },
    {
      "description": "Describe one table or view: columns with type, nullability, default, primary-key membership and foreign-key target; plus indexes and a planner row estimate. Foreign keys are structured (schema, table, column), not a joined string.",
      "metadata": {},
      "name": "database::describeTable",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "schema": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "description": "Table or view name; may be schema-qualified (`analytics.events`) on postgres. Use `schema` when the name itself contains a dot.",
            "type": "string"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "table"
        ],
        "title": "DescribeTableReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ColumnDesc": {
            "properties": {
              "auto_increment": {
                "description": "The database fills it in: postgres identity or `nextval` default, mysql `AUTO_INCREMENT`, sqlite `INTEGER PRIMARY KEY` (the rowid).",
                "type": "boolean"
              },
              "default_value": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "foreign_key": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/ForeignKeyRef"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "generated": {
                "description": "Computed from other columns (`GENERATED ALWAYS AS …`); cannot be written.",
                "type": "boolean"
              },
              "name": {
                "type": "string"
              },
              "nullable": {
                "type": "boolean"
              },
              "position": {
                "description": "1-based ordinal, as the driver reports it.",
                "format": "int32",
                "type": "integer"
              },
              "primary_key": {
                "type": "boolean"
              },
              "type": {
                "description": "Driver-reported type text (`TEXT`, `integer`, `varchar(255)`).",
                "type": "string"
              }
            },
            "required": [
              "auto_increment",
              "generated",
              "name",
              "nullable",
              "position",
              "primary_key",
              "type"
            ],
            "type": "object"
          },
          "ForeignKeyRef": {
            "description": "Where a foreign key points. Structured rather than a `\"table.column\"` string so a schema-qualified target stays unambiguous.",
            "properties": {
              "column": {
                "type": "string"
              },
              "schema": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "table": {
                "type": "string"
              }
            },
            "required": [
              "column",
              "table"
            ],
            "type": "object"
          },
          "IndexDesc": {
            "properties": {
              "columns": {
                "description": "Indexed columns in ordinal order. Empty when the index is on an expression rather than plain columns.",
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "name": {
                "type": "string"
              },
              "primary": {
                "type": "boolean"
              },
              "unique": {
                "type": "boolean"
              }
            },
            "required": [
              "columns",
              "name",
              "primary",
              "unique"
            ],
            "type": "object"
          },
          "TableKind": {
            "enum": [
              "table",
              "view"
            ],
            "type": "string"
          }
        },
        "properties": {
          "columns": {
            "items": {
              "$ref": "#/definitions/ColumnDesc"
            },
            "type": "array"
          },
          "indexes": {
            "items": {
              "$ref": "#/definitions/IndexDesc"
            },
            "type": "array"
          },
          "kind": {
            "$ref": "#/definitions/TableKind"
          },
          "row_count_estimate": {
            "description": "Planner estimate, never a `COUNT(*)`. Absent when the driver has no cheap estimate (sqlite) or has not analyzed the table yet.",
            "format": "int64",
            "type": [
              "integer",
              "null"
            ]
          },
          "schema": {
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "type": "string"
          }
        },
        "required": [
          "columns",
          "indexes",
          "kind",
          "table"
        ],
        "title": "TableDescription",
        "type": "object"
      }
    },
    {
      "description": "List the distinct values of one column, most frequent first, with their row counts — for a filter's value picker. `search` narrows by a case-insensitive substring of the text form.",
      "metadata": {},
      "name": "database::distinctValues",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "column": {
            "type": "string"
          },
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "limit": {
            "default": null,
            "description": "Default 50, at most 500.",
            "format": "uint32",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          },
          "schema": {
            "default": null,
            "description": "Postgres schema; ignored elsewhere.",
            "type": [
              "string",
              "null"
            ]
          },
          "search": {
            "default": null,
            "description": "Keep values whose text form contains this, case-insensitively.",
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "type": "string"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "column",
          "table"
        ],
        "title": "DistinctValuesReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "DistinctValue": {
            "properties": {
              "count": {
                "description": "Rows holding it.",
                "format": "int64",
                "type": "integer"
              },
              "value": {
                "description": "The value as JSON (`null` for NULL), the same encoding as query rows."
              }
            },
            "required": [
              "count",
              "value"
            ],
            "type": "object"
          }
        },
        "properties": {
          "elapsed_ms": {
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "truncated": {
            "description": "More distinct values exist past `limit`.",
            "type": "boolean"
          },
          "values": {
            "items": {
              "$ref": "#/definitions/DistinctValue"
            },
            "type": "array"
          }
        },
        "required": [
          "elapsed_ms",
          "truncated",
          "values"
        ],
        "title": "DistinctValuesResp",
        "type": "object"
      }
    },
    {
      "description": "Run a write statement (INSERT/UPDATE/DELETE/DDL); put RETURNING in the SQL to get rows back and into row-changed events. The `returning` option never adds the clause.",
      "metadata": {},
      "name": "database::execute",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "description": "Logical database name. Optional — omitting it targets the sole configured database, or `primary` when several are configured.",
            "type": [
              "string",
              "null"
            ]
          },
          "params": {
            "default": [],
            "items": true,
            "type": "array"
          },
          "returning": {
            "default": [],
            "description": "Optional, and NOT what produces rows: this never adds a `RETURNING` clause or projects columns — write the clause into `sql`. SQLite refuses a non-empty list when the statement returns no rows (`RETURNING_MISMATCH`), so a write cannot silently lose its identity; Postgres and MySQL ignore the list with a warning.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "sql": {
            "description": "The write statement. To get rows back — and to have them ride the `database::on-row-changed` event this write fires — put a `RETURNING` clause in the SQL itself: `INSERT INTO t (n) VALUES (?) RETURNING id` (SQLite, Postgres; MySQL has no RETURNING). Without one the response has `returned_rows: []` and the event carries only `affected_rows`.",
            "type": "string"
          }
        },
        "required": [
          "sql"
        ],
        "title": "ExecuteReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "affected_rows": {
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "elapsed_ms": {
            "description": "Time the database spent running the statement (pool acquisition excluded), in milliseconds.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "last_insert_id": {
            "description": "SQLite/MySQL: the engine's last insert id, INSERT only. Postgres has none, so it is the first column of the first `RETURNING` row of an INSERT — put the key first: `RETURNING id, name`.",
            "type": [
              "string",
              "null"
            ]
          },
          "returned_rows": {
            "description": "The rows the SQL's `RETURNING` clause produced (or a `SELECT`/`VALUES` sent here). Empty without such a clause.",
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "affected_rows",
          "elapsed_ms",
          "returned_rows"
        ],
        "title": "ExecuteResp",
        "type": "object"
      }
    },
    {
      "description": "Run an ordered batch of SQL statements atomically (bare strings or {sql, params} objects); rolls back on first failure. A statement's RETURNING rows come back in results[].rows.",
      "metadata": {},
      "name": "database::executeBatch",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "BatchStatement": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "$ref": "#/definitions/TxStmtReq"
              }
            ]
          },
          "TxStmtReq": {
            "properties": {
              "params": {
                "default": [],
                "items": true,
                "type": "array"
              },
              "sql": {
                "description": "One statement. A `RETURNING` clause in the SQL (SQLite, Postgres) puts the rows in this step's `results[].rows` and on the `database::on-row-changed` event fired for it after commit.",
                "type": "string"
              }
            },
            "required": [
              "sql"
            ],
            "type": "object"
          }
        },
        "properties": {
          "db": {
            "default": null,
            "description": "Logical database name. Optional — omitting it targets the sole configured database, or `primary` when several are configured.",
            "type": [
              "string",
              "null"
            ]
          },
          "isolation": {
            "default": null,
            "description": "Optional: `read_committed` | `repeatable_read` | `serializable`.",
            "type": [
              "string",
              "null"
            ]
          },
          "statements": {
            "description": "Statements to run in order inside one transaction. Put dynamic values in `params`, not inline in the SQL.",
            "items": {
              "$ref": "#/definitions/BatchStatement"
            },
            "type": "array"
          }
        },
        "required": [
          "statements"
        ],
        "title": "ExecuteBatchReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "TxStepResp": {
            "properties": {
              "affected_rows": {
                "format": "uint64",
                "minimum": 0,
                "type": "integer"
              },
              "rows": {
                "items": {
                  "items": true,
                  "type": "array"
                },
                "type": "array"
              }
            },
            "required": [
              "affected_rows",
              "rows"
            ],
            "type": "object"
          }
        },
        "properties": {
          "committed": {
            "type": "boolean"
          },
          "error": true,
          "failed_index": {
            "format": "uint",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          },
          "results": {
            "items": {
              "$ref": "#/definitions/TxStepResp"
            },
            "type": [
              "array",
              "null"
            ]
          }
        },
        "required": [
          "committed"
        ],
        "title": "TxResp",
        "type": "object"
      }
    },
    {
      "description": "Explain a statement's query plan as a tree with per-node costs, row estimates and warnings. `analyze` collects real timings by RUNNING the statement, so it defaults to false and is refused for anything that is not a single read.",
      "metadata": {},
      "name": "database::explain",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "analyze": {
            "default": false,
            "description": "Runs the statement to collect real timings. Refused for anything that is not a read.",
            "type": "boolean"
          },
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "params": {
            "default": [],
            "items": true,
            "type": "array"
          },
          "sql": {
            "type": "string"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "sql"
        ],
        "title": "ExplainReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "NodeClass": {
            "enum": [
              "scan",
              "index",
              "join",
              "sort",
              "aggregate",
              "cte",
              "limit",
              "other"
            ],
            "type": "string"
          },
          "PlanFormat": {
            "enum": [
              "pg_json",
              "sqlite_query_plan",
              "mysql_json",
              "unknown"
            ],
            "type": "string"
          },
          "PlanNode": {
            "properties": {
              "children": {
                "items": {
                  "$ref": "#/definitions/PlanNode"
                },
                "type": "array"
              },
              "cost_startup": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "cost_total": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "detail": {
                "type": "string"
              },
              "id": {
                "format": "uint32",
                "minimum": 0,
                "type": "integer"
              },
              "label": {
                "type": "string"
              },
              "loops": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "node_class": {
                "$ref": "#/definitions/NodeClass"
              },
              "parent": {
                "format": "uint32",
                "minimum": 0,
                "type": [
                  "integer",
                  "null"
                ]
              },
              "relation": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "rows_actual": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "rows_estimated": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "time_ms": {
                "format": "double",
                "type": [
                  "number",
                  "null"
                ]
              },
              "width": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              }
            },
            "required": [
              "children",
              "detail",
              "id",
              "label",
              "node_class"
            ],
            "type": "object"
          },
          "PlanWarning": {
            "properties": {
              "kind": {
                "$ref": "#/definitions/WarningKind"
              },
              "message": {
                "type": "string"
              },
              "node_id": {
                "format": "uint32",
                "minimum": 0,
                "type": "integer"
              },
              "severity": {
                "$ref": "#/definitions/Severity"
              }
            },
            "required": [
              "kind",
              "message",
              "node_id",
              "severity"
            ],
            "type": "object"
          },
          "Severity": {
            "enum": [
              "info",
              "warn"
            ],
            "type": "string"
          },
          "WarningKind": {
            "oneOf": [
              {
                "description": "A sequential scan over a large relation.",
                "enum": [
                  "seq_scan_large"
                ],
                "type": "string"
              },
              {
                "description": "Estimated and actual row counts differ by an order of magnitude — usually stale statistics.",
                "enum": [
                  "estimate_skew"
                ],
                "type": "string"
              },
              {
                "description": "An inner loop executed a very large number of times.",
                "enum": [
                  "nested_loop_large"
                ],
                "type": "string"
              }
            ]
          }
        },
        "properties": {
          "analyzed": {
            "type": "boolean"
          },
          "format": {
            "$ref": "#/definitions/PlanFormat"
          },
          "raw": {
            "description": "The driver's own output, so a caller is never stuck when the shape is one we do not recognise."
          },
          "root": {
            "anyOf": [
              {
                "$ref": "#/definitions/PlanNode"
              },
              {
                "type": "null"
              }
            ]
          },
          "warnings": {
            "items": {
              "$ref": "#/definitions/PlanWarning"
            },
            "type": "array"
          }
        },
        "required": [
          "analyzed",
          "format",
          "warnings"
        ],
        "title": "ExplainResp",
        "type": "object"
      }
    },
    {
      "description": "Pretty-print SQL for a driver's dialect: keywords cased, clauses indented, statements and comments kept. Pure text; nothing runs.",
      "metadata": {},
      "name": "database::formatSql",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "DriverKind": {
            "enum": [
              "postgres",
              "mysql",
              "sqlite"
            ],
            "type": "string"
          }
        },
        "properties": {
          "db": {
            "default": null,
            "description": "A configured database whose driver picks the dialect.",
            "type": [
              "string",
              "null"
            ]
          },
          "driver": {
            "anyOf": [
              {
                "$ref": "#/definitions/DriverKind"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "The dialect directly: `postgres`, `mysql` or `sqlite` (wins over `db`)."
          },
          "indent": {
            "default": null,
            "description": "Spaces per indent level, 1-8. Default 2.",
            "format": "uint8",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          },
          "sql": {
            "type": "string"
          },
          "uppercase": {
            "default": null,
            "description": "Uppercase keywords. Default true.",
            "type": [
              "boolean",
              "null"
            ]
          }
        },
        "required": [
          "sql"
        ],
        "title": "FormatSqlReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "sql": {
            "type": "string"
          }
        },
        "required": [
          "sql"
        ],
        "title": "FormatSqlResp",
        "type": "object"
      }
    },
    {
      "description": "Read one stored connection entry for editing: references and templates intact, literal passwords, passphrases and keys as \"__redacted__\".",
      "metadata": {},
      "name": "database::getConnection",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "name": {
            "description": "Connection name (the key under `databases`).",
            "type": "string"
          }
        },
        "required": [
          "name"
        ],
        "title": "GetConnectionReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "connection": {
            "description": "The entry as stored: references and `${VAR}` templates intact, literal passwords / passphrases / private keys / url passwords as `\"__redacted__\"`."
          },
          "name": {
            "type": "string"
          }
        },
        "required": [
          "connection",
          "name"
        ],
        "title": "GetConnectionResp",
        "type": "object"
      }
    },
    {
      "description": "Get a table's column layout for reading: widths, hidden columns and column order. Stored in the state worker rather than a browser, so it survives a restart and any caller can set it up for someone else.",
      "metadata": {},
      "name": "database::getTableView",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "type": "string"
          }
        },
        "required": [
          "table"
        ],
        "title": "GetTableViewReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "hidden": {
            "default": [],
            "description": "Columns the reader has hidden. Order is not meaningful.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "order": {
            "default": [],
            "description": "Column display order. Unlisted columns keep their natural position after the listed ones.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "widths": {
            "additionalProperties": {
              "format": "double",
              "type": "number"
            },
            "default": {},
            "description": "Per-column pixel width. Absent means \"size to content\".",
            "type": "object"
          }
        },
        "title": "TableView",
        "type": "object"
      }
    },
    {
      "description": "Check live pool occupancy plus active queries, table sizes, blocking locks and cache hit ratio. Each section reports separately as available, unsupported or denied, so a driver gap or a restricted role never reads as an empty result.",
      "metadata": {},
      "name": "database::health",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "timeout_ms": {
            "default": 15000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "title": "HealthReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ActiveQuery": {
            "properties": {
              "duration_ms": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "id": {
                "type": "string"
              },
              "sql": {
                "type": "string"
              },
              "state": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "user": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "required": [
              "id",
              "sql"
            ],
            "type": "object"
          },
          "CacheStats": {
            "properties": {
              "blocks_hit": {
                "format": "int64",
                "type": "integer"
              },
              "blocks_read": {
                "format": "int64",
                "type": "integer"
              },
              "hit_ratio": {
                "description": "Fraction of block reads served from cache. A healthy OLTP database usually sits well above 0.99.",
                "format": "double",
                "type": "number"
              }
            },
            "required": [
              "blocks_hit",
              "blocks_read",
              "hit_ratio"
            ],
            "type": "object"
          },
          "LockInfo": {
            "properties": {
              "blocked_id": {
                "type": "string"
              },
              "blocked_sql": {
                "type": "string"
              },
              "blocking_id": {
                "type": "string"
              },
              "blocking_sql": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "relation": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "required": [
              "blocked_id",
              "blocked_sql",
              "blocking_id"
            ],
            "type": "object"
          },
          "PoolStats": {
            "description": "Live pool occupancy, for `database::health`.\n\n`size` and `idle` are `None` where the underlying pool does not expose them — `mysql_async` keeps its counters private. Reporting `None` rather than zero matters: \"unknown\" and \"no idle connections\" are different answers, and a health panel that conflates them is actively misleading.",
            "properties": {
              "idle": {
                "format": "uint32",
                "minimum": 0,
                "type": [
                  "integer",
                  "null"
                ]
              },
              "max": {
                "format": "uint32",
                "minimum": 0,
                "type": "integer"
              },
              "size": {
                "format": "uint32",
                "minimum": 0,
                "type": [
                  "integer",
                  "null"
                ]
              },
              "waiting": {
                "format": "uint32",
                "minimum": 0,
                "type": [
                  "integer",
                  "null"
                ]
              }
            },
            "required": [
              "max"
            ],
            "type": "object"
          },
          "ProbeResult_for_Array_of_ActiveQuery": {
            "description": "One section of the report.",
            "oneOf": [
              {
                "description": "The driver answered.",
                "properties": {
                  "data": {
                    "items": {
                      "$ref": "#/definitions/ActiveQuery"
                    },
                    "type": "array"
                  },
                  "status": {
                    "enum": [
                      "available"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "data",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has no equivalent of this concept.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "unsupported"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has it, but this role may not read it.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "denied"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              }
            ]
          },
          "ProbeResult_for_Array_of_LockInfo": {
            "description": "One section of the report.",
            "oneOf": [
              {
                "description": "The driver answered.",
                "properties": {
                  "data": {
                    "items": {
                      "$ref": "#/definitions/LockInfo"
                    },
                    "type": "array"
                  },
                  "status": {
                    "enum": [
                      "available"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "data",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has no equivalent of this concept.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "unsupported"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has it, but this role may not read it.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "denied"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              }
            ]
          },
          "ProbeResult_for_Array_of_TableSize": {
            "description": "One section of the report.",
            "oneOf": [
              {
                "description": "The driver answered.",
                "properties": {
                  "data": {
                    "items": {
                      "$ref": "#/definitions/TableSize"
                    },
                    "type": "array"
                  },
                  "status": {
                    "enum": [
                      "available"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "data",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has no equivalent of this concept.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "unsupported"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has it, but this role may not read it.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "denied"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              }
            ]
          },
          "ProbeResult_for_CacheStats": {
            "description": "One section of the report.",
            "oneOf": [
              {
                "description": "The driver answered.",
                "properties": {
                  "data": {
                    "$ref": "#/definitions/CacheStats"
                  },
                  "status": {
                    "enum": [
                      "available"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "data",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has no equivalent of this concept.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "unsupported"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              },
              {
                "description": "The driver has it, but this role may not read it.",
                "properties": {
                  "reason": {
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "denied"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "reason",
                  "status"
                ],
                "type": "object"
              }
            ]
          },
          "TableSize": {
            "properties": {
              "index_bytes": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "row_estimate": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "schema": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "table": {
                "type": "string"
              },
              "total_bytes": {
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              }
            },
            "required": [
              "table"
            ],
            "type": "object"
          }
        },
        "properties": {
          "active_queries": {
            "$ref": "#/definitions/ProbeResult_for_Array_of_ActiveQuery"
          },
          "cache": {
            "$ref": "#/definitions/ProbeResult_for_CacheStats"
          },
          "db": {
            "type": "string"
          },
          "driver": {
            "type": "string"
          },
          "locks": {
            "$ref": "#/definitions/ProbeResult_for_Array_of_LockInfo"
          },
          "pool": {
            "$ref": "#/definitions/PoolStats"
          },
          "table_sizes": {
            "$ref": "#/definitions/ProbeResult_for_Array_of_TableSize"
          },
          "worker_version": {
            "type": "string"
          }
        },
        "required": [
          "active_queries",
          "cache",
          "db",
          "driver",
          "locks",
          "pool",
          "table_sizes",
          "worker_version"
        ],
        "title": "HealthResp",
        "type": "object"
      }
    },
    {
      "description": "List recent queries run against a database, newest first. Best effort — recording never blocks or fails a query, so it is a convenience, not an audit log. For an audit trail observe database::on-row-changed. Off by default: recorded only while history_max_entries > 0 in the database configuration; earlier entries stay readable.",
      "metadata": {},
      "name": "database::history",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "limit": {
            "default": null,
            "format": "uint",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          }
        },
        "title": "HistoryReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "HistoryEntry": {
            "properties": {
              "at": {
                "type": "string"
              },
              "duration_ms": {
                "format": "uint64",
                "minimum": 0,
                "type": [
                  "integer",
                  "null"
                ]
              },
              "row_count": {
                "format": "uint",
                "minimum": 0,
                "type": [
                  "integer",
                  "null"
                ]
              },
              "sql": {
                "type": "string"
              },
              "verb": {
                "type": "string"
              }
            },
            "required": [
              "at",
              "sql",
              "verb"
            ],
            "type": "object"
          }
        },
        "properties": {
          "count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "entries": {
            "items": {
              "$ref": "#/definitions/HistoryEntry"
            },
            "type": "array"
          }
        },
        "required": [
          "count",
          "entries"
        ],
        "title": "HistoryResp",
        "type": "object"
      }
    },
    {
      "description": "Insert one row from a {column: value} map; values are cast to each column's catalog type (numbers and dates as strings, bytea/blob as base64) and the inserted row comes back. Columns left out take their default.",
      "metadata": {},
      "name": "database::insertRow",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "schema": {
            "default": null,
            "description": "Postgres schema; ignored elsewhere.",
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "type": "string"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "values": {
            "additionalProperties": true,
            "default": {},
            "description": "Column → value. Strings are parsed by the column's type (numbers, booleans, uuids, dates, json); bytea/blob columns take base64. Columns left out take their default.",
            "type": "object"
          }
        },
        "required": [
          "table"
        ],
        "title": "InsertRowReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "affected_rows": {
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "elapsed_ms": {
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "row": {
            "additionalProperties": true,
            "description": "The inserted row as stored (defaults and generated values filled in), or null when it cannot be read back (mysql without a usable key).",
            "type": [
              "object",
              "null"
            ]
          }
        },
        "required": [
          "affected_rows",
          "elapsed_ms"
        ],
        "title": "InsertRowResp",
        "type": "object"
      }
    },
    {
      "description": "List all configured databases with connection details (driver, credential-redacted URL, pool settings, TLS mode). Config only — no health checks or live pool statistics.",
      "metadata": {},
      "name": "database::listDatabases",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "title": "ListDatabasesReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "DatabaseInfo": {
            "properties": {
              "database": {
                "description": "Database (schema) name; the file path for sqlite.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "display": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/DisplayConfig"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "driver": {
                "description": "\"postgres\" | \"mysql\" | \"sqlite\".",
                "type": "string"
              },
              "error": {
                "description": "Why the connection has no pool (an unresolvable reference, an SSH failure, an unreadable certificate…). Absent when it is usable.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "error_stage": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/Stage"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "The step `error` happened at: `config`, `secrets`, `ssh`, `tcp`, `tls`."
              },
              "folder": {
                "description": "Folder of `.sql` query files on the engine host.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "host": {
                "description": "Server host (postgres/mysql), from either form.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "name": {
                "description": "Logical key (e.g. \"primary\").",
                "type": "string"
              },
              "pool": {
                "$ref": "#/definitions/PoolInfo"
              },
              "port": {
                "format": "uint16",
                "minimum": 0,
                "type": [
                  "integer",
                  "null"
                ]
              },
              "ssh": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/SshInfo"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "tls": {
                "$ref": "#/definitions/TlsInfo"
              },
              "url": {
                "description": "Connection URL with credentials redacted (assembled from the fields for the structured form).",
                "type": "string"
              },
              "user": {
                "description": "User name (postgres/mysql), when configured.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "uses_secrets": {
                "description": "Whether any value is a `secret://` / `env://` reference.",
                "type": "boolean"
              }
            },
            "required": [
              "driver",
              "name",
              "pool",
              "tls",
              "url",
              "uses_secrets"
            ],
            "type": "object"
          },
          "DisplayConfig": {
            "description": "How a client draws a connection. The worker only stores it.",
            "properties": {
              "color": {
                "description": "`#RRGGBB`.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "icon": {
                "description": "A Lucide icon name (`database`, `server`, `cloud`, …).",
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "type": "object"
          },
          "PoolInfo": {
            "description": "Pool settings echoed back from config (no live stats).",
            "properties": {
              "acquire_timeout_ms": {
                "format": "uint64",
                "minimum": 0,
                "type": "integer"
              },
              "idle_timeout_ms": {
                "format": "uint64",
                "minimum": 0,
                "type": "integer"
              },
              "max": {
                "format": "uint32",
                "minimum": 0,
                "type": "integer"
              }
            },
            "required": [
              "acquire_timeout_ms",
              "idle_timeout_ms",
              "max"
            ],
            "type": "object"
          },
          "SshInfo": {
            "description": "The SSH tunnel's server (no credentials).",
            "properties": {
              "host": {
                "type": "string"
              },
              "host_key_pinned": {
                "description": "Whether `host_key` pins the server's key.",
                "type": "boolean"
              },
              "port": {
                "format": "uint16",
                "minimum": 0,
                "type": "integer"
              },
              "user": {
                "type": "string"
              }
            },
            "required": [
              "host",
              "host_key_pinned",
              "port",
              "user"
            ],
            "type": "object"
          },
          "Stage": {
            "description": "Where an attempt to reach a database failed.",
            "oneOf": [
              {
                "description": "The entry itself is unusable (unparseable url, unreadable file).",
                "enum": [
                  "config"
                ],
                "type": "string"
              },
              {
                "description": "A `secret://` / `env://` reference did not resolve.",
                "enum": [
                  "secrets"
                ],
                "type": "string"
              },
              {
                "description": "The SSH tunnel: server unreachable, host key, authentication.",
                "enum": [
                  "ssh"
                ],
                "type": "string"
              },
              {
                "description": "The database server (or the tunnel's far end) is unreachable.",
                "enum": [
                  "tcp"
                ],
                "type": "string"
              },
              {
                "description": "TLS negotiation or certificate validation.",
                "enum": [
                  "tls"
                ],
                "type": "string"
              },
              {
                "description": "The database refused the credentials.",
                "enum": [
                  "auth"
                ],
                "type": "string"
              },
              {
                "description": "Connected and authenticated, but the database is missing or unusable.",
                "enum": [
                  "database"
                ],
                "type": "string"
              }
            ]
          },
          "TlsInfo": {
            "description": "TLS settings. Certificates and keys are reported as presence booleans only — never the path, which would leak filesystem layout.",
            "properties": {
              "ca_cert_present": {
                "type": "boolean"
              },
              "client_cert_present": {
                "description": "`client_cert` + `client_key` set (mutual TLS).",
                "type": "boolean"
              },
              "mode": {
                "$ref": "#/definitions/TlsMode"
              },
              "trust_native": {
                "type": "boolean"
              }
            },
            "required": [
              "ca_cert_present",
              "client_cert_present",
              "mode",
              "trust_native"
            ],
            "type": "object"
          },
          "TlsMode": {
            "oneOf": [
              {
                "description": "No TLS. Plaintext connection. Local-dev only.",
                "enum": [
                  "disable"
                ],
                "type": "string"
              },
              {
                "description": "TLS when the server offers it (chain validated like `require`); plaintext only when the server does not offer TLS at all. A failed certificate check is an error, never a fallback.",
                "enum": [
                  "prefer"
                ],
                "type": "string"
              },
              {
                "description": "TLS handshake required; certificate chain validated; hostname NOT verified. Matches libpq's `sslmode=require`. The default.",
                "enum": [
                  "require"
                ],
                "type": "string"
              },
              {
                "description": "Same checks as `require` (chain validated against the trust roots, hostname not checked), named after libpq's `sslmode=verify-ca`.",
                "enum": [
                  "verify-ca"
                ],
                "type": "string"
              },
              {
                "description": "TLS handshake required; certificate chain validated; certificate hostname must match the server host. Matches libpq's `sslmode=verify-full`.",
                "enum": [
                  "verify-full"
                ],
                "type": "string"
              }
            ]
          }
        },
        "properties": {
          "config_id": {
            "description": "The configuration entry this worker reads its connections from — `database`, or `<namespace>-<container>` under compose (`III_CONFIG_NAME`). Filter `configuration::on-updated` on it.",
            "type": "string"
          },
          "count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "databases": {
            "items": {
              "$ref": "#/definitions/DatabaseInfo"
            },
            "type": "array"
          }
        },
        "required": [
          "config_id",
          "count",
          "databases"
        ],
        "title": "ListDatabasesResp",
        "type": "object"
      }
    },
    {
      "description": "List the saved queries for a database, sorted by name.",
      "metadata": {},
      "name": "database::listSavedQueries",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          }
        },
        "title": "ListSavedReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "SavedQuery": {
            "properties": {
              "description": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "saved_at": {
                "type": "string"
              },
              "sql": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "name",
              "saved_at",
              "sql"
            ],
            "type": "object"
          }
        },
        "properties": {
          "count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "queries": {
            "items": {
              "$ref": "#/definitions/SavedQuery"
            },
            "type": "array"
          }
        },
        "required": [
          "count",
          "queries"
        ],
        "title": "ListSavedResp",
        "type": "object"
      }
    },
    {
      "description": "List every table and view in a database, with its kind and (on postgres) its schema. Reads the driver's own catalog, so no dialect-specific SQL is needed from the caller.",
      "metadata": {},
      "name": "database::listTables",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "description": "Logical database name. Optional — omitting it targets the sole configured database, or `primary` when several are configured.",
            "type": [
              "string",
              "null"
            ]
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "title": "ListTablesReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "TableKind": {
            "enum": [
              "table",
              "view"
            ],
            "type": "string"
          },
          "TableRef": {
            "description": "A relation. `schema` is populated only where the driver has a meaningful namespace above the table (postgres); it is never concatenated into `name`, because `analytics.events` and a table literally called `analytics.events` are different things and callers must be able to tell them apart.",
            "properties": {
              "kind": {
                "$ref": "#/definitions/TableKind"
              },
              "name": {
                "type": "string"
              },
              "row_count_estimate": {
                "description": "The planner's row estimate where the catalog keeps one cheaply (postgres `reltuples`, mysql `TABLE_ROWS`); absent for sqlite, views and never-analyzed tables. An estimate, never a count.",
                "format": "int64",
                "type": [
                  "integer",
                  "null"
                ]
              },
              "schema": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "required": [
              "kind",
              "name"
            ],
            "type": "object"
          }
        },
        "properties": {
          "count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "tables": {
            "items": {
              "$ref": "#/definitions/TableRef"
            },
            "type": "array"
          }
        },
        "required": [
          "count",
          "tables"
        ],
        "title": "ListTablesResp",
        "type": "object"
      }
    },
    {
      "description": "Resolve a @database(id=…) chat mention to its pill, preview card and agent summary; null for an unknown connection. Declares the database mention provider.",
      "metadata": {
        "internal": true,
        "mention": {
          "color": "teal",
          "description": "A database connection, by name",
          "details": {
            "function_id": "database::listTables",
            "id_field": "db"
          },
          "icon": "database",
          "label": "Databases",
          "name": "database",
          "search": "database::mention::search",
          "v": 1
        },
        "trace_hidden": true
      },
      "name": "database::mention::get",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Input of a provider's get function.",
        "properties": {
          "id": {
            "description": "The id from the token.",
            "type": "string"
          }
        },
        "required": [
          "id"
        ],
        "title": "MentionGetRequest",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "anyOf": [
          {
            "$ref": "#/definitions/MentionView"
          },
          {
            "type": "null"
          }
        ],
        "definitions": {
          "MentionField": {
            "description": "One labelled value of a preview card.",
            "properties": {
              "label": {
                "type": "string"
              },
              "tone": {
                "description": "`neutral`, `info`, `success`, `warning` or `danger`.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "value": {
                "type": "string"
              }
            },
            "required": [
              "label",
              "value"
            ],
            "type": "object"
          },
          "MentionOpen": {
            "anyOf": [
              {
                "properties": {
                  "context": true,
                  "page": {
                    "description": "Console page id (as registered with `host.pages`).",
                    "type": "string"
                  }
                },
                "required": [
                  "page"
                ],
                "type": "object"
              },
              {
                "properties": {
                  "session": {
                    "description": "Session id to select.",
                    "type": "string"
                  }
                },
                "required": [
                  "session"
                ],
                "type": "object"
              },
              {
                "properties": {
                  "url": {
                    "type": "string"
                  }
                },
                "required": [
                  "url"
                ],
                "type": "object"
              }
            ],
            "description": "What clicking a mention opens: an injected console page, a chat session, or an http(s) URL."
          },
          "MentionView": {
            "description": "What a chat surface renders for one mention, and what an agent reads. A get function answers `null` for an id it does not know.",
            "properties": {
              "color": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "data": {
                "description": "The domain object, for a worker's own preview renderer."
              },
              "description": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "fields": {
                "description": "Labelled values for the preview card (status, assignee, …).",
                "items": {
                  "$ref": "#/definitions/MentionField"
                },
                "type": "array"
              },
              "hint": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "icon": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "id": {
                "description": "The canonical id (may differ from the one asked for, e.g. a key resolved to a uuid).",
                "type": "string"
              },
              "label": {
                "type": "string"
              },
              "open": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/MentionOpen"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "What clicking the mention opens."
              },
              "summary": {
                "description": "One line for an agent: what the item is and its state. Defaults to the label, hint, description and fields.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "updated_at": {
                "description": "RFC 3339 time of the item's last change.",
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "required": [
              "id",
              "label"
            ],
            "type": "object"
          }
        },
        "title": "Nullable_MentionView"
      }
    },
    {
      "description": "Search the configured connections for the chat @database mention menu, by name, driver or host; best match first.",
      "metadata": {
        "internal": true,
        "trace_hidden": true
      },
      "name": "database::mention::search",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "MentionSearchContext": {
            "description": "The chat a search was asked from.",
            "properties": {
              "session_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "working_dir": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "type": "object"
          }
        },
        "description": "Input of a provider's search function.",
        "properties": {
          "context": {
            "anyOf": [
              {
                "$ref": "#/definitions/MentionSearchContext"
              },
              {
                "type": "null"
              }
            ],
            "description": "Where the search was asked from, for providers that rank by it."
          },
          "limit": {
            "description": "Maximum rows (default 8, at most 50).",
            "format": "uint",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          },
          "query": {
            "default": "",
            "description": "What the user typed after `@<name>:`. Empty asks for the most relevant recent items.",
            "type": "string"
          }
        },
        "title": "MentionSearchRequest",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "MentionItem": {
            "description": "One search row.",
            "properties": {
              "color": {
                "description": "Overrides the provider's color for this row.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "description": {
                "description": "One line after the label (\"in progress · high\").",
                "type": [
                  "string",
                  "null"
                ]
              },
              "hint": {
                "description": "A short human handle shown before the label (\"KAN-12\").",
                "type": [
                  "string",
                  "null"
                ]
              },
              "icon": {
                "description": "Overrides the provider's icon for this row.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "id": {
                "description": "The id written into the token; stable for the item's lifetime.",
                "type": "string"
              },
              "label": {
                "description": "The item's name (\"Fix login redirect\").",
                "type": "string"
              }
            },
            "required": [
              "id",
              "label"
            ],
            "type": "object"
          }
        },
        "description": "Output of a provider's search function, best match first.",
        "properties": {
          "items": {
            "items": {
              "$ref": "#/definitions/MentionItem"
            },
            "type": "array"
          }
        },
        "required": [
          "items"
        ],
        "title": "MentionSearchResponse",
        "type": "object"
      }
    },
    {
      "description": "Internal: reload connection pools from the authoritative configuration when it changes.",
      "metadata": {
        "internal": true
      },
      "name": "database::on-config-change",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Event delivered to the internal `database::on-config-change` handler. A struct (not `Value`) keeps the request schema concrete; the handler re-fetches the configuration id; unknown fields are ignored.",
        "properties": {
          "id": {
            "default": null,
            "description": "Configuration id that changed (advisory; the handler re-fetches the value). Schema-only: kept to publish a typed request schema; the handler ignores it.",
            "type": [
              "string",
              "null"
            ]
          }
        },
        "title": "OnConfigChangeEvent",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Ack returned by the internal `database::on-config-change` handler.",
        "properties": {
          "ok": {
            "type": "boolean"
          }
        },
        "required": [
          "ok"
        ],
        "title": "OnConfigChangeResponse",
        "type": "object"
      }
    },
    {
      "description": "One event per committed write statement. Observe it with args { db, table?, ops? } (table canonical: bare, unquoted, lowercase) and filter on input.returning / caller. On a `capture: statements` database (the default) it reports only writes made THROUGH this worker, with the writer's own RETURNING rows as `returning`; on a `capture: native` database it reports any client's committed writes, with the changed rows' primary keys as `returning` (capped; `truncated` flags the rest). Best-effort delivery, no replay. Private: only the database worker calls it.",
      "metadata": {},
      "name": "database::on-row-changed",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "Op": {
            "description": "The kind of row change a statement makes.",
            "oneOf": [
              {
                "enum": [
                  "insert",
                  "update",
                  "delete"
                ],
                "type": "string"
              },
              {
                "description": "A write that is none of the above: a CTE-wrapped statement, `MERGE`, a driver-specific form.",
                "enum": [
                  "other"
                ],
                "type": "string"
              }
            ]
          }
        },
        "description": "One committed write statement: the input of `database::on-row-changed`, and its output (the handler returns the event it is called with).",
        "properties": {
          "affected_rows": {
            "description": "Rows the statement changed. Exact even when `returning` is capped.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "at": {
            "description": "Epoch millis at emit time.",
            "format": "int64",
            "type": "integer"
          },
          "db": {
            "type": "string"
          },
          "op": {
            "$ref": "#/definitions/Op"
          },
          "returning": {
            "description": "Which rows changed, when that is known. On a `capture: statements` database this is the writer's own `RETURNING` projection — whatever columns the writer's SQL named, nothing more — so it is absent when the writer's SQL had no `RETURNING` clause. On a `capture: native` database it is the primary-key columns of each changed row (UPDATE reports the new key), capped at 100 rows per event; absent for a table without a primary key. Values are encoded like `database::query` returns them for the same column.",
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "schema": {
            "description": "The table's schema, lowercased, when the SQL or the driver named one; `null` otherwise.",
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "description": "Canonical table name: bare, unquoted, lowercased. `null` when the statement was recognisably a write but its table could not be read out of the SQL (a CTE-wrapped write, for example): such an event reaches only observers whose args name no table. Always set on a `capture: native` database.",
            "type": [
              "string",
              "null"
            ]
          },
          "truncated": {
            "description": "True when `returning` holds fewer keys than `affected_rows` because the per-event cap dropped the rest (native capture only). Omitted when false.",
            "type": "boolean"
          }
        },
        "required": [
          "affected_rows",
          "at",
          "db",
          "op"
        ],
        "title": "RowChangedEvent",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "Op": {
            "description": "The kind of row change a statement makes.",
            "oneOf": [
              {
                "enum": [
                  "insert",
                  "update",
                  "delete"
                ],
                "type": "string"
              },
              {
                "description": "A write that is none of the above: a CTE-wrapped statement, `MERGE`, a driver-specific form.",
                "enum": [
                  "other"
                ],
                "type": "string"
              }
            ]
          }
        },
        "description": "One committed write statement: the input of `database::on-row-changed`, and its output (the handler returns the event it is called with).",
        "properties": {
          "affected_rows": {
            "description": "Rows the statement changed. Exact even when `returning` is capped.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "at": {
            "description": "Epoch millis at emit time.",
            "format": "int64",
            "type": "integer"
          },
          "db": {
            "type": "string"
          },
          "op": {
            "$ref": "#/definitions/Op"
          },
          "returning": {
            "description": "Which rows changed, when that is known. On a `capture: statements` database this is the writer's own `RETURNING` projection — whatever columns the writer's SQL named, nothing more — so it is absent when the writer's SQL had no `RETURNING` clause. On a `capture: native` database it is the primary-key columns of each changed row (UPDATE reports the new key), capped at 100 rows per event; absent for a table without a primary key. Values are encoded like `database::query` returns them for the same column.",
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "schema": {
            "description": "The table's schema, lowercased, when the SQL or the driver named one; `null` otherwise.",
            "type": [
              "string",
              "null"
            ]
          },
          "table": {
            "description": "Canonical table name: bare, unquoted, lowercased. `null` when the statement was recognisably a write but its table could not be read out of the SQL (a CTE-wrapped write, for example): such an event reaches only observers whose args name no table. Always set on a `capture: native` database.",
            "type": [
              "string",
              "null"
            ]
          },
          "truncated": {
            "description": "True when `returning` holds fewer keys than `affected_rows` because the per-event cap dropped the rest (native capture only). Omitted when false.",
            "type": "boolean"
          }
        },
        "required": [
          "affected_rows",
          "at",
          "db",
          "op"
        ],
        "title": "RowChangedEvent",
        "type": "object"
      }
    },
    {
      "description": "Internal: re-read a rotated or revoked secret:// / env:// value and rebuild the connections that reference it.",
      "metadata": {
        "internal": true,
        "trace_hidden": true
      },
      "name": "database::on-secret-change",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "Caller": {
            "description": "Who made an invocation. `worker_id` / `worker_name` are stamped by the engine from the calling connection; `function_id`, `invocation_id` and `parent` are asserted by the calling SDK.",
            "properties": {
              "function_id": {
                "description": "The handler the call was made from; absent for a top-level call.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "invocation_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "parent": {
                "anyOf": [
                  {
                    "$ref": "#/definitions/ParentCaller"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "The caller of that handler, one level only."
              },
              "worker_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "worker_name": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "type": "object"
          },
          "InvocationStatus": {
            "enum": [
              "success",
              "error"
            ],
            "type": "string"
          },
          "ObservedError": {
            "description": "What a call failed with: [`Observed::error`], [`Call::error`](crate::Call::error).",
            "properties": {
              "code": {
                "type": "string"
              },
              "message": {
                "type": "string"
              }
            },
            "required": [
              "code",
              "message"
            ],
            "type": "object"
          },
          "OnSecretChangeEvent": {
            "description": "The advisory `secrets::on-changed` event (never carries a value).",
            "properties": {
              "action": {
                "default": null,
                "description": "`created` | `rotated` | `deleted` | `access_changed` (advisory).",
                "type": [
                  "string",
                  "null"
                ]
              },
              "name": {
                "default": null,
                "type": [
                  "string",
                  "null"
                ]
              },
              "ref": {
                "default": null,
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "type": "object"
          },
          "ParentCaller": {
            "description": "[`Caller::parent`]: a caller without a parent of its own.",
            "properties": {
              "function_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "invocation_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "worker_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "worker_name": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "type": "object"
          }
        },
        "description": "What an observer's target receives when iii delivers: the observed call, per the observer's `capture`.\n\n```rust,no_run # use iii_sdk::{Error, IIIClient, Observed, RegisterFunction}; # use serde_json::Value; # fn demo(iii: &IIIClient) { iii.register_function( \"alerts::payment-failed\", RegisterFunction::new(|event: Observed<Value>| { println!(\"{} failed: {:?}\", event.function_id, event.error); Ok::<_, Error>(()) }), ); # } ```",
        "properties": {
          "activation_id": {
            "type": "string"
          },
          "caller": {
            "anyOf": [
              {
                "$ref": "#/definitions/Caller"
              },
              {
                "type": "null"
              }
            ]
          },
          "duration_ms": {
            "format": "double",
            "type": "number"
          },
          "error": {
            "anyOf": [
              {
                "$ref": "#/definitions/ObservedError"
              },
              {
                "type": "null"
              }
            ]
          },
          "function_id": {
            "type": "string"
          },
          "input": true,
          "invocation_id": {
            "type": "string"
          },
          "metadata": true,
          "namespace": {
            "type": [
              "string",
              "null"
            ]
          },
          "observer_id": {
            "type": "string"
          },
          "output": {
            "anyOf": [
              {
                "$ref": "#/definitions/OnSecretChangeEvent"
              },
              {
                "type": "null"
              }
            ]
          },
          "started_at_ms": {
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "status": {
            "$ref": "#/definitions/InvocationStatus"
          }
        },
        "required": [
          "activation_id",
          "duration_ms",
          "function_id",
          "invocation_id",
          "observer_id",
          "started_at_ms",
          "status"
        ],
        "title": "Observed_for_AnyValue_and_OnSecretChangeEvent",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Ack returned by the internal `database::on-config-change` handler.",
        "properties": {
          "ok": {
            "type": "boolean"
          }
        },
        "required": [
          "ok"
        ],
        "title": "OnConfigChangeResponse",
        "type": "object"
      }
    },
    {
      "description": "Prepare a parameterized SQL statement once for repeated runs.",
      "metadata": {},
      "name": "database::prepareStatement",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "description": "Logical database name. Optional — omitting it targets the sole configured database, or `primary` when several are configured.",
            "type": [
              "string",
              "null"
            ]
          },
          "sql": {
            "type": "string"
          },
          "ttl_seconds": {
            "default": 3600,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "sql"
        ],
        "title": "PrepareReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "HandleResponse": {
            "properties": {
              "expires_at": {
                "format": "date-time",
                "type": "string"
              },
              "id": {
                "type": "string"
              }
            },
            "required": [
              "expires_at",
              "id"
            ],
            "type": "object"
          }
        },
        "properties": {
          "handle": {
            "$ref": "#/definitions/HandleResponse"
          }
        },
        "required": [
          "handle"
        ],
        "title": "PrepareResp",
        "type": "object"
      }
    },
    {
      "description": "Run a read-only SQL query and return the result rows.",
      "metadata": {},
      "name": "database::query",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "description": "Logical database name. Optional — omitting it targets the sole configured database, or `primary` when several are configured.",
            "type": [
              "string",
              "null"
            ]
          },
          "max_rows": {
            "default": null,
            "description": "Return at most this many rows; `truncated` says whether more existed. The worker stops reading after `max_rows + 1` rows (a postgres portal fetch, mysql's `sql_select_limit`, sqlite's lazy stepping) and never rewrites the SQL. Absent: every row.",
            "format": "uint64",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          },
          "params": {
            "default": [],
            "items": true,
            "type": "array"
          },
          "sql": {
            "type": "string"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "sql"
        ],
        "title": "QueryReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ColumnMeta": {
            "properties": {
              "name": {
                "type": "string"
              },
              "type": {
                "type": "string"
              }
            },
            "required": [
              "name",
              "type"
            ],
            "type": "object"
          }
        },
        "properties": {
          "columns": {
            "items": {
              "$ref": "#/definitions/ColumnMeta"
            },
            "type": "array"
          },
          "elapsed_ms": {
            "description": "Time the database spent running the statement and returning its rows (pool acquisition excluded), in milliseconds.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "row_count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "rows": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          },
          "truncated": {
            "description": "More rows existed past `max_rows` (always false without it).",
            "type": "boolean"
          }
        },
        "required": [
          "columns",
          "elapsed_ms",
          "row_count",
          "rows",
          "truncated"
        ],
        "title": "QueryResp",
        "type": "object"
      }
    },
    {
      "description": "Roll back an open SQL transaction, discarding its uncommitted writes.",
      "metadata": {},
      "name": "database::rollbackTransaction",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "transaction_id": {
            "type": "string"
          }
        },
        "required": [
          "transaction_id"
        ],
        "title": "RollbackTxReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "rolled_back": {
            "type": "boolean"
          }
        },
        "required": [
          "rolled_back"
        ],
        "title": "RollbackTxResp",
        "type": "object"
      }
    },
    {
      "description": "Run a prepared SQL statement by handle, passing fresh parameters.",
      "metadata": {},
      "name": "database::runStatement",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "handle_id": {
            "type": "string"
          },
          "params": {
            "default": [],
            "items": true,
            "type": "array"
          }
        },
        "required": [
          "handle_id"
        ],
        "title": "RunReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ColumnMeta": {
            "properties": {
              "name": {
                "type": "string"
              },
              "type": {
                "type": "string"
              }
            },
            "required": [
              "name",
              "type"
            ],
            "type": "object"
          }
        },
        "properties": {
          "columns": {
            "items": {
              "$ref": "#/definitions/ColumnMeta"
            },
            "type": "array"
          },
          "elapsed_ms": {
            "description": "Time the database spent running the statement and returning its rows (pool acquisition excluded), in milliseconds.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "row_count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "rows": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          },
          "truncated": {
            "description": "More rows existed past `max_rows` (always false without it).",
            "type": "boolean"
          }
        },
        "required": [
          "columns",
          "elapsed_ms",
          "row_count",
          "rows",
          "truncated"
        ],
        "title": "QueryResp",
        "type": "object"
      }
    },
    {
      "description": "Create, update (previous_name = name) or rename (previous_name = old) a connection in the database configuration; \"__redacted__\" keeps a stored value. Returns after the pools reloaded, with the connection's error if any.",
      "metadata": {},
      "name": "database::saveConnection",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "connection": {
            "description": "The entry (url or structured form). `\"__redacted__\"` keeps the stored value of that field."
          },
          "credentials": {
            "default": null,
            "description": "Sensitive values sent apart from `connection`, in the same shape (`password`, `url`, `tls.client_key`, `ssh.password`, `ssh.private_key`, `ssh.passphrase`) and merged over it. Traces record a call's payload with keys like `password` redacted but not `passphrase`, `client_key` or a url's password; a key named `credentials` is redacted whole, so literals sent here stay out of them. Prefer `secret://` references, which are safe anywhere."
          },
          "name": {
            "description": "The name to save under.",
            "type": "string"
          },
          "previous_name": {
            "default": null,
            "description": "The connection's current name when editing an existing one (equal to `name` to update in place, different to rename). Absent creates a new connection, refused when `name` is taken.",
            "type": [
              "string",
              "null"
            ]
          }
        },
        "required": [
          "connection",
          "name"
        ],
        "title": "SaveConnectionReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "Stage": {
            "description": "Where an attempt to reach a database failed.",
            "oneOf": [
              {
                "description": "The entry itself is unusable (unparseable url, unreadable file).",
                "enum": [
                  "config"
                ],
                "type": "string"
              },
              {
                "description": "A `secret://` / `env://` reference did not resolve.",
                "enum": [
                  "secrets"
                ],
                "type": "string"
              },
              {
                "description": "The SSH tunnel: server unreachable, host key, authentication.",
                "enum": [
                  "ssh"
                ],
                "type": "string"
              },
              {
                "description": "The database server (or the tunnel's far end) is unreachable.",
                "enum": [
                  "tcp"
                ],
                "type": "string"
              },
              {
                "description": "TLS negotiation or certificate validation.",
                "enum": [
                  "tls"
                ],
                "type": "string"
              },
              {
                "description": "The database refused the credentials.",
                "enum": [
                  "auth"
                ],
                "type": "string"
              },
              {
                "description": "Connected and authenticated, but the database is missing or unusable.",
                "enum": [
                  "database"
                ],
                "type": "string"
              }
            ]
          }
        },
        "properties": {
          "error": {
            "description": "Why the saved connection has no pool after the reload (it is saved regardless). Absent when it is usable.",
            "type": [
              "string",
              "null"
            ]
          },
          "error_stage": {
            "anyOf": [
              {
                "$ref": "#/definitions/Stage"
              },
              {
                "type": "null"
              }
            ]
          },
          "name": {
            "type": "string"
          },
          "saved": {
            "type": "boolean"
          }
        },
        "required": [
          "name",
          "saved"
        ],
        "title": "SaveConnectionResp",
        "type": "object"
      }
    },
    {
      "description": "Save a named snippet to the web console's saved-query list (state worker): console-only, not a file. To save a query as a .sql file, write it into the connection's queries folder (listDatabases `folder`) with the file tools — that is what the apps list. Saving under an existing name replaces it.",
      "metadata": {},
      "name": "database::saveQuery",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "description": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "name": {
            "type": "string"
          },
          "sql": {
            "type": "string"
          }
        },
        "required": [
          "name",
          "sql"
        ],
        "title": "SaveQueryReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "id": {
            "type": "string"
          },
          "replaced": {
            "type": "boolean"
          }
        },
        "required": [
          "id",
          "replaced"
        ],
        "title": "SaveQueryResp",
        "type": "object"
      }
    },
    {
      "description": "Replace the stored layout for a table. Widths are clamped to a usable range; columns the table no longer has are kept rather than rejected, so a rename degrades to a missing width instead of an error.",
      "metadata": {},
      "name": "database::saveTableView",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "hidden": {
            "default": [],
            "description": "Columns the reader has hidden. Order is not meaningful.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "order": {
            "default": [],
            "description": "Column display order. Unlisted columns keep their natural position after the listed ones.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "table": {
            "type": "string"
          },
          "widths": {
            "additionalProperties": {
              "format": "double",
              "type": "number"
            },
            "default": {},
            "description": "Per-column pixel width. Absent means \"size to content\".",
            "type": "object"
          }
        },
        "required": [
          "table"
        ],
        "title": "SaveTableViewReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "saved": {
            "type": "boolean"
          }
        },
        "required": [
          "saved"
        ],
        "title": "SaveTableViewResp",
        "type": "object"
      }
    },
    {
      "description": "Diagram the database schema: tables as positioned nodes, foreign keys as routed edges. Also reports hub degree per table, isolated tables and remaining edge crossings. Reads the whole catalog in a handful of queries rather than one per table.",
      "metadata": {},
      "name": "database::schemaDiagram",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "depth": {
            "default": 1,
            "description": "How many foreign-key hops out from `focus` to include. Ignored without one. 1 is the table and its direct relations.",
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "focus": {
            "default": null,
            "description": "Lay out only the neighbourhood of this table, `depth` hops out.",
            "type": [
              "string",
              "null"
            ]
          },
          "include_views": {
            "default": false,
            "type": "boolean"
          },
          "max_tables": {
            "default": 200,
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "timeout_ms": {
            "default": 30000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "title": "SchemaDiagramReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "DiagramColumn": {
            "properties": {
              "foreign_key": {
                "type": "boolean"
              },
              "name": {
                "type": "string"
              },
              "nullable": {
                "type": "boolean"
              },
              "primary_key": {
                "type": "boolean"
              },
              "type": {
                "type": "string"
              }
            },
            "required": [
              "foreign_key",
              "name",
              "nullable",
              "primary_key",
              "type"
            ],
            "type": "object"
          },
          "DiagramComponent": {
            "description": "One connected group of tables and its bounding box.",
            "properties": {
              "h": {
                "format": "double",
                "type": "number"
              },
              "hub": {
                "description": "The most-referenced table in the group, if it has more than one member.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "index": {
                "description": "Stable index, in layout order.",
                "format": "uint",
                "minimum": 0,
                "type": "integer"
              },
              "tables": {
                "description": "Member tables, by node id.",
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "w": {
                "format": "double",
                "type": "number"
              },
              "x": {
                "format": "double",
                "type": "number"
              },
              "y": {
                "format": "double",
                "type": "number"
              }
            },
            "required": [
              "h",
              "index",
              "tables",
              "w",
              "x",
              "y"
            ],
            "type": "object"
          },
          "DiagramEdge": {
            "properties": {
              "from": {
                "type": "string"
              },
              "from_column": {
                "type": "string"
              },
              "points": {
                "description": "Polyline, already routed. Anchored on the column row where the column is visible, on the node edge otherwise.",
                "items": {
                  "$ref": "#/definitions/Point"
                },
                "type": "array"
              },
              "self_loop": {
                "type": "boolean"
              },
              "to": {
                "type": "string"
              },
              "to_column": {
                "type": "string"
              }
            },
            "required": [
              "from",
              "from_column",
              "points",
              "self_loop",
              "to",
              "to_column"
            ],
            "type": "object"
          },
          "DiagramNode": {
            "properties": {
              "columns": {
                "items": {
                  "$ref": "#/definitions/DiagramColumn"
                },
                "type": "array"
              },
              "degree": {
                "description": "Number of foreign keys touching this table, in or out. Renderers use it to emphasise hubs.",
                "format": "uint32",
                "minimum": 0,
                "type": "integer"
              },
              "h": {
                "format": "double",
                "type": "number"
              },
              "hidden_columns": {
                "description": "Columns not drawn because of `MAX_ROWS`.",
                "format": "uint",
                "minimum": 0,
                "type": "integer"
              },
              "rank": {
                "format": "uint32",
                "minimum": 0,
                "type": "integer"
              },
              "schema": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "table": {
                "type": "string"
              },
              "w": {
                "format": "double",
                "type": "number"
              },
              "x": {
                "format": "double",
                "type": "number"
              },
              "y": {
                "format": "double",
                "type": "number"
              }
            },
            "required": [
              "columns",
              "degree",
              "h",
              "hidden_columns",
              "rank",
              "table",
              "w",
              "x",
              "y"
            ],
            "type": "object"
          },
          "Point": {
            "properties": {
              "x": {
                "format": "double",
                "type": "number"
              },
              "y": {
                "format": "double",
                "type": "number"
              }
            },
            "required": [
              "x",
              "y"
            ],
            "type": "object"
          }
        },
        "properties": {
          "components": {
            "description": "Connected groups, with the box that encloses each. A schema is usually several independent clusters rather than one graph, and saying so is most of what makes a large diagram readable — a reader can take in \"four unrelated groups\" at a glance instead of scanning for edges that are not there.",
            "items": {
              "$ref": "#/definitions/DiagramComponent"
            },
            "type": "array"
          },
          "crossings": {
            "description": "Edge crossings remaining after ordering. Lower is a tidier diagram.",
            "format": "uint32",
            "minimum": 0,
            "type": "integer"
          },
          "edges": {
            "items": {
              "$ref": "#/definitions/DiagramEdge"
            },
            "type": "array"
          },
          "focus": {
            "description": "Echoed when the caller asked for a neighbourhood rather than the whole schema.",
            "type": [
              "string",
              "null"
            ]
          },
          "frontier": {
            "default": [],
            "description": "Tables one hop beyond what was drawn. Non-empty means there is more to expand into, which is the difference between a diagram that looks complete and one that says where it stops.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "height": {
            "format": "double",
            "type": "number"
          },
          "isolated": {
            "description": "Tables with no foreign keys at all, placed on a trailing shelf.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "nodes": {
            "items": {
              "$ref": "#/definitions/DiagramNode"
            },
            "type": "array"
          },
          "truncated": {
            "type": "boolean"
          },
          "width": {
            "format": "double",
            "type": "number"
          }
        },
        "required": [
          "components",
          "crossings",
          "edges",
          "height",
          "isolated",
          "nodes",
          "truncated",
          "width"
        ],
        "title": "SchemaDiagramResp",
        "type": "object"
      }
    },
    {
      "description": "Terminate a backend session, or cancel just its running statement with `cancel_only`. Takes an id from database::health. Separate from health because it is a write.",
      "metadata": {},
      "name": "database::terminateQuery",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "cancel_only": {
            "default": false,
            "description": "Ask the backend to cancel the running statement but keep the session. The default terminates the session outright.",
            "type": "boolean"
          },
          "db": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "id": {
            "description": "Backend pid (postgres) or connection id (mysql), as reported by `database::health`.",
            "type": "string"
          },
          "timeout_ms": {
            "default": 15000,
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "id"
        ],
        "title": "TerminateReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "id": {
            "type": "string"
          },
          "terminated": {
            "type": "boolean"
          }
        },
        "required": [
          "id",
          "terminated"
        ],
        "title": "TerminateResp",
        "type": "object"
      }
    },
    {
      "description": "Test a candidate connection entry (url or structured form, TLS, SSH tunnel, secret:// values) with one throwaway connection. Configured pools are untouched; reports ok/driver/latency/server version, the failing stage and the SSH host key; failures are data, not errors.",
      "metadata": {},
      "name": "database::testConnection",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "TlsConfig": {
            "description": "TLS settings for a single database. Applies to postgres and mysql. Sqlite is local-file and ignores this block.\n\nDefault is `mode: require` — TLS handshake required, certificate chain validated against the system trust store, hostname verification skipped (matching libpq's `sslmode=require` semantics). Use `mode: verify-full` to additionally verify the certificate hostname matches the server host, and `mode: disable` to opt out of TLS entirely (local-dev only).",
            "properties": {
              "ca_cert": {
                "default": null,
                "description": "Optional CA certificate(s): a path to a PEM file, the PEM itself, `secret://NAME` or `env://NAME`. Additive by default — these certs **extend** the system trust store rather than replace it. Set `trust_native: false` for strict-isolation deployments that must only trust the operator-supplied bundle.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "client_cert": {
                "description": "Client certificate (chain) for mutual TLS: a path, the PEM itself, `secret://NAME` or `env://NAME`. Requires `client_key`.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "client_key": {
                "description": "Private key of `client_cert` (PEM: PKCS#8, PKCS#1 or SEC1): a path, the PEM itself, `secret://NAME` or `env://NAME`.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "mode": {
                "allOf": [
                  {
                    "$ref": "#/definitions/TlsMode"
                  }
                ],
                "default": "require",
                "description": "TLS mode: `disable` (plaintext), `prefer` (TLS when the server offers it), `require` (default), `verify-ca`, or `verify-full`."
              },
              "trust_native": {
                "default": true,
                "description": "When true (default), the system/native trust store is loaded in addition to any `ca_cert` bundle. Set to `false` to trust only the `ca_cert` certificates — useful when an operator wants to pin trust to a private CA and explicitly *not* accept the public web PKI.\n\nEffective for postgres. MySQL is forced-additive: `mysql_async`'s rustls path always loads the Mozilla `webpki_roots` bundle and extends it with `ca_cert` — there is no upstream knob to suppress the bundled roots, so `trust_native: false` only affects postgres.\n\nNote: with both `trust_native: false` *and* `ca_cert: None` on postgres, no trust roots are available; pool construction fails with `CONFIG_ERROR`.",
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "TlsMode": {
            "oneOf": [
              {
                "description": "No TLS. Plaintext connection. Local-dev only.",
                "enum": [
                  "disable"
                ],
                "type": "string"
              },
              {
                "description": "TLS when the server offers it (chain validated like `require`); plaintext only when the server does not offer TLS at all. A failed certificate check is an error, never a fallback.",
                "enum": [
                  "prefer"
                ],
                "type": "string"
              },
              {
                "description": "TLS handshake required; certificate chain validated; hostname NOT verified. Matches libpq's `sslmode=require`. The default.",
                "enum": [
                  "require"
                ],
                "type": "string"
              },
              {
                "description": "Same checks as `require` (chain validated against the trust roots, hostname not checked), named after libpq's `sslmode=verify-ca`.",
                "enum": [
                  "verify-ca"
                ],
                "type": "string"
              },
              {
                "description": "TLS handshake required; certificate chain validated; certificate hostname must match the server host. Matches libpq's `sslmode=verify-full`.",
                "enum": [
                  "verify-full"
                ],
                "type": "string"
              }
            ]
          }
        },
        "properties": {
          "connection": {
            "default": null,
            "description": "The candidate entry: `{url, tls?, ssh?}` or the structured form (`driver`, `host`, `port`, `user`, `password`, `database`, `tls`, `ssh`). `\"__redacted__\"` takes that value from the stored entry `name`."
          },
          "credentials": {
            "default": null,
            "description": "Sensitive values apart from `connection` (same shape: `password`, `url`, `tls.client_key`, `ssh.password`, `ssh.private_key`, `ssh.passphrase`), merged over it. A key named `credentials` is redacted whole in traces; `passphrase`, `client_key` and a url's password inside `connection` are not."
          },
          "name": {
            "default": null,
            "description": "The stored connection `\"__redacted__\"` values come from.",
            "type": [
              "string",
              "null"
            ]
          },
          "timeout_ms": {
            "default": null,
            "description": "Overall budget for the attempt. Default 5000, capped at 30000.",
            "format": "uint64",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          },
          "tls": {
            "anyOf": [
              {
                "$ref": "#/definitions/TlsConfig"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Legacy: TLS settings for `url`. Defaults like a configured database (mode `require`) when omitted."
          },
          "url": {
            "default": null,
            "description": "Legacy: a connection url to probe (`postgres://…`, `mysql://…`, `sqlite:…`) when `connection` is absent.",
            "type": [
              "string",
              "null"
            ]
          }
        },
        "title": "TestConnectionReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "HostKeyInfo": {
            "description": "The server key a session saw, in OpenSSH notation.",
            "properties": {
              "algorithm": {
                "description": "`ssh-ed25519`, `ecdsa-sha2-nistp256`, `ssh-rsa`, …",
                "type": "string"
              },
              "fingerprint": {
                "description": "`SHA256:…`, as `ssh-keygen -lf` prints it — the value `ssh.host_key` pins.",
                "type": "string"
              }
            },
            "required": [
              "algorithm",
              "fingerprint"
            ],
            "type": "object"
          },
          "Stage": {
            "description": "Where an attempt to reach a database failed.",
            "oneOf": [
              {
                "description": "The entry itself is unusable (unparseable url, unreadable file).",
                "enum": [
                  "config"
                ],
                "type": "string"
              },
              {
                "description": "A `secret://` / `env://` reference did not resolve.",
                "enum": [
                  "secrets"
                ],
                "type": "string"
              },
              {
                "description": "The SSH tunnel: server unreachable, host key, authentication.",
                "enum": [
                  "ssh"
                ],
                "type": "string"
              },
              {
                "description": "The database server (or the tunnel's far end) is unreachable.",
                "enum": [
                  "tcp"
                ],
                "type": "string"
              },
              {
                "description": "TLS negotiation or certificate validation.",
                "enum": [
                  "tls"
                ],
                "type": "string"
              },
              {
                "description": "The database refused the credentials.",
                "enum": [
                  "auth"
                ],
                "type": "string"
              },
              {
                "description": "Connected and authenticated, but the database is missing or unusable.",
                "enum": [
                  "database"
                ],
                "type": "string"
              }
            ]
          }
        },
        "properties": {
          "driver": {
            "description": "\"postgres\" | \"mysql\" | \"sqlite\" | \"unknown\".",
            "type": "string"
          },
          "latency_ms": {
            "description": "Wall time of the whole attempt.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "message": {
            "description": "Why the probe failed (credentials scrubbed). Absent on success.",
            "type": [
              "string",
              "null"
            ]
          },
          "ok": {
            "description": "Whether a connection was established and answered a query.",
            "type": "boolean"
          },
          "server_version": {
            "description": "Server version string, when the probe got far enough to ask.",
            "type": [
              "string",
              "null"
            ]
          },
          "ssh_host_key": {
            "anyOf": [
              {
                "$ref": "#/definitions/HostKeyInfo"
              },
              {
                "type": "null"
              }
            ],
            "description": "The SSH server's host key as the tunnel saw it (also on a mismatch), for a client to pin as `ssh.host_key`."
          },
          "stage": {
            "anyOf": [
              {
                "$ref": "#/definitions/Stage"
              },
              {
                "type": "null"
              }
            ],
            "description": "The step that failed: `config`, `secrets`, `ssh`, `tcp`, `tls`, `auth`, `database`. Absent on success."
          }
        },
        "required": [
          "driver",
          "latency_ms",
          "ok"
        ],
        "title": "TestConnectionResp",
        "type": "object"
      }
    },
    {
      "description": "Run a list of SQL statements in one atomic transaction. A statement's RETURNING rows come back in results[].rows and ride its row-changed event.",
      "metadata": {},
      "name": "database::transaction",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "TxStmtReq": {
            "properties": {
              "params": {
                "default": [],
                "items": true,
                "type": "array"
              },
              "sql": {
                "description": "One statement. A `RETURNING` clause in the SQL (SQLite, Postgres) puts the rows in this step's `results[].rows` and on the `database::on-row-changed` event fired for it after commit.",
                "type": "string"
              }
            },
            "required": [
              "sql"
            ],
            "type": "object"
          }
        },
        "properties": {
          "db": {
            "default": null,
            "description": "Logical database name. Optional — omitting it targets the sole configured database, or `primary` when several are configured.",
            "type": [
              "string",
              "null"
            ]
          },
          "isolation": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "statements": {
            "items": {
              "$ref": "#/definitions/TxStmtReq"
            },
            "type": "array"
          }
        },
        "required": [
          "statements"
        ],
        "title": "TxReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "TxStepResp": {
            "properties": {
              "affected_rows": {
                "format": "uint64",
                "minimum": 0,
                "type": "integer"
              },
              "rows": {
                "items": {
                  "items": true,
                  "type": "array"
                },
                "type": "array"
              }
            },
            "required": [
              "affected_rows",
              "rows"
            ],
            "type": "object"
          }
        },
        "properties": {
          "committed": {
            "type": "boolean"
          },
          "error": true,
          "failed_index": {
            "format": "uint",
            "minimum": 0,
            "type": [
              "integer",
              "null"
            ]
          },
          "results": {
            "items": {
              "$ref": "#/definitions/TxStepResp"
            },
            "type": [
              "array",
              "null"
            ]
          }
        },
        "required": [
          "committed"
        ],
        "title": "TxResp",
        "type": "object"
      }
    },
    {
      "description": "Execute a write inside an open transaction; put RETURNING in the SQL to get rows back. BEGIN/COMMIT/ROLLBACK are rejected; use commit/rollbackTransaction.",
      "metadata": {},
      "name": "database::transactionExecute",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "params": {
            "default": [],
            "items": true,
            "type": "array"
          },
          "returning": {
            "default": [],
            "description": "Optional, and NOT what produces rows: never adds a `RETURNING` clause — write it into `sql`. SQLite refuses a non-empty list when the statement returns no rows (`RETURNING_MISMATCH`); Postgres and MySQL ignore it with a warning.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "sql": {
            "description": "The write statement. Put a `RETURNING` clause in the SQL itself to get rows back and onto the `database::on-row-changed` event that `commitTransaction` fires for this write (SQLite, Postgres; MySQL has no RETURNING).",
            "type": "string"
          },
          "transaction_id": {
            "type": "string"
          }
        },
        "required": [
          "sql",
          "transaction_id"
        ],
        "title": "TxExecuteReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "affected_rows": {
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "last_insert_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "returned_rows": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "affected_rows",
          "returned_rows"
        ],
        "title": "TxExecuteResp",
        "type": "object"
      }
    },
    {
      "description": "Query rows inside an open transaction.",
      "metadata": {},
      "name": "database::transactionQuery",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "params": {
            "default": [],
            "items": true,
            "type": "array"
          },
          "sql": {
            "type": "string"
          },
          "transaction_id": {
            "type": "string"
          }
        },
        "required": [
          "sql",
          "transaction_id"
        ],
        "title": "TxQueryReq",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "ColumnMeta": {
            "properties": {
              "name": {
                "type": "string"
              },
              "type": {
                "type": "string"
              }
            },
            "required": [
              "name",
              "type"
            ],
            "type": "object"
          }
        },
        "properties": {
          "columns": {
            "items": {
              "$ref": "#/definitions/ColumnMeta"
            },
            "type": "array"
          },
          "elapsed_ms": {
            "description": "Time the database spent running the statement and returning its rows (pool acquisition excluded), in milliseconds.",
            "format": "uint64",
            "minimum": 0,
            "type": "integer"
          },
          "row_count": {
            "format": "uint",
            "minimum": 0,
            "type": "integer"
          },
          "rows": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          },
          "truncated": {
            "description": "More rows existed past `max_rows` (always false without it).",
            "type": "boolean"
          }
        },
        "required": [
          "columns",
          "elapsed_ms",
          "row_count",
          "rows",
          "truncated"
        ],
        "title": "QueryResp",
        "type": "object"
      }
    },
    {
      "description": "Serve the database worker's injected console UI assets (the target of its ade::ui::asset observers; the console calls it through each asset's observer with {path}).",
      "metadata": {
        "internal": true
      },
      "name": "database::ui-content",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Input of the content function: the console asks for one asset by path.",
        "properties": {
          "path": {
            "description": "The asset path from the observer's args (e.g. `state/page.js`).",
            "type": "string"
          }
        },
        "required": [
          "path"
        ],
        "title": "UiContentInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Output of the content function.",
        "properties": {
          "content": {
            "description": "The asset source, verbatim.",
            "type": "string"
          },
          "content_type": {
            "description": "MIME type the console should serve the asset with.",
            "type": "string"
          }
        },
        "required": [
          "content",
          "content_type"
        ],
        "title": "UiContentResult",
        "type": "object"
      }
    }
  ]
}
```
