# API conventions

How the Glassbeetle API is shaped. Every endpoint follows these rules, so a
contributor implementing one resource does not have to reverse-engineer how
another one behaves.

If you disagree with something here, open an issue — changing a convention once
is cheap, reconciling twenty endpoints that each chose differently is not.

## Routing and versioning

Every route lives under `/api/v1`.

The `api` prefix is a global prefix and the `v1` segment comes from Nest's URI
versioning (`apps/api/src/bootstrap.ts`). Versioning is configured rather than
baked into a prefix string so an individual controller can pin or opt out of a
version later without the rest of the API moving.

A **plural** path segment is a collection; a **singular** one is a singleton.
`/agents` is a list with ids below it, `/user` is one resource with no id and no
list. The distinction is not decoration: the user profile is a singleton because
the application is single-user, and a path that could name a second person is
the first step towards an owner column on every table. See
[`user-profile.md`](user-profile.md).

Nested resources are expressed in the controller path:

```ts
@Controller('agents/:agentId/memories')   // → /api/v1/agents/:agentId/memories
@Controller('providers/:providerId/credential')
```

An endpoint scoped to a parent **must** filter by that parent in its query, not
just read the child by its own id. Ids are globally unique, so
`WHERE id = ?` alone would happily return another agent's private memory
through a URL naming the wrong agent. Always `WHERE id = ? AND agent_id = ?`.

## Resource representation

The database is SQLite and the API is JSON; these do not use the same types.
Helpers live in `apps/api/src/common/persistence/`.

| Concern | Storage | API | Helper |
| --- | --- | --- | --- |
| Identifiers | `TEXT PRIMARY KEY` | string | `newId()` |
| Timestamps | `TEXT` | ISO-8601 UTC string | `nowIso()`, `toIso()`, `fromIso()` |
| Booleans | `INTEGER` 0/1 | `true` / `false` | `toDbBoolean()`, `fromDbBoolean()` |
| Arrays, objects | JSON-encoded `TEXT` | real arrays/objects | `serializeJsonColumn()`, `parseJsonColumn()` |
| Column names | `snake_case` | `camelCase` | — |

**Identifiers** are UUIDv7. The leading 48 bits are a Unix millisecond
timestamp, so ids sort lexicographically in creation order — which makes
`ORDER BY id` a usable, stable pagination tiebreaker without needing an index on
`created_at`. A random UUIDv4 could not do that.

Identifiers are validated at the edge. A path parameter that is not a UUIDv7
(a v4 UUID included) answers `400 INVALID_IDENTIFIER` before any lookup, and the
message names the parameter without echoing the value. An id field in a body or
query string that is not a UUIDv7 is a `400` from `ValidationPipe`, listed in
`details`. A well-formed id that names nothing is still a `404` (or `422` for a
body reference). Use `ParseUuidV7Pipe` from `apps/api/src/common/identifiers/`
on every `@Param` that takes an id.

**Timestamps** are ISO-8601 UTC with millisecond precision
(`2026-09-21T09:30:52.123Z`), generated in TypeScript rather than in SQL. This
matches what `data/backups/seed.sql` already writes, and it compares correctly
under SQLite's lexicographic `TEXT` comparison, so `ORDER BY created_at` and
`WHERE created_at >= ?` work without conversion.

`created_at` and `updated_at` are always server-managed. A client that sends
`id`, `createdAt` or `updatedAt` gets a `400`.

Team memberships are an exception to the timestamp shape. `team_members` has a
composite primary key, `(team_id, agent_id)`, so a membership has no standalone
`id` and its route uses both ids: `/teams/:teamId/members/:agentId`. The table
has `created_at` but no `updated_at`; membership responses therefore include
`createdAt` without `updatedAt`. `PATCH` returns the updated membership in the
same shape, so changing a role does not add a change timestamp. This reflects
the schema, not an omission in the endpoint.

**Nullable columns** are emitted as `null`, not omitted. A client can then tell
"not set" from "field does not exist in this version of the API".

### Never serialised

Some columns exist for the server's benefit only and must never appear in a
response:

- `agents.picture_path`, `projects.image_path`, `artifacts.file_path`,
  `backups.file_path`, `user_profile.picture_path` — local filesystem references. Expose an API download reference or a boolean
  instead; a path leaks the layout of the user's machine.
- `user_profile.singleton` — the column exists so SQLite can refuse a second
  row. It constrains the table and says nothing about the user.
- `provider_credentials.encrypted_value`, `.nonce` — there is no endpoint that
  returns a credential's plaintext, and none should be added. `masked_preview`
  is the only credential value that may be returned.

## Schema changes

`data/` holds the DDL and `runMigrations()`
(`apps/api/src/database/schema-migrations.ts`) applies it, in two phases:

1. **The bootstrap.** `MIGRATION_FILE_SEQUENCE` builds the whole schema and is
   recorded once as `001_initial_bootstrap`. It only ever runs on a database
   with no schema at all.
2. **The incremental migrations.** `MIGRATIONS_AFTER_BOOTSTRAP` is a list of
   `{ name, sql }`, each applied in its own transaction and recorded under its
   own name.

A new table therefore needs **both**: a file in the sequence, for fresh
installations, and an entry in `MIGRATIONS_AFTER_BOOTSTRAP`, for every database
that already recorded the bootstrap. Adding only the file is the easy mistake —
it works on a developer's throwaway database and reaches no existing install.

Write a migration's DDL out in full rather than sharing a string with the
bootstrap, and guard it with `IF NOT EXISTS`. A released migration is frozen
history; the bootstrap DDL is free to evolve, and if the two shared a string an
edit to one would retroactively change what the other claims to have done.

Never edit a migration that has shipped. Add another one.

## File storage and stored references

Files (agent profile pictures, project images, artifact blobs, and backup archives) are managed through `FileStorageService` (`apps/api/src/file-storage/`).

### Database Reference Format

Database columns (`agents.picture_path`, `projects.image_path`, `artifacts.file_path`, `backups.file_path`) **must store POSIX-formatted relative references within the storage root** (e.g. `pictures/018f3a9e-0000-7000-8000-000000000001.jpg`), **never** absolute filesystem paths.

**Why?**
1. **Portability**: If the user moves their data directory or restores a backup on another machine, references remain intact.
2. **Security & Privacy**: Storing or exposing absolute paths leaks the local machine layout (e.g. `/Users/alice/...` or `C:\Users\bob\...`).

### Containment and Security Model

- **Internally Generated Filenames**: On-disk paths are never derived from client-supplied filenames. `FileStorageService.write()` generates a UUIDv7 identifier and appends an extension derived from the file's verified magic bytes.
- **Magic Byte Sniffing**: Content types are detected from the file's actual byte signatures, preventing disguised payloads.
- **Strict Containment Check**: All read, write, stat, stream, and delete operations assert that the resolved path resides strictly inside the configured storage root, rejecting traversal sequences (`../`), absolute paths, sibling prefix collisions, and symlink escapes.
- **Atomic Writes**: Writes are staged in a temporary file in the bucket directory and atomically renamed.
- **Silent Missing Deletion**: Deleting a non-existent file succeeds silently without throwing.

### Orphaned Files & Lifecycle

SQLite foreign keys with `ON DELETE CASCADE` or `ON DELETE SET NULL` clean up database rows but do not delete files on disk. Deleting an entity (e.g. an agent) leaves its stored file behind unless explicitly cleaned up.

Consumers and deletion endpoints are expected to invoke `fileStorageService.delete(row.picture_path)` when deleting or replacing resources.

## Credential encryption at rest

Provider credentials (API keys for OpenAI, Anthropic, Google, etc.) represent sensitive user secrets that cost money if compromised. They are protected using authenticated encryption at rest via `EncryptionService` (`apps/api/src/crypto/`).

### Cryptographic Scheme & Format Layout

- **Cipher**: AES-256-GCM (`node:crypto`) with 256-bit keys.
- **Nonce (IV)**: 12-byte (96-bit) cryptographically random bytes generated fresh on every encryption operation (`randomBytes(12)`). Nonce reuse is strictly prevented.
- **Additional Authenticated Data (AAD)**: The `provider_id` is bound as AAD during encryption and decryption, preventing an attacker from transplanting ciphertext from one provider row to another.
- **Fail Loudly**: Decryption errors (tampering, corrupt tag, wrong key, truncated payload) throw `DecryptionError` immediately and never return garbage or empty strings.
- **No Secret Leakage**: Plaintext secrets, keys, and ciphertexts are never logged and never included in error messages.

#### On-Disk Layout (`provider_credentials` table)

| Column | Type | Content Layout |
| --- | --- | --- |
| `encrypted_value` | `BLOB NOT NULL` | `[0]`: Format Version (`0x01`)<br>`[1 .. len-16]`: AES-256-GCM Ciphertext<br>`[len-16 .. len]`: GCM Auth Tag (16 bytes) |
| `nonce` | `BLOB NOT NULL` | 12 raw bytes (96-bit GCM Initialization Vector) |
| `masked_preview` | `TEXT` | Safe preview produced by `maskKey()` (e.g. `sk-ant-…4f2a`) |

The leading version byte (`0x01`) provides future-proof extensibility for key rotation, algorithm migration, or re-encryption.

### Master Key Management & Threat Model

The 256-bit master key is stored in a dedicated file (`master.key`) inside the application data directory (`<dataDir>/master.key`), configurable via `GLASSBEETLE_MASTER_KEY_FILE` or direct override `GLASSBEETLE_MASTER_KEY`. On first startup, the key is automatically generated using `randomBytes(32)` and written with restrictive permissions (`0600` on POSIX: readable and writable only by the file owner).

#### Threats it protects against:
1. **Database copy exfiltration**: If `glassbeetle.db` is leaked, accidentally committed to version control, copied to an unencrypted backup, synced via cloud storage, or exfiltrated via SQL injection, provider credentials cannot be decrypted without the separate `master.key` file.
2. **Accidental exposure**: Local SQLite inspection tools, query logging, and diagnostic database dumps expose only high-entropy binary blobs, not API keys.
3. **Tampering and Row Swapping**: AES-GCM tag verification detects any modification to ciphertext, nonce, or tag. AAD binding prevents moving credentials between providers.

#### Threats it does NOT protect against:
1. **Local user compromise**: An attacker or process executing with the user's OS permissions can read both the SQLite database and `master.key`.
2. **Root / Administrator access**: A privileged administrator account bypasses file mode restrictions.
3. **Process memory inspection**: Active plaintext keys temporarily reside in process memory during provider API invocations.

#### Backup Considerations:
- A backup archive containing only the SQLite database cannot restore usable credentials on another machine without the master key.
- A backup archive containing both the database and `master.key` negates the separation of data and key at rest.
- Recommended approach for backup issues: Backups should either require a user-supplied export passphrase to encrypt credentials within export archives, or intentionally exclude provider credentials, requiring users to re-enter them upon restoring.

### Request limit

`PUT /providers/:providerId/credential` accepts `apiKey` or `value` of up to
4096 characters. Real provider keys are tens to a few hundred characters, so
the limit is generous for every supported kind while it keeps a pasted `.env`
file, certificate or JSON blob from being accepted and encrypted as if it were
a key. A longer value is rejected with `400 Bad Request`.

## Collection endpoints (Pagination, Filtering, Sorting)

All eleven list endpoints in the API (`/agents`, `/memories`, `/teams`, `/chats`, `/projects`, `/artifacts`, `/providers`, `/models`, `/system-prompts`, `/chats/:chatId/messages`, `/application/backups`) share a unified envelope, pagination model, and SQL fragment helper.

### Envelope Shape

List endpoints return a JSON wrapper object instead of a bare array:

```json
{
  "items": [],
  "total": 42,
  "limit": 50,
  "offset": 0
}
```

Construct this using `createPaginatedResponse(items, total, limit, offset)` from `src/common/pagination/paginated-response.dto.ts`.

### Pagination Parameters & Bounds

- **Style**: Offset/Limit (`?limit=50&offset=0`).
- **Default limit**: `50` items.
- **Maximum limit**: `100` items (requests with `limit > 100` or `limit < 1` are rejected with `400 Bad Request`).
- **Default offset**: `0` (requests with `offset < 0` are rejected with `400 Bad Request`).

### Sorting & Safety

- **Query shape**: `?sort=createdAt&order=desc` (where `order` is `'asc'` or `'desc'`).
- **Whitelisting**: Every list endpoint defines a map of allowed sort keys to database columns. User-supplied sort strings are **never** interpolated directly into SQL. An unknown sort field returns `400 Bad Request`.
- **Tie-breaking**: `buildPaginationSqlFragment` automatically appends `, id <ORDER>` to guarantee deterministic sorting even when multiple rows share identical timestamps.

### Filtering & Booleans

- Query filters use simple query parameters: `?projectId=...`, `?enabled=true`.
- Booleans in query strings (`?enabled=true` or `?enabled=1`) must be decorated with `@TransformBoolean()` from `src/common/pagination/boolean-query.decorator.ts`.
- **Total Counts**: Executing a 2nd `SELECT COUNT(*)` query in SQLite is cheap on local desktop installations; do not hesitate to issue a count query for `total`.

### Worked Example for Contributors

```ts
// 1. DTO: src/modules/agents/dto/list-agents-query.dto.ts
import { IsOptional, IsString } from 'class-validator';
import { PaginationQueryDto } from '../../../common/pagination/pagination-query.dto.js';

export class ListAgentsQueryDto extends PaginationQueryDto {
  @IsOptional()
  @IsString()
  modelId?: string;
}

// 2. Service: src/modules/agents/agents.service.ts
import { buildPaginationSqlFragment } from '../../common/pagination/sql-query-builder.js';
import { createPaginatedResponse, PaginatedResponse } from '../../common/pagination/paginated-response.dto.js';

const ALLOWED_SORT_COLUMNS = {
  createdAt: 'created_at',
  name: 'name',
  id: 'id',
};

async findAll(query: ListAgentsQueryDto): Promise<PaginatedResponse<AgentDto>> {
  const sqlFragment = buildPaginationSqlFragment({
    query,
    allowedSortColumns: ALLOWED_SORT_COLUMNS,
    defaultSortKey: 'createdAt',
    defaultOrder: 'desc',
  });

  const conditions: string[] = [];
  const queryParams: any[] = [];

  if (query.modelId) {
    conditions.push('model_id = ?');
    queryParams.push(query.modelId);
  }

  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

  const totalRow = this.db.get<{ total: number }>(
    `SELECT COUNT(*) as total FROM agents ${whereClause}`,
    queryParams,
  );
  const total = totalRow?.total ?? 0;

  const sql = `SELECT * FROM agents ${whereClause} ${sqlFragment.clauseSql}`;
  const rows = this.db.all<AgentRow>(sql, [...queryParams, ...sqlFragment.params]);

  return createPaginatedResponse(rows.map(mapAgentRow), total, query.limit, query.offset);
}
```

## Request validation

A global `ValidationPipe` runs on every route with:

- `whitelist: true` — properties with no validation decorator are stripped
- `forbidNonWhitelisted: true` — unknown properties are **rejected**, so a client
  typo becomes a `400` rather than a silently ignored field
- `transform: true` with `enableImplicitConversion: false` — explicit `@Type()`
  conversions only

DTOs live in `apps/api/src/modules/<resource>/dto/` and are named
`create-<resource>.dto.ts`, `update-<resource>.dto.ts`. Update DTOs should
extend the create DTO via `PartialType` imported from **`@nestjs/swagger`** —
importing it from `@nestjs/mapped-types` instead produces a DTO that validates
correctly but is missing from the generated OpenAPI schema.

Validate anything the schema constrains with a `CHECK` in the DTO too — for
example `providers.kind`, `messages.role`, `backup_policy.frequency`. The
database constraint is the last line of defence, not the first: letting it fire
turns a client mistake into an opaque `500`.

## Error responses

Use `404` when a resource named in the URL path does not exist. Use `422` when
a request body references a resource that does not exist; the resource named
by the path can still exist. For example, posting a message to an existing chat
with an unknown `agentId` returns `422`, while posting to an unknown `chatId`
returns `404`.

Every error, from every endpoint, returns this envelope:

```json
{
  "statusCode": 404,
  "error": "Not Found",
  "code": "NOT_FOUND",
  "message": "Agent not found",
  "path": "/api/v1/agents/abc",
  "timestamp": "2026-09-21T09:30:52.123Z"
}
```

- `code` is stable and machine-readable; clients branch on it. It is derived
  from the HTTP status by default, and an exception may supply a more specific
  one (`throw new ConflictException({ code: 'AGENT_HAS_NO_MODEL', message: '…' })`).
- `message` is human-facing and may be reworded at any time.
- `details` is present only for validation failures and carries one string per
  failing constraint.

Raise errors with Nest's exception classes (`NotFoundException`,
`ConflictException`, …). The global filter in
`apps/api/src/common/filters/http-exception/http-exception.filter.ts` formats
them.

**Anything the application did not raise deliberately becomes a generic
`500`.** Unexpected errors carry SQLite messages, filesystem paths and upstream
provider responses; the real error is logged server-side and the client is told
only that something failed. Do not defeat this by catching an internal error and
rethrowing its message to the client.

A JSON body larger than `JSON_BODY_LIMIT_BYTES` (512 KiB, set in
`apps/api/src/bootstrap.ts`) is rejected before it reaches a route with `413`
and `code: "PAYLOAD_TOO_LARGE"`. The limit is sized so every character limit in
the DTOs is reachable in any script; a DTO limit is still enforced by its own
`400`.

Unmatched routes also return this envelope — see `registerNotFoundFallback`.
It must be registered *after* `app.init()`, or it shadows the routes it exists
to fall back from.

## Streaming and realtime transport

Completions and live progress updates use **Server-Sent Events (SSE)** over standard HTTP endpoints (e.g. `POST /api/v1/chats/:chatId/completions`). WebSockets are not used.

Errors that occur before response headers are sent return the standard JSON error envelope above. Errors occurring after the stream starts are transmitted in-band via structured `event: error` SSE payloads.

For full architectural details, protocol wire frames, SQLite persistence timing, disconnect behavior, and multi-agent team turn coordination, see [`docs/realtime-transport.md`](realtime-transport.md).

## Configuration

Settings are read through `AppConfigService`
(`apps/api/src/config/`), never from `process.env` in a service. The accessor
returns non-optional types, because defaults and validation have already run.

Invalid configuration fails at startup with a message naming the offending
setting. See `apps/api/.env.example` for every setting and its default; a `.env`
file is optional, as an installed desktop application must start without one.

The data directory resolves per-platform and never relative to the executable —
a packaged Tauri build runs from a read-only bundle.

## Security boundaries

The API binds to `127.0.0.1` and **has no authentication**. It is a single-user
local application, and the following two properties are what keep it safe:

1. **Loopback only.** It is not reachable from other machines.
2. **A CORS allowlist**, not origin reflection. Only the three origins the
   desktop app actually uses are allowed. Reflecting arbitrary origins would let
   any website the user happens to visit read their chats, agents and memories
   from `http://localhost:3000`. Credentials are deliberately not enabled.

Keep both when adding endpoints, and treat any change to them as
security-relevant.

## OpenAPI

The document is served at `/api/docs` (UI) and `/api/docs-json` (raw), and can
be written to a file with `npm run openapi:export`.

Annotate every endpoint:

```ts
@ApiTags('agents')
@Controller('agents')
export class AgentsController {
  @Get(':agentId')
  @ApiOperation({ summary: 'Retrieve an agent' })
  @ApiParam({ name: 'agentId', description: 'Agent identifier' })
  @ApiOkResponse({ type: AgentResponseDto })
  @ApiNotFoundResponse({ description: 'No agent with that id' })
  findOne(/* … */) {}
}
```

- `@ApiTags` on the controller, using one of the tags declared in
  `apps/api/src/openapi/openapi.ts`.
- `@ApiOperation` with a summary that says what the endpoint *does*, not what it
  is called.
- A response decorator for every status the endpoint can return, errors
  included.
- `@ApiProperty` / `@ApiPropertyOptional` on DTO fields with a description and a
  realistic example. `0.7` is a useful example for `temperature`; `"string"` is
  not.
- OpenAPI distinguishes *optional* from *nullable*. A field that is always
  present but may be `null` is not the same as one that may be absent — most
  agent fields are the former.

The `@nestjs/swagger` CLI plugin is deliberately **not** enabled. It only runs
under `nest build`, so enabling it would make the generated schema differ
between a built app and the Vitest/SWC test run. Annotate explicitly instead.

## Testing

- Unit tests sit next to the code as `*.spec.ts` and run with `npm test`.
- HTTP-level tests sit in `apps/api/test/` as `*.e2e-spec.ts` and run with
  `npm run test:e2e`.

E2E tests must apply `configureApp()` so they exercise the same pipeline
production uses. A test against a bare application — no validation, no error
envelope — proves very little about the real thing.
