libtmux 0.1.0.alpha.2 → 0.1.0.alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -11,116 +11,829 @@
11
11
 
12
12
  # libtmux
13
13
 
14
- Ruby tmux orchestration core. `Server.open` borrows an
15
- existing explicit endpoint. Closing it retires owned clients and preserves
16
- the daemon; `kill` explicitly terminates the daemon. `Server.start` creates a
17
- private owned foreground daemon whose lifetime ends with its server handle.
18
- Owned startup uses Linux and Darwin readiness backends. The
19
- [compatibility workflow](https://github.com/libtmux/libtmux-ruby/actions/workflows/compatibility.yml)
20
- retains exact per-revision platform and version results.
14
+ Drive tmux from Ruby: [sessions][session], [windows][window] and [panes][pane]
15
+ as handles, [snapshots][snapshot] you filter in plain Ruby, and
16
+ [control connections][controlconnection] that report what tmux does.
17
+
18
+ [API reference](https://libtmux.org/en/ruby/latest/reference/) ·
19
+ [Guides](https://libtmux.org/en/ruby/latest/guides/) ·
20
+ [RubyGems](https://rubygems.org/gems/libtmux)
21
21
 
22
22
  </div>
23
23
 
24
- Requires tmux 3.3a or newer; unpatched 3.3 is below the minimum. A server
25
- handle checks the connected daemon's release before any command is
26
- dispatched, and refuses an older daemon even when its client is newer.
27
-
28
- Install the alpha with `gem install libtmux --pre`, then require `libtmux`.
29
- Imports do not
30
- start tmux, a scheduler or an MCP server. See the repository's contribution
31
- guide for local build and verification commands.
32
-
33
- Handles carry immutable refs bound to one open server binding. IDs and refs
34
- are local readers; `list_*`, `snapshot` and command methods perform explicit
35
- I/O. Global windows represent unique entities. `WindowLink` retains a session,
36
- index and window ID so repeated links stay distinct.
37
-
38
- Link selection, unlinking, movement, swapping and display check the complete
39
- link identity in the same tmux queue turn as their operation. Configured
40
- command aliases are avoided using unshadowed builtin spellings. Hook waits
41
- before dispatch cannot turn a stale link into its replacement. Concurrent
42
- rewriting of command aliases is outside this guarantee; applications must
43
- coordinate configuration changes.
44
-
45
- Typed arguments preserve literal semicolons and distinguish pane text from
46
- key names. Pane commands take executable argument arrays. Hook commands,
47
- display formats, pipe shell commands and `source_file` configuration are
48
- explicit executable inputs. `Server.run` remains the raw tmux escape hatch,
49
- including daemon aliases, separators and format semantics.
50
-
51
- Creation accepts `cwd:` and a String-to-String `environment:` map. Directories
52
- resolve from the Ruby caller and are checked before dispatch; concurrent
53
- filesystem changes can still trigger tmux's directory fallback. Creation
54
- returns tmux-assigned IDs after dispatch, without claiming program readiness
55
- or a successful program exit. `new_session(window_name:)` names the initial
56
- window; its index can be moved explicitly after creation. `new_window(index:)`
57
- refuses an occupied slot. `Pane#split` targets that exact pane, with `size:` as
58
- cells or a percentage string. Windows and splits retain focus unless
59
- `focus: true` is requested.
60
-
61
- Typed operations accept `timeout:` and `cancel:`. Composed link and copy operations
62
- share one deadline across their preflights and final dispatch. Copy-mode
63
- exit uses `cancel_mode: true`; `cancel:` accepts `LibTmux::Cancellation.new`.
64
- Call the token's `cancel` from another thread to wake a blocked request, join
65
- its caller, then `close` the token. See the [plain-Ruby cancellation recipe](../../examples/cancel.rb)
66
- and [ownership contract](../../docs/ownership-errors.md).
67
-
68
- `Options` retains raw bytes, inheritance and sparse array indexes;
69
- `OptionValue#as` requests a strict conversion. Hook values remain tmux command
70
- strings. The stable tmux option listing uses its escaped representation,
71
- including octal bytes; it does not split raw values on line breaks. Option
72
- names containing whitespace are currently rejected. Inherited hook listing
73
- is not implemented and raises explicitly.
74
-
75
- Indexed `get` acquires the array and selects locally, so a missing index raises
76
- `NoMatchError` while a present empty value remains present. Reading an array
77
- without an index raises `MultipleMatchesError` when it has several entries.
78
- Append follows tmux's lowest-free-index rule; indexed hooks execute in index
79
- order. Empty arrays remain distinct from empty String values.
80
-
81
- Binary buffers and command results preserve trailing newlines. Capture can
82
- join wrapped lines, include attribute escapes, escape nonprintable bytes,
83
- preserve trailing spaces and trim unused trailing cells. `mode_screen: true`
84
- reads the mode's backing screen (the copy-mode snapshot, without its UI),
85
- `alternate: true` reads tmux's saved screen and raises when absent (while an
86
- application occupies the alternate screen, this is the saved main screen),
87
- and `pending: true` reads an incomplete escape sequence. These three selectors
88
- are mutually exclusive. Mode-screen and trailing-cell flags are checked
89
- against advertised command usage; unsupported requests raise explicitly.
90
- Copy-mode flags are checked against the connected daemon's advertised command
91
- usage. Client discovery returns observations. `Server#attach` uses an explicit
92
- caller-owned TTY and terminal type, waits for its owned client to exit, and
93
- restores the terminal mode. `Server#switch_client(client:, session:)` switches
94
- an explicit current native client selector to an exact bound session, keeping
95
- the session environment. A missing selector fails without fallback. This
96
- operation does not turn a client observation into an incarnation-safe
97
- reference; a reconnect matching the selector is eligible at dispatch.
98
-
99
- Control connections expose bounded event subscriptions and raw guarded replies.
100
- `pause_output(pane_id:)` and `resume_output(pane_id:)` return `GuardedReply`;
101
- they do not establish that an action took effect. Their gap events identify
102
- `:pause_requested` or `:resume_requested` when no outside-block native notice
103
- was observed, including cancellation after possible dispatch. Native notices
104
- use `:pause` and `:resume`. Loss counts are unknown (`dropped_bytes: nil`);
105
- resume does not replay skipped output. Guarded notification-looking text stays
106
- in its reply body.
107
-
108
- Close the old control connection, then explicitly call
109
- `server.open_control(session: ref, reconnect: old_connection)` to reconnect
110
- within the same binding and session. The replacement has a new `generation`
111
- and retains `previous_generation`. Every new subscription begins with a
112
- `:reconnect` gap containing both generations and an unknown loss count. Old
113
- subscriptions stay closed, and requests are never replayed. Event sequences
114
- describe one connection's observations, not durable pane history.
115
-
116
- Typed command coverage includes hierarchy creation/listing; rename, split,
117
- resize, swap, join, break, respawn, and layout operations; link operations;
118
- options/hooks/environment, capture/send/paste/pipe/buffers, copy commands,
119
- display/source-file/wait-for. It does not establish complete flag parity or
120
- every compatibility cell; consult the workflow results. RBS validation checks declarations;
121
- installed signature consumers check selected real arguments, blocks and
122
- return values. [Executable recipes](../../docs/recipes.md) run
123
- against installed artifacts; the documentation gate renders YARD and guides
124
- and checks local destinations and fragments. The [public method inventory](../../docs/reference/api.md)
125
- links exported methods to source and behavioral contracts. These consumer
126
- checks do not establish whole-program static typing.
24
+ Part of [libtmux for Ruby](https://github.com/libtmux/libtmux-ruby#readme).
25
+ This gem is the core; the [packages below](#packages) build on it.
26
+
27
+ [Create][server-new_session] and [split][pane-split] windows,
28
+ [read][server-snapshot] and [filter][selection-where] what a server holds, and
29
+ [type into a pane][pane-send_text] and capture what it shows.
30
+
31
+ It suits scripts, tests that need a real tmux, and tools that drive a terminal
32
+ program. [Cancel][cancellation-cancel] a request that is waiting, and
33
+ [follow events][controlconnection-subscribe] as tmux emits them.
34
+
35
+ **Contents** — [Quick start](#quick-start) ·
36
+ [Find things](#find-sessions-windows-and-panes) ·
37
+ [Create](#create-sessions-windows-and-panes) ·
38
+ [Type and read](#type-into-a-pane-and-read-it-back) ·
39
+ [Your own server](#use-the-tmux-server-you-already-run) ·
40
+ [Cancel](#wait-time-out-and-cancel) ·
41
+ [Link windows](#link-a-window-into-several-sessions) ·
42
+ [Options](#read-and-set-options-and-hooks) ·
43
+ [Watch tmux](#watch-tmux-change) ·
44
+ [Groups](#run-several-commands-in-order) ·
45
+ [Packages](#packages) · [Leaves out](#what-it-leaves-out) ·
46
+ [Support](#support-and-status) · [Documentation](#documentation)
47
+
48
+ ## Quick start
49
+
50
+ Install the alpha. It needs Ruby 3.3 or newer and tmux 3.3a or newer on
51
+ `PATH`:
52
+
53
+ ```console
54
+ $ gem install libtmux --pre
55
+ ```
56
+
57
+ This program creates a session, adds a window, splits it, and prints each
58
+ window with its panes. [`Server.start`][server-start] closes its private tmux
59
+ server when the block exits, and the snapshot stays readable afterward:
60
+
61
+ <!-- example: quickstart/main -->
62
+ ```ruby
63
+ require "libtmux"
64
+
65
+ snapshot = LibTmux::Server.start do |server|
66
+ session = server.new_session(name: "work", window_name: "main", command: ["/bin/cat"])
67
+ window = session.new_window(name: "logs", command: ["/bin/cat"])
68
+ window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"])
69
+
70
+ server.snapshot
71
+ end
72
+
73
+ snapshot.windows.each do |window|
74
+ puts "#{window.name}: #{window.panes.map(&:id).join(', ')}"
75
+ end
76
+ ```
77
+ <!-- /example -->
78
+
79
+ It prints:
80
+
81
+ ```text
82
+ main: %0
83
+ logs: %1, %2
84
+ ```
85
+
86
+ Requiring the gem starts no tmux process, scheduler or MCP server.
87
+ [`Server.start`][server-start] gives its tmux server a socket and an empty
88
+ configuration of its own, so it never touches a tmux you already use.
89
+
90
+ ## Find sessions, windows, and panes
91
+
92
+ ### [`Server#list_sessions`][server-list_sessions]: what tmux has now
93
+
94
+ One call asks tmux for every session and returns frozen handles in numeric ID
95
+ order. [`list_windows`][server-list_windows] and
96
+ [`list_panes`][server-list_panes] are its siblings, and
97
+ [`Session#list_windows`][session-list_windows] and
98
+ [`Window#list_panes`][window-list_panes] narrow them:
99
+
100
+ <!-- example: api_list_sessions/main -->
101
+ ```ruby
102
+ require "libtmux"
103
+
104
+ LibTmux::Server.start do |server|
105
+ server.new_session(name: "work", command: ["/bin/cat"])
106
+ server.new_session(name: "logs", command: ["/bin/cat"])
107
+ sessions = server.list_sessions
108
+ puts "sessions: #{sessions.map(&:id).sort.join(', ')}"
109
+ end
110
+ ```
111
+ <!-- /example -->
112
+
113
+ It runs on a private server and prints:
114
+
115
+ ```text
116
+ sessions: $0, $1
117
+ ```
118
+
119
+ An empty array means tmux answered with nothing to list. A listing that fails
120
+ raises [`CommandError`][commanderror].
121
+
122
+ ### [`Server#snapshot`][server-snapshot]: one read, many queries
123
+
124
+ Read the server once, then filter that read with
125
+ [`where`][selection-where], [`select`][selection-select],
126
+ [`one`][selection-one] and [`one_or_nil`][selection-one_or_nil]. These queries
127
+ make no tmux calls. Continue with the snapshot from the quick start:
128
+
129
+ <!-- example: quickstart/queries -->
130
+ ```ruby
131
+ panes = snapshot.panes
132
+ active_ids = panes.where(active: true).map(&:id)
133
+ wide_panes = panes.select { |pane| pane.width >= 40 }
134
+ panes_by_window = panes.group_by { |pane| pane.window.name }
135
+
136
+ logs = snapshot.windows.one(name: "logs")
137
+ missing = snapshot.windows.one_or_nil(name: "missing")
138
+ ```
139
+ <!-- /example -->
140
+
141
+ `one` raises [`NoMatchError`][nomatcherror] or
142
+ [`MultipleMatchesError`][multiplematcheserror] unless exactly one record
143
+ matches. `one_or_nil` returns `nil` for no match and still rejects duplicates.
144
+
145
+ A selection keeps the membership it captured, so call `server.snapshot` again
146
+ to read later changes. The [field catalog](../../docs/reference/fields.md)
147
+ lists every query field and wire name.
148
+
149
+ ### [`Server#search_panes`][server-search_panes]: the matching panes in one call
150
+
151
+ `search_panes` captures the server and answers a selection of the panes whose
152
+ fields match `where:`. [`explain_panes`][server-explain_panes] shows the plan
153
+ without running tmux. This program also uses the snapshot queries above:
154
+
155
+ <!-- example: api_query/main -->
156
+ ```ruby
157
+ require "libtmux"
158
+
159
+ LibTmux::Server.start do |server|
160
+ work = server.new_session(name: "work", command: ["/bin/cat"], receipt: true)
161
+ server.new_session(name: "logs", command: ["/bin/cat"])
162
+ snapshot = server.snapshot
163
+ session = snapshot.sessions.where(name: "work").one
164
+ puts "matching session: #{session.name}"
165
+ missing = snapshot.sessions.one_or_nil(name: "missing")
166
+ puts "missing session: #{missing.nil?}"
167
+ panes = server.search_panes(where: {id: work.pane.id})
168
+ puts "matching pane: #{panes.one.id}"
169
+ end
170
+ ```
171
+ <!-- /example -->
172
+
173
+ It prints:
174
+
175
+ ```text
176
+ matching session: work
177
+ missing session: true
178
+ matching pane: %0
179
+ ```
180
+
181
+ ## Create sessions, windows, and panes
182
+
183
+ ### [`Server#new_session`][server-new_session]: a session and its first window
184
+
185
+ `new_session` starts a detached session that runs `command:`, an argv array.
186
+ Ask for a receipt to read the IDs tmux assigned to the session, window and
187
+ pane:
188
+
189
+ <!-- example: api_new_session/main -->
190
+ ```ruby
191
+ require "libtmux"
192
+
193
+ LibTmux::Server.start do |server|
194
+ created = server.new_session(
195
+ name: "work", window_name: "main", command: ["/bin/cat"], receipt: true
196
+ )
197
+ puts "session: #{created.entity.id}"
198
+ puts "window: #{created.window.id}"
199
+ puts "pane: #{created.pane.id}"
200
+ end
201
+ ```
202
+ <!-- /example -->
203
+
204
+ It prints:
205
+
206
+ ```text
207
+ session: $0
208
+ window: @0
209
+ pane: %0
210
+ ```
211
+
212
+ Creation returns once tmux has assigned the IDs. It says nothing about whether
213
+ the program started or exited cleanly.
214
+
215
+ ### [`Session#new_window`][session-new_window]: add a window
216
+
217
+ [`Pane#split`][pane-split] and [`Window#split`][window-split] add panes the
218
+ same way. A new window takes a `name:` and the same `command:` as a session:
219
+
220
+ <!-- example: api_new_window/main -->
221
+ ```ruby
222
+ require "libtmux"
223
+
224
+ LibTmux::Server.start do |server|
225
+ session = server.new_session(name: "work", command: ["/bin/cat"])
226
+ window = session.new_window(name: "logs", command: ["/bin/cat"])
227
+ puts "window: #{window.snapshot.name}"
228
+ puts "session windows: #{session.list_windows.length}"
229
+ end
230
+ ```
231
+ <!-- /example -->
232
+
233
+ It prints:
234
+
235
+ ```text
236
+ window: logs
237
+ session windows: 2
238
+ ```
239
+
240
+ - `cwd:` names a directory on the machine running Ruby, and is checked before
241
+ the command is sent.
242
+ - `environment:` is a String-to-String map of literal values.
243
+ - `new_window(index:)` refuses a slot that is taken.
244
+ - [`Pane#split`][pane-split] targets that exact pane, and `size:` is a cell
245
+ count or a percentage string such as `"40%"`.
246
+ - New windows and splits keep focus unless you pass `focus: true`.
247
+
248
+ The full contract is in [Creation][behavior-creation].
249
+
250
+ ## Type into a pane and read it back
251
+
252
+ ### [`Pane#send_text`][pane-send_text]: type, then read what the pane showed
253
+
254
+ `send_text` types literal text, and [`send_keys`][pane-send_keys] sends tmux key
255
+ names such as `Enter`. [`Pane#capture`][pane-capture] reads the screen.
256
+
257
+ To wait for output, poll the pane until the line appears. A
258
+ [control connection][server-open_control] reports it as an event instead, but
259
+ needs tmux 3.7 or newer:
260
+
261
+ <!-- example: api_capture/main -->
262
+ ```ruby
263
+ require "libtmux"
264
+
265
+ LibTmux::Server.start do |server|
266
+ created = server.new_session(
267
+ name: "capture", command: ["/bin/sh"],
268
+ environment: {"ENV" => "/dev/null"}, receipt: true
269
+ )
270
+ pane = created.pane
271
+ pane.send_text("printf '\\nlibtmux capture ready\\n'")
272
+ pane.send_keys("Enter")
273
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5
274
+ captured = pane.capture.stdout.lines(chomp: true)
275
+ until captured.include?("libtmux capture ready")
276
+ raise "Output did not arrive within five seconds" if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
277
+ sleep 0.05
278
+ captured = pane.capture.stdout.lines(chomp: true)
279
+ end
280
+ raise "Expected output is absent from the pane" unless captured.include?("libtmux capture ready")
281
+ puts "libtmux capture ready"
282
+ end
283
+ ```
284
+ <!-- /example -->
285
+
286
+ It prints:
287
+
288
+ ```text
289
+ libtmux capture ready
290
+ ```
291
+
292
+ - Sending input does not show that the shell finished the command.
293
+ - `capture` returns the visible screen. `start:` and `finish:` choose a range,
294
+ and `join:` joins wrapped lines.
295
+ - `escapes:`, `escape_bytes:`, `preserve_trailing:` and `trim_trailing:` change
296
+ the bytes it returns.
297
+ - `mode_screen:`, `alternate:` and `pending:` read a copy-mode screen, the saved
298
+ screen and an unfinished escape sequence. Pass at most one.
299
+ - Binary buffers keep their trailing newlines. See
300
+ [`write_buffer`][server-write_buffer] and
301
+ [`read_buffer`][server-read_buffer] in the
302
+ [layout and bytes recipe](../../docs/recipes.md#layout-and-bytes).
303
+
304
+ The full contract is in [Pane input and capture][behavior-capture].
305
+
306
+ ## Use the tmux server you already run
307
+
308
+ ### [`Server.new`][server-new]: borrow a daemon
309
+
310
+ [`Server.open`][server-open] and [`Server.new`][server-new] bind an endpoint
311
+ that already exists. Closing the binding retires its clients and leaves the
312
+ daemon running; [`Server#kill`][server-kill] stops it.
313
+
314
+ The outer [`Server.start`][server-start] block here only supplies a daemon to
315
+ borrow:
316
+
317
+ <!-- example: api_server/main -->
318
+ ```ruby
319
+ require "libtmux"
320
+
321
+ LibTmux::Server.start do |owner|
322
+ owner.new_session(name: "work", command: ["/bin/cat"])
323
+ server = LibTmux::Server.new(endpoint: owner.endpoint)
324
+ begin
325
+ puts "connected sessions: #{server.list_sessions.length}"
326
+ ensure
327
+ server.close
328
+ end
329
+ puts "sessions after client close: #{owner.list_sessions.length}"
330
+ end
331
+ ```
332
+ <!-- /example -->
333
+
334
+ It prints:
335
+
336
+ ```text
337
+ connected sessions: 1
338
+ sessions after client close: 1
339
+ ```
340
+
341
+ - [`Endpoint.new`][endpoint-new] takes an explicit socket path or socket name.
342
+ [`Endpoint.from_env`][endpoint-from_env] is the opt-in for `$TMUX`.
343
+ - A binding keeps a private link to the socket it bound, so commands never
344
+ reach a different daemon that later takes the same path.
345
+ - A ref is valid on the server that issued it. Another server raises
346
+ [`TargetNotFoundError`][targetnotfounderror].
347
+
348
+ See [ownership and errors](../../docs/ownership-errors.md).
349
+
350
+ ## Wait, time out, and cancel
351
+
352
+ ### [`Cancellation.new`][cancellation-new]: wake a request that is waiting
353
+
354
+ Typed operations take `timeout:` and `cancel:`. Pass a
355
+ [`Cancellation`][cancellation] token as `cancel:`, call
356
+ [`cancel`][cancellation-cancel] from another thread to wake the request, join
357
+ its callers, then [`close`][cancellation-close] the token:
358
+
359
+ <!-- example: api_cancellation/main -->
360
+ ```ruby
361
+ require "libtmux"
362
+
363
+ LibTmux::Server.start do |server|
364
+ server.new_session(name: "work", command: ["/bin/cat"])
365
+ cancellation = LibTmux::Cancellation.new
366
+ waiting = Thread.new do
367
+ server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], timeout: 5, cancel: cancellation)
368
+ rescue LibTmux::Cancelled => error
369
+ error
370
+ end
371
+ server.wait_for("ready", timeout: 5)
372
+ cancellation.cancel
373
+ failure = waiting.value
374
+ puts "request: #{failure.class}"
375
+ puts "delivery: #{failure.delivery}"
376
+ cancellation.close
377
+ end
378
+ ```
379
+ <!-- /example -->
380
+
381
+ It prints:
382
+
383
+ ```text
384
+ request: LibTmux::Cancelled
385
+ delivery: possibly_sent
386
+ ```
387
+
388
+ [`Cancelled`][cancelled] reports `delivery` as `:not_sent` or `:possibly_sent`.
389
+ Cancelling does not undo what tmux already queued.
390
+
391
+ The [plain-Ruby recipe](../../examples/cancel.rb) also checks that the client
392
+ was reaped. The contracts are in
393
+ [Cancellation tokens][behavior-cancellation] and
394
+ [ownership and errors](../../docs/ownership-errors.md).
395
+
396
+ ## Link a window into several sessions
397
+
398
+ ### [`Session#link_window`][session-link_window]: one window at several indexes
399
+
400
+ A [`WindowLink`][windowlink] keeps a session, an index and a window ID
401
+ together, so a window linked twice stays one window. `link_window` needs an
402
+ explicit `index:`:
403
+
404
+ <!-- example: api_link_window/main -->
405
+ ```ruby
406
+ require "libtmux"
407
+
408
+ LibTmux::Server.start do |server|
409
+ session = server.new_session(name: "links", command: ["/bin/cat"])
410
+ window = session.list_windows.fetch(0)
411
+ session.link_window(window.ref, index: 4)
412
+ session.link_window(window.ref, index: 9)
413
+ links = session.list_window_links
414
+ puts "indexes: #{links.map(&:index).join(', ')}"
415
+ puts "windows: #{links.map { |link| link.window.id }.uniq.join(', ')}"
416
+ end
417
+ ```
418
+ <!-- /example -->
419
+
420
+ It prints:
421
+
422
+ ```text
423
+ indexes: 0, 4, 9
424
+ windows: @0
425
+ ```
426
+
427
+ - Select, unlink, move, swap and display check the whole link identity in the
428
+ same tmux queue turn as the operation.
429
+ - A hook that waits before dispatch cannot turn a stale link into its
430
+ replacement.
431
+ - Rewriting command aliases during an operation is outside that guarantee, so
432
+ coordinate configuration changes.
433
+
434
+ The contract is in [Window links][behavior-window-links], and the
435
+ [linked-windows recipe](../../docs/recipes.md#one-window-at-three-indexes)
436
+ runs this at three indexes.
437
+
438
+ ## Read and set options and hooks
439
+
440
+ ### [`Session#options`][session-options]: a value with its inheritance
441
+
442
+ [`Options#set`][options-set] writes an option at the scope of its accessor.
443
+ [`Options#get`][options-get] reads it back as an
444
+ [`OptionValue`][optionvalue], and [`as`][optionvalue-as] converts it strictly.
445
+ [`Hooks#set`][hooks-set] stores a tmux command:
446
+
447
+ <!-- example: api_options/main -->
448
+ ```ruby
449
+ require "libtmux"
450
+
451
+ LibTmux::Server.start do |server|
452
+ session = server.new_session(name: "work", command: ["/bin/cat"])
453
+ session.options.set("history-limit", 5000)
454
+ limit = session.options.get("history-limit")
455
+ puts "history-limit: #{limit.as(:integer)}"
456
+ puts "inherited: #{limit.inherited?}"
457
+ session.hooks.set("after-new-window", command: "display-message created")
458
+ puts "hook: #{session.hooks.get('after-new-window').as(:string)}"
459
+ end
460
+ ```
461
+ <!-- /example -->
462
+
463
+ It prints:
464
+
465
+ ```text
466
+ history-limit: 5000
467
+ inherited: false
468
+ hook: display-message created
469
+ ```
470
+
471
+ - An [`OptionValue`][optionvalue] keeps the raw bytes, whether the value is
472
+ inherited, and the array index. `as` takes `:bytes`, `:string`, `:integer` or
473
+ `:boolean`.
474
+ - A missing array index raises [`NoMatchError`][nomatcherror], and a present
475
+ empty value stays present.
476
+ - Reading an array without an index raises
477
+ [`MultipleMatchesError`][multiplematcheserror] when it has several entries.
478
+ - Hook values stay tmux command strings, and indexed hooks run in index order.
479
+
480
+ The contracts are in [Options and hooks][behavior-options] and
481
+ [Option values][behavior-option-values].
482
+
483
+ ## Watch tmux change
484
+
485
+ ### [`Server#open_control`][server-open_control]: events as they happen
486
+
487
+ A [`ControlConnection`][controlconnection] runs a command with
488
+ [`exchange`][controlconnection-exchange] and streams what tmux reports through
489
+ [`subscribe`][controlconnection-subscribe]. The subscription's
490
+ [`next`][controlsubscription-next] waits for the next
491
+ [`ControlEvent`][controlevent]:
492
+
493
+ <!-- example: api_control/main -->
494
+ ```ruby
495
+ require "libtmux"
496
+
497
+ LibTmux::Server.start do |server|
498
+ session = server.new_session(name: "work", command: ["/bin/cat"])
499
+ window = session.list_windows.fetch(0)
500
+ server.open_control(session: session.ref) do |control|
501
+ reply = control.exchange("display-message -p ready", timeout: 5)
502
+ puts "reply: #{reply.blocks.last.body.strip}"
503
+ events = control.subscribe(max_events: 64, max_bytes: 65_536)
504
+ window.rename("renamed")
505
+ event = events.next(timeout: 5) until event&.raw&.start_with?("%window-renamed")
506
+ puts "event: #{event.raw.strip}"
507
+ end
508
+ end
509
+ ```
510
+ <!-- /example -->
511
+
512
+ It prints:
513
+
514
+ ```text
515
+ reply: ready
516
+ event: %window-renamed @0 renamed
517
+ ```
518
+
519
+ - `exchange` answers a [`GuardedReply`][guardedreply]. It holds the blocks seen
520
+ between two boundaries, and a hook can print into the same interval.
521
+ - A subscription is bounded. A reliable one raises
522
+ [`SubscriptionOverflow`][subscriptionoverflow] when it falls behind, and a
523
+ tail one reports the lost range as a `:gap` event.
524
+ - [`pause_output`][controlconnection-pause_output] and
525
+ [`resume_output`][controlconnection-resume_output] return a
526
+ [`GuardedReply`][guardedreply]. A reply does not show that the action took
527
+ effect.
528
+ - To reconnect, close the old connection and pass it as
529
+ `open_control(session: ref, reconnect: old_connection)`. The replacement has
530
+ a new `generation`, and every new subscription starts with a `:reconnect`
531
+ gap. Nothing is replayed.
532
+
533
+ The contracts are in [Control connections][behavior-control], and the
534
+ [control overflow recipe](../../docs/recipes.md#control-overflow) runs both
535
+ subscription modes.
536
+
537
+ ## Run several commands in order
538
+
539
+ ### [`Server#run_group`][server-run_group]: several commands through one client
540
+
541
+ A group submits several tmux commands in order through one client. The
542
+ [`GroupResult`][groupresult] holds one aggregate status, and each step reports
543
+ `unknown`:
544
+
545
+ <!-- example: api_run_group/main -->
546
+ ```ruby
547
+ require "libtmux"
548
+
549
+ LibTmux::Server.start do |server|
550
+ server.new_session(name: "work", command: ["/bin/cat"])
551
+ group = server.run_group([
552
+ ["set-option", "-g", "@before", "kept"],
553
+ ["select-pane", "-t", "%4294967294"],
554
+ ["set-option", "-g", "@after", "never run"]
555
+ ])
556
+ puts "success: #{group.success?}"
557
+ puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(', ')}"
558
+ puts "@before: #{server.options(scope: :session).get('@before').as(:string)}"
559
+ end
560
+ ```
561
+ <!-- /example -->
562
+
563
+ It prints:
564
+
565
+ ```text
566
+ success: false
567
+ steps: unknown, unknown, unknown
568
+ @before: kept
569
+ ```
570
+
571
+ The first command keeps its effect when the second fails, and the third never
572
+ runs. The [group recipe](../../docs/recipes.md#failure-inside-a-group) checks
573
+ the same.
574
+
575
+ ## Packages
576
+
577
+ Start with `libtmux`. Add the companion for your caller:
578
+
579
+ | Gem | Require | Use it for |
580
+ | --- | --- | --- |
581
+ | [libtmux](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux) | `libtmux` | Blocking scripts, snapshots, and control connections |
582
+ | [libtmux-async](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux-async) | `libtmux/async` | Concurrent commands and bounded streams in Async tasks |
583
+ | [libtmux-mcp](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux-mcp) | `libtmux/mcp` | An MCP server with explicit endpoints and tool policy |
584
+ | [libtmux-workspace](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux-workspace) | `libtmux/workspace` | YAML/JSON workspace plans and a CLI to apply them |
585
+
586
+ ### [libtmux](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux): the core
587
+
588
+ This gem: blocking [server][server], [session][session], [window][window] and
589
+ [pane][pane] handles, immutable [snapshots][snapshot], and
590
+ [control connections][controlconnection]. The sections above run against it.
591
+
592
+ [API reference](https://libtmux.org/en/ruby/latest/reference/) ·
593
+ [Guides](https://libtmux.org/en/ruby/latest/guides/) ·
594
+ [RubyGems](https://rubygems.org/gems/libtmux)
595
+
596
+ ### [libtmux-async](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux-async): concurrent commands
597
+
598
+ Concurrent commands and bounded control streams inside an Async task that your
599
+ application owns. Require `libtmux/async`, then open a scope with
600
+ [`LibTmux::Async.open`][async-open].
601
+
602
+ [API reference](https://libtmux.org/en/ruby/latest/reference/libtmux-async/) ·
603
+ [Guide](https://libtmux.org/en/ruby/latest/guides/async/) ·
604
+ [RubyGems](https://rubygems.org/gems/libtmux-async)
605
+
606
+ ```console
607
+ $ gem install libtmux-async --pre
608
+ ```
609
+
610
+ Capture every pane concurrently with [`Scope#map`][async-scope-map]. `server`
611
+ is an open [`LibTmux::Server`][server]:
612
+
613
+ <!-- example: async_cancel/map -->
614
+ ```ruby
615
+ Async do |parent|
616
+ LibTmux::Async.open(parent: parent, server: server) do |scope|
617
+ refs = scope.server.list_panes.map(&:ref)
618
+ screens = scope.map(refs, concurrency: 2) { |ref| scope.server.pane(ref).capture }
619
+ Example.check(screens.length == refs.length && screens.all?(&:success?), "concurrent captures failed")
620
+ end
621
+ end.wait
622
+ ```
623
+ <!-- /example -->
624
+
625
+ ### [libtmux-mcp](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux-mcp): a tmux server for MCP clients
626
+
627
+ An MCP server over stdio for one tmux server, with an explicit tool policy.
628
+ Installs `libtmux-mcp`; require `libtmux/mcp` to embed it through
629
+ [`LibTmux::MCP::Application`][mcp-application].
630
+
631
+ [API reference](https://libtmux.org/en/ruby/latest/mcp/reference/) ·
632
+ [Tools](https://libtmux.org/en/ruby/latest/mcp/tools/) ·
633
+ [Guides](https://libtmux.org/en/ruby/latest/mcp/guides/) ·
634
+ [RubyGems](https://rubygems.org/gems/libtmux-mcp)
635
+
636
+ ```console
637
+ $ gem install libtmux-mcp --pre
638
+ ```
639
+
640
+ The server borrows a tmux server that is already running. Start one on a
641
+ socket of its own:
642
+
643
+ ```console
644
+ $ tmux -L agent new-session -d -s work
645
+ ```
646
+
647
+ Add the server to Claude Code. Until you enable more tools, it serves
648
+ [`tmux_capabilities`][tool-tmux_capabilities] and
649
+ [`tmux_snapshot`][tool-tmux_snapshot]:
650
+
651
+ ```console
652
+ $ claude mcp add tmux -- libtmux-mcp --socket-name agent --endpoint dev
653
+ ```
654
+
655
+ The [MCP README](../libtmux-mcp/README.md) covers other clients, every tool and
656
+ authored shell commands.
657
+
658
+ ### [libtmux-workspace](https://github.com/libtmux/libtmux-ruby/tree/master/gems/libtmux-workspace): YAML workspaces
659
+
660
+ YAML or JSON workspaces, validated, planned offline and applied to an open
661
+ server. Installs `libtmux-workspace`; require `libtmux/workspace` to use it
662
+ from Ruby through [`LibTmux::Workspace`][workspace].
663
+
664
+ [API reference](https://libtmux.org/en/ruby/latest/workspace/reference/) ·
665
+ [Command reference](https://libtmux.org/en/ruby/latest/workspace/cli/) ·
666
+ [Guides](https://libtmux.org/en/ruby/latest/workspace/guides/) ·
667
+ [RubyGems](https://rubygems.org/gems/libtmux-workspace)
668
+
669
+ ```console
670
+ $ gem install libtmux-workspace --pre
671
+ ```
672
+
673
+ Save this workspace as `workspace.yaml`:
674
+
675
+ <!-- example: workspace/config -->
676
+ ```yaml
677
+ session_name: work
678
+ environment:
679
+ PROJECT_MODE: development
680
+ windows:
681
+ - window_name: editor
682
+ window_index: 1
683
+ layout: tiled
684
+ panes:
685
+ - shell_command: printf 'editor ready\n'
686
+ - {}
687
+ ```
688
+ <!-- /example -->
689
+
690
+ Check it without contacting tmux:
691
+
692
+ ```console
693
+ $ libtmux-workspace validate workspace.yaml
694
+ ```
695
+
696
+ ```text
697
+ Workspace configuration is valid.
698
+ ```
699
+
700
+ The [workspace README](../libtmux-workspace/README.md) loads it into a running
701
+ server and lists every option.
702
+
703
+ ## What it leaves out
704
+
705
+ - **Live objects.** A [snapshot record][snapshot] is what tmux said when you
706
+ read it, and a [handle][server-list_sessions] reads tmux again each time you
707
+ list. See [Captured records][behavior-records] and
708
+ [Live handles][behavior-live-handles].
709
+ - **A terminal emulator.** [`Pane#capture`][pane-capture] returns the bytes
710
+ tmux holds for the screen, with the flags above to shape them.
711
+ - **An implied server.** [`Endpoint.new`][endpoint-new] needs an explicit
712
+ socket, and no API in the recipes uses the default server.
713
+ - **Replay.** A reconnected control connection reports a gap and never replays
714
+ requests or missed output. See [Control flow][behavior-control-flow].
715
+ - **Transactions.** A [group][server-run_group] runs in order and keeps the
716
+ effects of the steps before a failure.
717
+ - **Whole-program typing.** RBS declarations ship with the gem and selected
718
+ installed calls are checked. See [Signature proof][behavior-signature].
719
+
720
+ ## Support and status
721
+
722
+ **Alpha.** APIs may change between releases. See the
723
+ [initial alpha notes](../../CHANGELOG.md).
724
+
725
+ - **Ruby 3.3 or newer.** The gem depends on `json`, `tmpdir`, `securerandom`,
726
+ `fiddle` and `io-console`.
727
+ - **tmux 3.3a or newer.** Unpatched 3.3 is below the minimum. A
728
+ [server handle][server] checks the connected daemon's release before it sends
729
+ a command, and refuses an older daemon even when its client is newer.
730
+ - **Control connections need tmux 3.7 or newer.** An older daemon refuses
731
+ [`open_control`][server-open_control] before a control client attaches.
732
+ Subprocess operations and snapshots do not need it. The
733
+ [optional feature table](../../docs/reference/behavior.md#optional-tmux-features)
734
+ lists the other per-release requirements.
735
+ - **Linux, including WSL, and macOS.** The [compatibility workflow][compat]
736
+ runs Ruby 3.3, 3.4 and 4.0 with tmux 3.3a through 3.8 on Ubuntu 24.04.
737
+ macOS is supported on a best-effort basis, and CI coverage for it is highly
738
+ limited.
739
+ - **tmux master and old daemons.** On Ubuntu the workflow also runs the suite
740
+ against a pinned tmux master, and checks that tmux 3.0a, 3.1c, 3.2a and 3.3
741
+ daemons are refused.
742
+ - **Per-revision results.** Read the workflow's results for your revision
743
+ before relying on one combination.
744
+
745
+ ## Documentation
746
+
747
+ | | |
748
+ | --- | --- |
749
+ | [Reference](https://libtmux.org/en/ruby/latest/reference/) | Every public class and method, one page each |
750
+ | [Guides](https://libtmux.org/en/ruby/latest/guides/) | Getting started, server bindings and the Async scope |
751
+ | [Recipes](../../docs/recipes.md) | Complete programs with checked excerpts |
752
+ | [Execution modes](../../docs/modes.md) | Blocking calls, Async tasks and control subscriptions |
753
+ | [Ownership and errors](../../docs/ownership-errors.md) | What close and failure mean |
754
+ | [Public behavior](../../docs/reference/behavior.md) | Defaults, ownership, blocking and failure of each call |
755
+ | [Field catalog](../../docs/reference/fields.md) | Query fields and wire names |
756
+ | [Public methods](../../docs/reference/api.md) | Each exported method, its source and its contract |
757
+ | [Contributing](../../.github/CONTRIBUTING.md) | Local builds, checks and the test loops |
758
+
759
+ MIT. See [LICENSE](LICENSE).
760
+
761
+ [async-open]: https://libtmux.org/en/ruby/latest/reference/libtmux-async-open/
762
+ [async-scope-map]: https://libtmux.org/en/ruby/latest/reference/libtmux-async-scope-map/
763
+ [behavior-cancellation]: ../../docs/reference/behavior.md#cancellation-tokens
764
+ [behavior-capture]: ../../docs/reference/behavior.md#pane-input-and-capture
765
+ [behavior-control]: ../../docs/reference/behavior.md#control-connections
766
+ [behavior-control-flow]: ../../docs/reference/behavior.md#control-flow
767
+ [behavior-creation]: ../../docs/reference/behavior.md#creation
768
+ [behavior-live-handles]: ../../docs/reference/behavior.md#live-handles
769
+ [behavior-option-values]: ../../docs/reference/behavior.md#option-values
770
+ [behavior-options]: ../../docs/reference/behavior.md#options-and-hooks
771
+ [behavior-records]: ../../docs/reference/behavior.md#captured-records
772
+ [behavior-signature]: ../../docs/reference/behavior.md#signature-proof
773
+ [behavior-window-links]: ../../docs/reference/behavior.md#window-links
774
+ [cancellation]: https://libtmux.org/en/ruby/latest/reference/libtmux-cancellation/
775
+ [cancellation-cancel]: https://libtmux.org/en/ruby/latest/reference/libtmux-cancellation-cancel/
776
+ [cancellation-close]: https://libtmux.org/en/ruby/latest/reference/libtmux-cancellation-close/
777
+ [cancellation-new]: https://libtmux.org/en/ruby/latest/reference/libtmux-cancellation-new/
778
+ [cancelled]: https://libtmux.org/en/ruby/latest/reference/libtmux-cancelled/
779
+ [commanderror]: https://libtmux.org/en/ruby/latest/reference/libtmux-commanderror/
780
+ [compat]: https://github.com/libtmux/libtmux-ruby/actions/workflows/compatibility.yml
781
+ [controlconnection]: https://libtmux.org/en/ruby/latest/reference/libtmux-controlconnection/
782
+ [controlconnection-exchange]: https://libtmux.org/en/ruby/latest/reference/libtmux-controlconnection-exchange/
783
+ [controlconnection-pause_output]: https://libtmux.org/en/ruby/latest/reference/libtmux-controlconnection-pause_output/
784
+ [controlconnection-resume_output]: https://libtmux.org/en/ruby/latest/reference/libtmux-controlconnection-resume_output/
785
+ [controlconnection-subscribe]: https://libtmux.org/en/ruby/latest/reference/libtmux-controlconnection-subscribe/
786
+ [controlevent]: https://libtmux.org/en/ruby/latest/reference/libtmux-controlevent/
787
+ [controlsubscription-next]: https://libtmux.org/en/ruby/latest/reference/libtmux-controlsubscription-next/
788
+ [endpoint-from_env]: https://libtmux.org/en/ruby/latest/reference/libtmux-endpoint-from_env/
789
+ [endpoint-new]: https://libtmux.org/en/ruby/latest/reference/libtmux-endpoint-new/
790
+ [groupresult]: https://libtmux.org/en/ruby/latest/reference/libtmux-groupresult/
791
+ [guardedreply]: https://libtmux.org/en/ruby/latest/reference/libtmux-guardedreply/
792
+ [hooks-set]: https://libtmux.org/en/ruby/latest/reference/libtmux-hooks-set/
793
+ [mcp-application]: https://libtmux.org/en/ruby/latest/mcp/reference/libtmux-mcp-application/
794
+ [multiplematcheserror]: https://libtmux.org/en/ruby/latest/reference/libtmux-multiplematcheserror/
795
+ [nomatcherror]: https://libtmux.org/en/ruby/latest/reference/libtmux-nomatcherror/
796
+ [options-get]: https://libtmux.org/en/ruby/latest/reference/libtmux-options-get/
797
+ [options-set]: https://libtmux.org/en/ruby/latest/reference/libtmux-options-set/
798
+ [optionvalue]: https://libtmux.org/en/ruby/latest/reference/libtmux-optionvalue/
799
+ [optionvalue-as]: https://libtmux.org/en/ruby/latest/reference/libtmux-optionvalue-as/
800
+ [pane]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-14z6/
801
+ [pane-capture]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-capture/
802
+ [pane-send_keys]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-send_keys/
803
+ [pane-send_text]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-send_text/
804
+ [pane-split]: https://libtmux.org/en/ruby/latest/reference/libtmux-pane-split/
805
+ [selection-one]: https://libtmux.org/en/ruby/latest/reference/libtmux-selection-one/
806
+ [selection-one_or_nil]: https://libtmux.org/en/ruby/latest/reference/libtmux-selection-one_or_nil/
807
+ [selection-select]: https://libtmux.org/en/ruby/latest/reference/libtmux-selection-select/
808
+ [selection-where]: https://libtmux.org/en/ruby/latest/reference/libtmux-selection-where/
809
+ [server]: https://libtmux.org/en/ruby/latest/reference/libtmux-server/
810
+ [server-explain_panes]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-explain_panes/
811
+ [server-kill]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-kill/
812
+ [server-list_panes]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-list_panes/
813
+ [server-list_sessions]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-list_sessions/
814
+ [server-list_windows]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-list_windows/
815
+ [server-new]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-new/
816
+ [server-new_session]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-new_session/
817
+ [server-open]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-open/
818
+ [server-open_control]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-open_control/
819
+ [server-read_buffer]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-read_buffer/
820
+ [server-run_group]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-run_group/
821
+ [server-search_panes]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-search_panes/
822
+ [server-snapshot]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-snapshot/
823
+ [server-start]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-start/
824
+ [server-write_buffer]: https://libtmux.org/en/ruby/latest/reference/libtmux-server-write_buffer/
825
+ [session]: https://libtmux.org/en/ruby/latest/reference/libtmux-session-nvps/
826
+ [session-link_window]: https://libtmux.org/en/ruby/latest/reference/libtmux-session-link_window/
827
+ [session-list_windows]: https://libtmux.org/en/ruby/latest/reference/libtmux-session-list_windows/
828
+ [session-new_window]: https://libtmux.org/en/ruby/latest/reference/libtmux-session-new_window/
829
+ [session-options]: https://libtmux.org/en/ruby/latest/reference/libtmux-session-options/
830
+ [snapshot]: https://libtmux.org/en/ruby/latest/reference/libtmux-snapshot/
831
+ [subscriptionoverflow]: https://libtmux.org/en/ruby/latest/reference/libtmux-subscriptionoverflow/
832
+ [targetnotfounderror]: https://libtmux.org/en/ruby/latest/reference/libtmux-targetnotfounderror/
833
+ [tool-tmux_capabilities]: https://libtmux.org/en/ruby/latest/mcp/tools/tmux_capabilities/
834
+ [tool-tmux_snapshot]: https://libtmux.org/en/ruby/latest/mcp/tools/tmux_snapshot/
835
+ [window]: https://libtmux.org/en/ruby/latest/reference/libtmux-window-1vfx/
836
+ [window-list_panes]: https://libtmux.org/en/ruby/latest/reference/libtmux-window-list_panes/
837
+ [window-split]: https://libtmux.org/en/ruby/latest/reference/libtmux-window-split/
838
+ [windowlink]: https://libtmux.org/en/ruby/latest/reference/libtmux-windowlink-tusj/
839
+ [workspace]: https://libtmux.org/en/ruby/latest/workspace/reference/libtmux-workspace/