api

package
v0.179.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 103 Imported by: 0 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.

Documentation

Overview

This file holds the single place a route may be registered. That is not bookkeeping — it is the premise the route-drift gate in routes_golden_test.go rests on. The gate hands a recorder to RegisterRoutes and diffs what comes back against a checked-in golden file. That recording is a claim about production only for as long as RegisterRoutes is the ONLY registration site in the module; the moment a second one exists, the golden describes a subset and says nothing about the rest.

So the chokepoint ships before the routes do, and the gate checks the premise rather than assuming it.

Package api is muster's HTTP surface: the Server, its dependencies, and the single place a route may be registered.

🔴 ROUTE REGISTRATION IS UNCONDITIONAL, AND THAT IS A DELIBERATE DEPARTURE FROM THE CODE THIS WAS CARVED OUT OF.

Upstream, roughly half the route table sits behind `if s.ext.X == nil { return }` guards, so the set of registered routes is a function of the FIXTURE as much as of the code. That is not a hypothetical cost: it left that project's route golden seven routes short, with two separate guards green over the hole, because the fixture the recorder used had one dependency unset. The golden then described the fixture and was read as describing production.

Here, every route registers on every boot and each handler answers its own "this server has nothing to serve from" case — a 503 naming the missing dependency, or a rendered panel saying so on screen. Three things follow, and they are the reason this is worth the handful of extra nil checks:

  • the route golden is a claim about the CODE. `RegisterRoutes` takes no fixture and cannot be given one, so there is no configuration in which the recording and production disagree. TestRegistrationIsIndependentOfDependencies asserts exactly that, by recording from a bare server AND a fully-wired one and demanding set equality.
  • a no-database boot serves a UI that explains itself instead of a navigation of 404s. A panel that says "no database is configured" is a better first run than a tab whose partial 404s silently.
  • "which routes exist" stops being a thing a reader has to simulate.

The precedent is upstream's own: its seam and gate registrars are unconditional for this exact reason, and their comments say so.

Index

Constants

View Source
const (
	SendQueueNudgeOff     = "Not sent: chief nudges are off, or in shadow mode for you, on this server."
	SendQueueNudgeUnknown = "Not sent: its chief nudge could not be read."
	SendQueueNudgeClosed  = "Not sent: its chief nudge is no longer waiting to be sent"
	SendQueueNudgeMoved   = "Not sent: the window no longer holds the conversation the chief nudged."
	SendQueueNudgeStale   = "Not sent: the session moved on after the chief decided to nudge it."
	// SendQueueNudgeWait is the one gate answer that is NOT final: the
	// session's state could not be read (nudgeUnknown), so the row goes back to
	// queued (sendQueueDeliver hands it on as sendqueue.Outcome.Superseded:
	// nothing reached the host) and is decided on afresh by a later pass.
	// Its words hold on both paths: the dispatcher requeues the row, a
	// person's Send now ends it failed.
	SendQueueNudgeWait = "Not pasted: muster could not read the session's state (is its host connected?)."
)

Why a chief-nudge queued row is not pasted (sendQueueNudgeGate).

View Source
const (
	ComposeChiefRunsOnClaude = "Runs on your Claude subscription (MUSTER_CHIEF_CLAUDE_TOKEN)."
	ComposeChiefNetworkNote  = "Its network is not confined: the chief's container reaches the internet, and not muster's database (docs/chief.md)."
	ComposeChiefRoutingOn    = "Routing work to your sessions: on."
	ComposeChiefRoutingOff   = "Routing work to your sessions: off. Add MUSTER_SESSION_ROUTING=1 to .env and run docker compose up -d --wait."
)

The Account page's lines about the Compose chief, below its switch.

View Source
const (
	// GateStateDecided: the card was answered, by a human or by the router's
	// auto-approval.
	GateStateDecided = "decided"
	// GateStatePending: the card is on the operator's screen, undecided.
	GateStatePending = "pending"
	// GateStateGone: no decision will ever arrive. A caller MUST stop polling.
	GateStateGone = "gone"
)

The three states a gate read can report. They are the router's wire vocabulary, spelled here so a handler does not have to import the client.

View Source
const (
	SignOutEverywhereUnresolved = "muster could not confirm your sign-in, so your other sessions and paired phones were NOT signed out. " +
		"Sign in again and use Sign out everywhere again."
	SignOutEverywhereUnrecorded = "Your sign-ins were ended, but muster could not record the sign-out, so paired phones and queued messages " +
		"may still be active. Sign in again and use Sign out everywhere again, or remove phones on Account → Devices."
)

The two ways a Sign out everywhere can fail, as the person is told.

View Source
const (
	AgentMessagesDefaultLimit = 50
	AgentMessagesMaxLimit     = chatHistoryCap
)

The bounds on one `messages` read.

🔴 THE CEILING IS chatHistoryCap, THE SAME NUMBER THE HUMAN PAGE SHIPS, AND IT IS REFERENCED RATHER THAN RETYPED. handleAgentDetail and handleAgentChatLog both render at most chatHistoryCap messages, so a machine caller cannot ask this route for more of a conversation in one request than the operator's own browser loads — which is the honest shape for a tier whose whole argument is "no wider than what already exists". A second literal here would drift from that one silently, and the drift's direction is the bad one: the machine read growing past the page.

⚠ THE DEFAULT IS DELIBERATELY WELL BELOW THE CEILING. The intended caller is an agent spending its context window on the answer, and a chat message is not a tweet: a tool_call row carries raw JSON arguments and a tool_result row carries dispatch output. 50 is a few screens of conversation; a caller that wants more asks for it and reads `hasMore` to learn whether it got everything.

⚠ THEY ARE EXPORTED FOR ONE REASON, THE SAME ONE ChiefApprovalMaxWait IS: muster states both numbers in its `--help` and applies the default itself, and this binary deliberately does not link the server package — so the relationship is pinned by a test that imports both (cmd/muster's TestTheAgentMessageLimitsMatchTheServers) rather than by a build edge. A help text quoting a bound the server no longer applies is the thing that rots.

View Source
const (
	// MailResumePerSessionPerHour bounds how often one session is resumed.
	MailResumePerSessionPerHour = 2
	// MailResumePerHostPerHour bounds how many windows muster has one host
	// start in an hour (the host holds its own bound as well).
	MailResumePerHostPerHour = 6
	// MailResumeWait bounds how long a resumed window has to come up and take
	// the route before the message goes to the chief.
	MailResumeWait = 90 * time.Second
)
View Source
const (
	PasskeysOffRefusal     = "Passkeys are not enabled on this server."
	PasskeyNoUVRefusal     = "That passkey did not verify you (no PIN, fingerprint, face or device unlock). Use a passkey that asks for one."
	PasskeyRejectedRefusal = "That passkey was not accepted."
	PasskeyUnreadable      = "That passkey response could not be read."
	PasskeyReauthRequired  = "reauth_required"
)

The refusals a passkey route answers with. Each is shown to the person.

View Source
const (
	RefusedSubjectNotFound = "subject_not_found"
	RefusedNotDelivered    = "not_delivered"
)

The refusal reasons plugin_message_route adds to route_to_session's.

View Source
const (
	DraftPushTitle = "A reply draft awaits your approval"
	DraftPushBody  = "Your chief drafted a reply to a plugin message. Nothing is sent until you approve it."
)

The `plugin` push's title (muster's), and its body when the message cannot be read.

View Source
const (
	SendQueueRouteClosed  = "Not sent: its route is no longer waiting for an answer"
	SendQueueRouteMoved   = "Not sent: the window no longer holds the conversation the message was routed to; it went back to the chief."
	SendQueueRouteUnknown = "Not sent: its route could not be read."
)

Why a routed queued message is not sent (sendQueueRoutedGate).

View Source
const (
	SendQueueOwnerDisabled  = "Not sent: the account that queued it is disabled."
	SendQueueOwnerCutoff    = "" /* 160-byte string literal not displayed */
	SendQueueOwnerUnchecked = "Not sent: the account that queued it could not be checked. Queue it again."
	SendQueueCancelDisabled = "Cancelled: the account was disabled."
	SendQueueCancelSignOut  = "Cancelled: signed out everywhere."
)

Why a queued message is not sent because of its owner's account (sendQueueOwnerRefusal), and why it was cancelled (cancelQueuedFor).

View Source
const (
	SendQueueNotQueuedNow   = "Not sent: that message is no longer queued (it is being sent, or has finished)."
	SendQueueSendingAnother = "Not sent: another message for this window is being sent right now. Try again in a moment."
	SendQueueWaitingNow     = "Not sent: Claude Code is waiting for you (a prompt or a question). Answer it first."
)

Why a Send now was refused.

View Source
const (
	// EventTaskChanged nudges an open Tasks board to re-fetch a card.
	EventTaskChanged = "task.changed"
	// EventAgentChanged announces an agent status/identity change.
	EventAgentChanged = "agent.changed"
	// EventChatReply announces a persisted assistant turn.
	EventChatReply = "chat.reply"
	// EventConnectorChanged announces a connector request, decision or change.
	EventConnectorChanged = "connector.changed"
	// EventAttentionChanged announces that something entered or left the
	// owner's attention queue (attention.go) — and that a reply draft's
	// delivery status moved: a plugin claimed it or reported its result
	// (draftStatusMoved), so the Asks page's Archived view re-reads. Spelled with "_queue" so it can
	// never be read as the router's own attention events on a mirrored bus.
	EventAttentionChanged = "attention_queue.changed"
)

--- SSE event names --------------------------------------------------------

🔴 THIS IS THE muster HALF OF A THIRTEEN-NAME BLOCK. The eight that are not here — request created/resolved, auto-approve, suggestion, attention, tmux, terminal-write and transcript — name changes to state this service does not hold. A browser watching muster's /events sees these and nothing else. (privilege.created was one of them until the privilege subsystem was removed.)

View Source
const (

	// RouteTimeout is how long a routed message waits for its session's answer
	// before it is handed back to the chief — every route but a pull-request
	// review's (PRRouteTimeout) and a person's conversation's
	// (ConversationRouteTimeout); routeTimeout picks. A constant, not a setting: it must
	// stay longer than the send queue's idle wait (MUSTER_SEND_QUEUE_IDLE),
	// before which the message cannot even be pasted, so cmd/muster-server's
	// loadConfig refuses an idle wait that is not shorter when routing is on.
	RouteTimeout = 30 * time.Minute
	// PRRouteTimeout is RouteTimeout for a route muster makes for a
	// pull-request review mail (plugins.RouteViaPR; pr_routes.go), and for no
	// other route. Longer because the session that authored the pull request
	// is usually still at work on it: its paste waits for the window to go
	// idle (the send queue's wait), and a session that keeps working does not,
	// so a 30-minute deadline handed most reviews back to the chief before
	// they were pasted. A constant like RouteTimeout; being longer, it never
	// tightens loadConfig's idle-wait check, which RouteTimeout still binds.
	PRRouteTimeout = 4 * time.Hour
	// RequestRouteTimeout is RouteTimeout for a route carrying the OWNER'S OWN
	// REQUEST (route_to_session's text). Longer for PRRouteTimeout's reason: the
	// owner sends an idea to the session already working on it, so that session
	// is usually busy, and its paste waits for the window to go idle; a
	// 30-minute deadline would hand most of them back undelivered. Like
	// PRRouteTimeout, being longer it never tightens loadConfig's check.
	RequestRouteTimeout = 4 * time.Hour
	// ConversationRouteTimeout is RouteTimeout for a route carrying a message
	// its plugin marked human_conversation (plugins.MessageIn.HumanConversation:
	// a person writing in a direct conversation, such as a chat DM). Longer
	// because a person's answer is often the owner's to give, and an owner
	// deciding takes longer than 30 minutes: a shorter deadline handed messages
	// back to the chief while the session was still working on them. It is the
	// MESSAGE's mark, set by its plugin, never a match on the plugin's name.
	// Longer than RouteTimeout, so like PRRouteTimeout it never tightens
	// loadConfig's idle-wait check.
	ConversationRouteTimeout = 4 * time.Hour
	// RouteSweepInterval is how often due routes are timed out.
	RouteSweepInterval = 30 * time.Second
)
View Source
const (
	RefusedBadArguments      = "bad_arguments"
	RefusedMessageNotFound   = "message_not_found"
	RefusedTaskNotFound      = "task_not_found"
	RefusedNoReply           = "no_reply"
	RefusedAlreadyRouted     = "already_routed"
	RefusedReplyInFlight     = "reply_in_flight"
	RefusedWindowGone        = "window_gone"
	RefusedHostNotInteractve = "host_not_interactive"
	RefusedQueueUnavailable  = "queue_unavailable"
	RefusedUnsupported       = "unsupported_target"
	RefusedInjectFailed      = "inject_failed"
	// RefusedNotOwnersTurn: a text route whose owner_asked check failed — the
	// turn is not one the owner typed, or something else runs beside it.
	RefusedNotOwnersTurn = "not_owners_turn"
	// RefusedPluginsOff: a message_id route on a server without the plugin
	// interface.
	RefusedPluginsOff = "plugins_off"
	// RefusedDispatchedWindow: the target window runs an agent the chief
	// started (its listing carries a dispatch): task_forward reaches it, for
	// its task, through the host's tag check (docs/design/chief-dispatch.md 5.1).
	RefusedDispatchedWindow = "dispatched_window"
)

The refusal reasons route_to_session answers.

View Source
const (
	TranscribeTooLarge    = "That recording is too long to transcribe. Record a shorter one (up to two minutes)."
	TranscribeRateLimited = "Too many recordings in a short time. Wait a moment and try again."
	TranscribeBusy        = "The transcription service is busy. Try again in a moment."
	TranscribeEmptyBody   = "No recording arrived, so there was nothing to transcribe."
	TranscribeNotAudio    = "That is not a recording this server can read (WebM, MP4, Ogg or WAV audio)."
	TranscribeCutOff      = "The recording did not arrive whole, so nothing was transcribed. Try again."
	TranscribeUndecodable = "That recording could not be decoded, so nothing was transcribed. Record it again."
	TranscribeRefused     = "The transcription service refused this server's credential, so nothing was transcribed. " +
		"This is a fault in muster's configuration, not something signing in again would fix."
	TranscribeUnavailable = "The transcription service did not answer, so nothing was transcribed. Try again in a moment."
)

The route's answers. Each is muster's own sentence; the page shows it as is.

View Source
const (
	UploadTooLarge    = "That file is too large to attach."
	UploadEmpty       = "That file is empty, so there was nothing to attach."
	UploadNoFile      = "No file arrived, so nothing was attached."
	UploadBusy        = "Other files of yours are still uploading. Try again when they finish."
	UploadServerBusy  = "Too many files are being stored right now. Try again in a moment."
	UploadTooSlow     = "The file did not arrive in time, so nothing was attached. Try again."
	UploadCutOff      = "The file did not arrive whole, so nothing was attached. Try again."
	UploadStoreFailed = "The file could not be stored, so nothing was attached. Try again in a moment."
)

The routes' answers: muster's own sentences, shown by the page as they are.

View Source
const (
	// ViewChiefNotSignedIn: the principal is not a person signed in to muster
	// in a browser (an API token, the hook token, a plugin).
	ViewChiefNotSignedIn = "asking the chief from a session's view takes your own signed-in browser session"
	// ViewChiefNoSubject: the address names no window of the owner's that
	// shows a conversation muster can read.
	ViewChiefNoSubject = "this window shows no conversation muster can name, so the chief cannot be asked about it"
	// ViewChiefNoChief: the owner has no chief, or turned it off.
	ViewChiefNoChief = "you have no chief turned on: turn it on in Account → Chief"
)

The door's refusals, each its own sentence.

View Source
const APITokenRefusal = "invalid or revoked API token"

APITokenRefusal is the 401 body every refused personal token gets — malformed, unknown, revoked or a disabled owner alike, so a refusal says nothing about which.

View Source
const ActorHeader = "X-Muster-Actor"

ActorHeader is the header a service asserts its caller's name in.

🔴 IT IS A CONSTANT BECAUSE TWO WRAPPERS AND EVERY REFUSAL MESSAGE SPELL IT. A header name typed at four sites is a header name that is wrong at one of them, and the direction it would be wrong in is the quiet one: a misspelled read returns "", which is refused, so the surface would simply stop working for the one caller it exists for.

View Source
const AdminOnlyRefusal = "this page is for admins"

AdminOnlyRefusal is what a non-admin principal gets from /admin/*.

View Source
const AgentCreateScopeRefusal = "creating agents needs a token of scope agent-create: mint one at " + accountTokensPath +
	" (Create agents). No other token reaches this route, so that the CLI's ordinary token cannot create agents"

AgentCreateScopeRefusal is the 403 body every token whose scope is not agent-create gets on POST /api/agents — a full token included, which is the point: the CLI's ordinary token must not create agents.

View Source
const AgentCreateStartRequired = `"start" is required: true dispatches the agent now, false creates it stopped (Start it later from its page)`

AgentCreateStartRequired is the 400 body for a request that does not say whether to start the agent: the two outcomes differ too much to default.

View Source
const AgentCreateTokenRefusal = "an agent-create token reaches only " + apiAgentCreatePattern + "; use a full-access token for anything else"

AgentCreateTokenRefusal is the 403 body an agent-create token gets on any route other than POST /api/agents.

View Source
const AgentCreateViaRefusal = "POST /api/agents takes only a personal API token of scope agent-create " +
	"(mint one at " + accountTokensPath + ", Create agents); the shared hook secret and service credentials cannot create agents"

AgentCreateViaRefusal is the 403 body for any principal on POST /api/agents that did not come through a personal token: the shared hook secret, a service credential, anything else.

View Source
const AgentNotRunningNotice = "This agent is not running, so it cannot be sent a message. Start it first."

AgentNotRunningNotice is why an agent that is not running cannot be sent a message.

View Source
const AgentSendEmpty = "nothing to send: type a message first"

AgentSendEmpty answers a send with no text.

View Source
const AgentTurnFailedPrefix = "⚠ This message was not answered: "

AgentTurnFailedPrefix starts the stored line that stands in for a reply when a turn started by POST /agents/{name}/send failed.

View Source
const AskLogSweepInterval = 24 * time.Hour

AskLogSweepInterval is how often the retention sweep runs.

View Source
const AssetLinksPath = "/.well-known/assetlinks.json"

AssetLinksPath is where Android looks for a site's Digital Asset Links.

View Source
const ChatQueuedForDialogNotice = "Its terminal is showing a prompt that needs an answer — your message is queued and will be sent once it is answered."

ChatQueuedForDialogNotice is the queued notice when the session is held by a dialog in the agent's terminal rather than by a turn (code awaiting_approval).

View Source
const ChatQueuedNotice = "Still finishing its previous turn — your message is queued and will be sent as soon as it is free."

ChatQueuedNotice is what the chat shows while a message waits for the turn in flight (the WS "queued" message).

View Source
const ChiefDisplayName = "chief"

ChiefDisplayName is the display name that marks an agent as the fleet's chief.

View Source
const ChiefLLMAgentsReadRefusal = "muster could not read its agents list to tell whether this agent is the chief; nothing was " +
	"sent, retry shortly"

ChiefLLMAgentsReadRefusal is the 503 a caller of POST /llm/v1/messages gets when, with the chief LLM on, the agents list could not be read to tell whether it is the chief (serveLLMMessages).

View Source
const ChiefNotRoutedRefusal = "this chief is not on the LLM route (only the admin's claude-code chief is, with " +
	"MUSTER_CHIEF_LLM=openrouter): the LLM proxy does not serve it, and nothing was sent"

ChiefNotRoutedRefusal is the proxy's answer to a chief the route rule did not put on the LLM route (off Compose): one that is not a claude-code chief.

View Source
const ChiefNotSetUp = "Not available on this install yet. To turn it on, add COMPOSE_PROFILES=chief, " +
	"MUSTER_CHIEF_RUNTIME=compose and MUSTER_CONNECTOR_ENCRYPTION_KEY to .env, run docker compose up -d --wait, " +
	"and come back here (docs/features.md#chief). Everything else works without it."

ChiefNotSetUp is the Account page's text where the chief cannot run: no Compose chief runtime and no agent provisioner. It is the enable step.

View Source
const ChiefNudgeInterval = 2 * time.Minute

ChiefNudgeInterval is how often the sweep runs.

View Source
const ChiefOffProvisionRefusal = "your chief is turned off; turn it on under Account → Chief"

ChiefOffProvisionRefusal is POST /chief/provision's answer to an owner who turned their chief off.

View Source
const ClaimPath = "/auth/claim"

ClaimPath is the admin claim page. The token is NOT in the path: it rides in the URL FRAGMENT (`/auth/claim#<token>`), which a browser never sends to a server, and the page's form posts it as a field.

🔴 A PATH TOKEN WAS WRITTEN TO THE ACCESS LOG. accessLog records r.URL.Path for every request, so `GET /auth/claim/<token>` put a live, single-use admin credential into muster's logs (and any proxy's). A fragment reaches neither (TestTheClaimTokenNeverReachesTheLog).

View Source
const ClaimTTL = 24 * time.Hour

ClaimTTL is how long a claim link stays redeemable.

View Source
const ComposeChiefAccount = "chief"

ComposeChiefAccount is the Claude account the Compose chief's row names. It holds MUSTER_CHIEF_CLAUDE_TOKEN when that is set; otherwise the account has no token and the chief runs on the LLM route.

View Source
const ComposeChiefNeedsCredential = "set MUSTER_CHIEF_CLAUDE_TOKEN (a Claude subscription token from `claude setup-token`) " +
	"or MUSTER_AGENT_OPENROUTER_KEY in .env, then run `docker compose up -d --wait`, which restarts muster"

ComposeChiefNeedsCredential is what the operator is told to add.

View Source
const ComposeChiefNoTerminal = "the Compose chief's terminal is not reachable through muster: there is no " +
	"exec into its container without the Docker socket. Its output is in `docker compose logs chief` on the server"

ComposeChiefNoTerminal is the Terminal view's text on the Compose chief: muster reaches its container over HTTP only (there is no exec without the Docker socket, and the compose driver declares none).

View Source
const ComposeChiefNotYours = "Not available to you on this install. It runs one chief, in its own Compose " +
	"container, and that chief is the admin's. Everything else works without it."

ComposeChiefNotYours is the Account page's text for a user who is not the admin on a Compose install.

View Source
const ComposeChiefOnSubscription = "this chief runs on its Claude subscription (MUSTER_CHIEF_CLAUDE_TOKEN), not on the " +
	"server's OpenRouter key: the LLM proxy does not serve it, and nothing was sent"

ComposeChiefOnSubscription is the LLM proxy's refusal to a Compose chief that the credential rule puts on its Claude subscription.

View Source
const ComposeChiefReplaceRefusal = "the Compose chief cannot be replaced: this install runs one chief, on one kind " +
	"(claude-code), in its Compose container. Change its credential in .env instead, then run " +
	"`docker compose up -d --wait`: that restarts muster, and muster then re-applies a running chief on the new " +
	"credential (docs/chief.md)"

ComposeChiefReplaceRefusal is POST /api/chief/replace's answer on the Compose chief.

View Source
const ComposeDispatchRefusal = "this install runs the chief in its own Compose container and dispatches no other agent: " +
	"agent dispatch needs muster deployed in Kubernetes (docs/features.md#dispatch)"

ComposeDispatchRefusal is POST /agents' answer on the Compose chief.

View Source
const ComposerNoticeAgain = "You were signed in again on the way, so that message was not sent. Send it again."

ComposerNoticeAgain is what a send that came back as a GET is told: it was not delivered (its body did not survive the sign-in it was sent through).

View Source
const ConnectorsUnconfigured = "this server has no connector store: MUSTER_CONNECTOR_ENCRYPTION_KEY is not set"

ConnectorsUnconfigured is why the connector routes refuse on a server with no connector store.

View Source
const CrossOriginRefusal = "cross-origin request refused: this action must come from muster's own pages"

CrossOriginRefusal is the error requireSameOrigin answers.

View Source
const DefaultAgentReapStoppedAfter = 14 * 24 * time.Hour

DefaultAgentReapStoppedAfter is how long an agent may stay stopped before the reaper destroys it, when MUSTER_AGENT_REAP_STOPPED_AFTER is unset.

View Source
const (

	// DefaultChiefAskTimeout is how long a question waits for the chief when chief_ask names no timeout_seconds; one it
	// names is bounded as attention_ask's is (attention.Clean).
	DefaultChiefAskTimeout = 30 * time.Minute
)
View Source
const DefaultChiefLLMModel = "deepseek/deepseek-v4.1-flash"

DefaultChiefLLMModel is the model a chief on the LLM proxy is pinned to when ChiefLLM.Model is empty: an OpenRouter model id.

View Source
const DevicePairRefusal = "this pairing code cannot be used: pair again from a signed-in session"

DevicePairRefusal is the 401 body for a pairing code that cannot be used: unknown, used, expired, or minted by a session that has since been ended.

View Source
const DeviceThrottled = "too many requests from this device or address; wait a minute"

DeviceThrottled is the 429 body for a throttled device-tier request.

View Source
const DeviceTokenElsewhere = "a device credential (" + devices.TokenPrefix + "…) opens " + deviceAPIPrefix + "/* only"

DeviceTokenElsewhere is the 401 body when a device credential is presented on any route outside the device tier.

View Source
const DeviceTokenRefusal = "this route takes a paired device credential (" + devices.TokenPrefix + "…)"

DeviceTokenRefusal is the 401 body for every refused credential on the device tier: another kind of credential, a malformed one, an unknown or removed device, or a revoked one (disabled owner, cutoff, sign-out) — so a refusal says nothing about which.

View Source
const DeviceWebPath = deviceAPIPrefix + "/web"

DeviceWebPath is the open route the Android app reads its sign-in origins from.

View Source
const DevicesNotServed = "this server does not serve paired devices (no database)"

DevicesNotServed is the 503 body when the server has no device store.

View Source
const DisableSweepInterval = 10 * time.Second

DisableSweepInterval is how often the disable sweep (sweepDisabled) re-reads disabled_at for every user with an open request.

View Source
const DoctorPath = "/api/doctor"

DoctorPath is the server half of `muster doctor` (cmd/muster/doctor.go): the facts only the server can state about itself, as one JSON document.

View Source
const DraftStepUpRequired = "Approving a reply needs a recent sign-in. Confirm it's you, then approve again."

DraftStepUpRequired is the Asks page's notice for an approval refused as stale (the page's script did not ask first).

View Source
const EpisodeWaitingGrace = time.Minute

EpisodeWaitingGrace is how long a waiting window's push is held: a prompt answered at the terminal inside it is never pushed. Not configurable — on a live fleet 165 of 169 owner-answered waiting windows were answered inside 60 s. Server.waitingGrace holds it (New); a test may set that field.

View Source
const ErrRelayAdminOnly = "the approval relay files cards only for an admin's agents; this prompt stays in the agent's terminal"

ErrRelayAdminOnly is the relay's refusal for an agent whose owner is not an admin: its prompts stay in its own terminal.

View Source
const FaroRelayPath = "/telemetry/faro"

FaroRelayPath is the relay's route: what the page's Faro posts to when a relay upstream is configured.

View Source
const FeatureDisabledError = "feature_disabled"

FeatureDisabledError is the `error` of the typed answer a route gives when the feature behind it is off: the CLI branches on this value, never on the sentence beside it.

View Source
const FeaturesPagePath = ui.FeaturesPagePath

FeaturesPagePath is the page.

View Source
const FlowNotCancellable = "that job is running or already finished; a running job is the runner's until it reports (stop the runner to stop it now)"

FlowNotCancellable is the 409 body of a cancel that the job's state refuses.

View Source
const FlowsUnconfigured = "this server does not serve browser flows (no database)"

FlowsUnconfigured is the 503 body when no flow store is wired (no database).

View Source
const HookUnarmedField = "unarmed"

HookUnarmedField is the JSON key requireArmedHookToken sets to `true` on its 503, and the ONE thing a client may branch on to tell "this surface is not armed" from "this server is sick".

🔴 EXPORTED FOR THE REASON ServiceTierLogPrefix AND ChiefRefusalLogPrefix ARE: the string a consumer matches must be the string the code writes, stated once. The consumer is cmd/muster (unarmedHookSurface), and the two are pinned together by internal/api's TestTheAgentSteeringWriteRefusesAnUnarmedServer (the server writes it) and muster's TestTheUnarmedMarkerMatchesTheServer (the client reads the same spelling) — a second spelling is a spelling that rots.

View Source
const (

	// HostDispatchSweepInterval is how often the not-seen sweep runs.
	HostDispatchSweepInterval = 10 * time.Minute
)

The reconciler's timings (design 3.7, "Three deadlines").

View Source
const InvitePath = "/invite"

InvitePath is the invitee's page. The token rides in the URL FRAGMENT (`/invite#<token>`), for the reason ClaimPath gives.

View Source
const InviteTTL = 72 * time.Hour

InviteTTL is an invite link's default lifetime; inviteTTLChoices are the lifetimes the create form offers.

View Source
const JobModelUnconfirmedError = "the agent's runtime did not confirm it ran the turn in a Claude Code session of " +
	"the job's own (no " + agents.HeaderCCWorkdirUsed + "), so it may have run in the agent's own session on that " +
	"session's model; the turn's output was discarded; update the agent's image"

JobModelUnconfirmedError is a model job's error when its turn's answer did not come from a session CLI of the job's own (no agents.HeaderCCWorkdirUsed).

View Source
const JobNoOwnSessionError = "this deployment's chat store cannot open a Claude Code session of the job's own, " +
	"so the turn could not be kept out of the agent's checkout and session; nothing was run"

JobNoOwnSessionError is a sha or model job's error when the chat store cannot open a Claude Code session of the job's own (agents.SessionRuntimeStore).

View Source
const JobReapInterval = time.Minute

JobReapInterval is how often RunJobReaper runs after its first pass at boot. A job is reaped at most this long after its deadline (jobs.ReapOverdue).

View Source
const JobResultRemoveFailedPrefix = "could not delete the result file "

JobResultRemoveFailedPrefix opens the note a job's error carries when its result file could not be deleted.

View Source
const JobResultTrackedNotePrefix = "the result file "

JobResultTrackedNotePrefix opens the note a job's error carries when its result file is tracked by the repository and so was not deleted.

View Source
const JobShutdownTimeout = 5 * time.Second

JobShutdownTimeout bounds FailOwnJobs at shutdown.

View Source
const JobWorktreeRemoveFailedPrefix = "could not remove the job's worktree: "

JobWorktreeRemoveFailedPrefix opens the note a job's error carries when its worktree could not be removed.

View Source
const LLMMessagesRoute = "POST /llm/v1/messages"

LLMMessagesRoute is the one route the proxy serves.

View Source
const MaxSSOOrigins = 8

MaxSSOOrigins is how many sign-in origins MUSTER_ANDROID_SSO_ORIGINS may name. The app keeps at most this many, so a longer list would be cut there silently; boot refuses it instead.

View Source
const MirrorHostPath = "/mirror/host"

MirrorHostPath is a machine's OWN view of itself, on its mirror token: is the hub holding a live tunnel from it? `muster doctor` on a joining machine asks it (its `this-host` check), because that machine holds no hook token and its user service reads `active` while it retries a refused token.

View Source
const MirrorSendEmpty = "nothing to send: type a message first"

MirrorSendEmpty answers a send with no text: 400, said rather than dropped.

View Source
const MirrorSendUnconfirmed = "" /* 155-byte string literal not displayed */

MirrorSendUnconfirmed answers a send the host never confirmed.

View Source
const MirrorSendUnconfirmedRepeat = "" /* 161-byte string literal not displayed */

MirrorSendUnconfirmedRepeat answers a send whose nonce was already handed to the host and never confirmed: it may be in the conversation already.

View Source
const NeedChiefOpenRouterKey = "the chief runs on the server's OpenRouter key and there is none: set MUSTER_AGENT_OPENROUTER_KEY " +
	"in .env and restart muster; nothing was sent"

NeedChiefOpenRouterKey is the refusal a chief gets when the server has no OpenRouter key for it.

View Source
const NudgeRelayRetired = "not relayed: relaying an answer to a nudge was retired (migration 0071, notices)"

NudgeRelayRetired is the detail of a decision whose answer an older replica claimed for a relay (relay_queued) after 0071: relaying is retired.

View Source
const OffBrowserListenerRefusal = "browser sign-in is not served on this port; it serves machine tokens only"

OffBrowserListenerRefusal is the error a browser-session route answers on the machine-token listener in gotrue mode.

View Source
const OpenRouterKeySettingsURL = "https://openrouter.ai/settings/keys"

OpenRouterKeySettingsURL is where an OpenRouter key's credit limit is set. The Compose chief on OpenRouter has no muster budget: the limit on the key is its spending cap.

View Source
const OutcomeStarting = "starting"

OutcomeStarting is AgentOutcome.Outcome for an untracked agent whose first turn is still owed.

View Source
const PluginTokenElsewhere = "a plugin token (" + plugins.TokenPrefix + "…) opens " + pluginAPIPrefix + "/* only"

PluginTokenElsewhere is the 401 body when a plugin token is presented on any route that is not the plugin door.

View Source
const PluginTokenRefusal = "this route takes a plugin token (" + plugins.TokenPrefix + "…), minted at " + pluginsPath

PluginTokenRefusal is the 401 body for every refused credential on the plugin door — another kind of token, a malformed one, an unknown or revoked one — so a refusal says nothing about which.

View Source
const ProvisionerUnwiredField = "provisionerUnwired"

ProvisionerUnwiredField is the JSON key both provisioner wrappers set to `true` on its 503 body.

🔴 IT IS THE FIELD, NOT THE SENTENCE, THAT A CLIENT BRANCHES ON — the same shape HookUnarmedField gives the machine tier, and for a sharper reason. Every OTHER 503 a caller meets on these routes is a transient outage worth retrying; this one is a permanent property of the BUILD, and a client that cannot tell them apart retries for ever against a server whose answer can never change. A discriminator made of prose is one a reword silently breaks.

View Source
const ResetDoneNote = "Your password was reset. Your API tokens were revoked; create new ones under API tokens below."

ResetDoneNote is what /account?reset=1 — where a successful password reset lands — says: the reset revoked every personal API token (users.ResetCredentials). ⚠ DISPLAY-ONLY: the query flag is not a fact the server checks, so a hand-typed /account?reset=1 shows it too. It reaches nothing else.

View Source
const ResetPath = "/auth/reset"

ResetPath is the password-reset page; its token rides in the fragment too.

View Source
const RouteWindowGrace = 2 * time.Minute

RouteWindowGrace is how long the route sweep lets a routed message's target session go unseen by every online mirrored window, its paste still queued, before it hands the message back to the chief (routedPastePass): longer than a host's reconnect, so a blip does not drop a route.

View Source
const (

	// RoutedPrefacePrefix opens every routed block's preface (a message's and a
	// task's): the ONE spelling, which the chief nudge sweep also reads to
	// keep a routed paste out of the owner's own messages (chief_nudge.go).
	RoutedPrefacePrefix = "Routed to you by "
)

Who a routed block says routed it (renderRoutedMessageBy): muster's words.

View Source
const RunnerTokenRefusal = "this route takes a flow runner token (" + flows.RunnerTokenPrefix + "…), minted at " + flowsPath

RunnerTokenRefusal is the 401 body for every refused runner credential — another kind of token, a malformed one, an unknown, revoked or disabled owner's — so a refusal says nothing about which.

View Source
const ScopedTokenRefusal = "this API token's scope does not reach this route: a bar-summary token can only read GET " +
	attentionSummaryPath + " (mint a full-access token at " + accountTokensPath + " for anything else)"

ScopedTokenRefusal is the 403 body a bar-summary token gets on a route its scope does not reach.

View Source
const SendAgainHeader = ui.SendAgainHeader

SendAgainHeader is ui.SendAgainHeader: one spelling, which the composer's script reads.

View Source
const SendQueueMayHaveSent = "This message may already have been sent: muster stopped while sending it. Queue it again anyway?"

SendQueueMayHaveSent is what Retry on a message that may already have been sent asks before it queues it again.

View Source
const SendQueueNotClaude = "messages can be queued only for a Claude Code session: muster can tell when one is idle, and not when a shell is"

SendQueueNotClaude is why a mirrored window whose pane is not Claude Code cannot be queued for.

View Source
const SendQueueNotDeleted = "Not deleted: that message is still queued (cancel it first) or is being sent."

SendQueueNotDeleted is why a Delete was refused: the message is not finished.

View Source
const SendQueueRetryConfirmField = "confirm"

SendQueueRetryConfirmField is the form field that says the person confirmed retrying a message that may already have been sent.

View Source
const ServiceTierLogPrefix = "service-tier: "

ServiceTierLogPrefix is the prefix every ATTRIBUTED WRITE admitted by requireServiceToken or requireHookOrServiceToken is logged with.

🔴 EXPORTED FOR THE SAME REASON ChiefRefusalLogPrefix IS: the string an operator greps for must be the string the code writes, stated once. A second spelling in a runbook is a spelling that rots.

⚠ IT REPLACES `AgentTierLogPrefix = "agent-tier: "`, WHICH IS A CHANGE TO WHAT AN OPERATOR GREPS FOR, and it is deliberate rather than cosmetic: nothing behind these two wrappers resolves an agent row any more, so a line calling itself "agent-tier" would name a mechanism that no longer exists. Both wrappers use this ONE constant because they are one tier with two admission shapes; a second spelling would make "which door admitted this write" a question of which prefix the author happened to reach for.

View Source
const SessionStateInterval = 30 * time.Second

SessionStateInterval is how often the state pass runs.

View Source
const SharedTokenOffMachineListenerRefusal = "shared machine tokens are not accepted on this port; " +
	"use a personal API token (mst_) or the machine port"

SharedTokenOffMachineListenerRefusal is the error a hook- or service-tier route answers on the BROWSER listener in gotrue mode, whatever credential (other than a personal mst_ token) was presented.

View Source
const SharedTokenRefusal = "a shared machine token is not an agent credential: connectors are granted per agent, " +
	"so present the calling agent's own token (MUSTER_HOOK_TOKEN inside its pod)"

SharedTokenRefusal is the error a connector route answers when the caller presents a SHARED credential (the hook or service token) instead of an agent's own.

View Source
const SharedTokenRefusalLogPrefix = "shared-token-refusal: "

SharedTokenRefusalLogPrefix prefixes the log line refuseSharedTokenOnBrowserListener writes when a request on the browser listener PRESENTED a non-personal credential — the line to grep for when looking for a client still pointed at the wrong port.

View Source
const SignOutEverywhereTokenNote = "Paired phones are signed out too. API tokens are not affected — revoke them under API tokens below."

SignOutEverywhereTokenNote sits beside "Sign out everywhere": that button ends GoTrue sessions only, and a person must not believe it ended their API tokens (accounts PR 6).

View Source
const StepUpOtherAccountRefusal = "That passkey belongs to a different account. Use a passkey for the account you are signed in to, or your password."

StepUpOtherAccountRefusal answers a passkey that verified — for somebody else. The dialog shows it.

View Source
const (

	// TaskReapInterval is how often the idle-task reaper sweeps.
	//
	// 🔴 IT IS NOT THE RETENTION INTERVAL, AND THE DIFFERENCE IS A FIXED BUG
	// RATHER THAN A PREFERENCE. The reap used to ride a 24h ticker, whose first
	// tick lands a full interval after boot — so whether it ran at all was
	// decided by whether the pod outlived a deploy, and it usually did not.
	TaskReapInterval = 30 * time.Minute
)

--- retention windows ------------------------------------------------------

Variables

View Source
var (
	SendQueueEditingText       = "Editing: the message is held, and nothing queued for this window is sent until you Save or Cancel (at most " + editHoldText + ")."
	SendQueueEditedText        = "Saved: the message keeps its place in the queue."
	SendQueueEditCancelledText = "Edit cancelled: the message is unchanged."
)

What an edit's own notices say.

View Source
var (
	// SendQueueExpired is the same words the dispatcher's expiry sweep
	// records (sendqueue.PGStore.Expire).
	SendQueueExpired            = sendqueue.ExpiredDetail
	SendQueueNotFreshWhenQueued = "Not sent: the sign-in that queued it was not a recent one when it was queued. Retry it to queue it again."
	SendQueueNotFreshWhenEdited = "Not sent: the sign-in that edited it was not a recent one when the edit was saved. Retry it to queue it again."
)

Why a person's queued message is not sent on the sign-in that queued it (sendQueueAuthorization).

View Source
var (
	SendQueueNotEditable       = "Not editable: that message is no longer queued (it was sent, or cancelled)."
	SendQueueEditSending       = "Not editable: that message is being sent right now."
	SendQueueRoutedNotEditable = "Not editable: your chief routed that message, so its text is the chief's."
	SendQueueEditLapsed        = "Not saved: the hold on that message ran out (an edit holds it for " + editHoldText +
		") or it was opened for editing again elsewhere, so it kept its original text. Edit it again to change it."
	SendQueueEditTooLateSent = "Not saved: the hold on that message ran out and it has been sent with its original text."
	SendQueueEditTooLate     = "Not saved: that message is no longer queued (it was cancelled, or has finished)."
	SendQueueHeldNow         = "Not sent: that message is being edited. Save or cancel the edit first."
)

Why an edit was refused, and what it did.

View Source
var AgentCreateTooLarge = fmt.Sprintf("the request body is over %d KiB (%d bytes), the limit for POST /api/agents",
	agentCreateMaxBody>>10, agentCreateMaxBody)

AgentCreateTooLarge is the 413 body for a request over agentCreateMaxBody, spelled from the constant so the two cannot disagree.

View Source
var BuildVersion = "dev"

BuildVersion is the running build version, set from main via -ldflags "-X github.com/ZacxDev/muster/internal/api.BuildVersion=<ver>". Surfaced in /health and the startup log so the running build is identifiable.

View Source
var ConnectSurfacePrefixes = []string{"/connect/", "/agent/connectors", "/mcp", "/agent/approvals", "/agent/blocked", "/agent/work", "/agent/officer", "/llm/"}

ConnectSurfacePrefixes are the path prefixes the agent-facing connect surface is made of. cmd/muster-server's connect listener serves these and refuses everything else, so the network allowance an isolated agent pod is given to reach muster reaches this surface and no other route.

/agent/approvals and /agent/blocked are the claude-code pod's approval relay (approvals.go): the pod's PermissionRequest hook reaches the operator's approval queue THROUGH muster, so the pod holds no credential for that queue. /agent/work is the same pod's live work counts (agent_work.go), on the same per-agent token. /agent/officer is an officer instance's pod uploading a workspace image for an ask (`ccd ask-image`, officers.go), on the same token.

/llm/ is the officer LLM proxy (officer_llm.go): a routine officer instance's Claude Code reaches its model through it, on its own per-agent token, so its pod gains no egress and holds no provider key.

View Source
var ErrAgentBeingReplaced = errors.New("this agent is being replaced or restarted; send the message again once it is up")

ErrAgentBeingReplaced refuses a chat turn to an agent the chief replacement (about to delete it) or chief_restart (about to stop and start it) has closed.

View Source
var ErrChiefNotRunning = errors.New("the chief agent is not running")

ErrChiefNotRunning reports that the chief agent exists but its pod is not up, so there is nothing to ask.

View Source
var ErrChiefOff = fmt.Errorf("%w: the chief is turned off", ErrNoChief)

ErrChiefOff reports that the user has a chief agent and turned it off. It IS an ErrNoChief (errors.Is), so every caller that already handles "no chief" treats an off chief the same way.

View Source
var ErrComposeChiefNoCredential = errors.New("the chief has no credential")

ErrComposeChiefNoCredential is ComposeChief.Credential's answer when the chief has neither credential.

View Source
var ErrDispatchRefused = errors.New("dispatch refused")

ErrDispatchRefused marks a dispatch refused before anything was created: a kind this deployment does not enable, an account pin for a kind that has none, or a claude-code pool with no usable account.

View Source
var ErrModelUnknown = errors.New("unknown model")

ErrModelUnknown marks a model the catalogue check refused. It is wrapped together with ErrDispatchRefused, so every door that answers a refusal before the row (409 with the sentence, the chief's release of its reservation) answers this one the same way.

View Source
var ErrNoChief = errors.New("no agent carries the chief display name")

ErrNoChief reports that no agent carries the chief display name. It is a CONFIGURATION state, not a failure: a deployment with no chief renders recap cards that say so rather than a broken page.

View Source
var MirrorScrollUnsupported = unprefixed(mirror.ErrScrollUnsupported)

MirrorScrollUnsupported is the 409's text when the host cannot scroll.

Functions

func ApprovalCardHost

func ApprovalCardHost(a agents.Agent) string

ApprovalCardHost is BOTH the Host and the Project a relayed card carries: muster's, naming the agent. As the Project it is the only per-project auto-approve window on the router that can approve the card.

🔴 IT IS NAMESPACED ("muster-agent/<name>"), NOT THE BARE AGENT NAME, AND THE CALLER CANNOT CHOOSE IT. The router matches a window to a card by exact Project. A bare name could equal a laptop project's name, and a pod-supplied one could name any project with an open window; either would let a window opened for something else approve this pod's tool call.

func BrowserListener

func BrowserListener(h http.Handler) http.Handler

BrowserListener marks every request h serves as having arrived on the browser (edge) listener. cmd/muster-server wraps MUSTER_BROWSER_PORT's handler in it and nothing else; the key is unexported, so no request can carry the mark any other way.

func BuildAssetLinks(pkg, certs string) ([]byte, error)

BuildAssetLinks renders /.well-known/assetlinks.json for one Android app: its package name and the SHA-256 fingerprints of its signing certificates (comma-separated; 64 hex digits each, with or without colons, any case).

Both empty is "not configured": nil, nil, and the route answers 404. One without the other is an error, as is a malformed package or fingerprint: Android ignores a statement it cannot match, so a typo would otherwise ship as a silent "the app has no passkeys".

Fingerprints are written as Android prints them (`AA:BB:…`, upper case), deduplicated, in the order given.

func ChiefLLMOwner added in v0.178.0

func ChiefLLMOwner(owner int64) bool

ChiefLLMOwner reports whether owner's chief may be served by the LLM proxy: the admin's alone (the key is the admin's). The spec builder's rule on Kubernetes (cmd/muster-server chiefllm.go) asks this same predicate, so no chief is put on the route that the proxy would refuse.

func ComposeChiefRunsOnOpenRouter added in v0.158.0

func ComposeChiefRunsOnOpenRouter(model string) string

ComposeChiefRunsOnOpenRouter is the credential line for the OpenRouter key.

func ComposeChiefStopFailed added in v0.158.0

func ComposeChiefStopFailed(reason string) string

ComposeChiefStopFailed is the container line of a chief turned off whose container says the stop left something running.

func DraftStepUpWhy

func DraftStepUpWhy() string

DraftStepUpWhy is the confirm dialog's sentence on the Asks page.

func GitPushRecipe

func GitPushRecipe(connector, path string) string

GitPushRecipe is the git command line (up to the refspec) that pushes through a connector's proxy.

🔴 BOTH -c KEYS ARE SCOPED TO THE CONNECTOR'S PROXY URL, AND REDIRECTS ARE OFF. An unscoped `http.extraHeader` goes to every URL git talks to, and git's default redirect policy follows the first request's redirect carrying that header to whatever host it names — measured. Scoped to `$MUSTER_CONNECT_URL/connect/<connector>/` the token goes to the proxy only, and `followRedirects=false` keeps git from following even a redirect the proxy itself would never hand out (it answers 502 instead).

func NewAdminClaimLink(ctx context.Context, store ClaimMinter, publicURL string, now time.Time) (string, error)

NewAdminClaimLink mints a claim invite for user 1 and returns the link. The token is shown once here and stored only as its sha256.

func OnlyConnectSurface

func OnlyConnectSurface(h http.Handler) http.Handler

OnlyConnectSurface wraps h so it serves only ConnectSurfacePrefixes (and /health, for a probe), answering 404 for every other path.

func ParseSSOOrigins added in v0.171.0

func ParseSSOOrigins(raw string) ([]string, error)

ParseSSOOrigins parses MUSTER_ANDROID_SSO_ORIGINS: a comma-separated list of exact origins, each `https://host` or `https://host:port`. Empty (or only spaces) is "none": an empty, non-nil list and no error.

Each entry must be exactly an origin: scheme https, a host name or IP address, an optional numeric port, and NOTHING ELSE — no path (not even `/`), query, fragment, user info or wildcard. An empty entry (`a,,b`) is refused too. The host is lower-cased and `:443` dropped, which is the form a browser gives the origin; duplicates after that are dropped. More than MaxSSOOrigins is refused. Any refusal names the offending entry.

func PostgresUsage added in v0.118.0

func PostgresUsage(name string) string

PostgresUsage is a postgres connector's usage line: the query tool, not the proxy.

func ProxyRecipe

func ProxyRecipe(connector, host string) string

ProxyRecipe is THE sentence that tells an agent how to call a connector through the proxy. Every place that teaches the recipe — a connector's usage line, the MCP server's initialize instructions, the gateway agent's system prompt — builds it here, so the URL shape and the header cannot drift apart between them. Placeholders ("<connector>", "<host>") are fine arguments.

func ProxyUsage

func ProxyUsage(name string, hosts []string) string

ProxyUsage is the one-line instruction an agent is given for a connector.

🔴 THE RECIPE SENDS THE AGENT'S TOKEN AS `Authorization: Bearer`, NOT AS X-Muster-Token. HTTP clients resend a custom header on a redirect to another host (curl -L does, for every -H), but drop Authorization when the host changes. The proxy never hands out an off-allowlist redirect in the first place (rewriteLocation); this is the second layer. X-Muster-Token stays accepted (connectorAgentToken) for clients whose Authorization header is already spoken for; such a client must be told not to follow redirects.

func RegisterRoutes

func RegisterRoutes(mux Mux)

RegisterRoutes registers every muster HTTP route on mux.

🔴 IT TAKES NO SERVER, AND THAT IS WHAT MAKES THE ROUTE GOLDEN A CLAIM ABOUT PRODUCTION RATHER THAN ABOUT A FIXTURE.

The body registers against a ZERO-VALUE Server. That is only sound because registration in this package is unconditional — no `if dep == nil { return }` anywhere in the call tree, see the package doc in server.go — so a bare server and a fully-wired one register the identical set. Handler() calls the same registerAll against the real server.

The alternative, which upstream has, is a registrar that branches on which dependencies are present. Then "which routes exist" is a function of the fixture the recorder was handed, and a fixture missing one field produces a golden that is short by a whole block while reading as complete. That is not hypothetical: it cost that project seven routes, with two separate guards green over the hole.

TestRegistrationIsIndependentOfDependencies is the mechanical check. It is a RELATIONSHIP guard — it records from a bare server AND from one with every dependency supplied and demands set equality — not a count, because a count passes whether or not the two agree.

func SendQueueCancelledAnsweredText

func SendQueueCancelledAnsweredText(asker string) string

SendQueueCancelledAnsweredText is what a Cancel of a queued message that had already answered asker's question says ("" = the asker unnamed): the queued paste is cancelled, the answer is not.

func SendQueueEditedAnsweredText

func SendQueueEditedAnsweredText(asker string) string

SendQueueEditedAnsweredText is what a Save of a queued message that had already answered asker's question when it was queued says ("" = the asker unnamed): the text that will be pasted changed, the answer did not. (Cancel's twin: SendQueueCancelledAnsweredText.)

func ServiceWorkerSource

func ServiceWorkerSource() ([]byte, error)

ServiceWorkerSource is sw.js as served: the embedded file with BuildVersion stamped in.

🔴 THE STAMP IS WHAT MAKES A DEPLOY AN UPDATE. A browser only installs a new worker when the script's BYTES change, and most releases change Go and HTML, not sw.js — so without this every such deploy left installed apps on the old worker and the "new version" prompt never appeared. With it, each build's version is part of the script and every deploy is an update.

func SetTelemetryConnectSrc

func SetTelemetryConnectSrc(rawURL string)

SetTelemetryConnectSrc registers an additional connect-src CSP origin from a full URL (only its scheme://host is used). Without this, connect-src 'self' silently blocks every Faro POST and no telemetry is ever sent. Empty/invalid is a no-op (telemetry off ⇒ no CSP relaxation).

func SetUserDisabled

func SetUserDisabled(ctx context.Context, g GoTrueAuth, id int64, disabled bool, invalidate func()) error

SetUserDisabled is DisableUser without a server. invalidate (may be nil) drops a cache entry once the row has changed.

func SetUserDisabledAs

func SetUserDisabledAs(ctx context.Context, g GoTrueAuth, by *users.Actor, id int64, disabled bool, invalidate func()) error

SetUserDisabledAs is SetUserDisabled that audits as by (the CLI passes Via "cli"). With by set and an account store wired, the audit row commits with the change; a GoTrue ban that fails AFTER it gets its own user.ban_failed row.

func ShareBody

func ShareBody(title, text, link string) string

ShareBody is the task text a share pre-fills: the title, then the text, then the URL (or, when the share sent none, the first URL found in the text) — one per line, empty parts dropped, and a part already contained in an earlier line dropped too, so "text = the URL" does not print the URL twice.

func UseOpenRouterModelsURL

func UseOpenRouterModelsURL(u string)

UseOpenRouterModelsURL points the model search at another catalogue. Only the e2eterm build calls it (its fake upstream); a deployable binary never does.

func ValidActor

func ValidActor(s string) bool

ValidActor reports whether s is a legal actor label.

🔴 IT IS EXPORTED SO A DOOR CAN REFUSE BEFORE IT DECODES A BODY. A refusal after the body is read reads as a 400 about the request when the defect is in the server's identity resolution — a different thing, fixed in a different place.

func ValidLegacyProvenancePrefix added in v0.102.0

func ValidLegacyProvenancePrefix(prefix string) error

ValidLegacyProvenancePrefix reports why prefix cannot be a legacy provenance header prefix, or nil if it can. Empty is valid: it means "none".

Types

type AccountFailover added in v0.114.0

type AccountFailover interface {
	AccountFailed(ctx context.Context, agentID int64, account, failure, detail string) ccfailover.Result
	AccountFailedForPool(ctx context.Context, agentID int64, account, failure, detail string) ccfailover.Result
	AwaitRebound(ctx context.Context, r ccfailover.Result) error
	Rebinding(agentID int64) (ccfailover.Result, bool)
	Events(ctx context.Context, agentID int64, limit int) ([]ccfailover.Event, error)
	UseHooks(policy ccfailover.Policy, prepare ccfailover.Prepare)
	Allowed(a agents.Agent) (bool, string)
}

AccountFailover is the part of internal/ccfailover.Service this package uses: the job runner's re-queue (AccountFailed + AwaitRebound), the pool submission's failover of a worker (AccountFailedForPool), a job's wait for its worker's replacement pod (Rebinding + AwaitRebound), the agent page's history (Events) and the officer runtime's hooks (UseHooks).

type AccountStore

type AccountStore interface {
	CreateInvite(ctx context.Context, by users.Actor, tokenHash []byte, email string, expiresAt time.Time) (users.Invite, error)
	ListInvites(ctx context.Context) ([]users.Invite, error)
	RevokeInvite(ctx context.Context, by users.Actor, id int64) error
	OpenInvite(ctx context.Context, tokenHash []byte) (users.Invite, error)
	RedeemInvite(ctx context.Context, tokenHash []byte, email, displayName string,
		create func(context.Context) (string, error), undo func(sub string)) (users.User, error)
	ListUsers(ctx context.Context) ([]users.User, error)
	SetDisabledAs(ctx context.Context, by *users.Actor, id int64, disabled bool) (users.User, error)
	ResetCredentials(ctx context.Context, id int64) (time.Time, error)
	SetRole(ctx context.Context, by users.Actor, id int64, role authz.Role) (users.User, error)
	Audit(ctx context.Context, by users.Actor, action, object string, detail map[string]any) error
	Audited(ctx context.Context, by users.Actor, action, object string, detail map[string]any, fn func() error) error
	RecentAudit(ctx context.Context, limit int) ([]users.AuditEntry, error)
}

AccountStore is what invites and the admin pages need from internal/users.

type ActiveAgent

type ActiveAgent struct {
	Name     string
	Phase    string    // "thinking" | "responding"
	At       time.Time // last activity timestamp
	InFlight bool      // currently streaming (live phase) vs. recently active (Xm ago)
}

ActiveAgent is one entry of the notification panel's ACTIVE section: an agent that is streaming right now (InFlight) or was active within activeAgentWindow.

type AgentConnectorView

type AgentConnectorView struct {
	Name     string   `json:"name"`
	Exists   bool     `json:"exists"`
	Platform string   `json:"platform,omitempty"`
	Hosts    []string `json:"hosts,omitempty"`
	// Grant is this agent's status: none | pending | approved | denied | revoked.
	Grant   string `json:"grant"`
	GrantID int64  `json:"grantId,omitempty"`
	// Usage is how to call it once approved.
	Usage string `json:"usage,omitempty"`
}

AgentConnectorView is what an agent sees of one connector. No secret.

type AgentKinds

type AgentKinds interface {
	// Enabled is the kinds a dispatch may name, in picker order. It always
	// includes agents.KindGateway.
	Enabled() []string
	// ClaudeAccounts is owner's Claude account NAMES (never tokens), for the
	// pin picker.
	ClaudeAccounts(ctx context.Context, owner int64) ([]string, error)
	// SelectClaudeAccount picks the account owner's new claude-code agent runs
	// on, from owner's accounts only, or returns the pin when it names one of
	// them. An error is a dispatch refusal.
	SelectClaudeAccount(ctx context.Context, owner int64, pin string) (string, error)
	// Unavailable maps each enabled kind owner has NO credential for to the
	// sentence telling them what to add. Absent = usable.
	Unavailable(ctx context.Context, owner int64) map[string]string
	// ClaudeAccountStates is what the account pool knows about each of
	// owner's Claude accounts (auth-failed under its current token, last
	// rate-limited), for the job API's worker-pool selection (createPoolJob).
	ClaudeAccountStates(ctx context.Context, owner int64) (map[string]ccpool.AccountState, error)
}

AgentKinds is the dispatch side of agent kinds (cmd/muster-server implements it over internal/ccpool and internal/credentials).

🔴 EVERY ACCOUNT QUESTION IS ASKED FOR AN OWNER. Members bring their own credentials (accounts plan, operator decisions): the names a member's form lists, the account a member's dispatch selects and whether a kind is usable at all are answers about THAT member — never the deployment's pool, which is the admin's.

type AgentOutcome added in v0.165.0

type AgentOutcome struct {
	AgentID     int64  `json:"agentId"`
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
	// Status is the agent's stored status (pending|provisioning|running|stopped|error).
	Status string `json:"status"`
	// Outcome is agentoutcome's running|done|failed|stuck, or "starting" for an
	// agent whose first turn is still owed and that no outcome tracks yet, or ""
	// for an agent nobody started with a first turn.
	Outcome string `json:"outcome"`
	// Reason is why (a failure's error, the watchdog's verdict); "" otherwise.
	Reason string `json:"reason"`
	// Since is when Outcome last changed; null when it never has.
	Since *time.Time `json:"since"`
	// LastActivityAt is the newest evidence of life (agentoutcome.LastActivity).
	LastActivityAt time.Time `json:"lastActivityAt"`
	// DispatchedBy is the chief that started it; null for any other start.
	DispatchedBy *int64 `json:"dispatchedBy"`
}

AgentOutcome is an agent's status and the outcome of what it was started on.

type ApprovalRequest

type ApprovalRequest struct {
	Tool    string   `json:"tool"`
	Command string   `json:"command"`
	Input   string   `json:"input"`
	Cwd     string   `json:"cwd"`
	Session string   `json:"session"`
	Context []string `json:"context"`
}

ApprovalRequest is the POST /agent/approvals body the pod's hook sends.

type AskLog added in v0.165.0

type AskLog struct {
	// Store is the log (asklog.PG).
	Store asklog.Store
	// TextTTL is how long question and answer text is kept
	// (MUSTER_ASK_LOG_TEXT_TTL); 0 is asklog.DefaultTextTTL.
	TextTTL time.Duration
	// JevAtCapture runs the stall classifier on a kept plain-text question at
	// capture (MUSTER_ASK_LOG_CLASSIFY), reusing the stall sweep's answer for
	// the streak when it has one. Off: the jev columns stay empty.
	JevAtCapture bool
}

AskLog is the ask log's configuration (MUSTER_ASK_LOG; Extensions.AskLog).

type AuthConfig

type AuthConfig struct {
	// HookToken, when non-empty, is required (Bearer or X-Muster-Token) on the
	// machine-called endpoints.
	HookToken string
	// ServiceToken gates the SERVICE-TO-SERVICE door: the credential a NAMED
	// sibling process presents, together with an X-Muster-Actor header naming
	// the caller it is acting for.
	//
	// 🔴 IT IS FAIL-CLOSED. The hook tier's enforce-when-set shape is a
	// back-compat debt to callers that predate the token; a door with no legacy
	// caller is owed none, so unset means 503 here. See ServiceWriteRefusal for
	// each refusal and the reason it exists, and requireServiceToken for the
	// trust this door widens.
	ServiceToken string
	// UIPassword is the shared operator secret that gates the HUMAN web tier.
	// FAIL-CLOSED: unset or too short means the browser surface refuses, it does
	// NOT mean the surface is open. See BrowserAuthRefusal.
	UIPassword string
	// SecureCookies marks the session cookie Secure. It is off by default because
	// a common path to this server is a plain-HTTP LAN port, and a Secure cookie
	// there is never sent — which would present as "login succeeds and then
	// nothing is logged in".
	SecureCookies bool
	// Mode is MUSTER_AUTH_MODE. The zero value is AuthModePassword, so every
	// existing construction keeps today's behaviour. See accounts.go.
	Mode AuthMode
	// PublicURL is where a person should sign in (MUSTER_PUBLIC_URL). It is
	// named in the refusal the machine-token listener gives a browser in
	// gotrue mode, and it is the base of the admin claim link.
	PublicURL string
}

AuthConfig holds every auth tier this app performs.

🔴 THREE FIELDS FROM THE UPSTREAM SHAPE ARE ABSENT, AND THEIR ABSENCE IS A SECURITY PROPERTY RATHER THAN TIDYING. TerminalToken, TerminalUIWrites, TerminalUIHosts and ChiefToken all gated the terminal-WRITE surface — a free-form `send-keys` box onto an operator's real terminals. That surface is on the permission router's side of the carve in its entirety: muster registers no route that can reach an OPERATOR'S terminal, so a server that carried those credentials would be holding the keys to a door it does not have. Do not add them back "for parity"; a credential with no route is a credential that can only ever be leaked.

⚠ muster DOES NOW HAVE ONE TERMINAL ROUTE, AND IT NEEDS NONE OF THEM. A claude-code agent's live terminal (terminal.go, GET /agents/{name}/terminal and its socket) attaches to that AGENT'S own tmux session inside its own pod. It sits behind requireSession, the human tier, exactly as the agent chat socket does, and the hook token does not open it (TestTheTerminalSocketRefusesTheHookToken).

HookToken protects the machine-called surface via a bearer token. It is enforce-when-set: an empty HookToken leaves those endpoints open, a back-compat debt to callers that predate the token.

UIPassword is the HUMAN tier, and it is FAIL-CLOSED — the opposite polarity to HookToken, and that difference is the entire control. See BrowserAuthRefusal.

func (AuthConfig) BrowserAuthRefusal

func (c AuthConfig) BrowserAuthRefusal() string

BrowserAuthRefusal returns a human-readable reason this server will NOT serve the human web tier, or "" when it will.

🔴 IT IS FAIL-CLOSED, AND THAT POLARITY IS THE WHOLE POINT — it is the TerminalWriteRefusal shape, not the requireHookToken shape. An unset password must mean "refuse", never "serve to anyone", because "anyone" here is anyone who can reach a plain-HTTP LAN NodePort, and what they reach is the operator's session transcripts, tool inputs (file paths, bash command lines, edit bodies), and the approve/deny queue.

⚠ THIS PARAGRAPH USED TO END "and — through requireArmedTerminalUI — a free-form send-keys box", AND THE CLAUSE WAS INHERITED RATHER THAN TRUE. No such wrapper and no terminal-write surface onto the operator's terminals exists in this module: those routes stayed with the permission router in the carve. (An agent's own terminal is here now, behind this same tier; see AuthConfig.) The reasoning is unaffected — the transcripts and the approve/deny queue are on their own enough to make an open LAN port unacceptable — but the example was evidence for a hazard that is not on this side of the split, and evidence for the wrong service is what makes a reader stop checking.

⚠ THE COST, STATED PLAINLY: a deploy whose secret fails to mount serves NO web UI at all, rather than an open one. That is the intended trade. main() logs which state it is in at boot, unconditionally and in both directions, because a silent healthy state and a silent refusing state are otherwise identical in the log.

func (AuthConfig) HookArmingRefusal

func (c AuthConfig) HookArmingRefusal() string

HookArmingRefusal reports why this server must not serve a FAIL-CLOSED hook-tier route, or "" when it may. Today there is one reason: no MUSTER_HOOK_TOKEN.

🔴 IT EXISTS BECAUSE "enforce-when-set" IS A BACK-COMPAT PROMISE, AND A ROUTE THAT HAS NEVER SHIPPED IS OWED NONE. requireHookToken leaves an unconfigured server OPEN so the hook scripts that predate the token keep working; that is a debt to EXISTING callers, not a house style. A brand-new route has no existing caller to break, so inheriting the open default would be giving away a gate for nothing in return — which is exactly what task #633's audit found: the agent-steering write moved from a gate that refused unconditionally (requireOperatorToken, since deleted with the operator tier in task #653 phase two) onto one that serves anybody when a variable is unset.

⚠ THE SHAPE IS THE ONE THE OTHER DOORS THAT MATTER ALREADY USE. BrowserAuthRefusal (the human tier), TerminalWriteRefusal and ChiefWriteRefusal are all fail-closed, and main.go states the reason in so many words: "an unset value refuses the web UI rather than serving it to anyone who can reach the LAN NodePort." The hook tier's openness is the exception here, not the rule.

func (AuthConfig) ServiceWriteRefusal

func (c AuthConfig) ServiceWriteRefusal() string

ServiceWriteRefusal returns a human-readable reason this server will NOT serve the service-to-service tier, or "" when it will.

🔴 IT IS THE ChiefWriteRefusal SHAPE WITH TWO MORE CASES, AND IT IS FAIL-CLOSED FOR THE REASON HookArmingRefusal GIVES: "enforce-when-set" is a back-compat promise to callers that predate the token, and a door that has never shipped has no such caller. Inheriting the open default would give away a gate for nothing.

The four refusals, in order:

  • unset — the state a fresh deploy, a missing secret key and a typo'd env var all land in. This is the state this change SHIPS in, on purpose: no manifest sets MUSTER_SERVICE_TOKEN, so every route on this tier answers 503 until an operator decides otherwise.
  • too short — a placeholder rather than generated entropy.
  • identical to HookToken — that token is ONE shared value, handed to every hook script on every host and possibly travelling in cleartext to a plain-HTTP port many times a day, so it NAMES NO CALLER. This door's whole content is an asserted identity; admitting the secret every hook holds would let any of them assert any name, which is a WRONG identity rather than a missing one.
  • identical to UIPassword — 🔴 AND THIS ONE IS NOT PARANOIA. uiSessionSecret DERIVES the browser session-cookie signing key from that password, so a holder of a value that opened both doors could mint a signed operator session for themselves: the service credential would silently become the human tier.

That is boot-validated distinct from every other door this server has — two secrets plus the cookie key derived from the third.

⚠ TWO REFUSALS FROM THE UPSTREAM SHAPE ARE GONE BECAUSE THE CREDENTIALS THEY NAMED ARE GONE, NOT BECAUSE THE HAZARD WAS RE-JUDGED. They compared this token against the terminal and chief secrets, neither of which muster holds (see AuthConfig). If either credential is ever added here, its distinctness case has to come back with it — a field added without its refusal is a door that can silently collapse into another.

⚠ A "" RETURN IS NOT A CLAIM THAT A CALLER WILL BE ADMITTED. It says the server is willing to serve the tier; requireServiceToken still compares the presented credential AND still requires an attributable X-Muster-Actor, and it refuses if either fails. Configuration and admission are separate questions.

The caller decides what to do with a non-empty reason: main() logs it at boot (unconditionally, in both directions — a silent healthy state and a silent refusing state are otherwise byte-identical in the log), and requireServiceToken answers 503.

func (AuthConfig) SharedSecretPrefixRefusal

func (c AuthConfig) SharedSecretPrefixRefusal() string

SharedSecretPrefixRefusal reports why the shared machine secrets collide with the personal-token or plugin-token namespace, or "".

🔴 THE PLUGIN PREFIX IS REFUSED WHETHER OR NOT PLUGINS ARE ON: every door but the plugin door refuses an `mpl_` credential by shape (refusePluginTokenElsewhere) even with MUSTER_PLUGINS off, so a shared secret in that namespace would be refused on every route.

type AuthMode

type AuthMode string

AuthMode is MUSTER_AUTH_MODE.

const (
	// AuthModePassword is the shared operator password (the default).
	AuthModePassword AuthMode = "password"
	// AuthModeGoTrue is per-user login through muster's GoTrue.
	AuthModeGoTrue AuthMode = "gotrue"
)

type CatalogModel added in v0.165.0

type CatalogModel struct {
	ID   string
	Name string
}

CatalogModel is one model of the catalogue: OpenRouter's id ("vendor/model") and its display name ("Vendor: Model Name").

type ChiefLLM added in v0.158.0

type ChiefLLM struct {
	// Model is the OpenRouter model every chief request is pinned to; "" is
	// DefaultChiefLLMModel.
	Model string
	// Key is the admin's OpenRouter key (MUSTER_AGENT_OPENROUTER_KEY). Empty
	// is not a boot refusal: each request is refused (400, nothing sent) with
	// a message naming the variable.
	Key string
	// Upstream replaces the provider's API base (llmproxy.DefaultUpstream when
	// ""), and HTTP its transport: tests.
	Upstream string
	HTTP     *http.Client
	// Routed is the spec builder's own predicate for whether an agent runs
	// on the LLM route (agentprovision.ChiefLLMRouted over the server's
	// rule). Off Compose it is asked on every request, and a chief it does
	// not route — a gateway-kind chief, or a member's — is refused (403,
	// nothing sent). nil there refuses every chief: the proxy never serves
	// one no rule put on the route. On Compose the credential rule decides
	// instead (ComposeChief.Credential).
	Routed func(ctx context.Context, a agents.Agent) (bool, error)
}

ChiefLLM is EnableChiefLLM's input: the chief's place on the LLM proxy.

type ChiefNudges added in v0.112.0

type ChiefNudges struct {
	// Idle is how long a session must have been idle (MUSTER_CHIEF_NUDGE_IDLE).
	Idle time.Duration
	// HourlyCap bounds nudges per hour across every owner, shadow and live
	// together (MUSTER_CHIEF_NUDGE_HOURLY_CAP).
	HourlyCap int
	// Live is the owners whose nudges are SENT (MUSTER_CHIEF_NUDGE_LIVE_OWNERS);
	// everyone else is in shadow mode.
	Live map[int64]bool
	// NeedsYouLive is the owners whose NEEDS-YOU nudges are sent too
	// (MUSTER_CHIEF_NUDGE_NEEDS_YOU_LIVE_OWNERS): a nudge to a session the
	// classifier says asked something is live only for an owner in BOTH Live
	// and this; for everyone else it is shadow — recorded, never pasted, and
	// the stop pushed. Operator decision 2026-11-04, "Separate shadow gate".
	NeedsYouLive map[int64]bool
	// ChiefChatQuotesLive is the owners whose nudges QUOTING THE CHIEF CHAT are
	// sent too (MUSTER_CHIEF_NUDGE_CHIEF_CHAT_QUOTES_LIVE_OWNERS; session-state
	// step 3b-1, chief_chat_quotes.go): such a nudge is live only for an owner
	// also in this, on top of every other gate it is under; for everyone else
	// it is shadow. A same-session quote is not under it.
	ChiefChatQuotesLive map[int64]bool
	// Classifier is the stall classifier (Jev over OpenRouter's Decisions API,
	// on the owner's OpenRouter key); nil: the chief decides alone.
	Classifier *chiefnudge.Classifier
	// AskThreshold is the ask score at which a stall defaults to an ask
	// (MUSTER_CHIEF_NUDGE_ASK_THRESHOLD; 0 = chiefnudge.DefaultAskThreshold).
	AskThreshold float64
}

ChiefNudges is the stall nudges' configuration (cmd/muster-server).

type ClaimMinter

type ClaimMinter interface {
	CreateClaimInvite(ctx context.Context, tokenHash []byte, claimUserID, createdBy int64, expiresAt time.Time) error
}

ClaimMinter is what minting a claim link needs from the store.

type ClaudeAccountHealth

type ClaudeAccountHealth interface {
	ClaudeAccountAuthFailure(ctx context.Context, owner int64, account string) (string, error)
}

ClaudeAccountHealth is an optional extension of AgentKinds: whether one of owner's Claude accounts can authenticate. "" means usable; a sentence says why not. The chief replacement asks it before deleting anything (chief_replace.go); dispatch does not, because a pin there is an override. cmd/muster-server's kindSet implements it (asserted there).

type ClosedPRs added in v0.137.0

type ClosedPRs struct {
	States PRStateReader
	Store  plugins.PRReviewSettler
	// Timeout bounds one GitHub read (prStateTimeout when 0).
	Timeout time.Duration
	// Now is the cache's clock (time.Now when nil).
	Now func() time.Time
	// contains filtered or unexported fields
}

ClosedPRs is the closed-pull-request settle's dependencies, and its cache of GitHub's answers. The zero cache is ready to use.

type ComposeChief added in v0.158.0

type ComposeChief struct {
	// Credential is which credential owner's chief runs on, or
	// ErrComposeChiefNoCredential naming what to add. Required.
	Credential func(ctx context.Context, owner int64) (ComposeChiefCred, error)
	// OpenRouterKey is owner's OpenRouter key from the credential plane
	// (credentials.Plane.OpenRouterKey, the plane the Account page and
	// Credential read). The LLM proxy serves the chief on it. Required.
	OpenRouterKey func(ctx context.Context, owner int64) (string, error)
	// Spec reads the chief's spec on the volume: its generation (whether the
	// boot re-apply restarted the chief) and its replicas (whether it is live:
	// the re-apply never starts a stopped spec). Nil: nothing is re-applied.
	Spec func() (generation int64, replicas int, err error)
	// StartIfLive is the provisioner's Start, made only when live says so, the
	// check and the start under the agent's lifecycle lock (agentprovision
	// Adapter.StartIfLive): a Stop from the agent page during boot is never
	// undone by the boot re-apply. Nil: nothing is re-applied.
	StartIfLive func(ctx context.Context, agentID int64, live func() (bool, error)) (bool, error)
}

ComposeChief is Extensions.ComposeChief: the Compose chief's settings.

type ComposeChiefCred added in v0.158.0

type ComposeChiefCred string

ComposeChiefCred is which credential the Compose chief runs on.

const (
	// ComposeChiefClaude: the Claude subscription token, MUSTER_CHIEF_CLAUDE_TOKEN.
	ComposeChiefClaude ComposeChiefCred = "claude"
	// ComposeChiefOpenRouter: the owner's OpenRouter key, through muster's LLM
	// proxy (the claude-code CLI on CCD_LLM_ROUTE=muster).
	ComposeChiefOpenRouter ComposeChiefCred = "openrouter"
)

type CredentialStore

type CredentialStore interface {
	List(ctx context.Context) ([]credentials.Summary, error)
	PutClaude(ctx context.Context, name, token string) error
	PutOpenRouter(ctx context.Context, key string) error
	Delete(ctx context.Context, kind, name string) (bool, error)
	// UsesEnvironment reports whether owner's agents run on the environment's
	// credentials (an admin): such a user has nothing to add here.
	UsesEnvironment(ctx context.Context, owner int64) bool
}

CredentialStore is what the page needs (internal/credentials.PGStore, with the plane's role decision beside it).

type DoctorHost

type DoctorHost struct {
	Host string `json:"host"`
	// Token: the principal holds an unrevoked mirror token for it.
	Token bool `json:"token"`
	// Online: its muster-mirror is connected now (the hub's view).
	Online bool `json:"online"`
	// Interactive: it advertised -interactive.
	Interactive bool `json:"interactive"`
}

DoctorHost is one mirrored host.

type DoctorMirror

type DoctorMirror struct {
	// Enabled: MUSTER_MIRROR=1 with a database (the plugin is wired).
	Enabled bool `json:"enabled"`
	// Hosts is every host the principal holds a live token for, plus any host
	// the hub lists that has none (a token revoked while it was connected),
	// sorted by name. Empty, not null, when there are none.
	Hosts []DoctorHost `json:"hosts"`
	// HostsError is why the token list could not be read ("" when it was).
	HostsError string `json:"hosts_error,omitempty"`
}

DoctorMirror is the mirror plugin as the viewing principal sees it.

type DoctorReport

type DoctorReport struct {
	// AuthMode is "password" or "gotrue".
	AuthMode string `json:"auth_mode"`
	// HookTokenArmed: MUSTER_HOOK_TOKEN is set and usable (HookArmingRefusal
	// is empty). Stated even though a hook-token caller only gets here on an
	// armed server, because a PERSONAL token is admitted either way and must
	// not read as proof the shared machine tier is closed.
	HookTokenArmed bool `json:"hook_token_armed"`
	// Push: the Web Push routes serve (the VAPID triple and a database).
	Push bool `json:"push"`
	// Dictation: a message box draws a microphone (MUSTER_STT_TOKEN set).
	// Whether the service actually transcribes is the client's check: it
	// sends a sample through POST /transcribe.
	Dictation bool         `json:"dictation"`
	Mirror    DoctorMirror `json:"mirror"`
	// Features is every feature in the registry (features.go): its state, why,
	// and how to turn it on — variable NAMES, never values. Empty, not null,
	// when no registry is installed.
	Features []FeatureView `json:"features"`
}

DoctorReport is GET /api/doctor's body.

🔴 EVERY FIELD IS READ FROM THE SAME STATE THE FEATURE ITSELF READS, NOT FROM THE CONFIGURATION THAT WAS MEANT TO PRODUCE IT. Push is "the push routes would serve" (pushServed), dictation is "a microphone would be drawn" (dictatePath), and each host's Online is the tunnel hub's — so a doctor that says PASS and a phone that shows the feature cannot disagree about whether it exists.

⚠ IT CARRIES NO SECRET AND NO PER-USER CONTENT: booleans and the viewing principal's own host names. The route is still behind the armed hook token (or a personal token), so an unarmed server answers 503 with HookUnarmedField — which is itself what the doctor reports as "hook token: FAIL", read from the server rather than guessed by the client.

type Extensions

type Extensions struct {
	// LegacyProvenanceHeaderPrefix is MUSTER_LEGACY_PROVENANCE_HEADER_PREFIX:
	// when set, the task-provenance headers are also read as
	// `<prefix>-Source`, `<prefix>-Session-Id` and `<prefix>-Host`, for
	// installed clients that predate the X-Muster-* spelling
	// (provenance_headers.go). Empty: only X-Muster-* is read.
	LegacyProvenanceHeaderPrefix string

	Notes  notes.Store
	Agents agents.Store
	// Users answers a user's role for the request Principal (principal.go's
	// roleOf). Nil: user 1 is admin and everyone else a member.
	Users users.Store
	// APITokens is the personal API token store (accounts PR 6;
	// api_tokens.go). Nil: no personal token is admitted anywhere (503).
	APITokens apitokens.Store
	// Devices is the paired-device store (the Android app; devices.go). Nil:
	// no device is paired or admitted anywhere (503).
	Devices devices.Store
	// AllowPINKeys is MUSTER_ANDROID_ALLOW_PIN_KEYS: a phone with no strong
	// biometric may pair with a biometric-or-PIN step-up key. False (the
	// default): such a phone pairs read-only.
	AllowPINKeys bool
	// AssetLinks is the body of /.well-known/assetlinks.json (BuildAssetLinks,
	// from MUSTER_ANDROID_PACKAGE and MUSTER_ANDROID_CERT_SHA256): the
	// Android app's claim on this site's passkeys. Nil: the route answers 404.
	AssetLinks []byte
	// SSOOrigins is MUSTER_ANDROID_SSO_ORIGINS as ParseSSOOrigins returned it:
	// the sign-in origins the Android app may load in its WebView, served open
	// at GET /api/device/web (device_web.go). Nil or empty: `[]`.
	SSOOrigins []string

	// AgentNamespacePrefix is the prefix [Extensions.AgentNamespace] builds a new
	// agent's stored namespace from. It is the DEPLOYMENT's prefix — the same
	// MUSTER_AGENT_NAMESPACE_PREFIX the provisioning driver is configured with —
	// and NOT a default this package chooses.
	//
	// 🔴 IT IS HERE BECAUSE A HARDCODED CONSTANT WAS SHIPPED IN ITS PLACE AND
	// DISAGREED WITH THE DRIVER, SILENTLY. The row-writing handler used
	// agents.NamespaceFor(name) over agents.NamespacePrefix ("devpod-") while the
	// driver created `muster-agent-<name>`. Nothing fails when those differ: the
	// value is recorded, served on GET /api/agents and labelled onto the
	// instance's objects, and NOTHING places anything with it — so a card names a
	// namespace that holds nothing and reads as "never provisioned" while the
	// instance runs one namespace over. Measured live.
	//
	// 🔴 EMPTY IS NOT A SUPPORTED PRODUCTION STATE WHEN AGENTS CAN BE CREATED, and
	// defects() says so rather than this comment: an unset prefix beside a wired
	// Agents store and Provisioner means the wiring was FORGOTTEN, and the
	// consequence is the defect above rather than a missing feature. It resolves
	// to agents.NamespacePrefix so a test fixture need not set it, which is
	// exactly why the omission has to be caught somewhere that is not a reader's
	// attention.
	AgentNamespacePrefix string

	// SessionLiveness answers "does a transcript record for this session still
	// exist" — the one bit SessionLink.DetailAvailable is made of.
	//
	// 🔴 IT IS A PORT, NOT A STORE, BECAUSE THE DATA IS NOT THIS SERVICE'S. The
	// session table stays with the permission router. Nil is TOLERATED and is not
	// a supported production state: the wrapper still applies, but every link
	// resolves to false and the three-state transcript row collapses to two. See
	// withSessionLiveness for why that is tolerated rather than fatal, and
	// TestExtensionsWiringPairsNotesWithALivenessProbe for what stops it shipping.
	SessionLiveness SessionLivenessProbe

	// TagAutoDispatch arms the `auto:dispatch` routing tag
	// (MUSTER_TAG_AUTODISPATCH). It ships FALSE and implements PLUMBING ONLY
	// (recognition + eligibility + a log line + the metric) — no hands-off
	// dispatch behaviour. Rationale: the MANUAL dispatch loop has never closed
	// end-to-end, and automating a path that has never once worked by hand
	// converts an unproven feature into an unattended one. While false,
	// `auto:dispatch` behaves as a descriptive tag.
	TagAutoDispatch bool

	// Provisioner drives agent instance LIFECYCLE (provision/start/stop/delete,
	// state, logs). Nil disables the seven lifecycle routes even if Agents is set,
	// through requireLifecycleProvisioner.
	Provisioner Provisioner

	// ComposeChief is set when the provisioner runs the chief, and only the
	// chief, in the docker compose install's `chief` container
	// (MUSTER_CHIEF_RUNTIME=compose; compose_chief.go). Lifecycle stays wired
	// for the chief; every surface that DISPATCHES an agent reads it as off
	// (dispatchServed).
	ComposeChief *ComposeChief

	// Gateway drives agent CHAT. Nil disables the two chat routes even if
	// Provisioner is set, through requireGatewayProvisioner.
	//
	// 🔴 IT IS A SEPARATE FIELD FROM Provisioner ON PURPOSE — see [Gateway]. The
	// two nils are independent, so a deployment that can provision but not chat
	// renders truthfully instead of having to choose which lie to tell.
	Gateway Gateway

	// Kinds answers which agent kinds a dispatch may ask for and, for the
	// claude-code kind, which Claude account it runs on. Nil means the gateway
	// kind alone — every deployment before kinds existed — and the dispatch form
	// shows no picker.
	Kinds AgentKinds

	// ModelCatalog is the model catalogue every door that sets an agent's model
	// checks it against (model_validate.go): OpenRouterCatalog() in a deployment.
	// nil reads as an UNREACHABLE catalogue — an id-shaped model passes unchecked
	// and anything else is refused — never as "everything goes".
	ModelCatalog ModelCatalog

	// Outcomes writes a started agent's outcome (internal/agentoutcome,
	// migration 0088): agent_outcome.go and the watchdog. nil (no database):
	// nothing is tracked, a failed turn changes no status, and the watchdog
	// does nothing.
	Outcomes agentoutcome.Store

	// AgentWatchdog is the outcome watchdog's thresholds
	// (MUSTER_AGENT_STUCK_NO_REPLY, MUSTER_AGENT_STUCK_SILENT); the zero value is
	// agentoutcome.DefaultThresholds.
	AgentWatchdog agentoutcome.Thresholds

	// PublicURL is MUSTER_PUBLIC_URL, the externally reachable origin. Its host
	// is one of the origins requireSameOrigin and the WebSockets accept
	// (wsAllowedOrigins), for proxy setups that rewrite Host. "" accepts only
	// the request's own Host.
	PublicURL string
	// GitHubApp, when set, is muster's GitHub identity (internal/githubapp):
	// every connected-repository check lists the App's installation
	// repositories (github_source.go). The same App backs the `github`
	// connector (wired into Connectors by connectors.WithVirtual, so the two
	// cannot disagree about whether it is configured). nil: muster has no
	// GitHub identity, and every repository check answers errNoGitHub.
	GitHubApp GitHubApp

	// Push is muster's own Web Push (internal/push; push_routes.go). nil: no
	// VAPID keys are configured — no Enable button is drawn, the key route
	// answers 503, and nothing is ever sent.
	Push PushService

	// Transcriber turns a recording into text for the message box's microphone
	// (transcribe.go; internal/stt). nil: no speech-to-text service is
	// configured (MUSTER_STT_TOKEN unset) — no microphone is drawn on any
	// message box and POST /transcribe answers 404.
	Transcriber Transcriber

	// Uploads is the composer's file attachments (internal/uploads, migration
	// 0024; uploads.go). nil: not configured (the MUSTER_S3_* / signing key /
	// public URL set is incomplete, or there is no database) — no composer
	// draws an attach button and every upload route, the signed link
	// included, answers 404.
	Uploads *uploads.Service

	// Credentials is the per-owner model-provider credential store behind
	// Account → Credentials (internal/credentials). nil: none configured — the
	// page says so, and every member then has no credential (never the
	// admin's). See credentials.go.
	Credentials CredentialStore

	// Connectors is the secure connector store. nil means the feature is off
	// (no MUSTER_CONNECTOR_ENCRYPTION_KEY): every connector route answers 503 and
	// the tab is not drawn. See internal/connectors and connectors.go.
	Connectors connectors.Store
	// ConnectorPolicy is the proxy's upstream network policy. The zero value is
	// production's strict one; see connectors.Policy.
	ConnectorPolicy connectors.Policy
	// DialGuard, when set (MUSTER_DIAL_DENY_PRIVATE=1), is how the postgres
	// connector dials its database: a host that is, or resolves to, a
	// non-public address is refused at connect time. nil dials any host.
	DialGuard *safedial.Guard

	// Mirror is the optional MIRRORED-sessions plugin (internal/mirror). nil
	// means the plugin is off (MUSTER_MIRROR unset), which is the default: GET
	// /mirror/connect and the mirror terminal routes answer 404 and the sidebar
	// lists no mirrored entry. See mirror.go.
	Mirror Mirror

	// Flows is the browser-flow queue and its runner tokens (internal/flows,
	// migration 0012). nil (no database): every flow route answers 503 and
	// /flows says so.
	Flows flows.Store

	// Plugins is the plugin interface's store (internal/plugins, migration
	// 0015). nil means plugins are OFF (MUSTER_PLUGINS unset), which is the
	// default: every /plugin/* route and /plugins answer 404. See plugins.go.
	Plugins plugins.Store
	// PluginGateway resolves the owner's chief before a plugin message is handed
	// to it (agentgateway.Gateway satisfies it); the turn itself is chatTurn's,
	// over Gateway, so the chief has its tools on it. nil (or a nil Gateway) with
	// Plugins set: messages are stored and stay queued — nothing is delivered.
	PluginGateway plugins.Gateway

	// Pins is the per-user pins the session switcher sets and shows (internal/pins,
	// migration 0017). nil (no database): nothing is pinned, the switcher's Pins
	// view is empty, and the pin routes answer 404.
	Pins pins.Store

	// SessionTags is the per-user session tags (internal/sessiontags): the
	// session switcher's ⋯ → Tags…, the session headers' chips, and words the
	// palette and the dock's filter match. nil (no database): no session has
	// tags, and the tag routes answer 404.
	SessionTags sessiontags.Store

	// Recents is the per-user "recently viewed" entries (internal/recents,
	// migration 0018): the session switcher's Recent view, and where home goes
	// with no chief. nil (no database): no visit is recorded and Recent is empty.
	Recents recents.Store

	// SendQueue is the server-side send queue (internal/sendqueue, migration
	// 0019). nil (no database): no composer draws Queue, the queue routes answer
	// 404, and RunSendQueue does nothing.
	SendQueue SendQueue
	// SendQueueIdle is how long a target must have been idle before a queued
	// message is sent to it (MUSTER_SEND_QUEUE_IDLE); 0 is
	// sendqueue.DefaultIdleFor.
	SendQueueIdle time.Duration

	// AgentsIdleAfter is the Idle section's threshold (MUSTER_AGENTS_IDLE_AFTER,
	// ui.DefaultIdleSectionAfter when unset): an entry with no activity for longer
	// is drawn in the sidebar's collapsed "Idle (N)" group
	// (internal/ui/idle_section.go). 0 — the zero value, so every test
	// fixture that does not set it — draws no section.
	AgentsIdleAfter time.Duration

	// Focus is session focus (internal/focus, migration 0020): what each of a
	// user's sessions is working on. nil (no database): no entry has a focus
	// and the focus tools are not offered.
	Focus focus.Store
	// FocusSummarizer computes a focus from a transcript tail (the ScaleDown
	// summarizer through OpenRouter) — focus's only writer. nil: no focus is
	// ever written, and RunFocusRefresh does nothing.
	FocusSummarizer focus.Summarizer
	// FocusRetention is how long a mirrored session's focus outlives the last
	// time a pass saw it (MUSTER_FOCUS_RETENTION); 0 keeps it forever.
	FocusRetention time.Duration

	// Suggest is SUGGESTED REPLIES (internal/suggest, suggest.go): the engine
	// a rendered view's turn end asks for a set, and the composer's routes
	// read. nil: no set is ever generated and the routes answer 404. Its Off
	// (MUSTER_SUGGEST=off) keeps the routes and generates nothing.
	Suggest *suggest.Engine

	// ChiefPrefs is each user's chief on/off toggle (internal/chiefpref,
	// migration 0060; chief_toggle.go). nil (no database): no user has a
	// stored choice, so the chief is on exactly when the user has a chief
	// agent (chiefOn), and the Account page cannot change it.
	ChiefPrefs chiefpref.Store

	// NotifyPrefs is each user's notification preferences (internal/notifypref,
	// migration 0094; notify_prefs.go): today "Show tmux session in
	// notifications". nil (no database): off for everyone, and the Account
	// page draws no switch.
	NotifyPrefs notifypref.Store

	// ChiefNudge is the chief's STALL NUDGES' configuration (MUSTER_CHIEF_NUDGES,
	// chief_nudge.go; docs/chief-nudges.md) and ChiefNudges its decisions
	// (internal/chiefnudge, migration 0064). Either nil: the feature is off —
	// no sweep, no tab, and any queued nudge is refused at its paste.
	ChiefNudge  *ChiefNudges
	ChiefNudges chiefnudge.Store

	// Episodes is session state's store (internal/sessionstate, migration
	// 0073; session_state.go): one row per stop of one of an owner's
	// sessions. nil (no database): no state pass runs. It does NOT depend on
	// ChiefNudge — the state, and the episodes, are code-only.
	Episodes sessionstate.Store

	// Routes is session routing's store (internal/plugins/routes.go, migration
	// 0021) and Routing its configuration. Routing nil — MUSTER_SESSION_ROUTING
	// unset — is OFF: the chief's route_to_session tool is not offered,
	// POST /api/routes/{id}/reply answers 404, and the chief's plugin turns do
	// not mention routing.
	Routes  plugins.RouteStore
	Routing *Routing

	// TaskRouting is task routing's configuration (task_routing.go,
	// MUSTER_TASK_ROUTING). nil is OFF, the default: POST /plugin/v1/tasks
	// ignores route_to_chief and the chief's task_route_attention / task_forward
	// / agent_dispatch tools are not offered. ChiefDispatch is the ledger
	// agent_dispatch counts its caps from (the plugin store).
	TaskRouting   *TaskRouting
	ChiefDispatch plugins.DispatchStore

	// PRMail is pull-request → session routing's configuration
	// (MUSTER_PR_MAIL_SENDERS, pr_routes.go) and PRSessions its store
	// (migration 0055), which the host's hook fills through POST
	// /api/pr-sessions. PRMail nil — the variable unset — is OFF: that route
	// answers 404 and every message is handed on as before.
	PRMail     *PRMail
	PRSessions plugins.PRSessionStore
	// ClosedPRs settles a review of a pull request already merged or closed
	// instead of routing it, handing it back or asking about it (pr_closed.go).
	// nil — no GitHub App, or PR routing off — is OFF: every review is
	// handled as before.
	ClosedPRs *ClosedPRs

	// FleetReport is the fleet-report request's configuration
	// (MUSTER_FLEET_REPORT_SENDERS, MUSTER_FLEET_REPORT_PATHS;
	// fleet_report.go). nil — the senders unset — is OFF: such a mail is handed
	// on as any other. The chief's fleet_report tool needs only Focus, and
	// lists pull requests only with PRSessions.
	FleetReport *FleetReport

	// MailResume is the mail resume's configuration (MUSTER_MAIL_RESUME_ALLOW,
	// MUSTER_MAIL_RESUME_OFF; mail_resume.go) and MailResumes its durable
	// record (migration 0056). nil — the allowlist unset — is OFF: mail for a
	// session no window shows goes to the chief, as before.
	MailResume  *MailResume
	MailResumes plugins.MailResumeStore

	// Attention is the attention queue's explicit asks (internal/attention,
	// migration 0025). nil (no database): the attention tools are not offered,
	// /attention answers 404, and no link is drawn.
	Attention attention.Store
	// AskLog is the ask log (internal/asklog, migration 0089; MUSTER_ASK_LOG):
	// every question an agent puts to its owner, with its answer, recorded
	// (ask_log.go). nil (the default, or no database): nothing is recorded,
	// and every capture point is a no-op.
	AskLog *AskLog
	// MirrorTokens authenticates a mirror host's token for the mirrored
	// sessions' MCP door (mirror_mcp.go) — *mirror.PGStore, the same table
	// /mirror/connect reads. nil: POST /mirror/mcp answers 404.
	MirrorTokens MirrorTokenAuth

	// SessionRuntimes is MUSTER_CHIEF_SESSION_RUNTIMES: the runtimes a chief
	// chat session may be started on besides its own kind (session_runtime.go).
	// Empty, the default: no picker is drawn and POST /agents/{id}/sessions
	// refuses a runtime.
	//
	// ⚠ IT GATES THE PICKER, NOT THE ROUTING. Plugin deliveries and `chief ask`
	// go to the chief's DEFAULT session (defaultSession) whether or not this is
	// set, on any store with the 0030 half — so on such a deployment a plugin no
	// longer gets a session of its own even with this empty. That is the
	// operator's "one pinned default session" decision, not a leak of the flag.
	SessionRuntimes []string

	// Jobs is the machine job API's store (internal/jobs, migration 0037). nil
	// (no database): POST /api/jobs and GET /api/jobs/{id} answer 503.
	Jobs jobs.Store
	// JobWorkspace runs a job's in-instance steps: the worktree a sha job runs
	// in (created before its turn, removed after it), and the result_path read
	// and delete. nil (no provisioner): a job naming sha or result_path is
	// refused 501 when it is submitted, never accepted and then failed.
	JobWorkspace JobWorkspace
	// AccountFailover is the claude-code account failover
	// (internal/ccfailover.Service). nil (no claude-code kind, or no
	// provisioner): a job whose account hit its limit fails as before, and the
	// agent page shows no failovers.
	AccountFailover AccountFailover
}

Extensions are the server's optional dependencies. A Server built without them still boots, serves the shell, answers /health and /readyz, and refuses every data route with a reason — which is the behaviour a first run against no database should have.

🔴 THIS STRUCT IS THE muster HALF OF A STRUCT THAT USED TO HOLD EIGHTEEN FIELDS, AND THE NINE THAT ARE MISSING ARE MISSING ON PURPOSE. Upstream it also carried Suggest, Attention, Tmux, Transcripts, TranscriptArchive, TermWrite, Layout, AutoApprove and GenSuggestions — every one of which backs a surface on the permission router's side of the route partition. Carrying them across would give this service nine dependencies it has no route for, and would make the extraction's central claim — that the two halves are separable — false in the type system while looking true in the diff.

🔴 `Suggest` IS THE ONE WHOSE ABSENCE IS LOAD-BEARING RATHER THAN TIDY, AND IT MUST NOT COME BACK. It is the store that owns the session table, and the whole of the upstream work that preceded this carve existed to remove that table from the domain layer so the domain layer could move without it. The bit it used to supply — SessionLink.DetailAvailable — is now composed from a SEAM instead; see UseExtensions and session_liveness.go. A reviewer who sees a `Suggest` field reappear here should read that as the extraction being undone, not as a convenience.

func (Extensions) AgentNamespace

func (e Extensions) AgentNamespace(name string) string

AgentNamespace is the ONE expression that turns an agent's slug name into the namespace its row records.

🔴 IT IS A METHOD ON Extensions, NOT A PACKAGE FUNCTION, SO IT CANNOT BE CALLED WITHOUT THE DEPLOYMENT'S PREFIX IN HAND. The defect it replaces was a zero-argument call — agents.NamespaceFor(name) — that captured a package constant while the driver used the configured prefix; every line of the caller looked correct. Reaching this value now requires holding the wiring that carries the prefix, and defects() refuses to serve when that wiring is empty beside a creatable agent.

⚠ IT IS EXPORTED FOR THE GUARD AS WELL AS THE HANDLER. TestTheStoredNamespacePrefixIsWhatTheDriverIsConfiguredWith calls it from cmd/muster-server and compares the result against the namespace the real driver is OBSERVED to create — which is only a claim about the production path if the guard and the handler evaluate the same expression, rather than two copies of it.

type FeatureView added in v0.149.0

type FeatureView struct {
	features.Feature
	Docs        string   `json:"docs"`
	EnableLines []string `json:"enable_lines"`
	EnableHint  string   `json:"enable_hint"`
}

FeatureView is one feature as /api/doctor serves it: the registry entry plus what is derived from it, so a client needs no copy of the docs-anchor or hint rules.

func FeatureViews added in v0.149.0

func FeatureViews(set features.Set) []FeatureView

FeatureViews is set as the API serves it.

🔴 IT IS THE ONE SERIALISATION. The doctor and the leak test (cmd/muster-server, TestTheFeatureRegistryLeaksNoConfiguredValue) both call it, so what the test scans is byte for byte what a client is sent.

type FleetReport added in v0.113.0

type FleetReport struct {
	Senders plugins.AgentMailSenders
	Paths   plugins.FleetReportPaths
	Replies plugins.MusterReplier
}

FleetReport is the fleet-report request's configuration (MUSTER_FLEET_REPORT_SENDERS, MUSTER_FLEET_REPORT_PATHS) and the store that files muster's own reply. nil — the senders unset — is OFF: every such mail is handed on exactly as before. The fleet_report TOOL needs none of it.

type GateDecision

type GateDecision struct {
	// State is one of GateStateDecided, GateStatePending, GateStateGone.
	State string
	// Response is the answer when State is decided ("approve" / "reject"): a
	// human's, or the router's auto-approval for a type it lets that decide.
	Response string
	// Comment is the note left with the decision, when there is one.
	Comment string
}

GateDecision is the answer to one gate read.

type GatePort

type GatePort interface {
	// MintGate files an approval request and returns its id.
	MintGate(ctx context.Context, spec GateSpec) (string, error)
	// ReadGate reports the current state of a request this caller minted.
	ReadGate(ctx context.Context, id string) (GateDecision, error)
	// ClearGate removes a pending card. Best-effort.
	ClearGate(ctx context.Context, id string) error
}

GatePort is the approval queue muster asks through.

🔴 A nil GatePort MEANS "NOBODY CAN BE ASKED", WHICH MEANS "NOT APPROVED". It does not mean "proceed"; see this file's header.

type GateSpec

type GateSpec struct {
	Type    string
	Tool    string
	Command string
	Host    string
	Project string
	Cwd     string
	Session string
	Context []string
}

GateSpec describes the approval card an agent is asking a human to judge.

type Gateway

type Gateway interface {
	// Chat sends a user message to the agent gateway under the given chat-session
	// key (each session = an independent gateway context), streaming assistant
	// deltas to emit, and returns the full assistant reply. It carries no tools.
	//
	// ⚠ IT DOES NOT RETURN agents.ErrResponsesUnsupported, AND THE ASYMMETRY WITH
	// ChatWithTools BELOW IS THE POINT. An implementation picks the transport
	// itself — the one documented on agentgateway.Gateway.Chat runs over the
	// responses endpoint and drops to chat-completions on a 404 — because no caller
	// has information about which wire format an agent's image speaks. There is
	// nothing for a caller to branch on here, so a caller that received that
	// sentinel from ChatWithTools has exactly one move: call this.
	Chat(ctx context.Context, a agents.Agent, sessionKey, message string, emit func(string)) (string, error)
	// ChatWithTools runs a tool-enabled turn via the gateway's responses API
	// under the given chat-session key: the model gets the native function tools
	// and dispatch executes each call in-process. emit (nil-safe) streams live
	// text/thinking deltas plus tool_call/tool_result events as the loop runs.
	// Returns agents.ErrResponsesUnsupported when the agent's gateway lacks the
	// responses API, so the caller can fall back to Chat.
	ChatWithTools(ctx context.Context, a agents.Agent, sessionKey, instructions, message string, tools []agents.ToolDef, dispatch agents.ToolDispatch, emit agents.StreamEmit) (string, error)
}

Gateway is the agent CHAT surface: talking to a running instance's model gateway.

🔴 IT IS A SEPARATE INTERFACE FROM Provisioner, AND THE SPLIT IS THE WHOLE POINT. Both used to be one, behind one nil and one wrapper, so the seven LIFECYCLE methods could not be wired without also claiming the two CHAT ones. That is not a packaging preference: provision.Provisioner — the driver contract a lifecycle adapter is built on — has no notion of a chat turn at all, so an adapter over it can implement the seven honestly and the two not at all. Behind one interface the only ways to express that were to wire a stub (which doc_seams.go entry 1 rejects, because dispatch reporting success over a pod that does not exist is the defect the wrapper was built to remove) or to leave lifecycle unwired for as long as chat is. Two interfaces make "lifecycle works, chat honestly refuses" sayable.

⚠ A DEPLOYMENT MAY WIRE EITHER, BOTH, OR NEITHER, and each combination has a truthful rendering. Chat without lifecycle is unusual but not incoherent — an installation whose instances are provisioned by something else entirely.

type GitHubApp

type GitHubApp interface {
	Repos(ctx context.Context) ([]github.Repo, error)
	DefaultBranch(ctx context.Context, repo string) (string, error)
	ListPullRequests(ctx context.Context, agentID int64, repo, state string) ([]github.PullRequest, error)
	// Problem is the operator-facing reason the App cannot serve agentID now ("" if none).
	Problem(agentID int64) string
	// Access is the permission mode every agent token is minted with
	// (MUSTER_GITHUB_APP_ACCESS); each description of the connector's scope
	// reads it (githubAppScope), never a constant.
	Access() githubapp.Access
}

GitHubApp is what the API reads from a configured GitHub App (*githubapp.App). An interface so a test can stand one in without a key.

type GoTrueAuth

type GoTrueAuth struct {
	Client   *gotrue.Client
	Verifier gotrue.Verifier
	Users    UserStore
	// Accounts serves link invites and the admin pages (accounts PR 5; see
	// admin.go). Nil: /admin/* answers 503 and /invite is not served.
	Accounts AccountStore
}

GoTrueAuth is gotrue mode's wiring. cmd/muster-server builds it whenever MUSTER_GOTRUE_URL is set — in password mode too, so the admin claim can be redeemed before the mode is flipped.

type JobWorkspace

type JobWorkspace interface {
	// PrepareJobWorktree creates job jobID's own git worktree of the agent's
	// repository at sha — which must be pull request pr's head of repo, or an
	// ancestor of it, fetched anonymously, or through the pod's deploy-key
	// holder when the agent's worker pool has a key — outside the agent's
	// checkout, with the agent configuration overlaid from the default branch
	// (from commit configRef of it when non-empty, refused unless the default
	// branch reaches it), or with none of it when StripsRepoConfig, and — with
	// baseSHA — that commit fetched the same way into
	// refs/muster-jobs/<jobID>-base, and returns its path. The agent's
	// checkout is not moved.
	PrepareJobWorktree(ctx context.Context, a agents.Agent, jobID int64, repo string, pr int, sha, configRef, baseSHA string) (string, error)
	// StripsRepoConfig reports whether a job on agent a gets NONE of the
	// repository's agent configuration, whatever it asks — decided by a's
	// worker pool (one with a deploy key), not by the job. For a pool job
	// before its worker is chosen, a carries only the pool's name.
	StripsRepoConfig(a agents.Agent) bool
	// RemoveJobWorktree removes that worktree; one that is not there is not an
	// error.
	RemoveJobWorktree(ctx context.Context, a agents.Agent, jobID int64) error
	// ReadWorkspaceFile returns rel byte for byte, refusing a file over max
	// bytes: relative to job jobID's worktree for a positive jobID, to the
	// agent's working directory for zero.
	ReadWorkspaceFile(ctx context.Context, a agents.Agent, jobID int64, rel string, max int) ([]byte, error)
	// RemoveUntrackedWorkspaceFile deletes rel, relative to the agent's
	// working directory, unless the repository there tracks it; a file that
	// is not there is not an error. removed is false (with a nil error) for a
	// tracked file, which is left in place.
	RemoveUntrackedWorkspaceFile(ctx context.Context, a agents.Agent, rel string) (removed bool, err error)
}

JobWorkspace is the part of the agent lifecycle adapter the job runner uses (*agentprovision.Adapter implements it). Every method execs inside the agent's live instance.

type KickoffOutcomeReporter added in v0.165.0

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

KickoffOutcomeReporter feeds a first turn's course to the tracker.

func (*KickoffOutcomeReporter) TurnActivity added in v0.165.0

func (k *KickoffOutcomeReporter) TurnActivity(ctx context.Context, a agents.Agent)

TurnActivity: the first turn's stream showed life.

func (*KickoffOutcomeReporter) TurnAnswered added in v0.165.0

func (k *KickoffOutcomeReporter) TurnAnswered(ctx context.Context, a agents.Agent, reply string)

TurnAnswered: the first turn answered (it is already closed: TurnEnded).

func (*KickoffOutcomeReporter) TurnEnded added in v0.165.0

func (k *KickoffOutcomeReporter) TurnEnded(_ context.Context, a agents.Agent)

TurnEnded: the first turn is no longer open (agentkickoff runs it once per TurnStarted, on every path). Closing is all it does.

func (*KickoffOutcomeReporter) TurnFailed added in v0.165.0

func (k *KickoffOutcomeReporter) TurnFailed(ctx context.Context, a agents.Agent, reason string)

TurnFailed: the first turn failed (closed already: TurnEnded), or was never delivered (it opened none). It never touches the open-turn count — guessing "this agent's turn is open" from busy() would close another door's turn.

func (*KickoffOutcomeReporter) TurnStarted added in v0.165.0

func (k *KickoffOutcomeReporter) TurnStarted(ctx context.Context, a agents.Agent)

TurnStarted: the first turn is about to be sent.

type LeaderGate

type LeaderGate interface {
	// TryAcquire reports whether this process currently holds the lease.
	TryAcquire(ctx context.Context) bool
}

LeaderGate is the cross-process singleton gate the background loops consult.

🔴 DECLARED HERE, CONSUMER-SIDE, RATHER THAN IMPORTED FROM THE DATABASE PACKAGE. The implementation is a Postgres session advisory lock, which means it belongs to whatever owns the pool — and this package must be buildable, and testable, without one. Upstream this was a concrete type from the db package and the coupling was invisible until the carve tried to move the loops without the pool.

type MailResume

type MailResume struct {
	// Allow is MUSTER_MAIL_RESUME_ALLOW: per owner, the senders (each bound to
	// one plugin, VERIFIED only) whose mail may resume an ended session. The
	// relay allowlist's grammar and matching (plugins.RelayAllowlist). Empty
	// is the feature off.
	Allow plugins.RelayAllowlist
	// Off is MUSTER_MAIL_RESUME_OFF=1: the kill switch. On, nothing is
	// resumed whatever Allow says.
	Off bool
}

MailResume is the mail resume's configuration.

type Mirror

type Mirror interface {
	// ServeConnect is GET /mirror/connect: a host's muster-mirror dialling in.
	ServeConnect(w http.ResponseWriter, r *http.Request)
	// Hosts is the viewing principal's hosts and their sessions.
	Hosts(ctx context.Context) []mirror.HostView

	// AttachWindow attaches a terminal to one window of one of the viewing
	// principal's host sessions, with Provisioner.AttachTerminal's shape so one
	// terminal bridge serves both.
	AttachWindow(ctx context.Context, host, session, window string, readOnly bool, stdin io.Reader, stdout io.Writer, resize <-chan provision.TermSize) error
	// WatchWindow streams the transcript of the Claude Code session in that
	// window's pane (the rendered view), resuming at (gen, offset) when it can,
	// until ctx ends.
	WatchWindow(ctx context.Context, host, session, window, gen string, offset int64, out func(mirror.Msg) error) error
	// PasteWindow types a message into that window's pane and presses Enter:
	// its Claude pane only, or its active pane whatever runs there (target).
	// The caller has already required the step-up; the plugin requires it
	// again. opts: mirror.ExpectTurn (a queued message: refused as
	// superseded if the window's turn moved) and mirror.ReportWindow (the
	// window id "" resolved to).
	PasteWindow(ctx context.Context, host, session, window, text string, target mirror.PasteTarget, opts ...mirror.PasteOption) error
	// AgentState is whether the Claude Code session in that window is busy,
	// idle or waiting, and since when — or why it is unknown (an older
	// muster-mirror reports none). What the send queue waits on.
	AgentState(ctx context.Context, host, session, window string) mirror.AgentState
	// ScrollWindow scrolls that window's active pane through its history in
	// tmux copy-mode by lines (positive is back). No step-up: see
	// mirror.Hub.ScrollWindow.
	ScrollWindow(ctx context.Context, host, session, window string, lines int) error
	// HostRanks is the viewing principal's hosts' registration ranks
	// (mirror.RanksByRegistration): what picks each host's icon
	// (ui.HostIconFor).
	HostRanks(ctx context.Context) map[string]int
	// LiveTokenHosts is the viewing principal's hosts holding an unrevoked
	// mirror token, sorted: the hosts expected to connect (GET /api/doctor).
	LiveTokenHosts(ctx context.Context) ([]string, error)
	// HostToken is the id of the token the viewing principal's host is
	// connected with now (GET /mirror/host tells a machine whether THE
	// connection under its name is its own).
	HostToken(ctx context.Context, host string) (int64, bool)
}

Mirror is the mirror plugin as this package consumes it. *mirror.Service implements it. Hosts and Attach act for the principal on ctx: another user's hosts are not in Hosts and not attachable.

type MirrorHostReport

type MirrorHostReport struct {
	// Host is the host the presented token was minted for.
	Host string `json:"host"`
	// Online: the tunnel hub holds a live connection from that host now.
	Online bool `json:"online"`
	// Interactive: that connection advertised -interactive.
	Interactive bool `json:"interactive"`
	// OtherToken: a connection under this host name is live, but it was made
	// with ANOTHER token of the same owner — a second machine minted under the
	// same name. Online is false then: this machine is not the one connected.
	OtherToken bool `json:"other_token,omitempty"`
}

MirrorHostReport is GET /mirror/host's body.

type MirrorTokenAuth

type MirrorTokenAuth interface {
	Authenticate(ctx context.Context, token string) (mirror.Token, error)
}

MirrorTokenAuth resolves a presented mirror token to its row (ErrBadToken for none, a revoked one included). It runs under the system scope.

type ModelCatalog added in v0.165.0

type ModelCatalog interface {
	// Models is the catalogue, or an error when none can be read.
	Models(ctx context.Context) ([]CatalogModel, error)
}

ModelCatalog is the catalogue the model check reads. api.OpenRouterCatalog is the deployment's; a test passes a fake.

func OpenRouterCatalog added in v0.165.0

func OpenRouterCatalog() ModelCatalog

OpenRouterCatalog is OpenRouter's public catalogue through the process's one cache (the dispatch form's picker reads the same).

type Mux

type Mux interface {
	Handle(pattern string, handler http.Handler)
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}

Mux is the narrow slice of *http.ServeMux that RegisterRoutes uses.

It exists so the route gate can hand RegisterRoutes a recorder instead of a real mux and get back the set of patterns production would register. The compile-time assertion below is what makes the two interchangeable — without it, "the recorder and the mux are the same shape" would be a comment rather than a fact the compiler enforces.

type OfficersConfig added in v0.106.0

type OfficersConfig struct {
	Officers []officers.Officer
	// HTTPClient is the HQ client's transport; nil uses officers.NewClient's.
	HTTPClient *http.Client
	// Now is the wake loop's clock; nil is time.Now. For tests.
	Now func() time.Time
	// InstallSession installs the officer runtime's session source on the
	// provisioner (agentprovision.Adapter.UseClaudeCodeSession). REQUIRED:
	// without it an instance's Claude Code session would stop on a permission
	// prompt for its first tool call (it runs with every tool allowed only
	// through this source) and never run its model, and nothing would say so —
	// EnableOfficers refuses instead.
	InstallSession func(source func(agents.Agent) (agentspec.ClaudeCodeSession, bool))
	// ShipGitHub, ShipHosts and ShipHTTP replace a shipping officer's GitHub
	// side (its App, the REST client and the hosts the push gate serves) and
	// the rollout watch's HTTP client. For tests; nil/zero is production.
	ShipGitHub func(officers.Officer) officership.GitHub
	// ShipGitHubRepo, when set with ShipGitHub, is the GitHub of each of a
	// draft officer's ship repositories by name (tests); unset, ShipGitHub's
	// answers for every one.
	ShipGitHubRepo func(o officers.Officer, repo string) officership.GitHub
	ShipHosts      [2]string
	ShipHTTP       *http.Client
	// ShipCI replaces a ci_logs officer's cluster reader (tests); nil is the
	// in-cluster API with a token minted per call for its service_account.
	ShipCI func(officers.Officer) officership.CIReader
	// NoShipResume skips resuming rollout watches and starting the daily
	// orphan-branch report at boot (tests).
	NoShipResume bool
	// TranscriptSource replaces where a transcript-enabled officer's
	// instances' transcripts are read (tests); nil is each instance's ccd,
	// through the agent gateway (agentgateway.Gateway.Transcript).
	TranscriptSource transcript.Source
	// TranscriptInterval replaces the forwarder's cadence (tests); 0 is
	// transcript.DefaultInterval. NoTranscriptRun skips running its loop
	// (tests drive Tick).
	TranscriptInterval time.Duration
	NoTranscriptRun    bool
	// LLMStore keeps the LLM proxy's per-day usage (the budget); REQUIRED
	// when an officer declares `llm`. LLMUpstream replaces the provider's API
	// base and LLMHTTP its transport (tests); ""/nil is production.
	LLMStore llmproxy.Store
	// Sessions keeps the judgement session cap's count
	// (officers.PGSessionStore); REQUIRED when an officer declares
	// tiers.judgement.max_sessions_per_day.
	Sessions    officers.SessionStore
	LLMUpstream string
	LLMHTTP     *http.Client
}

OfficersConfig is EnableOfficers' input.

type PRMail

type PRMail struct {
	// Senders is MUSTER_PR_MAIL_SENDERS: whose verified agent mail is read as
	// a pull-request review. Empty is the feature off.
	Senders plugins.PRMailSenders
}

PRMail is pull-request → session routing's configuration.

type PRStateReader added in v0.137.0

type PRStateReader interface {
	PullRequestState(ctx context.Context, repo string, n int64) (githubapp.PRState, error)
}

PRStateReader reads a pull request's state from GitHub (the GitHub App: githubapp.App.PullRequestState).

type ProfileReapplier

type ProfileReapplier interface {
	ReapplyProfiles(ctx context.Context, agentID int64) error
}

ProfileReapplier reconciles a running instance to a freshly-rendered spec, which rolls it. Optional: the model-change path type-asserts for it, so a nil provisioner is unaffected.

⚠ THE NAME IS HISTORICAL. It was written for the privilege grant path, which re-rendered an agent's granted-profile env into its pod; that path is gone and the model change is the only caller. It reconciles the WHOLE spec, not "profiles".

⚠ ITS PREVIOUS WORDING WAS "re-applies an agent's granted-profile env/kubeconfig to its running POD (a HELM UPGRADE; the pod rolls)" — the same helm-and-pod vocabulary removed from Destroy and StreamLogs below, and missed in the same sweep that removed them. It is false of the only implementation (which calls the driver's Update), false for a driver with no pods, and it names a mechanism the provisioner contract deliberately does not have.

type Provisioner

type Provisioner interface {
	// Dispatch provisions an instance for the agent when kickoff is true, and
	// creates NOTHING when it is false — see the note below on both halves.
	//
	// 🔴 THIS DOC USED TO DESCRIBE BEHAVIOUR NO IMPLEMENTATION HAS. It read
	// "provisions a pod for the agent and, when kickoff is true, sends the note as
	// the first message once the gateway is reachable", which is wrong twice over
	// for internal/agentprovision — the only implementation in this module:
	//
	//   - it does NOT send the note. Delivery needs an api.Gateway and there is no
	//     implementation of one here, so the non-delivery is recorded on the row
	//     instead (agentprovision.UndeliveredKickoffReason). An interface doc
	//     promising a delivery is how a future implementer comes to call
	//     SetKickedOff, which is the one thing that package must never do.
	//   - kickoff=false creates NOTHING rather than provisioning-then-storing-
	//     stopped. The caller's OTHER action is a stopped create (POST /api/agents
	//     start: false, which replaced the UI's "Save for later"), whose gate check
	//     (agent_create_api.go, the `gate:<reason>` refusal) allows it on the
	//     stated grounds that it "provisions nothing".
	//
	// An implementer that provisions on kickoff=false, or that reports a delivery
	// it did not make, is wrong against this interface — not merely different.
	//
	// 🔴 REFUSING A KICKOFF IT CANNOT DELIVER IS ALSO LEGAL, AND IS WHAT
	// internal/agentprovision NOW DOES when nothing in its process could deliver
	// one: it creates nothing and returns an error
	// (agentprovision.ErrKickoffUndeliverable). The paragraph above describes the
	// CREATE-THEN-RECORD path. Both are honest; what this interface forbids is the
	// third option, doing the expensive half and reporting success.
	//
	// ⚠ THIS USED TO SAY CREATE-THEN-RECORD WAS "the gateway-configured one only",
	// WHICH MADE A CONFIGURED GATEWAY SOUND SUFFICIENT. It was not while nothing
	// CALLED the gateway. internal/agentkickoff now does, and the first bullet
	// above is superseded for a deployment that names a gateway: the adapter
	// still never sends the note itself, but it records no non-delivery either —
	// it creates the instance and leaves the owed row to that deliverer, which is
	// the one place SetKickedOff is called. See agentprovision.KickoffDeliveryWired.
	//
	// ✅ AND THE REFUSAL NOW REACHES THE CALLER, through
	// KickoffUndeliverableReason below rather than through this method. This
	// paragraph read "THE CALLER OF THIS METHOD IN THIS PACKAGE CANNOT SURFACE THAT
	// REFUSAL … A refusal an operator can see needs a synchronous check in the
	// create handler, before the row", and that check exists: handleAPIAgentCreate
	// answers 409 with the reason before Agents.Create. The asynchronous half is
	// unchanged and still true of THIS method — createAndDispatchAgent calls it
	// inside safeGo, after the row exists — which is why the pre-flight is a
	// separate question rather than a different return value here.
	//
	// 🔴 ctx CARRIES THE CALLER'S PRINCIPAL, NOT ITS DEADLINE (all four lifecycle
	// methods). The work outlives the request (these run inside safeGo), so an
	// implementation must detach from ctx's cancellation — context.WithoutCancel —
	// but keep its values: under row-level security every store read and write
	// the operation makes acts as ctx's principal, and a context.Background()
	// budget would see no rows (accounts PR 3a).
	Dispatch(ctx context.Context, agentID int64, kickoff bool) error
	// Start brings a stopped or never-provisioned agent up, creating its instance
	// when the driver reports the backend does not have one.
	//
	// ⚠ IT DOES NOT KICK OFF, AND THIS DOC SAID IT DID. It read "(kicking off if
	// pending)" — the same retracted claim Dispatch's doc above corrects, left
	// behind in the sibling method for one round. The only implementation records
	// the non-delivery instead; see agentprovision.UndeliveredKickoffReason.
	Start(ctx context.Context, agentID int64) error
	// Stop scales a running agent down to zero replicas, keeping its declaration.
	// An instance the backend does not have is already stopped, not an error.
	Stop(ctx context.Context, agentID int64) error
	// Destroy removes the instance and everything the driver created for it, then
	// deletes the stored row.
	//
	// ⚠ IT DELETES THE ROW ONLY WHEN THE BACKEND HOLDS NOTHING, and this doc did
	// not say so — which is the contract the lifecycle adapter added. A terminal
	// ownership refusal or an unreachable backend KEEPS the row, because the row is
	// then the only record of a live instance.
	//
	// ⚠ ITS PREVIOUS WORDING WAS "uninstalls the release and deletes the
	// namespace" — helm and Kubernetes vocabulary in an interface whose Instances
	// doc makes a 🔴 point of having removed exactly that, and false for any driver
	// without namespaces.
	Destroy(ctx context.Context, agentID int64) error
	// Instances returns the live state of every agent workload, for status
	// reconciliation.
	//
	// 🔴 IT IS provision.Instance, NOT A POD, AND THE RENAME IS THE CARVE. The
	// method this replaces was `Pods` returning a Kubernetes-shaped struct, which
	// made every status consumer in this package a Kubernetes consumer by
	// transitivity. The provisioner contract's own vocabulary is what lets
	// agents.ComputeStatus answer for an agent running under any driver.
	Instances(ctx context.Context) ([]provision.Instance, error)
	// StreamLogs follows the agent's instance output, invoking emit per line.
	StreamLogs(ctx context.Context, a agents.Agent, emit func(string)) error
	// AttachTerminal attaches a terminal to the agent's live session until ctx
	// ends or the session's client exits: what is written to stdin is typed,
	// what the terminal shows arrives on stdout, and each size on resize is
	// applied. readOnly attaches a client that cannot type.
	//
	// It refuses — agents.ErrNoTerminal for a kind with no session,
	// provision.ErrUnsupported for a driver that cannot exec — rather than
	// returning without having attached anything.
	//
	// ⚠ ON THE INTERFACE RATHER THAN TYPE-ASSERTED, for the reason
	// KickoffUndeliverableReason below gives: an optional interface an adapter
	// forgets yields ok=false with no trace, and the terminal route would then
	// refuse every agent while every capability reported it could exec.
	AttachTerminal(ctx context.Context, a agents.Agent, readOnly bool, stdin io.Reader, stdout io.Writer, resize <-chan provision.TermSize) error
	// KickoffUndeliverableReason answers why this process cannot deliver an
	// agent's FIRST TURN, and "" when it can. It must not create, write or
	// provision anything: it is the question Dispatch answers by refusing, asked
	// before anything exists to refuse over.
	//
	// 🔴 IT IS ON THIS INTERFACE RATHER THAN BEING A TYPE ASSERTION, AND THE
	// POLARITY OF THE FAILURE IS WHY. An optional interface that an
	// implementation does not satisfy yields ok=false and leaves NO TRACE —
	// doc_seams.go entry 3 is about exactly that — and here the no-trace branch
	// is the permissive one: no pre-flight, so a dispatch the deployment cannot
	// satisfy answers 200 again and the operator is back to reading a `running`
	// card over an agent nobody told what to do. A method on the interface makes
	// omitting it a compile error instead.
	//
	// 🔴 A CALLER MUST NOT RE-DERIVE THIS FROM ITS OWN CONFIGURATION. The answer
	// has to be the SAME fact the implementation's own Dispatch branches on, or
	// the pre-flight and the dispatch disagree — which is worse than no
	// pre-flight, because it refuses requests that would have worked or admits
	// ones that will not. internal/agentprovision returns the field Dispatch
	// reads; see its own doc on why.
	//
	// ⚠ "" IS DELIVERABLE, so the zero return is the permissive one. The
	// fail-closed argument lives on agentprovision.Config.KickoffDeliverable,
	// where a wiring can FORGET a struct field; a method cannot be forgotten.
	KickoffUndeliverableReason() string
}

Provisioner is the agent-instance LIFECYCLE driver the agent handlers depend on: bring one into existence, scale it, destroy it, read its state and its logs. It is defined here (consumer side) so this package does not import the heavy cluster dependencies unless the binary wires a real provisioner in.

⚠ CHAT IS NOT HERE ANY MORE — see Gateway for why the two are separate.

type PushService

type PushService interface {
	PublicKey() string
	Store() push.Store
	SendTo(ctx context.Context, owner int64, p push.Payload) push.Report
	// The paired-device half (devices.go): the ONE allowlist (the store's),
	// for /api/device/config's push hosts and the check a registration passes
	// before its test push, and that test push.
	Allowlist() push.Allowlist
	Probe(ctx context.Context, sub push.Subscription, payload []byte) push.SendResult
}

PushService is muster's own Web Push (internal/push). Nil: no VAPID keys are configured — the key route answers 503, the subscribe routes refuse, and the shell draws no Enable button (Features.Push).

type RouterNotification

type RouterNotification struct {
	Type  string
	ID    string
	Title string
	Body  string
	Tag   string
	Data  map[string]string
	// Ask (an attention ask's chips) and Update (a re-push replacing the
	// notification under the same tag) reach a paired phone's payload v2 only
	// (push.Payload); the router and the browser never see them.
	Ask    *push.V2Ask
	Update bool
	// AskActions: payload v2 offers Ask's signed actions (device_actions.go).
	AskActions bool
	// TitleKeep is a part of Title the title rule keeps verbatim
	// (textplain.TitleKeeping): a mirrored window's tmux target. "" for none.
	TitleKeep string
}

RouterNotification is the notification body RouterPort.Notify takes.

type RouterPort

type RouterPort interface {
	SessionLivenessProbe
	// PublishEvent puts one event on the router's SSE bus.
	PublishEvent(ctx context.Context, name, data string) error
	// Notify fans a notification out to the router's push subscriptions.
	Notify(ctx context.Context, n RouterNotification) error
	// Directories returns distinct working directories the router has observed.
	Directories(ctx context.Context, query string, limit int) ([]string, error)
	// SessionMeta returns what the router knows about one session, and whether
	// it holds a record at all.
	//
	// 🔴 IT IS SEPARATE FROM SessionsExisting RATHER THAN A WIDER VERSION OF IT,
	// AND THE NARROWNESS OF THE OTHER ONE IS THE REASON. The decorator that
	// composes DetailAvailable wants ONE BIT per id and must not be able to reach
	// for a project, a cwd or a transcript — a port that can is a port a future
	// handler will use to render another service's data. This method serves the
	// WRITE path, which genuinely needs the project/cwd to denormalise onto the
	// link row, and it is a single lookup rather than a batch because its caller
	// links one session at a time.
	SessionMeta(ctx context.Context, sessionID string) (SessionMeta, bool, error)
}

RouterPort is everything muster asks of the permission router it was extracted from.

🔴 IT IS ONE INTERFACE, DECLARED CONSUMER-SIDE, SO "WHAT muster STILL NEEDS FROM THE OTHER SERVICE" IS A LIST A READER CAN COUNT. That is the number the extraction is judged on: every method here is a coupling that survived, and an interface that grows is the extraction going backwards. internal/router implements it over HTTP; a test implements it in memory.

⚠ A nil RouterPort IS A SUPPORTED DEPLOYMENT. muster runs standalone — the board, the agents, the connectors and the repos all work — and the four features below degrade, each saying so where a human can see it.

type Routing

type Routing struct {
	// Allow is the per-owner sender allowlist whose routed answers are relayed
	// WITHOUT the owner's approval (MUSTER_ROUTE_RELAY_ALLOW); everyone else's
	// fall back to a pending draft.
	Allow plugins.RelayAllowlist
}

Routing is session routing's configuration (MUSTER_SESSION_ROUTING=1).

type SendQueue

type SendQueue interface {
	Enqueue(ctx context.Context, it sendqueue.Item) (sendqueue.Item, error)
	List(ctx context.Context, t sendqueue.Target) ([]sendqueue.Item, error)
	Get(ctx context.Context, id int64) (sendqueue.Item, error)
	Cancel(ctx context.Context, id int64, now time.Time) (sendqueue.Item, error)
	HeadOf(ctx context.Context, t sendqueue.Target) (sendqueue.Head, bool, error)
	NotePaste(ctx context.Context, t sendqueue.Target, since int64) error
	Retry(ctx context.Context, id int64, stepUpAt time.Time, afterSince int64) (sendqueue.Item, error)
	Delete(ctx context.Context, id int64) error
	// Hold, SaveEdit and ReleaseEdit are a queued message's Edit
	// (send_queue_edit.go): the hold, its Save, its Cancel.
	Hold(ctx context.Context, id int64) (sendqueue.Item, error)
	SaveEdit(ctx context.Context, id int64, token, body string, stepUpAt time.Time) (sendqueue.Item, error)
	ReleaseEdit(ctx context.Context, id int64, token string) (sendqueue.Item, bool, error)
	// CancelOwner is the system scope's: a disable or a sign-out everywhere
	// cancels the user's queued messages.
	CancelOwner(ctx context.Context, owner int64, now time.Time, detail string) (int, error)
	sendqueue.DispatchStore
}

SendQueue is the send queue's store as this package consumes it: *sendqueue.PGStore. The first eleven run under the request's principal; CancelOwner and the embedded DispatchStore are the system scope's.

type Server

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

Server is muster's HTTP application.

func New

func New(bus *sse.Broadcaster, authCfg AuthConfig, logger *log.Logger) *Server

New builds a Server. Attach dependencies with UseExtensions before Handler.

func (*Server) AgentConnectorList

func (s *Server) AgentConnectorList(ctx context.Context, a agents.Agent) ([]AgentConnectorView, error)

AgentConnectorList is the agent's view of every connector (and of the connectors it has requested that do not exist yet).

func (*Server) AgentConnectorStatus

func (s *Server) AgentConnectorStatus(ctx context.Context, a agents.Agent, name string, wait time.Duration) (AgentConnectorView, error)

AgentConnectorStatus returns the agent's view of one connector, waiting up to wait for a PENDING grant to be decided.

func (*Server) AgentInstructions

func (s *Server) AgentInstructions(a agents.Agent) string

AgentInstructions returns the worker's system prompt (used by the kickoff loop AND every interactive chat turn). It grounds the agent in its ACTUAL environment — its repo and, when configured, the connector store — and tells it to describe only its real capabilities. The base image prompt otherwise advertises a generic assistant feature set (Signal/ Telegram messaging, paired devices, image/video, calendar/email) this sandboxed worker does not have, so "what can you do" answers confabulate without this.

func (*Server) AgentOutcomeOf added in v0.165.0

func (s *Server) AgentOutcomeOf(a agents.Agent, lastMessage time.Time) AgentOutcome

AgentOutcomeOf projects a row the caller already holds (a card's): no read.

func (*Server) AgentRequestConnector

func (s *Server) AgentRequestConnector(ctx context.Context, a agents.Agent, name, reason string) (AgentConnectorView, bool, error)

AgentRequestConnector files (or finds) the agent's request for a connector.

Unlike the proxy's implicit request, this one IS filed after a denial or a revocation: asking explicitly is the deliberate act that re-prompts the operator.

func (*Server) AgentToolDefsFor

func (s *Server) AgentToolDefsFor(ctx context.Context, a agents.Agent) []agents.ToolDef

AgentToolDefsFor returns the native function tools given to gateway agent a: every tool in the registry a may see (toolsFor).

🔴 THERE IS NO AGENT-LESS VARIANT, ON PURPOSE. An unfiltered listing is how a chief-only tool would reach a worker; every consumer names the agent.

func (*Server) AgentToolDispatch

func (s *Server) AgentToolDispatch(ctx context.Context, a agents.Agent) agents.ToolDispatch

AgentToolDispatch returns the dispatch closure executing a worker's tool calls in-process, scoped to that agent (its bound task). Used by both the kickoff (via the provisioner hook) and the interactive chat.

func (*Server) AgentWatchdogPass added in v0.165.0

func (s *Server) AgentWatchdogPass(ctx context.Context) (int, error)

AgentWatchdogPass is one sweep: it returns how many agents it called stuck.

func (*Server) AgentWork

func (s *Server) AgentWork(id int64) mirror.WindowWork

AgentWork is what agent id's pod last reported it has running, or the zero value (no chip) when it reported nothing, nothing running, or not within agentWorkTTL.

func (*Server) AskLogMirrorChanged added in v0.165.0

func (s *Server) AskLogMirrorChanged(owner int64)

AskLogMirrorChanged is the hub's status hook (mirror.Service.SetStatusNotify; cmd/muster-server): owner's windows' status moved. It diffs each window against what it last saw and queues the captures a change calls for:

  • a Claude window naming its session, busy → idle: a turn ended (read its last assistant message for a question);
  • such a window leaving idle (busy, waiting): the owner may have replied (resolve its open question);
  • an opencode window's named ask appearing, changing or leaving;
  • a window gone from an online host: its open asks end.

A window seen for the first time records its status and captures nothing (a restart must not log every idle window's last question again) — except an opencode window's named ask, whose row is keyed by its prompt id and so cannot be logged twice.

func (*Server) AttentionMirrorChanged

func (s *Server) AttentionMirrorChanged(owner int64)

AttentionMirrorChanged is attentionMirrorChanged for the mirror hub's waiting-set hook (mirror.Service.SetWaitingNotify; cmd/muster-server).

func (*Server) AwaitingApproval

func (s *Server) AwaitingApproval(agentID int64) bool

AwaitingApproval reports whether an agent is waiting on a human: it has a request filed through the relay that is still open, or its terminal reported a permission prompt recently. It drives the agent's "awaiting approval" badge.

func (*Server) BroadcastAgentChanged

func (s *Server) BroadcastAgentChanged(agentName string)

BroadcastAgentChanged fires an SSE agent.changed nudge for the named agent so an open Tasks tab, the sidebar and the agent's page refresh live. Best-effort + nil-safe: it is wired into the reconciler's status-change hook, which runs on a background goroutine, so it must never panic.

It is handed only a NAME (the loops' OnChange hooks), so the owner the nudge reaches is read from the row (agentOwner). A request that has the agent in hand calls agentChangedFor with the request's owner instead.

func (*Server) BroadcastAgentsChangedFor

func (s *Server) BroadcastAgentsChangedFor(owner int64)

BroadcastAgentsChangedFor nudges owner's open sidebars and pages to re-fetch, with no agent named — the mirror plugin's host connected / dropped / re-listed hook, which knows the host's owner and nothing else.

func (*Server) ChiefNudgePass added in v0.112.0

func (s *Server) ChiefNudgePass(ctx context.Context) (int, error)

ChiefNudgePass is one sweep: settle the live decisions in flight, then decide each owner's stalled sessions. It returns how many decisions it recorded.

func (*Server) ChiefTurnTools added in v0.163.0

func (s *Server) ChiefTurnTools(ctx context.Context, chief agents.Agent) plugins.ChiefTools

ChiefTurnTools is the muster tools chief is offered when that set is restricted — the Compose chief's: exactly what toolsFor lists it, read from that one listing — or nil (unrestricted) for every other chief. Every turn text muster sends the chief that names a tool is rendered against it (plugins.ChiefTools): the plugin turn (DelivererConfig.Tools), a route's hand-back (handBackChoices), and a session's question (toolChiefAsk, which does not put one to a chief without answer_session_question).

func (*Server) DisableUser

func (s *Server) DisableUser(ctx context.Context, id int64, disabled bool) error

DisableUser disables user id: users.disabled_at, a GoTrue ban (which also stops its refresh tokens), and this process's cache entry, so the user's next request is a 401 (TestADisabledUserIsRefusedOnTheNextRequest).

⚠ THE ORDER IS DATABASE FIRST. disabled_at is what requireSession reads; a GoTrue failure after it leaves the user locked out of muster with a live GoTrue account, which is the safe half to be left in, and the error says so.

func (*Server) DisableUserAs

func (s *Server) DisableUserAs(ctx context.Context, by users.Actor, id int64, disabled bool) error

DisableUserAs is DisableUser on behalf of by: the user.disable / user.enable audit row is written in the same transaction as the change (accounts PR 5; the admin page).

func (*Server) EnableChiefLLM added in v0.158.0

func (s *Server) EnableChiefLLM(c ChiefLLM) error

EnableChiefLLM puts the admin's chief on the LLM proxy. Call it after UseExtensions. It refuses, for the caller to refuse to boot, without the agents store or the connector store: the proxy's door (requireConnectorAgent) answers 503 to every request without them, and its audit rows go to the connector store.

The proxy is its own, with no usage store: the chief is never budgeted, so nothing would read one, and a budgeted caller on it is refused rather than served (llmproxy.Config.Store).

func (*Server) EnableOfficers added in v0.106.0

func (s *Server) EnableOfficers(cfg OfficersConfig) (*officers.Reconciler, error)

EnableOfficers turns the officer runtime on and returns its wake loop for the caller to Run. It needs the agents store and the provisioner (an officer is nothing without instances), and the claude-code kind.

func (*Server) EndStreams

func (s *Server) EndStreams()

EndStreams ends every server-sent-event stream this server serves — its own handlers' and any text/event-stream relayed by the /connect/ proxy — and any opened after it. It is idempotent and safe to call concurrently. cmd/muster-server calls it once at the top of its shutdown, before EITHER of its http.Servers (main and connect) begins to drain.

🔴 WITHOUT IT EVERY SHUTDOWN WITH A BROWSER OPEN COST THE WHOLE DRAIN BUDGET. http.Server.Shutdown closes idle connections and WAITS for active ones, and an SSE stream is never idle: its handler returns only when the client goes away or the request context is cancelled, and Shutdown cancels no request context. Every page's shell opens /events, so one open tab held the process for the full shutdownDrainTimeout and then exited on the deadline with the "drain did not complete" line. MEASURED at `a75b09b` against the built binary on SIGTERM: ~10,010 ms with one /events stream open, under 100 ms with none.

⚠ IT ENDS STREAMS ONLY, AND THAT IS THE POINT. The tempting fix — a BaseContext cancelled on shutdown — would cancel EVERY in-flight request, turning the drain into an abort for the ordinary requests it exists to let finish. A stream has no "finished" state to drain to, so ending it loses nothing: the EventSource reconnects to whichever process answers next. Pinned by cmd/muster-server's TestShutdownEndsStreamsButLetsAnOrdinaryRequestFinish.

🔴 A STREAM PROXIED THROUGH /connect/ ENDS TOO — THIS WAS AN OPEN RESIDUAL. connectors.Proxy.Serve relays the upstream on the request's own context, so a long-lived upstream response was an active connection nothing here ended, on the main listener and the connect one alike. MEASURED at `f44c849` at component level: Shutdown ran to its 10 s deadline with one proxied stream open, against 0 s with none. The proxy now holds the SAME signal (connectors.Proxy.StreamsEnd, set in UseExtensions) and ends a relayed exchange when it fires — but only a GET answered with text/event-stream, because the proxy also carries requests the drain must let finish: a git fetch's pack, and a POST that streams one finite, unresumable answer as text/event-stream (an LLM call, an MCP tool call). Why that pair is the test, and what it still does not end, is on connectors.endsAtShutdown. Pinned through buildApp + Run (not the built binary) by cmd/muster-server's TestShutdownEndsAProxiedEventStreamOnBothListeners, TestShutdownLetsAnOrdinaryProxiedRequestFinish and TestShutdownLetsAProxiedPOSTEventStreamFinish.

It is a second registry beside terminalSet deliberately, not a missed reuse: terminalSet.endAll also refuses new entries and waits for each release, and a stream needs neither — sharing it would change how terminals shut down.

func (*Server) EndTerminals

func (s *Server) EndTerminals(timeout time.Duration) bool

EndTerminals ends every live agent terminal, refuses new ones, and waits up to timeout for their handlers to return — which is after each terminal's release has run (Provisioner.AttachTerminal returns only then). It reports whether they all did. Call during graceful shutdown.

🔴 WITHOUT IT A REDEPLOY LEAKS EVERY OPEN TERMINAL'S tmux CLIENT. A terminal's socket is hijacked, so http.Server.Shutdown neither cancels nor waits for it; the process would exit with the handler mid-bridge and the release that ends the client in the agent's pod would never run.

func (*Server) FailOwnJobs

func (s *Server) FailOwnJobs(timeout time.Duration) int

FailOwnJobs fails, with reason interrupted, every job this process accepted and has not finished — queued ones (never sent to the agent) and running ones (whose turn this process is about to abandon) — and returns how many it failed. Called by cmd/muster-server on a graceful shutdown, AFTER the HTTP drain, so no submission can arrive behind it; bounded by timeout overall.

🔴 ONLY THIS PROCESS'S OWN JOBS, NEVER A SWEEP. During a rolling update the other pod is running ITS jobs; this touches none of them. Each write is the store's conditional Finish, so a job whose runner records its real outcome first keeps it. A crash skips this entirely, and the deadline reaper (RunJobReaper) remains the backstop.

func (*Server) Features added in v0.149.0

func (s *Server) Features() features.Set

Features is the installed registry (the zero Set when none was installed).

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler builds the http.Handler for the whole service.

func (*Server) HostDispatchListing added in v0.170.0

func (s *Server) HostDispatchListing(owner int64, host string, windows []mirror.Window)

HostDispatchListing is the hub's listing hook (mirror.Hub.SetListingNotify).

func (*Server) HostDispatchOutcomes added in v0.179.0

func (s *Server) HostDispatchOutcomes(owner int64, host string, seq uint64, windows []mirror.Window, outcomes map[string]mirror.WindowOutcome)

HostDispatchOutcomes is the hub's outcomes hook (mirror.Hub.SetOutcomesNotify).

func (*Server) HostDispatchSpawnReply added in v0.170.0

func (s *Server) HostDispatchSpawnReply(owner int64, host string, m mirror.Msg)

HostDispatchSpawnReply is the hub's late-reply hook (mirror.Hub.SetSpawnReplyNotify).

func (*Server) KickoffOutcomes added in v0.165.0

func (s *Server) KickoffOutcomes() (*KickoffOutcomeReporter, bool)

KickoffOutcomes is the tracker as internal/agentkickoff's OutcomeReporter (cmd/muster-server wires it), and false when nothing is tracked.

func (*Server) KickoffTurnTools added in v0.167.0

func (s *Server) KickoffTurnTools(ctx context.Context, a agents.Agent) (context.Context, agentkickoff.TurnTools, bool)

KickoffTurnTools is agentkickoff.Config.TurnTools: a GATEWAY-kind agent's first turn carries its muster tools (gatewayTurnTools), as each of its chat turns does.

func (*Server) MCPToolDefsFor

func (s *Server) MCPToolDefsFor(ctx context.Context, a agents.Agent) []agents.ToolDef

MCPToolDefsFor returns the MCP subset of what agent a may see, in registry order.

func (*Server) OfficerClaudeCodeSession added in v0.106.0

func (s *Server) OfficerClaudeCodeSession(a agents.Agent) (agentspec.ClaudeCodeSession, bool)

OfficerClaudeCodeSession is the provisioner's session source (agentprovision.Adapter.UseClaudeCodeSession): for a declared officer's instance, its session settings; every other agent: ok=false, unchanged.

  • BypassPermissions: true. 🔴 AN OFFICER INSTANCE RUNS WITH EVERY TOOL ALLOWED — no permission prompt at all (operator decision, PR #337 round 1). An officer deployment may have no approval gate anyone watches, and an officer reads its repository with Bash (git, curl) through muster's proxy; a prompt there stalls the instance until its turn times out. The pod's ccd seed starts every session in bypassPermissions (podagent.EnvPermissionMode). What bounds an officer is what it can REACH, not what it may run: its token (an officer-only MCP toolset, a `github` grant the operator decides explicitly, minted read-only — callerOf), and its pod's network policy.
  • AllowMCPTools: the officer tools it is offered, in registry order, then — when the connector store is configured (so the instance is offered them) — connectors_list, connector_request, connector_status, and postgres_query when the officer declares `connectors`. Redundant under bypass, and kept: it names exactly the muster tools the instance is for, and holds if bypass is ever lifted.
  • Model: the officer's configured model (its pool's, for a tiered officer).
  • LLMRoute, with no Model: a routine instance of an officer that declares `llm` (below).
  • DisableAutoMemory: every officer instance (below).

func (*Server) OfficerTurnContext added in v0.163.0

func (s *Server) OfficerTurnContext(ctx context.Context, a agents.Agent) context.Context

OfficerTurnContext is THE context a turn muster gives agent a is sent under: for an instance of a fresh_session_per_item pool (officers.Officer.FreshSessionPerItem), ctx routed with agents.HeaderCCNewConversation "1", on which the pod's ccd starts a NEW conversation (the old transcript kept) before it pastes the turn; for every other agent, ctx unchanged.

Both of the officer runtime's turns ask it: the wake loop's prompt (Reprompt) and the kickoff deliverer's first turn (agentkickoff.Config. TurnContext, wired by cmd/muster-server) — so a pod started for an item, a pod restarted at the wall-time cap, and an idle instance prompted for its next item all begin that item in a new conversation.

🔴 THE CONVERSATION IS FREED ONLY WHEN ccd CONFIRMS IT. The context also asks for ccd's 103 (agents.WithTurnAccepted), sent once the CLI has taken the turn's text; ccd's names the new conversation the text went into (agents.TurnAcceptance.NewConversation). Only then is what the instance's conversation claimed forgotten (officerConversationAccepted) — never before the send, when a turn ccd then refused (409 busy: the old turn still running) would have let the OLD conversation claim again for one round trip, and never for a ccd that took the text without naming one. ⚠ The 103 is read on the transport's goroutine as it arrives; the instance's first claim needs a model request and a tool call after it, so the order is the CLI's, not a lock's.

func (*Server) OutcomeHold added in v0.165.0

func (s *Server) OutcomeHold(a agents.Agent) (release func())

OutcomeHold holds a turn of a open for the outcome watchdog — the agent is working, never "silent" — and judges NOTHING: a scheduled job's turn (its reply is the job's result, not the agent waiting on its owner) and a memo relay turn (internal/memorelay Config.TurnHold). It neither records activity nor re-arms a waiting agent. release closes it, exactly once; a no-op when no outcome is tracked.

func (*Server) Questions

func (s *Server) Questions() *askq.Store

Questions is the question store, keyed surface-neutrally (askq.Key). An attention view lists a user's open questions with Questions().Pending(owner).

func (*Server) ReapplyComposeChiefAtBoot added in v0.158.0

func (s *Server) ReapplyComposeChiefAtBoot(ctx context.Context) <-chan struct{}

ReapplyComposeChiefAtBoot re-applies the admin's RUNNING Compose chief through the provisioner's Start, in the background, and logs the outcome on one "chief runtime:" line. The returned channel is closed when it is done.

🔴 WHY: the credential rule (ComposeChief.Credential) reads the current config on every call, but the chief's spec (the CLI's environment: its CLAUDE_CODE_OAUTH_TOKEN or its LLM route) is built only when the chief starts. An admin who changes the credential in .env and runs `docker compose up -d --wait` restarts muster, not the chief container (its own environment does not change). Without this the running chief kept its old spec: Account named one credential while the CLI used the other, and on OpenRouter -> token the LLM proxy refused every turn (audit #469 F3).

Start rebuilds the spec from the current config, and the compose driver moves the generation (the supervisor's restart signal) only when the spec's fingerprint changed: an unchanged config is a no-op, a changed one restarts the chief on the new credential.

🔴 IT NEVER STARTS A CHIEF THAT IS OFF, on either axis:

  • the admin's chief switch must be on (chiefOn: a stored Off wins);
  • its spec must be live (spec.json's replicas are 1; never the instance's phase, which reads pending or failed for a spec that is stopping). A chief stopped from its agent page, or never applied, stays as it is.

It runs under the admin's switch lock, so a click on Account → Chief during boot is ordered with it, and the spec check and the Start run under the agent's own lifecycle lock (StartIfLive), so a Stop from the agent page during boot is never undone.

🔴 A RUNNING CHIEF WITH NO CREDENTIAL LEFT IS STOPPED (Provisioner.Stop): the admin withdrew it, and agentprovision.Start refuses to revive any agent on a withdrawn credential. Keeping the spec would leave the CLI on the deleted token while Account says "No credential yet".

func (*Server) RouteTimeoutPass

func (s *Server) RouteTimeoutPass(ctx context.Context) (int, error)

RouteTimeoutPass is the route sweep. It times out every route past its deadline (the route becomes timed_out and its injection is cancelled if it is still queued), relays every answered route whose relay never happened, and delivers every hand-back an ended route owes its chief — the ONLY place a hand-back is delivered (plugins.RouteStore.TakeHandBack: exactly once). It returns how many it timed out.

func (*Server) RunAgentWatchdog added in v0.165.0

func (s *Server) RunAgentWatchdog(ctx context.Context, interval time.Duration)

RunAgentWatchdog sweeps every interval (agentoutcome.DefaultInterval when interval <= 0) until ctx ends. It returns at once with no outcome store.

func (*Server) RunAskLogSweep added in v0.165.0

func (s *Server) RunAskLogSweep(ctx context.Context, interval time.Duration)

RunAskLogSweep runs the ask log's retention sweep every interval until ctx ends (once at start): question and answer text older than the text TTL is cleared, rows older than asklog.RowTTL deleted.

func (*Server) RunAskSweep

func (s *Server) RunAskSweep(ctx context.Context, interval time.Duration)

RunAskSweep runs the question store's expiry every interval until ctx ends.

func (*Server) RunAttentionSweep

func (s *Server) RunAttentionSweep(ctx context.Context, interval time.Duration)

RunAttentionSweep expires lapsed asks until ctx ends (interval <= 0: every 30s): each is cleared from its owner's devices and views, and its waiters woken. It also delivers every owed answer (deliverDueAnswers: after a restart, a busy agent, a retry). It also clears the notification of a reply draft that expired (expireDraftNotes), and puts in front of the owner every plugin message the chief has not acted on (sweepUnroutedMessages, unrouted.go). Started by cmd/muster-server beside the other background loops; it does nothing without a store.

func (*Server) RunChiefNudgeSweep added in v0.112.0

func (s *Server) RunChiefNudgeSweep(ctx context.Context, interval time.Duration)

RunChiefNudgeSweep runs ChiefNudgePass every interval (<= 0: ChiefNudgeInterval) until ctx ends. It does nothing with the feature off.

func (*Server) RunFocusRefresh

func (s *Server) RunFocusRefresh(ctx context.Context, interval time.Duration)

RunFocusRefresh runs the periodic focus pass until ctx ends (interval <= 0: focus.DefaultInterval). It does nothing without a focus store and a summarizer. Started by cmd/muster-server beside the other background loops.

func (*Server) RunFocusRetention

func (s *Server) RunFocusRetention(ctx context.Context)

RunFocusRetention runs the focus retention sweep (focus.Retainer) now and every focus.RetentionSweepInterval until ctx ends. It needs only the focus store — not a summarizer, not MUSTER_FOCUS_INTERVAL — so a mirrored session's focus is deleted MUSTER_FOCUS_RETENTION after it was last seen whether or not the refresh pass runs. Started by cmd/muster-server.

func (*Server) RunHostDispatchSweep added in v0.170.0

func (s *Server) RunHostDispatchSweep(ctx context.Context, interval time.Duration)

RunHostDispatchSweep ends, every interval, each open host dispatch whose host has not been seen for hostNotSeenEnd. It reads only the table (never the hub's memory of offline hosts), so it answers the same after a restart.

func (*Server) RunJobReaper

func (s *Server) RunJobReaper(ctx context.Context, interval time.Duration)

RunJobReaper fails abandoned jobs — each past its own deadline (jobs.Store.ReapOverdue) — and dispatches every agent's queued jobs (dispatchQueuedJobs), once immediately, then every interval until ctx ends. It does nothing with no job store. Started by cmd/muster-server.

🔴 THE PASS AT BOOT IS WHAT RUNS A JOB A CRASH LEFT QUEUED. Its goroutine died with the process; the row is the only thing left of it.

🔴 IT REPLACES A BOOT SWEEP THAT FAILED EVERY UNFINISHED JOB, which was wrong under a rolling update: the new pod boots while the old one still runs jobs, so the sweep failed live jobs (whose real result the old pod's conditional Finish then dropped), and a job the old pod accepted after the sweep was never failed by anything. A deadline is a fact about the job, not about which process is alive, so this pass is right from any pod at any time, and running it on every replica is duplicated work, not duplicated effect.

func (*Server) RunRouteTimeouts

func (s *Server) RunRouteTimeouts(ctx context.Context, interval time.Duration)

RunRouteTimeouts runs RouteTimeoutPass every interval until ctx ends. It does nothing with routing off. Started by cmd/muster-server.

func (*Server) RunSendQueue

func (s *Server) RunSendQueue(ctx context.Context, interval time.Duration)

RunSendQueue runs the send queue's dispatcher until ctx ends. It does nothing without a queue store. Started by cmd/muster-server beside the other background loops.

func (*Server) RunSessionStateSweep added in v0.141.0

func (s *Server) RunSessionStateSweep(ctx context.Context, interval time.Duration)

RunSessionStateSweep runs SessionStatePass every interval (<= 0: SessionStateInterval) until ctx ends. It does nothing when off.

func (*Server) RunSuggestSweep

func (s *Server) RunSuggestSweep(ctx context.Context)

RunSuggestSweep drops suggestion text past its TTL until ctx ends. Started by cmd/muster-server; nothing without an engine.

func (*Server) RunTaskReap

func (s *Server) RunTaskReap(ctx context.Context, interval time.Duration)

RunTaskReap drives the idle-task reaper, and the stopped-agent reaper (agent_reap.go), until ctx is cancelled.

🔴 It is a SEPARATE loop from RunTaskRetention, and that is a fixed bug rather than a preference — see TaskReapInterval.

func (*Server) RunTaskRetention

func (s *Server) RunTaskRetention(ctx context.Context, interval time.Duration)

RunTaskRetention drives the daily retention sweep until ctx is cancelled: each tick deletes connector audit entries and agent chat messages older than their windows, then reaps idle tasks.

🔴 A FOLLOWER SKIPS THE TICK AND CONTINUES — never `return`. A follower that exited would be permanently sweep-less for the rest of the process's life and would look identical to a healthy one.

func (*Server) SessionStatePass added in v0.141.0

func (s *Server) SessionStatePass(ctx context.Context) error

SessionStatePass is one pass over every owner.

func (*Server) SetAgentReapStoppedAfter

func (s *Server) SetAgentReapStoppedAfter(d time.Duration)

SetAgentReapStoppedAfter sets how long an agent may stay stopped before the reaper destroys it. Zero or less turns the reaper off.

func (*Server) SetFaroRelay

func (s *Server) SetFaroRelay(upstream, key string)

SetFaroRelay turns the relay on, forwarding to upstream with key as its x-api-key ("" for none). An empty upstream leaves it off: the route answers 404, like a route that does not exist.

func (*Server) SetReadyCheck

func (s *Server) SetReadyCheck(fn func(context.Context) error)

SetReadyCheck installs the readiness probe's dependency check (e.g. a DB ping).

func (*Server) SetTaskLeaderGate

func (s *Server) SetTaskLeaderGate(g LeaderGate)

SetTaskLeaderGate installs the cross-process singleton gate for the background loops: RunTaskRetention and RunTaskReap.

A nil gate leaves the loops unguarded, which is the single-process dev path.

func (*Server) SetTaskReapAfter

func (s *Server) SetTaskReapAfter(d time.Duration)

SetTaskReapAfter overrides the idle window the stale-task sweep uses.

func (*Server) StopJobs added in v0.179.0

func (s *Server) StopJobs()

StopJobs is the FIRST step of a graceful shutdown (cmd/muster-server's shutdown, before the HTTP drain): from now on this process takes no job from the table — no drain starts, a running drain reads the queue no more, the reaper's pass dispatches nothing, and a job not yet started is not started (runJob). A job this process took from the queue but had not started is left queued for another server; one it accepted stays this process's, and FailOwnJobs fails it as before.

🔴 WITHOUT IT, A STOPPING SERVER KEEPS TAKING JOBS. During a rolling update the old pod's drains run on their own context until the process exits, so it could take a job the NEW pod accepted, then fail it in FailOwnJobs or start it and exit, leaving it running with no runner until it is reaped.

func (*Server) UseApprovalGate

func (s *Server) UseApprovalGate(g GatePort)

UseApprovalGate attaches the queue the claude-code approval relay (approvals.go) files cards through, and nothing else uses. A nil gate is supported: the relay answers 503 and every prompt falls back to the terminal.

func (*Server) UseExtensions

func (s *Server) UseExtensions(ext Extensions)

UseExtensions attaches the dependencies. Call before Handler.

🔴 IT WRAPS Notes, AND THAT WRAP IS THE WHOLE REASON THIS FUNCTION EXISTS RATHER THAN A PLAIN FIELD ASSIGNMENT. internal/notes does not join the session table — it cannot, the table is another service's — so every SessionLink it returns has DetailAvailable=false until something composes it. This is the ONE place that happens. Doing it in handlers instead would be twenty-odd places to forget, and forgetting is SILENT: false renders the words "no transcript recorded" over a live transcript, with nothing logged and nothing 404ing. Upstream that exact conflation disguised a months-long outage as ordinary retention.

⚠ It is applied here rather than in the binary's wiring on purpose: this is the only door into s.ext, so a fixture and the binary get the same store.

func (*Server) UseFeatures added in v0.149.0

func (s *Server) UseFeatures(set features.Set)

UseFeatures installs the evaluated feature registry. Call before Handler.

func (*Server) UseGoTrue

func (s *Server) UseGoTrue(g GoTrueAuth)

UseGoTrue attaches the GoTrue wiring. Call before Handler.

func (*Server) UseRouter

func (s *Server) UseRouter(r RouterPort)

UseRouter attaches the permission-router client. Call before Handler.

⚠ A nil port is the standalone deployment and is supported; see RouterPort.

func (*Server) WaitForAskSuggestions

func (s *Server) WaitForAskSuggestions()

WaitForAskSuggestions waits for every ask-suggestion generation this server started: the tests, and cmd/muster-server's shutdown, which bounds it (askSuggestDrainTimeout) before the push drain.

func (*Server) WaitForAttentionDeliveries

func (s *Server) WaitForAttentionDeliveries()

WaitForAttentionDeliveries waits for every answer delivery this process started (shutdown, tests).

func (*Server) WaitForOfficerReprompts added in v0.106.0

func (s *Server) WaitForOfficerReprompts()

WaitForOfficerReprompts blocks until every in-flight re-prompt send has ended and released its session claim. Called by the shutdown drain after EndStreams (which cancels them), and by tests.

func (*Server) WaitForPluginDeliveries

func (s *Server) WaitForPluginDeliveries()

WaitForPluginDeliveries blocks until every in-flight plugin delivery has recorded its outcome. Call during graceful shutdown, after EndStreams.

func (*Server) WaitForPushes

func (s *Server) WaitForPushes()

WaitForPushes blocks until every in-flight notification fan-out has finished. Call during graceful shutdown.

type SessionLivenessProbe

type SessionLivenessProbe interface {
	// SessionsExisting reports which of sessionIDs still have a transcript record.
	// Ids absent from the map have none.
	SessionsExisting(ctx context.Context, sessionIDs []string) (map[string]bool, error)
}

SessionLivenessProbe is the batched existence read this package needs from whatever holds the session records. Declared consumer-side and NARROW: the decorator wants one bit per id and must not be able to reach for a transcript tail, a project name or anything else on the row.

🔴 IT IS BATCHED EVEN THOUGH THE ONLY IMPLEMENTATION IS PER-ID, AND THAT IS DELIBERATE. internal/router satisfies this by issuing one request per id behind the batched signature. Keeping the batch shape at the port means the decorator resolves a whole board read in ONE call — the N+1 the extraction plan explicitly refused to build — and it means a batch form of the upstream route, if one ever lands, drops in here without touching a single caller. A per-id port would have pushed the fan-out into the decorator and made that substitution a rewrite.

type SessionMeta

type SessionMeta struct {
	SessionID string
	Project   string
	Cwd       string
	Host      string
}

SessionMeta is what the router can say about one session.

type TaskRouting

type TaskRouting struct {
	// DispatchOwners is MUSTER_CHIEF_DISPATCH_OWNERS: the users who opted in to
	// their chief starting agents. Non-empty is what turns agent_dispatch on;
	// empty: nobody has, and the tool is not offered.
	DispatchOwners map[int64]bool
	// DispatchModels is MUSTER_CHIEF_DISPATCH_MODELS: the OpenRouter models a
	// mirrored dispatch's model card offers for opencode, in order, each
	// already in mirror.ValidSpawnModel's shape (empty: none listed; the card
	// still offers the typed id).
	DispatchModels []string
}

TaskRouting is task routing's configuration.

type Transcriber

type Transcriber interface {
	Transcribe(ctx context.Context, audio io.Reader, filename string) (string, error)
}

Transcriber turns a recording into text (internal/stt's Client).

type UserStore

type UserStore interface {
	BySub(ctx context.Context, sub string) (users.User, error)
	ByID(ctx context.Context, id int64) (users.User, error)
	SetDisabled(ctx context.Context, id int64, disabled bool) (users.User, error)
	// RecordSignOutEverywhere persists a sign-out-everywhere of user id
	// (users.signed_out_at), which the send queue's delivery checks.
	RecordSignOutEverywhere(ctx context.Context, id int64) (time.Time, error)
	// IDByEmail resolves a sign-in email to a muster user id (case-folded).
	IDByEmail(ctx context.Context, email string) (int64, bool, error)
	// DisabledAmong reports, for each of ids that exists, whether it is
	// disabled. One query: the disable sweep calls it every interval.
	DisabledAmong(ctx context.Context, ids []int64) (map[int64]bool, error)
	RedeemClaim(ctx context.Context, tokenHash []byte, email string,
		create func(context.Context) (string, error), undo func(sub string)) (users.User, error)
}

UserStore is what the session tier needs from internal/users.

type WebManifest

type WebManifest struct {
	ID              string              `json:"id"`
	Name            string              `json:"name"`
	ShortName       string              `json:"short_name"`
	Description     string              `json:"description"`
	StartURL        string              `json:"start_url"`
	Scope           string              `json:"scope"`
	Display         string              `json:"display"`
	ThemeColor      string              `json:"theme_color"`
	BackgroundColor string              `json:"background_color"`
	Icons           []manifestImage     `json:"icons"`
	Shortcuts       []manifestShortcut  `json:"shortcuts"`
	ShareTarget     manifestShareTarget `json:"share_target"`
	Screenshots     []manifestImage     `json:"screenshots"`
}

WebManifest is the web app manifest muster serves.

func Manifest

func Manifest() WebManifest

Manifest returns the manifest's value.

Design notes, each a decision rather than a default:

  • id "/" FOREVER. It is the installed app's identity; changing it makes every phone treat the next version as a second app.
  • no `orientation`. The old portrait lock also locked tablets and foldables.
  • theme_color/background_color are ui.ThemeColorDark — the same constant the theme-color meta reads, itself pinned to input.css's --mu-bg — so the splash screen, the status bar and the page cannot disagree.
  • share_target is GET. Behind the forward-auth edge a POST is answered 303 with its body dropped; a GET's query survives the login round trip (and muster's own ?next=), so a share started while signed out still lands.
  • every image lives under /static/icons/, one static prefix a forward-auth proxy can let through without a session — the screenshots included, so the richer install sheet does not depend on how the browser fetches them. Hence the fixture-data-only rule on them below.
  • Chrome on Android shows at most three shortcuts; there are three.

Source Files

Jump to

Keyboard shortcuts

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