Skip to content

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 ​

ModuleFolderDescription
authsrc/authbetter-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.
policiessrc/policiesResource-level access rules (API keys, data sources, files, realtime, workflows), registered once and checked by services.
limitsmodules/limitsSliding-window /v1 rate limits on Redis (RateLimitGuard), the monthly spend cap and storage quota (QuotaService), per-org settings. Global.
healthmodules/healthGET /health: database required, Redis reported. Used by container health checks.
memodules/meGET /console/me: the signed-in user and their organizations.
projectmodules/projectProjects inside an organization; every project-scoped route checks its project through ProjectRepository. Global.
api-keymodules/api-keyProject API keys: create (shown once, stored as SHA-256 hashes), scopes, optional agent restriction, revoke. ApiKeyGuard looks keys up here. Global.
secretmodules/secretEncrypted project secrets, resolved server-side for HTTP tools, data sources and workflow HTTP nodes ({{secret:NAME}}).
agentmodules/agentAgents and immutable versions, publish, config validation against the shared contracts (models, tools, schemas, guardrails).
toolmodules/toolCustomer-defined HTTP tools; plugs the http provider into the tool registry and calls endpoints through the SSRF-safe client.
tool-runtimemodules/tool-runtimeToolRegistry: turns an agent's tool refs into LLM tools via providers registered by other modules; built-in tools (web_fetch, language detection).
llmmodules/llmLlmService, the only way to call model providers: text, structured output, tools, vision, embeddings, token accounting. FAKE_LLM=true swaps in deterministic fake models.
runmodules/runRunExecutor 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.
workflowmodules/workflowDurable 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.
realtimemodules/realtimeVoice: 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-sourcemodules/data-sourceKnowledge: 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.
filemodules/fileUploaded files for run inputs and data sources: streaming multipart upload, type sniffing, quotas, signed downloads, hourly expiry (FileProcessor).
storagemodules/storageStorageService: the S3 client for SeaweedFS (put, get, delete, presigned URLs).
doc-workermodules/doc-workerDocWorkerClient: authenticated HTTP client for the internal doc-worker (parse, chunk, render pages, extract URL).
webhookmodules/webhookWebhook endpoints per project, event emission (emit), HMAC-signed deliveries with retries by WebhookProcessor; signing secrets stored encrypted.
catalogmodules/catalogGlobal model catalog: providers (enabled when a key is stored), models, prices, templates. Seeded on startup; every model lookup resolves here.
usagemodules/usageUsage events and daily rollups in USD micros, pricing, 80 % / 100 % spend alerts, console usage dashboards and CSV export. Global.
auditmodules/auditReads the audit log (entries written with audit() from common). Global.
opsmodules/opsSuper-admin /ops API: organizations, limits and suspension, model catalog and prices, platform usage, audit log, job queues.
commonsrc/commonShared 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.
dbsrc/dbDrizzle client (withOrg for RLS, getAdminDb for the few cross-tenant paths), schema (app.ts, better-auth's auth.ts), migration runner.
configsrc/configenv(): the only access to environment variables, validated with Zod, with production safety checks.

doc-worker ​

ComponentDescription
mainRoutes /health, /parse, /chunk, /parse-and-chunk, /render-pages, /extract-url; bearer-token auth (required in production); limits.
parsersdetect 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.
renderRenders PDF pages to PNG images, capped in pixels, for run input files sent to vision models.
chunkingSplits parsed text into chunks following headings and tables, for ingestion.
extract_urlFetches 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_setupSettings from env, Pydantic request and response models, error responses, JSON logging.

Previous: Level 2: Containers.

Hevkar public API v1