libtmux-go

mcp
Security Audit
Warn
Health Warn
  • License — License: MIT
  • Description — Repository has a description
  • Active repo — Last push 0 days ago
  • Low visibility — Only 5 GitHub stars
Code Pass
  • Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Pass
  • Permissions — No dangerous permissions requested

No AI report is available for this listing yet.

SUMMARY

libtmux for Go: a typed tmux client library. No runtime dependencies, plus an MCP server for agents.

README.md
libtmux for Go

libtmux for Go

Drive tmux from Go: sessions, windows and
panes as typed values, options and hooks
as typed accessors, and errors classified by what tmux refused.

tests
Go Reference
libtmux.org
license
workspace reference
mcp reference

Run a command, find and
filter what tmux holds, type and wait
for an answer, and hear changes as they happen.

It suits tools that drive a terminal program, test suites that need a real
tmux, and agents that share a terminal.

Add it to your module:

$ go get github.com/libtmux/libtmux-go/tmux@latest

Releases are numbered 0.1.N. The API is not settled: any release may change
or remove exported identifiers, and the changelog marks each
break. Pin an exact version to avoid one.

It needs Go 1.26 or newer and tmux 3.3a or newer, on a Unix host. Against an
older tmux, a call returns tmux.ErrVersionTooLow
instead of sending its command.

tmux release candidates are not supported.
The library contracts say what each feature needs.

A tmux server for AI agents and a tmuxp-style workspace builder ship beside the
library, under Packages.

Contents — Quick start ·
Find things ·
Type and wait ·
Watch tmux ·
Choosing a path ·
Testing · Packages ·
Leaves out · Support ·
Documentation

Quick start

Run a command in tmux and print what its terminal showed. This is the whole
program:

// Command quickstart runs a command in tmux and prints what it showed.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/libtmux/libtmux-go/tmux"
)

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) (err error) {
	directory, err := os.MkdirTemp("", "libtmux-quickstart-")
	if err != nil {
		return fmt.Errorf("create socket directory: %w", err)
	}
	defer func() { err = errors.Join(err, os.RemoveAll(directory)) }()

	server, err := tmux.NewServer(tmux.ServerOptions{
		SocketPath: filepath.Join(directory, "tmux.sock"),
		ConfigFile: os.DevNull,
	})
	if err != nil {
		return fmt.Errorf("configure tmux: %w", err)
	}
	// Cleanup runs even when ctx is the reason the program is leaving.
	defer func() {
		if cleanup := server.Kill(context.WithoutCancel(ctx)); !errors.Is(cleanup, tmux.ErrNoServer) {
			err = errors.Join(err, cleanup)
		}
	}()

	session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "demo"})
	if err != nil {
		return fmt.Errorf("create session: %w", err)
	}

	// The command runs in a window of its own, with a terminal.
	result, err := session.Run(ctx, "echo hello from tmux", tmux.RunOptions{})
	if err != nil {
		return fmt.Errorf("run command: %w", err)
	}
	for _, line := range result.Lines {
		fmt.Println(line)
	}
	fmt.Println("exit status:", result.Status)
	return nil
}

It prints:

hello from tmux
exit status: 0

To run it, save it as main.go in an empty directory, with tmux 3.3a or newer
on PATH:

$ go mod init demo && \
    go get github.com/libtmux/libtmux-go/tmux@latest && \
    go run .

The program puts its socket in a new temporary directory, and kills its server
and removes the directory on the way out.

With no socket in ServerOptions, a server uses
LIBTMUX_SOCKET_PATH, else LIBTMUX_SOCKET; with neither set it reaches the
server your own tmux command does.

Session.Run is os/exec for a program that needs a
terminal. The command runs in a window of its own with a tty, and you get back
its exit status and the screen tmux rendered.

A nonzero exit status arrives in the result.
examples/run-to-completion shows one, on a tmux
server of its own.

Find sessions, windows, and panes

Server.Sessions: what tmux has now

One call asks tmux for every session. Server.Windows
and Server.Panes are its siblings. This program starts
a server of its own, lists it, filters it, and kills it:

// Command filter-query demonstrates snapshot predicates and live tmux filters.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/libtmux/libtmux-go/tmux"
	"github.com/libtmux/libtmux-go/tmuxq"
)

func main() {
	if err := start(); err != nil {
		log.Fatal(err)
	}
}

// start owns cleanup because log.Fatal skips deferred calls in main.
func start() error {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Choose an unused socket name: cleanup kills the server selected here.
	// The empty config keeps personal settings out of a new server.
	server, err := tmux.NewServer(tmux.ServerOptions{
		SocketName: "libtmux-filter-query",
		ConfigFile: os.DevNull,
	})
	if err != nil {
		return fmt.Errorf("configure tmux server: %w", err)
	}
	defer func() { _ = server.Kill(context.WithoutCancel(ctx)) }()
	return run(ctx, server)
}

// run accepts injected server state so tests can isolate the example.
func run(ctx context.Context, server tmux.Server) (err error) {
	session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-filter"})
	if err != nil {
		return err
	}
	defer func() {
		cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
		defer cleanupCancel()
		err = errors.Join(err, session.Kill(cleanupCtx))
	}()

	if err := list(ctx, server); err != nil {
		return err
	}

	snapshot, err := server.Snapshot(ctx)
	if err != nil {
		return err
	}
	active, err := tmuxq.Matching(snapshot.Panes(), tmux.PaneActiveIs(true))
	if err != nil {
		return err
	}
	fmt.Println("active panes:", len(active))

	filter := tmux.PaneFilter{
		Active:  new(true),
		Session: &tmux.SessionFilter{Name: new("libtmux-filter")},
	}
	panes, err := tmuxq.Matching(snapshot.Panes(), filter)
	if err != nil {
		return err
	}
	fmt.Println("typed panes:", len(panes))

	live := tmux.TmuxFilter("#{==:#{session_name},libtmux-filter}")
	sessions, err := server.SearchSessions(ctx, &live)
	if err != nil {
		return err
	}
	fmt.Println("live matches:", len(sessions))
	return nil
}

// list prints what the server holds now.
func list(ctx context.Context, server tmux.Server) error {
	sessions, err := server.Sessions(ctx)
	if err != nil {
		return fmt.Errorf("list sessions: %w", err)
	}
	for _, session := range sessions {
		name, _ := session.Name()
		fmt.Println("session:", name)
	}
	return nil
}

Save it as main.go and run it as the quick start does, or run
examples/filter-query from a clone. It prints:

session: libtmux-filter
active panes: 1
typed panes: 1
live matches: 1

The blocks below are fragments of it: each is the body of a function that
returns an error, with the values its first line names already in hand.

What comes back is a record: the Session you hold is what
tmux said when you asked, and it stays as it was when tmux changes.

With no tmux server running, a listing returns an error matching
ErrNoServer instead of an empty list, so "nothing there"
and "nobody to ask" stay different answers.

tmuxq.Matching: several answers from one read

Collect a snapshot with Server.Snapshot, then filter
its records in Go; it is not an atomic view of one instant.
Matching takes any filter the tmux package declares:

// Given: ctx context.Context; server tmux.Server
snapshot, err := server.Snapshot(ctx)
if err != nil {
	return err
}
active, err := tmuxq.Matching(snapshot.Panes(), tmux.PaneActiveIs(true))
if err != nil {
	return err
}
fmt.Println("active panes:", len(active))

That session has one window with one pane in it, which is the active one, so
the example goes on to print active panes: 1.

Server.SearchSessions: let tmux filter

tmux filters the listing, so only the matches come back; the call also adds
the identity probes that detect a replaced daemon:

// Given: ctx context.Context; server tmux.Server
live := tmux.TmuxFilter("#{==:#{session_name},libtmux-filter}")
sessions, err := server.SearchSessions(ctx, &live)
if err != nil {
	return err
}
fmt.Println("live matches:", len(sessions))

One session has that name, so this prints live matches: 1.

The filter is a tmux format, written the way the FORMATS section of the tmux
manual describes, and tmux evaluates it while it lists. tmuxq/ has
the filters that run in Go and the helpers that apply them.

Session.Refresh: read a held record again

Unlike Python libtmux's in-place .refresh(), Refresh asks tmux again and
returns a replacement; the record you called it on stays as it was.
Window.Refresh and Pane.Refresh work alike:

// Given: ctx context.Context; session tmux.Session
// session was renamed above, so it still says "old". Refresh asks tmux
// again and returns a replacement; session itself does not change.
fresh, err := session.Refresh(ctx)
if err != nil {
	return fmt.Errorf("refresh session: %w", err)
}
name, _ := fresh.Name()
fmt.Println("refreshed record:", name)

examples/object-model renames a session first, so
the held record still has the old name when Refresh returns the new one:

It prints held record: old, then returned record: new, then
refreshed record: new.

Type into a pane and wait

Pane.WaitForText: wait for text on every release

Pane.WaitForText polls the visible screen until it holds the text, on every
supported tmux. A pane or server that ends first returns a
PaneEndedError; a deadline returns ctx.Err().

A pane is an io.Writer through Pane.Writer, and a
newline is the Enter key. Type, then wait for text the command prints:

package tmux_test

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/libtmux/libtmux-go/tmux"
)

// Type a command into a shell and wait for what it prints. The wait polls the
// visible screen on every supported tmux release, and the typed line is
// already on that screen, so the text names the answer and not the command.
func ExamplePane_WaitForText() {
	run := func() (runErr error) {
		directory, err := os.MkdirTemp("", "libtmux-go-api-")
		if err != nil {
			return fmt.Errorf("create socket directory: %w", err)
		}
		server, err := tmux.NewServer(tmux.ServerOptions{
			SocketPath: filepath.Join(directory, "tmux.sock"),
			ConfigFile: "/dev/null",
		})
		if err != nil {
			return errors.Join(err, os.RemoveAll(directory))
		}
		defer func() {
			cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) {
				runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err))
				return
			}
			runErr = errors.Join(runErr, os.RemoveAll(directory))
		}()
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		session, err := server.NewSession(ctx, tmux.NewSessionRequest{
			Name: "work", Command: "sh", Width: 100, Height: 30,
		})
		if err != nil {
			return fmt.Errorf("create session: %w", err)
		}
		pane, err := session.ResolveActivePane(ctx)
		if err != nil {
			return fmt.Errorf("resolve pane: %w", err)
		}

		// A pane is an io.Writer, and a newline is the Enter key.
		command := `echo "6 x 7 = $((6 * 7))"`
		if _, err := fmt.Fprintln(pane.Writer(ctx), command); err != nil {
			return fmt.Errorf("type command: %w", err)
		}
		// The screen already holds the typed line, which says "$((6 * 7))"
		// and never "42", so the answer is what the wait names.
		if _, err := pane.WaitForText(ctx, tmux.WaitForTextRequest{
			Text: "6 x 7 = 42",
		}); err != nil {
			return fmt.Errorf("wait for answer: %w", err)
		}
		fmt.Println("the pane answered 6 x 7 = 42")
		return nil
	}
	if err := run(); err != nil {
		panic(err)
	}
	// Output:
	// the pane answered 6 x 7 = 42
}

Save it as example_test.go and run it as a test:

$ go mod init demo && \
    go get github.com/libtmux/libtmux-go/tmux@latest && \
    go test
  • Text already on screen matches at once, with MatchedAtEntry set. The
    shell's echo of a typed line matches too, so name the answer, not the command.
  • Only the visible screen is read: text that scrolled off is not seen, and a
    poll sees the final state of text a program overwrote.
  • Each read runs the owner's after-capture-pane hook.
  • Every error carries the screen the wait last read.

More: docs/contracts.md.

PaneObservation.WaitFor: wait for what a command prints

Needs tmux 3.7. It reports only output written after its baseline, where
Pane.WaitForText matches what is on screen. tmux.Poll is for
state tmux does not announce, not for pane text.

Open an observation with Pane.OpenObservation
before typing, then wait for text the command prints:

// Given: ctx context.Context; pane tmux.Pane
// Open the observation before typing, so no output is missed.
output, err := pane.OpenObservation(ctx)
if err != nil {
	return fmt.Errorf("observe pane: %w", err)
}
defer func() { err = errors.Join(err, output.Close()) }()

// A pane is an io.Writer, and a newline is the Enter key.
command := `echo "6 x 7 = $((6 * 7))"`
if _, err := fmt.Fprintln(pane.Writer(ctx), command); err != nil {
	return fmt.Errorf("type command: %w", err)
}
// The terminal echoes what is typed, so wait for the answer: the typed
// line says "$((6 * 7))" and never "42".
if _, err := output.WaitFor(ctx, func(text string) bool {
	return strings.Contains(text, "6 x 7 = 42")
}); err != nil {
	return fmt.Errorf("wait for answer: %w", err)
}
fmt.Println("the pane answered 6 x 7 = 42")

tmux pushes each write as it happens, so nothing polls. The terminal echoes
what is typed, and that echo is output too, which is why the wait names the
answer the command prints.

Runnable: examples/pane-io, which goes on to read the
pane as an io.Reader.

To move a payload, skip the typing: the shell in the pane reads quotes, $,
and backslashes in it as syntax.

Server.LoadBufferFrom fills a tmux buffer from
an io.Reader, and Pane.CaptureTo writes a scrollback
to an io.Writer. examples/byte-streams does both.

Pane.SendKeys: send keys to a pane, then capture it

Window.SplitPane makes the pane,
Pane.Resize and Window.Resize set
sizes, and Pane.Capture reads the screen. Given a window,
this excerpt of a whole program
splits it, sizes the new pane, types into it and reads it back:

// Given: ctx context.Context; window tmux.Window
pane, err := window.SplitPane(ctx, tmux.SplitPaneRequest{
	Direction: tmux.PaneDirectionRight, Command: "cat",
})
if err != nil {
	return fmt.Errorf("split window: %w", err)
}
pane, err = pane.Resize(ctx, tmux.ResizePaneRequest{Width: tmux.PaneCells(20)})
if err != nil {
	return fmt.Errorf("resize pane: %w", err)
}
text := "hello"
if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &text}); err != nil {
	return fmt.Errorf("send keys: %w", err)
}
// Capture reads one moment, so wait for the typed line to show first.
if _, err := pane.WaitForText(ctx, tmux.WaitForTextRequest{Text: text}); err != nil {
	return fmt.Errorf("wait for text: %w", err)
}
lines, err := pane.Capture(ctx, tmux.CapturePaneRequest{})
if err != nil {
	return fmt.Errorf("capture pane: %w", err)
}
width, _ := pane.Width()
fmt.Printf("%d columns, showing %q\n", width, lines[0])

It prints 20 columns, showing "hello".

Pane.Kill, Window.Kill,
Session.Kill and Server.Kill remove
what a program made.

Session.SetMouse and the other typed setters change
options and hooks.

Watch tmux change

Session.OpenNotifications: hear changes as they happen

It returns a stream of what tmux does, such as a window opening or a session
being renamed. tmux pushes each change when it happens, so nothing has to
guess how often to ask:

// Given: ctx context.Context; session tmux.Session
stream, err := session.OpenNotifications(ctx, tmux.NotificationOptions{})
if err != nil {
	return fmt.Errorf("open notification stream: %w", err)
}
defer func() { err = errors.Join(err, stream.Close()) }()

// Rename after subscribing; notifications do not include earlier changes.
if _, err := session.Rename(ctx, "control-example"); err != nil {
	return fmt.Errorf("rename session: %w", err)
}

for {
	notification, err := stream.Next(ctx)
	if err != nil {
		return fmt.Errorf("read notification: %w", err)
	}
	fmt.Printf("notification: %s\n", notification.Kind())
	if notification.Kind() == tmux.ControlNotificationSessionRenamed {
		fmt.Println("heard the rename")
		break
	}
}

The first notification a new stream reads is %session-changed, which is
tmux telling the client which session it joined. The rename follows it.

This prints notification: %session-changed, then
notification: %session-renamed, then heard the rename.

NotificationStream.Subscribe: have tmux watch a value

A subscription goes further: tmux evaluates a format for you and reports it
each time its value changes, so a program hears about a window count or a
pane's current command without asking again:

// Given: ctx context.Context; session tmux.Session;
// stream *tmux.NotificationStream
// A subscription is a format tmux evaluates for you: it reports the value
// when it first looks, about a second later, and then each time it changes.
if err := stream.Subscribe(ctx, tmux.SubscriptionRequest{
	Name: "windows", Format: "#{session_windows}",
}); err != nil {
	return fmt.Errorf("subscribe: %w", err)
}
if _, err := session.NewWindow(ctx, tmux.NewWindowRequest{}); err != nil {
	return fmt.Errorf("open window: %w", err)
}
for {
	notification, err := stream.Next(ctx)
	if err != nil {
		return fmt.Errorf("read notification: %w", err)
	}
	if change, ok := notification.Subscription(); ok && change.Value == "2" {
		fmt.Println("session has", change.Value, "windows")
		return nil
	}
}

The session started with one window, so this prints session has 2 windows.

Runnable: examples/control-mode-subscribe
is the program both blocks come from.

Choosing how to reach tmux

Start with a plain Server: one tmux process per command. The
other paths keep a tmux client attached, or send several commands at once, to
start fewer:

Path Construct it with Cost Reach for it
a process per command tmux.NewServer a tmux process per command sent one-shot commands
a connection Session.OpenControl one tmux client, kept attached repeated commands
several connections ConnectionOptions{Lanes: N} N tmux clients, kept attached readers running in parallel
a plan tmux.NewPlan then Plan.Run fewer process starts builds and layouts
a stream Session.OpenNotifications one tmux client, kept attached watching what tmux does

tmux.NewPlan: write a layout in one pass

A plan records commands instead of running them, sends the ones needing no
answer together, and hands back a reference to what a step will create. This
program records one, previews it, runs it, and prints each step's result:

// Command planned-build records tmux commands, uses forward references, and
// groups compatible operations into fewer invocations.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/libtmux/libtmux-go/tmux"
)

func main() {
	if err := start(); err != nil {
		log.Fatal(err)
	}
}

// start owns cleanup because log.Fatal skips deferred calls in main.
func start() error {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Choose an unused socket name: cleanup kills the server selected here.
	// The empty config keeps personal settings out of a new server.
	server, err := tmux.NewServer(tmux.ServerOptions{
		SocketName: "libtmux-planned-build",
		ConfigFile: os.DevNull,
	})
	if err != nil {
		return fmt.Errorf("configure tmux server: %w", err)
	}
	return run(ctx, server)
}

// run accepts injected server state so tests can isolate the example.
func run(ctx context.Context, server tmux.Server) (err error) {
	session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-planned"})
	if err != nil {
		return fmt.Errorf("create session: %w", err)
	}
	defer func() {
		cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
		defer cleanupCancel()
		err = errors.Join(err, session.Kill(cleanupCtx))
	}()

	window, err := session.NewWindow(ctx, tmux.NewWindowRequest{Name: new("planned")})
	if err != nil {
		return fmt.Errorf("create window: %w", err)
	}

	// The split's forward reference is usable before tmux reports its pane ID.
	plan := tmux.NewPlan()
	plan.SelectLayout(window.Ref(), tmux.SelectLayoutRequest{Layout: "tiled"})
	editor := plan.SplitPane(window.Ref(), tmux.SplitPaneRequest{Attach: true})
	plan.SetPaneTitle(editor, "editor")
	plan.SendKeys(editor, tmux.SendKeysRequest{Command: new("echo built")})
	plan.DisplayMessage(editor, "#{pane_title}")

	// Preview leaves unresolved forward-reference steps nil; other rendering
	// failures return an error.
	preview, err := plan.Preview(tmux.Version{})
	if err != nil {
		return fmt.Errorf("preview: %w", err)
	}
	for index, argv := range preview {
		if argv == nil {
			fmt.Printf("step %d: rendered when the split has reported its pane\n", index)
			continue
		}
		fmt.Printf("step %d: tmux %s\n", index, strings.Join(argv, " "))
	}

	// Groups end when later steps need a created ID or when merged stdout would
	// prevent result attribution.
	dispatches := plan.Explain()
	for _, dispatch := range dispatches {
		fmt.Printf("tmux invocation carrying steps %v, ends because it %s\n",
			dispatch.Ops, dispatch.Reason)
	}
	fmt.Printf("operations: %d, tmux invocations: %d\n", plan.Len(), len(dispatches))
	if len(dispatches) >= plan.Len() {
		return fmt.Errorf("%d operations took %d tmux invocations, want fewer than one each",
			plan.Len(), len(dispatches))
	}

	result, err := plan.Run(ctx, server)
	if err != nil {
		return fmt.Errorf("run plan: %w", err)
	}
	if !result.OK() {
		return fmt.Errorf("plan did not complete: %w", result.Err())
	}

	// Results remain per operation even when operations share an invocation.
	for index, op := range result.Ops {
		fmt.Printf("step %d %-16s %-8s created %q stdout %q\n",
			index, op.Command, op.Status, op.Created, op.Stdout)
	}
	if result.Ops[1].Created == "" {
		return errors.New("the split reported no pane ID")
	}
	read := result.Ops[len(result.Ops)-1]
	if got := read.Stdout; len(got) != 1 || got[0] != "editor" {
		return fmt.Errorf("the read reported %q, want the title the plan set", got)
	}
	return nil
}

Save it as main.go and run it as the quick start does, or run
examples/planned-build from a clone. It prints:

step 0: tmux select-layout -t @1 tiled
step 1: tmux split-window -t @1 -v -P -F#{pane_id}
step 2: rendered when the split has reported its pane
step 3: rendered when the split has reported its pane
step 4: rendered when the split has reported its pane
step 5: rendered when the split has reported its pane
tmux invocation carrying steps [0], ends because it alone
tmux invocation carrying steps [1], ends because it creates
tmux invocation carrying steps [2 3 4], ends because it chained
tmux invocation carrying steps [5], ends because it captures
operations: 6, tmux invocations: 4
step 0 select-layout    complete created "" stdout []
step 1 split-window     complete created "%2" stdout []
step 2 select-pane      complete created "" stdout []
step 3 send-keys        complete created "" stdout []
step 4 send-keys        complete created "" stdout []
step 5 display-message  complete created "" stdout ["editor"]

In it, new("echo built") is how Go 1.26 writes a pointer to a value, for a
field that may be left unset. Plan.Run sends the plan, and
reports on each step by itself even where several shared one tmux process:

// Given: ctx context.Context; server tmux.Server; plan *tmux.Plan
result, err := plan.Run(ctx, server)
if err != nil {
	return fmt.Errorf("run plan: %w", err)
}
if !result.OK() {
	return fmt.Errorf("plan did not complete: %w", result.Err())
}

// Results remain per operation even when operations share an invocation.
for index, op := range result.Ops {
	fmt.Printf("step %d %-16s %-8s created %q stdout %q\n",
		index, op.Command, op.Status, op.Created, op.Stdout)
}

The last step reads back the title the plan set, so its line ends
stdout ["editor"].

Plan.Explain: see what runs in tmux first

Plan.Preview renders each step's tmux arguments, and
Explain shows how the plan groups steps into tmux invocations and why each
group ends. Neither runs a command:

// Given: plan *tmux.Plan
preview, err := plan.Preview(tmux.Version{})
if err != nil {
	return fmt.Errorf("preview: %w", err)
}
for index, argv := range preview {
	if argv == nil {
		fmt.Printf("step %d: rendered when the split has reported its pane\n", index)
		continue
	}
	fmt.Printf("step %d: tmux %s\n", index, strings.Join(argv, " "))
}

// Groups end when later steps need a created ID or when merged stdout would
// prevent result attribution.
dispatches := plan.Explain()
for _, dispatch := range dispatches {
	fmt.Printf("tmux invocation carrying steps %v, ends because it %s\n",
		dispatch.Ops, dispatch.Reason)
}
fmt.Printf("operations: %d, tmux invocations: %d\n", plan.Len(), len(dispatches))

Six tmux commands go out in four process starts, so this prints
operations: 6, tmux invocations: 4.

Plan.Run groups with Folding.
Plan.RunWith takes another Planner,
such as Sequential, which sends one process per step.

Session.OpenControl: one client for every command

A connection keeps one tmux client attached and sends each command through it,
where a plain Server starts a process per command. It needs
tmux 3.7:

// Given: ctx context.Context; session tmux.Session
connection, err := session.OpenControl(ctx, tmux.ConnectionOptions{})
if err != nil {
	return fmt.Errorf("open control connection: %w", err)
}
defer func() { _ = connection.Close() }()
connected := connection.Session()

A connection appears in list-clients and counts toward session_attached,
which is why opening one is explicit.

examples/fast-path runs ten searches down each path.

It prints process path: 10 searches, then connection path: 10 searches.

"Execution modes" in the package documentation has the rules
each path follows. BENCHMARKS.md is what each costs,
measured on every supported tmux.

Testing your own code

tmuxtest.RunInPane: run your program in a real pane

tmux/tmuxtest runs your program inside a real tmux and
lets a test assert on what it drew, without a sleep in it. This is a whole
test file:

package greeter_test

import (
	"context"
	"os"
	"testing"
	"time"

	"github.com/libtmux/libtmux-go/tmux/tmuxtest"
)

func TestMain(m *testing.M) {
	os.Exit(tmuxtest.Main(m))
}

func TestGreeterAnswersALine(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// A stand-in for your program: it greets each name it reads.
	greeter := `while read name; do echo "hello, $name"; done`
	pane := tmuxtest.RunInPane(ctx, t, greeter)

	tmuxtest.Type(ctx, t, pane, "world")
	tmuxtest.WaitForLine(ctx, t, pane, "hello, world")
}

tmuxtest.WaitForText: a failed wait shows the screen

A wait that runs out fails with the screen the pane last held, which is what a
print statement would have shown. This one was waiting for ready:

tmuxtest: pane %1 never showed a line containing "ready"
the pane showed 3 line(s):
    | tmuxtest$ printf 'loading widgets\nconnecting\n'; cat
    | loading widgets
    | connecting

More in tmuxtest

tmuxtest.NewServer gives a test whose subject is tmux
itself a server on a socket of its own, killed when the test ends.

tmuxtest.ScriptedTmux answers the tmux commands you
name instead, so a test of your own code needs no tmux installed.
tmux/tmuxtest shows both.

Packages

Package Source Reference What it is
tmux tmux/ pkg.go.dev The library. Sessions, windows, panes, options, hooks, formats, filters, snapshots, plans.
tmuxtest tmux/tmuxtest/ pkg.go.dev Run your program in a real tmux and assert on what it drew.
tmuxq tmuxq/ pkg.go.dev Model-free generic helpers for slices and iter.Seq.

Others ship as separate modules, so go get on the library pulls in none
of them:

Module Source Reference What it is
mcp mcp/ pkg.go.dev A tmux server for AI agents, over the Model Context Protocol
workspace workspace/ pkg.go.dev Loads tmuxp-style YAML workspaces and builds them, with a CLI
benchmarks benchmarks/ — Prints what each way of reaching tmux costs

The MCP server:

$ go install github.com/libtmux/libtmux-go/mcp/cmd/libtmux-mcp@latest

The workspace CLI:

$ go install github.com/libtmux/libtmux-go/workspace/cmd/tmux-workspace@latest

tmux: the library

Sessions, windows, panes, options, hooks, formats, filters, snapshots and
plans, with nothing outside the standard library.

Reference: pkg.go.dev,
libtmux.org. Changelog:
CHANGELOG.md.

Session.Run runs a command in a window of its own, with
a terminal. A nonzero exit status arrives in the result:

// Given: ctx context.Context; session tmux.Session
// The command runs with a terminal, so test -t holds where a pipe fails.
command := "test -t 1 && echo stdout is a terminal; exit 3"
result, err := session.Run(ctx, command, tmux.RunOptions{})
if err != nil {
	return fmt.Errorf("run command: %w", err)
}
for _, line := range result.Lines {
	fmt.Println("screen:", line)
}
fmt.Println("exited", result.Status)

This prints screen: stdout is a terminal, then exited 3.

tmuxq: filters for any slice

Helpers that find records in a slice or an iter.Seq, whether your own or the
ones tmux returns.

Reference: pkg.go.dev,
libtmux.org. Changelog:
CHANGELOG.md.

tmuxq.Where keeps what a function accepts, and
tmuxq.First returns the first match. This needs no tmux:

type task struct {
	name string
	done bool
}
tasks := []task{{"build", true}, {"test", false}, {"deploy", false}}
open := func(t *task) bool { return !t.done }

for _, t := range tmuxq.Where(tasks, open) {
	fmt.Println("open:", t.name)
}
first, _ := tmuxq.First(tasks, open)
fmt.Println("first open:", first.name)

This prints open: test and open: deploy, then first open: test.

tmuxtest: a real tmux for tests

Runs your program in a real pane and lets a test assert on what it drew. What
it starts ends with the test.

Reference: pkg.go.dev,
libtmux.org. Changelog:
CHANGELOG.md.

tmuxtest.NewServer gives a test of tmux itself a server
of its own. It goes in a package whose TestMain calls
tmuxtest.Main, as in the test above:

// Given: ctx context.Context; t *testing.T
server := tmuxtest.NewServer(ctx, t)

session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "under-test"})
if err != nil {
	t.Fatal(err)
}
if name, _ := session.Name(); name != "under-test" {
	t.Errorf("session name = %q, want under-test", name)
}

workspace: tmuxp-style workspaces

Loads tmuxp-style YAML workspace files and builds them in tmux, from Go or with
the tmux-workspace command.

Reference: pkg.go.dev,
libtmux.org,
command reference,
CLI.md. Changelog:
workspace/CHANGELOG.md.

With the command installed as above and a workspace file
saved as project.yaml, tmux-workspace load builds it
on a tmux socket named project without attaching to it:

$ tmux-workspace load \
    -L project \
    -d \
    ./project.yaml

mcp: a tmux server for agents

Serves one tmux server to Model Context Protocol clients, as the
libtmux-mcp command or from a program of your own.

Reference: pkg.go.dev,
libtmux.org,
tool pages,
TOOLS.md. Changelog: mcp/CHANGELOG.md.
mcp/README.md covers client configuration.

An MCP client starts the server installed above itself, and speaks to it over
stdin and stdout. Register it with Claude Code:

$ claude mcp add tmux -- libtmux-mcp

Check which socket it reaches, and what that holds, without a client, with
libtmux-mcp -doctor:

$ libtmux-mcp -doctor

The benchmarks
module is a command that prints what each way of reaching tmux costs.

What it leaves out

  • Live objects. A Session or a Pane is a
    record of what tmux said when it was read. Read again, or subscribe, to see
    a change.
  • A terminal emulator. A capture and
    Session.Run return the screen tmux drew;
    PaneObservation returns the bytes a program wrote.
  • Your tmux configuration file. Nothing here edits ~/.tmux.conf. tmux
    reads it when it starts a server, unless
    ServerOptions.ConfigFile names another.

Support and status

Any release may change or remove exported identifiers without a deprecation
period, so pin an exact version. Not recommended for production.

  • No third-party Go dependencies. The core module imports only the
    standard library; tmux is required at runtime.
  • Go 1.26 or newer, tmux 3.3a or newer. The Go floor rises with Go's own
    support window.
  • Linux, including WSL, is the primary platform. macOS is best-effort, with
    little CI coverage. What CI covers
    has the rest.
  • Other hosts. The BSDs, illumos and Plan 9 build; Windows compiles but
    has no tmux.
  • Tagged per directory. The tags are mcp/vN and workspace/vN beside the
    core's plain vN; pin the ones you want. Each module keeps a changelog beside
    its go.mod.

Documentation

The package documentation is the reference, written to be read start to
finish:

$ go doc github.com/libtmux/libtmux-go/tmux

It opens with a task index and maps each tmux command to its method:
kill-pane is Pane.Kill, rename-session is
Session.Rename.

Reference Every exported identifier, method, and field, one page each
tmux/ How the library is shaped: records, naming, options, errors
tmux/docs/contracts.md What the library promises: the tmux version check
examples/ Runnable programs, one per topic, each with a page of notes
DESIGN.md The conventions this package holds itself to, and the bakeoffs behind them
BENCHMARKS.md What each way of reaching tmux costs
CHANGELOG.md What each release of the tmux module changed, and the changes that span modules
workspace/CHANGELOG.md What each release of workspace changed
mcp/CHANGELOG.md What each release of mcp changed
SECURITY.md What this software executes, and how to report a hole in it
CONTRIBUTING.md The gates a change has to pass, and where the writing rules live
WRITING.md How this repository writes: docs, the changelog, commits
AGENTS.md Which of the above applies to what you are changing

AI policy

Use these packages with AI tools as you like. When contributing, check what you
submit and wait for a maintainer's invitation before preparing a pull request.
See the AI policy, also kept as
AI_POLICY.md.

Attribution

Please use the following BibTeX template to cite libtmux-go in scientific
discourse:

@misc{libtmux-go,
   author = {Tony Narlock},
   year = {2026},
   note = {https://libtmux.org/en/go/},
   title = {libtmux-go: Go wrapper for tmux}
}

License

MIT. See LICENSE.

Reviews (0)

No results found