previewhost

package
v0.261.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 28 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 previewhost is muster-mirror's half of previews: serving a loopback web server an agent started on this host to its owner, through the preview gateway (docs/design/previews.md). This package holds what the host decides ON ITS OWN, whatever the gateway asks:

  • config.go: previews.json, the allowlist and caps, and why a bad one turns previews off (never fatal);
  • ports.go: which ports may be exposed, and the ports that never may (muster-mirror's own -mcp-listen, the opencode server it talks to);
  • procnet.go: this host's listening sockets, from /proc/net/tcp{,6}, with the uid that owns each (the foreign_listener check);
  • listeners.go: the listener reports, attributing an allowlisted listener to the tmux window whose pane runs it;

and how it serves the gateway (this part imports the tunnel transport, internal/preview/tunnel; the rest is the standard library and internal/preview/wire):

  • connect.go: the tunnel's CONNECT streams (the port alone, the checks above, then 127.0.0.1 and ::1);
  • offer.go and host.go: the offer stream (config, window listing and reports, each sent only on change; open and close requests; the re-announce on a gateway restart) and the state it is served from;
  • dial.go: the tunnel to the gateway, mesh endpoint first.

The process table it walks comes in as a function (ProcTable): muster-mirror passes mirrorhost's, the same seam the Claude Code locator reads, so this package does not link mirrorhost and mirrorhost may later link it.

Index

Constants

View Source
const (
	DefaultMaxOpen = 8
	MaxMaxOpen     = 32
)

Caps on previews.json's numbers. maxConns has no constant here: its cap and default are wire.MaxConns, the one source the gateway sizes each tunnel's HTTP/2 connection window from before the host announces its own maxConns, so a host may not ask for more.

View Source
const (
	DefaultDialBudget = 3 * time.Second
	DefaultMeshRetry  = 5 * time.Minute
)

Defaults of TunnelConfig.

View Source
const (
	ToolOpen  = "preview_open"
	ToolList  = "preview_list"
	ToolClose = "preview_close"
)

The tools' names.

View Source
const (
	CodePreviewsOff = "previews_off"
	CodeNotFound    = "not_found"
	// CodeMaxOpen: the gateway's (or this host's) open limit.
	CodeMaxOpen = "max_open"
	// CodeNotAnswering: this user listens on the port and the loopback dial
	// connected, but no HTTP answer came within ProbeWait (a server still
	// starting, or not HTTP). Not CodeNotListening: retrying can succeed.
	CodeNotAnswering = "not_answering"
	// CodeInvalidArguments: a tool's arguments do not validate — a tool
	// result the model reads and can correct (muster's own convention),
	// not a failed request.
	CodeInvalidArguments = "invalid_arguments"
	// CodeCancelled: the caller's own request ended (its client gave up or
	// disconnected) before the open finished — not the gateway's doing.
	CodeCancelled = "cancelled"
	// CodeGatewayError: the gateway refused with something that is not a
	// well-formed code (gatewayCode).
	CodeGatewayError = "gateway_error"
	// CodeNoWindow: the caller's pane — or, for opencode, the session its
	// call names — is in no window this host mirrors, so
	// the preview would belong to no one (not in the design's table: a
	// session outside a mirrored window has nothing to bind a preview to).
	CodeNoWindow = "no_window"
)

Tool error codes beyond the host's refusals (CodePortNotAllowed, …) and RequestOpen's (ErrGatewayNotConnected, ErrGatewayTimeout).

View Source
const (
	CodePortNotAllowed  = "port_not_allowed"
	CodeForeignListener = "foreign_listener"
	CodeNotListening    = "not_listening"
)

Refusal codes, as the CONNECT answer and the agent tools return them.

View Source
const FileName = "previews.json"

FileName is previews.json's name in muster-mirror's config directory.

View Source
const MaxOpenAge = 24 * time.Hour

MaxOpenAge bounds how long the host keeps an open alive across gateway restarts: the design's default preview TTL and its offline close (24 h). The host cannot read the gateway's PREVIEW_TTL, so this is its own bound — and it is also what ends opens across a long disconnect: an open recorded before a disconnect of more than a day is older than this on reconnect. It is measured in WALL time, so a host suspended for a day has had its opens for a day (UNVERIFIED by a test: no test can suspend the process).

View Source
const MaxProcessName = 15

MaxProcessName is the longest process name a report carries: the kernel's own comm length (TASK_COMM_LEN 16, less its NUL).

View Source
const MinPort = 1024

MinPort is the lowest port previews.json may list: a privileged port is a system service's, never an agent's dev server.

View Source
const OpenCodeSessionMeta = mirror.OpenCodeSessionMeta

OpenCodeSessionMeta is mirror.OpenCodeSessionMeta: the key opencode puts the calling session's id under in every tools/call's params._meta. Read (mirror.OpenCodeCallSession) and handed to Caller; whether it is believed is the caller resolver's decision.

View Source
const ProbeWait = 5 * time.Second

ProbeWait bounds preview_open's probe: a loopback dial and HEAD /, answered.

Variables

View Source
var (
	ErrGatewayNotConnected = errors.New("gateway_not_connected")
	ErrGatewayTimeout      = errors.New("gateway_timeout")
)

Errors of RequestOpen and RequestClose, by their tool error code.

Functions

func CheckListener

func CheckListener(l Listeners, port, uid int) error

CheckListener is the foreign_listener check, on a ReadListeners read: nil when port has at least one listener where a loopback dial reaches it (Socket.Local) and EVERY such listener is uid's; a *Refusal with CodeForeignListener when any is another user's — the dial could reach that one, so one is enough — and ALSO when the read had rows it could not parse (FAIL CLOSED: an unread row may be another user's listener on this port); CodeNotListening when there is none.

func DefaultFile

func DefaultFile() string

DefaultFile is where muster-mirror reads previews.json when -preview-file does not say: muster-mirror's directory under os.UserConfigDir() ($XDG_CONFIG_HOME, else ~/.config, on Linux), beside the MCP secret. "" when there is no user config directory.

func PortOfURL

func PortOfURL(raw string) (int, bool)

PortOfURL is the port a URL connects to: its explicit port, else its scheme's default (80 for http, 443 for https); false when it names neither.

func Supported

func Supported() error

Supported is nil on Linux: /proc/net/tcp{,6} and /proc/<pid>/fd are where the listener reports and the foreign_listener check read.

Types

type AlwaysRefused

type AlwaysRefused func() map[int]string

AlwaysRefused is the ports the host never exposes, whatever previews.json lists, each with why: muster-mirror's own MCP endpoint (it would hand a viewer muster's tools) and the opencode server it talks to (an opencode session's shell). A function, read at every check, because the opencode server's address comes from a token file that is re-read while the host runs.

type Config

type Config struct {
	// Ports is the allowlist. Never empty in a Config Parse returned.
	Ports PortSet
	// Offer: listener reports on (the default) or off.
	Offer bool
	// MaxOpen is how many previews may be open at once on this host.
	MaxOpen int
	// MaxConns is how many upstream connections (tunnel streams) at once.
	MaxConns int
}

Config is a loaded, valid previews.json.

func Load

func Load(path string) (Config, error)

Load reads and validates previews.json at path. The error is the reason previews are off, written for the log and the offer stream: a missing, unreadable, empty or invalid file. A caller disables previews on it; it is never a reason to stop.

func Parse

func Parse(b []byte) (Config, error)

Parse validates previews.json's bytes. Unknown fields are refused, and every key must be spelt exactly (see the exact-key pass below).

func (Config) Allows

func (c Config) Allows(port int, refused AlwaysRefused) error

Allows is the host's port check, before any listener is looked at: nil when port may be exposed, else a *Refusal with CodePortNotAllowed. The always-refused ports are checked FIRST, so listing one in previews.json changes nothing.

type Host added in v0.186.0

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

Host is the host end of previews: what the tunnel's handler (Handler) serves, and the state it serves from. It is safe for concurrent use; one Host outlives every tunnel it serves.

func NewHost added in v0.186.0

func NewHost(hc HostConfig) *Host

NewHost builds a Host from hc.

func (*Host) Handler added in v0.186.0

func (h *Host) Handler() http.Handler

Handler is the tunnel's handler: CONNECT (connect.go), GET wire.OfferPath, POST wire.OpenedPath and wire.ClosedPath. Anything else is 404.

func (*Host) Opens added in v0.186.0

func (h *Host) Opens() []Open

Opens is the previews the gateway has acknowledged open, sorted by id.

func (*Host) RequestClose added in v0.186.0

func (h *Host) RequestClose(ctx context.Context, req wire.Request) (wire.Answer, error)

RequestClose writes an agent's close of req.Preview and waits for the gateway's answer.

func (*Host) RequestOpen added in v0.186.0

func (h *Host) RequestOpen(ctx context.Context, req wire.Request) (wire.Answer, error)

RequestOpen writes an agent's open on the offer stream and waits for the gateway's answer (AnswerWait). req.ID is assigned here. The answer's Error is the gateway's tool error ("max_open", …); an acknowledged open is recorded (Opens).

func (*Host) Run added in v0.186.0

func (h *Host) Run(ctx context.Context, tc TunnelConfig)

Run serves previews until ctx ends: it polls previews.json and the listeners, and keeps a tunnel to the gateway up. It returns only when ctx ends; nothing it meets is fatal.

func (*Host) Summary added in v0.194.0

func (h *Host) Summary() map[string]WindowSummary

Summary is, per tmux window id, what the host has to preview there NOW — what muster-mirror reports to muster so the session views show their Preview button only while there is something to open (docs/previews.md). Windows with nothing are absent.

🔴 NIL WHILE NO GATEWAY TUNNEL SERVES AN OFFER STREAM: without one the session page can show nothing but "the host is offline", so there is nothing to offer from muster. The opens the host keeps across a dropped tunnel (to re-announce them) come back with the tunnel. And nil while previews are off (every open preview was closed and no listener is reported then anyway).

type HostConfig added in v0.186.0

type HostConfig struct {
	// Config is previews.json as loaded at start (Load); File is re-read every
	// Poll, and a change takes effect at once: previews on a port that left
	// the list close, and a new maxConns reconnects the tunnel (its HTTP/2
	// SETTINGS are fixed for the tunnel's life).
	Config Config
	File   string
	// Refused is the always-refused ports (muster-mirror's -mcp-listen and the
	// opencode server's), checked before the allowlist on every CONNECT.
	Refused AlwaysRefused
	// UID is this user's: the foreign_listener check and the reports.
	UID int
	// Proc is the proc root ("" = "/proc"), Procs the process table the
	// report walk reads.
	Proc  string
	Procs ProcTable
	// Poll is how often previews.json is re-read, the windows are listed and
	// the listeners are scanned (default 5 s, the mirror's own refresh).
	Poll time.Duration
	// Windows lists the mirrored tmux windows, every Poll: previews' ONLY
	// window source, so they work whether or not muster is connected. nil =
	// no listing (no window line is sent, and no listener is attributed).
	Windows func(context.Context) ([]Window, error)
	// AnswerWait bounds how long an open or close request waits for the
	// gateway's answer (default 5 s).
	AnswerWait time.Duration
	Logger     *log.Logger
	// Now is the clock (nil = time.Now).
	Now func() time.Time
	// contains filtered or unexported fields
}

HostConfig configures a Host.

type Listeners

type Listeners struct {
	Sockets []Socket
	Bad     int
}

Listeners is one read of /proc/net/tcp{,6}: its LISTEN sockets, and how many rows could not be parsed. A bad row could be any socket — another user's listener included — so a check that must not fail open (CheckListener) refuses while Bad > 0; the offer scan, which only ever leaves things out, reads Sockets alone.

func ReadListeners

func ReadListeners(root string) (Listeners, error)

ReadListeners reads <root>/net/tcp and <root>/net/tcp6 and returns their LISTEN sockets and bad-row count. root is "/proc" on this host or a test's fixture tree. A missing tcp6 (a kernel without IPv6) is not an error; a missing tcp is, and so is a file with bad rows and no socket read.

type MCPServer added in v0.186.0

type MCPServer struct {
	// Host is this host's previews: its allowlist and checks, its record of
	// acknowledged opens, and its offer stream to the gateway.
	Host *Host
	// Caller is the tmux window ("@12") the request's caller is in, from a
	// fresh listing (mirrorhost.MCPProxy.CallerWindow): by its pane, or —
	// for opencode, whose headers cannot name one — by agentSession, the
	// session the tools/call itself names (OpenCodeSessionMeta; "" none). It
	// needs no Claude Code session in the pane: a preview belongs to the
	// window.
	Caller func(r *http.Request, agentSession string) (string, error)
	// Version is what `initialize` names as the server's version; "" = "dev".
	Version string
	// contains filtered or unexported fields
}

MCPServer is /preview-mcp's server. Its ServeHTTP is called past muster-mirror's guard (mirrorhost.MCPProxy.SetPreview).

func (*MCPServer) ServeHTTP added in v0.186.0

func (s *MCPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP answers one JSON-RPC request: `initialize` (serverInfo "muster-preview", the tools capability, the protocol version negotiated as muster's own server does, and serverInstructions), `ping`, notifications (202), `tools/list` (the three tools, exactly), `tools/call` for them; anything else "method not found".

type Open added in v0.186.0

type Open struct {
	Preview string
	Window  string
	Port    int
	Label   string
	Path    string
	// Opened is when the host first recorded it. A re-announce to a
	// restarted gateway keeps it (so a restart does not renew an open), and
	// an open older than MaxOpenAge is dropped instead of re-announced.
	Opened time.Time
}

Open is one preview the gateway has acknowledged open on this host: by an agent's request (Label and Path as asked) or by the owner clicking an offer (the gateway tells the host unsolicited, so preview_list includes it).

type PortRange

type PortRange struct{ Lo, Hi int }

PortRange is an inclusive range of ports; Lo == Hi for one port.

func (PortRange) String

func (r PortRange) String() string

type PortSet

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

PortSet is previews.json's allowlist: ranges, sorted by Lo.

func ParsePorts

func ParsePorts(entries []string) (PortSet, error)

ParsePorts reads previews.json's "ports": each entry one port ("3000") or an inclusive range ("8000-8099"), digits only, within MinPort-65535. Any entry that is not one is an error naming it: one bad entry disables previews, it is never skipped (a skipped entry would leave an allowlist smaller than the one written, silently).

func (PortSet) Contains

func (s PortSet) Contains(port int) bool

Contains reports whether port is on the allowlist.

func (PortSet) Ranges

func (s PortSet) Ranges() []PortRange

Ranges is the allowlist, sorted (a copy).

func (PortSet) String

func (s PortSet) String() string

String is the allowlist as previews.json would write it, comma-separated.

type Proc

type Proc struct {
	PPID int
	Comm string
}

Proc is one process as the attribution walk needs it.

type ProcTable

type ProcTable func() (map[int]Proc, error)

ProcTable reads this host's process table: every process's parent and name. muster-mirror passes mirrorhost's (mirrorhost.ProcTable), the source the Claude Code locator walks.

type Refusal

type Refusal struct {
	Code string
	Why  string
}

Refusal is why the host will not expose a port. Code is the wire's ("port_not_allowed", "foreign_listener", "not_listening"); Why is for a log.

func (*Refusal) Error

func (r *Refusal) Error() string

type Report

type Report struct {
	Port      int       `json:"port"`
	Process   string    `json:"process"` // the listening process's name, at most MaxProcessName bytes
	Window    string    `json:"window"`  // the tmux window id ("@12")
	FirstSeen time.Time `json:"first_seen"`
}

Report is one listener offered to the owner: an allowlisted port this user listens on from a process in a mirrored tmux window. These four fields are ALL it carries (TestAReportCarriesExactlyItsFourKeys): never the argv, working directory, environment or pid.

type Scanner

type Scanner struct {
	// Proc is the proc root for net/tcp{,6} and <pid>/fd ("" = "/proc").
	Proc string
	// UID is this user's: only its listeners are reported.
	UID int
	// Procs reads the process table (required).
	Procs ProcTable
	// Now is the clock (nil = time.Now).
	Now func() time.Time
	// contains filtered or unexported fields
}

Scanner finds the listener reports. Each Scan is one poll; the scanner keeps first_seen across polls. Safe for concurrent use.

func (*Scanner) Scan

func (s *Scanner) Scan(c Config, refused AlwaysRefused, panes map[int]string) ([]Report, error)

Scan is one poll. panes maps each mirrored pane's root process (its #{pane_pid}) to its tmux window id. A listener is reported when its port is allowed (Config.Allows, so never an always-refused one), it listens where a loopback dial reaches it, it is this user's, and its process is a pane's root or descends from one; a listener in no pane has no session to show it in and is not reported. Sorted by window, then port. With offers off (Config.Offer false) it reads nothing and reports nothing.

type Socket

type Socket struct {
	Addr  netip.Addr // the bound address (an IPv4-mapped IPv6 address is unmapped)
	Port  int
	UID   int    // the socket's owner
	Inode uint64 // what /proc/<pid>/fd/* links to, as socket:[<inode>]
}

Socket is one listening TCP socket from /proc/net/tcp or tcp6.

func ParseProcNet

func ParseProcNet(b []byte, v6 bool) (socks []Socket, bad int)

ParseProcNet reads a /proc/net/tcp (v6 false) or /proc/net/tcp6 (v6 true) file and returns its LISTEN sockets. The header and any line that is not a socket row are skipped; bad counts them, so a caller (and a test) can tell a file in an unknown shape from one with no listeners.

A row is

sl local_address rem_address st tx:rx tr:when retrnsmt uid timeout inode …

with the local address as hex: the IPv4 address as one 32-bit word, IPv6 as four, each written in the kernel's (this host's) byte order, then ':' and the port in network order. Hence binary.NativeEndian: the file is always read on the host that wrote it.

func (Socket) Local

func (s Socket) Local() bool

Local reports whether the socket is bound where a loopback dial reaches it: a loopback address (127.0.0.0/8, ::1) or the wildcard (0.0.0.0, ::).

type TunnelConfig added in v0.186.0

type TunnelConfig struct {
	// URLs is -preview-urls, in dial order (the mesh endpoint first).
	URLs []string
	// Token is the host's mpt_ token; HostName the name it was minted for.
	Token    string
	HostName string
	// DialBudget bounds each endpoint's TCP connect + upgrade + version
	// answer (default DefaultDialBudget). MeshRetry is how often a host on a
	// later endpoint re-tries the earlier ones (default DefaultMeshRetry).
	DialBudget time.Duration
	MeshRetry  time.Duration
	// PingInterval is the tunnel's WebSocket ping (0 = wire.PingInterval).
	PingInterval time.Duration
	// contains filtered or unexported fields
}

TunnelConfig is the host's tunnel: where and as whom it dials.

type Window added in v0.186.0

type Window struct {
	ID       string
	PanePIDs []int
}

Window is one mirrored tmux window as previews need it: its id ("@12") and the root process of each of its panes (the listener walk's targets).

type WindowSummary added in v0.194.0

type WindowSummary struct {
	// Offered is the window's listener reports with no open preview on their
	// port: the offers the gateway's session page lists (it lists an open
	// port as its preview, not again as an offer).
	Offered int
	// Open is the window's open previews.
	Open int
}

WindowSummary is what one window has to preview now (Summary).

Jump to

Keyboard shortcuts

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