Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ at one version, so a release has a section in each changelog.
- Core and Async can query the features and workarounds of the bound tmux
daemon. MCP exposes the same support decisions alongside the tools the
server permits. (#128)
- Core and Async can run a terminal program on a private or existing tmux
server, send input, and read its exit status and bounded screen. Program
management requires tmux 3.7 or newer. (#166)
- The unit tests load tmuxp's example catalog, with its license, through
`LibTmux::Workspace.load`. The files the loader reads show on the docs site as
workspace presets; each file it refuses fails with the message the test
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,12 @@ sessions after client close: 1

More: [ownership and errors][doc-ownership].

## Run a program and read its exit status

On tmux 3.7 or newer, core and Async can run a program on a new or existing
server and return its exit status and bounded final screen. See how
to [report a failed terminal command][owned-terminal-programs].

## Packages

Start with `libtmux`. Add the companion for your caller:
Expand Down Expand Up @@ -687,6 +693,7 @@ Part of the [libtmux.org](https://libtmux.org/) family alongside Python
[mcp-application]: https://libtmux.org/en/ruby/latest/mcp/reference/libtmux-mcp-application/
[multiplematcheserror]: https://libtmux.org/en/ruby/latest/reference/libtmux-multiplematcheserror/
[nomatcherror]: https://libtmux.org/en/ruby/latest/reference/libtmux-nomatcherror/
[owned-terminal-programs]: docs/reference/behavior.md#owned-terminal-programs
[pane]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-14z6/
[pane-capture]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-capture/
[pane-resize]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-resize/
Expand Down
16 changes: 16 additions & 0 deletions capabilities.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,22 @@
"minimum": "3.3a"
},
"capabilities": [
{
"id": "owned-terminal-program",
"name": "Owned terminal program",
"summary": "Run literal argv in an owned terminal and retain its final screen on the bound daemon.",
"since": "3.7",
"handling": "refuse",
"error": "LibTmux::UnsupportedFeatureError",
"apis": [
"LibTmux.start_program",
"LibTmux.run_program",
"LibTmux::Server#start_program",
"LibTmux::Async.start_program",
"LibTmux::Async.run_program"
],
"commands": []
},
{
"id": "control-mode",
"name": "Control mode",
Expand Down
124 changes: 91 additions & 33 deletions docs/reference/api.md

Large diffs are not rendered by default.

137 changes: 137 additions & 0 deletions docs/reference/behavior.md
Original file line number Diff line number Diff line change
Expand Up @@ -1135,3 +1135,140 @@ Checker-only dependencies are installed after each artifact's minimal
runtime import and executable recipes, so they cannot hide runtime dependency
omissions. Behavioral tests, real-tmux fixtures and the platform matrix remain
separate evidence.

## Owned terminal programs

`LibTmux.start_program(argv)` creates a private daemon. Pass `server:` or
call `server.start_program(argv)` to borrow an existing binding. Each program
owns one terminal in a new private session. Existing sessions and their
options keep their settings. The capability `owned-terminal-program` requires
tmux 3.7. The library checks the bound daemon before it creates a pane or
starts the application. The helper and Ruby installation must be accessible
to the daemon on the same machine.

`server.program_support` returns the bound daemon's identity, minimum
release and support decision in a frozen hash. It queries the binding
without running display hooks or acquiring a pane listing.

Pass an argv array of up to 256 KiB. Empty arguments and shell metacharacters
reach the executable literally. Set `cwd:`, `environment:`, `width:` or
`height:` when launching. Geometry defaults to 80×24 and accepts 1–256
columns and 1–100 rows. `history_lines:` accepts 0–100 and defaults to 100.

The factory retires the temporary pane used to set retention before it
returns or yields the program handle.

Use the block form for automatic cleanup. `run_program` returns the
completion result after closing its program. Startup, setup and completion
share the caller's timeout and cancellation token. Cancellation of an
owning run retires its resources. Each explicit `Program#wait` has a
separate deadline. Cancelling one waiter leaves the program and its other
waiters running. Async uses the supplied scope or creates a scoped adapter
for a core binding. It shares the same program owner and releases its own
adapter at close.

The supervisor observes the application's exit code or signal and sends
it over a one-shot local socket. After the application exits, the supervisor
writes a private terminal title. tmux processes that title after the
preceding output. Once both observations arrive, `wait` captures the screen
and returns a frozen result. Successful waiters share that result.
`screen` captures the current terminal on demand. The capture combines
rendered stdout and stderr, wraps at terminal width and retains up to 64 KiB
of valid UTF-8 from the visible rows and configured history.
`program.capture_screen` returns a frozen capture with `text` and
`truncated?`. The flag records bytes omitted by the 64 KiB cap. A completed
result exposes the same evidence through `screen_truncated?`. Terminal edits,
alternate screens and scrollback eviction can remove earlier text.
Polling screens provides snapshots and has no lossless stream or replay.
`send_text`, `send_keys` and `resize` operate on the live generation.

Each capture, input, resize and borrowed-pane retirement checks the
supervisor PID and launch token in the daemon command queue. Resize also
requires that the pane still belongs to its original window. A pane respawn
or daemon replacement invalidates the live handle. If the daemon is gone
before the native client connects, the operation raises a
`TargetNotFoundError` with `delivery: :not_sent`. If a connected native
client loses the daemon before a reply, the error has `delivery: :possibly_sent`.
A failed explicit close can be retried on the same handle. Block exit also runs
cleanup. Use the owner in the process that launched it. After a Ruby fork,
call `close` on the inherited handle in the forked child to release its copies
of the sockets. A child that
keeps those descriptors open can delay detection of owner death.

An external tmux move or resize can grow a pane beyond the program's
256-column or 100-row limit. Capture checks the geometry in the daemon
queue and raises `Program::ScreenGeometryError` before reading the screen.
Input and retirement remain available. Restore the pane size in tmux to
retry a capture or retrieve the observed completion with `wait`.

Closing the program releases its private socket. If the owner process dies,
the supervisor observes EOF and kills its foreground process group, including
children that ignore hangup. A process that creates a new group or session can
outlive this cleanup. The application runs with the daemon user's filesystem,
network and process privileges. The helper consumes and removes its private
launch files before running argv. Once setup completes a dedicated daemon
exits when its last session closes. A forced owner exit can leave its private
directory and socket pathname on disk after the daemon exits.

For recovery records, start the server explicitly and pass it to
`start_program`. Record `server.endpoint.socket_path` and the result of
`server.display('#{pid} #{start_time}').text` while the program runs.
After an interrupted launch, query that socket with
`tmux -N -S "$socket" display-message -p '#{pid} #{start_time}'` and
compare the identity before retiring a surviving dedicated daemon.
Once the recorded daemon has exited, remove its private directory.
On a shared daemon, check the specific program session and pane.

Run a sample migration command and report the failure from its retained
screen.

<!-- example: owned_program/main -->
```ruby
require "libtmux"
require "rbconfig"

command = [
RbConfig.ruby, "-e", "warn ARGV.fetch(0); exit 7",
"Migration stopped: café table missing"
]

result = LibTmux.run_program(command)
diagnostic = result.screen.lines(chomp: true).find do |line|
line.start_with?("Migration stopped:")
end
raise "Expected a migration failure with a diagnostic" unless
result.exit_status == 7 && diagnostic

puts "Exit #{result.exit_status}. #{diagnostic}"
```
<!-- /example -->

It prints:

```text
Exit 7. Migration stopped: café table missing
```


Send a line to an application on an existing server and check its own reply.

<!-- example: owned_program_input/main -->
```ruby
require "libtmux"
require "rbconfig"

command = [RbConfig.ruby, "-e", 'puts "Received: " + STDIN.readline.chomp']
LibTmux::Server.start do |server|
server.start_program(command) do |program|
program.send_text("café")
program.send_keys("Enter")
result = program.wait
reply = result.screen.lines(chomp: true).find { |line| line == "Received: café" }
raise "Missing confirmation from the program" unless reply && result.exit_status == 0
puts reply
end
end
```
<!-- /example -->

The program prints `Received: café`.
28 changes: 28 additions & 0 deletions docs/reference/contracts.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@
{
"version": 1,
"contracts": [
{
"id": "owned-terminal-programs",
"title": "Owned terminal programs",
"methods": [
"LibTmux.start_program",
"LibTmux.run_program",
"LibTmux::Server#program_support",
"LibTmux::Server#start_program",
"LibTmux::Async.start_program",
"LibTmux::Async.run_program",
"LibTmux::Program#capture_screen",
"LibTmux::Program#close",
"LibTmux::Program#inspect",
"LibTmux::Program#resize",
"LibTmux::Program#screen",
"LibTmux::Program#send_keys",
"LibTmux::Program#send_text",
"LibTmux::Program#wait",
"LibTmux::Program::Result#exit_status",
"LibTmux::Program::Result#inspect",
"LibTmux::Program::Result#screen",
"LibTmux::Program::Result#screen_truncated?",
"LibTmux::Program::Result#signal",
"LibTmux::Program::Screen#inspect",
"LibTmux::Program::Screen#text",
"LibTmux::Program::Screen#truncated?"
]
},
{
"id": "async-map",
"title": "Async map",
Expand Down
25 changes: 25 additions & 0 deletions examples/api/owned_program.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# frozen_string_literal: true

begin
# docs:begin main
require "libtmux"
require "rbconfig"

command = [
RbConfig.ruby, "-e", "warn ARGV.fetch(0); exit 7",
"Migration stopped: café table missing"
]

result = LibTmux.run_program(command)
diagnostic = result.screen.lines(chomp: true).find do |line|
line.start_with?("Migration stopped:")
end
raise "Expected a migration failure with a diagnostic" unless
result.exit_status == 7 && diagnostic

puts "Exit #{result.exit_status}. #{diagnostic}"
# docs:end main
rescue StandardError => error
warn "#{error.class}: #{error.message}"
exit 1
end
23 changes: 23 additions & 0 deletions examples/api/owned_program_input.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

begin
# docs:begin main
require "libtmux"
require "rbconfig"

command = [RbConfig.ruby, "-e", 'puts "Received: " + STDIN.readline.chomp']
LibTmux::Server.start do |server|
server.start_program(command) do |program|
program.send_text("café")
program.send_keys("Enter")
result = program.wait
reply = result.screen.lines(chomp: true).find { |line| line == "Received: café" }
raise "Missing confirmation from the program" unless reply && result.exit_status == 0
puts reply
end
end
# docs:end main
rescue LibTmux::UnsupportedFeatureError => error
warn "#{error.class}: #{error.message}"
exit 1
end
34 changes: 34 additions & 0 deletions examples/manifest.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
{
"version": 2,
"programs": [
{
"id": "owned_program",
"path": "examples/api/owned_program.rb",
"gem": "libtmux",
"api": {
"symbols": ["LibTmux.run_program"],
"capabilities": ["owned-terminal-program"],
"description": "Report a terminal program failure with the exit status and the final diagnostic.",
"output": "Exit 7. Migration stopped: café table missing\n"
}
},
{
"id": "owned_program_input",
"path": "examples/api/owned_program_input.rb",
"gem": "libtmux",
"api": {
"symbols": ["LibTmux::Server#start_program", "LibTmux::Program#send_text", "LibTmux::Program#send_keys", "LibTmux::Program#wait"],
"capabilities": ["owned-terminal-program"],
"description": "Send literal input on an existing server and verify the program's reply and exit status.",
"output": "Received: café\n"
}
},
{
"id": "quickstart",
"path": "examples/quickstart.rb",
Expand Down Expand Up @@ -454,6 +476,18 @@
"gems/libtmux/README.md"
],
"snippets": [
{
"id": "owned_program_input/main",
"source": "examples/api/owned_program_input.rb",
"region": "main",
"language": "ruby"
},
{
"id": "owned_program/main",
"source": "examples/api/owned_program.rb",
"region": "main",
"language": "ruby"
},
{
"id": "quickstart/main",
"source": "examples/quickstart.rb",
Expand Down
10 changes: 10 additions & 0 deletions gems/libtmux-async/lib/libtmux/async.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ def self.attach_cleanup(error, details)
end
private_class_method :attach_cleanup

# Own a private terminal program with scheduler-aware tmux requests.
def self.start_program(argv, parent: ::Async::Task.current, **options, &block)
adapter = ->(server) { Scope.new(parent: parent, server: server) unless server.is_a?(Server) }
Program.__send__(:start_with, adapter, argv, **options, &block)
end

def self.run_program(argv, **options)
Program.__send__(:run_with, self, argv, **options)
end

def self.open(server:, parent: ::Async::Task.current, **options)
raise ArgumentError, "Async scope requires a block" unless block_given?

Expand Down
20 changes: 11 additions & 9 deletions gems/libtmux-async/lib/libtmux/async/process.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,21 @@ class ProcessDriver

attr_reader :pid, :result

def initialize(scope, ticket, argv, input, deadline, cancel, limits)
def initialize(scope, ticket, argv, input, deadline, cancel, limits, stdout_tail: nil)
@scope, @ticket, @argv, @input = scope, ticket, argv, input
@deadline, @cancel, @limits = deadline, cancel, limits
@started = clock
@changed = ::Async::Notification.new
@tasks, @streams = [], []
@buffers = {stdout: +"".b, stderr: +"".b}
@stdout_tail = stdout_tail
@finished_reads = 0
end

def call
@buffers = {
stdout: Internal::CommandOutput.new(@limits.fetch(:stdout), tail: @stdout_tail),
stderr: Internal::CommandOutput.new(@limits.fetch(:stderr))
}
failure = nil
begin
watch_cancellation
Expand Down Expand Up @@ -219,16 +223,13 @@ def start_io
def read_stream(io, stream)
buffer = @buffers.fetch(stream)
loop do
remaining = @limits.fetch(stream) - buffer.bytesize
bytes = io.read_nonblock([CHUNK, remaining + 1].min, exception: false)
bytes = io.read_nonblock(buffer.read_size(CHUNK), exception: false)
case bytes
when nil then break
when :wait_readable then Fiber.scheduler.io_wait(io, IO::READABLE)
when String
raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) if bytes.bytesize > remaining

@scope.__send__(:retain_output, @ticket, bytes.bytesize)
buffer << bytes
appended = buffer.append(bytes) { |retained| @scope.__send__(:retain_output, @ticket, retained) }
raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) unless appended
end
end
@finished_reads += 1
Expand Down Expand Up @@ -273,7 +274,8 @@ def drive
raise @failure if @failure
if @status && @finished_reads == 2
check_budget(:publish)
@result = CommandResult.new(**@buffers, status: @status, pid: @pid, argv: @argv, elapsed_seconds: clock - @started)
@result = CommandResult.new(**@buffers.transform_values(&:bytes), status: @status,
pid: @pid, argv: @argv, elapsed_seconds: clock - @started)
return
end
phase = observed? ? :drain : :read
Expand Down
Loading
Loading