server

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

ABOUTME: Shared application state for the mammoth spec builder HTTP server. ABOUTME: Contains actor handles, swarm handles, event persisters, and provider status.

ABOUTME: Bearer token authentication middleware for API and web routes. ABOUTME: Supports Authorization header and mammoth_token cookie for browser sessions.

ABOUTME: Server configuration loaded from MAMMOTH_* environment variables. ABOUTME: Enforces security constraint: remote access requires auth token.

ABOUTME: Minimal .env file loader that sets environment variables from KEY=VALUE pairs. ABOUTME: Supports comments, blank lines, quoted values, and does not override existing env vars.

ABOUTME: Event persistence helpers for writing events to JSONL files. ABOUTME: Provides PersistEvents for batch writes and SpawnEventPersister for background streaming.

ABOUTME: LLM provider status detection from environment variables. ABOUTME: Checks for Anthropic, OpenAI, and Gemini API keys without exposing secrets.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRemoteWithoutToken = errors.New(
		"MAMMOTH_ALLOW_REMOTE is true but MAMMOTH_AUTH_TOKEN is not set; refusing to start without authentication",
	)
	ErrNonLoopbackBind = errors.New(
		"MAMMOTH_BIND is a non-loopback address but MAMMOTH_ALLOW_REMOTE is not true; set MAMMOTH_ALLOW_REMOTE=true and MAMMOTH_AUTH_TOKEN to allow remote access",
	)
)

ConfigError represents configuration validation errors.

Functions

func AuthMiddleware

func AuthMiddleware(token string) func(http.Handler) http.Handler

AuthMiddleware returns an http.Handler middleware that validates bearer tokens on /api/* and /web/* routes. Static assets, health checks, and the login endpoint pass through unprotected. For browser sessions, the middleware also accepts a mammoth_token cookie (set by the /login endpoint).

func LoadDotEnv

func LoadDotEnv(path string) error

LoadDotEnv reads a .env file and sets environment variables for any keys not already present in the environment. This preserves explicit env var overrides while providing defaults from the file.

Lines starting with # are comments. Blank lines are ignored. Values may be optionally wrapped in single or double quotes. Returns nil if the file does not exist.

func LoginHandler

func LoginHandler(expectedToken string) http.HandlerFunc

LoginHandler validates a token query parameter and sets a session cookie. GET /login?token=xxx validates and sets the cookie, then redirects to /. GET /login without a token shows a minimal login prompt.

func PersistEvents

func PersistEvents(specDir string, events []core.Event)

PersistEvents writes events to the JSONL file in the spec directory.

func SpawnEventPersister

func SpawnEventPersister(appState *AppState, specID ulid.ULID, handle *core.SpecActorHandle)

SpawnEventPersister starts a background goroutine that subscribes to an actor's broadcast channel and persists every event to JSONL.

Types

type AppState

type AppState struct {
	Actors          map[ulid.ULID]*core.SpecActorHandle
	Swarms          map[ulid.ULID]*SwarmHandle
	EventPersisters map[ulid.ULID]chan struct{} // stop channels for event persister goroutines
	MammothHome     string
	ProviderStatus  ProviderStatus
	LLMClient       llm.Client // may be nil if no provider is configured
	LLMModel        string
	// contains filtered or unexported fields
}

AppState holds the shared state accessible by all HTTP handlers.

func NewAppState

func NewAppState(mammothHome string, providerStatus ProviderStatus) *AppState

NewAppState creates a new AppState with empty maps and the given home directory.

func (*AppState) GetActor

func (s *AppState) GetActor(specID ulid.ULID) *core.SpecActorHandle

GetActor returns the actor handle for a spec, or nil if not found.

func (*AppState) GetSwarm

func (s *AppState) GetSwarm(specID ulid.ULID) *SwarmHandle

GetSwarm returns the swarm handle for a spec, or nil if not found.

func (*AppState) ListActorIDs

func (s *AppState) ListActorIDs() []ulid.ULID

ListActorIDs returns all spec IDs with active actors.

func (*AppState) SetActor

func (s *AppState) SetActor(specID ulid.ULID, handle *core.SpecActorHandle)

SetActor stores an actor handle for a spec.

func (*AppState) SetEventPersister

func (s *AppState) SetEventPersister(specID ulid.ULID, stopCh chan struct{})

SetEventPersister stores a stop channel for a spec's event persister goroutine.

func (*AppState) SetSwarm

func (s *AppState) SetSwarm(specID ulid.ULID, handle *SwarmHandle)

SetSwarm stores a swarm handle for a spec.

func (*AppState) StopAllEventPersisters

func (s *AppState) StopAllEventPersisters()

StopAllEventPersisters closes all event persister stop channels.

func (*AppState) StopAllSwarms

func (s *AppState) StopAllSwarms()

StopAllSwarms cancels all running swarm orchestrators.

func (*AppState) StopSwarm

func (s *AppState) StopSwarm(specID ulid.ULID) bool

StopSwarm cancels and removes the swarm for a specific spec. It returns true if a swarm was found and stopped.

func (*AppState) TryStartAgents

func (s *AppState) TryStartAgents(specID ulid.ULID) bool

TryStartAgents starts the agent swarm for a spec if an LLM provider is configured and no swarm is already running. Holds the lock across check-and-set to prevent double-start races. Returns true if a swarm was started.

type MammothConfig

type MammothConfig struct {
	Home            string // Data directory (MAMMOTH_HOME, default: ~/.mammoth-specd)
	Bind            string // Socket address (MAMMOTH_BIND, default: 127.0.0.1:7770)
	AllowRemote     bool   // Allow non-loopback connections (MAMMOTH_ALLOW_REMOTE, default: false)
	AuthToken       string // Bearer token for API auth (MAMMOTH_AUTH_TOKEN, optional)
	DefaultProvider string // LLM provider (MAMMOTH_DEFAULT_PROVIDER, default: anthropic)
	DefaultModel    string // LLM model name (MAMMOTH_DEFAULT_MODEL, optional)
	PublicBaseURL   string // Public URL for the server (MAMMOTH_PUBLIC_BASE_URL)
}

MammothConfig holds server configuration loaded from environment variables.

func ConfigFromEnv

func ConfigFromEnv() (*MammothConfig, error)

ConfigFromEnv loads configuration from MAMMOTH_* environment variables with sensible defaults.

type ProviderInfo

type ProviderInfo struct {
	Name      string  `json:"name"`
	HasAPIKey bool    `json:"has_api_key"`
	Model     string  `json:"model"`
	BaseURL   *string `json:"base_url,omitempty"`
}

ProviderInfo describes the status of a single LLM provider.

type ProviderStatus

type ProviderStatus struct {
	DefaultProvider string         `json:"default_provider"`
	DefaultModel    *string        `json:"default_model,omitempty"`
	Providers       []ProviderInfo `json:"providers"`
	AnyAvailable    bool           `json:"any_available"`
}

ProviderStatus is the aggregated provider availability for the UI.

func DetectProviders

func DetectProviders() ProviderStatus

DetectProviders checks environment variables to determine which LLM providers are configured.

type SwarmHandle

type SwarmHandle struct {
	Orchestrator *agents.SwarmOrchestrator
	Cancel       context.CancelFunc
}

SwarmHandle bundles a swarm orchestrator reference with a cancel function so the agent loop can be stopped on cleanup.

Jump to

Keyboard shortcuts

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