Orchestrator
The control plane is a strict TypeScript service in apps/orchestrator. The Python in runtime/ runs inside agent sandboxes: user scripts, browser automation, the code helper, and the coding harness drivers.
The process model, the Compose stack, and the trust boundary are Deployment and trust boundary. Where each module lives is the Code map.
Stack
- Node.js 24 LTS, image
node:24.21.0-bookworm-slim(pinned by digest in the Dockerfile),engines.node^24 - pnpm 10 (
packageManagerpinpnpm@10.17.1), workspaceapps/*andpackages/* - Fastify 5, TypeBox,
@fastify/type-provider-typebox,@fastify/static,@fastify/websocket - Drizzle ORM with
node-postgresonpostgres:17 openai(official client) for achat-completionsprovider,@anthropic-ai/sdk(official client) for amessagesprovider,js-tiktokenfor input counting,cronerfor cron,undicifor outbound HTTP,fastbrowsefor the agent-optimized browser,esbuild(development) to bundle a registry connector,@dicebear/*for avatars,@sentry/node,@sentry/profiling-node, and@sentry/node-nativefor event loop stall stacks- Tests:
node:testthroughtsx - OpenSandbox server commit
473ff611d93670a149ce6600f27ed194b18cce89,opensandbox/execd:v1.1.0, runtimeagent-runtime:0.4(every machine), TypeScript SDK from that same commit (sdks/sandbox/javascript) - Token counting:
js-tiktokenwith one encoding,o200k_base, for every model, loaded once per process (src/llm/tokens.ts) - Cost: provider-reported
cost_usdfirst, then the catalog's rate for the model on a billed provider, elsecost_source: unavailable. The catalog rate prices uncached input, cache reads, and output;cache_read_tokensis a subset ofinput_tokens. A message records the catalog's fetch date aspricing_version. A subscription agent's turn records the tokens its harness reports on its reply, withcost_usd0 andcost_source: subscription
Configuration
src/config/index.ts validates the environment once into a typed AppConfig. A value it refuses throws a ConfigError naming the variable, and boot stops.
DATABASE_URL(required)NOTES_ROOTandWORKSPACE_ROOT(required, existing directories)ATTACHMENTS_ROOT(empty keeps attachment bytes in memory)TEMPLATES_ROOT(the prompt templates,src/promptsby default)OPENSANDBOX_URLandOPENSANDBOX_API_KEY(required)SANDBOX_IMAGE(required: the image every machine runs)SECRETS_MASTER_KEY(required), andALLOW_ZERO_MASTER_KEY=1on a development stackAUTH_MODE(compat-cookieby default) with thetrusted-headersettings:PUBLIC_BASE_URL,TRUSTED_PROXY_SECRET, andOPERATOR_EMAIL, each required in that mode, andTRUSTED_HEADER_EMAIL(X-Forwarded-Emailby default)MAX_CONCURRENT_GENERATIONS(default 0, no ceiling)TOOL_RESULT_MAX_BYTES(default 65536)HARNESSES_OFF(coding harnesses this box does not offer, separated by commas or spaces; an unknown name stops boot)HOST(default0.0.0.0)PORT(default 8080)HARNESS_MCP_HOST(default127.0.0.1),HARNESS_MCP_PORT(default 8090), andHARNESS_MCP_URL(the URL a sandbox is given for the MCP listener;http://host.docker.internal:<port>by default, and refused unless anhttporhttpsURL with no credentials, query, or fragment)
Configure explains each one. The model catalog reads MODELS_DEV_URL on its own (Configure). The environment integrations' variables (SENTRY_DSN, REGISTRY_URL, REGISTRY_PUBLIC_KEY, CONNECTORS_CODE_TIER, CONNECTORS_ROOT) are read through the integration registry (Extension points).
loadConfig accepts the modes an extension identifies requests in beside core's two. The instance keys are read through the registry in src/instance/integrations.ts and the encrypted store it snapshots (src/instance/keys.ts), so a platform key a platform admin enters takes effect without a restart (Extension points).
A few modules read their own optional variables:
CODE_RESULT_MAX_BYTES(the code helper's result cap, default 8192)WORKSPACE_MAX_MIB(host-wide cap on one agent's home, default 10240; each agent also hasmax_workspace_mib, default the same, and each machine amax_workspace_mibover every home on it)SENTRY_ENVIRONMENT(defaultNODE_ENV, elsedevelopment),SENTRY_TRACES_SAMPLE_RATEandSENTRY_PROFILE_SESSION_SAMPLE_RATE(default 1 each),SENTRY_DEBUG=1ADAPTER_PROXY_URL(forward proxy for adapter and MCP HTTP)OPENSANDBOX_SDK_MODULE(test substitution)
Operational constants
Configurable only in tests:
- idle timeout (
LOOP_TIMINGS.idleTimeoutMs,generation/index.ts) = 5 minutes, for a machine and for an agent's Chrome - scheduler tick (
LOOP_TIMINGS.schedulerTickMs) = 30 seconds CANCEL_GRACE_MS(generation/completion.ts) = 2 secondsSHUTDOWN_TIMEOUT_MS(generation/completion.ts) = 15 seconds- PostgreSQL pool = min 1, max 5, TCP keepalive, connection handshake timeout 10 seconds
- runtime metrics sample = 10 seconds; event loop stall = 1 second
- OpenSandbox SDK
requestTimeoutSeconds= 180 - OpenSandbox list
pageSize= 100 - model request timeout = 25 ms per
max_tokens, at least 2 and at most 10 minutes - script command timeout = 120 seconds
- browser tool timeout = 60 seconds
- browser ready wait = 60 seconds
- code helper timeout = 120 seconds
- inline code helper request = 64 KiB of base64; larger goes through the sandbox file API
- MCP catalog refresh interval = 10 minutes
- MCP tools/list timeout = 15 seconds
- MCP tools/call timeout = 90 seconds
- adapter HTTP timeout = 30 seconds
- TypeSafe call timeout = 8 seconds, 2 retries with backoff
TOOL_RESULT_MAX_BYTESdefault = 65536- sandbox resources = 1 CPU and 2Gi on a standard machine, 2 CPU and 4Gi on a code machine, and the machine's
cpuandmemory_mibon a custom one (0.5 to 8 CPUs in steps of 0.25, 512 to 8192 MiB) - agents per machine = 32 (slots 0 to 31)
- agent minimum = the largest of 0.5 CPU and 256 MiB, 1 CPU and 2 GiB with
browser, 2 CPU and 4 GiB with a harness (a subscription agent) (Machine sizing) - overcommit before placement warns = 5× a machine's CPUs, 3× its memory
- browser desktop = 1280×720
- event queue per subscriber = 4096 on a run, guild, Studio, or Builder stream; 256 on an inbox stream
Compose stop_grace_period on the orchestrator is 20 seconds so Docker does not SIGKILL during SHUTDOWN_TIMEOUT_MS.
Startup and shutdown
From apps/orchestrator, pnpm start (or pnpm --filter @guildsrun/orchestrator start from the repo root) runs node --import tsx --import ./src/instrument.ts src/server.ts. Local Compose uses make up or make dev.
server.ts is core's process entry. It loads AppConfig and calls runServer (src/run.ts). runServer builds the server with createServer (src/compose.ts), listens, and shuts it down on a signal or a fatal error. The extending repository has an entry of its own, which passes its extensions with its configuration loaded beside core's (Extension points). Core passes none.
createServer runs these steps in order:
- install the extensions' connectors and integrations, and the
HARNESSES_OFFlist - connect to PostgreSQL: core's migrations, then each extension's; then seed the system catalog, then each extension's seed, then the operator and its organisation on a box that still has no user; start the runtime metrics; with
OPERATOR_EMAILset, giveuser_operatorthat address - construct
NotesStoreand check thatsystem.mdexists inTEMPLATES_ROOT - load the registry connectors' code (
registry/code.ts), derive the connector-declared integrations (connectors/instance.ts), load the instance keys into their snapshot (instance/keys.ts), and sync the platform logins (connectors/instance.ts) - take the organisation policy (an extension's, else
OPEN_POLICY); build the artifact store (artifactStore), the agent scripts and schedules, the model credentials (an extension's, else core's), the model service, and the MCP pool (mcpPool) - start the sandbox provider: one
RunSandboxesmanager onOPENSANDBOX_URL, or the one an extension supplies; then lay out agent homes by machine (machines/layout.ts): destroy every sandbox labelled with anagent_id, and move eachWORKSPACE_ROOT/<agent id>that exists toWORKSPACE_ROOT/<machine id>/<agent id>when the target does not - take the blob store (an extension's, else
FileBlobStoreunderATTACHMENTS_ROOT, elseMemoryBlobStore); construct the attachment service, the artifact files, the admission coordinator, andGenerationLoop; reconcile active runs; start the scheduler - construct Studio and reconcile its sessions; construct capabilities, recipe apply, and Builder; reconcile Builder sessions
- build the Fastify app (
buildApp,src/app.ts), each extension's routes first, then the MCP listener (buildHarnessMcpApp), a Fastify app of its own on the loop'sHarnessMcpServer
runServer logs whether Sentry is on and installs the fatal error handlers before it calls createServer. It then listens on HOST and PORT, and the MCP listener on HARNESS_MCP_HOST and HARNESS_MCP_PORT.
Run reconciliation:
- list every active run
- end a subscription agent's lost harness turn, named by the run's
metadata.harness_turn:guilds-harness stopon its machine when the machine is running, its state cleared once the CLI has exited, the session its result names kept on the record, and the interrupted result, markedfrom_harness, for each call of the harness's own tools without one - append interruption tool results for unresolved committed tool calls
- leave direct runs, and runs an operator resumed, active and reusable
- append a
generation.interruptedrun error to group and schedule runs - complete group delivery through the run's snapshotted sequence or complete the schedule run
- resume pending group dispatch
- schedule idle teardown for running machines on which no agent generates
Studio and Builder reconciliation settles each session left generating or cancelling: the generation is recorded as interrupted and the session goes idle.
Graceful shutdown (SIGTERM or SIGINT) runs once, in this order:
- close the HTTP server, sockets and streams included, then the MCP listener
- stop the scheduler, cancel the machines' idle timers, and stop the group dispatchers
- ask every in-flight generation to stop and interrupt its sandbox command, then wait up to
SHUTDOWN_TIMEOUT_MSfor them - close the sandbox provider, stop the runtime metrics, and close the PostgreSQL pool
- flush Sentry
An unhandled rejection or uncaught exception logs, flushes Sentry, shuts down, and exits 1.
Request path
CRUD writes PostgreSQL and returns JSON. Runs go through GenerationLoop. The UI follows on GET /api/runs/:id/stream (SSE). Studio and Builder use the shared conversation runner and their own streams.
A route reads the request, calls its domain, and writes the reply. A route declares a TypeBox schema for the body, query and params it reads, and Fastify checks the request against it before the handler runs. A route with a body schema takes a JSON object, and a request without one is refused. The check converts nothing: a value of the wrong JSON type is refused. A refused request is a 422 whose detail lists the problem as { type, loc, msg, input }: a missing field is type: "missing", msg: "Field required", at loc [part, ...path, field], with the object it is missing from as input; any other problem is the schema keyword it broke, at the value's path, with the value as input. part is body, querystring, params or headers (validationHttp in http/errors.ts). A route that answers 404 to whoever may not use it, such as the instance admin's, refuses them in a preValidation hook (instanceAdminOnly in http/instance-admin.ts), so the check comes before the schema's and a refused caller gets the same 404 whatever they send.
A domain refuses a request with a named error that carries the HTTP status it answers with, or with a validation error, which is a 422. domainHttp in http/errors.ts turns either into the reply. A refusal of the notes store answers by its message: 409 for a name that exists, 422 for a path or change refused, 404 for what is not found, and 500 otherwise. A route that reads notes answers every refusal of the store with 404, but an invalid path with 422 (notesRead).
Generation
Work queuing
An agent runs at most one generation at a time (ActiveGenerations in generation/active-generations.ts). Direct, group, and schedule work all take that same lock. Work waits in that registry, in group dispatch, and in the schedule's next_run_at, never in a job table.
| Incoming work | If the agent is already generating |
|---|---|
| Direct chat (message) | HTTP 409; the operator retries |
| Group delivery | Wait for lock release, then retry |
| Due schedule | Skip this tick; next_run_at stays due |
Studio and Builder take an organisation admission slot, not the agent lock (AdmissionCoordinator in admission/coordinator.ts). They do not make a target agent busy. A posted message takes the session's slot (ConversationRunner.admit) before the turn is recorded; a refused slot answers the post with HTTP 409 and the admission's message, and records nothing. A turn that fails to record gives the slot back, and the generation of a recorded turn gives it back when it ends.
Group chat coalesces. Several unseen messages become one run with a snapshot through the current chat_seq. Schedules do not coalesce: two due routines for the same agent fire on successive ticks.
A run
Three ways in: direct message, group-chat delivery, or a due schedule.
RunPreparation (generation/prepare.ts) builds the PreparedRun: it hydrates task + memory, builds the State JSON, and resolves bindings and the agent's secrets. The run row keeps the hashes of its opening prompts.
That prompt and the ordered message rows are the stored history. Each model call projects tool results from those rows (conversation/projection.ts).
Before each model call, input tokens are the o200k_base length of the JSON text of the projected messages, plus the JSON text of the offered tools when any are offered, and at least 1. The process loads that encoding once. Studio uses the same counter. A run adds 1600 tokens for each image. Counting runs on the server event loop.
Tools:
- Native (
toolbox/): artifacts, memory, scripts, schedules, browser, group post, report issue, secrets - Connectors (
connectors/, dispatched bymcp/): a remote MCP endpoint (Notion, Sentry, Cigale, Etherscan), adapter code (CoinGecko, Alchemy, X, TwitterAPI.io, Qonto, DexPaprika, Gmail, Tavily web search on the instance key), or both (Drive, OpenSea); one catalog shape
Scripts and Chromium run on the agent's machine. Notes and collections stay in PostgreSQL. The sandbox never mounts a notes tree.
Concurrency rules
- A registry maps each active agent to at most one generation.
- One mutex protects ownership check, controller insertion, cancellation handoff, and removal. It is never held during model or tool I/O.
- Generation start reserves the agent before the run row is inserted.
- Creating a direct run without a user message is allowed while that agent is generating. Creating or continuing a run with a message returns 409 while the agent is busy.
- Each controller owns one
AbortController. - Cancel first requests a cooperative stop, interrupts the in-flight sandbox command, waits
CANCEL_GRACE, then aborts. Settlement of interruption records runs once. - Group dispatch waits on a generation lock-release counter when every actionable agent is busy. Schedule retry does not wait: a busy agent is skipped and the 30-second ticker retries.
- Guild deletion sets a deleting-guild guard, refuses new runs and group actions with 409, and releases the guard in
finally. - Secret changes re-resolve the active-run secret snapshots of the agents they reach and replace no container: secrets travel on each command, and a generation resolves them at its start.
secretChanged(secretId)covers a new value, name, or description (the agents with an active run snapshot using it).secretAccessChanged(agentIds)covers a create, a delete, an access change, and a newsecret_storesecret (the agents that gain or lose it). - Agents on one machine generate at the same time. A machine is busy while any of its agents generates. Its idle timer starts when the last generation on it ends, and a machine whose tier or size changed while busy is destroyed then instead.
- Each browser agent's Chrome has its own idle timer, restarted by the agent's browser calls and Browser pane input.
- Agent deletion, guild deletion, and a move between machines stop the agent's processes on its machine through
agent-stop; a deletion removes its home, a move renames it on the host. They are refused while the agent generates.
Admission is per organisation. Ordinary runs, Studio, and Builder share one slot count under the organisation policy's maxConcurrentRuns and the instance ceiling MAX_CONCURRENT_GENERATIONS (0 is no ceiling). A Studio or Builder session holds its slot from the post of a message to the end of the generation it starts (Work queuing).
Events
One in-process bus carries every event. Each SSE stream sends : connected\n\n, then live events only, and a : keepalive\n\n comment every 15 seconds while it is open.
An event is a name and a JSON object (StreamEvent in lib/event.ts), written as the SSE frame's data by http/sse.ts. Each stream declares its events and what each carries, beside the stream: RunEvents in generation/events.ts, CoachEvents in conversation/runner.ts for Studio and Builder, GuildEvents in groupchat/index.ts, and InboxEvents in notifications/index.ts. A publish whose data does not match its event's type does not compile.
| Event | Stream | Class | What it says |
|---|---|---|---|
message.committed | run, Studio, Builder | durable | A message row committed |
generation.started | run, Studio, Builder | durable | A generation began |
generation.finished | run, Studio, Builder | durable | A generation ended. On a run, { generation, standing }, published once the run is completed when it ends with this generation and the generation no longer holds it: standing is where the run then stands (open, waiting, generating, completed, capped; runStanding in generation/lifecycle.ts) |
run.error | run | durable | A run error; cancellation has operation: "generation.cancelled" |
run.wake.changed | run | durable | { pending_wake }: the run's pending wake-up after it was set, replaced, cancelled, or fired; null when none is left |
assistant.delta | run, Studio, Builder | ephemeral | Text being written |
assistant.reasoning.delta | run, Studio, Builder | ephemeral | Reasoning being written |
tool.progress | run | ephemeral | {run_id, tool_call_id, lines}: a running browse call's redacted step line |
session.error | Studio, Builder | durable | An error of a coach session's running generation; a post the admission refuses publishes none |
draft.changed | Studio | durable | A Task draft changed |
recipe.changed | Builder | durable | The draft recipe changed |
group.message.committed | guild | durable | A group message committed |
group.cleared | guild | durable | An operator cleared the group chat |
group.limit_reached | guild | durable | The guild's message budget is spent |
group.idle | guild | durable | Group dispatch has nothing left to deliver |
group.delivery.started, group.delivery.finished, group.delivery.failed | guild | durable | A delivery run's progress |
guild.artifacts.changed | guild | invalidation | A note, file, record, or agent item the guild's page shows changed. An agent's write of a record or of its own items is announced on its guild. A write or delete of a note or a file, by an agent or an operator, and a replaced access list of one, are announced on each guild whose page lists the item, before or after the change: its home guild and the guilds in its scope, every guild of the organisation when its access list has an organisation row, read from every row of the list; an item homed in a private guild is announced on that guild alone. { path, scope?, agent_id? }, scope agent for an agent's Task or Memory and files for a shared file; re-read them |
guild.issues.changed | guild | invalidation | Re-read the guild's issues. The guild's group chat also looks again for agents to deliver to, since a resolved blocking issue enables its agent |
agent.scripts.changed | guild | invalidation | Re-read an agent's scripts |
agent.routines.changed | guild | invalidation | Re-read an agent's routines |
notifications.changed | inbox | invalidation | Re-read the inbox |
notifications.message | inbox | durable | A message posted in a guild the user sees, with its author's look |
notifications.issue | inbox | durable | An issue an agent reported in a guild the user operates, as the Inbox lists it |
The streams:
- run:
/api/runs/:id/stream - guild:
/api/guilds/:id/group-chat/stream - inbox:
/api/notifications/stream, one per user - Studio:
/api/studio/sessions/:session_id/stream - Builder:
/api/builder/sessions/:session_id/stream
Delivery rules:
- A durable or invalidation event is a commit notification. It is published only after its transaction commits. A subscriber that misses one recovers by re-reading PostgreSQL over REST.
- An ephemeral event cannot be reconstructed. The UI recovers by re-fetching committed messages. Their metadata carries the full reasoning text.
- There is no historical replay. After a reconnect the client re-reads over REST.
- A run's generation publishes
generation.started; then its deltas,message.committedandtool.progressevents as it goes; on a cancel, the interrupted tool results and the cancel'srun.error; on a terminal cap,run.wake.changedand therun.errorof the cancelled wake-up; thengeneration.finished. A client that re-reads the run ongeneration.finishedreads it as the generation left it: not generating, and completed when it completes with that generation. Thestandingit carries isopenfor an active run that takes an operator's message,waitingfor an active run that takes none (a group or schedule run that was not resumed),completedfor an ended run that can be resumed,cappedfor one that ended on a terminal cap, andgeneratingfor one a generation holds. A generation whose finishing fails, such as a failed completion of its run, still publishesgeneration.finished, with the standing of the run as it is read again; only a run whose row is gone publishes none. - Headers are
Content-Type: text/event-stream; charset=utf-8,Cache-Control: no-cache,Connection: keep-alive, andX-Accel-Buffering: no. - Slow subscribers do not stall generation. A disconnected subscriber, or one whose queue is full, is dropped. A subscriber dropped for a full queue has its response ended, so its client reconnects and re-reads.
PostgreSQL
Core's schema starts at 0001_baseline in apps/orchestrator/drizzle/. That file is a snapshot of every core table, including pg_trgm. Numbered migrations follow it.
Production never uses drizzle-kit push. Boot runs committed migrations before the HTTP listener becomes ready: core's, recorded in public.__drizzle_migrations, then each extension's chain. A core migration the database has not recorded after that stops boot with MigrationsNotApplied, naming it (Development). An extension keeps its tables and its record in a schema of its own (Extension points).
New core schema lands as the next numbered SQL file in apps/orchestrator/drizzle/. It is mirrored in src/db/schema/, one file per table family that index.ts re-exports, which the row types in db/ derive from, and stamped after the migration before it.
Core's tables:
- users
- orgs
- org_members
- org_model_providers
- org_monthly_usage
- instance_keys
- machines
- guilds
- guild_operators
- guild_repositories
- guild_issues
- agents
- runs
- messages
- run_wakes
- group_messages
- group_chat_reads
- schedules
- secrets
- secret_grants
- connectors
- connector_calls
- mcp_connections
- mcp_tools
- bindings
- usage_counters
- artifacts
- artifact_collections
- artifact_access
- attachments
- file_changes
- config_changes
- memory_revisions
- task_revisions
- studio_sessions
- studio_messages
- studio_drafts
- builder_sessions
- builder_messages
- recipes
- recipe_applies
Notes and files are artifacts of the organisation, with no agent_id; a name is unique among the organisation's live notes, and among its live files. Memory and scripts are artifacts with the agent's agent_id, unique per agent.
artifacts.origin_guild_id is the guild an item was made in, null for the organisation, written at insert and changed by no write. Deleting an agent of a private guild sets it to that guild on each note and file with no home whose access list names only the agent, before the agent's rows go; deleting a private guild removes the notes and files homed in it and those with no home whose list names only the guild and its agents, before its rows go (src/db/artifact-access.ts). It references guilds(id) with ON DELETE SET NULL (artifacts_origin_guild_id_fkey), and artifacts_by_origin_guild indexes (origin_guild_id, org_id), led by the home so the page lists and the foreign key's action both use it. On a note or a file it is the home guild: the guild and agent pages list the items homed in their guild apart from those shared with it, and an operator never reaches an item homed in a guild hidden from them. No agent's mode reads it (Artifact store). The page lists come from src/db/artifact-lists.ts, which reads each item's home and the page viewer's mode in the listing's own query, one lateral join per row, with no query per item.
Collections live in artifact_collections (name, purpose, typed columns, next_id). Their records live in artifacts (kindobject, key the id, identity the normalised unique value). artifact_collections.guild_id places a collection in one guild, or at the organisation when null.
Notes, files, and collections share one access list table, artifact_access: one row per item and subject, the subject being the organisation, a guild, or an agent. A note's or a file's rows are all that decides who reaches it. An agent's own row wins, and none there shuts it out; otherwise it takes the better of its guild's and the organisation's read or write. A new note or file starts with one row: the creating agent at write, or the subject the operator names, the organisation at write by default. A new guild collection starts with its guild at write, a new organisation collection with the organisation at read. A deleted note or file keeps its rows on its tombstone. Rows go with the guild or agent they name. A private guild takes every note and file homed in it, live or deleted, with its file_changes, its rows and the config_changes of its access list; a guild open to the organisation and an agent take no note or file (Access).
The standing task lives on agents.task. Agent names are globally unique.
The host-side trees beside PostgreSQL are in Deployment. OpenSandbox keeps its container lifecycle in its own SQLite store, which holds no application data.
Seeds stay separate from schema (src/seed/):
catalog.ts seed identifiers and native-tool lists
mcp-manifests.ts the installed connectors projected into catalog rows and tool copy
system.ts upsert catalog, platform bindings
operator.ts the operator and the Home organisation, on a box with no user
test.ts deterministic fixtures
connect.ts open the pool, migrate, and seedBoot runs the system seed, each extension's seed, and the operator seed. Each is idempotent. POST /api/users creates a personal organisation for the user it creates. The baseline contains no application data insert.
Codecs
node-postgres parsers and repository mappers are explicit.
| PostgreSQL type | API JSON |
|---|---|
INTEGER (messages.seq) | number |
BIGINT / BIGSERIAL | number (safe-integer check) |
NUMERIC (usage_counters.cost_usd) | number rounded to 8 decimal places |
TIMESTAMPTZ | string, microsecond precision |
BYTEA | never returned as UTF-8 text on list/get |
JSONB | object; defaults applied before validation |
Every JSONB parameter is written through formatJsonb in db/codecs.ts. JSONB holds neither a NUL character nor an unpaired UTF-16 surrogate, so each one in a string or an object key is stored as U+FFFD; every other character is stored as it is. A value read back holds U+FFFD where the written value held one of them.
Column timestamps in REST (created_at, updated_at, next_run_at, last_run_at, rotated_at) use YYYY-MM-DDTHH:MM:SS[.ffffff]+00:00.
Operational at fields in run and group errors use Z. Prompt-embedded JSON (State, group-chat info, schedule wake-up) uses JSON.stringify(value, null, 2). SSE data: framing is exact. HTTP bodies compare as parsed JSON.
AES-256-GCM uses a 12-byte nonce and no additional authenticated data. secrets.ciphertext stores ciphertext plus the GCM tag. secrets.nonce stores the 12-byte nonce separately. The master key stays outside PostgreSQL.
SECRETS_MASTER_KEY accepts a 32-byte strict base64 value, URL-safe base64, hex (whitespace allowed; invalid hex rejected), or raw ASCII, in that order. The all-zero key is refused unless ALLOW_ZERO_MASTER_KEY=1, which only the development overlay sets.
AES-GCM plaintext is compact sorted UTF-8 JSON with non-ASCII \uXXXX-escaped. Environment fingerprints serialize sorted [name, value] pairs as compact UTF-8 JSON.
Model client
Two functions are the model client:
// src/llm/client.ts
function streamCompletion(
request: ModelRequest,
endpoint: ModelEndpoint,
signal?: AbortSignal,
): AsyncGenerator<ModelEvent>;
// src/llm/tokens.ts
function countInputTokens(
model: string,
messages: readonly MessagePayload[],
tools?: readonly FunctionTool[] | null,
): number;Generation calls both through generationLive (generation/completion.ts), which tests replace.
Each provider row names the API it speaks. A chat-completions provider is called with the official OpenAI client, a messages provider with the official Anthropic client (src/llm/anthropic.ts), each pointed at the provider's base URL with the credentials the run resolved. A run is provider + credentials + model. Stored model ids are {provider}/{model}.
Providers
One row per provider (src/llm/providers.ts) is its whole definition. Whether a provider is billed comes from the id prefix, never from a catalog row.
| Id | Billed | API | Catalog | Base URL |
|---|---|---|---|---|
openai | yes | chat-completions | models.dev openai | https://api.openai.com/v1 |
anthropic | yes | messages | models.dev anthropic | https://api.anthropic.com |
openrouter | yes | chat-completions | models.dev openrouter | https://openrouter.ai/api/v1 |
xai | yes | chat-completions | models.dev xai | https://api.x.ai/v1 |
deepinfra | yes | chat-completions | models.dev deepinfra | https://api.deepinfra.com/v1/openai |
local | no | chat-completions | the endpoint's /models | the organisation's URL |
An unbilled provider's calls record cost_source: unavailable.
Catalog
models.dev (https://models.dev/api.json) is the catalog (src/llm/catalog.ts, src/llm/models-dev.ts). The orchestrator fetches it on the first read and again on a read once the cache is older than an hour. A failed refresh keeps the last good cache and is retried after five minutes. Before the first fetch, and on a box with no network, the snapshot in src/llm/models-dev.snapshot.json serves it: pnpm --filter @guildsrun/orchestrator models:snapshot rewrites that file from the feed, reduced to the hosted providers and the fields the catalog reads. The whole feed is never checked in.
A row is kept when tool_call is true, status is not deprecated, and text is among its input and output modalities. Each kept row maps to an entry: {provider}/{id}, name → label, reasoning → thinking, temperature, attachment or image among the input modalities → attachments, limit.context, and cost per million tokens → rates per token for a billed provider. The feed's fetch date, or the snapshot's, is the pricing_version a message records.
A model id that is well-formed for a known provider but missing from the last fetch is valid, with the default capacities: thinking on, temperature on, attachments off. The local endpoint is not in models.dev; once its URL is saved, GET {baseURL}/models lists it, and its models take those same capacities.
Credentials
Core asks one function for the credentials of a provider for an organisation: ModelCredentialsProvider (src/llm/credentials.ts), an extension point whose core default reads the organisation's row (Extension points). Agent save, Studio and Builder start, and every completion resolve credentials through it. A provider whose credentials resolve is connected; one that does not refuses the save with connect a … key on Model keys and ends a run with generation.model_key. A PolicyError it throws ends the run with its message, as the organisation policy does. A connected provider whose row holds no key of the organisation's is served by the platform (source: "platform"), and is not the organisation's to remove (409).
The function may return an onUsage callback. Core calls it once per completion with the run id, the model, the token usage, and the cost with its source; a failure is logged and never fails the run. Core keeps no spend gate of its own.
Requests
Requests send User-Agent: guilds.run. Automatic retries are off. The request timeout scales with max_tokens, from two to ten minutes.
- Inputs are the complete ordered OpenAI-style message history.
- Tool schemas pass through without framework transformation to a
chat-completionsprovider. temperatureis omitted when the catalog says the model does not take one.- A
chat-completionsbody differs per provider in three places:
| Provider | Output cap | Thinking | Prompt cache |
|---|---|---|---|
openai | max_completion_tokens | reasoning_effort | none |
openrouter | max_tokens | reasoning: { effort } | cache_control on the last text, and top-level |
xai, deepinfra, local | max_tokens | reasoning_effort | none |
OpenAI rejects a field it does not know, so a request to it carries only the fields in its row.
A
messagesprovider takes the same history translated to the Messages API: the leading system messages becomesystem, a later one a user turn; assistanttool_callsbecometool_useblocks andtoolmessagestool_resultblocks; consecutive turns of one role merge;image_urlparts become image blocks (a data URL as base64, an http(s) URL as a URL source). Tools are sent asname,description, andinput_schema. A thinking level sendsthinking: { type: "adaptive", display: "summarized" }withoutput_config.effortat that level, and notemperature; with no level,thinkingis omitted. Top-levelcache_controlcaches the prompt up to its last block. Thinking blocks are not replayed. Usage counts cache reads and writes intoinput_tokens;stop_reasonmaps tofinish_reason(tool_use→tool_calls,max_tokens→length,refusal→content_filter, otherwisestop). Saving a key probesGET /v1/modelswithx-api-key. The call fails withLLMErrorbefore anything is sent when the history holds a data URL that is not JPEG, PNG, GIF, or WebP, when a tool's parameters are an object that is not an object schema (type: "object",requireda list of strings), or when the thinking level asks for an effort the API does not take. A tool with no function name is left out, and parameters that are not an object are sent as an empty object schema.Streaming emits text deltas, reasoning deltas, and one final assembled assistant payload. A
chat-completionschunk is read into its id, served model, text, reasoning (reasoning, elsereasoning_content, else the text ofreasoning_details), tool call pieces, finish reason, and usage; a field that is missing or of another type is read as empty, and a tool call piece without an index belongs to the first call.Final metadata:
usage.input_tokens,usage.output_tokens,usage.cache_read_tokens,latency_ms,finish_reason, servedmodel,response_id,provider_request_id,cost_usd,cost_source, andpricing_versionwhen the catalog priced it. Accounting readscost_usdonly.
Sandbox and tools
A RunSandboxes manager drives one OpenSandbox, from the configuration. An extension may supply a sandbox provider of its own (Extension points).
A manager's work:
- ensure one matching container per machine, labelled with its
machine_id, tier, size, and image fingerprint, with the machine's directory mounted at/home - read the harness CLIs a new container's image carries
- execute and interrupt commands
- start and stop an agent's browser (
agent-browser-start,agent-stop) and terminal (agent-cli-start) on its slot's ports - resolve the agent's noVNC, DevTools relay, and terminal endpoints
- destroy the containers of idle or stale machines
The generation loop hands every tool an agent's view of the machine's container: each command runs in the agent's home with HOME, GUILDS_AGENT_HOME, PORT, GUILDS_PORTS, and the agent's secrets in its own environment. Files and interrupts are the machine's.
OpenSandbox SDK objects do not escape the sandbox module.
A CDP client in the orchestrator reaches an agent's Chrome through a CDP bridge (browse/bridge.ts), which its caller opens for one use and closes after it. The bridge listens on an ephemeral port of the loopback interface only. It forwards Chrome's /json endpoints, and the /devtools/ WebSockets they name, to the endpoint of the agent's DevTools relay with the headers the sandbox host requires, its Host left as the endpoint's URL names it, and rewrites every webSocketDebuggerUrl it relays to point at itself. A client that connects only to a local port and adds no headers, as fastbrowse does, drives the agent's Chrome that way. Any other path answers 404; a relay that does not answer is a 502 on HTTP and an ended socket on a WebSocket. The relay in the container sets each request's Host to Chrome's loopback address, because the sandbox host's proxy rebuilds the Host from its own upstream address and Chrome refuses a DevTools request whose Host is not an IP address or localhost.
A browse call runs in the orchestrator (browse/service.ts, browse/runner.ts). The tool validates its arguments and wakes the agent's Chrome (ensure_browser). The service reads the System One key and the agent's browser_model, resolves that model's credentials through resolveModelCredentials, and turns both into fastbrowse's environment (browse/env.ts). That environment sets every variable fastbrowse reads a key, an endpoint, a model, or its Jev source from, blank where the run's route does not use it, so nothing of the orchestrator's own environment reaches fastbrowse's routing. It asks the generation's cdp_target hook for the agent's DevTools relay, opens a CDP bridge to it, and starts a fastbrowse process attached to that Chrome in the foreground, its stderr logged at debug. The run's cancel, or max_seconds plus 30 seconds, aborts the run, and an aborted run's spend is logged as uncounted (browse.cost), since fastbrowse answers no result. Each step is published as the call's tool.progress event, redacted with the run's secrets and clipped like a harness's progress lines, and re-arms the agent's browser and machine idle timers (touch_browser); a step that fails to publish is logged (browse.progress) and the run goes on. The result is formatted for the model (browse/format.ts), and its cost lines become the call's browser_usage (browse/cost.ts), which incrementUsage counts when the tool message is committed. Fastbrowse and the bridge close however the call ends. The keys stay in the orchestrator's process: the machine's container sees only DevTools traffic.
Control-plane tools run in Node (notes, records, memory, schedules, scripts, secrets, remote MCP servers, adapters). Sandbox tools invoke reviewed helpers inside the agent container (script_run through guilds-script-run, Playwright through guilds-browser; a subscription turn's git setup, checkpoints and diffs through guilds-code, and its harness through guilds-harness).
A generation is typed by its model source (generation/generate.ts): a key generation, whose snapshot has a model, runs the model loop, and a subscription generation, whose snapshot has none and names a harness, runs one turn of that harness (generation/harness-loop.ts). The set-up, the cancel settlement, the finish, and the events around either loop are shared. A subscription generation on no harness fails with harness.missing, and one whose agent picks repositories, or whose harness needs one (harnessNeedsRepository, coding/harnesses.ts: Cursor and Antigravity), with coding.repositories_missing or coding.repositories_gone, before the machine is woken. Its tools are narrowed as a key generation's are, and no model credential is resolved. Once the workspace check passes, guilds-harness check fails it with harness.off, harness.not_installed, harness.credential, or harness.check; then the repositories it picks are prepared. Its turn opens a grant on the HarnessMcpServer (generation/harness-mcp.ts), starts the CLI with the run's first row as its system prompt (in place of the CLI's own, or as rules beside it on a harness whose HARNESS_INFO prompt is rules), the server's URL and the grant's token, and the user messages since the run's last reply on stdin, polls every second, and keeps each poll's events as rows through events.commitMessage: one parser per CLI (generation/parse-claude-code.ts, generation/parse-codex.ts, generation/parse-cursor.ts, generation/parse-antigravity.ts) and the steps the turn's reader from HARNESS_TURN_STEPS makes of its events (generation/harness-rows.ts), the reply holding the turn's usage at cost_source: subscription. It keeps the session in metadata.harness_turn for the next generation to resume, stops the harness after the snapshot's max_turn_minutes, gives Claude Code the snapshot's max_steps as --max-turns (HARNESS_TAKES_MAX_TURNS), records generation.max_steps when it stops there, and ends with harness.start, harness.failed, harness.lost, harness.unresponsive, or harness.timed_out when it does not exit cleanly. A turn offered a tool whose harness never listed or called one on its grant (harnessNeverConnected) records harness.mcp_unconnected first, however it ends but a cancel. The server runs the harness's calls through ToolCalls.executeHarnessCall, one at a time per grant; a call past max_tool_calls or one that files a blocking issue asks the turn to stop, and the loop stops the harness and records generation.max_tool_calls or generation.blocked. A run's events.commitMessage appends one row at a time, so the poll's rows and the server's take the next sequence number each. The grant is revoked, once its running call is kept, before the turn's own calls without a result get theirs. The start, the poll, the stop, and the result are guilds-harness ops (toolbox/harness-ops.ts). Browser tools are offered when the run snapshot has browser: true (Runs). group_post, wake_after, and wake_cancel are offered when their binding is on. secret_request is offered only on direct runs. report_issue is always offered.
Tool output: custom filter, exact-value secret redaction, byte cap, then remaining_tool_calls: N. Official tool HTTP clients go through ADAPTER_PROXY_URL when it is set and direct otherwise.
HTTP and WebSocket
The React app (apps/web) is the black-box client. Route paths, JSON names, status codes, and stable detail strings are the contract.
Wire fixtures live in fixtures/compat/ and make compat-verify checks their digests. pnpm compat:digest <path> in apps/orchestrator (or pnpm --filter @guildsrun/orchestrator compat:digest <path> from the root) refreshes a digest after a deliberate change.
Every request passes the host and origin check in src/http/origin.ts. A request is served only for a loopback host or the host of PUBLIC_BASE_URL. A state-changing request or a WebSocket handshake that carries an Origin is served only when that origin is that host, the origin of PUBLIC_BASE_URL, or a loopback origin to a loopback host (SEC-15).
The sandbox proxies (/api/agents/:id/browser/vnc/* to noVNC, /api/agents/:id/cli/tty/* to ttyd) find the agent's machine from the agent id and the port from its slot. They preserve HTTP streaming, WebSocket binary/text forwarding, and the binary and tty subprotocols. The terminal proxy prepends the daemon's secret path segment upstream. They decode and strip content-encoding before streaming to the browser. A body that is not in the gzip or deflate encoding the daemon names answers 502.
A proxy never wakes a machine. A WebSocket whose target is refused closes with 1000 when the terminal's machine is stopped, 1013 for any other refusal, the Browser view's stopped machine included, and 1008 when the agent is refused. ttyd reconnects at once on any code but 1000, so a stopped machine leaves the terminal waiting for the operator's restart, which goes through POST /api/agents/:id/cli.
Client frames on either socket count as activity and restart the machine's idle timer, and the agent's Chrome timer, at most once every 30 seconds.
The MCP listener
A second listener, apart from the API's, serves the orchestrator's MCP server to subscription agents' harnesses (src/http/harness-mcp-routes.ts, built by buildHarnessMcpApp). It serves nothing else:
| Route | Answer |
|---|---|
POST /mcp/:agent_id | A JSON-RPC message of MCP's Streamable HTTP transport: a request is answered with its JSON response, a notification with 202 and no body |
GET, DELETE /mcp/:agent_id | 405, Allow: POST: no server stream and no session |
GET /health | { "status": "ok" }, with no check of the database |
| anything else | 404 |
A request is answered only with the bearer token of the running generation of the agent its path names (HarnessMcpServer, src/generation/harness-mcp.ts). Any other answers 401 with WWW-Authenticate: Bearer, whatever the reason. A body over 1 MiB answers 413, and one that is not a JSON-RPC message 400. Each error answers { "error": <the status's name> } and nothing more; a 5xx is logged. The listener passes no host or origin check: it is no page's API, and the token is its only gate.
Observability
Structured JSON logs on stdout:
- timestamp
- level
- run/guild/agent ids
- operation
- error type
- redacted message
- redacted stack
Prompts, model payloads, raw tool output, and secret values are not logged.
A request id comes from the X-Request-Id header when the caller sends one and is echoed on the response. The web app sends its tab's id on every API call. It reports uncaught errors, unhandled rejections, React render errors, and API calls that fail with a 5xx or on the network to POST /api/client-errors (the app deduplicates for 30 s and sends at most 10 a minute; the endpoint accepts 30 a minute per address). A report is its kind and message, with the stack, the page's href and the tab's request_id when it has them, each text; any other body is refused with a 422. Each report is logged with that request id.
Compose json-file rotation is max-size: 10m, max-file: 5. error-level events go to Sentry when SENTRY_DSN is set (instrument.ts loads before the rest of the process; boot logs sentry enabled or sentry disabled).
Tests
| Layer | Role |
|---|---|
test/unit | Domain without Docker; generation tests drive GenerationLoop against NotesStore and fakes |
test/integration | HTTP + Postgres: a database per test on the server named by R1_ADMIN_DATABASE_URL (default the Compose Postgres on 127.0.0.1:5432); http-r2, http-r3, http-r6 replay the recorded routes and SSE/WS fixtures |
test/contract | Live OpenSandbox, runtime image, coding harness, model, and Jev contracts, each skipped unless its RUN_*_CONTRACT=1 is set, with its key or image where it needs one |
fixtures/compat | Frozen HTTP, SSE, schema, crypto, and adapter contracts (manifest.json digests) |
pnpm test in apps/orchestrator runs the three layers through node:test with MODELS_DEV_URL set empty, so the model catalog is the bundled snapshot. test/helpers/ holds the shared fixtures, and the package exports some of them to an extension's tests.
make contract runs the OpenSandbox contracts (RUN_OPENSANDBOX_CONTRACT) and the model contract (RUN_MODEL_CONTRACT, with MODEL_CONTRACT_MODEL and MODEL_CONTRACT_API_KEY from .env).
The OpenSandbox contracts start their own server at the pinned commit. coding.test.ts runs two agents on one machine, each in its own home with its own Chrome, and checks the image's toolchain, in agent-runtime:0.4 (or CONTRACT_RUNTIME_IMAGE). It is skipped until the image is built.
The web app's tests (pnpm test:web, node:test over apps/web/src/**/*.test.ts) and the design-system tests (pnpm test:ui over packages/ui/src/**/*.test.ts) cover the operator app's pure models and the @guildsrun/ui library.
How to run all of it, with make verify, make check, the pre-push hook, and CI, is Development.