LibTmux

NAME

LibTmux

Create an observatory

Server starts and owns a private daemon. Split the first pane, label the instruments, then capture the new state. LEAVE closes the owner on normal or exceptional exit.

use LibTmux;

my $server = Server.start(:name<observatory>, :shell-command('exec cat'));
LEAVE $server.close if $server.defined;

my $before = $server.snapshot;
my $left = $before.panes.single.ref;
my $right = $left.split(:horizontal, :shell-command('exec cat'));
$left.set-title('Starlight telescope');
$right.set-title('Orion weather');

my $after = $server.snapshot;
my $telescope = $after.panes.filter(*.title.starts-with('Starlight')).single;
say "{$telescope.title}: {$after.panes.elems} panes";

The program prints Starlight telescope: 2 panes. The earlier snapshot retains one pane. .ref constructs an explicit command target; mutation does not change an earlier observation. snapshot performs I/O, while reading a captured field or relationship stays local.

Follow the captured graph

A Snapshot contains sessions, session groups, physical windows, window links, panes, clients and buffer metadata. A physical window can appear at several indexes, including twice in the same session. Its WindowLink owns the session-relative index and active state. windows and panes enumerate physical identities once; window-links preserves placements.

A pane's window and a window's panes resolve against the retained graph. Keeping an observation after closing its acquisition owner remains useful: field reads, relationship traversal and selection operations make no tmux calls. Use .ref.inspect or a new snapshot when fresh information is needed. References include daemon incarnation evidence, so a replacement daemon does not inherit an old pane reference merely by reusing its ID.

Query captured values

Combine validated query data with native Raku predicates and transformations:

use v6.d;
use LibTmux;

sub MAIN(Str:D :$tmux = 'tmux') {
    my $server = Server.start(:binary($tmux), :name<instruments>,
        :width(160), :height(40), :shell-command('exec cat'));
    LEAVE $server.close if $server.defined;

    my $telescope = $server.snapshot.panes.single.ref;
    my $weather = $telescope.split(:horizontal, :shell-command('exec cat'));
    my $recorder = $weather.split(:shell-command('exec cat'));
    $telescope.set-title('Starlight telescope');
    $weather.set-title('Orion weather');
    $recorder.set-title('Spectrum recorder');

    my $snapshot = $server.snapshot;
    my @wide := $snapshot.panes.where(%(width => %(gte => 60)));
    my $selected = @wide.filter(*.title.ends-with('telescope')).single;
    say "Wide telescope: {$selected.title}";

    my @others = $snapshot.panes.grep(*.id ne $selected.id).map(*.title).sort;
    say 'Other instruments: ' ~ @others.join(', ');
}

It prints Wide telescope: Starlight telescope and Other instruments: Orion weather, Spectrum recorder.

Binding with := preserves a typed selection. Array assignment materializes ordinary Raku values; scalar assignment itemizes the collection. where validates fields and operators even on an empty selection. filter evaluates a callback eagerly and returns the same entity selection type. grep, including :k, :kv and :p, retains its native Seq contract. map, sort, first and junction operations also retain ordinary Raku behavior. Mapping panes to titles does not produce a pane selection of strings.

Use single for exactly one member and single-or-nil for zero or one; multiple matches throw Cardinality. one remains a junction. A directly returned Failure from a filter callback throws its wrapped exception before Boolean coercion.

Compile reusable criteria with Filter. Its ACCEPTS method permits native matching, and to-json/from-json preserve the bounded portable data grammar. Closures, regexes and junctions remain local Raku matchers. Data equality follows field types; it does not use generic smartmatch. Relations use some, every, none, is and is-not. An unloaded relation raises MissingData instead of behaving like an empty relation.

For explicit live acquisition, query-panes accepts where and a pushdown policy. auto pushes proven exact restrictions and evaluates residual work locally; never evaluates locally after acquisition; require refuses an inexact translation. explain-panes describes projections, scope, pushed conditions and residual work. Arbitrary callbacks are not translated to tmux.

Choose an operation from capabilities

Capabilities describe the observed daemon separately from the client executable. Ask supports before offering a newer operation, or use require to obtain a typed refusal with its reason. This program gives Aurora telemetry a floating pane when supported and a tiled split otherwise:

use v6.d;
use LibTmux;

sub MAIN(Str:D :$tmux = 'tmux') {
    my $server = Server.start(:binary($tmux), :name<flight-deck>,
        :width(120), :height(36), :shell-command('exec cat'));
    LEAVE $server.close if $server.defined;

    my $snapshot = $server.snapshot;
    my $main = $snapshot.panes.single.ref;
    my $floating = $snapshot.capabilities.supports('pane-floating');
    my $auxiliary = $floating
        ?? $main.new-floating(:width(40), :height(12), :x(2), :y(2), :empty)
        !! $main.split(:horizontal, :empty);
    $auxiliary.set-title('Aurora telemetry');

    my $after = $server.snapshot;
    die 'The auxiliary pane was not captured' unless $after.panes.elems == 2;
    say 'Telemetry placement: ' ~ ($floating ?? 'floating' !! 'tiled');
    say $after.panes.where(%(id => $auxiliary.id)).single.title;
}

The selected placement and Aurora telemetry are printed. An empty pane can have no child PID; its pid is then null rather than a fabricated integer. state('pid') distinguishes known null from a field that was not acquired. Unknown release profiles are refused conservatively. Field, codec, layout and command decisions come from the same packaged catalogue.

React to terminal output

Synchronous acquisition returns a snapshot or selection. An -async method returns a Promise resolving to that result. A ControlConnection owns one persistent client; its event Supply is shared by its subscribers. Native react and whenever can consume the output without polling:

use v6.d;
use LibTmux;
use LibTmux::Control;

sub MAIN(Str:D :$tmux = 'tmux') {
    my $server = Server.start(:binary($tmux), :name<downlink>, :shell-command('exec cat'));
    LEAVE $server.close if $server.defined;
    my $snapshot = await $server.snapshot-async;
    my $pane = $snapshot.panes.single.ref;
    my $connection = await $server.open-control-async(:session-id($snapshot.sessions.single.id));
    LEAVE $connection.close if $connection.defined;

    my $message = 'Starlight downlink: 42 stars catalogued';
    my $received = '';
    react {
        whenever $connection.events.grep(PaneOutput) -> $event {
            if $event.pane-id eq $pane.id {
                $received ~= $event.data.decode('utf8-c8');
                die 'Downlink output exceeded its bound' if $received.chars > 65536;
                done if $received.contains($message);
            }
        }
        whenever start { $pane.send-text($message); $pane.send-keys('Enter') } { }
        whenever Promise.in(2) { die 'Downlink timed out' }
    }

    die 'The captured screen did not contain the downlink'
        unless $pane.capture.decode('utf8').contains($message);
    say $message;
    say 'Screen capture confirmed';
}

It prints Starlight downlink: 42 stars catalogued and Screen capture confirmed. Subscribing precedes input. Received pane bytes establish the screen-capture precondition; the deadline bounds the wait. send-text never appends Enter. Output remains bytes until an explicit decoder is selected, so fragmented and invalid UTF-8 remains available. Unknown notification types retain their raw representation.

Connections need explicit close. Cancellation terminates and joins owned client work, but does not undo commands that the daemon already executed. Reconnection requires a fresh observation; event delivery does not imply a complete current graph. Attachment is a separate terminal client owner.

Recover from partial completion

Batch reports each operation's completion scope and outcome. The batch recovery program checks Complete, Failed and Skipped, verifies the successful first effect, then removes it explicitly. Acknowledgement alone does not prove an application effect. A failed batch offers no rollback guarantee.

The observatory program combines creation, a control-output subscription, screen capture, local filtering and an explained source query in one checked lifecycle.

Ownership and operational errors

Server.start owns its private daemon. Server.new configures a borrowed endpoint; closing that facade leaves the daemon running. Both need explicit close. A connection or terminal attachment has its own lifetime and must also be closed. An observation retains values and the captured graph, not a live acquisition process.

Commands pass an argument vector. Literal pane text, explicit key presses, FORMAT expressions, tmux command templates and deliberate shell commands have separate entry points. Operational errors retain typed context and captured bytes. Optional lookup absence never disguises a failed command. Fields retain known null, false, zero, empty text, unsupported, unavailable and unloaded data as distinct states.

LibTmux v0.0.1

Typed tmux observations, queries and explicit commands for Raku

Authors

  • libtmux contributors

License

MIT

Dependencies

JSON::Fast:ver<0.21.0+>:auth<zef:timo>

Test Dependencies

Provides

  • LibTmux
  • LibTmux::Attachment
  • LibTmux::Batch
  • LibTmux::Capabilities
  • LibTmux::Catalogue
  • LibTmux::Client
  • LibTmux::Command
  • LibTmux::Configuration
  • LibTmux::Control
  • LibTmux::Control::Connection
  • LibTmux::Engine
  • LibTmux::Exceptions
  • LibTmux::Fields
  • LibTmux::Format
  • LibTmux::Layout
  • LibTmux::Model
  • LibTmux::Operations
  • LibTmux::Query
  • LibTmux::Query::Execution
  • LibTmux::Query::Plan
  • LibTmux::Selection
  • LibTmux::Server
  • LibTmux::Transport
  • LibTmux::Types

The Camelia image is copyright 2009 by Larry Wall. "Raku" is a trademark of the Yet Another Society. All rights reserved.

Built with Podlite — the markup and publishing tools behind this site.