controller

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package controller provides UI-agnostic business logic for aimux. It orchestrates exports, session management, and agent coordination without depending on any TUI framework. Both the Bubble Tea TUI and a future web UI import this package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BulkDeleteSessions

func BulkDeleteSessions(sessions []history.Session) (int, error)

BulkDeleteSessions removes multiple sessions, returning the count of successfully deleted sessions and the first error encountered.

func DefaultSessionDir added in v0.13.0

func DefaultSessionDir(selectedAgentDir, launchDir string) string

DefaultSessionDir returns the directory to scope session discovery to. Selected agent dir takes priority, then launchDir, then empty (all).

func DeleteSession

func DeleteSession(s history.Session) error

DeleteSession removes a session's JSONL file and its sidecar .meta.json.

func EnvironmentNames added in v0.13.0

func EnvironmentNames(envs map[string]config.EnvironmentConfig) []string

EnvironmentNames returns sorted environment names from a config map. "local" is always sorted first if present.

func ExecuteKillSandbox added in v0.13.0

func ExecuteKillSandbox(action KillAction, engine *aimuxcompose.Engine) error

ExecuteKillSandbox kills the tmux session (closing the SSH connection), waits for the connection to close, then deletes the OpenShell sandbox.

func FilterAgents added in v0.11.0

func FilterAgents(agents []agent.Agent, query string) []agent.Agent

FilterAgents returns agents matching the query string. The match is case-insensitive and checks ShortProject, ShortModel, Status, Source, ProviderName, ShortDir, and LastAction. An empty query returns all agents.

func FilterHidden

func FilterHidden(agents []agent.Agent, hidden map[string]bool) []agent.Agent

FilterHidden removes agents whose session key is in the hidden set. The key is derived from SessionID, SessionFile, or PID (in that priority).

func NextAttend added in v0.11.0

func NextAttend(agents []agent.Agent, currentIdx int) int

NextAttend returns the index of the next agent needing attention, prioritized by urgency: WaitingPermission first, then Error, then Idle, then Unknown. Active agents are always skipped.

Within the highest-priority tier, it cycles through candidates starting after currentIdx, wrapping around. Returns -1 if no agent needs attention.

func PartitionByArchive added in v0.11.0

func PartitionByArchive(agents []agent.Agent, threshold time.Duration) (active, archived []agent.Agent)

PartitionByArchive splits agents into active and archived based on idle duration. Only Idle, Error, and Unknown agents can be archived. Active and WaitingPermission agents are never archived. A zero threshold disables archiving (all agents returned in the active list).

func RemoteAgentCommand added in v0.13.0

func RemoteAgentCommand(provider, sessionID string, resume bool) string

RemoteAgentCommand builds the shell command that starts the agent inside the sandbox. For Claude, the session id is pinned so telemetry and conversation stay continuous across reconnects.

func RemoteScaleDown added in v0.13.0

func RemoteScaleDown(ctx context.Context, b mcpserver.Backend) ([]string, error)

RemoteScaleDown deletes all sandboxes via the backend. Returns names deleted.

func RemoteSpawn added in v0.13.0

func RemoteSpawn(ctx context.Context, b mcpserver.Backend, provider string, count int) ([]string, error)

RemoteSpawn creates count sandboxes via the backend and returns their names. This is the controller function that TUI, Web, and CLI call.

func RemoteTraceParser added in v0.13.0

func RemoteTraceParser(store OTELLookup, otelSessionID, sandboxName string) []trace.Turn

RemoteTraceParser reads OTEL spans (or falls back to the sandbox session file) and returns trace turns for a remote agent session. This is the shared logic extracted from the TUI's parserForRemote; any frontend can call it directly.

func ResolveLaunchRuntime added in v0.13.0

func ResolveLaunchRuntime(env config.EnvironmentConfig) string

ResolveLaunchRuntime maps an environment type to the runtime string used by the launch dispatch in app.go. This centralizes the mapping so both TUI and web frontends use the same logic.

func ResolveMode added in v0.13.0

func ResolveMode(explicit, configDefault string) string

ResolveMode returns the effective mode: explicit override wins, then config default, then "default".

func ResumeArgs added in v0.13.0

func ResumeArgs(sessionID, mode string) []string

ResumeArgs builds the arguments for resuming a Claude session with the given permission mode.

func ResumeCommand added in v0.13.0

func ResumeCommand(claudeBin, sessionID, workingDir, mode string) *exec.Cmd

ResumeCommand builds the full exec.Cmd for resuming a session.

func SetAnnotation added in v0.11.0

func SetAnnotation(sessionFile, annotation string) error

SetAnnotation updates the annotation field for a session.

func SetNote added in v0.11.0

func SetNote(sessionFile, note string) error

SetNote updates the free-text note for a session.

func SetROI added in v0.12.0

func SetROI(sessionFile string, multiplier float64, taskType string) error

SetROI updates the ROI multiplier and task type for a session.

func SetTags added in v0.11.0

func SetTags(sessionFile string, tags []string) error

SetTags updates the tags list for a session.

func SortAgents added in v0.11.0

func SortAgents(agents []agent.Agent, field string)

SortAgents sorts agents in place using sort.SliceStable. Supported fields: "", "name", "cost", "cpu", "mem", "age", "model". The default ("") sorts by status priority (active first) then name alphabetically.

func ToggleBypass added in v0.13.0

func ToggleBypass(current string) string

ToggleBypass flips between "bypass" and "default" modes.

func ToggleStar added in v0.11.0

func ToggleStar(sessionFile string) (bool, error)

ToggleStar flips the starred state for a session and persists it. Returns the new starred value.

func UUIDValid added in v0.13.0

func UUIDValid(s string) bool

Types

type ActionInput

type ActionInput struct {
	Tool    string
	Input   string
	Success bool
	Error   string
}

ActionInput is a tool invocation within a trace turn.

type Controller

type Controller struct {
	Nav *Navigator
	// contains filtered or unexported fields
}

Controller owns the business logic and state that is shared across all UI frontends. It does NOT import bubbletea or lipgloss.

func New

func New(cfg config.Config) *Controller

New creates a new Controller with the given configuration.

func (*Controller) ExportJSONL

func (c *Controller) ExportJSONL(ctx ExportContext) (ExportResult, error)

ExportJSONL exports trace turns and session metadata to a JSONL file. Returns the file path and turn count on success.

func (*Controller) ExportOTEL

func (c *Controller) ExportOTEL(ctx ExportContext) (ExportResult, error)

ExportOTEL exports trace turns and session metadata as OTLP/HTTP spans. Returns the endpoint URL and turn count on success.

type ExportContext

type ExportContext struct {
	SessionID    string
	SessionFile  string // path to session JSONL (for loading .meta.json)
	ProviderName string
	Turns        []TraceInput
	EvalStore    *evaluation.Store
}

ExportContext holds the runtime context needed for an export operation. The UI layer populates this from its active state (which trace is open, which session file is loaded, etc.).

type ExportResult

type ExportResult struct {
	Path  string // file path (JSONL) or endpoint URL (OTEL)
	Count int    // number of turns exported
}

ExportResult holds the outcome of an export operation.

type Harness added in v0.13.0

type Harness interface {
	Name() string
	SpawnCommand(dir, model, mode string) *exec.Cmd
	OTELEnv(endpoint string) string
}

Harness is the subset of Provider that the launch path needs. It represents the "brain" -- what agent to run and how to configure it. The name aligns with industry terminology: the harness is the component that calls the model, parses tool calls, and decides when to stop.

type KillAction added in v0.11.0

type KillAction struct {
	Type        KillType
	PodName     string
	Namespace   string
	SandboxName string // OpenShell sandbox name
	TmuxSession string // tmux session to kill
}

KillAction holds the determined kill strategy and any provider-specific parameters (e.g., pod name and namespace for K8s agents).

func DetermineKillAction added in v0.11.0

func DetermineKillAction(ag agent.Agent) KillAction

DetermineKillAction inspects an agent and returns the appropriate kill strategy.

type KillType added in v0.11.0

type KillType int

KillType describes how an agent should be terminated.

const (
	KillProcess    KillType = iota // local process: SIGTERM via provider
	KillPod                        // K8s pod: kubectl delete + scale down
	KillRemoveOnly                 // session-only entry: hide from view
	KillSandbox                    // OpenShell sandbox: delete + kill tmux
)

type LaunchMeta added in v0.13.0

type LaunchMeta struct {
	SessionID string `json:"session_id"`
	Provider  string `json:"provider"`
	Dir       string `json:"dir"`
}

LaunchMeta records what was stored at sandbox launch time.

type LaunchRequest added in v0.13.0

type LaunchRequest struct {
	Dir            string
	Model          string
	Mode           string
	Prompt         string
	Shell          string
	SessionManager string
	OTELEnabled    bool
	OTELEndpoint   string
	Runtime        string
	ContainerOpts  spawn.ContainerOpts
}

LaunchRequest captures all user-specified launch parameters. Frontends (TUI, Web, CLI) build this; the controller resolves it.

type LaunchResult added in v0.13.0

type LaunchResult struct {
	PID           int
	TmuxSession   string
	SandboxName   string
	OTELSessionID string
}

LaunchResult carries information about a launched agent.

func ExecuteLocalLaunch added in v0.13.0

func ExecuteLocalLaunch(spec LaunchSpec) (LaunchResult, error)

ExecuteLocalLaunch runs a resolved LaunchSpec in the local environment. This replaces the three duplicated launch paths in app.go, main.go (Web), and main.go (CLI).

type LaunchSpec added in v0.13.0

type LaunchSpec struct {
	Provider       string
	Cmd            *exec.Cmd
	Dir            string
	Shell          string
	SessionManager string
	EnvPrefix      string
	Runtime        string
	ContainerOpts  spawn.ContainerOpts
}

LaunchSpec is the fully-resolved command ready for execution. The Environment (execution plane) can run this without knowing which harness produced it.

func BuildLaunchSpec added in v0.13.0

func BuildLaunchSpec(h Harness, req LaunchRequest) LaunchSpec

BuildLaunchSpec resolves a LaunchRequest into a LaunchSpec using the harness. This is the single point where "brain config" (from the harness) meets "user intent" (from the request). The result is execution-plane-ready.

type Navigator struct {
	CurrentView ViewType
	Breadcrumbs []string
	Zoomed      bool
	SplitMode   bool
	SplitFocus  string // "trace" or "session"
}

Navigator manages the view navigation state machine. It tracks which view is active, breadcrumbs, and zoom/split state.

func NewNavigator

func NewNavigator() *Navigator

NewNavigator creates a Navigator in the default state (agents view).

func (n *Navigator) EnterZoom()

EnterZoom enters zoomed session mode with split view.

func (n *Navigator) ExitZoom() (exitedFully bool)

ExitZoom implements hierarchical back navigation: fullscreen -> split view -> main view. Returns true if fully exited zoom (back to main), false if returned to split.

func (n *Navigator) NavigateBack()

NavigateBack returns to the agents view.

func (n *Navigator) NavigateTo(v ViewType, label string)

NavigateTo switches to a new view with a breadcrumb label.

func (n *Navigator) ToggleSplit()

ToggleSplit toggles between split and full-screen mode.

func (n *Navigator) ToggleSplitFocus()

ToggleSplitFocus switches focus between "trace" and "session" panes.

type Notification added in v0.11.0

type Notification struct {
	Title   string
	Message string
	Sound   bool
}

Notification describes a notification that should be delivered by the caller. The controller decides whether to notify; the UI layer decides how.

func ShouldNotify added in v0.11.0

func ShouldNotify(status agent.Status, projectName string, cfg config.NotificationsConfig) *Notification

ShouldNotify returns a Notification if the agent's current status warrants one, or nil if no notification should fire. The caller is responsible for delivering the notification (e.g., macOS notification center, SSE event).

type OTELLookup added in v0.13.0

type OTELLookup interface {
	HasData() bool
	GetByConversation(id string) *aimuxotel.Span
	ConversationIDs() []string
}

OTELLookup is the minimal interface over *otel.SpanStore needed by the remote trace parser. Both the TUI and web frontends satisfy this via the shared SpanStore.

type RemoteSession added in v0.13.0

type RemoteSession struct {
	SandboxName   string
	OTELSessionID string
}

RemoteSession holds the result of provisioning an interactive remote session.

func RemoteLaunchSession added in v0.13.0

func RemoteLaunchSession(engine *aimuxcompose.Engine, provider, dir string, opts RemoteSessionOpts) (*RemoteSession, error)

RemoteLaunchSession provisions a sandbox for an interactive remote session. The interactive terminal itself is established by the caller via terminal.NewOpenShellExec(SandboxName, ...).

type RemoteSessionOpts added in v0.13.0

type RemoteSessionOpts struct {
	Name   string
	Image  string
	Binary string
}

RemoteSessionOpts configures an interactive remote session.

type RemoteStatus added in v0.13.0

type RemoteStatus struct {
	Backend   string
	Sandboxes []mcpserver.SandboxStatus
	IdleCount int
	Error     string
}

RemoteStatus holds the result of a remote backend health check.

func RemoteBackendStatus added in v0.13.0

func RemoteBackendStatus(ctx context.Context, b mcpserver.Backend) RemoteStatus

RemoteBackendStatus queries the remote backend for its current state. Returns sandbox list and idle count. Usable from TUI, Web, and CLI.

type SessionStore added in v0.13.0

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

func NewSessionStore added in v0.13.0

func NewSessionStore(configDir string) *SessionStore

func (*SessionStore) Get added in v0.13.0

func (s *SessionStore) Get(sandboxName string) string

Get returns the session ID for the given sandbox (backward-compat accessor).

func (*SessionStore) GetMeta added in v0.13.0

func (s *SessionStore) GetMeta(sandboxName string) LaunchMeta

GetMeta returns the full launch metadata for a sandbox.

func (*SessionStore) Put added in v0.13.0

func (s *SessionStore) Put(sandboxName, sessionID string)

Put stores only the session ID; provider and dir are left empty. Prefer PutMeta when all three values are available.

func (*SessionStore) PutMeta added in v0.13.0

func (s *SessionStore) PutMeta(sandboxName string, meta LaunchMeta)

PutMeta stores the full launch metadata for a sandbox.

type TraceInput

type TraceInput struct {
	Number     int
	Timestamp  string // RFC3339
	UserText   string
	OutputText string
	Actions    []ActionInput
	TokensIn   int64
	TokensOut  int64
	CostUSD    float64
	DurationMs int64
	Model      string
}

TraceInput is the subset of trace.Turn fields needed for export, avoiding a direct dependency on the trace package's full type (which includes rendering-specific fields).

func TurnsToInputs

func TurnsToInputs(turns []trace.Turn) []TraceInput

TurnsToInputs converts trace.Turn slices to the UI-agnostic TraceInput format. Called by the UI layer before passing data to the controller.

type ViewType

type ViewType int

ViewType identifies which view is active.

const (
	ViewAgents ViewType = iota
	ViewLogs
	ViewCosts
	ViewTeams
	ViewSessions
	ViewHelp
)

Jump to

Keyboard shortcuts

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