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 CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ Notable changes to `libtmux`.
callers to open a fresh watch on the live observation. (#148)
- `Observation:watch_pane_lines` reads complete lines with an optional reply
prefix and a single deadline across intervening output.
- Await `Server:run_program(argv)` for a program’s exit code or signal, terminal
output and final tmux screen. Await `Server:start_program(argv)` to send text
or keys to its pane before waiting for it to finish. (#107)

## 0.1.1-1 (2026-11-01)

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,9 @@ editor build

## Create sessions, windows and panes

The [terminal program guide](docs/programs.md) shows how to run a job, send
input and collect its exit status and final screen after its pane closes.

### [`Session:new_window`][ref-session-new-window]: add a window

[`Session:new_window`][ref-session-new-window] adds a window to a session,
Expand Down
10 changes: 10 additions & 0 deletions capabilities.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
"port": "lua",
"floor": {"minimum": "3.3a"},
"capabilities": [
{
"id": "owned-program",
"name": "Owned terminal programs",
"summary": "Start a terminal program and collect its output, status and cleanup.",
"since": "3.3a",
"handling": "refuse",
"error": "libtmux.Error",
"apis": ["libtmux.Server:start_program", "libtmux.Server:run_program"],
"commands": [{"command": "new-session", "flags": ["-e", "-F", "-P"]}, {"command": "if-shell", "flags": ["-F", "-t"]}, {"command": "pipe-pane", "flags": ["-O", "-t"]}]
},
{
"id": "control-mode",
"name": "Control mode observation",
Expand Down
5 changes: 3 additions & 2 deletions docs/creation.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ from tmux's returned IDs. Its `created` list names what the call created:
- A window: the window, pane and link.
- A split: the pane only.

The other handles describe the containing context. A created pane proves
neither that its program started nor that it succeeded.
The other handles describe the containing context. Use
[`Server:run_program`](programs.md) to obtain the exit status and final screen
of the application you launched.

## Commands and literal values

Expand Down
139 changes: 139 additions & 0 deletions docs/programs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Run a terminal program

Use `Server:run_program(argv, options)` when you want the application's exit
status and final terminal output. Use `Server:start_program(argv, options)`
when you also need to send input or sample the screen while the program runs.
Both calls return Requests. The start Request resolves to a Program after
the executable launches in its own tmux session.

The [complete Program example](../examples/api/owned_program.lua) reads a
calculator's answer and exit status, stops a second interactive program,
and checks cleanup after a run deadline.

Install the source build of the library and `luv` using the
[API examples setup](../examples/api/README.md). The published `0.1.1-1` rock
predates this API.

```console
$ lua examples/api/owned_program.lua
```

The same example uses the
[`libtmux.runtime.nvim` adapter](runtime.md) in Neovim.

```console
$ nvim --headless -u NONE -i NONE -l examples/api/owned_program.lua
```

The example waits for the application's reply, then awaits `program:stop()`
for its signal, terminal output and cleanup result. It prints
`received: [draft] (signal 15, pane closed)` and reads the saved final screen
with `program:screen()`.

## Launch and input

- Pass a literal argv array. The executable may be a single item, and empty
later arguments and shell metacharacters are preserved. To interpret
shell source, pass that shell and its source explicitly as argv.
- `cwd` must be an absolute directory. `environment` adds literal strings
to the launched application's inherited terminal environment.
The launcher receives its own configuration. The internal names
`LIBTMUX_LUA_PROGRAM_TOKEN` and `LIBTMUX_LUA_PROGRAM_CPATH` are reserved.
- `width` and `height` default to 80 by 24. The requested area may contain
up to 1,048,576 terminal cells. The argv and environment limits are the
same as for [session creation](creation.md#errors-and-limits).
- `startup_timeout` defaults to 1,000 ms. With `start_program`, `timeout`
also selects the startup limit when `startup_timeout` is omitted. With
`run_program`, `timeout` bounds the entire run, including startup.
- `program:send_text(text)` sends literal text and
`program:send_keys({ "Enter" })` sends named keys. Both take optional timing
as the last argument. `program:reference()` copies the three tmux IDs and
exposes the launch's `cleanup_scope` while it runs.

The launch is pinned to the connected tmux generation. The
[`owned-program` capability](../capabilities.json) describes the minimum
daemon release and native commands. Below tmux 3.3a or with an unsupported
daemon version, connection or launch refuses before the application starts.

The tmux server and Lua host must run as the same user and see the same
installation and local socket directory. Standalone Lua launches the
supervisor with its own Lua executable and `luv`. Neovim launches a dedicated
headless Neovim using its embedded libuv. If needed, pass `lua` with an
absolute path to a standalone Lua executable that can load `luv`.
The supervisor path stays tied to the loaded library. Standalone Lua
resolves relative native-module templates from the runtime's starting
directory, including when the application uses a different `cwd`.

## Wait, stop and recover

`program:wait({ timeout = 25 })` can return `deadline_exceeded` with the
program still running. Cancelling that Request detaches that wait. Another
wait can collect the result. Use `deadline` for an absolute monotonic time
in milliseconds. When both bounds are present, the earlier one applies.
Requests follow the [runtime's settlement and retirement
rules](runtime.md#cancellation-and-limits).

`program:stop()` requests termination and returns the same ProgramResult as
`wait()`. Its default wait is 3,200 ms. Cancelling an owning `run_program`
Request also requests termination. The Request can settle with
`cancelled` while cleanup proceeds. After it retires, the error can carry
`partial.result`, `cleanup_error` and a recoverable `program` handle or
`program_name`. A run that reaches its timeout joins the bounded cleanup
before returning `deadline_exceeded`.

If the runtime closes while `start_program` or `run_program` is starting
an application, check the Request's error after it retires.
`cleanup_error` and `program_name` identify a tmux session whose removal
the runtime could not confirm. The session may already have closed.

Closing a Server handle stops its Programs. The runtime also owns the
native supervisor connection and closes it at scope exit. The supervisor
then terminates and reaps the directly spawned application. A verified
Linux subreaper with pidfds also terminates and reaps adopted descendants.
`cleanup.scope` reports `direct` or `tree` for the launch. Descendants on a
`direct` host can outlive the application. Loss of the supervisor can leave
status or process cleanup unconfirmed.

Pass `require_tree = true` to either launch call when you depend on orphan
cleanup. The application starts only after the supervisor verifies that
scope. Otherwise the call returns `unsupported` and closes any temporary
pane it used for qualification.

On Linux, a PUC Lua application can request tree cleanup by passing
`{ lua = "/path/to/luajit", require_tree = true }`. Use the absolute path to
a LuaJIT executable that can load its own `luv`.

`cleanup.pane_closed` confirms that the original pane disappeared from the
pinned daemon. On external replacement, input is refused and the
replacement pane stays available. A cleanup failure can include a
`program_name` to inspect on the same daemon. Confirm the ownership of a
remaining session before removing it.

## Read the status and output

The result's `kind` is `exit`, `signal` or `unknown`. An exit has
`exit_code`, a signal has a numeric `signal`, and an unconfirmed status can
carry an `error`. A nonzero exit code still returns a ProgramResult.

If someone closes the program's session or stops its server while it is
running, a confirmed status can arrive with `output.complete = false` and
a `screen_error`. When the server stops, `cleanup.pane_closed` can be
`false` with `cleanup_error.code = "stale_generation"`. The saved exit
status or signal is still valid. The cleanup error describes pane
verification against the old daemon.

- `output.bytes` is the retained PTY byte prefix from `tmux_pipe_pane`.
It preserves CR, NUL and escape sequences. It includes merged stdout,
stderr and terminal input echo. `output.complete` requires the supervisor's
end marker and zero dropped bytes. `dropped_bytes` counts discarded bytes
received before the marker. An interrupted stream can report `output.error`
with no count for the bytes it never received.
- `screen.bytes` is the rendered viewport from `tmux_capture_pane` with
`rows` and `columns`. It excludes scrollback and uses newline-separated
visible rows. `screen.final` records capture after the end marker.
`program:screen()` uses that saved sample after completion. Capture failure
is reported in `screen_error`.
- Both representations use the `max_output_bytes` cap, which defaults to
1 MiB and accepts integers through 16 MiB. Each has a `truncated` flag.
A byte prefix can end in the middle of UTF-8 text. Runtime byte limits
also apply to buffered output and delivery.
1 change: 1 addition & 0 deletions examples/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ to select a different build.
| [read_pane_line.lua](read_pane_line.lua) | Wait for a complete `result=` line (tmux 3.7 or newer) | `result=42` |
| [send_keys.lua](send_keys.lua) | Send text and press Enter | `lua input ready` |
| [capture.lua](capture.lua) | Read a completed command's output | `lua capture ready` |
| [owned_program.lua](owned_program.lua) | Read an exit status, stop an interactive program, and inspect its final screen | `answer=42 (exit 7)`, `received: [draft] (signal 15, pane closed)`, `deadline_exceeded, pane closed` |
| [wait_for_text.lua](wait_for_text.lua) | Wait for text on the visible screen | `lua wait ready` |
| [watch_pane.lua](watch_pane.lua) | Send a sum to `awk` and read its reply over control mode (tmux 3.7 or newer) | `19 + 23 = 42` |
| [vote_counter.lua](vote_counter.lua) | Send votes and read each tally over control mode (tmux 3.7 or newer) | Three tallies ending at `yes=2 no=1` |
Expand Down
16 changes: 16 additions & 0 deletions examples/api/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,22 @@
"description": "Capture a completed command's output from a pane.",
"stdout": "lua capture ready\n"
},
{
"id": "owned_program",
"symbols": [
"libtmux.Server:start_program",
"libtmux.Server:run_program",
"libtmux.Program:send_text",
"libtmux.Program:send_keys",
"libtmux.Program:wait",
"libtmux.Program:reference",
"libtmux.Program:stop",
"libtmux.Program:screen"
],
"file": "examples/api/owned_program.lua",
"description": "Read a calculator result, stop an interactive program, and inspect its final terminal output.",
"stdout": "answer=42 (exit 7)\nreceived: [draft] (signal 15, pane closed)\ndeadline_exceeded, pane closed\n"
},
{
"id": "wait_for_text",
"symbols": [
Expand Down
94 changes: 94 additions & 0 deletions examples/api/owned_program.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
local adapter = require("libtmux.runtime.luv")

local function must(value, err)
if err then
error(tostring(err), 0)
end
return assert(value)
end

local binary = os.getenv("TMUX_BIN")

---@param server libtmux.Server
local function run_programs(server)
local batch_argv = { "/bin/sh", "-c", [[printf 'batch\n'; exit 3]] }
local batch = must(server:run_program(batch_argv):await())
assert(batch.exit_code == 3 and batch.output.bytes == "batch\r\n")

local program = must(server
:start_program({
"/usr/bin/awk",
[[NF == 3 && $2 == "+" { printf "answer=%d\n", $1 + $3; exit 7 }]],
})
:await())
local ready, expired = program:wait({ timeout = 0 }):await()
assert(not ready and expired and expired.code == "deadline_exceeded")
must(program:send_text("19 + 23"):await())
must(program:send_keys({ "Enter" }):await())
local result = must(program:wait({ timeout = 2000 }):await())
assert(result.kind == "exit" and result.output.complete)
local answer = assert(result.output.bytes:match("(answer=%d+)\r\n"))
local final = must(result.screen, result.screen_error)
assert(final.bytes:find(answer, 1, true) and result.cleanup.pane_closed)
io.write(("%s (exit %d)\n"):format(answer, result.exit_code))

local draft = must(server
:start_program({
"/usr/bin/awk",
[[{ print "received: [" $0 "]"; fflush() }]],
})
:await())
must(draft:send_text("draft"):await())
must(draft:send_keys({ "Enter" }):await())

local snapshot = must(server:snapshot():await())
local pane_id = draft:reference().pane_id
local row = must(snapshot.panes:where({ id = pane_id }):one())
local pane = must(server:handle(snapshot, row))
local reply = "received: [draft]"
must(pane:wait_for_text(reply, { timeout = 2000 }):await())

local cancelled = must(draft:stop():await())
assert(cancelled.kind == "signal" and cancelled.signal == 15)
local output = cancelled.output
assert(output.complete and output.bytes == "draft\r\n" .. reply .. "\r\n")
local screen = must(draft:screen():await())
assert(screen.final and screen.bytes:find(reply .. "\n", 1, true))
assert(not cancelled.cleanup_error, tostring(cancelled.cleanup_error))
assert(cancelled.cleanup.pane_closed)
io.write(("%s (signal %d, pane closed)\n"):format(reply, cancelled.signal))

local bounded = server:run_program({ "/bin/cat" }, { timeout = 1000 })
local idle, timeout = bounded:await()
assert(not idle and timeout and timeout.code == "deadline_exceeded")
local stopped = assert(timeout.partial.result)
assert(stopped.kind == "signal" and stopped.cleanup.pane_closed)
io.write("deadline_exceeded, pane closed\n")
return true
end

---@param runtime libtmux.Runtime
local function run(runtime)
return runtime:with_server({ binary = binary }, run_programs):await()
end

local host = rawget(_G, "vim")
if not host then
must(adapter.run(run))
return
end

local done, value, failure
local nvim = require("libtmux.runtime.nvim")
local runtime, start_error = nvim.start(run, function(result, err)
done, value, failure = true, result, err
end)
assert(runtime, tostring(start_error))
local function finished()
return done == true
end
if not host.wait(15000, finished) then
runtime:close("example timed out")
assert(host.wait(6000, finished), "example cleanup timed out")
end
must(value, failure)
Loading