Appearance
Level 3: Components
The modules inside the backend containers. api, api-realtime and worker run the same NestJS codebase (apps/api), so they share one component model; which components are active depends on the process (HTTP routes in api, the WebSocket gateway in api-realtime, queue processors in worker). The doc-worker follows at the end.
Each feature is one folder under apps/api/src/modules/<feature>/ with one file per role (*.controller, *.service, *.repository, *.errors, *.processor). Only repositories query the database; tenant reads and writes run inside withOrg(orgId, tx => ...), which sets app.org_id for row-level security.
api: overview
Modules grouped by layer: requests pass the access layer, features build on the shared infrastructure in common / db. The diagrams below zoom into the main flows.
api: running an agent
What happens on POST /v1/runs (and in the playground, workflow agent nodes and agents used as tools).
Sync runs return the result; streaming runs send SSE events as the model produces them; async runs return 202 with a run id and finish in the worker, then emit a webhook. Every model call records usage in USD micros against the catalog prices; failed and cancelled runs are billed for what they used.
api: knowledge ingestion and retrieval
worker: queues
Producers in any process enqueue; consumers only exist in the worker (registerProcessor returns nothing outside QUEUE_ROLE=worker).
api modules
| Module | Folder | Description |
|---|---|---|
| auth | src/auth | better-auth (email + password, verification, Google/GitHub OAuth, organization and admin plugins), mounted outside Nest in app.ts. Guards: SessionGuard, OrgGuard + @MinRole, SuperAdminGuard, ApiKeyGuard for /v1. Writes org and admin actions to the audit log. |
| policies | src/policies | Resource-level access rules (API keys, data sources, files, realtime, workflows), registered once and checked by services. |
| limits | modules/limits | Sliding-window /v1 rate limits on Redis (RateLimitGuard), the monthly spend cap and storage quota (QuotaService), per-org settings. Global. |
| health | modules/health | GET /health: database required, Redis reported. Used by container health checks. |
| me | modules/me | GET /console/me: the signed-in user and their organizations. |
| project | modules/project | Projects inside an organization; every project-scoped route checks its project through ProjectRepository. Global. |
| api-key | modules/api-key | Project API keys: create (shown once, stored as SHA-256 hashes), scopes, optional agent restriction, revoke. ApiKeyGuard looks keys up here. Global. |
| secret | modules/secret | Encrypted project secrets, resolved server-side for HTTP tools, data sources and workflow HTTP nodes ({{secret:NAME}}). |
| agent | modules/agent | Agents and immutable versions, publish, config validation against the shared contracts (models, tools, schemas, guardrails). |
| tool | modules/tool | Customer-defined HTTP tools; plugs the http provider into the tool registry and calls endpoints through the SSRF-safe client. |
| tool-runtime | modules/tool-runtime | ToolRegistry: turns an agent's tool refs into LLM tools via providers registered by other modules; built-in tools (web_fetch, language detection). |
| llm | modules/llm | LlmService, the only way to call model providers: text, structured output, tools, vision, embeddings, token accounting. FAKE_LLM=true swaps in deterministic fake models. |
| run | modules/run | RunExecutor and runners (single-shot for extraction and transform, conversational with history and memory), guardrails, idempotency, input files, cancellation, conversations, RunProcessor for async runs, console and /v1 endpoints. Registers agents as tools. |
| workflow | modules/workflow | Durable workflow engine: graph validation, expressions (JSONata), node executors, run and node-run state in Postgres, steps on the workflows queue, waits, approvals, external events, retry from node, recovery job. |
| realtime | modules/realtime | Voice: session tokens, the WS /v1/realtime gateway, OpenAI Realtime and Gemini Live adapters (plus a fake one), audio handling, tools during a session, metering. |
| data-source | modules/data-source | Knowledge: file, text, website (crawler) and HTTP API sources, ingestion pipeline and its processor, chunks with vector indexes, hybrid retrieval (vector + full-text, RRF), live sources as tools. |
| file | modules/file | Uploaded files for run inputs and data sources: streaming multipart upload, type sniffing, quotas, signed downloads, hourly expiry (FileProcessor). |
| storage | modules/storage | StorageService: the S3 client for SeaweedFS (put, get, delete, presigned URLs). |
| doc-worker | modules/doc-worker | DocWorkerClient: authenticated HTTP client for the internal doc-worker (parse, chunk, render pages, extract URL). |
| webhook | modules/webhook | Webhook endpoints per project, event emission (emit), HMAC-signed deliveries with retries by WebhookProcessor; signing secrets stored encrypted. |
| catalog | modules/catalog | Global model catalog: providers (enabled when a key is stored), models, prices, templates. Seeded on startup; every model lookup resolves here. |
| usage | modules/usage | Usage events and daily rollups in USD micros, pricing, 80 % / 100 % spend alerts, console usage dashboards and CSV export. Global. |
| audit | modules/audit | Reads the audit log (entries written with audit() from common). Global. |
| ops | modules/ops | Super-admin /ops API: organizations, limits and suspension, model catalog and prices, platform usage, audit log, job queues. |
| common | src/common | Shared infrastructure: error catalogs and AppException, pino logger, request context, BullMQ helpers, Redis, encryption, SSRF-safe HTTP client, mail, CSRF check, JSON Schema (per-tenant Ajv), SSE, pagination. |
| db | src/db | Drizzle client (withOrg for RLS, getAdminDb for the few cross-tenant paths), schema (app.ts, better-auth's auth.ts), migration runner. |
| config | src/config | env(): the only access to environment variables, validated with Zod, with production safety checks. |
doc-worker
| Component | Description |
|---|---|
| main | Routes /health, /parse, /chunk, /parse-and-chunk, /render-pages, /extract-url; bearer-token auth (required in production); limits. |
| parsers | detect picks a parser by sniffed type; docling_parser (default, PARSER=docling), light (no layout model: pypdfium2, python-docx, python-pptx, BeautifulSoup) for tests and formats Docling does not handle, pdfium helpers behind a process-wide lock; ocr runs Tesseract (eng+deu+ara by default) on scanned pages. Zip-bomb and frame-count checks. |
| render | Renders PDF pages to PNG images, capped in pixels, for run input files sent to vision models. |
| chunking | Splits parsed text into chunks following headings and tables, for ingestion. |
| extract_url | Fetches a public page with a total deadline and private-network blocking, returns its main text (used by the built-in web_fetch tool; website sources are crawled by the worker itself). |
| config / models / errors / logging_setup | Settings from env, Pydantic request and response models, error responses, JSON logging. |
Previous: Level 2: Containers.