mirror

package
v0.219.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 40 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package mirror is the server half of MIRRORED sessions: tmux sessions that live on an operator's own machines (a workstation, a laptop) and appear in muster's sidebar and session switcher beside its provisioned agents, so the list is complete.

🔴 A MIRRORED SESSION IS NOT AN AGENT. Nothing about it is persisted: the hub holds each connected host's session list IN MEMORY, keyed by the host's token OWNER and host name, and the sidebar renders it from there. No agents row, no kind, no chat, no lifecycle — so it can never be dispatched, deleted, chatted with, or mistaken for an agent by name (a tmux session named "chief" is not the chief). The only table is mirror_tokens (migration 0008).

It is an OPTIONAL PLUGIN, off unless MUSTER_MIRROR=1. The other half is the `muster-mirror` binary (cmd/muster-mirror, internal/mirrorhost), installed only on the machines whose sessions should be mirrored.

🔴 THE HOST DIALS OUT; muster NEVER DIALS IN. muster holds no SSH key, no address and no inbound route to any host. A host's muster-mirror opens ONE WebSocket to muster (GET /mirror/connect), authenticated by a per-host mirror token, registers its session list on it, and serves terminal attaches that muster multiplexes back down the same connection. Nothing crosses from muster to the host but the tunnel's own frames: no muster credential, no agent token, no configuration.

This file is the WIRE, shared by both halves so they cannot disagree about it.

Index

Constants

View Source
const (
	// AgentBindVerified: the host sends to the window's session, to a paste
	// naming it.
	AgentBindVerified = "verified"
	// AgentBindTitleShared: another session — a subagent's child session —
	// carries the pane's title too (exactly, or as the start of a cut title),
	// and a TUI can show a child session.
	AgentBindTitleShared = "title-shared"
	// AgentBindArgv: the TUI was started on one session (its -s/--session)
	// and its title names another.
	AgentBindArgv = "argv-session"
	// AgentBindListCut: the server holds more sessions than muster reads, so
	// no title can be shown unique against them.
	AgentBindListCut = "list-cut"
	// AgentBindStream: the opencode server's event stream is not open, so the
	// session list the title was matched against may be stale.
	AgentBindStream = "stream-down"
)

The AgentBind codes.

View Source
const (
	PasteRefusedOpenCodeTitleSharedText = "Not sent: a subagent's opencode session has the same title as this pane " +
		"(or one that starts the same way), so muster can't be sure which session it shows. Type it in the terminal, " +
		"or start it with `muster-mirror opencode`."
	PasteRefusedOpenCodeArgvText = "Not sent: this opencode was started on one session (its -s) but its title names " +
		"another, so muster can't be sure which it shows. Type it in the terminal, or start it with `muster-mirror opencode`."
	PasteRefusedOpenCodeListCutText = "Not sent: the opencode server holds more sessions than muster reads, so it " +
		"can't be sure no other session shares this pane's title. Type it in the terminal, or start it with " +
		"`muster-mirror opencode`."
	PasteRefusedOpenCodeStreamText = "Not sent: muster can't confirm which session this opencode shows right now, " +
		"because the opencode server's event stream is not answering. Try again in a moment."
	// PasteRefusedOpenCodeMovedText: the window shows another session now
	// than the one the message was written in view of — the page's, or the
	// one a queued message was stored with (PasteRefusalOpenCodeMoved). The
	// hub refuses it against its list, and the host against the pane.
	PasteRefusedOpenCodeMovedText = "Not sent: this opencode pane shows another session now than the one this " +
		"message was written for, so nothing was sent. To send it there, write it again while viewing the session shown now."
	// PasteRefusedOpenCodeUnnamedText: a message for a hand-opened pane that
	// names no session (a page or a queued message from before muster
	// recorded one), which muster cannot tell is meant for the session shown.
	PasteRefusedOpenCodeUnnamedText = "Not sent: muster can't tell which opencode session this message was written " +
		"for (it was queued or typed on an older page), so nothing was sent. Reload the page, then write it again."
)

The refusals of a hand-opened opencode pane muster does not send to.

View Source
const (
	// TypeAgentClose (muster → host): end the agent in the window CloseReq
	// names.
	TypeAgentClose = "agent-close"
	// TypeAgentClosed (host → muster): its outcome (CloseResult, or Refusal
	// and Error), answering the request's ID.
	TypeAgentClosed = "agent-closed"
)

ENDING A SESSION (docs/design/chief-in-agent-view.md, end-session): muster asks a host to end ONE of its owner's agent windows, on the owner's tap of the chief's proposal card — never on its own.

  • agent-close (muster → host) names exactly one window: its tmux session and window id, and the conversation muster expects there (CloseReq.Key, a session key). The host checks the window is one it LISTS now, of that session, running an agent (Claude Code or opencode) in THAT conversation, and refuses anything else.
  • A Claude Code agent is asked to exit cleanly: the host types /exit only through the Claude prompt guard's checked paste, and only when the pane is at an idle prompt with an empty input box. Then it waits for the agent's process to end — the window closes with it, or its pane is back at a shell, which it then closes — and closes the window itself once the grace (AgentCloseGrace) has passed without that. A pane waiting on the person (a permission prompt, a picker, a dialog) or holding a draft is typed nothing: its window is closed at once.
  • An opencode window is closed at once: muster types into no opencode pane, and opencode's server offers no call that exits its TUI.
  • agent-closed (host → muster) says how it ended (CloseResult.Graceful, and Reason when it was not), or the refusal.

🔴 OPT-IN BY CAPABILITY, BACKWARD-COMPATIBLE BOTH WAYS: a host advertises Msg.AgentClose (an -interactive v2 host whose backend can close a window); muster asks no other host. An older host never advertises it.

View Source
const (
	// CloseNotListed: no window of that session with that id is listed.
	CloseNotListed = "not_listed"
	// CloseNoAgent: the window runs no agent (Claude Code or opencode).
	CloseNoAgent = "no_agent"
	// CloseUnavailable: this host does not close windows (not -interactive,
	// or a backend that cannot).
	CloseUnavailable = "unavailable"
	// CloseFailed: the close itself failed.
	CloseFailed = "failed"
	// CloseMismatch: the window runs a different conversation than the one
	// the request names (CloseReq.Key), or none at all now.
	CloseMismatch = "mismatch"
)

The host's agent-close refusals (Msg.Refusal).

View Source
const (
	// TypeAgentSpawn (muster → host): start an agent (Msg.Spawn) for host
	// dispatch Msg.Dispatch. ID is the request id (the stream id space).
	TypeAgentSpawn = "agent-spawn"
	// TypeAgentSpawned (host → muster): its outcome, always naming
	// Msg.Dispatch: Msg.Spawned on success, Msg.Refusal and Msg.Error on a
	// refusal.
	TypeAgentSpawned = "agent-spawned"
)
View Source
const (
	SpawnRuntimeClaude   = "claude"
	SpawnRuntimeOpenCode = "opencode"
)

The runtimes a host can spawn (Msg.AgentSpawn). opencode is advertised only beside Msg.OpenCodeSend (spawnRuntimesOf).

View Source
const (
	SpawnUnavailable = "unavailable"
	SpawnNoRepo      = "no_repo"
	SpawnBadBase     = "bad_base"
	SpawnBadModel    = "bad_model"
	SpawnFailed      = "failed"
	// SpawnBadClone: the clone muster hinted (AgentSpawnReq.Clone) is not one
	// of the host's own clones of the repository under its spawn roots now.
	SpawnBadClone = "bad_clone"
	// SpawnNotListed is not a refusal: the window exists but has not been in a
	// listing on this connection yet. The row stays pending.
	SpawnNotListed = "not_listed"
)

The refusal codes of an agent-spawned (Msg.Refusal), design 3.1. Each names the one thing the chief can do about it; Msg.Error is a fixed sentence.

View Source
const (
	// MaxSpawnPrompt is the prompt's limit in bytes (design 2.2: 8 KiB).
	MaxSpawnPrompt = 8 << 10
	// MaxSpawnName is the display name's limit before the host sanitises it.
	MaxSpawnName = 200
)

SpawnPrompt bounds.

View Source
const (
	// TypeCatalog (muster → host): send the catalog of Session/Window, by ID.
	TypeCatalog = "catalog"
	// TypeCataloged (host → muster): the answer to catalog ID — Msg.Catalog, or
	// Msg.Error.
	TypeCataloged = "cataloged"
)
View Source
const (
	// MaxCatalogCommands bounds the entry count.
	MaxCatalogCommands = 512
	// MaxCatalogName bounds a command's name (without its leading `/`), bytes.
	MaxCatalogName = 96
	// MaxCatalogDescription bounds a description, in RUNES, cut on a rune
	// boundary with an ellipsis.
	MaxCatalogDescription = 200
	// MaxCatalogBytes bounds a whole catalog ENCODED. A count is not a size —
	// JSON writes `<` as <, six bytes — so the bound that keeps one answer
	// inside MaxFrame is this one: entries past it are dropped (Truncated), in
	// order. TestTheLargestCatalogFitsOneFrame measures it.
	MaxCatalogBytes = 256 << 10
)

The catalog's bounds. Each is a property of the wire, so both halves read them here.

View Source
const (
	SourceProject = "project"
	SourceUser    = "user"
	SourcePlugin  = "plugin"
	SourceBuiltin = "builtin"
)

The sources of a command (CatalogEntry.Source), in the order a NAME is claimed when two define it: a project's own command shadows the user's of the same name, the user's shadows a plugin's, and any of them a built-in.

View Source
const (
	KindCommand = "command"
	KindSkill   = "skill"
)

The kinds of a command (CatalogEntry.Kind).

View Source
const (
	// MaxQueued bounds the list: the OLDEST are kept, the next ones Claude
	// takes.
	MaxQueued = 20
	// MaxQueuedText bounds each message, in runes (CleanText): the view shows
	// a two-line preview, never the whole of a long message.
	MaxQueuedText = 500
)
View Source
const (
	// TypeAgentClones (muster → host): list the host's clones of
	// Msg.CloneRepo. ID is the request id (the stream id space).
	TypeAgentClones = "agent-clones"
	// TypeAgentClonesList (host → muster): its answer, Msg.Clones, or
	// Msg.Refusal (a Spawn* code) and Msg.Error.
	TypeAgentClonesList = "agent-clones-list"
)
View Source
const (
	// MaxClones bounds an agent-clones-list (the card offers each, beside its
	// "Don't start", within attention's MaxOptions).
	MaxClones = 8
	// MaxClonePath bounds a clone's path, in bytes (it is a card option, with
	// a short suffix, within attention's MaxOptionRunes).
	MaxClonePath = 160
)
View Source
const (
	// AskRefusalOpenCodeGone: the ask is no longer pending (answered in the
	// terminal, the turn ended). Nothing was answered.
	AskRefusalOpenCodeGone = "opencode-gone"
	// AskRefusalOpenCodeUnreachable: the host could not reach the opencode
	// server, or it refused the host's token. Nothing was answered.
	AskRefusalOpenCodeUnreachable = "opencode-unreachable"
	// AskRefusalOpenCodeUnknown: the answer was sent and no outcome came back.
	// It may have been answered.
	AskRefusalOpenCodeUnknown = "opencode-unknown"
	// AskRefusalOpenCodeRefused: opencode refused the answer itself (HTTP 400:
	// the field cannot take that value). Nothing was answered; it is still
	// pending.
	AskRefusalOpenCodeRefused = "opencode-refused"
)

The refusals a host names on answered for an opencode ask (Msg.Refusal).

View Source
const (
	// TypeOpenCodeForm (muster → host): send ask OpenCodeReply.PromptID's
	// form, of the opencode window (Session, Window).
	TypeOpenCodeForm = "opencode-form"
	// TypeOpenCodeFormed (host → muster): the answer to form request ID —
	// Form, or Error.
	TypeOpenCodeFormed = "opencode-formed"
)
View Source
const (
	MaxFormQuestions   = 8
	MaxFormOptions     = 10
	MaxFormKey         = 32
	MaxFormHeader      = 80
	MaxFormQuestion    = 600
	MaxFormLabel       = 200
	MaxFormDescription = 400
	// MaxFormOther bounds an answer of the person's own, in CHARACTERS
	// (runes): the card's box holds askq.MaxFreeText of them (its maxlength,
	// which counts UTF-16 units — never fewer than runes), so whatever the box
	// lets a person type, in any script, is taken here too.
	MaxFormOther = askq.MaxFreeText
)

The OpenCodeForm bounds: a form past them is not answered from muster (NormalizeOpenCodeForm refuses it whole, so an index the card shows is always the host's).

View Source
const (
	// TerminalOnlyNoClaude: nothing in the window's pane is a Claude Code
	// conversation this host could find — a shell, Codex, Gemini CLI, or a
	// Claude Code its host could not see (an older muster-mirror says no more).
	TerminalOnlyNoClaude = "muster found no Claude Code conversation in this window."
	// TerminalOnlyOldHost: the host's muster-mirror predates rendered views.
	TerminalOnlyOldHost = "This host's muster-mirror is too old to send the Rendered view. Update it to read Claude Code as a chat."
)

The Terminal view's line for an entry with no rendered view, when its host gave no reason of its own (TerminalOnlyReason).

View Source
const (
	KindClaudeCode = "Claude Code"
	KindOpenCode   = "opencode"
	KindShell      = "shell"
)

The kinds Kind names itself. Anything else it returns is the command.

View Source
const (
	MaxOutcomeLines   = 3
	MaxOutcomeLine    = 200
	MaxOutcomeWindows = 32
)

The WindowOutcome bounds: how many lines of a reply are sent, each line's bytes, and how many windows of one map carry one (TestTheLargestOutcomesMessageFitsOneFrame measures the worst case).

View Source
const (
	PendingPermission = "permission"
	PendingQuestion   = "question"
)

The opencode asks a Pending names (docs/design/opencode.md, "Asks"): a permission request, and a form its question tool raised. Only an opencode window's (RuntimeSpec.AskKinds).

View Source
const (
	// MaxPendingSummary bounds Pending.Summary, in runes.
	MaxPendingSummary = 120
	// MaxPendingTool bounds Pending.Tool, in runes.
	MaxPendingTool = 40
	// MaxPendingLast bounds Pending.Last, in runes.
	MaxPendingLast = 200
	// MaxPendingWindows bounds how many windows of ONE list carry a Pending.
	MaxPendingWindows = 8
	// MaxPendingDetail bounds Pending.Detail, in runes.
	MaxPendingDetail = 120
	// MaxPendingOptions bounds how many options an opencode question offers
	// in muster, and MaxPendingOption each one's runes. With Last and Detail
	// left off a question, its Pending is never larger on the wire than a
	// Claude window's at its bounds (TestAnOpenCodePendingIsNoLargerThanAClaudeOne),
	// so the frame bound measured for those holds (internal/mirrorhost's
	// TestTheLargestWindowListFitsOneFrame).
	MaxPendingOptions = 4
	MaxPendingOption  = 40
)

The Pending bounds.

View Source
const (
	// TypeSpawnResume (muster → host): start a window resuming Claude Code
	// session Msg.Gen. ID is the request id (the stream id space).
	TypeSpawnResume = "spawn-resume"
	// TypeResumeSpawned (host → muster): its outcome. Session and Window name
	// the new window; Error and Refusal say why not.
	TypeResumeSpawned = "resume-spawned"
)
View Source
const (
	// ResumeRefusalUnsupported: the host does not resume (no -resume-spawn, or
	// read-only).
	ResumeRefusalUnsupported = "unsupported"
	// ResumeRefusalNotHere: the host holds no transcript of that session. The
	// one refusal after which another host may be asked.
	ResumeRefusalNotHere = "not_here"
	// ResumeRefusalLive: the session is running on this host already.
	ResumeRefusalLive = "live"
	// ResumeRefusalNoCwd: the transcript names no usable working directory, or
	// it no longer exists.
	ResumeRefusalNoCwd = "no_cwd"
	// ResumeRefusalInvalid: not a session id this host accepts.
	ResumeRefusalInvalid = "invalid"
	// ResumeRefusalLimited: the host's own limit (a session resumed moments
	// ago, or too many this hour).
	ResumeRefusalLimited = "limited"
)

The kinds of refusal a host answers a spawn-resume with (Msg.Refusal).

View Source
const (
	// TokenRecheck is how often a live connection's token is re-read, so a
	// revoked token ends a connection (and its open terminals) that is already up.
	TokenRecheck = 30 * time.Second
	// RecheckFailClosedAfter is how many CONSECUTIVE failed rechecks (a database
	// error, not a revocation) end the connection. One is tolerated — a blip —
	// but a token that cannot be re-verified is not kept live indefinitely.
	RecheckFailClosedAfter = 2
)
View Source
const (
	// TypeSubagentTail (muster → host): send the recent steps of subagent
	// Msg.Agent of Session/Window's Claude Code session, by ID.
	TypeSubagentTail = "subagent-tail"
	// TypeSubagentTailed (host → muster): the answer to tail request ID —
	// Msg.Tail, or Msg.Error.
	TypeSubagentTailed = "subagent-tailed"
)
View Source
const (
	// MaxSubagents bounds one view's summary list: the newest (by their Agent
	// call's place in the transcript) are kept. Defined in
	// internal/ccsubagents (the leaf ccd links too), re-exported here.
	MaxSubagents = ccsubagents.MaxSubagents
	// MaxSubagentText bounds a summary's description, type and latest step, and
	// a tail step's text, in RUNES (CleanText).
	MaxSubagentText = 200
	// MaxSubagentTailSteps bounds a tail; the newest are kept.
	MaxSubagentTailSteps = 20
	// MaxSubagentListBytes and MaxSubagentTailBytes bound one message ENCODED,
	// for the reason MaxBatchBytes gives. TestTheLargestSubagentMessagesFitOneFrame
	// measures both at their field bounds.
	MaxSubagentListBytes = 256 << 10
	MaxSubagentTailBytes = 64 << 10
)

The subagent bounds. Each is a property of the wire, so both halves read it here.

View Source
const (
	SubagentRunning = ccsubagents.Running
	SubagentDone    = ccsubagents.Done
	SubagentFailed  = ccsubagents.Failed
)

The values of Subagent.State (ccsubagents', re-exported).

View Source
const (
	// TurnErrorLimit: a usage limit.
	TurnErrorLimit = "usage_limit"
	// TurnErrorOther: an error record that names no code.
	TurnErrorOther = "error"
)

The turn error kinds muster names; any other is the CLI's own code.

View Source
const (
	// QuickTurnMS is how soon after its prompt an error must end a turn to
	// count as an immediate failure (TurnError.Quick): measured 0.3–1.0 s from
	// prompt to limit row on real transcripts; a turn that ran longer did work.
	QuickTurnMS = 10_000
	// MaxTurnErrorQuick bounds TurnError.Quick (the host stops counting).
	MaxTurnErrorQuick = 20
	// MaxTurnErrorWindows bounds how many windows of ONE list carry a
	// TurnError.
	MaxTurnErrorWindows = 16
)

The TurnError bounds.

View Source
const (
	TypeHello    = "hello"
	TypeWelcome  = "welcome"
	TypeSessions = "sessions"
	TypeOpen     = "open"
	TypeResize   = "resize"
	TypeClose    = "close"
	TypeClosed   = "closed"

	// v2. muster → host: watch (open a transcript stream), paste. Host → muster:
	// events (a batch of one stream), pasted (a paste's outcome). A watch is
	// ended like a terminal — close / closed — and shares the stream id space.
	TypeWatch  = "watch"
	TypeEvents = "events"
	TypePaste  = "paste"
	TypePasted = "pasted"

	// Scrolling a pane's history (tmux copy-mode). muster → host: scroll. Host →
	// muster: scrolled (its outcome). Sent only to a host that advertised
	// Msg.PaneScroll — see that field for the compatibility.
	TypeScroll   = "scroll"
	TypeScrolled = "scrolled"

	// Answering an AskUserQuestion picker by keys (askanswer.go). muster →
	// host: answer (Msg.Ask). Host → muster: answered (its outcome, with
	// Msg.Refusal naming the kind of refusal). Sent only to a host that
	// advertised Msg.AskAnswer.
	TypeAnswer   = "answer"
	TypeAnswered = "answered"

	// Dismissing an AskUserQuestion picker (askcancel.go). muster → host:
	// cancel-ask — the window only (ID, Session, Window): it carries NO keys,
	// and the host's one response to it is a single Escape into that pane's
	// picker. Host → muster: ask-cancelled (its outcome: Msg.Refusal naming
	// the kind of refusal; on success, Msg.Text a note, "" for none). Sent
	// only to a host that advertised Msg.AskCancel.
	TypeCancelAsk    = "cancel-ask"
	TypeAskCancelled = "ask-cancelled"
)

Message types. Host → muster: hello, sessions, closed. muster → host: welcome, open, resize, close. Binary frames carry terminal bytes in both directions (see EncodeData).

View Source
const (
	MaxAgentNote        = 200
	MaxAgentNoteWindows = 8
)

The AgentNote bounds: a note's bytes, and how many windows of one list carry one (the frame budget: TestTheLargestWindowListFitsOneFrame).

View Source
const (
	MaxOtherClaudePerWindow = 4
	MaxOtherClaude          = 32
)

The OtherClaude bounds.

View Source
const (
	// StatusBusy: a turn is running.
	StatusBusy = "busy"
	// StatusIdle: no turn is running and nothing is being asked of the person.
	StatusIdle = "idle"
	// StatusWaiting: the session is waiting on the person (a permission prompt,
	// a question). Not idle: a message pasted now would answer the prompt.
	StatusWaiting = "waiting"
)

The values of Window.Status: Claude Code's own session status, as its sessions file spells it.

View Source
const (
	// MaxWatchesPerHost bounds the transcript streams open on one host.
	MaxWatchesPerHost = 8
	// MaxBatchEvents and MaxBatchBytes bound one events message: at most this
	// many events, and at most this many bytes of them ENCODED (Batches). Bytes,
	// not a count alone, because JSON escaping can inflate a capped field up to
	// six-fold (`<` is written \u003c), so a count bound alone could exceed
	// MaxFrame and end the whole connection.
	MaxBatchEvents = 64
	MaxBatchBytes  = 256 << 10
	// MaxBackfillEvents bounds a fresh view's history; BackfillWindow is the
	// tail of the transcript file it is read from. The file is never sent
	// wholesale: a viewer gets the recent conversation, not tens of MiB.
	MaxBackfillEvents = 300
	BackfillWindow    = ccsubagents.BackfillWindow // defined in the leaf ccd links too
	// MaxPaste bounds a paste's text.
	MaxPaste = 16 << 10
	// MaxIndexPrompts and MaxIndexBytes bound a prompt index (Msg.Prompts): at
	// most this many prompts, at most this many bytes of them ENCODED — the
	// count alone could not keep a message inside MaxFrame, for the reason
	// MaxBatchBytes gives. The newest are kept (BoundPrompts).
	MaxIndexPrompts = 2000
	MaxIndexBytes   = 512 << 10
	// MaxScrollLines bounds one scroll request either way: a page coalesces a
	// drag into one request per animation frame, and a frame's worth of a fast
	// fling is tens of lines, not hundreds.
	MaxScrollLines = 200
)

The v2 bounds. Each is a property of the wire, so both halves read it here.

View Source
const (
	// ScrollRefusalMode: the pane is in a mode other than copy-mode at the top
	// of its stack (a tmux menu, choose-tree, view-mode): nothing scrolls until
	// it is closed. The pane can scroll again later.
	ScrollRefusalMode = "mode"
	// ScrollRefusalUnsupported: this host cannot scroll a pane at all (read-only,
	// or its backend has no copy-mode). The only refusal that means "stop asking".
	ScrollRefusalUnsupported = "unsupported"
)

The kinds of scroll refusal a host names (Msg.Refusal).

View Source
const (
	// PasteRefusalMultiplexer: the pane's process tree holds a terminal
	// multiplexer client (tmux, screen, dtach, abduco, zellij), which can hide
	// an agent the host cannot see. Nothing was typed.
	PasteRefusalMultiplexer = "multiplexer"
	// PasteRefusalUnchecked: the host could not read the pane's processes, so
	// it could not rule out an agent it does not type into. Nothing was typed.
	PasteRefusalUnchecked = "unchecked"
	// PasteRefusalOpenCode: the pane's process tree holds opencode. muster
	// never types into opencode (its send goes through opencode's own API, the
	// gated send, from the Rendered view), so the host types nothing into such
	// a pane. Nothing was typed.
	PasteRefusalOpenCode = "opencode"
	// PasteRefusalClaudeWaiting: the Claude prompt guard — the Claude Code
	// pane is waiting on the person (its session status is waiting, or its
	// screen shows a permission prompt, a picker or a select menu), or the host
	// could not read its screen to rule that out. Enter there would ANSWER the
	// dialog. Nothing was typed, so a queued message is decided on again
	// (Hub.PasteWindow turns it into ErrSuperseded) and held until it clears.
	PasteRefusalClaudeWaiting = "claude-waiting"
	// PasteRefusalClaudePasted: the Claude prompt guard's check before the
	// Enter refused — a dialog opened (or the pane changed) between the paste
	// and its Enter — so the text is in Claude Code's input box and Enter was
	// withheld. Not to be resent blindly: that would paste it twice.
	PasteRefusalClaudePasted = "claude-pasted"
	// PasteRefusalClaudeBox: the Claude prompt guard — Claude Code's input
	// box already holds text (a message left there unsubmitted, say), which
	// this one would be pasted after and submitted with as one turn. Nothing
	// was typed; a queued message is held, as for PasteRefusalClaudeWaiting.
	PasteRefusalClaudeBox = "claude-box"
	// The opencode gated send's refusals (docs/design/opencode-first-class.md).
	// Nothing was sent to opencode, except for PasteRefusalOpenCodeUnconfirmed.
	//
	// PasteRefusalOpenCodeOff: the host does not send to opencode (no
	// -interactive, no -opencode-send or no token).
	PasteRefusalOpenCodeOff = "opencode-off"
	// PasteRefusalOpenCodeUnbound: the window's pane was not started by the
	// launcher, so the host cannot say which session it shows.
	PasteRefusalOpenCodeUnbound = "opencode-unbound"
	// PasteRefusalOpenCodeNotIdle: the session is not idle since the status
	// muster decided on (busy, waiting on an ask, or newer). A queued message is
	// decided on again (Hub.PasteWindow turns it into ErrSuperseded).
	PasteRefusalOpenCodeNotIdle = "opencode-not-idle"
	// PasteRefusalOpenCodeSlash: the message starts with one of opencode's
	// slash commands, which a prompt would hand the model as text.
	PasteRefusalOpenCodeSlash = "opencode-slash"
	// PasteRefusalOpenCodeGone: opencode has no such session any more.
	PasteRefusalOpenCodeGone = "opencode-gone"
	// PasteRefusalOpenCodeConflict: opencode holds the message's id in
	// another session (409) — a Send again after the pane was started on
	// another session. muster forgets that first try, so the next send is a
	// new message.
	PasteRefusalOpenCodeConflict = "opencode-conflict"
	// PasteRefusalOpenCodeMoved: the pane resolves now to another session
	// than the one the paste named (Msg.AgentSession), or a pane bound by
	// verification was sent a paste naming none.
	PasteRefusalOpenCodeMoved = "opencode-moved"
	// PasteRefusalOpenCodeUnconfirmed: the host posted the message and heard
	// no answer: it MAY have been admitted (muster reads it as
	// ErrPasteUnconfirmed).
	PasteRefusalOpenCodeUnconfirmed = "opencode-unconfirmed"
)

The kinds of paste refusal a host names (Msg.Refusal on pasted): the host paste guard's (mirrorhost's paneguard.go). An older host names none — or a kind muster no longer knows (an older host's "hermes…" kinds) — and muster then shows the host's prose as a plain refusal.

View Source
const (
	PasteRefusedMultiplexerText = "Not sent: this pane runs another terminal multiplexer (tmux, screen, dtach, " +
		"abduco or zellij), so muster cannot see what runs inside it. Type it in the terminal."
	PasteRefusedUncheckedText = "Not sent: muster-mirror could not check what runs in this pane. " +
		"Type it in the terminal."
	PasteRefusedOpenCodeText = "Not sent from here: opencode runs in this pane, and muster never types into it, " +
		"because Enter there can answer a prompt opencode is showing, such as a permission request. Send it from " +
		"the session's Rendered view (when it was started with `muster-mirror opencode`), or type it in the terminal."
	// The opencode gated send's refusals, in the person's words.
	PasteRefusedOpenCodeOffText = "Not sent: this host's muster-mirror does not send to opencode " +
		"(it needs -interactive and -opencode-send). Type it in the terminal."
	PasteRefusedOpenCodeUnboundText = "Not sent: muster can't be sure which session this opencode shows, " +
		"because it wasn't started with `muster-mirror opencode`. Type it in the terminal, or restart it that way."
	PasteRefusedOpenCodeBusyText    = "Not sent: opencode is working. Queue it instead."
	PasteRefusedOpenCodeWaitingText = "Not sent: opencode is waiting for you (a permission request or a question). Answer it first."
	PasteRefusedOpenCodeUnknownText = "Not sent: muster cannot tell whether opencode is idle right now. Try again in a moment."
	PasteRefusedOpenCodeSlashText   = "Not sent: that is an opencode slash command, and muster cannot run opencode's " +
		"commands yet (sent as a message, the model would read it as text). Type it in the terminal."
	PasteRefusedOpenCodeGoneText     = "Not sent: that opencode session no longer exists."
	PasteRefusedOpenCodeConflictText = "Not sent: opencode already has this message in another session " +
		"(the pane was started on another session since the first try). Send it again to send it as a new message."
	// The Claude prompt guard's refusals (PasteRefusalClaudeWaiting): its
	// session says it is waiting on the person; its screen shows a dialog; its
	// screen could not be read.
	ClaudeWaitingText = "Not sent: Claude is waiting on a permission prompt — answer it first. " +
		"Nothing was typed into the pane."
	ClaudeDialogText = "Not sent: Claude Code's pane shows a dialog (a permission prompt, a question or a menu) — " +
		"answer it first. Nothing was typed into the pane."
	ClaudeScreenUnreadText = "Not sent: muster-mirror could not read Claude Code's screen, so it could not rule out " +
		"a permission prompt. Nothing was typed into the pane."
	// ClaudeBoxText (PasteRefusalClaudeBox): the input box holds text.
	ClaudeBoxText = "Not sent: Claude's input box already has text — clear or send it first. Nothing was typed into the pane."
	// ClaudeBoxUnreadText (PasteRefusalClaudeWaiting): the screen shows no
	// input box muster-mirror can read, so it cannot tell the box is empty.
	ClaudeBoxUnreadText = "Not sent: muster-mirror could not find Claude Code's input box on its screen, so it could not " +
		"tell whether it is empty. Nothing was typed into the pane."
)

The texts of the paste guard's refusals, for the person sending: the host sends them as its reason, and muster shows the same words when the page posted without script (one source, so the two paths cannot drift).

View Source
const (
	// AskRefusalNoPicker: the question's picker is not on screen — answered
	// or dismissed in the terminal already.
	AskRefusalNoPicker = "no-picker"
	// AskRefusalTouched: the picker shows the question but someone has started
	// answering it in the terminal.
	AskRefusalTouched = "touched"
	// AskRefusalLost: typing stopped mid-way (the picker changed under it);
	// nothing was submitted.
	AskRefusalLost = "lost"
	// AskRefusalUnsupported: this host cannot type answers at all.
	AskRefusalUnsupported = "unsupported"
	// AskRefusalUnrecognised: the pane shows something like the picker that
	// the host cannot read — Claude Code's layout has probably changed.
	AskRefusalUnrecognised = "unrecognised"
	// AskRefusalBusy: another answer is being typed into that pane.
	AskRefusalBusy = "busy"
	// AskRefusalUnreadable: the host could not read the question off the
	// screen as the one muster registered (the picker untouched, its question
	// in other words; or the picker taller than the pane) — nobody is
	// answering it in the terminal. Nothing was typed.
	AskRefusalUnreadable = "unreadable"
	// AskRefusalUnreadableTyped: as AskRefusalUnreadable, but keys were typed
	// before the picker went out of reading (off the top of the pane); nothing
	// was submitted.
	AskRefusalUnreadableTyped = "unreadable-typed"
)

The kinds of answer refusal a host names (Msg.Refusal on answered).

View Source
const ActivityBucket = 60

ActivityBucket is the granularity of Msg.Activity, in seconds. A session's activity is carried and compared floored to it.

🔴 IT IS THE RE-SEND AND RE-ORDER POLICY, NOT A ROUNDING NICETY. A busy pane's raw activity time moves every second; sent raw, every refresh would differ, every one would be re-sent, and two busy sessions would swap places in the sidebar each time. Floored, a host's map changes at most once per bucket per session, sessions active within the same bucket TIE (and keep their name order), and the list reorders only when a session falls a whole bucket behind another.

View Source
const AgentCloseGrace = 30 * time.Second

AgentCloseGrace is how long a host waits for the agent to exit on its own before it closes the window anyway (operator decision: ~30 s).

View Source
const AgentSpawnSession = "agents"

AgentSpawnSession is the tmux session every spawned agent's window opens in.

View Source
const AskScreenCutMark = "[… the top of the pane was cut]\n"

AskScreenCutMark begins a screen CapAskScreen cut.

View Source
const ClaudeStatusShell = "shell"

ClaudeStatusShell is what Claude Code's sessions file says INSTEAD of idle while a background shell (a run_in_background Bash task) is still running and no turn is (measured in Claude Code 2.1.289: an idle status with a live local_bash task is written as "shell"). The prompt is free and takes input exactly as when idle, so NormalizeStatus reads it as StatusIdle. Its statusUpdatedAt is a real status time: a turn that ends with a background shell still running writes "shell" with a newer time, which is what the send queue's "newer than the paste" rule waits for.

View Source
const ConnectPath = "/mirror/connect"

ConnectPath is the route a host's muster-mirror dials.

View Source
const DispatchOption = "@muster-dispatch"

DispatchOption is the tmux WINDOW option that names a spawned window's host dispatch (Window.Dispatch). A constant: nothing from outside the binary names another.

View Source
const LiveCopyShortID = 8

LiveCopyShortID is how many leading characters of the other session's id the warning shows: enough to tell it from the window's own, and to find it with `claude --resume`'s picker.

View Source
const MaxAskScreen = 16 << 10

MaxAskScreen bounds the pane a host sends with a refusal (Msg.Screen), in bytes: the bottom of the pane, where the picker is, is kept.

View Source
const MaxCommand = 32

MaxCommand bounds Window.Command, in bytes.

View Source
const MaxContextModel = 96

MaxContextModel bounds AgentContext.Model, in bytes.

View Source
const MaxFrame = 1 << 20

MaxFrame bounds one WebSocket message in either direction. A pty read is at most a few KiB; a control message is a session list. Both ends set it as the read limit (coder/websocket defaults to 32 KiB, which a burst of terminal output can exceed).

View Source
const MaxHosts = 64

MaxHosts bounds the hosts connected to one muster at once (all owners).

View Source
const MaxLabel = 64

MaxLabel bounds a session's display label (Msg.Labels), in bytes.

View Source
const MaxLiveCopyWindows = 8

MaxLiveCopyWindows bounds how many windows of ONE list carry a LiveCopy (the frame budget: TestTheLargestWindowListFitsOneFrame).

View Source
const MaxPreviewCount = 99

MaxPreviewCount bounds each count. The host's own limits are far below it (maxOpen ≤ 32; the allowlist's listeners in one window); it only bounds what a host can make muster draw.

View Source
const MaxRepoName = 64

MaxRepoName bounds one repo name, in bytes (cut on a rune boundary).

View Source
const MaxSessions = 64

MaxSessions bounds the SESSION list a per-session host may register (a muster-mirror from before per-window registration; Msg.Sessions). A host with more is truncated to this many, sorted, so the set is stable between refreshes. A per-window host is bounded by MaxWindows instead.

View Source
const MaxSpawnModel = 128

MaxSpawnModel bounds an OpenRouter model id, in bytes.

View Source
const MaxStreamsPerHost = 8

MaxStreamsPerHost bounds the terminals open on one host at once.

View Source
const MaxWindows = 512

MaxWindows bounds the WINDOW list one host may register (Msg.Windows). A host with more is truncated to this many in (session, index) order, so the set is stable between refreshes.

🔴 IT REPLACES MaxSessions FOR A PER-WINDOW HOST, AND THE NUMBER IS A DECISION: one entry per tmux WINDOW is several times one per session (an operator runs one coding agent per window), and 64 was already exceeded by a real host. 512 leaves that host room to grow several-fold.

🔴 IT IS ALSO A SIZE, AND THE SIZE IS WHAT CAPS IT. The whole list travels in ONE message, and a message over MaxFrame ends the connection. A count is not a size — JSON writes some bytes six-fold (`<` is \u003c) — so the bound that matters is the WORST-CASE encoding of MaxWindows entries, each field at its own limit, beside the per-session fields at theirs: it must stay within MaxFrame. TestTheLargestWindowListFitsOneFrame measures that, so raising this number (or a field's limit) past what fits fails there rather than on a host with many windows.

View Source
const MaxWorkCount = 99

MaxWorkCount bounds each count; the card shows "99+" at it.

View Source
const MinProtocolVersion = 1

MinProtocolVersion is the oldest host version this muster accepts.

View Source
const OpenCodeSessionMeta = "ai.opencode/sessionID"

OpenCodeSessionMeta is the key opencode puts the calling session's id under in every tools/call's params._meta (packages/core/src/mcp/client.ts at 6ec5682): the one per-session signal it sends.

View Source
const PasteRefusalNotMusterWindow = "not_muster_window"

PasteRefusalNotMusterWindow: a paste naming a dispatch reached a window whose own tag names another, or none. Nothing was typed.

View Source
const ProtocolVersion = 2

ProtocolVersion is the newest tunnel version this side speaks.

  • 1: session names, terminals.
  • 2: adds the RENDERED VIEW — which sessions' panes run Claude Code (Msg.Claude), a transcript stream per open view (watch / events), and pasting a message into such a pane (paste / pasted).

🔴 THE BUMP IS BACKWARD-COMPATIBLE IN BOTH DIRECTIONS, because hosts and the server upgrade at different times:

  • a v2 muster accepts a v1 host (MinProtocolVersion) and speaks v1 to it: its sessions are listed and attachable exactly as before, with no rendered view (nothing v2 is ever sent to it);
  • a v2 host that reaches a v1 muster is refused with that muster's version error, and retries AT ONCE as v1 (mirrorhost.Client) rather than staying offline until muster is upgraded.

Anything else outside [MinProtocolVersion, ProtocolVersion] is refused, so a genuinely skewed pair still fails loudly at connect rather than mid-attach.

View Source
const QualifierSep = " · "

QualifierSep joins a Title and its Qualifier: "mango:1 · laptop".

View Source
const (
	// RuntimeClaude: Claude Code. On the wire it is Window.Claude, never
	// Window.Runtime.
	RuntimeClaude = "claude"
)

The agent runtimes a window can run (Window.AgentRuntime). What muster knows of each is its RuntimeSpec (runtime.go); RuntimeOpenCode is there.

View Source
const RuntimeOpenCode = "opencode"

RuntimeOpenCode: opencode v2 (docs/design/opencode.md). A host whose pane runs an opencode TUI names the session the pane's launcher record names, or else the one its title matches (Window.AgentSession), and muster draws its rendered view from the opencode server's API. A message reaches it only through opencode's API (GatedSend, docs/design/opencode-first-class.md): on a host that advertised it (Msg.OpenCodeSend), to a launcher-bound window (Window.AgentSend), while it is idle — never as keys (the host's paste guard still refuses its panes). What it WAITS ON reaches muster (Caps.Prompts): a permission request or a question-tool form of its session (or of a subagent's child session) makes the window waiting, its Pending naming the ask (PendingPermission, PendingQuestion) — and a host that advertised it (Msg.OpenCodeAnswer: an -interactive host with an opencode token) relays an answer through opencode's API (Hub.AnswerOpenCodeAsk), never keys.

View Source
const SpawnModelProvider = "openrouter"

SpawnModelProvider is the opencode provider id a spawn's model is run under: measured on opencode v2.0.32+6ec5682, OpenRouter's models are listed under providerID "openrouter" (GET /api/model).

View Source
const SpawnPreface = "muster: your owner's chief started you"

SpawnPreface is how every prompt muster sends a spawned agent BEGINS.

🔴 IT IS LOAD-BEARING ON THE HOST, NOT DECORATION. Claude Code parses a positional word that equals a subcommand name (`update`, `mcp`, `doctor`) as that subcommand EVEN AFTER `--`: measured on 2.1.289, `claude --session-id <uuid> -- update` ran the updater (docs/design/chief-dispatch.md 7). So the host refuses any prompt that does not begin with this text, which is never a subcommand name and never begins with '-'.

View Source
const TokenPrefix = "mmt_"

TokenPrefix starts every mirror token. It is how an operator (and a leak scanner) recognises one, and how muster-mirror refuses a pasted credential that is plainly something else — the hook token or an agent's token.

View Source
const TypeColors = "colors"

TypeColors is the host → muster message carrying Msg.Colors.

View Source
const TypeOutcomes = "outcomes"

TypeOutcomes is the host → muster message carrying Msg.Outcomes.

View Source
const TypePreviews = "previews"

TypePreviews is the host → muster message carrying Msg.Previews.

View Source
const TypeRepos = "repos"

TypeRepos is the host → muster message carrying Msg.Repos.

View Source
const TypeWork = "work"

TypeWork is the host → muster message carrying Msg.Work.

View Source
const V1RefusalPrefix = "mirror: this muster speaks tunnel version 1 and the host sent "

V1RefusalPrefix is how a v1 muster's refusal of a newer host begins — its readHello error, frozen in every v1 build. A v2 host that sees it falls back to v1. (A v2 muster never sends it for a version it accepts.)

View Source
const ViewSessionPrefix = "muster-view-"

ViewSessionPrefix starts the name of every tmux session muster-mirror itself creates: the short-lived session a terminal viewer attaches to, holding a link to the one window it shows, so that viewing a window never moves the operator's own current window (internal/mirrorhost). Such a session is never registered, on either side.

Variables

View Source
var (
	// ErrCloseUnsupported: the host did not advertise agent-close.
	ErrCloseUnsupported = errors.New("mirror: this host's muster-mirror does not close windows (it needs -interactive and a current muster-mirror)")
	// ErrCloseUnconfirmed: the host did not answer in time; the window may be closing.
	ErrCloseUnconfirmed = errors.New("mirror: the host did not answer the close in time; the window may still be closing")
)
View Source
var (
	// ErrSpawnUnsupported: the host did not advertise the runtime.
	ErrSpawnUnsupported = errors.New("mirror: this host's muster-mirror does not start that runtime (it needs -interactive and -agent-spawn)")
	// ErrSpawnUnconfirmed: the host did not answer in time. The request was
	// written, so the window may exist: a late reply still lands
	// (SetSpawnReplyNotify), and nothing may treat this as a failure.
	ErrSpawnUnconfirmed = errors.New("mirror: the host did not answer the spawn in time; it may still have started the agent")
)
View Source
var (
	// ErrNoStatusReport: the host's muster-mirror does not report whether
	// Claude Code is busy.
	ErrNoStatusReport = errors.New("mirror: this host's muster-mirror does not report whether Claude Code is busy (it predates the send queue), so nothing queued for it is sent; upgrade it, or send by hand")
	// ErrNoStatus: the window runs Claude Code and the host cannot read its
	// status (its sessions file is missing or names no status).
	ErrNoStatus = errors.New("mirror: the host cannot read whether this window's Claude Code session is busy, so nothing queued for it is sent")
	// ErrNoStatusSince: the host reports the status but not when Claude Code
	// wrote it (an older muster-mirror, or a Claude Code whose sessions file has
	// no statusUpdatedAt). Without it a turn cannot be told from no turn.
	ErrNoStatusSince = errors.New("mirror: the host does not report since when this window's Claude Code session has been idle, so nothing queued for it is sent; upgrade muster-mirror (or Claude Code), or send by hand")
)
View Source
var (
	// ErrAskUnsupported: the host cannot type answers (an older or read-only
	// muster-mirror).
	ErrAskUnsupported = errors.New("mirror: this host's muster-mirror cannot type an answer into the terminal; update it (and start it with -interactive)")
	// ErrAskNoPicker: the question's picker is not on screen (answered or
	// dismissed in the terminal already).
	ErrAskNoPicker = errors.New("mirror: the question is no longer on the terminal's screen")
	// ErrAskTouched: someone is answering the question in the terminal.
	ErrAskTouched = errors.New("mirror: someone is answering this question in the terminal")
	// ErrAskLost: the picker changed while the answer was being typed; nothing
	// was submitted.
	ErrAskLost = errors.New("mirror: the terminal's picker changed while the answer was being typed, so it was not submitted")
	// ErrAskRefused wraps any other refusal by the host.
	ErrAskRefused = errors.New("mirror: the host could not type the answer in")
	// ErrAskTimeout: the host did not answer in time.
	ErrAskTimeout = errors.New("mirror: the host did not report the answer in time")
	// ErrAskUnrecognised: the host could not read the terminal's picker —
	// Claude Code's layout has probably changed. Nothing was typed.
	ErrAskUnrecognised = errors.New("mirror: the host could not recognise the terminal's picker (Claude Code may have changed)")
	// ErrAskBusy: another answer is being typed into that terminal. Nothing
	// was typed.
	ErrAskBusy = errors.New("mirror: another answer is being typed into that terminal")
	// ErrAskUnreadable: the host could not read the question off the
	// terminal's screen as the one muster registered — NOT someone answering
	// it there. Alone, nothing was typed; with ErrAskLost, keys were typed
	// before it went out of reading and nothing was submitted.
	ErrAskUnreadable = errors.New("mirror: the host could not read this question off the terminal's screen")
	// ErrAskNotSent wraps an AnswerWindow error from BEFORE the answer was
	// sent to the host: nothing can be being typed.
	ErrAskNotSent = errors.New("mirror: the answer was not sent to the host")
)
View Source
var (
	// ErrCatalogUnsupported: the host did not advertise a catalog (an older
	// muster-mirror). The composer then offers the built-ins alone.
	ErrCatalogUnsupported = errors.New("mirror: this host's muster-mirror does not report its commands or skills; upgrade it")
	// ErrCatalogRefused wraps the host's own reason for not answering.
	ErrCatalogRefused = errors.New("mirror: the host did not send its catalog")
	// ErrCatalogTimeout: the host did not answer in time.
	ErrCatalogTimeout = errors.New("mirror: the host did not send its catalog in time")
)

The catalog refusals.

View Source
var (
	// ErrClonesUnsupported: the host did not advertise AgentSpawnClones.
	ErrClonesUnsupported = errors.New("mirror: this host's muster-mirror does not list its clones")
	// ErrClonesUnanswered: the host did not answer in time.
	ErrClonesUnanswered = errors.New("mirror: the host did not list its clones in time")
)
View Source
var (
	// ErrHostOffline: the host's muster-mirror is not connected.
	ErrHostOffline = errors.New("mirror: the host is offline — its muster-mirror is not connected to muster")
	// ErrSessionGone: the host is connected and does not list the session.
	ErrSessionGone = errors.New("mirror: the host is online but no longer lists this tmux session")
	// ErrWindowGone: the host lists the session, and not this window of it (the
	// window was closed, or the host registers per session and has no windows
	// to name).
	ErrWindowGone = errors.New("mirror: the host is online but no longer lists this tmux window")
	// ErrHostDisconnected: the host's connection ended while attached (it went
	// away, its token was revoked, or a newer connection replaced it).
	ErrHostDisconnected = errors.New("mirror: the host's connection ended while the terminal was attached")
	// ErrOverrun: the browser could not keep up with the terminal's output.
	ErrOverrun = errors.New("mirror: the terminal produced output faster than the browser read it; reconnect to resume")
	// ErrInteractiveRefused: the host did not advertise interactive attaches.
	ErrInteractiveRefused = errors.New("mirror: this host is read-only — its muster-mirror was not started with -interactive")
	// ErrTooManyStreams: the host already has MaxStreamsPerHost terminals open.
	ErrTooManyStreams = fmt.Errorf("mirror: this host already has %d terminals open; close one first — a view left open in another tab or window may hold one: close that window", MaxStreamsPerHost)
	// ErrTooManyHosts: the hub already holds MaxHosts connected hosts.
	ErrTooManyHosts = fmt.Errorf("mirror: muster already has %d mirror hosts connected", MaxHosts)
)

The attach refusals. Each carries its own remedy, so internal/api passes the text to the browser verbatim.

View Source
var (
	// ErrOpenCodeAnswerUnsupported: the host does not relay answers to opencode
	// (an older or read-only muster-mirror, or one with no opencode token).
	ErrOpenCodeAnswerUnsupported = errors.New("mirror: this host's muster-mirror does not relay answers to opencode (it needs -interactive); answer it in the terminal")
	// ErrOpenCodeAskGone: the window is no longer waiting on that ask, or not
	// offering that answer. Nothing was answered.
	ErrOpenCodeAskGone = errors.New("mirror: opencode is no longer waiting on that")
	// ErrOpenCodeUnreachable: the host could not reach the opencode server.
	// Nothing was answered.
	ErrOpenCodeUnreachable = errors.New("mirror: the host could not reach its opencode server; answer it in the terminal")
	// ErrOpenCodeAnswerUnknown: the answer was sent and no outcome came back in
	// time. It may have been answered: check the terminal.
	ErrOpenCodeAnswerUnknown = errors.New("mirror: muster sent the answer but did not hear back; it may have been answered — check the terminal")
	// ErrOpenCodeAnswerRefused: opencode refused the answer (the field cannot
	// take that value). Nothing was answered; the ask is still pending.
	ErrOpenCodeAnswerRefused = errors.New("mirror: opencode refused that answer; nothing was answered")
)
View Source
var (
	// ErrOpenCodeFormsUnsupported: the host does not send opencode forms (an
	// older or read-only muster-mirror, or one with no opencode token).
	ErrOpenCodeFormsUnsupported = errors.New("mirror: this host's muster-mirror cannot show this opencode question here; answer it in the terminal")
	// ErrOpenCodeFormTimeout: the host did not send the form in time.
	ErrOpenCodeFormTimeout = errors.New("mirror: the host did not send the opencode question in time")
)
View Source
var (
	// ErrOpenCodeSendOff: the window runs opencode and its host did not
	// advertise Msg.OpenCodeSend. Nothing was sent.
	ErrOpenCodeSendOff = errors.New("mirror: muster did not send it: this window runs opencode, and its host's muster-mirror does not send to opencode")
	// ErrOpenCodeUnbound: the window runs opencode but its host does not send
	// to it (not started by the launcher). Nothing was sent.
	ErrOpenCodeUnbound = errors.New("mirror: muster did not send it: this opencode window was not started by `muster-mirror opencode`")
	// ErrOpenCodeNotIdle is the cause of every *OpenCodeNotIdleError.
	ErrOpenCodeNotIdle = errors.New("mirror: muster did not send it: the opencode session is not idle")
)
View Source
var (
	// ErrResumeUnsupported: the host did not advertise Msg.ResumeSpawn.
	ErrResumeUnsupported = errors.New("mirror: this host's muster-mirror does not resume sessions (it needs -interactive and -resume-spawn)")
	// ErrResumeRefused wraps the host's own reason; ResumeRefusal reads its kind.
	ErrResumeRefused = errors.New("mirror: the host refused to resume the session")
	// ErrResumeTimeout: the host did not answer in time.
	ErrResumeTimeout = errors.New("mirror: the host did not answer the resume in time")
)
View Source
var (
	// ErrScrollUnsupported: the host did not advertise copy-mode scrolling (an
	// older muster-mirror, or a read-only host).
	ErrScrollUnsupported = errors.New("mirror: this host's muster-mirror cannot scroll a pane's history; upgrade it (and start it with -interactive)")
	// ErrScrollRefused wraps the host's own reason for refusing a scroll.
	ErrScrollRefused = errors.New("mirror: the host refused the scroll")
	// ErrScrollPaneInMode: the host refused because the pane is in another
	// tmux mode (a menu, choose-tree, view-mode) — Msg.Refusal
	// ScrollRefusalMode. Unlike ErrScrollUnsupported it passes: the pane
	// scrolls again once that mode is closed.
	ErrScrollPaneInMode = errors.New("mirror: the pane is in another mode (e.g. a tmux menu)")
	// ErrScrollTimeout: the host did not answer a scroll in time.
	ErrScrollTimeout = errors.New("mirror: the host did not answer the scroll in time")
	// ErrBadScroll: a line count ClampScroll refuses (0).
	ErrBadScroll = errors.New("mirror: a scroll must move at least one line")
)
View Source
var (
	// ErrSubagentsUnsupported: the host's muster-mirror predates the subagent
	// cards (no Msg.SubagentReport in its hello).
	ErrSubagentsUnsupported = errors.New("mirror: this host's muster-mirror does not report subagents; upgrade it")
	// ErrSubagentTailRefused wraps the host's own reason for refusing a tail.
	ErrSubagentTailRefused = errors.New("mirror: the host refused the subagent's steps")
	// ErrSubagentTailTimeout: the host did not answer in time.
	ErrSubagentTailTimeout = errors.New("mirror: the host did not send the subagent's steps in time")
	// ErrBadSubagent: the agent id is not one the wire carries.
	ErrBadSubagent = errors.New("mirror: not a subagent id")
)
View Source
var (
	// ErrNoRenderedView: the host speaks tunnel v1, which carries no transcript.
	ErrNoRenderedView = errors.New("mirror: this host's muster-mirror predates the rendered view (tunnel v1); upgrade it, or use the Terminal")
	// ErrNotClaude: the host does not report Claude Code in the session's pane.
	ErrNotClaude = errors.New("mirror: the host reports no Claude Code session in this tmux session's pane")
	// ErrTooManyWatches: the host already has MaxWatchesPerHost views open.
	ErrTooManyWatches = fmt.Errorf("mirror: this host already has %d rendered views open; close one first — a view left open in another tab or window may hold one: close that window", MaxWatchesPerHost)
	// ErrViewOverrun: the browser fell streamBuffer batches behind a view.
	ErrViewOverrun = errors.New("mirror: the transcript arrived faster than the browser read it; reconnect to resume")
	// ErrPasteTimeout: the host did not confirm a paste in time.
	ErrPasteTimeout = errors.New("mirror: the host did not confirm the message in time")
	// ErrPasteRefused wraps the host's own reason for refusing a paste.
	ErrPasteRefused = errors.New("mirror: the host refused the message")
	// ErrPanePasteUnsupported: the session's pane does not run Claude Code and
	// the host's muster-mirror predates pasting into any other pane.
	ErrPanePasteUnsupported = errors.New("mirror: this host's muster-mirror can only send to a Claude Code pane; upgrade it to send into this session, or use the Interactive terminal")
	// ErrBadPaste: a message SanitizePaste refuses (empty, oversized, or
	// carrying a control character).
	ErrBadPaste = errors.New("mirror: the message cannot be pasted")
)
View Source
var BuiltinCommands = []CatalogEntry{
	builtin("add-dir", "Add a new working directory"),
	builtin("background", "Send this session to the background and free the terminal"),
	builtin("branch", "Create a branch of the current conversation at this point"),
	builtin("btw", "Ask a quick side question without interrupting the main conversation"),
	builtin("cd", "Move this session to a new working directory"),
	builtin("clear", "Start a new session with empty context; previous session stays on disk (resumable with /resume)"),
	builtin("compact", "Free up context by summarizing the conversation so far"),
	builtin("config", "Open settings"),
	builtin("context", "Visualize current context usage as a colored grid"),
	builtin("copy", "Copy Claude's last response to clipboard (or /copy N for the Nth-latest)"),
	builtin("diff", "Toggle the diff panel showing uncommitted changes"),
	builtin("effort", "Set effort level for model usage"),
	builtin("fast", "Toggle fast mode"),
	builtin("export", "Export the current conversation to a file or clipboard"),
	builtin("fork", "Copy this conversation into a new background session and keep working here"),
	builtin("goal", "Set a goal Claude checks before stopping"),
	builtin("help", "Show help and available commands"),
	builtin("hooks", "View hook configurations for tool events"),
	builtin("init", "Initialize a new CLAUDE.md file with codebase documentation"),
	builtin("mcp", "Manage MCP servers"),
	builtin("memory", "Edit CLAUDE.md files and memory settings"),
	builtin("model", "Set the AI model for Claude Code"),
	builtin("output-style", "List output styles or switch to one"),
	builtin("permissions", "Manage allow and deny tool permission rules"),
	builtin("plan", "Enable plan mode or view the current session plan"),
	builtin("plugin", "Manage Claude Code plugins"),
	builtin("recap", "Generate a one-line session recap now"),
	builtin("release-notes", "View release notes"),
	builtin("reload-plugins", "Activate pending plugin changes in the current session"),
	builtin("reload-skills", "Pick up skills added or changed on disk during this session"),
	builtin("rename", "Rename the current conversation"),
	builtin("resume", "Resume a previous conversation"),
	builtin("rewind", "Restore the code and/or conversation to a previous point"),
	builtin("security-review", "Complete a security review of the pending changes on the current branch"),
	builtin("skills", "List available skills"),
	builtin("subtask", "Send a subagent off with your full context; its result comes back here"),
	builtin("status", "Show Claude Code status including version, model, account, API connectivity, and tool statuses"),
	builtin("tasks", "View and manage everything running in the background"),
	builtin("usage", "Show session cost, plan usage, and activity stats"),
}

BuiltinCommands are the Claude Code built-in commands the composer offers on every window, whatever its host reports — the whole menu for a host whose muster-mirror predates the catalog. Names and descriptions as Claude Code 2.1.289's own `/` menu lists them (/init and /security-review are its bundled skills, listed in the same menu).

⚠ DELIBERATELY NOT ALL OF THEM. Left out: what ends or signs out the session in the pane (/exit, /logout, /login), and what only makes sense at the machine's own terminal or account page (/terminal-setup, /ide, /chrome, /keybindings, /mobile, /install-github-app, /install-slack-app, /upgrade, /passes, /stickers, /radio). Anything typed by hand is still sent as typed.

View Source
var ErrAskCancelUnsupported = errors.New("mirror: this host's muster-mirror cannot dismiss a question in the terminal; update it (and start it with -interactive)")

ErrAskCancelUnsupported: the host cannot dismiss a picker (an older or read-only muster-mirror).

View Source
var ErrBadHost = errors.New("mirror: a host name must be a lowercase DNS label ([a-z0-9-], 1-63 chars, not starting or ending with '-')")

ErrBadHost is the refusal for a host name that is not a lowercase DNS label.

View Source
var ErrBadToken = errors.New("mirror: unknown or revoked mirror token")

ErrBadToken is the refusal for a mirror token that is unknown or revoked.

View Source
var ErrClaudeWaiting = errors.New("mirror: muster did not send it: Claude Code is waiting on the person")

ErrClaudeWaiting is the cause of the hub's own Claude prompt guard refusal (a *PasteRefusedError with PasteRefusalClaudeWaiting): the host reports the window waiting on the person. Nothing was sent to the host.

View Source
var ErrClonesInvalid = errors.New("mirror: the host's clone list holds a path muster cannot carry")

ErrClonesInvalid: a host's list held a path muster cannot carry (or more than MaxClones). muster then decides nothing from it: no hint, no card — the host's own rule applies (no_repo for several), never a choice among the part of the list that happened to fit.

View Source
var ErrHostEnded = errors.New("mirror: the host ended the terminal")

ErrHostEnded is the cause of a stream the HOST ended with an error of its own (Msg.Error on closed): the transcript could not be read, the pane stopped running Claude Code, tmux refused the attach.

View Source
var ErrNoPrincipal = errors.New("mirror: no user principal on this request")

ErrNoPrincipal: a view or attach was asked for with no user on the context.

View Source
var ErrOpenCodeFormInvalid = errors.New("mirror: not an answer this question takes")

ErrOpenCodeFormInvalid wraps every refusal of a form or of its picks.

View Source
var ErrOpenCodeMoved = errors.New("mirror: muster did not send it: the opencode window shows another session than the one the message was written for")

ErrOpenCodeMoved: the window shows another session now than the one the message was written in view of, or a hand-opened pane's message named none. Nothing was sent.

View Source
var ErrPasteUnconfirmed = errors.New("mirror: the message was handed to the host, which did not confirm it")

ErrPasteUnconfirmed marks a paste that was HANDED TO THE HOST and never confirmed either way — the host's answer timed out, the caller gave up, or the connection ended first. It may have been pasted. (A paste refused before it was written to the host, or refused by the host, carries no such mark: it was not pasted.)

View Source
var ErrStepUpRequired error = stepUpRequired{}

ErrStepUpRequired: an interactive attach, or a paste, on a session that did not sign in within stepup.Window.

View Source
var ErrSuperseded = errors.New("mirror: superseded by a newer turn: something else was pasted into the window (or its status changed) after this message was decided on, so it was not pasted")

ErrSuperseded refuses a queued paste whose turn is no longer the one it was decided on (ExpectTurn). Nothing was sent to the host; the message can be queued again and decided on afresh. It is a *SupersededError.

View Source
var ErrSupersededJoin = errors.New("mirror: a newer connection from the same host already holds it")

ErrSupersededJoin ends a connection whose join finished after a NEWER connection of the same host had already taken its place.

View Source
var ErrTokenRevoked = errors.New("mirror: the host's token was revoked")

ErrTokenRevoked is the cause a connection ends with when its token is revoked. Such a host is dropped from the view at once — not kept as offline.

View Source
var MCPProtocolVersions = []string{"2025-06-18", "2025-03-26", "2024-11-05"}

MCPProtocolVersions are the MCP protocol revisions muster answers, newest first: a client asking for one gets it back; any other gets the newest.

ONE LIST, TWO ANSWERERS: muster's own MCP server (internal/api, POST /mcp and POST /mirror/mcp) and a host's local MCP endpoint (internal/mirrorhost's MCPProxy) when it answers `initialize` itself, for a caller outside the tmux server it mirrors. Both must negotiate alike.

View Source
var OpenCodePermissionChoices = []string{"once", "reject"}

OpenCodePermissionChoices are the answers muster ever sends an opencode permission request: this one call, or no. `always` widens the session's rules past this call, so muster never offers it.

View Source
var Reasons = []string{telemetry.ReasonOK, telemetry.ReasonClientLeft, telemetry.ReasonShutdown, telemetry.ReasonTimeout, telemetry.ReasonError,
	"host_disconnected", "host_offline", "session_gone", "window_gone", "not_agent", "no_rendered_view", "too_many",
	"overrun", "read_only", "step_up", "no_principal", "unconfirmed", "host_ended", "superseded", "refused", "unsupported"}

Reasons is Reason's whole vocabulary: a test pins that Reason never says anything else, so a reason can be a metric label.

View Source
var SessionKeyPattern = buildSessionKeyPattern()

SessionKeyPattern is every session key muster stores (SessionKey): a Claude session id as it always was (1-64 bytes), or a runtime's KeyPrefix and an id of 1-128 bytes, for each runtime that keys its sessions so. 🔴 IT IS SPELLED ONCE, HERE, FROM THE RUNTIME TABLE: internal/focus validates with it, and the CHECKs of agent_focus.subject_key, agent_focus_history.subject_key, session_routes.target_key and attention_asks.mirror_session carry the same expression — the migration that last wrote them is read by a test in internal/db that fails when the two differ (0085 last wrote them). A runtime that adds a KeyPrefix changes this pattern, so it fails that test until a NEW migration writes the wider CHECKs.

Functions

func AgentBindWords added in v0.189.0

func AgentBindWords(code string) string

AgentBindWords is the refusal of a send to a window of a gated-send runtime its host does not send to, in the person's words: the code's own reason, else (no code: an older host; a code this muster does not know) the launcher's.

func AskKeys

func AskKeys(err error) int

AskKeys is how many keys of the answer's plan the host reported the picker had received when AnswerWindow's err ended it: 0 when it reported none (an older host, nothing typed) or err is not the host's report.

func AskOutcomeKnown

func AskOutcomeKnown(err error) bool

AskOutcomeKnown reports whether err (from AnswerWindow) means the host is NOT typing any more: nil (typed), a refusal the host reported, or an answer never sent. False — the host may still be typing — for a timeout, a host that dropped after the answer was sent, or a send that failed part way.

func AskScreen added in v0.198.0

func AskScreen(err error) string

AskScreen is the pane the host sent with AnswerWindow's refusal err: "" when it sent none (an older host, a refusal before it read the pane).

func BoundPrompts

func BoundPrompts(refs []cctranscript.PromptRef) ([]cctranscript.PromptRef, int)

BoundPrompts is the newest of refs that fit the index bounds, in order, and how many earlier ones it dropped. A ref with no Line, or whose Line does not follow the one before it, is dropped too — not counted, since it names no prompt — and every Text is capped again: muster applies this to what a host sent as well as the host to what it read.

func CapAskScreen added in v0.198.0

func CapAskScreen(s string) string

CapAskScreen is s as a host sends it: REDACTED FIRST (redact.Secrets, over the whole pane), then, when it is over MaxAskScreen bytes, its tail from a line start, under AskScreenCutMark, MaxAskScreen bytes in all.

🔴 REDACTION BEFORE THE CUT: a cut first could split a secret — a key block's BEGIN line above the cut, its body below — into a fragment the redactor no longer recognises (internal/askattempt's store redacts again, and cuts again, for the same reason).

func CheckOpenCodePicks added in v0.189.0

func CheckOpenCodePicks(f OpenCodeForm, picks []OpenCodePick) error

CheckOpenCodePicks is why picks cannot answer form f, nil when they can: exactly one pick list per question, in the form's order, by its key; each index one of that question's options, none twice; an answer of one's own only on a question that takes one, within MaxFormOther characters; a single-select answered exactly once (an option or one's own), a multi-select at least once. Applied by BOTH halves.

func ClampScroll

func ClampScroll(n int) (int, bool)

ClampScroll is n bounded to [-MaxScrollLines, MaxScrollLines], and ok=false for 0 (nothing to scroll). Both halves apply it: muster to what a browser asked for, the host again to what muster sent.

func ClaudePastedRefusal

func ClaudePastedRefusal(err error) bool

ClaudePastedRefusal reports whether err is the Claude prompt guard's "pasted, not submitted" (PasteRefusalClaudePasted): the text is in Claude Code's input box. It counts as landed — what follows it would be pasted after it — so the queue holds behind it and its Retry warns.

func ClaudeWaitingRefusal

func ClaudeWaitingRefusal(err error) bool

ClaudeWaitingRefusal reports whether err is one of the Claude prompt guard's NOTHING-TYPED refusals — the hub's or the host's (PasteRefusalClaudeWaiting, PasteRefusalClaudeBox): a queued message is held on it, not failed.

func CleanOption added in v0.138.0

func CleanOption(label string) bool

CleanOption reports whether label is one an opencode question can offer in muster as it is (cleanOptions' per-label rule): the host checks each label with it before it offers any.

func CleanRepoName

func CleanRepoName(name string) string

CleanRepoName is name as the wire carries it: invalid UTF-8 dropped, control and format characters turned to spaces or removed and whitespace collapsed (the rule every other host-sent line follows), at most MaxRepoName bytes; "" when nothing is left, or when it holds a '/' (a path, not a name) or is "." or "..".

func CleanText

func CleanText(s string, max int) string

CleanText is s as one line of display text: invalid UTF-8 replaced, every control character (C0, DEL, C1) and the bidirectional overrides that can make a description read differently from what it says turned into a space, runs of white space collapsed, trimmed, and cut to max runes with "…".

func DecodeData

func DecodeData(b []byte) (uint32, []byte, error)

DecodeData splits a binary frame into its stream id and bytes.

func EncodeData

func EncodeData(id uint32, p []byte) []byte

EncodeData frames terminal bytes for stream id.

func GatedNotIdleRefusal added in v0.160.0

func GatedNotIdleRefusal(err error) bool

GatedNotIdleRefusal reports whether err is a host's refusal of a gated send because the window was not idle when it checked (nothing was sent).

func HashToken

func HashToken(token string) string

HashToken is the stored form of a token.

func IsAttachRefusal

func IsAttachRefusal(err error) bool

IsAttachRefusal reports whether err is one of the plugin's own refusals, whose text is written for the operator and is passed to the browser as is.

func IsSubagentTool

func IsSubagentTool(name string) bool

IsSubagentTool reports whether a tool call of this name spawns a subagent ("Agent", or "Task", its earlier name). Both halves read it: the host to track the calls, muster to draw them as cards. It is ccsubagents.IsSubagentTool, re-exported.

func IsViewSession

func IsViewSession(name string) bool

IsViewSession reports whether name is one of muster-mirror's own viewer sessions (ViewSessionPrefix), which are never listed.

func NegotiateMCPVersion added in v0.135.0

func NegotiateMCPVersion(requested string) string

NegotiateMCPVersion is the protocol revision to answer an `initialize` that asked for requested.

func NewToken

func NewToken() (string, error)

NewToken mints a fresh token: TokenPrefix + 43 base64url characters (256 bits).

func NormalizeActivity

func NormalizeActivity(activity map[string]int64, sessions []string, now int64) map[string]int64

NormalizeActivity is activity restricted to sessions (a host cannot rank a session it does not list), each time floored to ActivityBucket; nil when nothing is left. An entry that is not a positive time is dropped, and one later than now is CAPPED at now — a host whose clock runs ahead ties with "active now" rather than outranking every other host forever (now <= 0 skips the cap). Both halves apply it: the host to what it sends, muster to what it keeps.

func NormalizeColors

func NormalizeColors(in map[string]string, windows []Window) map[string]string

NormalizeColors is in restricted to windows, each value exactly a lowercase `#rrggbb` (anything else is dropped, never repaired: the host lowercases before it sends); nil when nothing is left. Both halves apply it.

func NormalizeGitHubRepos added in v0.198.0

func NormalizeGitHubRepos(in map[string]string, windows []Window) map[string]string

NormalizeGitHubRepos is in restricted to windows (NormalizeRepos' rule), each value a GitHub owner/name (ValidGitHubRepo) lowercased; an entry that is not is dropped; nil when nothing is left.

func NormalizeLabels

func NormalizeLabels(labels map[string]string, sessions []string) map[string]string

NormalizeLabels is labels restricted to sessions (a host cannot label a session it does not list) with every invalid label dropped; nil when nothing is left. Both halves apply it: the host to what it sends, muster to what it keeps — muster never trusts the host to have done it.

func NormalizeOutcomes added in v0.179.0

func NormalizeOutcomes(in map[string]WindowOutcome, windows []Window) map[string]WindowOutcome

NormalizeOutcomes is in restricted to windows (a host cannot report an outcome for a window it does not list): only a window the chief started (Dispatch > 0) that runs opencode, names its session and is IDLE keeps one, with a mark ValidAgentSession accepts and its lines through OutcomeLines; at most MaxOutcomeWindows, in listing order; nil when nothing is left. Both halves apply it. windows must be NormalizeWindows' output.

func NormalizePreviews added in v0.194.0

func NormalizePreviews(in map[string]WindowPreviews, windows []Window) map[string]WindowPreviews

NormalizePreviews is in restricted to windows (a host cannot report previews for a window it does not list), each count clamped to [0, MaxPreviewCount], entries with nothing to show dropped; nil when nothing is left. Both halves apply it: the host to what it sends, muster to what it keeps. windows must be NormalizeWindows' output, so the result has at most MaxWindows entries.

func NormalizeQueued added in v0.129.0

func NormalizeQueued(in []string) []string

NormalizeQueued is in as the wire carries it: each message cleaned and bounded (CleanText), blank ones dropped, at most MaxQueued. nil when none.

func NormalizeRepos

func NormalizeRepos(in map[string]string, windows []Window) map[string]string

NormalizeRepos is in restricted to windows (a host cannot name the repo of a window it does not list), each name through CleanRepoName (an entry left empty is dropped); nil when nothing is left. Both halves apply it: the host to what it sends, muster to what it keeps. windows must be NormalizeWindows' output, so the result has at most MaxWindows entries.

func NormalizeStatus

func NormalizeStatus(status string) string

NormalizeStatus is the Window.Status a sessions-file status is read as: busy, idle and waiting as themselves, ClaudeStatusShell as StatusIdle, anything else "" (unknown, which never releases a queued message). Both halves apply it.

func NormalizeWork

func NormalizeWork(in map[string]WindowWork, windows []Window) map[string]WindowWork

NormalizeWork is in restricted to windows (a host cannot report work for a window it does not list), each entry through normalizeWork, entries with nothing to show dropped; nil when nothing is left. Both halves apply it: the host to what it sends, muster to what it keeps. windows must be NormalizeWindows' output, so the result has at most MaxWindows entries.

func OneLine

func OneLine(s string, max int) string

OneLine is s as one short, phone-safe line: control characters as spaces, whitespace collapsed, at most max runes (a cut ends "…"). The rule CleanPending applies to each field, for any other excerpt shown beside it.

func OpenCodeCallSession added in v0.197.0

func OpenCodeCallSession(params json.RawMessage) string

OpenCodeCallSession is the session a tools/call's params name under OpenCodeSessionMeta, trimmed; "" when they name none, or name it as anything but a JSON string. Whether it is believed is the caller resolver's decision.

func OpenCodeCallerKey added in v0.197.0

func OpenCodeCallerKey(id string) string

OpenCodeCallerKey is the session key an opencode MCP caller is named by (opencode:<id>), "" for an id the wire would not carry.

func OpenCodeMCPCaller added in v0.197.0

func OpenCodeMCPCaller(key string) bool

OpenCodeMCPCaller reports whether key is an opencode caller's.

func OpenCodeMessageID added in v0.160.0

func OpenCodeMessageID(owner int64, key string) string

OpenCodeMessageID is the opencode message id a send with key by owner is posted under: "msg_" and 26 characters of HMAC-SHA256(owner, key), shaped like upstream's own ids (12 hex digits, 14 of its alphabet). DETERMINISTIC on purpose: opencode answers a second post of an id with the first one's record (measured, opencodetest/testdata/prompt-v2.0.32.json), so the same key can land once whatever retries it. Upstream orders a session's messages by their sequence, not their id (packages/core/src/session/ projector.ts), so an id need not encode the time. "" for an empty key.

func OutcomeLines added in v0.179.0

func OutcomeLines(text string) []string

OutcomeLines is text's last MaxOutcomeLines non-empty lines, oldest first, each with control characters made spaces, trimmed and cut to MaxOutcomeLine bytes: what a WindowOutcome carries. The host builds Lines with it and both halves apply it again (NormalizeOutcomes).

func OutcomesEqual added in v0.179.0

func OutcomesEqual(a, b map[string]WindowOutcome) bool

OutcomesEqual reports whether two outcome maps say the same.

func ParseSpawnModel added in v0.172.0

func ParseSpawnModel(wire string) (provider, id string, ok bool)

ParseSpawnModel reads an agent-spawn's model as opencode's Model.Ref does — the provider before the FIRST '/', the id after it — and reports whether it is an OpenRouter model id muster takes: the provider is exactly SpawnModelProvider and the id passes ValidSpawnModel. So "a/b/c" is provider "a", id "b/c", and refused.

func PasteGuardRefusal

func PasteGuardRefusal(err error) string

PasteGuardRefusal is the host's paste-guard refusal err carries (one of the PasteRefusal* kinds), or "" when it is not one.

func PromptDigest

func PromptDigest(text string) string

PromptDigest is what names a prompt's text on the wire (TurnError.Prompt): the first 8 bytes of the SHA-256 of the text with its surrounding whitespace trimmed and CRLF read as LF — the host digests the prompt as the transcript holds it, muster the message it sent, and the two agree however the terminal carried the line ends. Nothing stores it.

func RanksByRegistration

func RanksByRegistration(tokens []Token) map[string]int

RanksByRegistration ranks the hosts tokens were minted for by each host's lowest token id, 0 first. tokens may come in any order and may hold several per host (rotations) and revoked ones; all count.

func Reason

func Reason(err error) string

Reason is err as a closed reason code: what a span's status, a metric's label and the page's "disconnected because" all say. nil is ok.

func ResumeRefusal

func ResumeRefusal(err error) string

ResumeRefusal is the kind of a host's refusal (ResumeRefusal*), "" when err is not one.

func SanitizePaste

func SanitizePaste(text string) (string, error)

SanitizePaste is text ready to paste into a pane, or why it cannot be: CRLF and lone CR fold to LF, and every other control character is REFUSED (tab and newline excepted), with the size bounded by MaxPaste.

🔴 A CONTROL CHARACTER CAN END A BRACKETED PASTE, AND WHAT FOLLOWS IT IS TYPED. tmux wraps the buffer in ESC[200~ … ESC[201~ and passes an ESC inside it through raw on some versions (ccd measured 3.3a and 3.4), so "\x1b[201~…" would close the paste and type the rest as keys. muster checks this before sending and the host checks it again before pasting.

func SendBlocked added in v0.160.0

func SendBlocked(h HostView, e SessionView) string

SendBlocked is why a Rendered-view message cannot be sent to entry e of host h through its runtime's gated send — the words the refusal would say (the runtime's SendOff, or Unbound) — or "" when it can be, or e's runtime has no gated send. The PAGE's reading (its composer drawn disabled, and why) of the rule the hub ENFORCES on its own window list (gatedSendCheck); TestThePageAndTheHubAgreeOnWhatCanBeSent pins that the two agree.

func SessionIDOf

func SessionIDOf(key string) string

SessionIDOf is the bare conversation id a stored session key names: a Claude Code id as it is, a runtime-qualified one without its KeyPrefix.

func SessionsOf

func SessionsOf(windows []Window) (sessions, claude []string, labels map[string]string, activity map[string]int64)

SessionsOf is the PER-SESSION view of a per-window list — what a muster that predates Windows is sent, and what muster itself answers a request that names only a session with: the distinct session names (sorted), and per session its ACTIVE window's label and Claude flag and the NEWEST activity of any of its windows. windows must be NormalizeWindows' output.

func ShownSessionCheck added in v0.189.0

func ShownSessionCheck(shown, listed string, launcher bool) error

ShownSessionCheck is THE rule (the hub applies it; internal/api's fake mirror plays it): the refusal of a gated send that named shown (the session the sender's view showed; "" none) to a window whose list names listed — launcher-bound (launcher) or not — nil when it may go: shown is the listed session, or, for a launcher-bound window only, none is named (an older page or row: the launcher's record names the session).

func SpawnModelWire added in v0.172.0

func SpawnModelWire(id string) string

SpawnModelWire is id as an agent-spawn carries it: openrouter/<id>.

func SpawnSlug added in v0.170.0

func SpawnSlug(name string, max int) string

SpawnSlug is name as a slug: lowercased, every run of other characters a single '-', trimmed of '-', at most max characters. ONE rule for the window name and the branch, on the host.

func TokenShapeOK

func TokenShapeOK(token string) bool

TokenShapeOK reports whether token is shaped like one NewToken mints: TokenPrefix + 43 base64url characters. It is a FILTER, not authentication: it lets the connect route refuse junk without a database read.

func ValidAgentSession

func ValidAgentSession(id string) bool

ValidAgentSession reports whether id is a non-Claude session id the wire carries.

func ValidCatalogName

func ValidCatalogName(name string) bool

ValidCatalogName reports whether name is a command name the wire carries.

func ValidClaudeSession

func ValidClaudeSession(id string) bool

ValidClaudeSession reports whether id is a Claude session id the wire carries.

func ValidClonePath added in v0.204.0

func ValidClonePath(p string) bool

ValidClonePath reports whether p can be a clone's path on the wire: absolute, already clean, at most MaxClonePath bytes, no control or non-printing characters (it is shown on a card and goes into a host's git argv only after the host found it itself).

func ValidColor

func ValidColor(c string) bool

ValidColor is whether c is a colour the wire carries.

func ValidGitHubRepo added in v0.198.0

func ValidGitHubRepo(s string) bool

ValidGitHubRepo reports whether s is a GitHub owner/name (github.ValidRepoName's rule).

func ValidHost

func ValidHost(host string) error

ValidHost reports whether host is a usable host name.

func ValidLabel

func ValidLabel(label string) error

ValidLabel reports whether label is a display label the tunnel carries: valid UTF-8, 1-MaxLabel bytes, no control characters (C0, DEL or C1) and not all whitespace. It is rendered as text only, never parsed or passed to tmux.

func ValidMCPCaller added in v0.197.0

func ValidMCPCaller(key string) bool

ValidMCPCaller reports whether key can name an MCP caller at all: a Claude session id, or an opencode caller's key.

func ValidOpenCodeAskID added in v0.138.0

func ValidOpenCodeAskID(id string) bool

ValidOpenCodeAskID reports whether id is an opencode permission request or form id.

func ValidSession

func ValidSession(name string) error

ValidSession reports whether name is a session name the tunnel carries: valid UTF-8, 1-128 bytes, and no control characters. The name is passed to tmux as ONE argv element (never through a shell), behind tmux's `=` exact-match prefix, so nothing else about it is interpreted.

func ValidSessionKey

func ValidSessionKey(key string) bool

ValidSessionKey reports whether key is a session key muster stores.

func ValidSpawnModel added in v0.172.0

func ValidSpawnModel(id string) bool

ValidSpawnModel reports whether id is an OpenRouter model id muster takes for an opencode spawn: the shape above, at most MaxSpawnModel bytes.

func ValidSubagentID

func ValidSubagentID(id string) bool

ValidSubagentID reports whether id is a subagent (or tool_use) id the wire carries: the CLI's are hex (a3f…) and toolu_…, bounded so a summary's worst case is known, and safe as one path element on the host. It is ccsubagents.ValidID, re-exported.

func ValidTurnErrorKind

func ValidTurnErrorKind(s string) bool

ValidTurnErrorKind reports whether s is a kind the wire carries.

func ValidWindowID

func ValidWindowID(id string) error

ValidWindowID reports whether id is a tmux window id ("@12"): the only thing the tunnel carries as a window address, and — being digits behind an `@` — safe as one argv element of a tmux target.

func Where added in v0.124.0

func Where(host, session, window string, index int, label string) string

Where names a mirrored window so the operator can go to it in a terminal: "tmux <session>:<window index> @ <host>" — the tmux session name and window index, exactly as tmux's own target syntax takes them (Address) — led by the host's label for it when it has one that is not that same address:

tmux build:4 @ laptop
mango:1 · tmux scratch3:5 @ laptop

A per-session host's entry (window "") is "tmux <session> @ <host>".

🔴 ONE RULE, ONE PLACE. Every attention surface that names a mirrored window (a chief nudge's ask, a waiting session or held question, the session asker of an ask, their notifications and the ask page's header) takes its words from here. The label is a host's codename and is NOT a tmux name — on its own it named a window nobody could find — so it is never the only name, and the session name alone (no index) is not a target either.

The index is a SNAPSHOT: tmux renumbers windows, so text built from it says where the window was when the text was made. Links resolve the window by its Claude session id when followed and stay the source of truth.

func WhereTarget added in v0.124.0

func WhereTarget(host, session, window string, index int) string

WhereTarget is Where's machine part, "tmux <session>:<index> @ <host>", without the label: what a surface that plains a title for display must keep VERBATIM (textplain.TitleKeeping) — a tmux session named "_scratch_" is typed as "_scratch_", never as the "scratch" a markdown stripper reads.

func WithAskKeys

func WithAskKeys(err error, keys int) error

WithAskKeys is err carrying keys, as a host's refusal reports them (AskKeys): how a host's outcome reaches AnswerWindow's caller, and how a stand-in for the hub (a test's) reports one. nil stays nil, and keys 0 adds nothing.

func WithAskScreen added in v0.198.0

func WithAskScreen(err error, screen string) error

WithAskScreen is err carrying the pane screen a host read when it refused (AskScreen). nil stays nil, and an empty screen adds nothing.

func WithOpenStats

func WithOpenStats(ctx context.Context, st *OpenStats) context.Context

WithOpenStats has the watch or terminal opened under ctx fill st, BEFORE it hands its first batch or output on — so the caller reads it there.

Types

type AgentClone added in v0.204.0

type AgentClone struct {
	Path string `json:"path"`
	Live bool   `json:"live,omitempty"`
}

AgentClone is one of a host's clones of a repository (Msg.Clones): Path is its MAIN working tree, as the host resolved it (realpath); Live, one of the host's own listed windows works in it.

func ChooseClone added in v0.204.0

func ChooseClone(clones []AgentClone) (hint string, choices []AgentClone)

ChooseClone is THE rule for which clone a spawn is cut from, given the host's own list: the only clone, or the only LIVE clone among several, is the hint; with several and none or several live, hint is "" and choices is the clones for the owner to choose among — live ones first, each group in the host's order. No clones: "" and none (the host refuses the spawn itself).

func ClonesReplyResult added in v0.204.0

func ClonesReplyResult(m Msg) ([]AgentClone, error)

ClonesReplyResult reads an agent-clones-list frame: the clones, or the refusal.

func NormalizeClones added in v0.204.0

func NormalizeClones(in []AgentClone) ([]AgentClone, error)

NormalizeClones is a host's answer as muster takes it: each path once (the first kept), or ErrClonesInvalid when any path is invalid or there are more than MaxClones — the WHOLE list refused, so no choice is ever made among a part of it.

type AgentCloseReq added in v0.183.0

type AgentCloseReq struct {
	Session string `json:"session"`
	Window  string `json:"window"`
	Key     string `json:"key"`
}

AgentCloseReq is an agent-close's request (Msg.CloseReq): the window, and Key, the session key of the conversation muster expects it to run (Window.SessionKey's rule: a Claude session id, or "opencode:<id>"). The host refuses (CloseMismatch) a window running any other.

type AgentCloseResult added in v0.183.0

type AgentCloseResult struct {
	Graceful bool   `json:"graceful"`
	Reason   string `json:"reason,omitempty"`
}

AgentCloseResult is an agent-closed's outcome (Msg.CloseResult): Graceful when the agent exited on its own after /exit, false when the host closed the window without that, with Reason saying why (it was waiting on the person, an opencode window, the grace passed).

func CloseReplyResult added in v0.183.0

func CloseReplyResult(m Msg) (AgentCloseResult, error)

CloseReplyResult reads an agent-closed frame: the outcome, or the refusal.

type AgentContext added in v0.189.0

type AgentContext struct {
	Tokens int64  `json:"tokens"`
	Limit  int64  `json:"limit,omitempty"`
	Model  string `json:"model,omitempty"`
}

AgentContext is an agent's context fill (Msg.Context): Tokens in context now, of a window of Limit tokens (0: unknown), on model Model ("" unknown). opencode's is opencodehost.ContextOf: the newest step's input + cache read + cache write — the quantity a Claude Code view's readout counts.

func CleanAgentContext added in v0.189.0

func CleanAgentContext(c *AgentContext) *AgentContext

CleanAgentContext is c as muster keeps it: nil for none or no tokens, no negative limit, the model stripped of control characters and cut to MaxContextModel bytes on a rune boundary.

type AgentSpawnReq added in v0.170.0

type AgentSpawnReq struct {
	Runtime string `json:"runtime"`
	// Repo is <owner>/<repo>; the host resolves it to one of its own clones.
	Repo string `json:"repo"`
	// Base is the branch the worktree is cut from; "" = the remote's default.
	Base string `json:"base,omitempty"`
	// Prompt is the first message, already cleaned and wrapped by muster
	// (beginning with SpawnPreface).
	Prompt string `json:"prompt"`
	// Name is the short display label, used only for the window name after
	// the host sanitises it.
	Name string `json:"name,omitempty"`
	// Model is opencode's openrouter/<vendor>/<model>; refused on claude.
	Model string `json:"model,omitempty"`
	// Clone is muster's HINT of which of the host's clones of Repo to cut the
	// worktree from: the main working tree's path EXACTLY as the host itself
	// reported it in an agent-clones-list (clones.go). "" = the host's own
	// rule (its only clone). A host that advertised AgentSpawnClones uses it
	// only when it is one of the clones it enumerates now, and refuses
	// (SpawnBadClone) anything else; an older host ignores the field and keeps
	// refusing a repository with several clones (no_repo), never guessing.
	Clone string `json:"clone,omitempty"`
}

AgentSpawnReq is an agent-spawn's request (Msg.Spawn).

type AgentSpawned added in v0.170.0

type AgentSpawned struct {
	Session      string `json:"session"`
	Window       string `json:"window"`
	Pane         string `json:"pane,omitempty"`
	Worktree     string `json:"worktree"`
	Branch       string `json:"branch"`
	AgentSession string `json:"agentSession"`
	// Warning is a step that did not finish but did not refuse the spawn
	// ("submodules incomplete").
	Warning string `json:"warning,omitempty"`
}

AgentSpawned is a successful agent-spawned's window (Msg.Spawned).

func SpawnReplyResult added in v0.170.0

func SpawnReplyResult(m Msg) (AgentSpawned, error)

SpawnReplyResult reads an agent-spawned frame: the window, or the refusal. A frame that names no valid window is a refusal of its own (failed).

type AgentState

type AgentState struct {
	// Runtime is the agent CLI in the window (Window.AgentRuntime):
	// RuntimeClaude or RuntimeOpenCode — set whenever the hub knows it, ALSO
	// when Status is unknown. "" when the window runs no agent, or the hub
	// cannot say.
	Runtime string
	// Status is StatusBusy, StatusIdle or StatusWaiting; "" when unknown.
	Status string
	// Since is when Claude Code wrote Status (its statusUpdatedAt), in Unix
	// milliseconds ON THE HOST'S CLOCK. 0 when unknown.
	Since int64
	// Observed is when the hub first saw this (Status, Since) pair, on
	// MUSTER's clock: what an idle duration is measured from.
	Observed time.Time
	// Pasted is the Since the window held at its latest paste through this
	// hub (a Send or a queued message), on the host's clock; 0 for none.
	Pasted int64
	// TurnError is how the window's latest turn ended, when it ended in an
	// error Claude Code wrote itself (Window.TurnError); nil otherwise, and
	// whenever Status is not idle.
	TurnError *TurnError
	// HostLimit is a usage limit the window's HOST reports for all its Claude
	// windows (Msg.HostLimit), set on a Claude window whenever the host
	// reports one; nil otherwise.
	HostLimit *HostLimit
	// Session is the Claude Code session id of the conversation in the window
	// (Window.ClaudeSession), "" when the host does not say.
	Session string
	// Unknown is why Status is unknown; nil when it is known.
	Unknown error

	// GuardHeld is, while the window is held by the Claude prompt guard's
	// backoff (turns.go guardHold), why — the host's refusal, in words — and
	// "" otherwise. The send queue sends nothing while it is set.
	GuardHeld string
}

AgentState is what the hub knows of the agent session in one window.

type AskTyping

type AskTyping struct {
	Questions []askq.Question `json:"questions"`
	Choices   []askq.Choice   `json:"choices"`
	// Prior is what an earlier answer's typing is known to have left in this
	// picker (askq.Entry.Left): the host continues it when the picker shows
	// exactly that, and only then (askdrive.DriveFrom). nil: nothing. An
	// older host ignores it and requires the picker untouched, as before.
	Prior *askq.Progress `json:"prior,omitempty"`
}

AskTyping is an answer to type into an AskUserQuestion picker (Msg.Ask): the call's questions as muster showed them — which the host checks the picker against before every key — and one choice per question.

type Capabilities

type Capabilities struct {
	// View: muster shows the window's conversation in a rendered view.
	View bool
	// Send: muster sends a message into the window from a rendered view or
	// the queue (Claude Code: a paste).
	Send bool
	// Prompts: what the window waits on (a permission, an approval, a
	// question) reaches muster, as the window's Pending.
	Prompts bool
}

Capabilities is what muster can do with a window of a runtime. The host reads them here (LookupRuntime); tests in internal/mirrorhost pin that its implementations exist where these say.

type Catalog

type Catalog struct {
	Commands []CatalogEntry `json:"commands,omitempty"`
	// Truncated: something was dropped to stay within the bounds.
	Truncated bool `json:"truncated,omitempty"`
}

Catalog is one window's menu: its commands.

func MergeBuiltins

func MergeBuiltins(c Catalog) Catalog

MergeBuiltins is the menu muster offers for a window: the host's catalog with Claude Code's built-in commands added (a host-defined name shadows a built-in, as in Claude Code), normalised.

func NormalizeCatalog

func NormalizeCatalog(c Catalog) Catalog

NormalizeCatalog is c as the tunnel carries it. Both halves apply it: the host to what it read, muster to what it got.

  • a command with an invalid name, an unknown source or kind is dropped; a name defined twice is kept ONCE, by the first source in project, user, plugin, built-in order (and within one source the first as given);
  • every description is CleanText'd to MaxCatalogDescription;
  • commands are sorted by name and the count is capped;
  • finally the whole is cut to MaxCatalogBytes ENCODED; entries past the budget are dropped.

Truncated says anything was dropped for a bound (not for being invalid).

type CatalogEntry

type CatalogEntry struct {
	// Name is what follows the `/`: "compact", "handoff", "stripe:test-cards".
	Name string `json:"name"`
	// Description is what the entry says it does; "" for none.
	Description string `json:"description,omitempty"`
	// Source is SourceProject, SourceUser, SourcePlugin or SourceBuiltin.
	Source string `json:"source"`
	// Kind is KindCommand or KindSkill.
	Kind string `json:"kind"`
}

CatalogEntry is one slash command or skill: typed as `/<Name>`.

type ClonesRefusedError added in v0.204.0

type ClonesRefusedError struct{ Code, Detail string }

ClonesRefusedError is a host's refusal to list (a Spawn* code: the repository is not on its allow-list, spawning is off).

func (*ClonesRefusedError) Error added in v0.204.0

func (e *ClonesRefusedError) Error() string

type CloseRefusedError added in v0.183.0

type CloseRefusedError struct{ Code, Detail string }

CloseRefusedError is a host's refusal of an agent-close.

func (*CloseRefusedError) Error added in v0.183.0

func (e *CloseRefusedError) Error() string

type HostLimit

type HostLimit struct {
	// At is that limit record's time, Unix ms on the host's clock.
	At int64 `json:"at"`
	// ResetsAt is the reset it names, Unix ms (absolute); 0 for none.
	ResetsAt int64 `json:"resetsAt,omitempty"`
}

HostLimit is a usage limit a host reports for all its Claude Code windows (Msg.HostLimit): the newest limit record across them, and the reset it names — taken by the host from EVERY idle Claude window's transcript, before the window list's MaxTurnErrorWindows bound, and not reported once any of its Claude windows got a real answer after it (the limit has lifted).

func CleanHostLimit

func CleanHostLimit(l *HostLimit) *HostLimit

CleanHostLimit is l as muster keeps it: nil for none or no time, no negative reset.

type HostView

type HostView struct {
	Host     string
	Sessions []string
	// Windows is every window the host lists (NormalizeWindows' order); nil for
	// a per-session host.
	Windows []Window
	// Claude is the subset of Sessions whose active pane runs Claude Code (a v2
	// host's report; always empty for a v1 host): the sessions opened in the
	// rendered view by default.
	Claude []string
	// Labels is the host's display label per session (Msg.Labels), restricted
	// to Sessions; a session without one is shown by its name. nil when the
	// host sends none (an older muster-mirror, or no labels configured).
	Labels map[string]string
	// Activity is when each session was last active on the host
	// (Msg.Activity: Unix seconds, floored to ActivityBucket), restricted to
	// Sessions. nil when the host sends none (an older muster-mirror); a
	// session without one sorts after every session with one (Ordered).
	Activity map[string]int64
	// Rendered: the host speaks tunnel v2, so its Claude sessions have a
	// rendered view. False for a v1 host and for an offline one.
	Rendered bool
	// Online: connected now. False is a host that disconnected within
	// offlineRetention; Sessions is then its last list.
	Online bool
	// Interactive: the host advertised -interactive.
	Interactive bool
	// OpenCodeAnswer: the host advertised Msg.OpenCodeAnswer (it is
	// -interactive, v2, and holds an opencode token): an opencode ask muster shows
	// for one of its windows can be answered here.
	OpenCodeAnswer bool
	// OpenCodeSend: the host advertised Msg.OpenCodeSend (-interactive, v2,
	// -opencode-send, an opencode token): a message can be sent to its
	// launcher-bound opencode windows (Window.AgentSend).
	OpenCodeSend bool
	// OpenCodeForms: the host advertised Msg.OpenCodeForms — it sends a
	// pending opencode question's whole form and takes its answer
	// (opencode_form.go).
	OpenCodeForms bool
	// PanePaste: the host advertised that a paste may target a session's active
	// pane whatever runs there (Msg.PanePaste). False for an older muster-mirror
	// and for an offline host.
	PanePaste bool
	// PaneScroll: the host advertised that it scrolls a window's pane through
	// its history in copy-mode (Msg.PaneScroll). False for an older
	// muster-mirror and for an offline host.
	PaneScroll bool
	// StatusReport: the host advertised that it reports each window's Claude
	// Code status (Msg.StatusReport), which is what a queued message waits on.
	// False for an older muster-mirror and for an offline host.
	StatusReport bool
	// AskAnswer: the host advertised that it types answers into Claude Code's
	// AskUserQuestion picker (Msg.AskAnswer) and is -interactive. False for an
	// older or read-only muster-mirror and for an offline host.
	AskAnswer bool
	// AskCancel: the host advertised that it dismisses an AskUserQuestion
	// picker with one Escape (Msg.AskCancel) and is -interactive. False for an
	// older or read-only muster-mirror and for an offline host.
	AskCancel bool
	// ResumeSpawn: the host advertised that it resumes an ended Claude Code
	// session in a new window (Msg.ResumeSpawn) and is -interactive. False for
	// an older or read-only muster-mirror, one without -resume-spawn, and an
	// offline host.
	ResumeSpawn bool
	// AgentSpawn is the runtimes the host advertised it starts for the chief
	// (Msg.AgentSpawn), for an -interactive host only; nil otherwise.
	AgentSpawn []string
	// AgentSpawnSkipPermissions: the host advertised that it starts its
	// spawned Claude Code agents without permission prompts
	// (Msg.AgentSpawnSkipPermissions);
	// false whenever AgentSpawn is empty.
	AgentSpawnSkipPermissions bool
	// AgentSpawnClones: the host answers agent-clones and honours a spawn's
	// clone hint (Msg.AgentSpawnClones, clones.go); false whenever AgentSpawn
	// is empty.
	AgentSpawnClones bool
	// AgentClose: the host ends an agent window on muster's request
	// (Msg.AgentClose, agentclose.go), for an -interactive host only.
	AgentClose bool
	// Repos is the short repo name per WINDOW ID the host last sent
	// (TypeRepos, repos.go), restricted to its windows when it arrived; nil when
	// it sent none (an older muster-mirror, a per-session host). Display and
	// search only: Entries copies each window's onto its SessionView.Repo.
	Repos map[string]string
	// GitHubRepos is the GitHub <owner>/<name> per WINDOW ID the host last sent
	// on the same message (Msg.GitHubRepos), nil when it sent none: Entries
	// copies each window's onto its SessionView.GitHubRepo. A host's word.
	GitHubRepos map[string]string
	// Work is the live work counts per WINDOW ID the host last sent (TypeWork,
	// work.go), restricted to its windows when it arrived; nil when it sent none
	// (an older muster-mirror). 🔴 NEVER KEPT FOR AN OFFLINE HOST: a count is a
	// claim about NOW, and a host that is gone cannot vouch for it.
	Work map[string]WindowWork
	// Previews is the live preview counts per WINDOW ID the host last sent
	// (TypePreviews, previews.go), restricted to its windows when it arrived;
	// nil when it sent none (an older muster-mirror, one without -preview).
	// 🔴 NEVER KEPT FOR AN OFFLINE HOST, like Work: a count is a claim about NOW.
	Previews map[string]WindowPreviews
	// Colors is the tmux identity colour per WINDOW ID the host last sent
	// (TypeColors, work.go), restricted to its windows when it arrived; nil when
	// it sent none. Kept offline, like Repos: it is the window's identity, not
	// its state.
	Colors map[string]string
	// OfflineSince is when an offline host disconnected; zero while Online.
	// Its Windows keep the Status they last reported only when it reported
	// status (StatusReport) — the attention queue keeps such a host's waiting
	// windows for a short grace, so a blip neither drops nor re-notifies them.
	OfflineSince time.Time
}

HostView is one host as its owner sees it.

A PER-WINDOW host (Windows != nil) lists every tmux window; Sessions, Claude, Labels and Activity are then muster's own per-session view of that list (SessionsOf) — what a request naming only a session resolves through. A PER-SESSION host (an older muster-mirror) has no Windows, and those four are what it sent.

func (HostView) AnswersOn added in v0.156.0

func (h HostView) AnswersOn(r RuntimeSpec) bool

AnswersOn reports whether h's host advertised that it answers r's asks — read from the HostView's hello flags through r.Answers, the one place a flag is mapped to its runtime.

func (HostView) CanPaste

func (v HostView) CanPaste(session string) bool

CanPaste reports whether a message can be sent into session's active pane from the Terminal view. See SessionView.CanPaste.

func (HostView) Entries

func (h HostView) Entries() []SessionView

Entries is every entry of the host, in its own stable order: a per-window host's windows (session, then index), a per-session host's sessions (name).

func (HostView) Find

func (h HostView) Find(session, window string) (SessionView, bool)

Find is the host's entry for (session, window). window == "" is the session's ACTIVE window — what a URL from before windows were addressable names — and on a per-session host is the only address there is.

🔴 THE SAME RULE AS THE HUB'S OWN RESOLUTION (hostConn.target), over the same list: a page and the request it then makes cannot resolve one address to two windows.

func (HostView) SendsOn added in v0.160.0

func (h HostView) SendsOn(r RuntimeSpec) bool

SendsOn reports whether h's host advertised r's gated send (r.Sends).

type Hub

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

Hub is the set of connected hosts, their session lists and their live terminal streams. It is the plugin's whole state: nothing here is persisted.

⚠ IT IS IN-PROCESS STATE, like internal/sse's bus: a host is connected to ONE muster process, and a terminal opened on another replica cannot reach it. The deployment runs one replica, which is what makes this sufficient.

func NewHub

func NewHub(logger *log.Logger) *Hub

NewHub builds an empty hub.

func (*Hub) AgentClones added in v0.204.0

func (h *Hub) AgentClones(ctx context.Context, owner int64, host, repo string) (cl []AgentClone, err error)

AgentClones asks owner's host for its clones of repo and waits for the answer (ClonesReplyResult's). It starts and changes nothing on the host.

func (*Hub) AgentState

func (h *Hub) AgentState(owner int64, host, session, window string) AgentState

AgentState is the state of the agent session (Claude Code or opencode) in owner's host's (session, window) — window "" being the session's active window — or why it is unknown. Another owner's host answers ErrHostOffline, like a host that does not exist. A window that runs no agent answers ErrNotClaude, as it always did; an opencode window never does (its Runtime says which it is, and its status is read like Claude Code's).

func (*Hub) AnswerOpenCodeAsk added in v0.138.0

func (h *Hub) AnswerOpenCodeAsk(ctx context.Context, owner int64, host, session, window, promptID, choice string) (err error)

AnswerOpenCodeAsk answers the opencode ask promptID in one WINDOW of owner's host's session with choice, through the host, and waits for the host's outcome. nil means opencode took the answer.

func (*Hub) AnswerOpenCodeForm added in v0.189.0

func (h *Hub) AnswerOpenCodeForm(ctx context.Context, owner int64, host, session, window string, form OpenCodeForm, picks []OpenCodePick) (err error)

AnswerOpenCodeForm answers question promptID that the opencode window (session, window) waits on with picks (one per question of form, the form the host sent for it), through the host, and waits for its outcome. nil means opencode took the answer.

func (*Hub) AnswerWindow

func (h *Hub) AnswerWindow(ctx context.Context, owner int64, host, session, window string, qs []askq.Question, choices []askq.Choice, prior *askq.Progress) (err error)

AnswerWindow types choices for qs into the AskUserQuestion picker in the Claude pane of one WINDOW of owner's host's session (its tmux window id; "" = the session's active window), and waits for the host's outcome. prior is what an earlier answer is known to have left in that picker (nil: nothing); a refusal carries how many keys the picker has received (AskKeys).

func (*Hub) Attach

func (h *Hub) Attach(ctx context.Context, owner int64, host, session string, readOnly bool, stdin io.Reader, stdout io.Writer, resize <-chan provision.TermSize) error

Attach opens a terminal on owner's host's session and runs it until ctx ends, the host ends it, or the host's connection drops: what is written to stdin is typed (never, when readOnly), what the session shows arrives on stdout, and each size on resize is applied. It has provision.Provisioner's terminal shape, so internal/api's one terminal bridge serves both.

🔴 owner IS THE VIEWING PRINCIPAL'S USER, AND ANOTHER OWNER'S HOST IS NOT THERE AT ALL: the lookup is keyed by (owner, host), so it answers ErrHostOffline exactly as for a host that does not exist.

🔴 READ-ONLY IS ENFORCED HERE AS WELL AS ON EITHER SIDE OF IT. internal/api forwards no input to a read-only terminal; this drops stdin for a read-only stream without sending a byte, and refuses an interactive one outright when the host did not advertise -interactive; and the host attaches `tmux attach -r`, drops input for a read-only stream and refuses an interactive open it did not advertise. No single layer being wrong types into an operator's session.

It returns nil when the host reports the session's client exited cleanly, and when ctx ends (the browser left).

func (*Hub) AttachWindow

func (h *Hub) AttachWindow(ctx context.Context, owner int64, host, session, window string, readOnly bool, stdin io.Reader, stdout io.Writer, resize <-chan provision.TermSize) (err error)

AttachWindow is Attach on one WINDOW of the session (its tmux window id), or — window == "" — on the session's active window.

🔴 ON A PER-WINDOW HOST THE OPEN ALWAYS NAMES A WINDOW ID, resolved here even when the caller named only the session (hostConn.target). The host then shows that window through a viewer session of its own (internal/mirrorhost) and never through the operator's session, so neither viewing nor typing into a window moves what the operator is looking at.

func (*Hub) CancelAsk

func (h *Hub) CancelAsk(ctx context.Context, owner int64, host, session, window string) (note string, err error)

CancelAsk dismisses the AskUserQuestion picker in the Claude pane of one WINDOW of owner's host's session with one Escape, and waits for the host's outcome: nil means the Escape was sent, note what the host said about it ("" when the picker went; its note when it was still showing — no second Escape is sent). A refusal is one of the ask errors (ErrAskNoPicker, ErrAskUnrecognised, ErrAskBusy, ErrAskUnsupported, ErrAskRefused); one from before the host was asked wraps ErrAskNotSent.

func (*Hub) CatalogWindow

func (h *Hub) CatalogWindow(ctx context.Context, owner int64, host, session, window string) (_ Catalog, err error)

CatalogWindow asks owner's host for the catalog of one WINDOW of session (its tmux window id; "" = the session's active window) and waits for the answer.

🔴 owner IS THE VIEWING PRINCIPAL'S USER: the lookup is keyed by (owner, host), so another owner's host answers ErrHostOffline exactly as one that does not exist — and nothing is ever asked of it.

func (*Hub) CloseAgent added in v0.183.0

func (h *Hub) CloseAgent(ctx context.Context, owner int64, host string, req AgentCloseReq) (r AgentCloseResult, err error)

CloseAgent asks owner's host to end the agent in window req and waits for its answer. 🔴 ITS ONE CALLER is internal/api's end-session accept, on the owner's tap (a seam ledger pins that).

func (*Hub) Hosts

func (h *Hub) Hosts(owner int64) []HostView

Hosts is every host of owner — connected, or disconnected within offlineRetention — sorted by name.

func (*Hub) Online

func (h *Hub) Online(owner int64, host, session string) bool

Online reports whether owner's host is connected and lists session.

func (*Hub) OpenCodeForm added in v0.189.0

func (h *Hub) OpenCodeForm(ctx context.Context, owner int64, host, session, window, promptID string) (_ OpenCodeForm, err error)

OpenCodeForm asks owner's host for the whole form of question promptID that the opencode window (session, window) waits on, and waits for it.

func (*Hub) Paste

func (h *Hub) Paste(ctx context.Context, owner int64, host, session, text string, target PasteTarget) error

Paste types text into a pane of owner's host's session and presses Enter — the way ccd hands a provisioned agent a prompt (a bracketed paste, then Enter) — and waits for the host to confirm it. target says which pane it may be (PasteTarget).

🔴 IT IS A WRITE INTO THE OPERATOR'S SESSION, SO IT IS REFUSED UNLESS THE REQUEST'S SIGN-IN IS FRESH (internal/stepup) AND THE HOST ADVERTISED -interactive — both here, whatever the caller (internal/api) already checked, and the host refuses a paste it did not opt into again.

func (*Hub) PasteWindow

func (h *Hub) PasteWindow(ctx context.Context, owner int64, host, session, window, text string, target PasteTarget, opts ...PasteOption) error

PasteWindow is Paste into one WINDOW of the session (its tmux window id), or — window == "" — into the session's active window.

🔴 A PASTE NEVER MOVES ANYONE'S WINDOW. The host pastes into a PANE id (tmux's paste-buffer -t %<n>), which needs no client and no current window, so a message can be sent to a window nobody is looking at.

opts: ExpectTurn makes it a QUEUED paste, refused (ErrSuperseded) unless the window's turn is still the one it was decided on; ReportWindow reports the window id it resolved to.

func (*Hub) ScrollWindow

func (h *Hub) ScrollWindow(ctx context.Context, owner int64, host, session, window string, lines int) (err error)

ScrollWindow scrolls the active pane of one WINDOW of owner's host's session (its tmux window id; "" = the session's active window) through its history by lines (Msg.Lines: positive is back), and waits for the host's answer.

func (*Hub) ServeConn

func (h *Hub) ServeConn(ctx context.Context, owner int64, host string, ws *websocket.Conn) error

ServeConn runs one host's connection until it ends, and returns why.

🔴 owner AND host ARE THE TOKEN'S, DECIDED BY THE CALLER BEFORE THE UPGRADE, AND THE HELLO MUST NAME THE SAME HOST. The hello's own host field is never trusted to pick where sessions land: a token minted for host A that says hello as host B is refused here, before anything is registered.

A newer connection for the same (owner, host) replaces the older one (a restarted muster-mirror whose previous TCP connection has not timed out yet). A NEW host beyond MaxHosts is refused.

Registration is in memory only: nothing on this path waits on a database.

func (*Hub) SetListingNotify added in v0.170.0

func (h *Hub) SetListingNotify(fn func(owner int64, host string, windows []Window))

SetListingNotify installs the hook called (on its own goroutine) with a host's owner, its name and its windows after every listing the hub applies (a hello's and each sessions message): the host-dispatch reconciler's input.

func (*Hub) SetNotify

func (h *Hub) SetNotify(fn func(owner int64))

SetNotify installs the change nudge (a host connected, disconnected or changed its list), called with the OWNER of the host that changed — the one user whose sidebar lists it (accounts PR 3b: an SSE event reaches only its owner's streams). It is called on its own goroutine.

func (*Hub) SetOutcomesNotify added in v0.179.0

func (h *Hub) SetOutcomesNotify(fn func(owner int64, host string, seq uint64, windows []Window, outcomes map[string]WindowOutcome))

SetOutcomesNotify installs the hook called (on its own goroutine) with a host's owner and name, a snapshot number that grows with every call, and its current windows and outcomes, after every listing and every outcomes message the hub applies: the host-dispatch outcome reconciler's input. A receiver drops a snapshot older than one it has applied.

func (*Hub) SetSpawnReplyNotify added in v0.170.0

func (h *Hub) SetSpawnReplyNotify(fn func(owner int64, host string, m Msg))

SetSpawnReplyNotify installs the late-reply hook: called (on its own goroutine) with the owner and host of the CONNECTION every agent-spawned frame arrived on, and the frame, whether or not a waiter still waits for it. The hook acts as that owner and checks the row is that host's: a host can settle only its own owner's dispatches addressed to it.

func (*Hub) SetStatusNotify added in v0.165.0

func (h *Hub) SetStatusNotify(fn func(owner int64))

SetStatusNotify installs the hook called (on its own goroutine) with a host's owner whenever the status of any of that host's agent windows changes — busy, idle or waiting, or a window arriving or leaving with a status. The waiting-set hook (SetWaitingNotify) does not fire for a window going from busy to idle, which is exactly where a turn ends: the ask log (internal/api's askLogMirrorChanged) reads a plain-text question there.

func (*Hub) SetWaitingNotify

func (h *Hub) SetWaitingNotify(fn func(owner int64))

SetWaitingNotify installs the hook called (on its own goroutine) with a host's owner whenever the set of that host's windows whose Claude Code session reports StatusWaiting changes — a change no card draws, so the ordinary nudge (SetNotify) does not fire for it.

func (*Hub) SpawnAgent added in v0.170.0

func (h *Hub) SpawnAgent(ctx context.Context, owner int64, host string, dispatch int64, req AgentSpawnReq) (w AgentSpawned, err error)

SpawnAgent asks owner's host to start an agent for host dispatch dispatch and waits for its answer. ErrSpawnUnconfirmed after the wait: the request WAS written. 🔴 ITS ONE CALLER is internal/api's toolAgentDispatch (a seam ledger pins that): no HTTP route or token reaches a host spawn.

func (*Hub) SpawnResume

func (h *Hub) SpawnResume(ctx context.Context, owner int64, host, sid string) (w ResumedWindow, err error)

SpawnResume asks owner's host to start a window resuming Claude Code session sid, and waits for its answer.

func (*Hub) SubagentTail

func (h *Hub) SubagentTail(ctx context.Context, owner int64, host, session, window, agent string) (_ SubagentTail, err error)

SubagentTail asks owner's host for the recent steps of subagent agent of the Claude Code session in (session, window) — window "" being the session's active window — and waits for the answer.

🔴 owner IS THE VIEWING PRINCIPAL'S USER: the lookup is keyed by (owner, host), so another owner's host answers ErrHostOffline exactly as one that does not exist. The host resolves the window's Claude pane NOW and reads only that session's own subagents directory.

func (*Hub) Watch

func (h *Hub) Watch(ctx context.Context, owner int64, host, session, gen string, offset int64, out func(Msg) error) error

Watch streams owner's host's session's Claude Code transcript to out until ctx ends (nil), the host ends it, or the connection drops. gen and offset ask to RESUME (the browser reconnecting with what it already drew); the host honours them only when gen is still the session's transcript, and otherwise starts with a Reset backfill.

Each batch out receives is an events Msg exactly as the host sent it (bounded by MaxBatchEvents / MaxBatchBytes, every field capped by cctranscript). An out error ends the watch.

func (*Hub) WatchWindow

func (h *Hub) WatchWindow(ctx context.Context, owner int64, host, session, window, gen string, offset int64, out func(Msg) error) (err error)

WatchWindow is Watch on one WINDOW of the session (its tmux window id), or — window == "" — on the session's active window: the transcript of the Claude Code session running in THAT window's pane.

An opencode window's view is the same stream, its Gen the conversation's id.

type Msg

type Msg struct {
	Type    string `json:"type"`
	Version int    `json:"version,omitempty"`
	// Host is the registering host's name (hello only). It must equal the host
	// the presented token was minted for.
	Host string `json:"host,omitempty"`
	// Sessions is the host's full tmux session list (hello, sessions).
	Sessions []string `json:"sessions,omitempty"`
	// Labels (hello, sessions) is an optional DISPLAY name per session —
	// session → label, e.g. "scratch13" → "mango:1" (the host's codename for the
	// session plus its active window). Display only: a session is still
	// addressed by its name everywhere (opens, URLs), because a label changes
	// whenever the active window does.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS: an older muster's JSON
	// decode ignores the unknown field, and a host that sends none is shown by
	// its raw session names. muster keeps only entries NormalizeLabels accepts
	// and drops the rest — never the hello.
	Labels map[string]string `json:"labels,omitempty"`
	// Activity (hello, sessions) is, per session, WHEN it was last active on
	// the host: Unix seconds, floored to ActivityBucket. muster lists mirrored
	// sessions most recently active first (Ordered), and each card prints it
	// as "active … ago". Ordering and display only — it never addresses
	// anything.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, exactly like Labels: an
	// older muster ignores the field, and a host that sends none is listed in
	// the order it always was (host, then session name). muster keeps only
	// entries NormalizeActivity accepts and drops the rest — never the hello.
	Activity map[string]int64 `json:"activity,omitempty"`
	// Interactive (hello) is the host ADVERTISING that it accepts interactive
	// attaches — muster-mirror's -interactive flag. Without it the host is
	// read-only: muster offers no Interactive switch and refuses a rw attach,
	// and the host refuses one itself.
	Interactive bool `json:"interactive,omitempty"`
	// PanePaste (hello) is the host ADVERTISING that a paste may name a
	// session's ACTIVE PANE whatever runs in it (AnyPane) — a shell, another
	// TUI — and not only a Claude Code pane: what the Terminal view's composer
	// needs for a session with no rendered view. Only an -interactive v2 host
	// whose backend can do it sets it.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like Labels: an older
	// muster ignores the field and never asks; an older host never sets it, so
	// muster never sends it AnyPane (Hub.Paste) — and if it somehow did, that
	// host would ignore the unknown field and apply its Claude-only rule, which
	// REFUSES a pane that is not Claude Code. The failure direction is "not
	// sent", never "sent somewhere unintended".
	PanePaste bool `json:"panePaste,omitempty"`
	// PaneScroll (hello) is the host ADVERTISING that it scrolls a window's
	// active pane through its history in tmux COPY-MODE (scroll / scrolled):
	// what the Terminal view's drag-to-scroll needs, since the viewer's own tmux
	// client paints only the visible screen and so the browser holds no history.
	// Only an -interactive v2 host whose backend can do it sets it.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like PanePaste: an older
	// muster ignores the field and never asks; an older host never sets it, so
	// muster never sends it a scroll and the page draws no gesture at all. (An
	// older host that somehow got one would ignore the unknown type — its read
	// loop has no default case — and muster's wait would time out; it is never
	// sent one.)
	PaneScroll bool `json:"paneScroll,omitempty"`
	// StatusReport (hello) is the host ADVERTISING that it reports each window's
	// Claude Code status (Window.Status). Only a per-window v2 host sets it.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like PanePaste: an older
	// muster ignores it; an older host never sets it, and muster then treats
	// every one of its windows' status as unknown — so nothing queued for it is
	// sent (Hub.AgentState says why).
	StatusReport bool `json:"statusReport,omitempty"`
	// CatalogReport (hello) is the host ADVERTISING that it answers a catalog
	// request (TypeCatalog): a window's Claude Code commands and skills, for the
	// composer's `/` menu (catalog.go).
	// Only a v2 host sets it.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like PaneScroll: an older
	// muster ignores it and never asks; an older host never sets it, so muster
	// never asks it and the composer offers the built-in commands alone.
	CatalogReport bool `json:"catalogReport,omitempty"`
	// Catalog (cataloged) is the answer to catalog request ID; nil with Error
	// set when the host refused it.
	Catalog *Catalog `json:"catalog,omitempty"`
	// ID names one terminal stream (open, resize, close, closed).
	ID uint32 `json:"id,omitempty"`
	// Session is the tmux session an open attaches to.
	Session string `json:"session,omitempty"`
	// ReadOnly asks the host to attach `tmux attach -r` and to drop input.
	ReadOnly bool   `json:"readOnly,omitempty"`
	Cols     uint16 `json:"cols,omitempty"`
	Rows     uint16 `json:"rows,omitempty"`
	// Error is why a stream ended (closed), why a paste failed (pasted), or why
	// a connection is refused.
	Error string `json:"error,omitempty"`

	// Claude (hello, sessions) is the subset of Sessions whose active pane runs
	// Claude Code with a transcript the host can read: the sessions muster opens
	// in the rendered view by default.
	Claude []string `json:"claude,omitempty"`
	// Gen names the transcript a watch / events refers to (the Claude Code
	// session id). Offset is a byte offset into it — always a line boundary
	// (cctranscript): a watch's Offset is where to RESUME (honoured only when
	// Gen still names the session's current transcript, else the host backfills),
	// an events' Offset is where the next batch continues from.
	Gen    string `json:"gen,omitempty"`
	Offset int64  `json:"offset,omitempty"`
	// Reset (events): drop what was drawn; Events starts the transcript Gen
	// over (a fresh backfill, a /clear, a rotated or truncated file).
	Reset bool `json:"reset,omitempty"`
	// Busy (events): Claude Code reports a turn running (its session status).
	Busy bool `json:"busy,omitempty"`
	// StatusSince (events) is the time Claude Code wrote the status Busy was
	// read from (its statusUpdatedAt, Unix ms on the HOST's clock): the same
	// number the host lists as Window.StatusSince. So a turn end on the stream
	// names the exact status token of the turn's own idle, and muster can tell
	// it from the idle BEFORE the turn without guessing (suggested replies,
	// internal/api's suggestTracker). A status that moved with Busy unchanged
	// (a turn the host never saw busy) is sent as a marker of its own.
	// 🔴 NO VERSION BUMP: an older host never sends it (0), and an older muster
	// ignores it.
	StatusSince int64                `json:"statusSince,omitempty"`
	Events      []cctranscript.Event `json:"events,omitempty"`
	// PromptIndex (events) marks the message that carries the transcript's
	// PROMPT INDEX: Prompts is every prompt in the WHOLE file up to the
	// backfill's end (cctranscript.Prompts), the newest BoundPrompts keeps, and
	// PromptsMore how many earlier ones it dropped. The host sends it once per
	// Reset, as its own events message after the backfill, with no events and
	// the backfill's own Offset and Busy — so the message index can list a
	// prompt the backfill never loaded.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like Labels: an older
	// muster ignores the fields and relays the message as an empty batch at an
	// offset it already had; an older host never sends it, and the view lists
	// the prompts on the page and says that is all it can show.
	PromptIndex bool                     `json:"promptIndex,omitempty"`
	Prompts     []cctranscript.PromptRef `json:"prompts,omitempty"`
	PromptsMore int                      `json:"promptsMore,omitempty"`
	// Text is what a paste types into the session's pane.
	Text string `json:"text,omitempty"`
	// AnyPane (paste) asks for the session's ACTIVE pane whatever runs in it.
	// Unset — every paste before this field existed — the host pastes only into
	// a pane it resolves as Claude Code NOW, and refuses otherwise: the rendered
	// view's send must never land a prompt meant for Claude in a shell.
	AnyPane bool `json:"anyPane,omitempty"`
	// Runtime (answer) is the agent runtime an answer is for: "opencode"
	// relays it through opencode's API (OpenCodeReply); "" is Claude Code's
	// picker. A host never trusts it to OPEN anything: it re-checks what runs
	// in the pane NOW. On a PASTE it names a runtime's gated send
	// (RuntimeSpec.GatedSend: "opencode", through its API), with Since and
	// MessageID; an older host, which never advertised that send, is never
	// sent one.
	Runtime string `json:"runtime,omitempty"`
	// Since (paste, with Runtime) is the window's StatusSince muster decided
	// the gated send on: the host sends only while the window is still idle
	// since exactly then.
	Since int64 `json:"since,omitempty"`
	// MessageID (paste, with Runtime "opencode") is the id the message is
	// posted under (OpenCodeMessageID): the same send retried posts the same
	// id, and opencode admits it once.
	MessageID string `json:"messageID,omitempty"`
	// AgentSession (paste, with Runtime) is the session the message was
	// written for — the sender's view's, or a queued row's — which the hub has
	// checked is the one its window list names now (ShownSessionCheck); so
	// the ONLY session the host may post to: it refuses
	// (PasteRefusalOpenCodeMoved) when the pane resolves to any other now,
	// and refuses a pane bound by verification (Window.AgentBind) when the
	// paste names none. 🔴 BACKWARD-COMPATIBLE BOTH WAYS: an older host
	// ignores it and sends only to launcher-bound panes, as before; an older
	// muster never sends it, and so never reaches a verified pane.
	AgentSession string `json:"agentSession,omitempty"`
	// Context (events) is the agent's context fill for the view's header
	// readout, from a runtime that reports it beside its events (opencode:
	// AgentContext). Sent when it changed, and on the batch that ends a
	// Reset's backfill. 🔴 BACKWARD-COMPATIBLE BOTH WAYS: an older muster
	// ignores it (no readout, as before); an older host never sends it.
	Context *AgentContext `json:"context,omitempty"`
	// Lines (scroll) is how far to scroll the pane's history: positive is BACK
	// (tmux scroll-up, older output), negative is forward (scroll-down, toward
	// the live screen). 0 and anything beyond MaxScrollLines either way is
	// refused (ClampScroll is the bound both halves apply).
	Lines int `json:"lines,omitempty"`
	// Refusal (scrolled, answered, pasted) is WHICH KIND of refusal Error is,
	// for muster to act on without reading the host's prose: ScrollRefusalMode
	// or ScrollRefusalUnsupported on scrolled, an AskRefusal* on answered, a
	// PasteRefusal* on pasted; "" for any other (and for every refusal an
	// older host sends — which muster then treats as a plain refusal, never as
	// "this host cannot scroll"). Backward-compatible both ways, like PaneScroll.
	Refusal string `json:"refusal,omitempty"`
	// AskAnswer (hello) is the host ADVERTISING that it types answers into
	// Claude Code's AskUserQuestion picker (TypeAnswer) — an -interactive host
	// whose muster-mirror can. 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH
	// WAYS, like PaneScroll: an older muster ignores it, and an older host
	// never sets it, so muster never sends it an answer (the question is the
	// terminal's to answer there).
	AskAnswer bool `json:"askAnswer,omitempty"`
	// Ask (answer) is what to type: the questions as muster showed them, and
	// one choice per question.
	Ask *AskTyping `json:"ask,omitempty"`
	// AskCancel (hello) is the host ADVERTISING that it dismisses an
	// AskUserQuestion picker with one Escape (TypeCancelAsk) — an -interactive
	// host whose muster-mirror can. 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE
	// BOTH WAYS, like AskAnswer: an older host never sets it, so muster never
	// sends it a cancel (and the card offers none); an older muster ignores it.
	AskCancel bool `json:"askCancel,omitempty"`
	// Keys (answered) is how many keys of the answer's plan the picker has
	// received from muster (askdrive.DriveFrom): what the next answer's
	// AskTyping.Prior is when this one stopped part way. 🔴 NO VERSION BUMP,
	// BACKWARD-COMPATIBLE BOTH WAYS: an older host never sets it (0: nothing
	// muster can vouch for), and an older muster ignores it.
	Keys int `json:"keys,omitempty"`
	// Screen (answered, a refusal) is the pane as the host read it when the
	// answer stopped — plain text, redacted and then capped at MaxAskScreen by the host (CapAskScreen) — for
	// the answer-attempt log (internal/askattempt redacts and caps it again
	// before it is stored). 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH
	// WAYS: an older host never sets it (no snapshot), an older muster
	// ignores it.
	Screen string `json:"screen,omitempty"`
	// OpenCodeAnswer (hello) is the host ADVERTISING that it relays an answer
	// to an opencode ask — a permission request, a question-tool form —
	// through the opencode server's API (opencode_answer.go): an -interactive
	// v2 host that holds an opencode token — the same gate as AskAnswer.
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like AskCancel: an
	// older muster ignores it; an older host never sets it, so muster never
	// sends it an answer, and the ask says to answer it in the terminal.
	OpenCodeAnswer bool `json:"openCodeAnswer,omitempty"`
	// OpenCodeSend (hello) is the host ADVERTISING that it sends a message to
	// an opencode session through the opencode server's API (a paste with
	// Runtime "opencode", docs/design/opencode-first-class.md): an
	// -interactive v2 host started with -opencode-send that holds an opencode
	// token. Only to a window it lists as AgentSend (launcher-bound).
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like OpenCodeAnswer:
	// an older muster ignores it; an older host never sets it, so muster sends
	// it no opencode message and the composer says why.
	OpenCodeSend bool `json:"openCodeSend,omitempty"`
	// OpenCodeForms (hello) is the host ADVERTISING that it sends a pending
	// opencode question's whole form (TypeOpenCodeForm → TypeOpenCodeFormed,
	// Form) and takes its answer as OpenCodeReply.Picks (opencode_form.go):
	// an -interactive v2 host that holds an opencode token. 🔴 NO VERSION
	// BUMP, BACKWARD-COMPATIBLE BOTH WAYS: an older muster ignores it; an
	// older host never sets it, so muster never asks it for a form.
	OpenCodeForms bool `json:"openCodeForms,omitempty"`
	// Form (opencode-formed) is the form asked for; nil with Error set when
	// refused.
	Form *OpenCodeForm `json:"form,omitempty"`
	// OpenCodeReply (answer, with Runtime "opencode") is the opencode ask to
	// answer and how: the PromptID muster showed (Pending.PromptID) and one of
	// its offered answers (Pending.Offers). An older host, which never
	// advertised OpenCodeAnswer, is never sent one.
	OpenCodeReply *OpenCodeReply `json:"openCodeReply,omitempty"`
	// ResumeSpawn (hello) is the host ADVERTISING that it resumes an ended
	// Claude Code session in a new window (TypeSpawnResume, resume.go): an
	// -interactive v2 host started with -resume-spawn. 🔴 NO VERSION BUMP,
	// BACKWARD-COMPATIBLE BOTH WAYS, like PaneScroll: an older muster ignores
	// it; an older host never sets it, so muster never asks it to resume.
	ResumeSpawn bool `json:"resumeSpawn,omitempty"`
	// AgentSpawn (hello) is the runtimes this host STARTS for the chief
	// (TypeAgentSpawn, agentspawn.go): -interactive with -agent-spawn, and
	// each runtime's binary found. Empty for every other host.
	AgentSpawn []string `json:"agentSpawn,omitempty"`
	// AgentSpawnSkipPermissions (hello) is the host saying it starts the
	// CLAUDE CODE agents it spawns WITHOUT permission prompts
	// (-agent-spawn-skip-permissions, on by default; never on a root mirror,
	// where Claude Code refuses bypassPermissions). It is one bool per host,
	// not per runtime, because Claude Code's is the only wording muster varies
	// by it: an opencode spawn is told it does not ask either way. muster only
	// words its prompts by it (what the agent and the chief are told): the HOST
	// builds the argv, and nothing muster sends changes it. An older host never
	// sets it, and starts in normal permission mode, which is what false reads as.
	AgentSpawnSkipPermissions bool `json:"agentSpawnSkipPermissions,omitempty"`
	// AgentSpawnClones (hello) is the host ADVERTISING that it answers an
	// agent-clones request (TypeAgentClones, clones.go) and honours an
	// agent-spawn's clone hint (AgentSpawnReq.Clone), checked against its own
	// clones. Backward-compatible both ways: an older muster ignores it and
	// sends no hint; an older host never sets it, so muster asks it nothing
	// and sends it no hint (and a hint it was sent anyway it ignores, refusing
	// a repository with several clones as it always did).
	AgentSpawnClones bool `json:"agentSpawnClones,omitempty"`
	// CloneRepo is an agent-clones request's repository (<owner>/<repo>);
	// Clones an agent-clones-list's answer (clones.go).
	CloneRepo string       `json:"cloneRepo,omitempty"`
	Clones    []AgentClone `json:"clones,omitempty"`
	// Dispatch is the host dispatch an agent-spawn / agent-spawned is for, or
	// the one a paste is for (ForDispatch: the host checks the window's tag).
	Dispatch int64 `json:"dispatch,omitempty"`
	// Spawn is an agent-spawn's request; Spawned an agent-spawned's window.
	Spawn   *AgentSpawnReq `json:"spawn,omitempty"`
	Spawned *AgentSpawned  `json:"spawned,omitempty"`
	// AgentClose (hello) is the host ADVERTISING that it ends an agent window
	// on muster's request (TypeAgentClose, agentclose.go): -interactive, and a
	// backend that can close a window. Backward-compatible both ways.
	AgentClose bool `json:"agentClose,omitempty"`
	// CloseReq is an agent-close's window; CloseResult an agent-closed's
	// outcome.
	CloseReq    *AgentCloseReq    `json:"closeReq,omitempty"`
	CloseResult *AgentCloseResult `json:"closeResult,omitempty"`

	// SubagentReport (hello) is the host ADVERTISING that it answers a
	// subagent tail request (TypeSubagentTail). Backward-compatible both ways,
	// like CatalogReport.
	SubagentReport bool `json:"subagentReport,omitempty"`
	// SubagentList (events) marks a message carrying the view's subagent
	// summaries: Subagents is the WHOLE list (empty is a list too). Set on
	// every backfill's Reset batch by a host that reports subagents.
	SubagentList bool       `json:"subagentList,omitempty"`
	Subagents    []Subagent `json:"subagents,omitempty"`
	// Agent (subagent-tail) is the subagent whose steps are asked for.
	Agent string `json:"agent,omitempty"`
	// Tail (subagent-tailed) is the answer; nil with Error set when refused.
	Tail *SubagentTail `json:"tail,omitempty"`

	// QueuedList (events) marks a message carrying the messages Claude Code
	// has queued itself: Queued is the WHOLE list, oldest first (empty is a
	// list too). Set on every backfill's Reset batch and resume marker by a
	// host that reads the queue. Backward-compatible both ways, like
	// SubagentList.
	QueuedList bool     `json:"queuedList,omitempty"`
	Queued     []string `json:"queued,omitempty"`

	// Windows (hello, sessions) is EVERY WINDOW of every session on the host,
	// one entry each: what muster lists when it is present. A host that sends
	// it is a PER-WINDOW host; it still sends Sessions / Labels / Activity /
	// Claude beside it, describing each session by its ACTIVE window exactly as
	// before, for a muster that predates this field.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like Labels:
	//   - an older muster's JSON decode ignores the field and lists the host per
	//     session from the fields it always read; it never sends Window, so the
	//     host serves it the session's active window as it always did;
	//   - an older host sends none, and muster lists it per session, addresses it
	//     by session name alone, and never sends it Window.
	// muster keeps only what NormalizeWindows accepts and derives its own
	// per-session view of a per-window host from Windows — never from the
	// host's Sessions, so the two cannot disagree.
	Windows []Window `json:"windows,omitempty"`
	// HostLimit (hello, sessions) is a usage limit the host's Claude Code
	// sessions are under right now, across ALL its Claude windows — the limit
	// is the account's, not a window's, and Windows carries a TurnError on at
	// most MaxTurnErrorWindows of them. nil when none (turnerror.go).
	// Backward-compatible both ways, like Windows' TurnError.
	HostLimit *HostLimit `json:"hostLimit,omitempty"`
	// Window (open, watch, paste) is the tmux window id (Window.ID) the request
	// is for, within Session. Empty — every request before this field existed,
	// and every request to a per-session host — is the session's ACTIVE window.
	Window string `json:"window,omitempty"`

	// Repos (repos) is, per window id, the short name of the repository the
	// window works in — the WHOLE map each time (repos.go).
	Repos map[string]string `json:"repos,omitempty"`
	// GitHubRepos (repos) is, per window id, the GitHub <owner>/<name> the
	// window's checkout's origin names — on the same message as Repos, the
	// WHOLE map each time (repos.go).
	GitHubRepos map[string]string `json:"github_repos,omitempty"`

	// Work (work) is, per window id, the subagents and background shells its
	// Claude Code session has running — the WHOLE map each time (work.go).
	Work map[string]WindowWork `json:"work,omitempty"`
	// Colors (colors) is, per window id, the window's tmux identity colour as
	// lowercase #rrggbb — the WHOLE map each time (work.go).
	Colors map[string]string `json:"colors,omitempty"`
	// Outcomes (outcomes) is, per window id, the final reply of an idle
	// opencode window the chief started — the WHOLE map each time (outcomes.go).
	Outcomes map[string]WindowOutcome `json:"outcomes,omitempty"`
	// Previews (previews) is, per window id, how many of its web servers the
	// host offers and how many previews of it are open — the WHOLE map each
	// time (previews.go).
	Previews map[string]WindowPreviews `json:"previews,omitempty"`

	// Traceparent (every request muster sends a host: open, watch, paste,
	// scroll, catalog, answer, cancel-ask, subagent-tail) is the W3C trace
	// context of the server span that sent it, so the host's spans for the
	// request are children of it — one trace from the browser to the host's
	// transcript read. "" while the server's tracing is off.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS: an older host's JSON
	// decode ignores the field (its spans simply do not exist); a host whose
	// tracing is off ignores it too; an older muster never sends it.
	// TestAnOlderHostIgnoresTheTraceContext drives both directions.
	Traceparent string `json:"traceparent,omitempty"`
}

Msg is every control message on the tunnel, as one JSON text frame.

func BatchLines

func BatchLines(lines []cctranscript.Line, from int64) []Msg

BatchLines frames lines — read from a transcript starting at offset from — as events messages, each within MaxBatchEvents and MaxBatchBytes ENCODED, with Offset set to that message's exact resume point: just past the last line it carries whole. A line whose events do not fit one message is split; the messages before its last part then resume at the line's START, so a resume there re-sends the line — and a line with several events is tool results, which the view keys by tool id, so a repeat redraws rather than duplicates. Type, ID and Gen are the caller's to fill.

type OpenCodeForm added in v0.189.0

type OpenCodeForm struct {
	PromptID  string             `json:"promptId"`
	Title     string             `json:"title,omitempty"`
	Questions []OpenCodeQuestion `json:"questions"`
}

OpenCodeForm is an opencode ask's question form, as the card draws it.

func NormalizeOpenCodeForm added in v0.189.0

func NormalizeOpenCodeForm(f OpenCodeForm) (OpenCodeForm, bool)

NormalizeOpenCodeForm is f as the wire carries it — its text cleaned to one line each, cut to its bound — and false when it is not one muster answers: no prompt id, no question, more questions or options than the bounds, a question with no options it does not let the person answer themselves, a key that is empty, too long or repeated. Applied by BOTH halves.

type OpenCodeNotIdleError added in v0.160.0

type OpenCodeNotIdleError struct{ Status string }

OpenCodeNotIdleError refuses a send to an opencode window that is not idle (Hub.PasteWindow). Nothing was sent to the host. Status is the window's ("" unknown).

func (*OpenCodeNotIdleError) Error added in v0.160.0

func (e *OpenCodeNotIdleError) Error() string

func (*OpenCodeNotIdleError) Unwrap added in v0.160.0

func (e *OpenCodeNotIdleError) Unwrap() error

type OpenCodeOption added in v0.189.0

type OpenCodeOption struct {
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
}

OpenCodeOption is one option of a question.

type OpenCodePick added in v0.189.0

type OpenCodePick struct {
	Key   string `json:"key"`
	Picks []int  `json:"picks,omitempty"`
	Other string `json:"other,omitempty"`
}

OpenCodePick is the answer to one question of a form (OpenCodeReply.Picks): the indexes of the chosen options, and the person's own answer ("" none).

type OpenCodeQuestion added in v0.189.0

type OpenCodeQuestion struct {
	Key      string           `json:"key"`
	Header   string           `json:"header,omitempty"`
	Question string           `json:"question"`
	Multiple bool             `json:"multiple,omitempty"`
	Custom   bool             `json:"custom,omitempty"`
	Options  []OpenCodeOption `json:"options"`
}

OpenCodeQuestion is one question of a form: Key is the field's key ("q0"), Header its short title, Question its text; Multiple a multi-select; Custom that it takes an answer of the person's own.

type OpenCodeReply added in v0.138.0

type OpenCodeReply struct {
	// PromptID is the request's or form's id muster showed (Pending.PromptID).
	PromptID string `json:"promptId"`
	// Choice is the answer: one of OpenCodePermissionChoices for a permission
	// request, one of the question's option labels for a form.
	Choice string `json:"choice"`
	// Picks is a whole form's answer (opencode_form.go) in place of Choice:
	// one per question, sent only to a host that advertised OpenCodeForms
	// (an older host, which reads Choice alone, refuses an empty one).
	Picks []OpenCodePick `json:"picks,omitempty"`
}

OpenCodeReply is an opencode ask's answer on the wire (Msg.OpenCodeReply).

type OpenStats

type OpenStats struct {
	// Sent is when the request frame was written to the host; First when the
	// first batch (watch) or the first output (terminal) was read from it.
	Sent, First time.Time
}

OpenStats is what the hub measured opening one watch or terminal, on muster's own clock: the caller's log line reads it (WithOpenStats). What the host spent inside that round trip is its own spans' (host.*), not a field here.

type PGStore

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

PGStore is Store over Postgres (migration 0008).

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG builds the Postgres store.

func (*PGStore) Authenticate

func (s *PGStore) Authenticate(ctx context.Context, token string) (Token, error)

Authenticate looks the token up by hash among unrevoked tokens and stamps its last use.

⚠ A STRING WITHOUT THE PREFIX IS REFUSED BEFORE THE QUERY. That is not the security property — the hash lookup is, and no other credential's hash is in this table — it only keeps a hook token pasted into the wrong config from costing a database round trip per reconnect.

func (*PGStore) CreateToken

func (s *PGStore) CreateToken(ctx context.Context, host string) (string, Token, error)

func (*PGStore) ListTokens

func (s *PGStore) ListTokens(ctx context.Context) ([]Token, error)

func (*PGStore) RevokeToken

func (s *PGStore) RevokeToken(ctx context.Context, id int64) (bool, error)

func (*PGStore) TokenLive

func (s *PGStore) TokenLive(ctx context.Context, id int64) (bool, error)

type PasteOption

type PasteOption func(*PasteOptions)

PasteOption is an option of PasteWindow.

func ExpectTurn

func ExpectTurn(t Turn) PasteOption

ExpectTurn makes the paste a QUEUED one, decided on turn t: the hub refuses it with ErrSuperseded — before anything reaches the host — when another paste into the window is in flight, or the window's Since or Pasted is no longer t's (another paste, or a status write, came between the decision and this paste). A person's own Send carries no turn and is never refused so.

func ForDispatch added in v0.170.0

func ForDispatch(dispatch int64) PasteOption

ForDispatch stamps a paste with the host dispatch it is for (a chief's forward into a host-spawned window). The HOST then refuses it unless the window's own @muster-dispatch equals it (PasteRefusalNotMusterWindow): the real bound on forwarding (docs/design/chief-dispatch.md 3.10).

func MessageKey added in v0.160.0

func MessageKey(key string) PasteOption

MessageKey has a gated send post its message under the id derived from key (OpenCodeMessageID): what makes a RETRY of the same send — the composer's Send again of a message that may have landed, a queued row tried again — land at most once. internal/api passes the send's nonce, or the nonce of the first try of a message it holds as may-have-landed.

func ReportWindow

func ReportWindow(dst *string) PasteOption

ReportWindow has PasteWindow write the window id it resolved to into dst (window "" being the session's active window), once it has resolved it.

func ShownSession added in v0.189.0

func ShownSession(id string) PasteOption

ShownSession names the agent session (Window.AgentSession) the sender's view was showing when the message was written — the composer's, or the one a queued row was stored with. A gated send goes only while the window shows exactly that session (ShownSessionCheck); "" names none.

type PasteOptions

type PasteOptions struct {
	Expect *Turn
	Window *string
	// Key is what a gated send's message id is derived from (MessageKey).
	Key string
	// Dispatch is the host dispatch the paste is for (ForDispatch), 0 none.
	Dispatch int64
	// Shown is the agent session the sender's view was showing for the
	// window (ShownSession), "" for none named.
	Shown string
}

PasteOptions is what a list of PasteOptions asks for: Expect, the turn a queued paste was decided on (nil: a person's paste); Window, where to report the window id the paste resolved to (nil: nowhere).

func PasteOptionsOf

func PasteOptionsOf(opts ...PasteOption) PasteOptions

PasteOptionsOf applies opts. A PasteWindow implementation reads its options through it (the hub, and internal/api's test fakes).

type PasteRefusedError

type PasteRefusedError struct {
	Why     string
	Refusal string
	Cause   error
}

PasteRefusedError is ErrPasteRefused with the host's reason (Why, its prose, never parsed) and the kind it named (Refusal, a PasteRefusal* or "").

Cause is set when MUSTER refused it, before anything was sent (the Claude prompt guard's server half: ErrClaudeWaiting); nil for a refusal the host itself sent.

func (*PasteRefusedError) Error

func (e *PasteRefusedError) Error() string

func (*PasteRefusedError) Unwrap

func (e *PasteRefusedError) Unwrap() []error

type PasteTarget

type PasteTarget int

PasteTarget is WHICH pane of a session a paste may land in.

const (
	// PasteClaude: only a pane the host resolves as Claude Code — the rendered
	// view's composer. A session whose pane runs anything else is refused, on
	// muster and again on the host: a prompt written for Claude must never be
	// typed into a shell.
	PasteClaude PasteTarget = iota
	// PasteActivePane: the session's active pane, whatever runs in it — the
	// Terminal view's composer, where the person is looking at that pane.
	PasteActivePane
)

type Pending

type Pending struct {
	Summary string `json:"summary,omitempty"`
	Tool    string `json:"tool,omitempty"`
	Last    string `json:"last,omitempty"`
	// THE NAMED ASK: a waiting OPENCODE window's Pending also says which ask
	// it waits on, and the one its host can answer. Never on a Claude window
	// (boundPending drops them there), so a Claude window's bytes on the wire
	// are unchanged; an older muster ignores them, and an older host never
	// sends them (muster then shows its generic line). A kind muster does not
	// know (an older host's Hermes "approval", "clarify" or "sudo") is
	// dropped by CleanPending, and with it the window's named ask.
	//
	// Kind is PendingPermission or PendingQuestion; "" otherwise.
	Kind string `json:"kind,omitempty"`
	// Detail is a permission's description, capped at MaxPendingDetail like
	// the rest.
	Detail string `json:"detail,omitempty"`
	// PromptID is opencode's id for the request or form ("per…", "frm_…") —
	// what an answer names, so muster can only answer the ask it SHOWED.
	PromptID string `json:"promptId,omitempty"`
	// Choices are the answers muster may send for a permission's PromptID,
	// space-separated: a subset of OpenCodePermissionChoices, in that order.
	// Empty without a PromptID. (A string, not a slice, so a Pending stays
	// comparable with ==.)
	Choices string `json:"choices,omitempty"`
	// Options are an opencode QUESTION's option labels, one per line, when
	// muster can answer it (one single-select question of 1..MaxPendingOptions
	// options, each label within MaxPendingOption runes and unchanged by
	// cleaning — an answer is the label itself, so a cut one could not be
	// sent back). "" otherwise: the question is then the terminal's.
	Options string `json:"options,omitempty"`
}

Pending is WHAT a waiting Claude Code session is waiting on, as its host read it from the session's transcript (internal/mirrorhost's PendingOf): what the attention queue shows instead of a generic "waiting" line.

  • Summary is the pending action in one short line: the last tool call that has no result yet ("Bash: npm publish", "Edit internal/api/x.go", the question an AskUserQuestion asks), "" when the transcript shows none.
  • Tool is that call's tool as a NAME only ("Bash", "Edit", "MCP server/tool"), "" when there is none: what a notification may say.
  • Last is the last thing Claude said (its last text), whitespace-collapsed.

🔴 TEXT FROM THE SESSION, SHOWN ON A PAGE: every field is capped in RUNES (MaxPendingSummary, MaxPendingTool, MaxPendingLast), stripped of every control and format character and whitespace-collapsed (CleanPending) — by the host before sending and by muster again on receipt. The host also redacts what looks like a secret before it sends (internal/redact's Secrets, called by internal/mirrorhost). Only Tool ever reaches a lock screen: the summary and the last words are shown on the queue page, never in a push.

🔴 BOUNDED LIST-WIDE, LIKE OtherClaude: only a window that is Claude and StatusWaiting keeps one, and at most MaxPendingWindows windows of a list (the most recently waiting) carry one, so the window list's worst case grows by a fixed ~17 KiB of the frame's last few percent: 1,030,215 of 1,048,576 bytes with it (TestTheLargestWindowListFitsOneFrame encodes it at its bound).

🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS: an older muster ignores the field (unknown JSON key); an older host never sends it, and muster then shows its own generic line.

func CleanPending

func CleanPending(p *Pending) *Pending

CleanPending is p as the wire carries it: each field through cleanLine and capped at its rune bound (a cut ends "…"). nil when nothing is left of any field.

func (Pending) Offers

func (p Pending) Offers(choice string) bool

Offers reports whether p offers choice as an answer: one of its Choices, or — for an opencode question — one of its Options.

func (Pending) OptionList added in v0.138.0

func (p Pending) OptionList() []string

OptionList is p's Options, one label each; nil for none.

type Place added in v0.173.0

type Place struct {
	Code, Host string
	// Addr is the window's tmux address on its host ("scratch13:1", Address),
	// "" when unknown; Offline marks a window whose host has dropped and the hub
	// still lists. Neither is shown by String: they are for a title that must
	// name a window by its typeable target too (internal/api codenamePlace).
	Addr    string
	Offline bool
}

Place is a window's place as "Show tmux sessions" adds it (internal/api tmuxPlace): its codename — the host's label for it ("mango:1"), else its tmux address — and its host, kept APART so a session whose name already IS the codename can be told without parsing "mango:1 @ atlas" back. The zero value is "no window".

func (Place) String added in v0.173.0

func (p Place) String() string

String is the place as it is shown: "mango:1 @ atlas" (TitleAt).

type ResumeRefusedError

type ResumeRefusedError struct {
	Kind, Why string
}

ResumeRefusedError is ErrResumeRefused with the host's refusal: Kind is a ResumeRefusal* ("refused" for one the host did not classify), Why its prose.

func (*ResumeRefusedError) Error

func (r *ResumeRefusedError) Error() string

func (*ResumeRefusedError) Unwrap

func (r *ResumeRefusedError) Unwrap() error

type ResumedWindow

type ResumedWindow struct {
	Session string
	Window  string
}

ResumedWindow is the window a host started for a resume.

type RuntimeSpec

type RuntimeSpec struct {
	// Name is the runtime's wire name (RuntimeClaude, RuntimeOpenCode).
	Name string
	// Kind is what a list names a window of it (SessionView.Kind).
	Kind string
	// Caps is what muster can do with its windows.
	Caps Capabilities
	// OnWire: a host names a window of it as Window.Runtime, and
	// NormalizeWindows keeps that. Claude Code travels as Window.Claude
	// instead; a stub nothing reports is not on the wire.
	OnWire bool
	// KeyPrefix qualifies the window's AgentSession into its stored session
	// key ("opencode:"); "" for a runtime whose session is its own key (Claude
	// Code) or that names none.
	KeyPrefix string
	// ViewNeedsSession: a window of it has a rendered view only once its
	// host names the conversation (Window.AgentSession).
	ViewNeedsSession bool
	// TurnErrors: an idle window of it carries how its latest turn ended in
	// an error (Window.TurnError, turnerror.go) — read from Claude Code's
	// transcript, or opencode's session messages.
	TurnErrors bool
	// Answers reads, from a host's hello, whether it answers this runtime's
	// asks itself. nil: it answers none.
	Answers func(hello Msg) bool
	// GatedSend: muster sends to a window of it only through the host's own
	// gated send (Msg.Runtime names it on the paste), never as keys; only on a
	// host that advertised it (Sends), only to a window its host says it sends
	// to (Window.AgentSend), and only while that window is idle with a status
	// time, which the paste carries (Msg.Since) for the host to check again.
	// The paste waits PasteTimeout for the host's answer.
	GatedSend    bool
	PasteTimeout time.Duration
	// Sends reads, from a host's hello, whether it advertised its gated send.
	// nil: it advertises none.
	Sends func(hello Msg) bool
	// SendOff is the refusal of a send to a window of it on a host that did
	// not advertise its gated send; Unbound the refusal of one to a window its
	// host does not send to (not launcher-bound). nil without a gated send.
	SendOff, Unbound func() error
	// PendingNamesAsk: a window of it waits on a NAMED ask (Pending.Kind,
	// PromptID, Choices), and a Pending that names none is none. false: the
	// ask fields are not its own and are stripped.
	PendingNamesAsk bool
	// AskKinds are the asks (Pending.Kind) a window of it may name, when
	// PendingNamesAsk: a Pending naming another runtime's kind is none.
	AskKinds []string
}

RuntimeSpec is one agent runtime as muster's server sees it.

func LookupRuntime

func LookupRuntime(name string) (RuntimeSpec, bool)

LookupRuntime is the runtime named name, and whether muster knows it.

func Runtimes

func Runtimes() []RuntimeSpec

Runtimes is every runtime muster knows, Claude Code first.

func (RuntimeSpec) AgentKey

func (r RuntimeSpec) AgentKey(agentSession string) string

AgentKey is the stored session key of r's conversation agentSession: the prefix and the id, "" when r keys none or the window names none.

func (RuntimeSpec) HasView

func (r RuntimeSpec) HasView(agentSession string) bool

HasView reports whether a window of r whose host names agentSession has a rendered view.

type Service

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

Service is the mirror plugin as internal/api consumes it: the connect endpoint, the viewing principal's hosts, and terminal attach.

func NewService

func NewService(store Store, logger *log.Logger) *Service

NewService builds the plugin over store.

func (*Service) AgentClones added in v0.204.0

func (s *Service) AgentClones(ctx context.Context, host, repo string) ([]AgentClone, error)

AgentClones asks one of the viewing principal's hosts for its clones of repo. See Hub.AgentClones.

func (*Service) AgentState

func (s *Service) AgentState(ctx context.Context, host, session, window string) AgentState

AgentState is Hub.AgentState for the viewing principal's host.

func (*Service) AnswerOpenCodeAsk added in v0.138.0

func (s *Service) AnswerOpenCodeAsk(ctx context.Context, host, session, window, promptID, choice string) error

AnswerOpenCodeAsk is Hub.AnswerOpenCodeAsk for the viewing principal's host.

func (*Service) AnswerOpenCodeForm added in v0.189.0

func (s *Service) AnswerOpenCodeForm(ctx context.Context, host, session, window string, form OpenCodeForm, picks []OpenCodePick) error

AnswerOpenCodeForm is Hub.AnswerOpenCodeForm for the viewing principal's host.

func (*Service) AnswerWindow

func (s *Service) AnswerWindow(ctx context.Context, host, session, window string, qs []askq.Question, choices []askq.Choice, prior *askq.Progress) error

AnswerWindow is Hub.AnswerWindow for the viewing principal's host.

func (*Service) Attach

func (s *Service) Attach(ctx context.Context, host, session string, readOnly bool, stdin io.Reader, stdout io.Writer, resize <-chan provision.TermSize) error

Attach attaches a terminal to one of the viewing principal's host sessions. See Hub.Attach.

🔴 AN INTERACTIVE ATTACH NEEDS A FRESH SIGN-IN (internal/stepup), checked HERE as well as by internal/api before its socket upgrade: the plugin does not rely on its caller to have asked. A context with no sign-in time is never fresh, so a caller that forgot to carry one gets read-only or nothing.

func (*Service) AttachWindow

func (s *Service) AttachWindow(ctx context.Context, host, session, window string, readOnly bool, stdin io.Reader, stdout io.Writer, resize <-chan provision.TermSize) error

AttachWindow is Attach on one window of the session (its tmux window id); window == "" is the session's active window. See Hub.AttachWindow.

func (*Service) AuthenticateHost

func (s *Service) AuthenticateHost(w http.ResponseWriter, r *http.Request) (owner int64, host string, ok bool)

AuthenticateHost is the ASK HOOK's door (`muster-mirror ask`, internal/api's mirror_ask.go): the request's mirror token, checked exactly as /mirror/connect checks it, yielding the OWNER and HOST it was minted for. ok false: the refusal (401, 429 or 503) has been written.

🔴 A MIRROR TOKEN OPENS THIS AND /mirror/connect, AND NOTHING ELSE. The ask route registers a question under the token's own owner and host, and nowhere else: muster shows it only in a window that host lists as running that Claude session, and only to that owner.

func (*Service) CancelAsk

func (s *Service) CancelAsk(ctx context.Context, host, session, window string) (string, error)

CancelAsk is Hub.CancelAsk for the viewing principal's host.

func (*Service) CatalogWindow

func (s *Service) CatalogWindow(ctx context.Context, host, session, window string) (Catalog, error)

CatalogWindow is the composer menu's catalog of one window of one of the viewing principal's host sessions (window == "" is the session's active window): its commands and skills, as the host reports them. See Hub.CatalogWindow. No step-up: it reads names and descriptions, and types nothing.

func (*Service) CloseAgent added in v0.183.0

func (s *Service) CloseAgent(ctx context.Context, host string, req AgentCloseReq) (AgentCloseResult, error)

CloseAgent asks ctx's principal's host to end the agent in window req (agentclose.go).

func (*Service) HostRanks

func (s *Service) HostRanks(ctx context.Context) map[string]int

HostRanks is the viewing principal's hosts' registration ranks (RanksByRegistration over its own tokens — mirror_tokens is under row-level security, so ListTokens runs as the viewer and reads only theirs). Read on every call, uncached, like the rest of the sidebar's per-render reads. A failed read is logged and answers nil: the caller's fallback (ui.HostIconFor's hash) still draws an icon.

func (*Service) HostToken

func (s *Service) HostToken(ctx context.Context, host string) (int64, bool)

HostToken is the id of the token the viewing principal's host is connected with now, if it is connected through ServeConnect. Two machines minted under one host name are one hub entry; the token id is what tells which of them holds it (`muster doctor`'s this-host, via GET /mirror/host).

func (*Service) Hosts

func (s *Service) Hosts(ctx context.Context) []HostView

Hosts is the viewing principal's hosts: connected, or recently disconnected. Another user's hosts are never in it.

func (*Service) Hub

func (s *Service) Hub() *Hub

Hub is the service's hub (tests).

func (*Service) LiveTokenHosts

func (s *Service) LiveTokenHosts(ctx context.Context) ([]string, error)

LiveTokenHosts is the viewing principal's hosts that hold at least one UNREVOKED mirror token, sorted: the hosts muster expects to connect. It is what `muster doctor` checks the connected set against (GET /api/doctor). A host whose every token is revoked is not expected, whatever its rank.

func (*Service) Nudge

func (s *Service) Nudge(owner int64)

Nudge tells owner's open views to re-fetch (the hub's own debounced nudge).

func (*Service) OpenCodeForm added in v0.189.0

func (s *Service) OpenCodeForm(ctx context.Context, host, session, window, promptID string) (OpenCodeForm, error)

OpenCodeForm is Hub.OpenCodeForm for the viewing principal's host. No step-up: it reads, and answers nothing.

func (*Service) Paste

func (s *Service) Paste(ctx context.Context, host, session, text string, target PasteTarget) error

Paste types a message into a pane of one of the viewing principal's host sessions: its Claude pane, or its active pane (target). See Hub.Paste.

func (*Service) PasteWindow

func (s *Service) PasteWindow(ctx context.Context, host, session, window, text string, target PasteTarget, opts ...PasteOption) error

PasteWindow is Paste into one window of the session; window == "" is the session's active window. See Hub.PasteWindow.

func (*Service) ScrollWindow

func (s *Service) ScrollWindow(ctx context.Context, host, session, window string, lines int) error

ScrollWindow scrolls the active pane of one window of one of the viewing principal's host sessions through its history (tmux copy-mode); window == "" is the session's active window. See Hub.ScrollWindow — and why it needs no fresh sign-in.

func (*Service) ServeConnect

func (s *Service) ServeConnect(w http.ResponseWriter, r *http.Request)

ServeConnect is GET /mirror/connect: authenticate the host's token, upgrade, and run the connection.

🔴 THE TOKEN IS THE ONLY DOOR, AND IT IS A MIRROR TOKEN OR NOTHING. The route is not behind the browser session or the hook token: a host is neither. It is looked up by hash in mirror_tokens and nowhere else, so the hook, service and agent tokens are refused here. A mirror token also opens the AskUserQuestion hook's routes (/mirror/ask, internal/api's mirror_ask.go) and POST /mirror/mcp (mirror_mcp.go): the attention and task tools of that host's own Claude Code sessions — asks, and only the tasks those sessions created.

🔴 THE LOOKUP RUNS UNDER authz.System: mirror_tokens is under row-level security and nobody is known until the token is found. What the token yields — its OWNER and HOST — is everything the connection is then allowed: its sessions are registered under that owner only.

🔴 THE TOKEN IS LOOKED UP FIRST, AND A VALID TOKEN IS NEVER REFUSED BY THE FAILURE LIMIT. The limit used to be checked before the lookup, keyed on the TCP peer — which behind the public path is one address for everyone — so ~10 bad tokens a minute from anyone kept every legitimate host's reconnect refused. Now:

  • a string that is not even SHAPED like a mirror token (TokenShapeOK) is refused without touching the database — that, not the limiter, is what keeps junk off the database;
  • a well-shaped token is always looked up (one indexed read by unique hash); a valid one proceeds whatever the failure count says;
  • only FAILURES count, and an address past the limit gets 429 instead of 401 for its failures — a signal to a misconfigured host that it is hammering, not a lock on anyone. The secret's strength (256 bits) is the guessing defence.

func (*Service) SetActivityNudgeEvery

func (s *Service) SetActivityNudgeEvery(d time.Duration)

SetActivityNudgeEvery overrides activityNudgeEvery, the per-owner throttle on activity-only nudges (tests).

func (*Service) SetListingNotify added in v0.170.0

func (s *Service) SetListingNotify(fn func(owner int64, host string, windows []Window))

SetListingNotify installs the hub's listing hook (Hub.SetListingNotify).

func (*Service) SetNotify

func (s *Service) SetNotify(fn func(owner int64))

SetNotify installs the Agents-view refresh nudge (internal/api's agents-changed broadcast), called with the OWNER of the host that changed: the event reaches only that owner's open views (accounts PR 3b). It carries no data: it only tells them to re-fetch, and each re-fetch is scoped to its own principal.

func (*Service) SetNotifyDebounce

func (s *Service) SetNotifyDebounce(d time.Duration)

SetNotifyDebounce overrides the nudge coalescing window (tests).

func (*Service) SetOutcomesNotify added in v0.179.0

func (s *Service) SetOutcomesNotify(fn func(owner int64, host string, seq uint64, windows []Window, outcomes map[string]WindowOutcome))

SetOutcomesNotify installs the hub's outcomes hook (Hub.SetOutcomesNotify).

func (*Service) SetSpawnReplyNotify added in v0.170.0

func (s *Service) SetSpawnReplyNotify(fn func(owner int64, host string, m Msg))

SetSpawnReplyNotify installs the hub's late-reply hook (Hub.SetSpawnReplyNotify).

func (*Service) SetStatusNotify added in v0.165.0

func (s *Service) SetStatusNotify(fn func(owner int64))

SetStatusNotify installs the hub's status hook (Hub.SetStatusNotify).

func (*Service) SetTokenRecheck

func (s *Service) SetTokenRecheck(d time.Duration)

SetTokenRecheck overrides TokenRecheck (tests).

func (*Service) SetWaitingNotify

func (s *Service) SetWaitingNotify(fn func(owner int64))

SetWaitingNotify installs the hub's waiting-set hook (Hub.SetWaitingNotify).

func (*Service) SpawnAgent added in v0.170.0

func (s *Service) SpawnAgent(ctx context.Context, host string, dispatch int64, req AgentSpawnReq) (AgentSpawned, error)

SpawnAgent asks one of the viewing principal's hosts to start an agent for host dispatch dispatch. See Hub.SpawnAgent.

func (*Service) SpawnResume

func (s *Service) SpawnResume(ctx context.Context, host, sid string) (ResumedWindow, error)

SpawnResume asks one of the viewing principal's hosts to resume Claude Code session sid in a new window. See Hub.SpawnResume.

func (*Service) SubagentTail

func (s *Service) SubagentTail(ctx context.Context, host, session, window, agent string) (SubagentTail, error)

SubagentTail is Hub.SubagentTail for the viewing principal (ctx's). No step-up: it reads, and types nothing.

func (*Service) Watch

func (s *Service) Watch(ctx context.Context, host, session, gen string, offset int64, out func(Msg) error) error

Watch streams one of the viewing principal's host sessions' Claude Code transcript. See Hub.Watch.

func (*Service) WatchWindow

func (s *Service) WatchWindow(ctx context.Context, host, session, window, gen string, offset int64, out func(Msg) error) error

WatchWindow is Watch on one window of the session; window == "" is the session's active window. See Hub.WatchWindow.

type SessionView

type SessionView struct {
	Host    string
	Session string
	// Window is the tmux window id (Window.ID) the entry is; "" = the entry is
	// a per-session host's session, addressed by name alone.
	Window string
	// Index is the window's index (display only); meaningful when Window != "".
	Index int
	// Active: the session's current window (always true for a per-session
	// host's entry, which IS the session's active window).
	Active bool
	// Label is the host's display name for the entry, "" for none.
	Label string
	// Command is what runs in the window's active pane, "" for unknown.
	Command string
	// Activity is when the entry was last active (Unix seconds, floored to
	// ActivityBucket); 0 = the host did not say. For a Claude window it is its
	// last message when the host reported one (Window.CardActivity), else tmux's
	// window activity.
	Activity int64
	// Online, Interactive, Rendered, PanePaste, PaneScroll: the host's
	// (HostView). Claude:
	// the host reports Claude Code in this entry's pane.
	Online      bool
	Interactive bool
	Rendered    bool
	PanePaste   bool
	PaneScroll  bool
	Claude      bool
	// ClaudeSession is the Claude Code session id of the conversation in the
	// entry's pane (Window.ClaudeSession), "" for none — always "" for a
	// per-session host's entry. What its focus is keyed by.
	ClaudeSession string
	// Runtime is the window's non-Claude agent runtime (Window.Runtime:
	// RuntimeOpenCode, or ""), and AgentSession that runtime's session id
	// (Window.AgentSession), "" when the host names none — when the window
	// has no rendered view.
	Runtime      string
	AgentSession string
	// AgentNote is the host's line for the person about the window
	// (Window.AgentNote): why it has no rendered view, or what its credential
	// needs. Shown on its card.
	AgentNote string
	// AgentSend is Window.AgentSend: the host sends to this window's session
	// through its runtime's gated send (launcher-bound opencode). SendWhy says,
	// with the host's hello, whether a send can go and why not.
	AgentSend bool
	// AgentBind is Window.AgentBind: how a hand-opened pane of a gated-send
	// runtime is bound (verified: sent to), or why it is not sent to.
	AgentBind string
	// LiveCopy is the session id of another transcript of the entry's Claude
	// Code conversation that is still running elsewhere (Window.LiveCopy), ""
	// for none. LiveCopyWarning is its words.
	LiveCopy string
	// Qualifier is what the entry's Title needs beside it to be told apart from
	// every OTHER entry listed with it ("" = its Title is already unique). Set
	// by Ordered (qualify) and only there; a SessionView from HostView.Entries
	// or Find alone has none — Qualified gives one the list's.
	Qualifier string
	// Repo is the short name of the repository the entry works in
	// (HostView.Repos, repos.go), "" when its host did not say.
	Repo string
	// GitHubRepo is the GitHub <owner>/<name> the entry's checkout's origin
	// names (HostView.GitHubRepos, repos.go), "" when its host did not say. It
	// can differ from Repo (a folder named unlike its repository); the chief is
	// shown both, and dispatches with this one.
	GitHubRepo string
	// Dispatch is the host dispatch the entry's window was started for
	// (Window.Dispatch): an agent the chief started. 0 for every other window.
	Dispatch int64
	// Work is what the entry's Claude Code session has running now
	// (HostView.Work, work.go); the zero value when its host did not say.
	Work WindowWork
	// Previews is what the entry's window has to preview now
	// (HostView.Previews, previews.go); the zero value when its host did not
	// say — which draws no Preview button and no sidebar mark.
	Previews WindowPreviews
	// Color is the entry's tmux identity colour, lowercase #rrggbb
	// (HostView.Colors, work.go), "" when its host did not say.
	Color string
	// Status and StatusSince are the window's Window.Status / StatusSince —
	// only from a host that advertised StatusReport (the wire's rule: no other
	// host is believed about status); "" and 0 otherwise, and always for a
	// per-session host's entry.
	Status      string
	StatusSince int64
}

SessionView is one mirrored entry as a LIST or a page shows it — a WINDOW of a per-window host, or a whole session of a per-session host — with its host's facts beside its own. HostView.Entries and HostView.Find are the only producers.

func Ordered

func Ordered(hosts []HostView) []SessionView

Ordered is every entry of hosts, as ONE list across hosts, MOST RECENTLY ACTIVE FIRST.

The sort is STABLE over the order mirrored entries always had — hosts as given (Hub.Hosts sorts them by name), then each host's own order (HostView.Entries) — so entries active in the same ActivityBucket keep that order, and every entry whose host reported no activity (an older muster-mirror) comes after all that did, in that same order. With no activity anywhere the result is exactly the old list.

🔴 ONE RULE, ONE PLACE. The sidebar renders this list and the hub decides from this same list (listed) whether a host's update changed what the view shows: the order, which it re-renders for at once, and each entry's ActiveAt, which it re-renders for throttled. A second copy of either comparison would let the two disagree about what "changed" means.

func Qualified

func Qualified(hosts []HostView, e SessionView) SessionView

Qualified is e with the Qualifier Ordered(hosts) gives the same entry (host, session, window): what a PAGE of one entry calls it, so the page and the card it was opened from say the same name. An entry hosts does not list keeps no qualifier.

func (SessionView) ActiveAt

func (s SessionView) ActiveAt() time.Time

ActiveAt is the entry's last activity, as the sidebar row's recency dot reads it: its Activity (already floored to ActivityBucket by NormalizeActivity / NormalizeWindows), or zero for unknown so no time is drawn at all rather than one 56 years ago.

🔴 ONE RULE, ONE PLACE: the sidebar takes an entry's time from here, and the hub decides from here (listed) whether an update moved an entry's time.

func (SessionView) Address

func (s SessionView) Address() string

Address is the entry's tmux address on its host, as an operator types it: "<session>:<window index>" for a window, the session name for a per-session host's entry. It is unique WITHIN one host at any moment — tmux allows one session per name and one window per index in a session — which is what makes it the tie-break for two entries of one host that share a Title.

func (SessionView) AgentView

func (s SessionView) AgentView() bool

AgentView reports whether the entry is a window of a non-Claude runtime whose host names its conversation, and so has a rendered view (RuntimeSpec.HasView).

func (SessionView) CanPaste

func (s SessionView) CanPaste() bool

CanPaste reports whether a message can be sent into the entry's active pane from the Terminal view (PasteActivePane): the host is connected and -interactive, and either pastes into any pane or — an older muster-mirror — reports Claude Code in this one, which its Claude-only paste reaches.

func (SessionView) CanScroll

func (s SessionView) CanScroll() bool

CanScroll reports whether the Terminal view may scroll the entry's pane through its history (Hub.ScrollWindow): the host is connected, -interactive, and advertised copy-mode scrolling. An older muster-mirror cannot, and the page then draws no gesture at all.

func (SessionView) DisplayTitle

func (s SessionView) DisplayTitle() string

DisplayTitle is the entry's name as every surface shows it — the card, the rendered view's and the terminal's header and <title>: its Title, then its Qualifier when it has one.

func (SessionView) HasRenderedView

func (s SessionView) HasRenderedView() bool

HasRenderedView reports whether the entry has a rendered view: a connected v2 host reporting Claude Code in its pane — or another runtime with a view, with the session it shows (AgentView).

func (SessionView) Kind

func (s SessionView) Kind() string

Kind is what runs in the entry's pane, as a list names it: KindClaudeCode when the host resolved a Claude Code session there, KindOpenCode / KindShell from the pane's command, else the command itself; "" when the host said nothing (a per-session host, which reports no command).

func (SessionView) LiveCopyWarning added in v0.106.0

func (s SessionView) LiveCopyWarning() string

LiveCopyWarning is the one line a card and the views show about a window whose conversation also runs elsewhere (SessionView.LiveCopy), "" for none.

🔴 ONE RULE, ONE PLACE: the card, the Rendered view and the Terminal view all take it from here.

func (SessionView) Place added in v0.173.0

func (s SessionView) Place() Place

Place is the entry's Place: Title and Host (and its Address, and whether its host is offline).

func (SessionView) SessionKey

func (s SessionView) SessionKey() string

SessionKey is the key the entry's conversation is stored by (a focus): a Claude session id as itself, another runtime's runtime-qualified ("opencode:<id>", Window.SessionKey's rule); "" when the entry names none.

func (SessionView) Spec

func (s SessionView) Spec() (RuntimeSpec, bool)

Spec is the RuntimeSpec of the entry's non-Claude runtime (Runtime), false for none or a Claude Code entry.

func (SessionView) TerminalOnlyReason added in v0.104.0

func (s SessionView) TerminalOnlyReason() string

TerminalOnlyReason is the one line the Terminal view shows about WHY the entry has no Rendered view, "" when it has one (HasRenderedView) or its host is offline (the page says offline on its own). In order: a host too old for rendered views; the host's own reason (AgentNote: a Claude Code transcript not written yet or not found, an opencode pairing, …); a runtime with no view yet; and otherwise TerminalOnlyNoClaude.

🔴 ONE RULE, ONE PLACE: the Terminal view takes it from here, so a window that opens in the terminal always says why instead of silently falling back — the silent fallback is what read as "muster only has a terminal".

func (SessionView) Title

func (s SessionView) Title() string

Title is the entry's display name: the host's label when it sent one, else "<session>:<window index>" for a window, else the session name.

func (SessionView) TitleAt added in v0.173.0

func (s SessionView) TitleAt() string

TitleAt is how muster named the entry before sessions had names: its Title — the host's label for the window ("mango:1"), else its tmux address ("scratch3:5") — and its host: "mango:1 @ atlas". It is what a notification that names a session by its human name adds after it when its owner turned on "Show tmux sessions" (internal/api notifyName).

func (SessionView) Where added in v0.124.0

func (s SessionView) Where() string

Where is the entry's exact place, for every text that sends the operator to it (an ask, a waiting session, a notification): see the function Where.

func (SessionView) WhereTarget added in v0.124.0

func (s SessionView) WhereTarget() string

WhereTarget is the entry's WhereTarget.

type SpawnRefusedError added in v0.170.0

type SpawnRefusedError struct{ Code, Detail string }

SpawnRefusedError is a host's refusal: Code is one of the Spawn* codes, Detail its fixed sentence.

func (*SpawnRefusedError) Error added in v0.170.0

func (e *SpawnRefusedError) Error() string

type Store

type Store interface {
	// Authenticate resolves a presented token to its record, or ErrBadToken.
	Authenticate(ctx context.Context, token string) (Token, error)
	// TokenLive reports whether token id is still unrevoked.
	TokenLive(ctx context.Context, id int64) (bool, error)
	// CreateToken mints a token for host, owned by ctx's user, and returns it
	// ONCE, with its record.
	CreateToken(ctx context.Context, host string) (string, Token, error)
	ListTokens(ctx context.Context) ([]Token, error)
	// RevokeToken revokes token id, reporting whether it was live.
	RevokeToken(ctx context.Context, id int64) (bool, error)
}

Store is the plugin's persistence: tokens, and nothing else.

🔴 EVERY METHOD RUNS UNDER THE CALLER'S PRINCIPAL, AND mirror_tokens IS UNDER ROW-LEVEL SECURITY (migration 0008). Authenticate and TokenLive must find a token before anyone is known, so internal/mirror's Service calls them under authz.System; CreateToken, ListTokens and RevokeToken run as the minting user (authz.Operator for `muster-server mirror token …`), so a token lands owned by them and they see and revoke only their own.

type Subagent

type Subagent struct {
	// Agent is the subagent's id (its transcript is agent-<Agent>.jsonl).
	Agent string `json:"agent"`
	// ToolID is the parent's Agent tool_use id: the card it belongs to.
	ToolID string `json:"toolId"`
	// Type is the agent type ("general-purpose"), Description the call's
	// description: from the agent's meta file, "" when it has none.
	Type        string `json:"type,omitempty"`
	Description string `json:"description,omitempty"`
	// Background: launched to run in the background.
	Background bool `json:"background,omitempty"`
	// State is SubagentRunning, SubagentDone or SubagentFailed (the host's
	// rule: internal/ccsubagents' State).
	State string `json:"state"`
	// Started and Updated are the agent's first and last row (Unix ms, 0 =
	// unknown): its elapsed time is Updated-Started once it ended, now-Started
	// while it runs.
	Started int64 `json:"started,omitempty"`
	Updated int64 `json:"updated,omitempty"`
	// Last is the agent's latest step on one line: a tool call ("Bash: go
	// test ./...") or its latest text. Redacted.
	Last string `json:"last,omitempty"`
}

Subagent is one subagent's summary (Msg.Subagents).

func NormalizeSubagents

func NormalizeSubagents(in []Subagent) []Subagent

NormalizeSubagents is in as the wire carries it: entries with a valid agent and tool id, one per tool id (the first), a known state (else running), text fields cleaned and bounded, no time before 1970, at most MaxSubagents (the LAST ones, which the host orders oldest first) and within MaxSubagentListBytes encoded. Both halves apply it.

type SubagentStep

type SubagentStep = ccsubagents.Step

SubagentStep is one step of a tail: ccsubagents.Step, whose fields and JSON are {tool, text, at}.

type SubagentTail

type SubagentTail struct {
	Agent string         `json:"agent"`
	Steps []SubagentStep `json:"steps"`
	More  bool           `json:"more,omitempty"`
}

SubagentTail is a tail request's answer: the newest steps, oldest first, and whether earlier ones were left out.

func NormalizeSubagentTail

func NormalizeSubagentTail(t SubagentTail) SubagentTail

NormalizeSubagentTail is t as the wire carries it: its steps cleaned and bounded, the newest MaxSubagentTailSteps within MaxSubagentTailBytes (More set when any were dropped). Both halves apply it.

type SupersededError

type SupersededError struct {
	Pasted int64
}

SupersededError is ErrSuperseded with the window's Pasted at the refusal: what the message must now wait behind.

func (*SupersededError) Error

func (e *SupersededError) Error() string

func (*SupersededError) Unwrap

func (e *SupersededError) Unwrap() error

type Token

type Token struct {
	ID int64 `json:"id"`
	// OwnerID is the user who minted it; the host's sessions are visible only to
	// that user's principal.
	OwnerID   int64      `json:"ownerId"`
	Host      string     `json:"host"`
	CreatedAt time.Time  `json:"createdAt"`
	RevokedAt *time.Time `json:"revokedAt,omitempty"`
	LastUsed  *time.Time `json:"lastUsedAt,omitempty"`
}

Token is one minted mirror token's record. The token itself is never stored: only its sha256, so a database read cannot be replayed as a credential.

type Turn

type Turn struct {
	Since, Pasted int64
}

Turn is the window's turn a queued message was decided on: the AgentState's Since and Pasted that the send queue read when it decided to send.

type TurnError

type TurnError struct {
	// Kind is TurnErrorLimit for a usage limit, else the record's own error
	// code ("authentication_failed", "server_error", …: ValidTurnErrorKind),
	// TurnErrorOther when it names none.
	Kind string `json:"kind"`
	// At is when the record was written: its timestamp, Unix ms ON THE HOST'S
	// CLOCK (the CLI's).
	At int64 `json:"at,omitempty"`
	// ResetsAt is when a usage limit resets, Unix ms: an absolute time the
	// limit itself names (cctranscript.LimitReset), compared with muster's
	// clock. 0 when it names none, and for every other kind.
	ResetsAt int64 `json:"resetsAt,omitempty"`
	// Rejected: the prompt this turn answered got NO real reply at all — the
	// error is the turn's only reply, no tool ran, nothing was written. False
	// when any real reply came first (the limit hit mid-turn: the prompt was
	// processed) or no prompt was found. The send queue marks a message it
	// sent failed ("Rejected: usage limit") only on a turn that says this.
	Rejected bool `json:"rejected,omitempty"`
	// Prompt is PromptDigest of the prompt a Rejected turn answered; "" when
	// the turn is not Rejected. Never the text itself.
	Prompt string `json:"prompt,omitempty"`
	// PrevAt is the time of the newest message record (user or assistant,
	// any) BEFORE a Rejected turn's prompt — when the turn before it ended —
	// Unix ms on the host's clock (the CLI's, like Window.StatusSince). 0 when
	// the transcript has none before it. A Rejected turn whose host could not
	// read back that far is reported not Rejected.
	PrevAt int64 `json:"prevAt,omitempty"`
	// Quick counts the latest turns, this one first, that EACH ended in such a
	// record within QuickTurnMS of their prompt with no real reply between:
	// the send queue's circuit breaker. 0 when this turn was not one.
	Quick int `json:"quick,omitempty"`
}

A TURN THAT ENDED IN AN ERROR (Window.TurnError): the host's reading of an IDLE Claude window's transcript, when the latest turn in it ended in a record Claude Code wrote itself to say it got no answer — a usage limit ("You've hit your session limit · resets …"), "Not logged in", an API error (cctranscript.ErrorEndOf). nil when the latest turn ended in a real answer, or has not ended.

🔴 WHY THE SEND QUEUE NEEDS IT: such a turn ends in a second or so and Claude Code goes back to its prompt, so its status reads idle with a newer time — exactly what a turn that was answered looks like. Without this the queue sent the next message into the same wall, and the next, until the queue was empty: every message consumed by a limit and lost (internal/sendqueue's Decide holds on it now, and marks the one message the limit bounced failed, for a Retry by hand).

🔴 BACKWARD-COMPATIBLE BOTH WAYS, like Pending: an older muster ignores it; an older host never sends it, and its windows' queues behave as they did.

⚠ SIZE: it rides the window list, ONE message within MaxFrame (TestTheLargestWindowListFitsOneFrame). So it carries no text — a kind, two times, a flag, a count and a 16-hex digest, every field a closed alphabet that JSON writes as itself — and at most MaxTurnErrorWindows windows of a list carry one. (The digest and PrevAt cost ~45 bytes a window, ~720 at the bound: what it takes for the queue to know WHICH prompt was refused.)

func CleanTurnError

func CleanTurnError(e *TurnError) *TurnError

CleanTurnError is e as the wire carries it: nil for no kind or one the wire does not carry, no negative time, a reset only on a limit, a digest and a PrevAt only on a Rejected turn (and a Rejected turn only with a digest), Quick within its bound.

type Window

type Window struct {
	// Session is the tmux session the window belongs to.
	Session string `json:"session"`
	// ID is tmux's window id, "@<n>" (#{window_id}).
	ID string `json:"id"`
	// Index is the window's index in its session NOW. Display only.
	Index int `json:"index"`
	// Active: this is its session's current window — the one a request that
	// names only the session reaches.
	Active bool `json:"active,omitempty"`
	// Label is the host's display name, "<codename>:<index>", "" for none
	// (muster then shows "<session>:<index>").
	Label string `json:"label,omitempty"`
	// Activity is when the window was last active (Unix seconds, floored to
	// ActivityBucket); 0 = unknown. Ordering and display only (the sidebar
	// row's recency dot).
	Activity int64 `json:"activity,omitempty"`
	// Claude: the window's active pane runs Claude Code with a transcript the
	// host can read — it has a rendered view.
	Claude bool `json:"claude,omitempty"`
	// Command is what runs in the window's active pane (#{pane_current_command}:
	// "zsh", "opencode", "vim"), "" for unknown. Display and search only.
	Command string `json:"command,omitempty"`
	// Status is what the Claude Code session in the window's pane reports about
	// itself (StatusBusy, StatusIdle, StatusWaiting), "" when unknown — no Claude
	// pane, or one whose status the host cannot read. It is what decides when a
	// QUEUED message may be sent (internal/sendqueue), and only a host that
	// advertised Msg.StatusReport is believed about it.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like Labels: an older
	// muster ignores the field; an older host never sends it, and never sets
	// StatusReport, so muster treats every window of it as UNKNOWN — and a queued
	// message for it is NOT sent (it fails closed), never sent on a guess.
	Status string `json:"status,omitempty"`
	// StatusSince is WHEN Claude Code last wrote Status, in Unix milliseconds:
	// its sessions file's own statusUpdatedAt, the CLI's clock, not muster's
	// or the host's guess. 0 when unknown. The send queue reads an idle window
	// as idle SINCE this, and sends the next message only once it is later than
	// the last one was handed over: a turn the message started and finished
	// between two host refreshes still moves it.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like Status: an older
	// muster ignores it; a host that sends a Status without it is UNKNOWN to the
	// send queue (Hub.AgentState: ErrNoStatusSince) — held, never timed out on a
	// guess.
	StatusSince int64 `json:"statusSince,omitempty"`
	// ClaudeSession is the Claude Code SESSION ID of the conversation in the
	// window's pane (the transcript's own name, Msg.Gen's value), "" when the
	// pane is not Claude Code or the host does not say. It is what a mirrored
	// session's FOCUS is keyed by (internal/focus): the conversation, not the
	// window, so a focus survives tmux reissuing window ids and an operator
	// moving a conversation to another window.
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like Status: an older
	// muster ignores it; an older host never sends it, and its windows simply
	// have no focus. Only an id ValidClaudeSession accepts is kept.
	//
	// ⚠ THE TRANSCRIPT PATH IS DELIBERATELY NOT ON THE WIRE. The window list is
	// ONE message within MaxFrame, and with this field at its 64-byte bound its
	// worst case measures 98% of it (1,030,215 of 1,048,576 bytes, with every
	// field this list carries now: TestTheLargestWindowListFitsOneFrame, which
	// logs the figure) — a host path
	// per window does not fit beside it. muster never needs the path: it reads a transcript
	// through the host's own watch (Hub.WatchWindow), which resolves the path
	// on the host.
	ClaudeSession string `json:"claudeSession,omitempty"`
	// OtherClaude are the Claude Code session ids running in the window's
	// OTHER panes (a split), "" never. Only so a session in a non-active pane
	// is recognised as this host's by the mirrored sessions' MCP door
	// (internal/api's mirrorSessionOf); nothing renders them.
	//
	// 🔴 BOUNDED LIST-WIDE, NOT PER WINDOW: at most MaxOtherClaudePerWindow per
	// window and MaxOtherClaude across the whole list (NormalizeWindows), so the
	// list's worst case grows by a few KiB of the frame's last 4%
	// (TestTheLargestWindowListFitsOneFrame encodes it at its bound).
	// Backward-compatible both ways, like ClaudeSession.
	OtherClaude []string `json:"otherClaude,omitempty"`
	// Pending is what a WAITING Claude session waits on (pending.go): nil
	// unless Claude and StatusWaiting, and on at most MaxPendingWindows windows
	// of a list. Backward-compatible both ways, like ClaudeSession.
	Pending *Pending `json:"pending,omitempty"`
	// Runtime names the agent CLI in the window's active pane when it is NOT
	// Claude Code: RuntimeOpenCode, or "" (Claude Code, which Claude says, or
	// no agent at all). AgentRuntime is the one way to read it. A name muster
	// does not know (an older host's "hermes") is dropped by NormalizeWindows:
	// the window is a plain terminal window.
	//
	// 🔴 "" FOR CLAUDE CODE, NOT "claude", ON PURPOSE: a Claude window's bytes
	// on the wire stay exactly what they were before runtimes existed, and the
	// worst-case window list stays inside MaxFrame
	// (TestTheLargestWindowListFitsOneFrame measures both).
	//
	// 🔴 A WINDOW OF A RUNTIME ON THE WIRE IS NEVER Claude (NormalizeWindows
	// enforces it), so an older muster — which ignores this field — shows it
	// as a plain terminal window, and its only way in, the Terminal view's
	// paste, is refused by the host's paste guard. Backward-compatible both
	// ways, like ClaudeSession.
	Runtime string `json:"runtime,omitempty"`
	// AgentSession is the SESSION ID of the conversation in a non-Claude
	// window's pane (an opencode session id), "" when the host does not say. Bounded by ValidAgentSession,
	// which is wider than a Claude id's 64 bytes. A Claude window's id stays in
	// ClaudeSession (never in both, so a list's worst case grows by one id per
	// window at most). SessionKey is the runtime-qualified key it is stored by.
	// Backward-compatible both ways, like ClaudeSession.
	AgentSession string `json:"agentSession,omitempty"`
	// AgentNote is a line for the person about a window of a runtime on the
	// wire (opencode): why it has NO rendered view ("opencode is not paired on
	// this host…", an ambiguous title, a refused token), or what its view's
	// credential needs (a token about to expire, a failing renewal). On a
	// window that is NOT Claude and names no runtime, it is why a Claude Code
	// pane there has no rendered view (mirrorhost's NoView* lines: its
	// transcript not written yet, not found, ambiguous, or a host that cannot
	// read processes); a Claude window never carries one. "" for
	// none. Bounded (MaxAgentNote bytes, on at most MaxAgentNoteWindows windows
	// of a list) and stripped of control characters by NormalizeWindows.
	// Backward-compatible both ways, like AgentSession.
	AgentNote string `json:"agentNote,omitempty"`
	// AgentSend: the host sends to this window's session (AgentSession)
	// through its runtime's gated send — an opencode pane started by the
	// launcher (`muster-mirror opencode`), whose session the host knows
	// deterministically. Only a window of a GatedSend runtime naming a session
	// keeps it (NormalizeWindows). A title-matched opencode pane never has it,
	// and is view-only. Backward-compatible both ways, like AgentSession.
	AgentSend bool `json:"agentSend,omitempty"`
	// AgentBind is how a window of a gated-send runtime that is NOT AgentSend
	// (an opencode pane muster's launcher did not start) is bound to its
	// session, as a closed code (agentbind.go): AgentBindVerified — its host
	// verified the binding through opencode's own API and sends to it, but
	// only to a paste that names that very session (Msg.AgentSession) — or
	// why it is not sent to (AgentBindTitleShared, AgentBindArgv,
	// AgentBindStream). "" for none: a launcher-bound window, a window with
	// no view, any other runtime's, and every window of an older host.
	// 🔴 A SEPARATE FIELD FROM AgentSend ON PURPOSE, BACKWARD-COMPATIBLE BOTH
	// WAYS: an older muster ignores it, so such a pane stays view-only there
	// (and its pastes, which name no session, are refused by the host); an
	// older host never sets it.
	AgentBind string `json:"agentBind,omitempty"`
	// LastMessage is when the Claude Code conversation in the window last had
	// a MESSAGE — the newest timestamp of a user or assistant row in its
	// transcript that is not meta (mirrorhost's lastMessageReader) — Unix
	// seconds, floored to ActivityBucket; 0 when the window is not Claude or the
	// host did not say. While the session is WORKING (a turn running, waiting
	// on the person, a background shell of its own) it is instead the host's
	// now: Claude Code writes no row then, and a working window must not read
	// as idle (mirrorhost's WireWindows). CardActivity prefers it over Activity.
	//
	// 🔴 WHY: Activity is tmux's #{window_activity}, which a tmux restart (a
	// tmux-resurrect restore) resets for EVERY window to the restore — measured:
	// all 67 windows on one host read "active since the restore", so nothing
	// could ever look idle. A resumed session's transcript is written on start
	// too (attachment and system rows), so a file's mtime is no better; the last
	// MESSAGE's own timestamp is the one that survives both.
	//
	// Backward-compatible both ways, like ClaudeSession: an older muster ignores
	// it (and keeps ordering by Activity); an older host sends none, and muster
	// falls back to Activity.
	LastMessage int64 `json:"lastMessage,omitempty"`
	// TurnError is how the latest turn of an IDLE Claude window ended when it
	// ended in an error Claude Code wrote itself — a usage limit, "Not logged
	// in", an API error (turnerror.go); nil otherwise, and on at most
	// MaxTurnErrorWindows windows of a list. What the send queue holds on.
	// Backward-compatible both ways, like Pending.
	TurnError *TurnError `json:"turnError,omitempty"`
	// LiveCopy is the Claude Code session id of ANOTHER transcript of the same
	// conversation that is still running elsewhere — a `claude --resume` of a
	// conversation that was still open in another client copies it into a new
	// session instead of attaching to it (livecopy.go) — "" for none. Only a
	// Claude window carries one, and only one whose id ValidClaudeSession
	// accepts, on at most MaxLiveCopyWindows windows of a list. muster shows
	// it as a warning on the card and the views (SessionView.LiveCopyWarning).
	// Backward-compatible both ways, like ClaudeSession.
	LiveCopy string `json:"liveCopy,omitempty"`
	// Dispatch is the host dispatch this window was started for: its own
	// @muster-dispatch window option (DispatchOption), 0 for every window the
	// chief did not start. An older muster ignores it.
	Dispatch int64 `json:"dispatch,omitempty"`
}

Window is one tmux window of a host (Msg.Windows).

🔴 A WINDOW IS ADDRESSED BY (Session, ID), NEVER BY ITS INDEX. tmux renumbers indexes (renumber-windows, move-window, a window closing below it), so an index names whatever sits there NOW; the id (@12) is the window's own for as long as it exists. Index is carried for DISPLAY only ("Gold:8").

func ActiveWindow

func ActiveWindow(windows []Window, session string) (Window, bool)

ActiveWindow is the window of session a request naming only the session reaches: the one marked Active, else (a list with none marked) the session's first. ok is false when windows lists none for session. windows must be NormalizeWindows' output.

func NormalizeWindows

func NormalizeWindows(in []Window, now int64) []Window

NormalizeWindows is in as the tunnel carries it: every entry with a valid session and window id, de-duplicated on (session, id), sorted by session, then index, then id, and capped at MaxWindows. Within an entry an invalid label or command is blanked and the activity is floored and capped exactly as NormalizeActivity does; at most ONE window per session stays Active (the first in order). A viewer session's windows (IsViewSession) are dropped. Both halves apply it: the host to what it sends, muster to what it keeps.

It returns nil for no input and a non-nil empty slice when every entry was dropped, so "sent no window list" and "sent one that was all invalid" stay distinguishable to the caller.

func (Window) AgentRuntime

func (w Window) AgentRuntime() string

AgentRuntime is the agent CLI in w's active pane: RuntimeClaude, a runtime the wire carries as Window.Runtime (RuntimeSpec.OnWire: RuntimeOpenCode), or "" for none. What the hub's waiting set, AgentState and the gated-send switch key on, instead of w.Claude.

func (Window) CardActivity

func (w Window) CardActivity() int64

CardActivity is the window's activity as the sidebar and the switcher use it — the order, the recency dot and the Idle section, one number: a Claude window's LastMessage when the host reported one, else Activity.

func (Window) Equal

func (w Window) Equal(o Window) bool

Equal reports whether w and o are the same window in every field (Window holds a slice, so it has no ==).

func (Window) RunsMCPCaller added in v0.197.0

func (w Window) RunsMCPCaller(key string) bool

RunsMCPCaller reports whether w runs the mirrored session an MCP caller is named by — THE ONE window rule of the mirrored sessions' MCP door:

  • a Claude Code session id: in the window's active pane or another of its panes (a split);
  • an opencode caller's key (OpenCodeCallerKey): the session in the window's active pane, and only while its host SENDS to it — bound by the launcher (AgentSend) or by a verified title binding (AgentBind). A title match the host does not send to binds no call either: it is the binding muster-mirror resolved the call by.

func (Window) SessionKey

func (w Window) SessionKey() string

SessionKey is the key w's conversation is stored by (a focus, a route, an ask): a Claude session id as itself — exactly the key it always was — and another runtime's runtime-qualified, "opencode:<id>" (ValidSessionKey); "" when w names no conversation.

func (Window) Spec

func (w Window) Spec() (RuntimeSpec, bool)

Spec is the RuntimeSpec of w's AgentRuntime, false for none.

type WindowOutcome added in v0.179.0

type WindowOutcome struct {
	Mark  string   `json:"mark"`
	Lines []string `json:"lines,omitempty"`
}

WindowOutcome is the final reply of an idle opencode window the chief started: Mark names it (the opencode message id of the session's newest assistant message, so a new turn is a new mark), Lines are its last non-empty lines, oldest first, at most MaxOutcomeLines — none when the turn ended with no reply text.

type WindowPreviews added in v0.194.0

type WindowPreviews struct {
	Offered int `json:"offered,omitempty"`
	Open    int `json:"open,omitempty"`
}

WindowPreviews is what one window has to preview now: Offered is its listeners the host offers that have no open preview (the gateway's session page lists the same set: an open port is shown as its preview, not again as an offer), Open its open previews.

func (WindowPreviews) IsZero added in v0.194.0

func (p WindowPreviews) IsZero() bool

IsZero: nothing to show.

func (WindowPreviews) Total added in v0.194.0

func (p WindowPreviews) Total() int

Total is how many things the window's session page lists: its offers and its open previews.

type WindowWork

type WindowWork struct {
	Subagents     int  `json:"subagents,omitempty"`
	Shells        int  `json:"shells,omitempty"`
	ShellsAtLeast bool `json:"shellsAtLeast,omitempty"`
}

WindowWork is what one window's Claude Code session has running now.

ShellsAtLeast: Shells is a LOWER BOUND ("1+ shell"), never an exact count. It is what the host reports whenever a foreground command could be among the shells it counted — any running turn (docs/design/agent-cards.md, operator decision 3): the process tree cannot yet tell a foreground Bash call from a background one.

func NormalizeWorkEntry

func NormalizeWorkEntry(w WindowWork) WindowWork

NormalizeWorkEntry is normalizeWork for a count that is not a window's: a dispatched claude-code agent's, which its pod reports on POST /agent/work (internal/api/agent_work.go). The same clamp, so the two kinds of card can never show different bounds.

func (WindowWork) IsZero

func (w WindowWork) IsZero() bool

IsZero: nothing to show.

Jump to

Keyboard shortcuts

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