api

package
v0.3.162 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 38 Imported by: ? modules, 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

api

The client-facing HTTP surface (design spec §9, §10 axis 1): real, login-gated Bearer-token auth in front of app.App.Dispatch — "there is no 'it's just me so no auth' shortcut" (§9), since web/Android/iOS clients are reachable outside the server process's own trust boundary.

Design

Confirmed with the user before building (security/deployment tradeoffs, not engineering taste):

  • Deployment model: plain HTTP behind a reverse proxy. Server serves plain http.Handler — it does not terminate TLS itself. The expectation is a reverse proxy (Caddy/nginx) or an overlay network (Tailscale) in front handling TLS; loomuxd binds to whatever LOOMUX_HTTP_ADDR says (default :8080) with no cert/key story of its own. Running loomuxd directly exposed to an untrusted network over plain HTTP would leak the password and bearer tokens in transit — that's the proxy's job to prevent, not this package's.
  • Auth mechanism: password login → opaque Bearer session token, not cookies (native mobile clients don't do cookies well) and not a static API key (no session concept, no per-device revocation, "here's the proof you don't cut corners" — spec §9's own framing — points at a real login flow). POST /api/v1/login checks a bcrypt hash (LOOMUX_AUTH_PASSWORD_HASH, generate with loomuxd -hash-password) — the same env-at-process-start convention as the router's own credential (LOOM-12) and the vault's master key (LOOM-7), since v1 is single-user. On success, a random 32-byte token (crypto/rand) is returned to the client exactly once; only its SHA-256 hash is ever persisted (registry.Session.TokenHash) — a database compromise alone doesn't hand out working credentials. Every other request sends it as Authorization: Bearer <token> (the scheme in any case, LOOM-175).
  • Request bodies are one JSON value, at most 1 MiB, arriving within 30 s (LOOM-132): over the limit is 413 whatever the content (LOOM-175), and anything but whitespace after the value is 400.
    • The user's stated plan is SSO/OAuth later. The seam for that is the session layer itself, not a shared Authenticator interface: however a future auth method proves identity (an OAuth callback, say), it ends the same way this one does — mint a token, CreateSession, return it to the client. checkPassword (auth.go) is the one thing that would get an alternative, not the session/middleware machinery around it.
  • Session lifetime: long sliding expiration + explicit logout. A session stays valid as long as it's used at least once within SessionTTL (default 30 days, LOOMUX_SESSION_TTL overridable, time.ParseDuration syntax) — requireAuth refreshes LastUsedAt on every authenticated request. However much it's used, a session also ends SessionMaxAge after it was created (LOOM-175; default 90 days, LOOMUX_SESSION_MAX_AGE, 0 for no limit), so a token that leaked doesn't stay good for as long as it keeps being used; the device signs in again. POST /api/v1/logout deletes the session row outright, for revoking a lost device immediately rather than waiting out the window. Logout and DELETE /sessions/{id} also end that session's open conversation streams and blocking dispatch waits at once (LOOM-144, LOOM-182), and an open stream re-checks its session at each heartbeat, so it ends within 15 s of the session expiring. A stream doesn't itself count as use: only requests refresh LastUsedAt, so a tab left streaming doesn't keep a session alive forever.
  • /login brute-force protection: global exponential backoff, not a hard lockout (LOOM-15). throttle.go's loginThrottle is one in-memory counter for the whole process — deliberately not scoped per-IP or per-user: there's no username here to scope by (loginRequest is just {password} — single-user, single credential), and behind the confirmed reverse-proxy deployment model every request's RemoteAddr is typically the proxy's own address anyway, so IP-scoping would either do nothing (using RemoteAddr) or require trusting a client-spoofable X-Forwarded-For header — a global counter sidesteps that trust question entirely. Backoff, not a lockout, is also deliberate: on a single-account system a hard lockout is itself a denial-of-service vector (an attacker who can't guess the password can still lock the real user out just by failing repeatedly). Each failure doubles the wait before the next attempt is even checked (1s, 2s, 4s, ... capped at 30s); a success resets it to zero. A throttled attempt gets 429 with Retry-After — including a correct password presented while throttled, so the throttle state itself never leaks whether a guess would have worked. Still no audit log of failed attempts (no logging convention in this repo to hook into yet), and state resets on restart (in-memory only) — acceptable since the confirmed deployment has no attacker-triggerable restart path. Two refinements:
    • An attempt is admitted before its password is checked (LOOM-142): while one is being checked, others get 429 too, so attempts sent together can't all slip past the backoff at once.
    • Known devices (LOOM-151): a global counter alone let anyone keep the owner out by failing once per backoff window. A successful login returns a device token (a random id plus an HMAC keyed from the password hash: stateless, unforgeable, void once the password changes); a login that sends it back is throttled on that device's own backoff (device.go). Strangers' failures still drive the global one, so a browser that has never logged in (or lost its token) can still be held at the global backoff. Anyone holding the password hash could mint device tokens, but could equally crack the hash offline.
  • Browser hardening headers (LOOM-143, headers.go): every response carries X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer and X-Frame-Options: DENY, plus HSTS when the request came over HTTPS (directly or per the proxy's X-Forwarded-Proto). API responses get Cache-Control: no-store and a deny-all CSP; the web client gets a CSP limiting script, connections and framing to this origin. index.html's inline scripts (the pre-paint theme snippet) are allowed by hash, computed from the file served, since a web update can change it without a server release.
  • API version mismatch handling is real but URL-only (LOOM-10): any /api/... path outside /api/v1/ — a future /api/v2/, a typo, the bare /api/ root — gets a structured 404 naming api.APIVersion (ServeHTTP, ahead of routing so it can never shadow a real /api/v1/ route hit with the wrong HTTP method, which correctly gets a 405 instead). Inside /api/v1/, a path no route has is a 404 and a method its routes don't take a 405, both {error, code} (handleNoRoute, LOOM-161). GET /api/v1/version (unauthenticated) lets a client check api.APIVersion + version.Version before it even logs in. This satisfies §10 axis 1's "a mismatch is a clear rejection... not silent breakage" for the one version that exists — there's still no negotiation protocol beyond the URL itself (e.g. a client declaring a minimum/maximum it accepts), since nothing has needed one with only a v1 to compare against.
  • No idle-session reaper. A session past its TTL is only actually deleted the next time someone tries to use it (opportunistic cleanup in requireAuth) — an abandoned expired row otherwise just sits in the table. Harmless bloat for a single-user table, same shape as LOOM-16's idle-conversation-reaper gap.
  • Static SPA serving is opt-in and lives outside the API surface entirely (LOOM-33). WithStaticDir/LOOMUX_STATIC_DIR (unset by default) points Server at a built web-client directory (loomux/web's Vite output); any request whose path is neither /api nor starts with /api/ is served from there, with fallback to index.html for anything that isn't a real file — a browser refresh on a client-side route like /conversations/abc123 gets the SPA shell instead of a 404. A missing path under /assets/, or one whose last segment has an extension (.js, .css, .ico, …), is a plain 404 instead (LOOM-158): a chunk from the bundle before a web update then fails to load cleanly rather than arriving as HTML. Routed entirely in ServeHTTP ahead of mux, mirroring the existing /api/ version check already there — /api and every /api/* path never reach the static handler (the bare /api path, with no trailing slash, is checked explicitly alongside the /api/ prefix so it can't slip through and get served as static content) and the static handler never reaches mux, so neither can shadow the other. Not built as part of LOOM-23/LOOM-24 (the web client itself); this is the small server-side hosting addition their design flagged as a dependency.

Errors

Every /api/v1 error answer has the body {error, code}: error is human-readable text (for display or logs; its wording may change), code a stable machine-readable name a client branches on instead of parsing the text. Both are always present. writeError (in server.go) sets the default code for the status; writeErrorCode sets a specific one.

Default codes, by status:

Status code
400 invalid_request
401 unauthorized
403 forbidden
404 not_found
405 method_not_allowed (with Allow)
409 conflict
413 too_large
422 unprocessable
429 rate_limited (e.g. the login backoff)
500 internal
501 not_implemented
502 bad_gateway
503 unavailable
any other error

Specific codes, where a handler tells apart a case a client can act on:

Code Where
conversation_busy POST /api/v1/dispatch 409 when the conversation already has a dispatch in flight; the body also carries that dispatch's dispatch_id
detach_failed POST /api/v1/tasks/{id}/release (Take back) and a forced POST /api/v1/tasks/{id}/takeover 502 when the holder's tmux clients couldn't be detached (the target didn't answer): nothing changes, the hold and the task's human_takeover stay; try again (LOOM-265)
hold_ended POST /api/v1/tasks/{id}/takeover/heartbeat 410 when the hold has ended; the body also carries ended_reason and the hold (LOOM-264)
idempotency_conflict POST /api/v1/dispatch 422 when the Idempotency-Key was already used for a different request
task_held POST /api/v1/tasks/{id}/takeover 409 when another session holds the task; the body also carries its hold. force takes it (LOOM-264)
task_inactive POST /api/v1/tasks/{id}/takeover 409 for a task that has ended and whose pane wasn't kept for a person (LOOM-264)
unsupported_api_version 404 for any /api path outside /api/v1; the body also carries supported_versions
unsupported_mode POST /api/v1/tasks/{id}/takeover 400 for mode: "watch" from a server older than watch holds (LOOM-264; before LOOM-271): no hold is taken. A server with watch holds never answers it, but a client that may meet an older one still handles it
watch_unsupported POST /api/v1/tasks/{id}/takeover 409 for mode: "watch" on a machine whose plugin has no read-only attach command (it doesn't declare targets.attach_read_only, refused the request or answered none; the error names the plugin: upgrade it), or isn't running to give it (start it and try again). No hold is taken, and no writable command is handed out in its place; attaching to drive still works (LOOM-272)
workspace_name_taken POST /api/v1/workspaces 409 when another workspace has the name (LOOM-215)

New codes may be added within v1 (a client should treat an unknown code like the status's default); a code once given to a case doesn't change. A failed blocking dispatch's 500 is a dispatch job body, not this envelope: it classifies the failure with error_class.

API v1 conventions

  • Identifiers. A resource's own id is id; a reference to another resource is <thing>_id (workspace_id, target_id, task_id). Three places predate the rule and keep their names for all of 1.x (API v1 freeze review, item 7): a dispatch's own id is dispatch_id (in POST /dispatch, GET /dispatches/{id}, a conversation's dispatches[] and the stream's dispatch_update); a row of GET /conversations names its conversation conversation_id, as a conversation has no other id; and the stream's message_added carries message_id (and task_id). Attach-info's task_id is the task asked about.
  • Enums are snake_case: task statuses and permission_mode since the freeze review (item 9). Agent-type names such as claude-code are identifiers, not enums, and keep their spelling.
  • Errors are {error, code} (see the error section), including the 404 for an /api/v1 path no route matches and the 405 for a method its routes don't take (LOOM-161; both were ServeMux's plain text before).
  • /web/* is an operations API outside the v1 stability promise (docs/release/versioning.md, "The API v1 contract").

Plugins (LOOM-178)

/api/v1/plugins is the plugin system (docs/design/target-providers.md §1): GET /plugins/available lists the catalog (every manifest found in the bundle directory, the operator's plugin directory and the sidecar sockets, with its trust and isolation), POST /plugins installs one with a label and a configuration validated against the manifest's schema, GET /plugins and GET /plugins/{id} show installed instances, PUT /plugins/{id}/config reconfigures (a secret left out keeps its value, "" clears it), POST /plugins/{id}/enable|disable| upgrade|check are the lifecycle verbs, and DELETE /plugins/{id} uninstalls (?targets=destroy|keep is required once the plugin owns machines; 409 otherwise). Secrets never come back: each shows in config as {"set": bool}. A plugin that installs but can't work answers 422 with the plugin as it is (status: error, status_reason), its row kept so the configuration can be fixed. 503 without LOOMUX_MASTER_KEY. The routes answer 404 on a server built without WithPlugins.

GET /plugins/{id}/targets is what an instance offers for a new machine, as its targets.describe says right now (LOOM-238): sizes ({name, cpu, memory, disk}, the limits, plus cpu_request and memory_request when a size asks for less than its limits, LOOM-241; the first the default), persistent_default, egress_options (the first the default; none only while the plugin finds network isolation enforced), image, max_environments (0: no quota) and environments. 404 for no such instance (or a server without machines), 409 when it isn't running or doesn't make machines.

Machines (LOOM-178)

A target a plugin made (docs/design/target-providers.md §2, §5). POST /targets with a plugin object ({id, size, persistent, egress}) asks that installed plugin for a machine: kind must be remote or absent and host, user, ssh_port, ssh_key_id, generate_ssh_key, ssh_proxy and workspace_root must be absent (400), since the plugin sets them; the answer is 201 with the target, its plugin.status creating, and the machine comes up in the background (poll GET /targets/{id}). Every target carries plugin (null for a registered host): the owning plugin, the machine's status and reason, progress (image_pull while a machine coming up pulls its image, else empty; LOOM-239), size, persistence, egress, image and digest, update_available, and the plugin's warnings. POST /targets/{id}/start, /stop and /recreate ({size?}) answer 202 with the target; 409 while a task runs there, for a stop of an ephemeral machine, when the plugin isn't running or was uninstalled, or for a registered host. DELETE /targets/{id} of a machine cascades: its workspaces with their tasks, its target-scoped credentials, the machine and its data, the generated key. scan-host-key, pin, DELETE …/pin and migrate-ssh answer 409 for a machine, and PUT refuses its connection fields (400). POST /credentials takes target_id; a credential scoped to a target goes with it when the target is deleted (a registered host's too), and one scoped to a workspace may name only the workspace's own target (400). Attach-info's attach_commands lists the plugin's ways in and the plain ssh form. Each entry is {via, command, argv?}: command is the line to show or paste, argv (LOOM-269) the same command as arguments to execute directly with no shell. argv is absent when a plugin gave none or gave one the server refused.

Layout

  • auth.go — HashPassword (bcrypt, used by loomuxd -hash-password and by callers configuring LOOMUX_AUTH_PASSWORD_HASH), checkPassword, token generation/hashing (newToken, hashToken).
  • device.go — loginDevices: per-device login backoff for browsers that logged in before (LOOM-151; see Design above).
  • throttle.go — loginThrottle: the global exponential-backoff counter behind /login (see Design above for why global/backoff, not per-IP/lockout).
  • config.go — Config, LoadConfig(): LOOMUX_AUTH_PASSWORD_HASH (required, validated as a real bcrypt hash), LOOMUX_HTTP_ADDR (optional, default :8080), LOOMUX_SESSION_TTL (optional, default 30 days), LOOMUX_SESSION_MAX_AGE (optional, default 90 days, 0 for no absolute limit), LOOMUX_STATIC_DIR (optional, default unset — static serving disabled).
  • server.go — Server (implements http.Handler), NewServer, Dispatcher/SessionStore (the narrow seams this package depends on — satisfied by *app.App and *app.App.Store() respectively, without importing app directly, mirroring router.RoutingModel/ orchestrator.CompletionDetector's minimal-interface pattern), the requireAuth middleware, APIVersion, WithStaticDir (opt-in static SPA serving with index.html fallback, LOOM-33 — see Design above), and the handlers:
    • POST /api/v1/login — {password, device?} → {token, device} (device: see Known devices above; send it back on the next login)

    • POST /api/v1/logout — auth-gated, revokes the presented token, ending its streams, waits and holds (holds as session_revoked, LOOM-265)

    • GET /api/v1/sessions — auth-gated (LOOM-47), every active session (every device/client currently holding a valid, unexpired Bearer token), most-recently-used first: {sessions: [{id, created_at, last_used_at, label, client_kind, current}, ...]}. label names the session's device and client_kind its client (web, tui, app, or "" when unknown; LOOM-268), so the right row can be revoked. current marks the session backing this request's own token, so a "your devices" UI can label one row without this API ever exposing a token or its hash. Wraps SessionStore.ListSessions and then applies the same time.Since(last_used_at) > sessionTTL expiry check requireAuth uses — ListSessions itself has no expiration concept (design spec: that's a decision for the layer that knows the configured TTL, same as registry.Session.LastUsedAt's own doc comment says), and without this filter an expired row would still list as active until someone happened to present its token and trip requireAuth's own opportunistic cleanup.

    • POST /api/v1/sessions {token_hash, label?, client_kind?} — auth-gated (LOOM-268; design in docs/design/tui-client-design.md, "The link flow"). A logged-in session approves a session for a token another client made, by its hash: token_hash is hex(sha256(token)), 64 lowercase hex digits, which is all the server ever stores of a token. The terminal client, which can't reach the login behind the deployment's auth proxy and never holds the password, makes its own token, shows the hash to the browser and polls GET /api/v1/sessions with the token (401) until this call makes the session exist (200). Returns 201 with the new session's row (current: false). label is at most 64 characters with no control characters; client_kind is tui, app, web or left out (400 otherwise, and for a malformed hash). 409 if a session already has the hash. 403 unless the caller's own session was made by POST /api/v1/login: a linked session can't link another, so a stolen terminal token can't mint itself successors that outlive its revocation. A linked session has the same sliding window and absolute lifetime as any other, and is revoked like any other. POST /api/v1/login now marks its sessions client_kind: web.

    • DELETE /api/v1/sessions/{id} — auth-gated (LOOM-47), revokes any session by id — the same underlying operation as /logout, generalized to any id from GET /api/v1/sessions (e.g. signing another device out remotely); revoking the current request's own session is allowed and behaves exactly like /logout. 204 on success, 404 if id doesn't name an existing session. Wraps SessionStore.DeleteSession. The session's streams, waits and holds end with it, as on /logout.

    • POST /api/v1/dispatch — auth-gated, {conversation_id?, message, workspace_hint?}, optional Idempotency-Key header (≤ 255 chars). Since LOOM-80 every request becomes a dispatch job (wraps Dispatcher, i.e. dispatch.Service): the job and its user message are stored before anything runs, and the turn runs on a server-owned context, so a client that disconnects mid-turn loses nothing — the result lands on the job and in the conversation's history. See docs/design/async-dispatch-design.md.

      • Blocking (?wait=true): waits for the job and answers 200 {reply, dispatch_id, conversation_id, status, …}, or 500 {error, error_class, dispatch_id, …} if it failed or was interrupted. A wait whose session ends (logout, DELETE /sessions/{id}, or expiry) is 401 at once, without the reply (LOOM-182); the job carries on and its result is in the conversation.
      • Async (the default, or Prefer: respond-async): 202 {dispatch_id, conversation_id, status} at once, with Location: /api/v1/dispatches/{id} (and Preference-Applied: respond-async when the header asked). ?wait=true with Prefer: respond-async is 400. (?async=true was dropped before 1.0 and is ignored.)
      • The default is one constant, dispatchAsyncByDefault in api/dispatch.go: async since the LOOM-81 web shipped (it was blocking while the deployed web still expected {reply}).
      • conversation_id empty starts a new conversation (its id is in the response). A non-empty one, like workspace_hint, must be 1–64 ASCII letters, digits, - or _ (a server-minted id, a UUID, always is), else 400 (LOOM-154): it is a path segment in GET /conversations/{id}, so anything else could be stored but never fetched back. A repeat with the same Idempotency-Key and the same body returns the original job and runs nothing (a retry of a new conversation's first message leaves conversation_id empty, as the original did); the same key with a different body is 422 (code idempotency_conflict). A conversation with a job still in flight answers 409 {error, code, dispatch_id} (code conversation_busy) naming it (LOOM-83 owns serializing instead). 503 while the server is shutting down.
      • A message over 36 KiB (targets.MaxPasteBytes, 32 KiB, plus a 4 KiB margin) is 413 (code too_large) before anything runs (LOOM-155): the router couldn't send it to an agent anyway (error class message_too_large), and it never reaches the router model.
      • A message to a conversation whose task a person holds (taken over from a terminal, see the holds below) isn't typed into it: the job fails with error_class held (LOOM-267), and its error names who holds it.
      • workspace_hint (LOOM-46) is optional — a client-supplied workspace ID (e.g. a chat UI already focused on that workspace's conversation) that's folded into the router model's prompt as advisory context only; the router model (design spec §6) keeps final authority over which workspace a message actually goes to.
    • GET /api/v1/dispatches/{id} — auth-gated (LOOM-80), one dispatch job: {dispatch_id, conversation_id, status, reply?, error?, error_class?, created_at, started_at?, finished_at?}, status one of queued, running, succeeded, failed, interrupted (shutdown or restart cut it off; error class interrupted); 404 if unknown.

    • GET /api/v1/workspaces — auth-gated (LOOM-19), lists registered workspaces sorted by name: {workspaces: [{id, name, target_id, status, tags, description, rolling_summary, last_used_at?}, ...]} (is_dynamic was removed before 1.0: every workspace is dynamic). Includes the router's matching metadata (tags/description/rolling_summary) and the usage timestamp now that the Phase 2 web fleet-status page consumes them (LOOM-44). Wraps WorkspaceLister.ListWorkspaces, a narrow seam mirroring SessionStore, satisfied structurally by *app.App.Store().

    • POST /api/v1/workspaces — auth-gated (LOOM-215), provisions a workspace on a chosen target, as a chat's provision_workspace does: {target_id, name, kind?, git_remote?, worktree?, description?, tags?}, kind one of empty, git_clone, existing_dir, git_worktree (default git_worktree with a worktree, git_clone with a git_remote, else empty). git_worktree (LOOM-228) is git -C <root>/<worktree.base> worktree add -b <branch> <root>/<name> <ref>: worktree: {base, ref?, branch?}, base a repository's directory under the target's workspace root (confined like the workspace), ref the commit the branch starts at (default the base's HEAD), branch the new branch (default loomux/<name>, so each workspace, one per dispatch, has its own). git's refusals (the branch exists, no such ref, not a repository) are the workspace's status_reason. A repeat is matched by name and target only: the base and branch aren't recorded. It answers once the workspace row exists: 202 with the workspace (status provisioning), a Location: /api/v1/workspaces/{id} to follow, and conversation_id, the conversation its provisioning run is recorded under (its command, output and events, as for any turn). The run goes on in the background: a stopped machine a plugin made is started first (waiting out its image pull, up to 40 minutes with the check; LOOM-242), the target checked, then the confined recipe runs (bounded by its 10 minutes), ending the workspace idle with its path or failed with status_reason. The same name on the same target from the same source again is 200 with that workspace (no second one); 400 for a request to correct (target_id/name missing, an unknown target, a name or remote outside the grammar); 409 workspace_name_taken when another workspace has the name (on another target, from another source, or one that failed or was archived: delete or reopen it); 501 on a server without provisioning.

    • GET /api/v1/workspaces/{id} — auth-gated (LOOM-215), one workspace as GET /workspaces lists it; what a client polls while one provisions. 404 if unknown.

    • DELETE /api/v1/workspaces/{id}[?remove_worktree=true] — auth-gated (LOOM-70): deletes the workspace, its tasks and their sessions ({sessions_not_killed}); its files stay. With remove_worktree=true (LOOM-228, for a git_worktree workspace) its worktree is removed from the target first (git worktree remove, found from the worktree itself; the branch stays). git's refusal of a worktree with changes not committed or untracked files, a directory that is a repository's own checkout or not git, or a credential still scoped to the workspace is 409 with why, and nothing is deleted; a directory already gone counts as removed. 400 for any other remove_worktree value.

    • GET /api/v1/conversations — auth-gated (LOOM-18), one summary row per distinct conversation_id, most-recently-updated first: {conversations: [{conversation_id, workspace_id, status, updated_at, preview}, ...]}. A conversation isn't a stored entity (no such table in the design spec) — this groups TaskLister.ListTasks by conversation_id, taking each conversation's most-recently-updated task as representative, since one conversation can span more than one task row (LOOM-13 continuation, or the router sending a later message in the same conversation to a different workspace), and adds every conversation in the message log via MessageLister.ListConversationActivity (LOOM-62). A conversation of only answer_directly turns has no task: it is listed with workspace_id: "" and status: "completed". updated_at is the later of the latest task update and the latest message. preview (LOOM-45) is the conversation's first-ever message (via MessageLister, one lookup per distinct conversation), truncated to 200 runes with a trailing "…" — the opening line for a conversation list UI row, deliberately the earliest message rather than the latest (status/updated_at already cover "what's happening now"). has_more is false unless ?limit= cut the list short (see "Lists and paging"). Since LOOM-267 a row also carries held_by {client_kind, client_label, since} when a person drives one of the conversation's tasks from a terminal (its active drive hold: who took it, and when), and pending_confirmation_id when the conversation waits on a yes or no to an offer (its newest one still pending and not past expires_at; answered by POST /dispatch with confirmation_id). Both are left out when there is none. Since LOOM-271 a row also carries watchers: how many watch holds the conversation's tasks have (sessions attached read-only, see takeover below), left out when nobody watches. A watcher is never held_by: a row that is only watched has watchers and no held_by.

    • Enums are snake_case throughout the API (API v1 freeze review, item 9). Two were kebab-case before 1.0, and the store still spells them that way: task statuses (running, awaiting_input, needs_attention, human_takeover, completed, failed; a conversation's status is its latest task's) and a target's permission_mode (auto, accept_edits, manual; the legacy accept-edits is still accepted as input for 1.x). Agent-type names such as claude-code are identifiers, not enums, and keep their spelling.

    • GET /api/v1/conversations/{id} — auth-gated (LOOM-18), the full task history for one conversation plus its message transcript (LOOM-31): {conversation_id, tasks: [{id, workspace_id, kind, agent_type, status, created_at, updated_at, started_at, completed_at}, ...], messages: [{id, role, content, task_id, dispatch_id?, created_at}, ...], dispatches: [{dispatch_id, status, reply?, error?, …}, ...]} (dispatches and dispatch_id since LOOM-80; a conversation whose only turn is still in flight already resolves, via its job and stored user message), all oldest first; 404 only if there is neither task history nor any message for that conversation_id — an answer_directly-only conversation has messages but no tasks and still resolves to 200. Backed by TaskLister (ListTasks, the store's unfiltered, cross-workspace task query — ListTasksByWorkspace alone can't answer "every task in this conversation" since a conversation isn't pinned to one workspace) and MessageLister (ListMessagesByConversation), both satisfied structurally by *app.App.Store(). has_more and next_before page messages with ?limit= and ?before=<message id>; without them every message comes back and has_more is false (see "Lists and paging"). Each task carries hold (LOOM-267): its active drive hold, as takeover returns it, or null when nobody drives it. And watch_holds (LOOM-271): its active watch holds, oldest first, in the same shape (mode watch); [] when nobody watches. A watch hold is never in hold.

    • GET /api/v1/conversations/{id}/events — auth-gated (LOOM-110), the conversation's dispatch audit trail, oldest first: {conversation_id, events: [{id, dispatch_id?, created_at, kind, model?, tier?, target_id?, workspace_id?, task_id?, command?, outcome?, error_class?, duration_ms, detail?}, ...]}. kind is decision, command, provision, machine (a machine created from chat: target_id, no workspace_id; provision before LOOM-247), offer, offer_answered, agent_turn, relay (late output) or outcome; commands are redacted like transcripts. An unknown conversation, or one past LOOMUX_EVENT_RETENTION, has an empty list. Backed by EventStore (WithEvents); 501 without it.

    • GET /api/v1/conversations/{id}/stream — auth-gated (LOOM-21), Server-Sent Events reporting task status transitions for one conversation, so a client can watch a dispatch progress instead of only getting a single reply when POST /dispatch's blocking call eventually returns — that endpoint's own contract is unchanged, this is purely additive. No 404 for an unknown conversation_id: a client may open the stream before ever calling dispatch, to catch the very first transition. event: task_update frames carry {task_id, workspace_id, status, updated_at} for the conversation's most-recently-updated task, sent whenever that tuple changes. A : heartbeat comment line every 15s keeps the connection alive through the reverse-proxy deployment model (above); the stream stays open until the client disconnects or the request context ends — it does not auto-close on a terminal status, so a client can keep watching across multiple turns of a long-lived conversation. Implemented as a polling loop (default 500ms, WithStreamPollInterval override) against TaskLister — the same seam the conversation endpoints use — rather than a new push-based event bus, matching this repo's existing minimal-machinery style (e.g. completion detection's own idle- heuristic tier).

      Since LOOM-80 the same stream also carries event: dispatch_update, data: {dispatch_id, status, reply?, error?, error_class?, updated_at}, whenever one of the conversation's dispatch jobs changes. On connect it reports jobs still in flight (so a client reconnecting mid-turn picks up where it was) but not ones already finished. With the reply on the succeeded event, in the job and in the conversation's messages, an async client no longer has to hold a request open for the reply text.

      Since LOOM-121 it also carries event: message_added, data: {message_id, task_id?, role, created_at}, for each message logged to the conversation while the stream is open (messages there on connect aren't replayed). An agent can end its turn early — a job left running in the background — and report later; the server relays that report as an assistant message no dispatch carries, so this event is how a client learns to refetch the conversation.

      Since LOOM-267 it also carries event: task_hold, data: {task_id, hold, watch_holds, ended_reason?}, when the holds on one of the conversation's tasks change. It carries them as they now are: hold is the task's drive hold or null, watch_holds its watch holds, oldest first ([] for none; LOOM-271). The task is taken (hold the new hold), taken from its holder with force (hold the new hold, ended_reason taken_over), or given back (hold null, ended_reason why the hold ended: released, taken_back, expired, session_revoked, task_ended); or a watcher comes or goes (watch_holds changes, hold is whatever it was, and there is no ended_reason: that is only ever the drive hold's). A heartbeat's renewal isn't an event. Like task_update it compares what each poll finds, so a hold taken and given back between two polls isn't reported; holds there on connect aren't replayed.

    • GET /api/v1/tasks/{id}/attach-info — auth-gated (LOOM-20), resolves a task down to the target+session a human would SSH into to attach (design spec §4): {task_id, tmux_session, target: {id, name, kind, host, user}, agent_args: {model, effort}}; 404 if the task doesn't exist. agent_args (LOOM-307) is what the task was launched with, "" for what its target didn't pin; a pin changed later doesn't change it. Returns stored data as-is — no live probe of whether the tmux session is actually still up (matching this API's other endpoints' thin-passthrough style); a dead session is discovered the same way a human always would, by trying to attach. Wraps AttachInfoStore (GetTask → GetWorkspace → GetTarget), a narrow seam mirroring the others here. It carries hold too (LOOM-267): the task's active drive hold, or null; and watch_holds (LOOM-271): its active watch holds, [] for none. Its attach_command and attach_commands are writable: whoever runs one can type into the pane. The read-only ones come only from a takeover with mode: "watch" (LOOM-272).

    • POST /api/v1/tasks/{id}/takeover, POST /api/v1/tasks/{id}/takeover/heartbeat and POST /api/v1/tasks/{id}/release: auth-gated holds (LOOM-264, WithTaskHolds; 501 without it; design in docs/design/tui-client-design.md, "Server awareness: holds"). A hold is a lease on a task by the caller's session while a person is attached to its pane. Taking a drive hold (the default) moves the task to human_takeover, which pauses automation into the pane; the hold says who has it. A watch hold (LOOM-271) only says who is looking, and changes nothing else.

      • takeover takes {mode?, client_label?, ttl_seconds?, force?} (the body may be left out) and returns 200 {task_id, hold, attach}: attach is the attach-info body, hold is {id, task_id, session_id, client_kind, client_label, mode, prev_status, ttl_seconds, acquired_at, renewed_at, expires_at, ended_at?, ended_reason?}. ttl_seconds is 15 to 300, default 45. client_label is at most 64 characters with no control characters. mode is drive (the default) or watch (below); anything else is 400. The hold answered is always of the mode asked for. client_kind is the caller's session's (LOOM-268), and so is client_label when the takeover sends none. For a drive hold, the task's active drive hold is checked before its status. Held by the caller's own session: that hold is renewed and returned (idempotent; its lease length and label stay as first taken). Held by another session: 409 (code task_held) with its hold, unless force, which detaches the tmux clients attached to the task's session (before answering, so before the caller attaches), ends it as taken_over and gives the caller a new one while the task stays human_takeover. If the clients can't be detached it is 502 (code detach_failed) and nothing is taken. Not held: a running, awaiting_input or needs_attention task moves to human_takeover, and one already there with no hold is taken as it stands. A failed task with error_class login_required, agent_rate_limited or agent_api_error (its pane was kept for a person) is held too and stays failed. Any other ended task is 409 (code task_inactive). prev_status is the task's status when this hold was taken (human_takeover for a forced one). The hold and the status change are one write, a compare-and-set on the status read (LOOM-262); a task that keeps changing is 409. Taking a running task ends the wait on its turn at once (LOOM-266): the conversation's dispatch ends failed with error_class taken_over (also on its dispatch_update event), no keys are sent to the agent, and the task stays human_takeover. What the agent finishes reaches the conversation as a late reply once the task is handed back.
      • takeover with mode: "watch" (LOOM-271) takes a watch hold: the caller's session is attached to the pane read-only. The task's status isn't touched, so automation keeps typing and a turn in flight carries on; nobody is detached; and whoever drives the task keeps it. It is never 409 task_held: any number of sessions may watch a task, beside the one that drives it. A task can be watched when it could be held (the statuses above, a kept failed pane included); any other ended task is 409 task_inactive. prev_status is the task's status when the watch began. A session has one watch hold per task: asking again renews and returns it, as for a drive hold (two terminals of one session share it, and either one's release ends it for both). force is 400 with watch: it detaches a pane's holder, which a request to look is never read as asking for. A watch gives no claim on the pane: the watcher's own drive takeover is still 409 task_held while another session drives. A watch is never handed a command that can type. The response's hold.mode is watch, and every command in its attach attaches read-only (LOOM-272), with tmux's -r, so nothing typed reaches the pane (the keys that detach still work): attach_command is tmux -L <socket> attach -r -t <session>, the ssh entry of attach_commands runs that same line on the target, and a plugin's entry is its own exec form around it (kubectl … exec -it <pod> -- tmux -L <socket> attach -r -t <session>, docker … exec -it <container> tmux … attach -r …). The server builds the first two. A plugin is asked read-only, only when its manifest declares targets.attach_read_only, and its answer is used only if it confirms read-only and each command's argv ends with exactly tmux -L <socket> attach -r -t <session> for the socket and session asked for; the command line of a plugin's entry is then made by the server from that argv. Nothing is left for the client to add or check, and the writable commands of attach-info are never in a watch's answer. For a plugin's machine the watch gets the plugin's read-only command or is refused, with no hold taken: 409 (code watch_unsupported) naming the plugin when it has none (an older plugin), 409 with the same code when the plugin isn't running, and 502 when it didn't answer. It is never given the plugin's writable command, nor the ssh form alone, which doesn't reach a plugin's machine. A target no plugin stands behind (a registered host, or a machine whose plugin was uninstalled) has the ssh form alone, as in attach-info, and so has a machine of a plugin with no attach commands of its own. On tmux 3.2 or later -r also keeps the watcher's terminal from resizing the window (it is -f read-only,ignore-size); on an older tmux it is read-only only. attach.hold is whoever drives the task (or null), and attach.watch_holds includes the hold just taken. A client must check hold.mode is watch before it treats the answer as one: a server from before watch holds answers 400 unsupported_mode.
      • heartbeat takes {hold_id} and returns 200 {hold} with expires_at moved to ttl_seconds from now. An ended hold is 410 (code hold_ended) with ended_reason and the hold. Only the session that holds it may renew it (403 otherwise); a hold that isn't this task's is 404.
      • release takes {hold_id?} (the body may be left out) and returns 200 {task_id, status, hold?}, status being the task's status afterwards. With hold_id it ends that hold as released; a hold that had already ended comes back as it ended, so it is idempotent. A watch hold's release ends that hold and nothing else: the task keeps its status and its driver. Without hold_id it is Take back, which any session may do: the task's drive hold, if it has one, ends as taken_back once the tmux clients attached to the task's session are detached. If they can't be (the target doesn't answer) it is 502 (code detach_failed) and nothing changes, so automation never types into a pane its holder may still be in. Watch holds are left as they are by a Take back, but tmux can't tell a read-only client from the driver's: the detach (here, on a forced takeover and when a drive hold expires) closes the watchers' terminals too, and each watcher's client then releases its hold or lets it expire. A release by hold_id detaches nobody: the holder's own client has let go. Either way a task left in human_takeover with no drive hold becomes awaiting_input and its stale attention is cleared, in the same write as the hold's end; a task in any other status keeps it, and a task another session has taken meanwhile stays theirs.
      • Holds end by themselves too (LOOM-265): the server's hold sweeper, every 5 s, ends a hold whose lease ran out as expired, one whose session was logged out, revoked or has expired as session_revoked (a logout or revoke also ends them at once), and one whose task ended as task_ended. For the first two, a drive hold's tmux clients are detached (tmux detach-client -s on the task's session, through its target) and then the task is handed back as by a release; if they can't be detached the hold stays and the next sweep tries again. Targets are swept concurrently, each hold within 10 s, and a target that doesn't answer is skipped for the rest of a pass, so it never delays holds on other targets. A task_ended hold detaches nobody and leaves the status. A watch hold ends for the same three reasons, and its end is only that (LOOM-271): nobody is detached (a read-only client can't collide with automation, and the detach would throw the task's driver out too), the task is left as it is, and since it needs nothing from the target it ends even while the target doesn't answer. On start the sweeper first gives every active hold a full lease from then, so a restart or deploy longer than a lease doesn't end the holds of clients that resume heartbeating. Taking, renewing, releasing and ending a task's holds are serialized per task, detach included, so a heartbeat can't renew a hold the sweeper is ending, and a hold ended with a detach never detaches a holder who took the task meanwhile. A takeover whose session is logged out or revoked while it is being taken ends that hold again and answers 401, with no attach-info.
      • Holds are shown where clients look (LOOM-267): hold on each task of GET /conversations/{id}, on attach-info and on takeover's attach (the hold just taken); held_by on GET /conversations rows; and the stream's task_hold event. hold and held_by are the drive hold only. Watch holds are shown beside them (LOOM-271): watch_holds wherever hold is, and a watchers count on rows. A message sent to a conversation whose task is held isn't sent to the agent: its dispatch fails with error_class held (not internal), and its error names the holder ("being driven from the terminal on laptop since …; take it back, or wait until it is given back, then send the message again").
    • Targets carry relay (full, last_message, none, or "" for the purpose's default: none for purpose: work, else full) and show relay_effective: what the router models may see of the target's work (docs/deploy/operations.md, "What the router models see").

    • Targets carry keep_idle_sessions (LOOM-227, default false): when true the idle reaper never closes the target's sessions however long they wait for a follow-up, as a hub's own session needs (docs/deploy/operations.md, "Idle sessions").

    • POST /api/v1/targets/{id}/scan-host-key, POST /api/v1/targets/{id}/pin {fingerprint}, DELETE /api/v1/targets/{id}/pin, POST /api/v1/targets/{id}/test — auth-gated target onboarding (LOOM-114, WithHostKeyPinning; 501 without it). A scan returns {target_id, host_keys: [{type, fingerprint}], expires_at, pinned_host_keys} and trusts nothing; 502 with the SSH hint when the host can't be read. A pin must name a fingerprint from the target's latest scan, at most 10 minutes old and taken at the target's current host, port, proxy and key (LOOM-164; 409 otherwise, also when a PUT moves the target mid-pin), and returns the target, whose pinned_host_keys then lists it. A pinned target is checked against its pin alone. Only remote targets (400 for local). test returns {target_id, reachable, tmux_version?, latency_ms, error?, host_key_problem}. Targets also take and show ssh_port (0: the SSH config's). test also returns steps (LOOM-138): connect, host_key, auth and tmux, each {name, status: ok|failed|skipped, error?}, the failed one carrying the reason and what to do. Single user today; scanning and pinning must become admin-only if Loomux ever has several (see docs/deploy/ssh.md).

    • GET /api/v1/ssh-keys, POST /api/v1/ssh-keys {name}, DELETE /api/v1/ssh-keys/{id} — auth-gated SSH keys Loomux manages for reaching targets (LOOM-138, WithSSHKeys; 404 without it; design in docs/design/target-onboarding.md). POST generates an ed25519 key and returns {id, name, type, fingerprint, public_key, origin, created_at, used_by} — public_key is the authorized_keys line to add on a target, commented loomux-<name>; origin is generated, target (made by a target's generate_ssh_key) or imported. The private key is encrypted at rest with LOOMUX_MASTER_KEY (503 without it) and is never returned by any endpoint. name is letters, digits, ., _ and -, starting with a letter or digit, at most 64 (400 otherwise; 409 if taken). The list (ssh_keys, a complete list) works without a master key; used_by holds the ids of the targets using each key, and deleting a key in use is 409.

    • GET /api/v1/settings/router, PUT|DELETE /api/v1/settings/router/{tier}, POST /api/v1/settings/router/{tier}/test, POST /api/v1/settings/router/{tier}/models, GET /api/v1/settings/router/audit?limit=N — auth-gated router model settings (LOOM-185, WithRouterSettings; 404 without it; design in docs/design/router-settings.md). {tier} is primary or escalation. A stored tier {provider, base_url, model, api_key} overrides the environment's LOOMUX_ROUTER_<TIER>_* and applies without a restart; DELETE goes back to the environment's. The key is write-only: responses carry key_fingerprint, key_last4, set_at and which source (stored, env, none) is active, never the key. PUT may leave api_key out to keep the stored one, but only while provider and base_url are unchanged; base_url must be https (http only to loopback), optional for anthropic; 503 without a master key. test makes one one-token call: {ok, status?, error_class?, error?, model, source, duration_ms}, a failure described by its HTTP status and class, never the provider's body. models (LOOM-191) {provider?, base_url?, api_key?} lists the provider's models {ok, models: [{id, name?}], status?, error_class?, error?, cached}, with the tier's key for its own endpoint or the given api_key (used once, never stored or returned) for another; cached five minutes. audit lists {id, tier, action, fields, actor, created_at}, newest first.

    • POST /api/v1/targets/{id}/migrate-ssh {dry_run} — auth-gated (LOOM-138, WithSSHMigration; 501 without it, without /ssh-keys, or, to apply, without probing or pinning). Plans a config-mode remote target (400 otherwise) as a managed one from what the mounted SSH config does for it (docs/deploy/ssh.md, "Migrating a target off the SSH config"): {target_id, dry_run, can_apply, problems, plan: {host, ssh_port, user, ssh_proxy, key: {type, fingerprint, source_file, existing_key_id}, host_keys}, applied, rolled_back, test, target}. A dry run changes nothing (200). Applying with problems is 409. A successful apply returns 200 with test and the managed target. If the test fails, the target is put back as it was and the answer is 502 with test and rolled_back: true. A config that can't be read is 502. The private key never appears. key_file (a file name in ~/.ssh) picks the key to import. Another migration running is 409 with the usual {error}. A failed test on a target edited meanwhile is 409 too, the target left as edited; that one, and the other answers about the plan or its outcome (409 with problems, 502, a 500 from a failed rollback), carry the migrate body, with the reason in problems.

    • GET /api/v1/targets/{id}/agents, POST /api/v1/targets/{id}/probe, POST / DELETE /api/v1/targets/{id}/agents/{agent_type}/sign-in — auth-gated agent CLI status and sign-in (LOOM-71, LOOM-86, LOOM-316; docs/design/agent-sign-in.md). Each agent entry carries auth when its CLI is installed and has an auth check: state (logged_in, logged_out, expired, rate_limited, unknown), method, plan, expires_at, the sign-in problem or rate_limit a turn last saw, and the open sign_in session with attach_command/attach_commands (attach-info's shape). The POST ({restart?}) opens the agent CLI's own login (claude auth login, codex login --device-auth) in a tmux session on the target for a person to attach to, or hands back the one open; a signed-in agent opens nothing unless restart. 404 no such target or agent type, 409 agent_unavailable not installed, 422 no_sign_in, 502 target_unreachable, 501 without a router. Loomux never types into, captures or completes the sign-in; nothing in these responses comes from the auth check's raw output (no email, no key fragments).

    • POST /api/v1/targets, GET /api/v1/targets, PUT /api/v1/targets/{id}, DELETE /api/v1/targets/{id} — auth-gated target registration (LOOM-59). registry.Store's target CRUD existed and was tested from the first commit but had no production caller at all, so the only way to register an execution target was to hand-write a row into sqlite on the deployment host. That left a fresh deployment with nowhere to dispatch work — the router correctly falls back to answer_directly when no target exists — and it is why these are HTTP routes rather than an admin CLI subcommand: registration has to be reachable by an operator who has no shell on the pod, and a CLI would have been a second validation path to keep in sync while still not meeting that bar. The deployment already configures LOOMUX_AUTH_PASSWORD_HASH, so there is no bootstrap chicken-and-egg to justify one.

      Bodies are {name, kind, host, user} plus the optional fields below; on a PUT every field is optional, an omitted one (or "" for those four) keeping what's stored, and "kind": "local" clearing host and user (LOOM-256). ready follows the last probe unless how the target is reached changed since (kind, host, user, port, key, proxy, workspace root, host key pin): a new name, permission mode or policy keeps it. Responses add the server-minted id plus created_at/updated_at. The id is never accepted from the client — workspaces reference targets by id, and letting a caller choose one invites exactly the collisions and hand-minted ids this endpoint exists to replace, so it is generated here the way session ids already are. ssh_key_ref is not part of the API (removed before 1.0, freeze review item 1); a client that still sends it has it ignored. A target's key is set with ssh_key_id instead (below).

      agent_args (LOOM-307, docs/design/agent-launch-args.md) pins the model and effort each agent type is launched with on the target: {"claude-code": {"model": "opus", "effort": "high"}}. Optional; on a PUT an omitted agent_args keeps what's stored and a given one replaces the whole map (an agent type left out is unpinned, an entry with both fields "" pins nothing). Every target response carries it, {} when nothing is pinned, each entry with both fields. A model is 1-64 letters, digits, ., _, : or -, starting with a letter or digit, optionally ending in [1m]; an effort must be one its agent type's CLI takes (claude-code: low, medium, high, xhigh, max; codex: minimal, low, medium, high, xhigh). An unknown agent type, effort or field in an entry is 400. Only this API sets them: the router models and prompts can't, and a launch whose stored pin its CLI can't take fails rather than run on the account's defaults.

      GET /api/v1/targets also answers local_targets (LOOM-183): whether this server allows targets of kind local. It is false with LOOMUX_LOCAL_TARGETS=off (the container image's default, LOOM-141), when a local create or update is 400; a client hides or disables the choice instead of offering it and failing.

      Managed targets (LOOM-138, docs/deploy/ssh.md): a body may carry ssh_key_id (a key from /ssh-keys; "" returns the target to the SSH config), or "generate_ssh_key": true (a new key named after the target; 501 without /ssh-keys, 503 without a master key; not both, 400), and ssh_proxy (default or none, managed targets only). A managed target's host must be a host name or IP address (400 otherwise), and changing its host or ssh_port drops its pin. An unknown ssh_key_id is 400 (no such SSH key). Every target response adds ssh_mode (managed or config), ssh_key ({id, name, type, fingerprint, public_key}, null in config mode), ssh_proxy, ready, and next_step (pin_host_key, authorize_key, test_connection, or null when ready), judged from the latest probe newer than the target's last change. Create, update and pin responses now also carry the target's health. A key made by generate_ssh_key has origin: target in /ssh-keys and is deleted when its target is deleted or moves to another key; a host key scan is forgotten when a target's host, port, key or proxy changes. A health error for an unreachable target now ends with its class in parentheses, e.g. (auth_failed).

      Validation enforces the invariants the execution layer assumes but cannot check at registration time, so a target that could never be dispatched to is rejected at the boundary rather than stored and discovered broken later: kind must be one of the two targets.NewExecutor knows; a remote needs both host and user, because RemoteExecutor.destination() builds user+"@"+host and ssh rejects a bare @host; that host is a host name, an ssh_config Host alias (labels of letters, digits, - and _, dot-separated) or an IPv4/IPv6 address (LOOM-175; a managed target's takes no _); a local must carry neither, since clearing them silently would hide a caller's misunderstanding until an attach-info response came back missing fields they thought they had set. Bad body or failed validation is 400, a duplicate name 409 (the store's unique constraint).

      All four operations ship, not just create, because create-only would reproduce this ticket's own failure mode in miniature — a write path with no way to read or fix. GET is how a client discovers the server-assigned id it needs to attach a workspace; DELETE undoes a mistaken registration (409, not 500, once workspaces reference it — the foreign key doing its job, and the operator needs to be told which it is); PUT is then the only correction path left, which is why it exists. PUT re-reads the stored row rather than echoing back the struct it passed to UpdateTarget: that call fills in UpdatedAt but not CreatedAt, so only a read returns a canonical row. Unknown id is 404 on both.

    • GET /api/v1/version — unauthenticated, {server_version, api_version} (server_version comes from the top-level version package, not defined in this one)

Lists and paging

A list that can grow without bound carries has_more (a boolean, always present) beside it, so paging can be introduced without breaking a client that assumed the list was complete. Today that is GET /api/v1/conversations (conversations), GET /api/v1/conversations/{id} (messages), GET /api/v1/conversations/{id}/events (events, not paged yet: always false) and GET /api/v1/tasks/{id}/transcript (turns). Clients must check has_more: false means the list is complete, true that more remain.

The other lists are complete lists for all of v1: GET /workspaces, /targets, /credentials, /ssh-keys, /sessions and /targets/{id}/agents, bounded in practice by what one person registers. They carry no has_more, and paging them would need new, opt-in parameters.

Paging follows the task transcript's convention (LOOM-122):

  • ?limit=N returns at most N items. Out of range (not a number, below 1, above the route's maximum) is 400.
  • Items stay in the list's own order. For a list that grows at the end (messages, transcript turns: oldest first), a page is the latest N, and next_before (present when has_more is true) is the before= value that fetches the page preceding it: ?before=<id>&limit=N. A before naming no item of the list is 400.
  • The transcript always pages (default 20, at most 100: a turn carries a pane). The conversation routes have no default limit (at most 500 when given): without limit they return everything and has_more is false, as before the field existed. Tasks, dispatches and confirmations in GET /conversations/{id} are always complete; only messages pages. GET /conversations (most recently updated first) takes limit but no cursor yet: its order moves with activity, so a client wanting more asks for a larger limit.

Testing

api/apitest: a real server for another module's tests

github.com/Loomux/server/api/apitest (LOOM-270) is an exported test helper for clients that live in another module, first loomux/tui. Such a client requires this module at a release tag, imports apitest from its _test.go files only, and drives the server over HTTP, so its typed client is checked against the handlers, auth, JSON and event stream a deployed server answers with (docs/design/tui-client-design.md, "How it pins and tests against the server's API").

srv := apitest.New(t)            // torn down by t's cleanup
token := srv.Login()             // a new session each call
task := srv.SeedPrompt("conv-1", registry.Attention{})
// the client under test talks to srv.URL with token
  • Real: api.Server, a SQLite store in a temporary directory with every migration applied (srv.Store), the dispatch-job service, and the orchestrator behind takeover, heartbeat and release. Its hold sweeper runs when a test calls srv.SweepHolds() (LOOM-265), not on a timer: a lease past its expiry on the WithClock clock ends as expired, a hold whose session no longer exists (logged out) as session_revoked.
  • Stubbed: the router. srv.Dispatcher answers each dispatch: Reply, Fail, Block (hold a conversation busy until released or cancelled) or a Handle function; Dispatches() lists what it was sent. A successful reply is also logged as the assistant's message.
  • Faked: the targets. srv.Executor is an in-memory targets.TargetExecutor that records sessions and input and runs nothing; a session's Detaches counts the times its clients were detached.
  • Seeds: SeedTarget, SeedWorkspace, SeedTask, SeedConversation, SeedMessage, SeedPrompt (a needs_attention task), SeedFailedTask, SeedOffer (a pending confirmation), SeedTurn (a transcript entry) and SetTaskStatus (a status change an open stream reports). ActiveHold is a task's drive hold and WatchHolds its watch holds (LOOM-271), as the store has them. SeedLinkedSession returns the token of a session as the link flow leaves it (a terminal's), and TokenHash is the hash POST /api/v1/sessions takes.
  • Not configured: plugins, machines, credentials, SSH keys, router settings, web bundles and health checks answer as on a server without them. WithAPIOptions adds any api.Option; WithClock sets the clock holds run on; WithPassword the login password.

The helper is extended by each server ticket that adds a route a client calls. Its own tests (api/apitest/apitest_test.go) use it as a client module would, including takeover, heartbeat and release.

This package's own tests

server_test.go covers the auth/session state machine (login success/ failure, missing/invalid/expired/logged-out tokens, sliding-expiration refresh, and the login throttle — repeated failures triggering 429 with Retry-After, a success resetting it, that it's shared across different claimed X-Forwarded-For values (proving "global" is real, not just documented), and that enough waiting always lets the correct password through no matter how many failures preceded it), plus GET /api/v1/sessions / DELETE /api/v1/sessions/{id} (LOOM-47: listing across multiple logins with exactly the caller's own session marked current, a session past sessionTTL excluded from the listing even though nothing has presented its token since expiry to trigger requireAuth's own opportunistic cleanup, revoke-by-id invalidating that token without touching others, unknown-id 404, re-revoking the same id 404 rather than a repeatable success, and revoking the current session behaving like /logout) against a fake Dispatcher and a real (temp-file) sqlite store for sessions, plus /api/v1/workspaces (auth required, empty-list, populated-and-sorted, and metadata round-trip cases, asserting the full field set including tags/description/rolling_summary/last_used_at against real store fixtures) and /api/v1/conversations + /api/v1/conversations/{id} (auth required, empty-list, recency-sorted grouping across multiple conversations, a direct-answer-only (task-less) conversation being listed and recency counting messages as well as tasks (LOOM-62), a conversation spanning two workspaces returning chronological history, an unrelated conversation not leaking in, and unknown-id 404) and /api/v1/tasks/{id}/attach-info (auth required, unknown-task 404, and a remote target's host/user/kind flowing through correctly), and /api/v1/conversations/{id}/stream (auth required; a real SSE round-trip — created-then-updated task status changes arriving as ordered task_update events, parsed off the live response body with a bounded per-event timeout so a broken stream fails the test instead of hanging). Run with -race too — the stream handler's poll loop and heartbeat ticker run concurrently with request handling, and this is the one handler in this package doing that. server_test.go also covers WithStaticDir (LOOM-33): a real static file served as-is, an unknown client-side route and the root path both falling back to index.html, /api/* paths staying untouched by static serving (including the unsupported-API-version rejection still winning over the SPA fallback, and the bare /api path with no trailing slash specifically — a prior version of this routing check missed it and let it fall through to the static handler), a path-traversal attempt (both literal .. and its %2e%2e percent-encoded form) falling back to the SPA shell rather than escaping the configured directory, and — separately — that static serving stays off (still 404) when WithStaticDir is never used, matching this package's behavior before the option existed. targets_test.go covers the LOOM-59 target endpoints end-to-end through real HTTP against a real store: a remote target created and read back by GET, a local one persisting without host/user, server-minted ids being distinct and a client-supplied id field being ignored rather than honoured, every validation rejection (missing name; unknown/empty/ wrong-case kind; remote missing host or user; local carrying either; malformed JSON) as 400 with a populated error envelope, duplicate name as 409, PUT changing stored fields and DELETE removing them, unknown id as 404 on both, DELETE of a target with workspaces attached as 409, and — the check that matters most for an administrative endpoint — that all four routes reject an unauthenticated caller and that a rejected POST leaves the store empty, so auth failure can't be a write that merely reports failure. The unknown-id cases assert on the error envelope specifically: net/http's mux also returns 404 for an unregistered route, so a bare status check there passes vacuously whether or not the handler exists. throttle_test.go covers loginThrottle in isolation (pure timing logic, including the zero-base edge case tests use to disable backoff entirely). integration_test.go proves the auth/dispatch behavior against a real app.App (real sqlite, a real llmrouter.Model hitting an httptest.Server standing in for the LLM vendor) driven purely over real HTTP — the full stack, not just this package in isolation. Run go test ./api/....

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

View Source
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

View Source
var (
	// ErrUnknownAgentType: no agent type of that name.
	ErrUnknownAgentType = errors.New("api: unknown agent type")
	// ErrNoAgentSignIn: the agent type has no sign-in command.
	ErrNoAgentSignIn = errors.New("api: agent type has no sign-in")
	// ErrAgentNotInstalled: the agent's CLI isn't installed on the
	// target.
	ErrAgentNotInstalled = errors.New("api: agent not installed on the target")
)
View Source
var ErrNoSuchTarget = errors.New("no such target")

ErrNoSuchTarget: the target_id names no target.

Functions

func HashPassword

func HashPassword(password string) (string, error)

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 AgentArgsCheck added in v0.3.161

type AgentArgsCheck func(agentType string, a registry.AgentArgs) error

AgentArgsCheck reports whether agentType is one this server launches and its CLI takes the pin a (router.AgentTypeRegistry.CheckAgentArgs).

type AgentSignInResult added in v0.3.160

type AgentSignInResult struct {
	// Agent is the agent's record after its probe, its sign-in session
	// included.
	Agent *registry.TargetAgent
	// Opened: a sign-in session was opened now. Reused: the one already
	// open was handed back. Neither: the agent is signed in.
	Opened bool
	Reused bool
}

AgentSignInResult is what PrepareAgentSignIn did.

type AgentSignIns added in v0.3.160

type AgentSignIns interface {
	// PrepareAgentSignIn probes agentType on targetID and, unless it is
	// signed in (or restart), opens its sign-in session or hands back the
	// one already open. Errors: ErrUnknownAgentType, ErrNoAgentSignIn,
	// ErrAgentNotInstalled, registry.ErrNotFound (no such target),
	// targets.ErrUnreachable.
	PrepareAgentSignIn(ctx context.Context, targetID, agentType string, restart bool) (*AgentSignInResult, error)
	// CloseAgentSignIn closes agentType's sign-in session on targetID if
	// one is open.
	CloseAgentSignIn(ctx context.Context, targetID, agentType string) error
}

AgentSignIns opens and closes agent sign-in sessions (LOOM-316): a tmux session on a target running the agent CLI's own login, for a person to attach to and finish. Loomux never signs an agent in itself.

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

func LoadConfig() (Config, error)

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

type HostKeyScanner func(ctx context.Context, t *registry.Target) ([]targets.HostKey, error)

HostKeyScanner reads the host key a target presents, without trusting it — targets.ExecutorOptions.ScanHostKey, an app's own.

type HostKeyStore added in v0.3.8

type HostKeyStore interface {
	SetTargetHostKeys(ctx context.Context, id, hostKeys string) error
}

HostKeyStore is where pins are kept — satisfied by any registry.Store.

type Machines added in v0.3.69

type Machines interface {
	View(ctx context.Context, targetID string) (*providers.MachineView, error)
	Views(ctx context.Context) (map[string]*providers.MachineView, error)
	IsMachine(ctx context.Context, targetID string) bool
	// Describe is what a plugin instance offers for a new machine
	// (LOOM-238).
	Describe(ctx context.Context, pluginID string) (protocol.TargetsInfo, error)
	Create(ctx context.Context, req providers.CreateRequest) (*registry.Target, *registry.Environment, error)
	Start(ctx context.Context, targetID string) error
	Stop(ctx context.Context, targetID string) error
	Recreate(ctx context.Context, targetID, size string) error
	DeleteTarget(ctx context.Context, targetID string) error
	AttachCommands(ctx context.Context, targetID, session string) ([]protocol.AttachCommand, error)
	// ReadOnlyAttachCommands is the plugin's commands for a person who
	// only watches (LOOM-272): each attaches read-only. A
	// *providers.WatchUnsupportedError when the machine's plugin has
	// none; never the writable ones.
	ReadOnlyAttachCommands(ctx context.Context, targetID, session string) ([]protocol.AttachCommand, error)
}

Machines backs the machine side of /api/v1/targets (LOOM-178, docs/design/target-providers.md §5): targets a plugin made. Satisfied by *providers.Manager.

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 WithAgentArgsCheck added in v0.3.161

func WithAgentArgsCheck(check AgentArgsCheck) Option

WithAgentArgsCheck checks each target's agent_args against the agent types this server launches (LOOM-307). Without it only their form is checked; the launch still refuses a pin its CLI can't take.

func WithAgentSignIns added in v0.3.160

func WithAgentSignIns(a AgentSignIns) Option

WithAgentSignIns enables POST and DELETE /api/v1/targets/{id}/agents/{agent_type}/sign-in (LOOM-316).

func WithAgentTypes

func WithAgentTypes(names []string) Option

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

func WithLocalTargets(on bool) Option

WithLocalTargets says whether targets of kind "local" may be registered (LOOM-141; app.Config.LocalTargetsOff). On by default.

func WithLoginBackoff

func WithLoginBackoff(base, max time.Duration) Option

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 WithMachines added in v0.3.69

func WithMachines(m Machines) Option

WithMachines enables machines on /api/v1/targets (LOOM-178).

func WithPlugins added in v0.3.68

func WithPlugins(p Plugins) Option

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

func WithSSHKeyDropper(drop func(id string)) Option

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

func WithSessionMaxAge(d time.Duration) Option

WithSessionMaxAge overrides a session's absolute lifetime (defaultSessionMaxAge); 0 means none, only the sliding window.

func WithSessionTTL

func WithSessionTTL(d time.Duration) Option

WithSessionTTL overrides the default sliding-expiration window.

func WithStaticDir

func WithStaticDir(dir string) Option

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

func WithStreamHeartbeat(d time.Duration) Option

WithStreamHeartbeat overrides the stream's heartbeat interval, which is also how often an open stream re-checks its session. For tests.

func WithStreamPollInterval

func WithStreamPollInterval(d time.Duration) Option

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 WithTaskHolds added in v0.3.148

func WithTaskHolds(h TaskHolds) Option

WithTaskHolds enables POST /api/v1/tasks/{id}/takeover, /takeover/heartbeat and /release (LOOM-264).

func WithTaskTurns

func WithTaskTurns(t TaskTurnStore) Option

WithTaskTurns enables GET /api/v1/tasks/{id}/transcript (LOOM-91).

func WithTmuxSocket added in v0.3.101

func WithTmuxSocket(name string) Option

WithTmuxSocket names the instance's tmux socket (its executors' ExecutorOptions.TmuxSocket) in attach-info (LOOM-202). Without it, targets.DefaultTmuxSocket.

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).

func WithWorkspaceProvisioner added in v0.3.113

func WithWorkspaceProvisioner(p WorkspaceProvisioner) Option

WithWorkspaceProvisioner enables POST /api/v1/workspaces (LOOM-215).

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 ProvisionedWorkspace added in v0.3.113

type ProvisionedWorkspace struct {
	Workspace *registry.Workspace
	// ConversationID is the conversation the provisioning run is
	// recorded under; "" for an Existing workspace.
	ConversationID string
	Existing       bool
}

ProvisionedWorkspace is what ProvisionWorkspace did.

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)
	// Models lists the models the tier's provider offers (LOOM-191).
	Models(ctx context.Context, tier string, req llmrouter.ModelsRequest) (llmrouter.ModelsResult, 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.ExecutorOptions.ResolveSSHConfig, an app's own.

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 TaskHolds added in v0.3.148

type TaskHolds interface {
	Takeover(ctx context.Context, req orchestrator.TakeoverRequest) (*orchestrator.TakeoverResult, error)
	Heartbeat(ctx context.Context, taskID, holdID, sessionID string) (*registry.TaskHold, error)
	Release(ctx context.Context, taskID, holdID string) (*registry.HoldRelease, error)
	// EndSessionHolds ends a logged-out or revoked session's holds as
	// session_revoked, detaching their clients (LOOM-265). One it can't
	// end now is left for the hold sweeper.
	EndSessionHolds(ctx context.Context, sessionID string) (int, error)
	// ActiveHolds returns every hold that hasn't ended, and GetHold one
	// hold, active or ended (registry.ErrNotFound if unknown): what
	// conversations, attach-info and the stream show of holds
	// (LOOM-267).
	ActiveHolds(ctx context.Context) ([]*registry.TaskHold, error)
	GetHold(ctx context.Context, id string) (*registry.TaskHold, error)
}

TaskHolds takes, renews and releases holds on tasks (LOOM-264, docs/design/tui-client-design.md "Server awareness: holds"): the lease a client takes while a person is attached to a task's pane. Satisfied by *orchestrator.Orchestrator. Optional: with none configured (WithTaskHolds), the takeover, heartbeat and release endpoints answer 501.

type TaskLister

type TaskLister interface {
	ListTasks(ctx context.Context) ([]*registry.Task, error)
}

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)
	// GetWorkspace backs GET /api/v1/workspaces/{id} (LOOM-215);
	// registry.ErrNotFound for an unknown id.
	GetWorkspace(ctx context.Context, id string) (*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)
	// DeleteWorkspaceAndWorktree is DeleteWorkspace that first removes
	// the workspace's git worktree from its target (LOOM-228); git's
	// refusal (changes not committed) is a *registry.ConflictError.
	DeleteWorkspaceAndWorktree(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.

type WorkspaceNameTakenError added in v0.3.113

type WorkspaceNameTakenError struct{ Msg string }

WorkspaceNameTakenError: another workspace has the name; Msg says which and what to do.

func (*WorkspaceNameTakenError) Error added in v0.3.113

func (e *WorkspaceNameTakenError) Error() string

type WorkspaceProvisioner added in v0.3.113

type WorkspaceProvisioner interface {
	// ProvisionWorkspace writes the workspace row and starts its
	// provisioning in the background. The same name on the same target
	// from the same source returns the workspace already there
	// (Existing). Errors a caller can act on: ErrNoSuchTarget,
	// *WorkspaceSpecError, *WorkspaceNameTakenError.
	ProvisionWorkspace(ctx context.Context, req WorkspaceToProvision) (ProvisionedWorkspace, error)
}

WorkspaceProvisioner provisions a workspace on a chosen target: app.App, over the router.

type WorkspaceSpecError added in v0.3.113

type WorkspaceSpecError struct{ Msg string }

WorkspaceSpecError is a request to correct; Msg says how.

func (*WorkspaceSpecError) Error added in v0.3.113

func (e *WorkspaceSpecError) Error() string

type WorkspaceToProvision added in v0.3.113

type WorkspaceToProvision struct {
	TargetID, Name, Kind, GitRemote, Description string
	Tags                                         []string
	Worktree                                     WorktreeToAdd
}

WorkspaceToProvision is a workspace to make: Kind is empty, git_clone, existing_dir or git_worktree (LOOM-228: Worktree's base, ref and branch, only then).

type WorktreeToAdd added in v0.3.121

type WorktreeToAdd struct {
	Base, Ref, Branch string
}

WorktreeToAdd is a git_worktree workspace's source: the repository's directory under the workspace root, the ref the branch starts at ("" for its HEAD) and the new branch ("" for loomux/<name>).

Directories

Path Synopsis
Package apitest runs a real api.Server for tests in another module (LOOM-270, docs/design/tui-client-design.md "How it pins and tests against the server's API").
Package apitest runs a real api.Server for tests in another module (LOOM-270, docs/design/tui-client-design.md "How it pins and tests against the server's API").

Jump to

Keyboard shortcuts

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