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
- Variables
- func ApprovalCardHost(a agents.Agent) string
- func BrowserListener(h http.Handler) http.Handler
- func BuildAssetLinks(pkg, certs string) ([]byte, error)
- func DraftStepUpWhy() string
- func GitPushRecipe(connector, path string) string
- func NewAdminClaimLink(ctx context.Context, store ClaimMinter, publicURL string, now time.Time) (string, error)
- func OnlyConnectSurface(h http.Handler) http.Handler
- func ProxyRecipe(connector, host string) string
- func ProxyUsage(name string, hosts []string) string
- func RegisterRoutes(mux Mux)
- func SendQueueCancelledAnsweredText(asker string) string
- func SendQueueEditedAnsweredText(asker string) string
- func ServiceWorkerSource() ([]byte, error)
- func SetTelemetryConnectSrc(rawURL string)
- func SetUserDisabled(ctx context.Context, g GoTrueAuth, id int64, disabled bool, invalidate func()) error
- func SetUserDisabledAs(ctx context.Context, g GoTrueAuth, by *users.Actor, id int64, disabled bool, ...) error
- func ShareBody(title, text, link string) string
- func UseOpenRouterModelsURL(u string)
- func ValidActor(s string) bool
- func ValidLegacyProvenancePrefix(prefix string) error
- type AccountStore
- type ActiveAgent
- type AgentConnectorView
- type AgentKinds
- type ApprovalRequest
- type AuthConfig
- type AuthMode
- type ClaimMinter
- type ClaudeAccountHealth
- type CredentialStore
- type DoctorHost
- type DoctorMirror
- type DoctorReport
- type Extensions
- type GateDecision
- type GatePort
- type GateSpec
- type Gateway
- type GitHubApp
- type GoTrueAuth
- type JobWorkspace
- type LeaderGate
- type MailResume
- type Mirror
- type MirrorHostReport
- type MirrorTokenAuth
- type Mux
- type OfficersConfig
- type PRMail
- type ProfileReapplier
- type Provisioner
- type PushService
- type RouterNotification
- type RouterPort
- type Routing
- type SendQueue
- type Server
- func (s *Server) AgentConnectorList(ctx context.Context, a agents.Agent) ([]AgentConnectorView, error)
- func (s *Server) AgentConnectorStatus(ctx context.Context, a agents.Agent, name string, wait time.Duration) (AgentConnectorView, error)
- func (s *Server) AgentInstructions(a agents.Agent) string
- func (s *Server) AgentRequestConnector(ctx context.Context, a agents.Agent, name, reason string) (AgentConnectorView, bool, error)
- func (s *Server) AgentToolDefsFor(ctx context.Context, a agents.Agent) []agents.ToolDef
- func (s *Server) AgentToolDispatch(ctx context.Context, a agents.Agent) agents.ToolDispatch
- func (s *Server) AgentWork(id int64) mirror.WindowWork
- func (s *Server) AttentionMirrorChanged(owner int64)
- func (s *Server) AwaitingApproval(agentID int64) bool
- func (s *Server) BroadcastAgentChanged(agentName string)
- func (s *Server) BroadcastAgentsChangedFor(owner int64)
- func (s *Server) DisableUser(ctx context.Context, id int64, disabled bool) error
- func (s *Server) DisableUserAs(ctx context.Context, by users.Actor, id int64, disabled bool) error
- func (s *Server) EnableOfficers(cfg OfficersConfig) (*officers.Reconciler, error)
- func (s *Server) EndStreams()
- func (s *Server) EndTerminals(timeout time.Duration) bool
- func (s *Server) FailOwnJobs(timeout time.Duration) int
- func (s *Server) Handler() http.Handler
- func (s *Server) MCPToolDefsFor(ctx context.Context, a agents.Agent) []agents.ToolDef
- func (s *Server) OfficerClaudeCodeSession(a agents.Agent) (agentspec.ClaudeCodeSession, bool)
- func (s *Server) Questions() *askq.Store
- func (s *Server) RouteTimeoutPass(ctx context.Context) (int, error)
- func (s *Server) RunAskSweep(ctx context.Context, interval time.Duration)
- func (s *Server) RunAttentionSweep(ctx context.Context, interval time.Duration)
- func (s *Server) RunFocusRefresh(ctx context.Context, interval time.Duration)
- func (s *Server) RunFocusRetention(ctx context.Context)
- func (s *Server) RunJobReaper(ctx context.Context, interval time.Duration)
- func (s *Server) RunRouteTimeouts(ctx context.Context, interval time.Duration)
- func (s *Server) RunSendQueue(ctx context.Context, interval time.Duration)
- func (s *Server) RunSuggestSweep(ctx context.Context)
- func (s *Server) RunTaskReap(ctx context.Context, interval time.Duration)
- func (s *Server) RunTaskRetention(ctx context.Context, interval time.Duration)
- func (s *Server) SetAgentReapStoppedAfter(d time.Duration)
- func (s *Server) SetFaroRelay(upstream, key string)
- func (s *Server) SetReadyCheck(fn func(context.Context) error)
- func (s *Server) SetTaskLeaderGate(g LeaderGate)
- func (s *Server) SetTaskReapAfter(d time.Duration)
- func (s *Server) UseApprovalGate(g GatePort)
- func (s *Server) UseExtensions(ext Extensions)
- func (s *Server) UseGoTrue(g GoTrueAuth)
- func (s *Server) UseRouter(r RouterPort)
- func (s *Server) WaitForAskSuggestions()
- func (s *Server) WaitForAttentionDeliveries()
- func (s *Server) WaitForOfficerReprompts()
- func (s *Server) WaitForPluginDeliveries()
- func (s *Server) WaitForPushes()
- type SessionLivenessProbe
- type SessionMeta
- type TaskRouting
- type Transcriber
- type UserStore
- type WebManifest
Constants ¶
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.
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.
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.
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 )
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.
const ( RefusedSubjectNotFound = "subject_not_found" RefusedNotDelivered = "not_delivered" )
The refusal reasons plugin_message_route adds to route_to_session's.
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.
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).
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).
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." // A Hermes window's (docs/design/hermes.md, the gated send, step 1). SendQueueHermesWaitingNow = "Not sent: Hermes is waiting for you (an approval or a question). Answer it in the terminal first." SendQueueHermesBusyNow = "Not sent: Hermes is working, and Enter would interrupt its turn. Leave it queued." SendQueueHermesUnknownNow = "Not sent: muster cannot tell whether Hermes is idle, and Enter could answer a prompt it is showing. Leave it queued." // SendQueueGatedUnspokenNow: a window of a runtime with a gated send // for which this server has no Send now words (gatedSendNowWords): // refused whatever its state, rather than sent on a guess. SendQueueGatedUnspokenNow = "Not sent: muster cannot tell whether this agent is idle, and Enter could answer a prompt it is showing. Leave it queued." )
Why a Send now was refused.
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.)
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 // 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 )
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" RefusedUnsupported = "unsupported_target" RefusedInjectFailed = "inject_failed" )
The refusal reasons route_to_session answers.
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." )
The route's answers. Each is muster's own sentence; the page shows it as is.
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.
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.
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.
const AdminOnlyRefusal = "this page is for admins"
AdminOnlyRefusal is what a non-admin principal gets from /admin/*.
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.
const AgentSendEmpty = "nothing to send: type a message first"
AgentSendEmpty answers a send with no text.
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.
const AssetLinksPath = "/.well-known/assetlinks.json"
AssetLinksPath is where Android looks for a site's Digital Asset Links.
const ChiefDisplayName = "chief"
ChiefDisplayName is the display name that marks an agent as the fleet's chief.
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.
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).
const ClaimTTL = 24 * time.Hour
ClaimTTL is how long a claim link stays redeemable.
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).
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.
const CrossOriginRefusal = "cross-origin request refused: this action must come from muster's own pages"
CrossOriginRefusal is the error requireSameOrigin answers.
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.
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 )
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.
const DeviceThrottled = "too many requests from this device or address; wait a minute"
DeviceThrottled is the 429 body for a throttled device-tier request.
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.
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.
const DevicesNotServed = "this server does not serve paired devices (no database)"
DevicesNotServed is the 503 body when the server has no device store.
const DisableSweepInterval = 10 * time.Second
DisableSweepInterval is how often the disable sweep (sweepDisabled) re-reads disabled_at for every user with an open request.
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.
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).
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.
const FaroRelayPath = "/telemetry/faro"
FaroRelayPath is the relay's route: what the page's Faro posts to when a relay upstream is configured.
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.
const FlowsUnconfigured = "this server does not serve browser flows (no database)"
FlowsUnconfigured is the 503 body when no flow store is wired (no database).
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.
const InvitePath = "/invite"
InvitePath is the invitee's page. The token rides in the URL FRAGMENT (`/invite#<token>`), for the reason ClaimPath gives.
const InviteTTL = 72 * time.Hour
InviteTTL is an invite link's default lifetime; inviteTTLChoices are the lifetimes the create form offers.
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).
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).
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).
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.
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.
const JobShutdownTimeout = 5 * time.Second
JobShutdownTimeout bounds FailOwnJobs at shutdown.
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.
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.
const MirrorSendEmpty = "nothing to send: type a message first"
MirrorSendEmpty answers a send with no text: 400, said rather than dropped.
const MirrorSendUnconfirmed = "" /* 155-byte string literal not displayed */
MirrorSendUnconfirmed answers a send the host never confirmed (a Claude Code window's; a Hermes window's says it in the host's own words).
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.
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.
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.
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.
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.
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.
const ResetPath = "/auth/reset"
ResetPath is the password-reset page; its token rides in the fragment too.
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.
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.
const SendAgainHeader = ui.SendAgainHeader
SendAgainHeader is ui.SendAgainHeader: one spelling, which the composer's script reads.
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.
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.
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.
const SendQueueRetryConfirmField = "confirm"
SendQueueRetryConfirmField is the form field that says the person confirmed retrying a message that may already have been sent.
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.
"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.
"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.
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.
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).
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.
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 ¶
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.
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).
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.
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.
var ConnectSurfacePrefixes = []string{"/connect/", "/agent/connectors", "/mcp", "/agent/approvals", "/agent/blocked", "/agent/work"}
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.
var ErrAgentBeingReplaced = errors.New("this agent is being replaced; send the message to the new chief once it is up")
ErrAgentBeingReplaced refuses a chat turn to an agent the chief replacement has closed: it is about to be deleted.
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.
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.
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.
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.
var MirrorScrollUnsupported = unprefixed(mirror.ErrScrollUnsupported)
MirrorScrollUnsupported is the 409's text when the host cannot scroll.
Functions ¶
func ApprovalCardHost ¶
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 ¶
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 ¶
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 DraftStepUpWhy ¶
func DraftStepUpWhy() string
DraftStepUpWhy is the confirm dialog's sentence on the Asks page.
func GitPushRecipe ¶
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 ¶
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 ¶
OnlyConnectSurface wraps h so it serves only ConnectSurfacePrefixes (and /health, for a probe), answering 404 for every other path.
func ProxyRecipe ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
ValidLegacyProvenancePrefix reports why prefix cannot be a legacy provenance header prefix, or nil if it can. Empty is valid: it means "none".
Types ¶
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)
// 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 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 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 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 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"`
}
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
// 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
// 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
// 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
// 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 Agents
// view draws no mirrored card. 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 Agents list's per-user pins (internal/pins, migration 0017).
// nil (no database): nothing is pinned, no card is drawn pinned, and the pin
// routes answer 404.
Pins pins.Store
// Recents is the Agents list's per-user "recently viewed" entries
// (internal/recents, migration 0018). nil (no database): no visit is
// recorded and the strip is never drawn.
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 Agents list's Idle section threshold
// (MUSTER_AGENTS_IDLE_AFTER, ui.DefaultIdleSectionAfter when unset): an
// entry with no activity for longer is drawn under the collapsed "Idle (N)"
// header (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 card shows 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
// 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
// / task_dispatch tools are not offered. ChiefDispatch is the ledger
// task_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
// 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
// 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
}
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 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 — 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), 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 string) (string, error)
// 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 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 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))
}
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 ProfileReapplier ¶
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 the UI's "Save for later", whose
// gate check (agents.go, the `gate:<reason>` refusal) allows a save 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: handleAgentCreate
// 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
}
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 ¶
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) 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 ¶
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 ¶
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) 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) AttentionMirrorChanged ¶
AttentionMirrorChanged is attentionMirrorChanged for the mirror hub's waiting-set hook (mirror.Service.SetWaitingNotify; cmd/muster-server).
func (*Server) AwaitingApproval ¶
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 ¶
BroadcastAgentChanged fires an SSE agent.changed nudge for the named agent so an open Tasks tab and the Agents tab 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 ¶
BroadcastAgentsChangedFor nudges owner's open Agents views 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) DisableUser ¶
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 ¶
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) 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 ¶
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 ¶
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) MCPToolDefsFor ¶
MCPToolDefsFor returns the MCP subset of what agent a may see, in registry order.
func (*Server) OfficerClaudeCodeSession ¶ added in v0.106.0
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. 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.
func (*Server) Questions ¶
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) RouteTimeoutPass ¶
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) RunAskSweep ¶
RunAskSweep runs the question store's expiry every interval until ctx ends.
func (*Server) RunAttentionSweep ¶
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) RunFocusRefresh ¶
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 ¶
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) RunJobReaper ¶
RunJobReaper fails abandoned jobs — each past its own deadline (jobs.Store.ReapOverdue) — once immediately, then every interval until ctx ends. It does nothing with no job store. Started by cmd/muster-server.
🔴 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 ¶
RunRouteTimeouts runs RouteTimeoutPass every interval until ctx ends. It does nothing with routing off. Started by cmd/muster-server.
func (*Server) RunSendQueue ¶
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) RunSuggestSweep ¶
RunSuggestSweep drops suggestion text past its TTL until ctx ends. Started by cmd/muster-server; nothing without an engine.
func (*Server) RunTaskReap ¶
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 ¶
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) SetAgentReapStoppedAfter ¶
SetAgentReapStoppedAfter sets how long an agent may stay stopped before the reaper destroys it. Zero or less turns the reaper off.
func (*Server) SetFaroRelay ¶
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 ¶
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 ¶
SetTaskReapAfter overrides the idle window the stale-task sweep uses.
func (*Server) UseApprovalGate ¶
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) 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 ¶
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 task_dispatch on;
// empty: nobody has, and the tool is not offered.
DispatchOwners map[int64]bool
}
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"`
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
¶
- accounts.go
- active_agents.go
- actor.go
- admin.go
- agent.go
- agent_cli.go
- agent_destroy_tool.go
- agent_href.go
- agent_reap.go
- agent_send.go
- agent_work.go
- agents.go
- api_tokens.go
- approvals.go
- asks_drafts.go
- assetlinks.go
- attention.go
- attention_ask_page.go
- attention_asker.go
- attention_delivery.go
- attention_drafts.go
- attention_hermes.go
- attention_push_target.go
- attention_suggest.go
- attention_tools.go
- auth.go
- bounded_window.go
- cards_attention.go
- chief_agent.go
- chief_ask_tool.go
- chief_panel_ui.go
- chief_provision.go
- chief_replace.go
- chief_threads.go
- chief_toggle.go
- comment_delete.go
- composer.go
- connector_decide_tools.go
- connector_standing.go
- connector_tools.go
- connectors.go
- credentials.go
- device_actions.go
- devices.go
- directories.go
- doc_seams.go
- doctor.go
- ext.go
- faro_relay.go
- flow_tools.go
- flows.go
- focus.go
- focus_history.go
- focus_tools.go
- gate.go
- gated_task_tool.go
- github_source.go
- jobs.go
- jobs_grants.go
- live.go
- live_status.go
- login.go
- login_gotrue.go
- login_invite.go
- machine_agents.go
- mail_resume.go
- mcp.go
- merge.go
- middleware.go
- mirror.go
- mirror_ask.go
- mirror_complete.go
- mirror_ledger.go
- mirror_mcp.go
- mirror_scroll.go
- mirror_subagents.go
- mirror_view.go
- nav_agents.go
- notes.go
- notes_routes.go
- officers.go
- open_trace.go
- openrouter.go
- owner_replies.go
- passkeys.go
- passkeys_script.go
- pins.go
- plugin_draft_tools.go
- plugin_drafts.go
- plugin_message_route_tools.go
- plugin_retry.go
- plugin_tasks.go
- plugins.go
- pr_routes.go
- principal.go
- projects.go
- provenance_headers.go
- push_routes.go
- push_task.go
- pwa.go
- recents.go
- refresh_guard.go
- reply_draft_tool.go
- route_reply_tool.go
- routes.go
- send_queue.go
- send_queue_edit.go
- send_queue_now.go
- server.go
- session_liveness.go
- session_routes.go
- session_runtime.go
- sessions_overview.go
- signin_limiter.go
- stepup.go
- streams.go
- suggest.go
- suggest_account.go
- suggest_socket.go
- tags.go
- task_actions.go
- task_complete_stop.go
- task_routing.go
- task_sessions.go
- task_status_writer.go
- terminal.go
- thread_routes.go
- transcribe.go
- turn_gate.go
- unrouted.go
- uploads.go
- view.go