Documentation
¶
Overview ¶
Package api is Loomux's client-facing HTTP surface (design spec §9, §10 axis 1): a versioned /api/v1/... surface with real, login-gated Bearer-token auth in front of app.App.Dispatch — "there is no 'it's just me so no auth' shortcut" (spec §9), since clients are reachable outside the server process's own trust boundary. See README.md for the auth design and its deployment assumptions.
Index ¶
- Constants
- func HashPassword(password string) (string, error)
- type AttachInfoStore
- type Config
- type CredentialStore
- type Dispatcher
- type EventStore
- type HealthChecker
- type HostKeyScanner
- type HostKeyStore
- type MessageLister
- type Option
- func WithAgentTypes(names []string) Option
- func WithCredentials(c CredentialStore) Option
- func WithEvents(e EventStore) Option
- func WithHealthChecker(h HealthChecker) Option
- func WithHostKeyPinning(scan HostKeyScanner, store HostKeyStore) Option
- func WithLocalTargets(on bool) Option
- func WithLoginBackoff(base, max time.Duration) Option
- func WithPlugins(p Plugins) Option
- func WithRouterSettings(rs RouterSettings) Option
- func WithSSHKeyDropper(drop func(id string)) Option
- func WithSSHKeys(store SSHKeyStore) Option
- func WithSSHMigration(resolve SSHConfigResolver) Option
- func WithSessionMaxAge(d time.Duration) Option
- func WithSessionTTL(d time.Duration) Option
- func WithStaticDir(dir string) Option
- func WithStreamHeartbeat(d time.Duration) Option
- func WithStreamPollInterval(d time.Duration) Option
- func WithTargetProber(p TargetProber) Option
- func WithTaskCanceller(c TaskCanceller) Option
- func WithTaskTurns(t TaskTurnStore) Option
- func WithWebBundles(web WebBundles) Option
- func WithWorkspaceManager(m WorkspaceManager) Option
- type Plugins
- type RouterSettings
- type SSHConfigResolver
- type SSHKeyStore
- type Server
- type SessionStore
- type TargetProber
- type TargetStore
- type TaskCanceller
- type TaskLister
- type TaskTurnStore
- type WebBundles
- type WorkspaceLister
- type WorkspaceManager
Constants ¶
const APIVersion = "v1"
APIVersion is the server↔client API version this package serves (design spec §10 axis 1) — the "v1" in /api/v1/..., independent of version.Version (axis 4, the server's own release version).
Variables ¶
This section is empty.
Functions ¶
func HashPassword ¶
HashPassword bcrypt-hashes a plaintext password for storage in LOOMUX_AUTH_PASSWORD_HASH — the raw password itself is never meant to be configured or stored. loomuxd -hash-password exposes this to operators without needing external tooling.
Types ¶
type AttachInfoStore ¶
type AttachInfoStore interface {
GetTask(ctx context.Context, id string) (*registry.Task, error)
GetWorkspace(ctx context.Context, id string) (*registry.Workspace, error)
GetTarget(ctx context.Context, id string) (*registry.Target, error)
}
AttachInfoStore is the get-chain slice of registry.Store LOOM-20's attach-info endpoint needs to resolve a task down to the target a human would SSH into: task -> its workspace -> that workspace's target. Satisfied structurally by any registry.Store, mirroring this package's other narrow seams.
type Config ¶
type Config struct {
// PasswordHash is a bcrypt hash (see HashPassword) — the single v1
// user's credential. Required: there is no unauthenticated fallback
// (design spec §9: "no 'it's just me so no auth' shortcut").
PasswordHash []byte
// Addr is the address Server listens on. Plain HTTP is assumed — the
// deployment model is a reverse proxy in front terminating TLS (see
// README.md).
Addr string
// SessionTTL is the sliding-expiration window (see WithSessionTTL).
SessionTTL time.Duration
// SessionMaxAge is a session's absolute lifetime, 0 for none (see
// WithSessionMaxAge).
SessionMaxAge time.Duration
// StaticDir, if set, is the directory containing the web client's
// built static files (loomux/web's Vite build output) — passed to
// WithStaticDir so Server serves it for any non-/api/* path, with SPA
// fallback to index.html (design spec docs/design/web-client-design.md,
// "Hosting / serving integration"; tracked as GitHub issue LOOM-33).
// Empty (the default) disables static serving entirely — the same
// "optional, unvalidated path" convention as app.Config.MarkerDir,
// since there's no way to tell "not configured yet" apart from "wrong
// path" without trying to open it, and that's Server's job, not
// LoadConfig's.
StaticDir string
// MetricsAddr is the address the Prometheus metrics scraper listens
// on (LOOM-103). Empty disables the endpoint entirely. The default
// binds to loopback only (127.0.0.1:9090); production deployments that
// need in-cluster scraping must set this explicitly to ":9090" or a
// pod IP.
MetricsAddr string
// WebBundlesDir, if set together with StaticDir, is where web client
// updates are installed (LOOM-118): StaticDir is then the image's own
// bundle, served until a newer one is installed here. It must persist
// across restarts, so it defaults to web-bundles next to the database
// (LOOMUX_DB_PATH), which lives on the data volume.
WebBundlesDir string
// WebUpdates is how the web client is updated in place (LOOM-118):
// "attested" installs the newest release loomux/web's CI built on
// main, proven by its build-provenance attestation; "pinned" installs
// what loomux/server main pins; "off" installs nothing (the bundle
// served is still reported). Unset: "attested" if WebReleasesToken is
// set (how the feature was switched on before), otherwise "off".
WebUpdates string
// WebReleasesToken is an optional read-only GitHub token: both
// repositories are public, so it only raises the API rate limit.
WebReleasesToken string
// WebPinRepo is the repository whose main pins the bundle to serve
// (deploy/web-ref, deploy/web-sha256): loomux/server.
WebPinRepo string
// WebReleasesRepo is the repository web bundles are published in.
WebReleasesRepo string
}
Config is api's own process configuration, loaded from environment variables — this repo's established convention (see registry/sqlite.KeyFromEnv, router/llmrouter.ConfigFromEnv, app.LoadConfig).
func LoadConfig ¶
LoadConfig reads Config from the environment, failing fast on a missing or malformed password hash and on a malformed (not merely absent) session TTL.
type CredentialStore ¶ added in v0.1.18
type CredentialStore interface {
CreateCredential(ctx context.Context, c *registry.Credential) error
ListCredentialInfo(ctx context.Context) ([]*registry.Credential, error)
SetCredentialValue(ctx context.Context, id, value string) error
DeleteCredential(ctx context.Context, id string) error
}
CredentialStore backs /api/v1/credentials (LOOM-134): the vault of secrets injected into agents' environments per launch (design §7). Values go in and are never read back out through the API.
type Dispatcher ¶
type Dispatcher interface {
Submit(ctx context.Context, req dispatch.Request) (*registry.Dispatch, error)
// Wait blocks until the job is finished or ctx is done; ctx ending
// never affects the job.
Wait(ctx context.Context, id string) (*registry.Dispatch, error)
Get(ctx context.Context, id string) (*registry.Dispatch, error)
ListByConversation(ctx context.Context, conversationID string) ([]*registry.Dispatch, error)
// Cancel stops a running job (LOOM-99): registry.ErrNotFound for an
// unknown id, dispatch.ErrNotRunning for one that has ended.
Cancel(ctx context.Context, id string) error
}
Dispatcher is what Server needs from the domain layer to run chat dispatches: the dispatch-job service (LOOM-80), satisfied by *dispatch.Service (app.App.Dispatches() in production). Every POST /dispatch becomes a job running on a server-owned context; the request only decides whether to wait for it.
type EventStore ¶ added in v0.3.7
type EventStore interface {
ListDispatchEventsByConversation(ctx context.Context, conversationID string) ([]*registry.DispatchEvent, error)
}
EventStore is what GET /conversations/{id}/events reads (LOOM-110): the conversation's dispatch audit trail.
type HealthChecker ¶
type HealthChecker interface {
Shallow(ctx context.Context) health.Result
Deep(ctx context.Context) health.Result
}
HealthChecker is the narrow seam the health endpoints need from the domain layer (LOOM-105). It is satisfied by *health.Checker.
type HostKeyScanner ¶ added in v0.3.8
HostKeyScanner reads the host key a target presents, without trusting it — targets.ScanHostKey.
type HostKeyStore ¶ added in v0.3.8
HostKeyStore is where pins are kept — satisfied by any registry.Store.
type MessageLister ¶
type MessageLister interface {
ListMessagesByConversation(ctx context.Context, conversationID string) ([]*registry.Message, error)
ListConversationActivity(ctx context.Context) ([]*registry.ConversationActivity, error)
ListConfirmationsByConversation(ctx context.Context, conversationID string) ([]*registry.Confirmation, error)
}
MessageLister is the message-transcript slice of registry.Store this package needs to extend conversation-detail (LOOM-18) with real chat turns instead of only task-lifecycle rows (LOOM-31), and to list conversations that never touched a task (LOOM-62) — satisfied structurally by any registry.Store, mirroring TaskLister.
type Option ¶
type Option func(*Server)
Option configures a Server constructed via NewServer.
func WithAgentTypes ¶
WithAgentTypes names the agent types this server can launch, so a target's allowed_agent_types can be checked against them (LOOM-122). Without it any non-blank name is accepted.
func WithCredentials ¶ added in v0.1.18
func WithCredentials(c CredentialStore) Option
WithCredentials enables /api/v1/credentials (LOOM-134).
func WithEvents ¶ added in v0.3.7
func WithEvents(e EventStore) Option
WithEvents enables GET /api/v1/conversations/{id}/events (LOOM-110).
func WithHealthChecker ¶
func WithHealthChecker(h HealthChecker) Option
WithHealthChecker sets the checker used by /api/v1/health and /api/v1/health/deep (LOOM-105). A nil value is accepted and ignored.
func WithHostKeyPinning ¶ added in v0.3.8
func WithHostKeyPinning(scan HostKeyScanner, store HostKeyStore) Option
WithHostKeyPinning enables POST /targets/{id}/scan-host-key and POST/DELETE /targets/{id}/pin (LOOM-114).
func WithLocalTargets ¶ added in v0.3.40
WithLocalTargets says whether targets of kind "local" may be registered (LOOM-141; app.Config.LocalTargetsOff). On by default.
func WithLoginBackoff ¶
WithLoginBackoff overrides /login's default exponential-backoff timing (base delay after the first failure, capped at max). Mainly for tests; production defaults are defaultLoginBackoffBase/Max.
func WithPlugins ¶ added in v0.3.68
WithPlugins enables /api/v1/plugins (LOOM-178).
func WithRouterSettings ¶ added in v0.3.64
func WithRouterSettings(rs RouterSettings) Option
WithRouterSettings enables /api/v1/settings/router (LOOM-185).
func WithSSHKeyDropper ¶ added in v0.3.41
WithSSHKeyDropper is told when a managed SSH key is deleted, to stop serving it (App.DropSSHKey).
func WithSSHKeys ¶ added in v0.3.35
func WithSSHKeys(store SSHKeyStore) Option
WithSSHKeys enables /api/v1/ssh-keys (LOOM-138).
func WithSSHMigration ¶ added in v0.3.42
func WithSSHMigration(resolve SSHConfigResolver) Option
WithSSHMigration enables POST /targets/{id}/migrate-ssh.
func WithSessionMaxAge ¶ added in v0.3.58
WithSessionMaxAge overrides a session's absolute lifetime (defaultSessionMaxAge); 0 means none, only the sliding window.
func WithSessionTTL ¶
WithSessionTTL overrides the default sliding-expiration window.
func WithStaticDir ¶
WithStaticDir configures Server to serve a built single-page-app from dir for any request whose path does not start with /api/ — the web client's Vite build output (design spec docs/design/web-client-design.md, "Hosting / serving integration"; GitHub issue LOOM-33). A request that resolves to a real file under dir is served as-is (correct Content-Type via http.FileServer); anything else — an unknown path, or a client-side route like /conversations/abc123 that only exists in the SPA's own router — falls back to dir/index.html, so a hard refresh on a deep link gets the SPA shell instead of a 404. Unset (the default): every such request still 404s, unchanged from before this option existed.
func WithStreamHeartbeat ¶ added in v0.3.39
WithStreamHeartbeat overrides the stream's heartbeat interval, which is also how often an open stream re-checks its session. For tests.
func WithStreamPollInterval ¶
WithStreamPollInterval overrides the conversation-stream endpoint's default polling interval (see defaultStreamPollInterval). Mainly for tests, so they don't wait a full production-length interval per event.
func WithTargetProber ¶
func WithTargetProber(p TargetProber) Option
WithTargetProber enables POST /api/v1/targets/{id}/probe (LOOM-86).
func WithTaskCanceller ¶
func WithTaskCanceller(c TaskCanceller) Option
WithTaskCanceller enables POST /api/v1/tasks/{id}/cancel (LOOM-99).
func WithTaskTurns ¶
func WithTaskTurns(t TaskTurnStore) Option
WithTaskTurns enables GET /api/v1/tasks/{id}/transcript (LOOM-91).
func WithWebBundles ¶
func WithWebBundles(web WebBundles) Option
WithWebBundles serves the web client from whichever bundle web says is current, read per request so an update or rollback takes effect at once, and enables /api/v1/web/*. It takes the place of WithStaticDir.
func WithWorkspaceManager ¶
func WithWorkspaceManager(m WorkspaceManager) Option
WithWorkspaceManager enables DELETE and PATCH /api/v1/workspaces/{id} (LOOM-70).
type Plugins ¶ added in v0.3.68
type Plugins interface {
Available(ctx context.Context) ([]plugins.Available, error)
Install(ctx context.Context, r plugins.InstallRequest) (*plugins.View, error)
Get(ctx context.Context, id string) (*plugins.View, error)
List(ctx context.Context) ([]*plugins.View, error)
SetConfig(ctx context.Context, id string, config map[string]any) (*plugins.View, error)
Enable(ctx context.Context, id string) (*plugins.View, error)
Disable(ctx context.Context, id string) (*plugins.View, error)
Upgrade(ctx context.Context, id string) (*plugins.View, error)
Check(ctx context.Context, id string) (*plugins.View, error)
Uninstall(ctx context.Context, id, targets string) error
}
Plugins backs /api/v1/plugins (LOOM-178, docs/design/target-providers.md §1.5, §5): the catalog of available plugins and the installed ones' lifecycle. Satisfied by *plugins.Manager. Secrets go in and never come out: every view carries them as set or not set.
type RouterSettings ¶ added in v0.3.64
type RouterSettings interface {
Tiers() []llmrouter.TierView
Set(ctx context.Context, tier string, u llmrouter.TierUpdate, actor string) (llmrouter.TierView, error)
Clear(ctx context.Context, tier, actor string) error
Test(ctx context.Context, tier string) (llmrouter.TestResult, error)
Changes(ctx context.Context, limit int) ([]*registry.RouterSettingsChange, error)
}
RouterSettings backs /api/v1/settings/router (LOOM-185, docs/design/router-settings.md): the router model's provider, base URL, model and key per tier, changed without a restart. Satisfied by *llmrouter.Settings. Keys go in and never come out.
type SSHConfigResolver ¶ added in v0.3.42
type SSHConfigResolver func(ctx context.Context, t *registry.Target, keyFile string) (*targets.SSHConfigPlan, error)
SSHConfigResolver plans a config-mode target as a managed one, with the key file named, if any — targets.ResolveSSHConfig.
type SSHKeyStore ¶ added in v0.3.35
type SSHKeyStore interface {
CreateSSHKey(ctx context.Context, k *registry.SSHKey) error
ListSSHKeys(ctx context.Context) ([]*registry.SSHKey, error)
DeleteSSHKey(ctx context.Context, id string) error
ListTargets(ctx context.Context) ([]*registry.Target, error)
}
SSHKeyStore backs /api/v1/ssh-keys (LOOM-138): the SSH keys Loomux manages for reaching targets. Satisfied by any registry.Store; it lists targets itself to say which ones use a key.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the client-facing HTTP API. It implements http.Handler — callers decide how to actually listen (http.ListenAndServe, httptest.Server, etc.), keeping this package transport-agnostic about TLS/networking (deployment assumption: plain HTTP behind a reverse proxy that terminates TLS — see README.md).
func NewServer ¶
func NewServer(dispatcher Dispatcher, sessions SessionStore, workspaces WorkspaceLister, tasks TaskLister, messages MessageLister, attachInfo AttachInfoStore, targets TargetStore, passwordHash []byte, opts ...Option) *Server
NewServer constructs a Server. passwordHash is a bcrypt hash (see HashPassword) — the single v1 user's credential, verified at login; never a plaintext password.
func (*Server) EndStreams ¶ added in v0.3.45
func (s *Server) EndStreams()
EndStreams ends every open conversation stream (LOOM-147). A stream never goes idle on its own, so an http.Server shutdown would otherwise wait out its whole deadline for them: register this with http.Server.RegisterOnShutdown. Clients see the stream end and reconnect to whichever server is up next.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler. Any /api/... path outside /api/v1/ (a different or unsupported version, or the bare /api/ root) is rejected here, before reaching the mux — design spec §10 axis 1: "a mismatch is a clear rejection ... not silent breakage," structured rather than a bare 404. This check is a simple path-prefix test done ahead of routing, not a registered ServeMux pattern, specifically so it can never shadow a real /api/v1/... route hit with the wrong HTTP method (ServeMux's own 405 for that case is the correct, distinct response — a known path used incorrectly, not an unknown version).
Every other path (anything not equal to /api and not starting with /api/) goes to the static handler when WithStaticDir was used (LOOM-33) — never to mux, so a static build can never shadow or be shadowed by an /api/v1/ route. Without WithStaticDir, those paths 404 via http.NotFound, matching this package's behavior before this option existed. The bare "/api" case (no trailing slash) is checked explicitly alongside the "/api/" prefix — strings.HasPrefix alone would miss it, letting an API-shaped path fall through to the static handler and get served the SPA shell instead of the same unsupported-path rejection "/api/v2/..." already gets.
type SessionStore ¶
type SessionStore interface {
CreateSession(ctx context.Context, s *registry.Session) error
GetSessionByTokenHash(ctx context.Context, tokenHash string) (*registry.Session, error)
ListSessions(ctx context.Context) ([]*registry.Session, error)
TouchSession(ctx context.Context, id string, lastUsedAt time.Time) error
DeleteSession(ctx context.Context, id string) error
}
SessionStore is the session-related slice of registry.Store this package needs — satisfied structurally by any registry.Store (including *app.App.Store()). ListSessions backs LOOM-47's session-listing/revoke-by-id endpoints; DeleteSession already served self-revoke-only (/logout) and is reused unchanged for revoke-by-id.
type TargetProber ¶
type TargetProber interface {
ProbeTarget(ctx context.Context, targetID string) (*registry.TargetHealth, []*registry.TargetAgent, error)
}
TargetProber probes a target's health and agent CLIs now and records the results (LOOM-86) — satisfied by *app.App. Optional: with none configured (WithTargetProber), the probe endpoint answers 501.
type TargetStore ¶
type TargetStore interface {
CreateTarget(ctx context.Context, t *registry.Target) error
GetTarget(ctx context.Context, id string) (*registry.Target, error)
ListTargets(ctx context.Context) ([]*registry.Target, error)
UpdateTarget(ctx context.Context, t *registry.Target) error
DeleteTarget(ctx context.Context, id string) error
// ListTargetAgents backs GET /targets/{id}/agents (LOOM-71): the
// recorded agent CLI availability on a target.
ListTargetAgents(ctx context.Context, targetID string) ([]*registry.TargetAgent, error)
// ListTargetHealth backs each target's health in GET /targets
// (LOOM-86); a target never probed has no entry.
ListTargetHealth(ctx context.Context) ([]*registry.TargetHealth, error)
}
TargetStore is the target-CRUD slice of registry.Store behind the /api/v1/targets endpoints (LOOM-59). Those store methods existed and were tested from the start but had no production caller at all, which left registering a target possible only by hand-writing a row into sqlite on the deployment host — and so left a fresh deployment with nowhere to dispatch work. Satisfied structurally by any registry.Store, mirroring this package's other narrow seams.
type TaskCanceller ¶
type TaskCanceller interface {
CancelTask(ctx context.Context, taskID string) (dispatchID string, err error)
}
TaskCanceller cancels a running task (LOOM-99): through the dispatch driving it if there is one, else directly. It returns the dispatch it cancelled, if any; registry.ErrNotFound for an unknown task and orchestrator.ErrTaskInactive for one that has ended. Satisfied by *app.App. Optional: with none configured (WithTaskCanceller), the endpoint answers 501.
type TaskLister ¶
TaskLister is the unfiltered task-listing slice of registry.Store this package needs to serve conversation listing/history (LOOM-18) — satisfied structurally by any registry.Store. Unfiltered because a conversation isn't pinned to one workspace: the router can route the same conversation_id to a different workspace on a later message, so grouping/filtering by conversation has to happen above ListTasksByWorkspace's per-workspace scope.
type TaskTurnStore ¶
type TaskTurnStore interface {
GetTask(ctx context.Context, id string) (*registry.Task, error)
ListTaskTurnsPage(ctx context.Context, taskID, beforeID string, limit int) ([]*registry.TaskTurn, bool, error)
}
TaskTurnStore is what GET /tasks/{id}/transcript reads (LOOM-91) — satisfied by any registry.Store.
type WebBundles ¶
type WebBundles interface {
Root() string
Current() *webbundle.Release
Previous() *webbundle.Release
Installed() bool
Enabled() bool
Latest(ctx context.Context) (*webbundle.Release, error)
UpdateAvailable(latest *webbundle.Release) bool
Install(ctx context.Context) (*webbundle.Release, error)
Rollback() (*webbundle.Release, error)
}
WebBundles is the web client's bundle manager (LOOM-118, webbundle.Manager): which bundle to serve, and updating it in place.
type WorkspaceLister ¶
type WorkspaceLister interface {
ListWorkspaces(ctx context.Context) ([]*registry.Workspace, error)
}
WorkspaceLister is the workspace-listing slice of registry.Store this package needs — satisfied structurally by any registry.Store (including *app.App.Store()), mirroring SessionStore's narrow-seam pattern.
type WorkspaceManager ¶
type WorkspaceManager interface {
// DeleteWorkspace deletes a workspace and its tasks and kills their
// sessions, returning those it couldn't kill. registry.ErrNotFound for
// an unknown id; a *registry.ConflictError says what blocks it.
DeleteWorkspace(ctx context.Context, id string) ([]string, error)
// SetWorkspaceStatus moves a workspace to idle (back in service) or
// archived (out of it); errors as for DeleteWorkspace.
SetWorkspaceStatus(ctx context.Context, id string, status registry.WorkspaceStatus) error
}
WorkspaceManager deletes and repairs workspaces (LOOM-70). Satisfied by *app.App. Optional: with none configured (WithWorkspaceManager), DELETE and PATCH /api/v1/workspaces/{id} answer 501.