LibTmux 0.1.1

Prefix Reserved
dotnet add package LibTmux --version 0.1.1
                    
NuGet\Install-Package LibTmux -Version 0.1.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LibTmux" Version="0.1.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LibTmux" Version="0.1.1" />
                    
Directory.Packages.props
<PackageReference Include="LibTmux" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LibTmux --version 0.1.1
                    
#r "nuget: LibTmux, 0.1.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LibTmux@0.1.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LibTmux&version=0.1.1
                    
Install as a Cake Addin
#tool nuget:?package=LibTmux&version=0.1.1
                    
Install as a Cake Tool

LibTmux

LibTmux libtmux.org

A typed, async-first tmux client for .NET: servers, sessions, windows, panes, clients, options, hooks and buffers, against every tmux from 3.3a to 3.8, on net8.0 and net10.0.

Run a command and read its exit status, find and filter what a server holds, type into a pane and wait for the answer, and choose how a call reaches tmux.

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 project:

$ dotnet add package LibTmux

Releases. Releases are numbered 0.1.N, and each release increments 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.

Contents — Quick start · Find things · Run a command · Change tmux · Filter · Choose a path · Retries · Observe · Testing · Packages · Leaves out · Support

Quick start

Connect to the tmux server that is running, make a session, a window, and a pane, and type a command into the pane. This is the whole program:

using LibTmux;

// Requires a tmux server already listening on this socket:
// ConnectAsync() discovers one, it never starts one. With nothing
// running yet, call Server.CreateOwnedAsync() instead.
Server server = await Server.ConnectAsync();
Session session = await server.CreateSessionAsync(new NewSessionRequest { Name = "build" });
Window window = await session.CreateWindowAsync(new NewWindowRequest { Name = "tests" });
Pane pane = (await window.GetPanesAsync())[0];

await pane.SendTextAsync("dotnet test");

To run it, make a console project and paste the program into Program.cs, with tmux 3.3a or newer on PATH and a server running:

$ dotnet new console --output demo && \
    cd demo && \
    dotnet add package LibTmux

It prints nothing. The new session build has a window tests, and its pane has received dotnet test.

Server.ConnectAsync finds a server that is already listening and never starts one. With nothing running, call Server.CreateOwnedAsync, which starts a server and stops it when disposed.

Every call that reaches tmux is asynchronous and takes a CancellationToken.

Every csharp run block below runs against a tmux server of its own, with server, session, window, pane, and ct already in hand.

Find sessions, windows, and panes

Session.GetWindowsAsync: the windows of a session

One call reads the windows; Window.GetPanesAsync reads a window's panes, and Server.GetSessionsAsync reads the sessions. They return IReadOnlyList<T> and never run tmux while you enumerate them:

foreach (Window each in await session.GetWindowsAsync(ct))
{
    foreach (Pane every in await each.GetPanesAsync(ct))
    {
        Console.WriteLine($"{each.Name} {every.Index} {every.Width}x{every.Height}");
    }
}

It prints one line per pane: the window name, the pane index, and its size.

A listing that tmux rejects throws TmuxCommandException. A live server with no sessions returns an empty list. Server.IsAliveAsync returns false when the server cannot be reached.

Server.CaptureSnapshotAsync: the whole hierarchy in one read

A snapshot walks sessions, windows, and panes once, to the SnapshotDepth you ask for, and records how it went in SnapshotMetadata:

Server snapshot = await server.CaptureSnapshotAsync(SnapshotDepth.Panes, ct);
SnapshotMetadata acquired = snapshot.SnapshotMetadata!;
Console.WriteLine($"{acquired.Depth}: {acquired.Elapsed} on {acquired.Generation}");
foreach (Pane member in snapshot.Panes)
{
    Console.WriteLine($"{member.Session.Name}/{member.Window.Index}: {member.CurrentCommand}");
}

It prints the depth, how long the read took, and one line per pane.

Session.FindWindowAsync: look one up

Server.GetWindowAsync throws TmuxObjectNotFoundException for an absent window; FindWindowAsync returns null after a successful lookup that finds none:

Window created = await session.CreateWindowAsync(new NewWindowRequest { Name = "lookup" }, ct);
Server connected = await server.ConnectAsync(ct);
Window read = await connected.GetWindowAsync(created.Id, ct);
Console.WriteLine($"{read.Name} {read.Width}x{read.Height}");

Window? missing = await session.FindWindowAsync("not-created", ct);
Console.WriteLine($"missing {missing is null}");

Session current = await session.RefreshAsync(ct);
if (current.ActiveWindow.IsCaptured)
{
    Window active = current.ActiveWindow.Value;
    Console.WriteLine($"active {active.Name}");
}

It prints the window's name and size, missing True, and the active window's name.

Session.ActiveWindow, Session.ActivePane, and Window.ActivePane hold at most one captured child. Read Value, or TryGetValue when absence is expected; reading Value on an uncaptured child throws, and no property read runs tmux.

Run a command and read what it printed

Pane.RunAsync: a command's real exit status

It runs a POSIX shell command in a pane and returns PaneRunResult: the exit status and the rendered pane output. A command that exits nonzero returns normally with that status:

PaneRunResult run = await pane.RunAsync(
    "printf 'hello-from-libtmux\\n'",
    TimeSpan.FromSeconds(10),
    cancellationToken: ct);
if (run.ExitStatus != 0)
{
    throw new InvalidOperationException($"Command exited {run.ExitStatus}.");
}

if (!run.Output.Contains("hello-from-libtmux"))
{
    throw new InvalidOperationException("Command output was not observed in the pane.");
}

It prints nothing and throws if the status or the line is wrong.

  • A timeout returns TimedOut = true and ExitStatus = null; the command may still be running.
  • PaneRunResult.Output is the rendered pane text, so it can differ from the command's stdout and stderr bytes. Check PaneRunResult.LinesMissed and PaneRunResult.AnchorLost before relying on it.
  • A second run in the same pane is refused until the first can be authenticated as complete.

Pane.SendTextAsync: type, then wait for the result

For a program that reads input directly, type it and wait for what it prints with TmuxWait.UntilAsync. tmux accepts a command before the shell has finished it, so the example waits for the result:

await pane.SendTextAsync("echo hello-from-libtmux", cancellationToken: ct);
await pane.EnterAsync(ct);

// tmux accepts a command before the shell has finished it, so the result is
// waited for rather than assumed.
string output = await TmuxWait.UntilAsync(
    async token => string.Join('\n', await pane.CaptureAsync(cancellationToken: token)),
    text => text.Contains("hello-from-libtmux", StringComparison.Ordinal),
    TimeSpan.FromSeconds(10),
    TimeSpan.FromMilliseconds(20));

It prints nothing; it returns once the pane shows the line.

Text goes in as input: leading dashes, semicolons, and newlines are typed, and NUL is rejected before dispatch.

For readiness text a pane prints, Pane.WaitForTextAsync returns a typed outcome with a bounded rendered tail; the executed example shows setup and cleanup.

Change windows, panes, and options

Window.RenameAsync: a changed copy

A handle says what it read, and that stays true. An operation that changes what an object is hands back a replacement:

Window renamed = await window.RenameAsync("integration", ct);

It prints nothing; renamed has the new name and window keeps the old one.

Window.MoveAsync, Window.LinkAsync, and Window.UnlinkAsync check that the captured session and index still name the window before they change it.

If topology changes leave the result unknown, the call throws with unknown dispatch state: do not retry it.

Pane.SplitAsync: add a pane

Pane split = await pane.SplitAsync(new SplitPaneRequest { Direction = PaneDirection.Below }, ct);
await split.SetHeightAsync(10, ct);

It adds a pane below the first and sets its height to ten rows.

TmuxOptions and TmuxHooks: settings and callbacks

tmux has no types, so an option value carries the text tmux reported alongside the readings that text supports. An option the window does not hold reads as the inherited value:

await window.Options.SetAsync(new SetOptionRequest("automatic-rename", "off"), ct);
TmuxOption option = (await window.Options.GetAsync(
    new GetOptionRequest("automatic-rename"), ct))[0];

Console.WriteLine($"{option.Value.Raw} flag={option.Value.Boolean}");

It prints the raw value and whether tmux reads it as a flag.

Hooks are arrays even with one entry:

TmuxHook hook = await server.Hooks.SetAsync(
    new SetHookRequest("alert-bell", "set-option -g @rang yes"), ct);

Filter what you read

Plain LINQ

Ordinary filtering is LINQ over what you already read:

IReadOnlyList<Window> windows = await session.GetWindowsAsync(ct);
IEnumerable<Window> building = windows.Where(
    each => each.Name.StartsWith("build", StringComparison.Ordinal));

QueryExtensions.Matching: declarative filters over what you hold

It turns an expression into a portable document, or throws; it never quietly falls back to filtering in memory:

IReadOnlyList<Session> sessions = await server.GetSessionsAsync(ct);
IReadOnlyList<Session> building = sessions.Matching<Session>(
    session => session.Name.StartsWith("build", StringComparison.Ordinal)
        && session.Attached);

Relations quantify, and the element type carries its own fields:

Server captured = await server.CaptureSnapshotAsync(SnapshotDepth.Windows, ct);
IReadOnlyList<Session> withBuild = captured.Sessions.Matching<Session>(
    session => session.Windows.Any(
        each => each.Name.StartsWith("build", StringComparison.Ordinal)));

QueryExtensions.Translate: the same filter as a document

The expression is also a document, written here and answered somewhere else. LibTmux.Query.Json puts it on the wire:

QueryDocument document = QueryExtensions.Translate<Session>(
    session => session.Name.StartsWith("build", StringComparison.Ordinal)
        && session.Attached);

The document uses stable wire names: Session.Name is session_name and Client.IsControlClient is client_control_mode.

A field outside the catalog throws UnsupportedQueryExpressionException. UnsafeTmuxFilter is the separate opt-in for native tmux -f filters.

QueryPlan<T>: ask tmux to narrow the read

Prepare a reusable plan from an inspected daemon version with Server.InspectAsync, then execute it for a fresh observation:

Server inspected = await server.InspectAsync(ct)
    ?? throw new InvalidOperationException("The tmux daemon is absent.");
QueryDocument predicate = QueryExtensions.Translate<Window>(
    candidate => candidate.IsActive && candidate.Name.StartsWith("build", StringComparison.Ordinal));
QueryPlan<Window> plan = predicate.Plan<Window>(inspected.DaemonVersion!.Value);
QueryResult<Window> result = await plan.ExecuteAsync(inspected, ct);

Console.WriteLine($"{result.Count} matches from {result.Snapshot.Windows.Count} placements");
foreach (string reason in plan.FallbackReasons)
{
    Console.WriteLine(reason);
}

It prints the match count and why anything stayed local.

  • QueryPushdown.Auto evaluates an exact leading predicate in tmux and the rest locally; QueryPushdown.Never evaluates everything locally; QueryPushdown.Require rejects a plan that needs local evaluation.
  • The pushed predicate moves work into tmux without reducing rows or payload.
  • Execution never initializes or starts an absent daemon.

QueryFieldCatalog: which fields can be filtered

foreach (QueryFieldDescriptor field in QueryFieldCatalog.GetFields(QueryTarget.Pane))
{
    Console.WriteLine($"{field.WireName}: {string.Join(", ", field.Operators)}");
}

It prints each pane field's wire name and the operators it supports.

Choose how to reach tmux

Server.ConnectAsync: which server it reaches

With no arguments it takes the first of these that says anything:

Source What it decides
ServerConnectionOptions an explicit socketPath, socketName, or socketNameFactory
LIBTMUX_SOCKET_PATH the socket, by path
LIBTMUX_SOCKET the socket, by name, under the root below
— no socket: tmux is given neither -L nor -S and picks the server itself

When nothing above chooses a socket, tmux follows TMUX to the server a pane belongs to, and without it uses the socket named default under TMUX_TMPDIR, which is /tmp when unset. A name resolves under the same root.

  • Options always win, so exporting a variable for a whole process cannot redirect a call that named a socket. When both variables are set, the path wins.
  • LIBTMUX_SOCKET_NAME was this variable's earlier name and selects nothing now.
  • Server.FromEnvironment reads the socket out of the TMUX variable inside a pane and passes it as a path. With no socket chosen, Server.ConnectAsync passes none and leaves the choice to tmux, which follows the TMUX it is handed.

Three ways to send a command

Which one a call uses is visible where the call starts. One-shot calls and chains work on every supported tmux; explicit control mode needs tmux 3.7+.

Mode Flip it on Dispatch What one more command costs
One-shot session.CreateWindowAsync(…) one command, awaited another round trip on a shared client; a process where needed
Control server.EnterControlModeAsync(ct) one client, streamed another round trip — ~0.2 ms
Chained server.Chain()…ExecuteAsync(ct) N batched, one invocation more bytes on one command line — ~0.02 ms

Each figure is the marginal cost of one more command, as medians of 100 samples against tmux 3.7b; absolute timings move with the machine. The recorded runs give the distribution, the tmux, the host, and the date.

Session.CreateWindowAsync: one command, a typed object back

// One command, a typed object back.
Window built = await session.CreateWindowAsync(new NewWindowRequest { Name = "build" }, ct);

Server.EnterControlModeAsync: one client, held open

// One client, held open, streaming what tmux does on its own.
await using IControlModeSession control = await server.EnterControlModeAsync(cancellationToken: ct);
IReadOnlyList<string> reply = await control.SendAsync(
    TmuxCommand.Create("list-windows"),
    ct);

The recorded process-transport baseline makes control mode an order of magnitude cheaper per command. One-shot calls can already share a client. IControlModeSession.SendAsync is safe to call concurrently.

Server.Chain: many commands, one invocation

// Many commands, one invocation, one process cost.
await server.Chain()
    .Then("new-window", "-d", "-n", "one")
    .Then("new-window", "-d", "-n", "two")
    .ExecuteAsync(ct);

A chain pays one round trip for the whole sequence, so it wins for a batch.

Know when a retry is safe

LibTmuxException.Dispatch: did tmux get the command?

Retrying is sound only when the command never reached tmux, and every failure says which it was, so the decision is an exception filter:

try
{
    await server.CreateSessionAsync(new NewSessionRequest { Name = "build" }, ct);
}
catch (LibTmuxException error) when (error.Dispatch == TmuxDispatchState.NotDispatched)
{
    // tmux was never started, so nothing happened and this can be sent again.
    Console.WriteLine($"safe to retry: {error.Dispatch}");
}

It prints safe to retry: NotDispatched when no tmux process ran.

See what the library does

ServerConnectionOptions.Logger: log each command

Pass an ILogger when connecting. Every command the handle runs as a tmux process is recorded once, at Debug, and failures at Error; commands sent through a control-mode client are not:

Server logged = await Server.ConnectAsync(new ServerConnectionOptions { Logger = logger });

TmuxDiagnostics: spans and metrics

Each command is also a span and a measurement. Subscribe by name, so the library keeps its single dependency: pass TmuxDiagnostics.ActivitySourceName to OpenTelemetry's AddSource and TmuxDiagnostics.MeterName to AddMeter.

Both cost nothing when nothing listens.

ServerConnectionOptions.Interceptor: wrap every command

A policy that belongs to your application, such as an audit trail, a retry, or a stand-in answer in a test, lives outside the library:

Server audited = await Server.ConnectAsync(
    new ServerConnectionOptions
    {
        Interceptor = async (invocation, next, token) =>
        {
            TmuxCommandResult result = await next(token);
            Console.WriteLine($"{string.Join(' ', invocation.Arguments)} → {result.ExitCode}");
            return result;
        },
    },
    ct);

Call next once to pass through, again to retry, or not at all to answer in tmux's place. Commands sent through a control-mode client skip the interceptor.

Share handles across threads

Testing your own code

LibTmux.Testing gives a test a tmux server of its own, on its own socket, killed deterministically. It is a separate package, so test scaffolding stays out of an application's output:

$ dotnet add package LibTmux.Testing

Scope disposal attempts to stop the owned server even when the test body throws. TmuxTestFactory hands out the scopes:

TmuxTestFactory factory = new();
await using TemporaryHierarchyScope scope = await factory.CreateHierarchyAsync(cancellationToken: ct);

await scope.Pane.SendTextAsync("echo $((6 * 7))", cancellationToken: ct);
await scope.Pane.EnterAsync(ct);

// The product is printed only once the shell has run the line.
string screen = await TmuxWait.UntilAsync(
    async token => string.Join('\n', await scope.Pane.CaptureAsync(cancellationToken: token)),
    text => text.Contains("42", StringComparison.Ordinal),
    TimeSpan.FromSeconds(10),
    TimeSpan.FromMilliseconds(20));
Package Adds
LibTmux.FSharp Curried task helpers, native F# sequences, and portable snapshot filters over LibTmux
LibTmux.Query.Json JSON for query documents
LibTmux.Workspace Sessions from tmuxp YAML
LibTmux.Mcp A Model Context Protocol server, as a .NET tool
LibTmux.Testing Scoped tmux servers, sessions and windows for tests
LibTmux.Extensions.DependencyInjection A Server handle for Microsoft.Extensions.DependencyInjection
LibTmux.Workspace.Cli tmux-workspace, a tmuxp-compatible command, as a .NET tool

Packages

LibTmux: the client

This package. Quick start shows the first calls.

Reference: libtmux.org and NuGet.

LibTmux.FSharp: F# helpers over the core

Curried task helpers, ordinary seq queries, and typed portable filters over the core handles.

Reference: libtmux.org, guides, and NuGet.

LibTmux.Query.Json: query documents as JSON

A filter written in one process can be evaluated in another; the core does not reference System.Text.Json.

Reference: QueryJson and NuGet.

LibTmux.Testing: a tmux server for each test

Scoped servers, sessions, and windows that clean up after themselves.

Reference: TmuxTestFactory, the testing guide, and NuGet.

LibTmux.Extensions.DependencyInjection: a Server for dependency injection

AddLibTmux registers a Server as a singleton and binds ServerConnectionOptions through IOptions<T>.

Reference: Server, the package README, and NuGet.

LibTmux.Workspace: sessions from tmuxp files

Parses tmuxp YAML or JSON and builds sessions, in one call or from a plan you review first.

Reference: WorkspaceBuilder, the reference index, and NuGet.

LibTmux.Workspace.Cli: the tmux-workspace command

Loads, captures, and converts tmuxp workspace files from a shell.

Reference: the command reference and NuGet.

LibTmux.Mcp: a tmux server for assistants

A Model Context Protocol server that gives an assistant hands on tmux; it installs as a .NET tool.

Reference: the MCP guide, the tool reference, and NuGet.

What it leaves out

  • Live objects. A handle holds what tmux said when you asked. Pane.RefreshAsync asks again.
  • Synchronous calls. Every call that reaches tmux is asynchronous.
  • Silent fallbacks. Declarative filtering throws on an expression it cannot translate. A flag the running tmux lacks is left off, and a warning names it.
  • A logging or telemetry implementation. The one dependency is the logging abstractions; TmuxDiagnostics names the sources so your pipeline subscribes.
  • YAML, JSON, and MCP. Workspace files, query documents on the wire, and the MCP server are separate packages, so a caller who does not want them never sees their dependencies.
  • Native Windows. PsmuxServer and its siblings read one psmux session and cannot create or change anything; see the preview contract.

Support and status

  • Releases. Releases are numbered 0.1.N, and each release increments 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.
  • tmux. 3.3a to 3.8, proven against every supported version before each release and against 3.3a and 3.8 on each commit.
  • .NET. net8.0 and net10.0, with one dependency: Microsoft.Extensions.Logging.Abstractions.
  • Systems. Linux, including WSL. macOS is best effort, without CI coverage. CI builds on Windows x64, where Server, Session, Window, and Pane are annotated unsupported.
  • Trimming and NativeAOT. Core APIs are analyzer-gated. Compile and Matching resolve properties by name, so they warn trimmed callers to preserve the filtered types' public properties.

Documentation

License

MIT

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on LibTmux:

Package Downloads
LibTmux.Query.Json

System.Text.Json support for LibTmux query documents. The core library does not reference it, so a caller who does not want a JSON dependency does not get one.

LibTmux.Workspace

Builds tmux sessions from tmuxp workspace files, on top of LibTmux.

LibTmux.Testing

Scoped tmux servers, sessions and windows that clean themselves up, for testing code that drives tmux. Kept out of LibTmux so test scaffolding does not ship in an application.

LibTmux.Extensions.DependencyInjection

Registers a LibTmux server handle and its options with Microsoft.Extensions.DependencyInjection.

LibTmux.FSharp

F# task functions and pure snapshot queries over LibTmux handles.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.1 411 11/1/2026
0.1.0 451 10/25/2026
0.0.0-alpha.24 124 10/25/2026
0.0.0-alpha.23 144 10/24/2026
0.0.0-alpha.22 168 10/19/2026
0.0.0-alpha.21 100 10/11/2026
0.0.0-alpha.20 451 10/5/2026
0.0.0-alpha.19 99 10/4/2026
0.0.0-alpha.18 101 10/3/2026
0.0.0-alpha.17 109 9/27/2026
0.0.0-alpha.16 98 9/26/2026
0.0.0-alpha.15 84 9/20/2026
0.0.0-alpha.14 95 9/20/2026
0.0.0-alpha.12 87 9/12/2026
0.0.0-alpha.10 105 8/30/2026
0.0.0-alpha.9 101 8/22/2026
0.0.0-alpha.8 111 8/22/2026
0.0.0-alpha.7 108 8/16/2026
0.0.0-alpha.6 100 8/16/2026
0.0.0-alpha.5 97 8/16/2026
Loading failed

LibTmux, LibTmux.FSharp, LibTmux.Testing, LibTmux.Query.Json, LibTmux.Extensions.DependencyInjection, LibTmux.Workspace, LibTmux.Workspace.Cli and LibTmux.Mcp share one version, so this release covers them together. What changed, per package and per release: https://github.com/libtmux/libtmux-dotnet/blob/master/CHANGELOG.md The public API is not settled and any release may change it; pin an exact version.