Help us shape the future of Go! Take the 2026 Go Developer Survey

brain

package module
v0.0.0-...-cc1069a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 20 Imported by: 0

README

              ______ ______ _______ _______ _______
  ▄████▄     |   __ \   __ \   _   |_     _|    |  |
▄██▄██▄██▄   |   __ <      <       |_|   |_|       |
  ▀▀  ▀▀     |______/___|__|___|___|_______|__|____|

A minimal and extensible agent server for building agent applications

Quickstart · Docs · API reference · Examples · Roadmap

Brain is a single application you deploy as a service to run the agents behind your products. It's an open-source alternative to Claude Managed Agents and the OpenAI Agents SDK, running on your own infrastructure with the models you choose.

Brain gives you session-oriented primitives for building agents. Your application starts sessions, streams what the agent does, and connects tools from application code and services. Brain runs the agent loop and records each session's history, so you can replay a session or recover it after a failure.

  • Sessions: agent conversations that outlive connections and restarts.
  • Events: an ordered record of what the agent does, streamed live or replayed.
  • Harnesses: pluggable agent loops that drive the model and manage context.
  • Tools: capabilities implemented in your application, clients, or services.
  • Checkpoints: portable session state for recovering and moving sessions.
import { Pi, BrainServer, Model } from "brainserver";

const brain = new BrainServer();
await brain.start();
try {
  const session = await brain.create({ harness: Pi(), model: Model("openai/gpt-4.1-mini"), tools: [] });
  const input = await brain.send(session.id, { type: "user.message", text: "Say hello." });
  for await (const event of brain.observe(session.id)) {
    if (event.type === "assistant.message") console.log(event.data.text);
    if (event.input_id !== input.id) continue;
    if (event.type === "session.error") throw new Error(event.data.message);
    if (event.type === "session.status" && event.data.status === "idle") break;
  }
} finally {
  await brain.stop();
}

Save this as agent.mjs and follow the setup below.

Why Brain

  • Choose where tools run. Compose functions into your application, attach client functions, or connect services in any language.
  • Decide what the agent can do. The model sees exactly the tools you enable for each session.
  • Reconnect at any time. Sessions keep running when clients disconnect and survive server restarts, so any client can reconnect and continue from the last event it read.
  • Move sessions between servers. Checkpoints let another server recover a session after a failure or take it over in a planned handoff.
  • Isolate every customer. Keep each customer's sessions and tools separate, and give each client only the access it needs.
  • Run it yourself. Brain is open source and self-hosted, with structured logs and OpenTelemetry traces and metrics.

Get started

You need Node.js 24+ and an OpenAI API key for the example above.

  1. Install Brain. The package includes the server and harness runtimes:

    npm install brainserver
    
  2. Run your script. Set the provider key, then start the example:

    export OPENAI_API_KEY="your-provider-key"
    node agent.mjs
    

The Quickstart includes PowerShell setup. For a separately deployed server, use the container image and connect with @aexhq/brain or aex-brain.

Documentation

I want to… Read
Run my first session Quickstart
Understand how Brain runs a session Architecture
Stream events, interrupt turns, and resume sessions Session lifecycle
Write a tool service Distributed tools
Connect a remote MCP server MCP tools
Issue tokens and isolate customers Authentication
Back up sessions and move them between servers Persistence & recovery
Deploy and monitor Brain Operations & observability
Call Brain from my backend TypeScript SDK or Python SDK
Look up routes and config fields HTTP API and Host configuration
See what's coming next Roadmap

Build with a coding agent

Give your coding agent Brain's docs as plain text: llms-full.txt has every page in one file, and llms.txt lists the pages.

Contributing

Install the dependencies and run every local check before you open a pull request. The checks need Go 1.26+, Node.js 24+, and Python 3.11+.

node scripts/setup.mjs
node scripts/check.mjs

Development & verification covers what the checks run, how CI publishes releases, and how to preview the docs.

License

Brain is released under the MIT License.

Docs · Roadmap · Architecture · License · Issues

Documentation

Overview

Package brain composes an agent session server with application-owned harnesses and tools. Session requests select installed implementations; they never install code.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Validate

func Validate(o Options) error

Types

type BindingContext

type BindingContext = tools.BindingContext

type Call

type Call = core.Call

type Config

type Config = config.Config

func DefaultConfig

func DefaultConfig() Config

func LoadConfig

func LoadConfig(file string) (Config, error)

type Content

type Content = core.Content

type CreateSession

type CreateSession = core.CreateSession

type CredentialInput

type CredentialInput = core.CredentialInput

type CredentialKeys

type CredentialKeys = credentials.Keys

type Event

type Event = core.Event

type Grant

type Grant = core.Grant

type Handler

type Handler = tools.Handler

type Harness

type Harness = harness.Runner

type HarnessFactory

type HarnessFactory = harness.Factory

type HarnessOptions

type HarnessOptions = harness.Options

type HarnessProvider

type HarnessProvider = harness.Provider

type HostPool

type HostPool = harness.HostPool

func NewHostPool

func NewHostPool(limits HostPoolLimits) (*HostPool, error)

type HostPoolLimits

type HostPoolLimits = harness.PoolLimits

type KeyConfig

type KeyConfig = config.KeyConfig

type Limits

type Limits = config.Limits

type ManagedTool

type ManagedTool = tools.Binding

func NewTool

func NewTool(descriptor Tool, tenants []string, run Handler) ManagedTool

NewTool declares an ordinary application function using the common tool contract. Tenants explicitly selects its authority; an empty list fails startup validation.

type Media

type Media = core.Media

type Message

type Message = core.Text

type ModelContext

type ModelContext struct {
	Tenant, Session, Model string
	Credential             *ModelCredential
}

ModelContext carries authenticated scope, never model-supplied arguments.

type ModelCredential

type ModelCredential = core.ModelCredential

func APIKey

func APIKey(value string) *ModelCredential

func CredentialReference

func CredentialReference(value string) *ModelCredential

type ModelProvider

type ModelProvider struct {
	APIKey, BaseURL, API string
	Authorize            func(context.Context, ModelContext) error
	Resolve              func(context.Context, ModelContext) (string, error)
}

ModelProvider installs endpoint policy and an optional startup key. Authorize applies to defaults and overrides on admission and before each turn. Resolve resolves references in the supplied tenant scope; errors never select defaults.

func NewModelProvider

func NewModelProvider(apiKey string) ModelProvider

type ModelRequest

type ModelRequest = core.ModelRequest

type ModelUsage

type ModelUsage = core.ModelUsage

type NativeFile

type NativeFile = core.NativeFile

type Options

type Options struct {
	Config       Config
	Models       map[string]ModelProvider
	HostPool     *HostPool
	Tools        []ManagedTool
	Authenticate func(*http.Request) (Grant, bool)
	Harnesses    map[string]HarnessFactory
	Providers    map[string]ToolProvider
	Keys         CredentialKeys
	Logger       *slog.Logger
}

type Persistence

type Persistence = persistence.Settings

type PiPlugin

type PiPlugin = harness.PiPlugin

type ProcessConfig

type ProcessConfig = config.Runner

type ProcessFactory

type ProcessFactory = harness.ProcessFactory

func Codex

func Codex(command []string) *ProcessFactory

func OpenCode

func OpenCode(command []string) *ProcessFactory

type ProviderUnavailable

type ProviderUnavailable = tools.Unavailable

type Result

type Result = core.Result

func ToolError

func ToolError(message string, unknown bool) Result

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server owns opened resources. Call Shutdown even when serving through Handler.

func New

func New(ctx context.Context, o Options) (_ *Server, err error)

func (*Server) DeleteSession

func (s *Server) DeleteSession(ctx context.Context, tenant, id string) error

func (*Server) Handler

func (s *Server) Handler() http.Handler

func (*Server) ReadEvents

func (s *Server) ReadEvents(ctx context.Context, tenant, id, after string, limit int) ([]Event, error)

func (*Server) ReadSession

func (s *Server) ReadSession(ctx context.Context, tenant, id string) (Session, error)

func (*Server) RevokeCredential

func (s *Server) RevokeCredential(ctx context.Context, tenant, sessionID, binding string) error

func (*Server) RevokeModelCredential

func (s *Server) RevokeModelCredential(ctx context.Context, tenant, sessionID string) error

RevokeModelCredential retains a recovery tombstone like tool revocation.

func (*Server) RotateCredentials

func (s *Server) RotateCredentials(ctx context.Context, tenant, sessionID string) error

RotateCredentials re-encrypts live overrides using the application's active key. Keep old keys until every retained checkpoint that needs them has expired.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, listener net.Listener) error

Serve takes ownership of the listener and shuts down when ctx is cancelled.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

type Session

type Session = core.Session

type SessionConfig

type SessionConfig = core.Config

type Token

type Token = config.Token

type Tool

type Tool = core.Tool

type ToolBinding

type ToolBinding = core.ToolBinding

type ToolProvider

type ToolProvider = tools.Provider

type ToolRequest

type ToolRequest = tools.Request

type ToolScope

type ToolScope = core.ToolScope

Directories

Path Synopsis
cmd
brain command
generate command
Command generate derives wire declarations and OpenAPI from Go types/routes.
Command generate derives wire declarations and OpenAPI from Go types/routes.
mcp-tools command
mcp-tools discovers selected remote tools and prints static Brain bindings.
mcp-tools discovers selected remote tools and prints static Brain bindings.
resource-tools command
examples
application command
A Brain application with a trusted, session-bound function provider.
A Brain application with a trusted, session-bound function provider.
platforms/sessiontools
Package sessiontools is an example platform-owned session inspection policy.
Package sessiontools is an example platform-owned session inspection policy.
tools command
A separate local tool service.
A separate local tool service.
Package integrations supplies optional managed provider constructors.
Package integrations supplies optional managed provider constructors.
internal
api
Package api exposes authenticated sessions and event streams over HTTP.
Package api exposes authenticated sessions and event streams over HTTP.
config
Package config validates host-owned configuration before opening a listener.
Package config validates host-owned configuration before opening a listener.
core
Package core contains the public session and tool data shared by adapters.
Package core contains the public session and tool data shared by adapters.
credentials
Package credentials encrypts private binding values before they reach storage.
Package credentials encrypts private binding values before they reach storage.
harness
Package harness isolates native agent loops from the Brain coordinator.
Package harness isolates native agent loops from the Brain coordinator.
persistence
Package persistence publishes immutable checkpoints outside the hot path.
Package persistence publishes immutable checkpoints outside the hot path.
session
Package session coordinates local sessions without implementing an agent loop.
Package session coordinates local sessions without implementing an agent loop.
store
Package store owns local metadata and append-only event files.
Package store owns local metadata and append-only event files.
telemetry
Package telemetry configures bounded OpenTelemetry exporters and instruments.
Package telemetry configures bounded OpenTelemetry exporters and instruments.
tools
Package tools validates and transports calls.
Package tools validates and transports calls.
toolservice
Package toolservice implements optional external tools, outside the runtime.
Package toolservice implements optional external tools, outside the runtime.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL