Languages: English · 中文 · Français
This is the high-level map of the Braincode codebase. Read this first; the deeper subjects each have their own document:
- Architecture — design intent, modes, Pi integration, configuration layout.
- Context management — how Brain and worker contexts are isolated and what crosses the boundary.
- Agent communication — handoff/result protocol, worker lifecycle, runtime events.
- Review and audit — review gates before and after execution, permission decisions, and session audit records.
- Development workflow — project-level phase contracts and the artifact-driven development loop.
- Project structure and plan — workspace layout, package responsibilities, implementation status.
- Visual style — UI/brand direction.
Braincode is a Bun-based monorepo for a coding-first AI agent that routes each part of a task to the model best suited for it. The user picks a Brain Model (a routing policy), not a single LLM. A run is one or more isolated worker agents whose structured results are merged by a primary agent.
User -> Ink TUI / CLI / config browser UI
-> Bun.serve (config + control)
-> Brain Model: choose roles, models, workers
-> isolated worker agents (handoff packets in, worker results out)
-> primary agent merges results
-> optional review worker
-> final answer
The repo separates concerns into four layers. Most contribution work touches one layer at a time.
| Layer | Packages | Responsibility |
|---|---|---|
| Interface | apps/cli (Ink TUI + CLI), apps/config-web |
User entrypoints. Renders Braincode product concepts; never talks to providers directly. |
| Product | packages/brain, packages/server, packages/config |
Brain Model selection, routing policy, local config service, project support discovery. |
| Agent | packages/agent-runtime, packages/context, packages/tools, packages/protocol |
Worker orchestration, context isolation, handoff/result packets, tool registry. |
| Provider | packages/llm, @earendil-works/pi-ai, @earendil-works/pi-agent-core |
Normalize provider models, agent loop, tool calling, sessions. |
Cross-layer rules:
- The interface layer must not call Pi directly. It goes through
agent-runtime. agent-runtimeis the only place that constructs PiAgentinstances.brainandcontextare pure: they describe policy and shape, never call providers.protocolis the shared shape vocabulary and stays dependency-light.
apps/
cli/ Bun CLI + Ink TUI (BrainPet, /plan, /team, ...)
config-web/ Tabbed browser config UI served by packages/server
packages/
shared/ Tiny utilities (debugLog, primitives). Do not dump code here.
protocol/ Wire shapes: ApiResult, ContextRef, AgentMessage.
config/ ~/.braincode/* schemas, atomic writes, session JSONL,
user/project support discovery (AGENTS.md, MCP, skills, hooks).
server/ Bun.serve on 127.0.0.1; typed API for the config UI.
llm/ BraincodeModel -> Pi Model mapping, API key resolution.
brain/ BrainModel, role catalog + prompts, planAgentRouting.
context/ BrainTaskContext, AgentTaskContext, HandoffPacket, WorkerResult,
project phase workflow contracts.
agent-runtime/ Orchestrator: builds RuntimePlan, runs workers, hooks, MCP, sessions.
tools/ Coding tool definitions + permissions.
Where things actually live (entry points worth bookmarking):
- Routing:
packages/brain/src/index.ts—planAgentRouting,agentRoleProfiles,agentRoleSystemPrompts. - Runtime entry/public exports:
packages/agent-runtime/src/index.ts—executePromptFromConfig,planRuntimeFromConfig, and package exports. - Plan building:
packages/agent-runtime/src/router.ts—buildRuntimePlan,routePromptWithBrain. - Model selection:
packages/agent-runtime/src/model-selection.ts—selectRuntimeModel,selectRuntimeModelCandidatesWithApiKey. - Worker execution:
packages/agent-runtime/src/workers.ts—runWorkerFromPlan,runSupportWorkers. - Context shapes:
packages/context/src/index.ts— every type that crosses the Brain/agent boundary. - Prompt references:
packages/agent-runtime/src/prompt-references.tsplus the runtime wrapper inindex.ts—expandPromptReferencesfor@pathand@@session. - Sessions:
packages/config/src/index.ts—appendSessionRecord,readSessionContext.
A non-interactive braincode run "<prompt>" produces this trace through the code:
apps/cliparses argv and callsexecutePromptFromConfigfromagent-runtime.SessionStartandUserPromptSubmithooks run. Either can block; both can add context.expandPromptReferencesresolves@<file>(inlined up to 64 KB) and@@<session-id>(compact session snapshot up to 24 KB).buildRuntimePlancallsplanAgentRoutingfor a deterministic baseline, then asks the configured router brain to refine it. The result is aRuntimePlan: primary role, worker list, model selection, mode, tool-execution mode.- Support workers run concurrently (capped by
brain.routing.maxParallelAgents). Each gets only the original user request plus its ownHandoffPacket.SubagentStart/SubagentStophooks fire around each worker. buildPrimaryPromptcomposes the primary agent's prompt from the original request plus structured worker summaries. The primary agent has access to MCP tools when the project declares them in.mcp.json.- If
requiresReviewis true and the primary is not itself the review role, a review worker runs with the primary's summary and worker results. Stophook runs. The final summary plus review notes is returned to the caller, andrun_endis appended to the session JSONL under~/.braincode/sessions/<id>.jsonl.
The interactive TUI variant follows the same path. The TUI also subscribes to AgentEvent from pi-agent-core and to WorkerLifecycleEvent from agent-runtime to drive the BrainPet status panel, live elapsed/token status, and collapsible transcript rows.
Modes are a Braincode-level concept; they bias the orchestration, not the model.
auto— default. Tools execute sequentially per agent. Routing is focused; the router can use up to the configured worker/concurrency limit and up to 6 todos.radical— autonomous. Tools execute in parallel within an agent. routeBrain is instructed to decompose more broadly, use specialist support earlier, plan up to 8 todos, and use at least 4 routed workers / 4-way support concurrency when dependencies allow. In the TUI, default local tools are exposed even if user-level tool toggles are disabled, and tool calls are auto-approved so the TUI does not stop for Ask User prompts.
getModePolicy in packages/brain is the source of truth.
A Brain Model is a ModelPolicy per role plus routing/context defaults. The role catalog is defined in one place — agentRoleProfiles + agentRoleSystemPrompts in packages/brain — so the router prompt, defaults, and runtime system prompts never drift apart. routeBrain sees the full role catalog plus role-policy capability summaries, then chooses the primary role, workers, todos, and dependencies. Execution models are resolved from each selected role's own modelId -> fallbackModelIds chain; routeBrain must not rebind a role to the planner model or to another role's model. For image input, it should choose roles whose own chains can receive images.
Routed roles (the ones a worker can be), v0.2.0:
frontend · backend · designer · dba · devops · security · qa · review · summarize · oracle · librarian · rush
Removed in v0.2.0: coding (subsumed by frontend/backend), fastReply (subsumed by rush), research (subsumed by librarian). The catalog is shorter on purpose — each remaining role maps to a meaningfully different model-routing decision.
Non-routed roles:
routeBrain— orchestrator-only; selects roles, never solves tasks.pet— read-only BrainPet status reporter for the TUI.
When adding a role, update routedAgentRoles, agentRoleProfiles, agentRoleSystemPrompts, and BrainModel.roles together — they are deliberately keyed by the same union.
Everything user-specific lives under ~/.braincode/:
~/.braincode/
AGENTS.md durable user-global instructions injected into prompts
settings.json execution mode, default brain id, feature flags
auth.json provider keys (kept out of model prompts)
brains.json Brain Models
models.json BraincodeModel catalog for text, vision, and image-generation models
tools.json tool toggles
mcp.json user-global MCP server declarations (metadata only in prompts)
hooks.json user-level lifecycle hooks
skills/<id>/SKILL.md user-global skills
sessions/ per-session JSONL transcripts of orchestration events
logs/, cache/ runtime byproducts
braincode config serves a tabbed Web UI on localhost. Models are the first tab; usage statistics have a dedicated tab with Recharts summaries and click-through details by model, role, and runtime phase. OAuth-backed subscriptions such as Claude Pro/Max, ChatGPT Plus/Pro Codex, and GitHub Copilot appear as model-catalog providers once authenticated, so models can be added without duplicating API keys. GitHub Copilot OAuth defaults to public github.com; GitHub Enterprise domain input is only shown when explicitly enabled. ChatGPT subscription-backed model calls use a web-backed endpoint and can be rejected by browser or Cloudflare checks, so Braincode reports that separately from API-key auth failures and labels ChatGPT subscription OAuth as not recommended for reliable calls. Users who still want subscription-backed ChatGPT models should try ClIProxy API or another compatible proxy.
The Models tab is the single model registry for text, vision, and image-generation models. Its add-model flow has three explicit sources: the Pi provider catalog, a user provider /models endpoint, or manual compatible API metadata. Catalog entries never bundle credentials; runtime credentials are resolved by provider id from ~/.braincode/auth.json, including OAuth-backed subscription tokens. User-added providers declare an OpenAI-compatible, Anthropic-compatible, or OpenAI-compatible Images API, can load available models from /models when the provider supports it, and can also accept manual model ids. The imageMaker role is still only for raster image generation or editing, but it now selects an openai-images model from models.json like other roles select their own configured model entries. Vision-capable text models remain ordinary models with image input support; they are not image generation models.
Project-local support files live next to code:
<repo>/
AGENTS.md durable project instructions injected into prompts
.mcp.json project MCP server declarations (metadata only in prompts)
.braincode/checks.json optional project check policy overrides
.agents/hooks.json project lifecycle hooks
.agents/skills/<id>/SKILL.md project-local skills
packages/config owns discovery and parsing. agent-runtime decides what becomes prompt text vs. a ContextRef.
Project-level planning should use Development workflow for non-trivial changes that span multiple runs. Runtime AgentRoutingPlan records are for one prompt; phase contracts are for durable project progress and should remain readable by future sessions without copying private worker transcripts.
- Hooks are command handlers keyed by event name. Supported runtime events:
SessionStart,UserPromptSubmit,SubagentStart,SubagentStop,Stop. Handlers must settrusted: trueto run today (there is no review UI yet). SeerunConfiguredHooksinagent-runtime. - MCP servers are connected per run via
McpToolHub. The hub returns ready-to-use PiAgentTools; servers that fail or are skipped are reported back throughonMcpReport.
bun install
bun run check # typecheck across the workspace
bun test # unit tests (config, brain, llm, context, agent-runtime)
bun run braincode -- run --dry-run "<prompt>" # routeBrain plan preview
bun run braincode -- run --dry-run --heuristic "<prompt>" # no-provider diagnostic
bun run braincode -- run "<prompt>" # real run
bun run braincode # Ink TUI
bun run config # config browser UITest placement follows ownership. Put narrow unit tests next to their source module, for example packages/<name>/src/<module>.test.ts or apps/<name>/src/<module>.test.tsx. Put package-level integration tests and public-entrypoint tests in <workspace>/test/*.test.ts, such as packages/agent-runtime/test/runtime-integration.test.ts. Reserve a root tests/ tree for future cross-workspace or end-to-end suites, and keep fixtures under the nearest test/fixtures/ directory unless they are benchmark fixtures under benchmarks/fixtures/.
Keep new logic close to the package it belongs to; resist growing packages/shared.
- Working on routing or roles? Start with agent-communication.md, then
packages/brain. - Touching anything that crosses agents? Read context-management.md before editing prompts.
- Reshaping infra or packages? See project-structure.md for the intended layout and non-goals.