mirrorhost

package
v0.211.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 54 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 mirrorhost is the HOST half of mirrored sessions: what `muster-mirror` runs on an operator's own machine. It lists the machine's tmux sessions, dials OUT to muster (the server half is internal/mirror), registers them, and serves the terminal attaches muster asks for over that one connection.

🔴 IT OPENS NO LISTENER. Everything arrives on the connection this process dialled, authenticated by this host's own mirror token — the only muster credential it ever holds.

Index

Constants

View Source
const (
	// SourcePaneMap: the pane map's entry for this pane, validated against the
	// process running in the pane (ClaudeLocator.PaneMapDir).
	SourcePaneMap = "pane-map"
	// SourceSessions: Claude Code's own sessions/<pid>.json (following a
	// parked background job to the job's session).
	SourceSessions = "sessions"
	// SourceGuessed: the newest transcript in the process's cwd — a guess.
	SourceGuessed = "guessed"
)

How a ClaudePane's transcript was resolved, most to least authoritative.

View Source
const (
	// NoViewNoProcs: the host cannot read its process table (an OS with
	// neither /proc nor the macOS backend, or the read failed), so Claude Code
	// cannot be found in any pane. Said only on a window whose command looks
	// like Claude Code (looksLikeClaudeCommand).
	NoViewNoProcs = "muster-mirror cannot read this host's process table, so it cannot find the Claude Code conversation in this window."
	// NoViewNotYet: Claude Code runs and named its session, but has written no
	// transcript for it yet — a CLI just started, before its first message.
	NoViewNotYet = "Claude Code has not written this conversation yet. The Rendered view appears after its first message."
	// NoViewNoTranscript: Claude Code runs, and neither its sessions file nor
	// its working directory leads to a transcript in its config directory that
	// is its alone — none at all, or only a guess another pane makes too
	// (LocatePanes: two windows are never shown one conversation).
	//
	// ⚠ ONE LINE FOR BOTH ON PURPOSE. The ambiguous guess had its own line,
	// "…neither names its conversation", which was FALSE when the other pane
	// does name it (its sessions file) and only this one guesses; this wording
	// is true in every case that reaches it.
	NoViewNoTranscript = "Claude Code is running here, but muster-mirror cannot match it to a transcript in its Claude config directory."
	// NoViewNoEnv: Claude Code runs, nothing resolved, and its environment
	// could not be read (configDirOfErr) — so which config directory it
	// writes to is unknown, and the fallback's guess found nothing.
	NoViewNoEnv = "" /* 132-byte string literal not displayed */
)

The lines the person reads when a window's pane runs Claude Code (or may) but the window has NO rendered view: why (mirror.Window.AgentNote, shown on its card and in its Terminal view). Whole sentences, each well inside mirror.MaxAgentNote, and never a path: the reason, not the host's layout.

View Source
const (
	MCPPaneHeader    = "X-Muster-Pane"
	MCPTmuxHeader    = "X-Muster-Tmux"
	MCPSessionHeader = "X-Muster-Claude-Session"
	// MCPAgentSessionHeader is what the proxy tells muster INSTEAD of
	// MCPSessionHeader for an opencode caller: the KEY of the session the
	// call was bound to (mirror.OpenCodeCallerKey, "opencode:<id>").
	MCPAgentSessionHeader = "X-Muster-Agent-Session"
	// MCPPath is muster's mirrored-sessions MCP door.
	MCPPath = "/mirror/mcp"
	// PreviewMCPPath is the endpoint's second MCP server: the preview tools,
	// served here and never forwarded (SetPreview).
	PreviewMCPPath = "/preview-mcp"

	// MCPClientHeader names the MCP client when its headers cannot name a
	// pane; MCPClientOpenCode is opencode's value (OpenCodeCaller).
	MCPClientHeader   = "X-Muster-Client"
	MCPClientOpenCode = "opencode"
)

MCPPaneHeader and MCPTmuxHeader are how a caller names itself: its pane and its tmux server. MCPSessionHeader is what the proxy tells muster.

View Source
const (
	// DefaultResumeSession is the tmux session resumed windows are started in.
	DefaultResumeSession = "muster-resume"
	// DefaultResumeClaude is the Claude Code binary a resume runs.
	DefaultResumeClaude = "claude"
)
View Source
const AgentSpawnDeadline = 120 * time.Second

AgentSpawnDeadline is the host's spawn deadline, from RECEIPT of the request (queue wait included): below the server's 150 s wait by a 30 s margin.

View Source
const ColorOption = "@muster-color"

ColorOption is the tmux user option a window's identity colour is read from. A constant on purpose: a host's tmux config sets it (window, session or global), and no flag or environment variable can name another.

View Source
const DefaultAgentSpawnRate = "3/10m,10/24h"

DefaultAgentSpawnRate is -agent-spawn-rate's default: 3 per 10 minutes and 10 per 24 hours (its daily part equals the server's daily cap).

View Source
const DefaultScrollIdle = 30 * time.Second

DefaultScrollIdle is how long a pane this host put in copy-mode stays there with no further scroll before the host cancels it (Config.ScrollIdle).

View Source
const LiveCopyWindow = 5 * time.Minute

LiveCopyWindow is how recently a copy no sessions file speaks for must have had a message to count as running elsewhere. Long enough to span a person reading a reply before answering; short enough that a copy that was closed stops being warned about within minutes.

View Source
const MinRawPasteTmux = tmuxver.MinRawPaste

MinRawPasteTmux is the first tmux release with `paste-buffer -S`, and the first whose plain `paste-buffer` sanitizes (tmuxver.MinRawPaste).

View Source
const SourceLauncher = "launcher"

SourceLauncher: an opencode pane bound by its launcher record.

View Source
const SourceProcess = "process"

SourceProcess: an AgentPane found by its process alone, with no session resolved yet.

View Source
const SourceTitle = "title"

SourceTitle: an opencode pane whose session was matched by its pane title, a heuristic (view-only).

View Source
const SubagentQuiet = ccsubagents.Quiet

SubagentQuiet is ccsubagents.Quiet: how long a subagent whose last row is a final reply must go without a new row before it is called done with no word from the parent.

Variables

View Source
var (
	// ErrClaudeWaiting: Claude Code's session status is waiting.
	ErrClaudeWaiting = errors.New(mirror.ClaudeWaitingText)
	// ErrClaudeDialog: the pane's screen shows a dialog.
	ErrClaudeDialog = errors.New(mirror.ClaudeDialogText)
	// ErrClaudeScreenUnread: the pane's screen could not be read.
	ErrClaudeScreenUnread = errors.New(mirror.ClaudeScreenUnreadText)
	// ErrClaudeBox: Claude Code's input box already holds text.
	ErrClaudeBox = errors.New(mirror.ClaudeBoxText)
	// ErrClaudeBoxUnread: no input box could be read on the screen.
	ErrClaudeBoxUnread = errors.New(mirror.ClaudeBoxUnreadText)
	// ErrClaudeUncheckable: the backend has no screen read or no checked
	// paste (ClaudeScreenBackend, ClaudeCheckedPaster), so the guard cannot
	// run at all. It is no refusal kind: it is not something that clears, so
	// a queued message fails on it rather than waiting.
	ErrClaudeUncheckable = errors.New("Not sent: this muster-mirror cannot check Claude Code's screen before and after typing, so it pastes nothing into a Claude Code pane.")
)

The Claude prompt guard's refusals. Their text is the person's (mirror's Claude*Text); internals are logged on the host.

View Source
var (
	// ErrMultiplexerPane: the pane's process tree holds a multiplexer client.
	ErrMultiplexerPane = errors.New(mirror.PasteRefusedMultiplexerText)
	// ErrPaneUnchecked: the guard could not read the pane's processes.
	ErrPaneUnchecked = errors.New(mirror.PasteRefusedUncheckedText)
	// ErrOpenCodePane: the pane's process tree holds opencode, which muster
	// does not type into (openCodeShape).
	ErrOpenCodePane = errors.New(mirror.PasteRefusedOpenCodeText)
)

The guard's refusals. Their text is the person's (mirror.PasteRefused*Text): muster shows a host's refusal as is. Never with internals appended — those are logged on the host.

View Source
var ErrNoRawPaste = fmt.Errorf("%w: this tmux server rejects `paste-buffer -S` yet reports version %s or later, whose plain paste-buffer sanitizes control keys", errCannotAnswer, MinRawPasteTmux)

ErrNoRawPaste: this tmux cannot paste keys raw (KeyPasteNone): its server rejects `paste-buffer -S` yet reports a version of 3.7 or later, whose plain paste sanitizes.

View Source
var ErrPaneBusy = errors.New("muster-mirror: another answer is being typed into this pane")

ErrPaneBusy: another answer is being typed into the pane.

View Source
var ErrPaneInAnotherMode = errors.New("muster-mirror: the pane is in another mode")

ErrPaneInAnotherMode: the pane's top mode is not copy-mode (choose-tree, a menu, view-mode). A scroll is refused with it (mirror.ScrollRefusalMode on the wire) and a cancel reports it, since copy-mode, if it is there at all, is under that mode where `-X cancel` cannot reach it.

View Source
var ErrUnauthorized = errors.New("muster refused this mirror token (unknown or revoked)")

ErrUnauthorized: muster refused the token (unknown, revoked, or not a mirror token). Run keeps retrying at the slowest backoff, so a token re-issued under the same id is picked up, but every attempt is logged.

Functions

func AgentSpawnLogTail added in v0.170.0

func AgentSpawnLogTail(w io.Writer, path string, n int) error

AgentSpawnLogTail prints the last n lines of the audit log (muster-mirror agent-spawn-log).

func BuildLabels

func BuildLabels(codenames, windows map[string]string, sessions []string) map[string]string

BuildLabels is the display label of each of sessions that has a codename: "<codename>:<active window index>", or the codename alone when the index is unknown. A session without a codename gets no label (muster shows its name); so does one whose label would not be valid (mirror.NormalizeLabels). nil when nothing is labelled.

func CheckedPaste

func CheckedPaste(ctx context.Context, paste, enter, before, beforeEnter func(context.Context) error) error

CheckedPaste is the checked paste for a backend that types by its own means (the tmux backend; a test or e2e fake): before, paste, enterDelay, beforeEnter, then enter.

func ConnectURL

func ConnectURL(base string, allowHTTP bool) (string, error)

ConnectURL is the WebSocket URL for base: http→ws, https→wss, plus mirror.ConnectPath under any path prefix base carries.

func DefaultMCPSecretFile

func DefaultMCPSecretFile() string

DefaultMCPSecretFile is where the local MCP secret is kept by default: the ONE rule in internal/mirrorpath, which `muster doctor` calls too.

func EnsureMCPSecret

func EnsureMCPSecret(path string) (string, error)

EnsureMCPSecret reads the secret from path, creating it (32 random bytes, hex; the file 0600, its directory 0700) when it does not exist. A file readable by others is refused rather than used.

func ListenMCP

func ListenMCP(addr string) (net.Listener, error)

ListenMCP listens on addr, which must be a literal loopback IP and a numeric port ("127.0.0.1:47823", "[::1]:47823"): MCPListenPort's.

func LoadCodenames

func LoadCodenames(path string) (codenames map[string]string, skipped []string, err error)

LoadCodenames reads a labels file: one JSON object, session name → codename. An entry whose key is not a valid session name or whose codename is not a valid label (mirror.ValidSession / mirror.ValidLabel) is DROPPED and named in the returned skipped list; only an unreadable file or one that is not a JSON object of strings is an error. The caller decides what an error costs — muster-mirror logs it once and runs without labels, never exits.

func MCPListenPort added in v0.185.0

func MCPListenPort(addr string) (int, error)

MCPListenPort is the port -mcp-listen names, and the ONE answer to "which port is the MCP endpoint on": digits only, 1-65535. Port 0 (the kernel picks) and a service name ("postgresql") are refused, because either would bind a port the text does not show — and previews, which must never expose this endpoint, read its port from the text (before, or without, the bind). ListenMCP binds exactly this port, so the text and the bound port agree.

func MCPTarget

func MCPTarget(base string, allowHTTP bool) (string, error)

MCPTarget is muster's /mirror/mcp URL for base.

func OpenCodeCaller added in v0.193.0

func OpenCodeCaller(r *http.Request) bool

OpenCodeCaller reports whether r is marked as opencode's (X-Muster-Client: opencode).

func ParseAgentSpawnRate added in v0.170.0

func ParseAgentSpawnRate(s string) ([]spawnRate, error)

ParseAgentSpawnRate reads -agent-spawn-rate: comma-separated <n>/<duration>, a duration with units m or h ("3/10m,10/24h").

func ParseAgentSpawnRepos added in v0.170.0

func ParseAgentSpawnRepos(s string) ([]string, error)

ParseAgentSpawnRepos reads -agent-spawn-repos: comma-separated <owner>/<repo> or <owner>/* (every repository of that owner: the repository part is exactly the literal "*"), lower-cased.

func PendingOf

func PendingOf(events []cctranscript.Event) *mirror.Pending

PendingOf is what a waiting session waits on, from its transcript's events (oldest first): the last tool call AFTER THE LAST PROMPT that has no result (an earlier one was interrupted, not pending), summarised, and the last text Claude wrote, each with what looks like a secret redacted (redact.Secrets), and the call's tool as a name (toolName). nil when there is neither. All are cleaned and capped (mirror.CleanPending).

func ProcTable added in v0.185.0

func ProcTable(root string) (map[int]ProcEntry, error)

ProcTable reads this host's process table through the SAME source the Claude Code locator walks (procSource: /proc on Linux, ps on macOS): every process's parent and name. root non-empty reads a Linux-style proc tree there instead (a test's fixture). The error is the source's own; a process that cannot be read is left out. For internal/previewhost's listener attribution, which walks from a listening process up to a pane's root.

func ProjectSlug

func ProjectSlug(cwd string) string

ProjectSlug is the directory name Claude Code keeps a cwd's transcripts under: every character that is not an ASCII letter or digit becomes '-' (/srv/my.repo → -srv-my-repo).

func ReadSubagentTail

func ReadSubagentTail(transcript, agent string) (mirror.SubagentTail, error)

ReadSubagentTail is the recent steps of agent in the subagents directory of transcript, redacted and bounded for the wire.

func ServeMCP

func ServeMCP(ctx context.Context, l net.Listener, h http.Handler) error

ServeMCP serves h on l until ctx ends.

func SessionActivity

func SessionActivity(ctx context.Context, b Backend, sessions []string, now time.Time) (map[string]int64, error)

SessionActivity is what a host SENDS for sessions: b's activity through mirror.NormalizeActivity (listed sessions only, floored to mirror.ActivityBucket, nothing later than now). nil when the backend cannot tell or the read failed — the error is returned for the caller to log, and muster then keeps the name order.

func SessionLabels

func SessionLabels(ctx context.Context, b Backend, codenames map[string]string, sessions []string) (map[string]string, error)

SessionLabels is BuildLabels over b's live active windows. With no codenames it asks the backend nothing. A failed window read is not fatal: the labels are then the codenames alone, and the error is returned for the caller to log.

func TitleMismatchWarning added in v0.160.0

func TitleMismatchWarning(title string) string

TitleMismatchWarning is the bound window's note while its pane's title shows another session than the recorded one (title, as the pane shows it).

func TurnEndOf

func TurnEndOf(r io.ReaderAt, size int64) *mirror.TurnError

TurnEndOf is how the latest turn in transcript r (of the given size) ended, as the file header says; nil when it did not end in an error, or r cannot be read.

func ViewClientFlags

func ViewClientFlags(readOnly bool) string

ViewClientFlags is the tmux client flags (-f) a window viewer attaches with.

  • ignore-size, ALWAYS: the viewer's client never takes part in sizing a window. 🔴 MEASURED on tmux 3.7c (the tmuxit suite's TestTmuxAWindowViewerNeverResizesWhatTheOperatorIsLookingAt): the operator's client is 150x40 on a window, a 60x20 client of another session that links the SAME window shows it, and without this flag the operator's window becomes 60x19 — under `window-size latest` (the default) and under `smallest`. A viewer of the window the operator has current is the ordinary case (it is the window at the top of the list). With the flag the window keeps the operator's size whichever window the viewer shows.
  • read-only for a read-only attach: tmux ignores the client's keys.

func WireWindows

func WireWindows(windows []WindowInfo, codenames map[string]string, claude bool, now time.Time) []mirror.Window

WireWindows is windows as a host SENDS them: labelled from codenames ("<codename>:<index>" for a session that has one), with Claude — and the Claude session's Status — kept only when claude is set (a tunnel that carries no rendered view carries no claim of one), through mirror.NormalizeWindows. A window of another runtime (Agent) carries its Runtime, AgentSession and status under the same condition; a Claude window's fields are exactly what they were before runtimes existed (mirror.Window.Runtime stays "").

Types

type ActivityReader

type ActivityReader interface {
	// Activity is session name → the Unix time of its last activity.
	Activity(ctx context.Context) (map[string]int64, error)
}

ActivityReader is a Backend that can say when each session was last active. Tmux is one; a backend that is not sends no activity, and muster lists its sessions in name order as before.

func ActivityReaderOf

func ActivityReaderOf(b Backend) (ActivityReader, bool)

ActivityReaderOf is b's ActivityReader, looking through wrappers (see ClaudeOf).

type AgentPane

type AgentPane = ClaudePane

AgentPane is one tmux pane running an agent CLI, of any runtime: ClaudePane under the name the seam uses. Its Runtime field says which; "" is Claude Code (every ClaudePane written before the seam).

func ResolveOpenCodePane

func ResolveOpenCodePane(s *OpenCodeSource, pane string, pid int, title string) AgentPane

ResolveOpenCodePane is the AgentPane of an opencode TUI (pid) in pane whose title is title, resolved against s exactly as the tmux backend resolves one (a client of the shared server). For a backend that knows its panes' titles another way — the browser suite's fake tmux, whose windows file names them.

func ResolveOpenCodePaneStarted added in v0.160.0

func ResolveOpenCodePaneStarted(s *OpenCodeSource, pane string, pid int, start, title string) AgentPane

ResolveOpenCodePaneStarted is ResolveOpenCodePane for a TUI whose process start time is start (/proc/<pid>/stat field 22): with it, a launcher record for the pane can bind it (opencode_launch.go).

type AgentSpawnConfig added in v0.170.0

type AgentSpawnConfig struct {
	// Enabled is -agent-spawn. OFF by default.
	Enabled bool
	// Roots are the directories whose DIRECT children are the clones a
	// worktree may be cut from.
	Roots []string
	// Dir is where worktrees go (<Dir>/<owner>__<repo>/<dispatch>).
	Dir string
	// Repos is the allow-list, <owner>/<repo>, EMPTY BY DEFAULT: an empty list
	// spawns nothing.
	Repos []string
	// Rate is -agent-spawn-rate ("" = DefaultAgentSpawnRate).
	Rate string
	// Log is the append-only audit log (JSON lines, 0600).
	Log string
	// Server is the muster URL this mirror connects to, recorded on each
	// request's first line.
	Server string
	// RuntimeDir is $XDG_RUNTIME_DIR: prompt files go under it ("" refuses).
	RuntimeDir string
	// TenantServer is -agent-spawn-tenant-server: the ONE non-default tmux
	// server this mirror may spawn on, named as -tmux-socket names a server
	// (a socket name) or as -tmux-socket-path does (an absolute socket path).
	// It must resolve to the very server this mirror mirrors; empty (the
	// default) keeps spawning on the default tmux server only (design 3.8).
	TenantServer string
	// KeepPermissionPrompts is -agent-spawn-skip-permissions=false: start each
	// spawned agent EXACTLY as before that flag existed — claude in its normal
	// permission mode, opencode without --auto. The zero value is the default:
	// a spawned agent starts WITHOUT permission prompts (spawnPermissionWords),
	// because muster assumes its sessions run without them and answers none
	// itself (docs/mirroring.md, "Permission prompts").
	KeepPermissionPrompts bool
	// Geteuid is the mirror's effective uid (nil = os.Geteuid). 🔴 AS ROOT,
	// CLAUDE KEEPS ITS PROMPTS: Claude Code exits 1 on bypassPermissions when
	// it runs as root outside a sandbox of its own, so a root mirror starts
	// claude in normal permission mode whatever the setting says, and its hello
	// says so (ClaudeSkipsPermissions). opencode's --auto is unaffected. No
	// flag sets it; a test sets it to say "root" without being root.
	Geteuid func() int

	// ClaudeBin, when set, is the claude binary (absolute); otherwise it is
	// resolved against the tmux server's global PATH.
	ClaudeBin string
	// OpenCodeBin, when set, is the opencode binary (absolute) whose version
	// is compared with the service's; otherwise `opencode` on the tmux
	// server's global PATH.
	OpenCodeBin string
	// MirrorBin, when set, is the launcher binary an opencode window runs
	// (`<MirrorBin> opencode -s <id>`); otherwise this process's own
	// executable, so the launcher and the daemon are one build.
	MirrorBin string
	// BindWait replaces openCodeBindWait (tests).
	BindWait time.Duration
	// ClaudeState, when set, is Claude Code's state file; otherwise
	// $CLAUDE_CONFIG_DIR/.claude.json, else ~/.claude.json.
	ClaudeState string
	// Git is the git binary, absolute: New resolves "git" on PATH into it
	// when it is unset ("" after that: no git, nothing is offered).
	Git string
	// Now is the clock (nil = time.Now).
	Now func() time.Time
	// Deadline replaces AgentSpawnDeadline (tests).
	Deadline time.Duration
	// TrustLockWait replaces claudeLockWait (tests).
	TrustLockWait time.Duration
	// contains filtered or unexported fields
}

AgentSpawnConfig is -agent-spawn and its sibling flags (docs/design/ chief-dispatch.md 3.2).

func (AgentSpawnConfig) ClaudeSkipsPermissions added in v0.200.0

func (c AgentSpawnConfig) ClaudeSkipsPermissions() bool

ClaudeSkipsPermissions reports whether a spawned claude starts without permission prompts: the setting is on AND the mirror is not root (Geteuid). THE one place that decides it — the argv (spawnSkips) and the hello both read it, so what muster is told is what the host runs.

func (AgentSpawnConfig) Root added in v0.200.0

func (c AgentSpawnConfig) Root() bool

Root reports whether the mirror runs as root (effective uid 0, Geteuid).

type AskBackend

type AskBackend interface {
	AnswerAsk(ctx context.Context, pane string, qs []askq.Question, choices []askdrive.Choice, prior *askq.Progress) (keys int, err error)
}

AskBackend answers an AskUserQuestion picker in a pane, continuing an answer an earlier one left part-typed in it (askdrive.DriveFrom): prior is what that one sent (nil: nothing), and keys how many keys of choices' plan the picker has received when it returns.

func AskOf

func AskOf(b Backend) (AskBackend, bool)

AskOf is b's AskBackend, if it has one (through any wrapper).

type AskCanceller

type AskCanceller interface {
	CancelAsk(ctx context.Context, pane string) (gone bool, err error)
}

AskCanceller dismisses the AskUserQuestion picker in a pane with one Escape: gone false when it was still showing after the Escape (askdrive.Cancel).

type Backend

type Backend interface {
	// List is the current session names.
	List(ctx context.Context) ([]string, error)
	// Attach starts a client on session at the given size (0 = backend default).
	Attach(ctx context.Context, session string, readOnly bool, cols, rows uint16) (Terminal, error)
}

Backend is where sessions come from: the host's tmux (Tmux), or a test's fake.

func NoShrink

func NoShrink(b Backend) Backend

NoShrink wraps b so that no attach — read-only or interactive — shrinks the session's window (internal/termsize.Decide), and so that the browser is told, in-band, the size its client really has. A b that cannot report window sizes is returned unchanged.

🔴 WHY HERE AND NOT IN THE BROWSER: the window's size is a fact only this host has. The browser asks for its own fit; this decides, and says what it decided. A browser that asks for something smaller anyway (an old page, a bug) still cannot reflow the operator's session.

🔴 WHY NOT tmux's `window-size largest`: that is a SESSION option, so setting it would change the operator's own tmux for every client they attach — their laptop's terminal would then be the one panning a window sized for their desktop — and it would outlive muster-mirror. It also does not help when the phone is the only client (largest of one is the phone). Sizing OUR client is the only change that touches nothing but muster's own view.

type CatalogScanner

type CatalogScanner struct {
	// Config is Claude Code's config directory ("" = $CLAUDE_CONFIG_DIR, else
	// ~/.claude).
	Config string
	// Home is the user's home directory, where the project walk stops ("" =
	// os.UserHomeDir).
	Home string
	// contains filtered or unexported fields
}

CatalogScanner reads catalogs. Its zero value reads the real locations; a test points each at a fixture. Safe for concurrent use.

func (*CatalogScanner) Scan

func (s *CatalogScanner) Scan(cwd string) mirror.Catalog

Scan is the catalog for a window whose pane runs in cwd ("" = unknown: the user's and the plugins' alone), normalised for the wire.

type ClaudeBackend

type ClaudeBackend interface {
	// ClaudePanes is, for each of sessions whose ACTIVE pane runs Claude Code
	// with a transcript this user can read, that pane. A session missing from
	// the map is not a Claude pane (or could not be resolved).
	ClaudePanes(ctx context.Context, sessions []string) map[string]ClaudePane
	// Paste types text into pane as ONE bracketed paste and presses Enter.
	Paste(ctx context.Context, pane ClaudePane, text string) error
}

ClaudeBackend is a Backend that can also see Claude Code in a session's pane: what the RENDERED VIEW needs (tunnel v2). The tmux backend implements it; a backend that does not simply has no rendered view.

func ClaudeOf

func ClaudeOf(b Backend) (ClaudeBackend, bool)

ClaudeOf is b's ClaudeBackend, looking THROUGH any wrapper around it (a wrapper exposes what it wraps with `Unwrap() Backend`, as NoShrink's does). It is the ONE way to ask a backend for this capability: a bare type assertion on a wrapped backend answers "no" for a backend that can.

type ClaudeCheckedPaster

type ClaudeCheckedPaster interface {
	PasteChecked(ctx context.Context, p ClaudePane, text string, before, beforeEnter func(context.Context) error) error
}

ClaudeCheckedPaster is a ClaudeBackend whose paste runs before immediately before the paste and beforeEnter immediately before its Enter, and presses Enter only when both pass. (Two checks, because the second must not refuse the box for holding the text just pasted.) The tmux backend implements it; a backend that does not is refused every Claude paste (ErrClaudeUncheckable) — a plain Paste's Enter is unchecked.

type ClaudeLocator

type ClaudeLocator struct {
	// Proc is the proc filesystem root ("" = /proc). A test points it at a
	// fixture tree.
	Proc string
	// Home is Claude Code's config dir ("" = $CLAUDE_CONFIG_DIR, else ~/.claude).
	Home string
	// PaneMapDir is the pane map's directory ("" = not consulted). One file per
	// tmux pane, claude-p<N>.json for pane %N, whose first line is a JSON
	// object {runtime: "claude", pane_id, tmux_pid, session_id,
	// transcript_path, claude_pid, claude_start} — the shape a Claude Code hook
	// writes (the format is documented in docs/mirroring.md).
	PaneMapDir string
	// contains filtered or unexported fields
}

ClaudeLocator maps panes to the Claude Code sessions running in them.

HOW (decided here, see the PR for the alternatives):

  1. THE PANE MAP, when PaneMapDir is set: a file per pane written by a Claude Code hook on every event that carries the conversation's id — so it names the conversation the pane SHOWS NOW. It is believed only after it is proved to still describe this pane (paneMapEntry.valid); anything else falls through to 2. Why it outranks 2: Claude Code does NOT rewrite sessions/<pid>.json when the conversation in a process changes id — a conversation moved to a background job (/bg) keeps the CLI's file naming the session it was forked FROM, for hours.
  2. Walk the pane's process tree from its root process (#{pane_pid}), breadth-first, to the nearest process that IS Claude Code (isClaude). A shell, `nix develop`, a wrapper script in between is fine.
  3. Claude Code records itself in <home>/sessions/<pid>.json — {sessionId, cwd, status}, written by the CLI for its own peers (status flips busy/idle per turn; a /clear moves sessionId). That names the transcript exactly: <home>/projects/<slug(cwd)>/<sessionId>.jsonl, and it is unambiguous when several sessions share one cwd. When the file says the CLI has a background job PARKED (parkedJobId), the pane shows that job: the live job's own sessions file (kind "bg", the same jobId) names the session.
  4. Fallback, for a CLI that writes no sessions file: the NEWEST *.jsonl in <home>/projects/<slug(the process's cwd)>/. ⚠ With two CLIs in one cwd and no sessions files, that is whichever wrote last — the one ambiguity this cannot resolve, and it is only reached on CLIs older than the sessions file. So a GUESSED transcript that another pane resolves to as well is dropped (LocatePanes): two panes are never shown one conversation, and a pane it cannot tell apart has no rendered view rather than a wrong one.

It reads only what the user muster-mirror runs as can read: its own processes (through procs(): /proc on Linux, ps/sysctl/lsof on macOS) and its own ~/.claude.

func (ClaudeLocator) Locate

func (l ClaudeLocator) Locate(panes []pane) map[string]ClaudePane

Locate maps each pane that runs Claude Code to its ClaudePane, keyed by the pane's session (one pane per session: each session's active pane).

func (ClaudeLocator) LocatePanes

func (l ClaudeLocator) LocatePanes(panes []pane) map[string]ClaudePane

LocatePanes maps each pane that runs Claude Code to its ClaudePane, keyed by the PANE id — so any number of panes of one session (one per window) each resolve to their own Claude Code process and so their own transcript.

🔴 TWO PANES NEVER SHARE A GUESSED TRANSCRIPT. A CLI that named its own session (its sessions file) is resolved exactly, however many share a cwd. A CLI that did not is GUESSED from its cwd (resolve's fallback), and two of those in one cwd guess the same file: whichever wrote last. Showing that one conversation under both windows would put the wrong transcript above a composer that sends to the right pane — so a guess that any other pane also resolves to is dropped, and that window opens in the Terminal instead.

type ClaudePane

type ClaudePane struct {
	// Runtime is the agent CLI in the pane: "" for Claude Code (so every
	// ClaudePane means what it did before the seam), mirror.RuntimeOpenCode
	// for opencode. Only a Claude Code pane is ever sent to.
	Runtime string
	// Pane is the tmux pane id (%12): the only input target — never the session
	// name, which resolves to whatever pane was focused last.
	Pane string
	// PID is the Claude Code process.
	PID int
	// Transcript is the absolute path of the session's JSONL transcript.
	Transcript string
	// Gen names that transcript: the Claude Code session id. It changes when
	// the pane's CLI starts another session (/clear, a restart), which is how a
	// rendered view knows to start over.
	Gen string
	// Busy: Claude Code reports a turn running.
	Busy bool
	// Status is Claude Code's own session status, as its sessions file states
	// it, read through mirror.NormalizeStatus (StatusBusy, StatusIdle,
	// StatusWaiting; "shell" — idle with a background shell running — as
	// StatusIdle); "" when it states none this side recognises, and for a
	// GUESSED transcript, which has no sessions file to read one from. Busy is
	// Status == busy.
	Status string
	// StatusSince is when Claude Code wrote Status — its sessions file's
	// statusUpdatedAt, Unix milliseconds — 0 when it states none (and whenever
	// Status is ""). The send queue reads idle-since from it.
	StatusSince int64
	// RawStatus is the sessions file's status AS WRITTEN — "shell" stays
	// "shell" — and StartedAt its startedAt (Unix ms): what the live work
	// counts read (work.go, internal/cctasks), never sent as they are. "" and 0
	// whenever Status has no sessions file behind it.
	RawStatus string
	StartedAt int64
	// Shells is the CLI's background shells from its process tree
	// (cctasks.CountShells), read by Tmux.Windows only while RawStatus says
	// something may be running (shell, busy, waiting); zero otherwise.
	Shells cctasks.Shells
	// Pending is what the session waits on while Status is waiting
	// (pending.go: read from the transcript's tail by the host's listing, not
	// by the locator); nil otherwise.
	Pending *mirror.Pending
	// LastMessage is the Unix time of the transcript's last message
	// (lastmsg.go: read from its tail by the host's listing, not by the
	// locator); 0 when unknown.
	LastMessage int64
	// TurnError is how the latest turn ended when it ended in an error the CLI
	// wrote itself (turnend.go: read from the transcript's tail by the host's
	// listing, for an idle window only); nil otherwise.
	TurnError *mirror.TurnError
	// ReplyAt is, for an idle window whose latest turn ended in a real answer,
	// that answer's time (Unix ms, host clock; turnend.go); 0 otherwise. Not
	// on the wire: the host's limit reads it (hostLimitOf).
	ReplyAt int64
	// LiveCopy is the session id of another transcript of this conversation,
	// in the same project directory, that is still running elsewhere
	// (livecopy.go: set by Tmux.Windows when its LiveCopies is set); "" for
	// none.
	LiveCopy string
	// Source says how Transcript was found: SourcePaneMap, SourceSessions or
	// SourceGuessed (see ClaudeLocator).
	Source string
	// OpenCode is how an opencode pane resolved (its title, the match, why it
	// has no rendered view): what -list -opencode prints. nil for the other
	// runtimes, and for a host with no OpenCodeSource.
	OpenCode *OpenCodePane
	// Note is the line the person reads about the pane (mirror.Window.
	// AgentNote): for opencode, why it has no view, or what its token needs.
	Note string
	// Send: the host sends to this pane's session (Gen) through its runtime's
	// API (mirror.Window.AgentSend): an opencode pane its launcher record
	// binds (SourceLauncher). Never for Claude Code, whose send is a paste.
	Send bool
	// Bind is how a TITLE-matched opencode pane's binding came out
	// (mirror.Window.AgentBind, opencode_bind.go): mirror.AgentBindVerified —
	// the host sends to it, to a paste naming its session — or why it does
	// not. "" for every other pane.
	Bind string
	// ConfigDir is the Claude Code config dir this pane's CLI writes under
	// (ClaudeLocator.configDirOf); "" for another runtime's pane. Not on the
	// wire: what the host reads the CLI's own files from (its shell snapshots).
	ConfigDir string
}

ClaudePane is one tmux pane running Claude Code — or, with Runtime set, another agent CLI: it is also the runtime seam's AgentPane (runtime.go).

type ClaudePastedError

type ClaudePastedError struct{ Why error }

ClaudePastedError: the check before the Enter refused, after the text was pasted. The text is in Claude Code's input box; Enter was not pressed.

func (*ClaudePastedError) Error

func (e *ClaudePastedError) Error() string

func (*ClaudePastedError) Unwrap

func (e *ClaudePastedError) Unwrap() error

type ClaudeScreenBackend

type ClaudeScreenBackend interface {
	// ClaudeScreen is pane's screen, wrapped lines joined, with its styles
	// (capture-pane -p -e -J): the box check tells a dim ghost suggestion from
	// text by them (ccdialog.InputBox). A capture without styles still reads,
	// but then a suggestion reads as text.
	ClaudeScreen(ctx context.Context, pane string) (string, error)
}

ClaudeScreenBackend is a backend that can read a Claude Code pane's screen for the prompt guard. The tmux backend implements it; a backend that does not is refused every Claude paste (ErrClaudeUncheckable).

type Client

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

Client runs one host's connection to muster.

func New

func New(cfg Config) (*Client, error)

New validates cfg and builds a client.

func (*Client) AgentSpawnUnavailable added in v0.170.0

func (c *Client) AgentSpawnUnavailable() string

AgentSpawnUnavailable is why this host cannot spawn agents now ("" when it can): what the daemon logs at startup.

func (*Client) RefreshNow

func (c *Client) RefreshNow(ctx context.Context) error

RefreshNow re-reads this host's windows and, if they changed, sends them to muster NOW rather than at the next Refresh — returning once that is done (or ctx ends). The MCP endpoint calls it before forwarding a tool call, so muster hears of a Claude session that started since the last refresh before the call arrives. The read and send run in the connection's own refresh goroutine, the only one that sends listings.

func (*Client) Run

func (c *Client) Run(ctx context.Context) error

Run connects, and reconnects with jittered exponential backoff (1s → 60s), until ctx ends. A connection that stayed up for a minute resets the backoff.

func (*Client) RunOnce

func (c *Client) RunOnce(ctx context.Context) error

RunOnce makes one connection and serves it until it ends.

It speaks the newest tunnel version (mirror.ProtocolVersion) and, when a v1 muster refuses that with its version error, reconnects AT ONCE as v1: the sessions and terminals work as before, with no rendered view, instead of the host staying offline until muster is upgraded. The next connection tries the newest version again, so an upgraded muster is picked up.

func (*Client) SweepAgentWorktrees added in v0.170.0

func (c *Client) SweepAgentWorktrees(ctx context.Context, live map[int64]bool)

SweepAgentWorktrees removes every spawned worktree under the agents directory whose dispatch names no live tagged window, when it holds nothing: a clean working tree and no commit the remote lacks. Anything else is KEPT and logged with the reason. Never forced: `worktree remove` without --force, and the branch deleted only by `update-ref -d` against the tip it was verified at. It also deletes prompt files more than an hour old.

type Config

type Config struct {
	// URL is muster's base URL (https://muster.example.com, or a path prefix).
	URL string
	// Token is this host's mirror token (mirror.TokenPrefix…).
	Token string
	// Host is this host's name; it must be the host the token was minted for.
	Host    string
	Backend Backend
	// Refresh is how often the session list is re-read (default 5s); a change is
	// sent at once.
	Refresh time.Duration
	// ViewPoll is how often an open rendered view's transcript is checked for
	// new lines (default 300ms): what "live while a turn runs" costs — one stat
	// per open view per tick.
	ViewPoll time.Duration
	// Interactive lets muster open INTERACTIVE terminals on this host. It is OFF
	// by default (muster-mirror's -interactive flag): a host that did not opt in
	// is read-only — it advertises so in its hello, so muster offers no
	// Interactive switch and refuses a rw attach, and this side refuses one too.
	//
	// 🔴 INTERACTIVE IS A SHELL ON THIS HOST. An interactive tmux client can
	// switch to any session on the server or open a new window, so whoever can
	// use muster's Interactive switch for this host can run commands here as the
	// user muster-mirror runs as. Turn it on only where that is intended.
	Interactive bool
	// OpenCodeSend lets muster SEND a message to an opencode session on this
	// host through the opencode server's API (muster-mirror's -opencode-send),
	// with Interactive and an opencode token: only to a pane started by
	// `muster-mirror opencode` (docs/design/opencode-first-class.md). Off by
	// default. 🔴 It lets muster prompt an agent here: whatever that agent may
	// run, a message from muster can ask it to.
	OpenCodeSend bool
	// Codenames is session name → codename (LoadCodenames). A listed session
	// with one is shown in muster as "<codename>:<active window index>"
	// (BuildLabels); nil labels nothing, and then no window index is read.
	Codenames map[string]string
	// AllowHTTP permits a plain http:// URL — FOR TESTS AND LOCAL DEVELOPMENT
	// ONLY; the documented install is https. Without it only https is accepted:
	// the token travels in the Authorization header of every connect.
	AllowHTTP bool
	// NoPromptIndex makes this host behave as one that predates the prompt
	// index (mirror.Msg.PromptIndex): a fresh view gets its backfill and no
	// index, and no event names its prompt's place (Event.Line). FOR THE BROWSER SUITE'S OLDER-HOST CASE ONLY (cmd/muster-mirror's
	// e2emirror build); no flag sets it.
	NoPromptIndex bool
	Logger        *log.Logger
	// ScrollIdle is how long a pane this host put in copy-mode for a scroll
	// stays there with no further scroll before it is cancelled (default
	// DefaultScrollIdle). A test shortens it.
	ScrollIdle time.Duration
	// Catalog reads the composer menu's catalog (catalog.go); nil = the real
	// locations.
	Catalog *CatalogScanner
	// NoCatalog makes this host behave as one that predates the catalog
	// (mirror.Msg.CatalogReport): it advertises none and answers no request.
	// FOR THE BROWSER SUITE'S OLDER-HOST CASE ONLY (cmd/muster-mirror's
	// e2emirror build); no flag sets it.
	NoCatalog bool
	// NoSubagents makes this host behave as one that predates the subagent
	// cards (mirror.Msg.SubagentReport): no summaries on a view's stream, none
	// advertised, no tail request answered. FOR THE OLDER-HOST TESTS ONLY
	// (cmd/muster-mirror's e2emirror build); no flag sets it.
	NoSubagents bool
	// NoWork makes this host behave as one that predates the live work counts
	// and identity colours (mirror/work.go): it sends no work and no colors
	// message. FOR THE OLDER-HOST TESTS ONLY (cmd/muster-mirror's e2emirror
	// build); no flag sets it.
	NoWork bool
	// Previews reports, per tmux window id, what the host's preview side
	// offers and has open now (mirror/previews.go): cmd/muster-mirror's
	// -preview hands in its previewhost.Host's summary. nil — no -preview, or
	// previews not (yet) on — sends no previews message, so muster draws no
	// Preview button. Called on every refresh; it must not block.
	Previews func() map[string]mirror.WindowPreviews
	// FakeSpawn, when set, REPLACES the agent spawn (agentspawn.go) with a
	// fixture's: this host advertises FakeSpawnRuntimes and answers each
	// agent-spawn with what FakeSpawn returns. FOR THE BROWSER SUITE ONLY
	// (cmd/muster-mirror's e2emirror build); no flag sets it, and a shipped
	// build leaves it nil (TestTheShippedBuildSpawnsForReal).
	FakeSpawn         func(ctx context.Context, dispatch int64, req mirror.AgentSpawnReq) (mirror.AgentSpawned, error)
	FakeSpawnRuntimes []string
	// AgentCloseGrace replaces mirror.AgentCloseGrace (tests).
	AgentCloseGrace time.Duration
	// ResumeSpawn lets muster ask this host to RESUME an ended Claude Code
	// session in a new tmux window (muster-mirror's -resume-spawn,
	// MUSTER_MIRROR_RESUME_SPAWN; resume.go): with -interactive, the host
	// advertises Msg.ResumeSpawn. OFF by default: it starts a process here.
	ResumeSpawn bool
	// ResumeSession is the tmux session resumed windows start in (""
	// = DefaultResumeSession); ResumeClaude the Claude Code binary they run
	// ("" = DefaultResumeClaude, found on the tmux server's PATH).
	ResumeSession string
	ResumeClaude  string
	// ResumeLocator is where a resume finds transcripts (its Home) and live
	// Claude Code processes (its Proc); the zero value is ~/.claude and /proc.
	ResumeLocator ClaudeLocator
	// AgentSpawn is -agent-spawn and its sibling flags (agentspawn.go): the
	// chief starts agents on this host. OFF by default.
	AgentSpawn AgentSpawnConfig
}

Config is one muster-mirror's configuration.

type CwdResolver

type CwdResolver interface {
	// WindowCwd is the working directory of window's active pane in session —
	// of its Claude Code process when the pane runs one — or an error.
	// window == "" is the session's active window.
	WindowCwd(ctx context.Context, session, window string) (string, error)
}

CwdResolver is a Backend that can say where a window's pane runs: what the catalog's PROJECT commands and skills are found from. Tmux is one; a backend that is not gets the user's and the plugins' alone.

func CwdResolverOf

func CwdResolverOf(b Backend) (CwdResolver, bool)

CwdResolverOf is b's CwdResolver, looking through wrappers.

type GuardProc added in v0.156.0

type GuardProc struct {
	// PID is the process.
	PID int
	// Rule names which pattern matched (one of the rule* constants): what a
	// log line or a diagnostic prints. Never argv, which can hold anything
	// the person typed.
	Rule string
}

GuardProc is the process in a pane's tree that made the guard refuse.

type KeyPaste added in v0.106.0

type KeyPaste int

KeyPaste is how a tmux pastes a picker's keys so they arrive as keys.

const (
	// KeyPasteUnknown: not known — no tmux server running and a `tmux -V` it
	// cannot read; a server this client cannot talk to; or a server that
	// rejects -S but whose #{version} could not be read (a timeout, say).
	// Typed as KeyPasteRawFlag: a server without -S refuses that paste, so no
	// key goes in sanitized, and the next answer asks again.
	KeyPasteUnknown KeyPaste = iota
	// KeyPasteRawFlag: `paste-buffer -S` (tmux 3.7 and later).
	KeyPasteRawFlag
	// KeyPastePlain: `paste-buffer` with no flag — a tmux before 3.7, whose
	// paste never sanitized (tmuxver.MinRawPaste).
	KeyPastePlain
	// KeyPasteNone: cannot. The server rejects -S yet reports #{version} 3.7
	// or later — a contradiction no released tmux shows (3.7 added -S), so a
	// patched or mislabelled build: its plain paste may sanitize, and -S
	// cannot be sent.
	KeyPasteNone
)

func (KeyPaste) String added in v0.106.0

func (k KeyPaste) String() string

String names it in test failures.

type LiveCopies added in v0.106.0

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

LiveCopies finds each Claude window's live copy (ClaudePane.LiveCopy). Set on Tmux it runs on every listing; its caches make that cheap. Safe for concurrent use; the zero value is ready.

type MCPProxy

type MCPProxy struct {
	// URL is muster's base URL (as Config.URL); Token this host's mirror token.
	URL   string
	Token string
	// AllowHTTP permits a plain http:// URL (tests and local development).
	AllowHTTP bool
	// Secret is what a local caller must present.
	Secret string
	// Windows lists this host's windows: how a pane is resolved to its Claude
	// session. nil resolves none.
	Windows WindowLister
	// Socket is this host's tmux server: a caller's $TMUX must name it to be
	// forwarded (any other is answered as a server with no tools). nil
	// (a backend that is not tmux) skips the check.
	Socket ServerSocketer
	// Refresh sends muster this host's listing NOW (Client.RefreshNow), so a
	// session that started since the last refresh is known there before its
	// call arrives. nil skips it.
	Refresh func(context.Context) error
	// Client sends the forwarded request; nil is a client with no overall
	// timeout (attention_wait long-polls for up to ten minutes).
	Client *http.Client
	Logger *log.Logger
	// Version is what an `initialize` this endpoint answers itself names as
	// the server's version (answerOutsider); "" reads "dev".
	Version string
	// OpenCodeAncestors is an opencode session's parent, its parent's, …
	// nearest first (OpenCodeSource.Ancestors): how a subagent's child
	// session finds the window showing its root. nil: only a session a
	// window shows itself is found.
	OpenCodeAncestors func(id string) []string
	// contains filtered or unexported fields
}

MCPProxy is the local endpoint's handler.

func (*MCPProxy) CallerWindow added in v0.186.0

func (p *MCPProxy) CallerWindow(r *http.Request, agentSession string) (string, error)

CallerWindow is the tmux window ("@12") a preview tool's caller is in now, from a FRESH listing. agentSession is the calling agent session the call itself names (opencode's params._meta["ai.opencode/sessionID"]; "" none).

An opencode-marked request (OpenCodeCaller) is resolved by agentSession alone (openCodeBinding). Any other is resolved by its pane — its X-Muster-Pane, ANY pane of the window — and agentSession is not read: unlike session it needs no Claude Code session in the pane, as a preview belongs to the window, whatever runs in it. The guard has already checked such a caller's tmux server (checkServer: pane ids are per server).

func (*MCPProxy) ServeHTTP

func (p *MCPProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves the endpoint's two MCP servers, each behind the same guard (guarded): /mcp, muster's tools, forwarded (serveMuster); and, once SetPreview mounted it, PreviewMCPPath, the preview tools, answered on this machine and never forwarded (docs/design/previews.md, "The MCP tools"). Any other path — /preview-mcp too while it is not mounted — is 404.

func (*MCPProxy) SetPreview added in v0.186.0

func (p *MCPProxy) SetPreview(h http.Handler)

SetPreview mounts h at PreviewMCPPath, behind the same guard as /mcp (guarded). muster-mirror calls it once previews are on: -preview and a valid previews.json (cmd/muster-mirror's startPreview). Until then — and for good when previews are off — that path is 404, like any other.

🔴 A SEPARATE SERVER, NOT AN APPEND TO MUSTER'S LIST: /mcp is forwarded exactly as before, so a muster outage still fails the "muster" server loudly (502) while the preview tools work or fail on their own.

type OpenCodePane

type OpenCodePane struct {
	// PaneTitle is the pane's title as tmux reported it ("" when it could not
	// be read).
	PaneTitle string
	// Match is how the title resolved against the server's root sessions.
	Match opencodehost.Match
	// Server is the opencode server's state when the pane was resolved: ""
	// when it answered, else why muster cannot read it (no token, refused,
	// unreachable).
	Server string
	// NoView is why the pane has no rendered view, "" when it has one.
	NoView string
	// Warning is said of a launcher-bound pane whose title shows another
	// session than the recorded one (TitleMismatchWarning); "" for none.
	Warning string
}

OpenCodePane is how an opencode pane resolved: what -list -opencode prints.

type OpenCodeSource

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

OpenCodeSource is the host's opencode v2 server, as muster-mirror reads it with its pair token: the root sessions (refreshed when the event stream says they changed, and at most every sessionsMaxAge), each session's status from the event stream (session.status), and a change counter per session that a rendered view polls. ONE event stream for the whole host, opened on the first opencode pane and kept open (reconnecting) for the daemon's life.

func NewOpenCodeSource

func NewOpenCodeSource(ctx context.Context, creds *opencodehost.Credentials, why string, logger *log.Logger) *OpenCodeSource

NewOpenCodeSource is the source for creds (nil: why says why there is none — every opencode window then has no view, and that reason). Its event stream lives until ctx ends.

func OpenCodeSourceOf added in v0.193.0

func OpenCodeSourceOf(b Backend) *OpenCodeSource

OpenCodeSourceOf is b's OpenCodeSource, looking through wrappers; nil for none.

func (*OpenCodeSource) Ancestors added in v0.193.0

func (s *OpenCodeSource) Ancestors(id string) []string

Ancestors is session id's parent, that one's parent, and so on — nearest first, at most maxOpenCodeAncestors — from the server's session list (knownSessions): how a subagent's child session, which a TUI does not show, is traced to the root session its window shows (MCPProxy's openCodeBinding). An id the list does not hold, or a list that cannot be read, has none. A cycle ends the walk.

func (*OpenCodeSource) Changes added in v0.138.0

func (s *OpenCodeSource) Changes() (<-chan struct{}, func())

Changes is a channel that receives (coalesced) whenever an ask is raised or settled, and its cancel: what a connection listens on to send its listing at once rather than at the next refresh.

func (*OpenCodeSource) SetLaunches added in v0.160.0

func (s *OpenCodeSource) SetLaunches(dir, socket string)

SetLaunches has s bind panes by the launcher records under dir for the tmux server at socket (this daemon's). Without it, no pane is bound.

type OpenCodeSourcer

type OpenCodeSourcer interface {
	OpenCodeSource() *OpenCodeSource
}

OpenCodeSourcer is a backend that resolves opencode windows' sessions (Tmux with an OpenCodeSource).

type PaneBackend

type PaneBackend interface {
	// ActivePane is session's active pane (of its active window) as an input
	// target, and false when the session has none this backend can resolve.
	ActivePane(ctx context.Context, session string) (string, bool)
	// PastePane types text into pane as ONE bracketed paste and presses Enter.
	PastePane(ctx context.Context, pane, text string) error
}

PaneBackend is a Backend that can type into a session's ACTIVE pane whatever runs in it — a shell, another TUI: what the Terminal view's composer needs for a session with no rendered view. The tmux backend implements it.

func PaneOf

func PaneOf(b Backend) (PaneBackend, bool)

PaneOf is b's PaneBackend, looking through wrappers like ClaudeOf.

type PaneGuardBackend added in v0.156.0

type PaneGuardBackend interface {
	// PaneGuard is the process in pane's tree that makes the guard refuse,
	// read NOW (PaneProcs.InTree); false when it holds none. An error means
	// it could not be checked.
	PaneGuard(ctx context.Context, pane string) (GuardProc, bool, error)
}

PaneGuardBackend is a backend that can tell what runs in a pane: the paste guard's view of it. The tmux backend implements it. A backend that does not (a test's fake, the browser suite's fake tmux) has no processes to look at, and what it types is not guarded.

func PaneGuardOf added in v0.156.0

func PaneGuardOf(b Backend) (PaneGuardBackend, bool)

PaneGuardOf is b's PaneGuardBackend, looking through wrappers.

type PaneProcs added in v0.156.0

type PaneProcs struct {
	// Proc is the proc filesystem root ("" = /proc). A test points it at a
	// fixture tree, as ClaudeLocator's do.
	Proc string
}

PaneProcs reads what runs in a pane from the proc filesystem: the paste guard's process walk.

func (PaneProcs) InTree added in v0.156.0

func (h PaneProcs) InTree(root int) (GuardProc, bool, error)

InTree is the nearest process at or below root (a pane's #{pane_pid}), breadth-first, that makes the guard refuse — an opencode process on the pane's terminal or a multiplexer client — and true; or false when the tree holds none.

The error is the guard's fail-closed case, which the caller refuses on: the proc root could not be read; root is not in it; a process in the tree could not be read (its stat, or its cmdline); or the tree is larger than the walk's bound. A process's children are taken from the parent links AND from the kernel's own lists (/proc/<pid>/task/<tid>/children), so a child absent from the table is still found. Such a child is read on its own then (readProcEntry): one forked after the table was read — a busy Claude Code pane's tool calls fork constantly — is walked like any other, one that has exited meanwhile is skipped, and only one that still cannot be read refuses. A process whose command line reads empty (mid-exec, exiting) is read once more the same way, and refuses only if it is still alive with none. A zombie is skipped: it reads no input. The one exception is a host with no proc filesystem at all (not Linux, default root): there is nothing to walk, so it answers false — a ratified gap, not a check that passed.

type PaneReader added in v0.198.0

type PaneReader interface {
	CapturePane(ctx context.Context, pane string) (string, error)
}

PaneReader is a backend that can read a pane's screen: what a refused answer sends back as its snapshot (Msg.Screen).

type ProcEntry added in v0.185.0

type ProcEntry struct {
	PPID int
	Comm string
}

ProcEntry is one process as a reader outside this package needs it: its parent and its name.

type ResumeBackend

type ResumeBackend interface {
	// NewResumeWindow starts a DETACHED window named name in session (the
	// session created when absent), with working directory dir, running argv
	// with the user's login environment (each element one argument; nothing
	// interpreted by a shell), and answers its tmux window id.
	NewResumeWindow(ctx context.Context, session, name, dir string, argv []string) (string, error)
}

ResumeBackend is a Backend that can start a new window running a command. The tmux backend implements it.

func ResumeOf

func ResumeOf(b Backend) (ResumeBackend, bool)

ResumeOf is b's ResumeBackend, looking through wrappers like ClaudeOf.

type Runtime

type Runtime interface {
	// Name is the runtime's wire name: mirror.RuntimeClaude or
	// mirror.RuntimeOpenCode.
	Name() string
	// LocatePanes maps each of panes that this runtime CLAIMS — by the
	// process running in it, never by #{pane_current_command} — to the agent
	// session in it, keyed by pane id, reading the proc table procs/children
	// (readProcTable), which the caller reads ONCE for every runtime. The
	// tmux backend asks each runtime in turn, Claude Code first, and the first
	// to claim a pane has it.
	LocatePanes(panes []pane, procs map[int]procInfo, children map[int][]int) map[string]AgentPane
}

Runtime is one agent CLI this host knows.

type ScrollBackend

type ScrollBackend interface {
	// ScrollPane scrolls pane by lines (positive is back, mirror.Msg.Lines).
	// A pane in no mode is put in copy-mode (`copy-mode -e`) first — only for a
	// scroll BACK; a scroll forward of a pane in no mode is already at the
	// bottom and does nothing. entered reports that this call entered
	// copy-mode; inMode that the pane is in copy-mode afterwards (false once
	// -e has left it at the bottom).
	ScrollPane(ctx context.Context, pane string, lines int) (entered, inMode bool, err error)
	// CancelCopyMode leaves copy-mode on pane; a pane in no mode is left alone
	// (nil). A pane whose top mode is another one is left alone too, and
	// answers ErrPaneInAnotherMode: copy-mode may be under it.
	CancelCopyMode(ctx context.Context, pane string) error
}

ScrollBackend is a Backend that can scroll a pane through its history in tmux copy-mode. The tmux backend implements it.

func ScrollOf

func ScrollOf(b Backend) (ScrollBackend, bool)

ScrollOf is b's ScrollBackend, looking through wrappers like ClaudeOf.

type ServerSocketer

type ServerSocketer interface {
	ServerSocket(ctx context.Context) (string, error)
}

ServerSocketer is a backend that can name its tmux server's socket — what a caller's $TMUX must name for the local MCP endpoint (MCPProxy) to believe its pane.

func ServerSocketOf

func ServerSocketOf(b Backend) (ServerSocketer, bool)

ServerSocketOf is b's ServerSocketer.

type StatusReporter

type StatusReporter interface {
	ReportsStatus() bool
}

StatusReporter is a WindowLister that fills each Claude window's ClaudePane.Status from Claude Code's own sessions file — what a hello's Msg.StatusReport advertises, and what muster's send queue waits on. Tmux is one. A backend that is not is believed about no status (muster sends nothing queued to it).

type Terminal

type Terminal interface {
	io.ReadWriteCloser
	Resize(cols, rows uint16) error
}

Terminal is one attached client: Read is its screen, Write its keyboard. Close ends the client and never the session.

type Tmux

type Tmux struct {
	// Bin is the tmux binary ("" = "tmux" on PATH).
	Bin string
	// Socket is tmux's -L socket NAME; SocketPath its -S socket PATH. Both empty
	// means tmux's default socket — the server an operator's plain `tmux` uses.
	Socket     string
	SocketPath string
	// Claude finds Claude Code in a session's pane (the rendered view); its
	// zero value reads /proc and the user's own ~/.claude. Its Proc is also
	// the proc root the opencode runtime and the paste guard read.
	Claude ClaudeLocator
	// OpenCode is the host's opencode server, which opencode windows' sessions
	// and status are read from (opencode.go); nil detects opencode windows
	// without resolving them.
	OpenCode *OpenCodeSource
	// LiveCopies, when set, finds each Claude window's live copy: another
	// transcript of its conversation still running elsewhere (livecopy.go,
	// mirror.Window.LiveCopy). nil looks for none.
	LiveCopies *LiveCopies
}

Tmux is the real Backend: the host's own tmux server.

func ParseAgentSpawnTenantServer added in v0.184.0

func ParseAgentSpawnTenantServer(s string) (Tmux, error)

ParseAgentSpawnTenantServer reads -agent-spawn-tenant-server: "" (off), a socket name (-L form) or an absolute socket path (-S form). It answers the server as a Tmux whose resolvedTmuxSocket can be compared with the mirror's.

func (Tmux) ActivePane

func (t Tmux) ActivePane(ctx context.Context, session string) (string, bool)

ActivePane implements PaneBackend: session's active pane id, from the same `list-panes` read ClaudePanes resolves a Claude pane with — so for a session whose pane runs Claude Code the two name the SAME pane.

func (Tmux) ActiveWindows

func (t Tmux) ActiveWindows(ctx context.Context) (map[string]string, error)

ActiveWindows implements WindowIndexer with one `tmux list-sessions`.

In list-sessions' format context #{window_index} is the session's CURRENT window — measured on tmux 3.7c: a session with windows 0-2 and window 1 selected lists 1, and after `select-window` to 2 lists 2.

func (Tmux) Activity

func (t Tmux) Activity(ctx context.Context) (map[string]int64, error)

Activity implements ActivityReader with one `tmux list-windows -a`: a session's time is the NEWEST of its own #{session_activity} and every one of its windows' #{window_activity}.

🔴 #{session_activity} ALONE IS NOT "LAST ACTIVE". Measured on tmux 3.7c (a private server, no client attached, six readings over 13 s): a pane printing output moved its WINDOW's #{window_activity} to the second it printed — at two different times, and for a background window that was not the session's current one — while #{session_activity} stayed at the session's creation time throughout; `send-keys` into a pane moved the window's time too, and again not the session's. session_activity follows an attached CLIENT's keys, so on its own it would rank a session an agent has been working in for an hour below one the operator glanced at. Both are read, because a client's key that draws nothing (switching windows) is activity too.

⚠ "Active" is therefore "its screen changed, or someone typed": a pane that redraws on a timer (a clock, `watch`) is always recently active.

func (Tmux) AnswerAsk

func (t Tmux) AnswerAsk(ctx context.Context, pane string, qs []askq.Question, choices []askdrive.Choice, prior *askq.Progress) (int, error)

AnswerAsk implements AskBackend: askdrive.DriveFrom on the pane.

🔴 ONE DRIVE PER PANE AT A TIME: a second answer for a pane being typed into is refused (ErrPaneBusy) before any key — two drives' keys would interleave in one picker. And a tmux found unable to paste keys raw (KeyPasteNone) is refused (ErrNoRawPaste) before any key.

func (Tmux) Attach

func (t Tmux) Attach(ctx context.Context, session string, readOnly bool, cols, rows uint16) (Terminal, error)

Attach runs `tmux attach-session` for session on a fresh pty.

func (Tmux) AttachArgs

func (t Tmux) AttachArgs(session string, readOnly bool) []string

AttachArgs is the tmux argv (after the binary) for attaching session.

  • `-u`: the browser terminal is UTF-8 whatever this host's locale is.
  • `-r` for a read-only attach: tmux ignores the client's keys, the last of the three read-only layers (see mirror.Hub.Attach). In tmux >= 3.2 it also sets the client's ignore-size flag, so a read-only viewer does not resize a window another client is using.
  • `-t =<session>`: `=` is an EXACT match. A bare name is a prefix match, so `main` would attach `main2` when `main` had ended.

The session is one argv element, never a shell word.

func (Tmux) AttachWindow

func (t Tmux) AttachWindow(ctx context.Context, session, window string, readOnly bool, cols, rows uint16) (Terminal, error)

AttachWindow implements WindowAttacher: a client showing window (a tmux window id) of session, in a viewer session of its own.

🔴 THE OPERATOR'S SESSION IS NEVER THE TARGET OF A select-window OR AN attach. The steps, each checked:

  1. `list-windows -t =<session>`: the window must be in that session NOW. A window id is server-wide, so without this a request could be shown a window of another session — or of a session that has ended.
  2. `new-session -d -s muster-view-<rand> ”` and, in the SAME invocation, `link-window -k -s <window id> -t =muster-view-<rand>:{start}`: a new session whose one placeholder window is replaced by a LINK to the target window. The viewer session then holds exactly that window, as its current window; the operator's session is not named by either command. The empty command makes the placeholder a pane with NO process in it: nothing is forked on the host — not the operator's shell, not a sleep. (tmux removes such a pane by itself a moment later, measured on 3.7c; the two commands are one invocation so the link lands first.) ⚠ What the tmuxit suite can SEE is only that the server's default command never RUNS; it cannot tell the empty command from a default command forked and removed in the same instant (a marker-writing default command wrote nothing either way). The empty command is the stated intent, not a tested guard. A window that has closed since step 1 fails the link ("can't find window"); the viewer session is then removed and the attach refused.
  3. `attach-session -f <ViewClientFlags> -t =muster-view-<rand>`, then `set-option destroy-unattached on` for it: tmux itself removes the viewer session the moment its client is gone — also when muster-mirror is killed outright — and Close removes it explicitly as well.

🔴 WHY A LINK AND NOT A SESSION GROUP (`new-session -t <session>`), which also gives a viewer its own current window. Measured on tmux 3.7c, a session of 5 windows: joining the group fires the server's `window-linked` hook 6 times and needs a select-window (the `after-select-window` hook) — and an operator whose tmux.conf binds those hooks to per-window bookkeeping has it run, in the VIEWER session's context, on every open. The group also stays on the operator's session (#{session_group}) after the viewer is gone. A link fires `window-linked` twice whatever the session's size, selects nothing, and leaves the operator's session exactly as it was.

⚠ What still fires, as for any client: `session-created`, `client-attached` and `client-session-changed`, with the viewer session's name (mirror.ViewSessionPrefix) as the hook's session.

func (Tmux) CancelAsk

func (t Tmux) CancelAsk(ctx context.Context, pane string) (bool, error)

CancelAsk implements AskCanceller: askdrive.Cancel on the pane — the same one-drive-per-pane lock as an answer (ErrPaneBusy), and the same need for a raw paste (Tmux.KeyPaste; ErrNoRawPaste: a sanitizing paste would turn the Escape into nothing).

func (Tmux) CancelCopyMode

func (t Tmux) CancelCopyMode(ctx context.Context, pane string) error

CancelCopyMode implements ScrollBackend.

func (Tmux) CapturePane added in v0.198.0

func (t Tmux) CapturePane(ctx context.Context, pane string) (string, error)

CapturePane implements PaneReader: the pane's screen, wrapped lines joined (the screen askdrive reads).

func (Tmux) ClaudePanes

func (t Tmux) ClaudePanes(ctx context.Context, sessions []string) map[string]ClaudePane

ClaudePanes implements ClaudeBackend.

func (Tmux) ClaudeScreen

func (t Tmux) ClaudeScreen(ctx context.Context, paneID string) (string, error)

ClaudeScreen implements ClaudeScreenBackend: capture-pane -p -e -J by the pane's id. 🔴 -e IS LOAD-BEARING: without the styles Claude Code's dim ghost suggestion (a suggested next prompt drawn in an empty box) reads as text, and every paste into that pane is refused as claude-box.

func (Tmux) CleanViewSessions

func (t Tmux) CleanViewSessions(ctx context.Context) ([]string, error)

CleanViewSessions ends every viewer session with NO client attached: what a muster-mirror that was killed between creating one and attaching to it left behind (or a session-restore plugin brought back). It returns the names it ended. A viewer session in use — another muster-mirror's, on the same server — has a client and is left alone.

func (Tmux) KeyPaste added in v0.106.0

func (t Tmux) KeyPaste(ctx context.Context) KeyPaste

KeyPaste reports how this tmux can paste a picker's keys raw. Probed first: pasting a buffer that does not exist is refused as "no buffer" by a tmux that knows -S, and as "unknown flag -S" by one that does not — nothing is pasted either way. The SERVER parses the flag (the client parses a command only to learn whether it starts a server, and discards a parse error — tmux 3.4 client.c; measured: a 3.7c client against a 3.4 server gets "unknown flag -S" back from the server), so "unknown flag" means the server is older than 3.7. Its #{version} is read to confirm that: before 3.7 it is KeyPastePlain; 3.7 or later, a contradiction, KeyPasteNone; unreadable or failed (a timeout), KeyPasteUnknown. With no tmux server running the probe cannot tell ("no server running"), so `tmux -V` is read instead — the server that binary starts is that version; a version it cannot read, or any other failure, is KeyPasteUnknown, NOT "old": the caller asks again later.

func (Tmux) KillWindow added in v0.183.0

func (t Tmux) KillWindow(ctx context.Context, window string) error

KillWindow implements WindowCloser: tmux kill-window on the window id (unique on its server).

func (Tmux) List

func (t Tmux) List(ctx context.Context) ([]string, error)

List is the server's session names, sorted. A host with no tmux server running has no sessions — that is not an error.

func (Tmux) NewResumeWindow

func (t Tmux) NewResumeWindow(ctx context.Context, session, name, dir string, argv []string) (string, error)

NewResumeWindow implements ResumeBackend: `new-window -d` in session, or `new-session -d` when the session does not exist yet, each with -c dir, -n name and, as tmux's own command arguments, argv run through the user's LOGIN SHELL (loginArgv). -P -F answers the new window's id.

🔴 WHY NO PATH, AND THE LOGIN SHELL. tmux starts a window with the server's global environment, except PATH, which it takes from the CLIENT that asked whenever that client has one — over the server's own and even over `-e PATH=…` (measured with tmux 3.7c, for new-session and for new-window into an existing session alike). That client is this process: a service whose PATH typically holds tmux alone. A resumed Claude Code session started straight from argv got that PATH, so its hooks and every shell tool it ran failed "command not found". So:

  • the tmux command that starts the window runs with NO PATH (resumeEnv; the binary is already resolved), and the window gets the server's own global PATH — the operator's server, started from a login session;
  • and argv runs under tmux's default-shell as a LOGIN shell (loginArgv), which reads the user's profile: what builds the environment when the server has no PATH of its own (this resume started it, from this process's PATH-less environment). Where the profile skips work it already did (NixOS's set-environment guard, exported in the operator's server), the server's PATH above is what it keeps.

func (Tmux) OpenCodeSource

func (t Tmux) OpenCodeSource() *OpenCodeSource

OpenCodeSource implements OpenCodeSourcer; nil when t resolves none.

func (Tmux) PaneGuard added in v0.156.0

func (t Tmux) PaneGuard(ctx context.Context, paneID string) (GuardProc, bool, error)

PaneGuard implements PaneGuardBackend: the pane's root process (#{pane_pid}, read now by the pane's id) and a walk of its tree.

func (Tmux) Paste

func (t Tmux) Paste(ctx context.Context, p ClaudePane, text string) error

Paste implements ClaudeBackend: PastePane into the Claude pane's id.

func (Tmux) PasteChecked

func (t Tmux) PasteChecked(ctx context.Context, p ClaudePane, text string, before, beforeEnter func(context.Context) error) error

PasteChecked implements ClaudeCheckedPaster: PastePane's paste and Enter, with check run before each.

func (Tmux) PastePane

func (t Tmux) PastePane(ctx context.Context, paneID, text string) error

PastePane implements PaneBackend — and is the ONE paste this host has (Paste calls it) — the way ccd hands a provisioned agent its prompt: `load-buffer` from STDIN into a uniquely named buffer (never argv — visible in the process table and parsed by tmux), `paste-buffer -p -d` into the PANE id (buffer deleted after), then Enter — itself a pasted newline, see the end of the body.

`-p` brackets the paste ONLY for a program that asked for bracketed paste (zsh and bash 5.1+ do by default, as does Claude Code): there the whole text, newlines included, arrives as one paste and the Enter submits it once. A program that did not ask gets the bytes as typed, so every newline in the text is an Enter of its own (measured: tmux_integration_test.go).

The text must already be mirror.SanitizePaste'd: a control character inside a bracketed paste can end it, and what follows is then TYPED.

func (Tmux) ReportsStatus

func (Tmux) ReportsStatus() bool

ReportsStatus implements StatusReporter: ClaudeLocator reads the status from the sessions file the CLI writes for its peers.

func (Tmux) ScrollPane

func (t Tmux) ScrollPane(ctx context.Context, pane string, lines int) (entered, inMode bool, err error)

ScrollPane implements ScrollBackend.

The pane is a PANE ID (%<n>), never a session or window name, so the scroll reaches exactly the pane muster resolved and needs no client — it works with only muster's read-only viewer attached (measured: tmux_integration_test.go).

func (Tmux) ServerSocket

func (t Tmux) ServerSocket(ctx context.Context) (string, error)

ServerSocket is the socket path of the server this backend lists.

func (Tmux) WindowCwd

func (t Tmux) WindowCwd(ctx context.Context, session, window string) (string, error)

WindowCwd implements CwdResolver: the window's Claude Code process's cwd when its pane runs one (where Claude Code itself looks for the project's .claude), else the pane's root process's.

func (Tmux) WindowPane

func (t Tmux) WindowPane(ctx context.Context, session, window string) (string, error)

WindowPane implements WindowPaner with one `tmux list-windows` of that ONE session (#{pane_id} in a window's format is its active pane).

🔴 THE SESSION IS LISTED, NOT TARGETED AS `session:@id`. tmux resolves `=other:@12` to other's CURRENT window when @12 is not in it, and an unknown `@999` to an empty answer with exit status 0 (both measured, 3.7c) — a display-message on such a target would name the wrong pane, or none, without an error. Listing the session's own windows and matching the id exactly is how this knows the window is still the session's (as AttachWindow does).

func (Tmux) WindowSize

func (t Tmux) WindowSize(ctx context.Context, session string) (termsize.Size, error)

WindowSize is the CLIENT size that shows session's current window exactly (termsize.ParseTmuxWindow: the window plus its status line).

func (Tmux) WindowSizeOf

func (t Tmux) WindowSizeOf(ctx context.Context, session, window string) (termsize.Size, error)

WindowSizeOf is the CLIENT size that shows window of session exactly, like WindowSize.

⚠ tmux ANSWERS FOR ANOTHER WINDOW RATHER THAN FAILING when the id is not in the session (measured on 3.7c: `display-message -t =other:@1` printed other's current window), so the answer carries the window id and one that is not the window asked for is an error.

func (Tmux) Windows

func (t Tmux) Windows(ctx context.Context) ([]WindowInfo, error)

Windows implements WindowLister with ONE `tmux list-panes -a`, however many windows there are: the listing, each session's current window, each window's active pane (its input target and the root of the Claude Code lookup), its activity and its command all come from that read.

type ViewCleaner

type ViewCleaner interface {
	CleanViewSessions(ctx context.Context) ([]string, error)
}

ViewCleaner is a Backend that may have left viewer sessions behind.

func ViewCleanerOf

func ViewCleanerOf(b Backend) (ViewCleaner, bool)

ViewCleanerOf is b's ViewCleaner, looking through wrappers (see ClaudeOf).

type WindowAttacher

type WindowAttacher interface {
	AttachWindow(ctx context.Context, session, window string, readOnly bool, cols, rows uint16) (Terminal, error)
}

WindowAttacher is a Backend that can attach a client showing ONE window of a session without changing that session's current window for anyone else.

func WindowAttacherOf

func WindowAttacherOf(b Backend) (WindowAttacher, bool)

WindowAttacherOf is b's WindowAttacher. The OUTERMOST one: a wrapper that sizes a client (NoShrink) implements it over what it wraps, and capabilityOf asks the wrapper before it unwraps.

type WindowCloser added in v0.183.0

type WindowCloser interface {
	KillWindow(ctx context.Context, window string) error
}

WindowCloser is a Backend that can close one window by its id. Tmux is one.

type WindowIndexer

type WindowIndexer interface {
	// ActiveWindows is session name → its active window's index ("1").
	ActiveWindows(ctx context.Context) (map[string]string, error)
}

WindowIndexer is a Backend that can say which window each session has ACTIVE. Tmux is one; a backend that is not labels a session by its codename alone.

func WindowIndexerOf

func WindowIndexerOf(b Backend) (WindowIndexer, bool)

WindowIndexerOf is b's WindowIndexer, looking through wrappers (see ClaudeOf).

type WindowInfo

type WindowInfo struct {
	// Session and ID address the window: the tmux session name and window id
	// ("@12"). Index is its index in the session now (display only).
	Session string
	ID      string
	Index   int
	// Active: the session's current window.
	Active bool
	// Pane is the window's active pane id ("%7"): the only input target.
	Pane string
	// PanePID is that pane's root process.
	PanePID int
	// TTY is that pane's terminal device (#{pane_tty}, "/dev/pts/3"), "" when
	// tmux reported none a device path.
	TTY string
	// Activity is the Unix time the window was last active: its own
	// #{window_activity} and, for the session's ACTIVE window, the session's
	// #{session_activity} when that is newer (a client's key that draws
	// nothing — switching to the window — is activity too; see Tmux.Activity).
	Activity int64
	// Command is what runs in the active pane (#{pane_current_command}).
	Command string
	// Claude is the Claude Code session in the active pane; nil for none.
	Claude *ClaudePane
	// Agent is the active pane's agent session of ANOTHER runtime (opencode),
	// for a window whose pane Claude Code did not claim; nil for none, and
	// always nil when Claude is set (attachAgents).
	Agent *AgentPane
	// Color is the window's tmux identity colour, lowercase "#rrggbb" — from
	// the user option ColorOption (@muster-color), which tmux
	// resolves window, then session, then global — "" when it is unset or not a
	// colour (windowColor). docs/design/agent-cards.md (b).
	Color string
	// Dispatch is the host dispatch the window was started for (its
	// @muster-dispatch, mirror.DispatchOption), 0 for none.
	Dispatch int64
	// Cwd is the working directory of the window's active pane (its
	// /proc/<pid>/cwd link, " (deleted)" and all): of its Claude Code process
	// when it runs one, else of the pane's root process (the shell), "" when it
	// could not be read. What the window's repo name is found from (repo.go).
	Cwd string
	// Others are the Claude Code sessions in the window's OTHER panes (a
	// split), by pane: what lets a session in a non-active pane be resolved
	// from its pane (MCPProxy) and recognised by muster (mirror.Window's
	// OtherClaude). Nothing renders them.
	Others []ClaudePane

	// NoView is why the window has no rendered view when its active pane runs
	// Claude Code but no transcript was found for it (one of the NoView*
	// lines, ClaudeLocator.whyNoView); "" otherwise, and always "" when
	// Claude or Agent is set. Sent as mirror.Window.AgentNote.
	NoView string
	// contains filtered or unexported fields
}

WindowInfo is one tmux window as a backend reads it.

func FindWindow

func FindWindow(windows []WindowInfo, session, window string) (WindowInfo, bool)

FindWindow is the entry of windows for (session, window id).

func (WindowInfo) PaneIDs added in v0.186.0

func (w WindowInfo) PaneIDs() []string

PaneIDs is every pane id ("%7") of the window: its active pane's first, then the others the listing read.

func (WindowInfo) PanePIDs added in v0.185.0

func (w WindowInfo) PanePIDs() []int

PanePIDs is the root process (#{pane_pid}) of every pane of the window: its active pane's first, then the others the listing read.

type WindowLister

type WindowLister interface {
	// Windows is every window of every session, in (session, index) order.
	// Viewer sessions (mirror.IsViewSession) are not in it. A host with no tmux
	// server has none — that is not an error.
	Windows(ctx context.Context) ([]WindowInfo, error)
}

WindowLister is a Backend that can list every window of every session, from ONE read. Tmux is one; a backend that is not is registered per session, as before.

func WindowListerOf

func WindowListerOf(b Backend) (WindowLister, bool)

WindowListerOf is b's WindowLister, looking through wrappers (see ClaudeOf).

type WindowOfSizer

type WindowOfSizer interface {
	WindowSizeOf(ctx context.Context, session, window string) (termsize.Size, error)
}

WindowOfSizer is a Backend that can say how big one window is right now.

type WindowPaner

type WindowPaner interface {
	// WindowPane is the active pane id of window (a tmux window id, "@12") of
	// session, read now; an error when the session is gone or the window is no
	// longer in it.
	WindowPane(ctx context.Context, session, window string) (string, error)
}

WindowPaner is a Backend that can name one window's active pane with ONE cheap read — no Claude Code lookup, unlike WindowLister.Windows, whose LocatePanes scans /proc (measured on a host of 75 windows: 50–130 ms a call, for EVERY scroll). The tmux backend implements it.

func WindowPanerOf

func WindowPanerOf(b Backend) (WindowPaner, bool)

WindowPanerOf is b's WindowPaner, looking through wrappers like ClaudeOf.

type WindowSizer

type WindowSizer interface {
	WindowSize(ctx context.Context, session string) (termsize.Size, error)
}

WindowSizer is a Backend that can say how big a session's window is right now. Tmux is one; a backend that is not simply attaches at the size asked (and reports nothing), as before.

Jump to

Keyboard shortcuts

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