mirror

package
v0.151.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 37 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 (
	// 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 (
	// AskRefusalHermesGone: the approval is no longer pending in Hermes
	// (answered in the terminal, timed out, the turn ended). Nothing was
	// answered.
	AskRefusalHermesGone = "hermes-gone"
	// AskRefusalHermesUnreachable: the host could not reach Hermes's gateway
	// (none running, not the pinned commit, a control path that failed its
	// check). Nothing was answered.
	AskRefusalHermesUnreachable = "hermes-unreachable"
	// AskRefusalHermesUnknown: the answer reached Hermes's gateway, which did
	// not say how it went. It may have been answered.
	AskRefusalHermesUnknown = "hermes-unknown"
)

The refusals a host names on answered for a Hermes approval (Msg.Refusal).

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 (
	// 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"
	// KindHermes: the host reports a Hermes CLI in the pane
	// (Window.Runtime), whether or not it names the session.
	KindHermes   = "Hermes"
	KindOpenCode = "opencode"
	KindShell    = "shell"
)

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

View Source
const (
	PendingApproval = "approval"
	PendingClarify  = "clarify"
	PendingSudo     = "sudo"
)

The Hermes asks a Pending names (Pending.Kind), as Hermes's status hook records them (S2).

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 (
	HermesBusyText    = "Not sent: Hermes is working, and Enter would interrupt its turn. Queue it instead."
	HermesWaitingText = "Not sent: Hermes is waiting for you (an approval or a question). Answer it in the terminal first."
	HermesUnknownText = "Not sent: muster cannot tell whether Hermes is idle, and Enter could answer a prompt it is showing."
)

The idle gate's refusals, for the person sending.

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 (
	// RuntimeClaude: Claude Code. On the wire it is Window.Claude, never
	// Window.Runtime.
	RuntimeClaude = "claude"
	// RuntimeHermes: the Hermes CLI (`hermes chat`). No rendered view and no
	// send path yet: the window is detected and listed, nothing more.
	RuntimeHermes = "hermes"
)

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 (
	MaxAgentNote        = 200
	MaxAgentNoteWindows = 8
)

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

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 (
	// PasteRefusalHermes: the pane's process tree holds a Hermes-shaped
	// process. Nothing was typed.
	PasteRefusalHermes = "hermes"
	// PasteRefusalMultiplexer: the pane's process tree holds a terminal
	// multiplexer client (tmux, screen, dtach, abduco, zellij), which can hide
	// a Hermes the host cannot see. Nothing was typed.
	PasteRefusalMultiplexer = "multiplexer"
	// PasteRefusalUnchecked: the host could not read the pane's processes, so
	// it could not rule Hermes out. Nothing was typed.
	PasteRefusalUnchecked = "unchecked"
	// PasteRefusalOpenCode: the pane's process tree holds opencode. muster
	// cannot send to opencode yet (its send goes through opencode's own API,
	// not keystrokes, in a later version), 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 gated send into a Hermes pane (Msg.Runtime "hermes"), by how it
	// ended when it did not end "sent":
	//
	// PasteRefusalHermesNotSubmitted: refused before anything was pasted (the
	// text rules, the screen check, the Escape sequence's abort, the host's
	// -hermes-send off). Nothing was typed but, possibly, Escapes.
	PasteRefusalHermesNotSubmitted = "hermes-not-submitted"
	// PasteRefusalHermesSuperseded: the window's status moved after muster
	// decided (not idle, or idle since another time). Nothing was pasted; a
	// queued message can be decided on again.
	PasteRefusalHermesSuperseded = "hermes-superseded"
	// PasteRefusalHermesPasted: pasted, NOT submitted: the text is in
	// Hermes's input box and Enter was withheld. Not to be resent blindly.
	PasteRefusalHermesPasted = "hermes-pasted"
	// PasteRefusalHermesUnconfirmed: Enter was sent and Hermes recorded no
	// message in time: it MAY have been submitted. Never resent blindly.
	PasteRefusalHermesUnconfirmed = "hermes-unconfirmed"
)

The kinds of paste refusal a host names (Msg.Refusal on pasted): the Hermes paste guard's (docs/design/hermes.md). An older host names none, and muster then shows the host's prose as a plain refusal.

View Source
const (
	PasteRefusedHermesText = "Not sent: Hermes runs in this pane. muster sends to Hermes only from its window's " +
		"rendered view, and only on a host whose muster-mirror runs with -hermes-send, because Enter there can " +
		"answer a prompt Hermes is showing, such as a command approval. Type it in the terminal."
	PasteRefusedMultiplexerText = "Not sent: this pane runs another terminal multiplexer (tmux, screen, dtach, " +
		"abduco or zellij), so muster cannot see whether Hermes runs inside it. Type it in the terminal."
	PasteRefusedUncheckedText = "Not sent: muster-mirror could not check whether Hermes runs in this pane. " +
		"Type it in the terminal."
	PasteRefusedOpenCodeText = "Sending to opencode isn't supported yet: opencode runs in this pane, and muster " +
		"does not type into it, because Enter there can answer a prompt opencode is showing, such as a permission " +
		"request. Type it in the terminal."
	// 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 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 HermesKeyPrefix = RuntimeHermes + ":"

HermesKeyPrefix starts a Hermes conversation's session key.

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 MaxCommand = 32

MaxCommand bounds Window.Command, 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 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 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 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 RuntimeOpenCode = "opencode"

RuntimeOpenCode: opencode v2 (docs/design/opencode.md). A host whose pane runs an opencode TUI names the session the pane's title matches (Window.AgentSession), and muster draws its rendered view from the opencode server's API. It sends no message to it (the host's paste guard 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 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 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 (
	// 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")
	// ErrNoHermesStatus: the window runs Hermes and the host reports no status
	// for it — every host before Hermes mirroring's status hook, and one
	// whose hook wrote nothing. Unknown: nothing is sent to it.
	ErrNoHermesStatus = errors.New("mirror: the host cannot read whether this window's Hermes session is busy, so nothing is sent to it")
)
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 (
	// ErrHermesAnswerUnsupported: the host does not answer Hermes approvals
	// (an older or read-only muster-mirror, or one without -hermes-answer).
	ErrHermesAnswerUnsupported = errors.New("mirror: this host's muster-mirror does not answer Hermes approvals (it needs -interactive and -hermes-answer); answer it in the terminal")
	// ErrHermesApprovalGone: the window is no longer waiting on that
	// approval, or not with that choice. Nothing was answered.
	ErrHermesApprovalGone = errors.New("mirror: Hermes is no longer waiting on that approval")
	// ErrHermesUnreachable: the host could not reach Hermes's gateway.
	// Nothing was answered.
	ErrHermesUnreachable = errors.New("mirror: the host could not reach Hermes's gateway; answer it in the terminal")
	// ErrHermesAnswerUnknown: the answer was sent and no outcome came back in
	// time. It may have been answered: check the terminal.
	ErrHermesAnswerUnknown = errors.New("mirror: muster sent the answer but did not hear back; it may have been answered — check the terminal")
)
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 (
	// 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")
	// ErrHermesSendOff: the window runs Hermes and its host did not advertise
	// Msg.HermesSend — the hermesSend switch, closed (PasteWindow). Nothing
	// was sent to the host. It is the Cause of a *PasteRefusedError carrying
	// the host guard's own words (PasteRefusedHermesText, PasteRefusalHermes),
	// so a person sees the same refusal whichever side made it.
	ErrHermesSendOff = errors.New("mirror: muster did not send it: this window runs Hermes, and its host's muster-mirror does not accept a send to Hermes")
)
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 ErrHermesNotIdle = errors.New("mirror: muster did not send it: the Hermes window is not idle")

ErrHermesNotIdle is the cause of every *HermesNotIdleError.

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 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 HermesApprovalChoices = []string{"once", "deny"}

HermesApprovalChoices are the answers muster ever sends a Hermes approval: the moment being approved, or no. `session` and `always` widen what the agent may do beyond it (docs/design/hermes.md, open question 1), so muster never offers them.

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 (as HermesApprovalChoices leaves out `session` and `always`).

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 (0052 since opencode's prefix). A runtime that adds a KeyPrefix changes this pattern, so it fails that test until a NEW migration writes the wider CHECKs.

Functions ¶

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 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 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 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 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 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 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 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 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 ValidColor ¶

func ValidColor(c string) bool

ValidColor is whether c is a colour the wire carries.

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 ValidOpenCodeAskID ¶ added in v0.138.0

func ValidOpenCodeAskID(id string) bool

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

func ValidPromptID ¶

func ValidPromptID(id string) bool

ValidPromptID reports whether id is a Hermes request or approval 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 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 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 AgentState ¶

type AgentState struct {
	// Runtime is the agent CLI in the window (Window.AgentRuntime):
	// RuntimeClaude or RuntimeHermes — set whenever the hub knows it, ALSO when
	// Status is unknown, because the rules differ by runtime (Send now refuses
	// an unknown Hermes window, and pastes into an unknown Claude one). ""
	// 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; Hermes: the host's gated send).
	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 HermesApprovalAnswer ¶

type HermesApprovalAnswer struct {
	PromptID string `json:"promptId"`
	Choice   string `json:"choice"`
}

HermesApprovalAnswer is a Hermes approval's answer on the wire (Msg.HermesApproval).

type HermesNotIdleError ¶

type HermesNotIdleError struct{ Status string }

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

func (*HermesNotIdleError) Error ¶

func (e *HermesNotIdleError) Error() string

func (*HermesNotIdleError) Unwrap ¶

func (e *HermesNotIdleError) Unwrap() error

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
	// HermesSend: the host advertised Msg.HermesSend (it runs with
	// -hermes-send and is -interactive, v2): a Hermes window's rendered view
	// offers Send and Queue, through the host's gated send (Hermes Phase 3).
	HermesSend bool
	// HermesAnswer: the host advertised Msg.HermesAnswer (it runs with
	// -hermes-answer and is -interactive, v2): a Hermes approval muster shows
	// for one of its windows can be answered here (Hermes Phase 4).
	HermesAnswer 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
	// 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
	// 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
	// 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
	// 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) 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) GatedSendOn ¶

func (h HostView) GatedSendOn(r RuntimeSpec) (send, answers bool)

GatedSendOn reports whether h's host advertised the gated send of r (and, answers, that it answers r's asks) — read from the HostView's hello flags through r.Advertises, the one place a flag is mapped to its runtime.

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) AgentState ¶

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

AgentState is the state of the agent session (Claude Code or Hermes) 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; a Hermes window never does (its Runtime says which it is, and its status is read like Claude Code's).

func (*Hub) AnswerHermesApproval ¶

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

AnswerHermesApproval answers the Hermes approval promptID in one WINDOW of owner's host's session with choice, through the host's gateway viewer, and waits for the host's outcome. nil means Hermes took the answer.

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

A Hermes window's view (Phase 2) is the same stream: Gen is its conversation's id and the offset a messages.id; its host always answers a watch with a Reset backfill.

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 (paste) is the agent runtime muster decided this paste for.
	// "hermes" sends it to the host's GATED SEND into a Hermes pane (Hermes
	// Phase 3, docs/design/hermes.md; mirrorhost's hermes_send.go), which a
	// host runs only with -hermes-send; "" is every other paste, unchanged.
	// 🔴 A host never trusts it to OPEN anything: an unset Runtime aimed at a
	// Hermes pane still meets the host's paste guard, and "hermes" aimed at
	// a pane that runs no Hermes NOW is refused. An older host ignores it,
	// and muster never sends it one (an older host never advertises
	// HermesSend).
	Runtime string `json:"runtime,omitempty"`
	// Since (paste, Runtime "hermes") is the window's StatusSince the paste
	// was decided on. The host sends only while the window's status is still
	// idle at exactly this time, and refuses as superseded otherwise.
	Since int64 `json:"since,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"`
	// HermesSend (hello) is the host ADVERTISING that it accepts a paste into
	// a Hermes window (Window.Runtime RuntimeHermes), on an -interactive v2
	// host. 🔴 NO HOST SETS IT YET: the host's flag and its gated send arrive
	// together in Hermes Phase 3 (docs/design/hermes.md, the hermesSend
	// switch). muster refuses every paste into a window the host REPORTS as
	// Hermes unless the host advertised this (Hub.PasteWindow), so today every
	// such paste is refused before it reaches the host.
	//
	// âš  WHAT THIS GATE DOES NOT COVER: a window the host does not report as
	// Hermes. That is every window of a host older than this field, and any
	// Hermes the strict mirroring rule does not recognise (a profile-launched
	// `hermes -p coder chat`). Those rely on the host's own paste guard alone
	// (Hermes Phase 1a, mirrorhost's typeInto), and a host older than that
	// guard has none.
	//
	// NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS, like PanePaste: an older
	// muster ignores it (and never sees a Hermes window: it does not read
	// Window.Runtime); an older host never sets it.
	HermesSend bool `json:"hermesSend,omitempty"`
	// HermesAnswer (hello) is the host ADVERTISING that it answers a Hermes
	// approval through Hermes's gateway viewer (Hermes Phase 4,
	// hermes_answer.go): an -interactive v2 host that runs with
	// -hermes-answer. 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS: an
	// older muster ignores it; an older host never sets it, so muster never
	// sends it an answer, and every Hermes approval there is answered in the
	// terminal.
	HermesAnswer bool `json:"hermesAnswer,omitempty"`
	// HermesApproval (answer, with Runtime "hermes") is the Hermes approval to
	// answer and how: the PromptID muster showed (Pending.PromptID) and one of
	// HermesApprovalChoices. An older host, which never advertised
	// HermesAnswer, is never sent one.
	HermesApproval *HermesApprovalAnswer `json:"hermesApproval,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 HermesAnswer: 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"`
	// 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"`

	// 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"`

	// 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"`

	// 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 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"`
}

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

type PasteOptions ¶

type PasteOptions struct {
	Expect *Turn
	Window *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, on the host's behalf and in the host's words, before anything was sent (ErrHermesSendOff); 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 HERMES ASK (Hermes Phase 4, docs/design/hermes.md, "Questions and
	// approvals"): a waiting HERMES window's Pending also says which ask it
	// waits on, and for an approval 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).
	//
	// Kind is PendingApproval, PendingClarify or PendingSudo; "" otherwise.
	Kind string `json:"kind,omitempty"`
	// Detail is an approval's description (why Hermes asks), capped at
	// MaxPendingDetail like the rest.
	Detail string `json:"detail,omitempty"`
	// PromptID is the approval's id in Hermes's gateway — what an answer
	// names, so muster can only answer the approval it SHOWED. "" when the
	// host could not read the approval (its gateway viewer could not attach):
	// then there is nothing to answer here, and the card says so.
	PromptID string `json:"promptId,omitempty"`
	// Choices are the answers muster may send for PromptID, space-separated:
	// a subset of HermesApprovalChoices, in that order ("once deny"). Empty
	// without a PromptID. (A string, not a slice, so a Pending stays
	// comparable with ==.)
	//
	// An OPENCODE ask (PendingPermission, PendingQuestion) names its request
	// or form the same way: PromptID is opencode's id for it ("per…",
	// "frm_…"), and a permission's Choices a subset of
	// OpenCodePermissionChoices.
	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 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, RuntimeHermes, …).
	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 ("hermes:"); "" 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
	// GatedSend: muster sends to it only through the host's own gated send
	// (Msg.Runtime), only on a host that advertised it (Advertises), and only
	// while the window is idle with a status time; the paste carries that
	// time and waits PasteTimeout.
	GatedSend    bool
	PasteTimeout time.Duration
	// SendOff is the refusal of a send to a window of it on a host that did
	// not advertise its gated send, and SendOffErr that refusal's cause. nil
	// for a runtime without one.
	SendOff    func() error
	SendOffErr error
	// Advertises reads, from a host's hello, whether it sends (send) and
	// answers (answer) for this runtime itself. nil: it advertises neither.
	Advertises func(hello Msg) (send, answer bool)
	// NoStatus is AgentState's refusal when the host reports no status for a
	// window of it.
	NoStatus 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) 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) AnswerHermesApproval ¶

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

AnswerHermesApproval is Hub.AnswerHermesApproval 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) 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) 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) 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) 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) 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) 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:
	// RuntimeHermes, or ""), and AgentSession that runtime's session id
	// (Window.AgentSession), "" when the host names none — for Hermes, 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
	// 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
	// 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
	// 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 (Hermes's, 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) HermesView ¶

func (s SessionView) HermesView() bool

HermesView reports whether the entry is a Hermes window whose host names its conversation (AgentView, for Hermes).

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, KindHermes when it reports a Hermes CLI (its command reads python3.14, S10), 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) 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, a Hermes one runtime-qualified ("hermes:<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) 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 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: RuntimeHermes, or "" (Claude Code, which Claude says, or
	// no agent at all). AgentRuntime is the one way to read it.
	//
	// 🔴 "" 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 and its Hermes twin measure both).
	//
	// 🔴 A HERMES WINDOW 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
	// every current host's Hermes 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 (a Hermes id: "local-<64 hex>", or a rotated child's bare
	// 32-hex 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"`
	// 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"`
}

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: RuntimeHermes), 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) 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 a Hermes one runtime-qualified, "hermes:<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 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