Skip to content
brain.GitHub
Developer docs OPEN SOURCE
Runtime reference

Host configuration

Reference for brain.json fields, authentication tokens, harnesses, model providers, tools, resource limits, and external persistence.

Brain reads its host configuration from a JSON file passed with -config (defaults to brain.json). You can validate the configuration file and all referenced environment variables without starting the HTTP server by passing -check:

go run ./services/brain/cmd/brain -config brain.json -check

-stdio ties the server lifetime to its parent's stdin pipe. After initialization, the server writes one JSON line containing its listening url to stdout; logs remain on stderr. Closing stdin triggers graceful shutdown. In this mode the configured listen address may use port 0; Brain uses the assigned address as its public URL. The brainserver Node package uses this mode to own its child process without reserving a port in advance.

The stock executable accepts -tool-providers FILE for application-installed integrations. The Node package creates this private registration file from the constructor's tool list; credential values are environment references. Integration selection and private session overrides use the existing session binding contract.

go run ./services/brain/cmd/brain -config brain.json -check

Configuration files are limited to 4 MiB. Unknown JSON fields and trailing JSON data are rejected at startup. Relative paths (such as data_dir or persistence.directory) resolve from the working directory of the Brain process.

Distributed service configuration

The Docker composition uses four JSON files in deploy/docker. Brain's services object selects distributed execution; its harnesses map must contain the Pi profile. Service-call authentication uses the configured environment variable. Secret values do not belong in JSON files.

Brain service fieldTypeRequiredDefaultDescription
storage, tools, sandboxstringYes—Private HTTP base URLs.
token_envstringYes—Environment variable containing the shared service token, at least 32 bytes.
ownerstringYes—Platform-assigned Brain owner.
epochintegerYes—Positive platform-assigned ownership epoch.
idle_ttl_secondsintegerNo300Release an idle Pi environment after this duration; settled state remains in Storage.

Storage reads these fields:

FieldTypeRequiredDefaultDescription
listenstringNo:8081Private listener.
data_dirstringYes—Exclusive local cache volume.
credential_keysobjectNonullStorage encryption keyring for persisted credentials; see Private credential keys.
token_envstringNoBRAIN_SERVICE_TOKENService token environment variable.
memory_bytesintegerNo134217728Object memory budget, reduced under memory pressure.
disk_bytesintegerNo4294967296Object disk budget. Unsynced data is pinned.
metadata_disk_bytesintegerNo67108864Separate metadata disk budget; no metadata content memory cache.
memory_ttl_secondsintegerNo300Object memory TTL.
disk_ttl_secondsintegerNo86400Clean local-copy TTL; not permanent retention.
sync_secondsintegerNo5Background sync interval; not an outage recovery-point guarantee.
objects, metadataobjectYes—External backend configuration.

Each external backend implements the same get, conditional put, delete and paginated list contract. Configure each objects/metadata entry with:

kindRequired configurationOptional configuration
filesystempath—
sqlitepath—
s3, r2bucket, regionendpoint, prefix, path_style, access_key_env, secret_key_env
dynamodbtable, regionendpoint, access_key_env, secret_key_env
postgres, supabasedsn_env—

R2 uses its S3 endpoint and region auto. Supabase uses a PostgreSQL connection string. DynamoDB requires a table with string partition key k. Database adapters create their own object table. Cloud identity can use the AWS SDK credential chain when explicit key variables are omitted. The memory adapter is used for caches and tests, not external persistence configuration.

Storage reserves 256 MiB of filesystem free space before writes and evicts committed copies under pressure. Data objects use 64 KiB chunks. Metadata publication follows referenced object commitment; conditional head writes reject conflicts.

Tools reads listen, storage, sandbox, token_env, tokens, tools, executors and optional providers_file. The provider file follows the supplied integrations' registry format. Sandbox reads listen, instance, token_env, capacity, max_archive_bytes and profiles; each approved profile specifies image, network, memory_bytes, string cpus, pids, workspace_bytes and lifetime_seconds.

The configuration sections below also describe the embedded application composition. Its persistence and process command fields are replaced by service URLs and Sandbox profiles in distributed composition.

Minimal example

{
  "listen": "127.0.0.1:8080",
  "public_url": "http://127.0.0.1:8080",
  "data_dir": ".brain",
  "tokens": [
    { "token_env": "BRAIN_API_KEY", "tenant": "local", "manage": true }
  ],
  "harnesses": {
    "pi": { "command": ["node", "runtimes/pi/dist/main.js"] }
  },
  "providers": {
    "openai": { "api_key_env": "OPENAI_API_KEY" }
  },
  "tools": []
}

Top-level fields

media_origins is an optional array of exact HTTP/HTTPS origins, empty by default. Only images from those origins are admitted. Native runners accept PNG, JPEG, WebP and GIF responses, reject redirects, and limit one message's downloaded images to 20 MiB in total. A message accepts up to 64 image references; each URL is at most 4096 bytes. Image bytes enter native context and its checkpoints.

FieldTypeDefaultDescription
listenstring"127.0.0.1:8080"TCP host:port address to bind. Validated with net.SplitHostPort.
public_urlstring"http://127.0.0.1:8080"Base http or https URL passed as brain_url to tools with inspect_session: true. Must not contain credentials, query parameters, or fragments.
data_dirstring".brain"Local directory for metadata.sqlite and per-session directories (sessions/<id>/). Must be non-empty.
tokensToken[]RequiredNon-empty array of API token grants (see tokens).
harnessesRecord<string, Runner>RequiredMap of harness name (1–64 characters) to child process command (see harnesses). At least one harness is required.
providersRecord<string, Provider>{}Map of model provider prefix to credentials and optional transport overrides (see providers).
toolsBinding[][]Array of external HTTP, SSE, or MCP tool bindings (see tools).
host_poolobject{}Optional aggregate host, startup and active-turn ceilings across installed process factories.
limitsLimitsSee belowIn-memory, disk, queue, and SSE subscriber bounds (see limits).
persistenceSettingsnullOptional background checkpoint storage and session index settings (see persistence).
storage_keysobjectnullEmbedded Storage encryption keys for persisted model and provider credentials.

Authentication tokens (tokens)

Each entry in tokens binds an environment variable containing a bearer secret to a tenant and permission scope. Duplicate token values across entries are rejected at startup. See Authentication & tenants.

FieldTypeRequiredDefaultDescription
token_envstringYes—Name of the environment variable holding the bearer token. The environment variable must be set at startup and contain at least 24 bytes.
tenantstringYes—Tenant identifier (1–128 bytes). All operations using this token are isolated to this tenant.
sessionstringNo""Optional 32-character hex session ID. When set, the token can only access that single session and cannot create new sessions.
managebooleanNofalsePermits management operations (POST /sessions, resume, close, flush, and restore).
read_onlybooleanNofalseRestricts the credential to GET requests (list, get, events, sync, and catalog).

Harnesses (harnesses)

Each key in harnesses is the harness name clients pass in POST /sessions (for example, "pi").

FieldTypeRequiredDescription
commandstring[]YesNon-empty command and arguments used to spawn the harness child process (for example, ["node", "runtimes/pi/dist/main.js"]). command[0] must be non-empty.
kindstringNoNative adapter kind (pi, codex, or opencode); defaults to the profile name. Set it when the profile has a custom name.
pluginsPiPlugin[]NoTrusted Pi plugin definitions: name (web-access, subagents, or mcp), optional upstream config, and optional selected tools. Plugin profiles require max_shared: 1 and max_active_turns: 1; these are their defaults.
max_sharedintegerNoSession attachments per host; default 8, range 1–1024.
max_active_turnsintegerNoSimultaneous turns per host; defaults to max_shared, range 1–max_shared.
max_hostsintegerNoMaximum live hosts for this harness; default 16, minimum 1.
max_startingintegerNoConcurrent session opens; default 4, minimum 1.

Hosts use private working and home directories. Linux process guardians and Windows Job Objects own descendant lifetimes. Idle session eviction detaches only that session; the last detach closes the host. Global limits.active also bounds resident native session attachments.

Aggregate host pool

host_pool adds optional ceilings across installed process factories. Omitted or zero values impose no additional aggregate restriction. Adapter-specific host occupancy, active-turn, host-count, and startup settings still apply. Capacity exhaustion rejects acquisition or dispatch with overloaded; Brain does not switch harnesses or replay tools.

harnesses.<name>.credential_hosts partitions a process factory by a private digest of its provider credential context. It defaults to false; the installed codex policy enables it because native authentication is process-scoped. Keys are not pool labels. In application code, install process factories with the application's pool before first use; an already-opened factory cannot be transferred to another server.

FieldTypeRequiredDefaultDescription
hostsintegerNo0Maximum live native hosts across factories.
startingintegerNo0Maximum native hosts awaiting their first attachment's readiness.
active_turnsintegerNo0Maximum turns dispatched across native hosts.

Values must be non-negative. In Go applications, supply Options.HostPool from brain.NewHostPool(brain.HostPoolLimits{...}) instead of declaring host_pool in configuration. Aggregate limits require process factories; an opaque custom factory owns its own host lifecycle. Pool shutdown refuses new acquisitions and reaps owned process trees after sessions drain.

Private credential keys

{"storage_keys":{"active":"key-2026","keys":{"key-2026":"STORAGE_ENCRYPTION_KEY"}}}

active selects a key ID from keys. Each value names an environment variable containing a base64-encoded 32-byte AES key. Every configured key must be available at startup. Keep retired keys available while retained checkpoints still reference them. Application code may instead supply Options.StorageKeys implementing storage.Keys. Storage encrypts credentials at database and checkpoint writes and decrypts them at reads. In distributed deployments, configure credential_keys in the Storage service; Brain rejects embedded storage keys in distributed mode. Brain and Tools receive private values through Storage interfaces, with no cipher calls or separate encryption keys.

Private overrides are authenticated encrypted SQL records, bound to tenant, session, and alias. Creation rejects overrides without configured keys. Public JSON never contains ciphertext or plaintext values. Credential administration covers rotation, revocation, and checkpoint retention.

Model providers (providers)

Each key in providers matches the provider prefix in config.model (provider/model). A configured api_key_env must name a non-empty environment variable at startup. Omit it to require a private session credential. See Models & providers.

FieldTypeRequiredDefaultDescription
api_key_envstringNo""Environment variable containing the startup default API key. Passed to the harness runner via stdio open options when no session override is supplied.
base_urlstringNo""Optional http or https base URL override for proxies or compatible endpoints (must not include user credentials).
apistringNo""Optional transport override in the Pi model registry (for example, "openai-completions").

External tools (tools)

Each element in tools registers one tool that sessions belonging to authorized tenants can enable in config.tools. See External tools and MCP tools for protocol and discovery details.

FieldTypeRequiredDefaultDescription
namestringYes—Unique tool name matching ^[a-zA-Z][a-zA-Z0-9_]{0,63}$.
descriptionstringYes—Non-empty description shown to the model.
input_schemaobjectYes—JSON Schema for tool arguments. External $ref URLs are rejected.
output_schemaobjectNonullJSON Schema for successful structured_content. Error results bypass the success schema, while content and size limits still apply.
urlstringYes—Target http or https endpoint URL (no credentials or URL fragments).
tenantsstring[]Yes—Non-empty list of tenant IDs permitted to see and enable this tool.
token_envstringNo""Optional environment variable holding the bearer token Brain sends in Authorization: Bearer <token>. Must be non-empty at startup when specified.
transportstringNo"http", or "mcp" when mcp_tool is setTransport registered at startup. Unknown names fail config validation. Built-ins are http (JSON/SSE) and mcp.
mcp_toolstringNo""Remote MCP tool name. When set, Brain calls url using the MCP Streamable HTTP transport instead of the native HTTP/SSE tool protocol.
timeout_secondsintegerNo300Per-call deadline in seconds. Allowed range: 1–86400 (24 hours).
max_output_bytesintegerNo1048576Maximum response body size in bytes. Allowed range: 1–2097152 (2 MiB).
inspect_sessionbooleanNofalseWhen true, Brain issues a short-lived, read-only session token (inspection_token) and brain_url for the duration of each call. Cannot be combined with mcp_tool.

Resource limits (limits)

Every field is optional. Fields you omit keep the defaults below, so you can override only the limits you need. Brain validates the combined values at startup.

FieldTypeDefaultAllowed rangeDescription
activeinteger16>= 1Maximum concurrent running turns and resident native session attachments across the server. Hosts may share several attachments.
loadedinteger1024>= activeMaximum sessions held in memory at once. Idle unreferenced sessions are evicted when full.
queueinteger161–1024Maximum queued user.message inputs per session.
input_bytesinteger655361–1048576 (1 MiB)Maximum byte length of user.message text or session instructions.
session_bytesinteger1073741824>= 16777216 (16 MiB)Maximum local event log (events.jsonl) and checkpoint artifact size per session (default 1 GiB).
subscribersinteger128>= 1Maximum concurrent SSE connections across the server.
subscriber_eventsinteger128>= 1Maximum buffered live events per SSE subscriber before Brain disconnects the slow client.
subscriber_bytesinteger2097152>= 4096Maximum buffered live event bytes per SSE subscriber before disconnect (default 2 MiB; each event accounts for len(data) + 256 bytes).

External persistence (persistence)

Configure persistence to upload immutable 64 KiB transcript blocks and native checkpoints in the background. See Persistence & recovery for provider setup and handoff steps.

FieldTypeRequiredDefaultDescription
providerstringYes—Storage backend: "filesystem", "s3", "r2", or "gcs".
directorystringWhen filesystem""Target directory on disk for "filesystem" checkpoints.
bucketstringWhen s3, r2, or gcs""Object storage bucket name.
regionstringNo"auto" for r2AWS/S3 region. Rejected when provider is "gcs".
endpointstringWhen r2""Custom http or https S3/R2 endpoint URL (enables path-style addressing). Rejected when provider is "gcs".
prefixstringNo""Optional relative object key prefix (must not start with /, contain \, or traverse ..).
access_key_envstringWhen r2""Environment variable holding the S3/R2 access key ID. Optional for "s3" (which falls back to the default AWS credential chain); rejected for "gcs". Both access_key_env and secret_key_env must be set together.
secret_key_envstringWhen r2""Environment variable holding the S3/R2 secret access key. Rejected for "gcs".
postgres_envstringNo""Optional environment variable containing a PostgreSQL connection string (postgres://...) for cross-instance session discovery. Must be non-empty at startup when specified.
interval_secondsintegerNo5Background sync scan interval in seconds (1–3600).
queueintegerNo128Maximum pending dirty sessions in the background sync queue (1–10000). When full, Brain rejects new writes with 429 overloaded and marks /health/ready as 503.

On this page