brain

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MethodGetBrain     = "get_brain"
	MethodUpdateStatus = "update_status"
	MethodSendMessage  = "send_message"
	MethodRemoveAgent  = "remove_agent"
	MethodPing         = "ping"

	// Tier 3 methods — relayed to the TUI via action channel.
	MethodCreateInstance = "create_instance"
	MethodInjectMessage  = "inject_message"
	MethodPauseInstance  = "pause_instance"
	MethodResumeInstance = "resume_instance"
	MethodKillInstance   = "kill_instance"
	MethodDefineWorkflow = "define_workflow"
	MethodCompleteTask   = "complete_task"
	MethodGetWorkflow    = "get_workflow"
	// Event subscription methods.
	MethodSubscribe   = "subscribe"
	MethodPollEvents  = "poll_events"
	MethodUnsubscribe = "unsubscribe"
)

IPC method constants shared between client and server.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActionRequest

type ActionRequest struct {
	Type       ActionType
	Params     map[string]any
	ResponseCh chan ActionResponse
}

ActionRequest is sent from the brain server to the TUI via a channel. The server blocks on ResponseCh until the TUI processes the action.

type ActionResponse

type ActionResponse struct {
	OK    bool           `json:"ok"`
	Data  map[string]any `json:"data,omitempty"`
	Error string         `json:"error,omitempty"`
}

ActionResponse is sent back from the TUI to the brain server.

type ActionType

type ActionType string

ActionType identifies the kind of action request.

const (
	ActionCreateInstance ActionType = "create_instance"
	ActionInjectMessage  ActionType = "inject_message"
	ActionPauseInstance  ActionType = "pause_instance"
	ActionResumeInstance ActionType = "resume_instance"
	ActionKillInstance   ActionType = "kill_instance"
)

type AgentStatus

type AgentStatus struct {
	Feature   string   `json:"feature"`
	Files     []string `json:"files"`
	Role      string   `json:"role,omitempty"`
	UpdatedAt string   `json:"updated_at"`
}

AgentStatus tracks what an agent is currently working on.

type BrainMessage

type BrainMessage struct {
	From      string `json:"from"`
	To        string `json:"to"`
	Content   string `json:"content"`
	Timestamp string `json:"timestamp"`
}

BrainMessage is a directed message between agents.

type BrainState

type BrainState struct {
	Agents   map[string]*AgentStatus `json:"agents"`
	Messages []BrainMessage          `json:"messages"`
}

BrainState is the coordination state for a single repository.

type Client

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

Client connects to a brain server over a Unix domain socket.

func NewClient

func NewClient(socketPath string) *Client

NewClient creates a new socket client.

func (*Client) CompleteTask

func (c *Client) CompleteTask(repoPath, instanceID, taskID, status, errMsg string) (*WorkflowResult, error)

CompleteTask marks a workflow task as done or failed. Uses a longer timeout because the server may trigger dependent task instances.

func (*Client) CreateInstance

func (c *Client) CreateInstance(repoPath, instanceID string, params CreateInstanceParams) (*CreateInstanceResult, error)

CreateInstance requests the TUI to spawn a new agent instance.

func (*Client) DefineWorkflow

func (c *Client) DefineWorkflow(repoPath, instanceID string, tasks []*WorkflowTask) (*WorkflowResult, error)

DefineWorkflow creates a workflow DAG for a repo. Uses a long timeout because the server may auto-spawn instances sequentially.

func (*Client) GetBrain

func (c *Client) GetBrain(repoPath, instanceID string) (*BrainState, error)

GetBrain retrieves the coordination state for a repo, filtered for the requesting agent.

func (*Client) GetWorkflow

func (c *Client) GetWorkflow(repoPath, instanceID string) (*Workflow, error)

GetWorkflow retrieves the current workflow DAG for a repo.

func (*Client) InjectMessage

func (c *Client) InjectMessage(repoPath, instanceID string, params InjectMessageParams) error

InjectMessage requests the TUI to inject text directly into an agent's terminal.

func (*Client) KillInstance

func (c *Client) KillInstance(repoPath, instanceID, target string) error

KillInstance requests the TUI to terminate an agent instance.

func (*Client) PauseInstance

func (c *Client) PauseInstance(repoPath, instanceID, target string) error

PauseInstance requests the TUI to pause an agent instance.

func (*Client) Ping

func (c *Client) Ping() error

Ping checks connectivity to the brain server.

func (*Client) PollEvents

func (c *Client) PollEvents(subscriberID string, timeoutSec int) ([]Event, error)

PollEvents long-polls for events on the given subscription.

func (*Client) RemoveAgent

func (c *Client) RemoveAgent(repoPath, instanceID string) error

RemoveAgent removes an agent from the brain state.

func (*Client) ResumeInstance

func (c *Client) ResumeInstance(repoPath, instanceID, target string) error

ResumeInstance requests the TUI to resume a paused agent instance.

func (*Client) SendMessage

func (c *Client) SendMessage(repoPath, from, to, content string) error

SendMessage sends a message from one agent to another (or broadcast if to is empty).

func (*Client) Subscribe

func (c *Client) Subscribe(repoPath string, filter EventFilter) (string, error)

Subscribe creates an event subscription with the given filter.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(subscriberID string) error

Unsubscribe removes an event subscription.

func (*Client) UpdateStatus

func (c *Client) UpdateStatus(repoPath, instanceID, feature string, files []string) (*UpdateStatusResult, error)

UpdateStatus declares the agent's current feature and files.

func (*Client) UpdateStatusWithRole

func (c *Client) UpdateStatusWithRole(repoPath, instanceID, feature string, files []string, role string) (*UpdateStatusResult, error)

UpdateStatusWithRole declares the agent's current feature, files, and role.

type CreateInstanceParams

type CreateInstanceParams struct {
	Title           string `json:"title"`
	Program         string `json:"program,omitempty"`
	Prompt          string `json:"prompt,omitempty"`
	Role            string `json:"role,omitempty"`
	Topic           string `json:"topic,omitempty"`
	SkipPermissions *bool  `json:"skip_permissions,omitempty"` // defaults to true for programmatic creation
	// AutomationID links this instance to the automation that spawned it.
	// When set, the instance will enter the Review Queue on completion.
	AutomationID string `json:"automation_id,omitempty"`
}

CreateInstanceParams holds parameters for spawning a new agent instance.

type CreateInstanceResult

type CreateInstanceResult struct {
	Title  string `json:"title"`
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

CreateInstanceResult is returned after an instance is created.

type Event

type Event struct {
	Type      EventType      `json:"type"`
	Timestamp time.Time      `json:"timestamp"`
	RepoPath  string         `json:"repo_path"`
	Source    string         `json:"source"`
	Data      map[string]any `json:"data,omitempty"`
	Sequence  uint64         `json:"sequence"`
}

Event is a single occurrence pushed to subscribers.

type EventBus

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

EventBus fans events out to matching subscribers with per-subscriber buffering.

func NewEventBus

func NewEventBus(maxBuffer int) *EventBus

NewEventBus creates an EventBus. maxBuffer caps each subscriber's queue.

func (*EventBus) Emit

func (eb *EventBus) Emit(event Event)

Emit publishes an event to all matching subscribers.

func (*EventBus) Poll

func (eb *EventBus) Poll(subscriberID string, timeout time.Duration) ([]Event, error)

Poll drains the subscriber's buffer. If empty, blocks until events arrive or timeout.

func (*EventBus) PruneStale

func (eb *EventBus) PruneStale(maxAge time.Duration) int

PruneStale removes subscribers that haven't polled within maxAge. Returns count removed.

func (*EventBus) Subscribe

func (eb *EventBus) Subscribe(filter EventFilter) string

Subscribe creates a new subscriber with the given filter and returns its ID.

func (*EventBus) Unsubscribe

func (eb *EventBus) Unsubscribe(subscriberID string)

Unsubscribe removes a subscriber.

type EventFilter

type EventFilter struct {
	Types       []EventType `json:"types,omitempty"`
	Instances   []string    `json:"instances,omitempty"`
	ParentTitle string      `json:"parent_title,omitempty"`
}

EventFilter controls which events a subscriber receives.

type EventType

type EventType string

EventType identifies the kind of event.

const (
	EventStatusChanged         EventType = "status_changed"
	EventMessageReceived       EventType = "message_received"
	EventAgentRemoved          EventType = "agent_removed"
	EventWorkflowDefined       EventType = "workflow_defined"
	EventTaskCompleted         EventType = "task_completed"
	EventTaskTriggered         EventType = "task_triggered"
	EventInstanceStatusChanged EventType = "instance_status_changed"
	EventInstanceCreated       EventType = "instance_created"
	EventInstanceKilled        EventType = "instance_killed"
)

type InjectMessageParams

type InjectMessageParams struct {
	To      string `json:"to"`
	Content string `json:"content"`
	Format  string `json:"format,omitempty"` // "plain" or "hivemind" (default)
}

InjectMessageParams holds parameters for direct terminal injection.

type Manager

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

Manager holds per-repo brain state in memory with mutex protection. All mutations are serialized through this struct.

func NewManager

func NewManager() *Manager

NewManager creates a new empty Manager.

func (*Manager) CompleteTask

func (m *Manager) CompleteTask(repoPath, taskID string, status TaskStatus, errMsg string) error

CompleteTask marks a workflow task as done or failed.

func (*Manager) DefineWorkflow

func (m *Manager) DefineWorkflow(repoPath string, tasks []*WorkflowTask) *WorkflowResult

DefineWorkflow creates or replaces a workflow for a repo.

func (*Manager) EvaluateWorkflow

func (m *Manager) EvaluateWorkflow(repoPath string) []string

EvaluateWorkflow checks for pending tasks whose dependencies are all done, marks them as running, and returns their IDs.

func (*Manager) GetBrain

func (m *Manager) GetBrain(repoPath, instanceID string) *BrainState

GetBrain returns the brain state for a repo, filtered for the requesting agent. Stale agents are pruned. Messages are filtered to those addressed to instanceID or broadcast.

func (*Manager) GetWorkflow

func (m *Manager) GetWorkflow(repoPath string) *Workflow

GetWorkflow returns the current workflow for a repo, or nil if none exists.

func (*Manager) GetWorkflowTask

func (m *Manager) GetWorkflowTask(repoPath, taskID string) *WorkflowTask

GetWorkflowTask returns a single task from the workflow by ID.

func (*Manager) RemoveAgent

func (m *Manager) RemoveAgent(repoPath, instanceID string)

RemoveAgent removes an agent from the repo's state.

func (*Manager) SendMessage

func (m *Manager) SendMessage(repoPath, from, to, content string)

SendMessage appends a message to the repo's message list, capping at maxMessages.

func (*Manager) SetEventCallback

func (m *Manager) SetEventCallback(fn func(Event))

SetEventCallback sets the function called when the manager emits an event.

func (*Manager) UpdateStatus

func (m *Manager) UpdateStatus(repoPath, instanceID, feature string, files []string) *UpdateStatusResult

UpdateStatus sets the agent's feature and files, returning conflict warnings.

func (*Manager) UpdateStatusWithRole

func (m *Manager) UpdateStatusWithRole(repoPath, instanceID, feature string, files []string, role string) *UpdateStatusResult

UpdateStatusWithRole sets the agent's feature, files, and optional role.

type PollEventsResult

type PollEventsResult struct {
	SubscriberID string  `json:"subscriber_id"`
	Events       []Event `json:"events"`
}

PollEventsResult is returned by the poll_events method.

type Request

type Request struct {
	Method     string         `json:"method"`
	InstanceID string         `json:"instance_id"`
	RepoPath   string         `json:"repo_path"`
	Params     map[string]any `json:"params,omitempty"`
}

Request is the JSON envelope sent from client to server over the Unix socket.

type Response

type Response struct {
	OK    bool            `json:"ok"`
	Data  json.RawMessage `json:"data,omitempty"`
	Error string          `json:"error,omitempty"`
}

Response is the JSON envelope sent from server to client.

type Server

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

Server listens on a Unix domain socket and dispatches requests to a Manager.

func NewServer

func NewServer(socketPath string) *Server

NewServer creates a new brain server. Call Start() to begin listening.

func (*Server) Actions

func (s *Server) Actions() <-chan ActionRequest

Actions returns the channel for receiving action requests from agents. The TUI reads from this channel to process Tier 3 operations.

func (*Server) CreateInstanceDirect added in v0.2.2

func (s *Server) CreateInstanceDirect(params CreateInstanceParams) error

CreateInstanceDirect allows the daemon (or any in-process caller) to trigger instance creation without going through the Unix socket. It mirrors the path taken by the MethodCreateInstance socket handler: it builds a params map and sends an ActionCreateInstance request to the TUI via the action channel.

func (*Server) Manager

func (s *Server) Manager() *Manager

Manager returns the underlying state manager for direct in-process access.

func (*Server) PushEvent

func (s *Server) PushEvent(event Event)

PushEvent emits an event into the event bus (used by TUI for instance lifecycle events).

func (*Server) SocketPath

func (s *Server) SocketPath() string

SocketPath returns the path the server is listening on.

func (*Server) Start

func (s *Server) Start() error

Start begins listening on the Unix socket. It blocks in an accept loop until Stop() is called.

func (*Server) Stop

func (s *Server) Stop() error

Stop closes the listener, waits for in-flight connections to finish, and removes the socket file.

type SubscribeResult

type SubscribeResult struct {
	SubscriberID string `json:"subscriber_id"`
}

SubscribeResult is returned by the subscribe method.

type Subscriber

type Subscriber struct {
	ID     string
	Filter EventFilter
	// contains filtered or unexported fields
}

Subscriber holds a buffered queue of events for a single consumer.

type TaskStatus

type TaskStatus string

TaskStatus tracks the state of a workflow task.

const (
	TaskPending TaskStatus = "pending"
	TaskRunning TaskStatus = "running"
	TaskDone    TaskStatus = "done"
	TaskFailed  TaskStatus = "failed"
)

type UpdateStatusResult

type UpdateStatusResult struct {
	Conflicts []string `json:"conflicts,omitempty"`
}

UpdateStatusResult is returned by UpdateStatus with optional conflict warnings.

type Workflow

type Workflow struct {
	ID    string          `json:"id"`
	Tasks []*WorkflowTask `json:"tasks"`
}

Workflow is a DAG of tasks for a repository.

type WorkflowResult

type WorkflowResult struct {
	WorkflowID string   `json:"workflow_id"`
	Triggered  []string `json:"triggered,omitempty"`
	Error      string   `json:"error,omitempty"`
}

WorkflowResult is returned by workflow operations.

type WorkflowTask

type WorkflowTask struct {
	ID         string     `json:"id"`
	Title      string     `json:"title"`
	Status     TaskStatus `json:"status"`
	DependsOn  []string   `json:"depends_on,omitempty"`
	AssignedTo string     `json:"assigned_to,omitempty"`
	Prompt     string     `json:"prompt,omitempty"`
	Role       string     `json:"role,omitempty"`
	Error      string     `json:"error,omitempty"`
}

WorkflowTask represents a single task in a workflow DAG.

Jump to

Keyboard shortcuts

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