app

package
v0.3.97 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 32 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

app

Composition root. Wires the workspace registry, TargetExecutor, orchestrator, completion detection, credential vault, and router dispatch pipeline (design spec §2-§7) into a runnable App with a single Dispatch operation.

The versioned HTTP client API and login-gated auth (design spec §9, §10 axis 1) are out of scope here by design — this package only proves the whole stack constructs and is dispatchable, exposing Dispatch and Store() as the narrow surface a client-facing layer needs. The api package (LOOM-9, shipped 2026-08-30) is that layer: it imports this package and wraps an *App rather than re-wiring these pieces itself, via the same structural, narrow-interface seam (api.Dispatcher) this package's own RoutingModel/CompletionDetector seams use elsewhere. cmd/loomuxd is the thin CLI entrypoint that wires both app.Build and api.NewServer together (plus a -message flag for dispatching one message directly, bypassing HTTP/auth entirely, for local debugging).

Layout

  • config.go — Config, LoadConfig(): reads LOOMUX_DB_PATH (optional, defaults to loomux.db), LOOMUX_MARKER_DIR (optional), LOOMUX_MASTER_KEY (optional — the credential vault's AES-256 key; unset means credential operations fail per registry/sqlite's own fail-fast behavior, not a startup requirement here), LOOMUX_SSH_PROXY (optional, socks5://host:port: managed targets' proxy, LOOM-138; anything else is a startup error), the router model's own config via router/llmrouter.ConfigFromEnv(), and the idle reaper's timing (LOOMUX_REAP_IDLE_THRESHOLD default 24h, LOOMUX_REAP_INTERVAL default 1h — design spec's continuation model, LOOM-16), the target health probe's interval (LOOMUX_TARGET_PROBE_INTERVAL default 5m, LOOM-86), and LOOMUX_LOG_LEVEL (debug/info/warn/error, default info) for the JSON-on-stderr Config.Logger that build hands the router (LOOM-63; a nil Logger logs nothing). A zero ReapIdleThreshold/ReapInterval on a Config built directly (not via LoadConfig — existing tests do this) isn't an error: build applies the same defaults, so callers don't need to set every field.

  • app.go — App, Build(cfg), DefaultAgentTypes(): the actual wiring order is storage → executor factory → completion detection → orchestrator → credential resolver → LLM-backed routing model → router → a background idle-reaper goroutine (orchestrator.Reaper.Run, started here and stopped by App.Close). DefaultAgentTypes() is the production router.AgentTypeRegistry — "claude-code" (launch template claude) and "codex" (launch template codex, LOOM-22 — proves the interface generalizes beyond one CLI), both declaring Tier: TierMarker symmetrically, plus the "" bookkeeping entry completion detection needs for shell-kind (provisioning) tasks — deliberately excluded from what's offered to the router model as a real agent-type choice.

    build passes the configured marker directory (cfg.MarkerDir; empty means each target's per-user default, which both sides resolve with completion.ResolveMarkerDir) unchanged to both completion.NewDetector and router.New — the two halves of LOOM-32's fix (see router/README.md's "Getting a task ID into a launched agent" section) that must agree on where marker files live: Router computes the path a launched process is told to touch, Detector is what actually watches for it. Build wraps an unexported, parameterized build(cfg, agentTypes) — the public signature always uses DefaultAgentTypes(); the split exists purely so tests can wire a fast TierIdle agent type against a real tmux session without needing a real claude CLI installed.

Testing

app_test.go runs a real end-to-end dispatch (real SQLite via a temp file, real llmrouter.Model hitting an httptest.Server standing in for the LLM vendor) through the answer_directly path, which needs no real tmux/agent CLI. continuation_test.go goes further — a real local tmux session carries two turns of a conversation (LOOM-13: the second turn's message is sent into the same session, not a fresh one, until the fake LLM server's second Relay call says Done: true) — using build directly with a custom agent type, per the note above. reap_test.go proves the background reaper started inside build actually tears down a real, idle tmux session on its own — no further Dispatch calls, just waiting — then that a follow-up Dispatch for the same conversation transparently picks up with a fresh session (the router-level fallback, LOOM-16). This test is what caught a real bug in the reaper's own filtering logic (see orchestrator/README.md's Reap section) before it shipped. Run go test ./app/....

Documentation

Overview

Package app is Loomux's composition root: it wires the workspace registry, TargetExecutor, orchestrator, completion detection, credential vault, and router dispatch pipeline (design spec §2-§7) into a runnable App with a single Dispatch operation. The versioned HTTP/WS client API and login-gated auth (design spec §9, §10 axis 1, LOOM-9) are explicitly out of scope here — this package only proves the whole stack constructs and is dispatchable; a later HTTP/WS/auth layer is expected to wrap an *App rather than re-wire these pieces itself. cmd/loomuxd is the thin CLI entrypoint built on this package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultAgentTypes

func DefaultAgentTypes() router.AgentTypeRegistry

DefaultAgentTypes is the production registered-agent-type set: "claude-code" and "codex" (LOOM-22 — proves the agent-type interface generalizes beyond a single CLI), both built by package agents. Both are TierMarker, and Loomux owns the whole completion path (LOOM-75): router.launchAgent tells the launched process its marker path (LOOMUX_MARKER_PATH, LOOM-32), and each adapter's CompletionHookArgs install the hook that touches it — claude's Stop hook via --settings, codex's notify via -c — per launch, with nothing configured on the target beforehand. The "" entry configures completion detection for shell-kind (provisioning) tasks only (router/agenttype.go's own doc comment) — it is never a real dispatchable agent type and is deliberately excluded from what's offered to the router model by dispatchableAgentTypeNames below.

Types

type App

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

App is the fully wired Loomux domain layer, exposed through the one operation this package's "minimal internal interface" needs — Dispatch — plus lifecycle cleanup and read access to the underlying Store for a client-facing layer (api.Server) that needs its own session storage in the same database.

func Build

func Build(cfg Config) (*App, error)

Build wires the full domain layer (design spec §2-§7) from cfg: storage -> executor factory -> completion detection -> orchestrator -> credential resolver -> LLM-backed routing model -> router. On any failure after the store opens successfully, the store is closed before returning the error.

func (*App) AgentTypeNames

func (a *App) AgentTypeNames() []string

AgentTypeNames are the agent types this server can launch, sorted (LOOM-122: what a target's allowed_agent_types may name).

func (*App) CancelTask

func (a *App) CancelTask(ctx context.Context, taskID string) (string, error)

CancelTask cancels a task (LOOM-99). A running task is the one its conversation's running dispatch drives — only one task is ever mid-turn — so it is cancelled through that dispatch, which ends the turn. Any other open task (left awaiting input, stopped at a prompt, or running with no dispatch after a restart) is cancelled directly — see router.Router.CancelTask — never through a dispatch driving some other task of the conversation. Satisfies api.TaskCanceller.

func (*App) Close

func (a *App) Close() error

Close stops the background idle reaper (LOOM-16) and releases the store's resources (its DB connection).

func (*App) DeleteWorkspace

func (a *App) DeleteWorkspace(ctx context.Context, id string) ([]string, error)

DeleteWorkspace deletes a workspace, its tasks and their sessions (LOOM-70) — see orchestrator.Orchestrator.DeleteWorkspace. Satisfies api.WorkspaceManager.

func (*App) Dispatch

func (a *App) Dispatch(ctx context.Context, conversationID, message, workspaceHint string) (string, error)

Dispatch routes one chat message through the full pipeline. See router.Router.Dispatch. workspaceHint (LOOM-46) is an optional, advisory workspace ID — empty means no hint — surfaced as a plain string rather than a router.DispatchOption specifically so callers like api.Server's Dispatcher interface don't need to import the router package just to supply it (mirroring api.Dispatcher's own narrow-seam rationale).

func (*App) Dispatches

func (a *App) Dispatches() *dispatch.Service

Dispatches is the dispatch-job service (LOOM-80) the client API submits chat messages to: each runs through the router as a job on a server-owned context, outliving the request that submitted it.

func (*App) DrainDispatches

func (a *App) DrainDispatches() error

DrainDispatches stops accepting dispatch jobs and gives in-flight ones the configured drain time to finish; any still running are then marked interrupted, their tasks left for startup reconciliation (LOOM-82). Call it on shutdown before the HTTP server's own Shutdown, so blocking requests waiting on a job get their answer first.

func (*App) DropSSHKey added in v0.3.41

func (a *App) DropSSHKey(id string)

DropSSHKey stops serving a managed SSH key (LOOM-138): the key was deleted.

func (*App) HealthChecker

func (a *App) HealthChecker() *health.Checker

HealthChecker returns the deep-health checker for api.Server to expose on /api/v1/health and /api/v1/health/deep (LOOM-105).

func (*App) Machines added in v0.3.69

func (a *App) Machines() *providers.Manager

Machines serves the machine side of /api/v1/targets (LOOM-178): targets plugins made.

func (*App) Metrics

func (a *App) Metrics() *metrics.Metrics

Metrics returns the Prometheus metrics bundle so cmd/loomuxd can expose it on a scraper port (LOOM-103).

func (*App) Plugins added in v0.3.68

func (a *App) Plugins() *plugins.Manager

Plugins serves /api/v1/plugins (LOOM-178): the plugin system's catalog and installed instances.

func (*App) ProbeTarget

func (a *App) ProbeTarget(ctx context.Context, targetID string) (*registry.TargetHealth, []*registry.TargetAgent, error)

ProbeTarget probes a target's health and agent CLIs now and records the results (LOOM-86) — see router.Router.ProbeTarget. Satisfies api.TargetProber.

func (*App) RouterSettings added in v0.3.64

func (a *App) RouterSettings() *llmrouter.Settings

RouterSettings serves /api/v1/settings/router (LOOM-185): the router model's tiers as stored through Settings over the environment's, applied to the running model without a restart.

func (*App) SetWorkspaceStatus

func (a *App) SetWorkspaceStatus(ctx context.Context, id string, status registry.WorkspaceStatus) error

SetWorkspaceStatus reopens (idle) or archives a workspace (LOOM-70) — see orchestrator.Orchestrator.ReopenWorkspace and ArchiveWorkspace. Satisfies api.WorkspaceManager.

func (*App) StartRetention added in v0.3.74

func (a *App) StartRetention(sessionTTL, sessionMaxAge time.Duration)

StartRetention starts the retention sweep (LOOM-193): every retentionSweepInterval, and once now, it deletes sessions expired longer than Config.SessionRetention, dispatches finished longer than Config.DispatchRetention and confirmations resolved longer than Config.ConfirmationRetention. Messages are kept. sessionTTL and sessionMaxAge are the session lifetime the client API enforces (its sliding window and absolute lifetime, 0 for none), which say when a session expired. Close stops it; only the first call starts it.

func (*App) Store

func (a *App) Store() registry.Store

Store returns the underlying registry.Store — e.g. for api.Server's session storage, which must live in the same database as everything else rather than a second, separately managed connection.

type Config

type Config struct {
	// DBPath is the SQLite database file path. Defaults to "loomux.db"
	// in the working directory if unset — not a secret, so (unlike the
	// fail-fast-on-malformed values below) a default is appropriate.
	DBPath string
	// MarkerDir is completion.NewDetector's marker file directory.
	// Empty uses completion's own package default.
	MarkerDir string
	// TmuxSocket is the tmux socket name every session runs on
	// (LOOMUX_TMUX_SOCKET); empty means targets.DefaultTmuxSocket. Give
	// two instances driving the same targets different ones.
	TmuxSocket string
	// LocalTargetsOff (LOOMUX_LOCAL_TARGETS=off; the container image sets
	// it) turns local targets off (LOOM-141): a local target's agents run
	// as loomuxd's own user, so they're fully trusted. The zero value
	// leaves them on. See targets.LocalTargets.
	LocalTargetsOff bool
	// MasterKey is the credential vault's AES-256 key, or nil if
	// LOOMUX_MASTER_KEY is unset. Optional at this layer: registry/sqlite
	// already fails fast on any credential operation that actually needs
	// it, rather than this process refusing to start without one.
	MasterKey []byte
	// SSHProxy is the SOCKS5 proxy (host:port) managed targets are
	// reached through unless they opt out (LOOMUX_SSH_PROXY, as
	// socks5://host:port; LOOM-138); "" for none.
	SSHProxy string
	// Router is the LLM-backed RoutingModel's own configuration.
	Router llmrouter.Config
	// ReapIdleThreshold is how long a task can go without a state change
	// (design spec's continuation model, LOOM-16 — see
	// orchestrator.Reaper's doc comment for exactly what "idle" means)
	// before its session is torn down. Zero means "unset" — build applies
	// defaultReapIdleThreshold, the same way LoadConfig does; existing
	// callers that construct Config directly (tests) get sensible
	// behavior without needing to set every field.
	ReapIdleThreshold time.Duration
	// ReapInterval is how often the idle reaper sweeps. Same zero-means-
	// default handling as ReapIdleThreshold.
	ReapInterval time.Duration
	// TargetProbeInterval is how often every target's health is probed
	// (LOOM-86). Same zero-means-default handling as ReapIdleThreshold.
	TargetProbeInterval time.Duration
	// Logger receives the router's structured records (LOOM-63). Nil —
	// as in tests that construct Config directly — means nothing is
	// logged; LoadConfig always sets one.
	Logger *slog.Logger
	// AgentProfiles overrides agent-types' launch profiles (LOOM-78):
	// permission/sandbox args, workspace pre-trust, first prompt as an
	// argument. Keyed by agent-type name. Nil keeps every default (see
	// agents/README.md); naming an unregistered agent-type fails Build.
	AgentProfiles map[string]router.ProfileOverride
	// DispatchMaxDuration bounds one dispatch job end to end (LOOM-80).
	// Zero means the dispatch package's own default.
	DispatchMaxDuration time.Duration
	// DispatchDrain is how long shutdown lets in-flight dispatch jobs
	// finish before marking them interrupted (LOOM-80). Zero means
	// defaultDispatchDrain.
	DispatchDrain time.Duration
	// Notify configures turn notifications (LOOM-102); off when
	// Notify.NtfyURL is empty.
	Notify NotifyConfig
	// TurnRetention is how long each task turn's transcript is kept
	// (LOOM-122); zero keeps them. LoadConfig defaults it to
	// defaultTurnRetention.
	TurnRetention time.Duration
	// EventRetention is how long the dispatch audit trail is kept
	// (LOOM-110); zero keeps it. LoadConfig defaults it to
	// defaultEventRetention.
	EventRetention time.Duration
	// PluginBundleDir, PluginDir and PluginSocketDir are where plugins
	// are found (LOOM-178, docs/design/target-providers.md §1.8): the
	// image's bundled plugins, the operator's, and sidecars' sockets.
	// An empty PluginDir means plugins/ beside the database; the other
	// two empty mean nothing is looked for there.
	PluginBundleDir string
	PluginDir       string
	PluginSocketDir string
	// SessionRetention is how long a session row is kept after it
	// expired, DispatchRetention how long a dispatch is kept after it
	// finished, and ConfirmationRetention how long a confirmation is kept
	// after it was answered or expired (LOOM-193); zero keeps them.
	// LoadConfig defaults them to defaultSessionRetention,
	// defaultDispatchRetention and defaultConfirmationRetention. Messages
	// are kept.
	SessionRetention      time.Duration
	DispatchRetention     time.Duration
	ConfirmationRetention time.Duration
	// contains filtered or unexported fields
}

Config is the process configuration, loaded from environment variables (this repo's established convention — see registry/sqlite.KeyFromEnv, router/llmrouter.ConfigFromEnv).

func LoadConfig

func LoadConfig() (Config, error)

LoadConfig reads Config from the environment, failing fast on malformed (as opposed to merely absent) values — an unset LOOMUX_MASTER_KEY is fine (MasterKey stays nil); an invalid one is not.

type NotifyConfig

type NotifyConfig struct {
	// NtfyURL is the ntfy server ("https://ntfy.sh"), NtfyTopic the topic
	// posted to and NtfyToken an optional access token. An empty NtfyURL
	// turns notifications off.
	NtfyURL, NtfyTopic, NtfyToken string
	// Events are the kinds notified ("done", "failed", "needs_you").
	Events map[notify.Kind]bool
	// MinDuration skips turns shorter than this: the user was likely
	// still watching.
	MinDuration time.Duration
	// PublicURL is where the web client is served, for each
	// notification's link to its conversation; empty means no link.
	PublicURL string
}

NotifyConfig configures turn notifications (LOOM-102).

Jump to

Keyboard shortcuts

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